@multiplatform.one/cli 9.16.1 → 10.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.
@@ -0,0 +1,1034 @@
1
+ import type { Dirent } from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import nanoSpawn from "nano-spawn";
5
+ import ts from "typescript";
6
+ import themeKeyRenames from "./themeKeyRenames.json";
7
+
8
+ /**
9
+ * `mpo migrate theme-keys`: renames MPO's theme keys from Tamagui 2's camelCase
10
+ * (`borderColorControl`, `color12`) to Tamagui 3's kebab-case
11
+ * (`border-color-control`, `color-12`). It runs after `mpo update` and after
12
+ * Tamagui's flat-values codemod, so it reads both spellings: `"$color12"`
13
+ * (before the codemod) and a bare `color12` in a flat value (after it).
14
+ *
15
+ * The pass is syntactic (TypeScript's parser, no type checker). A site it can
16
+ * tie to a theme is rewritten; a site that spells a theme key somewhere it
17
+ * cannot tie to a theme is left alone and listed as unclassified.
18
+ */
19
+
20
+ export type ThemeKeyForm =
21
+ | "token"
22
+ | "css-var"
23
+ | "flat"
24
+ | "member"
25
+ | "element"
26
+ | "destructure"
27
+ | "definition"
28
+ | "key-list"
29
+ | "call-arg"
30
+ | "family";
31
+
32
+ export const themeKeyForms: readonly ThemeKeyForm[] = [
33
+ "token",
34
+ "css-var",
35
+ "flat",
36
+ "member",
37
+ "element",
38
+ "destructure",
39
+ "definition",
40
+ "key-list",
41
+ "call-arg",
42
+ "family",
43
+ ];
44
+
45
+ export type FormCounts = Partial<Record<ThemeKeyForm, number>>;
46
+
47
+ export type UnclassifiedSite = {
48
+ file: string;
49
+ line: number;
50
+ column: number;
51
+ key: string;
52
+ reason: string;
53
+ text: string;
54
+ };
55
+
56
+ export type SourceResult = {
57
+ output: string;
58
+ counts: FormCounts;
59
+ unclassified: UnclassifiedSite[];
60
+ error?: string;
61
+ };
62
+
63
+ export type FileReport = {
64
+ file: string;
65
+ counts: FormCounts;
66
+ total: number;
67
+ unclassified: UnclassifiedSite[];
68
+ error?: string;
69
+ };
70
+
71
+ export type ThemeKeysReport = {
72
+ root: string;
73
+ write: boolean;
74
+ scanned: number;
75
+ files: FileReport[];
76
+ skipped: { file: string; reason: string }[];
77
+ };
78
+
79
+ export type ThemeKeysOptions = {
80
+ paths?: string[];
81
+ exclude?: string[];
82
+ write?: boolean;
83
+ renames?: Record<string, string>;
84
+ };
85
+
86
+ const codeExtensions = new Set([".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]);
87
+ const cssExtensions = new Set([".css"]);
88
+ const skippedDirectories = new Set([
89
+ "node_modules",
90
+ "dist",
91
+ ".git",
92
+ ".turbo",
93
+ ".expo",
94
+ ".tamagui",
95
+ ".next",
96
+ "coverage",
97
+ ]);
98
+ export const themeKeysSkipMarker = "mpo-theme-keys: skip-file";
99
+ const generatedHeader = /@generated|do not edit|auto-?generated/iu;
100
+
101
+ /** Tamagui's lookups that take a theme key or token as their first argument. */
102
+ const lookupCalls = new Set([
103
+ "getVariable",
104
+ "getVariableValue",
105
+ "getVariableName",
106
+ "getTokenValue",
107
+ "getToken",
108
+ "getTokenObject",
109
+ ]);
110
+
111
+ /** Theme keys that are also style property names: outside a theme they are style keys. */
112
+ const styleNamedKeys = new Set([
113
+ "borderColor",
114
+ "shadowColor",
115
+ "outlineColor",
116
+ "accentColor",
117
+ "placeholderColor",
118
+ ]);
119
+
120
+ const styleValueProps = new Set([
121
+ "bg",
122
+ "bc",
123
+ "boc",
124
+ "background",
125
+ "backgroundImage",
126
+ "border",
127
+ "borderTop",
128
+ "borderRight",
129
+ "borderBottom",
130
+ "borderLeft",
131
+ "borderBlock",
132
+ "borderInline",
133
+ "boxShadow",
134
+ "textShadow",
135
+ "outline",
136
+ "fill",
137
+ "stroke",
138
+ ]);
139
+
140
+ /** A prop or style key whose value is a colour or carries one. */
141
+ export function isStyleValueProp(name: string): boolean {
142
+ return name === "color" || name.endsWith("Color") || styleValueProps.has(name);
143
+ }
144
+
145
+ type Renamer = {
146
+ map: Map<string, string>;
147
+ known: Set<string>;
148
+ families: Set<string>;
149
+ };
150
+
151
+ function buildRenamer(renames: Record<string, string>): Renamer {
152
+ const map = new Map<string, string>();
153
+ for (const [from, to] of Object.entries(renames)) if (from !== to) map.set(from, to);
154
+ const steps = new Map<string, boolean>();
155
+ for (const [from, to] of map) {
156
+ const step = /^([A-Za-z]+)(\d+)$/u.exec(from);
157
+ if (!step) continue;
158
+ const ok = to === `${step[1]}-${step[2]}`;
159
+ steps.set(step[1], (steps.get(step[1]) ?? true) && ok);
160
+ }
161
+ const families = new Set([...steps].filter(([, ok]) => ok).map(([prefix]) => prefix));
162
+ return { map, known: new Set(Object.keys(renames)), families };
163
+ }
164
+
165
+ const defaultRenamer = buildRenamer(themeKeyRenames);
166
+
167
+ function renamerFor(renames?: Record<string, string>): Renamer {
168
+ return renames ? buildRenamer(renames) : defaultRenamer;
169
+ }
170
+
171
+ const tokenPattern = /(?<![A-Za-z0-9_$])\$([A-Za-z][A-Za-z0-9]*)(?![A-Za-z0-9_-])/gu;
172
+ const cssVarPattern = /(?<![A-Za-z0-9_-])--([A-Za-z][A-Za-z0-9]*)(?![A-Za-z0-9_-])/gu;
173
+ const barePattern = /(?<=^|[\s:(,])([A-Za-z][A-Za-z0-9]*)(?=$|[\s,)])/gu;
174
+ const tokenFamilyTail = /(?<![A-Za-z0-9_$])\$([A-Za-z]+)$/u;
175
+ const cssVarFamilyTail = /(?<![A-Za-z0-9_-])--([A-Za-z]+)$/u;
176
+ const bareFamilyTail = /(?<=^|[\s:(,])([A-Za-z]+)$/u;
177
+
178
+ function bump(counts: FormCounts, form: ThemeKeyForm, by = 1) {
179
+ if (by) counts[form] = (counts[form] ?? 0) + by;
180
+ }
181
+
182
+ function replaceKeys(
183
+ text: string,
184
+ pattern: RegExp,
185
+ renamer: Renamer,
186
+ wrap: (next: string) => string,
187
+ ): { text: string; count: number } {
188
+ let count = 0;
189
+ const next = text.replace(pattern, (whole, key: string) => {
190
+ const renamed = renamer.map.get(key);
191
+ if (!renamed) return whole;
192
+ count += 1;
193
+ return wrap(renamed);
194
+ });
195
+ return { text: next, count };
196
+ }
197
+
198
+ /** `var(--color12)` and `--color12:` in a CSS file or a CSS string. */
199
+ export function renameCssVars(text: string, renames?: Record<string, string>) {
200
+ return replaceKeys(text, cssVarPattern, renamerFor(renames), (next) => `--${next}`);
201
+ }
202
+
203
+ type Edit = { start: number; end: number; text: string };
204
+
205
+ function scriptKindFor(file: string): ts.ScriptKind {
206
+ const ext = path.extname(file);
207
+ if (ext === ".tsx") return ts.ScriptKind.TSX;
208
+ if (ext === ".ts" || ext === ".mts" || ext === ".cts") return ts.ScriptKind.TS;
209
+ return ts.ScriptKind.JSX;
210
+ }
211
+
212
+ function parseErrors(sf: ts.SourceFile): readonly ts.Diagnostic[] {
213
+ return (sf as unknown as { parseDiagnostics?: ts.Diagnostic[] }).parseDiagnostics ?? [];
214
+ }
215
+
216
+ function unwrap(node: ts.Expression): ts.Expression {
217
+ let current = node;
218
+ while (
219
+ ts.isParenthesizedExpression(current) ||
220
+ ts.isAsExpression(current) ||
221
+ ts.isSatisfiesExpression(current) ||
222
+ ts.isNonNullExpression(current) ||
223
+ ts.isTypeAssertionExpression(current)
224
+ ) {
225
+ current = current.expression;
226
+ }
227
+ return current;
228
+ }
229
+
230
+ function calleeName(expression: ts.Expression): string | undefined {
231
+ const callee = unwrap(expression);
232
+ if (ts.isIdentifier(callee)) return callee.text;
233
+ if (ts.isPropertyAccessExpression(callee)) return callee.name.text;
234
+ return undefined;
235
+ }
236
+
237
+ function propertyNameText(name: ts.Node | undefined): string | undefined {
238
+ if (!name) return undefined;
239
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name))
240
+ return name.text;
241
+ if (ts.isComputedPropertyName(name)) {
242
+ const inner = unwrap(name.expression);
243
+ if (ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) return inner.text;
244
+ }
245
+ return undefined;
246
+ }
247
+
248
+ const themeName = /theme/iu;
249
+ const themesName = /themes$/iu;
250
+ const themeTypeName = /Theme(?!Name)/u;
251
+
252
+ function isThemeIdentifierName(name: string): boolean {
253
+ return themeName.test(name) && !themesName.test(name);
254
+ }
255
+
256
+ /**
257
+ * Rewrites one source file's theme keys. `file` names the file in reports and
258
+ * picks the parser (TS, TSX, or JS with JSX).
259
+ */
260
+ export function renameThemeKeysInSource(
261
+ source: string,
262
+ file: string,
263
+ renames?: Record<string, string>,
264
+ ): SourceResult {
265
+ const renamer = renamerFor(renames);
266
+ const counts: FormCounts = {};
267
+ const unclassified: UnclassifiedSite[] = [];
268
+ const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, scriptKindFor(file));
269
+ if (parseErrors(sf).length) {
270
+ return { output: source, counts, unclassified, error: "does not parse" };
271
+ }
272
+
273
+ const edits: Edit[] = [];
274
+ const handled = new Set<ts.Node>();
275
+ const themeVars = new Set<string>();
276
+ const themeRecords = new Set<string>();
277
+ const libraryPalettes = new Set<string>();
278
+ const lines = source.split("\n");
279
+
280
+ const report = (node: ts.Node, key: string, reason: string) => {
281
+ const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
282
+ unclassified.push({
283
+ file,
284
+ line: line + 1,
285
+ column: character + 1,
286
+ key,
287
+ reason,
288
+ text: (lines[line] ?? "").trim().slice(0, 160),
289
+ });
290
+ };
291
+
292
+ const isRenamable = (key: string | undefined): key is string =>
293
+ key !== undefined && renamer.map.has(key);
294
+ const isStyleNamed = (key: string) => styleNamedKeys.has(key);
295
+ const typeMentionsTheme = (type: ts.TypeNode | undefined) =>
296
+ type ? themeTypeName.test(type.getText(sf)) : false;
297
+ const rootIdentifier = (expression: ts.Expression): ts.Identifier | undefined => {
298
+ let current = unwrap(expression);
299
+ while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current))
300
+ current = unwrap(current.expression);
301
+ return ts.isIdentifier(current) ? current : undefined;
302
+ };
303
+ const isLibraryPalette = (expression: ts.Expression) => {
304
+ const root = rootIdentifier(expression);
305
+ return root !== undefined && libraryPalettes.has(root.text);
306
+ };
307
+
308
+ const isThemeRecord = (node: ts.Expression): boolean => {
309
+ const expression = unwrap(node);
310
+ if (ts.isIdentifier(expression))
311
+ return themesName.test(expression.text) || themeRecords.has(expression.text);
312
+ if (ts.isPropertyAccessExpression(expression)) return themesName.test(expression.name.text);
313
+ if (ts.isCallExpression(expression)) return calleeName(expression.expression) === "getThemes";
314
+ return false;
315
+ };
316
+
317
+ const isTheme = (node: ts.Expression): boolean => {
318
+ const expression = unwrap(node);
319
+ if (ts.isCallExpression(expression)) return calleeName(expression.expression) === "useTheme";
320
+ if (ts.isIdentifier(expression)) {
321
+ if (libraryPalettes.has(expression.text)) return false;
322
+ return themeVars.has(expression.text) || isThemeIdentifierName(expression.text);
323
+ }
324
+ if (ts.isPropertyAccessExpression(expression)) {
325
+ if (isThemeIdentifierName(expression.name.text)) return true;
326
+ return isThemeRecord(expression.expression);
327
+ }
328
+ if (ts.isElementAccessExpression(expression)) return isThemeRecord(expression.expression);
329
+ if (ts.isBinaryExpression(expression)) {
330
+ const op = expression.operatorToken.kind;
331
+ if (op === ts.SyntaxKind.QuestionQuestionToken || op === ts.SyntaxKind.BarBarToken)
332
+ return isTheme(expression.left) || isTheme(expression.right);
333
+ return false;
334
+ }
335
+ if (ts.isConditionalExpression(expression))
336
+ return isTheme(expression.whenTrue) || isTheme(expression.whenFalse);
337
+ return false;
338
+ };
339
+
340
+ const collectBindings = (node: ts.Node) => {
341
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
342
+ if (/(^|\/)colors$/u.test(node.moduleSpecifier.text) && node.importClause) {
343
+ const { name, namedBindings } = node.importClause;
344
+ if (name) libraryPalettes.add(name.text);
345
+ if (namedBindings && ts.isNamedImports(namedBindings))
346
+ for (const element of namedBindings.elements) libraryPalettes.add(element.name.text);
347
+ if (namedBindings && ts.isNamespaceImport(namedBindings))
348
+ libraryPalettes.add(namedBindings.name.text);
349
+ }
350
+ }
351
+ if (ts.isVariableDeclaration(node) && node.initializer && isLibraryPalette(node.initializer)) {
352
+ if (ts.isIdentifier(node.name)) libraryPalettes.add(node.name.text);
353
+ if (ts.isObjectBindingPattern(node.name))
354
+ for (const element of node.name.elements)
355
+ if (ts.isIdentifier(element.name)) libraryPalettes.add(element.name.text);
356
+ } else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
357
+ const name = node.name.text;
358
+ if (node.initializer && isThemeRecord(node.initializer)) themeRecords.add(name);
359
+ else if ((node.initializer && isTheme(node.initializer)) || typeMentionsTheme(node.type)) {
360
+ if (!themesName.test(name)) themeVars.add(name);
361
+ }
362
+ }
363
+ if (ts.isParameter(node) && ts.isIdentifier(node.name) && typeMentionsTheme(node.type)) {
364
+ if (!themesName.test(node.name.text)) themeVars.add(node.name.text);
365
+ }
366
+ if (ts.isForOfStatement(node) && ts.isVariableDeclarationList(node.initializer)) {
367
+ const declaration = node.initializer.declarations[0];
368
+ const iterated = unwrap(node.expression);
369
+ if (
370
+ declaration &&
371
+ ts.isCallExpression(iterated) &&
372
+ ts.isPropertyAccessExpression(iterated.expression) &&
373
+ ts.isIdentifier(iterated.expression.expression) &&
374
+ iterated.expression.expression.text === "Object" &&
375
+ iterated.arguments[0] &&
376
+ isThemeRecord(iterated.arguments[0])
377
+ ) {
378
+ const method = iterated.expression.name.text;
379
+ if (method === "values" && ts.isIdentifier(declaration.name))
380
+ themeVars.add(declaration.name.text);
381
+ if (method === "entries" && ts.isArrayBindingPattern(declaration.name)) {
382
+ const second = declaration.name.elements[1];
383
+ if (second && ts.isBindingElement(second) && ts.isIdentifier(second.name))
384
+ themeVars.add(second.name.text);
385
+ }
386
+ }
387
+ }
388
+ ts.forEachChild(node, collectBindings);
389
+ };
390
+ for (let pass = 0; pass < 3; pass += 1) {
391
+ const before = themeVars.size + themeRecords.size;
392
+ collectBindings(sf);
393
+ if (themeVars.size + themeRecords.size === before) break;
394
+ }
395
+
396
+ const literalInner = (node: ts.Node): [number, number] => {
397
+ const start = node.getStart(sf);
398
+ const end = node.end;
399
+ switch (node.kind) {
400
+ case ts.SyntaxKind.TemplateHead:
401
+ case ts.SyntaxKind.TemplateMiddle:
402
+ return [start + 1, end - 2];
403
+ case ts.SyntaxKind.RegularExpressionLiteral:
404
+ return [start, end];
405
+ default:
406
+ return [start + 1, end - 1];
407
+ }
408
+ };
409
+
410
+ const keyLiteral = (key: string) => JSON.stringify(key);
411
+
412
+ const replaceLiteral = (node: ts.Node, next: string, form: ThemeKeyForm) => {
413
+ handled.add(node);
414
+ const [start, end] = literalInner(node);
415
+ edits.push({ start, end, text: next });
416
+ bump(counts, form);
417
+ };
418
+
419
+ /** Edits the text of a string, template piece or regex in place. */
420
+ const rewriteText = (node: ts.Node, bare: boolean) => {
421
+ const [start, end] = literalInner(node);
422
+ let text = source.slice(start, end);
423
+ const original = text;
424
+ const token = replaceKeys(text, tokenPattern, renamer, (next) => `$${next}`);
425
+ text = token.text;
426
+ bump(counts, "token", token.count);
427
+ const cssVar = replaceKeys(text, cssVarPattern, renamer, (next) => `--${next}`);
428
+ text = cssVar.text;
429
+ bump(counts, "css-var", cssVar.count);
430
+ if (bare && node.kind !== ts.SyntaxKind.RegularExpressionLiteral) {
431
+ const flat = replaceKeys(text, barePattern, renamer, (next) => next);
432
+ text = flat.text;
433
+ bump(counts, "flat", flat.count);
434
+ }
435
+ if (node.kind === ts.SyntaxKind.TemplateHead || node.kind === ts.SyntaxKind.TemplateMiddle) {
436
+ const tails: [RegExp, string, boolean][] = [
437
+ [tokenFamilyTail, "$", true],
438
+ [cssVarFamilyTail, "--", true],
439
+ [bareFamilyTail, "", bare],
440
+ ];
441
+ for (const [pattern, sigil, active] of tails) {
442
+ const match = active ? pattern.exec(text) : null;
443
+ if (match && renamer.families.has(match[1])) {
444
+ text = `${text.slice(0, match.index)}${sigil}${match[1]}-`;
445
+ bump(counts, "family");
446
+ break;
447
+ }
448
+ }
449
+ }
450
+ if (text !== original) edits.push({ start, end, text });
451
+ };
452
+
453
+ const renameName = (name: ts.Node, form: ThemeKeyForm) => {
454
+ const key = propertyNameText(name);
455
+ if (!isRenamable(key)) return;
456
+ const next = renamer.map.get(key) as string;
457
+ if (ts.isComputedPropertyName(name)) replaceLiteral(unwrap(name.expression), next, form);
458
+ else if (ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name))
459
+ replaceLiteral(name, next, form);
460
+ else {
461
+ edits.push({ start: name.getStart(sf), end: name.end, text: keyLiteral(next) });
462
+ bump(counts, form);
463
+ }
464
+ };
465
+
466
+ const ownerName = (object: ts.Node): string | undefined => {
467
+ let child = object;
468
+ let parent = object.parent;
469
+ while (
470
+ parent &&
471
+ (ts.isParenthesizedExpression(parent) ||
472
+ ts.isAsExpression(parent) ||
473
+ ts.isSatisfiesExpression(parent))
474
+ ) {
475
+ child = parent;
476
+ parent = parent.parent;
477
+ }
478
+ if (!parent) return undefined;
479
+ if (ts.isVariableDeclaration(parent) || ts.isPropertyAssignment(parent))
480
+ return parent.initializer === child ? propertyNameText(parent.name) : undefined;
481
+ return undefined;
482
+ };
483
+
484
+ const isThemeDefinitionObject = (object: ts.ObjectLiteralExpression): boolean => {
485
+ let child: ts.Node = object;
486
+ let parent = object.parent;
487
+ while (
488
+ parent &&
489
+ (ts.isParenthesizedExpression(parent) ||
490
+ ts.isAsExpression(parent) ||
491
+ ts.isSatisfiesExpression(parent))
492
+ ) {
493
+ if (
494
+ (ts.isAsExpression(parent) || ts.isSatisfiesExpression(parent)) &&
495
+ typeMentionsTheme(parent.type)
496
+ )
497
+ return true;
498
+ child = parent;
499
+ parent = parent.parent;
500
+ }
501
+ if (!parent) return false;
502
+ if (ts.isVariableDeclaration(parent) && parent.initializer === child) {
503
+ if (typeMentionsTheme(parent.type)) return true;
504
+ if (ts.isIdentifier(parent.name) && isThemeIdentifierName(parent.name.text)) return true;
505
+ }
506
+ if (ts.isPropertyAssignment(parent) && parent.initializer === child) {
507
+ if (isThemeIdentifierName(propertyNameText(parent.name) ?? "")) return true;
508
+ if (themesName.test(ownerName(parent.parent) ?? "")) return true;
509
+ }
510
+ if (
511
+ ts.isBinaryExpression(parent) &&
512
+ parent.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
513
+ parent.right === child
514
+ ) {
515
+ const left = unwrap(parent.left);
516
+ const target = ts.isIdentifier(left)
517
+ ? left.text
518
+ : ts.isPropertyAccessExpression(left)
519
+ ? left.name.text
520
+ : "";
521
+ if (isThemeIdentifierName(target)) return true;
522
+ }
523
+ const fn =
524
+ ts.isArrowFunction(parent) && parent.body === child
525
+ ? parent
526
+ : ts.isReturnStatement(parent)
527
+ ? ts.findAncestor(parent, ts.isFunctionLike)
528
+ : undefined;
529
+ if (fn) {
530
+ const holder = fn.parent;
531
+ const holderName = ts.isFunctionDeclaration(fn)
532
+ ? fn.name?.text
533
+ : holder && (ts.isPropertyAssignment(holder) || ts.isVariableDeclaration(holder))
534
+ ? propertyNameText(holder.name)
535
+ : undefined;
536
+ if (holderName === "getTheme") return true;
537
+ }
538
+ const properties = object.properties.filter(ts.isPropertyAssignment);
539
+ if (!properties.length || properties.length !== object.properties.length) return false;
540
+ const keys = properties.map((property) => propertyNameText(property.name));
541
+ if (!keys.some(isRenamable)) return false;
542
+ const variableMocks = properties.every((property) => {
543
+ const value = unwrap(property.initializer);
544
+ return (
545
+ ts.isObjectLiteralExpression(value) &&
546
+ value.properties.some((inner) => propertyNameText(inner.name) === "val")
547
+ );
548
+ });
549
+ return variableMocks;
550
+ };
551
+
552
+ const isKeyList = (elements: readonly ts.Node[]): boolean => {
553
+ if (elements.length < 2) return false;
554
+ for (const element of elements) {
555
+ if (!ts.isStringLiteral(element) && !ts.isNoSubstitutionTemplateLiteral(element))
556
+ return false;
557
+ if (!renamer.known.has(element.text)) return false;
558
+ }
559
+ return elements.some((element) => {
560
+ const key = (element as ts.StringLiteral).text;
561
+ return renamer.map.has(key) && !isStyleNamed(key);
562
+ });
563
+ };
564
+
565
+ const renameKeyList = (elements: readonly ts.Node[]) => {
566
+ for (const element of elements) {
567
+ handled.add(element);
568
+ const next = renamer.map.get((element as ts.StringLiteral).text);
569
+ if (next) replaceLiteral(element, next, "key-list");
570
+ }
571
+ };
572
+
573
+ const isModuleSpecifier = (node: ts.Node): boolean => {
574
+ const parent = node.parent;
575
+ if (!parent) return false;
576
+ if (
577
+ (ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent)) &&
578
+ parent.moduleSpecifier === node
579
+ )
580
+ return true;
581
+ if (ts.isExternalModuleReference(parent)) return true;
582
+ if (ts.isLiteralTypeNode(parent) && ts.isImportTypeNode(parent.parent)) return true;
583
+ if (ts.isCallExpression(parent)) {
584
+ if (calleeName(parent.expression) === "require") return true;
585
+ if (parent.expression.kind === ts.SyntaxKind.ImportKeyword) return true;
586
+ }
587
+ return false;
588
+ };
589
+
590
+ const isPropertyNameOfParent = (node: ts.Node): boolean => {
591
+ const parent = node.parent as ts.Node & { name?: ts.Node; propertyName?: ts.Node };
592
+ if (!parent) return false;
593
+ if (parent.name === node && !ts.isJsxAttribute(parent)) return true;
594
+ if (ts.isBindingElement(parent) && parent.propertyName === node) return true;
595
+ return ts.isComputedPropertyName(parent);
596
+ };
597
+
598
+ const visitObject = (node: ts.ObjectLiteralExpression, style: boolean) => {
599
+ const definition = isThemeDefinitionObject(node);
600
+ for (const property of node.properties) {
601
+ if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) {
602
+ visit(property, false);
603
+ continue;
604
+ }
605
+ const key = propertyNameText(property.name);
606
+ if (isRenamable(key)) {
607
+ if (definition && ts.isShorthandPropertyAssignment(property)) {
608
+ edits.push({
609
+ start: property.name.getStart(sf),
610
+ end: property.name.end,
611
+ text: `${keyLiteral(renamer.map.get(key) as string)}: ${property.name.text}`,
612
+ });
613
+ bump(counts, "definition");
614
+ } else if (definition) {
615
+ renameName(property.name, "definition");
616
+ } else if (!isStyleNamed(key) && !style) {
617
+ report(
618
+ property.name,
619
+ key,
620
+ "object key named like a theme key outside a theme definition",
621
+ );
622
+ }
623
+ }
624
+ if (ts.isComputedPropertyName(property.name)) visit(property.name.expression, false);
625
+ if (ts.isPropertyAssignment(property)) {
626
+ visit(property.initializer, style || (!definition && isStyleValueProp(key ?? "")));
627
+ }
628
+ }
629
+ };
630
+
631
+ const visitElementAccess = (node: ts.ElementAccessExpression) => {
632
+ const argument = unwrap(node.argumentExpression);
633
+ const theme = isTheme(node.expression);
634
+ if (ts.isStringLiteral(argument) || ts.isNoSubstitutionTemplateLiteral(argument)) {
635
+ if (isRenamable(argument.text)) {
636
+ if (theme) replaceLiteral(argument, renamer.map.get(argument.text) as string, "element");
637
+ else if (isLibraryPalette(node.expression)) handled.add(argument);
638
+ }
639
+ } else if (ts.isTemplateExpression(argument)) {
640
+ const head = argument.head;
641
+ const span = argument.templateSpans[0];
642
+ const isFamily =
643
+ renamer.families.has(head.text) &&
644
+ argument.templateSpans.length === 1 &&
645
+ span?.literal.text === "";
646
+ if (isFamily && theme) {
647
+ handled.add(head);
648
+ handled.add(span.literal);
649
+ const [start, end] = literalInner(head);
650
+ edits.push({ start, end, text: `${head.text}-` });
651
+ bump(counts, "family");
652
+ } else if (isFamily && !isLibraryPalette(node.expression)) {
653
+ handled.add(head);
654
+ handled.add(span.literal);
655
+ report(
656
+ argument,
657
+ `${head.text}\${n}`,
658
+ "ramp step built by a template on a receiver not known to be a theme",
659
+ );
660
+ }
661
+ }
662
+ visit(node.expression, false);
663
+ visit(node.argumentExpression, false);
664
+ };
665
+
666
+ const visitBindingDeclaration = (
667
+ node: ts.VariableDeclaration & { name: ts.ObjectBindingPattern },
668
+ ) => {
669
+ const fromTheme = node.initializer ? isTheme(node.initializer) : false;
670
+ for (const element of node.name.elements) {
671
+ const key = propertyNameText(element.propertyName ?? element.name);
672
+ if (isRenamable(key)) {
673
+ if (fromTheme && element.propertyName) renameName(element.propertyName, "destructure");
674
+ else if (fromTheme) {
675
+ edits.push({
676
+ start: element.name.getStart(sf),
677
+ end: element.name.end,
678
+ text: `${keyLiteral(renamer.map.get(key) as string)}: ${element.name.getText(sf)}`,
679
+ });
680
+ bump(counts, "destructure");
681
+ } else if (!isStyleNamed(key)) {
682
+ report(element, key, "destructured from a receiver not known to be a theme");
683
+ }
684
+ }
685
+ if (element.initializer) visit(element.initializer, false);
686
+ }
687
+ if (node.type) visit(node.type, false);
688
+ if (node.initializer) visit(node.initializer, false);
689
+ };
690
+
691
+ const visit = (node: ts.Node, style: boolean): void => {
692
+ if (
693
+ ts.isStringLiteral(node) ||
694
+ ts.isNoSubstitutionTemplateLiteral(node) ||
695
+ ts.isRegularExpressionLiteral(node)
696
+ ) {
697
+ if (handled.has(node) || isModuleSpecifier(node) || isPropertyNameOfParent(node)) return;
698
+ rewriteText(node, style);
699
+ if (
700
+ !style &&
701
+ !ts.isRegularExpressionLiteral(node) &&
702
+ isRenamable(node.text) &&
703
+ !isStyleNamed(node.text)
704
+ )
705
+ report(node, node.text, "bare key string outside a theme or style value");
706
+ return;
707
+ }
708
+ if (ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)) {
709
+ if (!handled.has(node)) rewriteText(node, style);
710
+ return;
711
+ }
712
+ if (ts.isJsxAttribute(node)) {
713
+ if (node.initializer) visit(node.initializer, isStyleValueProp(node.name.getText(sf)));
714
+ return;
715
+ }
716
+ if (ts.isJsxExpression(node)) {
717
+ if (node.expression) visit(node.expression, style);
718
+ return;
719
+ }
720
+ if (ts.isObjectLiteralExpression(node)) {
721
+ visitObject(node, style);
722
+ return;
723
+ }
724
+ if (ts.isArrayLiteralExpression(node)) {
725
+ if (isKeyList(node.elements)) renameKeyList(node.elements);
726
+ for (const element of node.elements) visit(element, style);
727
+ return;
728
+ }
729
+ if (ts.isUnionTypeNode(node)) {
730
+ const literals = node.types.map((type) => (ts.isLiteralTypeNode(type) ? type.literal : type));
731
+ if (isKeyList(literals)) renameKeyList(literals);
732
+ ts.forEachChild(node, (child) => visit(child, false));
733
+ return;
734
+ }
735
+ if (ts.isPropertySignature(node) || ts.isPropertyDeclaration(node)) {
736
+ const key = propertyNameText(node.name);
737
+ if (isRenamable(key)) {
738
+ const owner = node.parent;
739
+ const name =
740
+ ts.isInterfaceDeclaration(owner) || ts.isClassDeclaration(owner)
741
+ ? owner.name?.text
742
+ : ts.isTypeLiteralNode(owner) && ts.isTypeAliasDeclaration(owner.parent)
743
+ ? owner.parent.name.text
744
+ : undefined;
745
+ if (name && themeTypeName.test(name)) renameName(node.name, "definition");
746
+ else if (!isStyleNamed(key)) report(node.name, key, "type member named like a theme key");
747
+ }
748
+ ts.forEachChild(node, (child) => {
749
+ if (child !== node.name) visit(child, false);
750
+ });
751
+ return;
752
+ }
753
+ if (ts.isPropertyAccessExpression(node)) {
754
+ const key = node.name.text;
755
+ if (isRenamable(key)) {
756
+ if (isTheme(node.expression)) {
757
+ const optional = node.questionDotToken ? "?." : "";
758
+ edits.push({
759
+ start: node.expression.end,
760
+ end: node.name.end,
761
+ text: `${optional}[${keyLiteral(renamer.map.get(key) as string)}]`,
762
+ });
763
+ bump(counts, "member");
764
+ } else if (!isStyleNamed(key) && !isLibraryPalette(node.expression)) {
765
+ report(node.name, key, "property read on a receiver not known to be a theme");
766
+ }
767
+ }
768
+ visit(node.expression, false);
769
+ return;
770
+ }
771
+ if (ts.isElementAccessExpression(node)) {
772
+ visitElementAccess(node);
773
+ return;
774
+ }
775
+ if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name)) {
776
+ visitBindingDeclaration(node as ts.VariableDeclaration & { name: ts.ObjectBindingPattern });
777
+ return;
778
+ }
779
+ if (ts.isCallExpression(node)) {
780
+ const name = calleeName(node.expression);
781
+ const first = node.arguments[0] ? unwrap(node.arguments[0]) : undefined;
782
+ if (
783
+ name &&
784
+ lookupCalls.has(name) &&
785
+ first &&
786
+ (ts.isStringLiteral(first) || ts.isNoSubstitutionTemplateLiteral(first)) &&
787
+ isRenamable(first.text)
788
+ ) {
789
+ replaceLiteral(first, renamer.map.get(first.text) as string, "call-arg");
790
+ }
791
+ if (node.arguments.some((argument) => isTheme(argument))) {
792
+ for (const argument of node.arguments) {
793
+ const inner = unwrap(argument);
794
+ if (
795
+ (ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) &&
796
+ !handled.has(inner) &&
797
+ isRenamable(inner.text)
798
+ )
799
+ replaceLiteral(inner, renamer.map.get(inner.text) as string, "call-arg");
800
+ }
801
+ }
802
+ ts.forEachChild(node, (child) => visit(child, false));
803
+ return;
804
+ }
805
+ if (ts.isConditionalExpression(node)) {
806
+ visit(node.condition, false);
807
+ visit(node.whenTrue, style);
808
+ visit(node.whenFalse, style);
809
+ return;
810
+ }
811
+ if (ts.isBinaryExpression(node)) {
812
+ const op = node.operatorToken.kind;
813
+ const fallback =
814
+ op === ts.SyntaxKind.BarBarToken || op === ts.SyntaxKind.QuestionQuestionToken;
815
+ visit(node.left, fallback ? style : false);
816
+ visit(node.right, fallback || op === ts.SyntaxKind.AmpersandAmpersandToken ? style : false);
817
+ return;
818
+ }
819
+ if (
820
+ ts.isParenthesizedExpression(node) ||
821
+ ts.isAsExpression(node) ||
822
+ ts.isSatisfiesExpression(node) ||
823
+ ts.isNonNullExpression(node) ||
824
+ ts.isTemplateExpression(node) ||
825
+ ts.isTemplateSpan(node)
826
+ ) {
827
+ ts.forEachChild(node, (child) => visit(child, ts.isTypeNode(child) ? false : style));
828
+ return;
829
+ }
830
+ ts.forEachChild(node, (child) => visit(child, false));
831
+ };
832
+
833
+ visit(sf, false);
834
+
835
+ if (!edits.length) return { output: source, counts, unclassified };
836
+ edits.sort((a, b) => b.start - a.start);
837
+ let output = source;
838
+ let floor = Number.POSITIVE_INFINITY;
839
+ for (const edit of edits) {
840
+ if (edit.end > floor) {
841
+ return {
842
+ output: source,
843
+ counts: {},
844
+ unclassified,
845
+ error: `overlapping edits at ${edit.start}`,
846
+ };
847
+ }
848
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
849
+ floor = edit.start;
850
+ }
851
+ const check = ts.createSourceFile(
852
+ file,
853
+ output,
854
+ ts.ScriptTarget.Latest,
855
+ false,
856
+ scriptKindFor(file),
857
+ );
858
+ if (parseErrors(check).length) {
859
+ return { output: source, counts: {}, unclassified, error: "the rewrite would not parse" };
860
+ }
861
+ return { output, counts, unclassified };
862
+ }
863
+
864
+ /** Rewrites a CSS file's custom properties (`var(--color12)`, `--color12:`). */
865
+ export function renameThemeKeysInCss(
866
+ source: string,
867
+ renames?: Record<string, string>,
868
+ ): SourceResult {
869
+ const result = renameCssVars(source, renames);
870
+ const counts: FormCounts = {};
871
+ bump(counts, "css-var", result.count);
872
+ return { output: result.text, counts, unclassified: [] };
873
+ }
874
+
875
+ function inside(relative: string, prefixes: string[]): boolean {
876
+ return prefixes.some((prefix) => {
877
+ const clean = prefix.replace(/^\.\//u, "").replace(/\/+$/u, "");
878
+ return relative === clean || relative.startsWith(`${clean}/`);
879
+ });
880
+ }
881
+
882
+ async function walk(root: string, directory: string, out: string[]) {
883
+ let entries: Dirent[];
884
+ try {
885
+ entries = await fs.readdir(directory, { withFileTypes: true });
886
+ } catch {
887
+ return;
888
+ }
889
+ for (const entry of entries) {
890
+ if (entry.isDirectory()) {
891
+ if (!skippedDirectories.has(entry.name))
892
+ await walk(root, path.join(directory, entry.name), out);
893
+ } else if (entry.isFile()) {
894
+ out.push(path.relative(root, path.join(directory, entry.name)).split(path.sep).join("/"));
895
+ }
896
+ }
897
+ }
898
+
899
+ async function gitFiles(root: string, scope: string[]): Promise<string[] | undefined> {
900
+ try {
901
+ const { stdout } = await nanoSpawn("git", [
902
+ "-C",
903
+ root,
904
+ "ls-files",
905
+ "-z",
906
+ "--cached",
907
+ "--others",
908
+ "--exclude-standard",
909
+ "--",
910
+ ...(scope.length ? scope : ["."]),
911
+ ]);
912
+ return stdout.split("\0").filter(Boolean);
913
+ } catch {
914
+ return undefined;
915
+ }
916
+ }
917
+
918
+ /**
919
+ * The files the pass reads: git's tracked and untracked-but-not-ignored files
920
+ * when `root` is a repository, else a walk that skips node_modules, dist and
921
+ * build caches. Paths come back relative to `root`, with forward slashes.
922
+ */
923
+ export async function listThemeKeyFiles(
924
+ root: string,
925
+ paths: string[] = [],
926
+ exclude: string[] = [],
927
+ ): Promise<string[]> {
928
+ const scope = paths.map((entry) =>
929
+ path.relative(root, path.resolve(root, entry)).split(path.sep).join("/"),
930
+ );
931
+ let files = await gitFiles(root, scope);
932
+ if (!files) {
933
+ files = [];
934
+ for (const entry of scope.length ? scope : [""]) {
935
+ const absolute = path.join(root, entry);
936
+ const stat = await fs.stat(absolute).catch(() => undefined);
937
+ if (stat?.isFile()) files.push(entry);
938
+ else if (stat?.isDirectory()) await walk(root, absolute, files);
939
+ }
940
+ }
941
+ return [...new Set(files)]
942
+ .filter((file) => {
943
+ const ext = path.extname(file);
944
+ if (!codeExtensions.has(ext) && !cssExtensions.has(ext)) return false;
945
+ if (file.split("/").some((segment) => skippedDirectories.has(segment))) return false;
946
+ if (/\.(generated|gen|min)\.[cm]?[jt]sx?$/u.test(file)) return false;
947
+ return !inside(file, exclude);
948
+ })
949
+ .sort();
950
+ }
951
+
952
+ function totalOf(counts: FormCounts): number {
953
+ return Object.values(counts).reduce((sum, count) => sum + (count ?? 0), 0);
954
+ }
955
+
956
+ /** Runs the pass over `root`, or the given paths under it. Writes only with `write`. */
957
+ export async function runThemeKeys(
958
+ root: string,
959
+ options: ThemeKeysOptions = {},
960
+ ): Promise<ThemeKeysReport> {
961
+ const files = await listThemeKeyFiles(root, options.paths, options.exclude);
962
+ const report: ThemeKeysReport = {
963
+ root,
964
+ write: Boolean(options.write),
965
+ scanned: 0,
966
+ files: [],
967
+ skipped: [],
968
+ };
969
+ for (const file of files) {
970
+ const absolute = path.join(root, file);
971
+ let source: string;
972
+ try {
973
+ source = await fs.readFile(absolute, "utf8");
974
+ } catch {
975
+ continue;
976
+ }
977
+ const head = source.slice(0, 500);
978
+ if (head.includes(themeKeysSkipMarker)) {
979
+ report.skipped.push({ file, reason: themeKeysSkipMarker });
980
+ continue;
981
+ }
982
+ if (generatedHeader.test(head)) {
983
+ report.skipped.push({ file, reason: "generated" });
984
+ continue;
985
+ }
986
+ report.scanned += 1;
987
+ const result = cssExtensions.has(path.extname(file))
988
+ ? renameThemeKeysInCss(source, options.renames)
989
+ : renameThemeKeysInSource(source, file, options.renames);
990
+ if (result.error) report.skipped.push({ file, reason: result.error });
991
+ const total = totalOf(result.counts);
992
+ if (!total && !result.unclassified.length) continue;
993
+ report.files.push({ file, counts: result.counts, total, unclassified: result.unclassified });
994
+ if (options.write && total && result.output !== source) {
995
+ await fs.writeFile(absolute, result.output);
996
+ }
997
+ }
998
+ return report;
999
+ }
1000
+
1001
+ /** The console report: per-file counts, the totals, then every unclassified site. */
1002
+ export function formatThemeKeysReport(report: ThemeKeysReport): string {
1003
+ const lines: string[] = [];
1004
+ const changed = report.files.filter((file) => file.total > 0);
1005
+ for (const file of changed) {
1006
+ const forms = themeKeyForms
1007
+ .filter((form) => file.counts[form])
1008
+ .map((form) => `${form} ${file.counts[form]}`)
1009
+ .join(", ");
1010
+ lines.push(`${String(file.total).padStart(5)} ${file.file} (${forms})`);
1011
+ }
1012
+ const renamed = changed.reduce((sum, file) => sum + file.total, 0);
1013
+ const byForm = themeKeyForms
1014
+ .map(
1015
+ (form) => [form, changed.reduce((sum, file) => sum + (file.counts[form] ?? 0), 0)] as const,
1016
+ )
1017
+ .filter(([, count]) => count)
1018
+ .map(([form, count]) => `${form} ${count}`)
1019
+ .join(", ");
1020
+ lines.push(
1021
+ `${renamed} theme keys ${report.write ? "renamed" : "to rename"} in ${changed.length} of ${report.scanned} files${byForm ? ` (${byForm})` : ""}${report.write ? "" : "; dry run, nothing written (--write applies it)"}`,
1022
+ );
1023
+ const unclassified = report.files.flatMap((file) => file.unclassified);
1024
+ if (unclassified.length) {
1025
+ lines.push(`${unclassified.length} sites left alone, not tied to a theme; check each by hand:`);
1026
+ for (const site of unclassified) {
1027
+ lines.push(` ${site.file}:${site.line}:${site.column} ${site.key} ${site.reason}`);
1028
+ }
1029
+ }
1030
+ for (const skipped of report.skipped.filter((entry) => entry.reason !== "generated")) {
1031
+ lines.push(`skipped ${skipped.file}: ${skipped.reason}`);
1032
+ }
1033
+ return lines.join("\n");
1034
+ }