@octanejs/codemod 0.1.3 → 0.2.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.
Files changed (58) hide show
  1. package/README.md +305 -5
  2. package/dist/bin.d.ts +2 -0
  3. package/dist/bin.js +162 -0
  4. package/dist/compiler.d.ts +11 -0
  5. package/dist/compiler.js +48 -0
  6. package/dist/effect-receivers.d.ts +11 -0
  7. package/dist/effect-receivers.js +315 -0
  8. package/dist/expression-wrappers.d.ts +6 -0
  9. package/dist/expression-wrappers.js +16 -0
  10. package/dist/forwarded-props.d.ts +27 -0
  11. package/dist/forwarded-props.js +489 -0
  12. package/dist/index.d.ts +6 -0
  13. package/{src → dist}/index.js +1 -0
  14. package/dist/linked-state.d.ts +17 -0
  15. package/dist/linked-state.js +126 -0
  16. package/dist/local-calls.d.ts +20 -0
  17. package/dist/local-calls.js +143 -0
  18. package/dist/local-react-hook.d.ts +15 -0
  19. package/dist/local-react-hook.js +353 -0
  20. package/dist/local-uses.d.ts +13 -0
  21. package/dist/local-uses.js +987 -0
  22. package/dist/mappings.d.ts +57 -0
  23. package/dist/mappings.js +343 -0
  24. package/dist/path-svg.d.ts +60 -0
  25. package/dist/path-svg.js +207 -0
  26. package/dist/project.d.ts +9 -0
  27. package/dist/project.js +1568 -0
  28. package/dist/react-intl.d.ts +4 -0
  29. package/dist/react-intl.js +389 -0
  30. package/dist/react-renderer.d.ts +9 -0
  31. package/dist/react-renderer.js +106 -0
  32. package/dist/scoped-signal.d.ts +4 -0
  33. package/dist/scoped-signal.js +480 -0
  34. package/dist/scoped-store-contract.d.ts +13 -0
  35. package/dist/scoped-store-contract.js +741 -0
  36. package/dist/store-hook-uses.d.ts +18 -0
  37. package/dist/store-hook-uses.js +403 -0
  38. package/dist/store-inputs.d.ts +16 -0
  39. package/dist/store-inputs.js +391 -0
  40. package/dist/strong.d.ts +24 -0
  41. package/dist/strong.js +142 -0
  42. package/dist/transform.d.ts +27 -0
  43. package/dist/transform.js +4890 -0
  44. package/dist/types.d.ts +203 -0
  45. package/dist/types.js +1 -0
  46. package/package.json +19 -6
  47. package/src/path-svg.ts +218 -0
  48. package/templates/octane-path-svg.ts +56 -0
  49. package/templates/octane-store-context.tsrx +49 -0
  50. package/templates/octane-store-hooks.ts +61 -0
  51. package/templates/react-intl.tsrx +116 -0
  52. package/src/bin.js +0 -151
  53. package/src/compiler.js +0 -61
  54. package/src/index.d.ts +0 -95
  55. package/src/mappings.js +0 -429
  56. package/src/project.js +0 -670
  57. package/src/strong.js +0 -149
  58. package/src/transform.js +0 -3425
package/src/project.js DELETED
@@ -1,670 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { findRoot, readInstalled, scanSourceFiles } from '@octanejs/cli';
4
- import { DATA } from '@octanejs/cli/data';
5
- import ts from 'typescript';
6
- import { finding, loadCompiler, thrown } from './compiler.js';
7
- import { PORTED_PACKAGES } from './mappings.js';
8
- import { strengthen } from './strong.js';
9
- import { transformModule } from './transform.js';
10
-
11
- /**
12
- * @typedef {import('./transform.js').Note} Note
13
- *
14
- * @typedef {Object} CodemodOptions
15
- * @property {'tsrx' | 'tsx'} [target]
16
- * @property {boolean} [strong] migrate to Strong mode where the compiler
17
- * accepts it, falling back to compatibility mode per module
18
- * @property {boolean} [forceStrong] keep `"use strong"` even on modules with
19
- * Strong errors left
20
- * @property {boolean} [verify] compile every migrated module (default true)
21
- * @property {boolean} [write] write the result to disk (default true)
22
- * @property {string} [root] the project root, for resolving its compiler
23
- *
24
- * @typedef {Object} FileResult
25
- * @property {string} file the module's path, relative to the root
26
- * @property {string} output where it is written, relative to the root
27
- * @property {boolean} changed
28
- * @property {Record<string, number>} rules
29
- * @property {Note[]} notes the codemod's own findings, at the original file's
30
- * lines
31
- * @property {boolean | null} strong whether it is Strong, or null when Strong
32
- * was not requested or does not apply
33
- * @property {string[]} strongFixes
34
- * @property {{ code: string, severity: string, message: string, line: number }[]} diagnostics
35
- * what the compiler reported for the migrated module
36
- * @property {string} code
37
- *
38
- * @typedef {Object} CodemodResult
39
- * @property {string} root
40
- * @property {FileResult[]} files
41
- * @property {{ from: string, to: string }[]} packages React packages the
42
- * migrated code now imports as Octane bindings
43
- * @property {{ name: string, range: string }[]} dependencies the bindings
44
- * added to package.json, which the project did not declare yet
45
- * @property {{ name: string, patch: string }[]} patched patches the project
46
- * applies to replaced React packages, which do not reach their bindings
47
- * @property {Missing[]} missing React packages the code imports that have no
48
- * Octane port, and how it uses them
49
- * @property {string[]} html entry pages whose script reference was updated
50
- * @property {string | null} compiler where the verifying compiler came from
51
- *
52
- * @typedef {import('./transform.js').Unported & { modules: number }} Missing
53
- * with how many modules import it
54
- */
55
-
56
- const SOURCE = /\.(?:[cm]?[jt]sx?)$/;
57
- /** React packages and the Octane package that replaces each. */
58
- const CATALOG = { ...DATA.reactPackages, ...PORTED_PACKAGES };
59
- /** A package that, by its name, renders through React. */
60
- const REACT_PACKAGE = /^(?:react-|@[^/]+\/react(?:-|\/|$)|[^/]+\/react$)|-react(?:\/|$)/;
61
-
62
- /**
63
- * Migrate every React module under `paths`.
64
- *
65
- * Two passes: the first decides which modules become `.tsrx`, the second
66
- * rewrites every module with that rename map in hand, so an import of a
67
- * renamed module is updated wherever it is.
68
- *
69
- * @param {string[]} paths
70
- * @param {CodemodOptions} [options]
71
- * @returns {Promise<CodemodResult>}
72
- */
73
- export async function runCodemod(paths, options = {}) {
74
- const target = options.target ?? 'tsrx';
75
- const strong = options.strong === true && target === 'tsrx';
76
- const root = path.resolve(options.root ?? findRoot(paths[0] ?? '.'));
77
- const files = paths.flatMap((entry) => collect(path.resolve(entry)));
78
-
79
- const known = new Set(files);
80
- const config = tsconfigOptions(root);
81
- const program = projectProgram(config, files);
82
- const checker = program?.getTypeChecker();
83
- /** @type {Map<string, string>} */
84
- const renames = new Map();
85
- /** @type {Map<string, import('./transform.js').ModuleExports>} */
86
- const exports = new Map();
87
- for (const file of files) {
88
- const result = transformModule(fs.readFileSync(file, 'utf8'), file, { target });
89
- exports.set(file, result.exports);
90
- if (result.template) renames.set(file, file.replace(/\.(?:jsx?|tsx)$/, '.tsrx'));
91
- }
92
- const contextsOf = contextIndex(exports, known);
93
-
94
- const verify = options.verify !== false;
95
- const compiler = verify || strong ? await loadCompiler(root) : null;
96
- /** @type {Map<string, string>} */
97
- const packages = new Map();
98
- /** @type {Map<string, Missing>} */
99
- const missing = new Map();
100
- // `ReactCompat` hosts a component from a package with no port in a React
101
- // root, from 19.2 within the React 19 series it supports.
102
- const reactCompat = ['react', 'react-dom'].every((name) =>
103
- /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(root, name)?.version ?? ''),
104
- );
105
- /** @type {FileResult[]} */
106
- const results = [];
107
- for (const file of files) {
108
- const source = fs.readFileSync(file, 'utf8');
109
- /** @type {Note[]} */
110
- const extra = [];
111
- const resolveSpecifier = (/** @type {string} */ specifier) =>
112
- resolveRelative(file, specifier, known, renames) ??
113
- resolveAlias(file, specifier, renames, config) ??
114
- resolveBinding(specifier, packages, extra);
115
- const isContext = (/** @type {string} */ specifier, /** @type {string} */ name) => {
116
- if (!specifier.startsWith('.')) return null;
117
- const target = resolveModule(file, specifier, known);
118
- return target ? contextsOf(target.file).has(name) : null;
119
- };
120
- const sourceFile = program?.getSourceFile(file);
121
- const result = transformModule(source, file, {
122
- target,
123
- strong,
124
- strictNullChecks: program !== null,
125
- types: sourceFile && checker && { sourceFile, checker },
126
- resolveSpecifier,
127
- isContext,
128
- unported: (specifier) => unportedName(specifier, file),
129
- reactCompat,
130
- });
131
- for (const port of result.unported) {
132
- const entry = missing.get(port.name) ?? {
133
- name: port.name,
134
- modules: 0,
135
- islands: 0,
136
- blocked: 0,
137
- };
138
- entry.modules++;
139
- entry.islands += port.islands;
140
- entry.blocked += port.blocked;
141
- missing.set(port.name, entry);
142
- }
143
- const output = renames.get(file) ?? file;
144
- let code = result.code;
145
- /** @type {boolean | null} */
146
- let isStrong = null;
147
- /** @type {string[]} */
148
- let strongFixes = [];
149
- /** @type {FileResult['diagnostics']} */
150
- let diagnostics = [];
151
- if (compiler && result.changed) {
152
- if (strong && result.template) {
153
- const strengthened = strengthen(compiler, code, output, { force: options.forceStrong });
154
- code = strengthened.code;
155
- isStrong = strengthened.strong;
156
- strongFixes = strengthened.fixed;
157
- if (!strengthened.strong) diagnostics.push(...strengthened.blockers);
158
- }
159
- if (verify && isCompiled(output, code))
160
- diagnostics.push(...compile(compiler, code, output, isStrong === true));
161
- }
162
- results.push({
163
- file: path.relative(root, file),
164
- output: path.relative(root, output),
165
- changed: result.changed || output !== file,
166
- rules: result.rules,
167
- notes: [...result.notes, ...extra],
168
- strong: isStrong,
169
- strongFixes,
170
- diagnostics: dedupe(diagnostics),
171
- code,
172
- });
173
- }
174
-
175
- // TSRX written for React (`@tsrx/react`) is a dialect the TypeScript
176
- // parser cannot read, so it is reported rather than skipped silently.
177
- for (const file of paths.flatMap((entry) => collect(path.resolve(entry), isTsrx))) {
178
- const source = fs.readFileSync(file, 'utf8');
179
- const react = /^import\b[^;]*?\bfrom\s+['"]react(?:-dom)?(?:\/[^'"]*)?['"]/m.exec(source);
180
- if (!react || /\bfrom\s+['"]octane(?:\/[^'"]*)?['"]/.test(source)) continue;
181
- results.push({
182
- file: path.relative(root, file),
183
- output: path.relative(root, file),
184
- changed: false,
185
- rules: {},
186
- notes: [
187
- {
188
- rule: 'tsrx-react',
189
- severity: 'error',
190
- line: source.slice(0, react.index).split('\n').length,
191
- message:
192
- 'This is TSRX written for React (`@tsrx/react`), which the codemod cannot read. Port it by hand: its templates are already TSRX, but its React imports and APIs need the changes the codemod makes to TSX.',
193
- },
194
- ],
195
- strong: null,
196
- strongFixes: [],
197
- diagnostics: [],
198
- code: source,
199
- });
200
- }
201
-
202
- const html = rewriteEntryPages(
203
- root,
204
- paths.map((entry) => path.resolve(entry)),
205
- renames,
206
- options.write !== false,
207
- );
208
- const dependencies = addBindings(root, packages, options.write !== false);
209
- if (options.write !== false) {
210
- for (const result of results) {
211
- if (!result.changed) continue;
212
- const output = path.join(root, result.output);
213
- fs.writeFileSync(output, result.code);
214
- if (result.output !== result.file) fs.rmSync(path.join(root, result.file));
215
- }
216
- }
217
- return {
218
- root,
219
- files: results,
220
- packages: [...packages].map(([from, to]) => ({ from, to })),
221
- dependencies,
222
- patched: patchedPackages(root, packages),
223
- missing: [...missing.values()].sort((a, b) => a.name.localeCompare(b.name)),
224
- html,
225
- compiler: compiler?.from ?? null,
226
- };
227
- }
228
-
229
- /**
230
- * Whether Octane compiles this module: `.tsrx`, JSX, or a module that imports
231
- * the runtime. A declaration file is only types.
232
- *
233
- * @param {string} file
234
- * @param {string} code
235
- */
236
- function isCompiled(file, code) {
237
- if (file.endsWith('.d.ts')) return false;
238
- return /\.(?:tsrx|[jt]sx)$/.test(file) || /from\s+['"]octane['"]/.test(code);
239
- }
240
-
241
- /**
242
- * @param {import('./compiler.js').Compiler} compiler
243
- * @param {string} code
244
- * @param {string} file
245
- * @param {boolean} strong
246
- */
247
- function compile(compiler, code, file, strong) {
248
- try {
249
- const result = compiler.collectDiagnostics(code, file, strong ? { strong: true } : {});
250
- const found = result.diagnostics.filter((d) => d.severity !== 'hint').map(finding);
251
- return result.error == null ? found : [...found, thrown(result.error)];
252
- } catch (error) {
253
- return [thrown(error)];
254
- }
255
- }
256
-
257
- /** @param {FileResult['diagnostics']} diagnostics */
258
- function dedupe(diagnostics) {
259
- const seen = new Set();
260
- return diagnostics.filter((d) => {
261
- const key = `${d.code}:${d.line}:${d.message}`;
262
- if (seen.has(key)) return false;
263
- seen.add(key);
264
- return true;
265
- });
266
- }
267
-
268
- /**
269
- * The modules under `entry` that pass `test`: by default, those the codemod
270
- * migrates.
271
- *
272
- * @param {string} entry
273
- * @param {(name: string) => boolean} [test]
274
- */
275
- function collect(entry, test = isSource) {
276
- if (fs.statSync(entry).isFile()) return test(entry) ? [entry] : [];
277
- return scanSourceFiles(entry, { limit: Infinity }).filter(test).sort();
278
- }
279
-
280
- /** @param {string} name */
281
- function isTsrx(name) {
282
- return name.endsWith('.tsrx');
283
- }
284
-
285
- /**
286
- * The compiler options of the tsconfig that governs `root`, or null.
287
- *
288
- * @param {string} root
289
- * @returns {ts.CompilerOptions | null}
290
- */
291
- function tsconfigOptions(root) {
292
- const file = ts.findConfigFile(root, ts.sys.fileExists);
293
- if (!file) return null;
294
- const { config } = ts.readConfigFile(file, ts.sys.readFile);
295
- return ts.parseJsonConfigFileContent(config ?? {}, ts.sys, path.dirname(file)).options;
296
- }
297
-
298
- /**
299
- * A program over the TypeScript modules being migrated, under the project's
300
- * tsconfig, so their types resolve through imports. Null unless that config
301
- * enables `strictNullChecks`: without it a `string` may still hold null, so
302
- * types cannot prove a hole is text.
303
- *
304
- * @param {ts.CompilerOptions | null} options
305
- * @param {string[]} files
306
- */
307
- function projectProgram(options, files) {
308
- if (!options || !(options.strictNullChecks ?? options.strict)) return null;
309
- return ts.createProgram(
310
- files.filter((name) => /\.[cm]?tsx?$/.test(name)),
311
- // As the compiler's typed-text proof requires.
312
- { ...options, noEmit: true, noUncheckedIndexedAccess: true },
313
- );
314
- }
315
-
316
- /**
317
- * Bundler and tool configs belong to `octane init`, not the codemod.
318
- *
319
- * @param {string} name
320
- */
321
- function isSource(name) {
322
- return SOURCE.test(name) && !/\.config\.[cm]?[jt]s$/.test(name);
323
- }
324
-
325
- /**
326
- * The project module a relative specifier names, trying the extensions and
327
- * directory indexes a bundler would.
328
- *
329
- * @param {string} from
330
- * @param {string} specifier
331
- * @param {Set<string>} files
332
- * @returns {{ file: string, index: boolean } | null}
333
- */
334
- function resolveModule(from, specifier, files) {
335
- if (!specifier.startsWith('.')) return null;
336
- const base = path.resolve(path.dirname(from), specifier);
337
- const stem = base.replace(/\.(?:[cm]?[jt]sx?)$/, '');
338
- for (const file of [base, ...['.tsx', '.ts', '.jsx', '.js'].map((ext) => stem + ext)]) {
339
- if (files.has(file)) return { file, index: false };
340
- }
341
- for (const ext of ['.tsx', '.ts', '.jsx', '.js']) {
342
- const file = path.join(base, 'index' + ext);
343
- if (files.has(file)) return { file, index: true };
344
- }
345
- return null;
346
- }
347
-
348
- /**
349
- * The new specifier for a relative import of a renamed module. `.tsrx` modules
350
- * are imported by their full name.
351
- *
352
- * @param {string} from
353
- * @param {string} specifier
354
- * @param {Set<string>} files
355
- * @param {Map<string, string>} renames
356
- */
357
- function resolveRelative(from, specifier, files, renames) {
358
- const target = resolveModule(from, specifier, files);
359
- if (!target || !renames.has(target.file)) return null;
360
- if (target.index) return specifier.replace(/\/?$/, '/index.tsrx');
361
- return specifier.replace(/\.(?:[cm]?[jt]sx?)$/, '') + '.tsrx';
362
- }
363
-
364
- /**
365
- * The new specifier for an import of a renamed module through a tsconfig
366
- * `paths` alias (`~/components/Card`), resolved as TypeScript resolves it.
367
- *
368
- * @param {string} from
369
- * @param {string} specifier
370
- * @param {Map<string, string>} renames
371
- * @param {ts.CompilerOptions | null} options
372
- */
373
- function resolveAlias(from, specifier, renames, options) {
374
- if (!options?.paths || specifier.startsWith('.')) return null;
375
- const file = ts.resolveModuleName(specifier, from, { ...options, preserveSymlinks: true }, ts.sys)
376
- .resolvedModule?.resolvedFileName;
377
- if (!file || !renames.has(file)) return null;
378
- if (SOURCE.test(specifier)) return specifier.replace(SOURCE, '.tsrx');
379
- return path.basename(file).startsWith('index.') && !/(?:^|\/)index$/.test(specifier)
380
- ? `${specifier}/index.tsrx`
381
- : `${specifier}.tsrx`;
382
- }
383
-
384
- /**
385
- * Which names each module exports as a context, following `export … from`.
386
- *
387
- * @param {Map<string, import('./transform.js').ModuleExports>} exports
388
- * @param {Set<string>} files
389
- * @returns {(file: string) => Set<string>}
390
- */
391
- function contextIndex(exports, files) {
392
- /** @type {Map<string, Set<string>>} */
393
- const resolved = new Map();
394
- const contextsOf = (/** @type {string} */ file) => {
395
- let names = resolved.get(file);
396
- if (names) return names;
397
- names = new Set(exports.get(file)?.contexts);
398
- // Set before following re-exports, so a cycle ends.
399
- resolved.set(file, names);
400
- for (const { specifier, names: pairs } of exports.get(file)?.reexports ?? []) {
401
- const target = resolveModule(file, specifier, files);
402
- if (!target) continue;
403
- const theirs = contextsOf(target.file);
404
- if (pairs === null) for (const name of theirs) names.add(name);
405
- else for (const [imported, exported] of pairs) if (theirs.has(imported)) names.add(exported);
406
- }
407
- return names;
408
- };
409
- return contextsOf;
410
- }
411
-
412
- /**
413
- * The binding that replaces a React package import, recorded so the report
414
- * can list the dependency changes.
415
- *
416
- * @param {string} specifier
417
- * @param {Map<string, string>} packages
418
- * @param {Note[]} notes
419
- */
420
- function resolveBinding(specifier, packages, notes) {
421
- const name = catalogName(specifier);
422
- if (name === null) return null;
423
- const binding = CATALOG[name];
424
- packages.set(name, binding);
425
- const entry = DATA.bindings.find((candidate) => candidate.name === binding);
426
- // An aggregate binding (`@octanejs/visx`, for `@visx/visx`) serves each
427
- // package of its scope from a subpath: `@visx/hierarchy` is
428
- // `@octanejs/visx/hierarchy`.
429
- const upstream = entry?.upstream?.package;
430
- const aggregate = upstream?.match(/^@([^/]+)\/\1$/);
431
- if (aggregate && name !== upstream && name.startsWith(`@${aggregate[1]}/`)) {
432
- return `${binding}/${name.slice(aggregate[1].length + 2)}${specifier.slice(name.length)}`;
433
- }
434
- const subpath = specifier.slice(name.length);
435
- if (subpath === '' || entry?.exports.some((key) => serves(key, `.${subpath}`))) {
436
- return binding + subpath;
437
- }
438
- // A binding outside the catalog has exports the codemod cannot see.
439
- notes.push(
440
- entry
441
- ? {
442
- rule: 'bindings',
443
- severity: 'error',
444
- line: 1,
445
- message: `\`${binding}\` has no \`.${subpath}\` export. Import these names from its root if it exports them there.`,
446
- }
447
- : {
448
- rule: 'bindings',
449
- severity: 'warning',
450
- line: 1,
451
- message: `Check that \`${binding}${subpath}\` exists; the binding may export it from its root.`,
452
- },
453
- );
454
- return binding + subpath;
455
- }
456
-
457
- /**
458
- * Whether a package `exports` key serves a subpath, directly or through a
459
- * `*` pattern such as `./locale/*`.
460
- *
461
- * @param {string} key
462
- * @param {string} subpath
463
- */
464
- function serves(key, subpath) {
465
- const [head, tail] = key.split('*');
466
- return tail === undefined ? key === subpath : subpath.startsWith(head) && subpath.endsWith(tail);
467
- }
468
-
469
- /**
470
- * The catalog entry for a package specifier, or null. The catalog keys some
471
- * bindings by subpath (`better-auth/react`), so the longest matching prefix
472
- * wins.
473
- *
474
- * @param {string} specifier
475
- */
476
- function catalogName(specifier) {
477
- if (specifier.startsWith('.') || specifier.startsWith('/')) return null;
478
- const parts = specifier.split('/');
479
- for (let length = parts.length; length > 0; length--) {
480
- const candidate = parts.slice(0, length).join('/');
481
- if (candidate in CATALOG) return candidate;
482
- }
483
- return null;
484
- }
485
-
486
- /**
487
- * The React package a specifier names when Octane has no binding for it, or
488
- * null.
489
- *
490
- * @param {string} specifier
491
- * @param {string} from the importing module
492
- */
493
- function unportedName(specifier, from) {
494
- if (specifier.startsWith('.') || specifier.startsWith('/') || catalogName(specifier) !== null)
495
- return null;
496
- const root = packageName(specifier);
497
- // Any package's `/react` entry renders with React (`@tanstack/markdown/react`).
498
- if (/\/react(?:\/|$)/.test(specifier.slice(root.length))) return specifier;
499
- return rendersWithReact(root, from) ? root : null;
500
- }
501
-
502
- /**
503
- * The package a bare specifier imports from: `@pierre/diffs` for
504
- * `@pierre/diffs/react`.
505
- *
506
- * @param {string} specifier
507
- */
508
- function packageName(specifier) {
509
- return specifier
510
- .split('/')
511
- .slice(0, specifier.startsWith('@') ? 2 : 1)
512
- .join('/');
513
- }
514
-
515
- /**
516
- * Add the bindings the migrated code imports to the project's package.json,
517
- * each at its catalog version and in the field that lists the React package it
518
- * replaces. TanStack publishes its Octane adapters outside the catalog, so
519
- * those take `latest`.
520
- *
521
- * @param {string} root
522
- * @param {Map<string, string>} packages
523
- * @param {boolean} write
524
- * @returns {CodemodResult['dependencies']}
525
- */
526
- function addBindings(root, packages, write) {
527
- const file = path.join(root, 'package.json');
528
- if (!fs.existsSync(file)) return [];
529
- const text = fs.readFileSync(file, 'utf8');
530
- const manifest = JSON.parse(text);
531
- const fields = ['dependencies', 'devDependencies', 'peerDependencies'];
532
- /** @type {CodemodResult['dependencies']} */
533
- const added = [];
534
- for (const [from, to] of packages) {
535
- if (fields.some((field) => manifest[field]?.[to] !== undefined)) continue;
536
- const version = DATA.bindings.find((binding) => binding.name === to)?.version;
537
- const range = version ? `^${version}` : 'latest';
538
- const field = manifest.devDependencies?.[packageName(from)]
539
- ? 'devDependencies'
540
- : 'dependencies';
541
- manifest[field] = Object.fromEntries(
542
- Object.entries({ ...manifest[field], [to]: range }).sort(([a], [b]) => a.localeCompare(b)),
543
- );
544
- added.push({ name: to, range });
545
- }
546
- if (write && added.length > 0) {
547
- const indent = /^[ \t]+/m.exec(text)?.[0] ?? ' ';
548
- fs.writeFileSync(file, JSON.stringify(manifest, null, indent) + '\n');
549
- }
550
- return added;
551
- }
552
-
553
- /**
554
- * The patches a project applies to the React packages the migration replaces,
555
- * which stop applying once the code imports the binding instead: pnpm's and
556
- * Bun's `patchedDependencies`, in package.json or pnpm-workspace.yaml, and
557
- * patch-package's `patches/name+version.patch`. They live where the project
558
- * installs, so each directory up from `root` is read until a lockfile.
559
- *
560
- * @param {string} root
561
- * @param {Map<string, string>} packages
562
- * @returns {CodemodResult['patched']}
563
- */
564
- function patchedPackages(root, packages) {
565
- const replaced = new Set([...packages.keys()].map(packageName));
566
- /** @type {CodemodResult['patched']} */
567
- const patched = [];
568
- for (let dir = root; ; dir = path.dirname(dir)) {
569
- const read = (/** @type {string} */ name) => {
570
- const file = path.join(dir, name);
571
- return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
572
- };
573
- const manifest = JSON.parse(read('package.json') ?? '{}');
574
- /** @type {[string, string][]} `name@version` and its patch */
575
- const declared = Object.entries({
576
- ...manifest.pnpm?.patchedDependencies,
577
- ...manifest.patchedDependencies,
578
- });
579
- const workspace =
580
- /^patchedDependencies:[ \t]*\r?\n((?:[ \t]+.*\r?\n?)*)/m.exec(
581
- read('pnpm-workspace.yaml') ?? '',
582
- )?.[1] ?? '';
583
- for (const [, , key, , patch] of workspace.matchAll(
584
- /^[ \t]+(["']?)(.+?)\1:[ \t]*(["']?)(.+?)\3[ \t]*$/gm,
585
- )) {
586
- declared.push([key, patch]);
587
- }
588
- const patches = path.join(dir, 'patches');
589
- for (const name of fs.existsSync(patches) ? fs.readdirSync(patches) : []) {
590
- const match = /^((?:@[^+]+\+)?[^+]+)\+[^+]+\.patch$/.exec(name);
591
- if (match) declared.push([match[1].replace('+', '/'), `patches/${name}`]);
592
- }
593
- for (const [key, patch] of declared) {
594
- const name = key.replace(/(?!^)@[^@]*$/, '');
595
- if (replaced.has(name))
596
- patched.push({ name, patch: path.relative(root, path.join(dir, patch)) });
597
- }
598
- const installed = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb'];
599
- if (installed.some((name) => fs.existsSync(path.join(dir, name))) || path.dirname(dir) === dir)
600
- return patched;
601
- }
602
- }
603
-
604
- /**
605
- * Whether a package renders through React: it declares `react` as a peer or
606
- * dependency when installed, or its name says so when it is not. A package
607
- * with a `./react` entry (`@pierre/trees/react`) renders through React there,
608
- * which the caller matches by subpath; its other entries need no binding. An
609
- * optional peer alone does not say which entries use React.
610
- *
611
- * @param {string} name
612
- * @param {string} from
613
- */
614
- function rendersWithReact(name, from) {
615
- if (name === 'octane' || name.startsWith('@octanejs/') || name.startsWith('node:')) return false;
616
- const manifest = readInstalled(path.dirname(from), name)?.manifest;
617
- if (!manifest) return REACT_PACKAGE.test(name);
618
- if (manifest.exports?.['./react']) return false;
619
- return ['peerDependencies', 'dependencies'].some((field) => manifest[field]?.react !== undefined);
620
- }
621
-
622
- /**
623
- * Point `<script src>` in HTML entry pages at renamed modules.
624
- *
625
- * @param {string} root
626
- * @param {string[]} targets the paths being migrated
627
- * @param {Map<string, string>} renames
628
- * @param {boolean} write
629
- */
630
- function rewriteEntryPages(root, targets, renames, write) {
631
- /** @type {string[]} */
632
- const updated = [];
633
- for (const page of findHtml(root, targets)) {
634
- const html = fs.readFileSync(page, 'utf8');
635
- const next = html.replace(
636
- /(<script\b[^>]*\bsrc=)(["'])([^"']+)\2/g,
637
- (match, open, quote, src) => {
638
- // Vite serves `/` from the page's own directory, as it does `./`.
639
- const file = path.join(path.dirname(page), src);
640
- const renamed = renames.get(file);
641
- if (!renamed) return match;
642
- return open + quote + src.replace(/\.[jt]sx?$/, '.tsrx') + quote;
643
- },
644
- );
645
- if (next !== html) {
646
- updated.push(path.relative(root, page));
647
- if (write) fs.writeFileSync(page, next);
648
- }
649
- }
650
- return updated;
651
- }
652
-
653
- /**
654
- * The HTML pages a Vite or CRA app keeps beside its sources: those in the
655
- * root, `public/`, `src/`, and each migrated directory.
656
- *
657
- * @param {string} root
658
- * @param {string[]} targets
659
- */
660
- function findHtml(root, targets) {
661
- const dirs = new Set([root, path.join(root, 'public'), path.join(root, 'src'), ...targets]);
662
- return [...dirs]
663
- .filter((dir) => fs.existsSync(dir) && fs.statSync(dir).isDirectory())
664
- .flatMap((dir) =>
665
- fs
666
- .readdirSync(dir)
667
- .filter((name) => name.endsWith('.html'))
668
- .map((name) => path.join(dir, name)),
669
- );
670
- }