@bamboocss/node 1.56.7 → 1.57.1

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,30 +1,31 @@
1
1
  import { isStaticCompilerActive, markStaticCompilerActive } from "./static-compiler.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { colors, logger, quote } from "@bamboocss/logger";
4
- import { convertTsPathsToRegexes, diffConfigs, findConfig, loadConfig, mergeHooks } from "@bamboocss/config";
4
+ import { checkNamingAgreement, formatNamingDisagreement, messages, prunesPreflight } from "@bamboocss/core";
5
5
  import { BambooError, cssVarRefs, getOrCreateSet, groupBy, truncateList, uniq } from "@bamboocss/shared";
6
- import { appendFileSync, existsSync, readFileSync, statSync, writeFileSync } from "fs";
7
- import { dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "path";
8
- import picomatch from "picomatch";
6
+ import { isMatch } from "matcher";
7
+ import fs, { appendFileSync, existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
8
+ import { changesEveryArtifact, convertTsPathsToRegexes, diffConfigs, findConfig, loadConfig, mergeHooks } from "@bamboocss/config";
9
+ import path, { basename, dirname, extname, isAbsolute, join, normalize, parse, posix, relative, resolve, sep } from "node:path";
9
10
  import { pluginSvelte } from "@bamboocss/plugin-svelte";
10
11
  import { pluginVue } from "@bamboocss/plugin-vue";
11
- import { checkNamingAgreement, formatNamingDisagreement, messages, prunesPreflight } from "@bamboocss/core";
12
+ import { fileURLToPath } from "node:url";
12
13
  import { Generator, generatePackageExports } from "@bamboocss/generator";
13
- import fs, { existsSync as existsSync$1, promises, statSync as statSync$1 } from "node:fs";
14
- import path, { dirname as dirname$1, isAbsolute as isAbsolute$1, join as join$1, resolve as resolve$1 } from "node:path";
15
14
  import { debounce } from "perfect-debounce";
16
- import { fileURLToPath } from "node:url";
17
15
  import process$1 from "node:process";
18
16
  import os from "node:os";
19
17
  import tty from "node:tty";
18
+ import { declaresAliases, findClosestTsconfig, globBase, includesUnder, isSolutionTsconfig, isSourceFileIncludedInTsconfig, readTsconfigGraph, resolveDirectTsconfigJson, resolvePathsBase } from "@bamboocss/config/tsconfig";
20
19
  import chokidar from "chokidar";
21
20
  import glob from "fast-glob";
22
21
  import fsExtra from "fs-extra";
23
- import { isMatch } from "matcher";
22
+ import picomatch from "picomatch";
24
23
  import readline from "node:readline";
24
+ import { writeFile } from "node:fs/promises";
25
+ import { crc32, deflateRawSync } from "node:zlib";
25
26
  import { lookItUpSync } from "look-it-up";
26
27
  import outdent$1, { outdent } from "outdent";
27
- import { execFileSync } from "child_process";
28
+ import { execFileSync } from "node:child_process";
28
29
  //#region \0rolldown/runtime.js
29
30
  var __create = Object.create;
30
31
  var __defProp = Object.defineProperty;
@@ -48,334 +49,1432 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
48
49
  enumerable: true
49
50
  }) : target, mod));
50
51
  //#endregion
51
- //#region src/analyze.ts
52
+ //#region src/source-snapshots.ts
52
53
  /**
53
- * `analyze` is one CLI command, but this module is reachable from `@bamboocss/node`'s index,
54
- * so a static import made every consumer of that index — the CLI on any command, and the Vite
55
- * plugin on every build — load the reporter and its table formatters to run neither. Loading
56
- * it here keeps that off the path of everything that is not the `analyze` command.
54
+ * Every file `include` covers, read once.
55
+ *
56
+ * The scans that decide what survives pruning — the token reference set, the reachability
57
+ * gate, the strict accounting — all want the same two copies of the same files, and each used
58
+ * to fetch them itself. A strict build therefore read every file three times over: once to
59
+ * collect references, once to account, and once more for the gate whenever the accounting
60
+ * declined. Yielding a snapshot lets one walk feed all of them.
61
+ *
62
+ * Both copies, because neither alone is complete and the text scans are safe when over-fed. A
63
+ * file the parser transformed is stored rewritten (`parseSourceFile` calls `replaceWithText`),
64
+ * and those transforms lose things the scans want: `svelteToTsx` and `vueToTsx` each swallow a
65
+ * throw and return an empty string, and a Vue SFC with a render function and no `<template>`
66
+ * becomes the literal `<template>undefined</template>`. Read only the parsed copy and a file
67
+ * like that reports no tokens and no elements at all.
68
+ *
69
+ * The parsed copy still has to be read as well, because `parser:before` is the documented way
70
+ * to teach bamboo a format it does not know. A template compiled to jsx by such a hook holds
71
+ * nothing a scan of the raw file would recognise, and that is the hook working as intended.
57
72
  */
58
- async function analyze(ctx, options = {}) {
59
- const { Reporter, formatRecipeReport, formatTokenReport } = await import("@bamboocss/reporter");
60
- const reporter = new Reporter(ctx, {
61
- parserOptions: ctx.parserOptions,
62
- parseFile: (file) => ctx.parseFile(file),
63
- prepare: (files) => ctx.prepareNativeExtraction(files),
64
- getRelativePath: ctx.runtime.path.relative,
65
- getFiles: ctx.getFiles,
66
- ...options
67
- });
68
- reporter.init();
69
- return {
70
- getRecipeReport(format = "table") {
71
- const report = reporter.getRecipeReport();
72
- return {
73
- report,
74
- formatted: formatRecipeReport(report, format)
75
- };
76
- },
77
- getTokenReport(format = "table") {
78
- const report = reporter.getTokenReport();
79
- return {
80
- report,
81
- formatted: formatTokenReport(report.getSummary(), format)
82
- };
83
- },
84
- writeReport(filePath) {
85
- const dirname = ctx.runtime.path.dirname(filePath);
86
- ctx.runtime.fs.ensureDirSync(dirname);
87
- const str = JSON.stringify(reporter.report, replacer, 2);
88
- return ctx.runtime.fs.writeFile(filePath, str);
89
- }
90
- };
91
- }
92
- function replacer(_, value) {
93
- if (value instanceof Set) return Array.from(value);
94
- if (value instanceof Map) return Object.fromEntries(value);
95
- return value;
96
- }
97
- //#endregion
98
- //#region src/build-info.ts
99
- async function buildInfo(ctx, outfile) {
100
- const { filesWithCss, files } = ctx.parseFiles();
101
- logger.info("cli", `Found ${colors.bold(`${filesWithCss.length}/${files.length}`)} files using Bamboo`);
102
- const { minify, staticCss } = ctx.config;
103
- logger.info("cli", `Writing ${minify ? "[min] " : " "}${colors.bold(outfile)}`);
104
- if (staticCss) {
105
- logger.info("cli", "Adding staticCss definitions...");
106
- ctx.staticCss.process(staticCss);
107
- }
108
- const output = JSON.stringify(ctx.encoder.toJSON(), null, minify ? 0 : 2);
109
- ctx.output.ensure(outfile, process.cwd());
110
- await ctx.runtime.fs.writeFile(outfile, output);
111
- logger.info("cli", "Done!");
73
+ function* sourceSnapshots(ctx) {
74
+ for (const file of ctx.getFiles()) yield readSnapshot(ctx, ctx.runtime.path.abs(ctx.config.cwd, file));
112
75
  }
113
- //#endregion
114
- //#region src/codegen.ts
115
- async function codegen(ctx, ids) {
116
- const { default: pLimit } = await import("p-limit");
117
- const limit = pLimit(20);
118
- if (ctx.config.clean) ctx.output.empty();
119
- let artifacts = ctx.getArtifacts(ids);
120
- let hookFiltered = false;
121
- if (ctx.hooks["codegen:prepare"]) {
122
- const results = await ctx.hooks["codegen:prepare"]?.({
123
- changed: ids,
124
- artifacts
125
- });
126
- if (results) {
127
- artifacts = results;
128
- hookFiltered = true;
129
- }
76
+ /** One file's snapshot, for a walk that decides per file whether it needs to read at all. */
77
+ function readSnapshot(ctx, filePath) {
78
+ let onDisk;
79
+ try {
80
+ onDisk = ctx.runtime.fs.readFileSync(filePath);
81
+ } catch {
82
+ onDisk = void 0;
130
83
  }
131
- const promises = artifacts.map((artifact) => limit(() => ctx.output.write(artifact)));
132
- await Promise.allSettled(promises);
133
- if (!hookFiltered) ctx.output.prune(ids ? ctx.getArtifacts() : artifacts);
134
- await ctx.hooks["codegen:done"]?.({ changed: ids });
135
84
  return {
136
- box: ctx.initMessage(),
137
- msg: ctx.messages.artifactsGenerated()
85
+ filePath,
86
+ onDisk,
87
+ parsed: ctx.parsedSourceText(filePath, onDisk)
138
88
  };
139
89
  }
140
- //#endregion
141
- //#region src/astro-to-tsx.ts
142
90
  /**
143
- * Astro's compiler, loaded the first time a `.astro` file is actually parsed.
91
+ * The distinct texts a snapshot carries.
144
92
  *
145
- * Every build carries this hook, so a static import would make every build pay to load a
146
- * compiler most projects never call — the reason the Vue and Svelte plugins load theirs lazily
147
- * too. The `sync` entry because `parser:before` is synchronous. `@astrojs/compiler` is an
148
- * optional peer: `astro` depends on it, so a project with `.astro` files already has it.
93
+ * One when the parser holds the file as written, two when a transform rewrote it. Every
94
+ * textual scan wants both, and wants neither twice.
149
95
  */
150
- let convert;
151
- const load = () => convert ??= createRequire(import.meta.url)("@astrojs/compiler/sync").convertToTSX;
152
- /** The inline source map Astro appends, which nothing downstream reads. */
153
- const SOURCE_MAP_COMMENT = /\n\/\/# sourceMappingURL=data:[^\n]*\s*$/;
154
- /** A static `import` statement starting a line: a binding clause and `from`, or neither. */
155
- const IMPORT_STATEMENT = /^[ \t]*import\s+(?:type\s+)?(?:[\w$*{}\s,]+?\s+from\s+)?(['"])[^'"\n]+\1[ \t]*;?/gm;
96
+ function* snapshotTexts(snapshot) {
97
+ const { onDisk, parsed } = snapshot;
98
+ if (onDisk != null) yield onDisk;
99
+ if (parsed != null && parsed !== onDisk) yield parsed;
100
+ }
101
+ //#endregion
102
+ //#region src/token-accounting.ts
156
103
  /**
157
- * A bundled `<script>` as module code: its imports at the top level, where they bind, and the
158
- * rest in a block of its own, so its declarations do not meet the frontmatter's.
104
+ * The one decline `prune.unresolvedPath: 'error'` fails the build on.
105
+ *
106
+ * That setting asserts that every token path resolves, and this is the reason that says otherwise:
107
+ * a token binding used in a way the build cannot follow — a path built at runtime, a binding
108
+ * assigned away, a namespace enumerated. It is about the author's *token usage*, and it has a
109
+ * fix at the call site.
110
+ *
111
+ * Nothing else may throw, because nothing else is necessarily about tokens at all. The other
112
+ * reasons were written under a premise this would break: declining was free, so every branch
113
+ * that could not prove a shape declined, and the accepted set was kept deliberately small.
114
+ * `import(`./pages/${name}`)` declines as `dynamic-import` because the specifier is not a
115
+ * literal and *could* be the artifact; `import lexer = require('./tokenizer')` declines because
116
+ * the statement contains the substring `token`. Both are routine code with nothing to do with
117
+ * design tokens, and failing a build over them would be indefensible. They keep every
118
+ * declaration, which is what they always did, and say so.
159
119
  */
160
- const moduleCode = (script) => {
161
- const imports = [];
162
- const body = script.content.replace(IMPORT_STATEMENT, (statement) => {
163
- imports.push(statement.trim());
164
- return "";
165
- });
166
- return `${imports.join("\n")}\n${/^[ \t]*export\b/m.test(body) ? body : `{\n${body}\n}`}`;
167
- };
120
+ const failsStrict = (entry) => entry.reason === "unresolved-reference";
168
121
  /**
169
- * A `.astro` file as TSX the extractor can parse.
170
- *
171
- * Nothing converted these before: the TypeScript parser read the raw file, recovering from the
172
- * `---` fences and the template well enough to find calls in it. Oxc, which does all extraction
173
- * now, rejects that text, failing the build on every Astro component.
122
+ * One file's contribution, split out so the build can account and scan in a single walk.
174
123
  *
175
- * Astro's own TSX output is what its language tools type-check against — the frontmatter as
176
- * module code, the template as JSX in a fragment — so it is valid by construction and keeps
177
- * every expression the template evaluates, `class={css({ … })}` included.
124
+ * `pruneTokensForBuild` needs the keep set, the reachability answer and this accounting from
125
+ * the same files; three separate passes read every file three times.
178
126
  */
179
- const astroToTsx = (code, filename) => {
180
- let result;
181
- try {
182
- result = load()(code, { filename });
183
- } catch {
184
- return "";
127
+ function accountSnapshot(ctx, snapshot, accounting) {
128
+ const { filePath, onDisk, parsed } = snapshot;
129
+ const { paths, prefixes, declined } = accounting;
130
+ {
131
+ if (onDisk == null || parsed == null || parsed !== onDisk) {
132
+ if (!(mentionsToken(ctx, onDisk) || mentionsToken(ctx, parsed))) return;
133
+ declined.push({
134
+ filePath,
135
+ line: 1,
136
+ reason: onDisk == null || parsed == null ? "unreadable" : "transformed"
137
+ });
138
+ return;
139
+ }
140
+ if (!mentionsToken(ctx, parsed)) return;
141
+ const native = ctx.accountTokens(filePath, parsed);
142
+ if (native.unparsed) {
143
+ declined.push({
144
+ filePath,
145
+ line: 1,
146
+ reason: "unparsed"
147
+ });
148
+ return;
149
+ }
150
+ for (const path of native.paths) paths.add(path);
151
+ for (const prefix of native.prefixes) prefixes.add(prefix);
152
+ for (const entry of native.declined) declined.push({
153
+ filePath,
154
+ ...entry
155
+ });
185
156
  }
186
- const tsx = result.code.replace(SOURCE_MAP_COMMENT, "\n");
187
- const scripts = (result.metaRanges?.scripts ?? []).filter((script) => script.type === "processed-module");
188
- if (!scripts.length) return tsx;
189
- return `${tsx}\n${scripts.map(moduleCode).join("\n")}\n`;
190
- };
191
- /** Built in, rather than a plugin package: Astro support is part of the Vite integration. */
192
- const pluginAstro = () => ({
193
- name: "@bamboocss/node:astro",
194
- hooks: { "parser:before": ({ filePath, content }) => {
195
- if (filePath.endsWith(".astro")) return astroToTsx(content, filePath);
196
- } }
197
- });
198
- //#endregion
199
- //#region src/extractable-files.ts
157
+ }
200
158
  /**
201
- * Which of the files `include` matched an extraction pass actually has to read.
202
- *
203
- * A file can only contribute to the stylesheet by *calling* something bamboo owns — `css`, a
204
- * recipe, a pattern, `token`. Every one of those arrives as a binding, and a binding arrives
205
- * through an import: either straight from an entrypoint, or from a local module that got it
206
- * from one. A file with no such chain cannot hold a call, whatever else is in it.
207
- *
208
- * On a real application that is most of the tree. Measured over 6,425 files: 4,062 could reach
209
- * an entrypoint and 2,363 provably could not, and not handing the extractor the latter took the
210
- * pass from 88.9s to 26.3s with byte-identical CSS out. The scan itself costs ~300ms, because
211
- * it reads text and never parses.
212
- *
213
- * ## Skipping is not the same as ignoring
159
+ * Whether a file is worth walking — because it can name the artifact, or because a shape in it
160
+ * declines without naming one.
214
161
  *
215
- * A file left out here is still *reachable*. Cross-file composition works by resolving an
216
- * import and reading what it names, so a module that exports a style object still arrives
217
- * the moment something that qualifies imports it. What is skipped is only asking "does this
218
- * file *originate* a call", of a file that has no binding to originate one with.
162
+ * The obvious half is the substring `token`, which an import of the default entrypoint, a call,
163
+ * a member read and a `require` of it all put in the source. Three things defeat it, and each one
164
+ * is a silent under-keep rather than a slow build, so the test errs wide:
219
165
  *
220
- * ## Everything here fails open
166
+ * - **A configured entrypoint need not spell it.** `importMap: { tokens: '@acme/design' }` and a
167
+ * tsconfig path mapping both make `isTokensEntrypoint` true for a specifier with no `token` in
168
+ * it, so the configured modules are tested for as well.
169
+ * - **An identifier may be written with unicode escapes.** An import specifier can spell the `t`
170
+ * of `token` as a backslash-u escape and still bind the export, which `nameOf` resolves and
171
+ * there is a test on. Both escape forms — the four-digit one and the braced one — begin with a
172
+ * backslash followed by `u`, so testing for that pair catches every spelling.
173
+ * - **`require()` and `import()` decline on a specifier this cannot read**, which is a statement
174
+ * about the specifier rather than about tokens: `import(`./pages/${name}`)` names nothing and
175
+ * declines all the same, because it *could* be the artifact. Skipping the file would drop that
176
+ * decline and with it the keep it was standing in for.
221
177
  *
222
- * The failure this must not have is dropping a rule, which is silent: the build stays green and
223
- * the class the component asks for has nothing behind it. So every uncertainty resolves toward
224
- * including the file, and the cases are named rather than left to a catch-all — a file that
225
- * cannot be read, a source whose imports could not be scanned, a specifier that looks local and
226
- * resolves to nothing. Being wrong in that direction costs time; being wrong in the other costs
227
- * correctness.
178
+ * A false positive costs one identifier walk. A false negative deletes a declaration something
179
+ * still asks for, so anything uncertain belongs on the walking side.
228
180
  */
229
- /**
230
- * Module specifiers, from the four places one can appear.
231
- *
232
- * Deliberately loose about what surrounds them. A specifier missed here costs an edge, and an
233
- * edge missed can exclude a file that should have been kept — so the pattern is written to
234
- * over-match rather than to parse, and `scanSpecifiers` treats a source it found nothing in as
235
- * one it failed to read.
236
- */
237
- const SPECIFIER = /(?:\bfrom\s*|^\s*(?:import|export)\s*|\bimport\s*\(\s*|\brequire\s*\(\s*)['"]([^'"\n]+)['"]/gm;
238
- /** The extensions a specifier may omit, in the order the native resolver tries them. */
239
- const EXTENSIONS = [
240
- ".ts",
241
- ".tsx",
242
- ".d.ts",
243
- ".mts",
244
- ".cts",
245
- ".js",
246
- ".jsx",
247
- ".mjs",
248
- ".cjs"
249
- ];
250
- /** What a `.js`-family specifier may actually name, source first. */
251
- const EMITTED = [
252
- [".js", [
253
- ".ts",
254
- ".tsx",
255
- ".d.ts",
256
- ".js",
257
- ".jsx"
258
- ]],
259
- [".mjs", [
260
- ".mts",
261
- ".d.mts",
262
- ".mjs"
263
- ]],
264
- [".cjs", [
265
- ".cts",
266
- ".d.cts",
267
- ".cjs"
268
- ]]
269
- ];
270
- /** Every specifier in a source, or `undefined` when the text could not be scanned at all. */
271
- const scanSpecifiers = (text) => {
272
- const found = [];
273
- for (const match of text.matchAll(SPECIFIER)) if (match[1]) found.push(match[1]);
274
- if (found.length) return found;
275
- return /\b(?:import|require)\b/.test(text) ? void 0 : found;
276
- };
277
- /** A candidate path with every extension a specifier may have omitted. */
278
- const candidatesFor = (base) => {
279
- const emitted = EMITTED.find(([suffix]) => base.endsWith(suffix));
280
- return [...emitted ? emitted[1].map((extension) => base.slice(0, -emitted[0].length) + extension) : [base, ...EXTENSIONS.map((extension) => base + extension)], ...EXTENSIONS.map((extension) => `${base}/index${extension}`)];
181
+ const IMPORTING_CALL = /\b(?:require|import)\s*\(/;
182
+ const mentionsToken = (ctx, text) => {
183
+ if (text == null) return false;
184
+ if (text.includes("token") || text.includes("\\u")) return true;
185
+ if (ctx.imports.value.tokens.some((mod) => text.includes(mod))) return true;
186
+ return IMPORTING_CALL.test(text);
281
187
  };
188
+ //#endregion
189
+ //#region src/token-references.ts
282
190
  /**
283
- * Where a specifier points, when that is somewhere inside the project.
191
+ * `token('spacing.4')` and `token.value('colors.red.300')`, including the whitespace a
192
+ * formatter may leave behind. The parser reports both, resolving constants and template
193
+ * literals through them — `token.value()` included, since it is recorded as its own kind
194
+ * rather than dropped for having a property access as its callee. Scanning the text still
195
+ * earns its place twice over: it covers a path built somewhere the extractor cannot
196
+ * follow, and it covers the callers below that supply no `results` at all.
197
+ */
198
+ const TOKEN_CALL = /\btoken(?:\s*\.\s*value)?\s*\(\s*['"`]([^'"`]+)['"`]/g;
199
+ /** An import of the generated tokens artifact, under any of the spellings that reach it. */
200
+ const TOKEN_IMPORT = /\b(?:from|import|require)\s*\(?\s*['"][^'"]*\/tokens(\/[^'"]*|\.[cm]?[jt]sx?)?['"]/;
201
+ /** A call to `token()` or `token.value()`, whatever the argument is — or is not. */
202
+ const TOKEN_CALLEE = /\btoken(\s*\.\s*value)?\s*\(/;
203
+ /** The same, but only where the argument is a string literal — the shape `TOKEN_CALL` resolves. */
204
+ const TOKEN_CALL_LITERAL = /\btoken(?:\s*\.\s*value)?\s*\(\s*['"`]/;
205
+ /** String literals, contents and all. */
206
+ const STRING_LITERAL = /'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|`(?:[^`\\]|\\.)*`/g;
207
+ /**
208
+ * Whether a token is reached from javascript at all — a call of any shape, or an import of the
209
+ * artifact. It no longer decides pruning on its own: the accounting does that, and this is the
210
+ * gate the *fallback* defers to when the accounting declines. A project reaching for no token at
211
+ * all is one a decline cannot endanger, so it keeps nothing extra.
284
212
  *
285
- * `undefined` means "nothing local", which is the answer for a package as well as for a broken
286
- * path — and both are correct here, because neither can hand this file a binding bamboo owns.
287
- * bamboo's own resolution stops at the same boundary: a target outside the project reads as
288
- * non-local, so nothing it exports is ever extracted from.
213
+ * The awkward part is that a token reference inside a css value is now spelled `token(…)` too,
214
+ * and it must *not* count: `css({ border: '1px solid token(colors.red.300)' })` reaches a token
215
+ * from a stylesheet, where the css scan already accounts for it, not from javascript. Reading it
216
+ * as a call turned pruning off wholesale — measured at 3.2x the stylesheet on a sandbox, since
217
+ * "keep everything" is what the gate means. It was only ever latent before, because `{…}` was
218
+ * the spelling the docs used and it looked nothing like a call.
219
+ *
220
+ * So a `token(` that survives blanking every string literal is a real call, and one that does
221
+ * not was written inside a string. The literal-argument test comes first and on the raw text,
222
+ * which is what keeps this a superset of `TOKEN_CALL` as the coupling in `collectTokenReferences`
223
+ * requires: a resolvable call embedded in a template literal — a fixture holding source code —
224
+ * still counts, even though blanking would hide it.
225
+ *
226
+ * No `g` flag on the tests, so `test` carries no state between files.
289
227
  */
290
- const localTargetOf = (specifier, importer, options) => {
291
- const bases = [];
292
- if (specifier.startsWith(".")) bases.push(resolve$1(dirname$1(importer), specifier));
293
- else if (isAbsolute$1(specifier)) bases.push(specifier);
294
- else {
295
- for (const [pattern, targets] of Object.entries(options.paths ?? {})) {
296
- const star = pattern.indexOf("*");
297
- if (star === -1) {
298
- if (pattern !== specifier) continue;
299
- for (const target of targets) bases.push(resolve$1(options.cwd, target));
300
- continue;
301
- }
302
- const head = pattern.slice(0, star);
303
- const tail = pattern.slice(star + 1);
304
- if (!specifier.startsWith(head) || !specifier.endsWith(tail)) continue;
305
- const filled = specifier.slice(head.length, specifier.length - tail.length);
306
- for (const target of targets) bases.push(resolve$1(options.cwd, target.replace("*", filled)));
307
- }
308
- if (options.baseUrl) bases.push(resolve$1(options.cwd, options.baseUrl, specifier));
309
- }
310
- const exists = options.fileExists ?? existsSync$1;
311
- const root = options.cwd.endsWith("/") ? options.cwd : `${options.cwd}/`;
312
- for (const base of bases) {
313
- if (!base.startsWith(root)) continue;
314
- for (const candidate of candidatesFor(base)) if (exists(candidate)) return candidate;
315
- }
228
+ const reachableFromJs = (text) => {
229
+ if (TOKEN_IMPORT.test(text) || TOKEN_CALL_LITERAL.test(text)) return true;
230
+ return TOKEN_CALLEE.test(text) && TOKEN_CALLEE.test(text.replace(STRING_LITERAL, "''"));
316
231
  };
317
232
  /**
318
- * The subset of `files` that could hold a call to something bamboo owns.
233
+ * The text of every file `include` covers — as written on disk, and, when they differ, as the
234
+ * parser understands it.
319
235
  *
320
- * Two passes over text and no parsing. The first marks every file that names an entrypoint and
321
- * records where each file's other imports point; the second walks those edges backwards from
322
- * the marked set, because a file that imports a module carrying bamboo bindings may be using
323
- * one — a recipe defined with `cva` in one file and called in another is exactly that shape.
236
+ * Both, because neither alone is complete and every scan below is safe when over-fed. A file
237
+ * the parser transformed is stored rewritten (`parseSourceFile` calls `replaceWithText`), and
238
+ * those transforms lose things the scans want: `svelteToTsx` and `vueToTsx` each swallow a
239
+ * throw and return an empty string, and a Vue SFC with a render function and no `<template>`
240
+ * becomes the literal `<template>undefined</template>`. Read only the parsed copy and a file
241
+ * like that reports no tokens and no elements at all.
324
242
  *
325
- * The edges are worth more than the walk they were built for. Every one of them names a module
326
- * that is *going* to be demanded, so the same scan that decides what to parse also says which
327
- * virtual or transformed sources the native source map may need — see `auxiliary`.
243
+ * The parsed copy still has to be read as well, because `parser:before` is the documented way
244
+ * to teach bamboo a format it does not know. A template compiled to jsx by such a hook holds
245
+ * nothing a scan of the raw file would recognise, and that is the hook working as intended.
246
+ *
247
+ * So the cost is one extra read per file, and a second regex pass over the files a transform
248
+ * actually changed. Measured at ~14ms for 806 files, against a build where css emission alone
249
+ * is an order of magnitude more.
328
250
  */
329
- const selectExtractable = (files, options) => {
330
- const keep = /* @__PURE__ */ new Set();
331
- const importers = /* @__PURE__ */ new Map();
332
- for (const file of files) {
333
- const text = options.readFile(file);
334
- if (text === void 0) {
335
- keep.add(file);
336
- continue;
337
- }
338
- if (options.entrypoints.some((entrypoint) => text.includes(entrypoint))) keep.add(file);
339
- const specifiers = scanSpecifiers(text);
340
- if (specifiers === void 0) {
341
- keep.add(file);
342
- continue;
343
- }
344
- for (const specifier of specifiers) {
345
- const target = localTargetOf(specifier, file, options);
346
- if (!target) continue;
347
- const seen = importers.get(target);
348
- if (seen) seen.push(file);
349
- else importers.set(target, [file]);
251
+ function* sourceTexts(ctx) {
252
+ for (const snapshot of sourceSnapshots(ctx)) yield* snapshotTexts(snapshot);
253
+ }
254
+ const createSourceScanCache = () => ({
255
+ signature: "",
256
+ entries: /* @__PURE__ */ new Map(),
257
+ resolvedTokenReferences: /* @__PURE__ */ new Map()
258
+ });
259
+ const resolvedTokenReferences = (result) => {
260
+ if (!result) return [];
261
+ const facts = [];
262
+ for (const item of result.token) {
263
+ if (!item.tokenCalleeRange || !item.data?.length) continue;
264
+ const paths = [];
265
+ for (const value of item.data) {
266
+ if (typeof value !== "string") break;
267
+ paths.push(value);
350
268
  }
269
+ if (paths.length !== item.data.length) continue;
270
+ facts.push({
271
+ ...item.tokenCalleeRange,
272
+ paths: [...new Set(paths)].sort()
273
+ });
351
274
  }
352
- let frontier = [...keep];
353
- while (frontier.length) {
354
- const next = [];
355
- for (const target of frontier) for (const importer of importers.get(target) ?? []) {
356
- if (keep.has(importer)) continue;
357
- keep.add(importer);
358
- next.push(importer);
359
- }
360
- frontier = next;
275
+ return facts.sort((left, right) => left.start - right.start || left.end - right.end);
276
+ };
277
+ const sameResolvedTokenReferences = (left, right) => (left?.length ?? 0) === right.length && right.every((fact, index) => fact.start === left[index].start && fact.end === left[index].end && fact.paths.length === left[index].paths.length && fact.paths.every((path, pathIndex) => path === left[index].paths[pathIndex]));
278
+ /**
279
+ * Reconcile one file's lightweight token facts after extraction.
280
+ *
281
+ * Deleting the source scan only when the semantic facts moved is important for dependents:
282
+ * changing an imported constant can change `token(KEY)` without changing the consumer's mtime.
283
+ */
284
+ const recordResolvedTokenReferences = (cache, filePath, result) => {
285
+ const next = resolvedTokenReferences(result);
286
+ if (sameResolvedTokenReferences(cache.resolvedTokenReferences.get(filePath), next)) return;
287
+ if (next.length) cache.resolvedTokenReferences.set(filePath, next);
288
+ else cache.resolvedTokenReferences.delete(filePath);
289
+ cache.entries.delete(filePath);
290
+ };
291
+ const reconcileAccounting = (accounting, references, filePath) => {
292
+ if (!references?.length) return;
293
+ const ranges = new Set(references.map(({ start, end }) => `${start}:${end}`));
294
+ for (const reference of references) for (const path of reference.paths) accounting.paths.add(path);
295
+ accounting.declined = accounting.declined.filter((entry) => entry.reason !== "unresolved-reference" || filePath !== void 0 && entry.filePath !== filePath || entry.start == null || entry.end == null || !ranges.has(`${entry.start}:${entry.end}`));
296
+ };
297
+ const OPEN_TAG = /<\s*([a-z][\w-]*)(?=[\s/>]|$)/g;
298
+ const scanSnapshot = (ctx, snapshot, options, patterns, resolvedReferences) => {
299
+ const tokenPaths = /* @__PURE__ */ new Set();
300
+ const cssVars = /* @__PURE__ */ new Set();
301
+ const elements = /* @__PURE__ */ new Set();
302
+ const keyframeHits = /* @__PURE__ */ new Set();
303
+ let reachable = false;
304
+ for (const text of snapshotTexts(snapshot)) {
305
+ for (const match of text.matchAll(TOKEN_CALL)) tokenPaths.add(match[1]);
306
+ for (const name of cssVarRefs(text)) cssVars.add(name);
307
+ if (!reachable && reachableFromJs(text)) reachable = true;
308
+ if (options.elements) for (const match of text.matchAll(OPEN_TAG)) elements.add(match[1].toLowerCase());
309
+ for (const [name, pattern] of patterns) if (!keyframeHits.has(name) && pattern.test(text)) keyframeHits.add(name);
361
310
  }
362
- const inventory = new Set(files);
311
+ const accounting = {
312
+ paths: /* @__PURE__ */ new Set(),
313
+ prefixes: /* @__PURE__ */ new Set(),
314
+ declined: []
315
+ };
316
+ accountSnapshot(ctx, snapshot, accounting);
317
+ reconcileAccounting(accounting, resolvedReferences);
363
318
  return {
364
- auxiliary: [...importers.keys()].filter((target) => !inventory.has(target)),
365
- extractable: files.filter((file) => keep.has(file))
319
+ tokenPaths: [...tokenPaths],
320
+ cssVars: [...cssVars],
321
+ reachableFromJs: reachable,
322
+ elements: [...elements],
323
+ keyframeHits: [...keyframeHits],
324
+ accountingPaths: [...accounting.paths],
325
+ accountingPrefixes: [...accounting.prefixes],
326
+ accountingDeclined: accounting.declined
366
327
  };
367
328
  };
368
- //#endregion
369
- //#region ../../node_modules/.pnpm/ansi-regex@6.2.2/node_modules/ansi-regex/index.js
370
- function ansiRegex({ onlyFirst = false } = {}) {
371
- return new RegExp(`(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`, onlyFirst ? void 0 : "g");
372
- }
373
- //#endregion
374
- //#region ../../node_modules/.pnpm/strip-ansi@7.1.2/node_modules/strip-ansi/index.js
375
- const regex = ansiRegex();
376
- function stripAnsi(string) {
377
- if (typeof string !== "string") throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
378
- return string.replace(regex, "");
329
+ /**
330
+ * Every source-derived answer the pruning passes need, from one walk over the sources.
331
+ *
332
+ * The token scan, the reachability gate, the strict accounting, the keyframe references and
333
+ * the rendered-element set all read the same two copies of the same files, and each caller
334
+ * used to run its own sweep — `Builder.toCss` paid the walk up to three times per stylesheet.
335
+ * This is the same de-duplication `pruneTokensForBuild` already performed for its own three
336
+ * answers, extended to all five.
337
+ *
338
+ * With a `cache`, a file whose mtime has not moved is not even read: its previous contribution
339
+ * merges as-is, which is what turns the walk from O(project) to O(changed) on a rebuild.
340
+ * Without one — the one-shot CLI paths — the keyframe scan keeps its historical early exit:
341
+ * once every declared name is found, later files skip those tests.
342
+ */
343
+ function collectSourceScans(ctx, options, cache, mtimeOf, files) {
344
+ const result = {
345
+ tokenPaths: /* @__PURE__ */ new Set(),
346
+ cssVars: /* @__PURE__ */ new Set(),
347
+ reachableFromJs: false,
348
+ elements: /* @__PURE__ */ new Set(),
349
+ keyframeHits: /* @__PURE__ */ new Set(),
350
+ accounting: {
351
+ paths: /* @__PURE__ */ new Set(),
352
+ prefixes: /* @__PURE__ */ new Set(),
353
+ declined: []
354
+ }
355
+ };
356
+ const signature = `${options.elements ? 1 : 0}\n${options.keyframeNames.join("\n")}`;
357
+ if (cache && cache.signature !== signature) {
358
+ cache.entries.clear();
359
+ cache.signature = signature;
360
+ }
361
+ const allPatterns = options.keyframeNames.map((name) => [name, new RegExp(`\\b${escapeRegExp(name)}\\b`)]);
362
+ const remaining = cache ? void 0 : new Set(options.keyframeNames);
363
+ const merge = (scan) => {
364
+ for (const path of scan.tokenPaths) result.tokenPaths.add(path);
365
+ for (const name of scan.cssVars) result.cssVars.add(name);
366
+ if (scan.reachableFromJs) result.reachableFromJs = true;
367
+ for (const element of scan.elements) result.elements.add(element);
368
+ for (const name of scan.keyframeHits) {
369
+ result.keyframeHits.add(name);
370
+ remaining?.delete(name);
371
+ }
372
+ for (const path of scan.accountingPaths) result.accounting.paths.add(path);
373
+ for (const prefix of scan.accountingPrefixes) result.accounting.prefixes.add(prefix);
374
+ result.accounting.declined.push(...scan.accountingDeclined);
375
+ };
376
+ const seen = cache ? /* @__PURE__ */ new Set() : void 0;
377
+ for (const file of files ?? ctx.getFiles()) {
378
+ const filePath = ctx.runtime.path.abs(ctx.config.cwd, file);
379
+ seen?.add(filePath);
380
+ if (cache) {
381
+ const mtime = mtimeOf?.(filePath) ?? (existsSync(filePath) ? statSync(filePath).mtimeMs : -Infinity);
382
+ const entry = cache.entries.get(filePath);
383
+ if (entry && entry.mtime === mtime) {
384
+ merge(entry.scan);
385
+ continue;
386
+ }
387
+ const scan = scanSnapshot(ctx, readSnapshot(ctx, filePath), options, allPatterns, cache.resolvedTokenReferences.get(filePath));
388
+ cache.entries.set(filePath, {
389
+ mtime,
390
+ scan
391
+ });
392
+ merge(scan);
393
+ continue;
394
+ }
395
+ const patterns = remaining.size ? allPatterns.filter(([name]) => remaining.has(name)) : [];
396
+ merge(scanSnapshot(ctx, readSnapshot(ctx, filePath), options, patterns));
397
+ }
398
+ if (cache && seen) {
399
+ for (const filePath of cache.entries.keys()) if (!seen.has(filePath)) cache.entries.delete(filePath);
400
+ for (const filePath of cache.resolvedTokenReferences.keys()) if (!seen.has(filePath)) cache.resolvedTokenReferences.delete(filePath);
401
+ }
402
+ return result;
403
+ }
404
+ /**
405
+ * Returns the custom properties left standing, for `pruneKeyframes` to root its own walk
406
+ * at — see `Generator.pruneKeyframes`. `'all'` when this pass had nothing to remove and so
407
+ * never computed the closure, which is not a missing answer but the correct one: a sheet
408
+ * nothing was removed from still declares everything it declared.
409
+ */
410
+ function pruneTokensForBuild(ctx, sheet, results, sourceScans) {
411
+ if (ctx.config.prune?.tokens === false) return ctx.pruneTokens(sheet)?.reachable ?? "all";
412
+ const unresolved = ctx.config.prune?.unresolvedPath ?? "off";
413
+ const scans = sourceScans ?? collectSourceScans(ctx, {
414
+ keyframeNames: [],
415
+ elements: false
416
+ });
417
+ const paths = new Set(scans.tokenPaths);
418
+ const vars = new Set(scans.cssVars);
419
+ const accounting = scans.accounting;
420
+ const reachable = scans.reachableFromJs;
421
+ for (const result of results) {
422
+ if (result.filePath) reconcileAccounting(accounting, resolvedTokenReferences(result), ctx.runtime.path.abs(ctx.config.cwd, result.filePath));
423
+ for (const item of result.token) for (const value of item.data ?? []) if (typeof value === "string") paths.add(value);
424
+ }
425
+ for (const name of tokenVarsFor(ctx, paths)) vars.add(name);
426
+ const declared = declaredKeeps(ctx);
427
+ for (const name of tokenVarsFor(ctx, declared)) vars.add(name);
428
+ for (const name of tokenVarsFor(ctx, accounting.paths)) vars.add(name);
429
+ const bounded = (ctx.config.prune?.keepTokens?.length ?? 0) > 0;
430
+ if (accounting.prefixes.size && (bounded || !accounting.declined.length || !reachable)) {
431
+ const prefixes = Array.from(accounting.prefixes);
432
+ const matched = [];
433
+ for (const token of ctx.tokens.allTokens) if (prefixes.some((prefix) => token.name.startsWith(prefix))) matched.push(token.name);
434
+ for (const name of tokenVarsFor(ctx, matched)) vars.add(name);
435
+ }
436
+ const failing = accounting.declined.filter(failsStrict);
437
+ const reported = accounting.declined.filter((entry) => !failsStrict(entry));
438
+ if (bounded && unresolved === "error" && accounting.declined.length) throw new BambooError("TOKEN_REFERENCE_UNRESOLVED", `${accounting.declined.length} token reference(s) could not be accounted for.\n\n${formatDeclined(ctx, accounting.declined)}\n\n\`prune.unresolvedPath: 'error'\` asserts that every token path resolves at build time, and \`prune.keepTokens\` declares where the ones that do not will land. Those are contradictory, so one has to go: drop \`keepTokens\` and respell the paths, or set \`prune: { unresolvedPath: 'warn' }\` and let the keeps cover them.`);
439
+ if (failing.length && unresolved !== "off") {
440
+ const where = `${failing.length} token reference(s) could not be resolved.\n\n${formatDeclined(ctx, failing)}\n\n`;
441
+ if (unresolved === "error") throw new BambooError("TOKEN_REFERENCE_UNRESOLVED", where + "`prune.unresolvedPath: 'error'` asserts that every token path resolves at build time. Spell the path as a string literal at the call, give a template a static prefix so it can be bounded, name the category they land in with `prune: { keepTokens: ['colors.*'] }` and drop to `prune: { unresolvedPath: 'warn' }`, or set `prune: { unresolvedPath: 'off' }` to stop asserting.");
442
+ logger.warn("tokens:unresolved", bounded ? where + "`prune.keepTokens` covers them: they keep what it names rather than every declaration in the theme. Nothing checks that they stay inside it, which is why it is yours to declare — a read landing outside the patterns loses its declaration and resolves to a `var()` with nothing behind it. Respell what you can, and widen the patterns for what you cannot." : where + "An unfollowable path keeps every token declaration. Spell the path as a string literal at the call, give a template a static prefix so it can be bounded, name the category they land in with `prune: { keepTokens: ['colors.*'] }`, or set `prune: { unresolvedPath: 'off' }` to stop reporting it.");
443
+ }
444
+ if (reported.length && unresolved !== "off") logger.warn("tokens:unresolved", `${reported.length} reference(s) could not be accounted for, so ` + (bounded ? `\`prune.keepTokens\` decides what they keep` : `every token declaration is kept`) + `.\n\n${formatDeclined(ctx, reported)}\n\nThese are shapes the build cannot follow rather than paths you can respell — a component stored post-transform, a file it could not parse, a barrel it cannot classify, a dynamic \`import()\`. ` + (bounded ? "Nothing checks that they stay inside `keepTokens`, which is why it is yours to declare: a read landing outside it loses its declaration. Narrow `include`, or widen the patterns." : "Narrow `include`, name the categories they reach with `prune: { keepTokens: [...] }`, or accept the keeps."));
445
+ return ctx.pruneTokens(sheet, vars, !bounded && accounting.declined.length > 0 && reachable)?.reachable ?? "all";
446
+ }
447
+ /**
448
+ * The dash-cased spelling of a token path, as it appears in the emitted css variable.
449
+ *
450
+ * Not a transform this applies — only one it recognises, to tell a user their pattern is
451
+ * written against the wrong side of the system. The paths are camelCase (`fontSizes.3xl`) and
452
+ * the variables are dash-cased (`--font-sizes-3xl`), so `font-sizes.*` is the natural thing to
453
+ * write after reading `styles.css` and it matches nothing at all.
454
+ */
455
+ const dashed = (path) => path.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
456
+ /**
457
+ * The token names `prune.keepTokens` names, matched against the whole theme.
458
+ *
459
+ * Patterns are anchored globs over the dotted token *path* — `colors.*`, `colors.brand.*`,
460
+ * `!colors.legacy.*`, or a bare path for one token. Matched case-sensitively, because a path is
461
+ * a key in the config rather than free text.
462
+ *
463
+ * A pattern that matches nothing is reported rather than ignored. It is nearly always a typo
464
+ * for one that would have matched, and the failure it causes is the one this whole module is
465
+ * careful about everywhere else: a declaration dropped while something still asks for it, with
466
+ * no error and no warning, resolving to a `var()` that inherits instead of falling back.
467
+ */
468
+ function declaredKeeps(ctx) {
469
+ const patterns = ctx.config.prune?.keepTokens;
470
+ if (!patterns?.length) return [];
471
+ const includes = patterns.filter((pattern) => !pattern.startsWith("!"));
472
+ if (!includes.length) logger.warn("prune:tokens", `\`prune.keepTokens\` holds only exclusions, so it keeps every token they do not name:\n\n${patterns.map((pattern) => ` ${pattern}`).join("\n")}\n\nA leading \`!\` subtracts from a selection and there is none here. Add the categories to keep — \`['colors.*', '!colors.legacy.*']\` — or use \`prune: { tokens: false }\` if keeping everything is the intent.`);
473
+ const matched = [];
474
+ const used = /* @__PURE__ */ new Set();
475
+ for (const token of ctx.tokens.allTokens) {
476
+ if (isMatch(token.name, patterns, { caseSensitive: true })) matched.push(token.name);
477
+ if (used.size === includes.length) continue;
478
+ for (const pattern of includes) if (isMatch(token.name, pattern, { caseSensitive: true })) used.add(pattern);
479
+ }
480
+ const unused = includes.filter((pattern) => !used.has(pattern));
481
+ if (unused.length) {
482
+ const paths = ctx.tokens.allTokens.map((token) => token.name);
483
+ const respell = unused.map((pattern) => {
484
+ const hit = paths.find((path) => isMatch(dashed(path), pattern, { caseSensitive: true }));
485
+ if (!hit) return ` ${pattern}`;
486
+ return ` ${pattern} — matches \`${dashed(hit)}\`, which is the css variable's spelling. Write the token path: \`${hit.split(".")[0]}.*\``;
487
+ }).join("\n");
488
+ logger.warn("prune:tokens", `${unused.length} \`prune.keepTokens\` pattern(s) match no token in this theme:\n\n${respell}\n\nA pattern is an anchored glob over the dotted token *path* — \`colors.*\`, not \`colors\`, and \`fontSizes.*\` rather than the \`--font-sizes-\` spelling the css variable uses. One that matches nothing keeps nothing, which is silent everywhere except here.`);
489
+ }
490
+ return matched;
491
+ }
492
+ /** The custom properties a set of token paths resolves to. */
493
+ function tokenVarsFor(ctx, paths) {
494
+ const vars = /* @__PURE__ */ new Set();
495
+ for (const path of paths) {
496
+ if (!path) continue;
497
+ const ref = ctx.tokens.view.getVar(path);
498
+ if (!ref) continue;
499
+ for (const name of cssVarRefs(ref)) vars.add(name);
500
+ }
501
+ return vars;
502
+ }
503
+ /** Where to look, grouped by file. The surrounding text differs by whether this throws. */
504
+ function formatDeclined(ctx, declined) {
505
+ const byFile = /* @__PURE__ */ new Map();
506
+ for (const entry of declined) {
507
+ const list = byFile.get(entry.filePath) ?? [];
508
+ list.push(entry);
509
+ byFile.set(entry.filePath, list);
510
+ }
511
+ return Array.from(byFile.entries()).map(([filePath, entries]) => {
512
+ return [` ${filePath.startsWith(ctx.config.cwd) ? filePath.slice(ctx.config.cwd.length + 1) : filePath}`, ...entries.map((entry) => ` ${entry.line}: ${entry.reason}`)].join("\n");
513
+ }).join("\n");
514
+ }
515
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
516
+ /** The keyframes the theme declares — the allow-list `pruneKeyframes` works against. */
517
+ const keyframeNames = (ctx) => Object.keys(ctx.config.theme?.keyframes ?? {});
518
+ /**
519
+ * The HTML element names the source renders.
520
+ *
521
+ * A textual scan for an opening tag, over the same files the other collectors read. Matching
522
+ * `<tag` rather than parsing: a template can spell an element in more ways than a parser of
523
+ * any one framework's syntax would find, and over-reporting an element only keeps a reset
524
+ * rule that would otherwise go.
525
+ *
526
+ * Lowercase-initial only, so a JSX component (`<Button />`) is not mistaken for an element.
527
+ * That cuts the other way too — a component rendering `<button>` inside a dependency is
528
+ * invisible here, which is why `preflight.prune` is opt-in.
529
+ *
530
+ * The commoner blind spot is nearer than a dependency: this reads `include`, and `include`
531
+ * conventionally covers components rather than markup. An entry template — `index.html`,
532
+ * `app.html` — is where `<table>`, `<noscript>` and a page's static markup usually live, and a
533
+ * glob rooted at `./src` does not match it, so every element appearing only there loses its
534
+ * reset. Nothing here can detect that; the file simply is not in the list. Listing it in
535
+ * `include` fixes it, because this reads whatever `include` covers rather than only what the
536
+ * parser understands — `token-references.test.ts` pins both halves.
537
+ *
538
+ * Reading the raw file as well as the parsed copy is what makes an SFC work here; see
539
+ * `sourceTexts`. On a healthy `.svelte` file the two agree on everything but `<script>`, so
540
+ * the raw read earns its place only when a transform fails -- and there it is the difference
541
+ * between the file's elements and none of them.
542
+ */
543
+ function collectRenderedElements(ctx) {
544
+ const found = /* @__PURE__ */ new Set();
545
+ for (const content of sourceTexts(ctx)) for (const match of content.matchAll(/<\s*([a-z][\w-]*)(?=[\s/>]|$)/g)) found.add(match[1].toLowerCase());
546
+ return found;
547
+ }
548
+ //#endregion
549
+ //#region src/assemble-sheet.ts
550
+ /**
551
+ * One stylesheet from an already-extracted encoder.
552
+ *
553
+ * Vite, `bamboo cssgen`, and the CLI `bamboo` command all finish here so a recipe lowered to
554
+ * atoms cannot have a different sheet depending on which integration asked for it.
555
+ */
556
+ const assembleExtractedSheet = (ctx, { layerParams = false, sourceScanCache, mtimeOf, sourceInventory, parserResults = [], prunePreflight = true } = {}) => {
557
+ ctx.encoder.atomizeObservedRecipes();
558
+ const sheet = ctx.createSheet();
559
+ if (layerParams) {
560
+ const recipeLayer = ctx.config.layers?.recipes ?? "recipes";
561
+ sheet.layers.root.prepend(`@layer ${sheet.layers.layerNames.filter((name) => name !== recipeLayer).join(", ")};`);
562
+ }
563
+ ctx.appendBaselineCss(sheet, { atomizeRecipes: true });
564
+ const collectElements = prunePreflight && prunesPreflight(ctx.config.preflight);
565
+ const pruneKeyframes = Boolean(ctx.config.prune?.keyframes);
566
+ const declaredKeyframes = pruneKeyframes ? keyframeNames(ctx) : [];
567
+ const scans = ctx.config.prune?.tokens !== false || collectElements || pruneKeyframes ? collectSourceScans(ctx, {
568
+ keyframeNames: declaredKeyframes,
569
+ elements: collectElements
570
+ }, sourceScanCache, mtimeOf, sourceInventory) : void 0;
571
+ const reachableVars = pruneTokensForBuild(ctx, sheet, parserResults, scans);
572
+ if (collectElements && scans) ctx.prunePreflight(sheet, scans.elements);
573
+ if (pruneKeyframes && scans) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
574
+ return sheet;
575
+ };
576
+ //#endregion
577
+ //#region src/analyze.ts
578
+ /**
579
+ * `analyze` is one CLI command, but this module is reachable from `@bamboocss/node`'s index,
580
+ * so a static import made every consumer of that index — the CLI on any command, and the Vite
581
+ * plugin on every build — load the reporter and its table formatters to run neither. Loading
582
+ * it here keeps that off the path of everything that is not the `analyze` command.
583
+ */
584
+ async function analyze(ctx, options = {}) {
585
+ const { Reporter, formatRecipeReport, formatTokenReport } = await import("@bamboocss/reporter");
586
+ const { logger: reporterLogger } = await import("@bamboocss/logger");
587
+ reporterLogger.level = logger.level;
588
+ const parserResults = [];
589
+ const reporter = new Reporter(ctx, {
590
+ parserOptions: ctx.parserOptions,
591
+ parseFile: (file) => ctx.parseFile(file),
592
+ prepare: (files) => ctx.prepareNativeExtraction(files),
593
+ getRelativePath: ctx.runtime.path.relative,
594
+ getFiles: ctx.getFiles,
595
+ ...options,
596
+ onResult: (file, result) => {
597
+ parserResults.push(result);
598
+ options.onResult?.(file, result);
599
+ }
600
+ });
601
+ reporter.init();
602
+ const writeJson = (filePath, value) => {
603
+ ctx.runtime.fs.ensureDirSync(ctx.runtime.path.dirname(filePath));
604
+ return ctx.runtime.fs.writeFile(filePath, JSON.stringify(value, replacer, 2));
605
+ };
606
+ return {
607
+ getRecipeReport(format = "table") {
608
+ const report = reporter.getRecipeReport();
609
+ return {
610
+ report,
611
+ formatted: formatRecipeReport(report, format)
612
+ };
613
+ },
614
+ getTokenReport(format = "table") {
615
+ const report = reporter.getTokenReport();
616
+ return {
617
+ report,
618
+ formatted: formatTokenReport(report.getSummary(), format)
619
+ };
620
+ },
621
+ /** Every pattern the config defines, and how often each is called. */
622
+ getPatternReport: () => reporter.getPatternReport(),
623
+ /** Every style property written, and how often. */
624
+ getUtilityReport: () => reporter.getUtilityReport(),
625
+ /** Every keyframe the theme defines, and how often an animation names it. */
626
+ getKeyframeReport: () => reporter.getKeyframeReport(),
627
+ /**
628
+ * The configured names no source uses, of the kinds asked for.
629
+ *
630
+ * Tokens and keyframes are what the build's own prune removes, run with every prune on
631
+ * whatever the config says, so a name here is one the stylesheet already ships without.
632
+ * Anything the prune keeps for a reader it cannot follow — a `token()` path built at runtime,
633
+ * a theme, a `keepTokens` pattern — is kept here too, and not listed: being told a token is
634
+ * unused when something still asks for it is worse than not being told at all. A recipe or a
635
+ * pattern is one no source calls and `staticCss` does not emit regardless.
636
+ *
637
+ * Read off a sheet of its own. The prune's settings are laid over the context's while it is
638
+ * built, and `unresolvedPath` is off for it: that one only decides how loudly the prune says
639
+ * what it could not read, and a project that does not prune tokens never hears it.
640
+ */
641
+ getUnused(kinds = [
642
+ "tokens",
643
+ "recipes",
644
+ "patterns",
645
+ "keyframes"
646
+ ]) {
647
+ const unused = {
648
+ tokens: [],
649
+ recipes: [],
650
+ patterns: [],
651
+ keyframes: []
652
+ };
653
+ if (kinds.includes("tokens") || kinds.includes("keyframes")) {
654
+ const prune = {
655
+ ...ctx.config.prune,
656
+ keyframes: true,
657
+ unresolvedPath: "off"
658
+ };
659
+ if (prune.tokens === false) delete prune.tokens;
660
+ const configured = ctx.config.prune;
661
+ ctx.config.prune = prune;
662
+ let sheet;
663
+ try {
664
+ sheet = assembleExtractedSheet(ctx, {
665
+ parserResults,
666
+ prunePreflight: false
667
+ });
668
+ } finally {
669
+ ctx.config.prune = configured;
670
+ }
671
+ const declared = /* @__PURE__ */ new Set();
672
+ const keyframes = /* @__PURE__ */ new Set();
673
+ sheet.layers.tokens.walkDecls((decl) => {
674
+ if (decl.prop.startsWith("--")) declared.add(decl.prop);
675
+ });
676
+ sheet.layers.tokens.walkAtRules(/keyframes$/, (rule) => {
677
+ keyframes.add(rule.params.trim().replace(/^(["'])(.*)\1$/, "$2").replace(/\\(.)/g, "$1"));
678
+ });
679
+ const declarable = /* @__PURE__ */ new Set();
680
+ for (const vars of ctx.tokens.view.vars.values()) for (const name of vars.keys()) declarable.add(name);
681
+ const tokens = /* @__PURE__ */ new Set();
682
+ for (const token of ctx.tokens.allTokens) {
683
+ const { isVirtual, isNegative, category } = token.extensions;
684
+ if (isVirtual || isNegative || category === "breakpoints" || token.name.startsWith("sizes.breakpoint-")) continue;
685
+ const name = token.extensions.var;
686
+ if (declarable.has(name) && !declared.has(name)) tokens.add(token.name);
687
+ }
688
+ if (kinds.includes("tokens")) unused.tokens = [...tokens].sort();
689
+ if (kinds.includes("keyframes")) unused.keyframes = Object.keys(ctx.config.theme?.keyframes ?? {}).filter((name) => !keyframes.has(name)).sort();
690
+ }
691
+ const { staticCss } = ctx.config;
692
+ const emitted = (rules) => (name) => rules === "*" || rules != null && typeof rules === "object" && name in rules;
693
+ if (kinds.includes("recipes")) {
694
+ const called = new Set(reporter.getRecipeReport().map((entry) => entry.recipeName));
695
+ const inConfig = emitted(staticCss?.recipes);
696
+ const { recipes = {}, slotRecipes = {} } = ctx.config.theme ?? {};
697
+ const ofItself = (name) => Boolean((recipes[name] ?? slotRecipes[name])?.staticCss?.length);
698
+ unused.recipes = [...ctx.recipes.keys].filter((name) => !called.has(name) && !inConfig(name) && !ofItself(name)).sort();
699
+ }
700
+ if (kinds.includes("patterns")) {
701
+ const kept = emitted(staticCss?.patterns);
702
+ unused.patterns = reporter.getPatternReport().filter((entry) => !entry.usedCount && !kept(entry.patternName)).map((entry) => entry.patternName).sort();
703
+ }
704
+ return unused;
705
+ },
706
+ /** The names as JSON, of the kinds `getUnused` was asked for. */
707
+ writeUnused(filePath, unused) {
708
+ return writeJson(filePath, unused);
709
+ },
710
+ writeReport(filePath) {
711
+ return writeJson(filePath, reporter.report);
712
+ }
713
+ };
714
+ }
715
+ function replacer(_, value) {
716
+ if (value instanceof Set) return Array.from(value);
717
+ if (value instanceof Map) return Object.fromEntries(value);
718
+ return value;
719
+ }
720
+ //#endregion
721
+ //#region src/build-info.ts
722
+ async function buildInfo(ctx, outfile) {
723
+ const { filesWithCss, files } = ctx.parseFiles();
724
+ logger.info("cli", `Found ${colors.bold(`${filesWithCss.length}/${files.length}`)} files using Bamboo`);
725
+ const { minify, staticCss } = ctx.config;
726
+ logger.info("cli", `Writing ${minify ? "[min] " : " "}${colors.bold(outfile)}`);
727
+ if (staticCss) {
728
+ logger.info("cli", "Adding staticCss definitions...");
729
+ ctx.staticCss.process(staticCss);
730
+ }
731
+ const output = JSON.stringify(ctx.encoder.toJSON(), null, minify ? 0 : 2);
732
+ ctx.output.ensure(outfile, process.cwd());
733
+ await ctx.runtime.fs.writeFile(outfile, output);
734
+ logger.info("cli", "Done!");
735
+ }
736
+ //#endregion
737
+ //#region src/codegen.ts
738
+ /**
739
+ * What a rebuild after a config edit writes: the artifacts the edit changed, or every artifact,
740
+ * as a run from cold would, when the edit changed what all of them are written from.
741
+ */
742
+ const artifactsToRebuild = (affected) => changesEveryArtifact(affected.diffs) ? void 0 : Array.from(affected.artifacts);
743
+ async function codegen(ctx, ids) {
744
+ const { default: pLimit } = await import("p-limit");
745
+ const limit = pLimit(20);
746
+ if (ctx.config.clean && !ids) ctx.output.empty();
747
+ let artifacts = ctx.getArtifacts(ids);
748
+ let hookFiltered = false;
749
+ if (ctx.hooks["codegen:prepare"]) {
750
+ const results = await ctx.hooks["codegen:prepare"]?.({
751
+ changed: ids,
752
+ artifacts
753
+ });
754
+ if (results) {
755
+ artifacts = results;
756
+ hookFiltered = true;
757
+ }
758
+ }
759
+ const promises = artifacts.map((artifact) => limit(() => ctx.output.write(artifact)));
760
+ await Promise.allSettled(promises);
761
+ if (!hookFiltered) ctx.output.prune(ids ? ctx.getArtifacts() : artifacts);
762
+ await ctx.hooks["codegen:done"]?.({ changed: ids });
763
+ return {
764
+ box: ctx.initMessage(),
765
+ msg: ctx.messages.artifactsGenerated()
766
+ };
767
+ }
768
+ //#endregion
769
+ //#region src/astro-template.ts
770
+ /** HTML elements that take no children, and so no closing tag. */
771
+ const VOID_ELEMENTS = new Set([
772
+ "area",
773
+ "base",
774
+ "br",
775
+ "col",
776
+ "embed",
777
+ "hr",
778
+ "img",
779
+ "input",
780
+ "link",
781
+ "meta",
782
+ "param",
783
+ "source",
784
+ "track",
785
+ "wbr"
786
+ ]);
787
+ /** Elements whose content is text, in which a `{` is no expression. */
788
+ const RAW_TEXT_ELEMENTS = new Set(["script", "style"]);
789
+ /** Words after which an expression starts, so that a `/` begins a regex rather than divides. */
790
+ const KEYWORDS_BEFORE_EXPRESSION = new Set([
791
+ "await",
792
+ "case",
793
+ "delete",
794
+ "do",
795
+ "else",
796
+ "in",
797
+ "instanceof",
798
+ "new",
799
+ "of",
800
+ "return",
801
+ "throw",
802
+ "typeof",
803
+ "void",
804
+ "yield"
805
+ ]);
806
+ /** Words that carry an expression on past an element, `<a /> as any`, rather than begin text. */
807
+ const WORDS_AFTER_OPERAND = new Set([
808
+ "as",
809
+ "in",
810
+ "instanceof",
811
+ "satisfies"
812
+ ]);
813
+ /** What Astro reads in a regex as its own syntax, as an escape matching the same character. */
814
+ const ESCAPES$1 = {
815
+ "{": "\\x7b",
816
+ "}": "\\x7d",
817
+ "`": "\\x60",
818
+ "'": "\\x27",
819
+ "\"": "\\x22"
820
+ };
821
+ const QUANTIFIER = /\{\d+(?:,\d*)?\}/y;
822
+ const TAG_NAME = /[^\s/>{]*/y;
823
+ const ATTRIBUTE_NAME = /[^\s=/>{"'`]+/y;
824
+ /** An unquoted attribute value, which ends at a space or the tag's end: `/>` included. */
825
+ const UNQUOTED_VALUE = /(?:[^\s/>]|\/(?!>))*/y;
826
+ const WORD = /[\p{ID_Continue}$‌‍]+/uy;
827
+ const SPACE = /\s/;
828
+ /** A character that carries an expression on past an operand: an operator or a closing bracket. */
829
+ const CONTINUATION = /[)\]},;:?.&|=!+\-*/%^~>]/;
830
+ const matchAt = (pattern, source, at) => {
831
+ pattern.lastIndex = at;
832
+ return pattern.exec(source)?.[0] ?? "";
833
+ };
834
+ /** A regex's body with what Astro reads as syntax escaped, or `undefined` if nothing in it is. */
835
+ const escapeRegexBody = (body) => {
836
+ if (!/[{}`'"]/.test(body)) return;
837
+ let escaped = "";
838
+ let inClass = false;
839
+ for (let i = 0; i < body.length; i++) {
840
+ const char = body[i];
841
+ if (char === "\\") {
842
+ escaped += char + (body[i + 1] ?? "");
843
+ i++;
844
+ continue;
845
+ }
846
+ if (char === "[") inClass = true;
847
+ else if (char === "]") inClass = false;
848
+ else if (char === "{" && !inClass) {
849
+ const quantifier = matchAt(QUANTIFIER, body, i);
850
+ if (quantifier) {
851
+ escaped += quantifier;
852
+ i += quantifier.length - 1;
853
+ continue;
854
+ }
855
+ }
856
+ escaped += ESCAPES$1[char] ?? char;
857
+ }
858
+ return escaped === body ? void 0 : escaped;
859
+ };
860
+ /**
861
+ * Where an Astro component's template starts: after its frontmatter, if it has one. The fence
862
+ * that ends it is a line of its own, and a `---` in a string or a comment of the frontmatter is
863
+ * the frontmatter's.
864
+ */
865
+ const templateStart = (source) => {
866
+ const open = /^\s*---/.exec(source);
867
+ if (!open) return 0;
868
+ const length = source.length;
869
+ for (let i = open[0].length; i < length; i++) {
870
+ const char = source[i];
871
+ if (char === "\n" && source.startsWith("---", i + 1) && /^[ \t]*(?:\r?\n|$)/.test(source.slice(i + 4, i + 6))) return i + 4;
872
+ if (char === "\"" || char === "'" || char === "`") {
873
+ for (i++; i < length && source[i] !== char; i++) if (source[i] === "\\") i++;
874
+ } else if (char === "/" && source[i + 1] === "/") while (i < length && source[i + 1] !== "\n") i++;
875
+ else if (char === "/" && source[i + 1] === "*") {
876
+ const end = source.indexOf("*/", i + 2);
877
+ i = end === -1 ? length : end + 1;
878
+ }
879
+ }
880
+ return length;
881
+ };
882
+ /** An Astro component, with its template written as `@astrojs/compiler` turns into valid TSX. */
883
+ const prepareAstroTemplate = (source) => {
884
+ const length = source.length;
885
+ const edits = [];
886
+ let lowered;
887
+ const skipPast = (token, from) => {
888
+ const at = source.indexOf(token, from);
889
+ return at === -1 ? length : at + token.length;
890
+ };
891
+ const skipSpace = (from) => {
892
+ let i = from;
893
+ while (i < length && SPACE.test(source[i])) i++;
894
+ return i;
895
+ };
896
+ const startsElement = (at) => source[at] === "<" && /[A-Za-z>]/.test(source[at + 1] ?? "");
897
+ /** A JavaScript string, from its opening quote: it ends at the line, if its quote does not. */
898
+ const string = (at) => {
899
+ const quote = source[at];
900
+ for (let i = at + 1; i < length; i++) {
901
+ const char = source[i];
902
+ if (char === "\\") i++;
903
+ else if (char === quote) return i + 1;
904
+ else if (char === "\n") return i;
905
+ }
906
+ return length;
907
+ };
908
+ /** A template literal, from after its backtick, with the expressions it holds. */
909
+ const template = (at) => {
910
+ let i = at;
911
+ while (i < length) {
912
+ const char = source[i];
913
+ if (char === "\\") i += 2;
914
+ else if (char === "`") return i + 1;
915
+ else if (char === "$" && source[i + 1] === "{") i = expression(i + 2);
916
+ else i++;
917
+ }
918
+ return length;
919
+ };
920
+ /** A regex literal, from its `/`, or `-1` if there is none: a regex ends on its line. */
921
+ const regex = (at) => {
922
+ let inClass = false;
923
+ let i = at + 1;
924
+ for (; i < length; i++) {
925
+ const char = source[i];
926
+ if (char === "\n" || char === "\r") return -1;
927
+ if (char === "\\") i++;
928
+ else if (char === "[") inClass = true;
929
+ else if (char === "]") inClass = false;
930
+ else if (char === "/" && !inClass) break;
931
+ }
932
+ if (i >= length) return -1;
933
+ const escaped = escapeRegexBody(source.slice(at + 1, i));
934
+ if (escaped !== void 0) edits.push([
935
+ at + 1,
936
+ i,
937
+ escaped
938
+ ]);
939
+ i++;
940
+ while (i < length && /[a-z]/i.test(source[i])) i++;
941
+ return i;
942
+ };
943
+ /** Whether what is at `at`, after an element, carries an expression on rather than adds a node. */
944
+ const continuesExpression = (at) => {
945
+ const char = source[at];
946
+ if (char === "<") return !startsElement(at) && !source.startsWith("<!--", at);
947
+ if (CONTINUATION.test(char)) return true;
948
+ return WORDS_AFTER_OPERAND.has(matchAt(WORD, source, at));
949
+ };
950
+ /**
951
+ * Nodes an expression starts with, from the `<` of the first, to where the expression goes on:
952
+ * after that element, or at the `closer` that ends the nodes side by side with it, which are put
953
+ * in one fragment.
954
+ */
955
+ const nodes = (start, closer) => {
956
+ const first = element(start, true);
957
+ const next = skipSpace(first);
958
+ if (next >= length || continuesExpression(next)) return first;
959
+ let i = next;
960
+ let depth = 0;
961
+ while (i < length) {
962
+ const char = source[i];
963
+ if (char === "{") i = expression(i + 1);
964
+ else if (char === closer && depth === 0) {
965
+ edits.push([
966
+ start,
967
+ start,
968
+ "<>"
969
+ ], [
970
+ i,
971
+ i,
972
+ "</>"
973
+ ]);
974
+ return i;
975
+ } else if (char === "}") return i;
976
+ else if (char === "(") {
977
+ depth++;
978
+ i++;
979
+ } else if (char === ")") {
980
+ depth = Math.max(0, depth - 1);
981
+ i++;
982
+ } else if (char === "<" && source.startsWith("<!--", i)) i = skipPast("-->", i + 4);
983
+ else if (char === "<" && source[i + 1] === "/") return i;
984
+ else if (startsElement(i)) i = element(i, true);
985
+ else i++;
986
+ }
987
+ return length;
988
+ };
989
+ /** An expression, from after its `{`, to after the `}` that ends it. */
990
+ const expression = (at) => {
991
+ const first = skipSpace(at);
992
+ let i = startsElement(first) ? nodes(first, "}") : first;
993
+ let depth = 0;
994
+ let operand = i !== first;
995
+ let property = false;
996
+ while (i < length) {
997
+ const char = source[i];
998
+ if (SPACE.test(char)) {
999
+ i++;
1000
+ continue;
1001
+ }
1002
+ if (char === "/") {
1003
+ const next = source[i + 1];
1004
+ if (next === "/") i = skipPast("\n", i + 2);
1005
+ else if (next === "*") i = skipPast("*/", i + 2);
1006
+ else {
1007
+ const end = operand ? -1 : regex(i);
1008
+ operand = end !== -1;
1009
+ i = end === -1 ? i + 1 : end;
1010
+ }
1011
+ continue;
1012
+ }
1013
+ if (char === "\"" || char === "'") {
1014
+ i = string(i);
1015
+ operand = true;
1016
+ } else if (char === "`") {
1017
+ i = template(i + 1);
1018
+ operand = true;
1019
+ } else if (char === "(") {
1020
+ depth++;
1021
+ const inner = skipSpace(i + 1);
1022
+ operand = startsElement(inner);
1023
+ i = operand ? nodes(inner, ")") : i + 1;
1024
+ } else if (char === "{" || char === "[") {
1025
+ depth++;
1026
+ i++;
1027
+ operand = false;
1028
+ } else if (char === "}") {
1029
+ if (depth === 0) return i + 1;
1030
+ depth--;
1031
+ i++;
1032
+ operand = true;
1033
+ } else if (char === ")" || char === "]") {
1034
+ depth = Math.max(0, depth - 1);
1035
+ i++;
1036
+ operand = true;
1037
+ } else if (char === "<" && source[i + 1] === "/") {
1038
+ i = skipPast(">", i + 2);
1039
+ operand = true;
1040
+ } else if (char === "<" && source.startsWith("<!--", i)) {
1041
+ i = skipPast("-->", i + 4);
1042
+ operand = true;
1043
+ } else if (char === "<" && !operand && startsElement(i)) {
1044
+ i = element(i, true);
1045
+ operand = true;
1046
+ } else {
1047
+ const word = matchAt(WORD, source, i);
1048
+ if (word) {
1049
+ i += word.length;
1050
+ operand = property || !KEYWORDS_BEFORE_EXPRESSION.has(word);
1051
+ } else if (operand && (char === "!" || (char === "+" || char === "-") && source[i + 1] === char)) i += char === "!" ? 1 : 2;
1052
+ else {
1053
+ i++;
1054
+ operand = false;
1055
+ }
1056
+ property = !word && char === ".";
1057
+ continue;
1058
+ }
1059
+ property = false;
1060
+ }
1061
+ return length;
1062
+ };
1063
+ /**
1064
+ * An element's children, to after its closing tag. The closing tag of an element above it ends
1065
+ * it too, as HTML closes what is left open, and so does the `}` of the expression it is in.
1066
+ */
1067
+ const children = (at, name, inExpression) => {
1068
+ let i = at;
1069
+ while (i < length) {
1070
+ const char = source[i];
1071
+ if (char === "{") i = expression(i + 1);
1072
+ else if (char === "}" && inExpression) return i;
1073
+ else if (char === "<" && source.startsWith("<!--", i)) i = skipPast("-->", i + 4);
1074
+ else if (char === "<" && source[i + 1] === "/") {
1075
+ const closing = matchAt(TAG_NAME, source, i + 2);
1076
+ if (name !== void 0 && closing.toLowerCase() !== name.toLowerCase()) return i;
1077
+ i = skipPast(">", i + 2);
1078
+ if (name !== void 0) return i;
1079
+ } else if (startsElement(i)) i = element(i, inExpression);
1080
+ else i++;
1081
+ }
1082
+ return length;
1083
+ };
1084
+ /** An element, from its `<`: its attributes' expressions, and its children unless they are text. */
1085
+ const element = (at, inExpression) => {
1086
+ const name = matchAt(TAG_NAME, source, at + 1);
1087
+ let raw = RAW_TEXT_ELEMENTS.has(name.toLowerCase());
1088
+ let i = at + 1 + name.length;
1089
+ for (;;) {
1090
+ i = skipSpace(i);
1091
+ if (i >= length) return length;
1092
+ const char = source[i];
1093
+ if (char === ">") {
1094
+ i++;
1095
+ break;
1096
+ }
1097
+ if (char === "/" && source[i + 1] === ">") return i + 2;
1098
+ if (char === "{") {
1099
+ i = expression(i + 1);
1100
+ continue;
1101
+ }
1102
+ const attribute = matchAt(ATTRIBUTE_NAME, source, i);
1103
+ if (!attribute) {
1104
+ i++;
1105
+ continue;
1106
+ }
1107
+ if (attribute === "is:raw") raw = true;
1108
+ i = skipSpace(i + attribute.length);
1109
+ if (source[i] !== "=") continue;
1110
+ i = skipSpace(i + 1);
1111
+ const quote = source[i];
1112
+ if (quote === "\"" || quote === "'") i = skipPast(quote, i + 1);
1113
+ else if (quote === "`") i = template(i + 1);
1114
+ else if (quote === "{") i = expression(i + 1);
1115
+ else i += matchAt(UNQUOTED_VALUE, source, i).length;
1116
+ }
1117
+ if (raw) {
1118
+ lowered ??= source.toLowerCase();
1119
+ const close = lowered.indexOf(`</${name.toLowerCase()}`, i);
1120
+ return close === -1 ? length : skipPast(">", close);
1121
+ }
1122
+ if (VOID_ELEMENTS.has(name.toLowerCase())) return i;
1123
+ return children(i, name, inExpression);
1124
+ };
1125
+ children(templateStart(source), void 0, false);
1126
+ if (!edits.length) return source;
1127
+ edits.sort((a, b) => a[0] - b[0]);
1128
+ let prepared = "";
1129
+ let from = 0;
1130
+ for (const [start, end, text] of edits) {
1131
+ prepared += source.slice(from, start) + text;
1132
+ from = end;
1133
+ }
1134
+ return prepared + source.slice(from);
1135
+ };
1136
+ //#endregion
1137
+ //#region src/native-extractor.ts
1138
+ const nativeBinaryName = () => {
1139
+ if (process.platform === "darwin" && process.arch === "arm64") return "darwin-arm64.node";
1140
+ if (process.platform === "darwin" && process.arch === "x64") return "darwin-x64.node";
1141
+ if (process.platform === "linux" && process.arch === "arm64") return "linux-arm64-gnu.node";
1142
+ if (process.platform === "linux" && process.arch === "x64") return "linux-x64-gnu.node";
1143
+ if (process.platform === "win32" && process.arch === "x64") return "win32-x64-msvc.node";
1144
+ };
1145
+ /** Load the required Rust extractor from the workspace or the published prebuild directory. */
1146
+ const loadNativeExtractor = () => {
1147
+ const nativeRequire = createRequire(import.meta.url);
1148
+ try {
1149
+ return nativeRequire("@bamboocss/native-extractor");
1150
+ } catch (workspaceError) {
1151
+ const binary = nativeBinaryName();
1152
+ if (!binary) throw new BambooError("NATIVE_EXTRACTION", `Native extraction is not available for ${process.platform}-${process.arch}.`, { cause: workspaceError });
1153
+ try {
1154
+ return nativeRequire(join(dirname(fileURLToPath(import.meta.url)), "native", binary));
1155
+ } catch (publishedError) {
1156
+ throw new BambooError("NATIVE_EXTRACTION", `Failed to load the native extractor binary ${binary}.`, { cause: publishedError });
1157
+ }
1158
+ }
1159
+ };
1160
+ //#endregion
1161
+ //#region src/astro-to-tsx.ts
1162
+ /**
1163
+ * The compilers to read `.astro` files with, of those `require` can load.
1164
+ *
1165
+ * `@astrojs/compiler-rs` first. Astro 7 depends on it rather than on `@astrojs/compiler`, so a
1166
+ * project on it had no compiler here, and each of its `.astro` files was read as empty, without a
1167
+ * word. Its `transform` is synchronous, as `parser:before` is, and reads a template as Astro's own
1168
+ * build does. `@astrojs/compiler`, which Astro 6 and before depend on, through the `sync` entry for
1169
+ * the same reason. Each is an optional peer: a project with `.astro` files has the one its `astro`
1170
+ * depends on.
1171
+ *
1172
+ * One that is there and fails to load — a platform binary missing, a Node with no `require` of an
1173
+ * ES module — is said, rather than read as one to install.
1174
+ */
1175
+ const loadAstroCompiler = (require = createRequire(import.meta.url)) => {
1176
+ const failures = [];
1177
+ const load = (id) => {
1178
+ try {
1179
+ return require(id);
1180
+ } catch (error) {
1181
+ if (!(error.code === "MODULE_NOT_FOUND" && String(error).includes(`'${id}'`))) failures.push(`\`${id}\` is installed and failed to load: ${error.message ?? error}`);
1182
+ return;
1183
+ }
1184
+ };
1185
+ const transform = load("@astrojs/compiler-rs")?.transform;
1186
+ const convertToTSX = load("@astrojs/compiler/sync")?.convertToTSX;
1187
+ if (transform || convertToTSX) {
1188
+ for (const failure of failures) logger.debug("astro", failure);
1189
+ return {
1190
+ transform,
1191
+ convertToTSX
1192
+ };
1193
+ }
1194
+ logger.warn("astro", "No Astro compiler could be loaded, so nothing in a `.astro` file is extracted. " + ["Install `@astrojs/compiler-rs` for Astro 7, or `@astrojs/compiler` for Astro 6 and before.", ...failures].join("\n"));
1195
+ return null;
1196
+ };
1197
+ /**
1198
+ * Loaded the first time a `.astro` file is actually parsed. Every build carries this hook, so a
1199
+ * static import would make every build pay to load a compiler most projects never call — the
1200
+ * reason the Vue and Svelte plugins load theirs lazily too.
1201
+ */
1202
+ let compiler;
1203
+ const loaded = () => compiler === void 0 ? compiler = loadAstroCompiler() : compiler;
1204
+ /** The inline source map Astro appends, which nothing downstream reads. */
1205
+ const SOURCE_MAP_COMMENT = /\n\/\/# sourceMappingURL=data:[^\n]*\s*$/;
1206
+ /** A static `import` statement starting a line: a binding clause and `from`, or neither. */
1207
+ const IMPORT_STATEMENT = /^[ \t]*import\s+(?:type\s+)?(?:[\w$*{}\s,]+?\s+from\s+)?(['"])[^'"\n]+\1[ \t]*;?/gm;
1208
+ /**
1209
+ * A bundled `<script>` as module code: its imports at the top level, where they bind, and the
1210
+ * rest in a block of its own, so its declarations do not meet the frontmatter's.
1211
+ */
1212
+ const moduleCode = (script) => {
1213
+ const imports = [];
1214
+ const body = script.replace(IMPORT_STATEMENT, (statement) => {
1215
+ imports.push(statement.trim());
1216
+ return "";
1217
+ });
1218
+ return `${imports.join("\n")}\n${/^[ \t]*export\b/m.test(body) ? body : `{\n${body}\n}`}`;
1219
+ };
1220
+ /**
1221
+ * The component, and each `<script>` Astro bundles as module code after it.
1222
+ *
1223
+ * Neither compiler's output holds a bundled script where its calls are read: the TSX has it inside
1224
+ * an arrow function, where its imports bind nothing, and the compiled module only names it. So no
1225
+ * call in one was seen — while Vite compiles the script, and its classes shipped with no rule.
1226
+ */
1227
+ const withScripts = (code, scripts) => scripts.length ? `${code}\n${scripts.map(moduleCode).join("\n")}\n` : code;
1228
+ /** Whether code parses as extraction will parse it: a parse error there fails the whole file. */
1229
+ const parses = (code) => {
1230
+ try {
1231
+ return loadNativeExtractor().analyze("component.tsx", code, []).errors.length === 0;
1232
+ } catch {
1233
+ return true;
1234
+ }
1235
+ };
1236
+ const transformed = (transform, code, filename) => {
1237
+ let result;
1238
+ try {
1239
+ result = transform(code, { filename });
1240
+ } catch {
1241
+ return;
1242
+ }
1243
+ if (!result.code) return;
1244
+ const scripts = (result.scripts ?? []).flatMap((script) => script.type === "inline" && script.code ? [script.code] : []);
1245
+ return withScripts(result.code, scripts);
1246
+ };
1247
+ const converted = (convertToTSX, code, filename) => {
1248
+ let result;
1249
+ try {
1250
+ result = convertToTSX(code, { filename });
1251
+ } catch {
1252
+ return;
1253
+ }
1254
+ const scripts = (result.metaRanges?.scripts ?? []).flatMap((script) => script.type === "processed-module" ? [script.content] : []);
1255
+ return withScripts(result.code.replace(SOURCE_MAP_COMMENT, "\n"), scripts);
1256
+ };
1257
+ /**
1258
+ * A `.astro` file as code the extractor can parse.
1259
+ *
1260
+ * Nothing converted these before: the TypeScript parser read the raw file, recovering from the
1261
+ * `---` fences and the template well enough to find calls in it. Oxc, which does all extraction
1262
+ * now, rejects that text, failing the build on every Astro component.
1263
+ *
1264
+ * Either compiler keeps every expression the template evaluates, `class={css({ … })}` included.
1265
+ * `@astrojs/compiler-rs` compiles the component to the module Astro serves. A component it cannot
1266
+ * read — one in a project on Astro 6, which takes templates Astro 7 does not — is converted by
1267
+ * `@astrojs/compiler` instead, when that is there too, to the TSX Astro's language tools
1268
+ * type-check against: the frontmatter as module code, the template as JSX in a fragment.
1269
+ *
1270
+ * That conversion misreads two shapes of template, and the TSX it gives for them does not parse;
1271
+ * see `prepareAstroTemplate`. A template holding one is converted again prepared, if its TSX does
1272
+ * not parse, and that kept only if it does, so a component that converts today is converted as
1273
+ * it was.
1274
+ *
1275
+ * A component neither can read comes back as nothing: it fails Astro's own compile with a far
1276
+ * better message than any this could give, and there is nothing to extract from it here.
1277
+ */
1278
+ const astroToTsx = (code, filename, astro = loaded()) => {
1279
+ if (!astro) return "";
1280
+ const compiled = astro.transform && transformed(astro.transform, code, filename);
1281
+ if (compiled !== void 0) return compiled;
1282
+ if (!astro.convertToTSX) return "";
1283
+ const tsx = converted(astro.convertToTSX, code, filename);
1284
+ if (tsx === void 0) return "";
1285
+ const prepared = prepareAstroTemplate(code);
1286
+ if (prepared === code || parses(tsx)) return tsx;
1287
+ const retried = converted(astro.convertToTSX, prepared, filename);
1288
+ return retried !== void 0 && parses(retried) ? retried : tsx;
1289
+ };
1290
+ /** Built in, rather than a plugin package: Astro support is part of the Vite integration. */
1291
+ const pluginAstro = () => ({
1292
+ name: "@bamboocss/node:astro",
1293
+ hooks: { "parser:before": ({ filePath, content }) => {
1294
+ if (filePath.endsWith(".astro")) return astroToTsx(content, filePath);
1295
+ } }
1296
+ });
1297
+ //#endregion
1298
+ //#region src/extractable-files.ts
1299
+ /**
1300
+ * Which of the files `include` matched an extraction pass actually has to read.
1301
+ *
1302
+ * A file can only contribute to the stylesheet by *calling* something bamboo owns — `css`, a
1303
+ * recipe, a pattern, `token`. Every one of those arrives as a binding, and a binding arrives
1304
+ * through an import: either straight from an entrypoint, or from a local module that got it
1305
+ * from one. A file with no such chain cannot hold a call, whatever else is in it.
1306
+ *
1307
+ * On a real application that is most of the tree. Measured over 6,425 files: 4,062 could reach
1308
+ * an entrypoint and 2,363 provably could not, and not handing the extractor the latter took the
1309
+ * pass from 88.9s to 26.3s with byte-identical CSS out. The scan itself costs ~300ms, because
1310
+ * it reads text and never parses.
1311
+ *
1312
+ * ## Skipping is not the same as ignoring
1313
+ *
1314
+ * A file left out here is still *reachable*. Cross-file composition works by resolving an
1315
+ * import and reading what it names, so a module that exports a style object still arrives
1316
+ * the moment something that qualifies imports it. What is skipped is only asking "does this
1317
+ * file *originate* a call", of a file that has no binding to originate one with.
1318
+ *
1319
+ * ## Everything here fails open
1320
+ *
1321
+ * The failure this must not have is dropping a rule, which is silent: the build stays green and
1322
+ * the class the component asks for has nothing behind it. So every uncertainty resolves toward
1323
+ * including the file, and the cases are named rather than left to a catch-all — a file that
1324
+ * cannot be read, a source whose imports could not be scanned, a specifier that looks local and
1325
+ * resolves to nothing. Being wrong in that direction costs time; being wrong in the other costs
1326
+ * correctness.
1327
+ */
1328
+ /**
1329
+ * Module specifiers, from the four places one can appear.
1330
+ *
1331
+ * Deliberately loose about what surrounds them. A specifier missed here costs an edge, and an
1332
+ * edge missed can exclude a file that should have been kept — so the pattern is written to
1333
+ * over-match rather than to parse, and `scanSpecifiers` treats a source it found nothing in as
1334
+ * one it failed to read.
1335
+ */
1336
+ const SPECIFIER = /(?:\bfrom\s*|^\s*(?:import|export)\s*|\bimport\s*\(\s*|\brequire\s*\(\s*)['"]([^'"\n]+)['"]/gm;
1337
+ /** The extensions a specifier may omit, in the order the native resolver tries them. */
1338
+ const EXTENSIONS = [
1339
+ ".ts",
1340
+ ".tsx",
1341
+ ".d.ts",
1342
+ ".mts",
1343
+ ".cts",
1344
+ ".js",
1345
+ ".jsx",
1346
+ ".mjs",
1347
+ ".cjs"
1348
+ ];
1349
+ /** What a `.js`-family specifier may actually name, source first. */
1350
+ const EMITTED = [
1351
+ [".js", [
1352
+ ".ts",
1353
+ ".tsx",
1354
+ ".d.ts",
1355
+ ".js",
1356
+ ".jsx"
1357
+ ]],
1358
+ [".mjs", [
1359
+ ".mts",
1360
+ ".d.mts",
1361
+ ".mjs"
1362
+ ]],
1363
+ [".cjs", [
1364
+ ".cts",
1365
+ ".d.cts",
1366
+ ".cjs"
1367
+ ]]
1368
+ ];
1369
+ /** Every specifier in a source, or `undefined` when the text could not be scanned at all. */
1370
+ const scanSpecifiers = (text) => {
1371
+ const found = [];
1372
+ for (const match of text.matchAll(SPECIFIER)) if (match[1]) found.push(match[1]);
1373
+ if (found.length) return found;
1374
+ return /\b(?:import|require)\b/.test(text) ? void 0 : found;
1375
+ };
1376
+ /** A candidate path with every extension a specifier may have omitted. */
1377
+ const candidatesFor = (base) => {
1378
+ const emitted = EMITTED.find(([suffix]) => base.endsWith(suffix));
1379
+ return [...emitted ? emitted[1].map((extension) => base.slice(0, -emitted[0].length) + extension) : [base, ...EXTENSIONS.map((extension) => base + extension)], ...EXTENSIONS.map((extension) => `${base}/index${extension}`)];
1380
+ };
1381
+ /**
1382
+ * Where a specifier points, when that is somewhere inside the project.
1383
+ *
1384
+ * `undefined` means "nothing local", which is the answer for a package as well as for a broken
1385
+ * path — and both are correct here, because neither can hand this file a binding bamboo owns.
1386
+ * bamboo's own resolution stops at the same boundary: a target outside the project reads as
1387
+ * non-local, so nothing it exports is ever extracted from.
1388
+ */
1389
+ const localTargetOf = (specifier, importer, options) => {
1390
+ const bases = [];
1391
+ if (specifier.startsWith(".")) bases.push(resolve(dirname(importer), specifier));
1392
+ else if (isAbsolute(specifier)) bases.push(specifier);
1393
+ else {
1394
+ for (const [pattern, targets] of Object.entries(options.paths ?? {})) {
1395
+ const star = pattern.indexOf("*");
1396
+ if (star === -1) {
1397
+ if (pattern !== specifier) continue;
1398
+ for (const target of targets) bases.push(resolve(options.cwd, target));
1399
+ continue;
1400
+ }
1401
+ const head = pattern.slice(0, star);
1402
+ const tail = pattern.slice(star + 1);
1403
+ if (!specifier.startsWith(head) || !specifier.endsWith(tail)) continue;
1404
+ const filled = specifier.slice(head.length, specifier.length - tail.length);
1405
+ for (const target of targets) bases.push(resolve(options.cwd, target.replace("*", filled)));
1406
+ }
1407
+ if (options.baseUrl) bases.push(resolve(options.cwd, options.baseUrl, specifier));
1408
+ }
1409
+ const exists = options.fileExists ?? existsSync;
1410
+ const root = options.cwd.endsWith("/") ? options.cwd : `${options.cwd}/`;
1411
+ for (const base of bases) {
1412
+ if (!base.startsWith(root)) continue;
1413
+ for (const candidate of candidatesFor(base)) if (exists(candidate)) return candidate;
1414
+ }
1415
+ };
1416
+ /**
1417
+ * The subset of `files` that could hold a call to something bamboo owns.
1418
+ *
1419
+ * Two passes over text and no parsing. The first marks every file that names an entrypoint and
1420
+ * records where each file's other imports point; the second walks those edges backwards from
1421
+ * the marked set, because a file that imports a module carrying bamboo bindings may be using
1422
+ * one — a recipe defined with `cva` in one file and called in another is exactly that shape.
1423
+ *
1424
+ * The edges are worth more than the walk they were built for. Every one of them names a module
1425
+ * that is *going* to be demanded, so the same scan that decides what to parse also says which
1426
+ * virtual or transformed sources the native source map may need — see `auxiliary`.
1427
+ */
1428
+ const selectExtractable = (files, options) => {
1429
+ const keep = /* @__PURE__ */ new Set();
1430
+ const importers = /* @__PURE__ */ new Map();
1431
+ for (const file of files) {
1432
+ const text = options.readFile(file);
1433
+ if (text === void 0) {
1434
+ keep.add(file);
1435
+ continue;
1436
+ }
1437
+ if (options.entrypoints.some((entrypoint) => text.includes(entrypoint))) keep.add(file);
1438
+ const specifiers = scanSpecifiers(text);
1439
+ if (specifiers === void 0) {
1440
+ keep.add(file);
1441
+ continue;
1442
+ }
1443
+ for (const specifier of specifiers) {
1444
+ const target = localTargetOf(specifier, file, options);
1445
+ if (!target) continue;
1446
+ const seen = importers.get(target);
1447
+ if (seen) seen.push(file);
1448
+ else importers.set(target, [file]);
1449
+ }
1450
+ }
1451
+ let frontier = [...keep];
1452
+ while (frontier.length) {
1453
+ const next = [];
1454
+ for (const target of frontier) for (const importer of importers.get(target) ?? []) {
1455
+ if (keep.has(importer)) continue;
1456
+ keep.add(importer);
1457
+ next.push(importer);
1458
+ }
1459
+ frontier = next;
1460
+ }
1461
+ const inventory = new Set(files);
1462
+ return {
1463
+ auxiliary: [...importers.keys()].filter((target) => !inventory.has(target)),
1464
+ extractable: files.filter((file) => keep.has(file))
1465
+ };
1466
+ };
1467
+ //#endregion
1468
+ //#region ../../node_modules/.pnpm/ansi-regex@6.2.2/node_modules/ansi-regex/index.js
1469
+ function ansiRegex({ onlyFirst = false } = {}) {
1470
+ return new RegExp(`(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`, onlyFirst ? void 0 : "g");
1471
+ }
1472
+ //#endregion
1473
+ //#region ../../node_modules/.pnpm/strip-ansi@7.1.2/node_modules/strip-ansi/index.js
1474
+ const regex = ansiRegex();
1475
+ function stripAnsi(string) {
1476
+ if (typeof string !== "string") throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
1477
+ return string.replace(regex, "");
379
1478
  }
380
1479
  //#endregion
381
1480
  //#region ../../node_modules/.pnpm/get-east-asian-width@1.4.0/node_modules/get-east-asian-width/lookup.js
@@ -935,11 +2034,11 @@ var import_cli_boxes = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((
935
2034
  const UPPERCASE = /[\p{Lu}]/u;
936
2035
  const LOWERCASE = /[\p{Ll}]/u;
937
2036
  const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
938
- const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
2037
+ const IDENTIFIER$1 = /([\p{Alpha}\p{N}_]|$)/u;
939
2038
  const SEPARATORS = /[_.\- ]+/;
940
2039
  const LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
941
- const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
942
- const NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
2040
+ const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER$1.source, "gu");
2041
+ const NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER$1.source, "gu");
943
2042
  const preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutiveUppercase) => {
944
2043
  let isLastCharLower = false;
945
2044
  let isLastCharUpper = false;
@@ -1625,215 +2724,71 @@ const createBox = (options) => boxen(options.content, {
1625
2724
  titleAlignment: "center"
1626
2725
  });
1627
2726
  //#endregion
1628
- //#region src/tsconfig-utils.ts
1629
- /**
1630
- * If `filename` points to a `.json` file that exists as a regular file, return its absolute path.
1631
- */
1632
- async function resolveDirectTsconfigJson(filename) {
1633
- if (path.extname(filename) !== ".json") return null;
1634
- const resolved = path.resolve(filename);
1635
- try {
1636
- const stat = await promises.stat(resolved);
1637
- if (stat.isFile() || stat.isFIFO()) return resolved;
1638
- throw new Error(`${filename} exists but is not a regular file.`);
1639
- } catch (e) {
1640
- if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return null;
1641
- throw e;
1642
- }
1643
- }
1644
- /**
1645
- * Walk upward from `dirname(filename)` and return the first existing `configName`,
1646
- * stopping at `root` (inclusive) or the filesystem root.
1647
- */
1648
- async function findClosestTsconfig(filename, root, configName = "tsconfig.json") {
1649
- const resolvedRoot = path.resolve(root);
1650
- let dir = path.dirname(path.resolve(filename));
1651
- for (;;) {
1652
- const candidate = path.join(dir, configName);
1653
- try {
1654
- const stat = await promises.stat(candidate);
1655
- if (stat.isFile() || stat.isFIFO()) return candidate;
1656
- } catch {}
1657
- if (dir === resolvedRoot || path.dirname(dir) === dir) return null;
1658
- dir = path.dirname(dir);
1659
- }
1660
- }
2727
+ //#region src/config-reload.ts
1661
2728
  /**
1662
- * Resolve `compilerOptions.baseUrl` the same way TypeScript does: relative to the tsconfig file.
1663
- * Falls back to `cwd` when `baseUrl` is omitted.
2729
+ * How each config was prepared, so that reading it again — once it has been edited — prepares it
2730
+ * the same way.
2731
+ *
2732
+ * An integration does more than read the file: it adds the Vue, Svelte and Astro parsers, marks a
2733
+ * dev server's build as one, keeps the `cwd` it was handed, and lays its own `config` over the
2734
+ * file's. A reload that only read the file again dropped all of that from the context it built: a
2735
+ * `.vue` file stopped reaching the sheet after the first edit to the config, and `hash: 'auto'`
2736
+ * changed every class name the browser already held.
2737
+ *
2738
+ * Kept apart from where it is filled, so the diff engine can ask without importing what creates
2739
+ * the contexts it refreshes.
1664
2740
  */
1665
- function resolveBaseUrlForCompilerOptions(baseUrl, tsconfigFile, cwd) {
1666
- if (baseUrl == null) return cwd;
1667
- if (baseUrl.startsWith("${")) return baseUrl;
1668
- if (path.isAbsolute(baseUrl)) return baseUrl;
1669
- return path.resolve(path.dirname(tsconfigFile), baseUrl);
1670
- }
1671
- const SOURCE_EXTENSIONS = [
1672
- ".ts",
1673
- ".tsx",
1674
- ".mts",
1675
- ".cts"
1676
- ];
1677
- function resolveReferencedTsconfigPath(refPath, fromDir, configName = "tsconfig.json") {
1678
- const p = refPath.endsWith(".json") ? refPath : path.join(refPath, configName);
1679
- return path.resolve(fromDir, p);
1680
- }
2741
+ const reloaders = /* @__PURE__ */ new WeakMap();
2742
+ const rememberConfigReload = (conf, reload) => {
2743
+ reloaders.set(conf, reload);
2744
+ };
2745
+ const configReloadOf = (conf) => reloaders.get(conf);
1681
2746
  /**
1682
- * When a file belongs to a referenced project (TypeScript project references),
1683
- * return that project's merged tsconfig for `compilerOptions`.
2747
+ * A copy of what is laid over a config, for the next read to lay over in turn.
2748
+ *
2749
+ * Down through its arrays and plain objects, property by property as each is defined — a getter
2750
+ * stays a getter, and is not called; frozen stays frozen. Anything else, a function, a `Map` or
2751
+ * any other instance, is the same value. An object met twice is copied once, so a value that
2752
+ * refers to itself refers to its copy. One that cannot be read through — a revoked proxy — is
2753
+ * laid over as it is, as it was before there was a copy.
1684
2754
  */
1685
- async function resolveSolutionTsconfigForFile(absoluteFilename, rootTsconfigPath, rootParsed, getTsconfigModule, cache) {
1686
- const { parseTsconfig } = getTsconfigModule;
1687
- if (isSourceFileIncludedInTsconfig(absoluteFilename, rootTsconfigPath, rootParsed)) return {
1688
- tsconfig: rootParsed,
1689
- tsconfigFile: rootTsconfigPath
1690
- };
1691
- const refs = rootParsed.references;
1692
- if (!refs?.length) return {
1693
- tsconfig: rootParsed,
1694
- tsconfigFile: rootTsconfigPath
1695
- };
1696
- if (!SOURCE_EXTENSIONS.some((ext) => absoluteFilename.endsWith(ext))) return {
1697
- tsconfig: rootParsed,
1698
- tsconfigFile: rootTsconfigPath
1699
- };
1700
- const rootDir = path.dirname(rootTsconfigPath);
1701
- for (const ref of refs) {
1702
- const refPath = resolveReferencedTsconfigPath(ref.path, rootDir);
1703
- try {
1704
- await promises.access(refPath);
1705
- } catch {
1706
- continue;
1707
- }
1708
- const childParsed = parseTsconfig(refPath, cache);
1709
- if (isSourceFileIncludedInTsconfig(absoluteFilename, refPath, childParsed)) return {
1710
- tsconfig: childParsed,
1711
- tsconfigFile: refPath
1712
- };
2755
+ const copyLaidOver = (value) => {
2756
+ try {
2757
+ return copyThrough(value, /* @__PURE__ */ new WeakMap());
2758
+ } catch {
2759
+ return value;
1713
2760
  }
1714
- return {
1715
- tsconfig: rootParsed,
1716
- tsconfigFile: rootTsconfigPath
1717
- };
1718
- }
1719
- const POSIX_SEP_RE = new RegExp("\\" + path.posix.sep, "g");
1720
- const NATIVE_SEP_RE = new RegExp("\\" + path.sep, "g");
1721
- const PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
1722
- const GLOB_ALL_PATTERN = `**/*`;
1723
- const TS_EXTENSIONS = [
1724
- ".ts",
1725
- ".tsx",
1726
- ".mts",
1727
- ".cts"
1728
- ];
1729
- const TSJS_EXTENSIONS = TS_EXTENSIONS.concat([
1730
- ".js",
1731
- ".jsx",
1732
- ".mjs",
1733
- ".cjs"
1734
- ]);
1735
- const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
1736
- const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
1737
- const IS_POSIX = path.posix.sep === path.sep;
1738
- const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, path.posix.sep);
1739
- const resolve2posix = IS_POSIX ? (dir, filename) => dir ? path.resolve(dir, filename) : path.resolve(filename) : (dir, filename) => {
1740
- const posix2native = (f) => f.replace(POSIX_SEP_RE, path.sep);
1741
- return native2posix(dir ? path.resolve(posix2native(dir), posix2native(filename)) : path.resolve(posix2native(filename)));
1742
2761
  };
1743
- function isGlobMatch(filename, dir, patterns, allowJs) {
1744
- const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
1745
- return patterns.some((patternArg) => {
1746
- let pattern = patternArg;
1747
- let lastWildcardIndex = pattern.length;
1748
- let hasWildcard = false;
1749
- let hasExtension = false;
1750
- let hasSlash = false;
1751
- let lastSlashIndex = -1;
1752
- for (let i = pattern.length - 1; i > -1; i--) {
1753
- const c = pattern[i];
1754
- if (!hasWildcard) {
1755
- if (c === "*" || c === "?") {
1756
- lastWildcardIndex = i;
1757
- hasWildcard = true;
1758
- }
1759
- }
1760
- if (!hasSlash) {
1761
- if (c === ".") hasExtension = true;
1762
- else if (c === "/") {
1763
- lastSlashIndex = i;
1764
- hasSlash = true;
1765
- }
1766
- }
1767
- if (hasWildcard && hasSlash) break;
1768
- }
1769
- if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
1770
- pattern += `${pattern.endsWith("/") ? "" : "/"}${GLOB_ALL_PATTERN}`;
1771
- lastWildcardIndex = pattern.length - 1;
1772
- hasWildcard = true;
1773
- }
1774
- if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
1775
- if (pattern.endsWith("*") && !extensions.some((ext) => filename.endsWith(ext))) return false;
1776
- if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
1777
- const resolvedPattern = resolve2posix(dir, pattern);
1778
- let firstWildcardIndex = -1;
1779
- for (let i = 0; i < resolvedPattern.length; i++) if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
1780
- firstWildcardIndex = i;
1781
- hasWildcard = true;
1782
- break;
1783
- }
1784
- if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
1785
- if (!hasWildcard) return filename === resolvedPattern;
1786
- if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) return true;
1787
- if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
1788
- const regex = pattern2regex(resolvedPattern, allowJs);
1789
- PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
1790
- return regex.test(filename);
1791
- });
1792
- }
1793
- function pattern2regex(resolvedPattern, allowJs) {
1794
- let regexStr = "^";
1795
- for (let i = 0; i < resolvedPattern.length; i++) {
1796
- const char = resolvedPattern[i];
1797
- if (char === "?") {
1798
- regexStr += "[^\\/]";
1799
- continue;
1800
- }
1801
- if (char === "*") {
1802
- if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
1803
- i += 2;
1804
- regexStr += "(?:[^\\/]*\\/)*";
1805
- continue;
1806
- }
1807
- regexStr += "[^\\/]*";
1808
- continue;
1809
- }
1810
- if ("/.+^${}()|[]\\".includes(char)) regexStr += "\\";
1811
- regexStr += char;
2762
+ const copyThrough = (value, copies) => {
2763
+ if (value === null || typeof value !== "object") return value;
2764
+ if (copies.has(value)) return copies.get(value);
2765
+ const prototype = Object.getPrototypeOf(value);
2766
+ const array = Array.isArray(value) && prototype === Array.prototype;
2767
+ if (!array && prototype !== null && Object.getPrototypeOf(prototype) !== null) return value;
2768
+ const result = array ? new Array(value.length) : Object.create(prototype);
2769
+ copies.set(value, result);
2770
+ for (const key of Reflect.ownKeys(value)) {
2771
+ if (array && key === "length") continue;
2772
+ const property = Object.getOwnPropertyDescriptor(value, key);
2773
+ if (!property) continue;
2774
+ if ("value" in property) property.value = copyThrough(property.value, copies);
2775
+ Object.defineProperty(result, key, property);
1812
2776
  }
1813
- if (resolvedPattern.endsWith("*")) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
1814
- regexStr += "$";
1815
- return new RegExp(regexStr);
1816
- }
1817
- function isIncluded(filename, tsconfigFile, tsconfig) {
1818
- const dir = native2posix(path.dirname(tsconfigFile));
1819
- const files = (tsconfig.files || []).map((file) => resolve2posix(dir, file));
1820
- const absoluteFilename = resolve2posix(null, filename);
1821
- if (files.includes(filename)) return true;
1822
- const allowJs = tsconfig.compilerOptions?.allowJs;
1823
- if (isGlobMatch(absoluteFilename, dir, tsconfig.include || (tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs)) return !isGlobMatch(absoluteFilename, dir, tsconfig.exclude || [], allowJs);
1824
- return false;
1825
- }
1826
- /** Whether `absoluteFilename` is part of the compilation set defined by this tsconfig. */
1827
- function isSourceFileIncludedInTsconfig(absoluteFilename, tsconfigFile, tsconfig) {
1828
- return isIncluded(absoluteFilename, tsconfigFile, tsconfig);
1829
- }
2777
+ if (!Object.isExtensible(value)) Object.preventExtensions(result);
2778
+ return result;
2779
+ };
1830
2780
  //#endregion
1831
2781
  //#region src/load-tsconfig.ts
1832
- const readPathsFromCache = (cache) => {
1833
- const prefix = "readFileSync:";
1834
- const suffix = ":utf8";
1835
- return Array.from(cache.keys()).filter((key) => key.startsWith(prefix) && key.endsWith(suffix)).map((key) => key.slice(13, -5));
1836
- };
2782
+ /**
2783
+ * What each `include` glob reaches: the file it names, or the directory up to its first segment
2784
+ * with a glob character in it — braces and brackets too, in this syntax. A negation reaches none.
2785
+ */
2786
+ const includeTargets = (include, cwd) => (include ?? []).flatMap((glob) => {
2787
+ if (glob.startsWith("!")) return [];
2788
+ const { base, wildcard } = globBase(glob, /[*?{}[\]!()]/);
2789
+ const target = path.resolve(cwd, base);
2790
+ return [wildcard || !path.extname(base) ? { directory: target } : { file: target }];
2791
+ });
1837
2792
  /**
1838
2793
  * Exact tsconfig files read while producing one resolved Node config.
1839
2794
  *
@@ -1846,115 +2801,50 @@ const rememberTsConfigResolutionFiles = (conf, files) => {
1846
2801
  resolutionFilesByConfig.set(conf, Object.freeze([...new Set(files)].sort()));
1847
2802
  };
1848
2803
  const getTsConfigResolutionFiles = (conf) => resolutionFilesByConfig.get(conf) ?? Object.freeze(conf.tsconfigFile ? [path.resolve(conf.tsconfigFile)] : []);
1849
- const referencedTsconfigPath = (reference, rootPath) => path.resolve(path.dirname(rootPath), reference.endsWith(".json") ? reference : path.join(reference, "tsconfig.json"));
1850
- const MAX_TSCONFIG_REFERENCE_FILES = 256;
1851
- const getImplicitBaseUrl = (compilerOptions) => {
1852
- if (!compilerOptions) return void 0;
1853
- const matches = Object.getOwnPropertySymbols(compilerOptions).filter((candidate) => candidate.description === "implicitBaseUrl");
1854
- if (matches.length !== 1) return void 0;
1855
- const symbol = matches[0];
1856
- const descriptor = Object.getOwnPropertyDescriptor(compilerOptions, symbol);
1857
- if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "string") return void 0;
1858
- return {
1859
- owner: compilerOptions,
1860
- symbol,
1861
- value: descriptor.value
1862
- };
1863
- };
1864
- const collectReferenceGraph = async (rootPath, rootParsed, parseTsconfig, cache) => {
1865
- const references = [];
1866
- const unresolvedReferences = [];
1867
- let traversalLimitExceeded = false;
1868
- const visited = new Set([path.resolve(rootPath)]);
1869
- const queue = [{
1870
- parsed: rootParsed,
1871
- path: rootPath
1872
- }];
1873
- for (let index = 0; index < queue.length; index++) {
1874
- const current = queue[index];
1875
- for (const reference of current.parsed.references ?? []) {
1876
- const referencedPath = referencedTsconfigPath(reference.path, current.path);
1877
- references.push({
1878
- from: current.path,
1879
- path: referencedPath
1880
- });
1881
- if (visited.has(referencedPath)) continue;
1882
- if (visited.size >= MAX_TSCONFIG_REFERENCE_FILES) {
1883
- traversalLimitExceeded = true;
1884
- unresolvedReferences.push(referencedPath);
1885
- continue;
1886
- }
1887
- visited.add(referencedPath);
1888
- try {
1889
- const source = await promises.readFile(referencedPath, "utf8");
1890
- JSON.parse(source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"));
1891
- queue.push({
1892
- parsed: parseTsconfig(referencedPath, cache),
1893
- path: referencedPath
1894
- });
1895
- } catch {
1896
- unresolvedReferences.push(referencedPath);
1897
- }
1898
- }
1899
- }
1900
- return {
1901
- references,
1902
- traversalLimitExceeded,
1903
- unresolvedReferences
1904
- };
1905
- };
1906
- async function loadTsConfig(conf, cwd, provenance, resolutionFiles) {
1907
- const root = cwd;
2804
+ async function loadTsConfig(conf, cwd, resolutionFiles) {
1908
2805
  let tsconfigFile = await resolveDirectTsconfigJson(conf.path);
1909
- const direct = tsconfigFile !== null;
1910
2806
  if (!tsconfigFile) {
1911
2807
  if (resolutionFiles) resolutionFiles.value = Object.freeze([]);
1912
- tsconfigFile = await findClosestTsconfig(conf.path, root, "tsconfig.json");
2808
+ tsconfigFile = await findClosestTsconfig(conf.path, cwd, "tsconfig.json");
1913
2809
  }
1914
- if (!tsconfigFile) {
1915
- if (provenance) provenance.value = {
1916
- direct: false,
1917
- readPaths: [],
1918
- references: [],
1919
- traversalLimitExceeded: false,
1920
- unresolvedReferences: []
1921
- };
1922
- return {
1923
- tsconfig: {},
1924
- tsconfigFile: void 0
1925
- };
2810
+ if (!tsconfigFile) return {
2811
+ tsconfig: {},
2812
+ tsconfigFile: void 0
2813
+ };
2814
+ const graph = await readTsconfigGraph(tsconfigFile);
2815
+ const configFile = path.resolve(conf.path);
2816
+ let effective = /\.[cm]?tsx?$/.test(configFile) && graph.projectIncluding(configFile) || graph.root;
2817
+ if (isSolutionTsconfig(graph.root.tsconfig)) {
2818
+ const targets = includeTargets(conf.config?.include, conf.config?.cwd ? path.resolve(conf.config.cwd) : cwd);
2819
+ const probes = targets.flatMap(({ file, directory }) => file ? [file] : [path.join(directory, "__bamboo__.ts"), path.join(directory, "__bamboo__.tsx")]);
2820
+ const includes = ({ tsconfig, tsconfigFile }) => probes.some((probe) => isSourceFileIncludedInTsconfig(probe, tsconfigFile, tsconfig));
2821
+ const reaches = (project) => targets.some(({ directory }) => directory !== void 0 && includesUnder(directory, project));
2822
+ const sources = graph.find((project) => declaresAliases(project) && includes(project)) ?? graph.find((project) => declaresAliases(project) && reaches(project));
2823
+ if (sources) effective = sources;
1926
2824
  }
1927
- const gtc = await import("get-tsconfig");
1928
- const cache = /* @__PURE__ */ new Map();
1929
- const rootParsed = gtc.parseTsconfig(tsconfigFile, cache);
1930
- const { tsconfig, tsconfigFile: effectiveTsconfigPath } = await resolveSolutionTsconfigForFile(path.resolve(conf.path), tsconfigFile, rootParsed, gtc, cache);
1931
- const compilerOptions = tsconfig?.compilerOptions;
1932
- const implicitBaseUrl = getImplicitBaseUrl(compilerOptions);
2825
+ let { tsconfig } = effective;
2826
+ const effectiveTsconfigPath = effective.tsconfigFile;
2827
+ const compilerOptions = tsconfig.compilerOptions;
2828
+ const base = resolvePathsBase(tsconfig, effectiveTsconfigPath, cwd);
2829
+ if (compilerOptions && (compilerOptions.baseUrl != null || compilerOptions.paths)) tsconfig = {
2830
+ ...tsconfig,
2831
+ compilerOptions: compilerOptions.baseUrl != null ? {
2832
+ ...compilerOptions,
2833
+ baseUrl: base
2834
+ } : {
2835
+ ...compilerOptions,
2836
+ paths: Object.fromEntries(Object.entries(compilerOptions.paths).map(([pattern, targets]) => [pattern, targets.map((target) => path.resolve(base, target))]))
2837
+ }
2838
+ };
1933
2839
  const result = {
1934
2840
  tsconfig,
1935
2841
  tsconfigFile: effectiveTsconfigPath
1936
2842
  };
1937
- if (resolutionFiles) resolutionFiles.value = Object.freeze([...new Set(readPathsFromCache(cache).map((file) => path.resolve(file)))].sort());
1938
- if (compilerOptions?.paths) {
1939
- const baseUrl = compilerOptions.baseUrl;
1940
- result.tsOptions = {
1941
- baseUrl,
1942
- pathMappings: convertTsPathsToRegexes(compilerOptions.paths, resolveBaseUrlForCompilerOptions(baseUrl, effectiveTsconfigPath, cwd))
1943
- };
1944
- }
1945
- if (provenance) {
1946
- const referenceGraph = await collectReferenceGraph(tsconfigFile, rootParsed, gtc.parseTsconfig, cache);
1947
- provenance.value = {
1948
- direct,
1949
- effectivePath: effectiveTsconfigPath,
1950
- implicitBaseUrl,
1951
- readPaths: readPathsFromCache(cache),
1952
- references: referenceGraph.references,
1953
- rootPath: tsconfigFile,
1954
- traversalLimitExceeded: referenceGraph.traversalLimitExceeded,
1955
- unresolvedReferences: referenceGraph.unresolvedReferences
1956
- };
1957
- }
2843
+ if (resolutionFiles) resolutionFiles.value = Object.freeze([...new Set(graph.files())].sort());
2844
+ if (tsconfig.compilerOptions?.paths) result.tsOptions = {
2845
+ baseUrl: tsconfig.compilerOptions.baseUrl,
2846
+ pathMappings: convertTsPathsToRegexes(tsconfig.compilerOptions.paths, base)
2847
+ };
1958
2848
  return result;
1959
2849
  }
1960
2850
  //#endregion
@@ -1975,21 +2865,26 @@ var DiffEngine = class {
1975
2865
  * Reload config from disk and refresh the context
1976
2866
  */
1977
2867
  async reloadConfigAndRefreshContext(fn) {
2868
+ const reload = configReloadOf(this.ctx.conf);
2869
+ const conf = reload ? await reload() : await this.readAgain();
2870
+ const affected = this.refresh(conf, fn);
2871
+ if (!affected.hasConfigChanged) {
2872
+ applyTsConfig(this.ctx.conf, conf);
2873
+ rememberTsConfigResolutionFiles(this.ctx.conf, getTsConfigResolutionFiles(conf));
2874
+ }
2875
+ return affected;
2876
+ }
2877
+ /** The file read again, and its tsconfig, for a context no integration prepared. */
2878
+ readAgain = async () => {
1978
2879
  const conf = await loadConfig({
1979
2880
  cwd: this.ctx.config.cwd,
1980
2881
  file: this.ctx.conf.path
1981
2882
  });
1982
2883
  const resolutionFiles = {};
1983
- const tsconfig = await loadTsConfig(conf, conf.config.cwd || this.ctx.config.cwd, void 0, resolutionFiles);
1984
- applyTsConfig(conf, tsconfig);
2884
+ applyTsConfig(conf, await loadTsConfig(conf, conf.config.cwd || this.ctx.config.cwd, resolutionFiles));
1985
2885
  rememberTsConfigResolutionFiles(conf, resolutionFiles.value ?? []);
1986
- const affected = this.refresh(conf, fn);
1987
- if (!affected.hasConfigChanged) {
1988
- applyTsConfig(this.ctx.conf, tsconfig);
1989
- rememberTsConfigResolutionFiles(this.ctx.conf, resolutionFiles.value ?? []);
1990
- }
1991
- return affected;
1992
- }
2886
+ return conf;
2887
+ };
1993
2888
  /** @internal Exact tsconfig files behind the currently attached resolution options. */
1994
2889
  getResolutionConfigFiles = () => getTsConfigResolutionFiles(this.ctx.conf);
1995
2890
  /**
@@ -2231,7 +3126,7 @@ var SourceProject = class {
2231
3126
  addSourceFile = (filePath, content) => {
2232
3127
  this.overlaySource(this.absolute(filePath), content);
2233
3128
  };
2234
- absolute = (filePath) => isAbsolute$1(filePath) ? filePath : join$1(this.options.cwd ?? process.cwd(), filePath);
3129
+ absolute = (filePath) => isAbsolute(filePath) ? filePath : join(this.options.cwd ?? process.cwd(), filePath);
2235
3130
  /** Forget bytes supplied through `overlaySource`. Returns whether there were any. */
2236
3131
  removeOverlay = (filePath) => {
2237
3132
  const removed = this.overlays.delete(this.normalizePath(filePath));
@@ -2275,7 +3170,7 @@ function globDirname(globs) {
2275
3170
  continue;
2276
3171
  }
2277
3172
  const nonGlobTokens = scan.tokens?.filter((token) => !token.isPrefix && !token.isGlob);
2278
- if (nonGlobTokens?.length) rootDirs.add(join(...nonGlobTokens.map((token) => token.value)));
3173
+ rootDirs.add(nonGlobTokens?.length ? join(...nonGlobTokens.map((token) => token.value)) : ".");
2279
3174
  }
2280
3175
  if (rootDirs.size === 0) return ["."];
2281
3176
  return Array.from(rootDirs);
@@ -2301,21 +3196,206 @@ function globDirname(globs) {
2301
3196
  * mutated.
2302
3197
  */
2303
3198
  const globIgnore = (exclude) => ["**/*.d.ts", ...exclude ?? []];
3199
+ /** Patterns that name what to read, apart from those, `!`-led, that name what to pass over. */
3200
+ const splitPatterns = (patterns) => {
3201
+ const positive = [];
3202
+ const negative = [];
3203
+ for (const pattern of patterns) if (picomatch.scan(pattern).negated) negative.push(pattern.slice(1));
3204
+ else positive.push(pattern);
3205
+ return {
3206
+ negative,
3207
+ positive
3208
+ };
3209
+ };
3210
+ /**
3211
+ * Whether a `cwd`-relative, `/`-spelled path is one the source glob returns for `include` and
3212
+ * `exclude`, told without walking: what decides a file's membership when it appears, and whether
3213
+ * the compiler reads a module.
3214
+ *
3215
+ * As the glob reads the two, which a matcher handed the same lists does not:
3216
+ *
3217
+ * - A negated `include` pattern — `!src/legacy/**` — is one more thing to pass over, where such a
3218
+ * matcher matches every path it does not name: `README.md`, and each module in `node_modules`,
3219
+ * was a source. So is a negated `exclude` pattern, which the glob reads without its `!`.
3220
+ * - A file passed over is matched with hidden paths in reach, so `**\/*.d.ts` drops one under
3221
+ * `.storybook` that `include` names, though a wildcard of `include`'s own does not enter it.
3222
+ * - A folder the walk meets below where it began, with a name an ignore matches outright —
3223
+ * `src/legacy`, `**\/legacy`, not `src/legacy/*` — is not read: nothing in it is a source. The
3224
+ * folder a walk begins at is never tested, so `src/legacy/**` beside `exclude: ['src/legacy']`
3225
+ * reads it, and a pattern without a glob — looked up in its own folder — is one wherever it is.
3226
+ * - A pattern is matched as its own walk spells what it meets: one written as an absolute path
3227
+ * against where a file is from the root, and every other against where it is from `cwd` — so
3228
+ * `**\/*.tsx` reaches nothing above `cwd`, and an absolute `exclude` beside a relative `include`
3229
+ * passes over nothing, as the glob passes over nothing for it.
3230
+ */
3231
+ const sourceMatcher = (include = [], exclude, cwd = process.cwd()) => {
3232
+ const { negative, positive } = splitPatterns(include);
3233
+ const ignore = [...negative, ...globIgnore(exclude).map((pattern) => pattern.startsWith("!") ? pattern.slice(1) : pattern)];
3234
+ const read = positive.map(resolveDots);
3235
+ const fromCwd = membership(read.filter((pattern) => !isAbsolute(pattern)), ignore, cwd);
3236
+ const absolute = read.filter((pattern) => isAbsolute(pattern));
3237
+ const spelled = (input) => input.includes("\\") ? slashes(input) : input;
3238
+ if (!absolute.length) return (input) => fromCwd(spelled(input));
3239
+ const fromRoot = membership(absolute, ignore, cwd);
3240
+ const root = slashes(cwd);
3241
+ return (input) => {
3242
+ const path = spelled(input);
3243
+ return fromCwd(path) || fromRoot(posix.join(root, path));
3244
+ };
3245
+ };
3246
+ /** A pattern with `.` and `..` segments resolved, as the walk resolves them on its way down. */
3247
+ const resolveDots = (pattern) => pattern.startsWith("./") || pattern.includes("/./") || pattern.includes("/../") ? posix.normalize(pattern) : pattern;
3248
+ /** As `sourceMatcher` tells it, for patterns all spelled the one way — and paths spelled so. */
3249
+ const membership = (read, ignore, cwd) => {
3250
+ if (!read.length) return () => false;
3251
+ const options = { windows: false };
3252
+ const matches = picomatch(read, options);
3253
+ const ignored = picomatch(ignore, {
3254
+ ...options,
3255
+ dot: true
3256
+ });
3257
+ const member = (path) => matches(path) && !ignored(path);
3258
+ const folderIgnore = ignore.filter((pattern) => !pattern.endsWith("/**") && !glob.isDynamicPattern(posix.basename(pattern)));
3259
+ if (!folderIgnore.length) return member;
3260
+ const walks = byWalk(glob.generateTasks(read, { cwd }).flatMap((task) => task.positive), cwd);
3261
+ let stops = false;
3262
+ const reads = [...walks].map(([base, patterns]) => {
3263
+ const inWalk = walks.size === 1 ? () => true : picomatch(patterns, options);
3264
+ const skipped = folderIgnore.filter((pattern) => !picomatch([pattern, `${pattern}/**`], options)(base));
3265
+ if (!skipped.length) return inWalk;
3266
+ stops = true;
3267
+ const inSkipped = picomatch(skipped.map((pattern) => `${pattern}/**`), options);
3268
+ return (path) => inWalk(path) && !inSkipped(path);
3269
+ });
3270
+ return stops ? (path) => member(path) && reads.some((read) => read(path)) : member;
3271
+ };
3272
+ /** Patterns by the folder each is walked from when alone, as the source glob walks them. */
3273
+ const byWalk = (patterns, cwd) => {
3274
+ const walks = /* @__PURE__ */ new Map();
3275
+ for (const pattern of patterns) {
3276
+ const base = glob.generateTasks([pattern], { cwd })[0]?.base ?? ".";
3277
+ walks.set(base, [...walks.get(base) ?? [], pattern]);
3278
+ }
3279
+ return walks;
3280
+ };
3281
+ /**
3282
+ * The order the source glob returns files in, made a decision rather than an accident.
3283
+ *
3284
+ * `fast-glob` hands back whatever `readdir` gave it, which is the filesystem's order and is not
3285
+ * the same on every machine. That order is not cosmetic: it is the order atoms enter the sheet,
3286
+ * and sheet order is what decides a conflict between two classes on one element — `cx` joins
3287
+ * them and the browser picks by position, not by the order they were passed. So an unsorted
3288
+ * glob lets two checkouts of the same commit build stylesheets that resolve the same conflict
3289
+ * differently, and makes the emitted bytes irreproducible, which is also what content-hashed
3290
+ * asset caching is keyed on.
3291
+ *
3292
+ * Sorted by code unit rather than `localeCompare`, whose answer depends on the host's locale —
3293
+ * the exact class of machine-dependence this exists to remove.
3294
+ */
3295
+ const sortSources = (files) => files.sort();
3296
+ const slashes = (path) => path.replaceAll("\\", "/");
3297
+ /**
3298
+ * A folder's entry, joined as the walk joins it — onto the path it read, with `/` unless that path
3299
+ * ends in one already — and spelled as every path here is, with `/`.
3300
+ */
3301
+ const entryPath = (directory, name) => slashes(directory.endsWith("/") ? directory + name : `${directory}/${name}`);
3302
+ const identify = (stats) => `${stats.dev}:${stats.ino}`;
3303
+ /**
3304
+ * One walk's `readdirSync` and `statSync`, which end the walk where a link leads back into it.
3305
+ *
3306
+ * The glob follows symbolic links — how a workspace package or a folder linked into `src` is read
3307
+ * at all — and a link to a folder the walk was inside took it round that folder again, and again:
3308
+ * once per lap until the system would resolve no deeper a chain of links, some thirty of them, with
3309
+ * every file returned once per lap — and with two such links on the way, the laps doubled each
3310
+ * time round, and the build hung at the glob with nothing to say why. Every folder the walk reads
3311
+ * is listed here, so a link whose folder is one the walk is already inside is read as empty, as
3312
+ * `find -L` reads it: all of it is being read already, by the path that reached it first. A link
3313
+ * that closes no loop is followed, and every path through it returned, as before.
3314
+ *
3315
+ * Only a link is asked, since only a link can close a loop, and by what the walk already learns of
3316
+ * it: listing a link, the walk stats it, which names the folder behind it by device and inode. The
3317
+ * folders above it are stat'd once each — mostly, just the one the walk began at — and a real path
3318
+ * is resolved only where two of those match, to tell apart inodes too large to be told apart.
3319
+ */
3320
+ const stopAtCycles = () => {
3321
+ const directories = /* @__PURE__ */ new Map();
3322
+ /** Every entry listed that is a symbolic link, by its path, and what the walk's stat of it found. */
3323
+ const links = /* @__PURE__ */ new Map();
3324
+ const identityOf = (directory) => {
3325
+ const walked = directories.get(directory);
3326
+ if (walked.identity === void 0) try {
3327
+ walked.identity = walked.link && links.get(directory) || identify(statSync(directory));
3328
+ } catch {
3329
+ walked.identity = directory;
3330
+ }
3331
+ return walked.identity;
3332
+ };
3333
+ const realDirectory = (directory) => {
3334
+ const walked = directories.get(directory);
3335
+ if (walked.real === void 0) try {
3336
+ walked.real = slashes(realpathSync.native(directory));
3337
+ } catch {
3338
+ walked.real = directory;
3339
+ }
3340
+ return walked.real;
3341
+ };
3342
+ const readdir = ((path, options) => {
3343
+ const directory = slashes(String(path));
3344
+ const cut = directory.lastIndexOf("/");
3345
+ const above = directory.slice(0, cut);
3346
+ const parent = directories.has(above) ? above : directories.has(directory.slice(0, cut + 1)) ? directory.slice(0, cut + 1) : void 0;
3347
+ const link = links.has(directory);
3348
+ directories.set(directory, {
3349
+ link,
3350
+ parent
3351
+ });
3352
+ if (link) for (let ancestor = parent; ancestor !== void 0; ancestor = directories.get(ancestor).parent) {
3353
+ if (identityOf(ancestor) !== identityOf(directory)) continue;
3354
+ if (realDirectory(ancestor) !== realDirectory(directory)) continue;
3355
+ logger.debug("glob", `${directory} leads back into ${ancestor}, which is read already`);
3356
+ directories.get(directory).cut = true;
3357
+ return [];
3358
+ }
3359
+ const entries = readdirSync(path, { withFileTypes: true });
3360
+ for (const entry of entries) if (entry.isSymbolicLink()) links.set(entryPath(String(path), entry.name), void 0);
3361
+ return options?.withFileTypes ? entries : entries.map((entry) => entry.name);
3362
+ });
3363
+ /** Every entry listed as a link that is one to a file. */
3364
+ const fileLinks = /* @__PURE__ */ new Set();
3365
+ const stat = ((path, options) => {
3366
+ const stats = statSync(path, options);
3367
+ const key = slashes(String(path));
3368
+ if (stats && links.has(key)) {
3369
+ links.set(key, identify(stats));
3370
+ if (stats.isFile()) fileLinks.add(key);
3371
+ }
3372
+ return stats;
3373
+ });
3374
+ /**
3375
+ * Where this walk began, and the folders and files it reached through a link, as it spelled them —
3376
+ * not a folder it read as empty, which is really one above it.
3377
+ */
3378
+ const linked = () => [...[...directories].flatMap(([directory, walked]) => (walked.parent === void 0 || walked.link) && !walked.cut ? [directory] : []), ...fileLinks];
3379
+ return {
3380
+ linked,
3381
+ fs: {
3382
+ readdirSync: readdir,
3383
+ statSync: stat
3384
+ }
3385
+ };
3386
+ };
2304
3387
  /**
2305
- * The order the source glob returns files in, made a decision rather than an accident.
2306
- *
2307
- * `fast-glob` hands back whatever `readdir` gave it, which is the filesystem's order and is not
2308
- * the same on every machine. That order is not cosmetic: it is the order atoms enter the sheet,
2309
- * and sheet order is what decides a conflict between two classes on one element — `cx` joins
2310
- * them and the browser picks by position, not by the order they were passed. So an unsorted
2311
- * glob lets two checkouts of the same commit build stylesheets that resolve the same conflict
2312
- * differently, and makes the emitted bytes irreproducible, which is also what content-hashed
2313
- * asset caching is keyed on.
3388
+ * A task's patterns, by the folder each is walked from when it is alone.
2314
3389
  *
2315
- * Sorted by code unit rather than `localeCompare`, whose answer depends on the host's locale —
2316
- * the exact class of machine-dependence this exists to remove.
3390
+ * `fast-glob` walks every pattern inside `cwd` from `.` once any of them starts there, which saves
3391
+ * reading folders twice — and would make where a loop closes, and so what a pattern behind a link
3392
+ * matches, hang on its neighbours: `src/a/loop/**` matches through `src/a/loop` when walked from
3393
+ * there, and nothing once `*.css` beside it has the walk start at `.` and meet `src` first.
2317
3394
  */
2318
- const sortSources = (files) => files.sort();
3395
+ const byOwnBase = (task, cwd) => {
3396
+ if (task.base !== "." || task.positive.length < 2) return [task.positive];
3397
+ return [...byWalk(task.positive, cwd).values()];
3398
+ };
2319
3399
  const nodeRuntime = {
2320
3400
  cwd() {
2321
3401
  return process.cwd();
@@ -2342,11 +3422,26 @@ const nodeRuntime = {
2342
3422
  },
2343
3423
  glob(opts) {
2344
3424
  if (!opts.include) return [];
2345
- return sortSources(glob.sync(opts.include, {
2346
- cwd: opts.cwd,
2347
- ignore: globIgnore(opts.exclude),
2348
- absolute: true
2349
- }));
3425
+ const { cwd } = opts;
3426
+ const walks = [];
3427
+ for (const task of glob.generateTasks(opts.include, {
3428
+ cwd,
3429
+ ignore: globIgnore(opts.exclude)
3430
+ })) {
3431
+ const negatives = task.negative.map((pattern) => `!${pattern}`);
3432
+ for (const patterns of byOwnBase(task, cwd)) {
3433
+ const walk = stopAtCycles();
3434
+ const found = glob.sync([...patterns, ...negatives], {
3435
+ absolute: true,
3436
+ cwd,
3437
+ fs: walk.fs
3438
+ });
3439
+ walks.push(found);
3440
+ opts.linked?.push(...walk.linked(), ...task.dynamic ? [] : found);
3441
+ }
3442
+ }
3443
+ const files = sortSources(walks.length === 1 ? walks[0] : walks.flat());
3444
+ return walks.length > 1 ? files.filter((file, index) => index === 0 || file !== files[index - 1]) : files;
2350
3445
  },
2351
3446
  writeFile: fsExtra.writeFile,
2352
3447
  writeFileSync: fsExtra.writeFileSync,
@@ -2363,11 +3458,8 @@ const nodeRuntime = {
2363
3458
  const { include, exclude, cwd, poll } = options;
2364
3459
  const coalesce = poll || process.platform === "win32";
2365
3460
  const dirnames = globDirname(include);
2366
- const isValidPath = picomatch(include, {
2367
- cwd,
2368
- ignore: exclude
2369
- });
2370
3461
  const workingDir = cwd || process.cwd();
3462
+ const isValidPath = sourceMatcher(include, exclude, workingDir);
2371
3463
  const watcher = chokidar.watch(dirnames, {
2372
3464
  usePolling: poll,
2373
3465
  cwd,
@@ -2398,6 +3490,59 @@ process.on("uncaughtException", (error) => {
2398
3490
  logger.caughtError("process", "Uncaught exception", error);
2399
3491
  });
2400
3492
  //#endregion
3493
+ //#region src/real-sources.ts
3494
+ const slashed = (path) => path.replaceAll("\\", "/");
3495
+ /**
3496
+ * The files, each real one once: under the first of the paths the glob reached it by.
3497
+ *
3498
+ * Two links in `include` to one folder — `src/shared` and `vendor/shared`, a package linked twice —
3499
+ * and the inventory holds each of its files under both, as it holds any file two paths reach,
3500
+ * which is how the watcher and a bundler naming a module have to find it. Extracted, each was
3501
+ * read twice for the same styles. The first of them in the inventory's order is the one kept: an
3502
+ * atom sits at the rank of the earliest file that wrote it, which is that one, so the stylesheet's
3503
+ * order is as it was.
3504
+ *
3505
+ * `linked` is what the glob reports reaching through a link, each resolved once; a glob that
3506
+ * reached none hands the files back as they are, without a look at the filesystem. Among it is
3507
+ * the folder each walk began at, and a file an exact pattern names, so a file reached directly is
3508
+ * compared as it really is too: a project under a link of its own — macOS's `/tmp` — is read once
3509
+ * as much as one under none.
3510
+ */
3511
+ const firstSpellingOfEachFile = (files, linked) => {
3512
+ if (!linked.length) return files;
3513
+ const links = [];
3514
+ for (const link of linked) {
3515
+ let real;
3516
+ try {
3517
+ real = slashed(realpathSync.native(link));
3518
+ } catch {
3519
+ continue;
3520
+ }
3521
+ const spelled = slashed(link);
3522
+ if (real !== spelled) links.push({
3523
+ spelled,
3524
+ spelledPrefix: `${spelled}/`,
3525
+ real
3526
+ });
3527
+ }
3528
+ if (!links.length) return files;
3529
+ links.sort((left, right) => right.spelled.length - left.spelled.length);
3530
+ const seen = /* @__PURE__ */ new Set();
3531
+ return files.filter((file) => {
3532
+ const path = slashed(file);
3533
+ let real = path;
3534
+ for (const { spelled, spelledPrefix, real: target } of links) {
3535
+ if (path === spelled) real = target;
3536
+ else if (path.startsWith(spelledPrefix)) real = target + path.slice(spelled.length);
3537
+ else continue;
3538
+ break;
3539
+ }
3540
+ if (seen.has(real)) return false;
3541
+ seen.add(real);
3542
+ return true;
3543
+ });
3544
+ };
3545
+ //#endregion
2401
3546
  //#region src/output-engine.ts
2402
3547
  var OutputEngine = class {
2403
3548
  paths;
@@ -2447,7 +3592,7 @@ var OutputEngine = class {
2447
3592
  * Subdirectories are left alone; they are swept as themselves when their own artifacts
2448
3593
  * are written.
2449
3594
  */
2450
- prune = (artifacts) => {
3595
+ prune = (artifacts, { dry = false } = {}) => {
2451
3596
  const produced = /* @__PURE__ */ new Map();
2452
3597
  /** Per directory, the file extensions this codegen wrote into it. */
2453
3598
  const kinds = /* @__PURE__ */ new Map();
@@ -2465,6 +3610,8 @@ var OutputEngine = class {
2465
3610
  }
2466
3611
  }
2467
3612
  let removed = 0;
3613
+ /** What was removed, or under `dry` what would be: `bamboo doctor` asks without removing. */
3614
+ const stale = [];
2468
3615
  for (const [dir, files] of produced) {
2469
3616
  if (!this.fs.existsSync(dir)) continue;
2470
3617
  const extensions = kinds.get(dir);
@@ -2473,13 +3620,18 @@ var OutputEngine = class {
2473
3620
  if (!extensions.has(this.path.extname(entry))) continue;
2474
3621
  const absPath = this.path.join(dir, entry);
2475
3622
  if (this.fs.isDirSync(absPath)) continue;
3623
+ stale.push(absPath);
3624
+ if (dry) continue;
2476
3625
  logger.debug("write:stale", `removing ${entry}`);
2477
3626
  this.fs.rmFileSync(absPath);
2478
3627
  removed++;
2479
3628
  }
2480
3629
  }
2481
3630
  if (removed) logger.debug("write:stale", `Removed ${removed} artifact(s) no longer generated`);
2482
- return { removed };
3631
+ return {
3632
+ removed,
3633
+ stale
3634
+ };
2483
3635
  };
2484
3636
  write = (output) => {
2485
3637
  if (!output) return;
@@ -2546,14 +3698,7 @@ var OutputEngine = class {
2546
3698
  //#endregion
2547
3699
  //#region src/create-context.ts
2548
3700
  /** A thrown value's message, for a `catch` binding that is typed `unknown`. */
2549
- const messageOf = (error) => error instanceof Error ? error.message : String(error);
2550
- const nativeBinaryName = () => {
2551
- if (process.platform === "darwin" && process.arch === "arm64") return "darwin-arm64.node";
2552
- if (process.platform === "darwin" && process.arch === "x64") return "darwin-x64.node";
2553
- if (process.platform === "linux" && process.arch === "arm64") return "linux-arm64-gnu.node";
2554
- if (process.platform === "linux" && process.arch === "x64") return "linux-x64-gnu.node";
2555
- if (process.platform === "win32" && process.arch === "x64") return "win32-x64-msvc.node";
2556
- };
3701
+ const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
2557
3702
  /**
2558
3703
  * What each loss is, and what the author can do about it.
2559
3704
  *
@@ -2568,6 +3713,32 @@ const unresolvedReasons = {
2568
3713
  "unenumerable-keys": () => ["an object spread or computed key leaves the build unable to tell which properties this call sets", "Write the properties out, or spread a value the build can resolve, to group it."],
2569
3714
  "unresolved-raw": (prop) => [`${prop}.raw() composes its own props rather than its styles, so ${prop}'s declarations will not reach the stylesheet`, `Call it instead — cx(${prop}(props), css({ … })) — or move the overrides into ${prop} itself.`]
2570
3715
  };
3716
+ /**
3717
+ * What the build warns about a style it could not read, in parts: what is lost, why, what to do
3718
+ * about it, and where to read more. The build's warning is all four; the editor's diagnostic —
3719
+ * `@bamboocss/eslint-plugin`'s `no-unresolved-styles` — the first and the third, the same words.
3720
+ *
3721
+ * A recipe does not degrade the way a `css()` call does, so it does not get the same explanation.
3722
+ * Its classes are named from a hash of its config: a declaration the build cannot see changes that
3723
+ * hash, the browser asks for a name no rule was emitted under, and *every* style is lost rather
3724
+ * than the unresolved one. A `css()` call's loss is partial — what the build saw still applies — so
3725
+ * its wording says which half is missing rather than implying the element is unstyled.
3726
+ */
3727
+ function explainUnresolvedStyle(entry) {
3728
+ const [loss] = unresolvedReasons[entry.reason](entry.prop ? `\`${entry.prop}\`` : "a property");
3729
+ const what = entry.prop ? `${loss} at \`${entry.prop}\`` : loss;
3730
+ return entry.kind === "recipe" ? {
3731
+ what,
3732
+ why: "A recipe's classes are named from a hash of its config, so a declaration the build cannot see gives the build and the browser different names and the element renders with no styles at all.",
3733
+ fix: "Set `className` on the recipe, so its name does not depend on what the build could resolve.",
3734
+ see: "https://bamboocss.com/docs/concepts/recipes"
3735
+ } : {
3736
+ what,
3737
+ why: "The build emits a rule per declaration it can see, and the runtime names a class for every declaration the object actually has — so the ones it could not see have no rule behind them and are simply absent.",
3738
+ fix: "Write the value out, or generate it with `staticCss` if it is genuinely dynamic.",
3739
+ see: "https://bamboocss.com/docs/guides/dynamic-styling"
3740
+ };
3741
+ }
2571
3742
  var BambooContext = class extends Generator {
2572
3743
  runtime;
2573
3744
  project;
@@ -2649,17 +3820,8 @@ var BambooContext = class extends Generator {
2649
3820
  for (const entry of unresolved) {
2650
3821
  if (this.isGenerated(entry.filePath)) continue;
2651
3822
  const where = `${entry.filePath}:${entry.line}:${entry.column}`;
2652
- const prop = entry.prop ? `\`${entry.prop}\`` : "a property";
2653
- const [what] = unresolvedReasons[entry.reason](prop);
2654
- if (entry.kind === "recipe") {
2655
- const at = entry.prop ? ` at \`${entry.prop}\`` : "";
2656
- logger.warn("recipe", `${where} — ${what}${at}. A recipe's classes are named from a hash of its config, so a declaration the build cannot see gives the build and the browser different names and the element renders with no styles at all. Set \`className\` on the recipe, so its name does not depend on what the build could resolve. See https://bamboocss.com/docs/concepts/recipes`);
2657
- continue;
2658
- }
2659
- {
2660
- const at = entry.prop ? ` at \`${entry.prop}\`` : "";
2661
- logger.warn("css", `${where} — ${what}${at}. The build emits a rule per declaration it can see, and the runtime names a class for every declaration the object actually has — so the ones it could not see have no rule behind them and are simply absent. Write the value out, or generate it with \`staticCss\` if it is genuinely dynamic. See https://bamboocss.com/docs/guides/dynamic-styling`);
2662
- }
3823
+ const { fix, see, what, why } = explainUnresolvedStyle(entry);
3824
+ logger.warn(entry.kind === "recipe" ? "recipe" : "css", `${where} — ${what}. ${why} ${fix} See ${see}`);
2663
3825
  }
2664
3826
  };
2665
3827
  getExplicitDependencies = () => {
@@ -2676,12 +3838,17 @@ var BambooContext = class extends Generator {
2676
3838
  title: this.messages.exclamation()
2677
3839
  });
2678
3840
  };
2679
- getFiles = () => {
3841
+ /**
3842
+ * The sources `include` names. `linked`, where given, is filled with where the glob began and
3843
+ * the folders and files it reached through a link: where a source may really be somewhere else.
3844
+ */
3845
+ getFiles = (linked) => {
2680
3846
  const { include, exclude, cwd } = this.config;
2681
3847
  return this.runtime.fs.glob({
2682
3848
  include,
2683
3849
  exclude,
2684
- cwd
3850
+ cwd,
3851
+ linked
2685
3852
  });
2686
3853
  };
2687
3854
  /**
@@ -2708,7 +3875,7 @@ var BambooContext = class extends Generator {
2708
3875
  const inScope = new Set(Array.from(files ?? this.getFiles(), (file) => this.runtime.path.abs(this.config.cwd, file)));
2709
3876
  for (const file of this.parseFailures.keys()) if (!inScope.has(file)) this.parseFailures.delete(file);
2710
3877
  if (!this.parseFailures.size) return;
2711
- const detail = truncateList(Array.from(this.parseFailures.entries(), ([file, error]) => `${this.relative(file)}\n${messageOf(error).replace(/^(?=.)/gm, " ")}`), { unit: "file" });
3878
+ const detail = truncateList(Array.from(this.parseFailures.entries(), ([file, error]) => `${this.relative(file)}\n${messageOf$1(error).replace(/^(?=.)/gm, " ")}`), { unit: "file" });
2712
3879
  throw new BambooError("EXTRACT_FAILED", `${this.parseFailures.size} file(s) could not be extracted:\n\n${detail}\n\nNothing emits a rule for a file the build could not read, so every style in these is absent from the stylesheet and the classes their components ask for have nothing behind them.`, { cause: new AggregateError(Array.from(this.parseFailures.values()), `${this.parseFailures.size} file(s) could not be extracted`) });
2713
3880
  };
2714
3881
  /**
@@ -2861,7 +4028,7 @@ var BambooContext = class extends Generator {
2861
4028
  let stamp;
2862
4029
  if (overridden) stamp = `overlay:${this.project.overlayRevision}`;
2863
4030
  else try {
2864
- const stat = statSync$1(filename);
4031
+ const stat = statSync(filename);
2865
4032
  stamp = `${stat.mtimeMs}:${stat.size}`;
2866
4033
  } catch {
2867
4034
  stamp = "missing";
@@ -2901,21 +4068,7 @@ var BambooContext = class extends Generator {
2901
4068
  return this.hookedAuxiliary;
2902
4069
  };
2903
4070
  hookedAuxiliary;
2904
- /** Load the required Rust extractor from the workspace or the published prebuild directory. */
2905
- loadNativeExtractor = () => {
2906
- const nativeRequire = createRequire(import.meta.url);
2907
- try {
2908
- return nativeRequire("@bamboocss/native-extractor");
2909
- } catch (workspaceError) {
2910
- const binary = nativeBinaryName();
2911
- if (!binary) throw new BambooError("NATIVE_EXTRACTION", `Native extraction is not available for ${process.platform}-${process.arch}.`, { cause: workspaceError });
2912
- try {
2913
- return nativeRequire(join$1(dirname$1(fileURLToPath(import.meta.url)), "native", binary));
2914
- } catch (publishedError) {
2915
- throw new BambooError("NATIVE_EXTRACTION", `Failed to load the native extractor binary ${binary}.`, { cause: publishedError });
2916
- }
2917
- }
2918
- };
4071
+ loadNativeExtractor = loadNativeExtractor;
2919
4072
  prepareNativeSource = (filePath, original) => {
2920
4073
  let parserOptions = {};
2921
4074
  const source = this.parserHooks["parser:before"]?.({
@@ -3201,13 +4354,16 @@ var BambooContext = class extends Generator {
3201
4354
  return uniq(Object.values(this.imports.matchers).flatMap((matcher) => matcher.mods));
3202
4355
  }
3203
4356
  /**
3204
- * The files this pass has to read, out of everything `include` matched.
4357
+ * The files this pass has to read, out of everything `include` matched: each real file once, and
4358
+ * of those the ones that can reach an entrypoint.
3205
4359
  *
3206
- * See `selectExtractable`. Kept behind a method so the reasons live in one place and a caller
4360
+ * See `firstSpellingOfEachFile`, given `linked` — what the glob reported reaching through a link —
4361
+ * and `selectExtractable`. Kept behind a method so the reasons live in one place and a caller
3207
4362
  * that wants the whole inventory — the watcher, the token scan — is unaffected: this narrows
3208
4363
  * what is *parsed*, not what the project holds.
3209
4364
  */
3210
- extractableFiles = (files) => {
4365
+ extractableFiles = (files, linked = []) => {
4366
+ files = firstSpellingOfEachFile(files, linked);
3211
4367
  this.nativePreparedSources.clear();
3212
4368
  const { baseUrl, paths } = this.project.resolutionOptions;
3213
4369
  const measure = logger.time.debug("Selected extractable files");
@@ -3237,7 +4393,8 @@ var BambooContext = class extends Generator {
3237
4393
  };
3238
4394
  parseFiles = (styleEncoder) => {
3239
4395
  const encoder = styleEncoder || this.parserOptions.encoder;
3240
- const files = this.extractableFiles(this.getFiles());
4396
+ const linked = [];
4397
+ const files = this.extractableFiles(this.getFiles(linked), linked);
3241
4398
  this.prepareNativeExtraction(files);
3242
4399
  const filesWithCss = [];
3243
4400
  const results = [];
@@ -3257,690 +4414,745 @@ var BambooContext = class extends Generator {
3257
4414
  };
3258
4415
  };
3259
4416
  writeCss = (sheet) => {
3260
- logger.info("css", this.runtime.path.join(...this.paths.root, "styles.css"));
3261
- return this.output.write({
3262
- id: "styles.css",
3263
- dir: this.paths.root,
3264
- files: [{
3265
- file: "styles.css",
3266
- code: this.getCss(sheet)
3267
- }]
3268
- });
3269
- };
3270
- writeSplitCss = async (sheet) => {
3271
- const { path: pathUtil, fs } = this.runtime;
3272
- const rootDir = this.paths.root;
3273
- const stylesDir = [...rootDir, "styles"];
3274
- const artifacts = this.getSplitCssArtifacts(sheet);
3275
- const subDirs = new Set(artifacts.themes.map((a) => a.dir).filter(Boolean));
3276
- fs.ensureDirSync(pathUtil.join(...stylesDir));
3277
- subDirs.forEach((dir) => fs.ensureDirSync(pathUtil.join(...stylesDir, dir)));
3278
- const styleFiles = [];
3279
- for (const layer of artifacts.layers) {
3280
- styleFiles.push({
3281
- file: layer.file,
3282
- code: layer.code
3283
- });
3284
- logger.info("css", pathUtil.join(...stylesDir, layer.file));
3285
- }
3286
- for (const theme of artifacts.themes) {
3287
- styleFiles.push({
3288
- file: `${theme.dir}/${theme.file}`,
3289
- code: theme.code
3290
- });
3291
- logger.info("css", pathUtil.join(...stylesDir, theme.dir, theme.file));
3292
- }
3293
- await this.output.write({
3294
- id: "styles",
3295
- dir: stylesDir,
3296
- files: styleFiles
3297
- });
3298
- logger.info("css", pathUtil.join(...rootDir, "styles.css"));
3299
- await this.output.write({
3300
- id: "styles.css",
3301
- dir: rootDir,
3302
- files: [{
3303
- file: "styles.css",
3304
- code: artifacts.index
3305
- }]
3306
- });
3307
- const recipesIndex = pathUtil.join(...stylesDir, "recipes.css");
3308
- const recipesDir = pathUtil.join(...stylesDir, "recipes");
3309
- if (fs.existsSync(recipesIndex)) fs.rmFileSync(recipesIndex);
3310
- if (fs.existsSync(recipesDir)) fs.rmFileSync(recipesDir);
3311
- };
3312
- watchConfig = (cb, opts) => {
3313
- const { cwd, poll, exclude } = opts ?? {};
3314
- logger.info("ctx:watch", this.messages.configWatch());
3315
- this.runtime.fs.watch({
3316
- include: uniq([...this.explicitDeps, ...this.conf.dependencies]),
3317
- exclude,
3318
- cwd,
3319
- poll
3320
- }).on("change", debounce(async (file) => {
3321
- logger.info("ctx:change", "config changed, rebuilding...");
3322
- await reportRebuildFailure(() => cb(file));
3323
- }));
3324
- };
3325
- watchFiles = (cb, opts) => {
3326
- const { include, exclude, poll, cwd } = this.config;
3327
- logger.info("ctx:watch", this.messages.watch());
3328
- this.runtime.fs.watch({
3329
- ...opts,
3330
- include,
3331
- exclude,
3332
- poll,
3333
- cwd
3334
- }).on("all", debounce(async (event, file) => {
3335
- logger.info(`file:${event}`, file);
3336
- await reportRebuildFailure(() => cb(event, file));
3337
- }));
3338
- };
3339
- };
3340
- /**
3341
- * Report a failed rebuild as a failed rebuild.
3342
- *
3343
- * Chokidar is an `EventEmitter`, so it discards whatever a listener returns, and the debounce
3344
- * wrapper attaches no rejection handler — a throw from inside a rebuild became a dangling
3345
- * promise. `node-runtime.ts` then catches it as `Unhandled rejection`, which labels a config
3346
- * error as an internal crash, leaves the exit code at 0, and is suppressed entirely at
3347
- * `logLevel: 'silent'`. The initial build is caught by the CLI and prints properly; only
3348
- * rebuilds of the identical source were silent, which is the worse half of the asymmetry.
3349
- *
3350
- * Caught rather than rethrown: a watcher's job is to survive a bad intermediate state and
3351
- * rebuild when the next edit fixes it. What it must not do is claim success.
3352
- */
3353
- async function reportRebuildFailure(run) {
3354
- try {
3355
- await run();
3356
- } catch (error) {
3357
- logger.error("ctx:rebuild", error instanceof Error ? error.message : String(error));
3358
- }
3359
- }
3360
- //#endregion
3361
- //#region src/config.ts
3362
- const RESOLVED_HOOKS_NAME = "__resolved__";
3363
- const AUTO_PARSER_HOOKS = Object.freeze([
3364
- "vue",
3365
- "svelte",
3366
- "astro"
3367
- ]);
3368
- const autoPluginFactories = {
3369
- astro: pluginAstro,
3370
- svelte: pluginSvelte,
3371
- vue: pluginVue
3372
- };
3373
- /**
3374
- * Built-in plugins that are auto-injected when using the CLI or PostCSS plugin.
3375
- * These provide Vue, Svelte and Astro single-file-component support.
3376
- *
3377
- * LightningCSS is not among them any more. It was reached through a `lightningcss: true`
3378
- * config flag whose only job was to push `pluginLightningcss()` into this list — a second
3379
- * way to say something `plugins` already said, and the expensive one: naming the plugin
3380
- * here meant a static import, which made `@bamboocss/plugin-lightningcss` a hard dependency
3381
- * of this package, which put a native binary in every install whether or not the flag was
3382
- * ever set. List the plugin yourself to use it.
3383
- */
3384
- function getAutoPlugins() {
3385
- return AUTO_PARSER_HOOKS.map((identity) => autoPluginFactories[identity]());
3386
- }
3387
- /** Resolve all config state without constructing the parser Project owned by BambooContext. */
3388
- async function prepareNodeConfig(options = {}) {
3389
- const { config, configPath } = options;
3390
- const cwd = options.cwd ?? options?.config?.cwd ?? process.cwd();
3391
- const conf = await loadConfig({
3392
- cwd,
3393
- file: configPath
3394
- });
3395
- if (config) Object.assign(conf.config, config);
3396
- if (options.cwd) conf.config.cwd = options.cwd;
3397
- if (options.dev) conf.config.dev = true;
3398
- const autoPlugins = getAutoPlugins();
3399
- conf.hooks = mergeHooks([...autoPlugins, {
3400
- name: RESOLVED_HOOKS_NAME,
3401
- hooks: conf.hooks
3402
- }]);
3403
- conf.config.plugins = [...autoPlugins, ...conf.config.plugins ?? []];
3404
- const tsconfigResolutionFiles = {};
3405
- const tsConfResult = await loadTsConfig(conf, cwd, void 0, tsconfigResolutionFiles);
3406
- if (tsConfResult) Object.assign(conf, tsConfResult);
3407
- rememberTsConfigResolutionFiles(conf, tsconfigResolutionFiles.value ?? []);
3408
- return { conf };
3409
- }
3410
- /**
3411
- * Load config and create context with auto-injected plugins.
3412
- * Used by the CLI and PostCSS plugin.
3413
- */
3414
- async function loadConfigAndCreateContext(options = {}) {
3415
- const { conf } = await prepareNodeConfig(options);
3416
- return new BambooContext(conf);
3417
- }
3418
- //#endregion
3419
- //#region src/source-snapshots.ts
3420
- /**
3421
- * Every file `include` covers, read once.
3422
- *
3423
- * The scans that decide what survives pruning — the token reference set, the reachability
3424
- * gate, the strict accounting — all want the same two copies of the same files, and each used
3425
- * to fetch them itself. A strict build therefore read every file three times over: once to
3426
- * collect references, once to account, and once more for the gate whenever the accounting
3427
- * declined. Yielding a snapshot lets one walk feed all of them.
3428
- *
3429
- * Both copies, because neither alone is complete and the text scans are safe when over-fed. A
3430
- * file the parser transformed is stored rewritten (`parseSourceFile` calls `replaceWithText`),
3431
- * and those transforms lose things the scans want: `svelteToTsx` and `vueToTsx` each swallow a
3432
- * throw and return an empty string, and a Vue SFC with a render function and no `<template>`
3433
- * becomes the literal `<template>undefined</template>`. Read only the parsed copy and a file
3434
- * like that reports no tokens and no elements at all.
3435
- *
3436
- * The parsed copy still has to be read as well, because `parser:before` is the documented way
3437
- * to teach bamboo a format it does not know. A template compiled to jsx by such a hook holds
3438
- * nothing a scan of the raw file would recognise, and that is the hook working as intended.
3439
- */
3440
- function* sourceSnapshots(ctx) {
3441
- for (const file of ctx.getFiles()) yield readSnapshot(ctx, ctx.runtime.path.abs(ctx.config.cwd, file));
3442
- }
3443
- /** One file's snapshot, for a walk that decides per file whether it needs to read at all. */
3444
- function readSnapshot(ctx, filePath) {
3445
- let onDisk;
3446
- try {
3447
- onDisk = ctx.runtime.fs.readFileSync(filePath);
3448
- } catch {
3449
- onDisk = void 0;
3450
- }
3451
- return {
3452
- filePath,
3453
- onDisk,
3454
- parsed: ctx.parsedSourceText(filePath, onDisk)
4417
+ logger.info("css", this.runtime.path.join(...this.paths.root, "styles.css"));
4418
+ return this.output.write({
4419
+ id: "styles.css",
4420
+ dir: this.paths.root,
4421
+ files: [{
4422
+ file: "styles.css",
4423
+ code: this.getCss(sheet)
4424
+ }]
4425
+ });
3455
4426
  };
3456
- }
3457
- /**
3458
- * The distinct texts a snapshot carries.
3459
- *
3460
- * One when the parser holds the file as written, two when a transform rewrote it. Every
3461
- * textual scan wants both, and wants neither twice.
3462
- */
3463
- function* snapshotTexts(snapshot) {
3464
- const { onDisk, parsed } = snapshot;
3465
- if (onDisk != null) yield onDisk;
3466
- if (parsed != null && parsed !== onDisk) yield parsed;
3467
- }
3468
- //#endregion
3469
- //#region src/token-accounting.ts
3470
- /**
3471
- * The one decline `prune.unresolvedPath: 'error'` fails the build on.
3472
- *
3473
- * That setting asserts that every token path resolves, and this is the reason that says otherwise:
3474
- * a token binding used in a way the build cannot follow — a path built at runtime, a binding
3475
- * assigned away, a namespace enumerated. It is about the author's *token usage*, and it has a
3476
- * fix at the call site.
3477
- *
3478
- * Nothing else may throw, because nothing else is necessarily about tokens at all. The other
3479
- * reasons were written under a premise this would break: declining was free, so every branch
3480
- * that could not prove a shape declined, and the accepted set was kept deliberately small.
3481
- * `import(`./pages/${name}`)` declines as `dynamic-import` because the specifier is not a
3482
- * literal and *could* be the artifact; `import lexer = require('./tokenizer')` declines because
3483
- * the statement contains the substring `token`. Both are routine code with nothing to do with
3484
- * design tokens, and failing a build over them would be indefensible. They keep every
3485
- * declaration, which is what they always did, and say so.
3486
- */
3487
- const failsStrict = (entry) => entry.reason === "unresolved-reference";
3488
- /**
3489
- * One file's contribution, split out so the build can account and scan in a single walk.
3490
- *
3491
- * `pruneTokensForBuild` needs the keep set, the reachability answer and this accounting from
3492
- * the same files; three separate passes read every file three times.
3493
- */
3494
- function accountSnapshot(ctx, snapshot, accounting) {
3495
- const { filePath, onDisk, parsed } = snapshot;
3496
- const { paths, prefixes, declined } = accounting;
3497
- {
3498
- if (onDisk == null || parsed == null || parsed !== onDisk) {
3499
- if (!(mentionsToken(ctx, onDisk) || mentionsToken(ctx, parsed))) return;
3500
- declined.push({
3501
- filePath,
3502
- line: 1,
3503
- reason: onDisk == null || parsed == null ? "unreadable" : "transformed"
4427
+ writeSplitCss = async (sheet) => {
4428
+ const { path: pathUtil, fs } = this.runtime;
4429
+ const rootDir = this.paths.root;
4430
+ const stylesDir = [...rootDir, "styles"];
4431
+ const artifacts = this.getSplitCssArtifacts(sheet);
4432
+ const subDirs = new Set(artifacts.themes.map((a) => a.dir).filter(Boolean));
4433
+ fs.ensureDirSync(pathUtil.join(...stylesDir));
4434
+ subDirs.forEach((dir) => fs.ensureDirSync(pathUtil.join(...stylesDir, dir)));
4435
+ const styleFiles = [];
4436
+ for (const layer of artifacts.layers) {
4437
+ styleFiles.push({
4438
+ file: layer.file,
4439
+ code: layer.code
3504
4440
  });
3505
- return;
4441
+ logger.info("css", pathUtil.join(...stylesDir, layer.file));
3506
4442
  }
3507
- if (!mentionsToken(ctx, parsed)) return;
3508
- const native = ctx.accountTokens(filePath, parsed);
3509
- if (native.unparsed) {
3510
- declined.push({
3511
- filePath,
3512
- line: 1,
3513
- reason: "unparsed"
4443
+ for (const theme of artifacts.themes) {
4444
+ styleFiles.push({
4445
+ file: `${theme.dir}/${theme.file}`,
4446
+ code: theme.code
3514
4447
  });
3515
- return;
4448
+ logger.info("css", pathUtil.join(...stylesDir, theme.dir, theme.file));
3516
4449
  }
3517
- for (const path of native.paths) paths.add(path);
3518
- for (const prefix of native.prefixes) prefixes.add(prefix);
3519
- for (const entry of native.declined) declined.push({
3520
- filePath,
3521
- ...entry
4450
+ await this.output.write({
4451
+ id: "styles",
4452
+ dir: stylesDir,
4453
+ files: styleFiles
3522
4454
  });
3523
- }
3524
- }
3525
- /**
3526
- * Whether a file is worth walking — because it can name the artifact, or because a shape in it
3527
- * declines without naming one.
3528
- *
3529
- * The obvious half is the substring `token`, which an import of the default entrypoint, a call,
3530
- * a member read and a `require` of it all put in the source. Three things defeat it, and each one
3531
- * is a silent under-keep rather than a slow build, so the test errs wide:
3532
- *
3533
- * - **A configured entrypoint need not spell it.** `importMap: { tokens: '@acme/design' }` and a
3534
- * tsconfig path mapping both make `isTokensEntrypoint` true for a specifier with no `token` in
3535
- * it, so the configured modules are tested for as well.
3536
- * - **An identifier may be written with unicode escapes.** An import specifier can spell the `t`
3537
- * of `token` as a backslash-u escape and still bind the export, which `nameOf` resolves and
3538
- * there is a test on. Both escape forms — the four-digit one and the braced one — begin with a
3539
- * backslash followed by `u`, so testing for that pair catches every spelling.
3540
- * - **`require()` and `import()` decline on a specifier this cannot read**, which is a statement
3541
- * about the specifier rather than about tokens: `import(`./pages/${name}`)` names nothing and
3542
- * declines all the same, because it *could* be the artifact. Skipping the file would drop that
3543
- * decline and with it the keep it was standing in for.
3544
- *
3545
- * A false positive costs one identifier walk. A false negative deletes a declaration something
3546
- * still asks for, so anything uncertain belongs on the walking side.
3547
- */
3548
- const IMPORTING_CALL = /\b(?:require|import)\s*\(/;
3549
- const mentionsToken = (ctx, text) => {
3550
- if (text == null) return false;
3551
- if (text.includes("token") || text.includes("\\u")) return true;
3552
- if (ctx.imports.value.tokens.some((mod) => text.includes(mod))) return true;
3553
- return IMPORTING_CALL.test(text);
3554
- };
3555
- //#endregion
3556
- //#region src/token-references.ts
3557
- /**
3558
- * `token('spacing.4')` and `token.value('colors.red.300')`, including the whitespace a
3559
- * formatter may leave behind. The parser reports both, resolving constants and template
3560
- * literals through them — `token.value()` included, since it is recorded as its own kind
3561
- * rather than dropped for having a property access as its callee. Scanning the text still
3562
- * earns its place twice over: it covers a path built somewhere the extractor cannot
3563
- * follow, and it covers the callers below that supply no `results` at all.
3564
- */
3565
- const TOKEN_CALL = /\btoken(?:\s*\.\s*value)?\s*\(\s*['"`]([^'"`]+)['"`]/g;
3566
- /** An import of the generated tokens artifact, under any of the spellings that reach it. */
3567
- const TOKEN_IMPORT = /\b(?:from|import|require)\s*\(?\s*['"][^'"]*\/tokens(\/[^'"]*|\.[cm]?[jt]sx?)?['"]/;
3568
- /** A call to `token()` or `token.value()`, whatever the argument is — or is not. */
3569
- const TOKEN_CALLEE = /\btoken(\s*\.\s*value)?\s*\(/;
3570
- /** The same, but only where the argument is a string literal — the shape `TOKEN_CALL` resolves. */
3571
- const TOKEN_CALL_LITERAL = /\btoken(?:\s*\.\s*value)?\s*\(\s*['"`]/;
3572
- /** String literals, contents and all. */
3573
- const STRING_LITERAL = /'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|`(?:[^`\\]|\\.)*`/g;
3574
- /**
3575
- * Whether a token is reached from javascript at all — a call of any shape, or an import of the
3576
- * artifact. It no longer decides pruning on its own: the accounting does that, and this is the
3577
- * gate the *fallback* defers to when the accounting declines. A project reaching for no token at
3578
- * all is one a decline cannot endanger, so it keeps nothing extra.
3579
- *
3580
- * The awkward part is that a token reference inside a css value is now spelled `token(…)` too,
3581
- * and it must *not* count: `css({ border: '1px solid token(colors.red.300)' })` reaches a token
3582
- * from a stylesheet, where the css scan already accounts for it, not from javascript. Reading it
3583
- * as a call turned pruning off wholesale — measured at 3.2x the stylesheet on a sandbox, since
3584
- * "keep everything" is what the gate means. It was only ever latent before, because `{…}` was
3585
- * the spelling the docs used and it looked nothing like a call.
3586
- *
3587
- * So a `token(` that survives blanking every string literal is a real call, and one that does
3588
- * not was written inside a string. The literal-argument test comes first and on the raw text,
3589
- * which is what keeps this a superset of `TOKEN_CALL` as the coupling in `collectTokenReferences`
3590
- * requires: a resolvable call embedded in a template literal — a fixture holding source code —
3591
- * still counts, even though blanking would hide it.
3592
- *
3593
- * No `g` flag on the tests, so `test` carries no state between files.
3594
- */
3595
- const reachableFromJs = (text) => {
3596
- if (TOKEN_IMPORT.test(text) || TOKEN_CALL_LITERAL.test(text)) return true;
3597
- return TOKEN_CALLEE.test(text) && TOKEN_CALLEE.test(text.replace(STRING_LITERAL, "''"));
4455
+ logger.info("css", pathUtil.join(...rootDir, "styles.css"));
4456
+ await this.output.write({
4457
+ id: "styles.css",
4458
+ dir: rootDir,
4459
+ files: [{
4460
+ file: "styles.css",
4461
+ code: artifacts.index
4462
+ }]
4463
+ });
4464
+ const recipesIndex = pathUtil.join(...stylesDir, "recipes.css");
4465
+ const recipesDir = pathUtil.join(...stylesDir, "recipes");
4466
+ if (fs.existsSync(recipesIndex)) fs.rmFileSync(recipesIndex);
4467
+ if (fs.existsSync(recipesDir)) fs.rmFileSync(recipesDir);
4468
+ };
4469
+ watchConfig = (cb, opts) => {
4470
+ const { cwd, poll, exclude } = opts ?? {};
4471
+ logger.info("ctx:watch", this.messages.configWatch());
4472
+ const watcher = this.runtime.fs.watch({
4473
+ include: uniq([...this.explicitDeps, ...this.conf.dependencies]),
4474
+ exclude,
4475
+ cwd,
4476
+ poll
4477
+ });
4478
+ const rebuild = debounce(async (file) => {
4479
+ logger.info("ctx:change", "config changed, rebuilding...");
4480
+ await reportRebuildFailure(() => cb(file));
4481
+ });
4482
+ watcher.on("all", (event, file) => {
4483
+ if (event === "add" || event === "change") rebuild(file);
4484
+ });
4485
+ };
4486
+ watchFiles = (cb, opts) => {
4487
+ const { include, exclude, poll, cwd } = this.config;
4488
+ logger.info("ctx:watch", this.messages.watch());
4489
+ this.runtime.fs.watch({
4490
+ ...opts,
4491
+ include,
4492
+ exclude,
4493
+ poll,
4494
+ cwd
4495
+ }).on("all", debounce(async (event, file) => {
4496
+ logger.info(`file:${event}`, file);
4497
+ await reportRebuildFailure(() => cb(event, file));
4498
+ }));
4499
+ };
3598
4500
  };
3599
4501
  /**
3600
- * The text of every file `include` covers — as written on disk, and, when they differ, as the
3601
- * parser understands it.
3602
- *
3603
- * Both, because neither alone is complete and every scan below is safe when over-fed. A file
3604
- * the parser transformed is stored rewritten (`parseSourceFile` calls `replaceWithText`), and
3605
- * those transforms lose things the scans want: `svelteToTsx` and `vueToTsx` each swallow a
3606
- * throw and return an empty string, and a Vue SFC with a render function and no `<template>`
3607
- * becomes the literal `<template>undefined</template>`. Read only the parsed copy and a file
3608
- * like that reports no tokens and no elements at all.
3609
- *
3610
- * The parsed copy still has to be read as well, because `parser:before` is the documented way
3611
- * to teach bamboo a format it does not know. A template compiled to jsx by such a hook holds
3612
- * nothing a scan of the raw file would recognise, and that is the hook working as intended.
4502
+ * Report a failed rebuild as a failed rebuild.
3613
4503
  *
3614
- * So the cost is one extra read per file, and a second regex pass over the files a transform
3615
- * actually changed. Measured at ~14ms for 806 files, against a build where css emission alone
3616
- * is an order of magnitude more.
3617
- */
3618
- function* sourceTexts(ctx) {
3619
- for (const snapshot of sourceSnapshots(ctx)) yield* snapshotTexts(snapshot);
3620
- }
3621
- const createSourceScanCache = () => ({
3622
- signature: "",
3623
- entries: /* @__PURE__ */ new Map(),
3624
- resolvedTokenReferences: /* @__PURE__ */ new Map()
3625
- });
3626
- const resolvedTokenReferences = (result) => {
3627
- if (!result) return [];
3628
- const facts = [];
3629
- for (const item of result.token) {
3630
- if (!item.tokenCalleeRange || !item.data?.length) continue;
3631
- const paths = [];
3632
- for (const value of item.data) {
3633
- if (typeof value !== "string") break;
3634
- paths.push(value);
3635
- }
3636
- if (paths.length !== item.data.length) continue;
3637
- facts.push({
3638
- ...item.tokenCalleeRange,
3639
- paths: [...new Set(paths)].sort()
3640
- });
4504
+ * Chokidar is an `EventEmitter`, so it discards whatever a listener returns, and the debounce
4505
+ * wrapper attaches no rejection handler — a throw from inside a rebuild became a dangling
4506
+ * promise. `node-runtime.ts` then catches it as `Unhandled rejection`, which labels a config
4507
+ * error as an internal crash, leaves the exit code at 0, and is suppressed entirely at
4508
+ * `logLevel: 'silent'`. The initial build is caught by the CLI and prints properly; only
4509
+ * rebuilds of the identical source were silent, which is the worse half of the asymmetry.
4510
+ *
4511
+ * Caught rather than rethrown: a watcher's job is to survive a bad intermediate state and
4512
+ * rebuild when the next edit fixes it. What it must not do is claim success.
4513
+ */
4514
+ async function reportRebuildFailure(run) {
4515
+ try {
4516
+ await run();
4517
+ } catch (error) {
4518
+ logger.error("ctx:rebuild", error instanceof Error ? error.message : String(error));
3641
4519
  }
3642
- return facts.sort((left, right) => left.start - right.start || left.end - right.end);
3643
- };
3644
- const sameResolvedTokenReferences = (left, right) => (left?.length ?? 0) === right.length && right.every((fact, index) => fact.start === left[index].start && fact.end === left[index].end && fact.paths.length === left[index].paths.length && fact.paths.every((path, pathIndex) => path === left[index].paths[pathIndex]));
4520
+ }
4521
+ //#endregion
4522
+ //#region src/mdx-to-tsx.ts
4523
+ const MDX_FILE = /\.mdx$/i;
4524
+ /** Every character but a line ending: a blanked span keeps where its lines break. */
4525
+ const NOT_LINE_ENDING = /[^\r\n]/g;
4526
+ const blank = (text) => text.replace(NOT_LINE_ENDING, " ");
4527
+ /** Frontmatter, YAML or TOML, opening the file. */
4528
+ const FRONTMATTER = /^(?:---[ \t]*\r?\n(?:[\s\S]*?\r?\n)?---|\+\+\+[ \t]*\r?\n(?:[\s\S]*?\r?\n)?\+\+\+)[ \t]*(?:\r?\n|$)/;
4529
+ /** An import or export as MDX reads one: the keyword at the start of a line, then a space. */
4530
+ const ESM = /^(?:import|export) /;
4531
+ /** The blockquote and list markers a line opens with: the containers what follows is in. */
4532
+ const CONTAINERS = /^(?:[ \t]*(?:>[ \t]?|(?:[-+*]|\d{1,9}[.)])[ \t]+))*/;
4533
+ /** A code fence: the run, and its info. */
4534
+ const FENCE = /^[ \t]*(`{3,}|~{3,})(.*)$/;
4535
+ const FENCE_CLOSE = /^[ \t]*(`{3,}|~{3,})[ \t]*$/;
4536
+ /** A list item's marker, and the space after it: where its content starts. */
4537
+ const LIST_ITEM = /^([ \t]*)([-+*]|\d{1,9}[.)])([ \t]+|$)/;
4538
+ /** A list item that can interrupt a paragraph: not empty, and if ordered, numbered 1. */
4539
+ const LIST_INTERRUPT = /^[ \t]{0,3}(?:[-+*]|1[.)])[ \t]+\S/;
4540
+ /** A line opening with a tag or an expression, which MDX lets interrupt a paragraph. */
4541
+ const JSX_OR_EXPRESSION = /^[ \t]*(?:<(?:[/>]|[\p{ID_Start}$_])|\{)/u;
4542
+ /** Display math, which `remark-math` reads as text, opening a line. */
4543
+ const MATH_FENCE = /^[ \t]*\$\$/;
4544
+ /** What tells math from a dollar amount: a LaTeX command, `\frac` — whose `{a}{b}` holds no expression. */
4545
+ const LATEX = /\\[a-z]/i;
3645
4546
  /**
3646
- * Reconcile one file's lightweight token facts after extraction.
3647
- *
3648
- * Deleting the source scan only when the semantic facts moved is important for dependents:
3649
- * changing an imported constant can change `token(KEY)` without changing the consumer's mtime.
4547
+ * A link reference definition, `[label]: destination 'title'`, the whole line: a URL, braces and
4548
+ * all. Not a footnote, `[^1]:`, whose text is Markdown. Its title, where it has one on the line.
3650
4549
  */
3651
- const recordResolvedTokenReferences = (cache, filePath, result) => {
3652
- const next = resolvedTokenReferences(result);
3653
- if (sameResolvedTokenReferences(cache.resolvedTokenReferences.get(filePath), next)) return;
3654
- if (next.length) cache.resolvedTokenReferences.set(filePath, next);
3655
- else cache.resolvedTokenReferences.delete(filePath);
3656
- cache.entries.delete(filePath);
4550
+ const DEFINITION = /^[ \t]{0,3}\[(?!\^)(?:[^\]\\\n]|\\.)+\]:[ \t]*(?:<[^<>\n]*>|[^\s<>]\S*)(?:[ \t]+("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|\((?:[^()\\\n]|\\.)*\)))?[ \t]*$/;
4551
+ /** A definition's title, on the line after it. */
4552
+ const DEFINITION_TITLE = /^[ \t]*(?:"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|\((?:[^()\\\n]|\\.)*\))[ \t]*$/;
4553
+ /** What follows a link's text: `(destination 'title')`. */
4554
+ const LINK_RESOURCE = /^\(\s*(?:<[^<>\n]*>|(?:[^\s()<>\\]|\\.|\((?:[^\s()<>\\]|\\.)*\))*)(?:\s+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?\s*\)/;
4555
+ /** How far a link's destination is looked for: past it, a `](` is prose. */
4556
+ const DESTINATION_LIMIT = 2048;
4557
+ const ATX_HEADING = /^ {0,3}#{1,6}(?:[ \t]|$)/;
4558
+ const THEMATIC_BREAK = /^ {0,3}(?:(?:\*[ \t]*){3,}|(?:_[ \t]*){3,}|(?:-[ \t]*){3,})$/;
4559
+ /** The line under a paragraph that makes it a heading. */
4560
+ const SETEXT_UNDERLINE = /^ {0,3}(?:=+|-+)[ \t]*$/;
4561
+ const NAME_START = /[\p{ID_Start}$_]/u;
4562
+ const IDENTIFIER = /[\p{ID_Start}$_][\p{ID_Continue}$]*/uy;
4563
+ const NUMBER = /[\d.][\w.]*/y;
4564
+ const ASCII_PUNCTUATION = /[!-/:-@[-`{-~]/;
4565
+ /** `<https://…>`, `<mailto:…>`, `<a@b.c>`: links, not JSX — and an error to MDX besides. */
4566
+ const AUTOLINK = /<(?:[a-z][a-z\d+.-]{1,31}:[^\s<>]*|[\w.!#$%&'*+/=?^`{|}~-]+@[a-z\d](?:[a-z\d-]*[a-z\d])?(?:\.[a-z\d](?:[a-z\d-]*[a-z\d])?)*)>/iy;
4567
+ /** After these, what follows starts an expression: a `/` opens a regular expression, a `<` JSX. */
4568
+ const OPERATOR_KEYWORDS = new Set([
4569
+ "await",
4570
+ "case",
4571
+ "delete",
4572
+ "do",
4573
+ "else",
4574
+ "extends",
4575
+ "in",
4576
+ "instanceof",
4577
+ "new",
4578
+ "of",
4579
+ "return",
4580
+ "throw",
4581
+ "typeof",
4582
+ "void",
4583
+ "yield"
4584
+ ]);
4585
+ /**
4586
+ * Where the `depth`th blockquote marker a line starts with ends — past the space after it — or
4587
+ * `-1` for a line in fewer blockquotes than that.
4588
+ */
4589
+ const pastQuotes = (line, depth) => {
4590
+ let i = 0;
4591
+ for (let quote = 0; quote < depth; quote++) {
4592
+ while (line[i] === " " || line[i] === " ") i++;
4593
+ if (line[i] !== ">") return -1;
4594
+ i++;
4595
+ if (line[i] === " " || line[i] === " ") i++;
4596
+ }
4597
+ return i;
3657
4598
  };
3658
- const reconcileAccounting = (accounting, references, filePath) => {
3659
- if (!references?.length) return;
3660
- const ranges = new Set(references.map(({ start, end }) => `${start}:${end}`));
3661
- for (const reference of references) for (const path of reference.paths) accounting.paths.add(path);
3662
- accounting.declined = accounting.declined.filter((entry) => entry.reason !== "unresolved-reference" || filePath !== void 0 && entry.filePath !== filePath || entry.start == null || entry.end == null || !ranges.has(`${entry.start}:${entry.end}`));
4599
+ /** How many blockquotes a line is in. */
4600
+ const quoteDepth = (line) => {
4601
+ let depth = 0;
4602
+ while (pastQuotes(line, depth + 1) !== -1) depth++;
4603
+ return depth;
3663
4604
  };
3664
- const OPEN_TAG = /<\s*([a-z][\w-]*)(?=[\s/>]|$)/g;
3665
- const scanSnapshot = (ctx, snapshot, options, patterns, resolvedReferences) => {
3666
- const tokenPaths = /* @__PURE__ */ new Set();
3667
- const cssVars = /* @__PURE__ */ new Set();
3668
- const elements = /* @__PURE__ */ new Set();
3669
- const keyframeHits = /* @__PURE__ */ new Set();
3670
- let reachable = false;
3671
- for (const text of snapshotTexts(snapshot)) {
3672
- for (const match of text.matchAll(TOKEN_CALL)) tokenPaths.add(match[1]);
3673
- for (const name of cssVarRefs(text)) cssVars.add(name);
3674
- if (!reachable && reachableFromJs(text)) reachable = true;
3675
- if (options.elements) for (const match of text.matchAll(OPEN_TAG)) elements.add(match[1].toLowerCase());
3676
- for (const [name, pattern] of patterns) if (!keyframeHits.has(name) && pattern.test(text)) keyframeHits.add(name);
3677
- }
3678
- const accounting = {
3679
- paths: /* @__PURE__ */ new Set(),
3680
- prefixes: /* @__PURE__ */ new Set(),
3681
- declined: []
3682
- };
3683
- accountSnapshot(ctx, snapshot, accounting);
3684
- reconcileAccounting(accounting, resolvedReferences);
3685
- return {
3686
- tokenPaths: [...tokenPaths],
3687
- cssVars: [...cssVars],
3688
- reachableFromJs: reachable,
3689
- elements: [...elements],
3690
- keyframeHits: [...keyframeHits],
3691
- accountingPaths: [...accounting.paths],
3692
- accountingPrefixes: [...accounting.prefixes],
3693
- accountingDeclined: accounting.declined
3694
- };
4605
+ /** A fence opening `text`, or `null`: a backtick fence's info has no backtick, or it is inline code. */
4606
+ const fenceOf = (text) => {
4607
+ const fence = FENCE.exec(text);
4608
+ return fence && !(fence[1].startsWith("`") && fence[2].includes("`")) ? fence[1] : null;
3695
4609
  };
3696
4610
  /**
3697
- * Every source-derived answer the pruning passes need, from one walk over the sources.
4611
+ * How far a list item's content is from its marker: past the spaces after it. CommonMark starts it
4612
+ * one past the marker where five or more follow, which would be an indented code block — and MDX,
4613
+ * having none, does not.
4614
+ */
4615
+ const contentOffset = (spaces) => spaces.length || 1;
4616
+ /** A line inside the blockquotes it is in: what their markers leave of it. */
4617
+ const unquote = (line) => line.slice(pastQuotes(line, quoteDepth(line)));
4618
+ /** Where a line's text starts. */
4619
+ const indentation = (line) => line.search(/\S|$/);
4620
+ /**
4621
+ * An `.mdx` file as TSX the extractor can parse.
3698
4622
  *
3699
- * The token scan, the reachability gate, the strict accounting, the keyframe references and
3700
- * the rendered-element set all read the same two copies of the same files, and each caller
3701
- * used to run its own sweep — `Builder.toCss` paid the walk up to three times per stylesheet.
3702
- * This is the same de-duplication `pruneTokensForBuild` already performed for its own three
3703
- * answers, extended to all five.
4623
+ * It reached the parser as it was, and Markdown is not TSX: the first apostrophe in a paragraph
4624
+ * failed the file, and every style in it left the stylesheet. One that parsed anyway — JSX and
4625
+ * nothing else — had the `css()` in a code example read as a call, when to MDX it is a string.
3704
4626
  *
3705
- * With a `cache`, a file whose mtime has not moved is not even read: its previous contribution
3706
- * merges as-is, which is what turns the walk from O(project) to O(changed) on a rebuild.
3707
- * Without one — the one-shot CLI paths — the keyframe scan keeps its historical early exit:
3708
- * once every declared name is found, later files skip those tests.
4627
+ * So what MDX runs stays where it stands, and what it shows goes. Its imports and exports are
4628
+ * kept as they are, and each JSX tag and `{expression}` as it is written, in a fragment; prose,
4629
+ * code, comments and frontmatter between them become spaces, with every line ending kept, so a
4630
+ * line is where it was. A JSX element's children are Markdown to MDX as well, and blanked the
4631
+ * same way; an import among them, which MDX hoists, is moved to the end, where it binds the same.
4632
+ *
4633
+ * Not MDX's parser, which is asynchronous and ESM — `parser:before` is neither — but what MDX
4634
+ * reads them by: an import or export at the start of a line that does not continue a paragraph,
4635
+ * running to the next blank line once nothing it opened is still open; an element's tag, its
4636
+ * attributes read as JavaScript; an expression to the brace that closes it, a blockquote's `>`
4637
+ * at the start of each of its lines left out; a code block to its fence, or to the end of the
4638
+ * blockquote or list item it is in.
3709
4639
  */
3710
- function collectSourceScans(ctx, options, cache, mtimeOf, files) {
3711
- const result = {
3712
- tokenPaths: /* @__PURE__ */ new Set(),
3713
- cssVars: /* @__PURE__ */ new Set(),
3714
- reachableFromJs: false,
3715
- elements: /* @__PURE__ */ new Set(),
3716
- keyframeHits: /* @__PURE__ */ new Set(),
3717
- accounting: {
3718
- paths: /* @__PURE__ */ new Set(),
3719
- prefixes: /* @__PURE__ */ new Set(),
3720
- declined: []
4640
+ const mdxToTsx = (input) => {
4641
+ const length = input.length;
4642
+ /** The blockquotes a tag or an expression being read is in: the `>` opening each line it runs on is theirs. */
4643
+ let quoted = 0;
4644
+ const lineEnd = (at) => {
4645
+ const end = input.indexOf("\n", at);
4646
+ return end === -1 ? length : end;
4647
+ };
4648
+ const lineAt = (at) => input.slice(at, lineEnd(at)).replace(/\r$/, "");
4649
+ const isBlankLine = (at) => {
4650
+ for (let i = at; i < length; i++) {
4651
+ const c = input[i];
4652
+ if (c === "\n") return true;
4653
+ if (c !== " " && c !== " " && c !== "\r") return false;
3721
4654
  }
4655
+ return true;
3722
4656
  };
3723
- const signature = `${options.elements ? 1 : 0}\n${options.keyframeNames.join("\n")}`;
3724
- if (cache && cache.signature !== signature) {
3725
- cache.entries.clear();
3726
- cache.signature = signature;
3727
- }
3728
- const allPatterns = options.keyframeNames.map((name) => [name, new RegExp(`\\b${escapeRegExp(name)}\\b`)]);
3729
- const remaining = cache ? void 0 : new Set(options.keyframeNames);
3730
- const merge = (scan) => {
3731
- for (const path of scan.tokenPaths) result.tokenPaths.add(path);
3732
- for (const name of scan.cssVars) result.cssVars.add(name);
3733
- if (scan.reachableFromJs) result.reachableFromJs = true;
3734
- for (const element of scan.elements) result.elements.add(element);
3735
- for (const name of scan.keyframeHits) {
3736
- result.keyframeHits.add(name);
3737
- remaining?.delete(name);
4657
+ /** The start of a line, past the markers of the blockquotes being read in. */
4658
+ const lineStart = (at) => {
4659
+ if (!quoted) return at;
4660
+ const past = pastQuotes(lineAt(at), quoted);
4661
+ return past === -1 ? at : at + past;
4662
+ };
4663
+ const skipBlockComment = (at) => {
4664
+ const end = input.indexOf("*/", at + 2);
4665
+ return end === -1 ? length : end + 2;
4666
+ };
4667
+ /** Past a quoted string, or at the line's end where it does not close. */
4668
+ const skipString = (at) => {
4669
+ const quote = input[at];
4670
+ for (let i = at + 1; i < length; i++) {
4671
+ const c = input[i];
4672
+ if (c === "\\") i++;
4673
+ else if (c === quote) return i + 1;
4674
+ else if (c === "\n") return i;
3738
4675
  }
3739
- for (const path of scan.accountingPaths) result.accounting.paths.add(path);
3740
- for (const prefix of scan.accountingPrefixes) result.accounting.prefixes.add(prefix);
3741
- result.accounting.declined.push(...scan.accountingDeclined);
4676
+ return length;
3742
4677
  };
3743
- const seen = cache ? /* @__PURE__ */ new Set() : void 0;
3744
- for (const file of files ?? ctx.getFiles()) {
3745
- const filePath = ctx.runtime.path.abs(ctx.config.cwd, file);
3746
- seen?.add(filePath);
3747
- if (cache) {
3748
- const mtime = mtimeOf?.(filePath) ?? (existsSync(filePath) ? statSync(filePath).mtimeMs : -Infinity);
3749
- const entry = cache.entries.get(filePath);
3750
- if (entry && entry.mtime === mtime) {
3751
- merge(entry.scan);
4678
+ const skipTemplate = (at) => {
4679
+ let i = at + 1;
4680
+ while (i < length) {
4681
+ const c = input[i];
4682
+ if (c === "\\") i += 2;
4683
+ else if (c === "`") return i + 1;
4684
+ else if (c === "$" && input[i + 1] === "{") i = skipScript(i + 2, "brace");
4685
+ else i++;
4686
+ }
4687
+ return length;
4688
+ };
4689
+ /** Past a regular expression, or at the line's end, where a `/` turns out to have divided. */
4690
+ const skipRegex = (at) => {
4691
+ let inClass = false;
4692
+ for (let i = at + 1; i < length; i++) {
4693
+ const c = input[i];
4694
+ if (c === "\\") i++;
4695
+ else if (c === "\n") return i;
4696
+ else if (inClass) inClass = c !== "]";
4697
+ else if (c === "[") inClass = true;
4698
+ else if (c === "/") {
4699
+ IDENTIFIER.lastIndex = i + 1;
4700
+ return i + 1 + (IDENTIFIER.exec(input)?.[0].length ?? 0);
4701
+ }
4702
+ }
4703
+ return length;
4704
+ };
4705
+ const startsElement = (at) => {
4706
+ const next = input[at + 1];
4707
+ return next === ">" || next !== void 0 && NAME_START.test(next);
4708
+ };
4709
+ /**
4710
+ * Past a JSX tag: `<name`, its attributes — strings, `{expressions}` and comments whole, where a
4711
+ * `>` closes nothing — and the `>` or `/>` that ends it.
4712
+ */
4713
+ const skipTag = (at) => {
4714
+ let i = at + 1;
4715
+ const closing = input[i] === "/";
4716
+ if (closing) i++;
4717
+ let value = false;
4718
+ while (i < length) {
4719
+ const c = input[i];
4720
+ if (c === ">") return {
4721
+ end: i + 1,
4722
+ closing,
4723
+ selfClosing: false
4724
+ };
4725
+ if (c === "/") {
4726
+ const next = input[i + 1];
4727
+ if (next === ">") return {
4728
+ end: i + 2,
4729
+ closing,
4730
+ selfClosing: true
4731
+ };
4732
+ i = next === "*" ? skipBlockComment(i) : next === "/" ? lineEnd(i) : i + 1;
3752
4733
  continue;
3753
4734
  }
3754
- const scan = scanSnapshot(ctx, readSnapshot(ctx, filePath), options, allPatterns, cache.resolvedTokenReferences.get(filePath));
3755
- cache.entries.set(filePath, {
3756
- mtime,
3757
- scan
4735
+ if (c === "\"" || c === "'") {
4736
+ const end = input.indexOf(c, i + 1);
4737
+ i = end === -1 ? length : end + 1;
4738
+ } else if (c === "{") i = skipScript(i + 1, "brace");
4739
+ else if (c === "<" && value && startsElement(i)) i = skipElement(i);
4740
+ else if (c === "\n") i = lineStart(i + 1);
4741
+ else i++;
4742
+ if (c !== " " && c !== " " && c !== "\r" && c !== "\n") value = c === "=";
4743
+ }
4744
+ return {
4745
+ end: length,
4746
+ closing,
4747
+ selfClosing: false
4748
+ };
4749
+ };
4750
+ /**
4751
+ * Past a JSX element inside JavaScript, whose children are JSX text rather than Markdown. One
4752
+ * tag at a time, counting what each opens and closes, so a deep element is not a deep stack.
4753
+ */
4754
+ const skipElement = (at) => {
4755
+ let open = 0;
4756
+ let i = at;
4757
+ while (i < length) {
4758
+ const tag = skipTag(i);
4759
+ i = tag.end;
4760
+ if (tag.closing) open--;
4761
+ else if (!tag.selfClosing) open++;
4762
+ if (open <= 0) return i;
4763
+ while (i < length) {
4764
+ const c = input[i];
4765
+ if (c === "{") i = skipScript(i + 1, "brace");
4766
+ else if (c === "<" && (input[i + 1] === "/" || startsElement(i))) break;
4767
+ else i++;
4768
+ }
4769
+ }
4770
+ return length;
4771
+ };
4772
+ /**
4773
+ * Where JavaScript starting at `at` ends: past the `}` that closes a brace already open, or —
4774
+ * an import or export — past the line before a blank one, once nothing it opened is open.
4775
+ *
4776
+ * As much of the language as finding that needs: strings, templates, comments, regular
4777
+ * expressions and JSX, so that a brace, a blank line or an apostrophe in one is not read as
4778
+ * the end.
4779
+ */
4780
+ const skipScript = (at, until) => {
4781
+ let braces = until === "brace" ? 1 : 0;
4782
+ let brackets = 0;
4783
+ let expression = true;
4784
+ let i = at;
4785
+ while (i < length) {
4786
+ const c = input[i];
4787
+ if (c === "\"" || c === "'") {
4788
+ i = skipString(i);
4789
+ expression = false;
4790
+ } else if (c === "`") {
4791
+ i = skipTemplate(i);
4792
+ expression = false;
4793
+ } else if (c === "/" && input[i + 1] === "/") i = lineEnd(i);
4794
+ else if (c === "/" && input[i + 1] === "*") i = skipBlockComment(i);
4795
+ else if (c === "/" && expression) {
4796
+ i = skipRegex(i);
4797
+ expression = false;
4798
+ } else if (c === "<" && expression && startsElement(i)) {
4799
+ i = skipElement(i);
4800
+ expression = false;
4801
+ } else if (c === "{" || c === "(" || c === "[") {
4802
+ if (c === "{") braces++;
4803
+ else brackets++;
4804
+ i++;
4805
+ expression = true;
4806
+ } else if (c === "}") {
4807
+ i++;
4808
+ if (--braces === 0 && until === "brace") return i;
4809
+ expression = true;
4810
+ } else if (c === ")" || c === "]") {
4811
+ brackets--;
4812
+ i++;
4813
+ expression = false;
4814
+ } else if (c === "\n") {
4815
+ i = lineStart(i + 1);
4816
+ if (until === "statement" && braces <= 0 && brackets <= 0 && isBlankLine(i)) return i;
4817
+ } else if (c === " " || c === " " || c === "\r") i++;
4818
+ else if (NAME_START.test(c)) {
4819
+ IDENTIFIER.lastIndex = i;
4820
+ const word = IDENTIFIER.exec(input)[0];
4821
+ i += word.length;
4822
+ expression = OPERATOR_KEYWORDS.has(word);
4823
+ } else if (c >= "0" && c <= "9") {
4824
+ NUMBER.lastIndex = i;
4825
+ i += NUMBER.exec(input)[0].length;
4826
+ expression = false;
4827
+ } else {
4828
+ i++;
4829
+ expression = c !== ".";
4830
+ }
4831
+ }
4832
+ return length;
4833
+ };
4834
+ /** Whether the line at `at`, in `quotes` blockquotes, ends the paragraph above it: blank, or a block of its own. */
4835
+ const endsParagraph = (at, quotes) => {
4836
+ const line = lineAt(at);
4837
+ const past = pastQuotes(line, quotes);
4838
+ const body = past === -1 ? unquote(line) : line.slice(past);
4839
+ if (!body.trim()) return true;
4840
+ if (past !== -1 && quoteDepth(body) > 0) return true;
4841
+ return fenceOf(body) !== null || ATX_HEADING.test(body) || THEMATIC_BREAK.test(body) || LIST_INTERRUPT.test(body) || JSX_OR_EXPRESSION.test(body);
4842
+ };
4843
+ /**
4844
+ * Where a span opened by `size` of `marker` closes: the next run as long, in the paragraph.
4845
+ * Where none does, remembered to the paragraph's end, so the next run asking is answered at once.
4846
+ */
4847
+ const unclosed = /* @__PURE__ */ new Map();
4848
+ const closingRun = (at, marker, size, quotes) => {
4849
+ const key = marker + size;
4850
+ if (at < (unclosed.get(key) ?? -1)) return -1;
4851
+ let i = at;
4852
+ while (i < length) {
4853
+ const c = input[i];
4854
+ if (c === marker) {
4855
+ let run = 0;
4856
+ while (input[i + run] === marker) run++;
4857
+ if (run === size) return i;
4858
+ i += run;
4859
+ } else if (c === "\n" && endsParagraph(i + 1, quotes)) break;
4860
+ else i++;
4861
+ }
4862
+ unclosed.set(key, i);
4863
+ return -1;
4864
+ };
4865
+ const out = [];
4866
+ let fragment = false;
4867
+ /** Elements open in the Markdown. */
4868
+ let depth = 0;
4869
+ /** Whether the line before was prose, which a line starting `import ` continues, as MDX reads it. */
4870
+ let paragraph = false;
4871
+ /** Imports and exports among an element's children, which MDX hoists. */
4872
+ const hoisted = [];
4873
+ /** The list items the line is in, innermost last: where each one's content starts, inside the blockquotes it is in. */
4874
+ const lists = [];
4875
+ const keep = (kept) => {
4876
+ if (!fragment) out.push(";<>");
4877
+ fragment = true;
4878
+ out.push(kept);
4879
+ };
4880
+ /**
4881
+ * A tag or an expression starting at `at`, as `read` finds its end. One in a blockquote that
4882
+ * runs past its line is read, and kept, without the `>` markers of the lines it runs on.
4883
+ */
4884
+ const keepConstruct = (at, quotes, read) => {
4885
+ quoted = quotes;
4886
+ let end;
4887
+ try {
4888
+ end = read(at);
4889
+ } finally {
4890
+ quoted = 0;
4891
+ }
4892
+ let kept = input.slice(at, end);
4893
+ if (quotes > 0 && kept.includes("\n")) kept = kept.replace(/\n([^\n]*)/g, (_, line) => {
4894
+ const past = pastQuotes(line, quotes);
4895
+ return past === -1 ? `\n${line}` : `\n${" ".repeat(past)}${line.slice(past)}`;
4896
+ });
4897
+ keep(kept);
4898
+ return end;
4899
+ };
4900
+ /**
4901
+ * A line of Markdown, and past it whatever it opened that runs on: a tag, an expression or a
4902
+ * code span. Where the line it stops on ends, and whether any of it was prose.
4903
+ */
4904
+ const scanMarkdown = (at, quotes) => {
4905
+ let i = at;
4906
+ let run = at;
4907
+ let prose = false;
4908
+ let bracket = false;
4909
+ const flush = (to) => {
4910
+ if (to > run) out.push(blank(input.slice(run, to)));
4911
+ run = to;
4912
+ };
4913
+ while (i < length) {
4914
+ const c = input[i];
4915
+ if (c === "\n") {
4916
+ flush(++i);
4917
+ return {
4918
+ next: i,
4919
+ prose
4920
+ };
4921
+ }
4922
+ if (c === "\\" && ASCII_PUNCTUATION.test(input[i + 1] ?? "")) {
4923
+ i += 2;
4924
+ prose = true;
4925
+ } else if (c === "`" || c === "$") {
4926
+ let size = 0;
4927
+ while (input[i + size] === c) size++;
4928
+ const close = closingRun(i + size, c, size, quotes);
4929
+ i = close !== -1 && (c === "`" || LATEX.test(input.slice(i + size, close))) ? close + size : i + size;
4930
+ prose = true;
4931
+ } else if (c === "{") {
4932
+ flush(i);
4933
+ i = run = keepConstruct(i, quotes, (from) => skipScript(from + 1, "brace"));
4934
+ } else if (c === "<" && input.startsWith("<!--", i)) {
4935
+ const end = input.indexOf("-->", i + 4);
4936
+ i = end === -1 ? length : end + 3;
4937
+ } else if (c === "<" && (AUTOLINK.lastIndex = i, AUTOLINK.test(input))) {
4938
+ i = AUTOLINK.lastIndex;
4939
+ prose = true;
4940
+ } else if (c === "<" && (input[i + 1] === "/" || startsElement(i))) {
4941
+ flush(i);
4942
+ let tag = {
4943
+ end: i,
4944
+ closing: false,
4945
+ selfClosing: true
4946
+ };
4947
+ i = run = keepConstruct(i, quotes, (from) => (tag = skipTag(from)).end);
4948
+ if (tag.closing) depth = Math.max(0, depth - 1);
4949
+ else if (!tag.selfClosing) depth++;
4950
+ } else if (c === "]" && input[i + 1] === "(" && bracket) {
4951
+ const resource = LINK_RESOURCE.exec(input.slice(i + 1, i + 1 + DESTINATION_LIMIT));
4952
+ i += resource ? 1 + resource[0].length : 1;
4953
+ prose = true;
4954
+ } else {
4955
+ if (c !== " " && c !== " " && c !== "\r") prose = true;
4956
+ if (c === "[") bracket = true;
4957
+ i++;
4958
+ }
4959
+ }
4960
+ flush(length);
4961
+ return {
4962
+ next: length,
4963
+ prose
4964
+ };
4965
+ };
4966
+ /**
4967
+ * Where a block opened on the line before `from` ends: past the line that `closes` it, or at
4968
+ * the start of one that leaves the `quotes` blockquotes, or the list `item`, it is in.
4969
+ */
4970
+ const blockUntil = (from, quotes, item, closes) => {
4971
+ let i = from;
4972
+ while (i < length) {
4973
+ const line = lineAt(i);
4974
+ const past = pastQuotes(line, quotes);
4975
+ if (past === -1) return i;
4976
+ if (item && line.trim() !== "") {
4977
+ const inItem = pastQuotes(line, item.quotes);
4978
+ if (inItem === -1 || indentation(line.slice(inItem)) < item.column) return i;
4979
+ }
4980
+ i = lineEnd(i) + 1;
4981
+ if (closes(line.slice(past))) break;
4982
+ }
4983
+ return Math.min(i, length);
4984
+ };
4985
+ let i = input.charCodeAt(0) === 65279 ? 1 : 0;
4986
+ out.push(input.slice(0, i));
4987
+ const frontmatter = FRONTMATTER.exec(input.slice(i));
4988
+ if (frontmatter) {
4989
+ out.push(blank(frontmatter[0]));
4990
+ i += frontmatter[0].length;
4991
+ }
4992
+ while (i < length) {
4993
+ const end = lineEnd(i);
4994
+ const line = input.slice(i, end).replace(/\r$/, "");
4995
+ if (!line.trim()) {
4996
+ out.push(input.slice(i, end + 1));
4997
+ i = end + 1;
4998
+ paragraph = false;
4999
+ continue;
5000
+ }
5001
+ if (!paragraph && ESM.test(line)) {
5002
+ const stop = skipScript(i, "statement");
5003
+ if (depth === 0) {
5004
+ if (fragment) out.push("</>;");
5005
+ fragment = false;
5006
+ out.push(input.slice(i, stop));
5007
+ } else {
5008
+ out.push(blank(input.slice(i, stop)));
5009
+ hoisted.push(input.slice(i, stop));
5010
+ }
5011
+ lists.length = 0;
5012
+ i = stop;
5013
+ continue;
5014
+ }
5015
+ const quotes = quoteDepth(line);
5016
+ const body = unquote(line);
5017
+ const rest = line.slice(CONTAINERS.exec(line)[0].length);
5018
+ const fenceQuotes = quoteDepth(line.slice(0, line.length - rest.length));
5019
+ while (lists.length) {
5020
+ const top = lists.at(-1);
5021
+ const past = pastQuotes(line, top.quotes);
5022
+ if (past !== -1 && indentation(line.slice(past)) >= top.column) break;
5023
+ lists.pop();
5024
+ }
5025
+ const item = LIST_ITEM.exec(body);
5026
+ if (item) lists.push({
5027
+ column: item[1].length + item[2].length + contentOffset(item[3]),
5028
+ quotes
5029
+ });
5030
+ const marker = fenceOf(rest);
5031
+ if (marker !== null) {
5032
+ const stop = blockUntil(end + 1, fenceQuotes, lists.at(-1), (text) => {
5033
+ const closing = FENCE_CLOSE.exec(text);
5034
+ return closing !== null && closing[1][0] === marker[0] && closing[1].length >= marker.length;
3758
5035
  });
3759
- merge(scan);
5036
+ out.push(blank(input.slice(i, stop)));
5037
+ i = stop;
5038
+ paragraph = false;
3760
5039
  continue;
3761
5040
  }
3762
- const patterns = remaining.size ? allPatterns.filter(([name]) => remaining.has(name)) : [];
3763
- merge(scanSnapshot(ctx, readSnapshot(ctx, filePath), options, patterns));
3764
- }
3765
- if (cache && seen) {
3766
- for (const filePath of cache.entries.keys()) if (!seen.has(filePath)) cache.entries.delete(filePath);
3767
- for (const filePath of cache.resolvedTokenReferences.keys()) if (!seen.has(filePath)) cache.resolvedTokenReferences.delete(filePath);
3768
- }
3769
- return result;
3770
- }
3771
- /**
3772
- * Returns the custom properties left standing, for `pruneKeyframes` to root its own walk
3773
- * at — see `Generator.pruneKeyframes`. `'all'` when this pass had nothing to remove and so
3774
- * never computed the closure, which is not a missing answer but the correct one: a sheet
3775
- * nothing was removed from still declares everything it declared.
3776
- */
3777
- function pruneTokensForBuild(ctx, sheet, results, sourceScans) {
3778
- if (ctx.config.prune?.tokens === false) return ctx.pruneTokens(sheet)?.reachable ?? "all";
3779
- const unresolved = ctx.config.prune?.unresolvedPath ?? "off";
3780
- const scans = sourceScans ?? collectSourceScans(ctx, {
3781
- keyframeNames: [],
3782
- elements: false
3783
- });
3784
- const paths = new Set(scans.tokenPaths);
3785
- const vars = new Set(scans.cssVars);
3786
- const accounting = scans.accounting;
3787
- const reachable = scans.reachableFromJs;
3788
- for (const result of results) {
3789
- if (result.filePath) reconcileAccounting(accounting, resolvedTokenReferences(result), ctx.runtime.path.abs(ctx.config.cwd, result.filePath));
3790
- for (const item of result.token) for (const value of item.data ?? []) if (typeof value === "string") paths.add(value);
3791
- }
3792
- for (const name of tokenVarsFor(ctx, paths)) vars.add(name);
3793
- const declared = declaredKeeps(ctx);
3794
- for (const name of tokenVarsFor(ctx, declared)) vars.add(name);
3795
- for (const name of tokenVarsFor(ctx, accounting.paths)) vars.add(name);
3796
- const bounded = (ctx.config.prune?.keepTokens?.length ?? 0) > 0;
3797
- if (accounting.prefixes.size && (bounded || !accounting.declined.length || !reachable)) {
3798
- const prefixes = Array.from(accounting.prefixes);
3799
- const matched = [];
3800
- for (const token of ctx.tokens.allTokens) if (prefixes.some((prefix) => token.name.startsWith(prefix))) matched.push(token.name);
3801
- for (const name of tokenVarsFor(ctx, matched)) vars.add(name);
3802
- }
3803
- const failing = accounting.declined.filter(failsStrict);
3804
- const reported = accounting.declined.filter((entry) => !failsStrict(entry));
3805
- if (bounded && unresolved === "error" && accounting.declined.length) throw new BambooError("TOKEN_REFERENCE_UNRESOLVED", `${accounting.declined.length} token reference(s) could not be accounted for.\n\n${formatDeclined(ctx, accounting.declined)}\n\n\`prune.unresolvedPath: 'error'\` asserts that every token path resolves at build time, and \`prune.keepTokens\` declares where the ones that do not will land. Those are contradictory, so one has to go: drop \`keepTokens\` and respell the paths, or set \`prune: { unresolvedPath: 'warn' }\` and let the keeps cover them.`);
3806
- if (failing.length && unresolved !== "off") {
3807
- const where = `${failing.length} token reference(s) could not be resolved.\n\n${formatDeclined(ctx, failing)}\n\n`;
3808
- if (unresolved === "error") throw new BambooError("TOKEN_REFERENCE_UNRESOLVED", where + "`prune.unresolvedPath: 'error'` asserts that every token path resolves at build time. Spell the path as a string literal at the call, give a template a static prefix so it can be bounded, name the category they land in with `prune: { keepTokens: ['colors.*'] }` and drop to `prune: { unresolvedPath: 'warn' }`, or set `prune: { unresolvedPath: 'off' }` to stop asserting.");
3809
- logger.warn("tokens:unresolved", bounded ? where + "`prune.keepTokens` covers them: they keep what it names rather than every declaration in the theme. Nothing checks that they stay inside it, which is why it is yours to declare — a read landing outside the patterns loses its declaration and resolves to a `var()` with nothing behind it. Respell what you can, and widen the patterns for what you cannot." : where + "An unfollowable path keeps every token declaration. Spell the path as a string literal at the call, give a template a static prefix so it can be bounded, name the category they land in with `prune: { keepTokens: ['colors.*'] }`, or set `prune: { unresolvedPath: 'off' }` to stop reporting it.");
3810
- }
3811
- if (reported.length && unresolved !== "off") logger.warn("tokens:unresolved", `${reported.length} reference(s) could not be accounted for, so ` + (bounded ? `\`prune.keepTokens\` decides what they keep` : `every token declaration is kept`) + `.\n\n${formatDeclined(ctx, reported)}\n\nThese are shapes the build cannot follow rather than paths you can respell — a component stored post-transform, a file it could not parse, a barrel it cannot classify, a dynamic \`import()\`. ` + (bounded ? "Nothing checks that they stay inside `keepTokens`, which is why it is yours to declare: a read landing outside it loses its declaration. Narrow `include`, or widen the patterns." : "Narrow `include`, name the categories they reach with `prune: { keepTokens: [...] }`, or accept the keeps."));
3812
- return ctx.pruneTokens(sheet, vars, !bounded && accounting.declined.length > 0 && reachable)?.reachable ?? "all";
3813
- }
3814
- /**
3815
- * The dash-cased spelling of a token path, as it appears in the emitted css variable.
3816
- *
3817
- * Not a transform this applies — only one it recognises, to tell a user their pattern is
3818
- * written against the wrong side of the system. The paths are camelCase (`fontSizes.3xl`) and
3819
- * the variables are dash-cased (`--font-sizes-3xl`), so `font-sizes.*` is the natural thing to
3820
- * write after reading `styles.css` and it matches nothing at all.
5041
+ if (MATH_FENCE.test(body) && !body.slice(body.indexOf("$$") + 2).includes("$$")) {
5042
+ const stop = blockUntil(end + 1, quotes, lists.at(-1), (text) => /^[ \t]*\$\$/.test(text));
5043
+ if (LATEX.test(input.slice(i, stop))) {
5044
+ out.push(blank(input.slice(i, stop)));
5045
+ i = stop;
5046
+ paragraph = false;
5047
+ continue;
5048
+ }
5049
+ }
5050
+ const definition = paragraph ? null : DEFINITION.exec(rest);
5051
+ if (definition) {
5052
+ let stop = Math.min(end + 1, length);
5053
+ if (definition[1] === void 0 && stop < length) {
5054
+ const next = lineAt(stop);
5055
+ const past = pastQuotes(next, quotes);
5056
+ if (past !== -1 && quoteDepth(next) === quotes && DEFINITION_TITLE.test(next.slice(past))) stop = Math.min(lineEnd(stop) + 1, length);
5057
+ }
5058
+ out.push(blank(input.slice(i, stop)));
5059
+ i = stop;
5060
+ continue;
5061
+ }
5062
+ const { next, prose } = scanMarkdown(i, quotes);
5063
+ paragraph = prose && !ATX_HEADING.test(body) && !THEMATIC_BREAK.test(body) && !(paragraph && SETEXT_UNDERLINE.test(body));
5064
+ i = next;
5065
+ }
5066
+ if (fragment) out.push(hoisted.length ? "</>;" : "</>");
5067
+ for (const statement of hoisted) out.push("\n", statement);
5068
+ return out.join("");
5069
+ };
5070
+ /**
5071
+ * Built in, as the Vue, Svelte and Astro converters are. Last of the `parser:before` hooks, and
5072
+ * only for a file none before it made something of: a project that already converts its MDX
5073
+ * itself keeps its own.
3821
5074
  */
3822
- const dashed = (path) => path.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
5075
+ const pluginMdx = () => ({
5076
+ name: "@bamboocss/node:mdx",
5077
+ hooks: { "parser:before": ({ filePath, content, original }) => {
5078
+ if (!MDX_FILE.test(filePath)) return;
5079
+ if (content === (original ?? content)) return mdxToTsx(content);
5080
+ logger.debug("mdx", `${filePath} was rewritten by a \`parser:before\` hook, and is read as that left it`);
5081
+ } }
5082
+ });
5083
+ //#endregion
5084
+ //#region src/config.ts
5085
+ const RESOLVED_HOOKS_NAME = "__resolved__";
5086
+ const AUTO_PARSER_HOOKS = Object.freeze([
5087
+ "vue",
5088
+ "svelte",
5089
+ "astro"
5090
+ ]);
5091
+ const autoPluginFactories = {
5092
+ astro: pluginAstro,
5093
+ svelte: pluginSvelte,
5094
+ vue: pluginVue
5095
+ };
3823
5096
  /**
3824
- * The token names `prune.keepTokens` names, matched against the whole theme.
3825
- *
3826
- * Patterns are anchored globs over the dotted token *path* — `colors.*`, `colors.brand.*`,
3827
- * `!colors.legacy.*`, or a bare path for one token. Matched case-sensitively, because a path is
3828
- * a key in the config rather than free text.
5097
+ * Built-in plugins that are auto-injected when using the CLI or PostCSS plugin.
5098
+ * These provide Vue, Svelte and Astro single-file-component support.
3829
5099
  *
3830
- * A pattern that matches nothing is reported rather than ignored. It is nearly always a typo
3831
- * for one that would have matched, and the failure it causes is the one this whole module is
3832
- * careful about everywhere else: a declaration dropped while something still asks for it, with
3833
- * no error and no warning, resolving to a `var()` that inherits instead of falling back.
5100
+ * LightningCSS is not among them any more. It was reached through a `lightningcss: true`
5101
+ * config flag whose only job was to push `pluginLightningcss()` into this list — a second
5102
+ * way to say something `plugins` already said, and the expensive one: naming the plugin
5103
+ * here meant a static import, which made `@bamboocss/plugin-lightningcss` a hard dependency
5104
+ * of this package, which put a native binary in every install whether or not the flag was
5105
+ * ever set. List the plugin yourself to use it.
3834
5106
  */
3835
- function declaredKeeps(ctx) {
3836
- const patterns = ctx.config.prune?.keepTokens;
3837
- if (!patterns?.length) return [];
3838
- const includes = patterns.filter((pattern) => !pattern.startsWith("!"));
3839
- if (!includes.length) logger.warn("prune:tokens", `\`prune.keepTokens\` holds only exclusions, so it keeps every token they do not name:\n\n${patterns.map((pattern) => ` ${pattern}`).join("\n")}\n\nA leading \`!\` subtracts from a selection and there is none here. Add the categories to keep — \`['colors.*', '!colors.legacy.*']\` — or use \`prune: { tokens: false }\` if keeping everything is the intent.`);
3840
- const matched = [];
3841
- const used = /* @__PURE__ */ new Set();
3842
- for (const token of ctx.tokens.allTokens) {
3843
- if (isMatch(token.name, patterns, { caseSensitive: true })) matched.push(token.name);
3844
- if (used.size === includes.length) continue;
3845
- for (const pattern of includes) if (isMatch(token.name, pattern, { caseSensitive: true })) used.add(pattern);
3846
- }
3847
- const unused = includes.filter((pattern) => !used.has(pattern));
3848
- if (unused.length) {
3849
- const paths = ctx.tokens.allTokens.map((token) => token.name);
3850
- const respell = unused.map((pattern) => {
3851
- const hit = paths.find((path) => isMatch(dashed(path), pattern, { caseSensitive: true }));
3852
- if (!hit) return ` ${pattern}`;
3853
- return ` ${pattern} — matches \`${dashed(hit)}\`, which is the css variable's spelling. Write the token path: \`${hit.split(".")[0]}.*\``;
3854
- }).join("\n");
3855
- logger.warn("prune:tokens", `${unused.length} \`prune.keepTokens\` pattern(s) match no token in this theme:\n\n${respell}\n\nA pattern is an anchored glob over the dotted token *path* — \`colors.*\`, not \`colors\`, and \`fontSizes.*\` rather than the \`--font-sizes-\` spelling the css variable uses. One that matches nothing keeps nothing, which is silent everywhere except here.`);
3856
- }
3857
- return matched;
3858
- }
3859
- /** The custom properties a set of token paths resolves to. */
3860
- function tokenVarsFor(ctx, paths) {
3861
- const vars = /* @__PURE__ */ new Set();
3862
- for (const path of paths) {
3863
- if (!path) continue;
3864
- const ref = ctx.tokens.view.getVar(path);
3865
- if (!ref) continue;
3866
- for (const name of cssVarRefs(ref)) vars.add(name);
3867
- }
3868
- return vars;
5107
+ function getAutoPlugins() {
5108
+ return AUTO_PARSER_HOOKS.map((identity) => autoPluginFactories[identity]());
3869
5109
  }
3870
- /** Where to look, grouped by file. The surrounding text differs by whether this throws. */
3871
- function formatDeclined(ctx, declined) {
3872
- const byFile = /* @__PURE__ */ new Map();
3873
- for (const entry of declined) {
3874
- const list = byFile.get(entry.filePath) ?? [];
3875
- list.push(entry);
3876
- byFile.set(entry.filePath, list);
3877
- }
3878
- return Array.from(byFile.entries()).map(([filePath, entries]) => {
3879
- return [` ${filePath.startsWith(ctx.config.cwd) ? filePath.slice(ctx.config.cwd.length + 1) : filePath}`, ...entries.map((entry) => ` ${entry.line}: ${entry.reason}`)].join("\n");
3880
- }).join("\n");
5110
+ /** Resolve all config state without constructing the parser Project owned by BambooContext. */
5111
+ async function prepareNodeConfig(options = {}, cwd = options.cwd ?? options?.config?.cwd ?? process.cwd()) {
5112
+ const { config, configPath } = options;
5113
+ const conf = await loadConfig({
5114
+ cwd,
5115
+ file: configPath
5116
+ });
5117
+ if (config) Object.assign(conf.config, config);
5118
+ if (options.cwd) conf.config.cwd = options.cwd;
5119
+ if (options.dev) conf.config.dev = true;
5120
+ const autoPlugins = getAutoPlugins();
5121
+ const mdx = pluginMdx();
5122
+ conf.hooks = mergeHooks([
5123
+ ...autoPlugins,
5124
+ {
5125
+ name: RESOLVED_HOOKS_NAME,
5126
+ hooks: conf.hooks
5127
+ },
5128
+ mdx
5129
+ ]);
5130
+ conf.config.plugins = [
5131
+ ...autoPlugins,
5132
+ ...conf.config.plugins ?? [],
5133
+ mdx
5134
+ ];
5135
+ const tsconfigResolutionFiles = {};
5136
+ const tsConfResult = await loadTsConfig(conf, cwd, tsconfigResolutionFiles);
5137
+ if (tsConfResult) Object.assign(conf, tsConfResult);
5138
+ rememberTsConfigResolutionFiles(conf, tsconfigResolutionFiles.value ?? []);
5139
+ const again = {
5140
+ ...options,
5141
+ config: copyLaidOver(config),
5142
+ configPath: conf.path
5143
+ };
5144
+ rememberConfigReload(conf, async () => (await prepareNodeConfig(again, cwd)).conf);
5145
+ return { conf };
3881
5146
  }
3882
- const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3883
- /** The keyframes the theme declares — the allow-list `pruneKeyframes` works against. */
3884
- const keyframeNames = (ctx) => Object.keys(ctx.config.theme?.keyframes ?? {});
3885
5147
  /**
3886
- * The HTML element names the source renders.
3887
- *
3888
- * A textual scan for an opening tag, over the same files the other collectors read. Matching
3889
- * `<tag` rather than parsing: a template can spell an element in more ways than a parser of
3890
- * any one framework's syntax would find, and over-reporting an element only keeps a reset
3891
- * rule that would otherwise go.
3892
- *
3893
- * Lowercase-initial only, so a JSX component (`<Button />`) is not mistaken for an element.
3894
- * That cuts the other way too — a component rendering `<button>` inside a dependency is
3895
- * invisible here, which is why `preflight.prune` is opt-in.
3896
- *
3897
- * The commoner blind spot is nearer than a dependency: this reads `include`, and `include`
3898
- * conventionally covers components rather than markup. An entry template — `index.html`,
3899
- * `app.html` — is where `<table>`, `<noscript>` and a page's static markup usually live, and a
3900
- * glob rooted at `./src` does not match it, so every element appearing only there loses its
3901
- * reset. Nothing here can detect that; the file simply is not in the list. Listing it in
3902
- * `include` fixes it, because this reads whatever `include` covers rather than only what the
3903
- * parser understands — `token-references.test.ts` pins both halves.
3904
- *
3905
- * Reading the raw file as well as the parsed copy is what makes an SFC work here; see
3906
- * `sourceTexts`. On a healthy `.svelte` file the two agree on everything but `<script>`, so
3907
- * the raw read earns its place only when a transform fails -- and there it is the difference
3908
- * between the file's elements and none of them.
5148
+ * Load config and create context with auto-injected plugins.
5149
+ * Used by the CLI and PostCSS plugin.
3909
5150
  */
3910
- function collectRenderedElements(ctx) {
3911
- const found = /* @__PURE__ */ new Set();
3912
- for (const content of sourceTexts(ctx)) for (const match of content.matchAll(/<\s*([a-z][\w-]*)(?=[\s/>]|$)/g)) found.add(match[1].toLowerCase());
3913
- return found;
5151
+ async function loadConfigAndCreateContext(options = {}) {
5152
+ const { conf } = await prepareNodeConfig(options);
5153
+ return new BambooContext(conf);
3914
5154
  }
3915
5155
  //#endregion
3916
- //#region src/assemble-sheet.ts
3917
- /**
3918
- * One stylesheet from an already-extracted encoder.
3919
- *
3920
- * Vite, `bamboo cssgen`, and the CLI `bamboo` command all finish here so a recipe lowered to
3921
- * atoms cannot have a different sheet depending on which integration asked for it.
3922
- */
3923
- const assembleExtractedSheet = (ctx, { layerParams = false, sourceScanCache, mtimeOf, sourceInventory, parserResults = [] } = {}) => {
3924
- ctx.encoder.atomizeObservedRecipes();
3925
- const sheet = ctx.createSheet();
3926
- if (layerParams) {
3927
- const recipeLayer = ctx.config.layers?.recipes ?? "recipes";
3928
- sheet.layers.root.prepend(`@layer ${sheet.layers.layerNames.filter((name) => name !== recipeLayer).join(", ")};`);
3929
- }
3930
- ctx.appendBaselineCss(sheet, { atomizeRecipes: true });
3931
- const collectElements = prunesPreflight(ctx.config.preflight);
3932
- const pruneKeyframes = Boolean(ctx.config.prune?.keyframes);
3933
- const declaredKeyframes = pruneKeyframes ? keyframeNames(ctx) : [];
3934
- const scans = ctx.config.prune?.tokens !== false || collectElements || pruneKeyframes ? collectSourceScans(ctx, {
3935
- keyframeNames: declaredKeyframes,
3936
- elements: collectElements
3937
- }, sourceScanCache, mtimeOf, sourceInventory) : void 0;
3938
- const reachableVars = pruneTokensForBuild(ctx, sheet, parserResults, scans);
3939
- if (collectElements && scans) ctx.prunePreflight(sheet, scans.elements);
3940
- if (pruneKeyframes && scans) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3941
- return sheet;
3942
- };
3943
- //#endregion
3944
5156
  //#region src/builder.ts
3945
5157
  const fileModifiedMap = /* @__PURE__ */ new Map();
3946
5158
  /** Binary minimum heap; callers provide the stable semantic rank used for ties/order. */
@@ -3997,6 +5209,8 @@ var Builder = class {
3997
5209
  configDependencies = /* @__PURE__ */ new Set();
3998
5210
  /** Last complete included inventory, including members which have since been deleted. */
3999
5211
  sourceInventory;
5212
+ /** Where the glob behind that inventory began, and what it reached through a link. */
5213
+ sourceLinks = [];
4000
5214
  /** Existing included owners selected by the last resolution-ledger invalidation pass. */
4001
5215
  affectedFiles;
4002
5216
  /** Dependency-before-importer parse order for the selected owners. */
@@ -4066,8 +5280,46 @@ var Builder = class {
4066
5280
  };
4067
5281
  /** @internal The inventory reconciled by the most recent extraction pass. */
4068
5282
  getSourceFiles = () => Object.freeze([...this.sourceInventory ?? []]);
5283
+ /** The folders each context's patterns are globbed from. @see getWatchDirectories */
5284
+ patternDirectories = /* @__PURE__ */ new WeakMap();
5285
+ /** Those, and the folders the glob reached through a link, for one context and glob. @see getWatchDirectories */
5286
+ watchDirectories;
5287
+ /**
5288
+ * @internal The folders `include` and `dependencies` are globbed from, absolute — and each folder
5289
+ * the last glob reached through a link — where a file appearing can change the stylesheet, and so
5290
+ * what a watcher has to watch for it to be seen. A link a pattern's wildcard reaches,
5291
+ * `node_modules/@acme/*` to a workspace package, leads somewhere no pattern names.
5292
+ */
5293
+ getWatchDirectories = () => {
5294
+ const ctx = this.getContextOrThrow();
5295
+ let patterns = this.patternDirectories.get(ctx);
5296
+ if (!patterns) {
5297
+ const { cwd, dependencies, include } = ctx.config;
5298
+ const { positive } = splitPatterns([...include ?? [], ...dependencies ?? []]);
5299
+ patterns = Object.freeze(positive.length ? uniq(globDirname(positive).map((directory) => resolve(cwd, directory))) : []);
5300
+ this.patternDirectories.set(ctx, patterns);
5301
+ }
5302
+ const cached = this.watchDirectories;
5303
+ if (cached?.ctx === ctx && cached.links === this.sourceLinks) return cached.directories;
5304
+ const linked = this.linkedPaths().toReal.filter((path) => path.directory);
5305
+ const directories = Object.freeze(uniq([...patterns, ...linked.map((path) => path.spelled)]));
5306
+ this.watchDirectories = {
5307
+ ctx,
5308
+ links: this.sourceLinks,
5309
+ directories
5310
+ };
5311
+ return directories;
5312
+ };
4069
5313
  /** The compiled `include`/`exclude` matcher of each context, since the compiler asks per module. */
4070
5314
  sourceMatchers = /* @__PURE__ */ new WeakMap();
5315
+ sourceMatcherOf = (ctx) => {
5316
+ let matches = this.sourceMatchers.get(ctx);
5317
+ if (!matches) {
5318
+ matches = sourceMatcher(ctx.config.include, ctx.config.exclude, ctx.config.cwd);
5319
+ this.sourceMatchers.set(ctx, matches);
5320
+ }
5321
+ return matches;
5322
+ };
4071
5323
  /**
4072
5324
  * @internal Whether this path is one `include` covers and `exclude` does not.
4073
5325
  *
@@ -4079,22 +5331,129 @@ var Builder = class {
4079
5331
  const ctx = this.getContextOrThrow();
4080
5332
  const absolutePath = this.absOwner(ctx, filePath);
4081
5333
  const relativePath = this.sourcePath(ctx.runtime.path.relative(ctx.config.cwd, absolutePath));
4082
- if (!this.sourceMatchers.has(ctx)) {
4083
- const sourcePatterns = ctx.config.include ?? [];
4084
- this.sourceMatchers.set(ctx, sourcePatterns.length ? picomatch(sourcePatterns, { ignore: globIgnore(ctx.config.exclude) }) : void 0);
5334
+ const isSource = this.sourceMatcherOf(ctx);
5335
+ if (isSource(relativePath)) return true;
5336
+ const bases = this.includeBases(ctx);
5337
+ return this.sourcePathsOf(absolutePath).some((source) => bases.some((base) => source === base.path || source.startsWith(base.prefix)) && isSource(this.sourcePath(ctx.runtime.path.relative(ctx.config.cwd, source))));
5338
+ };
5339
+ /** The folders each context's `include` is globbed from. @see isPotentialSourceFile */
5340
+ includeBaseCache = /* @__PURE__ */ new WeakMap();
5341
+ includeBases = (ctx) => {
5342
+ let bases = this.includeBaseCache.get(ctx);
5343
+ if (!bases) {
5344
+ const { positive } = splitPatterns(ctx.config.include ?? []);
5345
+ bases = (positive.length ? uniq(globDirname(positive)) : []).map((directory) => {
5346
+ const path = this.sourcePath(resolve(ctx.config.cwd, directory));
5347
+ return {
5348
+ path,
5349
+ prefix: path.endsWith("/") ? path : `${path}/`
5350
+ };
5351
+ });
5352
+ this.includeBaseCache.set(ctx, bases);
5353
+ }
5354
+ return bases;
5355
+ };
5356
+ /** The linked paths of each glob, resolved once each. @see linkedPaths */
5357
+ linkedPathCache = /* @__PURE__ */ new WeakMap();
5358
+ /**
5359
+ * Where each folder and file the glob behind the inventory reached through a link — or the folder
5360
+ * it began at, spelled through a link above it — really is, which is what a bundler resolving a
5361
+ * module there names it by. Resolved once per glob, and only when asked, so a build that never
5362
+ * asks pays nothing. Any difference in spelling counts, case too: a bundler names a module as the
5363
+ * system does, and a path the inventory spells otherwise is no member of it.
5364
+ */
5365
+ linkedPaths = () => {
5366
+ let linked = this.linkedPathCache.get(this.sourceLinks);
5367
+ if (!linked) {
5368
+ const all = [];
5369
+ for (const link of this.sourceLinks) {
5370
+ let real;
5371
+ let directory;
5372
+ try {
5373
+ real = this.sourcePath(realpathSync.native(link));
5374
+ directory = statSync(real).isDirectory();
5375
+ } catch {
5376
+ continue;
5377
+ }
5378
+ const spelled = this.sourcePath(link);
5379
+ if (real !== spelled) all.push({
5380
+ directory,
5381
+ real,
5382
+ realPrefix: `${real}/`,
5383
+ spelled,
5384
+ spelledPrefix: `${spelled}/`
5385
+ });
5386
+ }
5387
+ linked = {
5388
+ all,
5389
+ toReal: [...all].sort((left, right) => right.spelled.length - left.spelled.length)
5390
+ };
5391
+ this.linkedPathCache.set(this.sourceLinks, linked);
5392
+ }
5393
+ return linked;
5394
+ };
5395
+ /**
5396
+ * An absolute, `/`-spelled path as the inventory spells it — each way, where two links reach one
5397
+ * folder and the inventory holds the files under both. None, where no link is in the way.
5398
+ */
5399
+ sourcePathsOf = (path) => {
5400
+ const sources = [];
5401
+ for (const { real, realPrefix, spelled } of this.linkedPaths().all) if (path === real) sources.push(spelled);
5402
+ else if (path.startsWith(realPrefix)) sources.push(spelled + path.slice(real.length));
5403
+ return sources;
5404
+ };
5405
+ /**
5406
+ * @internal `filePath` as the source inventory spells it, where a bundler names it by where it
5407
+ * really is: through each folder or file a link was read at. None, where no link is in the way.
5408
+ */
5409
+ toSourcePaths = (filePath) => {
5410
+ const ctx = this.getContextOrThrow();
5411
+ return this.sourcePathsOf(this.absOwner(ctx, filePath));
5412
+ };
5413
+ /** The inventory's sources by where each really is, for one inventory and glob. @see getRealSourceFiles */
5414
+ realSourceFiles;
5415
+ /**
5416
+ * @internal The sources the inventory reached through a link, by where each really is: the names
5417
+ * a bundler gives them, and so what it reports compiling and editing.
5418
+ */
5419
+ getRealSourceFiles = () => {
5420
+ const ctx = this.getContextOrThrow();
5421
+ const inventory = this.sourceInventory;
5422
+ if (!inventory) return [];
5423
+ const cached = this.realSourceFiles;
5424
+ if (cached?.inventory === inventory && cached.links === this.sourceLinks) return cached.reals;
5425
+ const { toReal } = this.linkedPaths();
5426
+ const reals = [];
5427
+ if (toReal.length) for (const file of inventory) {
5428
+ const path = this.absOwner(ctx, file);
5429
+ for (const { real, spelled, spelledPrefix } of toReal) {
5430
+ if (path === spelled) reals.push(real);
5431
+ else if (path.startsWith(spelledPrefix)) reals.push(real + path.slice(spelled.length));
5432
+ else continue;
5433
+ break;
5434
+ }
4085
5435
  }
4086
- const sourceMatcher = this.sourceMatchers.get(ctx);
4087
- return sourceMatcher?.(relativePath) || sourceMatcher?.(absolutePath) || false;
5436
+ this.realSourceFiles = {
5437
+ inventory,
5438
+ links: this.sourceLinks,
5439
+ reals: Object.freeze(reals)
5440
+ };
5441
+ return this.realSourceFiles.reals;
4088
5442
  };
4089
5443
  /** @internal Whether creating or deleting this path can change a `dependencies` glob. */
4090
5444
  isPotentialConfigDependency = (filePath) => {
4091
5445
  const ctx = this.getContextOrThrow();
4092
5446
  const absolutePath = this.absOwner(ctx, filePath);
4093
5447
  const relativePath = this.sourcePath(ctx.runtime.path.relative(ctx.config.cwd, absolutePath));
4094
- const patterns = ctx.config.dependencies ?? [];
4095
- const matcher = patterns.length ? picomatch(patterns) : void 0;
4096
- return matcher?.(relativePath) || matcher?.(absolutePath) || false;
5448
+ let matcher = this.dependencyMatchers.get(ctx);
5449
+ if (!matcher) {
5450
+ matcher = sourceMatcher(ctx.config.dependencies, void 0, ctx.config.cwd);
5451
+ this.dependencyMatchers.set(ctx, matcher);
5452
+ }
5453
+ return matcher(relativePath);
4097
5454
  };
5455
+ /** The compiled `dependencies` matcher of each context, since a watcher asks per event. */
5456
+ dependencyMatchers = /* @__PURE__ */ new WeakMap();
4098
5457
  /** @internal Exact local package/tsconfig files which can change semantic resolution. */
4099
5458
  getResolutionConfigurationFiles = () => {
4100
5459
  const files = /* @__PURE__ */ new Set();
@@ -4144,11 +5503,16 @@ var Builder = class {
4144
5503
  * of them moving — including appearing or disappearing, which `getFileMeta` reports as a
4145
5504
  * changed mtime — takes the full reload below, as does a file the last snapshot never saw.
4146
5505
  *
4147
- * Dev-only because the reload is also the recovery for edits this guard cannot see — a
4148
- * preset external to the config bundle — and a one-shot build keeps paying the reload
4149
- * rather than trading that recovery for a latency only watch mode feels.
5506
+ * Dev and watch only, because the reload is also the recovery for edits this guard cannot
5507
+ * see — a preset external to the config bundle — and a one-shot build keeps paying the
5508
+ * reload rather than trading that recovery for a latency only watch mode feels. A watching
5509
+ * build takes it as a dev server does for a second reason: an ES module config is imported
5510
+ * anew on every reload, and Node keeps every version it imported, so a reload per rebuild
5511
+ * held one more copy of the config per rebuild for as long as the build watched.
4150
5512
  */
4151
- if (options.dev && this.configGraphUnchanged(configPath, options.sourceChanges)) {
5513
+ const membersMoved = Boolean(options.watch && !options.sourceChanges && this.dependencyMembersMoved(ctx));
5514
+ const needsConfigReload = Boolean(options.sourceChanges?.needsConfigReload) || membersMoved;
5515
+ if ((options.dev || options.watch) && !membersMoved && this.configGraphUnchanged(configPath, options.sourceChanges)) {
4152
5516
  this.affecteds = {
4153
5517
  artifacts: /* @__PURE__ */ new Set(),
4154
5518
  hasConfigChanged: false,
@@ -4163,7 +5527,7 @@ var Builder = class {
4163
5527
  });
4164
5528
  const nextContext = this.getContextOrThrow();
4165
5529
  nextContext.encoder.recordOrigins = Boolean(options.atomOrigins);
4166
- if (options.sourceChanges?.needsConfigReload) {
5530
+ if (needsConfigReload) {
4167
5531
  const { cwd: configCwd, dependencies } = nextContext.config;
4168
5532
  nextContext.explicitDeps = dependencies ? nextContext.runtime.fs.glob({
4169
5533
  include: dependencies,
@@ -4173,7 +5537,7 @@ var Builder = class {
4173
5537
  this.recordConfigDependencies(nextContext, options.cwd);
4174
5538
  this.tsconfigResolutionFiles = nextContext.diff.getResolutionConfigFiles();
4175
5539
  logger.debug("builder", this.affecteds);
4176
- const explicitDeps = options.sourceChanges?.needsConfigReload ? uniq([...previousExplicitDeps, ...this.context.explicitDeps]) : this.context.explicitDeps;
5540
+ const explicitDeps = needsConfigReload ? uniq([...previousExplicitDeps, ...this.context.explicitDeps]) : this.context.explicitDeps;
4177
5541
  const knownChanges = options.sourceChanges ? new Set(options.sourceChanges.files.map((file) => this.absOwner(this.context, file))) : void 0;
4178
5542
  this.explicitDepsMeta = this.checkFilesChanged(explicitDeps, knownChanges);
4179
5543
  if (this.explicitDepsMeta.hasFilesChanged) {
@@ -4198,8 +5562,9 @@ var Builder = class {
4198
5562
  this.sourceScanCache.resolvedTokenReferences.clear();
4199
5563
  this.capturedLedger = void 0;
4200
5564
  this.capturedDependents.clear();
4201
- await ctx.hooks["config:change"]?.({
4202
- config: ctx.config,
5565
+ const current = this.getContextOrThrow();
5566
+ await current.hooks["config:change"]?.({
5567
+ config: current.config,
4203
5568
  changes: this.affecteds
4204
5569
  });
4205
5570
  this.snapshotConfigGraphMtimes(configPath);
@@ -4208,6 +5573,16 @@ var Builder = class {
4208
5573
  this.refreshSourceState(ctx, previousTsconfigFiles, options.sourceChanges);
4209
5574
  this.snapshotConfigGraphMtimes(configPath);
4210
5575
  };
5576
+ /** Whether `dependencies` matches other files now than the context was built with. */
5577
+ dependencyMembersMoved = (ctx) => {
5578
+ const { cwd, dependencies } = ctx.config;
5579
+ if (!dependencies?.length) return false;
5580
+ const members = new Set(ctx.runtime.fs.glob({
5581
+ include: dependencies,
5582
+ cwd
5583
+ }));
5584
+ return members.size !== ctx.explicitDeps.length || ctx.explicitDeps.some((file) => !members.has(file));
5585
+ };
4211
5586
  /** Every file whose content participates in the resolved config, for the dev fast path. */
4212
5587
  configGraphFiles = (configPath) => uniq([
4213
5588
  ...configPath ? [configPath] : [],
@@ -4248,7 +5623,8 @@ var Builder = class {
4248
5623
  if (changedResolutionConfigurations.some((file) => tsconfigCandidates.has(file))) ctx.project.refreshResolutionConfiguration(ctx.conf.tsconfig?.compilerOptions);
4249
5624
  }
4250
5625
  const needsInventoryScan = !sourceChanges || sourceChanges.needsInventoryScan || this.sourceInventory === void 0;
4251
- const inventory = needsInventoryScan ? ctx.getFiles() : [...this.sourceInventory];
5626
+ const linked = [];
5627
+ const inventory = needsInventoryScan ? ctx.getFiles(linked) : [...this.sourceInventory];
4252
5628
  const allTracked = uniq([
4253
5629
  ...this.sourceInventory ?? inventory,
4254
5630
  ...inventory,
@@ -4272,7 +5648,10 @@ var Builder = class {
4272
5648
  this.affectedFiles = /* @__PURE__ */ new Set();
4273
5649
  this.extractionOrder = [];
4274
5650
  }
4275
- this.sourceInventory = [...inventory];
5651
+ if (needsInventoryScan) {
5652
+ this.sourceInventory = [...inventory];
5653
+ this.sourceLinks = linked;
5654
+ }
4276
5655
  };
4277
5656
  /** Normalize the path identity shared by the Project ledger and file-owner keys. */
4278
5657
  sourcePath = (file) => file.replaceAll("\\", "/");
@@ -4369,7 +5748,7 @@ var Builder = class {
4369
5748
  await codegen(this.getContextOrThrow());
4370
5749
  } else if (this.affecteds?.hasConfigChanged) {
4371
5750
  logger.debug("builder", "Emit artifacts after config change");
4372
- await codegen(this.getContextOrThrow(), Array.from(this.affecteds.artifacts));
5751
+ await codegen(this.getContextOrThrow(), artifactsToRebuild(this.affecteds));
4373
5752
  }
4374
5753
  this.hasEmitted = true;
4375
5754
  }
@@ -4452,7 +5831,8 @@ var Builder = class {
4452
5831
  ctx.assertExtracted();
4453
5832
  return ctx.assertNoDeadCalls();
4454
5833
  }
4455
- const files = !hasConfigChanged && this.sourceInventory ? [...this.sourceInventory] : ctx.getFiles();
5834
+ const linked = [];
5835
+ const files = !hasConfigChanged && this.sourceInventory ? [...this.sourceInventory] : ctx.getFiles(linked);
4456
5836
  const inventory = new Set(files.map(this.sourcePath));
4457
5837
  if (hasConfigChanged) {
4458
5838
  this.resolutionReadSets.clear();
@@ -4466,12 +5846,15 @@ var Builder = class {
4466
5846
  for (const owner of this.resolutionConfigurationSets.keys()) if (!inventory.has(owner)) this.resolutionConfigurationSets.delete(owner);
4467
5847
  }
4468
5848
  ctx.encoder?.reconcileFileOwnerOrder("extract", files);
4469
- const filesToExtract = hasConfigChanged ? ctx.extractableFiles(files) : this.extractionOrder ?? files;
5849
+ const filesToExtract = hasConfigChanged ? ctx.extractableFiles(files, linked) : this.extractionOrder ?? files;
4470
5850
  const done = logger.time.info("Extracted in");
4471
5851
  ctx.prepareNativeExtraction(filesToExtract);
4472
5852
  for (const file of filesToExtract) this.extractFile(ctx, file);
4473
5853
  done();
4474
- this.sourceInventory = [...files];
5854
+ if (hasConfigChanged || !this.sourceInventory) {
5855
+ this.sourceInventory = [...files];
5856
+ this.sourceLinks = linked;
5857
+ }
4475
5858
  for (const file of uniq([...files, ...this.getResolutionReadFiles()])) {
4476
5859
  const mtime = this.filesMeta?.changes.get(file)?.mtime ?? fileModifiedMap.get(file) ?? this.getFileMeta(file).mtime;
4477
5860
  fileModifiedMap.set(file, mtime);
@@ -4604,6 +5987,84 @@ const cssgen = async (ctx, options) => {
4604
5987
  }
4605
5988
  };
4606
5989
  //#endregion
5990
+ //#region src/zip.ts
5991
+ /**
5992
+ * The time as an MS-DOS date and time, which is how a zip records when a file was written. Its
5993
+ * years run from 1980 to 2107, and a clock outside them is held to the nearest.
5994
+ */
5995
+ const dosTime = (when) => {
5996
+ const date = new Date(Math.min(Math.max(when.getTime(), new Date(1980, 0, 1).getTime()), new Date(2107, 11, 31).getTime()));
5997
+ return {
5998
+ time: date.getHours() << 11 | date.getMinutes() << 5 | Math.floor(date.getSeconds() / 2),
5999
+ date: date.getFullYear() - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate()
6000
+ };
6001
+ };
6002
+ /** What a zip without ZIP64 can record: 65,535 files, and no file nor archive past 4 GB. */
6003
+ const MAX_ENTRIES = 65535;
6004
+ const MAX_SIZE = 4294967295;
6005
+ /**
6006
+ * A zip archive of `entries`, each deflated.
6007
+ *
6008
+ * Written here rather than by a dependency because `bamboo debug --zip` is all that needs one,
6009
+ * and the format a bug report attaches is small: a local header and the deflated data for each
6010
+ * file, the central directory naming them, and its end record. No ZIP64, so an archive is limited
6011
+ * to 4 GB and 65,535 files, which a debug dump never nears. Names are UTF-8, as flag bit 11 says.
6012
+ */
6013
+ const createZip = (entries, modified = /* @__PURE__ */ new Date()) => {
6014
+ if (entries.length > MAX_ENTRIES) throw new RangeError(`A zip holds at most ${MAX_ENTRIES} files, and this one would hold ${entries.length}.`);
6015
+ const { time, date } = dosTime(modified);
6016
+ const locals = [];
6017
+ const centrals = [];
6018
+ let offset = 0;
6019
+ for (const entry of entries) {
6020
+ const name = Buffer.from(entry.name, "utf8");
6021
+ const data = typeof entry.data === "string" ? Buffer.from(entry.data, "utf8") : entry.data;
6022
+ const deflated = deflateRawSync(data);
6023
+ const checksum = crc32(data);
6024
+ if (data.length > MAX_SIZE || offset + 30 + name.length + deflated.length > MAX_SIZE) throw new RangeError(`A zip holds at most 4 GB, and \`${entry.name}\` takes this one past it.`);
6025
+ const local = Buffer.alloc(30);
6026
+ local.writeUInt32LE(67324752, 0);
6027
+ local.writeUInt16LE(20, 4);
6028
+ local.writeUInt16LE(2048, 6);
6029
+ local.writeUInt16LE(8, 8);
6030
+ local.writeUInt16LE(time, 10);
6031
+ local.writeUInt16LE(date, 12);
6032
+ local.writeUInt32LE(checksum, 14);
6033
+ local.writeUInt32LE(deflated.length, 18);
6034
+ local.writeUInt32LE(data.length, 22);
6035
+ local.writeUInt16LE(name.length, 26);
6036
+ local.writeUInt16LE(0, 28);
6037
+ locals.push(local, name, deflated);
6038
+ const central = Buffer.alloc(46);
6039
+ central.writeUInt32LE(33639248, 0);
6040
+ central.writeUInt16LE(20, 4);
6041
+ central.writeUInt16LE(20, 6);
6042
+ central.writeUInt16LE(2048, 8);
6043
+ central.writeUInt16LE(8, 10);
6044
+ central.writeUInt16LE(time, 12);
6045
+ central.writeUInt16LE(date, 14);
6046
+ central.writeUInt32LE(checksum, 16);
6047
+ central.writeUInt32LE(deflated.length, 20);
6048
+ central.writeUInt32LE(data.length, 24);
6049
+ central.writeUInt16LE(name.length, 28);
6050
+ central.writeUInt32LE(offset, 42);
6051
+ centrals.push(central, name);
6052
+ offset += local.length + name.length + deflated.length;
6053
+ }
6054
+ const directory = Buffer.concat(centrals);
6055
+ const end = Buffer.alloc(22);
6056
+ end.writeUInt32LE(101010256, 0);
6057
+ end.writeUInt16LE(entries.length, 8);
6058
+ end.writeUInt16LE(entries.length, 10);
6059
+ end.writeUInt32LE(directory.length, 12);
6060
+ end.writeUInt32LE(offset, 16);
6061
+ return Buffer.concat([
6062
+ ...locals,
6063
+ directory,
6064
+ end
6065
+ ]);
6066
+ };
6067
+ //#endregion
4607
6068
  //#region src/debug.ts
4608
6069
  async function debug(ctx, options) {
4609
6070
  const files = ctx.getFiles();
@@ -4611,12 +6072,34 @@ async function debug(ctx, options) {
4611
6072
  ctx.config.minify = false;
4612
6073
  const { fs, path } = ctx.runtime;
4613
6074
  const outdir = options.outdir;
6075
+ const archive = options.zip && outdir ? `${path.resolve(outdir)}.zip` : void 0;
6076
+ const entries = [];
6077
+ const writes = [];
6078
+ const write = (name, content) => {
6079
+ if (options.zip) {
6080
+ entries.push({
6081
+ name: `${basename(path.resolve(outdir))}/${name}`,
6082
+ data: content
6083
+ });
6084
+ return;
6085
+ }
6086
+ logger.info("cli", `Writing ${colors.bold(`${outdir}/${name}`)}`);
6087
+ writes.push(fs.writeFile(`${outdir}${path.sep}${name}`, content));
6088
+ };
6089
+ const finish = async () => {
6090
+ const failed = (await Promise.allSettled(writes)).flatMap((write) => write.status === "rejected" ? [write.reason] : []);
6091
+ if (failed.length) throw new AggregateError(failed, `${failed.length} debug file(s) could not be written to ${outdir}: ${failed[0]}`);
6092
+ if (!archive) return;
6093
+ fs.ensureDirSync(dirname(archive));
6094
+ logger.info("cli", `Writing ${colors.bold(archive)}`);
6095
+ await writeFile(archive, createZip(entries));
6096
+ };
4614
6097
  if (!options.dry && outdir) {
4615
- fs.ensureDirSync(outdir);
4616
- logger.info("cli", `Writing ${colors.bold(`${outdir}/config.json`)}`);
4617
- await fs.writeFile(`${outdir}/config.json`, JSON.stringify(ctx.config, null, 2));
6098
+ if (!options.zip) fs.ensureDirSync(outdir);
6099
+ write("config.json", JSON.stringify(ctx.config, null, 2));
4618
6100
  }
4619
6101
  if (options.onlyConfig) {
6102
+ await finish();
4620
6103
  measureTotal();
4621
6104
  return;
4622
6105
  }
@@ -4645,15 +6128,140 @@ async function debug(ctx, options) {
4645
6128
  const relative = path.relative(ctx.config.cwd, parsedPath.dir);
4646
6129
  const astJsonPath = `${relative}${path.sep}${parsedPath.name}.ast.json`.replaceAll(path.sep, "__");
4647
6130
  const cssPath = `${relative}${path.sep}${parsedPath.name}.css`.replaceAll(path.sep, "__");
4648
- logger.info("cli", `Writing ${colors.bold(`${outdir}/${astJsonPath}`)}`);
4649
- logger.info("cli", `Writing ${colors.bold(`${outdir}/${cssPath}`)}`);
4650
- return Promise.allSettled([fs.writeFile(`${outdir}${path.sep}${astJsonPath}`, JSON.stringify(result.toJSON(), null, 2)), fs.writeFile(`${outdir}${path.sep}${cssPath}`, css)]);
6131
+ write(astJsonPath, JSON.stringify(result.toJSON(), null, 2));
6132
+ write(cssPath, css);
4651
6133
  }
4652
6134
  });
6135
+ await finish();
4653
6136
  logger.info("cli", `Found ${colors.bold(`${filesWithCss.length}/${files.length}`)} files using Bamboo`);
4654
6137
  measureTotal();
4655
6138
  }
4656
6139
  //#endregion
6140
+ //#region src/doctor.ts
6141
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
6142
+ /**
6143
+ * Whether a generated file holds what codegen would write there.
6144
+ *
6145
+ * A file that cannot be read is not — codegen writes over it, as `OutputEngine` does. A
6146
+ * `package.json` is the consumer's as much as codegen's: `emit-pkg` writes entrypoints into it
6147
+ * and codegen only fills in the keys that are absent, so it is current when it has every one.
6148
+ */
6149
+ const isCurrent = (ctx, file, name, code) => {
6150
+ let text;
6151
+ try {
6152
+ text = ctx.runtime.fs.readFileSync(file);
6153
+ } catch {
6154
+ return false;
6155
+ }
6156
+ if (name !== "package.json") return text === code;
6157
+ try {
6158
+ const existing = JSON.parse(text);
6159
+ return Object.keys(JSON.parse(code)).every((key) => existing[key] !== void 0);
6160
+ } catch {
6161
+ return false;
6162
+ }
6163
+ };
6164
+ /**
6165
+ * Check a project the way the build reads it, without writing anything.
6166
+ *
6167
+ * What it reports are the causes of a build that does not do what it is asked, in the order a
6168
+ * reader would look: a generated `styled-system` out of step with the config — the types and the
6169
+ * runtime say one thing and the stylesheet another — a source the extractor cannot read, whose
6170
+ * every style is absent, and a call naming a pattern or recipe that does not exist.
6171
+ */
6172
+ async function doctor(ctx) {
6173
+ const { fs, path } = ctx.runtime;
6174
+ const cwd = ctx.config.cwd;
6175
+ const outdir = path.join(...ctx.paths.root);
6176
+ const relativeToOutdir = (file) => path.relative(outdir, file);
6177
+ let artifacts = ctx.getArtifacts();
6178
+ artifacts = await ctx.hooks["codegen:prepare"]?.({
6179
+ artifacts,
6180
+ changed: void 0
6181
+ }) ?? artifacts;
6182
+ const missing = [];
6183
+ const stale = [];
6184
+ let files = 0;
6185
+ for (const artifact of artifacts) {
6186
+ if (!artifact) continue;
6187
+ const dir = artifact.dir ?? ctx.paths.root;
6188
+ for (const entry of artifact.files) {
6189
+ if (!entry?.code) continue;
6190
+ files++;
6191
+ const file = path.join(...dir, entry.file);
6192
+ if (!fs.existsSync(file)) missing.push(relativeToOutdir(file));
6193
+ else if (!isCurrent(ctx, file, entry.file, entry.code)) stale.push(relativeToOutdir(file));
6194
+ }
6195
+ }
6196
+ const leftover = ctx.output.prune(artifacts, { dry: true }).stale.map(relativeToOutdir);
6197
+ const sources = ctx.getFiles();
6198
+ try {
6199
+ ctx.parseFiles();
6200
+ } catch (error) {
6201
+ const { code } = error;
6202
+ if (code !== "ERR_BAMBOO_EXTRACT_FAILED" && code !== "ERR_BAMBOO_DEAD_IMPORT") throw error;
6203
+ }
6204
+ const unextracted = Array.from(ctx.parseFailures, ([file, error]) => ({
6205
+ file: path.relative(cwd, file),
6206
+ message: messageOf(error)
6207
+ }));
6208
+ const deadCalls = Array.from(ctx.deadCalls, ([file, calls]) => calls.map((call) => `${path.relative(cwd, file)}: ${call.alias}`)).flat();
6209
+ const tokens = {};
6210
+ for (const [category, values] of ctx.tokens.view.categoryMap) tokens[category] = values.size;
6211
+ const problems = [];
6212
+ const outOfStep = [
6213
+ missing.length && `${missing.length} missing`,
6214
+ stale.length && `${stale.length} out of date`,
6215
+ leftover.length && `${leftover.length} no longer generated`
6216
+ ].filter(Boolean);
6217
+ if (outOfStep.length) problems.push(`The generated files in ${path.relative(cwd, outdir) || "."} are out of step with the config, ${outOfStep.join(", ")}: run \`bamboo codegen\`.`);
6218
+ if (unextracted.length) problems.push(`${unextracted.length} source file(s) could not be extracted.`);
6219
+ if (deadCalls.length) problems.push(`${deadCalls.length} call(s) name a pattern or recipe that does not exist.`);
6220
+ return {
6221
+ cwd,
6222
+ config: ctx.conf.path,
6223
+ sources: sources.length,
6224
+ artifacts: {
6225
+ outdir,
6226
+ files,
6227
+ missing,
6228
+ stale,
6229
+ leftover
6230
+ },
6231
+ unextracted,
6232
+ deadCalls,
6233
+ conditions: ctx.conditions.keys().length,
6234
+ tokens,
6235
+ utilities: ctx.utility.keys().length,
6236
+ recipes: ctx.recipes.keys.length,
6237
+ patterns: ctx.patterns.keys.length,
6238
+ problems
6239
+ };
6240
+ }
6241
+ /** The report as a reader takes it in: the project first, then what to fix. */
6242
+ function formatDoctorReport(report) {
6243
+ const tokenCount = Object.values(report.tokens).reduce((sum, count) => sum + count, 0);
6244
+ const categories = Object.keys(report.tokens).length;
6245
+ const lines = [
6246
+ `config ${report.config}`,
6247
+ `sources ${report.sources} file(s)`,
6248
+ `styled-system ${report.artifacts.outdir}, ${report.artifacts.files} file(s)`,
6249
+ `tokens ${tokenCount} in ${categories} categor${categories === 1 ? "y" : "ies"}`,
6250
+ `conditions ${report.conditions}`,
6251
+ `utilities ${report.utilities}`,
6252
+ `recipes ${report.recipes}`,
6253
+ `patterns ${report.patterns}`
6254
+ ];
6255
+ const detail = (title, items) => items.length ? [
6256
+ ``,
6257
+ title,
6258
+ ...items.map((item) => ` ${item}`)
6259
+ ] : [];
6260
+ lines.push(...detail("missing", report.artifacts.missing), ...detail("out of date", report.artifacts.stale), ...detail("no longer generated", report.artifacts.leftover), ...detail("not extracted", report.unextracted.map(({ file, message }) => `${file}: ${message.split("\n").find(Boolean) ?? ""}`)), ...detail("calls to nothing", report.deadCalls));
6261
+ lines.push("", report.problems.length ? report.problems.join("\n") : "No problems found.");
6262
+ return lines.join("\n");
6263
+ }
6264
+ //#endregion
4657
6265
  //#region src/generate.ts
4658
6266
  async function build(ctx, sourceScanCache, artifactIds) {
4659
6267
  await codegen(ctx, artifactIds);
@@ -4674,13 +6282,22 @@ async function build(ctx, sourceScanCache, artifactIds) {
4674
6282
  await ctx.writeCss(sheet);
4675
6283
  done(ctx.messages.buildComplete(parsed.files.length));
4676
6284
  }
4677
- async function generate(config, configPath) {
6285
+ /** Refuse an `include` matching no files — see `GenerateOptions.requireFiles`. */
6286
+ function assertFilesMatched(ctx) {
6287
+ const { include, exclude, cwd, watch } = ctx.config;
6288
+ const directory = include.find((glob) => statSync(resolve(cwd, glob), { throwIfNoEntry: false })?.isDirectory());
6289
+ if (watch && directory === void 0 || ctx.getFiles().length) return;
6290
+ const name = directory?.replace(/(.)[\\/]+$/, "$1");
6291
+ throw new BambooError("NOT_FOUND", `${include.map((glob) => `\`${glob}\``).join(", ")} match${include.length === 1 ? "es" : ""} no files, so nothing was built, and the stylesheet was left as it was.`, { hint: name !== void 0 ? `\`${name}\` is a directory, and a glob matches files: write one for the files in it, like \`${name}/**/*.tsx\`.` : `Globs are read from ${cwd}${exclude?.length ? ", less what `exclude` takes out" : ""}. Run \`bamboo --help\` if you meant a command.` });
6292
+ }
6293
+ async function generate(config, configPath, options = {}) {
4678
6294
  let ctx = await loadConfigAndCreateContext({
4679
6295
  config,
4680
6296
  configPath
4681
6297
  });
4682
6298
  const sourceScanCache = createSourceScanCache();
4683
6299
  const { cwd, watch, poll } = ctx.config;
6300
+ if (options.requireFiles && !ctx.config.emitTokensOnly) assertFilesMatched(ctx);
4684
6301
  await build(ctx, watch ? sourceScanCache : void 0);
4685
6302
  if (watch) {
4686
6303
  ctx.watchConfig(async () => {
@@ -4694,7 +6311,7 @@ async function generate(config, configPath) {
4694
6311
  config: ctx.config,
4695
6312
  changes: affecteds
4696
6313
  });
4697
- return build(ctx, sourceScanCache, Array.from(affecteds.artifacts));
6314
+ return build(ctx, sourceScanCache, artifactsToRebuild(affecteds));
4698
6315
  }, {
4699
6316
  cwd,
4700
6317
  poll
@@ -4921,4 +6538,4 @@ const hasUncompilableSources = (options) => {
4921
6538
  }
4922
6539
  };
4923
6540
  //#endregion
4924
- export { BambooContext, Builder, ParserResult, SourceProject, analyze, buildInfo, codegen, cssgen, debug, findViteConfig, generate, generatePackageExports, hasUncompilableSources, isStaticCompilerActive, loadConfigAndCreateContext, markStaticCompilerActive, setLogStream, setupConfig, setupGitIgnore, spec, startProfiling };
6541
+ export { BambooContext, Builder, ParserResult, SourceProject, analyze, artifactsToRebuild, buildInfo, codegen, cssgen, debug, doctor, explainUnresolvedStyle, findViteConfig, formatDoctorReport, generate, generatePackageExports, hasUncompilableSources, isStaticCompilerActive, loadConfigAndCreateContext, markStaticCompilerActive, setLogStream, setupConfig, setupGitIgnore, sourceMatcher, spec, startProfiling };