@bamboocss/node 1.46.3 → 1.48.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/README.md CHANGED
@@ -3,9 +3,9 @@
3
3
  The Node runtime behind Bamboo CSS: config loading, context creation, extraction and the write side of codegen and
4
4
  `styles.css`.
5
5
 
6
- This is an internal package. It is what `@bamboocss/dev` (the CLI), `@bamboocss/postcss` and `@bamboocss/vite` are built
7
- on, and it is versioned with them — most projects should install one of those instead. User-facing documentation lives
8
- at [bamboocss.com/docs](https://bamboocss.com/docs).
6
+ This is an internal package. It is what `@bamboocss/dev` (the CLI) and `@bamboocss/vite` are built on, and it is
7
+ versioned with them — most projects should install one of those instead. User-facing documentation lives at
8
+ [bamboocss.com/docs](https://bamboocss.com/docs).
9
9
 
10
10
  ## Exports
11
11
 
@@ -18,8 +18,7 @@ Everything below is exported from `@bamboocss/node`.
18
18
  - `BambooContext` – the resolved config plus everything derived from it: tokens, utilities, conditions, recipes,
19
19
  patterns, the `ts-morph` project, the output engine and the diff engine.
20
20
  - `Builder` – the incremental driver the bundler plugins use. It owns context setup, tracks which files and config
21
- dependencies changed, re-extracts only those, and hands back the stylesheet (`toCss`) or writes it into a PostCSS root
22
- (`write`).
21
+ dependencies changed, re-extracts only those, and hands back the stylesheet (`toCss`).
23
22
 
24
23
  ### Commands
25
24
 
@@ -35,10 +34,8 @@ Each takes a `BambooContext`, and each backs the CLI command of the same name.
35
34
 
36
35
  ### Setup and utilities
37
36
 
38
- - `setupConfig(cwd, options?)` / `setupPostcss(cwd)` – scaffold `bamboo.config.ts` and the PostCSS config.
37
+ - `setupConfig(cwd, options?)` – scaffold `bamboo.config.ts`.
39
38
  - `setupGitIgnore(ctx)` – add the outdir to `.gitignore`, unless `config.gitignore` is off.
40
- - `parseDependency(fileOrGlob)` – turn a `config.dependencies` entry into a PostCSS `dependency` or `dir-dependency`
41
- message.
42
39
  - `setLogStream({ cwd, logfile })` – tee logs to a file.
43
40
  - `startProfiling(cwd, prefix, isWatching?)` – start a V8 CPU profile; the returned function stops it and writes
44
41
  `bamboo-{prefix}-{timestamp}.cpuprofile` into `cwd`.
package/dist/index.cjs CHANGED
@@ -26,13 +26,13 @@ const require_static_compiler = require("./static-compiler.cjs");
26
26
  let _bamboocss_reporter = require("@bamboocss/reporter");
27
27
  let _bamboocss_logger = require("@bamboocss/logger");
28
28
  let _bamboocss_config = require("@bamboocss/config");
29
- let _bamboocss_core = require("@bamboocss/core");
30
29
  let _bamboocss_shared = require("@bamboocss/shared");
31
30
  let node_crypto = require("node:crypto");
32
31
  let fs = require("fs");
33
32
  let path = require("path");
34
33
  let _bamboocss_plugin_svelte = require("@bamboocss/plugin-svelte");
35
34
  let _bamboocss_plugin_vue = require("@bamboocss/plugin-vue");
35
+ let _bamboocss_core = require("@bamboocss/core");
36
36
  let _bamboocss_generator = require("@bamboocss/generator");
37
37
  let _bamboocss_parser = require("@bamboocss/parser");
38
38
  let perfect_debounce = require("perfect-debounce");
@@ -55,10 +55,6 @@ let fs_extra = require("fs-extra");
55
55
  fs_extra = __toESM(fs_extra);
56
56
  let picomatch = require("picomatch");
57
57
  picomatch = __toESM(picomatch);
58
- let is_glob = require("is-glob");
59
- is_glob = __toESM(is_glob);
60
- let glob_parent = require("glob-parent");
61
- glob_parent = __toESM(glob_parent);
62
58
  let matcher = require("matcher");
63
59
  let _bamboocss_config_ts_path = require("@bamboocss/config/ts-path");
64
60
  let node_readline = require("node:readline");
@@ -2298,7 +2294,7 @@ var BambooContext = class extends _bamboocss_generator.Generator {
2298
2294
  const rootDir = this.paths.root;
2299
2295
  const stylesDir = [...rootDir, "styles"];
2300
2296
  const artifacts = this.getSplitCssArtifacts(sheet);
2301
- const subDirs = new Set([...artifacts.recipes, ...artifacts.themes].map((a) => a.dir).filter(Boolean));
2297
+ const subDirs = new Set(artifacts.themes.map((a) => a.dir).filter(Boolean));
2302
2298
  fs.ensureDirSync(pathUtil.join(...stylesDir));
2303
2299
  subDirs.forEach((dir) => fs.ensureDirSync(pathUtil.join(...stylesDir, dir)));
2304
2300
  const styleFiles = [];
@@ -2309,20 +2305,6 @@ var BambooContext = class extends _bamboocss_generator.Generator {
2309
2305
  });
2310
2306
  _bamboocss_logger.logger.info("css", pathUtil.join(...stylesDir, layer.file));
2311
2307
  }
2312
- for (const recipe of artifacts.recipes) {
2313
- styleFiles.push({
2314
- file: `${recipe.dir}/${recipe.file}`,
2315
- code: recipe.code
2316
- });
2317
- _bamboocss_logger.logger.info("css", pathUtil.join(...stylesDir, recipe.dir, recipe.file));
2318
- }
2319
- if (artifacts.recipes.length) {
2320
- styleFiles.push({
2321
- file: "recipes.css",
2322
- code: artifacts.recipesIndex
2323
- });
2324
- _bamboocss_logger.logger.info("css", pathUtil.join(...stylesDir, "recipes.css"));
2325
- }
2326
2308
  for (const theme of artifacts.themes) {
2327
2309
  styleFiles.push({
2328
2310
  file: `${theme.dir}/${theme.file}`,
@@ -2344,6 +2326,10 @@ var BambooContext = class extends _bamboocss_generator.Generator {
2344
2326
  code: artifacts.index
2345
2327
  }]
2346
2328
  });
2329
+ const recipesIndex = pathUtil.join(...stylesDir, "recipes.css");
2330
+ const recipesDir = pathUtil.join(...stylesDir, "recipes");
2331
+ if (fs.existsSync(recipesIndex)) fs.rmFileSync(recipesIndex);
2332
+ if (fs.existsSync(recipesDir)) fs.rmFileSync(recipesDir);
2347
2333
  };
2348
2334
  watchConfig = (cb, opts) => {
2349
2335
  const { cwd, poll, exclude } = opts ?? {};
@@ -2447,44 +2433,6 @@ async function loadConfigAndCreateContext(options = {}) {
2447
2433
  return new BambooContext(conf);
2448
2434
  }
2449
2435
  //#endregion
2450
- //#region src/parse-glob.ts
2451
- function parseGlob(pattern) {
2452
- let glob = pattern;
2453
- const base = (0, glob_parent.default)(pattern);
2454
- if (base !== ".") {
2455
- glob = pattern.substring(base.length);
2456
- if (glob.charAt(0) === "/") glob = glob.substring(1);
2457
- }
2458
- if (glob.substring(0, 2) === "./") glob = glob.substring(2);
2459
- if (glob.charAt(0) === "/") glob = glob.substring(1);
2460
- return {
2461
- base,
2462
- glob
2463
- };
2464
- }
2465
- //#endregion
2466
- //#region src/parse-dependency.ts
2467
- function parseDependency(fileOrGlob) {
2468
- if (fileOrGlob.startsWith("!")) return null;
2469
- let message = null;
2470
- if ((0, is_glob.default)(fileOrGlob)) {
2471
- const { base, glob } = parseGlob(fileOrGlob);
2472
- message = {
2473
- type: "dir-dependency",
2474
- dir: (0, path.normalize)((0, path.resolve)(base)),
2475
- glob
2476
- };
2477
- } else message = {
2478
- type: "dependency",
2479
- file: (0, path.normalize)((0, path.resolve)(fileOrGlob))
2480
- };
2481
- if (message.type === "dir-dependency" && process.env.ROLLUP_WATCH === "true") message = {
2482
- type: "dependency",
2483
- file: (0, path.normalize)((0, path.resolve)(message.dir))
2484
- };
2485
- return message;
2486
- }
2487
- //#endregion
2488
2436
  //#region src/source-snapshots.ts
2489
2437
  /**
2490
2438
  * Every file `include` covers, read once.
@@ -3290,26 +3238,36 @@ function collectRenderedElements(ctx) {
3290
3238
  return found;
3291
3239
  }
3292
3240
  //#endregion
3293
- //#region src/builder.ts
3294
- const fileModifiedMap = /* @__PURE__ */ new Map();
3241
+ //#region src/assemble-sheet.ts
3295
3242
  /**
3296
- * The declaration that says generated css is already present in a root.
3243
+ * One stylesheet from an already-extracted encoder.
3297
3244
  *
3298
- * `generateGlobalCss` emits it unconditionally and `appendBaselineCss` always reaches that
3299
- * artifact, so anything carrying it holds a copy of the sheet however it got there — written
3300
- * by `write` on an earlier pass, or inlined from `styles.css` by `postcss-import`.
3301
- *
3302
- * A declaration rather than a comment because it has to survive the css being minified
3303
- * between the copy landing and this check running, which a comment does not.
3245
+ * Vite, `bamboo cssgen`, and the CLI `bamboo` command all finish here so a recipe lowered to
3246
+ * atoms cannot have a different sheet depending on which integration asked for it.
3304
3247
  */
3305
- const GENERATED_SENTINEL = "--made-with-bamboo";
3306
- function hasGeneratedCss(root) {
3307
- let found = false;
3308
- root.walkDecls(GENERATED_SENTINEL, () => {
3309
- found = true;
3310
- });
3311
- return found;
3312
- }
3248
+ const assembleExtractedSheet = (ctx, { layerParams = false, sourceScanCache, mtimeOf, sourceInventory } = {}) => {
3249
+ ctx.encoder.atomizeObservedRecipes();
3250
+ const sheet = ctx.createSheet();
3251
+ if (layerParams) {
3252
+ const recipeLayer = ctx.config.layers?.recipes ?? "recipes";
3253
+ sheet.layers.root.prepend(`@layer ${sheet.layers.layerNames.filter((name) => name !== recipeLayer).join(", ")};`);
3254
+ }
3255
+ ctx.appendBaselineCss(sheet, { atomizeRecipes: true });
3256
+ const collectElements = (0, _bamboocss_core.prunesPreflight)(ctx.config.preflight);
3257
+ const pruneKeyframes = Boolean(ctx.config.prune?.keyframes);
3258
+ const declaredKeyframes = pruneKeyframes ? keyframeNames(ctx) : [];
3259
+ const scans = ctx.config.prune?.tokens !== false || collectElements || pruneKeyframes ? collectSourceScans(ctx, {
3260
+ keyframeNames: declaredKeyframes,
3261
+ elements: collectElements
3262
+ }, sourceScanCache, mtimeOf, sourceInventory) : void 0;
3263
+ const reachableVars = pruneTokensForBuild(ctx, sheet, [], scans);
3264
+ if (collectElements && scans) ctx.prunePreflight(sheet, scans.elements);
3265
+ if (pruneKeyframes && scans) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3266
+ return sheet;
3267
+ };
3268
+ //#endregion
3269
+ //#region src/builder.ts
3270
+ const fileModifiedMap = /* @__PURE__ */ new Map();
3313
3271
  var Builder = class {
3314
3272
  /**
3315
3273
  * The current bamboo context
@@ -3320,7 +3278,6 @@ var Builder = class {
3320
3278
  explicitDepsMeta;
3321
3279
  affecteds;
3322
3280
  configDependencies = /* @__PURE__ */ new Set();
3323
- pendingConfigCrawl;
3324
3281
  /** Last complete included inventory, including members which have since been deleted. */
3325
3282
  sourceInventory;
3326
3283
  /** Existing included owners selected by the last resolution-ledger invalidation pass. */
@@ -3355,6 +3312,35 @@ var Builder = class {
3355
3312
  resolutionAffectedThisPass = false;
3356
3313
  /** Per-pass digests of re-read values, so N dependents of one edit digest each value once. */
3357
3314
  readDigestMemo = /* @__PURE__ */ new Map();
3315
+ /** Resolution ledger as it stood before this pass's first physical source mutation. */
3316
+ capturedLedger;
3317
+ /**
3318
+ * Reload one edited source, keeping the closure the next extraction pass has to select.
3319
+ *
3320
+ * An integration which shares this context has to refresh an edited module before anything
3321
+ * folds against it — a consumer is transformed before the module it imports, so the fold
3322
+ * would otherwise bake in the previous contents. Doing that through the Project directly
3323
+ * loses the graph the rebuild needs: reloading retracts the file's own forward edges, and
3324
+ * `invalidateChangedSources` reads them afterwards to find its dependents. So the mutation
3325
+ * belongs here, behind a snapshot taken before the first of them.
3326
+ *
3327
+ * Once per pass, not once per file: the first mutation is the boundary, and every later one
3328
+ * in the same event is already described by that snapshot. `refreshSourceState` consumes it.
3329
+ */
3330
+ reloadSource = (filePath) => {
3331
+ const ctx = this.getContextOrThrow();
3332
+ this.captureResolutionLedger(ctx);
3333
+ return ctx.project.reloadSourceFile(filePath);
3334
+ };
3335
+ /** The deletion half of `reloadSource`, with the same snapshot obligation. */
3336
+ removeSource = (filePath) => {
3337
+ const ctx = this.getContextOrThrow();
3338
+ this.captureResolutionLedger(ctx);
3339
+ return ctx.project.removeSourceFile(filePath);
3340
+ };
3341
+ captureResolutionLedger = (ctx) => {
3342
+ this.capturedLedger ??= ctx.project.getResolutionLedger();
3343
+ };
3358
3344
  /** @internal Current and missing resolver paths which can change the stylesheet. */
3359
3345
  getResolutionReadFiles = () => {
3360
3346
  const files = /* @__PURE__ */ new Set();
@@ -3385,41 +3371,13 @@ var Builder = class {
3385
3371
  for (const file of current) this.resolutionConfigurationBytes.set(file, this.readResolutionConfiguration(file));
3386
3372
  for (const file of this.resolutionConfigurationBytes.keys()) if (!current.has(file)) this.resolutionConfigurationBytes.delete(file);
3387
3373
  };
3388
- /**
3389
- * Remember what to crawl; do not crawl yet.
3390
- *
3391
- * The crawl walks the config's own import graph, and resolving a bare specifier there loads a
3392
- * whole TypeScript compiler. Only `registerDependency` reads the result, and only the PostCSS
3393
- * plugin calls that — the CLI and the Vite plugin (which crawls separately, when it watches)
3394
- * paid ~155ms of compiler load per build for a set neither of them ever read.
3395
- */
3396
- setConfigDependencies(options) {
3397
- this.pendingConfigCrawl = options;
3398
- const cwd = options?.cwd ?? this.context?.config.cwd ?? process.cwd();
3399
- for (const file of this.context?.conf.dependencies ?? []) this.configDependencies.add((0, path.resolve)(cwd, file));
3400
- }
3401
- /** Crawl on first read, once per `setConfigDependencies`. */
3402
- crawlConfigDependencies() {
3403
- const options = this.pendingConfigCrawl;
3404
- if (!options) return;
3405
- this.pendingConfigCrawl = void 0;
3406
- const tsOptions = this.context?.conf.tsOptions ?? {
3407
- baseUrl: void 0,
3408
- pathMappings: []
3409
- };
3410
- const compilerOptions = this.context?.conf.tsconfig?.compilerOptions ?? {};
3411
- const { deps } = (0, _bamboocss_config.getConfigDependencies)(options.configPath, tsOptions, compilerOptions);
3412
- deps.forEach((file) => this.configDependencies.add(file));
3413
- _bamboocss_logger.logger.debug("builder", "Config dependencies");
3414
- _bamboocss_logger.logger.debug("builder", deps);
3415
- }
3374
+ recordConfigDependencies = (ctx, cwd) => {
3375
+ const root = cwd ?? ctx.config.cwd;
3376
+ for (const file of (0, _bamboocss_shared.uniq)([...ctx.conf.dependencies, ...ctx.explicitDeps])) this.configDependencies.add((0, path.resolve)(root, file));
3377
+ };
3416
3378
  setup = async (options = {}) => {
3417
3379
  _bamboocss_logger.logger.debug("builder", "🚧 Setup");
3418
3380
  const configPath = options.configPath ?? (0, _bamboocss_config.findConfig)({ cwd: options.cwd });
3419
- this.setConfigDependencies({
3420
- configPath,
3421
- cwd: options.cwd
3422
- });
3423
3381
  if (!this.context) return this.setupContext({
3424
3382
  configPath,
3425
3383
  cwd: options.cwd,
@@ -3457,7 +3415,9 @@ var Builder = class {
3457
3415
  this.affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
3458
3416
  this.context = new BambooContext(conf);
3459
3417
  });
3460
- this.tsconfigResolutionFiles = this.getContextOrThrow().diff.getResolutionConfigFiles();
3418
+ const nextContext = this.getContextOrThrow();
3419
+ this.recordConfigDependencies(nextContext, options.cwd);
3420
+ this.tsconfigResolutionFiles = nextContext.diff.getResolutionConfigFiles();
3461
3421
  _bamboocss_logger.logger.debug("builder", this.affecteds);
3462
3422
  this.explicitDepsMeta = this.checkFilesChanged(this.context.explicitDeps);
3463
3423
  if (this.explicitDepsMeta.hasFilesChanged) {
@@ -3481,6 +3441,7 @@ var Builder = class {
3481
3441
  this.sourceScanCache.entries.clear();
3482
3442
  this.extractionReadsByOwner.clear();
3483
3443
  this.recipeSurfaceByOwner.clear();
3444
+ this.capturedLedger = void 0;
3484
3445
  await ctx.hooks["config:change"]?.({
3485
3446
  config: ctx.config,
3486
3447
  changes: this.affecteds
@@ -3517,7 +3478,8 @@ var Builder = class {
3517
3478
  const changedResolutionConfigurations = this.changedResolutionConfigurations();
3518
3479
  const changedResolutionSet = new Set(changedResolutionConfigurations);
3519
3480
  const resolutionAffected = /* @__PURE__ */ new Set();
3520
- const resolutionLedger = changedResolutionConfigurations.length ? ctx.project.getResolutionLedger() : void 0;
3481
+ const resolutionLedger = this.capturedLedger ?? (changedResolutionConfigurations.length ? ctx.project.getResolutionLedger() : void 0);
3482
+ this.capturedLedger = void 0;
3521
3483
  for (const [owner, configurations] of this.resolutionConfigurationSets) if (configurations.some((file) => changedResolutionSet.has(file))) resolutionAffected.add(owner);
3522
3484
  this.resolutionAffectedThisPass = resolutionAffected.size > 0;
3523
3485
  if (changedResolutionConfigurations.length) {
@@ -3655,9 +3617,7 @@ var Builder = class {
3655
3617
  cwd,
3656
3618
  dev
3657
3619
  });
3658
- (0, _bamboocss_shared.uniq)([...ctx.conf.dependencies, ...ctx.explicitDeps]).forEach((file) => {
3659
- this.configDependencies.add((0, path.resolve)(cwd || ctx.conf.config.cwd, file));
3660
- });
3620
+ this.recordConfigDependencies(ctx, cwd);
3661
3621
  this.context = ctx;
3662
3622
  this.tsconfigResolutionFiles = ctx.diff.getResolutionConfigFiles();
3663
3623
  return ctx;
@@ -3816,73 +3776,23 @@ var Builder = class {
3816
3776
  ctx.assertExtracted(files);
3817
3777
  ctx.assertNoDeadCalls(files);
3818
3778
  };
3819
- isValidRoot = (root) => {
3820
- const ctx = this.getContextOrThrow();
3821
- let valid = false;
3822
- root.walkAtRules("layer", (rule) => {
3823
- if (ctx.isValidLayerParams(rule.params)) valid = true;
3824
- });
3825
- return valid;
3826
- };
3827
- write = (root) => {
3828
- if (hasGeneratedCss(root)) {
3829
- _bamboocss_logger.logger.warn("postcss", "Generated css is already present in this file, so nothing was injected. It is imported and generated here at once — keep the `@import` of `styles.css` or the `@layer` statement that the postcss plugin injects at, not both.");
3830
- return;
3831
- }
3832
- root.append(this.toCss());
3833
- };
3834
3779
  /**
3835
3780
  * The finished stylesheet, as a string.
3836
3781
  *
3837
- * The same sheet `write` injects into a postcss root, for callers that want the css
3838
- * rather than a mutated root -- the vite plugin serves it as a virtual module. Both go
3839
- * through here so a build cannot depend on which integration asked for it.
3840
- *
3841
- * `layerParams` is the one thing that differs between them, and it is not cosmetic: the
3842
- * `@layer a, b, c;` statement is what fixes layer *order*, and css layers are ordered by
3843
- * first appearance otherwise. `write` leaves it out because the root it appends to is a
3844
- * file that already declares it -- that declaration is what `isValidRoot` matches on. A
3845
- * virtual module is the whole stylesheet and has nothing to inherit it from.
3782
+ * `layerParams` controls the `@layer a, b, c;` statement that fixes layer order. CSS layers
3783
+ * are ordered by first appearance otherwise.
3846
3784
  *
3847
3785
  * `extract` has to have run first: this reads the encoder rather than filling it.
3848
3786
  */
3849
- toCss = ({ layerParams = false, includeRecipes = true } = {}) => {
3850
- const ctx = this.getContextOrThrow();
3851
- const sheet = ctx.createSheet();
3852
- if (layerParams) if (includeRecipes) ctx.appendLayerParams(sheet);
3853
- else {
3854
- const recipeLayer = ctx.config.layers?.recipes ?? "recipes";
3855
- sheet.layers.root.prepend(`@layer ${sheet.layers.layerNames.filter((name) => name !== recipeLayer).join(", ")};`);
3856
- }
3857
- ctx.appendBaselineCss(sheet);
3858
- if (!includeRecipes) {
3859
- sheet.layers.recipes.removeAll();
3860
- sheet.layers.recipes_base.removeAll();
3861
- sheet.layers.recipes_slots.removeAll();
3862
- sheet.layers.recipes_slots_base.removeAll();
3863
- }
3864
- const collectElements = (0, _bamboocss_core.prunesPreflight)(ctx.config.preflight);
3865
- const declaredKeyframes = ctx.config.prune?.keyframes ? keyframeNames(ctx) : [];
3866
- const scans = ctx.config.prune?.tokens !== false || collectElements || declaredKeyframes.length > 0 ? collectSourceScans(ctx, {
3867
- keyframeNames: declaredKeyframes,
3868
- elements: collectElements
3869
- }, this.sourceScanCache, (filePath) => this.filesMeta?.changes.get(filePath)?.mtime, this.sourceInventory) : void 0;
3870
- const reachableVars = pruneTokensForBuild(ctx, sheet, [], scans);
3871
- if (collectElements && scans) ctx.prunePreflight(sheet, scans.elements);
3872
- if (ctx.config.prune?.keyframes && scans) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3873
- return ctx.getCss(sheet);
3874
- };
3875
- registerDependency = (fn) => {
3787
+ toCss = ({ layerParams = false } = {}) => {
3876
3788
  const ctx = this.getContextOrThrow();
3877
- this.crawlConfigDependencies();
3878
- for (const fileOrGlob of ctx.config.include) {
3879
- const dependency = parseDependency(fileOrGlob);
3880
- if (dependency) fn(dependency);
3881
- }
3882
- for (const file of this.configDependencies) fn({
3883
- type: "dependency",
3884
- file: (0, path.normalize)((0, path.resolve)(file))
3789
+ const sheet = assembleExtractedSheet(ctx, {
3790
+ layerParams,
3791
+ sourceScanCache: this.sourceScanCache,
3792
+ mtimeOf: (filePath) => this.filesMeta?.changes.get(filePath)?.mtime,
3793
+ sourceInventory: this.sourceInventory
3885
3794
  });
3795
+ return ctx.getCss(sheet);
3886
3796
  };
3887
3797
  };
3888
3798
  //#endregion
@@ -3954,8 +3864,8 @@ const startProfiling = async (cwd, prefix, isWatching) => {
3954
3864
  //#region src/cssgen.ts
3955
3865
  const cssgen = async (ctx, options) => {
3956
3866
  const { outfile, type, splitting } = options;
3957
- const sheet = ctx.createSheet();
3958
3867
  if (type) {
3868
+ const sheet = ctx.createSheet();
3959
3869
  const done = _bamboocss_logger.logger.time.info(ctx.messages.cssArtifactComplete(type));
3960
3870
  ctx.appendCssOfType(type, sheet);
3961
3871
  if (type === "preflight" && (0, _bamboocss_core.prunesPreflight)(ctx.config.preflight)) ctx.prunePreflight(sheet, collectRenderedElements(ctx));
@@ -3966,19 +3876,9 @@ const cssgen = async (ctx, options) => {
3966
3876
  } else await ctx.writeCss(sheet);
3967
3877
  done();
3968
3878
  } else {
3969
- const { files, results } = ctx.parseFiles();
3879
+ const { files } = ctx.parseFiles();
3970
3880
  const done = _bamboocss_logger.logger.time.info(ctx.messages.buildComplete(files.length));
3971
- ctx.appendLayerParams(sheet);
3972
- ctx.appendBaselineCss(sheet);
3973
- ctx.appendParserCss(sheet);
3974
- const collectElements = (0, _bamboocss_core.prunesPreflight)(ctx.config.preflight);
3975
- const scans = collectSourceScans(ctx, {
3976
- keyframeNames: ctx.config.prune?.keyframes ? keyframeNames(ctx) : [],
3977
- elements: collectElements
3978
- });
3979
- const reachableVars = pruneTokensForBuild(ctx, sheet, results, scans);
3980
- if (collectElements) ctx.prunePreflight(sheet, scans.elements);
3981
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3881
+ const sheet = assembleExtractedSheet(ctx, { layerParams: true });
3982
3882
  if (splitting) await ctx.writeSplitCss(sheet);
3983
3883
  else if (outfile) {
3984
3884
  const css = ctx.getCss(sheet);
@@ -4043,19 +3943,8 @@ async function build(ctx, artifactIds) {
4043
3943
  await codegen(ctx, artifactIds);
4044
3944
  if (ctx.config.emitTokensOnly) return _bamboocss_logger.logger.info("css:emit", "Successfully rebuilt the css variables and js function to query your tokens ✨");
4045
3945
  const done = _bamboocss_logger.logger.time.info("");
4046
- const sheet = ctx.createSheet();
4047
- ctx.appendLayerParams(sheet);
4048
- ctx.appendBaselineCss(sheet);
4049
3946
  const parsed = ctx.parseFiles();
4050
- ctx.appendParserCss(sheet);
4051
- const collectElements = (0, _bamboocss_core.prunesPreflight)(ctx.config.preflight);
4052
- const scans = collectSourceScans(ctx, {
4053
- keyframeNames: ctx.config.prune?.keyframes ? keyframeNames(ctx) : [],
4054
- elements: collectElements
4055
- });
4056
- const reachableVars = pruneTokensForBuild(ctx, sheet, parsed.results, scans);
4057
- if (collectElements) ctx.prunePreflight(sheet, scans.elements);
4058
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3947
+ const sheet = assembleExtractedSheet(ctx, { layerParams: true });
4059
3948
  await ctx.writeCss(sheet);
4060
3949
  done(ctx.messages.buildComplete(parsed.files.length));
4061
3950
  }
@@ -4096,18 +3985,7 @@ async function generate(config, configPath) {
4096
3985
  if (parsed === 0) return;
4097
3986
  const outfile = ctx.runtime.path.join(...ctx.paths.root, "styles.css");
4098
3987
  const done = _bamboocss_logger.logger.time.info(ctx.messages.buildComplete(parsed));
4099
- const sheet = ctx.createSheet();
4100
- ctx.appendLayerParams(sheet);
4101
- ctx.appendBaselineCss(sheet);
4102
- ctx.appendParserCss(sheet);
4103
- const collectWatchElements = (0, _bamboocss_core.prunesPreflight)(ctx.config.preflight);
4104
- const watchScans = collectSourceScans(ctx, {
4105
- keyframeNames: ctx.config.prune?.keyframes ? keyframeNames(ctx) : [],
4106
- elements: collectWatchElements
4107
- });
4108
- const reachableVars = pruneTokensForBuild(ctx, sheet, [], watchScans);
4109
- if (collectWatchElements) ctx.prunePreflight(sheet, watchScans.elements);
4110
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, watchScans.keyframeHits, reachableVars);
3988
+ const sheet = assembleExtractedSheet(ctx, { layerParams: true });
4111
3989
  const css = ctx.getCss(sheet);
4112
3990
  await ctx.runtime.fs.writeFile(outfile, css);
4113
3991
  done();
@@ -4155,6 +4033,7 @@ const setLogStream = (options) => {
4155
4033
  if (options.logfile) {
4156
4034
  const outPath = node_path.default.resolve(cwd, options.logfile);
4157
4035
  ensure(outPath);
4036
+ node_fs.default.closeSync(node_fs.default.openSync(outPath, "a"));
4158
4037
  _bamboocss_logger.logger.info("logfile", outPath);
4159
4038
  stream = node_fs.default.createWriteStream(outPath, { flags: "a" });
4160
4039
  _bamboocss_logger.logger.onLog = (entry) => {
@@ -4179,67 +4058,6 @@ const ensure = (outPath) => {
4179
4058
  return outPath;
4180
4059
  };
4181
4060
  //#endregion
4182
- //#region src/vite-integration.ts
4183
- /**
4184
- * Every extension Vite accepts for its config, so "is this a Vite project" is answered by the
4185
- * same file Vite itself would load.
4186
- *
4187
- * A file rather than a resolvable `vite` package: Vite is a transitive dependency of plenty of
4188
- * things — Vitest above all — and a project that has one for its tests and builds with webpack
4189
- * is exactly the case this must not mistake for a Vite app.
4190
- */
4191
- const VITE_CONFIG_FILES = [
4192
- "vite.config.ts",
4193
- "vite.config.js",
4194
- "vite.config.mjs",
4195
- "vite.config.mts",
4196
- "vite.config.cjs",
4197
- "vite.config.cts"
4198
- ];
4199
- /** The project's Vite config, if it has one. Not resolved further than existence. */
4200
- const findViteConfig = (cwd) => VITE_CONFIG_FILES.map((file) => (0, path.join)(cwd, file)).find((file) => (0, fs.existsSync)(file));
4201
- /**
4202
- * Frameworks that author styles in a file the Vite compiler does not transform.
4203
- *
4204
- * It compiles JavaScript and TypeScript. A `.svelte`, `.vue` or `.astro` file is a template
4205
- * with a script in it, and the compiler leaves those alone — which for a Svelte or Vue project
4206
- * makes the PostCSS integration the right one, not a downgrade. Worse than that: switching one
4207
- * to `@bamboocss/vite` would prune every rule only its components reach, since reachability is
4208
- * computed from modules the compiler saw, so the pages would render unstyled.
4209
- *
4210
- * So this is the exception to the advice, and it has to be checked before giving it.
4211
- */
4212
- const TEMPLATE_EXTENSIONS = /\b(?:svelte|vue|astro|html|hbs|mdx?)\b/;
4213
- const TEMPLATE_PACKAGES = [
4214
- "svelte",
4215
- "@sveltejs/kit",
4216
- "vue",
4217
- "nuxt",
4218
- "astro"
4219
- ];
4220
- /**
4221
- * Does this project author styles somewhere the Vite compiler cannot reach?
4222
- *
4223
- * Two signals because the two callers know different things. A resolved config names the file
4224
- * types directly, and is authoritative when it does; `bamboo init` runs before there is one,
4225
- * so the dependency list stands in. Either one is enough — both directions of a wrong answer
4226
- * here only decide whether advice is offered, and the advice is worth less than a Svelte
4227
- * project being told to break itself.
4228
- */
4229
- const hasUncompilableSources = (options) => {
4230
- if (options.include?.some((glob) => TEMPLATE_EXTENSIONS.test(glob))) return true;
4231
- try {
4232
- const manifest = JSON.parse((0, fs.readFileSync)((0, path.join)(options.cwd, "package.json"), "utf8"));
4233
- const dependencies = {
4234
- ...manifest.dependencies,
4235
- ...manifest.devDependencies
4236
- };
4237
- return TEMPLATE_PACKAGES.some((name) => name in dependencies);
4238
- } catch {
4239
- return false;
4240
- }
4241
- };
4242
- //#endregion
4243
4061
  //#region src/setup-config.ts
4244
4062
  async function setupConfig(cwd, opts = {}) {
4245
4063
  const { force, outExtension, outdir = "styled-system", strictValues } = opts;
@@ -4296,19 +4114,6 @@ strictValues: ${JSON.stringify(strictValues)},\n` : ""}
4296
4114
  _bamboocss_logger.logger.log(_bamboocss_core.messages.thankYou());
4297
4115
  }
4298
4116
  }
4299
- async function setupPostcss(cwd) {
4300
- const viteConfig = findViteConfig(cwd);
4301
- if (viteConfig && !hasUncompilableSources({ cwd })) _bamboocss_logger.logger.warn("init:postcss", `This project has ${(0, _bamboocss_logger.quote)((0, path.basename)(viteConfig))}, so ${(0, _bamboocss_logger.quote)("@bamboocss/vite")} is the integration to use. The PostCSS one emits CSS only: it does not compile source, so ${(0, _bamboocss_logger.quote)("css()")} and ${(0, _bamboocss_logger.quote)("cva()")} stay runtime calls and the generated style engine ships in your client bundle. Both render identically, which is what makes the difference easy to miss. See https://bamboocss.com/docs/installation/vite`);
4302
- _bamboocss_logger.logger.info("init:postcss", `creating postcss config file: ${(0, _bamboocss_logger.quote)("postcss.config.cjs")}`);
4303
- const content = outdent.outdent`
4304
- module.exports = {
4305
- plugins: {
4306
- '@bamboocss/dev/postcss': {},
4307
- },
4308
- }
4309
- `;
4310
- await fs_extra.default.writeFile((0, path.join)(cwd, "postcss.config.cjs"), content);
4311
- }
4312
4117
  //#endregion
4313
4118
  //#region src/spec.ts
4314
4119
  async function spec(ctx, options) {
@@ -4332,6 +4137,55 @@ async function spec(ctx, options) {
4332
4137
  return specs;
4333
4138
  }
4334
4139
  //#endregion
4140
+ //#region src/vite-integration.ts
4141
+ /**
4142
+ * Every extension Vite accepts for its config, so "is this a Vite project" is answered by the
4143
+ * same file Vite itself would load.
4144
+ *
4145
+ * A file rather than a resolvable `vite` package: Vite is a transitive dependency of plenty of
4146
+ * things — Vitest above all — and a project that has one for its tests and builds with webpack
4147
+ * is exactly the case this must not mistake for a Vite app.
4148
+ */
4149
+ const VITE_CONFIG_FILES = [
4150
+ "vite.config.ts",
4151
+ "vite.config.js",
4152
+ "vite.config.mjs",
4153
+ "vite.config.mts",
4154
+ "vite.config.cjs",
4155
+ "vite.config.cts"
4156
+ ];
4157
+ /** The project's Vite config, if it has one. Not resolved further than existence. */
4158
+ const findViteConfig = (cwd) => VITE_CONFIG_FILES.map((file) => (0, path.join)(cwd, file)).find((file) => (0, fs.existsSync)(file));
4159
+ /**
4160
+ * Frameworks that author styles in a file the Vite compiler does not transform as JavaScript
4161
+ * until a dedicated preprocessor exists. Vue, Svelte and Astro compile through
4162
+ * `bamboocss:compiler-sfc`. HTML / Handlebars templates still do not.
4163
+ */
4164
+ const TEMPLATE_EXTENSIONS = /\b(?:html|hbs)\b/;
4165
+ const TEMPLATE_PACKAGES = [];
4166
+ /**
4167
+ * Does this project author styles somewhere the Vite compiler cannot reach?
4168
+ *
4169
+ * Two signals because the two callers know different things. A resolved config names the file
4170
+ * types directly, and is authoritative when it does; `bamboo init` runs before there is one,
4171
+ * so the dependency list stands in. Either one is enough — both directions of a wrong answer
4172
+ * here only decide whether advice is offered, and the advice is worth less than a Svelte
4173
+ * project being told to break itself.
4174
+ */
4175
+ const hasUncompilableSources = (options) => {
4176
+ if (options.include?.some((glob) => TEMPLATE_EXTENSIONS.test(glob))) return true;
4177
+ try {
4178
+ const manifest = JSON.parse((0, fs.readFileSync)((0, path.join)(options.cwd, "package.json"), "utf8"));
4179
+ const dependencies = {
4180
+ ...manifest.dependencies,
4181
+ ...manifest.devDependencies
4182
+ };
4183
+ return TEMPLATE_PACKAGES.some((name) => name in dependencies);
4184
+ } catch {
4185
+ return false;
4186
+ }
4187
+ };
4188
+ //#endregion
4335
4189
  exports.BambooContext = BambooContext;
4336
4190
  exports.Builder = Builder;
4337
4191
  exports.analyze = analyze;
@@ -4351,10 +4205,8 @@ exports.hasUncompilableSources = hasUncompilableSources;
4351
4205
  exports.isStaticCompilerActive = require_static_compiler.isStaticCompilerActive;
4352
4206
  exports.loadConfigAndCreateContext = loadConfigAndCreateContext;
4353
4207
  exports.markStaticCompilerActive = require_static_compiler.markStaticCompilerActive;
4354
- exports.parseDependency = parseDependency;
4355
4208
  exports.setLogStream = setLogStream;
4356
4209
  exports.setupConfig = setupConfig;
4357
4210
  exports.setupGitIgnore = setupGitIgnore;
4358
- exports.setupPostcss = setupPostcss;
4359
4211
  exports.spec = spec;
4360
4212
  exports.startProfiling = startProfiling;