|
| 1 | +/** |
| 2 | + * `iob-sync types` — sets up editor intellisense for pulled scripts. |
| 3 | + * |
| 4 | + * ioBroker scripts call globals that exist only inside the javascript adapter's |
| 5 | + * sandbox — `log`, `schedule`, `on`, `getState`. Nothing in a plain checkout tells an |
| 6 | + * editor those exist, so every script lights up red in neovim, VS Code, or any other |
| 7 | + * LSP client. This writes the two pieces that fix it: |
| 8 | + * |
| 9 | + * .iobroker/types/javascript.d.ts the adapter's own typings, downloaded |
| 10 | + * <scriptRoot>/tsconfig.json a config that picks them up |
| 11 | + * |
| 12 | + * Also reachable as `init --types`, but it exists separately because wanting types |
| 13 | + * later — or refreshing them after the adapter adds a function — is the common case, |
| 14 | + * and re-running `init` to get them would mean `--force`-overwriting a working config. |
| 15 | + */ |
| 16 | + |
| 17 | +import * as fs from 'node:fs/promises'; |
| 18 | +import * as path from 'node:path'; |
| 19 | + |
| 20 | +import { Logger } from '../types'; |
| 21 | + |
| 22 | +const JAVASCRIPT_DTS_URL = |
| 23 | + 'https://raw.githubusercontent.com/ioBroker/ioBroker.javascript/refs/heads/master/src/lib/javascript.d.ts'; |
| 24 | + |
| 25 | +const GLOBAL_DTS_CONTENT = `export {}; |
| 26 | +declare global { |
| 27 | + function require(library: string): any; |
| 28 | +} |
| 29 | +`; |
| 30 | + |
| 31 | +export interface TypesOptions { |
| 32 | + /** Replace an existing `<scriptRoot>/tsconfig.json` instead of leaving it alone. */ |
| 33 | + force?: boolean; |
| 34 | + /** Skip the download and only write the local files. */ |
| 35 | + offline?: boolean; |
| 36 | +} |
| 37 | + |
| 38 | +async function pathExists(p: string): Promise<boolean> { |
| 39 | + try { |
| 40 | + await fs.access(p); |
| 41 | + return true; |
| 42 | + } catch { |
| 43 | + return false; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +/** |
| 48 | + * The tsconfig that gives the *scripts* intellisense. |
| 49 | + * |
| 50 | + * It lives inside the script root rather than merging into a `tsconfig.json` at the |
| 51 | + * project root: the project root may already hold a build config that owns |
| 52 | + * `rootDir`/`outDir`, and injecting `scripts/**` into it produces TS6059 and breaks |
| 53 | + * that build. Scripts are only ever type-*checked*, never emitted, hence `noEmit`. |
| 54 | + * |
| 55 | + * `typesPrefix` is the relative hop from the script root back to the project root, so |
| 56 | + * the downloaded `.iobroker/types` are found from wherever the scripts live. |
| 57 | + * |
| 58 | + * `types` is intentionally left unset: naming `["node"]` hard-fails when `@types/node` |
| 59 | + * is absent, whereas the default (auto-include every visible `@types`) degrades to |
| 60 | + * merely missing the `NodeJS.*` names that `javascript.d.ts` refers to. |
| 61 | + */ |
| 62 | +function scriptsTsconfig(typesPrefix: string): Record<string, unknown> { |
| 63 | + return { |
| 64 | + compilerOptions: { |
| 65 | + allowJs: true, |
| 66 | + checkJs: true, |
| 67 | + // `moduleDetection: force` is what makes a folder of scripts checkable at all. |
| 68 | + // Each ioBroker script runs in its own sandbox scope, but to TypeScript they |
| 69 | + // are plain scripts sharing one global scope, so two files each declaring |
| 70 | + // `const helper` collide with TS2451 — a phantom error about code that is |
| 71 | + // fine at runtime. Forcing module semantics gives every file its own scope, |
| 72 | + // matching how the adapter actually runs them. Globals from javascript.d.ts |
| 73 | + // are declared with `declare global` and stay visible. |
| 74 | + moduleDetection: 'force', |
| 75 | + // es2022 (not commonjs) because scripts may use top-level `await`, which the |
| 76 | + // adapter supports and which TS1378 rejects under commonjs. |
| 77 | + module: 'es2022', |
| 78 | + target: 'es2022', |
| 79 | + lib: ['ES2022'], |
| 80 | + moduleResolution: 'node', |
| 81 | + noEmit: true, |
| 82 | + skipLibCheck: true, |
| 83 | + }, |
| 84 | + include: ['**/*.ts', '**/*.js', `${typesPrefix}.iobroker/types/**/*.d.ts`], |
| 85 | + }; |
| 86 | +} |
| 87 | + |
| 88 | +export async function setupTypes( |
| 89 | + root: string, |
| 90 | + scriptRoot: string, |
| 91 | + opts: TypesOptions, |
| 92 | + log: Logger, |
| 93 | +): Promise<void> { |
| 94 | + const scriptRootDir = path.join(root, scriptRoot); |
| 95 | + const tsconfigPath = path.join(scriptRootDir, 'tsconfig.json'); |
| 96 | + |
| 97 | + // path.relative gives '..' / '../..'; normalise to a POSIX prefix for tsconfig globs. |
| 98 | + const rel = path.relative(scriptRootDir, root).split(path.sep).join('/'); |
| 99 | + const typesPrefix = rel === '' ? '' : `${rel}/`; |
| 100 | + |
| 101 | + if ((await pathExists(tsconfigPath)) && !opts.force) { |
| 102 | + log.info(`${tsconfigPath} already exists; keeping it. Use --force to replace it.`); |
| 103 | + } else { |
| 104 | + await fs.mkdir(scriptRootDir, { recursive: true }); |
| 105 | + await fs.writeFile( |
| 106 | + tsconfigPath, |
| 107 | + JSON.stringify(scriptsTsconfig(typesPrefix), null, 2) + '\n', |
| 108 | + 'utf8', |
| 109 | + ); |
| 110 | + log.info(`Wrote ${tsconfigPath}`); |
| 111 | + } |
| 112 | + |
| 113 | + const typesDir = path.join(root, '.iobroker', 'types'); |
| 114 | + await fs.mkdir(typesDir, { recursive: true }); |
| 115 | + |
| 116 | + const dtsPath = path.join(typesDir, 'javascript.d.ts'); |
| 117 | + if (opts.offline) { |
| 118 | + log.info('Skipping the javascript.d.ts download (--offline).'); |
| 119 | + } else { |
| 120 | + try { |
| 121 | + const res = await fetch(JAVASCRIPT_DTS_URL); |
| 122 | + if (!res.ok) { |
| 123 | + throw new Error(`HTTP ${res.status}`); |
| 124 | + } |
| 125 | + const text = await res.text(); |
| 126 | + await fs.writeFile(dtsPath, text, 'utf8'); |
| 127 | + log.info(`Downloaded javascript.d.ts (${Math.round(text.length / 1024)} KB)`); |
| 128 | + } catch (err) { |
| 129 | + // Not fatal: the tsconfig and global.d.ts are still worth writing, and a |
| 130 | + // previously downloaded copy may already be sitting there. |
| 131 | + log.warn(`Could not download javascript.d.ts (${(err as Error).message}).`); |
| 132 | + log.warn( |
| 133 | + (await pathExists(dtsPath)) |
| 134 | + ? 'Keeping the copy already in .iobroker/types/.' |
| 135 | + : `Scripts will still show "Cannot find name 'log'" until it is fetched. Re-run \`iob-sync types\` when online.`, |
| 136 | + ); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + await fs.writeFile(path.join(typesDir, 'global.d.ts'), GLOBAL_DTS_CONTENT, 'utf8'); |
| 141 | + log.info(`Wrote ${path.join(typesDir, 'global.d.ts')}`); |
| 142 | + |
| 143 | + // javascript.d.ts refers to NodeJS.Timeout, NodeJS.ErrnoException and friends |
| 144 | + // throughout, so without @types/node the scripts light up with "Cannot find |
| 145 | + // namespace 'NodeJS'". Nothing here can install it, so say so plainly. |
| 146 | + if (!(await pathExists(path.join(root, 'node_modules', '@types', 'node')))) { |
| 147 | + log.warn('@types/node is not installed; javascript.d.ts needs it for NodeJS.* types.'); |
| 148 | + log.warn(`Run this in ${root}: npm install --save-dev @types/node`); |
| 149 | + } |
| 150 | + |
| 151 | + log.result(`Types ready. Restart your editor's language server to pick them up.`); |
| 152 | +} |
0 commit comments