@octanejs/codemod 0.2.2 → 0.2.3

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 CHANGED
@@ -100,6 +100,16 @@ whose local component returns an intrinsic element. Migrate the server entry
100
100
  with that component or keep the component in React. Review custom bundler
101
101
  resolution, indirect calls, and dynamic imports.
102
102
 
103
+ A retained React DOM client root also keeps ownership of its elements.
104
+ The codemod blocks writes when a direct `createRoot(...).render(...)`, a local
105
+ root handle, or `hydrateRoot(...)` renders a direct local TSX import that would
106
+ become an Octane template. It also covers a root stored in a JavaScript private
107
+ field when the constructor starts by assigning `createRoot(...)`, the field is
108
+ used only for direct `render` and `unmount` calls, and React's named
109
+ `createElement` creates the element. Migrate the root and component
110
+ together, keep the component in React, or give React an authored
111
+ `OctaneCompatInline` boundary.
112
+
103
113
  ### Element-only children
104
114
 
105
115
  A nested component call in a DOM template supplies a render block. When a
@@ -6,6 +6,7 @@ export declare function hasPrototypeAccess(file: ts.SourceFile): boolean;
6
6
  export declare function rendersElementChildren(element: ts.JsxOpeningLikeElement): boolean;
7
7
  export declare function renderUses(refs: ts.Identifier[]): ts.Identifier[];
8
8
  /** A local root handle stays owned while callers only invoke its two root methods. */
9
+ export declare function callsRootMethod(root: ts.Expression): boolean;
9
10
  export declare function rootHandleEscapes(refs: ts.Identifier[], inOwner?: (ref: ts.Identifier) => boolean): boolean;
10
11
  type RenderTypes = {
11
12
  typeOf: (node: ts.Node) => ts.Type;
@@ -94,16 +94,16 @@ export function renderUses(refs) {
94
94
  });
95
95
  }
96
96
  /** A local root handle stays owned while callers only invoke its two root methods. */
97
+ export function callsRootMethod(root) {
98
+ const member = root.parent;
99
+ return (ts.isPropertyAccessExpression(member) &&
100
+ member.expression === root &&
101
+ (member.name.text === 'render' || member.name.text === 'unmount') &&
102
+ ts.isCallExpression(member.parent) &&
103
+ member.parent.expression === member);
104
+ }
97
105
  export function rootHandleEscapes(refs, inOwner) {
98
- return renderUses(refs).some((ref) => {
99
- const member = ref.parent;
100
- return (!ts.isPropertyAccessExpression(member) ||
101
- member.expression !== ref ||
102
- (member.name.text !== 'render' && member.name.text !== 'unmount') ||
103
- !ts.isCallExpression(member.parent) ||
104
- member.parent.expression !== member ||
105
- inOwner?.(ref) === false);
106
- });
106
+ return renderUses(refs).some((ref) => !callsRootMethod(ref) || inOwner?.(ref) === false);
107
107
  }
108
108
  /** Follow the value being rendered all the way to its containing component's return. */
109
109
  export function nativeOutputOwner(value, slot, { typeOf, text }) {
@@ -12,7 +12,7 @@ export declare function nativeSetupHook(ref: ts.Expression, uses: ReturnType<typ
12
12
  originalReact(): boolean;
13
13
  contextSetup?: boolean;
14
14
  privateContext?: boolean;
15
- }, allowAnonymousDefault?: boolean): false | "diagnostic" | "first" | "afterRefs";
15
+ }, storeRoot?: boolean): false | "diagnostic" | "first" | "afterRefs";
16
16
  /** Find renderer calls at the start of an unchanged export's setup. */
17
17
  export declare function directRendererCalls(sf: ts.SourceFile, checker: ts.TypeChecker, module: 'react' | 'react-dom' | 'react-intl' | ((specifier: string, name: string) => boolean), accepts?: (name: string) => boolean, privateContextExports?: Set<string>): Map<string, string>;
18
18
  /** Clone a stateless hook while leaving its DOM reader and subscription shared. */
@@ -119,8 +119,8 @@ function conditionalOutput(value) {
119
119
  }
120
120
  /** A direct initialization in an ordinary component with native output. */
121
121
  export function nativeSetupHook(ref, uses, checker, diagnostic,
122
- // Store-root diagnostics can prove an anonymous declaration's default export.
123
- allowAnonymousDefault = false) {
122
+ // These shapes are used for store-root diagnostics, without adapting a hook.
123
+ storeRoot = false) {
124
124
  const call = ref.parent;
125
125
  if (!ts.isCallExpression(call) || call.expression !== ref)
126
126
  return false;
@@ -193,10 +193,12 @@ allowAnonymousDefault = false) {
193
193
  name = fn.name;
194
194
  }
195
195
  else {
196
- if (!diagnostic || (ts.isFunctionExpression(fn) && fn.name && renderUses(uses(fn.name)).length))
196
+ if ((!diagnostic && !storeRoot) ||
197
+ (ts.isFunctionExpression(fn) && fn.name && renderUses(uses(fn.name)).length))
197
198
  return false;
198
199
  let value = fn;
199
- while (ts.isCallExpression(value.parent) &&
200
+ while (diagnostic &&
201
+ ts.isCallExpression(value.parent) &&
200
202
  value.parent.arguments[0] === value &&
201
203
  /^(?:memo|forwardRef)$/.test(diagnostic.calleeName(value.parent.expression) ?? ''))
202
204
  value = value.parent;
@@ -213,8 +215,7 @@ allowAnonymousDefault = false) {
213
215
  }
214
216
  if ((name
215
217
  ? !/^[A-Z]/.test(name.text)
216
- : !allowAnonymousDefault ||
217
- !owner.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) ||
218
+ : !storeRoot || !owner.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) ||
218
219
  !ts.isSourceFile(owner.parent) ||
219
220
  !owner.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ||
220
221
  (name &&
package/dist/project.js CHANGED
@@ -16,7 +16,7 @@ import { strengthen } from './strong.js';
16
16
  import { bind, BUFFERED_SSR_OPTIONS, BUFFERED_SSR_REACT_COMPONENT, CONTEXT_ALIAS, CONTEXT_PROVIDER_GETTER, ELEMENT_CHILD_ALIAS, INTL_PROVIDER_DEFAULTS, MAP_CALLBACK_SCOPE, MAP_PARAMETER_TDZ, MAP_PARAMETER_WRITE, projectTypeAt, REACT_TYPE_PROJECTION, textKind, transformModule, } from './transform.js';
17
17
  import { directRendererCalls, namedRuntimeImport, nativeExternalStore, } from './local-react-hook.js';
18
18
  import { contains, forwardedProps } from './forwarded-props.js';
19
- import { importsReactBridge, islandComponents, executableImports, hostedComponents, directReactExports, migratedJsxFactories, octaneRootComponents, reactClassExports, reactServerComponents, retainedReactComponentReturns, retainedReactContextExports, retainedReactElementReturns, reverseIslandExports, } from './react-island-sources.js';
19
+ import { importsReactBridge, islandComponents, executableImports, hostedComponents, directReactExports, migratedJsxFactories, octaneRootComponents, reactClientComponents, reactClassExports, reactServerComponents, retainedReactComponentReturns, retainedReactContextExports, retainedReactElementReturns, reverseIslandExports, } from './react-island-sources.js';
20
20
  const SOURCE = /\.(?:[cm]?[jt]sx?)$/;
21
21
  const ADAPTER_OCTANE_VERSION = /^0\.(?:16\.(?:[7-9]|[1-9]\d+)|1[789]\.(?:0|[1-9]\d*))$/;
22
22
  // React Intl 7.1.14. Both entry points re-export a hook that calls React.useContext.
@@ -50,6 +50,8 @@ export async function runCodemod(paths, options = {}) {
50
50
  findRoot(fs.statSync(first, { throwIfNoEntry: false })?.isFile() ? path.dirname(first) : first));
51
51
  const known = new Set(paths.flatMap((entry) => collect(path.resolve(entry))));
52
52
  const files = [...known];
53
+ const config = tsconfigOptions(root);
54
+ const rootProject = ts.findConfigFile(root, ts.sys.fileExists);
53
55
  let selectedRealpaths;
54
56
  const renames = new Map();
55
57
  const exports = new Map();
@@ -103,7 +105,31 @@ export async function runCodemod(paths, options = {}) {
103
105
  });
104
106
  for (const file of files) {
105
107
  const source = fs.readFileSync(file, 'utf8');
106
- const result = transformModule(source, file, { target });
108
+ const result = transformModule(source, file, {
109
+ target,
110
+ mutableExports() {
111
+ const options = bindingOptions(file);
112
+ if (!options)
113
+ return false;
114
+ const kind = options.module;
115
+ if (kind === undefined) {
116
+ return (!options.noEmit &&
117
+ options.moduleResolution !== ts.ModuleResolutionKind.Bundler &&
118
+ (options.target ?? ts.ScriptTarget.ES5) < ts.ScriptTarget.ES2015);
119
+ }
120
+ if (kind === ts.ModuleKind.CommonJS ||
121
+ kind === ts.ModuleKind.AMD ||
122
+ kind === ts.ModuleKind.UMD)
123
+ return true;
124
+ if (kind !== ts.ModuleKind.Node16 &&
125
+ kind !== ts.ModuleKind.Node18 &&
126
+ kind !== ts.ModuleKind.Node20 &&
127
+ kind !== ts.ModuleKind.NodeNext)
128
+ return false;
129
+ return (ts.getImpliedNodeFormatForFile(file, undefined, ts.sys, options) ===
130
+ ts.ModuleKind.CommonJS);
131
+ },
132
+ });
107
133
  exports.set(file, result.exports);
108
134
  if (!result.template)
109
135
  continue;
@@ -150,7 +176,6 @@ export async function runCodemod(paths, options = {}) {
150
176
  // must not participate in the preview as if it had been migrated.
151
177
  for (const file of conflicts.keys())
152
178
  exports.delete(file);
153
- const config = tsconfigOptions(root);
154
179
  const strictConfig = (config?.strictNullChecks ?? config?.strict) ? config : null;
155
180
  let program;
156
181
  function typesOf(file) {
@@ -252,7 +277,6 @@ export async function runCodemod(paths, options = {}) {
252
277
  // `ReactCompat` hosts a component from a retained package import in a React
253
278
  // root, from 19.2 within the React 19 series it supports.
254
279
  const reactCompat = ['react', 'react-dom'].every((name) => /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(root, name)?.version ?? ''));
255
- const rootProject = ts.findConfigFile(root, ts.sys.fileExists);
256
280
  const reactExports = new Map();
257
281
  function originalReactExports(file) {
258
282
  let exports = reactExports.get(file);
@@ -312,6 +336,13 @@ export async function runCodemod(paths, options = {}) {
312
336
  fs.realpathSync(target.resolvedFileName).split(path.sep).includes('node_modules'));
313
337
  }
314
338
  let physicalRoot;
339
+ function isPlainFile(file) {
340
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
341
+ return (!!stat?.isFile() &&
342
+ stat.nlink === 1 &&
343
+ fs.realpathSync(file) ===
344
+ path.join((physicalRoot ??= fs.realpathSync(root)), path.relative(root, file)));
345
+ }
315
346
  const retainedStoreArguments = new Map();
316
347
  const descriptorModules = new Map();
317
348
  function retainedStoreArgument(file, source, name) {
@@ -894,6 +925,52 @@ export async function runCodemod(paths, options = {}) {
894
925
  checkedHelpers.set(output, { code, state, error });
895
926
  return error;
896
927
  }
928
+ function selectedContextReexport(file, name) {
929
+ const seen = new Set();
930
+ for (;;) {
931
+ const selected = exports.get(file);
932
+ if (!selected ||
933
+ seen.has(file) ||
934
+ !isPlainFile(file) ||
935
+ ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
936
+ return false;
937
+ const hasContext = selected.contexts.includes(name);
938
+ if (!hasContext && !selected.reexports.length)
939
+ return false;
940
+ // TypeScript's source lookup omits these competing bundler targets.
941
+ const stem = file.slice(0, -path.extname(file).length);
942
+ if (['.json', '.tsrx'].some((ext) => fs.lstatSync(stem + ext, { throwIfNoEntry: false })))
943
+ return false;
944
+ const source = fs.readFileSync(file, 'utf8');
945
+ if (hasContext)
946
+ return installedReact(file) && retainedReactContextExports(file, source).has(name);
947
+ seen.add(file);
948
+ const { statements } = ts.createSourceFile(file, source, ts.ScriptTarget.Latest);
949
+ const [statement] = statements;
950
+ // A pure named forwarding module has no competing value export.
951
+ if (statements.length !== 1 ||
952
+ !ts.isExportDeclaration(statement) ||
953
+ statement.isTypeOnly ||
954
+ statement.attributes ||
955
+ !statement.exportClause ||
956
+ !ts.isNamedExports(statement.exportClause) ||
957
+ !statement.moduleSpecifier ||
958
+ !ts.isStringLiteral(statement.moduleSpecifier))
959
+ return false;
960
+ const specifier = statement.moduleSpecifier.text;
961
+ if (!/^\.{1,2}\//.test(specifier) || /[!%?#\\]/.test(specifier))
962
+ return false;
963
+ const bindings = statement.exportClause.elements.filter((element) => !element.isTypeOnly && element.name.text === name);
964
+ if (bindings.length !== 1)
965
+ return false;
966
+ const next = localFile(file, specifier, true);
967
+ const direct = path.resolve(path.dirname(file), specifier);
968
+ if (!next || (next !== direct && next !== direct + path.extname(next)))
969
+ return false;
970
+ file = next;
971
+ name = (bindings[0].propertyName ?? bindings[0].name).text;
972
+ }
973
+ }
897
974
  const results = [];
898
975
  const storeHookComponents = new Map();
899
976
  if (options.svgPaths && target === 'tsrx') {
@@ -928,7 +1005,7 @@ export async function runCodemod(paths, options = {}) {
928
1005
  const reactStoreComponents = new Map();
929
1006
  let installedClsx;
930
1007
  let reactJsx;
931
- const isContext = (specifier, name, local) => {
1008
+ const isContext = (specifier, name, local, attributed) => {
932
1009
  if (!specifier.startsWith('.')) {
933
1010
  if (!contextPaths.length ||
934
1011
  !esmContextProject ||
@@ -938,11 +1015,13 @@ export async function runCodemod(paths, options = {}) {
938
1015
  : specifier.startsWith(start) && specifier.endsWith(end)))
939
1016
  return null;
940
1017
  const source = localFile(file, specifier, true);
1018
+ const selected = source && exports.get(source);
941
1019
  return source &&
942
- exports.has(source) &&
1020
+ selected &&
943
1021
  ts.findConfigFile(path.dirname(source), ts.sys.fileExists) === rootProject &&
944
- (exports.get(source)?.contexts.includes(name) ||
945
- (name === 'default' ? local : name).endsWith('Context'))
1022
+ (selected.contexts.includes(name) ||
1023
+ (name === 'default' ? local : name).endsWith('Context') ||
1024
+ (!attributed && selected.reexports.length > 0 && selectedContextReexport(source, name)))
946
1025
  ? 'review-alias'
947
1026
  : null;
948
1027
  }
@@ -1439,13 +1518,18 @@ export async function runCodemod(paths, options = {}) {
1439
1518
  const jsxFactories = new Map();
1440
1519
  const renamedJsx = [...renames.keys()].some((file) => file.endsWith('.tsx'));
1441
1520
  const namedReexports = new Map();
1442
- const isPlainFile = (file) => {
1443
- const stat = fs.lstatSync(file, { throwIfNoEntry: false });
1444
- return (!!stat?.isFile() &&
1445
- stat.nlink === 1 &&
1446
- fs.realpathSync(file) ===
1447
- path.join((physicalRoot ??= fs.realpathSync(root)), path.relative(root, file)));
1448
- };
1521
+ function canResolveExtensionlessJsx(specifier) {
1522
+ return (/^\.{1,2}\//.test(specifier) &&
1523
+ !/[!%?#\\]/.test(specifier) &&
1524
+ !/\.(?:[cm]?[jt]sx?|tsrx)$/.test(specifier) &&
1525
+ (config?.moduleResolution === undefined ||
1526
+ config.moduleResolution === ts.ModuleResolutionKind.Bundler) &&
1527
+ !config?.rootDirs &&
1528
+ !config?.moduleSuffixes?.some(Boolean));
1529
+ }
1530
+ function isExtensionlessJsxTarget(file, original) {
1531
+ return file.endsWith('.tsx') && unambiguousJsxPath(file, original) && isPlainFile(file);
1532
+ }
1449
1533
  function retainedJsxTarget(from, specifier, name) {
1450
1534
  if (!/^\.{1,2}\//.test(specifier) ||
1451
1535
  /[!%?#\\]/.test(specifier) ||
@@ -1679,6 +1763,47 @@ export async function runCodemod(paths, options = {}) {
1679
1763
  leaf.notes.push({ ...note, line: 1 });
1680
1764
  }
1681
1765
  }
1766
+ if (paths &&
1767
+ !edited.has(file) &&
1768
+ !isTsrx(file) &&
1769
+ (source.includes('react-dom/client') || source.includes('\\')) &&
1770
+ ts.findConfigFile(path.dirname(file), ts.sys.fileExists) === rootProject &&
1771
+ originalReactEntry(file, 'react-dom/client')) {
1772
+ for (const edge of reactClientComponents(file, source, (module) => module === 'react'
1773
+ ? originalReactEntry(file, module)
1774
+ : automaticReactJsx(file) && originalReactEntry(file, module))) {
1775
+ const explicit = edge.module.endsWith('.tsx');
1776
+ if (!explicit && !canResolveExtensionlessJsx(edge.module))
1777
+ continue;
1778
+ const original = path.resolve(path.dirname(file), edge.module);
1779
+ const match = explicit
1780
+ ? retainedJsxTarget(file, edge.module, edge.name)
1781
+ : renamed(file, edge.module);
1782
+ if (!match ||
1783
+ ('indirect' in match && match.indirect) ||
1784
+ (explicit ? match.file !== original : !isExtensionlessJsxTarget(match.file, original)) ||
1785
+ !automaticReactJsx(match.file) ||
1786
+ !originalReactEntry(match.file, 'react/jsx-runtime'))
1787
+ continue;
1788
+ const leaf = byFile.get(match.file);
1789
+ if (!leaf?.output.endsWith('.tsrx'))
1790
+ continue;
1791
+ const { intrinsics, wrappers } = originalReactExports(match.file);
1792
+ if ((!intrinsics.has(edge.name) && !wrappers.has(edge.name)) ||
1793
+ !hasTemplateExport(leaf, edge.name))
1794
+ continue;
1795
+ const note = {
1796
+ rule: 'react-compat',
1797
+ severity: 'error',
1798
+ line: edge.line,
1799
+ message: `The retained React DOM client root in ${name} renders ${leaf.file}. Migrate the root too or keep this component in React.`,
1800
+ };
1801
+ if (write)
1802
+ return blockedWrite(root, unchangedFile(name, source, note), compiler?.from);
1803
+ host.notes.push(note);
1804
+ leaf.notes.push({ ...note, line: 1 });
1805
+ }
1806
+ }
1682
1807
  const retainedServer = paths && !isTsrx(file) && (source.includes('react-dom/server') || source.includes('\\'));
1683
1808
  const retainedElement = paths &&
1684
1809
  !known.has(file) &&
@@ -1703,14 +1828,7 @@ export async function runCodemod(paths, options = {}) {
1703
1828
  for (const edge of edges) {
1704
1829
  const factory = 'factory' in edge && edge.factory;
1705
1830
  const inferredServerPath = edge.renderer === 'server render' && !/\.[jt]sx$/.test(edge.module);
1706
- if (inferredServerPath &&
1707
- (/\.(?:[cm]?[jt]sx?|tsrx)$/.test(edge.module) ||
1708
- (config?.moduleResolution !== undefined &&
1709
- config.moduleResolution !== ts.ModuleResolutionKind.Bundler) ||
1710
- !/^\.{1,2}\//.test(edge.module) ||
1711
- /[!%?#\\]/.test(edge.module) ||
1712
- config?.rootDirs ||
1713
- config?.moduleSuffixes?.some(Boolean)))
1831
+ if (inferredServerPath && !canResolveExtensionlessJsx(edge.module))
1714
1832
  continue;
1715
1833
  const original = path.resolve(path.dirname(file), edge.module);
1716
1834
  const direct = edge.renderer === 'createElement' ? null : renamed(file, edge.module);
@@ -1725,10 +1843,7 @@ export async function runCodemod(paths, options = {}) {
1725
1843
  if (!match || (edge.renderer === 'createElement' && proven?.indirect))
1726
1844
  continue;
1727
1845
  const exportName = proven?.name ?? edge.name;
1728
- const extensionlessServer = inferredServerPath &&
1729
- match.file.endsWith('.tsx') &&
1730
- unambiguousJsxPath(match.file, original) &&
1731
- isPlainFile(match.file);
1846
+ const extensionlessServer = inferredServerPath && isExtensionlessJsxTarget(match.file, original);
1732
1847
  const explicit = match.file === original && (edge.renderer !== 'JSX' || /\.[jt]sx$/.test(edge.module));
1733
1848
  if (!explicit &&
1734
1849
  !extensionlessServer &&
@@ -1762,10 +1877,17 @@ export async function runCodemod(paths, options = {}) {
1762
1877
  if (edge.lazy && originalExports.mayExportThen)
1763
1878
  continue;
1764
1879
  if (!originalExports.intrinsics.has(exportName)) {
1880
+ const extensionlessJsx = edge.renderer === 'JSX' &&
1881
+ !!direct &&
1882
+ canResolveExtensionlessJsx(edge.module) &&
1883
+ isExtensionlessJsxTarget(match.file, original);
1765
1884
  const splitIntrinsicDefault = edge.renderer === 'createElement' &&
1766
1885
  exportName === 'default' &&
1767
1886
  originalExports.splitIntrinsicDefault;
1768
- if ((!explicit && !extensionlessServer && edge.renderer !== 'createElement') ||
1887
+ if ((!explicit &&
1888
+ !extensionlessServer &&
1889
+ !extensionlessJsx &&
1890
+ edge.renderer !== 'createElement') ||
1769
1891
  edge.lazy ||
1770
1892
  (!splitIntrinsicDefault && !originalExports.wrappers.has(edge.name)) ||
1771
1893
  !hasTemplateExport(leaf, edge.name))
@@ -32,6 +32,12 @@ export declare function octaneRootComponents(file: string, source: string): {
32
32
  name: string;
33
33
  line: number;
34
34
  }[];
35
+ /** Retained React DOM client roots that render a directly imported React element. */
36
+ export declare function reactClientComponents(file: string, source: string, original: (module: 'react' | 'react/jsx-runtime') => boolean): {
37
+ module: string;
38
+ name: string;
39
+ line: number;
40
+ }[];
35
41
  /** React server calls that render directly imported components. */
36
42
  export declare function reactServerComponents(file: string, source: string, original: (module: 'react' | 'react/jsx-runtime') => boolean, selected?: boolean): {
37
43
  module: string;