@octanejs/codemod 0.2.1 → 0.2.2

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.
@@ -1,9 +1,12 @@
1
1
  import ts from 'typescript';
2
+ import { parseSync } from '@tsrx/oxc/parser';
2
3
  import { hasRuntimeDependency } from './scoped-store-contract.js';
3
- import { skipWrappers } from './expression-wrappers.js';
4
- import { hasEval } from './forwarded-props.js';
5
- import { componentTagOrExport, localUses } from './local-uses.js';
6
- import { bind, nativeReactCompat, withoutJsxIndentation } from './transform.js';
4
+ import { literalCondition, skipWrappers } from './expression-wrappers.js';
5
+ import { atInitializedModuleHandle, initializedBefore } from './effect-receivers.js';
6
+ import { hasEval, rendersElementChildren, rootHandleEscapes } from './forwarded-props.js';
7
+ import { componentTagOrExport, inTypeNode, localUses, unchangedContextProviderUse, } from './local-uses.js';
8
+ import { staticReactProps } from './react-renderer.js';
9
+ import { bind, nativeReactCompat, skipParens, withoutJsxIndentation } from './transform.js';
7
10
  export function importsReactBridge(source) {
8
11
  return (((source.includes('ReactCompat') && source.includes('octane/react')) ||
9
12
  source.includes('\\')) &&
@@ -27,7 +30,7 @@ async function bindIsland(file, source) {
27
30
  }
28
31
  return bind(file.endsWith('.tsrx') ? file + '.tsx' : file, code);
29
32
  }
30
- function imported(checker, node) {
33
+ function imported(checker, node, defaultMember = false) {
31
34
  const ref = ts.isPropertyAccessExpression(node) ? node.expression : node;
32
35
  if (!ts.isIdentifier(ref))
33
36
  return;
@@ -35,7 +38,7 @@ function imported(checker, node) {
35
38
  if (!decl)
36
39
  return;
37
40
  const name = ts.isPropertyAccessExpression(node)
38
- ? ts.isNamespaceImport(decl) && node.name.text
41
+ ? (ts.isNamespaceImport(decl) || (defaultMember && ts.isImportClause(decl))) && node.name.text
39
42
  : ts.isImportSpecifier(decl) && !decl.isTypeOnly
40
43
  ? (decl.propertyName ?? decl.name).text
41
44
  : ts.isImportClause(decl) && 'default';
@@ -46,6 +49,195 @@ function imported(checker, node) {
46
49
  ts.isStringLiteral(imp.moduleSpecifier))
47
50
  return { name, module: imp.moduleSpecifier.text };
48
51
  }
52
+ function closedReactReceiver(receiver, uses) {
53
+ return uses(receiver).every((ref) => {
54
+ if (ts.isImportClause(ref.parent) || ts.isNamespaceImport(ref.parent) || inTypeNode(ref))
55
+ return true;
56
+ const member = ref.parent;
57
+ if (!ts.isPropertyAccessExpression(member) || member.expression !== ref)
58
+ return false;
59
+ const parent = member.parent;
60
+ return (ts.isExpressionWithTypeArguments(parent) ||
61
+ ((ts.isJsxOpeningElement(parent) ||
62
+ ts.isJsxClosingElement(parent) ||
63
+ ts.isJsxSelfClosingElement(parent)) &&
64
+ parent.tagName === member &&
65
+ (member.name.text === 'Fragment' ||
66
+ member.name.text === 'Suspense' ||
67
+ member.name.text === 'StrictMode')) ||
68
+ (ts.isCallExpression(parent) &&
69
+ parent.expression === member &&
70
+ member.name.text !== 'default'));
71
+ });
72
+ }
73
+ function soleReactReceiver(checker, receiver) {
74
+ const declaration = checker.getSymbolAtLocation(receiver)?.declarations?.[0];
75
+ return (declaration &&
76
+ (ts.isNamespaceImport(declaration)
77
+ ? !declaration.parent.name
78
+ : ts.isImportClause(declaration) && !declaration.namedBindings));
79
+ }
80
+ /** A direct assignment of inert metadata does not change the exported constructor. */
81
+ function classMetadataAssignment(ref, decl) {
82
+ const access = ref.parent;
83
+ if (!ts.isPropertyAccessExpression(access) || access.expression !== ref)
84
+ return false;
85
+ const name = access.name.text;
86
+ if (name !== 'displayName' && name !== 'defaultProps')
87
+ return false;
88
+ const assignment = access.parent;
89
+ if (!ts.isBinaryExpression(assignment) ||
90
+ assignment.left !== access ||
91
+ assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||
92
+ !ts.isExpressionStatement(assignment.parent) ||
93
+ assignment.parent.parent !== decl.parent ||
94
+ assignment.getStart() < decl.end ||
95
+ decl.members.some((member) => ts.isClassStaticBlockDeclaration(member) ||
96
+ (member.name && ts.isComputedPropertyName(member.name)) ||
97
+ (ts.canHaveDecorators(member) && ts.getDecorators(member)?.length) ||
98
+ (ts.getCombinedModifierFlags(member) & ts.ModifierFlags.Static &&
99
+ (ts.isPropertyDeclaration(member) ||
100
+ ts.isSetAccessorDeclaration(member) ||
101
+ ts.isGetAccessorDeclaration(member)))))
102
+ return false;
103
+ const value = skipWrappers(assignment.right);
104
+ if (name === 'displayName')
105
+ return ts.isStringLiteralLike(value);
106
+ return (ts.isObjectLiteralExpression(value) &&
107
+ value.properties.every((field) => {
108
+ if (!ts.isPropertyAssignment(field) ||
109
+ !(ts.isIdentifier(field.name) ||
110
+ ts.isStringLiteral(field.name) ||
111
+ ts.isNumericLiteral(field.name)) ||
112
+ field.name.text === '__proto__')
113
+ return false;
114
+ const value = skipWrappers(field.initializer);
115
+ return (ts.isStringLiteralLike(value) ||
116
+ ts.isNumericLiteral(value) ||
117
+ value.kind === ts.SyntaxKind.TrueKeyword ||
118
+ value.kind === ts.SyntaxKind.FalseKeyword ||
119
+ value.kind === ts.SyntaxKind.NullKeyword);
120
+ }));
121
+ }
122
+ function localValueExport(symbol, checker) {
123
+ const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
124
+ if (!declaration || !ts.isExportSpecifier(declaration))
125
+ return declaration;
126
+ const exported = declaration.parent.parent;
127
+ if (declaration.isTypeOnly || exported.isTypeOnly || exported.moduleSpecifier)
128
+ return;
129
+ return checker.getExportSpecifierLocalTargetSymbol(declaration)?.valueDeclaration;
130
+ }
131
+ /** Direct React class exports, including an alias in a local export list. */
132
+ export function reactClassExports(file, source) {
133
+ const { sf, checker } = bind(file, source);
134
+ const names = new Set();
135
+ const module = checker.getSymbolAtLocation(sf);
136
+ if (!module || hasEval(sf))
137
+ return names;
138
+ const uses = localUses(sf, checker);
139
+ let decorators;
140
+ const hasDecorator = (node) => ts.isDecorator(node) ||
141
+ (ts.forEachChild(node, (child) => hasDecorator(child) || undefined) ?? false);
142
+ const erasedClassUse = (ref) => inTypeNode(ref) &&
143
+ (ts.isTypeQueryNode(ref.parent) || !(decorators ??= source.includes('@') && hasDecorator(sf)));
144
+ for (const symbol of checker.getExportsOfModule(module)) {
145
+ let decl = localValueExport(symbol, checker);
146
+ if (decl && ts.isExportAssignment(decl)) {
147
+ const value = decl.expression;
148
+ if (decl.isExportEquals || !ts.isIdentifier(value))
149
+ continue;
150
+ const local = checker.getSymbolAtLocation(value)?.valueDeclaration;
151
+ if (!local || local.parent !== sf || local.end > decl.getStart(sf))
152
+ continue;
153
+ decl = local;
154
+ }
155
+ if (!decl ||
156
+ !ts.isClassDeclaration(decl) ||
157
+ ts.getCombinedModifierFlags(decl) & ts.ModifierFlags.Ambient ||
158
+ ts.getDecorators(decl)?.length)
159
+ continue;
160
+ const base = decl.heritageClauses?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword)?.types[0]?.expression;
161
+ if (!base)
162
+ continue;
163
+ let entry = imported(checker, base);
164
+ if (!entry && ts.isPropertyAccessExpression(base) && ts.isIdentifier(base.expression)) {
165
+ const candidate = imported(checker, base, true);
166
+ if (candidate?.module === 'react' && closedReactReceiver(base.expression, uses))
167
+ entry = candidate;
168
+ }
169
+ if (entry?.module !== 'react' || (entry.name !== 'Component' && entry.name !== 'PureComponent'))
170
+ continue;
171
+ if (!decl.name ||
172
+ uses(decl.name).every((ref) => erasedClassUse(ref) || componentTagOrExport(ref) || classMetadataAssignment(ref, decl)))
173
+ names.add(symbol.name);
174
+ }
175
+ return names;
176
+ }
177
+ function hasSingleReactImport(sf, source) {
178
+ const erased = new Set();
179
+ for (const statement of sf.statements) {
180
+ if ((ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) &&
181
+ statement.moduleSpecifier &&
182
+ !hasRuntimeDependency(statement, true))
183
+ erased.add(statement.moduleSpecifier.getStart(sf));
184
+ }
185
+ // Keep dynamic imports and require calls in the scan. Only declaration-level
186
+ // type imports and exports are erased even with verbatim module syntax.
187
+ return (ts
188
+ .preProcessFile(source, true, true)
189
+ .importedFiles.filter(({ fileName, pos }) => fileName === 'react' && !erased.has(pos))
190
+ .length === 1);
191
+ }
192
+ /** Direct module-level const exports initialized by the real React context factory. */
193
+ export function retainedReactContextExports(file, source) {
194
+ const { sf, checker } = bind(file, source);
195
+ const module = checker.getSymbolAtLocation(sf);
196
+ const names = new Map();
197
+ if (!module)
198
+ return names;
199
+ let uses;
200
+ let singleReactImport;
201
+ let dynamicScope;
202
+ const readContext = (callee) => {
203
+ const hook = ts.isIdentifier(callee) && imported(checker, callee);
204
+ return !!hook && hook.module === 'react' && hook.name === 'useContext';
205
+ };
206
+ for (const symbol of checker.getExportsOfModule(module)) {
207
+ const declaration = localValueExport(symbol, checker);
208
+ if (!declaration || !ts.isVariableDeclaration(declaration) || !declaration.initializer)
209
+ continue;
210
+ const list = declaration.parent;
211
+ if ((list.flags & ts.NodeFlags.BlockScoped) !== ts.NodeFlags.Const ||
212
+ !ts.isVariableStatement(list.parent) ||
213
+ list.parent.parent !== sf ||
214
+ ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Ambient)
215
+ continue;
216
+ const init = skipWrappers(declaration.initializer);
217
+ if (!ts.isCallExpression(init) || ts.isOptionalChain(init))
218
+ continue;
219
+ const factory = init.expression;
220
+ const entry = imported(checker, factory, true);
221
+ if (entry?.module !== 'react' || entry.name !== 'createContext')
222
+ continue;
223
+ if (ts.isPropertyAccessExpression(factory)) {
224
+ // With interop the default and namespace can share the same mutable React object.
225
+ singleReactImport ??= !(dynamicScope ??= hasEval(sf)) && hasSingleReactImport(sf, source);
226
+ if (!singleReactImport ||
227
+ !ts.isIdentifier(factory.expression) ||
228
+ !soleReactReceiver(checker, factory.expression) ||
229
+ !closedReactReceiver(factory.expression, (uses ??= localUses(sf, checker))))
230
+ continue;
231
+ }
232
+ // The context itself stays a React value even if its Provider member is reassigned.
233
+ // For a retained member read, require the producer to keep that object local.
234
+ const unchangedProvider = ts.isIdentifier(declaration.name) &&
235
+ !(dynamicScope ??= hasEval(sf)) &&
236
+ (uses ??= localUses(sf, checker))(declaration.name).every((ref) => unchangedContextProviderUse(ref, readContext));
237
+ names.set(symbol.name, unchangedProvider);
238
+ }
239
+ return names;
240
+ }
49
241
  /** Original imported components handed to an authored React island. */
50
242
  export async function islandComponents(file, source, original) {
51
243
  const bound = await bindIsland(file, source);
@@ -127,7 +319,7 @@ export async function islandComponents(file, source, original) {
127
319
  visit(sf);
128
320
  return [...components];
129
321
  }
130
- function* directExportReturns({ sf, checker }) {
322
+ function* exportReturns({ sf, checker }, allowSetup = false) {
131
323
  const module = checker.getSymbolAtLocation(sf);
132
324
  if (!module || hasEval(sf))
133
325
  return;
@@ -136,6 +328,19 @@ function* directExportReturns({ sf, checker }) {
136
328
  let decl = symbol.valueDeclaration ?? symbol.declarations?.[0];
137
329
  if (!decl)
138
330
  continue;
331
+ let splitExport = false;
332
+ if (ts.isExportSpecifier(decl)) {
333
+ if (!allowSetup ||
334
+ decl.isTypeOnly ||
335
+ decl.parent.parent.isTypeOnly ||
336
+ decl.parent.parent.moduleSpecifier)
337
+ continue;
338
+ const local = checker.getExportSpecifierLocalTargetSymbol(decl)?.valueDeclaration;
339
+ if (!local || !ts.isFunctionDeclaration(local))
340
+ continue;
341
+ splitExport = true;
342
+ decl = local;
343
+ }
139
344
  let value = decl;
140
345
  let defaultRef;
141
346
  if (ts.isExportAssignment(decl)) {
@@ -162,28 +367,84 @@ function* directExportReturns({ sf, checker }) {
162
367
  continue;
163
368
  value = skipWrappers(value.initializer);
164
369
  }
165
- const output = returnedJsx(value);
166
- if (output)
167
- yield { name: symbol.name, output, localName: name?.text };
370
+ const returned = singleReturn(value, allowSetup);
371
+ if (returned)
372
+ yield {
373
+ name: symbol.name,
374
+ output: skipWrappers(returned),
375
+ localName: name?.text,
376
+ decl,
377
+ symbol,
378
+ splitExport,
379
+ };
380
+ }
381
+ }
382
+ function* directExportReturns(bound, allowSetup = false) {
383
+ for (const entry of exportReturns(bound, allowSetup)) {
384
+ const { output } = entry;
385
+ if (ts.isJsxElement(output) || ts.isJsxSelfClosingElement(output))
386
+ yield { ...entry, output };
168
387
  }
169
388
  }
170
- function returnedJsx(fn) {
389
+ function singleReturn(fn, allowSetup = false) {
171
390
  if (!(ts.isFunctionDeclaration(fn) || ts.isFunctionExpression(fn) || ts.isArrowFunction(fn)) ||
172
391
  fn.asteriskToken ||
173
392
  fn.modifiers?.some((item) => item.kind === ts.SyntaxKind.AsyncKeyword))
174
393
  return;
175
- let value;
176
394
  if (fn.body && ts.isBlock(fn.body)) {
177
- const [statement, extra] = fn.body.statements;
178
- if (!statement || extra || !ts.isReturnStatement(statement))
395
+ const statements = fn.body.statements;
396
+ const last = statements.at(-1);
397
+ if (!last || !ts.isReturnStatement(last) || !last.expression)
398
+ return;
399
+ if (statements.length === 1)
400
+ return last.expression;
401
+ // The codemod moves this setup and its terminal JSX into one template body.
402
+ if (!allowSetup ||
403
+ (ts.getCombinedModifierFlags(fn) & ts.ModifierFlags.Ambient) !== 0 ||
404
+ (ts.isVariableDeclaration(fn.parent) &&
405
+ (ts.getCombinedModifierFlags(fn.parent) & ts.ModifierFlags.Ambient) !== 0) ||
406
+ (!ts.isFunctionDeclaration(fn) &&
407
+ !ts.isVariableDeclaration(fn.parent) &&
408
+ !ts.isExportAssignment(fn.parent)) ||
409
+ !statements
410
+ .slice(0, -1)
411
+ .every((statement) => (typeof allowSetup === 'function' && allowSetup(statement)) ||
412
+ (ts.isVariableStatement(statement) &&
413
+ !statement.modifiers?.some((item) => item.kind === ts.SyntaxKind.DeclareKeyword) &&
414
+ (statement.declarationList.flags & ts.NodeFlags.BlockScoped) === ts.NodeFlags.Const &&
415
+ statement.declarationList.declarations.every((decl) => decl.initializer !== undefined))))
179
416
  return;
180
- value = statement.expression;
417
+ if (typeof allowSetup === 'function')
418
+ return last.expression;
419
+ const output = skipParens(last.expression);
420
+ if (ts.isJsxElement(output) || ts.isJsxSelfClosingElement(output))
421
+ return output;
422
+ return;
181
423
  }
182
- else
183
- value = fn.body;
184
- const output = value && skipWrappers(value);
185
- if (output && (ts.isJsxElement(output) || ts.isJsxSelfClosingElement(output)))
186
- return output;
424
+ return fn.body;
425
+ }
426
+ function conditionalFallback(statement, checker) {
427
+ if (!ts.isIfStatement(statement) || statement.elseStatement)
428
+ return false;
429
+ const test = skipWrappers(statement.expression);
430
+ const negated = ts.isPrefixUnaryExpression(test) && test.operator === ts.SyntaxKind.ExclamationToken;
431
+ const identifier = negated ? skipWrappers(test.operand) : test;
432
+ if (!ts.isIdentifier(identifier))
433
+ return false;
434
+ const declaration = checker.getSymbolAtLocation(identifier)?.valueDeclaration;
435
+ if (declaration &&
436
+ ts.isVariableDeclaration(declaration) &&
437
+ ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const &&
438
+ declaration.initializer) {
439
+ const value = literalCondition(declaration.initializer);
440
+ if (value !== undefined && negated !== (value === 'truthy'))
441
+ return false;
442
+ }
443
+ const branch = statement.thenStatement;
444
+ return (ts.isReturnStatement(branch) ||
445
+ (ts.isBlock(branch) &&
446
+ branch.statements.length === 1 &&
447
+ ts.isReturnStatement(branch.statements[0])));
187
448
  }
188
449
  function openingTag(element) {
189
450
  return ts.isJsxElement(element) ? element.openingElement : element;
@@ -197,7 +458,15 @@ function hostedLeaf(output) {
197
458
  return;
198
459
  const name = attr.name.text;
199
460
  if (seen.has(name) ||
200
- !['component', 'props', 'key', 'hostClassName', 'hostStyle'].includes(name))
461
+ ![
462
+ 'component',
463
+ 'props',
464
+ 'key',
465
+ 'hostClassName',
466
+ 'hostStyle',
467
+ 'hostRole',
468
+ 'hostAriaLabel',
469
+ ].includes(name))
201
470
  return;
202
471
  seen.add(name);
203
472
  if (name === 'component') {
@@ -223,29 +492,119 @@ function ordinaryReactJsx(source) {
223
492
  [...source.matchAll(/@jsxRuntime\s+(\S+)/gi)].some(([, mode]) => mode !== 'automatic') ||
224
493
  [...source.matchAll(/@jsxImportSource\s+(\S+)/gi)].some(([, name]) => name !== 'react'));
225
494
  }
226
- /** Runtime imports that an explicit server host returns directly. */
227
- export function hostedServerComponents(file, source) {
495
+ /** Runtime imports that an explicit React host returns directly. */
496
+ export function hostedComponents(file, source, bridge, selected = false) {
228
497
  if (!ordinaryReactJsx(source))
229
498
  return [];
230
499
  const bound = bind(file, source);
231
500
  const { sf, checker } = bound;
232
501
  const edges = [];
233
- for (const { output } of directExportReturns(bound)) {
234
- const tag = openingTag(output).tagName;
235
- if (ts.isIdentifier(tag) && (/^[a-z]/.test(tag.text) || tag.text.includes('-')))
236
- continue;
502
+ function visit(output) {
503
+ if (selected && ts.isJsxFragment(output)) {
504
+ output.children.forEach(visit);
505
+ return;
506
+ }
507
+ if (!ts.isJsxElement(output) && !ts.isJsxSelfClosingElement(output))
508
+ return;
509
+ const opening = openingTag(output);
510
+ const tag = opening.tagName;
511
+ if (ts.isIdentifier(tag) && (/^[a-z]/.test(tag.text) || tag.text.includes('-'))) {
512
+ // Intrinsic children reach the returned output; custom slots can capture JSX.
513
+ if (selected && ts.isJsxElement(output) && rendersElementChildren(opening))
514
+ output.children.forEach(visit);
515
+ return;
516
+ }
237
517
  const host = imported(checker, tag);
238
- if (host?.module !== 'octane/react/server' ||
518
+ if (host?.module !== bridge ||
239
519
  (host.name !== 'OctaneCompat' && host.name !== 'OctaneCompatInline'))
240
- continue;
520
+ return;
241
521
  const ref = hostedLeaf(output);
242
522
  const leaf = ref && imported(checker, ref);
243
523
  if (leaf)
244
524
  edges.push({ ...leaf, line: sf.getLineAndCharacterOfPosition(output.getStart(sf)).line + 1 });
245
525
  }
526
+ const allowSetup = selected && ((statement) => conditionalFallback(statement, checker));
527
+ for (const { output } of exportReturns(bound, allowSetup))
528
+ visit(output);
246
529
  return edges;
247
530
  }
248
- /** A retained component that returns JSX for a directly imported component. */
531
+ function literalImport(expr) {
532
+ const call = skipWrappers(expr);
533
+ if (!ts.isCallExpression(call) || call.expression.kind !== ts.SyntaxKind.ImportKeyword)
534
+ return;
535
+ const [specifier, extra] = call.arguments;
536
+ if (specifier &&
537
+ !extra &&
538
+ ts.isStringLiteralLike(specifier) &&
539
+ /^\.{1,2}\//.test(specifier.text) &&
540
+ !/[!%?#\\]/.test(specifier.text))
541
+ return specifier.text;
542
+ }
543
+ function lazyComponentImport(checker, tag) {
544
+ if (!ts.isIdentifier(tag))
545
+ return;
546
+ const symbol = checker.getSymbolAtLocation(tag);
547
+ const decl = symbol?.valueDeclaration;
548
+ if (symbol?.declarations?.length !== 1 ||
549
+ !decl ||
550
+ !ts.isVariableDeclaration(decl) ||
551
+ ts.getCombinedModifierFlags(decl) & ts.ModifierFlags.Ambient ||
552
+ !decl.initializer ||
553
+ !ts.isVariableDeclarationList(decl.parent) ||
554
+ (decl.parent.flags & ts.NodeFlags.BlockScoped) !== ts.NodeFlags.Const ||
555
+ !ts.isVariableStatement(decl.parent.parent) ||
556
+ !ts.isSourceFile(decl.parent.parent.parent))
557
+ return;
558
+ const call = skipWrappers(decl.initializer);
559
+ if (!ts.isCallExpression(call) || ts.isOptionalChain(call) || call.arguments.length !== 1)
560
+ return;
561
+ const callee = skipWrappers(call.expression);
562
+ if (ts.isOptionalChain(callee))
563
+ return;
564
+ const factory = imported(checker, callee);
565
+ if (factory?.module !== 'react' || factory.name !== 'lazy')
566
+ return;
567
+ const loader = skipWrappers(call.arguments[0]);
568
+ if (!ts.isArrowFunction(loader) || loader.parameters.length)
569
+ return;
570
+ const result = singleReturn(loader);
571
+ if (!result)
572
+ return;
573
+ const direct = literalImport(result);
574
+ if (direct)
575
+ return { module: direct, name: 'default', lazy: true };
576
+ const map = skipWrappers(result);
577
+ if (!ts.isCallExpression(map) ||
578
+ ts.isOptionalChain(map) ||
579
+ map.arguments.length !== 1 ||
580
+ !ts.isPropertyAccessExpression(map.expression) ||
581
+ map.expression.name.text !== 'then')
582
+ return;
583
+ const module = literalImport(map.expression.expression);
584
+ if (!module)
585
+ return;
586
+ const mapper = skipWrappers(map.arguments[0]);
587
+ if (!ts.isArrowFunction(mapper) || mapper.parameters.length !== 1)
588
+ return;
589
+ const parameter = mapper.parameters[0];
590
+ if (!ts.isIdentifier(parameter.name) || parameter.initializer || parameter.dotDotDotToken)
591
+ return;
592
+ const mapped = singleReturn(mapper);
593
+ const object = mapped && skipWrappers(mapped);
594
+ if (!object || !ts.isObjectLiteralExpression(object) || object.properties.length !== 1)
595
+ return;
596
+ const field = object.properties[0];
597
+ if (!ts.isPropertyAssignment(field) ||
598
+ !ts.isIdentifier(field.name) ||
599
+ field.name.text !== 'default')
600
+ return;
601
+ const value = skipWrappers(field.initializer);
602
+ if (ts.isPropertyAccessExpression(value) &&
603
+ !ts.isOptionalChain(value) &&
604
+ checker.getSymbolAtLocation(value.expression) === checker.getSymbolAtLocation(parameter.name))
605
+ return { module, name: value.name.text, lazy: true };
606
+ }
607
+ /** Imports rendered directly by a retained component. */
249
608
  export function retainedReactComponentReturns(file, source) {
250
609
  if (!ordinaryReactJsx(source))
251
610
  return [];
@@ -253,18 +612,72 @@ export function retainedReactComponentReturns(file, source) {
253
612
  const { sf, checker } = bound;
254
613
  const edges = [];
255
614
  const seen = new Set();
256
- for (const { output, localName } of directExportReturns(bound)) {
615
+ const mayBeLazy = source.includes('import') && (source.includes('lazy') || source.includes('\\'));
616
+ for (const { output, localName, decl } of directExportReturns(bound)) {
257
617
  if (seen.has(output))
258
618
  continue;
259
619
  const tag = openingTag(output).tagName;
260
620
  if (localName && !/^[A-Z]/.test(localName))
261
621
  continue;
622
+ seen.add(output);
623
+ if (ts.isIdentifier(tag) && /^[a-z]/.test(tag.text)) {
624
+ if (!ts.isJsxElement(output) ||
625
+ (ts.getCombinedModifierFlags(decl) & ts.ModifierFlags.Ambient) !== 0 ||
626
+ !rendersElementChildren(output.openingElement) ||
627
+ output.openingElement.attributes.properties.some(ts.isJsxSpreadAttribute))
628
+ continue;
629
+ for (const child of output.children) {
630
+ if (!ts.isJsxExpression(child) || !child.expression || child.dotDotDotToken)
631
+ continue;
632
+ const call = skipWrappers(child.expression);
633
+ if (!ts.isCallExpression(call) || ts.isOptionalChain(call) || call.arguments.length)
634
+ continue;
635
+ const callee = skipWrappers(call.expression);
636
+ const leaf = ts.isIdentifier(callee) && imported(checker, callee);
637
+ if (leaf && /^\.{1,2}\/[^!%?#\\]*\.tsx$/.test(leaf.module))
638
+ edges.push({
639
+ ...leaf,
640
+ factory: true,
641
+ line: sf.getLineAndCharacterOfPosition(call.getStart(sf)).line + 1,
642
+ });
643
+ }
644
+ continue;
645
+ }
262
646
  if (ts.isIdentifier(tag) && !/^[A-Z]/.test(tag.text))
263
647
  continue;
264
- const leaf = imported(checker, tag);
265
- if (leaf?.module.startsWith('.') && /\.[jt]sx$/.test(leaf.module)) {
266
- seen.add(output);
648
+ const leaf = imported(checker, tag) ?? (mayBeLazy ? lazyComponentImport(checker, tag) : undefined);
649
+ if (leaf?.module.startsWith('.'))
267
650
  edges.push({ ...leaf, line: sf.getLineAndCharacterOfPosition(output.getStart(sf)).line + 1 });
651
+ }
652
+ return edges;
653
+ }
654
+ /** Named React factories returned by an otherwise retained function. */
655
+ export function retainedReactElementReturns(file, source) {
656
+ const bound = bind(file, source);
657
+ const { sf, checker } = bound;
658
+ const edges = [];
659
+ const seen = new Set();
660
+ for (const { output } of exportReturns(bound)) {
661
+ if (seen.has(output) ||
662
+ !ts.isCallExpression(output) ||
663
+ ts.isOptionalChain(output) ||
664
+ !ts.isIdentifier(output.expression) ||
665
+ !output.arguments.length ||
666
+ output.arguments.some(ts.isSpreadElement))
667
+ continue;
668
+ const factory = imported(checker, output.expression);
669
+ if (factory?.module !== 'react' || factory.name !== 'createElement')
670
+ continue;
671
+ const component = skipWrappers(output.arguments[0]);
672
+ if (!ts.isIdentifier(component))
673
+ continue;
674
+ const leaf = imported(checker, component);
675
+ if (leaf?.module.startsWith('.')) {
676
+ seen.add(output);
677
+ edges.push({
678
+ ...leaf,
679
+ line: sf.getLineAndCharacterOfPosition(output.getStart(sf)).line + 1,
680
+ });
268
681
  }
269
682
  }
270
683
  return edges;
@@ -273,6 +686,7 @@ export function retainedReactComponentReturns(file, source) {
273
686
  export function octaneRootComponents(file, source) {
274
687
  const { sf, checker } = bind(file, source);
275
688
  const edges = [];
689
+ let uses;
276
690
  function clientComponent(call, callee, hydrate) {
277
691
  if (hydrate && call.arguments.length <= 4)
278
692
  return call.arguments[1];
@@ -281,16 +695,42 @@ export function octaneRootComponents(file, source) {
281
695
  callee.name.text !== 'render' ||
282
696
  call.arguments.length > 2)
283
697
  return;
284
- const root = skipWrappers(callee.expression);
285
- if (ts.isCallExpression(root) &&
286
- !ts.isOptionalChain(root) &&
287
- root.arguments.length >= 1 &&
288
- root.arguments.length <= 2 &&
289
- !root.arguments.some(ts.isSpreadElement)) {
290
- const factory = imported(checker, skipWrappers(root.expression));
291
- if (factory?.module === 'octane' && factory.name === 'createRoot')
292
- return call.arguments[0];
698
+ const receiver = skipWrappers(callee.expression);
699
+ let root = receiver;
700
+ let handle;
701
+ if (ts.isIdentifier(receiver)) {
702
+ const declaration = checker.getSymbolAtLocation(receiver)?.valueDeclaration;
703
+ if (!declaration ||
704
+ !ts.isVariableDeclaration(declaration) ||
705
+ !ts.isIdentifier(declaration.name) ||
706
+ !declaration.initializer ||
707
+ !(declaration.parent.flags & ts.NodeFlags.Const) ||
708
+ ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Export ||
709
+ (!atInitializedModuleHandle(declaration, call) &&
710
+ !initializedBefore(checker, receiver, call)))
711
+ return;
712
+ handle = declaration.name;
713
+ root = skipWrappers(declaration.initializer);
714
+ }
715
+ if (!ts.isCallExpression(root) ||
716
+ ts.isOptionalChain(root) ||
717
+ root.arguments.length < 1 ||
718
+ root.arguments.length > 2 ||
719
+ root.arguments.some(ts.isSpreadElement))
720
+ return;
721
+ const factory = imported(checker, skipWrappers(root.expression));
722
+ if (factory?.module !== 'octane' || factory.name !== 'createRoot')
723
+ return;
724
+ if (handle) {
725
+ if ((source.includes('eval') || source.includes('\\u')) && hasEval(sf))
726
+ return;
727
+ const rootScope = (node) => ts.isFunctionLike(node) || ts.isClassLike(node);
728
+ const owner = ts.findAncestor(handle, rootScope);
729
+ const refs = (uses ??= localUses(sf, checker))(handle);
730
+ if (rootHandleEscapes(refs, (ref) => ts.findAncestor(ref, rootScope) === owner))
731
+ return;
293
732
  }
733
+ return call.arguments[0];
294
734
  }
295
735
  function visit(node) {
296
736
  if (ts.isCallExpression(node) &&
@@ -318,7 +758,7 @@ export function octaneRootComponents(file, source) {
318
758
  return edges;
319
759
  }
320
760
  /** React server calls that render directly imported components. */
321
- export function reactServerComponents(file, source, original, topLevel = false) {
761
+ export function reactServerComponents(file, source, original, selected = false) {
322
762
  const { sf, checker } = bind(file, source);
323
763
  const edges = [];
324
764
  function visit(node) {
@@ -335,7 +775,13 @@ export function reactServerComponents(file, source, original, topLevel = false)
335
775
  : undefined;
336
776
  if (jsx &&
337
777
  (!ts.isIdentifier(jsx.tagName) || /^[A-Z][\w$]*$/.test(jsx.tagName.text)) &&
338
- jsx.attributes.properties.length === 0 &&
778
+ (jsx.attributes.properties.length === 0 ||
779
+ (selected &&
780
+ ts.isJsxSelfClosingElement(jsx) &&
781
+ staticReactProps(jsx) !== null &&
782
+ !jsx.attributes.properties.some((attr) => ts.isJsxAttribute(attr) &&
783
+ ts.isIdentifier(attr.name) &&
784
+ attr.name.text === 'children'))) &&
339
785
  ordinaryReactJsx(source) &&
340
786
  original('react/jsx-runtime'))
341
787
  ref = jsx.tagName;
@@ -343,52 +789,150 @@ export function reactServerComponents(file, source, original, topLevel = false)
343
789
  !ts.isOptionalChain(value) &&
344
790
  (value.arguments.length === 1 ||
345
791
  (value.arguments.length === 2 &&
346
- skipWrappers(value.arguments[1]).kind === ts.SyntaxKind.NullKeyword))) {
792
+ (selected || skipWrappers(value.arguments[1]).kind === ts.SyntaxKind.NullKeyword)))) {
347
793
  const factory = imported(checker, value.expression);
348
794
  if (factory?.module === 'react' && factory.name === 'createElement' && original('react'))
349
795
  ref = skipWrappers(value.arguments[0]);
350
796
  }
351
797
  const leaf = ref && imported(checker, ref);
352
- if (leaf?.module.startsWith('.') && /\.[jt]sx$/.test(leaf.module))
798
+ if (leaf?.module.startsWith('.') && (!selected || /\.[jt]sx$/.test(leaf.module)))
353
799
  edges.push({
354
800
  ...leaf,
355
801
  line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1,
356
802
  });
357
803
  }
358
804
  }
359
- ts.forEachChild(node, visit);
805
+ if (!selected)
806
+ ts.forEachChild(node, visit);
360
807
  }
361
- if (topLevel) {
808
+ if (selected) {
809
+ function visitDirectRoot(expression) {
810
+ const call = expression && skipParens(expression);
811
+ if (!call || !ts.isCallExpression(call))
812
+ return;
813
+ const argument = call.arguments[0] && skipParens(call.arguments[0]);
814
+ if (!argument)
815
+ return;
816
+ if (ts.isJsxSelfClosingElement(argument) && ts.isIdentifier(argument.tagName)) {
817
+ visit(call);
818
+ return;
819
+ }
820
+ const target = ts.isJsxSelfClosingElement(argument)
821
+ ? argument.tagName
822
+ : ts.isCallExpression(argument) && argument.arguments[0];
823
+ if (target &&
824
+ (ts.isIdentifier(target) || ts.isPropertyAccessExpression(target)) &&
825
+ /^[A-Z]/.test(target.getText(sf).split('.').pop() ?? ''))
826
+ visit(call);
827
+ }
828
+ function visitEntryStatement(statement) {
829
+ if (ts.isVariableStatement(statement)) {
830
+ for (const declaration of statement.declarationList.declarations)
831
+ visitDirectRoot(declaration.initializer);
832
+ }
833
+ else if (ts.isExpressionStatement(statement) ||
834
+ (ts.isExportAssignment(statement) && !statement.isExportEquals)) {
835
+ visitDirectRoot(statement.expression);
836
+ }
837
+ }
362
838
  for (const statement of sf.statements) {
363
- if (!ts.isVariableStatement(statement))
364
- continue;
365
- for (const declaration of statement.declarationList.declarations) {
366
- const call = declaration.initializer;
367
- if (!call || !ts.isCallExpression(call))
368
- continue;
369
- const [argument] = call.arguments;
370
- if (argument && ts.isJsxSelfClosingElement(argument) && ts.isIdentifier(argument.tagName))
371
- visit(call);
839
+ if (ts.isIfStatement(statement)) {
840
+ const condition = skipParens(statement.expression);
841
+ if (ts.isPropertyAccessExpression(condition) &&
842
+ !ts.isOptionalChain(condition) &&
843
+ condition.name.text === 'main' &&
844
+ ts.isMetaProperty(condition.expression) &&
845
+ condition.expression.keywordToken === ts.SyntaxKind.ImportKeyword &&
846
+ condition.expression.name.text === 'meta') {
847
+ const body = statement.thenStatement;
848
+ if (ts.isBlock(body))
849
+ body.statements.forEach(visitEntryStatement);
850
+ else
851
+ visitEntryStatement(body);
852
+ }
853
+ }
854
+ else if (ts.isFunctionDeclaration(statement) &&
855
+ statement.body &&
856
+ !statement.asteriskToken &&
857
+ !statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)) {
858
+ for (const bodyStatement of statement.body.statements)
859
+ if (ts.isReturnStatement(bodyStatement))
860
+ visitDirectRoot(bodyStatement.expression);
372
861
  }
862
+ else
863
+ visitEntryStatement(statement);
373
864
  }
374
865
  }
375
866
  else
376
867
  visit(sf);
377
868
  return edges;
378
869
  }
379
- /** Local exports whose original body returns an intrinsic React element. */
380
- export function intrinsicReactExports(file, source) {
381
- const names = new Set();
870
+ /** Local exports whose original body returns React JSX directly. */
871
+ export function directReactExports(file, source) {
872
+ const intrinsics = new Set();
873
+ const wrappers = new Set();
874
+ let splitIntrinsicDefault = false;
875
+ let mayExportThen = false;
382
876
  if (ordinaryReactJsx(source)) {
383
- for (const { name, output, localName } of directExportReturns(bind(file, source))) {
877
+ const bound = bind(file, source);
878
+ const { sf, checker } = bound;
879
+ const module = checker.getSymbolAtLocation(sf);
880
+ const then = module && checker.getExportsOfModule(module).find((symbol) => symbol.name === 'then');
881
+ // import() assimilates a callable namespace then. This local checker cannot resolve wildcard re-exports.
882
+ mayExportThen =
883
+ !!then &&
884
+ (!!(then.flags & ts.SymbolFlags.Value) ||
885
+ !!then.declarations?.some((decl) => (ts.isExportSpecifier(decl) && !decl.isTypeOnly && !decl.parent.parent.isTypeOnly) ||
886
+ (ts.isImportEqualsDeclaration(decl) && !decl.isTypeOnly)));
887
+ mayExportThen ||= sf.statements.some((stmt) => ts.isExportDeclaration(stmt) && !stmt.isTypeOnly && !stmt.exportClause);
888
+ for (const { name, output, localName, decl, splitExport } of directExportReturns(bound, true)) {
384
889
  const tag = openingTag(output).tagName;
385
890
  if (ts.isIdentifier(tag) &&
386
891
  /^[a-z]/.test(tag.text) &&
387
- (!localName || /^[A-Z]/.test(localName)))
892
+ (!localName || /^[A-Z]/.test(localName))) {
893
+ if (!splitExport)
894
+ intrinsics.add(name);
895
+ else if (name === 'default')
896
+ splitIntrinsicDefault = true;
897
+ }
898
+ else if (ts.isFunctionDeclaration(decl) &&
899
+ (name === 'default'
900
+ ? !localName || /^[A-Z]/.test(localName)
901
+ : localName === name && /^[A-Z]/.test(name)) &&
902
+ ts.isIdentifier(tag) &&
903
+ /^[A-Z]/.test(tag.text))
904
+ wrappers.add(name);
905
+ }
906
+ }
907
+ return { intrinsics, wrappers, splitIntrinsicDefault, mayExportThen };
908
+ }
909
+ /** Factories whose intrinsic JSX return survives as Octane JSX in the emitted file. */
910
+ export function migratedJsxFactories(file, source, emitted) {
911
+ if (!ordinaryReactJsx(source))
912
+ return new Set();
913
+ function factories(code) {
914
+ const names = new Set();
915
+ for (const { name, output, decl, symbol } of directExportReturns(bind(file, code))) {
916
+ const tag = openingTag(output).tagName;
917
+ if (ts.isFunctionDeclaration(decl) &&
918
+ symbol.declarations?.length === 1 &&
919
+ decl.name?.text === name &&
920
+ /^[a-z]/.test(name) &&
921
+ decl.parameters.length === 0 &&
922
+ (ts.getCombinedModifierFlags(decl) &
923
+ (ts.ModifierFlags.Export | ts.ModifierFlags.Ambient)) ===
924
+ ts.ModifierFlags.Export &&
925
+ ts.isIdentifier(tag) &&
926
+ /^[a-z]/.test(tag.text))
388
927
  names.add(name);
389
928
  }
929
+ return names;
390
930
  }
391
- return names;
931
+ const original = factories(source);
932
+ // TSX parsing proves the emitted return directly. Volar can hoist it out of the function.
933
+ if (!original.size || parseSync(file, emitted).errors.length)
934
+ return new Set();
935
+ return original.intersection(factories(emitted));
392
936
  }
393
937
  /** Inspect the emitted local export before assigning a reverse island to a server host. */
394
938
  export async function reverseIslandExports(file, source, original) {
@@ -417,6 +961,12 @@ export function executableImports(file, source, verbatim) {
417
961
  imports.push(node.moduleSpecifier.text);
418
962
  return;
419
963
  }
964
+ if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly) {
965
+ const reference = node.moduleReference;
966
+ if (ts.isExternalModuleReference(reference) && ts.isStringLiteral(reference.expression)) {
967
+ imports.push(reference.expression.text);
968
+ }
969
+ }
420
970
  if (ts.isCallExpression(node) &&
421
971
  node.expression.kind === ts.SyntaxKind.ImportKeyword &&
422
972
  node.arguments[0] &&