@bamboocss/vite 1.34.0 → 1.35.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.
- package/dist/index.cjs +989 -742
- package/dist/index.d.cts +19 -264
- package/dist/index.d.mts +19 -264
- package/dist/index.mjs +987 -740
- package/package.json +12 -9
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,84 @@
|
|
|
1
1
|
import { Builder, loadConfigAndCreateContext } from "@bamboocss/node";
|
|
2
2
|
import { logger } from "@bamboocss/logger";
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
3
|
+
import { compact, createCssUncached, createMergeCss, esc, memo, toHash, truncateList, viewTransitionClassName } from "@bamboocss/shared";
|
|
4
|
+
import remapping from "@ampproject/remapping";
|
|
5
5
|
import MagicString from "magic-string";
|
|
6
|
+
import postcss from "postcss";
|
|
7
|
+
import selectorParser from "postcss-selector-parser";
|
|
6
8
|
import { dirname, relative, resolve } from "node:path";
|
|
9
|
+
import { resolveTsPathPattern } from "@bamboocss/config/ts-path";
|
|
10
|
+
import { box, maybeBoxNode } from "@bamboocss/extractor";
|
|
7
11
|
import { Node, SyntaxKind, VariableDeclarationKind } from "ts-morph";
|
|
8
|
-
|
|
9
|
-
|
|
12
|
+
//#region src/prune-static-css.ts
|
|
13
|
+
/** The generated declaration that identifies a Bamboo stylesheet after minification. */
|
|
14
|
+
const SENTINEL = "--made-with-bamboo";
|
|
15
|
+
/**
|
|
16
|
+
* Remove source-graph atoms no transformed module can emit.
|
|
17
|
+
*
|
|
18
|
+
* `prunableClasses` contains only atoms extracted from the source graph. Explicit `staticCss`
|
|
19
|
+
* additions are absent and survive as a safelist; graph atoms are governed by the transformed
|
|
20
|
+
* module reachability set, regardless of whether they originated in `css()` or a recipe.
|
|
21
|
+
*/
|
|
22
|
+
const pruneStaticCss = (css, session, { prune = true } = {}) => {
|
|
23
|
+
if (!css.includes(SENTINEL)) return css;
|
|
24
|
+
const root = postcss.parse(css);
|
|
25
|
+
const isUtilityRule = (rule) => {
|
|
26
|
+
let parent = rule.parent;
|
|
27
|
+
while (parent) {
|
|
28
|
+
if (parent.type === "atrule") {
|
|
29
|
+
const atRule = parent;
|
|
30
|
+
if (atRule.name === "layer" && atRule.params === session.utilityLayer) return true;
|
|
31
|
+
}
|
|
32
|
+
parent = parent.parent;
|
|
33
|
+
}
|
|
34
|
+
return false;
|
|
35
|
+
};
|
|
36
|
+
if (prune) root.walkRules((rule) => {
|
|
37
|
+
if (!isUtilityRule(rule)) return;
|
|
38
|
+
const classes = /* @__PURE__ */ new Set();
|
|
39
|
+
try {
|
|
40
|
+
selectorParser((selectors) => {
|
|
41
|
+
selectors.walkClasses((classNode) => {
|
|
42
|
+
classes.add(classNode.toString().slice(1));
|
|
43
|
+
});
|
|
44
|
+
}).processSync(rule.selector);
|
|
45
|
+
} catch {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (classes.size !== 1) return;
|
|
49
|
+
const [className] = classes;
|
|
50
|
+
if (!className || !session.prunableClasses.has(className) || session.usedClasses.has(className)) return;
|
|
51
|
+
rule.remove();
|
|
52
|
+
});
|
|
53
|
+
let removed = true;
|
|
54
|
+
while (removed) {
|
|
55
|
+
removed = false;
|
|
56
|
+
root.walkAtRules((rule) => {
|
|
57
|
+
if (rule.nodes?.length !== 0) return;
|
|
58
|
+
rule.remove();
|
|
59
|
+
removed = true;
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
if (session.denseClassNames) root.walkRules((rule) => {
|
|
63
|
+
if (!isUtilityRule(rule)) return;
|
|
64
|
+
const transitionClasses = /* @__PURE__ */ new Set();
|
|
65
|
+
try {
|
|
66
|
+
rule.selector = selectorParser((selectors) => {
|
|
67
|
+
selectors.walkClasses((classNode) => {
|
|
68
|
+
if (!session.prunableClasses.has(classNode.toString().slice(1))) return;
|
|
69
|
+
if (session.viewTransitionClasses.has(classNode.value)) transitionClasses.add(classNode.value);
|
|
70
|
+
classNode.value = session.allocateClassString(classNode.value);
|
|
71
|
+
});
|
|
72
|
+
}).processSync(rule.selector);
|
|
73
|
+
} catch {}
|
|
74
|
+
if (transitionClasses.size) rule.walkDecls("view-transition-class", (declaration) => {
|
|
75
|
+
if (!transitionClasses.has(declaration.value)) return;
|
|
76
|
+
declaration.value = session.allocateClassString(declaration.value);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
return root.toString();
|
|
80
|
+
};
|
|
81
|
+
//#endregion
|
|
10
82
|
//#region src/css.ts
|
|
11
83
|
/**
|
|
12
84
|
* What a project imports to get the stylesheet.
|
|
@@ -21,6 +93,76 @@ const VIRTUAL_CSS_ID = "virtual:bamboo.css";
|
|
|
21
93
|
* not to try reading it off disk.
|
|
22
94
|
*/
|
|
23
95
|
const RESOLVED_ID = `\0${VIRTUAL_CSS_ID}`;
|
|
96
|
+
const INLINE_SOURCE_MAP = /\n?\/\/# sourceMappingURL=data:application\/json[^\n]*$/;
|
|
97
|
+
/** Rewrite one generated chunk without invalidating all mappings after the changed string. */
|
|
98
|
+
const replaceChunkReference = (chunk, bundle, previous, next, sourcemap) => {
|
|
99
|
+
if (!chunk.code.includes(previous)) return;
|
|
100
|
+
const magic = new MagicString(chunk.code);
|
|
101
|
+
let index = chunk.code.indexOf(previous);
|
|
102
|
+
while (index !== -1) {
|
|
103
|
+
magic.overwrite(index, index + previous.length, next);
|
|
104
|
+
index = chunk.code.indexOf(previous, index + previous.length);
|
|
105
|
+
}
|
|
106
|
+
chunk.code = magic.toString();
|
|
107
|
+
if (!chunk.map) return;
|
|
108
|
+
const file = chunk.map.file;
|
|
109
|
+
const debugId = chunk.map.debugId;
|
|
110
|
+
const combined = remapping([magic.generateMap({
|
|
111
|
+
source: chunk.fileName,
|
|
112
|
+
hires: "boundary"
|
|
113
|
+
}), chunk.map], () => null);
|
|
114
|
+
if (file) combined.file = file;
|
|
115
|
+
if (debugId) combined.debugId = debugId;
|
|
116
|
+
const rollupMap = combined;
|
|
117
|
+
rollupMap.toUrl = () => `data:application/json;charset=utf-8;base64,${Buffer.from(combined.toString()).toString("base64")}`;
|
|
118
|
+
chunk.map = rollupMap;
|
|
119
|
+
if (sourcemap === "inline") {
|
|
120
|
+
chunk.code = chunk.code.replace(INLINE_SOURCE_MAP, "");
|
|
121
|
+
chunk.code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(combined.toString()).toString("base64")}`;
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const mapAsset = bundle[`${chunk.fileName}.map`];
|
|
125
|
+
if (mapAsset?.type === "asset") mapAsset.source = combined.toString();
|
|
126
|
+
};
|
|
127
|
+
/** Replace an emitted filename wherever Vite or Rollup has already recorded it. */
|
|
128
|
+
const replaceAssetReferences = (bundle, previous, next, sourcemap) => {
|
|
129
|
+
const replace = (value) => value.replaceAll(previous, next);
|
|
130
|
+
for (const output of Object.values(bundle)) {
|
|
131
|
+
if (output.type === "asset") {
|
|
132
|
+
if (typeof output.source === "string") output.source = replace(output.source);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
replaceChunkReference(output, bundle, previous, next, sourcemap);
|
|
136
|
+
output.referencedFiles = output.referencedFiles.map(replace);
|
|
137
|
+
const importedCss = output.viteMetadata?.importedCss;
|
|
138
|
+
if (importedCss?.delete(previous)) importedCss.add(next);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* Prune and rename compiler-owned CSS, then give changed assets a hash of their final bytes.
|
|
143
|
+
*
|
|
144
|
+
* Rollup has already expanded `[hash]` when `generateBundle` runs. Mutating only `source`
|
|
145
|
+
* would therefore leave two different reachable subsets under one CDN key. The extra final
|
|
146
|
+
* hash is not cosmetic: it makes late graph reachability cache-safe.
|
|
147
|
+
*/
|
|
148
|
+
const optimizeStaticCssAssets = (bundle, session) => {
|
|
149
|
+
for (const [bundleName, output] of Object.entries(bundle)) {
|
|
150
|
+
if (output.type !== "asset") continue;
|
|
151
|
+
const source = typeof output.source === "string" ? output.source : Buffer.from(output.source).toString();
|
|
152
|
+
if (!source.includes("--made-with-bamboo")) continue;
|
|
153
|
+
const optimized = pruneStaticCss(source, session);
|
|
154
|
+
output.source = optimized;
|
|
155
|
+
if (optimized === source) continue;
|
|
156
|
+
const nextName = output.fileName.replace(/\.css$/, `.b-${toHash(optimized)}.css`);
|
|
157
|
+
if (nextName === output.fileName) continue;
|
|
158
|
+
if (bundle[nextName] && bundle[nextName] !== output) throw new Error(`bamboocss: final CSS asset name collision at ${JSON.stringify(nextName)}.`);
|
|
159
|
+
const previous = output.fileName;
|
|
160
|
+
output.fileName = nextName;
|
|
161
|
+
replaceAssetReferences(bundle, previous, nextName, session.sourcemap);
|
|
162
|
+
delete bundle[bundleName];
|
|
163
|
+
bundle[nextName] = output;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
24
166
|
/**
|
|
25
167
|
* Serve bamboo's stylesheet as a virtual module, in dev and in build.
|
|
26
168
|
*
|
|
@@ -34,10 +176,11 @@ const RESOLVED_ID = `\0${VIRTUAL_CSS_ID}`;
|
|
|
34
176
|
* `styles.css` and asking the project to import it means the build reads a file the same
|
|
35
177
|
* process just wrote, which is a race on any watch rebuild.
|
|
36
178
|
*/
|
|
37
|
-
const bamboocssCss = (options
|
|
38
|
-
const { configPath, cwd } = options;
|
|
179
|
+
const bamboocssCss = (options) => {
|
|
180
|
+
const { configPath, cwd, session } = options;
|
|
39
181
|
const builder = new Builder();
|
|
40
182
|
let server;
|
|
183
|
+
let command = "build";
|
|
41
184
|
/**
|
|
42
185
|
* Serialised, because both `load` and the watcher can reach it and `Builder` keeps one
|
|
43
186
|
* context. Two overlapping passes would extract into the same encoder and emit the
|
|
@@ -51,7 +194,33 @@ const bamboocssCss = (options = {}) => {
|
|
|
51
194
|
});
|
|
52
195
|
await builder.emit();
|
|
53
196
|
builder.extract();
|
|
54
|
-
|
|
197
|
+
if (builder.context?.config.polyfill) throw new Error("bamboocss: the cascade-layer polyfill is incompatible with compiled atomic styles. The polyfill removes the utility-layer boundary required for safe atom reachability and renaming.");
|
|
198
|
+
if (builder.context) {
|
|
199
|
+
session.cssLoaded = true;
|
|
200
|
+
session.utilityLayer = builder.context.config.layers?.utilities ?? "utilities";
|
|
201
|
+
session.extractedFiles.clear();
|
|
202
|
+
for (const file of builder.context.getFiles()) session.extractedFiles.add(builder.context.runtime.path.abs(builder.context.config.cwd, file));
|
|
203
|
+
}
|
|
204
|
+
let graphAtomHashes;
|
|
205
|
+
if (builder.context) {
|
|
206
|
+
builder.context.encoder.atomizeObservedRecipes();
|
|
207
|
+
graphAtomHashes = new Set(builder.context.encoder.atomic);
|
|
208
|
+
}
|
|
209
|
+
const css = builder.toCss({
|
|
210
|
+
layerParams: true,
|
|
211
|
+
includeRecipes: false
|
|
212
|
+
});
|
|
213
|
+
session.prunableClasses.clear();
|
|
214
|
+
session.viewTransitionClasses.clear();
|
|
215
|
+
if (graphAtomHashes && builder.context) {
|
|
216
|
+
const decoder = builder.context.decoder.collect(builder.context.encoder);
|
|
217
|
+
for (const atom of decoder.atomic) if (graphAtomHashes.has(atom.hash)) session.prunableClasses.add(atom.className);
|
|
218
|
+
for (const transition of decoder.view_transitions) {
|
|
219
|
+
session.viewTransitionClasses.add(transition.className);
|
|
220
|
+
session.prunableClasses.add(esc(transition.className));
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return command === "serve" ? pruneStaticCss(css, session, { prune: false }) : css;
|
|
55
224
|
};
|
|
56
225
|
const generate = () => {
|
|
57
226
|
pending = Promise.resolve(pending).catch(() => void 0).then(build);
|
|
@@ -59,6 +228,10 @@ const bamboocssCss = (options = {}) => {
|
|
|
59
228
|
};
|
|
60
229
|
return {
|
|
61
230
|
name: "bamboocss:css",
|
|
231
|
+
configResolved(config) {
|
|
232
|
+
command = config.command;
|
|
233
|
+
session.sourcemap = config.build.sourcemap;
|
|
234
|
+
},
|
|
62
235
|
resolveId(id) {
|
|
63
236
|
if (id === "virtual:bamboo.css") return RESOLVED_ID;
|
|
64
237
|
return null;
|
|
@@ -78,20 +251,23 @@ const bamboocssCss = (options = {}) => {
|
|
|
78
251
|
const mod = server?.moduleGraph.getModuleById(RESOLVED_ID);
|
|
79
252
|
if (!mod) return;
|
|
80
253
|
server?.moduleGraph.invalidateModule(mod);
|
|
81
|
-
server?.
|
|
82
|
-
type: "update",
|
|
83
|
-
updates: []
|
|
84
|
-
});
|
|
254
|
+
server?.reloadModule(mod);
|
|
85
255
|
logger.debug("vite", `styles invalidated by ${file}`);
|
|
86
256
|
};
|
|
87
257
|
devServer.watcher.on("change", invalidate);
|
|
88
258
|
devServer.watcher.on("add", invalidate);
|
|
89
259
|
devServer.watcher.on("unlink", invalidate);
|
|
260
|
+
},
|
|
261
|
+
generateBundle: {
|
|
262
|
+
order: "post",
|
|
263
|
+
handler(_, bundle) {
|
|
264
|
+
optimizeStaticCssAssets(bundle, session);
|
|
265
|
+
}
|
|
90
266
|
}
|
|
91
267
|
};
|
|
92
268
|
};
|
|
93
269
|
//#endregion
|
|
94
|
-
//#region src/fold-
|
|
270
|
+
//#region src/fold-analysis.ts
|
|
95
271
|
/**
|
|
96
272
|
* Statically resolvable means: every box in the tree carries a known value.
|
|
97
273
|
*
|
|
@@ -106,7 +282,10 @@ const isStaticBox = (node, seen = /* @__PURE__ */ new Set()) => {
|
|
|
106
282
|
seen.add(node);
|
|
107
283
|
if (box.isUnresolvable(node) || box.isConditional(node)) return false;
|
|
108
284
|
if (!("type" in node) || node.type == null) return false;
|
|
109
|
-
if (box.isLiteral(node) && node.value === void 0)
|
|
285
|
+
if (box.isLiteral(node) && node.value === void 0) {
|
|
286
|
+
const source = node.getNode?.();
|
|
287
|
+
return Boolean(source && Node.isIdentifier(source) && source.getText() === "undefined");
|
|
288
|
+
}
|
|
110
289
|
if (box.isMap(node)) {
|
|
111
290
|
for (const child of node.value.values()) if (!isStaticBox(child, seen)) return false;
|
|
112
291
|
return true;
|
|
@@ -231,8 +410,8 @@ const isCollapsedBinary = (node) => Node.isBinaryExpression(node) && COLLAPSED_B
|
|
|
231
410
|
* Spreads are the conservative case. `{ ...base }` where `base` is a static local
|
|
232
411
|
* object *is* resolved by the extractor, but a resolved spread and an unresolved one
|
|
233
412
|
* are indistinguishable once flattened into the map — both just contribute keys, or
|
|
234
|
-
* fail to. Rather than guess
|
|
235
|
-
*
|
|
413
|
+
* fail to. Rather than guess and erase evaluation the compiler cannot reproduce, the call
|
|
414
|
+
* is rejected.
|
|
236
415
|
*/
|
|
237
416
|
/**
|
|
238
417
|
* What a property's value is written as. A shorthand names it, so the name *is* the
|
|
@@ -277,37 +456,6 @@ const accountsForSource = (node, boxNode) => {
|
|
|
277
456
|
return true;
|
|
278
457
|
};
|
|
279
458
|
/**
|
|
280
|
-
* A property whose value is a ternary is not dynamic, it is *finite*: both branches are
|
|
281
|
-
* known, so each can be resolved now and the choice left to a ternary between two
|
|
282
|
-
* literals. That removes the `css()` call without needing to know which branch runs.
|
|
283
|
-
*
|
|
284
|
-
* Independent conditionals stay linear rather than multiplying, because each property
|
|
285
|
-
* contributes its own ternary. Two conditionals give two ternaries, not four
|
|
286
|
-
* combinations — which is only sound because `collides()` already rules out two
|
|
287
|
-
* properties resolving to the same class, so no combination can interact with another.
|
|
288
|
-
*/
|
|
289
|
-
const finiteBranches = (key, value, boxNode, deps) => {
|
|
290
|
-
if (!box.isConditional(boxNode)) return void 0;
|
|
291
|
-
const node = boxNode.getNode();
|
|
292
|
-
if (!Node.isConditionalExpression(node)) return void 0;
|
|
293
|
-
if (!value || unwrapExpression(value) !== node) return void 0;
|
|
294
|
-
const [whenTrue, whenFalse] = [[node.getWhenTrue(), boxNode.whenTrue], [node.getWhenFalse(), boxNode.whenFalse]].map(([source, branch]) => {
|
|
295
|
-
if (!deps.isStatic(branch)) return void 0;
|
|
296
|
-
if (!deps.isAccounted(source, branch)) return void 0;
|
|
297
|
-
const value = unbox(branch).raw;
|
|
298
|
-
try {
|
|
299
|
-
return deps.runtimeCss({ [key]: value });
|
|
300
|
-
} catch {
|
|
301
|
-
return;
|
|
302
|
-
}
|
|
303
|
-
});
|
|
304
|
-
if (whenTrue === void 0 || whenFalse === void 0) return void 0;
|
|
305
|
-
if (!whenTrue && !whenFalse) return void 0;
|
|
306
|
-
return `${node.getCondition().getText()} ? ${JSON.stringify(whenTrue)} : ${JSON.stringify(whenFalse)}`;
|
|
307
|
-
};
|
|
308
|
-
/** The binding the leaf fold calls, exported by the generated css module. */
|
|
309
|
-
const LEAF_HELPER = "cssLeaf";
|
|
310
|
-
/**
|
|
311
459
|
* Memo keyed on a file, thrown away when its text is replaced.
|
|
312
460
|
*
|
|
313
461
|
* A plain `WeakMap<SourceFile, …>` is wrong here: ts-morph reuses the wrapper when a path
|
|
@@ -328,18 +476,6 @@ const byText = (cache, sourceFile, compute) => {
|
|
|
328
476
|
return value;
|
|
329
477
|
};
|
|
330
478
|
/**
|
|
331
|
-
* The modules this file imports from, as specifiers.
|
|
332
|
-
*
|
|
333
|
-
* Only strings are cached. A ts-morph *node* cannot be: re-adding a path forgets the old
|
|
334
|
-
* nodes even when the text is identical, so the memo would hand back wrappers that throw
|
|
335
|
-
* on access. Strings outlive that, and answer the one question worth asking before the
|
|
336
|
-
* helper resolution walks the declarations — whether this file imports from bamboo at
|
|
337
|
-
* all. On a module of many elements that never fold, that walk was the entire cost of
|
|
338
|
-
* trying.
|
|
339
|
-
*/
|
|
340
|
-
const specifierCache = /* @__PURE__ */ new WeakMap();
|
|
341
|
-
const importsAnything = (sourceFile, matches) => byText(specifierCache, sourceFile, () => sourceFile.getImportDeclarations().map((declaration) => declaration.getModuleSpecifierValue())).some(matches);
|
|
342
|
-
/**
|
|
343
479
|
* Every name declared at module scope, which is what an added import could collide with.
|
|
344
480
|
*
|
|
345
481
|
* This replaced `sourceFile.getLocals()`. That was precise, but it goes through the
|
|
@@ -450,282 +586,6 @@ const collectModuleScopeNames = (sourceFile) => {
|
|
|
450
586
|
}
|
|
451
587
|
return names;
|
|
452
588
|
};
|
|
453
|
-
/**
|
|
454
|
-
* The local name an already-imported bamboo binding goes by.
|
|
455
|
-
*
|
|
456
|
-
* `ensureCxImport` answers this too, but it also decides whether a *missing* binding can
|
|
457
|
-
* be added, which needs `getLocals()` — the compiler's binder over the whole module. This
|
|
458
|
-
* runs for every candidate whether it folds or not, so it stops at what the import
|
|
459
|
-
* declarations already say and never forces that.
|
|
460
|
-
*/
|
|
461
|
-
const findBambooBinding = (call, imported, isBambooCssModule, isShadowed) => {
|
|
462
|
-
if (!importsAnything(call.getSourceFile(), isBambooCssModule)) return void 0;
|
|
463
|
-
for (const declaration of call.getSourceFile().getImportDeclarations()) {
|
|
464
|
-
if (declaration.isTypeOnly() || !isBambooCssModule(declaration.getModuleSpecifierValue())) continue;
|
|
465
|
-
for (const named of declaration.getNamedImports()) {
|
|
466
|
-
if (named.isTypeOnly() || named.getNameNode().getText() !== imported) continue;
|
|
467
|
-
const local = (named.getAliasNode() ?? named.getNameNode()).getText();
|
|
468
|
-
return isShadowed(call, local) ? void 0 : local;
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
};
|
|
472
|
-
/**
|
|
473
|
-
* A value that survives the class pipeline unchanged, so the class built around it is the
|
|
474
|
-
* prefix and nothing else: no whitespace for `sanitize` to collapse, no `!` for the
|
|
475
|
-
* important regex, no space for `withoutSpace`, and nothing a token or condition could
|
|
476
|
-
* plausibly be named.
|
|
477
|
-
*/
|
|
478
|
-
const LEAF_SENTINEL = "bamboo0leaf0sentinel0";
|
|
479
|
-
/**
|
|
480
|
-
* A property the extractor could not resolve is *open-ended* rather than finite — but its
|
|
481
|
-
* class is still `prefix + value`, and the prefix is known now.
|
|
482
|
-
*
|
|
483
|
-
* `utility.transform` is string construction over a table fixed at build time, and
|
|
484
|
-
* nothing consults which rules were emitted. So `css({ color: tone })` already returns
|
|
485
|
-
* `c_<tone>` for a value the extractor never saw, with no CSS behind it. Emitting that
|
|
486
|
-
* string directly cannot be less correct than the call it replaces.
|
|
487
|
-
*
|
|
488
|
-
* The prefix is read off the real implementation rather than rebuilt: resolving a
|
|
489
|
-
* sentinel through `runtimeCss` applies the shorthand table and the utility's class name
|
|
490
|
-
* in one step. It also self-gates — a hashed or grouped class does not contain the
|
|
491
|
-
* sentinel, so both modes decline here without this having to read the config.
|
|
492
|
-
*
|
|
493
|
-
* Shared with the element surface, which asks the same question about a JSX style prop.
|
|
494
|
-
*
|
|
495
|
-
* Top level only, like the finite lowering beside it. A nested leaf's class carries its
|
|
496
|
-
* condition path, which the prefix would describe correctly — but the helper's fallback
|
|
497
|
-
* rebuilds `{ [prop]: value }` to hand back to `css()`, and that reconstruction has to
|
|
498
|
-
* carry the same path or the declined shape resolves without its condition.
|
|
499
|
-
*/
|
|
500
|
-
const leafPrefix = (key, ctx, runtimeCss) => {
|
|
501
|
-
if (ctx.conditions.isCondition(key)) return void 0;
|
|
502
|
-
let resolved;
|
|
503
|
-
try {
|
|
504
|
-
resolved = runtimeCss({ [key]: LEAF_SENTINEL });
|
|
505
|
-
} catch {
|
|
506
|
-
return;
|
|
507
|
-
}
|
|
508
|
-
if (!resolved.endsWith(LEAF_SENTINEL)) return void 0;
|
|
509
|
-
const prefix = resolved.slice(0, -21);
|
|
510
|
-
return !prefix || prefix.includes(" ") ? void 0 : prefix;
|
|
511
|
-
};
|
|
512
|
-
/**
|
|
513
|
-
* Written as an object or an array, this is a condition block or a responsive list: one
|
|
514
|
-
* class per entry rather than one class. `leafClass` declines both at runtime and falls
|
|
515
|
-
* back, so lowering one is not wrong — it is a guaranteed round trip through the fallback,
|
|
516
|
-
* which is the same reason a condition key is declined.
|
|
517
|
-
*/
|
|
518
|
-
const isWrittenAsCollection = (value) => {
|
|
519
|
-
const inner = unwrapExpression(value);
|
|
520
|
-
return Node.isObjectLiteralExpression(inner) || Node.isArrayLiteralExpression(inner);
|
|
521
|
-
};
|
|
522
|
-
/** The call this surface emits in place of the property. */
|
|
523
|
-
const leafCall = (prefix, key, valueText, name = LEAF_HELPER) => `${name}(${JSON.stringify(prefix)}, ${JSON.stringify(key)}, ${valueText})`;
|
|
524
|
-
const dynamicLeaf = (key, value, deps) => {
|
|
525
|
-
if (!deps.allowLeaf || !value) return void 0;
|
|
526
|
-
if (isWrittenAsCollection(value)) return void 0;
|
|
527
|
-
const prefix = leafPrefix(key, deps.ctx, deps.runtimeCss);
|
|
528
|
-
return prefix === void 0 ? void 0 : leafCall(prefix, key, value.getText(), deps.leafName ?? "cssLeaf");
|
|
529
|
-
};
|
|
530
|
-
/**
|
|
531
|
-
* Properties are partitioned whole rather than recursed into. A top-level property is
|
|
532
|
-
* either entirely static or entirely dynamic, which keeps the reconstructed object a
|
|
533
|
-
* verbatim slice of the source and avoids rebuilding nested conditions by hand.
|
|
534
|
-
*/
|
|
535
|
-
const planPartialFold = (argument, boxNode, styles, deps) => {
|
|
536
|
-
const partition = partitionObject(argument, boxNode, styles, deps);
|
|
537
|
-
if (!partition) return void 0;
|
|
538
|
-
const className = deps.runtimeCss(partition.staticStyles);
|
|
539
|
-
if (!className && !partition.finite.length) return void 0;
|
|
540
|
-
return {
|
|
541
|
-
className,
|
|
542
|
-
dynamicText: partition.dynamicText.length ? `{ ${partition.dynamicText.join(", ")} }` : void 0,
|
|
543
|
-
finite: partition.finite,
|
|
544
|
-
finiteFirst: partition.finiteFirst
|
|
545
|
-
};
|
|
546
|
-
};
|
|
547
|
-
/**
|
|
548
|
-
* Split one object level, recursing into a block that is part static and part dynamic.
|
|
549
|
-
*
|
|
550
|
-
* Without the recursion a single dynamic leaf sends its whole block to the runtime:
|
|
551
|
-
* `{ _hover: { color: 'red.300', bg: p } }` loses the resolved `color` even though
|
|
552
|
-
* nothing about it depends on `p`. That is a precision loss rather than a wrong answer,
|
|
553
|
-
* but it costs exactly the calls a component re-renders most.
|
|
554
|
-
*
|
|
555
|
-
* A class is identified by its condition path *and* its property, so `_hover.color` in
|
|
556
|
-
* one half and `_hover.bg` in the other cannot collide, and neither can `color` against
|
|
557
|
-
* `_hover.color`. Collision is therefore checked per level, among siblings.
|
|
558
|
-
*
|
|
559
|
-
* The static subtree is read from the extracted data rather than rebuilt: the extractor
|
|
560
|
-
* has already dropped the unresolvable leaves, so `styles[key]` for a mixed block is
|
|
561
|
-
* exactly the resolvable part. The dynamic side is taken from source text, so nothing
|
|
562
|
-
* depends on that pruning being complete.
|
|
563
|
-
*/
|
|
564
|
-
const partitionObject = (node, boxNode, styles, deps, topLevel = true) => {
|
|
565
|
-
if (!box.isMap(boxNode)) return void 0;
|
|
566
|
-
const { ctx, isAccounted, isStatic } = deps;
|
|
567
|
-
const staticKeys = [];
|
|
568
|
-
const staticStyles = {};
|
|
569
|
-
const seenKeys = /* @__PURE__ */ new Set();
|
|
570
|
-
/**
|
|
571
|
-
* Everything not resolved outright, in source order. Kept as one list because a ternary
|
|
572
|
-
* that cannot be lowered has to become a runtime property *in its original position*,
|
|
573
|
-
* and because whether the two kinds interleave is a property of that order.
|
|
574
|
-
*/
|
|
575
|
-
const slots = [];
|
|
576
|
-
for (const property of node.getProperties()) {
|
|
577
|
-
if (!Node.isPropertyAssignment(property) && !Node.isShorthandPropertyAssignment(property)) return void 0;
|
|
578
|
-
const nameNode = property.getNameNode();
|
|
579
|
-
if (Node.isComputedPropertyName(nameNode)) return void 0;
|
|
580
|
-
const key = Node.isStringLiteral(nameNode) || Node.isNumericLiteral(nameNode) ? String(nameNode.getLiteralValue()) : nameNode.getText();
|
|
581
|
-
if (seenKeys.has(key)) return void 0;
|
|
582
|
-
seenKeys.add(key);
|
|
583
|
-
const value = valueOf(property);
|
|
584
|
-
const valueBox = boxNode.value.get(key);
|
|
585
|
-
if (key in styles && isStatic(valueBox) && isAccounted(value, valueBox)) {
|
|
586
|
-
staticKeys.push(key);
|
|
587
|
-
staticStyles[key] = styles[key];
|
|
588
|
-
continue;
|
|
589
|
-
}
|
|
590
|
-
if (topLevel) {
|
|
591
|
-
const branches = finiteBranches(key, value, valueBox, deps);
|
|
592
|
-
if (branches) {
|
|
593
|
-
slots.push({
|
|
594
|
-
key,
|
|
595
|
-
kind: "finite",
|
|
596
|
-
lowered: {
|
|
597
|
-
expression: branches,
|
|
598
|
-
emitsLiterals: true
|
|
599
|
-
},
|
|
600
|
-
text: property.getText()
|
|
601
|
-
});
|
|
602
|
-
continue;
|
|
603
|
-
}
|
|
604
|
-
const leaf = dynamicLeaf(key, value, deps);
|
|
605
|
-
if (leaf) {
|
|
606
|
-
slots.push({
|
|
607
|
-
key,
|
|
608
|
-
kind: "finite",
|
|
609
|
-
lowered: {
|
|
610
|
-
expression: leaf,
|
|
611
|
-
emitsLiterals: false
|
|
612
|
-
},
|
|
613
|
-
text: property.getText()
|
|
614
|
-
});
|
|
615
|
-
continue;
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
const nested = value && Node.isObjectLiteralExpression(value) && isAccounted(value, valueBox) ? partitionObject(value, valueBox, styles[key] ?? {}, deps, false) : void 0;
|
|
619
|
-
if (nested && Object.keys(nested.staticStyles).length && nested.dynamicText.length) {
|
|
620
|
-
staticKeys.push(key);
|
|
621
|
-
staticStyles[key] = nested.staticStyles;
|
|
622
|
-
slots.push({
|
|
623
|
-
key,
|
|
624
|
-
kind: "dynamic",
|
|
625
|
-
split: true,
|
|
626
|
-
text: `${property.getNameNode().getText()}: { ${nested.dynamicText.join(", ")} }`
|
|
627
|
-
});
|
|
628
|
-
continue;
|
|
629
|
-
}
|
|
630
|
-
slots.push({
|
|
631
|
-
key,
|
|
632
|
-
kind: "dynamic",
|
|
633
|
-
text: property.getText()
|
|
634
|
-
});
|
|
635
|
-
}
|
|
636
|
-
const demote = (slot) => {
|
|
637
|
-
slot.kind = "dynamic";
|
|
638
|
-
slot.lowered = void 0;
|
|
639
|
-
};
|
|
640
|
-
const contested = () => slots.filter((slot) => slot.kind === "dynamic" && !slot.split).map((slot) => slot.key);
|
|
641
|
-
for (;;) {
|
|
642
|
-
const lowered = slots.filter((slot) => slot.kind === "finite");
|
|
643
|
-
const dynamic = contested();
|
|
644
|
-
const offender = lowered.find((slot, index) => collides([slot.key], [
|
|
645
|
-
...staticKeys,
|
|
646
|
-
...dynamic,
|
|
647
|
-
...lowered.slice(0, index).map((kept) => kept.key)
|
|
648
|
-
], ctx));
|
|
649
|
-
if (!offender) break;
|
|
650
|
-
demote(offender);
|
|
651
|
-
}
|
|
652
|
-
const written = () => slots.map((slot) => slot.kind === "finite" ? "f" : "d").join("");
|
|
653
|
-
while (!/^f*d*$/.test(written()) && !/^d*f*$/.test(written())) demote(slots.findLast((slot) => slot.kind === "finite"));
|
|
654
|
-
const dynamicText = slots.filter((slot) => slot.kind === "dynamic").map((slot) => slot.text);
|
|
655
|
-
const finite = slots.filter((slot) => slot.kind === "finite").map((slot) => slot.lowered);
|
|
656
|
-
if (!staticKeys.length && !finite.length) return void 0;
|
|
657
|
-
if (!dynamicText.length && !finite.length) return void 0;
|
|
658
|
-
if (collides(staticKeys, contested(), ctx)) return void 0;
|
|
659
|
-
return {
|
|
660
|
-
staticStyles,
|
|
661
|
-
dynamicText,
|
|
662
|
-
finite,
|
|
663
|
-
finiteFirst: !written().startsWith("d")
|
|
664
|
-
};
|
|
665
|
-
};
|
|
666
|
-
/**
|
|
667
|
-
* Do the two halves resolve to a shared property?
|
|
668
|
-
*
|
|
669
|
-
* Compared after shorthand resolution, since that is where distinct keys become the same
|
|
670
|
-
* property. An unrecognised key resolves to itself, so two distinct unknown keys are read
|
|
671
|
-
* as distinct — which is right for atomic output, where one class is emitted per key.
|
|
672
|
-
*/
|
|
673
|
-
const collides = (staticKeys, dynamicKeys, ctx) => {
|
|
674
|
-
if (staticKeys.includes("base") || dynamicKeys.includes("base")) return true;
|
|
675
|
-
const resolve = (key) => ctx.utility.hasShorthand ? ctx.utility.resolveShorthand(key) : key;
|
|
676
|
-
const resolvedStatic = new Set(staticKeys.map(resolve));
|
|
677
|
-
return dynamicKeys.some((key) => resolvedStatic.has(resolve(key)));
|
|
678
|
-
};
|
|
679
|
-
/**
|
|
680
|
-
* The `cx` binding to call, adding it to the import that already brings in the style
|
|
681
|
-
* helper when it is not there yet.
|
|
682
|
-
*
|
|
683
|
-
* Reusing that declaration rather than writing a new one avoids having to guess the
|
|
684
|
-
* module specifier, which varies with `importMap`, path aliases and how the project
|
|
685
|
-
* spells its outdir.
|
|
686
|
-
*/
|
|
687
|
-
const ensureCxImport = (call, calleeRoot, isBambooCssModule, isGeneratedCssModule, isShadowed, extra = []) => {
|
|
688
|
-
const sourceFile = call.getSourceFile();
|
|
689
|
-
const wanted = ["cx", ...extra];
|
|
690
|
-
const resolved = {};
|
|
691
|
-
let host;
|
|
692
|
-
for (const declaration of sourceFile.getImportDeclarations()) {
|
|
693
|
-
const mod = declaration.getModuleSpecifierValue();
|
|
694
|
-
for (const named of declaration.getNamedImports()) {
|
|
695
|
-
const local = (named.getAliasNode() ?? named.getNameNode()).getText();
|
|
696
|
-
const imported = named.getNameNode().getText();
|
|
697
|
-
if (wanted.includes(imported) && !(imported in resolved)) {
|
|
698
|
-
if (declaration.isTypeOnly() || named.isTypeOnly()) return void 0;
|
|
699
|
-
if (!isBambooCssModule(mod)) return void 0;
|
|
700
|
-
if (isShadowed(call, local)) return void 0;
|
|
701
|
-
resolved[imported] = local;
|
|
702
|
-
}
|
|
703
|
-
if (local === calleeRoot) host = declaration;
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
const missing = wanted.filter((name) => !(name in resolved));
|
|
707
|
-
if (!missing.length) return {
|
|
708
|
-
name: resolved.cx,
|
|
709
|
-
names: resolved
|
|
710
|
-
};
|
|
711
|
-
if (!host) return void 0;
|
|
712
|
-
if (!isGeneratedCssModule(host.getModuleSpecifierValue())) return void 0;
|
|
713
|
-
const declared = declaredAtModuleScope(sourceFile);
|
|
714
|
-
for (const name of missing) {
|
|
715
|
-
if (declared.has(name) || isShadowed(call, name)) return void 0;
|
|
716
|
-
resolved[name] = name;
|
|
717
|
-
}
|
|
718
|
-
const last = host.getNamedImports().at(-1);
|
|
719
|
-
if (!last) return void 0;
|
|
720
|
-
return {
|
|
721
|
-
name: resolved.cx,
|
|
722
|
-
names: resolved,
|
|
723
|
-
insert: {
|
|
724
|
-
pos: last.getEnd(),
|
|
725
|
-
names: missing
|
|
726
|
-
}
|
|
727
|
-
};
|
|
728
|
-
};
|
|
729
589
|
//#endregion
|
|
730
590
|
//#region src/fold-recipe.ts
|
|
731
591
|
/**
|
|
@@ -735,15 +595,12 @@ const ensureCxImport = (call, calleeRoot, isBambooCssModule, isGeneratedCssModul
|
|
|
735
595
|
* that names it. The parser records a definition under the name it was *imported* as (`cva`),
|
|
736
596
|
* and a call under the name the file *bound* (`badge`); this is what joins the two.
|
|
737
597
|
*
|
|
738
|
-
*
|
|
739
|
-
* a call of *either* as a recipe call, but an `sva` invocation returns one class per slot — an
|
|
740
|
-
* object, not a string — so there is no literal to substitute. Leaving slot recipes out of this
|
|
741
|
-
* map is what makes them decline as `unknown-recipe` instead of folding to a string that would
|
|
742
|
-
* break every consumer reading `.root` off it.
|
|
598
|
+
* Slot and ordinary recipes share one representation.
|
|
743
599
|
*/
|
|
744
600
|
const collectRecipeConfigs = (parserResult) => {
|
|
745
601
|
const configs = /* @__PURE__ */ new Map();
|
|
746
|
-
|
|
602
|
+
const definitions = [...parserResult.cva, ...parserResult.sva];
|
|
603
|
+
for (const definition of definitions) {
|
|
747
604
|
const node = definition.box?.getNode?.();
|
|
748
605
|
if (!node) continue;
|
|
749
606
|
const nameNode = ((Node.isCallExpression(node) ? node : node.getFirstAncestorByKind(SyntaxKind.CallExpression))?.getFirstAncestorByKind(SyntaxKind.VariableDeclaration))?.getNameNode();
|
|
@@ -760,21 +617,20 @@ const collectRecipeConfigs = (parserResult) => {
|
|
|
760
617
|
}
|
|
761
618
|
configs.set(nameNode.getText(), {
|
|
762
619
|
config,
|
|
763
|
-
name: getRecipeIdentity(config),
|
|
764
620
|
box: definition.box
|
|
765
621
|
});
|
|
766
622
|
}
|
|
767
623
|
return configs;
|
|
768
624
|
};
|
|
769
|
-
/**
|
|
770
|
-
const
|
|
625
|
+
/** Pick a complete precompiled StyleSet for one or more runtime recipe axes. */
|
|
626
|
+
const RECIPE_MAP_HELPER = "cvaMap";
|
|
627
|
+
/** Guard the exact compiler against accidentally materialising an enormous Cartesian product. */
|
|
628
|
+
const DEFAULT_MAX_RECIPE_STATES = 65536;
|
|
771
629
|
/** What `recipe.splitVariantProps` calls, reached directly once the call is lowered. */
|
|
772
630
|
const SPLIT_PROPS_HELPER = "splitProps";
|
|
773
|
-
const HELPER = RECIPE_PICK_HELPER;
|
|
774
631
|
/** Marker for a binding the fold must never resolve — declared twice, or unresolvable. */
|
|
775
632
|
const AMBIGUOUS = Object.freeze({
|
|
776
633
|
config: {},
|
|
777
|
-
name: "",
|
|
778
634
|
box: void 0
|
|
779
635
|
});
|
|
780
636
|
/** `.size`, or `["x-large"]` when the variant is not a valid identifier. */
|
|
@@ -816,10 +672,9 @@ const propertyKey = (nameNode) => {
|
|
|
816
672
|
if (Node.isNumericLiteral(nameNode)) return String(nameNode.getLiteralValue());
|
|
817
673
|
};
|
|
818
674
|
/**
|
|
819
|
-
* Make
|
|
675
|
+
* Make a generated compile helper callable at this call site, by whatever name the file gives it.
|
|
820
676
|
*
|
|
821
|
-
*
|
|
822
|
-
* matching the *callee* against an import. An inline recipe's callee is a local binding, so
|
|
677
|
+
* Unlike `cx`, an inline recipe's callee is a local binding, so
|
|
823
678
|
* there is nothing to match — the host here is any import of the generated css module, which
|
|
824
679
|
* a file defining a recipe necessarily has, since `cva` came from it.
|
|
825
680
|
*/
|
|
@@ -871,13 +726,18 @@ const ensureRecipeHelperImport = (imported, call, isBambooCssModule, isGenerated
|
|
|
871
726
|
* an unresolved variant does not merely omit a class, it can change which of several the
|
|
872
727
|
* recipe applies — so a partially-known selection is not foldable at all.
|
|
873
728
|
*/
|
|
874
|
-
const lowerRecipeCall = (call, entry,
|
|
729
|
+
const lowerRecipeCall = (call, entry, styleCompiler, isInert, resolvedSelection, slot, maxRecipeStates = DEFAULT_MAX_RECIPE_STATES) => {
|
|
875
730
|
if (!entry || entry === AMBIGUOUS) return {
|
|
876
731
|
kind: "decline",
|
|
877
732
|
reason: "unknown-recipe"
|
|
878
733
|
};
|
|
879
|
-
const { config
|
|
880
|
-
if (config.slots !== void 0)
|
|
734
|
+
const { config } = entry;
|
|
735
|
+
if (config.slots !== void 0) {
|
|
736
|
+
if (!Array.isArray(config.slots) || slot !== void 0 && !config.slots.includes(slot)) return {
|
|
737
|
+
kind: "decline",
|
|
738
|
+
reason: "unsupported-shape"
|
|
739
|
+
};
|
|
740
|
+
} else if (slot) return {
|
|
881
741
|
kind: "decline",
|
|
882
742
|
reason: "unsupported-shape"
|
|
883
743
|
};
|
|
@@ -913,16 +773,13 @@ const lowerRecipeCall = (call, entry, ctx, isInert, resolvedSelection) => {
|
|
|
913
773
|
/**
|
|
914
774
|
* `input(variantProps)` — a selection the build cannot see inside.
|
|
915
775
|
*
|
|
916
|
-
*
|
|
917
|
-
*
|
|
918
|
-
*
|
|
919
|
-
* selection through `createCss`, which *expands* conditions into one class per breakpoint,
|
|
920
|
-
* so a scalar lookup silently drops them. That is why this lowering is not applied to
|
|
921
|
-
* config recipes: for a dynamic axis the build cannot know which kind of value arrives.
|
|
776
|
+
* The compiled recipe contract accepts scalar declared variant values. A conditional
|
|
777
|
+
* object is not a finite selection value; responsiveness belongs inside a variant's style
|
|
778
|
+
* declaration, where the compiler can materialize its conditions ahead of time.
|
|
922
779
|
*
|
|
923
|
-
* The
|
|
924
|
-
*
|
|
925
|
-
*
|
|
780
|
+
* The complete StyleSets are knowable: the config declares every scalar value each axis
|
|
781
|
+
* accepts. This is the shape a wrapper component takes, where variants are its public API
|
|
782
|
+
* and therefore cannot be literals by definition.
|
|
926
783
|
*
|
|
927
784
|
* An identifier only. Each variant reads the binding again, and re-reading anything else —
|
|
928
785
|
* a call, a property access — would evaluate it once per axis instead of once.
|
|
@@ -1005,19 +862,51 @@ const lowerRecipeCall = (call, entry, ctx, isInert, resolvedSelection) => {
|
|
|
1005
862
|
* typecheck and does transform `.js`, so this is reachable.
|
|
1006
863
|
*/
|
|
1007
864
|
const everyEffectSurvives = () => effectful.every(({ key, text }) => dynamicAxes.get(key) === text);
|
|
1008
|
-
const
|
|
1009
|
-
|
|
1010
|
-
|
|
865
|
+
const compiledSelection = (selected) => {
|
|
866
|
+
if (Array.isArray(config.slots) && slot === void 0) {
|
|
867
|
+
const slots = {};
|
|
868
|
+
const classNames = /* @__PURE__ */ new Set();
|
|
869
|
+
for (const slotName of config.slots) {
|
|
870
|
+
const styles = styleCompiler.resolveRecipe(config, selected, slotName);
|
|
871
|
+
if (!styles) return void 0;
|
|
872
|
+
const className = styleCompiler.className(styles);
|
|
873
|
+
slots[slotName] = className;
|
|
874
|
+
for (const token of className.split(" ")) if (token) classNames.add(token);
|
|
875
|
+
}
|
|
876
|
+
return {
|
|
877
|
+
value: slots,
|
|
878
|
+
classNames: [...classNames]
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
const styles = styleCompiler.resolveRecipe(config, selected, slot);
|
|
882
|
+
if (!styles) return void 0;
|
|
883
|
+
const className = styleCompiler.className(styles);
|
|
884
|
+
return {
|
|
885
|
+
value: className,
|
|
886
|
+
classNames: className.split(" ").filter(Boolean),
|
|
887
|
+
styles
|
|
888
|
+
};
|
|
1011
889
|
};
|
|
1012
|
-
const format = classFormatter(ctx);
|
|
1013
890
|
if (dynamicAxes.size === 0) {
|
|
1014
891
|
if (!everyEffectSurvives()) return {
|
|
1015
892
|
kind: "decline",
|
|
1016
893
|
reason: "dynamic"
|
|
1017
894
|
};
|
|
1018
|
-
|
|
895
|
+
const compiled = compiledSelection(selection);
|
|
896
|
+
if (!compiled) return {
|
|
897
|
+
kind: "decline",
|
|
898
|
+
reason: "dynamic"
|
|
899
|
+
};
|
|
900
|
+
if (typeof compiled.value === "string") return {
|
|
1019
901
|
kind: "class",
|
|
1020
|
-
className:
|
|
902
|
+
className: compiled.value,
|
|
903
|
+
styles: compiled.styles
|
|
904
|
+
};
|
|
905
|
+
return {
|
|
906
|
+
kind: "slots",
|
|
907
|
+
expression: JSON.stringify(compiled.value),
|
|
908
|
+
classNames: compiled.classNames,
|
|
909
|
+
dynamic: false
|
|
1021
910
|
};
|
|
1022
911
|
}
|
|
1023
912
|
if (!everyEffectSurvives()) return {
|
|
@@ -1033,45 +922,126 @@ const lowerRecipeCall = (call, entry, ctx, isInert, resolvedSelection) => {
|
|
|
1033
922
|
};
|
|
1034
923
|
}
|
|
1035
924
|
for (const key of [...dynamicAxes.keys()]) if (!Object.hasOwn(config.variants ?? {}, key)) dynamicAxes.delete(key);
|
|
1036
|
-
if (dynamicAxes.size === 0)
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
continue;
|
|
1054
|
-
}
|
|
1055
|
-
const values = config.variants[key];
|
|
1056
|
-
const table = {};
|
|
1057
|
-
for (const value of Object.keys(values)) {
|
|
1058
|
-
const className = format(`${name}--${key}${ctx.utility.separator}${withoutSpace(value)}`);
|
|
1059
|
-
table[value] = ` ${className}`;
|
|
1060
|
-
classNames.push(className);
|
|
1061
|
-
}
|
|
1062
|
-
const fallbackValue = config.defaultVariants?.[key];
|
|
1063
|
-
const fallback = fallbackValue != null && values[fallbackValue] != null ? ` ${format(`${name}--${key}${ctx.utility.separator}${withoutSpace(fallbackValue)}`)}` : void 0;
|
|
1064
|
-
parts.push(`${HELPER}(${expression}, ${JSON.stringify(table)}${fallback === void 0 ? "" : `, ${JSON.stringify(fallback)}`})`);
|
|
925
|
+
if (dynamicAxes.size === 0) {
|
|
926
|
+
const compiled = compiledSelection(selection);
|
|
927
|
+
if (!compiled) return {
|
|
928
|
+
kind: "decline",
|
|
929
|
+
reason: "dynamic"
|
|
930
|
+
};
|
|
931
|
+
if (typeof compiled.value === "string") return {
|
|
932
|
+
kind: "class",
|
|
933
|
+
className: compiled.value,
|
|
934
|
+
styles: compiled.styles
|
|
935
|
+
};
|
|
936
|
+
return {
|
|
937
|
+
kind: "slots",
|
|
938
|
+
expression: JSON.stringify(compiled.value),
|
|
939
|
+
classNames: compiled.classNames,
|
|
940
|
+
dynamic: false
|
|
941
|
+
};
|
|
1065
942
|
}
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
943
|
+
/**
|
|
944
|
+
* Compile the finite recipe state space into a reduced decision table.
|
|
945
|
+
*
|
|
946
|
+
* Each leaf is a *complete* final StyleSet. This matters for declarations overridden by
|
|
947
|
+
* variants and compounds: selecting independent per-axis atoms would put both values in
|
|
948
|
+
* the utility layer and let stylesheet order, rather than the recipe's merge order, pick
|
|
949
|
+
* the winner. Complete leaves retain the same precedence while sharing their atoms with
|
|
950
|
+
* every `css()` and recipe in the build.
|
|
951
|
+
*
|
|
952
|
+
* `undefined` is its own edge because it restores a default variant. `null` and any
|
|
953
|
+
* undeclared value take the miss edge and explicitly suppress that default. Declared
|
|
954
|
+
* values use string keys, matching JavaScript's property-key coercion in the recipe
|
|
955
|
+
* runtime. A flat alternating key/value array avoids the special `__proto__` semantics
|
|
956
|
+
* of an object literal.
|
|
957
|
+
*/
|
|
958
|
+
const axes = Object.keys(config.variants ?? {}).filter((key) => dynamicAxes.has(key));
|
|
959
|
+
const stateCount = axes.reduce((product, axis) => product * (Object.keys(config.variants?.[axis] ?? {}).length + 2), 1);
|
|
960
|
+
if (stateCount > maxRecipeStates) throw new Error(`Static recipe compilation would inspect ${stateCount.toLocaleString("en-US")} selections across ${axes.length} runtime variant axes, above maxRecipeStates=${maxRecipeStates.toLocaleString("en-US")}. Make one or more axes statically known, split the recipe, or raise the limit explicitly.`);
|
|
961
|
+
const expressions = axes.map((axis) => dynamicAxes.get(axis));
|
|
962
|
+
const wholeSlots = Array.isArray(config.slots) && slot === void 0;
|
|
1070
963
|
return {
|
|
1071
|
-
kind: "
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
964
|
+
kind: "dynamic-style",
|
|
965
|
+
map: {
|
|
966
|
+
outputKind: wholeSlots ? "slots" : "class",
|
|
967
|
+
compile(before = [], after = []) {
|
|
968
|
+
const nodes = [];
|
|
969
|
+
const nodeByShape = /* @__PURE__ */ new Map();
|
|
970
|
+
const leaves = [];
|
|
971
|
+
const leafByShape = /* @__PURE__ */ new Map();
|
|
972
|
+
const emittedClasses = /* @__PURE__ */ new Set();
|
|
973
|
+
const leaf = (dynamicSelection) => {
|
|
974
|
+
const selected = {
|
|
975
|
+
...selection,
|
|
976
|
+
...dynamicSelection
|
|
977
|
+
};
|
|
978
|
+
if (wholeSlots) {
|
|
979
|
+
const compiled = compiledSelection(selected);
|
|
980
|
+
if (!compiled || typeof compiled.value === "string") return internLeaf("");
|
|
981
|
+
for (const token of compiled.classNames) emittedClasses.add(token);
|
|
982
|
+
return internLeaf(compiled.value);
|
|
983
|
+
}
|
|
984
|
+
const styles = styleCompiler.resolveRecipe(config, selected, slot);
|
|
985
|
+
if (!styles) return internLeaf("");
|
|
986
|
+
const className = styleCompiler.className(styleCompiler.compose(...before, styles, ...after));
|
|
987
|
+
for (const token of className.split(" ")) if (token) emittedClasses.add(token);
|
|
988
|
+
return internLeaf(className);
|
|
989
|
+
};
|
|
990
|
+
function internLeaf(value) {
|
|
991
|
+
const shape = JSON.stringify(value);
|
|
992
|
+
const known = leafByShape.get(shape);
|
|
993
|
+
if (known !== void 0) return ~known;
|
|
994
|
+
const id = leaves.length;
|
|
995
|
+
leaves.push(value);
|
|
996
|
+
leafByShape.set(shape, id);
|
|
997
|
+
return ~id;
|
|
998
|
+
}
|
|
999
|
+
const buildNode = (index, dynamicSelection) => {
|
|
1000
|
+
if (index === axes.length) return leaf(dynamicSelection);
|
|
1001
|
+
const axis = axes[index];
|
|
1002
|
+
const values = Object.keys(config.variants?.[axis] ?? {});
|
|
1003
|
+
const miss = buildNode(index + 1, {
|
|
1004
|
+
...dynamicSelection,
|
|
1005
|
+
[axis]: null
|
|
1006
|
+
});
|
|
1007
|
+
const absentSelection = { ...dynamicSelection };
|
|
1008
|
+
delete absentSelection[axis];
|
|
1009
|
+
const absent = buildNode(index + 1, absentSelection);
|
|
1010
|
+
const byValue = [];
|
|
1011
|
+
for (const value of values) byValue.push(value, buildNode(index + 1, {
|
|
1012
|
+
...dynamicSelection,
|
|
1013
|
+
[axis]: value
|
|
1014
|
+
}));
|
|
1015
|
+
const refs = [
|
|
1016
|
+
miss,
|
|
1017
|
+
absent,
|
|
1018
|
+
...byValue.filter((_, valueIndex) => valueIndex % 2 === 1)
|
|
1019
|
+
];
|
|
1020
|
+
if (refs.every((ref) => ref === refs[0])) return refs[0];
|
|
1021
|
+
const node = [
|
|
1022
|
+
miss,
|
|
1023
|
+
absent,
|
|
1024
|
+
byValue
|
|
1025
|
+
];
|
|
1026
|
+
const shape = JSON.stringify(node);
|
|
1027
|
+
const known = nodeByShape.get(shape);
|
|
1028
|
+
if (known !== void 0) return known;
|
|
1029
|
+
const id = nodes.length;
|
|
1030
|
+
nodes.push(node);
|
|
1031
|
+
nodeByShape.set(shape, id);
|
|
1032
|
+
return id;
|
|
1033
|
+
};
|
|
1034
|
+
const root = buildNode(0, {});
|
|
1035
|
+
const staticLeaf = root < 0 ? leaves[~root] : void 0;
|
|
1036
|
+
return {
|
|
1037
|
+
expression: root < 0 && effectful.length === 0 ? JSON.stringify(staticLeaf) : `${RECIPE_MAP_HELPER}([${expressions.join(", ")}], ${JSON.stringify(nodes)}, ${JSON.stringify(leaves)}, ${root})`,
|
|
1038
|
+
classNames: [...emittedClasses],
|
|
1039
|
+
staticClasses: typeof staticLeaf === "string" ? staticLeaf : "",
|
|
1040
|
+
outputKind: wholeSlots ? "slots" : "class",
|
|
1041
|
+
usesHelper: !(root < 0 && effectful.length === 0)
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1075
1045
|
};
|
|
1076
1046
|
};
|
|
1077
1047
|
//#endregion
|
|
@@ -1135,114 +1105,29 @@ const createRuntimeTokenValue = (ctx) => (path) => {
|
|
|
1135
1105
|
* the default form the trivially foldable one.
|
|
1136
1106
|
*/
|
|
1137
1107
|
const createRuntimeToken = (ctx) => (path) => tokenValuesFor(ctx).get(path)?.variable || void 0;
|
|
1138
|
-
/**
|
|
1139
|
-
* Whether a slot's class is independent of the variant props.
|
|
1140
|
-
*
|
|
1141
|
-
* A scoped slot recipe delivers variants through `@scope` rules anchored on an enclosing
|
|
1142
|
-
* slot, so every *other* slot carries a constant class — the same string whatever the props
|
|
1143
|
-
* are. That is what makes `recipe(anything).slot` foldable even when the variant is fully
|
|
1144
|
-
* dynamic, which was not true before scoping existed.
|
|
1145
|
-
*/
|
|
1146
|
-
const createConstantSlotCheck = (ctx) => (name, slot) => {
|
|
1147
|
-
const config = ctx.recipes.getConfig(name);
|
|
1148
|
-
if (!config || !("slots" in config)) return false;
|
|
1149
|
-
if (!config.slots.includes(slot)) return false;
|
|
1150
|
-
const anchors = Recipes.getScopeRoots(config);
|
|
1151
|
-
return anchors.length > 0 && !anchors.includes(slot);
|
|
1152
|
-
};
|
|
1153
|
-
const createRuntimeRecipe = (ctx) => {
|
|
1154
|
-
const separator = ctx.utility.separator;
|
|
1155
|
-
return (name, variants, slot) => {
|
|
1156
|
-
const config = ctx.recipes.getConfig(name);
|
|
1157
|
-
const node = ctx.recipes.getRecipe(name);
|
|
1158
|
-
if (!config || !node) return void 0;
|
|
1159
|
-
const isSlotRecipe = "slots" in config;
|
|
1160
|
-
if (isSlotRecipe !== Boolean(slot)) return void 0;
|
|
1161
|
-
if (slot && !config.slots.includes(slot)) return void 0;
|
|
1162
|
-
const anchors = isSlotRecipe ? Recipes.getScopeRoots(config) : [];
|
|
1163
|
-
const isConstantSlot = Boolean(slot) && anchors.length > 0 && !anchors.includes(slot);
|
|
1164
|
-
const className = slot ? ctx.recipes.getSlotKey(node.className, slot) : node.className;
|
|
1165
|
-
const { defaultVariants = {} } = config;
|
|
1166
|
-
const compoundVariants = slot ? getSlotCompoundVariant(config.compoundVariants ?? [], slot) : config.compoundVariants ?? [];
|
|
1167
|
-
const recipeCss = createCssUncached({
|
|
1168
|
-
hash: Boolean(ctx.hash.className),
|
|
1169
|
-
conditions: {
|
|
1170
|
-
shift: ctx.conditions.shift,
|
|
1171
|
-
finalize: ctx.conditions.finalize
|
|
1172
|
-
},
|
|
1173
|
-
utility: {
|
|
1174
|
-
prefix: ctx.utility.prefix,
|
|
1175
|
-
hasShorthand: false,
|
|
1176
|
-
resolveShorthand: (prop) => prop,
|
|
1177
|
-
toHash: ctx.utility.toHash.bind(ctx.utility),
|
|
1178
|
-
transform: (prop, value) => {
|
|
1179
|
-
if (value === "__ignore__") return { className };
|
|
1180
|
-
return { className: `${className}--${prop}${separator}${withoutSpace(value)}` };
|
|
1181
|
-
}
|
|
1182
|
-
}
|
|
1183
|
-
});
|
|
1184
|
-
const declaredValues = config.variants ?? {};
|
|
1185
|
-
/**
|
|
1186
|
-
* The same filter the generated `createRecipe` applies: only a value the config declares
|
|
1187
|
-
* names a class.
|
|
1188
|
-
*
|
|
1189
|
-
* Scalars only — a conditional or responsive value is an object of leaves, and the leaves
|
|
1190
|
-
* are what name classes when `createCss` walks them.
|
|
1191
|
-
*/
|
|
1192
|
-
const onlyDeclared = (styles) => Object.fromEntries(Object.entries(styles).filter(([prop, value]) => {
|
|
1193
|
-
if (prop === className) return true;
|
|
1194
|
-
if (value === null || typeof value === "object") return true;
|
|
1195
|
-
return Object.hasOwn(declaredValues, prop) && Object.hasOwn(declaredValues[prop] ?? {}, String(value));
|
|
1196
|
-
}));
|
|
1197
|
-
const recipeStyles = isConstantSlot ? { [className]: "__ignore__" } : onlyDeclared({
|
|
1198
|
-
[className]: "__ignore__",
|
|
1199
|
-
...defaultVariants,
|
|
1200
|
-
...compact(variants)
|
|
1201
|
-
});
|
|
1202
|
-
if (compoundVariants.length > 0 && Object.keys(recipeStyles).some((prop) => typeof variants[prop] === "object")) return;
|
|
1203
|
-
if (isSlotRecipe) {
|
|
1204
|
-
const evaluated = anchors.length > 0 ? anchors : config.slots;
|
|
1205
|
-
if (Object.values(variants).some((value) => typeof value === "object" && value !== null) && evaluated.some((slotName) => getSlotCompoundVariant(config.compoundVariants ?? [], slotName).length > 0)) return void 0;
|
|
1206
|
-
}
|
|
1207
|
-
return recipeCss(recipeStyles);
|
|
1208
|
-
};
|
|
1209
|
-
};
|
|
1210
1108
|
//#endregion
|
|
1211
1109
|
//#region src/fold.ts
|
|
1212
1110
|
/**
|
|
1213
|
-
* `cva`/`sva` return a function, so
|
|
1214
|
-
*
|
|
1215
|
-
*
|
|
1111
|
+
* `cva`/`sva` return a function, so their definitions are compile-time declarations rather
|
|
1112
|
+
* than class-producing calls; once their uses are lowered, the factory calls are erased.
|
|
1113
|
+
* `token` also resolves to no class, but it does resolve to a literal, so it compiles through
|
|
1114
|
+
* its own path rather than being declined outright. A static `viewTransition` bag resolves to
|
|
1115
|
+
* its extracted class and uses the ordinary class candidate path.
|
|
1216
1116
|
*
|
|
1217
|
-
*
|
|
1218
|
-
*
|
|
1219
|
-
*
|
|
1117
|
+
* Recipe invocations compile through `fold-recipe`. Inline calls
|
|
1118
|
+
* are recorded under the name the file bound; config calls arrive as `recipe`. Routing both
|
|
1119
|
+
* through one exact finite-state lowering keeps their selection contract identical.
|
|
1220
1120
|
*/
|
|
1221
1121
|
const FOLDABLE_TYPES = new Set([
|
|
1222
1122
|
"css",
|
|
1223
1123
|
"pattern",
|
|
1224
|
-
"
|
|
1124
|
+
"viewTransition"
|
|
1225
1125
|
]);
|
|
1226
1126
|
/**
|
|
1227
|
-
* The class strings inside a lowered ternary — `e ? "c_red" : "c_blue"` gives both arms.
|
|
1228
|
-
*
|
|
1229
|
-
* They are read back out of the emitted text rather than threaded through the planner,
|
|
1230
|
-
* because the planner's product *is* that text: anything it did not write cannot appear
|
|
1231
|
-
* here, and anything it did cannot be missed.
|
|
1232
|
-
*/
|
|
1233
|
-
const literalsIn = (expression) => [...expression.matchAll(/"((?:[^"\\]|\\.)*)"/g)].flatMap((match) => JSON.parse(match[0]).split(" ")).filter(Boolean);
|
|
1234
|
-
/**
|
|
1235
|
-
* The kinds reported as `not-foldable`, which is permanent rather than a limit of this
|
|
1236
|
-
* phase — hence separate from `unsupported-kind`, where a slot recipe lands because it
|
|
1237
|
-
* resolves to one class per slot rather than to a single string.
|
|
1238
|
-
*/
|
|
1239
|
-
const UNFOLDABLE_TYPES = new Set(["cva", "sva"]);
|
|
1240
|
-
/**
|
|
1241
1127
|
* The skip reasons that leave a `css()`-family call in the output.
|
|
1242
1128
|
*
|
|
1243
1129
|
* `overlapping` is handled by the enclosing fold, and `not-imported` is somebody else's
|
|
1244
|
-
* function of the same name — neither leaves a call of ours.
|
|
1245
|
-
* definition, which keeps the recipe runtime rather than the css engine; see `failOnUnfolded`.
|
|
1130
|
+
* function of the same name — neither leaves a call of ours.
|
|
1246
1131
|
*/
|
|
1247
1132
|
const SURVIVES_TO_RUNTIME = new Set([
|
|
1248
1133
|
"dynamic",
|
|
@@ -1250,9 +1135,8 @@ const SURVIVES_TO_RUNTIME = new Set([
|
|
|
1250
1135
|
"raw-call",
|
|
1251
1136
|
"unsupported-kind",
|
|
1252
1137
|
"no-call-expression",
|
|
1253
|
-
"empty",
|
|
1254
1138
|
"unresolved-token",
|
|
1255
|
-
"
|
|
1139
|
+
"compile-failed"
|
|
1256
1140
|
]);
|
|
1257
1141
|
/**
|
|
1258
1142
|
* A call of a recipe the file bound itself: `const badge = cva(...)`, then `badge({ tone })`.
|
|
@@ -1300,21 +1184,13 @@ const isValueReference = (identifier) => {
|
|
|
1300
1184
|
/**
|
|
1301
1185
|
* Imports a surviving reference to is not a failure.
|
|
1302
1186
|
*
|
|
1303
|
-
*
|
|
1187
|
+
* These are what the compiler itself writes; all live in `cx` and pull no engine, so a
|
|
1304
1188
|
* reference to one is the fold having worked.
|
|
1305
|
-
*
|
|
1306
|
-
* `cva` and `sva` are there for the reason `SURVIVES_TO_RUNTIME` omits `not-foldable`: a
|
|
1307
|
-
* recipe *definition* cannot fold to a class string and never could, and what it keeps is the
|
|
1308
|
-
* recipe runtime rather than the css engine — which `failOnUnfolded` accepts. Their unfoldable
|
|
1309
|
-
* invocations are reported separately, as `recipe-call`.
|
|
1310
1189
|
*/
|
|
1311
1190
|
const PERMITTED_BINDINGS = new Set([
|
|
1312
1191
|
"cx",
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
RECIPE_PICK_HELPER,
|
|
1316
|
-
SPLIT_PROPS_HELPER,
|
|
1317
|
-
LEAF_HELPER
|
|
1192
|
+
RECIPE_MAP_HELPER,
|
|
1193
|
+
SPLIT_PROPS_HELPER
|
|
1318
1194
|
]);
|
|
1319
1195
|
/**
|
|
1320
1196
|
* The pieces `trim` reduces a module specifier by, hoisted because a regex literal
|
|
@@ -1542,64 +1418,7 @@ const argumentsAccountedFor = (call, boxNode) => {
|
|
|
1542
1418
|
return accountsForSource(args[0], boxNode);
|
|
1543
1419
|
};
|
|
1544
1420
|
const foldSource = (options) => {
|
|
1545
|
-
const { ctx, code, parserResult,
|
|
1546
|
-
/**
|
|
1547
|
-
* Recover the static half of a call the whole-call path gave up on. Only a
|
|
1548
|
-
* single-argument `css()` qualifies: a pattern or recipe call takes props rather than a
|
|
1549
|
-
* style object, and a multi-argument `css` is later-wins across the whole object.
|
|
1550
|
-
*/
|
|
1551
|
-
const tryPartial = (item, call, rootName) => {
|
|
1552
|
-
if (item.type !== "css" || !rootName) return void 0;
|
|
1553
|
-
if (!Node.isCallExpression(call)) return void 0;
|
|
1554
|
-
const args = call.getArguments();
|
|
1555
|
-
if (args.length !== 1) return void 0;
|
|
1556
|
-
const unboxed = box.isMap(item.box) ? unbox(item.box) : void 0;
|
|
1557
|
-
if (!unboxed?.raw) return void 0;
|
|
1558
|
-
const raw = unboxed.raw;
|
|
1559
|
-
if (unboxed.spreadConditions?.length) return void 0;
|
|
1560
|
-
const argument = args[0];
|
|
1561
|
-
if (!argument || !Node.isObjectLiteralExpression(argument)) return void 0;
|
|
1562
|
-
const leafName = findBambooBinding(call, LEAF_HELPER, isBambooCssModule, isShadowed);
|
|
1563
|
-
const plan_ = (allowLeaf) => {
|
|
1564
|
-
try {
|
|
1565
|
-
return planPartialFold(argument, item.box, raw, {
|
|
1566
|
-
ctx,
|
|
1567
|
-
runtimeCss,
|
|
1568
|
-
isAccounted: accountsForSource,
|
|
1569
|
-
isStatic: (boxNode) => isStaticBox(boxNode),
|
|
1570
|
-
allowLeaf,
|
|
1571
|
-
leafName: leafName ?? "cssLeaf"
|
|
1572
|
-
});
|
|
1573
|
-
} catch {
|
|
1574
|
-
return;
|
|
1575
|
-
}
|
|
1576
|
-
};
|
|
1577
|
-
let plan = plan_(true);
|
|
1578
|
-
if (!plan) return void 0;
|
|
1579
|
-
const usesLeaf = () => plan.finite.some((entry) => !entry.emitsLiterals);
|
|
1580
|
-
let cx = ensureCxImport(call, rootName, isBambooCssModule, isGeneratedCssModule, isShadowed, usesLeaf() ? [LEAF_HELPER] : []);
|
|
1581
|
-
if (!cx && usesLeaf()) {
|
|
1582
|
-
plan = plan_(false);
|
|
1583
|
-
if (!plan) return void 0;
|
|
1584
|
-
cx = ensureCxImport(call, rootName, isBambooCssModule, isGeneratedCssModule, isShadowed);
|
|
1585
|
-
}
|
|
1586
|
-
if (!cx) return void 0;
|
|
1587
|
-
const callee = call.getExpression().getText();
|
|
1588
|
-
const runtimePart = plan.dynamicText ? `${callee}(${plan.dynamicText})` : void 0;
|
|
1589
|
-
const runtimeParts = runtimePart ? [runtimePart] : [];
|
|
1590
|
-
const lowered = plan.finite.map((entry) => entry.expression);
|
|
1591
|
-
const parts = [...plan.className ? [JSON.stringify(plan.className)] : [], ...plan.finiteFirst ? [...lowered, ...runtimeParts] : [...runtimeParts, ...lowered]];
|
|
1592
|
-
if (!parts.length || parts.length === 1 && runtimePart) return void 0;
|
|
1593
|
-
return {
|
|
1594
|
-
className: plan.className,
|
|
1595
|
-
classNames: [plan.className, ...plan.finite.filter((entry) => entry.emitsLiterals).flatMap((entry) => literalsIn(entry.expression))].filter(Boolean),
|
|
1596
|
-
replacement: `${cx.name}(${parts.join(", ")})`,
|
|
1597
|
-
insert: cx.insert,
|
|
1598
|
-
runtimeCallee: runtimePart ? callee : void 0
|
|
1599
|
-
};
|
|
1600
|
-
};
|
|
1601
|
-
const runtimeRecipe = createRuntimeRecipe(ctx);
|
|
1602
|
-
const isConstantSlot = createConstantSlotCheck(ctx);
|
|
1421
|
+
const { ctx, code, parserResult, runtimeCss = createRuntimeCss(ctx), styleCompiler, maxRecipeStates, parseModule, recipeConfigCache, reportSurvivors, sourceFile: ownSourceFile } = options;
|
|
1603
1422
|
const runtimeToken = createRuntimeToken(ctx);
|
|
1604
1423
|
const runtimeTokenValue = createRuntimeTokenValue(ctx);
|
|
1605
1424
|
/**
|
|
@@ -1612,7 +1431,7 @@ const foldSource = (options) => {
|
|
|
1612
1431
|
*
|
|
1613
1432
|
* A tsconfig path alias is resolved first, the same way `ImportMap.match` does. Without
|
|
1614
1433
|
* that, `@site/styled-system/css` — the spelling this repo's own website uses — fails
|
|
1615
|
-
* the check and silently loses
|
|
1434
|
+
* the check and silently loses helper lowering, which is indistinguishable in the
|
|
1616
1435
|
* diagnostics from a genuinely dynamic call.
|
|
1617
1436
|
*/
|
|
1618
1437
|
const cssModules = ctx.imports.matchers.css?.mods ?? [];
|
|
@@ -1662,10 +1481,30 @@ const foldSource = (options) => {
|
|
|
1662
1481
|
const isBambooCssModule = (mod) => matchesModule(mod, cssModules);
|
|
1663
1482
|
const isGeneratedCssModule = (mod) => matchesModule(mod, [generatedCssModule]);
|
|
1664
1483
|
/**
|
|
1484
|
+
* The generated css entry as spelled beside an imported config recipe.
|
|
1485
|
+
*
|
|
1486
|
+
* A decision table needs only `cvaMap`, but a module importing a config recipe often has
|
|
1487
|
+
* no css import to extend. Preserve a relative/aliased styled-system spelling by replacing
|
|
1488
|
+
* its `/recipes` suffix; falling back to the configured generated entry covers bare imports.
|
|
1489
|
+
*/
|
|
1490
|
+
const configRecipeCssSpecifier = (call, binding) => {
|
|
1491
|
+
for (const declaration of call.getSourceFile().getImportDeclarations()) {
|
|
1492
|
+
if (declaration.isTypeOnly()) continue;
|
|
1493
|
+
if (!declaration.getNamedImports().some((named) => {
|
|
1494
|
+
if (named.isTypeOnly()) return false;
|
|
1495
|
+
return (named.getAliasNode() ?? named.getNameNode()).getText() === binding;
|
|
1496
|
+
})) continue;
|
|
1497
|
+
const mod = declaration.getModuleSpecifierValue().replaceAll("\\", "/");
|
|
1498
|
+
const at = mod.lastIndexOf("/recipes");
|
|
1499
|
+
if (at >= 0) return `${mod.slice(0, at)}/css`;
|
|
1500
|
+
}
|
|
1501
|
+
return generatedCssModule;
|
|
1502
|
+
};
|
|
1503
|
+
/**
|
|
1665
1504
|
* How *this* module would have to spell the css module, learnt from one that already does.
|
|
1666
1505
|
*
|
|
1667
1506
|
* A file calling an imported recipe need not import the css module at all, so when the
|
|
1668
|
-
* lowering needs
|
|
1507
|
+
* lowering needs a decision-table helper there is no spelling in the file to copy. The declaring module
|
|
1669
1508
|
* necessarily has one — `cva` came from it — and that is the spelling reused here.
|
|
1670
1509
|
*
|
|
1671
1510
|
* A bare or aliased specifier resolves identically from any file, so it is taken as
|
|
@@ -1717,9 +1556,8 @@ const foldSource = (options) => {
|
|
|
1717
1556
|
* either end. Each hop is an alias symbol, so following them to a non-alias lands on the
|
|
1718
1557
|
* declaration wherever it lives.
|
|
1719
1558
|
*
|
|
1720
|
-
* The
|
|
1721
|
-
*
|
|
1722
|
-
* sites produce, and exactly the one the runtime would have.
|
|
1559
|
+
* The selected declarations do not depend on which module the call is in. A recipe lowered
|
|
1560
|
+
* here therefore reaches the same globally shared atoms as a call in its declaring module.
|
|
1723
1561
|
*/
|
|
1724
1562
|
const resolveImportedRecipe = (call, name, origin) => {
|
|
1725
1563
|
if (importedRecipes.has(name)) return importedRecipes.get(name);
|
|
@@ -1736,7 +1574,6 @@ const foldSource = (options) => {
|
|
|
1736
1574
|
const configs = /* @__PURE__ */ new Map();
|
|
1737
1575
|
for (const [key, entry] of collected) configs.set(key, entry === AMBIGUOUS ? entry : {
|
|
1738
1576
|
config: entry.config,
|
|
1739
|
-
name: entry.name,
|
|
1740
1577
|
box: void 0
|
|
1741
1578
|
});
|
|
1742
1579
|
foreign = {
|
|
@@ -1759,21 +1596,19 @@ const foldSource = (options) => {
|
|
|
1759
1596
|
const skipped = [];
|
|
1760
1597
|
const candidates = [];
|
|
1761
1598
|
const seenRanges = /* @__PURE__ */ new Set();
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
/** Bindings whose `splitVariantProps` was rewritten, so that access no longer reads them. */
|
|
1776
|
-
const loweredSplitProps = /* @__PURE__ */ new Set();
|
|
1599
|
+
const recipeConfigs = collectRecipeConfigs(parserResult);
|
|
1600
|
+
const recipeDefinitions = [];
|
|
1601
|
+
for (const [name, entry] of recipeConfigs) {
|
|
1602
|
+
if (entry === AMBIGUOUS) continue;
|
|
1603
|
+
const definition = entry.box?.getNode?.();
|
|
1604
|
+
if (!definition) continue;
|
|
1605
|
+
const call = Node.isCallExpression(definition) ? definition : definition.getFirstAncestorByKind(SyntaxKind.CallExpression);
|
|
1606
|
+
if (!call || code.slice(call.getStart(), call.getEnd()) !== call.getText()) continue;
|
|
1607
|
+
recipeDefinitions.push({
|
|
1608
|
+
name,
|
|
1609
|
+
call
|
|
1610
|
+
});
|
|
1611
|
+
}
|
|
1777
1612
|
/** Ranges already reported as declined, so one call is never counted twice. */
|
|
1778
1613
|
const reportedRanges = /* @__PURE__ */ new Set();
|
|
1779
1614
|
const importCache = /* @__PURE__ */ new Map();
|
|
@@ -1894,13 +1729,7 @@ const foldSource = (options) => {
|
|
|
1894
1729
|
continue;
|
|
1895
1730
|
}
|
|
1896
1731
|
if (!FOLDABLE_TYPES.has(type)) {
|
|
1897
|
-
if (call &&
|
|
1898
|
-
name,
|
|
1899
|
-
reason: "not-foldable",
|
|
1900
|
-
start: call.getStart(),
|
|
1901
|
-
end: call.getEnd()
|
|
1902
|
-
});
|
|
1903
|
-
if (call && type === RECIPE_CALL_TYPE && !isShadowed(call, name)) {
|
|
1732
|
+
if (call && (type === RECIPE_CALL_TYPE || type === "recipe") && !isShadowed(call, name)) {
|
|
1904
1733
|
const start = call.getStart();
|
|
1905
1734
|
const end = call.getEnd();
|
|
1906
1735
|
const rangeKey = `${start}:${end}`;
|
|
@@ -1915,35 +1744,95 @@ const foldSource = (options) => {
|
|
|
1915
1744
|
});
|
|
1916
1745
|
continue;
|
|
1917
1746
|
}
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1747
|
+
if (isRawCall(call)) {
|
|
1748
|
+
skipped.push({
|
|
1749
|
+
name,
|
|
1750
|
+
reason: "raw-call",
|
|
1751
|
+
start,
|
|
1752
|
+
end
|
|
1753
|
+
});
|
|
1754
|
+
continue;
|
|
1755
|
+
}
|
|
1756
|
+
if (!recipeConfigs.has(name)) {
|
|
1757
|
+
if (type === "recipe") {
|
|
1758
|
+
const config = ctx.recipes.getConfig(name);
|
|
1759
|
+
if (config) {
|
|
1760
|
+
recipeConfigs.set(name, {
|
|
1761
|
+
config,
|
|
1762
|
+
box: void 0
|
|
1763
|
+
});
|
|
1764
|
+
helperModules.set(name, configRecipeCssSpecifier(call, name));
|
|
1765
|
+
}
|
|
1766
|
+
} else if (item.origin) {
|
|
1767
|
+
const imported = resolveImportedRecipe(call, name, item.origin);
|
|
1768
|
+
if (imported) recipeConfigs.set(name, imported);
|
|
1769
|
+
}
|
|
1922
1770
|
}
|
|
1923
|
-
const tally = recipeCalls.get(name) ?? {
|
|
1924
|
-
seen: 0,
|
|
1925
|
-
lowered: 0
|
|
1926
|
-
};
|
|
1927
|
-
tally.seen++;
|
|
1928
|
-
recipeCalls.set(name, tally);
|
|
1929
1771
|
const resolvedSelection = item.data?.length === 1 ? item.data[0] : void 0;
|
|
1930
1772
|
const entry = recipeConfigs.get(name);
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1773
|
+
let inlineSlot;
|
|
1774
|
+
let inlineEnd = end;
|
|
1775
|
+
if (Array.isArray(entry?.config.slots)) {
|
|
1776
|
+
const parent = call.getParent();
|
|
1777
|
+
if (Node.isPropertyAccessExpression(parent) && parent.getExpression() === call) {
|
|
1778
|
+
const accessed = parent.getName();
|
|
1779
|
+
if (entry.config.slots.includes(accessed)) {
|
|
1780
|
+
inlineSlot = accessed;
|
|
1781
|
+
inlineEnd = parent.getEnd();
|
|
1782
|
+
}
|
|
1783
|
+
} else if (Node.isElementAccessExpression(parent) && parent.getExpression() === call) {
|
|
1784
|
+
const argument = parent.getArgumentExpression();
|
|
1785
|
+
const accessed = argument && (Node.isStringLiteral(argument) || Node.isNoSubstitutionTemplateLiteral(argument)) ? argument.getLiteralValue() : void 0;
|
|
1786
|
+
if (typeof accessed === "string" && entry.config.slots.includes(accessed)) {
|
|
1787
|
+
inlineSlot = accessed;
|
|
1788
|
+
inlineEnd = parent.getEnd();
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
const lowered = lowerRecipeCall(call, entry, styleCompiler, isInertExpression, resolvedSelection, inlineSlot, maxRecipeStates);
|
|
1793
|
+
if (lowered.kind === "dynamic-style") {
|
|
1794
|
+
const helper = ensureRecipeHelperImport(RECIPE_MAP_HELPER, call, isBambooCssModule, isGeneratedCssModule, isShadowed, helperModules.get(name));
|
|
1934
1795
|
if (helper) {
|
|
1935
|
-
tally.lowered++;
|
|
1936
1796
|
candidates.push({
|
|
1937
1797
|
item,
|
|
1938
1798
|
call,
|
|
1939
1799
|
node: call,
|
|
1940
1800
|
start,
|
|
1941
|
-
end,
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1801
|
+
end: inlineEnd,
|
|
1802
|
+
className: "",
|
|
1803
|
+
classNames: [],
|
|
1804
|
+
styleMap: lowered.map,
|
|
1805
|
+
mapHelperName: helper.name,
|
|
1945
1806
|
insert: helper.insert,
|
|
1946
|
-
configBox: entry?.box
|
|
1807
|
+
configBox: entry?.box,
|
|
1808
|
+
outputKind: lowered.map.outputKind === "slots" ? "slots" : void 0
|
|
1809
|
+
});
|
|
1810
|
+
continue;
|
|
1811
|
+
}
|
|
1812
|
+
skipped.push({
|
|
1813
|
+
name,
|
|
1814
|
+
reason: "recipe-call",
|
|
1815
|
+
start,
|
|
1816
|
+
end
|
|
1817
|
+
});
|
|
1818
|
+
continue;
|
|
1819
|
+
}
|
|
1820
|
+
if (lowered.kind === "slots") {
|
|
1821
|
+
const helper = lowered.helper ? ensureRecipeHelperImport(lowered.helper, call, isBambooCssModule, isGeneratedCssModule, isShadowed, helperModules.get(name)) : void 0;
|
|
1822
|
+
if (!lowered.helper || helper) {
|
|
1823
|
+
const replacement = lowered.helper && helper && helper.name !== lowered.helper ? lowered.expression.replaceAll(`${lowered.helper}(`, `${helper.name}(`) : lowered.expression;
|
|
1824
|
+
candidates.push({
|
|
1825
|
+
item,
|
|
1826
|
+
call,
|
|
1827
|
+
node: call,
|
|
1828
|
+
start,
|
|
1829
|
+
end: inlineEnd,
|
|
1830
|
+
replacement,
|
|
1831
|
+
className: "",
|
|
1832
|
+
classNames: lowered.classNames,
|
|
1833
|
+
insert: helper?.insert,
|
|
1834
|
+
configBox: entry?.box,
|
|
1835
|
+
outputKind: "slots"
|
|
1947
1836
|
});
|
|
1948
1837
|
continue;
|
|
1949
1838
|
}
|
|
@@ -1956,16 +1845,16 @@ const foldSource = (options) => {
|
|
|
1956
1845
|
continue;
|
|
1957
1846
|
}
|
|
1958
1847
|
if (lowered.kind === "class") {
|
|
1959
|
-
tally.lowered++;
|
|
1960
1848
|
candidates.push({
|
|
1961
1849
|
item,
|
|
1962
1850
|
call,
|
|
1963
1851
|
node: call,
|
|
1964
1852
|
start,
|
|
1965
|
-
end,
|
|
1853
|
+
end: inlineEnd,
|
|
1966
1854
|
replacement: JSON.stringify(lowered.className),
|
|
1967
1855
|
className: lowered.className,
|
|
1968
1856
|
classNames: lowered.className.split(" ").filter(Boolean),
|
|
1857
|
+
styleSet: lowered.styles,
|
|
1969
1858
|
configBox: entry?.box
|
|
1970
1859
|
});
|
|
1971
1860
|
continue;
|
|
@@ -2029,37 +1918,7 @@ const foldSource = (options) => {
|
|
|
2029
1918
|
});
|
|
2030
1919
|
continue;
|
|
2031
1920
|
}
|
|
2032
|
-
if (slot && isConstantSlot(name, slot) && Node.isCallExpression(call) && call.getArguments().every(isInertExpression)) {
|
|
2033
|
-
candidates.push({
|
|
2034
|
-
item,
|
|
2035
|
-
call,
|
|
2036
|
-
node: call,
|
|
2037
|
-
start,
|
|
2038
|
-
end: foldEnd,
|
|
2039
|
-
slot,
|
|
2040
|
-
constantSlot: true
|
|
2041
|
-
});
|
|
2042
|
-
continue;
|
|
2043
|
-
}
|
|
2044
1921
|
if (!(Node.isCallExpression(call) && call.getArguments().length === 0 && item.data.length === 1) && !isStaticBox(item.box) || !hasStyles(item.data) || !argumentsAccountedFor(call, item.box)) {
|
|
2045
|
-
const partial = partial_ ? tryPartial(item, call, rootName) : void 0;
|
|
2046
|
-
if (partial) {
|
|
2047
|
-
if (reportSurvivors && partial.runtimeCallee) skipped.push({
|
|
2048
|
-
name,
|
|
2049
|
-
reason: "runtime-binding",
|
|
2050
|
-
start,
|
|
2051
|
-
end
|
|
2052
|
-
});
|
|
2053
|
-
candidates.push({
|
|
2054
|
-
item,
|
|
2055
|
-
call,
|
|
2056
|
-
node: call,
|
|
2057
|
-
start,
|
|
2058
|
-
end,
|
|
2059
|
-
...partial
|
|
2060
|
-
});
|
|
2061
|
-
continue;
|
|
2062
|
-
}
|
|
2063
1922
|
skipped.push({
|
|
2064
1923
|
name,
|
|
2065
1924
|
reason: "dynamic",
|
|
@@ -2078,12 +1937,220 @@ const foldSource = (options) => {
|
|
|
2078
1937
|
});
|
|
2079
1938
|
}
|
|
2080
1939
|
/**
|
|
1940
|
+
* Resolve every fully static candidate to symbolic declarations before allocating a class.
|
|
1941
|
+
*
|
|
1942
|
+
* The normal fold can wait until the rewrite loop to compute a class string. Semantic
|
|
1943
|
+
* composition cannot: an enclosing `cx()` needs the declarations of its arguments so it can
|
|
1944
|
+
* discard overridden values before any string exists.
|
|
1945
|
+
*/
|
|
1946
|
+
{
|
|
1947
|
+
for (const candidate of candidates) {
|
|
1948
|
+
if (candidate.styleSet || candidate.value !== void 0 || candidate.replacement) continue;
|
|
1949
|
+
const { item } = candidate;
|
|
1950
|
+
if (item.type === "css") {
|
|
1951
|
+
candidate.styleSet = styleCompiler.compose(...item.data);
|
|
1952
|
+
continue;
|
|
1953
|
+
}
|
|
1954
|
+
if (item.type === "pattern") {
|
|
1955
|
+
candidate.styleSet = styleCompiler.compose(...item.data.map((entry) => ctx.patterns.transform(item.name ?? "", entry)));
|
|
1956
|
+
continue;
|
|
1957
|
+
}
|
|
1958
|
+
if (item.type === "viewTransition") {
|
|
1959
|
+
const semantic = viewTransitionClassName(item.data[0], ctx.utility.prefix);
|
|
1960
|
+
candidate.className = styleCompiler.allocateClassString(semantic);
|
|
1961
|
+
candidate.classNames = [candidate.className];
|
|
1962
|
+
candidate.replacement = JSON.stringify(candidate.className);
|
|
1963
|
+
continue;
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
const sourceFile = ownSourceFile ?? candidates[0]?.node.getSourceFile();
|
|
1967
|
+
if (sourceFile) {
|
|
1968
|
+
const cxBindings = /* @__PURE__ */ new Set();
|
|
1969
|
+
for (const declaration of sourceFile.getImportDeclarations()) {
|
|
1970
|
+
if (declaration.isTypeOnly() || !isBambooCssModule(declaration.getModuleSpecifierValue())) continue;
|
|
1971
|
+
for (const named of declaration.getNamedImports()) {
|
|
1972
|
+
if (named.isTypeOnly() || named.getNameNode().getText() !== "cx") continue;
|
|
1973
|
+
cxBindings.add((named.getAliasNode() ?? named.getNameNode()).getText());
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
const byRange = new Map(candidates.map((candidate) => [`${candidate.start}:${candidate.end}`, candidate]));
|
|
1977
|
+
for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
|
1978
|
+
const callee = call.getExpression();
|
|
1979
|
+
if (!Node.isIdentifier(callee) || !cxBindings.has(callee.getText()) || isShadowed(call, callee.getText())) continue;
|
|
1980
|
+
const matched = [];
|
|
1981
|
+
const parts = [];
|
|
1982
|
+
const dynamic = [];
|
|
1983
|
+
const constantCandidates = [];
|
|
1984
|
+
let supported = true;
|
|
1985
|
+
const take = (arg) => {
|
|
1986
|
+
const candidate = byRange.get(`${arg.getStart()}:${arg.getEnd()}`);
|
|
1987
|
+
if (candidate?.styleMap?.outputKind === "class") {
|
|
1988
|
+
dynamic.push(candidate);
|
|
1989
|
+
parts.push({
|
|
1990
|
+
kind: "dynamic",
|
|
1991
|
+
candidate
|
|
1992
|
+
});
|
|
1993
|
+
return true;
|
|
1994
|
+
}
|
|
1995
|
+
if (candidate?.styleSet) {
|
|
1996
|
+
matched.push(candidate);
|
|
1997
|
+
parts.push({
|
|
1998
|
+
kind: "style",
|
|
1999
|
+
candidate
|
|
2000
|
+
});
|
|
2001
|
+
return true;
|
|
2002
|
+
}
|
|
2003
|
+
if (candidate?.item.type === "viewTransition" && candidate.replacement && candidate.className) {
|
|
2004
|
+
constantCandidates.push(candidate);
|
|
2005
|
+
parts.push({
|
|
2006
|
+
kind: "class",
|
|
2007
|
+
value: candidate.className,
|
|
2008
|
+
candidate
|
|
2009
|
+
});
|
|
2010
|
+
return true;
|
|
2011
|
+
}
|
|
2012
|
+
if (Node.isStringLiteral(arg) || Node.isNoSubstitutionTemplateLiteral(arg)) {
|
|
2013
|
+
parts.push({
|
|
2014
|
+
kind: "class",
|
|
2015
|
+
value: arg.getLiteralValue()
|
|
2016
|
+
});
|
|
2017
|
+
return true;
|
|
2018
|
+
}
|
|
2019
|
+
if (Node.isArrayLiteralExpression(arg)) {
|
|
2020
|
+
for (const element of arg.getElements()) if (Node.isSpreadElement(element) || !take(element)) return false;
|
|
2021
|
+
return true;
|
|
2022
|
+
}
|
|
2023
|
+
if (arg.getKind() === SyntaxKind.FalseKeyword || arg.getKind() === SyntaxKind.TrueKeyword || Node.isNumericLiteral(arg) || arg.getKind() === SyntaxKind.NullKeyword || Node.isIdentifier(arg) && arg.getText() === "undefined") return true;
|
|
2024
|
+
return false;
|
|
2025
|
+
};
|
|
2026
|
+
for (const arg of call.getArguments()) {
|
|
2027
|
+
if (take(arg)) continue;
|
|
2028
|
+
supported = false;
|
|
2029
|
+
break;
|
|
2030
|
+
}
|
|
2031
|
+
if (dynamic.length > 1) {
|
|
2032
|
+
skipped.push({
|
|
2033
|
+
name: "cx",
|
|
2034
|
+
reason: "dynamic",
|
|
2035
|
+
start: call.getStart(),
|
|
2036
|
+
end: call.getEnd()
|
|
2037
|
+
});
|
|
2038
|
+
continue;
|
|
2039
|
+
}
|
|
2040
|
+
if (!supported) {
|
|
2041
|
+
skipped.push({
|
|
2042
|
+
name: "cx",
|
|
2043
|
+
reason: "dynamic",
|
|
2044
|
+
start: call.getStart(),
|
|
2045
|
+
end: call.getEnd()
|
|
2046
|
+
});
|
|
2047
|
+
continue;
|
|
2048
|
+
}
|
|
2049
|
+
if (dynamic.length === 1 && matched.length > 0) {
|
|
2050
|
+
const dynamicCandidate = dynamic[0];
|
|
2051
|
+
const styleParts = parts.filter((part) => part.kind !== "class");
|
|
2052
|
+
const dynamicIndex = styleParts.findIndex((part) => part.kind === "dynamic");
|
|
2053
|
+
const before = styleParts.slice(0, dynamicIndex).filter((part) => part.kind === "style").map((part) => part.candidate.styleSet);
|
|
2054
|
+
const after = styleParts.slice(dynamicIndex + 1).filter((part) => part.kind === "style").map((part) => part.candidate.styleSet);
|
|
2055
|
+
const compiled = dynamicCandidate.styleMap.compile(before, after);
|
|
2056
|
+
const expression = compiled.usesHelper && dynamicCandidate.mapHelperName && dynamicCandidate.mapHelperName !== "cvaMap" ? compiled.expression.replaceAll(`${RECIPE_MAP_HELPER}(`, `${dynamicCandidate.mapHelperName}(`) : compiled.expression;
|
|
2057
|
+
const arguments_ = [];
|
|
2058
|
+
let wroteCompiled = false;
|
|
2059
|
+
for (const part of parts) {
|
|
2060
|
+
if (part.kind === "class") {
|
|
2061
|
+
if (part.value) arguments_.push(JSON.stringify(part.value));
|
|
2062
|
+
continue;
|
|
2063
|
+
}
|
|
2064
|
+
if (!wroteCompiled) {
|
|
2065
|
+
arguments_.push(expression);
|
|
2066
|
+
wroteCompiled = true;
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
dynamicCandidate.subsumed = true;
|
|
2070
|
+
const first = styleParts[0].candidate;
|
|
2071
|
+
candidates.push({
|
|
2072
|
+
...first,
|
|
2073
|
+
call,
|
|
2074
|
+
node: call,
|
|
2075
|
+
start: call.getStart(),
|
|
2076
|
+
end: call.getEnd(),
|
|
2077
|
+
displayName: "cx",
|
|
2078
|
+
replacement: arguments_.length === 1 ? arguments_[0] : `${callee.getText()}(${arguments_.join(", ")})`,
|
|
2079
|
+
className: "",
|
|
2080
|
+
classNames: [...compiled.classNames, ...parts.filter((part) => part.kind === "class").flatMap((part) => part.value.split(" "))].filter(Boolean),
|
|
2081
|
+
styleSet: void 0,
|
|
2082
|
+
styleMap: void 0,
|
|
2083
|
+
outputKind: void 0,
|
|
2084
|
+
insert: compiled.usesHelper ? dynamicCandidate.insert : void 0,
|
|
2085
|
+
sourceBoxes: styleParts.flatMap((part) => [part.candidate.item.box, part.candidate.configBox]).concat(constantCandidates.map((candidate) => candidate.item.box)).filter(Boolean)
|
|
2086
|
+
});
|
|
2087
|
+
continue;
|
|
2088
|
+
}
|
|
2089
|
+
if (matched.length === 0) {
|
|
2090
|
+
if (constantCandidates.length === 0) continue;
|
|
2091
|
+
const className = parts.filter((part) => part.kind === "class").map((part) => part.value).filter(Boolean).join(" ");
|
|
2092
|
+
const first = constantCandidates[0];
|
|
2093
|
+
candidates.push({
|
|
2094
|
+
...first,
|
|
2095
|
+
call,
|
|
2096
|
+
node: call,
|
|
2097
|
+
start: call.getStart(),
|
|
2098
|
+
end: call.getEnd(),
|
|
2099
|
+
displayName: "cx",
|
|
2100
|
+
replacement: JSON.stringify(className),
|
|
2101
|
+
className,
|
|
2102
|
+
classNames: className.split(" ").filter(Boolean),
|
|
2103
|
+
sourceBoxes: constantCandidates.map((candidate) => candidate.item.box).filter(Boolean)
|
|
2104
|
+
});
|
|
2105
|
+
continue;
|
|
2106
|
+
}
|
|
2107
|
+
const merged = styleCompiler.compose(...matched.map((candidate) => candidate.styleSet));
|
|
2108
|
+
const compiled = styleCompiler.className(merged);
|
|
2109
|
+
const classParts = [];
|
|
2110
|
+
let wroteCompiled = false;
|
|
2111
|
+
for (const part of parts) {
|
|
2112
|
+
if (part.kind === "class") {
|
|
2113
|
+
if (part.value) classParts.push(part.value);
|
|
2114
|
+
continue;
|
|
2115
|
+
}
|
|
2116
|
+
if (!wroteCompiled && compiled) {
|
|
2117
|
+
classParts.push(compiled);
|
|
2118
|
+
wroteCompiled = true;
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
const first = matched[0];
|
|
2122
|
+
candidates.push({
|
|
2123
|
+
...first,
|
|
2124
|
+
call,
|
|
2125
|
+
node: call,
|
|
2126
|
+
start: call.getStart(),
|
|
2127
|
+
end: call.getEnd(),
|
|
2128
|
+
displayName: "cx",
|
|
2129
|
+
replacement: JSON.stringify(classParts.join(" ")),
|
|
2130
|
+
className: classParts.join(" "),
|
|
2131
|
+
classNames: classParts.flatMap((part) => part.split(" ")).filter(Boolean),
|
|
2132
|
+
styleSet: merged,
|
|
2133
|
+
sourceBoxes: [...matched.flatMap((candidate) => [candidate.item.box, candidate.configBox]), ...constantCandidates.map((candidate) => candidate.item.box)].filter(Boolean)
|
|
2134
|
+
});
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
for (const candidate of candidates) {
|
|
2138
|
+
if (!candidate.styleMap || candidate.subsumed || candidate.replacement) continue;
|
|
2139
|
+
const compiled = candidate.styleMap.compile();
|
|
2140
|
+
candidate.replacement = compiled.usesHelper && candidate.mapHelperName && candidate.mapHelperName !== "cvaMap" ? compiled.expression.replaceAll(`${RECIPE_MAP_HELPER}(`, `${candidate.mapHelperName}(`) : compiled.expression;
|
|
2141
|
+
if (!compiled.usesHelper) candidate.insert = void 0;
|
|
2142
|
+
candidate.className = compiled.staticClasses;
|
|
2143
|
+
candidate.classNames = compiled.classNames;
|
|
2144
|
+
candidate.outputKind = compiled.outputKind === "slots" ? "slots" : void 0;
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
/**
|
|
2081
2148
|
* Ranges the rewrite actually replaced. Declared before the early return below, because
|
|
2082
2149
|
* that return is now also a reporting point: a module with nothing to fold is exactly the
|
|
2083
2150
|
* shape `reportSurvivors` exists to catch.
|
|
2084
2151
|
*/
|
|
2085
2152
|
const applied = [];
|
|
2086
|
-
if (candidates.length === 0) {
|
|
2153
|
+
if (candidates.length === 0 && recipeDefinitions.length === 0) {
|
|
2087
2154
|
if (reportSurvivors) reportRuntimeBindings();
|
|
2088
2155
|
return {
|
|
2089
2156
|
code,
|
|
@@ -2093,7 +2160,15 @@ const foldSource = (options) => {
|
|
|
2093
2160
|
dependencies: []
|
|
2094
2161
|
};
|
|
2095
2162
|
}
|
|
2096
|
-
const
|
|
2163
|
+
const rewriteSourceFile = ownSourceFile ?? candidates[0]?.node.getSourceFile() ?? recipeDefinitions[0]?.call.getSourceFile();
|
|
2164
|
+
if (!rewriteSourceFile) return {
|
|
2165
|
+
code,
|
|
2166
|
+
map: null,
|
|
2167
|
+
folded,
|
|
2168
|
+
skipped,
|
|
2169
|
+
dependencies: []
|
|
2170
|
+
};
|
|
2171
|
+
const dependencyScan = createDependencyScan(rewriteSourceFile);
|
|
2097
2172
|
candidates.sort((a, b) => a.start - b.start || b.end - a.end);
|
|
2098
2173
|
const magic = new MagicString(code);
|
|
2099
2174
|
const insertedNames = /* @__PURE__ */ new Set();
|
|
@@ -2107,7 +2182,7 @@ const foldSource = (options) => {
|
|
|
2107
2182
|
const collides = (edits) => edits.some(([start, end]) => applied.some(([from, to]) => start < to && from < end));
|
|
2108
2183
|
for (const candidate of candidates) {
|
|
2109
2184
|
const { item, start, end } = candidate;
|
|
2110
|
-
const name = item.name ?? item.type ?? "";
|
|
2185
|
+
const name = candidate.displayName ?? item.name ?? item.type ?? "";
|
|
2111
2186
|
const ranges = [[start, end]];
|
|
2112
2187
|
if (collides(ranges)) {
|
|
2113
2188
|
skipped.push({
|
|
@@ -2139,7 +2214,7 @@ const foldSource = (options) => {
|
|
|
2139
2214
|
applied.push(...ranges);
|
|
2140
2215
|
folded.push({
|
|
2141
2216
|
name,
|
|
2142
|
-
kind: "class",
|
|
2217
|
+
kind: candidate.outputKind ?? "class",
|
|
2143
2218
|
className: candidate.className,
|
|
2144
2219
|
classNames: (candidate.classNames ?? [candidate.className]).filter(Boolean),
|
|
2145
2220
|
start,
|
|
@@ -2147,24 +2222,13 @@ const foldSource = (options) => {
|
|
|
2147
2222
|
});
|
|
2148
2223
|
collectSourceFiles(item.box, dependencyScan);
|
|
2149
2224
|
if (candidate.configBox) collectSourceFiles(candidate.configBox, dependencyScan);
|
|
2225
|
+
for (const box of candidate.sourceBoxes ?? []) collectSourceFiles(box, dependencyScan);
|
|
2150
2226
|
continue;
|
|
2151
2227
|
}
|
|
2152
2228
|
let className;
|
|
2153
2229
|
try {
|
|
2154
2230
|
if (item.type === "pattern") className = runtimeCss(...item.data.map((entry) => ctx.patterns.transform(name, entry)));
|
|
2155
|
-
else
|
|
2156
|
-
const resolved = candidate.constantSlot ? runtimeRecipe(name, {}, candidate.slot) : item.data.length === 1 ? runtimeRecipe(name, item.data[0], candidate.slot) : void 0;
|
|
2157
|
-
if (resolved == null) {
|
|
2158
|
-
skipped.push({
|
|
2159
|
-
name,
|
|
2160
|
-
reason: "unsupported-kind",
|
|
2161
|
-
start,
|
|
2162
|
-
end
|
|
2163
|
-
});
|
|
2164
|
-
continue;
|
|
2165
|
-
}
|
|
2166
|
-
className = resolved;
|
|
2167
|
-
} else className = runtimeCss(...item.data);
|
|
2231
|
+
else className = runtimeCss(...item.data);
|
|
2168
2232
|
} catch {
|
|
2169
2233
|
skipped.push({
|
|
2170
2234
|
name,
|
|
@@ -2174,22 +2238,13 @@ const foldSource = (options) => {
|
|
|
2174
2238
|
});
|
|
2175
2239
|
continue;
|
|
2176
2240
|
}
|
|
2177
|
-
if (!className) {
|
|
2178
|
-
skipped.push({
|
|
2179
|
-
name,
|
|
2180
|
-
reason: "empty",
|
|
2181
|
-
start,
|
|
2182
|
-
end
|
|
2183
|
-
});
|
|
2184
|
-
continue;
|
|
2185
|
-
}
|
|
2186
2241
|
magic.overwrite(start, end, JSON.stringify(className));
|
|
2187
2242
|
applied.push(...ranges);
|
|
2188
2243
|
folded.push({
|
|
2189
2244
|
name,
|
|
2190
2245
|
kind: "class",
|
|
2191
2246
|
className,
|
|
2192
|
-
classNames: [className],
|
|
2247
|
+
classNames: className ? [className] : [],
|
|
2193
2248
|
start,
|
|
2194
2249
|
end
|
|
2195
2250
|
});
|
|
@@ -2205,7 +2260,6 @@ const foldSource = (options) => {
|
|
|
2205
2260
|
const importedConfig = !local && importsFor(recipeSourceFile).has(target.getText()) ? ctx.recipes.getConfig(target.getText()) : void 0;
|
|
2206
2261
|
const entry = local && local !== AMBIGUOUS ? local : importedConfig ? {
|
|
2207
2262
|
config: importedConfig,
|
|
2208
|
-
name: "",
|
|
2209
2263
|
box: void 0
|
|
2210
2264
|
} : void 0;
|
|
2211
2265
|
if (!entry) continue;
|
|
@@ -2223,17 +2277,21 @@ const foldSource = (options) => {
|
|
|
2223
2277
|
magic.overwrite(start, end, `${helper.name}(${args[0].getText()}, ${JSON.stringify(keys)})`);
|
|
2224
2278
|
applyInsert(helper.insert);
|
|
2225
2279
|
applied.push([start, end]);
|
|
2226
|
-
loweredSplitProps.add(target.getText());
|
|
2227
2280
|
}
|
|
2228
|
-
for (const
|
|
2229
|
-
if (!tally.seen || tally.lowered !== tally.seen) continue;
|
|
2230
|
-
const definition = recipeConfigs?.get(binding)?.box?.getNode?.();
|
|
2231
|
-
if (!definition) continue;
|
|
2232
|
-
const call = Node.isCallExpression(definition) ? definition : definition.getFirstAncestorByKind(SyntaxKind.CallExpression);
|
|
2233
|
-
if (!call) continue;
|
|
2281
|
+
for (const { name, call } of recipeDefinitions) {
|
|
2234
2282
|
const start = call.getStart();
|
|
2235
|
-
|
|
2236
|
-
|
|
2283
|
+
const end = call.getEnd();
|
|
2284
|
+
if (collides([[start, end]])) continue;
|
|
2285
|
+
magic.overwrite(start, end, "undefined");
|
|
2286
|
+
applied.push([start, end]);
|
|
2287
|
+
folded.push({
|
|
2288
|
+
name,
|
|
2289
|
+
kind: "definition",
|
|
2290
|
+
className: "",
|
|
2291
|
+
classNames: [],
|
|
2292
|
+
start,
|
|
2293
|
+
end
|
|
2294
|
+
});
|
|
2237
2295
|
}
|
|
2238
2296
|
/**
|
|
2239
2297
|
* Bindings from a bamboo module still referenced once every rewrite is applied.
|
|
@@ -2241,21 +2299,65 @@ const foldSource = (options) => {
|
|
|
2241
2299
|
* Deliberately not driven by `parserResult`: that is the recogniser, and the point here is
|
|
2242
2300
|
* to catch what it did not see. A namespace import called as `s.cva(...)`, a default
|
|
2243
2301
|
* import, a specifier that resolved to nothing — each leaves a live reference and no ledger
|
|
2244
|
-
* entry at all, which
|
|
2302
|
+
* entry at all, which used to let a build silently ship the engine.
|
|
2245
2303
|
*
|
|
2246
|
-
* The helpers the
|
|
2247
|
-
*
|
|
2248
|
-
*
|
|
2304
|
+
* The helpers the compiler writes are excluded because they pull no style engine. `cx` is
|
|
2305
|
+
* also allowed to remain when it joins an arbitrary external class; only fully analyzable
|
|
2306
|
+
* arguments receive Bamboo's semantic composition guarantee.
|
|
2249
2307
|
*/
|
|
2250
2308
|
function reportRuntimeBindings() {
|
|
2251
|
-
const sourceFile = ownSourceFile ?? candidates[0]?.node.getSourceFile();
|
|
2309
|
+
const sourceFile = ownSourceFile ?? candidates[0]?.node.getSourceFile() ?? recipeDefinitions[0]?.call.getSourceFile();
|
|
2252
2310
|
if (!sourceFile) return;
|
|
2311
|
+
for (const [binding, entry] of recipeConfigs) {
|
|
2312
|
+
if (entry === AMBIGUOUS) continue;
|
|
2313
|
+
const definition = entry.box?.getNode?.();
|
|
2314
|
+
if (!definition || definition.getSourceFile() !== sourceFile) continue;
|
|
2315
|
+
const nameNode = definition.getFirstAncestorByKind(SyntaxKind.VariableDeclaration)?.getNameNode();
|
|
2316
|
+
if (!nameNode || !Node.isIdentifier(nameNode)) continue;
|
|
2317
|
+
if (skipped.filter((item) => SURVIVES_TO_RUNTIME.has(item.reason) && item.end > item.start).some((item) => nameNode.findReferencesAsNodes().some((ref) => ref.getStart() >= item.start && ref.getStart() < item.end))) continue;
|
|
2318
|
+
const survivor = nameNode.findReferencesAsNodes().find((ref) => !applied.some(([from, to]) => ref.getStart() >= from && ref.getStart() < to));
|
|
2319
|
+
if (!survivor) continue;
|
|
2320
|
+
skipped.push({
|
|
2321
|
+
name: binding,
|
|
2322
|
+
reason: "runtime-binding",
|
|
2323
|
+
start: survivor.getStart(),
|
|
2324
|
+
end: survivor.getEnd()
|
|
2325
|
+
});
|
|
2326
|
+
}
|
|
2253
2327
|
const bambooModules = [
|
|
2254
2328
|
...cssModules,
|
|
2255
2329
|
...ctx.imports.matchers.recipe?.mods ?? [],
|
|
2256
2330
|
...ctx.imports.matchers.pattern?.mods ?? [],
|
|
2257
2331
|
...ctx.imports.matchers.tokens?.mods ?? []
|
|
2258
2332
|
];
|
|
2333
|
+
for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
|
2334
|
+
const callee = call.getExpression();
|
|
2335
|
+
const argument = call.getArguments()[0];
|
|
2336
|
+
if (!argument || !Node.isStringLiteral(argument) && !Node.isNoSubstitutionTemplateLiteral(argument)) continue;
|
|
2337
|
+
if (!matchesModule(argument.getLiteralValue(), bambooModules)) continue;
|
|
2338
|
+
const isDynamicImport = callee.getKind() === SyntaxKind.ImportKeyword;
|
|
2339
|
+
const isRequire = Node.isIdentifier(callee) && callee.getText() === "require" && !isShadowed(call, "require");
|
|
2340
|
+
if (!isDynamicImport && !isRequire) continue;
|
|
2341
|
+
skipped.push({
|
|
2342
|
+
name: isDynamicImport ? "import" : "require",
|
|
2343
|
+
reason: "runtime-binding",
|
|
2344
|
+
start: call.getStart(),
|
|
2345
|
+
end: call.getEnd()
|
|
2346
|
+
});
|
|
2347
|
+
}
|
|
2348
|
+
for (const declaration of sourceFile.getDescendantsOfKind(SyntaxKind.ImportEqualsDeclaration)) {
|
|
2349
|
+
if (declaration.isTypeOnly()) continue;
|
|
2350
|
+
const reference = declaration.getModuleReference();
|
|
2351
|
+
if (!Node.isExternalModuleReference(reference)) continue;
|
|
2352
|
+
const expression = reference.getExpression();
|
|
2353
|
+
if (!expression || !Node.isStringLiteral(expression) || !matchesModule(expression.getLiteralValue(), bambooModules)) continue;
|
|
2354
|
+
skipped.push({
|
|
2355
|
+
name: declaration.getName(),
|
|
2356
|
+
reason: "runtime-binding",
|
|
2357
|
+
start: declaration.getStart(),
|
|
2358
|
+
end: declaration.getEnd()
|
|
2359
|
+
});
|
|
2360
|
+
}
|
|
2259
2361
|
/** Local name -> what to call it in the report. */
|
|
2260
2362
|
const watched = /* @__PURE__ */ new Map();
|
|
2261
2363
|
for (const declaration of sourceFile.getImportDeclarations()) {
|
|
@@ -2353,6 +2455,122 @@ const foldSource = (options) => {
|
|
|
2353
2455
|
};
|
|
2354
2456
|
};
|
|
2355
2457
|
//#endregion
|
|
2458
|
+
//#region src/style-set.ts
|
|
2459
|
+
const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
2460
|
+
/** A compound selector matches only through variant classes the recipe actually emits. */
|
|
2461
|
+
const matchesCompound = (compound, selection, variants) => {
|
|
2462
|
+
for (const [key, expected] of Object.entries(compound)) {
|
|
2463
|
+
if (key === "css") continue;
|
|
2464
|
+
const declared = variants?.[key];
|
|
2465
|
+
const selected = selection[key];
|
|
2466
|
+
if (selected == null || !declared || !Object.hasOwn(declared, String(selected))) return false;
|
|
2467
|
+
if (!(Array.isArray(expected) ? expected : [expected]).some((value) => value != null && String(selected) === String(value))) return false;
|
|
2468
|
+
}
|
|
2469
|
+
return true;
|
|
2470
|
+
};
|
|
2471
|
+
/**
|
|
2472
|
+
* Resolve the style fragments one recipe call contributes, in emitted-rule precedence.
|
|
2473
|
+
*
|
|
2474
|
+
* This intentionally rejects conditional variant *selections*. A scalar selects a style
|
|
2475
|
+
* object; an object such as `{ base: 'sm', md: 'lg' }` selects several objects under
|
|
2476
|
+
* conditions and needs a separate lowering. Returning `undefined` rejects that call instead
|
|
2477
|
+
* of silently compiling only one branch.
|
|
2478
|
+
*/
|
|
2479
|
+
const createStaticStyleSetCompiler = (ctx, runtimeCss, allocateClassString = (className) => className) => {
|
|
2480
|
+
const { mergeCssUncached } = createMergeCss(createCssContext(ctx));
|
|
2481
|
+
const compose = (...styles) => mergeCssUncached(...styles);
|
|
2482
|
+
const resolveRecipe = (config, input = {}, slot) => {
|
|
2483
|
+
const slots = Array.isArray(config.slots) ? config.slots : void 0;
|
|
2484
|
+
if (Boolean(slots) !== Boolean(slot)) return void 0;
|
|
2485
|
+
if (slot && !slots?.includes(slot)) return void 0;
|
|
2486
|
+
const selection = {
|
|
2487
|
+
...config.defaultVariants ?? {},
|
|
2488
|
+
...compact(input)
|
|
2489
|
+
};
|
|
2490
|
+
if (Object.values(selection).some((value) => isRecord(value))) return void 0;
|
|
2491
|
+
const fragments = [];
|
|
2492
|
+
const take = (candidate) => {
|
|
2493
|
+
if (!isRecord(candidate)) return;
|
|
2494
|
+
const styles = slot ? candidate[slot] : candidate;
|
|
2495
|
+
if (isRecord(styles)) fragments.push(styles);
|
|
2496
|
+
};
|
|
2497
|
+
take(config.base);
|
|
2498
|
+
for (const variant of Object.keys(config.variants ?? {})) {
|
|
2499
|
+
const value = selection[variant];
|
|
2500
|
+
if (value == null) continue;
|
|
2501
|
+
take(config.variants?.[variant]?.[String(value)]);
|
|
2502
|
+
}
|
|
2503
|
+
for (const compound of config.compoundVariants ?? []) {
|
|
2504
|
+
if (!isRecord(compound) || !matchesCompound(compound, selection, config.variants)) continue;
|
|
2505
|
+
take(compound.css);
|
|
2506
|
+
}
|
|
2507
|
+
return compose(...fragments);
|
|
2508
|
+
};
|
|
2509
|
+
return {
|
|
2510
|
+
compose,
|
|
2511
|
+
resolveRecipe,
|
|
2512
|
+
className: (...styles) => runtimeCss(...styles),
|
|
2513
|
+
allocateClassString
|
|
2514
|
+
};
|
|
2515
|
+
};
|
|
2516
|
+
//#endregion
|
|
2517
|
+
//#region src/static-session.ts
|
|
2518
|
+
const ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
2519
|
+
const denseName = (index) => {
|
|
2520
|
+
let value = index;
|
|
2521
|
+
let result = "";
|
|
2522
|
+
do {
|
|
2523
|
+
result = ALPHABET[value % 52] + result;
|
|
2524
|
+
value = Math.floor(value / 52) - 1;
|
|
2525
|
+
} while (value >= 0);
|
|
2526
|
+
return `_${result}`;
|
|
2527
|
+
};
|
|
2528
|
+
const createStaticCompilationSession = (denseClassNames = true) => {
|
|
2529
|
+
const mode = denseClassNames === true ? "stable" : denseClassNames;
|
|
2530
|
+
const session = {
|
|
2531
|
+
utilityLayer: "utilities",
|
|
2532
|
+
sourcemap: false,
|
|
2533
|
+
cssLoaded: false,
|
|
2534
|
+
transformedFiles: /* @__PURE__ */ new Set(),
|
|
2535
|
+
extractedFiles: /* @__PURE__ */ new Set(),
|
|
2536
|
+
prunableClasses: /* @__PURE__ */ new Set(),
|
|
2537
|
+
viewTransitionClasses: /* @__PURE__ */ new Set(),
|
|
2538
|
+
usedClasses: /* @__PURE__ */ new Set(),
|
|
2539
|
+
denseClasses: /* @__PURE__ */ new Map(),
|
|
2540
|
+
semanticClasses: /* @__PURE__ */ new Map(),
|
|
2541
|
+
denseClassNames: Boolean(mode),
|
|
2542
|
+
allocateClassString(className) {
|
|
2543
|
+
if (!mode) return className;
|
|
2544
|
+
return className.split(" ").filter(Boolean).map((semantic) => {
|
|
2545
|
+
let dense = session.denseClasses.get(semantic);
|
|
2546
|
+
if (!dense) {
|
|
2547
|
+
dense = mode === "local" ? denseName(session.denseClasses.size) : `_${toHash(semantic)}`;
|
|
2548
|
+
const collision = session.semanticClasses.get(dense);
|
|
2549
|
+
if (collision && collision !== semantic) throw new Error(`Bamboo compact class collision between ${JSON.stringify(collision)} and ${JSON.stringify(semantic)}. Disable \`denseClassNames\` for this build.`);
|
|
2550
|
+
session.denseClasses.set(semantic, dense);
|
|
2551
|
+
session.semanticClasses.set(dense, semantic);
|
|
2552
|
+
}
|
|
2553
|
+
return dense;
|
|
2554
|
+
}).join(" ");
|
|
2555
|
+
},
|
|
2556
|
+
markClassUsed(className) {
|
|
2557
|
+
const semantic = session.semanticClasses.get(className) ?? className;
|
|
2558
|
+
session.usedClasses.add(esc(semantic));
|
|
2559
|
+
}
|
|
2560
|
+
};
|
|
2561
|
+
return session;
|
|
2562
|
+
};
|
|
2563
|
+
const resetStaticCompilationSession = (session) => {
|
|
2564
|
+
session.cssLoaded = false;
|
|
2565
|
+
session.transformedFiles.clear();
|
|
2566
|
+
session.extractedFiles.clear();
|
|
2567
|
+
session.prunableClasses.clear();
|
|
2568
|
+
session.viewTransitionClasses.clear();
|
|
2569
|
+
session.usedClasses.clear();
|
|
2570
|
+
session.denseClasses.clear();
|
|
2571
|
+
session.semanticClasses.clear();
|
|
2572
|
+
};
|
|
2573
|
+
//#endregion
|
|
2356
2574
|
//#region src/plugin.ts
|
|
2357
2575
|
const DEFAULT_EXTENSIONS = /\.(?:[cm]?[jt]sx?)$/;
|
|
2358
2576
|
const NODE_MODULES = /node_modules/;
|
|
@@ -2395,15 +2613,17 @@ const formatSkipped = (id, skipped) => {
|
|
|
2395
2613
|
*
|
|
2396
2614
|
* Two plugins, because they do unrelated jobs on different schedules. The first emits the
|
|
2397
2615
|
* stylesheet as a virtual module and runs in dev and build alike — that is the integration,
|
|
2398
|
-
* and nothing styles without it. The second
|
|
2616
|
+
* and nothing styles without it. The second compiles every Bamboo source call in both dev
|
|
2617
|
+
* and build; there is no runtime styling fallback.
|
|
2399
2618
|
*
|
|
2400
|
-
* The
|
|
2619
|
+
* The compiler runs with `enforce: 'pre'` so it sees module source as close as possible to what
|
|
2401
2620
|
* the CSS extractor reads off disk. A plugin that rewrites style calls before bamboo
|
|
2402
2621
|
* sees them would otherwise make the two disagree, and a folded class could end up
|
|
2403
2622
|
* with no matching rule.
|
|
2404
2623
|
*/
|
|
2405
2624
|
const bamboocss = (options = {}) => {
|
|
2406
|
-
const {
|
|
2625
|
+
const { configPath, cwd, reportSkipped = false, reportSummary = true, denseClassNames = true, maxRecipeStates } = options;
|
|
2626
|
+
if (maxRecipeStates !== void 0 && (!Number.isSafeInteger(maxRecipeStates) || maxRecipeStates < 1)) throw new Error("bamboocss: `maxRecipeStates` must be a positive safe integer.");
|
|
2407
2627
|
/** Totals across the build, for the summary. */
|
|
2408
2628
|
const totals = {
|
|
2409
2629
|
folded: 0,
|
|
@@ -2411,8 +2631,35 @@ const bamboocss = (options = {}) => {
|
|
|
2411
2631
|
filesWithFolds: 0,
|
|
2412
2632
|
skipped: /* @__PURE__ */ new Map()
|
|
2413
2633
|
};
|
|
2414
|
-
|
|
2634
|
+
const staticSession = createStaticCompilationSession(denseClassNames);
|
|
2415
2635
|
const survivors = [];
|
|
2636
|
+
const survivorKeys = /* @__PURE__ */ new Set();
|
|
2637
|
+
const addSurvivor = (entry) => {
|
|
2638
|
+
const key = `${entry.file}:${entry.line}:${entry.name}:${entry.reason}`;
|
|
2639
|
+
if (survivorKeys.has(key)) return;
|
|
2640
|
+
survivorKeys.add(key);
|
|
2641
|
+
survivors.push(entry);
|
|
2642
|
+
};
|
|
2643
|
+
const clearSurvivorsFor = (file) => {
|
|
2644
|
+
for (let index = survivors.length - 1; index >= 0; index--) if (survivors[index]?.file === file) survivors.splice(index, 1);
|
|
2645
|
+
survivorKeys.clear();
|
|
2646
|
+
for (const entry of survivors) survivorKeys.add(`${entry.file}:${entry.line}:${entry.name}:${entry.reason}`);
|
|
2647
|
+
};
|
|
2648
|
+
const createSurvivorError = (entries) => {
|
|
2649
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
2650
|
+
for (const entry of entries) {
|
|
2651
|
+
const list = byFile.get(entry.file) ?? [];
|
|
2652
|
+
list.push(entry);
|
|
2653
|
+
byFile.set(entry.file, list);
|
|
2654
|
+
}
|
|
2655
|
+
const named = (entry) => entry.reason === "runtime-binding" || entry.reason === "compile-failed" ? entry.name : `${entry.name}()`;
|
|
2656
|
+
const detail = truncateList(Array.from(byFile.entries(), ([file, fileEntries]) => [` ${file}`, ...fileEntries.map((entry) => ` ${entry.line}: ${named(entry)} — ${entry.reason}`)].join("\n")), {
|
|
2657
|
+
unit: "file",
|
|
2658
|
+
separator: "\n"
|
|
2659
|
+
});
|
|
2660
|
+
const threw = entries.some((entry) => entry.reason === "compile-failed");
|
|
2661
|
+
return /* @__PURE__ */ new Error(`bamboocss: ${entries.length} call(s) could not be compiled.\n\n${detail}\n\n` + (threw ? "`compile-failed` is a module the compiler threw on — see the error logged for it above. Nothing was established about its calls either way.\n\n" : "") + "Bamboo emits no runtime styling fallback or recipe layer. Make the values finite and statically analyzable, move variation into declared recipe variants, or safelist intentional dynamic classes with `staticCss`.");
|
|
2662
|
+
};
|
|
2416
2663
|
/**
|
|
2417
2664
|
* Recipe configs read out of modules other than the one being transformed.
|
|
2418
2665
|
*
|
|
@@ -2422,6 +2669,8 @@ const bamboocss = (options = {}) => {
|
|
|
2422
2669
|
const recipeConfigCache = /* @__PURE__ */ new Map();
|
|
2423
2670
|
let ctx;
|
|
2424
2671
|
let runtimeCss;
|
|
2672
|
+
let styleCompiler;
|
|
2673
|
+
let command = "build";
|
|
2425
2674
|
let setup;
|
|
2426
2675
|
const ensureContext = async () => {
|
|
2427
2676
|
if (!setup) setup = loadConfigAndCreateContext({
|
|
@@ -2429,25 +2678,31 @@ const bamboocss = (options = {}) => {
|
|
|
2429
2678
|
cwd
|
|
2430
2679
|
}).then((loaded) => {
|
|
2431
2680
|
ctx = loaded;
|
|
2432
|
-
|
|
2681
|
+
const semanticCss = createRuntimeCss(loaded);
|
|
2682
|
+
runtimeCss = (...styles) => staticSession.allocateClassString(semanticCss(...styles));
|
|
2683
|
+
styleCompiler = createStaticStyleSetCompiler(loaded, runtimeCss, staticSession.allocateClassString);
|
|
2433
2684
|
});
|
|
2434
2685
|
await setup;
|
|
2435
2686
|
};
|
|
2436
2687
|
return [bamboocssCss({
|
|
2437
2688
|
configPath,
|
|
2438
|
-
cwd
|
|
2689
|
+
cwd,
|
|
2690
|
+
session: staticSession
|
|
2439
2691
|
}), {
|
|
2440
|
-
name: "bamboocss:
|
|
2692
|
+
name: "bamboocss:compiler",
|
|
2441
2693
|
enforce: "pre",
|
|
2442
|
-
|
|
2694
|
+
configResolved(config) {
|
|
2695
|
+
command = config.command;
|
|
2696
|
+
},
|
|
2443
2697
|
async buildStart() {
|
|
2444
|
-
if (!transform) return;
|
|
2445
2698
|
totals.folded = 0;
|
|
2446
2699
|
totals.files = 0;
|
|
2447
2700
|
totals.filesWithFolds = 0;
|
|
2448
2701
|
totals.skipped.clear();
|
|
2449
2702
|
survivors.length = 0;
|
|
2703
|
+
survivorKeys.clear();
|
|
2450
2704
|
recipeConfigCache.clear();
|
|
2705
|
+
resetStaticCompilationSession(staticSession);
|
|
2451
2706
|
await ensureContext();
|
|
2452
2707
|
},
|
|
2453
2708
|
/**
|
|
@@ -2471,7 +2726,7 @@ const bamboocss = (options = {}) => {
|
|
|
2471
2726
|
* the parser still holds the file.
|
|
2472
2727
|
*/
|
|
2473
2728
|
watchChange(id, change) {
|
|
2474
|
-
if (!
|
|
2729
|
+
if (!ctx) return;
|
|
2475
2730
|
if (!shouldTransform(id)) return;
|
|
2476
2731
|
const [filePath] = id.split("?");
|
|
2477
2732
|
if (!filePath) return;
|
|
@@ -2483,96 +2738,88 @@ const bamboocss = (options = {}) => {
|
|
|
2483
2738
|
ctx.project.reloadSourceFile(filePath);
|
|
2484
2739
|
},
|
|
2485
2740
|
async transform(code, id) {
|
|
2486
|
-
if (!transform) return null;
|
|
2487
2741
|
if (!shouldTransform(id)) return null;
|
|
2488
2742
|
await ensureContext();
|
|
2489
|
-
if (!ctx || !runtimeCss) return null;
|
|
2743
|
+
if (!ctx || !runtimeCss || !styleCompiler) return null;
|
|
2490
2744
|
const [filePath] = id.split("?");
|
|
2745
|
+
clearSurvivorsFor(filePath);
|
|
2491
2746
|
if (isGeneratedOutput(filePath, ctx)) return null;
|
|
2492
2747
|
let result;
|
|
2493
2748
|
try {
|
|
2494
2749
|
const sourceFile = ctx.project.addSourceFile(filePath, code);
|
|
2495
2750
|
const parserResult = ctx.project.parseSourceFile(filePath);
|
|
2496
|
-
if (!parserResult
|
|
2751
|
+
if (!parserResult) return null;
|
|
2497
2752
|
result = foldSource({
|
|
2498
2753
|
ctx,
|
|
2499
2754
|
code,
|
|
2500
2755
|
parserResult,
|
|
2501
2756
|
filePath,
|
|
2502
2757
|
runtimeCss,
|
|
2503
|
-
|
|
2758
|
+
styleCompiler,
|
|
2759
|
+
maxRecipeStates,
|
|
2504
2760
|
parseModule: (path) => ctx?.project.parseSourceFile(path),
|
|
2505
2761
|
recipeConfigCache,
|
|
2506
|
-
reportSurvivors:
|
|
2762
|
+
reportSurvivors: true,
|
|
2507
2763
|
sourceFile
|
|
2508
2764
|
});
|
|
2509
2765
|
} catch (error) {
|
|
2510
|
-
logger.caughtError("vite:transform", `Failed to
|
|
2766
|
+
logger.caughtError("vite:transform", `Failed to compile ${filePath}`, error);
|
|
2511
2767
|
totals.files++;
|
|
2512
|
-
totals.skipped.set("
|
|
2513
|
-
|
|
2768
|
+
totals.skipped.set("compile-failed", (totals.skipped.get("compile-failed") ?? 0) + 1);
|
|
2769
|
+
addSurvivor({
|
|
2514
2770
|
file: filePath,
|
|
2515
2771
|
line: 1,
|
|
2516
|
-
name: "
|
|
2517
|
-
reason: "
|
|
2772
|
+
name: "compiler",
|
|
2773
|
+
reason: "compile-failed"
|
|
2518
2774
|
});
|
|
2775
|
+
if (command === "serve") throw error;
|
|
2519
2776
|
return null;
|
|
2520
2777
|
}
|
|
2521
2778
|
totals.files++;
|
|
2522
2779
|
totals.folded += result.folded.length;
|
|
2523
2780
|
if (result.folded.length) totals.filesWithFolds++;
|
|
2524
2781
|
for (const entry of result.skipped) totals.skipped.set(entry.reason, (totals.skipped.get(entry.reason) ?? 0) + 1);
|
|
2525
|
-
if (
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
name: entry.name,
|
|
2532
|
-
reason: entry.reason
|
|
2533
|
-
});
|
|
2534
|
-
}
|
|
2535
|
-
if ((ctx.config.leafFallback ?? true) && result.code.includes("cssLeaf(")) survivors.push({
|
|
2782
|
+
if (result.folded.some((entry) => entry.kind === "class" || entry.kind === "slots")) staticSession.transformedFiles.add(resolve(filePath));
|
|
2783
|
+
for (const entry of result.folded) for (const className of entry.classNames) staticSession.markClassUsed(className);
|
|
2784
|
+
for (const entry of result.skipped) {
|
|
2785
|
+
if (entry.reason === "not-imported" || entry.reason === "overlapping") continue;
|
|
2786
|
+
if (entry.name === "cx" && entry.reason === "dynamic") continue;
|
|
2787
|
+
addSurvivor({
|
|
2536
2788
|
file: filePath,
|
|
2537
|
-
line: lineAt(
|
|
2538
|
-
name:
|
|
2539
|
-
reason:
|
|
2789
|
+
line: lineAt(code, entry.start),
|
|
2790
|
+
name: entry.name,
|
|
2791
|
+
reason: entry.reason
|
|
2540
2792
|
});
|
|
2541
2793
|
}
|
|
2542
2794
|
if (reportSkipped && result.skipped.length) logger.info("vite:transform", formatSkipped(filePath, result.skipped));
|
|
2543
2795
|
for (const dependency of result.dependencies) this.addWatchFile?.(dependency);
|
|
2796
|
+
if (command === "serve" && survivors.some((entry) => entry.file === filePath)) throw createSurvivorError(survivors.filter((entry) => entry.file === filePath));
|
|
2544
2797
|
if (!result.folded.length) return null;
|
|
2545
|
-
logger.debug("vite:transform", `
|
|
2798
|
+
logger.debug("vite:transform", `Compiled ${result.folded.length} call(s) in ${filePath}`);
|
|
2546
2799
|
return {
|
|
2547
2800
|
code: result.code,
|
|
2548
2801
|
map: result.map
|
|
2549
2802
|
};
|
|
2550
2803
|
},
|
|
2551
2804
|
buildEnd() {
|
|
2552
|
-
if (
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
byFile.set(entry.file, list);
|
|
2558
|
-
}
|
|
2559
|
-
const named = (e) => e.reason === "runtime-binding" || e.reason === "fold-failed" ? e.name : `${e.name}()`;
|
|
2560
|
-
const detail = truncateList(Array.from(byFile.entries(), ([file, entries]) => [` ${file}`, ...entries.map((e) => ` ${e.line}: ${named(e)} — ${e.reason}`)].join("\n")), {
|
|
2805
|
+
if (survivors.length) throw createSurvivorError(survivors);
|
|
2806
|
+
if (typeof this.getModuleInfo === "function") {
|
|
2807
|
+
if (!staticSession.cssLoaded) throw new Error(`bamboocss: compiled class values were produced, but ${JSON.stringify(VIRTUAL_CSS_ID)} was not imported. Import it once from the application entry so the compiled rules are emitted.`);
|
|
2808
|
+
const outsideExtraction = [...staticSession.transformedFiles].filter((file) => !staticSession.extractedFiles.has(file));
|
|
2809
|
+
if (outsideExtraction.length) throw new Error(`bamboocss: ${outsideExtraction.length} statically compiled module(s) are outside the CSS extraction graph:\n\n${truncateList(outsideExtraction.map((file) => ` ${file}`), {
|
|
2561
2810
|
unit: "file",
|
|
2562
2811
|
separator: "\n"
|
|
2563
|
-
});
|
|
2564
|
-
const threw = survivors.some((entry) => entry.reason === "fold-failed");
|
|
2565
|
-
throw new Error(`bamboocss: ${survivors.length} call(s) could not be folded, and \`failOnUnfolded\` is on.\n\n${detail}\n\n` + (threw ? "`fold-failed` is a module the fold threw on — see the error logged for it above. Nothing was established about its calls either way, so it cannot support the guarantee this option makes.\n\n" : "") + "Each one keeps `styled-system/css` in the bundle, so the engine cannot be dropped however many other calls folded. Make the values static, move the variation into a `cva` variant, or generate them with `staticCss` — or set `failOnUnfolded: false` to accept the runtime.");
|
|
2812
|
+
})}\n\nAdd them to \`include\` in bamboo.config, or no CSS rule can back their emitted classes.`);
|
|
2566
2813
|
}
|
|
2567
|
-
if (!
|
|
2814
|
+
if (!reportSummary) return;
|
|
2568
2815
|
const declined = Array.from(totals.skipped.values()).reduce((sum, count) => sum + count, 0);
|
|
2569
2816
|
const total = totals.folded + declined;
|
|
2570
2817
|
if (!total) return;
|
|
2571
2818
|
const share = Math.round(totals.folded / total * 100);
|
|
2572
2819
|
const reasons = Array.from(totals.skipped.entries()).sort((a, b) => b[1] - a[1]).map(([reason, count]) => `${reason}=${count}`).join(" ");
|
|
2573
|
-
logger.info("vite:transform", `
|
|
2820
|
+
logger.info("vite:transform", `Compiled ${totals.folded}/${total} (${share}%) across ${totals.filesWithFolds}/${totals.files} files` + (reasons ? ` — declined: ${reasons}` : ""));
|
|
2574
2821
|
}
|
|
2575
2822
|
}];
|
|
2576
2823
|
};
|
|
2577
2824
|
//#endregion
|
|
2578
|
-
export { VIRTUAL_CSS_ID, bamboocss, bamboocss as default
|
|
2825
|
+
export { VIRTUAL_CSS_ID, bamboocss, bamboocss as default };
|