@bamboocss/vite 1.45.4 → 1.46.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.mjs CHANGED
@@ -1,132 +1,65 @@
1
- import { findConfig, getConfigDependencies } from "@bamboocss/config";
2
- import { Builder, loadConfigAndCreateContext, markStaticCompilerActive } from "@bamboocss/node";
1
+ import { t as bare } from "./class-name.mjs";
3
2
  import { logger } from "@bamboocss/logger";
4
- import { compact, createCssUncached, createMergeCss, esc, memo, toHash, truncateList, viewTransitionClassName } from "@bamboocss/shared";
5
- import remapping from "@ampproject/remapping";
6
- import MagicString from "magic-string";
7
- import postcss from "postcss";
8
- import selectorParser from "postcss-selector-parser";
9
- import { createHash } from "node:crypto";
3
+ import { esc, truncateList } from "@bamboocss/shared";
4
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
10
5
  import { readFileSync } from "node:fs";
11
- import { dirname, relative, resolve } from "node:path";
12
- import { resolveTsPathPattern } from "@bamboocss/config/ts-path";
13
- import { box, maybeBoxNode } from "@bamboocss/extractor";
14
- import { Node, SyntaxKind, VariableDeclarationKind, ts } from "ts-morph";
15
- //#region src/prune-static-css.ts
16
- /** The generated declaration that identifies a Bamboo stylesheet after minification. */
17
- const SENTINEL = "--made-with-bamboo";
6
+ import { resolve } from "node:path";
7
+ import { markStaticCompilerActive } from "@bamboocss/node/static-compiler";
8
+ //#region src/lazy-modules.ts
18
9
  /**
19
- * A class name with its CSS escapes removed, which is the only spelling both sides agree on.
10
+ * Keep one asynchronous initialization in flight, retain its fulfilled value, and forget only
11
+ * a rejected attempt so a later Vite rebuild can recover.
20
12
  *
21
- * The same class reaches the stylesheet either escaped or not `--bottom-mask-size_16px` is a
22
- * valid selector as written, since a CSS ident may begin with `--`, while `esc` produces the
23
- * escaped `\--…` form that reachability keys are stored in. Comparing raw spellings therefore
24
- * missed a rule written the other way, and pruning removed an atom whose rule was in the sheet
25
- * all along. It could only ever affect names needing an escape, which is why it presented as
26
- * every custom property and vendor-prefixed declaration losing its rule at once.
27
- *
28
- * Stripping backslashes is unambiguous here: a semantic atom name never contains a literal one.
13
+ * Starting through a resolved promise also turns a synchronous loader throw into the same
14
+ * rejected-promise contract as a failed dynamic import.
29
15
  */
30
- const bare = (className) => className.replaceAll("\\", "");
16
+ const createRetryableLazy = (load) => {
17
+ let pending;
18
+ return () => {
19
+ if (pending) return pending;
20
+ const attempt = Promise.resolve().then(load);
21
+ pending = attempt;
22
+ attempt.catch(() => {
23
+ if (pending === attempt) pending = void 0;
24
+ });
25
+ return attempt;
26
+ };
27
+ };
28
+ /** Process-wide module loading; individual plugin instances still own their mutable state. */
29
+ const loadNodeModule = createRetryableLazy(() => import("./node-module.mjs"));
30
+ const loadConfigModule = createRetryableLazy(() => import("./config-module.mjs"));
31
31
  /**
32
- * Remove source-graph atoms no transformed module can emit.
33
- *
34
- * `prunableClasses` contains only atoms extracted from the source graph. Explicit `staticCss`
35
- * additions are absent and survive as a safelist; graph atoms are governed by the transformed
36
- * module reachability set, regardless of whether they originated in `css()` or a recipe.
32
+ * Keep stylesheet parsing, selector inventory and late sourcemap rewriting behind one built
33
+ * chunk. The injectable loader proves sharing and retry without exposing a package subpath.
37
34
  */
38
- const pruneStaticCss = (css, session, { prune = true } = {}) => {
39
- if (!css.includes(SENTINEL)) return css;
40
- const root = postcss.parse(css);
41
- const prunable = new Set([...session.prunableClasses].map(bare));
42
- const used = new Set([...session.usedClasses].map(bare));
43
- const isUtilityRule = (rule) => {
44
- let parent = rule.parent;
45
- while (parent) {
46
- if (parent.type === "atrule") {
47
- const atRule = parent;
48
- if (atRule.name === "layer" && atRule.params === session.utilityLayer) return true;
49
- }
50
- parent = parent.parent;
51
- }
52
- return false;
35
+ const createLazyCssOutputModule = (loadCssOutput = () => import("./css-output-module.mjs")) => createRetryableLazy(loadCssOutput);
36
+ /** One process-wide CSS-output load shared by every plugin instance and Vite environment. */
37
+ const loadCssOutputModule = createLazyCssOutputModule();
38
+ /**
39
+ * Keep the AST fold behind its own built chunk. The injectable loader is an architectural
40
+ * seam: callers can prove sharing and retry without a production-only switch, while the
41
+ * default remains a statically discoverable dynamic import for both published formats.
42
+ */
43
+ const createLazyFoldModule = (loadFold = () => import("./fold-module.mjs")) => createRetryableLazy(loadFold);
44
+ /** One process-wide fold-module load shared by every plugin instance and Vite environment. */
45
+ const loadFoldModule = createLazyFoldModule();
46
+ /** One Builder per CSS plugin instance, created only when a hook first needs it. */
47
+ const createLazyBuilder = (loadNode = loadNodeModule) => createRetryableLazy(async () => {
48
+ const { Builder } = await loadNode();
49
+ return new Builder();
50
+ });
51
+ /** Build and publish one complete fold state; no caller can observe partial initialization. */
52
+ const createLazyCompilerState = (loadContext, loadFold) => createRetryableLazy(async () => {
53
+ const [context, fold] = await Promise.all([loadContext(), loadFold()]);
54
+ const runtimeCss = fold.createRuntimeCss(context);
55
+ const styleCompiler = fold.createStaticStyleSetCompiler(context, runtimeCss);
56
+ return {
57
+ context,
58
+ foldSource: fold.foldSource,
59
+ runtimeCss,
60
+ styleCompiler
53
61
  };
54
- if (prune) root.walkRules((rule) => {
55
- if (!isUtilityRule(rule)) return;
56
- let removedAny = false;
57
- let selector;
58
- try {
59
- selector = selectorParser((selectors) => {
60
- selectors.each((candidate) => {
61
- const classes = /* @__PURE__ */ new Set();
62
- candidate.walkClasses((classNode) => {
63
- classes.add(bare(classNode.toString().slice(1)));
64
- });
65
- if (classes.size !== 1) return;
66
- const [className] = classes;
67
- if (!className || !prunable.has(className) || used.has(className)) return;
68
- candidate.remove();
69
- removedAny = true;
70
- session.prunedClasses.add(className);
71
- });
72
- }).processSync(rule.selector);
73
- } catch {
74
- return;
75
- }
76
- if (!removedAny) return;
77
- if (!selector.trim()) {
78
- rule.remove();
79
- return;
80
- }
81
- rule.selector = selector;
82
- });
83
- let removed = true;
84
- while (removed) {
85
- removed = false;
86
- root.walkAtRules((rule) => {
87
- if (rule.nodes?.length !== 0) return;
88
- rule.remove();
89
- removed = true;
90
- });
91
- }
92
- if (prune) {
93
- const present = /* @__PURE__ */ new Set();
94
- root.walkRules((rule) => {
95
- if (!isUtilityRule(rule)) return;
96
- try {
97
- selectorParser((selectors) => {
98
- selectors.walkClasses((classNode) => {
99
- present.add(bare(classNode.toString().slice(1)));
100
- });
101
- }).processSync(rule.selector);
102
- } catch {}
103
- });
104
- const orphaned = [];
105
- for (const className of session.usedClasses) {
106
- if (/\s/.test(className)) {
107
- orphaned.push(className);
108
- continue;
109
- }
110
- if (!prunable.has(bare(className))) continue;
111
- if (present.has(bare(className))) continue;
112
- orphaned.push(className);
113
- }
114
- if (orphaned.length) {
115
- const describe = (className) => {
116
- if (/\s/.test(className)) return ` ${className}\n (malformed key: a class name cannot contain whitespace)`;
117
- const extracted = session.prunableClasses.has(className) ? "in the extracted atoms" : "NOT extracted";
118
- const bare = className.replaceAll("\\", "");
119
- const near = [...present].filter((candidate) => candidate !== className && candidate.replaceAll("\\", "") === bare);
120
- return ` ${className}\n (${extracted}; no rule in the sheet` + (near.length ? `; a rule exists under ${near.map((n) => JSON.stringify(n)).join(", ")}` : "") + `)`;
121
- };
122
- throw new Error(`bamboocss: ${orphaned.length} compiled class(es) have no rule in the emitted stylesheet. Elements carrying them would render unstyled.\n\n${truncateList(orphaned.map(describe), {
123
- unit: "class",
124
- separator: "\n"
125
- })}\n\nThis is a compiler bug rather than anything to fix in your source. Please report it with the block above — the parenthesised part is what distinguishes an atom that was never emitted from one whose rule is present under a different spelling.`);
126
- }
127
- }
128
- return root.toString();
129
- };
62
+ });
130
63
  //#endregion
131
64
  //#region src/static-session.ts
132
65
  const createStaticCompilationSession = () => {
@@ -140,8 +73,19 @@ const createStaticCompilationSession = () => {
140
73
  viewTransitionClasses: /* @__PURE__ */ new Set(),
141
74
  usedClasses: /* @__PURE__ */ new Set(),
142
75
  expectedEnvironments: void 0,
143
- startedEnvironments: /* @__PURE__ */ new Set(),
76
+ participatingEnvironments: /* @__PURE__ */ new Set(),
77
+ completedEnvironments: /* @__PURE__ */ new Set(),
144
78
  prunedClasses: /* @__PURE__ */ new Set(),
79
+ beginOutputProjection(_environment, _outputOptions, _bundle, replacesGeneratedStylesheet) {
80
+ if (replacesGeneratedStylesheet) session.prunedClasses.clear();
81
+ const prunable = new Set([...session.prunableClasses].map((className) => className.replaceAll("\\", "")));
82
+ const requiredClasses = new Set([...session.usedClasses].filter((className) => prunable.has(className.replaceAll("\\", ""))));
83
+ return {
84
+ cssLoaded: session.cssLoaded,
85
+ requiredClasses,
86
+ restore() {}
87
+ };
88
+ },
145
89
  markClassUsed(className) {
146
90
  for (const token of className.split(" ")) {
147
91
  if (!token) continue;
@@ -152,30 +96,28 @@ const createStaticCompilationSession = () => {
152
96
  return session;
153
97
  };
154
98
  /**
155
- * Environments this run intends to build that have not been compiled yet.
99
+ * Expected or observed environments whose current generation has not completed yet.
156
100
  *
157
101
  * Empty means everything the run will contribute has been contributed, which is the condition
158
102
  * every whole-run judgement here waits for: pruning the stylesheet against reachability, and
159
103
  * the two guards that ask whether the compiled modules and the extraction graph agree. Each of
160
104
  * those is false about a build in progress and true only about a finished one.
161
105
  *
162
- * Empty is also the answer for a single-environment build, where nothing announced an
163
- * environment list because there is only ever one so that path is unchanged.
106
+ * The environment currently at `buildEnd` may be supplied as the candidate completing this
107
+ * call. That keeps publication transactional: whole-run checks can include its finished graph
108
+ * without marking it complete before those checks themselves succeed.
109
+ *
110
+ * Empty is also the answer for a single-environment build, where the only participant is the
111
+ * completing candidate — so that path is unchanged.
164
112
  *
165
113
  * An environment a run declares and then never builds leaves this permanently non-empty, and
166
114
  * those judgements are skipped for the run. Every one of them errs towards shipping more CSS
167
115
  * or asserting less, so that is the safe direction to be wrong in.
168
116
  */
169
- const remainingEnvironments = (session) => [...session.expectedEnvironments ?? []].filter((name) => !session.startedEnvironments.has(name));
170
- const resetStaticCompilationSession = (session) => {
171
- session.cssLoaded = false;
172
- session.transformedFiles.clear();
173
- session.extractedFiles.clear();
174
- session.prunableClasses.clear();
175
- session.viewTransitionClasses.clear();
176
- session.usedClasses.clear();
177
- session.startedEnvironments.clear();
178
- session.prunedClasses.clear();
117
+ const remainingEnvironments = (session, completingEnvironment) => {
118
+ const participating = new Set(session.expectedEnvironments ?? []);
119
+ for (const environment of session.participatingEnvironments) participating.add(environment);
120
+ return [...participating].filter((name) => name !== completingEnvironment && !session.completedEnvironments.has(name));
179
121
  };
180
122
  //#endregion
181
123
  //#region src/css.ts
@@ -222,95 +164,6 @@ const queryOf = (id) => {
222
164
  * `transform`, and both are answered by the same middleware.
223
165
  */
224
166
  const asError = (error, context) => error instanceof Error ? error : new Error(`bamboocss: ${context}: ${String(error)}`, { cause: error });
225
- const INLINE_SOURCE_MAP = /\n?\/\/# sourceMappingURL=data:application\/json[^\n]*$/;
226
- /** Rewrite one generated chunk without invalidating all mappings after the changed string. */
227
- const replaceChunkReference = (chunk, bundle, previous, next, sourcemap) => {
228
- if (!chunk.code.includes(previous)) return;
229
- const magic = new MagicString(chunk.code);
230
- let index = chunk.code.indexOf(previous);
231
- while (index !== -1) {
232
- magic.overwrite(index, index + previous.length, next);
233
- index = chunk.code.indexOf(previous, index + previous.length);
234
- }
235
- chunk.code = magic.toString();
236
- if (!chunk.map) return;
237
- const file = chunk.map.file;
238
- const debugId = chunk.map.debugId;
239
- const combined = remapping([magic.generateMap({
240
- source: chunk.fileName,
241
- hires: "boundary"
242
- }), chunk.map], () => null);
243
- if (file) combined.file = file;
244
- if (debugId) combined.debugId = debugId;
245
- const rollupMap = combined;
246
- rollupMap.toUrl = () => `data:application/json;charset=utf-8;base64,${Buffer.from(combined.toString()).toString("base64")}`;
247
- chunk.map = rollupMap;
248
- if (sourcemap === "inline") {
249
- chunk.code = chunk.code.replace(INLINE_SOURCE_MAP, "");
250
- chunk.code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(combined.toString()).toString("base64")}`;
251
- return;
252
- }
253
- const mapAsset = bundle[`${chunk.fileName}.map`];
254
- if (mapAsset?.type === "asset") mapAsset.source = combined.toString();
255
- };
256
- /** Replace an emitted filename wherever Vite or Rollup has already recorded it. */
257
- const replaceAssetReferences = (bundle, previous, next, sourcemap) => {
258
- const replace = (value) => value.replaceAll(previous, next);
259
- for (const output of Object.values(bundle)) {
260
- if (output.type === "asset") {
261
- if (typeof output.source === "string") output.source = replace(output.source);
262
- continue;
263
- }
264
- replaceChunkReference(output, bundle, previous, next, sourcemap);
265
- const referencedFiles = output.referencedFiles;
266
- if (referencedFiles) output.referencedFiles = referencedFiles.map(replace);
267
- const importedCss = output.viteMetadata?.importedCss;
268
- if (importedCss?.delete(previous)) importedCss.add(next);
269
- }
270
- };
271
- /**
272
- * Could this bundle entry be the generated stylesheet?
273
- *
274
- * The filename is checked before the bytes because the alternative decodes every asset in the
275
- * bundle to a UTF-8 string in order to search it — fonts, images and sourcemaps included. On an
276
- * app with a large asset graph that is seconds of decode and a lot of garbage, twice over, to
277
- * answer a question the extension already answers. The marker is a CSS custom property, so it
278
- * cannot occur anywhere but CSS.
279
- */
280
- const carriesGeneratedCss = (output) => output.type === "asset" && output.fileName.endsWith(".css");
281
- /**
282
- * Prune compiler-owned CSS, then give any sheet whose bytes changed a hash of those bytes.
283
- *
284
- * Rollup has already expanded `[hash]` when `generateBundle` runs. Mutating only `source`
285
- * would therefore leave two different reachable subsets under one CDN key. The extra final
286
- * hash is not cosmetic: it makes late graph reachability cache-safe.
287
- *
288
- * Renaming is therefore not a choice this takes. Pruned bytes under the unpruned sheet's name
289
- * is the one outcome that must never be reachable, and a sheet nothing was removed from keeps
290
- * its name because its bytes are unchanged — so "rename" is a consequence of "the bytes moved",
291
- * not a second option. `prune` is the only knob.
292
- */
293
- const optimizeStaticCssAssets = (bundle, session, options = {}) => {
294
- const { prune = true, sourcemap = session.sourcemap } = options;
295
- /** Assets in this bundle that carry the generated stylesheet, pruned or not. */
296
- let sheets = 0;
297
- for (const output of Object.values(bundle)) {
298
- if (!carriesGeneratedCss(output)) continue;
299
- const source = typeof output.source === "string" ? output.source : Buffer.from(output.source).toString();
300
- if (!source.includes("--made-with-bamboo")) continue;
301
- sheets++;
302
- if (!prune) continue;
303
- const optimized = pruneStaticCss(source, session);
304
- output.source = optimized;
305
- if (optimized === source) continue;
306
- const nextName = output.fileName.replace(/\.css$/, `.b-${toHash(optimized)}.css`);
307
- if (bundle[nextName] && bundle[nextName] !== output) throw new Error(`bamboocss: final CSS asset name collision at ${JSON.stringify(nextName)}.`);
308
- const previous = output.fileName;
309
- output.fileName = nextName;
310
- replaceAssetReferences(bundle, previous, nextName, sourcemap);
311
- }
312
- return { sheets };
313
- };
314
167
  /**
315
168
  * Serve bamboo's stylesheet as a virtual module, in dev and in build.
316
169
  *
@@ -325,21 +178,25 @@ const optimizeStaticCssAssets = (bundle, session, options = {}) => {
325
178
  * process just wrote, which is a race on any watch rebuild.
326
179
  */
327
180
  const bamboocssCss = (options) => {
328
- const { configPath, cwd, session, pruneCss = true } = options;
329
- /**
330
- * Environments whose `load` served the virtual stylesheet.
331
- *
332
- * The lost-sheet guard below is about an asset that existed and then went missing, so it
333
- * can only be asked of an environment that asked for one. An SSR bundle never imports the
334
- * stylesheet — the client build emits it — and firing there turned a correct two-environment
335
- * build into a hard failure.
336
- */
337
- const servedEnvironments = /* @__PURE__ */ new Set();
338
- const builder = new Builder();
181
+ const { configPath, cwd, loadCssOutput = loadCssOutputModule, session, pruneCss = true } = options;
182
+ let builder;
183
+ const loadBuilder = createLazyBuilder();
184
+ const ensureBuilder = async () => {
185
+ const loaded = await loadBuilder();
186
+ builder = loaded;
187
+ return loaded;
188
+ };
339
189
  let server;
340
190
  let command = "build";
341
191
  /** The run's own `build` options, for a bundler with no per-environment config. */
342
192
  let ssrBuildOptions;
193
+ /** Included owners plus local modules their extraction actually resolved and read. */
194
+ const extractedSourceFiles = () => {
195
+ const activeBuilder = builder;
196
+ const context = activeBuilder?.context;
197
+ if (!context) return [];
198
+ return [...new Set([...context.getFiles(), ...activeBuilder.getResolutionReadFiles()].map((file) => context.runtime.path.abs(context.config.cwd, file)))];
199
+ };
343
200
  /**
344
201
  * Serialised, because both `load` and the watcher can reach it and `Builder` keeps one
345
202
  * context. Two overlapping passes would extract into the same encoder and emit the
@@ -347,6 +204,7 @@ const bamboocssCss = (options) => {
347
204
  */
348
205
  let pending;
349
206
  const build = async () => {
207
+ const builder = await ensureBuilder();
350
208
  await builder.setup({
351
209
  configPath,
352
210
  cwd,
@@ -358,7 +216,7 @@ const bamboocssCss = (options) => {
358
216
  if (builder.context) {
359
217
  session.utilityLayer = builder.context.config.layers?.utilities ?? "utilities";
360
218
  session.extractedFiles.clear();
361
- for (const file of builder.context.getFiles()) session.extractedFiles.add(builder.context.runtime.path.abs(builder.context.config.cwd, file));
219
+ for (const file of extractedSourceFiles()) session.extractedFiles.add(file);
362
220
  }
363
221
  let graphAtomHashes;
364
222
  if (builder.context) {
@@ -379,7 +237,7 @@ const bamboocssCss = (options) => {
379
237
  session.prunableClasses.add(esc(transition.className));
380
238
  }
381
239
  }
382
- return command === "serve" ? pruneStaticCss(css, session, { prune: false }) : css;
240
+ return css;
383
241
  };
384
242
  const generate = () => {
385
243
  pending = Promise.resolve(pending).catch(() => void 0).then(build);
@@ -405,10 +263,43 @@ const bamboocssCss = (options) => {
405
263
  let prebuilt;
406
264
  let prebuildStarted = false;
407
265
  const prebuild = async () => {
408
- if (prebuildStarted) return;
409
- prebuildStarted = true;
410
- prebuilt = generate();
411
- await prebuilt;
266
+ if (!prebuildStarted) {
267
+ prebuildStarted = true;
268
+ prebuilt = generate();
269
+ }
270
+ const attempt = prebuilt ?? pending;
271
+ if (!attempt) return;
272
+ try {
273
+ await attempt;
274
+ } catch (error) {
275
+ if (prebuilt === attempt || prebuilt === void 0 && pending === attempt) {
276
+ prebuildStarted = false;
277
+ prebuilt = void 0;
278
+ }
279
+ throw error;
280
+ }
281
+ };
282
+ /**
283
+ * The dev config graph is independent of Builder setup and is needed one hook earlier. Keep
284
+ * its module load and graph walk single-flight as well: shared plugins may be resolved for
285
+ * client and SSR concurrently, but both describe the same Vite config.
286
+ */
287
+ const configDependencyLoaders = /* @__PURE__ */ new Map();
288
+ const discoverConfigDependencies = (root) => {
289
+ const projectRoot = cwd ?? root;
290
+ let discover = configDependencyLoaders.get(projectRoot);
291
+ if (!discover) {
292
+ const created = createRetryableLazy(async () => {
293
+ const { findConfig, getConfigDependencies } = await loadConfigModule();
294
+ return getConfigDependencies(findConfig({
295
+ cwd: projectRoot,
296
+ file: configPath
297
+ })).deps;
298
+ });
299
+ configDependencyLoaders.set(projectRoot, created);
300
+ discover = created;
301
+ }
302
+ return discover();
412
303
  };
413
304
  return {
414
305
  name: "bamboocss:css",
@@ -423,7 +314,7 @@ const bamboocssCss = (options) => {
423
314
  * happened once per environment.
424
315
  */
425
316
  sharedDuringBuild: true,
426
- configResolved(config) {
317
+ async configResolved(config) {
427
318
  command = config.command;
428
319
  session.sourcemap = config.build.sourcemap;
429
320
  ssrBuildOptions = {
@@ -457,10 +348,7 @@ const bamboocssCss = (options) => {
457
348
  * that meant.
458
349
  */
459
350
  if (config.command === "serve") try {
460
- const { deps } = getConfigDependencies(findConfig({
461
- cwd: cwd ?? config.root,
462
- file: configPath
463
- }));
351
+ const deps = await discoverConfigDependencies(config.root);
464
352
  config.configFileDependencies.push(...deps);
465
353
  } catch {}
466
354
  if (config.builder && config.environments) session.expectedEnvironments = new Set(Object.keys(config.environments));
@@ -471,2618 +359,161 @@ const bamboocssCss = (options) => {
471
359
  * environment is set up and pruning is therefore safe.
472
360
  */
473
361
  buildApp: {
474
- order: "pre",
475
- async handler(builder) {
476
- session.expectedEnvironments = new Set(Object.keys(builder.environments));
477
- }
478
- },
479
- /**
480
- * Put `styled-system/` on disk before anything resolves an import of it.
481
- *
482
- * Normalized rather than rethrown as caught, for the reason the compiler's `buildStart`
483
- * gives: this evaluates the user's config and its hooks, and in dev anything that is not an
484
- * object crashes Vite's error middleware instead of being reported.
485
- */
486
- async buildStart() {
487
- try {
488
- await prebuild();
489
- } catch (error) {
490
- throw asError(error, `failed to generate ${VIRTUAL_CSS_ID}`);
491
- }
492
- },
493
- resolveId(id) {
494
- const query = queryOf(id);
495
- const base = id.slice(0, id.length - query.length);
496
- if (base !== "virtual:bamboo.css" && base !== RESOLVED_ID) return null;
497
- return `${RESOLVED_ID}${query}`;
498
- },
499
- async load(id) {
500
- const query = queryOf(id);
501
- if (id.slice(0, id.length - query.length) !== RESOLVED_ID) return null;
502
- servedEnvironments.add(this.environment?.name ?? "default");
503
- session.cssLoaded = true;
504
- let css;
505
- try {
506
- const first = prebuilt;
507
- prebuilt = void 0;
508
- css = await (first ?? generate());
509
- } catch (error) {
510
- throw asError(error, `failed to generate ${VIRTUAL_CSS_ID}`);
511
- }
512
- if (this.addWatchFile) for (const file of builder.context?.getFiles() ?? []) this.addWatchFile(builder.context.runtime.path.abs(builder.context.config.cwd, file));
513
- return css;
514
- },
515
- configureServer(devServer) {
516
- server = devServer;
517
- /**
518
- * The graph the stylesheet's own module lives in, which is the one that has to reach it.
519
- *
520
- * `load` registers every extracted file with `addWatchFile`, and `vite:css-analysis`
521
- * turns those into real importer edges — the virtual module ends up a direct importer of
522
- * each file the extractor read. So an edit to any of them propagates to the stylesheet on
523
- * Vite's own pass, in whichever environment holds that edge.
524
- *
525
- * The client one, because CSS is a client concern: an ssr environment never applies a
526
- * stylesheet update, and asking whether *any* environment matched would skip the forced
527
- * reload below for a server-only module whose styles the client still has to be told
528
- * about. Vite 5 has one graph and no `environments`, where the question is exact.
529
- */
530
- const clientGraph = devServer.environments?.client?.moduleGraph ?? devServer.moduleGraph;
531
- const invalidate = (file) => {
532
- const ctx = builder.context;
533
- if (!ctx) return;
534
- if (!ctx.getFiles().some((f) => ctx.runtime.path.abs(ctx.config.cwd, f) === file)) return;
535
- prebuilt = void 0;
536
- const mod = server?.moduleGraph.getModuleById(RESOLVED_ID);
537
- if (!mod) return;
538
- if (clientGraph.getModulesByFile(file)?.size) return;
539
- server?.moduleGraph.invalidateModule(mod);
540
- server?.reloadModule(mod);
541
- logger.debug("vite", `styles invalidated by ${file}`);
542
- };
543
- devServer.watcher.on("change", invalidate);
544
- devServer.watcher.on("add", invalidate);
545
- devServer.watcher.on("unlink", invalidate);
546
- },
547
- generateBundle: {
548
- order: "post",
549
- handler(_, bundle) {
550
- const environment = this.environment;
551
- /**
552
- * Every environment of this run has already had its modules compiled.
553
- *
554
- * Reachability is what pruning removes rules against, and it is only complete once
555
- * nothing is left to contribute to it. The stylesheet is emitted and finalized by the
556
- * environment that *imports* it, which in an SSR app is the client — and the client
557
- * builds first, before the server environment has transformed a single module. Pruning
558
- * there deletes every rule for a class only the server graph reaches, and the pages
559
- * link the pruned copy: one project lost 39% of its atoms that way, presenting as
560
- * rarely-used classes such as `md:{display:inline-block}` silently not applying.
561
- *
562
- * So the full extracted stylesheet ships instead, which is what `pruneCss: false` asks
563
- * for by hand. Being the last environment is not the common case — frameworks build the
564
- * client first — but it is the only one where the answer is knowable, and a framework
565
- * that builds its server bundle first does get pruned output.
566
- */
567
- const pending = remainingEnvironments(session);
568
- const { sheets } = optimizeStaticCssAssets(bundle, session, {
569
- prune: pruneCss && pending.length === 0,
570
- sourcemap: environment?.config?.build?.sourcemap
571
- });
572
- if (sheets && !pruneCss) logger.info("vite", "Reachability pruning is off (`pruneCss: false`). The full extracted stylesheet ships.");
573
- else if (sheets && pending.length) logger.info("vite", `Reachability pruning skipped: the stylesheet is emitted by the ${JSON.stringify(environment?.name ?? "default")} environment, and ${truncateList(pending, {
574
- unit: "environment",
575
- separator: ", "
576
- })} ${pending.length === 1 ? "has" : "have"} not been compiled in this run. The full extracted stylesheet ships — nothing is missing from it.`);
577
- if (!servedEnvironments.has(environment?.name ?? "default")) return;
578
- if (!session.transformedFiles.size) return;
579
- /**
580
- * An SSR bundle emits no CSS assets, and is not supposed to.
581
- *
582
- * `build.ssrEmitAssets` is off by default, so Vite discards them: the client build is
583
- * what carries the stylesheet, and a server bundle that imports `virtual:bamboo.css`
584
- * from shared code — a root component, a layout — still asks this plugin to load it.
585
- * Which means the environment *served* the sheet and then emitted nothing, and the
586
- * check below read that as the failure it exists to catch.
587
- *
588
- * It fails a build that is entirely correct. Qwik's `vite build --ssr` is the shape
589
- * that showed it: 7/7 calls compiled, the client bundle carrying the stylesheet, and
590
- * the server bundle refusing to finish. React Router does not hit it only because its
591
- * plugin turns `ssrEmitAssets` on.
592
- *
593
- * Read per environment where that exists, falling back to the run's own config, so
594
- * Vite 5's single-config builds are answered by the same question.
595
- */
596
- const buildOptions = environment?.config?.build ?? ssrBuildOptions;
597
- if (buildOptions?.ssr && !buildOptions.ssrEmitAssets) return;
598
- if (!Object.values(bundle).some((output) => {
599
- if (!carriesGeneratedCss(output)) return false;
600
- return (typeof output.source === "string" ? output.source : Buffer.from(output.source).toString()).includes("--made-with-bamboo");
601
- })) throw new Error(`bamboocss: ${session.transformedFiles.size} module(s) were compiled to Bamboo class values, but no emitted asset carries the generated stylesheet. The build would ship unstyled.\n\nThis happens when another plugin, or the bundler itself, drops or replaces the CSS asset after it is emitted. If you are on Rolldown, report this — the rename that used to cause it is already disabled there. Otherwise look for a plugin running in \`generateBundle\` that rewrites CSS assets.`);
602
- }
603
- }
604
- };
605
- };
606
- //#endregion
607
- //#region src/fold-analysis.ts
608
- /**
609
- * Nodes that *compose* a value out of their children rather than computing one.
610
- *
611
- * The boundary of the walk below, and the whole of its precision. Climbing through these
612
- * keeps a value's provenance: `'red.300'` inside `{ color: 'red.300' }` inside a default is
613
- * still the default's. Anything else — a call, a function body, a JSX element — produces its
614
- * value by being evaluated, so what is written inside it is an argument to that evaluation
615
- * and not the enclosing default's value.
616
- *
617
- * Without the boundary, `({ cls = css({ color: 'red.300' }) }) => cls` is rejected: the call's
618
- * own literal argument is syntactically inside a default, so an unbounded walk calls it one.
619
- * That is correct code, and rejecting it fails the build.
620
- */
621
- const composesValue = (node) => Node.isObjectLiteralExpression(node) || Node.isArrayLiteralExpression(node) || Node.isPropertyAssignment(node) || Node.isShorthandPropertyAssignment(node) || Node.isSpreadAssignment(node) || Node.isSpreadElement(node) || Node.isAsExpression(node) || Node.isParenthesizedExpression(node) || Node.isNonNullExpression(node) || Node.isTypeAssertion(node) || Node.isSatisfiesExpression(node);
622
- /** Is `inner` written within `outer`? Positions rather than a walk, so it is O(1). */
623
- const contains = (outer, inner) => outer.getSourceFile() === inner.getSourceFile() && outer.getStart() <= inner.getStart() && inner.getEnd() <= outer.getEnd();
624
- /**
625
- * Did this value come from the `= …` of a destructuring binding?
626
- *
627
- * `const { tone = 'red.300' } = source` boxes as the literal `'red.300'`: the extractor's
628
- * `maybeDefinitionValue` tests for an initializer first and returns the boxed default, never
629
- * reaching the branch that would read `source`. So the default is reported as the value whether
630
- * or not it is the one that applies.
631
- *
632
- * For extraction that is merely optimistic, and deliberately so: a CLI or PostCSS build ships a
633
- * runtime `css()`, where the default genuinely does apply when the caller omits the key, and it
634
- * needs a rule behind it. Folding is where the same resolution turns into a wrong answer,
635
- * because the call is *replaced* by that value.
636
- *
637
- * Stops at the first non-composing parent, so a call written inside a default keeps its own
638
- * provenance, and checks that the binding element was reached through its initializer, so
639
- * `{ tone = X }`'s name node is not mistaken for its default.
640
- */
641
- const isBindingElementDefault = (node) => {
642
- if (node && Node.isCallExpression(node)) return false;
643
- let current = node;
644
- while (current) {
645
- const parent = current.getParent();
646
- if (!parent) return false;
647
- if (Node.isBindingElement(parent)) return parent.getInitializer() === current;
648
- if (!composesValue(parent)) return false;
649
- current = parent;
650
- }
651
- return false;
652
- };
653
- /**
654
- * The same question asked of a whole box, including how it was resolved.
655
- *
656
- * The node a box reports is not always the one its value came from — an empty `{}` default
657
- * boxes against the call rather than against the `{}` — so the resolution stack is consulted
658
- * too. A binding element reaches that stack by having been resolved *through*, which is the
659
- * signal the extractor itself reads when one of these is a conditional's test.
660
- *
661
- * Only the entries that are binding elements are examined. Walking up from every other entry
662
- * was tried and never once changed a verdict across the default spellings or the sandbox's own
663
- * modules, while accounting for most of the parent hops this does — the stack carries nodes
664
- * that were never resolved through, including a call's own arguments, so walking from them is
665
- * both the expensive half and the one that reaches conclusions it has no basis for.
666
- *
667
- * A binding element without an initializer carries no default to mistrust: `const { tone } =
668
- * source` either resolves from `source` or does not resolve at all.
669
- */
670
- const isFromBindingDefault = (node) => {
671
- const own = node.getNode?.();
672
- if (isBindingElementDefault(own)) return true;
673
- for (const entry of node.getStack?.() ?? []) {
674
- if (!Node.isBindingElement(entry) || !entry.getInitializer()) continue;
675
- if (own && contains(entry, own)) continue;
676
- return true;
677
- }
678
- return false;
679
- };
680
- /**
681
- * Statically resolvable means: every box in the tree carries a known value.
682
- *
683
- * `unresolvable` is the extractor saying it could not evaluate a node.
684
- * `conditional` is a ternary — two possible values, so there is no single string to
685
- * fold to. `box.fallback` produces an object with no `type` at all, which is likewise
686
- * not something we can trust.
687
- */
688
- const isStaticBox = (node, seen = /* @__PURE__ */ new Set()) => {
689
- if (!node) return false;
690
- if (seen.has(node)) return true;
691
- seen.add(node);
692
- if (box.isUnresolvable(node) || box.isConditional(node)) return false;
693
- if (!("type" in node) || node.type == null) return false;
694
- if (isFromBindingDefault(node)) return false;
695
- if (box.isLiteral(node) && node.value === void 0) {
696
- const source = node.getNode?.();
697
- return Boolean(source && Node.isIdentifier(source) && source.getText() === "undefined");
698
- }
699
- if (box.isMap(node)) {
700
- for (const child of node.value.values()) if (!isStaticBox(child, seen)) return false;
701
- return true;
702
- }
703
- if (box.isArray(node)) {
704
- for (const child of node.value) if (!isStaticBox(child, seen)) return false;
705
- return true;
706
- }
707
- return true;
708
- };
709
- /**
710
- * Strip the wrappers the extractor strips before it builds a box, so the source node
711
- * compared against a box is the same node the box was built from.
712
- *
713
- * A local copy of the extractor's `unwrapExpression`, which is not part of its public
714
- * surface. Recognising fewer wrappers than it does is not a cosmetic difference: an
715
- * unrecognised one leaves an object literal wrapped, and the object checks below skip it.
716
- */
717
- const unwrapExpression = (node) => Node.isAsExpression(node) || Node.isParenthesizedExpression(node) || Node.isNonNullExpression(node) || Node.isTypeAssertion(node) || Node.isSatisfiesExpression(node) ? unwrapExpression(node.getExpression()) : node;
718
- /**
719
- * Mirrors the parser's evaluator environment, so re-boxing an operand here gets the same
720
- * answer the extraction did. Left to its default, ts-evaluator presets to `NODE` and
721
- * would resolve expressions the parser cannot see — making this check *more* permissive
722
- * than the extraction it is auditing, which is the one thing it must never be.
723
- */
724
- const REBOXED = { getEvaluateOptions: () => ({ environment: { preset: "ECMA" } }) };
725
- const rebox = (node) => maybeBoxNode(unwrapExpression(node), [], REBOXED);
726
- /**
727
- * Did this operand resolve to a value the program will actually produce?
728
- *
729
- * Producing a box is not enough when the operand is itself a choice: `a || b || c` parses
730
- * as `(a || b) || c`, so the outer operator is handed whatever the inner one answered —
731
- * including an arm the extractor invented. Asking only "is there a box" reads that
732
- * invention as an ordinary literal.
733
- */
734
- const resolvesExactly = (node) => {
735
- const inner = unwrapExpression(node);
736
- if (!rebox(inner)) return false;
737
- return Node.isConditionalExpression(inner) || isCollapsedBinary(inner) ? decidedAtBuildTime(inner) : true;
738
- };
739
- /**
740
- * Is this operand's value written here, rather than named?
741
- *
742
- * A box records what the extractor resolved a name *through* — a `let`'s initializer, a
743
- * parameter's default — none of which is what the operand holds when the call runs.
744
- * `let m = '1'; m = undefined` still boxes as `'1'`, and `({ c = 'red.300' })` still boxes
745
- * as `'red.300'` for a caller that passed something else. Only a value written at the call
746
- * site is what it appears to be, so only that can be judged truthy or nullish here.
747
- */
748
- const isWrittenHere = (node) => {
749
- const inner = unwrapExpression(node);
750
- return Node.isStringLiteral(inner) || Node.isNumericLiteral(inner) || Node.isNoSubstitutionTemplateLiteral(inner) || Node.isObjectLiteralExpression(inner) || Node.isArrayLiteralExpression(inner) || Node.isTrueLiteral(inner) || Node.isFalseLiteral(inner) || inner.getKind() === SyntaxKind.NullKeyword || Node.isPrefixUnaryExpression(inner) && Node.isNumericLiteral(inner.getOperand());
751
- };
752
- /** An inline value's truthiness, which its box carries directly. */
753
- const isTruthy = (boxNode) => box.isLiteral(boxNode) ? Boolean(boxNode.value) : box.isMap(boxNode) || box.isArray(boxNode) || box.isObject(boxNode);
754
- /**
755
- * Did the extractor *decide* this choice, or guess at it?
756
- *
757
- * `a ? b : c`, `a || b` and `a && b` are asked "what styles could this produce", and when
758
- * one arm does not evaluate the extractor answers with the other rather than refusing
759
- * (`maybe-box-node.ts`, `whenTrueValue && !whenFalseValue`). That is right for generating
760
- * CSS — emit rules for whatever might be used — and wrong for rewriting source, where the
761
- * arm it kept becomes the only one that runs.
762
- *
763
- * For a ternary the tell is the arms: it guessed exactly when one produced a box and the
764
- * other did not. For a short-circuit the answer is always the left operand, so what has to
765
- * be established is that the left is the side that wins.
766
- */
767
- const decidedAtBuildTime = (node) => {
768
- if (Node.isConditionalExpression(node)) return resolvesExactly(node.getWhenTrue()) && resolvesExactly(node.getWhenFalse());
769
- const operator = node.getOperatorToken().getKind();
770
- if (!SHORT_CIRCUIT.includes(operator)) return false;
771
- if (!isWrittenHere(node.getLeft())) return false;
772
- const left = rebox(node.getLeft());
773
- if (!left) return false;
774
- if (operator === SyntaxKind.BarBarToken) return isTruthy(left);
775
- if (operator === SyntaxKind.QuestionQuestionToken) return !box.isLiteral(left) || left.value != null;
776
- return isTruthy(left) ? resolvesExactly(node.getRight()) : true;
777
- };
778
- const SHORT_CIRCUIT = [
779
- SyntaxKind.AmpersandAmpersandToken,
780
- SyntaxKind.BarBarToken,
781
- SyntaxKind.QuestionQuestionToken
782
- ];
783
- /**
784
- * Every binary form the extractor collapses to one operand — the short-circuits plus the
785
- * comparisons, which `isLogicalSyntax` sends down the same path even though their value is
786
- * a boolean rather than either side.
787
- *
788
- * Hoisted rather than built per call: `accountsForSource` asks this for every property of
789
- * every candidate, and rebuilding a thirteen-element list each time is not free.
790
- */
791
- const COLLAPSED_BINARY = new Set([
792
- ...SHORT_CIRCUIT,
793
- SyntaxKind.EqualsEqualsToken,
794
- SyntaxKind.EqualsEqualsEqualsToken,
795
- SyntaxKind.ExclamationEqualsToken,
796
- SyntaxKind.ExclamationEqualsEqualsToken,
797
- SyntaxKind.GreaterThanToken,
798
- SyntaxKind.GreaterThanEqualsToken,
799
- SyntaxKind.LessThanToken,
800
- SyntaxKind.LessThanEqualsToken,
801
- SyntaxKind.InKeyword,
802
- SyntaxKind.InstanceOfKeyword
803
- ]);
804
- const isCollapsedBinary = (node) => Node.isBinaryExpression(node) && COLLAPSED_BINARY.has(node.getOperatorToken().getKind());
805
- /**
806
- * Does the extracted box account for every property the source declares?
807
- *
808
- * `isStaticBox` is not sufficient on its own. The extractor *omits* what it cannot
809
- * evaluate rather than marking it unresolvable, so `css({ color: 'red.300', ...rest })`
810
- * yields a perfectly static-looking map holding only `color`. Folding that produces
811
- * `"c_red.300"` and silently drops everything `rest` contributed.
812
- *
813
- * So the source is the authority on what the call contains, and anything the box does
814
- * not account for disqualifies the fold:
815
- *
816
- * - a declared property missing from the map (its value did not evaluate)
817
- * - a computed key, which we cannot match against the map by name
818
- * - a spread, unless it is an inline object literal
819
- *
820
- * Spreads are the conservative case. `{ ...base }` where `base` is a static local
821
- * object *is* resolved by the extractor, but a resolved spread and an unresolved one
822
- * are indistinguishable once flattened into the map — both just contribute keys, or
823
- * fail to. Rather than guess and erase evaluation the compiler cannot reproduce, the call
824
- * is rejected.
825
- */
826
- /**
827
- * What a property's value is written as. A shorthand names it, so the name *is* the
828
- * expression — reading an initializer that is not there reports the property as having no
829
- * source, and everything hidden behind the name goes unchecked.
830
- */
831
- const valueOf = (property) => Node.isPropertyAssignment(property) ? property.getInitializer() : Node.isShorthandPropertyAssignment(property) ? property.getNameNode() : void 0;
832
- const accountsForSource = (node, boxNode) => {
833
- if (!node) return true;
834
- const unwrapped = unwrapExpression(node);
835
- if ((Node.isConditionalExpression(unwrapped) || isCollapsedBinary(unwrapped)) && !box.isConditional(boxNode) && !decidedAtBuildTime(unwrapped)) return false;
836
- if (Node.isArrayLiteralExpression(unwrapped)) {
837
- if (!box.isArray(boxNode)) return false;
838
- const elements = unwrapped.getElements();
839
- if (elements.length !== boxNode.value.length) return false;
840
- return elements.every((element, index) => accountsForSource(element, boxNode.value[index]));
841
- }
842
- if (!Node.isObjectLiteralExpression(unwrapped)) {
843
- const origin = box.isMap(boxNode) ? boxNode.getNode() : void 0;
844
- return !origin || origin === unwrapped || !Node.isObjectLiteralExpression(origin) ? true : accountsForSource(origin, boxNode);
845
- }
846
- if (!box.isMap(boxNode)) return false;
847
- for (const property of unwrapped.getProperties()) {
848
- if (Node.isSpreadAssignment(property)) {
849
- const expression = unwrapExpression(property.getExpression());
850
- if (Node.isObjectLiteralExpression(expression)) continue;
851
- const walked = boxNode.resolvedSpreads?.find((entry) => entry.node === expression);
852
- if (!walked) return false;
853
- if (!accountsForSource(walked.box.getNode(), walked.box)) return false;
854
- continue;
855
- }
856
- if (Node.isMethodDeclaration(property) || Node.isGetAccessorDeclaration(property) || Node.isSetAccessorDeclaration(property)) return false;
857
- if (!Node.isPropertyAssignment(property) && !Node.isShorthandPropertyAssignment(property)) return false;
858
- const nameNode = property.getNameNode();
859
- if (Node.isComputedPropertyName(nameNode)) return false;
860
- const key = Node.isStringLiteral(nameNode) || Node.isNumericLiteral(nameNode) ? String(nameNode.getLiteralValue()) : nameNode.getText();
861
- const value = valueOf(property);
862
- if (value && Node.isIdentifier(value) && value.getText() === "undefined") continue;
863
- if (!boxNode.value.has(key)) return false;
864
- if (!accountsForSource(value, boxNode.value.get(key))) return false;
865
- }
866
- return true;
867
- };
868
- /**
869
- * Memo keyed on a file, thrown away when its text is replaced.
870
- *
871
- * A plain `WeakMap<SourceFile, …>` is wrong here: ts-morph reuses the wrapper when a path
872
- * is re-added with new text — which is what a watch rebuild does — so it would answer for
873
- * the previous revision. Comparing against the text it was computed from costs a
874
- * reference check while the file is unchanged, since `getFullText()` hands back the same
875
- * string instance.
876
- */
877
- const byText = (cache, sourceFile, compute) => {
878
- const text = sourceFile.getFullText();
879
- const hit = cache.get(sourceFile);
880
- if (hit && hit.text === text) return hit.value;
881
- const value = compute();
882
- cache.set(sourceFile, {
883
- text,
884
- value
885
- });
886
- return value;
887
- };
888
- /**
889
- * Every name declared at module scope, which is what an added import could collide with.
890
- *
891
- * This replaced `sourceFile.getLocals()`. That was precise, but it goes through the
892
- * compiler's symbol table, and reaching for it binds the program — including every
893
- * `.d.ts` the module's imports pull in. It cost ~8ms on a ten-line file and grew with the
894
- * project, which was invisible while only a partial split reached it and became the
895
- * dominant cost once open-ended values started lowering too.
896
- *
897
- * A syntactic walk answers the same question: a binding in a nested *function* cannot
898
- * collide with a module-scope import, and one that shadows it *at the call site* is what
899
- * `isShadowed` is for. Memoized against the file's text rather than the file, since
900
- * ts-morph reuses the wrapper across a re-add and a plain `WeakMap` would answer for the
901
- * previous revision. Uncached it is re-walked per candidate, which is quadratic in a
902
- * module of many elements.
903
- */
904
- const moduleScopeCache = /* @__PURE__ */ new WeakMap();
905
- const declaredAtModuleScope = (sourceFile) => byText(moduleScopeCache, sourceFile, () => collectModuleScopeNames(sourceFile));
906
- const collectModuleScopeNames = (sourceFile) => {
907
- const names = /* @__PURE__ */ new Set();
908
- const addBinding = (node) => {
909
- if (!node) return;
910
- if (Node.isObjectBindingPattern(node) || Node.isArrayBindingPattern(node)) {
911
- for (const element of node.getElements()) if (Node.isBindingElement(element)) addBinding(element.getNameNode());
912
- return;
913
- }
914
- if (Node.isIdentifier(node)) names.add(node.getText());
915
- };
916
- const addDeclarations = (list) => {
917
- if (Node.isVariableStatement(list)) {
918
- for (const declaration of list.getDeclarations()) addBinding(declaration.getNameNode());
919
- return;
920
- }
921
- if (Node.isVariableDeclarationList(list)) for (const declaration of list.getDeclarations()) addBinding(declaration.getNameNode());
922
- };
923
- const isVar = (node) => (Node.isVariableStatement(node) || Node.isVariableDeclarationList(node)) && node.getDeclarationKind() === VariableDeclarationKind.Var;
924
- /**
925
- * `var` is scoped to the enclosing *function*, not the enclosing block, so one written
926
- * inside any statement at the top level still binds at module scope. Walking only the
927
- * top-level statements missed every one of them, and each emitted a duplicate binding.
928
- *
929
- * Only statement containers are followed. A function or class body opens a new variable
930
- * scope, so a `var` inside one cannot collide with a module-level import.
931
- */
932
- const addHoistedVars = (node) => {
933
- if (isVar(node)) {
934
- addDeclarations(node);
935
- return;
936
- }
937
- if (Node.isBlock(node)) {
938
- for (const statement of node.getStatements()) addHoistedVars(statement);
939
- return;
940
- }
941
- if (Node.isIfStatement(node)) {
942
- addHoistedVars(node.getThenStatement());
943
- const otherwise = node.getElseStatement();
944
- if (otherwise) addHoistedVars(otherwise);
945
- return;
946
- }
947
- if (Node.isForStatement(node)) {
948
- const initializer = node.getInitializer();
949
- if (initializer) addHoistedVars(initializer);
950
- addHoistedVars(node.getStatement());
951
- return;
952
- }
953
- if (Node.isForInStatement(node) || Node.isForOfStatement(node)) {
954
- addHoistedVars(node.getInitializer());
955
- addHoistedVars(node.getStatement());
956
- return;
957
- }
958
- if (Node.isWhileStatement(node) || Node.isDoStatement(node) || Node.isWithStatement(node)) {
959
- addHoistedVars(node.getStatement());
960
- return;
961
- }
962
- if (Node.isLabeledStatement(node)) {
963
- addHoistedVars(node.getStatement());
964
- return;
965
- }
966
- if (Node.isTryStatement(node)) {
967
- addHoistedVars(node.getTryBlock());
968
- const caught = node.getCatchClause();
969
- if (caught) addHoistedVars(caught.getBlock());
970
- const finally_ = node.getFinallyBlock();
971
- if (finally_) addHoistedVars(finally_);
972
- return;
973
- }
974
- if (Node.isSwitchStatement(node)) for (const clause of node.getCaseBlock().getClauses()) for (const statement of clause.getStatements()) addHoistedVars(statement);
975
- };
976
- for (const statement of sourceFile.getStatements()) {
977
- if (Node.isVariableStatement(statement)) {
978
- addDeclarations(statement);
979
- continue;
980
- }
981
- if (Node.isImportDeclaration(statement)) {
982
- addBinding(statement.getDefaultImport());
983
- addBinding(statement.getNamespaceImport());
984
- for (const named of statement.getNamedImports()) addBinding(named.getAliasNode() ?? named.getNameNode());
985
- continue;
986
- }
987
- if (Node.isImportEqualsDeclaration(statement)) {
988
- addBinding(statement.getNameNode());
989
- continue;
990
- }
991
- if (Node.isFunctionDeclaration(statement) || Node.isClassDeclaration(statement) || Node.isEnumDeclaration(statement) || Node.isModuleDeclaration(statement) || Node.isTypeAliasDeclaration(statement) || Node.isInterfaceDeclaration(statement)) {
992
- addBinding(statement.getNameNode());
993
- continue;
994
- }
995
- addHoistedVars(statement);
996
- }
997
- return names;
998
- };
999
- /**
1000
- * Every identifier in the module, grouped by the name it spells.
1001
- *
1002
- * Built once per pass and handed to each lookup, because walking the whole tree per binding
1003
- * made that O(bindings x identifiers): a module declaring ten recipes walked its identifiers
1004
- * ten times.
1005
- *
1006
- * ## Why this is a raw walk rather than `getDescendantsOfKind`
1007
- *
1008
- * `SyntaxKind.Identifier` sorts *below* `SyntaxKind.FirstNode`, which is what ts-morph tests to
1009
- * decide whether it may search the parse tree. For a kind below that line it falls back to
1010
- * materialising the whole **token** tree — every brace, comma and keyword becomes a ts-morph node
1011
- * on the way to collecting the identifiers. On 55 KB of real tsx that measured 22ms against
1012
- * 0.22ms for the same collection over compiler nodes, and the node cache does not help: a second
1013
- * call cost the same 22ms.
1014
- *
1015
- * Wrapping is what costs, so only the buckets a caller actually reads are wrapped, on the first
1016
- * read and cached after. Nothing enumerates this index — both callers ask for one name — so the
1017
- * rest is never built. `_getNodeFromCompilerNode` is ts-morph's own memoized wrapper factory, so
1018
- * a node handed back here is the very object `getDescendantsOfKind` would have returned, which
1019
- * `localReferencesTo` depends on: it compares against the declaration by identity.
1020
- *
1021
- * JSDoc is walked explicitly. `ts.forEachChild` does not descend into it, while the token path
1022
- * this replaces does, so a name mentioned only in a `@type` annotation was previously found and
1023
- * would otherwise stop being — a silent narrowing of what counts as a surviving reference.
1024
- * Keyed on `escapedText` because that is what ts-morph's `Identifier.getText()` returns: the name
1025
- * as the compiler resolves it, so `\u0062adge` and `badge` share a bucket exactly as before.
1026
- *
1027
- * Deliberately *not* memoized across passes, unlike the module-scope names beside it. That
1028
- * cache holds strings, which outlive anything; this one holds nodes, and a node does not
1029
- * survive its source file being replaced — `addSourceFile` overwrites, which forgets every
1030
- * node previously taken from it. Keying on the source text does not help, because identical
1031
- * text re-parsed is a fresh tree: the cache hits and returns nodes that throw
1032
- * `Attempted to get information from a node that was removed or forgotten` on the next read.
1033
- */
1034
- const identifierIndex = (sourceFile) => {
1035
- const compilerNodes = /* @__PURE__ */ new Map();
1036
- const collect = (node) => {
1037
- if (node.kind === ts.SyntaxKind.Identifier) {
1038
- const name = String(node.escapedText);
1039
- const known = compilerNodes.get(name);
1040
- if (known) known.push(node);
1041
- else compilerNodes.set(name, [node]);
1042
- }
1043
- const jsDoc = node.jsDoc;
1044
- if (jsDoc) for (const doc of jsDoc) collect(doc);
1045
- ts.forEachChild(node, collect);
1046
- };
1047
- ts.forEachChild(sourceFile.compilerNode, collect);
1048
- const wrapped = /* @__PURE__ */ new Map();
1049
- const wrap = sourceFile;
1050
- return { get: (name) => {
1051
- const known = wrapped.get(name);
1052
- if (known) return known;
1053
- const nodes = (compilerNodes.get(name) ?? []).map((node) => wrap._getNodeFromCompilerNode(node));
1054
- wrapped.set(name, nodes);
1055
- return nodes;
1056
- } };
1057
- };
1058
- const localReferencesTo = (index, name, declaration) => {
1059
- const references = [];
1060
- for (const identifier of index.get(name)) {
1061
- if (identifier === declaration) continue;
1062
- const parent = identifier.getParent();
1063
- if (!parent) continue;
1064
- if (Node.isPropertyAccessExpression(parent) && parent.getNameNode() === identifier) continue;
1065
- if (Node.isPropertyAssignment(parent) && parent.getNameNode() === identifier) continue;
1066
- if (Node.isBindingElement(parent) && parent.getPropertyNameNode() === identifier) continue;
1067
- if ((Node.isJsxOpeningElement(parent) || Node.isJsxSelfClosingElement(parent) || Node.isJsxClosingElement(parent)) && parent.getTagNameNode() === identifier) continue;
1068
- if (Node.isJsxAttribute(parent) && parent.getNameNode() === identifier) continue;
1069
- if ((Node.isMethodDeclaration(parent) || Node.isPropertyDeclaration(parent) || Node.isGetAccessorDeclaration(parent) || Node.isSetAccessorDeclaration(parent) || Node.isMethodSignature(parent) || Node.isPropertySignature(parent) || Node.isEnumMember(parent)) && parent.getNameNode() === identifier) continue;
1070
- if ((Node.isVariableDeclaration(parent) || Node.isParameterDeclaration(parent) || Node.isFunctionDeclaration(parent) || Node.isClassDeclaration(parent) || Node.isBindingElement(parent)) && parent.getNameNode() === identifier) continue;
1071
- if (Node.isImportSpecifier(parent) || Node.isExportSpecifier(parent)) {
1072
- if (parent.getNameNode() !== identifier) continue;
1073
- if (Node.isExportSpecifier(parent)) {
1074
- references.push(identifier);
1075
- continue;
1076
- }
1077
- continue;
1078
- }
1079
- references.push(identifier);
1080
- }
1081
- return references;
1082
- };
1083
- //#endregion
1084
- //#region src/fold-recipe.ts
1085
- /**
1086
- * Binding name → the config it was declared with.
1087
- *
1088
- * Built from the definitions the parser already recorded, walking each one to the declaration
1089
- * that names it. The parser records a definition under the name it was *imported* as (`cva`),
1090
- * and a call under the name the file *bound* (`badge`); this is what joins the two.
1091
- *
1092
- * Slot and ordinary recipes share one representation.
1093
- */
1094
- const collectRecipeConfigs = (parserResult) => {
1095
- const configs = /* @__PURE__ */ new Map();
1096
- const definitions = [...parserResult.cva, ...parserResult.sva];
1097
- for (const definition of definitions) {
1098
- const node = definition.box?.getNode?.();
1099
- if (!node) continue;
1100
- const nameNode = ((Node.isCallExpression(node) ? node : node.getFirstAncestorByKind(SyntaxKind.CallExpression))?.getFirstAncestorByKind(SyntaxKind.VariableDeclaration))?.getNameNode();
1101
- if (!nameNode || !Node.isIdentifier(nameNode)) continue;
1102
- if (definition.data?.length !== 1) {
1103
- configs.set(nameNode.getText(), AMBIGUOUS);
1104
- continue;
1105
- }
1106
- const config = definition.data[0];
1107
- if (!config || typeof config !== "object") continue;
1108
- if (configs.has(nameNode.getText())) {
1109
- configs.set(nameNode.getText(), AMBIGUOUS);
1110
- continue;
1111
- }
1112
- configs.set(nameNode.getText(), {
1113
- config,
1114
- box: definition.box
1115
- });
1116
- }
1117
- return configs;
1118
- };
1119
- /** Pick a complete precompiled StyleSet for one or more runtime recipe axes. */
1120
- const RECIPE_MAP_HELPER = "cvaMap";
1121
- /** Guard the exact compiler against accidentally materialising an enormous Cartesian product. */
1122
- const DEFAULT_MAX_RECIPE_STATES = 65536;
1123
- /** What `recipe.splitVariantProps` calls, reached directly once the call is lowered. */
1124
- const SPLIT_PROPS_HELPER = "splitProps";
1125
- /** Marker for a binding the fold must never resolve — declared twice, or unresolvable. */
1126
- const AMBIGUOUS = Object.freeze({
1127
- config: {},
1128
- box: void 0
1129
- });
1130
- /** `.size`, or `["x-large"]` when the variant is not a valid identifier. */
1131
- const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
1132
- const propertyAccess = (key) => IDENTIFIER.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
1133
- const LITERAL_KINDS = new Set([
1134
- SyntaxKind.StringLiteral,
1135
- SyntaxKind.NoSubstitutionTemplateLiteral,
1136
- SyntaxKind.NumericLiteral,
1137
- SyntaxKind.TrueKeyword,
1138
- SyntaxKind.FalseKeyword
1139
- ]);
1140
- /**
1141
- * The value a literal node denotes, or `undefined` for anything else.
1142
- *
1143
- * Read off the node rather than from the extractor's resolved data, because that data is lossy
1144
- * in the direction that matters: a property it could not resolve is *dropped*, so `badge({ tone })`
1145
- * and `badge({})` are identical there. Folding the first as if it were the second emits a class
1146
- * string missing the variant — the element renders, wrongly, with no report.
1147
- */
1148
- const literalValue = (node) => {
1149
- if (!node || !LITERAL_KINDS.has(node.getKind())) return void 0;
1150
- if (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) return node.getLiteralValue();
1151
- if (Node.isNumericLiteral(node)) return node.getLiteralValue();
1152
- if (node.getKind() === SyntaxKind.TrueKeyword) return true;
1153
- if (node.getKind() === SyntaxKind.FalseKeyword) return false;
1154
- };
1155
- /**
1156
- * The property name a key node denotes.
1157
- *
1158
- * Read off the node rather than unquoted from its text. `{ '\\u0074one': 'a' }` names the
1159
- * variant `tone`, and stripping the surrounding quotes leaves the escape uninterpreted — so
1160
- * the variant did not match, its class was dropped, and the element rendered without it. A
1161
- * numeric key normalises the same way: `{ 0x10: 'a' }` is the key `16`.
1162
- */
1163
- const propertyKey = (nameNode) => {
1164
- if (Node.isIdentifier(nameNode)) return nameNode.getText();
1165
- if (Node.isStringLiteral(nameNode) || Node.isNoSubstitutionTemplateLiteral(nameNode)) return nameNode.getLiteralValue();
1166
- if (Node.isNumericLiteral(nameNode)) return String(nameNode.getLiteralValue());
1167
- };
1168
- /**
1169
- * Make a generated compile helper callable at this call site, by whatever name the file gives it.
1170
- *
1171
- * Unlike `cx`, an inline recipe's callee is a local binding, so
1172
- * there is nothing to match — the host here is any import of the generated css module, which
1173
- * a file defining a recipe necessarily has, since `cva` came from it.
1174
- */
1175
- const ensureRecipeHelperImport = (imported, call, isBambooCssModule, isGeneratedCssModule, isShadowed, newImportModule, helperModuleFromSubpath) => {
1176
- const sourceFile = call.getSourceFile();
1177
- let host;
1178
- let subpathModule;
1179
- for (const declaration of sourceFile.getImportDeclarations()) {
1180
- const mod = declaration.getModuleSpecifierValue();
1181
- if (declaration.isTypeOnly()) continue;
1182
- for (const named of declaration.getNamedImports()) {
1183
- if (named.isTypeOnly()) continue;
1184
- if (named.getNameNode().getText() === imported) {
1185
- if (!isBambooCssModule(mod)) return void 0;
1186
- const local = (named.getAliasNode() ?? named.getNameNode()).getText();
1187
- return isShadowed(call, local) ? void 0 : { name: local };
1188
- }
1189
- }
1190
- if (!host && isGeneratedCssModule(mod) && declaration.getNamedImports().length > 0) host = declaration;
1191
- if (!subpathModule) subpathModule = helperModuleFromSubpath?.(mod);
1192
- }
1193
- const fallbackModule = newImportModule ?? subpathModule;
1194
- if (!host && !fallbackModule) return void 0;
1195
- if (declaredAtModuleScope(sourceFile).has(imported)) return void 0;
1196
- if (isShadowed(call, imported)) return void 0;
1197
- if (!host) {
1198
- const anchor = sourceFile.getImportDeclarations().at(-1);
1199
- if (!anchor) return void 0;
1200
- return {
1201
- name: imported,
1202
- insert: {
1203
- pos: anchor.getEnd(),
1204
- names: [imported],
1205
- module: fallbackModule
1206
- }
1207
- };
1208
- }
1209
- const last = host.getNamedImports().at(-1);
1210
- if (!last) return void 0;
1211
- return {
1212
- name: imported,
1213
- insert: {
1214
- pos: last.getEnd(),
1215
- names: [imported]
1216
- }
1217
- };
1218
- };
1219
- /**
1220
- * Lower one invocation, or say why not.
1221
- *
1222
- * Every property written at the call site has to be a literal. A selection is not additive —
1223
- * an unresolved variant does not merely omit a class, it can change which of several the
1224
- * recipe applies — so a partially-known selection is not foldable at all.
1225
- */
1226
- const lowerRecipeCall = (call, entry, styleCompiler, isInert, resolvedSelection, slot, maxRecipeStates = DEFAULT_MAX_RECIPE_STATES) => {
1227
- if (!entry || entry === AMBIGUOUS) return {
1228
- kind: "decline",
1229
- reason: "unknown-recipe"
1230
- };
1231
- const { config } = entry;
1232
- if (config.slots !== void 0) {
1233
- if (!Array.isArray(config.slots) || slot !== void 0 && !config.slots.includes(slot)) return {
1234
- kind: "decline",
1235
- reason: "unsupported-shape"
1236
- };
1237
- } else if (slot) return {
1238
- kind: "decline",
1239
- reason: "unsupported-shape"
1240
- };
1241
- if (!config.base && !config.variants && !config.className) return {
1242
- kind: "decline",
1243
- reason: "unknown-recipe"
1244
- };
1245
- if (!Node.isCallExpression(call)) return {
1246
- kind: "decline",
1247
- reason: "unsupported-shape"
1248
- };
1249
- const args = call.getArguments();
1250
- if (args.length > 1) return {
1251
- kind: "decline",
1252
- reason: "unsupported-shape"
1253
- };
1254
- const selection = {};
1255
- /** Variant → the source expression selecting it, for axes that stay runtime decisions. */
1256
- const dynamicAxes = /* @__PURE__ */ new Map();
1257
- /**
1258
- * Variants whose expression could run something, in the order the source evaluates them.
1259
- *
1260
- * The text is kept, not just the key: a later property writing the same key replaces the
1261
- * entry in `dynamicAxes`, and the expression recorded here would then never be emitted.
1262
- */
1263
- const effectful = [];
1264
- if (args.length === 1) {
1265
- const arg = args[0];
1266
- if (!arg) return {
1267
- kind: "decline",
1268
- reason: "dynamic"
1269
- };
1270
- /**
1271
- * `input(variantProps)` — a selection the build cannot see inside.
1272
- *
1273
- * The compiled recipe contract accepts scalar declared variant values. A conditional
1274
- * object is not a finite selection value; responsiveness belongs inside a variant's style
1275
- * declaration, where the compiler can materialize its conditions ahead of time.
1276
- *
1277
- * The complete StyleSets are knowable: the config declares every scalar value each axis
1278
- * accepts. This is the shape a wrapper component takes, where variants are its public API
1279
- * and therefore cannot be literals by definition.
1280
- *
1281
- * An identifier only. Each variant reads the binding again, and re-reading anything else —
1282
- * a call, a property access — would evaluate it once per axis instead of once.
1283
- */
1284
- if (Node.isIdentifier(arg)) {
1285
- const binding = arg.getText();
1286
- for (const key of Object.keys(config.variants ?? {})) dynamicAxes.set(key, `${binding}${propertyAccess(key)}`);
1287
- } else if (!Node.isObjectLiteralExpression(arg)) return {
1288
- kind: "decline",
1289
- reason: "dynamic"
1290
- };
1291
- else for (const property of arg.getProperties()) {
1292
- if (Node.isSpreadAssignment(property)) return {
1293
- kind: "decline",
1294
- reason: "dynamic"
1295
- };
1296
- if (Node.isShorthandPropertyAssignment(property)) {
1297
- dynamicAxes.set(property.getName(), property.getName());
1298
- delete selection[property.getName()];
1299
- continue;
1300
- }
1301
- if (!Node.isPropertyAssignment(property)) return {
1302
- kind: "decline",
1303
- reason: "dynamic"
1304
- };
1305
- const nameNode = property.getNameNode();
1306
- if (Node.isComputedPropertyName(nameNode)) return {
1307
- kind: "decline",
1308
- reason: "dynamic"
1309
- };
1310
- const key = propertyKey(nameNode);
1311
- if (key === void 0) return {
1312
- kind: "decline",
1313
- reason: "dynamic"
1314
- };
1315
- const initializer = property.getInitializer();
1316
- if (initializer && !isInert(initializer)) {
1317
- if (!Object.hasOwn(config.variants ?? {}, key)) return {
1318
- kind: "decline",
1319
- reason: "dynamic"
1320
- };
1321
- effectful.push({
1322
- key,
1323
- text: initializer.getText()
1324
- });
1325
- dynamicAxes.set(key, initializer.getText());
1326
- delete selection[key];
1327
- continue;
1328
- }
1329
- const literal = literalValue(initializer);
1330
- if (literal !== void 0) {
1331
- selection[key] = literal;
1332
- dynamicAxes.delete(key);
1333
- continue;
1334
- }
1335
- if (!resolvedSelection || !Object.hasOwn(resolvedSelection, key)) {
1336
- if (!initializer) return {
1337
- kind: "decline",
1338
- reason: "dynamic"
1339
- };
1340
- dynamicAxes.set(key, initializer.getText());
1341
- delete selection[key];
1342
- continue;
1343
- }
1344
- const value = resolvedSelection[key];
1345
- if (value !== null && typeof value === "object") return {
1346
- kind: "decline",
1347
- reason: "dynamic"
1348
- };
1349
- selection[key] = value;
1350
- dynamicAxes.delete(key);
1351
- }
1352
- }
1353
- /**
1354
- * Every expression that could run something has to reach the output carrying its own text.
1355
- *
1356
- * A later property writing the same key replaces it in `dynamicAxes` — `badge({ tone: a(),
1357
- * tone: 'b' })` is last-wins for the *value*, but `a()` still runs, and emitting only the
1358
- * literal would delete it. Duplicate keys are a type error in TypeScript; the fold does not
1359
- * typecheck and does transform `.js`, so this is reachable.
1360
- */
1361
- const everyEffectSurvives = () => effectful.every(({ key, text }) => dynamicAxes.get(key) === text);
1362
- const compiledSelection = (selected) => {
1363
- if (Array.isArray(config.slots) && slot === void 0) {
1364
- const slots = {};
1365
- const classNames = /* @__PURE__ */ new Set();
1366
- for (const slotName of config.slots) {
1367
- const styles = styleCompiler.resolveRecipe(config, selected, slotName);
1368
- if (!styles) return void 0;
1369
- const className = styleCompiler.className(styles);
1370
- slots[slotName] = className;
1371
- for (const token of className.split(" ")) if (token) classNames.add(token);
1372
- }
1373
- return {
1374
- value: slots,
1375
- classNames: [...classNames]
1376
- };
1377
- }
1378
- const styles = styleCompiler.resolveRecipe(config, selected, slot);
1379
- if (!styles) return void 0;
1380
- const className = styleCompiler.className(styles);
1381
- return {
1382
- value: className,
1383
- classNames: className.split(" ").filter(Boolean),
1384
- styles
1385
- };
1386
- };
1387
- if (dynamicAxes.size === 0) {
1388
- if (!everyEffectSurvives()) return {
1389
- kind: "decline",
1390
- reason: "dynamic"
1391
- };
1392
- const compiled = compiledSelection(selection);
1393
- if (!compiled) return {
1394
- kind: "decline",
1395
- reason: "dynamic"
1396
- };
1397
- if (typeof compiled.value === "string") return {
1398
- kind: "class",
1399
- className: compiled.value,
1400
- styles: compiled.styles
1401
- };
1402
- return {
1403
- kind: "slots",
1404
- expression: JSON.stringify(compiled.value),
1405
- classNames: compiled.classNames,
1406
- dynamic: false
1407
- };
1408
- }
1409
- if (!everyEffectSurvives()) return {
1410
- kind: "decline",
1411
- reason: "dynamic"
1412
- };
1413
- if (effectful.length > 1) {
1414
- const variantOrder = Object.keys(config.variants ?? {});
1415
- const keys = effectful.map((entry) => entry.key);
1416
- if ([...keys].sort((a, b) => variantOrder.indexOf(a) - variantOrder.indexOf(b)).join("\0") !== keys.join("\0")) return {
1417
- kind: "decline",
1418
- reason: "dynamic"
1419
- };
1420
- }
1421
- for (const key of [...dynamicAxes.keys()]) if (!Object.hasOwn(config.variants ?? {}, key)) dynamicAxes.delete(key);
1422
- if (dynamicAxes.size === 0) {
1423
- const compiled = compiledSelection(selection);
1424
- if (!compiled) return {
1425
- kind: "decline",
1426
- reason: "dynamic"
1427
- };
1428
- if (typeof compiled.value === "string") return {
1429
- kind: "class",
1430
- className: compiled.value,
1431
- styles: compiled.styles
1432
- };
1433
- return {
1434
- kind: "slots",
1435
- expression: JSON.stringify(compiled.value),
1436
- classNames: compiled.classNames,
1437
- dynamic: false
1438
- };
1439
- }
1440
- /**
1441
- * Compile the finite recipe state space into a reduced decision table.
1442
- *
1443
- * Each leaf is a *complete* final StyleSet. This matters for declarations overridden by
1444
- * variants and compounds: selecting independent per-axis atoms would put both values in
1445
- * the utility layer and let stylesheet order, rather than the recipe's merge order, pick
1446
- * the winner. Complete leaves retain the same precedence while sharing their atoms with
1447
- * every `css()` and recipe in the build.
1448
- *
1449
- * `undefined` is its own edge because it restores a default variant. `null` and any
1450
- * undeclared value take the miss edge and explicitly suppress that default. Declared
1451
- * values use string keys, matching JavaScript's property-key coercion in the recipe
1452
- * runtime. A flat alternating key/value array avoids the special `__proto__` semantics
1453
- * of an object literal.
1454
- */
1455
- const axes = Object.keys(config.variants ?? {}).filter((key) => dynamicAxes.has(key));
1456
- const stateCount = axes.reduce((product, axis) => product * (Object.keys(config.variants?.[axis] ?? {}).length + 2), 1);
1457
- 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.`);
1458
- const expressions = axes.map((axis) => dynamicAxes.get(axis));
1459
- const wholeSlots = Array.isArray(config.slots) && slot === void 0;
1460
- return {
1461
- kind: "dynamic-style",
1462
- map: {
1463
- outputKind: wholeSlots ? "slots" : "class",
1464
- compile(before = [], after = []) {
1465
- const nodes = [];
1466
- const nodeByShape = /* @__PURE__ */ new Map();
1467
- const leaves = [];
1468
- const leafByShape = /* @__PURE__ */ new Map();
1469
- const emittedClasses = /* @__PURE__ */ new Set();
1470
- const leaf = (dynamicSelection) => {
1471
- const selected = {
1472
- ...selection,
1473
- ...dynamicSelection
1474
- };
1475
- if (wholeSlots) {
1476
- const compiled = compiledSelection(selected);
1477
- if (!compiled || typeof compiled.value === "string") return internLeaf("");
1478
- for (const token of compiled.classNames) emittedClasses.add(token);
1479
- return internLeaf(compiled.value);
1480
- }
1481
- const styles = styleCompiler.resolveRecipe(config, selected, slot);
1482
- if (!styles) return internLeaf("");
1483
- const className = styleCompiler.className(styleCompiler.compose(...before, styles, ...after));
1484
- for (const token of className.split(" ")) if (token) emittedClasses.add(token);
1485
- return internLeaf(className);
1486
- };
1487
- function internLeaf(value) {
1488
- const shape = JSON.stringify(value);
1489
- const known = leafByShape.get(shape);
1490
- if (known !== void 0) return ~known;
1491
- const id = leaves.length;
1492
- leaves.push(value);
1493
- leafByShape.set(shape, id);
1494
- return ~id;
1495
- }
1496
- const buildNode = (index, dynamicSelection) => {
1497
- if (index === axes.length) return leaf(dynamicSelection);
1498
- const axis = axes[index];
1499
- const values = Object.keys(config.variants?.[axis] ?? {});
1500
- const miss = buildNode(index + 1, {
1501
- ...dynamicSelection,
1502
- [axis]: null
1503
- });
1504
- const absentSelection = { ...dynamicSelection };
1505
- delete absentSelection[axis];
1506
- const absent = buildNode(index + 1, absentSelection);
1507
- const byValue = [];
1508
- for (const value of values) byValue.push(value, buildNode(index + 1, {
1509
- ...dynamicSelection,
1510
- [axis]: value
1511
- }));
1512
- const refs = [
1513
- miss,
1514
- absent,
1515
- ...byValue.filter((_, valueIndex) => valueIndex % 2 === 1)
1516
- ];
1517
- if (refs.every((ref) => ref === refs[0])) return refs[0];
1518
- const node = [
1519
- miss,
1520
- absent,
1521
- byValue
1522
- ];
1523
- const shape = JSON.stringify(node);
1524
- const known = nodeByShape.get(shape);
1525
- if (known !== void 0) return known;
1526
- const id = nodes.length;
1527
- nodes.push(node);
1528
- nodeByShape.set(shape, id);
1529
- return id;
1530
- };
1531
- const root = buildNode(0, {});
1532
- const staticLeaf = root < 0 ? leaves[~root] : void 0;
1533
- return {
1534
- expression: root < 0 && effectful.length === 0 ? JSON.stringify(staticLeaf) : `${RECIPE_MAP_HELPER}([${expressions.join(", ")}], ${JSON.stringify(nodes)}, ${JSON.stringify(leaves)}, ${root})`,
1535
- classNames: [...emittedClasses],
1536
- staticClasses: typeof staticLeaf === "string" ? staticLeaf : "",
1537
- outputKind: wholeSlots ? "slots" : "class",
1538
- usesHelper: !(root < 0 && effectful.length === 0)
1539
- };
1540
- }
1541
- }
1542
- };
1543
- };
1544
- //#endregion
1545
- //#region src/runtime-css.ts
1546
- /** The shape `createCss` and `createMergeCss` both take, derived from a resolved context. */
1547
- const createCssContext = (ctx) => ({
1548
- hash: Boolean(ctx.hash.className),
1549
- conditions: {
1550
- shift: ctx.conditions.shift,
1551
- finalize: ctx.conditions.finalize
1552
- },
1553
- utility: {
1554
- prefix: ctx.utility.prefix,
1555
- hasShorthand: ctx.utility.hasShorthand,
1556
- resolveShorthand: ctx.utility.resolveShorthand.bind(ctx.utility),
1557
- transform: ctx.utility.transform.bind(ctx.utility),
1558
- toHash: ctx.utility.toHash.bind(ctx.utility)
1559
- }
1560
- });
1561
- const createRuntimeCss = (ctx) => {
1562
- const cssContext = createCssContext(ctx);
1563
- const cssFn = createCssUncached(cssContext);
1564
- const { mergeCssUncached } = createMergeCss(cssContext);
1565
- return memo((...styles) => cssFn(mergeCssUncached(...styles)));
1566
- };
1567
- /**
1568
- * The map is every token in the project, so it is built once per context and shared by
1569
- * every module in the build — not once per `foldSource`, which would price a whole token
1570
- * table into each of the overwhelming majority of modules that call `token()` zero times.
1571
- * Keyed weakly so a context that goes out of scope takes its table with it.
1572
- *
1573
- * Both halves of the generated entry are stored, because `token()` and `token.value()` read
1574
- * different ones and building a second table would pay the same per-project cost twice.
1575
- */
1576
- const tokenValues = /* @__PURE__ */ new WeakMap();
1577
- const tokenValuesFor = (ctx) => {
1578
- let values = tokenValues.get(ctx);
1579
- if (values) return values;
1580
- values = /* @__PURE__ */ new Map();
1581
- for (const token of ctx.tokens.allTokens) {
1582
- const { varRef, isVirtual, condition } = token.extensions;
1583
- values.set(token.name, {
1584
- value: ctx.tokens.view.get(token.name) ?? (isVirtual || condition !== "base" ? varRef : token.value),
1585
- variable: ctx.tokens.view.getVar(token.name) ?? varRef
1586
- });
1587
- }
1588
- tokenValues.set(ctx, values);
1589
- return values;
1590
- };
1591
- const createRuntimeTokenValue = (ctx) => (path) => {
1592
- const value = tokenValuesFor(ctx).get(path)?.value;
1593
- return typeof value === "string" ? value : void 0;
1594
- };
1595
- /**
1596
- * The generated runtime's `token()`, rebuilt in-process.
1597
- *
1598
- * Reads the `variable` half of the same entry `token.value()` reads the `value` half of.
1599
- * That half is `varRef` for every token regardless of condition, so unlike
1600
- * `createRuntimeTokenValue` there is no split to get wrong and no non-string case to
1601
- * decline: a `var()` reference is a string or the token does not exist. Which is what makes
1602
- * the default form the trivially foldable one.
1603
- */
1604
- const createRuntimeToken = (ctx) => (path) => tokenValuesFor(ctx).get(path)?.variable || void 0;
1605
- //#endregion
1606
- //#region src/fold.ts
1607
- /**
1608
- * `cva`/`sva` return a function, so their definitions are compile-time declarations rather
1609
- * than class-producing calls; once their uses are lowered, the factory calls are erased.
1610
- * `token` also resolves to no class, but it does resolve to a literal, so it compiles through
1611
- * its own path rather than being declined outright. A static `viewTransition` bag resolves to
1612
- * its extracted class and uses the ordinary class candidate path.
1613
- *
1614
- * Recipe invocations compile through `fold-recipe`. Inline calls
1615
- * are recorded under the name the file bound; config calls arrive as `recipe`. Routing both
1616
- * through one exact finite-state lowering keeps their selection contract identical.
1617
- */
1618
- const FOLDABLE_TYPES = new Set([
1619
- "css",
1620
- "pattern",
1621
- "viewTransition"
1622
- ]);
1623
- /**
1624
- * The skip reasons that leave a `css()`-family call in the output.
1625
- *
1626
- * `overlapping` is handled by the enclosing fold, and `not-imported` is somebody else's
1627
- * function of the same name — neither leaves a call of ours.
1628
- */
1629
- const SURVIVES_TO_RUNTIME = new Set([
1630
- "dynamic",
1631
- "runtime-binding",
1632
- "raw-call",
1633
- "unsupported-kind",
1634
- "no-call-expression",
1635
- "unresolved-token",
1636
- "compile-failed"
1637
- ]);
1638
- /**
1639
- * A call of a recipe the file bound itself: `const badge = cva(...)`, then `badge({ tone })`.
1640
- *
1641
- * Folded when the whole selection resolves, reported under this reason when it does not.
1642
- * Deliberately all-or-nothing: an unresolved variant does not merely omit its own class, so a
1643
- * partially-known selection is not foldable at all.
1644
- *
1645
- * Visible at all because it used to not be. The parser matched calls by imported name, so a
1646
- * local binding was never recorded, and an unfoldable invocation looked identical to code
1647
- * nothing had parsed.
1648
- */
1649
- const RECIPE_CALL_TYPE = "cva-call";
1650
- /**
1651
- * An identifier that actually reads the binding.
1652
- *
1653
- * `getDescendantsOfKind(Identifier)` yields every name in the file, and most of them bind or
1654
- * label rather than read: a JSX tag (`<button/>` against a recipe called `button`), an object
1655
- * key, a property name, a declaration. Counting those failed builds on modules that had
1656
- * folded completely — and `button`, `input`, `label`, `select`, `table`, `dialog` and `form`
1657
- * are all ordinary recipe names as well as intrinsic elements.
1658
- *
1659
- * A type position is excluded for a different reason: it is erased, and with it the import.
1660
- */
1661
- const isValueReference = (identifier) => {
1662
- const parent = identifier.getParent();
1663
- if (!parent) return false;
1664
- if (Node.isImportSpecifier(parent) || Node.isExportSpecifier(parent)) return false;
1665
- if (Node.isImportClause(parent) || Node.isNamespaceImport(parent)) return false;
1666
- if (Node.isPropertyAccessExpression(parent) && parent.getNameNode() === identifier) return false;
1667
- if (Node.isQualifiedName(parent) && parent.getRight() === identifier) return false;
1668
- if (Node.isPropertyAssignment(parent) && parent.getNameNode() === identifier) return false;
1669
- if (Node.isMethodDeclaration(parent) || Node.isPropertyDeclaration(parent) || Node.isGetAccessorDeclaration(parent) || Node.isSetAccessorDeclaration(parent) || Node.isMethodSignature(parent) || Node.isPropertySignature(parent) || Node.isEnumMember(parent)) {
1670
- if (parent.getNameNode() === identifier) return false;
1671
- }
1672
- if (Node.isLabeledStatement(parent) || Node.isBreakStatement(parent) || Node.isContinueStatement(parent)) return false;
1673
- if (Node.isJsxOpeningElement(parent) || Node.isJsxSelfClosingElement(parent) || Node.isJsxClosingElement(parent)) {
1674
- if (parent.getTagNameNode() === identifier) return identifier.getText()[0] === identifier.getText()[0]?.toUpperCase();
1675
- }
1676
- if (Node.isJsxAttribute(parent)) return false;
1677
- if (Node.isBindingElement(parent) && parent.getPropertyNameNode() === identifier) return false;
1678
- if ((Node.isVariableDeclaration(parent) || Node.isParameterDeclaration(parent) || Node.isBindingElement(parent) || Node.isFunctionDeclaration(parent) || Node.isClassDeclaration(parent)) && parent.getNameNode() === identifier) return false;
1679
- return !identifier.getFirstAncestor((ancestor) => Node.isTypeNode(ancestor) || Node.isTypeAliasDeclaration(ancestor) || Node.isInterfaceDeclaration(ancestor));
1680
- };
1681
- /**
1682
- * Imports a surviving reference to is not a failure.
1683
- *
1684
- * These are what the compiler itself writes; all live in `cx` and pull no engine, so a
1685
- * reference to one is the fold having worked.
1686
- */
1687
- const PERMITTED_BINDINGS = new Set([
1688
- "cx",
1689
- RECIPE_MAP_HELPER,
1690
- SPLIT_PROPS_HELPER
1691
- ]);
1692
- /**
1693
- * Whether a module's text could hold a `splitVariantProps` property access.
1694
- *
1695
- * A necessary condition, deliberately not a sufficient one: the name inside a string or a
1696
- * comment opens the walk, which costs what the walk always cost. What it must never do is
1697
- * close on a module that has one, and an identifier may be spelled with unicode escapes —
1698
- * `badge.splitVariantProps(p)` reads as the name to the compiler and contains none of it
1699
- * as text. Both escape forms start `\u`, so one test covers every spelling.
1700
- */
1701
- const mayNameSplitVariantProps = (text) => text.includes("splitVariantProps") || text.includes("\\u");
1702
- /**
1703
- * The pieces `trim` reduces a module specifier by, hoisted because a regex literal
1704
- * constructs a new object every time it is evaluated and `trim` runs per specifier per
1705
- * import declaration per module.
1706
- */
1707
- const LEADING_RELATIVE = /^(?:\.\.?\/)+/;
1708
- const TRAILING_SLASH = /\/$/;
1709
- const MODULE_EXTENSION = /\.[mc]?[jt]sx?$/;
1710
- const TRAILING_INDEX = /\/index$/;
1711
- /**
1712
- * An argument that cannot run anything when it is evaluated.
1713
- *
1714
- * `token()` takes one argument, but javascript evaluates every argument a call site passes
1715
- * before the call — so a fold that drops an extra one also drops whatever evaluating it would
1716
- * have done. `token('x', compute())` is pathological and no longer type-checks, and the fold's
1717
- * contract is behaviour preservation regardless: a literal is the cheap way to prove it, since
1718
- * it means no call, no property read, no getter.
1719
- */
1720
- const isInertArgument = (node) => Node.isStringLiteral(node) || Node.isNumericLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node) || node.getKind() === SyntaxKind.TrueKeyword || node.getKind() === SyntaxKind.FalseKeyword || node.getKind() === SyntaxKind.NullKeyword || Node.isIdentifier(node) && node.getText() === "undefined";
1721
- /**
1722
- * An expression whose evaluation cannot do anything observable, so deleting it preserves
1723
- * behaviour.
1724
- *
1725
- * `isInertArgument` covers the leaves; this walks the object and array literals a recipe
1726
- * call is actually written with. A spread runs the source's getters, a computed key runs an
1727
- * expression, a getter or method definition is a function — none of those are safe to
1728
- * delete, so they are declined rather than enumerated.
1729
- */
1730
- const isInertExpression = (node) => {
1731
- if (isInertArgument(node)) return true;
1732
- if (Node.isIdentifier(node)) return true;
1733
- if (Node.isAsExpression(node) || Node.isSatisfiesExpression(node) || Node.isNonNullExpression(node) || Node.isTypeAssertion(node) || Node.isParenthesizedExpression(node)) return isInertExpression(node.getExpression());
1734
- if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) return true;
1735
- if (Node.isRegularExpressionLiteral(node) || Node.isBigIntLiteral(node)) return true;
1736
- if (Node.isPrefixUnaryExpression(node)) {
1737
- const operator = node.getOperatorToken();
1738
- return (operator === SyntaxKind.MinusToken || operator === SyntaxKind.PlusToken || operator === SyntaxKind.ExclamationToken || operator === SyntaxKind.TildeToken) && isInertExpression(node.getOperand());
1739
- }
1740
- if (Node.isBinaryExpression(node)) {
1741
- const operator = node.getOperatorToken().getKind();
1742
- return (operator === SyntaxKind.QuestionQuestionToken || operator === SyntaxKind.BarBarToken || operator === SyntaxKind.AmpersandAmpersandToken) && isInertExpression(node.getLeft()) && isInertExpression(node.getRight());
1743
- }
1744
- if (Node.isObjectLiteralExpression(node)) return node.getProperties().every((property) => {
1745
- if (Node.isShorthandPropertyAssignment(property)) return true;
1746
- if (!Node.isPropertyAssignment(property)) return false;
1747
- if (Node.isComputedPropertyName(property.getNameNode())) return false;
1748
- const initializer = property.getInitializer();
1749
- return initializer !== void 0 && isInertExpression(initializer);
1750
- });
1751
- if (Node.isArrayLiteralExpression(node)) return node.getElements().every(isInertExpression);
1752
- return false;
1753
- };
1754
- /**
1755
- * Source files a box tree reaches, other than the one being folded.
1756
- *
1757
- * When the extractor resolves an imported identifier it boxes the *declaration's*
1758
- * node, which lives in the defining module. Walking the tree and reading each node's
1759
- * source file therefore recovers exactly the files a fold depended on — narrower and
1760
- * more accurate than treating every import of the module as a dependency.
1761
- */
1762
- const collectSourceFiles = (node, ctx, seen = /* @__PURE__ */ new Set()) => {
1763
- if (!node || seen.has(node)) return;
1764
- seen.add(node);
1765
- ctx.record(node.getNode?.());
1766
- if (box.isMap(node)) {
1767
- for (const child of node.value.values()) collectSourceFiles(child, ctx, seen);
1768
- return;
1769
- }
1770
- if (box.isArray(node)) for (const child of node.value) collectSourceFiles(child, ctx, seen);
1771
- };
1772
- const createDependencyScan = (ownFile) => {
1773
- const results = /* @__PURE__ */ new Set();
1774
- const paths = /* @__PURE__ */ new Map();
1775
- return {
1776
- results,
1777
- record(node) {
1778
- if (!node) return;
1779
- const sourceFile = node.getSourceFile();
1780
- if (sourceFile === ownFile) return;
1781
- let path = paths.get(sourceFile);
1782
- if (path === void 0) {
1783
- path = sourceFile.getFilePath();
1784
- paths.set(sourceFile, path);
1785
- }
1786
- if (path) results.add(path);
1787
- }
1788
- };
1789
- };
1790
- /**
1791
- * The call expression to replace.
1792
- *
1793
- * `extractCallExpressionArguments` boxes the argument list against the call node and
1794
- * pushes `[callNode, argNode]` onto each argument's stack, so the call is reachable
1795
- * from either shape the parser stores: the argument array (multi-arg) or the first
1796
- * argument's map (single-arg).
1797
- */
1798
- const findCallExpression = (node) => {
1799
- const own = node.getNode?.();
1800
- if (own && Node.isCallExpression(own)) return own;
1801
- const stack = node.getStack?.() ?? [];
1802
- for (const entry of stack) if (Node.isCallExpression(entry)) return entry;
1803
- let current = own;
1804
- for (let depth = 0; current && depth < 3; depth++) {
1805
- if (Node.isCallExpression(current)) return current;
1806
- current = current.getParent();
1807
- }
1808
- };
1809
- /**
1810
- * `css.raw(...)` must keep returning a style object — folding it to a class string
1811
- * breaks every caller composing those styles. The file matcher strips `.raw` when it
1812
- * normalizes function names, so the parser result cannot tell us; the callee text can.
1813
- */
1814
- const isRawCall = (call) => {
1815
- if (!Node.isCallExpression(call)) return false;
1816
- const callee = call.getExpression().getText();
1817
- return callee === "raw" || callee.endsWith(".raw");
1818
- };
1819
- /** The identifier a callee is rooted at: `css` for `css(…)`, `panda` for `panda.css(…)`. */
1820
- const calleeRootName = (call) => {
1821
- if (!Node.isCallExpression(call)) return void 0;
1822
- let current = call.getExpression();
1823
- while (Node.isPropertyAccessExpression(current)) current = current.getExpression();
1824
- return Node.isIdentifier(current) ? current.getText() : void 0;
1825
- };
1826
- /**
1827
- * Local names a module binds to an import of bamboo's own generated system.
1828
- *
1829
- * The parser matches by name and asks neither question this does — deliberately, since
1830
- * for CSS extraction the worst case is a few unused rules. A transform cannot be that
1831
- * relaxed, and it needs both halves:
1832
- *
1833
- * - imported at all, or a user's `const css = (s) => JSON.stringify(s)` gets rewritten
1834
- * - imported *from bamboo*, or `import { css } from '@emotion/css'` does, which is the
1835
- * likelier accident of the two since a migrating project has both in the tree
1836
- *
1837
- * Answered together and once per file, because the scan is the expensive part and both
1838
- * answers fall out of the same pass. Per call site instead of per file, this scan
1839
- * measured +74% on the largest sandbox module.
1840
- */
1841
- const bambooImportedNames = (sourceFile, ctx) => {
1842
- const names = /* @__PURE__ */ new Set();
1843
- for (const declaration of sourceFile.getImportDeclarations()) {
1844
- const mod = declaration.getModuleSpecifierValue();
1845
- for (const named of declaration.getNamedImports()) {
1846
- const name = named.getNameNode().getText();
1847
- const alias = named.getAliasNode()?.getText() ?? name;
1848
- if (ctx.imports.match({
1849
- mod,
1850
- name,
1851
- alias
1852
- })) names.add(alias);
1853
- }
1854
- const namespace = declaration.getNamespaceImport();
1855
- if (namespace) {
1856
- const alias = namespace.getText();
1857
- if (ctx.imports.match({
1858
- mod,
1859
- name: alias,
1860
- alias,
1861
- kind: "namespace"
1862
- })) names.add(alias);
1863
- }
1864
- }
1865
- return names;
1866
- };
1867
- /**
1868
- * Is the callee the imported binding, or a local one that shadows it?
1869
- *
1870
- * A block-scoped binding of the same name is legal alongside the import, and it is
1871
- * the one the call actually reaches. Walking ancestors is the precise answer; the
1872
- * cost is kept off the common path by only inspecting the two node kinds that can
1873
- * introduce a binding. Ancestors of a call in JSX are overwhelmingly elements and
1874
- * attributes, which match neither and cost nothing.
1875
- */
1876
- const isShadowed = (call, name) => {
1877
- for (let node = call.getParent(); node; node = node.getParent()) {
1878
- if (Node.isSourceFile(node)) return false;
1879
- if (bindsName(node, name)) return true;
1880
- }
1881
- return false;
1882
- };
1883
- /**
1884
- * Does a binding name introduce `name`?
1885
- *
1886
- * A plain identifier check is not enough: destructuring is the likeliest way a
1887
- * same-named local reaches a call, since `({ css }) => css(…)` is what a component
1888
- * taking a `css` prop looks like. Nested and rest elements bind too, so the pattern
1889
- * is walked rather than inspected at the top level.
1890
- */
1891
- const bindingIntroduces = (nameNode, name) => {
1892
- if (!nameNode) return false;
1893
- if (Node.isIdentifier(nameNode)) return nameNode.getText() === name;
1894
- if (Node.isObjectBindingPattern(nameNode) || Node.isArrayBindingPattern(nameNode)) return nameNode.getElements().some((element) => Node.isBindingElement(element) && bindingIntroduces(element.getNameNode(), name));
1895
- return false;
1896
- };
1897
- const declarationsBind = (list, name) => Node.isVariableDeclarationList(list) && list.getDeclarations().some((declaration) => bindingIntroduces(declaration.getNameNode(), name));
1898
- const bindsName = (scope, name) => {
1899
- if (Node.isBlock(scope)) return scope.getStatements().some((statement) => statementBinds(statement, name));
1900
- if (Node.isFunctionDeclaration(scope) || Node.isArrowFunction(scope) || Node.isFunctionExpression(scope) || Node.isMethodDeclaration(scope)) return scope.getParameters().some((parameter) => bindingIntroduces(parameter.getNameNode(), name));
1901
- if (Node.isCatchClause(scope)) return bindingIntroduces(scope.getVariableDeclaration()?.getNameNode(), name);
1902
- if (Node.isForStatement(scope) || Node.isForOfStatement(scope) || Node.isForInStatement(scope)) return declarationsBind(scope.getInitializer(), name);
1903
- return false;
1904
- };
1905
- const statementBinds = (statement, name) => {
1906
- if (Node.isVariableStatement(statement)) return statement.getDeclarations().some((declaration) => bindingIntroduces(declaration.getNameNode(), name));
1907
- if (Node.isFunctionDeclaration(statement) || Node.isClassDeclaration(statement)) return statement.getNameNode()?.getText() === name;
1908
- return false;
1909
- };
1910
- const hasStyles = (data) => data.length > 0 && data.every((entry) => entry != null && typeof entry === "object");
1911
- /**
1912
- * Pair each source argument with the box the parser stored for it, and require the
1913
- * box to account for all of it. The parser keeps either the whole argument array
1914
- * (multi-arg calls) or just the first argument's map (single-arg calls).
1915
- */
1916
- const argumentsAccountedFor = (call, boxNode) => {
1917
- if (!Node.isCallExpression(call)) return false;
1918
- const args = call.getArguments();
1919
- if (args.length === 0) return true;
1920
- if (box.isArray(boxNode) && boxNode.getNode() === call) {
1921
- if (boxNode.value.length !== args.length) return false;
1922
- return args.every((arg, index) => accountsForSource(arg, boxNode.value[index]));
1923
- }
1924
- if (args.length !== 1) return false;
1925
- return accountsForSource(args[0], boxNode);
1926
- };
1927
- const foldSource = (options) => {
1928
- const { ctx, code, parserResult, runtimeCss = createRuntimeCss(ctx), styleCompiler, maxRecipeStates, parseModule, recipeConfigCache, reportSurvivors, sourceFile: ownSourceFile } = options;
1929
- const runtimeToken = createRuntimeToken(ctx);
1930
- const runtimeTokenValue = createRuntimeTokenValue(ctx);
1931
- /**
1932
- * Does this specifier name a module that exports the css API, exactly?
1933
- *
1934
- * `ImportMap.match` is substring-based, which is right for deciding whether a call is
1935
- * bamboo's and wrong for deciding whether a module can be imported *from*:
1936
- * `styled-system/css/css` matches while exporting no `cx`. So the comparison is
1937
- * equality, not containment.
1938
- *
1939
- * A tsconfig path alias is resolved first, the same way `ImportMap.match` does. Without
1940
- * that, `@site/styled-system/css` — the spelling this repo's own website uses — fails
1941
- * the check and silently loses helper lowering, which is indistinguishable in the
1942
- * diagnostics from a genuinely dynamic call.
1943
- */
1944
- const cssModules = ctx.imports.matchers.css?.mods ?? [];
1945
- /**
1946
- * The generated css module, the only one whose exports are known.
1947
- *
1948
- * A configured `importMap.css` points at the user's own wrapper, and a wrapper that
1949
- * re-exports `css` need not re-export `cx` — adding one there imports a binding that
1950
- * may not exist. Reusing a `cx` the user already imported from it stays fine, since
1951
- * that binding demonstrably resolves; only *adding* one is restricted.
1952
- */
1953
- const generatedCssModule = [ctx.imports.outdir, "css"].join("/");
1954
- const pathMappings = ctx.conf.tsOptions?.pathMappings;
1955
- /**
1956
- * The spelling reduced to the module it names.
1957
- *
1958
- * The extension and `/index` are stripped because bamboo's own output makes a file
1959
- * import them: `outExtension: 'js'` under NodeNext resolution is written
1960
- * `styled-system/css/index.js`, which is neither equal to `styled-system/css` nor a
1961
- * tail of it. Extraction admitted such a file anyway — `ImportMap.match` is
1962
- * substring-based — so the call was folded while the *insert* was refused, and the
1963
- * result was reported as `dynamic`: the same silent downgrade the alias case above
1964
- * describes, reached through the extension instead.
1965
- *
1966
- * This does not weaken the equality the comment above insists on. `styled-system/css/css`
1967
- * still names neither, because only a trailing `/index` is a module's own directory.
1968
- *
1969
- * `.d.ts` is deliberately not stripped. A declaration file exports no runtime binding, so
1970
- * matching one would authorise inserting an import that resolves to nothing — and a value
1971
- * import cannot name one anyway, which is what makes leaving it out free.
1972
- */
1973
- const trim = (value) => value.replaceAll("\\", "/").replace(LEADING_RELATIVE, "").replace(TRAILING_SLASH, "").replace(MODULE_EXTENSION, "").replace(TRAILING_INDEX, "");
1974
- const matchesModule = (mod, entries) => {
1975
- const candidates = [mod];
1976
- if (pathMappings) {
1977
- const resolved = resolveTsPathPattern(pathMappings, mod);
1978
- if (resolved) candidates.push(resolved);
1979
- }
1980
- return candidates.some((candidate) => {
1981
- const normalized = trim(candidate);
1982
- return entries.some((entry) => {
1983
- const target = trim(entry);
1984
- return normalized === target || normalized.endsWith(`/${target}`);
1985
- });
1986
- });
1987
- };
1988
- const isBambooCssModule = (mod) => matchesModule(mod, cssModules);
1989
- const isGeneratedCssModule = (mod) => matchesModule(mod, [generatedCssModule]);
1990
- /**
1991
- * Where the compiler's helpers can be imported from, for a file that imports the generated
1992
- * css module by *subpath* rather than through its barrel.
1993
- *
1994
- * `styled-system/css/cva.js` is a real spelling, and it cannot host the helper: that module
1995
- * exports `cva`, not `cvaMap`. Matching only the barrel meant no host was found and every
1996
- * runtime recipe selection in the file declined — a failure whose reported reason said
1997
- * nothing about import spelling, and whose suggested remedies all pointed elsewhere.
1998
- *
1999
- * The sibling `cx` module is what actually exports them. The prefix is verified against the
2000
- * configured output before anything is derived, so an unrelated `foo/css/bar.js` is left
2001
- * alone, and the caller's extension is preserved rather than guessed at.
2002
- */
2003
- const helperModuleFromSubpath = (mod) => {
2004
- const normalized = mod.replaceAll("\\", "/");
2005
- const at = normalized.lastIndexOf("/css/");
2006
- if (at < 0) return void 0;
2007
- const prefix = normalized.slice(0, at + 5 - 1);
2008
- if (!isGeneratedCssModule(prefix)) return void 0;
2009
- const rest = normalized.slice(at + 5);
2010
- if (!rest || rest.includes("/")) return void 0;
2011
- const dot = rest.lastIndexOf(".");
2012
- const extension = dot > 0 ? rest.slice(dot) : "";
2013
- if (rest === `cx${extension}`) return void 0;
2014
- return `${prefix}/cx${extension}`;
2015
- };
2016
- /**
2017
- * The generated css entry as spelled beside an imported config recipe.
2018
- *
2019
- * A decision table needs only `cvaMap`, but a module importing a config recipe often has
2020
- * no css import to extend. Preserve a relative/aliased styled-system spelling by replacing
2021
- * its `/recipes` suffix; falling back to the configured generated entry covers bare imports.
2022
- */
2023
- const configRecipeCssSpecifier = (call, binding) => {
2024
- for (const declaration of call.getSourceFile().getImportDeclarations()) {
2025
- if (declaration.isTypeOnly()) continue;
2026
- if (!declaration.getNamedImports().some((named) => {
2027
- if (named.isTypeOnly()) return false;
2028
- return (named.getAliasNode() ?? named.getNameNode()).getText() === binding;
2029
- })) continue;
2030
- const mod = declaration.getModuleSpecifierValue().replaceAll("\\", "/");
2031
- const at = mod.lastIndexOf("/recipes");
2032
- if (at >= 0) return `${mod.slice(0, at)}/css`;
2033
- }
2034
- return generatedCssModule;
2035
- };
2036
- /**
2037
- * How *this* module would have to spell the css module, learnt from one that already does.
2038
- *
2039
- * A file calling an imported recipe need not import the css module at all, so when the
2040
- * lowering needs a decision-table helper there is no spelling in the file to copy. The declaring module
2041
- * necessarily has one — `cva` came from it — and that is the spelling reused here.
2042
- *
2043
- * A bare or aliased specifier resolves identically from any file, so it is taken as
2044
- * written. A relative one is re-based: resolved against the module that wrote it, then
2045
- * expressed from the module being folded.
2046
- */
2047
- const cssModuleSpecifierFrom = (declaring) => {
2048
- for (const declaration of declaring.getImportDeclarations()) {
2049
- if (declaration.isTypeOnly()) continue;
2050
- const mod = declaration.getModuleSpecifierValue();
2051
- if (isGeneratedCssModule(mod)) return mod;
2052
- }
2053
- };
2054
- /**
2055
- * That spelling, said from the module being folded.
2056
- *
2057
- * A bare or aliased specifier resolves identically from any file, so it is taken as
2058
- * written. A relative one is re-based: resolved against the module that wrote it, then
2059
- * expressed from the module being folded. Pure path arithmetic, so it holds a string
2060
- * rather than a node — a cached node does not survive the next `addSourceFile`, which
2061
- * ts-morph implements by forgetting the file's whole tree.
2062
- */
2063
- const rebaseSpecifier = (specifier, declaringPath, consumingPath) => {
2064
- if (!specifier.startsWith(".")) return specifier;
2065
- const absolute = resolve(dirname(declaringPath), specifier);
2066
- const rebased = relative(dirname(consumingPath), absolute).replaceAll("\\", "/");
2067
- if (!rebased) return void 0;
2068
- return rebased.startsWith(".") ? rebased : `./${rebased}`;
2069
- };
2070
- /**
2071
- * Configs of one foreign module, parsed once however many of its recipes are called.
2072
- *
2073
- * Falls back to a per-call map when the caller supplies none, so the fold stays correct
2074
- * standalone — only repeated, which is what the shared cache exists to avoid.
2075
- */
2076
- const configsByModule = recipeConfigCache ?? /* @__PURE__ */ new Map();
2077
- /** The specifier each imported recipe's module used for the css module, when it needs one. */
2078
- const helperModules = /* @__PURE__ */ new Map();
2079
- /** Declaring modules a fold read, recorded as paths because their nodes do not persist. */
2080
- const foreignDependencies = /* @__PURE__ */ new Set();
2081
- /** Resolutions for this module's own call sites, keyed by the name the call site writes. */
2082
- const importedRecipes = /* @__PURE__ */ new Map();
2083
- /**
2084
- * The config of a recipe this module imports.
2085
- *
2086
- * The binding is followed with ts-morph's symbol aliasing rather than by re-reading import
2087
- * declarations, because that is what already understands the shapes these are reached
2088
- * through: `export { badge } from './styles'`, `export * from './styles'`, and an alias at
2089
- * either end. Each hop is an alias symbol, so following them to a non-alias lands on the
2090
- * declaration wherever it lives.
2091
- *
2092
- * The selected declarations do not depend on which module the call is in. A recipe lowered
2093
- * here therefore reaches the same globally shared atoms as a call in its declaring module.
2094
- */
2095
- const resolveImportedRecipe = (call, name, origin) => {
2096
- if (importedRecipes.has(name)) return importedRecipes.get(name);
2097
- const resolve = () => {
2098
- if (!parseModule) return void 0;
2099
- const consuming = call.getSourceFile();
2100
- if (origin.filePath === consuming.getFilePath()) return void 0;
2101
- let foreign = configsByModule.get(origin.filePath);
2102
- if (!foreign) {
2103
- const result = parseModule(origin.filePath);
2104
- if (!result) return void 0;
2105
- const collected = collectRecipeConfigs(result);
2106
- const declaring = [...collected.values()].find((entry) => entry.box)?.box?.getNode?.()?.getSourceFile();
2107
- const configs = /* @__PURE__ */ new Map();
2108
- for (const [key, entry] of collected) configs.set(key, entry === AMBIGUOUS ? entry : {
2109
- config: entry.config,
2110
- box: void 0
2111
- });
2112
- foreign = {
2113
- configs,
2114
- cssSpecifier: declaring ? cssModuleSpecifierFrom(declaring) : void 0
2115
- };
2116
- configsByModule.set(origin.filePath, foreign);
2117
- }
2118
- const entry = foreign.configs.get(origin.name);
2119
- if (!entry || entry === AMBIGUOUS) return void 0;
2120
- foreignDependencies.add(origin.filePath);
2121
- helperModules.set(name, foreign.cssSpecifier ? rebaseSpecifier(foreign.cssSpecifier, origin.filePath, consuming.getFilePath()) : void 0);
2122
- return entry;
2123
- };
2124
- const resolved = resolve();
2125
- importedRecipes.set(name, resolved);
2126
- return resolved;
2127
- };
2128
- const folded = [];
2129
- const skipped = [];
2130
- const candidates = [];
2131
- const seenRanges = /* @__PURE__ */ new Set();
2132
- const recipeConfigs = collectRecipeConfigs(parserResult);
2133
- const recipeDefinitions = [];
2134
- for (const [name, entry] of recipeConfigs) {
2135
- if (entry === AMBIGUOUS) continue;
2136
- const definition = entry.box?.getNode?.();
2137
- if (!definition) continue;
2138
- const call = Node.isCallExpression(definition) ? definition : definition.getFirstAncestorByKind(SyntaxKind.CallExpression);
2139
- if (!call || code.slice(call.getStart(), call.getEnd()) !== call.getText()) continue;
2140
- recipeDefinitions.push({
2141
- name,
2142
- call
2143
- });
2144
- }
2145
- /** Ranges already reported as declined, so one call is never counted twice. */
2146
- const reportedRanges = /* @__PURE__ */ new Set();
2147
- const importCache = /* @__PURE__ */ new Map();
2148
- const importsFor = (sourceFile) => {
2149
- let names = importCache.get(sourceFile);
2150
- if (!names) {
2151
- names = bambooImportedNames(sourceFile, ctx);
2152
- importCache.set(sourceFile, names);
2153
- }
2154
- return names;
2155
- };
2156
- for (const item of parserResult.toArray()) {
2157
- const type = item.type ?? "";
2158
- const name = item.name ?? type;
2159
- if (!item.box) continue;
2160
- const call = findCallExpression(item.box);
2161
- if (type === "token" || type === "tokenValue") {
2162
- if (!call) {
2163
- skipped.push({
2164
- name,
2165
- reason: "no-call-expression",
2166
- start: 0,
2167
- end: 0
2168
- });
2169
- continue;
2170
- }
2171
- const start = call.getStart();
2172
- const end = call.getEnd();
2173
- if (code.slice(start, end) !== call.getText()) {
2174
- skipped.push({
2175
- name,
2176
- reason: "no-call-expression",
2177
- start: 0,
2178
- end: 0
2179
- });
2180
- continue;
2181
- }
2182
- const rangeKey = `${start}:${end}`;
2183
- if (seenRanges.has(rangeKey)) continue;
2184
- seenRanges.add(rangeKey);
2185
- const rootName = calleeRootName(call);
2186
- if (!rootName || !importsFor(call.getSourceFile()).has(rootName) || isShadowed(call, rootName)) {
2187
- skipped.push({
2188
- name,
2189
- reason: "not-imported",
2190
- start,
2191
- end
2192
- });
2193
- continue;
2194
- }
2195
- const callee = Node.isCallExpression(call) ? call.getExpression() : void 0;
2196
- const propertyName = Node.isPropertyAccessExpression(callee) ? callee.getNameNode().getText() : void 0;
2197
- const wantsValue = type === "tokenValue";
2198
- if (wantsValue !== (propertyName === "value")) {
2199
- skipped.push({
2200
- name,
2201
- reason: "unsupported-kind",
2202
- start,
2203
- end
2204
- });
2205
- continue;
2206
- }
2207
- if (!wantsValue && propertyName !== void 0 && !ctx.imports.matchers.tokens.match(propertyName)) {
2208
- skipped.push({
2209
- name,
2210
- reason: "unsupported-kind",
2211
- start,
2212
- end
2213
- });
2214
- continue;
2215
- }
2216
- if (!isStaticBox(item.box) || item.data.length !== 1) {
2217
- skipped.push({
2218
- name,
2219
- reason: "dynamic",
2220
- start,
2221
- end
2222
- });
2223
- continue;
2224
- }
2225
- const path = item.data[0];
2226
- if (typeof path !== "string") {
2227
- skipped.push({
2228
- name,
2229
- reason: "dynamic",
2230
- start,
2231
- end
2232
- });
2233
- continue;
2234
- }
2235
- if (!(Node.isCallExpression(call) ? call.getArguments().slice(1) : []).every(isInertArgument)) {
2236
- skipped.push({
2237
- name,
2238
- reason: "dynamic",
2239
- start,
2240
- end
2241
- });
2242
- continue;
2243
- }
2244
- const value = wantsValue ? runtimeTokenValue(path) : runtimeToken(path);
2245
- if (!value) {
2246
- skipped.push({
2247
- name,
2248
- reason: "unresolved-token",
2249
- start,
2250
- end
2251
- });
2252
- continue;
2253
- }
2254
- candidates.push({
2255
- item,
2256
- call,
2257
- node: call,
2258
- start,
2259
- end,
2260
- value
2261
- });
2262
- continue;
2263
- }
2264
- if (!FOLDABLE_TYPES.has(type)) {
2265
- if (call && (type === RECIPE_CALL_TYPE || type === "recipe") && !isShadowed(call, name)) {
2266
- const start = call.getStart();
2267
- const end = call.getEnd();
2268
- const rangeKey = `${start}:${end}`;
2269
- if (!reportedRanges.has(rangeKey)) {
2270
- reportedRanges.add(rangeKey);
2271
- if (code.slice(start, end) !== call.getText()) {
2272
- skipped.push({
2273
- name,
2274
- reason: "no-call-expression",
2275
- start: 0,
2276
- end: 0
2277
- });
2278
- continue;
2279
- }
2280
- if (isRawCall(call)) {
2281
- skipped.push({
2282
- name,
2283
- reason: "raw-call",
2284
- start,
2285
- end
2286
- });
2287
- continue;
2288
- }
2289
- if (!recipeConfigs.has(name)) {
2290
- if (type === "recipe") {
2291
- const config = ctx.recipes.getConfig(name);
2292
- if (config) {
2293
- recipeConfigs.set(name, {
2294
- config,
2295
- box: void 0
2296
- });
2297
- helperModules.set(name, configRecipeCssSpecifier(call, name));
2298
- }
2299
- } else if (item.origin) {
2300
- const imported = resolveImportedRecipe(call, name, item.origin);
2301
- if (imported) recipeConfigs.set(name, imported);
2302
- }
2303
- }
2304
- const resolvedSelection = item.data?.length === 1 ? item.data[0] : void 0;
2305
- const entry = recipeConfigs.get(name);
2306
- let inlineSlot;
2307
- let inlineEnd = end;
2308
- if (Array.isArray(entry?.config.slots)) {
2309
- const parent = call.getParent();
2310
- if (Node.isPropertyAccessExpression(parent) && parent.getExpression() === call) {
2311
- const accessed = parent.getName();
2312
- if (entry.config.slots.includes(accessed)) {
2313
- inlineSlot = accessed;
2314
- inlineEnd = parent.getEnd();
2315
- }
2316
- } else if (Node.isElementAccessExpression(parent) && parent.getExpression() === call) {
2317
- const argument = parent.getArgumentExpression();
2318
- const accessed = argument && (Node.isStringLiteral(argument) || Node.isNoSubstitutionTemplateLiteral(argument)) ? argument.getLiteralValue() : void 0;
2319
- if (typeof accessed === "string" && entry.config.slots.includes(accessed)) {
2320
- inlineSlot = accessed;
2321
- inlineEnd = parent.getEnd();
2322
- }
2323
- }
2324
- }
2325
- const lowered = lowerRecipeCall(call, entry, styleCompiler, isInertExpression, resolvedSelection, inlineSlot, maxRecipeStates);
2326
- if (lowered.kind === "dynamic-style") {
2327
- const helper = ensureRecipeHelperImport(RECIPE_MAP_HELPER, call, isBambooCssModule, isGeneratedCssModule, isShadowed, helperModules.get(name), helperModuleFromSubpath);
2328
- if (helper) {
2329
- candidates.push({
2330
- item,
2331
- call,
2332
- node: call,
2333
- start,
2334
- end: inlineEnd,
2335
- className: "",
2336
- classNames: [],
2337
- styleMap: lowered.map,
2338
- mapHelperName: helper.name,
2339
- insert: helper.insert,
2340
- configBox: entry?.box,
2341
- outputKind: lowered.map.outputKind === "slots" ? "slots" : void 0
2342
- });
2343
- continue;
2344
- }
2345
- skipped.push({
2346
- name,
2347
- reason: "recipe-call",
2348
- start,
2349
- end
2350
- });
2351
- continue;
2352
- }
2353
- if (lowered.kind === "slots") {
2354
- const helper = lowered.helper ? ensureRecipeHelperImport(lowered.helper, call, isBambooCssModule, isGeneratedCssModule, isShadowed, helperModules.get(name), helperModuleFromSubpath) : void 0;
2355
- if (!lowered.helper || helper) {
2356
- const replacement = lowered.helper && helper && helper.name !== lowered.helper ? lowered.expression.replaceAll(`${lowered.helper}(`, `${helper.name}(`) : lowered.expression;
2357
- candidates.push({
2358
- item,
2359
- call,
2360
- node: call,
2361
- start,
2362
- end: inlineEnd,
2363
- replacement,
2364
- className: "",
2365
- classNames: lowered.classNames,
2366
- insert: helper?.insert,
2367
- configBox: entry?.box,
2368
- outputKind: "slots"
2369
- });
2370
- continue;
2371
- }
2372
- skipped.push({
2373
- name,
2374
- reason: "recipe-call",
2375
- start,
2376
- end
2377
- });
2378
- continue;
2379
- }
2380
- if (lowered.kind === "class") {
2381
- candidates.push({
2382
- item,
2383
- call,
2384
- node: call,
2385
- start,
2386
- end: inlineEnd,
2387
- replacement: JSON.stringify(lowered.className),
2388
- className: lowered.className,
2389
- classNames: lowered.className.split(" ").filter(Boolean),
2390
- styleSet: lowered.styles,
2391
- configBox: entry?.box
2392
- });
2393
- continue;
2394
- }
2395
- skipped.push({
2396
- name,
2397
- reason: "recipe-call",
2398
- start,
2399
- end
2400
- });
2401
- }
2402
- }
2403
- continue;
2404
- }
2405
- if (!call) {
2406
- skipped.push({
2407
- name,
2408
- reason: "no-call-expression",
2409
- start: 0,
2410
- end: 0
2411
- });
2412
- continue;
2413
- }
2414
- const start = call.getStart();
2415
- const end = call.getEnd();
2416
- const memberParent = call.getParent();
2417
- const accessed = type === "recipe" && Node.isPropertyAccessExpression(memberParent) && memberParent.getExpression() === call ? memberParent : void 0;
2418
- const accessedName = accessed?.getNameNode().getText();
2419
- const declaredSlots = accessed ? ctx.recipes.getConfig(name)?.slots ?? [] : [];
2420
- const memberAccess = accessedName && declaredSlots.includes(accessedName) ? accessed : void 0;
2421
- const slot = memberAccess ? accessedName : void 0;
2422
- const foldEnd = memberAccess ? memberAccess.getEnd() : end;
2423
- if (code.slice(start, end) !== call.getText()) {
2424
- skipped.push({
2425
- name,
2426
- reason: "no-call-expression",
2427
- start: 0,
2428
- end: 0
2429
- });
2430
- continue;
2431
- }
2432
- const rangeKey = `${start}:${foldEnd}`;
2433
- if (seenRanges.has(rangeKey)) continue;
2434
- seenRanges.add(rangeKey);
2435
- if (isRawCall(call)) {
2436
- skipped.push({
2437
- name,
2438
- reason: "raw-call",
2439
- start,
2440
- end
2441
- });
2442
- continue;
2443
- }
2444
- const rootName = calleeRootName(call);
2445
- if (!rootName || !importsFor(call.getSourceFile()).has(rootName) || isShadowed(call, rootName)) {
2446
- skipped.push({
2447
- name,
2448
- reason: "not-imported",
2449
- start,
2450
- end
2451
- });
2452
- continue;
2453
- }
2454
- if (!(Node.isCallExpression(call) && call.getArguments().length === 0 && item.data.length === 1) && !isStaticBox(item.box) || !hasStyles(item.data) || !argumentsAccountedFor(call, item.box)) {
2455
- skipped.push({
2456
- name,
2457
- reason: "dynamic",
2458
- start,
2459
- end
2460
- });
2461
- continue;
2462
- }
2463
- candidates.push({
2464
- item,
2465
- call,
2466
- node: call,
2467
- start,
2468
- end: foldEnd,
2469
- slot
2470
- });
2471
- }
2472
- /**
2473
- * Resolve every fully static candidate to symbolic declarations before allocating a class.
2474
- *
2475
- * The normal fold can wait until the rewrite loop to compute a class string. Semantic
2476
- * composition cannot: an enclosing `cx()` needs the declarations of its arguments so it can
2477
- * discard overridden values before any string exists.
2478
- */
2479
- {
2480
- for (const candidate of candidates) {
2481
- if (candidate.styleSet || candidate.value !== void 0 || candidate.replacement) continue;
2482
- const { item } = candidate;
2483
- if (item.type === "css") {
2484
- candidate.styleSet = styleCompiler.compose(...item.data);
2485
- continue;
2486
- }
2487
- if (item.type === "pattern") {
2488
- candidate.styleSet = styleCompiler.compose(...item.data.map((entry) => ctx.patterns.transform(item.name ?? "", entry)));
2489
- continue;
2490
- }
2491
- if (item.type === "viewTransition") {
2492
- const semantic = viewTransitionClassName(item.data[0], ctx.utility.prefix);
2493
- candidate.className = styleCompiler.allocateClassString(semantic);
2494
- candidate.classNames = [candidate.className];
2495
- candidate.replacement = JSON.stringify(candidate.className);
2496
- continue;
2497
- }
2498
- }
2499
- const sourceFile = ownSourceFile ?? candidates[0]?.node.getSourceFile();
2500
- if (sourceFile) {
2501
- const cxBindings = /* @__PURE__ */ new Set();
2502
- for (const declaration of sourceFile.getImportDeclarations()) {
2503
- if (declaration.isTypeOnly() || !isBambooCssModule(declaration.getModuleSpecifierValue())) continue;
2504
- for (const named of declaration.getNamedImports()) {
2505
- if (named.isTypeOnly() || named.getNameNode().getText() !== "cx") continue;
2506
- cxBindings.add((named.getAliasNode() ?? named.getNameNode()).getText());
2507
- }
2508
- }
2509
- const byRange = new Map(candidates.map((candidate) => [`${candidate.start}:${candidate.end}`, candidate]));
2510
- for (const call of cxBindings.size ? sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression) : []) {
2511
- const callee = call.getExpression();
2512
- if (!Node.isIdentifier(callee) || !cxBindings.has(callee.getText()) || isShadowed(call, callee.getText())) continue;
2513
- const matched = [];
2514
- const parts = [];
2515
- const dynamic = [];
2516
- const constantCandidates = [];
2517
- let supported = true;
2518
- const take = (arg) => {
2519
- const candidate = byRange.get(`${arg.getStart()}:${arg.getEnd()}`);
2520
- if (candidate?.styleMap?.outputKind === "class") {
2521
- dynamic.push(candidate);
2522
- parts.push({
2523
- kind: "dynamic",
2524
- candidate
2525
- });
2526
- return true;
2527
- }
2528
- if (candidate?.styleSet) {
2529
- matched.push(candidate);
2530
- parts.push({
2531
- kind: "style",
2532
- candidate
2533
- });
2534
- return true;
2535
- }
2536
- if (candidate?.item.type === "viewTransition" && candidate.replacement && candidate.className) {
2537
- constantCandidates.push(candidate);
2538
- parts.push({
2539
- kind: "class",
2540
- value: candidate.className,
2541
- candidate
2542
- });
2543
- return true;
2544
- }
2545
- if (Node.isStringLiteral(arg) || Node.isNoSubstitutionTemplateLiteral(arg)) {
2546
- parts.push({
2547
- kind: "class",
2548
- value: arg.getLiteralValue()
2549
- });
2550
- return true;
2551
- }
2552
- if (Node.isArrayLiteralExpression(arg)) {
2553
- for (const element of arg.getElements()) if (Node.isSpreadElement(element) || !take(element)) return false;
2554
- return true;
2555
- }
2556
- if (arg.getKind() === SyntaxKind.FalseKeyword || arg.getKind() === SyntaxKind.TrueKeyword || Node.isNumericLiteral(arg) || arg.getKind() === SyntaxKind.NullKeyword || Node.isIdentifier(arg) && arg.getText() === "undefined") return true;
2557
- return false;
2558
- };
2559
- for (const arg of call.getArguments()) {
2560
- if (take(arg)) continue;
2561
- supported = false;
2562
- break;
2563
- }
2564
- if (dynamic.length > 1) {
2565
- skipped.push({
2566
- name: "cx",
2567
- reason: "dynamic",
2568
- start: call.getStart(),
2569
- end: call.getEnd()
2570
- });
2571
- continue;
2572
- }
2573
- if (!supported) {
2574
- skipped.push({
2575
- name: "cx",
2576
- reason: "dynamic",
2577
- start: call.getStart(),
2578
- end: call.getEnd()
2579
- });
2580
- continue;
2581
- }
2582
- if (dynamic.length === 1 && matched.length > 0) {
2583
- const dynamicCandidate = dynamic[0];
2584
- const styleParts = parts.filter((part) => part.kind !== "class");
2585
- const dynamicIndex = styleParts.findIndex((part) => part.kind === "dynamic");
2586
- const before = styleParts.slice(0, dynamicIndex).filter((part) => part.kind === "style").map((part) => part.candidate.styleSet);
2587
- const after = styleParts.slice(dynamicIndex + 1).filter((part) => part.kind === "style").map((part) => part.candidate.styleSet);
2588
- const compiled = dynamicCandidate.styleMap.compile(before, after);
2589
- const expression = compiled.usesHelper && dynamicCandidate.mapHelperName && dynamicCandidate.mapHelperName !== "cvaMap" ? compiled.expression.replaceAll(`${RECIPE_MAP_HELPER}(`, `${dynamicCandidate.mapHelperName}(`) : compiled.expression;
2590
- const arguments_ = [];
2591
- let wroteCompiled = false;
2592
- for (const part of parts) {
2593
- if (part.kind === "class") {
2594
- if (part.value) arguments_.push(JSON.stringify(part.value));
2595
- continue;
2596
- }
2597
- if (!wroteCompiled) {
2598
- arguments_.push(expression);
2599
- wroteCompiled = true;
2600
- }
2601
- }
2602
- dynamicCandidate.subsumed = true;
2603
- const first = styleParts[0].candidate;
2604
- candidates.push({
2605
- ...first,
2606
- call,
2607
- node: call,
2608
- start: call.getStart(),
2609
- end: call.getEnd(),
2610
- displayName: "cx",
2611
- replacement: arguments_.length === 1 ? arguments_[0] : `${callee.getText()}(${arguments_.join(", ")})`,
2612
- className: "",
2613
- classNames: [...compiled.classNames, ...parts.filter((part) => part.kind === "class").flatMap((part) => part.value.split(" "))].filter(Boolean),
2614
- styleSet: void 0,
2615
- styleMap: void 0,
2616
- outputKind: void 0,
2617
- insert: compiled.usesHelper ? dynamicCandidate.insert : void 0,
2618
- sourceBoxes: styleParts.flatMap((part) => [part.candidate.item.box, part.candidate.configBox]).concat(constantCandidates.map((candidate) => candidate.item.box)).filter(Boolean)
2619
- });
2620
- continue;
2621
- }
2622
- if (matched.length === 0) {
2623
- if (constantCandidates.length === 0) continue;
2624
- const className = parts.filter((part) => part.kind === "class").map((part) => part.value).filter(Boolean).join(" ");
2625
- const first = constantCandidates[0];
2626
- candidates.push({
2627
- ...first,
2628
- call,
2629
- node: call,
2630
- start: call.getStart(),
2631
- end: call.getEnd(),
2632
- displayName: "cx",
2633
- replacement: JSON.stringify(className),
2634
- className,
2635
- classNames: className.split(" ").filter(Boolean),
2636
- sourceBoxes: constantCandidates.map((candidate) => candidate.item.box).filter(Boolean)
2637
- });
2638
- continue;
2639
- }
2640
- const merged = styleCompiler.compose(...matched.map((candidate) => candidate.styleSet));
2641
- const compiled = styleCompiler.className(merged);
2642
- const classParts = [];
2643
- let wroteCompiled = false;
2644
- for (const part of parts) {
2645
- if (part.kind === "class") {
2646
- if (part.value) classParts.push(part.value);
2647
- continue;
2648
- }
2649
- if (!wroteCompiled && compiled) {
2650
- classParts.push(compiled);
2651
- wroteCompiled = true;
2652
- }
2653
- }
2654
- const first = matched[0];
2655
- candidates.push({
2656
- ...first,
2657
- call,
2658
- node: call,
2659
- start: call.getStart(),
2660
- end: call.getEnd(),
2661
- displayName: "cx",
2662
- replacement: JSON.stringify(classParts.join(" ")),
2663
- className: classParts.join(" "),
2664
- classNames: classParts.flatMap((part) => part.split(" ")).filter(Boolean),
2665
- styleSet: merged,
2666
- sourceBoxes: [...matched.flatMap((candidate) => [candidate.item.box, candidate.configBox]), ...constantCandidates.map((candidate) => candidate.item.box)].filter(Boolean)
2667
- });
2668
- }
2669
- }
2670
- for (const candidate of candidates) {
2671
- if (!candidate.styleMap || candidate.subsumed || candidate.replacement) continue;
2672
- const compiled = candidate.styleMap.compile();
2673
- candidate.replacement = compiled.usesHelper && candidate.mapHelperName && candidate.mapHelperName !== "cvaMap" ? compiled.expression.replaceAll(`${RECIPE_MAP_HELPER}(`, `${candidate.mapHelperName}(`) : compiled.expression;
2674
- if (!compiled.usesHelper) candidate.insert = void 0;
2675
- candidate.className = compiled.staticClasses;
2676
- candidate.classNames = compiled.classNames;
2677
- candidate.outputKind = compiled.outputKind === "slots" ? "slots" : void 0;
2678
- }
2679
- }
2680
- /**
2681
- * Ranges the rewrite actually replaced. Declared before the early return below, because
2682
- * that return is now also a reporting point: a module with nothing to fold is exactly the
2683
- * shape `reportSurvivors` exists to catch.
2684
- */
2685
- const applied = [];
2686
- if (candidates.length === 0 && recipeDefinitions.length === 0) {
2687
- if (reportSurvivors) reportRuntimeBindings();
2688
- return {
2689
- code,
2690
- map: null,
2691
- folded,
2692
- skipped,
2693
- dependencies: []
2694
- };
2695
- }
2696
- const rewriteSourceFile = ownSourceFile ?? candidates[0]?.node.getSourceFile() ?? recipeDefinitions[0]?.call.getSourceFile();
2697
- if (!rewriteSourceFile) return {
2698
- code,
2699
- map: null,
2700
- folded,
2701
- skipped,
2702
- dependencies: []
2703
- };
2704
- const dependencyScan = createDependencyScan(rewriteSourceFile);
2705
- candidates.sort((a, b) => a.start - b.start || b.end - a.end);
2706
- const magic = new MagicString(code);
2707
- const insertedNames = /* @__PURE__ */ new Set();
2708
- const applyInsert = (insert) => {
2709
- if (!insert) return;
2710
- const missing = insert.names.filter((name) => !insertedNames.has(name));
2711
- if (!missing.length) return;
2712
- magic.appendLeft(insert.pos, insert.module ? `\nimport { ${missing.join(", ")} } from '${insert.module}'` : missing.map((name) => `, ${name}`).join(""));
2713
- for (const name of missing) insertedNames.add(name);
2714
- };
2715
- const collides = (edits) => edits.some(([start, end]) => applied.some(([from, to]) => start < to && from < end));
2716
- for (const candidate of candidates) {
2717
- const { item, start, end } = candidate;
2718
- const name = candidate.displayName ?? item.name ?? item.type ?? "";
2719
- const ranges = [[start, end]];
2720
- if (collides(ranges)) {
2721
- skipped.push({
2722
- name,
2723
- reason: "overlapping",
2724
- start,
2725
- end
2726
- });
2727
- continue;
2728
- }
2729
- if (candidate.value !== void 0) {
2730
- magic.overwrite(start, end, JSON.stringify(candidate.value));
2731
- applied.push(...ranges);
2732
- folded.push({
2733
- name,
2734
- kind: "value",
2735
- className: "",
2736
- classNames: [],
2737
- value: candidate.value,
2738
- start,
2739
- end
2740
- });
2741
- collectSourceFiles(item.box, dependencyScan);
2742
- continue;
2743
- }
2744
- if (candidate.replacement) {
2745
- magic.overwrite(start, end, candidate.replacement);
2746
- applyInsert(candidate.insert);
2747
- applied.push(...ranges);
2748
- folded.push({
2749
- name,
2750
- kind: candidate.outputKind ?? "class",
2751
- className: candidate.className,
2752
- classNames: (candidate.classNames ?? [candidate.className]).filter(Boolean),
2753
- start,
2754
- end
2755
- });
2756
- collectSourceFiles(item.box, dependencyScan);
2757
- if (candidate.configBox) collectSourceFiles(candidate.configBox, dependencyScan);
2758
- for (const box of candidate.sourceBoxes ?? []) collectSourceFiles(box, dependencyScan);
2759
- continue;
2760
- }
2761
- let className;
2762
- try {
2763
- if (item.type === "pattern") className = runtimeCss(...item.data.map((entry) => ctx.patterns.transform(name, entry)));
2764
- else className = runtimeCss(...item.data);
2765
- } catch {
2766
- skipped.push({
2767
- name,
2768
- reason: "dynamic",
2769
- start,
2770
- end
2771
- });
2772
- continue;
2773
- }
2774
- magic.overwrite(start, end, JSON.stringify(className));
2775
- applied.push(...ranges);
2776
- folded.push({
2777
- name,
2778
- kind: "class",
2779
- className,
2780
- classNames: className ? [className] : [],
2781
- start,
2782
- end
2783
- });
2784
- collectSourceFiles(item.box, dependencyScan);
2785
- }
2786
- const recipeSourceFile = candidates[0]?.node.getSourceFile();
2787
- if (recipeSourceFile && mayNameSplitVariantProps(recipeSourceFile.getFullText())) for (const access of recipeSourceFile.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression)) {
2788
- if (access.getName() !== "splitVariantProps") continue;
2789
- const target = access.getExpression();
2790
- if (!Node.isIdentifier(target)) continue;
2791
- if (isShadowed(access, target.getText())) continue;
2792
- const local = recipeConfigs?.get(target.getText());
2793
- const importedConfig = !local && importsFor(recipeSourceFile).has(target.getText()) ? ctx.recipes.getConfig(target.getText()) : void 0;
2794
- const entry = local && local !== AMBIGUOUS ? local : importedConfig ? {
2795
- config: importedConfig,
2796
- box: void 0
2797
- } : void 0;
2798
- if (!entry) continue;
2799
- const call = access.getParent();
2800
- if (!Node.isCallExpression(call) || call.getExpression() !== access) continue;
2801
- const args = call.getArguments();
2802
- if (args.length !== 1) continue;
2803
- const start = call.getStart();
2804
- const end = call.getEnd();
2805
- if (code.slice(start, end) !== call.getText()) continue;
2806
- if (collides([[start, end]])) continue;
2807
- const helper = ensureRecipeHelperImport(SPLIT_PROPS_HELPER, call, isBambooCssModule, isGeneratedCssModule, isShadowed, helperModules.get(target.getText()), helperModuleFromSubpath);
2808
- if (!helper) continue;
2809
- const keys = Object.keys(entry.config.variants ?? {});
2810
- magic.overwrite(start, end, `${helper.name}(${args[0].getText()}, ${JSON.stringify(keys)})`);
2811
- applyInsert(helper.insert);
2812
- applied.push([start, end]);
2813
- }
2814
- for (const { name, call } of recipeDefinitions) {
2815
- const start = call.getStart();
2816
- const end = call.getEnd();
2817
- if (collides([[start, end]])) continue;
2818
- magic.overwrite(start, end, "undefined");
2819
- applied.push([start, end]);
2820
- folded.push({
2821
- name,
2822
- kind: "definition",
2823
- className: "",
2824
- classNames: [],
2825
- start,
2826
- end
2827
- });
2828
- }
2829
- /**
2830
- * Bindings from a bamboo module still referenced once every rewrite is applied.
2831
- *
2832
- * Deliberately not driven by `parserResult`: that is the recogniser, and the point here is
2833
- * to catch what it did not see. A namespace import called as `s.cva(...)`, a default
2834
- * import, a specifier that resolved to nothing — each leaves a live reference and no ledger
2835
- * entry at all, which used to let a build silently ship the engine.
2836
- *
2837
- * The helpers the compiler writes are excluded because they pull no style engine. `cx` is
2838
- * also allowed to remain when it joins an arbitrary external class; only fully analyzable
2839
- * arguments receive Bamboo's semantic composition guarantee.
2840
- */
2841
- /** The specifier this module imported `binding` through, if it did. */
2842
- function importSpecifierFor(sourceFile, binding) {
2843
- for (const declaration of sourceFile.getImportDeclarations()) {
2844
- if (declaration.isTypeOnly()) continue;
2845
- for (const named of declaration.getNamedImports()) {
2846
- if (named.isTypeOnly()) continue;
2847
- if ((named.getAliasNode() ?? named.getNameNode()).getText() === binding) return named.getAliasNode() ?? named.getNameNode();
362
+ order: "pre",
363
+ async handler(builder) {
364
+ session.expectedEnvironments = new Set(Object.keys(builder.environments));
2848
365
  }
2849
- }
2850
- }
2851
- function reportRuntimeBindings() {
2852
- const sourceFile = ownSourceFile ?? candidates[0]?.node.getSourceFile() ?? recipeDefinitions[0]?.call.getSourceFile();
2853
- if (!sourceFile) return;
2854
- const importedRecipeBindings = new Set(parserResult.importedRecipes?.keys() ?? []);
366
+ },
2855
367
  /**
2856
- * Every identifier in the module, grouped by the name it spells — built at most once per
2857
- * pass, and only when something below has a name to look up.
2858
- *
2859
- * One index answers for every binding, rather than a walk per binding. Built here rather
2860
- * than cached across passes: it holds nodes, and a node does not outlive its source file
2861
- * being replaced.
368
+ * Put `styled-system/` on disk before anything resolves an import of it.
2862
369
  *
2863
- * Deferred because most modules in an app neither declare nor import a recipe, and the
2864
- * walk is not cheap `getDescendantsOfKind` wraps every identifier in the file in a
2865
- * ts-morph node to answer a question those modules never ask. It was 11% of a 6,307-file
2866
- * build, most of it spent producing an index nothing read.
370
+ * Normalized rather than rethrown as caught, for the reason the compiler's `buildStart`
371
+ * gives: this evaluates the user's config and its hooks, and in dev anything that is not an
372
+ * object crashes Vite's error middleware instead of being reported.
2867
373
  */
2868
- let identifiers;
2869
- const identifiersByName = () => identifiers ??= identifierIndex(sourceFile);
2870
- for (const binding of new Set([...recipeConfigs.keys(), ...importedRecipeBindings])) {
2871
- const entry = recipeConfigs.get(binding);
2872
- if (entry === AMBIGUOUS) continue;
2873
- if (!entry && !importedRecipeBindings.has(binding)) continue;
2874
- const definition = entry?.box?.getNode?.();
2875
- const nameNode = definition?.getSourceFile() === sourceFile ? definition?.getFirstAncestorByKind(SyntaxKind.VariableDeclaration)?.getNameNode() : importSpecifierFor(sourceFile, binding);
2876
- if (!nameNode || !Node.isIdentifier(nameNode)) continue;
2877
- const references = localReferencesTo(identifiersByName(), binding, nameNode);
2878
- if (skipped.filter((item) => SURVIVES_TO_RUNTIME.has(item.reason) && item.end > item.start).some((item) => references.some((ref) => ref.getStart() >= item.start && ref.getStart() < item.end))) continue;
2879
- const survivor = references.find((ref) => !applied.some(([from, to]) => ref.getStart() >= from && ref.getStart() < to));
2880
- if (!survivor) continue;
2881
- skipped.push({
2882
- name: binding,
2883
- reason: "runtime-binding",
2884
- start: survivor.getStart(),
2885
- end: survivor.getEnd()
2886
- });
2887
- }
2888
- const bambooModules = [
2889
- ...cssModules,
2890
- ...ctx.imports.matchers.recipe?.mods ?? [],
2891
- ...ctx.imports.matchers.pattern?.mods ?? [],
2892
- ...ctx.imports.matchers.tokens?.mods ?? []
2893
- ];
2894
- const runtimeCalls = [];
2895
- const importEquals = [];
2896
- sourceFile.forEachDescendant((node) => {
2897
- if (Node.isCallExpression(node)) runtimeCalls.push(node);
2898
- else if (Node.isImportEqualsDeclaration(node)) importEquals.push(node);
2899
- });
2900
- for (const call of runtimeCalls) {
2901
- const callee = call.getExpression();
2902
- const argument = call.getArguments()[0];
2903
- if (!argument || !Node.isStringLiteral(argument) && !Node.isNoSubstitutionTemplateLiteral(argument)) continue;
2904
- if (!matchesModule(argument.getLiteralValue(), bambooModules)) continue;
2905
- const isDynamicImport = callee.getKind() === SyntaxKind.ImportKeyword;
2906
- const isRequire = Node.isIdentifier(callee) && callee.getText() === "require" && !isShadowed(call, "require");
2907
- if (!isDynamicImport && !isRequire) continue;
2908
- skipped.push({
2909
- name: isDynamicImport ? "import" : "require",
2910
- reason: "runtime-binding",
2911
- start: call.getStart(),
2912
- end: call.getEnd()
2913
- });
2914
- }
2915
- for (const declaration of importEquals) {
2916
- if (declaration.isTypeOnly()) continue;
2917
- const reference = declaration.getModuleReference();
2918
- if (!Node.isExternalModuleReference(reference)) continue;
2919
- const expression = reference.getExpression();
2920
- if (!expression || !Node.isStringLiteral(expression) || !matchesModule(expression.getLiteralValue(), bambooModules)) continue;
2921
- skipped.push({
2922
- name: declaration.getName(),
2923
- reason: "runtime-binding",
2924
- start: declaration.getStart(),
2925
- end: declaration.getEnd()
2926
- });
2927
- }
2928
- /** Local name -> what to call it in the report. */
2929
- const watched = /* @__PURE__ */ new Map();
2930
- for (const declaration of sourceFile.getImportDeclarations()) {
2931
- if (declaration.isTypeOnly()) continue;
2932
- if (!matchesModule(declaration.getModuleSpecifierValue(), bambooModules)) continue;
2933
- for (const named of declaration.getNamedImports()) {
2934
- if (named.isTypeOnly()) continue;
2935
- const imported = named.getNameNode().getText();
2936
- if (PERMITTED_BINDINGS.has(imported)) continue;
2937
- watched.set((named.getAliasNode() ?? named.getNameNode()).getText(), imported);
2938
- }
2939
- const namespace = declaration.getNamespaceImport();
2940
- if (namespace) watched.set(namespace.getText(), `${namespace.getText()}.*`);
2941
- const defaultImport = declaration.getDefaultImport();
2942
- if (defaultImport) watched.set(defaultImport.getText(), defaultImport.getText());
2943
- }
2944
- for (const declaration of sourceFile.getExportDeclarations()) {
2945
- if (declaration.isTypeOnly()) continue;
2946
- if (!matchesModule(declaration.getModuleSpecifierValue() ?? "", bambooModules)) continue;
2947
- if (declaration.isNamespaceExport()) {
2948
- skipped.push({
2949
- name: declaration.getNamespaceExport()?.getName() ?? "*",
2950
- reason: "runtime-binding",
2951
- start: declaration.getStart(),
2952
- end: declaration.getEnd()
2953
- });
2954
- continue;
374
+ async buildStart() {
375
+ try {
376
+ await prebuild();
377
+ } catch (error) {
378
+ throw asError(error, `failed to generate ${VIRTUAL_CSS_ID}`);
2955
379
  }
2956
- for (const named of declaration.getNamedExports()) {
2957
- if (named.isTypeOnly()) continue;
2958
- const imported = named.getNameNode().getText();
2959
- if (PERMITTED_BINDINGS.has(imported)) continue;
2960
- skipped.push({
2961
- name: imported,
2962
- reason: "runtime-binding",
2963
- start: named.getStart(),
2964
- end: named.getEnd()
2965
- });
380
+ },
381
+ resolveId(id) {
382
+ const query = queryOf(id);
383
+ const base = id.slice(0, id.length - query.length);
384
+ if (base !== "virtual:bamboo.css" && base !== RESOLVED_ID) return null;
385
+ return `${RESOLVED_ID}${query}`;
386
+ },
387
+ async load(id) {
388
+ const query = queryOf(id);
389
+ if (id.slice(0, id.length - query.length) !== RESOLVED_ID) return null;
390
+ session.cssLoaded = true;
391
+ let css;
392
+ try {
393
+ const validateDevCss = command === "serve" ? (await loadCssOutput()).pruneStaticCss : void 0;
394
+ const first = prebuilt;
395
+ prebuilt = void 0;
396
+ css = await (first ?? generate());
397
+ if (validateDevCss) css = validateDevCss(css, session, { prune: false });
398
+ } catch (error) {
399
+ throw asError(error, `failed to generate ${VIRTUAL_CSS_ID}`);
2966
400
  }
2967
- }
2968
- for (const declaration of sourceFile.getExportDeclarations()) {
2969
- if (declaration.isTypeOnly() || declaration.getModuleSpecifier()) continue;
2970
- for (const named of declaration.getNamedExports()) {
2971
- if (named.isTypeOnly()) continue;
2972
- const imported = watched.get(named.getNameNode().getText());
2973
- if (imported === void 0) continue;
2974
- skipped.push({
2975
- name: imported,
2976
- reason: "runtime-binding",
2977
- start: named.getStart(),
2978
- end: named.getEnd()
2979
- });
401
+ if (this.addWatchFile) for (const file of extractedSourceFiles()) this.addWatchFile(file);
402
+ return css;
403
+ },
404
+ configureServer(devServer) {
405
+ server = devServer;
406
+ /**
407
+ * The graph the stylesheet's own module lives in, which is the one that has to reach it.
408
+ *
409
+ * `load` registers every extracted file with `addWatchFile`, and `vite:css-analysis`
410
+ * turns those into real importer edges — the virtual module ends up a direct importer of
411
+ * each file the extractor read. So an edit to any of them propagates to the stylesheet on
412
+ * Vite's own pass, in whichever environment holds that edge.
413
+ *
414
+ * The client one, because CSS is a client concern: an ssr environment never applies a
415
+ * stylesheet update, and asking whether *any* environment matched would skip the forced
416
+ * reload below for a server-only module whose styles the client still has to be told
417
+ * about. Vite 5 has one graph and no `environments`, where the question is exact.
418
+ */
419
+ const clientGraph = devServer.environments?.client?.moduleGraph ?? devServer.moduleGraph;
420
+ const invalidate = (file) => {
421
+ const ctx = builder?.context;
422
+ if (!ctx) return;
423
+ const absoluteFile = ctx.runtime.path.abs(ctx.config.cwd, file);
424
+ if (!session.extractedFiles.has(absoluteFile)) return;
425
+ prebuilt = void 0;
426
+ const mod = server?.moduleGraph.getModuleById(RESOLVED_ID);
427
+ if (!mod) return;
428
+ if (clientGraph.getModulesByFile(absoluteFile)?.size) return;
429
+ server?.moduleGraph.invalidateModule(mod);
430
+ server?.reloadModule(mod);
431
+ logger.debug("vite", `styles invalidated by ${absoluteFile}`);
432
+ };
433
+ devServer.watcher.on("change", invalidate);
434
+ devServer.watcher.on("add", invalidate);
435
+ devServer.watcher.on("unlink", invalidate);
436
+ },
437
+ generateBundle: {
438
+ order: "post",
439
+ async handler(outputOptions, bundle) {
440
+ const { containsGeneratedCssAsset, optimizeStaticCssAssets } = await loadCssOutputModule();
441
+ const environment = this.environment;
442
+ const environmentName = environment?.name ?? "default";
443
+ const replacesGeneratedStylesheet = containsGeneratedCssAsset(bundle);
444
+ const outputProjection = session.beginOutputProjection(environmentName, outputOptions, bundle, replacesGeneratedStylesheet);
445
+ try {
446
+ /**
447
+ * Pruned against what this environment compiled, without waiting for the rest.
448
+ *
449
+ * The stylesheet is emitted and finalized by the environment that *imports* it, which
450
+ * in an SSR app is the client — and the client builds first, before the server
451
+ * environment has transformed a single module. Waiting for a complete answer therefore
452
+ * meant never pruning at all in any SSR framework: react-router, Remix, Nuxt, SvelteKit
453
+ * and Qwik all build the client first, and the client's output is on disk before the
454
+ * server environment starts. That is most production apps, and the feature was inert in
455
+ * every one of them — silently, since a build with nothing to prune looks identical.
456
+ *
457
+ * The reason for waiting was real: a class only the server graph reaches is not in this
458
+ * environment's reachability set, so pruning here removes rules the server-rendered
459
+ * markup still names. What makes it safe to prune anyway is that the mistake is
460
+ * *detectable* rather than silent — `buildEnd` in `plugin.ts` intersects every later
461
+ * environment's compiled classes against `prunedClasses` and fails the build naming
462
+ * them. A styled component that only ever renders on the server is the shape that
463
+ * trips it, and `pruneCss: false` is the answer when it does.
464
+ *
465
+ * So the trade is deliberate: a loud build failure in the rare case, in exchange for
466
+ * the feature working at all in the common one. It is the same reasoning as the
467
+ * unimported-`virtual:bamboo.css` check — a class with no rule behind it must never
468
+ * leave the build quietly.
469
+ */
470
+ const pending = remainingEnvironments(session);
471
+ if (pending.length) logger.debug("vite", `Pruning against the ${JSON.stringify(environment?.name ?? "default")} environment with ${truncateList(pending, {
472
+ unit: "environment",
473
+ separator: ", "
474
+ })} still to compile. A class only those reach fails the build rather than shipping without its rule.`);
475
+ const { sheets } = optimizeStaticCssAssets(bundle, session, {
476
+ environment: environmentName,
477
+ prune: pruneCss,
478
+ requiredClasses: outputProjection.requiredClasses,
479
+ sourcemap: environment?.config?.build?.sourcemap
480
+ });
481
+ if (sheets && !pruneCss) logger.info("vite", "Reachability pruning is off (`pruneCss: false`). The full extracted stylesheet ships.");
482
+ if (!outputProjection.cssLoaded) return;
483
+ if (!session.transformedFiles.size) return;
484
+ /**
485
+ * An SSR bundle emits no CSS assets, and is not supposed to.
486
+ *
487
+ * `build.ssrEmitAssets` is off by default, so Vite discards them: the client build is
488
+ * what carries the stylesheet, and a server bundle that imports `virtual:bamboo.css`
489
+ * from shared code — a root component, a layout — still asks this plugin to load it.
490
+ * Which means the environment *served* the sheet and then emitted nothing, and the
491
+ * check below read that as the failure it exists to catch.
492
+ *
493
+ * It fails a build that is entirely correct. Qwik's `vite build --ssr` is the shape
494
+ * that showed it: 7/7 calls compiled, the client bundle carrying the stylesheet, and
495
+ * the server bundle refusing to finish. React Router does not hit it only because its
496
+ * plugin turns `ssrEmitAssets` on.
497
+ *
498
+ * Read per environment where that exists, falling back to the run's own config, so
499
+ * Vite 5's single-config builds are answered by the same question.
500
+ */
501
+ const buildOptions = environment?.config?.build ?? ssrBuildOptions;
502
+ if (buildOptions?.ssr && !buildOptions.ssrEmitAssets) return;
503
+ if (!replacesGeneratedStylesheet) throw new Error(`bamboocss: ${session.transformedFiles.size} module(s) were compiled to Bamboo class values, but no emitted asset carries the generated stylesheet. The build would ship unstyled.\n\nThis happens when another plugin, or the bundler itself, drops or replaces the CSS asset after it is emitted. If you are on Rolldown, report this — the rename that used to cause it is already disabled there. Otherwise look for a plugin running in \`generateBundle\` that rewrites CSS assets.`);
504
+ } finally {
505
+ outputProjection.restore();
506
+ }
2980
507
  }
2981
508
  }
2982
- if (watched.size === 0) return;
2983
- const declined = skipped.filter((entry) => SURVIVES_TO_RUNTIME.has(entry.reason) && entry.end > entry.start).map((entry) => [entry.start, entry.end]);
2984
- const survivors = [];
2985
- for (const [local, imported] of watched) for (const identifier of identifiersByName().get(local)) {
2986
- const start = identifier.getStart();
2987
- if (identifier.getFirstAncestorByKind(SyntaxKind.ImportDeclaration)) continue;
2988
- if (applied.some(([from, to]) => start >= from && start < to)) continue;
2989
- if (declined.some(([from, to]) => start >= from && start < to)) continue;
2990
- if (!isValueReference(identifier)) continue;
2991
- if (isShadowed(identifier, local)) continue;
2992
- survivors.push({
2993
- name: imported,
2994
- reason: "runtime-binding",
2995
- start,
2996
- end: identifier.getEnd()
2997
- });
2998
- break;
2999
- }
3000
- survivors.sort((a, b) => a.start - b.start);
3001
- skipped.push(...survivors);
3002
- }
3003
- if (reportSurvivors) reportRuntimeBindings();
3004
- if (folded.length === 0) return {
3005
- code,
3006
- map: null,
3007
- folded,
3008
- skipped,
3009
- dependencies: []
3010
- };
3011
- return {
3012
- code: magic.toString(),
3013
- map: magic.generateMap({
3014
- source: options.filePath,
3015
- hires: true,
3016
- includeContent: true
3017
- }),
3018
- folded,
3019
- skipped,
3020
- dependencies: [...dependencyScan.results, ...foreignDependencies]
3021
- };
3022
- };
3023
- //#endregion
3024
- //#region src/style-set.ts
3025
- const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
3026
- /** A compound selector matches only through variant classes the recipe actually emits. */
3027
- const matchesCompound = (compound, selection, variants) => {
3028
- for (const [key, expected] of Object.entries(compound)) {
3029
- if (key === "css") continue;
3030
- const declared = variants?.[key];
3031
- const selected = selection[key];
3032
- if (selected == null || !declared || !Object.hasOwn(declared, String(selected))) return false;
3033
- if (!(Array.isArray(expected) ? expected : [expected]).some((value) => value != null && String(selected) === String(value))) return false;
3034
- }
3035
- return true;
3036
- };
3037
- /**
3038
- * Resolve the style fragments one recipe call contributes, in emitted-rule precedence.
3039
- *
3040
- * This intentionally rejects conditional variant *selections*. A scalar selects a style
3041
- * object; an object such as `{ base: 'sm', md: 'lg' }` selects several objects under
3042
- * conditions and needs a separate lowering. Returning `undefined` rejects that call instead
3043
- * of silently compiling only one branch.
3044
- */
3045
- const createStaticStyleSetCompiler = (ctx, runtimeCss, allocateClassString = (className) => className) => {
3046
- const { mergeCssUncached } = createMergeCss(createCssContext(ctx));
3047
- const compose = (...styles) => mergeCssUncached(...styles);
3048
- const resolveRecipe = (config, input = {}, slot) => {
3049
- const slots = Array.isArray(config.slots) ? config.slots : void 0;
3050
- if (Boolean(slots) !== Boolean(slot)) return void 0;
3051
- if (slot && !slots?.includes(slot)) return void 0;
3052
- const selection = {
3053
- ...config.defaultVariants ?? {},
3054
- ...compact(input)
3055
- };
3056
- if (Object.values(selection).some((value) => isRecord(value))) return void 0;
3057
- const fragments = [];
3058
- const take = (candidate) => {
3059
- if (!isRecord(candidate)) return;
3060
- const styles = slot ? candidate[slot] : candidate;
3061
- if (isRecord(styles)) fragments.push(styles);
3062
- };
3063
- take(config.base);
3064
- for (const variant of Object.keys(config.variants ?? {})) {
3065
- const value = selection[variant];
3066
- if (value == null) continue;
3067
- take(config.variants?.[variant]?.[String(value)]);
3068
- }
3069
- for (const compound of config.compoundVariants ?? []) {
3070
- if (!isRecord(compound) || !matchesCompound(compound, selection, config.variants)) continue;
3071
- take(compound.css);
3072
- }
3073
- return compose(...fragments);
3074
- };
3075
- return {
3076
- compose,
3077
- resolveRecipe,
3078
- className: (...styles) => runtimeCss(...styles),
3079
- allocateClassString
3080
509
  };
3081
510
  };
3082
511
  //#endregion
3083
512
  //#region src/plugin.ts
3084
513
  const DEFAULT_EXTENSIONS = /\.(?:[cm]?[jt]sx?)$/;
3085
514
  const NODE_MODULES = /node_modules/;
515
+ const TRANSFORM_META_KEY = "bamboocss:transform";
516
+ const TRANSFORM_ARTIFACT_VERSION = 3;
3086
517
  /**
3087
518
  * Queries that make Vite serve something other than the module's own source.
3088
519
  *
@@ -3186,43 +617,141 @@ const bamboocss = (options = {}) => {
3186
617
  markStaticCompilerActive();
3187
618
  if (maxRecipeStates !== void 0 && (!Number.isSafeInteger(maxRecipeStates) || maxRecipeStates < 1)) throw new Error("bamboocss: `maxRecipeStates` must be a positive safe integer.");
3188
619
  if ("renameCssAsset" in options) throw new Error("bamboocss: `renameCssAsset` has been replaced by `pruneCss`. Use `pruneCss: false` for what `renameCssAsset: false` did — it always disabled the pruning as well, since pruned bytes under the unpruned sheet's name is what lets a CDN serve a stale stylesheet. The new name says which of the two it is really about.");
3189
- /**
3190
- * What each file's transform found, for the summary. Keyed by file rather than summed as it
3191
- * goes, because a build has more than one environment and they share most of their modules.
3192
- *
3193
- * Running totals double-counted every shared module once per environment — a two-environment
3194
- * build of one shared file and one entry each reported "2/2 across 2/4 files" for three
3195
- * source modules. Coverage is a property of the source, not of how many times a bundler
3196
- * handed the same file over. It also grew without bound in dev, where every HMR
3197
- * re-transform of a file counted as another file.
3198
- *
3199
- * A second pass over a file replaces its entry rather than adding to it. Both environments
3200
- * are assumed to compute the same answer for the same module — true of this compiler, though
3201
- * not something the plugin can enforce, since another `pre` plugin may hand each environment
3202
- * different code. Where they disagree the last one wins, which is a cosmetic number either
3203
- * way.
3204
- */
3205
- const perFile = /* @__PURE__ */ new Map();
3206
620
  const staticSession = createStaticCompilationSession();
3207
- /**
3208
- * Indexed by file, because the only bulk operation on it is "forget this one's".
3209
- *
3210
- * A flat array meant every transform scanned every survivor and then rebuilt the dedupe key
3211
- * set from scratch — O(modules x survivors) across a build, and worst exactly when a build is
3212
- * already failing and the user is iterating on it. One project had 736 of them across 9,461
3213
- * modules, which is seven million string builds to discard.
3214
- */
3215
- const survivorsByFile = /* @__PURE__ */ new Map();
3216
- const allSurvivors = () => [...survivorsByFile.values()].flat();
3217
- const addSurvivor = (entry) => {
3218
- const forFile = survivorsByFile.get(entry.file) ?? [];
3219
- if (forFile.some((seen) => seen.line === entry.line && seen.name === entry.name && seen.reason === entry.reason)) return;
3220
- forFile.push(entry);
3221
- survivorsByFile.set(entry.file, forFile);
621
+ const transformArtifactIntegrityKey = randomBytes(32);
622
+ const serializeTransformArtifact = (environment, artifact) => JSON.stringify([
623
+ TRANSFORM_META_KEY,
624
+ environment,
625
+ artifact.version,
626
+ artifact.moduleId,
627
+ artifact.file,
628
+ artifact.folded,
629
+ artifact.skipped.map(([reason, count]) => [reason, count]),
630
+ artifact.survivors.map(({ line, name, reason }) => [
631
+ line,
632
+ name,
633
+ reason
634
+ ]),
635
+ artifact.transformedFile,
636
+ [...artifact.classNames],
637
+ [...artifact.dependencies],
638
+ artifact.signature ? [
639
+ artifact.signature.input,
640
+ artifact.signature.output,
641
+ artifact.signature.path
642
+ ] : null
643
+ ]);
644
+ const transformArtifactIntegrity = (environment, artifact) => createHmac("sha256", transformArtifactIntegrityKey).update(serializeTransformArtifact(environment, artifact)).digest("base64url");
645
+ const sealTransformArtifact = (environment, artifact) => ({
646
+ ...artifact,
647
+ integrity: transformArtifactIntegrity(environment, artifact)
648
+ });
649
+ const skipReasons = new Set([
650
+ "dynamic",
651
+ "raw-call",
652
+ "recipe-call",
653
+ "unsupported-kind",
654
+ "not-imported",
655
+ "no-call-expression",
656
+ "overlapping",
657
+ "unresolved-token",
658
+ "runtime-binding",
659
+ "compile-failed"
660
+ ]);
661
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
662
+ const isNonNegativeInteger = (value) => Number.isSafeInteger(value) && value >= 0;
663
+ const isPositiveInteger = (value) => Number.isSafeInteger(value) && value > 0;
664
+ const isTransformArtifact = (value) => {
665
+ if (!isRecord(value) || value.version !== TRANSFORM_ARTIFACT_VERSION) return false;
666
+ if (typeof value.moduleId !== "string" || typeof value.file !== "string") return false;
667
+ if (!isNonNegativeInteger(value.folded) || typeof value.transformedFile !== "boolean") return false;
668
+ if (typeof value.integrity !== "string" || !/^[\w-]{43}$/.test(value.integrity)) return false;
669
+ if (!Array.isArray(value.classNames) || !value.classNames.every((entry) => typeof entry === "string")) return false;
670
+ if (!Array.isArray(value.dependencies) || !value.dependencies.every((entry) => typeof entry === "string")) return false;
671
+ if (!Array.isArray(value.skipped) || !value.skipped.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && skipReasons.has(entry[0]) && isPositiveInteger(entry[1]))) return false;
672
+ if (!Array.isArray(value.survivors) || !value.survivors.every((entry) => isRecord(entry) && Number.isSafeInteger(entry.line) && entry.line >= 1 && typeof entry.name === "string" && typeof entry.reason === "string" && skipReasons.has(entry.reason))) return false;
673
+ if (value.signature === void 0) return true;
674
+ return isRecord(value.signature) && typeof value.signature.input === "string" && typeof value.signature.output === "string" && value.signature.path === value.file;
675
+ };
676
+ const hasValidTransformArtifactIntegrity = (environment, artifact) => {
677
+ const expected = Buffer.from(transformArtifactIntegrity(environment, artifact));
678
+ const actual = Buffer.from(artifact.integrity);
679
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
3222
680
  };
3223
- const clearSurvivorsFor = (file) => {
3224
- survivorsByFile.delete(file);
681
+ const cachedArtifactError = (id, environment, value, snapshotProblem) => {
682
+ let problem;
683
+ if (snapshotProblem) problem = snapshotProblem;
684
+ else if (!isRecord(value) || value.version !== TRANSFORM_ARTIFACT_VERSION) problem = isRecord(value) && (typeof value.version === "number" || typeof value.version === "string") ? `uses version ${JSON.stringify(value.version)}; expected schema version ${TRANSFORM_ARTIFACT_VERSION}` : `is malformed and has no valid version; expected schema version ${TRANSFORM_ARTIFACT_VERSION}`;
685
+ else if (!isTransformArtifact(value)) problem = `is malformed for schema version ${TRANSFORM_ARTIFACT_VERSION}`;
686
+ else if (value.moduleId !== id || value.file !== id.split("?")[0]) problem = `does not belong to this module id and physical file`;
687
+ else if (!hasValidTransformArtifactIntegrity(environment, value)) problem = `failed its schema version ${TRANSFORM_ARTIFACT_VERSION} integrity check`;
688
+ else problem = `could not be validated for schema version ${TRANSFORM_ARTIFACT_VERSION}`;
689
+ return /* @__PURE__ */ new Error(`bamboocss: cached transform metadata for ${JSON.stringify(id)} in the ${JSON.stringify(environment)} environment ${problem}.\n\nBamboo cannot safely rebuild from this entry because cached JavaScript may still name CSS classes whose rules would be dropped. Restart Vite to invalidate its in-memory transform cache. If this persists, clear Vite's cache directory and rebuild.`);
690
+ };
691
+ const transformStateByEnvironment = /* @__PURE__ */ new Map();
692
+ /** The immutable generation currently occupying each configured output on disk. */
693
+ const liveOutputSlotsByEnvironment = /* @__PURE__ */ new Map();
694
+ /** Graphs which passed `buildEnd`, but whose output has not succeeded yet. */
695
+ const preparedGenerations = /* @__PURE__ */ new Map();
696
+ /** Success accumulated across hosts which run one buildStart/buildEnd pair per output. */
697
+ const pendingOutputCycles = /* @__PURE__ */ new Map();
698
+ /** Last configured output whose render phase actually began, for missing-marker recovery. */
699
+ const lastStartedOutputSlotByEnvironment = /* @__PURE__ */ new Map();
700
+ const nextBuildSerialByEnvironment = /* @__PURE__ */ new Map();
701
+ const observedBuildSerialByEnvironment = /* @__PURE__ */ new Map();
702
+ const buildSerialByState = /* @__PURE__ */ new WeakMap();
703
+ /** Output finalizers installed by the `options` hook for the next generation. */
704
+ const outputTokensByEnvironment = /* @__PURE__ */ new Map();
705
+ const OUTPUT_FINALIZER = Symbol("bamboocss-output-finalizer");
706
+ const OUTPUT_START_MARKER = Symbol("bamboocss-output-start-marker");
707
+ const DIRECT_OUTPUT_TOKEN = 0;
708
+ let nextOutputToken = 0;
709
+ let nextEpochId = 0;
710
+ const outputIdentityByBundle = /* @__PURE__ */ new WeakMap();
711
+ const outputIdentityByOptions = /* @__PURE__ */ new WeakMap();
712
+ const outputStageByBundle = /* @__PURE__ */ new WeakMap();
713
+ const outputStageByOptions = /* @__PURE__ */ new WeakMap();
714
+ const environmentOf = (context) => context.environment;
715
+ const environmentName = (context) => environmentOf(context)?.name ?? "default";
716
+ const newEnvironmentState = () => ({
717
+ transformArtifactsByModule: /* @__PURE__ */ new Map(),
718
+ dependentsByDependency: /* @__PURE__ */ new Map(),
719
+ dependenciesByModule: /* @__PURE__ */ new Map(),
720
+ filesByModule: /* @__PURE__ */ new Map(),
721
+ foldSignatures: /* @__PURE__ */ new Map(),
722
+ recipeConfigCache: /* @__PURE__ */ new Map(),
723
+ transformedModulesThisRun: /* @__PURE__ */ new Set(),
724
+ unchangedFolds: /* @__PURE__ */ new Map(),
725
+ changedRun: 0,
726
+ cssLoaded: false
727
+ });
728
+ const cloneEnvironmentState = (state) => ({
729
+ transformArtifactsByModule: new Map(state.transformArtifactsByModule),
730
+ dependentsByDependency: new Map([...state.dependentsByDependency].map(([dependency, dependents]) => [dependency, new Set(dependents)])),
731
+ dependenciesByModule: new Map([...state.dependenciesByModule].map(([moduleId, dependencies]) => [moduleId, new Set(dependencies)])),
732
+ filesByModule: new Map(state.filesByModule),
733
+ foldSignatures: new Map(state.foldSignatures),
734
+ recipeConfigCache: new Map(state.recipeConfigCache),
735
+ transformedModulesThisRun: new Set(state.transformedModulesThisRun),
736
+ unchangedFolds: new Map(state.unchangedFolds),
737
+ changedRun: state.changedRun,
738
+ cssLoaded: state.cssLoaded
739
+ });
740
+ const environmentState = (context) => {
741
+ const identity = environmentName(context);
742
+ let state = transformStateByEnvironment.get(identity);
743
+ if (!state) {
744
+ state = newEnvironmentState();
745
+ transformStateByEnvironment.set(identity, state);
746
+ }
747
+ return state;
3225
748
  };
749
+ const allSurvivors = (states) => [...states].flatMap((state) => [...state.transformArtifactsByModule.values()].flatMap((artifact) => artifact.survivors.map(({ line, name, reason }) => ({
750
+ file: artifact.file,
751
+ line,
752
+ name,
753
+ reason
754
+ }))));
3226
755
  const createSurvivorError = (entries) => {
3227
756
  const byFile = /* @__PURE__ */ new Map();
3228
757
  for (const entry of entries) {
@@ -3239,13 +768,6 @@ const bamboocss = (options = {}) => {
3239
768
  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" : "") + (entries.some((entry) => entry.reason === "runtime-binding") ? "`runtime-binding` is a Bamboo value read rather than called. An inline `cva`/`sva` declaration is erased, so its binding is `undefined` at runtime: calling it compiles, including from another module, but reading the value itself — `const alias = badge`, `badge.raw(...)`, re-exporting it — has nothing behind it. The location given is the read to change, not the declaration.\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`.\n\nSet `BAMBOO_DIAGNOSTIC_LIMIT=all` to list every finding rather than the first few.");
3240
769
  };
3241
770
  /**
3242
- * Recipe configs read out of modules other than the one being transformed.
3243
- *
3244
- * Per build rather than per module: a recipe declared once and imported by fifty components
3245
- * would otherwise re-parse its module fifty times, which is the transform path.
3246
- */
3247
- const recipeConfigCache = /* @__PURE__ */ new Map();
3248
- /**
3249
771
  * Which modules folded a value read out of which other module, for dev invalidation.
3250
772
  *
3251
773
  * `addWatchFile` reports the same edges, and in a build that is enough — Rollup discards a
@@ -3270,26 +792,27 @@ const bamboocss = (options = {}) => {
3270
792
  * Keyed by dependency, since "what changed" is the question asked, and tracked in the other
3271
793
  * direction as well so a re-transform can retract edges the module no longer has.
3272
794
  */
3273
- const dependentsByDependency = /* @__PURE__ */ new Map();
3274
- const dependenciesByFile = /* @__PURE__ */ new Map();
3275
- const recordFoldDependencies = (file, dependencies) => {
3276
- const next = new Set(dependencies.map(normalizeFsPath).filter((dependency) => dependency !== file));
3277
- const previous = dependenciesByFile.get(file);
795
+ const recordFoldDependencies = (state, moduleId, file, dependencies) => {
796
+ const { dependenciesByModule, dependentsByDependency, filesByModule } = state;
797
+ const normalizedFile = normalizeFsPath(file);
798
+ const next = new Set(dependencies.map(normalizeFsPath).filter((dependency) => dependency !== normalizedFile));
799
+ const previous = dependenciesByModule.get(moduleId);
800
+ filesByModule.set(moduleId, file);
3278
801
  for (const dependency of previous ?? []) {
3279
802
  if (next.has(dependency)) continue;
3280
803
  const dependents = dependentsByDependency.get(dependency);
3281
- if (!dependents?.delete(file)) continue;
804
+ if (!dependents?.delete(moduleId)) continue;
3282
805
  if (!dependents.size) dependentsByDependency.delete(dependency);
3283
806
  }
3284
807
  if (!next.size) {
3285
- dependenciesByFile.delete(file);
808
+ dependenciesByModule.delete(moduleId);
3286
809
  return;
3287
810
  }
3288
- dependenciesByFile.set(file, next);
811
+ dependenciesByModule.set(moduleId, next);
3289
812
  for (const dependency of next) {
3290
813
  const dependents = dependentsByDependency.get(dependency);
3291
- if (dependents) dependents.add(file);
3292
- else dependentsByDependency.set(dependency, new Set([file]));
814
+ if (dependents) dependents.add(moduleId);
815
+ else dependentsByDependency.set(dependency, new Set([moduleId]));
3293
816
  }
3294
817
  };
3295
818
  /**
@@ -3303,7 +826,7 @@ const bamboocss = (options = {}) => {
3303
826
  * Digests, not text. Retaining every consumer's source and compiled output for the life of the
3304
827
  * process is the same order of memory as the ts-morph project already holding it; two 44-byte
3305
828
  * strings per entry is not, and it does not grow with module size. The set is bounded the way
3306
- * `dependenciesByFile` is — an entry exists only while a module's fold actually reads another
829
+ * `dependenciesByModule` is — an entry exists only while a module's fold actually reads another
3307
830
  * file, which most modules never do — so a project that folds nothing across a boundary pays
3308
831
  * neither the bytes nor the hashing.
3309
832
  *
@@ -3313,16 +836,343 @@ const bamboocss = (options = {}) => {
3313
836
  * that comparison and is treated as changed. `path` is the spelling `transform` used, because
3314
837
  * ts-morph and the fold both key on it and Windows spells it more than one way.
3315
838
  */
3316
- const foldSignatures = /* @__PURE__ */ new Map();
3317
839
  const digest = (text) => createHash("sha256").update(text).digest("base64");
840
+ /** Fingerprint the generated Bamboo assets after every plugin which may rewrite the bundle. */
841
+ const bambooCssDigest = (bundle) => {
842
+ const assets = [];
843
+ for (const output of Object.values(bundle)) {
844
+ if (!isRecord(output) || output.type !== "asset") continue;
845
+ const { source } = output;
846
+ if (typeof source !== "string" && !(source instanceof Uint8Array)) continue;
847
+ const text = typeof source === "string" ? source : Buffer.from(source).toString();
848
+ if (!text.includes("--made-with-bamboo")) continue;
849
+ assets.push(text);
850
+ }
851
+ if (!assets.length) return void 0;
852
+ return digest(JSON.stringify(assets.sort()));
853
+ };
854
+ /** Add one detached transform contribution to the global reachability projection. */
855
+ const applyStaticTransformContribution = (artifact) => {
856
+ if (artifact.transformedFile) staticSession.transformedFiles.add(resolve(artifact.file));
857
+ for (const className of artifact.classNames) staticSession.markClassUsed(className);
858
+ };
859
+ /**
860
+ * Re-derive the two global sets CSS pruning consumes from environment-owned artifacts.
861
+ *
862
+ * A watch run may rebuild one environment or several at once. The candidate being judged
863
+ * replaces its own previous contribution; every sibling contributes its committed generation,
864
+ * even when a replacement for that sibling is already in flight. Its old JavaScript remains
865
+ * the live output until the replacement succeeds, so pruning against a half-filled candidate
866
+ * would remove rules that output still names.
867
+ */
868
+ const contributionStates = (candidateEnvironment, candidateState) => {
869
+ const states = [];
870
+ const seenEpochs = /* @__PURE__ */ new Set();
871
+ let candidateIncluded = false;
872
+ for (const [environment, slots] of liveOutputSlotsByEnvironment) if (environment === candidateEnvironment && candidateState) {
873
+ states.push(candidateState);
874
+ candidateIncluded = true;
875
+ } else for (const { epoch } of slots.values()) {
876
+ if (seenEpochs.has(epoch.id)) continue;
877
+ seenEpochs.add(epoch.id);
878
+ states.push(epoch.state);
879
+ }
880
+ if (candidateEnvironment && candidateState && !candidateIncluded) states.push(candidateState);
881
+ return states;
882
+ };
883
+ const rebuildStaticTransformContributions = (candidateEnvironment, candidateState) => {
884
+ staticSession.transformedFiles.clear();
885
+ staticSession.usedClasses.clear();
886
+ staticSession.cssLoaded = false;
887
+ for (const state of contributionStates(candidateEnvironment, candidateState)) {
888
+ if (state.cssLoaded) staticSession.cssLoaded = true;
889
+ for (const artifact of state.transformArtifactsByModule.values()) applyStaticTransformContribution(artifact);
890
+ }
891
+ };
892
+ /**
893
+ * Snapshot which reported classes Bamboo actually extracted for this JavaScript generation.
894
+ *
895
+ * Fold artifacts also report literal classes passed through helpers such as `cx('external',
896
+ * css(...))`. Intersecting with the extraction inventory keeps those useful reachability facts
897
+ * without later demanding that Bamboo provide a rule it never owned.
898
+ */
899
+ const ownedClassesForState = (state) => {
900
+ const extracted = new Map([...staticSession.prunableClasses].map((className) => [bare(className), className]));
901
+ const owned = /* @__PURE__ */ new Set();
902
+ for (const artifact of state.transformArtifactsByModule.values()) for (const reported of artifact.classNames) for (const token of reported.split(" ")) {
903
+ if (!token) continue;
904
+ const extractedClass = extracted.get(bare(token));
905
+ if (extractedClass !== void 0) owned.add(extractedClass);
906
+ }
907
+ return owned;
908
+ };
909
+ const createTransformEpoch = (state) => {
910
+ const detachedState = cloneEnvironmentState(state);
911
+ return {
912
+ id: ++nextEpochId,
913
+ state: detachedState,
914
+ ownedClasses: ownedClassesForState(detachedState)
915
+ };
916
+ };
917
+ /** Apply the same candidate-replaces-its-environment rule as the reachability projection. */
918
+ const requiredClassesForProjection = (candidateEnvironment, candidateOwnedClasses) => {
919
+ const required = /* @__PURE__ */ new Set();
920
+ let candidateIncluded = false;
921
+ const seenEpochs = /* @__PURE__ */ new Set();
922
+ for (const [environment, slots] of liveOutputSlotsByEnvironment) {
923
+ if (environment === candidateEnvironment) {
924
+ for (const className of candidateOwnedClasses) required.add(className);
925
+ candidateIncluded = true;
926
+ continue;
927
+ }
928
+ for (const { epoch } of slots.values()) {
929
+ if (seenEpochs.has(epoch.id)) continue;
930
+ seenEpochs.add(epoch.id);
931
+ for (const className of epoch.ownedClasses) required.add(className);
932
+ }
933
+ }
934
+ if (!candidateIncluded) for (const className of candidateOwnedClasses) required.add(className);
935
+ return required;
936
+ };
937
+ const currentRequiredClasses = () => {
938
+ const prunable = new Set([...staticSession.prunableClasses].map(bare));
939
+ return new Set([...staticSession.usedClasses].filter((className) => prunable.has(bare(className))));
940
+ };
941
+ /** Derive loss history from the stylesheet outputs which are still observable. */
942
+ const rebuildLivePrunedClasses = () => {
943
+ staticSession.prunedClasses.clear();
944
+ for (const slots of liveOutputSlotsByEnvironment.values()) for (const slot of slots.values()) for (const className of slot.prunedClasses ?? []) staticSession.prunedClasses.add(className);
945
+ };
946
+ const observeEnvironmentBuildStart = (environment) => {
947
+ const serial = (nextBuildSerialByEnvironment.get(environment) ?? 0) + 1;
948
+ nextBuildSerialByEnvironment.set(environment, serial);
949
+ observedBuildSerialByEnvironment.set(environment, serial);
950
+ };
951
+ /** Open a replacement without discarding the generation a failed rebuild can fall back to. */
952
+ const beginEnvironmentGeneration = (environment) => {
953
+ preparedGenerations.delete(environment);
954
+ const state = newEnvironmentState();
955
+ const observedSerial = observedBuildSerialByEnvironment.get(environment);
956
+ const buildSerial = observedSerial ?? (nextBuildSerialByEnvironment.get(environment) ?? 0) + 1;
957
+ if (observedSerial === void 0) nextBuildSerialByEnvironment.set(environment, buildSerial);
958
+ else observedBuildSerialByEnvironment.delete(environment);
959
+ buildSerialByState.set(state, buildSerial);
960
+ transformStateByEnvironment.set(environment, state);
961
+ staticSession.participatingEnvironments.add(environment);
962
+ if (liveOutputSlotsByEnvironment.get(environment)?.size) staticSession.completedEnvironments.add(environment);
963
+ else staticSession.completedEnvironments.delete(environment);
964
+ rebuildStaticTransformContributions();
965
+ return state;
966
+ };
967
+ /** Collapse an environment to a generation which replaced all of its observable outputs. */
968
+ const completeEnvironmentGeneration = (environment, state) => {
969
+ if (transformStateByEnvironment.get(environment) !== state) return;
970
+ const epoch = createTransformEpoch(state);
971
+ liveOutputSlotsByEnvironment.set(environment, new Map([[DIRECT_OUTPUT_TOKEN, { epoch }]]));
972
+ staticSession.completedEnvironments.add(environment);
973
+ rebuildStaticTransformContributions();
974
+ rebuildLivePrunedClasses();
975
+ };
976
+ const prepareEnvironmentGeneration = (environment, state) => {
977
+ if (transformStateByEnvironment.get(environment) !== state) return;
978
+ preparedGenerations.set(environment, {
979
+ state,
980
+ epoch: createTransformEpoch(state),
981
+ buildSerial: buildSerialByState.get(state) ?? 0,
982
+ outputTokens: new Set(outputTokensByEnvironment.get(environment) ?? []),
983
+ stagedOutputs: /* @__PURE__ */ new Map()
984
+ });
985
+ rebuildStaticTransformContributions();
986
+ };
987
+ const sameTokens = (left, right) => left.size === right.size && [...left].every((token) => right.has(token));
988
+ /** The first configured output is an observable boundary even when its later hooks throw. */
989
+ const beginOutputCycle = (environment, outputSlot) => {
990
+ const previousSlot = lastStartedOutputSlotByEnvironment.get(environment);
991
+ if (outputSlot === 0 || previousSlot !== void 0 && outputSlot <= previousSlot) pendingOutputCycles.delete(environment);
992
+ lastStartedOutputSlotByEnvironment.set(environment, outputSlot);
993
+ };
994
+ const completeOutputCycle = (environment, cycle) => {
995
+ liveOutputSlotsByEnvironment.set(environment, new Map(cycle.candidatesBySlot));
996
+ pendingOutputCycles.delete(environment);
997
+ preparedGenerations.delete(environment);
998
+ staticSession.completedEnvironments.add(environment);
999
+ rebuildStaticTransformContributions();
1000
+ rebuildLivePrunedClasses();
1001
+ };
1002
+ const publishPreparedOutput = (environment, outputToken, outputSlot, wasWritten) => {
1003
+ const generation = preparedGenerations.get(environment);
1004
+ if (!generation || transformStateByEnvironment.get(environment) !== generation.state) return;
1005
+ if (!generation.outputTokens.has(outputToken)) return;
1006
+ const mode = wasWritten ? "write" : "memory";
1007
+ let cycle = pendingOutputCycles.get(environment);
1008
+ const serialContinues = cycle !== void 0 && outputSlot > cycle.lastOutputSlot && (generation.buildSerial === cycle.lastBuildSerial || generation.buildSerial === cycle.lastBuildSerial + (outputSlot - cycle.lastOutputSlot));
1009
+ if (!cycle || cycle.mode !== mode || !sameTokens(cycle.expectedTokens, generation.outputTokens) || cycle.successfulTokens.has(outputToken) || !serialContinues) {
1010
+ cycle = {
1011
+ expectedTokens: new Set(generation.outputTokens),
1012
+ successfulTokens: /* @__PURE__ */ new Set(),
1013
+ candidatesBySlot: /* @__PURE__ */ new Map(),
1014
+ lastBuildSerial: generation.buildSerial,
1015
+ lastOutputSlot: outputSlot,
1016
+ mode
1017
+ };
1018
+ pendingOutputCycles.set(environment, cycle);
1019
+ }
1020
+ const stage = generation.stagedOutputs.get(outputToken);
1021
+ const candidateSlot = {
1022
+ epoch: generation.epoch,
1023
+ ...stage?.prunedClasses ? { prunedClasses: new Set(stage.prunedClasses) } : {}
1024
+ };
1025
+ cycle.successfulTokens.add(outputToken);
1026
+ cycle.candidatesBySlot.set(outputSlot, candidateSlot);
1027
+ cycle.lastBuildSerial = generation.buildSerial;
1028
+ cycle.lastOutputSlot = outputSlot;
1029
+ const allOutputsSucceeded = cycle.successfulTokens.size === cycle.expectedTokens.size;
1030
+ if (wasWritten) {
1031
+ const slots = liveOutputSlotsByEnvironment.get(environment) ?? /* @__PURE__ */ new Map();
1032
+ slots.set(outputSlot, candidateSlot);
1033
+ liveOutputSlotsByEnvironment.set(environment, slots);
1034
+ staticSession.completedEnvironments.add(environment);
1035
+ rebuildStaticTransformContributions();
1036
+ rebuildLivePrunedClasses();
1037
+ }
1038
+ if (!allOutputsSucceeded || !wasWritten) return;
1039
+ completeOutputCycle(environment, cycle);
1040
+ };
1041
+ const closePreparedMemoryOutputs = (environment) => {
1042
+ const cycle = pendingOutputCycles.get(environment);
1043
+ if (!cycle || cycle.mode !== "memory" || cycle.successfulTokens.size !== cycle.expectedTokens.size) return;
1044
+ completeOutputCycle(environment, cycle);
1045
+ };
1046
+ /** Restore the still-live output contribution when the replacement generation fails. */
1047
+ const rollbackEnvironmentGeneration = (environment, state) => {
1048
+ if (transformStateByEnvironment.get(environment) !== state) return;
1049
+ preparedGenerations.delete(environment);
1050
+ pendingOutputCycles.delete(environment);
1051
+ const slots = liveOutputSlotsByEnvironment.get(environment);
1052
+ const liveEpochs = /* @__PURE__ */ new Map();
1053
+ for (const { epoch } of slots?.values() ?? []) liveEpochs.set(epoch.id, epoch);
1054
+ const latestLive = [...liveEpochs.values()].sort((a, b) => a.id - b.id).at(-1);
1055
+ if (latestLive) {
1056
+ transformStateByEnvironment.set(environment, cloneEnvironmentState(latestLive.state));
1057
+ staticSession.completedEnvironments.add(environment);
1058
+ } else {
1059
+ transformStateByEnvironment.delete(environment);
1060
+ staticSession.completedEnvironments.delete(environment);
1061
+ }
1062
+ rebuildStaticTransformContributions();
1063
+ rebuildLivePrunedClasses();
1064
+ };
1065
+ staticSession.beginOutputProjection = (environment, outputOptions, bundle, replacesGeneratedStylesheet) => {
1066
+ const generation = preparedGenerations.get(environment);
1067
+ if (!generation || transformStateByEnvironment.get(environment) !== generation.state) {
1068
+ const currentState = transformStateByEnvironment.get(environment);
1069
+ return {
1070
+ cssLoaded: currentState?.cssLoaded ?? staticSession.cssLoaded,
1071
+ requiredClasses: requiredClassesForProjection(environment, currentState ? ownedClassesForState(currentState) : currentRequiredClasses()),
1072
+ restore() {}
1073
+ };
1074
+ }
1075
+ const committedPrunedClasses = staticSession.prunedClasses;
1076
+ staticSession.prunedClasses = new Set(committedPrunedClasses);
1077
+ rebuildStaticTransformContributions(environment, generation.epoch.state);
1078
+ const requiredClasses = requiredClassesForProjection(environment, generation.epoch.ownedClasses);
1079
+ if (replacesGeneratedStylesheet) staticSession.prunedClasses.clear();
1080
+ let restored = false;
1081
+ return {
1082
+ cssLoaded: generation.epoch.state.cssLoaded,
1083
+ requiredClasses,
1084
+ restore() {
1085
+ if (restored) return;
1086
+ restored = true;
1087
+ const stage = replacesGeneratedStylesheet ? {
1088
+ cssDigest: bambooCssDigest(bundle),
1089
+ prunedClasses: new Set(staticSession.prunedClasses)
1090
+ } : {};
1091
+ outputStageByBundle.set(bundle, stage);
1092
+ outputStageByOptions.set(outputOptions, stage);
1093
+ staticSession.prunedClasses = committedPrunedClasses;
1094
+ rebuildStaticTransformContributions();
1095
+ }
1096
+ };
1097
+ };
1098
+ /** Aggregate environment-owned coverage once the participating generation is complete. */
1099
+ const reportTransformCoverage = (states) => {
1100
+ const perFile = /* @__PURE__ */ new Map();
1101
+ const reportedCoverageByModule = /* @__PURE__ */ new Map();
1102
+ for (const state of states) for (const artifact of state.transformArtifactsByModule.values()) {
1103
+ const coverageKey = JSON.stringify([
1104
+ artifact.file,
1105
+ artifact.folded,
1106
+ artifact.skipped
1107
+ ]);
1108
+ const reported = reportedCoverageByModule.get(artifact.moduleId);
1109
+ if (reported?.has(coverageKey)) continue;
1110
+ if (reported) reported.add(coverageKey);
1111
+ else reportedCoverageByModule.set(artifact.moduleId, new Set([coverageKey]));
1112
+ const entry = perFile.get(artifact.file) ?? {
1113
+ folded: 0,
1114
+ skipped: /* @__PURE__ */ new Map()
1115
+ };
1116
+ entry.folded += artifact.folded;
1117
+ for (const [reason, count] of artifact.skipped) entry.skipped.set(reason, (entry.skipped.get(reason) ?? 0) + count);
1118
+ perFile.set(artifact.file, entry);
1119
+ }
1120
+ let folded = 0;
1121
+ let filesWithFolds = 0;
1122
+ const skipped = /* @__PURE__ */ new Map();
1123
+ for (const entry of perFile.values()) {
1124
+ folded += entry.folded;
1125
+ if (entry.folded) filesWithFolds++;
1126
+ for (const [reason, count] of entry.skipped) skipped.set(reason, (skipped.get(reason) ?? 0) + count);
1127
+ }
1128
+ const declined = Array.from(skipped.values()).reduce((sum, count) => sum + count, 0);
1129
+ const total = folded + declined;
1130
+ if (!total) return;
1131
+ const share = Math.round(folded / total * 100);
1132
+ const reasons = Array.from(skipped.entries()).sort((a, b) => b[1] - a[1]).map(([reason, count]) => `${reason}=${count}`).join(" ");
1133
+ logger.info("vite:transform", `Compiled ${folded}/${total} (${share}%) across ${filesWithFolds}/${perFile.size} files` + (reasons ? ` — declined: ${reasons}` : ""));
1134
+ };
1135
+ /** Restore every per-build fact established by one successful transform. */
1136
+ const applyTransformArtifact = (state, value, expectedModuleId, environment) => {
1137
+ let snapshot;
1138
+ try {
1139
+ snapshot = structuredClone(value);
1140
+ } catch {
1141
+ throw cachedArtifactError(expectedModuleId, environment, void 0, `could not be snapshotted as serializable schema version ${TRANSFORM_ARTIFACT_VERSION} data`);
1142
+ }
1143
+ if (!isTransformArtifact(snapshot) || snapshot.moduleId !== expectedModuleId || snapshot.file !== expectedModuleId.split("?")[0] || !hasValidTransformArtifactIntegrity(environment, snapshot)) throw cachedArtifactError(expectedModuleId, environment, snapshot);
1144
+ const artifact = snapshot;
1145
+ const { file, moduleId } = artifact;
1146
+ state.transformArtifactsByModule.set(moduleId, artifact);
1147
+ recordFoldDependencies(state, moduleId, file, artifact.dependencies);
1148
+ if (artifact.signature) state.foldSignatures.set(moduleId, artifact.signature);
1149
+ else state.foldSignatures.delete(moduleId);
1150
+ };
3318
1151
  /**
3319
- * Consumers this edit cannot move, resolved once per watcher event.
1152
+ * Replay transform metadata for modules Rollup reused from its cache.
1153
+ *
1154
+ * `buildStart` has to clear reachability because a watch rebuild may have a different graph,
1155
+ * but Rollup does not call `transform` again for an unchanged module. The transform result is
1156
+ * still present on that module as serializable metadata, and `buildEnd` is the common Rollup
1157
+ * and Rolldown point where the complete graph can be enumerated while CSS generation is still
1158
+ * ahead of us. Replaying here restores the exact state pruning and the finished-build guards
1159
+ * would have observed after a clean build.
3320
1160
  *
3321
- * `hotUpdate` runs once per environment client and ssr both and the answer is a property
3322
- * of the files, not of which environment is asking. Cleared in `watchChange`, which every Vite
3323
- * in the peer range calls for every file event, before either update hook.
1161
+ * Freshly transformed module IDs are skipped inside this environment only. Besides avoiding
1162
+ * duplicate work, that makes a failed transform authoritative: an older cached artifact must
1163
+ * not overwrite the diagnostic and signature retraction established by the failing pass.
3324
1164
  */
3325
- const unchangedFolds = /* @__PURE__ */ new Map();
1165
+ const replayCachedTransformArtifacts = (pluginContext) => {
1166
+ if (!pluginContext.getModuleIds || !pluginContext.getModuleInfo) return;
1167
+ const state = environmentState(pluginContext);
1168
+ for (const id of pluginContext.getModuleIds()) {
1169
+ if (state.transformedModulesThisRun.has(id)) continue;
1170
+ const meta = pluginContext.getModuleInfo(id)?.meta;
1171
+ if (!meta || !Object.prototype.hasOwnProperty.call(meta, TRANSFORM_META_KEY)) continue;
1172
+ const artifact = meta[TRANSFORM_META_KEY];
1173
+ applyTransformArtifact(state, artifact, id, environmentName(pluginContext));
1174
+ }
1175
+ };
3326
1176
  /**
3327
1177
  * How many dependents in a row may come back changed before the check gives up for this event.
3328
1178
  *
@@ -3349,7 +1199,6 @@ const bamboocss = (options = {}) => {
3349
1199
  * run to reach eight, the consumers seen so far have to be uniformly changed.
3350
1200
  */
3351
1201
  const CHANGED_RUN_LIMIT = 8;
3352
- let changedRun = 0;
3353
1202
  /**
3354
1203
  * Whether re-folding `dependent` now produces exactly the bytes it produced last time.
3355
1204
  *
@@ -3364,24 +1213,24 @@ const bamboocss = (options = {}) => {
3364
1213
  * that returns nothing, a fold that throws — because "changed" is what this path did before,
3365
1214
  * and a wrong "unchanged" is a stale class string in the browser.
3366
1215
  */
3367
- const foldOutputUnchanged = (dependent) => {
3368
- const memoized = unchangedFolds.get(dependent);
1216
+ const foldOutputUnchanged = (state, dependent) => {
1217
+ const memoized = state.unchangedFolds.get(dependent);
3369
1218
  if (memoized !== void 0) return memoized;
3370
- const unchanged = changedRun < CHANGED_RUN_LIMIT && refoldMatchesSignature(dependent);
3371
- changedRun = unchanged ? 0 : changedRun + 1;
3372
- unchangedFolds.set(dependent, unchanged);
1219
+ const unchanged = state.changedRun < CHANGED_RUN_LIMIT && refoldMatchesSignature(state, dependent);
1220
+ state.changedRun = unchanged ? 0 : state.changedRun + 1;
1221
+ state.unchangedFolds.set(dependent, unchanged);
3373
1222
  return unchanged;
3374
1223
  };
3375
- const refoldMatchesSignature = (dependent) => {
3376
- const signature = foldSignatures.get(dependent);
3377
- if (!signature || !ctx || !runtimeCss || !styleCompiler) return false;
1224
+ const refoldMatchesSignature = (state, dependent) => {
1225
+ const signature = state.foldSignatures.get(dependent);
1226
+ if (!signature || !ctx || !foldSourceImpl || !runtimeCss || !styleCompiler) return false;
3378
1227
  try {
3379
1228
  const code = readFileSync(signature.path, "utf8");
3380
1229
  if (digest(code) !== signature.input) return false;
3381
1230
  const sourceFile = ctx.project.addSourceFile(signature.path, code);
3382
1231
  const parserResult = ctx.project.parseSourceFile(signature.path);
3383
1232
  if (!parserResult) return false;
3384
- const result = foldSource({
1233
+ const result = withResolutionClosure(signature.path, foldSourceImpl({
3385
1234
  ctx,
3386
1235
  code,
3387
1236
  parserResult,
@@ -3390,38 +1239,29 @@ const bamboocss = (options = {}) => {
3390
1239
  styleCompiler,
3391
1240
  maxRecipeStates,
3392
1241
  parseModule: (path) => ctx?.project.parseSourceFile(path),
3393
- recipeConfigCache,
1242
+ recipeConfigCache: state.recipeConfigCache,
3394
1243
  reportSurvivors: false,
3395
1244
  sourceFile
3396
- });
1245
+ }), parserResult.getDependencies(), state.dependenciesByModule.get(dependent));
3397
1246
  const unchanged = digest(result.code) === signature.output;
3398
1247
  /**
3399
- * Edges re-recorded on the way to suppressing a module, and never on the way to
3400
- * invalidating one.
1248
+ * Edges re-recorded exactly on the way to suppressing a module. A changed provisional
1249
+ * fold may add newly observed edges, but never retracts the last recoverable ones.
3401
1250
  *
3402
1251
  * The first is necessary: *which* files a module folds from can move while the bytes it
3403
1252
  * emits do not — a value now re-exported through a different module, say — and suppressing
3404
1253
  * the announcement means no transform will run to notice. Leaving the old edges would make
3405
1254
  * the next edit to the new dependency reach nobody.
3406
1255
  *
3407
- * The second would be a bug, and is the reason this is a branch rather than an
3408
- * unconditional write. `hotUpdate` runs once per environment, client then ssr, against one
3409
- * shared map. A fold that now yields nothing an export renamed, a call commented out, any
3410
- * ordinary mid-edit state returns `dependencies: []`, so writing it here would retract the
3411
- * consumer's edge during the *client* pass and leave the *ssr* pass finding an empty set and
3412
- * returning without invalidating anything: the stale compiled class kept in the SSR cache,
3413
- * with the client half correctly updated. That is the shape of the bug the self-accepting
3414
- * fix was about, one environment over. `transform` performs the same retraction, but only
3415
- * after every environment has already invalidated, which is why it is safe there.
3416
- *
3417
- * Confining the write to the unchanged branch removes the hazard rather than sequencing
3418
- * around it, because a retraction cannot reach that branch: `dependencies` is empty only
3419
- * when `folded.length === 0`, and a fold that folds nothing returns the module's own source,
3420
- * which cannot equal an output digest recorded from a pass that replaced a call with a
3421
- * literal. And where an unchanged verdict *does* narrow the edges, both passes agree anyway
3422
- * — neither invalidates a module it has just called unchanged.
1256
+ * A changed result is only a provisional check on the way to a real transform. Its reads
1257
+ * can warm the extractor cache, so the authoritative parse may not cross every nested
1258
+ * module again; retaining the union gives that transform semantic targets to validate
1259
+ * against the current Project ledger. It then records the exact answer. If that pass
1260
+ * throws, the additive update has kept every old edge while also making a fix in a newly
1261
+ * observed dependency able to retry it.
3423
1262
  */
3424
- if (unchanged) recordFoldDependencies(dependent, result.dependencies);
1263
+ if (unchanged) recordFoldDependencies(state, dependent, signature.path, result.dependencies);
1264
+ else recordFoldDependencies(state, dependent, signature.path, [...state.dependenciesByModule.get(dependent) ?? [], ...result.dependencies]);
3425
1265
  return unchanged;
3426
1266
  } catch {
3427
1267
  return false;
@@ -3458,8 +1298,8 @@ const bamboocss = (options = {}) => {
3458
1298
  * one can end in a page reload, which is the honest outcome: its compiled classes really did
3459
1299
  * change, and a reload is what Vite does with any update nothing accepts.
3460
1300
  */
3461
- const foldDependentModules = (file, modules, graph) => {
3462
- const dependents = dependentsByDependency.get(normalizeFsPath(file));
1301
+ const foldDependentModules = (state, file, modules, graph) => {
1302
+ const dependents = state.dependentsByDependency.get(normalizeFsPath(file));
3463
1303
  if (!dependents?.size) return;
3464
1304
  const added = [];
3465
1305
  for (const dependent of [...dependents]) {
@@ -3496,8 +1336,11 @@ const bamboocss = (options = {}) => {
3496
1336
  * the edited module for a runtime value is still reached by `propagateUpdate` exactly as
3497
1337
  * it would be with no plugin here at all — that direction was never this list's to decide.
3498
1338
  */
3499
- if (foldOutputUnchanged(dependent)) continue;
3500
- for (const module of graph.getModulesByFile(dependent) ?? []) {
1339
+ if (foldOutputUnchanged(state, dependent)) continue;
1340
+ const exact = graph.getModuleById?.(dependent);
1341
+ const dependentFile = state.filesByModule.get(dependent) ?? dependent;
1342
+ const candidates = exact ? [exact] : graph.getModulesByFile(normalizeFsPath(dependentFile)) ?? [];
1343
+ for (const module of candidates) {
3501
1344
  if (modules.includes(module) || added.includes(module)) continue;
3502
1345
  graph.invalidateModule(module);
3503
1346
  added.push(module);
@@ -3526,52 +1369,189 @@ const bamboocss = (options = {}) => {
3526
1369
  return [...modules, ...added];
3527
1370
  };
3528
1371
  let ctx;
1372
+ let foldSourceImpl;
3529
1373
  let runtimeCss;
3530
1374
  let styleCompiler;
3531
1375
  let command = "build";
3532
- let setup;
3533
- const ensureContext = async () => {
3534
- if (!setup) setup = loadConfigAndCreateContext({
1376
+ let defaultEmitAssets = true;
1377
+ /**
1378
+ * Expand semantic leaf reads through the Project's exact resolution paths.
1379
+ *
1380
+ * Most boxed values point at their final declaration, which the fold reports directly. An
1381
+ * evaluated imported helper is different: its returned box belongs to the local call node,
1382
+ * while ParserResult records the modules crossed during that evaluation. Seed from both so
1383
+ * neither form can leave compiled JavaScript stale. A re-export or barrel on either path can
1384
+ * change which declaration the same import selects and must be watched too. Supplying only
1385
+ * these semantic leaves back to Project keeps unrelated runtime-import branches out and walks
1386
+ * only the indexed closure rather than scanning the global ledger.
1387
+ */
1388
+ const withResolutionClosure = (filePath, result, parserDependencies = [], previousDependencies = void 0) => {
1389
+ if (!ctx || !result.folded.length) return result;
1390
+ const dependencies = new Set(result.dependencies);
1391
+ for (const dependency of parserDependencies) if (!isGeneratedOutput(dependency, ctx)) dependencies.add(dependency);
1392
+ const targets = new Set(dependencies);
1393
+ for (const dependency of previousDependencies ?? []) targets.add(dependency);
1394
+ if (!targets.size) return result;
1395
+ for (const dependency of ctx.project.getDependencies(filePath, [...targets])) if (!isGeneratedOutput(dependency, ctx)) dependencies.add(dependency);
1396
+ const expanded = [...dependencies];
1397
+ if (expanded.length === result.dependencies.length && expanded.every((dependency, index) => dependency === result.dependencies[index])) return result;
1398
+ return {
1399
+ ...result,
1400
+ dependencies: expanded
1401
+ };
1402
+ };
1403
+ const loadContext = createRetryableLazy(async () => {
1404
+ const { loadConfigAndCreateContext } = await loadNodeModule();
1405
+ return loadConfigAndCreateContext({
3535
1406
  configPath,
3536
1407
  cwd,
3537
1408
  dev: command === "serve"
3538
- }).then((loaded) => {
3539
- ctx = loaded;
3540
- runtimeCss = createRuntimeCss(loaded);
3541
- styleCompiler = createStaticStyleSetCompiler(loaded, runtimeCss);
3542
1409
  });
3543
- await setup;
1410
+ });
1411
+ const loadCompilerState = createLazyCompilerState(loadContext, loadFoldModule);
1412
+ const ensureContext = async () => {
1413
+ ctx = await loadContext();
3544
1414
  };
3545
- return [bamboocssCss({
3546
- configPath,
3547
- cwd,
3548
- session: staticSession,
3549
- pruneCss
3550
- }), {
1415
+ const ensureCompilerState = async () => {
1416
+ const loaded = await loadCompilerState();
1417
+ ctx = loaded.context;
1418
+ foldSourceImpl = loaded.foldSource;
1419
+ runtimeCss = loaded.runtimeCss;
1420
+ styleCompiler = loaded.styleCompiler;
1421
+ };
1422
+ const outputFinalizerTag = (value) => {
1423
+ if (!value || typeof value !== "object") return void 0;
1424
+ return value[OUTPUT_FINALIZER];
1425
+ };
1426
+ const outputStartMarkerTag = (value) => {
1427
+ if (!value || typeof value !== "object") return void 0;
1428
+ return value[OUTPUT_START_MARKER];
1429
+ };
1430
+ const findOutputFinalizer = (value, environment, outputSlot) => {
1431
+ if (Array.isArray(value)) {
1432
+ for (const entry of value) {
1433
+ const found = findOutputFinalizer(entry, environment, outputSlot);
1434
+ if (found) return found;
1435
+ }
1436
+ return;
1437
+ }
1438
+ const identity = outputFinalizerTag(value);
1439
+ return identity?.environment === environment && identity.outputSlot === outputSlot ? value : void 0;
1440
+ };
1441
+ const findOutputStartMarker = (value, environment, outputSlot) => {
1442
+ if (Array.isArray(value)) {
1443
+ for (const entry of value) {
1444
+ const found = findOutputStartMarker(entry, environment, outputSlot);
1445
+ if (found) return found;
1446
+ }
1447
+ return;
1448
+ }
1449
+ const identity = outputStartMarkerTag(value);
1450
+ return identity?.environment === environment && identity.outputSlot === outputSlot ? value : void 0;
1451
+ };
1452
+ const stripOutputLifecyclePlugins = (value) => {
1453
+ if (Array.isArray(value)) return value.flatMap(stripOutputLifecyclePlugins);
1454
+ return value == null || outputFinalizerTag(value) || outputStartMarkerTag(value) ? [] : [value];
1455
+ };
1456
+ const createOutputStartMarker = (environment, outputSlot) => {
1457
+ return Object.assign({
1458
+ name: `bamboocss:output-start:${environment}:${outputSlot}`,
1459
+ renderStart: {
1460
+ order: "pre",
1461
+ sequential: true,
1462
+ handler() {
1463
+ beginOutputCycle(environment, outputSlot);
1464
+ }
1465
+ }
1466
+ }, { [OUTPUT_START_MARKER]: {
1467
+ environment,
1468
+ outputSlot
1469
+ } });
1470
+ };
1471
+ const createOutputFinalizer = (environment, outputSlot) => {
1472
+ const outputToken = ++nextOutputToken;
1473
+ return Object.assign({
1474
+ name: `bamboocss:output-finalizer:${environment}:${outputSlot}`,
1475
+ generateBundle: {
1476
+ order: "post",
1477
+ handler(outputOptions, bundle, isWrite) {
1478
+ if (!bundle || typeof bundle !== "object") return;
1479
+ const identity = {
1480
+ environment,
1481
+ outputSlot,
1482
+ outputToken
1483
+ };
1484
+ outputIdentityByBundle.set(bundle, identity);
1485
+ if (outputOptions && typeof outputOptions === "object") outputIdentityByOptions.set(outputOptions, identity);
1486
+ const generation = preparedGenerations.get(environment);
1487
+ const stage = outputStageByBundle.get(bundle) ?? (outputOptions && typeof outputOptions === "object" ? outputStageByOptions.get(outputOptions) : void 0);
1488
+ if (stage?.cssDigest && bambooCssDigest(bundle) !== stage.cssDigest) throw new Error("bamboocss: an output plugin changed or removed the generated stylesheet after Bamboo finalized its reachability. The cached prune history would no longer describe the emitted CSS. Preserve the Bamboo asset in later `generateBundle` hooks, or run that transformation before Bamboo.");
1489
+ if (generation && stage) generation.stagedOutputs.set(outputToken, stage);
1490
+ if (!isWrite) publishPreparedOutput(environment, outputToken, outputSlot, false);
1491
+ }
1492
+ }
1493
+ }, { [OUTPUT_FINALIZER]: {
1494
+ environment,
1495
+ outputSlot,
1496
+ outputToken
1497
+ } });
1498
+ };
1499
+ const installOutputFinalizers = (inputOptions, environment) => {
1500
+ if (!inputOptions.output) {
1501
+ outputTokensByEnvironment.delete(environment);
1502
+ return;
1503
+ }
1504
+ const outputs = Array.isArray(inputOptions.output) ? inputOptions.output : [inputOptions.output];
1505
+ const outputTokens = /* @__PURE__ */ new Set();
1506
+ const installed = outputs.map((output, outputSlot) => {
1507
+ const existing = findOutputFinalizer(output.plugins, environment, outputSlot);
1508
+ const existingStart = findOutputStartMarker(output.plugins, environment, outputSlot);
1509
+ if (existing && existingStart) {
1510
+ outputTokens.add(existing[OUTPUT_FINALIZER].outputToken);
1511
+ return output;
1512
+ }
1513
+ const finalizer = existing ?? createOutputFinalizer(environment, outputSlot);
1514
+ const startMarker = existingStart ?? createOutputStartMarker(environment, outputSlot);
1515
+ outputTokens.add(finalizer[OUTPUT_FINALIZER].outputToken);
1516
+ output.plugins = [
1517
+ startMarker,
1518
+ ...stripOutputLifecyclePlugins(output.plugins),
1519
+ finalizer
1520
+ ];
1521
+ return output;
1522
+ });
1523
+ inputOptions.output = Array.isArray(inputOptions.output) ? installed : installed[0];
1524
+ outputTokensByEnvironment.set(environment, outputTokens);
1525
+ };
1526
+ const compiler = {
3551
1527
  name: "bamboocss:compiler",
3552
1528
  enforce: "pre",
3553
1529
  /** See the same declaration on the css plugin: one instance per build, not per environment. */
3554
1530
  sharedDuringBuild: true,
1531
+ options(inputOptions) {
1532
+ installOutputFinalizers(inputOptions, environmentName(this));
1533
+ return inputOptions;
1534
+ },
3555
1535
  configResolved(config) {
3556
1536
  command = config.command;
1537
+ defaultEmitAssets = config.build?.emitAssets ?? (!config.build?.ssr || config.build?.ssrEmitAssets === true);
1538
+ const plugins = config.plugins;
1539
+ if (plugins) {
1540
+ for (const finalizer of [outputWriteObserver, memoryOutputCommitter]) {
1541
+ const index = plugins.indexOf(finalizer);
1542
+ if (index !== -1) plugins.splice(index, 1);
1543
+ }
1544
+ plugins.unshift(outputWriteObserver);
1545
+ plugins.push(memoryOutputCommitter);
1546
+ }
3557
1547
  },
3558
1548
  async buildStart() {
3559
- const environment = this.environment?.name ?? "default";
3560
- if (staticSession.startedEnvironments.has(environment)) {
3561
- perFile.clear();
3562
- survivorsByFile.clear();
3563
- recipeConfigCache.clear();
3564
- dependentsByDependency.clear();
3565
- dependenciesByFile.clear();
3566
- foldSignatures.clear();
3567
- unchangedFolds.clear();
3568
- changedRun = 0;
3569
- resetStaticCompilationSession(staticSession);
3570
- }
3571
- staticSession.startedEnvironments.add(environment);
1549
+ const environment = environmentName(this);
1550
+ const state = beginEnvironmentGeneration(environment);
3572
1551
  try {
3573
1552
  await ensureContext();
3574
1553
  } catch (error) {
1554
+ rollbackEnvironmentGeneration(environment, state);
3575
1555
  throw asError(error, "failed to load the bamboo config");
3576
1556
  }
3577
1557
  },
@@ -3596,17 +1576,25 @@ const bamboocss = (options = {}) => {
3596
1576
  * the parser still holds the file.
3597
1577
  */
3598
1578
  watchChange(id, change) {
3599
- unchangedFolds.clear();
3600
- changedRun = 0;
1579
+ for (const state of transformStateByEnvironment.values()) {
1580
+ state.unchangedFolds.clear();
1581
+ state.changedRun = 0;
1582
+ }
3601
1583
  if (!ctx) return;
3602
1584
  if (!shouldTransform(id)) return;
3603
1585
  const [filePath] = id.split("?");
3604
1586
  if (!filePath) return;
3605
- recipeConfigCache.clear();
1587
+ for (const state of transformStateByEnvironment.values()) state.recipeConfigCache.clear();
3606
1588
  if (change.event === "delete") {
3607
1589
  ctx.project.removeSourceFile(filePath);
3608
- recordFoldDependencies(normalizeFsPath(filePath), []);
3609
- foldSignatures.delete(normalizeFsPath(filePath));
1590
+ const deleted = normalizeFsPath(filePath);
1591
+ for (const state of transformStateByEnvironment.values()) for (const [moduleId, moduleFile] of [...state.filesByModule]) {
1592
+ if (normalizeFsPath(moduleFile) !== deleted) continue;
1593
+ recordFoldDependencies(state, moduleId, moduleFile, []);
1594
+ state.foldSignatures.delete(moduleId);
1595
+ state.transformArtifactsByModule.delete(moduleId);
1596
+ state.filesByModule.delete(moduleId);
1597
+ }
3610
1598
  return;
3611
1599
  }
3612
1600
  ctx.project.reloadSourceFile(filePath);
@@ -3633,30 +1621,39 @@ const bamboocss = (options = {}) => {
3633
1621
  hotUpdate({ file, modules }) {
3634
1622
  const graph = this.environment?.moduleGraph;
3635
1623
  if (!graph) return;
3636
- return foldDependentModules(file, modules, graph);
1624
+ return foldDependentModules(environmentState(this), file, modules, graph);
3637
1625
  },
3638
1626
  handleHotUpdate({ file, modules, server }) {
3639
1627
  const legacy = server;
3640
1628
  if (legacy.environments) return;
3641
- return foldDependentModules(file, modules, legacy.moduleGraph);
1629
+ return foldDependentModules(environmentState(this), file, modules, legacy.moduleGraph);
3642
1630
  },
3643
1631
  async transform(code, id) {
3644
1632
  if (!shouldTransform(id)) return null;
3645
1633
  try {
3646
- await ensureContext();
1634
+ await ensureCompilerState();
3647
1635
  } catch (error) {
3648
- throw asError(error, "failed to load the bamboo config");
1636
+ throw asError(error, "failed to initialize the bamboo compiler");
3649
1637
  }
3650
- if (!ctx || !runtimeCss || !styleCompiler) return null;
1638
+ if (!ctx || !foldSourceImpl || !runtimeCss || !styleCompiler) return null;
3651
1639
  const [filePath] = id.split("?");
3652
- clearSurvivorsFor(filePath);
3653
1640
  if (isGeneratedOutput(filePath, ctx)) return null;
1641
+ const state = environmentState(this);
1642
+ state.transformedModulesThisRun.add(id);
1643
+ let inputDigest;
1644
+ const previousSignature = state.foldSignatures.get(id);
1645
+ const previousDependencies = previousSignature && previousSignature.input === (inputDigest ??= digest(code)) ? state.dependenciesByModule.get(id) : void 0;
3654
1646
  let result;
3655
1647
  try {
3656
1648
  const sourceFile = ctx.project.addSourceFile(filePath, code);
3657
1649
  const parserResult = ctx.project.parseSourceFile(filePath);
3658
- if (!parserResult) return null;
3659
- result = foldSource({
1650
+ if (!parserResult) {
1651
+ state.transformArtifactsByModule.delete(id);
1652
+ recordFoldDependencies(state, id, filePath, []);
1653
+ state.foldSignatures.delete(id);
1654
+ return null;
1655
+ }
1656
+ result = withResolutionClosure(filePath, foldSourceImpl({
3660
1657
  ctx,
3661
1658
  code,
3662
1659
  parserResult,
@@ -3665,106 +1662,167 @@ const bamboocss = (options = {}) => {
3665
1662
  styleCompiler,
3666
1663
  maxRecipeStates,
3667
1664
  parseModule: (path) => ctx?.project.parseSourceFile(path),
3668
- recipeConfigCache,
1665
+ recipeConfigCache: state.recipeConfigCache,
3669
1666
  reportSurvivors: true,
3670
1667
  sourceFile
3671
- });
1668
+ }), parserResult.getDependencies(), previousDependencies);
3672
1669
  } catch (error) {
3673
1670
  logger.caughtError("vite:transform", `Failed to compile ${filePath}`, error);
3674
- perFile.set(filePath, {
3675
- folded: 0,
3676
- skipped: new Map([["compile-failed", 1]])
3677
- });
3678
- foldSignatures.delete(normalizeFsPath(filePath));
3679
- addSurvivor({
1671
+ const previousDependencies = [...state.dependenciesByModule.get(id) ?? []];
1672
+ applyTransformArtifact(state, sealTransformArtifact(environmentName(this), {
1673
+ version: TRANSFORM_ARTIFACT_VERSION,
1674
+ moduleId: id,
3680
1675
  file: filePath,
3681
- line: 1,
3682
- name: "compiler",
3683
- reason: "compile-failed"
3684
- });
1676
+ folded: 0,
1677
+ skipped: [["compile-failed", 1]],
1678
+ survivors: [{
1679
+ line: 1,
1680
+ name: "compiler",
1681
+ reason: "compile-failed"
1682
+ }],
1683
+ transformedFile: false,
1684
+ classNames: [],
1685
+ dependencies: previousDependencies
1686
+ }), id, environmentName(this));
1687
+ state.foldSignatures.delete(id);
3685
1688
  if (command === "serve") throw asError(error, `failed to compile ${filePath}`);
3686
1689
  return null;
3687
1690
  }
3688
- let skippedHere;
3689
- for (const entry of result.skipped) {
3690
- skippedHere ??= /* @__PURE__ */ new Map();
3691
- skippedHere.set(entry.reason, (skippedHere.get(entry.reason) ?? 0) + 1);
3692
- }
3693
- perFile.set(filePath, {
3694
- folded: result.folded.length,
3695
- skipped: skippedHere
3696
- });
3697
- if (result.folded.some((entry) => entry.kind === "class" || entry.kind === "slots")) staticSession.transformedFiles.add(resolve(filePath));
3698
- for (const entry of result.folded) for (const className of entry.classNames) staticSession.markClassUsed(className);
1691
+ const skippedHere = /* @__PURE__ */ new Map();
1692
+ for (const entry of result.skipped) skippedHere.set(entry.reason, (skippedHere.get(entry.reason) ?? 0) + 1);
1693
+ const survivorsHere = [];
3699
1694
  for (const entry of result.skipped) {
3700
1695
  if (entry.reason === "not-imported" || entry.reason === "overlapping") continue;
3701
1696
  if (entry.name === "cx" && entry.reason === "dynamic") continue;
3702
- addSurvivor({
3703
- file: filePath,
1697
+ survivorsHere.push({
3704
1698
  line: lineAt(code, entry.start),
3705
1699
  name: entry.name,
3706
1700
  reason: entry.reason
3707
1701
  });
3708
1702
  }
1703
+ const artifact = sealTransformArtifact(environmentName(this), {
1704
+ version: TRANSFORM_ARTIFACT_VERSION,
1705
+ moduleId: id,
1706
+ file: filePath,
1707
+ folded: result.folded.length,
1708
+ skipped: [...skippedHere],
1709
+ survivors: survivorsHere,
1710
+ transformedFile: result.folded.some((entry) => entry.kind === "class" || entry.kind === "slots"),
1711
+ classNames: [...new Set(result.folded.flatMap((entry) => entry.classNames))],
1712
+ dependencies: [...result.dependencies],
1713
+ ...result.dependencies.length ? { signature: {
1714
+ input: inputDigest ??= digest(code),
1715
+ output: digest(result.code),
1716
+ path: filePath
1717
+ } } : {}
1718
+ });
1719
+ applyTransformArtifact(state, artifact, id, environmentName(this));
3709
1720
  if (reportSkipped && result.skipped.length) logger.info("vite:transform", formatSkipped(filePath, result.skipped));
3710
1721
  for (const dependency of result.dependencies) this.addWatchFile?.(dependency);
3711
- const dependentKey = normalizeFsPath(filePath);
3712
- recordFoldDependencies(dependentKey, result.dependencies);
3713
- if (result.dependencies.length) foldSignatures.set(dependentKey, {
3714
- input: digest(code),
3715
- output: digest(result.code),
3716
- path: filePath
3717
- });
3718
- else foldSignatures.delete(dependentKey);
3719
- const forFile = survivorsByFile.get(filePath);
3720
- if (command === "serve" && forFile?.length) {
3721
- foldSignatures.delete(dependentKey);
3722
- throw createSurvivorError(forFile);
1722
+ if (command === "serve" && artifact.survivors.length) {
1723
+ state.foldSignatures.delete(id);
1724
+ throw createSurvivorError(artifact.survivors.map((survivor) => ({
1725
+ file: filePath,
1726
+ ...survivor
1727
+ })));
3723
1728
  }
3724
- if (!result.folded.length) return null;
1729
+ const meta = { [TRANSFORM_META_KEY]: artifact };
1730
+ if (!result.folded.length) return typeof this.getModuleInfo === "function" ? {
1731
+ code,
1732
+ map: null,
1733
+ meta
1734
+ } : null;
3725
1735
  logger.debug("vite:transform", `Compiled ${result.folded.length} call(s) in ${filePath}`);
3726
1736
  return {
3727
1737
  code: result.code,
3728
- map: result.map
1738
+ map: result.map,
1739
+ meta
3729
1740
  };
3730
1741
  },
3731
- buildEnd() {
3732
- const survivors = allSurvivors();
3733
- if (survivors.length) throw createSurvivorError(survivors);
3734
- const lost = [...staticSession.usedClasses].filter((className) => staticSession.prunedClasses.has(bare(className)));
3735
- if (lost.length) {
3736
- const environment = this.environment?.name ?? "default";
3737
- throw new Error(`bamboocss: ${lost.length} class(es) compiled in the ${JSON.stringify(environment)} environment were already pruned out of a stylesheet emitted by an earlier one. Elements carrying them would render unstyled.\n\n${truncateList(lost.map((className) => ` ${className}`), {
1742
+ buildEnd(buildError) {
1743
+ const environment = environmentName(this);
1744
+ const state = environmentState(this);
1745
+ if (buildError) {
1746
+ rollbackEnvironmentGeneration(environment, state);
1747
+ return;
1748
+ }
1749
+ try {
1750
+ replayCachedTransformArtifacts(this);
1751
+ let currentWillEmitCss = false;
1752
+ if (typeof this.getModuleIds === "function") {
1753
+ state.cssLoaded = [...this.getModuleIds()].some((id) => id.split("?")[0] === `\0${VIRTUAL_CSS_ID}`);
1754
+ currentWillEmitCss = state.cssLoaded && (this.environment?.config?.build?.emitAssets ?? defaultEmitAssets);
1755
+ }
1756
+ const states = contributionStates(environment, state);
1757
+ rebuildStaticTransformContributions(environment, state);
1758
+ const survivors = allSurvivors(states);
1759
+ if (survivors.length) throw createSurvivorError(survivors);
1760
+ const lost = currentWillEmitCss ? [] : [...staticSession.usedClasses].filter((className) => staticSession.prunedClasses.has(bare(className)));
1761
+ if (lost.length) throw new Error(`bamboocss: ${lost.length} class(es) compiled in the ${JSON.stringify(environment)} environment were already pruned out of a stylesheet emitted by an earlier one. Elements carrying them would render unstyled.\n\n${truncateList(lost.map((className) => ` ${className}`), {
3738
1762
  unit: "class",
3739
1763
  separator: "\n"
3740
- })}\n\nThe stylesheet is finalized by the environment that imports it, so pruning it is only safe once every environment has been compiled. This build did not say how many there would be: it called \`builder.build(environment)\` directly. Run it through \`vite build\`, call \`builder.buildApp()\`, or set \`builder: {}\` in the Vite config so the environments are known before the first one builds. \`bamboocss({ pruneCss: false })\` also turns pruning off entirely.`);
1764
+ })}\n\nThe stylesheet is finalized by the environment that imports it — the client, which builds first — so it is pruned against what that environment compiled. These classes are reached only from here, so no rule for them survived.\n\nThat usually means a styled component which renders only on the server. Either give the client a path to it, or set \`bamboocss({ pruneCss: false })\` to ship the whole extracted stylesheet.`);
1765
+ const remaining = remainingEnvironments(staticSession, environment);
1766
+ if (typeof this.getModuleInfo === "function" && !remaining.length) {
1767
+ if (!staticSession.cssLoaded) throw new Error(`bamboocss: compiled class values were produced, but ${JSON.stringify(VIRTUAL_CSS_ID)} was not imported. Add \`import ${JSON.stringify(VIRTUAL_CSS_ID)}\` once, from a JavaScript or TypeScript module in the application entry graph.\n\nIt has to be a JS import. \`@import\` from a stylesheet does not reach it: the id names a virtual module resolved by this plugin, and Vite resolves CSS \`@import\` before plugin resolution, so it fails as an unresolvable path. A project that ships one preloaded stylesheet imports this from its entry module instead, and lets Vite emit the CSS asset.`);
1768
+ const outsideExtraction = [...staticSession.transformedFiles].filter((file) => !staticSession.extractedFiles.has(file));
1769
+ 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}`), {
1770
+ unit: "file",
1771
+ separator: "\n"
1772
+ })}\n\nAdd them to \`include\` in bamboo.config, or no CSS rule can back their emitted classes.`);
1773
+ }
1774
+ if (reportSummary && (command !== "build" || !remaining.length)) reportTransformCoverage(states);
1775
+ if (command === "serve" || !outputTokensByEnvironment.get(environment)?.size) completeEnvironmentGeneration(environment, state);
1776
+ else prepareEnvironmentGeneration(environment, state);
1777
+ } catch (error) {
1778
+ rollbackEnvironmentGeneration(environment, state);
1779
+ throw error;
3741
1780
  }
3742
- if (typeof this.getModuleInfo === "function" && !remainingEnvironments(staticSession).length) {
3743
- if (!staticSession.cssLoaded) throw new Error(`bamboocss: compiled class values were produced, but ${JSON.stringify(VIRTUAL_CSS_ID)} was not imported. Add \`import ${JSON.stringify(VIRTUAL_CSS_ID)}\` once, from a JavaScript or TypeScript module in the application entry graph.\n\nIt has to be a JS import. \`@import\` from a stylesheet does not reach it: the id names a virtual module resolved by this plugin, and Vite resolves CSS \`@import\` before plugin resolution, so it fails as an unresolvable path. A project that ships one preloaded stylesheet imports this from its entry module instead, and lets Vite emit the CSS asset.`);
3744
- const outsideExtraction = [...staticSession.transformedFiles].filter((file) => !staticSession.extractedFiles.has(file));
3745
- 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}`), {
3746
- unit: "file",
3747
- separator: "\n"
3748
- })}\n\nAdd them to \`include\` in bamboo.config, or no CSS rule can back their emitted classes.`);
1781
+ },
1782
+ renderError() {
1783
+ const environment = environmentName(this);
1784
+ const state = transformStateByEnvironment.get(environment);
1785
+ if (state) rollbackEnvironmentGeneration(environment, state);
1786
+ }
1787
+ };
1788
+ const outputWriteObserver = {
1789
+ name: "bamboocss:output-write-observer",
1790
+ enforce: "pre",
1791
+ sharedDuringBuild: true,
1792
+ buildStart: {
1793
+ order: "pre",
1794
+ sequential: true,
1795
+ handler() {
1796
+ observeEnvironmentBuildStart(environmentName(this));
1797
+ }
1798
+ },
1799
+ writeBundle: {
1800
+ order: "pre",
1801
+ sequential: true,
1802
+ handler(outputOptions, bundle) {
1803
+ const identity = outputIdentityByBundle.get(bundle) ?? outputIdentityByOptions.get(outputOptions);
1804
+ if (identity?.environment === environmentName(this)) publishPreparedOutput(identity.environment, identity.outputToken, identity.outputSlot, true);
3749
1805
  }
3750
- if (!reportSummary) return;
3751
- if (command === "build" && remainingEnvironments(staticSession).length) return;
3752
- let folded = 0;
3753
- let filesWithFolds = 0;
3754
- const skipped = /* @__PURE__ */ new Map();
3755
- for (const entry of perFile.values()) {
3756
- folded += entry.folded;
3757
- if (entry.folded) filesWithFolds++;
3758
- for (const [reason, count] of entry.skipped ?? []) skipped.set(reason, (skipped.get(reason) ?? 0) + count);
1806
+ }
1807
+ };
1808
+ const memoryOutputCommitter = {
1809
+ name: "bamboocss:output-memory-committer",
1810
+ enforce: "post",
1811
+ sharedDuringBuild: true,
1812
+ closeBundle: {
1813
+ order: "post",
1814
+ sequential: true,
1815
+ handler() {
1816
+ closePreparedMemoryOutputs(environmentName(this));
3759
1817
  }
3760
- const declined = Array.from(skipped.values()).reduce((sum, count) => sum + count, 0);
3761
- const total = folded + declined;
3762
- if (!total) return;
3763
- const share = Math.round(folded / total * 100);
3764
- const reasons = Array.from(skipped.entries()).sort((a, b) => b[1] - a[1]).map(([reason, count]) => `${reason}=${count}`).join(" ");
3765
- logger.info("vite:transform", `Compiled ${folded}/${total} (${share}%) across ${filesWithFolds}/${perFile.size} files` + (reasons ? ` — declined: ${reasons}` : ""));
3766
1818
  }
3767
- }];
1819
+ };
1820
+ return [bamboocssCss({
1821
+ configPath,
1822
+ cwd,
1823
+ session: staticSession,
1824
+ pruneCss
1825
+ }), compiler];
3768
1826
  };
3769
1827
  //#endregion
3770
1828
  export { VIRTUAL_CSS_ID, bamboocss, bamboocss as default };