@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.cjs CHANGED
@@ -615,6 +615,112 @@ async function analyze(ctx, options = {}) {
615
615
  ctx.runtime.fs.ensureDirSync(ctx.runtime.path.dirname(filePath));
616
616
  return ctx.runtime.fs.writeFile(filePath, JSON.stringify(value, replacer, 2));
617
617
  };
618
+ /**
619
+ * The tokens and keyframes the build's own prune removes, worked out once and shared by every
620
+ * report that speaks of use, so none of them can call a name unused that `getUnused` does not,
621
+ * or the other way round.
622
+ *
623
+ * Run with every prune on, whatever the config says, so a name here is one the stylesheet ships
624
+ * without. Anything the prune keeps for a reader it cannot follow — a `token()` path built at
625
+ * runtime, a theme, a `keepTokens` pattern — is kept here too: being told a token is unused when
626
+ * something still asks for it is worse than not being told at all.
627
+ *
628
+ * Read off a sheet of its own. The prune's settings are laid over the context's while it is
629
+ * built, and `unresolvedPath` is off for it: that one only decides how loudly the prune says what
630
+ * it could not read, and a project that does not prune tokens never hears it.
631
+ */
632
+ let pruned;
633
+ const prunedNames = () => {
634
+ if (pruned) return pruned;
635
+ const prune = {
636
+ ...ctx.config.prune,
637
+ keyframes: true,
638
+ unresolvedPath: "off"
639
+ };
640
+ if (prune.tokens === false) delete prune.tokens;
641
+ const configured = ctx.config.prune;
642
+ ctx.config.prune = prune;
643
+ let sheet;
644
+ try {
645
+ sheet = assembleExtractedSheet(ctx, {
646
+ parserResults,
647
+ prunePreflight: false
648
+ });
649
+ } finally {
650
+ ctx.config.prune = configured;
651
+ }
652
+ const declared = /* @__PURE__ */ new Set();
653
+ const keyframes = /* @__PURE__ */ new Set();
654
+ sheet.layers.tokens.walkDecls((decl) => {
655
+ if (decl.prop.startsWith("--")) declared.add(decl.prop);
656
+ });
657
+ sheet.layers.tokens.walkAtRules(/keyframes$/, (rule) => {
658
+ keyframes.add(rule.params.trim().replace(/^(["'])(.*)\1$/, "$2").replace(/\\(.)/g, "$1"));
659
+ });
660
+ const declarable = /* @__PURE__ */ new Set();
661
+ for (const vars of ctx.tokens.view.vars.values()) for (const name of vars.keys()) declarable.add(name);
662
+ const judged = /* @__PURE__ */ new Map();
663
+ const unused = /* @__PURE__ */ new Map();
664
+ const tokens = [];
665
+ const add = (into, category, name) => {
666
+ const names = into.get(category) ?? /* @__PURE__ */ new Set();
667
+ names.add(name);
668
+ into.set(category, names);
669
+ };
670
+ for (const token of ctx.tokens.allTokens) {
671
+ const { isVirtual, isNegative, category } = token.extensions;
672
+ if (isVirtual || isNegative || category === "breakpoints" || token.name.startsWith("sizes.breakpoint-")) continue;
673
+ const name = token.extensions.var;
674
+ if (!declarable.has(name)) continue;
675
+ if (category) add(judged, category, token.extensions.prop);
676
+ if (declared.has(name)) continue;
677
+ tokens.push(token.name);
678
+ if (category) add(unused, category, token.extensions.prop);
679
+ }
680
+ pruned = {
681
+ tokens: [...new Set(tokens)].sort(),
682
+ keyframes: Object.keys(ctx.config.theme?.keyframes ?? {}).filter((name) => !keyframes.has(name)).sort(),
683
+ judged,
684
+ unused
685
+ };
686
+ return pruned;
687
+ };
688
+ const { staticCss } = ctx.config;
689
+ const emitted = (rules) => (name) => rules === "*" || rules != null && typeof rules === "object" && name in rules;
690
+ const unusedPatterns = () => {
691
+ const kept = emitted(staticCss?.patterns);
692
+ return reporter.getPatternReport().filter((entry) => !entry.usedCount && !kept(entry.patternName)).map((entry) => entry.patternName).sort();
693
+ };
694
+ /**
695
+ * The configured names no source uses, of the kinds asked for.
696
+ *
697
+ * Tokens and keyframes are what the build's own prune removes; see `prunedNames`. A recipe or a
698
+ * pattern is one no source calls and `staticCss` does not emit regardless.
699
+ */
700
+ const getUnused = (kinds = [
701
+ "tokens",
702
+ "recipes",
703
+ "patterns",
704
+ "keyframes"
705
+ ]) => {
706
+ const unused = {
707
+ tokens: [],
708
+ recipes: [],
709
+ patterns: [],
710
+ keyframes: []
711
+ };
712
+ if (kinds.includes("tokens")) unused.tokens = prunedNames().tokens;
713
+ if (kinds.includes("keyframes")) unused.keyframes = prunedNames().keyframes;
714
+ if (kinds.includes("recipes")) {
715
+ const called = new Set(reporter.getRecipeReport().map((entry) => entry.recipeName));
716
+ const inConfig = emitted(staticCss?.recipes);
717
+ const { recipes = {}, slotRecipes = {} } = ctx.config.theme ?? {};
718
+ const ofItself = (name) => Boolean((recipes[name] ?? slotRecipes[name])?.staticCss?.length);
719
+ unused.recipes = [...ctx.recipes.keys].filter((name) => !called.has(name) && !inConfig(name) && !ofItself(name)).sort();
720
+ }
721
+ if (kinds.includes("patterns")) unused.patterns = unusedPatterns();
722
+ return unused;
723
+ };
618
724
  return {
619
725
  getRecipeReport(format = "table") {
620
726
  const report = reporter.getRecipeReport();
@@ -623,104 +729,47 @@ async function analyze(ctx, options = {}) {
623
729
  formatted: formatRecipeReport(report, format)
624
730
  };
625
731
  },
732
+ /** Each category's tokens, counted as used exactly when the build keeps them. */
626
733
  getTokenReport(format = "table") {
627
- const report = reporter.getTokenReport();
734
+ const { judged, unused } = prunedNames();
735
+ const report = reporter.getTokenReport({
736
+ judged,
737
+ unused
738
+ });
628
739
  return {
629
740
  report,
630
741
  formatted: formatTokenReport(report.getSummary(), format)
631
742
  };
632
743
  },
633
- /** Every pattern the config defines, and how often each is called. */
634
- getPatternReport: () => reporter.getPatternReport(),
744
+ /** Every pattern the config defines, how often each is called, and whether anything uses it. */
745
+ getPatternReport: () => {
746
+ const unused = new Set(unusedPatterns());
747
+ return reporter.getPatternReport().map((entry) => ({
748
+ ...entry,
749
+ unused: unused.has(entry.patternName)
750
+ }));
751
+ },
635
752
  /** Every style property written, and how often. */
636
753
  getUtilityReport: () => reporter.getUtilityReport(),
637
- /** Every keyframe the theme defines, and how often an animation names it. */
638
- getKeyframeReport: () => reporter.getKeyframeReport(),
639
- /**
640
- * The configured names no source uses, of the kinds asked for.
641
- *
642
- * Tokens and keyframes are what the build's own prune removes, run with every prune on
643
- * whatever the config says, so a name here is one the stylesheet already ships without.
644
- * Anything the prune keeps for a reader it cannot follow — a `token()` path built at runtime,
645
- * a theme, a `keepTokens` pattern — is kept here too, and not listed: being told a token is
646
- * unused when something still asks for it is worse than not being told at all. A recipe or a
647
- * pattern is one no source calls and `staticCss` does not emit regardless.
648
- *
649
- * Read off a sheet of its own. The prune's settings are laid over the context's while it is
650
- * built, and `unresolvedPath` is off for it: that one only decides how loudly the prune says
651
- * what it could not read, and a project that does not prune tokens never hears it.
652
- */
653
- getUnused(kinds = [
654
- "tokens",
655
- "recipes",
656
- "patterns",
657
- "keyframes"
658
- ]) {
659
- const unused = {
660
- tokens: [],
661
- recipes: [],
662
- patterns: [],
663
- keyframes: []
664
- };
665
- if (kinds.includes("tokens") || kinds.includes("keyframes")) {
666
- const prune = {
667
- ...ctx.config.prune,
668
- keyframes: true,
669
- unresolvedPath: "off"
670
- };
671
- if (prune.tokens === false) delete prune.tokens;
672
- const configured = ctx.config.prune;
673
- ctx.config.prune = prune;
674
- let sheet;
675
- try {
676
- sheet = assembleExtractedSheet(ctx, {
677
- parserResults,
678
- prunePreflight: false
679
- });
680
- } finally {
681
- ctx.config.prune = configured;
682
- }
683
- const declared = /* @__PURE__ */ new Set();
684
- const keyframes = /* @__PURE__ */ new Set();
685
- sheet.layers.tokens.walkDecls((decl) => {
686
- if (decl.prop.startsWith("--")) declared.add(decl.prop);
687
- });
688
- sheet.layers.tokens.walkAtRules(/keyframes$/, (rule) => {
689
- keyframes.add(rule.params.trim().replace(/^(["'])(.*)\1$/, "$2").replace(/\\(.)/g, "$1"));
690
- });
691
- const declarable = /* @__PURE__ */ new Set();
692
- for (const vars of ctx.tokens.view.vars.values()) for (const name of vars.keys()) declarable.add(name);
693
- const tokens = /* @__PURE__ */ new Set();
694
- for (const token of ctx.tokens.allTokens) {
695
- const { isVirtual, isNegative, category } = token.extensions;
696
- if (isVirtual || isNegative || category === "breakpoints" || token.name.startsWith("sizes.breakpoint-")) continue;
697
- const name = token.extensions.var;
698
- if (declarable.has(name) && !declared.has(name)) tokens.add(token.name);
699
- }
700
- if (kinds.includes("tokens")) unused.tokens = [...tokens].sort();
701
- if (kinds.includes("keyframes")) unused.keyframes = Object.keys(ctx.config.theme?.keyframes ?? {}).filter((name) => !keyframes.has(name)).sort();
702
- }
703
- const { staticCss } = ctx.config;
704
- const emitted = (rules) => (name) => rules === "*" || rules != null && typeof rules === "object" && name in rules;
705
- if (kinds.includes("recipes")) {
706
- const called = new Set(reporter.getRecipeReport().map((entry) => entry.recipeName));
707
- const inConfig = emitted(staticCss?.recipes);
708
- const { recipes = {}, slotRecipes = {} } = ctx.config.theme ?? {};
709
- const ofItself = (name) => Boolean((recipes[name] ?? slotRecipes[name])?.staticCss?.length);
710
- unused.recipes = [...ctx.recipes.keys].filter((name) => !called.has(name) && !inConfig(name) && !ofItself(name)).sort();
711
- }
712
- if (kinds.includes("patterns")) {
713
- const kept = emitted(staticCss?.patterns);
714
- unused.patterns = reporter.getPatternReport().filter((entry) => !entry.usedCount && !kept(entry.patternName)).map((entry) => entry.patternName).sort();
715
- }
716
- return unused;
754
+ /** Every keyframe the theme defines, how often an animation names it, and whether the build keeps it. */
755
+ getKeyframeReport: () => {
756
+ const unused = new Set(prunedNames().keyframes);
757
+ return reporter.getKeyframeReport().map((entry) => ({
758
+ ...entry,
759
+ unused: unused.has(entry.keyframe)
760
+ }));
717
761
  },
762
+ getUnused,
718
763
  /** The names as JSON, of the kinds `getUnused` was asked for. */
719
764
  writeUnused(filePath, unused) {
720
765
  return writeJson(filePath, unused);
721
766
  },
767
+ /** The extraction report, with what `getUnused` makes of it, so the file cannot be read as calling a kept name unused. */
722
768
  writeReport(filePath) {
723
- return writeJson(filePath, reporter.report);
769
+ return writeJson(filePath, {
770
+ ...reporter.report,
771
+ unused: getUnused()
772
+ });
724
773
  }
725
774
  };
726
775
  }
@@ -2907,6 +2956,7 @@ var DiffEngine = class {
2907
2956
  if (!affected.hasConfigChanged) {
2908
2957
  applyTsConfig(this.ctx.conf, conf);
2909
2958
  rememberTsConfigResolutionFiles(this.ctx.conf, getTsConfigResolutionFiles(conf));
2959
+ this.ctx.conf.dependencies = conf.dependencies;
2910
2960
  }
2911
2961
  return affected;
2912
2962
  }
@@ -2971,6 +3021,14 @@ var ParserResult = class {
2971
3021
  */
2972
3022
  deadCalls = [];
2973
3023
  /**
3024
+ * `token()` and `token.value()` calls naming no token.
3025
+ *
3026
+ * Each returns `undefined`, so a property it was written into never reaches the encoder and
3027
+ * nothing else records it. Graded by the token half of `unresolvedToken` — see
3028
+ * `Generator.unresolvedTokenCalls` for where they are reported.
3029
+ */
3030
+ unresolvedTokenCalls = [];
3031
+ /**
2974
3032
  * Whether each result item is attributed to its call site, for a source map.
2975
3033
  *
2976
3034
  * Off for a source a `parser:before` hook rewrote: its positions are the hook's output's,
@@ -3518,9 +3576,15 @@ const nodeRuntime = {
3518
3576
  } : false
3519
3577
  });
3520
3578
  _bamboocss_logger.logger.debug("watch:file", `Watching [ ${dirnames.join(", ")} ]`);
3521
- process.once("SIGINT", async () => {
3579
+ const onInterrupt = async () => {
3522
3580
  await watcher.close();
3523
- });
3581
+ };
3582
+ process.once("SIGINT", onInterrupt);
3583
+ const close = watcher.close.bind(watcher);
3584
+ watcher.close = () => {
3585
+ process.off("SIGINT", onInterrupt);
3586
+ return close();
3587
+ };
3524
3588
  return watcher;
3525
3589
  }
3526
3590
  }
@@ -4285,6 +4349,7 @@ var BambooContext = class extends _bamboocss_generator.Generator {
4285
4349
  this.nativeConfigurationFiles.delete(file);
4286
4350
  this.nativeExtractions.delete(file);
4287
4351
  this.nativeSourceMetadata.delete(file);
4352
+ this.unresolvedTokenCalls.delete(this.runtime.path.abs(this.config.cwd, filePath));
4288
4353
  };
4289
4354
  parseNativeFile = (filePath, native, encoder) => {
4290
4355
  if (native.errors.length) throw new _bamboocss_shared.BambooError("NATIVE_EXTRACTION", `Native extraction failed for ${filePath}:\n${native.errors.join("\n")}`);
@@ -4295,6 +4360,7 @@ var BambooContext = class extends _bamboocss_generator.Generator {
4295
4360
  for (const dependency of native.dependencies) result.addDependency(dependency);
4296
4361
  const metadata = this.nativeSourceMetadata.get(filePath.replaceAll("\\", "/"));
4297
4362
  result.origins = metadata?.origins ?? true;
4363
+ let tokenTable;
4298
4364
  for (const call of native.calls) {
4299
4365
  const atomOrigin = encoder.recordOrigins && result.origins ? {
4300
4366
  filePath,
@@ -4353,8 +4419,24 @@ var BambooContext = class extends _bamboocss_generator.Generator {
4353
4419
  });
4354
4420
  else if (call.kind === "pattern") result.setPattern(call.importedName, item);
4355
4421
  else if (call.kind === "recipe") result.setRecipe(call.importedName, item, new Set(call.unresolvedKeys));
4356
- else if (call.kind === "token" || call.kind === "tokenValue") result.setToken(item, call.kind);
4357
- else if (call.kind === "dead") result.deadCalls.push({
4422
+ else if (call.kind === "token" || call.kind === "tokenValue") {
4423
+ result.setToken(item, call.kind);
4424
+ if (call.complete && !call.guarded) {
4425
+ tokenTable ??= this.tokens.view.values;
4426
+ for (let index = 0; index < call.arguments.length; index++) {
4427
+ const path = call.arguments[index];
4428
+ if (typeof path !== "string" || tokenTable.has(path)) continue;
4429
+ if (call.arguments.indexOf(path) !== index) continue;
4430
+ const unresolved = this.utility.unresolvedTokenCall(call.kind === "token" ? "token" : "token.value", path);
4431
+ if (unresolved) result.unresolvedTokenCalls.push({
4432
+ call: unresolved,
4433
+ filePath,
4434
+ line: call.line,
4435
+ column: call.column
4436
+ });
4437
+ }
4438
+ }
4439
+ } else if (call.kind === "dead") result.deadCalls.push({
4358
4440
  name: call.importedName,
4359
4441
  alias: call.name,
4360
4442
  mod: call.module,
@@ -4383,6 +4465,7 @@ var BambooContext = class extends _bamboocss_generator.Generator {
4383
4465
  encoder.releaseFile(file);
4384
4466
  this.parseFailures.delete(file);
4385
4467
  this.deadCalls.delete(file);
4468
+ this.unresolvedTokenCalls.delete(file);
4386
4469
  measure();
4387
4470
  return;
4388
4471
  }
@@ -4402,11 +4485,45 @@ var BambooContext = class extends _bamboocss_generator.Generator {
4402
4485
  this.reportUnresolvedStyles(result);
4403
4486
  if (result.deadCalls.length) this.deadCalls.set(file, result.deadCalls);
4404
4487
  else this.deadCalls.delete(file);
4488
+ this.recordUnresolvedTokenCalls(file, result);
4405
4489
  }
4406
4490
  measure();
4407
4491
  return result;
4408
4492
  };
4409
4493
  /**
4494
+ * Keep a file's `token()` calls naming no token for the sheet's check, and warn about them when
4495
+ * the token half of `unresolvedToken` is `warn`.
4496
+ *
4497
+ * Set or deleted on every parse, like `deadCalls` and for the same reason: a file read again
4498
+ * without them has fixed them, and an entry outliving the fix would fail every later build. A
4499
+ * file under `outdir` is left out, as `reportUnresolvedStyles` leaves it: nothing there is the
4500
+ * author's to rewrite.
4501
+ */
4502
+ recordUnresolvedTokenCalls = (file, result) => {
4503
+ const found = this.isGenerated(file) ? [] : result.unresolvedTokenCalls;
4504
+ if (!found.length) {
4505
+ this.unresolvedTokenCalls.delete(file);
4506
+ return;
4507
+ }
4508
+ const sites = found.map(({ call, line, column }) => ({
4509
+ call,
4510
+ where: `${this.relative(file)}:${line}:${column}`
4511
+ }));
4512
+ this.unresolvedTokenCalls.set(file, sites);
4513
+ if (this.utility.unresolvedToken.token !== "warn") return;
4514
+ for (const { call, where } of sites) _bamboocss_logger.logger.warn("token", `${where} — ${this.utility.explainUnresolvedTokenCall(call)}`);
4515
+ };
4516
+ /**
4517
+ * Drop the `token()` call findings of every file outside `files`, as `assertNoDeadCalls` drops
4518
+ * its own: one deleted or taken out of `include` is not parsed again, so its entry would fail
4519
+ * every later sheet, naming a file that is no longer part of the build.
4520
+ */
4521
+ forgetUnresolvedTokenCallsOutside = (files) => {
4522
+ if (!this.unresolvedTokenCalls.size) return;
4523
+ const inScope = new Set(Array.from(files, (file) => this.runtime.path.abs(this.config.cwd, file)));
4524
+ for (const file of this.unresolvedTokenCalls.keys()) if (!inScope.has(file)) this.unresolvedTokenCalls.delete(file);
4525
+ };
4526
+ /**
4410
4527
  * Extract every file in one pass, and fail on the ones that could not be read.
4411
4528
  *
4412
4529
  * Routed through `parseFile` rather than parsing directly, so the two entry points cannot
@@ -4475,6 +4592,7 @@ var BambooContext = class extends _bamboocss_generator.Generator {
4475
4592
  if (encoder.isEmpty()) return;
4476
4593
  filesWithCss.push(file);
4477
4594
  });
4595
+ this.forgetUnresolvedTokenCallsOutside(files);
4478
4596
  this.assertExtracted(files);
4479
4597
  this.assertNoDeadCalls(files);
4480
4598
  return {
@@ -4536,23 +4654,80 @@ var BambooContext = class extends _bamboocss_generator.Generator {
4536
4654
  if (fs.existsSync(recipesIndex)) fs.rmFileSync(recipesIndex);
4537
4655
  if (fs.existsSync(recipesDir)) fs.rmFileSync(recipesDir);
4538
4656
  };
4657
+ /**
4658
+ * Call `cb` when a file the config is built from changes.
4659
+ *
4660
+ * `cb` reloads the config, and hands the context it built to `reloaded` as soon as it has one, so
4661
+ * the watch can follow what that config is built from. Armed once with this context's files, an
4662
+ * edit that swapped in a preset, or imported one more module, left the new file unwatched:
4663
+ * editing it did nothing until the process restarted. Handed over before `cb` builds, because a
4664
+ * build can fail where the reload did not — a recipe in the new preset naming no token — and the
4665
+ * file to fix is that preset.
4666
+ */
4539
4667
  watchConfig = (cb, opts) => {
4540
4668
  const { cwd, poll, exclude } = opts ?? {};
4541
4669
  _bamboocss_logger.logger.info("ctx:watch", this.messages.configWatch());
4542
- const watcher = this.runtime.fs.watch({
4543
- include: (0, _bamboocss_shared.uniq)([...this.explicitDeps, ...this.conf.dependencies]),
4544
- exclude,
4545
- cwd,
4546
- poll
4547
- });
4670
+ const arm = (include) => {
4671
+ const watcher = this.runtime.fs.watch({
4672
+ include,
4673
+ exclude,
4674
+ cwd,
4675
+ poll
4676
+ });
4677
+ watcher.on("all", (event, file) => {
4678
+ if (event === "add" || event === "change") rebuild(file);
4679
+ });
4680
+ return watcher;
4681
+ };
4682
+ let files = this.configFiles();
4683
+ let watcher = arm(files);
4684
+ const rearm = async (nextFiles) => {
4685
+ if (nextFiles.join("\n") === files.join("\n")) return;
4686
+ const previous = watcher;
4687
+ files = nextFiles;
4688
+ watcher = arm(files);
4689
+ await previous.close();
4690
+ };
4548
4691
  const rebuild = (0, perfect_debounce.debounce)(async (file) => {
4549
4692
  _bamboocss_logger.logger.info("ctx:change", "config changed, rebuilding...");
4550
- await reportRebuildFailure(() => cb(file));
4551
- });
4552
- watcher.on("all", (event, file) => {
4553
- if (event === "add" || event === "change") rebuild(file);
4693
+ const reload = {};
4694
+ try {
4695
+ const next = await cb(file, (ctx) => {
4696
+ reload.ctx = ctx;
4697
+ });
4698
+ if (next) reload.ctx = next;
4699
+ } catch (error) {
4700
+ _bamboocss_logger.logger.error("ctx:rebuild", error instanceof Error ? error.message : String(error));
4701
+ const reloaded = reload.ctx;
4702
+ const nextFiles = reloaded ? reloaded.configFiles() : (0, _bamboocss_shared.uniq)([
4703
+ ...files,
4704
+ ...this.importedFiles(),
4705
+ ...(0, _bamboocss_config.filesReadBy)(error)
4706
+ ]).sort();
4707
+ await reportRebuildFailure(() => rearm(nextFiles));
4708
+ return;
4709
+ }
4710
+ const reloaded = reload.ctx;
4711
+ if (reloaded) await reportRebuildFailure(() => rearm(reloaded.configFiles()));
4554
4712
  });
4555
4713
  };
4714
+ /**
4715
+ * The files the config is built from: the config, what it imports, the presets it names by path,
4716
+ * and its `dependencies` — as patterns too, so a file that starts to match one is seen.
4717
+ */
4718
+ configFiles = () => (0, _bamboocss_shared.uniq)([
4719
+ ...this.explicitDeps,
4720
+ ...this.conf.dependencies,
4721
+ ...this.config.dependencies ?? []
4722
+ ]).sort();
4723
+ /** What the config file imports, read off its source without running it, for a config that failed to load. */
4724
+ importedFiles = () => {
4725
+ try {
4726
+ return [...(0, _bamboocss_config.getConfigDependencies)(this.conf.path, this.conf.tsOptions, this.conf.tsconfig?.compilerOptions).deps];
4727
+ } catch {
4728
+ return [];
4729
+ }
4730
+ };
4556
4731
  watchFiles = (cb, opts) => {
4557
4732
  const { include, exclude, poll, cwd } = this.config;
4558
4733
  _bamboocss_logger.logger.info("ctx:watch", this.messages.watch());
@@ -5932,6 +6107,7 @@ var Builder = class {
5932
6107
  this.snapshotResolutionConfigurations();
5933
6108
  this.affectedFiles = void 0;
5934
6109
  this.extractionOrder = void 0;
6110
+ ctx.forgetUnresolvedTokenCallsOutside(files);
5935
6111
  ctx.assertExtracted(files);
5936
6112
  ctx.assertNoDeadCalls(files);
5937
6113
  };
@@ -6371,10 +6547,11 @@ async function generate(config, configPath, options = {}) {
6371
6547
  if (options.requireFiles && !ctx.config.emitTokensOnly) assertFilesMatched(ctx);
6372
6548
  await build(ctx, watch ? sourceScanCache : void 0);
6373
6549
  if (watch) {
6374
- ctx.watchConfig(async () => {
6550
+ ctx.watchConfig(async (_file, reloaded) => {
6375
6551
  const affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
6376
6552
  ctx = new BambooContext(conf);
6377
6553
  });
6554
+ reloaded(ctx);
6378
6555
  sourceScanCache.entries.clear();
6379
6556
  sourceScanCache.resolvedTokenReferences.clear();
6380
6557
  _bamboocss_logger.logger.info("ctx:updated", "config rebuilt ✅");
@@ -6382,7 +6559,8 @@ async function generate(config, configPath, options = {}) {
6382
6559
  config: ctx.config,
6383
6560
  changes: affecteds
6384
6561
  });
6385
- return build(ctx, sourceScanCache, artifactsToRebuild(affecteds));
6562
+ await build(ctx, sourceScanCache, artifactsToRebuild(affecteds));
6563
+ return ctx;
6386
6564
  }, {
6387
6565
  cwd,
6388
6566
  poll
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { n as markStaticCompilerActive, t as isStaticCompilerActive } from "./static-compiler-C1QNL5nu.cjs";
2
2
  import { ReportFormat } from "@bamboocss/reporter";
3
3
  import { AnalysisOptions, Artifact, ArtifactId, BambooHooks, Config, CssArtifactType, DiffConfigResult, LoadConfigResult, ParserResultInterface, ResultItem, Runtime, SpecFile, WatchOptions, WatcherEventType } from "@bamboocss/types";
4
- import { DeadImport, ParserOptions, StyleEncoder, Stylesheet } from "@bamboocss/core";
4
+ import { DeadImport, ParserOptions, StyleEncoder, Stylesheet, UnresolvedTokenCall } from "@bamboocss/core";
5
5
  import { Generator, generatePackageExports } from "@bamboocss/generator";
6
6
 
7
7
  //#region ../native-extractor/index.d.ts
@@ -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