@ecopages/codemod 0.9.0-rc.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Codemod: migrate-radiant-refs
3
+ *
4
+ * Moves `@ecopages/radiant` code across the ref/query split of Radiant 0.11.0, which removed
5
+ * the `@query` options object, `cache`, the options form of `createQuery` and the `QueryConfig` type.
6
+ *
7
+ * Before:
8
+ * @query({ ref: 'menubar-root' }) menubarRoot!: HTMLElement | null;
9
+ * @query({ ref: 'item', all: true }) items!: HTMLElement[];
10
+ * @query({ selector: 'input', cache: true }) input!: HTMLInputElement | null;
11
+ * @query({ selector: '[data-row]', all: true }) rows!: HTMLElement[];
12
+ * readonly title = createQuery(this, { ref: 'title' });
13
+ *
14
+ * After:
15
+ * @ref() menubarRoot!: HTMLElement | null;
16
+ * @refAll('item') items!: HTMLElement[];
17
+ * @query('input') input!: HTMLInputElement | null;
18
+ * @queryAll('[data-row]') rows!: HTMLElement[];
19
+ * readonly title = createQuery(this, '[data-ref="title"]');
20
+ *
21
+ * Fields keep their names. `@ref` and `@refAll` get no name when the `ref` equals the field name as an
22
+ * attribute name, the rule Radiant applies to a nameless `@ref` (`menubarRoot` finds `menubar-root`), and the
23
+ * name as written otherwise. `cache` is dropped, and `cache: true` is reported, since the field no longer
24
+ * holds on to the first node. The imports gain `ref`, `refAll`, `queryAll` and `createQueryAll` from the
25
+ * module that exports them, and lose `query` and `createQuery` when nothing reads them any more.
26
+ *
27
+ * Anything it cannot rewrite safely is left unchanged and reported with its line: `QueryConfig` imports,
28
+ * options it cannot read, `getReactiveMember(...).set(...)`, a controller identifier with `:`, a string
29
+ * `ref` attribute in JSX, and a `data-hydration-key` in a file that registers controllers.
30
+ *
31
+ * @remarks
32
+ * `createQuery(host, { ref })` becomes the selector the options form built, `[data-ref="name"]`, which still
33
+ * reaches into nested hosts as before. `getRef(name)` is the scoped alternative, a behaviour change the author
34
+ * chooses by hand. A decorator moves to `@ref` as the release notes direct, and so only sees the parts its
35
+ * host owns: an outer host no longer reads a nested host's part. That change, and `@onEvent({ ref })` no
36
+ * longer firing for a `data-ref` on the host itself, cannot be seen in the source, so they are documented
37
+ * rather than reported.
38
+ */
39
+ import type { API, FileInfo, Options } from 'jscodeshift';
40
+ export declare const parser = "tsx";
41
+ /** The part name Radiant derives from a field name: `toKebabCaseAttributeName` in `@ecopages/radiant`. */
42
+ export declare function partNameOf(fieldName: string): string;
43
+ export default function transform(file: FileInfo, api: API, _options: Options): string | null;
@@ -0,0 +1,503 @@
1
+ /**
2
+ * Codemod: migrate-radiant-refs
3
+ *
4
+ * Moves `@ecopages/radiant` code across the ref/query split of Radiant 0.11.0, which removed
5
+ * the `@query` options object, `cache`, the options form of `createQuery` and the `QueryConfig` type.
6
+ *
7
+ * Before:
8
+ * @query({ ref: 'menubar-root' }) menubarRoot!: HTMLElement | null;
9
+ * @query({ ref: 'item', all: true }) items!: HTMLElement[];
10
+ * @query({ selector: 'input', cache: true }) input!: HTMLInputElement | null;
11
+ * @query({ selector: '[data-row]', all: true }) rows!: HTMLElement[];
12
+ * readonly title = createQuery(this, { ref: 'title' });
13
+ *
14
+ * After:
15
+ * @ref() menubarRoot!: HTMLElement | null;
16
+ * @refAll('item') items!: HTMLElement[];
17
+ * @query('input') input!: HTMLInputElement | null;
18
+ * @queryAll('[data-row]') rows!: HTMLElement[];
19
+ * readonly title = createQuery(this, '[data-ref="title"]');
20
+ *
21
+ * Fields keep their names. `@ref` and `@refAll` get no name when the `ref` equals the field name as an
22
+ * attribute name, the rule Radiant applies to a nameless `@ref` (`menubarRoot` finds `menubar-root`), and the
23
+ * name as written otherwise. `cache` is dropped, and `cache: true` is reported, since the field no longer
24
+ * holds on to the first node. The imports gain `ref`, `refAll`, `queryAll` and `createQueryAll` from the
25
+ * module that exports them, and lose `query` and `createQuery` when nothing reads them any more.
26
+ *
27
+ * Anything it cannot rewrite safely is left unchanged and reported with its line: `QueryConfig` imports,
28
+ * options it cannot read, `getReactiveMember(...).set(...)`, a controller identifier with `:`, a string
29
+ * `ref` attribute in JSX, and a `data-hydration-key` in a file that registers controllers.
30
+ *
31
+ * @remarks
32
+ * `createQuery(host, { ref })` becomes the selector the options form built, `[data-ref="name"]`, which still
33
+ * reaches into nested hosts as before. `getRef(name)` is the scoped alternative, a behaviour change the author
34
+ * chooses by hand. A decorator moves to `@ref` as the release notes direct, and so only sees the parts its
35
+ * host owns: an outer host no longer reads a nested host's part. That change, and `@onEvent({ ref })` no
36
+ * longer firing for a `data-ref` on the host itself, cannot be seen in the source, so they are documented
37
+ * rather than reported.
38
+ */
39
+ import { applyEdits, isNode, keyName, lineOf, offsetsOf, parseOptions, RADIANT_SOURCE, removeNode, stringValue, } from './source-edits.js';
40
+ export const parser = 'tsx';
41
+ const TRANSFORM = 'migrate-radiant-refs';
42
+ const QUERY_OPTION_KEYS = new Set(['selector', 'ref', 'all', 'cache']);
43
+ const CONTROLLER_REGISTRARS = new Set([
44
+ 'controller',
45
+ 'registerController',
46
+ 'replaceController',
47
+ 'registerControllerWithConfiguredStrategy',
48
+ ]);
49
+ const CONTROLLER_EXPORTS = new Set([...CONTROLLER_REGISTRARS, 'RadiantController']);
50
+ /**
51
+ * The module that exports each new name, given the module the file reads `query` or `createQuery` from.
52
+ *
53
+ * @remarks
54
+ * The package root exports the decorators but not `createQuery`, which only `helpers/create-query` exports.
55
+ * `@ref` and `@refAll` live in `decorators/ref`, next to `decorators/query`.
56
+ */
57
+ const TARGET_MODULES = {
58
+ '@ecopages/radiant': { ref: '@ecopages/radiant', refAll: '@ecopages/radiant', queryAll: '@ecopages/radiant' },
59
+ '@ecopages/radiant/decorators/query': {
60
+ ref: '@ecopages/radiant/decorators/ref',
61
+ refAll: '@ecopages/radiant/decorators/ref',
62
+ queryAll: '@ecopages/radiant/decorators/query',
63
+ },
64
+ '@ecopages/radiant/helpers/create-query': { createQueryAll: '@ecopages/radiant/helpers/create-query' },
65
+ };
66
+ const HYDRATION_KEY_IN_TEXT = /data-hydration-key=(["'])([^"']*)\1/;
67
+ /** The part name Radiant derives from a field name: `toKebabCaseAttributeName` in `@ecopages/radiant`. */
68
+ export function partNameOf(fieldName) {
69
+ return fieldName
70
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
71
+ .replace(/[_\s]+/g, '-')
72
+ .toLowerCase();
73
+ }
74
+ function text(ctx, node) {
75
+ return ctx.source.slice(ctx.pos.start(node), ctx.pos.end(node));
76
+ }
77
+ function readImports(j, root) {
78
+ const imports = new Map();
79
+ root.find(j.ImportDeclaration)
80
+ .filter((path) => RADIANT_SOURCE.test(String(path.node.source.value)))
81
+ .forEach((path) => {
82
+ const declaration = path.node;
83
+ for (const specifier of (declaration.specifiers ?? [])) {
84
+ if (specifier.type !== 'ImportSpecifier')
85
+ continue;
86
+ const imported = String(specifier.imported.name ?? specifier.imported.value);
87
+ const local = String(specifier.local?.name ?? imported);
88
+ imports.set(local, { imported, source: String(path.node.source.value), specifier, declaration });
89
+ }
90
+ });
91
+ return imports;
92
+ }
93
+ function readTopLevelNames(j, root) {
94
+ const names = new Set();
95
+ const program = root.find(j.Program).get().node;
96
+ for (const statement of program.body) {
97
+ const declaration = (statement.type.startsWith('Export') ? statement.declaration : statement);
98
+ if (!declaration)
99
+ continue;
100
+ if (declaration.type === 'ImportDeclaration') {
101
+ for (const specifier of declaration.specifiers)
102
+ names.add(String(specifier.local.name));
103
+ }
104
+ else if (declaration.type === 'VariableDeclaration') {
105
+ for (const declarator of declaration.declarations) {
106
+ const id = declarator.id;
107
+ if (id.type === 'Identifier')
108
+ names.add(String(id.name));
109
+ else
110
+ j(id)
111
+ .find(j.Identifier)
112
+ .forEach((path) => names.add(path.node.name));
113
+ }
114
+ }
115
+ else if (isNode(declaration.id)) {
116
+ names.add(String(declaration.id.name));
117
+ }
118
+ }
119
+ return names;
120
+ }
121
+ /**
122
+ * Whether a `@query` or `createQuery` argument is the removed options object: an object literal, or a name
123
+ * this file binds to one.
124
+ *
125
+ * @remarks
126
+ * Any other value is taken for a selector, the new form. An options object that comes from elsewhere is then
127
+ * left alone, and TypeScript rejects it where a selector string is expected.
128
+ */
129
+ function isOptionsValue(ctx, value) {
130
+ if (!value)
131
+ return false;
132
+ if (value.type === 'ObjectExpression')
133
+ return true;
134
+ if (value.type !== 'Identifier')
135
+ return false;
136
+ return ctx.root
137
+ .find(ctx.j.VariableDeclarator, { id: { type: 'Identifier', name: String(value.name) } })
138
+ .some((path) => path.node.init?.type === 'ObjectExpression');
139
+ }
140
+ /** Reads a `@query` or `createQuery` options object, or names what keeps it from being rewritten. */
141
+ function readQueryOptions(options) {
142
+ const result = { all: false };
143
+ for (const property of options.properties) {
144
+ const key = property.type === 'ObjectProperty' ? keyName(property) : undefined;
145
+ if (key === undefined || !QUERY_OPTION_KEYS.has(key)) {
146
+ return { all: false, problem: 'options this codemod cannot read (a spread, a computed or unknown key)' };
147
+ }
148
+ const value = property.value;
149
+ if (key === 'all') {
150
+ if (value.type !== 'BooleanLiteral')
151
+ return { all: false, problem: 'an `all` that is not true or false' };
152
+ result.all = value.value;
153
+ }
154
+ else if (key === 'cache') {
155
+ result.cache = property;
156
+ }
157
+ else {
158
+ result[key] = value;
159
+ }
160
+ }
161
+ if (Boolean(result.selector) === Boolean(result.ref)) {
162
+ return { all: false, problem: 'options with neither or both of `selector` and `ref`' };
163
+ }
164
+ return result;
165
+ }
166
+ function reportCache(ctx, options) {
167
+ const value = options.cache?.value;
168
+ if (!options.cache || (value?.type === 'BooleanLiteral' && value.value === false))
169
+ return;
170
+ ctx.report(options.cache, 'drops cache, which Radiant removed: the field now reads the DOM on every access; read it once into a local where you need a stable node.');
171
+ }
172
+ /**
173
+ * Returns the local name to call `exportName` by, queuing its import from the module that exports it, or
174
+ * undefined when that module or name cannot be used.
175
+ */
176
+ function localFor(ctx, exportName, from, at) {
177
+ for (const [local, binding] of ctx.imports) {
178
+ if (binding.imported === exportName)
179
+ return local;
180
+ }
181
+ const target = TARGET_MODULES[from.source]?.[exportName];
182
+ if (!target) {
183
+ ctx.report(at, `needs ${exportName}, but ${from.source} does not export it; import it from @ecopages/radiant by hand.`);
184
+ return undefined;
185
+ }
186
+ if (ctx.topLevelNames.has(exportName)) {
187
+ ctx.report(at, `needs ${exportName}, but the file already declares that name; rename one and migrate this use by hand.`);
188
+ return undefined;
189
+ }
190
+ const addition = ctx.additions.get(target) ?? { names: new Set(), anchor: from.declaration };
191
+ addition.names.add(exportName);
192
+ ctx.additions.set(target, addition);
193
+ return exportName;
194
+ }
195
+ function replaceCallee(ctx, callee, local) {
196
+ const current = String(callee.name);
197
+ if (local === current)
198
+ return;
199
+ ctx.edits.push({ start: ctx.pos.start(callee), end: ctx.pos.end(callee), text: local });
200
+ ctx.replacedUses.set(current, (ctx.replacedUses.get(current) ?? 0) + 1);
201
+ }
202
+ /** The `@ref` or `@refAll` argument: none when the field name finds the part, the name as written otherwise. */
203
+ function refArgument(ctx, ref, field) {
204
+ const name = stringValue(ref);
205
+ return field !== undefined && name !== undefined && partNameOf(field) === name ? '' : text(ctx, ref);
206
+ }
207
+ /** Rewrites a `query({ ... })` call, applied as a decorator or to `Class.prototype`, for the field it decorates. */
208
+ function migrateQueryDecorator(ctx, call, binding, field) {
209
+ const args = call.arguments;
210
+ const [options] = args;
211
+ if (!isOptionsValue(ctx, options))
212
+ return;
213
+ if (options.type !== 'ObjectExpression' || args.length > 1) {
214
+ ctx.report(call, 'passes @query something other than an options literal or a selector string; move it to @ref, @refAll, @query(selector) or @queryAll(selector) by hand.');
215
+ return;
216
+ }
217
+ const read = readQueryOptions(options);
218
+ if (read.problem) {
219
+ ctx.report(options, `passes @query ${read.problem}; move it to @ref, @refAll, @query(selector) or @queryAll(selector) by hand.`);
220
+ return;
221
+ }
222
+ const exportName = read.ref ? (read.all ? 'refAll' : 'ref') : read.all ? 'queryAll' : 'query';
223
+ const local = exportName === 'query' ? String(call.callee.name) : localFor(ctx, exportName, binding, call);
224
+ if (!local)
225
+ return;
226
+ const argument = read.ref ? refArgument(ctx, read.ref, field) : text(ctx, read.selector);
227
+ replaceCallee(ctx, call.callee, local);
228
+ ctx.edits.push({ start: ctx.pos.start(options), end: ctx.pos.end(options), text: argument });
229
+ reportCache(ctx, read);
230
+ }
231
+ /** The selector the removed `{ ref }` option built, or undefined when the name needs escaping in it. */
232
+ function refSelector(ref) {
233
+ const name = stringValue(ref);
234
+ return name === undefined || /["'\\]/.test(name) ? undefined : `'[data-ref="${name}"]'`;
235
+ }
236
+ function migrateCreateQuery(ctx, call, binding) {
237
+ const options = call.arguments[1];
238
+ if (!isOptionsValue(ctx, options))
239
+ return;
240
+ const read = options.type === 'ObjectExpression'
241
+ ? readQueryOptions(options)
242
+ : { all: false, problem: 'an options value it cannot read' };
243
+ const selector = read.ref ? refSelector(read.ref) : read.selector && text(ctx, read.selector);
244
+ if (read.problem || !selector) {
245
+ const why = read.problem ?? 'a `ref` that is not a plain string';
246
+ ctx.report(options, `passes createQuery ${why}; pass a selector instead, and for a ref use getRef(name) on the host (only the parts it owns) or createQuery(host, '[data-ref="name"]') (nested hosts too, as before).`);
247
+ return;
248
+ }
249
+ const local = read.all ? localFor(ctx, 'createQueryAll', binding, call) : String(call.callee.name);
250
+ if (!local)
251
+ return;
252
+ replaceCallee(ctx, call.callee, local);
253
+ ctx.edits.push({ start: ctx.pos.start(options), end: ctx.pos.end(options), text: selector });
254
+ reportCache(ctx, read);
255
+ }
256
+ function reportControllerIdentifier(ctx, call) {
257
+ const identifier = stringValue(call.arguments[0]);
258
+ if (identifier?.includes(':')) {
259
+ ctx.report(call, `registers the controller identifier '${identifier}', which contains ':'; Radiant now throws on it, because ':' separates the identifier from the field in hydration keys. Rename the controller.`);
260
+ }
261
+ }
262
+ /** The field a `query(...)` call decorates when it is applied as `query(...)(Class.prototype, 'field')`. */
263
+ function prototypeField(path) {
264
+ const outer = path.parent?.node;
265
+ if (outer?.type !== 'CallExpression' || outer.callee !== path.node)
266
+ return undefined;
267
+ return stringValue(outer.arguments[1]);
268
+ }
269
+ function migrateCall(ctx, path) {
270
+ const call = path.node;
271
+ const callee = call.callee;
272
+ const binding = callee.type === 'Identifier' ? ctx.imports.get(String(callee.name)) : undefined;
273
+ if (!binding)
274
+ return;
275
+ if (binding.imported === 'query')
276
+ migrateQueryDecorator(ctx, call, binding, prototypeField(path));
277
+ else if (binding.imported === 'createQuery')
278
+ migrateCreateQuery(ctx, call, binding);
279
+ else if (CONTROLLER_REGISTRARS.has(binding.imported))
280
+ reportControllerIdentifier(ctx, call);
281
+ }
282
+ /** Visits the decorators on classes and their members, which the AST walker does not reach. */
283
+ function migrateDecorators(ctx) {
284
+ const { j, root } = ctx;
285
+ const classes = [
286
+ ...root.find(j.ClassDeclaration).nodes(),
287
+ ...root.find(j.ClassExpression).nodes(),
288
+ ];
289
+ for (const node of classes) {
290
+ for (const decorator of (node.decorators ?? []))
291
+ migrateDecorator(ctx, decorator, undefined);
292
+ for (const member of node.body.body) {
293
+ for (const decorator of (member.decorators ?? []))
294
+ migrateDecorator(ctx, decorator, keyName(member));
295
+ }
296
+ }
297
+ }
298
+ function migrateDecorator(ctx, decorator, field) {
299
+ const call = decorator.expression;
300
+ const callee = call.type === 'CallExpression' ? call.callee : undefined;
301
+ const binding = callee?.type === 'Identifier' ? ctx.imports.get(String(callee.name)) : undefined;
302
+ if (binding?.imported === 'query')
303
+ migrateQueryDecorator(ctx, call, binding, field);
304
+ else if (binding?.imported === 'controller')
305
+ reportControllerIdentifier(ctx, call);
306
+ }
307
+ function reportReadonlyMembers(ctx) {
308
+ ctx.root.find(ctx.j.MemberExpression).forEach((path) => {
309
+ const node = path.node;
310
+ const object = node.object;
311
+ if (node.computed || node.property.name !== 'set' || object.type !== 'CallExpression')
312
+ return;
313
+ const callee = object.callee;
314
+ const name = callee.type === 'MemberExpression' ? callee.property.name : callee.name;
315
+ if (name === 'getReactiveMember') {
316
+ ctx.report(node, 'writes through getReactiveMember(...).set, which Radiant made read-only; assign the host field instead.');
317
+ }
318
+ });
319
+ }
320
+ function literalAttributeValue(attribute) {
321
+ const value = attribute.value;
322
+ if (!value)
323
+ return undefined;
324
+ const expression = value.type === 'JSXExpressionContainer' ? value.expression : value;
325
+ return ['StringLiteral', 'TemplateLiteral'].includes(expression.type) ? expression : undefined;
326
+ }
327
+ function reportStringRefs(ctx) {
328
+ ctx.root.find(ctx.j.JSXAttribute).forEach((path) => {
329
+ const attribute = path.node;
330
+ if (attribute.name.name === 'ref' && literalAttributeValue(attribute)) {
331
+ ctx.report(attribute, 'sets a string ref attribute, which is now a type error and no longer rendered; ref takes a callback. Use data-ref for a part name.');
332
+ }
333
+ });
334
+ }
335
+ function reportHydrationKey(ctx, at, key) {
336
+ if (key.includes(':'))
337
+ return;
338
+ ctx.report(at, `writes data-hydration-key="${key}"; a hydration script for a controller registered with @controller('id') is now keyed "id:${key}", so update it if it belongs to a controller, or emit it with renderHydrationScriptTag().`);
339
+ }
340
+ function reportHydrationKeys(ctx) {
341
+ const { j, root } = ctx;
342
+ root.find(j.JSXAttribute).forEach((path) => {
343
+ const attribute = path.node;
344
+ const value = literalAttributeValue(attribute);
345
+ if (attribute.name.name !== 'data-hydration-key' || value?.type !== 'StringLiteral')
346
+ return;
347
+ reportHydrationKey(ctx, attribute, String(value.value));
348
+ });
349
+ root.find(j.StringLiteral).forEach((path) => {
350
+ const match = HYDRATION_KEY_IN_TEXT.exec(path.node.value);
351
+ if (match)
352
+ reportHydrationKey(ctx, path.node, match[2]);
353
+ });
354
+ root.find(j.TemplateElement).forEach((path) => {
355
+ const match = HYDRATION_KEY_IN_TEXT.exec(path.node.value.raw);
356
+ if (match)
357
+ reportHydrationKey(ctx, path.node, match[2]);
358
+ });
359
+ }
360
+ /** How many references to `local` the file holds outside its import, decorators included. */
361
+ function countUses(ctx, local) {
362
+ const { j, root } = ctx;
363
+ let uses = root.find(j.Identifier, { name: local }).filter((path) => {
364
+ const parent = path.parent.node;
365
+ if (parent.type === 'ImportSpecifier')
366
+ return false;
367
+ if ((parent.type === 'MemberExpression' || parent.type === 'OptionalMemberExpression') &&
368
+ parent.property === path.node) {
369
+ return Boolean(parent.computed);
370
+ }
371
+ return !(parent.type === 'ObjectProperty' && parent.key === path.node && !parent.computed);
372
+ }).length;
373
+ const classes = [
374
+ ...root.find(j.ClassDeclaration).nodes(),
375
+ ...root.find(j.ClassExpression).nodes(),
376
+ ];
377
+ for (const node of classes) {
378
+ const decorated = [node, ...node.body.body];
379
+ for (const decorator of decorated.flatMap((member) => (member.decorators ?? []))) {
380
+ uses += j(decorator.expression).find(j.Identifier, { name: local }).length;
381
+ if (decorator.expression.name === local)
382
+ uses += 1;
383
+ }
384
+ }
385
+ return uses;
386
+ }
387
+ /** Rewrites the specifier list of one import declaration, keeping its one-line or multi-line layout. */
388
+ function specifierListEdit(ctx, declaration, names) {
389
+ const specifiers = declaration.specifiers;
390
+ const first = specifiers[0];
391
+ const last = specifiers.at(-1);
392
+ const lineStart = ctx.source.lastIndexOf('\n', ctx.pos.start(first) - 1) + 1;
393
+ const multiLine = declaration.loc?.start.line !== declaration.loc?.end.line;
394
+ const indent = /^[ \t]*/.exec(ctx.source.slice(lineStart))?.[0] ?? '';
395
+ const separator = multiLine ? `,${lineTerminatorOf(ctx)}${indent}` : ', ';
396
+ return { start: ctx.pos.start(first), end: ctx.pos.end(last), text: names.join(separator) };
397
+ }
398
+ function lineTerminatorOf(ctx) {
399
+ return ctx.source.includes('\r\n') ? '\r\n' : '\n';
400
+ }
401
+ /** An import statement for `module`, quoted and terminated like the declaration it follows. */
402
+ function importStatement(ctx, like, module, names) {
403
+ const quote = text(ctx, like.source).startsWith('"') ? '"' : "'";
404
+ const semicolon = text(ctx, like).endsWith(';') ? ';' : '';
405
+ return `import { ${[...names].join(', ')} } from ${quote}${module}${quote}${semicolon}`;
406
+ }
407
+ /** Whether nothing reads `binding` any more once this transform's replacements are made. */
408
+ function isUnused(ctx, binding) {
409
+ const local = String(binding.specifier.local.name);
410
+ const replaced = ctx.replacedUses.get(local) ?? 0;
411
+ return replaced > 0 && countUses(ctx, local) <= replaced;
412
+ }
413
+ /**
414
+ * Edits one Radiant import declaration: adds the names queued for its module, drops the specifiers nothing
415
+ * reads, and follows it with an import for each queued module the file does not import yet.
416
+ */
417
+ function updateDeclaration(ctx, declaration, bindings, adds) {
418
+ const source = String(declaration.source.value);
419
+ const added = adds ? [...(ctx.additions.get(source)?.names ?? [])] : [];
420
+ const dropped = new Set(bindings.filter((binding) => isUnused(ctx, binding)).map((binding) => binding.specifier));
421
+ const created = [...ctx.additions]
422
+ .filter(([module, addition]) => addition.anchor === declaration && !ctx.importedModules.has(module))
423
+ .map(([module, addition]) => importStatement(ctx, declaration, module, addition.names));
424
+ if (added.length === 0 && dropped.size === 0 && created.length === 0)
425
+ return;
426
+ const eol = lineTerminatorOf(ctx);
427
+ const kept = (declaration.specifiers ?? [])
428
+ .filter((specifier) => !dropped.has(specifier))
429
+ .map((specifier) => text(ctx, specifier));
430
+ const names = [...kept, ...added];
431
+ const end = ctx.pos.end(declaration);
432
+ if (names.length > 0) {
433
+ ctx.edits.push(specifierListEdit(ctx, declaration, names));
434
+ if (created.length > 0)
435
+ ctx.edits.push({ start: end, end, text: created.map((line) => `${eol}${line}`).join('') });
436
+ }
437
+ else if (created.length > 0) {
438
+ ctx.edits.push({ start: ctx.pos.start(declaration), end, text: created.join(eol) });
439
+ }
440
+ else {
441
+ ctx.edits.push(removeNode(ctx.source, ctx.pos, declaration));
442
+ }
443
+ }
444
+ /** Adds the queued names to the imports and drops `query` and `createQuery` specifiers nothing reads. */
445
+ function updateImports(ctx) {
446
+ const declarations = new Map();
447
+ for (const binding of ctx.imports.values()) {
448
+ declarations.set(binding.declaration, [...(declarations.get(binding.declaration) ?? []), binding]);
449
+ }
450
+ const firstForModule = new Map();
451
+ for (const declaration of declarations.keys()) {
452
+ const source = String(declaration.source.value);
453
+ if (!firstForModule.has(source))
454
+ firstForModule.set(source, declaration);
455
+ }
456
+ for (const [declaration, bindings] of declarations) {
457
+ const source = String(declaration.source.value);
458
+ updateDeclaration(ctx, declaration, bindings, firstForModule.get(source) === declaration);
459
+ }
460
+ }
461
+ function reportQueryConfigImports(ctx) {
462
+ for (const binding of ctx.imports.values()) {
463
+ if (binding.imported === 'QueryConfig') {
464
+ ctx.report(binding.specifier, 'imports QueryConfig, which Radiant removed with the @query options object; type the selector as a string.');
465
+ }
466
+ }
467
+ }
468
+ /** Whether the file is Radiant or `@ecopages/jsx` code, where a string `ref` attribute is the removed form. */
469
+ function usesEcopagesJsx(ctx) {
470
+ return ctx.imports.size > 0 || /@jsxImportSource\s+@ecopages\/jsx|from\s+['"]@ecopages\/jsx/.test(ctx.source);
471
+ }
472
+ export default function transform(file, api, _options) {
473
+ const j = api.jscodeshift;
474
+ const root = j(file.source, parseOptions());
475
+ const messages = [];
476
+ const imports = readImports(j, root);
477
+ const ctx = {
478
+ j,
479
+ root,
480
+ source: file.source,
481
+ pos: offsetsOf(file.source),
482
+ imports,
483
+ importedModules: new Set([...imports.values()].map((binding) => binding.source)),
484
+ topLevelNames: readTopLevelNames(j, root),
485
+ additions: new Map(),
486
+ replacedUses: new Map(),
487
+ edits: [],
488
+ report: (at, message) => messages.push({ line: typeof at === 'number' ? at : lineOf(at), text: message }),
489
+ };
490
+ migrateDecorators(ctx);
491
+ root.find(j.CallExpression).forEach((path) => migrateCall(ctx, path));
492
+ reportReadonlyMembers(ctx);
493
+ if (usesEcopagesJsx(ctx))
494
+ reportStringRefs(ctx);
495
+ if ([...ctx.imports.values()].some((binding) => CONTROLLER_EXPORTS.has(binding.imported)))
496
+ reportHydrationKeys(ctx);
497
+ reportQueryConfigImports(ctx);
498
+ updateImports(ctx);
499
+ messages
500
+ .sort((a, b) => (a.line ?? 0) - (b.line ?? 0))
501
+ .forEach(({ line, text: message }) => api.report(`${TRANSFORM}: ${file.path}:${line ?? '?'}: ${message}`));
502
+ return ctx.edits.length > 0 ? applyEdits(file.source, ctx.edits) : null;
503
+ }
@@ -3,11 +3,14 @@
3
3
  *
4
4
  * @remarks
5
5
  * Recast ends reprinted lines with the host's line ending unless told otherwise, so on Windows a rewritten
6
- * import in an LF file would end in CRLF. The source's own line ending is kept instead.
6
+ * import in an LF file would end in CRLF. The source's own line ending is kept instead. Recast measures a kept line's
7
+ * tabs in `tabWidth` columns and indents new code by the same step, so tabs count as 4 columns; the indentation style
8
+ * follows most of the source, tabs or spaces. Recast still prints new objects one key per line and may indent their
9
+ * inner lines with spaces in a tabbed file, so run the project's formatter after a transform.
7
10
  */
8
11
  export declare function printOptions(source: string): {
9
12
  readonly quote: "single";
10
- readonly tabWidth: 2;
11
- readonly useTabs: true;
13
+ readonly tabWidth: number;
14
+ readonly useTabs: boolean;
12
15
  readonly lineTerminator: "\r\n" | "\n";
13
16
  };
@@ -3,13 +3,19 @@
3
3
  *
4
4
  * @remarks
5
5
  * Recast ends reprinted lines with the host's line ending unless told otherwise, so on Windows a rewritten
6
- * import in an LF file would end in CRLF. The source's own line ending is kept instead.
6
+ * import in an LF file would end in CRLF. The source's own line ending is kept instead. Recast measures a kept line's
7
+ * tabs in `tabWidth` columns and indents new code by the same step, so tabs count as 4 columns; the indentation style
8
+ * follows most of the source, tabs or spaces. Recast still prints new objects one key per line and may indent their
9
+ * inner lines with spaces in a tabbed file, so run the project's formatter after a transform.
7
10
  */
8
11
  export function printOptions(source) {
12
+ const tabbed = source.match(/^\t/gm)?.length ?? 0;
13
+ const spaced = source.match(/^ {2,}(?=[^ *])/gm) ?? [];
14
+ const useTabs = tabbed >= spaced.length;
9
15
  return {
10
16
  quote: 'single',
11
- tabWidth: 2,
12
- useTabs: true,
17
+ tabWidth: useTabs ? 4 : Math.min(...spaced.map((indent) => indent.length)),
18
+ useTabs,
13
19
  lineTerminator: source.includes('\r\n') ? '\r\n' : '\n',
14
20
  };
15
21
  }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Source-splicing helpers shared by the Radiant transforms.
3
+ *
4
+ * @remarks
5
+ * These transforms do not reprint through Recast. A change to a class or JSX node makes Recast reprint the
6
+ * whole node, which re-indents it and drops whitespace in JSX text. They record each change as a replacement
7
+ * between two offsets of the original source and apply them to the text, so every other character stays as
8
+ * written: tabs or spaces, line endings and JSX text.
9
+ */
10
+ import type { Collection, JSCodeshift } from 'jscodeshift';
11
+ export declare const RADIANT_SOURCE: RegExp;
12
+ export type Position = {
13
+ line: number;
14
+ column: number;
15
+ };
16
+ export type NodeLike = {
17
+ type: string;
18
+ loc?: {
19
+ start: Position;
20
+ end: Position;
21
+ } | null;
22
+ } & Record<string, unknown>;
23
+ /** A replacement of the source text between two offsets. */
24
+ export type Edit = {
25
+ start: number;
26
+ end: number;
27
+ text: string;
28
+ };
29
+ /** Offsets of a node's bounds in the original source text. */
30
+ export type Offsets = {
31
+ start: (node: NodeLike) => number;
32
+ end: (node: NodeLike) => number;
33
+ };
34
+ /**
35
+ * Recast parse options under which a node's line and column match the original text.
36
+ *
37
+ * @remarks
38
+ * A new object on every call: jscodeshift writes its parser into the options object it is given, and a shared
39
+ * one then carries that parser into the next file.
40
+ */
41
+ export declare function parseOptions(): {
42
+ tabWidth: number;
43
+ };
44
+ export declare function isNode(value: unknown): value is NodeLike;
45
+ export declare function lineOf(node: unknown): number | undefined;
46
+ export declare function keyName(node: NodeLike): string | undefined;
47
+ export declare function stringValue(node: unknown): string | undefined;
48
+ /**
49
+ * Reads node offsets from their line and column.
50
+ *
51
+ * @remarks
52
+ * Recast parses a copy of the source with its line endings normalized and its indentation re-measured, so the
53
+ * parser's own `start` and `end` drift from the original text on CRLF or tab-indented files. Line and column
54
+ * stay true when the source is parsed with {@link parseOptions}.
55
+ */
56
+ export declare function offsetsOf(source: string): Offsets;
57
+ export declare function applyEdits(source: string, edits: Edit[]): string;
58
+ /** Removes a node with its leading comments, and its line when nothing else is on it. */
59
+ export declare function removeNode(source: string, pos: Offsets, node: NodeLike): Edit;
60
+ /** Maps each local name imported from `@ecopages/radiant` or one of its subpaths to its exported name. */
61
+ export declare function readRadiantImports(j: JSCodeshift, root: Collection): Map<string, string>;