@bamboocss/node 1.58.1 → 1.58.3

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.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as markStaticCompilerActive, t as isStaticCompilerActive } from "./static-compiler-CvT9iHM_.mjs";
2
- import { DeadImport, ParserOptions, StyleEncoder, Stylesheet } from "@bamboocss/core";
2
+ import { DeadImport, ParserOptions, StyleEncoder, Stylesheet, UnresolvedTokenCall } from "@bamboocss/core";
3
3
  import { Generator, generatePackageExports } from "@bamboocss/generator";
4
4
  import { ReportFormat } from "@bamboocss/reporter";
5
5
  import { AnalysisOptions, Artifact, ArtifactId, BambooHooks, Config, CssArtifactType, DiffConfigResult, LoadConfigResult, ParserResultInterface, ResultItem, Runtime, SpecFile, WatchOptions, WatcherEventType } from "@bamboocss/types";
@@ -209,6 +209,14 @@ interface UnresolvedStyle {
209
209
  */
210
210
  reason: 'unresolvable-value' | 'missing-property' | 'unenumerable-keys' | 'unresolved-raw';
211
211
  }
212
+ /** A `token()` call naming no token, and where it is. @see UnresolvedTokenCall */
213
+ interface UnresolvedTokenCallFinding {
214
+ call: UnresolvedTokenCall;
215
+ filePath: string;
216
+ /** One-based, as the native analysis reports the call's start. */
217
+ line: number;
218
+ column: number;
219
+ }
212
220
  /**
213
221
  * What extraction found in one file, and the encoder calls that turn it into rules.
214
222
  *
@@ -241,6 +249,14 @@ declare class ParserResult implements ParserResultInterface {
241
249
  * `assertNoDeadCalls` rather than warned about, for that reason.
242
250
  */
243
251
  deadCalls: DeadImport[];
252
+ /**
253
+ * `token()` and `token.value()` calls naming no token.
254
+ *
255
+ * Each returns `undefined`, so a property it was written into never reaches the encoder and
256
+ * nothing else records it. Graded by the token half of `unresolvedToken` — see
257
+ * `Generator.unresolvedTokenCalls` for where they are reported.
258
+ */
259
+ unresolvedTokenCalls: UnresolvedTokenCallFinding[];
244
260
  /**
245
261
  * Whether each result item is attributed to its call site, for a source map.
246
262
  *
@@ -660,6 +676,22 @@ declare class BambooContext extends Generator {
660
676
  forgetNativeFile: (filePath: string) => void;
661
677
  private parseNativeFile;
662
678
  parseFile: (filePath: string, styleEncoder?: StyleEncoder) => ParserResult | undefined;
679
+ /**
680
+ * Keep a file's `token()` calls naming no token for the sheet's check, and warn about them when
681
+ * the token half of `unresolvedToken` is `warn`.
682
+ *
683
+ * Set or deleted on every parse, like `deadCalls` and for the same reason: a file read again
684
+ * without them has fixed them, and an entry outliving the fix would fail every later build. A
685
+ * file under `outdir` is left out, as `reportUnresolvedStyles` leaves it: nothing there is the
686
+ * author's to rewrite.
687
+ */
688
+ private recordUnresolvedTokenCalls;
689
+ /**
690
+ * Drop the `token()` call findings of every file outside `files`, as `assertNoDeadCalls` drops
691
+ * its own: one deleted or taken out of `include` is not parsed again, so its entry would fail
692
+ * every later sheet, naming a file that is no longer part of the build.
693
+ */
694
+ forgetUnresolvedTokenCallsOutside: (files: Iterable<string>) => void;
663
695
  /**
664
696
  * Extract every file in one pass, and fail on the ones that could not be read.
665
697
  *
@@ -692,7 +724,24 @@ declare class BambooContext extends Generator {
692
724
  };
693
725
  writeCss: (sheet?: Stylesheet) => Promise<PromiseSettledResult<void>[]> | undefined;
694
726
  writeSplitCss: (sheet: Stylesheet) => Promise<void>;
695
- watchConfig: (cb: (file: string) => void | Promise<void>, opts?: Omit<WatchOptions, "include">) => void;
727
+ /**
728
+ * Call `cb` when a file the config is built from changes.
729
+ *
730
+ * `cb` reloads the config, and hands the context it built to `reloaded` as soon as it has one, so
731
+ * the watch can follow what that config is built from. Armed once with this context's files, an
732
+ * edit that swapped in a preset, or imported one more module, left the new file unwatched:
733
+ * editing it did nothing until the process restarted. Handed over before `cb` builds, because a
734
+ * build can fail where the reload did not — a recipe in the new preset naming no token — and the
735
+ * file to fix is that preset.
736
+ */
737
+ watchConfig: (cb: (file: string, reloaded: (ctx: BambooContext) => void) => BambooContext | void | Promise<BambooContext | void>, opts?: Omit<WatchOptions, "include">) => void;
738
+ /**
739
+ * The files the config is built from: the config, what it imports, the presets it names by path,
740
+ * and its `dependencies` — as patterns too, so a file that starts to match one is seen.
741
+ */
742
+ private configFiles;
743
+ /** What the config file imports, read off its source without running it, for a config that failed to load. */
744
+ private importedFiles;
696
745
  watchFiles: (cb: (event: WatcherEventType, file: string) => void | Promise<void>, opts?: Omit<WatchOptions, "include" | "exclude" | "poll" | "cwd" | "logger">) => void;
697
746
  }
698
747
  //#endregion
@@ -714,30 +763,26 @@ declare function analyze(ctx: BambooContext, options?: AnalysisOptions): Promise
714
763
  getRecipeReport(format?: ReportFormat): {
715
764
  report: import("@bamboocss/reporter").RecipeReportEntry[];
716
765
  formatted: string;
717
- };
766
+ }; /** Each category's tokens, counted as used exactly when the build keeps them. */
718
767
  getTokenReport(format?: ReportFormat): {
719
768
  report: import("@bamboocss/reporter").TokenAnalysisReport;
720
769
  formatted: string;
721
- }; /** Every pattern the config defines, and how often each is called. */
722
- getPatternReport: () => import("@bamboocss/reporter").PatternReportEntry[]; /** Every style property written, and how often. */
723
- getUtilityReport: () => import("@bamboocss/reporter").UtilityReportEntry[]; /** Every keyframe the theme defines, and how often an animation names it. */
724
- getKeyframeReport: () => import("@bamboocss/reporter").KeyframeReportEntry[];
725
- /**
726
- * The configured names no source uses, of the kinds asked for.
727
- *
728
- * Tokens and keyframes are what the build's own prune removes, run with every prune on
729
- * whatever the config says, so a name here is one the stylesheet already ships without.
730
- * Anything the prune keeps for a reader it cannot follow — a `token()` path built at runtime,
731
- * a theme, a `keepTokens` pattern — is kept here too, and not listed: being told a token is
732
- * unused when something still asks for it is worse than not being told at all. A recipe or a
733
- * pattern is one no source calls and `staticCss` does not emit regardless.
734
- *
735
- * Read off a sheet of its own. The prune's settings are laid over the context's while it is
736
- * built, and `unresolvedPath` is off for it: that one only decides how loudly the prune says
737
- * what it could not read, and a project that does not prune tokens never hears it.
738
- */
739
- getUnused(kinds?: ReadonlyArray<keyof UnusedNames>): UnusedNames; /** The names as JSON, of the kinds `getUnused` was asked for. */
740
- writeUnused(filePath: string, unused: Partial<UnusedNames>): Promise<void>;
770
+ }; /** Every pattern the config defines, how often each is called, and whether anything uses it. */
771
+ getPatternReport: () => {
772
+ unused: boolean;
773
+ patternName: string;
774
+ usedCount: number;
775
+ usedInXFiles: number;
776
+ }[]; /** Every style property written, and how often. */
777
+ getUtilityReport: () => import("@bamboocss/reporter").UtilityReportEntry[]; /** Every keyframe the theme defines, how often an animation names it, and whether the build keeps it. */
778
+ getKeyframeReport: () => {
779
+ unused: boolean;
780
+ keyframe: string;
781
+ usedCount: number;
782
+ usedInXFiles: number;
783
+ }[];
784
+ getUnused: (kinds?: ReadonlyArray<keyof UnusedNames>) => UnusedNames; /** The names as JSON, of the kinds `getUnused` was asked for. */
785
+ writeUnused(filePath: string, unused: Partial<UnusedNames>): Promise<void>; /** The extraction report, with what `getUnused` makes of it, so the file cannot be read as calling a kept name unused. */
741
786
  writeReport(filePath: string): Promise<void>;
742
787
  }>;
743
788
  //#endregion
package/dist/index.mjs CHANGED
@@ -5,7 +5,7 @@ import { checkNamingAgreement, formatNamingDisagreement, messages, prunesPreflig
5
5
  import { BambooError, cssVarRefs, getOrCreateSet, groupBy, truncateList, uniq } from "@bamboocss/shared";
6
6
  import { isMatch } from "matcher";
7
7
  import fs, { appendFileSync, existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
8
- import { changesEveryArtifact, convertTsPathsToRegexes, diffConfigs, findConfig, loadConfig, mergeHooks } from "@bamboocss/config";
8
+ import { changesEveryArtifact, convertTsPathsToRegexes, diffConfigs, filesReadBy, findConfig, getConfigDependencies, loadConfig, mergeHooks } from "@bamboocss/config";
9
9
  import path, { basename, dirname, extname, isAbsolute, join, normalize, parse, posix, relative, resolve, sep } from "node:path";
10
10
  import { pluginSvelte } from "@bamboocss/plugin-svelte";
11
11
  import { pluginVue } from "@bamboocss/plugin-vue";
@@ -603,6 +603,112 @@ async function analyze(ctx, options = {}) {
603
603
  ctx.runtime.fs.ensureDirSync(ctx.runtime.path.dirname(filePath));
604
604
  return ctx.runtime.fs.writeFile(filePath, JSON.stringify(value, replacer, 2));
605
605
  };
606
+ /**
607
+ * The tokens and keyframes the build's own prune removes, worked out once and shared by every
608
+ * report that speaks of use, so none of them can call a name unused that `getUnused` does not,
609
+ * or the other way round.
610
+ *
611
+ * Run with every prune on, whatever the config says, so a name here is one the stylesheet ships
612
+ * without. Anything the prune keeps for a reader it cannot follow — a `token()` path built at
613
+ * runtime, a theme, a `keepTokens` pattern — is kept here too: being told a token is unused when
614
+ * something still asks for it is worse than not being told at all.
615
+ *
616
+ * Read off a sheet of its own. The prune's settings are laid over the context's while it is
617
+ * built, and `unresolvedPath` is off for it: that one only decides how loudly the prune says what
618
+ * it could not read, and a project that does not prune tokens never hears it.
619
+ */
620
+ let pruned;
621
+ const prunedNames = () => {
622
+ if (pruned) return pruned;
623
+ const prune = {
624
+ ...ctx.config.prune,
625
+ keyframes: true,
626
+ unresolvedPath: "off"
627
+ };
628
+ if (prune.tokens === false) delete prune.tokens;
629
+ const configured = ctx.config.prune;
630
+ ctx.config.prune = prune;
631
+ let sheet;
632
+ try {
633
+ sheet = assembleExtractedSheet(ctx, {
634
+ parserResults,
635
+ prunePreflight: false
636
+ });
637
+ } finally {
638
+ ctx.config.prune = configured;
639
+ }
640
+ const declared = /* @__PURE__ */ new Set();
641
+ const keyframes = /* @__PURE__ */ new Set();
642
+ sheet.layers.tokens.walkDecls((decl) => {
643
+ if (decl.prop.startsWith("--")) declared.add(decl.prop);
644
+ });
645
+ sheet.layers.tokens.walkAtRules(/keyframes$/, (rule) => {
646
+ keyframes.add(rule.params.trim().replace(/^(["'])(.*)\1$/, "$2").replace(/\\(.)/g, "$1"));
647
+ });
648
+ const declarable = /* @__PURE__ */ new Set();
649
+ for (const vars of ctx.tokens.view.vars.values()) for (const name of vars.keys()) declarable.add(name);
650
+ const judged = /* @__PURE__ */ new Map();
651
+ const unused = /* @__PURE__ */ new Map();
652
+ const tokens = [];
653
+ const add = (into, category, name) => {
654
+ const names = into.get(category) ?? /* @__PURE__ */ new Set();
655
+ names.add(name);
656
+ into.set(category, names);
657
+ };
658
+ for (const token of ctx.tokens.allTokens) {
659
+ const { isVirtual, isNegative, category } = token.extensions;
660
+ if (isVirtual || isNegative || category === "breakpoints" || token.name.startsWith("sizes.breakpoint-")) continue;
661
+ const name = token.extensions.var;
662
+ if (!declarable.has(name)) continue;
663
+ if (category) add(judged, category, token.extensions.prop);
664
+ if (declared.has(name)) continue;
665
+ tokens.push(token.name);
666
+ if (category) add(unused, category, token.extensions.prop);
667
+ }
668
+ pruned = {
669
+ tokens: [...new Set(tokens)].sort(),
670
+ keyframes: Object.keys(ctx.config.theme?.keyframes ?? {}).filter((name) => !keyframes.has(name)).sort(),
671
+ judged,
672
+ unused
673
+ };
674
+ return pruned;
675
+ };
676
+ const { staticCss } = ctx.config;
677
+ const emitted = (rules) => (name) => rules === "*" || rules != null && typeof rules === "object" && name in rules;
678
+ const unusedPatterns = () => {
679
+ const kept = emitted(staticCss?.patterns);
680
+ return reporter.getPatternReport().filter((entry) => !entry.usedCount && !kept(entry.patternName)).map((entry) => entry.patternName).sort();
681
+ };
682
+ /**
683
+ * The configured names no source uses, of the kinds asked for.
684
+ *
685
+ * Tokens and keyframes are what the build's own prune removes; see `prunedNames`. A recipe or a
686
+ * pattern is one no source calls and `staticCss` does not emit regardless.
687
+ */
688
+ const getUnused = (kinds = [
689
+ "tokens",
690
+ "recipes",
691
+ "patterns",
692
+ "keyframes"
693
+ ]) => {
694
+ const unused = {
695
+ tokens: [],
696
+ recipes: [],
697
+ patterns: [],
698
+ keyframes: []
699
+ };
700
+ if (kinds.includes("tokens")) unused.tokens = prunedNames().tokens;
701
+ if (kinds.includes("keyframes")) unused.keyframes = prunedNames().keyframes;
702
+ if (kinds.includes("recipes")) {
703
+ const called = new Set(reporter.getRecipeReport().map((entry) => entry.recipeName));
704
+ const inConfig = emitted(staticCss?.recipes);
705
+ const { recipes = {}, slotRecipes = {} } = ctx.config.theme ?? {};
706
+ const ofItself = (name) => Boolean((recipes[name] ?? slotRecipes[name])?.staticCss?.length);
707
+ unused.recipes = [...ctx.recipes.keys].filter((name) => !called.has(name) && !inConfig(name) && !ofItself(name)).sort();
708
+ }
709
+ if (kinds.includes("patterns")) unused.patterns = unusedPatterns();
710
+ return unused;
711
+ };
606
712
  return {
607
713
  getRecipeReport(format = "table") {
608
714
  const report = reporter.getRecipeReport();
@@ -611,104 +717,47 @@ async function analyze(ctx, options = {}) {
611
717
  formatted: formatRecipeReport(report, format)
612
718
  };
613
719
  },
720
+ /** Each category's tokens, counted as used exactly when the build keeps them. */
614
721
  getTokenReport(format = "table") {
615
- const report = reporter.getTokenReport();
722
+ const { judged, unused } = prunedNames();
723
+ const report = reporter.getTokenReport({
724
+ judged,
725
+ unused
726
+ });
616
727
  return {
617
728
  report,
618
729
  formatted: formatTokenReport(report.getSummary(), format)
619
730
  };
620
731
  },
621
- /** Every pattern the config defines, and how often each is called. */
622
- getPatternReport: () => reporter.getPatternReport(),
732
+ /** Every pattern the config defines, how often each is called, and whether anything uses it. */
733
+ getPatternReport: () => {
734
+ const unused = new Set(unusedPatterns());
735
+ return reporter.getPatternReport().map((entry) => ({
736
+ ...entry,
737
+ unused: unused.has(entry.patternName)
738
+ }));
739
+ },
623
740
  /** Every style property written, and how often. */
624
741
  getUtilityReport: () => reporter.getUtilityReport(),
625
- /** Every keyframe the theme defines, and how often an animation names it. */
626
- getKeyframeReport: () => reporter.getKeyframeReport(),
627
- /**
628
- * The configured names no source uses, of the kinds asked for.
629
- *
630
- * Tokens and keyframes are what the build's own prune removes, run with every prune on
631
- * whatever the config says, so a name here is one the stylesheet already ships without.
632
- * Anything the prune keeps for a reader it cannot follow — a `token()` path built at runtime,
633
- * a theme, a `keepTokens` pattern — is kept here too, and not listed: being told a token is
634
- * unused when something still asks for it is worse than not being told at all. A recipe or a
635
- * pattern is one no source calls and `staticCss` does not emit regardless.
636
- *
637
- * Read off a sheet of its own. The prune's settings are laid over the context's while it is
638
- * built, and `unresolvedPath` is off for it: that one only decides how loudly the prune says
639
- * what it could not read, and a project that does not prune tokens never hears it.
640
- */
641
- getUnused(kinds = [
642
- "tokens",
643
- "recipes",
644
- "patterns",
645
- "keyframes"
646
- ]) {
647
- const unused = {
648
- tokens: [],
649
- recipes: [],
650
- patterns: [],
651
- keyframes: []
652
- };
653
- if (kinds.includes("tokens") || kinds.includes("keyframes")) {
654
- const prune = {
655
- ...ctx.config.prune,
656
- keyframes: true,
657
- unresolvedPath: "off"
658
- };
659
- if (prune.tokens === false) delete prune.tokens;
660
- const configured = ctx.config.prune;
661
- ctx.config.prune = prune;
662
- let sheet;
663
- try {
664
- sheet = assembleExtractedSheet(ctx, {
665
- parserResults,
666
- prunePreflight: false
667
- });
668
- } finally {
669
- ctx.config.prune = configured;
670
- }
671
- const declared = /* @__PURE__ */ new Set();
672
- const keyframes = /* @__PURE__ */ new Set();
673
- sheet.layers.tokens.walkDecls((decl) => {
674
- if (decl.prop.startsWith("--")) declared.add(decl.prop);
675
- });
676
- sheet.layers.tokens.walkAtRules(/keyframes$/, (rule) => {
677
- keyframes.add(rule.params.trim().replace(/^(["'])(.*)\1$/, "$2").replace(/\\(.)/g, "$1"));
678
- });
679
- const declarable = /* @__PURE__ */ new Set();
680
- for (const vars of ctx.tokens.view.vars.values()) for (const name of vars.keys()) declarable.add(name);
681
- const tokens = /* @__PURE__ */ new Set();
682
- for (const token of ctx.tokens.allTokens) {
683
- const { isVirtual, isNegative, category } = token.extensions;
684
- if (isVirtual || isNegative || category === "breakpoints" || token.name.startsWith("sizes.breakpoint-")) continue;
685
- const name = token.extensions.var;
686
- if (declarable.has(name) && !declared.has(name)) tokens.add(token.name);
687
- }
688
- if (kinds.includes("tokens")) unused.tokens = [...tokens].sort();
689
- if (kinds.includes("keyframes")) unused.keyframes = Object.keys(ctx.config.theme?.keyframes ?? {}).filter((name) => !keyframes.has(name)).sort();
690
- }
691
- const { staticCss } = ctx.config;
692
- const emitted = (rules) => (name) => rules === "*" || rules != null && typeof rules === "object" && name in rules;
693
- if (kinds.includes("recipes")) {
694
- const called = new Set(reporter.getRecipeReport().map((entry) => entry.recipeName));
695
- const inConfig = emitted(staticCss?.recipes);
696
- const { recipes = {}, slotRecipes = {} } = ctx.config.theme ?? {};
697
- const ofItself = (name) => Boolean((recipes[name] ?? slotRecipes[name])?.staticCss?.length);
698
- unused.recipes = [...ctx.recipes.keys].filter((name) => !called.has(name) && !inConfig(name) && !ofItself(name)).sort();
699
- }
700
- if (kinds.includes("patterns")) {
701
- const kept = emitted(staticCss?.patterns);
702
- unused.patterns = reporter.getPatternReport().filter((entry) => !entry.usedCount && !kept(entry.patternName)).map((entry) => entry.patternName).sort();
703
- }
704
- return unused;
742
+ /** Every keyframe the theme defines, how often an animation names it, and whether the build keeps it. */
743
+ getKeyframeReport: () => {
744
+ const unused = new Set(prunedNames().keyframes);
745
+ return reporter.getKeyframeReport().map((entry) => ({
746
+ ...entry,
747
+ unused: unused.has(entry.keyframe)
748
+ }));
705
749
  },
750
+ getUnused,
706
751
  /** The names as JSON, of the kinds `getUnused` was asked for. */
707
752
  writeUnused(filePath, unused) {
708
753
  return writeJson(filePath, unused);
709
754
  },
755
+ /** The extraction report, with what `getUnused` makes of it, so the file cannot be read as calling a kept name unused. */
710
756
  writeReport(filePath) {
711
- return writeJson(filePath, reporter.report);
757
+ return writeJson(filePath, {
758
+ ...reporter.report,
759
+ unused: getUnused()
760
+ });
712
761
  }
713
762
  };
714
763
  }
@@ -2895,6 +2944,7 @@ var DiffEngine = class {
2895
2944
  if (!affected.hasConfigChanged) {
2896
2945
  applyTsConfig(this.ctx.conf, conf);
2897
2946
  rememberTsConfigResolutionFiles(this.ctx.conf, getTsConfigResolutionFiles(conf));
2947
+ this.ctx.conf.dependencies = conf.dependencies;
2898
2948
  }
2899
2949
  return affected;
2900
2950
  }
@@ -2959,6 +3009,14 @@ var ParserResult = class {
2959
3009
  */
2960
3010
  deadCalls = [];
2961
3011
  /**
3012
+ * `token()` and `token.value()` calls naming no token.
3013
+ *
3014
+ * Each returns `undefined`, so a property it was written into never reaches the encoder and
3015
+ * nothing else records it. Graded by the token half of `unresolvedToken` — see
3016
+ * `Generator.unresolvedTokenCalls` for where they are reported.
3017
+ */
3018
+ unresolvedTokenCalls = [];
3019
+ /**
2962
3020
  * Whether each result item is attributed to its call site, for a source map.
2963
3021
  *
2964
3022
  * Off for a source a `parser:before` hook rewrote: its positions are the hook's output's,
@@ -3506,9 +3564,15 @@ const nodeRuntime = {
3506
3564
  } : false
3507
3565
  });
3508
3566
  logger.debug("watch:file", `Watching [ ${dirnames.join(", ")} ]`);
3509
- process.once("SIGINT", async () => {
3567
+ const onInterrupt = async () => {
3510
3568
  await watcher.close();
3511
- });
3569
+ };
3570
+ process.once("SIGINT", onInterrupt);
3571
+ const close = watcher.close.bind(watcher);
3572
+ watcher.close = () => {
3573
+ process.off("SIGINT", onInterrupt);
3574
+ return close();
3575
+ };
3512
3576
  return watcher;
3513
3577
  }
3514
3578
  }
@@ -4273,6 +4337,7 @@ var BambooContext = class extends Generator {
4273
4337
  this.nativeConfigurationFiles.delete(file);
4274
4338
  this.nativeExtractions.delete(file);
4275
4339
  this.nativeSourceMetadata.delete(file);
4340
+ this.unresolvedTokenCalls.delete(this.runtime.path.abs(this.config.cwd, filePath));
4276
4341
  };
4277
4342
  parseNativeFile = (filePath, native, encoder) => {
4278
4343
  if (native.errors.length) throw new BambooError("NATIVE_EXTRACTION", `Native extraction failed for ${filePath}:\n${native.errors.join("\n")}`);
@@ -4283,6 +4348,7 @@ var BambooContext = class extends Generator {
4283
4348
  for (const dependency of native.dependencies) result.addDependency(dependency);
4284
4349
  const metadata = this.nativeSourceMetadata.get(filePath.replaceAll("\\", "/"));
4285
4350
  result.origins = metadata?.origins ?? true;
4351
+ let tokenTable;
4286
4352
  for (const call of native.calls) {
4287
4353
  const atomOrigin = encoder.recordOrigins && result.origins ? {
4288
4354
  filePath,
@@ -4341,8 +4407,24 @@ var BambooContext = class extends Generator {
4341
4407
  });
4342
4408
  else if (call.kind === "pattern") result.setPattern(call.importedName, item);
4343
4409
  else if (call.kind === "recipe") result.setRecipe(call.importedName, item, new Set(call.unresolvedKeys));
4344
- else if (call.kind === "token" || call.kind === "tokenValue") result.setToken(item, call.kind);
4345
- else if (call.kind === "dead") result.deadCalls.push({
4410
+ else if (call.kind === "token" || call.kind === "tokenValue") {
4411
+ result.setToken(item, call.kind);
4412
+ if (call.complete && !call.guarded) {
4413
+ tokenTable ??= this.tokens.view.values;
4414
+ for (let index = 0; index < call.arguments.length; index++) {
4415
+ const path = call.arguments[index];
4416
+ if (typeof path !== "string" || tokenTable.has(path)) continue;
4417
+ if (call.arguments.indexOf(path) !== index) continue;
4418
+ const unresolved = this.utility.unresolvedTokenCall(call.kind === "token" ? "token" : "token.value", path);
4419
+ if (unresolved) result.unresolvedTokenCalls.push({
4420
+ call: unresolved,
4421
+ filePath,
4422
+ line: call.line,
4423
+ column: call.column
4424
+ });
4425
+ }
4426
+ }
4427
+ } else if (call.kind === "dead") result.deadCalls.push({
4346
4428
  name: call.importedName,
4347
4429
  alias: call.name,
4348
4430
  mod: call.module,
@@ -4371,6 +4453,7 @@ var BambooContext = class extends Generator {
4371
4453
  encoder.releaseFile(file);
4372
4454
  this.parseFailures.delete(file);
4373
4455
  this.deadCalls.delete(file);
4456
+ this.unresolvedTokenCalls.delete(file);
4374
4457
  measure();
4375
4458
  return;
4376
4459
  }
@@ -4390,11 +4473,45 @@ var BambooContext = class extends Generator {
4390
4473
  this.reportUnresolvedStyles(result);
4391
4474
  if (result.deadCalls.length) this.deadCalls.set(file, result.deadCalls);
4392
4475
  else this.deadCalls.delete(file);
4476
+ this.recordUnresolvedTokenCalls(file, result);
4393
4477
  }
4394
4478
  measure();
4395
4479
  return result;
4396
4480
  };
4397
4481
  /**
4482
+ * Keep a file's `token()` calls naming no token for the sheet's check, and warn about them when
4483
+ * the token half of `unresolvedToken` is `warn`.
4484
+ *
4485
+ * Set or deleted on every parse, like `deadCalls` and for the same reason: a file read again
4486
+ * without them has fixed them, and an entry outliving the fix would fail every later build. A
4487
+ * file under `outdir` is left out, as `reportUnresolvedStyles` leaves it: nothing there is the
4488
+ * author's to rewrite.
4489
+ */
4490
+ recordUnresolvedTokenCalls = (file, result) => {
4491
+ const found = this.isGenerated(file) ? [] : result.unresolvedTokenCalls;
4492
+ if (!found.length) {
4493
+ this.unresolvedTokenCalls.delete(file);
4494
+ return;
4495
+ }
4496
+ const sites = found.map(({ call, line, column }) => ({
4497
+ call,
4498
+ where: `${this.relative(file)}:${line}:${column}`
4499
+ }));
4500
+ this.unresolvedTokenCalls.set(file, sites);
4501
+ if (this.utility.unresolvedToken.token !== "warn") return;
4502
+ for (const { call, where } of sites) logger.warn("token", `${where} — ${this.utility.explainUnresolvedTokenCall(call)}`);
4503
+ };
4504
+ /**
4505
+ * Drop the `token()` call findings of every file outside `files`, as `assertNoDeadCalls` drops
4506
+ * its own: one deleted or taken out of `include` is not parsed again, so its entry would fail
4507
+ * every later sheet, naming a file that is no longer part of the build.
4508
+ */
4509
+ forgetUnresolvedTokenCallsOutside = (files) => {
4510
+ if (!this.unresolvedTokenCalls.size) return;
4511
+ const inScope = new Set(Array.from(files, (file) => this.runtime.path.abs(this.config.cwd, file)));
4512
+ for (const file of this.unresolvedTokenCalls.keys()) if (!inScope.has(file)) this.unresolvedTokenCalls.delete(file);
4513
+ };
4514
+ /**
4398
4515
  * Extract every file in one pass, and fail on the ones that could not be read.
4399
4516
  *
4400
4517
  * Routed through `parseFile` rather than parsing directly, so the two entry points cannot
@@ -4463,6 +4580,7 @@ var BambooContext = class extends Generator {
4463
4580
  if (encoder.isEmpty()) return;
4464
4581
  filesWithCss.push(file);
4465
4582
  });
4583
+ this.forgetUnresolvedTokenCallsOutside(files);
4466
4584
  this.assertExtracted(files);
4467
4585
  this.assertNoDeadCalls(files);
4468
4586
  return {
@@ -4524,23 +4642,80 @@ var BambooContext = class extends Generator {
4524
4642
  if (fs.existsSync(recipesIndex)) fs.rmFileSync(recipesIndex);
4525
4643
  if (fs.existsSync(recipesDir)) fs.rmFileSync(recipesDir);
4526
4644
  };
4645
+ /**
4646
+ * Call `cb` when a file the config is built from changes.
4647
+ *
4648
+ * `cb` reloads the config, and hands the context it built to `reloaded` as soon as it has one, so
4649
+ * the watch can follow what that config is built from. Armed once with this context's files, an
4650
+ * edit that swapped in a preset, or imported one more module, left the new file unwatched:
4651
+ * editing it did nothing until the process restarted. Handed over before `cb` builds, because a
4652
+ * build can fail where the reload did not — a recipe in the new preset naming no token — and the
4653
+ * file to fix is that preset.
4654
+ */
4527
4655
  watchConfig = (cb, opts) => {
4528
4656
  const { cwd, poll, exclude } = opts ?? {};
4529
4657
  logger.info("ctx:watch", this.messages.configWatch());
4530
- const watcher = this.runtime.fs.watch({
4531
- include: uniq([...this.explicitDeps, ...this.conf.dependencies]),
4532
- exclude,
4533
- cwd,
4534
- poll
4535
- });
4658
+ const arm = (include) => {
4659
+ const watcher = this.runtime.fs.watch({
4660
+ include,
4661
+ exclude,
4662
+ cwd,
4663
+ poll
4664
+ });
4665
+ watcher.on("all", (event, file) => {
4666
+ if (event === "add" || event === "change") rebuild(file);
4667
+ });
4668
+ return watcher;
4669
+ };
4670
+ let files = this.configFiles();
4671
+ let watcher = arm(files);
4672
+ const rearm = async (nextFiles) => {
4673
+ if (nextFiles.join("\n") === files.join("\n")) return;
4674
+ const previous = watcher;
4675
+ files = nextFiles;
4676
+ watcher = arm(files);
4677
+ await previous.close();
4678
+ };
4536
4679
  const rebuild = debounce(async (file) => {
4537
4680
  logger.info("ctx:change", "config changed, rebuilding...");
4538
- await reportRebuildFailure(() => cb(file));
4539
- });
4540
- watcher.on("all", (event, file) => {
4541
- if (event === "add" || event === "change") rebuild(file);
4681
+ const reload = {};
4682
+ try {
4683
+ const next = await cb(file, (ctx) => {
4684
+ reload.ctx = ctx;
4685
+ });
4686
+ if (next) reload.ctx = next;
4687
+ } catch (error) {
4688
+ logger.error("ctx:rebuild", error instanceof Error ? error.message : String(error));
4689
+ const reloaded = reload.ctx;
4690
+ const nextFiles = reloaded ? reloaded.configFiles() : uniq([
4691
+ ...files,
4692
+ ...this.importedFiles(),
4693
+ ...filesReadBy(error)
4694
+ ]).sort();
4695
+ await reportRebuildFailure(() => rearm(nextFiles));
4696
+ return;
4697
+ }
4698
+ const reloaded = reload.ctx;
4699
+ if (reloaded) await reportRebuildFailure(() => rearm(reloaded.configFiles()));
4542
4700
  });
4543
4701
  };
4702
+ /**
4703
+ * The files the config is built from: the config, what it imports, the presets it names by path,
4704
+ * and its `dependencies` — as patterns too, so a file that starts to match one is seen.
4705
+ */
4706
+ configFiles = () => uniq([
4707
+ ...this.explicitDeps,
4708
+ ...this.conf.dependencies,
4709
+ ...this.config.dependencies ?? []
4710
+ ]).sort();
4711
+ /** What the config file imports, read off its source without running it, for a config that failed to load. */
4712
+ importedFiles = () => {
4713
+ try {
4714
+ return [...getConfigDependencies(this.conf.path, this.conf.tsOptions, this.conf.tsconfig?.compilerOptions).deps];
4715
+ } catch {
4716
+ return [];
4717
+ }
4718
+ };
4544
4719
  watchFiles = (cb, opts) => {
4545
4720
  const { include, exclude, poll, cwd } = this.config;
4546
4721
  logger.info("ctx:watch", this.messages.watch());
@@ -5920,6 +6095,7 @@ var Builder = class {
5920
6095
  this.snapshotResolutionConfigurations();
5921
6096
  this.affectedFiles = void 0;
5922
6097
  this.extractionOrder = void 0;
6098
+ ctx.forgetUnresolvedTokenCallsOutside(files);
5923
6099
  ctx.assertExtracted(files);
5924
6100
  ctx.assertNoDeadCalls(files);
5925
6101
  };
@@ -6359,10 +6535,11 @@ async function generate(config, configPath, options = {}) {
6359
6535
  if (options.requireFiles && !ctx.config.emitTokensOnly) assertFilesMatched(ctx);
6360
6536
  await build(ctx, watch ? sourceScanCache : void 0);
6361
6537
  if (watch) {
6362
- ctx.watchConfig(async () => {
6538
+ ctx.watchConfig(async (_file, reloaded) => {
6363
6539
  const affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
6364
6540
  ctx = new BambooContext(conf);
6365
6541
  });
6542
+ reloaded(ctx);
6366
6543
  sourceScanCache.entries.clear();
6367
6544
  sourceScanCache.resolvedTokenReferences.clear();
6368
6545
  logger.info("ctx:updated", "config rebuilt ✅");
@@ -6370,7 +6547,8 @@ async function generate(config, configPath, options = {}) {
6370
6547
  config: ctx.config,
6371
6548
  changes: affecteds
6372
6549
  });
6373
- return build(ctx, sourceScanCache, artifactsToRebuild(affecteds));
6550
+ await build(ctx, sourceScanCache, artifactsToRebuild(affecteds));
6551
+ return ctx;
6374
6552
  }, {
6375
6553
  cwd,
6376
6554
  poll
Binary file
Binary file
Binary file
Binary file
Binary file