@bamboocss/node 1.12.3 → 1.13.1

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/LICENSE.md CHANGED
@@ -1,6 +1,7 @@
1
1
  MIT License
2
2
 
3
3
  Copyright (c) 2023 Segun Adebayo
4
+ Copyright (c) 2026 Gajus Kuizinas
4
5
 
5
6
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
7
  documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
package/dist/index.cjs CHANGED
@@ -1565,9 +1565,32 @@ var OutputEngine = class {
1565
1565
  const { file, code } = artifact;
1566
1566
  const absPath = this.path.join(...dir, file);
1567
1567
  _bamboocss_logger.logger.debug("write:file", dir.slice(-1).concat(file).join("/"));
1568
+ if (file === "package.json") return this.writePackageJson(absPath, code);
1568
1569
  return this.fs.writeFile(absPath, code);
1569
1570
  }));
1570
1571
  };
1572
+ /**
1573
+ * Unlike the rest of the output, `package.json` is not exclusively ours: `emit-pkg`
1574
+ * writes entrypoints to the same path, and consumers hand-edit it. Overwriting would
1575
+ * drop that, so only keys that are absent get filled in — anything already declared,
1576
+ * including a deliberate `sideEffects`, is left as it stands.
1577
+ */
1578
+ writePackageJson = (absPath, code) => {
1579
+ if (!this.fs.existsSync(absPath)) return this.fs.writeFile(absPath, code);
1580
+ let existing;
1581
+ try {
1582
+ existing = JSON.parse(this.fs.readFileSync(absPath));
1583
+ } catch {
1584
+ _bamboocss_logger.logger.warn("write:file", `Skipped ${absPath}: could not be parsed as JSON`);
1585
+ return;
1586
+ }
1587
+ const missing = Object.entries(JSON.parse(code)).filter(([key]) => existing[key] === void 0);
1588
+ if (!missing.length) return;
1589
+ return this.fs.writeFile(absPath, JSON.stringify({
1590
+ ...existing,
1591
+ ...Object.fromEntries(missing)
1592
+ }, null, 2) + "\n");
1593
+ };
1571
1594
  };
1572
1595
  //#endregion
1573
1596
  //#region src/create-context.ts
@@ -2048,6 +2071,90 @@ function parseDependency(fileOrGlob) {
2048
2071
  return message;
2049
2072
  }
2050
2073
  //#endregion
2074
+ //#region src/token-references.ts
2075
+ /**
2076
+ * `token.var('colors.red.300')` and `token('spacing.4')`, including the whitespace a
2077
+ * formatter may leave behind. The parser already reports `token()` calls and resolves
2078
+ * constants and template literals through them, but it does not match `token.var()`,
2079
+ * whose callee is a property access. Scanning the text covers that, and covers a path
2080
+ * built somewhere the extractor cannot follow.
2081
+ */
2082
+ const TOKEN_CALL = /\btoken(?:\s*\.\s*var)?\s*\(\s*['"`]([^'"`]+)['"`]/g;
2083
+ /**
2084
+ * Collect token references that reading the generated css cannot reveal.
2085
+ *
2086
+ * This is deliberately textual and therefore over-inclusive: a match inside a comment or
2087
+ * a string that is never evaluated keeps a token alive. Keeping a token that is not used
2088
+ * costs bytes; dropping one that is breaks the page, so the bias belongs on this side.
2089
+ *
2090
+ * `results` is a second, redundant source for the same paths: the extractor resolves one
2091
+ * built from a constant, which the text scan reads literally and fails to look up. Callers
2092
+ * that cannot supply it — the watch rebuild and the PostCSS plugin, where re-parsing would
2093
+ * encode every style a second time — pass none, and stay correct only because a path the
2094
+ * scan misses can lose nothing: `token()` hands javascript a literal for exactly the
2095
+ * tokens this cannot see, and hands it a `var()` only for virtual, conditional and
2096
+ * negative tokens, which `getAlwaysKeptTokenVars` keeps whatever the source says. Narrow
2097
+ * those blanket keeps and this argument stops being redundant, so those two callers would
2098
+ * have to find another way to supply it.
2099
+ */
2100
+ function collectTokenReferences(ctx, results) {
2101
+ const paths = /* @__PURE__ */ new Set();
2102
+ const vars = /* @__PURE__ */ new Set();
2103
+ for (const result of results) for (const item of result.token) for (const value of item.data ?? []) if (typeof value === "string") paths.add(value);
2104
+ for (const file of ctx.getFiles()) {
2105
+ const filePath = ctx.runtime.path.abs(ctx.config.cwd, file);
2106
+ let content = ctx.project.getSourceFile(filePath)?.getFullText();
2107
+ if (content == null) try {
2108
+ content = ctx.runtime.fs.readFileSync(filePath);
2109
+ } catch {
2110
+ continue;
2111
+ }
2112
+ for (const match of content.matchAll(TOKEN_CALL)) paths.add(match[1]);
2113
+ for (const name of (0, _bamboocss_shared.cssVarRefs)(content)) vars.add(name);
2114
+ }
2115
+ for (const path of paths) {
2116
+ const ref = ctx.tokens.view.getVar(path);
2117
+ if (!ref) continue;
2118
+ for (const name of (0, _bamboocss_shared.cssVarRefs)(ref)) vars.add(name);
2119
+ }
2120
+ return vars;
2121
+ }
2122
+ /**
2123
+ * Collect keyframe names that reading the generated css cannot reveal.
2124
+ *
2125
+ * A keyframe reached through `css({ animation: 'fade-in 1s' })` lands in the stylesheet
2126
+ * and `pruneKeyframes` sees it there. What it cannot see is a name assembled at runtime,
2127
+ * or one handed to an inline `style` rather than to bamboo — in both cases the animation
2128
+ * plays against a `@keyframes` that no bamboo declaration references.
2129
+ *
2130
+ * So each declared name is looked for in the source text. Like the token scan this is
2131
+ * deliberately over-inclusive: a name that happens to appear in a comment, or as a word
2132
+ * in unrelated prose, keeps its keyframe alive. Keeping an unused keyframe costs bytes;
2133
+ * dropping a used one silently stops an animation, which is the worse failure and the
2134
+ * harder one to trace.
2135
+ */
2136
+ function collectKeyframeReferences(ctx, names) {
2137
+ const declared = Array.from(names);
2138
+ const found = /* @__PURE__ */ new Set();
2139
+ if (!declared.length) return found;
2140
+ const patterns = declared.map((name) => [name, new RegExp(`\\b${escapeRegExp(name)}\\b`)]);
2141
+ for (const file of ctx.getFiles()) {
2142
+ if (found.size === declared.length) break;
2143
+ const filePath = ctx.runtime.path.abs(ctx.config.cwd, file);
2144
+ let content = ctx.project.getSourceFile(filePath)?.getFullText();
2145
+ if (content == null) try {
2146
+ content = ctx.runtime.fs.readFileSync(filePath);
2147
+ } catch {
2148
+ continue;
2149
+ }
2150
+ for (const [name, pattern] of patterns) if (!found.has(name) && pattern.test(content)) found.add(name);
2151
+ }
2152
+ return found;
2153
+ }
2154
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2155
+ /** The keyframes the theme declares — the allow-list `pruneKeyframes` works against. */
2156
+ const keyframeNames = (ctx) => Object.keys(ctx.config.theme?.keyframes ?? {});
2157
+ //#endregion
2051
2158
  //#region src/builder.ts
2052
2159
  const fileModifiedMap = /* @__PURE__ */ new Map();
2053
2160
  var Builder = class {
@@ -2188,6 +2295,8 @@ var Builder = class {
2188
2295
  const ctx = this.getContextOrThrow();
2189
2296
  const sheet = ctx.createSheet();
2190
2297
  ctx.appendBaselineCss(sheet);
2298
+ if (ctx.config.pruneUnusedTokens) ctx.pruneTokens(sheet, collectTokenReferences(ctx, []));
2299
+ if (ctx.config.pruneUnusedKeyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)));
2191
2300
  const css = ctx.getCss(sheet);
2192
2301
  root.append(css);
2193
2302
  };
@@ -2283,13 +2392,15 @@ const cssgen = async (ctx, options) => {
2283
2392
  } else await ctx.writeCss(sheet);
2284
2393
  done();
2285
2394
  } else {
2286
- const { files } = ctx.parseFiles();
2395
+ const { files, results } = ctx.parseFiles();
2287
2396
  const done = _bamboocss_logger.logger.time.info(ctx.messages.buildComplete(files.length));
2288
2397
  if (!minimal) {
2289
2398
  ctx.appendLayerParams(sheet);
2290
2399
  ctx.appendBaselineCss(sheet);
2291
2400
  }
2292
2401
  ctx.appendParserCss(sheet);
2402
+ if (!minimal && ctx.config.pruneUnusedTokens) ctx.pruneTokens(sheet, collectTokenReferences(ctx, results));
2403
+ if (!minimal && ctx.config.pruneUnusedKeyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)));
2293
2404
  if (splitting) await ctx.writeSplitCss(sheet);
2294
2405
  else if (outfile) {
2295
2406
  const css = ctx.getCss(sheet);
@@ -2359,6 +2470,8 @@ async function build(ctx, artifactIds) {
2359
2470
  ctx.appendBaselineCss(sheet);
2360
2471
  const parsed = ctx.parseFiles();
2361
2472
  ctx.appendParserCss(sheet);
2473
+ if (ctx.config.pruneUnusedTokens) ctx.pruneTokens(sheet, collectTokenReferences(ctx, parsed.results));
2474
+ if (ctx.config.pruneUnusedKeyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)));
2362
2475
  await ctx.writeCss(sheet);
2363
2476
  done(ctx.messages.buildComplete(parsed.files.length));
2364
2477
  }
@@ -2384,28 +2497,46 @@ async function generate(config, configPath) {
2384
2497
  cwd,
2385
2498
  poll
2386
2499
  });
2387
- const bundleStyles = async (ctx, changedFilePath) => {
2500
+ /**
2501
+ * Re-parses every affected file, then builds and writes the stylesheet once.
2502
+ *
2503
+ * One edit can affect many files — a shared style file is folded into all of
2504
+ * its importers — and the sheet is rebuilt from the whole parser result, not
2505
+ * per file. Writing per file would run the optimize pipeline and hit the disk
2506
+ * once per importer for a single keystroke.
2507
+ */
2508
+ const bundleStyles = async (ctx, changedFilePaths) => {
2509
+ let parsed = 0;
2510
+ for (const filePath of changedFilePaths) if (ctx.project.parseSourceFile(filePath)) parsed++;
2511
+ if (parsed === 0) return;
2388
2512
  const outfile = ctx.runtime.path.join(...ctx.paths.root, "styles.css");
2389
- if (ctx.project.parseSourceFile(changedFilePath)) {
2390
- const done = _bamboocss_logger.logger.time.info(ctx.messages.buildComplete(1));
2391
- const sheet = ctx.createSheet();
2392
- ctx.appendLayerParams(sheet);
2393
- ctx.appendBaselineCss(sheet);
2394
- ctx.appendParserCss(sheet);
2395
- const css = ctx.getCss(sheet);
2396
- await ctx.runtime.fs.writeFile(outfile, css);
2397
- done();
2398
- }
2513
+ const done = _bamboocss_logger.logger.time.info(ctx.messages.buildComplete(parsed));
2514
+ const sheet = ctx.createSheet();
2515
+ ctx.appendLayerParams(sheet);
2516
+ ctx.appendBaselineCss(sheet);
2517
+ ctx.appendParserCss(sheet);
2518
+ if (ctx.config.pruneUnusedTokens) ctx.pruneTokens(sheet, collectTokenReferences(ctx, []));
2519
+ if (ctx.config.pruneUnusedKeyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)));
2520
+ const css = ctx.getCss(sheet);
2521
+ await ctx.runtime.fs.writeFile(outfile, css);
2522
+ done();
2399
2523
  };
2400
2524
  ctx.watchFiles(async (event, file) => {
2401
2525
  const filePath = ctx.runtime.path.abs(cwd, file);
2402
- if (event === "unlink") ctx.project.removeSourceFile(filePath);
2403
- else if (event === "change") {
2404
- ctx.project.reloadSourceFile(file);
2405
- await bundleStyles(ctx, filePath);
2526
+ if (event === "unlink") {
2527
+ const dependents = ctx.project.getDependents(filePath);
2528
+ ctx.project.removeSourceFile(filePath);
2529
+ await bundleStyles(ctx, dependents);
2530
+ } else if (event === "change") {
2531
+ ctx.project.reloadSourceFile(filePath);
2532
+ await bundleStyles(ctx, [filePath, ...ctx.project.getDependents(filePath)]);
2406
2533
  } else if (event === "add") {
2407
- ctx.project.createSourceFile(file);
2408
- await bundleStyles(ctx, filePath);
2534
+ ctx.project.createSourceFile(filePath);
2535
+ await bundleStyles(ctx, [
2536
+ filePath,
2537
+ ...ctx.project.getDependents(filePath),
2538
+ ...ctx.project.getUnresolvedImporters()
2539
+ ]);
2409
2540
  }
2410
2541
  });
2411
2542
  }
package/dist/index.d.cts CHANGED
@@ -35,6 +35,13 @@ declare class OutputEngine {
35
35
  empty: () => void;
36
36
  ensure: (file: string, cwd: string) => string;
37
37
  write: (output: Artifact | undefined) => Promise<PromiseSettledResult<void>[]> | undefined;
38
+ /**
39
+ * Unlike the rest of the output, `package.json` is not exclusively ours: `emit-pkg`
40
+ * writes entrypoints to the same path, and consumers hand-edit it. Overwriting would
41
+ * drop that, so only keys that are absent get filled in — anything already declared,
42
+ * including a deliberate `sideEffects`, is left as it stands.
43
+ */
44
+ private writePackageJson;
38
45
  }
39
46
  //#endregion
40
47
  //#region src/create-context.d.ts
package/dist/index.d.mts CHANGED
@@ -35,6 +35,13 @@ declare class OutputEngine {
35
35
  empty: () => void;
36
36
  ensure: (file: string, cwd: string) => string;
37
37
  write: (output: Artifact | undefined) => Promise<PromiseSettledResult<void>[]> | undefined;
38
+ /**
39
+ * Unlike the rest of the output, `package.json` is not exclusively ours: `emit-pkg`
40
+ * writes entrypoints to the same path, and consumers hand-edit it. Overwriting would
41
+ * drop that, so only keys that are absent get filled in — anything already declared,
42
+ * including a deliberate `sideEffects`, is left as it stands.
43
+ */
44
+ private writePackageJson;
38
45
  }
39
46
  //#endregion
40
47
  //#region src/create-context.d.ts
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Reporter, formatRecipeReport, formatTokenReport } from "@bamboocss/reporter";
2
2
  import { colors, logger, quote } from "@bamboocss/logger";
3
3
  import { convertTsPathsToRegexes, diffConfigs, findConfig, getConfigDependencies, loadConfig, mergeHooks } from "@bamboocss/config";
4
- import { BambooError, uniq } from "@bamboocss/shared";
4
+ import { BambooError, cssVarRefs, uniq } from "@bamboocss/shared";
5
5
  import { appendFileSync, existsSync, readFileSync, statSync, writeFileSync } from "fs";
6
6
  import { dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "path";
7
7
  import { pluginLightningcss } from "@bamboocss/plugin-lightningcss";
@@ -1550,9 +1550,32 @@ var OutputEngine = class {
1550
1550
  const { file, code } = artifact;
1551
1551
  const absPath = this.path.join(...dir, file);
1552
1552
  logger.debug("write:file", dir.slice(-1).concat(file).join("/"));
1553
+ if (file === "package.json") return this.writePackageJson(absPath, code);
1553
1554
  return this.fs.writeFile(absPath, code);
1554
1555
  }));
1555
1556
  };
1557
+ /**
1558
+ * Unlike the rest of the output, `package.json` is not exclusively ours: `emit-pkg`
1559
+ * writes entrypoints to the same path, and consumers hand-edit it. Overwriting would
1560
+ * drop that, so only keys that are absent get filled in — anything already declared,
1561
+ * including a deliberate `sideEffects`, is left as it stands.
1562
+ */
1563
+ writePackageJson = (absPath, code) => {
1564
+ if (!this.fs.existsSync(absPath)) return this.fs.writeFile(absPath, code);
1565
+ let existing;
1566
+ try {
1567
+ existing = JSON.parse(this.fs.readFileSync(absPath));
1568
+ } catch {
1569
+ logger.warn("write:file", `Skipped ${absPath}: could not be parsed as JSON`);
1570
+ return;
1571
+ }
1572
+ const missing = Object.entries(JSON.parse(code)).filter(([key]) => existing[key] === void 0);
1573
+ if (!missing.length) return;
1574
+ return this.fs.writeFile(absPath, JSON.stringify({
1575
+ ...existing,
1576
+ ...Object.fromEntries(missing)
1577
+ }, null, 2) + "\n");
1578
+ };
1556
1579
  };
1557
1580
  //#endregion
1558
1581
  //#region src/create-context.ts
@@ -2033,6 +2056,90 @@ function parseDependency(fileOrGlob) {
2033
2056
  return message;
2034
2057
  }
2035
2058
  //#endregion
2059
+ //#region src/token-references.ts
2060
+ /**
2061
+ * `token.var('colors.red.300')` and `token('spacing.4')`, including the whitespace a
2062
+ * formatter may leave behind. The parser already reports `token()` calls and resolves
2063
+ * constants and template literals through them, but it does not match `token.var()`,
2064
+ * whose callee is a property access. Scanning the text covers that, and covers a path
2065
+ * built somewhere the extractor cannot follow.
2066
+ */
2067
+ const TOKEN_CALL = /\btoken(?:\s*\.\s*var)?\s*\(\s*['"`]([^'"`]+)['"`]/g;
2068
+ /**
2069
+ * Collect token references that reading the generated css cannot reveal.
2070
+ *
2071
+ * This is deliberately textual and therefore over-inclusive: a match inside a comment or
2072
+ * a string that is never evaluated keeps a token alive. Keeping a token that is not used
2073
+ * costs bytes; dropping one that is breaks the page, so the bias belongs on this side.
2074
+ *
2075
+ * `results` is a second, redundant source for the same paths: the extractor resolves one
2076
+ * built from a constant, which the text scan reads literally and fails to look up. Callers
2077
+ * that cannot supply it — the watch rebuild and the PostCSS plugin, where re-parsing would
2078
+ * encode every style a second time — pass none, and stay correct only because a path the
2079
+ * scan misses can lose nothing: `token()` hands javascript a literal for exactly the
2080
+ * tokens this cannot see, and hands it a `var()` only for virtual, conditional and
2081
+ * negative tokens, which `getAlwaysKeptTokenVars` keeps whatever the source says. Narrow
2082
+ * those blanket keeps and this argument stops being redundant, so those two callers would
2083
+ * have to find another way to supply it.
2084
+ */
2085
+ function collectTokenReferences(ctx, results) {
2086
+ const paths = /* @__PURE__ */ new Set();
2087
+ const vars = /* @__PURE__ */ new Set();
2088
+ for (const result of results) for (const item of result.token) for (const value of item.data ?? []) if (typeof value === "string") paths.add(value);
2089
+ for (const file of ctx.getFiles()) {
2090
+ const filePath = ctx.runtime.path.abs(ctx.config.cwd, file);
2091
+ let content = ctx.project.getSourceFile(filePath)?.getFullText();
2092
+ if (content == null) try {
2093
+ content = ctx.runtime.fs.readFileSync(filePath);
2094
+ } catch {
2095
+ continue;
2096
+ }
2097
+ for (const match of content.matchAll(TOKEN_CALL)) paths.add(match[1]);
2098
+ for (const name of cssVarRefs(content)) vars.add(name);
2099
+ }
2100
+ for (const path of paths) {
2101
+ const ref = ctx.tokens.view.getVar(path);
2102
+ if (!ref) continue;
2103
+ for (const name of cssVarRefs(ref)) vars.add(name);
2104
+ }
2105
+ return vars;
2106
+ }
2107
+ /**
2108
+ * Collect keyframe names that reading the generated css cannot reveal.
2109
+ *
2110
+ * A keyframe reached through `css({ animation: 'fade-in 1s' })` lands in the stylesheet
2111
+ * and `pruneKeyframes` sees it there. What it cannot see is a name assembled at runtime,
2112
+ * or one handed to an inline `style` rather than to bamboo — in both cases the animation
2113
+ * plays against a `@keyframes` that no bamboo declaration references.
2114
+ *
2115
+ * So each declared name is looked for in the source text. Like the token scan this is
2116
+ * deliberately over-inclusive: a name that happens to appear in a comment, or as a word
2117
+ * in unrelated prose, keeps its keyframe alive. Keeping an unused keyframe costs bytes;
2118
+ * dropping a used one silently stops an animation, which is the worse failure and the
2119
+ * harder one to trace.
2120
+ */
2121
+ function collectKeyframeReferences(ctx, names) {
2122
+ const declared = Array.from(names);
2123
+ const found = /* @__PURE__ */ new Set();
2124
+ if (!declared.length) return found;
2125
+ const patterns = declared.map((name) => [name, new RegExp(`\\b${escapeRegExp(name)}\\b`)]);
2126
+ for (const file of ctx.getFiles()) {
2127
+ if (found.size === declared.length) break;
2128
+ const filePath = ctx.runtime.path.abs(ctx.config.cwd, file);
2129
+ let content = ctx.project.getSourceFile(filePath)?.getFullText();
2130
+ if (content == null) try {
2131
+ content = ctx.runtime.fs.readFileSync(filePath);
2132
+ } catch {
2133
+ continue;
2134
+ }
2135
+ for (const [name, pattern] of patterns) if (!found.has(name) && pattern.test(content)) found.add(name);
2136
+ }
2137
+ return found;
2138
+ }
2139
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2140
+ /** The keyframes the theme declares — the allow-list `pruneKeyframes` works against. */
2141
+ const keyframeNames = (ctx) => Object.keys(ctx.config.theme?.keyframes ?? {});
2142
+ //#endregion
2036
2143
  //#region src/builder.ts
2037
2144
  const fileModifiedMap = /* @__PURE__ */ new Map();
2038
2145
  var Builder = class {
@@ -2173,6 +2280,8 @@ var Builder = class {
2173
2280
  const ctx = this.getContextOrThrow();
2174
2281
  const sheet = ctx.createSheet();
2175
2282
  ctx.appendBaselineCss(sheet);
2283
+ if (ctx.config.pruneUnusedTokens) ctx.pruneTokens(sheet, collectTokenReferences(ctx, []));
2284
+ if (ctx.config.pruneUnusedKeyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)));
2176
2285
  const css = ctx.getCss(sheet);
2177
2286
  root.append(css);
2178
2287
  };
@@ -2268,13 +2377,15 @@ const cssgen = async (ctx, options) => {
2268
2377
  } else await ctx.writeCss(sheet);
2269
2378
  done();
2270
2379
  } else {
2271
- const { files } = ctx.parseFiles();
2380
+ const { files, results } = ctx.parseFiles();
2272
2381
  const done = logger.time.info(ctx.messages.buildComplete(files.length));
2273
2382
  if (!minimal) {
2274
2383
  ctx.appendLayerParams(sheet);
2275
2384
  ctx.appendBaselineCss(sheet);
2276
2385
  }
2277
2386
  ctx.appendParserCss(sheet);
2387
+ if (!minimal && ctx.config.pruneUnusedTokens) ctx.pruneTokens(sheet, collectTokenReferences(ctx, results));
2388
+ if (!minimal && ctx.config.pruneUnusedKeyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)));
2278
2389
  if (splitting) await ctx.writeSplitCss(sheet);
2279
2390
  else if (outfile) {
2280
2391
  const css = ctx.getCss(sheet);
@@ -2344,6 +2455,8 @@ async function build(ctx, artifactIds) {
2344
2455
  ctx.appendBaselineCss(sheet);
2345
2456
  const parsed = ctx.parseFiles();
2346
2457
  ctx.appendParserCss(sheet);
2458
+ if (ctx.config.pruneUnusedTokens) ctx.pruneTokens(sheet, collectTokenReferences(ctx, parsed.results));
2459
+ if (ctx.config.pruneUnusedKeyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)));
2347
2460
  await ctx.writeCss(sheet);
2348
2461
  done(ctx.messages.buildComplete(parsed.files.length));
2349
2462
  }
@@ -2369,28 +2482,46 @@ async function generate(config, configPath) {
2369
2482
  cwd,
2370
2483
  poll
2371
2484
  });
2372
- const bundleStyles = async (ctx, changedFilePath) => {
2485
+ /**
2486
+ * Re-parses every affected file, then builds and writes the stylesheet once.
2487
+ *
2488
+ * One edit can affect many files — a shared style file is folded into all of
2489
+ * its importers — and the sheet is rebuilt from the whole parser result, not
2490
+ * per file. Writing per file would run the optimize pipeline and hit the disk
2491
+ * once per importer for a single keystroke.
2492
+ */
2493
+ const bundleStyles = async (ctx, changedFilePaths) => {
2494
+ let parsed = 0;
2495
+ for (const filePath of changedFilePaths) if (ctx.project.parseSourceFile(filePath)) parsed++;
2496
+ if (parsed === 0) return;
2373
2497
  const outfile = ctx.runtime.path.join(...ctx.paths.root, "styles.css");
2374
- if (ctx.project.parseSourceFile(changedFilePath)) {
2375
- const done = logger.time.info(ctx.messages.buildComplete(1));
2376
- const sheet = ctx.createSheet();
2377
- ctx.appendLayerParams(sheet);
2378
- ctx.appendBaselineCss(sheet);
2379
- ctx.appendParserCss(sheet);
2380
- const css = ctx.getCss(sheet);
2381
- await ctx.runtime.fs.writeFile(outfile, css);
2382
- done();
2383
- }
2498
+ const done = logger.time.info(ctx.messages.buildComplete(parsed));
2499
+ const sheet = ctx.createSheet();
2500
+ ctx.appendLayerParams(sheet);
2501
+ ctx.appendBaselineCss(sheet);
2502
+ ctx.appendParserCss(sheet);
2503
+ if (ctx.config.pruneUnusedTokens) ctx.pruneTokens(sheet, collectTokenReferences(ctx, []));
2504
+ if (ctx.config.pruneUnusedKeyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)));
2505
+ const css = ctx.getCss(sheet);
2506
+ await ctx.runtime.fs.writeFile(outfile, css);
2507
+ done();
2384
2508
  };
2385
2509
  ctx.watchFiles(async (event, file) => {
2386
2510
  const filePath = ctx.runtime.path.abs(cwd, file);
2387
- if (event === "unlink") ctx.project.removeSourceFile(filePath);
2388
- else if (event === "change") {
2389
- ctx.project.reloadSourceFile(file);
2390
- await bundleStyles(ctx, filePath);
2511
+ if (event === "unlink") {
2512
+ const dependents = ctx.project.getDependents(filePath);
2513
+ ctx.project.removeSourceFile(filePath);
2514
+ await bundleStyles(ctx, dependents);
2515
+ } else if (event === "change") {
2516
+ ctx.project.reloadSourceFile(filePath);
2517
+ await bundleStyles(ctx, [filePath, ...ctx.project.getDependents(filePath)]);
2391
2518
  } else if (event === "add") {
2392
- ctx.project.createSourceFile(file);
2393
- await bundleStyles(ctx, filePath);
2519
+ ctx.project.createSourceFile(filePath);
2520
+ await bundleStyles(ctx, [
2521
+ filePath,
2522
+ ...ctx.project.getDependents(filePath),
2523
+ ...ctx.project.getUnresolvedImporters()
2524
+ ]);
2394
2525
  }
2395
2526
  });
2396
2527
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@bamboocss/node",
3
- "version": "1.12.3",
3
+ "version": "1.13.1",
4
4
  "description": "The core css bamboo library",
5
- "homepage": "https://bamboo-css.com",
5
+ "homepage": "https://bamboocss.com",
6
6
  "license": "MIT",
7
- "author": "Segun Adebayo <joseshegs@gmail.com>",
7
+ "author": "Gajus Kuizinas <gajus@gajus.com>",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/bamboocss/bamboo.git",
@@ -52,18 +52,18 @@
52
52
  "postcss": "8.5.14",
53
53
  "ts-morph": "28.0.0",
54
54
  "ts-pattern": "5.9.0",
55
- "@bamboocss/config": "1.12.3",
56
- "@bamboocss/generator": "1.12.3",
57
- "@bamboocss/core": "1.12.3",
58
- "@bamboocss/plugin-lightningcss": "1.12.3",
59
- "@bamboocss/parser": "1.12.3",
60
- "@bamboocss/logger": "1.12.3",
61
- "@bamboocss/plugin-vue": "1.12.3",
62
- "@bamboocss/reporter": "1.12.3",
63
- "@bamboocss/plugin-svelte": "1.12.3",
64
- "@bamboocss/types": "1.12.3",
65
- "@bamboocss/token-dictionary": "1.12.3",
66
- "@bamboocss/shared": "1.12.3"
55
+ "@bamboocss/config": "1.13.1",
56
+ "@bamboocss/core": "1.13.1",
57
+ "@bamboocss/generator": "1.13.1",
58
+ "@bamboocss/logger": "1.13.1",
59
+ "@bamboocss/parser": "1.13.1",
60
+ "@bamboocss/plugin-lightningcss": "1.13.1",
61
+ "@bamboocss/plugin-svelte": "1.13.1",
62
+ "@bamboocss/plugin-vue": "1.13.1",
63
+ "@bamboocss/reporter": "1.13.1",
64
+ "@bamboocss/shared": "1.13.1",
65
+ "@bamboocss/token-dictionary": "1.13.1",
66
+ "@bamboocss/types": "1.13.1"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@types/fs-extra": "11.0.4",