@una-ui/extractor-vue-script 0.64.0 → 0.66.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.
Files changed (2) hide show
  1. package/dist/index.mjs +122 -33
  2. package/package.json +9 -2
package/dist/index.mjs CHANGED
@@ -1,4 +1,9 @@
1
+ import * as babel from '@babel/types';
1
2
  import { defaultSplitRE } from '@unocss/core';
3
+ import { transform, NodeTypes } from '@vue/compiler-core';
4
+ import { parse } from '@vue/compiler-sfc';
5
+ import { parseModule } from 'magicast';
6
+ import { parsePath } from 'ufo';
2
7
 
3
8
  function generateSelectors(prefix, values) {
4
9
  prefix = prefix.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
@@ -8,50 +13,134 @@ function normalizePrefixes(prefixes) {
8
13
  const camelCasePrefixes = prefixes.map((prefix) => prefix.replace(/-([a-z])/g, (_, c) => c.toUpperCase()));
9
14
  return [.../* @__PURE__ */ new Set([...prefixes, ...camelCasePrefixes])];
10
15
  }
11
- function splitCodeWithArbitraryVariants(code, prefixes) {
12
- const result = [];
13
- const normalizedPrefixes = normalizePrefixes(prefixes);
14
- for (const prefix of normalizedPrefixes) {
15
- const regex = new RegExp(`\\b${prefix}\\s*:\\s*(?:['"]([^'"]*)['"]|{[^}]*\\bdefault\\s*:\\s*['"]([^'"]*)['"]\\s*,?.*?})`, "gms");
16
- let match;
17
- while ((match = regex.exec(code)) !== null) {
18
- const values = (match[1] ?? match[2]).split(defaultSplitRE);
19
- const selectors = generateSelectors(prefix, values);
20
- result.push(...selectors);
16
+ function getLiteralValue(node) {
17
+ if (node.type === "ConditionalExpression") {
18
+ return [node.consequent, node.alternate].map(getLiteralValue);
19
+ }
20
+ if (node.type === "StringLiteral") {
21
+ return node.value;
22
+ }
23
+ if (node.type === "TemplateLiteral") {
24
+ if (node.expressions.length > 0) {
25
+ return void 0;
21
26
  }
27
+ return node.quasis.map((q) => q.value.cooked).join("");
28
+ }
29
+ if (node.type === "ObjectExpression") {
30
+ return getObjectLiteralValue(node);
22
31
  }
23
- return result;
32
+ return void 0;
24
33
  }
25
- function extractConditionalStatements(code, prefixes) {
34
+ function getObjectLiteralValue(node) {
35
+ return Object.fromEntries(
36
+ node.properties.filter((prop) => prop.type === "ObjectProperty").flatMap((prop) => {
37
+ const key = prop.key.type === "Identifier" ? prop.key.name : prop.key.type === "StringLiteral" ? prop.key.value : null;
38
+ if (!key) {
39
+ return [];
40
+ }
41
+ return [[key, getLiteralValue(prop.value)]];
42
+ })
43
+ );
44
+ }
45
+ function discoverVariants(node, prefixes) {
26
46
  const result = [];
27
- const normalizedPrefixes = normalizePrefixes(prefixes);
28
- for (const prefix of normalizedPrefixes) {
29
- const ternaryRegex = new RegExp(
30
- `\\b${prefix}\\s*:\\s*[^?]*?\\?\\s*['"\`]([^'"\`]*?)['"\`]\\s*:\\s*['"\`]([^'"\`]*?)['"\`]`,
31
- "gms"
32
- );
33
- let match;
34
- while ((match = ternaryRegex.exec(code)) !== null) {
35
- const [, trueValue, falseValue] = match;
36
- const allValues = [
37
- ...trueValue.split(defaultSplitRE),
38
- ...falseValue.split(defaultSplitRE)
39
- ];
40
- const selectors = generateSelectors(prefix, allValues);
41
- result.push(...selectors);
47
+ babel.traverse(node, {
48
+ enter(node2) {
49
+ if (node2.type === "ObjectExpression") {
50
+ const object = getObjectLiteralValue(node2);
51
+ for (let [key, value] of Object.entries(object)) {
52
+ if (prefixes.includes(key) && value) {
53
+ if (!Array.isArray(value)) {
54
+ value = [value];
55
+ }
56
+ for (let v of value) {
57
+ if (typeof v === "object" && v !== null && "default" in v) {
58
+ v = v.default;
59
+ }
60
+ if (typeof v !== "string") {
61
+ continue;
62
+ }
63
+ result.push([key, v]);
64
+ }
65
+ }
66
+ }
67
+ }
68
+ if (node2.type === "AssignmentPattern") {
69
+ const { left, right } = node2;
70
+ if (left.type === "Identifier" && right.type === "StringLiteral") {
71
+ const prefix = left.name;
72
+ const value = right.value;
73
+ if (prefixes.includes(prefix)) {
74
+ result.push([prefix, value]);
75
+ }
76
+ }
77
+ }
42
78
  }
79
+ });
80
+ return result.flatMap(([key, v]) => {
81
+ const values = v.split(defaultSplitRE);
82
+ return generateSelectors(key, values);
83
+ });
84
+ }
85
+ function parseCodeAst(code, id) {
86
+ try {
87
+ const { $ast: node } = parseModule(code, {
88
+ sourceFileName: id
89
+ });
90
+ return node;
91
+ } catch (e) {
92
+ throw new SyntaxError(`Failed to parse code ast${id ? ` (file: ${id})` : ""}`, { cause: e });
43
93
  }
44
- return result;
45
94
  }
95
+ function extractTemplateExpressions(node) {
96
+ const expressions = [];
97
+ transform(node, {
98
+ nodeTransforms: [
99
+ // readonly "transformer", doesn't do any changes
100
+ (node2) => {
101
+ if (node2.type === NodeTypes.ELEMENT) {
102
+ node2.props.forEach((prop) => {
103
+ if (prop.type === NodeTypes.DIRECTIVE && prop.exp?.ast) {
104
+ expressions.push(prop.exp.ast);
105
+ }
106
+ });
107
+ }
108
+ }
109
+ ]
110
+ });
111
+ return expressions;
112
+ }
113
+ const SUPPORTED_EXTENSION_IDS = /\.(?:[mc]?[jt]sx?|vue)$/;
46
114
  function extractorVueScript(options) {
47
115
  return {
48
116
  name: "@una-ui/extractor-vue-script",
49
117
  order: 0,
50
- async extract({ code }) {
51
- const prefixes = options?.prefixes ?? [];
52
- const regularResults = splitCodeWithArbitraryVariants(code, prefixes);
53
- const conditionalResults = extractConditionalStatements(code, prefixes);
54
- return [.../* @__PURE__ */ new Set([...regularResults, ...conditionalResults])];
118
+ async extract({ code, id }) {
119
+ const cleanPath = parsePath(id).pathname;
120
+ if (!SUPPORTED_EXTENSION_IDS.test(cleanPath)) {
121
+ return void 0;
122
+ }
123
+ const astExprs = [];
124
+ if (cleanPath.endsWith(".vue")) {
125
+ const sfc = parse(code, {
126
+ filename: cleanPath
127
+ });
128
+ if (sfc.descriptor.script) {
129
+ astExprs.push(parseCodeAst(sfc.descriptor.script.content));
130
+ }
131
+ if (sfc.descriptor.scriptSetup) {
132
+ astExprs.push(parseCodeAst(sfc.descriptor.scriptSetup.content));
133
+ }
134
+ if (sfc.descriptor.template?.ast) {
135
+ astExprs.push(...extractTemplateExpressions(sfc.descriptor.template.ast));
136
+ }
137
+ } else {
138
+ astExprs.push(parseCodeAst(code, id));
139
+ }
140
+ const prefixes = normalizePrefixes(options?.prefixes ?? []);
141
+ return [...new Set(
142
+ astExprs.flatMap((node) => discoverVariants(node, prefixes))
143
+ )];
55
144
  }
56
145
  };
57
146
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@una-ui/extractor-vue-script",
3
- "version": "0.64.0",
3
+ "version": "0.66.0",
4
4
  "description": "Unocss extractor for Vue script",
5
5
  "author": "Phojie Rengel <phojrengel@gmail.com>",
6
6
  "license": "MIT",
@@ -34,8 +34,15 @@
34
34
  "publishConfig": {
35
35
  "access": "public"
36
36
  },
37
+ "dependencies": {
38
+ "@babel/types": "^7.28.5",
39
+ "@vue/compiler-core": "^3.5.24",
40
+ "@vue/compiler-sfc": "^3.5.24",
41
+ "magicast": "^0.5.1",
42
+ "ufo": "^1.6.1"
43
+ },
37
44
  "devDependencies": {
38
- "@unocss/core": "^66.4.2",
45
+ "@unocss/core": "^66.5.4",
39
46
  "vitest": "^3.2.4"
40
47
  },
41
48
  "scripts": {