@oxy.so/bloom-language-codemod 0.0.0-bootstrap.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2683 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.cleanJsxText = cleanJsxText;
37
+ exports.transformSource = transformSource;
38
+ /**
39
+ * The codemod: one source file's JSX regions rewritten as language chains.
40
+ *
41
+ * A region is a JSX element the codemod converts whole, with everything
42
+ * inside it: React Native's `View` and `Pressable` (a stack), Bloom's `Text`
43
+ * (`@oxy.so/bloom/typography`) and Bloom's icons. A child it cannot convert
44
+ * stays JSX inside the chain (`Embed`), and its own children are regions of
45
+ * their own. An element that cannot convert stays as it is and is reported
46
+ * with every reason. A region is placed back in its JSX with `toElement()`.
47
+ *
48
+ * Nothing is guessed: each utility lands through the className table
49
+ * (`resolve.ts`), each prop through the short list below, and anything else
50
+ * is a reason.
51
+ */
52
+ const node_fs_1 = require("node:fs");
53
+ const node_path_1 = require("node:path");
54
+ const recast = __importStar(require("recast"));
55
+ const babelTs = __importStar(require("recast/parsers/babel-ts"));
56
+ const components_1 = require("./components");
57
+ const resolve_1 = require("./resolve");
58
+ const style_1 = require("./style");
59
+ const table_1 = require("./table");
60
+ const n = recast.types.namedTypes;
61
+ const spec = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(table_1.LANGUAGE_PACKAGE, 'spec/language.json'), 'utf8'));
62
+ /** The roles the universal `.role()` takes, each React Native's `accessibilityRole` of its name. */
63
+ const ROLES = new Set(spec.enums.role);
64
+ /** What a scroll view's content view takes: the layout of one view. */
65
+ const CONTENT_VIEW = new Set(spec.contentView.modifiers);
66
+ /** A Bloom theme colour (`theme.colors.textSecondary`) as the role painted from it (`muted`). */
67
+ const ROLE_OF_THEME_COLOR = new Map();
68
+ for (const [role, entry] of Object.entries(spec.colors))
69
+ if (Array.isArray(entry) && !ROLE_OF_THEME_COLOR.has(entry[0]))
70
+ ROLE_OF_THEME_COLOR.set(entry[0], role);
71
+ const ICON_SIZES = Object.entries(spec.scales.iconSize);
72
+ const RAMP = new Set(Object.keys(spec.typeRamp).filter((k) => !k.startsWith('$')));
73
+ /** A content container's padding key as the edge of its content margin. */
74
+ const CONTENT_EDGE = {
75
+ padding: 'all',
76
+ paddingHorizontal: 'horizontal',
77
+ paddingVertical: 'vertical',
78
+ paddingTop: 'top',
79
+ paddingBottom: 'bottom',
80
+ paddingStart: 'leading',
81
+ paddingEnd: 'trailing',
82
+ paddingLeft: 'left',
83
+ paddingRight: 'right',
84
+ };
85
+ /** React Native's `pointerEvents` as the language's hit testing (`auto` is the default, left as JSX). */
86
+ const HIT_TESTING = {
87
+ none: false,
88
+ 'box-none': 'children',
89
+ 'box-only': 'self',
90
+ };
91
+ /**
92
+ * What `defineTokens` takes as a colour (the language's `isAppColorValue`): a
93
+ * hex of 3, 4, 6 or 8 digits, an `rgb()` or `rgba()` of numbers, or a CSS
94
+ * colour name both platforms paint (the spec's `appColorName`).
95
+ */
96
+ const HEX = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
97
+ const RGB = /^rgb\(\s*\d{1,3}\s*(?:,\s*\d{1,3}\s*){2}\)$|^rgba\(\s*\d{1,3}\s*(?:,\s*\d{1,3}\s*){2},\s*(?:0|1|0?\.\d+)\s*\)$/;
98
+ const COLOR_NAMES = new Set(spec.enums.appColorName);
99
+ const isAppColorValue = (value) => HEX.test(value) || RGB.test(value) || COLOR_NAMES.has(value);
100
+ /** A colour written out as its token's name: `hex` and its digits, a colour name itself, an rgb()'s numbers joined. */
101
+ const appColorName = (value) => HEX.test(value)
102
+ ? `hex${value.slice(1)}`
103
+ : COLOR_NAMES.has(value)
104
+ ? value
105
+ : value.replace(/[^\w]+/g, '_').replace(/_$/, '');
106
+ /** Bloom's colour scope: inside it, a theme read outside it is another scheme's colour. */
107
+ const COLOR_SCOPE = '@oxy.so/bloom/theme#BloomColorScope';
108
+ /** The parameter of a list's row that hands a named row function its argument. */
109
+ const ROW_INFO = 'info';
110
+ const isCarried = (value) => typeof value === 'object' && 'hole' in value && 'node' in value;
111
+ /** A value of the codemod's own (a style object literal never has a `$` key). */
112
+ const isTagged = (value) => typeof value === 'object' && '$' in value && !isCarried(value);
113
+ const isAbsent = (value) => isTagged(value) && value.$ === 'absent';
114
+ /** Whether an expression holds JSX anywhere (an element is no string, number or flag). */
115
+ function hasJsx(expression) {
116
+ let found = false;
117
+ recast.visit(expression, {
118
+ visitJSXElement() {
119
+ found = true;
120
+ return false;
121
+ },
122
+ visitJSXFragment() {
123
+ found = true;
124
+ return false;
125
+ },
126
+ });
127
+ return found;
128
+ }
129
+ const LANGUAGE_MODULE = '@oxy.so/bloom-language';
130
+ const SCREEN_KEY = '@oxy.so/bloom/screen#Screen';
131
+ /**
132
+ * Bloom's `PressableScale`: a Pressable that eases to a smaller scale under a
133
+ * press, its className on the node that scales. The language's parity pairs it
134
+ * with a pressable stack's `.pressScale()` (parity/pieces.cases.tsx).
135
+ */
136
+ function isPressableScale(source) {
137
+ return source.module === '@oxy.so/bloom/pressable-scale' && source.imported === 'PressableScale';
138
+ }
139
+ /** The import that names an element, by kind. */
140
+ function kindOf(source) {
141
+ if (!source)
142
+ return undefined;
143
+ if (source.module === 'react-native') {
144
+ if (source.imported === 'View')
145
+ return 'view';
146
+ if (source.imported === 'Pressable')
147
+ return 'pressable';
148
+ if (source.imported === 'Text')
149
+ return 'rnText';
150
+ if (source.imported === 'Image')
151
+ return 'rnImage';
152
+ return undefined;
153
+ }
154
+ if (source.module === '@oxy.so/bloom/typography' &&
155
+ (source.imported === 'Text' || components_1.TEXT_STYLES[source.imported]))
156
+ return 'bloomText';
157
+ if (source.module === '@oxy.so/bloom/button' && source.imported === 'Button')
158
+ return 'button';
159
+ if (isPressableScale(source))
160
+ return 'pressable';
161
+ if ((0, components_1.ruleFor)(source.module, source.imported))
162
+ return 'component';
163
+ if (components_1.KEPT[`${source.module}#${source.imported}`] || components_1.REMOVED[`${source.module}#${source.imported}`])
164
+ return 'kept';
165
+ if ((source.module === '@oxy.so/bloom/icons' || source.module.startsWith('@oxy.so/bloom/icons/')) &&
166
+ /^(Ri|Si)[A-Z0-9]\w*$|Icon$/.test(source.imported) &&
167
+ source.module !== '@oxy.so/bloom/icons/shared')
168
+ return 'icon';
169
+ return undefined;
170
+ }
171
+ /** React's JSX text rule: lines trimmed and joined, an empty result is no child. */
172
+ function cleanJsxText(value) {
173
+ const lines = value.split(/\r\n|\n|\r/);
174
+ let lastNonEmpty = 0;
175
+ lines.forEach((line, i) => {
176
+ if (/[^ \t]/.test(line))
177
+ lastNonEmpty = i;
178
+ });
179
+ let out = '';
180
+ lines.forEach((line, i) => {
181
+ let trimmed = line.replace(/\t/g, ' ');
182
+ if (i !== 0)
183
+ trimmed = trimmed.replace(/^[ ]+/, '');
184
+ if (i !== lines.length - 1)
185
+ trimmed = trimmed.replace(/[ ]+$/, '');
186
+ if (trimmed) {
187
+ if (i !== lastNonEmpty)
188
+ trimmed += ' ';
189
+ out += trimmed;
190
+ }
191
+ });
192
+ return out;
193
+ }
194
+ /**
195
+ * A condition read without a call: names, properties, literals and their
196
+ * comparisons, negations and logic, so reading it again reads the same.
197
+ */
198
+ function isPlainRead(node) {
199
+ if (n.Identifier.check(node) || n.Literal.check(node) || n.StringLiteral.check(node))
200
+ return true;
201
+ if (n.NumericLiteral.check(node) || n.BooleanLiteral.check(node) || n.NullLiteral.check(node))
202
+ return true;
203
+ if (n.MemberExpression.check(node) || n.OptionalMemberExpression.check(node))
204
+ return isPlainRead(node.object) && (!node.computed || isPlainRead(node.property));
205
+ if (n.UnaryExpression.check(node))
206
+ return node.operator === '!' && isPlainRead(node.argument);
207
+ if (n.BinaryExpression.check(node) || n.LogicalExpression.check(node))
208
+ return isPlainRead(node.left) && isPlainRead(node.right);
209
+ return false;
210
+ }
211
+ /** A condition that is a boolean by its form, so `c && x` never renders a value of `c`. */
212
+ function isBooleanForm(node) {
213
+ if (n.BooleanLiteral.check(node))
214
+ return true;
215
+ if (n.UnaryExpression.check(node) && node.operator === '!')
216
+ return true;
217
+ if (n.BinaryExpression.check(node) &&
218
+ ['===', '!==', '==', '!=', '<', '>', '<=', '>=', 'in', 'instanceof'].includes(node.operator))
219
+ return true;
220
+ if (n.LogicalExpression.check(node) && node.operator !== '??')
221
+ return isBooleanForm(node.left) && isBooleanForm(node.right);
222
+ if (n.CallExpression.check(node) &&
223
+ n.Identifier.check(node.callee) &&
224
+ node.callee.name === 'Boolean')
225
+ return true;
226
+ return false;
227
+ }
228
+ function jsxName(node) {
229
+ const name = node.openingElement.name;
230
+ return n.JSXIdentifier.check(name) ? name.name : undefined;
231
+ }
232
+ function staticString(value) {
233
+ if (!value)
234
+ return undefined;
235
+ if (n.StringLiteral.check(value) || n.Literal.check(value))
236
+ return typeof value.value === 'string' ? value.value : undefined;
237
+ if (n.JSXExpressionContainer.check(value))
238
+ return staticString(value.expression);
239
+ if (n.TemplateLiteral.check(value) && value.expressions.length === 0)
240
+ return value.quasis.map((q) => q.value.cooked).join('');
241
+ return undefined;
242
+ }
243
+ function staticNumber(value) {
244
+ if (n.JSXExpressionContainer.check(value))
245
+ return staticNumber(value.expression);
246
+ if (n.NumericLiteral.check(value))
247
+ return value.value;
248
+ if (n.Literal.check(value) && typeof value.value === 'number')
249
+ return value.value;
250
+ return undefined;
251
+ }
252
+ /** The expression of an attribute value, or a string literal's node. */
253
+ function attributeExpression(value) {
254
+ if (n.JSXExpressionContainer.check(value))
255
+ return value.expression;
256
+ return value;
257
+ }
258
+ /** Code without its block comments: a name in a comment is no binding. */
259
+ const uncommented = (code) => code.replace(/\/\*[\s\S]*?\*\//g, '');
260
+ const quote = (text) => `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n')}'`;
261
+ function printArg(arg) {
262
+ if (typeof arg === 'string')
263
+ return quote(arg);
264
+ if (typeof arg === 'number' || typeof arg === 'boolean')
265
+ return String(arg);
266
+ const entries = Object.entries(arg).map(([k, v]) => `${/^[A-Za-z_$][\w$]*$/.test(k) ? k : quote(k)}: ${quote(v)}`);
267
+ return `{ ${entries.join(', ')} }`;
268
+ }
269
+ const printMod = (mod) => `.${mod.name}(${mod.args.map(printArg).join(', ')})`;
270
+ /** Transforms one file's source. */
271
+ function transformSource(source, options) {
272
+ const ast = recast.parse(source, { parser: babelTs });
273
+ const sources = new Map();
274
+ const declared = new Set();
275
+ recast.visit(ast, {
276
+ visitImportDeclaration(path) {
277
+ const module = String(path.node.source.value);
278
+ for (const specifier of path.node.specifiers ?? []) {
279
+ const local = specifier.local?.name;
280
+ declared.add(local);
281
+ if (n.ImportSpecifier.check(specifier))
282
+ sources.set(local, { module, imported: specifier.imported.name });
283
+ else if (n.ImportDefaultSpecifier.check(specifier) &&
284
+ module.startsWith('@oxy.so/bloom/icons/'))
285
+ sources.set(local, { module, imported: module.slice('@oxy.so/bloom/icons/'.length) });
286
+ }
287
+ return false;
288
+ },
289
+ visitIdentifier(path) {
290
+ declared.add(path.node.name);
291
+ this.traverse(path);
292
+ },
293
+ });
294
+ /** A language name, aliased when the file already uses it. */
295
+ const usedLanguage = new Map();
296
+ const lang = (name) => {
297
+ let local = usedLanguage.get(name);
298
+ if (!local) {
299
+ local = declared.has(name) ? `L${name}` : name;
300
+ usedLanguage.set(name, local);
301
+ }
302
+ return local;
303
+ };
304
+ /** Module-level `const styles = StyleSheet.create({...})`, by name: each style's object literal. */
305
+ const styleSheets = new Map();
306
+ const styleSheetLocal = [...sources].find(([, s]) => s.module === 'react-native' && s.imported === 'StyleSheet')?.[0];
307
+ for (const statement of ast.program.body) {
308
+ const declaration = n.ExportNamedDeclaration.check(statement)
309
+ ? statement.declaration
310
+ : statement;
311
+ if (!n.VariableDeclaration.check(declaration) || declaration.kind !== 'const')
312
+ continue;
313
+ for (const declarator of declaration.declarations) {
314
+ const init = declarator.init;
315
+ if (!styleSheetLocal ||
316
+ !n.Identifier.check(declarator.id) ||
317
+ !n.CallExpression.check(init) ||
318
+ !n.MemberExpression.check(init.callee) ||
319
+ !n.Identifier.check(init.callee.object) ||
320
+ init.callee.object.name !== styleSheetLocal ||
321
+ !n.Identifier.check(init.callee.property) ||
322
+ init.callee.property.name !== 'create' ||
323
+ !n.ObjectExpression.check(init.arguments[0]))
324
+ continue;
325
+ const sheet = new Map();
326
+ for (const property of init.arguments[0].properties)
327
+ if ((n.ObjectProperty.check(property) || n.Property.check(property)) &&
328
+ n.Identifier.check(property.key))
329
+ sheet.set(property.key.name, property.value);
330
+ styleSheets.set(declarator.id.name, sheet);
331
+ }
332
+ }
333
+ /**
334
+ * Each `theme.colors.key` (`theme` from Bloom's `useTheme()`) and `colors.key`
335
+ * (`const { colors } = useTheme()`) in the file, as the role painted from that
336
+ * theme colour, resolved through the scope it is read in.
337
+ */
338
+ const themeRoles = new Map();
339
+ const useThemeLocals = new Set([...sources]
340
+ .filter(([, s]) => s.module === '@oxy.so/bloom/theme' && s.imported === 'useTheme')
341
+ .map(([local]) => local));
342
+ /**
343
+ * The scope that declares `name` where `path` reads it. ast-types cannot scan
344
+ * every pattern Babel parses (an array pattern's hole, `const [, b] = …`):
345
+ * a scope it cannot scan is no known binding.
346
+ */
347
+ const scopeOf = (path, name) => {
348
+ try {
349
+ return path.scope?.lookup(name);
350
+ }
351
+ catch {
352
+ return undefined;
353
+ }
354
+ };
355
+ /** What `name` is bound to where `path` reads it: Bloom's theme, its colours, or neither. */
356
+ const boundTo = (path, name) => {
357
+ const bindings = scopeOf(path, name)?.getBindings()[name];
358
+ if (bindings?.length !== 1)
359
+ return undefined;
360
+ // `const theme = useTheme()`, or `const { colors } = useTheme()` (the property's value is the binding).
361
+ let at = bindings[0];
362
+ while (at && !n.VariableDeclarator.check(at.node))
363
+ at = at.parent;
364
+ const init = at?.node.init;
365
+ if (!init ||
366
+ !n.CallExpression.check(init) ||
367
+ !n.Identifier.check(init.callee) ||
368
+ !useThemeLocals.has(init.callee.name) ||
369
+ at.parent?.node.kind !== 'const')
370
+ return undefined;
371
+ if (n.Identifier.check(at.node.id) && at.node.id.name === name)
372
+ return 'theme';
373
+ if (n.ObjectPattern.check(at.node.id) &&
374
+ at.node.id.properties.some((p) => (n.ObjectProperty.check(p) || n.Property.check(p)) &&
375
+ !p.computed &&
376
+ n.Identifier.check(p.key) &&
377
+ p.key.name === 'colors' &&
378
+ n.Identifier.check(p.value) &&
379
+ p.value.name === name))
380
+ return 'colors';
381
+ return undefined;
382
+ };
383
+ /** Each `styles.x` read where `styles` is the module's StyleSheet (not a name that shadows it). */
384
+ const moduleStyleReads = new Set();
385
+ if (useThemeLocals.size > 0 || styleSheets.size > 0)
386
+ recast.visit(ast, {
387
+ visitMemberExpression(path) {
388
+ const { object, property, computed } = path.node;
389
+ if (n.Identifier.check(object) &&
390
+ styleSheets.has(object.name) &&
391
+ scopeOf(path, object.name)?.isGlobal)
392
+ moduleStyleReads.add(path.node);
393
+ if (!computed && n.Identifier.check(property)) {
394
+ const role = ROLE_OF_THEME_COLOR.get(property.name);
395
+ const colorsOf = n.MemberExpression.check(object) &&
396
+ !object.computed &&
397
+ n.Identifier.check(object.property) &&
398
+ object.property.name === 'colors' &&
399
+ n.Identifier.check(object.object) &&
400
+ boundTo(path, object.object.name) === 'theme';
401
+ const colors = n.Identifier.check(object) && boundTo(path, object.name) === 'colors';
402
+ if (role && (colorsOf || colors))
403
+ themeRoles.set(path.node, role);
404
+ }
405
+ this.traverse(path);
406
+ },
407
+ });
408
+ /** A className chosen at runtime, by its expression: both branches' classes, which the parity's stylesheet holds. */
409
+ const choiceClasses = new Map();
410
+ /** Each `{name}` in JSX where `name` is a `const` holding an element (`const header = <PageHeader … />`). */
411
+ const elementReads = new Set();
412
+ recast.visit(ast, {
413
+ visitJSXExpressionContainer(path) {
414
+ const { expression } = path.node;
415
+ const bindings = n.Identifier.check(expression)
416
+ ? scopeOf(path, expression.name)?.getBindings()[expression.name]
417
+ : undefined;
418
+ let at = bindings?.length === 1 ? bindings[0] : undefined;
419
+ while (at && !n.VariableDeclarator.check(at.node))
420
+ at = at.parent;
421
+ if (at?.parent?.node.kind === 'const' &&
422
+ n.Identifier.check(at.node.id) &&
423
+ (n.JSXElement.check(at.node.init) || n.JSXFragment.check(at.node.init)))
424
+ elementReads.add(expression);
425
+ this.traverse(path);
426
+ },
427
+ });
428
+ /**
429
+ * Module-level `const NAME = 'text'` (no type annotation, so a colour's type is
430
+ * the literal `defineTokens` takes), by name: a colour the codemod reads in the file.
431
+ */
432
+ const colorConstants = new Map();
433
+ for (const statement of ast.program.body) {
434
+ const declaration = n.ExportNamedDeclaration.check(statement)
435
+ ? statement.declaration
436
+ : statement;
437
+ if (!n.VariableDeclaration.check(declaration) || declaration.kind !== 'const')
438
+ continue;
439
+ for (const declarator of declaration.declarations) {
440
+ const value = staticString(declarator.init);
441
+ if (n.Identifier.check(declarator.id) &&
442
+ !declarator.id.typeAnnotation &&
443
+ n.StringLiteral.check(declarator.init) &&
444
+ value !== undefined)
445
+ colorConstants.set(declarator.id.name, { value, statement });
446
+ }
447
+ }
448
+ /** Each name that reads a string constant of the module's (not a name that shadows it). */
449
+ const colorConstantReads = new Set();
450
+ if (colorConstants.size > 0)
451
+ recast.visit(ast, {
452
+ visitIdentifier(path) {
453
+ if (colorConstants.has(path.node.name) && scopeOf(path, path.node.name)?.isGlobal)
454
+ colorConstantReads.add(path.node);
455
+ this.traverse(path);
456
+ },
457
+ });
458
+ /** The local name of the file's app colour table, free in the file. */
459
+ let appColorTable = 'appColors';
460
+ for (let i = 2; declared.has(appColorTable); i++)
461
+ appColorTable = `appColors${i}`;
462
+ /** The app colours the converted regions paint with, by token name: the file's table. */
463
+ const appColors = new Map();
464
+ /** A `style` whose objects are the parity's before side, where `styles.x` is not in scope. */
465
+ const styleLiterals = new Map();
466
+ /** A static style (an object literal, a module StyleSheet's style, or a list of them) as utilities. */
467
+ function staticStyle(expression, read) {
468
+ const parts = n.ArrayExpression.check(expression)
469
+ ? expression.elements
470
+ : [expression];
471
+ const classes = [];
472
+ const mods = [];
473
+ // A StyleSheet's style is its literal on the before side; an inline object stays as written.
474
+ const literals = new Map();
475
+ for (const part of parts) {
476
+ let object = part;
477
+ const referenced = n.MemberExpression.check(part) &&
478
+ !part.computed &&
479
+ n.Identifier.check(part.object) &&
480
+ n.Identifier.check(part.property);
481
+ if (referenced) {
482
+ const { object: sheet, property } = part;
483
+ object = moduleStyleReads.has(part)
484
+ ? styleSheets.get(sheet.name)?.get(property.name)
485
+ : undefined;
486
+ }
487
+ const style = object ? (0, style_1.styleUtilities)(object, read) : undefined;
488
+ if (!style)
489
+ return { ok: false, subject: 'style', why: 'a style the codemod cannot read' };
490
+ if (!style.ok)
491
+ return style;
492
+ classes.push(...style.classes);
493
+ mods.push(...style.mods);
494
+ if (referenced)
495
+ literals.set(part, style.literal);
496
+ }
497
+ for (const [part, literal] of literals)
498
+ styleLiterals.set(part, literal);
499
+ return { ok: true, classes, mods };
500
+ }
501
+ /** Each element's nearest enclosing element in the file. */
502
+ const enclosing = new Map();
503
+ recast.visit(ast, {
504
+ visitJSXElement(path) {
505
+ let at = path.parent;
506
+ while (at && !n.JSXElement.check(at.node))
507
+ at = at.parent;
508
+ if (at)
509
+ enclosing.set(path.node, at.node);
510
+ this.traverse(path);
511
+ },
512
+ });
513
+ /** The first element around `node` (in the file) drawn by one of `components` (`module#export`). */
514
+ function insideOf(node, components) {
515
+ for (let at = enclosing.get(node); at; at = enclosing.get(at)) {
516
+ const local = jsxName(at);
517
+ const source = local ? sources.get(local) : undefined;
518
+ if (source && components.includes(`${source.module}#${source.imported}`))
519
+ return local;
520
+ }
521
+ return undefined;
522
+ }
523
+ /**
524
+ * Each route's Screen: a default-exported function component (named, not
525
+ * async, no return type, its name read nowhere else) whose every return is a
526
+ * Bloom Screen becomes `screen(function …)`, each Screen its body's root.
527
+ */
528
+ const screenRoutes = new Map();
529
+ for (const statement of ast.program.body) {
530
+ const fn = n.ExportDefaultDeclaration.check(statement)
531
+ ? statement.declaration
532
+ : undefined;
533
+ if (!n.FunctionDeclaration.check(fn) || !fn.id || fn.async || fn.generator || fn.returnType)
534
+ continue;
535
+ const returned = [];
536
+ recast.visit(fn.body, {
537
+ visitFunction: () => false,
538
+ visitReturnStatement(path) {
539
+ returned.push(path.node.argument);
540
+ return false;
541
+ },
542
+ });
543
+ const isScreen = (node) => {
544
+ const local = n.JSXElement.check(node) ? jsxName(node) : undefined;
545
+ const source = local ? sources.get(local) : undefined;
546
+ return source?.module === '@oxy.so/bloom/screen' && source.imported === 'Screen';
547
+ };
548
+ const name = fn.id.name;
549
+ let named = 0;
550
+ recast.visit(ast, {
551
+ visitIdentifier(path) {
552
+ if (path.node.name === name)
553
+ named++;
554
+ this.traverse(path);
555
+ },
556
+ });
557
+ if (returned.length && returned.every(isScreen) && named === 1)
558
+ for (const node of returned)
559
+ screenRoutes.set(node, fn);
560
+ }
561
+ /**
562
+ * An icon's fill as the chain paints it: a Bloom theme colour read from
563
+ * `useTheme()` is its role, and a static colour (a literal, or a module
564
+ * constant) an app colour, the same colour in both schemes. Anything else is a reason.
565
+ */
566
+ function iconFill(node, fill) {
567
+ const reason = (code, why) => ({ reason: { subject: 'fill', code, why } });
568
+ const expression = attributeExpression(fill);
569
+ const role = themeRoles.get(expression);
570
+ if (role) {
571
+ const scope = insideOf(node, [COLOR_SCOPE]);
572
+ return scope
573
+ ? reason('icon-fill:color-scope', `a theme colour read outside the ${scope} the icon is drawn in, where the role paints the scope's scheme`)
574
+ : { role };
575
+ }
576
+ const constant = n.Identifier.check(expression) && colorConstantReads.has(expression)
577
+ ? expression.name
578
+ : undefined;
579
+ const value = constant ? colorConstants.get(constant)?.value : staticString(fill);
580
+ if (value !== undefined) {
581
+ if (!isAppColorValue(value))
582
+ return reason('icon-fill:not-a-colour', 'a colour the platforms do not paint alike (`currentColor`, an `hsl()`, a name only one knows): an app colour is a hex, an `rgb()` or `rgba()` of numbers, or a CSS colour name');
583
+ const name = constant ?? appColorName(value);
584
+ if (!constant && colorConstants.has(name))
585
+ return reason('icon-fill', `a colour whose token name the file declares (\`${name}\`)`);
586
+ return { color: constant ? { name, value, constant, read: expression } : { name, value } };
587
+ }
588
+ // `x.colors.key` or `colors.key` with no role, or not bound to `useTheme()` where it is read.
589
+ const object = n.MemberExpression.check(expression) ? expression.object : undefined;
590
+ const themed = object &&
591
+ !expression.computed &&
592
+ n.Identifier.check(expression.property) &&
593
+ ((n.Identifier.check(object) && object.name === 'colors') ||
594
+ (n.MemberExpression.check(object) &&
595
+ !object.computed &&
596
+ n.Identifier.check(object.property) &&
597
+ object.property.name === 'colors'));
598
+ if (themed && !ROLE_OF_THEME_COLOR.has(expression.property.name))
599
+ return reason('icon-fill:no-role', `a theme colour no language role paints (\`${expression.property.name}\`)`);
600
+ if (themed)
601
+ return reason('icon-fill:theme-handed-in', 'a theme colour read from a theme handed in (a prop, a parameter), not from `useTheme()` here: the scheme it was read in may not be the one the icon is drawn in');
602
+ return reason('icon-fill', 'a fill set at runtime, or read from outside the file');
603
+ }
604
+ const results = new Map();
605
+ const classes = new Set();
606
+ let candidates = 0;
607
+ const counted = new Set();
608
+ const unconverted = [];
609
+ const convertedNodes = new Set();
610
+ const convertedLocals = new Set();
611
+ /** The text style a Bloom typography component draws its Text in. */
612
+ function textStyleOf(local) {
613
+ const source = sources.get(local);
614
+ return source?.module === '@oxy.so/bloom/typography' ? components_1.TEXT_STYLES[source.imported] : undefined;
615
+ }
616
+ function elementOf(node) {
617
+ const local = jsxName(node);
618
+ if (!local)
619
+ return undefined;
620
+ const kind = kindOf(sources.get(local));
621
+ return kind ? { kind, local } : undefined;
622
+ }
623
+ /** Converts one element, children included; a child that cannot convert is embedded. */
624
+ function convert(node) {
625
+ const cached = results.get(node);
626
+ if (cached)
627
+ return cached;
628
+ const element = elementOf(node);
629
+ let result;
630
+ if (!element)
631
+ result = {
632
+ reasons: [{ subject: jsxName(node) ?? 'element', code: 'not-a-candidate', why: '' }],
633
+ };
634
+ else {
635
+ if (!counted.has(node)) {
636
+ counted.add(node);
637
+ candidates++;
638
+ }
639
+ result = convertCandidate(node, element.kind, element.local);
640
+ }
641
+ results.set(node, result);
642
+ return result;
643
+ }
644
+ function convertCandidate(node, kind, local) {
645
+ if (kind === 'rnImage')
646
+ return {
647
+ reasons: [
648
+ {
649
+ subject: 'Image',
650
+ code: 'react-native-image',
651
+ why: 'React Native’s Image: the language’s Image is Bloom’s BloomImage (expo-image on a device)',
652
+ },
653
+ ],
654
+ };
655
+ if (kind === 'button')
656
+ return convertButton(node);
657
+ if (kind === 'kept' && screenRoutes.has(node))
658
+ return convertScreen(node);
659
+ if (kind === 'kept') {
660
+ const source = sources.get(local);
661
+ const removed = components_1.REMOVED[`${source.module}#${source.imported}`];
662
+ return {
663
+ reasons: [
664
+ removed
665
+ ? {
666
+ subject: local,
667
+ code: `removed:${source.imported}`,
668
+ why: `removed in Bloom 22: use ${removed}`,
669
+ }
670
+ : {
671
+ subject: local,
672
+ code: `kept:${source.imported}`,
673
+ why: components_1.KEPT[`${source.module}#${source.imported}`],
674
+ },
675
+ ],
676
+ };
677
+ }
678
+ if (kind === 'component') {
679
+ const source = sources.get(local);
680
+ const rule = (0, components_1.ruleFor)(source.module, source.imported);
681
+ // A part converts with its compound element (`convertParts`), never alone.
682
+ if (rule.partOf)
683
+ return {
684
+ reasons: [
685
+ {
686
+ subject: local,
687
+ code: `${rule.node}:part`,
688
+ why: `a part of \`${rule.partOf.split('#')[1]}\`, converted only with it, which stays JSX here`,
689
+ },
690
+ ],
691
+ };
692
+ return rule.shell ? convertShell(node, rule, rule.shell) : convertComponent(node, rule);
693
+ }
694
+ const reasons = [];
695
+ const fail = (subject, code, why) => reasons.push({ subject, code, why });
696
+ const props = [];
697
+ let key = null;
698
+ let className = '';
699
+ /** A className chosen at runtime: its condition and the other branch's classes. */
700
+ let other;
701
+ let numberOfLines;
702
+ let variant;
703
+ let size;
704
+ /** The utilities a static `style` writes, read with the className. */
705
+ const styleClasses = [];
706
+ const styleMods = [];
707
+ /** An icon's `width`, `height` and `fill`. */
708
+ const iconProps = new Map();
709
+ for (const attribute of node.openingElement.attributes) {
710
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name)) {
711
+ fail('{...spread}', 'spread', 'spread props: the codemod cannot see what they set');
712
+ continue;
713
+ }
714
+ const name = attribute.name.name;
715
+ const value = attribute.value;
716
+ if (value === null || value === undefined) {
717
+ if (kind === 'pressable' && name === 'disabled')
718
+ props.push({ name: 'disabled', args: [] });
719
+ else
720
+ fail(name, `prop:${name}`, 'a boolean prop the codemod does not map');
721
+ continue;
722
+ }
723
+ const expression = attributeExpression(value);
724
+ if (name === 'key') {
725
+ key = { node: expression, hole: 'key', attribute };
726
+ continue;
727
+ }
728
+ if (name === 'className') {
729
+ const text = staticString(value);
730
+ const choice = text === undefined ? classNameChoice(expression) : undefined;
731
+ if (text !== undefined)
732
+ className = text;
733
+ else if (choice) {
734
+ className = choice.whenTrue;
735
+ other = { test: { node: choice.test, hole: 'condition' }, className: choice.whenFalse };
736
+ choiceClasses.set(expression, `${choice.whenTrue} ${choice.whenFalse}`);
737
+ }
738
+ else
739
+ fail('className', 'dynamic-className', 'a className built at runtime other than one of two static strings by a plain condition');
740
+ continue;
741
+ }
742
+ if (name === 'testID') {
743
+ props.push({
744
+ name: 'testID',
745
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
746
+ });
747
+ continue;
748
+ }
749
+ if (name === 'accessibilityLabel' && kind !== 'icon') {
750
+ props.push({
751
+ name: 'label',
752
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
753
+ });
754
+ continue;
755
+ }
756
+ if (kind !== 'icon' && name === 'accessibilityHint') {
757
+ props.push({
758
+ name: 'hint',
759
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
760
+ });
761
+ continue;
762
+ }
763
+ if (kind === 'pressable' && (name === 'onPress' || name === 'onLongPress')) {
764
+ props.push({ name, args: [{ node: expression, hole: 'handler' }] });
765
+ continue;
766
+ }
767
+ if (kind === 'pressable' && name === 'disabled') {
768
+ props.push({ name: 'disabled', args: [{ node: expression, hole: 'boolean' }] });
769
+ continue;
770
+ }
771
+ if ((kind === 'bloomText' || kind === 'rnText') && name === 'numberOfLines') {
772
+ numberOfLines = staticNumber(value) ?? { node: expression, hole: 'number' };
773
+ continue;
774
+ }
775
+ if (kind === 'bloomText' && name === 'variant') {
776
+ const text = staticString(value);
777
+ if (text === undefined || !RAMP.has(text))
778
+ fail('variant', 'variant', 'a variant that is no type-ramp step, or set at runtime');
779
+ else
780
+ variant = text;
781
+ continue;
782
+ }
783
+ if (name === 'style' && kind !== 'icon') {
784
+ // A theme colour read from `useTheme()` here is its role, as an icon's fill is.
785
+ const read = (key, read) => {
786
+ const role = themeRoles.get(read);
787
+ if (!role || insideOf(node, [COLOR_SCOPE]))
788
+ return undefined;
789
+ if (key === 'backgroundColor')
790
+ return { name: 'background', args: [role] };
791
+ if (key === 'color' && (kind === 'bloomText' || kind === 'rnText'))
792
+ return { name: 'foreground', args: [role] };
793
+ return undefined;
794
+ };
795
+ const style = staticStyle(expression, read);
796
+ if (style.ok) {
797
+ styleClasses.push(...style.classes);
798
+ styleMods.push(...style.mods);
799
+ }
800
+ else
801
+ fail(style.subject, 'style', style.why);
802
+ continue;
803
+ }
804
+ // What takes touches: `none` nothing (SwiftUI's `allowsHitTesting(false)`), `box-none` what is inside only, `box-only` the view only.
805
+ if (name === 'pointerEvents' && (kind === 'view' || kind === 'pressable')) {
806
+ const hitTesting = HIT_TESTING[staticString(value) ?? ''];
807
+ if (hitTesting !== undefined)
808
+ props.push({ name: 'allowsHitTesting', args: [hitTesting] });
809
+ else
810
+ fail(name, 'prop:pointerEvents', 'a pointerEvents set at runtime');
811
+ continue;
812
+ }
813
+ if (name === 'accessibilityRole' && kind !== 'icon') {
814
+ const role = staticString(value);
815
+ if (role !== undefined && ROLES.has(role))
816
+ props.push({ name: 'role', args: [role] });
817
+ else
818
+ fail(name, 'role', 'a role the language does not take, or set at runtime');
819
+ continue;
820
+ }
821
+ if (kind === 'icon' && name === 'size') {
822
+ size = value;
823
+ continue;
824
+ }
825
+ if (kind === 'icon' && (name === 'width' || name === 'height' || name === 'fill')) {
826
+ iconProps.set(name, value);
827
+ continue;
828
+ }
829
+ fail(name, `prop:${name}`, `the prop \`${name}\` has no mapping`);
830
+ }
831
+ for (const token of `${className} ${other?.className ?? ''}`.split(/\s+/).filter(Boolean))
832
+ classes.add(token);
833
+ if (styleClasses.length) {
834
+ className = [className, ...styleClasses].filter(Boolean).join(' ');
835
+ if (other)
836
+ other.className = [other.className, ...styleClasses].filter(Boolean).join(' ');
837
+ }
838
+ if (kind === 'icon') {
839
+ if (className || other)
840
+ fail('className', 'icon-className', 'a className on an icon');
841
+ const mods = [];
842
+ // A width and a height of one number are the glyph's side, as `size` is.
843
+ const width = iconProps.get('width');
844
+ const height = iconProps.get('height');
845
+ if (width !== undefined || height !== undefined) {
846
+ const side = staticNumber(width);
847
+ if (size !== undefined || side === undefined || staticNumber(height) !== side)
848
+ fail('width', 'icon-size', 'a width and a height that are not one static side');
849
+ else
850
+ size = width;
851
+ }
852
+ if (size !== undefined) {
853
+ // A rung by name, or a number of points that is a rung's (Bloom draws a number as its side).
854
+ const named = staticString(size);
855
+ const number = staticNumber(size);
856
+ const rung = ICON_SIZES.find(([k, v]) => k === named || v === number);
857
+ if (!rung)
858
+ fail('size', 'icon-size', 'an icon size that is no icon rung, or set at runtime');
859
+ else
860
+ mods.push({ name: 'size', args: [rung[0]] });
861
+ }
862
+ if (node.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
863
+ fail('children', 'icon-children', 'an icon with children');
864
+ const fill = iconProps.get('fill');
865
+ let color;
866
+ if (fill !== undefined) {
867
+ const ink = iconFill(node, fill);
868
+ if ('role' in ink)
869
+ mods.push({ name: 'foreground', args: [ink.role] });
870
+ else if ('color' in ink)
871
+ color = ink.color;
872
+ else
873
+ reasons.push(ink.reason);
874
+ }
875
+ else {
876
+ // A bare Bloom icon paints primary; Icon(X) paints the ink around it.
877
+ mods.push(...options.table.bareIcon);
878
+ }
879
+ if (reasons.length)
880
+ return { reasons };
881
+ return { ir: { type: 'icon', component: local, mods, key, ...(color && { color }) } };
882
+ }
883
+ const isText = kind === 'bloomText' || kind === 'rnText';
884
+ // Bloom's typography components (`Muted`, `H2`) are its Text in a text style.
885
+ const textStyle = textStyleOf(local);
886
+ if (textStyle && (className || other))
887
+ fail('className', 'text-style-className', 'a className on a typography component drops its own style');
888
+ const host = isText ? 'text' : kind;
889
+ const resolveOptions = {
890
+ overridden: options.overridden,
891
+ styleMods,
892
+ styleClasses: new Set(styleClasses),
893
+ };
894
+ let resolution = (0, resolve_1.resolveClassName)(className, host, options.table, resolveOptions);
895
+ if (!resolution.ok)
896
+ reasons.push(...resolution.reasons);
897
+ // The other branch resolves alike: the same modifiers, only their values differing, or a variant of each.
898
+ let choice = null;
899
+ if (other) {
900
+ const otherwise = (0, resolve_1.resolveClassName)(other.className, host, options.table, resolveOptions);
901
+ if (!otherwise.ok)
902
+ reasons.push(...otherwise.reasons);
903
+ else if (resolution.ok) {
904
+ const mods = sameShape(resolution.value, otherwise.value);
905
+ const only = mods ? undefined : branchesOnly(resolution.value, otherwise.value);
906
+ if (mods)
907
+ choice = { test: other.test, mods };
908
+ else if (only) {
909
+ choice = { test: other.test, only };
910
+ resolution = { ok: true, value: { ...resolution.value, mods: only.both } };
911
+ }
912
+ else
913
+ fail('className', 'dynamic-className', 'a className whose two branches differ in their layout axis or variants, or add a modifier a variant cannot change');
914
+ }
915
+ }
916
+ if (isText) {
917
+ const runs = [];
918
+ for (const child of node.children) {
919
+ if (n.JSXText.check(child)) {
920
+ const text = cleanJsxText(child.value);
921
+ if (text)
922
+ runs.push({ type: 'string', value: text });
923
+ }
924
+ else if (n.JSXExpressionContainer.check(child)) {
925
+ if (n.JSXEmptyExpression.check(child.expression))
926
+ fail('{/* */}', 'comment', 'a JSX comment (kept only in JSX)');
927
+ else if (n.StringLiteral.check(child.expression))
928
+ runs.push({ type: 'string', value: child.expression.value });
929
+ else
930
+ runs.push({ type: 'expr', value: { node: child.expression, hole: 'text' } });
931
+ }
932
+ else if (n.JSXElement.check(child)) {
933
+ const inner = convert(child);
934
+ const innerKind = elementOf(child)?.kind;
935
+ // A span is the same Text as its parent: Bloom's in Bloom's, React Native's in React Native's.
936
+ const span = jsxName(child);
937
+ if ('ir' in inner && innerKind === kind && !(span && textStyleOf(span)))
938
+ runs.push(inner.ir);
939
+ else
940
+ fail(jsxName(child) ?? 'element', 'text-child', 'an element inside a Text that is no convertible Text');
941
+ }
942
+ else
943
+ fail('child', 'text-child', 'a child inside a Text the codemod does not map');
944
+ }
945
+ if (!resolution.ok || reasons.length)
946
+ return { reasons };
947
+ const resolved = resolution.value;
948
+ const fontMods = textStyle ? [{ name: 'textStyle', args: [textStyle] }] : [];
949
+ if (variant) {
950
+ if ([...resolved.mods, ...choiceMods(choice)].some((m) => m.name === 'font' || m.name === 'weight'))
951
+ return {
952
+ reasons: [
953
+ { subject: 'variant', code: 'conflict', why: 'a variant and a className font' },
954
+ ],
955
+ };
956
+ const [family, weight] = [
957
+ variant.replace(/-(regular|medium|semibold|bold)$/, ''),
958
+ variant.split('-').pop(),
959
+ ];
960
+ fontMods.push({ name: 'font', args: [family] });
961
+ if (weight !== 'regular')
962
+ fontMods.push({ name: 'weight', args: [weight] });
963
+ }
964
+ if (numberOfLines !== undefined)
965
+ props.push({ name: 'lines', args: [numberOfLines] });
966
+ return {
967
+ ir: {
968
+ type: 'text',
969
+ raw: kind === 'rnText',
970
+ resolved: { ...resolved, mods: [...resolved.mods, ...fontMods] },
971
+ choice: choice && 'mods' in choice
972
+ ? { ...choice, mods: [...choice.mods, ...fontMods] }
973
+ : choice,
974
+ props,
975
+ key,
976
+ runs,
977
+ },
978
+ };
979
+ }
980
+ // A stack: View or Pressable. A Pressable with no press is still a focusable pressable; a stack with none is a View.
981
+ if (kind === 'pressable' &&
982
+ !props.some((p) => p.name === 'onPress' || p.name === 'onLongPress'))
983
+ fail('Pressable', 'pressable-without-press', 'a Pressable with no onPress or onLongPress stays a focusable pressable');
984
+ const children = [];
985
+ for (const child of node.children) {
986
+ if (n.JSXText.check(child)) {
987
+ if (cleanJsxText(child.value))
988
+ fail('text', 'raw-text', 'text directly inside a View');
989
+ }
990
+ else if (n.JSXExpressionContainer.check(child)) {
991
+ if (n.JSXEmptyExpression.check(child.expression)) {
992
+ const comment = commentOf(child);
993
+ if (comment)
994
+ children.push(comment);
995
+ else
996
+ fail('{/* */}', 'comment', 'a line comment in JSX (only a block comment moves)');
997
+ continue;
998
+ }
999
+ children.push(expressionChild(child.expression));
1000
+ }
1001
+ else if (n.JSXElement.check(child)) {
1002
+ const inner = convert(child);
1003
+ children.push('ir' in inner ? inner.ir : { type: 'embed', content: { node: child, hole: 'element' } });
1004
+ }
1005
+ else if (n.JSXFragment.check(child)) {
1006
+ children.push({ type: 'embed', content: { node: child, hole: 'element' } });
1007
+ }
1008
+ else
1009
+ fail('child', 'child', 'a child the codemod does not map');
1010
+ }
1011
+ if (!resolution.ok || reasons.length)
1012
+ return { reasons };
1013
+ if (isPressableScale(sources.get(local)))
1014
+ props.push({ name: 'pressScale', args: [] });
1015
+ return { ir: { type: 'stack', resolved: resolution.value, choice, props, key, children } };
1016
+ }
1017
+ /**
1018
+ * A route's Screen by `SCREEN`: its one child is the body's root, and several
1019
+ * (a fragment's, a comment or a condition among them) a `Group` of them, which
1020
+ * draws no view of its own; its props are the root's screen modifiers, with no
1021
+ * header `.header(false)`.
1022
+ */
1023
+ function convertScreen(node) {
1024
+ const inner = convertComponent(node, components_1.SCREEN);
1025
+ if (!('ir' in inner) || inner.ir.type !== 'component')
1026
+ return inner;
1027
+ const { args } = inner.ir;
1028
+ const only = args.length === 1 ? args[0] : undefined;
1029
+ const view = only && isTagged(only) && only.$ === 'view' ? only.view : undefined;
1030
+ if (!args.some((arg) => isTagged(arg) && arg.$ === 'view' && arg.view.type !== 'comment'))
1031
+ return {
1032
+ reasons: [
1033
+ {
1034
+ subject: 'children',
1035
+ code: 'screen:children',
1036
+ why: 'a screen with no content: the body’s root is a view',
1037
+ },
1038
+ ],
1039
+ };
1040
+ const root = view && view.type !== 'cond' && view.type !== 'comment'
1041
+ ? view
1042
+ : { type: 'component', node: 'Group', within: undefined, args, props: [], key: null };
1043
+ const props = inner.ir.props;
1044
+ if (!props.some((prop) => prop.name === 'header'))
1045
+ props.unshift({ name: 'header', args: [false] });
1046
+ return { ir: { type: 'screen', content: root, props } };
1047
+ }
1048
+ /**
1049
+ * A className that is one of two static strings by one condition:
1050
+ * `test ? 'a' : 'b'` (a branch of `''`, `undefined` or `null` writes no
1051
+ * class), or a template literal holding one such choice of strings. The
1052
+ * condition is a plain read (no call), since the chain reads it once per
1053
+ * value it chooses.
1054
+ */
1055
+ function classNameChoice(expression) {
1056
+ const template = n.TemplateLiteral.check(expression) && expression.expressions.length === 1;
1057
+ const choice = template ? expression.expressions[0] : expression;
1058
+ if (!n.ConditionalExpression.check(choice) || !isPlainRead(choice.test))
1059
+ return undefined;
1060
+ // Outside a template an absent branch is no className; inside one it would be the word.
1061
+ const branch = (node) => !template &&
1062
+ (n.NullLiteral.check(node) || (n.Identifier.check(node) && node.name === 'undefined'))
1063
+ ? ''
1064
+ : staticString(node);
1065
+ const [whenTrue, whenFalse] = [branch(choice.consequent), branch(choice.alternate)];
1066
+ if (whenTrue === undefined || whenFalse === undefined)
1067
+ return undefined;
1068
+ if (!template)
1069
+ return { test: choice.test, whenTrue, whenFalse };
1070
+ const [head, tail] = expression.quasis.map((q) => q.value.cooked);
1071
+ return {
1072
+ test: choice.test,
1073
+ whenTrue: head + whenTrue + tail,
1074
+ whenFalse: head + whenFalse + tail,
1075
+ };
1076
+ }
1077
+ /** The modifiers a choice writes besides the chain's. */
1078
+ function choiceMods(choice) {
1079
+ if (!choice)
1080
+ return [];
1081
+ return 'mods' in choice ? choice.mods : [...choice.only.whenTrue, ...choice.only.whenFalse];
1082
+ }
1083
+ /**
1084
+ * Each branch's own modifiers over those both write, when the branches lay
1085
+ * out on one axis with the same variants, and what each adds alone is what
1086
+ * a variant under the app's condition changes. Both branches resolved with
1087
+ * no two classes setting one thing, so a modifier one branch adds sets
1088
+ * nothing the other modifiers set: the variant adds it, overriding nothing.
1089
+ */
1090
+ function branchesOnly(chain, other) {
1091
+ if (chain.axis !== other.axis ||
1092
+ JSON.stringify(chain.variants) !== JSON.stringify(other.variants))
1093
+ return undefined;
1094
+ const rest = other.mods.map((mod) => JSON.stringify(mod));
1095
+ const both = [];
1096
+ const whenTrue = [];
1097
+ for (const mod of chain.mods) {
1098
+ const at = rest.indexOf(JSON.stringify(mod));
1099
+ if (at < 0)
1100
+ whenTrue.push(mod);
1101
+ else {
1102
+ both.push(mod);
1103
+ rest[at] = '';
1104
+ }
1105
+ }
1106
+ const whenFalse = other.mods.filter((_, i) => rest[i] !== '');
1107
+ return [...whenTrue, ...whenFalse].every(resolve_1.heldVariantChanges)
1108
+ ? { both, whenTrue, whenFalse }
1109
+ : undefined;
1110
+ }
1111
+ /**
1112
+ * The other branch's modifiers when they are the chain's, one for one, with
1113
+ * arguments of the same kinds (the same axis and variants too); else undefined.
1114
+ */
1115
+ function sameShape(chain, other) {
1116
+ const same = chain.axis === other.axis &&
1117
+ JSON.stringify(chain.variants) === JSON.stringify(other.variants) &&
1118
+ chain.mods.length === other.mods.length &&
1119
+ chain.mods.every((mod, i) => {
1120
+ const at = other.mods[i];
1121
+ return (mod.name === at.name &&
1122
+ mod.args.length === at.args.length &&
1123
+ mod.args.every((arg, j) => typeof arg === typeof at.args[j] && typeof arg !== 'object'));
1124
+ });
1125
+ return same ? other.mods : undefined;
1126
+ }
1127
+ /**
1128
+ * A shell around one input, as the input's node: the input by its own rule
1129
+ * (its shell is this one, so its context is), the glyphs beside it as the
1130
+ * node's `icon` and `trailingIcon`, and the shell's props joined to the input's.
1131
+ */
1132
+ function convertShell(node, rule, shell) {
1133
+ const fail = (subject, why) => ({
1134
+ reasons: [{ subject, code: `${rule.node}:${subject}`, why }],
1135
+ });
1136
+ const named = (child) => {
1137
+ const local = n.JSXElement.check(child) ? jsxName(child) : undefined;
1138
+ const source = local ? sources.get(local) : undefined;
1139
+ return source ? `${source.module}#${source.imported}` : undefined;
1140
+ };
1141
+ const children = node.children.filter((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === ''));
1142
+ const at = children.findIndex((child) => named(child) === shell.input);
1143
+ const input = children[at];
1144
+ const [inputSource] = shell.input.split('#');
1145
+ const inputRule = (0, components_1.ruleFor)(inputSource, shell.input.slice(inputSource.length + 1));
1146
+ if (!input || !inputRule || at > 1 || children.length > at + 2)
1147
+ return fail('children', 'a shell holds its input, a glyph before it and one after');
1148
+ // The shell's own props and its key.
1149
+ const own = [];
1150
+ let key = null;
1151
+ for (const attribute of node.openingElement.attributes) {
1152
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name))
1153
+ return fail('{...spread}', 'spread props: the codemod cannot see what they set');
1154
+ const name = attribute.name.name;
1155
+ if (name === 'key' && attribute.value) {
1156
+ key = { node: attributeExpression(attribute.value), hole: 'key', attribute };
1157
+ continue;
1158
+ }
1159
+ const prop = rule.props?.[name];
1160
+ const values = prop ? valuesOf(prop.form, attribute.value ?? null, prop.map) : undefined;
1161
+ if (!prop || !values)
1162
+ return fail(name, `the shell's \`${name}\` (or its form here) has no mapping`);
1163
+ own.push({ name: prop.modifier, args: values });
1164
+ }
1165
+ // Its glyphs: a TextFieldIcon before the input is the node's icon, one after its trailing icon.
1166
+ for (const [index, child] of children.entries()) {
1167
+ if (index === at)
1168
+ continue;
1169
+ if (named(child) !== shell.icon)
1170
+ return fail('children', 'a shell child that is no glyph');
1171
+ const position = index < at ? 'leading' : 'trailing';
1172
+ let icon;
1173
+ for (const attribute of child.openingElement.attributes) {
1174
+ const plain = n.JSXAttribute.check(attribute) && n.JSXIdentifier.check(attribute.name);
1175
+ const name = plain ? attribute.name.name : '{...spread}';
1176
+ const value = plain ? attribute.value : null;
1177
+ if (name === 'icon')
1178
+ icon = valuesOf('icon', value)?.[0];
1179
+ else if (name !== 'position' || staticString(value) !== position)
1180
+ return fail(name, `a glyph's \`${name}\` (or its form here) has no mapping`);
1181
+ }
1182
+ if (!icon)
1183
+ return fail('icon', 'a glyph that is no Bloom icon');
1184
+ own.push({ name: position === 'leading' ? 'icon' : 'trailingIcon', args: [icon] });
1185
+ }
1186
+ // The input by its own rule: its shell is this one, so the shell's context is its own.
1187
+ const inner = convertComponent(input, inputRule, false);
1188
+ if (!('ir' in inner) || inner.ir.type !== 'component')
1189
+ return inner;
1190
+ const props = inner.ir.props;
1191
+ const twice = own.find((prop) => props.some((p) => p.name === prop.name));
1192
+ if (twice)
1193
+ return fail(twice.name, 'set on the shell and on its input');
1194
+ if (inner.ir.key)
1195
+ return fail('key', 'a key on the input inside a shell');
1196
+ // The input converts with its shell, as one node.
1197
+ if (!counted.has(input)) {
1198
+ counted.add(input);
1199
+ candidates++;
1200
+ }
1201
+ const ir = { ...inner.ir, props: [...props, ...own], key };
1202
+ results.set(input, { ir });
1203
+ return { ir };
1204
+ }
1205
+ /** A Bloom component the language draws as a node of its own, by its rule (`components.ts`). */
1206
+ function convertComponent(node, rule,
1207
+ /** Whether the rule's `outside` applies: not to an input converted with its own shell. */
1208
+ checkOutside = true) {
1209
+ const reasons = [];
1210
+ const unmapped = (name) => reasons.push({
1211
+ subject: name,
1212
+ code: `${rule.node}:${name}`,
1213
+ why: `${rule.node}'s \`${name}\` (or its form here) has no mapping`,
1214
+ });
1215
+ const around = rule.outside && checkOutside ? insideOf(node, rule.outside) : undefined;
1216
+ if (around)
1217
+ reasons.push({
1218
+ subject: around,
1219
+ code: `${rule.node}:inside-${around}`,
1220
+ why: `inside a ${around}, whose context the Bloom component reads and the language's node does not`,
1221
+ });
1222
+ let key = null;
1223
+ /** Each prop's attribute value (`null` when it is bare). */
1224
+ const given = new Map();
1225
+ for (const attribute of node.openingElement.attributes) {
1226
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name)) {
1227
+ reasons.push({
1228
+ subject: '{...spread}',
1229
+ code: 'spread',
1230
+ why: 'spread props: the codemod cannot see what they set',
1231
+ });
1232
+ continue;
1233
+ }
1234
+ const name = attribute.name.name;
1235
+ if (name === 'key' && attribute.value)
1236
+ key = { node: attributeExpression(attribute.value), hole: 'key', attribute };
1237
+ else
1238
+ given.set(name, attribute.value ?? null);
1239
+ }
1240
+ const args = [];
1241
+ const consumed = new Set();
1242
+ let textChildren = false;
1243
+ /** The props of an object given as one value, each under its own name or the key beside its form. */
1244
+ const optionsOf = (options) => {
1245
+ const entries = [];
1246
+ for (const [name, entry] of Object.entries(options)) {
1247
+ consumed.add(name);
1248
+ if (!given.has(name))
1249
+ continue;
1250
+ const [key, form] = typeof entry === 'string' ? [name, entry] : entry;
1251
+ const value = valuesOf(form, given.get(name));
1252
+ // A bare flag is `true` in an object.
1253
+ if (value?.length === 0 && (form === 'flag' || form === 'mark'))
1254
+ entries.push([key, true]);
1255
+ else if (value?.length !== 1)
1256
+ unmapped(name);
1257
+ else
1258
+ entries.push([key, value[0]]);
1259
+ }
1260
+ return entries;
1261
+ };
1262
+ for (const param of rule.params ?? []) {
1263
+ if ('binding' in param) {
1264
+ const [valueProp, setters] = param.binding;
1265
+ const setProps = typeof setters === 'string' ? [setters] : setters;
1266
+ consumed.add(valueProp);
1267
+ for (const name of setProps)
1268
+ consumed.add(name);
1269
+ const value = given.get(valueProp);
1270
+ // One setter: two would be Bloom's choice between them, which the binding does not carry.
1271
+ const named = setProps.filter((name) => given.has(name));
1272
+ const set = named.length === 1 ? given.get(named[0]) : undefined;
1273
+ if (!value || !set)
1274
+ unmapped(valueProp);
1275
+ else
1276
+ args.push({
1277
+ $: 'binding',
1278
+ binding: [
1279
+ { node: attributeExpression(value), hole: param.hole },
1280
+ { node: attributeExpression(set), hole: 'handler' },
1281
+ ],
1282
+ });
1283
+ }
1284
+ else if ('options' in param) {
1285
+ const entries = optionsOf(param.options);
1286
+ args.push(entries.length ? { $: 'options', entries } : { $: 'absent' });
1287
+ }
1288
+ else if ('label' in param) {
1289
+ // Its glyphs and its label, as the node reads them from its content.
1290
+ textChildren = true;
1291
+ const glyph = (prop) => {
1292
+ if (!prop || !given.has(prop))
1293
+ return null;
1294
+ consumed.add(prop);
1295
+ const value = valuesOf('icon', given.get(prop));
1296
+ if (value?.length !== 1) {
1297
+ unmapped(prop);
1298
+ return null;
1299
+ }
1300
+ const { name } = value[0];
1301
+ return { $: 'view', view: { type: 'icon', component: name, mods: [], key: null } };
1302
+ };
1303
+ const leading = glyph(param.label.leading);
1304
+ const text = textOf(node.children);
1305
+ const trailing = glyph(param.label.trailing);
1306
+ if (leading)
1307
+ args.push(leading);
1308
+ if (text !== undefined)
1309
+ args.push({
1310
+ $: 'view',
1311
+ view: {
1312
+ type: 'text',
1313
+ raw: false,
1314
+ resolved: { axis: 'column', mods: [], variants: [] },
1315
+ choice: null,
1316
+ props: [],
1317
+ key: null,
1318
+ runs: [
1319
+ typeof text === 'string'
1320
+ ? { type: 'string', value: text }
1321
+ : { type: 'expr', value: text },
1322
+ ],
1323
+ },
1324
+ });
1325
+ else if (node.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
1326
+ unmapped('children');
1327
+ if (trailing)
1328
+ args.push(trailing);
1329
+ }
1330
+ else if ('text' in param) {
1331
+ textChildren = true;
1332
+ const children = param.text === true ? node.children : innerChildren(node.children, param.text);
1333
+ const text = children && textOf(children);
1334
+ if (text === undefined)
1335
+ unmapped('children');
1336
+ else
1337
+ args.push(text);
1338
+ }
1339
+ else {
1340
+ consumed.add(param.prop);
1341
+ if (!given.has(param.prop)) {
1342
+ if (param.optional)
1343
+ args.push({ $: 'absent' });
1344
+ else
1345
+ unmapped(param.prop);
1346
+ continue;
1347
+ }
1348
+ const value = valuesOf(param.form, given.get(param.prop));
1349
+ if (value?.length !== 1)
1350
+ unmapped(param.prop);
1351
+ else
1352
+ args.push(value[0]);
1353
+ }
1354
+ }
1355
+ const props = [];
1356
+ if (rule.gather) {
1357
+ const entries = optionsOf(rule.gather.props);
1358
+ if (entries.length)
1359
+ props.push({ name: rule.gather.modifier, args: [{ $: 'options', entries }] });
1360
+ }
1361
+ /** A binding that ends the chain (`.presented()`), written after every other modifier. */
1362
+ let last;
1363
+ // A prop that is another's modifier's next argument (or its close handler) is read with it.
1364
+ for (const prop of Object.values(rule.props ?? {})) {
1365
+ if (prop.with && given.has(prop.with[0]))
1366
+ consumed.add(prop.with[0]);
1367
+ if (prop.closedBy && given.has(prop.closedBy))
1368
+ consumed.add(prop.closedBy);
1369
+ for (const option of Object.keys(prop.options ?? {}))
1370
+ if (given.has(option))
1371
+ consumed.add(option);
1372
+ }
1373
+ for (const [name, value] of given) {
1374
+ if (consumed.has(name))
1375
+ continue;
1376
+ const differs = rule.differs?.[name];
1377
+ if (differs) {
1378
+ reasons.push({ subject: name, code: `${rule.node}:${name}`, why: differs });
1379
+ continue;
1380
+ }
1381
+ const prop = rule.props?.[name];
1382
+ if (prop?.form === 'className') {
1383
+ const text = value ? staticString(value) : undefined;
1384
+ const view = text === undefined ? undefined : contentViewOf(text);
1385
+ if (!view)
1386
+ unmapped(name);
1387
+ else if ('reasons' in view)
1388
+ reasons.push(...view.reasons);
1389
+ else
1390
+ props.push({ name: prop.modifier, args: [view] });
1391
+ continue;
1392
+ }
1393
+ if (prop?.form === 'contentStyle') {
1394
+ const margins = value ? contentStyleOf(attributeExpression(value)) : undefined;
1395
+ if (margins)
1396
+ props.push(...margins);
1397
+ else
1398
+ unmapped(name);
1399
+ continue;
1400
+ }
1401
+ if (prop?.marks) {
1402
+ // A static string naming the bare modifier, or none.
1403
+ const text = staticString(value);
1404
+ const mark = text === undefined ? undefined : prop.marks[text];
1405
+ if (mark === undefined)
1406
+ unmapped(name);
1407
+ else if (mark)
1408
+ props.push({ name: prop.modifier, args: [] });
1409
+ continue;
1410
+ }
1411
+ const values = prop ? valuesOf(prop.form, value, prop.map) : undefined;
1412
+ if (!prop || !values) {
1413
+ unmapped(name);
1414
+ continue;
1415
+ }
1416
+ if (prop.with && given.has(prop.with[0])) {
1417
+ const next = valuesOf(prop.with[1], given.get(prop.with[0]));
1418
+ if (next?.length !== 1)
1419
+ unmapped(prop.with[0]);
1420
+ else
1421
+ values.push(next[0]);
1422
+ }
1423
+ if (prop.closedBy) {
1424
+ // The value and the close handler, one binding: setting it false calls the handler.
1425
+ const close = given.has(prop.closedBy)
1426
+ ? actionOf(attributeExpression(given.get(prop.closedBy)))
1427
+ : undefined;
1428
+ if (values.length !== 1 || !close)
1429
+ unmapped(name);
1430
+ else
1431
+ last = {
1432
+ name: prop.modifier,
1433
+ args: [{ $: 'binding', binding: [values[0], close] }],
1434
+ };
1435
+ continue;
1436
+ }
1437
+ if (prop.options) {
1438
+ // Its options object, each prop given by its key.
1439
+ const entries = [];
1440
+ for (const [option, [key, form, map]] of Object.entries(prop.options)) {
1441
+ if (!given.has(option))
1442
+ continue;
1443
+ const value = valuesOf(form, given.get(option), map);
1444
+ if (value?.length !== 1)
1445
+ unmapped(option);
1446
+ else
1447
+ entries.push([key, value[0]]);
1448
+ }
1449
+ if (entries.length)
1450
+ values.push({ $: 'options', entries });
1451
+ }
1452
+ if (prop.key) {
1453
+ // One object for the modifier: each prop its key.
1454
+ const entry = [prop.key, values[0]];
1455
+ const joined = props.find((mod) => mod.name === prop.modifier);
1456
+ const object = joined?.args[0];
1457
+ if (values.length !== 1)
1458
+ unmapped(name);
1459
+ else if (object && isTagged(object) && object.$ === 'options')
1460
+ joined.args[0] = { $: 'options', entries: [...object.entries, entry] };
1461
+ else
1462
+ props.push({ name: prop.modifier, args: [{ $: 'options', entries: [entry] }] });
1463
+ continue;
1464
+ }
1465
+ props.push({ name: prop.modifier, args: [...values, ...(prop.args ?? [])] });
1466
+ }
1467
+ if (last)
1468
+ props.push(last);
1469
+ // A next argument (or a close handler) given without its modifier's prop.
1470
+ for (const [name, prop] of Object.entries(rule.props ?? {})) {
1471
+ if (prop.with && given.has(prop.with[0]) && !given.has(name))
1472
+ unmapped(prop.with[0]);
1473
+ if (prop.closedBy && given.has(prop.closedBy) && !given.has(name))
1474
+ unmapped(prop.closedBy);
1475
+ for (const option of Object.keys(prop.options ?? {}))
1476
+ if (given.has(option) && !given.has(name))
1477
+ unmapped(option);
1478
+ }
1479
+ /** Its parts, each converted with it. */
1480
+ const parts = new Map();
1481
+ if (rule.parts) {
1482
+ const converted = convertParts(node.children, rule.parts, parts);
1483
+ if ('reasons' in converted)
1484
+ reasons.push(...converted.reasons);
1485
+ else
1486
+ args.push(...converted.views.map((view) => ({ $: 'view', view })));
1487
+ }
1488
+ else if (rule.children) {
1489
+ // A fragment's children are the element's own, where the fragment is.
1490
+ const children = rule.fragments
1491
+ ? node.children.flatMap((child) => n.JSXFragment.check(child) ? child.children : [child])
1492
+ : node.children;
1493
+ for (const child of children) {
1494
+ const view = childView(child);
1495
+ if (view === null)
1496
+ continue;
1497
+ if (view === undefined)
1498
+ unmapped('children');
1499
+ else
1500
+ args.push({ $: 'view', view });
1501
+ }
1502
+ }
1503
+ else if (!textChildren &&
1504
+ node.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
1505
+ unmapped('children');
1506
+ for (const name of rule.always ?? [])
1507
+ props.push({ name, args: [] });
1508
+ // An optional argument left out at the end (children included) is no argument.
1509
+ while (args.length > 0 && isAbsent(args[args.length - 1]))
1510
+ args.pop();
1511
+ if (reasons.length)
1512
+ return { reasons };
1513
+ for (const [element, ir] of parts)
1514
+ results.set(element, { ir });
1515
+ return {
1516
+ ir: {
1517
+ type: 'component',
1518
+ node: rule.node,
1519
+ within: rule.within ??
1520
+ Object.entries(rule.props ?? {}).find(([name, prop]) => prop.within && given.has(name))?.[1].within,
1521
+ args,
1522
+ props,
1523
+ key,
1524
+ },
1525
+ };
1526
+ }
1527
+ /**
1528
+ * The children of a compound element as its parts (`module#export`), each
1529
+ * by its own rule: an element, a comment, or a `.map()` whose function
1530
+ * returns one (its array carried). Each part converted is added to `converted`.
1531
+ */
1532
+ function convertParts(children, parts, converted) {
1533
+ const reasons = [];
1534
+ const views = [];
1535
+ const names = parts.map((part) => `\`${part.split('#')[1]}\``).join(', ');
1536
+ const part = (element) => {
1537
+ const local = n.JSXElement.check(element) ? jsxName(element) : undefined;
1538
+ const source = local ? sources.get(local) : undefined;
1539
+ const rule = source && parts.includes(`${source.module}#${source.imported}`)
1540
+ ? (0, components_1.ruleFor)(source.module, source.imported)
1541
+ : undefined;
1542
+ if (!rule) {
1543
+ reasons.push({
1544
+ subject: local ?? 'children',
1545
+ code: 'not-a-part',
1546
+ why: `a child that is none of its parts (${names})`,
1547
+ });
1548
+ return undefined;
1549
+ }
1550
+ if (!counted.has(element)) {
1551
+ counted.add(element);
1552
+ candidates++;
1553
+ }
1554
+ const result = convertComponent(element, rule);
1555
+ if (!('ir' in result) || result.ir.type !== 'component') {
1556
+ if ('reasons' in result)
1557
+ reasons.push(...result.reasons);
1558
+ return undefined;
1559
+ }
1560
+ const ir = { ...result.ir, part: true };
1561
+ converted.set(element, ir);
1562
+ return ir;
1563
+ };
1564
+ for (const child of children) {
1565
+ if (n.JSXText.check(child) && !cleanJsxText(child.value))
1566
+ continue;
1567
+ const expression = n.JSXExpressionContainer.check(child) ? child.expression : undefined;
1568
+ if (expression && n.JSXEmptyExpression.check(expression)) {
1569
+ const comment = commentOf(child);
1570
+ if (comment)
1571
+ views.push(comment);
1572
+ else
1573
+ reasons.push({
1574
+ subject: '{/* */}',
1575
+ code: 'comment',
1576
+ why: 'a line comment in JSX (only a block comment moves)',
1577
+ });
1578
+ continue;
1579
+ }
1580
+ const map = expression ? mapOf(expression) : undefined;
1581
+ const body = part(map ? map.body : expression ? undefined : child);
1582
+ if (!body)
1583
+ continue;
1584
+ views.push(map
1585
+ ? { type: 'map', items: { node: map.items, hole: 'items' }, params: map.params, body }
1586
+ : body);
1587
+ }
1588
+ return reasons.length ? { reasons } : { views };
1589
+ }
1590
+ /** `items.map((item) => <Element />)`: its array, its function's parameters and the element it returns. */
1591
+ function mapOf(expression) {
1592
+ if (!n.CallExpression.check(expression) || expression.arguments.length !== 1)
1593
+ return undefined;
1594
+ const { callee } = expression;
1595
+ const fn = expression.arguments[0];
1596
+ if (!n.MemberExpression.check(callee) ||
1597
+ callee.computed ||
1598
+ !n.Identifier.check(callee.property) ||
1599
+ callee.property.name !== 'map' ||
1600
+ !n.ArrowFunctionExpression.check(fn) ||
1601
+ !n.JSXElement.check(fn.body))
1602
+ return undefined;
1603
+ return { items: callee.object, params: fn.params, body: fn.body };
1604
+ }
1605
+ /** The children of an element's one child, when it is `component` (`module#export`) with no props. */
1606
+ function innerChildren(children, component) {
1607
+ const given = children.filter((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === ''));
1608
+ const only = given.length === 1 && n.JSXElement.check(given[0]) ? given[0] : null;
1609
+ const source = only ? sources.get(jsxName(only) ?? '') : undefined;
1610
+ return source &&
1611
+ `${source.module}#${source.imported}` === component &&
1612
+ only.openingElement.attributes.length === 0
1613
+ ? only.children
1614
+ : undefined;
1615
+ }
1616
+ /**
1617
+ * A prop's value in a rule's form, as the modifier's arguments (none for a
1618
+ * bare flag), or undefined when the value is in a form the rule does not take.
1619
+ */
1620
+ function valuesOf(form, value, map) {
1621
+ if (value === null)
1622
+ // A bare prop is `true`.
1623
+ return form === 'flag' || form === 'mark'
1624
+ ? []
1625
+ : form === 'boolean'
1626
+ ? [true]
1627
+ : form === 'literal' && map?.true !== undefined
1628
+ ? [map.true]
1629
+ : undefined;
1630
+ const expression = attributeExpression(value);
1631
+ if (n.JSXEmptyExpression.check(expression))
1632
+ return undefined;
1633
+ switch (form) {
1634
+ case 'string': {
1635
+ const text = staticString(value);
1636
+ if (text !== undefined)
1637
+ return [text];
1638
+ return hasJsx(expression) ? undefined : [{ node: expression, hole: 'string' }];
1639
+ }
1640
+ case 'token': {
1641
+ // A token is a static string, or a static number of points (`spacing={12}`).
1642
+ const number = staticNumber(value);
1643
+ const text = staticString(value) ?? (number === undefined ? undefined : String(number));
1644
+ if (text === undefined)
1645
+ return undefined;
1646
+ const token = map ? map[text] : text;
1647
+ return token === undefined ? undefined : [token];
1648
+ }
1649
+ case 'flag':
1650
+ case 'boolean':
1651
+ if (n.BooleanLiteral.check(expression))
1652
+ return [expression.value];
1653
+ return hasJsx(expression) ? undefined : [{ node: expression, hole: 'boolean' }];
1654
+ case 'mark':
1655
+ return n.BooleanLiteral.check(expression) && expression.value ? [] : undefined;
1656
+ case 'empty':
1657
+ return n.ObjectExpression.check(expression) && expression.properties.length === 0
1658
+ ? []
1659
+ : undefined;
1660
+ case 'number': {
1661
+ const number = staticNumber(value);
1662
+ if (number !== undefined)
1663
+ return [number];
1664
+ return hasJsx(expression) || n.StringLiteral.check(expression)
1665
+ ? undefined
1666
+ : [{ node: expression, hole: 'number' }];
1667
+ }
1668
+ case 'handler':
1669
+ // `null` is a handler's own value (a header's `onBack={null}` shows no back button).
1670
+ if (n.NullLiteral.check(expression))
1671
+ return [{ $: 'null' }];
1672
+ return n.ArrowFunctionExpression.check(expression) ||
1673
+ n.FunctionExpression.check(expression) ||
1674
+ n.Identifier.check(expression) ||
1675
+ n.MemberExpression.check(expression) ||
1676
+ n.CallExpression.check(expression)
1677
+ ? [{ node: expression, hole: 'handler' }]
1678
+ : undefined;
1679
+ case 'view': {
1680
+ if (n.StringLiteral.check(expression) || n.TemplateLiteral.check(expression))
1681
+ return undefined;
1682
+ const view = n.JSXElement.check(expression) ? elementView(expression) : null;
1683
+ if (view)
1684
+ return [{ $: 'view', view }];
1685
+ if (n.JSXFragment.check(expression))
1686
+ return [
1687
+ { $: 'view', view: { type: 'embed', content: { node: expression, hole: 'element' } } },
1688
+ ];
1689
+ return [{ $: 'view', view: expressionChild(expression) }];
1690
+ }
1691
+ case 'icon':
1692
+ return n.Identifier.check(expression) && kindOf(sources.get(expression.name)) === 'icon'
1693
+ ? [{ $: 'icon', name: expression.name }]
1694
+ : undefined;
1695
+ case 'literal': {
1696
+ const token = n.BooleanLiteral.check(expression)
1697
+ ? map?.[String(expression.value)]
1698
+ : undefined;
1699
+ return token === undefined ? undefined : [token];
1700
+ }
1701
+ case 'refresh':
1702
+ return refreshOf(expression);
1703
+ case 'items':
1704
+ // Data carried as it is, the elements inside it (a row's trailing button) included.
1705
+ return n.JSXElement.check(expression) ||
1706
+ n.JSXFragment.check(expression) ||
1707
+ n.StringLiteral.check(expression)
1708
+ ? undefined
1709
+ : [{ node: expression, hole: 'items' }];
1710
+ case 'element':
1711
+ if (n.JSXElement.check(expression))
1712
+ return [{ $: 'view', view: elementView(expression) }];
1713
+ // A fragment, or a `const` holding an element, is drawn as it is.
1714
+ return n.JSXFragment.check(expression) || elementReads.has(expression)
1715
+ ? [{ $: 'view', view: { type: 'embed', content: { node: expression, hole: 'element' } } }]
1716
+ : undefined;
1717
+ case 'row': {
1718
+ const row = rowOf(expression);
1719
+ return row === undefined ? undefined : [row];
1720
+ }
1721
+ case 'placement':
1722
+ return placementOf(value);
1723
+ }
1724
+ }
1725
+ /**
1726
+ * Bloom's responsive placement as `.presentAt(base, tiers)`: a static token,
1727
+ * or an object literal of static tokens with its `base` and any of the
1728
+ * breakpoints, each tier written as Bloom reads it over the base.
1729
+ */
1730
+ function placementOf(value) {
1731
+ const text = staticString(value);
1732
+ if (text !== undefined) {
1733
+ const token = components_1.DIALOG_PLACEMENT[text];
1734
+ return token === undefined ? undefined : [token];
1735
+ }
1736
+ const object = attributeExpression(value);
1737
+ if (!n.ObjectExpression.check(object))
1738
+ return undefined;
1739
+ let base;
1740
+ const tiers = [];
1741
+ for (const property of object.properties) {
1742
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
1743
+ property.computed ||
1744
+ !n.Identifier.check(property.key))
1745
+ return undefined;
1746
+ const token = components_1.DIALOG_PLACEMENT[staticString(property.value) ?? ''];
1747
+ const key = property.key.name;
1748
+ if (token === undefined)
1749
+ return undefined;
1750
+ if (key === 'base')
1751
+ base = token;
1752
+ else if (components_1.PLACEMENT_TIERS.includes(key))
1753
+ tiers.push([key, token]);
1754
+ else
1755
+ return undefined;
1756
+ }
1757
+ // An object is drawn as an object (`{ base, ...tiers }`), its tiers none or more.
1758
+ return base === undefined ? undefined : [base, { $: 'options', entries: tiers }];
1759
+ }
1760
+ /**
1761
+ * A handler Bloom calls with no arguments, as a function of none: an arrow of
1762
+ * no parameters as it is (it ignores what it is called with), a name or a
1763
+ * member called with none (`() => onClose()`). Anything else may read an argument.
1764
+ */
1765
+ function actionOf(expression) {
1766
+ if (n.ArrowFunctionExpression.check(expression) && expression.params.length === 0)
1767
+ return { node: expression, hole: 'handler' };
1768
+ if (n.Identifier.check(expression) || n.MemberExpression.check(expression))
1769
+ return { node: expression, hole: 'action' };
1770
+ return undefined;
1771
+ }
1772
+ /**
1773
+ * A static content container style (an object literal or a module
1774
+ * StyleSheet's style) of paddings and a gap, each a space token, as the
1775
+ * scroll view's content margins and spacing: the language's content
1776
+ * container style holds the same keys.
1777
+ */
1778
+ function contentStyleOf(expression) {
1779
+ const object = moduleStyleReads.has(expression)
1780
+ ? styleSheets.get(expression.object.name)?.get(expression.property.name)
1781
+ : expression;
1782
+ if (!n.ObjectExpression.check(object))
1783
+ return undefined;
1784
+ const mods = [];
1785
+ for (const property of object.properties) {
1786
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
1787
+ property.computed ||
1788
+ !n.Identifier.check(property.key))
1789
+ return undefined;
1790
+ const token = components_1.SPACE[String(staticNumber(property.value))];
1791
+ const key = property.key.name;
1792
+ const edge = key === 'gap' ? undefined : CONTENT_EDGE[key];
1793
+ if (token === undefined || (key !== 'gap' && !edge))
1794
+ return undefined;
1795
+ mods.push(key === 'gap'
1796
+ ? { name: 'spacing', args: [token] }
1797
+ : { name: 'contentMargins', args: edge === 'all' ? [token] : [edge, token] });
1798
+ }
1799
+ if (object !== expression)
1800
+ styleLiterals.set(expression, recast.print(object).code);
1801
+ return mods;
1802
+ }
1803
+ /**
1804
+ * A scroll view's content class as its content view's build function: each
1805
+ * class through the className table, as a View's, and every modifier one the
1806
+ * content view takes (the spec's `contentView.modifiers`: the layout of one view).
1807
+ */
1808
+ function contentViewOf(className) {
1809
+ const resolution = (0, resolve_1.resolveClassName)(className, 'view', options.table, {
1810
+ overridden: options.overridden,
1811
+ });
1812
+ if (!resolution.ok)
1813
+ return { reasons: [...resolution.reasons] };
1814
+ for (const token of className.split(/\s+/).filter(Boolean))
1815
+ classes.add(token);
1816
+ const { axis, mods, variants } = resolution.value;
1817
+ const all = axis === 'row' ? [{ name: 'axis', args: ['horizontal'] }, ...mods] : [...mods];
1818
+ const subject = 'contentContainerClassName';
1819
+ if (variants.length)
1820
+ return {
1821
+ reasons: [
1822
+ {
1823
+ subject,
1824
+ code: 'contentView:variant',
1825
+ why: 'a content class with a variant (`md:`, `dark:`): the content view takes the layout of one view, without variants',
1826
+ },
1827
+ ],
1828
+ };
1829
+ const outside = all.find((mod) => !CONTENT_VIEW.has(mod.name));
1830
+ if (outside)
1831
+ return {
1832
+ reasons: [
1833
+ {
1834
+ subject,
1835
+ code: `contentView:${outside.name}`,
1836
+ why: `the content view takes the layout of one view (the spec's \`contentView.modifiers\`), not \`.${outside.name}()\``,
1837
+ },
1838
+ ],
1839
+ };
1840
+ return { $: 'build', mods: all };
1841
+ }
1842
+ /**
1843
+ * React Native's `RefreshControl` as a pull to refresh: its `refreshing` and
1844
+ * the binding a pull writes `true` to, which calls `onRefresh` with no
1845
+ * arguments as React Native does; its `tintColor` and `colors` as the tint
1846
+ * when both are one theme colour, since the tint paints both. A `tintColor`
1847
+ * alone tints iOS only, which no tint draws.
1848
+ */
1849
+ function refreshOf(expression) {
1850
+ const local = n.JSXElement.check(expression) ? jsxName(expression) : undefined;
1851
+ const source = local ? sources.get(local) : undefined;
1852
+ if (source?.module !== 'react-native' || source.imported !== 'RefreshControl')
1853
+ return undefined;
1854
+ if (expression.children.length)
1855
+ return undefined;
1856
+ const given = new Map();
1857
+ for (const attribute of expression.openingElement.attributes) {
1858
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name))
1859
+ return undefined;
1860
+ if (!attribute.value)
1861
+ return undefined;
1862
+ given.set(attribute.name.name, attributeExpression(attribute.value));
1863
+ }
1864
+ const { refreshing, onRefresh, tintColor, colors, ...rest } = Object.fromEntries(given);
1865
+ if (Object.keys(rest).length || !refreshing || !onRefresh || hasJsx(refreshing))
1866
+ return undefined;
1867
+ // A function of no parameters ignores the `true` a pull writes; a named one is called with none.
1868
+ const action = actionOf(onRefresh);
1869
+ if (!action)
1870
+ return undefined;
1871
+ const binding = {
1872
+ $: 'binding',
1873
+ binding: [{ node: refreshing, hole: 'boolean' }, action],
1874
+ };
1875
+ // Its import goes with the element when nothing else draws one.
1876
+ convertedLocals.add(local);
1877
+ if (!tintColor && !colors)
1878
+ return [binding];
1879
+ const tint = tintColor && themeRoles.get(tintColor);
1880
+ const [only, ...others] = n.ArrayExpression.check(colors) ? colors.elements : [];
1881
+ return tint && only && !others.length && themeRoles.get(only) === tint
1882
+ ? [binding, tint]
1883
+ : undefined;
1884
+ }
1885
+ /**
1886
+ * FlashList's `renderItem` as the node's row, which Bloom hands the same
1887
+ * `{ item, index }`: an arrow of one parameter returning an expression (its
1888
+ * parameter as written; an element as the row's view, anything else
1889
+ * embedded as it is), or a named function, carried as it is
1890
+ * (`VirtualList(posts, renderPost)`: the language draws its element as it
1891
+ * is, and the list's `renderItem` keeps its identity).
1892
+ */
1893
+ function rowOf(expression) {
1894
+ // A named renderItem is the row itself, as JSX handed it: its identity kept, so FlashList's memoised rows stay.
1895
+ if (n.Identifier.check(expression) || n.MemberExpression.check(expression))
1896
+ return { $: 'renderer', fn: { node: expression, hole: 'renderer' } };
1897
+ if (!n.ArrowFunctionExpression.check(expression) ||
1898
+ expression.params.length !== 1 ||
1899
+ n.BlockStatement.check(expression.body))
1900
+ return undefined;
1901
+ const [param] = expression.params;
1902
+ if (!n.Identifier.check(param) && !n.ObjectPattern.check(param))
1903
+ return undefined;
1904
+ const { body } = expression;
1905
+ // An element is converted where it can be; any other expression (`renderRow(item)`) is embedded as it is.
1906
+ const view = n.JSXElement.check(body)
1907
+ ? elementView(body)
1908
+ : { type: 'embed', content: { node: body, hole: 'element' } };
1909
+ return { $: 'row', param: recast.print(param).code, view };
1910
+ }
1911
+ /** An element as a view: converted when it can be, else embedded. */
1912
+ function elementView(element) {
1913
+ const inner = convert(element);
1914
+ return 'ir' in inner
1915
+ ? inner.ir
1916
+ : { type: 'embed', content: { node: element, hole: 'element' } };
1917
+ }
1918
+ /** A JSX comment's block comments as a code comment; undefined for a line comment. */
1919
+ function commentOf(container) {
1920
+ const text = source.slice(container.start + 1, container.end - 1).trim();
1921
+ // Block comments only: a line comment would swallow the arguments after it.
1922
+ return text.startsWith('/*') && text.endsWith('*/') && !text.includes('//')
1923
+ ? { type: 'comment', text }
1924
+ : undefined;
1925
+ }
1926
+ /**
1927
+ * A list of views as arguments: a comment sits before the view after it
1928
+ * (after the last one when it ends the list), never an argument of its own.
1929
+ */
1930
+ function printViews(views, carry) {
1931
+ const out = [];
1932
+ let pending = [];
1933
+ for (const view of views) {
1934
+ if (view.type === 'comment')
1935
+ pending.push(view.text);
1936
+ else {
1937
+ out.push([...pending, print(view, carry)].join(' '));
1938
+ pending = [];
1939
+ }
1940
+ }
1941
+ if (pending.length && out.length)
1942
+ out[out.length - 1] += ` ${pending.join(' ')}`;
1943
+ else if (pending.length)
1944
+ out.push(pending.join(' '));
1945
+ return out;
1946
+ }
1947
+ /** A child of a view-holding element as a view; null when it is no child, undefined when it is text. */
1948
+ function childView(child) {
1949
+ if (n.JSXText.check(child))
1950
+ return cleanJsxText(child.value) ? undefined : null;
1951
+ if (n.JSXExpressionContainer.check(child)) {
1952
+ if (n.JSXEmptyExpression.check(child.expression))
1953
+ return commentOf(child);
1954
+ if (n.StringLiteral.check(child.expression) || n.TemplateLiteral.check(child.expression))
1955
+ return undefined;
1956
+ return expressionChild(child.expression);
1957
+ }
1958
+ if (n.JSXElement.check(child))
1959
+ return elementView(child);
1960
+ if (n.JSXFragment.check(child))
1961
+ return { type: 'embed', content: { node: child, hole: 'element' } };
1962
+ return undefined;
1963
+ }
1964
+ /** An element's children as one string: one static text, or one expression (a hole). */
1965
+ function textOf(children) {
1966
+ const runs = children.filter((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === ''));
1967
+ if (runs.length !== 1)
1968
+ return undefined;
1969
+ const run = runs[0];
1970
+ if (n.JSXText.check(run))
1971
+ return cleanJsxText(run.value);
1972
+ if (!n.JSXExpressionContainer.check(run) || n.JSXEmptyExpression.check(run.expression))
1973
+ return undefined;
1974
+ const text = staticString(run);
1975
+ if (text !== undefined)
1976
+ return text;
1977
+ return hasJsx(run.expression) ? undefined : { node: run.expression, hole: 'string' };
1978
+ }
1979
+ /** Bloom's `Button`, as the language's Button parity cases draw it (`packages/bloom-language/parity/button.cases.tsx`). */
1980
+ function convertButton(node) {
1981
+ const reasons = [];
1982
+ const fail = (subject, code, why) => reasons.push({ subject, code, why });
1983
+ const props = [];
1984
+ let key = null;
1985
+ let leading = null;
1986
+ let trailing = null;
1987
+ const flags = new Set();
1988
+ const ENUM = {
1989
+ appearance: 'style',
1990
+ tone: 'tint',
1991
+ size: 'size',
1992
+ density: 'density',
1993
+ linkTone: 'linkTone',
1994
+ };
1995
+ const BOOLEAN = {
1996
+ disabled: 'disabled',
1997
+ loading: 'loading',
1998
+ pressed: 'pressed',
1999
+ inverted: 'inverted',
2000
+ };
2001
+ const icon = (value) => {
2002
+ const expression = attributeExpression(value);
2003
+ return n.Identifier.check(expression) && kindOf(sources.get(expression.name)) === 'icon'
2004
+ ? expression.name
2005
+ : undefined;
2006
+ };
2007
+ for (const attribute of node.openingElement.attributes) {
2008
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name)) {
2009
+ fail('{...spread}', 'spread', 'spread props: the codemod cannot see what they set');
2010
+ continue;
2011
+ }
2012
+ const name = attribute.name.name;
2013
+ const value = attribute.value;
2014
+ const expression = value ? attributeExpression(value) : null;
2015
+ if (name === 'key' && expression)
2016
+ key = { node: expression, hole: 'key', attribute };
2017
+ else if (ENUM[name] && staticString(value) !== undefined)
2018
+ props.push({ name: ENUM[name], args: [staticString(value)] });
2019
+ else if (BOOLEAN[name] && (value === null || value === undefined))
2020
+ props.push({ name: BOOLEAN[name], args: [] });
2021
+ else if (BOOLEAN[name] && expression)
2022
+ props.push({
2023
+ name: BOOLEAN[name],
2024
+ args: [{ node: expression, hole: 'boolean' }],
2025
+ });
2026
+ else if (['iconOnly', 'wide', 'grow'].includes(name) &&
2027
+ (value === null || value === undefined))
2028
+ flags.add(name);
2029
+ else if (name === 'leadingIcon' && icon(value))
2030
+ leading = icon(value);
2031
+ else if (name === 'trailingIcon' && icon(value))
2032
+ trailing = icon(value);
2033
+ else if (name === 'accessibilityLabel' && value)
2034
+ props.push({
2035
+ name: 'label',
2036
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
2037
+ });
2038
+ else if ((name === 'onPress' || name === 'onLongPress') && expression)
2039
+ props.push({ name, args: [{ node: expression, hole: 'handler' }] });
2040
+ else if (name === 'testID' && value)
2041
+ props.push({
2042
+ name: 'testID',
2043
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
2044
+ });
2045
+ else
2046
+ fail(name, `button:${name}`, `Button's \`${name}\` (or its form here) has no mapping`);
2047
+ }
2048
+ const shape = flags.has('iconOnly')
2049
+ ? flags.has('wide')
2050
+ ? 'pill'
2051
+ : 'circle'
2052
+ : flags.has('grow')
2053
+ ? 'fit'
2054
+ : null;
2055
+ if (flags.has('wide') && !flags.has('iconOnly'))
2056
+ fail('wide', 'button:wide', 'wide without iconOnly');
2057
+ if (flags.has('grow') && flags.has('iconOnly'))
2058
+ fail('grow', 'button:grow', 'grow with iconOnly');
2059
+ if (shape)
2060
+ props.unshift({ name: 'shape', args: [shape] });
2061
+ const runs = [];
2062
+ for (const child of node.children) {
2063
+ if (n.JSXText.check(child)) {
2064
+ const text = cleanJsxText(child.value);
2065
+ if (text)
2066
+ runs.push({ type: 'string', value: text });
2067
+ }
2068
+ else if (n.JSXExpressionContainer.check(child) &&
2069
+ !n.JSXEmptyExpression.check(child.expression)) {
2070
+ if (n.StringLiteral.check(child.expression))
2071
+ runs.push({ type: 'string', value: child.expression.value });
2072
+ else
2073
+ runs.push({ type: 'expr', value: { node: child.expression, hole: 'text' } });
2074
+ }
2075
+ else
2076
+ fail('child', 'button-child', 'a Button child that is no text');
2077
+ }
2078
+ if (reasons.length)
2079
+ return { reasons };
2080
+ return { ir: { type: 'button', leading, trailing, runs, props, key } };
2081
+ }
2082
+ /** A `{…}` child of a stack: a converted branch where its form is safe, else embedded. */
2083
+ function expressionChild(expression) {
2084
+ const branch = (node) => {
2085
+ if (n.NullLiteral.check(node))
2086
+ return null;
2087
+ if (n.JSXElement.check(node)) {
2088
+ const inner = convert(node);
2089
+ return 'ir' in inner ? inner.ir : undefined;
2090
+ }
2091
+ return undefined;
2092
+ };
2093
+ if (n.ConditionalExpression.check(expression)) {
2094
+ const then = branch(expression.consequent);
2095
+ const otherwise = branch(expression.alternate);
2096
+ if (then !== undefined && otherwise !== undefined && (then || otherwise))
2097
+ return {
2098
+ type: 'cond',
2099
+ test: { node: expression.test, hole: 'condition' },
2100
+ then,
2101
+ otherwise,
2102
+ };
2103
+ }
2104
+ if (n.LogicalExpression.check(expression) &&
2105
+ expression.operator === '&&' &&
2106
+ isBooleanForm(expression.left)) {
2107
+ const then = branch(expression.right);
2108
+ if (then)
2109
+ return {
2110
+ type: 'cond',
2111
+ test: { node: expression.left, hole: 'condition' },
2112
+ then,
2113
+ otherwise: null,
2114
+ };
2115
+ }
2116
+ return { type: 'embed', content: { node: expression, hole: 'element' } };
2117
+ }
2118
+ // ── printing ─────────────────────────────────────────────────────────
2119
+ /** Prints the chain; with `holes`, each carried value is its hole. */
2120
+ function print(ir, carry, root = false) {
2121
+ switch (ir.type) {
2122
+ case 'embed':
2123
+ return `${lang('Embed')}(${carry(ir.content)})`;
2124
+ case 'comment':
2125
+ return ir.text;
2126
+ case 'screen':
2127
+ return `${print(ir.content, carry)}${ir.props.map((p) => printProp(p, carry)).join('')}`;
2128
+ case 'cond':
2129
+ return `${carry(ir.test)} ? ${ir.then ? print(ir.then, carry) : 'null'} : ${ir.otherwise ? print(ir.otherwise, carry) : 'null'}`;
2130
+ case 'map':
2131
+ return `${carry(ir.items)}.map((${ir.params.map((param) => recast.print(param).code).join(', ')}) => ${print(ir.body, carry)})`;
2132
+ case 'icon':
2133
+ return `${lang('Icon')}(${ir.component})${ir.mods.map(printMod).join('')}${ir.color ? `.foreground(${appColorTable}.color.${ir.color.name})` : ''}${ir.key && !root ? `.id(${carry(ir.key)})` : ''}`;
2134
+ case 'component': {
2135
+ // Its children (the trailing views) with their comments; the arguments before them as values.
2136
+ const first = ir.args.findIndex((a) => isTagged(a) && a.$ === 'view');
2137
+ const leading = first === -1 ? ir.args : ir.args.slice(0, first);
2138
+ const views = first === -1 ? [] : ir.args.slice(first);
2139
+ const args = [
2140
+ ...leading.map((a) => printValue(a, carry)),
2141
+ ...(views.every((a) => isTagged(a) && a.$ === 'view')
2142
+ ? printViews(views.map((a) => a.view), carry)
2143
+ : views.map((a) => printValue(a, carry))),
2144
+ ].join(', ');
2145
+ const tail = ir.props.map((p) => printProp(p, carry)).join('');
2146
+ return `${lang(ir.node)}(${args})${tail}${ir.key && !root && !ir.part ? `.id(${carry(ir.key)})` : ''}`;
2147
+ }
2148
+ case 'button': {
2149
+ const parts = [];
2150
+ if (ir.leading)
2151
+ parts.push(`${lang('Icon')}(${ir.leading})`);
2152
+ if (ir.runs.length)
2153
+ parts.push(`${lang('Text')}(${ir.runs.map((run) => ('type' in run && run.type === 'string' ? quote(run.value) : carry(run.value))).join(', ')})`);
2154
+ if (ir.trailing)
2155
+ parts.push(`${lang('Icon')}(${ir.trailing})`);
2156
+ const tail = ir.props.map((p) => printProp(p, carry)).join('');
2157
+ return `${lang('Button')}(${parts.join(', ')})${tail}${ir.key && !root ? `.id(${carry(ir.key)})` : ''}`;
2158
+ }
2159
+ case 'text': {
2160
+ const runs = ir.runs.map((run) => 'type' in run && run.type === 'string'
2161
+ ? quote(run.value)
2162
+ : 'type' in run && run.type === 'expr'
2163
+ ? carry(run.value)
2164
+ : print(run, carry));
2165
+ return `${lang(ir.raw ? 'RawText' : 'Text')}(${runs.join(', ')})${chainTail(ir.resolved, ir.choice, ir.props, root ? null : ir.key, carry)}`;
2166
+ }
2167
+ case 'stack': {
2168
+ const ctor = lang(ir.resolved.axis === 'row' ? 'HStack' : 'VStack');
2169
+ const children = printViews(ir.children, carry);
2170
+ return `${ctor}(${children.join(', ')})${chainTail(ir.resolved, ir.choice, ir.props, root ? null : ir.key, carry)}`;
2171
+ }
2172
+ }
2173
+ }
2174
+ function chainTail(resolved, choice, props, key, carry) {
2175
+ // A value the other branch writes differently is chosen by its condition.
2176
+ let out = resolved.mods
2177
+ .map((mod, i) => {
2178
+ const other = choice && 'mods' in choice ? choice.mods[i] : undefined;
2179
+ if (!choice || !other)
2180
+ return printMod(mod);
2181
+ const args = mod.args.map((arg, j) => {
2182
+ const alternative = other.args[j];
2183
+ return arg === alternative
2184
+ ? printArg(arg)
2185
+ : `${carry(choice.test)} ? ${printArg(arg)} : ${printArg(alternative)}`;
2186
+ });
2187
+ return `.${mod.name}(${args.join(', ')})`;
2188
+ })
2189
+ .join('');
2190
+ // What one branch alone adds is a variant of its condition, before the live variants, which override it.
2191
+ if (choice && 'only' in choice) {
2192
+ const test = carry(choice.test);
2193
+ const plain = n.Identifier.check(choice.test.node) || n.MemberExpression.check(choice.test.node);
2194
+ const holds = isBooleanForm(choice.test.node) ? test : `Boolean(${test})`;
2195
+ const fails = plain ? `!${test}` : `!(${test})`;
2196
+ for (const [condition, mods] of [
2197
+ [holds, choice.only.whenTrue],
2198
+ [fails, choice.only.whenFalse],
2199
+ ])
2200
+ if (mods.length)
2201
+ out += `.when(${condition}, (v) => v${mods.map(printMod).join('')})`;
2202
+ }
2203
+ for (const variant of resolved.variants) {
2204
+ let inner = `v${variant.mods.map(printMod).join('')}`;
2205
+ for (const condition of [...variant.conditions].reverse().slice(0, -1))
2206
+ inner = `v.when(${quote(condition)}, (v) => ${inner})`;
2207
+ out += `.when(${quote(variant.conditions[0])}, (v) => ${inner})`;
2208
+ }
2209
+ for (const prop of props)
2210
+ out += printProp(prop, carry);
2211
+ if (key)
2212
+ out += `.id(${carry(key)})`;
2213
+ return out;
2214
+ }
2215
+ function printValue(value, carry) {
2216
+ if (isCarried(value))
2217
+ return value.hole === 'action' ? `() => ${carry(value)}()` : carry(value);
2218
+ if (isTagged(value)) {
2219
+ switch (value.$) {
2220
+ case 'view':
2221
+ return print(value.view, carry);
2222
+ case 'binding':
2223
+ return `[${printValue(value.binding[0], carry)}, ${printValue(value.binding[1], carry)}]`;
2224
+ case 'icon':
2225
+ return value.name;
2226
+ case 'options':
2227
+ return value.entries.length
2228
+ ? `{ ${value.entries.map(([key, v]) => `${key}: ${printValue(v, carry)}`).join(', ')} }`
2229
+ : '{}';
2230
+ case 'row':
2231
+ return `(${value.param}) => ${print(value.view, carry)}`;
2232
+ case 'build':
2233
+ return `(v) => v${value.mods.map(printMod).join('')}`;
2234
+ case 'renderer':
2235
+ return carry(value.fn);
2236
+ case 'absent':
2237
+ return 'undefined';
2238
+ case 'null':
2239
+ return 'null';
2240
+ }
2241
+ }
2242
+ return printArg(value);
2243
+ }
2244
+ const printProp = (prop, carry) => `.${prop.name}(${prop.args.map((a) => printValue(a, carry)).join(', ')})`;
2245
+ /** The carried values inside a value, in order. */
2246
+ function carriedOfValue(value, out) {
2247
+ if (isCarried(value))
2248
+ out.push(value);
2249
+ else if (isTagged(value)) {
2250
+ if (value.$ === 'view' || value.$ === 'row')
2251
+ carriedOf(value.view, out);
2252
+ else if (value.$ === 'binding')
2253
+ for (const v of value.binding)
2254
+ carriedOfValue(v, out);
2255
+ else if (value.$ === 'renderer')
2256
+ out.push(value.fn);
2257
+ else if (value.$ === 'options')
2258
+ for (const [, v] of value.entries)
2259
+ carriedOfValue(v, out);
2260
+ }
2261
+ }
2262
+ /** The views a value holds. */
2263
+ function viewsOfValue(value) {
2264
+ if (!isTagged(value))
2265
+ return [];
2266
+ if (value.$ === 'view' || value.$ === 'row')
2267
+ return [value.view];
2268
+ if (value.$ === 'options')
2269
+ return value.entries.flatMap(([, v]) => viewsOfValue(v));
2270
+ return [];
2271
+ }
2272
+ /** The views directly inside a view: its children, spans, branches and the views its values hold. */
2273
+ function childrenOf(ir) {
2274
+ const props = 'props' in ir ? ir.props.flatMap((prop) => prop.args.flatMap(viewsOfValue)) : [];
2275
+ switch (ir.type) {
2276
+ case 'cond':
2277
+ return [ir.then, ir.otherwise].filter((branch) => branch !== null);
2278
+ case 'map':
2279
+ return [ir.body];
2280
+ case 'component':
2281
+ return [...ir.args.flatMap(viewsOfValue), ...props];
2282
+ case 'text':
2283
+ return [
2284
+ ...ir.runs.filter((run) => !('type' in run && (run.type === 'string' || run.type === 'expr'))),
2285
+ ...props,
2286
+ ];
2287
+ case 'stack':
2288
+ return [...ir.children, ...props];
2289
+ case 'screen':
2290
+ return [ir.content, ...props];
2291
+ default:
2292
+ return props;
2293
+ }
2294
+ }
2295
+ /** Every carried value of a tree, in order. */
2296
+ function carriedOf(ir, out = []) {
2297
+ switch (ir.type) {
2298
+ case 'embed':
2299
+ out.push(ir.content);
2300
+ break;
2301
+ case 'screen':
2302
+ carriedOf(ir.content, out);
2303
+ for (const prop of ir.props)
2304
+ for (const a of prop.args)
2305
+ carriedOfValue(a, out);
2306
+ break;
2307
+ case 'cond':
2308
+ out.push(ir.test);
2309
+ if (ir.then)
2310
+ carriedOf(ir.then, out);
2311
+ if (ir.otherwise)
2312
+ carriedOf(ir.otherwise, out);
2313
+ break;
2314
+ case 'map':
2315
+ out.push(ir.items);
2316
+ carriedOf(ir.body, out);
2317
+ break;
2318
+ case 'icon':
2319
+ if (ir.key)
2320
+ out.push(ir.key);
2321
+ break;
2322
+ case 'component':
2323
+ for (const a of ir.args)
2324
+ carriedOfValue(a, out);
2325
+ for (const prop of ir.props)
2326
+ for (const a of prop.args)
2327
+ carriedOfValue(a, out);
2328
+ if (ir.key)
2329
+ out.push(ir.key);
2330
+ break;
2331
+ case 'button':
2332
+ for (const run of ir.runs)
2333
+ if ('type' in run && run.type === 'expr')
2334
+ out.push(run.value);
2335
+ for (const prop of ir.props)
2336
+ for (const a of prop.args)
2337
+ carriedOfValue(a, out);
2338
+ if (ir.key)
2339
+ out.push(ir.key);
2340
+ break;
2341
+ case 'text':
2342
+ for (const run of ir.runs)
2343
+ if ('type' in run && run.type === 'expr')
2344
+ out.push(run.value);
2345
+ else if (!('type' in run && run.type === 'string'))
2346
+ carriedOf(run, out);
2347
+ if (ir.choice)
2348
+ out.push(ir.choice.test);
2349
+ for (const prop of ir.props)
2350
+ for (const a of prop.args)
2351
+ carriedOfValue(a, out);
2352
+ if (ir.key)
2353
+ out.push(ir.key);
2354
+ break;
2355
+ case 'stack':
2356
+ for (const child of ir.children)
2357
+ carriedOf(child, out);
2358
+ if (ir.choice)
2359
+ out.push(ir.choice.test);
2360
+ for (const prop of ir.props)
2361
+ for (const a of prop.args)
2362
+ carriedOfValue(a, out);
2363
+ if (ir.key)
2364
+ out.push(ir.key);
2365
+ break;
2366
+ }
2367
+ return out;
2368
+ }
2369
+ // ── fixtures ─────────────────────────────────────────────────────────
2370
+ const fixtures = [];
2371
+ const HOLE = {
2372
+ text: (i) => `'⟨${i}⟩'`,
2373
+ string: (i) => `'⟨${i}⟩'`,
2374
+ key: (i) => `'k${i}'`,
2375
+ number: () => '2',
2376
+ boolean: () => 'true',
2377
+ handler: () => '() => {}',
2378
+ action: () => '(() => {})',
2379
+ element: (i) => `<Hole n="${i}" />`,
2380
+ // The corpus's sample items (`corpus.ts`), the same array on both sides.
2381
+ items: () => 'ITEMS',
2382
+ // A row function drawing each item's index, so the argument it is handed is proven.
2383
+ renderer: (i) => `((${ROW_INFO}) => <Hole n={'${i}-' + ${ROW_INFO}.index} />)`,
2384
+ };
2385
+ /**
2386
+ * The region's fixture; a region with a condition has a second with every
2387
+ * condition false, so each branch it chooses between is drawn.
2388
+ */
2389
+ function fixture(node, ir, rootKey, conditions = true) {
2390
+ const carried = carriedOf(ir).filter((c) => c !== rootKey);
2391
+ if (conditions && carried.some((c) => c.hole === 'condition'))
2392
+ fixture(node, ir, rootKey, false);
2393
+ const index = new Map(carried.map((c, i) => [c, i]));
2394
+ const hole = (c) => c.hole === 'condition' ? String(conditions) : HOLE[c.hole](index.get(c) ?? 0);
2395
+ const removed = rootKey?.attribute;
2396
+ const after = ir.type === 'screen' ? print(ir, hole, true) : `toElement(${print(ir, hole, true)})`;
2397
+ // The source of the region, each carried value replaced by its hole.
2398
+ let before = '';
2399
+ let at = node.start;
2400
+ const spans = carried.map((c) => ({
2401
+ start: c.node.start,
2402
+ end: c.node.end,
2403
+ text: hole(c),
2404
+ }));
2405
+ if (removed)
2406
+ spans.push({ start: removed.start, end: removed.end, text: '' });
2407
+ // An element's type arguments (`<SegmentedControl<Cadence>`) draw nothing, and name the app's types.
2408
+ recast.visit(node, {
2409
+ visitJSXOpeningElement(path) {
2410
+ const opening = path.node;
2411
+ const types = opening.typeParameters ?? opening.typeArguments;
2412
+ if (types)
2413
+ spans.push({ start: types.start, end: types.end, text: '' });
2414
+ this.traverse(path);
2415
+ },
2416
+ });
2417
+ // A StyleSheet's style is its object literal on the before side.
2418
+ for (const [read, literal] of styleLiterals)
2419
+ if (read.start >= node.start && read.end <= node.end)
2420
+ spans.push({ start: read.start, end: read.end, text: literal });
2421
+ // A theme colour the chain names by its role is read from the theme the before side is drawn in.
2422
+ let themed = false;
2423
+ for (const [read] of themeRoles)
2424
+ if (read.start >= node.start && read.end <= node.end) {
2425
+ themed = true;
2426
+ spans.push({
2427
+ start: read.start,
2428
+ end: read.end,
2429
+ text: `parityTheme.colors.${read.property.name}`,
2430
+ });
2431
+ }
2432
+ // A constant the chain names as an app colour is its colour on the before side, drawn without the module.
2433
+ const colors = colorsOf(ir);
2434
+ for (const color of colors)
2435
+ if (color.read)
2436
+ spans.push({ start: color.read.start, end: color.read.end, text: quote(color.value) });
2437
+ spans.sort((a, b) => a.start - b.start);
2438
+ for (const span of spans) {
2439
+ if (span.start < at)
2440
+ continue;
2441
+ before += source.slice(at, span.start) + span.text;
2442
+ at = span.end;
2443
+ }
2444
+ before += source.slice(at, node.end);
2445
+ const bindings = {};
2446
+ for (const local of new Set([...uncommented(before).matchAll(/<\/?([A-Z][\w]*)/g)].map((m) => m[1])))
2447
+ if (sources.has(local))
2448
+ bindings[local] = sources.get(local);
2449
+ for (const match of uncommented(after).matchAll(/\b([A-Z][\w]*)\b/g)) {
2450
+ const local = match[1];
2451
+ if (sources.has(local))
2452
+ bindings[local] = sources.get(local);
2453
+ }
2454
+ const regionClasses = new Set();
2455
+ // A className, and a content class (`contentContainerClassName`).
2456
+ for (const m of before.matchAll(/(?:className|ClassName)=["'`{]+([^"'`}]*)/g))
2457
+ for (const token of m[1].split(/\s+/).filter(Boolean))
2458
+ regionClasses.add(token);
2459
+ for (const [read, both] of choiceClasses)
2460
+ if (read.start >= node.start && read.end <= node.end)
2461
+ for (const token of both.split(/\s+/).filter(Boolean))
2462
+ regionClasses.add(token);
2463
+ fixtures.push({
2464
+ name: `${options.name ?? 'file'}:${node.loc?.start.line ?? 0}${conditions ? '' : ' (false)'}`,
2465
+ before,
2466
+ after,
2467
+ bindings,
2468
+ language: [...usedLanguage.entries()].map(([name, local]) => name === local ? name : `${name}: ${local}`),
2469
+ classes: [...regionClasses],
2470
+ // A route's Screen is the Screen its nodes are drawn in.
2471
+ within: withinOf(ir).filter((key) => ir.type !== 'screen' || key !== SCREEN_KEY),
2472
+ themed,
2473
+ screen: ir.type === 'screen',
2474
+ appColors: colors.length
2475
+ ? {
2476
+ table: appColorTable,
2477
+ color: Object.fromEntries(colors.map((c) => [c.name, c.value])),
2478
+ }
2479
+ : null,
2480
+ });
2481
+ }
2482
+ /** The app colours a region's icons paint with. */
2483
+ function colorsOf(ir) {
2484
+ const found = [];
2485
+ const visit = (at) => {
2486
+ if (at.type === 'icon' && at.color)
2487
+ found.push(at.color);
2488
+ for (const child of childrenOf(at))
2489
+ visit(child);
2490
+ };
2491
+ visit(ir);
2492
+ return found;
2493
+ }
2494
+ /** The Bloom components the region's nodes are drawn only inside. */
2495
+ function withinOf(ir) {
2496
+ const found = new Set();
2497
+ const visit = (at) => {
2498
+ if (at.type === 'component' && at.within)
2499
+ found.add(at.within);
2500
+ for (const child of childrenOf(at))
2501
+ visit(child);
2502
+ };
2503
+ visit(ir);
2504
+ return [...found];
2505
+ }
2506
+ // ── the walk ─────────────────────────────────────────────────────────
2507
+ let regions = 0;
2508
+ const markConverted = (node) => {
2509
+ recast.visit(node, {
2510
+ visitJSXElement(path) {
2511
+ const result = results.get(path.node);
2512
+ if (result && 'ir' in result) {
2513
+ convertedNodes.add(path.node);
2514
+ const local = jsxName(path.node);
2515
+ if (local)
2516
+ convertedLocals.add(local);
2517
+ this.traverse(path);
2518
+ }
2519
+ else
2520
+ return false;
2521
+ },
2522
+ });
2523
+ };
2524
+ const visitor = {
2525
+ visitJSXElement(path) {
2526
+ const node = path.node;
2527
+ const result = convert(node);
2528
+ if (!('ir' in result)) {
2529
+ if (elementOf(node))
2530
+ unconverted.push({
2531
+ line: node.loc?.start.line ?? 0,
2532
+ element: jsxName(node) ?? '',
2533
+ reasons: result.reasons,
2534
+ });
2535
+ this.traverse(path);
2536
+ return undefined;
2537
+ }
2538
+ regions++;
2539
+ markConverted(node);
2540
+ const ir = result.ir;
2541
+ const rootKey = 'key' in ir ? ir.key : null;
2542
+ // The file's table holds every app colour a region paints with.
2543
+ for (const color of colorsOf(ir)) {
2544
+ appColors.set(color.name, color);
2545
+ lang('defineTokens');
2546
+ }
2547
+ if (options.fixtures)
2548
+ fixture(node, ir, rootKey);
2549
+ // Regions inside the values it carries (an embedded element's children, an array's elements).
2550
+ for (const c of carriedOf(ir)) {
2551
+ if (c.hole === 'element' || c.hole === 'items') {
2552
+ // An element can sit at the root of what is carried; visit inside it.
2553
+ const holder = { type: 'ExpressionStatement', expression: c.node };
2554
+ recast.visit(holder, visitor);
2555
+ c.node.__carried = holder.expression;
2556
+ }
2557
+ }
2558
+ const carry = (c) => recast.print(c.node.__carried ?? c.node).code;
2559
+ const chain = print(ir, carry, true);
2560
+ // A route's Screen is its body's root, the chain itself.
2561
+ if (ir.type === 'screen')
2562
+ routes.add(screenRoutes.get(node));
2563
+ const code = ir.type === 'screen'
2564
+ ? chain
2565
+ : `${lang('toElement')}(${chain}${rootKey ? `, ${carry(rootKey)}` : ''})`;
2566
+ // Parsed by recast, so the comments the chain carries are printed where they are.
2567
+ const expression = recast.parse(`${code};`, { parser: babelTs }).program.body[0].expression;
2568
+ const parent = path.parent?.node;
2569
+ const inJsx = parent &&
2570
+ (n.JSXElement.check(parent) || n.JSXFragment.check(parent) || n.JSXAttribute.check(parent));
2571
+ path.replace(inJsx ? recast.types.builders.jsxExpressionContainer(expression) : expression);
2572
+ return false;
2573
+ },
2574
+ };
2575
+ // Bloom components the codemod does not map, counted before the walk rewrites anything.
2576
+ const bloomComponents = {};
2577
+ recast.visit(ast, {
2578
+ visitJSXOpeningElement(path) {
2579
+ const local = n.JSXIdentifier.check(path.node.name)
2580
+ ? path.node.name.name
2581
+ : undefined;
2582
+ const source = local ? sources.get(local) : undefined;
2583
+ if (source?.module.startsWith('@oxy.so/bloom') && !kindOf(source)) {
2584
+ const key = `${source.module}#${source.imported}`;
2585
+ bloomComponents[key] = (bloomComponents[key] ?? 0) + 1;
2586
+ }
2587
+ this.traverse(path);
2588
+ },
2589
+ });
2590
+ // A route converts whole: a Screen it returns that stays JSX keeps the others JSX.
2591
+ for (const fn of new Set(screenRoutes.values())) {
2592
+ const screens = [...screenRoutes].filter(([, of]) => of === fn).map(([node]) => node);
2593
+ if (screens.every((node) => 'ir' in convert(node)))
2594
+ continue;
2595
+ for (const node of screens)
2596
+ if ('ir' in convert(node))
2597
+ results.set(node, {
2598
+ reasons: [
2599
+ {
2600
+ subject: 'Screen',
2601
+ code: 'screen:route',
2602
+ why: 'another return of the route stays JSX, and a route converts whole',
2603
+ },
2604
+ ],
2605
+ });
2606
+ }
2607
+ /** The routes whose Screens converted: each becomes `screen(function …)`. */
2608
+ const routes = new Set();
2609
+ recast.visit(ast, visitor);
2610
+ for (const statement of ast.program.body)
2611
+ if (n.ExportDefaultDeclaration.check(statement) && routes.has(statement.declaration)) {
2612
+ const fn = statement.declaration;
2613
+ const b = recast.types.builders;
2614
+ const body = b.functionExpression(fn.id, fn.params, fn.body);
2615
+ body.typeParameters = fn.typeParameters;
2616
+ statement.declaration = b.callExpression(b.identifier(lang('screen')), [body]);
2617
+ }
2618
+ const converted = [...counted].filter((node) => convertedNodes.has(node)).length;
2619
+ if (regions > 0) {
2620
+ // Imports: the language's names in, and the converted components' out when nothing else uses them.
2621
+ const remaining = new Map();
2622
+ recast.visit(ast, {
2623
+ visitJSXIdentifier(path) {
2624
+ remaining.set(path.node.name, (remaining.get(path.node.name) ?? 0) + 1);
2625
+ this.traverse(path);
2626
+ },
2627
+ visitIdentifier(path) {
2628
+ const parent = path.parent?.node;
2629
+ if (!n.ImportSpecifier.check(parent) && !n.ImportDefaultSpecifier.check(parent))
2630
+ remaining.set(path.node.name, (remaining.get(path.node.name) ?? 0) + 1);
2631
+ this.traverse(path);
2632
+ },
2633
+ });
2634
+ const body = ast.program.body;
2635
+ for (const statement of [...body]) {
2636
+ if (!n.ImportDeclaration.check(statement))
2637
+ continue;
2638
+ const before = statement.specifiers?.length ?? 0;
2639
+ statement.specifiers = (statement.specifiers ?? []).filter((s) => {
2640
+ const local = s.local?.name;
2641
+ return !(convertedLocals.has(local) && !remaining.get(local));
2642
+ });
2643
+ if (before > 0 && statement.specifiers.length === 0)
2644
+ body.splice(body.indexOf(statement), 1);
2645
+ }
2646
+ // `screen` is the router's; every other name the language's own.
2647
+ const imports = (module, names) => {
2648
+ if (!names.length)
2649
+ return [];
2650
+ const specifiers = names
2651
+ .sort(([a], [b]) => (a < b ? -1 : 1))
2652
+ .map(([name, local]) => (name === local ? name : `${name} as ${local}`));
2653
+ return recast.parse(`import { ${specifiers.join(', ')} } from '${module}';\n`, {
2654
+ parser: babelTs,
2655
+ }).program.body;
2656
+ };
2657
+ const names = [...usedLanguage.entries()];
2658
+ const declarations = [
2659
+ ...imports(LANGUAGE_MODULE, names.filter(([name]) => name !== 'screen')),
2660
+ ...imports(`${LANGUAGE_MODULE}/router`, names.filter(([name]) => name === 'screen')),
2661
+ ];
2662
+ const lastImport = body.reduce((last, s, i) => (n.ImportDeclaration.check(s) ? i : last), -1);
2663
+ body.splice(lastImport + 1, 0, ...declarations);
2664
+ if (appColors.size > 0) {
2665
+ // The app colour table, after the imports and the constants it reads.
2666
+ const entries = [...appColors.values()].map((c) => c.constant ? c.constant : `${c.name}: ${quote(c.value)}`);
2667
+ const table = recast.parse(`const ${appColorTable} = ${lang('defineTokens')}({ color: { ${entries.join(', ')} } });\n`, { parser: babelTs }).program.body[0];
2668
+ const after = Math.max(lastImport + 1, ...[...appColors.values()].map((c) => c.constant ? body.indexOf(colorConstants.get(c.constant)?.statement) : -1));
2669
+ body.splice(after + 1, 0, table);
2670
+ }
2671
+ }
2672
+ return {
2673
+ code: regions > 0 ? recast.print(ast).code : source,
2674
+ changed: regions > 0,
2675
+ candidates,
2676
+ converted,
2677
+ regions,
2678
+ unconverted,
2679
+ fixtures,
2680
+ classes: [...classes],
2681
+ bloomComponents,
2682
+ };
2683
+ }