@bamboocss/node 1.55.7 → 1.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,10 +1,8 @@
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 { Node, SyntaxKind, childOf, forEachDescendant, getAliasNode, getDefaultImport, getDescendantsOfKind, getExportDeclarations, getFirstAncestor, getFirstAncestorByKind, getLineAndColumnAtPos, getLiteralText, getModuleSpecifierValue, getNamedImports, getNamespaceImport, isCompilerGone, isTypeOnly, nameNodeOf, stringLiteralValue, ts } from "@bamboocss/ts-ast";
5
4
  import { convertTsPathsToRegexes, diffConfigs, findConfig, loadConfig, mergeHooks } from "@bamboocss/config";
6
- import { BambooError, cssVarRefs, groupBy, truncateList, uniq } from "@bamboocss/shared";
7
- import { createHash } from "node:crypto";
5
+ import { BambooError, cssVarRefs, getOrCreateSet, groupBy, truncateList, uniq } from "@bamboocss/shared";
8
6
  import { appendFileSync, existsSync, readFileSync, statSync, writeFileSync } from "fs";
9
7
  import { dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "path";
10
8
  import picomatch from "picomatch";
@@ -12,7 +10,6 @@ import { pluginSvelte } from "@bamboocss/plugin-svelte";
12
10
  import { pluginVue } from "@bamboocss/plugin-vue";
13
11
  import { checkNamingAgreement, formatNamingDisagreement, messages, prunesPreflight } from "@bamboocss/core";
14
12
  import { Generator, generatePackageExports } from "@bamboocss/generator";
15
- import { ParserResult, Project } from "@bamboocss/parser";
16
13
  import fs, { existsSync as existsSync$1, promises } from "node:fs";
17
14
  import path, { dirname as dirname$1, isAbsolute as isAbsolute$1, join as join$1, resolve as resolve$1 } from "node:path";
18
15
  import { debounce } from "perfect-debounce";
@@ -24,7 +21,6 @@ import chokidar from "chokidar";
24
21
  import glob from "fast-glob";
25
22
  import fsExtra from "fs-extra";
26
23
  import { isMatch } from "matcher";
27
- import { resolveTsPathPattern } from "@bamboocss/config/ts-path";
28
24
  import readline from "node:readline";
29
25
  import { lookItUpSync } from "look-it-up";
30
26
  import outdent$1, { outdent } from "outdent";
@@ -62,7 +58,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
62
58
  async function analyze(ctx, options = {}) {
63
59
  const { Reporter, formatRecipeReport, formatTokenReport } = await import("@bamboocss/reporter");
64
60
  const reporter = new Reporter(ctx, {
65
- project: ctx.project,
61
+ parserOptions: ctx.parserOptions,
62
+ parseFile: (file) => ctx.parseFile(file),
63
+ prepare: (files) => ctx.prepareNativeExtraction(files),
66
64
  getRelativePath: ctx.runtime.path.relative,
67
65
  getFiles: ctx.getFiles,
68
66
  ...options
@@ -140,6 +138,47 @@ async function codegen(ctx, ids) {
140
138
  };
141
139
  }
142
140
  //#endregion
141
+ //#region src/astro-to-tsx.ts
142
+ /**
143
+ * Astro's compiler, loaded the first time a `.astro` file is actually parsed.
144
+ *
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.
149
+ */
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
+ /**
155
+ * A `.astro` file as TSX the extractor can parse.
156
+ *
157
+ * Nothing converted these before: the TypeScript parser read the raw file, recovering from the
158
+ * `---` fences and the template well enough to find calls in it. Oxc, which does all extraction
159
+ * now, rejects that text, failing the build on every Astro component.
160
+ *
161
+ * Astro's own TSX output is what its language tools type-check against — the frontmatter as
162
+ * module code, the template as JSX in a fragment — so it is valid by construction and keeps
163
+ * every expression the template evaluates, `class={css({ … })}` included.
164
+ */
165
+ const astroToTsx = (code, filename) => {
166
+ let result;
167
+ try {
168
+ result = load()(code, { filename });
169
+ } catch {
170
+ return "";
171
+ }
172
+ return result.code.replace(SOURCE_MAP_COMMENT, "\n");
173
+ };
174
+ /** Built in, rather than a plugin package: Astro support is part of the Vite integration. */
175
+ const pluginAstro = () => ({
176
+ name: "@bamboocss/node:astro",
177
+ hooks: { "parser:before": ({ filePath, content }) => {
178
+ if (filePath.endsWith(".astro")) return astroToTsx(content, filePath);
179
+ } }
180
+ });
181
+ //#endregion
143
182
  //#region src/extractable-files.ts
144
183
  /**
145
184
  * Which of the files `include` matched an extraction pass actually has to read.
@@ -179,7 +218,7 @@ async function codegen(ctx, ids) {
179
218
  * one it failed to read.
180
219
  */
181
220
  const SPECIFIER = /(?:\bfrom\s*|^\s*(?:import|export)\s*|\bimport\s*\(\s*|\brequire\s*\(\s*)['"]([^'"\n]+)['"]/gm;
182
- /** The extensions a specifier may omit, in the order `@bamboocss/ts-ast` tries them. */
221
+ /** The extensions a specifier may omit, in the order the native resolver tries them. */
183
222
  const EXTENSIONS = [
184
223
  ".ts",
185
224
  ".tsx",
@@ -1950,6 +1989,256 @@ var DiffEngine = class {
1950
1989
  }
1951
1990
  };
1952
1991
  //#endregion
1992
+ //#region src/parser-result.ts
1993
+ /**
1994
+ * What extraction found in one file, and the encoder calls that turn it into rules.
1995
+ *
1996
+ * Filled from the native analysis by `BambooContext.parseFile`; nothing here reads source.
1997
+ */
1998
+ var ParserResult = class {
1999
+ context;
2000
+ /** Ordered list of all ResultItem */
2001
+ all = [];
2002
+ css = /* @__PURE__ */ new Set();
2003
+ cva = /* @__PURE__ */ new Set();
2004
+ sva = /* @__PURE__ */ new Set();
2005
+ token = /* @__PURE__ */ new Set();
2006
+ viewTransition = /* @__PURE__ */ new Set();
2007
+ recipe = /* @__PURE__ */ new Map();
2008
+ pattern = /* @__PURE__ */ new Map();
2009
+ filePath;
2010
+ encoder;
2011
+ /** Resolver targets crossed while extracting values which contributed CSS. */
2012
+ dependencies = /* @__PURE__ */ new Set();
2013
+ /** Styles the build could not fully see. @see `UnresolvedStyle` */
2014
+ unresolved = [];
2015
+ /**
2016
+ * Calls to a name the pattern or recipe entrypoint no longer exports.
2017
+ *
2018
+ * Separate from `unresolved`, which grades a call the build *did* see and could only
2019
+ * partly resolve. These it saw and could not resolve at all: the binding is dead, so every
2020
+ * rule the call would have contributed is absent rather than incomplete. Reported by
2021
+ * `assertNoDeadCalls` rather than warned about, for that reason.
2022
+ */
2023
+ deadCalls = [];
2024
+ /**
2025
+ * Whether each result item is attributed to its call site, for a source map.
2026
+ *
2027
+ * Off for a source a `parser:before` hook rewrote: its positions are the hook's output's,
2028
+ * not the file's, and a wrong line is worse than none.
2029
+ */
2030
+ origins = true;
2031
+ /** Set on a result the native engine produced, with the reads it reported. @internal */
2032
+ native = false;
2033
+ nativePendingCandidates = [];
2034
+ nativeConfigurationFiles = [];
2035
+ constructor(context, encoder) {
2036
+ this.context = context;
2037
+ this.encoder = encoder ?? context.encoder;
2038
+ }
2039
+ append(result) {
2040
+ this.all.push(result);
2041
+ return result;
2042
+ }
2043
+ set(name, result) {
2044
+ switch (name) {
2045
+ case "css":
2046
+ this.setCss(result);
2047
+ break;
2048
+ case "cva":
2049
+ this.setCva(result);
2050
+ break;
2051
+ case "sva":
2052
+ this.setSva(result);
2053
+ break;
2054
+ case "token":
2055
+ this.setToken(result);
2056
+ break;
2057
+ default: throw new BambooError("UNKNOWN_RESULT_TYPE", `Unknown parser result type: "${name}". Expected one of: css, cva, sva, token`);
2058
+ }
2059
+ }
2060
+ setCss(result) {
2061
+ this.css.add(this.append(Object.assign({ type: "css" }, result)));
2062
+ if (result.data.some(Array.isArray)) throw new BambooError("INVALID_STYLE_ARGUMENT", "An array is not a style argument.", { hint: "Spread it instead, e.g. css(...styles) rather than css(styles)." });
2063
+ const encoder = this.encoder;
2064
+ encoder.withOrigin(this.originOf(result), () => result.data.forEach((obj) => encoder.processAtomic(obj)));
2065
+ }
2066
+ /** The call site of `result`, when the encoder is recording them. */
2067
+ originOf = (result) => {
2068
+ if (!this.origins || !this.encoder.recordOrigins) return void 0;
2069
+ return result.atomOrigin;
2070
+ };
2071
+ setCva(result) {
2072
+ this.cva.add(this.append(Object.assign({ type: "cva" }, result)));
2073
+ const encoder = this.encoder;
2074
+ encoder.withOrigin(this.originOf(result), () => result.data.forEach((data) => encoder.processAtomicRecipe(data)));
2075
+ }
2076
+ setSva(result) {
2077
+ this.sva.add(this.append(Object.assign({ type: "sva" }, result)));
2078
+ const encoder = this.encoder;
2079
+ encoder.withOrigin(this.originOf(result), () => result.data.forEach((data) => encoder.processAtomicSlotRecipe(data)));
2080
+ }
2081
+ /**
2082
+ * `kind` separates the variable reference — `token()` — from `token.value()`, the resolved
2083
+ * literal. They share this set deliberately: everything that reads a result for the token
2084
+ * *path* wants both, and only the fold cares which half was asked for.
2085
+ */
2086
+ setToken(result, kind = "token") {
2087
+ this.token.add(this.append(Object.assign({ type: kind }, result)));
2088
+ }
2089
+ setViewTransition(result) {
2090
+ this.viewTransition.add(this.append(Object.assign({ type: "viewTransition" }, result)));
2091
+ const encoder = this.encoder;
2092
+ result.data.forEach((obj) => encoder.processViewTransition(obj));
2093
+ }
2094
+ setPattern(name, result) {
2095
+ getOrCreateSet(this.pattern, name).add(this.append(Object.assign({
2096
+ type: "pattern",
2097
+ name
2098
+ }, result)));
2099
+ this.encoder.withOrigin(this.originOf(result), () => result.data.forEach((obj) => this.encoder.processPattern(name, obj)));
2100
+ }
2101
+ /**
2102
+ * @param unresolved The variant axes the call site passed and the build could not read.
2103
+ * `button({ size })` with a dynamic `size` and `button()` both arrive as `{}`, and the
2104
+ * difference decides whether a class the encoder is about to emit has a rule behind it.
2105
+ */
2106
+ setRecipe(recipeName, result, unresolved) {
2107
+ getOrCreateSet(this.recipe, recipeName).add(this.append(Object.assign({ type: "recipe" }, result)));
2108
+ const encoder = this.encoder;
2109
+ const recipes = this.context.recipes;
2110
+ if (!recipes.getConfig(recipeName)) return;
2111
+ const axes = unresolved?.size ? new Set(unresolved) : void 0;
2112
+ if (result.type) result.data.forEach((data) => {
2113
+ const [recipeProps, styleProps] = recipes.splitProps(recipeName, data);
2114
+ encoder.processStyleProps(styleProps);
2115
+ encoder.processRecipe(recipeName, recipeProps, axes);
2116
+ });
2117
+ else result.data.forEach((data) => {
2118
+ encoder.processRecipe(recipeName, data, axes);
2119
+ });
2120
+ }
2121
+ isEmpty() {
2122
+ return this.all.length === 0;
2123
+ }
2124
+ setFilePath(filePath) {
2125
+ this.filePath = filePath;
2126
+ return this;
2127
+ }
2128
+ /** @internal Called with each resolver target the native evaluation crossed. */
2129
+ addDependency(filePath) {
2130
+ this.dependencies.add(filePath.replaceAll("\\", "/"));
2131
+ }
2132
+ /** Local source paths crossed while resolving values this extraction encoded. */
2133
+ getDependencies() {
2134
+ const own = this.filePath?.replaceAll("\\", "/");
2135
+ return [...this.dependencies].filter((path) => path !== own).sort();
2136
+ }
2137
+ toArray() {
2138
+ return this.all;
2139
+ }
2140
+ toJSON() {
2141
+ return {
2142
+ css: Array.from(this.css),
2143
+ cva: Array.from(this.cva),
2144
+ sva: Array.from(this.sva),
2145
+ token: Array.from(this.token),
2146
+ viewTransition: Array.from(this.viewTransition),
2147
+ recipe: Object.fromEntries(Array.from(this.recipe.entries()).map(([key, value]) => [key, Array.from(value)])),
2148
+ pattern: Object.fromEntries(Array.from(this.pattern.entries()).map(([key, value]) => [key, Array.from(value)]))
2149
+ };
2150
+ }
2151
+ };
2152
+ //#endregion
2153
+ //#region src/source-project.ts
2154
+ /**
2155
+ * The source view every engine reads: disk, with caller-supplied bytes layered over it.
2156
+ *
2157
+ * Extraction and the Vite compiler run in Rust, and the Rust resolver reads ordinary files
2158
+ * itself. What it cannot see is bytes that exist nowhere on disk — a single-file component's
2159
+ * compiled script, a test's in-memory module — so those are held here, as overlays, and handed
2160
+ * across the native boundary with every analysis. Nothing here parses anything.
2161
+ */
2162
+ var SourceProject = class {
2163
+ options;
2164
+ /** Bytes explicitly supplied by a caller rather than read from disk, by normalized path. */
2165
+ overlays = /* @__PURE__ */ new Map();
2166
+ compilerOptions;
2167
+ constructor(options) {
2168
+ this.options = options;
2169
+ this.compilerOptions = { ...options.compilerOptions };
2170
+ }
2171
+ normalizePath = (filePath) => filePath.replaceAll("\\", "/");
2172
+ /** The `baseUrl` and `paths` module resolution reads. */
2173
+ get resolutionOptions() {
2174
+ return {
2175
+ baseUrl: this.compilerOptions.baseUrl,
2176
+ paths: this.compilerOptions.paths
2177
+ };
2178
+ }
2179
+ /** A tsconfig reload replaced the options resolution reads. */
2180
+ refreshResolutionConfiguration = (compilerOptions = {}) => {
2181
+ this.compilerOptions = { ...compilerOptions };
2182
+ };
2183
+ /** Source bytes from an overlay, else from disk; `undefined` when neither can be read. */
2184
+ getSourceText = (filePath) => {
2185
+ const overlay = this.overlays.get(this.normalizePath(filePath));
2186
+ if (overlay !== void 0) return overlay;
2187
+ try {
2188
+ return this.options.readFile(filePath);
2189
+ } catch {
2190
+ return;
2191
+ }
2192
+ };
2193
+ /** Whether that same source view can read a path. */
2194
+ sourceExists = (filePath) => this.overlays.has(this.normalizePath(filePath)) || this.options.fileExists(filePath);
2195
+ /** Whether a caller supplied bytes that can differ from the path on disk. */
2196
+ sourceIsOverridden = (filePath) => this.overlays.has(this.normalizePath(filePath));
2197
+ /** Every path a caller supplied bytes for. */
2198
+ getOverriddenSources = () => [...this.overlays.keys()];
2199
+ /** Supply the bytes for a path. */
2200
+ overlaySource = (filePath, content) => {
2201
+ this.overlays.set(this.normalizePath(filePath), content);
2202
+ };
2203
+ /**
2204
+ * Supply the bytes for a module, under the path extraction will ask for.
2205
+ *
2206
+ * A relative path resolves against the project's working directory, as `parseFile` resolves
2207
+ * it — so a module added as `src/a.tsx` is the one `parseFile('src/a.tsx')` reads.
2208
+ */
2209
+ addSourceFile = (filePath, content) => {
2210
+ this.overlaySource(this.absolute(filePath), content);
2211
+ };
2212
+ absolute = (filePath) => isAbsolute$1(filePath) ? filePath : join$1(this.options.cwd ?? process.cwd(), filePath);
2213
+ /** Forget bytes supplied through `overlaySource`. Returns whether there were any. */
2214
+ removeOverlay = (filePath) => this.overlays.delete(this.normalizePath(filePath));
2215
+ /**
2216
+ * A watched file changed on disk. Disk is now the truth for it, so an overlay that
2217
+ * stood in for it goes.
2218
+ */
2219
+ reloadSourceFile = (filePath) => {
2220
+ this.removeOverlay(this.absolute(filePath));
2221
+ };
2222
+ /**
2223
+ * A watched file was deleted. Its styles go with it — nothing re-parses a file that is gone,
2224
+ * so they would otherwise outlive it for as long as the context does.
2225
+ */
2226
+ removeSourceFile = (filePath, encoder = this.options.parserOptions.encoder) => {
2227
+ encoder.releaseFile(this.absolute(filePath));
2228
+ this.removeOverlay(this.absolute(filePath));
2229
+ };
2230
+ /**
2231
+ * Restore an encoder dump from a `.json` file in `include` — the output of `bamboo ship`,
2232
+ * or a library's shipped extraction — and report it as an empty result for that file.
2233
+ */
2234
+ parseJson = (filePath, encoder = this.options.parserOptions.encoder) => {
2235
+ const content = this.getSourceText(filePath);
2236
+ if (content === void 0) throw new Error(`bamboo: could not read ${filePath}`);
2237
+ encoder.fromJSON(JSON.parse(content));
2238
+ return new ParserResult(this.options.parserOptions, encoder).setFilePath(filePath);
2239
+ };
2240
+ };
2241
+ //#endregion
1953
2242
  //#region src/glob-dirname.ts
1954
2243
  function globDirname(globs) {
1955
2244
  const rootDirs = /* @__PURE__ */ new Set();
@@ -2306,23 +2595,14 @@ var BambooContext = class extends Generator {
2306
2595
  const config = conf.config;
2307
2596
  this.runtime = nodeRuntime;
2308
2597
  this.parserHooks = conf.hooks;
2309
- config.cwd ||= this.runtime.cwd();
2598
+ config.cwd = this.runtime.path.resolve(this.runtime.cwd(), config.cwd || ".");
2310
2599
  if (config.logLevel) logger.level = config.logLevel;
2311
- this.project = new Project({
2312
- cwd: config.cwd ?? this.runtime.cwd(),
2313
- tsConfigFilePath: conf.tsconfigFile ?? `${config.cwd ?? this.runtime.cwd()}/tsconfig.json`,
2314
- fs: { readFile: (filePath) => this.runtime.fs.readFileSync(filePath) },
2315
- ...conf.tsconfig,
2316
- deferInitialSourceFiles: true,
2317
- resolutionConfigFiles: getTsConfigResolutionFiles(conf),
2318
- getFiles: () => this.getFiles(),
2600
+ this.project = new SourceProject({
2601
+ cwd: config.cwd,
2319
2602
  readFile: (filePath) => this.runtime.fs.readFileSync(filePath),
2320
2603
  fileExists: (filePath) => this.runtime.fs.existsSync(filePath),
2321
- hooks: conf.hooks,
2322
- parserOptions: {
2323
- ...this.parserOptions,
2324
- join: this.runtime.path.join || this.parserOptions.join
2325
- }
2604
+ compilerOptions: conf.tsconfig?.compilerOptions,
2605
+ parserOptions: this.parserOptions
2326
2606
  });
2327
2607
  this.output = new OutputEngine(this);
2328
2608
  this.diff = new DiffEngine(this);
@@ -2462,6 +2742,90 @@ var BambooContext = class extends Generator {
2462
2742
  const outdir = this.runtime.path.join(...this.paths.root);
2463
2743
  return file === outdir || file.startsWith(outdir + this.runtime.path.sep);
2464
2744
  };
2745
+ /**
2746
+ * The text extraction reads for a file: its `parser:before` output, or its bytes when no hook
2747
+ * rewrites it. `undefined` when the file cannot be read at all.
2748
+ *
2749
+ * The same preparation `analyzeMany` is handed, so every scan that compares "what the parser
2750
+ * holds" against "what is on disk" compares against what extraction actually saw.
2751
+ */
2752
+ parsedSourceText = (filePath, onDisk) => {
2753
+ const original = this.project.getSourceText(filePath) ?? onDisk;
2754
+ if (original === void 0) return void 0;
2755
+ return this.prepareNativeSource(filePath, original).source;
2756
+ };
2757
+ /**
2758
+ * Token accounting for one file's text, in Rust — see `token-accounting.ts` for the rules.
2759
+ *
2760
+ * This used to walk the TypeScript tree, which meant reading `project.getSourceFile` for
2761
+ * every file mentioning a token, and that started the Go compiler over the whole inventory
2762
+ * on every stylesheet build, since `prune.tokens` defaults on.
2763
+ */
2764
+ accountTokens = (filePath, source) => {
2765
+ const { paths = {} } = this.project.resolutionOptions;
2766
+ return this.loadNativeExtractor().accountTokens(filePath, source, this.imports.value.tokens, Object.entries(paths).map(([pattern, values]) => ({
2767
+ pattern,
2768
+ paths: values
2769
+ })));
2770
+ };
2771
+ /**
2772
+ * What the Vite compiler needs to know about modules, in one native call. See
2773
+ * `native-extractor/src/fold/model.rs`.
2774
+ *
2775
+ * `sources` are the modules to analyze, as the bundler hands them over. Every other module a
2776
+ * value is resolved through is read the way extraction reads it: its `parser:before` output
2777
+ * when a hook rewrites it, disk otherwise, and an overlay the project holds wins over both.
2778
+ */
2779
+ compileModules = (sources, options) => {
2780
+ const { baseUrl, paths = {} } = this.project.resolutionOptions;
2781
+ const own = new Set(sources.map((source) => source.filename.replaceAll("\\", "/")));
2782
+ const auxiliary = [];
2783
+ for (const filePath of new Set([...this.nativeAuxiliaryFiles, ...this.project.getOverriddenSources()])) {
2784
+ const filename = this.runtime.path.abs(this.config.cwd, filePath);
2785
+ if (own.has(filename.replaceAll("\\", "/"))) continue;
2786
+ const overridden = this.project.sourceIsOverridden(filename);
2787
+ if (!overridden && !this.parserHooks["parser:before"] && this.runtime === nodeRuntime) continue;
2788
+ const original = this.project.getSourceText(filename);
2789
+ if (original === void 0) continue;
2790
+ const prepared = this.prepareNativeSource(filename, original);
2791
+ if (prepared.source !== original || overridden || this.runtime !== nodeRuntime) auxiliary.push({
2792
+ filename,
2793
+ source: prepared.source
2794
+ });
2795
+ }
2796
+ return this.loadNativeExtractor().compileModules(sources, auxiliary, {
2797
+ cwd: this.config.cwd,
2798
+ baseUrl,
2799
+ paths: Object.entries(paths).map(([pattern, values]) => ({
2800
+ pattern,
2801
+ paths: values
2802
+ })),
2803
+ tokens: this.nativeTokens,
2804
+ cssModules: this.imports.value.css,
2805
+ tokenModules: this.imports.value.tokens,
2806
+ recipeModules: this.imports.value.recipe,
2807
+ patternModules: this.imports.value.pattern,
2808
+ recipeNames: this.recipes.keys,
2809
+ patternNames: this.patterns.keys,
2810
+ references: options.references
2811
+ });
2812
+ };
2813
+ /**
2814
+ * The token table as the native evaluator reads it.
2815
+ *
2816
+ * Built once per context rather than per call: `compileModules` runs once per transformed
2817
+ * module, and the table is every token in the project — rebuilding it priced the whole
2818
+ * dictionary into every file, most of which never call `token()`.
2819
+ */
2820
+ get nativeTokens() {
2821
+ this.nativeTokenTable ??= this.tokens.allTokens.map((token) => ({
2822
+ path: token.name,
2823
+ value: this.tokens.view.get(token.name),
2824
+ variable: this.tokens.view.getVar(token.name)
2825
+ }));
2826
+ return this.nativeTokenTable;
2827
+ }
2828
+ nativeTokenTable;
2465
2829
  /** Load the required Rust extractor from the workspace or the published prebuild directory. */
2466
2830
  loadNativeExtractor = () => {
2467
2831
  const nativeRequire = createRequire(import.meta.url);
@@ -2509,7 +2873,7 @@ var BambooContext = class extends Generator {
2509
2873
  this.nativeConfigurationFiles.delete(owner);
2510
2874
  }
2511
2875
  const sources = [];
2512
- const auxiliary = this.parserHooks["parser:before"] || this.runtime !== nodeRuntime ? this.nativeAuxiliaryFiles : this.nativeAuxiliaryFiles.filter(this.project.sourceIsOverridden);
2876
+ const auxiliary = [...this.parserHooks["parser:before"] || this.runtime !== nodeRuntime ? this.nativeAuxiliaryFiles : this.nativeAuxiliaryFiles.filter(this.project.sourceIsOverridden), ...this.project.getOverriddenSources()];
2513
2877
  const inventory = uniq([...filePaths, ...auxiliary]);
2514
2878
  for (const filePath of inventory) {
2515
2879
  if (filePath.endsWith(".json")) continue;
@@ -2582,11 +2946,7 @@ var BambooContext = class extends Generator {
2582
2946
  pattern,
2583
2947
  paths: values
2584
2948
  })),
2585
- tokens: this.tokens.allTokens.map((token) => ({
2586
- path: token.name,
2587
- value: this.tokens.view.get(token.name),
2588
- variable: this.tokens.view.getVar(token.name)
2589
- })),
2949
+ tokens: this.nativeTokens,
2590
2950
  jsx: this.jsx.isEnabled
2591
2951
  };
2592
2952
  let analyses;
@@ -2659,7 +3019,7 @@ var BambooContext = class extends Generator {
2659
3019
  name: call.name,
2660
3020
  data,
2661
3021
  atomOrigin
2662
- });
3022
+ }, new Set(call.unresolvedKeys));
2663
3023
  continue;
2664
3024
  }
2665
3025
  const item = {
@@ -2687,7 +3047,7 @@ var BambooContext = class extends Generator {
2687
3047
  ].includes(call.importedName)) result.set(call.importedName, item);
2688
3048
  else if (call.kind === "css" && call.importedName === "viewTransition") result.setViewTransition(item);
2689
3049
  else if (call.kind === "pattern") result.setPattern(call.importedName, item);
2690
- else if (call.kind === "recipe") result.setRecipe(call.importedName, item);
3050
+ else if (call.kind === "recipe") result.setRecipe(call.importedName, item, new Set(call.unresolvedKeys));
2691
3051
  else if (call.kind === "token" || call.kind === "tokenValue") result.setToken(item, call.kind);
2692
3052
  else if (call.kind === "dead") result.deadCalls.push({
2693
3053
  name: call.importedName,
@@ -2730,7 +3090,6 @@ var BambooContext = class extends Generator {
2730
3090
  } catch (error) {
2731
3091
  this.nativeExtractions.delete(nativeFile);
2732
3092
  this.nativeSourceMetadata.delete(nativeFile);
2733
- if (isCompilerGone(error)) throw error;
2734
3093
  logger.caughtError("file:extract", `Failed to parse ${file}`, error);
2735
3094
  this.parseFailures.set(file, error);
2736
3095
  }
@@ -2918,14 +3277,19 @@ async function reportRebuildFailure(run) {
2918
3277
  //#endregion
2919
3278
  //#region src/config.ts
2920
3279
  const RESOLVED_HOOKS_NAME = "__resolved__";
2921
- const AUTO_PARSER_HOOKS = Object.freeze(["vue", "svelte"]);
3280
+ const AUTO_PARSER_HOOKS = Object.freeze([
3281
+ "vue",
3282
+ "svelte",
3283
+ "astro"
3284
+ ]);
2922
3285
  const autoPluginFactories = {
3286
+ astro: pluginAstro,
2923
3287
  svelte: pluginSvelte,
2924
3288
  vue: pluginVue
2925
3289
  };
2926
3290
  /**
2927
3291
  * Built-in plugins that are auto-injected when using the CLI or PostCSS plugin.
2928
- * These provide Vue/Svelte single-file-component support.
3292
+ * These provide Vue, Svelte and Astro single-file-component support.
2929
3293
  *
2930
3294
  * LightningCSS is not among them any more. It was reached through a `lightningcss: true`
2931
3295
  * config flag whose only job was to push `pluginLightningcss()` into this list — a second
@@ -3001,12 +3365,10 @@ function readSnapshot(ctx, filePath) {
3001
3365
  } catch {
3002
3366
  onDisk = void 0;
3003
3367
  }
3004
- const sourceFile = ctx.project.getSourceFile(filePath);
3005
3368
  return {
3006
3369
  filePath,
3007
3370
  onDisk,
3008
- parsed: sourceFile?.getFullText(),
3009
- sourceFile
3371
+ parsed: ctx.parsedSourceText(filePath, onDisk)
3010
3372
  };
3011
3373
  }
3012
3374
  /**
@@ -3047,27 +3409,35 @@ const failsStrict = (entry) => entry.reason === "unresolved-reference";
3047
3409
  * the same files; three separate passes read every file three times.
3048
3410
  */
3049
3411
  function accountSnapshot(ctx, snapshot, accounting) {
3050
- const { filePath, onDisk, parsed, sourceFile } = snapshot;
3412
+ const { filePath, onDisk, parsed } = snapshot;
3051
3413
  const { paths, prefixes, declined } = accounting;
3052
- if (onDisk == null || parsed == null || parsed !== onDisk) {
3053
- if (!(mentionsToken(ctx, onDisk) || mentionsToken(ctx, parsed))) return;
3054
- declined.push({
3055
- filePath,
3056
- line: 1,
3057
- reason: onDisk == null || parsed == null ? "unreadable" : "transformed"
3058
- });
3059
- return;
3060
- }
3061
- if (!mentionsToken(ctx, parsed)) return;
3062
- if (ctx.project.getSyntacticDiagnosticCount(filePath)) {
3063
- declined.push({
3414
+ {
3415
+ if (onDisk == null || parsed == null || parsed !== onDisk) {
3416
+ if (!(mentionsToken(ctx, onDisk) || mentionsToken(ctx, parsed))) return;
3417
+ declined.push({
3418
+ filePath,
3419
+ line: 1,
3420
+ reason: onDisk == null || parsed == null ? "unreadable" : "transformed"
3421
+ });
3422
+ return;
3423
+ }
3424
+ if (!mentionsToken(ctx, parsed)) return;
3425
+ const native = ctx.accountTokens(filePath, parsed);
3426
+ if (native.unparsed) {
3427
+ declined.push({
3428
+ filePath,
3429
+ line: 1,
3430
+ reason: "unparsed"
3431
+ });
3432
+ return;
3433
+ }
3434
+ for (const path of native.paths) paths.add(path);
3435
+ for (const prefix of native.prefixes) prefixes.add(prefix);
3436
+ for (const entry of native.declined) declined.push({
3064
3437
  filePath,
3065
- line: 1,
3066
- reason: "unparsed"
3438
+ ...entry
3067
3439
  });
3068
- return;
3069
3440
  }
3070
- accountFile(ctx, sourceFile, filePath, paths, prefixes, declined);
3071
3441
  }
3072
3442
  /**
3073
3443
  * Whether a file is worth walking — because it can name the artifact, or because a shape in it
@@ -3099,355 +3469,6 @@ const mentionsToken = (ctx, text) => {
3099
3469
  if (ctx.imports.value.tokens.some((mod) => text.includes(mod))) return true;
3100
3470
  return IMPORTING_CALL.test(text);
3101
3471
  };
3102
- /** Whether a module specifier resolves to the generated tokens artifact. */
3103
- const isTokensEntrypoint = (ctx, specifier) => {
3104
- const mods = ctx.imports.value.tokens;
3105
- if (mods.some((mod) => specifier.includes(mod))) return true;
3106
- const pathMappings = ctx.conf.tsOptions?.pathMappings;
3107
- if (!pathMappings) return false;
3108
- const resolved = resolveTsPathPattern(pathMappings, specifier);
3109
- if (!resolved) return false;
3110
- return mods.some((mod) => resolved.includes(mod) || resolved === mod);
3111
- };
3112
- const lineOf = (node) => getLineAndColumnAtPos(node.getSourceFile(), node.getStart()).line;
3113
- function accountFile(ctx, sourceFile, filePath, paths, prefixes, declined) {
3114
- const decline = (node, reason) => declined.push({
3115
- filePath,
3116
- line: lineOf(node),
3117
- reason,
3118
- start: node.getStart(),
3119
- end: node.getEnd()
3120
- });
3121
- /** Local names bound to the artifact: the `token` export, and any namespace of it. */
3122
- const bindings = /* @__PURE__ */ new Set();
3123
- for (const statement of sourceFile.statements) {
3124
- if (Node.isExportDeclaration(statement)) {
3125
- const specifier = getModuleSpecifierValue(statement);
3126
- if (specifier && isTokensEntrypoint(ctx, specifier)) decline(statement, "re-exported");
3127
- continue;
3128
- }
3129
- if (!Node.isImportDeclaration(statement)) continue;
3130
- const specifier = getModuleSpecifierValue(statement);
3131
- if (!specifier) continue;
3132
- const clause = statement.importClause;
3133
- if (!clause || isTypeOnly(statement)) continue;
3134
- if (!isTokensEntrypoint(ctx, specifier)) {
3135
- for (const named of getNamedImports(clause)) if (!isTypeOnly(named) && nameOf(nameNodeOf(named)) === "token") decline(named, "unclassified-import");
3136
- const foreignDefault = getDefaultImport(clause);
3137
- if (foreignDefault && nameOf(foreignDefault) === "token") decline(foreignDefault, "unclassified-import");
3138
- const foreignNamespace = getNamespaceImport(clause);
3139
- if (foreignNamespace && usesTokenMember(sourceFile, foreignNamespace.getText())) decline(foreignNamespace, "unclassified-import");
3140
- continue;
3141
- }
3142
- const defaultImport = getDefaultImport(clause);
3143
- if (defaultImport) decline(defaultImport, "unsupported-import");
3144
- const namespace = getNamespaceImport(clause);
3145
- if (namespace) bindings.add(namespace.getText());
3146
- for (const named of getNamedImports(clause)) {
3147
- if (isTypeOnly(named)) continue;
3148
- if (nameOf(nameNodeOf(named)) !== "token") {
3149
- if (usedAsValue(sourceFile, (getAliasNode(named) ?? nameNodeOf(named))?.getText() ?? "", named)) decline(named, "unsupported-import");
3150
- continue;
3151
- }
3152
- bindings.add((getAliasNode(named) ?? nameNodeOf(named))?.getText() ?? "");
3153
- }
3154
- }
3155
- for (const importEquals of getDescendantsOfKind(sourceFile, SyntaxKind.ImportEqualsDeclaration)) if (importEquals.getText().includes("token")) decline(importEquals, "import-equals");
3156
- for (const call of getDescendantsOfKind(sourceFile, SyntaxKind.CallExpression)) {
3157
- const callee = childOf(call, "expression");
3158
- const isRequire = callee !== void 0 && Node.isIdentifier(callee) && callee.getText() === "require";
3159
- const isDynamicImport = callee?.kind === SyntaxKind.ImportKeyword;
3160
- if (!isRequire && !isDynamicImport) continue;
3161
- const argument = childOf(call, "arguments")?.[0];
3162
- if (!argument) continue;
3163
- if (Node.isStringLiteral(argument) ? isTokensEntrypoint(ctx, stringLiteralValue(argument)) : true) decline(call, isRequire ? "require" : "dynamic-import");
3164
- }
3165
- const shadows = shadowedScopes(sourceFile);
3166
- for (const identifier of identifiersNamed(sourceFile, (name) => bindings.has(name) || name === "token")) {
3167
- const text = nameOf(identifier);
3168
- const parent = identifier.parent;
3169
- if (Node.isExportSpecifier(parent)) {
3170
- const declaration = getFirstAncestorByKind(parent, SyntaxKind.ExportDeclaration);
3171
- if (declaration && !childOf(declaration, "moduleSpecifier")) decline(identifier, "re-exported");
3172
- continue;
3173
- }
3174
- if (Node.isPropertyAccessExpression(parent) && parent.name === identifier) {
3175
- const object = parent.expression;
3176
- const objectName = Node.isIdentifier(object) ? object.getText() : void 0;
3177
- if (objectName && bindings.has(objectName)) continue;
3178
- decline(identifier, "unresolved-reference");
3179
- continue;
3180
- }
3181
- if (isDeclarationName(identifier, parent)) continue;
3182
- if (isShadowed(identifier, shadows.get(text))) continue;
3183
- const resolved = accountedPath(identifier);
3184
- if (resolved === void 0) {
3185
- decline(identifier, "unresolved-reference");
3186
- continue;
3187
- }
3188
- if (resolved.kind === "binding") continue;
3189
- if (resolved.kind === "prefix") {
3190
- prefixes.add(resolved.value);
3191
- continue;
3192
- }
3193
- paths.add(resolved.value);
3194
- }
3195
- }
3196
- /**
3197
- * Whether any `<namespace>.token` member access appears, for an unclassified namespace.
3198
- *
3199
- * Element access counts too: `ui['token'](k)` reaches the same export and is invisible to a
3200
- * property-access-only scan.
3201
- */
3202
- function usesTokenMember(sourceFile, namespace) {
3203
- if (getDescendantsOfKind(sourceFile, SyntaxKind.PropertyAccessExpression).some((access) => childOf(access, "expression")?.getText() === namespace && nameOf(nameNodeOf(access)) === "token")) return true;
3204
- return getDescendantsOfKind(sourceFile, SyntaxKind.ElementAccessExpression).some((access) => {
3205
- if (childOf(access, "expression")?.getText() !== namespace) return false;
3206
- const argument = childOf(access, "argumentExpression");
3207
- return argument != null && (!Node.isStringLiteral(argument) || stringLiteralValue(argument) === "token");
3208
- });
3209
- }
3210
- /**
3211
- * Every `Identifier` in the file whose name passes `wanted`, in document order.
3212
- *
3213
- * Not `getDescendantsOfKind(SyntaxKind.Identifier)`. `Identifier` is kind 80 and sorts *below*
3214
- * `SyntaxKind.FirstNode` (167), which is the boundary between tokens and parse-tree nodes — so
3215
- * ts-morph cannot search the parse tree for it and falls back to materializing the whole
3216
- * **token** tree. Measured at 27x this walk for the same 21,466 identifiers across 178 real
3217
- * files, and `usedAsValue` below pays it once per name, so the file was re-scanned in full for
3218
- * every binding it asked about.
3219
- *
3220
- * The name is tested on the compiler node, before any ts-morph wrapper is built, because the
3221
- * wrapper is the expensive half and almost every identifier in a file is not one of the handful
3222
- * this pass cares about. `nameOf` reads the same `escapedText` for an identifier, so the two
3223
- * agree by construction.
3224
- *
3225
- * The JSDoc walk is load-bearing rather than defensive: `ts.forEachChild` does not descend into
3226
- * JSDoc, but `getDescendantsOfKind` reaches it, and 72 of 1,116 files in this repository carry
3227
- * an identifier visible only that way. Dropping those reads as "this token is never used" and
3228
- * prunes a rule that is live — the silent direction, with no failing test to catch it.
3229
- */
3230
- function* identifiersNamed(sourceFile, wanted) {
3231
- const found = [];
3232
- const collect = (node) => {
3233
- if (node.kind === SyntaxKind.Identifier && wanted(String(node.text))) found.push(node);
3234
- const jsDoc = node.jsDoc;
3235
- if (jsDoc) for (const doc of jsDoc) collect(doc);
3236
- ts.forEachChild(node, collect);
3237
- };
3238
- collect(sourceFile);
3239
- for (const node of found) yield node;
3240
- }
3241
- /**
3242
- * An identifier's name as the compiler resolves it, not as it is spelled.
3243
- *
3244
- * `token` is the identifier `token`; reading `getText()` returns the escape and compares
3245
- * unequal, which let an import of the artifact's export past the checks that key on the name.
3246
- */
3247
- const nameOf = (node) => Node.isIdentifier(node) ? String(node.text) : node.getText();
3248
- /** Every name a binding name binds, following object and array destructuring. */
3249
- function boundNames(name, bound) {
3250
- if (!name) return;
3251
- if (Node.isIdentifier(name)) {
3252
- bound(nameOf(name));
3253
- return;
3254
- }
3255
- if (!Node.isObjectBindingPattern(name) && !Node.isArrayBindingPattern(name)) return;
3256
- for (const element of name.elements) if (Node.isBindingElement(element)) boundNames(element.name, bound);
3257
- }
3258
- /**
3259
- * Scopes that bind a name to something which cannot be the artifact, keyed by that name.
3260
- *
3261
- * A parameter named `token` is not the `token` export. `items.map((token) => token.value)`
3262
- * iterates token *objects* — from `@bamboocss/token-dictionary`, or from any list — and `token`
3263
- * is the obvious name to reach for. The identifier walk keyed on the spelling alone, so every
3264
- * read off such a parameter declined as an `unresolved-reference`, and one decline anywhere
3265
- * keeps every declaration in the project.
3266
- *
3267
- * That is not hypothetical: on this repository's own documentation site it was 40 declines
3268
- * across seven components, none of them a token call, holding a token layer of 500 declarations
3269
- * where 146 are referenced. Token accounting there emitted a byte-identical
3270
- * stylesheet and a wall of warnings — the feature reporting loudly that it had done nothing.
3271
- *
3272
- * Only the forms that *cannot* hold the artifact are collected. A parameter, a catch variable,
3273
- * and a function or class declaration each bind something this file defines. A `const token = …`
3274
- * in general does not — its initializer can be anything, including the artifact reached through a
3275
- * barrel — so it goes on declining. Declining is free; accepting a reference whose path is never
3276
- * recorded is the failure this module exists to prevent.
3277
- *
3278
- * The one variable form that is collected is a read off a binding already known to be local:
3279
- * `const { token } = props` is whatever `props` holds, and `props` is a parameter. Rooting the
3280
- * test at a local binding is what keeps `const { token } = ui` — a namespace import, which a
3281
- * barrel could make the artifact — declining as before.
3282
- */
3283
- function shadowedScopes(sourceFile) {
3284
- const scopes = /* @__PURE__ */ new Map();
3285
- const add = (name, scope) => {
3286
- if (!scope) return;
3287
- const existing = scopes.get(name);
3288
- if (existing) existing.push(scope);
3289
- else scopes.set(name, [scope]);
3290
- };
3291
- const variables = [];
3292
- forEachDescendant(sourceFile, (node) => {
3293
- if (Node.isParameterDeclaration(node)) {
3294
- const scope = node.parent;
3295
- boundNames(node.name, (name) => add(name, scope));
3296
- return;
3297
- }
3298
- if (Node.isCatchClause(node)) {
3299
- boundNames(node.variableDeclaration?.name, (name) => add(name, node));
3300
- return;
3301
- }
3302
- if (Node.isFunctionDeclaration(node) || Node.isClassDeclaration(node)) {
3303
- const name = node.name;
3304
- if (name) add(nameOf(name), node.parent);
3305
- return;
3306
- }
3307
- if (Node.isFunctionExpression(node) || Node.isClassExpression(node)) {
3308
- const name = node.name;
3309
- if (name) add(nameOf(name), node);
3310
- return;
3311
- }
3312
- if (Node.isVariableDeclaration(node)) variables.push(node);
3313
- });
3314
- for (const declaration of variables) {
3315
- if (!Node.isVariableDeclaration(declaration)) continue;
3316
- const root = rootIdentifier(declaration.initializer);
3317
- if (!root || !isShadowed(root, scopes.get(nameOf(root)))) continue;
3318
- const scope = getFirstAncestor(declaration, (ancestor) => Node.isBlock(ancestor) || Node.isSourceFile(ancestor) || Node.isModuleBlock(ancestor) || Node.isCaseClause(ancestor) || Node.isDefaultClause(ancestor) || Node.isForStatement(ancestor) || Node.isForOfStatement(ancestor) || Node.isForInStatement(ancestor));
3319
- boundNames(declaration.name, (name) => add(name, scope));
3320
- }
3321
- return scopes;
3322
- }
3323
- /**
3324
- * The identifier an expression is rooted at, for the member reads that keep it local.
3325
- *
3326
- * `props`, `props.theme` and `props['theme']` all root at `props`. Anything else — a call, an
3327
- * `await`, a literal — returns nothing, so the variable it initializes is not treated as local.
3328
- */
3329
- function rootIdentifier(expression) {
3330
- let current = expression;
3331
- while (current && (Node.isPropertyAccessExpression(current) || Node.isElementAccessExpression(current))) current = current.expression;
3332
- return current && Node.isIdentifier(current) ? current : void 0;
3333
- }
3334
- /**
3335
- * Whether an identifier is the *name* of a declaration rather than a read of one.
3336
- *
3337
- * `interface Props { token: Token }` names a member and reads nothing, but reached
3338
- * `accountedPath`, which cannot read it and so declined — and an `unresolved-reference` is the
3339
- * one decline that fails a strict build. `PropertyAssignment` was already excluded for this
3340
- * reason; the type and class members are the same statement about a different node.
3341
- *
3342
- * `ShorthandPropertyAssignment` is deliberately absent: `{ token }` names a property *and* reads
3343
- * the binding, so it is a reference like any other.
3344
- */
3345
- function isDeclarationName(identifier, parent) {
3346
- if (Node.isPropertyAssignment(parent) || Node.isPropertySignatureDeclaration(parent) || Node.isMethodSignatureDeclaration(parent) || Node.isPropertyDeclaration(parent) || Node.isMethodDeclaration(parent) || Node.isEnumMember(parent)) return nameNodeOf(parent) === identifier;
3347
- return false;
3348
- }
3349
- /**
3350
- * Whether an occurrence falls inside one of the scopes that shadow its name.
3351
- *
3352
- * Both nodes come from the same file, so containment in the tree is containment in the source
3353
- * range — which answers it without walking ancestors once per candidate scope.
3354
- */
3355
- function isShadowed(identifier, scopes) {
3356
- if (!scopes) return false;
3357
- const start = identifier.getStart();
3358
- const end = identifier.getEnd();
3359
- return scopes.some((scope) => scope.getStart() <= start && end <= scope.getEnd());
3360
- }
3361
- /**
3362
- * What one occurrence asks for, or `undefined` if it is not a call this can read.
3363
- *
3364
- * Accepts the callee position and nothing else — `token('x')`, `token.value('x')`, and the
3365
- * namespaced spellings of each. An identifier anywhere else is a value
3366
- * escaping somewhere this pass cannot follow: assigned (`const t = token`), passed
3367
- * (`useMemo(() => token)`), spread, or enumerated.
3368
- */
3369
- function accountedPath(identifier) {
3370
- const parent = identifier.parent;
3371
- if (!parent) return void 0;
3372
- if (Node.isImportSpecifier(parent) || Node.isNamespaceImport(parent) || Node.isImportClause(parent) || Node.isExportSpecifier(parent)) return { kind: "binding" };
3373
- if (Node.isCallExpression(parent) && parent.expression === identifier) return literalPath(parent);
3374
- if (!Node.isPropertyAccessExpression(parent) || parent.expression !== identifier) return void 0;
3375
- const property = parent.name.getText();
3376
- const grandParent = parent.parent;
3377
- if (property === "value") return Node.isCallExpression(grandParent) && grandParent.expression === parent ? literalPath(grandParent) : void 0;
3378
- if (property !== "token") return void 0;
3379
- if (Node.isCallExpression(grandParent) && grandParent.expression === parent) return literalPath(grandParent);
3380
- if (Node.isPropertyAccessExpression(grandParent) && grandParent.expression === parent) {
3381
- if (grandParent.name.getText() !== "value") return void 0;
3382
- const call = grandParent.parent;
3383
- return Node.isCallExpression(call) && call.expression === grandParent ? literalPath(call) : void 0;
3384
- }
3385
- }
3386
- /**
3387
- * The path a call asks for, or the prefix it is bounded by.
3388
- *
3389
- * Read through `getLiteralValue()`, never off the source text. The text carries escapes —
3390
- * `token('colors.red.300')` — and a path recorded raw looks up nothing, which
3391
- * would accept a reference and keep no declaration for it. That is the exact failure this
3392
- * module exists to make unrepresentable.
3393
- *
3394
- * A template literal with substitutions is not a path, but it is not unbounded either: its
3395
- * head is a prefix everything it can produce begins with. Declining one cost every token
3396
- * declaration in the project; bounding it costs the category. The head is the *whole* answer —
3397
- * `` `colors.${a}.${b}` `` bounds no more tightly than `` `colors.${x}` `` does — and an empty
3398
- * head bounds nothing at all, so that still declines.
3399
- */
3400
- function literalPath(call) {
3401
- if (!Node.isCallExpression(call)) return void 0;
3402
- const argument = unwrapAssertions(call.arguments[0]);
3403
- if (!argument) return void 0;
3404
- if (Node.isStringLiteral(argument)) return {
3405
- kind: "path",
3406
- value: stringLiteralValue(argument)
3407
- };
3408
- if (Node.isNoSubstitutionTemplateLiteral(argument)) return {
3409
- kind: "path",
3410
- value: stringLiteralValue(argument)
3411
- };
3412
- if (Node.isTemplateExpression(argument)) {
3413
- const head = getLiteralText(argument.head);
3414
- return head ? {
3415
- kind: "prefix",
3416
- value: head
3417
- } : void 0;
3418
- }
3419
- }
3420
- /**
3421
- * Whether a binding is read anywhere outside a type position.
3422
- *
3423
- * `import { Token, token }` brings in a type beside the value, and a type cannot produce a
3424
- * `var()` — but a binding that is *called* can, whatever it is named, because a barrel
3425
- * matching the specifier test could re-export `token` under it.
3426
- */
3427
- function usedAsValue(sourceFile, name, declaration) {
3428
- for (const identifier of identifiersNamed(sourceFile, (candidate) => candidate === name)) {
3429
- if (getFirstAncestor(identifier, (ancestor) => ancestor === declaration)) continue;
3430
- if (!getFirstAncestor(identifier, (ancestor) => Node.isTypeNode(ancestor))) return true;
3431
- }
3432
- return false;
3433
- }
3434
- /**
3435
- * Strip the wrappers that carry no runtime meaning.
3436
- *
3437
- * `` token(`animations.${name}` as Token) `` is the shape a *typed* caller writes, and has to
3438
- * be: the generated `Token` type is a union of template literals, so a `string`-typed
3439
- * substitution does not typecheck without the assertion. Reading only the outermost node
3440
- * declined exactly the call this bounding exists for — the one in this repository's own
3441
- * documentation site.
3442
- *
3443
- * Each of these evaluates to its inner expression, so unwrapping changes nothing about what
3444
- * the call receives.
3445
- */
3446
- function unwrapAssertions(node) {
3447
- let current = node;
3448
- while (current && (Node.isAsExpression(current) || Node.isSatisfiesExpression(current) || Node.isNonNullExpression(current) || Node.isParenthesizedExpression(current) || Node.isTypeAssertion(current))) current = current.expression;
3449
- return current;
3450
- }
3451
3472
  //#endregion
3452
3473
  //#region src/token-references.ts
3453
3474
  /**
@@ -3913,20 +3934,12 @@ var Builder = class {
3913
3934
  configGraphMtimes;
3914
3935
  /** Per-file source-scan results for `toCss`, valid while each file's mtime stands still. */
3915
3936
  sourceScanCache = createSourceScanCache();
3916
- /** Cross-file value reads each owner's last extraction performed, with parse-time digests. */
3917
- extractionReadsByOwner = /* @__PURE__ */ new Map();
3918
- /** Each owner's recipe surface — declared cva/sva configs plus export-statement texts. */
3919
- recipeSurfaceByOwner = /* @__PURE__ */ new Map();
3920
- /** Whether each file changed this pass kept its recipe surface; consulted by dependents. */
3921
- recipeSurfaceStable = /* @__PURE__ */ new Map();
3922
- /** Files this pass re-extracts because their bytes moved, as `sourcePath` spellings. */
3923
- changedThisPass = /* @__PURE__ */ new Set();
3924
- /** Whether this pass selected any owner through resolution-configuration changes. */
3925
- resolutionAffectedThisPass = false;
3926
- /** Per-pass digests of re-read values, so N dependents of one edit digest each value once. */
3927
- readDigestMemo = /* @__PURE__ */ new Map();
3928
- /** Resolution ledger as it stood before this pass's first physical source mutation. */
3937
+ /**
3938
+ * Dependency edges as they stood before this pass's first source mutation, and the owners
3939
+ * each changed file reached then — before re-extraction replaces the edges that found them.
3940
+ */
3929
3941
  capturedLedger;
3942
+ capturedDependents = /* @__PURE__ */ new Map();
3930
3943
  /**
3931
3944
  * Reload one edited source, keeping the closure the next extraction pass has to select.
3932
3945
  *
@@ -3942,18 +3955,20 @@ var Builder = class {
3942
3955
  */
3943
3956
  reloadSource = (filePath) => {
3944
3957
  const ctx = this.getContextOrThrow();
3945
- this.captureResolutionLedger(ctx);
3946
- return ctx.project.reloadSourceFile(filePath);
3958
+ this.captureResolutionLedger(ctx, filePath);
3959
+ ctx.project.reloadSourceFile(filePath);
3947
3960
  };
3948
3961
  /** The deletion half of `reloadSource`, with the same snapshot obligation. */
3949
3962
  removeSource = (filePath) => {
3950
3963
  const ctx = this.getContextOrThrow();
3951
- this.captureResolutionLedger(ctx);
3964
+ this.captureResolutionLedger(ctx, filePath);
3965
+ ctx.project.removeSourceFile(filePath);
3952
3966
  ctx.forgetNativeFile(filePath);
3953
- return ctx.project.removeSourceFile(filePath);
3954
3967
  };
3955
- captureResolutionLedger = (ctx) => {
3956
- this.capturedLedger ??= ctx.project.getResolutionLedger();
3968
+ captureResolutionLedger = (ctx, filePath) => {
3969
+ this.capturedLedger ??= ctx.getNativeDependencyLedger();
3970
+ const file = this.absOwner(ctx, filePath);
3971
+ if (!this.capturedDependents.has(file)) this.capturedDependents.set(file, ctx.getNativeDependents(file));
3957
3972
  };
3958
3973
  /** @internal Current and missing resolver paths which can change the stylesheet. */
3959
3974
  getResolutionReadFiles = () => {
@@ -4097,9 +4112,8 @@ var Builder = class {
4097
4112
  this.resolutionConfigurationBytes.clear();
4098
4113
  this.sourceScanCache.entries.clear();
4099
4114
  this.sourceScanCache.resolvedTokenReferences.clear();
4100
- this.extractionReadsByOwner.clear();
4101
- this.recipeSurfaceByOwner.clear();
4102
4115
  this.capturedLedger = void 0;
4116
+ this.capturedDependents.clear();
4103
4117
  await ctx.hooks["config:change"]?.({
4104
4118
  config: ctx.config,
4105
4119
  changes: this.affecteds
@@ -4140,14 +4154,14 @@ var Builder = class {
4140
4154
  const changedResolutionConfigurations = this.changedResolutionConfigurations(knownChanges);
4141
4155
  const changedResolutionSet = new Set(changedResolutionConfigurations);
4142
4156
  const resolutionAffected = /* @__PURE__ */ new Set();
4143
- const resolutionLedger = this.capturedLedger ?? (changedResolutionConfigurations.length ? ctx.project.getResolutionLedger() : void 0);
4157
+ const resolutionLedger = this.capturedLedger ?? (changedResolutionConfigurations.length ? ctx.getNativeDependencyLedger() : void 0);
4158
+ const capturedDependents = this.capturedDependents;
4144
4159
  this.capturedLedger = void 0;
4160
+ this.capturedDependents = /* @__PURE__ */ new Map();
4145
4161
  for (const [owner, configurations] of this.resolutionConfigurationSets) if (configurations.some((file) => changedResolutionSet.has(file))) resolutionAffected.add(owner);
4146
- this.resolutionAffectedThisPass = resolutionAffected.size > 0;
4147
4162
  if (changedResolutionConfigurations.length) {
4148
4163
  const tsconfigCandidates = new Set([...previousTsconfigFiles, ...this.tsconfigResolutionFiles]);
4149
- const replaceCompilerOptions = changedResolutionConfigurations.some((file) => tsconfigCandidates.has(file));
4150
- ctx.project.refreshResolutionConfiguration(ctx.conf.tsconfig?.compilerOptions, this.tsconfigResolutionFiles, replaceCompilerOptions);
4164
+ if (changedResolutionConfigurations.some((file) => tsconfigCandidates.has(file))) ctx.project.refreshResolutionConfiguration(ctx.conf.tsconfig?.compilerOptions);
4151
4165
  }
4152
4166
  const needsInventoryScan = !sourceChanges || sourceChanges.needsInventoryScan || this.sourceInventory === void 0;
4153
4167
  const inventory = needsInventoryScan ? ctx.getFiles() : [...this.sourceInventory];
@@ -4165,10 +4179,10 @@ var Builder = class {
4165
4179
  for (const [file, meta] of this.filesMeta?.changes ?? []) if (!meta.isUnchanged) this.sourceScanCache.entries.delete(this.absOwner(ctx, file));
4166
4180
  if (this.filesMeta?.hasFilesChanged) {
4167
4181
  logger.debug("builder", "Files changed, invalidating them");
4168
- this.invalidateChangedSources(ctx, inventory, resolutionAffected, resolutionLedger);
4182
+ this.invalidateChangedSources(ctx, inventory, resolutionAffected, resolutionLedger, capturedDependents);
4169
4183
  } else if (changedResolutionConfigurations.length) {
4170
4184
  ctx.encoder?.reconcileFileOwnerOrder("extract", inventory);
4171
- this.extractionOrder = this.orderAffectedFiles(inventory, resolutionAffected, resolutionLedger ?? [], []);
4185
+ this.extractionOrder = this.orderAffectedFiles(inventory, resolutionAffected, resolutionLedger ?? []);
4172
4186
  this.affectedFiles = new Set(this.extractionOrder.map(this.sourcePath));
4173
4187
  } else {
4174
4188
  this.affectedFiles = /* @__PURE__ */ new Set();
@@ -4179,43 +4193,35 @@ var Builder = class {
4179
4193
  /** Normalize the path identity shared by the Project ledger and file-owner keys. */
4180
4194
  sourcePath = (file) => file.replaceAll("\\", "/");
4181
4195
  /**
4182
- * Reload only changed ledger members, then select their transitive included consumers.
4196
+ * Refresh changed sources, then select them and their transitive included consumers.
4183
4197
  *
4184
- * The dependency graph is snapshotted before mutation: reloading an importer retracts its
4185
- * old forward edges, while deletion removes the target. Waiting until afterwards loses the
4186
- * very closure the rebuild needs. New targets also select every pending importer and each
4187
- * pending importer's dependent closure, because no edge to the new path existed yet.
4198
+ * Consumers come from the native evaluator's read graph, which includes paths a consumer
4199
+ * probed and did not find — so a file appearing reaches the importers that were waiting for
4200
+ * it. The graph is read before anything is re-extracted: re-extraction replaces an owner's
4201
+ * edges, and waiting would lose the very closure the rebuild needs. An integration that
4202
+ * mutated sources earlier in the pass captured it then (`reloadSource`, `removeSource`).
4188
4203
  */
4189
- invalidateChangedSources = (ctx, inventory, seededAffected = /* @__PURE__ */ new Set(), previousLedger) => {
4190
- const project = ctx.project;
4204
+ invalidateChangedSources = (ctx, inventory, seededAffected = /* @__PURE__ */ new Set(), previousLedger, capturedDependents = /* @__PURE__ */ new Map()) => {
4191
4205
  const current = new Set(inventory.map(this.sourcePath));
4192
4206
  const changed = [...this.filesMeta?.changes ?? []].filter(([, meta]) => !meta.isUnchanged).map(([file]) => this.sourcePath(file));
4193
- const ledger = previousLedger ?? project.getResolutionLedger();
4194
- const pending = project.getUnresolvedImporters().map(this.sourcePath);
4207
+ const ledger = previousLedger ?? ctx.getNativeDependencyLedger();
4195
4208
  const affected = new Set(seededAffected);
4196
- const added = [];
4197
4209
  for (const file of changed) {
4198
4210
  if (current.has(file)) affected.add(file);
4199
- for (const dependent of project.getDependents(file)) affected.add(this.sourcePath(dependent));
4211
+ for (const dependent of capturedDependents.get(file) ?? []) affected.add(this.sourcePath(dependent));
4200
4212
  for (const dependent of ctx.getNativeDependents(file)) affected.add(this.sourcePath(dependent));
4201
- if (existsSync(file) && !project.getSourceFile(file)) added.push(file);
4202
- }
4203
- if (added.length) for (const importer of pending) {
4204
- affected.add(importer);
4205
- for (const dependent of project.getDependents(importer)) affected.add(this.sourcePath(dependent));
4206
4213
  }
4207
4214
  for (const file of changed) if (!existsSync(file)) {
4208
- project.removeSourceFile(file);
4215
+ ctx.project.removeSourceFile(file);
4216
+ ctx.forgetNativeFile(file);
4209
4217
  fileModifiedMap.set(file, -Infinity);
4210
- } else if (project.getSourceFile(file)) project.reloadSourceFile(file);
4211
- else project.createSourceFile(file);
4218
+ } else ctx.project.reloadSourceFile(file);
4212
4219
  ctx.encoder?.reconcileFileOwnerOrder("extract", inventory);
4213
- const syntheticEdges = added.flatMap((target) => pending.map((importer) => [target, importer]));
4214
- this.extractionOrder = this.orderAffectedFiles(inventory, affected, ledger, syntheticEdges);
4220
+ this.extractionOrder = this.orderAffectedFiles(inventory, affected, ledger);
4215
4221
  this.affectedFiles = new Set(this.extractionOrder.map(this.sourcePath));
4216
4222
  };
4217
4223
  /** Deterministic topological order, with current inventory order as the stable tie-break. */
4218
- orderAffectedFiles = (inventory, affected, ledger, syntheticEdges) => {
4224
+ orderAffectedFiles = (inventory, affected, ledger) => {
4219
4225
  const files = inventory.filter((file) => affected.has(this.sourcePath(file)));
4220
4226
  const byPath = new Map(files.map((file) => [this.sourcePath(file), file]));
4221
4227
  const inventoryRank = new Map(files.map((file, index) => [this.sourcePath(file), index]));
@@ -4232,9 +4238,8 @@ var Builder = class {
4232
4238
  outgoing.set(target, importers);
4233
4239
  indegree.set(importer, (indegree.get(importer) ?? 0) + 1);
4234
4240
  };
4235
- for (const fact of ledger) addEdge(fact.target, fact.importer);
4241
+ for (const [target, importer] of ledger) addEdge(target, importer);
4236
4242
  for (const [target, importer] of this.getContextOrThrow().getNativeDependencyLedger()) addEdge(target, importer);
4237
- for (const [target, importer] of syntheticEdges) addEdge(target, importer);
4238
4243
  const compare = (left, right) => (inventoryRank.get(left) ?? 0) - (inventoryRank.get(right) ?? 0);
4239
4244
  const ready = new MinPriorityQueue(compare);
4240
4245
  for (const [file, degree] of indegree) if (degree === 0) ready.push(file);
@@ -4298,45 +4303,8 @@ var Builder = class {
4298
4303
  if (!this.context) throw new BambooError("NO_CONTEXT", "context not loaded");
4299
4304
  return this.context;
4300
4305
  };
4301
- /**
4302
- * The changed file's recipe surface: every declared `cva`/`sva` config, in declaration
4303
- * order, plus the text of every export statement. A value edit inside a `css()` call moves
4304
- * neither; a recipe config edit moves the first; an export alias or re-export edit — which
4305
- * can re-route what a consumer's call resolves to without any declaration changing — moves
4306
- * the second. `undefined` when any part cannot be pinned down, which disables skipping.
4307
- */
4308
- digestRecipeSurface = (ctx, file, parserResult) => {
4309
- try {
4310
- const recipes = [];
4311
- for (const set of [parserResult?.cva, parserResult?.sva]) for (const item of set ?? []) recipes.push([item.name ?? "", item.data]);
4312
- const sourceFile = ctx.project?.getSourceFile?.(file);
4313
- const exports = sourceFile ? getExportDeclarations(sourceFile).map((declaration) => declaration.getText()) : [];
4314
- const json = JSON.stringify([recipes, exports], (_key, value) => value === void 0 ? "bamboo:undefined" : value);
4315
- if (json === void 0) return void 0;
4316
- return createHash("sha256").update(json).digest("base64");
4317
- } catch {
4318
- return;
4319
- }
4320
- };
4321
4306
  /** One canonical spelling for verification keys: absolute, forward slashes. */
4322
4307
  absOwner = (ctx, file) => this.sourcePath(ctx.runtime?.path?.abs ? ctx.runtime.path.abs(ctx.config.cwd, file) : file);
4323
- /** Whether every changed file this dependent reads kept both its values and its surface. */
4324
- dependentUnchangedByReads = (ctx, owner) => {
4325
- if (this.resolutionAffectedThisPass || this.changedThisPass.size === 0) return false;
4326
- const reads = this.extractionReadsByOwner.get(owner);
4327
- if (reads === void 0) return false;
4328
- for (const changed of this.changedThisPass) if (this.recipeSurfaceStable.get(changed) !== true) return false;
4329
- for (const read of reads) {
4330
- const readOwner = this.sourcePath(ctx.runtime.path.abs(ctx.config.cwd, read.file));
4331
- if (!this.changedThisPass.has(readOwner)) continue;
4332
- if (read.digest === void 0) return false;
4333
- const key = `${read.file}\u0000${read.name}`;
4334
- if (!this.readDigestMemo.has(key)) this.readDigestMemo.set(key, ctx.project.digestExportRead(read.file, read.name));
4335
- const current = this.readDigestMemo.get(key);
4336
- if (current === void 0 || current !== read.digest) return false;
4337
- }
4338
- return true;
4339
- };
4340
4308
  getFileMeta = (file) => {
4341
4309
  const mtime = existsSync(file) ? statSync(file).mtimeMs : -Infinity;
4342
4310
  return {
@@ -4362,18 +4330,6 @@ var Builder = class {
4362
4330
  const meta = this.filesMeta?.changes.get(file) ?? this.getFileMeta(file);
4363
4331
  const hasConfigChanged = this.affecteds ? this.affecteds.hasConfigChanged : true;
4364
4332
  if (meta.isUnchanged && !hasConfigChanged && !this.affectedFiles?.has(this.sourcePath(file))) return;
4365
- /**
4366
- * A dependent selected only because a file it reads changed can be verified instead of
4367
- * re-extracted: its own bytes did not move, so its extraction output moves only if a
4368
- * value it read moved, or if the changed file's recipe surface — which decides how its
4369
- * calls classify — moved. Both are checked against digests recorded when this owner was
4370
- * last extracted; the changed file itself was re-extracted earlier in this same ordered
4371
- * pass, which is what makes the surface comparison current. Any gap — a read that could
4372
- * not be digested, a surface this pass has no verdict for, a JSX-component config whose
4373
- * classification these records do not witness — falls through to the re-extraction this
4374
- * replaces.
4375
- */
4376
- if (meta.isUnchanged && !hasConfigChanged && !this.changedThisPass.has(this.absOwner(ctx, file)) && !(ctx.jsx?.isEnabled ?? true) && this.dependentUnchangedByReads(ctx, this.absOwner(ctx, file))) return;
4377
4333
  const owner = this.sourcePath(file);
4378
4334
  const previousReads = this.resolutionReadSets.get(owner) ?? [];
4379
4335
  const previousPending = this.pendingResolutionReadSets.get(owner) ?? [];
@@ -4382,33 +4338,13 @@ var Builder = class {
4382
4338
  const parserResult = ctx.parseFile(file);
4383
4339
  recordResolvedTokenReferences(this.sourceScanCache, this.absOwner(ctx, file), parserResult);
4384
4340
  fileModifiedMap.set(file, meta.mtime);
4385
- {
4386
- const owner = this.absOwner(ctx, file);
4387
- const reads = parserResult?.getExportReads?.() ?? [];
4388
- const parsedNatively = Boolean(parserResult?.native);
4389
- if (parsedNatively) this.extractionReadsByOwner.delete(owner);
4390
- else this.extractionReadsByOwner.set(owner, reads);
4391
- const surface = !parsedNatively && ctx.project ? this.digestRecipeSurface(ctx, file, parserResult) : void 0;
4392
- if (this.changedThisPass.has(owner)) {
4393
- const previous = this.recipeSurfaceByOwner.get(owner);
4394
- this.recipeSurfaceStable.set(owner, previous !== void 0 && surface !== void 0 && previous === surface);
4395
- }
4396
- this.recipeSurfaceByOwner.set(owner, surface);
4397
- }
4398
4341
  if (parserResult) {
4399
- const previousReadSet = meta.isUnchanged ? {
4400
- dependencies: uniq([...previousReads, ...previousPending]).sort(),
4401
- pendingCandidates: previousCandidates
4402
- } : void 0;
4403
- const nativeResult = parserResult;
4404
- const native = Boolean(nativeResult.native);
4405
- const dependencies = parserResult.getDependencies();
4406
- const readSet = native ? {
4407
- dependencies: uniq(dependencies).sort(),
4408
- pendingCandidates: uniq([...nativeResult.nativePendingCandidates ?? []]).sort()
4409
- } : ctx.project.getResolutionReadSet(file, dependencies, previousReadSet);
4342
+ const readSet = {
4343
+ dependencies: uniq(parserResult.getDependencies()).sort(),
4344
+ pendingCandidates: uniq([...parserResult.nativePendingCandidates]).sort()
4345
+ };
4410
4346
  const currentReads = readSet.dependencies;
4411
- const currentConfigurations = native ? uniq([...currentReads.length || readSet.pendingCandidates.length ? this.tsconfigResolutionFiles : [], ...nativeResult.nativeConfigurationFiles ?? []]).sort() : ctx.project.getResolutionConfigurationFiles(file, dependencies, meta.isUnchanged ? previousConfigurations : []);
4347
+ const currentConfigurations = uniq([...currentReads.length || readSet.pendingCandidates.length ? this.tsconfigResolutionFiles : [], ...parserResult.nativeConfigurationFiles]).sort();
4412
4348
  this.resolutionReadSets.set(owner, currentReads);
4413
4349
  if (readSet.pendingCandidates.length) this.resolutionCandidateSets.set(owner, readSet.pendingCandidates);
4414
4350
  else this.resolutionCandidateSets.delete(owner);
@@ -4444,9 +4380,6 @@ var Builder = class {
4444
4380
  }
4445
4381
  ctx.encoder?.reconcileFileOwnerOrder("extract", files);
4446
4382
  const filesToExtract = hasConfigChanged ? ctx.extractableFiles(files) : this.extractionOrder ?? files;
4447
- this.changedThisPass = new Set([...this.filesMeta?.changes ?? []].filter(([, fileMeta]) => !fileMeta.isUnchanged).map(([changed]) => this.sourcePath(ctx.runtime.path.abs(ctx.config.cwd, changed))));
4448
- this.recipeSurfaceStable.clear();
4449
- this.readDigestMemo.clear();
4450
4383
  const done = logger.time.info("Extracted in");
4451
4384
  ctx.prepareNativeExtraction(filesToExtract);
4452
4385
  for (const file of filesToExtract) this.extractFile(ctx, file);
@@ -4721,7 +4654,6 @@ async function generate(config, configPath) {
4721
4654
  await bundleStyles(ctx, [...new Set([filePath, ...dependents])]);
4722
4655
  } else if (event === "add") {
4723
4656
  const dependents = ctx.getNativeDependents(filePath);
4724
- ctx.project.createSourceFile(filePath);
4725
4657
  await bundleStyles(ctx, [...new Set([filePath, ...dependents])]);
4726
4658
  }
4727
4659
  });
@@ -4902,4 +4834,4 @@ const hasUncompilableSources = (options) => {
4902
4834
  }
4903
4835
  };
4904
4836
  //#endregion
4905
- export { BambooContext, Builder, analyze, buildInfo, codegen, cssgen, debug, findViteConfig, generate, generatePackageExports, hasUncompilableSources, isStaticCompilerActive, loadConfigAndCreateContext, markStaticCompilerActive, setLogStream, setupConfig, setupGitIgnore, spec, startProfiling };
4837
+ export { BambooContext, Builder, ParserResult, SourceProject, analyze, buildInfo, codegen, cssgen, debug, findViteConfig, generate, generatePackageExports, hasUncompilableSources, isStaticCompilerActive, loadConfigAndCreateContext, markStaticCompilerActive, setLogStream, setupConfig, setupGitIgnore, spec, startProfiling };