@octanejs/codemod 0.1.4 → 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 +295 -4
  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 +18 -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 -738
  57. package/src/strong.js +0 -149
  58. package/src/transform.js +0 -3455
@@ -0,0 +1,391 @@
1
+ import fs from 'node:fs';
2
+ import { createRequire, isBuiltin } from 'node:module';
3
+ import path from 'node:path';
4
+ import ts from 'typescript';
5
+ import { skipWrappers } from './expression-wrappers.js';
6
+ import { hasLocalMemberWrite } from './local-uses.js';
7
+ import { bind } from './transform.js';
8
+ import { hasRuntimeDependency } from './scoped-store-contract.js';
9
+ const sourceExtensions = ['.ts', '.tsx', '.js', '.jsx', '.mts', '.mjs', '.cts', '.cjs'];
10
+ const resourceHints = new Set([
11
+ 'default',
12
+ 'preconnect',
13
+ 'prefetchDNS',
14
+ 'preinit',
15
+ 'preinitModule',
16
+ 'preload',
17
+ 'preloadModule',
18
+ ]);
19
+ function importsResourceHint(statement) {
20
+ const imported = ts.isImportDeclaration(statement);
21
+ if (imported && !statement.importClause)
22
+ return false;
23
+ const bindings = imported ? statement.importClause?.namedBindings : statement.exportClause;
24
+ if ((imported && statement.importClause?.name) || !bindings)
25
+ return true;
26
+ if (!ts.isNamedImports(bindings) && !ts.isNamedExports(bindings))
27
+ return true;
28
+ return bindings.elements.some((item) => !item.isTypeOnly && resourceHints.has((item.propertyName ?? item.name).text));
29
+ }
30
+ function dataInput(expr, locals) {
31
+ const value = skipWrappers(expr);
32
+ if (ts.isIdentifier(value)) {
33
+ const input = locals.get(value.text);
34
+ return !!input && 'literal' in input;
35
+ }
36
+ if (ts.isArrayLiteralExpression(value))
37
+ return value.elements.every((element) => dataInput(element, locals));
38
+ if (ts.isObjectLiteralExpression(value))
39
+ return value.properties.every((field) => ts.isPropertyAssignment(field) &&
40
+ (ts.isIdentifier(field.name) ||
41
+ ts.isStringLiteral(field.name) ||
42
+ ts.isNumericLiteral(field.name)) &&
43
+ field.name.text !== '__proto__' &&
44
+ dataInput(field.initializer, locals));
45
+ return inertLiteral(value);
46
+ }
47
+ function inertLiteral(value) {
48
+ if (ts.isPrefixUnaryExpression(value))
49
+ return ((value.operator === ts.SyntaxKind.PlusToken || value.operator === ts.SyntaxKind.MinusToken) &&
50
+ (ts.isNumericLiteral(value.operand) || ts.isBigIntLiteral(value.operand)));
51
+ return (ts.isStringLiteralLike(value) ||
52
+ ts.isNumericLiteral(value) ||
53
+ ts.isBigIntLiteral(value) ||
54
+ value.kind === ts.SyntaxKind.TrueKeyword ||
55
+ value.kind === ts.SyntaxKind.FalseKeyword ||
56
+ value.kind === ts.SyntaxKind.NullKeyword);
57
+ }
58
+ /** Resolve application source used by a workspace store consumer. */
59
+ export function storeSources(root, config, unchanged) {
60
+ const options = { moduleResolution: ts.ModuleResolutionKind.Bundler, ...config };
61
+ const cache = ts.createModuleResolutionCache(root, (file) => file, options);
62
+ const modules = new Map();
63
+ const project = fs.realpathSync(root);
64
+ function inputs(file) {
65
+ const saved = modules.get(file);
66
+ if (saved)
67
+ return saved;
68
+ const exported = new Map();
69
+ const locals = new Map();
70
+ const localFunctions = new Set();
71
+ const { sf, checker } = bind(file, fs.readFileSync(file, 'utf8'));
72
+ for (const s of sf.statements) {
73
+ if (ts.isFunctionDeclaration(s) && s.name && s.body)
74
+ localFunctions.add(s.name.text);
75
+ if (!ts.isImportDeclaration(s) ||
76
+ !ts.isStringLiteral(s.moduleSpecifier) ||
77
+ s.attributes ||
78
+ s.importClause?.isTypeOnly)
79
+ continue;
80
+ const named = s.importClause?.namedBindings;
81
+ if (named && ts.isNamedImports(named))
82
+ for (const item of named.elements) {
83
+ if (!item.isTypeOnly)
84
+ locals.set(item.name.text, {
85
+ reexport: {
86
+ module: s.moduleSpecifier.text,
87
+ name: (item.propertyName ?? item.name).text,
88
+ from: file,
89
+ },
90
+ });
91
+ }
92
+ }
93
+ for (const s of sf.statements) {
94
+ if (!ts.isVariableStatement(s) ||
95
+ (s.declarationList.flags & ts.NodeFlags.BlockScoped) !== ts.NodeFlags.Const)
96
+ continue;
97
+ for (const d of s.declarationList.declarations) {
98
+ if (!ts.isIdentifier(d.name) || !d.initializer)
99
+ continue;
100
+ const call = skipWrappers(d.initializer);
101
+ const alias = ts.isIdentifier(call) && locals.get(call.text);
102
+ let input;
103
+ if (alias) {
104
+ if ('reexport' in alias)
105
+ input = { ...alias, opaqueOnly: true };
106
+ else if ('factory' in alias && call !== d.initializer)
107
+ input = { ...alias, direct: false };
108
+ else
109
+ input = alias;
110
+ }
111
+ else if (ts.isCallExpression(call)) {
112
+ let target = skipWrappers(call.expression);
113
+ while (ts.isExpressionWithTypeArguments(target))
114
+ target = skipWrappers(target.expression);
115
+ if (!ts.isIdentifier(target))
116
+ continue;
117
+ const callee = locals.get(target.text);
118
+ if (callee && 'reexport' in callee) {
119
+ // A type assertion cannot make a modified handle portable.
120
+ if (hasLocalMemberWrite(d.name, checker))
121
+ input = { opaque: true };
122
+ else
123
+ input = {
124
+ factory: callee.reexport,
125
+ direct: !callee.opaqueOnly && call === d.initializer && target === call.expression,
126
+ data: call.arguments.every((arg) => dataInput(arg, locals)),
127
+ };
128
+ }
129
+ else if (localFunctions.has(target.text))
130
+ input = { opaque: true };
131
+ }
132
+ else if (inertLiteral(call))
133
+ input = { literal: true };
134
+ if (!input)
135
+ continue;
136
+ locals.set(d.name.text, input);
137
+ if (s.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword))
138
+ exported.set(d.name.text, input);
139
+ }
140
+ }
141
+ for (const s of sf.statements) {
142
+ if (!ts.isExportDeclaration(s) ||
143
+ s.isTypeOnly ||
144
+ !s.exportClause ||
145
+ !ts.isNamedExports(s.exportClause))
146
+ continue;
147
+ for (const item of s.exportClause.elements) {
148
+ if (item.isTypeOnly)
149
+ continue;
150
+ if (s.attributes) {
151
+ // Attributes can select a different implementation at runtime.
152
+ exported.set(item.name.text, { opaque: true });
153
+ continue;
154
+ }
155
+ const name = (item.propertyName ?? item.name).text;
156
+ const input = s.moduleSpecifier
157
+ ? ts.isStringLiteral(s.moduleSpecifier)
158
+ ? { reexport: { module: s.moduleSpecifier.text, name, from: file } }
159
+ : undefined
160
+ : locals.get(name);
161
+ if (input)
162
+ exported.set(item.name.text, input);
163
+ }
164
+ }
165
+ modules.set(file, exported);
166
+ return exported;
167
+ }
168
+ function typedFile(from, specifier) {
169
+ return ts.resolveModuleName(specifier, from, options, ts.sys, cache).resolvedModule
170
+ ?.resolvedFileName;
171
+ }
172
+ function inProject(file, directory) {
173
+ return (file.startsWith(directory + path.sep) && !file.includes(path.sep + 'node_modules' + path.sep));
174
+ }
175
+ function runtimeFile(from, specifier) {
176
+ try {
177
+ return createRequire(from).resolve(specifier);
178
+ }
179
+ catch {
180
+ // A tsconfig alias or an authored TS file need not resolve through Node.
181
+ return undefined;
182
+ }
183
+ }
184
+ function localFile(from, specifier) {
185
+ const file = typedFile(from, specifier);
186
+ if (!file || !/(?<!\.d)\.ts$/.test(file) || !inProject(file, root))
187
+ return null;
188
+ const physical = fs.realpathSync(file);
189
+ if (!inProject(physical, project))
190
+ return null;
191
+ // A JS sibling or directory can implement a different export even for a tsconfig alias.
192
+ if (!specifier.endsWith('.ts')) {
193
+ const stem = file.slice(0, -3);
194
+ if (['.js', '.jsx', '.tsx', '.mjs', '.cjs', '.mts', '.cts', ''].some((ext) => fs.existsSync(stem + ext)))
195
+ return null;
196
+ }
197
+ const runtime = runtimeFile(from, specifier);
198
+ if (runtime && (!path.isAbsolute(runtime) || fs.realpathSync(runtime) !== physical))
199
+ return null;
200
+ return file;
201
+ }
202
+ // Renderer evidence can come from any plausible executable source. It never proves factory identity.
203
+ function executableFiles(from, specifier) {
204
+ const typed = typedFile(from, specifier);
205
+ const candidates = new Set();
206
+ if (typed && inProject(typed, root)) {
207
+ candidates.add(typed);
208
+ // TypeScript can substitute authored types for an explicit JS path.
209
+ const stem = typed.replace(/(?:\.d)?\.(?:[cm]?[jt]s|[jt]sx)$/, '');
210
+ if (stem !== typed) {
211
+ const extension = path.extname(specifier);
212
+ const siblings = sourceExtensions.includes(extension) ? [extension] : sourceExtensions;
213
+ for (const suffix of siblings)
214
+ candidates.add(stem + suffix);
215
+ }
216
+ }
217
+ if (candidates.size || specifier.startsWith('.')) {
218
+ const runtime = runtimeFile(from, specifier);
219
+ if (runtime) {
220
+ // Node resolves symlinks before returning the runtime path.
221
+ const file = root !== project && inProject(runtime, project)
222
+ ? path.join(root, path.relative(project, runtime))
223
+ : runtime;
224
+ candidates.add(file);
225
+ }
226
+ }
227
+ return [...candidates].filter((file) => sourceExtensions.includes(path.extname(file)) &&
228
+ !/\.d\.[cm]?ts$/.test(file) &&
229
+ inProject(file, root) &&
230
+ fs.statSync(file, { throwIfNoEntry: false })?.isFile() &&
231
+ inProject(fs.realpathSync(file), project));
232
+ }
233
+ const resourceFiles = new Map();
234
+ function reachesResourceHint(file) {
235
+ const known = resourceFiles.get(file);
236
+ if (known !== undefined)
237
+ return known;
238
+ const pending = [file];
239
+ const seen = new Set();
240
+ while (pending.length) {
241
+ const current = pending.pop();
242
+ const cached = resourceFiles.get(current);
243
+ if (cached === false || seen.has(current))
244
+ continue;
245
+ if (cached === true) {
246
+ resourceFiles.set(file, true);
247
+ return true;
248
+ }
249
+ seen.add(current);
250
+ const source = ts.createSourceFile(current, fs.readFileSync(current, 'utf8'), ts.ScriptTarget.Latest);
251
+ for (const statement of source.statements) {
252
+ if ((!ts.isImportDeclaration(statement) && !ts.isExportDeclaration(statement)) ||
253
+ !hasRuntimeDependency(statement) ||
254
+ !statement.moduleSpecifier ||
255
+ !ts.isStringLiteral(statement.moduleSpecifier))
256
+ continue;
257
+ const specifier = statement.moduleSpecifier.text;
258
+ if (specifier === 'react-dom' && importsResourceHint(statement)) {
259
+ resourceFiles.set(file, true);
260
+ return true;
261
+ }
262
+ pending.push(...executableFiles(current, specifier));
263
+ }
264
+ }
265
+ for (const current of seen)
266
+ resourceFiles.set(current, false);
267
+ return false;
268
+ }
269
+ // Follow named re-exports to a direct factory or an opaque local initializer.
270
+ function inputFactory(from, specifier, name, shared = () => false) {
271
+ let ref = { module: specifier, name, from };
272
+ let opaqueOnly = false;
273
+ const seen = new Set();
274
+ for (;;) {
275
+ const file = localFile(ref.from, ref.module);
276
+ if (!file)
277
+ return null;
278
+ const key = file + '\0' + ref.name;
279
+ if (seen.has(key))
280
+ return null;
281
+ seen.add(key);
282
+ const input = inputs(file).get(ref.name);
283
+ if (!input)
284
+ return null;
285
+ if ('factory' in input) {
286
+ const { factory } = input;
287
+ // A read can invoke an initializer callback after migration, under a different renderer.
288
+ if (!input.data &&
289
+ shared(factory.module, factory.name, factory.from) &&
290
+ reachesResourceHint(factory.from))
291
+ return { opaque: true };
292
+ return input.direct && !opaqueOnly ? factory : null;
293
+ }
294
+ if ('literal' in input)
295
+ return null;
296
+ if ('opaque' in input)
297
+ return input;
298
+ // A snapshot can propagate a rejection without establishing factory identity.
299
+ opaqueOnly ||= !!input.opaqueOnly;
300
+ ref = input.reexport;
301
+ }
302
+ }
303
+ // A byte-identical helper can still reach a module whose renderer changed.
304
+ function originalHelper(file) {
305
+ const pending = [file];
306
+ const seen = new Set();
307
+ let entry;
308
+ while (pending.length) {
309
+ const current = pending.pop();
310
+ if (seen.has(current))
311
+ continue;
312
+ seen.add(current);
313
+ // A linked path may be selected for a rewrite under its physical name.
314
+ if (fs.realpathSync(current) !== path.join(project, path.relative(root, current)) ||
315
+ fs.existsSync(current.slice(0, -3) + '.tsrx'))
316
+ return;
317
+ const source = fs.readFileSync(current, 'utf8');
318
+ if (!unchanged(current, source))
319
+ return;
320
+ const sf = ts.createSourceFile(current, source, ts.ScriptTarget.Latest);
321
+ entry ??= sf;
322
+ function unsafe(node) {
323
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
324
+ const spec = node.moduleSpecifier;
325
+ const typeOnly = ts.isImportDeclaration(node)
326
+ ? node.importClause?.isTypeOnly
327
+ : node.isTypeOnly;
328
+ if (!spec || typeOnly)
329
+ return false;
330
+ if (node.attributes || !ts.isStringLiteral(spec))
331
+ return true;
332
+ if (spec.text === 'node:module' || spec.text === 'module')
333
+ return true;
334
+ const local = localFile(current, spec.text);
335
+ if (local) {
336
+ pending.push(local);
337
+ return false;
338
+ }
339
+ const resolved = ts.resolveModuleName(spec.text, current, options, ts.sys, cache).resolvedModule;
340
+ if (!resolved)
341
+ return !isBuiltin(spec.text);
342
+ if (!resolved.isExternalLibraryImport)
343
+ return true;
344
+ const physical = fs.realpathSync(resolved.resolvedFileName);
345
+ return (physical.startsWith(project + path.sep) &&
346
+ !physical.includes(path.sep + 'node_modules' + path.sep));
347
+ }
348
+ if (ts.isImportEqualsDeclaration(node))
349
+ return !node.isTypeOnly;
350
+ if (ts.isExpressionWithTypeArguments(node))
351
+ return unsafe(node.expression);
352
+ if (ts.isTypeNode(node))
353
+ return false;
354
+ if (node.kind === ts.SyntaxKind.ImportKeyword ||
355
+ (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword) ||
356
+ (ts.isIdentifier(node) && (node.text === 'eval' || node.text === 'require')))
357
+ return true;
358
+ return !!ts.forEachChild(node, unsafe);
359
+ }
360
+ if (ts.forEachChild(sf, unsafe))
361
+ return;
362
+ }
363
+ return entry;
364
+ }
365
+ const helpers = new Map();
366
+ function helperFunction(from, specifier, name) {
367
+ if (/^use[A-Z0-9]/.test(name) || /[!%?#\\]/.test(specifier))
368
+ return false;
369
+ const file = localFile(from, specifier);
370
+ if (!file)
371
+ return false;
372
+ let exported = helpers.get(file);
373
+ if (!exported) {
374
+ exported = new Set();
375
+ helpers.set(file, exported);
376
+ const sf = originalHelper(file);
377
+ if (!sf)
378
+ return false;
379
+ for (const statement of sf.statements) {
380
+ if (ts.isFunctionDeclaration(statement) &&
381
+ statement.name &&
382
+ statement.body &&
383
+ statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) &&
384
+ !statement.modifiers.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword))
385
+ exported.add(statement.name.text);
386
+ }
387
+ }
388
+ return exported.has(name);
389
+ }
390
+ return { inputFactory, helperFunction, localFile };
391
+ }
@@ -0,0 +1,24 @@
1
+ import type { Compiler, StrongResult } from './types.js';
2
+ /**
3
+ * Compile a module the codemod emitted in Strong mode and repair what the
4
+ * compiler reports, until it compiles clean or nothing more can be fixed.
5
+ *
6
+ * The repairs are the compiler's own suggested edits, as `octane analyze --fix`
7
+ * applies them, plus the rewrites that keep React's behavior exactly:
8
+ *
9
+ * - an explicit dependency list the compiler reports as equivalent to the one
10
+ * it infers is dropped;
11
+ * - state initialized from a prop is captured lazily, `useState(() => prop)`,
12
+ * which is what `useState(prop)` meant in React.
13
+ *
14
+ * Strong errors that remain mean the module needs a person. With `force`
15
+ * unset the module falls back to compatibility mode so the migrated app still
16
+ * builds, and the errors are reported as the work left to make it Strong.
17
+ */
18
+ export declare function strengthen(compiler: Compiler, code: string, filename: string, { force, withEffectReceivers, withEffectProperties, withEffectSnapshots, withLinkedState, }?: {
19
+ force?: boolean;
20
+ withEffectReceivers?: () => string;
21
+ withEffectProperties?: () => string;
22
+ withEffectSnapshots?: () => string;
23
+ withLinkedState?: () => string;
24
+ }): StrongResult;
package/dist/strong.js ADDED
@@ -0,0 +1,142 @@
1
+ import { applyFixes, pruneImports } from '@octanejs/cli/fix';
2
+ import { finding, thrown } from './compiler.js';
3
+ /**
4
+ * The source without the directive the codemod added: its own line after any
5
+ * leading comments and `"use client"`, or, at the very top, that line and the
6
+ * blank line after it. `line` is where it stood and `lines` how many went.
7
+ */
8
+ function withoutDirective(code) {
9
+ const top = '"use strong";\n\n';
10
+ if (code.startsWith(top))
11
+ return { code: code.slice(top.length), line: 1, lines: 2 };
12
+ const match = /^"use strong";\n/m.exec(code);
13
+ if (!match)
14
+ return { code, line: 0, lines: 0 };
15
+ return {
16
+ code: code.slice(0, match.index) + code.slice(match.index + match[0].length),
17
+ line: code.slice(0, match.index).split('\n').length,
18
+ lines: 1,
19
+ };
20
+ }
21
+ const MAX_ROUNDS = 6;
22
+ /**
23
+ * Compile a module the codemod emitted in Strong mode and repair what the
24
+ * compiler reports, until it compiles clean or nothing more can be fixed.
25
+ *
26
+ * The repairs are the compiler's own suggested edits, as `octane analyze --fix`
27
+ * applies them, plus the rewrites that keep React's behavior exactly:
28
+ *
29
+ * - an explicit dependency list the compiler reports as equivalent to the one
30
+ * it infers is dropped;
31
+ * - state initialized from a prop is captured lazily, `useState(() => prop)`,
32
+ * which is what `useState(prop)` meant in React.
33
+ *
34
+ * Strong errors that remain mean the module needs a person. With `force`
35
+ * unset the module falls back to compatibility mode so the migrated app still
36
+ * builds, and the errors are reported as the work left to make it Strong.
37
+ */
38
+ export function strengthen(compiler, code, filename, { force = false, withEffectReceivers, withEffectProperties, withEffectSnapshots, withLinkedState, } = {}) {
39
+ const original = code;
40
+ const fixed = [];
41
+ let diagnostics = [];
42
+ for (let round = 0; round < MAX_ROUNDS; round++) {
43
+ const result = compiler.collectDiagnostics(code, filename, { strong: true });
44
+ if (result.error != null) {
45
+ // A module that compatibility mode cannot compile either has no
46
+ // Strong blocker to report; the compile failure is its own error.
47
+ const compat = compiler.collectDiagnostics(withoutDirective(code).code, filename, {});
48
+ return fallback(code, compat.error == null ? [thrown(result.error)] : [], fixed, force);
49
+ }
50
+ diagnostics = result.diagnostics;
51
+ const fixes = diagnostics.flatMap((diagnostic) => fixesFor(code, diagnostic));
52
+ if (fixes.length === 0)
53
+ break;
54
+ const { text, applied } = applyFixes(code, fixes);
55
+ if (applied.length === 0)
56
+ break;
57
+ code = pruneImports(text);
58
+ for (const fix of applied)
59
+ fixed.push(fix.code);
60
+ }
61
+ const blockers = diagnostics.filter((diagnostic) => diagnostic.severity === 'error').map(finding);
62
+ if (blockers.length === 0)
63
+ return { code, strong: true, fixed, blockers };
64
+ const retries = blockers.every((b) => b.code === 'OCTANE_STRONG_EXPLICIT_DEPENDENCIES')
65
+ ? [withEffectReceivers, withEffectProperties]
66
+ : withEffectSnapshots &&
67
+ blockers.every((b) => b.code === 'OCTANE_STRONG_EXPLICIT_DEPENDENCIES' ||
68
+ b.code === 'OCTANE_STRONG_READ_ONLY_STATE')
69
+ ? [withEffectSnapshots]
70
+ : withLinkedState && blockers.every((b) => b.code === 'OCTANE_STRONG_RENDER_STATE_UPDATE')
71
+ ? [withLinkedState]
72
+ : null;
73
+ if (retries) {
74
+ let previous = original;
75
+ for (const retry of retries) {
76
+ const candidate = retry?.();
77
+ if (!candidate || candidate === previous || candidate === original)
78
+ continue;
79
+ const checked = strengthen(compiler, candidate, filename);
80
+ if (checked.strong)
81
+ return checked;
82
+ previous = candidate;
83
+ }
84
+ }
85
+ return fallback(code, blockers, fixed, force);
86
+ }
87
+ function fallback(code, blockers, fixed, force) {
88
+ if (force)
89
+ return { code, strong: true, fixed, blockers };
90
+ // The module builds in compatibility mode; what kept it there is work
91
+ // left, not a failure. Its lines are the written file's, without the
92
+ // directive.
93
+ const compat = withoutDirective(code);
94
+ const kept = blockers.map((blocker) => ({
95
+ ...blocker,
96
+ severity: 'warning',
97
+ line: blocker.line > compat.line ? blocker.line - compat.lines : blocker.line,
98
+ }));
99
+ return { code: compat.code, strong: false, fixed, blockers: kept };
100
+ }
101
+ /** The edits that resolve one diagnostic, as `applyFixes` takes them. */
102
+ function fixesFor(code, diagnostic) {
103
+ const fixes = [];
104
+ for (const suggestion of diagnostic.suggestions ?? []) {
105
+ if ('edits' in suggestion && suggestion.edits?.length) {
106
+ fixes.push({ code: diagnostic.code, edits: [...suggestion.edits] });
107
+ break;
108
+ }
109
+ }
110
+ if (fixes.length > 0)
111
+ return fixes;
112
+ const start = diagnostic.start?.offset;
113
+ const end = diagnostic.end?.offset;
114
+ if (typeof start !== 'number' || typeof end !== 'number')
115
+ return fixes;
116
+ if (diagnostic.code === 'OCTANE_STRONG_EXPLICIT_DEPENDENCIES' && diagnostic.severity === 'hint') {
117
+ // `useEffect(fn, [a])` -> `useEffect(fn)`: the compiler infers `[a]`.
118
+ const comma = /,\s*$/.exec(code.slice(0, start));
119
+ if (comma && code[start] === '[') {
120
+ fixes.push({ code: diagnostic.code, edits: [{ start: comma.index, end, text: '' }] });
121
+ }
122
+ }
123
+ if (diagnostic.code === 'OCTANE_STRONG_UNLINKED_PROP_STATE') {
124
+ const before = /\S\s*$/.exec(code.slice(0, start))?.[0][0];
125
+ const value = code.slice(start, end);
126
+ if (before === '(') {
127
+ // useState(prop): React captured the value once, as a lazy
128
+ // initializer does.
129
+ const body = /^[\w$.]+$/.test(value) ? value : `(${value})`;
130
+ fixes.push({ code: diagnostic.code, edits: [{ start, end, text: `() => ${body}` }] });
131
+ }
132
+ else if (before === ',') {
133
+ // useReducer(reducer, prop): an explicit initializer is the
134
+ // deliberate capture.
135
+ fixes.push({
136
+ code: diagnostic.code,
137
+ edits: [{ start: end, end, text: ', (initial) => initial' }],
138
+ });
139
+ }
140
+ }
141
+ return fixes;
142
+ }
@@ -0,0 +1,27 @@
1
+ import ts from 'typescript';
2
+ import type { TransformOptions, TransformResult } from './types.js';
3
+ /**
4
+ * Rewrite one React module as Octane.
5
+ */
6
+ export declare function transformModule(source: string, filename: string, options?: TransformOptions): TransformResult;
7
+ export declare function projectTypeAt(node: ts.Node, types: TransformOptions['types']): {
8
+ type: ts.Type;
9
+ checker: ts.TypeChecker;
10
+ } | null;
11
+ /**
12
+ * Parse and bind one module on its own, with only the ES5 library and no
13
+ * module resolution. Binding is enough to map every name to the declaration it
14
+ * refers to, so a shadowed `useState` or event parameter is never mistaken for
15
+ * another; the library gives the module's own types their array and string
16
+ * members.
17
+ */
18
+ export declare function bind(filename: string, source: string): {
19
+ sf: ts.SourceFile;
20
+ checker: ts.TypeChecker;
21
+ };
22
+ /**
23
+ * What a type renders as: 1 when every member is a string, 2 when every
24
+ * member is a string, number, or bigint and one is not a string, else 0. The
25
+ * compiler's typed-text proof applies the same test.
26
+ */
27
+ export declare function textKind(type: ts.Type): 0 | 1 | 2;