@bamboocss/node 1.48.5 → 1.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -23,8 +23,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  }) : target, mod));
24
24
  //#endregion
25
25
  const require_static_compiler = require("./static-compiler.cjs");
26
- let _bamboocss_reporter = require("@bamboocss/reporter");
27
26
  let _bamboocss_logger = require("@bamboocss/logger");
27
+ let _bamboocss_ts_ast = require("@bamboocss/ts-ast");
28
28
  let _bamboocss_config = require("@bamboocss/config");
29
29
  let _bamboocss_shared = require("@bamboocss/shared");
30
30
  let node_crypto = require("node:crypto");
@@ -48,7 +48,6 @@ let node_fs = require("node:fs");
48
48
  node_fs = __toESM(node_fs);
49
49
  let node_path = require("node:path");
50
50
  node_path = __toESM(node_path);
51
- let ts_morph = require("ts-morph");
52
51
  let chokidar = require("chokidar");
53
52
  chokidar = __toESM(chokidar);
54
53
  let fast_glob = require("fast-glob");
@@ -64,8 +63,15 @@ let outdent = require("outdent");
64
63
  outdent = __toESM(outdent);
65
64
  let child_process = require("child_process");
66
65
  //#region src/analyze.ts
67
- function analyze(ctx, options = {}) {
68
- const reporter = new _bamboocss_reporter.Reporter(ctx, {
66
+ /**
67
+ * `analyze` is one CLI command, but this module is reachable from `@bamboocss/node`'s index,
68
+ * so a static import made every consumer of that index — the CLI on any command, and the Vite
69
+ * plugin on every build — load the reporter and its table formatters to run neither. Loading
70
+ * it here keeps that off the path of everything that is not the `analyze` command.
71
+ */
72
+ async function analyze(ctx, options = {}) {
73
+ const { Reporter, formatRecipeReport, formatTokenReport } = await import("@bamboocss/reporter");
74
+ const reporter = new Reporter(ctx, {
69
75
  project: ctx.project,
70
76
  getRelativePath: ctx.runtime.path.relative,
71
77
  getFiles: ctx.getFiles,
@@ -77,14 +83,14 @@ function analyze(ctx, options = {}) {
77
83
  const report = reporter.getRecipeReport();
78
84
  return {
79
85
  report,
80
- formatted: (0, _bamboocss_reporter.formatRecipeReport)(report, format)
86
+ formatted: formatRecipeReport(report, format)
81
87
  };
82
88
  },
83
89
  getTokenReport(format = "table") {
84
90
  const report = reporter.getTokenReport();
85
91
  return {
86
92
  report,
87
- formatted: (0, _bamboocss_reporter.formatTokenReport)(report.getSummary(), format)
93
+ formatted: formatTokenReport(report.getSummary(), format)
88
94
  };
89
95
  },
90
96
  writeReport(filePath) {
@@ -1665,7 +1671,7 @@ const collectReferenceGraph = async (rootPath, rootParsed, parseTsconfig, cache)
1665
1671
  visited.add(referencedPath);
1666
1672
  try {
1667
1673
  const source = await node_fs.promises.readFile(referencedPath, "utf8");
1668
- if (ts_morph.ts.parseConfigFileTextToJson(referencedPath, source).error) throw new Error("Invalid tsconfig");
1674
+ JSON.parse(source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"));
1669
1675
  queue.push({
1670
1676
  parsed: parseTsconfig(referencedPath, cache),
1671
1677
  path: referencedPath
@@ -1820,6 +1826,21 @@ function globDirname(globs) {
1820
1826
  * mutated.
1821
1827
  */
1822
1828
  const globIgnore = (exclude) => ["**/*.d.ts", ...exclude ?? []];
1829
+ /**
1830
+ * The order the source glob returns files in, made a decision rather than an accident.
1831
+ *
1832
+ * `fast-glob` hands back whatever `readdir` gave it, which is the filesystem's order and is not
1833
+ * the same on every machine. That order is not cosmetic: it is the order atoms enter the sheet,
1834
+ * and sheet order is what decides a conflict between two classes on one element — `cx` joins
1835
+ * them and the browser picks by position, not by the order they were passed. So an unsorted
1836
+ * glob lets two checkouts of the same commit build stylesheets that resolve the same conflict
1837
+ * differently, and makes the emitted bytes irreproducible, which is also what content-hashed
1838
+ * asset caching is keyed on.
1839
+ *
1840
+ * Sorted by code unit rather than `localeCompare`, whose answer depends on the host's locale —
1841
+ * the exact class of machine-dependence this exists to remove.
1842
+ */
1843
+ const sortSources = (files) => files.sort();
1823
1844
  const nodeRuntime = {
1824
1845
  cwd() {
1825
1846
  return process.cwd();
@@ -1846,11 +1867,11 @@ const nodeRuntime = {
1846
1867
  },
1847
1868
  glob(opts) {
1848
1869
  if (!opts.include) return [];
1849
- return fast_glob.default.sync(opts.include, {
1870
+ return sortSources(fast_glob.default.sync(opts.include, {
1850
1871
  cwd: opts.cwd,
1851
1872
  ignore: globIgnore(opts.exclude),
1852
1873
  absolute: true
1853
- });
1874
+ }));
1854
1875
  },
1855
1876
  writeFile: fs_extra.default.writeFile,
1856
1877
  writeFileSync: fs_extra.default.writeFileSync,
@@ -1995,10 +2016,36 @@ var OutputEngine = class {
1995
2016
  const absPath = this.path.join(...dir, file);
1996
2017
  _bamboocss_logger.logger.debug("write:file", dir.slice(-1).concat(file).join("/"));
1997
2018
  if (file === "package.json") return this.writePackageJson(absPath, code);
2019
+ if (this.isUnchanged(absPath, code)) {
2020
+ _bamboocss_logger.logger.debug("write:unchanged", dir.slice(-1).concat(file).join("/"));
2021
+ return;
2022
+ }
1998
2023
  return this.fs.writeFile(absPath, code);
1999
2024
  }));
2000
2025
  };
2001
2026
  /**
2027
+ * Whether the file on disk already holds exactly what codegen would write.
2028
+ *
2029
+ * Not for the write itself, which is cheap — 54 artifacts and 1.4 MB measure ~6ms, against
2030
+ * ~1.3ms to read them back and compare. It is for the mtime. Codegen rewrote every artifact
2031
+ * on every build whether or not a byte moved, and most builds move nothing: `csstype.d.ts` is
2032
+ * copied verbatim from a constant and accounts for 895 kB on its own. Everything downstream
2033
+ * watches those files — the dev server's module graph, `tsc --incremental`, any bundler with
2034
+ * the output directory in scope — and each of them re-does work for a file that is identical
2035
+ * to the one it already read.
2036
+ *
2037
+ * A read that throws is an answer, not a failure: the file is unreadable or absent, so it has
2038
+ * to be written.
2039
+ */
2040
+ isUnchanged = (absPath, code) => {
2041
+ if (!this.fs.existsSync(absPath)) return false;
2042
+ try {
2043
+ return this.fs.readFileSync(absPath) === code;
2044
+ } catch {
2045
+ return false;
2046
+ }
2047
+ };
2048
+ /**
2002
2049
  * Unlike the rest of the output, `package.json` is not exclusively ours: `emit-pkg`
2003
2050
  * writes entrypoints to the same path, and consumers hand-edit it. Overwriting would
2004
2051
  * drop that, so only keys that are absent get filled in — anything already declared,
@@ -2082,6 +2129,9 @@ var BambooContext = class extends _bamboocss_generator.Generator {
2082
2129
  config.cwd ||= this.runtime.cwd();
2083
2130
  if (config.logLevel) _bamboocss_logger.logger.level = config.logLevel;
2084
2131
  this.project = new _bamboocss_parser.Project({
2132
+ cwd: config.cwd ?? this.runtime.cwd(),
2133
+ tsConfigFilePath: conf.tsconfigFile ?? `${config.cwd ?? this.runtime.cwd()}/tsconfig.json`,
2134
+ fs: { readFile: (filePath) => this.runtime.fs.readFileSync(filePath) },
2085
2135
  ...conf.tsconfig,
2086
2136
  deferInitialSourceFiles: true,
2087
2137
  resolutionConfigFiles: getTsConfigResolutionFiles(conf),
@@ -2266,9 +2316,10 @@ var BambooContext = class extends _bamboocss_generator.Generator {
2266
2316
  const results = [];
2267
2317
  files.forEach((file) => {
2268
2318
  const result = this.parseFile(file, encoder);
2269
- if (!result || result.isEmpty() || encoder.isEmpty()) return;
2270
- filesWithCss.push(file);
2319
+ if (!result || result.isEmpty()) return;
2271
2320
  results.push(result);
2321
+ if (encoder.isEmpty()) return;
2322
+ filesWithCss.push(file);
2272
2323
  });
2273
2324
  this.assertExtracted(files);
2274
2325
  this.assertNoDeadCalls(files);
@@ -2522,7 +2573,7 @@ function accountSnapshot(ctx, snapshot, accounting) {
2522
2573
  });
2523
2574
  return;
2524
2575
  }
2525
- if (parseErrorCount(sourceFile)) {
2576
+ if (ctx.project.getSyntacticDiagnosticCount(filePath)) {
2526
2577
  if (!mentionsToken(ctx, parsed)) return;
2527
2578
  declined.push({
2528
2579
  filePath,
@@ -2564,15 +2615,6 @@ const mentionsToken = (ctx, text) => {
2564
2615
  if (ctx.imports.value.tokens.some((mod) => text.includes(mod))) return true;
2565
2616
  return IMPORTING_CALL.test(text);
2566
2617
  };
2567
- /**
2568
- * How many syntax errors the parse produced.
2569
- *
2570
- * `parseDiagnostics` is TypeScript-internal and absent from the public `SourceFile` type, so
2571
- * it is reached through a cast. The alternative, `getPreEmitDiagnostics`, runs the type checker
2572
- * over the whole program — orders of magnitude more work for a question about syntax, and it
2573
- * would report type errors this pass has no business declining over.
2574
- */
2575
- const parseErrorCount = (sourceFile) => sourceFile.compilerNode.parseDiagnostics?.length ?? 0;
2576
2618
  /** Whether a module specifier resolves to the generated tokens artifact. */
2577
2619
  const isTokensEntrypoint = (ctx, specifier) => {
2578
2620
  const mods = ctx.imports.value.tokens;
@@ -2583,69 +2625,71 @@ const isTokensEntrypoint = (ctx, specifier) => {
2583
2625
  if (!resolved) return false;
2584
2626
  return mods.some((mod) => resolved.includes(mod) || resolved === mod);
2585
2627
  };
2586
- const lineOf = (node) => node.getSourceFile().getLineAndColumnAtPos(node.getStart()).line;
2628
+ const lineOf = (node) => (0, _bamboocss_ts_ast.getLineAndColumnAtPos)(node.getSourceFile(), node.getStart()).line;
2587
2629
  function accountFile(ctx, sourceFile, filePath, paths, prefixes, declined) {
2588
2630
  const decline = (node, reason) => declined.push({
2589
2631
  filePath,
2590
2632
  line: lineOf(node),
2591
- reason
2633
+ reason,
2634
+ start: node.getStart(),
2635
+ end: node.getEnd()
2592
2636
  });
2593
2637
  /** Local names bound to the artifact: the `token` export, and any namespace of it. */
2594
2638
  const bindings = /* @__PURE__ */ new Set();
2595
- for (const statement of sourceFile.getStatements()) {
2596
- if (ts_morph.Node.isExportDeclaration(statement)) {
2597
- const specifier = statement.getModuleSpecifierValue();
2639
+ for (const statement of sourceFile.statements) {
2640
+ if (_bamboocss_ts_ast.Node.isExportDeclaration(statement)) {
2641
+ const specifier = (0, _bamboocss_ts_ast.getModuleSpecifierValue)(statement);
2598
2642
  if (specifier && isTokensEntrypoint(ctx, specifier)) decline(statement, "re-exported");
2599
2643
  continue;
2600
2644
  }
2601
- if (!ts_morph.Node.isImportDeclaration(statement)) continue;
2602
- const specifier = statement.getModuleSpecifierValue();
2645
+ if (!_bamboocss_ts_ast.Node.isImportDeclaration(statement)) continue;
2646
+ const specifier = (0, _bamboocss_ts_ast.getModuleSpecifierValue)(statement);
2603
2647
  if (!specifier) continue;
2604
- const clause = statement.getImportClause();
2605
- if (!clause || statement.isTypeOnly()) continue;
2648
+ const clause = statement.importClause;
2649
+ if (!clause || (0, _bamboocss_ts_ast.isTypeOnly)(statement)) continue;
2606
2650
  if (!isTokensEntrypoint(ctx, specifier)) {
2607
- for (const named of clause.getNamedImports()) if (!named.isTypeOnly() && nameOf(named.getNameNode()) === "token") decline(named, "unclassified-import");
2608
- const foreignDefault = clause.getDefaultImport();
2651
+ for (const named of (0, _bamboocss_ts_ast.getNamedImports)(clause)) if (!(0, _bamboocss_ts_ast.isTypeOnly)(named) && nameOf((0, _bamboocss_ts_ast.nameNodeOf)(named)) === "token") decline(named, "unclassified-import");
2652
+ const foreignDefault = (0, _bamboocss_ts_ast.getDefaultImport)(clause);
2609
2653
  if (foreignDefault && nameOf(foreignDefault) === "token") decline(foreignDefault, "unclassified-import");
2610
- const foreignNamespace = clause.getNamespaceImport();
2654
+ const foreignNamespace = (0, _bamboocss_ts_ast.getNamespaceImport)(clause);
2611
2655
  if (foreignNamespace && usesTokenMember(sourceFile, foreignNamespace.getText())) decline(foreignNamespace, "unclassified-import");
2612
2656
  continue;
2613
2657
  }
2614
- const defaultImport = clause.getDefaultImport();
2658
+ const defaultImport = (0, _bamboocss_ts_ast.getDefaultImport)(clause);
2615
2659
  if (defaultImport) decline(defaultImport, "unsupported-import");
2616
- const namespace = clause.getNamespaceImport();
2660
+ const namespace = (0, _bamboocss_ts_ast.getNamespaceImport)(clause);
2617
2661
  if (namespace) bindings.add(namespace.getText());
2618
- for (const named of clause.getNamedImports()) {
2619
- if (named.isTypeOnly()) continue;
2620
- if (nameOf(named.getNameNode()) !== "token") {
2621
- if (usedAsValue(sourceFile, (named.getAliasNode() ?? named.getNameNode()).getText(), named)) decline(named, "unsupported-import");
2662
+ for (const named of (0, _bamboocss_ts_ast.getNamedImports)(clause)) {
2663
+ if ((0, _bamboocss_ts_ast.isTypeOnly)(named)) continue;
2664
+ if (nameOf((0, _bamboocss_ts_ast.nameNodeOf)(named)) !== "token") {
2665
+ if (usedAsValue(sourceFile, ((0, _bamboocss_ts_ast.getAliasNode)(named) ?? (0, _bamboocss_ts_ast.nameNodeOf)(named))?.getText() ?? "", named)) decline(named, "unsupported-import");
2622
2666
  continue;
2623
2667
  }
2624
- bindings.add((named.getAliasNode() ?? named.getNameNode()).getText());
2668
+ bindings.add(((0, _bamboocss_ts_ast.getAliasNode)(named) ?? (0, _bamboocss_ts_ast.nameNodeOf)(named))?.getText() ?? "");
2625
2669
  }
2626
2670
  }
2627
- for (const importEquals of sourceFile.getDescendantsOfKind(ts_morph.SyntaxKind.ImportEqualsDeclaration)) if (importEquals.getText().includes("token")) decline(importEquals, "import-equals");
2628
- for (const call of sourceFile.getDescendantsOfKind(ts_morph.SyntaxKind.CallExpression)) {
2629
- const callee = call.getExpression();
2630
- const isRequire = ts_morph.Node.isIdentifier(callee) && callee.getText() === "require";
2631
- const isDynamicImport = callee.getKind() === ts_morph.SyntaxKind.ImportKeyword;
2671
+ for (const importEquals of (0, _bamboocss_ts_ast.getDescendantsOfKind)(sourceFile, _bamboocss_ts_ast.SyntaxKind.ImportEqualsDeclaration)) if (importEquals.getText().includes("token")) decline(importEquals, "import-equals");
2672
+ for (const call of (0, _bamboocss_ts_ast.getDescendantsOfKind)(sourceFile, _bamboocss_ts_ast.SyntaxKind.CallExpression)) {
2673
+ const callee = (0, _bamboocss_ts_ast.childOf)(call, "expression");
2674
+ const isRequire = callee !== void 0 && _bamboocss_ts_ast.Node.isIdentifier(callee) && callee.getText() === "require";
2675
+ const isDynamicImport = callee?.kind === _bamboocss_ts_ast.SyntaxKind.ImportKeyword;
2632
2676
  if (!isRequire && !isDynamicImport) continue;
2633
- const argument = call.getArguments()[0];
2677
+ const argument = (0, _bamboocss_ts_ast.childOf)(call, "arguments")?.[0];
2634
2678
  if (!argument) continue;
2635
- if (ts_morph.Node.isStringLiteral(argument) ? isTokensEntrypoint(ctx, argument.getLiteralValue()) : true) decline(call, isRequire ? "require" : "dynamic-import");
2679
+ if (_bamboocss_ts_ast.Node.isStringLiteral(argument) ? isTokensEntrypoint(ctx, (0, _bamboocss_ts_ast.stringLiteralValue)(argument)) : true) decline(call, isRequire ? "require" : "dynamic-import");
2636
2680
  }
2637
2681
  const shadows = shadowedScopes(sourceFile);
2638
2682
  for (const identifier of identifiersNamed(sourceFile, (name) => bindings.has(name) || name === "token")) {
2639
2683
  const text = nameOf(identifier);
2640
- const parent = identifier.getParent();
2641
- if (ts_morph.Node.isExportSpecifier(parent)) {
2642
- const declaration = parent.getFirstAncestorByKind(ts_morph.SyntaxKind.ExportDeclaration);
2643
- if (declaration && !declaration.getModuleSpecifier()) decline(identifier, "re-exported");
2684
+ const parent = identifier.parent;
2685
+ if (_bamboocss_ts_ast.Node.isExportSpecifier(parent)) {
2686
+ const declaration = (0, _bamboocss_ts_ast.getFirstAncestorByKind)(parent, _bamboocss_ts_ast.SyntaxKind.ExportDeclaration);
2687
+ if (declaration && !(0, _bamboocss_ts_ast.childOf)(declaration, "moduleSpecifier")) decline(identifier, "re-exported");
2644
2688
  continue;
2645
2689
  }
2646
- if (ts_morph.Node.isPropertyAccessExpression(parent) && parent.getNameNode() === identifier) {
2647
- const object = parent.getExpression();
2648
- const objectName = ts_morph.Node.isIdentifier(object) ? object.getText() : void 0;
2690
+ if (_bamboocss_ts_ast.Node.isPropertyAccessExpression(parent) && parent.name === identifier) {
2691
+ const object = parent.expression;
2692
+ const objectName = _bamboocss_ts_ast.Node.isIdentifier(object) ? object.getText() : void 0;
2649
2693
  if (objectName && bindings.has(objectName)) continue;
2650
2694
  decline(identifier, "unresolved-reference");
2651
2695
  continue;
@@ -2672,11 +2716,11 @@ function accountFile(ctx, sourceFile, filePath, paths, prefixes, declined) {
2672
2716
  * property-access-only scan.
2673
2717
  */
2674
2718
  function usesTokenMember(sourceFile, namespace) {
2675
- if (sourceFile.getDescendantsOfKind(ts_morph.SyntaxKind.PropertyAccessExpression).some((access) => access.getExpression().getText() === namespace && nameOf(access.getNameNode()) === "token")) return true;
2676
- return sourceFile.getDescendantsOfKind(ts_morph.SyntaxKind.ElementAccessExpression).some((access) => {
2677
- if (access.getExpression().getText() !== namespace) return false;
2678
- const argument = access.getArgumentExpression();
2679
- return argument != null && (!ts_morph.Node.isStringLiteral(argument) || argument.getLiteralValue() === "token");
2719
+ if ((0, _bamboocss_ts_ast.getDescendantsOfKind)(sourceFile, _bamboocss_ts_ast.SyntaxKind.PropertyAccessExpression).some((access) => (0, _bamboocss_ts_ast.childOf)(access, "expression")?.getText() === namespace && nameOf((0, _bamboocss_ts_ast.nameNodeOf)(access)) === "token")) return true;
2720
+ return (0, _bamboocss_ts_ast.getDescendantsOfKind)(sourceFile, _bamboocss_ts_ast.SyntaxKind.ElementAccessExpression).some((access) => {
2721
+ if ((0, _bamboocss_ts_ast.childOf)(access, "expression")?.getText() !== namespace) return false;
2722
+ const argument = (0, _bamboocss_ts_ast.childOf)(access, "argumentExpression");
2723
+ return argument != null && (!_bamboocss_ts_ast.Node.isStringLiteral(argument) || (0, _bamboocss_ts_ast.stringLiteralValue)(argument) === "token");
2680
2724
  });
2681
2725
  }
2682
2726
  /**
@@ -2702,14 +2746,13 @@ function usesTokenMember(sourceFile, namespace) {
2702
2746
  function* identifiersNamed(sourceFile, wanted) {
2703
2747
  const found = [];
2704
2748
  const collect = (node) => {
2705
- if (node.kind === ts_morph.SyntaxKind.Identifier && wanted(String(node.escapedText))) found.push(node);
2749
+ if (node.kind === _bamboocss_ts_ast.SyntaxKind.Identifier && wanted(String(node.text))) found.push(node);
2706
2750
  const jsDoc = node.jsDoc;
2707
2751
  if (jsDoc) for (const doc of jsDoc) collect(doc);
2708
- ts_morph.ts.forEachChild(node, collect);
2752
+ _bamboocss_ts_ast.ts.forEachChild(node, collect);
2709
2753
  };
2710
- collect(sourceFile.compilerNode);
2711
- const wrap = sourceFile;
2712
- for (const node of found) yield wrap._getNodeFromCompilerNode(node);
2754
+ collect(sourceFile);
2755
+ for (const node of found) yield node;
2713
2756
  }
2714
2757
  /**
2715
2758
  * An identifier's name as the compiler resolves it, not as it is spelled.
@@ -2717,16 +2760,16 @@ function* identifiersNamed(sourceFile, wanted) {
2717
2760
  * `token` is the identifier `token`; reading `getText()` returns the escape and compares
2718
2761
  * unequal, which let an import of the artifact's export past the checks that key on the name.
2719
2762
  */
2720
- const nameOf = (node) => ts_morph.Node.isIdentifier(node) ? String(node.compilerNode.escapedText) : node.getText();
2763
+ const nameOf = (node) => _bamboocss_ts_ast.Node.isIdentifier(node) ? String(node.text) : node.getText();
2721
2764
  /** Every name a binding name binds, following object and array destructuring. */
2722
2765
  function boundNames(name, bound) {
2723
2766
  if (!name) return;
2724
- if (ts_morph.Node.isIdentifier(name)) {
2767
+ if (_bamboocss_ts_ast.Node.isIdentifier(name)) {
2725
2768
  bound(nameOf(name));
2726
2769
  return;
2727
2770
  }
2728
- if (!ts_morph.Node.isObjectBindingPattern(name) && !ts_morph.Node.isArrayBindingPattern(name)) return;
2729
- for (const element of name.getElements()) if (ts_morph.Node.isBindingElement(element)) boundNames(element.getNameNode(), bound);
2771
+ if (!_bamboocss_ts_ast.Node.isObjectBindingPattern(name) && !_bamboocss_ts_ast.Node.isArrayBindingPattern(name)) return;
2772
+ for (const element of name.elements) if (_bamboocss_ts_ast.Node.isBindingElement(element)) boundNames(element.name, bound);
2730
2773
  }
2731
2774
  /**
2732
2775
  * Scopes that bind a name to something which cannot be the artifact, keyed by that name.
@@ -2762,34 +2805,34 @@ function shadowedScopes(sourceFile) {
2762
2805
  else scopes.set(name, [scope]);
2763
2806
  };
2764
2807
  const variables = [];
2765
- sourceFile.forEachDescendant((node) => {
2766
- if (ts_morph.Node.isParameterDeclaration(node)) {
2767
- const scope = node.getParent();
2768
- boundNames(node.getNameNode(), (name) => add(name, scope));
2808
+ (0, _bamboocss_ts_ast.forEachDescendant)(sourceFile, (node) => {
2809
+ if (_bamboocss_ts_ast.Node.isParameterDeclaration(node)) {
2810
+ const scope = node.parent;
2811
+ boundNames(node.name, (name) => add(name, scope));
2769
2812
  return;
2770
2813
  }
2771
- if (ts_morph.Node.isCatchClause(node)) {
2772
- boundNames(node.getVariableDeclaration()?.getNameNode(), (name) => add(name, node));
2814
+ if (_bamboocss_ts_ast.Node.isCatchClause(node)) {
2815
+ boundNames(node.variableDeclaration?.name, (name) => add(name, node));
2773
2816
  return;
2774
2817
  }
2775
- if (ts_morph.Node.isFunctionDeclaration(node) || ts_morph.Node.isClassDeclaration(node)) {
2776
- const name = node.getNameNode();
2777
- if (name) add(nameOf(name), node.getParent());
2818
+ if (_bamboocss_ts_ast.Node.isFunctionDeclaration(node) || _bamboocss_ts_ast.Node.isClassDeclaration(node)) {
2819
+ const name = node.name;
2820
+ if (name) add(nameOf(name), node.parent);
2778
2821
  return;
2779
2822
  }
2780
- if (ts_morph.Node.isFunctionExpression(node) || ts_morph.Node.isClassExpression(node)) {
2781
- const name = node.getNameNode();
2823
+ if (_bamboocss_ts_ast.Node.isFunctionExpression(node) || _bamboocss_ts_ast.Node.isClassExpression(node)) {
2824
+ const name = node.name;
2782
2825
  if (name) add(nameOf(name), node);
2783
2826
  return;
2784
2827
  }
2785
- if (ts_morph.Node.isVariableDeclaration(node)) variables.push(node);
2828
+ if (_bamboocss_ts_ast.Node.isVariableDeclaration(node)) variables.push(node);
2786
2829
  });
2787
2830
  for (const declaration of variables) {
2788
- if (!ts_morph.Node.isVariableDeclaration(declaration)) continue;
2789
- const root = rootIdentifier(declaration.getInitializer());
2831
+ if (!_bamboocss_ts_ast.Node.isVariableDeclaration(declaration)) continue;
2832
+ const root = rootIdentifier(declaration.initializer);
2790
2833
  if (!root || !isShadowed(root, scopes.get(nameOf(root)))) continue;
2791
- const scope = declaration.getFirstAncestor((ancestor) => ts_morph.Node.isBlock(ancestor) || ts_morph.Node.isSourceFile(ancestor) || ts_morph.Node.isModuleBlock(ancestor) || ts_morph.Node.isCaseClause(ancestor) || ts_morph.Node.isDefaultClause(ancestor) || ts_morph.Node.isForStatement(ancestor) || ts_morph.Node.isForOfStatement(ancestor) || ts_morph.Node.isForInStatement(ancestor));
2792
- boundNames(declaration.getNameNode(), (name) => add(name, scope));
2834
+ const scope = (0, _bamboocss_ts_ast.getFirstAncestor)(declaration, (ancestor) => _bamboocss_ts_ast.Node.isBlock(ancestor) || _bamboocss_ts_ast.Node.isSourceFile(ancestor) || _bamboocss_ts_ast.Node.isModuleBlock(ancestor) || _bamboocss_ts_ast.Node.isCaseClause(ancestor) || _bamboocss_ts_ast.Node.isDefaultClause(ancestor) || _bamboocss_ts_ast.Node.isForStatement(ancestor) || _bamboocss_ts_ast.Node.isForOfStatement(ancestor) || _bamboocss_ts_ast.Node.isForInStatement(ancestor));
2835
+ boundNames(declaration.name, (name) => add(name, scope));
2793
2836
  }
2794
2837
  return scopes;
2795
2838
  }
@@ -2801,8 +2844,8 @@ function shadowedScopes(sourceFile) {
2801
2844
  */
2802
2845
  function rootIdentifier(expression) {
2803
2846
  let current = expression;
2804
- while (current && (ts_morph.Node.isPropertyAccessExpression(current) || ts_morph.Node.isElementAccessExpression(current))) current = current.getExpression();
2805
- return current && ts_morph.Node.isIdentifier(current) ? current : void 0;
2847
+ while (current && (_bamboocss_ts_ast.Node.isPropertyAccessExpression(current) || _bamboocss_ts_ast.Node.isElementAccessExpression(current))) current = current.expression;
2848
+ return current && _bamboocss_ts_ast.Node.isIdentifier(current) ? current : void 0;
2806
2849
  }
2807
2850
  /**
2808
2851
  * Whether an identifier is the *name* of a declaration rather than a read of one.
@@ -2816,7 +2859,7 @@ function rootIdentifier(expression) {
2816
2859
  * the binding, so it is a reference like any other.
2817
2860
  */
2818
2861
  function isDeclarationName(identifier, parent) {
2819
- if (ts_morph.Node.isPropertyAssignment(parent) || ts_morph.Node.isPropertySignature(parent) || ts_morph.Node.isMethodSignature(parent) || ts_morph.Node.isPropertyDeclaration(parent) || ts_morph.Node.isMethodDeclaration(parent) || ts_morph.Node.isEnumMember(parent)) return parent.getNameNode() === identifier;
2862
+ if (_bamboocss_ts_ast.Node.isPropertyAssignment(parent) || _bamboocss_ts_ast.Node.isPropertySignatureDeclaration(parent) || _bamboocss_ts_ast.Node.isMethodSignatureDeclaration(parent) || _bamboocss_ts_ast.Node.isPropertyDeclaration(parent) || _bamboocss_ts_ast.Node.isMethodDeclaration(parent) || _bamboocss_ts_ast.Node.isEnumMember(parent)) return (0, _bamboocss_ts_ast.nameNodeOf)(parent) === identifier;
2820
2863
  return false;
2821
2864
  }
2822
2865
  /**
@@ -2840,20 +2883,20 @@ function isShadowed(identifier, scopes) {
2840
2883
  * (`useMemo(() => token)`), spread, or enumerated.
2841
2884
  */
2842
2885
  function accountedPath(identifier) {
2843
- const parent = identifier.getParent();
2886
+ const parent = identifier.parent;
2844
2887
  if (!parent) return void 0;
2845
- if (ts_morph.Node.isImportSpecifier(parent) || ts_morph.Node.isNamespaceImport(parent) || ts_morph.Node.isImportClause(parent) || ts_morph.Node.isExportSpecifier(parent)) return { kind: "binding" };
2846
- if (ts_morph.Node.isCallExpression(parent) && parent.getExpression() === identifier) return literalPath(parent);
2847
- if (!ts_morph.Node.isPropertyAccessExpression(parent) || parent.getExpression() !== identifier) return void 0;
2848
- const property = parent.getNameNode().getText();
2849
- const grandParent = parent.getParent();
2850
- if (property === "value") return ts_morph.Node.isCallExpression(grandParent) && grandParent.getExpression() === parent ? literalPath(grandParent) : void 0;
2888
+ if (_bamboocss_ts_ast.Node.isImportSpecifier(parent) || _bamboocss_ts_ast.Node.isNamespaceImport(parent) || _bamboocss_ts_ast.Node.isImportClause(parent) || _bamboocss_ts_ast.Node.isExportSpecifier(parent)) return { kind: "binding" };
2889
+ if (_bamboocss_ts_ast.Node.isCallExpression(parent) && parent.expression === identifier) return literalPath(parent);
2890
+ if (!_bamboocss_ts_ast.Node.isPropertyAccessExpression(parent) || parent.expression !== identifier) return void 0;
2891
+ const property = parent.name.getText();
2892
+ const grandParent = parent.parent;
2893
+ if (property === "value") return _bamboocss_ts_ast.Node.isCallExpression(grandParent) && grandParent.expression === parent ? literalPath(grandParent) : void 0;
2851
2894
  if (property !== "token") return void 0;
2852
- if (ts_morph.Node.isCallExpression(grandParent) && grandParent.getExpression() === parent) return literalPath(grandParent);
2853
- if (ts_morph.Node.isPropertyAccessExpression(grandParent) && grandParent.getExpression() === parent) {
2854
- if (grandParent.getNameNode().getText() !== "value") return void 0;
2855
- const call = grandParent.getParent();
2856
- return ts_morph.Node.isCallExpression(call) && call.getExpression() === grandParent ? literalPath(call) : void 0;
2895
+ if (_bamboocss_ts_ast.Node.isCallExpression(grandParent) && grandParent.expression === parent) return literalPath(grandParent);
2896
+ if (_bamboocss_ts_ast.Node.isPropertyAccessExpression(grandParent) && grandParent.expression === parent) {
2897
+ if (grandParent.name.getText() !== "value") return void 0;
2898
+ const call = grandParent.parent;
2899
+ return _bamboocss_ts_ast.Node.isCallExpression(call) && call.expression === grandParent ? literalPath(call) : void 0;
2857
2900
  }
2858
2901
  }
2859
2902
  /**
@@ -2871,19 +2914,19 @@ function accountedPath(identifier) {
2871
2914
  * head bounds nothing at all, so that still declines.
2872
2915
  */
2873
2916
  function literalPath(call) {
2874
- if (!ts_morph.Node.isCallExpression(call)) return void 0;
2875
- const argument = unwrapAssertions(call.getArguments()[0]);
2917
+ if (!_bamboocss_ts_ast.Node.isCallExpression(call)) return void 0;
2918
+ const argument = unwrapAssertions(call.arguments[0]);
2876
2919
  if (!argument) return void 0;
2877
- if (ts_morph.Node.isStringLiteral(argument)) return {
2920
+ if (_bamboocss_ts_ast.Node.isStringLiteral(argument)) return {
2878
2921
  kind: "path",
2879
- value: argument.getLiteralValue()
2922
+ value: (0, _bamboocss_ts_ast.stringLiteralValue)(argument)
2880
2923
  };
2881
- if (ts_morph.Node.isNoSubstitutionTemplateLiteral(argument)) return {
2924
+ if (_bamboocss_ts_ast.Node.isNoSubstitutionTemplateLiteral(argument)) return {
2882
2925
  kind: "path",
2883
- value: argument.getLiteralValue()
2926
+ value: (0, _bamboocss_ts_ast.stringLiteralValue)(argument)
2884
2927
  };
2885
- if (ts_morph.Node.isTemplateExpression(argument)) {
2886
- const head = argument.getHead().getLiteralText();
2928
+ if (_bamboocss_ts_ast.Node.isTemplateExpression(argument)) {
2929
+ const head = (0, _bamboocss_ts_ast.getLiteralText)(argument.head);
2887
2930
  return head ? {
2888
2931
  kind: "prefix",
2889
2932
  value: head
@@ -2899,8 +2942,8 @@ function literalPath(call) {
2899
2942
  */
2900
2943
  function usedAsValue(sourceFile, name, declaration) {
2901
2944
  for (const identifier of identifiersNamed(sourceFile, (candidate) => candidate === name)) {
2902
- if (identifier.getFirstAncestor((ancestor) => ancestor === declaration)) continue;
2903
- if (!identifier.getFirstAncestor((ancestor) => ts_morph.Node.isTypeNode(ancestor))) return true;
2945
+ if ((0, _bamboocss_ts_ast.getFirstAncestor)(identifier, (ancestor) => ancestor === declaration)) continue;
2946
+ if (!(0, _bamboocss_ts_ast.getFirstAncestor)(identifier, (ancestor) => _bamboocss_ts_ast.Node.isTypeNode(ancestor))) return true;
2904
2947
  }
2905
2948
  return false;
2906
2949
  }
@@ -2918,7 +2961,7 @@ function usedAsValue(sourceFile, name, declaration) {
2918
2961
  */
2919
2962
  function unwrapAssertions(node) {
2920
2963
  let current = node;
2921
- while (current && (ts_morph.Node.isAsExpression(current) || ts_morph.Node.isSatisfiesExpression(current) || ts_morph.Node.isNonNullExpression(current) || ts_morph.Node.isParenthesizedExpression(current) || ts_morph.Node.isTypeAssertion(current))) current = current.getExpression();
2964
+ while (current && (_bamboocss_ts_ast.Node.isAsExpression(current) || _bamboocss_ts_ast.Node.isSatisfiesExpression(current) || _bamboocss_ts_ast.Node.isNonNullExpression(current) || _bamboocss_ts_ast.Node.isParenthesizedExpression(current) || _bamboocss_ts_ast.Node.isTypeAssertion(current))) current = current.expression;
2922
2965
  return current;
2923
2966
  }
2924
2967
  //#endregion
@@ -2989,10 +3032,49 @@ function* sourceTexts(ctx) {
2989
3032
  }
2990
3033
  const createSourceScanCache = () => ({
2991
3034
  signature: "",
2992
- entries: /* @__PURE__ */ new Map()
3035
+ entries: /* @__PURE__ */ new Map(),
3036
+ resolvedTokenReferences: /* @__PURE__ */ new Map()
2993
3037
  });
3038
+ const resolvedTokenReferences = (result) => {
3039
+ if (!result) return [];
3040
+ const facts = [];
3041
+ for (const item of result.token) {
3042
+ if (!item.tokenCalleeRange || !item.data?.length) continue;
3043
+ const paths = [];
3044
+ for (const value of item.data) {
3045
+ if (typeof value !== "string") break;
3046
+ paths.push(value);
3047
+ }
3048
+ if (paths.length !== item.data.length) continue;
3049
+ facts.push({
3050
+ ...item.tokenCalleeRange,
3051
+ paths: [...new Set(paths)].sort()
3052
+ });
3053
+ }
3054
+ return facts.sort((left, right) => left.start - right.start || left.end - right.end);
3055
+ };
3056
+ 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]));
3057
+ /**
3058
+ * Reconcile one file's lightweight token facts after extraction.
3059
+ *
3060
+ * Deleting the source scan only when the semantic facts moved is important for dependents:
3061
+ * changing an imported constant can change `token(KEY)` without changing the consumer's mtime.
3062
+ */
3063
+ const recordResolvedTokenReferences = (cache, filePath, result) => {
3064
+ const next = resolvedTokenReferences(result);
3065
+ if (sameResolvedTokenReferences(cache.resolvedTokenReferences.get(filePath), next)) return;
3066
+ if (next.length) cache.resolvedTokenReferences.set(filePath, next);
3067
+ else cache.resolvedTokenReferences.delete(filePath);
3068
+ cache.entries.delete(filePath);
3069
+ };
3070
+ const reconcileAccounting = (accounting, references, filePath) => {
3071
+ if (!references?.length) return;
3072
+ const ranges = new Set(references.map(({ start, end }) => `${start}:${end}`));
3073
+ for (const reference of references) for (const path of reference.paths) accounting.paths.add(path);
3074
+ 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}`));
3075
+ };
2994
3076
  const OPEN_TAG = /<\s*([a-z][\w-]*)(?=[\s/>]|$)/g;
2995
- const scanSnapshot = (ctx, snapshot, options, patterns) => {
3077
+ const scanSnapshot = (ctx, snapshot, options, patterns, resolvedReferences) => {
2996
3078
  const tokenPaths = /* @__PURE__ */ new Set();
2997
3079
  const cssVars = /* @__PURE__ */ new Set();
2998
3080
  const elements = /* @__PURE__ */ new Set();
@@ -3011,6 +3093,7 @@ const scanSnapshot = (ctx, snapshot, options, patterns) => {
3011
3093
  declined: []
3012
3094
  };
3013
3095
  accountSnapshot(ctx, snapshot, accounting);
3096
+ reconcileAccounting(accounting, resolvedReferences);
3014
3097
  return {
3015
3098
  tokenPaths: [...tokenPaths],
3016
3099
  cssVars: [...cssVars],
@@ -3080,7 +3163,7 @@ function collectSourceScans(ctx, options, cache, mtimeOf, files) {
3080
3163
  merge(entry.scan);
3081
3164
  continue;
3082
3165
  }
3083
- const scan = scanSnapshot(ctx, readSnapshot(ctx, filePath), options, allPatterns);
3166
+ const scan = scanSnapshot(ctx, readSnapshot(ctx, filePath), options, allPatterns, cache.resolvedTokenReferences.get(filePath));
3084
3167
  cache.entries.set(filePath, {
3085
3168
  mtime,
3086
3169
  scan
@@ -3093,6 +3176,7 @@ function collectSourceScans(ctx, options, cache, mtimeOf, files) {
3093
3176
  }
3094
3177
  if (cache && seen) {
3095
3178
  for (const filePath of cache.entries.keys()) if (!seen.has(filePath)) cache.entries.delete(filePath);
3179
+ for (const filePath of cache.resolvedTokenReferences.keys()) if (!seen.has(filePath)) cache.resolvedTokenReferences.delete(filePath);
3096
3180
  }
3097
3181
  return result;
3098
3182
  }
@@ -3113,7 +3197,10 @@ function pruneTokensForBuild(ctx, sheet, results, sourceScans) {
3113
3197
  const vars = new Set(scans.cssVars);
3114
3198
  const accounting = scans.accounting;
3115
3199
  const reachable = scans.reachableFromJs;
3116
- for (const result of results) for (const item of result.token) for (const value of item.data ?? []) if (typeof value === "string") paths.add(value);
3200
+ for (const result of results) {
3201
+ if (result.filePath) reconcileAccounting(accounting, resolvedTokenReferences(result), ctx.runtime.path.abs(ctx.config.cwd, result.filePath));
3202
+ for (const item of result.token) for (const value of item.data ?? []) if (typeof value === "string") paths.add(value);
3203
+ }
3117
3204
  for (const name of tokenVarsFor(ctx, paths)) vars.add(name);
3118
3205
  const declared = declaredKeeps(ctx);
3119
3206
  for (const name of tokenVarsFor(ctx, declared)) vars.add(name);
@@ -3245,7 +3332,7 @@ function collectRenderedElements(ctx) {
3245
3332
  * Vite, `bamboo cssgen`, and the CLI `bamboo` command all finish here so a recipe lowered to
3246
3333
  * atoms cannot have a different sheet depending on which integration asked for it.
3247
3334
  */
3248
- const assembleExtractedSheet = (ctx, { layerParams = false, sourceScanCache, mtimeOf, sourceInventory } = {}) => {
3335
+ const assembleExtractedSheet = (ctx, { layerParams = false, sourceScanCache, mtimeOf, sourceInventory, parserResults = [] } = {}) => {
3249
3336
  ctx.encoder.atomizeObservedRecipes();
3250
3337
  const sheet = ctx.createSheet();
3251
3338
  if (layerParams) {
@@ -3260,7 +3347,7 @@ const assembleExtractedSheet = (ctx, { layerParams = false, sourceScanCache, mti
3260
3347
  keyframeNames: declaredKeyframes,
3261
3348
  elements: collectElements
3262
3349
  }, sourceScanCache, mtimeOf, sourceInventory) : void 0;
3263
- const reachableVars = pruneTokensForBuild(ctx, sheet, [], scans);
3350
+ const reachableVars = pruneTokensForBuild(ctx, sheet, parserResults, scans);
3264
3351
  if (collectElements && scans) ctx.prunePreflight(sheet, scans.elements);
3265
3352
  if (pruneKeyframes && scans) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3266
3353
  return sheet;
@@ -3511,6 +3598,7 @@ var Builder = class {
3511
3598
  this.resolutionConfigurationSets.clear();
3512
3599
  this.resolutionConfigurationBytes.clear();
3513
3600
  this.sourceScanCache.entries.clear();
3601
+ this.sourceScanCache.resolvedTokenReferences.clear();
3514
3602
  this.extractionReadsByOwner.clear();
3515
3603
  this.recipeSurfaceByOwner.clear();
3516
3604
  this.capturedLedger = void 0;
@@ -3721,7 +3809,7 @@ var Builder = class {
3721
3809
  const recipes = [];
3722
3810
  for (const set of [parserResult?.cva, parserResult?.sva]) for (const item of set ?? []) recipes.push([item.name ?? "", item.data]);
3723
3811
  const sourceFile = ctx.project?.getSourceFile?.(file);
3724
- const exports = sourceFile ? sourceFile.getExportDeclarations().map((declaration) => declaration.getText()) : [];
3812
+ const exports = sourceFile ? (0, _bamboocss_ts_ast.getExportDeclarations)(sourceFile).map((declaration) => declaration.getText()) : [];
3725
3813
  const json = JSON.stringify([recipes, exports], (_key, value) => value === void 0 ? "bamboo:undefined" : value);
3726
3814
  if (json === void 0) return void 0;
3727
3815
  return (0, node_crypto.createHash)("sha256").update(json).digest("base64");
@@ -3791,6 +3879,7 @@ var Builder = class {
3791
3879
  const previousCandidates = this.resolutionCandidateSets.get(owner) ?? [];
3792
3880
  const previousConfigurations = this.resolutionConfigurationSets.get(owner) ?? [];
3793
3881
  const parserResult = ctx.parseFile(file);
3882
+ recordResolvedTokenReferences(this.sourceScanCache, this.absOwner(ctx, file), parserResult);
3794
3883
  fileModifiedMap.set(file, meta.mtime);
3795
3884
  {
3796
3885
  const owner = this.absOwner(ctx, file);
@@ -3963,9 +4052,12 @@ const cssgen = async (ctx, options) => {
3963
4052
  } else await ctx.writeCss(sheet);
3964
4053
  done();
3965
4054
  } else {
3966
- const { files } = ctx.parseFiles();
4055
+ const { files, results } = ctx.parseFiles();
3967
4056
  const done = _bamboocss_logger.logger.time.info(ctx.messages.buildComplete(files.length));
3968
- const sheet = assembleExtractedSheet(ctx, { layerParams: true });
4057
+ const sheet = assembleExtractedSheet(ctx, {
4058
+ layerParams: true,
4059
+ parserResults: results
4060
+ });
3969
4061
  if (splitting) await ctx.writeSplitCss(sheet);
3970
4062
  else if (outfile) {
3971
4063
  const css = ctx.getCss(sheet);
@@ -4026,12 +4118,22 @@ async function debug(ctx, options) {
4026
4118
  }
4027
4119
  //#endregion
4028
4120
  //#region src/generate.ts
4029
- async function build(ctx, artifactIds) {
4121
+ async function build(ctx, sourceScanCache, artifactIds) {
4030
4122
  await codegen(ctx, artifactIds);
4031
4123
  if (ctx.config.emitTokensOnly) return _bamboocss_logger.logger.info("css:emit", "Successfully rebuilt the css variables and js function to query your tokens ✨");
4032
4124
  const done = _bamboocss_logger.logger.time.info("");
4033
4125
  const parsed = ctx.parseFiles();
4034
- const sheet = assembleExtractedSheet(ctx, { layerParams: true });
4126
+ if (sourceScanCache) {
4127
+ for (const result of parsed.results) if (result.filePath) recordResolvedTokenReferences(sourceScanCache, ctx.runtime.path.abs(ctx.config.cwd, result.filePath), result);
4128
+ }
4129
+ const sheet = assembleExtractedSheet(ctx, sourceScanCache ? {
4130
+ layerParams: true,
4131
+ sourceScanCache,
4132
+ sourceInventory: parsed.files
4133
+ } : {
4134
+ layerParams: true,
4135
+ parserResults: parsed.results
4136
+ });
4035
4137
  await ctx.writeCss(sheet);
4036
4138
  done(ctx.messages.buildComplete(parsed.files.length));
4037
4139
  }
@@ -4040,19 +4142,22 @@ async function generate(config, configPath) {
4040
4142
  config,
4041
4143
  configPath
4042
4144
  });
4043
- await build(ctx);
4145
+ const sourceScanCache = createSourceScanCache();
4044
4146
  const { cwd, watch, poll } = ctx.config;
4147
+ await build(ctx, watch ? sourceScanCache : void 0);
4045
4148
  if (watch) {
4046
4149
  ctx.watchConfig(async () => {
4047
4150
  const affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
4048
4151
  ctx = new BambooContext(conf);
4049
4152
  });
4153
+ sourceScanCache.entries.clear();
4154
+ sourceScanCache.resolvedTokenReferences.clear();
4050
4155
  _bamboocss_logger.logger.info("ctx:updated", "config rebuilt ✅");
4051
4156
  await ctx.hooks["config:change"]?.({
4052
4157
  config: ctx.config,
4053
4158
  changes: affecteds
4054
4159
  });
4055
- return build(ctx, Array.from(affecteds.artifacts));
4160
+ return build(ctx, sourceScanCache, Array.from(affecteds.artifacts));
4056
4161
  }, {
4057
4162
  cwd,
4058
4163
  poll
@@ -4065,14 +4170,21 @@ async function generate(config, configPath) {
4065
4170
  * per file. Writing per file would run the optimize pipeline and hit the disk
4066
4171
  * once per importer for a single keystroke.
4067
4172
  */
4068
- const bundleStyles = async (ctx, changedFilePaths) => {
4173
+ const bundleStyles = async (ctx, changedFilePaths, inventoryChanged = false) => {
4069
4174
  let parsed = 0;
4070
4175
  const encoder = ctx.parserOptions.encoder;
4071
- for (const filePath of changedFilePaths) if (encoder.withOwner("extract", filePath, () => ctx.project.parseSourceFile(filePath, encoder))) parsed++;
4072
- if (parsed === 0) return;
4176
+ for (const filePath of changedFilePaths) {
4177
+ const result = encoder.withOwner("extract", filePath, () => ctx.project.parseSourceFile(filePath, encoder));
4178
+ recordResolvedTokenReferences(sourceScanCache, filePath, result);
4179
+ if (result) parsed++;
4180
+ }
4181
+ if (parsed === 0 && !inventoryChanged) return;
4073
4182
  const outfile = ctx.runtime.path.join(...ctx.paths.root, "styles.css");
4074
4183
  const done = _bamboocss_logger.logger.time.info(ctx.messages.buildComplete(parsed));
4075
- const sheet = assembleExtractedSheet(ctx, { layerParams: true });
4184
+ const sheet = assembleExtractedSheet(ctx, {
4185
+ layerParams: true,
4186
+ sourceScanCache
4187
+ });
4076
4188
  const css = ctx.getCss(sheet);
4077
4189
  await ctx.runtime.fs.writeFile(outfile, css);
4078
4190
  done();
@@ -4082,7 +4194,9 @@ async function generate(config, configPath) {
4082
4194
  if (event === "unlink") {
4083
4195
  const dependents = ctx.project.getDependents(filePath);
4084
4196
  ctx.project.removeSourceFile(filePath);
4085
- await bundleStyles(ctx, dependents);
4197
+ sourceScanCache.entries.delete(filePath);
4198
+ sourceScanCache.resolvedTokenReferences.delete(filePath);
4199
+ await bundleStyles(ctx, dependents, true);
4086
4200
  } else if (event === "change") {
4087
4201
  ctx.project.reloadSourceFile(filePath);
4088
4202
  await bundleStyles(ctx, [filePath, ...ctx.project.getDependents(filePath)]);