@plumeria/turbopack-loader 12.0.8 → 13.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1275 -1199
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -39,300 +39,363 @@ const fs = __importStar(require("fs"));
39
39
  const path = __importStar(require("path"));
40
40
  const zss_engine_1 = require("zss-engine");
41
41
  const utils_1 = require("@plumeria/utils");
42
+ let lastValidCss = '';
43
+ function cleanStaleThemeRules(currentCss, optInCss) {
44
+ const hashRegex = /--([a-z0-9]{8})-[a-zA-Z0-9-]+/g;
45
+ const hashes = new Set();
46
+ let match;
47
+ while ((match = hashRegex.exec(optInCss)) !== null) {
48
+ hashes.add(match[1]);
49
+ }
50
+ let cleanedCss = currentCss;
51
+ for (const hash of hashes) {
52
+ const ruleRegex = new RegExp(`(@[a-zA-Z]+[^{]*\\{[^{]*\\{[^\\}]*--${hash}-[a-zA-Z0-9-]+[^\\}]*\\}[^\\}]*\\})|([^\\}]*\\{[^\\}]*--${hash}-[a-zA-Z0-9-]+[^\\}]*\\})`, 'g');
53
+ cleanedCss = cleanedCss.replace(ruleRegex, '');
54
+ }
55
+ return cleanedCss.trim();
56
+ }
42
57
  async function loader(source) {
43
58
  const callback = this.async();
44
59
  const resourcePath = this.resourcePath;
45
60
  const isProduction = process.env.NODE_ENV === 'production';
46
61
  const VIRTUAL_FILE_PATH = path.resolve(__dirname, '..', 'zero-virtual.css');
62
+ if (!lastValidCss && !isProduction) {
63
+ try {
64
+ lastValidCss = fs.readFileSync(VIRTUAL_FILE_PATH, 'utf-8');
65
+ }
66
+ catch (e) {
67
+ }
68
+ }
47
69
  if (resourcePath.includes('node_modules') ||
48
70
  !source.includes('@plumeria/core')) {
49
71
  return callback(null, source);
50
72
  }
51
- this.clearDependencies();
52
- this.addDependency(resourcePath);
53
- const ast = (0, core_1.parseSync)(source, {
54
- syntax: 'typescript',
55
- tsx: true,
56
- target: 'es2022',
57
- });
58
- const leadingLen = (0, utils_1.getLeadingCommentLength)(source);
59
- const sourceBuffer = Buffer.from(source, 'utf-8');
60
- const leadingBytes = Buffer.byteLength(source.slice(0, leadingLen), 'utf-8');
61
- const baseByteOffset = ast.span.start - leadingBytes;
62
- for (const node of ast.body) {
63
- if (node.type === 'ImportDeclaration') {
64
- const sourcePath = node.source.value;
65
- const actualPath = (0, utils_1.resolveImportPath)(sourcePath, resourcePath);
66
- if (actualPath) {
67
- this.addDependency(actualPath);
73
+ try {
74
+ this.clearDependencies();
75
+ this.addDependency(resourcePath);
76
+ const ast = (0, core_1.parseSync)(source, {
77
+ syntax: 'typescript',
78
+ tsx: true,
79
+ target: 'es2022',
80
+ });
81
+ const leadingLen = (0, utils_1.getLeadingCommentLength)(source);
82
+ const sourceBuffer = Buffer.from(source, 'utf-8');
83
+ const leadingBytes = Buffer.byteLength(source.slice(0, leadingLen), 'utf-8');
84
+ const baseByteOffset = ast.span.start - leadingBytes;
85
+ for (const node of ast.body) {
86
+ if (node.type === 'ImportDeclaration') {
87
+ const sourcePath = node.source.value;
88
+ const actualPath = (0, utils_1.resolveImportPath)(sourcePath, resourcePath);
89
+ if (actualPath) {
90
+ this.addDependency(actualPath);
91
+ }
68
92
  }
69
93
  }
70
- }
71
- const scannedTables = (0, utils_1.scanAll)();
72
- const extractedSheets = [];
73
- const addSheet = (sheet) => {
74
- if (!extractedSheets.includes(sheet)) {
75
- extractedSheets.push(sheet);
76
- }
77
- };
78
- const processStyleRecords = (style) => {
79
- const records = (0, utils_1.getStyleRecords)(style);
80
- if (!isProduction) {
81
- (0, utils_1.extractOndemandStyles)(style, extractedSheets, scannedTables);
82
- records.forEach((r) => {
83
- addSheet(r.sheet);
84
- });
85
- }
86
- return records;
87
- };
88
- const localConsts = (0, utils_1.collectLocalConsts)(ast);
89
- const importMap = {};
90
- const keyframesImportMap = {};
91
- const viewTransitionImportMap = {};
92
- const createImportMap = {};
93
- const variantsImportMap = {};
94
- const createThemeImportMap = {};
95
- const createStaticImportMap = {};
96
- const plumeriaAliases = {};
97
- (0, utils_1.traverse)(ast, {
98
- ImportDeclaration({ node }) {
99
- const sourcePath = node.source.value;
100
- if (sourcePath === '@plumeria/core') {
101
- node.specifiers.forEach((specifier) => {
102
- if (specifier.type === 'ImportNamespaceSpecifier') {
103
- plumeriaAliases[specifier.local.value] = 'NAMESPACE';
104
- }
105
- else if (specifier.type === 'ImportDefaultSpecifier') {
106
- plumeriaAliases[specifier.local.value] = 'NAMESPACE';
107
- }
108
- else if (specifier.type === 'ImportSpecifier') {
109
- const importedName = specifier.imported
110
- ? specifier.imported.value
111
- : specifier.local.value;
112
- plumeriaAliases[specifier.local.value] = importedName;
113
- }
94
+ const scannedTables = (0, utils_1.scanAll)();
95
+ const extractedSheets = [];
96
+ const addSheet = (sheet) => {
97
+ if (!extractedSheets.includes(sheet)) {
98
+ extractedSheets.push(sheet);
99
+ }
100
+ };
101
+ const processStyleRecords = (style) => {
102
+ const records = (0, utils_1.getStyleRecords)(style);
103
+ if (!isProduction) {
104
+ (0, utils_1.extractOndemandStyles)(style, extractedSheets, scannedTables);
105
+ records.forEach((r) => {
106
+ addSheet(r.sheet);
114
107
  });
115
108
  }
116
- const actualPath = (0, utils_1.resolveImportPath)(sourcePath, resourcePath);
117
- if (actualPath) {
118
- node.specifiers.forEach((specifier) => {
119
- if (specifier.type === 'ImportSpecifier') {
120
- const importedName = specifier.imported
121
- ? specifier.imported.value
122
- : specifier.local.value;
123
- const localName = specifier.local.value;
124
- const uniqueKey = `${actualPath}-${importedName}`;
125
- if (scannedTables.staticTable[uniqueKey]) {
126
- importMap[localName] = scannedTables.staticTable[uniqueKey];
127
- }
128
- if (scannedTables.keyframesHashTable[uniqueKey]) {
129
- keyframesImportMap[localName] =
130
- scannedTables.keyframesHashTable[uniqueKey];
131
- }
132
- if (scannedTables.viewTransitionHashTable[uniqueKey]) {
133
- viewTransitionImportMap[localName] =
134
- scannedTables.viewTransitionHashTable[uniqueKey];
135
- }
136
- if (scannedTables.createHashTable[uniqueKey]) {
137
- createImportMap[localName] =
138
- scannedTables.createHashTable[uniqueKey];
109
+ return records;
110
+ };
111
+ const localConsts = (0, utils_1.collectLocalConsts)(ast);
112
+ const importMap = {};
113
+ const keyframesImportMap = {};
114
+ const viewTransitionImportMap = {};
115
+ const createImportMap = {};
116
+ const variantsImportMap = {};
117
+ const createThemeImportMap = {};
118
+ const createStaticImportMap = {};
119
+ const plumeriaAliases = {};
120
+ (0, utils_1.traverse)(ast, {
121
+ ImportDeclaration({ node }) {
122
+ const sourcePath = node.source.value;
123
+ if (sourcePath === '@plumeria/core') {
124
+ node.specifiers.forEach((specifier) => {
125
+ if (specifier.type === 'ImportNamespaceSpecifier') {
126
+ plumeriaAliases[specifier.local.value] = 'NAMESPACE';
139
127
  }
140
- if (scannedTables.variantsHashTable[uniqueKey]) {
141
- variantsImportMap[localName] =
142
- scannedTables.variantsHashTable[uniqueKey];
128
+ else if (specifier.type === 'ImportDefaultSpecifier') {
129
+ plumeriaAliases[specifier.local.value] = 'NAMESPACE';
143
130
  }
144
- if (scannedTables.createThemeHashTable[uniqueKey]) {
145
- createThemeImportMap[localName] =
146
- scannedTables.createThemeHashTable[uniqueKey];
131
+ else if (specifier.type === 'ImportSpecifier') {
132
+ const importedName = specifier.imported
133
+ ? specifier.imported.value
134
+ : specifier.local.value;
135
+ plumeriaAliases[specifier.local.value] = importedName;
147
136
  }
148
- if (scannedTables.createStaticHashTable[uniqueKey]) {
149
- createStaticImportMap[localName] =
150
- scannedTables.createStaticHashTable[uniqueKey];
137
+ });
138
+ }
139
+ const actualPath = (0, utils_1.resolveImportPath)(sourcePath, resourcePath);
140
+ if (actualPath) {
141
+ node.specifiers.forEach((specifier) => {
142
+ if (specifier.type === 'ImportSpecifier') {
143
+ const importedName = specifier.imported
144
+ ? specifier.imported.value
145
+ : specifier.local.value;
146
+ const localName = specifier.local.value;
147
+ const uniqueKey = `${actualPath}-${importedName}`;
148
+ if (scannedTables.staticTable[uniqueKey]) {
149
+ importMap[localName] = scannedTables.staticTable[uniqueKey];
150
+ }
151
+ if (scannedTables.keyframesHashTable[uniqueKey]) {
152
+ keyframesImportMap[localName] =
153
+ scannedTables.keyframesHashTable[uniqueKey];
154
+ }
155
+ if (scannedTables.viewTransitionHashTable[uniqueKey]) {
156
+ viewTransitionImportMap[localName] =
157
+ scannedTables.viewTransitionHashTable[uniqueKey];
158
+ }
159
+ if (scannedTables.createHashTable[uniqueKey]) {
160
+ createImportMap[localName] =
161
+ scannedTables.createHashTable[uniqueKey];
162
+ }
163
+ if (scannedTables.variantsHashTable[uniqueKey]) {
164
+ variantsImportMap[localName] =
165
+ scannedTables.variantsHashTable[uniqueKey];
166
+ }
167
+ if (scannedTables.createThemeHashTable[uniqueKey]) {
168
+ createThemeImportMap[localName] =
169
+ scannedTables.createThemeHashTable[uniqueKey];
170
+ }
171
+ if (scannedTables.createStaticHashTable[uniqueKey]) {
172
+ createStaticImportMap[localName] =
173
+ scannedTables.createStaticHashTable[uniqueKey];
174
+ }
151
175
  }
152
- }
153
- });
176
+ });
177
+ }
178
+ },
179
+ });
180
+ const mergedStaticTable = {};
181
+ for (const key of Object.keys(scannedTables.staticTable)) {
182
+ mergedStaticTable[key] = scannedTables.staticTable[key];
183
+ }
184
+ for (const key of Object.keys(localConsts)) {
185
+ mergedStaticTable[key] = localConsts[key];
186
+ }
187
+ for (const key of Object.keys(importMap)) {
188
+ mergedStaticTable[key] = importMap[key];
189
+ }
190
+ const mergedKeyframesTable = {};
191
+ for (const key of Object.keys(scannedTables.keyframesHashTable)) {
192
+ mergedKeyframesTable[key] = scannedTables.keyframesHashTable[key];
193
+ if (key.startsWith(`${resourcePath}-`)) {
194
+ const varName = key.slice(resourcePath.length + 1);
195
+ mergedKeyframesTable[varName] = scannedTables.keyframesHashTable[key];
154
196
  }
155
- },
156
- });
157
- const mergedStaticTable = {};
158
- for (const key of Object.keys(scannedTables.staticTable)) {
159
- mergedStaticTable[key] = scannedTables.staticTable[key];
160
- }
161
- for (const key of Object.keys(localConsts)) {
162
- mergedStaticTable[key] = localConsts[key];
163
- }
164
- for (const key of Object.keys(importMap)) {
165
- mergedStaticTable[key] = importMap[key];
166
- }
167
- const mergedKeyframesTable = {};
168
- for (const key of Object.keys(scannedTables.keyframesHashTable)) {
169
- mergedKeyframesTable[key] = scannedTables.keyframesHashTable[key];
170
- if (key.startsWith(`${resourcePath}-`)) {
171
- const varName = key.slice(resourcePath.length + 1);
172
- mergedKeyframesTable[varName] = scannedTables.keyframesHashTable[key];
173
197
  }
174
- }
175
- for (const key of Object.keys(keyframesImportMap)) {
176
- mergedKeyframesTable[key] = keyframesImportMap[key];
177
- }
178
- const mergedViewTransitionTable = {};
179
- for (const key of Object.keys(scannedTables.viewTransitionHashTable)) {
180
- mergedViewTransitionTable[key] = scannedTables.viewTransitionHashTable[key];
181
- if (key.startsWith(`${resourcePath}-`)) {
182
- const varName = key.slice(resourcePath.length + 1);
183
- mergedViewTransitionTable[varName] =
198
+ for (const key of Object.keys(keyframesImportMap)) {
199
+ mergedKeyframesTable[key] = keyframesImportMap[key];
200
+ }
201
+ const mergedViewTransitionTable = {};
202
+ for (const key of Object.keys(scannedTables.viewTransitionHashTable)) {
203
+ mergedViewTransitionTable[key] =
184
204
  scannedTables.viewTransitionHashTable[key];
205
+ if (key.startsWith(`${resourcePath}-`)) {
206
+ const varName = key.slice(resourcePath.length + 1);
207
+ mergedViewTransitionTable[varName] =
208
+ scannedTables.viewTransitionHashTable[key];
209
+ }
185
210
  }
186
- }
187
- for (const key of Object.keys(viewTransitionImportMap)) {
188
- mergedViewTransitionTable[key] = viewTransitionImportMap[key];
189
- }
190
- const mergedCreateTable = {};
191
- for (const key of Object.keys(scannedTables.createHashTable)) {
192
- mergedCreateTable[key] = scannedTables.createHashTable[key];
193
- if (key.startsWith(`${resourcePath}-`)) {
194
- const varName = key.slice(resourcePath.length + 1);
195
- mergedCreateTable[varName] = scannedTables.createHashTable[key];
211
+ for (const key of Object.keys(viewTransitionImportMap)) {
212
+ mergedViewTransitionTable[key] = viewTransitionImportMap[key];
196
213
  }
197
- }
198
- for (const key of Object.keys(createImportMap)) {
199
- mergedCreateTable[key] = createImportMap[key];
200
- }
201
- const mergedVariantsTable = {};
202
- for (const key of Object.keys(scannedTables.variantsHashTable)) {
203
- mergedVariantsTable[key] = scannedTables.variantsHashTable[key];
204
- if (key.startsWith(`${resourcePath}-`)) {
205
- const varName = key.slice(resourcePath.length + 1);
206
- mergedVariantsTable[varName] = scannedTables.variantsHashTable[key];
214
+ const mergedCreateTable = {};
215
+ for (const key of Object.keys(scannedTables.createHashTable)) {
216
+ mergedCreateTable[key] = scannedTables.createHashTable[key];
217
+ if (key.startsWith(`${resourcePath}-`)) {
218
+ const varName = key.slice(resourcePath.length + 1);
219
+ mergedCreateTable[varName] = scannedTables.createHashTable[key];
220
+ }
207
221
  }
208
- }
209
- for (const key of Object.keys(variantsImportMap)) {
210
- mergedVariantsTable[key] = variantsImportMap[key];
211
- }
212
- const mergedCreateThemeHashTable = {};
213
- for (const key of Object.keys(scannedTables.createThemeHashTable)) {
214
- mergedCreateThemeHashTable[key] = scannedTables.createThemeHashTable[key];
215
- if (key.startsWith(`${resourcePath}-`)) {
216
- const varName = key.slice(resourcePath.length + 1);
217
- mergedCreateThemeHashTable[varName] =
218
- scannedTables.createThemeHashTable[key];
222
+ for (const key of Object.keys(createImportMap)) {
223
+ mergedCreateTable[key] = createImportMap[key];
219
224
  }
220
- }
221
- for (const key of Object.keys(createThemeImportMap)) {
222
- mergedCreateThemeHashTable[key] = createThemeImportMap[key];
223
- }
224
- const mergedCreateStaticHashTable = {};
225
- for (const key of Object.keys(scannedTables.createStaticHashTable)) {
226
- mergedCreateStaticHashTable[key] = scannedTables.createStaticHashTable[key];
227
- if (key.startsWith(`${resourcePath}-`)) {
228
- const varName = key.slice(resourcePath.length + 1);
229
- mergedCreateStaticHashTable[varName] =
230
- scannedTables.createStaticHashTable[key];
225
+ const mergedVariantsTable = {};
226
+ for (const key of Object.keys(scannedTables.variantsHashTable)) {
227
+ mergedVariantsTable[key] = scannedTables.variantsHashTable[key];
228
+ if (key.startsWith(`${resourcePath}-`)) {
229
+ const varName = key.slice(resourcePath.length + 1);
230
+ mergedVariantsTable[varName] = scannedTables.variantsHashTable[key];
231
+ }
231
232
  }
232
- }
233
- for (const key of Object.keys(createStaticImportMap)) {
234
- mergedCreateStaticHashTable[key] = createStaticImportMap[key];
235
- }
236
- const localCreateStyles = {};
237
- const replacements = [];
238
- const processedDecls = new Set();
239
- const idSpans = new Set();
240
- const excludedSpans = new Set();
241
- const checkVariantAssignment = (decl) => {
242
- const init = decl.init;
243
- if (init && utils_1.t.isCallExpression(init) && utils_1.t.isIdentifier(init.callee)) {
244
- const varName = init.callee.value;
245
- if ((localCreateStyles[varName] &&
246
- localCreateStyles[varName].type === 'variant') ||
247
- mergedVariantsTable[varName]) {
248
- throw new Error(`Plumeria: Assigning the return value of "css.variants" to a variable is not supported.\nPlease pass the variant function directly to "css.use". Found assignment to: ${utils_1.t.isIdentifier(decl.id) ? decl.id.value : 'unknown'}`);
233
+ for (const key of Object.keys(variantsImportMap)) {
234
+ mergedVariantsTable[key] = variantsImportMap[key];
235
+ }
236
+ const mergedCreateThemeHashTable = {};
237
+ for (const key of Object.keys(scannedTables.createThemeHashTable)) {
238
+ mergedCreateThemeHashTable[key] = scannedTables.createThemeHashTable[key];
239
+ if (key.startsWith(`${resourcePath}-`)) {
240
+ const varName = key.slice(resourcePath.length + 1);
241
+ mergedCreateThemeHashTable[varName] =
242
+ scannedTables.createThemeHashTable[key];
249
243
  }
250
244
  }
251
- };
252
- const registerStyle = (node, declSpan, isExported) => {
253
- let propName;
254
- const init = node.init;
255
- if (utils_1.t.isIdentifier(node.id) &&
256
- init &&
257
- utils_1.t.isCallExpression(init) &&
258
- init.arguments.length >= 1) {
259
- const callee = init.callee;
260
- if (utils_1.t.isMemberExpression(callee) &&
261
- utils_1.t.isIdentifier(callee.object) &&
262
- utils_1.t.isIdentifier(callee.property)) {
263
- const objectName = callee.object.value;
264
- const propertyName = callee.property.value;
265
- const alias = plumeriaAliases[objectName];
266
- if (alias === 'NAMESPACE') {
267
- propName = propertyName;
245
+ for (const key of Object.keys(createThemeImportMap)) {
246
+ mergedCreateThemeHashTable[key] = createThemeImportMap[key];
247
+ }
248
+ const mergedCreateStaticHashTable = {};
249
+ for (const key of Object.keys(scannedTables.createStaticHashTable)) {
250
+ mergedCreateStaticHashTable[key] =
251
+ scannedTables.createStaticHashTable[key];
252
+ if (key.startsWith(`${resourcePath}-`)) {
253
+ const varName = key.slice(resourcePath.length + 1);
254
+ mergedCreateStaticHashTable[varName] =
255
+ scannedTables.createStaticHashTable[key];
256
+ }
257
+ }
258
+ for (const key of Object.keys(createStaticImportMap)) {
259
+ mergedCreateStaticHashTable[key] = createStaticImportMap[key];
260
+ }
261
+ const localCreateStyles = {};
262
+ const replacements = [];
263
+ const processedDecls = new Set();
264
+ const idSpans = new Set();
265
+ const excludedSpans = new Set();
266
+ const checkVariantAssignment = (decl) => {
267
+ const init = decl.init;
268
+ if (init && utils_1.t.isCallExpression(init) && utils_1.t.isIdentifier(init.callee)) {
269
+ const varName = init.callee.value;
270
+ if ((localCreateStyles[varName] &&
271
+ localCreateStyles[varName].type === 'variant') ||
272
+ mergedVariantsTable[varName]) {
273
+ throw new Error(`Plumeria: Assigning the return value of "css.variants" to a variable is not supported.\nPlease pass the variant function directly to "css.use". Found assignment to: ${utils_1.t.isIdentifier(decl.id) ? decl.id.value : 'unknown'}`);
268
274
  }
269
275
  }
270
- else if (utils_1.t.isIdentifier(callee)) {
271
- const calleeName = callee.value;
272
- const originalName = plumeriaAliases[calleeName];
273
- if (originalName) {
274
- propName = originalName;
276
+ };
277
+ const registerStyle = (node, declSpan, isExported) => {
278
+ let propName;
279
+ const init = node.init;
280
+ if (utils_1.t.isIdentifier(node.id) &&
281
+ init &&
282
+ utils_1.t.isCallExpression(init) &&
283
+ init.arguments.length >= 1) {
284
+ const callee = init.callee;
285
+ if (utils_1.t.isMemberExpression(callee) &&
286
+ utils_1.t.isIdentifier(callee.object) &&
287
+ utils_1.t.isIdentifier(callee.property)) {
288
+ const objectName = callee.object.value;
289
+ const propertyName = callee.property.value;
290
+ const alias = plumeriaAliases[objectName];
291
+ if (alias === 'NAMESPACE') {
292
+ propName = propertyName;
293
+ }
294
+ }
295
+ else if (utils_1.t.isIdentifier(callee)) {
296
+ const calleeName = callee.value;
297
+ const originalName = plumeriaAliases[calleeName];
298
+ if (originalName) {
299
+ propName = originalName;
300
+ }
275
301
  }
276
302
  }
277
- }
278
- if (propName && init && utils_1.t.isCallExpression(init)) {
279
- if (propName === 'create' &&
280
- utils_1.t.isObjectExpression(init.arguments[0].expression)) {
281
- const obj = (0, utils_1.objectExpressionToObject)(init.arguments[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
282
- if (obj) {
283
- const hashMap = {};
284
- Object.entries(obj).forEach(([key, style]) => {
285
- if (typeof style !== 'object' || style === null)
286
- return;
287
- const records = (0, utils_1.getStyleRecords)(style);
288
- const atomMap = {};
289
- records.forEach((r) => (atomMap[r.key] = r.hash));
290
- hashMap[key] = atomMap;
291
- });
292
- const styleFunctions = {};
293
- const objExpr = init.arguments[0].expression;
294
- objExpr.properties.forEach((prop) => {
295
- if (prop.type !== 'KeyValueProperty' ||
296
- prop.key.type !== 'Identifier')
297
- return;
298
- const func = prop.value;
299
- if (func.type !== 'ArrowFunctionExpression' &&
300
- func.type !== 'FunctionExpression')
301
- return;
302
- const params = func.params.map((p) => {
303
- if (utils_1.t.isIdentifier(p))
304
- return p.value;
305
- if (typeof p === 'object' &&
306
- p !== null &&
307
- 'pat' in p &&
308
- utils_1.t.isIdentifier(p.pat))
309
- return p.pat.value;
310
- return 'arg';
303
+ if (propName && init && utils_1.t.isCallExpression(init)) {
304
+ if (propName === 'create' &&
305
+ utils_1.t.isObjectExpression(init.arguments[0].expression)) {
306
+ const obj = (0, utils_1.objectExpressionToObject)(init.arguments[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
307
+ if (obj) {
308
+ const hashMap = {};
309
+ Object.entries(obj).forEach(([key, style]) => {
310
+ if (typeof style !== 'object' || style === null)
311
+ return;
312
+ const records = (0, utils_1.getStyleRecords)(style);
313
+ const atomMap = {};
314
+ records.forEach((r) => (atomMap[r.key] = r.hash));
315
+ hashMap[key] = atomMap;
311
316
  });
312
- let actualBody = func.body;
313
- if (actualBody?.type === 'ParenthesisExpression')
314
- actualBody = actualBody.expression;
315
- if (actualBody?.type === 'BlockStatement') {
316
- const first = actualBody.stmts?.[0];
317
- if (first?.type === 'ReturnStatement')
318
- actualBody = first.argument;
317
+ const styleFunctions = {};
318
+ const objExpr = init.arguments[0].expression;
319
+ objExpr.properties.forEach((prop) => {
320
+ if (prop.type !== 'KeyValueProperty' ||
321
+ prop.key.type !== 'Identifier')
322
+ return;
323
+ const func = prop.value;
324
+ if (func.type !== 'ArrowFunctionExpression' &&
325
+ func.type !== 'FunctionExpression')
326
+ return;
327
+ const params = func.params.map((p) => {
328
+ if (utils_1.t.isIdentifier(p))
329
+ return p.value;
330
+ if (typeof p === 'object' &&
331
+ p !== null &&
332
+ 'pat' in p &&
333
+ utils_1.t.isIdentifier(p.pat))
334
+ return p.pat.value;
335
+ return 'arg';
336
+ });
337
+ let actualBody = func.body;
319
338
  if (actualBody?.type === 'ParenthesisExpression')
320
339
  actualBody = actualBody.expression;
340
+ if (actualBody?.type === 'BlockStatement') {
341
+ const first = actualBody.stmts?.[0];
342
+ if (first?.type === 'ReturnStatement')
343
+ actualBody = first.argument;
344
+ if (actualBody?.type === 'ParenthesisExpression')
345
+ actualBody = actualBody.expression;
346
+ }
347
+ if (actualBody && actualBody.type === 'ObjectExpression') {
348
+ styleFunctions[prop.key.value] = {
349
+ params,
350
+ body: actualBody,
351
+ };
352
+ }
353
+ });
354
+ if (utils_1.t.isIdentifier(node.id)) {
355
+ idSpans.add(node.id.span.start);
321
356
  }
322
- if (actualBody && actualBody.type === 'ObjectExpression') {
323
- styleFunctions[prop.key.value] = {
324
- params,
325
- body: actualBody,
357
+ if (utils_1.t.isIdentifier(node.id)) {
358
+ localCreateStyles[node.id.value] = {
359
+ name: node.id.value,
360
+ type: 'create',
361
+ obj,
362
+ hashMap,
363
+ isExported,
364
+ initSpan: {
365
+ start: init.span.start - baseByteOffset,
366
+ end: init.span.end - baseByteOffset,
367
+ },
368
+ declSpan: {
369
+ start: declSpan.start - baseByteOffset,
370
+ end: declSpan.end - baseByteOffset,
371
+ },
372
+ functions: styleFunctions,
326
373
  };
327
374
  }
328
- });
375
+ }
376
+ }
377
+ else if (propName === 'variants' &&
378
+ utils_1.t.isObjectExpression(init.arguments[0].expression)) {
329
379
  if (utils_1.t.isIdentifier(node.id)) {
330
380
  idSpans.add(node.id.span.start);
331
381
  }
382
+ const obj = (0, utils_1.objectExpressionToObject)(init.arguments[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable, (name) => {
383
+ if (localCreateStyles[name]) {
384
+ return localCreateStyles[name].obj;
385
+ }
386
+ if (mergedCreateTable[name]) {
387
+ const hash = mergedCreateTable[name];
388
+ if (scannedTables.createObjectTable[hash]) {
389
+ return scannedTables.createObjectTable[hash];
390
+ }
391
+ }
392
+ return undefined;
393
+ });
394
+ const { hashMap } = (0, utils_1.processVariants)(obj);
332
395
  if (utils_1.t.isIdentifier(node.id)) {
333
396
  localCreateStyles[node.id.value] = {
334
397
  name: node.id.value,
335
- type: 'create',
398
+ type: 'variant',
336
399
  obj,
337
400
  hashMap,
338
401
  isExported,
@@ -344,719 +407,784 @@ async function loader(source) {
344
407
  start: declSpan.start - baseByteOffset,
345
408
  end: declSpan.end - baseByteOffset,
346
409
  },
347
- functions: styleFunctions,
348
410
  };
349
411
  }
350
412
  }
351
- }
352
- else if (propName === 'variants' &&
353
- utils_1.t.isObjectExpression(init.arguments[0].expression)) {
354
- if (utils_1.t.isIdentifier(node.id)) {
355
- idSpans.add(node.id.span.start);
356
- }
357
- const obj = (0, utils_1.objectExpressionToObject)(init.arguments[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable, (name) => {
358
- if (localCreateStyles[name]) {
359
- return localCreateStyles[name].obj;
413
+ else if (propName === 'createTheme' &&
414
+ init.arguments.length >= 2 &&
415
+ utils_1.t.isObjectExpression(init.arguments[1].expression)) {
416
+ if (utils_1.t.isIdentifier(node.id)) {
417
+ idSpans.add(node.id.span.start);
418
+ }
419
+ let selector = '';
420
+ const selectorExpr = init.arguments[0].expression;
421
+ if (utils_1.t.isStringLiteral(selectorExpr)) {
422
+ selector = selectorExpr.value;
423
+ }
424
+ if (selector.startsWith('@') && !(0, zss_engine_1.isAtRule)(selector)) {
425
+ throw new Error(`Plumeria: Unsupported at-rule: "${selector}". createTheme only supports nesting at-rules such as @media, @container, @supports, @layer, and @scope.`);
360
426
  }
361
- if (mergedCreateTable[name]) {
362
- const hash = mergedCreateTable[name];
363
- if (scannedTables.createObjectTable[hash]) {
364
- return scannedTables.createObjectTable[hash];
427
+ const obj = (0, utils_1.objectExpressionToObject)(init.arguments[1].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
428
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
429
+ if (utils_1.t.isIdentifier(node.id)) {
430
+ const uniqueKey = `${resourcePath}-${node.id.value}`;
431
+ scannedTables.createThemeHashTable[uniqueKey] = hash;
432
+ scannedTables.createThemeObjectTable[hash] = obj;
433
+ if (scannedTables.createThemeSelectorTable) {
434
+ scannedTables.createThemeSelectorTable[hash] = selector;
435
+ }
436
+ mergedCreateThemeHashTable[node.id.value] = hash;
437
+ const themeHashMap = {};
438
+ for (const [key, value] of Object.entries(obj)) {
439
+ const cssVarName = (0, zss_engine_1.camelToKebabCase)(key);
440
+ const atomicHash = (0, zss_engine_1.genBase36Hash)({ [key]: value }, 1, 8);
441
+ themeHashMap[key] = `var(--${atomicHash}-${cssVarName})`;
365
442
  }
443
+ localCreateStyles[node.id.value] = {
444
+ name: node.id.value,
445
+ type: 'constant',
446
+ obj,
447
+ hashMap: themeHashMap,
448
+ isExported,
449
+ initSpan: {
450
+ start: init.span.start - baseByteOffset,
451
+ end: init.span.end - baseByteOffset,
452
+ },
453
+ declSpan: {
454
+ start: declSpan.start - baseByteOffset,
455
+ end: declSpan.end - baseByteOffset,
456
+ },
457
+ };
366
458
  }
367
- return undefined;
368
- });
369
- const { hashMap } = (0, utils_1.processVariants)(obj);
370
- if (utils_1.t.isIdentifier(node.id)) {
371
- localCreateStyles[node.id.value] = {
372
- name: node.id.value,
373
- type: 'variant',
374
- obj,
375
- hashMap,
376
- isExported,
377
- initSpan: {
378
- start: init.span.start - baseByteOffset,
379
- end: init.span.end - baseByteOffset,
380
- },
381
- declSpan: {
382
- start: declSpan.start - baseByteOffset,
383
- end: declSpan.end - baseByteOffset,
384
- },
385
- };
386
- }
387
- }
388
- else if (propName === 'createTheme' &&
389
- utils_1.t.isObjectExpression(init.arguments[0].expression)) {
390
- if (utils_1.t.isIdentifier(node.id)) {
391
- idSpans.add(node.id.span.start);
392
459
  }
393
- const obj = (0, utils_1.objectExpressionToObject)(init.arguments[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
394
- const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
395
- if (utils_1.t.isIdentifier(node.id)) {
396
- const uniqueKey = `${resourcePath}-${node.id.value}`;
397
- scannedTables.createThemeHashTable[uniqueKey] = hash;
398
- scannedTables.createThemeObjectTable[hash] = obj;
399
- mergedCreateThemeHashTable[node.id.value] = hash;
400
- const themeHashMap = {};
401
- for (const [key] of Object.entries(obj)) {
402
- const cssVarName = (0, zss_engine_1.camelToKebabCase)(key);
403
- themeHashMap[key] = `var(--${hash}-${cssVarName})`;
460
+ else if (propName === 'createStatic' &&
461
+ utils_1.t.isObjectExpression(init.arguments[0].expression)) {
462
+ if (utils_1.t.isIdentifier(node.id)) {
463
+ idSpans.add(node.id.span.start);
464
+ }
465
+ const obj = (0, utils_1.objectExpressionToObject)(init.arguments[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
466
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
467
+ if (utils_1.t.isIdentifier(node.id)) {
468
+ const uniqueKey = `${resourcePath}-${node.id.value}`;
469
+ scannedTables.createStaticHashTable[uniqueKey] = hash;
470
+ scannedTables.createStaticObjectTable[hash] = obj;
471
+ mergedCreateStaticHashTable[node.id.value] = hash;
472
+ localCreateStyles[node.id.value] = {
473
+ name: node.id.value,
474
+ type: 'constant',
475
+ obj,
476
+ hashMap: obj,
477
+ isExported,
478
+ initSpan: {
479
+ start: init.span.start - baseByteOffset,
480
+ end: init.span.end - baseByteOffset,
481
+ },
482
+ declSpan: {
483
+ start: declSpan.start - baseByteOffset,
484
+ end: declSpan.end - baseByteOffset,
485
+ },
486
+ };
404
487
  }
405
- localCreateStyles[node.id.value] = {
406
- name: node.id.value,
407
- type: 'constant',
408
- obj,
409
- hashMap: themeHashMap,
410
- isExported,
411
- initSpan: {
412
- start: init.span.start - baseByteOffset,
413
- end: init.span.end - baseByteOffset,
414
- },
415
- declSpan: {
416
- start: declSpan.start - baseByteOffset,
417
- end: declSpan.end - baseByteOffset,
418
- },
419
- };
420
- }
421
- }
422
- else if (propName === 'createStatic' &&
423
- utils_1.t.isObjectExpression(init.arguments[0].expression)) {
424
- if (utils_1.t.isIdentifier(node.id)) {
425
- idSpans.add(node.id.span.start);
426
- }
427
- const obj = (0, utils_1.objectExpressionToObject)(init.arguments[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
428
- const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
429
- if (utils_1.t.isIdentifier(node.id)) {
430
- const uniqueKey = `${resourcePath}-${node.id.value}`;
431
- scannedTables.createStaticHashTable[uniqueKey] = hash;
432
- scannedTables.createStaticObjectTable[hash] = obj;
433
- mergedCreateStaticHashTable[node.id.value] = hash;
434
- localCreateStyles[node.id.value] = {
435
- name: node.id.value,
436
- type: 'constant',
437
- obj,
438
- hashMap: obj,
439
- isExported,
440
- initSpan: {
441
- start: init.span.start - baseByteOffset,
442
- end: init.span.end - baseByteOffset,
443
- },
444
- declSpan: {
445
- start: declSpan.start - baseByteOffset,
446
- end: declSpan.end - baseByteOffset,
447
- },
448
- };
449
488
  }
450
489
  }
451
- }
452
- };
453
- (0, utils_1.traverse)(ast, {
454
- ImportDeclaration({ node }) {
455
- if (node.source.value === '@plumeria/core') {
456
- if (node.typeOnly)
457
- return;
458
- const typeOnlySpecs = node.specifiers.filter((s) => s.type === 'ImportSpecifier' && s.isTypeOnly);
459
- if (typeOnlySpecs.length > 0) {
460
- const names = typeOnlySpecs
461
- .map((s) => {
462
- if (s.type !== 'ImportSpecifier')
463
- return;
464
- const imported = s.imported ? s.imported.value : s.local.value;
465
- const local = s.local.value;
466
- return imported === local ? imported : `${imported} as ${local}`;
467
- })
468
- .join(', ');
469
- replacements.push({
470
- start: node.span.start - baseByteOffset,
471
- end: node.span.end - baseByteOffset,
472
- content: `import type { ${names} } from '@plumeria/core'`,
473
- });
490
+ };
491
+ (0, utils_1.traverse)(ast, {
492
+ ImportDeclaration({ node }) {
493
+ if (node.source.value === '@plumeria/core') {
494
+ if (node.typeOnly)
495
+ return;
496
+ const typeOnlySpecs = node.specifiers.filter((s) => s.type === 'ImportSpecifier' && s.isTypeOnly);
497
+ if (typeOnlySpecs.length > 0) {
498
+ const names = typeOnlySpecs
499
+ .map((s) => {
500
+ if (s.type !== 'ImportSpecifier')
501
+ return;
502
+ const imported = s.imported ? s.imported.value : s.local.value;
503
+ const local = s.local.value;
504
+ return imported === local
505
+ ? imported
506
+ : `${imported} as ${local}`;
507
+ })
508
+ .join(', ');
509
+ replacements.push({
510
+ start: node.span.start - baseByteOffset,
511
+ end: node.span.end - baseByteOffset,
512
+ content: `import type { ${names} } from '@plumeria/core'`,
513
+ });
514
+ }
515
+ else {
516
+ replacements.push({
517
+ start: node.span.start - baseByteOffset,
518
+ end: node.span.end - baseByteOffset,
519
+ content: '',
520
+ });
521
+ }
474
522
  }
475
- else {
476
- replacements.push({
477
- start: node.span.start - baseByteOffset,
478
- end: node.span.end - baseByteOffset,
479
- content: '',
523
+ node.specifiers.forEach((specifier) => {
524
+ if (specifier.local) {
525
+ excludedSpans.add(specifier.local.span.start);
526
+ }
527
+ if (specifier.type === 'ImportSpecifier' && specifier.imported) {
528
+ excludedSpans.add(specifier.imported.span.start);
529
+ }
530
+ });
531
+ },
532
+ ExportDeclaration({ node }) {
533
+ if (utils_1.t.isVariableDeclaration(node.declaration)) {
534
+ processedDecls.add(node.declaration);
535
+ node.declaration.declarations.forEach((decl) => {
536
+ checkVariantAssignment(decl);
537
+ registerStyle(decl, node.span, true);
480
538
  });
481
539
  }
482
- }
483
- node.specifiers.forEach((specifier) => {
484
- if (specifier.local) {
485
- excludedSpans.add(specifier.local.span.start);
486
- }
487
- if (specifier.type === 'ImportSpecifier' && specifier.imported) {
488
- excludedSpans.add(specifier.imported.span.start);
489
- }
490
- });
491
- },
492
- ExportDeclaration({ node }) {
493
- if (utils_1.t.isVariableDeclaration(node.declaration)) {
494
- processedDecls.add(node.declaration);
495
- node.declaration.declarations.forEach((decl) => {
540
+ },
541
+ VariableDeclaration({ node }) {
542
+ if (processedDecls.has(node))
543
+ return;
544
+ node.declarations.forEach((decl) => {
496
545
  checkVariantAssignment(decl);
497
- registerStyle(decl, node.span, true);
546
+ registerStyle(decl, node.span, false);
498
547
  });
499
- }
500
- },
501
- VariableDeclaration({ node }) {
502
- if (processedDecls.has(node))
503
- return;
504
- node.declarations.forEach((decl) => {
505
- checkVariantAssignment(decl);
506
- registerStyle(decl, node.span, false);
507
- });
508
- },
509
- CallExpression({ node }) {
510
- const callee = node.callee;
511
- let propName;
512
- if (utils_1.t.isMemberExpression(callee) &&
513
- utils_1.t.isIdentifier(callee.object) &&
514
- utils_1.t.isIdentifier(callee.property)) {
515
- const objectName = callee.object.value;
516
- const propertyName = callee.property.value;
517
- const alias = plumeriaAliases[objectName];
518
- if (alias === 'NAMESPACE') {
519
- propName = propertyName;
548
+ },
549
+ CallExpression({ node }) {
550
+ const callee = node.callee;
551
+ let propName;
552
+ if (utils_1.t.isMemberExpression(callee) &&
553
+ utils_1.t.isIdentifier(callee.object) &&
554
+ utils_1.t.isIdentifier(callee.property)) {
555
+ const objectName = callee.object.value;
556
+ const propertyName = callee.property.value;
557
+ const alias = plumeriaAliases[objectName];
558
+ if (alias === 'NAMESPACE') {
559
+ propName = propertyName;
560
+ }
520
561
  }
521
- }
522
- else if (utils_1.t.isIdentifier(callee)) {
523
- const calleeName = callee.value;
524
- const originalName = plumeriaAliases[calleeName];
525
- if (originalName) {
526
- propName = originalName;
562
+ else if (utils_1.t.isIdentifier(callee)) {
563
+ const calleeName = callee.value;
564
+ const originalName = plumeriaAliases[calleeName];
565
+ if (originalName) {
566
+ propName = originalName;
567
+ }
527
568
  }
528
- }
529
- if (propName) {
530
- const args = node.arguments;
531
- if (propName === 'keyframes') {
532
- const expr = args[0].expression;
533
- if (utils_1.t.isObjectExpression(expr)) {
534
- const obj = (0, utils_1.objectExpressionToObject)(expr, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
569
+ if (propName) {
570
+ const args = node.arguments;
571
+ if (propName === 'keyframes') {
572
+ const expr = args[0].expression;
573
+ if (utils_1.t.isObjectExpression(expr)) {
574
+ const obj = (0, utils_1.objectExpressionToObject)(expr, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
575
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
576
+ scannedTables.keyframesObjectTable[hash] = obj;
577
+ replacements.push({
578
+ start: node.span.start - baseByteOffset,
579
+ end: node.span.end - baseByteOffset,
580
+ content: JSON.stringify(`kf-${hash}`),
581
+ });
582
+ }
583
+ }
584
+ else if (propName === 'viewTransition' &&
585
+ args.length > 0 &&
586
+ utils_1.t.isObjectExpression(args[0].expression)) {
587
+ const obj = (0, utils_1.objectExpressionToObject)(args[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
535
588
  const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
536
- scannedTables.keyframesObjectTable[hash] = obj;
589
+ scannedTables.viewTransitionObjectTable[hash] = obj;
537
590
  replacements.push({
538
591
  start: node.span.start - baseByteOffset,
539
592
  end: node.span.end - baseByteOffset,
540
- content: JSON.stringify(`kf-${hash}`),
593
+ content: JSON.stringify(`vt-${hash}`),
541
594
  });
542
595
  }
543
- }
544
- else if (propName === 'viewTransition' &&
545
- args.length > 0 &&
546
- utils_1.t.isObjectExpression(args[0].expression)) {
547
- const obj = (0, utils_1.objectExpressionToObject)(args[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
548
- const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
549
- scannedTables.viewTransitionObjectTable[hash] = obj;
550
- replacements.push({
551
- start: node.span.start - baseByteOffset,
552
- end: node.span.end - baseByteOffset,
553
- content: JSON.stringify(`vt-${hash}`),
554
- });
555
- }
556
- else if ((propName === 'createTheme' || propName === 'createStatic') &&
557
- args.length > 0 &&
558
- utils_1.t.isObjectExpression(args[0].expression)) {
559
- const obj = (0, utils_1.objectExpressionToObject)(args[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
560
- const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
561
- if (propName === 'createTheme') {
596
+ else if (propName === 'createTheme' &&
597
+ args.length >= 2 &&
598
+ utils_1.t.isObjectExpression(args[1].expression)) {
599
+ let selector = '';
600
+ const selectorExpr = args[0].expression;
601
+ if (utils_1.t.isStringLiteral(selectorExpr)) {
602
+ selector = selectorExpr.value;
603
+ }
604
+ if (selector.startsWith('@') && !(0, zss_engine_1.isAtRule)(selector)) {
605
+ throw new Error(`Plumeria: Unsupported at-rule: "${selector}". createTheme only supports nesting at-rules such as @media, @container, @supports, @layer, and @scope.`);
606
+ }
607
+ const obj = (0, utils_1.objectExpressionToObject)(args[1].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
608
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
562
609
  scannedTables.createThemeObjectTable[hash] = obj;
610
+ if (scannedTables.createThemeSelectorTable) {
611
+ scannedTables.createThemeSelectorTable[hash] = selector;
612
+ }
563
613
  }
564
- else {
614
+ else if (propName === 'createStatic' &&
615
+ args.length > 0 &&
616
+ utils_1.t.isObjectExpression(args[0].expression)) {
617
+ const obj = (0, utils_1.objectExpressionToObject)(args[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
618
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
565
619
  scannedTables.createStaticObjectTable[hash] = obj;
566
620
  }
621
+ else if (propName === 'create' &&
622
+ args.length > 0 &&
623
+ utils_1.t.isObjectExpression(args[0].expression)) {
624
+ const obj = (0, utils_1.objectExpressionToObject)(args[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
625
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
626
+ scannedTables.createObjectTable[hash] = obj;
627
+ }
567
628
  }
568
- else if (propName === 'create' &&
569
- args.length > 0 &&
570
- utils_1.t.isObjectExpression(args[0].expression)) {
571
- const obj = (0, utils_1.objectExpressionToObject)(args[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
572
- const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
573
- scannedTables.createObjectTable[hash] = obj;
574
- }
575
- }
576
- },
577
- });
578
- const jsxOpeningElementMap = new Map();
579
- const getSource = (node) => {
580
- const start = node.span.start - baseByteOffset;
581
- const end = node.span.end - baseByteOffset;
582
- return sourceBuffer.subarray(start, end).toString('utf-8');
583
- };
584
- const resolveStyleObject = (expr) => {
585
- if (utils_1.t.isObjectExpression(expr)) {
586
- return (0, utils_1.objectExpressionToObject)(expr, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
587
- }
588
- else if (utils_1.t.isMemberExpression(expr) &&
589
- utils_1.t.isIdentifier(expr.object) &&
590
- (utils_1.t.isIdentifier(expr.property) || expr.property.type === 'Computed')) {
591
- if (expr.property.type === 'Computed')
592
- return {};
593
- const varName = expr.object.value;
594
- const propName = expr.property.value;
595
- const styleInfo = localCreateStyles[varName];
596
- if (styleInfo?.obj[propName]) {
597
- const style = styleInfo.obj[propName];
598
- if (typeof style === 'object' && style !== null)
599
- return style;
600
- }
601
- const hash = mergedCreateTable[varName];
602
- if (hash) {
603
- const obj = scannedTables.createObjectTable[hash];
604
- if (obj?.[propName] && typeof obj[propName] === 'object')
605
- return obj[propName];
606
- }
607
- }
608
- else if (utils_1.t.isIdentifier(expr)) {
609
- const varName = expr.value;
610
- const uniqueKey = `${resourcePath}-${varName}`;
611
- let hash = scannedTables.createHashTable[uniqueKey];
612
- if (!hash)
613
- hash = mergedCreateTable[varName];
614
- if (hash) {
615
- const obj = scannedTables.createObjectTable[hash];
616
- if (obj && typeof obj === 'object')
617
- return obj;
629
+ },
630
+ });
631
+ const jsxOpeningElementMap = new Map();
632
+ const getSource = (node) => {
633
+ const start = node.span.start - baseByteOffset;
634
+ const end = node.span.end - baseByteOffset;
635
+ return sourceBuffer.subarray(start, end).toString('utf-8');
636
+ };
637
+ const resolveStyleObject = (expr) => {
638
+ if (utils_1.t.isObjectExpression(expr)) {
639
+ return (0, utils_1.objectExpressionToObject)(expr, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
618
640
  }
619
- const styleInfo = localCreateStyles[varName];
620
- if (styleInfo?.obj)
621
- return styleInfo.obj;
622
- const vHash = mergedVariantsTable[varName];
623
- if (vHash)
624
- return scannedTables.variantsObjectTable[vHash];
625
- }
626
- return null;
627
- };
628
- const buildClassParts = (args, dynamicClassParts = [], existingClass = '') => {
629
- const conditionals = [];
630
- let groupIdCounter = 0;
631
- let baseStyle = {};
632
- let isOptimizable = true;
633
- const collectConditions = (node, currentTestStrings = []) => {
634
- const staticStyle = resolveStyleObject(node);
635
- if (staticStyle) {
636
- if (currentTestStrings.length === 0) {
637
- baseStyle = (0, utils_1.deepMerge)(baseStyle, staticStyle);
641
+ else if (utils_1.t.isMemberExpression(expr) &&
642
+ utils_1.t.isIdentifier(expr.object) &&
643
+ (utils_1.t.isIdentifier(expr.property) || expr.property.type === 'Computed')) {
644
+ if (expr.property.type === 'Computed')
645
+ return {};
646
+ const varName = expr.object.value;
647
+ const propName = expr.property.value;
648
+ const styleInfo = localCreateStyles[varName];
649
+ if (styleInfo?.obj[propName]) {
650
+ const style = styleInfo.obj[propName];
651
+ if (typeof style === 'object' && style !== null)
652
+ return style;
638
653
  }
639
- else {
640
- conditionals.push({
641
- test: node,
642
- testString: currentTestStrings.join(' && '),
643
- truthy: staticStyle,
644
- falsy: {},
645
- varName: undefined,
646
- });
654
+ const hash = mergedCreateTable[varName];
655
+ if (hash) {
656
+ const obj = scannedTables.createObjectTable[hash];
657
+ if (obj?.[propName] && typeof obj[propName] === 'object')
658
+ return obj[propName];
647
659
  }
648
- return true;
649
660
  }
650
- if (node.type === 'ConditionalExpression') {
651
- const testSource = getSource(node.test);
652
- if (currentTestStrings.length === 0) {
653
- const trueStyle = resolveStyleObject(node.consequent);
654
- const falseStyle = resolveStyleObject(node.alternate);
655
- if (trueStyle && falseStyle) {
661
+ else if (utils_1.t.isIdentifier(expr)) {
662
+ const varName = expr.value;
663
+ const uniqueKey = `${resourcePath}-${varName}`;
664
+ let hash = scannedTables.createHashTable[uniqueKey];
665
+ if (!hash)
666
+ hash = mergedCreateTable[varName];
667
+ if (hash) {
668
+ const obj = scannedTables.createObjectTable[hash];
669
+ if (obj && typeof obj === 'object')
670
+ return obj;
671
+ }
672
+ const styleInfo = localCreateStyles[varName];
673
+ if (styleInfo?.obj)
674
+ return styleInfo.obj;
675
+ const vHash = mergedVariantsTable[varName];
676
+ if (vHash)
677
+ return scannedTables.variantsObjectTable[vHash];
678
+ }
679
+ return null;
680
+ };
681
+ const buildClassParts = (args, dynamicClassParts = [], existingClass = '') => {
682
+ const conditionals = [];
683
+ let groupIdCounter = 0;
684
+ let baseStyle = {};
685
+ let isOptimizable = true;
686
+ const collectConditions = (node, currentTestStrings = []) => {
687
+ const staticStyle = resolveStyleObject(node);
688
+ if (staticStyle) {
689
+ if (currentTestStrings.length === 0) {
690
+ baseStyle = (0, utils_1.deepMerge)(baseStyle, staticStyle);
691
+ }
692
+ else {
656
693
  conditionals.push({
657
694
  test: node,
658
- testString: testSource,
659
- truthy: trueStyle,
660
- falsy: falseStyle,
695
+ testString: currentTestStrings.join(' && '),
696
+ truthy: staticStyle,
697
+ falsy: {},
661
698
  varName: undefined,
662
699
  });
663
- return true;
664
700
  }
701
+ return true;
665
702
  }
666
- collectConditions(node.consequent, [
667
- ...currentTestStrings,
668
- `(${testSource})`,
669
- ]);
670
- collectConditions(node.alternate, [
671
- ...currentTestStrings,
672
- `!(${testSource})`,
673
- ]);
674
- return true;
675
- }
676
- else if (node.type === 'BinaryExpression' && node.operator === '&&') {
677
- collectConditions(node.right, [
678
- ...currentTestStrings,
679
- `(${getSource(node.left)})`,
680
- ]);
681
- return true;
682
- }
683
- else if (node.type === 'ParenthesisExpression') {
684
- return collectConditions(node.expression, currentTestStrings);
685
- }
686
- return false;
687
- };
688
- for (const arg of args) {
689
- const expr = arg.expression;
690
- if (utils_1.t.isCallExpression(expr) && utils_1.t.isIdentifier(expr.callee)) {
691
- const varName = expr.callee.value;
692
- const uniqueKey = `${resourcePath}-${varName}`;
693
- let variantObj;
694
- let hash = scannedTables.variantsHashTable[uniqueKey];
695
- if (!hash)
696
- hash = mergedVariantsTable[varName];
697
- if (hash && scannedTables.variantsObjectTable[hash])
698
- variantObj = scannedTables.variantsObjectTable[hash];
699
- if (!variantObj && localCreateStyles[varName]?.obj)
700
- variantObj = localCreateStyles[varName].obj;
701
- if (variantObj) {
702
- const callArgs = expr.arguments;
703
- if (callArgs.length === 1 && !callArgs[0].spread) {
704
- const arg = callArgs[0].expression;
705
- if (arg.type === 'ObjectExpression') {
706
- for (const prop of arg.properties) {
707
- let groupName;
708
- let valExpr;
709
- if (prop.type === 'KeyValueProperty' &&
710
- prop.key.type === 'Identifier') {
711
- groupName = prop.key.value;
712
- valExpr = prop.value;
713
- }
714
- else if (prop.type === 'Identifier') {
715
- groupName = prop.value;
716
- valExpr = prop;
717
- }
718
- if (groupName && valExpr) {
719
- const groupVariants = variantObj[groupName];
720
- if (!groupVariants)
721
- continue;
722
- const currentGroupId = ++groupIdCounter;
723
- const valSource = getSource(valExpr);
724
- if (valExpr.type === 'StringLiteral') {
725
- const groupVariantsAsObj = groupVariants;
726
- if (groupVariantsAsObj[valExpr.value])
727
- baseStyle = (0, utils_1.deepMerge)(baseStyle, groupVariantsAsObj[valExpr.value]);
728
- continue;
703
+ if (node.type === 'ConditionalExpression') {
704
+ const testSource = getSource(node.test);
705
+ if (currentTestStrings.length === 0) {
706
+ const trueStyle = resolveStyleObject(node.consequent);
707
+ const falseStyle = resolveStyleObject(node.alternate);
708
+ if (trueStyle && falseStyle) {
709
+ conditionals.push({
710
+ test: node,
711
+ testString: testSource,
712
+ truthy: trueStyle,
713
+ falsy: falseStyle,
714
+ varName: undefined,
715
+ });
716
+ return true;
717
+ }
718
+ }
719
+ collectConditions(node.consequent, [
720
+ ...currentTestStrings,
721
+ `(${testSource})`,
722
+ ]);
723
+ collectConditions(node.alternate, [
724
+ ...currentTestStrings,
725
+ `!(${testSource})`,
726
+ ]);
727
+ return true;
728
+ }
729
+ else if (node.type === 'BinaryExpression' && node.operator === '&&') {
730
+ collectConditions(node.right, [
731
+ ...currentTestStrings,
732
+ `(${getSource(node.left)})`,
733
+ ]);
734
+ return true;
735
+ }
736
+ else if (node.type === 'ParenthesisExpression') {
737
+ return collectConditions(node.expression, currentTestStrings);
738
+ }
739
+ return false;
740
+ };
741
+ for (const arg of args) {
742
+ const expr = arg.expression;
743
+ if (utils_1.t.isCallExpression(expr) && utils_1.t.isIdentifier(expr.callee)) {
744
+ const varName = expr.callee.value;
745
+ const uniqueKey = `${resourcePath}-${varName}`;
746
+ let variantObj;
747
+ let hash = scannedTables.variantsHashTable[uniqueKey];
748
+ if (!hash)
749
+ hash = mergedVariantsTable[varName];
750
+ if (hash && scannedTables.variantsObjectTable[hash])
751
+ variantObj = scannedTables.variantsObjectTable[hash];
752
+ if (!variantObj && localCreateStyles[varName]?.obj)
753
+ variantObj = localCreateStyles[varName].obj;
754
+ if (variantObj) {
755
+ const callArgs = expr.arguments;
756
+ if (callArgs.length === 1 && !callArgs[0].spread) {
757
+ const arg = callArgs[0].expression;
758
+ if (arg.type === 'ObjectExpression') {
759
+ for (const prop of arg.properties) {
760
+ let groupName;
761
+ let valExpr;
762
+ if (prop.type === 'KeyValueProperty' &&
763
+ prop.key.type === 'Identifier') {
764
+ groupName = prop.key.value;
765
+ valExpr = prop.value;
766
+ }
767
+ else if (prop.type === 'Identifier') {
768
+ groupName = prop.value;
769
+ valExpr = prop;
729
770
  }
730
- Object.entries(groupVariants).forEach(([optionName, style]) => {
731
- conditionals.push({
732
- test: valExpr,
733
- testLHS: valSource,
734
- testString: `${valSource} === '${optionName}'`,
735
- truthy: style,
736
- falsy: {},
737
- groupId: currentGroupId,
738
- groupName,
739
- valueName: optionName,
740
- varName,
771
+ if (groupName && valExpr) {
772
+ const groupVariants = variantObj[groupName];
773
+ if (!groupVariants)
774
+ continue;
775
+ const currentGroupId = ++groupIdCounter;
776
+ const valSource = getSource(valExpr);
777
+ if (valExpr.type === 'StringLiteral') {
778
+ const groupVariantsAsObj = groupVariants;
779
+ if (groupVariantsAsObj[valExpr.value])
780
+ baseStyle = (0, utils_1.deepMerge)(baseStyle, groupVariantsAsObj[valExpr.value]);
781
+ continue;
782
+ }
783
+ Object.entries(groupVariants).forEach(([optionName, style]) => {
784
+ conditionals.push({
785
+ test: valExpr,
786
+ testLHS: valSource,
787
+ testString: `${valSource} === '${optionName}'`,
788
+ truthy: style,
789
+ falsy: {},
790
+ groupId: currentGroupId,
791
+ groupName,
792
+ valueName: optionName,
793
+ varName,
794
+ });
741
795
  });
742
- });
796
+ }
743
797
  }
798
+ continue;
744
799
  }
800
+ const argSource = getSource(arg);
801
+ if (utils_1.t.isStringLiteral(arg)) {
802
+ if (variantObj[arg.value])
803
+ baseStyle = (0, utils_1.deepMerge)(baseStyle, variantObj[arg.value]);
804
+ continue;
805
+ }
806
+ const currentGroupId = ++groupIdCounter;
807
+ Object.entries(variantObj).forEach(([key, style]) => {
808
+ conditionals.push({
809
+ test: arg,
810
+ testLHS: argSource,
811
+ testString: `${argSource} === '${key}'`,
812
+ truthy: style,
813
+ falsy: {},
814
+ groupId: currentGroupId,
815
+ groupName: undefined,
816
+ valueName: key,
817
+ varName,
818
+ });
819
+ });
745
820
  continue;
746
821
  }
747
- const argSource = getSource(arg);
748
- if (utils_1.t.isStringLiteral(arg)) {
749
- if (variantObj[arg.value])
750
- baseStyle = (0, utils_1.deepMerge)(baseStyle, variantObj[arg.value]);
751
- continue;
752
- }
753
- const currentGroupId = ++groupIdCounter;
754
- Object.entries(variantObj).forEach(([key, style]) => {
755
- conditionals.push({
756
- test: arg,
757
- testLHS: argSource,
758
- testString: `${argSource} === '${key}'`,
759
- truthy: style,
760
- falsy: {},
761
- groupId: currentGroupId,
762
- groupName: undefined,
763
- valueName: key,
764
- varName,
822
+ isOptimizable = false;
823
+ break;
824
+ }
825
+ }
826
+ else if (utils_1.t.isIdentifier(expr)) {
827
+ const varName = expr.value;
828
+ const uniqueKey = `${resourcePath}-${varName}`;
829
+ let variantObj;
830
+ let hash = scannedTables.variantsHashTable[uniqueKey];
831
+ if (!hash)
832
+ hash = mergedVariantsTable[varName];
833
+ if (hash && scannedTables.variantsObjectTable[hash])
834
+ variantObj = scannedTables.variantsObjectTable[hash];
835
+ if (!variantObj && localCreateStyles[varName]?.obj)
836
+ variantObj = localCreateStyles[varName].obj;
837
+ if (variantObj) {
838
+ Object.entries(variantObj).forEach(([groupName, groupVariants]) => {
839
+ if (!groupVariants)
840
+ return;
841
+ const currentGroupId = ++groupIdCounter;
842
+ Object.entries(groupVariants).forEach(([optionName, style]) => {
843
+ conditionals.push({
844
+ test: expr,
845
+ testLHS: `props["${groupName}"]`,
846
+ testString: `props["${groupName}"] === '${optionName}'`,
847
+ truthy: style,
848
+ falsy: {},
849
+ groupId: currentGroupId,
850
+ groupName,
851
+ valueName: optionName,
852
+ varName,
853
+ });
765
854
  });
766
855
  });
767
856
  continue;
768
857
  }
769
- isOptimizable = false;
770
- break;
771
858
  }
772
- }
773
- else if (utils_1.t.isIdentifier(expr)) {
774
- const varName = expr.value;
775
- const uniqueKey = `${resourcePath}-${varName}`;
776
- let variantObj;
777
- let hash = scannedTables.variantsHashTable[uniqueKey];
778
- if (!hash)
779
- hash = mergedVariantsTable[varName];
780
- if (hash && scannedTables.variantsObjectTable[hash])
781
- variantObj = scannedTables.variantsObjectTable[hash];
782
- if (!variantObj && localCreateStyles[varName]?.obj)
783
- variantObj = localCreateStyles[varName].obj;
784
- if (variantObj) {
785
- Object.entries(variantObj).forEach(([groupName, groupVariants]) => {
786
- if (!groupVariants)
787
- return;
788
- const currentGroupId = ++groupIdCounter;
789
- Object.entries(groupVariants).forEach(([optionName, style]) => {
790
- conditionals.push({
791
- test: expr,
792
- testLHS: `props["${groupName}"]`,
793
- testString: `props["${groupName}"] === '${optionName}'`,
794
- truthy: style,
795
- falsy: {},
796
- groupId: currentGroupId,
797
- groupName,
798
- valueName: optionName,
799
- varName,
800
- });
801
- });
802
- });
859
+ const handled = collectConditions(expr);
860
+ if (handled)
803
861
  continue;
804
- }
862
+ isOptimizable = false;
863
+ break;
805
864
  }
806
- const handled = collectConditions(expr);
807
- if (handled)
808
- continue;
809
- isOptimizable = false;
810
- break;
811
- }
812
- if (!isOptimizable ||
813
- (args.length === 0 && Object.keys(baseStyle).length === 0)) {
814
- return { classParts: [...dynamicClassParts], isOptimizable, baseStyle };
815
- }
816
- const participation = {};
817
- const registerParticipation = (style, sourceId) => {
818
- Object.keys(style).forEach((key) => {
819
- if (!participation[key])
820
- participation[key] = new Set();
821
- participation[key].add(sourceId);
822
- });
823
- };
824
- registerParticipation(baseStyle, 'base');
825
- conditionals
826
- .filter((c) => c.groupId === undefined)
827
- .forEach((c, idx) => {
828
- registerParticipation(c.truthy, `std_${idx}`);
829
- registerParticipation(c.falsy, `std_${idx}`);
830
- });
831
- const variantGroups = {};
832
- conditionals.forEach((c) => {
833
- if (c.groupId !== undefined) {
834
- if (!variantGroups[c.groupId])
835
- variantGroups[c.groupId] = [];
836
- variantGroups[c.groupId].push(c);
865
+ if (!isOptimizable ||
866
+ (args.length === 0 && Object.keys(baseStyle).length === 0)) {
867
+ return { classParts: [...dynamicClassParts], isOptimizable, baseStyle };
837
868
  }
838
- });
839
- Object.entries(variantGroups).forEach(([groupId, opts]) => {
840
- opts.forEach((opt) => registerParticipation(opt.truthy, `var_${groupId}`));
841
- });
842
- const conflictingKeys = new Set();
843
- Object.entries(participation).forEach(([key, sources]) => {
844
- if (sources.size > 1)
845
- conflictingKeys.add(key);
846
- });
847
- const baseIndependent = {};
848
- const baseConflict = {};
849
- Object.entries(baseStyle).forEach(([key, val]) => {
850
- if (conflictingKeys.has(key))
851
- baseConflict[key] = val;
852
- else
853
- baseIndependent[key] = val;
854
- });
855
- const indepConditionals = [];
856
- const conflictConditionals = [];
857
- conditionals.forEach((c) => {
858
- const truthyIndep = {};
859
- const truthyConf = {};
860
- const falsyIndep = {};
861
- const falsyConf = {};
862
- let hasIndep = false;
863
- let hasConf = false;
864
- Object.entries(c.truthy).forEach(([k, v]) => {
865
- if (conflictingKeys.has(k)) {
866
- truthyConf[k] = v;
867
- hasConf = true;
868
- }
869
- else {
870
- truthyIndep[k] = v;
871
- hasIndep = true;
872
- }
869
+ const participation = {};
870
+ const registerParticipation = (style, sourceId) => {
871
+ Object.keys(style).forEach((key) => {
872
+ if (!participation[key])
873
+ participation[key] = new Set();
874
+ participation[key].add(sourceId);
875
+ });
876
+ };
877
+ registerParticipation(baseStyle, 'base');
878
+ conditionals
879
+ .filter((c) => c.groupId === undefined)
880
+ .forEach((c, idx) => {
881
+ registerParticipation(c.truthy, `std_${idx}`);
882
+ registerParticipation(c.falsy, `std_${idx}`);
873
883
  });
874
- Object.entries(c.falsy).forEach(([k, v]) => {
875
- if (conflictingKeys.has(k)) {
876
- falsyConf[k] = v;
877
- hasConf = true;
878
- }
879
- else {
880
- falsyIndep[k] = v;
881
- hasIndep = true;
884
+ const variantGroups = {};
885
+ conditionals.forEach((c) => {
886
+ if (c.groupId !== undefined) {
887
+ if (!variantGroups[c.groupId])
888
+ variantGroups[c.groupId] = [];
889
+ variantGroups[c.groupId].push(c);
882
890
  }
883
891
  });
884
- if (hasIndep)
885
- indepConditionals.push({
886
- ...c,
887
- truthy: truthyIndep,
888
- falsy: falsyIndep,
892
+ Object.entries(variantGroups).forEach(([groupId, opts]) => {
893
+ opts.forEach((opt) => registerParticipation(opt.truthy, `var_${groupId}`));
894
+ });
895
+ const conflictingKeys = new Set();
896
+ Object.entries(participation).forEach(([key, sources]) => {
897
+ if (sources.size > 1)
898
+ conflictingKeys.add(key);
899
+ });
900
+ const baseIndependent = {};
901
+ const baseConflict = {};
902
+ Object.entries(baseStyle).forEach(([key, val]) => {
903
+ if (conflictingKeys.has(key))
904
+ baseConflict[key] = val;
905
+ else
906
+ baseIndependent[key] = val;
907
+ });
908
+ const indepConditionals = [];
909
+ const conflictConditionals = [];
910
+ conditionals.forEach((c) => {
911
+ const truthyIndep = {};
912
+ const truthyConf = {};
913
+ const falsyIndep = {};
914
+ const falsyConf = {};
915
+ let hasIndep = false;
916
+ let hasConf = false;
917
+ Object.entries(c.truthy).forEach(([k, v]) => {
918
+ if (conflictingKeys.has(k)) {
919
+ truthyConf[k] = v;
920
+ hasConf = true;
921
+ }
922
+ else {
923
+ truthyIndep[k] = v;
924
+ hasIndep = true;
925
+ }
889
926
  });
890
- if (hasConf)
891
- conflictConditionals.push({
892
- ...c,
893
- truthy: truthyConf,
894
- falsy: falsyConf,
927
+ Object.entries(c.falsy).forEach(([k, v]) => {
928
+ if (conflictingKeys.has(k)) {
929
+ falsyConf[k] = v;
930
+ hasConf = true;
931
+ }
932
+ else {
933
+ falsyIndep[k] = v;
934
+ hasIndep = true;
935
+ }
895
936
  });
896
- });
897
- const classParts = [];
898
- if (existingClass)
899
- classParts.push(JSON.stringify(existingClass));
900
- if (Object.keys(baseIndependent).length > 0) {
901
- const className = processStyleRecords(baseIndependent)
902
- .map((r) => r.hash)
903
- .join(' ');
904
- if (className)
905
- classParts.push(JSON.stringify(className));
906
- }
907
- indepConditionals
908
- .filter((c) => c.groupId === undefined)
909
- .forEach((c) => {
910
- const processBranch = (style) => {
911
- if (Object.keys(style).length === 0)
912
- return '""';
913
- return JSON.stringify(processStyleRecords(style)
914
- .map((r) => r.hash)
915
- .join(' '));
916
- };
917
- const testStr = c.testString ?? getSource(c.test);
918
- classParts.push(`(${testStr} ? ${processBranch(c.truthy)} : ${processBranch(c.falsy)})`);
919
- });
920
- const indepVarGroups = {};
921
- indepConditionals.forEach((c) => {
922
- if (c.groupId !== undefined) {
923
- if (!indepVarGroups[c.groupId])
924
- indepVarGroups[c.groupId] = [];
925
- indepVarGroups[c.groupId].push(c);
926
- }
927
- });
928
- Object.values(indepVarGroups).forEach((options) => {
929
- const commonTestExpr = options[0].testLHS ??
930
- options[0].testString ??
931
- getSource(options[0].test);
932
- const lookupMap = {};
933
- options.forEach((opt) => {
934
- if (opt.valueName && opt.truthy) {
935
- const className = processStyleRecords(opt.truthy)
936
- .map((r) => r.hash)
937
- .join(' ');
938
- if (className)
939
- lookupMap[opt.valueName] = className;
940
- }
937
+ if (hasIndep)
938
+ indepConditionals.push({
939
+ ...c,
940
+ truthy: truthyIndep,
941
+ falsy: falsyIndep,
942
+ });
943
+ if (hasConf)
944
+ conflictConditionals.push({
945
+ ...c,
946
+ truthy: truthyConf,
947
+ falsy: falsyConf,
948
+ });
941
949
  });
942
- if (Object.keys(lookupMap).length > 0) {
943
- const entries = Object.entries(lookupMap)
944
- .map(([k, v]) => `"${k}":"${v}"`)
945
- .join(',');
946
- classParts.push(`({${entries}}[${commonTestExpr}] || "")`);
950
+ const classParts = [];
951
+ if (existingClass)
952
+ classParts.push(JSON.stringify(existingClass));
953
+ if (Object.keys(baseIndependent).length > 0) {
954
+ const className = processStyleRecords(baseIndependent)
955
+ .map((r) => r.hash)
956
+ .join(' ');
957
+ if (className)
958
+ classParts.push(JSON.stringify(className));
947
959
  }
948
- });
949
- if (Object.keys(baseConflict).length > 0 ||
950
- conflictConditionals.length > 0) {
951
- const dimensions = [];
952
- conflictConditionals
960
+ indepConditionals
953
961
  .filter((c) => c.groupId === undefined)
954
962
  .forEach((c) => {
955
- dimensions.push({
956
- type: 'std',
957
- testExpr: c.testString ?? getSource(c.test),
958
- options: [
959
- { value: 0, style: c.falsy, label: 'false' },
960
- { value: 1, style: c.truthy, label: 'true' },
961
- ],
962
- });
963
+ const processBranch = (style) => {
964
+ if (Object.keys(style).length === 0)
965
+ return '""';
966
+ return JSON.stringify(processStyleRecords(style)
967
+ .map((r) => r.hash)
968
+ .join(' '));
969
+ };
970
+ const testStr = c.testString ?? getSource(c.test);
971
+ classParts.push(`(${testStr} ? ${processBranch(c.truthy)} : ${processBranch(c.falsy)})`);
963
972
  });
964
- const conflictVarGroups = {};
965
- conflictConditionals.forEach((c) => {
973
+ const indepVarGroups = {};
974
+ indepConditionals.forEach((c) => {
966
975
  if (c.groupId !== undefined) {
967
- if (!conflictVarGroups[c.groupId])
968
- conflictVarGroups[c.groupId] = [];
969
- conflictVarGroups[c.groupId].push(c);
976
+ if (!indepVarGroups[c.groupId])
977
+ indepVarGroups[c.groupId] = [];
978
+ indepVarGroups[c.groupId].push(c);
970
979
  }
971
980
  });
972
- Object.entries(conflictVarGroups).forEach(([, opts]) => {
973
- dimensions.push({
974
- type: 'var',
975
- testExpr: opts[0].testLHS ?? opts[0].testString ?? getSource(opts[0].test),
976
- options: opts.map((opt) => ({
977
- value: opt.valueName,
978
- style: opt.truthy,
979
- label: opt.valueName || 'default',
980
- })),
981
+ Object.values(indepVarGroups).forEach((options) => {
982
+ const commonTestExpr = options[0].testLHS ??
983
+ options[0].testString ??
984
+ getSource(options[0].test);
985
+ const lookupMap = {};
986
+ options.forEach((opt) => {
987
+ if (opt.valueName && opt.truthy) {
988
+ const className = processStyleRecords(opt.truthy)
989
+ .map((r) => r.hash)
990
+ .join(' ');
991
+ if (className)
992
+ lookupMap[opt.valueName] = className;
993
+ }
981
994
  });
982
- });
983
- const results = {};
984
- const recurse = (dimIndex, currentStyle, keyParts) => {
985
- if (dimIndex >= dimensions.length) {
986
- const className = processStyleRecords(currentStyle)
987
- .map((r) => r.hash)
988
- .join(' ');
989
- if (className)
990
- results[keyParts.join('__')] = className;
991
- return;
995
+ if (Object.keys(lookupMap).length > 0) {
996
+ const entries = Object.entries(lookupMap)
997
+ .map(([k, v]) => `"${k}":"${v}"`)
998
+ .join(',');
999
+ classParts.push(`({${entries}}[${commonTestExpr}] || "")`);
992
1000
  }
993
- dimensions[dimIndex].options.forEach((opt) => recurse(dimIndex + 1, (0, utils_1.deepMerge)(currentStyle, opt.style), [
994
- ...keyParts,
995
- String(opt.value),
996
- ]));
997
- };
998
- recurse(0, baseConflict, []);
999
- const baseConflictClass = Object.keys(baseConflict).length > 0
1000
- ? processStyleRecords(baseConflict)
1001
- .map((r) => r.hash)
1002
- .join(' ')
1003
- : '';
1004
- const masterKeyExpr = dimensions
1005
- .map((dim) => dim.type === 'std'
1006
- ? `(${dim.testExpr} ? "1" : "0")`
1007
- : dim.testExpr || '""')
1008
- .join(' + "__" + ');
1009
- classParts.push(`(${JSON.stringify(results)}[${masterKeyExpr || '""'}] || ${baseConflictClass ? JSON.stringify(baseConflictClass) : '""'})`);
1010
- }
1011
- classParts.push(...dynamicClassParts);
1012
- return { classParts, isOptimizable, baseStyle };
1013
- };
1014
- (0, utils_1.traverse)(ast, {
1015
- JSXOpeningElement({ node }) {
1016
- jsxOpeningElementMap.set(node.span.start, node.attributes);
1017
- },
1018
- MemberExpression({ node }) {
1019
- if (utils_1.t.isIdentifier(node.object) && utils_1.t.isIdentifier(node.property)) {
1020
- const varName = node.object.value;
1021
- const propName = node.property.value;
1022
- const uniqueKey = `${resourcePath}-${varName}`;
1023
- const localStyle = localCreateStyles[varName];
1024
- if (localStyle && localStyle.type === 'create') {
1025
- const atomMap = localStyle.hashMap[propName];
1026
- if (atomMap) {
1027
- replacements.push({
1028
- start: node.span.start - baseByteOffset,
1029
- end: node.span.end - baseByteOffset,
1030
- content: `(${JSON.stringify(atomMap)})`,
1031
- });
1032
- return;
1001
+ });
1002
+ if (Object.keys(baseConflict).length > 0 ||
1003
+ conflictConditionals.length > 0) {
1004
+ const dimensions = [];
1005
+ conflictConditionals
1006
+ .filter((c) => c.groupId === undefined)
1007
+ .forEach((c) => {
1008
+ dimensions.push({
1009
+ type: 'std',
1010
+ testExpr: c.testString ?? getSource(c.test),
1011
+ options: [
1012
+ { value: 0, style: c.falsy, label: 'false' },
1013
+ { value: 1, style: c.truthy, label: 'true' },
1014
+ ],
1015
+ });
1016
+ });
1017
+ const conflictVarGroups = {};
1018
+ conflictConditionals.forEach((c) => {
1019
+ if (c.groupId !== undefined) {
1020
+ if (!conflictVarGroups[c.groupId])
1021
+ conflictVarGroups[c.groupId] = [];
1022
+ conflictVarGroups[c.groupId].push(c);
1033
1023
  }
1034
- }
1035
- if (localStyle && localStyle.type === 'variant') {
1036
- const variantMap = localStyle.hashMap[propName];
1037
- if (variantMap) {
1038
- replacements.push({
1039
- start: node.span.start - baseByteOffset,
1040
- end: node.span.end - baseByteOffset,
1041
- content: `(${JSON.stringify(variantMap)})`,
1042
- });
1024
+ });
1025
+ Object.entries(conflictVarGroups).forEach(([, opts]) => {
1026
+ dimensions.push({
1027
+ type: 'var',
1028
+ testExpr: opts[0].testLHS ?? opts[0].testString ?? getSource(opts[0].test),
1029
+ options: opts.map((opt) => ({
1030
+ value: opt.valueName,
1031
+ style: opt.truthy,
1032
+ label: opt.valueName || 'default',
1033
+ })),
1034
+ });
1035
+ });
1036
+ const results = {};
1037
+ const recurse = (dimIndex, currentStyle, keyParts) => {
1038
+ if (dimIndex >= dimensions.length) {
1039
+ const className = processStyleRecords(currentStyle)
1040
+ .map((r) => r.hash)
1041
+ .join(' ');
1042
+ if (className)
1043
+ results[keyParts.join('__')] = className;
1043
1044
  return;
1044
1045
  }
1046
+ dimensions[dimIndex].options.forEach((opt) => recurse(dimIndex + 1, (0, utils_1.deepMerge)(currentStyle, opt.style), [
1047
+ ...keyParts,
1048
+ String(opt.value),
1049
+ ]));
1050
+ };
1051
+ recurse(0, baseConflict, []);
1052
+ const baseConflictClass = Object.keys(baseConflict).length > 0
1053
+ ? processStyleRecords(baseConflict)
1054
+ .map((r) => r.hash)
1055
+ .join(' ')
1056
+ : '';
1057
+ const masterKeyExpr = dimensions
1058
+ .map((dim) => dim.type === 'std'
1059
+ ? `(${dim.testExpr} ? "1" : "0")`
1060
+ : dim.testExpr || '""')
1061
+ .join(' + "__" + ');
1062
+ classParts.push(`(${JSON.stringify(results)}[${masterKeyExpr || '""'}] || ${baseConflictClass ? JSON.stringify(baseConflictClass) : '""'})`);
1063
+ }
1064
+ classParts.push(...dynamicClassParts);
1065
+ return { classParts, isOptimizable, baseStyle };
1066
+ };
1067
+ (0, utils_1.traverse)(ast, {
1068
+ JSXOpeningElement({ node }) {
1069
+ jsxOpeningElementMap.set(node.span.start, node.attributes);
1070
+ },
1071
+ MemberExpression({ node }) {
1072
+ if (utils_1.t.isIdentifier(node.object) && utils_1.t.isIdentifier(node.property)) {
1073
+ const varName = node.object.value;
1074
+ const propName = node.property.value;
1075
+ const uniqueKey = `${resourcePath}-${varName}`;
1076
+ const localStyle = localCreateStyles[varName];
1077
+ if (localStyle && localStyle.type === 'create') {
1078
+ const atomMap = localStyle.hashMap[propName];
1079
+ if (atomMap) {
1080
+ replacements.push({
1081
+ start: node.span.start - baseByteOffset,
1082
+ end: node.span.end - baseByteOffset,
1083
+ content: `(${JSON.stringify(atomMap)})`,
1084
+ });
1085
+ return;
1086
+ }
1087
+ }
1088
+ if (localStyle && localStyle.type === 'variant') {
1089
+ const variantMap = localStyle.hashMap[propName];
1090
+ if (variantMap) {
1091
+ replacements.push({
1092
+ start: node.span.start - baseByteOffset,
1093
+ end: node.span.end - baseByteOffset,
1094
+ content: `(${JSON.stringify(variantMap)})`,
1095
+ });
1096
+ return;
1097
+ }
1098
+ }
1099
+ let hash = scannedTables.createHashTable[uniqueKey];
1100
+ if (!hash) {
1101
+ hash = mergedCreateTable[varName];
1102
+ }
1103
+ if (hash) {
1104
+ let atomMap;
1105
+ if (scannedTables.createAtomicMapTable[hash]) {
1106
+ atomMap = scannedTables.createAtomicMapTable[hash][propName];
1107
+ }
1108
+ if (atomMap) {
1109
+ replacements.push({
1110
+ start: node.span.start - baseByteOffset,
1111
+ end: node.span.end - baseByteOffset,
1112
+ content: `(${JSON.stringify(atomMap)})`,
1113
+ });
1114
+ }
1115
+ }
1116
+ let themeHash = mergedCreateThemeHashTable[varName];
1117
+ if (!themeHash) {
1118
+ themeHash = scannedTables.createThemeHashTable[uniqueKey];
1119
+ }
1120
+ if (themeHash) {
1121
+ const atomicMap = scannedTables.createAtomicMapTable[themeHash];
1122
+ if (atomicMap && atomicMap[propName]) {
1123
+ replacements.push({
1124
+ start: node.span.start - baseByteOffset,
1125
+ end: node.span.end - baseByteOffset,
1126
+ content: `(${JSON.stringify(atomicMap[propName])})`,
1127
+ });
1128
+ }
1129
+ else {
1130
+ const cssVarName = (0, zss_engine_1.camelToKebabCase)(propName);
1131
+ replacements.push({
1132
+ start: node.span.start - baseByteOffset,
1133
+ end: node.span.end - baseByteOffset,
1134
+ content: `(${JSON.stringify(`var(--${themeHash}-${cssVarName})`)})`,
1135
+ });
1136
+ }
1137
+ }
1138
+ let staticHash = mergedCreateStaticHashTable[varName];
1139
+ if (!staticHash) {
1140
+ staticHash = scannedTables.createStaticHashTable[uniqueKey];
1141
+ }
1142
+ if (staticHash) {
1143
+ const staticObj = scannedTables.createStaticObjectTable[staticHash];
1144
+ if (staticObj && staticObj[propName] !== undefined) {
1145
+ replacements.push({
1146
+ start: node.span.start - baseByteOffset,
1147
+ end: node.span.end - baseByteOffset,
1148
+ content: `(${JSON.stringify(staticObj[propName])})`,
1149
+ });
1150
+ }
1151
+ }
1045
1152
  }
1046
- let hash = scannedTables.createHashTable[uniqueKey];
1153
+ },
1154
+ Identifier({ node }) {
1155
+ if (excludedSpans.has(node.span.start))
1156
+ return;
1157
+ if (idSpans.has(node.span.start))
1158
+ return;
1159
+ const styleInfo = localCreateStyles[node.value];
1160
+ if (styleInfo) {
1161
+ replacements.push({
1162
+ start: node.span.start - baseByteOffset,
1163
+ end: node.span.end - baseByteOffset,
1164
+ content: `(${JSON.stringify(styleInfo.hashMap)})`,
1165
+ });
1166
+ return;
1167
+ }
1168
+ const varName = node.value;
1169
+ const uniqueKey = `${resourcePath}-${varName}`;
1170
+ let hash = mergedCreateTable[varName];
1047
1171
  if (!hash) {
1048
- hash = mergedCreateTable[varName];
1172
+ hash = scannedTables.createHashTable[uniqueKey];
1049
1173
  }
1050
1174
  if (hash) {
1051
- let atomMap;
1052
- if (scannedTables.createAtomicMapTable[hash]) {
1053
- atomMap = scannedTables.createAtomicMapTable[hash][propName];
1054
- }
1055
- if (atomMap) {
1175
+ const obj = scannedTables.createObjectTable[hash];
1176
+ const atomicMap = scannedTables.createAtomicMapTable[hash];
1177
+ if (obj && atomicMap) {
1178
+ const hashMap = {};
1179
+ Object.keys(obj).forEach((key) => {
1180
+ if (atomicMap[key]) {
1181
+ hashMap[key] = atomicMap[key];
1182
+ }
1183
+ });
1056
1184
  replacements.push({
1057
1185
  start: node.span.start - baseByteOffset,
1058
1186
  end: node.span.end - baseByteOffset,
1059
- content: `(${JSON.stringify(atomMap)})`,
1187
+ content: `(${JSON.stringify(hashMap)})`,
1060
1188
  });
1061
1189
  }
1062
1190
  }
@@ -1066,20 +1194,13 @@ async function loader(source) {
1066
1194
  }
1067
1195
  if (themeHash) {
1068
1196
  const atomicMap = scannedTables.createAtomicMapTable[themeHash];
1069
- if (atomicMap && atomicMap[propName]) {
1070
- replacements.push({
1071
- start: node.span.start - baseByteOffset,
1072
- end: node.span.end - baseByteOffset,
1073
- content: `(${JSON.stringify(atomicMap[propName])})`,
1074
- });
1075
- }
1076
- else {
1077
- const cssVarName = (0, zss_engine_1.camelToKebabCase)(propName);
1197
+ if (atomicMap) {
1078
1198
  replacements.push({
1079
1199
  start: node.span.start - baseByteOffset,
1080
1200
  end: node.span.end - baseByteOffset,
1081
- content: `(${JSON.stringify(`var(--${themeHash}-${cssVarName})`)})`,
1201
+ content: `(${JSON.stringify(atomicMap)})`,
1082
1202
  });
1203
+ return;
1083
1204
  }
1084
1205
  }
1085
1206
  let staticHash = mergedCreateStaticHashTable[varName];
@@ -1088,349 +1209,304 @@ async function loader(source) {
1088
1209
  }
1089
1210
  if (staticHash) {
1090
1211
  const staticObj = scannedTables.createStaticObjectTable[staticHash];
1091
- if (staticObj && staticObj[propName] !== undefined) {
1212
+ if (staticObj) {
1092
1213
  replacements.push({
1093
1214
  start: node.span.start - baseByteOffset,
1094
1215
  end: node.span.end - baseByteOffset,
1095
- content: `(${JSON.stringify(staticObj[propName])})`,
1216
+ content: `(${JSON.stringify(staticObj)})`,
1096
1217
  });
1097
1218
  }
1098
1219
  }
1099
- }
1100
- },
1101
- Identifier({ node }) {
1102
- if (excludedSpans.has(node.span.start))
1103
- return;
1104
- if (idSpans.has(node.span.start))
1105
- return;
1106
- const styleInfo = localCreateStyles[node.value];
1107
- if (styleInfo) {
1108
- replacements.push({
1109
- start: node.span.start - baseByteOffset,
1110
- end: node.span.end - baseByteOffset,
1111
- content: `(${JSON.stringify(styleInfo.hashMap)})`,
1112
- });
1113
- return;
1114
- }
1115
- const varName = node.value;
1116
- const uniqueKey = `${resourcePath}-${varName}`;
1117
- let hash = mergedCreateTable[varName];
1118
- if (!hash) {
1119
- hash = scannedTables.createHashTable[uniqueKey];
1120
- }
1121
- if (hash) {
1122
- const obj = scannedTables.createObjectTable[hash];
1123
- const atomicMap = scannedTables.createAtomicMapTable[hash];
1124
- if (obj && atomicMap) {
1125
- const hashMap = {};
1126
- Object.keys(obj).forEach((key) => {
1127
- if (atomicMap[key]) {
1128
- hashMap[key] = atomicMap[key];
1129
- }
1220
+ },
1221
+ JSXAttribute({ node }) {
1222
+ if (node.name.type !== 'Identifier' || node.name.value !== 'styleName')
1223
+ return;
1224
+ if (!node.value || node.value.type !== 'JSXExpressionContainer')
1225
+ return;
1226
+ const expr = node.value.expression;
1227
+ let args = expr.type === 'ArrayExpression'
1228
+ ? expr.elements
1229
+ .filter((el) => el !== undefined)
1230
+ .map((el) => ({ expression: el.expression }))
1231
+ : [{ expression: expr }];
1232
+ const dynamicClassParts = [];
1233
+ const dynamicStyleParts = [];
1234
+ let attributes = [];
1235
+ for (const [, attrs] of jsxOpeningElementMap) {
1236
+ const found = attrs
1237
+ .filter((a) => a.type === 'JSXAttribute')
1238
+ .find((a) => a.span.start === node.span.start);
1239
+ if (found) {
1240
+ attributes = attrs;
1241
+ break;
1242
+ }
1243
+ }
1244
+ const classNameAttr = attributes.find((attr) => attr.type === 'JSXAttribute' &&
1245
+ attr.name.type === 'Identifier' &&
1246
+ attr.name.value === 'className');
1247
+ let existingClass = '';
1248
+ if (classNameAttr?.value?.type === 'StringLiteral') {
1249
+ existingClass = classNameAttr.value.value;
1250
+ replacements.push({
1251
+ start: classNameAttr.span.start - baseByteOffset,
1252
+ end: classNameAttr.span.end - baseByteOffset,
1253
+ content: '',
1130
1254
  });
1255
+ }
1256
+ const styleAttrExisting = attributes.find((attr) => attr.type === 'JSXAttribute' &&
1257
+ attr.name.type === 'Identifier' &&
1258
+ attr.name.value === 'style');
1259
+ if (styleAttrExisting) {
1131
1260
  replacements.push({
1132
- start: node.span.start - baseByteOffset,
1133
- end: node.span.end - baseByteOffset,
1134
- content: `(${JSON.stringify(hashMap)})`,
1261
+ start: styleAttrExisting.span.start - baseByteOffset,
1262
+ end: styleAttrExisting.span.end - baseByteOffset,
1263
+ content: '',
1135
1264
  });
1265
+ if (styleAttrExisting.value?.type === 'JSXExpressionContainer') {
1266
+ const innerExpr = styleAttrExisting.value?.expression;
1267
+ if (innerExpr?.type === 'ObjectExpression') {
1268
+ const start = innerExpr.span.start - baseByteOffset;
1269
+ const end = innerExpr.span.end - baseByteOffset;
1270
+ const innerSource = sourceBuffer
1271
+ .subarray(start, end)
1272
+ .toString('utf-8');
1273
+ const stripped = innerSource.slice(1, -1).trim();
1274
+ if (stripped)
1275
+ dynamicStyleParts.push(stripped);
1276
+ }
1277
+ }
1136
1278
  }
1137
- }
1138
- let themeHash = mergedCreateThemeHashTable[varName];
1139
- if (!themeHash) {
1140
- themeHash = scannedTables.createThemeHashTable[uniqueKey];
1141
- }
1142
- if (themeHash) {
1143
- const atomicMap = scannedTables.createAtomicMapTable[themeHash];
1144
- if (atomicMap) {
1279
+ args = args.filter((arg) => {
1280
+ const expr = arg.expression;
1281
+ if (!utils_1.t.isCallExpression(expr) || !utils_1.t.isMemberExpression(expr.callee))
1282
+ return true;
1283
+ const callee = expr.callee;
1284
+ if (!utils_1.t.isIdentifier(callee.object) ||
1285
+ !utils_1.t.isIdentifier(callee.property))
1286
+ return true;
1287
+ const varName = callee.object.value;
1288
+ const propKey = callee.property.value;
1289
+ const styleInfo = localCreateStyles[varName];
1290
+ if (styleInfo?.functions?.[propKey]) {
1291
+ const func = styleInfo.functions[propKey];
1292
+ const callArgs = expr.arguments;
1293
+ const hasSpread = callArgs.some((a) => a.spread);
1294
+ if (!hasSpread && callArgs.length >= 1) {
1295
+ const tempStaticTable = { ...mergedStaticTable };
1296
+ const cssVarInfo = {};
1297
+ if (callArgs.length === 1 &&
1298
+ callArgs[0].expression.type === 'ObjectExpression') {
1299
+ const argObj = (0, utils_1.objectExpressionToObject)(callArgs[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
1300
+ func.params.forEach((p) => {
1301
+ if (argObj[p] !== undefined)
1302
+ tempStaticTable[p] = argObj[p];
1303
+ });
1304
+ }
1305
+ else {
1306
+ callArgs.forEach((_callArg, i) => {
1307
+ const p = func.params[i];
1308
+ if (!p)
1309
+ return;
1310
+ const cssVar = `--${propKey}-${p}`;
1311
+ tempStaticTable[p] = `var(${cssVar})`;
1312
+ cssVarInfo[p] = { cssVar, propKey: '' };
1313
+ });
1314
+ }
1315
+ const substituted = (0, utils_1.objectExpressionToObject)(func.body, tempStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
1316
+ if (substituted) {
1317
+ const records = processStyleRecords(substituted);
1318
+ const hashes = records.map((r) => r.hash).join(' ');
1319
+ if (hashes)
1320
+ dynamicClassParts.push(JSON.stringify(hashes));
1321
+ if (Object.keys(cssVarInfo).length > 0) {
1322
+ Object.entries(cssVarInfo).forEach(([paramName, info]) => {
1323
+ const targetProp = Object.keys(substituted).find((k) => typeof substituted[k] === 'string' &&
1324
+ substituted[k].includes(info.cssVar));
1325
+ if (targetProp) {
1326
+ const paramIndex = func.params.indexOf(paramName);
1327
+ const srcArg = paramIndex >= 0 && callArgs[paramIndex]
1328
+ ? callArgs[paramIndex].expression
1329
+ : callArgs[0].expression;
1330
+ const argStart = srcArg.span.start - baseByteOffset;
1331
+ const argEnd = srcArg.span.end - baseByteOffset;
1332
+ const argSource = sourceBuffer
1333
+ .subarray(argStart, argEnd)
1334
+ .toString('utf-8');
1335
+ let valueExpr;
1336
+ const maybeNumber = Number(argSource);
1337
+ if (!isNaN(maybeNumber) &&
1338
+ argSource.trim() === String(maybeNumber)) {
1339
+ valueExpr = JSON.stringify((0, zss_engine_1.applyCssValue)(maybeNumber, targetProp));
1340
+ }
1341
+ else if ((argSource.startsWith('"') &&
1342
+ argSource.endsWith('"')) ||
1343
+ (argSource.startsWith("'") && argSource.endsWith("'"))) {
1344
+ valueExpr = JSON.stringify((0, zss_engine_1.applyCssValue)(argSource.slice(1, -1), targetProp));
1345
+ }
1346
+ else {
1347
+ valueExpr = zss_engine_1.exceptionCamelCase.includes(targetProp)
1348
+ ? argSource
1349
+ : `(typeof (${argSource}) === 'number' ? (${argSource}) + 'px' : (${argSource}))`;
1350
+ }
1351
+ dynamicStyleParts.push(`"${info.cssVar}": ${valueExpr}`);
1352
+ }
1353
+ });
1354
+ }
1355
+ return false;
1356
+ }
1357
+ }
1358
+ }
1359
+ return true;
1360
+ });
1361
+ const styleAttr = dynamicStyleParts.length > 0
1362
+ ? ` style={{${dynamicStyleParts.join(', ')}}}`
1363
+ : '';
1364
+ const { classParts, isOptimizable, baseStyle } = buildClassParts(args, dynamicClassParts, existingClass);
1365
+ if (isOptimizable &&
1366
+ (args.length > 0 ||
1367
+ Object.keys(baseStyle).length > 0 ||
1368
+ dynamicClassParts.length > 0)) {
1369
+ const replacement = classParts.length > 0 ? classParts.join(' + " " + ') : '""';
1145
1370
  replacements.push({
1146
1371
  start: node.span.start - baseByteOffset,
1147
1372
  end: node.span.end - baseByteOffset,
1148
- content: `(${JSON.stringify(atomicMap)})`,
1373
+ content: `className={${replacement}}${styleAttr}`,
1149
1374
  });
1150
- return;
1151
1375
  }
1152
- }
1153
- let staticHash = mergedCreateStaticHashTable[varName];
1154
- if (!staticHash) {
1155
- staticHash = scannedTables.createStaticHashTable[uniqueKey];
1156
- }
1157
- if (staticHash) {
1158
- const staticObj = scannedTables.createStaticObjectTable[staticHash];
1159
- if (staticObj) {
1376
+ else {
1160
1377
  replacements.push({
1161
1378
  start: node.span.start - baseByteOffset,
1162
1379
  end: node.span.end - baseByteOffset,
1163
- content: `(${JSON.stringify(staticObj)})`,
1380
+ content: styleAttr || '',
1164
1381
  });
1165
1382
  }
1166
- }
1167
- },
1168
- JSXAttribute({ node }) {
1169
- if (node.name.type !== 'Identifier' || node.name.value !== 'styleName')
1170
- return;
1171
- if (!node.value || node.value.type !== 'JSXExpressionContainer')
1172
- return;
1173
- const expr = node.value.expression;
1174
- let args = expr.type === 'ArrayExpression'
1175
- ? expr.elements
1176
- .filter((el) => el !== undefined)
1177
- .map((el) => ({ expression: el.expression }))
1178
- : [{ expression: expr }];
1179
- const dynamicClassParts = [];
1180
- const dynamicStyleParts = [];
1181
- let attributes = [];
1182
- for (const [, attrs] of jsxOpeningElementMap) {
1183
- const found = attrs
1184
- .filter((a) => a.type === 'JSXAttribute')
1185
- .find((a) => a.span.start === node.span.start);
1186
- if (found) {
1187
- attributes = attrs;
1188
- break;
1383
+ },
1384
+ CallExpression({ node }) {
1385
+ const callee = node.callee;
1386
+ let isUseCall = false;
1387
+ if (utils_1.t.isMemberExpression(callee) &&
1388
+ utils_1.t.isIdentifier(callee.object) &&
1389
+ utils_1.t.isIdentifier(callee.property)) {
1390
+ const objectName = callee.object.value;
1391
+ const propertyName = callee.property.value;
1392
+ const alias = plumeriaAliases[objectName];
1393
+ if (alias === 'NAMESPACE' && propertyName === 'use') {
1394
+ isUseCall = true;
1395
+ }
1189
1396
  }
1190
- }
1191
- const classNameAttr = attributes.find((attr) => attr.type === 'JSXAttribute' &&
1192
- attr.name.type === 'Identifier' &&
1193
- attr.name.value === 'className');
1194
- let existingClass = '';
1195
- if (classNameAttr?.value?.type === 'StringLiteral') {
1196
- existingClass = classNameAttr.value.value;
1197
- replacements.push({
1198
- start: classNameAttr.span.start - baseByteOffset,
1199
- end: classNameAttr.span.end - baseByteOffset,
1200
- content: '',
1201
- });
1202
- }
1203
- const styleAttrExisting = attributes.find((attr) => attr.type === 'JSXAttribute' &&
1204
- attr.name.type === 'Identifier' &&
1205
- attr.name.value === 'style');
1206
- if (styleAttrExisting) {
1207
- replacements.push({
1208
- start: styleAttrExisting.span.start - baseByteOffset,
1209
- end: styleAttrExisting.span.end - baseByteOffset,
1210
- content: '',
1211
- });
1212
- if (styleAttrExisting.value?.type === 'JSXExpressionContainer') {
1213
- const innerExpr = styleAttrExisting.value?.expression;
1214
- if (innerExpr?.type === 'ObjectExpression') {
1215
- const start = innerExpr.span.start - baseByteOffset;
1216
- const end = innerExpr.span.end - baseByteOffset;
1217
- const innerSource = sourceBuffer
1218
- .subarray(start, end)
1219
- .toString('utf-8');
1220
- const stripped = innerSource.slice(1, -1).trim();
1221
- if (stripped)
1222
- dynamicStyleParts.push(stripped);
1397
+ else if (utils_1.t.isIdentifier(callee)) {
1398
+ const calleeName = callee.value;
1399
+ const originalName = plumeriaAliases[calleeName];
1400
+ if (originalName === 'use') {
1401
+ isUseCall = true;
1223
1402
  }
1224
1403
  }
1225
- }
1226
- args = args.filter((arg) => {
1227
- const expr = arg.expression;
1228
- if (!utils_1.t.isCallExpression(expr) || !utils_1.t.isMemberExpression(expr.callee))
1229
- return true;
1230
- const callee = expr.callee;
1231
- if (!utils_1.t.isIdentifier(callee.object) || !utils_1.t.isIdentifier(callee.property))
1232
- return true;
1233
- const varName = callee.object.value;
1234
- const propKey = callee.property.value;
1235
- const styleInfo = localCreateStyles[varName];
1236
- if (styleInfo?.functions?.[propKey]) {
1237
- const func = styleInfo.functions[propKey];
1238
- const callArgs = expr.arguments;
1239
- const hasSpread = callArgs.some((a) => a.spread);
1240
- if (!hasSpread && callArgs.length >= 1) {
1241
- const tempStaticTable = { ...mergedStaticTable };
1242
- const cssVarInfo = {};
1243
- if (callArgs.length === 1 &&
1244
- callArgs[0].expression.type === 'ObjectExpression') {
1245
- const argObj = (0, utils_1.objectExpressionToObject)(callArgs[0].expression, mergedStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
1246
- func.params.forEach((p) => {
1247
- if (argObj[p] !== undefined)
1248
- tempStaticTable[p] = argObj[p];
1249
- });
1250
- }
1251
- else {
1252
- callArgs.forEach((_callArg, i) => {
1253
- const p = func.params[i];
1254
- if (!p)
1255
- return;
1256
- const cssVar = `--${propKey}-${p}`;
1257
- tempStaticTable[p] = `var(${cssVar})`;
1258
- cssVarInfo[p] = { cssVar, propKey: '' };
1259
- });
1260
- }
1261
- const substituted = (0, utils_1.objectExpressionToObject)(func.body, tempStaticTable, mergedKeyframesTable, mergedViewTransitionTable, mergedCreateThemeHashTable, scannedTables.createThemeObjectTable, mergedCreateTable, mergedCreateStaticHashTable, scannedTables.createStaticObjectTable, mergedVariantsTable);
1262
- if (substituted) {
1263
- const records = processStyleRecords(substituted);
1264
- const hashes = records.map((r) => r.hash).join(' ');
1265
- if (hashes)
1266
- dynamicClassParts.push(JSON.stringify(hashes));
1267
- if (Object.keys(cssVarInfo).length > 0) {
1268
- Object.entries(cssVarInfo).forEach(([paramName, info]) => {
1269
- const targetProp = Object.keys(substituted).find((k) => typeof substituted[k] === 'string' &&
1270
- substituted[k].includes(info.cssVar));
1271
- if (targetProp) {
1272
- const paramIndex = func.params.indexOf(paramName);
1273
- const srcArg = paramIndex >= 0 && callArgs[paramIndex]
1274
- ? callArgs[paramIndex].expression
1275
- : callArgs[0].expression;
1276
- const argStart = srcArg.span.start - baseByteOffset;
1277
- const argEnd = srcArg.span.end - baseByteOffset;
1278
- const argSource = sourceBuffer
1279
- .subarray(argStart, argEnd)
1280
- .toString('utf-8');
1281
- let valueExpr;
1282
- const maybeNumber = Number(argSource);
1283
- if (!isNaN(maybeNumber) &&
1284
- argSource.trim() === String(maybeNumber)) {
1285
- valueExpr = JSON.stringify((0, zss_engine_1.applyCssValue)(maybeNumber, targetProp));
1286
- }
1287
- else if ((argSource.startsWith('"') && argSource.endsWith('"')) ||
1288
- (argSource.startsWith("'") && argSource.endsWith("'"))) {
1289
- valueExpr = JSON.stringify((0, zss_engine_1.applyCssValue)(argSource.slice(1, -1), targetProp));
1290
- }
1291
- else {
1292
- valueExpr = zss_engine_1.exceptionCamelCase.includes(targetProp)
1293
- ? argSource
1294
- : `(typeof (${argSource}) === 'number' ? (${argSource}) + 'px' : (${argSource}))`;
1295
- }
1296
- dynamicStyleParts.push(`"${info.cssVar}": ${valueExpr}`);
1297
- }
1298
- });
1299
- }
1300
- return false;
1301
- }
1404
+ if (!isUseCall)
1405
+ return;
1406
+ const args = node.arguments;
1407
+ for (const arg of args) {
1408
+ const expr = arg.expression;
1409
+ if (!utils_1.t.isCallExpression(expr) || !utils_1.t.isMemberExpression(expr.callee))
1410
+ continue;
1411
+ const callee = expr.callee;
1412
+ if (!utils_1.t.isIdentifier(callee.object) ||
1413
+ !utils_1.t.isIdentifier(callee.property))
1414
+ continue;
1415
+ const varName = callee.object.value;
1416
+ const propKey = callee.property.value;
1417
+ const styleInfo = localCreateStyles[varName];
1418
+ if (styleInfo?.functions?.[propKey]) {
1419
+ throw new Error(`Plumeria: css.use(${getSource(expr)}) does not support dynamic function keys.\n`);
1302
1420
  }
1303
1421
  }
1304
- return true;
1305
- });
1306
- const styleAttr = dynamicStyleParts.length > 0
1307
- ? ` style={{${dynamicStyleParts.join(', ')}}}`
1308
- : '';
1309
- const { classParts, isOptimizable, baseStyle } = buildClassParts(args, dynamicClassParts, existingClass);
1310
- if (isOptimizable &&
1311
- (args.length > 0 ||
1312
- Object.keys(baseStyle).length > 0 ||
1313
- dynamicClassParts.length > 0)) {
1314
- const replacement = classParts.length > 0 ? classParts.join(' + " " + ') : '""';
1422
+ const { classParts, isOptimizable, baseStyle } = buildClassParts(args);
1423
+ if (isOptimizable &&
1424
+ (args.length > 0 || Object.keys(baseStyle).length > 0)) {
1425
+ const replacement = classParts.length > 0 ? classParts.join(' + " " + ') : '""';
1426
+ replacements.push({
1427
+ start: node.span.start - baseByteOffset,
1428
+ end: node.span.end - baseByteOffset,
1429
+ content: replacement,
1430
+ });
1431
+ }
1432
+ },
1433
+ });
1434
+ Object.values(localCreateStyles).forEach((info) => {
1435
+ if (info.isExported) {
1315
1436
  replacements.push({
1316
- start: node.span.start - baseByteOffset,
1317
- end: node.span.end - baseByteOffset,
1318
- content: `className={${replacement}}${styleAttr}`,
1437
+ start: info.initSpan.start,
1438
+ end: info.initSpan.end,
1439
+ content: JSON.stringify(''),
1319
1440
  });
1320
1441
  }
1321
1442
  else {
1322
1443
  replacements.push({
1323
- start: node.span.start - baseByteOffset,
1324
- end: node.span.end - baseByteOffset,
1325
- content: styleAttr || '',
1444
+ start: info.declSpan.start,
1445
+ end: info.declSpan.end,
1446
+ content: '',
1326
1447
  });
1327
1448
  }
1328
- },
1329
- CallExpression({ node }) {
1330
- const callee = node.callee;
1331
- let isUseCall = false;
1332
- if (utils_1.t.isMemberExpression(callee) &&
1333
- utils_1.t.isIdentifier(callee.object) &&
1334
- utils_1.t.isIdentifier(callee.property)) {
1335
- const objectName = callee.object.value;
1336
- const propertyName = callee.property.value;
1337
- const alias = plumeriaAliases[objectName];
1338
- if (alias === 'NAMESPACE' && propertyName === 'use') {
1339
- isUseCall = true;
1340
- }
1449
+ });
1450
+ const buffer = Buffer.from(source);
1451
+ let offset = 0;
1452
+ const parts = [];
1453
+ replacements
1454
+ .sort((a, b) => a.start - b.start || b.end - a.end)
1455
+ .forEach((r) => {
1456
+ if (r.start < offset)
1457
+ return;
1458
+ parts.push(buffer.subarray(offset, r.start));
1459
+ parts.push(Buffer.from(r.content));
1460
+ offset = r.end;
1461
+ });
1462
+ parts.push(buffer.subarray(offset));
1463
+ const transformedSource = Buffer.concat(parts).toString();
1464
+ const optInCSS = await (0, utils_1.optimizer)(extractedSheets.join(''));
1465
+ let relativeImportPath = path.relative(path.dirname(resourcePath), VIRTUAL_FILE_PATH);
1466
+ relativeImportPath = relativeImportPath.replace(/\\/g, '/');
1467
+ if (!relativeImportPath.startsWith('.')) {
1468
+ relativeImportPath = './' + relativeImportPath;
1469
+ }
1470
+ const hash = (0, zss_engine_1.genBase36Hash)(optInCSS, 1, 8);
1471
+ const postfix = `\nimport "${relativeImportPath}?v=${hash}";`;
1472
+ if (process.env.NODE_ENV === 'production') {
1473
+ return callback(null, transformedSource);
1474
+ }
1475
+ if (extractedSheets.length > 0 && process.env.NODE_ENV === 'development') {
1476
+ const newCss = optInCSS + '\n';
1477
+ let currentCss = '';
1478
+ try {
1479
+ currentCss = fs.readFileSync(VIRTUAL_FILE_PATH, 'utf-8');
1341
1480
  }
1342
- else if (utils_1.t.isIdentifier(callee)) {
1343
- const calleeName = callee.value;
1344
- const originalName = plumeriaAliases[calleeName];
1345
- if (originalName === 'use') {
1346
- isUseCall = true;
1347
- }
1481
+ catch (e) {
1348
1482
  }
1349
- if (!isUseCall)
1350
- return;
1351
- const args = node.arguments;
1352
- for (const arg of args) {
1353
- const expr = arg.expression;
1354
- if (!utils_1.t.isCallExpression(expr) || !utils_1.t.isMemberExpression(expr.callee))
1355
- continue;
1356
- const callee = expr.callee;
1357
- if (!utils_1.t.isIdentifier(callee.object) || !utils_1.t.isIdentifier(callee.property))
1358
- continue;
1359
- const varName = callee.object.value;
1360
- const propKey = callee.property.value;
1361
- const styleInfo = localCreateStyles[varName];
1362
- if (styleInfo?.functions?.[propKey]) {
1363
- throw new Error(`Plumeria: css.use(${getSource(expr)}) does not support dynamic function keys.\n`);
1364
- }
1483
+ if (!currentCss.includes(optInCSS)) {
1484
+ const cleanedCss = cleanStaleThemeRules(currentCss, optInCSS);
1485
+ const nextCss = cleanedCss ? cleanedCss + '\n' + newCss : newCss;
1486
+ fs.writeFileSync(VIRTUAL_FILE_PATH, nextCss, 'utf-8');
1487
+ lastValidCss = nextCss;
1365
1488
  }
1366
- const { classParts, isOptimizable, baseStyle } = buildClassParts(args);
1367
- if (isOptimizable &&
1368
- (args.length > 0 || Object.keys(baseStyle).length > 0)) {
1369
- const replacement = classParts.length > 0 ? classParts.join(' + " " + ') : '""';
1370
- replacements.push({
1371
- start: node.span.start - baseByteOffset,
1372
- end: node.span.end - baseByteOffset,
1373
- content: replacement,
1374
- });
1489
+ else {
1490
+ lastValidCss = currentCss;
1375
1491
  }
1376
- },
1377
- });
1378
- Object.values(localCreateStyles).forEach((info) => {
1379
- if (info.isExported) {
1380
- replacements.push({
1381
- start: info.initSpan.start,
1382
- end: info.initSpan.end,
1383
- content: JSON.stringify(''),
1384
- });
1385
1492
  }
1386
- else {
1387
- replacements.push({
1388
- start: info.declSpan.start,
1389
- end: info.declSpan.end,
1390
- content: '',
1391
- });
1493
+ else if (!isProduction) {
1494
+ try {
1495
+ lastValidCss = fs.readFileSync(VIRTUAL_FILE_PATH, 'utf-8');
1496
+ }
1497
+ catch (e) {
1498
+ }
1392
1499
  }
1393
- });
1394
- const buffer = Buffer.from(source);
1395
- let offset = 0;
1396
- const parts = [];
1397
- replacements
1398
- .sort((a, b) => a.start - b.start || b.end - a.end)
1399
- .forEach((r) => {
1400
- if (r.start < offset)
1401
- return;
1402
- parts.push(buffer.subarray(offset, r.start));
1403
- parts.push(Buffer.from(r.content));
1404
- offset = r.end;
1405
- });
1406
- parts.push(buffer.subarray(offset));
1407
- const transformedSource = Buffer.concat(parts).toString();
1408
- const optInCSS = await (0, utils_1.optimizer)(extractedSheets.join(''));
1409
- let relativeImportPath = path.relative(path.dirname(resourcePath), VIRTUAL_FILE_PATH);
1410
- relativeImportPath = relativeImportPath.replace(/\\/g, '/');
1411
- if (!relativeImportPath.startsWith('.')) {
1412
- relativeImportPath = './' + relativeImportPath;
1500
+ return callback(null, transformedSource + postfix);
1413
1501
  }
1414
- const postfix = `\nimport "${relativeImportPath}";`;
1415
- if (process.env.NODE_ENV === 'production') {
1416
- return callback(null, transformedSource);
1417
- }
1418
- if (extractedSheets.length > 0 && process.env.NODE_ENV === 'development') {
1419
- const newCss = optInCSS + '\n';
1420
- let currentCss = '';
1421
- try {
1422
- currentCss = fs.readFileSync(VIRTUAL_FILE_PATH, 'utf-8');
1423
- }
1424
- catch (e) {
1425
- }
1426
- if (!currentCss.includes(optInCSS)) {
1427
- if (currentCss) {
1428
- fs.writeFileSync(VIRTUAL_FILE_PATH, currentCss + newCss, 'utf-8');
1502
+ catch (error) {
1503
+ if (!isProduction) {
1504
+ try {
1505
+ fs.writeFileSync(VIRTUAL_FILE_PATH, lastValidCss, 'utf-8');
1429
1506
  }
1430
- else {
1431
- fs.writeFileSync(VIRTUAL_FILE_PATH, newCss, 'utf-8');
1507
+ catch (e) {
1432
1508
  }
1433
1509
  }
1510
+ return callback(error);
1434
1511
  }
1435
- return callback(null, transformedSource + postfix);
1436
1512
  }