@octanejs/codemod 0.2.1 → 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/dist/transform.js CHANGED
@@ -1,20 +1,33 @@
1
1
  import { svgDataAttribute, svgLiteralRootOverride } from './path-svg.js';
2
- import { forwardedProps, hasEval, literalJsxAttribute, nativeOutputOwner, returnedTextReceiver, renderUses, svgLocalReads, } from './forwarded-props.js';
3
- import { reactRenderer, staticReactProps } from './react-renderer.js';
2
+ import { contains, forwardedProps, hasEval, hasPrototypeAccess, literalJsxAttribute, nativeOutputOwner, returnedTextReceiver, renderUses, rootHandleEscapes, svgLocalReads, } from './forwarded-props.js';
3
+ import { reactRenderer, staticReactProps, unreadServerStream } from './react-renderer.js';
4
4
  import { linkedRenderState } from './linked-state.js';
5
5
  import { nativeSetupHook } from './local-react-hook.js';
6
- import { componentTagOrExport, inTypeNode, localSymbol, localUses, scalar, walkLocalValues, } from './local-uses.js';
7
- import { isWrapper, skipWrappers } from './expression-wrappers.js';
6
+ import { componentTagOrExport, inTypeNode, localSymbol, localUses, scalar, unchangedContextProviderUse, walkLocalValues, } from './local-uses.js';
7
+ import { isWrapper, literalCondition, skipWrappers } from './expression-wrappers.js';
8
8
  import ts from 'typescript';
9
- import { effectHelpers, effectReceivers, fixedBinding, initializedBefore, stableExportedProp, } from './effect-receivers.js';
9
+ import { atInitializedModuleHandle, effectHelpers, effectReceivers, fixedBinding, initializedBefore, stableExportedProp, } from './effect-receivers.js';
10
10
  import { isBareSvgTag, storeHookUses } from './store-hook-uses.js';
11
11
  import { intlImports } from './react-intl.js';
12
- import { DEPENDENCY_HOOKS, RADIX_TYPES, REACT_MODULES, TEXT_FIELD_COMPONENTS, TEXT_INPUT_TYPES, UNSUPPORTED_VALUES, mapPackageExport, mapQualifiedType, mapReactImport, missingExport, radixNamespace, } from './mappings.js';
12
+ import { DEPENDENCY_HOOKS, RADIX_TYPES, REACT_MODULES, TEXT_FIELD_COMPONENTS, TEXT_INPUT_TYPES, UNSUPPORTED_VALUES, hasOctaneValue, isComputedReactHookOrRef, mapPackageExport, mapQualifiedType, mapReactImport, missingExport, radixNamespace, } from './mappings.js';
13
13
  const RADIX_SLOT_MEMBERS = new Map([
14
14
  ['Root', 'Slot'],
15
15
  ['Slot', 'Slot'],
16
16
  ['Slottable', 'Slottable'],
17
17
  ]);
18
+ function quotedPropWithReference(node) {
19
+ return (ts.isJsxAttribute(node) &&
20
+ !!node.initializer &&
21
+ ts.isStringLiteral(node.initializer) &&
22
+ node.initializer.text.includes('&'));
23
+ }
24
+ function singleCallbackExpression(body) {
25
+ if (!ts.isBlock(body))
26
+ return body;
27
+ const statement = body.statements[0];
28
+ if (body.statements.length === 1 && ts.isReturnStatement(statement))
29
+ return statement.expression;
30
+ }
18
31
  function directMember(receiver) {
19
32
  const parent = receiver.parent;
20
33
  if (ts.isPropertyAccessExpression(parent) &&
@@ -25,6 +38,54 @@ function directMember(receiver) {
25
38
  return parent.right;
26
39
  return null;
27
40
  }
41
+ function literalDisplayNameAssignment(ref, declaration) {
42
+ const member = ref.parent;
43
+ if (!ts.isPropertyAccessExpression(member) ||
44
+ member.expression !== ref ||
45
+ member.questionDotToken ||
46
+ member.name.text !== 'displayName')
47
+ return false;
48
+ const assignment = member.parent;
49
+ return (ts.isBinaryExpression(assignment) &&
50
+ assignment.left === member &&
51
+ assignment.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
52
+ ts.isExpressionStatement(assignment.parent) &&
53
+ assignment.parent.parent === declaration.parent &&
54
+ assignment.getStart() >= declaration.end &&
55
+ ts.isStringLiteralLike(skipWrappers(assignment.right)));
56
+ }
57
+ // React Router applications can augment this loader type on the original module.
58
+ function routerLoadContext(module, name) {
59
+ return name === 'AppLoadContext' && (module === 'react-router' || module === 'react-router-dom');
60
+ }
61
+ function firstQualifiedName(name) {
62
+ while (ts.isQualifiedName(name))
63
+ name = name.left;
64
+ return name;
65
+ }
66
+ function isValueTypeQuery(name) {
67
+ while (ts.isQualifiedName(name.parent) && name.parent.left === name)
68
+ name = name.parent;
69
+ return ts.isTypeQueryNode(name.parent) && name.parent.exprName === name;
70
+ }
71
+ /** The lexical root of an interface base or class implements type. */
72
+ function typeHeritageRoot(node) {
73
+ if (!ts.isPartOfTypeNode(node))
74
+ return;
75
+ let root = node.expression;
76
+ while (ts.isPropertyAccessExpression(root) && !root.questionDotToken)
77
+ root = root.expression;
78
+ if (ts.isIdentifier(root) && root !== node.expression)
79
+ return root;
80
+ }
81
+ function needsTouchValueOrNamespace(ref) {
82
+ if (isValueTypeQuery(ref) || (ts.isQualifiedName(ref.parent) && ref.parent.left === ref))
83
+ return true;
84
+ let access = ref;
85
+ while (ts.isPropertyAccessExpression(access.parent) && access.parent.expression === access)
86
+ access = access.parent;
87
+ return ts.isExpressionWithTypeArguments(access.parent) && typeHeritageRoot(access.parent) === ref;
88
+ }
28
89
  /** Marks emitted text whose whole line should go. */
29
90
  const DROP = '\u0000DROP\u0000';
30
91
  /**
@@ -49,6 +110,11 @@ export const MAP_PARAMETER_WRITE = 'map-parameter-write';
49
110
  export const MAP_CALLBACK_SCOPE = 'map-callback-scope';
50
111
  export const CONTEXT_ALIAS = 'context-path-alias';
51
112
  export const CONTEXT_PROVIDER_GETTER = 'context-provider-getter';
113
+ export const ELEMENT_CHILD_ALIAS = 'element-child-path-alias';
114
+ export const INTL_PROVIDER_DEFAULTS = 'intl-provider-defaults';
115
+ export const REACT_TYPE_PROJECTION = 'react-type-projection';
116
+ export const BUFFERED_SSR_OPTIONS = 'buffered-ssr-options';
117
+ export const BUFFERED_SSR_REACT_COMPONENT = 'buffered-ssr-react-component';
52
118
  /** Rule names, as reported. */
53
119
  const RULE = {
54
120
  binding: 'bindings',
@@ -122,6 +188,8 @@ export function projectTypeAt(node, types) {
122
188
  * members.
123
189
  */
124
190
  export function bind(filename, source) {
191
+ // The program asks its host for slash-delimited paths even on Windows.
192
+ filename = filename.replaceAll('\\', '/');
125
193
  const lib = esLib();
126
194
  const sf = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, scriptKind(filename));
127
195
  const host = {
@@ -180,6 +248,14 @@ function isDOMTag(tag) {
180
248
  }
181
249
  return domTagNames.has(tag);
182
250
  }
251
+ /** Follow direct JSX children only through ordinary HTML hosts with no content override. */
252
+ function rendersOrdinaryHtmlChildren(opening) {
253
+ return (ts.isIdentifier(opening.tagName) &&
254
+ /^(?:article|aside|div|footer|header|main|nav|section)$/.test(opening.tagName.text) &&
255
+ opening.attributes.properties.every((attr) => ts.isJsxAttribute(attr) &&
256
+ ts.isIdentifier(attr.name) &&
257
+ !/^(?:children|dangerouslySetInnerHTML|is)$/i.test(attr.name.text)));
258
+ }
183
259
  function scriptKind(filename) {
184
260
  if (filename.endsWith('.tsx'))
185
261
  return ts.ScriptKind.TSX;
@@ -194,7 +270,7 @@ export function nativeReactCompat(module, name) {
194
270
  return ((name === 'ReactCompat' || name === 'ReactCompatInline') &&
195
271
  (module === 'octane/react' || module === 'octane/react/server'));
196
272
  }
197
- function skipParens(node) {
273
+ export function skipParens(node) {
198
274
  while (ts.isParenthesizedExpression(node))
199
275
  node = node.expression;
200
276
  return node;
@@ -213,6 +289,37 @@ function asRest(declaration) {
213
289
  function isJsx(node) {
214
290
  return ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node);
215
291
  }
292
+ function numericConstantValue(node) {
293
+ node = skipWrappers(node);
294
+ if (ts.isNumericLiteral(node))
295
+ return Number(node.text);
296
+ if (!ts.isPrefixUnaryExpression(node) ||
297
+ (node.operator !== ts.SyntaxKind.MinusToken && node.operator !== ts.SyntaxKind.PlusToken))
298
+ return undefined;
299
+ const operand = skipWrappers(node.operand);
300
+ if (!ts.isNumericLiteral(operand))
301
+ return undefined;
302
+ const value = Number(operand.text);
303
+ return node.operator === ts.SyntaxKind.MinusToken ? -value : value;
304
+ }
305
+ function isNumericConstant(node) {
306
+ return numericConstantValue(node) !== undefined;
307
+ }
308
+ const TRUTHY = 1;
309
+ const FALSY = 2;
310
+ const NULLISH = 4;
311
+ function logicalRightCases(operator) {
312
+ switch (operator) {
313
+ case ts.SyntaxKind.AmpersandAmpersandToken:
314
+ return TRUTHY;
315
+ case ts.SyntaxKind.BarBarToken:
316
+ return FALSY | NULLISH;
317
+ case ts.SyntaxKind.QuestionQuestionToken:
318
+ return NULLISH;
319
+ default:
320
+ return 0;
321
+ }
322
+ }
216
323
  /** A deferred clsx call may test a binding only if its truth value stays fixed. */
217
324
  function svgClassToken(expr, fixedToken, truthTest = false) {
218
325
  expr = skipWrappers(expr);
@@ -256,16 +363,15 @@ function readsCssToken(ref) {
256
363
  use.operatorToken.kind === ts.SyntaxKind.BarBarToken)));
257
364
  }
258
365
  /**
259
- * What a module's import of a package with no Octane port leaves to do.
366
+ * Describe a package import that the codemod keeps on React.
260
367
  */
261
368
  function portComment({ name, islands, blocked }) {
262
- const missing = `No Octane port of \`${name}\` exists`;
263
- if (blocked > 0) {
264
- return `${missing}, and this module needs one: Octane cannot call its hooks, read its contexts, or pass Octane content to its components.`;
265
- }
369
+ const retained = `Retained React import of \`${name}\``;
370
+ if (blocked > 0)
371
+ return `${retained}. Review the uses that need a React renderer.`;
266
372
  return islands > 0
267
- ? `${missing}, so its components render in React through ReactCompat.`
268
- : `${missing}; React stays a dependency for it.`;
373
+ ? `${retained}. Its components render in React through ReactCompat.`
374
+ : `${retained}. Keep React as a dependency.`;
269
375
  }
270
376
  /**
271
377
  * Whether a hole is already spelled as text, or as a literal the cast would
@@ -339,7 +445,7 @@ function nodeSpanning(sf, start, end) {
339
445
  node = child;
340
446
  }
341
447
  }
342
- function rowKeyLiteral(node) {
448
+ function isPrimitiveLiteral(node) {
343
449
  node = skipWrappers(node);
344
450
  if (ts.isPrefixUnaryExpression(node)) {
345
451
  const operand = skipWrappers(node.operand);
@@ -405,6 +511,20 @@ function returnsJsx(statements) {
405
511
  };
406
512
  return statements.some(visit);
407
513
  }
514
+ /** Follow a clause's straight-line statements and plain lexical blocks to an exit. */
515
+ function clauseReturnsJsx(statements) {
516
+ for (const statement of statements) {
517
+ if (ts.isReturnStatement(statement))
518
+ return !!statement.expression && isJsx(skipWrappers(statement.expression));
519
+ if (ts.isBreakStatement(statement) || ts.isThrowStatement(statement))
520
+ return false;
521
+ if (ts.isBlock(statement)) {
522
+ const returns = clauseReturnsJsx(statement.statements);
523
+ if (returns !== undefined)
524
+ return returns;
525
+ }
526
+ }
527
+ }
408
528
  /** Document tags a router shell renders through `@octanejs/tanstack-router`. */
409
529
  const DOCUMENT_TAGS = {
410
530
  html: 'Html',
@@ -579,6 +699,9 @@ class ModuleTransform {
579
699
  removed = new Set();
580
700
  /** `<Fragment key>` rows whose key moved to the `@for` header. */
581
701
  bare = new Set();
702
+ /** Map calls in output with a proven native renderer. */
703
+ nativeOutputMaps;
704
+ logicalResults;
582
705
  /** Functions whose parameter list a rule replaced. */
583
706
  parameters = new Map();
584
707
  /** Rest props that give up `onChange` to a text field. */
@@ -587,6 +710,7 @@ class ModuleTransform {
587
710
  changeSpreads = new Set();
588
711
  /** Proven element slots on converted top-level declarations, for the project caller pass. */
589
712
  elementChildren = [];
713
+ ordinaryElementMetadata;
590
714
  /** Components to mark `descriptorChildren`. */
591
715
  descriptorComponents = new Set();
592
716
  /** Whether a `declare module` now augments `octane/jsx-runtime`. */
@@ -597,6 +721,7 @@ class ModuleTransform {
597
721
  unported = new Map();
598
722
  /** Elements to host in a `ReactCompat` island. */
599
723
  islands = new Map();
724
+ inlineIntlMessages = new Set();
600
725
  reactRendererBodies = new Map();
601
726
  originalStoreTags = new Map();
602
727
  storeSourceNames;
@@ -604,6 +729,7 @@ class ModuleTransform {
604
729
  unrenderable = new Map();
605
730
  /** Placeholder index -> import declaration. */
606
731
  importSlots = [];
732
+ retainedTypeNamespaces = new Set();
607
733
  intrinsicPropsHelper = null;
608
734
  hasJsx = false;
609
735
  /** Whether the module imports React, rather than already being Octane. */
@@ -691,6 +817,8 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
691
817
  const reexports = [];
692
818
  const isExported = (statement) => ts.canHaveModifiers(statement) &&
693
819
  ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
820
+ const elementChildren = [...this.elementChildren];
821
+ let safeElementAliases;
694
822
  const descriptorChildren = [...this.descriptorComponents].flatMap((d) => {
695
823
  const statement = ts.isVariableDeclaration(d) ? d.parent.parent : d;
696
824
  return d.name && isExported(statement) ? [d.name.getText(this.sf)] : [];
@@ -719,7 +847,9 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
719
847
  for (const element of statement.exportClause.elements) {
720
848
  if (contexts.has((element.propertyName ?? element.name).text))
721
849
  exported.add(element.name.text);
722
- if (!this.descriptorComponents.size || statement.isTypeOnly || element.isTypeOnly)
850
+ if ((!this.descriptorComponents.size && !this.elementChildren.length) ||
851
+ statement.isTypeOnly ||
852
+ element.isTypeOnly)
723
853
  continue;
724
854
  const local = this.checker.getExportSpecifierLocalTargetSymbol(element)?.valueDeclaration;
725
855
  if (local &&
@@ -727,6 +857,22 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
727
857
  this.descriptorComponents.has(local)) {
728
858
  descriptorChildren.push(element.name.text);
729
859
  }
860
+ if (local && ts.isFunctionDeclaration(local) && local.name) {
861
+ const start = local.getStart(this.sf);
862
+ if (this.elementChildren.some((slot) => slot.start === start) &&
863
+ this.localUses(local.name).every((ref) => inTypeNode(ref) ||
864
+ componentTagOrExport(ref) ||
865
+ this.isOrdinaryElementMetadata(ref, local)) &&
866
+ (safeElementAliases ??=
867
+ this.options.mutableExports?.() !== true &&
868
+ !contains(this.sf, (node) => node.kind === ts.SyntaxKind.ThisKeyword ||
869
+ (ts.isIdentifier(node) &&
870
+ /^(?:eval|module|exports|require|arguments)$/.test(node.text) &&
871
+ !isPropertyName(node) &&
872
+ !declaresName(node) &&
873
+ !inTypeNode(node)))))
874
+ elementChildren.push({ start, exported: element.name.text });
875
+ }
730
876
  }
731
877
  }
732
878
  }
@@ -748,11 +894,18 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
748
894
  continue;
749
895
  if (nativeSetupHook(ref, this.localUses, this.checker, undefined, true) !== 'first')
750
896
  continue;
751
- const component = ts.findAncestor(ref, ts.isFunctionDeclaration);
752
- if (component?.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword))
753
- storeHookComponents.add('default');
754
- else if (component?.name)
755
- storeHookComponents.add(component.name.text);
897
+ const component = ts.findAncestor(ref, ts.isFunctionLike);
898
+ if (component && ts.isFunctionDeclaration(component)) {
899
+ if (component.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword))
900
+ storeHookComponents.add('default');
901
+ else if (component.name)
902
+ storeHookComponents.add(component.name.text);
903
+ }
904
+ else if (component && ts.isVariableDeclaration(component.parent)) {
905
+ const name = component.parent.name;
906
+ if (ts.isIdentifier(name))
907
+ storeHookComponents.add(name.text);
908
+ }
756
909
  }
757
910
  }
758
911
  return {
@@ -760,7 +913,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
760
913
  reexports,
761
914
  ...(descriptorChildren.length ? { descriptorChildren } : {}),
762
915
  ...(storeHookComponents.size ? { storeHookComponents: [...storeHookComponents] } : {}),
763
- ...(this.elementChildren.length ? { elementChildren: this.elementChildren } : {}),
916
+ ...(elementChildren.length ? { elementChildren } : {}),
764
917
  };
765
918
  }
766
919
  // ---------------------------------------------------------------- analysis
@@ -768,7 +921,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
768
921
  // Added imports quote their module as the module's own imports do.
769
922
  const first = this.sf.statements.find(ts.isImportDeclaration);
770
923
  this.quote = first ? first.moduleSpecifier.getText(this.sf)[0] : "'";
771
- /** Locals imported from a package with no Octane port. */
924
+ /** Locals whose package imports stay on React. */
772
925
  const portLocals = new Set();
773
926
  const reactSvgImports = new Set();
774
927
  for (const statement of this.sf.statements) {
@@ -778,7 +931,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
778
931
  ts.isStringLiteral(statement.moduleSpecifier)) {
779
932
  const port = this.portOf(statement.moduleSpecifier.text);
780
933
  if (port) {
781
- this.note(RULE.bindings, 'warning', statement, `\`${port.name}\` has no Octane port: import its components from it where they render, so they can render in a \`ReactCompat\` island.`);
934
+ this.note(RULE.bindings, 'warning', statement, `\`${port.name}\` stays on React. Import its components directly where they render so they can render in a \`ReactCompat\` island.`);
782
935
  }
783
936
  }
784
937
  if (!ts.isImportDeclaration(statement) || !statement.importClause)
@@ -834,7 +987,12 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
834
987
  this.nativeIntl = intlImports(this.sf, this.options.forwardedText, this.checker, (expr) => this.typeOf(expr), (fn) => this.isComponent(fn), (element) => !!this.authoredIsland(element), (element) => this.hostsInReact(element), (tag) => !!returnedTextReceiver(tag, {
835
988
  typeOf: (n) => this.typeOf(n),
836
989
  text: (n) => textKind(this.typeOf(n)) !== 0,
837
- }, this.localUses), () => this.options.reactStoreComponent?.('react-intl') === true, (call, method) => {
990
+ }, this.localUses), () => this.options.reactStoreComponent?.('react-intl') === true, (callee) => {
991
+ const hook = this.directImportedValue(skipWrappers(callee))?.entry;
992
+ return hook?.module === 'react' && this.options.originalReact === true
993
+ ? hook.imported
994
+ : null;
995
+ }, (call, method) => {
838
996
  if (method === 'formatMessage' || this.options.automaticReactJsx)
839
997
  this.note(RULE.bindings, 'error', call, `A React Intl formatter can schedule React DOM resources on the original request. Verify this ${method} call runs without renderer-owned effects, or keep it in the original React render.`);
840
998
  });
@@ -848,7 +1006,9 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
848
1006
  this.options.resolveStoreHook &&
849
1007
  ts.isImportSpecifier(declaration) &&
850
1008
  /^use[A-Z0-9]/.test(entry.imported) &&
851
- /^use[A-Z0-9]/.test(entry.local)) {
1009
+ // The compiler only assigns custom hook slots to these local names.
1010
+ /^use[A-Z]/.test(entry.local) &&
1011
+ entry.local !== 'useContext') {
852
1012
  const statement = declaration.parent.parent.parent;
853
1013
  if (!statement.attributes && !/\/\*|\/\//.test(statement.getText(this.sf))) {
854
1014
  const pending = new Map();
@@ -890,12 +1050,22 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
890
1050
  }
891
1051
  if (this.target === 'tsrx') {
892
1052
  for (const item of this.nativeIntl) {
893
- if ((item.propertyName ?? item.name).text !== 'FormattedMessage')
1053
+ const name = (item.propertyName ?? item.name).text;
1054
+ if (name !== 'FormattedMessage' && name !== 'IntlProvider')
894
1055
  continue;
895
1056
  for (const ref of this.localUses(item.name)) {
896
1057
  const element = ref.parent;
897
- if (ts.isJsxSelfClosingElement(element) && !this.reactRendererBodies.has(element))
1058
+ if ((!ts.isJsxOpeningElement(element) && !ts.isJsxSelfClosingElement(element)) ||
1059
+ element.tagName !== ref ||
1060
+ this.reactRendererBodies.has(element))
1061
+ continue;
1062
+ if (name === 'IntlProvider')
1063
+ this.checkIntlProviderResources(element);
1064
+ else if (ts.isJsxSelfClosingElement(element)) {
898
1065
  this.reportIntlFormatterOwner(element, 'generated native adapter');
1066
+ if (this.inParagraph(element) && this.options.reactCompatInline)
1067
+ this.inlineIntlMessages.add(element);
1068
+ }
899
1069
  }
900
1070
  }
901
1071
  }
@@ -1185,8 +1355,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1185
1355
  });
1186
1356
  }
1187
1357
  /**
1188
- * The package with no Octane port that a specifier names, or null. It
1189
- * still runs on React, which only the codemod's report and a comment say.
1358
+ * The package that the codemod keeps on React for this specifier, or null.
1190
1359
  */
1191
1360
  portOf(module) {
1192
1361
  let port = this.ports.get(module);
@@ -1228,7 +1397,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1228
1397
  }
1229
1398
  }
1230
1399
  /**
1231
- * A component from a package with no Octane port renders in React, inside
1400
+ * A component from a retained React import renders in React, inside
1232
1401
  * a `ReactCompat` island, when its element hands React nothing Octane
1233
1402
  * renders. Its hooks and contexts cannot run in an Octane component, so
1234
1403
  * they are reported.
@@ -1255,7 +1424,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1255
1424
  const parent = member.parent;
1256
1425
  const block = (message) => {
1257
1426
  port.blocked++;
1258
- const error = `${message} \`${port.name}\` has no Octane port.`;
1427
+ const error = `${message} \`${port.name}\` stays on React.`;
1259
1428
  this.note(RULE.bindings, 'error', member, error);
1260
1429
  return error;
1261
1430
  };
@@ -1289,6 +1458,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1289
1458
  (name === 'FormattedMessage' ||
1290
1459
  (this.options.reactIntlAdapter && INTL_FORMATTER.test(importedName))))
1291
1460
  this.reportIntlFormatterOwner(element, 'generated island');
1461
+ this.checkIslandLayoutRef(parent);
1292
1462
  this.islands.set(element, paragraph ? 'ReactCompatInline' : 'ReactCompat');
1293
1463
  }
1294
1464
  else {
@@ -1299,13 +1469,104 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1299
1469
  }
1300
1470
  else if (ts.isCallExpression(parent) && parent.expression === member) {
1301
1471
  if (/^use[A-Z0-9]/.test(name))
1302
- block(`\`${text}\` is a React hook, which Octane cannot call.`);
1472
+ block(`\`${text}\` is a React hook. Keep this hook call under a React renderer.`);
1303
1473
  }
1304
1474
  else if (ts.isCallExpression(parent) &&
1305
1475
  /^(?:use|useContext)$/.test(this.calleeName(parent.expression) ?? '')) {
1306
- block(`\`${text}\` is a React context, which Octane cannot read.`);
1476
+ block(`\`${text}\` is a React context. Keep this context read under a React renderer.`);
1307
1477
  }
1308
1478
  }
1479
+ /** A layout setup can depend on the child ref from the original shared commit. */
1480
+ checkIslandLayoutRef(tag) {
1481
+ const attr = tag.attributes.properties.findLast((p) => ts.isJsxSpreadAttribute(p) || (ts.isIdentifier(p.name) && p.name.text === 'ref'));
1482
+ const value = attr && ts.isJsxAttribute(attr) && attr.initializer;
1483
+ if (!attr || !value || !ts.isJsxExpression(value) || !value.expression)
1484
+ return;
1485
+ const element = ts.isJsxOpeningElement(tag) ? tag.parent : tag;
1486
+ const owner = ts.findAncestor(element, isFunctionLike);
1487
+ if (!owner)
1488
+ return;
1489
+ const layoutRead = (ref) => {
1490
+ if (directMember(ref)?.text !== 'current')
1491
+ return false;
1492
+ const setup = ts.findAncestor(ref, ts.isFunctionLike);
1493
+ if (!setup || !ts.isArrowFunction(setup) || setup.modifiers?.length)
1494
+ return false;
1495
+ const call = setup.parent;
1496
+ if (!ts.isCallExpression(call) ||
1497
+ call.arguments[0] !== setup ||
1498
+ call.questionDotToken ||
1499
+ this.reactHook(call.expression) !== 'useLayoutEffect' ||
1500
+ !ts.isExpressionStatement(call.parent) ||
1501
+ call.parent.parent !== owner.body)
1502
+ return false;
1503
+ let value = ref.parent;
1504
+ while (isWrapper(value.parent) ||
1505
+ ts.isPropertyAccessExpression(value.parent) ||
1506
+ ts.isTemplateSpan(value.parent) ||
1507
+ ts.isTemplateExpression(value.parent) ||
1508
+ (ts.isPrefixUnaryExpression(value.parent) &&
1509
+ value.parent.operator === ts.SyntaxKind.ExclamationToken) ||
1510
+ (ts.isCallExpression(value.parent) &&
1511
+ (value.parent.expression === value || !ts.isOptionalChain(value.parent))))
1512
+ value = value.parent;
1513
+ const step = value.parent;
1514
+ return (value === setup.body ||
1515
+ (ts.isExpressionStatement(step) &&
1516
+ step.parent === setup.body &&
1517
+ ts.isBlock(setup.body) &&
1518
+ setup.body.statements[0] === step));
1519
+ };
1520
+ const readsInLayout = (name) => {
1521
+ const init = this.constValue(name);
1522
+ if (!init ||
1523
+ !ts.isCallExpression(init) ||
1524
+ init.questionDotToken ||
1525
+ init.arguments.length !== 1 ||
1526
+ init.arguments[0].kind !== ts.SyntaxKind.NullKeyword ||
1527
+ this.reactHook(init.expression) !== 'useRef' ||
1528
+ !fixedBinding(this.checker, name, element) ||
1529
+ !initializedBefore(this.checker, name, element))
1530
+ return false;
1531
+ return this.localUses(name).some(layoutRead);
1532
+ };
1533
+ const ref = skipWrappers(value.expression);
1534
+ let late = ts.isIdentifier(ref) && readsInLayout(ref);
1535
+ if (ts.isArrowFunction(ref) &&
1536
+ !ref.modifiers?.length &&
1537
+ ref.parameters.length === 1 &&
1538
+ !ref.parameters[0].initializer &&
1539
+ !ref.parameters[0].dotDotDotToken) {
1540
+ const body = ref.body;
1541
+ const assign = (value) => {
1542
+ const write = skipWrappers(value);
1543
+ if (!ts.isBinaryExpression(write) || write.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
1544
+ return false;
1545
+ const left = skipWrappers(write.left);
1546
+ const right = skipWrappers(write.right);
1547
+ if (ts.isPropertyAccessExpression(left) &&
1548
+ left.name.text === 'current' &&
1549
+ ts.isIdentifier(left.expression) &&
1550
+ ts.isIdentifier(right) &&
1551
+ this.declarationOf(right) === ref.parameters[0] &&
1552
+ fixedBinding(this.checker, right, write))
1553
+ return readsInLayout(left.expression);
1554
+ return false;
1555
+ };
1556
+ if (ts.isBlock(body)) {
1557
+ for (const step of body.statements) {
1558
+ if (!ts.isExpressionStatement(step))
1559
+ break;
1560
+ if ((late = assign(step.expression)))
1561
+ break;
1562
+ }
1563
+ }
1564
+ else
1565
+ late = assign(body);
1566
+ }
1567
+ if (late)
1568
+ this.note('react-island-layout-ref', 'error', attr, 'This layout effect can run before the generated ReactCompat island sets its child ref. Keep both in React or move the layout work to the ref callback.');
1569
+ }
1309
1570
  reportIntlFormatterOwner(node, boundary) {
1310
1571
  this.note(RULE.bindings, 'error', node, `A React Intl formatter can depend on ancestor contexts or schedule React DOM resources outside this ${boundary}. Verify the provider and its formatters, or keep the formatter under its original React ancestors.`);
1311
1572
  }
@@ -1695,19 +1956,11 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1695
1956
  return text.text.trim() !== '' && !/[!;]/.test(text.text);
1696
1957
  if (!ts.isTemplateExpression(text) || /[!;]/.test(text.head.text))
1697
1958
  return false;
1698
- const numeric = (node) => {
1699
- node = skipWrappers(node);
1700
- return (ts.isNumericLiteral(node) ||
1701
- (ts.isPrefixUnaryExpression(node) &&
1702
- (node.operator === ts.SyntaxKind.MinusToken ||
1703
- node.operator === ts.SyntaxKind.PlusToken) &&
1704
- ts.isNumericLiteral(skipWrappers(node.operand))));
1705
- };
1706
1959
  return text.templateSpans.every(({ expression, literal }) => {
1707
1960
  if (/[!;]/.test(literal.text))
1708
1961
  return false;
1709
1962
  const part = skipWrappers(expression);
1710
- if (numeric(part))
1963
+ if (isNumericConstant(part))
1711
1964
  return true;
1712
1965
  if (!ts.isConditionalExpression(part))
1713
1966
  return false;
@@ -1715,13 +1968,31 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1715
1968
  return (ts.isIdentifier(test) &&
1716
1969
  fixedBinding(this.checker, test, part, (this.fixedSvgParameters ??= new Map())) &&
1717
1970
  initializedBefore(this.checker, test, part) &&
1718
- numeric(part.whenTrue) &&
1719
- numeric(part.whenFalse));
1971
+ isNumericConstant(part.whenTrue) &&
1972
+ isNumericConstant(part.whenFalse));
1720
1973
  });
1721
1974
  }
1722
1975
  svgRead;
1723
1976
  nativeSvgProps;
1724
1977
  provenSvgOwners;
1978
+ provenOutputOwners;
1979
+ /** A direct component-value entry into one of the installed native server renderers. */
1980
+ nativeSvgServerEntry(ref) {
1981
+ let argument = ref;
1982
+ while (ts.isParenthesizedExpression(argument.parent))
1983
+ argument = argument.parent;
1984
+ const call = argument.parent;
1985
+ if (!ts.isCallExpression(call) ||
1986
+ call.arguments[0] !== argument ||
1987
+ call.arguments.length > 3 ||
1988
+ ts.isOptionalChain(call) ||
1989
+ call.arguments.some(ts.isSpreadElement))
1990
+ return false;
1991
+ const entry = this.directImportedValue(skipParens(call.expression))?.entry;
1992
+ return (entry?.module === 'octane/server' &&
1993
+ (entry.imported === 'renderToString' || entry.imported === 'renderToStaticMarkup') &&
1994
+ this.options.originalSvgServer === true);
1995
+ }
1725
1996
  nativeOutput(value, uses, unproven) {
1726
1997
  const typeOf = (node) => this.typeOf(node);
1727
1998
  const destination = {
@@ -1740,9 +2011,11 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1740
2011
  if (!first)
1741
2012
  return false;
1742
2013
  const pending = [first];
1743
- const proven = (this.provenSvgOwners ??= new Set());
2014
+ const proven = unproven
2015
+ ? (this.provenSvgOwners ??= new Set())
2016
+ : (this.provenOutputOwners ??= new Set());
1744
2017
  const seen = new Set();
1745
- let exported = false;
2018
+ let reachesRenderer = false;
1746
2019
  // A local function can hand its return value to another renderer. Follow every
1747
2020
  // use of its binding, including uses of a component that also has an export.
1748
2021
  while (pending.length) {
@@ -1753,7 +2026,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1753
2026
  (ts.isFunctionExpression(fn) && fn.name))
1754
2027
  return false;
1755
2028
  if (proven.has(fn)) {
1756
- exported = true;
2029
+ reachesRenderer = true;
1757
2030
  continue;
1758
2031
  }
1759
2032
  if (seen.has(fn))
@@ -1761,7 +2034,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1761
2034
  seen.add(fn);
1762
2035
  const parent = fn.parent;
1763
2036
  if (ts.isExportAssignment(parent) && parent.parent === this.sf) {
1764
- exported = true;
2037
+ reachesRenderer = true;
1765
2038
  continue;
1766
2039
  }
1767
2040
  const variable = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? parent : null;
@@ -1775,27 +2048,31 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
1775
2048
  if (!refs.length && !directExport)
1776
2049
  return false;
1777
2050
  if (directExport)
1778
- exported = true;
2051
+ reachesRenderer = true;
1779
2052
  for (const ref of refs) {
1780
2053
  const tag = ref.parent;
1781
2054
  if (ts.isExportSpecifier(tag) || ts.isExportAssignment(tag)) {
1782
- exported = true;
2055
+ reachesRenderer = true;
1783
2056
  continue;
1784
2057
  }
1785
2058
  if (!(ts.isJsxSelfClosingElement(tag) ||
1786
2059
  ts.isJsxOpeningElement(tag) ||
1787
2060
  ts.isJsxClosingElement(tag)) ||
1788
- tag.tagName !== ref)
1789
- return false;
2061
+ tag.tagName !== ref) {
2062
+ if (!unproven || !this.nativeSvgServerEntry(ref))
2063
+ return false;
2064
+ reachesRenderer = true;
2065
+ continue;
2066
+ }
1790
2067
  const owner = nativeOutputOwner(ts.isJsxSelfClosingElement(tag) ? tag : tag.parent, slot, destination);
1791
2068
  if (!owner)
1792
2069
  return false;
1793
2070
  pending.push(owner);
1794
2071
  }
1795
2072
  }
1796
- if (exported)
2073
+ if (reachesRenderer)
1797
2074
  proven.add(first);
1798
- return exported;
2075
+ return reachesRenderer;
1799
2076
  }
1800
2077
  /** Keep the imported React component as the type of the element the service receives. */
1801
2078
  storeReactDescriptor(element) {
@@ -2029,20 +2306,31 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2029
2306
  if (ts.isFunctionDeclaration(fn) &&
2030
2307
  fn.name &&
2031
2308
  fn.parent === this.sf &&
2032
- this.checker.getSymbolAtLocation(fn.name)?.declarations?.length === 1 &&
2033
2309
  this.acceptsSingleElement(declaration.type)) {
2034
2310
  const flags = ts.getCombinedModifierFlags(fn);
2035
- this.elementChildren.push({
2036
- start: fn.getStart(this.sf),
2037
- exported: flags & ts.ModifierFlags.Export
2038
- ? flags & ts.ModifierFlags.Default
2039
- ? 'default'
2040
- : fn.name.text
2041
- : undefined,
2042
- });
2311
+ const declarations = this.checker.getSymbolAtLocation(fn.name)?.declarations;
2312
+ // TypeScript records a property written on the function as an additional
2313
+ // declaration. Ordinary displayName assignments still have one function body.
2314
+ if (declarations?.includes(fn) &&
2315
+ declarations.every((item) => item === fn ||
2316
+ (!(flags & ts.ModifierFlags.Export) &&
2317
+ ts.isIdentifier(item) &&
2318
+ this.isOrdinaryElementMetadata(item, fn))))
2319
+ this.elementChildren.push({
2320
+ start: fn.getStart(this.sf),
2321
+ exported: flags & ts.ModifierFlags.Export
2322
+ ? flags & ts.ModifierFlags.Default
2323
+ ? 'default'
2324
+ : fn.name.text
2325
+ : undefined,
2326
+ });
2043
2327
  }
2044
2328
  this.note(RULE.elementChildren, 'warning', fn, 'Nested TSRX children arrive as a render block. Pass element values explicitly with `children={...}` to keep this slot’s element type. If it only renders content and should accept nested templates, include `ChildrenBlock` from `octane/tsrx-boundary` in the children type.');
2045
2329
  }
2330
+ isOrdinaryElementMetadata(ref, fn) {
2331
+ return (literalDisplayNameAssignment(ref, fn) &&
2332
+ (this.ordinaryElementMetadata ??= !hasPrototypeAccess(this.sf)));
2333
+ }
2046
2334
  // The caller already established that this is an element-only slot. Array-only
2047
2335
  // and parameterized element types still need the author's review.
2048
2336
  acceptsSingleElement(type) {
@@ -2364,8 +2652,60 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2364
2652
  return null;
2365
2653
  return { name: node.name.text, module: entry.module };
2366
2654
  }
2655
+ if (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression)) {
2656
+ const name = node.argumentExpression.text;
2657
+ if (this.canMigrateComputedReactCall(node, name))
2658
+ return { name, module: 'react' };
2659
+ }
2367
2660
  return null;
2368
2661
  }
2662
+ canMigrateComputedReactCall(node, name) {
2663
+ const parent = node.parent;
2664
+ if (!isComputedReactHookOrRef(name) ||
2665
+ name === 'useFormState' ||
2666
+ name === 'useFormStatus' ||
2667
+ !ts.isCallExpression(parent) ||
2668
+ parent.expression !== node ||
2669
+ ts.isOptionalChain(parent) ||
2670
+ !ts.isIdentifier(node.expression))
2671
+ return false;
2672
+ const declaration = this.declarationOf(node.expression);
2673
+ if (!declaration ||
2674
+ !ts.isNamespaceImport(declaration) ||
2675
+ this.imports.get(declaration)?.module !== 'react' ||
2676
+ declaration.parent.isTypeOnly ||
2677
+ declaration.parent.parent.attributes ||
2678
+ this.lostComments(node.getStart(this.sf), node.end, '').length)
2679
+ return false;
2680
+ return this.closedReactNamespace(declaration);
2681
+ }
2682
+ reactNamespaceCalls;
2683
+ closedReactNamespace(declaration) {
2684
+ // Bundlers can expose the mutable CommonJS object through a default import
2685
+ // or the namespace's default member. Require the namespace to stay local.
2686
+ return (this.reactNamespaceCalls ??=
2687
+ [...this.imports].every(([binding, item]) => item.module !== 'react' ||
2688
+ item.typeOnly ||
2689
+ binding === declaration ||
2690
+ (!item.namespace && item.imported !== 'default')) &&
2691
+ !(/eval|\\u/.test(this.source) && hasEval(this.sf)) &&
2692
+ this.namespaceMemberCalls(declaration));
2693
+ }
2694
+ namespaceMemberCalls(declaration) {
2695
+ return this.localUses(declaration.name).every((ref) => {
2696
+ if (inTypeNode(ref))
2697
+ return true;
2698
+ const member = ref.parent;
2699
+ return ((ts.isPropertyAccessExpression(member) || ts.isElementAccessExpression(member)) &&
2700
+ member.expression === ref &&
2701
+ ts.isCallExpression(member.parent) &&
2702
+ member.parent.expression === member &&
2703
+ (ts.isPropertyAccessExpression(member)
2704
+ ? member.name.text !== 'default'
2705
+ : ts.isStringLiteralLike(member.argumentExpression) &&
2706
+ member.argumentExpression.text !== 'default'));
2707
+ });
2708
+ }
2369
2709
  line(node) {
2370
2710
  return this.sf.getLineAndCharacterOfPosition(node.getStart(this.sf)).line + 1;
2371
2711
  }
@@ -2390,8 +2730,17 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2390
2730
  }
2391
2731
  // A React import of the same name becomes this import.
2392
2732
  const prior = this.apiLocals.get(name);
2393
- const collides = (this.declared.has(name) || this.readsGlobal(name)) &&
2394
- !(prior && mapReactImport(prior.module, prior.imported, prior.typeOnly)?.name === name);
2733
+ const originalFactory = module === 'octane' && name === 'createElement' && prior?.module === 'react';
2734
+ const canReuse = prior &&
2735
+ mapReactImport(prior.module, prior.imported, prior.typeOnly)?.name === name &&
2736
+ ![...this.imports].some(([decl, entry]) => entry === prior &&
2737
+ ts.isImportSpecifier(decl) &&
2738
+ (decl.parent.parent.parent.attributes ||
2739
+ (entry.module === 'react' &&
2740
+ entry.imported === 'Touch' &&
2741
+ this.localUses(decl.name).some(needsTouchValueOrNamespace)) ||
2742
+ (originalFactory && this.retainedReactFactoryImport(decl))));
2743
+ const collides = (this.declared.has(name) || this.readsGlobal(name)) && !canReuse;
2395
2744
  let local = collides ? `Octane${name[0].toUpperCase()}${name.slice(1)}` : name;
2396
2745
  while (collides && (this.declared.has(local) || this.readsGlobal(local)))
2397
2746
  local += '_';
@@ -2586,14 +2935,34 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2586
2935
  return this.rewriteReexport(node);
2587
2936
  if (ts.isCallExpression(node))
2588
2937
  return this.rewriteCall(node);
2938
+ if (ts.isAwaitExpression(node) && ts.isPropertyAccessExpression(node.expression))
2939
+ this.checkServerStream(node);
2589
2940
  if (ts.isPropertyAccessExpression(node)) {
2590
2941
  const text = this.rewriteMember(node);
2591
2942
  if (text === null)
2592
2943
  this.checkProjectReactEventMember(node, node.name.text);
2593
2944
  return text;
2594
2945
  }
2595
- if (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression))
2596
- this.checkProjectReactEventMember(node, node.argumentExpression.text);
2946
+ if (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression)) {
2947
+ const name = node.argumentExpression.text;
2948
+ const mapped = this.checkReactNamespaceMember(node, name);
2949
+ const module = mapped && this.importOf(node.expression)?.module;
2950
+ const formHook = name === 'useFormState' || name === 'useFormStatus';
2951
+ if (mapped &&
2952
+ (module === 'react' || (module === 'react-dom' && formHook)) &&
2953
+ isComputedReactHookOrRef(name)) {
2954
+ if (this.canMigrateComputedReactCall(node, name)) {
2955
+ this.count(RULE.import);
2956
+ return this.require(mapped.module, mapped.name, false);
2957
+ }
2958
+ this.note(RULE.unsupported, 'error', node, formHook && module === 'react'
2959
+ ? `React DOM exports \`${name}\`. Check this computed React namespace access before migrating it.`
2960
+ : formHook
2961
+ ? `Import React DOM's \`${name}\` by name before migrating this computed access.`
2962
+ : `Computed React \`${name}\` migration requires a direct call on a local React namespace import. Review the receiver and the call before migrating it.`);
2963
+ }
2964
+ this.checkProjectReactEventMember(node, name);
2965
+ }
2597
2966
  if (ts.isQualifiedName(node))
2598
2967
  return this.rewriteQualifiedType(node);
2599
2968
  if (ts.isImportTypeNode(node))
@@ -2703,7 +3072,176 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2703
3072
  }
2704
3073
  return null;
2705
3074
  }
3075
+ retainedRegistryFactoryImport(react) {
3076
+ const resolveRegistry = this.options.retainedRegistry;
3077
+ if (!resolveRegistry)
3078
+ return false;
3079
+ // Check the registration shape without the inert exported constants.
3080
+ const statements = this.sf.statements.filter((statement) => {
3081
+ if (!ts.isVariableStatement(statement) ||
3082
+ statement.modifiers?.length !== 1 ||
3083
+ statement.modifiers[0].kind !== ts.SyntaxKind.ExportKeyword ||
3084
+ (statement.declarationList.flags & ts.NodeFlags.BlockScoped) !== ts.NodeFlags.Const ||
3085
+ statement.declarationList.declarations.length !== 1)
3086
+ return true;
3087
+ const { name, initializer, type } = statement.declarationList.declarations[0];
3088
+ return !ts.isIdentifier(name) || !!type || !initializer || !isPrimitiveLiteral(initializer);
3089
+ });
3090
+ const bindings = react.importClause?.namedBindings;
3091
+ if (statements.length !== 3 ||
3092
+ !statements.slice(0, 2).every(ts.isImportDeclaration) ||
3093
+ react.attributes ||
3094
+ react.importClause?.name ||
3095
+ !bindings ||
3096
+ !ts.isNamedImports(bindings) ||
3097
+ bindings.elements.length !== 1 ||
3098
+ !this.options.originalReact)
3099
+ return false;
3100
+ const binding = this.importOf(bindings.elements[0].name);
3101
+ if (!binding || binding.typeOnly || binding.imported !== 'createElement')
3102
+ return false;
3103
+ // Only a registration module can keep the descriptor without also moving
3104
+ // a consumer of it in the same file.
3105
+ const declaration = statements[2];
3106
+ if (!ts.isVariableStatement(declaration) ||
3107
+ !(declaration.declarationList.flags & ts.NodeFlags.Const))
3108
+ return false;
3109
+ const [entry, extra] = declaration.declarationList.declarations;
3110
+ const use = entry?.initializer;
3111
+ if (extra ||
3112
+ !entry ||
3113
+ !ts.isIdentifier(entry.name) ||
3114
+ entry.type ||
3115
+ !use ||
3116
+ !ts.isCallExpression(use) ||
3117
+ use.questionDotToken ||
3118
+ use.typeArguments ||
3119
+ !ts.isIdentifier(use.expression))
3120
+ return false;
3121
+ const owner = this.importOf(use.expression);
3122
+ if (!owner || owner.namespace || owner.typeOnly)
3123
+ return false;
3124
+ const [name, object, trailing] = use.arguments;
3125
+ if (!name ||
3126
+ !ts.isStringLiteral(name) ||
3127
+ !object ||
3128
+ !ts.isObjectLiteralExpression(object) ||
3129
+ trailing ||
3130
+ object.properties.length !== 1)
3131
+ return false;
3132
+ const [property] = object.properties;
3133
+ if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name))
3134
+ return false;
3135
+ const arrow = property.initializer;
3136
+ if (!ts.isArrowFunction(arrow) ||
3137
+ arrow.type ||
3138
+ arrow.modifiers ||
3139
+ arrow.typeParameters ||
3140
+ arrow.parameters.length)
3141
+ return false;
3142
+ const output = singleCallbackExpression(arrow.body);
3143
+ if (!output)
3144
+ return false;
3145
+ const call = skipParens(output);
3146
+ if (!ts.isCallExpression(call) ||
3147
+ call.questionDotToken ||
3148
+ call.typeArguments ||
3149
+ this.importOf(call.expression) !== binding)
3150
+ return false;
3151
+ const [tag, props, ...children] = call.arguments;
3152
+ if (!tag ||
3153
+ !ts.isStringLiteral(tag) ||
3154
+ (props &&
3155
+ props.kind !== ts.SyntaxKind.NullKeyword &&
3156
+ (!ts.isObjectLiteralExpression(props) ||
3157
+ !props.properties.every((item) => ts.isPropertyAssignment(item) &&
3158
+ ts.isIdentifier(item.name) &&
3159
+ ts.isStringLiteral(item.initializer)))) ||
3160
+ !children.every(ts.isStringLiteral))
3161
+ return false;
3162
+ const types = this.options.types;
3163
+ if (!types || types.sourceFile.text !== this.source)
3164
+ return false;
3165
+ const file = resolveRegistry(owner.module);
3166
+ if (!file)
3167
+ return false;
3168
+ const { sourceFile, checker } = types;
3169
+ const peer = nodeSpanning(sourceFile, call.getStart(this.sf), call.end);
3170
+ const callee = nodeSpanning(sourceFile, use.expression.getStart(this.sf), use.expression.end);
3171
+ const specifier = nodeSpanning(sourceFile, react.moduleSpecifier.getStart(this.sf), react.moduleSpecifier.end);
3172
+ if (!peer || !ts.isCallExpression(peer) || !callee || !specifier)
3173
+ return false;
3174
+ const signatures = checker.getTypeAtLocation(callee).getCallSignatures();
3175
+ const signature = signatures[0];
3176
+ const decl = signature?.declaration;
3177
+ if (signatures.length !== 1 ||
3178
+ signature.typeParameters?.length ||
3179
+ !decl ||
3180
+ !ts.isFunctionDeclaration(decl) ||
3181
+ !decl.body ||
3182
+ decl.getSourceFile() !== file ||
3183
+ !(ts.getCombinedModifierFlags(decl) & ts.ModifierFlags.Export))
3184
+ return false;
3185
+ const module = checker.getSymbolAtLocation(specifier);
3186
+ const reactNode = module && checker.getExportsOfModule(module).find((symbol) => symbol.name === 'ReactNode');
3187
+ return !!reactNode && checker.getContextualType(peer)?.aliasSymbol === reactNode;
3188
+ }
2706
3189
  // ---------------------------------------------------------------- imports
3190
+ retainedHookSetup() {
3191
+ return {
3192
+ calleeName: (callee) => this.calleeName(callee),
3193
+ nativeOutput: (element) => this.nativeOutput(element, this.localUses),
3194
+ originalReact: () => this.options.originalReact === true,
3195
+ };
3196
+ }
3197
+ warnRetainedPrivateContext(module, name, site) {
3198
+ const resolution = module.endsWith('.js')
3199
+ ? ' and the import resolves to its TypeScript source'
3200
+ : '';
3201
+ this.note(RULE.bindings, 'warning', site, `If native setup reaches the unchanged ${module} export ${name} after its module initializes${resolution}, its private helper calls React's useContext. Provide a compiled Octane hook or keep the component under React.`);
3202
+ }
3203
+ warnRetainedStore(module, name, site) {
3204
+ this.note(RULE.bindings, 'warning', site, `If native setup reaches the unchanged ${module} export ${name} through the original workspace entry, its store hook calls React. Provide a compiled Octane hook or keep the component under React.`);
3205
+ }
3206
+ checkRetainedNamespaceHooks(module, binding) {
3207
+ const retainedHook = this.options.localReactHook;
3208
+ if (!retainedHook)
3209
+ return;
3210
+ let reported;
3211
+ for (const ref of renderUses(this.localUses(binding))) {
3212
+ const member = ref.parent;
3213
+ if (!ts.isPropertyAccessExpression(member) && !ts.isElementAccessExpression(member))
3214
+ continue;
3215
+ const call = member.parent;
3216
+ if (member.expression !== ref ||
3217
+ ts.isOptionalChain(member) ||
3218
+ !ts.isCallExpression(call) ||
3219
+ call.expression !== member ||
3220
+ ts.isOptionalChain(call))
3221
+ continue;
3222
+ const name = ts.isPropertyAccessExpression(member)
3223
+ ? member.name.text
3224
+ : ts.isStringLiteralLike(member.argumentExpression) && member.argumentExpression.text;
3225
+ if (!name || !/^use[A-Z0-9]/.test(name) || reported?.has(name))
3226
+ continue;
3227
+ const setup = this.retainedHookSetup();
3228
+ if (!nativeSetupHook(member, this.localUses, this.checker) &&
3229
+ !nativeSetupHook(member, this.localUses, this.checker, setup) &&
3230
+ !nativeSetupHook(member, this.localUses, this.checker, { ...setup, contextSetup: true }))
3231
+ continue;
3232
+ const local = retainedHook(module, name, false);
3233
+ if (!local || typeof local === 'string')
3234
+ continue;
3235
+ if ('retainedStore' in local)
3236
+ this.warnRetainedStore(module, name, member);
3237
+ else if ('privateContext' in local &&
3238
+ nativeSetupHook(member, this.localUses, this.checker, { ...setup, privateContext: true }))
3239
+ this.warnRetainedPrivateContext(module, name, member);
3240
+ else
3241
+ continue;
3242
+ (reported ??= new Set()).add(name);
3243
+ }
3244
+ }
2707
3245
  rewriteImport(node) {
2708
3246
  const native = this.pathSvgImports.get(node);
2709
3247
  if (native) {
@@ -2719,15 +3257,43 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2719
3257
  this.note(RULE.unsupported, 'error', node, "Three.js elements compile only in a `.three.tsrx` module, Octane's three renderer: move the scene components there and mount them with `root.render(Scene, props)`.");
2720
3258
  }
2721
3259
  if (module in REACT_MODULES) {
3260
+ if (module === 'react' && this.retainedRegistryFactoryImport(node))
3261
+ return null;
3262
+ const clause = node.importClause;
3263
+ const bindings = clause?.namedBindings;
3264
+ if (module === 'react' &&
3265
+ node.attributes &&
3266
+ clause &&
3267
+ bindings &&
3268
+ ts.isNamedImports(bindings)) {
3269
+ const touch = bindings.elements.filter((element) => (clause.isTypeOnly || element.isTypeOnly) &&
3270
+ (element.propertyName ?? element.name).text === 'Touch');
3271
+ // An erased default import may also be written inside a named import list.
3272
+ const defaultTouch = bindings.elements.some((element) => (clause.isTypeOnly || element.isTypeOnly) &&
3273
+ element.propertyName?.text === 'default' &&
3274
+ this.localUses(element.name).some((ref) => directMember(ref)?.text === 'Touch'));
3275
+ if (touch.length > 0) {
3276
+ // Preserve the authored resolution condition and its React export.
3277
+ for (const element of touch) {
3278
+ if (this.localUses(element.name).some(needsTouchValueOrNamespace))
3279
+ this.note(RULE.unsupported, 'error', element, "`Touch` from 'react' has no Octane equivalent for this use.");
3280
+ }
3281
+ return null;
3282
+ }
3283
+ if (defaultTouch)
3284
+ return null;
3285
+ }
2722
3286
  this.importSlots.push(node);
2723
3287
  return `\u0000IMPORT${this.importSlots.length - 1}\u0000`;
2724
3288
  }
2725
3289
  const clause = node.importClause;
2726
3290
  const bindings = clause?.namedBindings;
2727
- if (bindings &&
2728
- ts.isNamespaceImport(bindings) &&
2729
- this.radixSlotImports?.get(bindings.name) === 'original')
2730
- return null;
3291
+ if (clause && bindings && ts.isNamespaceImport(bindings)) {
3292
+ if (this.radixSlotImports?.get(bindings.name) === 'original')
3293
+ return null;
3294
+ if (!clause.isTypeOnly && !node.attributes)
3295
+ this.checkRetainedNamespaceHooks(module, bindings.name);
3296
+ }
2731
3297
  if (clause && bindings && ts.isNamedImports(bindings)) {
2732
3298
  const moved = new Map();
2733
3299
  const kept = [];
@@ -2754,11 +3320,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2754
3320
  const nativeOnly = sites.length > 0 &&
2755
3321
  sites.every(Boolean) &&
2756
3322
  (!sites.includes('afterRefs') || this.options.originalReact === true);
2757
- const setup = {
2758
- calleeName: (callee) => this.calleeName(callee),
2759
- nativeOutput: (element) => this.nativeOutput(element, this.localUses),
2760
- originalReact: () => this.options.originalReact === true,
2761
- };
3323
+ const setup = this.retainedHookSetup();
2762
3324
  const call = refs[sites.indexOf('first')] ??
2763
3325
  (nativeOnly
2764
3326
  ? refs[0]
@@ -2783,8 +3345,10 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2783
3345
  privateContext: true,
2784
3346
  }));
2785
3347
  if (advisorySite)
2786
- this.note(RULE.bindings, 'warning', advisorySite, `If native setup reaches the unchanged ${module} export ${name} after its module initializes, its private helper calls React's useContext. Provide a compiled Octane hook or keep the component under React.`);
3348
+ this.warnRetainedPrivateContext(module, name, advisorySite);
2787
3349
  }
3350
+ else if (site && local && typeof local !== 'string' && 'retainedStore' in local)
3351
+ this.warnRetainedStore(module, name, site);
2788
3352
  }
2789
3353
  if (!dest) {
2790
3354
  kept.push(item);
@@ -2831,7 +3395,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2831
3395
  if (!port ||
2832
3396
  ts
2833
3397
  .getLeadingCommentRanges(this.source, node.pos)
2834
- ?.some((range) => this.source.slice(range.pos, range.end).includes('No Octane port of')))
3398
+ ?.some(({ pos, end }) => /(?:No Octane port|Retained React import) of/.test(this.source.slice(pos, end))))
2835
3399
  return text;
2836
3400
  return `// ${portComment(port)}\n${text ?? node.getText(this.sf)}`;
2837
3401
  }
@@ -2855,6 +3419,16 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2855
3419
  const type = clause.isTypeOnly ? 'type ' : '';
2856
3420
  const bindings = ts.isImportClause(clause) ? clause.namedBindings : clause.exportClause;
2857
3421
  if (bindings && ts.isNamespaceImport(bindings)) {
3422
+ if (next === '@octanejs/remix-router' &&
3423
+ clause.isTypeOnly &&
3424
+ this.localUses(bindings.name).some((ref) => {
3425
+ const member = ref.parent;
3426
+ return (ts.isQualifiedName(member) &&
3427
+ member.left === ref &&
3428
+ !isValueTypeQuery(member) &&
3429
+ routerLoadContext(module, member.right.text));
3430
+ }))
3431
+ return node.getText(this.sf);
2858
3432
  if (namespace === null)
2859
3433
  return null;
2860
3434
  const local = bindings.name.text;
@@ -2866,10 +3440,19 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2866
3440
  const kept = [];
2867
3441
  const values = [];
2868
3442
  const types = [];
3443
+ let retainedRouterTypes;
2869
3444
  let renamed = false;
2870
3445
  for (const element of bindings.elements) {
2871
3446
  const imported = (element.propertyName ?? element.name).text;
2872
3447
  const local = element.name.text;
3448
+ if (next === '@octanejs/remix-router' &&
3449
+ (clause.isTypeOnly || element.isTypeOnly) &&
3450
+ routerLoadContext(module, imported)) {
3451
+ (retainedRouterTypes ??= new Set()).add(element);
3452
+ const name = element.propertyName ?? element.name;
3453
+ kept.push(this.source.slice(name.getStart(this.sf), element.end));
3454
+ continue;
3455
+ }
2873
3456
  if (module === 'radix-ui' && imported === 'Slot' && next === '@octanejs/radix') {
2874
3457
  if (!ts.isImportSpecifier(element)) {
2875
3458
  this.note(RULE.binding, 'error', element, 'The Octane binding has no Radix Slot namespace to re-export.');
@@ -2907,8 +3490,19 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2907
3490
  }
2908
3491
  if (namespace === null && kept.length === 0 && !renamed)
2909
3492
  return null;
3493
+ if (retainedRouterTypes) {
3494
+ if (values.length === 0 || node.attributes)
3495
+ return node.getText(this.sf);
3496
+ const available = this.options.bindingExports?.(module, next);
3497
+ if (available && !this.hasBindingExports(node, next, available, retainedRouterTypes))
3498
+ return node.getText(this.sf);
3499
+ }
2910
3500
  this.count(RULE.import);
2911
- const lines = kept.length > 0 ? [`${keyword} ${type}{ ${kept.join(', ')} } ${from(module)}`] : [];
3501
+ const lines = kept.length > 0
3502
+ ? [
3503
+ `${keyword} ${retainedRouterTypes ? 'type ' : type}{ ${kept.join(', ')} } ${from(module)}`,
3504
+ ]
3505
+ : [];
2912
3506
  if (values.length > 0) {
2913
3507
  lines.push(namespace === null
2914
3508
  ? `${keyword} ${type}{ ${values.join(', ')} } ${from(next)}`
@@ -2954,10 +3548,17 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2954
3548
  for (const [index, item] of exports.elements.entries()) {
2955
3549
  const text = this.source.slice(item.getFullStart(), exports.elements[index + 1]?.getFullStart() ?? exports.end - 1);
2956
3550
  const name = (item.propertyName ?? item.name).text;
2957
- if (mapReactImport(module, name, node.isTypeOnly || item.isTypeOnly)?.module === module) {
3551
+ const typeOnly = node.isTypeOnly || item.isTypeOnly;
3552
+ const mapped = mapReactImport(module, name, typeOnly);
3553
+ if (mapped?.module === module) {
2958
3554
  retained.push(text);
2959
3555
  continue;
2960
3556
  }
3557
+ if (!typeOnly && !mapped && Object.hasOwn(UNSUPPORTED_VALUES, name)) {
3558
+ retained.push(text);
3559
+ this.note(RULE.unsupported, 'error', item, `${UNSUPPORTED_VALUES[name]} This re-export stays on React.`);
3560
+ continue;
3561
+ }
2961
3562
  if (name === 'SubmitEvent' ||
2962
3563
  name === 'SubmitEventHandler' ||
2963
3564
  name === 'ReactEventHandler') {
@@ -2965,6 +3566,10 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2965
3566
  this.note(RULE.unsupported, 'error', item, 'Review the React event re-export and define an explicit native event type.');
2966
3567
  }
2967
3568
  else {
3569
+ if (typeOnly &&
3570
+ mapped?.name !== name &&
3571
+ mapReactImport(module, name, false)?.name !== name)
3572
+ this.note(REACT_TYPE_PROJECTION, 'error', item, `Octane has no export \`${name}\`.`);
2968
3573
  migrated.push(text);
2969
3574
  }
2970
3575
  }
@@ -2993,6 +3598,13 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
2993
3598
  const next = this.resolve(specifier.text);
2994
3599
  if (next === null || next === specifier.text)
2995
3600
  return null;
3601
+ if (next === '@octanejs/remix-router' &&
3602
+ ts.isModuleDeclaration(node) &&
3603
+ node.body &&
3604
+ ts.isModuleBlock(node.body) &&
3605
+ node.body.statements.some((statement) => ts.isInterfaceDeclaration(statement) &&
3606
+ routerLoadContext(specifier.text, statement.name.text)))
3607
+ return null;
2996
3608
  const available = this.options.bindingExports?.(specifier.text, next);
2997
3609
  if (available && !this.hasBindingExports(node, next, available))
2998
3610
  return null;
@@ -3020,7 +3632,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3020
3632
  return this.replaceSpecifier(node, specifier, next);
3021
3633
  }
3022
3634
  /** Check known exports without guessing at a whole namespace. */
3023
- hasBindingExports(node, binding, available) {
3635
+ hasBindingExports(node, binding, available, retained) {
3024
3636
  const hasDifferentType = (name) => binding === '@octanejs/motion' && name === 'MotionConfigContext';
3025
3637
  const check = (site, name, needsType = false) => {
3026
3638
  const missingType = needsType && hasDifferentType(name);
@@ -3038,6 +3650,8 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3038
3650
  return check(node);
3039
3651
  let supported = true;
3040
3652
  for (const element of elements) {
3653
+ if (retained?.has(element))
3654
+ continue;
3041
3655
  const name = (element.propertyName ?? element.name).text;
3042
3656
  // A re-export can expose both the type and the value to another module.
3043
3657
  const typeUse = hasDifferentType(name) &&
@@ -3135,15 +3749,37 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3135
3749
  return null;
3136
3750
  const specifier = argument.literal;
3137
3751
  const module = REACT_MODULES[specifier.text];
3138
- if (module === undefined)
3139
- return this.rewriteSpecifier(node, specifier);
3140
3752
  const qualifier = node.qualifier;
3141
- const name = qualifier && ts.isIdentifier(qualifier) ? qualifier.text : null;
3142
- if (node.isTypeOf &&
3143
- name &&
3144
- mapReactImport(specifier.text, name, true)?.module === specifier.text) {
3753
+ if (module === undefined) {
3754
+ if (!node.isTypeOf &&
3755
+ qualifier &&
3756
+ routerLoadContext(specifier.text, firstQualifiedName(qualifier).text) &&
3757
+ this.resolve(specifier.text) === '@octanejs/remix-router')
3758
+ return null;
3759
+ return this.rewriteSpecifier(node, specifier);
3760
+ }
3761
+ if (qualifier &&
3762
+ firstQualifiedName(qualifier).text === 'Touch' &&
3763
+ (specifier.text === 'react-dom' ||
3764
+ (specifier.text === 'react' &&
3765
+ (node.attributes || node.isTypeOf || ts.isQualifiedName(qualifier))))) {
3766
+ this.reportRetainedTouchType(specifier.text, node, node.isTypeOf, ts.isQualifiedName(qualifier));
3145
3767
  return null;
3146
3768
  }
3769
+ const name = qualifier && ts.isIdentifier(qualifier) ? qualifier.text : null;
3770
+ let missingValue = false;
3771
+ if (specifier.text === 'react' && node.isTypeOf && qualifier) {
3772
+ let value = qualifier;
3773
+ while (ts.isQualifiedName(value))
3774
+ value = value.left;
3775
+ const retained = mapReactImport('react', value.text, true)?.module === 'react';
3776
+ if (retained)
3777
+ return null;
3778
+ if (!hasOctaneValue(value.text)) {
3779
+ missingValue = true;
3780
+ this.note(REACT_TYPE_PROJECTION, 'error', value, `Octane has no value export \`${value.text}\`.`);
3781
+ }
3782
+ }
3147
3783
  if (specifier.text === 'react' && !node.isTypeOf) {
3148
3784
  const event = this.nativeEventType(node, name);
3149
3785
  if (event !== undefined) {
@@ -3153,9 +3789,12 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3153
3789
  }
3154
3790
  }
3155
3791
  this.count(RULE.import);
3156
- const renamed = name === null ? null : mapQualifiedType(name);
3157
- if (name !== null && renamed === null) {
3158
- this.note(RULE.unsupported, 'warning', node, `Octane has no type \`${name}\`.`);
3792
+ const renamed = name === null || missingValue
3793
+ ? null
3794
+ : mapQualifiedType(name, specifier.text, node.isTypeOf, node.typeArguments?.length ?? 0);
3795
+ if (name !== null && renamed === null && !missingValue) {
3796
+ const unresolvedProjection = specifier.text === 'react' && !node.isTypeOf;
3797
+ this.note(unresolvedProjection ? REACT_TYPE_PROJECTION : RULE.unsupported, unresolvedProjection ? 'error' : 'warning', node, `Octane has no type \`${name}\`.`);
3159
3798
  }
3160
3799
  const quote = this.source[specifier.getStart(this.sf)];
3161
3800
  const head = this.span(node, node.getStart(this.sf), specifier.getStart(this.sf), PLAIN) +
@@ -3173,6 +3812,99 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3173
3812
  renamed +
3174
3813
  this.span(node, qualifier.end, node.end, PLAIN));
3175
3814
  }
3815
+ retainedReactFactory(ref) {
3816
+ const call = ref.parent;
3817
+ if (!ts.isCallExpression(call) ||
3818
+ call.expression !== ref ||
3819
+ ts.isOptionalChain(call) ||
3820
+ call.typeArguments?.length)
3821
+ return false;
3822
+ const [tag, props, ...children] = call.arguments;
3823
+ if (!tag ||
3824
+ !ts.isStringLiteral(tag) ||
3825
+ props?.kind !== ts.SyntaxKind.NullKeyword ||
3826
+ !children.every(ts.isStringLiteral))
3827
+ return false;
3828
+ let value = call;
3829
+ while (ts.isParenthesizedExpression(value.parent))
3830
+ value = value.parent;
3831
+ const direct = value.parent;
3832
+ const block = ts.isReturnStatement(direct) &&
3833
+ ts.isBlock(direct.parent) &&
3834
+ direct.parent.statements.length === 1
3835
+ ? direct.parent
3836
+ : null;
3837
+ const callback = block ? block.parent : direct;
3838
+ if (!ts.isArrowFunction(callback) ||
3839
+ callback.body !== (block ?? value) ||
3840
+ callback.parameters.length ||
3841
+ callback.type ||
3842
+ callback.typeParameters?.length ||
3843
+ callback.modifiers?.length)
3844
+ return false;
3845
+ const property = callback.parent;
3846
+ if (!ts.isPropertyAssignment(property) ||
3847
+ property.initializer !== callback ||
3848
+ !ts.isIdentifier(property.name) ||
3849
+ property.name.text === '__proto__' ||
3850
+ property.parent.properties.length !== 1)
3851
+ return false;
3852
+ const expression = property.parent.parent;
3853
+ const attribute = expression.parent;
3854
+ if (!ts.isJsxExpression(expression) ||
3855
+ expression.dotDotDotToken ||
3856
+ !ts.isJsxAttribute(attribute) ||
3857
+ attribute.initializer !== expression ||
3858
+ !ts.isIdentifier(attribute.name) ||
3859
+ attribute.name.text !== 'props')
3860
+ return false;
3861
+ const island = attribute.parent.parent;
3862
+ if (!ts.isJsxSelfClosingElement(island) || island.attributes.properties.length !== 2)
3863
+ return false;
3864
+ const component = island.attributes.properties.find((item) => item !== attribute);
3865
+ if (!component ||
3866
+ !ts.isJsxAttribute(component) ||
3867
+ !ts.isIdentifier(component.name) ||
3868
+ component.name.text !== 'component' ||
3869
+ !component.initializer ||
3870
+ !ts.isJsxExpression(component.initializer) ||
3871
+ !component.initializer.expression)
3872
+ return false;
3873
+ const named = (id) => {
3874
+ if (!ts.isIdentifier(id))
3875
+ return;
3876
+ const decl = this.declarationOf(id);
3877
+ const entry = decl && this.imports.get(decl);
3878
+ if (decl &&
3879
+ ts.isImportSpecifier(decl) &&
3880
+ entry &&
3881
+ !entry.typeOnly &&
3882
+ !decl.parent.parent.parent.attributes)
3883
+ return entry;
3884
+ };
3885
+ const bridge = named(island.tagName);
3886
+ const owner = named(component.initializer.expression);
3887
+ return (!!bridge &&
3888
+ !!owner &&
3889
+ nativeReactCompat(bridge.module, bridge.imported) &&
3890
+ this.options.retainedReactBridgeComponent?.(bridge.module, owner.module, owner.imported) ===
3891
+ true);
3892
+ }
3893
+ retainedReactFactoryImport(element) {
3894
+ const binding = this.imports.get(element);
3895
+ if (binding?.module !== 'react' ||
3896
+ binding.imported !== 'createElement' ||
3897
+ binding.typeOnly ||
3898
+ element.parent.parent.parent.attributes ||
3899
+ this.target !== 'tsrx' ||
3900
+ !this.hasReactBridge ||
3901
+ !this.options.retainedReactBridgeComponent ||
3902
+ !this.options.originalReact ||
3903
+ hasEval(this.sf))
3904
+ return false;
3905
+ const refs = this.localUses(element.name).filter((ref) => !inTypeNode(ref));
3906
+ return refs.length > 0 && refs.every((ref) => this.retainedReactFactory(ref));
3907
+ }
3176
3908
  /**
3177
3909
  * Fill each React import placeholder. The first one carries every Octane
3178
3910
  * import the module needs, the module's own specifiers first; the others
@@ -3192,8 +3924,10 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3192
3924
  };
3193
3925
  /** React specifiers with no Octane export stay on React, for a person. */
3194
3926
  const kept = new Map();
3927
+ const typeNamespaces = [];
3195
3928
  /** Locals of React's `jsx` factories, which a JSX runtime consumer calls. */
3196
3929
  const factories = [];
3930
+ let retainsCreateElement = false;
3197
3931
  for (const node of this.importSlots) {
3198
3932
  const module = node.moduleSpecifier.text;
3199
3933
  const clause = node.importClause;
@@ -3203,17 +3937,46 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3203
3937
  const namespace = clause.name?.text ??
3204
3938
  (bindings && ts.isNamespaceImport(bindings) ? bindings.name.text : null);
3205
3939
  // Members the rewrite could not map keep the namespace alive.
3206
- if (namespace && this.used.has(namespace))
3940
+ if (namespace && this.retainedTypeNamespaces.has(clause)) {
3941
+ if (node.attributes) {
3942
+ typeNamespaces.push(node.getText(this.sf));
3943
+ continue;
3944
+ }
3945
+ // A static type query can follow a value chain that an import() type cannot.
3946
+ typeNamespaces.push(clause.name && bindings && ts.isNamedImports(bindings)
3947
+ ? this.source.slice(node.getStart(this.sf), clause.name.end) +
3948
+ this.source.slice(clause.end, node.end).replace(/^from\b/, ' from')
3949
+ : node.getText(this.sf));
3950
+ }
3951
+ else if (namespace && this.used.has(namespace)) {
3207
3952
  add(REACT_MODULES[module], '*', namespace, false);
3953
+ }
3208
3954
  if (!bindings || !ts.isNamedImports(bindings))
3209
3955
  continue;
3210
3956
  for (const element of bindings.elements) {
3211
3957
  const local = element.name.text;
3212
- if (!this.used.has(local))
3213
- continue;
3214
3958
  const imported = (element.propertyName ?? element.name).text;
3215
- const typeOnly = clause.isTypeOnly || element.isTypeOnly;
3216
- const mapped = mapReactImport(module, imported, typeOnly);
3959
+ let typeOnly = clause.isTypeOnly || element.isTypeOnly;
3960
+ let typeReferences = false;
3961
+ let unsupportedTouchUse = false;
3962
+ if (module === 'react' && imported === 'Touch' && !node.attributes && this.isTypeScript()) {
3963
+ // A type query still needs a value export, which Touch does not have.
3964
+ const references = this.localUses(element.name);
3965
+ typeReferences =
3966
+ references.length > 0 &&
3967
+ references.every((ref) => ts.isPartOfTypeNode(ref) || ts.isTypeOnlyExportDeclaration(ref.parent));
3968
+ unsupportedTouchUse = references.some(needsTouchValueOrNamespace);
3969
+ if (!unsupportedTouchUse)
3970
+ typeOnly ||= typeReferences;
3971
+ }
3972
+ if (!this.used.has(local) && !typeReferences)
3973
+ continue;
3974
+ if (imported === 'createElement' && this.retainedReactFactoryImport(element)) {
3975
+ add(module, imported, local, false);
3976
+ retainsCreateElement ||= local === 'createElement';
3977
+ continue;
3978
+ }
3979
+ const mapped = unsupportedTouchUse ? null : mapReactImport(module, imported, typeOnly);
3217
3980
  if (mapped) {
3218
3981
  // A name read only in types imports as a type, which bundlers elide.
3219
3982
  add(mapped.module, mapped.name, local, typeOnly || !this.valueUses.has(local));
@@ -3226,15 +3989,25 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3226
3989
  }
3227
3990
  this.note(RULE.unsupported, 'error', element, UNSUPPORTED_VALUES[imported] ??
3228
3991
  `\`${imported}\` from '${module}' has no Octane equivalent.`);
3992
+ if (unsupportedTouchUse && clause.isTypeOnly) {
3993
+ const binding = imported === local ? local : `${imported} as ${local}`;
3994
+ typeNamespaces.push(`import type { ${binding} } from ${this.quote}${module}${this.quote};`);
3995
+ continue;
3996
+ }
3229
3997
  const spec = (typeOnly ? 'type ' : '') + (imported === local ? local : `${imported} as ${local}`);
3230
3998
  kept.set(module, [...(kept.get(module) ?? []), spec]);
3231
3999
  }
3232
4000
  }
4001
+ const jsxFactory = retainsCreateElement && factories.length > 0
4002
+ ? this.require('octane', 'createElement', false)
4003
+ : 'createElement';
4004
+ if (jsxFactory !== 'createElement')
4005
+ imports.get('octane')?.delete('createElement createElement');
3233
4006
  for (const [module, names] of this.added) {
3234
4007
  for (const [name, { local, typeOnly }] of names)
3235
4008
  add(module, name, local, typeOnly);
3236
4009
  }
3237
- const lines = [];
4010
+ const lines = typeNamespaces;
3238
4011
  const quote = (module) => this.quote + module + this.quote;
3239
4012
  for (const [module, names] of imports) {
3240
4013
  const specs = [...names.values()];
@@ -3255,10 +4028,10 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3255
4028
  // React's runtime takes the key apart from the props; Octane's
3256
4029
  // `createElement` reads it from them.
3257
4030
  const params = this.isTypeScript()
3258
- ? 'type: Parameters<typeof createElement>[0], props: Record<string, unknown>, key?: string | number'
4031
+ ? `type: Parameters<typeof ${jsxFactory}>[0], props: Record<string, unknown>, key?: string | number`
3259
4032
  : 'type, props, key';
3260
4033
  const [first, ...rest] = factories;
3261
- lines.push(`function ${first}(${params}) {`, `${this.indentUnit}return createElement(type, key === undefined ? props : { ...props, key });`, '}', ...rest.map((local) => `const ${local} = ${first};`));
4034
+ lines.push(`function ${first}(${params}) {`, `${this.indentUnit}return ${jsxFactory}(type, key === undefined ? props : { ...props, key });`, '}', ...rest.map((local) => `const ${local} = ${first};`));
3262
4035
  }
3263
4036
  if (this.intrinsicPropsHelper) {
3264
4037
  lines.push(`type ${this.intrinsicPropsHelper}<Props> = {`, `${this.indentUnit}[K in keyof Props]: K extends 'className' ? string | undefined`, `${this.indentUnit}${this.indentUnit}: K extends 'style' ? import(${quote('octane')}).CSSProperties | undefined : Props[K];`, '};');
@@ -3298,7 +4071,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3298
4071
  // line, and directive lines. Anything inserted here starts a line, so
3299
4072
  // the Strong fallback can find its own directive line again. The
3300
4073
  // comment on an unported package's import stays with it.
3301
- const prologue = /^(?:#![^\n]*\n)?(?:[ \t]*(?:\/\/(?! No Octane port of)[^\n]*|\/\*[\s\S]*?\*\/[ \t]*|(['"])use [a-z ]+\1;?[^\n]*)?\r?\n)*/.exec(code);
4074
+ const prologue = /^(?:#![^\n]*\n)?(?:[ \t]*(?:\/\/(?! (?:No Octane port|Retained React import) of)[^\n]*|\/\*[\s\S]*?\*\/[ \t]*|(['"])use [a-z ]+\1;?[^\n]*)?\r?\n)*/.exec(code);
3302
4075
  return prologue ? prologue[0].length : 0;
3303
4076
  }
3304
4077
  addStrongDirective(code) {
@@ -3313,6 +4086,13 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3313
4086
  return replaced !== code ? replaced : '/** @jsxImportSource octane */\n' + code;
3314
4087
  }
3315
4088
  // ---------------------------------------------------------------- APIs
4089
+ checkServerStream(wait) {
4090
+ const originalServer = this.options.originalReactServerEntry;
4091
+ if (originalServer &&
4092
+ unreadServerStream(wait, (id) => this.declarationOf(id), (id) => this.localUses(id), originalServer) &&
4093
+ !hasEval(this.sf))
4094
+ this.note(RULE.serverRender, 'warning', wait, "Octane's renderToReadableStream can wait for a reader when it writes deferred output. Start reading before awaiting allReady, or use prerender for fully resolved HTML.");
4095
+ }
3316
4096
  rewriteMember(node) {
3317
4097
  // `<Ctx.Provider value>` is `<Ctx value>` in Octane, as in React 19.
3318
4098
  const tag = node.parent;
@@ -3333,25 +4113,32 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3333
4113
  (isTag || isValue) &&
3334
4114
  this.isContext(node.expression, node)) {
3335
4115
  if (!ts.isJsxClosingElement(tag)) {
3336
- if (isTag &&
3337
- ts.isIdentifier(node.expression) &&
3338
- this.hasLocalProviderGetter(node.expression))
3339
- this.note(CONTEXT_PROVIDER_GETTER, 'error', node, 'Replacing this React context Provider read can skip an authored getter. Review the custom Provider before migrating it.');
4116
+ let value = node;
4117
+ while (isWrapper(value.parent) && value.parent.expression === value)
4118
+ value = value.parent;
4119
+ const declaration = value.parent;
4120
+ const topLevelInitializer = ts.isVariableDeclaration(declaration) &&
4121
+ declaration.initializer === value &&
4122
+ ts.isVariableDeclarationList(declaration.parent) &&
4123
+ ts.isVariableStatement(declaration.parent.parent) &&
4124
+ declaration.parent.parent.parent === this.sf;
4125
+ const change = (isTag || topLevelInitializer) && ts.isIdentifier(node.expression)
4126
+ ? this.localProviderReadChange(node.expression, topLevelInitializer && declaration.parent.declarations[0] === declaration
4127
+ ? declaration.parent.parent
4128
+ : undefined)
4129
+ : undefined;
4130
+ if (change)
4131
+ this.note(CONTEXT_PROVIDER_GETTER, 'error', node, `Replacing this React context Provider read can skip an authored ${change}. Review the custom Provider before migrating it.`);
3340
4132
  this.count(RULE.provider);
3341
4133
  }
3342
4134
  return this.emit(node.expression, PLAIN);
3343
4135
  }
3344
- const namespace = this.importOf(node.expression);
3345
- if (namespace?.namespace && namespace.module in REACT_MODULES) {
3346
- const name = node.name.text;
3347
- const mapped = mapReactImport(namespace.module, name, false);
3348
- if (!mapped) {
3349
- this.used.add(namespace.local);
3350
- this.note(RULE.unsupported, 'error', node, UNSUPPORTED_VALUES[name] ?? `\`${node.getText(this.sf)}\` has no Octane equivalent.`);
4136
+ const reactMember = this.checkReactNamespaceMember(node, node.name.text);
4137
+ if (reactMember !== undefined) {
4138
+ if (!reactMember)
3351
4139
  return null;
3352
- }
3353
4140
  this.count(RULE.import);
3354
- return this.require(mapped.module, mapped.name, false);
4141
+ return this.require(reactMember.module, reactMember.name, false);
3355
4142
  }
3356
4143
  const member = this.rewritePackageMember(node.expression, node.name, 'error');
3357
4144
  if (member !== null)
@@ -3367,6 +4154,18 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3367
4154
  }
3368
4155
  return null;
3369
4156
  }
4157
+ checkReactNamespaceMember(node, name) {
4158
+ const namespace = this.importOf(node.expression);
4159
+ if (!namespace?.namespace || !(namespace.module in REACT_MODULES))
4160
+ return;
4161
+ const mapped = mapReactImport(namespace.module, name, false);
4162
+ if (!mapped) {
4163
+ this.used.add(namespace.local);
4164
+ this.note(RULE.unsupported, 'error', node, UNSUPPORTED_VALUES[name] ?? `\`${node.getText(this.sf)}\` has no Octane equivalent.`);
4165
+ return null;
4166
+ }
4167
+ return mapped;
4168
+ }
3370
4169
  /**
3371
4170
  * Whether `node` names a global namespace React's types declare, such as
3372
4171
  * `React` in `React.ReactNode` written without an import.
@@ -3382,6 +4181,17 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3382
4181
  ? entry.namespace && entry.module === 'react'
3383
4182
  : this.isGlobalNamespace(node, 'React');
3384
4183
  }
4184
+ reportRetainedTouchType(module, node, query, nested) {
4185
+ const message = module === 'react-dom'
4186
+ ? "`Touch` from 'react-dom' stays on React DOM. Octane only maps the type from 'react'."
4187
+ : query
4188
+ ? 'Octane has no Touch value for this type query.'
4189
+ : nested
4190
+ ? 'Octane has no Touch namespace for this type reference.'
4191
+ : null;
4192
+ if (message)
4193
+ this.note(RULE.unsupported, 'warning', node, message);
4194
+ }
3385
4195
  rewriteQualifiedType(node) {
3386
4196
  const member = this.rewritePackageMember(node.left, node.right, 'warning');
3387
4197
  if (member !== null)
@@ -3392,26 +4202,117 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3392
4202
  : !this.isGlobalNamespace(node.left, 'React')) {
3393
4203
  return null;
3394
4204
  }
3395
- if (ts.isTypeQueryNode(node.parent)) {
3396
- const mapped = mapReactImport(namespace?.module ?? 'react', node.right.text, true);
4205
+ if (ts.isIdentifier(node.left) &&
4206
+ node.right.text === 'Touch' &&
4207
+ (!namespace || namespace.module === 'react-dom' || namespace.module === 'react')) {
4208
+ const declaration = this.declarationOf(node.left);
4209
+ if (!namespace && declaration)
4210
+ return null;
4211
+ const clause = declaration && (ts.isNamespaceImport(declaration) ? declaration.parent : declaration);
4212
+ const importClause = clause && ts.isImportClause(clause) ? clause : null;
4213
+ if (!namespace || importClause) {
4214
+ let access = node;
4215
+ while (ts.isQualifiedName(access.parent) && access.parent.left === access)
4216
+ access = access.parent;
4217
+ const query = isValueTypeQuery(access);
4218
+ const nested = access !== node;
4219
+ const attributes = importClause?.parent.attributes;
4220
+ if (query ||
4221
+ (ts.isTypeReferenceNode(access.parent) &&
4222
+ (namespace?.module === 'react-dom' || nested || attributes))) {
4223
+ this.reportRetainedTouchType(namespace?.module ?? 'react', node, query, nested);
4224
+ if (importClause)
4225
+ this.retainedTypeNamespaces.add(importClause);
4226
+ return node.getText(this.sf);
4227
+ }
4228
+ }
4229
+ }
4230
+ let queried = node;
4231
+ if (namespace?.module === 'react') {
4232
+ while (ts.isQualifiedName(queried.parent) && queried.parent.left === queried)
4233
+ queried = queried.parent;
4234
+ }
4235
+ if (ts.isTypeQueryNode(queried.parent) && queried.parent.exprName === queried) {
4236
+ const name = node.right.text;
4237
+ const mapped = mapReactImport(namespace?.module ?? 'react', name, true);
3397
4238
  if (mapped?.module === 'react') {
3398
4239
  if (!namespace)
3399
4240
  return null;
4241
+ const declaration = ts.isIdentifier(node.left) ? this.declarationOf(node.left) : null;
4242
+ const clause = declaration && (ts.isNamespaceImport(declaration) ? declaration.parent : declaration);
4243
+ if (clause && ts.isImportClause(clause) && (queried !== node || clause.parent.attributes)) {
4244
+ this.retainedTypeNamespaces.add(clause);
4245
+ return node.getText(this.sf);
4246
+ }
3400
4247
  this.count(RULE.import);
3401
4248
  return this.require(mapped.module, mapped.name, true);
3402
4249
  }
4250
+ if (namespace?.module === 'react' && !hasOctaneValue(name)) {
4251
+ this.note(REACT_TYPE_PROJECTION, 'error', node, `Octane has no value export \`${name}\`.`);
4252
+ return null;
4253
+ }
3403
4254
  }
3404
- const name = mapQualifiedType(node.right.text);
4255
+ const name = mapQualifiedType(node.right.text, namespace?.module ?? 'react', ts.isTypeQueryNode(node.parent), ts.isTypeReferenceNode(node.parent) ? (node.parent.typeArguments?.length ?? 0) : 0);
3405
4256
  if (!name) {
3406
4257
  if (namespace)
3407
4258
  this.used.add(namespace.local);
3408
- this.note(RULE.unsupported, 'warning', node, `Octane has no type \`${node.getText(this.sf)}\`.`);
4259
+ const unresolvedProjection = namespace?.module === 'react' && ts.isTypeReferenceNode(node.parent);
4260
+ this.note(unresolvedProjection ? REACT_TYPE_PROJECTION : RULE.unsupported, unresolvedProjection ? 'error' : 'warning', node, `Octane has no type \`${node.getText(this.sf)}\`.`);
3409
4261
  return null;
3410
4262
  }
3411
4263
  this.count(RULE.import);
3412
4264
  return this.require('octane', name, true);
3413
4265
  }
3414
4266
  rewriteTypeReference(node, name) {
4267
+ if (ts.isExpressionWithTypeArguments(node)) {
4268
+ const root = typeHeritageRoot(node);
4269
+ const entry = root && this.importOf(root);
4270
+ const member = root && directMember(root);
4271
+ if (root && entry && member && (entry.module === 'react' || entry.module === 'react-dom')) {
4272
+ if (entry.namespace && member.text === 'Touch' && member.parent !== name) {
4273
+ const decl = this.declarationOf(root);
4274
+ const clause = decl && (ts.isNamespaceImport(decl) ? decl.parent : decl);
4275
+ if (clause && ts.isImportClause(clause)) {
4276
+ this.reportRetainedTouchType(entry.module, member, false, true);
4277
+ this.retainedTypeNamespaces.add(clause);
4278
+ return name.getText(this.sf) + this.span(node, name.end, node.end, PLAIN);
4279
+ }
4280
+ }
4281
+ if (entry.module === 'react' && entry.imported === 'Touch') {
4282
+ this.used.add(entry.local);
4283
+ return name.getText(this.sf) + this.span(node, name.end, node.end, PLAIN);
4284
+ }
4285
+ }
4286
+ }
4287
+ // Type heritage parses a qualified name as a property access expression.
4288
+ if (ts.isExpressionWithTypeArguments(node) &&
4289
+ ts.isPartOfTypeNode(node) &&
4290
+ ts.isPropertyAccessExpression(name) &&
4291
+ !name.questionDotToken &&
4292
+ ts.isIdentifier(name.expression) &&
4293
+ name.name.text === 'Touch') {
4294
+ const receiver = name.expression;
4295
+ const entry = this.importOf(receiver);
4296
+ const declaration = this.declarationOf(receiver);
4297
+ if (entry?.namespace && (entry.module === 'react' || entry.module === 'react-dom')) {
4298
+ const clause = declaration && (ts.isNamespaceImport(declaration) ? declaration.parent : declaration);
4299
+ if (clause &&
4300
+ ts.isImportClause(clause) &&
4301
+ (clause.parent.attributes || entry.module === 'react-dom')) {
4302
+ this.reportRetainedTouchType(entry.module, name, false, false);
4303
+ this.retainedTypeNamespaces.add(clause);
4304
+ return name.getText(this.sf) + this.span(node, name.end, node.end, PLAIN);
4305
+ }
4306
+ }
4307
+ if ((entry?.namespace && entry.module === 'react') ||
4308
+ (!entry &&
4309
+ !declaration &&
4310
+ this.isGlobalNamespace(receiver, 'React') &&
4311
+ ts.isExternalModule(this.sf))) {
4312
+ this.count(RULE.import);
4313
+ return this.require('octane', 'Touch', true) + this.span(node, name.end, node.end, PLAIN);
4314
+ }
4315
+ }
3415
4316
  // The global `JSX` namespace React's types declared is Octane's export.
3416
4317
  if (ts.isQualifiedName(name) && this.isGlobalNamespace(name.left, 'JSX'))
3417
4318
  this.require('octane', 'JSX', true);
@@ -3487,8 +4388,7 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3487
4388
  const root = ts.isIdentifier(receiver) ? this.constValue(receiver) : receiver;
3488
4389
  if (root && ts.isCallExpression(root) && this.calleeName(root.expression) === 'createRoot') {
3489
4390
  const rewritten = this.rewriteRootRender(node, node.arguments[0]);
3490
- if (rewritten !== null)
3491
- this.checkLocalReactRoot(node, receiver, root);
4391
+ this.checkLocalReactRoot(node, receiver, root, rewritten === null);
3492
4392
  return rewritten;
3493
4393
  }
3494
4394
  }
@@ -3509,8 +4409,14 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3509
4409
  return this.rewriteRootRender(node, node.arguments[1]);
3510
4410
  }
3511
4411
  if ((name === 'renderToString' || name === 'renderToStaticMarkup') &&
3512
- callee.module.startsWith('react-dom/server') &&
3513
- node.arguments.length === 1) {
4412
+ callee.module.startsWith('react-dom/server')) {
4413
+ if (node.arguments.length > 1) {
4414
+ this.note(BUFFERED_SSR_OPTIONS, 'error', node, 'Keep this buffered server render in React. Migrating the call can change when arguments are evaluated and which server options the renderer reads.');
4415
+ return null;
4416
+ }
4417
+ if (node.arguments.length !== 1)
4418
+ return null;
4419
+ this.checkBufferedReactComponent(node, node.arguments[0], callee.module);
3514
4420
  // React returns the HTML; Octane returns `{ html, css }`.
3515
4421
  this.count(RULE.serverRender);
3516
4422
  return ((this.rewriteRootRender(node, node.arguments[0]) ??
@@ -3518,6 +4424,24 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3518
4424
  }
3519
4425
  if (name === 'flushSync') {
3520
4426
  this.note(RULE.flushSync, 'warning', node, "Octane's `flushSync` commits synchronously but leaves the commit's `useEffect`s queued, where React runs them before returning. If code after it reads what an effect did, use `useLayoutEffect` for that effect.");
4427
+ if (callee.module === 'react-dom' &&
4428
+ !node.typeArguments?.length &&
4429
+ !ts.isOptionalChain(node) &&
4430
+ !(ts.isPropertyAccessExpression(node.expression) &&
4431
+ this.importOf(node.expression.expression)?.typeOnly)) {
4432
+ const [argument] = node.arguments;
4433
+ const value = argument && skipParens(argument);
4434
+ if (!value || (node.arguments.length === 1 && value.kind === ts.SyntaxKind.NullKeyword)) {
4435
+ // Older Octane versions need a callback even for a drain-only call.
4436
+ const close = node.getChildren(this.sf).at(-1);
4437
+ if (close?.kind === ts.SyntaxKind.CloseParenToken && close.getWidth(this.sf) > 0) {
4438
+ const start = (value ?? close).getStart(this.sf);
4439
+ return (this.span(node, node.getStart(this.sf), start, PLAIN) +
4440
+ '() => {}' +
4441
+ this.source.slice(value?.end ?? start, node.end));
4442
+ }
4443
+ }
4444
+ }
3521
4445
  return null;
3522
4446
  }
3523
4447
  if (name in DEPENDENCY_HOOKS) {
@@ -3528,6 +4452,36 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3528
4452
  }
3529
4453
  return null;
3530
4454
  }
4455
+ checkIntlProviderResources(tag) {
4456
+ const resourceHint = this.options.initializerResourceHint;
4457
+ if (!resourceHint)
4458
+ return;
4459
+ // Provider admission already excludes spreads. JSX takes the last duplicate prop.
4460
+ const attribute = (name) => tag.attributes.properties.findLast((attr) => ts.isJsxAttribute(attr) && ts.isIdentifier(attr.name) && attr.name.text === name);
4461
+ const locale = attribute('locale')?.initializer;
4462
+ const expression = locale && ts.isJsxExpression(locale) ? locale.expression : locale;
4463
+ const value = expression && skipWrappers(expression);
4464
+ if (!value || !ts.isStringLiteralLike(value) || value.text !== '')
4465
+ return;
4466
+ const callback = attribute('onError');
4467
+ const handler = callback?.initializer;
4468
+ if (!callback || !handler || !ts.isJsxExpression(handler) || !handler.expression)
4469
+ return;
4470
+ const callee = skipWrappers(handler.expression);
4471
+ if (!ts.isIdentifier(callee))
4472
+ return;
4473
+ const declaration = this.declarationOf(callee);
4474
+ const imported = declaration && this.imports.get(declaration);
4475
+ if (!declaration ||
4476
+ !imported ||
4477
+ imported.typeOnly ||
4478
+ imported.namespace ||
4479
+ ts.findAncestor(declaration, ts.isImportDeclaration)?.attributes)
4480
+ return;
4481
+ const hint = resourceHint(imported.module, imported.imported, true);
4482
+ if (hint)
4483
+ this.note(RULE.bindings, 'error', callback, `IntlProvider can call \`${imported.imported}\` for an empty locale. The retained callback uses React DOM ${hint} outside the original React server request. Move it into Octane-compiled code or retain the React provider.`);
4484
+ }
3531
4485
  checkInitializerResourceHints(initializer) {
3532
4486
  const resourceHint = this.options.initializerResourceHint;
3533
4487
  if (!resourceHint)
@@ -3840,7 +4794,162 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3840
4794
  return;
3841
4795
  return `[${field.name.getText(this.sf)}]`;
3842
4796
  }
3843
- ownDataDependency(member, hook) {
4797
+ /** Prove the state record is never exposed and every update owns the dependency field. */
4798
+ ownStateDependency(receiver, key, hook, dependencies, nestedRead) {
4799
+ const state = this.declarationOf(receiver);
4800
+ if (!state ||
4801
+ !ts.isBindingElement(state) ||
4802
+ !ts.isIdentifier(state.name) ||
4803
+ state.initializer ||
4804
+ state.dotDotDotToken)
4805
+ return false;
4806
+ const tuple = state.parent;
4807
+ if (!ts.isArrayBindingPattern(tuple) ||
4808
+ tuple.elements.length !== 2 ||
4809
+ tuple.elements[0] !== state)
4810
+ return false;
4811
+ const setter = tuple.elements[1];
4812
+ const declaration = tuple.parent;
4813
+ if (!ts.isBindingElement(setter) ||
4814
+ !ts.isIdentifier(setter.name) ||
4815
+ setter.initializer ||
4816
+ setter.dotDotDotToken ||
4817
+ !ts.isVariableDeclaration(declaration) ||
4818
+ !declaration.initializer ||
4819
+ !fixedBinding(this.checker, receiver, hook) ||
4820
+ !initializedBefore(this.checker, receiver, hook) ||
4821
+ (/eval|\\u/.test(this.source) && hasEval(this.sf)))
4822
+ return false;
4823
+ const init = skipWrappers(declaration.initializer);
4824
+ if (!ts.isCallExpression(init) ||
4825
+ init.questionDotToken ||
4826
+ init.arguments.length !== 1 ||
4827
+ !ts.isIdentifier(init.expression) ||
4828
+ this.reactHook(init.expression) !== 'useState' ||
4829
+ this.options.originalReact === false ||
4830
+ [...this.imports.values()].some((item) => item.module === 'react' &&
4831
+ !item.typeOnly &&
4832
+ (item.namespace || item.imported === 'default')))
4833
+ return false;
4834
+ // A CommonJS import or dynamic import can expose React's mutable export object.
4835
+ const staticReactImports = this.sf.statements.filter((statement) => ts.isImportDeclaration(statement) &&
4836
+ ts.isStringLiteral(statement.moduleSpecifier) &&
4837
+ statement.moduleSpecifier.text === 'react').length;
4838
+ const reactLoads = ts.preProcessFile(this.source, true, true).importedFiles;
4839
+ if (reactLoads.filter((entry) => entry.fileName === 'react').length !== staticReactImports)
4840
+ return false;
4841
+ const simpleName = (name) => ts.isIdentifier(name) || ts.isStringLiteral(name) ? name.text : undefined;
4842
+ const required = new Set([key]);
4843
+ const coerced = new Set();
4844
+ const addField = (name) => {
4845
+ if (name === undefined || name === '__proto__')
4846
+ return false;
4847
+ required.add(name);
4848
+ return true;
4849
+ };
4850
+ const closed = renderUses(this.localUses(state.name)).every((use) => {
4851
+ const parent = use.parent;
4852
+ if (ts.isVariableDeclaration(parent) &&
4853
+ parent.initializer === use &&
4854
+ ts.isObjectBindingPattern(parent.name)) {
4855
+ return parent.name.elements.every((binding) => {
4856
+ const name = simpleName(binding.propertyName ?? binding.name);
4857
+ return (!binding.initializer &&
4858
+ !binding.dotDotDotToken &&
4859
+ ts.isIdentifier(binding.name) &&
4860
+ addField(name));
4861
+ });
4862
+ }
4863
+ if (!ts.isPropertyAccessExpression(parent) ||
4864
+ parent.expression !== use ||
4865
+ !addField(parent.name.text))
4866
+ return false;
4867
+ let value = parent;
4868
+ while (isWrapper(value.parent))
4869
+ value = value.parent;
4870
+ const outer = value.parent;
4871
+ if (ts.isPrefixUnaryExpression(outer) &&
4872
+ outer.operator !== ts.SyntaxKind.PlusPlusToken &&
4873
+ outer.operator !== ts.SyntaxKind.MinusMinusToken) {
4874
+ if (outer.operator !== ts.SyntaxKind.ExclamationToken)
4875
+ coerced.add(parent.name.text);
4876
+ return true;
4877
+ }
4878
+ if (ts.isTypeOfExpression(outer) ||
4879
+ ts.isVoidExpression(outer) ||
4880
+ (ts.isBinaryExpression(outer) &&
4881
+ (outer.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken ||
4882
+ outer.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken)) ||
4883
+ (ts.isIfStatement(outer) && outer.expression === value) ||
4884
+ (ts.isJsxExpression(outer) && ts.isJsxAttribute(outer.parent)) ||
4885
+ outer === dependencies)
4886
+ return true;
4887
+ const coercesValue = nestedRead(parent);
4888
+ if (coercesValue === undefined)
4889
+ return false;
4890
+ if (coercesValue)
4891
+ coerced.add(parent.name.text);
4892
+ return true;
4893
+ });
4894
+ if (!closed)
4895
+ return false;
4896
+ const ownsFields = (expression, prior) => {
4897
+ const record = skipWrappers(expression);
4898
+ if (!ts.isObjectLiteralExpression(record))
4899
+ return false;
4900
+ let firstField = 0;
4901
+ if (prior) {
4902
+ const [spread] = record.properties;
4903
+ const uses = this.localUses(prior);
4904
+ if (!spread ||
4905
+ !ts.isSpreadAssignment(spread) ||
4906
+ uses.length !== 1 ||
4907
+ uses[0] !== spread.expression)
4908
+ return false;
4909
+ firstField = 1;
4910
+ }
4911
+ const missing = new Set(prior ? [] : required);
4912
+ for (const field of record.properties.slice(firstField)) {
4913
+ if (!ts.isPropertyAssignment(field))
4914
+ return false;
4915
+ const name = simpleName(field.name);
4916
+ if (name === undefined || name === '__proto__')
4917
+ return false;
4918
+ if (coerced.has(name) && !isPrimitiveLiteral(field.initializer))
4919
+ return false;
4920
+ missing.delete(name);
4921
+ }
4922
+ return missing.size === 0;
4923
+ };
4924
+ const initializer = skipWrappers(init.arguments[0]);
4925
+ const birth = ts.isArrowFunction(initializer) ? initializer.body : initializer;
4926
+ if ((ts.isArrowFunction(initializer) &&
4927
+ (initializer.modifiers?.length || initializer.parameters.length)) ||
4928
+ ts.isBlock(birth) ||
4929
+ !ownsFields(birth))
4930
+ return false;
4931
+ return this.localUses(setter.name).every((use) => {
4932
+ const call = use.parent;
4933
+ if (!ts.isCallExpression(call) ||
4934
+ call.expression !== use ||
4935
+ call.questionDotToken ||
4936
+ !ts.isExpressionStatement(call.parent) ||
4937
+ call.arguments.length !== 1)
4938
+ return false;
4939
+ const next = skipWrappers(call.arguments[0]);
4940
+ if (!ts.isArrowFunction(next))
4941
+ return ownsFields(next);
4942
+ const [prior] = next.parameters;
4943
+ return (!next.modifiers?.length &&
4944
+ next.parameters.length === 1 &&
4945
+ ts.isIdentifier(prior.name) &&
4946
+ !prior.initializer &&
4947
+ !prior.dotDotDotToken &&
4948
+ !ts.isBlock(next.body) &&
4949
+ ownsFields(next.body, prior.name));
4950
+ });
4951
+ }
4952
+ ownDataDependency(member, hook, dependencies, coercesValue, nestedRead) {
3844
4953
  const receiver = skipWrappers(member.expression);
3845
4954
  const name = ts.isPropertyAccessExpression(member)
3846
4955
  ? member.name
@@ -3851,6 +4960,8 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3851
4960
  const key = name.text;
3852
4961
  if (key === '__proto__' || !ts.isIdentifier(receiver))
3853
4962
  return false;
4963
+ if (this.ownStateDependency(receiver, key, hook, dependencies, nestedRead))
4964
+ return true;
3854
4965
  const init = this.constValue(receiver);
3855
4966
  const object = init && skipWrappers(init);
3856
4967
  const owner = ts.findAncestor(hook, ts.isFunctionLike);
@@ -3862,36 +4973,204 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
3862
4973
  reads(owner, (name) => name.text === 'eval'))
3863
4974
  return false;
3864
4975
  // Spreads, computed names and accessors can redefine the property.
3865
- return (object.properties.every((field) => (ts.isPropertyAssignment(field) && !ts.isComputedPropertyName(field.name)) ||
3866
- (ts.isShorthandPropertyAssignment(field) && !field.objectAssignmentInitializer)) &&
3867
- object.properties.some(({ name }) => name && (ts.isIdentifier(name) || ts.isStringLiteralLike(name)) && name.text === key));
4976
+ let owns = false;
4977
+ for (const field of object.properties) {
4978
+ const name = field.name;
4979
+ if (!(ts.isPropertyAssignment(field) && !ts.isComputedPropertyName(field.name)) &&
4980
+ !(ts.isShorthandPropertyAssignment(field) && !field.objectAssignmentInitializer))
4981
+ return false;
4982
+ if (!name || (!ts.isIdentifier(name) && !ts.isStringLiteralLike(name))) {
4983
+ // A numeric name can override the corresponding string name.
4984
+ if (coercesValue)
4985
+ return false;
4986
+ continue;
4987
+ }
4988
+ if (name.text !== key)
4989
+ continue;
4990
+ owns = true;
4991
+ if (coercesValue &&
4992
+ !(ts.isPropertyAssignment(field) && isPrimitiveLiteral(field.initializer)))
4993
+ return false;
4994
+ }
4995
+ return owns;
4996
+ }
4997
+ copiesOwnGetter(spread, hook) {
4998
+ let object = skipWrappers(spread.expression);
4999
+ // An inline operand can invoke a getter before the outer copy begins.
5000
+ if (ts.isObjectLiteralExpression(object) &&
5001
+ object.properties.some((field) => ts.isSpreadAssignment(field) && this.copiesOwnGetter(field, hook)))
5002
+ return true;
5003
+ if (ts.isIdentifier(object)) {
5004
+ const owner = ts.findAncestor(hook, ts.isFunctionLike);
5005
+ const init = this.constValue(object);
5006
+ if (!init ||
5007
+ !owner ||
5008
+ !fixedBinding(this.checker, object, hook) ||
5009
+ !initializedBefore(this.checker, object, hook) ||
5010
+ this.localUses(object).some((name) => !declaresName(name) && !inTypeNode(name)) ||
5011
+ reads(owner, (name) => name.text === 'eval'))
5012
+ return false;
5013
+ object = skipWrappers(init);
5014
+ }
5015
+ if (!ts.isObjectLiteralExpression(object))
5016
+ return false;
5017
+ const overwritten = new Set();
5018
+ for (let i = object.properties.length - 1; i >= 0; i--) {
5019
+ const field = object.properties[i];
5020
+ // A later setter preserves an existing getter for its key.
5021
+ if (ts.isSetAccessorDeclaration(field))
5022
+ continue;
5023
+ if (ts.isGetAccessorDeclaration(field) && overwritten.size === 0)
5024
+ return true;
5025
+ const computed = field.name && ts.isComputedPropertyName(field.name);
5026
+ const name = computed ? skipWrappers(field.name.expression) : field.name;
5027
+ if (!name ||
5028
+ !((!computed && ts.isIdentifier(name)) ||
5029
+ ts.isStringLiteralLike(name) ||
5030
+ ts.isNumericLiteral(name)))
5031
+ return false;
5032
+ if (!computed && ts.isPropertyAssignment(field) && name.text === '__proto__')
5033
+ continue;
5034
+ if (ts.isGetAccessorDeclaration(field) && !overwritten.has(name.text))
5035
+ return true;
5036
+ overwritten.add(name.text);
5037
+ }
5038
+ return false;
3868
5039
  }
3869
5040
  checkHookDependencyReads(node, deps) {
3870
5041
  const list = skipWrappers(deps);
3871
5042
  if (!this.emitsTsrx || !ts.isArrayLiteralExpression(list))
3872
5043
  return;
3873
- const read = (expr) => {
5044
+ let memberReads;
5045
+ const recordStateRead = (member, coercesValue) => {
5046
+ memberReads?.set(member, coercesValue);
5047
+ return undefined;
5048
+ };
5049
+ const read = (expr, visit, coercesValue = false) => {
3874
5050
  const member = skipWrappers(expr);
5051
+ if (ts.isSpreadElement(member)) {
5052
+ const value = skipWrappers(member.expression);
5053
+ const stateProof = visit === recordStateRead;
5054
+ if (stateProof && !ts.isArrayLiteralExpression(value))
5055
+ return;
5056
+ // A custom iterator can observe elements of a fresh array.
5057
+ return read(value, visit, coercesValue || stateProof);
5058
+ }
5059
+ if (ts.isArrayLiteralExpression(member)) {
5060
+ for (const item of member.elements) {
5061
+ const found = read(item, visit, coercesValue);
5062
+ if (found)
5063
+ return found;
5064
+ }
5065
+ return;
5066
+ }
5067
+ if (ts.isObjectLiteralExpression(member)) {
5068
+ for (const property of member.properties) {
5069
+ if (ts.isSpreadAssignment(property)) {
5070
+ if (visit !== recordStateRead && this.copiesOwnGetter(property, node))
5071
+ return property;
5072
+ continue;
5073
+ }
5074
+ const name = property.name;
5075
+ if (name && ts.isComputedPropertyName(name)) {
5076
+ const found = read(name.expression, visit, true);
5077
+ if (found)
5078
+ return found;
5079
+ }
5080
+ // Method and accessor bodies are deferred. Outer coercion or iteration can read any field.
5081
+ if (ts.isPropertyAssignment(property)) {
5082
+ const found = read(property.initializer, visit, coercesValue);
5083
+ if (found)
5084
+ return found;
5085
+ }
5086
+ }
5087
+ return;
5088
+ }
5089
+ if (ts.isTemplateExpression(member)) {
5090
+ for (const span of member.templateSpans) {
5091
+ const found = read(span.expression, visit, true);
5092
+ if (found)
5093
+ return found;
5094
+ }
5095
+ return;
5096
+ }
5097
+ if (ts.isTypeOfExpression(member) || ts.isVoidExpression(member))
5098
+ return read(member.expression, visit);
5099
+ if (ts.isPrefixUnaryExpression(member) &&
5100
+ member.operator !== ts.SyntaxKind.PlusPlusToken &&
5101
+ member.operator !== ts.SyntaxKind.MinusMinusToken)
5102
+ return read(member.operand, visit, member.operator !== ts.SyntaxKind.ExclamationToken);
3875
5103
  if (ts.isConditionalExpression(member)) {
3876
5104
  const condition = skipWrappers(member.condition);
3877
5105
  if (condition.kind === ts.SyntaxKind.TrueKeyword)
3878
- return read(member.whenTrue);
5106
+ return read(member.whenTrue, visit, coercesValue);
3879
5107
  if (condition.kind === ts.SyntaxKind.FalseKeyword)
3880
- return read(member.whenFalse);
3881
- return read(condition) ?? read(member.whenTrue) ?? read(member.whenFalse);
5108
+ return read(member.whenFalse, visit, coercesValue);
5109
+ return (read(condition, visit) ??
5110
+ read(member.whenTrue, visit, coercesValue) ??
5111
+ read(member.whenFalse, visit, coercesValue));
5112
+ }
5113
+ if (ts.isBinaryExpression(member)) {
5114
+ const op = member.operatorToken.kind;
5115
+ // The left value is read and discarded. Only the right value reaches outer coercion.
5116
+ if (op === ts.SyntaxKind.CommaToken)
5117
+ return read(member.left, visit) ?? read(member.right, visit, coercesValue);
5118
+ // Strict comparison reads both operands and does not coerce either.
5119
+ if (op === ts.SyntaxKind.EqualsEqualsEqualsToken ||
5120
+ op === ts.SyntaxKind.ExclamationEqualsEqualsToken)
5121
+ return read(member.left, visit) ?? read(member.right, visit);
5122
+ // Relational comparison can coerce either operand through user code.
5123
+ if (op === ts.SyntaxKind.LessThanToken ||
5124
+ op === ts.SyntaxKind.LessThanEqualsToken ||
5125
+ op === ts.SyntaxKind.GreaterThanToken ||
5126
+ op === ts.SyntaxKind.GreaterThanEqualsToken)
5127
+ return read(member.left, visit, true) ?? read(member.right, visit, true);
5128
+ if (op === ts.SyntaxKind.AmpersandAmpersandToken ||
5129
+ op === ts.SyntaxKind.BarBarToken ||
5130
+ op === ts.SyntaxKind.QuestionQuestionToken) {
5131
+ // Only a falsy left value can become the result of &&.
5132
+ const left = read(member.left, visit, coercesValue && op !== ts.SyntaxKind.AmpersandAmpersandToken);
5133
+ if (left)
5134
+ return left;
5135
+ const condition = literalCondition(member.left);
5136
+ if (condition === undefined ||
5137
+ (op === ts.SyntaxKind.AmpersandAmpersandToken && condition === 'truthy') ||
5138
+ (op === ts.SyntaxKind.BarBarToken && condition !== 'truthy') ||
5139
+ (op === ts.SyntaxKind.QuestionQuestionToken && condition === 'nullish'))
5140
+ return read(member.right, visit, coercesValue);
5141
+ }
5142
+ }
5143
+ if (ts.isPropertyAccessExpression(member) || ts.isElementAccessExpression(member))
5144
+ return visit(member, coercesValue);
5145
+ };
5146
+ // The closed-state proof must account for every field read in this list.
5147
+ const nestedRead = (member) => {
5148
+ if (!memberReads) {
5149
+ memberReads = new Map();
5150
+ for (const entry of list.elements)
5151
+ read(entry, recordStateRead);
3882
5152
  }
3883
- if ((ts.isPropertyAccessExpression(member) || ts.isElementAccessExpression(member)) &&
3884
- !this.ownDataDependency(member, node))
5153
+ return memberReads.get(member);
5154
+ };
5155
+ let opaqueCoercion = false;
5156
+ const check = (member, coercesValue) => {
5157
+ if (!this.ownDataDependency(member, node, list, coercesValue, nestedRead)) {
5158
+ opaqueCoercion = coercesValue;
3885
5159
  return member;
5160
+ }
3886
5161
  };
3887
5162
  let opaque;
3888
5163
  for (const entry of list.elements) {
3889
- opaque = read(entry);
5164
+ opaque = read(entry, check);
3890
5165
  if (opaque)
3891
5166
  break;
3892
5167
  }
3893
5168
  if (opaque)
3894
- this.note(RULE.deps, 'error', opaque, 'This hook dependency reads a property during render and may run a getter owned by React. Keep the component in React or verify the getter before moving it to native SSR.');
5169
+ this.note(RULE.deps, 'error', opaque, ts.isSpreadAssignment(opaque)
5170
+ ? 'This hook dependency can invoke an own getter while spreading an object. Keep the component in React or verify the getter before moving it to native SSR.'
5171
+ : opaqueCoercion
5172
+ ? 'This hook dependency reads a property during render. It may run a getter owned by React or execute user code during value coercion. Keep the component in React or verify the property before moving it to native SSR.'
5173
+ : 'This hook dependency reads a property during render and may run a getter owned by React. Keep the component in React or verify the getter before moving it to native SSR.');
3895
5174
  }
3896
5175
  /**
3897
5176
  * React runs a hook with an omitted or undefined list on every render.
@@ -4034,20 +5313,110 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
4034
5313
  ? `${this.require('octane', 'createRoot', false)}(${containerText}).render(${elementText})`
4035
5314
  : `${this.require('octane', 'hydrateRoot', false)}(${containerText}, ${elementText})`;
4036
5315
  }
4037
- /** Report renderer ownership only for the ordinary direct root rewrite. */
4038
- checkLocalReactRoot(call, receiver, root) {
5316
+ /** Report a retained React hook when the server render receives its JSX descriptor. */
5317
+ checkBufferedReactComponent(call, argument, module) {
5318
+ const check = this.options.localReactHook;
5319
+ if (!check || ts.isOptionalChain(call))
5320
+ return;
5321
+ const callee = call.expression;
5322
+ const receiver = ts.isPropertyAccessExpression(callee) ? callee.expression : callee;
5323
+ if (!ts.isIdentifier(receiver))
5324
+ return;
5325
+ const binding = this.importOf(receiver);
5326
+ const declaration = this.declarationOf(receiver);
5327
+ if (!binding ||
5328
+ binding.typeOnly ||
5329
+ !declaration ||
5330
+ !(ts.isImportSpecifier(declaration) || ts.isNamespaceImport(declaration)) ||
5331
+ ts.findAncestor(declaration, ts.isImportDeclaration)?.attributes ||
5332
+ !this.options.automaticReactJsx ||
5333
+ !this.options.originalReactServerEntry?.(module) ||
5334
+ ((this.source.includes('eval') || this.source.includes('\\')) && hasEval(this.sf)))
5335
+ return;
5336
+ // Another import of the module can expose its mutable CommonJS exports.
5337
+ if ([...this.imports].some(([decl, entry]) => REACT_MODULES[entry.module] === 'octane/server' &&
5338
+ !entry.typeOnly &&
5339
+ (ts.isNamespaceImport(decl)
5340
+ ? !this.namespaceMemberCalls(decl)
5341
+ : entry.namespace || entry.imported === 'default')))
5342
+ return;
5343
+ const retained = (expression) => {
5344
+ const value = skipParens(expression);
5345
+ if (!ts.isJsxSelfClosingElement(value) || this.retainedReactOutput(value))
5346
+ return;
5347
+ const imported = this.directImportedValue(value.tagName);
5348
+ if (!imported || !isComponentName(imported.tag.text))
5349
+ return;
5350
+ const hook = check(imported.entry.module, imported.entry.imported, false);
5351
+ if (typeof hook === 'string')
5352
+ return { tag: imported.tag.text, hook };
5353
+ };
5354
+ const value = skipParens(argument);
5355
+ let component = retained(value);
5356
+ if (ts.isIdentifier(value)) {
5357
+ const local = this.declarationOf(value);
5358
+ if (!local ||
5359
+ !ts.isVariableDeclaration(local) ||
5360
+ !ts.isIdentifier(local.name) ||
5361
+ !local.initializer ||
5362
+ !initializedBefore(this.checker, value, call) ||
5363
+ ts.findAncestor(local, ts.isFunctionLike) !== ts.findAncestor(call, ts.isFunctionLike))
5364
+ return;
5365
+ component = retained(local.initializer);
5366
+ if (!component || !this.closedBufferedValue(local, value, call, (expr) => !!retained(expr)))
5367
+ return;
5368
+ }
5369
+ if (component)
5370
+ this.note(BUFFERED_SSR_REACT_COMPONENT, 'error', call, `The migrated server renderer can render ${component.tag}, which stays on React and calls ${component.hook}. Migrate the component with this file or keep the render in React.`);
5371
+ }
5372
+ /** The descriptor can only go to this renderer or be replaced by another proven descriptor. */
5373
+ closedBufferedValue(local, value, call, retained) {
5374
+ const block = local.parent.parent.parent;
5375
+ const kind = ts.getCombinedNodeFlags(local) & ts.NodeFlags.BlockScoped;
5376
+ const canAssign = kind === ts.NodeFlags.Let &&
5377
+ ts.isReturnStatement(call.parent) &&
5378
+ call.parent.parent === block;
5379
+ if (!canAssign && kind !== ts.NodeFlags.Const)
5380
+ return false;
5381
+ return renderUses(this.localUses(value)).every((ref) => {
5382
+ if (ref === local.name)
5383
+ return true;
5384
+ const write = ref.parent;
5385
+ const statement = write.parent;
5386
+ return (canAssign &&
5387
+ ts.isBinaryExpression(write) &&
5388
+ write.left === ref &&
5389
+ write.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
5390
+ ts.isExpressionStatement(statement) &&
5391
+ statement.end <= call.pos &&
5392
+ (statement.parent === block ||
5393
+ (ts.isIfStatement(statement.parent) && statement.parent.parent === block)) &&
5394
+ retained(write.right));
5395
+ });
5396
+ }
5397
+ /** JSX retained for a prop spread or quoted reference still uses the migrated root. */
5398
+ checkLocalReactRoot(call, receiver, root, retained) {
4039
5399
  const local = this.options.localReactRootComponent;
4040
5400
  const element = skipParens(call.arguments[0]);
4041
5401
  if (!local || !ts.isJsxSelfClosingElement(element) || !ts.isIdentifier(element.tagName))
4042
5402
  return;
4043
5403
  const tag = element.tagName;
4044
5404
  const leaf = this.importOf(tag);
5405
+ const attributes = element.attributes.properties;
4045
5406
  const factoryName = ts.isPropertyAccessExpression(root.expression)
4046
5407
  ? root.expression.expression
4047
5408
  : root.expression;
4048
5409
  const rootImport = this.importOf(factoryName);
4049
5410
  const factoryBinding = ts.isIdentifier(factoryName) && this.declarationOf(factoryName);
4050
- if (!leaf ||
5411
+ if (!isComponentName(tag.text) ||
5412
+ (retained &&
5413
+ (!(attributes.some(ts.isJsxSpreadAttribute) ||
5414
+ (attributes.some(quotedPropWithReference) &&
5415
+ !attributes.some((attr) => ts.isJsxAttribute(attr) && /^(key|ref)$/.test(attr.name.getText(this.sf))))) ||
5416
+ this.islands.has(element) ||
5417
+ this.reactRendererBodies.has(element) ||
5418
+ this.unrenderable.has(element))) ||
5419
+ !leaf ||
4051
5420
  leaf.typeOnly ||
4052
5421
  ts.findAncestor(this.declarationOf(tag), ts.isImportDeclaration)?.attributes ||
4053
5422
  rootImport?.module !== 'react-dom/client' ||
@@ -4067,22 +5436,9 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
4067
5436
  ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Export ||
4068
5437
  (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.BlockScoped) !== ts.NodeFlags.Const)
4069
5438
  return;
4070
- const statement = declaration.parent.parent;
4071
- if (!ts.isVariableStatement(statement))
4072
- return;
4073
- const topLevel = ts.isExpressionStatement(call.parent) &&
4074
- call.parent.parent === this.sf &&
4075
- statement.parent === this.sf &&
4076
- statement.end <= call.getStart(this.sf);
4077
- if ((!topLevel && !initializedBefore(this.checker, receiver, call)) ||
4078
- renderUses(this.localUses(declaration.name)).some((ref) => {
4079
- const access = ref.parent;
4080
- return (!ts.isPropertyAccessExpression(access) ||
4081
- access.expression !== ref ||
4082
- (access.name.text !== 'render' && access.name.text !== 'unmount') ||
4083
- !ts.isCallExpression(access.parent) ||
4084
- access.parent.expression !== access);
4085
- }))
5439
+ if ((!atInitializedModuleHandle(declaration, call) &&
5440
+ !initializedBefore(this.checker, receiver, call)) ||
5441
+ rootHandleEscapes(this.localUses(declaration.name)))
4086
5442
  return;
4087
5443
  }
4088
5444
  const hook = local(leaf.module, leaf.imported);
@@ -4090,10 +5446,8 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
4090
5446
  this.note(RULE.rootRender, 'error', tag, `The migrated root renders ${tag.text}, but the unchanged ${leaf.module} export calls ${hook === 'useIntl' ? "React Intl's" : "React's"} ${hook}. Migrate the component or keep this root under React DOM.`);
4091
5447
  }
4092
5448
  /**
4093
- * `root.render(<App a={1} />)` and `root.render(createElement(App, props))`
4094
- * are `root.render(App, props)`, which mounts the component without an
4095
- * element: the generic element renderer stays out of the bundle. So are
4096
- * `hydrateRoot(c, <App />)` and the server renderers' element argument.
5449
+ * Mount component roots directly when the element carries no key or
5450
+ * factory configuration. The same applies to hydration and server roots.
4097
5451
  *
4098
5452
  * @param argument the element, the call's last argument
4099
5453
  */
@@ -4124,12 +5478,12 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
4124
5478
  return null;
4125
5479
  if (!isComponentName(tag.getText(this.sf).split('.').pop() ?? ''))
4126
5480
  return null;
5481
+ const attributes = node.attributes.properties;
5482
+ // A spread can carry a key. Keep quoted references for the JSX parser.
5483
+ if (!attributes.every(ts.isJsxAttribute) || attributes.some(quotedPropWithReference))
5484
+ return null;
4127
5485
  const props = [];
4128
- for (const property of node.attributes.properties) {
4129
- if (ts.isJsxSpreadAttribute(property)) {
4130
- props.push(`...${this.emit(property.expression, PLAIN)}`);
4131
- continue;
4132
- }
5486
+ for (const property of attributes) {
4133
5487
  const name = property.name.getText(this.sf);
4134
5488
  if (name === 'key' || name === 'ref')
4135
5489
  return null;
@@ -4137,8 +5491,12 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
4137
5491
  const value = property.initializer;
4138
5492
  if (!value)
4139
5493
  props.push(`${key}: true`);
4140
- else if (ts.isStringLiteral(value))
4141
- props.push(`${key}: ${value.getText(this.sf)}`);
5494
+ else if (ts.isStringLiteral(value)) {
5495
+ const text = /[\\\r\n]/.test(value.text)
5496
+ ? JSON.stringify(value.text)
5497
+ : value.getText(this.sf);
5498
+ props.push(`${key}: ${text}`);
5499
+ }
4142
5500
  else if (ts.isJsxExpression(value) && value.expression)
4143
5501
  props.push(`${key}: ${this.emit(value.expression, PLAIN)}`);
4144
5502
  else
@@ -4155,8 +5513,10 @@ function ${this.nativeRefStoreFactory}<T>(initial: T) {
4155
5513
  return null;
4156
5514
  if (!isComponentName(type.getText(this.sf).split('.').pop() ?? ''))
4157
5515
  return null;
4158
- const text = this.emit(type, PLAIN);
4159
- return !props || isNullish(props) ? text : `${text}, ${this.emit(props, PLAIN)}`;
5516
+ // The element factory extracts the config's key and snapshots its enumerable props.
5517
+ if (props && (!isNullish(props) || (ts.isIdentifier(props) && this.declarationOf(props))))
5518
+ return null;
5519
+ return this.emit(type, PLAIN);
4160
5520
  }
4161
5521
  return null;
4162
5522
  }
@@ -4540,11 +5900,30 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4540
5900
  : `Class component \`${node.name?.text ?? 'class'}\` needs a rewrite as a function component.`);
4541
5901
  }
4542
5902
  checkDefaultProps(node) {
4543
- if (node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
4544
- ts.isPropertyAccessExpression(node.left) &&
4545
- node.left.name.text === 'defaultProps') {
4546
- this.note(RULE.defaultProps, 'warning', node, 'Function components ignore `defaultProps`; move the defaults into the props destructuring.');
5903
+ if (node.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||
5904
+ !ts.isPropertyAccessExpression(node.left))
5905
+ return;
5906
+ const member = node.left.name.text === 'defaultProps' ? node.left : node.left.expression;
5907
+ if (ts.isExpressionStatement(node.parent) &&
5908
+ node.parent.parent === this.sf &&
5909
+ ts.isPropertyAccessExpression(member) &&
5910
+ member.name.text === 'defaultProps' &&
5911
+ ts.isIdentifier(member.expression) &&
5912
+ [...this.nativeIntl].some((item) => (item.propertyName ?? item.name).text === 'IntlProvider')) {
5913
+ const declaration = this.declarationOf(member.expression);
5914
+ const imported = declaration && this.imports.get(declaration);
5915
+ if (declaration &&
5916
+ imported?.module === 'react-intl' &&
5917
+ imported.imported === 'IntlProvider' &&
5918
+ !imported.typeOnly &&
5919
+ !ts.findAncestor(declaration, ts.isImportDeclaration)?.attributes) {
5920
+ this.note(INTL_PROVIDER_DEFAULTS, 'error', node, 'The generated IntlProvider cannot share the React class defaults assigned here. Keep the provider and its consumers in the original React render.');
5921
+ return;
5922
+ }
4547
5923
  }
5924
+ if (node.left.name.text !== 'defaultProps')
5925
+ return;
5926
+ this.note(RULE.defaultProps, 'warning', node, 'Function components ignore `defaultProps`; move the defaults into the props destructuring.');
4548
5927
  }
4549
5928
  // ---------------------------------------------------------------- JSX
4550
5929
  rewriteAttributes(node, ctx) {
@@ -4598,7 +5977,8 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4598
5977
  this.count(RULE.className);
4599
5978
  out += 'class' + this.emitInitializer(attribute);
4600
5979
  }
4601
- else if ((name === 'onChange' || name === 'onChangeCapture') && this.isTextEntry(element)) {
5980
+ else if ((name === 'onChange' || name === 'onChangeCapture') &&
5981
+ this.isTextEntry(element, name === 'onChange')) {
4602
5982
  const input = name === 'onChange' ? 'onInput' : 'onInputCapture';
4603
5983
  const existing = attributeOf(element, input);
4604
5984
  const changesOrder = !spread &&
@@ -4627,6 +6007,8 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4627
6007
  out += this.emit(attribute, PLAIN);
4628
6008
  }
4629
6009
  }
6010
+ if (ts.isJsxSelfClosingElement(element) && this.inlineIntlMessages.has(element))
6011
+ out += ` inlineHost={${this.require('octane/react', 'ReactCompatInline', false)}}`;
4630
6012
  return out + this.source.slice(cursor, node.end);
4631
6013
  }
4632
6014
  mayHaveJsxHandler(attribute) {
@@ -4649,11 +6031,60 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4649
6031
  return (this.source.slice(attribute.name.end, attribute.initializer.getStart(this.sf)) +
4650
6032
  this.emit(attribute.initializer, PLAIN));
4651
6033
  }
6034
+ textInputResult(expression) {
6035
+ if (!expression)
6036
+ return false;
6037
+ const value = skipWrappers(expression);
6038
+ if (ts.isConditionalExpression(value))
6039
+ return this.textInputResult(value.whenTrue) && this.textInputResult(value.whenFalse);
6040
+ return (ts.isStringLiteralLike(value) && (value.text === 'date' || TEXT_INPUT_TYPES.has(value.text)));
6041
+ }
6042
+ textInputTypeCall(call) {
6043
+ if (!ts.isIdentifier(call.expression) || !ts.isExternalModule(this.sf))
6044
+ return false;
6045
+ const symbol = this.checker.getSymbolAtLocation(call.expression);
6046
+ const fn = symbol?.valueDeclaration;
6047
+ if (symbol?.declarations?.length !== 1 ||
6048
+ !fn ||
6049
+ !ts.isFunctionDeclaration(fn) ||
6050
+ !fn.name ||
6051
+ !fn.body ||
6052
+ fn.parent !== this.sf ||
6053
+ fn.asteriskToken ||
6054
+ fn.modifiers?.length)
6055
+ return false;
6056
+ const [statement] = fn.body.statements;
6057
+ // Unmatched switch values and empty trailing clauses return undefined, the default text type.
6058
+ const knownResult = this.textInputResult(singleCallbackExpression(fn.body)) ||
6059
+ (fn.body.statements.length === 1 &&
6060
+ ts.isSwitchStatement(statement) &&
6061
+ statement.caseBlock.clauses.every(({ statements }) => {
6062
+ const [first] = statements;
6063
+ return (!first ||
6064
+ (statements.length === 1 &&
6065
+ ts.isReturnStatement(first) &&
6066
+ this.textInputResult(first.expression)));
6067
+ }));
6068
+ return (knownResult &&
6069
+ (!/eval|\\u/.test(this.source) || !hasEval(this.sf)) &&
6070
+ this.localUses(fn.name).every((ref) => inTypeNode(ref) || (ts.isCallExpression(ref.parent) && ref.parent.expression === ref)));
6071
+ }
6072
+ hasAncestorInputHandler(element) {
6073
+ for (let parent = element.parent; !ts.isFunctionLike(parent) && !ts.isSourceFile(parent); parent = parent.parent) {
6074
+ if (!ts.isJsxElement(parent) || parent.openingElement === element)
6075
+ continue;
6076
+ if (parent.openingElement.attributes.properties.some((attribute) => ts.isJsxSpreadAttribute(attribute) ||
6077
+ (ts.isIdentifier(attribute.name) &&
6078
+ /^on(?:Input|Change)(?:Capture)?$/.test(attribute.name.text))))
6079
+ return true;
6080
+ }
6081
+ return false;
6082
+ }
4652
6083
  /**
4653
6084
  * Whether `element` is a text-entry control, where React's `onChange` fires
4654
6085
  * per edit and the native `change` fires on commit.
4655
6086
  */
4656
- isTextEntry(element) {
6087
+ isTextEntry(element, ordinaryChange) {
4657
6088
  const tag = element.tagName.getText(this.sf);
4658
6089
  if (tag === 'textarea')
4659
6090
  return true;
@@ -4665,6 +6096,26 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4665
6096
  const value = type.initializer;
4666
6097
  if (value && ts.isStringLiteral(value))
4667
6098
  return TEXT_INPUT_TYPES.has(value.text);
6099
+ if (tag === 'input' && value && ts.isJsxExpression(value) && value.expression) {
6100
+ const expression = skipWrappers(value.expression);
6101
+ // A spread can also supply the input handler that a rename would overwrite.
6102
+ const fixedType = !element.attributes.properties.some((attribute) => ts.isJsxSpreadAttribute(attribute) ||
6103
+ (attribute !== type && ts.isIdentifier(attribute.name) && attribute.name.text === 'type'));
6104
+ if (fixedType) {
6105
+ if (ts.isStringLiteralLike(expression) && TEXT_INPUT_TYPES.has(expression.text))
6106
+ return true;
6107
+ // React dispatches native input and synthetic change in separate passes.
6108
+ if (this.target === 'tsrx' &&
6109
+ ordinaryChange &&
6110
+ !attributeOf(element, 'ref') &&
6111
+ !attributeOf(element, 'onInputCapture') &&
6112
+ !attributeOf(element, 'onChangeCapture') &&
6113
+ ((ts.isConditionalExpression(expression) && this.textInputResult(expression)) ||
6114
+ (ts.isCallExpression(expression) && this.textInputTypeCall(expression))) &&
6115
+ !this.hasAncestorInputHandler(element))
6116
+ return true;
6117
+ }
6118
+ }
4668
6119
  this.note(RULE.nativeChange, 'warning', element, 'This `<input>` has a dynamic `type`; if it can be a text field, use `onInput` for per-edit updates.');
4669
6120
  return false;
4670
6121
  }
@@ -4679,12 +6130,12 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4679
6130
  // in React; `@if` or `@for` there would hand it a fragment instead.
4680
6131
  const declaration = ts.isIdentifier(tag) ? this.declarationOf(tag) : null;
4681
6132
  const entry = this.importOf(tag);
4682
- const imported = entry && !entry.namespace && !entry.typeOnly && entry.module.startsWith('.') ? entry : null;
6133
+ const imported = entry && !entry.namespace && !entry.typeOnly ? entry : null;
4683
6134
  if ((declaration &&
4684
6135
  (ts.isVariableDeclaration(declaration) || ts.isFunctionDeclaration(declaration)) &&
4685
6136
  this.descriptorComponents.has(declaration)) ||
4686
6137
  (this.hasReactBridge && this.reactCompatTag(tag)) ||
4687
- (imported && this.options.descriptorChild?.(imported))) {
6138
+ (imported?.module.startsWith('.') && this.options.descriptorChild?.(imported))) {
4688
6139
  return this.span(node, node.getStart(this.sf), node.end, DESCRIPTOR);
4689
6140
  }
4690
6141
  const name = this.calleeName(tag);
@@ -4694,16 +6145,22 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4694
6145
  const binding = declaration && ts.isFunctionDeclaration(declaration)
4695
6146
  ? declaration.getStart(this.sf)
4696
6147
  : imported;
4697
- if (radixSlot || (binding !== null && this.options.elementChild?.(binding))) {
4698
- const child = this.singleElementChild(node);
4699
- if (child) {
4700
- this.count(RULE.elementChildProp);
4701
- return (this.span(opening, opening.getStart(this.sf), opening.end - 1, ctx) +
4702
- ' children={' +
4703
- this.emit(child, PLAIN) +
4704
- '} />');
4705
- }
6148
+ const alias = imported && !imported.module.startsWith('.') ? imported : null;
6149
+ const plan = radixSlot || (binding !== null && this.options.elementChild?.(binding));
6150
+ const child = plan && this.singleElementChild(node);
6151
+ if (child && plan === true && !alias) {
6152
+ this.count(RULE.elementChildProp);
6153
+ return (this.span(opening, opening.getStart(this.sf), opening.end - 1, ctx) +
6154
+ ' children={' +
6155
+ this.emit(child, PLAIN) +
6156
+ '} />');
4706
6157
  }
6158
+ if (child &&
6159
+ plan === 'review-alias' &&
6160
+ alias &&
6161
+ declaration &&
6162
+ !ts.findAncestor(declaration, ts.isImportDeclaration)?.attributes)
6163
+ this.note(ELEMENT_CHILD_ALIAS, 'error', opening, `TypeScript resolves \`${alias.module}\` to a selected component with an element-only slot. Verify the runtime alias before passing the element with \`children={...}\`.`);
4707
6164
  }
4708
6165
  if (name === 'StrictMode') {
4709
6166
  // Octane's StrictMode is a pass-through wrapper.
@@ -4734,7 +6191,7 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4734
6191
  if (!entry || entry.namespace || entry.typeOnly)
4735
6192
  return false;
4736
6193
  const name = entry.imported === 'default' ? entry.local : entry.imported;
4737
- const context = this.options.isContext?.(entry.module, entry.imported, entry.local);
6194
+ const context = this.options.isContext?.(entry.module, entry.imported, entry.local, declaration != null && !!ts.findAncestor(declaration, ts.isImportDeclaration)?.attributes);
4738
6195
  if (context !== 'review-alias')
4739
6196
  return context ?? /Context$/.test(name);
4740
6197
  if (member && !ts.isJsxClosingElement(member.parent))
@@ -4751,16 +6208,21 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4751
6208
  }
4752
6209
  return ts.isCallExpression(node) && this.calleeName(node.expression) === 'createContext';
4753
6210
  }
4754
- hasLocalProviderGetter(context) {
4755
- if (!this.source.includes('defineProperty') && !this.source.includes('\\u'))
4756
- return false;
6211
+ localProviderReadChange(context, capture) {
6212
+ if (!this.source.includes('defineProperty') &&
6213
+ !(capture && this.source.includes('assign')) &&
6214
+ !this.source.includes('\\u'))
6215
+ return;
4757
6216
  const initial = this.constValue(context);
4758
6217
  const factory = initial && skipParens(initial);
4759
6218
  if (!factory ||
4760
6219
  !ts.isCallExpression(factory) ||
4761
6220
  this.reactHook(factory.expression) !== 'createContext')
4762
- return false;
4763
- return this.localUses(context).some((reference) => {
6221
+ return;
6222
+ let change = 'getter';
6223
+ const declaration = this.declarationOf(context);
6224
+ const references = this.localUses(context);
6225
+ const found = references.some((reference) => {
4764
6226
  let target = reference;
4765
6227
  while (isWrapper(target.parent) && target.parent.expression === target)
4766
6228
  target = target.parent;
@@ -4775,16 +6237,50 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4775
6237
  return false;
4776
6238
  const method = skipWrappers(call.expression);
4777
6239
  const object = ts.isPropertyAccessExpression(method) && skipWrappers(method.expression);
4778
- const [, keyArgument, descriptorArgument] = call.arguments;
4779
- const key = keyArgument && skipWrappers(keyArgument);
4780
- const descriptor = descriptorArgument && skipWrappers(descriptorArgument);
4781
6240
  if (!ts.isPropertyAccessExpression(method) ||
4782
6241
  method.questionDotToken ||
4783
- method.name.text !== 'defineProperty' ||
4784
6242
  !object ||
4785
6243
  !ts.isIdentifier(object) ||
4786
6244
  object.text !== 'Object' ||
4787
- this.declarationOf(object)?.getSourceFile().hasNoDefaultLib !== true ||
6245
+ this.declarationOf(object)?.getSourceFile().hasNoDefaultLib !== true)
6246
+ return false;
6247
+ const [, keyArgument, descriptorArgument] = call.arguments;
6248
+ if (capture && method.name.text === 'assign' && call.arguments.length === 2) {
6249
+ if (this.sf.statements[this.sf.statements.indexOf(capture) - 1] !== call.parent ||
6250
+ hasEval(this.sf) ||
6251
+ this.localUses(object).some((use) => !inTypeNode(use)) ||
6252
+ references.some((use) => use !== reference &&
6253
+ !(declaration && ts.isVariableDeclaration(declaration) && use === declaration.name) &&
6254
+ !inTypeNode(use)))
6255
+ return false;
6256
+ const data = skipWrappers(keyArgument);
6257
+ if (!ts.isObjectLiteralExpression(data) || data.properties.length !== 1)
6258
+ return false;
6259
+ const [property] = data.properties;
6260
+ const name = property.name;
6261
+ if (!name ||
6262
+ (!ts.isIdentifier(name) && !ts.isStringLiteral(name)) ||
6263
+ name.text !== 'Provider' ||
6264
+ !ts.isPropertyAssignment(property))
6265
+ return false;
6266
+ const value = skipWrappers(property.initializer);
6267
+ const binding = ts.isIdentifier(value) && this.declarationOf(value);
6268
+ if (!ts.isArrowFunction(value) &&
6269
+ !ts.isFunctionExpression(value) &&
6270
+ !(binding &&
6271
+ ts.isFunctionDeclaration(binding) &&
6272
+ binding.parent === this.sf &&
6273
+ binding.body &&
6274
+ binding.name &&
6275
+ !binding.modifiers?.length &&
6276
+ renderUses(this.localUses(binding.name)).every((ref) => ref === value)))
6277
+ return false;
6278
+ change = 'Provider replacement';
6279
+ return true;
6280
+ }
6281
+ const key = keyArgument && skipWrappers(keyArgument);
6282
+ const descriptor = descriptorArgument && skipWrappers(descriptorArgument);
6283
+ if (method.name.text !== 'defineProperty' ||
4788
6284
  !key ||
4789
6285
  !ts.isStringLiteralLike(key) ||
4790
6286
  key.text !== 'Provider' ||
@@ -4799,22 +6295,26 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4799
6295
  return false;
4800
6296
  if (name.text === 'configurable' || name.text === 'enumerable')
4801
6297
  continue;
4802
- if (name.text === 'set' && !setter) {
4803
- const value = ts.isPropertyAssignment(property)
4804
- ? skipWrappers(property.initializer)
4805
- : null;
4806
- if (!ts.isMethodDeclaration(property) &&
4807
- !(value && (ts.isArrowFunction(value) || ts.isFunctionExpression(value))))
6298
+ if (name.text !== 'get' && name.text !== 'set')
6299
+ return false;
6300
+ const value = ts.isPropertyAssignment(property) ? skipWrappers(property.initializer) : null;
6301
+ if (!ts.isMethodDeclaration(property) &&
6302
+ !(value && (ts.isArrowFunction(value) || ts.isFunctionExpression(value))))
6303
+ return false;
6304
+ if (name.text === 'get') {
6305
+ if (getter)
6306
+ return false;
6307
+ getter = true;
6308
+ }
6309
+ else {
6310
+ if (setter)
4808
6311
  return false;
4809
6312
  setter = true;
4810
- continue;
4811
6313
  }
4812
- if (name.text !== 'get' || getter || !ts.isMethodDeclaration(property))
4813
- return false;
4814
- getter = true;
4815
6314
  }
4816
6315
  return getter;
4817
6316
  });
6317
+ return found ? change : undefined;
4818
6318
  }
4819
6319
  /**
4820
6320
  * `typeof children === 'function'` also holds for a compiled children
@@ -4881,12 +6381,9 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4881
6381
  const output = isJsx(body) ? this.emit(body, TEMPLATE) : `<>{${this.emit(body, PLAIN)}}</>`;
4882
6382
  return `@{ const ${param} = ${useContext}(${this.emit(tag.expression, PLAIN)}); ${output} }`;
4883
6383
  }
4884
- /**
4885
- * `<Suspense fallback={f}>…</Suspense>` is the template boundary
4886
- * `@try { … } @pending { f }`.
4887
- */
4888
- rewriteSuspense(node) {
4889
- const attributes = node.openingElement.attributes.properties.filter((a) => !this.removed.has(a));
6384
+ suspenseFallback(node, allowKey = false) {
6385
+ const attributes = node.openingElement.attributes.properties.filter((a) => !this.removed.has(a) &&
6386
+ !(allowKey && ts.isJsxAttribute(a) && a.name.getText(this.sf) === 'key'));
4890
6387
  const fallback = attributes[0];
4891
6388
  if (attributes.length !== 1 ||
4892
6389
  !ts.isJsxAttribute(fallback) ||
@@ -4894,8 +6391,20 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
4894
6391
  !fallback.initializer) {
4895
6392
  return null;
4896
6393
  }
4897
- let pending;
4898
6394
  const value = fallback.initializer;
6395
+ return ts.isStringLiteral(value) || (ts.isJsxExpression(value) && value.expression)
6396
+ ? value
6397
+ : null;
6398
+ }
6399
+ /**
6400
+ * `<Suspense fallback={f}>…</Suspense>` is the template boundary
6401
+ * `@try { … } @pending { f }`.
6402
+ */
6403
+ rewriteSuspense(node) {
6404
+ const value = this.suspenseFallback(node);
6405
+ if (!value)
6406
+ return null;
6407
+ let pending;
4899
6408
  if (ts.isStringLiteral(value))
4900
6409
  pending = `<>{${value.getText(this.sf)}}</>`;
4901
6410
  else if (ts.isJsxExpression(value) && value.expression) {
@@ -5102,22 +6611,23 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5102
6611
  * The template directive equivalent to a renderable expression, as
5103
6612
  * relative text, or null.
5104
6613
  */
5105
- directive(expression) {
6614
+ directive(expression, componentRoot = false) {
5106
6615
  const node = skipParens(expression);
5107
6616
  if (ts.isConditionalExpression(node))
5108
- return this.ifDirective(node);
6617
+ return this.ifDirective(node, componentRoot);
5109
6618
  if (ts.isBinaryExpression(node) &&
5110
6619
  node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken &&
5111
6620
  (this.isBoolean(node.left) ||
5112
6621
  (this.strictTypes && isBooleanGuardType(this.typeOf(node.left))))) {
5113
- const arm = this.arm(node.right);
6622
+ const condition = componentRoot ? literalCondition(node.left) : undefined;
6623
+ const arm = this.arm(node.right, componentRoot && (condition === undefined || condition === 'truthy'));
5114
6624
  if (arm === null || arm === '')
5115
6625
  return null;
5116
6626
  this.count(RULE.if);
5117
6627
  return this.block(`@if (${this.emit(node.left, PLAIN)})`, arm);
5118
6628
  }
5119
6629
  if (ts.isCallExpression(node))
5120
- return this.forDirective(node);
6630
+ return this.forDirective(node, componentRoot);
5121
6631
  return null;
5122
6632
  }
5123
6633
  /**
@@ -5125,13 +6635,16 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5125
6635
  * directive, or '' for nothing. An arm that is only a value is null; the
5126
6636
  * caller decides whether it may become a `{value}` hole.
5127
6637
  */
5128
- arm(expression) {
6638
+ arm(expression, componentRoot = false) {
5129
6639
  const node = skipParens(expression);
5130
- if (isJsx(node))
6640
+ if (isJsx(node)) {
6641
+ if (componentRoot)
6642
+ this.checkNativeOutput(node);
5131
6643
  return this.relative(this.emit(node, TEMPLATE), node);
6644
+ }
5132
6645
  if (isNullish(node))
5133
6646
  return '';
5134
- const directive = this.directive(node);
6647
+ const directive = this.directive(node, componentRoot);
5135
6648
  // A retained map is a JSX hole, which needs a fragment inside a directive arm.
5136
6649
  return directive?.startsWith('{') ? `<>${directive}</>` : directive;
5137
6650
  }
@@ -5164,12 +6677,13 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5164
6677
  const condition = this.emit(test, PLAIN);
5165
6678
  return `<input defaultValue={${condition} ? ${JSON.stringify(yes)} : ${JSON.stringify(no)}} />`;
5166
6679
  }
5167
- ifDirective(node) {
6680
+ ifDirective(node, componentRoot = false) {
5168
6681
  const shared = this.conditionalInputDefault(node);
5169
6682
  if (shared !== null)
5170
6683
  return shared;
5171
- let whenTrue = this.arm(node.whenTrue);
5172
- let whenFalse = this.arm(node.whenFalse);
6684
+ const literal = componentRoot ? literalCondition(node.condition) : undefined;
6685
+ let whenTrue = this.arm(node.whenTrue, componentRoot && (literal === undefined || literal === 'truthy'));
6686
+ let whenFalse = this.arm(node.whenFalse, componentRoot && literal !== 'truthy');
5173
6687
  // A ternary between two values is a value; one with an element on
5174
6688
  // either side is control flow, and a value arm is a hole in a fragment:
5175
6689
  // a bare `{value}` arm is a JavaScript block, not a hole.
@@ -5188,11 +6702,14 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5188
6702
  const then = this.block(`@if (${condition})`, whenTrue);
5189
6703
  return whenFalse === '' ? then : then + ' ' + this.block('@else', whenFalse);
5190
6704
  }
6705
+ reportOpaqueMap(node) {
6706
+ this.note(RULE.for, 'error', node, 'This receiver can override .map() and inspect the React elements its callback returns. Keep this list in React or verify its map behavior before porting it.');
6707
+ }
5191
6708
  /**
5192
6709
  * `items.map((item, i) => <Row key={item.id} />)` is
5193
6710
  * `@for (const item of items; index i; key item.id) { <Row /> }`.
5194
6711
  */
5195
- forDirective(node) {
6712
+ forDirective(node, componentRoot) {
5196
6713
  const callee = node.expression;
5197
6714
  if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== 'map')
5198
6715
  return null;
@@ -5248,6 +6765,15 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5248
6765
  if (ts.isBlock(fn.body)) {
5249
6766
  const statements = fn.body.statements;
5250
6767
  const last = statements[statements.length - 1];
6768
+ if (last &&
6769
+ ts.isSwitchStatement(last) &&
6770
+ !literal &&
6771
+ !isPrimitiveLiteral(last.expression) &&
6772
+ !fn.asteriskToken &&
6773
+ !fn.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) &&
6774
+ last.caseBlock.clauses.some((clause) => clauseReturnsJsx(clause.statements) === true)) {
6775
+ this.reportOpaqueMap(node);
6776
+ }
5251
6777
  if (!last || !ts.isReturnStatement(last) || !last.expression)
5252
6778
  return null;
5253
6779
  setup = statements.slice(0, -1);
@@ -5281,9 +6807,8 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5281
6807
  return null;
5282
6808
  }
5283
6809
  }
5284
- if (!literal) {
5285
- this.note(RULE.for, 'error', node, 'This receiver can override .map() and inspect the React elements its callback returns. Keep this list in React or verify its map behavior before porting it.');
5286
- }
6810
+ if (!literal)
6811
+ this.reportOpaqueMap(node);
5287
6812
  if (attribute && key && !this.stableRowKey(key, item, iterable)) {
5288
6813
  const open = attribute.parent.parent;
5289
6814
  const children = ts.isJsxElement(root) ? root.children : [];
@@ -5295,7 +6820,7 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5295
6820
  if (!value.expression)
5296
6821
  return false;
5297
6822
  const expression = skipWrappers(value.expression);
5298
- return !(rowKeyLiteral(expression) ||
6823
+ return !(isPrimitiveLiteral(expression) ||
5299
6824
  (ts.isIdentifier(expression) &&
5300
6825
  fixedBinding(this.checker, expression, expression) &&
5301
6826
  initializedBefore(this.checker, expression, expression)));
@@ -5316,6 +6841,16 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5316
6841
  this.note(RULE.for, 'error', node, 'An @for row would discard this callback’s promise or iterator. Review the retained .map() call for suspension or iteration.');
5317
6842
  return null;
5318
6843
  }
6844
+ if (ts.isFunctionExpression(fn) &&
6845
+ fn.name &&
6846
+ (this.localUses(fn.name).length ||
6847
+ reads(fn, (name) => name.text === 'eval' &&
6848
+ !isPropertyName(name) &&
6849
+ !declaresName(name) &&
6850
+ !inTypeNode(name)))) {
6851
+ this.note(MAP_CALLBACK_SCOPE, 'error', node, 'An @for row cannot preserve this map callback’s local function name. Keep the original map callback until these references are migrated explicitly.');
6852
+ return null;
6853
+ }
5319
6854
  if (fn.parameters.some((parameter) => readsFunctionContext(parameter, this.checker))) {
5320
6855
  this.note(MAP_CALLBACK_SCOPE, 'error', node, 'An @for row cannot preserve this callback’s access to this, arguments, or new.target. Keep the original map callback until these reads are migrated explicitly.');
5321
6856
  return null;
@@ -5328,6 +6863,10 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5328
6863
  this.calleeName(opening.tagName) === 'Fragment')
5329
6864
  this.bare.add(opening.parent);
5330
6865
  }
6866
+ if ((componentRoot || this.nativeOutputMaps?.has(node)) &&
6867
+ literal.elements.some((element) => !ts.isSpreadElement(element)) &&
6868
+ (!skipsRow || this.mapRowCanRender(item, literal, setup)))
6869
+ this.checkNativeOutput(root);
5331
6870
  const arm = ts.isConditionalExpression(root)
5332
6871
  ? this.ifDirective(root)
5333
6872
  : this.relative(this.emit(root, TEMPLATE), root);
@@ -5361,22 +6900,53 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5361
6900
  return this.block(header, statements + '\n' + arm);
5362
6901
  }
5363
6902
  patternReadsOrdinal(pattern, ordinal) {
5364
- const eagerBinary = (op) => op === ts.SyntaxKind.CommaToken ||
6903
+ const nonCoercingBinary = (op) => op === ts.SyntaxKind.CommaToken ||
5365
6904
  op === ts.SyntaxKind.EqualsEqualsEqualsToken ||
5366
6905
  op === ts.SyntaxKind.ExclamationEqualsEqualsToken;
6906
+ const safeObjectSpread = (expression) => {
6907
+ const source = skipWrappers(expression);
6908
+ // A fresh record proven below has only own data properties to copy.
6909
+ return ts.isObjectLiteralExpression(source) && safePrefix(source);
6910
+ };
5367
6911
  const safePrefix = (expr) => {
5368
6912
  const value = skipWrappers(expr);
5369
- if (rowKeyLiteral(value))
6913
+ if (isPrimitiveLiteral(value))
5370
6914
  return true;
6915
+ if (ts.isVoidExpression(value))
6916
+ return safePrefix(value.expression);
5371
6917
  if (ts.isBinaryExpression(value))
5372
- return (eagerBinary(value.operatorToken.kind) && safePrefix(value.left) && safePrefix(value.right));
6918
+ return (nonCoercingBinary(value.operatorToken.kind) &&
6919
+ safePrefix(value.left) &&
6920
+ safePrefix(value.right));
5373
6921
  if (ts.isArrayLiteralExpression(value))
5374
6922
  return value.elements.every((element) => ts.isOmittedExpression(element) || safePrefix(element));
5375
6923
  return (ts.isObjectLiteralExpression(value) &&
5376
- value.properties.every((property) => ts.isPropertyAssignment(property) &&
5377
- (!ts.isComputedPropertyName(property.name) ||
5378
- rowKeyLiteral(property.name.expression)) &&
5379
- safePrefix(property.initializer)));
6924
+ value.properties.every((property) => ts.isSpreadAssignment(property)
6925
+ ? safeObjectSpread(property.expression)
6926
+ : ts.isPropertyAssignment(property) &&
6927
+ (!ts.isComputedPropertyName(property.name) ||
6928
+ isPrimitiveLiteral(property.name.expression)) &&
6929
+ safePrefix(property.initializer)));
6930
+ };
6931
+ const branchCondition = (expression) => {
6932
+ const value = skipWrappers(expression);
6933
+ // A fresh array with literal spreads is truthy if its iterators finish.
6934
+ // Branch detection can use that result even when iteration can throw.
6935
+ if (ts.isArrayLiteralExpression(value) &&
6936
+ value.elements.every((element) => {
6937
+ if (!ts.isSpreadElement(element))
6938
+ return ts.isOmittedExpression(element) || safePrefix(element);
6939
+ const source = skipWrappers(element.expression);
6940
+ return ts.isArrayLiteralExpression(source) && safePrefix(source);
6941
+ }))
6942
+ return 'truthy';
6943
+ if (!safePrefix(value))
6944
+ return undefined;
6945
+ // For the allowed unary + and -, the operand has the same truthiness.
6946
+ const literal = ts.isPrefixUnaryExpression(value) ? skipWrappers(value.operand) : value;
6947
+ if (ts.isBigIntLiteral(literal))
6948
+ return /^(?:0[xXoObB])?0+n$/.test(literal.text) ? 'falsy' : 'truthy';
6949
+ return literalCondition(literal);
5380
6950
  };
5381
6951
  // Once a value can interrupt evaluation, a later read is no longer proven.
5382
6952
  const readsInOrder = (expressions) => {
@@ -5397,7 +6967,7 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5397
6967
  const read = skipWrappers(expr);
5398
6968
  if (ts.isIdentifier(read))
5399
6969
  return this.declarationOf(read) === ordinal;
5400
- if (ts.isTypeOfExpression(read) || ts.isVoidExpression(read))
6970
+ if (ts.isTypeOfExpression(read) || ts.isVoidExpression(read) || ts.isDeleteExpression(read))
5401
6971
  return readsOrdinal(read.expression);
5402
6972
  if (ts.isPrefixUnaryExpression(read))
5403
6973
  return (read.operator !== ts.SyntaxKind.PlusPlusToken &&
@@ -5408,17 +6978,16 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5408
6978
  if (ts.isConditionalExpression(read)) {
5409
6979
  if (readsOrdinal(read.condition))
5410
6980
  return true;
5411
- const test = skipWrappers(read.condition).kind;
5412
- if (test === ts.SyntaxKind.TrueKeyword)
5413
- return readsOrdinal(read.whenTrue);
5414
- return test === ts.SyntaxKind.FalseKeyword && readsOrdinal(read.whenFalse);
6981
+ const condition = branchCondition(read.condition);
6982
+ return (condition !== undefined &&
6983
+ readsOrdinal(condition === 'truthy' ? read.whenTrue : read.whenFalse));
5415
6984
  }
5416
6985
  if (ts.isTemplateExpression(read)) {
5417
6986
  for (const { expression } of read.templateSpans) {
5418
6987
  if (readsOrdinal(expression))
5419
6988
  return true;
5420
6989
  // Each interpolation is coerced to text before the next one runs.
5421
- if (!rowKeyLiteral(expression))
6990
+ if (!isPrimitiveLiteral(expression))
5422
6991
  return false;
5423
6992
  }
5424
6993
  return false;
@@ -5427,13 +6996,18 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5427
6996
  return readsInOrder(read.elements.filter((element) => !ts.isOmittedExpression(element)));
5428
6997
  if (ts.isObjectLiteralExpression(read)) {
5429
6998
  for (const property of read.properties) {
5430
- if (ts.isSpreadAssignment(property))
5431
- return readsOrdinal(property.expression);
6999
+ if (ts.isSpreadAssignment(property)) {
7000
+ if (readsOrdinal(property.expression))
7001
+ return true;
7002
+ if (!safeObjectSpread(property.expression))
7003
+ return false;
7004
+ continue;
7005
+ }
5432
7006
  if (ts.isComputedPropertyName(property.name)) {
5433
7007
  const key = property.name.expression;
5434
7008
  if (readsOrdinal(key))
5435
7009
  return true;
5436
- if (!rowKeyLiteral(key))
7010
+ if (!isPrimitiveLiteral(key))
5437
7011
  return false;
5438
7012
  }
5439
7013
  if (ts.isShorthandPropertyAssignment(property))
@@ -5451,12 +7025,23 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5451
7025
  if (readsOrdinal(read.expression))
5452
7026
  return true;
5453
7027
  const receiver = skipWrappers(read.expression);
5454
- // A safe comma expression can still produce null.
7028
+ // A safe prefix can still produce a nullish receiver.
5455
7029
  return (safePrefix(receiver) &&
5456
7030
  (!ts.isOptionalChain(read) ||
5457
- (receiver.kind !== ts.SyntaxKind.NullKeyword && !ts.isBinaryExpression(receiver))) &&
7031
+ (!ts.isBinaryExpression(receiver) && literalCondition(receiver) !== 'nullish')) &&
5458
7032
  readsOrdinal(read.argumentExpression));
5459
7033
  }
7034
+ if (ts.isNewExpression(read)) {
7035
+ const constructor = skipWrappers(read.expression);
7036
+ // A plain inline class finishes defining itself before the arguments run.
7037
+ return (ts.isClassExpression(constructor) &&
7038
+ !constructor.heritageClauses?.length &&
7039
+ !constructor.modifiers?.length &&
7040
+ constructor.members.every((member) => ts.isConstructorDeclaration(member) &&
7041
+ !member.modifiers?.length &&
7042
+ member.parameters.every((parameter) => !ts.getDecorators(parameter)?.length)) &&
7043
+ readsInOrder(read.arguments ?? []));
7044
+ }
5460
7045
  if (ts.isCallExpression(read)) {
5461
7046
  if (readsOrdinal(read.expression))
5462
7047
  return true;
@@ -5464,9 +7049,14 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5464
7049
  if (ts.isArrowFunction(callee) &&
5465
7050
  !callee.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) &&
5466
7051
  callee.parameters.length === 0 &&
5467
- read.arguments.length === 0 &&
5468
- !ts.isBlock(callee.body))
5469
- return readsOrdinal(callee.body);
7052
+ read.arguments.length === 0) {
7053
+ if (!ts.isBlock(callee.body))
7054
+ return readsOrdinal(callee.body);
7055
+ if (callee.body.statements.length !== 1)
7056
+ return false;
7057
+ const [statement] = callee.body.statements;
7058
+ return ts.isReturnStatement(statement) && readsOrdinal(statement.expression);
7059
+ }
5470
7060
  // Optional calls can skip their arguments, and earlier arguments or a
5471
7061
  // member getter can interrupt evaluation before the ordinal read.
5472
7062
  if (!ts.isArrowFunction(callee) && (ts.isOptionalChain(read) || !ts.isIdentifier(callee)))
@@ -5485,25 +7075,25 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5485
7075
  if (!ts.isBinaryExpression(read))
5486
7076
  return false;
5487
7077
  const op = read.operatorToken.kind;
5488
- if (eagerBinary(op))
5489
- return readsInOrder([read.left, read.right]);
5490
7078
  if (op === ts.SyntaxKind.AmpersandAmpersandToken ||
5491
7079
  op === ts.SyntaxKind.BarBarToken ||
5492
7080
  op === ts.SyntaxKind.QuestionQuestionToken) {
5493
7081
  if (readsOrdinal(read.left))
5494
7082
  return true;
5495
- const left = skipWrappers(read.left).kind;
5496
- const rightWhen = op === ts.SyntaxKind.AmpersandAmpersandToken
5497
- ? ts.SyntaxKind.TrueKeyword
7083
+ const condition = branchCondition(read.left);
7084
+ if (condition === undefined)
7085
+ return false;
7086
+ const reachesRight = op === ts.SyntaxKind.AmpersandAmpersandToken
7087
+ ? condition === 'truthy'
5498
7088
  : op === ts.SyntaxKind.BarBarToken
5499
- ? ts.SyntaxKind.FalseKeyword
5500
- : ts.SyntaxKind.NullKeyword;
5501
- return left === rightWhen && readsOrdinal(read.right);
5502
- }
5503
- return (((op >= ts.SyntaxKind.PlusToken && op <= ts.SyntaxKind.PercentToken) ||
5504
- (op >= ts.SyntaxKind.LessThanLessThanToken && op <= ts.SyntaxKind.CaretToken)) &&
5505
- ((rowKeyLiteral(read.right) && readsOrdinal(read.left)) ||
5506
- (rowKeyLiteral(read.left) && readsOrdinal(read.right))));
7089
+ ? condition !== 'truthy'
7090
+ : condition === 'nullish';
7091
+ return reachesRight && readsOrdinal(read.right);
7092
+ }
7093
+ // Ordinary non-assignment operators read operands before coercion.
7094
+ // A private brand operand is not a proven prefix, so the scan stops there.
7095
+ return ((op < ts.SyntaxKind.FirstAssignment || op > ts.SyntaxKind.LastAssignment) &&
7096
+ readsInOrder([read.left, read.right]));
5507
7097
  };
5508
7098
  return (!ts.isIdentifier(pattern) &&
5509
7099
  pattern.elements.some((element) => ts.isBindingElement(element) &&
@@ -5553,6 +7143,32 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5553
7143
  };
5554
7144
  return statements.some(exitsWithValue) ? null : exits;
5555
7145
  }
7146
+ /** A literal row remains after a single numeric equality guard skips its match. */
7147
+ mapRowCanRender(item, literal, setup) {
7148
+ const [guard] = setup;
7149
+ if (setup.length !== 1 || !ts.isIfStatement(guard) || guard.elseStatement)
7150
+ return false;
7151
+ const branch = guard.thenStatement;
7152
+ const exit = ts.isBlock(branch) && branch.statements.length === 1 ? branch.statements[0] : branch;
7153
+ const test = skipParens(guard.expression);
7154
+ if (!ts.isReturnStatement(exit) ||
7155
+ !ts.isBinaryExpression(test) ||
7156
+ test.operatorToken.kind !== ts.SyntaxKind.EqualsEqualsEqualsToken)
7157
+ return false;
7158
+ const left = skipWrappers(test.left);
7159
+ const right = skipWrappers(test.right);
7160
+ const compared = ts.isIdentifier(left) && this.declarationOf(left) === item
7161
+ ? right
7162
+ : ts.isIdentifier(right) && this.declarationOf(right) === item
7163
+ ? left
7164
+ : null;
7165
+ const skipped = compared === null ? undefined : numericConstantValue(compared);
7166
+ return (skipped !== undefined &&
7167
+ literal.elements.some((element) => {
7168
+ const value = numericConstantValue(element);
7169
+ return value !== undefined && value !== skipped;
7170
+ }));
7171
+ }
5556
7172
  // The automatic JSX runtime receives props (including children) before its
5557
7173
  // separate key argument. Keep a block-body map so the compiler builds every
5558
7174
  // row value before rendering any of them.
@@ -5600,14 +7216,14 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5600
7216
  return '{' + head + '{ return ' + row + '; }' + tail + '}';
5601
7217
  }
5602
7218
  stableRowKey(key, item, iterable) {
5603
- if (rowKeyLiteral(key))
7219
+ if (isPrimitiveLiteral(key))
5604
7220
  return true;
5605
7221
  key = skipWrappers(key);
5606
7222
  const source = skipWrappers(iterable);
5607
7223
  return (ts.isIdentifier(key) &&
5608
7224
  this.declarationOf(key) === item &&
5609
7225
  ts.isArrayLiteralExpression(source) &&
5610
- source.elements.every(rowKeyLiteral) &&
7226
+ source.elements.every(isPrimitiveLiteral) &&
5611
7227
  fixedBinding(this.checker, key, key));
5612
7228
  }
5613
7229
  /** An @for header evaluates its key before the row body runs. */
@@ -5619,7 +7235,7 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5619
7235
  // Even an accessor key can precede initialization that reads nothing.
5620
7236
  return (setup.every((statement) => ts.isVariableStatement(statement) &&
5621
7237
  (statement.declarationList.flags & ts.NodeFlags.BlockScoped) === ts.NodeFlags.Const &&
5622
- statement.declarationList.declarations.every(({ name, initializer }) => ts.isIdentifier(name) && initializer !== undefined && rowKeyLiteral(initializer))) && !reads(key, (name) => name.text === 'eval' && !isPropertyName(name)));
7238
+ statement.declarationList.declarations.every(({ name, initializer }) => ts.isIdentifier(name) && initializer !== undefined && isPrimitiveLiteral(initializer))) && !reads(key, (name) => name.text === 'eval' && !isPropertyName(name)));
5623
7239
  }
5624
7240
  readsLocals(expression, statements) {
5625
7241
  const declared = new Set(statements
@@ -5662,13 +7278,27 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5662
7278
  if (!last || !ts.isReturnStatement(last) || !last.expression)
5663
7279
  return null;
5664
7280
  const guard = statements.findIndex((s, i) => i < statements.length - 1 && guardReturn(s));
5665
- if (guard !== -1)
5666
- return this.rewriteGuards(node, body, guard);
7281
+ if (guard !== -1) {
7282
+ const output = this.rewriteGuards(node, body, guard);
7283
+ if (output !== null)
7284
+ return output;
7285
+ }
7286
+ const inner = skipParens(last.expression);
5667
7287
  // A template body has one output; any other early `return <A />` would
5668
7288
  // render through runtime descriptors, so the plain function stays.
5669
- if (returnsJsx(statements.slice(0, -1)))
7289
+ const setupStatements = statements.slice(0, -1);
7290
+ if (guard !== -1 || returnsJsx(setupStatements)) {
7291
+ if (this.options.localReactClass &&
7292
+ isJsx(inner) &&
7293
+ this.moduleComponent(node) &&
7294
+ setupStatements.every((statement) => ts.isVariableStatement(statement) ||
7295
+ (ts.isIfStatement(statement) &&
7296
+ !statement.elseStatement &&
7297
+ literalCondition(statement.expression) !== 'truthy')) &&
7298
+ this.options.automaticReactJsx)
7299
+ this.checkNativeOutput(inner, false, true);
5670
7300
  return null;
5671
- const inner = skipParens(last.expression);
7301
+ }
5672
7302
  let output = this.output(inner);
5673
7303
  if (output === null)
5674
7304
  return null;
@@ -5707,7 +7337,14 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5707
7337
  const rest = statements.slice(first + 1, -1).filter((statement) => !guardReturn(statement));
5708
7338
  if (returnsJsx(statements.slice(0, first)) || this.emptyArmExit(rest) === null)
5709
7339
  return null;
5710
- const output = this.arm(last.expression);
7340
+ const checkRoot = this.options.localReactClass !== undefined || this.options.localReactContext !== undefined;
7341
+ const terminal = checkRoot
7342
+ ? statements.findIndex((statement, index) => index >= first &&
7343
+ ts.isIfStatement(statement) &&
7344
+ guardReturn(statement) &&
7345
+ literalCondition(statement.expression) === 'truthy')
7346
+ : -1;
7347
+ const output = this.arm(last.expression, checkRoot && terminal === -1);
5711
7348
  if (output === null)
5712
7349
  return null;
5713
7350
  const chain = (from) => {
@@ -5725,8 +7362,11 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5725
7362
  if (at === statements.length - 1)
5726
7363
  return prefix + output;
5727
7364
  const guard = statements[at];
7365
+ const condition = checkRoot ? literalCondition(guard.expression) : undefined;
5728
7366
  this.count(RULE.if);
5729
- const then = this.block(`@if (${this.emit(guard.expression, PLAIN)})`, this.arm(guardReturn(guard)));
7367
+ const then = this.block(`@if (${this.emit(guard.expression, PLAIN)})`, this.arm(guardReturn(guard), checkRoot &&
7368
+ (terminal === -1 || at <= terminal) &&
7369
+ (condition === undefined || condition === 'truthy')));
5730
7370
  const rest = chain(at + 1);
5731
7371
  return prefix + (rest === '' ? then : then + ' ' + this.block('@else', rest));
5732
7372
  };
@@ -5747,17 +7387,290 @@ type ${handler}<T = unknown> = { listener(event: ${event}<T>): void }['listener'
5747
7387
  * and indentation `node` had, or null when it is not a single renderable.
5748
7388
  */
5749
7389
  output(node) {
5750
- if (isJsx(node))
7390
+ if (isJsx(node)) {
7391
+ this.checkNativeOutput(node);
5751
7392
  return this.emit(node, TEMPLATE);
7393
+ }
5752
7394
  if (ts.isConditionalExpression(node) || ts.isCallExpression(node)) {
5753
- const directive = this.directive(node);
7395
+ const directive = this.directive(node, this.options.localReactClass !== undefined || this.options.localReactContext !== undefined);
5754
7396
  return directive === null ? null : this.absolute(directive, node);
5755
7397
  }
5756
7398
  return null;
5757
7399
  }
7400
+ /** Possible values if the expression completes, grouped by short-circuit behavior. */
7401
+ logicalResult(expression) {
7402
+ const node = skipWrappers(expression);
7403
+ if (isJsx(node))
7404
+ return TRUTHY;
7405
+ switch (literalCondition(node)) {
7406
+ case 'truthy':
7407
+ return TRUTHY;
7408
+ case 'falsy':
7409
+ return FALSY;
7410
+ case 'nullish':
7411
+ return NULLISH;
7412
+ }
7413
+ if (ts.isBinaryExpression(node)) {
7414
+ const rightCases = logicalRightCases(node.operatorToken.kind);
7415
+ if (rightCases) {
7416
+ // Left-associated chains are also visited as possible template outputs.
7417
+ const cached = this.logicalResults?.get(node);
7418
+ if (cached !== undefined)
7419
+ return cached;
7420
+ const left = this.logicalResult(node.left);
7421
+ let result = left & ~rightCases;
7422
+ if (left & rightCases)
7423
+ result |= this.logicalResult(node.right);
7424
+ (this.logicalResults ??= new WeakMap()).set(node, result);
7425
+ return result;
7426
+ }
7427
+ }
7428
+ return TRUTHY | FALSY | NULLISH;
7429
+ }
7430
+ checkNativeOutput(node, conditional = false, retained = false, descriptorValue = false) {
7431
+ if (!this.options.localReactClass && !this.options.localReactContext)
7432
+ return;
7433
+ if (!retained) {
7434
+ while (isWrapper(node)) {
7435
+ // String assertions select text in template holes. Descriptor values erase them.
7436
+ if (!descriptorValue &&
7437
+ (ts.isAsExpression(node) ||
7438
+ ts.isSatisfiesExpression(node) ||
7439
+ ts.isTypeAssertionExpression(node)) &&
7440
+ node.type.kind === ts.SyntaxKind.StringKeyword)
7441
+ return;
7442
+ node = node.expression;
7443
+ }
7444
+ if (ts.isConditionalExpression(node)) {
7445
+ const condition = literalCondition(node.condition);
7446
+ if (condition === undefined || condition === 'truthy')
7447
+ this.checkNativeOutput(node.whenTrue, conditional, false, descriptorValue);
7448
+ if (condition !== 'truthy')
7449
+ this.checkNativeOutput(node.whenFalse, conditional, false, descriptorValue);
7450
+ return;
7451
+ }
7452
+ if (ts.isBinaryExpression(node)) {
7453
+ const operator = node.operatorToken.kind;
7454
+ const rightCases = logicalRightCases(operator);
7455
+ if (!rightCases)
7456
+ return;
7457
+ const left = this.logicalResult(node.left);
7458
+ // The left result of && is falsy and cannot render JSX.
7459
+ if (operator !== ts.SyntaxKind.AmpersandAmpersandToken && left & ~rightCases)
7460
+ this.checkNativeOutput(node.left, conditional, false, descriptorValue);
7461
+ if (left & rightCases)
7462
+ this.checkNativeOutput(node.right, conditional, false, descriptorValue);
7463
+ return;
7464
+ }
7465
+ if (ts.isArrayLiteralExpression(node)) {
7466
+ for (const element of node.elements)
7467
+ this.checkNativeOutput(element, conditional, false, true);
7468
+ return;
7469
+ }
7470
+ if (ts.isCallExpression(node)) {
7471
+ const callee = node.expression;
7472
+ if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== 'map')
7473
+ return;
7474
+ if (descriptorValue) {
7475
+ if (this.options.localReactClass)
7476
+ this.checkDescriptorMapClassOutput(node, callee.expression);
7477
+ }
7478
+ else if (!conditional)
7479
+ (this.nativeOutputMaps ??= new WeakSet()).add(node);
7480
+ return;
7481
+ }
7482
+ }
7483
+ if (!isJsx(node))
7484
+ return;
7485
+ if (!ts.isJsxFragment(node)) {
7486
+ if (this.retainedReactOutput(node))
7487
+ return;
7488
+ if (!retained && !descriptorValue) {
7489
+ this.checkRetainedReactContext(node);
7490
+ this.checkRetainedReactTemplateComponent(node);
7491
+ }
7492
+ if (ts.isJsxSelfClosingElement(node))
7493
+ return this.checkReactClassRoot(node, conditional, retained);
7494
+ if (!retained && rendersOrdinaryHtmlChildren(node.openingElement)) {
7495
+ this.checkNativeChildren(node, conditional, false, descriptorValue);
7496
+ return;
7497
+ }
7498
+ const tag = node.openingElement.tagName;
7499
+ const callee = this.callee(tag);
7500
+ if (callee?.module !== 'react' && callee?.module !== 'octane')
7501
+ return this.checkReactClassRoot(node, conditional, retained);
7502
+ if (callee.name === 'Fragment' || callee.name === 'Suspense') {
7503
+ const member = ts.isPropertyAccessExpression(tag);
7504
+ const reference = member ? tag.expression : tag;
7505
+ const declaration = ts.isIdentifier(reference) && this.declarationOf(reference);
7506
+ if (!declaration ||
7507
+ this.imports.get(declaration)?.typeOnly !== false ||
7508
+ (member && callee.module === 'octane' && !ts.isNamespaceImport(declaration)))
7509
+ return this.checkReactClassRoot(node, conditional, retained);
7510
+ const imp = ts.findAncestor(declaration, ts.isImportDeclaration);
7511
+ if (!imp || imp.attributes)
7512
+ return this.checkReactClassRoot(node, conditional, retained);
7513
+ if (callee.name === 'Suspense') {
7514
+ const fallback = !retained && this.suspenseFallback(node, true);
7515
+ if (!fallback)
7516
+ return this.checkReactClassRoot(node, conditional, retained);
7517
+ if (ts.isJsxExpression(fallback) && fallback.expression) {
7518
+ const expression = skipParens(fallback.expression);
7519
+ if (isJsx(expression))
7520
+ this.checkNativeOutput(expression, conditional === 'map' ? 'map' : true, false, descriptorValue);
7521
+ }
7522
+ }
7523
+ }
7524
+ else if (callee.name !== 'StrictMode') {
7525
+ return this.checkReactClassRoot(node, conditional, retained);
7526
+ }
7527
+ }
7528
+ this.checkNativeChildren(node, conditional, retained, descriptorValue);
7529
+ }
7530
+ checkDescriptorMapClassOutput(call, receiver) {
7531
+ const array = skipWrappers(receiver);
7532
+ const [argument] = call.arguments;
7533
+ if (!ts.isArrayLiteralExpression(array) ||
7534
+ !array.elements.some((element) => !ts.isSpreadElement(element) && !ts.isOmittedExpression(element)) ||
7535
+ call.arguments.length !== 1)
7536
+ return;
7537
+ const fn = skipWrappers(argument);
7538
+ if ((!ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) ||
7539
+ fn.modifiers?.length ||
7540
+ fn.asteriskToken)
7541
+ return;
7542
+ const output = singleCallbackExpression(fn.body);
7543
+ // The retained map can be overridden and discard its callback's result.
7544
+ if (output)
7545
+ this.checkNativeOutput(output, 'map', false, true);
7546
+ }
7547
+ checkNativeChildren(node, conditional, retained, descriptorValue) {
7548
+ for (const child of node.children) {
7549
+ if (isJsx(child))
7550
+ this.checkNativeOutput(child, conditional, retained, descriptorValue);
7551
+ else if (!retained && ts.isJsxExpression(child) && child.expression && !child.dotDotDotToken)
7552
+ this.checkNativeOutput(child.expression, conditional, false, descriptorValue);
7553
+ }
7554
+ }
7555
+ retainedReactOutput(node) {
7556
+ return (this.islands.has(node) || this.unrenderable.has(node) || this.reactRendererBodies.has(node));
7557
+ }
7558
+ directImportedValue(tag) {
7559
+ if (!ts.isIdentifier(tag))
7560
+ return;
7561
+ const entry = this.importOf(tag);
7562
+ if (!entry || entry.namespace || entry.typeOnly)
7563
+ return;
7564
+ const declaration = ts.findAncestor(this.declarationOf(tag), ts.isImportDeclaration);
7565
+ if (declaration && !declaration.attributes)
7566
+ return { tag, entry };
7567
+ }
7568
+ checkRetainedReactTemplateComponent(node) {
7569
+ const check = this.options.localReactTemplateComponent;
7570
+ if (!check)
7571
+ return;
7572
+ const tag = ts.isJsxElement(node) ? node.openingElement.tagName : node.tagName;
7573
+ if (!ts.isIdentifier(tag) || !isComponentName(tag.text))
7574
+ return;
7575
+ const binding = this.directImportedValue(tag);
7576
+ if (!binding || !check(binding.entry.module, binding.entry.imported))
7577
+ return;
7578
+ this.note('retained-react-component', 'warning', tag, `This native template can render ${tag.text} from the unchanged ${binding.entry.module} module. Its JSX returns a React element under the project's React JSX settings. Migrate the component too or keep its render under React.`);
7579
+ }
7580
+ checkRetainedReactContext(node) {
7581
+ const check = this.options.localReactContext;
7582
+ if (!check)
7583
+ return;
7584
+ const tag = ts.isJsxElement(node) ? node.openingElement.tagName : node.tagName;
7585
+ const provider = ts.isPropertyAccessExpression(tag) && tag.name.text === 'Provider';
7586
+ if (!provider && (!ts.isIdentifier(tag) || !isComponentName(tag.text)))
7587
+ return;
7588
+ const binding = this.directImportedValue(provider ? tag.expression : tag);
7589
+ if (!binding)
7590
+ return;
7591
+ const { tag: context, entry } = binding;
7592
+ if (!check(entry.module, entry.imported, false))
7593
+ return;
7594
+ const retainedMember = provider && !this.isContext(context);
7595
+ if (retainedMember &&
7596
+ (!check(entry.module, entry.imported, true) || !this.hasUnchangedProviderUse(context)))
7597
+ return;
7598
+ this.note('retained-react-context', 'warning', tag, retainedMember
7599
+ ? `If \`${context.text}.Provider\` from \`${entry.module}\` still exposes the React provider, this native template cannot render it. Verify the runtime import and keep this render in React or migrate the context producer.`
7600
+ : `If this native template resolves \`${entry.module}\` to the retained React context \`${context.text}\`, Octane cannot render it as a provider. Verify the runtime import and keep this render in React or migrate the context producer.`);
7601
+ }
7602
+ hasUnchangedProviderUse(context) {
7603
+ let originalReact;
7604
+ const readContext = (callee) => {
7605
+ if (!ts.isIdentifier(callee))
7606
+ return false;
7607
+ const hook = this.directImportedValue(callee)?.entry;
7608
+ return (hook?.module === 'react' &&
7609
+ hook.imported === 'useContext' &&
7610
+ (originalReact ??= this.options.originalReact === true));
7611
+ };
7612
+ return ((!/eval|\\/.test(this.source) || !hasEval(this.sf)) &&
7613
+ this.localUses(context).every((ref) => declaresName(ref) || unchangedContextProviderUse(ref, readContext)));
7614
+ }
7615
+ checkReactClassRoot(node, conditional, retained) {
7616
+ const check = this.options.localReactClass;
7617
+ if (!check)
7618
+ return;
7619
+ const tagName = ts.isJsxElement(node) ? node.openingElement.tagName : node.tagName;
7620
+ if (!ts.isIdentifier(tagName) || !isComponentName(tagName.text))
7621
+ return;
7622
+ const binding = this.directImportedValue(tagName);
7623
+ if (!binding)
7624
+ return;
7625
+ const { tag, entry } = binding;
7626
+ const proof = check(entry.module, entry.imported);
7627
+ if (!proof)
7628
+ return;
7629
+ const severity = conditional === 'map' ? 'warning' : proof;
7630
+ this.note(RULE.classComponent, severity, tag, severity === 'error'
7631
+ ? `The migration resolves \`${entry.module}\` to the imported React class \`${tag.text}\`, ${retained ? 'which fails if Octane renders this output' : `which this native template ${conditional ? 'can render' : 'renders'}`}. Keep this render in React or replace the class with an Octane function component.`
7632
+ : `If ${retained ? 'Octane' : 'this native template'} renders the imported React class \`${tag.text}\` resolved from \`${entry.module}\`, the call will fail. Verify the runtime import, keep the render in React, or replace the class with an Octane function component.`);
7633
+ }
5758
7634
  startsLine(node) {
5759
7635
  return this.linePrefix(node).trim() === '';
5760
7636
  }
7637
+ /** A direct module component, without going through an arbitrary wrapper or callback. */
7638
+ moduleComponent(node) {
7639
+ const parent = node.parent;
7640
+ if (ts.isExportAssignment(parent))
7641
+ return !parent.isExportEquals && parent.parent === this.sf;
7642
+ let statement;
7643
+ let name;
7644
+ if (ts.isFunctionDeclaration(node)) {
7645
+ statement = node;
7646
+ name = node.name;
7647
+ }
7648
+ else {
7649
+ if (!ts.isVariableDeclaration(parent) ||
7650
+ parent.initializer !== node ||
7651
+ !ts.isIdentifier(parent.name) ||
7652
+ !isComponentName(parent.name.text) ||
7653
+ (ts.getCombinedNodeFlags(parent) & ts.NodeFlags.BlockScoped) !== ts.NodeFlags.Const ||
7654
+ !ts.isVariableStatement(parent.parent.parent))
7655
+ return false;
7656
+ statement = parent.parent.parent;
7657
+ name = parent.name;
7658
+ }
7659
+ if (statement.parent !== this.sf)
7660
+ return false;
7661
+ if (statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword))
7662
+ return true;
7663
+ if (!name)
7664
+ return false;
7665
+ const refs = renderUses(this.localUses(name));
7666
+ return (refs.some((ref) => ts.isExportSpecifier(ref.parent)
7667
+ ? !ref.parent.parent.parent.moduleSpecifier
7668
+ : ts.isExportAssignment(ref.parent) && !ref.parent.isExportEquals) ||
7669
+ (refs.length > 0 &&
7670
+ refs.every((ref) => !ts.isExportAssignment(ref.parent) &&
7671
+ !ts.isExportSpecifier(ref.parent) &&
7672
+ componentTagOrExport(ref))));
7673
+ }
5761
7674
  /**
5762
7675
  * Whether `node` is a component definition: a capitalized function, or the
5763
7676
  * function passed to `memo` / `forwardRef`, or a default-exported one.