@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.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { isStaticCompilerActive, markStaticCompilerActive } from "./static-compiler.mjs";
2
- import { Reporter, formatRecipeReport, formatTokenReport } from "@bamboocss/reporter";
3
2
  import { colors, logger, quote } from "@bamboocss/logger";
3
+ import { Node, SyntaxKind, childOf, forEachDescendant, getAliasNode, getDefaultImport, getDescendantsOfKind, getExportDeclarations, getFirstAncestor, getFirstAncestorByKind, getLineAndColumnAtPos, getLiteralText, getModuleSpecifierValue, getNamedImports, getNamespaceImport, isTypeOnly, nameNodeOf, stringLiteralValue, ts } from "@bamboocss/ts-ast";
4
4
  import { convertTsPathsToRegexes, diffConfigs, findConfig, loadConfig, mergeHooks } from "@bamboocss/config";
5
5
  import { BambooError, cssVarRefs, groupBy, truncateList, uniq } from "@bamboocss/shared";
6
6
  import { createHash } from "node:crypto";
@@ -18,7 +18,6 @@ import os from "node:os";
18
18
  import tty from "node:tty";
19
19
  import fs, { promises } from "node:fs";
20
20
  import path from "node:path";
21
- import { Node, SyntaxKind, ts } from "ts-morph";
22
21
  import chokidar from "chokidar";
23
22
  import glob from "fast-glob";
24
23
  import fsExtra from "fs-extra";
@@ -52,7 +51,14 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
52
51
  }) : target, mod));
53
52
  //#endregion
54
53
  //#region src/analyze.ts
55
- function analyze(ctx, options = {}) {
54
+ /**
55
+ * `analyze` is one CLI command, but this module is reachable from `@bamboocss/node`'s index,
56
+ * so a static import made every consumer of that index — the CLI on any command, and the Vite
57
+ * plugin on every build — load the reporter and its table formatters to run neither. Loading
58
+ * it here keeps that off the path of everything that is not the `analyze` command.
59
+ */
60
+ async function analyze(ctx, options = {}) {
61
+ const { Reporter, formatRecipeReport, formatTokenReport } = await import("@bamboocss/reporter");
56
62
  const reporter = new Reporter(ctx, {
57
63
  project: ctx.project,
58
64
  getRelativePath: ctx.runtime.path.relative,
@@ -1653,7 +1659,7 @@ const collectReferenceGraph = async (rootPath, rootParsed, parseTsconfig, cache)
1653
1659
  visited.add(referencedPath);
1654
1660
  try {
1655
1661
  const source = await promises.readFile(referencedPath, "utf8");
1656
- if (ts.parseConfigFileTextToJson(referencedPath, source).error) throw new Error("Invalid tsconfig");
1662
+ JSON.parse(source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"));
1657
1663
  queue.push({
1658
1664
  parsed: parseTsconfig(referencedPath, cache),
1659
1665
  path: referencedPath
@@ -1808,6 +1814,21 @@ function globDirname(globs) {
1808
1814
  * mutated.
1809
1815
  */
1810
1816
  const globIgnore = (exclude) => ["**/*.d.ts", ...exclude ?? []];
1817
+ /**
1818
+ * The order the source glob returns files in, made a decision rather than an accident.
1819
+ *
1820
+ * `fast-glob` hands back whatever `readdir` gave it, which is the filesystem's order and is not
1821
+ * the same on every machine. That order is not cosmetic: it is the order atoms enter the sheet,
1822
+ * and sheet order is what decides a conflict between two classes on one element — `cx` joins
1823
+ * them and the browser picks by position, not by the order they were passed. So an unsorted
1824
+ * glob lets two checkouts of the same commit build stylesheets that resolve the same conflict
1825
+ * differently, and makes the emitted bytes irreproducible, which is also what content-hashed
1826
+ * asset caching is keyed on.
1827
+ *
1828
+ * Sorted by code unit rather than `localeCompare`, whose answer depends on the host's locale —
1829
+ * the exact class of machine-dependence this exists to remove.
1830
+ */
1831
+ const sortSources = (files) => files.sort();
1811
1832
  const nodeRuntime = {
1812
1833
  cwd() {
1813
1834
  return process.cwd();
@@ -1834,11 +1855,11 @@ const nodeRuntime = {
1834
1855
  },
1835
1856
  glob(opts) {
1836
1857
  if (!opts.include) return [];
1837
- return glob.sync(opts.include, {
1858
+ return sortSources(glob.sync(opts.include, {
1838
1859
  cwd: opts.cwd,
1839
1860
  ignore: globIgnore(opts.exclude),
1840
1861
  absolute: true
1841
- });
1862
+ }));
1842
1863
  },
1843
1864
  writeFile: fsExtra.writeFile,
1844
1865
  writeFileSync: fsExtra.writeFileSync,
@@ -1983,10 +2004,36 @@ var OutputEngine = class {
1983
2004
  const absPath = this.path.join(...dir, file);
1984
2005
  logger.debug("write:file", dir.slice(-1).concat(file).join("/"));
1985
2006
  if (file === "package.json") return this.writePackageJson(absPath, code);
2007
+ if (this.isUnchanged(absPath, code)) {
2008
+ logger.debug("write:unchanged", dir.slice(-1).concat(file).join("/"));
2009
+ return;
2010
+ }
1986
2011
  return this.fs.writeFile(absPath, code);
1987
2012
  }));
1988
2013
  };
1989
2014
  /**
2015
+ * Whether the file on disk already holds exactly what codegen would write.
2016
+ *
2017
+ * Not for the write itself, which is cheap — 54 artifacts and 1.4 MB measure ~6ms, against
2018
+ * ~1.3ms to read them back and compare. It is for the mtime. Codegen rewrote every artifact
2019
+ * on every build whether or not a byte moved, and most builds move nothing: `csstype.d.ts` is
2020
+ * copied verbatim from a constant and accounts for 895 kB on its own. Everything downstream
2021
+ * watches those files — the dev server's module graph, `tsc --incremental`, any bundler with
2022
+ * the output directory in scope — and each of them re-does work for a file that is identical
2023
+ * to the one it already read.
2024
+ *
2025
+ * A read that throws is an answer, not a failure: the file is unreadable or absent, so it has
2026
+ * to be written.
2027
+ */
2028
+ isUnchanged = (absPath, code) => {
2029
+ if (!this.fs.existsSync(absPath)) return false;
2030
+ try {
2031
+ return this.fs.readFileSync(absPath) === code;
2032
+ } catch {
2033
+ return false;
2034
+ }
2035
+ };
2036
+ /**
1990
2037
  * Unlike the rest of the output, `package.json` is not exclusively ours: `emit-pkg`
1991
2038
  * writes entrypoints to the same path, and consumers hand-edit it. Overwriting would
1992
2039
  * drop that, so only keys that are absent get filled in — anything already declared,
@@ -2070,6 +2117,9 @@ var BambooContext = class extends Generator {
2070
2117
  config.cwd ||= this.runtime.cwd();
2071
2118
  if (config.logLevel) logger.level = config.logLevel;
2072
2119
  this.project = new Project({
2120
+ cwd: config.cwd ?? this.runtime.cwd(),
2121
+ tsConfigFilePath: conf.tsconfigFile ?? `${config.cwd ?? this.runtime.cwd()}/tsconfig.json`,
2122
+ fs: { readFile: (filePath) => this.runtime.fs.readFileSync(filePath) },
2073
2123
  ...conf.tsconfig,
2074
2124
  deferInitialSourceFiles: true,
2075
2125
  resolutionConfigFiles: getTsConfigResolutionFiles(conf),
@@ -2254,9 +2304,10 @@ var BambooContext = class extends Generator {
2254
2304
  const results = [];
2255
2305
  files.forEach((file) => {
2256
2306
  const result = this.parseFile(file, encoder);
2257
- if (!result || result.isEmpty() || encoder.isEmpty()) return;
2258
- filesWithCss.push(file);
2307
+ if (!result || result.isEmpty()) return;
2259
2308
  results.push(result);
2309
+ if (encoder.isEmpty()) return;
2310
+ filesWithCss.push(file);
2260
2311
  });
2261
2312
  this.assertExtracted(files);
2262
2313
  this.assertNoDeadCalls(files);
@@ -2510,7 +2561,7 @@ function accountSnapshot(ctx, snapshot, accounting) {
2510
2561
  });
2511
2562
  return;
2512
2563
  }
2513
- if (parseErrorCount(sourceFile)) {
2564
+ if (ctx.project.getSyntacticDiagnosticCount(filePath)) {
2514
2565
  if (!mentionsToken(ctx, parsed)) return;
2515
2566
  declined.push({
2516
2567
  filePath,
@@ -2552,15 +2603,6 @@ const mentionsToken = (ctx, text) => {
2552
2603
  if (ctx.imports.value.tokens.some((mod) => text.includes(mod))) return true;
2553
2604
  return IMPORTING_CALL.test(text);
2554
2605
  };
2555
- /**
2556
- * How many syntax errors the parse produced.
2557
- *
2558
- * `parseDiagnostics` is TypeScript-internal and absent from the public `SourceFile` type, so
2559
- * it is reached through a cast. The alternative, `getPreEmitDiagnostics`, runs the type checker
2560
- * over the whole program — orders of magnitude more work for a question about syntax, and it
2561
- * would report type errors this pass has no business declining over.
2562
- */
2563
- const parseErrorCount = (sourceFile) => sourceFile.compilerNode.parseDiagnostics?.length ?? 0;
2564
2606
  /** Whether a module specifier resolves to the generated tokens artifact. */
2565
2607
  const isTokensEntrypoint = (ctx, specifier) => {
2566
2608
  const mods = ctx.imports.value.tokens;
@@ -2571,68 +2613,70 @@ const isTokensEntrypoint = (ctx, specifier) => {
2571
2613
  if (!resolved) return false;
2572
2614
  return mods.some((mod) => resolved.includes(mod) || resolved === mod);
2573
2615
  };
2574
- const lineOf = (node) => node.getSourceFile().getLineAndColumnAtPos(node.getStart()).line;
2616
+ const lineOf = (node) => getLineAndColumnAtPos(node.getSourceFile(), node.getStart()).line;
2575
2617
  function accountFile(ctx, sourceFile, filePath, paths, prefixes, declined) {
2576
2618
  const decline = (node, reason) => declined.push({
2577
2619
  filePath,
2578
2620
  line: lineOf(node),
2579
- reason
2621
+ reason,
2622
+ start: node.getStart(),
2623
+ end: node.getEnd()
2580
2624
  });
2581
2625
  /** Local names bound to the artifact: the `token` export, and any namespace of it. */
2582
2626
  const bindings = /* @__PURE__ */ new Set();
2583
- for (const statement of sourceFile.getStatements()) {
2627
+ for (const statement of sourceFile.statements) {
2584
2628
  if (Node.isExportDeclaration(statement)) {
2585
- const specifier = statement.getModuleSpecifierValue();
2629
+ const specifier = getModuleSpecifierValue(statement);
2586
2630
  if (specifier && isTokensEntrypoint(ctx, specifier)) decline(statement, "re-exported");
2587
2631
  continue;
2588
2632
  }
2589
2633
  if (!Node.isImportDeclaration(statement)) continue;
2590
- const specifier = statement.getModuleSpecifierValue();
2634
+ const specifier = getModuleSpecifierValue(statement);
2591
2635
  if (!specifier) continue;
2592
- const clause = statement.getImportClause();
2593
- if (!clause || statement.isTypeOnly()) continue;
2636
+ const clause = statement.importClause;
2637
+ if (!clause || isTypeOnly(statement)) continue;
2594
2638
  if (!isTokensEntrypoint(ctx, specifier)) {
2595
- for (const named of clause.getNamedImports()) if (!named.isTypeOnly() && nameOf(named.getNameNode()) === "token") decline(named, "unclassified-import");
2596
- const foreignDefault = clause.getDefaultImport();
2639
+ for (const named of getNamedImports(clause)) if (!isTypeOnly(named) && nameOf(nameNodeOf(named)) === "token") decline(named, "unclassified-import");
2640
+ const foreignDefault = getDefaultImport(clause);
2597
2641
  if (foreignDefault && nameOf(foreignDefault) === "token") decline(foreignDefault, "unclassified-import");
2598
- const foreignNamespace = clause.getNamespaceImport();
2642
+ const foreignNamespace = getNamespaceImport(clause);
2599
2643
  if (foreignNamespace && usesTokenMember(sourceFile, foreignNamespace.getText())) decline(foreignNamespace, "unclassified-import");
2600
2644
  continue;
2601
2645
  }
2602
- const defaultImport = clause.getDefaultImport();
2646
+ const defaultImport = getDefaultImport(clause);
2603
2647
  if (defaultImport) decline(defaultImport, "unsupported-import");
2604
- const namespace = clause.getNamespaceImport();
2648
+ const namespace = getNamespaceImport(clause);
2605
2649
  if (namespace) bindings.add(namespace.getText());
2606
- for (const named of clause.getNamedImports()) {
2607
- if (named.isTypeOnly()) continue;
2608
- if (nameOf(named.getNameNode()) !== "token") {
2609
- if (usedAsValue(sourceFile, (named.getAliasNode() ?? named.getNameNode()).getText(), named)) decline(named, "unsupported-import");
2650
+ for (const named of getNamedImports(clause)) {
2651
+ if (isTypeOnly(named)) continue;
2652
+ if (nameOf(nameNodeOf(named)) !== "token") {
2653
+ if (usedAsValue(sourceFile, (getAliasNode(named) ?? nameNodeOf(named))?.getText() ?? "", named)) decline(named, "unsupported-import");
2610
2654
  continue;
2611
2655
  }
2612
- bindings.add((named.getAliasNode() ?? named.getNameNode()).getText());
2656
+ bindings.add((getAliasNode(named) ?? nameNodeOf(named))?.getText() ?? "");
2613
2657
  }
2614
2658
  }
2615
- for (const importEquals of sourceFile.getDescendantsOfKind(SyntaxKind.ImportEqualsDeclaration)) if (importEquals.getText().includes("token")) decline(importEquals, "import-equals");
2616
- for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
2617
- const callee = call.getExpression();
2618
- const isRequire = Node.isIdentifier(callee) && callee.getText() === "require";
2619
- const isDynamicImport = callee.getKind() === SyntaxKind.ImportKeyword;
2659
+ for (const importEquals of getDescendantsOfKind(sourceFile, SyntaxKind.ImportEqualsDeclaration)) if (importEquals.getText().includes("token")) decline(importEquals, "import-equals");
2660
+ for (const call of getDescendantsOfKind(sourceFile, SyntaxKind.CallExpression)) {
2661
+ const callee = childOf(call, "expression");
2662
+ const isRequire = callee !== void 0 && Node.isIdentifier(callee) && callee.getText() === "require";
2663
+ const isDynamicImport = callee?.kind === SyntaxKind.ImportKeyword;
2620
2664
  if (!isRequire && !isDynamicImport) continue;
2621
- const argument = call.getArguments()[0];
2665
+ const argument = childOf(call, "arguments")?.[0];
2622
2666
  if (!argument) continue;
2623
- if (Node.isStringLiteral(argument) ? isTokensEntrypoint(ctx, argument.getLiteralValue()) : true) decline(call, isRequire ? "require" : "dynamic-import");
2667
+ if (Node.isStringLiteral(argument) ? isTokensEntrypoint(ctx, stringLiteralValue(argument)) : true) decline(call, isRequire ? "require" : "dynamic-import");
2624
2668
  }
2625
2669
  const shadows = shadowedScopes(sourceFile);
2626
2670
  for (const identifier of identifiersNamed(sourceFile, (name) => bindings.has(name) || name === "token")) {
2627
2671
  const text = nameOf(identifier);
2628
- const parent = identifier.getParent();
2672
+ const parent = identifier.parent;
2629
2673
  if (Node.isExportSpecifier(parent)) {
2630
- const declaration = parent.getFirstAncestorByKind(SyntaxKind.ExportDeclaration);
2631
- if (declaration && !declaration.getModuleSpecifier()) decline(identifier, "re-exported");
2674
+ const declaration = getFirstAncestorByKind(parent, SyntaxKind.ExportDeclaration);
2675
+ if (declaration && !childOf(declaration, "moduleSpecifier")) decline(identifier, "re-exported");
2632
2676
  continue;
2633
2677
  }
2634
- if (Node.isPropertyAccessExpression(parent) && parent.getNameNode() === identifier) {
2635
- const object = parent.getExpression();
2678
+ if (Node.isPropertyAccessExpression(parent) && parent.name === identifier) {
2679
+ const object = parent.expression;
2636
2680
  const objectName = Node.isIdentifier(object) ? object.getText() : void 0;
2637
2681
  if (objectName && bindings.has(objectName)) continue;
2638
2682
  decline(identifier, "unresolved-reference");
@@ -2660,11 +2704,11 @@ function accountFile(ctx, sourceFile, filePath, paths, prefixes, declined) {
2660
2704
  * property-access-only scan.
2661
2705
  */
2662
2706
  function usesTokenMember(sourceFile, namespace) {
2663
- if (sourceFile.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).some((access) => access.getExpression().getText() === namespace && nameOf(access.getNameNode()) === "token")) return true;
2664
- return sourceFile.getDescendantsOfKind(SyntaxKind.ElementAccessExpression).some((access) => {
2665
- if (access.getExpression().getText() !== namespace) return false;
2666
- const argument = access.getArgumentExpression();
2667
- return argument != null && (!Node.isStringLiteral(argument) || argument.getLiteralValue() === "token");
2707
+ if (getDescendantsOfKind(sourceFile, SyntaxKind.PropertyAccessExpression).some((access) => childOf(access, "expression")?.getText() === namespace && nameOf(nameNodeOf(access)) === "token")) return true;
2708
+ return getDescendantsOfKind(sourceFile, SyntaxKind.ElementAccessExpression).some((access) => {
2709
+ if (childOf(access, "expression")?.getText() !== namespace) return false;
2710
+ const argument = childOf(access, "argumentExpression");
2711
+ return argument != null && (!Node.isStringLiteral(argument) || stringLiteralValue(argument) === "token");
2668
2712
  });
2669
2713
  }
2670
2714
  /**
@@ -2690,14 +2734,13 @@ function usesTokenMember(sourceFile, namespace) {
2690
2734
  function* identifiersNamed(sourceFile, wanted) {
2691
2735
  const found = [];
2692
2736
  const collect = (node) => {
2693
- if (node.kind === SyntaxKind.Identifier && wanted(String(node.escapedText))) found.push(node);
2737
+ if (node.kind === SyntaxKind.Identifier && wanted(String(node.text))) found.push(node);
2694
2738
  const jsDoc = node.jsDoc;
2695
2739
  if (jsDoc) for (const doc of jsDoc) collect(doc);
2696
2740
  ts.forEachChild(node, collect);
2697
2741
  };
2698
- collect(sourceFile.compilerNode);
2699
- const wrap = sourceFile;
2700
- for (const node of found) yield wrap._getNodeFromCompilerNode(node);
2742
+ collect(sourceFile);
2743
+ for (const node of found) yield node;
2701
2744
  }
2702
2745
  /**
2703
2746
  * An identifier's name as the compiler resolves it, not as it is spelled.
@@ -2705,7 +2748,7 @@ function* identifiersNamed(sourceFile, wanted) {
2705
2748
  * `token` is the identifier `token`; reading `getText()` returns the escape and compares
2706
2749
  * unequal, which let an import of the artifact's export past the checks that key on the name.
2707
2750
  */
2708
- const nameOf = (node) => Node.isIdentifier(node) ? String(node.compilerNode.escapedText) : node.getText();
2751
+ const nameOf = (node) => Node.isIdentifier(node) ? String(node.text) : node.getText();
2709
2752
  /** Every name a binding name binds, following object and array destructuring. */
2710
2753
  function boundNames(name, bound) {
2711
2754
  if (!name) return;
@@ -2714,7 +2757,7 @@ function boundNames(name, bound) {
2714
2757
  return;
2715
2758
  }
2716
2759
  if (!Node.isObjectBindingPattern(name) && !Node.isArrayBindingPattern(name)) return;
2717
- for (const element of name.getElements()) if (Node.isBindingElement(element)) boundNames(element.getNameNode(), bound);
2760
+ for (const element of name.elements) if (Node.isBindingElement(element)) boundNames(element.name, bound);
2718
2761
  }
2719
2762
  /**
2720
2763
  * Scopes that bind a name to something which cannot be the artifact, keyed by that name.
@@ -2750,23 +2793,23 @@ function shadowedScopes(sourceFile) {
2750
2793
  else scopes.set(name, [scope]);
2751
2794
  };
2752
2795
  const variables = [];
2753
- sourceFile.forEachDescendant((node) => {
2796
+ forEachDescendant(sourceFile, (node) => {
2754
2797
  if (Node.isParameterDeclaration(node)) {
2755
- const scope = node.getParent();
2756
- boundNames(node.getNameNode(), (name) => add(name, scope));
2798
+ const scope = node.parent;
2799
+ boundNames(node.name, (name) => add(name, scope));
2757
2800
  return;
2758
2801
  }
2759
2802
  if (Node.isCatchClause(node)) {
2760
- boundNames(node.getVariableDeclaration()?.getNameNode(), (name) => add(name, node));
2803
+ boundNames(node.variableDeclaration?.name, (name) => add(name, node));
2761
2804
  return;
2762
2805
  }
2763
2806
  if (Node.isFunctionDeclaration(node) || Node.isClassDeclaration(node)) {
2764
- const name = node.getNameNode();
2765
- if (name) add(nameOf(name), node.getParent());
2807
+ const name = node.name;
2808
+ if (name) add(nameOf(name), node.parent);
2766
2809
  return;
2767
2810
  }
2768
2811
  if (Node.isFunctionExpression(node) || Node.isClassExpression(node)) {
2769
- const name = node.getNameNode();
2812
+ const name = node.name;
2770
2813
  if (name) add(nameOf(name), node);
2771
2814
  return;
2772
2815
  }
@@ -2774,10 +2817,10 @@ function shadowedScopes(sourceFile) {
2774
2817
  });
2775
2818
  for (const declaration of variables) {
2776
2819
  if (!Node.isVariableDeclaration(declaration)) continue;
2777
- const root = rootIdentifier(declaration.getInitializer());
2820
+ const root = rootIdentifier(declaration.initializer);
2778
2821
  if (!root || !isShadowed(root, scopes.get(nameOf(root)))) continue;
2779
- const scope = declaration.getFirstAncestor((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));
2780
- boundNames(declaration.getNameNode(), (name) => add(name, scope));
2822
+ 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));
2823
+ boundNames(declaration.name, (name) => add(name, scope));
2781
2824
  }
2782
2825
  return scopes;
2783
2826
  }
@@ -2789,7 +2832,7 @@ function shadowedScopes(sourceFile) {
2789
2832
  */
2790
2833
  function rootIdentifier(expression) {
2791
2834
  let current = expression;
2792
- while (current && (Node.isPropertyAccessExpression(current) || Node.isElementAccessExpression(current))) current = current.getExpression();
2835
+ while (current && (Node.isPropertyAccessExpression(current) || Node.isElementAccessExpression(current))) current = current.expression;
2793
2836
  return current && Node.isIdentifier(current) ? current : void 0;
2794
2837
  }
2795
2838
  /**
@@ -2804,7 +2847,7 @@ function rootIdentifier(expression) {
2804
2847
  * the binding, so it is a reference like any other.
2805
2848
  */
2806
2849
  function isDeclarationName(identifier, parent) {
2807
- if (Node.isPropertyAssignment(parent) || Node.isPropertySignature(parent) || Node.isMethodSignature(parent) || Node.isPropertyDeclaration(parent) || Node.isMethodDeclaration(parent) || Node.isEnumMember(parent)) return parent.getNameNode() === identifier;
2850
+ if (Node.isPropertyAssignment(parent) || Node.isPropertySignatureDeclaration(parent) || Node.isMethodSignatureDeclaration(parent) || Node.isPropertyDeclaration(parent) || Node.isMethodDeclaration(parent) || Node.isEnumMember(parent)) return nameNodeOf(parent) === identifier;
2808
2851
  return false;
2809
2852
  }
2810
2853
  /**
@@ -2828,20 +2871,20 @@ function isShadowed(identifier, scopes) {
2828
2871
  * (`useMemo(() => token)`), spread, or enumerated.
2829
2872
  */
2830
2873
  function accountedPath(identifier) {
2831
- const parent = identifier.getParent();
2874
+ const parent = identifier.parent;
2832
2875
  if (!parent) return void 0;
2833
2876
  if (Node.isImportSpecifier(parent) || Node.isNamespaceImport(parent) || Node.isImportClause(parent) || Node.isExportSpecifier(parent)) return { kind: "binding" };
2834
- if (Node.isCallExpression(parent) && parent.getExpression() === identifier) return literalPath(parent);
2835
- if (!Node.isPropertyAccessExpression(parent) || parent.getExpression() !== identifier) return void 0;
2836
- const property = parent.getNameNode().getText();
2837
- const grandParent = parent.getParent();
2838
- if (property === "value") return Node.isCallExpression(grandParent) && grandParent.getExpression() === parent ? literalPath(grandParent) : void 0;
2877
+ if (Node.isCallExpression(parent) && parent.expression === identifier) return literalPath(parent);
2878
+ if (!Node.isPropertyAccessExpression(parent) || parent.expression !== identifier) return void 0;
2879
+ const property = parent.name.getText();
2880
+ const grandParent = parent.parent;
2881
+ if (property === "value") return Node.isCallExpression(grandParent) && grandParent.expression === parent ? literalPath(grandParent) : void 0;
2839
2882
  if (property !== "token") return void 0;
2840
- if (Node.isCallExpression(grandParent) && grandParent.getExpression() === parent) return literalPath(grandParent);
2841
- if (Node.isPropertyAccessExpression(grandParent) && grandParent.getExpression() === parent) {
2842
- if (grandParent.getNameNode().getText() !== "value") return void 0;
2843
- const call = grandParent.getParent();
2844
- return Node.isCallExpression(call) && call.getExpression() === grandParent ? literalPath(call) : void 0;
2883
+ if (Node.isCallExpression(grandParent) && grandParent.expression === parent) return literalPath(grandParent);
2884
+ if (Node.isPropertyAccessExpression(grandParent) && grandParent.expression === parent) {
2885
+ if (grandParent.name.getText() !== "value") return void 0;
2886
+ const call = grandParent.parent;
2887
+ return Node.isCallExpression(call) && call.expression === grandParent ? literalPath(call) : void 0;
2845
2888
  }
2846
2889
  }
2847
2890
  /**
@@ -2860,18 +2903,18 @@ function accountedPath(identifier) {
2860
2903
  */
2861
2904
  function literalPath(call) {
2862
2905
  if (!Node.isCallExpression(call)) return void 0;
2863
- const argument = unwrapAssertions(call.getArguments()[0]);
2906
+ const argument = unwrapAssertions(call.arguments[0]);
2864
2907
  if (!argument) return void 0;
2865
2908
  if (Node.isStringLiteral(argument)) return {
2866
2909
  kind: "path",
2867
- value: argument.getLiteralValue()
2910
+ value: stringLiteralValue(argument)
2868
2911
  };
2869
2912
  if (Node.isNoSubstitutionTemplateLiteral(argument)) return {
2870
2913
  kind: "path",
2871
- value: argument.getLiteralValue()
2914
+ value: stringLiteralValue(argument)
2872
2915
  };
2873
2916
  if (Node.isTemplateExpression(argument)) {
2874
- const head = argument.getHead().getLiteralText();
2917
+ const head = getLiteralText(argument.head);
2875
2918
  return head ? {
2876
2919
  kind: "prefix",
2877
2920
  value: head
@@ -2887,8 +2930,8 @@ function literalPath(call) {
2887
2930
  */
2888
2931
  function usedAsValue(sourceFile, name, declaration) {
2889
2932
  for (const identifier of identifiersNamed(sourceFile, (candidate) => candidate === name)) {
2890
- if (identifier.getFirstAncestor((ancestor) => ancestor === declaration)) continue;
2891
- if (!identifier.getFirstAncestor((ancestor) => Node.isTypeNode(ancestor))) return true;
2933
+ if (getFirstAncestor(identifier, (ancestor) => ancestor === declaration)) continue;
2934
+ if (!getFirstAncestor(identifier, (ancestor) => Node.isTypeNode(ancestor))) return true;
2892
2935
  }
2893
2936
  return false;
2894
2937
  }
@@ -2906,7 +2949,7 @@ function usedAsValue(sourceFile, name, declaration) {
2906
2949
  */
2907
2950
  function unwrapAssertions(node) {
2908
2951
  let current = node;
2909
- while (current && (Node.isAsExpression(current) || Node.isSatisfiesExpression(current) || Node.isNonNullExpression(current) || Node.isParenthesizedExpression(current) || Node.isTypeAssertion(current))) current = current.getExpression();
2952
+ while (current && (Node.isAsExpression(current) || Node.isSatisfiesExpression(current) || Node.isNonNullExpression(current) || Node.isParenthesizedExpression(current) || Node.isTypeAssertion(current))) current = current.expression;
2910
2953
  return current;
2911
2954
  }
2912
2955
  //#endregion
@@ -2977,10 +3020,49 @@ function* sourceTexts(ctx) {
2977
3020
  }
2978
3021
  const createSourceScanCache = () => ({
2979
3022
  signature: "",
2980
- entries: /* @__PURE__ */ new Map()
3023
+ entries: /* @__PURE__ */ new Map(),
3024
+ resolvedTokenReferences: /* @__PURE__ */ new Map()
2981
3025
  });
3026
+ const resolvedTokenReferences = (result) => {
3027
+ if (!result) return [];
3028
+ const facts = [];
3029
+ for (const item of result.token) {
3030
+ if (!item.tokenCalleeRange || !item.data?.length) continue;
3031
+ const paths = [];
3032
+ for (const value of item.data) {
3033
+ if (typeof value !== "string") break;
3034
+ paths.push(value);
3035
+ }
3036
+ if (paths.length !== item.data.length) continue;
3037
+ facts.push({
3038
+ ...item.tokenCalleeRange,
3039
+ paths: [...new Set(paths)].sort()
3040
+ });
3041
+ }
3042
+ return facts.sort((left, right) => left.start - right.start || left.end - right.end);
3043
+ };
3044
+ 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]));
3045
+ /**
3046
+ * Reconcile one file's lightweight token facts after extraction.
3047
+ *
3048
+ * Deleting the source scan only when the semantic facts moved is important for dependents:
3049
+ * changing an imported constant can change `token(KEY)` without changing the consumer's mtime.
3050
+ */
3051
+ const recordResolvedTokenReferences = (cache, filePath, result) => {
3052
+ const next = resolvedTokenReferences(result);
3053
+ if (sameResolvedTokenReferences(cache.resolvedTokenReferences.get(filePath), next)) return;
3054
+ if (next.length) cache.resolvedTokenReferences.set(filePath, next);
3055
+ else cache.resolvedTokenReferences.delete(filePath);
3056
+ cache.entries.delete(filePath);
3057
+ };
3058
+ const reconcileAccounting = (accounting, references, filePath) => {
3059
+ if (!references?.length) return;
3060
+ const ranges = new Set(references.map(({ start, end }) => `${start}:${end}`));
3061
+ for (const reference of references) for (const path of reference.paths) accounting.paths.add(path);
3062
+ 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}`));
3063
+ };
2982
3064
  const OPEN_TAG = /<\s*([a-z][\w-]*)(?=[\s/>]|$)/g;
2983
- const scanSnapshot = (ctx, snapshot, options, patterns) => {
3065
+ const scanSnapshot = (ctx, snapshot, options, patterns, resolvedReferences) => {
2984
3066
  const tokenPaths = /* @__PURE__ */ new Set();
2985
3067
  const cssVars = /* @__PURE__ */ new Set();
2986
3068
  const elements = /* @__PURE__ */ new Set();
@@ -2999,6 +3081,7 @@ const scanSnapshot = (ctx, snapshot, options, patterns) => {
2999
3081
  declined: []
3000
3082
  };
3001
3083
  accountSnapshot(ctx, snapshot, accounting);
3084
+ reconcileAccounting(accounting, resolvedReferences);
3002
3085
  return {
3003
3086
  tokenPaths: [...tokenPaths],
3004
3087
  cssVars: [...cssVars],
@@ -3068,7 +3151,7 @@ function collectSourceScans(ctx, options, cache, mtimeOf, files) {
3068
3151
  merge(entry.scan);
3069
3152
  continue;
3070
3153
  }
3071
- const scan = scanSnapshot(ctx, readSnapshot(ctx, filePath), options, allPatterns);
3154
+ const scan = scanSnapshot(ctx, readSnapshot(ctx, filePath), options, allPatterns, cache.resolvedTokenReferences.get(filePath));
3072
3155
  cache.entries.set(filePath, {
3073
3156
  mtime,
3074
3157
  scan
@@ -3081,6 +3164,7 @@ function collectSourceScans(ctx, options, cache, mtimeOf, files) {
3081
3164
  }
3082
3165
  if (cache && seen) {
3083
3166
  for (const filePath of cache.entries.keys()) if (!seen.has(filePath)) cache.entries.delete(filePath);
3167
+ for (const filePath of cache.resolvedTokenReferences.keys()) if (!seen.has(filePath)) cache.resolvedTokenReferences.delete(filePath);
3084
3168
  }
3085
3169
  return result;
3086
3170
  }
@@ -3101,7 +3185,10 @@ function pruneTokensForBuild(ctx, sheet, results, sourceScans) {
3101
3185
  const vars = new Set(scans.cssVars);
3102
3186
  const accounting = scans.accounting;
3103
3187
  const reachable = scans.reachableFromJs;
3104
- for (const result of results) for (const item of result.token) for (const value of item.data ?? []) if (typeof value === "string") paths.add(value);
3188
+ for (const result of results) {
3189
+ if (result.filePath) reconcileAccounting(accounting, resolvedTokenReferences(result), ctx.runtime.path.abs(ctx.config.cwd, result.filePath));
3190
+ for (const item of result.token) for (const value of item.data ?? []) if (typeof value === "string") paths.add(value);
3191
+ }
3105
3192
  for (const name of tokenVarsFor(ctx, paths)) vars.add(name);
3106
3193
  const declared = declaredKeeps(ctx);
3107
3194
  for (const name of tokenVarsFor(ctx, declared)) vars.add(name);
@@ -3233,7 +3320,7 @@ function collectRenderedElements(ctx) {
3233
3320
  * Vite, `bamboo cssgen`, and the CLI `bamboo` command all finish here so a recipe lowered to
3234
3321
  * atoms cannot have a different sheet depending on which integration asked for it.
3235
3322
  */
3236
- const assembleExtractedSheet = (ctx, { layerParams = false, sourceScanCache, mtimeOf, sourceInventory } = {}) => {
3323
+ const assembleExtractedSheet = (ctx, { layerParams = false, sourceScanCache, mtimeOf, sourceInventory, parserResults = [] } = {}) => {
3237
3324
  ctx.encoder.atomizeObservedRecipes();
3238
3325
  const sheet = ctx.createSheet();
3239
3326
  if (layerParams) {
@@ -3248,7 +3335,7 @@ const assembleExtractedSheet = (ctx, { layerParams = false, sourceScanCache, mti
3248
3335
  keyframeNames: declaredKeyframes,
3249
3336
  elements: collectElements
3250
3337
  }, sourceScanCache, mtimeOf, sourceInventory) : void 0;
3251
- const reachableVars = pruneTokensForBuild(ctx, sheet, [], scans);
3338
+ const reachableVars = pruneTokensForBuild(ctx, sheet, parserResults, scans);
3252
3339
  if (collectElements && scans) ctx.prunePreflight(sheet, scans.elements);
3253
3340
  if (pruneKeyframes && scans) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3254
3341
  return sheet;
@@ -3499,6 +3586,7 @@ var Builder = class {
3499
3586
  this.resolutionConfigurationSets.clear();
3500
3587
  this.resolutionConfigurationBytes.clear();
3501
3588
  this.sourceScanCache.entries.clear();
3589
+ this.sourceScanCache.resolvedTokenReferences.clear();
3502
3590
  this.extractionReadsByOwner.clear();
3503
3591
  this.recipeSurfaceByOwner.clear();
3504
3592
  this.capturedLedger = void 0;
@@ -3709,7 +3797,7 @@ var Builder = class {
3709
3797
  const recipes = [];
3710
3798
  for (const set of [parserResult?.cva, parserResult?.sva]) for (const item of set ?? []) recipes.push([item.name ?? "", item.data]);
3711
3799
  const sourceFile = ctx.project?.getSourceFile?.(file);
3712
- const exports = sourceFile ? sourceFile.getExportDeclarations().map((declaration) => declaration.getText()) : [];
3800
+ const exports = sourceFile ? getExportDeclarations(sourceFile).map((declaration) => declaration.getText()) : [];
3713
3801
  const json = JSON.stringify([recipes, exports], (_key, value) => value === void 0 ? "bamboo:undefined" : value);
3714
3802
  if (json === void 0) return void 0;
3715
3803
  return createHash("sha256").update(json).digest("base64");
@@ -3779,6 +3867,7 @@ var Builder = class {
3779
3867
  const previousCandidates = this.resolutionCandidateSets.get(owner) ?? [];
3780
3868
  const previousConfigurations = this.resolutionConfigurationSets.get(owner) ?? [];
3781
3869
  const parserResult = ctx.parseFile(file);
3870
+ recordResolvedTokenReferences(this.sourceScanCache, this.absOwner(ctx, file), parserResult);
3782
3871
  fileModifiedMap.set(file, meta.mtime);
3783
3872
  {
3784
3873
  const owner = this.absOwner(ctx, file);
@@ -3951,9 +4040,12 @@ const cssgen = async (ctx, options) => {
3951
4040
  } else await ctx.writeCss(sheet);
3952
4041
  done();
3953
4042
  } else {
3954
- const { files } = ctx.parseFiles();
4043
+ const { files, results } = ctx.parseFiles();
3955
4044
  const done = logger.time.info(ctx.messages.buildComplete(files.length));
3956
- const sheet = assembleExtractedSheet(ctx, { layerParams: true });
4045
+ const sheet = assembleExtractedSheet(ctx, {
4046
+ layerParams: true,
4047
+ parserResults: results
4048
+ });
3957
4049
  if (splitting) await ctx.writeSplitCss(sheet);
3958
4050
  else if (outfile) {
3959
4051
  const css = ctx.getCss(sheet);
@@ -4014,12 +4106,22 @@ async function debug(ctx, options) {
4014
4106
  }
4015
4107
  //#endregion
4016
4108
  //#region src/generate.ts
4017
- async function build(ctx, artifactIds) {
4109
+ async function build(ctx, sourceScanCache, artifactIds) {
4018
4110
  await codegen(ctx, artifactIds);
4019
4111
  if (ctx.config.emitTokensOnly) return logger.info("css:emit", "Successfully rebuilt the css variables and js function to query your tokens ✨");
4020
4112
  const done = logger.time.info("");
4021
4113
  const parsed = ctx.parseFiles();
4022
- const sheet = assembleExtractedSheet(ctx, { layerParams: true });
4114
+ if (sourceScanCache) {
4115
+ for (const result of parsed.results) if (result.filePath) recordResolvedTokenReferences(sourceScanCache, ctx.runtime.path.abs(ctx.config.cwd, result.filePath), result);
4116
+ }
4117
+ const sheet = assembleExtractedSheet(ctx, sourceScanCache ? {
4118
+ layerParams: true,
4119
+ sourceScanCache,
4120
+ sourceInventory: parsed.files
4121
+ } : {
4122
+ layerParams: true,
4123
+ parserResults: parsed.results
4124
+ });
4023
4125
  await ctx.writeCss(sheet);
4024
4126
  done(ctx.messages.buildComplete(parsed.files.length));
4025
4127
  }
@@ -4028,19 +4130,22 @@ async function generate(config, configPath) {
4028
4130
  config,
4029
4131
  configPath
4030
4132
  });
4031
- await build(ctx);
4133
+ const sourceScanCache = createSourceScanCache();
4032
4134
  const { cwd, watch, poll } = ctx.config;
4135
+ await build(ctx, watch ? sourceScanCache : void 0);
4033
4136
  if (watch) {
4034
4137
  ctx.watchConfig(async () => {
4035
4138
  const affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
4036
4139
  ctx = new BambooContext(conf);
4037
4140
  });
4141
+ sourceScanCache.entries.clear();
4142
+ sourceScanCache.resolvedTokenReferences.clear();
4038
4143
  logger.info("ctx:updated", "config rebuilt ✅");
4039
4144
  await ctx.hooks["config:change"]?.({
4040
4145
  config: ctx.config,
4041
4146
  changes: affecteds
4042
4147
  });
4043
- return build(ctx, Array.from(affecteds.artifacts));
4148
+ return build(ctx, sourceScanCache, Array.from(affecteds.artifacts));
4044
4149
  }, {
4045
4150
  cwd,
4046
4151
  poll
@@ -4053,14 +4158,21 @@ async function generate(config, configPath) {
4053
4158
  * per file. Writing per file would run the optimize pipeline and hit the disk
4054
4159
  * once per importer for a single keystroke.
4055
4160
  */
4056
- const bundleStyles = async (ctx, changedFilePaths) => {
4161
+ const bundleStyles = async (ctx, changedFilePaths, inventoryChanged = false) => {
4057
4162
  let parsed = 0;
4058
4163
  const encoder = ctx.parserOptions.encoder;
4059
- for (const filePath of changedFilePaths) if (encoder.withOwner("extract", filePath, () => ctx.project.parseSourceFile(filePath, encoder))) parsed++;
4060
- if (parsed === 0) return;
4164
+ for (const filePath of changedFilePaths) {
4165
+ const result = encoder.withOwner("extract", filePath, () => ctx.project.parseSourceFile(filePath, encoder));
4166
+ recordResolvedTokenReferences(sourceScanCache, filePath, result);
4167
+ if (result) parsed++;
4168
+ }
4169
+ if (parsed === 0 && !inventoryChanged) return;
4061
4170
  const outfile = ctx.runtime.path.join(...ctx.paths.root, "styles.css");
4062
4171
  const done = logger.time.info(ctx.messages.buildComplete(parsed));
4063
- const sheet = assembleExtractedSheet(ctx, { layerParams: true });
4172
+ const sheet = assembleExtractedSheet(ctx, {
4173
+ layerParams: true,
4174
+ sourceScanCache
4175
+ });
4064
4176
  const css = ctx.getCss(sheet);
4065
4177
  await ctx.runtime.fs.writeFile(outfile, css);
4066
4178
  done();
@@ -4070,7 +4182,9 @@ async function generate(config, configPath) {
4070
4182
  if (event === "unlink") {
4071
4183
  const dependents = ctx.project.getDependents(filePath);
4072
4184
  ctx.project.removeSourceFile(filePath);
4073
- await bundleStyles(ctx, dependents);
4185
+ sourceScanCache.entries.delete(filePath);
4186
+ sourceScanCache.resolvedTokenReferences.delete(filePath);
4187
+ await bundleStyles(ctx, dependents, true);
4074
4188
  } else if (event === "change") {
4075
4189
  ctx.project.reloadSourceFile(filePath);
4076
4190
  await bundleStyles(ctx, [filePath, ...ctx.project.getDependents(filePath)]);