@octanejs/codemod 0.0.0-stage → 0.0.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.
- package/LICENSE +21 -0
- package/README.md +88 -2
- package/package.json +50 -3
- package/src/bin.js +122 -0
- package/src/compiler.js +61 -0
- package/src/index.d.ts +80 -0
- package/src/index.js +4 -0
- package/src/mappings.js +235 -0
- package/src/project.js +515 -0
- package/src/strong.js +149 -0
- package/src/transform.js +2568 -0
package/src/transform.js
ADDED
|
@@ -0,0 +1,2568 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import {
|
|
3
|
+
DEPENDENCY_HOOKS,
|
|
4
|
+
REACT_MODULES,
|
|
5
|
+
TEXT_INPUT_TYPES,
|
|
6
|
+
UNSUPPORTED_VALUES,
|
|
7
|
+
mapQualifiedType,
|
|
8
|
+
mapReactImport,
|
|
9
|
+
} from './mappings.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @typedef {'info' | 'warning' | 'error'} Severity
|
|
13
|
+
* @typedef {{ rule: string, severity: Severity, line: number, message: string }} Note
|
|
14
|
+
*
|
|
15
|
+
* @typedef {Object} TransformOptions
|
|
16
|
+
* @property {'tsrx' | 'tsx'} [target] `tsrx` (default) rewrites component
|
|
17
|
+
* bodies as templates; `tsx` keeps JSX and only ports the React APIs.
|
|
18
|
+
* @property {boolean} [strong] emit Strong-mode source: add `"use strong"` and
|
|
19
|
+
* leave omitted dependency lists to the compiler.
|
|
20
|
+
* @property {boolean} [strictNullChecks] the project checks with
|
|
21
|
+
* `strictNullChecks`, so a TypeScript module's own types may prove a child
|
|
22
|
+
* hole is text
|
|
23
|
+
* @property {{ sourceFile: ts.SourceFile, checker: ts.TypeChecker }} [types]
|
|
24
|
+
* this module in a program over the whole project, whose resolved imports
|
|
25
|
+
* type what the module's own program cannot
|
|
26
|
+
* @property {(specifier: string) => string | null} [resolveSpecifier] the new
|
|
27
|
+
* spelling of an import specifier (a renamed module, a binding package), or
|
|
28
|
+
* null to keep it.
|
|
29
|
+
* @property {(specifier: string, name: string) => boolean | null} [isContext]
|
|
30
|
+
* whether an imported name is a context, or null when it cannot be known
|
|
31
|
+
*
|
|
32
|
+
* @typedef {Object} TransformResult
|
|
33
|
+
* @property {string} code
|
|
34
|
+
* @property {boolean} changed
|
|
35
|
+
* @property {boolean} template whether the module becomes `.tsrx`: it holds a
|
|
36
|
+
* template, keeps JSX, or was a JSX module, so no `.tsx` module is left
|
|
37
|
+
* outside Strong mode's reach
|
|
38
|
+
* @property {Note[]} notes
|
|
39
|
+
* @property {Record<string, number>} rules how often each rule fired
|
|
40
|
+
* @property {ModuleExports} exports what the module exports that other modules'
|
|
41
|
+
* rewrites depend on
|
|
42
|
+
*
|
|
43
|
+
* @typedef {Object} ModuleExports
|
|
44
|
+
* @property {string[]} contexts exported names whose value is a context this
|
|
45
|
+
* module creates
|
|
46
|
+
* @property {{ specifier: string, names: [string, string][] | null }[]} reexports
|
|
47
|
+
* `export … from` declarations: [imported, exported] pairs, or null for `*`
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {{ template: boolean }} Context
|
|
52
|
+
* @typedef {{ module: string, local: string, imported: string, namespace: boolean, typeOnly: boolean }} Import
|
|
53
|
+
*/
|
|
54
|
+
|
|
55
|
+
/** Marks emitted text whose whole line should go. */
|
|
56
|
+
const DROP = '\u0000DROP\u0000';
|
|
57
|
+
/**
|
|
58
|
+
* Stands in for a newline inside a string or template literal while arms are
|
|
59
|
+
* re-indented, so moving a literal never changes its value.
|
|
60
|
+
*/
|
|
61
|
+
const LITERAL_NEWLINE = '\u0000NL\u0000';
|
|
62
|
+
|
|
63
|
+
const TEMPLATE = { template: true };
|
|
64
|
+
const PLAIN = { template: false };
|
|
65
|
+
|
|
66
|
+
/** Rule names, as reported. */
|
|
67
|
+
const RULE = {
|
|
68
|
+
classComponent: 'class-component',
|
|
69
|
+
consumer: 'context-consumer',
|
|
70
|
+
defaultProps: 'default-props',
|
|
71
|
+
deps: 'hook-dependencies',
|
|
72
|
+
eventObject: 'event-object',
|
|
73
|
+
forwardRef: 'forward-ref',
|
|
74
|
+
import: 'imports',
|
|
75
|
+
legacyRoot: 'legacy-root',
|
|
76
|
+
rootRender: 'root-render',
|
|
77
|
+
serverRender: 'server-render',
|
|
78
|
+
flushSync: 'flush-sync',
|
|
79
|
+
renderProp: 'render-prop-children',
|
|
80
|
+
documentShell: 'document-shell',
|
|
81
|
+
nativeChange: 'native-text-change',
|
|
82
|
+
className: 'class-attribute',
|
|
83
|
+
provider: 'context-provider',
|
|
84
|
+
strictMode: 'strict-mode',
|
|
85
|
+
component: 'template-component',
|
|
86
|
+
if: 'template-if',
|
|
87
|
+
for: 'template-for',
|
|
88
|
+
text: 'template-text',
|
|
89
|
+
try: 'template-try',
|
|
90
|
+
unsupported: 'unsupported-api',
|
|
91
|
+
strong: 'strong',
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Rewrite one React module as Octane.
|
|
96
|
+
*
|
|
97
|
+
* @param {string} source
|
|
98
|
+
* @param {string} filename
|
|
99
|
+
* @param {TransformOptions} [options]
|
|
100
|
+
* @returns {TransformResult}
|
|
101
|
+
*/
|
|
102
|
+
export function transformModule(source, filename, options = {}) {
|
|
103
|
+
return new ModuleTransform(source, filename, options).run();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Parse and bind one module on its own, with only the ES5 library and no
|
|
108
|
+
* module resolution. Binding is enough to map every name to the declaration it
|
|
109
|
+
* refers to, so a shadowed `useState` or event parameter is never mistaken for
|
|
110
|
+
* another; the library gives the module's own types their array and string
|
|
111
|
+
* members.
|
|
112
|
+
*
|
|
113
|
+
* @param {string} filename
|
|
114
|
+
* @param {string} source
|
|
115
|
+
*/
|
|
116
|
+
function bind(filename, source) {
|
|
117
|
+
const lib = esLib();
|
|
118
|
+
const sf = ts.createSourceFile(
|
|
119
|
+
filename,
|
|
120
|
+
source,
|
|
121
|
+
ts.ScriptTarget.Latest,
|
|
122
|
+
true,
|
|
123
|
+
scriptKind(filename),
|
|
124
|
+
);
|
|
125
|
+
/** @type {ts.CompilerHost} */
|
|
126
|
+
const host = {
|
|
127
|
+
getSourceFile: (name) => (name === filename ? sf : name === lib.fileName ? lib : undefined),
|
|
128
|
+
getDefaultLibFileName: () => lib.fileName,
|
|
129
|
+
writeFile: () => {},
|
|
130
|
+
getCurrentDirectory: () => '',
|
|
131
|
+
getCanonicalFileName: (name) => name,
|
|
132
|
+
useCaseSensitiveFileNames: () => true,
|
|
133
|
+
getNewLine: () => '\n',
|
|
134
|
+
fileExists: (name) => name === filename || name === lib.fileName,
|
|
135
|
+
readFile: () => undefined,
|
|
136
|
+
};
|
|
137
|
+
const program = ts.createProgram({
|
|
138
|
+
rootNames: [filename, lib.fileName],
|
|
139
|
+
options: {
|
|
140
|
+
noLib: true,
|
|
141
|
+
noResolve: true,
|
|
142
|
+
allowJs: true,
|
|
143
|
+
jsx: ts.JsxEmit.Preserve,
|
|
144
|
+
types: [],
|
|
145
|
+
// As the compiler's typed-text proof requires: a `string` excludes
|
|
146
|
+
// null, and an indexed read may be missing.
|
|
147
|
+
strictNullChecks: true,
|
|
148
|
+
noUncheckedIndexedAccess: true,
|
|
149
|
+
},
|
|
150
|
+
host,
|
|
151
|
+
});
|
|
152
|
+
return { sf, checker: program.getTypeChecker() };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** @type {ts.SourceFile | undefined} */
|
|
156
|
+
let es5;
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The ES5 library, parsed once and shared by every module's program, so
|
|
160
|
+
* array and string members have types.
|
|
161
|
+
*/
|
|
162
|
+
function esLib() {
|
|
163
|
+
const file = ts.getDefaultLibFilePath({}).replace(/[^/\\]+$/, 'lib.es5.d.ts');
|
|
164
|
+
es5 ??= ts.createSourceFile(
|
|
165
|
+
'lib.es5.d.ts',
|
|
166
|
+
/** @type {string} */ (ts.sys.readFile(file)),
|
|
167
|
+
ts.ScriptTarget.Latest,
|
|
168
|
+
true,
|
|
169
|
+
);
|
|
170
|
+
return es5;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** @param {string} filename */
|
|
174
|
+
function scriptKind(filename) {
|
|
175
|
+
if (filename.endsWith('.tsx')) return ts.ScriptKind.TSX;
|
|
176
|
+
if (filename.endsWith('.jsx')) return ts.ScriptKind.JSX;
|
|
177
|
+
if (/\.[cm]?ts$/.test(filename)) return ts.ScriptKind.TS;
|
|
178
|
+
// Plain .js files often hold JSX in React projects.
|
|
179
|
+
return ts.ScriptKind.JSX;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* @param {ts.Expression} node
|
|
184
|
+
* @returns {ts.Expression}
|
|
185
|
+
*/
|
|
186
|
+
function skipParens(node) {
|
|
187
|
+
while (ts.isParenthesizedExpression(node)) node = node.expression;
|
|
188
|
+
return node;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** @param {ts.Node} node */
|
|
192
|
+
function isJsx(node) {
|
|
193
|
+
return ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Whether a hole is already spelled as text, or as a literal the cast would
|
|
198
|
+
* only clutter.
|
|
199
|
+
*
|
|
200
|
+
* @param {ts.Expression} node
|
|
201
|
+
*/
|
|
202
|
+
function isTextSpelling(node) {
|
|
203
|
+
node = skipParens(node);
|
|
204
|
+
return (
|
|
205
|
+
ts.isNumericLiteral(node) ||
|
|
206
|
+
ts.isBigIntLiteral(node) ||
|
|
207
|
+
ts.isAsExpression(node) ||
|
|
208
|
+
isStringSpelling(node)
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Whether the compiler proves `node` a string by its spelling: a string
|
|
214
|
+
* literal, a `String()` call, or a concatenation with one.
|
|
215
|
+
*
|
|
216
|
+
* @param {ts.Expression} node
|
|
217
|
+
* @returns {boolean}
|
|
218
|
+
*/
|
|
219
|
+
function isStringSpelling(node) {
|
|
220
|
+
node = skipParens(node);
|
|
221
|
+
if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) return true;
|
|
222
|
+
if (ts.isCallExpression(node)) {
|
|
223
|
+
return ts.isIdentifier(node.expression) && node.expression.text === 'String';
|
|
224
|
+
}
|
|
225
|
+
return (
|
|
226
|
+
ts.isBinaryExpression(node) &&
|
|
227
|
+
node.operatorToken.kind === ts.SyntaxKind.PlusToken &&
|
|
228
|
+
(isStringSpelling(node.left) || isStringSpelling(node.right))
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* What a type renders as: 1 when every member is a string, 2 when every
|
|
234
|
+
* member is a string, number, or bigint and one is not a string, else 0. The
|
|
235
|
+
* compiler's typed-text proof applies the same test.
|
|
236
|
+
*
|
|
237
|
+
* @param {ts.Type} type
|
|
238
|
+
* @returns {0 | 1 | 2}
|
|
239
|
+
*/
|
|
240
|
+
function textKind(type) {
|
|
241
|
+
const { TypeFlags } = ts;
|
|
242
|
+
const opaque =
|
|
243
|
+
TypeFlags.Any | TypeFlags.Unknown | TypeFlags.Never | TypeFlags.VoidLike | TypeFlags.Null;
|
|
244
|
+
if (type.flags & opaque) return 0;
|
|
245
|
+
if (type.flags & TypeFlags.StringLike) return 1;
|
|
246
|
+
if (type.flags & (TypeFlags.NumberLike | TypeFlags.BigIntLike)) return 2;
|
|
247
|
+
if (!type.isUnion()) return 0;
|
|
248
|
+
/** @type {0 | 1 | 2} */
|
|
249
|
+
let kind = 1;
|
|
250
|
+
for (const member of type.types) {
|
|
251
|
+
const each = textKind(member);
|
|
252
|
+
if (each === 0) return 0;
|
|
253
|
+
if (each === 2) kind = 2;
|
|
254
|
+
}
|
|
255
|
+
return kind;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The outermost node of `sf` spanning exactly `[start, end)`.
|
|
260
|
+
*
|
|
261
|
+
* @param {ts.SourceFile} sf
|
|
262
|
+
* @param {number} start
|
|
263
|
+
* @param {number} end
|
|
264
|
+
* @returns {ts.Node | null}
|
|
265
|
+
*/
|
|
266
|
+
function nodeSpanning(sf, start, end) {
|
|
267
|
+
/** @type {ts.Node} */
|
|
268
|
+
let node = sf;
|
|
269
|
+
for (;;) {
|
|
270
|
+
const child = ts.forEachChild(node, (c) => (c.pos <= start && c.end >= end ? c : undefined));
|
|
271
|
+
if (!child) return null;
|
|
272
|
+
if (child.getStart(sf) === start && child.end === end) return child;
|
|
273
|
+
node = child;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* The elements a list row can render: the row itself, or each arm of a
|
|
279
|
+
* conditional row. Null when an arm renders anything else.
|
|
280
|
+
*
|
|
281
|
+
* @param {ts.Expression} node
|
|
282
|
+
* @returns {(ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment)[] | null}
|
|
283
|
+
*/
|
|
284
|
+
function rowElements(node) {
|
|
285
|
+
node = skipParens(node);
|
|
286
|
+
if (isJsx(node))
|
|
287
|
+
return [/** @type {ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment} */ (node)];
|
|
288
|
+
if (isNullish(node)) return [];
|
|
289
|
+
if (!ts.isConditionalExpression(node)) return null;
|
|
290
|
+
const whenTrue = rowElements(node.whenTrue);
|
|
291
|
+
const whenFalse = rowElements(node.whenFalse);
|
|
292
|
+
return whenTrue && whenFalse && [...whenTrue, ...whenFalse];
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* The element an `if (c) return <A />;` guard returns, or null for any other
|
|
297
|
+
* statement.
|
|
298
|
+
*
|
|
299
|
+
* @param {ts.Statement} statement
|
|
300
|
+
* @returns {ts.Expression | null}
|
|
301
|
+
*/
|
|
302
|
+
function guardReturn(statement) {
|
|
303
|
+
if (!ts.isIfStatement(statement) || statement.elseStatement) return null;
|
|
304
|
+
let then = statement.thenStatement;
|
|
305
|
+
if (ts.isBlock(then)) {
|
|
306
|
+
if (then.statements.length !== 1) return null;
|
|
307
|
+
then = then.statements[0];
|
|
308
|
+
}
|
|
309
|
+
if (!ts.isReturnStatement(then) || !then.expression) return null;
|
|
310
|
+
return isJsx(skipParens(then.expression)) ? then.expression : null;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Whether any `return` in `statements`, outside nested functions, returns
|
|
315
|
+
* JSX.
|
|
316
|
+
*
|
|
317
|
+
* @param {readonly ts.Statement[]} statements
|
|
318
|
+
*/
|
|
319
|
+
function returnsJsx(statements) {
|
|
320
|
+
/** @type {(node: ts.Node) => boolean} */
|
|
321
|
+
const hasJsx = (node) => isJsx(node) || (ts.forEachChild(node, hasJsx) ?? false);
|
|
322
|
+
/** @type {(node: ts.Node) => boolean} */
|
|
323
|
+
const visit = (node) => {
|
|
324
|
+
if (isFunctionLike(node)) return false;
|
|
325
|
+
if (ts.isReturnStatement(node) && node.expression && hasJsx(node.expression)) return true;
|
|
326
|
+
return ts.forEachChild(node, visit) ?? false;
|
|
327
|
+
};
|
|
328
|
+
return statements.some(visit);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Document tags a router shell renders through `@octanejs/tanstack-router`. */
|
|
332
|
+
const DOCUMENT_TAGS = /** @type {Record<string, string>} */ ({
|
|
333
|
+
html: 'Html',
|
|
334
|
+
head: 'Head',
|
|
335
|
+
body: 'Body',
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Whether an identifier is read in a type, where an import needs no value.
|
|
340
|
+
* A `typeof X` query is a type, which `import type` serves; `extends Base`
|
|
341
|
+
* reads a value, so heritage counts as one.
|
|
342
|
+
*
|
|
343
|
+
* @param {ts.Identifier} node
|
|
344
|
+
*/
|
|
345
|
+
function inTypeNode(node) {
|
|
346
|
+
let parent = node.parent;
|
|
347
|
+
while (ts.isQualifiedName(parent)) parent = parent.parent;
|
|
348
|
+
return ts.isTypeNode(parent) && !ts.isExpressionWithTypeArguments(parent);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** @param {ts.Node} node */
|
|
352
|
+
function isNullish(node) {
|
|
353
|
+
return (
|
|
354
|
+
node.kind === ts.SyntaxKind.NullKeyword ||
|
|
355
|
+
node.kind === ts.SyntaxKind.FalseKeyword ||
|
|
356
|
+
(ts.isIdentifier(node) && node.text === 'undefined')
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** @param {ts.Node} node */
|
|
361
|
+
function isFunctionLike(node) {
|
|
362
|
+
return (
|
|
363
|
+
ts.isFunctionDeclaration(node) ||
|
|
364
|
+
ts.isFunctionExpression(node) ||
|
|
365
|
+
ts.isArrowFunction(node) ||
|
|
366
|
+
ts.isMethodDeclaration(node) ||
|
|
367
|
+
ts.isGetAccessor(node) ||
|
|
368
|
+
ts.isSetAccessor(node) ||
|
|
369
|
+
ts.isConstructorDeclaration(node)
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Whether evaluating `node` can only produce a boolean, so `node && <X />`
|
|
375
|
+
* renders nothing when it is falsy, exactly as `@if` does. React renders `0`
|
|
376
|
+
* and `NaN` from a numeric left side, so anything unproven stays a hole.
|
|
377
|
+
* `valueOf` gives the initializer a `const` name is bound to, if any.
|
|
378
|
+
*
|
|
379
|
+
* @param {ts.Expression} node
|
|
380
|
+
* @param {(name: ts.Identifier) => ts.Expression | null} valueOf
|
|
381
|
+
* @returns {boolean}
|
|
382
|
+
*/
|
|
383
|
+
function isBoolean(node, valueOf) {
|
|
384
|
+
node = skipParens(node);
|
|
385
|
+
if (ts.isIdentifier(node)) {
|
|
386
|
+
const value = valueOf(node);
|
|
387
|
+
return value !== null && isBoolean(value, valueOf);
|
|
388
|
+
}
|
|
389
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword) {
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
if (ts.isPrefixUnaryExpression(node)) {
|
|
393
|
+
return node.operator === ts.SyntaxKind.ExclamationToken;
|
|
394
|
+
}
|
|
395
|
+
if (ts.isBinaryExpression(node)) {
|
|
396
|
+
switch (node.operatorToken.kind) {
|
|
397
|
+
case ts.SyntaxKind.EqualsEqualsEqualsToken:
|
|
398
|
+
case ts.SyntaxKind.ExclamationEqualsEqualsToken:
|
|
399
|
+
case ts.SyntaxKind.EqualsEqualsToken:
|
|
400
|
+
case ts.SyntaxKind.ExclamationEqualsToken:
|
|
401
|
+
case ts.SyntaxKind.LessThanToken:
|
|
402
|
+
case ts.SyntaxKind.LessThanEqualsToken:
|
|
403
|
+
case ts.SyntaxKind.GreaterThanToken:
|
|
404
|
+
case ts.SyntaxKind.GreaterThanEqualsToken:
|
|
405
|
+
case ts.SyntaxKind.InstanceOfKeyword:
|
|
406
|
+
case ts.SyntaxKind.InKeyword:
|
|
407
|
+
return true;
|
|
408
|
+
case ts.SyntaxKind.AmpersandAmpersandToken:
|
|
409
|
+
case ts.SyntaxKind.BarBarToken:
|
|
410
|
+
return isBoolean(node.left, valueOf) && isBoolean(node.right, valueOf);
|
|
411
|
+
}
|
|
412
|
+
return false;
|
|
413
|
+
}
|
|
414
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
|
|
415
|
+
return node.expression.text === 'Boolean';
|
|
416
|
+
}
|
|
417
|
+
return false;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Modules whose exports the codemod knows by name: React's, and Octane's own
|
|
422
|
+
* for code already partly migrated.
|
|
423
|
+
*
|
|
424
|
+
* @param {string} module
|
|
425
|
+
*/
|
|
426
|
+
function isApiModule(module) {
|
|
427
|
+
return module in REACT_MODULES || module === 'octane';
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Whether an identifier names a property rather than a binding.
|
|
432
|
+
*
|
|
433
|
+
* @param {ts.Identifier} node
|
|
434
|
+
*/
|
|
435
|
+
function isPropertyName(node) {
|
|
436
|
+
const parent = /** @type {ts.Node & { name?: ts.Node }} */ (node.parent);
|
|
437
|
+
if (ts.isPropertyAccessExpression(parent)) return parent.name === node;
|
|
438
|
+
if (ts.isQualifiedName(parent)) return parent.right === node;
|
|
439
|
+
return (
|
|
440
|
+
parent.name === node &&
|
|
441
|
+
(ts.isPropertyAssignment(parent) ||
|
|
442
|
+
ts.isPropertySignature(parent) ||
|
|
443
|
+
ts.isPropertyDeclaration(parent) ||
|
|
444
|
+
ts.isMethodDeclaration(parent) ||
|
|
445
|
+
ts.isMethodSignature(parent) ||
|
|
446
|
+
ts.isJsxAttribute(parent))
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Whether an identifier is the name a declaration introduces.
|
|
452
|
+
*
|
|
453
|
+
* @param {ts.Identifier} node
|
|
454
|
+
*/
|
|
455
|
+
function declaresName(node) {
|
|
456
|
+
const parent = /** @type {ts.Node & { name?: ts.Node }} */ (node.parent);
|
|
457
|
+
if (parent.name !== node) return false;
|
|
458
|
+
return (
|
|
459
|
+
ts.isVariableDeclaration(parent) ||
|
|
460
|
+
ts.isFunctionDeclaration(parent) ||
|
|
461
|
+
ts.isFunctionExpression(parent) ||
|
|
462
|
+
ts.isClassDeclaration(parent) ||
|
|
463
|
+
ts.isClassExpression(parent) ||
|
|
464
|
+
ts.isParameter(parent) ||
|
|
465
|
+
ts.isBindingElement(parent) ||
|
|
466
|
+
ts.isImportSpecifier(parent) ||
|
|
467
|
+
ts.isImportClause(parent) ||
|
|
468
|
+
ts.isNamespaceImport(parent) ||
|
|
469
|
+
ts.isTypeAliasDeclaration(parent) ||
|
|
470
|
+
ts.isInterfaceDeclaration(parent) ||
|
|
471
|
+
ts.isEnumDeclaration(parent) ||
|
|
472
|
+
ts.isTypeParameterDeclaration(parent)
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* The names a binding pattern introduces.
|
|
478
|
+
*
|
|
479
|
+
* @param {ts.BindingName} name
|
|
480
|
+
* @returns {string[]}
|
|
481
|
+
*/
|
|
482
|
+
function bindingNames(name) {
|
|
483
|
+
if (ts.isIdentifier(name)) return [name.text];
|
|
484
|
+
return name.elements.flatMap((element) =>
|
|
485
|
+
ts.isOmittedExpression(element) ? [] : bindingNames(element.name),
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Whether `node` reads a name `test` accepts.
|
|
491
|
+
*
|
|
492
|
+
* @param {ts.Node} node
|
|
493
|
+
* @param {(name: string) => boolean} test
|
|
494
|
+
* @returns {boolean}
|
|
495
|
+
*/
|
|
496
|
+
function reads(node, test) {
|
|
497
|
+
if (ts.isIdentifier(node)) return test(node.text);
|
|
498
|
+
return ts.forEachChild(node, (child) => reads(child, test) || undefined) === true;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* Whether a `function` body reads its own `this` or `arguments`.
|
|
503
|
+
*
|
|
504
|
+
* @param {ts.Node} node
|
|
505
|
+
* @returns {boolean}
|
|
506
|
+
*/
|
|
507
|
+
function usesOwnThis(node) {
|
|
508
|
+
if (node.kind === ts.SyntaxKind.ThisKeyword) return true;
|
|
509
|
+
if (ts.isIdentifier(node) && node.text === 'arguments') return true;
|
|
510
|
+
if (isFunctionLike(node) && !ts.isArrowFunction(node)) return false;
|
|
511
|
+
return ts.forEachChild(node, (child) => usesOwnThis(child) || undefined) === true;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* The children of an element that are more than layout whitespace.
|
|
516
|
+
*
|
|
517
|
+
* @param {ts.JsxElement | ts.JsxFragment} node
|
|
518
|
+
*/
|
|
519
|
+
function contentOf(node) {
|
|
520
|
+
return node.children.filter(
|
|
521
|
+
(child) => !(ts.isJsxText(child) && child.containsOnlyTriviaWhiteSpaces),
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* A comment's text without its delimiters, to wrap as a JSX comment.
|
|
527
|
+
*
|
|
528
|
+
* @param {string} comment
|
|
529
|
+
*/
|
|
530
|
+
function commentText(comment) {
|
|
531
|
+
const body = comment.startsWith('//') ? comment.slice(2) : comment.slice(2, -2);
|
|
532
|
+
return body.trim().replaceAll('*/', '* /');
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** @param {string} name */
|
|
536
|
+
function isComponentName(name) {
|
|
537
|
+
return /^[A-Z]/.test(name);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
class ModuleTransform {
|
|
541
|
+
/**
|
|
542
|
+
* @param {string} source
|
|
543
|
+
* @param {string} filename
|
|
544
|
+
* @param {TransformOptions} options
|
|
545
|
+
*/
|
|
546
|
+
constructor(source, filename, options) {
|
|
547
|
+
this.source = source;
|
|
548
|
+
this.filename = filename;
|
|
549
|
+
this.options = options;
|
|
550
|
+
this.target = options.target ?? 'tsrx';
|
|
551
|
+
this.strong = options.strong === true;
|
|
552
|
+
/** @type {Set<string>} React imports read as values, not only as types. */
|
|
553
|
+
this.valueUses = new Set();
|
|
554
|
+
this.routerShell = false;
|
|
555
|
+
this.textTypes = options.strictNullChecks === true && /\.[cm]?tsx?$/.test(filename);
|
|
556
|
+
const { sf, checker } = bind(filename, source);
|
|
557
|
+
this.sf = sf;
|
|
558
|
+
this.checker = checker;
|
|
559
|
+
/** @type {Note[]} */
|
|
560
|
+
this.notes = [];
|
|
561
|
+
/** @type {Record<string, number>} */
|
|
562
|
+
this.rules = {};
|
|
563
|
+
this.template = false;
|
|
564
|
+
this.indentUnit = /^\t/m.test(source) ? '\t' : ' ';
|
|
565
|
+
|
|
566
|
+
/** @type {Map<ts.Node, Import>} Every import, keyed by its declaration. */
|
|
567
|
+
this.imports = new Map();
|
|
568
|
+
/** @type {Map<string, Import>} React and Octane imports, by local name. */
|
|
569
|
+
this.apiLocals = new Map();
|
|
570
|
+
/** React-module locals that are still referenced after the rewrite. */
|
|
571
|
+
this.used = new Set();
|
|
572
|
+
/** Imports the rewrite needs from Octane: module -> name -> { local, typeOnly } */
|
|
573
|
+
this.added = new Map();
|
|
574
|
+
/** Every name the module declares, to keep added imports from colliding. */
|
|
575
|
+
this.declared = new Set();
|
|
576
|
+
/** Attributes a parent rule has already consumed, such as a row key. */
|
|
577
|
+
this.removed = new Set();
|
|
578
|
+
/** `<Fragment key>` rows whose key moved to the `@for` header. */
|
|
579
|
+
this.bare = new Set();
|
|
580
|
+
/** Functions whose parameter list a rule replaced. */
|
|
581
|
+
this.parameters = new Map();
|
|
582
|
+
/** @type {ts.ImportDeclaration[]} Placeholder index -> import declaration. */
|
|
583
|
+
this.importSlots = [];
|
|
584
|
+
this.hasJsx = false;
|
|
585
|
+
/** Whether the module imports React, rather than already being Octane. */
|
|
586
|
+
this.fromReact = false;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/** @returns {TransformResult} */
|
|
590
|
+
run() {
|
|
591
|
+
this.analyze();
|
|
592
|
+
let code = this.emit(this.sf, PLAIN, 0);
|
|
593
|
+
code = this.finishImports(code);
|
|
594
|
+
code = code.replace(/^[ \t]*\u0000DROP\u0000[ \t]*\r?\n/gm, '').replaceAll(DROP, '');
|
|
595
|
+
code = code.replaceAll(LITERAL_NEWLINE, '\n');
|
|
596
|
+
const tsrx =
|
|
597
|
+
this.template || (this.target === 'tsrx' && (this.hasJsx || /\.[jt]sx$/.test(this.filename)));
|
|
598
|
+
if (tsrx) code = code.replace(/^\/\*\*\s*@jsxImportSource\s+\S+\s*\*\/[ \t]*\r?\n/m, '');
|
|
599
|
+
// A JavaScript module was never type-checked; as TSRX it stays unchecked.
|
|
600
|
+
if (tsrx && /\.[cm]?jsx?$/.test(this.filename)) {
|
|
601
|
+
code = code.replace(/^(#![^\n]*\n)?/, '$1// @ts-nocheck\n');
|
|
602
|
+
}
|
|
603
|
+
if (this.strong && tsrx) code = this.addStrongDirective(code);
|
|
604
|
+
if (!tsrx && this.fromReact && this.hasJsx && /\.(?:[jt]sx|js)$/.test(this.filename)) {
|
|
605
|
+
code = this.addJsxPragma(code);
|
|
606
|
+
}
|
|
607
|
+
return {
|
|
608
|
+
code,
|
|
609
|
+
changed: code !== this.source,
|
|
610
|
+
template: tsrx,
|
|
611
|
+
notes: this.notes.sort((a, b) => a.line - b.line),
|
|
612
|
+
rules: this.rules,
|
|
613
|
+
exports: this.exportsOf(),
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** @returns {ModuleExports} */
|
|
618
|
+
exportsOf() {
|
|
619
|
+
/** @type {Set<string>} */
|
|
620
|
+
const contexts = new Set();
|
|
621
|
+
/** @type {Set<string>} */
|
|
622
|
+
const exported = new Set();
|
|
623
|
+
/** @type {ModuleExports['reexports']} */
|
|
624
|
+
const reexports = [];
|
|
625
|
+
const isExported = (/** @type {ts.Statement} */ statement) =>
|
|
626
|
+
ts.canHaveModifiers(statement) &&
|
|
627
|
+
ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
|
|
628
|
+
for (const statement of this.sf.statements) {
|
|
629
|
+
if (ts.isVariableStatement(statement)) {
|
|
630
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
631
|
+
if (!ts.isIdentifier(declaration.name) || !this.isContext(declaration.name)) continue;
|
|
632
|
+
contexts.add(declaration.name.text);
|
|
633
|
+
if (isExported(statement)) exported.add(declaration.name.text);
|
|
634
|
+
}
|
|
635
|
+
} else if (
|
|
636
|
+
ts.isExportDeclaration(statement) &&
|
|
637
|
+
statement.exportClause &&
|
|
638
|
+
ts.isNamedExports(statement.exportClause)
|
|
639
|
+
) {
|
|
640
|
+
const pairs = statement.exportClause.elements.map(
|
|
641
|
+
(element) =>
|
|
642
|
+
/** @type {[string, string]} */ ([
|
|
643
|
+
(element.propertyName ?? element.name).text,
|
|
644
|
+
element.name.text,
|
|
645
|
+
]),
|
|
646
|
+
);
|
|
647
|
+
if (statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) {
|
|
648
|
+
reexports.push({ specifier: statement.moduleSpecifier.text, names: pairs });
|
|
649
|
+
} else {
|
|
650
|
+
for (const [local, name] of pairs) if (contexts.has(local)) exported.add(name);
|
|
651
|
+
}
|
|
652
|
+
} else if (
|
|
653
|
+
ts.isExportDeclaration(statement) &&
|
|
654
|
+
statement.moduleSpecifier &&
|
|
655
|
+
ts.isStringLiteral(statement.moduleSpecifier)
|
|
656
|
+
) {
|
|
657
|
+
reexports.push({ specifier: statement.moduleSpecifier.text, names: null });
|
|
658
|
+
} else if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) {
|
|
659
|
+
if (contexts.has(statement.expression.text)) exported.add('default');
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return { contexts: [...exported], reexports };
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// ---------------------------------------------------------------- analysis
|
|
666
|
+
|
|
667
|
+
analyze() {
|
|
668
|
+
for (const statement of this.sf.statements) {
|
|
669
|
+
if (!ts.isImportDeclaration(statement) || !statement.importClause) continue;
|
|
670
|
+
const module = /** @type {ts.StringLiteral} */ (statement.moduleSpecifier).text;
|
|
671
|
+
if (module in REACT_MODULES) this.fromReact = true;
|
|
672
|
+
if (/^@tanstack\/react-(?:router|start)(?:\/|$)/.test(module)) this.routerShell = true;
|
|
673
|
+
const clause = statement.importClause;
|
|
674
|
+
const record = (
|
|
675
|
+
/** @type {ts.Node} */ declaration,
|
|
676
|
+
/** @type {ts.Identifier} */ name,
|
|
677
|
+
/** @type {string} */ imported,
|
|
678
|
+
/** @type {boolean} */ typeOnly,
|
|
679
|
+
) => {
|
|
680
|
+
const entry = { module, local: name.text, imported, namespace: imported === '*', typeOnly };
|
|
681
|
+
this.imports.set(declaration, entry);
|
|
682
|
+
if (isApiModule(module)) this.apiLocals.set(name.text, entry);
|
|
683
|
+
};
|
|
684
|
+
// A default import of React is the namespace in practice; any other
|
|
685
|
+
// module's default import is its `default` export.
|
|
686
|
+
if (clause.name) {
|
|
687
|
+
record(clause, clause.name, isApiModule(module) ? '*' : 'default', clause.isTypeOnly);
|
|
688
|
+
}
|
|
689
|
+
const bindings = clause.namedBindings;
|
|
690
|
+
if (bindings && ts.isNamespaceImport(bindings)) {
|
|
691
|
+
record(bindings, bindings.name, '*', clause.isTypeOnly);
|
|
692
|
+
}
|
|
693
|
+
if (bindings && ts.isNamedImports(bindings)) {
|
|
694
|
+
for (const element of bindings.elements) {
|
|
695
|
+
const imported = (element.propertyName ?? element.name).text;
|
|
696
|
+
record(element, element.name, imported, clause.isTypeOnly || element.isTypeOnly);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
const visit = (/** @type {ts.Node} */ node) => {
|
|
701
|
+
if (ts.isIdentifier(node) && declaresName(node)) this.declared.add(node.text);
|
|
702
|
+
if (isJsx(node)) this.hasJsx = true;
|
|
703
|
+
ts.forEachChild(node, visit);
|
|
704
|
+
};
|
|
705
|
+
visit(this.sf);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* The declaration a name refers to.
|
|
710
|
+
*
|
|
711
|
+
* @param {ts.Identifier} node
|
|
712
|
+
* @returns {ts.Declaration | null}
|
|
713
|
+
*/
|
|
714
|
+
declarationOf(node) {
|
|
715
|
+
const parent = node.parent;
|
|
716
|
+
const symbol =
|
|
717
|
+
ts.isShorthandPropertyAssignment(parent) && parent.name === node
|
|
718
|
+
? this.checker.getShorthandAssignmentValueSymbol(parent)
|
|
719
|
+
: this.checker.getSymbolAtLocation(node);
|
|
720
|
+
return symbol?.declarations?.[0] ?? null;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* The initializer of the `const` a name refers to, or null.
|
|
725
|
+
*
|
|
726
|
+
* @param {ts.Identifier} node
|
|
727
|
+
* @returns {ts.Expression | null}
|
|
728
|
+
*/
|
|
729
|
+
constValue(node) {
|
|
730
|
+
const declaration = this.declarationOf(node);
|
|
731
|
+
if (
|
|
732
|
+
!declaration ||
|
|
733
|
+
!ts.isVariableDeclaration(declaration) ||
|
|
734
|
+
!declaration.initializer ||
|
|
735
|
+
!(ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const)
|
|
736
|
+
) {
|
|
737
|
+
return null;
|
|
738
|
+
}
|
|
739
|
+
return declaration.initializer;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* The import a name refers to, or null when it refers to anything else,
|
|
744
|
+
* such as a local that shadows the import.
|
|
745
|
+
*
|
|
746
|
+
* @param {ts.Node} node
|
|
747
|
+
* @returns {Import | null}
|
|
748
|
+
*/
|
|
749
|
+
importOf(node) {
|
|
750
|
+
if (!ts.isIdentifier(node)) return null;
|
|
751
|
+
const declaration = this.declarationOf(node);
|
|
752
|
+
return declaration ? (this.imports.get(declaration) ?? null) : null;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* The React or Octane export a callee names, through a named import or a
|
|
757
|
+
* namespace.
|
|
758
|
+
*
|
|
759
|
+
* @param {ts.Node} node
|
|
760
|
+
* @returns {string | null}
|
|
761
|
+
*/
|
|
762
|
+
calleeName(node) {
|
|
763
|
+
return this.callee(node)?.name ?? null;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* @param {ts.Node} node
|
|
768
|
+
* @returns {{ name: string, module: string } | null}
|
|
769
|
+
*/
|
|
770
|
+
callee(node) {
|
|
771
|
+
if (ts.isIdentifier(node)) {
|
|
772
|
+
const entry = this.importOf(node);
|
|
773
|
+
if (!entry || entry.namespace || entry.typeOnly || !isApiModule(entry.module)) return null;
|
|
774
|
+
return { name: entry.imported, module: entry.module };
|
|
775
|
+
}
|
|
776
|
+
if (ts.isPropertyAccessExpression(node)) {
|
|
777
|
+
const entry = this.importOf(node.expression);
|
|
778
|
+
if (!entry?.namespace || !isApiModule(entry.module)) return null;
|
|
779
|
+
return { name: node.name.text, module: entry.module };
|
|
780
|
+
}
|
|
781
|
+
return null;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** @param {ts.Node} node */
|
|
785
|
+
line(node) {
|
|
786
|
+
return this.sf.getLineAndCharacterOfPosition(node.getStart(this.sf)).line + 1;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* @param {string} rule
|
|
791
|
+
* @param {Severity} severity
|
|
792
|
+
* @param {ts.Node} node
|
|
793
|
+
* @param {string} message
|
|
794
|
+
*/
|
|
795
|
+
note(rule, severity, node, message) {
|
|
796
|
+
this.notes.push({ rule, severity, line: this.line(node), message });
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** @param {string} rule */
|
|
800
|
+
count(rule) {
|
|
801
|
+
this.rules[rule] = (this.rules[rule] ?? 0) + 1;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* Request an import from Octane and return the local name to use.
|
|
806
|
+
*
|
|
807
|
+
* @param {string} module
|
|
808
|
+
* @param {string} name
|
|
809
|
+
* @param {boolean} typeOnly
|
|
810
|
+
*/
|
|
811
|
+
require(module, name, typeOnly) {
|
|
812
|
+
let names = this.added.get(module);
|
|
813
|
+
if (!names) this.added.set(module, (names = new Map()));
|
|
814
|
+
const existing = names.get(name);
|
|
815
|
+
if (existing) {
|
|
816
|
+
if (!typeOnly) existing.typeOnly = false;
|
|
817
|
+
return existing.local;
|
|
818
|
+
}
|
|
819
|
+
// A React import of the same name becomes this import.
|
|
820
|
+
const prior = this.apiLocals.get(name);
|
|
821
|
+
const collides =
|
|
822
|
+
(this.declared.has(name) || this.readsGlobal(name)) &&
|
|
823
|
+
!(prior && mapReactImport(prior.module, prior.imported, prior.typeOnly)?.name === name);
|
|
824
|
+
const local = collides ? `Octane${name[0].toUpperCase()}${name.slice(1)}` : name;
|
|
825
|
+
names.set(name, { local, typeOnly });
|
|
826
|
+
return local;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/**
|
|
830
|
+
* Whether this module declares `symbol`, rather than the library or
|
|
831
|
+
* nothing at all.
|
|
832
|
+
*
|
|
833
|
+
* @param {ts.Symbol | undefined} symbol
|
|
834
|
+
*/
|
|
835
|
+
declaresHere(symbol) {
|
|
836
|
+
return symbol?.declarations?.some((d) => d.getSourceFile() === this.sf) ?? false;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/**
|
|
840
|
+
* Whether the module reads `name` as a global, such as the DOM's
|
|
841
|
+
* `MouseEvent`, which an import of the same name would shadow.
|
|
842
|
+
*
|
|
843
|
+
* @param {string} name
|
|
844
|
+
*/
|
|
845
|
+
readsGlobal(name) {
|
|
846
|
+
/** @type {(node: ts.Node) => boolean} */
|
|
847
|
+
const visit = (node) => {
|
|
848
|
+
if (
|
|
849
|
+
ts.isIdentifier(node) &&
|
|
850
|
+
node.text === name &&
|
|
851
|
+
!isPropertyName(node) &&
|
|
852
|
+
!declaresName(node) &&
|
|
853
|
+
!this.declaresHere(this.checker.getSymbolAtLocation(node))
|
|
854
|
+
) {
|
|
855
|
+
return true;
|
|
856
|
+
}
|
|
857
|
+
return ts.forEachChild(node, visit) ?? false;
|
|
858
|
+
};
|
|
859
|
+
return visit(this.sf) === true;
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// ---------------------------------------------------------------- emission
|
|
863
|
+
|
|
864
|
+
/**
|
|
865
|
+
* The new text of `node`: a rule's replacement, or the original text with
|
|
866
|
+
* its children emitted in place.
|
|
867
|
+
*
|
|
868
|
+
* @param {ts.Node} node
|
|
869
|
+
* @param {Context} ctx
|
|
870
|
+
* @param {number} [start]
|
|
871
|
+
* @returns {string}
|
|
872
|
+
*/
|
|
873
|
+
emit(node, ctx, start) {
|
|
874
|
+
if (ts.isIdentifier(node) && this.apiLocals.has(node.text) && !this.inImport(node)) {
|
|
875
|
+
const entry = this.importOf(node);
|
|
876
|
+
if (entry) {
|
|
877
|
+
this.used.add(entry.local);
|
|
878
|
+
if (!inTypeNode(node)) this.valueUses.add(entry.local);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
const replaced = this.rewrite(node, ctx);
|
|
882
|
+
if (replaced !== null) return replaced;
|
|
883
|
+
const text = this.span(node, start ?? node.getStart(this.sf), node.end, ctx);
|
|
884
|
+
if ((ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) && text.includes('\n')) {
|
|
885
|
+
return text.replaceAll('\n', LITERAL_NEWLINE);
|
|
886
|
+
}
|
|
887
|
+
return text;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/** @param {ts.Node} node */
|
|
891
|
+
inImport(node) {
|
|
892
|
+
for (let current = node.parent; current; current = current.parent) {
|
|
893
|
+
if (ts.isImportDeclaration(current)) return true;
|
|
894
|
+
}
|
|
895
|
+
return false;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* The text of `node` between `from` and `to`, with every child inside that
|
|
900
|
+
* range emitted.
|
|
901
|
+
*
|
|
902
|
+
* @param {ts.Node} node
|
|
903
|
+
* @param {number} from
|
|
904
|
+
* @param {number} to
|
|
905
|
+
* @param {Context} ctx
|
|
906
|
+
*/
|
|
907
|
+
span(node, from, to, ctx) {
|
|
908
|
+
let out = '';
|
|
909
|
+
let cursor = from;
|
|
910
|
+
const childCtx = ts.isJsxElement(node) || ts.isJsxFragment(node) ? ctx : PLAIN;
|
|
911
|
+
node.forEachChild((child) => {
|
|
912
|
+
if (child.pos === child.end) return;
|
|
913
|
+
const start = child.getStart(this.sf);
|
|
914
|
+
if (start < from || child.end > to) return;
|
|
915
|
+
out += this.source.slice(cursor, start);
|
|
916
|
+
if (ts.isJsxAttributes(child) && child.properties.every((a) => this.removed.has(a))) {
|
|
917
|
+
out = out.replace(/[ \t]+$/, '');
|
|
918
|
+
cursor = child.end;
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
const jsxChild =
|
|
922
|
+
ts.isJsxElement(child) ||
|
|
923
|
+
ts.isJsxSelfClosingElement(child) ||
|
|
924
|
+
ts.isJsxFragment(child) ||
|
|
925
|
+
ts.isJsxExpression(child) ||
|
|
926
|
+
ts.isJsxText(child);
|
|
927
|
+
out += this.emit(child, jsxChild ? childCtx : PLAIN);
|
|
928
|
+
cursor = child.end;
|
|
929
|
+
});
|
|
930
|
+
return out + this.source.slice(cursor, to);
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/**
|
|
934
|
+
* @param {ts.Node} node
|
|
935
|
+
* @param {Context} ctx
|
|
936
|
+
* @returns {string | null}
|
|
937
|
+
*/
|
|
938
|
+
rewrite(node, ctx) {
|
|
939
|
+
if (ts.isImportDeclaration(node)) return this.rewriteImport(node);
|
|
940
|
+
if (ts.isExportDeclaration(node) && node.moduleSpecifier) return this.rewriteReexport(node);
|
|
941
|
+
if (ts.isCallExpression(node)) return this.rewriteCall(node);
|
|
942
|
+
if (ts.isPropertyAccessExpression(node)) return this.rewriteMember(node);
|
|
943
|
+
if (ts.isQualifiedName(node)) return this.rewriteQualifiedType(node);
|
|
944
|
+
if (ts.isImportTypeNode(node)) return this.rewriteImportType(node);
|
|
945
|
+
if (ts.isTypeReferenceNode(node)) return this.rewriteTypeReference(node);
|
|
946
|
+
if (ts.isExpressionStatement(node)) return this.rewriteStatement(node);
|
|
947
|
+
if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) this.checkClass(node);
|
|
948
|
+
if (ts.isBinaryExpression(node)) {
|
|
949
|
+
const guarded = this.rewriteRenderProp(node);
|
|
950
|
+
if (guarded !== null) return guarded;
|
|
951
|
+
this.checkDefaultProps(node);
|
|
952
|
+
}
|
|
953
|
+
if (ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name)) {
|
|
954
|
+
return this.rewriteSpecifier(node, node.name);
|
|
955
|
+
}
|
|
956
|
+
if (ts.isJsxText(node) && this.target === 'tsrx' && /\/[/*]/.test(node.text)) {
|
|
957
|
+
// TSRX reads `//` and `/*` in element text as comments, as JavaScript does.
|
|
958
|
+
return node.getText(this.sf).replace(/\/(?=[/*])/g, "{'/'}");
|
|
959
|
+
}
|
|
960
|
+
if (
|
|
961
|
+
ts.isIdentifier(node) &&
|
|
962
|
+
this.routerShell &&
|
|
963
|
+
Object.hasOwn(DOCUMENT_TAGS, node.text) &&
|
|
964
|
+
(ts.isJsxOpeningElement(node.parent) ||
|
|
965
|
+
ts.isJsxClosingElement(node.parent) ||
|
|
966
|
+
ts.isJsxSelfClosingElement(node.parent)) &&
|
|
967
|
+
node.parent.tagName === node
|
|
968
|
+
) {
|
|
969
|
+
// The router's document components own the hydration root.
|
|
970
|
+
if (!ts.isJsxClosingElement(node.parent)) this.count(RULE.documentShell);
|
|
971
|
+
return this.require('@octanejs/tanstack-router', DOCUMENT_TAGS[node.text], false);
|
|
972
|
+
}
|
|
973
|
+
if (ts.isJsxAttributes(node)) return this.rewriteAttributes(node);
|
|
974
|
+
if (ts.isJsxElement(node)) return this.rewriteElement(node, ctx);
|
|
975
|
+
if (ts.isJsxExpression(node) && ctx.template) return this.rewriteHole(node);
|
|
976
|
+
if (
|
|
977
|
+
ts.isFunctionDeclaration(node) ||
|
|
978
|
+
ts.isFunctionExpression(node) ||
|
|
979
|
+
ts.isArrowFunction(node)
|
|
980
|
+
) {
|
|
981
|
+
const component = this.target === 'tsrx' ? this.rewriteComponent(node) : null;
|
|
982
|
+
if (component !== null || !this.parameters.has(node) || !node.body) return component;
|
|
983
|
+
return this.head(node, node.body.getStart(this.sf)) + this.emit(node.body, PLAIN);
|
|
984
|
+
}
|
|
985
|
+
return null;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// ---------------------------------------------------------------- imports
|
|
989
|
+
|
|
990
|
+
/** @param {ts.ImportDeclaration} node */
|
|
991
|
+
rewriteImport(node) {
|
|
992
|
+
const module = /** @type {ts.StringLiteral} */ (node.moduleSpecifier).text;
|
|
993
|
+
if (module === 'octane') return null;
|
|
994
|
+
if (module === '@react-three/fiber' && this.hasJsx) {
|
|
995
|
+
this.note(
|
|
996
|
+
RULE.unsupported,
|
|
997
|
+
'error',
|
|
998
|
+
node,
|
|
999
|
+
"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)`.",
|
|
1000
|
+
);
|
|
1001
|
+
}
|
|
1002
|
+
if (module in REACT_MODULES) {
|
|
1003
|
+
this.importSlots.push(node);
|
|
1004
|
+
return `\u0000IMPORT${this.importSlots.length - 1}\u0000`;
|
|
1005
|
+
}
|
|
1006
|
+
return this.rewriteSpecifier(node, node.moduleSpecifier);
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/** @param {ts.ExportDeclaration} node */
|
|
1010
|
+
rewriteReexport(node) {
|
|
1011
|
+
const module = /** @type {ts.StringLiteral} */ (node.moduleSpecifier).text;
|
|
1012
|
+
const mapped = REACT_MODULES[module];
|
|
1013
|
+
if (mapped) {
|
|
1014
|
+
this.count(RULE.import);
|
|
1015
|
+
return this.replaceSpecifier(
|
|
1016
|
+
node,
|
|
1017
|
+
/** @type {ts.Expression} */ (node.moduleSpecifier),
|
|
1018
|
+
mapped,
|
|
1019
|
+
);
|
|
1020
|
+
}
|
|
1021
|
+
return this.rewriteSpecifier(node, /** @type {ts.Expression} */ (node.moduleSpecifier));
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
/**
|
|
1025
|
+
* @param {ts.Node} node
|
|
1026
|
+
* @param {ts.Expression} specifier
|
|
1027
|
+
*/
|
|
1028
|
+
rewriteSpecifier(node, specifier) {
|
|
1029
|
+
if (!ts.isStringLiteral(specifier)) return null;
|
|
1030
|
+
const next = this.options.resolveSpecifier?.(specifier.text) ?? null;
|
|
1031
|
+
if (next === null || next === specifier.text) return null;
|
|
1032
|
+
this.count(RULE.import);
|
|
1033
|
+
return this.replaceSpecifier(node, specifier, next);
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
/**
|
|
1037
|
+
* @param {ts.Node} node
|
|
1038
|
+
* @param {ts.Expression} specifier
|
|
1039
|
+
* @param {string} next
|
|
1040
|
+
*/
|
|
1041
|
+
replaceSpecifier(node, specifier, next) {
|
|
1042
|
+
const quote = this.source[specifier.getStart(this.sf)];
|
|
1043
|
+
return (
|
|
1044
|
+
this.span(node, node.getStart(this.sf), specifier.getStart(this.sf), PLAIN) +
|
|
1045
|
+
quote +
|
|
1046
|
+
next +
|
|
1047
|
+
quote +
|
|
1048
|
+
// The rest is emitted, not copied: `import('./x').T<import('react').U>`
|
|
1049
|
+
// has a nested specifier of its own.
|
|
1050
|
+
this.span(node, specifier.end, node.end, PLAIN)
|
|
1051
|
+
);
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* `import('react').ReactNode` in a type: the module, and a React type name
|
|
1056
|
+
* Octane spells differently, follow the same map as static imports.
|
|
1057
|
+
*
|
|
1058
|
+
* @param {ts.ImportTypeNode} node
|
|
1059
|
+
*/
|
|
1060
|
+
rewriteImportType(node) {
|
|
1061
|
+
const argument = node.argument;
|
|
1062
|
+
if (!ts.isLiteralTypeNode(argument) || !ts.isStringLiteral(argument.literal)) return null;
|
|
1063
|
+
const specifier = argument.literal;
|
|
1064
|
+
const module = REACT_MODULES[specifier.text];
|
|
1065
|
+
if (module === undefined) return this.rewriteSpecifier(node, specifier);
|
|
1066
|
+
this.count(RULE.import);
|
|
1067
|
+
const qualifier = node.qualifier;
|
|
1068
|
+
const name = qualifier && ts.isIdentifier(qualifier) ? qualifier.text : null;
|
|
1069
|
+
const renamed = name === null ? null : mapQualifiedType(name);
|
|
1070
|
+
if (name !== null && renamed === null) {
|
|
1071
|
+
this.note(RULE.unsupported, 'warning', node, `Octane has no type \`${name}\`.`);
|
|
1072
|
+
}
|
|
1073
|
+
const quote = this.source[specifier.getStart(this.sf)];
|
|
1074
|
+
const head =
|
|
1075
|
+
this.span(node, node.getStart(this.sf), specifier.getStart(this.sf), PLAIN) +
|
|
1076
|
+
quote +
|
|
1077
|
+
module +
|
|
1078
|
+
quote;
|
|
1079
|
+
if (!qualifier || renamed === null || renamed === name) {
|
|
1080
|
+
return head + this.span(node, specifier.end, node.end, PLAIN);
|
|
1081
|
+
}
|
|
1082
|
+
return (
|
|
1083
|
+
head +
|
|
1084
|
+
this.source.slice(specifier.end, qualifier.getStart(this.sf)) +
|
|
1085
|
+
renamed +
|
|
1086
|
+
this.span(node, qualifier.end, node.end, PLAIN)
|
|
1087
|
+
);
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
/**
|
|
1091
|
+
* Fill each React import placeholder. The first one carries every Octane
|
|
1092
|
+
* import the module needs, the module's own specifiers first; the others
|
|
1093
|
+
* disappear with their line.
|
|
1094
|
+
*
|
|
1095
|
+
* @param {string} code
|
|
1096
|
+
*/
|
|
1097
|
+
finishImports(code) {
|
|
1098
|
+
/** @type {Map<string, Map<string, { name: string, local: string, typeOnly: boolean }>>} */
|
|
1099
|
+
const imports = new Map();
|
|
1100
|
+
const add = (
|
|
1101
|
+
/** @type {string} */ module,
|
|
1102
|
+
/** @type {string} */ name,
|
|
1103
|
+
/** @type {string} */ local,
|
|
1104
|
+
/** @type {boolean} */ typeOnly,
|
|
1105
|
+
) => {
|
|
1106
|
+
let names = imports.get(module);
|
|
1107
|
+
if (!names) imports.set(module, (names = new Map()));
|
|
1108
|
+
const existing = names.get(`${name} ${local}`);
|
|
1109
|
+
if (existing) existing.typeOnly &&= typeOnly;
|
|
1110
|
+
else names.set(`${name} ${local}`, { name, local, typeOnly });
|
|
1111
|
+
};
|
|
1112
|
+
/** React specifiers with no Octane export stay on React, for a person. */
|
|
1113
|
+
const kept = new Map();
|
|
1114
|
+
for (const node of this.importSlots) {
|
|
1115
|
+
const module = /** @type {ts.StringLiteral} */ (node.moduleSpecifier).text;
|
|
1116
|
+
const clause = node.importClause;
|
|
1117
|
+
if (!clause) continue;
|
|
1118
|
+
const bindings = clause.namedBindings;
|
|
1119
|
+
const namespace =
|
|
1120
|
+
clause.name?.text ??
|
|
1121
|
+
(bindings && ts.isNamespaceImport(bindings) ? bindings.name.text : null);
|
|
1122
|
+
// Members the rewrite could not map keep the namespace alive.
|
|
1123
|
+
if (namespace && this.used.has(namespace)) add(REACT_MODULES[module], '*', namespace, false);
|
|
1124
|
+
if (!bindings || !ts.isNamedImports(bindings)) continue;
|
|
1125
|
+
for (const element of bindings.elements) {
|
|
1126
|
+
const local = element.name.text;
|
|
1127
|
+
if (!this.used.has(local)) continue;
|
|
1128
|
+
const imported = (element.propertyName ?? element.name).text;
|
|
1129
|
+
const typeOnly = clause.isTypeOnly || element.isTypeOnly;
|
|
1130
|
+
const mapped = mapReactImport(module, imported, typeOnly);
|
|
1131
|
+
if (mapped) {
|
|
1132
|
+
// A name read only in types imports as a type, which bundlers elide.
|
|
1133
|
+
add(mapped.module, mapped.name, local, typeOnly || !this.valueUses.has(local));
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
this.note(
|
|
1137
|
+
RULE.unsupported,
|
|
1138
|
+
'error',
|
|
1139
|
+
element,
|
|
1140
|
+
UNSUPPORTED_VALUES[imported] ??
|
|
1141
|
+
`\`${imported}\` from '${module}' has no Octane equivalent.`,
|
|
1142
|
+
);
|
|
1143
|
+
const spec =
|
|
1144
|
+
(typeOnly ? 'type ' : '') + (imported === local ? local : `${imported} as ${local}`);
|
|
1145
|
+
kept.set(module, [...(kept.get(module) ?? []), spec]);
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
for (const [module, names] of this.added) {
|
|
1149
|
+
for (const [name, { local, typeOnly }] of names) add(module, name, local, typeOnly);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
/** @type {string[]} */
|
|
1153
|
+
const lines = [];
|
|
1154
|
+
for (const [module, names] of imports) {
|
|
1155
|
+
const specs = [...names.values()];
|
|
1156
|
+
for (const { name, local } of specs) {
|
|
1157
|
+
if (name === '*') lines.push(`import * as ${local} from '${module}';`);
|
|
1158
|
+
}
|
|
1159
|
+
const named = specs.filter(({ name }) => name !== '*');
|
|
1160
|
+
if (named.length === 0) continue;
|
|
1161
|
+
const allTypes = named.every(({ typeOnly }) => typeOnly);
|
|
1162
|
+
const list = named.map(
|
|
1163
|
+
({ name, local, typeOnly }) =>
|
|
1164
|
+
(typeOnly && !allTypes ? 'type ' : '') + (name === local ? name : `${name} as ${local}`),
|
|
1165
|
+
);
|
|
1166
|
+
lines.push(`import ${allTypes ? 'type ' : ''}{ ${list.join(', ')} } from '${module}';`);
|
|
1167
|
+
}
|
|
1168
|
+
for (const [module, specs] of kept)
|
|
1169
|
+
lines.push(`import { ${specs.join(', ')} } from '${module}';`);
|
|
1170
|
+
|
|
1171
|
+
if (this.importSlots.length === 0) {
|
|
1172
|
+
if (lines.length === 0) return code;
|
|
1173
|
+
const at = this.insertionPoint(code);
|
|
1174
|
+
return code.slice(0, at) + lines.join('\n') + '\n' + code.slice(at);
|
|
1175
|
+
}
|
|
1176
|
+
this.count(RULE.import);
|
|
1177
|
+
return code.replace(/\u0000IMPORT(\d+)\u0000(\r?\n)?/g, (_, index, newline) =>
|
|
1178
|
+
index === '0' && lines.length > 0 ? lines.join('\n') + (newline ?? '') : '',
|
|
1179
|
+
);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
/**
|
|
1183
|
+
* Where new imports go when the module imported nothing from React: after
|
|
1184
|
+
* the directive prologue and any leading comments.
|
|
1185
|
+
*
|
|
1186
|
+
* @param {string} code
|
|
1187
|
+
*/
|
|
1188
|
+
insertionPoint(code) {
|
|
1189
|
+
// Whole lines only: a shebang, blank lines, comments that end their
|
|
1190
|
+
// line, and directive lines. Anything inserted here starts a line, so
|
|
1191
|
+
// the Strong fallback can find its own directive line again.
|
|
1192
|
+
const prologue =
|
|
1193
|
+
/^(?:#![^\n]*\n)?(?:[ \t]*(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/[ \t]*|(['"])use [a-z ]+\1;?[^\n]*)?\r?\n)*/.exec(
|
|
1194
|
+
code,
|
|
1195
|
+
);
|
|
1196
|
+
return prologue ? prologue[0].length : 0;
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
/** @param {string} code */
|
|
1200
|
+
addStrongDirective(code) {
|
|
1201
|
+
this.count(RULE.strong);
|
|
1202
|
+
const at = this.insertionPoint(code);
|
|
1203
|
+
return code.slice(0, at) + '"use strong";\n' + (at === 0 ? '\n' : '') + code.slice(at);
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
/** @param {string} code */
|
|
1207
|
+
addJsxPragma(code) {
|
|
1208
|
+
if (/@jsxImportSource\s+octane/.test(code)) return code;
|
|
1209
|
+
const replaced = code.replace(/@jsxImportSource\s+\S+/, '@jsxImportSource octane');
|
|
1210
|
+
return replaced !== code ? replaced : '/** @jsxImportSource octane */\n' + code;
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// ---------------------------------------------------------------- APIs
|
|
1214
|
+
|
|
1215
|
+
/** @param {ts.PropertyAccessExpression} node */
|
|
1216
|
+
rewriteMember(node) {
|
|
1217
|
+
// `<Ctx.Provider value>` is `<Ctx value>` in Octane, as in React 19.
|
|
1218
|
+
const tag = node.parent;
|
|
1219
|
+
const isTag =
|
|
1220
|
+
(ts.isJsxOpeningElement(tag) ||
|
|
1221
|
+
ts.isJsxClosingElement(tag) ||
|
|
1222
|
+
ts.isJsxSelfClosingElement(tag)) &&
|
|
1223
|
+
tag.tagName === node;
|
|
1224
|
+
// So is `const P = C.Provider`; a member of the provider (`C.Provider.x`)
|
|
1225
|
+
// or a write to it stays.
|
|
1226
|
+
const isValue =
|
|
1227
|
+
!isTag &&
|
|
1228
|
+
!(ts.isPropertyAccessExpression(tag) && tag.expression === node) &&
|
|
1229
|
+
!(ts.isBinaryExpression(tag) && tag.left === node);
|
|
1230
|
+
if (node.name.text === 'Provider' && (isTag || isValue) && this.isContext(node.expression)) {
|
|
1231
|
+
if (!ts.isJsxClosingElement(tag)) this.count(RULE.provider);
|
|
1232
|
+
return this.emit(node.expression, PLAIN);
|
|
1233
|
+
}
|
|
1234
|
+
const namespace = this.importOf(node.expression);
|
|
1235
|
+
if (namespace?.namespace && namespace.module in REACT_MODULES) {
|
|
1236
|
+
const name = node.name.text;
|
|
1237
|
+
const mapped = mapReactImport(namespace.module, name, false);
|
|
1238
|
+
if (!mapped) {
|
|
1239
|
+
this.used.add(namespace.local);
|
|
1240
|
+
this.note(
|
|
1241
|
+
RULE.unsupported,
|
|
1242
|
+
'error',
|
|
1243
|
+
node,
|
|
1244
|
+
UNSUPPORTED_VALUES[name] ?? `\`${node.getText(this.sf)}\` has no Octane equivalent.`,
|
|
1245
|
+
);
|
|
1246
|
+
return null;
|
|
1247
|
+
}
|
|
1248
|
+
this.count(RULE.import);
|
|
1249
|
+
return this.require(mapped.module, mapped.name, false);
|
|
1250
|
+
}
|
|
1251
|
+
// event.nativeEvent: Octane events are already native.
|
|
1252
|
+
if (node.name.text === 'nativeEvent' && this.isEventParameter(node.expression)) {
|
|
1253
|
+
this.count(RULE.eventObject);
|
|
1254
|
+
return this.emit(node.expression, PLAIN);
|
|
1255
|
+
}
|
|
1256
|
+
if (node.name.text === 'target' && this.targetsControl(node.expression)) {
|
|
1257
|
+
this.count(RULE.eventObject);
|
|
1258
|
+
return this.emit(node.expression, PLAIN) + '.currentTarget';
|
|
1259
|
+
}
|
|
1260
|
+
return null;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/** @param {ts.QualifiedName} node */
|
|
1264
|
+
rewriteQualifiedType(node) {
|
|
1265
|
+
const namespace = this.importOf(node.left);
|
|
1266
|
+
if (!namespace?.namespace || !(namespace.module in REACT_MODULES)) return null;
|
|
1267
|
+
const name = mapQualifiedType(node.right.text);
|
|
1268
|
+
if (!name) {
|
|
1269
|
+
this.used.add(namespace.local);
|
|
1270
|
+
this.note(
|
|
1271
|
+
RULE.unsupported,
|
|
1272
|
+
'warning',
|
|
1273
|
+
node,
|
|
1274
|
+
`Octane has no type \`${node.getText(this.sf)}\`.`,
|
|
1275
|
+
);
|
|
1276
|
+
return null;
|
|
1277
|
+
}
|
|
1278
|
+
this.count(RULE.import);
|
|
1279
|
+
return this.require('octane', name, true);
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/** @param {ts.TypeReferenceNode} node */
|
|
1283
|
+
rewriteTypeReference(node) {
|
|
1284
|
+
// The global `JSX` namespace React's types declared is Octane's export.
|
|
1285
|
+
const name = node.typeName;
|
|
1286
|
+
if (
|
|
1287
|
+
ts.isQualifiedName(name) &&
|
|
1288
|
+
ts.isIdentifier(name.left) &&
|
|
1289
|
+
name.left.text === 'JSX' &&
|
|
1290
|
+
!this.checker.resolveName('JSX', node, ts.SymbolFlags.Namespace, false)
|
|
1291
|
+
) {
|
|
1292
|
+
this.require('octane', 'JSX', true);
|
|
1293
|
+
}
|
|
1294
|
+
return null;
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
/** @param {ts.CallExpression} node */
|
|
1298
|
+
rewriteCall(node) {
|
|
1299
|
+
if (node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0]) {
|
|
1300
|
+
const [specifier] = node.arguments;
|
|
1301
|
+
const mapped = ts.isStringLiteral(specifier) ? REACT_MODULES[specifier.text] : undefined;
|
|
1302
|
+
if (mapped === undefined) return this.rewriteSpecifier(node, specifier);
|
|
1303
|
+
this.count(RULE.import);
|
|
1304
|
+
return this.replaceSpecifier(node, specifier, mapped);
|
|
1305
|
+
}
|
|
1306
|
+
if (
|
|
1307
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
1308
|
+
node.expression.name.text === 'render' &&
|
|
1309
|
+
node.arguments.length === 1 &&
|
|
1310
|
+
this.isRoot(node.expression.expression)
|
|
1311
|
+
) {
|
|
1312
|
+
return this.rewriteRootRender(node, node.arguments[0]);
|
|
1313
|
+
}
|
|
1314
|
+
const callee = this.callee(node.expression);
|
|
1315
|
+
// An Octane hook without a list already means "inferred".
|
|
1316
|
+
if (!callee || callee.module === 'octane') return null;
|
|
1317
|
+
const name = callee.name;
|
|
1318
|
+
if (name === 'forwardRef') return this.rewriteForwardRef(node);
|
|
1319
|
+
if (name === 'render' || name === 'hydrate') return this.rewriteLegacyRoot(node, name);
|
|
1320
|
+
if (name === 'hydrateRoot' && node.arguments.length === 2) {
|
|
1321
|
+
return this.rewriteRootRender(node, node.arguments[1]);
|
|
1322
|
+
}
|
|
1323
|
+
if (
|
|
1324
|
+
(name === 'renderToString' || name === 'renderToStaticMarkup') &&
|
|
1325
|
+
callee.module.startsWith('react-dom/server') &&
|
|
1326
|
+
node.arguments.length === 1
|
|
1327
|
+
) {
|
|
1328
|
+
// React returns the HTML; Octane returns `{ html, css }`.
|
|
1329
|
+
this.count(RULE.serverRender);
|
|
1330
|
+
return (
|
|
1331
|
+
(this.rewriteRootRender(node, node.arguments[0]) ??
|
|
1332
|
+
this.span(node, node.getStart(this.sf), node.end, PLAIN)) + '.html'
|
|
1333
|
+
);
|
|
1334
|
+
}
|
|
1335
|
+
if (name === 'flushSync') {
|
|
1336
|
+
this.note(
|
|
1337
|
+
RULE.flushSync,
|
|
1338
|
+
'warning',
|
|
1339
|
+
node,
|
|
1340
|
+
"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.",
|
|
1341
|
+
);
|
|
1342
|
+
return null;
|
|
1343
|
+
}
|
|
1344
|
+
if (name in DEPENDENCY_HOOKS) return this.rewriteDependencies(node, name);
|
|
1345
|
+
return null;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
/**
|
|
1349
|
+
* React runs an effect or memo without a dependency list on every render.
|
|
1350
|
+
* Octane infers the list instead, so compatibility output passes `null` to
|
|
1351
|
+
* keep React's behavior. Strong output leaves it to the compiler, which is
|
|
1352
|
+
* what Strong asks for.
|
|
1353
|
+
*
|
|
1354
|
+
* @param {ts.CallExpression} node
|
|
1355
|
+
* @param {string} name
|
|
1356
|
+
*/
|
|
1357
|
+
rewriteDependencies(node, name) {
|
|
1358
|
+
if (node.arguments.length !== DEPENDENCY_HOOKS[name]) return null;
|
|
1359
|
+
if (this.strong) {
|
|
1360
|
+
this.note(
|
|
1361
|
+
RULE.deps,
|
|
1362
|
+
'info',
|
|
1363
|
+
node,
|
|
1364
|
+
`\`${name}\` had no dependency list, so React ran it on every render; Strong infers its dependencies.`,
|
|
1365
|
+
);
|
|
1366
|
+
return null;
|
|
1367
|
+
}
|
|
1368
|
+
this.count(RULE.deps);
|
|
1369
|
+
const last = node.arguments[node.arguments.length - 1];
|
|
1370
|
+
return (
|
|
1371
|
+
this.span(node, node.getStart(this.sf), last.end, PLAIN) +
|
|
1372
|
+
', null' +
|
|
1373
|
+
this.source.slice(last.end, node.end)
|
|
1374
|
+
);
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
/**
|
|
1378
|
+
* `forwardRef((props, ref) => …)` becomes the inner function with `ref`
|
|
1379
|
+
* read from props.
|
|
1380
|
+
*
|
|
1381
|
+
* @param {ts.CallExpression} node
|
|
1382
|
+
*/
|
|
1383
|
+
rewriteForwardRef(node) {
|
|
1384
|
+
const [render] = node.arguments;
|
|
1385
|
+
if (
|
|
1386
|
+
node.arguments.length !== 1 ||
|
|
1387
|
+
!(ts.isArrowFunction(render) || ts.isFunctionExpression(render)) ||
|
|
1388
|
+
render.parameters.length > 2
|
|
1389
|
+
) {
|
|
1390
|
+
this.note(
|
|
1391
|
+
RULE.forwardRef,
|
|
1392
|
+
'error',
|
|
1393
|
+
node,
|
|
1394
|
+
'Unwrap this `forwardRef`: refs are ordinary props in Octane.',
|
|
1395
|
+
);
|
|
1396
|
+
return null;
|
|
1397
|
+
}
|
|
1398
|
+
this.count(RULE.forwardRef);
|
|
1399
|
+
const [props, ref] = render.parameters;
|
|
1400
|
+
const typeArgs = node.typeArguments;
|
|
1401
|
+
const refType = typeArgs?.[0]?.getText(this.sf) ?? this.refTypeOf(ref);
|
|
1402
|
+
const propsType =
|
|
1403
|
+
typeArgs?.[1]?.getText(this.sf) ?? (props?.type ? this.emit(props.type, PLAIN) : null);
|
|
1404
|
+
const refName = ref && ts.isIdentifier(ref.name) ? ref.name.text : null;
|
|
1405
|
+
const refBinding = refName === null ? null : refName === 'ref' ? 'ref' : `ref: ${refName}`;
|
|
1406
|
+
|
|
1407
|
+
// Splice `ref` into the props pattern in the pattern's own layout.
|
|
1408
|
+
let pattern;
|
|
1409
|
+
if (!props) pattern = refBinding ? `{ ${refBinding} }` : null;
|
|
1410
|
+
else if (refBinding === null) pattern = this.emit(props.name, PLAIN);
|
|
1411
|
+
else if (ts.isObjectBindingPattern(props.name)) {
|
|
1412
|
+
const elements = props.name.elements;
|
|
1413
|
+
const rest = elements.find((element) => element.dotDotDotToken);
|
|
1414
|
+
const last = elements[elements.length - 1];
|
|
1415
|
+
const multiline = this.source
|
|
1416
|
+
.slice(props.name.getStart(this.sf), props.name.end)
|
|
1417
|
+
.includes('\n');
|
|
1418
|
+
if (rest) {
|
|
1419
|
+
const separator = multiline ? `,\n${this.indentOf(rest)}` : ', ';
|
|
1420
|
+
pattern =
|
|
1421
|
+
this.span(props.name, props.name.getStart(this.sf), rest.getStart(this.sf), PLAIN) +
|
|
1422
|
+
refBinding +
|
|
1423
|
+
separator +
|
|
1424
|
+
this.span(props.name, rest.getStart(this.sf), props.name.end, PLAIN);
|
|
1425
|
+
} else if (last) {
|
|
1426
|
+
const separator = multiline ? `,\n${this.indentOf(last)}` : ', ';
|
|
1427
|
+
pattern =
|
|
1428
|
+
this.span(props.name, props.name.getStart(this.sf), last.end, PLAIN) +
|
|
1429
|
+
separator +
|
|
1430
|
+
refBinding +
|
|
1431
|
+
this.source.slice(last.end, props.name.end);
|
|
1432
|
+
} else pattern = `{ ${refBinding} }`;
|
|
1433
|
+
} else if (ts.isIdentifier(props.name) && props.name.text !== '_') {
|
|
1434
|
+
pattern = `{ ${refBinding}, ...${props.name.text} }`;
|
|
1435
|
+
} else {
|
|
1436
|
+
pattern = `{ ${refBinding} }`;
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
let annotation = '';
|
|
1440
|
+
if (this.isTypeScript() && (propsType || refType)) {
|
|
1441
|
+
const refProp = refType ? `{ ref?: ${this.require('octane', 'Ref', true)}<${refType}> }` : '';
|
|
1442
|
+
annotation = ': ' + [propsType, refProp].filter(Boolean).join(' & ');
|
|
1443
|
+
}
|
|
1444
|
+
// Keep the parameter list's layout: the props parameter is replaced in
|
|
1445
|
+
// place and the ref parameter goes with the comma before it.
|
|
1446
|
+
const list = render.parameters;
|
|
1447
|
+
let parameters;
|
|
1448
|
+
if (pattern === null) parameters = '';
|
|
1449
|
+
else if (!props) parameters = pattern + annotation;
|
|
1450
|
+
else {
|
|
1451
|
+
parameters =
|
|
1452
|
+
this.source.slice(list.pos, props.getStart(this.sf)) +
|
|
1453
|
+
pattern +
|
|
1454
|
+
annotation +
|
|
1455
|
+
this.source.slice(ref ? ref.end : props.end, list.end);
|
|
1456
|
+
}
|
|
1457
|
+
this.parameters.set(render, parameters);
|
|
1458
|
+
return this.emit(render, PLAIN);
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/**
|
|
1462
|
+
* A function's text up to its body, with any parameters a rule replaced.
|
|
1463
|
+
*
|
|
1464
|
+
* @param {ts.SignatureDeclaration & { body?: ts.Node }} node
|
|
1465
|
+
* @param {number} end
|
|
1466
|
+
*/
|
|
1467
|
+
head(node, end) {
|
|
1468
|
+
const parameters = this.parameters.get(node);
|
|
1469
|
+
if (parameters === undefined) return this.span(node, node.getStart(this.sf), end, PLAIN);
|
|
1470
|
+
return (
|
|
1471
|
+
this.span(node, node.getStart(this.sf), node.parameters.pos, PLAIN) +
|
|
1472
|
+
parameters +
|
|
1473
|
+
this.span(node, node.parameters.end, end, PLAIN)
|
|
1474
|
+
);
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
/** @param {ts.ParameterDeclaration | undefined} ref */
|
|
1478
|
+
refTypeOf(ref) {
|
|
1479
|
+
const type = ref?.type;
|
|
1480
|
+
if (type && ts.isTypeReferenceNode(type) && type.typeArguments?.length === 1) {
|
|
1481
|
+
return type.typeArguments[0].getText(this.sf);
|
|
1482
|
+
}
|
|
1483
|
+
return null;
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
isTypeScript() {
|
|
1487
|
+
return /\.[cm]?tsx?$/.test(this.filename);
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
/**
|
|
1491
|
+
* @param {ts.CallExpression} node
|
|
1492
|
+
* @param {'render' | 'hydrate'} name
|
|
1493
|
+
*/
|
|
1494
|
+
rewriteLegacyRoot(node, name) {
|
|
1495
|
+
const [element, container, callback] = node.arguments;
|
|
1496
|
+
if (!element || !container) return null;
|
|
1497
|
+
if (callback) {
|
|
1498
|
+
this.note(
|
|
1499
|
+
RULE.legacyRoot,
|
|
1500
|
+
'warning',
|
|
1501
|
+
node,
|
|
1502
|
+
'The legacy render callback was dropped; run it from an effect.',
|
|
1503
|
+
);
|
|
1504
|
+
}
|
|
1505
|
+
this.count(RULE.legacyRoot);
|
|
1506
|
+
const elementText = this.rootComponent(element) ?? this.emit(element, PLAIN);
|
|
1507
|
+
const containerText = this.emit(container, PLAIN);
|
|
1508
|
+
return name === 'render'
|
|
1509
|
+
? `${this.require('octane', 'createRoot', false)}(${containerText}).render(${elementText})`
|
|
1510
|
+
: `${this.require('octane', 'hydrateRoot', false)}(${containerText}, ${elementText})`;
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
/**
|
|
1514
|
+
* Whether `node` is a root `createRoot` made: the call itself, or a
|
|
1515
|
+
* `const` bound to it.
|
|
1516
|
+
*
|
|
1517
|
+
* @param {ts.Expression} node
|
|
1518
|
+
*/
|
|
1519
|
+
isRoot(node) {
|
|
1520
|
+
node = skipParens(node);
|
|
1521
|
+
const value = ts.isIdentifier(node) ? this.constValue(node) : node;
|
|
1522
|
+
return (
|
|
1523
|
+
!!value && ts.isCallExpression(value) && this.calleeName(value.expression) === 'createRoot'
|
|
1524
|
+
);
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
/**
|
|
1528
|
+
* `root.render(<App a={1} />)` and `root.render(createElement(App, props))`
|
|
1529
|
+
* are `root.render(App, props)`, which mounts the component without an
|
|
1530
|
+
* element: the generic element renderer stays out of the bundle. So are
|
|
1531
|
+
* `hydrateRoot(c, <App />)` and the server renderers' element argument.
|
|
1532
|
+
*
|
|
1533
|
+
* @param {ts.CallExpression} node
|
|
1534
|
+
* @param {ts.Expression} argument the element, the call's last argument
|
|
1535
|
+
*/
|
|
1536
|
+
rewriteRootRender(node, argument) {
|
|
1537
|
+
const component = this.rootComponent(argument);
|
|
1538
|
+
if (component === null) return null;
|
|
1539
|
+
this.count(RULE.rootRender);
|
|
1540
|
+
return (
|
|
1541
|
+
this.span(node, node.getStart(this.sf), argument.getStart(this.sf), PLAIN) +
|
|
1542
|
+
component +
|
|
1543
|
+
this.span(node, argument.end, node.end, PLAIN)
|
|
1544
|
+
);
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
/**
|
|
1548
|
+
* `App` or `App, props` for an element of a component with no key, ref,
|
|
1549
|
+
* or children, through a `<StrictMode>` wrapper, else null.
|
|
1550
|
+
*
|
|
1551
|
+
* @param {ts.Expression} expression
|
|
1552
|
+
* @returns {string | null}
|
|
1553
|
+
*/
|
|
1554
|
+
rootComponent(expression) {
|
|
1555
|
+
let node = skipParens(expression);
|
|
1556
|
+
if (ts.isJsxElement(node) && this.calleeName(node.openingElement.tagName) === 'StrictMode') {
|
|
1557
|
+
const children = node.children.filter(
|
|
1558
|
+
(child) => !(ts.isJsxText(child) && child.containsOnlyTriviaWhiteSpaces),
|
|
1559
|
+
);
|
|
1560
|
+
if (children.length !== 1 || !isJsx(children[0])) return null;
|
|
1561
|
+
node = /** @type {ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment} */ (children[0]);
|
|
1562
|
+
}
|
|
1563
|
+
if (ts.isJsxSelfClosingElement(node)) {
|
|
1564
|
+
const tag = node.tagName;
|
|
1565
|
+
if (!ts.isIdentifier(tag) && !ts.isPropertyAccessExpression(tag)) return null;
|
|
1566
|
+
if (!isComponentName(tag.getText(this.sf).split('.').pop() ?? '')) return null;
|
|
1567
|
+
/** @type {string[]} */
|
|
1568
|
+
const props = [];
|
|
1569
|
+
for (const property of node.attributes.properties) {
|
|
1570
|
+
if (ts.isJsxSpreadAttribute(property)) {
|
|
1571
|
+
props.push(`...${this.emit(property.expression, PLAIN)}`);
|
|
1572
|
+
continue;
|
|
1573
|
+
}
|
|
1574
|
+
const name = property.name.getText(this.sf);
|
|
1575
|
+
if (name === 'key' || name === 'ref') return null;
|
|
1576
|
+
const key = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
|
|
1577
|
+
const value = property.initializer;
|
|
1578
|
+
if (!value) props.push(`${key}: true`);
|
|
1579
|
+
else if (ts.isStringLiteral(value)) props.push(`${key}: ${value.getText(this.sf)}`);
|
|
1580
|
+
else if (ts.isJsxExpression(value) && value.expression)
|
|
1581
|
+
props.push(`${key}: ${this.emit(value.expression, PLAIN)}`);
|
|
1582
|
+
else return null;
|
|
1583
|
+
}
|
|
1584
|
+
const type = this.emit(tag, PLAIN);
|
|
1585
|
+
return props.length === 0 ? type : `${type}, { ${props.join(', ')} }`;
|
|
1586
|
+
}
|
|
1587
|
+
if (ts.isCallExpression(node) && this.calleeName(node.expression) === 'createElement') {
|
|
1588
|
+
const [type, props, ...children] = node.arguments;
|
|
1589
|
+
if (!type || children.length > 0) return null;
|
|
1590
|
+
if (!(ts.isIdentifier(type) || ts.isPropertyAccessExpression(type))) return null;
|
|
1591
|
+
if (!isComponentName(type.getText(this.sf).split('.').pop() ?? '')) return null;
|
|
1592
|
+
const text = this.emit(type, PLAIN);
|
|
1593
|
+
return !props || isNullish(props) ? text : `${text}, ${this.emit(props, PLAIN)}`;
|
|
1594
|
+
}
|
|
1595
|
+
return null;
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
/** @param {ts.ExpressionStatement} node */
|
|
1599
|
+
rewriteStatement(node) {
|
|
1600
|
+
const call = node.expression;
|
|
1601
|
+
if (
|
|
1602
|
+
ts.isCallExpression(call) &&
|
|
1603
|
+
call.arguments.length === 0 &&
|
|
1604
|
+
ts.isPropertyAccessExpression(call.expression) &&
|
|
1605
|
+
call.expression.name.text === 'persist' &&
|
|
1606
|
+
this.isEventParameter(call.expression.expression)
|
|
1607
|
+
) {
|
|
1608
|
+
// Octane never pools events, so there is nothing to persist.
|
|
1609
|
+
this.count(RULE.eventObject);
|
|
1610
|
+
return DROP;
|
|
1611
|
+
}
|
|
1612
|
+
return null;
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
/**
|
|
1616
|
+
* The parameter `node` refers to, with its function.
|
|
1617
|
+
*
|
|
1618
|
+
* @param {ts.Node} node
|
|
1619
|
+
* @returns {{ fn: ts.SignatureDeclaration, param: ts.ParameterDeclaration } | null}
|
|
1620
|
+
*/
|
|
1621
|
+
parameterOf(node) {
|
|
1622
|
+
if (!ts.isIdentifier(node)) return null;
|
|
1623
|
+
const param = this.declarationOf(node);
|
|
1624
|
+
if (!param || !ts.isParameter(param)) return null;
|
|
1625
|
+
return { fn: /** @type {ts.SignatureDeclaration} */ (param.parent), param };
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
/** @param {ts.Node} node */
|
|
1629
|
+
isEventParameter(node) {
|
|
1630
|
+
const found = this.parameterOf(node);
|
|
1631
|
+
if (!found) return false;
|
|
1632
|
+
const type = found.param.type;
|
|
1633
|
+
if (type && ts.isTypeReferenceNode(type) && /Event$/.test(type.typeName.getText(this.sf))) {
|
|
1634
|
+
return true;
|
|
1635
|
+
}
|
|
1636
|
+
return this.handlerAttribute(found.fn) !== null;
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
/**
|
|
1640
|
+
* The `on*` attribute an inline handler is passed to.
|
|
1641
|
+
*
|
|
1642
|
+
* @param {ts.Node} fn
|
|
1643
|
+
*/
|
|
1644
|
+
handlerAttribute(fn) {
|
|
1645
|
+
const container = fn.parent;
|
|
1646
|
+
if (!container || !ts.isJsxExpression(container)) return null;
|
|
1647
|
+
const attribute = container.parent;
|
|
1648
|
+
return ts.isJsxAttribute(attribute) && /^on[A-Z]/.test(attribute.name.getText(this.sf))
|
|
1649
|
+
? attribute
|
|
1650
|
+
: null;
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
/**
|
|
1654
|
+
* Whether `event.target` is the form control the handler is attached to, so
|
|
1655
|
+
* it can read Octane's typed `currentTarget` instead. Octane types events as
|
|
1656
|
+
* the native `Event`, whose `target` is an untyped `EventTarget`.
|
|
1657
|
+
*
|
|
1658
|
+
* @param {ts.Node} node
|
|
1659
|
+
*/
|
|
1660
|
+
targetsControl(node) {
|
|
1661
|
+
const found = this.parameterOf(node);
|
|
1662
|
+
if (!found) return false;
|
|
1663
|
+
const type = found.param.type?.getText(this.sf) ?? '';
|
|
1664
|
+
if (/(ChangeEvent|FormEvent)<\s*HTML(Input|TextArea|Select)Element\s*>$/.test(type))
|
|
1665
|
+
return true;
|
|
1666
|
+
const attribute = this.handlerAttribute(found.fn);
|
|
1667
|
+
if (!attribute || !/^on(Change|Input)/.test(attribute.name.getText(this.sf))) return false;
|
|
1668
|
+
const tag = attribute.parent.parent.tagName.getText(this.sf);
|
|
1669
|
+
return tag === 'input' || tag === 'textarea' || tag === 'select';
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
/** @param {ts.ClassDeclaration | ts.ClassExpression} node */
|
|
1673
|
+
checkClass(node) {
|
|
1674
|
+
const base = node.heritageClauses?.find(
|
|
1675
|
+
(clause) => clause.token === ts.SyntaxKind.ExtendsKeyword,
|
|
1676
|
+
)?.types[0]?.expression;
|
|
1677
|
+
const name = base && this.calleeName(base);
|
|
1678
|
+
if (name !== 'Component' && name !== 'PureComponent') return;
|
|
1679
|
+
const boundary = node.members.some(
|
|
1680
|
+
(member) =>
|
|
1681
|
+
member.name &&
|
|
1682
|
+
/^(componentDidCatch|getDerivedStateFromError)$/.test(member.name.getText(this.sf)),
|
|
1683
|
+
);
|
|
1684
|
+
this.note(
|
|
1685
|
+
RULE.classComponent,
|
|
1686
|
+
'error',
|
|
1687
|
+
node,
|
|
1688
|
+
boundary
|
|
1689
|
+
? `Error boundary \`${node.name?.text ?? 'class'}\` needs a rewrite: use \`@try { … } @catch (error) { … }\` or Octane's \`ErrorBoundary\`.`
|
|
1690
|
+
: `Class component \`${node.name?.text ?? 'class'}\` needs a rewrite as a function component.`,
|
|
1691
|
+
);
|
|
1692
|
+
}
|
|
1693
|
+
|
|
1694
|
+
/** @param {ts.BinaryExpression} node */
|
|
1695
|
+
checkDefaultProps(node) {
|
|
1696
|
+
if (
|
|
1697
|
+
node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
|
|
1698
|
+
ts.isPropertyAccessExpression(node.left) &&
|
|
1699
|
+
node.left.name.text === 'defaultProps'
|
|
1700
|
+
) {
|
|
1701
|
+
this.note(
|
|
1702
|
+
RULE.defaultProps,
|
|
1703
|
+
'warning',
|
|
1704
|
+
node,
|
|
1705
|
+
'Function components ignore `defaultProps`; move the defaults into the props destructuring.',
|
|
1706
|
+
);
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
// ---------------------------------------------------------------- JSX
|
|
1711
|
+
|
|
1712
|
+
/** @param {ts.JsxAttributes} node */
|
|
1713
|
+
rewriteAttributes(node) {
|
|
1714
|
+
const element = node.parent;
|
|
1715
|
+
const tag = element.tagName.getText(this.sf);
|
|
1716
|
+
const intrinsic = /^[a-z]/.test(tag);
|
|
1717
|
+
const spread = node.properties.some(ts.isJsxSpreadAttribute);
|
|
1718
|
+
const attributes = node.properties;
|
|
1719
|
+
const named = (/** @type {string} */ name) =>
|
|
1720
|
+
attributes.find((a) => ts.isJsxAttribute(a) && a.name.getText(this.sf) === name);
|
|
1721
|
+
|
|
1722
|
+
let out = '';
|
|
1723
|
+
let cursor = node.getStart(this.sf);
|
|
1724
|
+
for (const attribute of attributes) {
|
|
1725
|
+
const start = attribute.getStart(this.sf);
|
|
1726
|
+
if (this.removed.has(attribute)) {
|
|
1727
|
+
// Drop the attribute and the whitespace on one side of it.
|
|
1728
|
+
if (out === '' && cursor === start) {
|
|
1729
|
+
cursor =
|
|
1730
|
+
attribute.end +
|
|
1731
|
+
(this.source.slice(attribute.end).length -
|
|
1732
|
+
this.source.slice(attribute.end).trimStart().length);
|
|
1733
|
+
if (attribute === attributes[attributes.length - 1]) cursor = attribute.end;
|
|
1734
|
+
} else {
|
|
1735
|
+
out = out.replace(/\s+$/, '') + this.source.slice(cursor, start).replace(/\s+$/, '');
|
|
1736
|
+
cursor = attribute.end;
|
|
1737
|
+
}
|
|
1738
|
+
continue;
|
|
1739
|
+
}
|
|
1740
|
+
out += this.source.slice(cursor, start);
|
|
1741
|
+
cursor = attribute.end;
|
|
1742
|
+
if (!ts.isJsxAttribute(attribute) || !intrinsic) {
|
|
1743
|
+
out += this.emit(attribute, PLAIN);
|
|
1744
|
+
continue;
|
|
1745
|
+
}
|
|
1746
|
+
const name = attribute.name.getText(this.sf);
|
|
1747
|
+
if (name === 'className' && this.target === 'tsrx' && !named('class') && !spread) {
|
|
1748
|
+
this.count(RULE.className);
|
|
1749
|
+
out += 'class' + this.emitInitializer(attribute);
|
|
1750
|
+
} else if ((name === 'onChange' || name === 'onChangeCapture') && this.isTextEntry(element)) {
|
|
1751
|
+
const input = name === 'onChange' ? 'onInput' : 'onInputCapture';
|
|
1752
|
+
if (named(input)) {
|
|
1753
|
+
this.note(
|
|
1754
|
+
RULE.nativeChange,
|
|
1755
|
+
'warning',
|
|
1756
|
+
attribute,
|
|
1757
|
+
`\`${name}\` beside \`${input}\` now fires on commit (blur), not per edit.`,
|
|
1758
|
+
);
|
|
1759
|
+
out += this.emit(attribute, PLAIN);
|
|
1760
|
+
} else {
|
|
1761
|
+
this.count(RULE.nativeChange);
|
|
1762
|
+
out += input + this.emitInitializer(attribute);
|
|
1763
|
+
}
|
|
1764
|
+
} else {
|
|
1765
|
+
out += this.emit(attribute, PLAIN);
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
return out + this.source.slice(cursor, node.end);
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
/** @param {ts.JsxAttribute} attribute */
|
|
1772
|
+
emitInitializer(attribute) {
|
|
1773
|
+
if (!attribute.initializer) return '';
|
|
1774
|
+
return (
|
|
1775
|
+
this.source.slice(attribute.name.end, attribute.initializer.getStart(this.sf)) +
|
|
1776
|
+
this.emit(attribute.initializer, PLAIN)
|
|
1777
|
+
);
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
/**
|
|
1781
|
+
* Whether `element` is a text-entry control, where React's `onChange` fires
|
|
1782
|
+
* per edit and the native `change` fires on commit.
|
|
1783
|
+
*
|
|
1784
|
+
* @param {ts.JsxOpeningLikeElement} element
|
|
1785
|
+
*/
|
|
1786
|
+
isTextEntry(element) {
|
|
1787
|
+
const tag = element.tagName.getText(this.sf);
|
|
1788
|
+
if (tag === 'textarea') return true;
|
|
1789
|
+
if (tag !== 'input') return false;
|
|
1790
|
+
const type = element.attributes.properties.find(
|
|
1791
|
+
(a) => ts.isJsxAttribute(a) && a.name.getText(this.sf) === 'type',
|
|
1792
|
+
);
|
|
1793
|
+
if (!type || !ts.isJsxAttribute(type)) return true;
|
|
1794
|
+
const value = type.initializer;
|
|
1795
|
+
if (value && ts.isStringLiteral(value)) return TEXT_INPUT_TYPES.has(value.text);
|
|
1796
|
+
this.note(
|
|
1797
|
+
RULE.nativeChange,
|
|
1798
|
+
'warning',
|
|
1799
|
+
element,
|
|
1800
|
+
'This `<input>` has a dynamic `type`; if it can be a text field, use `onInput` for per-edit updates.',
|
|
1801
|
+
);
|
|
1802
|
+
return false;
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
/**
|
|
1806
|
+
* @param {ts.JsxElement} node
|
|
1807
|
+
* @param {Context} ctx
|
|
1808
|
+
*/
|
|
1809
|
+
rewriteElement(node, ctx) {
|
|
1810
|
+
if (this.bare.has(node)) {
|
|
1811
|
+
return (
|
|
1812
|
+
'<>' +
|
|
1813
|
+
this.span(node, node.openingElement.end, node.closingElement.getStart(this.sf), ctx) +
|
|
1814
|
+
'</>'
|
|
1815
|
+
);
|
|
1816
|
+
}
|
|
1817
|
+
const tag = node.openingElement.tagName;
|
|
1818
|
+
const name = this.calleeName(tag);
|
|
1819
|
+
if (name === 'StrictMode') {
|
|
1820
|
+
// Octane's StrictMode is a pass-through wrapper.
|
|
1821
|
+
this.count(RULE.strictMode);
|
|
1822
|
+
return this.emitChildren(node, ctx);
|
|
1823
|
+
}
|
|
1824
|
+
if (name === 'Suspense' && ctx.template) return this.rewriteSuspense(node);
|
|
1825
|
+
if (ts.isPropertyAccessExpression(tag) && this.isContext(tag.expression)) {
|
|
1826
|
+
if (tag.name.text === 'Consumer') return this.rewriteConsumer(node, ctx);
|
|
1827
|
+
}
|
|
1828
|
+
return null;
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
/**
|
|
1832
|
+
* Whether `node` is a React context, by where it comes from: a
|
|
1833
|
+
* `createContext` call here, or an export the project knows is one. Only
|
|
1834
|
+
* a package's export, which the codemod cannot see, is judged by its name.
|
|
1835
|
+
*
|
|
1836
|
+
* @param {ts.Expression} node
|
|
1837
|
+
*/
|
|
1838
|
+
isContext(node) {
|
|
1839
|
+
if (!ts.isIdentifier(node)) return false;
|
|
1840
|
+
const declaration = this.declarationOf(node);
|
|
1841
|
+
if (declaration && ts.isVariableDeclaration(declaration)) {
|
|
1842
|
+
return !!declaration.initializer && this.createsContext(declaration.initializer);
|
|
1843
|
+
}
|
|
1844
|
+
const entry = declaration ? this.imports.get(declaration) : null;
|
|
1845
|
+
if (!entry || entry.namespace) return false;
|
|
1846
|
+
const name = entry.imported === 'default' ? entry.local : entry.imported;
|
|
1847
|
+
return this.options.isContext?.(entry.module, entry.imported) ?? /Context$/.test(name);
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
/**
|
|
1851
|
+
* Whether `node` evaluates to a `createContext` result on every branch.
|
|
1852
|
+
*
|
|
1853
|
+
* @param {ts.Expression} node
|
|
1854
|
+
* @returns {boolean}
|
|
1855
|
+
*/
|
|
1856
|
+
createsContext(node) {
|
|
1857
|
+
node = skipParens(node);
|
|
1858
|
+
if (ts.isConditionalExpression(node)) {
|
|
1859
|
+
return this.createsContext(node.whenTrue) && this.createsContext(node.whenFalse);
|
|
1860
|
+
}
|
|
1861
|
+
return ts.isCallExpression(node) && this.calleeName(node.expression) === 'createContext';
|
|
1862
|
+
}
|
|
1863
|
+
|
|
1864
|
+
/**
|
|
1865
|
+
* `typeof children === 'function'` also holds for a compiled children
|
|
1866
|
+
* block, which renders through Octane rather than being called, so the
|
|
1867
|
+
* check also asks `isChildrenBlock`.
|
|
1868
|
+
*
|
|
1869
|
+
* @param {ts.BinaryExpression} node
|
|
1870
|
+
*/
|
|
1871
|
+
rewriteRenderProp(node) {
|
|
1872
|
+
const op = node.operatorToken.kind;
|
|
1873
|
+
if (op !== ts.SyntaxKind.EqualsEqualsEqualsToken && op !== ts.SyntaxKind.EqualsEqualsToken) {
|
|
1874
|
+
return null;
|
|
1875
|
+
}
|
|
1876
|
+
if (!ts.isTypeOfExpression(node.left) || !ts.isStringLiteral(node.right)) return null;
|
|
1877
|
+
const operand = skipParens(node.left.expression);
|
|
1878
|
+
const name = ts.isIdentifier(operand)
|
|
1879
|
+
? operand.text
|
|
1880
|
+
: ts.isPropertyAccessExpression(operand)
|
|
1881
|
+
? operand.name.text
|
|
1882
|
+
: null;
|
|
1883
|
+
if (node.right.text !== 'function' || name !== 'children') return null;
|
|
1884
|
+
const parent = node.parent;
|
|
1885
|
+
if (ts.isBinaryExpression(parent) && /\bisChildrenBlock\(/.test(parent.getText(this.sf))) {
|
|
1886
|
+
return null;
|
|
1887
|
+
}
|
|
1888
|
+
this.count(RULE.renderProp);
|
|
1889
|
+
const check = this.require('octane', 'isChildrenBlock', false);
|
|
1890
|
+
return `(${this.span(node, node.getStart(this.sf), node.end, PLAIN)} && !${check}(${this.emit(operand, PLAIN)}))`;
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
/**
|
|
1894
|
+
* The children of `node` as one renderable: the sole element, or a
|
|
1895
|
+
* fragment around several.
|
|
1896
|
+
*
|
|
1897
|
+
* @param {ts.JsxElement | ts.JsxFragment} node
|
|
1898
|
+
* @param {Context} ctx
|
|
1899
|
+
*/
|
|
1900
|
+
emitChildren(node, ctx) {
|
|
1901
|
+
const children = contentOf(node);
|
|
1902
|
+
if (children.length === 1 && isJsx(children[0])) return this.emit(children[0], ctx);
|
|
1903
|
+
const first = node.children[0];
|
|
1904
|
+
const last = node.children[node.children.length - 1];
|
|
1905
|
+
if (!first) return '<></>';
|
|
1906
|
+
return '<>' + this.span(node, first.pos, last.end, ctx) + '</>';
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
/**
|
|
1910
|
+
* `<Ctx.Consumer>{(value) => …}</Ctx.Consumer>` reads the context in a
|
|
1911
|
+
* nested template scope, where a hook is legal.
|
|
1912
|
+
*
|
|
1913
|
+
* @param {ts.JsxElement} node
|
|
1914
|
+
* @param {Context} ctx
|
|
1915
|
+
*/
|
|
1916
|
+
rewriteConsumer(node, ctx) {
|
|
1917
|
+
const tag = /** @type {ts.PropertyAccessExpression} */ (node.openingElement.tagName);
|
|
1918
|
+
const children = contentOf(node);
|
|
1919
|
+
const render =
|
|
1920
|
+
children.length === 1 && ts.isJsxExpression(children[0]) ? children[0].expression : null;
|
|
1921
|
+
const fn = render && skipParens(render);
|
|
1922
|
+
if (
|
|
1923
|
+
!ctx.template ||
|
|
1924
|
+
!fn ||
|
|
1925
|
+
!(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) ||
|
|
1926
|
+
fn.parameters.length !== 1 ||
|
|
1927
|
+
ts.isBlock(fn.body)
|
|
1928
|
+
) {
|
|
1929
|
+
this.note(
|
|
1930
|
+
RULE.consumer,
|
|
1931
|
+
'error',
|
|
1932
|
+
node,
|
|
1933
|
+
'`Context.Consumer` does not exist in Octane; read the context with `use(Context)`.',
|
|
1934
|
+
);
|
|
1935
|
+
return null;
|
|
1936
|
+
}
|
|
1937
|
+
this.count(RULE.consumer);
|
|
1938
|
+
const useContext = this.require('octane', 'useContext', false);
|
|
1939
|
+
const param = this.emit(fn.parameters[0].name, PLAIN);
|
|
1940
|
+
const body = skipParens(fn.body);
|
|
1941
|
+
const output = isJsx(body) ? this.emit(body, TEMPLATE) : `<>{${this.emit(body, PLAIN)}}</>`;
|
|
1942
|
+
return `@{ const ${param} = ${useContext}(${this.emit(tag.expression, PLAIN)}); ${output} }`;
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
/**
|
|
1946
|
+
* `<Suspense fallback={f}>…</Suspense>` is the template boundary
|
|
1947
|
+
* `@try { … } @pending { f }`.
|
|
1948
|
+
*
|
|
1949
|
+
* @param {ts.JsxElement} node
|
|
1950
|
+
*/
|
|
1951
|
+
rewriteSuspense(node) {
|
|
1952
|
+
const attributes = node.openingElement.attributes.properties.filter(
|
|
1953
|
+
(a) => !this.removed.has(a),
|
|
1954
|
+
);
|
|
1955
|
+
const fallback = attributes[0];
|
|
1956
|
+
if (
|
|
1957
|
+
attributes.length !== 1 ||
|
|
1958
|
+
!ts.isJsxAttribute(fallback) ||
|
|
1959
|
+
fallback.name.getText(this.sf) !== 'fallback' ||
|
|
1960
|
+
!fallback.initializer
|
|
1961
|
+
) {
|
|
1962
|
+
return null;
|
|
1963
|
+
}
|
|
1964
|
+
let pending;
|
|
1965
|
+
const value = fallback.initializer;
|
|
1966
|
+
if (ts.isStringLiteral(value)) pending = `<>{${value.getText(this.sf)}}</>`;
|
|
1967
|
+
else if (ts.isJsxExpression(value) && value.expression) {
|
|
1968
|
+
const expression = skipParens(value.expression);
|
|
1969
|
+
if (isJsx(expression)) pending = this.relative(this.emit(expression, TEMPLATE), expression);
|
|
1970
|
+
else if (isNullish(expression)) pending = '<></>';
|
|
1971
|
+
else pending = `<>{${this.emit(expression, PLAIN)}}</>`;
|
|
1972
|
+
} else return null;
|
|
1973
|
+
this.count(RULE.try);
|
|
1974
|
+
const body = this.relative(this.emitChildren(node, TEMPLATE), node, this.indentUnit);
|
|
1975
|
+
return this.absolute(this.block('@try', body) + ' ' + this.block('@pending', pending), node);
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
// Directive text is built relative to its first line: line 1 carries no
|
|
1979
|
+
// indentation and every later line is indented from that line's level.
|
|
1980
|
+
// `absolute` re-anchors it where it lands in the module.
|
|
1981
|
+
|
|
1982
|
+
/**
|
|
1983
|
+
* Source text emitted for `node`, re-based so `node`'s own line is level 0.
|
|
1984
|
+
*
|
|
1985
|
+
* @param {string} text
|
|
1986
|
+
* @param {ts.Node} node
|
|
1987
|
+
* @param {string} [deeper] how far inside `node`'s line the text's own
|
|
1988
|
+
* first line sat, such as the children of an element
|
|
1989
|
+
*/
|
|
1990
|
+
relative(text, node, deeper = '') {
|
|
1991
|
+
const from = this.indentOf(node) + deeper;
|
|
1992
|
+
return text
|
|
1993
|
+
.split('\n')
|
|
1994
|
+
.map((line, i) => {
|
|
1995
|
+
if (i === 0) return line;
|
|
1996
|
+
if (line.trim() === '') return '';
|
|
1997
|
+
return line.startsWith(from) ? line.slice(from.length) : line.trimStart();
|
|
1998
|
+
})
|
|
1999
|
+
.join('\n');
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
/**
|
|
2003
|
+
* @param {string} text relative text
|
|
2004
|
+
* @param {ts.Node} node the node it replaces
|
|
2005
|
+
*/
|
|
2006
|
+
absolute(text, node) {
|
|
2007
|
+
const indent = this.indentOf(node);
|
|
2008
|
+
return text
|
|
2009
|
+
.split('\n')
|
|
2010
|
+
.map((line, i) => (i === 0 || line === '' ? line : indent + line))
|
|
2011
|
+
.join('\n');
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
/**
|
|
2015
|
+
* `head { body }` on one line when the body fits on one, else with the body
|
|
2016
|
+
* on its own lines one level in.
|
|
2017
|
+
*
|
|
2018
|
+
* @param {string} head
|
|
2019
|
+
* @param {string} body relative text
|
|
2020
|
+
*/
|
|
2021
|
+
block(head, body) {
|
|
2022
|
+
if (!body.includes('\n') && !body.startsWith('@') && head.length + body.length < 80) {
|
|
2023
|
+
return `${head} { ${body} }`;
|
|
2024
|
+
}
|
|
2025
|
+
const unit = this.indentUnit;
|
|
2026
|
+
const lines = body.split('\n').map((line) => (line === '' ? '' : unit + line));
|
|
2027
|
+
return `${head} {\n${lines.join('\n')}\n}`;
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
/**
|
|
2031
|
+
* The text before `node` on its line.
|
|
2032
|
+
*
|
|
2033
|
+
* @param {ts.Node} node
|
|
2034
|
+
*/
|
|
2035
|
+
linePrefix(node) {
|
|
2036
|
+
const start = node.getStart(this.sf);
|
|
2037
|
+
return this.source.slice(this.source.lastIndexOf('\n', start - 1) + 1, start);
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
/** @param {ts.Node} node */
|
|
2041
|
+
indentOf(node) {
|
|
2042
|
+
const prefix = this.linePrefix(node);
|
|
2043
|
+
return prefix.slice(0, prefix.length - prefix.trimStart().length);
|
|
2044
|
+
}
|
|
2045
|
+
|
|
2046
|
+
/**
|
|
2047
|
+
* Template control flow for a JSX child hole.
|
|
2048
|
+
*
|
|
2049
|
+
* @param {ts.JsxExpression} node
|
|
2050
|
+
*/
|
|
2051
|
+
rewriteHole(node) {
|
|
2052
|
+
if (!node.expression || node.dotDotDotToken) return null;
|
|
2053
|
+
const directive = this.directive(node.expression);
|
|
2054
|
+
if (directive === null) return this.textHole(node);
|
|
2055
|
+
// Comments the directive did not carry over sit before it, as JSX
|
|
2056
|
+
// comments, since this is a children position.
|
|
2057
|
+
const lost = this.lostComments(node.getStart(this.sf) + 1, node.end - 1, directive)
|
|
2058
|
+
.map((comment) => `{/* ${commentText(comment)} */}\n`)
|
|
2059
|
+
.join('');
|
|
2060
|
+
return this.absolute(lost + directive, node);
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
/**
|
|
2064
|
+
* A child hole the module's types prove is a string, number, or bigint,
|
|
2065
|
+
* spelled as text so it compiles to a text binding rather than a
|
|
2066
|
+
* renderable hole. React renders those values as text too.
|
|
2067
|
+
*
|
|
2068
|
+
* @param {ts.JsxExpression} node
|
|
2069
|
+
*/
|
|
2070
|
+
textHole(node) {
|
|
2071
|
+
const expression = /** @type {ts.Expression} */ (node.expression);
|
|
2072
|
+
if (!this.textTypes || isTextSpelling(expression)) return null;
|
|
2073
|
+
const kind = textKind(this.typeOf(expression));
|
|
2074
|
+
if (kind === 0) return null;
|
|
2075
|
+
this.count(RULE.text);
|
|
2076
|
+
const value = this.emit(expression, PLAIN);
|
|
2077
|
+
let text;
|
|
2078
|
+
if (kind === 1) {
|
|
2079
|
+
const bare =
|
|
2080
|
+
ts.isIdentifier(expression) ||
|
|
2081
|
+
ts.isPropertyAccessExpression(expression) ||
|
|
2082
|
+
ts.isElementAccessExpression(expression) ||
|
|
2083
|
+
ts.isCallExpression(expression) ||
|
|
2084
|
+
ts.isParenthesizedExpression(expression) ||
|
|
2085
|
+
ts.isNonNullExpression(expression);
|
|
2086
|
+
text = `${bare ? value : `(${value})`} as string`;
|
|
2087
|
+
} else if (
|
|
2088
|
+
this.declaresHere(this.checker.resolveName('String', node, ts.SymbolFlags.Value, false))
|
|
2089
|
+
) {
|
|
2090
|
+
text = `\`\${${value}}\``;
|
|
2091
|
+
} else {
|
|
2092
|
+
text = `String(${value})`;
|
|
2093
|
+
}
|
|
2094
|
+
return (
|
|
2095
|
+
this.span(node, node.getStart(this.sf), expression.getStart(this.sf), PLAIN) +
|
|
2096
|
+
text +
|
|
2097
|
+
this.span(node, expression.end, node.end, PLAIN)
|
|
2098
|
+
);
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
/**
|
|
2102
|
+
* The type of `expression`, from the project's program when it has this
|
|
2103
|
+
* module, else from the module's own.
|
|
2104
|
+
*
|
|
2105
|
+
* @param {ts.Expression} expression
|
|
2106
|
+
*/
|
|
2107
|
+
typeOf(expression) {
|
|
2108
|
+
const types = this.options.types;
|
|
2109
|
+
if (types?.sourceFile.text === this.source) {
|
|
2110
|
+
const start = expression.getStart(this.sf);
|
|
2111
|
+
const same = nodeSpanning(types.sourceFile, start, expression.end);
|
|
2112
|
+
if (same?.kind === expression.kind) return types.checker.getTypeAtLocation(same);
|
|
2113
|
+
}
|
|
2114
|
+
return this.checker.getTypeAtLocation(expression);
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
/**
|
|
2118
|
+
* Comments in `[from, to)` whose text `kept` does not already carry.
|
|
2119
|
+
*
|
|
2120
|
+
* @param {number} from
|
|
2121
|
+
* @param {number} to
|
|
2122
|
+
* @param {string} kept
|
|
2123
|
+
*/
|
|
2124
|
+
lostComments(from, to, kept) {
|
|
2125
|
+
const scanner = ts.createScanner(
|
|
2126
|
+
ts.ScriptTarget.Latest,
|
|
2127
|
+
false,
|
|
2128
|
+
ts.LanguageVariant.Standard,
|
|
2129
|
+
this.source,
|
|
2130
|
+
undefined,
|
|
2131
|
+
from,
|
|
2132
|
+
to - from,
|
|
2133
|
+
);
|
|
2134
|
+
/** @type {string[]} */
|
|
2135
|
+
const lost = [];
|
|
2136
|
+
for (
|
|
2137
|
+
let token = scanner.scan();
|
|
2138
|
+
token !== ts.SyntaxKind.EndOfFileToken;
|
|
2139
|
+
token = scanner.scan()
|
|
2140
|
+
) {
|
|
2141
|
+
if (
|
|
2142
|
+
token !== ts.SyntaxKind.SingleLineCommentTrivia &&
|
|
2143
|
+
token !== ts.SyntaxKind.MultiLineCommentTrivia
|
|
2144
|
+
) {
|
|
2145
|
+
continue;
|
|
2146
|
+
}
|
|
2147
|
+
const text = scanner.getTokenText();
|
|
2148
|
+
if (!kept.includes(text.replaceAll('\n', LITERAL_NEWLINE)) && !kept.includes(text))
|
|
2149
|
+
lost.push(text);
|
|
2150
|
+
}
|
|
2151
|
+
return lost;
|
|
2152
|
+
}
|
|
2153
|
+
|
|
2154
|
+
/**
|
|
2155
|
+
* The template directive equivalent to a renderable expression, as
|
|
2156
|
+
* relative text, or null.
|
|
2157
|
+
*
|
|
2158
|
+
* @param {ts.Expression} expression
|
|
2159
|
+
* @returns {string | null}
|
|
2160
|
+
*/
|
|
2161
|
+
directive(expression) {
|
|
2162
|
+
const node = skipParens(expression);
|
|
2163
|
+
if (ts.isConditionalExpression(node)) return this.ifDirective(node);
|
|
2164
|
+
if (
|
|
2165
|
+
ts.isBinaryExpression(node) &&
|
|
2166
|
+
node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken &&
|
|
2167
|
+
isBoolean(node.left, (name) => this.constValue(name))
|
|
2168
|
+
) {
|
|
2169
|
+
const arm = this.arm(node.right);
|
|
2170
|
+
if (arm === null || arm === '') return null;
|
|
2171
|
+
this.count(RULE.if);
|
|
2172
|
+
return this.block(`@if (${this.emit(node.left, PLAIN)})`, arm);
|
|
2173
|
+
}
|
|
2174
|
+
if (ts.isCallExpression(node)) return this.forDirective(node);
|
|
2175
|
+
return null;
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
/**
|
|
2179
|
+
* The relative template text for one directive arm: an element, a nested
|
|
2180
|
+
* directive, or '' for nothing. An arm that is only a value is null; the
|
|
2181
|
+
* caller decides whether it may become a `{value}` hole.
|
|
2182
|
+
*
|
|
2183
|
+
* @param {ts.Expression} expression
|
|
2184
|
+
* @returns {string | null}
|
|
2185
|
+
*/
|
|
2186
|
+
arm(expression) {
|
|
2187
|
+
const node = skipParens(expression);
|
|
2188
|
+
if (isJsx(node)) return this.relative(this.emit(node, TEMPLATE), node);
|
|
2189
|
+
if (isNullish(node)) return '';
|
|
2190
|
+
return this.directive(node);
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
/** @param {ts.ConditionalExpression} node */
|
|
2194
|
+
ifDirective(node) {
|
|
2195
|
+
let whenTrue = this.arm(node.whenTrue);
|
|
2196
|
+
let whenFalse = this.arm(node.whenFalse);
|
|
2197
|
+
// A ternary between two values is a value; one with an element on
|
|
2198
|
+
// either side is control flow, and a value arm is a hole in a fragment:
|
|
2199
|
+
// a bare `{value}` arm is a JavaScript block, not a hole.
|
|
2200
|
+
if (whenTrue === null && whenFalse === null) return null;
|
|
2201
|
+
if ((whenTrue ?? '') === '' && (whenFalse ?? '') === '') return null;
|
|
2202
|
+
whenTrue ??= `<>{${this.emit(skipParens(node.whenTrue), PLAIN)}}</>`;
|
|
2203
|
+
whenFalse ??= `<>{${this.emit(skipParens(node.whenFalse), PLAIN)}}</>`;
|
|
2204
|
+
this.count(RULE.if);
|
|
2205
|
+
const condition = this.emit(node.condition, PLAIN);
|
|
2206
|
+
if (whenTrue === '') {
|
|
2207
|
+
const negated = /^[\w$.]+$/.test(condition) ? `!${condition}` : `!(${condition})`;
|
|
2208
|
+
return this.block(`@if (${negated})`, whenFalse);
|
|
2209
|
+
}
|
|
2210
|
+
const then = this.block(`@if (${condition})`, whenTrue);
|
|
2211
|
+
return whenFalse === '' ? then : then + ' ' + this.block('@else', whenFalse);
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
/**
|
|
2215
|
+
* `items.map((item, i) => <Row key={item.id} />)` is
|
|
2216
|
+
* `@for (const item of items; index i; key item.id) { <Row /> }`.
|
|
2217
|
+
*
|
|
2218
|
+
* @param {ts.CallExpression} node
|
|
2219
|
+
*/
|
|
2220
|
+
forDirective(node) {
|
|
2221
|
+
const callee = node.expression;
|
|
2222
|
+
if (
|
|
2223
|
+
!ts.isPropertyAccessExpression(callee) ||
|
|
2224
|
+
callee.name.text !== 'map' ||
|
|
2225
|
+
node.arguments.length !== 1
|
|
2226
|
+
) {
|
|
2227
|
+
return null;
|
|
2228
|
+
}
|
|
2229
|
+
const fn = node.arguments[0];
|
|
2230
|
+
if (!(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) return null;
|
|
2231
|
+
if (fn.parameters.length === 0 || fn.parameters.length > 2) return null;
|
|
2232
|
+
if (fn.parameters.some((p) => p.initializer || p.dotDotDotToken)) return null;
|
|
2233
|
+
const [item, index] = fn.parameters;
|
|
2234
|
+
if (index && !ts.isIdentifier(index.name)) return null;
|
|
2235
|
+
// `@for (const items of items)` would read `items` in its own TDZ.
|
|
2236
|
+
const bound = new Set([...bindingNames(item.name), ...(index ? bindingNames(index.name) : [])]);
|
|
2237
|
+
if (reads(callee.expression, (name) => bound.has(name))) return null;
|
|
2238
|
+
// A `function` row sees its own `this` and `arguments`; an arm does not.
|
|
2239
|
+
if (ts.isFunctionExpression(fn) && usesOwnThis(fn.body)) return null;
|
|
2240
|
+
// A row that writes an outer variable (`n++`) needs every row to run in
|
|
2241
|
+
// order; an `@for` row can be skipped.
|
|
2242
|
+
if (this.writesOuter(fn)) return null;
|
|
2243
|
+
|
|
2244
|
+
/** @type {ts.Statement[]} */
|
|
2245
|
+
let setup = [];
|
|
2246
|
+
/** @type {ts.Expression} */
|
|
2247
|
+
let output;
|
|
2248
|
+
if (ts.isBlock(fn.body)) {
|
|
2249
|
+
const statements = fn.body.statements;
|
|
2250
|
+
const last = statements[statements.length - 1];
|
|
2251
|
+
if (!last || !ts.isReturnStatement(last) || !last.expression) return null;
|
|
2252
|
+
setup = statements.slice(0, -1);
|
|
2253
|
+
if (!this.armReturnsOnlyEmpty(setup)) return null;
|
|
2254
|
+
output = last.expression;
|
|
2255
|
+
} else output = fn.body;
|
|
2256
|
+
const root = skipParens(output);
|
|
2257
|
+
if (!isJsx(root) && !ts.isConditionalExpression(root)) return null;
|
|
2258
|
+
|
|
2259
|
+
// Every element the row can render carries the item's key, so it moves
|
|
2260
|
+
// to the header once: the same key on each arm of a conditional row.
|
|
2261
|
+
const elements = (rowElements(root) ?? []).filter((element) => !ts.isJsxFragment(element));
|
|
2262
|
+
const keys = elements.map((element) => {
|
|
2263
|
+
const opening = ts.isJsxElement(element) ? element.openingElement : element;
|
|
2264
|
+
const attribute = opening.attributes.properties.find(
|
|
2265
|
+
(a) => ts.isJsxAttribute(a) && a.name.getText(this.sf) === 'key',
|
|
2266
|
+
);
|
|
2267
|
+
return /** @type {ts.JsxAttribute | undefined} */ (attribute);
|
|
2268
|
+
});
|
|
2269
|
+
let key = null;
|
|
2270
|
+
if (keys.some(Boolean)) {
|
|
2271
|
+
const values = keys.map((attribute) => {
|
|
2272
|
+
const value = attribute?.initializer;
|
|
2273
|
+
return value && ts.isJsxExpression(value) ? value.expression : value;
|
|
2274
|
+
});
|
|
2275
|
+
const text = values[0]?.getText(this.sf);
|
|
2276
|
+
if (!values[0] || values.some((value) => value?.getText(this.sf) !== text)) return null;
|
|
2277
|
+
key = values[0];
|
|
2278
|
+
if (this.readsLocals(key, setup)) {
|
|
2279
|
+
this.note(
|
|
2280
|
+
RULE.for,
|
|
2281
|
+
'warning',
|
|
2282
|
+
/** @type {ts.JsxAttribute} */ (keys[0]),
|
|
2283
|
+
'This row key reads a value computed in the row, so the list stays a `.map()`.',
|
|
2284
|
+
);
|
|
2285
|
+
return null;
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
const hoisted = key ? /** @type {ts.JsxAttribute[]} */ (keys) : [];
|
|
2289
|
+
/** @type {ts.JsxElement[]} A keyed `<Fragment>` is a bare row. */
|
|
2290
|
+
const fragments = [];
|
|
2291
|
+
for (const attribute of hoisted) {
|
|
2292
|
+
this.removed.add(attribute);
|
|
2293
|
+
const opening = attribute.parent.parent;
|
|
2294
|
+
if (
|
|
2295
|
+
ts.isJsxOpeningElement(opening) &&
|
|
2296
|
+
opening.attributes.properties.length === 1 &&
|
|
2297
|
+
this.calleeName(opening.tagName) === 'Fragment'
|
|
2298
|
+
) {
|
|
2299
|
+
fragments.push(opening.parent);
|
|
2300
|
+
this.bare.add(opening.parent);
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
const arm = ts.isConditionalExpression(root)
|
|
2304
|
+
? this.ifDirective(root)
|
|
2305
|
+
: this.relative(this.emit(root, TEMPLATE), root);
|
|
2306
|
+
if (arm === null) {
|
|
2307
|
+
for (const attribute of hoisted) this.removed.delete(attribute);
|
|
2308
|
+
for (const fragment of fragments) this.bare.delete(fragment);
|
|
2309
|
+
return null;
|
|
2310
|
+
}
|
|
2311
|
+
this.count(RULE.for);
|
|
2312
|
+
let source = this.emit(callee.expression, PLAIN);
|
|
2313
|
+
if (callee.questionDotToken) source = `${source} ?? []`;
|
|
2314
|
+
let header = `@for (const ${this.emit(item.name, PLAIN)} of ${source}`;
|
|
2315
|
+
if (index) header += `; index ${index.name.getText(this.sf)}`;
|
|
2316
|
+
if (key) header += `; key ${this.emit(key, PLAIN)}`;
|
|
2317
|
+
else if (this.strong) {
|
|
2318
|
+
this.note(
|
|
2319
|
+
RULE.for,
|
|
2320
|
+
'warning',
|
|
2321
|
+
node,
|
|
2322
|
+
'Strong mode needs a keyed `@for`; add `key <item id>` to the header.',
|
|
2323
|
+
);
|
|
2324
|
+
}
|
|
2325
|
+
header += ')';
|
|
2326
|
+
if (setup.length === 0) return this.block(header, arm);
|
|
2327
|
+
const statements = this.relative(
|
|
2328
|
+
this.span(fn.body, setup[0].getStart(this.sf), setup[setup.length - 1].end, PLAIN),
|
|
2329
|
+
setup[0],
|
|
2330
|
+
);
|
|
2331
|
+
return this.block(header, statements + '\n' + arm);
|
|
2332
|
+
}
|
|
2333
|
+
|
|
2334
|
+
/**
|
|
2335
|
+
* Whether `fn` assigns a variable declared outside it.
|
|
2336
|
+
*
|
|
2337
|
+
* @param {ts.ArrowFunction | ts.FunctionExpression} fn
|
|
2338
|
+
*/
|
|
2339
|
+
writesOuter(fn) {
|
|
2340
|
+
/** @type {(node: ts.Node) => boolean} */
|
|
2341
|
+
const visit = (node) => {
|
|
2342
|
+
let target = null;
|
|
2343
|
+
if (
|
|
2344
|
+
ts.isBinaryExpression(node) &&
|
|
2345
|
+
node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
|
|
2346
|
+
node.operatorToken.kind <= ts.SyntaxKind.LastAssignment
|
|
2347
|
+
) {
|
|
2348
|
+
target = node.left;
|
|
2349
|
+
} else if (
|
|
2350
|
+
(ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
|
|
2351
|
+
(node.operator === ts.SyntaxKind.PlusPlusToken ||
|
|
2352
|
+
node.operator === ts.SyntaxKind.MinusMinusToken)
|
|
2353
|
+
) {
|
|
2354
|
+
target = node.operand;
|
|
2355
|
+
}
|
|
2356
|
+
if (target && ts.isIdentifier(skipParens(target))) {
|
|
2357
|
+
const declaration = this.declarationOf(/** @type {ts.Identifier} */ (skipParens(target)));
|
|
2358
|
+
if (declaration && (declaration.pos < fn.pos || declaration.end > fn.end)) return true;
|
|
2359
|
+
}
|
|
2360
|
+
return ts.forEachChild(node, visit) ?? false;
|
|
2361
|
+
};
|
|
2362
|
+
return visit(fn.body);
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
/**
|
|
2366
|
+
* Whether every `return` in a list row's setup leaves the row empty, the
|
|
2367
|
+
* only early exit a directive arm allows.
|
|
2368
|
+
*
|
|
2369
|
+
* @param {ts.Statement[]} statements
|
|
2370
|
+
*/
|
|
2371
|
+
armReturnsOnlyEmpty(statements) {
|
|
2372
|
+
let ok = true;
|
|
2373
|
+
const visit = (/** @type {ts.Node} */ node) => {
|
|
2374
|
+
if (isFunctionLike(node)) return;
|
|
2375
|
+
if (ts.isReturnStatement(node) && node.expression && !isNullish(node.expression)) ok = false;
|
|
2376
|
+
node.forEachChild(visit);
|
|
2377
|
+
};
|
|
2378
|
+
statements.forEach(visit);
|
|
2379
|
+
return ok;
|
|
2380
|
+
}
|
|
2381
|
+
|
|
2382
|
+
/**
|
|
2383
|
+
* @param {ts.Node} expression
|
|
2384
|
+
* @param {ts.Statement[]} statements
|
|
2385
|
+
*/
|
|
2386
|
+
readsLocals(expression, statements) {
|
|
2387
|
+
const declared = new Set(
|
|
2388
|
+
statements
|
|
2389
|
+
.filter(ts.isVariableStatement)
|
|
2390
|
+
.flatMap((statement) => statement.declarationList.declarations)
|
|
2391
|
+
.flatMap((declaration) => bindingNames(declaration.name)),
|
|
2392
|
+
);
|
|
2393
|
+
return reads(expression, (name) => declared.has(name));
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
// ---------------------------------------------------------------- components
|
|
2397
|
+
|
|
2398
|
+
/**
|
|
2399
|
+
* Rewrite a component whose last statement returns JSX as a template body:
|
|
2400
|
+
* `function C() { setup; return <div /> }` is `function C() @{ setup; <div /> }`.
|
|
2401
|
+
*
|
|
2402
|
+
* @param {ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction} node
|
|
2403
|
+
*/
|
|
2404
|
+
rewriteComponent(node) {
|
|
2405
|
+
if (!node.body || !this.isComponent(node)) return null;
|
|
2406
|
+
if (node.asteriskToken || node.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword))
|
|
2407
|
+
return null;
|
|
2408
|
+
const body = node.body;
|
|
2409
|
+
|
|
2410
|
+
if (!ts.isBlock(body)) {
|
|
2411
|
+
const inner = skipParens(body);
|
|
2412
|
+
const output = this.output(inner);
|
|
2413
|
+
if (output === null) return null;
|
|
2414
|
+
const head = this.head(node, body.getStart(this.sf));
|
|
2415
|
+
this.markTemplate();
|
|
2416
|
+
if (inner !== body && this.startsLine(inner)) {
|
|
2417
|
+
// `=> (\n\t<div />\n)` keeps its layout with the parens as braces.
|
|
2418
|
+
return (
|
|
2419
|
+
head +
|
|
2420
|
+
'@{' +
|
|
2421
|
+
this.source.slice(body.getStart(this.sf) + 1, inner.getStart(this.sf)) +
|
|
2422
|
+
output +
|
|
2423
|
+
this.source.slice(inner.end, body.end - 1).replace(/\)\s*$/, '') +
|
|
2424
|
+
'}'
|
|
2425
|
+
);
|
|
2426
|
+
}
|
|
2427
|
+
return head + '@{ ' + output + ' }';
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2430
|
+
const statements = body.statements;
|
|
2431
|
+
const last = statements[statements.length - 1];
|
|
2432
|
+
if (!last || !ts.isReturnStatement(last) || !last.expression) return null;
|
|
2433
|
+
const guard = statements.findIndex((s, i) => i < statements.length - 1 && guardReturn(s));
|
|
2434
|
+
if (guard !== -1) return this.rewriteGuards(node, body, guard);
|
|
2435
|
+
// A template body has one output; any other early `return <A />` would
|
|
2436
|
+
// render through runtime descriptors, so the plain function stays.
|
|
2437
|
+
if (returnsJsx(statements.slice(0, -1))) return null;
|
|
2438
|
+
const inner = skipParens(last.expression);
|
|
2439
|
+
let output = this.output(inner);
|
|
2440
|
+
if (output === null) return null;
|
|
2441
|
+
const head = this.head(node, body.getStart(this.sf));
|
|
2442
|
+
this.markTemplate();
|
|
2443
|
+
|
|
2444
|
+
if (this.startsLine(inner)) {
|
|
2445
|
+
// `return (\n\t\t<div>…` sits one level deeper than the statements.
|
|
2446
|
+
output = this.absolute(this.relative(output, inner), last);
|
|
2447
|
+
}
|
|
2448
|
+
// A comment inside `return ( … )` becomes a setup comment.
|
|
2449
|
+
const indent = this.indentOf(last);
|
|
2450
|
+
const lost = [
|
|
2451
|
+
...this.lostComments(last.getStart(this.sf), inner.getStart(this.sf), output),
|
|
2452
|
+
...this.lostComments(inner.end, last.end, output),
|
|
2453
|
+
];
|
|
2454
|
+
output =
|
|
2455
|
+
lost.map((comment) => comment.replaceAll('\n', '\n' + indent) + '\n' + indent).join('') +
|
|
2456
|
+
output;
|
|
2457
|
+
const previous = statements[statements.length - 2];
|
|
2458
|
+
const setup = previous ? this.span(body, body.getStart(this.sf) + 1, previous.end, PLAIN) : '';
|
|
2459
|
+
const gap = this.source.slice(
|
|
2460
|
+
previous ? previous.end : body.getStart(this.sf) + 1,
|
|
2461
|
+
last.getStart(this.sf),
|
|
2462
|
+
);
|
|
2463
|
+
return head + '@{' + setup + gap + output + this.source.slice(last.end, body.end - 1) + '}';
|
|
2464
|
+
}
|
|
2465
|
+
|
|
2466
|
+
/**
|
|
2467
|
+
* A component with `if (c) return <A />;` guards: each becomes
|
|
2468
|
+
* `@if (c) { <A /> } @else { …the rest }`, since a template body has one
|
|
2469
|
+
* output. The setup before the first guard stays as it was.
|
|
2470
|
+
*
|
|
2471
|
+
* @param {ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction} node
|
|
2472
|
+
* @param {ts.Block} body
|
|
2473
|
+
* @param {number} first the index of the first guard
|
|
2474
|
+
*/
|
|
2475
|
+
rewriteGuards(node, body, first) {
|
|
2476
|
+
const statements = body.statements;
|
|
2477
|
+
const last = /** @type {ts.ReturnStatement} */ (statements[statements.length - 1]);
|
|
2478
|
+
// Setup before the first guard stays in the body, which may return a
|
|
2479
|
+
// value early; the rest moves into arms, which may only return nothing.
|
|
2480
|
+
const rest = statements.slice(first + 1, -1).filter((statement) => !guardReturn(statement));
|
|
2481
|
+
if (returnsJsx(statements.slice(0, first)) || !this.armReturnsOnlyEmpty(rest)) return null;
|
|
2482
|
+
const output = this.arm(/** @type {ts.Expression} */ (last.expression));
|
|
2483
|
+
if (output === null) return null;
|
|
2484
|
+
/** @type {(from: number) => string} */
|
|
2485
|
+
const chain = (from) => {
|
|
2486
|
+
let at = from;
|
|
2487
|
+
while (at < statements.length - 1 && !guardReturn(statements[at])) at++;
|
|
2488
|
+
// Comments before the first guard stay in the body's own text.
|
|
2489
|
+
const lead =
|
|
2490
|
+
from > first
|
|
2491
|
+
? this.lostComments(statements[from - 1].end, statements[from].getStart(this.sf), '')
|
|
2492
|
+
: [];
|
|
2493
|
+
const prefix =
|
|
2494
|
+
lead.map((comment) => comment + '\n').join('') +
|
|
2495
|
+
(at > from
|
|
2496
|
+
? this.relative(
|
|
2497
|
+
this.span(body, statements[from].getStart(this.sf), statements[at - 1].end, PLAIN),
|
|
2498
|
+
statements[from],
|
|
2499
|
+
) + '\n'
|
|
2500
|
+
: '');
|
|
2501
|
+
if (at === statements.length - 1) return prefix + output;
|
|
2502
|
+
const guard = /** @type {ts.IfStatement} */ (statements[at]);
|
|
2503
|
+
this.count(RULE.if);
|
|
2504
|
+
const then = this.block(
|
|
2505
|
+
`@if (${this.emit(guard.expression, PLAIN)})`,
|
|
2506
|
+
/** @type {string} */ (this.arm(/** @type {ts.Expression} */ (guardReturn(guard)))),
|
|
2507
|
+
);
|
|
2508
|
+
const rest = chain(at + 1);
|
|
2509
|
+
return prefix + (rest === '' ? then : then + ' ' + this.block('@else', rest));
|
|
2510
|
+
};
|
|
2511
|
+
const directive = this.absolute(chain(first), statements[first]);
|
|
2512
|
+
const head = this.head(node, body.getStart(this.sf));
|
|
2513
|
+
this.markTemplate();
|
|
2514
|
+
const previous = statements[first - 1];
|
|
2515
|
+
const before = previous ? this.span(body, body.getStart(this.sf) + 1, previous.end, PLAIN) : '';
|
|
2516
|
+
const gap = this.source.slice(
|
|
2517
|
+
previous ? previous.end : body.getStart(this.sf) + 1,
|
|
2518
|
+
statements[first].getStart(this.sf),
|
|
2519
|
+
);
|
|
2520
|
+
return head + '@{' + before + gap + directive + this.source.slice(last.end, body.end - 1) + '}';
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
markTemplate() {
|
|
2524
|
+
this.template = true;
|
|
2525
|
+
this.count(RULE.component);
|
|
2526
|
+
}
|
|
2527
|
+
|
|
2528
|
+
/**
|
|
2529
|
+
* A component's returned expression as template output, at the position
|
|
2530
|
+
* and indentation `node` had, or null when it is not a single renderable.
|
|
2531
|
+
*
|
|
2532
|
+
* @param {ts.Expression} node
|
|
2533
|
+
*/
|
|
2534
|
+
output(node) {
|
|
2535
|
+
if (isJsx(node)) return this.emit(node, TEMPLATE);
|
|
2536
|
+
if (ts.isConditionalExpression(node) || ts.isCallExpression(node)) {
|
|
2537
|
+
const directive = this.directive(node);
|
|
2538
|
+
return directive === null ? null : this.absolute(directive, node);
|
|
2539
|
+
}
|
|
2540
|
+
return null;
|
|
2541
|
+
}
|
|
2542
|
+
|
|
2543
|
+
/** @param {ts.Node} node */
|
|
2544
|
+
startsLine(node) {
|
|
2545
|
+
return this.linePrefix(node).trim() === '';
|
|
2546
|
+
}
|
|
2547
|
+
|
|
2548
|
+
/**
|
|
2549
|
+
* Whether `node` is a component definition: a capitalized function, or the
|
|
2550
|
+
* function passed to `memo` / `forwardRef`, or a default-exported one.
|
|
2551
|
+
*
|
|
2552
|
+
* @param {ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction} node
|
|
2553
|
+
*/
|
|
2554
|
+
isComponent(node) {
|
|
2555
|
+
if (node.name && isComponentName(node.name.text)) return true;
|
|
2556
|
+
const parent = node.parent;
|
|
2557
|
+
if (ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name)) {
|
|
2558
|
+
return isComponentName(parent.name.text);
|
|
2559
|
+
}
|
|
2560
|
+
if (ts.isCallExpression(parent) && parent.arguments[0] === node) {
|
|
2561
|
+
const name = this.calleeName(parent.expression);
|
|
2562
|
+
if (name === 'memo' || name === 'forwardRef') return true;
|
|
2563
|
+
}
|
|
2564
|
+
if (ts.isExportAssignment(parent)) return true;
|
|
2565
|
+
if (ts.isFunctionDeclaration(node) && !node.name) return true;
|
|
2566
|
+
return false;
|
|
2567
|
+
}
|
|
2568
|
+
}
|