@typestyles/migrate 0.2.0 → 0.4.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,868 @@
1
+ #!/usr/bin/env node
2
+ import { parse } from '@babel/parser';
3
+ import generate from '@babel/generator';
4
+ import traverse from '@babel/traverse';
5
+ import * as t4 from '@babel/types';
6
+ import postcss from 'postcss';
7
+ import { readFile, writeFile, mkdir, stat } from 'fs/promises';
8
+ import { relative, dirname, resolve, extname } from 'path';
9
+ import { createPatch } from 'diff';
10
+ import fg from 'fast-glob';
11
+ import picomatch from 'picomatch';
12
+
13
+ function camelCaseProperty(property) {
14
+ return property.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
15
+ }
16
+ function toValueNode(value, varReplacements) {
17
+ const trimmed = value.trim();
18
+ if (varReplacements?.has(trimmed)) {
19
+ return varReplacements.get(trimmed);
20
+ }
21
+ if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
22
+ return t4.numericLiteral(Number(trimmed));
23
+ }
24
+ return t4.stringLiteral(trimmed);
25
+ }
26
+ function toKeyNode(key) {
27
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)) {
28
+ return t4.identifier(key);
29
+ }
30
+ return t4.stringLiteral(key);
31
+ }
32
+ function nodesToObject(nodes, warnings, varReplacements) {
33
+ const properties = [];
34
+ for (const node of nodes ?? []) {
35
+ if (node.type === "decl") {
36
+ const normalized = node.prop.startsWith("--") ? node.prop : camelCaseProperty(node.prop);
37
+ properties.push(
38
+ t4.objectProperty(toKeyNode(normalized), toValueNode(node.value, varReplacements))
39
+ );
40
+ continue;
41
+ }
42
+ if (node.type === "rule") {
43
+ const nested = nodesToObject(node.nodes, warnings, varReplacements);
44
+ properties.push(t4.objectProperty(t4.stringLiteral(node.selector.trim()), nested));
45
+ continue;
46
+ }
47
+ if (node.type === "atrule") {
48
+ const nested = nodesToObject(node.nodes, warnings, varReplacements);
49
+ const atRuleKey = `@${node.name}${node.params ? ` ${node.params}` : ""}`;
50
+ properties.push(t4.objectProperty(t4.stringLiteral(atRuleKey), nested));
51
+ continue;
52
+ }
53
+ warnings.push({
54
+ message: `Unsupported CSS node "${node.type}" skipped.`
55
+ });
56
+ }
57
+ return t4.objectExpression(properties);
58
+ }
59
+ function cssToObjectExpression(cssText, warnings, varReplacements) {
60
+ try {
61
+ const root = postcss.parse(cssText);
62
+ return nodesToObject(root.nodes, warnings, varReplacements);
63
+ } catch (error) {
64
+ warnings.push({
65
+ message: `Could not parse CSS template literal: ${error.message}`
66
+ });
67
+ return null;
68
+ }
69
+ }
70
+ var PLACEHOLDER_PREFIX = "__ts_migrate_var_";
71
+ function camelCaseProperty2(property) {
72
+ return property.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
73
+ }
74
+ function placeholderToken(index) {
75
+ return `${PLACEHOLDER_PREFIX}${index}__`;
76
+ }
77
+ function extractSuffixFromQuasi(quasiText) {
78
+ const match = quasiText.match(/^([^;\n]*)/);
79
+ return match?.[1] ?? "";
80
+ }
81
+ function literalToCssValue(node) {
82
+ if (t4.isStringLiteral(node)) return node.value;
83
+ if (t4.isNumericLiteral(node)) return String(node.value);
84
+ return null;
85
+ }
86
+ function unwrapExpression(expression) {
87
+ if (t4.isParenthesizedExpression(expression)) {
88
+ return unwrapExpression(expression.expression);
89
+ }
90
+ return expression;
91
+ }
92
+ function extractCssPropertyBeforeInterpolation(quasiText) {
93
+ const match = quasiText.match(/([a-zA-Z-]+)\s*:\s*$/);
94
+ return match?.[1] ?? null;
95
+ }
96
+ function stripTrailingPropertyDeclaration(quasiText) {
97
+ return quasiText.replace(/[a-zA-Z-]+\s*:\s*$/, "");
98
+ }
99
+ function stripLeadingDeclarationRemainder(quasiText) {
100
+ const semiIdx = quasiText.indexOf(";");
101
+ if (semiIdx === -1) return quasiText;
102
+ return quasiText.slice(semiIdx + 1).trimStart();
103
+ }
104
+ function parsePropInterpolation(expression) {
105
+ if (!t4.isArrowFunctionExpression(expression)) return null;
106
+ const param = expression.params[0];
107
+ if (!param) return null;
108
+ const body = unwrapExpression(expression.body);
109
+ if (!t4.isExpression(body)) return null;
110
+ if (t4.isIdentifier(param)) {
111
+ if (t4.isMemberExpression(body) && !body.computed && t4.isIdentifier(body.object, { name: param.name }) && t4.isIdentifier(body.property)) {
112
+ return { propName: body.property.name };
113
+ }
114
+ return null;
115
+ }
116
+ if (t4.isObjectPattern(param) && t4.isIdentifier(body)) {
117
+ const propName = body.name;
118
+ const hasProp = param.properties.some((property) => {
119
+ if (!t4.isObjectProperty(property)) return false;
120
+ const keyName = t4.isIdentifier(property.key) ? property.key.name : t4.isStringLiteral(property.key) ? property.key.value : null;
121
+ return keyName === propName;
122
+ });
123
+ if (!hasProp) return null;
124
+ return { propName };
125
+ }
126
+ return null;
127
+ }
128
+ function parseBooleanTernaryInterpolation(expression) {
129
+ if (!t4.isArrowFunctionExpression(expression)) return null;
130
+ const param = expression.params[0];
131
+ if (!t4.isIdentifier(param)) return null;
132
+ const body = unwrapExpression(expression.body);
133
+ if (!t4.isConditionalExpression(body)) return null;
134
+ if (!t4.isMemberExpression(body.test) || body.test.computed || !t4.isIdentifier(body.test.object, { name: param.name }) || !t4.isIdentifier(body.test.property)) {
135
+ return null;
136
+ }
137
+ const trueValue = literalToCssValue(body.consequent);
138
+ const falseValue = literalToCssValue(body.alternate);
139
+ if (trueValue === null || falseValue === null) return null;
140
+ return {
141
+ propName: body.test.property.name,
142
+ trueValue,
143
+ falseValue
144
+ };
145
+ }
146
+ function parseTemplateInterpolations(template) {
147
+ const interpolations = [];
148
+ for (let i = 0; i < template.expressions.length; i++) {
149
+ const expression = template.expressions[i];
150
+ if (!t4.isExpression(expression)) return null;
151
+ const parsed = parsePropInterpolation(expression);
152
+ if (!parsed) return null;
153
+ const followingQuasi = template.quasis[i + 1]?.value.cooked ?? "";
154
+ interpolations.push({
155
+ index: i,
156
+ propName: parsed.propName,
157
+ suffix: extractSuffixFromQuasi(followingQuasi)
158
+ });
159
+ }
160
+ return interpolations;
161
+ }
162
+ function parseBooleanTemplateInterpolations(template) {
163
+ const interpolations = [];
164
+ for (let i = 0; i < template.expressions.length; i++) {
165
+ const expression = template.expressions[i];
166
+ if (!t4.isExpression(expression)) return null;
167
+ const parsed = parseBooleanTernaryInterpolation(expression);
168
+ if (!parsed) return null;
169
+ const quasiBefore = template.quasis[i]?.value.cooked ?? "";
170
+ const cssProperty = extractCssPropertyBeforeInterpolation(quasiBefore);
171
+ if (!cssProperty) return null;
172
+ interpolations.push({
173
+ index: i,
174
+ propName: parsed.propName,
175
+ trueValue: parsed.trueValue,
176
+ falseValue: parsed.falseValue,
177
+ cssProperty: camelCaseProperty2(cssProperty)
178
+ });
179
+ }
180
+ return interpolations;
181
+ }
182
+ function reconstructInterpolatedCss(template, interpolations) {
183
+ let result = "";
184
+ for (let i = 0; i < template.quasis.length; i++) {
185
+ let quasiText = template.quasis[i].value.cooked ?? "";
186
+ if (i > 0) {
187
+ const interpolation = interpolations[i - 1];
188
+ if (interpolation?.suffix && quasiText.startsWith(interpolation.suffix)) {
189
+ quasiText = quasiText.slice(interpolation.suffix.length);
190
+ }
191
+ }
192
+ result += quasiText;
193
+ if (i < interpolations.length) {
194
+ result += placeholderToken(interpolations[i].index);
195
+ }
196
+ }
197
+ return result;
198
+ }
199
+ function reconstructStaticCssWithoutVariants(template, booleanInterpolations) {
200
+ const skipIndices = new Set(booleanInterpolations.map((interpolation) => interpolation.index));
201
+ let result = "";
202
+ for (let i = 0; i < template.quasis.length; i++) {
203
+ let quasiText = template.quasis[i].value.cooked ?? "";
204
+ if (skipIndices.has(i)) {
205
+ quasiText = stripTrailingPropertyDeclaration(quasiText);
206
+ }
207
+ if (i > 0 && skipIndices.has(i - 1)) {
208
+ quasiText = stripLeadingDeclarationRemainder(quasiText);
209
+ }
210
+ result += quasiText;
211
+ }
212
+ return result.trim();
213
+ }
214
+ function toVarDebugName(componentName, propName) {
215
+ return `${componentName}${propName.charAt(0).toUpperCase()}${propName.slice(1)}`;
216
+ }
217
+ function toComponentConstName(componentName) {
218
+ if (!componentName) return componentName;
219
+ return componentName.charAt(0).toLowerCase() + componentName.slice(1);
220
+ }
221
+ function toCssValueNode(value) {
222
+ if (/^-?\d+(\.\d+)?$/.test(value.trim())) {
223
+ return t4.numericLiteral(Number(value));
224
+ }
225
+ return t4.stringLiteral(value);
226
+ }
227
+ function toKeyNode2(key) {
228
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)) {
229
+ return t4.identifier(key);
230
+ }
231
+ return t4.stringLiteral(key);
232
+ }
233
+ function buildVariantStyles(properties) {
234
+ return t4.objectExpression(
235
+ Object.entries(properties).map(
236
+ ([key, value]) => t4.objectProperty(toKeyNode2(key), toCssValueNode(value))
237
+ )
238
+ );
239
+ }
240
+ function buildVariantComponentConfig(baseObject, booleanInterpolations) {
241
+ const variantGroups = /* @__PURE__ */ new Map();
242
+ for (const interpolation of booleanInterpolations) {
243
+ const group = variantGroups.get(interpolation.propName) ?? { true: {}, false: {} };
244
+ group.true[interpolation.cssProperty] = interpolation.trueValue;
245
+ group.false[interpolation.cssProperty] = interpolation.falseValue;
246
+ variantGroups.set(interpolation.propName, group);
247
+ }
248
+ const variantsProperties = [...variantGroups.entries()].map(
249
+ ([propName, values]) => t4.objectProperty(
250
+ t4.identifier(propName),
251
+ t4.objectExpression([
252
+ t4.objectProperty(t4.identifier("true"), buildVariantStyles(values.true)),
253
+ t4.objectProperty(t4.identifier("false"), buildVariantStyles(values.false))
254
+ ])
255
+ )
256
+ );
257
+ const defaultVariantProperties = [...variantGroups.keys()].map(
258
+ (propName) => t4.objectProperty(t4.identifier(propName), t4.booleanLiteral(false))
259
+ );
260
+ return t4.objectExpression([
261
+ t4.objectProperty(t4.identifier("base"), baseObject),
262
+ t4.objectProperty(t4.identifier("variants"), t4.objectExpression(variantsProperties)),
263
+ t4.objectProperty(t4.identifier("defaultVariants"), t4.objectExpression(defaultVariantProperties))
264
+ ]);
265
+ }
266
+
267
+ // src/transform.ts
268
+ function toKebabCase(input) {
269
+ return input.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[_\s]+/g, "-").toLowerCase();
270
+ }
271
+ function memberExpressionToJsxName(expression) {
272
+ if (t4.isIdentifier(expression)) {
273
+ return t4.jsxIdentifier(expression.name);
274
+ }
275
+ if (t4.isMemberExpression(expression) && !expression.computed) {
276
+ const left = memberExpressionToJsxName(expression.object);
277
+ const right = t4.isIdentifier(expression.property) ? t4.jsxIdentifier(expression.property.name) : null;
278
+ if (!left || !right) return null;
279
+ return t4.jsxMemberExpression(left, right);
280
+ }
281
+ return null;
282
+ }
283
+ function parseStyledTarget(tag, styledNames) {
284
+ if (t4.isMemberExpression(tag) && t4.isIdentifier(tag.object) && styledNames.has(tag.object.name) && t4.isIdentifier(tag.property)) {
285
+ return { kind: "intrinsic", jsxName: t4.jsxIdentifier(tag.property.name) };
286
+ }
287
+ if (t4.isCallExpression(tag) && t4.isIdentifier(tag.callee) && styledNames.has(tag.callee.name)) {
288
+ const firstArg = tag.arguments[0];
289
+ if (!firstArg || !t4.isExpression(firstArg)) return null;
290
+ const jsxName = memberExpressionToJsxName(firstArg);
291
+ if (!jsxName) return null;
292
+ return { kind: "component", jsxName };
293
+ }
294
+ return null;
295
+ }
296
+ function addWarning(warnings, message, nodeName) {
297
+ warnings.push({ message, nodeName });
298
+ }
299
+ function createMergedClassExpression(existing, classNameExpression) {
300
+ return t4.callExpression(
301
+ t4.memberExpression(
302
+ t4.callExpression(
303
+ t4.memberExpression(
304
+ t4.arrayExpression([existing, classNameExpression]),
305
+ t4.identifier("filter")
306
+ ),
307
+ [t4.identifier("Boolean")]
308
+ ),
309
+ t4.identifier("join")
310
+ ),
311
+ [t4.stringLiteral(" ")]
312
+ );
313
+ }
314
+ function updateClassNameAttribute(openingElement, classNameExpression) {
315
+ const existingAttr = openingElement.attributes.find(
316
+ (attribute) => t4.isJSXAttribute(attribute) && t4.isJSXIdentifier(attribute.name, { name: "className" })
317
+ );
318
+ if (!existingAttr) {
319
+ openingElement.attributes.push(
320
+ t4.jsxAttribute(t4.jsxIdentifier("className"), t4.jsxExpressionContainer(classNameExpression))
321
+ );
322
+ return;
323
+ }
324
+ if (!existingAttr.value) {
325
+ existingAttr.value = t4.jsxExpressionContainer(classNameExpression);
326
+ return;
327
+ }
328
+ if (t4.isStringLiteral(existingAttr.value)) {
329
+ existingAttr.value = t4.jsxExpressionContainer(
330
+ createMergedClassExpression(t4.stringLiteral(existingAttr.value.value), classNameExpression)
331
+ );
332
+ return;
333
+ }
334
+ if (t4.isJSXExpressionContainer(existingAttr.value)) {
335
+ existingAttr.value = t4.jsxExpressionContainer(
336
+ createMergedClassExpression(
337
+ existingAttr.value.expression,
338
+ classNameExpression
339
+ )
340
+ );
341
+ }
342
+ }
343
+ function ensureTypestylesImport(ast, needsVars) {
344
+ const requiredSpecifiers = /* @__PURE__ */ new Set(["styles"]);
345
+ if (needsVars) {
346
+ requiredSpecifiers.add("createVar");
347
+ requiredSpecifiers.add("assignVars");
348
+ }
349
+ let typestylesImport = null;
350
+ for (const statement of ast.program.body) {
351
+ if (t4.isImportDeclaration(statement) && statement.source.value === "typestyles") {
352
+ typestylesImport = statement;
353
+ break;
354
+ }
355
+ }
356
+ const buildSpecifiers = (names) => [...names].map((name) => t4.importSpecifier(t4.identifier(name), t4.identifier(name)));
357
+ if (!typestylesImport) {
358
+ ast.program.body.unshift(
359
+ t4.importDeclaration(buildSpecifiers(requiredSpecifiers), t4.stringLiteral("typestyles"))
360
+ );
361
+ return;
362
+ }
363
+ for (const name of requiredSpecifiers) {
364
+ const hasSpecifier = typestylesImport.specifiers.some(
365
+ (specifier) => t4.isImportSpecifier(specifier) && t4.isIdentifier(specifier.imported, { name }) && t4.isIdentifier(specifier.local, { name })
366
+ );
367
+ if (!hasSpecifier) {
368
+ typestylesImport.specifiers.push(t4.importSpecifier(t4.identifier(name), t4.identifier(name)));
369
+ }
370
+ }
371
+ }
372
+ function cleanupUnusedImports(ast) {
373
+ traverse(ast, {
374
+ Program(path) {
375
+ path.scope.crawl();
376
+ },
377
+ ImportDeclaration(path) {
378
+ const unusedLocals = path.node.specifiers.filter((specifier) => {
379
+ if (path.node.source.value === "typestyles" && t4.isImportSpecifier(specifier) && (specifier.local.name === "styles" || specifier.local.name === "createVar" || specifier.local.name === "assignVars")) {
380
+ return false;
381
+ }
382
+ const local = specifier.local.name;
383
+ const binding = path.scope.getBinding(local);
384
+ return !binding || binding.referencePaths.length === 0;
385
+ });
386
+ if (unusedLocals.length === 0) return;
387
+ path.node.specifiers = path.node.specifiers.filter(
388
+ (specifier) => !unusedLocals.includes(specifier)
389
+ );
390
+ if (path.node.specifiers.length === 0) {
391
+ path.remove();
392
+ }
393
+ }
394
+ });
395
+ }
396
+ function createAssignVarValue(propExpression, suffix) {
397
+ if (!suffix) return propExpression;
398
+ if (t4.isStringLiteral(propExpression)) {
399
+ return t4.stringLiteral(`${propExpression.value}${suffix}`);
400
+ }
401
+ return t4.binaryExpression("+", propExpression, t4.stringLiteral(suffix));
402
+ }
403
+ function buildAssignVarsCall(propVars, propValues) {
404
+ const properties = propVars.filter((binding) => propValues.has(binding.propName)).map((binding) => {
405
+ const propExpression = propValues.get(binding.propName);
406
+ return t4.objectProperty(
407
+ t4.identifier(binding.varConstName),
408
+ createAssignVarValue(propExpression, binding.suffix),
409
+ true
410
+ );
411
+ });
412
+ return t4.callExpression(t4.identifier("assignVars"), [t4.objectExpression(properties)]);
413
+ }
414
+ function mergeStyleExpressions(existing, assignVarsCall) {
415
+ return t4.objectExpression([t4.spreadElement(existing), t4.spreadElement(assignVarsCall)]);
416
+ }
417
+ function updateStyleAttribute(openingElement, assignVarsCall) {
418
+ const existingAttr = openingElement.attributes.find(
419
+ (attribute) => t4.isJSXAttribute(attribute) && t4.isJSXIdentifier(attribute.name, { name: "style" })
420
+ );
421
+ if (!existingAttr) {
422
+ openingElement.attributes.push(
423
+ t4.jsxAttribute(t4.jsxIdentifier("style"), t4.jsxExpressionContainer(assignVarsCall))
424
+ );
425
+ return;
426
+ }
427
+ if (!existingAttr.value) {
428
+ existingAttr.value = t4.jsxExpressionContainer(assignVarsCall);
429
+ return;
430
+ }
431
+ if (t4.isJSXExpressionContainer(existingAttr.value)) {
432
+ existingAttr.value = t4.jsxExpressionContainer(
433
+ mergeStyleExpressions(existingAttr.value.expression, assignVarsCall)
434
+ );
435
+ }
436
+ }
437
+ function collectPropValuesFromJsx(openingElement, propNames) {
438
+ const values = /* @__PURE__ */ new Map();
439
+ for (const attribute of openingElement.attributes) {
440
+ if (!t4.isJSXAttribute(attribute) || !t4.isJSXIdentifier(attribute.name)) continue;
441
+ if (!propNames.has(attribute.name.name)) continue;
442
+ if (!attribute.value) {
443
+ values.set(attribute.name.name, t4.booleanLiteral(true));
444
+ continue;
445
+ }
446
+ if (t4.isStringLiteral(attribute.value)) {
447
+ values.set(attribute.name.name, t4.stringLiteral(attribute.value.value));
448
+ continue;
449
+ }
450
+ if (t4.isJSXExpressionContainer(attribute.value)) {
451
+ values.set(attribute.name.name, attribute.value.expression);
452
+ }
453
+ }
454
+ return values;
455
+ }
456
+ function removeStyledProps(openingElement, propNames) {
457
+ openingElement.attributes = openingElement.attributes.filter((attribute) => {
458
+ if (!t4.isJSXAttribute(attribute) || !t4.isJSXIdentifier(attribute.name)) return true;
459
+ return !propNames.has(attribute.name.name);
460
+ });
461
+ }
462
+ function buildComponentClassNameExpression(componentConstName, variantProps, propValues) {
463
+ const properties = variantProps.filter((propName) => propValues.has(propName)).map((propName) => t4.objectProperty(t4.identifier(propName), propValues.get(propName)));
464
+ if (properties.length === 0) {
465
+ return t4.callExpression(t4.identifier(componentConstName), []);
466
+ }
467
+ return t4.callExpression(t4.identifier(componentConstName), [t4.objectExpression(properties)]);
468
+ }
469
+ function migrateBooleanVariantTemplate(path, variableName, template, styledTarget, warnings, styledTransforms) {
470
+ const booleanInterpolations = parseBooleanTemplateInterpolations(template);
471
+ if (!booleanInterpolations) return false;
472
+ const staticCss = reconstructStaticCssWithoutVariants(template, booleanInterpolations);
473
+ const baseObject = cssToObjectExpression(staticCss, warnings);
474
+ if (!baseObject) {
475
+ addWarning(warnings, "Skipped because CSS could not be parsed.", variableName);
476
+ return false;
477
+ }
478
+ const componentConstName = path.scope.generateUidIdentifier(
479
+ toComponentConstName(variableName)
480
+ ).name;
481
+ const componentConfig = buildVariantComponentConfig(baseObject, booleanInterpolations);
482
+ const variantProps = [
483
+ ...new Set(booleanInterpolations.map((interpolation) => interpolation.propName))
484
+ ];
485
+ const declaration = path.parentPath;
486
+ if (!declaration.isVariableDeclaration()) return false;
487
+ declaration.node.declarations = [
488
+ t4.variableDeclarator(
489
+ t4.identifier(componentConstName),
490
+ t4.callExpression(t4.memberExpression(t4.identifier("styles"), t4.identifier("component")), [
491
+ t4.stringLiteral(toKebabCase(variableName)),
492
+ componentConfig
493
+ ])
494
+ )
495
+ ];
496
+ styledTransforms.set(variableName, {
497
+ originalName: variableName,
498
+ mode: "component",
499
+ classConstName: componentConstName,
500
+ target: styledTarget,
501
+ propVars: [],
502
+ variantProps
503
+ });
504
+ return true;
505
+ }
506
+ function migrateInterpolatedTemplate(path, variableName, template, styledTarget, warnings, styledTransforms) {
507
+ const interpolations = parseTemplateInterpolations(template);
508
+ if (!interpolations) {
509
+ addWarning(
510
+ warnings,
511
+ "Skipped template literal with unsupported interpolations. Only prop-based patterns like `${props => props.color}` are migrated.",
512
+ variableName
513
+ );
514
+ return false;
515
+ }
516
+ const cssText = reconstructInterpolatedCss(template, interpolations);
517
+ const propVars = interpolations.map((interpolation) => ({
518
+ propName: interpolation.propName,
519
+ varConstName: path.scope.generateUidIdentifier(
520
+ `${variableName}${interpolation.propName.charAt(0).toUpperCase()}${interpolation.propName.slice(1)}Var`
521
+ ).name,
522
+ suffix: interpolation.suffix
523
+ }));
524
+ const varReplacements = /* @__PURE__ */ new Map();
525
+ for (let i = 0; i < interpolations.length; i++) {
526
+ varReplacements.set(
527
+ placeholderToken(interpolations[i].index),
528
+ t4.identifier(propVars[i].varConstName)
529
+ );
530
+ }
531
+ const objectExpression4 = cssToObjectExpression(cssText, warnings, varReplacements);
532
+ if (!objectExpression4) {
533
+ addWarning(warnings, "Skipped because CSS could not be parsed.", variableName);
534
+ return false;
535
+ }
536
+ const classConstName = path.scope.generateUidIdentifier(`${variableName}Class`).name;
537
+ const varDeclarators = propVars.map(
538
+ (propVar) => t4.variableDeclarator(
539
+ t4.identifier(propVar.varConstName),
540
+ t4.callExpression(t4.identifier("createVar"), [
541
+ t4.stringLiteral(toVarDebugName(variableName, propVar.propName))
542
+ ])
543
+ )
544
+ );
545
+ const declaration = path.parentPath;
546
+ if (!declaration.isVariableDeclaration()) return false;
547
+ declaration.node.declarations = [
548
+ ...varDeclarators,
549
+ t4.variableDeclarator(
550
+ t4.identifier(classConstName),
551
+ t4.callExpression(t4.memberExpression(t4.identifier("styles"), t4.identifier("class")), [
552
+ t4.stringLiteral(toKebabCase(variableName)),
553
+ objectExpression4
554
+ ])
555
+ )
556
+ ];
557
+ styledTransforms.set(variableName, {
558
+ originalName: variableName,
559
+ mode: "class",
560
+ classConstName,
561
+ target: styledTarget,
562
+ propVars,
563
+ variantProps: []
564
+ });
565
+ return true;
566
+ }
567
+ function isOnlyJsxReferences(binding) {
568
+ return binding.referencePaths.every((referencePath) => {
569
+ const parent = referencePath.parentPath;
570
+ if (!parent) return false;
571
+ return parent.isJSXOpeningElement() && parent.get("name") === referencePath || parent.isJSXClosingElement() && parent.get("name") === referencePath;
572
+ });
573
+ }
574
+ function migrateSource(filePath, source) {
575
+ const warnings = [];
576
+ let changed = false;
577
+ const ast = parse(source, {
578
+ sourceType: "module",
579
+ plugins: ["typescript", "jsx"]
580
+ });
581
+ const styledNames = /* @__PURE__ */ new Set();
582
+ const cssTagNames = /* @__PURE__ */ new Set();
583
+ const styledTransforms = /* @__PURE__ */ new Map();
584
+ let needsVars = false;
585
+ traverse(ast, {
586
+ ImportDeclaration(path) {
587
+ if (path.node.source.value === "styled-components" || path.node.source.value === "@emotion/styled") {
588
+ for (const specifier of path.node.specifiers) {
589
+ if (t4.isImportDefaultSpecifier(specifier)) {
590
+ styledNames.add(specifier.local.name);
591
+ }
592
+ if (t4.isImportSpecifier(specifier) && t4.isIdentifier(specifier.imported, { name: "css" })) {
593
+ cssTagNames.add(specifier.local.name);
594
+ }
595
+ }
596
+ }
597
+ if (path.node.source.value === "@emotion/react" || path.node.source.value === "@emotion/css") {
598
+ for (const specifier of path.node.specifiers) {
599
+ if (t4.isImportSpecifier(specifier) && t4.isIdentifier(specifier.imported, { name: "css" })) {
600
+ cssTagNames.add(specifier.local.name);
601
+ }
602
+ }
603
+ }
604
+ }
605
+ });
606
+ traverse(ast, {
607
+ VariableDeclarator(path) {
608
+ if (!t4.isIdentifier(path.node.id)) return;
609
+ if (!t4.isTaggedTemplateExpression(path.node.init)) return;
610
+ const variableName = path.node.id.name;
611
+ const binding = path.scope.getBinding(variableName);
612
+ if (!binding) return;
613
+ const template = path.node.init.quasi;
614
+ const hasInterpolations = template.expressions.length > 0;
615
+ const styledTarget = parseStyledTarget(path.node.init.tag, styledNames);
616
+ if (hasInterpolations) {
617
+ if (!styledTarget) {
618
+ addWarning(
619
+ warnings,
620
+ "Skipped template literal with interpolations. Only styled-components prop patterns are migrated.",
621
+ variableName
622
+ );
623
+ return;
624
+ }
625
+ const declaration = path.parentPath;
626
+ if (declaration.parentPath?.isExportNamedDeclaration() || declaration.parentPath?.isExportDefaultDeclaration()) {
627
+ addWarning(
628
+ warnings,
629
+ "Skipped exported styled component to avoid changing external API shape.",
630
+ variableName
631
+ );
632
+ return;
633
+ }
634
+ if (!isOnlyJsxReferences(binding)) {
635
+ addWarning(warnings, "Skipped styled component with non-JSX references.", variableName);
636
+ return;
637
+ }
638
+ if (migrateBooleanVariantTemplate(
639
+ path,
640
+ variableName,
641
+ template,
642
+ styledTarget,
643
+ warnings,
644
+ styledTransforms
645
+ )) {
646
+ changed = true;
647
+ return;
648
+ }
649
+ if (migrateInterpolatedTemplate(
650
+ path,
651
+ variableName,
652
+ template,
653
+ styledTarget,
654
+ warnings,
655
+ styledTransforms
656
+ )) {
657
+ needsVars = true;
658
+ changed = true;
659
+ }
660
+ return;
661
+ }
662
+ const cssText = template.quasis.map((quasi) => quasi.value.cooked ?? "").join("");
663
+ const objectExpression4 = cssToObjectExpression(cssText, warnings);
664
+ if (!objectExpression4) {
665
+ addWarning(warnings, "Skipped because CSS could not be parsed.", variableName);
666
+ return;
667
+ }
668
+ if (styledTarget) {
669
+ const declaration = path.parentPath;
670
+ if (declaration.parentPath?.isExportNamedDeclaration() || declaration.parentPath?.isExportDefaultDeclaration()) {
671
+ addWarning(
672
+ warnings,
673
+ "Skipped exported styled component to avoid changing external API shape.",
674
+ variableName
675
+ );
676
+ return;
677
+ }
678
+ if (!isOnlyJsxReferences(binding)) {
679
+ addWarning(warnings, "Skipped styled component with non-JSX references.", variableName);
680
+ return;
681
+ }
682
+ const classConstName = path.scope.generateUidIdentifier(`${variableName}Class`).name;
683
+ path.node.id = t4.identifier(classConstName);
684
+ path.node.init = t4.callExpression(
685
+ t4.memberExpression(t4.identifier("styles"), t4.identifier("class")),
686
+ [t4.stringLiteral(toKebabCase(variableName)), objectExpression4]
687
+ );
688
+ styledTransforms.set(variableName, {
689
+ originalName: variableName,
690
+ mode: "class",
691
+ classConstName,
692
+ target: styledTarget,
693
+ propVars: [],
694
+ variantProps: []
695
+ });
696
+ changed = true;
697
+ return;
698
+ }
699
+ if (t4.isIdentifier(path.node.init.tag) && cssTagNames.has(path.node.init.tag.name)) {
700
+ path.node.init = t4.callExpression(
701
+ t4.memberExpression(t4.identifier("styles"), t4.identifier("class")),
702
+ [t4.stringLiteral(toKebabCase(variableName)), objectExpression4]
703
+ );
704
+ changed = true;
705
+ }
706
+ }
707
+ });
708
+ if (styledTransforms.size > 0) {
709
+ traverse(ast, {
710
+ JSXElement(path) {
711
+ const openingName = path.node.openingElement.name;
712
+ if (!t4.isJSXIdentifier(openingName)) return;
713
+ const transform = styledTransforms.get(openingName.name);
714
+ if (!transform) return;
715
+ path.node.openingElement.name = transform.target.jsxName;
716
+ if (path.node.closingElement) {
717
+ path.node.closingElement.name = transform.target.jsxName;
718
+ }
719
+ const classNameExpression = transform.mode === "component" ? buildComponentClassNameExpression(
720
+ transform.classConstName,
721
+ transform.variantProps,
722
+ collectPropValuesFromJsx(path.node.openingElement, new Set(transform.variantProps))
723
+ ) : t4.identifier(transform.classConstName);
724
+ updateClassNameAttribute(path.node.openingElement, classNameExpression);
725
+ if (transform.propVars.length > 0) {
726
+ const propNames = new Set(transform.propVars.map((propVar) => propVar.propName));
727
+ const propValues = collectPropValuesFromJsx(path.node.openingElement, propNames);
728
+ if (propValues.size > 0) {
729
+ const assignVarsCall = buildAssignVarsCall(transform.propVars, propValues);
730
+ updateStyleAttribute(path.node.openingElement, assignVarsCall);
731
+ removeStyledProps(path.node.openingElement, propNames);
732
+ }
733
+ }
734
+ if (transform.variantProps.length > 0) {
735
+ removeStyledProps(path.node.openingElement, new Set(transform.variantProps));
736
+ }
737
+ }
738
+ });
739
+ }
740
+ if (changed) {
741
+ ensureTypestylesImport(ast, needsVars);
742
+ cleanupUnusedImports(ast);
743
+ }
744
+ const output = generate(
745
+ ast,
746
+ {
747
+ retainLines: false,
748
+ comments: true,
749
+ concise: false
750
+ },
751
+ source
752
+ );
753
+ return {
754
+ filePath,
755
+ changed: changed && output.code !== source,
756
+ code: output.code,
757
+ warnings
758
+ };
759
+ }
760
+ var DEFAULT_EXCLUDES = ["**/node_modules/**", "**/dist/**", "**/.next/**", "**/.turbo/**"];
761
+ function normalizeExtension(extension) {
762
+ return extension.startsWith(".") ? extension : `.${extension}`;
763
+ }
764
+ async function collectTargetFiles(cwd, targets, extensions, include, exclude) {
765
+ const normalizedTargets = targets.length > 0 ? targets : ["."];
766
+ const literalFiles = [];
767
+ const dynamicPatterns = [];
768
+ for (const target of normalizedTargets) {
769
+ const absolute = resolve(cwd, target);
770
+ try {
771
+ const targetStat = await stat(absolute);
772
+ if (targetStat.isFile()) {
773
+ literalFiles.push(absolute);
774
+ } else if (targetStat.isDirectory()) {
775
+ dynamicPatterns.push(`${absolute.split("\\").join("/")}/**/*`);
776
+ }
777
+ } catch {
778
+ dynamicPatterns.push(target);
779
+ }
780
+ }
781
+ const globbed = await fg(dynamicPatterns, {
782
+ cwd,
783
+ absolute: true,
784
+ onlyFiles: true,
785
+ ignore: [...DEFAULT_EXCLUDES, ...exclude]
786
+ });
787
+ const extensionSet = new Set(extensions.map(normalizeExtension));
788
+ const includeMatchers = include.length > 0 ? include.map((pattern) => picomatch(pattern)) : null;
789
+ const unique = /* @__PURE__ */ new Set([...literalFiles, ...globbed]);
790
+ return Array.from(unique).filter((filePath) => extensionSet.has(extname(filePath))).filter((filePath) => {
791
+ if (!includeMatchers) return true;
792
+ const rel = relative(cwd, filePath).split("\\").join("/");
793
+ return includeMatchers.some((matcher) => matcher(rel));
794
+ }).sort();
795
+ }
796
+
797
+ // src/migrate.ts
798
+ function renderPatch(filePath, before, after) {
799
+ return createPatch(filePath, before, after, "before", "after").split("\n").slice(2).join("\n");
800
+ }
801
+ async function runMigration(cwd, options) {
802
+ const files = await collectTargetFiles(
803
+ cwd,
804
+ options.targets,
805
+ options.extensions,
806
+ options.include,
807
+ options.exclude
808
+ );
809
+ const reportEntries = [];
810
+ let changedCount = 0;
811
+ let warningCount = 0;
812
+ for (const filePath of files) {
813
+ const before = await readFile(filePath, "utf8");
814
+ const result = migrateSource(filePath, before);
815
+ const relativePath = relative(cwd, filePath);
816
+ warningCount += result.warnings.length;
817
+ if (result.changed) {
818
+ changedCount += 1;
819
+ if (options.write) {
820
+ await writeFile(filePath, result.code, "utf8");
821
+ process.stdout.write(`updated ${relativePath}
822
+ `);
823
+ } else {
824
+ process.stdout.write(`
825
+ --- ${relativePath} (dry-run) ---
826
+ `);
827
+ process.stdout.write(`${renderPatch(relativePath, before, result.code)}
828
+ `);
829
+ }
830
+ }
831
+ for (const warning of result.warnings) {
832
+ const nodeLabel = warning.nodeName ? ` (${warning.nodeName})` : "";
833
+ process.stdout.write(`warning ${relativePath}${nodeLabel}: ${warning.message}
834
+ `);
835
+ }
836
+ reportEntries.push({
837
+ filePath: relativePath,
838
+ changed: result.changed,
839
+ warnings: result.warnings
840
+ });
841
+ }
842
+ const summary = {
843
+ filesScanned: files.length,
844
+ filesChanged: changedCount,
845
+ warnings: warningCount
846
+ };
847
+ process.stdout.write(
848
+ `
849
+ Scanned ${summary.filesScanned} files, changed ${summary.filesChanged}, warnings ${summary.warnings}.
850
+ `
851
+ );
852
+ const report = {
853
+ summary,
854
+ files: reportEntries
855
+ };
856
+ if (options.reportPath) {
857
+ await mkdir(dirname(options.reportPath), { recursive: true });
858
+ await writeFile(options.reportPath, `${JSON.stringify(report, null, 2)}
859
+ `, "utf8");
860
+ process.stdout.write(`Report written to ${options.reportPath}
861
+ `);
862
+ }
863
+ return report;
864
+ }
865
+
866
+ export { migrateSource, runMigration };
867
+ //# sourceMappingURL=chunk-D2W3OEBT.js.map
868
+ //# sourceMappingURL=chunk-D2W3OEBT.js.map