@tamagui/codemod-flat-values 0.0.0-bootstrap.0 → 3.0.0-beta.643.1

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,1139 @@
1
+ import { Node, SyntaxKind } from "ts-morph";
2
+ import { compact, literalTree, numericValue, runtimeType, staticLeafValue, unwrapExpression } from "./expressions.mjs";
3
+ import { assessFlatConversion, convertLegacyConditionProp, expandToLonghands, flatStringValue, mergeProgramValues, parseValue, printProgram, resolveProp, sharedPayload, shorthands, styleProps, unitSuffix } from "./grammar.mjs";
4
+ import { isLegacyConditionName, resolveLegacyName } from "./legacyNames.mjs";
5
+ import { classifyStructuredNativeValue } from "./structuredNative.mjs";
6
+
7
+ function assessmentVerdict(assessments) {
8
+ if (assessments.some((assessment) => assessment.verdict === "ineligible")) {
9
+ return "ineligible";
10
+ }
11
+ if (assessments.some((assessment) => assessment.verdict === "needs-relocation")) {
12
+ return "needs-relocation";
13
+ }
14
+ return assessments.length ? "unknown-host" : "clean";
15
+ }
16
+ function createSite(kind, registry, containers, targets, host) {
17
+ return {
18
+ kind,
19
+ registry,
20
+ containers,
21
+ targets,
22
+ host,
23
+ members: [],
24
+ comments: /* @__PURE__ */ new Map(),
25
+ extras: [],
26
+ warnings: [],
27
+ flags: [],
28
+ inventory: [],
29
+ pending: [],
30
+ assessments: [],
31
+ notes: [],
32
+ legacy: false,
33
+ index: 0
34
+ };
35
+ }
36
+ function assessProgram(site, property, modifiers) {
37
+ const targetProperty = resolveProp(property);
38
+ const assessment = assessFlatConversion({
39
+ property: targetProperty,
40
+ modifiers,
41
+ targets: site.targets,
42
+ host: site.host
43
+ }, site.registry);
44
+ if (assessment.verdict !== "clean") addAssessment(site, targetProperty, assessment);
45
+ return assessment.verdict !== "ineligible";
46
+ }
47
+ function addAssessment(site, property, assessment) {
48
+ if (assessment.verdict === "clean") return;
49
+ if (!site.assessments.some((finding) => finding.property === property && finding.verdict === assessment.verdict && JSON.stringify(finding.reasons) === JSON.stringify(assessment.reasons))) {
50
+ site.assessments.push({
51
+ property,
52
+ verdict: assessment.verdict,
53
+ reasons: assessment.reasons
54
+ });
55
+ }
56
+ }
57
+ function addFlag(list, code, detail) {
58
+ if (!list.some((flag) => flag.code === code && flag.detail === detail)) {
59
+ list.push({
60
+ code,
61
+ detail
62
+ });
63
+ }
64
+ }
65
+ function addNote(site, note) {
66
+ if (!site.notes.includes(note)) site.notes.push(note);
67
+ }
68
+ const legacyPaletteStepPattern = /(?:^|[^\w-])\$?((?:gray|mauve|slate|sage|olive|sand|tomato|red|ruby|crimson|pink|plum|purple|violet|iris|indigo|blue|cyan|teal|jade|green|grass|bronze|gold|brown|orange|amber|yellow|lime|mint|sky)(?:1[0-2]|[1-9]))(?![\w-])/g;
69
+ function legacyPaletteStepWarning(prop, values) {
70
+ const names = /* @__PURE__ */ new Set();
71
+ for (const value of values) {
72
+ legacyPaletteStepPattern.lastIndex = 0;
73
+ for (const match of value.matchAll(legacyPaletteStepPattern)) names.add(match[1]);
74
+ }
75
+ if (!names.size) return null;
76
+ const formatted = [...names].sort().map((name) => `\`${name}\``).join(", ");
77
+ return {
78
+ code: "legacy-palette-token",
79
+ detail: `${prop} preserves ${formatted}, which @tamagui/config/v6 does not define; choose an absolute palette token or an adaptive colorN value`
80
+ };
81
+ }
82
+ const empty = {
83
+ payload: null,
84
+ text: null,
85
+ dynamic: false,
86
+ problem: null,
87
+ warning: null,
88
+ blocked: null,
89
+ inventory: null
90
+ };
91
+ function interpolate(prop, text, kind, registry) {
92
+ return `\${${text}}${kind === "number" ? unitSuffix(resolveProp(prop), registry) : ""}`;
93
+ }
94
+ function classifyStatic(prop, value, registry) {
95
+ const probe = sharedPayload(prop, value, registry);
96
+ const error = probe.errors[0];
97
+ if (error || probe.payload === null) {
98
+ const flag = {
99
+ code: error?.code ?? "unsupported-legacy-value",
100
+ detail: `${prop}: ${error?.message ?? `"${String(value)}" has no flat spelling`}`
101
+ };
102
+ return {
103
+ ...empty,
104
+ problem: flag,
105
+ blocked: flag
106
+ };
107
+ }
108
+ return {
109
+ ...empty,
110
+ payload: probe.payload
111
+ };
112
+ }
113
+ function reparsesAsBase(value, registry) {
114
+ const parsed = parseValue(value, registry);
115
+ return parsed.ok && parsed.value.clauses.length === 0 && parsed.value.base === value.trim();
116
+ }
117
+ function classifyDynamic(prop, expression, registry) {
118
+ const current = unwrapExpression(expression);
119
+ const source = compact(current.getText());
120
+ const structured = classifyStructuredNativeValue(resolveProp(prop), current, source, registry);
121
+ if (structured) {
122
+ return {
123
+ ...empty,
124
+ payload: structured.payload,
125
+ blocked: structured.blocked
126
+ };
127
+ }
128
+ const tree = literalTree(current, registry);
129
+ if (tree && tree.error) {
130
+ const flag2 = {
131
+ code: tree.error.code,
132
+ detail: `${prop}: ${tree.error.message}`
133
+ };
134
+ return {
135
+ ...empty,
136
+ problem: flag2,
137
+ blocked: flag2
138
+ };
139
+ }
140
+ if (tree && tree.kind !== "nullish") {
141
+ const rewrittenTokenText = /\$(?=[\w-])/.test(source) && tree.text !== source ? tree.text : null;
142
+ return {
143
+ ...empty,
144
+ payload: interpolate(prop, tree.text, tree.kind, registry),
145
+ text: rewrittenTokenText,
146
+ dynamic: true,
147
+ warning: legacyPaletteStepWarning(prop, tree.strings)
148
+ };
149
+ }
150
+ if (tree) {
151
+ const flag2 = {
152
+ code: "empty-style-value",
153
+ detail: `${prop} value "${source}" is always nullish and cannot join a program`
154
+ };
155
+ return {
156
+ ...empty,
157
+ blocked: flag2
158
+ };
159
+ }
160
+ const runtime = runtimeType(current);
161
+ if (runtime.kind === "number") {
162
+ return {
163
+ ...empty,
164
+ payload: interpolate(prop, source, "number", registry),
165
+ dynamic: true
166
+ };
167
+ }
168
+ if (runtime.kind === "string") {
169
+ const tokens = runtime.literals?.filter((literal) => literal.startsWith("$"));
170
+ if (tokens?.length) {
171
+ const flag2 = {
172
+ code: "legacy-token-constant",
173
+ detail: `${prop} value "${source}" resolves to legacy token ${tokens.map((token) => `"${token}"`).join(", ")}; migrate the constant it comes from`
174
+ };
175
+ return {
176
+ ...empty,
177
+ problem: flag2,
178
+ blocked: flag2
179
+ };
180
+ }
181
+ if (runtime.literals === null) {
182
+ return {
183
+ ...empty,
184
+ payload: interpolate(prop, source, "string", registry),
185
+ dynamic: true,
186
+ inventory: {
187
+ code: "dynamic-string-value",
188
+ detail: `${prop} value "${source}" is an open string; confirm it never holds a legacy "$token" spelling`
189
+ }
190
+ };
191
+ }
192
+ return {
193
+ ...empty,
194
+ payload: interpolate(prop, source, "string", registry),
195
+ dynamic: true
196
+ };
197
+ }
198
+ const flag = {
199
+ code: "unprovable-dynamic-value",
200
+ detail: `${prop} value "${source}" has no provable number or string type, so it cannot fold into a program`
201
+ };
202
+ return {
203
+ ...empty,
204
+ blocked: flag
205
+ };
206
+ }
207
+ function pushBase(site, prop, text, value, literalString) {
208
+ const index = site.index++;
209
+ if (literalString !== null) {
210
+ const warning = legacyPaletteStepWarning(prop, [literalString]);
211
+ if (warning) addFlag(site.warnings, warning.code, warning.detail);
212
+ if (literalString.includes("$")) {
213
+ site.legacy = true;
214
+ const allowed2 = assessProgram(site, prop, []);
215
+ const flat = flatStringValue(literalString, site.registry);
216
+ const problem = flat.text === null ? {
217
+ code: flat.error?.code ?? "unsupported-legacy-value",
218
+ detail: `${prop}: ${flat.error?.message ?? `${JSON.stringify(literalString)} has no flat spelling`}`
219
+ } : !reparsesAsBase(flat.text, site.registry) ? {
220
+ code: "value-reparses-as-program",
221
+ detail: `${prop} value ${JSON.stringify(flat.text)} does not read back as one flat base value`
222
+ } : null;
223
+ if (problem !== null) addFlag(site.flags, problem.code, problem.detail);
224
+ site.members.push({
225
+ type: "authored",
226
+ index,
227
+ prop,
228
+ text,
229
+ payload: allowed2 && problem === null ? flat.text : null,
230
+ dynamic: false,
231
+ blocked: problem,
232
+ token: allowed2,
233
+ activated: false
234
+ });
235
+ return;
236
+ }
237
+ if (!reparsesAsBase(literalString, site.registry)) {
238
+ const flag = {
239
+ code: "value-reparses-as-program",
240
+ detail: `${prop} value ${JSON.stringify(literalString)} does not read back as one flat base value`
241
+ };
242
+ addFlag(site.flags, flag.code, flag.detail);
243
+ site.members.push({
244
+ type: "authored",
245
+ index,
246
+ prop,
247
+ text,
248
+ payload: null,
249
+ dynamic: false,
250
+ blocked: flag,
251
+ token: false,
252
+ activated: false
253
+ });
254
+ return;
255
+ }
256
+ site.members.push({
257
+ type: "authored",
258
+ index,
259
+ prop,
260
+ text,
261
+ payload: literalString,
262
+ dynamic: false,
263
+ blocked: null,
264
+ token: false,
265
+ activated: false
266
+ });
267
+ return;
268
+ }
269
+ const number = value ? numericValue(value) : null;
270
+ if (number !== null) {
271
+ const classified2 = classifyStatic(prop, number, site.registry);
272
+ site.members.push({
273
+ type: "authored",
274
+ index,
275
+ prop,
276
+ text,
277
+ payload: classified2.payload,
278
+ dynamic: false,
279
+ blocked: classified2.blocked,
280
+ token: false,
281
+ activated: false
282
+ });
283
+ return;
284
+ }
285
+ const kind = value?.getKind();
286
+ if (value === null || kind === SyntaxKind.TrueKeyword || kind === SyntaxKind.FalseKeyword || kind === SyntaxKind.NullKeyword) {
287
+ site.members.push({
288
+ type: "authored",
289
+ index,
290
+ prop,
291
+ text,
292
+ payload: null,
293
+ dynamic: false,
294
+ blocked: {
295
+ code: "non-css-style-value",
296
+ detail: `${prop} value "${compact(text)}" is not a CSS value and cannot join a program`
297
+ },
298
+ token: false,
299
+ activated: false
300
+ });
301
+ return;
302
+ }
303
+ const classified = classifyDynamic(prop, value, site.registry);
304
+ if (classified.problem) {
305
+ site.legacy = true;
306
+ addFlag(site.flags, classified.problem.code, classified.problem.detail);
307
+ }
308
+ if (classified.warning) {
309
+ addFlag(site.warnings, classified.warning.code, classified.warning.detail);
310
+ }
311
+ if (classified.inventory) {
312
+ addFlag(site.inventory, classified.inventory.code, classified.inventory.detail);
313
+ }
314
+ if (classified.text !== null) site.legacy = true;
315
+ const allowed = classified.text === null || assessProgram(site, prop, []);
316
+ site.members.push({
317
+ type: "authored",
318
+ index,
319
+ prop,
320
+ text,
321
+ payload: allowed ? classified.payload : null,
322
+ dynamic: classified.dynamic,
323
+ blocked: classified.blocked,
324
+ token: allowed && classified.text !== null,
325
+ activated: false
326
+ });
327
+ }
328
+ const sentinelMark = "";
329
+ function evaluateLegacyObject(object, rootPath) {
330
+ const leaves = [];
331
+ const visit = (current, currentPath) => {
332
+ const value = {};
333
+ for (const property of current.getProperties()) {
334
+ if (Node.isSpreadAssignment(property)) {
335
+ return {
336
+ value: null,
337
+ fatal: `spread "${compact(property.getText())}" hides legacy condition entries`
338
+ };
339
+ }
340
+ if (!Node.isPropertyAssignment(property)) {
341
+ return {
342
+ value: null,
343
+ fatal: `property "${compact(property.getText())}" is not a static assignment`
344
+ };
345
+ }
346
+ const nameNode = property.getNameNode();
347
+ if (Node.isComputedPropertyName(nameNode)) {
348
+ return {
349
+ value: null,
350
+ fatal: `computed property "${compact(nameNode.getText())}" hides the affected style property`
351
+ };
352
+ }
353
+ const name = propertyName(nameNode);
354
+ if (name === null) {
355
+ return {
356
+ value: null,
357
+ fatal: `property name "${compact(nameNode.getText())}" is not statically known`
358
+ };
359
+ }
360
+ const path = `${currentPath}.${name}`;
361
+ const initializer = unwrapExpression(property.getInitializerOrThrow());
362
+ if (Node.isObjectLiteralExpression(initializer)) {
363
+ const nested = visit(initializer, path);
364
+ if (nested.fatal) return nested;
365
+ value[name] = nested.value;
366
+ continue;
367
+ }
368
+ const leaf = staticLeafValue(initializer);
369
+ if (leaf) {
370
+ value[name] = leaf.value;
371
+ continue;
372
+ }
373
+ value[name] = `${sentinelMark}${leaves.length}${sentinelMark}`;
374
+ leaves.push({
375
+ path,
376
+ prop: name,
377
+ expression: initializer
378
+ });
379
+ }
380
+ return {
381
+ value,
382
+ fatal: null
383
+ };
384
+ };
385
+ const result = visit(object, rootPath);
386
+ return {
387
+ ...result,
388
+ leaves
389
+ };
390
+ }
391
+ function conditionProperties(value) {
392
+ const properties = /* @__PURE__ */ new Set();
393
+ const visit = (object) => {
394
+ for (const key in object) {
395
+ const child = object[key];
396
+ if (child !== null && typeof child === "object" && isLegacyConditionName(key)) {
397
+ visit(child);
398
+ continue;
399
+ }
400
+ if (!styleProps.has(key)) continue;
401
+ for (const property of expandToLonghands(key, shorthands)) properties.add(property);
402
+ }
403
+ };
404
+ visit(value);
405
+ return properties;
406
+ }
407
+ function pushLegacy(site, name, text, initializer, node) {
408
+ const index = site.index++;
409
+ site.legacy = true;
410
+ const keep = (properties2) => {
411
+ site.members.push({
412
+ type: "legacy",
413
+ index,
414
+ name,
415
+ text,
416
+ contributions: [],
417
+ properties: properties2,
418
+ failed: true
419
+ });
420
+ };
421
+ if (initializer === null || !Node.isObjectLiteralExpression(initializer)) {
422
+ addFlag(site.flags, "dynamic-legacy-condition", `"${name}" is not an inline object literal, so its entries are not statically known`);
423
+ keep(null);
424
+ return;
425
+ }
426
+ const evaluated = evaluateLegacyObject(initializer, name);
427
+ if (evaluated.fatal || evaluated.value === null) {
428
+ addFlag(site.flags, "dynamic-legacy-condition", evaluated.fatal ?? "unresolved");
429
+ keep(null);
430
+ return;
431
+ }
432
+ const properties = conditionProperties(evaluated.value);
433
+ const eligibilityStack = [{
434
+ object: evaluated.value,
435
+ path: name
436
+ }];
437
+ let hasRejectedProperty = false;
438
+ while (eligibilityStack.length > 0) {
439
+ const current = eligibilityStack.pop();
440
+ for (const prop in current.object) {
441
+ const value = current.object[prop];
442
+ const targetProp = resolveProp(prop);
443
+ if (styleProps.has(targetProp) && !isLegacyConditionName(prop)) {
444
+ const assessment = assessFlatConversion({
445
+ property: targetProp,
446
+ targets: site.targets,
447
+ host: site.host
448
+ }, site.registry);
449
+ if (assessment.verdict === "ineligible") {
450
+ addAssessment(site, targetProp, assessment);
451
+ hasRejectedProperty = true;
452
+ }
453
+ continue;
454
+ }
455
+ if (value !== null && typeof value === "object" && !Array.isArray(value) && isLegacyConditionName(prop)) {
456
+ eligibilityStack.push({
457
+ object: value,
458
+ path: `${current.path}.${prop}`
459
+ });
460
+ }
461
+ }
462
+ }
463
+ if (hasRejectedProperty) {
464
+ keep(properties);
465
+ return;
466
+ }
467
+ const unresolved = site.containers.unresolved.get(node);
468
+ if (unresolved !== void 0) {
469
+ addFlag(site.flags, unresolved.code, unresolved.detail);
470
+ keep(properties);
471
+ return;
472
+ }
473
+ const resolution = resolveLegacyName(name, site.registry);
474
+ if (!resolution.ok) {
475
+ addFlag(site.flags, resolution.code, resolution.message);
476
+ keep(properties);
477
+ return;
478
+ }
479
+ const payloads = /* @__PURE__ */ new Map();
480
+ let failed = false;
481
+ for (let index2 = 0; index2 < evaluated.leaves.length; index2++) {
482
+ const leaf = evaluated.leaves[index2];
483
+ const classified = classifyDynamic(leaf.prop, leaf.expression, site.registry);
484
+ if (classified.warning) {
485
+ addFlag(site.warnings, classified.warning.code, `${leaf.path}: ${classified.warning.detail}`);
486
+ }
487
+ if (classified.payload === null) {
488
+ const flag = classified.problem ?? classified.blocked;
489
+ addFlag(site.flags, flag?.code ?? "dynamic-condition-value", `${leaf.path}: ${flag?.detail ?? "the value is not statically known"}`);
490
+ failed = true;
491
+ continue;
492
+ }
493
+ payloads.set(`${sentinelMark}${index2}${sentinelMark}`, classified.payload);
494
+ }
495
+ if (failed) {
496
+ keep(properties);
497
+ return;
498
+ }
499
+ const { canonical, replaceRoot } = resolution.resolved;
500
+ const converted = convertLegacyConditionProp(canonical, evaluated.value, { registry: site.registry });
501
+ if (converted === null) {
502
+ addFlag(site.flags, "unknown-legacy-condition", `"${name}" is not a registered legacy condition spelling`);
503
+ keep(properties);
504
+ return;
505
+ }
506
+ for (const error of converted.errors) {
507
+ const path = error.path.startsWith(canonical) ? `${name}${error.path.slice(canonical.length)}` : error.path;
508
+ addFlag(site.flags, error.code, `${path}: ${error.message}`);
509
+ failed = true;
510
+ }
511
+ const contributions = [];
512
+ for (const contribution of converted.contributions) {
513
+ if (!styleProps.has(contribution.prop)) {
514
+ addFlag(site.flags, "non-style-condition-entry", `${name}.${contribution.prop} is not a style property, so a flat value cannot carry it`);
515
+ failed = true;
516
+ continue;
517
+ }
518
+ const modifiers = replaceRoot ? [...replaceRoot, ...contribution.clause.modifiers.slice(1)] : contribution.clause.modifiers;
519
+ const dynamicPayload = payloads.get(contribution.clause.payload);
520
+ contributions.push({
521
+ prop: contribution.prop,
522
+ clause: {
523
+ modifiers,
524
+ payload: dynamicPayload ?? contribution.clause.payload
525
+ },
526
+ dynamic: dynamicPayload !== void 0
527
+ });
528
+ if (!assessProgram(site, contribution.prop, modifiers)) failed = true;
529
+ }
530
+ if (failed) {
531
+ keep(properties);
532
+ return;
533
+ }
534
+ site.members.push({
535
+ type: "legacy",
536
+ index,
537
+ name,
538
+ text,
539
+ contributions,
540
+ properties,
541
+ failed: false
542
+ });
543
+ }
544
+ function activationName(prop) {
545
+ return resolveProp(prop);
546
+ }
547
+ const noProperties = /* @__PURE__ */ new Set();
548
+ const legacyStatePriorities = Object.freeze({
549
+ hover: 2,
550
+ press: 3,
551
+ active: 3,
552
+ focus: 4,
553
+ "focus-visible": 4,
554
+ "focus-within": 4,
555
+ enter: 4,
556
+ disabled: 5,
557
+ exit: 5
558
+ });
559
+ function legacyStatePriority(modifiers) {
560
+ let priority = null;
561
+ for (const modifier of modifiers) {
562
+ const candidate = legacyStatePriorities[modifier];
563
+ if (candidate !== void 0 && (priority === null || candidate > priority)) {
564
+ priority = candidate;
565
+ }
566
+ }
567
+ return priority;
568
+ }
569
+ function orderedEntries(site) {
570
+ const ordered = [];
571
+ for (const member of site.members) {
572
+ if (member.type === "authored") {
573
+ if (!member.activated || member.payload === null) continue;
574
+ ordered.push({
575
+ prop: member.prop,
576
+ value: {
577
+ base: member.payload,
578
+ clauses: []
579
+ },
580
+ dynamic: member.dynamic,
581
+ index: member.index,
582
+ base: true,
583
+ from: null,
584
+ legacyStatePriority: null
585
+ });
586
+ continue;
587
+ }
588
+ if (member.type !== "legacy" || member.failed) continue;
589
+ for (const contribution of member.contributions) {
590
+ ordered.push({
591
+ prop: contribution.prop,
592
+ value: {
593
+ base: null,
594
+ clauses: [contribution.clause]
595
+ },
596
+ dynamic: contribution.dynamic,
597
+ index: member.index,
598
+ base: false,
599
+ from: member,
600
+ legacyStatePriority: legacyStatePriority(contribution.clause.modifiers)
601
+ });
602
+ }
603
+ }
604
+ const ranked = ordered.filter((entry) => entry.legacyStatePriority !== null).sort((left, right) => left.legacyStatePriority - right.legacyStatePriority || left.index - right.index);
605
+ if (ranked.length < 2) return ordered;
606
+ let rankedIndex = 0;
607
+ return ordered.map((entry) => entry.legacyStatePriority === null ? entry : ranked[rankedIndex++]);
608
+ }
609
+ function buildSlots(ordered) {
610
+ const slots = /* @__PURE__ */ new Map();
611
+ for (const entry of ordered) {
612
+ for (const property of expandToLonghands(entry.prop, shorthands)) {
613
+ const previous = slots.get(property);
614
+ const value = previous ? mergeProgramValues(previous.value, entry.value) : entry.value;
615
+ slots.delete(property);
616
+ slots.set(property, {
617
+ property,
618
+ sourceProp: entry.prop,
619
+ value,
620
+ anchor: previous ? Math.min(previous.anchor, entry.index) : entry.index,
621
+ last: previous ? Math.max(previous.last, entry.index) : entry.index,
622
+ dynamic: (previous?.dynamic ?? false) || entry.dynamic
623
+ });
624
+ }
625
+ }
626
+ return slots;
627
+ }
628
+ function barriers(site) {
629
+ const list = [];
630
+ for (const member of site.members) {
631
+ if (member.type === "spread") {
632
+ list.push({
633
+ index: member.index,
634
+ source: member.text,
635
+ bases: null,
636
+ clauses: null
637
+ });
638
+ continue;
639
+ }
640
+ if (member.type === "authored" && !member.activated) {
641
+ list.push({
642
+ index: member.index,
643
+ source: member.text,
644
+ bases: new Set(expandToLonghands(member.prop, shorthands)),
645
+ clauses: noProperties
646
+ });
647
+ continue;
648
+ }
649
+ if (member.type === "legacy" && member.failed) {
650
+ list.push({
651
+ index: member.index,
652
+ source: member.name,
653
+ bases: noProperties,
654
+ clauses: member.properties
655
+ });
656
+ }
657
+ }
658
+ return list;
659
+ }
660
+ function resolveBarriers(site, ordered, slots) {
661
+ let changed = false;
662
+ for (const slot of slots.values()) {
663
+ const contributions = ordered.filter((entry) => expandToLonghands(entry.prop, shorthands).includes(slot.property));
664
+ for (const barrier of barriers(site)) {
665
+ if (barrier.index <= slot.anchor || barrier.index >= slot.last) continue;
666
+ if (barrier.clauses === null || barrier.clauses.has(slot.property)) {
667
+ for (const entry of contributions) {
668
+ if (entry.base || entry.index < barrier.index || !entry.from) continue;
669
+ addFlag(site.flags, "condition-order-not-preservable", `"${compact(barrier.source)}" can set "${slot.property}" between the values contributing to it, so "${entry.from.name}" stays authored instead of merging`);
670
+ entry.from.failed = true;
671
+ changed = true;
672
+ }
673
+ }
674
+ if (barrier.bases === null || barrier.bases.has(slot.property)) {
675
+ for (const entry of contributions) {
676
+ if (!entry.base || entry.index < barrier.index) continue;
677
+ const authored = site.members.find((member) => member.type === "authored" && member.index === entry.index && member.activated);
678
+ if (authored && authored.type === "authored") {
679
+ authored.payload = null;
680
+ authored.blocked = {
681
+ code: "base-order-not-preservable",
682
+ detail: `"${compact(barrier.source)}" can set "${slot.property}" between the values contributing to it, so this base cannot move`
683
+ };
684
+ changed = true;
685
+ continue;
686
+ }
687
+ addFlag(site.flags, "base-order-not-preservable", `"${compact(barrier.source)}" can set "${slot.property}" between the values contributing to it, so the merged base may win where it did not before`);
688
+ }
689
+ }
690
+ }
691
+ }
692
+ return changed;
693
+ }
694
+ function assemble(site) {
695
+ let slots = /* @__PURE__ */ new Map();
696
+ for (;;) {
697
+ let changed = false;
698
+ const contributed = /* @__PURE__ */ new Set();
699
+ for (const member of site.members) {
700
+ if (member.type !== "legacy" || member.failed) continue;
701
+ for (const contribution of member.contributions) {
702
+ contributed.add(activationName(contribution.prop));
703
+ }
704
+ }
705
+ for (const member of site.members) {
706
+ if (member.type !== "authored") continue;
707
+ const name = activationName(member.prop);
708
+ member.activated = member.token && member.payload !== null || contributed.has(name);
709
+ if (!member.activated || member.payload !== null) continue;
710
+ const blocked = member.blocked;
711
+ addFlag(site.flags, blocked?.code ?? "unprovable-dynamic-value", `a legacy condition targets "${member.prop}": ${blocked?.detail ?? `its base value "${compact(member.text)}" cannot join a program`}`);
712
+ member.activated = false;
713
+ for (const other of site.members) {
714
+ if (other.type !== "legacy" || other.failed) continue;
715
+ if (other.contributions.some((one) => activationName(one.prop) === name)) {
716
+ other.failed = true;
717
+ changed = true;
718
+ }
719
+ }
720
+ }
721
+ if (changed) continue;
722
+ const ordered = orderedEntries(site);
723
+ slots = buildSlots(ordered);
724
+ if (!resolveBarriers(site, ordered, slots)) break;
725
+ }
726
+ const entries = [];
727
+ for (const member of site.members) {
728
+ if (member.type === "authored" && member.activated) continue;
729
+ if (member.type === "legacy" && !member.failed) continue;
730
+ entries.push({
731
+ index: member.index,
732
+ text: member.text
733
+ });
734
+ }
735
+ const printed = printSlots(site, slots);
736
+ entries.push(...printed.output);
737
+ entries.push(...site.extras);
738
+ entries.sort((left, right) => left.index - right.index);
739
+ return {
740
+ entries,
741
+ programs: printed.programs
742
+ };
743
+ }
744
+ function printSlots(site, slots) {
745
+ const printed = /* @__PURE__ */ new Set();
746
+ const output = [];
747
+ const programs = [];
748
+ const outputCommentRanges = [];
749
+ for (const [property, slot] of slots) {
750
+ if (printed.has(property)) continue;
751
+ const serialized = printProgram(slot.value);
752
+ const expansion = expandToLonghands(slot.sourceProp, shorthands);
753
+ const collapses = expansion.length > 0 && expansion.every((expanded) => {
754
+ const candidate = slots.get(expanded);
755
+ return candidate !== void 0 && candidate.sourceProp === slot.sourceProp && candidate.anchor === slot.anchor && candidate.dynamic === slot.dynamic && printProgram(candidate.value) === serialized;
756
+ });
757
+ const name = collapses ? slot.sourceProp : property;
758
+ if (collapses) for (const expanded of expansion) printed.add(expanded);
759
+ else printed.add(property);
760
+ const value = slot.dynamic ? `\`${serialized}\`` : JSON.stringify(serialized);
761
+ programs.push({
762
+ name,
763
+ value: serialized,
764
+ dynamic: slot.dynamic
765
+ });
766
+ const propertyText = site.kind === "styled" ? `${name}: ${value}` : `${name}=${slot.dynamic ? `{${value}}` : value}`;
767
+ output.push({
768
+ index: slot.anchor,
769
+ text: propertyText
770
+ });
771
+ outputCommentRanges.push({
772
+ outputIndex: output.length - 1,
773
+ first: slot.anchor,
774
+ last: slot.last
775
+ });
776
+ }
777
+ verify(site, slots, [...output].sort((left, right) => left.index - right.index));
778
+ if (site.kind === "styled") {
779
+ const commentedIndexes = /* @__PURE__ */ new Set();
780
+ for (const range of outputCommentRanges) {
781
+ const comments = [];
782
+ for (const [index, texts] of site.comments) {
783
+ if (index < range.first || index > range.last || commentedIndexes.has(index)) {
784
+ continue;
785
+ }
786
+ comments.push(...texts);
787
+ commentedIndexes.add(index);
788
+ }
789
+ if (comments.length) {
790
+ output[range.outputIndex].text = `${comments.join("\n")}
791
+ ${output[range.outputIndex].text}`;
792
+ }
793
+ }
794
+ }
795
+ return {
796
+ output,
797
+ programs
798
+ };
799
+ }
800
+ function sanitize(text) {
801
+ let result = "";
802
+ for (let index = 0; index < text.length; index++) {
803
+ if (text[index] !== "$" || text[index + 1] !== "{") {
804
+ result += text[index];
805
+ continue;
806
+ }
807
+ let depth = 0;
808
+ let end = index + 1;
809
+ for (; end < text.length; end++) {
810
+ if (text[end] === "{") depth++;
811
+ else if (text[end] === "}" && --depth === 0) break;
812
+ }
813
+ result += "zz";
814
+ index = end;
815
+ }
816
+ return result;
817
+ }
818
+ function verify(site, slots, output) {
819
+ const separator = site.kind === "styled" ? ": " : "=";
820
+ const reparsed = /* @__PURE__ */ new Map();
821
+ for (const entry of output) {
822
+ const split = entry.text.indexOf(separator);
823
+ const prop = entry.text.slice(0, split);
824
+ let raw = entry.text.slice(split + separator.length);
825
+ if (raw.startsWith("{")) raw = raw.slice(1, -1);
826
+ const text = sanitize(raw.slice(1, -1));
827
+ const parsed = parseValue(text, site.registry);
828
+ if (!parsed.ok) {
829
+ addFlag(site.flags, "emitted-value-invalid", `"${prop}=${text}" does not parse: ${parsed.errors.map((error) => error.message).join("; ")}`);
830
+ return;
831
+ }
832
+ for (const property of expandToLonghands(prop, shorthands)) {
833
+ const previous = reparsed.get(property);
834
+ reparsed.set(property, previous ? mergeProgramValues(previous, parsed.value) : parsed.value);
835
+ }
836
+ }
837
+ for (const [property, slot] of slots) {
838
+ const actual = reparsed.get(property);
839
+ const expected = sanitize(printProgram(slot.value));
840
+ if (actual === void 0 || sanitize(printProgram(actual)) !== expected) {
841
+ addFlag(site.flags, "emitted-program-mismatch", `"${property}" reads back as "${actual ? sanitize(printProgram(actual)) : "(missing)"}" instead of "${expected}"`);
842
+ }
843
+ }
844
+ }
845
+ function propertyName(node) {
846
+ if (Node.isIdentifier(node) || Node.isStringLiteral(node) || Node.isNumericLiteral(node)) {
847
+ return node.getText().replace(/^['"]|['"]$/g, "");
848
+ }
849
+ return null;
850
+ }
851
+ function jsxAttributeName(attribute) {
852
+ const name = attribute.getNameNode();
853
+ return Node.isIdentifier(name) ? name.getText() : null;
854
+ }
855
+ function jsxLiteralString(attribute) {
856
+ const initializer = attribute.getInitializer();
857
+ if (Node.isStringLiteral(initializer)) return initializer.getLiteralValue();
858
+ const expression = jsxExpression(attribute);
859
+ if (expression && (Node.isStringLiteral(expression) || Node.isNoSubstitutionTemplateLiteral(expression))) {
860
+ return expression.getLiteralValue();
861
+ }
862
+ return null;
863
+ }
864
+ function jsxExpression(attribute) {
865
+ const initializer = attribute.getInitializer();
866
+ if (!Node.isJsxExpression(initializer)) return null;
867
+ const expression = initializer.getExpression();
868
+ return expression ? unwrapExpression(expression) : null;
869
+ }
870
+ function isConvertedJsxAttribute(attribute) {
871
+ if (Node.isJsxSpreadAttribute(attribute)) return true;
872
+ if (!Node.isJsxAttribute(attribute)) return false;
873
+ const name = jsxAttributeName(attribute);
874
+ return !!name && (name === "group" || styleProps.has(name) || isLegacyConditionName(name));
875
+ }
876
+ function rewriteJsxSite(opening, entries) {
877
+ const attributes = opening.getAttributes();
878
+ const rendered = [];
879
+ let inserted = false;
880
+ for (const attribute of attributes) {
881
+ if (isConvertedJsxAttribute(attribute)) {
882
+ if (!inserted) {
883
+ rendered.push(...entries.map((entry) => entry.text));
884
+ inserted = true;
885
+ }
886
+ } else {
887
+ rendered.push(attribute.getText());
888
+ }
889
+ }
890
+ const source = opening.getText();
891
+ const start = opening.getStart();
892
+ const first = attributes[0];
893
+ const last = attributes[attributes.length - 1];
894
+ const prefix = source.slice(0, first.getStart() - start);
895
+ const suffix = source.slice(last.getEnd() - start);
896
+ opening.replaceWithText(`${prefix}${rendered.join(" ")}${suffix}`);
897
+ }
898
+ function containerExtras(site, declaration, index) {
899
+ const target = site.containers.targets.get(declaration);
900
+ if (target === void 0) return;
901
+ const name = target.named && target.group !== "" ? target.group : null;
902
+ const text = site.kind === "styled" ? name === null ? "container: true" : `container: true, containerName: ${JSON.stringify(name)}` : name === null ? "container" : `container containerName=${JSON.stringify(name)}`;
903
+ site.legacy = true;
904
+ site.extras.push({
905
+ index,
906
+ text
907
+ });
908
+ if (target.flag !== null) addFlag(site.flags, target.flag.code, target.flag.detail);
909
+ addNote(site, `a descendant uses a legacy container-size condition on this group, so it declares a query container`);
910
+ }
911
+ function convertJsxSite(opening, registry, containers, targets, host, write = false) {
912
+ const site = createSite("jsx", registry, containers, targets, host);
913
+ const before = [];
914
+ for (const attribute of opening.getAttributes()) {
915
+ if (Node.isJsxSpreadAttribute(attribute)) {
916
+ const expression = unwrapExpression(attribute.getExpression());
917
+ if (Node.isObjectLiteralExpression(expression)) {
918
+ before.push(compact(attribute.getText()));
919
+ for (const property of expression.getProperties()) {
920
+ if (Node.isPropertyAssignment(property)) {
921
+ const name2 = propertyName(property.getNameNode());
922
+ if (name2 !== null) {
923
+ if (name2 === "group" || styleProps.has(name2) || isLegacyConditionName(name2)) {
924
+ pushStyledProperty(site, name2, property, `${name2}={${property.getInitializerOrThrow().getText()}}`);
925
+ } else {
926
+ site.members.push({
927
+ type: "passthrough",
928
+ index: site.index++,
929
+ text: `${name2}={${property.getInitializerOrThrow().getText()}}`
930
+ });
931
+ }
932
+ continue;
933
+ }
934
+ }
935
+ site.members.push({
936
+ type: "spread",
937
+ index: site.index++,
938
+ text: Node.isSpreadAssignment(property) ? `{${property.getText()}}` : `{...{ ${property.getText()} }}`
939
+ });
940
+ }
941
+ continue;
942
+ }
943
+ before.push(compact(attribute.getText()));
944
+ site.members.push({
945
+ type: "spread",
946
+ index: site.index++,
947
+ text: attribute.getText()
948
+ });
949
+ continue;
950
+ }
951
+ const name = jsxAttributeName(attribute);
952
+ if (!name) continue;
953
+ const text = compact(attribute.getText());
954
+ if (name === "group") {
955
+ before.push(text);
956
+ containerExtras(site, attribute, site.index);
957
+ site.members.push({
958
+ type: "passthrough",
959
+ index: site.index++,
960
+ text
961
+ });
962
+ continue;
963
+ }
964
+ if (isLegacyConditionName(name)) {
965
+ before.push(text);
966
+ pushLegacy(site, name, text, jsxExpression(attribute), attribute);
967
+ continue;
968
+ }
969
+ if (!styleProps.has(name)) continue;
970
+ before.push(text);
971
+ const literal = jsxLiteralString(attribute);
972
+ pushBase(site, name, text, literal === null ? jsxExpression(attribute) : null, literal);
973
+ }
974
+ if (!site.legacy) return null;
975
+ const { entries, programs } = assemble(site);
976
+ const sourceFile = opening.getSourceFile();
977
+ const report = {
978
+ kind: "jsx",
979
+ label: `<${opening.getTagNameNode().getText()}>`,
980
+ line: sourceFile.getLineAndColumnAtPos(opening.getStart()).line,
981
+ before: before.join(" "),
982
+ after: entries.map((entry) => entry.text).join(" ") || "(no style props left)",
983
+ programs,
984
+ assessments: site.assessments,
985
+ assessmentVerdict: assessmentVerdict(site.assessments),
986
+ warnings: site.warnings,
987
+ flags: site.flags,
988
+ inventory: site.inventory,
989
+ pending: site.pending,
990
+ notes: site.notes,
991
+ legacyLeft: site.members.filter((member) => member.type === "legacy" && member.failed).length
992
+ };
993
+ if (write && !site.flags.some((flag) => flag.code === "emitted-program-mismatch" || flag.code === "emitted-value-invalid")) {
994
+ rewriteJsxSite(opening, entries);
995
+ }
996
+ return report;
997
+ }
998
+ function pushStyledProperty(site, name, property, authoredText) {
999
+ const comments = allCommentTexts(property);
1000
+ if (comments.length) site.comments.set(site.index, comments);
1001
+ const text = authoredText ?? textWithOuterComments(property);
1002
+ const initializer = unwrapExpression(property.getInitializerOrThrow());
1003
+ if (name === "group") {
1004
+ containerExtras(site, property, site.index);
1005
+ site.members.push({
1006
+ type: "passthrough",
1007
+ index: site.index++,
1008
+ text
1009
+ });
1010
+ return;
1011
+ }
1012
+ if (isLegacyConditionName(name)) {
1013
+ pushLegacy(site, name, text, initializer, property);
1014
+ return;
1015
+ }
1016
+ if (!styleProps.has(name)) return;
1017
+ const literal = Node.isStringLiteral(initializer) || Node.isNoSubstitutionTemplateLiteral(initializer) ? initializer.getLiteralValue() : null;
1018
+ pushBase(site, name, text, literal === null ? initializer : null, literal);
1019
+ }
1020
+ function convertStyleObject(object, kind, label, registry, containers, targets, host, write = false) {
1021
+ const site = createSite(kind, registry, containers, targets, host);
1022
+ const before = [];
1023
+ for (const property of object.getProperties()) {
1024
+ if (Node.isSpreadAssignment(property)) {
1025
+ const expression = unwrapExpression(property.getExpression());
1026
+ before.push(compact(property.getText()));
1027
+ if (Node.isObjectLiteralExpression(expression)) {
1028
+ for (const nested of expression.getProperties()) {
1029
+ if (Node.isPropertyAssignment(nested)) {
1030
+ const name2 = propertyName(nested.getNameNode());
1031
+ if (name2 !== null) {
1032
+ if (name2 === "group" || styleProps.has(name2) || isLegacyConditionName(name2)) {
1033
+ pushStyledProperty(site, name2, nested);
1034
+ } else {
1035
+ site.members.push({
1036
+ type: "passthrough",
1037
+ index: site.index++,
1038
+ text: compact(nested.getText())
1039
+ });
1040
+ }
1041
+ continue;
1042
+ }
1043
+ }
1044
+ site.members.push({
1045
+ type: "spread",
1046
+ index: site.index++,
1047
+ text: compact(nested.getText())
1048
+ });
1049
+ }
1050
+ continue;
1051
+ }
1052
+ site.members.push({
1053
+ type: "spread",
1054
+ index: site.index++,
1055
+ text: compact(property.getText())
1056
+ });
1057
+ continue;
1058
+ }
1059
+ if (!Node.isPropertyAssignment(property)) continue;
1060
+ const nameNode = property.getNameNode();
1061
+ if (Node.isComputedPropertyName(nameNode)) {
1062
+ addFlag(site.flags, "computed-property", `"${compact(nameNode.getText())}" hides the affected style property`);
1063
+ continue;
1064
+ }
1065
+ const name = propertyName(nameNode);
1066
+ if (name === null) continue;
1067
+ if (!styleProps.has(name) && !isLegacyConditionName(name) && name !== "group") continue;
1068
+ before.push(compact(property.getText()));
1069
+ pushStyledProperty(site, name, property);
1070
+ }
1071
+ if (!site.legacy) return null;
1072
+ const { entries, programs } = assemble(site);
1073
+ const sourceFile = object.getSourceFile();
1074
+ const report = {
1075
+ kind,
1076
+ label,
1077
+ line: sourceFile.getLineAndColumnAtPos(object.getStart()).line,
1078
+ before: before.join(", "),
1079
+ after: entries.map((entry) => entry.text).join(", ") || "(no style props left)",
1080
+ programs,
1081
+ assessments: site.assessments,
1082
+ assessmentVerdict: assessmentVerdict(site.assessments),
1083
+ warnings: site.warnings,
1084
+ flags: site.flags,
1085
+ inventory: site.inventory,
1086
+ pending: site.pending,
1087
+ notes: site.notes,
1088
+ legacyLeft: site.members.filter((member) => member.type === "legacy" && member.failed).length
1089
+ };
1090
+ if (write && !site.flags.some((flag) => flag.code === "emitted-program-mismatch" || flag.code === "emitted-value-invalid")) {
1091
+ rewriteStyleObject(object, entries);
1092
+ }
1093
+ return report;
1094
+ }
1095
+ function isConvertedStyledProperty(property) {
1096
+ if (Node.isSpreadAssignment(property)) return true;
1097
+ if (!Node.isPropertyAssignment(property)) return false;
1098
+ const nameNode = property.getNameNode();
1099
+ if (Node.isComputedPropertyName(nameNode)) return false;
1100
+ const name = propertyName(nameNode);
1101
+ return !!name && (name === "group" || styleProps.has(name) || isLegacyConditionName(name));
1102
+ }
1103
+ function allCommentTexts(node) {
1104
+ const comments = /* @__PURE__ */ new Map();
1105
+ for (const current of [node, ...node.getDescendants()]) {
1106
+ for (const range of [...current.getLeadingCommentRanges(), ...current.getTrailingCommentRanges()]) {
1107
+ comments.set(range.getPos(), range.getText());
1108
+ }
1109
+ }
1110
+ return [...comments.entries()].sort((left, right) => left[0] - right[0]).map((entry) => entry[1]);
1111
+ }
1112
+ function textWithOuterComments(node) {
1113
+ const comments = /* @__PURE__ */ new Map();
1114
+ for (const range of [...node.getLeadingCommentRanges(), ...node.getTrailingCommentRanges()]) {
1115
+ comments.set(range.getPos(), range.getText());
1116
+ }
1117
+ const prefix = [...comments.entries()].sort((left, right) => left[0] - right[0]).map((entry) => entry[1]);
1118
+ return [...prefix, node.getText()].join("\n");
1119
+ }
1120
+ function rewriteStyleObject(object, entries) {
1121
+ const rendered = [];
1122
+ let inserted = false;
1123
+ for (const property of object.getProperties()) {
1124
+ if (isConvertedStyledProperty(property)) {
1125
+ if (!inserted) {
1126
+ rendered.push(...entries.map((entry) => entry.text));
1127
+ inserted = true;
1128
+ }
1129
+ } else {
1130
+ rendered.push(textWithOuterComments(property));
1131
+ }
1132
+ }
1133
+ object.replaceWithText(rendered.length ? `{
1134
+ ${rendered.join(",\n")}
1135
+ }` : "{}");
1136
+ }
1137
+
1138
+ export { convertJsxSite, convertStyleObject, sanitize };
1139
+ //# sourceMappingURL=convert.mjs.map