@octanejs/codemod 0.2.2 → 0.2.4

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.
@@ -3,7 +3,7 @@ import { parseSync } from '@tsrx/oxc/parser';
3
3
  import { hasRuntimeDependency } from './scoped-store-contract.js';
4
4
  import { literalCondition, skipWrappers } from './expression-wrappers.js';
5
5
  import { atInitializedModuleHandle, initializedBefore } from './effect-receivers.js';
6
- import { hasEval, rendersElementChildren, rootHandleEscapes } from './forwarded-props.js';
6
+ import { callsRootMethod, contains, hasEval, hasPrototypeAccess, rendersElementChildren, rootHandleEscapes, } from './forwarded-props.js';
7
7
  import { componentTagOrExport, inTypeNode, localUses, unchangedContextProviderUse, } from './local-uses.js';
8
8
  import { staticReactProps } from './react-renderer.js';
9
9
  import { bind, nativeReactCompat, skipParens, withoutJsxIndentation } from './transform.js';
@@ -49,7 +49,10 @@ function imported(checker, node, defaultMember = false) {
49
49
  ts.isStringLiteral(imp.moduleSpecifier))
50
50
  return { name, module: imp.moduleSpecifier.text };
51
51
  }
52
- function closedReactReceiver(receiver, uses) {
52
+ function isReactWrapper(name) {
53
+ return name === 'Fragment' || name === 'Suspense' || name === 'StrictMode';
54
+ }
55
+ function closedReactReceiver(receiver, uses, proveWrapper = false) {
53
56
  return uses(receiver).every((ref) => {
54
57
  if (ts.isImportClause(ref.parent) || ts.isNamespaceImport(ref.parent) || inTypeNode(ref))
55
58
  return true;
@@ -57,17 +60,18 @@ function closedReactReceiver(receiver, uses) {
57
60
  if (!ts.isPropertyAccessExpression(member) || member.expression !== ref)
58
61
  return false;
59
62
  const parent = member.parent;
60
- return (ts.isExpressionWithTypeArguments(parent) ||
63
+ return ((ts.isExpressionWithTypeArguments(parent) &&
64
+ (!proveWrapper || ts.isHeritageClause(parent.parent))) ||
61
65
  ((ts.isJsxOpeningElement(parent) ||
62
66
  ts.isJsxClosingElement(parent) ||
63
67
  ts.isJsxSelfClosingElement(parent)) &&
64
68
  parent.tagName === member &&
65
- (member.name.text === 'Fragment' ||
66
- member.name.text === 'Suspense' ||
67
- member.name.text === 'StrictMode')) ||
69
+ isReactWrapper(member.name.text)) ||
68
70
  (ts.isCallExpression(parent) &&
69
71
  parent.expression === member &&
70
- member.name.text !== 'default'));
72
+ member.name.text !== 'default' &&
73
+ // React's mutable CommonJS object inherits methods that can replace a wrapper.
74
+ (!proveWrapper || !Object.hasOwn(Object.prototype, member.name.text))));
71
75
  });
72
76
  }
73
77
  function soleReactReceiver(checker, receiver) {
@@ -174,7 +178,7 @@ export function reactClassExports(file, source) {
174
178
  }
175
179
  return names;
176
180
  }
177
- function hasSingleReactImport(sf, source) {
181
+ function hasSingleRuntimeImport(sf, source, module = 'react') {
178
182
  const erased = new Set();
179
183
  for (const statement of sf.statements) {
180
184
  if ((ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) &&
@@ -186,7 +190,7 @@ function hasSingleReactImport(sf, source) {
186
190
  // type imports and exports are erased even with verbatim module syntax.
187
191
  return (ts
188
192
  .preProcessFile(source, true, true)
189
- .importedFiles.filter(({ fileName, pos }) => fileName === 'react' && !erased.has(pos))
193
+ .importedFiles.filter(({ fileName, pos }) => fileName === module && !erased.has(pos))
190
194
  .length === 1);
191
195
  }
192
196
  /** Direct module-level const exports initialized by the real React context factory. */
@@ -222,7 +226,7 @@ export function retainedReactContextExports(file, source) {
222
226
  continue;
223
227
  if (ts.isPropertyAccessExpression(factory)) {
224
228
  // With interop the default and namespace can share the same mutable React object.
225
- singleReactImport ??= !(dynamicScope ??= hasEval(sf)) && hasSingleReactImport(sf, source);
229
+ singleReactImport ??= !(dynamicScope ??= hasEval(sf)) && hasSingleRuntimeImport(sf, source);
226
230
  if (!singleReactImport ||
227
231
  !ts.isIdentifier(factory.expression) ||
228
232
  !soleReactReceiver(checker, factory.expression) ||
@@ -682,20 +686,85 @@ export function retainedReactElementReturns(file, source) {
682
686
  }
683
687
  return edges;
684
688
  }
685
- /** Existing Octane roots that render a directly imported component body. */
686
- export function octaneRootComponents(file, source) {
687
- const { sf, checker } = bind(file, source);
688
- const edges = [];
689
+ function privateRootField(access) {
690
+ if (ts.isPropertyAccessExpression(access) &&
691
+ ts.isPrivateIdentifier(access.name) &&
692
+ access.expression.kind === ts.SyntaxKind.ThisKeyword)
693
+ return access.name;
694
+ }
695
+ /** Find the createRoot initializer of a closed, branded instance field. */
696
+ function privateRootInitializer(name, checker) {
697
+ const symbol = checker.getSymbolAtLocation(name);
698
+ const field = symbol?.valueDeclaration;
699
+ if (!field || !ts.isPropertyDeclaration(field) || field.initializer)
700
+ return;
701
+ const owner = field.parent;
702
+ if (!ts.isClassDeclaration(owner) ||
703
+ owner.heritageClauses?.length ||
704
+ field.modifiers?.some((modifier) => modifier.kind !== ts.SyntaxKind.ReadonlyKeyword))
705
+ return;
706
+ const constructor = owner.members.find(ts.isConstructorDeclaration);
707
+ const first = constructor?.body?.statements[0];
708
+ const assignment = first && ts.isExpressionStatement(first) && first.expression;
709
+ if (!assignment ||
710
+ !ts.isBinaryExpression(assignment) ||
711
+ assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
712
+ return;
713
+ const initialized = privateRootField(assignment.left);
714
+ if (!initialized || checker.getSymbolAtLocation(initialized) !== symbol)
715
+ return;
716
+ if (contains(owner, (node) => {
717
+ if (ts.isDecorator(node))
718
+ return true;
719
+ if (!ts.isPrivateIdentifier(node) ||
720
+ node.text !== name.text ||
721
+ node === field.name ||
722
+ node === initialized)
723
+ return false;
724
+ // An any-typed receiver can still access the current class brand at runtime.
725
+ const accessed = checker.getSymbolAtLocation(node);
726
+ if (accessed && accessed !== symbol)
727
+ return false;
728
+ const use = node.parent;
729
+ const method = ts.findAncestor(use, ts.isFunctionLike);
730
+ return (!ts.isPropertyAccessExpression(use) ||
731
+ privateRootField(use) !== node ||
732
+ !method ||
733
+ !ts.isMethodDeclaration(method) ||
734
+ method.parent !== owner ||
735
+ !method.body ||
736
+ use.pos < method.body.pos ||
737
+ !!(ts.getCombinedModifierFlags(method) & ts.ModifierFlags.Static) ||
738
+ !callsRootMethod(use));
739
+ }))
740
+ return;
741
+ return skipWrappers(assignment.right);
742
+ }
743
+ function closedNamedImport(checker, reference) {
744
+ const declaration = ts.isIdentifier(reference) && checker.getSymbolAtLocation(reference)?.declarations?.[0];
745
+ return (declaration &&
746
+ ts.isImportSpecifier(declaration) &&
747
+ !declaration.parent.parent.name &&
748
+ !declaration.parent.elements.some((item) => !item.isTypeOnly && (item.propertyName ?? item.name).text === 'default'));
749
+ }
750
+ /** Direct createRoot handles and hydrateRoot calls with verified import provenance. */
751
+ function clientRootArgument({ sf, checker }, source, runtime) {
689
752
  let uses;
690
- function clientComponent(call, callee, hydrate) {
691
- if (hydrate && call.arguments.length <= 4)
692
- return call.arguments[1];
753
+ let closedClientImport;
754
+ return (call, callee) => {
755
+ const entry = imported(checker, callee);
756
+ if (entry?.module === runtime && entry.name === 'hydrateRoot') {
757
+ const maxArgs = runtime === 'octane' ? 4 : 3;
758
+ if (call.arguments.length <= maxArgs)
759
+ return call.arguments[1];
760
+ }
693
761
  if (!ts.isPropertyAccessExpression(callee) ||
694
762
  ts.isOptionalChain(callee) ||
695
763
  callee.name.text !== 'render' ||
696
- call.arguments.length > 2)
764
+ call.arguments.length > (runtime === 'octane' ? 2 : 1))
697
765
  return;
698
766
  const receiver = skipWrappers(callee.expression);
767
+ const privateField = runtime === 'react-dom/client' && privateRootField(receiver);
699
768
  let root = receiver;
700
769
  let handle;
701
770
  if (ts.isIdentifier(receiver)) {
@@ -712,6 +781,17 @@ export function octaneRootComponents(file, source) {
712
781
  handle = declaration.name;
713
782
  root = skipWrappers(declaration.initializer);
714
783
  }
784
+ else if (privateField) {
785
+ const initializer = privateRootInitializer(privateField, checker);
786
+ // A CommonJS export or root prototype can be changed through another reference.
787
+ if (!initializer ||
788
+ !ts.isCallExpression(initializer) ||
789
+ !closedNamedImport(checker, initializer.expression) ||
790
+ !(closedClientImport ??=
791
+ !hasEval(sf) && !hasPrototypeAccess(sf) && hasSingleRuntimeImport(sf, source, runtime)))
792
+ return;
793
+ root = initializer;
794
+ }
715
795
  if (!ts.isCallExpression(root) ||
716
796
  ts.isOptionalChain(root) ||
717
797
  root.arguments.length < 1 ||
@@ -719,7 +799,7 @@ export function octaneRootComponents(file, source) {
719
799
  root.arguments.some(ts.isSpreadElement))
720
800
  return;
721
801
  const factory = imported(checker, skipWrappers(root.expression));
722
- if (factory?.module !== 'octane' || factory.name !== 'createRoot')
802
+ if (factory?.module !== runtime || factory.name !== 'createRoot')
723
803
  return;
724
804
  if (handle) {
725
805
  if ((source.includes('eval') || source.includes('\\u')) && hasEval(sf))
@@ -731,7 +811,14 @@ export function octaneRootComponents(file, source) {
731
811
  return;
732
812
  }
733
813
  return call.arguments[0];
734
- }
814
+ };
815
+ }
816
+ /** Existing Octane roots that render a directly imported component body. */
817
+ export function octaneRootComponents(file, source) {
818
+ const bound = bind(file, source);
819
+ const { sf, checker } = bound;
820
+ const edges = [];
821
+ const clientArgument = clientRootArgument(bound, source, 'octane');
735
822
  function visit(node) {
736
823
  if (ts.isCallExpression(node) &&
737
824
  !ts.isOptionalChain(node) &&
@@ -743,7 +830,7 @@ export function octaneRootComponents(file, source) {
743
830
  ? node.arguments.length <= 3 &&
744
831
  (entry.name === 'renderToString' || entry.name === 'renderToStaticMarkup') &&
745
832
  node.arguments[0]
746
- : clientComponent(node, callee, entry?.module === 'octane' && entry.name === 'hydrateRoot');
833
+ : clientArgument(node, callee);
747
834
  const leaf = value ? imported(checker, skipWrappers(value)) : undefined;
748
835
  if (leaf?.module.startsWith('.') && /\.[jt]sx$/.test(leaf.module))
749
836
  edges.push({
@@ -757,6 +844,92 @@ export function octaneRootComponents(file, source) {
757
844
  visit(sf);
758
845
  return edges;
759
846
  }
847
+ /** Retained React DOM client roots that render a directly imported React element. */
848
+ export function reactClientComponents(file, source, original) {
849
+ const bound = bind(file, source);
850
+ const { sf, checker } = bound;
851
+ const clientArgument = clientRootArgument(bound, source, 'react-dom/client');
852
+ const edges = [];
853
+ let reactJsx;
854
+ let reactModule;
855
+ let singleReactImport;
856
+ let uses;
857
+ const isReact = () => (reactModule ??= original('react'));
858
+ function builtin(tag) {
859
+ const entry = imported(checker, tag, true);
860
+ if (entry?.module !== 'react' ||
861
+ !isReactWrapper(entry.name) ||
862
+ !isReact() ||
863
+ !(singleReactImport ??= !hasEval(sf) && hasSingleRuntimeImport(sf, source)))
864
+ return false;
865
+ if (ts.isPropertyAccessExpression(tag))
866
+ return (ts.isIdentifier(tag.expression) &&
867
+ soleReactReceiver(checker, tag.expression) &&
868
+ closedReactReceiver(tag.expression, (uses ??= localUses(sf, checker)), true));
869
+ // A CJS React member can be mutated through a default import from the same clause.
870
+ return closedNamedImport(checker, tag);
871
+ }
872
+ function rendered(expression, line) {
873
+ const value = ts.isExpression(expression) ? skipWrappers(expression) : expression;
874
+ let ref;
875
+ if (ts.isJsxExpression(value) && value.expression && !value.dotDotDotToken) {
876
+ rendered(value.expression, line);
877
+ return;
878
+ }
879
+ if (ts.isJsxFragment(value) || ts.isJsxElement(value) || ts.isJsxSelfClosingElement(value)) {
880
+ if (!(reactJsx ??= ordinaryReactJsx(source) && original('react/jsx-runtime')))
881
+ return;
882
+ if (ts.isJsxFragment(value) ||
883
+ (ts.isJsxElement(value) && builtin(value.openingElement.tagName))) {
884
+ for (const child of value.children)
885
+ rendered(child, line);
886
+ return;
887
+ }
888
+ const { tagName } = openingTag(value);
889
+ if (!ts.isIdentifier(tagName) || /^[A-Z]/.test(tagName.text))
890
+ ref = tagName;
891
+ }
892
+ else if (ts.isCallExpression(value) && !ts.isOptionalChain(value)) {
893
+ const [type] = value.arguments;
894
+ if (!type || ts.isSpreadElement(type))
895
+ return;
896
+ const factory = imported(checker, skipWrappers(value.expression));
897
+ if (factory?.module !== 'react' || factory.name !== 'createElement' || !isReact())
898
+ return;
899
+ ref = skipWrappers(type);
900
+ if (builtin(ref)) {
901
+ if (!value.arguments.some(ts.isSpreadElement))
902
+ for (const child of value.arguments.slice(2))
903
+ rendered(child, line);
904
+ return;
905
+ }
906
+ }
907
+ const leaf = ref && imported(checker, ref);
908
+ if (leaf?.module.startsWith('.'))
909
+ edges.push({ ...leaf, line });
910
+ }
911
+ const closedPrivateRootElement = (value) => ts.isCallExpression(value) &&
912
+ closedNamedImport(checker, skipWrappers(value.expression)) &&
913
+ !!value.arguments[0] &&
914
+ imported(checker, skipWrappers(value.arguments[0]))?.module.startsWith('.') &&
915
+ (singleReactImport ??= !hasEval(sf) && hasSingleRuntimeImport(sf, source));
916
+ function visit(node) {
917
+ if (ts.isCallExpression(node) &&
918
+ !ts.isOptionalChain(node) &&
919
+ !node.arguments.some(ts.isSpreadElement)) {
920
+ const callee = skipWrappers(node.expression);
921
+ const argument = clientArgument(node, callee);
922
+ if (argument &&
923
+ (!ts.isPropertyAccessExpression(callee) ||
924
+ !privateRootField(skipWrappers(callee.expression)) ||
925
+ closedPrivateRootElement(skipWrappers(argument))))
926
+ rendered(argument, sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1);
927
+ }
928
+ ts.forEachChild(node, visit);
929
+ }
930
+ visit(sf);
931
+ return edges;
932
+ }
760
933
  /** React server calls that render directly imported components. */
761
934
  export function reactServerComponents(file, source, original, selected = false) {
762
935
  const { sf, checker } = bind(file, source);
@@ -806,6 +979,12 @@ export function reactServerComponents(file, source, original, selected = false)
806
979
  ts.forEachChild(node, visit);
807
980
  }
808
981
  if (selected) {
982
+ function exportedRoot(expression) {
983
+ const value = expression && skipParens(expression);
984
+ return value && (ts.isArrowFunction(value) || ts.isFunctionExpression(value))
985
+ ? singleReturn(value)
986
+ : expression;
987
+ }
809
988
  function visitDirectRoot(expression) {
810
989
  const call = expression && skipParens(expression);
811
990
  if (!call || !ts.isCallExpression(call))
@@ -836,7 +1015,16 @@ export function reactServerComponents(file, source, original, selected = false)
836
1015
  }
837
1016
  }
838
1017
  for (const statement of sf.statements) {
839
- if (ts.isIfStatement(statement)) {
1018
+ if (ts.isVariableStatement(statement) &&
1019
+ (statement.declarationList.flags & ts.NodeFlags.BlockScoped) === ts.NodeFlags.Const &&
1020
+ statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
1021
+ for (const { name, initializer } of statement.declarationList.declarations)
1022
+ visitDirectRoot(ts.isIdentifier(name) ? exportedRoot(initializer) : initializer);
1023
+ }
1024
+ else if (ts.isExportAssignment(statement) && !statement.isExportEquals) {
1025
+ visitDirectRoot(exportedRoot(statement.expression));
1026
+ }
1027
+ else if (ts.isIfStatement(statement)) {
840
1028
  const condition = skipParens(statement.expression);
841
1029
  if (ts.isPropertyAccessExpression(condition) &&
842
1030
  !ts.isOptionalChain(condition) &&