@particle/tooling 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,154 @@
1
+ # Shared tooling config for Particle
2
+
3
+ Shared [oxlint](https://oxc.rs/docs/guide/usage/linter.html), [oxfmt](https://oxc.rs/docs/guide/usage/formatter.html) and TypeScript configuration for Particle projects.
4
+
5
+ ## Usage
6
+
7
+ Run the migration from the root of the project. It does not need the package installed first:
8
+
9
+ ```shell
10
+ $ npx @particle/tooling
11
+ ```
12
+
13
+ It asks what kind of project this is (or takes `--style`), prints everything it is going to change, and waits for confirmation before touching anything.
14
+
15
+ | Style | Project |
16
+ | ------------ | ------------------------------------------- |
17
+ | `js` | JavaScript project |
18
+ | `ts-service` | TypeScript service |
19
+ | `ts-library` | TypeScript library, built with declarations |
20
+
21
+ What it does, depending on what it finds:
22
+
23
+ - **Dependencies:** removes ESLint and its configs and plugins, adds `@particle/tooling` (which installs `oxlint` and `oxfmt` as peers), and moves `typescript` to version 7. TypeScript projects also get `oxlint-tsgolint`, which runs the type-aware lint rules.
24
+ - **Lint and format configs:** deletes `eslint.config.*`, `.eslintrc*`, `.oxlintrc.json` and `.oxfmtrc.json`, and creates `oxlint.config.ts` and `oxfmt.config.ts` that re-export the shared configs. TypeScript projects re-export `@particle/tooling/oxlint-typescript`, JavaScript projects `@particle/tooling/oxlint`.
25
+ - **tsconfigs:** rewrites `tsconfig.json` and `tsconfig.build.json` to extend the shared configs, keeping the project's own `include`, `exclude` and `types`. A config with other project-specific compiler options, or one that already extends something else, is left alone and reported for you to migrate by hand.
26
+ - **Sentry:** when the project depends on a `@sentry/*` package, the build config gets `"sourceRoot": "/"`, which strips the build path from source references so Sentry groups issues consistently. Without Sentry it is removed, because it makes Node stack traces point at paths that do not exist.
27
+ - **Build output:** standardizes on `build/`, adds it to `.gitignore`, and lists every place that still names the old directory (`package.json` fields, scripts, `Dockerfile`, CI config) for you to update.
28
+ - **Scripts:** replaces plain `eslint` steps with `oxlint --deny-warnings` (so a warning fails the check, in CI too), adds `oxfmt --check` to an existing `check` script, and adds `fmt` and `fmt:check` where they are missing. TypeScript projects without them also get `check` (`tsc && oxlint --deny-warnings && oxfmt --check`) and `build`. It does not add a `lint` script.
29
+ - **CI:** looks at `.circleci/config.yml` and `.github/workflows` and reminds you to confirm that CI runs a step that checks formatting.
30
+ - **Install:** runs `npm install` at the end.
31
+
32
+ Anything it cannot decide for you is listed under "Needs your attention", before you confirm and again at the end.
33
+
34
+ Options:
35
+
36
+ | Option | Effect |
37
+ | -------------- | ----------------------------------------------------- |
38
+ | `--style` | Skip the style question |
39
+ | `--yes`, `-y` | Apply without asking. Required when not in a terminal |
40
+ | `--no-install` | Skip `npm install` |
41
+
42
+ After migrating, format the project once and commit that separately:
43
+
44
+ ```shell
45
+ $ npm run fmt
46
+ $ npm run check
47
+ ```
48
+
49
+ The config files are TypeScript, which requires Node 22.23.4 or later.
50
+
51
+ ## Lint configs
52
+
53
+ | Config | Use |
54
+ | ------------------------------------- | ----------------------------------------------------------------------------------------- |
55
+ | `@particle/tooling/oxlint` | JavaScript projects |
56
+ | `@particle/tooling/oxlint-typescript` | TypeScript projects: the same rules plus the TypeScript rules, with type-aware linting on |
57
+
58
+ Type-aware rules such as `no-floating-promises` need the `oxlint-tsgolint` package and a `tsconfig.json`. Only the typed rules named in `oxlint-typescript.js` are enforced. The other typed rules in the enabled categories are switched off there, and a project can turn one on in its own config.
59
+
60
+ ## Overriding
61
+
62
+ Replace the re-export with a config that builds on the shared one.
63
+
64
+ ```ts
65
+ // oxlint.config.ts
66
+ import shared from '@particle/tooling/oxlint';
67
+ import { defineConfig } from 'oxlint';
68
+
69
+ export default defineConfig({
70
+ extends: [shared],
71
+ rules: { 'no-console': 'off' }
72
+ });
73
+ ```
74
+
75
+ oxfmt has no `extends`, so spread the shared options. The merge is shallow: nested options such as `sortImports` are replaced as a whole.
76
+
77
+ ```ts
78
+ // oxfmt.config.ts
79
+ import shared from '@particle/tooling/oxfmt';
80
+ import { defineConfig } from 'oxfmt';
81
+
82
+ export default defineConfig({ ...shared, printWidth: 120 });
83
+ ```
84
+
85
+ ## TypeScript configs
86
+
87
+ `typescript` is an optional peer dependency. The configs target TypeScript 7, so install it in projects that use them:
88
+
89
+ ```shell
90
+ $ npm install --save-dev typescript@^7
91
+ ```
92
+
93
+ | Config | Use |
94
+ | -------------------------------------------------- | ------------------------------------------------------------------------------- |
95
+ | `@particle/tooling/tsconfig/js.json` | JavaScript projects, with `checkJs` off |
96
+ | `@particle/tooling/tsconfig/ts.json` | Type checking for TypeScript projects: `src` and `test`, no emit |
97
+ | `@particle/tooling/tsconfig/ts-build.json` | Building TypeScript services: `src` without tests, to `build/` |
98
+ | `@particle/tooling/tsconfig/ts-build-library.json` | Building TypeScript libraries: the same, with declarations and declaration maps |
99
+
100
+ A TypeScript project has two files. A library extends `ts-build-library.json` in the second one:
101
+
102
+ ```jsonc
103
+ // tsconfig.json
104
+ { "extends": "@particle/tooling/tsconfig/ts.json" }
105
+ ```
106
+
107
+ ```jsonc
108
+ // tsconfig.build.json
109
+ { "extends": "@particle/tooling/tsconfig/ts-build.json" }
110
+ ```
111
+
112
+ `ts.json` sets `module` to `NodeNext`, so the output is CommonJS or ES modules according to `type` in the project's `package.json`.
113
+
114
+ `tsconfig.build.json` does not inherit from the project's `tsconfig.json`. A compiler option overridden there has to be repeated in `tsconfig.build.json` if the build needs it.
115
+
116
+ A JavaScript project has one file. It covers the whole project unless `include` narrows it:
117
+
118
+ ```jsonc
119
+ // tsconfig.json
120
+ { "extends": "@particle/tooling/tsconfig/js.json" }
121
+ ```
122
+
123
+ ## Development
124
+
125
+ ```shell
126
+ $ npm run check # lint and format check
127
+ $ npm test
128
+ ```
129
+
130
+ To try local changes in another project, pack this one and point the migration at the tarball:
131
+
132
+ ```bash
133
+ $ npm pack
134
+ $ cd ../api-service
135
+ $ node ../particle-tooling/bin/init.js --tooling-spec file:../particle-tooling/particle-tooling-0.1.0.tgz
136
+ ```
137
+
138
+ ## Pre-releasing
139
+
140
+ To use a new config in a PR for another service, publish a pre-release. Don't forget to update your PR with the released version before merging!
141
+
142
+ 1. Run `npm version <premajor|preminor|prepatch>`
143
+ - For subsequent pre-releases on the same feature branch, run `npm version prerelease` to increment the pre-release number
144
+ 2. Push to origin `git push --follow-tags`
145
+ 3. CircleCI will publish the npm package to the `beta` tag
146
+ 4. Point your PR to the new version `npm install --save-dev @particle/tooling@beta`
147
+
148
+ ## Releasing changes
149
+
150
+ 1. Merge your changes to main and be on `main`
151
+ 2. Run `npm version <major|minor|patch>`
152
+ 3. Push to origin `git push --follow-tags`
153
+ 4. CircleCI will publish the npm package to the `latest` tag
154
+ 5. Point your project to the new version `npm install --save-dev @particle/tooling@latest`
package/bin/init.js ADDED
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { existsSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { createInterface } from 'node:readline/promises';
6
+ import { parseArgs } from 'node:util';
7
+
8
+ import { applyPlan, createPlan, detectStyle, formatAttention, formatPlan, hasChanges, STYLES } from '../lib/migrate.js';
9
+
10
+ const styleNames = Object.keys(STYLES);
11
+
12
+ /**
13
+ * @param {string} message
14
+ * @returns {never}
15
+ */
16
+ function fail(message) {
17
+ console.error(message);
18
+ process.exit(1);
19
+ }
20
+
21
+ /**
22
+ * @param {import('node:readline/promises').Interface} prompt
23
+ * @param {string} question
24
+ * @returns {Promise<string>} the trimmed answer. Exits when the prompt is closed with Ctrl+D.
25
+ */
26
+ async function ask(prompt, question) {
27
+ try {
28
+ return (await prompt.question(question)).trim();
29
+ } catch (err) {
30
+ if (err.code === 'ABORT_ERR') {
31
+ process.exit(1);
32
+ }
33
+ throw err;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * @param {import('node:readline/promises').Interface} prompt
39
+ * @param {string} detected the style offered as the default
40
+ * @returns {Promise<string>} the chosen style, which may not be a valid one
41
+ */
42
+ async function askStyle(prompt, detected) {
43
+ console.log('What kind of project is this?');
44
+ for (const [index, name] of styleNames.entries()) {
45
+ console.log(` ${index + 1}) ${name}: ${STYLES[name]}${name === detected ? ' (detected)' : ''}`);
46
+ }
47
+ const fallback = styleNames.indexOf(detected) + 1;
48
+ const answer = (await ask(prompt, `Style (1-${styleNames.length}) [${fallback}]: `)) || String(fallback);
49
+ return styleNames[Number(answer) - 1] ?? answer;
50
+ }
51
+
52
+ /**
53
+ * @param {string} dir
54
+ * @returns {Promise<number>} the exit code of npm install
55
+ */
56
+ function npmInstall(dir) {
57
+ const { promise, resolve, reject } = Promise.withResolvers();
58
+ const child = spawn('npm', ['install'], { cwd: dir, stdio: 'inherit' });
59
+ child.on('error', reject);
60
+ child.on('close', resolve);
61
+ return promise;
62
+ }
63
+
64
+ if (import.meta.main) {
65
+ const { values } = parseArgs({
66
+ options: {
67
+ style: { type: 'string' },
68
+ yes: { type: 'boolean', short: 'y', default: false },
69
+ install: { type: 'boolean', default: true },
70
+ 'tooling-spec': { type: 'string' }
71
+ },
72
+ allowNegative: true
73
+ });
74
+ const dir = process.cwd();
75
+ if (!existsSync(path.join(dir, 'package.json'))) {
76
+ fail('No package.json here. Run this from the root of the project to migrate.');
77
+ }
78
+ const interactive = process.stdin.isTTY === true;
79
+ if (!interactive && (!values.style || !values.yes)) {
80
+ fail(`Pass --style and --yes when not running interactively. Styles: ${styleNames.join(', ')}`);
81
+ }
82
+ const prompt = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : null;
83
+ try {
84
+ const style = values.style ?? (await askStyle(prompt, await detectStyle(dir)));
85
+ if (!Object.hasOwn(STYLES, style)) {
86
+ fail(`Unknown style "${style}". Expected one of: ${styleNames.join(', ')}`);
87
+ }
88
+ const plan = await createPlan(dir, style, { toolingSpec: values['tooling-spec'] });
89
+ if (!hasChanges(plan)) {
90
+ console.log('Nothing to change: this project is already set up.');
91
+ if (plan.attention.length > 0) {
92
+ console.log(`\n${formatPlan(plan)}`);
93
+ }
94
+ process.exit(0);
95
+ }
96
+ console.log(`\nMigrating ${path.basename(dir)} as a ${STYLES[style]}. Nothing has been changed yet.\n`);
97
+ console.log(formatPlan(plan));
98
+ console.log(values.install ? '\nThen: npm install\n' : '');
99
+ if (!values.yes && !/^y(es)?$/i.test(await ask(prompt, 'Apply these changes? [y/N] '))) {
100
+ fail('No changes made.');
101
+ }
102
+ await applyPlan(dir, plan);
103
+ console.log('Changes applied.');
104
+ if (values.install) {
105
+ const code = await npmInstall(dir);
106
+ if (code !== 0) {
107
+ fail(
108
+ 'npm install failed. The file changes above are in place: fix the install error and run npm install again.'
109
+ );
110
+ }
111
+ }
112
+ if (plan.attention.length > 0) {
113
+ console.log(`\n${formatAttention(plan)}`);
114
+ }
115
+ } finally {
116
+ prompt?.close();
117
+ }
118
+ }
package/lib/jsonc.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Parses JSON that may contain comments and trailing commas, as tsconfig files do.
3
+ * @param {string} text
4
+ * @returns {any}
5
+ */
6
+ export function parseJsonc(text) {
7
+ let json = '';
8
+ let index = 0;
9
+ while (index < text.length) {
10
+ const char = text[index];
11
+ const next = text[index + 1];
12
+ if (char === '"') {
13
+ const start = index;
14
+ index++;
15
+ while (index < text.length && text[index] !== '"') {
16
+ index += text[index] === '\\' ? 2 : 1;
17
+ }
18
+ index++;
19
+ json += text.slice(start, index);
20
+ } else if (char === '/' && next === '/') {
21
+ const end = text.indexOf('\n', index);
22
+ index = end === -1 ? text.length : end;
23
+ } else if (char === '/' && next === '*') {
24
+ const end = text.indexOf('*/', index + 2);
25
+ index = end === -1 ? text.length : end + 2;
26
+ } else if (char === ',' && /^\s*[}\]]/.test(withoutLeadingComments(text.slice(index + 1)))) {
27
+ index++;
28
+ } else {
29
+ json += char;
30
+ index++;
31
+ }
32
+ }
33
+ return JSON.parse(json);
34
+ }
35
+
36
+ /**
37
+ * @param {string} text
38
+ * @returns {string} text with any comments and whitespace at the start removed
39
+ */
40
+ function withoutLeadingComments(text) {
41
+ let rest = text;
42
+ for (;;) {
43
+ const trimmed = rest.trimStart();
44
+ if (trimmed.startsWith('//')) {
45
+ const end = trimmed.indexOf('\n');
46
+ rest = end === -1 ? '' : trimmed.slice(end);
47
+ } else if (trimmed.startsWith('/*')) {
48
+ const end = trimmed.indexOf('*/');
49
+ rest = end === -1 ? '' : trimmed.slice(end + 2);
50
+ } else {
51
+ return trimmed;
52
+ }
53
+ }
54
+ }
package/lib/migrate.js ADDED
@@ -0,0 +1,771 @@
1
+ import { execFile as execFileCallback } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { readdir, readFile, rm, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { promisify, styleText } from 'node:util';
6
+
7
+ import { parseJsonc } from './jsonc.js';
8
+
9
+ const execFile = promisify(execFileCallback);
10
+ const packageRoot = path.resolve(import.meta.dirname, '..');
11
+
12
+ const TOOLING = '@particle/tooling';
13
+
14
+ export const STYLES = {
15
+ js: 'JavaScript project',
16
+ 'ts-service': 'TypeScript service',
17
+ 'ts-library': 'TypeScript library, built with declarations'
18
+ };
19
+
20
+ const LEGACY_PACKAGES =
21
+ /^(eslint|eslint-config-.+|eslint-plugin-.+|@eslint\/.+|typescript-eslint|@typescript-eslint\/.+|oxlint|oxfmt)$/;
22
+
23
+ const LEGACY_FILES = [
24
+ 'eslint.config.js',
25
+ 'eslint.config.mjs',
26
+ 'eslint.config.cjs',
27
+ 'eslint.config.ts',
28
+ '.eslintrc',
29
+ '.eslintrc.js',
30
+ '.eslintrc.cjs',
31
+ '.eslintrc.json',
32
+ '.eslintrc.yml',
33
+ '.eslintrc.yaml',
34
+ '.eslintignore',
35
+ '.oxlintrc.json',
36
+ '.oxlintrc.jsonc',
37
+ '.oxfmtrc.json',
38
+ '.oxfmtrc.jsonc'
39
+ ];
40
+
41
+ const TYPE_AWARE_LINTER = 'oxlint-tsgolint';
42
+
43
+ /**
44
+ * @param {string} style
45
+ * @returns {Record<string, string>} lint and format config contents by file name. TypeScript styles get the type-aware lint config.
46
+ */
47
+ const lintFiles = (style) => ({
48
+ 'oxlint.config.ts': `export { default } from '${TOOLING}/${style === 'js' ? 'oxlint' : 'oxlint-typescript'}';\n`,
49
+ 'oxfmt.config.ts': `export { default } from '${TOOLING}/oxfmt';\n`
50
+ });
51
+
52
+ const FORMAT_CHECK = 'oxfmt --check';
53
+ /** Warnings fail the lint step, so a `warn` rule still fails CI. */
54
+ const LINT = 'oxlint --deny-warnings';
55
+
56
+ const FORMAT_SCRIPTS = {
57
+ fmt: 'oxfmt',
58
+ 'fmt:check': FORMAT_CHECK
59
+ };
60
+
61
+ const BUILD_DIR = 'build';
62
+ const BUILD_SCRIPT = `rm -rf ${BUILD_DIR}/ && tsc -p tsconfig.build.json`;
63
+ const OUT_DIR_REFERENCE_FILES = ['.gitignore', '.dockerignore', 'Dockerfile', '.circleci/config.yml'];
64
+ const REDUNDANT_UNDER_STRICT = new Set(['noImplicitAny', 'strictNullChecks']);
65
+ const TRUE_BY_DEFAULT = new Set(['forceConsistentCasingInFileNames']);
66
+
67
+ /** Overrides a project may carry through an automatic tsconfig rewrite. Anything else is left for the developer. */
68
+ const SIMPLE_TS_OVERRIDES = new Set(['types', 'sourceRoot', 'declaration', 'declarationMap', 'outDir', 'rootDir']);
69
+ const SIMPLE_JS_OVERRIDES = new Set(['checkJs']);
70
+
71
+ /** Strips the build path from source references so Sentry groups issues consistently. It breaks paths in plain Node stack traces, so it is only set for projects that use Sentry. */
72
+ const SENTRY_SOURCE_ROOT = '/';
73
+ const SOURCE_ROOT_REMOVED =
74
+ ' removes: sourceRoot (it only helps Sentry, which is not installed, and it breaks paths in Node stack traces)';
75
+
76
+ /**
77
+ * @typedef {object} Plan
78
+ * @property {string} style
79
+ * @property {string[]} dependencies changes to package.json dependencies
80
+ * @property {string[]} files files created, rewritten or deleted
81
+ * @property {string[]} scripts changes to package.json scripts
82
+ * @property {string[]} attention things the migration cannot do and the user has to check
83
+ * @property {string | null} packageJson new package.json contents, or null when unchanged
84
+ * @property {{ file: string, contents: string }[]} writes
85
+ * @property {string[]} deletes
86
+ */
87
+
88
+ /**
89
+ * @param {string} file path relative to this package
90
+ * @returns {Promise<any>}
91
+ */
92
+ const readOwnJson = async (file) => parseJsonc(await readFile(path.join(packageRoot, file), 'utf8'));
93
+
94
+ /**
95
+ * @param {string} dir
96
+ * @param {string} file
97
+ * @returns {Promise<string | null>} the file contents, or null when it does not exist
98
+ */
99
+ async function readOptional(dir, file) {
100
+ try {
101
+ return await readFile(path.join(dir, file), 'utf8');
102
+ } catch (err) {
103
+ if (err.code === 'ENOENT') {
104
+ return null;
105
+ }
106
+ throw err;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * @param {string} dir
112
+ * @param {string} file
113
+ * @returns {Promise<boolean>} false for untracked files and outside a git repository
114
+ */
115
+ async function isTracked(dir, file) {
116
+ try {
117
+ await execFile('git', ['ls-files', '--error-unmatch', file], { cwd: dir });
118
+ return true;
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * @param {string} dir
126
+ * @returns {Promise<boolean>} whether src contains a TypeScript source file
127
+ */
128
+ async function hasTypeScriptSource(dir) {
129
+ try {
130
+ const entries = await readdir(path.join(dir, 'src'), { recursive: true });
131
+ return entries.some((entry) => /\.(ts|mts|cts|tsx)$/.test(entry) && !entry.endsWith('.d.ts'));
132
+ } catch {
133
+ return false;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Guesses the project style to offer as the default at the prompt.
139
+ * @param {string} dir
140
+ * @returns {Promise<string>} a key of STYLES
141
+ */
142
+ export async function detectStyle(dir) {
143
+ const pkg = JSON.parse(await readFile(path.join(dir, 'package.json'), 'utf8'));
144
+ if (!existsSync(path.join(dir, 'tsconfig.build.json')) && !(await hasTypeScriptSource(dir))) {
145
+ return 'js';
146
+ }
147
+ const build = await readOptional(dir, 'tsconfig.build.json');
148
+ const emitsDeclarations = build ? parseJsonc(build).compilerOptions?.declaration === true : false;
149
+ return emitsDeclarations || pkg.types || pkg.typings || pkg.publishConfig ? 'ts-library' : 'ts-service';
150
+ }
151
+
152
+ /**
153
+ * @param {unknown} value
154
+ * @returns {string} a form that ignores letter case and array order, for comparing compiler options
155
+ */
156
+ function canonical(value) {
157
+ if (Array.isArray(value)) {
158
+ return JSON.stringify(value.map(canonical).toSorted());
159
+ }
160
+ return JSON.stringify(typeof value === 'string' ? value.toLowerCase() : value);
161
+ }
162
+
163
+ /**
164
+ * @param {string} pattern an include pattern or directory option
165
+ * @returns {string} the directory it names, without ./ prefix, trailing slash or trailing glob
166
+ */
167
+ const directoryOf = (pattern) =>
168
+ pattern
169
+ .replace(/^\.\//, '')
170
+ .replace(/\/\*\*\/\*$/, '')
171
+ .replace(/\/$/, '');
172
+
173
+ /**
174
+ * @param {string[] | undefined} patterns
175
+ * @param {string[]} directories
176
+ * @returns {boolean} whether the include patterns name exactly these directories
177
+ */
178
+ const includesOnly = (patterns, directories) =>
179
+ patterns !== undefined && canonical(patterns.map(directoryOf)) === canonical(directories);
180
+
181
+ /**
182
+ * Splits a project's compiler options into the ones the shared config already provides and the ones to keep.
183
+ * @param {Record<string, unknown>} options the project's own compiler options
184
+ * @param {Record<string, unknown>} base the shared config's compiler options
185
+ * @returns {{ kept: Record<string, unknown>, dropped: string[], changed: string[] }}
186
+ */
187
+ function splitOptions(options, base) {
188
+ /** @type {Record<string, unknown>} */
189
+ const kept = {};
190
+ const dropped = [];
191
+ const changed = [];
192
+ const baseLib = Array.isArray(base.lib) ? base.lib.map((entry) => String(entry).toLowerCase()) : [];
193
+ for (const [name, value] of Object.entries(options)) {
194
+ if (name === 'module' || name === 'moduleResolution') {
195
+ if (name === 'module' && canonical(value) !== canonical(base.module)) {
196
+ changed.push(`module ${value} -> ${base.module}`);
197
+ } else {
198
+ dropped.push(name);
199
+ }
200
+ } else if (REDUNDANT_UNDER_STRICT.has(name) && value === true && base.strict === true) {
201
+ dropped.push(name);
202
+ } else if (TRUE_BY_DEFAULT.has(name) && value === true) {
203
+ dropped.push(name);
204
+ } else if (
205
+ name === 'lib' &&
206
+ Array.isArray(value) &&
207
+ value.every((entry) => baseLib.includes(String(entry).toLowerCase()))
208
+ ) {
209
+ dropped.push(name);
210
+ } else if (name in base && canonical(value) === canonical(base[name])) {
211
+ dropped.push(name);
212
+ } else {
213
+ kept[name] = value;
214
+ }
215
+ }
216
+ return { kept, dropped, changed };
217
+ }
218
+
219
+ /**
220
+ * @param {string} file
221
+ * @param {string[]} names compiler options the automatic rewrite does not handle
222
+ * @param {string} target the shared config to extend
223
+ * @returns {string} an attention note
224
+ */
225
+ const leftAlone = (file, names, target) =>
226
+ `${file} has project-specific compiler options (${names.join(', ')}), so it was left alone. Extend ${target} by hand and keep what the project needs.`;
227
+
228
+ /**
229
+ * @param {string} source existing file contents, used to keep its indentation
230
+ * @param {object} config
231
+ * @returns {string}
232
+ */
233
+ function serialize(source, config) {
234
+ const indent = /^[ \t]+/m.exec(source)?.[0] ?? '\t';
235
+ return `${JSON.stringify(config, null, indent)}\n`;
236
+ }
237
+
238
+ /**
239
+ * @param {string} file
240
+ * @param {string} target the shared config being extended
241
+ * @param {{ kept: Record<string, unknown>, dropped: string[], changed: string[] }} split
242
+ * @param {Record<string, unknown>} extras top-level keys kept, such as include
243
+ * @param {string[]} [notes] extra lines
244
+ * @returns {string[]} plan lines describing the rewrite
245
+ */
246
+ function describeRewrite(file, target, split, extras, notes = []) {
247
+ const lines = [`rewrite ${file} to extend ${target}`];
248
+ const keeps = [...Object.keys(split.kept), ...Object.keys(extras)];
249
+ if (keeps.length > 0) {
250
+ lines.push(` keeps: ${keeps.join(', ')}`);
251
+ }
252
+ if (split.changed.length > 0) {
253
+ lines.push(` changes: ${split.changed.join(', ')}`);
254
+ }
255
+ if (split.dropped.length > 0) {
256
+ lines.push(` drops (provided by the shared config): ${split.dropped.join(', ')}`);
257
+ }
258
+ return [...lines, ...notes];
259
+ }
260
+
261
+ /**
262
+ * Plans the tsconfig changes for a project.
263
+ * @param {string} dir
264
+ * @param {string} style
265
+ * @param {Plan} plan mutated with the file changes and attention notes
266
+ * @param {boolean} hasSentry whether the project depends on a Sentry package
267
+ * @returns {Promise<{ hasBuildConfig: boolean, previousOutDir: string | null }>} hasBuildConfig is true when the project ends up with a build config that extends the shared one
268
+ */
269
+ async function planTsconfigs(dir, style, plan, hasSentry) {
270
+ const rootSource = await readOptional(dir, 'tsconfig.json');
271
+ const buildSource = await readOptional(dir, 'tsconfig.build.json');
272
+
273
+ if (style === 'js') {
274
+ const target = `${TOOLING}/tsconfig/js.json`;
275
+ if (rootSource === null) {
276
+ plan.writes.push({ file: 'tsconfig.json', contents: serialize('', { extends: target }) });
277
+ plan.files.push('create tsconfig.json');
278
+ return { hasBuildConfig: false, previousOutDir: null };
279
+ }
280
+ const root = parseJsonc(rootSource);
281
+ if (String(root.extends ?? '').startsWith(TOOLING)) {
282
+ return { hasBuildConfig: false, previousOutDir: null };
283
+ }
284
+ if (root.extends !== undefined || root.references !== undefined) {
285
+ plan.attention.push(
286
+ `tsconfig.json uses extends or references, so it was left alone. Point it at ${target} by hand.`
287
+ );
288
+ return { hasBuildConfig: false, previousOutDir: null };
289
+ }
290
+ const base = (await readOwnJson('tsconfig/js.json')).compilerOptions;
291
+ const split = splitOptions(root.compilerOptions ?? {}, base);
292
+ const complex = [
293
+ ...Object.keys(split.kept).filter((name) => !SIMPLE_JS_OVERRIDES.has(name)),
294
+ ...(split.changed.length > 0 ? ['module'] : [])
295
+ ];
296
+ if (complex.length > 0) {
297
+ plan.attention.push(leftAlone('tsconfig.json', complex, target));
298
+ return { hasBuildConfig: false, previousOutDir: null };
299
+ }
300
+ const extras = Object.fromEntries(
301
+ ['include', 'exclude', 'files'].filter((key) => root[key] !== undefined).map((key) => [key, root[key]])
302
+ );
303
+ const config = {
304
+ extends: target,
305
+ ...(Object.keys(split.kept).length > 0 && { compilerOptions: split.kept }),
306
+ ...extras
307
+ };
308
+ plan.writes.push({ file: 'tsconfig.json', contents: serialize(rootSource, config) });
309
+ plan.files.push(...describeRewrite('tsconfig.json', target, split, extras));
310
+ return { hasBuildConfig: false, previousOutDir: null };
311
+ }
312
+
313
+ const rootTarget = `${TOOLING}/tsconfig/ts.json`;
314
+ const buildTarget = `${TOOLING}/tsconfig/${style === 'ts-library' ? 'ts-build-library' : 'ts-build'}.json`;
315
+ const rootBase = (await readOwnJson('tsconfig/ts.json')).compilerOptions;
316
+ const buildBase = {
317
+ ...rootBase,
318
+ ...(await readOwnJson('tsconfig/ts-build.json')).compilerOptions,
319
+ ...(style === 'ts-library' && (await readOwnJson('tsconfig/ts-build-library.json')).compilerOptions)
320
+ };
321
+
322
+ /** @type {Record<string, unknown>} */
323
+ let rootOverrides = {};
324
+ let rootMigrated = rootSource === null;
325
+ let sourceRootLeftRoot = false;
326
+ const sentryOptions = hasSentry ? { compilerOptions: { sourceRoot: SENTRY_SOURCE_ROOT } } : {};
327
+ if (rootSource === null) {
328
+ plan.writes.push({ file: 'tsconfig.json', contents: serialize('', { extends: rootTarget }) });
329
+ plan.files.push('create tsconfig.json');
330
+ } else {
331
+ const root = parseJsonc(rootSource);
332
+ if (String(root.extends ?? '').startsWith(TOOLING)) {
333
+ rootOverrides = root.compilerOptions ?? {};
334
+ rootMigrated = true;
335
+ } else if (root.extends !== undefined || root.references !== undefined) {
336
+ plan.attention.push(
337
+ `tsconfig.json uses extends or references, so it was left alone. Point it at ${rootTarget} by hand.`
338
+ );
339
+ } else if (
340
+ Object.keys(splitOptions(root.compilerOptions ?? {}, rootBase).kept).some(
341
+ (name) => !SIMPLE_TS_OVERRIDES.has(name)
342
+ )
343
+ ) {
344
+ const { kept } = splitOptions(root.compilerOptions ?? {}, rootBase);
345
+ plan.attention.push(
346
+ leftAlone(
347
+ 'tsconfig.json',
348
+ Object.keys(kept).filter((name) => !SIMPLE_TS_OVERRIDES.has(name)),
349
+ rootTarget
350
+ )
351
+ );
352
+ } else {
353
+ const split = splitOptions(root.compilerOptions ?? {}, rootBase);
354
+ const notes = [];
355
+ if ('sourceRoot' in split.kept && !(hasSentry && buildSource === null)) {
356
+ delete split.kept.sourceRoot;
357
+ sourceRootLeftRoot = true;
358
+ notes.push(hasSentry ? ' moves: sourceRoot to tsconfig.build.json' : SOURCE_ROOT_REMOVED);
359
+ }
360
+ rootOverrides = split.kept;
361
+ rootMigrated = true;
362
+ /** @type {Record<string, unknown>} */
363
+ const extras = {};
364
+ if (!includesOnly(root.include, ['src', 'test'])) {
365
+ extras.include = root.include ?? ['**/*'];
366
+ }
367
+ if (root.exclude !== undefined && canonical(root.exclude) !== canonical(['node_modules'])) {
368
+ extras.exclude = root.exclude;
369
+ }
370
+ if (root.files !== undefined) {
371
+ extras.files = root.files;
372
+ }
373
+ const config = {
374
+ extends: rootTarget,
375
+ ...(Object.keys(split.kept).length > 0 && { compilerOptions: split.kept }),
376
+ ...extras
377
+ };
378
+ plan.writes.push({ file: 'tsconfig.json', contents: serialize(rootSource, config) });
379
+ plan.files.push(...describeRewrite('tsconfig.json', rootTarget, split, extras, notes));
380
+ if (split.changed.length > 0) {
381
+ plan.attention.push(
382
+ `${split.changed.join(', ')}: run the type check afterwards. Relative dynamic imports need a file extension under NodeNext.`
383
+ );
384
+ }
385
+ if (root.compilerOptions?.noUncheckedIndexedAccess !== true) {
386
+ plan.attention.push(
387
+ 'The shared tsconfig turns on noUncheckedIndexedAccess: reading array[i] or record[key] now includes undefined. Expect new type errors where the code does not check for it.'
388
+ );
389
+ }
390
+ }
391
+ }
392
+
393
+ if (buildSource === null) {
394
+ if (rootSource === null) {
395
+ plan.writes.push({
396
+ file: 'tsconfig.build.json',
397
+ contents: serialize('', { extends: buildTarget, ...sentryOptions })
398
+ });
399
+ plan.files.push('create tsconfig.build.json');
400
+ return { hasBuildConfig: true, previousOutDir: null };
401
+ }
402
+ plan.attention.push(
403
+ 'No tsconfig.build.json was found, so none was added. Add one extending ' +
404
+ buildTarget +
405
+ ' if this project should build with tsc.'
406
+ );
407
+ return { hasBuildConfig: false, previousOutDir: null };
408
+ }
409
+
410
+ const build = parseJsonc(buildSource);
411
+ if (String(build.extends ?? '').startsWith(TOOLING)) {
412
+ return { hasBuildConfig: true, previousOutDir: null };
413
+ }
414
+ if (!rootMigrated) {
415
+ plan.attention.push(`tsconfig.build.json was left alone because tsconfig.json was. Extend ${buildTarget} by hand.`);
416
+ return { hasBuildConfig: false, previousOutDir: null };
417
+ }
418
+ const sourceRootReminder =
419
+ hasSentry && sourceRootLeftRoot
420
+ ? ' tsconfig.json no longer sets sourceRoot, so set "sourceRoot": "/" there for Sentry.'
421
+ : '';
422
+ if (!['./tsconfig.json', './tsconfig', 'tsconfig.json'].includes(build.extends)) {
423
+ plan.attention.push(
424
+ `tsconfig.build.json does not extend ./tsconfig.json, so it was left alone. Extend ${buildTarget} by hand.${sourceRootReminder}`
425
+ );
426
+ return { hasBuildConfig: false, previousOutDir: null };
427
+ }
428
+
429
+ const { outDir, rootDir, sourceRoot: previousSourceRoot, ...own } = build.compilerOptions ?? {};
430
+ const previousOutDir = typeof outDir === 'string' ? directoryOf(outDir) : null;
431
+ const { types: _types, noEmit: _noEmit, sourceRoot: _sourceRoot, ...inherited } = rootOverrides;
432
+ const split = splitOptions({ ...inherited, ...own }, buildBase);
433
+ const complex = Object.keys(split.kept).filter((name) => !SIMPLE_TS_OVERRIDES.has(name));
434
+ if (complex.length > 0) {
435
+ plan.attention.push(leftAlone('tsconfig.build.json', complex, buildTarget) + sourceRootReminder);
436
+ return { hasBuildConfig: false, previousOutDir: null };
437
+ }
438
+ if (typeof rootDir === 'string' && directoryOf(rootDir) !== 'src') {
439
+ split.kept.rootDir = rootDir;
440
+ }
441
+ if (previousOutDir !== null && previousOutDir !== BUILD_DIR) {
442
+ split.changed.push(`outDir ${previousOutDir}/ -> ${BUILD_DIR}/`);
443
+ }
444
+ const notes = [];
445
+ if (hasSentry) {
446
+ split.kept.sourceRoot = SENTRY_SOURCE_ROOT;
447
+ if (previousSourceRoot === undefined && !sourceRootLeftRoot) {
448
+ notes.push(' adds: sourceRoot "/" (Sentry is installed: this keeps source paths stable for issue grouping)');
449
+ }
450
+ } else if (previousSourceRoot !== undefined) {
451
+ notes.push(SOURCE_ROOT_REMOVED);
452
+ }
453
+ /** @type {Record<string, unknown>} */
454
+ const extras = {};
455
+ if (build.include !== undefined && !includesOnly(build.include, ['src'])) {
456
+ extras.include = build.include;
457
+ }
458
+ if (build.exclude !== undefined && canonical(build.exclude) !== canonical(['**/*.test.ts'])) {
459
+ extras.exclude = build.exclude;
460
+ }
461
+ const config = {
462
+ extends: buildTarget,
463
+ ...(Object.keys(split.kept).length > 0 && { compilerOptions: split.kept }),
464
+ ...extras
465
+ };
466
+ plan.writes.push({ file: 'tsconfig.build.json', contents: serialize(buildSource, config) });
467
+ plan.files.push(...describeRewrite('tsconfig.build.json', buildTarget, split, extras, notes));
468
+ return { hasBuildConfig: true, previousOutDir };
469
+ }
470
+
471
+ /**
472
+ * @param {string} dir
473
+ * @param {any} pkg the project's package.json before the migration
474
+ * @param {string} previous the old build output directory
475
+ * @returns {Promise<string[]>} places that still name the old build output directory
476
+ */
477
+ async function findOutDirReferences(dir, pkg, previous) {
478
+ const mention = new RegExp(`(^|[\\s"'./=:])${previous.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&')}(/|$|[\\s"'])`, 'm');
479
+ const references = [];
480
+ for (const field of ['main', 'types', 'typings', 'bin', 'exports', 'files']) {
481
+ if (pkg[field] !== undefined && mention.test(JSON.stringify(pkg[field]).replaceAll('"', ' '))) {
482
+ references.push(`package.json ${field}`);
483
+ }
484
+ }
485
+ for (const [name, command] of Object.entries(pkg.scripts ?? {})) {
486
+ if (mention.test(command)) {
487
+ references.push(`package.json scripts.${name}`);
488
+ }
489
+ }
490
+ const sources = await Promise.all(OUT_DIR_REFERENCE_FILES.map((file) => readOptional(dir, file)));
491
+ for (const [index, source] of sources.entries()) {
492
+ if (source !== null && mention.test(source)) {
493
+ references.push(OUT_DIR_REFERENCE_FILES[index]);
494
+ }
495
+ }
496
+ return references;
497
+ }
498
+
499
+ /**
500
+ * @param {string} dir
501
+ * @param {Record<string, string>} scripts the project's scripts after the migration
502
+ * @returns {Promise<string>} a reminder to make sure CI checks formatting, naming the CI config and script when it can
503
+ */
504
+ async function ciReminder(dir, scripts) {
505
+ const workflows = await readdir(path.join(dir, '.github/workflows')).catch(() => []);
506
+ const candidates = [
507
+ '.circleci/config.yml',
508
+ ...workflows.filter((file) => /\.ya?ml$/.test(file)).map((file) => `.github/workflows/${file}`)
509
+ ];
510
+ const sources = await Promise.all(candidates.map((file) => readOptional(dir, file)));
511
+ const configs = candidates.filter((_, index) => sources[index] !== null);
512
+ const formatScripts = Object.keys(scripts).filter((name) =>
513
+ /\boxfmt --check\b|\b(fmt|format):check\b/.test(scripts[name])
514
+ );
515
+ const ciText = sources.filter((source) => source !== null).join('\n');
516
+ const covered = formatScripts.find((name) => new RegExp(`npm run ${name}(\\s|$)`, 'm').test(ciText));
517
+ if (configs.length === 0) {
518
+ return 'Double check your CI: no CI config was found here. It should run a step that fails on unformatted code, such as "npm run fmt:check".';
519
+ }
520
+ if (covered) {
521
+ return `Double check CI: ${configs.join(', ')} runs "npm run ${covered}", which now includes the format check. Confirm that step fails the build on unformatted code.`;
522
+ }
523
+ return `Double check CI: ${configs.join(', ')} does not appear to run a script that checks formatting. Add a step such as "npm run ${formatScripts.includes('check') ? 'check' : 'fmt:check'}".`;
524
+ }
525
+
526
+ /**
527
+ * Works out everything the migration would change, without changing anything.
528
+ * @param {string} dir directory containing the package.json to migrate
529
+ * @param {string} style a key of STYLES
530
+ * @param {{ toolingSpec?: string }} [options] toolingSpec overrides the @particle/tooling version written to package.json
531
+ * @returns {Promise<Plan>}
532
+ */
533
+ export async function createPlan(dir, style, options = {}) {
534
+ if (!Object.hasOwn(STYLES, style)) {
535
+ throw new Error(`Unknown style "${style}". Expected one of: ${Object.keys(STYLES).join(', ')}`);
536
+ }
537
+ const own = await readOwnJson('package.json');
538
+ const toolingSpec = options.toolingSpec ?? `^${own.version}`;
539
+ const typescriptSpec = own.peerDependencies.typescript;
540
+ const packageSource = await readFile(path.join(dir, 'package.json'), 'utf8');
541
+ const pkg = JSON.parse(packageSource);
542
+ const original = structuredClone(pkg);
543
+
544
+ /** @type {Plan} */
545
+ const plan = {
546
+ style,
547
+ dependencies: [],
548
+ files: [],
549
+ scripts: [],
550
+ attention: [],
551
+ packageJson: null,
552
+ writes: [],
553
+ deletes: []
554
+ };
555
+
556
+ const removed = [];
557
+ for (const field of ['dependencies', 'devDependencies']) {
558
+ for (const name of Object.keys(pkg[field] ?? {})) {
559
+ if (LEGACY_PACKAGES.test(name)) {
560
+ delete pkg[field][name];
561
+ removed.push(name);
562
+ }
563
+ }
564
+ }
565
+ if (removed.length > 0) {
566
+ plan.dependencies.push(`remove ${removed.join(', ')}`);
567
+ }
568
+ const typescriptField = pkg.dependencies?.typescript ? 'dependencies' : 'devDependencies';
569
+ const currentTypescript = pkg[typescriptField]?.typescript;
570
+ if (currentTypescript !== undefined) {
571
+ const major = Number(/\d+/.exec(currentTypescript.replace(/^npm:.+@/, ''))?.[0]);
572
+ if (currentTypescript.startsWith('npm:') || !(major >= 7)) {
573
+ pkg[typescriptField].typescript = typescriptSpec;
574
+ plan.dependencies.push(`typescript ${currentTypescript} -> ${typescriptSpec}`);
575
+ plan.attention.push('TypeScript moves to version 7: run the type check afterwards and fix any new errors.');
576
+ }
577
+ } else if (style !== 'js') {
578
+ pkg.devDependencies = { ...pkg.devDependencies, typescript: typescriptSpec };
579
+ plan.dependencies.push(`add typescript ${typescriptSpec}`);
580
+ }
581
+ if (style !== 'js' && pkg.devDependencies?.[TYPE_AWARE_LINTER] === undefined) {
582
+ const spec = own.peerDependencies[TYPE_AWARE_LINTER];
583
+ pkg.devDependencies = { ...pkg.devDependencies, [TYPE_AWARE_LINTER]: spec };
584
+ plan.dependencies.push(
585
+ `add ${TYPE_AWARE_LINTER} ${spec} (runs the type-aware lint rules, such as no-floating-promises)`
586
+ );
587
+ }
588
+ if (pkg.devDependencies?.[TOOLING] !== toolingSpec) {
589
+ pkg.devDependencies = { ...pkg.devDependencies, [TOOLING]: toolingSpec };
590
+ plan.dependencies.push(`add ${TOOLING} ${toolingSpec} (installs oxlint and oxfmt as peer dependencies)`);
591
+ }
592
+ if (pkg.devDependencies) {
593
+ pkg.devDependencies = Object.fromEntries(
594
+ Object.entries(pkg.devDependencies).toSorted(([a], [b]) => a.localeCompare(b, 'en'))
595
+ );
596
+ }
597
+
598
+ const legacyFiles = LEGACY_FILES.filter((file) => existsSync(path.join(dir, file)));
599
+ const tracked = await Promise.all(legacyFiles.map((file) => isTracked(dir, file)));
600
+ for (const [index, file] of legacyFiles.entries()) {
601
+ plan.deletes.push(file);
602
+ plan.files.push(`delete ${file}${tracked[index] ? '' : ' (not tracked by git, so it cannot be restored)'}`);
603
+ }
604
+ const legacyLintConfigs = legacyFiles.filter((file) => file !== '.eslintignore' && !file.startsWith('.oxfmtrc'));
605
+ if (legacyLintConfigs.length > 0) {
606
+ plan.attention.push(
607
+ `${legacyLintConfigs.join(', ')}: project-specific rules and ignores are not carried over, and the files are deleted. Save anything you still need before applying, then re-add it in oxlint.config.ts.`
608
+ );
609
+ }
610
+ for (const [file, contents] of Object.entries(lintFiles(style))) {
611
+ if (!existsSync(path.join(dir, file))) {
612
+ plan.writes.push({ file, contents });
613
+ plan.files.push(`create ${file}`);
614
+ }
615
+ }
616
+
617
+ const hasSentry = Object.keys({ ...original.dependencies, ...original.devDependencies }).some((name) =>
618
+ name.startsWith('@sentry/')
619
+ );
620
+ const { hasBuildConfig, previousOutDir } = await planTsconfigs(dir, style, plan, hasSentry);
621
+
622
+ if (hasBuildConfig) {
623
+ const gitignore = (await readOptional(dir, '.gitignore')) ?? '';
624
+ const ignored = gitignore.split('\n').some((line) => directoryOf(line.trim().replace(/^\//, '')) === BUILD_DIR);
625
+ if (!ignored) {
626
+ const separator = gitignore === '' || gitignore.endsWith('\n') ? '' : '\n';
627
+ plan.writes.push({ file: '.gitignore', contents: `${gitignore}${separator}${BUILD_DIR}/\n` });
628
+ plan.files.push(`add ${BUILD_DIR}/ to .gitignore`);
629
+ }
630
+ }
631
+ if (previousOutDir !== null && previousOutDir !== BUILD_DIR) {
632
+ const references = await findOutDirReferences(dir, original, previousOutDir);
633
+ plan.attention.push(
634
+ `Build output moves from ${previousOutDir}/ to ${BUILD_DIR}/.` +
635
+ (references.length > 0
636
+ ? ` Update these references to the old directory by hand: ${references.join(', ')}.`
637
+ : '')
638
+ );
639
+ }
640
+
641
+ pkg.scripts ??= {};
642
+ for (const [name, command] of Object.entries(pkg.scripts)) {
643
+ let steps = command.split('&&').map((step) => step.trim());
644
+ steps = steps.map((step) => (/^(eslint( \.)?|oxlint)$/.test(step) ? LINT : step));
645
+ if (name === 'check' && !/\boxfmt\b|\b(fmt|format):check\b/.test(command)) {
646
+ const lintStep = steps.findIndex((step) => /^oxlint\b/.test(step));
647
+ steps = steps.toSpliced(lintStep === -1 ? steps.length : lintStep + 1, 0, FORMAT_CHECK);
648
+ }
649
+ const migrated = steps.join(' && ');
650
+ if (
651
+ migrated !==
652
+ command
653
+ .split('&&')
654
+ .map((step) => step.trim())
655
+ .join(' && ')
656
+ ) {
657
+ pkg.scripts[name] = migrated;
658
+ plan.scripts.push(`${name}: "${command}" -> "${migrated}"`);
659
+ }
660
+ if (/\beslint\b/.test(migrated)) {
661
+ plan.attention.push(`scripts.${name} still runs eslint with options ("${migrated}"). Update it by hand.`);
662
+ }
663
+ }
664
+ const wantedScripts = {
665
+ ...FORMAT_SCRIPTS,
666
+ ...(style !== 'js' && { check: `tsc && ${LINT} && ${FORMAT_CHECK}` }),
667
+ ...(style !== 'js' && hasBuildConfig && { build: BUILD_SCRIPT })
668
+ };
669
+ const added = [];
670
+ for (const [name, command] of Object.entries(wantedScripts)) {
671
+ if (!(name in pkg.scripts)) {
672
+ pkg.scripts[name] = command;
673
+ added.push(name);
674
+ }
675
+ }
676
+ if (added.length > 0) {
677
+ plan.scripts.push(`add ${added.join(', ')}`);
678
+ }
679
+
680
+ if (JSON.stringify(pkg) !== JSON.stringify(original)) {
681
+ plan.packageJson = serialize(packageSource, pkg);
682
+ }
683
+ if (hasChanges(plan)) {
684
+ plan.attention.push(await ciReminder(dir, pkg.scripts));
685
+ }
686
+ return plan;
687
+ }
688
+
689
+ /**
690
+ * @param {Plan} plan
691
+ * @returns {boolean} whether applying the plan would change anything
692
+ */
693
+ export const hasChanges = (plan) => plan.packageJson !== null || plan.writes.length > 0 || plan.deletes.length > 0;
694
+
695
+ /**
696
+ * @param {string} line a plan line
697
+ * @returns {'red' | 'yellow' | 'green' | null} the color for removals, changes and additions
698
+ */
699
+ function lineColor(line) {
700
+ const text = line.trimStart();
701
+ if (/^(remove|delete|removes:|drops) /.test(text)) {
702
+ return 'red';
703
+ }
704
+ if (/^(rewrite|changes:|moves:) /.test(text) || text.includes(' -> ')) {
705
+ return 'yellow';
706
+ }
707
+ if (/^(add|create|adds:) /.test(text)) {
708
+ return 'green';
709
+ }
710
+ return null;
711
+ }
712
+
713
+ /**
714
+ * @param {Plan} plan
715
+ * @param {{ color?: boolean }} [options] color defaults to whether stdout is a terminal that supports it
716
+ * @returns {string} the plan as text for the terminal
717
+ */
718
+ export function formatPlan(plan, { color } = {}) {
719
+ /**
720
+ * @param {Parameters<typeof styleText>[0]} format
721
+ * @param {string} text
722
+ * @returns {string}
723
+ */
724
+ const paint = (format, text) =>
725
+ color === false ? text : styleText(format, text, { validateStream: color !== true });
726
+ const sections = [
727
+ ['Dependencies (package.json)', plan.dependencies],
728
+ ['Files', plan.files],
729
+ ['Scripts (package.json)', plan.scripts]
730
+ ];
731
+ const changes = sections
732
+ .filter(([, lines]) => lines.length > 0)
733
+ .map(([title, lines]) => {
734
+ const body = lines.map((line) => {
735
+ const text = line.startsWith(' ') ? line : ` - ${line}`;
736
+ const format = lineColor(line);
737
+ return format ? paint(format, text) : text;
738
+ });
739
+ return `${paint('bold', title)}\n${body.join('\n')}`;
740
+ });
741
+ const attention = formatAttention(plan, { color });
742
+ return [...changes, ...(attention ? [attention] : [])].join('\n\n');
743
+ }
744
+
745
+ /**
746
+ * @param {Plan} plan
747
+ * @param {{ color?: boolean }} [options] color defaults to whether stdout is a terminal that supports it
748
+ * @returns {string} the notes the user has to act on, or an empty string when there are none
749
+ */
750
+ export function formatAttention(plan, { color } = {}) {
751
+ if (plan.attention.length === 0) {
752
+ return '';
753
+ }
754
+ const title = 'Needs your attention';
755
+ const heading = color === false ? title : styleText(['bold', 'yellow'], title, { validateStream: color !== true });
756
+ return `${heading}\n${plan.attention.map((line) => ` - ${line}`).join('\n')}`;
757
+ }
758
+
759
+ /**
760
+ * @param {string} dir
761
+ * @param {Plan} plan
762
+ * @returns {Promise<void>}
763
+ */
764
+ export async function applyPlan(dir, plan) {
765
+ const writes =
766
+ plan.packageJson === null ? plan.writes : [...plan.writes, { file: 'package.json', contents: plan.packageJson }];
767
+ await Promise.all([
768
+ ...writes.map(({ file, contents }) => writeFile(path.join(dir, file), contents)),
769
+ ...plan.deletes.map((file) => rm(path.join(dir, file)))
770
+ ]);
771
+ }
package/oxfmt.js ADDED
@@ -0,0 +1,9 @@
1
+ import { defineConfig } from 'oxfmt';
2
+
3
+ export default defineConfig({
4
+ useTabs: true,
5
+ singleQuote: true,
6
+ sortImports: {},
7
+ trailingComma: 'none',
8
+ printWidth: 120
9
+ });
@@ -0,0 +1,53 @@
1
+ import { defineConfig } from 'oxlint';
2
+
3
+ import base from './oxlint.js';
4
+
5
+ /**
6
+ * Typed rules that the enabled categories include. They only run in type-aware mode, so turning that mode on
7
+ * would start enforcing all of them at once. They stay off until one is chosen deliberately.
8
+ */
9
+ const UNADOPTED_TYPED_RULES = {
10
+ 'typescript/consistent-return': 'off',
11
+ 'typescript/no-array-delete': 'off',
12
+ 'typescript/no-duplicate-type-constituents': 'off',
13
+ 'typescript/no-for-in-array': 'off',
14
+ 'typescript/no-generated-empty-object-type': 'off',
15
+ 'typescript/no-implied-eval': 'off',
16
+ 'typescript/no-meaningless-void-operator': 'off',
17
+ 'typescript/no-misused-spread': 'off',
18
+ 'typescript/no-redundant-type-constituents': 'off',
19
+ 'typescript/no-unnecessary-boolean-literal-compare': 'off',
20
+ 'typescript/no-unnecessary-template-expression': 'off',
21
+ 'typescript/no-unnecessary-type-arguments': 'off',
22
+ 'typescript/no-unnecessary-type-conversion': 'off',
23
+ 'typescript/no-unnecessary-type-parameters': 'off',
24
+ 'typescript/no-unsafe-enum-assignment': 'off',
25
+ 'typescript/no-unsafe-enum-comparison': 'off',
26
+ 'typescript/no-unsafe-type-assertion': 'off',
27
+ 'typescript/no-unsafe-unary-minus': 'off',
28
+ 'typescript/no-useless-default-assignment': 'off',
29
+ 'typescript/require-array-sort-compare': 'off',
30
+ 'typescript/restrict-template-expressions': 'off',
31
+ 'typescript/unbound-method': 'off'
32
+ };
33
+
34
+ export default defineConfig({
35
+ ...base,
36
+ // Type-aware rules need the oxlint-tsgolint package.
37
+ options: { typeAware: true },
38
+ rules: {
39
+ ...base.rules,
40
+ ...UNADOPTED_TYPED_RULES,
41
+ 'typescript/await-thenable': 'error',
42
+ 'typescript/ban-ts-comment': 'error',
43
+ 'typescript/no-array-constructor': 'error',
44
+ 'typescript/no-base-to-string': 'error',
45
+ 'typescript/no-empty-object-type': ['error', { allowInterfaces: 'always' }],
46
+ 'typescript/no-floating-promises': ['error', { ignoreVoid: true }],
47
+ 'typescript/no-misused-promises': ['error', { checksVoidReturn: { arguments: false, inheritedMethods: false } }],
48
+ 'typescript/no-namespace': 'error',
49
+ 'typescript/no-require-imports': 'error',
50
+ 'typescript/no-unnecessary-type-assertion': 'warn',
51
+ 'typescript/no-unsafe-function-type': 'error'
52
+ }
53
+ });
package/oxlint.js ADDED
@@ -0,0 +1,59 @@
1
+ import { defineConfig } from 'oxlint';
2
+
3
+ const TEST_FILES = ['**/*.{spec,test,e2e,unit,integration}.{mjs,cjs,js,ts}', '**/test/**/*.{mjs,cjs,js,ts}'];
4
+
5
+ export default defineConfig({
6
+ plugins: ['eslint', 'typescript', 'unicorn', 'oxc', 'promise', 'node', 'vitest'],
7
+ categories: {
8
+ correctness: 'error',
9
+ suspicious: 'warn',
10
+ perf: 'warn'
11
+ },
12
+ rules: {
13
+ curly: 'error',
14
+ eqeqeq: ['error', 'smart'],
15
+ 'func-names': ['error', 'as-needed'],
16
+ 'func-style': ['error', 'declaration', { allowArrowFunctions: true }],
17
+ 'no-console': 'error',
18
+ 'no-nested-ternary': 'error',
19
+ 'no-undef': 'error',
20
+ 'no-underscore-dangle': 'off',
21
+ 'no-unused-vars': [
22
+ 'error',
23
+ {
24
+ vars: 'all',
25
+ varsIgnorePattern: '^_',
26
+ args: 'after-used',
27
+ argsIgnorePattern: '^_',
28
+ caughtErrors: 'all',
29
+ caughtErrorsIgnorePattern: '^_'
30
+ }
31
+ ],
32
+ 'no-var': 'error',
33
+ 'node/handle-callback-err': 'error',
34
+ 'prefer-const': ['error', { destructuring: 'all' }],
35
+ 'typescript/no-explicit-any': 'off',
36
+ 'typescript/no-non-null-asserted-optional-chain': 'error',
37
+ 'vitest/require-mock-type-parameters': 'off'
38
+ },
39
+ overrides: [
40
+ {
41
+ // A top-level `env` is dropped when a project extends this config. Overrides are kept.
42
+ files: ['**/*'],
43
+ env: { node: true }
44
+ },
45
+ {
46
+ files: ['**/scripts/**', '**/examples/**'],
47
+ rules: {
48
+ 'no-console': 'off'
49
+ }
50
+ },
51
+ {
52
+ files: TEST_FILES,
53
+ env: { vitest: true },
54
+ rules: {
55
+ 'func-names': 'off'
56
+ }
57
+ }
58
+ ]
59
+ });
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@particle/tooling",
3
+ "version": "0.1.0",
4
+ "description": "Shared oxlint, oxfmt and TypeScript configuration for Particle projects",
5
+ "homepage": "https://github.com/particle-iot-inc/particle-tooling",
6
+ "bugs": {
7
+ "url": "https://github.com/particle-iot-inc/particle-tooling/issues"
8
+ },
9
+ "license": "ISC",
10
+ "author": "",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/particle-iot-inc/particle-tooling.git"
14
+ },
15
+ "bin": {
16
+ "particle-tooling-init": "bin/init.js"
17
+ },
18
+ "files": [
19
+ "bin/init.js",
20
+ "lib",
21
+ "oxfmt.js",
22
+ "oxlint-typescript.js",
23
+ "oxlint.js",
24
+ "tsconfig"
25
+ ],
26
+ "type": "module",
27
+ "exports": {
28
+ "./oxlint": "./oxlint.js",
29
+ "./oxlint-typescript": "./oxlint-typescript.js",
30
+ "./oxfmt": "./oxfmt.js",
31
+ "./tsconfig/*.json": "./tsconfig/*.json"
32
+ },
33
+ "publishConfig": {
34
+ "access": "restricted"
35
+ },
36
+ "scripts": {
37
+ "check": "npm run lint && npm run fmt:check",
38
+ "lint": "oxlint --deny-warnings",
39
+ "fmt": "oxfmt",
40
+ "fmt:check": "oxfmt --check",
41
+ "test": "vitest run"
42
+ },
43
+ "devDependencies": {
44
+ "oxfmt": "~0.78.0",
45
+ "oxlint": "^1.93.0",
46
+ "oxlint-tsgolint": "^7.0.2007",
47
+ "typescript": "^7.0.2",
48
+ "vitest": "^5.1.0"
49
+ },
50
+ "peerDependencies": {
51
+ "oxfmt": "~0.78.0",
52
+ "oxlint": "^1.93.0",
53
+ "oxlint-tsgolint": "^7.0.2007",
54
+ "typescript": "^7.0.2"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "typescript": {
58
+ "optional": true
59
+ },
60
+ "oxlint-tsgolint": {
61
+ "optional": true
62
+ }
63
+ },
64
+ "engines": {
65
+ "node": ">=22.23.4",
66
+ "npm": ">=10"
67
+ }
68
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "checkJs": false,
5
+ "module": "commonjs",
6
+ "target": "es2022",
7
+ "skipLibCheck": true,
8
+ "noEmit": true
9
+ }
10
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "./ts-build.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "declarationMap": true
6
+ }
7
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "./ts.json",
3
+ "compilerOptions": {
4
+ "noEmit": false,
5
+ "outDir": "${configDir}/build",
6
+ "rootDir": "${configDir}/src"
7
+ },
8
+ "include": ["${configDir}/src/**/*"],
9
+ "exclude": ["${configDir}/**/*.test.ts"]
10
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "noEmit": true,
4
+ "target": "ES2024",
5
+ "lib": ["ES2024", "ESNext.Collection", "ESNext.Iterator"],
6
+ "module": "NodeNext",
7
+ "strict": true,
8
+ "noImplicitOverride": true,
9
+ "noUncheckedIndexedAccess": true,
10
+ "noUnusedLocals": true,
11
+ "noUnusedParameters": true,
12
+ "allowJs": true,
13
+ "maxNodeModuleJsDepth": 2,
14
+ "resolveJsonModule": true,
15
+ "esModuleInterop": true,
16
+ "skipLibCheck": true,
17
+ "sourceMap": true,
18
+ "inlineSources": true
19
+ },
20
+ "include": ["${configDir}/src/**/*", "${configDir}/test/**/*"]
21
+ }