@octanejs/codemod 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3311 @@
1
+ import ts from 'typescript';
2
+ import {
3
+ DEPENDENCY_HOOKS,
4
+ RADIX_TYPES,
5
+ REACT_MODULES,
6
+ TEXT_INPUT_TYPES,
7
+ UNSUPPORTED_VALUES,
8
+ mapPackageExport,
9
+ mapQualifiedType,
10
+ mapReactImport,
11
+ missingExport,
12
+ radixNamespace,
13
+ } from './mappings.js';
14
+
15
+ /**
16
+ * @typedef {'info' | 'warning' | 'error'} Severity
17
+ * @typedef {{ rule: string, severity: Severity, line: number, message: string }} Note
18
+ *
19
+ * @typedef {Object} TransformOptions
20
+ * @property {'tsrx' | 'tsx'} [target] `tsrx` (default) rewrites component
21
+ * bodies as templates; `tsx` keeps JSX and only ports the React APIs.
22
+ * @property {boolean} [strong] emit Strong-mode source: add `"use strong"` and
23
+ * leave omitted dependency lists to the compiler.
24
+ * @property {boolean} [strictNullChecks] the project checks with
25
+ * `strictNullChecks`, so a TypeScript module's own types may prove a child
26
+ * hole is text
27
+ * @property {{ sourceFile: ts.SourceFile, checker: ts.TypeChecker }} [types]
28
+ * this module in a program over the whole project, whose resolved imports
29
+ * type what the module's own program cannot
30
+ * @property {(specifier: string) => string | null} [resolveSpecifier] the new
31
+ * spelling of an import specifier (a renamed module, a binding package), or
32
+ * null to keep it.
33
+ * @property {(specifier: string, name: string) => boolean | null} [isContext]
34
+ * whether an imported name is a context, or null when it cannot be known
35
+ * @property {(specifier: string) => string | null} [unported] the React package
36
+ * an import specifier names when that package has no Octane port, or null
37
+ * @property {boolean} [reactCompat] the project has React and React DOM 19.2 or
38
+ * newer in the React 19 series, so `ReactCompat` can host an unported
39
+ * package's components
40
+ *
41
+ * @typedef {Object} Unported A React package with no Octane port, as this
42
+ * module uses it
43
+ * @property {string} name
44
+ * @property {number} islands elements now rendered in a `ReactCompat` island
45
+ * @property {number} blocked uses that only a port can support
46
+ *
47
+ * @typedef {Object} TransformResult
48
+ * @property {string} code
49
+ * @property {boolean} changed
50
+ * @property {boolean} template whether the module becomes `.tsrx`: it holds a
51
+ * template, keeps JSX, or was a JSX module, so no `.tsx` module is left
52
+ * outside Strong mode's reach
53
+ * @property {Note[]} notes
54
+ * @property {Record<string, number>} rules how often each rule fired
55
+ * @property {ModuleExports} exports what the module exports that other modules'
56
+ * rewrites depend on
57
+ * @property {Unported[]} unported
58
+ *
59
+ * @typedef {Object} ModuleExports
60
+ * @property {string[]} contexts exported names whose value is a context this
61
+ * module creates
62
+ * @property {{ specifier: string, names: [string, string][] | null }[]} reexports
63
+ * `export … from` declarations: [imported, exported] pairs, or null for `*`
64
+ */
65
+
66
+ /**
67
+ * @typedef {{ template: boolean }} Context
68
+ * @typedef {{ module: string, local: string, imported: string, namespace: boolean, typeOnly: boolean, port: Unported | null }} Import
69
+ */
70
+
71
+ /** Marks emitted text whose whole line should go. */
72
+ const DROP = '\u0000DROP\u0000';
73
+ /**
74
+ * Stands in for a newline inside a string or template literal while arms are
75
+ * re-indented, so moving a literal never changes its value.
76
+ */
77
+ const LITERAL_NEWLINE = '\u0000NL\u0000';
78
+
79
+ const TEMPLATE = { template: true };
80
+ const PLAIN = { template: false };
81
+
82
+ /** Rule names, as reported. */
83
+ const RULE = {
84
+ binding: 'bindings',
85
+ classComponent: 'class-component',
86
+ consumer: 'context-consumer',
87
+ defaultProps: 'default-props',
88
+ descriptorChildren: 'descriptor-children',
89
+ deps: 'hook-dependencies',
90
+ eventObject: 'event-object',
91
+ forwardRef: 'forward-ref',
92
+ import: 'imports',
93
+ legacyRoot: 'legacy-root',
94
+ rootRender: 'root-render',
95
+ serverRender: 'server-render',
96
+ flushSync: 'flush-sync',
97
+ renderProp: 'render-prop-children',
98
+ documentShell: 'document-shell',
99
+ nativeChange: 'native-text-change',
100
+ className: 'class-attribute',
101
+ provider: 'context-provider',
102
+ strictMode: 'strict-mode',
103
+ component: 'template-component',
104
+ if: 'template-if',
105
+ for: 'template-for',
106
+ text: 'template-text',
107
+ try: 'template-try',
108
+ unsupported: 'unsupported-api',
109
+ strong: 'strong',
110
+ bindings: 'bindings',
111
+ reactCompat: 'react-compat',
112
+ };
113
+
114
+ /**
115
+ * Rewrite one React module as Octane.
116
+ *
117
+ * @param {string} source
118
+ * @param {string} filename
119
+ * @param {TransformOptions} [options]
120
+ * @returns {TransformResult}
121
+ */
122
+ export function transformModule(source, filename, options = {}) {
123
+ return new ModuleTransform(source, filename, options).run();
124
+ }
125
+
126
+ /**
127
+ * Parse and bind one module on its own, with only the ES5 library and no
128
+ * module resolution. Binding is enough to map every name to the declaration it
129
+ * refers to, so a shadowed `useState` or event parameter is never mistaken for
130
+ * another; the library gives the module's own types their array and string
131
+ * members.
132
+ *
133
+ * @param {string} filename
134
+ * @param {string} source
135
+ */
136
+ function bind(filename, source) {
137
+ const lib = esLib();
138
+ const sf = ts.createSourceFile(
139
+ filename,
140
+ source,
141
+ ts.ScriptTarget.Latest,
142
+ true,
143
+ scriptKind(filename),
144
+ );
145
+ /** @type {ts.CompilerHost} */
146
+ const host = {
147
+ getSourceFile: (name) => (name === filename ? sf : name === lib.fileName ? lib : undefined),
148
+ getDefaultLibFileName: () => lib.fileName,
149
+ writeFile: () => {},
150
+ getCurrentDirectory: () => '',
151
+ getCanonicalFileName: (name) => name,
152
+ useCaseSensitiveFileNames: () => true,
153
+ getNewLine: () => '\n',
154
+ fileExists: (name) => name === filename || name === lib.fileName,
155
+ readFile: () => undefined,
156
+ };
157
+ const program = ts.createProgram({
158
+ rootNames: [filename, lib.fileName],
159
+ options: {
160
+ noLib: true,
161
+ noResolve: true,
162
+ allowJs: true,
163
+ jsx: ts.JsxEmit.Preserve,
164
+ types: [],
165
+ // As the compiler's typed-text proof requires: a `string` excludes
166
+ // null, and an indexed read may be missing.
167
+ strictNullChecks: true,
168
+ noUncheckedIndexedAccess: true,
169
+ },
170
+ host,
171
+ });
172
+ return { sf, checker: program.getTypeChecker() };
173
+ }
174
+
175
+ /** @type {ts.SourceFile | undefined} */
176
+ let es5;
177
+
178
+ /**
179
+ * The ES5 library, parsed once and shared by every module's program, so
180
+ * array and string members have types.
181
+ */
182
+ function esLib() {
183
+ const file = ts.getDefaultLibFilePath({}).replace(/[^/\\]+$/, 'lib.es5.d.ts');
184
+ es5 ??= ts.createSourceFile(
185
+ 'lib.es5.d.ts',
186
+ /** @type {string} */ (ts.sys.readFile(file)),
187
+ ts.ScriptTarget.Latest,
188
+ true,
189
+ );
190
+ return es5;
191
+ }
192
+
193
+ /** @param {string} filename */
194
+ function scriptKind(filename) {
195
+ if (filename.endsWith('.tsx')) return ts.ScriptKind.TSX;
196
+ if (filename.endsWith('.jsx')) return ts.ScriptKind.JSX;
197
+ if (/\.[cm]?ts$/.test(filename)) return ts.ScriptKind.TS;
198
+ // Plain .js files often hold JSX in React projects.
199
+ return ts.ScriptKind.JSX;
200
+ }
201
+
202
+ /**
203
+ * @param {ts.Expression} node
204
+ * @returns {ts.Expression}
205
+ */
206
+ function skipParens(node) {
207
+ while (ts.isParenthesizedExpression(node)) node = node.expression;
208
+ return node;
209
+ }
210
+
211
+ /** @param {ts.Node} node */
212
+ function isJsx(node) {
213
+ return ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node);
214
+ }
215
+
216
+ /**
217
+ * What a module's import of a package with no Octane port leaves to do.
218
+ *
219
+ * @param {Unported} port
220
+ */
221
+ function portComment({ name, islands, blocked }) {
222
+ const missing = `No Octane port of \`${name}\` exists`;
223
+ if (blocked > 0) {
224
+ return `${missing}, and this module needs one: Octane cannot call its hooks, read its contexts, or pass Octane content to its components.`;
225
+ }
226
+ return islands > 0
227
+ ? `${missing}, so its components render in React through ReactCompat.`
228
+ : `${missing}; React stays a dependency for it.`;
229
+ }
230
+
231
+ /**
232
+ * Whether a hole is already spelled as text, or as a literal the cast would
233
+ * only clutter.
234
+ *
235
+ * @param {ts.Expression} node
236
+ */
237
+ function isTextSpelling(node) {
238
+ node = skipParens(node);
239
+ return (
240
+ ts.isNumericLiteral(node) ||
241
+ ts.isBigIntLiteral(node) ||
242
+ ts.isAsExpression(node) ||
243
+ isStringSpelling(node)
244
+ );
245
+ }
246
+
247
+ /**
248
+ * Whether the compiler proves `node` a string by its spelling: a string
249
+ * literal, a `String()` call, or a concatenation with one.
250
+ *
251
+ * @param {ts.Expression} node
252
+ * @returns {boolean}
253
+ */
254
+ function isStringSpelling(node) {
255
+ node = skipParens(node);
256
+ if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) return true;
257
+ if (ts.isCallExpression(node)) {
258
+ return ts.isIdentifier(node.expression) && node.expression.text === 'String';
259
+ }
260
+ return (
261
+ ts.isBinaryExpression(node) &&
262
+ node.operatorToken.kind === ts.SyntaxKind.PlusToken &&
263
+ (isStringSpelling(node.left) || isStringSpelling(node.right))
264
+ );
265
+ }
266
+
267
+ /**
268
+ * What a type renders as: 1 when every member is a string, 2 when every
269
+ * member is a string, number, or bigint and one is not a string, else 0. The
270
+ * compiler's typed-text proof applies the same test.
271
+ *
272
+ * @param {ts.Type} type
273
+ * @returns {0 | 1 | 2}
274
+ */
275
+ function textKind(type) {
276
+ const { TypeFlags } = ts;
277
+ const opaque =
278
+ TypeFlags.Any | TypeFlags.Unknown | TypeFlags.Never | TypeFlags.VoidLike | TypeFlags.Null;
279
+ if (type.flags & opaque) return 0;
280
+ if (type.flags & TypeFlags.StringLike) return 1;
281
+ if (type.flags & (TypeFlags.NumberLike | TypeFlags.BigIntLike)) return 2;
282
+ if (!type.isUnion()) return 0;
283
+ /** @type {0 | 1 | 2} */
284
+ let kind = 1;
285
+ for (const member of type.types) {
286
+ const each = textKind(member);
287
+ if (each === 0) return 0;
288
+ if (each === 2) kind = 2;
289
+ }
290
+ return kind;
291
+ }
292
+
293
+ /**
294
+ * The outermost node of `sf` spanning exactly `[start, end)`.
295
+ *
296
+ * @param {ts.SourceFile} sf
297
+ * @param {number} start
298
+ * @param {number} end
299
+ * @returns {ts.Node | null}
300
+ */
301
+ function nodeSpanning(sf, start, end) {
302
+ /** @type {ts.Node} */
303
+ let node = sf;
304
+ for (;;) {
305
+ const child = ts.forEachChild(node, (c) => (c.pos <= start && c.end >= end ? c : undefined));
306
+ if (!child) return null;
307
+ if (child.getStart(sf) === start && child.end === end) return child;
308
+ node = child;
309
+ }
310
+ }
311
+
312
+ /**
313
+ * The attribute an element sets by `name`.
314
+ *
315
+ * @param {ts.JsxOpeningLikeElement} element
316
+ * @param {string} name
317
+ */
318
+ function attributeOf(element, name) {
319
+ return /** @type {ts.JsxAttribute | undefined} */ (
320
+ element.attributes.properties.find(
321
+ (a) => ts.isJsxAttribute(a) && ts.isIdentifier(a.name) && a.name.text === name,
322
+ )
323
+ );
324
+ }
325
+
326
+ /**
327
+ * The elements a list row can render: the row itself, or each arm of a
328
+ * conditional row. Null when an arm renders anything else.
329
+ *
330
+ * @param {ts.Expression} node
331
+ * @returns {(ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment)[] | null}
332
+ */
333
+ function rowElements(node) {
334
+ node = skipParens(node);
335
+ if (isJsx(node))
336
+ return [/** @type {ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment} */ (node)];
337
+ if (isNullish(node)) return [];
338
+ if (!ts.isConditionalExpression(node)) return null;
339
+ const whenTrue = rowElements(node.whenTrue);
340
+ const whenFalse = rowElements(node.whenFalse);
341
+ return whenTrue && whenFalse && [...whenTrue, ...whenFalse];
342
+ }
343
+
344
+ /**
345
+ * The element an `if (c) return <A />;` guard returns, or null for any other
346
+ * statement.
347
+ *
348
+ * @param {ts.Statement} statement
349
+ * @returns {ts.Expression | null}
350
+ */
351
+ function guardReturn(statement) {
352
+ if (!ts.isIfStatement(statement) || statement.elseStatement) return null;
353
+ let then = statement.thenStatement;
354
+ if (ts.isBlock(then)) {
355
+ if (then.statements.length !== 1) return null;
356
+ then = then.statements[0];
357
+ }
358
+ if (!ts.isReturnStatement(then) || !then.expression) return null;
359
+ return isJsx(skipParens(then.expression)) ? then.expression : null;
360
+ }
361
+
362
+ /**
363
+ * Whether any `return` in `statements`, outside nested functions, returns
364
+ * JSX.
365
+ *
366
+ * @param {readonly ts.Statement[]} statements
367
+ */
368
+ function returnsJsx(statements) {
369
+ /** @type {(node: ts.Node) => boolean} */
370
+ const hasJsx = (node) => isJsx(node) || (ts.forEachChild(node, hasJsx) ?? false);
371
+ /** @type {(node: ts.Node) => boolean} */
372
+ const visit = (node) => {
373
+ if (isFunctionLike(node)) return false;
374
+ if (ts.isReturnStatement(node) && node.expression && hasJsx(node.expression)) return true;
375
+ return ts.forEachChild(node, visit) ?? false;
376
+ };
377
+ return statements.some(visit);
378
+ }
379
+
380
+ /** Document tags a router shell renders through `@octanejs/tanstack-router`. */
381
+ const DOCUMENT_TAGS = /** @type {Record<string, string>} */ ({
382
+ html: 'Html',
383
+ head: 'Head',
384
+ body: 'Body',
385
+ });
386
+
387
+ /**
388
+ * Whether an identifier is read in a type, where an import needs no value.
389
+ * A `typeof X` query is a type, which `import type` serves; `extends Base`
390
+ * reads a value, so heritage counts as one.
391
+ *
392
+ * @param {ts.Identifier} node
393
+ */
394
+ function inTypeNode(node) {
395
+ let parent = node.parent;
396
+ while (ts.isQualifiedName(parent)) parent = parent.parent;
397
+ return ts.isTypeNode(parent) && !ts.isExpressionWithTypeArguments(parent);
398
+ }
399
+
400
+ /** @param {ts.Node} node */
401
+ function isNullish(node) {
402
+ return (
403
+ node.kind === ts.SyntaxKind.NullKeyword ||
404
+ node.kind === ts.SyntaxKind.FalseKeyword ||
405
+ (ts.isIdentifier(node) && node.text === 'undefined')
406
+ );
407
+ }
408
+
409
+ /** @param {ts.Node} node */
410
+ function isFunctionLike(node) {
411
+ return (
412
+ ts.isFunctionDeclaration(node) ||
413
+ ts.isFunctionExpression(node) ||
414
+ ts.isArrowFunction(node) ||
415
+ ts.isMethodDeclaration(node) ||
416
+ ts.isGetAccessor(node) ||
417
+ ts.isSetAccessor(node) ||
418
+ ts.isConstructorDeclaration(node)
419
+ );
420
+ }
421
+
422
+ /**
423
+ * Whether evaluating `node` can only produce a boolean, so `node && <X />`
424
+ * renders nothing when it is falsy, exactly as `@if` does. React renders `0`
425
+ * and `NaN` from a numeric left side, so anything unproven stays a hole.
426
+ * `valueOf` gives the initializer a `const` name is bound to, if any.
427
+ *
428
+ * @param {ts.Expression} node
429
+ * @param {(name: ts.Identifier) => ts.Expression | null} valueOf
430
+ * @returns {boolean}
431
+ */
432
+ function isBoolean(node, valueOf) {
433
+ node = skipParens(node);
434
+ if (ts.isIdentifier(node)) {
435
+ const value = valueOf(node);
436
+ return value !== null && isBoolean(value, valueOf);
437
+ }
438
+ if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword) {
439
+ return true;
440
+ }
441
+ if (ts.isPrefixUnaryExpression(node)) {
442
+ return node.operator === ts.SyntaxKind.ExclamationToken;
443
+ }
444
+ if (ts.isBinaryExpression(node)) {
445
+ switch (node.operatorToken.kind) {
446
+ case ts.SyntaxKind.EqualsEqualsEqualsToken:
447
+ case ts.SyntaxKind.ExclamationEqualsEqualsToken:
448
+ case ts.SyntaxKind.EqualsEqualsToken:
449
+ case ts.SyntaxKind.ExclamationEqualsToken:
450
+ case ts.SyntaxKind.LessThanToken:
451
+ case ts.SyntaxKind.LessThanEqualsToken:
452
+ case ts.SyntaxKind.GreaterThanToken:
453
+ case ts.SyntaxKind.GreaterThanEqualsToken:
454
+ case ts.SyntaxKind.InstanceOfKeyword:
455
+ case ts.SyntaxKind.InKeyword:
456
+ return true;
457
+ case ts.SyntaxKind.AmpersandAmpersandToken:
458
+ case ts.SyntaxKind.BarBarToken:
459
+ return isBoolean(node.left, valueOf) && isBoolean(node.right, valueOf);
460
+ }
461
+ return false;
462
+ }
463
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
464
+ return node.expression.text === 'Boolean';
465
+ }
466
+ return false;
467
+ }
468
+
469
+ /**
470
+ * Modules whose exports the codemod knows by name: React's, and Octane's own
471
+ * for code already partly migrated.
472
+ *
473
+ * @param {string} module
474
+ */
475
+ function isApiModule(module) {
476
+ return module in REACT_MODULES || module === 'octane';
477
+ }
478
+
479
+ /**
480
+ * Whether an identifier names a property rather than a binding.
481
+ *
482
+ * @param {ts.Identifier} node
483
+ */
484
+ function isPropertyName(node) {
485
+ const parent = /** @type {ts.Node & { name?: ts.Node }} */ (node.parent);
486
+ if (ts.isPropertyAccessExpression(parent)) return parent.name === node;
487
+ if (ts.isQualifiedName(parent)) return parent.right === node;
488
+ return (
489
+ parent.name === node &&
490
+ (ts.isPropertyAssignment(parent) ||
491
+ ts.isPropertySignature(parent) ||
492
+ ts.isPropertyDeclaration(parent) ||
493
+ ts.isMethodDeclaration(parent) ||
494
+ ts.isMethodSignature(parent) ||
495
+ ts.isJsxAttribute(parent))
496
+ );
497
+ }
498
+
499
+ /**
500
+ * Whether an identifier is the name a declaration introduces.
501
+ *
502
+ * @param {ts.Identifier} node
503
+ */
504
+ function declaresName(node) {
505
+ const parent = /** @type {ts.Node & { name?: ts.Node }} */ (node.parent);
506
+ if (parent.name !== node) return false;
507
+ return (
508
+ ts.isVariableDeclaration(parent) ||
509
+ ts.isFunctionDeclaration(parent) ||
510
+ ts.isFunctionExpression(parent) ||
511
+ ts.isClassDeclaration(parent) ||
512
+ ts.isClassExpression(parent) ||
513
+ ts.isParameter(parent) ||
514
+ ts.isBindingElement(parent) ||
515
+ ts.isImportSpecifier(parent) ||
516
+ ts.isImportClause(parent) ||
517
+ ts.isNamespaceImport(parent) ||
518
+ ts.isTypeAliasDeclaration(parent) ||
519
+ ts.isInterfaceDeclaration(parent) ||
520
+ ts.isEnumDeclaration(parent) ||
521
+ ts.isTypeParameterDeclaration(parent)
522
+ );
523
+ }
524
+
525
+ /**
526
+ * The names a binding pattern introduces.
527
+ *
528
+ * @param {ts.BindingName} name
529
+ * @returns {string[]}
530
+ */
531
+ function bindingNames(name) {
532
+ if (ts.isIdentifier(name)) return [name.text];
533
+ return name.elements.flatMap((element) =>
534
+ ts.isOmittedExpression(element) ? [] : bindingNames(element.name),
535
+ );
536
+ }
537
+
538
+ /**
539
+ * Whether `node` reads a name `test` accepts.
540
+ *
541
+ * @param {ts.Node} node
542
+ * @param {(name: string) => boolean} test
543
+ * @returns {boolean}
544
+ */
545
+ function reads(node, test) {
546
+ if (ts.isIdentifier(node)) return test(node.text);
547
+ return ts.forEachChild(node, (child) => reads(child, test) || undefined) === true;
548
+ }
549
+
550
+ /**
551
+ * Whether a `function` body reads its own `this` or `arguments`.
552
+ *
553
+ * @param {ts.Node} node
554
+ * @returns {boolean}
555
+ */
556
+ function usesOwnThis(node) {
557
+ if (node.kind === ts.SyntaxKind.ThisKeyword) return true;
558
+ if (ts.isIdentifier(node) && node.text === 'arguments') return true;
559
+ if (isFunctionLike(node) && !ts.isArrowFunction(node)) return false;
560
+ return ts.forEachChild(node, (child) => usesOwnThis(child) || undefined) === true;
561
+ }
562
+
563
+ /**
564
+ * The children of an element that are more than layout whitespace.
565
+ *
566
+ * @param {ts.JsxElement | ts.JsxFragment} node
567
+ */
568
+ function contentOf(node) {
569
+ return node.children.filter(
570
+ (child) => !(ts.isJsxText(child) && child.containsOnlyTriviaWhiteSpaces),
571
+ );
572
+ }
573
+
574
+ /**
575
+ * A comment's text without its delimiters, to wrap as a JSX comment.
576
+ *
577
+ * @param {string} comment
578
+ */
579
+ function commentText(comment) {
580
+ const body = comment.startsWith('//') ? comment.slice(2) : comment.slice(2, -2);
581
+ return body.trim().replaceAll('*/', '* /');
582
+ }
583
+
584
+ /** @param {string} name */
585
+ function isComponentName(name) {
586
+ return /^[A-Z]/.test(name);
587
+ }
588
+
589
+ class ModuleTransform {
590
+ /**
591
+ * @param {string} source
592
+ * @param {string} filename
593
+ * @param {TransformOptions} options
594
+ */
595
+ constructor(source, filename, options) {
596
+ this.source = source;
597
+ this.filename = filename;
598
+ this.options = options;
599
+ this.target = options.target ?? 'tsrx';
600
+ this.strong = options.strong === true;
601
+ /** @type {Set<string>} React imports read as values, not only as types. */
602
+ this.valueUses = new Set();
603
+ this.routerShell = false;
604
+ this.textTypes = options.strictNullChecks === true && /\.[cm]?tsx?$/.test(filename);
605
+ const { sf, checker } = bind(filename, source);
606
+ this.sf = sf;
607
+ this.checker = checker;
608
+ /** @type {Note[]} */
609
+ this.notes = [];
610
+ /** @type {Record<string, number>} */
611
+ this.rules = {};
612
+ this.template = false;
613
+ this.indentUnit = /^\t/m.test(source) ? '\t' : ' ';
614
+
615
+ /** @type {Map<ts.Node, Import>} Every import, keyed by its declaration. */
616
+ this.imports = new Map();
617
+ /** @type {Map<string, Import>} React and Octane imports, by local name. */
618
+ this.apiLocals = new Map();
619
+ /** React-module locals that are still referenced after the rewrite. */
620
+ this.used = new Set();
621
+ /** Imports the rewrite needs from Octane: module -> name -> { local, typeOnly } */
622
+ this.added = new Map();
623
+ /** Every name the module declares, to keep added imports from colliding. */
624
+ this.declared = new Set();
625
+ /** Attributes a parent rule has already consumed, such as a row key. */
626
+ this.removed = new Set();
627
+ /** `<Fragment key>` rows whose key moved to the `@for` header. */
628
+ this.bare = new Set();
629
+ /** Functions whose parameter list a rule replaced. */
630
+ this.parameters = new Map();
631
+ /** @type {Set<ts.BindingElement>} Rest props that give up `onChange` to a text field. */
632
+ this.restChange = new Set();
633
+ /** @type {Set<ts.JsxSpreadAttribute>} Spreads of those rest props, which pass it as `onInput`. */
634
+ this.changeSpreads = new Set();
635
+ /** @type {Set<ts.VariableDeclaration | ts.FunctionDeclaration>} Components to mark `descriptorChildren`. */
636
+ this.descriptorComponents = new Set();
637
+ /** Whether a `declare module` now augments `octane/jsx-runtime`. */
638
+ this.augments = false;
639
+ /** @type {Map<string, Unported | null>} Each import specifier's unported package. */
640
+ this.ports = new Map();
641
+ /** @type {Map<string, Unported>} Unported packages, by name. */
642
+ this.unported = new Map();
643
+ /** @type {Set<ts.JsxElement | ts.JsxSelfClosingElement>} Elements to host in a `ReactCompat` island. */
644
+ this.islands = new Set();
645
+ /** @type {ts.ImportDeclaration[]} Placeholder index -> import declaration. */
646
+ this.importSlots = [];
647
+ this.hasJsx = false;
648
+ /** Whether the module imports React, rather than already being Octane. */
649
+ this.fromReact = false;
650
+ /** @type {Map<string, string | null>} Each specifier's new spelling, or null to keep it. */
651
+ this.resolved = new Map();
652
+ }
653
+
654
+ /** @returns {TransformResult} */
655
+ run() {
656
+ this.analyze();
657
+ let code = this.emit(this.sf, PLAIN, 0);
658
+ code = this.finishImports(code);
659
+ code = code.replace(/^[ \t]*\u0000DROP\u0000[ \t]*\r?\n/gm, '').replaceAll(DROP, '');
660
+ code = code.replaceAll(LITERAL_NEWLINE, '\n');
661
+ const tsrx =
662
+ this.template || (this.target === 'tsrx' && (this.hasJsx || /\.[jt]sx$/.test(this.filename)));
663
+ if (tsrx) code = code.replace(/^\/\*\*\s*@jsxImportSource\s+\S+\s*\*\/[ \t]*\r?\n/m, '');
664
+ // A JavaScript module was never type-checked; as TSRX it stays unchecked.
665
+ if (tsrx && /\.[cm]?jsx?$/.test(this.filename)) {
666
+ code = code.replace(/^(#![^\n]*\n)?/, '$1// @ts-nocheck\n');
667
+ }
668
+ if (this.strong && tsrx) code = this.addStrongDirective(code);
669
+ if (!tsrx && this.fromReact && this.hasJsx && /\.(?:[jt]sx|js)$/.test(this.filename)) {
670
+ code = this.addJsxPragma(code);
671
+ }
672
+ return {
673
+ code,
674
+ changed: code !== this.source,
675
+ template: tsrx,
676
+ notes: this.notes.sort((a, b) => a.line - b.line),
677
+ rules: this.rules,
678
+ exports: this.exportsOf(),
679
+ unported: [...this.unported.values()],
680
+ };
681
+ }
682
+
683
+ /** @returns {ModuleExports} */
684
+ exportsOf() {
685
+ /** @type {Set<string>} */
686
+ const contexts = new Set();
687
+ /** @type {Set<string>} */
688
+ const exported = new Set();
689
+ /** @type {ModuleExports['reexports']} */
690
+ const reexports = [];
691
+ const isExported = (/** @type {ts.Statement} */ statement) =>
692
+ ts.canHaveModifiers(statement) &&
693
+ ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
694
+ for (const statement of this.sf.statements) {
695
+ if (ts.isVariableStatement(statement)) {
696
+ for (const declaration of statement.declarationList.declarations) {
697
+ if (!ts.isIdentifier(declaration.name) || !this.isContext(declaration.name)) continue;
698
+ contexts.add(declaration.name.text);
699
+ if (isExported(statement)) exported.add(declaration.name.text);
700
+ }
701
+ } else if (
702
+ ts.isExportDeclaration(statement) &&
703
+ statement.exportClause &&
704
+ ts.isNamedExports(statement.exportClause)
705
+ ) {
706
+ const pairs = statement.exportClause.elements.map(
707
+ (element) =>
708
+ /** @type {[string, string]} */ ([
709
+ (element.propertyName ?? element.name).text,
710
+ element.name.text,
711
+ ]),
712
+ );
713
+ if (statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) {
714
+ reexports.push({ specifier: statement.moduleSpecifier.text, names: pairs });
715
+ } else {
716
+ for (const [local, name] of pairs) if (contexts.has(local)) exported.add(name);
717
+ }
718
+ } else if (
719
+ ts.isExportDeclaration(statement) &&
720
+ statement.moduleSpecifier &&
721
+ ts.isStringLiteral(statement.moduleSpecifier)
722
+ ) {
723
+ reexports.push({ specifier: statement.moduleSpecifier.text, names: null });
724
+ } else if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) {
725
+ if (contexts.has(statement.expression.text)) exported.add('default');
726
+ }
727
+ }
728
+ return { contexts: [...exported], reexports };
729
+ }
730
+
731
+ // ---------------------------------------------------------------- analysis
732
+
733
+ analyze() {
734
+ // Added imports quote their module as the module's own imports do.
735
+ const first = this.sf.statements.find(ts.isImportDeclaration);
736
+ this.quote = first ? first.moduleSpecifier.getText(this.sf)[0] : "'";
737
+ /** Locals imported from a package with no Octane port. */
738
+ const portLocals = new Set();
739
+ for (const statement of this.sf.statements) {
740
+ if (
741
+ ts.isExportDeclaration(statement) &&
742
+ !statement.isTypeOnly &&
743
+ statement.moduleSpecifier &&
744
+ ts.isStringLiteral(statement.moduleSpecifier)
745
+ ) {
746
+ const port = this.portOf(statement.moduleSpecifier.text);
747
+ if (port) {
748
+ this.note(
749
+ RULE.bindings,
750
+ 'warning',
751
+ statement,
752
+ `\`${port.name}\` has no Octane port: import its components from it where they render, so they can render in a \`ReactCompat\` island.`,
753
+ );
754
+ }
755
+ }
756
+ if (!ts.isImportDeclaration(statement) || !statement.importClause) continue;
757
+ const module = /** @type {ts.StringLiteral} */ (statement.moduleSpecifier).text;
758
+ if (module in REACT_MODULES) this.fromReact = true;
759
+ if (/^@tanstack\/react-(?:router|start)(?:\/|$)/.test(module)) this.routerShell = true;
760
+ const clause = statement.importClause;
761
+ const record = (
762
+ /** @type {ts.Node} */ declaration,
763
+ /** @type {ts.Identifier} */ name,
764
+ /** @type {string} */ imported,
765
+ /** @type {boolean} */ typeOnly,
766
+ ) => {
767
+ const port = typeOnly ? null : this.portOf(module);
768
+ const entry = {
769
+ module,
770
+ local: name.text,
771
+ imported,
772
+ namespace: imported === '*',
773
+ typeOnly,
774
+ port,
775
+ };
776
+ this.imports.set(declaration, entry);
777
+ if (port) portLocals.add(name.text);
778
+ if (isApiModule(module)) this.apiLocals.set(name.text, entry);
779
+ };
780
+ // A default import of React is the namespace in practice; any other
781
+ // module's default import is its `default` export.
782
+ if (clause.name) {
783
+ record(clause, clause.name, isApiModule(module) ? '*' : 'default', clause.isTypeOnly);
784
+ }
785
+ const bindings = clause.namedBindings;
786
+ if (bindings && ts.isNamespaceImport(bindings)) {
787
+ record(bindings, bindings.name, '*', clause.isTypeOnly);
788
+ }
789
+ if (bindings && ts.isNamedImports(bindings)) {
790
+ for (const element of bindings.elements) {
791
+ const imported = (element.propertyName ?? element.name).text;
792
+ record(element, element.name, imported, clause.isTypeOnly || element.isTypeOnly);
793
+ }
794
+ }
795
+ }
796
+ /** @type {ts.JsxOpeningLikeElement[]} */
797
+ const fields = [];
798
+ /** @type {ts.Expression[]} Values read as an element: cloned, inspected, or a `render` prop. */
799
+ const elements = [];
800
+ const visit = (/** @type {ts.Node} */ node) => {
801
+ if (ts.isIdentifier(node) && declaresName(node)) this.declared.add(node.text);
802
+ if (ts.isIdentifier(node) && portLocals.has(node.text)) this.planUnported(node);
803
+ if (isJsx(node)) this.hasJsx = true;
804
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) fields.push(node);
805
+ if (
806
+ ts.isJsxAttribute(node) &&
807
+ node.name.getText(this.sf) === 'render' &&
808
+ node.initializer &&
809
+ ts.isJsxExpression(node.initializer) &&
810
+ node.initializer.expression
811
+ ) {
812
+ elements.push(node.initializer.expression);
813
+ }
814
+ if (ts.isCallExpression(node) && node.arguments[0] && this.readsElement(node.expression)) {
815
+ elements.push(node.arguments[0]);
816
+ }
817
+ ts.forEachChild(node, visit);
818
+ };
819
+ visit(this.sf);
820
+ for (const field of fields) if (this.takesChange(field)) this.planRestChange(field);
821
+ for (const element of elements) this.planDescriptorChildren(element);
822
+ }
823
+
824
+ /**
825
+ * The package with no Octane port that a specifier names, or null. It
826
+ * still runs on React, which only the codemod's report and a comment say.
827
+ *
828
+ * @param {string} module
829
+ */
830
+ portOf(module) {
831
+ let port = this.ports.get(module);
832
+ if (port === undefined) {
833
+ const name = isApiModule(module) ? null : (this.options.unported?.(module) ?? null);
834
+ port = name === null ? null : (this.unported.get(name) ?? { name, islands: 0, blocked: 0 });
835
+ if (port) this.unported.set(port.name, port);
836
+ this.ports.set(module, port);
837
+ }
838
+ return port;
839
+ }
840
+
841
+ /**
842
+ * A component from a package with no Octane port renders in React, inside
843
+ * a `ReactCompat` island, when its element hands React nothing Octane
844
+ * renders. Its hooks and contexts cannot run in an Octane component, so
845
+ * they are reported.
846
+ *
847
+ * @param {ts.Identifier} node
848
+ */
849
+ planUnported(node) {
850
+ const port = this.inImport(node) ? null : this.importOf(node)?.port;
851
+ if (!port) return;
852
+ // `Toast.Bar`, through a namespace or default import, is the member.
853
+ const member =
854
+ ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node
855
+ ? node.parent
856
+ : node;
857
+ const name = ts.isPropertyAccessExpression(member) ? member.name.text : node.text;
858
+ const text = member.getText(this.sf);
859
+ const parent = member.parent;
860
+ const block = (/** @type {string} */ message) => {
861
+ port.blocked++;
862
+ this.note(RULE.bindings, 'error', member, `${message} \`${port.name}\` has no Octane port.`);
863
+ };
864
+ if (
865
+ (ts.isJsxOpeningElement(parent) || ts.isJsxSelfClosingElement(parent)) &&
866
+ parent.tagName === member
867
+ ) {
868
+ const element = ts.isJsxOpeningElement(parent) ? parent.parent : parent;
869
+ if (this.inIsland(element)) return;
870
+ if (!this.hostsInReact(element)) {
871
+ block(
872
+ `\`<${text}>\` takes children or props that Octane renders, which cannot cross into a React island.`,
873
+ );
874
+ } else if (!this.options.reactCompat) {
875
+ block(
876
+ `\`<${text}>\` can render in a \`ReactCompat\` island only with React and React DOM 19.2 or newer in the React 19 series.`,
877
+ );
878
+ } else {
879
+ port.islands++;
880
+ this.islands.add(element);
881
+ }
882
+ } else if (ts.isCallExpression(parent) && parent.expression === member) {
883
+ if (/^use[A-Z0-9]/.test(name))
884
+ block(`\`${text}\` is a React hook, which Octane cannot call.`);
885
+ } else if (
886
+ ts.isCallExpression(parent) &&
887
+ /^(?:use|useContext)$/.test(this.calleeName(parent.expression) ?? '')
888
+ ) {
889
+ block(`\`${text}\` is a React context, which Octane cannot read.`);
890
+ }
891
+ }
892
+
893
+ /**
894
+ * Whether a React component's element can be the root of a `ReactCompat`
895
+ * island: React renders all of it, so its children are text and no prop
896
+ * holds an element, as JSX here, through a value this module declares, or
897
+ * by its type.
898
+ *
899
+ * @param {ts.JsxElement | ts.JsxSelfClosingElement} element
900
+ */
901
+ hostsInReact(element) {
902
+ // By type: a cast to `any` or `ReactNode` proves nothing.
903
+ const text = (/** @type {ts.JsxChild} */ child) =>
904
+ ts.isJsxText(child) ||
905
+ (ts.isJsxExpression(child) &&
906
+ (!child.expression || textKind(this.typeOf(child.expression)) !== 0));
907
+ if (ts.isJsxElement(element) && !element.children.every(text)) return false;
908
+ const seen = new Set();
909
+ /** @type {(node: ts.Node) => boolean} */
910
+ const rendersOctane = (node) => {
911
+ if (isJsx(node)) return true;
912
+ if (ts.isIdentifier(node)) {
913
+ const project = this.projectType(node);
914
+ const type = (project?.checker ?? this.checker).typeToString(
915
+ project?.type ?? this.checker.getTypeAtLocation(node),
916
+ undefined,
917
+ ts.TypeFormatFlags.NoTruncation,
918
+ );
919
+ if (/\b(?:React(?:Node|Element)|JSX\.Element)\b/.test(type)) return true;
920
+ const declaration = this.declarationOf(node);
921
+ if (declaration?.getSourceFile() === this.sf && !seen.has(declaration)) {
922
+ seen.add(declaration);
923
+ if (rendersOctane(declaration)) return true;
924
+ }
925
+ }
926
+ return ts.forEachChild(node, rendersOctane) ?? false;
927
+ };
928
+ return !rendersOctane(
929
+ ts.isJsxElement(element) ? element.openingElement.attributes : element.attributes,
930
+ );
931
+ }
932
+
933
+ /**
934
+ * Whether an element is already the child of a `ReactCompat` island.
935
+ *
936
+ * @param {ts.JsxElement | ts.JsxSelfClosingElement} element
937
+ */
938
+ inIsland(element) {
939
+ const parent = element.parent;
940
+ if (!ts.isJsxElement(parent)) return false;
941
+ const entry = this.importOf(parent.openingElement.tagName);
942
+ return entry?.module === 'octane/react' && entry.imported === 'ReactCompat';
943
+ }
944
+
945
+ /**
946
+ * Whether a callee reads its argument as an element: `cloneElement`,
947
+ * `isValidElement`, or a `Children` method.
948
+ *
949
+ * @param {ts.Expression} callee
950
+ */
951
+ readsElement(callee) {
952
+ const name = this.calleeName(callee);
953
+ if (name === 'cloneElement' || name === 'isValidElement') return true;
954
+ return (
955
+ ts.isPropertyAccessExpression(callee) && this.calleeName(callee.expression) === 'Children'
956
+ );
957
+ }
958
+
959
+ /**
960
+ * React passes a component its JSX children as elements, which
961
+ * `render={children}` and `cloneElement(children)` rely on. Octane passes a
962
+ * compiled render body unless the component is marked `descriptorChildren`,
963
+ * so mark the component whose own `children` this reads.
964
+ *
965
+ * @param {ts.Expression} expression
966
+ */
967
+ planDescriptorChildren(expression) {
968
+ let value = expression;
969
+ while (
970
+ ts.isParenthesizedExpression(value) ||
971
+ ts.isAsExpression(value) ||
972
+ ts.isSatisfiesExpression(value) ||
973
+ ts.isNonNullExpression(value) ||
974
+ ts.isTypeAssertionExpression(value)
975
+ ) {
976
+ value = value.expression;
977
+ }
978
+ const component = this.childrenOwner(value);
979
+ if (!component) return;
980
+ // `memo(…)` and `forwardRef(…)` wrap it; the declaration holds the call.
981
+ let holder = component.parent;
982
+ while (
983
+ ts.isCallExpression(holder) &&
984
+ /^(?:memo|forwardRef)$/.test(this.calleeName(holder.expression) ?? '')
985
+ ) {
986
+ holder = holder.parent;
987
+ }
988
+ if (ts.isCallExpression(holder) && this.calleeName(holder.expression) === 'descriptorChildren')
989
+ return;
990
+ // The compiler reads the marker from module-level `const` bindings only.
991
+ if (
992
+ ts.isVariableDeclaration(holder) &&
993
+ ts.isIdentifier(holder.name) &&
994
+ ts.getCombinedNodeFlags(holder) & ts.NodeFlags.Const &&
995
+ holder.parent.parent.parent === this.sf
996
+ ) {
997
+ this.descriptorComponents.add(holder);
998
+ } else if (
999
+ ts.isFunctionDeclaration(component) &&
1000
+ component.parent === this.sf &&
1001
+ component.name &&
1002
+ !component.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword) &&
1003
+ // Overload signatures would stay `function` declarations.
1004
+ this.checker.getSymbolAtLocation(component.name)?.declarations?.length === 1 &&
1005
+ this.declaredBeforeUse(component)
1006
+ ) {
1007
+ this.descriptorComponents.add(component);
1008
+ } else {
1009
+ this.note(
1010
+ RULE.descriptorChildren,
1011
+ 'warning',
1012
+ expression,
1013
+ 'This reads `children` as an element, which Octane passes as a compiled render body; mark the component with `descriptorChildren` so callers pass element descriptors.',
1014
+ );
1015
+ }
1016
+ }
1017
+
1018
+ /**
1019
+ * The component whose own `children` prop `node` is: `children` from its
1020
+ * props pattern, or `props.children`.
1021
+ *
1022
+ * @param {ts.Expression} node
1023
+ * @returns {ts.SignatureDeclaration | null}
1024
+ */
1025
+ childrenOwner(node) {
1026
+ /** @type {ts.Node | null} */
1027
+ let props = null;
1028
+ if (ts.isPropertyAccessExpression(node) && node.name.text === 'children') {
1029
+ props = ts.isIdentifier(node.expression) ? this.declarationOf(node.expression) : null;
1030
+ } else if (ts.isIdentifier(node)) {
1031
+ const declaration = this.declarationOf(node);
1032
+ if (
1033
+ declaration &&
1034
+ ts.isBindingElement(declaration) &&
1035
+ (declaration.propertyName ?? declaration.name).getText(this.sf) === 'children'
1036
+ ) {
1037
+ props = declaration.parent.parent;
1038
+ }
1039
+ }
1040
+ if (!props || !ts.isParameter(props)) return null;
1041
+ const component = /** @type {ts.SignatureDeclaration} */ (props.parent);
1042
+ return component.parameters[0] === props && isFunctionLike(component) ? component : null;
1043
+ }
1044
+
1045
+ /**
1046
+ * Whether no code that runs while the module loads can reach `fn` before
1047
+ * its declaration, so it can become a `const`, which is not hoisted. Any
1048
+ * function there may run (an IIFE, a callback, a method an imported call
1049
+ * invokes) except one it only defines: a declaration or a variable's value.
1050
+ * Those run only when called or passed on, which counts as reaching `fn`
1051
+ * for any binding the module declares.
1052
+ *
1053
+ * @param {ts.FunctionDeclaration} fn
1054
+ */
1055
+ declaredBeforeUse(fn) {
1056
+ let safe = true;
1057
+ const visit = (/** @type {ts.Node} */ node) => {
1058
+ if (!safe) return;
1059
+ if (isFunctionLike(node) && this.onlyDefines(node)) return;
1060
+ if (ts.isIdentifier(node) && node !== fn.name) {
1061
+ const declaration = this.declarationOf(node);
1062
+ const call = node.parent;
1063
+ const handed =
1064
+ (ts.isCallExpression(call) || ts.isNewExpression(call)) &&
1065
+ (call.expression === node || call.arguments?.includes(node));
1066
+ if (
1067
+ declaration === fn ||
1068
+ (handed && declaration?.getSourceFile() === this.sf && !this.importOf(node))
1069
+ ) {
1070
+ safe = false;
1071
+ }
1072
+ }
1073
+ ts.forEachChild(node, visit);
1074
+ };
1075
+ for (const statement of this.sf.statements) {
1076
+ if (statement === fn) break;
1077
+ visit(statement);
1078
+ }
1079
+ return safe;
1080
+ }
1081
+
1082
+ /**
1083
+ * Whether a function is only defined where it stands: a declaration, or a
1084
+ * variable's value, also through `memo` or `forwardRef`, which do not call it.
1085
+ *
1086
+ * @param {ts.Node} fn
1087
+ */
1088
+ onlyDefines(fn) {
1089
+ if (ts.isFunctionDeclaration(fn)) return true;
1090
+ let parent = fn.parent;
1091
+ while (
1092
+ ts.isParenthesizedExpression(parent) ||
1093
+ (ts.isCallExpression(parent) &&
1094
+ /^(?:memo|forwardRef)$/.test(this.calleeName(parent.expression) ?? ''))
1095
+ ) {
1096
+ parent = parent.parent;
1097
+ }
1098
+ return ts.isVariableDeclaration(parent);
1099
+ }
1100
+
1101
+ /**
1102
+ * Whether an `onChange` a spread passes this element fires per edit in
1103
+ * React: a text field with no `onChange` or `onInput` of its own.
1104
+ *
1105
+ * @param {ts.JsxOpeningLikeElement} element
1106
+ */
1107
+ takesChange(element) {
1108
+ if (!/^(?:input|textarea)$/.test(element.tagName.getText(this.sf))) return false;
1109
+ if (attributeOf(element, 'onChange') || attributeOf(element, 'onInput')) return false;
1110
+ const type = attributeOf(element, 'type')?.initializer;
1111
+ return !type || !ts.isStringLiteral(type) || TEXT_INPUT_TYPES.has(type.text);
1112
+ }
1113
+
1114
+ /**
1115
+ * A text field that spreads a component's rest props passes on any
1116
+ * `onChange` in them, which React fires per edit and Octane on commit. Take
1117
+ * it out of the rest and pass it as `onInput`, before the spread, so a
1118
+ * caller's own `onInput` still wins. Only when the rest is read nowhere
1119
+ * else, since those reads would lose it.
1120
+ *
1121
+ * @param {ts.JsxOpeningLikeElement} field
1122
+ */
1123
+ planRestChange(field) {
1124
+ for (const spread of field.attributes.properties) {
1125
+ if (!ts.isJsxSpreadAttribute(spread)) continue;
1126
+ // Props whose type has no `onChange` have none to pass on.
1127
+ const type = this.projectType(spread.expression)?.type;
1128
+ if (type && !(type.flags & ts.TypeFlags.Any) && !type.getProperty('onChange')) continue;
1129
+ const declaration = ts.isIdentifier(spread.expression)
1130
+ ? this.declarationOf(spread.expression)
1131
+ : null;
1132
+ const rest =
1133
+ declaration &&
1134
+ ts.isBindingElement(declaration) &&
1135
+ declaration.dotDotDotToken &&
1136
+ ts.isObjectBindingPattern(declaration.parent)
1137
+ ? declaration
1138
+ : null;
1139
+ // A pattern that names `onChange` leaves none in the rest.
1140
+ const pattern = /** @type {ts.ObjectBindingPattern | undefined} */ (rest?.parent);
1141
+ if (
1142
+ pattern?.elements.some((e) => (e.propertyName ?? e.name).getText(this.sf) === 'onChange')
1143
+ ) {
1144
+ continue;
1145
+ }
1146
+ if (
1147
+ rest &&
1148
+ !this.checker.resolveName('onChange', spread, ts.SymbolFlags.Value, false) &&
1149
+ this.onlySpreadOntoFields(rest)
1150
+ ) {
1151
+ this.restChange.add(rest);
1152
+ this.changeSpreads.add(spread);
1153
+ } else {
1154
+ this.note(
1155
+ RULE.nativeChange,
1156
+ 'warning',
1157
+ spread,
1158
+ `An \`onChange\` in this spread fires on commit (blur) in Octane, not per edit; pass it to the \`<${field.tagName.getText(this.sf)}>\` as \`onInput\`.`,
1159
+ );
1160
+ }
1161
+ }
1162
+ }
1163
+
1164
+ /**
1165
+ * Whether no read of a rest binding but its spreads onto text fields can
1166
+ * see an `onChange` in it: other reads name another member (`props.type`).
1167
+ *
1168
+ * @param {ts.BindingElement} rest
1169
+ */
1170
+ onlySpreadOntoFields(rest) {
1171
+ let only = true;
1172
+ const visit = (/** @type {ts.Node} */ node) => {
1173
+ if (!only) return;
1174
+ if (ts.isIdentifier(node) && node !== rest.name && this.declarationOf(node) === rest) {
1175
+ const parent = node.parent;
1176
+ only = ts.isJsxSpreadAttribute(parent)
1177
+ ? this.takesChange(parent.parent.parent)
1178
+ : ts.isPropertyAccessExpression(parent) &&
1179
+ parent.expression === node &&
1180
+ parent.name.text !== 'onChange';
1181
+ }
1182
+ ts.forEachChild(node, visit);
1183
+ };
1184
+ visit(ts.findAncestor(rest, ts.isFunctionLike) ?? this.sf);
1185
+ return only;
1186
+ }
1187
+
1188
+ /**
1189
+ * The declaration a name refers to.
1190
+ *
1191
+ * @param {ts.Identifier} node
1192
+ * @returns {ts.Declaration | null}
1193
+ */
1194
+ declarationOf(node) {
1195
+ const parent = node.parent;
1196
+ const symbol =
1197
+ ts.isShorthandPropertyAssignment(parent) && parent.name === node
1198
+ ? this.checker.getShorthandAssignmentValueSymbol(parent)
1199
+ : this.checker.getSymbolAtLocation(node);
1200
+ return symbol?.declarations?.[0] ?? null;
1201
+ }
1202
+
1203
+ /**
1204
+ * The initializer of the `const` a name refers to, or null.
1205
+ *
1206
+ * @param {ts.Identifier} node
1207
+ * @returns {ts.Expression | null}
1208
+ */
1209
+ constValue(node) {
1210
+ const declaration = this.declarationOf(node);
1211
+ if (
1212
+ !declaration ||
1213
+ !ts.isVariableDeclaration(declaration) ||
1214
+ !declaration.initializer ||
1215
+ !(ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const)
1216
+ ) {
1217
+ return null;
1218
+ }
1219
+ return declaration.initializer;
1220
+ }
1221
+
1222
+ /**
1223
+ * The import a name refers to, or null when it refers to anything else,
1224
+ * such as a local that shadows the import.
1225
+ *
1226
+ * @param {ts.Node} node
1227
+ * @returns {Import | null}
1228
+ */
1229
+ importOf(node) {
1230
+ if (!ts.isIdentifier(node)) return null;
1231
+ const declaration = this.declarationOf(node);
1232
+ return declaration ? (this.imports.get(declaration) ?? null) : null;
1233
+ }
1234
+
1235
+ /**
1236
+ * The React or Octane export a callee names, through a named import or a
1237
+ * namespace.
1238
+ *
1239
+ * @param {ts.Node} node
1240
+ * @returns {string | null}
1241
+ */
1242
+ calleeName(node) {
1243
+ return this.callee(node)?.name ?? null;
1244
+ }
1245
+
1246
+ /**
1247
+ * @param {ts.Node} node
1248
+ * @returns {{ name: string, module: string } | null}
1249
+ */
1250
+ callee(node) {
1251
+ if (ts.isIdentifier(node)) {
1252
+ const entry = this.importOf(node);
1253
+ if (!entry || entry.namespace || entry.typeOnly || !isApiModule(entry.module)) return null;
1254
+ return { name: entry.imported, module: entry.module };
1255
+ }
1256
+ if (ts.isPropertyAccessExpression(node)) {
1257
+ const entry = this.importOf(node.expression);
1258
+ if (!entry?.namespace || !isApiModule(entry.module)) return null;
1259
+ return { name: node.name.text, module: entry.module };
1260
+ }
1261
+ return null;
1262
+ }
1263
+
1264
+ /** @param {ts.Node} node */
1265
+ line(node) {
1266
+ return this.sf.getLineAndCharacterOfPosition(node.getStart(this.sf)).line + 1;
1267
+ }
1268
+
1269
+ /**
1270
+ * @param {string} rule
1271
+ * @param {Severity} severity
1272
+ * @param {ts.Node} node
1273
+ * @param {string} message
1274
+ */
1275
+ note(rule, severity, node, message) {
1276
+ this.notes.push({ rule, severity, line: this.line(node), message });
1277
+ }
1278
+
1279
+ /** @param {string} rule */
1280
+ count(rule) {
1281
+ this.rules[rule] = (this.rules[rule] ?? 0) + 1;
1282
+ }
1283
+
1284
+ /**
1285
+ * Request an import from Octane and return the local name to use.
1286
+ *
1287
+ * @param {string} module
1288
+ * @param {string} name
1289
+ * @param {boolean} typeOnly
1290
+ */
1291
+ require(module, name, typeOnly) {
1292
+ let names = this.added.get(module);
1293
+ if (!names) this.added.set(module, (names = new Map()));
1294
+ const existing = names.get(name);
1295
+ if (existing) {
1296
+ if (!typeOnly) existing.typeOnly = false;
1297
+ return existing.local;
1298
+ }
1299
+ // A React import of the same name becomes this import.
1300
+ const prior = this.apiLocals.get(name);
1301
+ const collides =
1302
+ (this.declared.has(name) || this.readsGlobal(name)) &&
1303
+ !(prior && mapReactImport(prior.module, prior.imported, prior.typeOnly)?.name === name);
1304
+ const local = collides ? `Octane${name[0].toUpperCase()}${name.slice(1)}` : name;
1305
+ names.set(name, { local, typeOnly });
1306
+ return local;
1307
+ }
1308
+
1309
+ /**
1310
+ * Whether this module declares `symbol`, rather than the library or
1311
+ * nothing at all.
1312
+ *
1313
+ * @param {ts.Symbol | undefined} symbol
1314
+ */
1315
+ declaresHere(symbol) {
1316
+ return symbol?.declarations?.some((d) => d.getSourceFile() === this.sf) ?? false;
1317
+ }
1318
+
1319
+ /**
1320
+ * Whether the module reads `name` as a global, such as the DOM's
1321
+ * `MouseEvent`, which an import of the same name would shadow.
1322
+ *
1323
+ * @param {string} name
1324
+ */
1325
+ readsGlobal(name) {
1326
+ /** @type {(node: ts.Node) => boolean} */
1327
+ const visit = (node) => {
1328
+ if (
1329
+ ts.isIdentifier(node) &&
1330
+ node.text === name &&
1331
+ !isPropertyName(node) &&
1332
+ !declaresName(node) &&
1333
+ !this.declaresHere(this.checker.getSymbolAtLocation(node))
1334
+ ) {
1335
+ return true;
1336
+ }
1337
+ return ts.forEachChild(node, visit) ?? false;
1338
+ };
1339
+ return visit(this.sf) === true;
1340
+ }
1341
+
1342
+ // ---------------------------------------------------------------- emission
1343
+
1344
+ /**
1345
+ * The new text of `node`: a rule's replacement, or the original text with
1346
+ * its children emitted in place.
1347
+ *
1348
+ * @param {ts.Node} node
1349
+ * @param {Context} ctx
1350
+ * @param {number} [start]
1351
+ * @returns {string}
1352
+ */
1353
+ emit(node, ctx, start) {
1354
+ if (ts.isIdentifier(node) && this.apiLocals.has(node.text) && !this.inImport(node)) {
1355
+ const entry = this.importOf(node);
1356
+ if (entry) {
1357
+ this.used.add(entry.local);
1358
+ if (!inTypeNode(node)) this.valueUses.add(entry.local);
1359
+ }
1360
+ }
1361
+ const replaced = this.rewrite(node, ctx);
1362
+ if (replaced !== null) return replaced;
1363
+ const text = this.span(node, start ?? node.getStart(this.sf), node.end, ctx);
1364
+ if ((ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) && text.includes('\n')) {
1365
+ return text.replaceAll('\n', LITERAL_NEWLINE);
1366
+ }
1367
+ return text;
1368
+ }
1369
+
1370
+ /** @param {ts.Node} node */
1371
+ inImport(node) {
1372
+ for (let current = node.parent; current; current = current.parent) {
1373
+ if (ts.isImportDeclaration(current)) return true;
1374
+ }
1375
+ return false;
1376
+ }
1377
+
1378
+ /**
1379
+ * The text of `node` between `from` and `to`, with every child inside that
1380
+ * range emitted.
1381
+ *
1382
+ * @param {ts.Node} node
1383
+ * @param {number} from
1384
+ * @param {number} to
1385
+ * @param {Context} ctx
1386
+ */
1387
+ span(node, from, to, ctx) {
1388
+ let out = '';
1389
+ let cursor = from;
1390
+ const childCtx = ts.isJsxElement(node) || ts.isJsxFragment(node) ? ctx : PLAIN;
1391
+ node.forEachChild((child) => {
1392
+ if (child.pos === child.end) return;
1393
+ const start = child.getStart(this.sf);
1394
+ if (start < from || child.end > to) return;
1395
+ out += this.source.slice(cursor, start);
1396
+ if (ts.isJsxAttributes(child) && child.properties.every((a) => this.removed.has(a))) {
1397
+ out = out.replace(/[ \t]+$/, '');
1398
+ cursor = child.end;
1399
+ return;
1400
+ }
1401
+ const jsxChild =
1402
+ ts.isJsxElement(child) ||
1403
+ ts.isJsxSelfClosingElement(child) ||
1404
+ ts.isJsxFragment(child) ||
1405
+ ts.isJsxExpression(child) ||
1406
+ ts.isJsxText(child);
1407
+ out += this.emit(child, jsxChild ? childCtx : PLAIN);
1408
+ cursor = child.end;
1409
+ });
1410
+ return out + this.source.slice(cursor, to);
1411
+ }
1412
+
1413
+ /**
1414
+ * @param {ts.Node} node
1415
+ * @param {Context} ctx
1416
+ * @returns {string | null}
1417
+ */
1418
+ rewrite(node, ctx) {
1419
+ if (ts.isImportDeclaration(node)) return this.rewriteImport(node);
1420
+ if (ts.isExportDeclaration(node) && node.moduleSpecifier) return this.rewriteReexport(node);
1421
+ if (ts.isCallExpression(node)) return this.rewriteCall(node);
1422
+ if (ts.isPropertyAccessExpression(node)) return this.rewriteMember(node);
1423
+ if (ts.isQualifiedName(node)) return this.rewriteQualifiedType(node);
1424
+ if (ts.isImportTypeNode(node)) return this.rewriteImportType(node);
1425
+ if (ts.isTypeReferenceNode(node)) return this.rewriteTypeReference(node);
1426
+ if (ts.isExpressionStatement(node)) return this.rewriteStatement(node);
1427
+ if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) this.checkClass(node);
1428
+ if (ts.isBinaryExpression(node)) {
1429
+ const guarded = this.rewriteRenderProp(node);
1430
+ if (guarded !== null) return guarded;
1431
+ this.checkDefaultProps(node);
1432
+ }
1433
+ if (ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name)) {
1434
+ return node.name.text in REACT_MODULES
1435
+ ? this.rewriteAugmentation(node, node.name)
1436
+ : this.rewriteSpecifier(node, node.name);
1437
+ }
1438
+ if (ts.isBindingElement(node) && this.restChange.has(node)) {
1439
+ return 'onChange, ' + node.getText(this.sf);
1440
+ }
1441
+ if (ts.isVariableDeclaration(node) && this.descriptorComponents.has(node) && node.initializer) {
1442
+ this.count(RULE.descriptorChildren);
1443
+ return (
1444
+ this.span(node, node.getStart(this.sf), node.initializer.getStart(this.sf), PLAIN) +
1445
+ `${this.require('octane', 'descriptorChildren', false)}(${this.emit(node.initializer, PLAIN)})`
1446
+ );
1447
+ }
1448
+ if (ts.isJsxText(node) && this.target === 'tsrx' && /\/[/*]/.test(node.text)) {
1449
+ // TSRX reads `//` and `/*` in element text as comments, as JavaScript does.
1450
+ return node.getText(this.sf).replace(/\/(?=[/*])/g, "{'/'}");
1451
+ }
1452
+ if (
1453
+ ts.isIdentifier(node) &&
1454
+ this.routerShell &&
1455
+ Object.hasOwn(DOCUMENT_TAGS, node.text) &&
1456
+ (ts.isJsxOpeningElement(node.parent) ||
1457
+ ts.isJsxClosingElement(node.parent) ||
1458
+ ts.isJsxSelfClosingElement(node.parent)) &&
1459
+ node.parent.tagName === node
1460
+ ) {
1461
+ // The router's document components own the hydration root.
1462
+ if (!ts.isJsxClosingElement(node.parent)) this.count(RULE.documentShell);
1463
+ return this.require('@octanejs/tanstack-router', DOCUMENT_TAGS[node.text], false);
1464
+ }
1465
+ if (ts.isJsxAttributes(node)) return this.rewriteAttributes(node);
1466
+ if ((ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) && this.islands.has(node)) {
1467
+ this.count(RULE.reactCompat);
1468
+ const island = this.require('octane/react', 'ReactCompat', false);
1469
+ return `<${island}>${this.span(node, node.getStart(this.sf), node.end, PLAIN)}</${island}>`;
1470
+ }
1471
+ if (ts.isJsxElement(node)) return this.rewriteElement(node, ctx);
1472
+ if (ts.isJsxExpression(node) && ctx.template) return this.rewriteHole(node);
1473
+ if (
1474
+ ts.isFunctionDeclaration(node) ||
1475
+ ts.isFunctionExpression(node) ||
1476
+ ts.isArrowFunction(node)
1477
+ ) {
1478
+ const component = this.target === 'tsrx' ? this.rewriteComponent(node) : null;
1479
+ const text =
1480
+ component ??
1481
+ (this.parameters.has(node) && node.body
1482
+ ? this.head(node, node.body.getStart(this.sf)) + this.emit(node.body, PLAIN)
1483
+ : null);
1484
+ if (!ts.isFunctionDeclaration(node) || !this.descriptorComponents.has(node)) return text;
1485
+ // A marked binding is a `const`; the function keeps its name.
1486
+ this.count(RULE.descriptorChildren);
1487
+ const fn = (text ?? this.span(node, node.getStart(this.sf), node.end, ctx)).replace(
1488
+ /^export\s+/,
1489
+ '',
1490
+ );
1491
+ const exported = node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
1492
+ return `${exported ? 'export ' : ''}const ${node.name?.text} = ${this.require('octane', 'descriptorChildren', false)}(${fn});`;
1493
+ }
1494
+ return null;
1495
+ }
1496
+
1497
+ // ---------------------------------------------------------------- imports
1498
+
1499
+ /** @param {ts.ImportDeclaration} node */
1500
+ rewriteImport(node) {
1501
+ const module = /** @type {ts.StringLiteral} */ (node.moduleSpecifier).text;
1502
+ if (module === 'octane') return null;
1503
+ if (module === '@react-three/fiber' && this.hasJsx) {
1504
+ this.note(
1505
+ RULE.unsupported,
1506
+ 'error',
1507
+ node,
1508
+ "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)`.",
1509
+ );
1510
+ }
1511
+ if (module in REACT_MODULES) {
1512
+ this.importSlots.push(node);
1513
+ return `\u0000IMPORT${this.importSlots.length - 1}\u0000`;
1514
+ }
1515
+ const text =
1516
+ this.rewritePackageNames(node, module) ?? this.rewriteSpecifier(node, node.moduleSpecifier);
1517
+ // Analysis recorded the packages this module imports values from.
1518
+ const port = node.importClause?.isTypeOnly === false ? (this.ports.get(module) ?? null) : null;
1519
+ if (
1520
+ !port ||
1521
+ ts
1522
+ .getLeadingCommentRanges(this.source, node.pos)
1523
+ ?.some((range) => this.source.slice(range.pos, range.end).includes('No Octane port of'))
1524
+ )
1525
+ return text;
1526
+ return `// ${portComment(port)}\n${text ?? node.getText(this.sf)}`;
1527
+ }
1528
+
1529
+ /**
1530
+ * An import or re-export of a ported package whose port spells some of its
1531
+ * names differently. A Radix package is a namespace of `@octanejs/radix`, so
1532
+ * its namespace import becomes that namespace and its named imports read
1533
+ * from it. Names the port lacks stay on the React package, for a person.
1534
+ *
1535
+ * @param {ts.ImportDeclaration | ts.ExportDeclaration} node
1536
+ * @param {string} module
1537
+ */
1538
+ rewritePackageNames(node, module) {
1539
+ const clause = ts.isImportDeclaration(node) ? node.importClause : node;
1540
+ const namespace = radixNamespace(module);
1541
+ const next = this.resolve(module);
1542
+ // A default import; and a Radix package's re-export, which rewriteSpecifier reports.
1543
+ if (!clause || next === null || (ts.isImportClause(clause) ? clause.name : namespace)) {
1544
+ return null;
1545
+ }
1546
+ const keyword = ts.isImportClause(clause) ? 'import' : 'export';
1547
+ const quote =
1548
+ this.source[/** @type {ts.Expression} */ (node.moduleSpecifier).getStart(this.sf)];
1549
+ const from = (/** @type {string} */ specifier) => `from ${quote}${specifier}${quote};`;
1550
+ const type = clause.isTypeOnly ? 'type ' : '';
1551
+ const bindings = ts.isImportClause(clause) ? clause.namedBindings : clause.exportClause;
1552
+ if (bindings && ts.isNamespaceImport(bindings)) {
1553
+ if (namespace === null) return null;
1554
+ const local = bindings.name.text;
1555
+ this.count(RULE.import);
1556
+ return `import ${type}{ ${local === namespace ? local : `${namespace} as ${local}`} } ${from(next)}`;
1557
+ }
1558
+ if (!bindings || ts.isNamespaceExport(bindings)) return null;
1559
+ /** @type {string[]} */
1560
+ const kept = [];
1561
+ /** @type {string[]} */
1562
+ const values = [];
1563
+ /** @type {string[]} */
1564
+ const types = [];
1565
+ let renamed = false;
1566
+ for (const element of bindings.elements) {
1567
+ const imported = (element.propertyName ?? element.name).text;
1568
+ const local = element.name.text;
1569
+ const name = mapPackageExport(module, imported);
1570
+ if (name === null) {
1571
+ this.note(RULE.binding, 'error', element, missingExport(module, imported));
1572
+ kept.push(element.getText(this.sf));
1573
+ continue;
1574
+ }
1575
+ renamed ||= name !== imported;
1576
+ if (namespace === null) {
1577
+ values.push(
1578
+ `${element.isTypeOnly ? 'type ' : ''}${name === local ? name : `${name} as ${local}`}`,
1579
+ );
1580
+ } else if (RADIX_TYPES.has(name)) {
1581
+ types.push(`type ${local} = ${this.require(next, namespace, true)}.${name};`);
1582
+ } else {
1583
+ values.push(name === local ? name : `${name}: ${local}`);
1584
+ }
1585
+ }
1586
+ if (namespace === null && kept.length === 0 && !renamed) return null;
1587
+ this.count(RULE.import);
1588
+ const lines =
1589
+ kept.length > 0 ? [`${keyword} ${type}{ ${kept.join(', ')} } ${from(module)}`] : [];
1590
+ if (values.length > 0) {
1591
+ lines.push(
1592
+ namespace === null
1593
+ ? `${keyword} ${type}{ ${values.join(', ')} } ${from(next)}`
1594
+ : `const { ${values.join(', ')} } = ${this.require(next, namespace, false)};`,
1595
+ );
1596
+ }
1597
+ return [...lines, ...types].join('\n');
1598
+ }
1599
+
1600
+ /**
1601
+ * `DialogPrimitive.DialogTitle`, a member of a ported package's namespace
1602
+ * import, as its port spells it.
1603
+ *
1604
+ * @param {ts.Node} namespace
1605
+ * @param {ts.MemberName} member
1606
+ * @param {Severity} severity of a member the port lacks
1607
+ */
1608
+ rewritePackageMember(namespace, member, severity) {
1609
+ const entry = this.importOf(namespace);
1610
+ if (!entry?.namespace) return null;
1611
+ const name = mapPackageExport(entry.module, member.text);
1612
+ if (name === member.text || this.resolve(entry.module) === null) return null;
1613
+ if (name === null) {
1614
+ if (!ts.isJsxClosingElement(member.parent.parent)) {
1615
+ this.note(RULE.binding, severity, member, missingExport(entry.module, member.text));
1616
+ }
1617
+ return null;
1618
+ }
1619
+ this.count(RULE.import);
1620
+ return `${entry.local}.${name}`;
1621
+ }
1622
+
1623
+ /** @param {ts.ExportDeclaration} node */
1624
+ rewriteReexport(node) {
1625
+ const module = /** @type {ts.StringLiteral} */ (node.moduleSpecifier).text;
1626
+ const mapped = REACT_MODULES[module];
1627
+ if (mapped) {
1628
+ this.count(RULE.import);
1629
+ return this.replaceSpecifier(
1630
+ node,
1631
+ /** @type {ts.Expression} */ (node.moduleSpecifier),
1632
+ mapped,
1633
+ );
1634
+ }
1635
+ return (
1636
+ this.rewritePackageNames(node, module) ??
1637
+ this.rewriteSpecifier(node, /** @type {ts.Expression} */ (node.moduleSpecifier))
1638
+ );
1639
+ }
1640
+
1641
+ /**
1642
+ * @param {ts.Node} node
1643
+ * @param {ts.Expression} specifier
1644
+ */
1645
+ rewriteSpecifier(node, specifier) {
1646
+ if (!ts.isStringLiteral(specifier)) return null;
1647
+ const next = this.resolve(specifier.text);
1648
+ if (next === null || next === specifier.text) return null;
1649
+ const namespace = radixNamespace(specifier.text);
1650
+ if (namespace !== null) {
1651
+ // A re-export, `import()`, or type of the package would be the whole binding.
1652
+ this.note(
1653
+ RULE.binding,
1654
+ 'error',
1655
+ node,
1656
+ `\`@octanejs/radix\` serves \`${specifier.text}\` as its \`${namespace}\` namespace; read it from \`import { ${namespace} } from '@octanejs/radix'\`.`,
1657
+ );
1658
+ return null;
1659
+ }
1660
+ this.count(RULE.import);
1661
+ return this.replaceSpecifier(node, specifier, next);
1662
+ }
1663
+
1664
+ /**
1665
+ * The new spelling of an import specifier, or null to keep it.
1666
+ *
1667
+ * @param {string} specifier
1668
+ */
1669
+ resolve(specifier) {
1670
+ let next = this.resolved.get(specifier);
1671
+ if (next === undefined) {
1672
+ next = this.options.resolveSpecifier?.(specifier) ?? null;
1673
+ this.resolved.set(specifier, next);
1674
+ }
1675
+ return next;
1676
+ }
1677
+
1678
+ /**
1679
+ * `declare module 'react' { namespace JSX { … } }` types custom elements,
1680
+ * which Octane reads from `octane/jsx-runtime`'s JSX namespace. Anything
1681
+ * else it adds patches React's own types, which Octane does not use.
1682
+ *
1683
+ * @param {ts.ModuleDeclaration} node
1684
+ * @param {ts.StringLiteral} specifier
1685
+ */
1686
+ rewriteAugmentation(node, specifier) {
1687
+ const statements = node.body && ts.isModuleBlock(node.body) ? node.body.statements : [];
1688
+ if (
1689
+ statements.length > 0 &&
1690
+ statements.every((s) => ts.isModuleDeclaration(s) && s.name.getText(this.sf) === 'JSX')
1691
+ ) {
1692
+ this.count(RULE.import);
1693
+ this.augments = true;
1694
+ return this.replaceSpecifier(node, specifier, 'octane/jsx-runtime');
1695
+ }
1696
+ this.note(
1697
+ RULE.unsupported,
1698
+ 'warning',
1699
+ node,
1700
+ `This augments React's own types, which Octane does not read; add what it declares to Octane's.`,
1701
+ );
1702
+ return null;
1703
+ }
1704
+
1705
+ /**
1706
+ * @param {ts.Node} node
1707
+ * @param {ts.Expression} specifier
1708
+ * @param {string} next
1709
+ */
1710
+ replaceSpecifier(node, specifier, next) {
1711
+ const quote = this.source[specifier.getStart(this.sf)];
1712
+ return (
1713
+ this.span(node, node.getStart(this.sf), specifier.getStart(this.sf), PLAIN) +
1714
+ quote +
1715
+ next +
1716
+ quote +
1717
+ // The rest is emitted, not copied: `import('./x').T<import('react').U>`
1718
+ // has a nested specifier of its own.
1719
+ this.span(node, specifier.end, node.end, PLAIN)
1720
+ );
1721
+ }
1722
+
1723
+ /**
1724
+ * `import('react').ReactNode` in a type: the module, and a React type name
1725
+ * Octane spells differently, follow the same map as static imports.
1726
+ *
1727
+ * @param {ts.ImportTypeNode} node
1728
+ */
1729
+ rewriteImportType(node) {
1730
+ const argument = node.argument;
1731
+ if (!ts.isLiteralTypeNode(argument) || !ts.isStringLiteral(argument.literal)) return null;
1732
+ const specifier = argument.literal;
1733
+ const module = REACT_MODULES[specifier.text];
1734
+ if (module === undefined) return this.rewriteSpecifier(node, specifier);
1735
+ this.count(RULE.import);
1736
+ const qualifier = node.qualifier;
1737
+ const name = qualifier && ts.isIdentifier(qualifier) ? qualifier.text : null;
1738
+ const renamed = name === null ? null : mapQualifiedType(name);
1739
+ if (name !== null && renamed === null) {
1740
+ this.note(RULE.unsupported, 'warning', node, `Octane has no type \`${name}\`.`);
1741
+ }
1742
+ const quote = this.source[specifier.getStart(this.sf)];
1743
+ const head =
1744
+ this.span(node, node.getStart(this.sf), specifier.getStart(this.sf), PLAIN) +
1745
+ quote +
1746
+ module +
1747
+ quote;
1748
+ if (!qualifier || renamed === null || renamed === name) {
1749
+ return head + this.span(node, specifier.end, node.end, PLAIN);
1750
+ }
1751
+ return (
1752
+ head +
1753
+ this.source.slice(specifier.end, qualifier.getStart(this.sf)) +
1754
+ renamed +
1755
+ this.span(node, qualifier.end, node.end, PLAIN)
1756
+ );
1757
+ }
1758
+
1759
+ /**
1760
+ * Fill each React import placeholder. The first one carries every Octane
1761
+ * import the module needs, the module's own specifiers first; the others
1762
+ * disappear with their line.
1763
+ *
1764
+ * @param {string} code
1765
+ */
1766
+ finishImports(code) {
1767
+ /** @type {Map<string, Map<string, { name: string, local: string, typeOnly: boolean }>>} */
1768
+ const imports = new Map();
1769
+ const add = (
1770
+ /** @type {string} */ module,
1771
+ /** @type {string} */ name,
1772
+ /** @type {string} */ local,
1773
+ /** @type {boolean} */ typeOnly,
1774
+ ) => {
1775
+ let names = imports.get(module);
1776
+ if (!names) imports.set(module, (names = new Map()));
1777
+ const existing = names.get(`${name} ${local}`);
1778
+ if (existing) existing.typeOnly &&= typeOnly;
1779
+ else names.set(`${name} ${local}`, { name, local, typeOnly });
1780
+ };
1781
+ /** React specifiers with no Octane export stay on React, for a person. */
1782
+ const kept = new Map();
1783
+ for (const node of this.importSlots) {
1784
+ const module = /** @type {ts.StringLiteral} */ (node.moduleSpecifier).text;
1785
+ const clause = node.importClause;
1786
+ if (!clause) continue;
1787
+ const bindings = clause.namedBindings;
1788
+ const namespace =
1789
+ clause.name?.text ??
1790
+ (bindings && ts.isNamespaceImport(bindings) ? bindings.name.text : null);
1791
+ // Members the rewrite could not map keep the namespace alive.
1792
+ if (namespace && this.used.has(namespace)) add(REACT_MODULES[module], '*', namespace, false);
1793
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
1794
+ for (const element of bindings.elements) {
1795
+ const local = element.name.text;
1796
+ if (!this.used.has(local)) continue;
1797
+ const imported = (element.propertyName ?? element.name).text;
1798
+ const typeOnly = clause.isTypeOnly || element.isTypeOnly;
1799
+ const mapped = mapReactImport(module, imported, typeOnly);
1800
+ if (mapped) {
1801
+ // A name read only in types imports as a type, which bundlers elide.
1802
+ add(mapped.module, mapped.name, local, typeOnly || !this.valueUses.has(local));
1803
+ continue;
1804
+ }
1805
+ this.note(
1806
+ RULE.unsupported,
1807
+ 'error',
1808
+ element,
1809
+ UNSUPPORTED_VALUES[imported] ??
1810
+ `\`${imported}\` from '${module}' has no Octane equivalent.`,
1811
+ );
1812
+ const spec =
1813
+ (typeOnly ? 'type ' : '') + (imported === local ? local : `${imported} as ${local}`);
1814
+ kept.set(module, [...(kept.get(module) ?? []), spec]);
1815
+ }
1816
+ }
1817
+ for (const [module, names] of this.added) {
1818
+ for (const [name, { local, typeOnly }] of names) add(module, name, local, typeOnly);
1819
+ }
1820
+
1821
+ /** @type {string[]} */
1822
+ const lines = [];
1823
+ const quote = (/** @type {string} */ module) => this.quote + module + this.quote;
1824
+ for (const [module, names] of imports) {
1825
+ const specs = [...names.values()];
1826
+ for (const { name, local } of specs) {
1827
+ if (name === '*') lines.push(`import * as ${local} from ${quote(module)};`);
1828
+ }
1829
+ const named = specs.filter(({ name }) => name !== '*');
1830
+ if (named.length === 0) continue;
1831
+ const allTypes = named.every(({ typeOnly }) => typeOnly);
1832
+ const list = named.map(
1833
+ ({ name, local, typeOnly }) =>
1834
+ (typeOnly && !allTypes ? 'type ' : '') + (name === local ? name : `${name} as ${local}`),
1835
+ );
1836
+ lines.push(`import ${allTypes ? 'type ' : ''}{ ${list.join(', ')} } from ${quote(module)};`);
1837
+ }
1838
+ for (const [module, specs] of kept)
1839
+ lines.push(`import { ${specs.join(', ')} } from ${quote(module)};`);
1840
+
1841
+ // In a script, `declare module` declares the module instead of adding to
1842
+ // it: a module whose only import was `import 'react'` stays a module, and
1843
+ // a script with a retargeted augmentation becomes one.
1844
+ if (
1845
+ lines.length === 0 &&
1846
+ (this.importSlots.length > 0 || this.augments) &&
1847
+ !this.otherModuleSyntax()
1848
+ ) {
1849
+ lines.push('export {};');
1850
+ }
1851
+ if (this.importSlots.length === 0) {
1852
+ if (lines.length === 0) return code;
1853
+ const at = this.insertionPoint(code);
1854
+ return code.slice(0, at) + lines.join('\n') + '\n' + code.slice(at);
1855
+ }
1856
+ this.count(RULE.import);
1857
+ return code.replace(/\u0000IMPORT(\d+)\u0000(\r?\n)?/g, (_, index, newline) =>
1858
+ index === '0' && lines.length > 0 ? lines.join('\n') + (newline ?? '') : '',
1859
+ );
1860
+ }
1861
+
1862
+ /** Whether the module has an import or export besides its React imports. */
1863
+ otherModuleSyntax() {
1864
+ return this.sf.statements.some(
1865
+ (statement) =>
1866
+ (ts.isImportDeclaration(statement) && !this.importSlots.includes(statement)) ||
1867
+ ts.isImportEqualsDeclaration(statement) ||
1868
+ ts.isExportDeclaration(statement) ||
1869
+ ts.isExportAssignment(statement) ||
1870
+ (ts.canHaveModifiers(statement) &&
1871
+ ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)),
1872
+ );
1873
+ }
1874
+
1875
+ /**
1876
+ * Where new imports go when the module imported nothing from React: after
1877
+ * the directive prologue and any leading comments.
1878
+ *
1879
+ * @param {string} code
1880
+ */
1881
+ insertionPoint(code) {
1882
+ // Whole lines only: a shebang, blank lines, comments that end their
1883
+ // line, and directive lines. Anything inserted here starts a line, so
1884
+ // the Strong fallback can find its own directive line again. The
1885
+ // comment on an unported package's import stays with it.
1886
+ const prologue =
1887
+ /^(?:#![^\n]*\n)?(?:[ \t]*(?:\/\/(?! No Octane port of)[^\n]*|\/\*[\s\S]*?\*\/[ \t]*|(['"])use [a-z ]+\1;?[^\n]*)?\r?\n)*/.exec(
1888
+ code,
1889
+ );
1890
+ return prologue ? prologue[0].length : 0;
1891
+ }
1892
+
1893
+ /** @param {string} code */
1894
+ addStrongDirective(code) {
1895
+ this.count(RULE.strong);
1896
+ const at = this.insertionPoint(code);
1897
+ return code.slice(0, at) + '"use strong";\n' + (at === 0 ? '\n' : '') + code.slice(at);
1898
+ }
1899
+
1900
+ /** @param {string} code */
1901
+ addJsxPragma(code) {
1902
+ if (/@jsxImportSource\s+octane/.test(code)) return code;
1903
+ const replaced = code.replace(/@jsxImportSource\s+\S+/, '@jsxImportSource octane');
1904
+ return replaced !== code ? replaced : '/** @jsxImportSource octane */\n' + code;
1905
+ }
1906
+
1907
+ // ---------------------------------------------------------------- APIs
1908
+
1909
+ /** @param {ts.PropertyAccessExpression} node */
1910
+ rewriteMember(node) {
1911
+ // `<Ctx.Provider value>` is `<Ctx value>` in Octane, as in React 19.
1912
+ const tag = node.parent;
1913
+ const isTag =
1914
+ (ts.isJsxOpeningElement(tag) ||
1915
+ ts.isJsxClosingElement(tag) ||
1916
+ ts.isJsxSelfClosingElement(tag)) &&
1917
+ tag.tagName === node;
1918
+ // So is `const P = C.Provider`; a member of the provider (`C.Provider.x`)
1919
+ // or a write to it stays.
1920
+ const isValue =
1921
+ !isTag &&
1922
+ !(ts.isPropertyAccessExpression(tag) && tag.expression === node) &&
1923
+ !(ts.isBinaryExpression(tag) && tag.left === node);
1924
+ if (node.name.text === 'Provider' && (isTag || isValue) && this.isContext(node.expression)) {
1925
+ if (!ts.isJsxClosingElement(tag)) this.count(RULE.provider);
1926
+ return this.emit(node.expression, PLAIN);
1927
+ }
1928
+ const namespace = this.importOf(node.expression);
1929
+ if (namespace?.namespace && namespace.module in REACT_MODULES) {
1930
+ const name = node.name.text;
1931
+ const mapped = mapReactImport(namespace.module, name, false);
1932
+ if (!mapped) {
1933
+ this.used.add(namespace.local);
1934
+ this.note(
1935
+ RULE.unsupported,
1936
+ 'error',
1937
+ node,
1938
+ UNSUPPORTED_VALUES[name] ?? `\`${node.getText(this.sf)}\` has no Octane equivalent.`,
1939
+ );
1940
+ return null;
1941
+ }
1942
+ this.count(RULE.import);
1943
+ return this.require(mapped.module, mapped.name, false);
1944
+ }
1945
+ const member = this.rewritePackageMember(node.expression, node.name, 'error');
1946
+ if (member !== null) return member;
1947
+ // event.nativeEvent: Octane events are already native.
1948
+ if (node.name.text === 'nativeEvent' && this.isEventParameter(node.expression)) {
1949
+ this.count(RULE.eventObject);
1950
+ return this.emit(node.expression, PLAIN);
1951
+ }
1952
+ if (node.name.text === 'target' && this.targetsControl(node.expression)) {
1953
+ this.count(RULE.eventObject);
1954
+ return this.emit(node.expression, PLAIN) + '.currentTarget';
1955
+ }
1956
+ return null;
1957
+ }
1958
+
1959
+ /**
1960
+ * Whether `node` names a global namespace React's types declare, such as
1961
+ * `React` in `React.ReactNode` written without an import.
1962
+ *
1963
+ * @param {ts.EntityName} node
1964
+ * @param {string} name
1965
+ */
1966
+ isGlobalNamespace(node, name) {
1967
+ return (
1968
+ ts.isIdentifier(node) &&
1969
+ node.text === name &&
1970
+ !this.checker.resolveName(name, node, ts.SymbolFlags.Namespace, false)
1971
+ );
1972
+ }
1973
+
1974
+ /** @param {ts.QualifiedName} node */
1975
+ rewriteQualifiedType(node) {
1976
+ const member = this.rewritePackageMember(node.left, node.right, 'warning');
1977
+ if (member !== null) return member;
1978
+ const namespace = this.importOf(node.left);
1979
+ if (
1980
+ namespace
1981
+ ? !namespace.namespace || !(namespace.module in REACT_MODULES)
1982
+ : !this.isGlobalNamespace(node.left, 'React')
1983
+ ) {
1984
+ return null;
1985
+ }
1986
+ const name = mapQualifiedType(node.right.text);
1987
+ if (!name) {
1988
+ if (namespace) this.used.add(namespace.local);
1989
+ this.note(
1990
+ RULE.unsupported,
1991
+ 'warning',
1992
+ node,
1993
+ `Octane has no type \`${node.getText(this.sf)}\`.`,
1994
+ );
1995
+ return null;
1996
+ }
1997
+ this.count(RULE.import);
1998
+ return this.require('octane', name, true);
1999
+ }
2000
+
2001
+ /** @param {ts.TypeReferenceNode} node */
2002
+ rewriteTypeReference(node) {
2003
+ // The global `JSX` namespace React's types declared is Octane's export.
2004
+ const name = node.typeName;
2005
+ if (ts.isQualifiedName(name) && this.isGlobalNamespace(name.left, 'JSX')) {
2006
+ this.require('octane', 'JSX', true);
2007
+ }
2008
+ return null;
2009
+ }
2010
+
2011
+ /** @param {ts.CallExpression} node */
2012
+ rewriteCall(node) {
2013
+ if (node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0]) {
2014
+ const [specifier] = node.arguments;
2015
+ const mapped = ts.isStringLiteral(specifier) ? REACT_MODULES[specifier.text] : undefined;
2016
+ if (mapped === undefined) return this.rewriteSpecifier(node, specifier);
2017
+ this.count(RULE.import);
2018
+ return this.replaceSpecifier(node, specifier, mapped);
2019
+ }
2020
+ if (
2021
+ ts.isPropertyAccessExpression(node.expression) &&
2022
+ node.expression.name.text === 'render' &&
2023
+ node.arguments.length === 1 &&
2024
+ this.isRoot(node.expression.expression)
2025
+ ) {
2026
+ return this.rewriteRootRender(node, node.arguments[0]);
2027
+ }
2028
+ const callee = this.callee(node.expression);
2029
+ // An Octane hook without a list already means "inferred".
2030
+ if (!callee || callee.module === 'octane') return null;
2031
+ const name = callee.name;
2032
+ if (name === 'forwardRef') return this.rewriteForwardRef(node);
2033
+ if (name === 'render' || name === 'hydrate') return this.rewriteLegacyRoot(node, name);
2034
+ if (name === 'hydrateRoot' && node.arguments.length === 2) {
2035
+ return this.rewriteRootRender(node, node.arguments[1]);
2036
+ }
2037
+ if (
2038
+ (name === 'renderToString' || name === 'renderToStaticMarkup') &&
2039
+ callee.module.startsWith('react-dom/server') &&
2040
+ node.arguments.length === 1
2041
+ ) {
2042
+ // React returns the HTML; Octane returns `{ html, css }`.
2043
+ this.count(RULE.serverRender);
2044
+ return (
2045
+ (this.rewriteRootRender(node, node.arguments[0]) ??
2046
+ this.span(node, node.getStart(this.sf), node.end, PLAIN)) + '.html'
2047
+ );
2048
+ }
2049
+ if (name === 'flushSync') {
2050
+ this.note(
2051
+ RULE.flushSync,
2052
+ 'warning',
2053
+ node,
2054
+ "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.",
2055
+ );
2056
+ return null;
2057
+ }
2058
+ if (name in DEPENDENCY_HOOKS) return this.rewriteDependencies(node, name);
2059
+ return null;
2060
+ }
2061
+
2062
+ /**
2063
+ * React runs an effect or memo without a dependency list on every render.
2064
+ * Octane infers the list instead, so compatibility output passes `null` to
2065
+ * keep React's behavior. Strong output leaves it to the compiler, which is
2066
+ * what Strong asks for.
2067
+ *
2068
+ * @param {ts.CallExpression} node
2069
+ * @param {string} name
2070
+ */
2071
+ rewriteDependencies(node, name) {
2072
+ if (node.arguments.length !== DEPENDENCY_HOOKS[name]) return null;
2073
+ if (this.strong) {
2074
+ this.note(
2075
+ RULE.deps,
2076
+ 'info',
2077
+ node,
2078
+ `\`${name}\` had no dependency list, so React ran it on every render; Strong infers its dependencies.`,
2079
+ );
2080
+ return null;
2081
+ }
2082
+ this.count(RULE.deps);
2083
+ const last = node.arguments[node.arguments.length - 1];
2084
+ return (
2085
+ this.span(node, node.getStart(this.sf), last.end, PLAIN) +
2086
+ ', null' +
2087
+ this.source.slice(last.end, node.end)
2088
+ );
2089
+ }
2090
+
2091
+ /**
2092
+ * `forwardRef((props, ref) => …)` becomes the inner function with `ref`
2093
+ * read from props.
2094
+ *
2095
+ * @param {ts.CallExpression} node
2096
+ */
2097
+ rewriteForwardRef(node) {
2098
+ const [render] = node.arguments;
2099
+ if (
2100
+ node.arguments.length !== 1 ||
2101
+ !(ts.isArrowFunction(render) || ts.isFunctionExpression(render)) ||
2102
+ render.parameters.length > 2
2103
+ ) {
2104
+ this.note(
2105
+ RULE.forwardRef,
2106
+ 'error',
2107
+ node,
2108
+ 'Unwrap this `forwardRef`: refs are ordinary props in Octane.',
2109
+ );
2110
+ return null;
2111
+ }
2112
+ this.count(RULE.forwardRef);
2113
+ const [props, ref] = render.parameters;
2114
+ const typeArgs = node.typeArguments;
2115
+ const refType = typeArgs?.[0] ? this.emit(typeArgs[0], PLAIN) : this.refTypeOf(ref);
2116
+ const propsNode = typeArgs?.[1] ?? props?.type;
2117
+ const propsType = propsNode ? this.emit(propsNode, PLAIN) : null;
2118
+ const refName = ref && ts.isIdentifier(ref.name) ? ref.name.text : null;
2119
+ const refBinding = refName === null ? null : refName === 'ref' ? 'ref' : `ref: ${refName}`;
2120
+
2121
+ // Splice `ref` into the props pattern in the pattern's own layout.
2122
+ let pattern;
2123
+ if (!props) pattern = refBinding ? `{ ${refBinding} }` : null;
2124
+ else if (refBinding === null) pattern = this.emit(props.name, PLAIN);
2125
+ else if (ts.isObjectBindingPattern(props.name)) {
2126
+ const elements = props.name.elements;
2127
+ const rest = elements.find((element) => element.dotDotDotToken);
2128
+ const last = elements[elements.length - 1];
2129
+ const multiline = this.source
2130
+ .slice(props.name.getStart(this.sf), props.name.end)
2131
+ .includes('\n');
2132
+ if (rest) {
2133
+ const separator = multiline ? `,\n${this.indentOf(rest)}` : ', ';
2134
+ pattern =
2135
+ this.span(props.name, props.name.getStart(this.sf), rest.getStart(this.sf), PLAIN) +
2136
+ refBinding +
2137
+ separator +
2138
+ this.span(props.name, rest.getStart(this.sf), props.name.end, PLAIN);
2139
+ } else if (last) {
2140
+ const separator = multiline ? `,\n${this.indentOf(last)}` : ', ';
2141
+ pattern =
2142
+ this.span(props.name, props.name.getStart(this.sf), last.end, PLAIN) +
2143
+ separator +
2144
+ refBinding +
2145
+ this.source.slice(last.end, props.name.end);
2146
+ } else pattern = `{ ${refBinding} }`;
2147
+ } else if (ts.isIdentifier(props.name) && props.name.text !== '_') {
2148
+ pattern = `{ ${refBinding}, ...${props.name.text} }`;
2149
+ } else {
2150
+ pattern = `{ ${refBinding} }`;
2151
+ }
2152
+
2153
+ let annotation = '';
2154
+ if (this.isTypeScript() && (propsType || refType)) {
2155
+ const refProp = refType ? `{ ref?: ${this.require('octane', 'Ref', true)}<${refType}> }` : '';
2156
+ annotation = ': ' + [propsType, refProp].filter(Boolean).join(' & ');
2157
+ }
2158
+ // Keep the parameter list's layout: the props parameter is replaced in
2159
+ // place and the ref parameter goes with the comma before it.
2160
+ const list = render.parameters;
2161
+ let parameters;
2162
+ if (pattern === null) parameters = '';
2163
+ else if (!props) parameters = pattern + annotation;
2164
+ else {
2165
+ parameters =
2166
+ this.source.slice(list.pos, props.getStart(this.sf)) +
2167
+ pattern +
2168
+ annotation +
2169
+ this.source.slice(ref ? ref.end : props.end, list.end);
2170
+ }
2171
+ this.parameters.set(render, parameters);
2172
+ return this.emit(render, PLAIN);
2173
+ }
2174
+
2175
+ /**
2176
+ * A function's text up to its body, with any parameters a rule replaced.
2177
+ *
2178
+ * @param {ts.SignatureDeclaration & { body?: ts.Node }} node
2179
+ * @param {number} end
2180
+ */
2181
+ head(node, end) {
2182
+ const parameters = this.parameters.get(node);
2183
+ if (parameters === undefined) return this.span(node, node.getStart(this.sf), end, PLAIN);
2184
+ return (
2185
+ this.span(node, node.getStart(this.sf), node.parameters.pos, PLAIN) +
2186
+ parameters +
2187
+ this.span(node, node.parameters.end, end, PLAIN)
2188
+ );
2189
+ }
2190
+
2191
+ /** @param {ts.ParameterDeclaration | undefined} ref */
2192
+ refTypeOf(ref) {
2193
+ const type = ref?.type;
2194
+ if (type && ts.isTypeReferenceNode(type) && type.typeArguments?.length === 1) {
2195
+ return this.emit(type.typeArguments[0], PLAIN);
2196
+ }
2197
+ return null;
2198
+ }
2199
+
2200
+ isTypeScript() {
2201
+ return /\.[cm]?tsx?$/.test(this.filename);
2202
+ }
2203
+
2204
+ /**
2205
+ * @param {ts.CallExpression} node
2206
+ * @param {'render' | 'hydrate'} name
2207
+ */
2208
+ rewriteLegacyRoot(node, name) {
2209
+ const [element, container, callback] = node.arguments;
2210
+ if (!element || !container) return null;
2211
+ if (callback) {
2212
+ this.note(
2213
+ RULE.legacyRoot,
2214
+ 'warning',
2215
+ node,
2216
+ 'The legacy render callback was dropped; run it from an effect.',
2217
+ );
2218
+ }
2219
+ this.count(RULE.legacyRoot);
2220
+ const elementText = this.rootComponent(element) ?? this.emit(element, PLAIN);
2221
+ const containerText = this.emit(container, PLAIN);
2222
+ return name === 'render'
2223
+ ? `${this.require('octane', 'createRoot', false)}(${containerText}).render(${elementText})`
2224
+ : `${this.require('octane', 'hydrateRoot', false)}(${containerText}, ${elementText})`;
2225
+ }
2226
+
2227
+ /**
2228
+ * Whether `node` is a root `createRoot` made: the call itself, or a
2229
+ * `const` bound to it.
2230
+ *
2231
+ * @param {ts.Expression} node
2232
+ */
2233
+ isRoot(node) {
2234
+ node = skipParens(node);
2235
+ const value = ts.isIdentifier(node) ? this.constValue(node) : node;
2236
+ return (
2237
+ !!value && ts.isCallExpression(value) && this.calleeName(value.expression) === 'createRoot'
2238
+ );
2239
+ }
2240
+
2241
+ /**
2242
+ * `root.render(<App a={1} />)` and `root.render(createElement(App, props))`
2243
+ * are `root.render(App, props)`, which mounts the component without an
2244
+ * element: the generic element renderer stays out of the bundle. So are
2245
+ * `hydrateRoot(c, <App />)` and the server renderers' element argument.
2246
+ *
2247
+ * @param {ts.CallExpression} node
2248
+ * @param {ts.Expression} argument the element, the call's last argument
2249
+ */
2250
+ rewriteRootRender(node, argument) {
2251
+ const component = this.rootComponent(argument);
2252
+ if (component === null) return null;
2253
+ this.count(RULE.rootRender);
2254
+ return (
2255
+ this.span(node, node.getStart(this.sf), argument.getStart(this.sf), PLAIN) +
2256
+ component +
2257
+ this.span(node, argument.end, node.end, PLAIN)
2258
+ );
2259
+ }
2260
+
2261
+ /**
2262
+ * `App` or `App, props` for an element of a component with no key, ref,
2263
+ * or children, through a `<StrictMode>` wrapper, else null.
2264
+ *
2265
+ * @param {ts.Expression} expression
2266
+ * @returns {string | null}
2267
+ */
2268
+ rootComponent(expression) {
2269
+ let node = skipParens(expression);
2270
+ if (ts.isJsxElement(node) && this.calleeName(node.openingElement.tagName) === 'StrictMode') {
2271
+ const children = node.children.filter(
2272
+ (child) => !(ts.isJsxText(child) && child.containsOnlyTriviaWhiteSpaces),
2273
+ );
2274
+ if (children.length !== 1 || !isJsx(children[0])) return null;
2275
+ node = /** @type {ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment} */ (children[0]);
2276
+ }
2277
+ if (ts.isJsxSelfClosingElement(node)) {
2278
+ const tag = node.tagName;
2279
+ if (!ts.isIdentifier(tag) && !ts.isPropertyAccessExpression(tag)) return null;
2280
+ if (!isComponentName(tag.getText(this.sf).split('.').pop() ?? '')) return null;
2281
+ /** @type {string[]} */
2282
+ const props = [];
2283
+ for (const property of node.attributes.properties) {
2284
+ if (ts.isJsxSpreadAttribute(property)) {
2285
+ props.push(`...${this.emit(property.expression, PLAIN)}`);
2286
+ continue;
2287
+ }
2288
+ const name = property.name.getText(this.sf);
2289
+ if (name === 'key' || name === 'ref') return null;
2290
+ const key = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
2291
+ const value = property.initializer;
2292
+ if (!value) props.push(`${key}: true`);
2293
+ else if (ts.isStringLiteral(value)) props.push(`${key}: ${value.getText(this.sf)}`);
2294
+ else if (ts.isJsxExpression(value) && value.expression)
2295
+ props.push(`${key}: ${this.emit(value.expression, PLAIN)}`);
2296
+ else return null;
2297
+ }
2298
+ const type = this.emit(tag, PLAIN);
2299
+ return props.length === 0 ? type : `${type}, { ${props.join(', ')} }`;
2300
+ }
2301
+ if (ts.isCallExpression(node) && this.calleeName(node.expression) === 'createElement') {
2302
+ const [type, props, ...children] = node.arguments;
2303
+ if (!type || children.length > 0) return null;
2304
+ if (!(ts.isIdentifier(type) || ts.isPropertyAccessExpression(type))) return null;
2305
+ if (!isComponentName(type.getText(this.sf).split('.').pop() ?? '')) return null;
2306
+ const text = this.emit(type, PLAIN);
2307
+ return !props || isNullish(props) ? text : `${text}, ${this.emit(props, PLAIN)}`;
2308
+ }
2309
+ return null;
2310
+ }
2311
+
2312
+ /** @param {ts.ExpressionStatement} node */
2313
+ rewriteStatement(node) {
2314
+ const call = node.expression;
2315
+ if (
2316
+ ts.isCallExpression(call) &&
2317
+ call.arguments.length === 0 &&
2318
+ ts.isPropertyAccessExpression(call.expression) &&
2319
+ call.expression.name.text === 'persist' &&
2320
+ this.isEventParameter(call.expression.expression)
2321
+ ) {
2322
+ // Octane never pools events, so there is nothing to persist.
2323
+ this.count(RULE.eventObject);
2324
+ return DROP;
2325
+ }
2326
+ return null;
2327
+ }
2328
+
2329
+ /**
2330
+ * The parameter `node` refers to, with its function.
2331
+ *
2332
+ * @param {ts.Node} node
2333
+ * @returns {{ fn: ts.SignatureDeclaration, param: ts.ParameterDeclaration } | null}
2334
+ */
2335
+ parameterOf(node) {
2336
+ if (!ts.isIdentifier(node)) return null;
2337
+ const param = this.declarationOf(node);
2338
+ if (!param || !ts.isParameter(param)) return null;
2339
+ return { fn: /** @type {ts.SignatureDeclaration} */ (param.parent), param };
2340
+ }
2341
+
2342
+ /** @param {ts.Node} node */
2343
+ isEventParameter(node) {
2344
+ const found = this.parameterOf(node);
2345
+ if (!found) return false;
2346
+ const type = found.param.type;
2347
+ if (type && ts.isTypeReferenceNode(type) && /Event$/.test(type.typeName.getText(this.sf))) {
2348
+ return true;
2349
+ }
2350
+ return this.handlerAttribute(found.fn) !== null;
2351
+ }
2352
+
2353
+ /**
2354
+ * The `on*` attribute an inline handler is passed to.
2355
+ *
2356
+ * @param {ts.Node} fn
2357
+ */
2358
+ handlerAttribute(fn) {
2359
+ const container = fn.parent;
2360
+ if (!container || !ts.isJsxExpression(container)) return null;
2361
+ const attribute = container.parent;
2362
+ return ts.isJsxAttribute(attribute) && /^on[A-Z]/.test(attribute.name.getText(this.sf))
2363
+ ? attribute
2364
+ : null;
2365
+ }
2366
+
2367
+ /**
2368
+ * Whether `event.target` is the form control the handler is attached to, so
2369
+ * it can read Octane's typed `currentTarget` instead. Octane types events as
2370
+ * the native `Event`, whose `target` is an untyped `EventTarget`.
2371
+ *
2372
+ * @param {ts.Node} node
2373
+ */
2374
+ targetsControl(node) {
2375
+ const found = this.parameterOf(node);
2376
+ if (!found) return false;
2377
+ // Unannotated, the project's types still name a handler a component
2378
+ // passes on to a control: `<Input onChange={(e) => …}>`.
2379
+ const inferred = found.param.type ? null : this.projectType(found.param);
2380
+ const type =
2381
+ found.param.type?.getText(this.sf) ??
2382
+ (inferred ? inferred.checker.typeToString(inferred.type) : '');
2383
+ if (
2384
+ /(ChangeEvent|FormEvent)<\s*(?:HTML(?:Input|TextArea|Select)Element\s*[|,]?\s*)+>$/.test(type)
2385
+ )
2386
+ return true;
2387
+ const attribute = this.handlerAttribute(found.fn);
2388
+ if (!attribute || !/^on(Change|Input|Focus|Blur)/.test(attribute.name.getText(this.sf)))
2389
+ return false;
2390
+ const tag = attribute.parent.parent.tagName.getText(this.sf);
2391
+ return tag === 'input' || tag === 'textarea' || tag === 'select';
2392
+ }
2393
+
2394
+ /** @param {ts.ClassDeclaration | ts.ClassExpression} node */
2395
+ checkClass(node) {
2396
+ const base = node.heritageClauses?.find(
2397
+ (clause) => clause.token === ts.SyntaxKind.ExtendsKeyword,
2398
+ )?.types[0]?.expression;
2399
+ const name = base && this.calleeName(base);
2400
+ if (name !== 'Component' && name !== 'PureComponent') return;
2401
+ const boundary = node.members.some(
2402
+ (member) =>
2403
+ member.name &&
2404
+ /^(componentDidCatch|getDerivedStateFromError)$/.test(member.name.getText(this.sf)),
2405
+ );
2406
+ this.note(
2407
+ RULE.classComponent,
2408
+ 'error',
2409
+ node,
2410
+ boundary
2411
+ ? `Error boundary \`${node.name?.text ?? 'class'}\` needs a rewrite: use \`@try { … } @catch (error) { … }\` or Octane's \`ErrorBoundary\`.`
2412
+ : `Class component \`${node.name?.text ?? 'class'}\` needs a rewrite as a function component.`,
2413
+ );
2414
+ }
2415
+
2416
+ /** @param {ts.BinaryExpression} node */
2417
+ checkDefaultProps(node) {
2418
+ if (
2419
+ node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
2420
+ ts.isPropertyAccessExpression(node.left) &&
2421
+ node.left.name.text === 'defaultProps'
2422
+ ) {
2423
+ this.note(
2424
+ RULE.defaultProps,
2425
+ 'warning',
2426
+ node,
2427
+ 'Function components ignore `defaultProps`; move the defaults into the props destructuring.',
2428
+ );
2429
+ }
2430
+ }
2431
+
2432
+ // ---------------------------------------------------------------- JSX
2433
+
2434
+ /** @param {ts.JsxAttributes} node */
2435
+ rewriteAttributes(node) {
2436
+ const element = node.parent;
2437
+ const tag = element.tagName.getText(this.sf);
2438
+ const intrinsic = /^[a-z]/.test(tag);
2439
+ const spread = node.properties.some(ts.isJsxSpreadAttribute);
2440
+ const attributes = node.properties;
2441
+
2442
+ let out = '';
2443
+ let cursor = node.getStart(this.sf);
2444
+ for (const attribute of attributes) {
2445
+ const start = attribute.getStart(this.sf);
2446
+ if (this.removed.has(attribute)) {
2447
+ // Drop the attribute and the whitespace on one side of it.
2448
+ if (out === '' && cursor === start) {
2449
+ cursor =
2450
+ attribute.end +
2451
+ (this.source.slice(attribute.end).length -
2452
+ this.source.slice(attribute.end).trimStart().length);
2453
+ if (attribute === attributes[attributes.length - 1]) cursor = attribute.end;
2454
+ } else {
2455
+ out = out.replace(/\s+$/, '') + this.source.slice(cursor, start).replace(/\s+$/, '');
2456
+ cursor = attribute.end;
2457
+ }
2458
+ continue;
2459
+ }
2460
+ out += this.source.slice(cursor, start);
2461
+ cursor = attribute.end;
2462
+ if (ts.isJsxSpreadAttribute(attribute) && this.changeSpreads.has(attribute)) {
2463
+ // On the spread's own line when it has one.
2464
+ this.count(RULE.nativeChange);
2465
+ const line = this.source.slice(this.source.lastIndexOf('\n', start - 1), start);
2466
+ out += 'onInput={onChange}' + (/^\n[ \t]*$/.test(line) ? line : ' ');
2467
+ }
2468
+ if (!ts.isJsxAttribute(attribute) || !intrinsic) {
2469
+ out += this.emit(attribute, PLAIN);
2470
+ continue;
2471
+ }
2472
+ const name = attribute.name.getText(this.sf);
2473
+ if (
2474
+ name === 'className' &&
2475
+ this.target === 'tsrx' &&
2476
+ !attributeOf(element, 'class') &&
2477
+ !spread
2478
+ ) {
2479
+ this.count(RULE.className);
2480
+ out += 'class' + this.emitInitializer(attribute);
2481
+ } else if ((name === 'onChange' || name === 'onChangeCapture') && this.isTextEntry(element)) {
2482
+ const input = name === 'onChange' ? 'onInput' : 'onInputCapture';
2483
+ if (attributeOf(element, input)) {
2484
+ this.note(
2485
+ RULE.nativeChange,
2486
+ 'warning',
2487
+ attribute,
2488
+ `\`${name}\` beside \`${input}\` now fires on commit (blur), not per edit.`,
2489
+ );
2490
+ out += this.emit(attribute, PLAIN);
2491
+ } else {
2492
+ this.count(RULE.nativeChange);
2493
+ out += input + this.emitInitializer(attribute);
2494
+ }
2495
+ } else {
2496
+ out += this.emit(attribute, PLAIN);
2497
+ }
2498
+ }
2499
+ return out + this.source.slice(cursor, node.end);
2500
+ }
2501
+
2502
+ /** @param {ts.JsxAttribute} attribute */
2503
+ emitInitializer(attribute) {
2504
+ if (!attribute.initializer) return '';
2505
+ return (
2506
+ this.source.slice(attribute.name.end, attribute.initializer.getStart(this.sf)) +
2507
+ this.emit(attribute.initializer, PLAIN)
2508
+ );
2509
+ }
2510
+
2511
+ /**
2512
+ * Whether `element` is a text-entry control, where React's `onChange` fires
2513
+ * per edit and the native `change` fires on commit.
2514
+ *
2515
+ * @param {ts.JsxOpeningLikeElement} element
2516
+ */
2517
+ isTextEntry(element) {
2518
+ const tag = element.tagName.getText(this.sf);
2519
+ if (tag === 'textarea') return true;
2520
+ if (tag !== 'input') return false;
2521
+ const type = attributeOf(element, 'type');
2522
+ if (!type) return true;
2523
+ const value = type.initializer;
2524
+ if (value && ts.isStringLiteral(value)) return TEXT_INPUT_TYPES.has(value.text);
2525
+ this.note(
2526
+ RULE.nativeChange,
2527
+ 'warning',
2528
+ element,
2529
+ 'This `<input>` has a dynamic `type`; if it can be a text field, use `onInput` for per-edit updates.',
2530
+ );
2531
+ return false;
2532
+ }
2533
+
2534
+ /**
2535
+ * @param {ts.JsxElement} node
2536
+ * @param {Context} ctx
2537
+ */
2538
+ rewriteElement(node, ctx) {
2539
+ if (this.bare.has(node)) {
2540
+ return (
2541
+ '<>' +
2542
+ this.span(node, node.openingElement.end, node.closingElement.getStart(this.sf), ctx) +
2543
+ '</>'
2544
+ );
2545
+ }
2546
+ const tag = node.openingElement.tagName;
2547
+ // A `descriptorChildren` component receives its children as elements, as
2548
+ // in React; `@if` or `@for` there would hand it a fragment instead.
2549
+ const declaration = ts.isIdentifier(tag) ? this.declarationOf(tag) : null;
2550
+ if (
2551
+ declaration &&
2552
+ this.descriptorComponents.has(/** @type {ts.VariableDeclaration} */ (declaration))
2553
+ ) {
2554
+ return this.span(node, node.getStart(this.sf), node.end, PLAIN);
2555
+ }
2556
+ const name = this.calleeName(tag);
2557
+ if (name === 'StrictMode') {
2558
+ // Octane's StrictMode is a pass-through wrapper.
2559
+ this.count(RULE.strictMode);
2560
+ return this.emitChildren(node, ctx);
2561
+ }
2562
+ if (name === 'Suspense' && ctx.template) return this.rewriteSuspense(node);
2563
+ if (ts.isPropertyAccessExpression(tag) && this.isContext(tag.expression)) {
2564
+ if (tag.name.text === 'Consumer') return this.rewriteConsumer(node, ctx);
2565
+ }
2566
+ return null;
2567
+ }
2568
+
2569
+ /**
2570
+ * Whether `node` is a React context, by where it comes from: a
2571
+ * `createContext` call here, or an export the project knows is one. Only
2572
+ * a package's export, which the codemod cannot see, is judged by its name.
2573
+ *
2574
+ * @param {ts.Expression} node
2575
+ */
2576
+ isContext(node) {
2577
+ if (!ts.isIdentifier(node)) return false;
2578
+ const declaration = this.declarationOf(node);
2579
+ if (declaration && ts.isVariableDeclaration(declaration)) {
2580
+ return !!declaration.initializer && this.createsContext(declaration.initializer);
2581
+ }
2582
+ const entry = declaration ? this.imports.get(declaration) : null;
2583
+ if (!entry || entry.namespace) return false;
2584
+ const name = entry.imported === 'default' ? entry.local : entry.imported;
2585
+ return this.options.isContext?.(entry.module, entry.imported) ?? /Context$/.test(name);
2586
+ }
2587
+
2588
+ /**
2589
+ * Whether `node` evaluates to a `createContext` result on every branch.
2590
+ *
2591
+ * @param {ts.Expression} node
2592
+ * @returns {boolean}
2593
+ */
2594
+ createsContext(node) {
2595
+ node = skipParens(node);
2596
+ if (ts.isConditionalExpression(node)) {
2597
+ return this.createsContext(node.whenTrue) && this.createsContext(node.whenFalse);
2598
+ }
2599
+ return ts.isCallExpression(node) && this.calleeName(node.expression) === 'createContext';
2600
+ }
2601
+
2602
+ /**
2603
+ * `typeof children === 'function'` also holds for a compiled children
2604
+ * block, which renders through Octane rather than being called, so the
2605
+ * check also asks `isChildrenBlock`.
2606
+ *
2607
+ * @param {ts.BinaryExpression} node
2608
+ */
2609
+ rewriteRenderProp(node) {
2610
+ const op = node.operatorToken.kind;
2611
+ if (op !== ts.SyntaxKind.EqualsEqualsEqualsToken && op !== ts.SyntaxKind.EqualsEqualsToken) {
2612
+ return null;
2613
+ }
2614
+ if (!ts.isTypeOfExpression(node.left) || !ts.isStringLiteral(node.right)) return null;
2615
+ const operand = skipParens(node.left.expression);
2616
+ const name = ts.isIdentifier(operand)
2617
+ ? operand.text
2618
+ : ts.isPropertyAccessExpression(operand)
2619
+ ? operand.name.text
2620
+ : null;
2621
+ if (node.right.text !== 'function' || name !== 'children') return null;
2622
+ const parent = node.parent;
2623
+ if (ts.isBinaryExpression(parent) && /\bisChildrenBlock\(/.test(parent.getText(this.sf))) {
2624
+ return null;
2625
+ }
2626
+ this.count(RULE.renderProp);
2627
+ const check = this.require('octane', 'isChildrenBlock', false);
2628
+ return `(${this.span(node, node.getStart(this.sf), node.end, PLAIN)} && !${check}(${this.emit(operand, PLAIN)}))`;
2629
+ }
2630
+
2631
+ /**
2632
+ * The children of `node` as one renderable: the sole element, or a
2633
+ * fragment around several.
2634
+ *
2635
+ * @param {ts.JsxElement | ts.JsxFragment} node
2636
+ * @param {Context} ctx
2637
+ */
2638
+ emitChildren(node, ctx) {
2639
+ const children = contentOf(node);
2640
+ if (children.length === 1 && isJsx(children[0])) return this.emit(children[0], ctx);
2641
+ const first = node.children[0];
2642
+ const last = node.children[node.children.length - 1];
2643
+ if (!first) return '<></>';
2644
+ return '<>' + this.span(node, first.pos, last.end, ctx) + '</>';
2645
+ }
2646
+
2647
+ /**
2648
+ * `<Ctx.Consumer>{(value) => …}</Ctx.Consumer>` reads the context in a
2649
+ * nested template scope, where a hook is legal.
2650
+ *
2651
+ * @param {ts.JsxElement} node
2652
+ * @param {Context} ctx
2653
+ */
2654
+ rewriteConsumer(node, ctx) {
2655
+ const tag = /** @type {ts.PropertyAccessExpression} */ (node.openingElement.tagName);
2656
+ const children = contentOf(node);
2657
+ const render =
2658
+ children.length === 1 && ts.isJsxExpression(children[0]) ? children[0].expression : null;
2659
+ const fn = render && skipParens(render);
2660
+ if (
2661
+ !ctx.template ||
2662
+ !fn ||
2663
+ !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) ||
2664
+ fn.parameters.length !== 1 ||
2665
+ ts.isBlock(fn.body)
2666
+ ) {
2667
+ this.note(
2668
+ RULE.consumer,
2669
+ 'error',
2670
+ node,
2671
+ '`Context.Consumer` does not exist in Octane; read the context with `use(Context)`.',
2672
+ );
2673
+ return null;
2674
+ }
2675
+ this.count(RULE.consumer);
2676
+ const useContext = this.require('octane', 'useContext', false);
2677
+ const param = this.emit(fn.parameters[0].name, PLAIN);
2678
+ const body = skipParens(fn.body);
2679
+ const output = isJsx(body) ? this.emit(body, TEMPLATE) : `<>{${this.emit(body, PLAIN)}}</>`;
2680
+ return `@{ const ${param} = ${useContext}(${this.emit(tag.expression, PLAIN)}); ${output} }`;
2681
+ }
2682
+
2683
+ /**
2684
+ * `<Suspense fallback={f}>…</Suspense>` is the template boundary
2685
+ * `@try { … } @pending { f }`.
2686
+ *
2687
+ * @param {ts.JsxElement} node
2688
+ */
2689
+ rewriteSuspense(node) {
2690
+ const attributes = node.openingElement.attributes.properties.filter(
2691
+ (a) => !this.removed.has(a),
2692
+ );
2693
+ const fallback = attributes[0];
2694
+ if (
2695
+ attributes.length !== 1 ||
2696
+ !ts.isJsxAttribute(fallback) ||
2697
+ fallback.name.getText(this.sf) !== 'fallback' ||
2698
+ !fallback.initializer
2699
+ ) {
2700
+ return null;
2701
+ }
2702
+ let pending;
2703
+ const value = fallback.initializer;
2704
+ if (ts.isStringLiteral(value)) pending = `<>{${value.getText(this.sf)}}</>`;
2705
+ else if (ts.isJsxExpression(value) && value.expression) {
2706
+ const expression = skipParens(value.expression);
2707
+ if (isJsx(expression)) pending = this.relative(this.emit(expression, TEMPLATE), expression);
2708
+ else if (isNullish(expression)) pending = '<></>';
2709
+ else pending = `<>{${this.emit(expression, PLAIN)}}</>`;
2710
+ } else return null;
2711
+ this.count(RULE.try);
2712
+ const body = this.relative(this.emitChildren(node, TEMPLATE), node, this.indentUnit);
2713
+ return this.absolute(this.block('@try', body) + ' ' + this.block('@pending', pending), node);
2714
+ }
2715
+
2716
+ // Directive text is built relative to its first line: line 1 carries no
2717
+ // indentation and every later line is indented from that line's level.
2718
+ // `absolute` re-anchors it where it lands in the module.
2719
+
2720
+ /**
2721
+ * Source text emitted for `node`, re-based so `node`'s own line is level 0.
2722
+ *
2723
+ * @param {string} text
2724
+ * @param {ts.Node} node
2725
+ * @param {string} [deeper] how far inside `node`'s line the text's own
2726
+ * first line sat, such as the children of an element
2727
+ */
2728
+ relative(text, node, deeper = '') {
2729
+ const from = this.indentOf(node) + deeper;
2730
+ return text
2731
+ .split('\n')
2732
+ .map((line, i) => {
2733
+ if (i === 0) return line;
2734
+ if (line.trim() === '') return '';
2735
+ return line.startsWith(from) ? line.slice(from.length) : line.trimStart();
2736
+ })
2737
+ .join('\n');
2738
+ }
2739
+
2740
+ /**
2741
+ * @param {string} text relative text
2742
+ * @param {ts.Node} node the node it replaces
2743
+ */
2744
+ absolute(text, node) {
2745
+ const indent = this.indentOf(node);
2746
+ return text
2747
+ .split('\n')
2748
+ .map((line, i) => (i === 0 || line === '' ? line : indent + line))
2749
+ .join('\n');
2750
+ }
2751
+
2752
+ /**
2753
+ * `head { body }` on one line when the body fits on one, else with the body
2754
+ * on its own lines one level in.
2755
+ *
2756
+ * @param {string} head
2757
+ * @param {string} body relative text
2758
+ */
2759
+ block(head, body) {
2760
+ if (!body.includes('\n') && !body.startsWith('@') && head.length + body.length < 80) {
2761
+ return `${head} { ${body} }`;
2762
+ }
2763
+ const unit = this.indentUnit;
2764
+ const lines = body.split('\n').map((line) => (line === '' ? '' : unit + line));
2765
+ return `${head} {\n${lines.join('\n')}\n}`;
2766
+ }
2767
+
2768
+ /**
2769
+ * The text before `node` on its line.
2770
+ *
2771
+ * @param {ts.Node} node
2772
+ */
2773
+ linePrefix(node) {
2774
+ const start = node.getStart(this.sf);
2775
+ return this.source.slice(this.source.lastIndexOf('\n', start - 1) + 1, start);
2776
+ }
2777
+
2778
+ /** @param {ts.Node} node */
2779
+ indentOf(node) {
2780
+ const prefix = this.linePrefix(node);
2781
+ return prefix.slice(0, prefix.length - prefix.trimStart().length);
2782
+ }
2783
+
2784
+ /**
2785
+ * Template control flow for a JSX child hole.
2786
+ *
2787
+ * @param {ts.JsxExpression} node
2788
+ */
2789
+ rewriteHole(node) {
2790
+ if (!node.expression || node.dotDotDotToken) return null;
2791
+ const directive = this.directive(node.expression);
2792
+ if (directive === null) return this.textHole(node);
2793
+ // Comments the directive did not carry over sit before it, as JSX
2794
+ // comments, since this is a children position.
2795
+ const lost = this.lostComments(node.getStart(this.sf) + 1, node.end - 1, directive)
2796
+ .map((comment) => `{/* ${commentText(comment)} */}\n`)
2797
+ .join('');
2798
+ return this.absolute(lost + directive, node);
2799
+ }
2800
+
2801
+ /**
2802
+ * A child hole the module's types prove is a string, number, or bigint,
2803
+ * spelled as text so it compiles to a text binding rather than a
2804
+ * renderable hole. React renders those values as text too.
2805
+ *
2806
+ * @param {ts.JsxExpression} node
2807
+ */
2808
+ textHole(node) {
2809
+ const expression = /** @type {ts.Expression} */ (node.expression);
2810
+ if (!this.textTypes || isTextSpelling(expression)) return null;
2811
+ const kind = textKind(this.typeOf(expression));
2812
+ if (kind === 0) return null;
2813
+ this.count(RULE.text);
2814
+ const value = this.emit(expression, PLAIN);
2815
+ let text;
2816
+ if (kind === 1) {
2817
+ const bare =
2818
+ ts.isIdentifier(expression) ||
2819
+ ts.isPropertyAccessExpression(expression) ||
2820
+ ts.isElementAccessExpression(expression) ||
2821
+ ts.isCallExpression(expression) ||
2822
+ ts.isParenthesizedExpression(expression) ||
2823
+ ts.isNonNullExpression(expression);
2824
+ text = `${bare ? value : `(${value})`} as string`;
2825
+ } else if (
2826
+ this.declaresHere(this.checker.resolveName('String', node, ts.SymbolFlags.Value, false))
2827
+ ) {
2828
+ text = `\`\${${value}}\``;
2829
+ } else {
2830
+ text = `String(${value})`;
2831
+ }
2832
+ return (
2833
+ this.span(node, node.getStart(this.sf), expression.getStart(this.sf), PLAIN) +
2834
+ text +
2835
+ this.span(node, expression.end, node.end, PLAIN)
2836
+ );
2837
+ }
2838
+
2839
+ /**
2840
+ * The type of `node` in the project's program, which resolves imports and
2841
+ * packages, or null when the program does not have this module.
2842
+ *
2843
+ * @param {ts.Node} node
2844
+ * @returns {{ type: ts.Type, checker: ts.TypeChecker } | null}
2845
+ */
2846
+ projectType(node) {
2847
+ const types = this.options.types;
2848
+ if (types?.sourceFile.text !== this.source) return null;
2849
+ const same = nodeSpanning(types.sourceFile, node.getStart(this.sf), node.end);
2850
+ if (same?.kind !== node.kind) return null;
2851
+ return { type: types.checker.getTypeAtLocation(same), checker: types.checker };
2852
+ }
2853
+
2854
+ /**
2855
+ * The type of `expression`, from the project's program when it has this
2856
+ * module, else from the module's own.
2857
+ *
2858
+ * @param {ts.Expression} expression
2859
+ */
2860
+ typeOf(expression) {
2861
+ return this.projectType(expression)?.type ?? this.checker.getTypeAtLocation(expression);
2862
+ }
2863
+
2864
+ /**
2865
+ * Comments in `[from, to)` whose text `kept` does not already carry.
2866
+ *
2867
+ * @param {number} from
2868
+ * @param {number} to
2869
+ * @param {string} kept
2870
+ */
2871
+ lostComments(from, to, kept) {
2872
+ const scanner = ts.createScanner(
2873
+ ts.ScriptTarget.Latest,
2874
+ false,
2875
+ ts.LanguageVariant.Standard,
2876
+ this.source,
2877
+ undefined,
2878
+ from,
2879
+ to - from,
2880
+ );
2881
+ /** @type {string[]} */
2882
+ const lost = [];
2883
+ for (
2884
+ let token = scanner.scan();
2885
+ token !== ts.SyntaxKind.EndOfFileToken;
2886
+ token = scanner.scan()
2887
+ ) {
2888
+ if (
2889
+ token !== ts.SyntaxKind.SingleLineCommentTrivia &&
2890
+ token !== ts.SyntaxKind.MultiLineCommentTrivia
2891
+ ) {
2892
+ continue;
2893
+ }
2894
+ const text = scanner.getTokenText();
2895
+ if (!kept.includes(text.replaceAll('\n', LITERAL_NEWLINE)) && !kept.includes(text))
2896
+ lost.push(text);
2897
+ }
2898
+ return lost;
2899
+ }
2900
+
2901
+ /**
2902
+ * The template directive equivalent to a renderable expression, as
2903
+ * relative text, or null.
2904
+ *
2905
+ * @param {ts.Expression} expression
2906
+ * @returns {string | null}
2907
+ */
2908
+ directive(expression) {
2909
+ const node = skipParens(expression);
2910
+ if (ts.isConditionalExpression(node)) return this.ifDirective(node);
2911
+ if (
2912
+ ts.isBinaryExpression(node) &&
2913
+ node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken &&
2914
+ isBoolean(node.left, (name) => this.constValue(name))
2915
+ ) {
2916
+ const arm = this.arm(node.right);
2917
+ if (arm === null || arm === '') return null;
2918
+ this.count(RULE.if);
2919
+ return this.block(`@if (${this.emit(node.left, PLAIN)})`, arm);
2920
+ }
2921
+ if (ts.isCallExpression(node)) return this.forDirective(node);
2922
+ return null;
2923
+ }
2924
+
2925
+ /**
2926
+ * The relative template text for one directive arm: an element, a nested
2927
+ * directive, or '' for nothing. An arm that is only a value is null; the
2928
+ * caller decides whether it may become a `{value}` hole.
2929
+ *
2930
+ * @param {ts.Expression} expression
2931
+ * @returns {string | null}
2932
+ */
2933
+ arm(expression) {
2934
+ const node = skipParens(expression);
2935
+ if (isJsx(node)) return this.relative(this.emit(node, TEMPLATE), node);
2936
+ if (isNullish(node)) return '';
2937
+ return this.directive(node);
2938
+ }
2939
+
2940
+ /** @param {ts.ConditionalExpression} node */
2941
+ ifDirective(node) {
2942
+ let whenTrue = this.arm(node.whenTrue);
2943
+ let whenFalse = this.arm(node.whenFalse);
2944
+ // A ternary between two values is a value; one with an element on
2945
+ // either side is control flow, and a value arm is a hole in a fragment:
2946
+ // a bare `{value}` arm is a JavaScript block, not a hole.
2947
+ if (whenTrue === null && whenFalse === null) return null;
2948
+ if ((whenTrue ?? '') === '' && (whenFalse ?? '') === '') return null;
2949
+ whenTrue ??= `<>{${this.emit(skipParens(node.whenTrue), PLAIN)}}</>`;
2950
+ whenFalse ??= `<>{${this.emit(skipParens(node.whenFalse), PLAIN)}}</>`;
2951
+ this.count(RULE.if);
2952
+ const condition = this.emit(node.condition, PLAIN);
2953
+ if (whenTrue === '') {
2954
+ const negated = /^[\w$.]+$/.test(condition) ? `!${condition}` : `!(${condition})`;
2955
+ return this.block(`@if (${negated})`, whenFalse);
2956
+ }
2957
+ const then = this.block(`@if (${condition})`, whenTrue);
2958
+ return whenFalse === '' ? then : then + ' ' + this.block('@else', whenFalse);
2959
+ }
2960
+
2961
+ /**
2962
+ * `items.map((item, i) => <Row key={item.id} />)` is
2963
+ * `@for (const item of items; index i; key item.id) { <Row /> }`.
2964
+ *
2965
+ * @param {ts.CallExpression} node
2966
+ */
2967
+ forDirective(node) {
2968
+ const callee = node.expression;
2969
+ if (
2970
+ !ts.isPropertyAccessExpression(callee) ||
2971
+ callee.name.text !== 'map' ||
2972
+ node.arguments.length !== 1
2973
+ ) {
2974
+ return null;
2975
+ }
2976
+ const fn = node.arguments[0];
2977
+ if (!(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) return null;
2978
+ if (fn.parameters.length === 0 || fn.parameters.length > 2) return null;
2979
+ if (fn.parameters.some((p) => p.initializer || p.dotDotDotToken)) return null;
2980
+ const [item, index] = fn.parameters;
2981
+ if (index && !ts.isIdentifier(index.name)) return null;
2982
+ // `@for (const items of items)` would read `items` in its own TDZ.
2983
+ const bound = new Set([...bindingNames(item.name), ...(index ? bindingNames(index.name) : [])]);
2984
+ if (reads(callee.expression, (name) => bound.has(name))) return null;
2985
+ // A `function` row sees its own `this` and `arguments`; an arm does not.
2986
+ if (ts.isFunctionExpression(fn) && usesOwnThis(fn.body)) return null;
2987
+ // A row that writes an outer variable (`n++`) needs every row to run in
2988
+ // order; an `@for` row can be skipped.
2989
+ if (this.writesOuter(fn)) return null;
2990
+
2991
+ /** @type {ts.Statement[]} */
2992
+ let setup = [];
2993
+ /** @type {ts.Expression} */
2994
+ let output;
2995
+ if (ts.isBlock(fn.body)) {
2996
+ const statements = fn.body.statements;
2997
+ const last = statements[statements.length - 1];
2998
+ if (!last || !ts.isReturnStatement(last) || !last.expression) return null;
2999
+ setup = statements.slice(0, -1);
3000
+ if (!this.armReturnsOnlyEmpty(setup)) return null;
3001
+ output = last.expression;
3002
+ } else output = fn.body;
3003
+ const root = skipParens(output);
3004
+ if (!isJsx(root) && !ts.isConditionalExpression(root)) return null;
3005
+
3006
+ // Every element the row can render carries the item's key, so it moves
3007
+ // to the header once: the same key on each arm of a conditional row.
3008
+ const elements = (rowElements(root) ?? []).filter((element) => !ts.isJsxFragment(element));
3009
+ const keys = elements.map((element) => {
3010
+ return attributeOf(ts.isJsxElement(element) ? element.openingElement : element, 'key');
3011
+ });
3012
+ let key = null;
3013
+ if (keys.some(Boolean)) {
3014
+ const values = keys.map((attribute) => {
3015
+ const value = attribute?.initializer;
3016
+ return value && ts.isJsxExpression(value) ? value.expression : value;
3017
+ });
3018
+ const text = values[0]?.getText(this.sf);
3019
+ if (!values[0] || values.some((value) => value?.getText(this.sf) !== text)) return null;
3020
+ key = values[0];
3021
+ if (this.readsLocals(key, setup)) {
3022
+ this.note(
3023
+ RULE.for,
3024
+ 'warning',
3025
+ /** @type {ts.JsxAttribute} */ (keys[0]),
3026
+ 'This row key reads a value computed in the row, so the list stays a `.map()`.',
3027
+ );
3028
+ return null;
3029
+ }
3030
+ }
3031
+ const hoisted = key ? /** @type {ts.JsxAttribute[]} */ (keys) : [];
3032
+ /** @type {ts.JsxElement[]} A keyed `<Fragment>` is a bare row. */
3033
+ const fragments = [];
3034
+ for (const attribute of hoisted) {
3035
+ this.removed.add(attribute);
3036
+ const opening = attribute.parent.parent;
3037
+ if (
3038
+ ts.isJsxOpeningElement(opening) &&
3039
+ opening.attributes.properties.length === 1 &&
3040
+ this.calleeName(opening.tagName) === 'Fragment'
3041
+ ) {
3042
+ fragments.push(opening.parent);
3043
+ this.bare.add(opening.parent);
3044
+ }
3045
+ }
3046
+ const arm = ts.isConditionalExpression(root)
3047
+ ? this.ifDirective(root)
3048
+ : this.relative(this.emit(root, TEMPLATE), root);
3049
+ if (arm === null) {
3050
+ for (const attribute of hoisted) this.removed.delete(attribute);
3051
+ for (const fragment of fragments) this.bare.delete(fragment);
3052
+ return null;
3053
+ }
3054
+ this.count(RULE.for);
3055
+ let source = this.emit(callee.expression, PLAIN);
3056
+ if (callee.questionDotToken) source = `${source} ?? []`;
3057
+ let header = `@for (const ${this.emit(item.name, PLAIN)} of ${source}`;
3058
+ if (index) header += `; index ${index.name.getText(this.sf)}`;
3059
+ if (key) header += `; key ${this.emit(key, PLAIN)}`;
3060
+ else if (this.strong) {
3061
+ this.note(
3062
+ RULE.for,
3063
+ 'warning',
3064
+ node,
3065
+ 'Strong mode needs a keyed `@for`; add `key <item id>` to the header.',
3066
+ );
3067
+ }
3068
+ header += ')';
3069
+ if (setup.length === 0) return this.block(header, arm);
3070
+ const statements = this.relative(
3071
+ this.span(fn.body, setup[0].getStart(this.sf), setup[setup.length - 1].end, PLAIN),
3072
+ setup[0],
3073
+ );
3074
+ return this.block(header, statements + '\n' + arm);
3075
+ }
3076
+
3077
+ /**
3078
+ * Whether `fn` assigns a variable declared outside it.
3079
+ *
3080
+ * @param {ts.ArrowFunction | ts.FunctionExpression} fn
3081
+ */
3082
+ writesOuter(fn) {
3083
+ /** @type {(node: ts.Node) => boolean} */
3084
+ const visit = (node) => {
3085
+ let target = null;
3086
+ if (
3087
+ ts.isBinaryExpression(node) &&
3088
+ node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
3089
+ node.operatorToken.kind <= ts.SyntaxKind.LastAssignment
3090
+ ) {
3091
+ target = node.left;
3092
+ } else if (
3093
+ (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
3094
+ (node.operator === ts.SyntaxKind.PlusPlusToken ||
3095
+ node.operator === ts.SyntaxKind.MinusMinusToken)
3096
+ ) {
3097
+ target = node.operand;
3098
+ }
3099
+ if (target && ts.isIdentifier(skipParens(target))) {
3100
+ const declaration = this.declarationOf(/** @type {ts.Identifier} */ (skipParens(target)));
3101
+ if (declaration && (declaration.pos < fn.pos || declaration.end > fn.end)) return true;
3102
+ }
3103
+ return ts.forEachChild(node, visit) ?? false;
3104
+ };
3105
+ return visit(fn.body);
3106
+ }
3107
+
3108
+ /**
3109
+ * Whether every `return` in a list row's setup leaves the row empty, the
3110
+ * only early exit a directive arm allows.
3111
+ *
3112
+ * @param {ts.Statement[]} statements
3113
+ */
3114
+ armReturnsOnlyEmpty(statements) {
3115
+ let ok = true;
3116
+ const visit = (/** @type {ts.Node} */ node) => {
3117
+ if (isFunctionLike(node)) return;
3118
+ if (ts.isReturnStatement(node) && node.expression && !isNullish(node.expression)) ok = false;
3119
+ node.forEachChild(visit);
3120
+ };
3121
+ statements.forEach(visit);
3122
+ return ok;
3123
+ }
3124
+
3125
+ /**
3126
+ * @param {ts.Node} expression
3127
+ * @param {ts.Statement[]} statements
3128
+ */
3129
+ readsLocals(expression, statements) {
3130
+ const declared = new Set(
3131
+ statements
3132
+ .filter(ts.isVariableStatement)
3133
+ .flatMap((statement) => statement.declarationList.declarations)
3134
+ .flatMap((declaration) => bindingNames(declaration.name)),
3135
+ );
3136
+ return reads(expression, (name) => declared.has(name));
3137
+ }
3138
+
3139
+ // ---------------------------------------------------------------- components
3140
+
3141
+ /**
3142
+ * Rewrite a component whose last statement returns JSX as a template body:
3143
+ * `function C() { setup; return <div /> }` is `function C() @{ setup; <div /> }`.
3144
+ *
3145
+ * @param {ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction} node
3146
+ */
3147
+ rewriteComponent(node) {
3148
+ if (!node.body || !this.isComponent(node)) return null;
3149
+ if (node.asteriskToken || node.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword))
3150
+ return null;
3151
+ const body = node.body;
3152
+
3153
+ if (!ts.isBlock(body)) {
3154
+ const inner = skipParens(body);
3155
+ const output = this.output(inner);
3156
+ if (output === null) return null;
3157
+ const head = this.head(node, body.getStart(this.sf));
3158
+ this.markTemplate();
3159
+ if (inner !== body && this.startsLine(inner)) {
3160
+ // `=> (\n\t<div />\n)` keeps its layout with the parens as braces.
3161
+ return (
3162
+ head +
3163
+ '@{' +
3164
+ this.source.slice(body.getStart(this.sf) + 1, inner.getStart(this.sf)) +
3165
+ output +
3166
+ this.source.slice(inner.end, body.end - 1).replace(/\)\s*$/, '') +
3167
+ '}'
3168
+ );
3169
+ }
3170
+ return head + '@{ ' + output + ' }';
3171
+ }
3172
+
3173
+ const statements = body.statements;
3174
+ const last = statements[statements.length - 1];
3175
+ if (!last || !ts.isReturnStatement(last) || !last.expression) return null;
3176
+ const guard = statements.findIndex((s, i) => i < statements.length - 1 && guardReturn(s));
3177
+ if (guard !== -1) return this.rewriteGuards(node, body, guard);
3178
+ // A template body has one output; any other early `return <A />` would
3179
+ // render through runtime descriptors, so the plain function stays.
3180
+ if (returnsJsx(statements.slice(0, -1))) return null;
3181
+ const inner = skipParens(last.expression);
3182
+ let output = this.output(inner);
3183
+ if (output === null) return null;
3184
+ const head = this.head(node, body.getStart(this.sf));
3185
+ this.markTemplate();
3186
+
3187
+ if (this.startsLine(inner)) {
3188
+ // `return (\n\t\t<div>…` sits one level deeper than the statements.
3189
+ output = this.absolute(this.relative(output, inner), last);
3190
+ }
3191
+ // A comment inside `return ( … )` becomes a setup comment.
3192
+ const indent = this.indentOf(last);
3193
+ const lost = [
3194
+ ...this.lostComments(last.getStart(this.sf), inner.getStart(this.sf), output),
3195
+ ...this.lostComments(inner.end, last.end, output),
3196
+ ];
3197
+ output =
3198
+ lost.map((comment) => comment.replaceAll('\n', '\n' + indent) + '\n' + indent).join('') +
3199
+ output;
3200
+ const previous = statements[statements.length - 2];
3201
+ const setup = previous ? this.span(body, body.getStart(this.sf) + 1, previous.end, PLAIN) : '';
3202
+ const gap = this.source.slice(
3203
+ previous ? previous.end : body.getStart(this.sf) + 1,
3204
+ last.getStart(this.sf),
3205
+ );
3206
+ return head + '@{' + setup + gap + output + this.source.slice(last.end, body.end - 1) + '}';
3207
+ }
3208
+
3209
+ /**
3210
+ * A component with `if (c) return <A />;` guards: each becomes
3211
+ * `@if (c) { <A /> } @else { …the rest }`, since a template body has one
3212
+ * output. The setup before the first guard stays as it was.
3213
+ *
3214
+ * @param {ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction} node
3215
+ * @param {ts.Block} body
3216
+ * @param {number} first the index of the first guard
3217
+ */
3218
+ rewriteGuards(node, body, first) {
3219
+ const statements = body.statements;
3220
+ const last = /** @type {ts.ReturnStatement} */ (statements[statements.length - 1]);
3221
+ // Setup before the first guard stays in the body, which may return a
3222
+ // value early; the rest moves into arms, which may only return nothing.
3223
+ const rest = statements.slice(first + 1, -1).filter((statement) => !guardReturn(statement));
3224
+ if (returnsJsx(statements.slice(0, first)) || !this.armReturnsOnlyEmpty(rest)) return null;
3225
+ const output = this.arm(/** @type {ts.Expression} */ (last.expression));
3226
+ if (output === null) return null;
3227
+ /** @type {(from: number) => string} */
3228
+ const chain = (from) => {
3229
+ let at = from;
3230
+ while (at < statements.length - 1 && !guardReturn(statements[at])) at++;
3231
+ // Comments before the first guard stay in the body's own text.
3232
+ const lead =
3233
+ from > first
3234
+ ? this.lostComments(statements[from - 1].end, statements[from].getStart(this.sf), '')
3235
+ : [];
3236
+ const prefix =
3237
+ lead.map((comment) => comment + '\n').join('') +
3238
+ (at > from
3239
+ ? this.relative(
3240
+ this.span(body, statements[from].getStart(this.sf), statements[at - 1].end, PLAIN),
3241
+ statements[from],
3242
+ ) + '\n'
3243
+ : '');
3244
+ if (at === statements.length - 1) return prefix + output;
3245
+ const guard = /** @type {ts.IfStatement} */ (statements[at]);
3246
+ this.count(RULE.if);
3247
+ const then = this.block(
3248
+ `@if (${this.emit(guard.expression, PLAIN)})`,
3249
+ /** @type {string} */ (this.arm(/** @type {ts.Expression} */ (guardReturn(guard)))),
3250
+ );
3251
+ const rest = chain(at + 1);
3252
+ return prefix + (rest === '' ? then : then + ' ' + this.block('@else', rest));
3253
+ };
3254
+ const directive = this.absolute(chain(first), statements[first]);
3255
+ const head = this.head(node, body.getStart(this.sf));
3256
+ this.markTemplate();
3257
+ const previous = statements[first - 1];
3258
+ const before = previous ? this.span(body, body.getStart(this.sf) + 1, previous.end, PLAIN) : '';
3259
+ const gap = this.source.slice(
3260
+ previous ? previous.end : body.getStart(this.sf) + 1,
3261
+ statements[first].getStart(this.sf),
3262
+ );
3263
+ return head + '@{' + before + gap + directive + this.source.slice(last.end, body.end - 1) + '}';
3264
+ }
3265
+
3266
+ markTemplate() {
3267
+ this.template = true;
3268
+ this.count(RULE.component);
3269
+ }
3270
+
3271
+ /**
3272
+ * A component's returned expression as template output, at the position
3273
+ * and indentation `node` had, or null when it is not a single renderable.
3274
+ *
3275
+ * @param {ts.Expression} node
3276
+ */
3277
+ output(node) {
3278
+ if (isJsx(node)) return this.emit(node, TEMPLATE);
3279
+ if (ts.isConditionalExpression(node) || ts.isCallExpression(node)) {
3280
+ const directive = this.directive(node);
3281
+ return directive === null ? null : this.absolute(directive, node);
3282
+ }
3283
+ return null;
3284
+ }
3285
+
3286
+ /** @param {ts.Node} node */
3287
+ startsLine(node) {
3288
+ return this.linePrefix(node).trim() === '';
3289
+ }
3290
+
3291
+ /**
3292
+ * Whether `node` is a component definition: a capitalized function, or the
3293
+ * function passed to `memo` / `forwardRef`, or a default-exported one.
3294
+ *
3295
+ * @param {ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction} node
3296
+ */
3297
+ isComponent(node) {
3298
+ if (node.name && isComponentName(node.name.text)) return true;
3299
+ const parent = node.parent;
3300
+ if (ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name)) {
3301
+ return isComponentName(parent.name.text);
3302
+ }
3303
+ if (ts.isCallExpression(parent) && parent.arguments[0] === node) {
3304
+ const name = this.calleeName(parent.expression);
3305
+ if (name === 'memo' || name === 'forwardRef') return true;
3306
+ }
3307
+ if (ts.isExportAssignment(parent)) return true;
3308
+ if (ts.isFunctionDeclaration(node) && !node.name) return true;
3309
+ return false;
3310
+ }
3311
+ }