@bamboocss/node 1.45.5 → 1.46.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/dist/index.cjs CHANGED
@@ -22,6 +22,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
22
22
  enumerable: true
23
23
  }) : target, mod));
24
24
  //#endregion
25
+ const require_static_compiler = require("./static-compiler.cjs");
25
26
  let _bamboocss_reporter = require("@bamboocss/reporter");
26
27
  let _bamboocss_logger = require("@bamboocss/logger");
27
28
  let _bamboocss_config = require("@bamboocss/config");
@@ -40,6 +41,11 @@ let node_os = require("node:os");
40
41
  node_os = __toESM(node_os, 1);
41
42
  let node_tty = require("node:tty");
42
43
  node_tty = __toESM(node_tty, 1);
44
+ let node_fs = require("node:fs");
45
+ node_fs = __toESM(node_fs);
46
+ let node_path = require("node:path");
47
+ node_path = __toESM(node_path);
48
+ let ts_morph = require("ts-morph");
43
49
  let chokidar = require("chokidar");
44
50
  chokidar = __toESM(chokidar);
45
51
  let fast_glob = require("fast-glob");
@@ -48,17 +54,12 @@ let fs_extra = require("fs-extra");
48
54
  fs_extra = __toESM(fs_extra);
49
55
  let picomatch = require("picomatch");
50
56
  picomatch = __toESM(picomatch);
51
- let node_path = require("node:path");
52
- node_path = __toESM(node_path);
53
- let node_fs = require("node:fs");
54
- node_fs = __toESM(node_fs);
55
57
  let is_glob = require("is-glob");
56
58
  is_glob = __toESM(is_glob);
57
59
  let glob_parent = require("glob-parent");
58
60
  glob_parent = __toESM(glob_parent);
59
61
  let matcher = require("matcher");
60
62
  let _bamboocss_config_ts_path = require("@bamboocss/config/ts-path");
61
- let ts_morph = require("ts-morph");
62
63
  let node_readline = require("node:readline");
63
64
  node_readline = __toESM(node_readline);
64
65
  let look_it_up = require("look-it-up");
@@ -1405,7 +1406,345 @@ const createBox = (options) => boxen(options.content, {
1405
1406
  titleAlignment: "center"
1406
1407
  });
1407
1408
  //#endregion
1409
+ //#region src/tsconfig-utils.ts
1410
+ /**
1411
+ * If `filename` points to a `.json` file that exists as a regular file, return its absolute path.
1412
+ */
1413
+ async function resolveDirectTsconfigJson(filename) {
1414
+ if (node_path.default.extname(filename) !== ".json") return null;
1415
+ const resolved = node_path.default.resolve(filename);
1416
+ try {
1417
+ const stat = await node_fs.promises.stat(resolved);
1418
+ if (stat.isFile() || stat.isFIFO()) return resolved;
1419
+ throw new Error(`${filename} exists but is not a regular file.`);
1420
+ } catch (e) {
1421
+ if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return null;
1422
+ throw e;
1423
+ }
1424
+ }
1425
+ /**
1426
+ * Walk upward from `dirname(filename)` and return the first existing `configName`,
1427
+ * stopping at `root` (inclusive) or the filesystem root.
1428
+ */
1429
+ async function findClosestTsconfig(filename, root, configName = "tsconfig.json") {
1430
+ const resolvedRoot = node_path.default.resolve(root);
1431
+ let dir = node_path.default.dirname(node_path.default.resolve(filename));
1432
+ for (;;) {
1433
+ const candidate = node_path.default.join(dir, configName);
1434
+ try {
1435
+ const stat = await node_fs.promises.stat(candidate);
1436
+ if (stat.isFile() || stat.isFIFO()) return candidate;
1437
+ } catch {}
1438
+ if (dir === resolvedRoot || node_path.default.dirname(dir) === dir) return null;
1439
+ dir = node_path.default.dirname(dir);
1440
+ }
1441
+ }
1442
+ /**
1443
+ * Resolve `compilerOptions.baseUrl` the same way TypeScript does: relative to the tsconfig file.
1444
+ * Falls back to `cwd` when `baseUrl` is omitted.
1445
+ */
1446
+ function resolveBaseUrlForCompilerOptions(baseUrl, tsconfigFile, cwd) {
1447
+ if (baseUrl == null) return cwd;
1448
+ if (baseUrl.startsWith("${")) return baseUrl;
1449
+ if (node_path.default.isAbsolute(baseUrl)) return baseUrl;
1450
+ return node_path.default.resolve(node_path.default.dirname(tsconfigFile), baseUrl);
1451
+ }
1452
+ const SOURCE_EXTENSIONS = [
1453
+ ".ts",
1454
+ ".tsx",
1455
+ ".mts",
1456
+ ".cts"
1457
+ ];
1458
+ function resolveReferencedTsconfigPath(refPath, fromDir, configName = "tsconfig.json") {
1459
+ const p = refPath.endsWith(".json") ? refPath : node_path.default.join(refPath, configName);
1460
+ return node_path.default.resolve(fromDir, p);
1461
+ }
1462
+ /**
1463
+ * When a file belongs to a referenced project (TypeScript project references),
1464
+ * return that project's merged tsconfig for `compilerOptions`.
1465
+ */
1466
+ async function resolveSolutionTsconfigForFile(absoluteFilename, rootTsconfigPath, rootParsed, getTsconfigModule, cache) {
1467
+ const { parseTsconfig } = getTsconfigModule;
1468
+ if (isSourceFileIncludedInTsconfig(absoluteFilename, rootTsconfigPath, rootParsed)) return {
1469
+ tsconfig: rootParsed,
1470
+ tsconfigFile: rootTsconfigPath
1471
+ };
1472
+ const refs = rootParsed.references;
1473
+ if (!refs?.length) return {
1474
+ tsconfig: rootParsed,
1475
+ tsconfigFile: rootTsconfigPath
1476
+ };
1477
+ if (!SOURCE_EXTENSIONS.some((ext) => absoluteFilename.endsWith(ext))) return {
1478
+ tsconfig: rootParsed,
1479
+ tsconfigFile: rootTsconfigPath
1480
+ };
1481
+ const rootDir = node_path.default.dirname(rootTsconfigPath);
1482
+ for (const ref of refs) {
1483
+ const refPath = resolveReferencedTsconfigPath(ref.path, rootDir);
1484
+ try {
1485
+ await node_fs.promises.access(refPath);
1486
+ } catch {
1487
+ continue;
1488
+ }
1489
+ const childParsed = parseTsconfig(refPath, cache);
1490
+ if (isSourceFileIncludedInTsconfig(absoluteFilename, refPath, childParsed)) return {
1491
+ tsconfig: childParsed,
1492
+ tsconfigFile: refPath
1493
+ };
1494
+ }
1495
+ return {
1496
+ tsconfig: rootParsed,
1497
+ tsconfigFile: rootTsconfigPath
1498
+ };
1499
+ }
1500
+ const POSIX_SEP_RE = new RegExp("\\" + node_path.default.posix.sep, "g");
1501
+ const NATIVE_SEP_RE = new RegExp("\\" + node_path.default.sep, "g");
1502
+ const PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
1503
+ const GLOB_ALL_PATTERN = `**/*`;
1504
+ const TS_EXTENSIONS = [
1505
+ ".ts",
1506
+ ".tsx",
1507
+ ".mts",
1508
+ ".cts"
1509
+ ];
1510
+ const TSJS_EXTENSIONS = TS_EXTENSIONS.concat([
1511
+ ".js",
1512
+ ".jsx",
1513
+ ".mjs",
1514
+ ".cjs"
1515
+ ]);
1516
+ const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
1517
+ const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
1518
+ const IS_POSIX = node_path.default.posix.sep === node_path.default.sep;
1519
+ const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, node_path.default.posix.sep);
1520
+ const resolve2posix = IS_POSIX ? (dir, filename) => dir ? node_path.default.resolve(dir, filename) : node_path.default.resolve(filename) : (dir, filename) => {
1521
+ const posix2native = (f) => f.replace(POSIX_SEP_RE, node_path.default.sep);
1522
+ return native2posix(dir ? node_path.default.resolve(posix2native(dir), posix2native(filename)) : node_path.default.resolve(posix2native(filename)));
1523
+ };
1524
+ function isGlobMatch(filename, dir, patterns, allowJs) {
1525
+ const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
1526
+ return patterns.some((patternArg) => {
1527
+ let pattern = patternArg;
1528
+ let lastWildcardIndex = pattern.length;
1529
+ let hasWildcard = false;
1530
+ let hasExtension = false;
1531
+ let hasSlash = false;
1532
+ let lastSlashIndex = -1;
1533
+ for (let i = pattern.length - 1; i > -1; i--) {
1534
+ const c = pattern[i];
1535
+ if (!hasWildcard) {
1536
+ if (c === "*" || c === "?") {
1537
+ lastWildcardIndex = i;
1538
+ hasWildcard = true;
1539
+ }
1540
+ }
1541
+ if (!hasSlash) {
1542
+ if (c === ".") hasExtension = true;
1543
+ else if (c === "/") {
1544
+ lastSlashIndex = i;
1545
+ hasSlash = true;
1546
+ }
1547
+ }
1548
+ if (hasWildcard && hasSlash) break;
1549
+ }
1550
+ if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
1551
+ pattern += `${pattern.endsWith("/") ? "" : "/"}${GLOB_ALL_PATTERN}`;
1552
+ lastWildcardIndex = pattern.length - 1;
1553
+ hasWildcard = true;
1554
+ }
1555
+ if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
1556
+ if (pattern.endsWith("*") && !extensions.some((ext) => filename.endsWith(ext))) return false;
1557
+ if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
1558
+ const resolvedPattern = resolve2posix(dir, pattern);
1559
+ let firstWildcardIndex = -1;
1560
+ for (let i = 0; i < resolvedPattern.length; i++) if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
1561
+ firstWildcardIndex = i;
1562
+ hasWildcard = true;
1563
+ break;
1564
+ }
1565
+ if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
1566
+ if (!hasWildcard) return filename === resolvedPattern;
1567
+ if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) return true;
1568
+ if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
1569
+ const regex = pattern2regex(resolvedPattern, allowJs);
1570
+ PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
1571
+ return regex.test(filename);
1572
+ });
1573
+ }
1574
+ function pattern2regex(resolvedPattern, allowJs) {
1575
+ let regexStr = "^";
1576
+ for (let i = 0; i < resolvedPattern.length; i++) {
1577
+ const char = resolvedPattern[i];
1578
+ if (char === "?") {
1579
+ regexStr += "[^\\/]";
1580
+ continue;
1581
+ }
1582
+ if (char === "*") {
1583
+ if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
1584
+ i += 2;
1585
+ regexStr += "(?:[^\\/]*\\/)*";
1586
+ continue;
1587
+ }
1588
+ regexStr += "[^\\/]*";
1589
+ continue;
1590
+ }
1591
+ if ("/.+^${}()|[]\\".includes(char)) regexStr += "\\";
1592
+ regexStr += char;
1593
+ }
1594
+ if (resolvedPattern.endsWith("*")) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
1595
+ regexStr += "$";
1596
+ return new RegExp(regexStr);
1597
+ }
1598
+ function isIncluded(filename, tsconfigFile, tsconfig) {
1599
+ const dir = native2posix(node_path.default.dirname(tsconfigFile));
1600
+ const files = (tsconfig.files || []).map((file) => resolve2posix(dir, file));
1601
+ const absoluteFilename = resolve2posix(null, filename);
1602
+ if (files.includes(filename)) return true;
1603
+ const allowJs = tsconfig.compilerOptions?.allowJs;
1604
+ if (isGlobMatch(absoluteFilename, dir, tsconfig.include || (tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs)) return !isGlobMatch(absoluteFilename, dir, tsconfig.exclude || [], allowJs);
1605
+ return false;
1606
+ }
1607
+ /** Whether `absoluteFilename` is part of the compilation set defined by this tsconfig. */
1608
+ function isSourceFileIncludedInTsconfig(absoluteFilename, tsconfigFile, tsconfig) {
1609
+ return isIncluded(absoluteFilename, tsconfigFile, tsconfig);
1610
+ }
1611
+ //#endregion
1612
+ //#region src/load-tsconfig.ts
1613
+ const readPathsFromCache = (cache) => {
1614
+ const prefix = "readFileSync:";
1615
+ const suffix = ":utf8";
1616
+ return Array.from(cache.keys()).filter((key) => key.startsWith(prefix) && key.endsWith(suffix)).map((key) => key.slice(13, -5));
1617
+ };
1618
+ /**
1619
+ * Exact tsconfig files read while producing one resolved Node config.
1620
+ *
1621
+ * This metadata is deliberately kept outside `LoadConfigResult`: it is incremental resolver
1622
+ * provenance, not Bamboo configuration, and must therefore neither participate in
1623
+ * `diffConfigs` nor become part of the public/serialized config shape.
1624
+ */
1625
+ const resolutionFilesByConfig = /* @__PURE__ */ new WeakMap();
1626
+ const rememberTsConfigResolutionFiles = (conf, files) => {
1627
+ resolutionFilesByConfig.set(conf, Object.freeze([...new Set(files)].sort()));
1628
+ };
1629
+ const getTsConfigResolutionFiles = (conf) => resolutionFilesByConfig.get(conf) ?? Object.freeze(conf.tsconfigFile ? [node_path.default.resolve(conf.tsconfigFile)] : []);
1630
+ const referencedTsconfigPath = (reference, rootPath) => node_path.default.resolve(node_path.default.dirname(rootPath), reference.endsWith(".json") ? reference : node_path.default.join(reference, "tsconfig.json"));
1631
+ const MAX_TSCONFIG_REFERENCE_FILES = 256;
1632
+ const getImplicitBaseUrl = (compilerOptions) => {
1633
+ if (!compilerOptions) return void 0;
1634
+ const matches = Object.getOwnPropertySymbols(compilerOptions).filter((candidate) => candidate.description === "implicitBaseUrl");
1635
+ if (matches.length !== 1) return void 0;
1636
+ const symbol = matches[0];
1637
+ const descriptor = Object.getOwnPropertyDescriptor(compilerOptions, symbol);
1638
+ if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "string") return void 0;
1639
+ return {
1640
+ owner: compilerOptions,
1641
+ symbol,
1642
+ value: descriptor.value
1643
+ };
1644
+ };
1645
+ const collectReferenceGraph = async (rootPath, rootParsed, parseTsconfig, cache) => {
1646
+ const references = [];
1647
+ const unresolvedReferences = [];
1648
+ let traversalLimitExceeded = false;
1649
+ const visited = new Set([node_path.default.resolve(rootPath)]);
1650
+ const queue = [{
1651
+ parsed: rootParsed,
1652
+ path: rootPath
1653
+ }];
1654
+ for (let index = 0; index < queue.length; index++) {
1655
+ const current = queue[index];
1656
+ for (const reference of current.parsed.references ?? []) {
1657
+ const referencedPath = referencedTsconfigPath(reference.path, current.path);
1658
+ references.push({
1659
+ from: current.path,
1660
+ path: referencedPath
1661
+ });
1662
+ if (visited.has(referencedPath)) continue;
1663
+ if (visited.size >= MAX_TSCONFIG_REFERENCE_FILES) {
1664
+ traversalLimitExceeded = true;
1665
+ unresolvedReferences.push(referencedPath);
1666
+ continue;
1667
+ }
1668
+ visited.add(referencedPath);
1669
+ try {
1670
+ const source = await node_fs.promises.readFile(referencedPath, "utf8");
1671
+ if (ts_morph.ts.parseConfigFileTextToJson(referencedPath, source).error) throw new Error("Invalid tsconfig");
1672
+ queue.push({
1673
+ parsed: parseTsconfig(referencedPath, cache),
1674
+ path: referencedPath
1675
+ });
1676
+ } catch {
1677
+ unresolvedReferences.push(referencedPath);
1678
+ }
1679
+ }
1680
+ }
1681
+ return {
1682
+ references,
1683
+ traversalLimitExceeded,
1684
+ unresolvedReferences
1685
+ };
1686
+ };
1687
+ async function loadTsConfig(conf, cwd, provenance, resolutionFiles) {
1688
+ const root = cwd;
1689
+ let tsconfigFile = await resolveDirectTsconfigJson(conf.path);
1690
+ const direct = tsconfigFile !== null;
1691
+ if (!tsconfigFile) {
1692
+ if (resolutionFiles) resolutionFiles.value = Object.freeze([]);
1693
+ tsconfigFile = await findClosestTsconfig(conf.path, root, "tsconfig.json");
1694
+ }
1695
+ if (!tsconfigFile) {
1696
+ if (provenance) provenance.value = {
1697
+ direct: false,
1698
+ readPaths: [],
1699
+ references: [],
1700
+ traversalLimitExceeded: false,
1701
+ unresolvedReferences: []
1702
+ };
1703
+ return {
1704
+ tsconfig: {},
1705
+ tsconfigFile: void 0
1706
+ };
1707
+ }
1708
+ const gtc = await import("get-tsconfig");
1709
+ const cache = /* @__PURE__ */ new Map();
1710
+ const rootParsed = gtc.parseTsconfig(tsconfigFile, cache);
1711
+ const { tsconfig, tsconfigFile: effectiveTsconfigPath } = await resolveSolutionTsconfigForFile(node_path.default.resolve(conf.path), tsconfigFile, rootParsed, gtc, cache);
1712
+ const compilerOptions = tsconfig?.compilerOptions;
1713
+ const implicitBaseUrl = getImplicitBaseUrl(compilerOptions);
1714
+ const result = {
1715
+ tsconfig,
1716
+ tsconfigFile: effectiveTsconfigPath
1717
+ };
1718
+ if (resolutionFiles) resolutionFiles.value = Object.freeze([...new Set(readPathsFromCache(cache).map((file) => node_path.default.resolve(file)))].sort());
1719
+ if (compilerOptions?.paths) {
1720
+ const baseUrl = compilerOptions.baseUrl;
1721
+ result.tsOptions = {
1722
+ baseUrl,
1723
+ pathMappings: (0, _bamboocss_config.convertTsPathsToRegexes)(compilerOptions.paths, resolveBaseUrlForCompilerOptions(baseUrl, effectiveTsconfigPath, cwd))
1724
+ };
1725
+ }
1726
+ if (provenance) {
1727
+ const referenceGraph = await collectReferenceGraph(tsconfigFile, rootParsed, gtc.parseTsconfig, cache);
1728
+ provenance.value = {
1729
+ direct,
1730
+ effectivePath: effectiveTsconfigPath,
1731
+ implicitBaseUrl,
1732
+ readPaths: readPathsFromCache(cache),
1733
+ references: referenceGraph.references,
1734
+ rootPath: tsconfigFile,
1735
+ traversalLimitExceeded: referenceGraph.traversalLimitExceeded,
1736
+ unresolvedReferences: referenceGraph.unresolvedReferences
1737
+ };
1738
+ }
1739
+ return result;
1740
+ }
1741
+ //#endregion
1408
1742
  //#region src/diff-engine.ts
1743
+ const applyTsConfig = (conf, next) => {
1744
+ conf.tsconfig = next?.tsconfig ?? {};
1745
+ conf.tsconfigFile = next?.tsconfigFile;
1746
+ conf.tsOptions = next?.tsOptions;
1747
+ };
1409
1748
  var DiffEngine = class {
1410
1749
  ctx;
1411
1750
  prevConfig;
@@ -1421,14 +1760,19 @@ var DiffEngine = class {
1421
1760
  cwd: this.ctx.config.cwd,
1422
1761
  file: this.ctx.conf.path
1423
1762
  });
1424
- const { tsconfig, tsconfigFile, tsOptions } = this.ctx.conf;
1425
- Object.assign(conf, {
1426
- tsconfig,
1427
- tsconfigFile,
1428
- tsOptions
1429
- });
1430
- return this.refresh(conf, fn);
1763
+ const resolutionFiles = {};
1764
+ const tsconfig = await loadTsConfig(conf, conf.config.cwd || this.ctx.config.cwd, void 0, resolutionFiles);
1765
+ applyTsConfig(conf, tsconfig);
1766
+ rememberTsConfigResolutionFiles(conf, resolutionFiles.value ?? []);
1767
+ const affected = this.refresh(conf, fn);
1768
+ if (!affected.hasConfigChanged) {
1769
+ applyTsConfig(this.ctx.conf, tsconfig);
1770
+ rememberTsConfigResolutionFiles(this.ctx.conf, resolutionFiles.value ?? []);
1771
+ }
1772
+ return affected;
1431
1773
  }
1774
+ /** @internal Exact tsconfig files behind the currently attached resolution options. */
1775
+ getResolutionConfigFiles = () => getTsConfigResolutionFiles(this.ctx.conf);
1432
1776
  /**
1433
1777
  * Update the context from the refreshed config
1434
1778
  * then persist the changes on each affected engines
@@ -1742,8 +2086,10 @@ var BambooContext = class extends _bamboocss_generator.Generator {
1742
2086
  if (config.logLevel) _bamboocss_logger.logger.level = config.logLevel;
1743
2087
  this.project = new _bamboocss_parser.Project({
1744
2088
  ...conf.tsconfig,
1745
- getFiles: this.getFiles.bind(this),
1746
- readFile: this.runtime.fs.readFileSync.bind(this),
2089
+ deferInitialSourceFiles: true,
2090
+ resolutionConfigFiles: getTsConfigResolutionFiles(conf),
2091
+ getFiles: () => this.getFiles(),
2092
+ readFile: (filePath) => this.runtime.fs.readFileSync(filePath),
1747
2093
  hooks: conf.hooks,
1748
2094
  parserOptions: {
1749
2095
  ...this.parserOptions,
@@ -2047,238 +2393,13 @@ async function reportRebuildFailure(run) {
2047
2393
  }
2048
2394
  }
2049
2395
  //#endregion
2050
- //#region src/tsconfig-utils.ts
2051
- /**
2052
- * If `filename` points to a `.json` file that exists as a regular file, return its absolute path.
2053
- */
2054
- async function resolveDirectTsconfigJson(filename) {
2055
- if (node_path.default.extname(filename) !== ".json") return null;
2056
- const resolved = node_path.default.resolve(filename);
2057
- try {
2058
- const stat = await node_fs.promises.stat(resolved);
2059
- if (stat.isFile() || stat.isFIFO()) return resolved;
2060
- throw new Error(`${filename} exists but is not a regular file.`);
2061
- } catch (e) {
2062
- if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return null;
2063
- throw e;
2064
- }
2065
- }
2066
- /**
2067
- * Walk upward from `dirname(filename)` and return the first existing `configName`,
2068
- * stopping at `root` (inclusive) or the filesystem root.
2069
- */
2070
- async function findClosestTsconfig(filename, root, configName = "tsconfig.json") {
2071
- const resolvedRoot = node_path.default.resolve(root);
2072
- let dir = node_path.default.dirname(node_path.default.resolve(filename));
2073
- for (;;) {
2074
- const candidate = node_path.default.join(dir, configName);
2075
- try {
2076
- const stat = await node_fs.promises.stat(candidate);
2077
- if (stat.isFile() || stat.isFIFO()) return candidate;
2078
- } catch {}
2079
- if (dir === resolvedRoot || node_path.default.dirname(dir) === dir) return null;
2080
- dir = node_path.default.dirname(dir);
2081
- }
2082
- }
2083
- /**
2084
- * Resolve `compilerOptions.baseUrl` the same way TypeScript does: relative to the tsconfig file.
2085
- * Falls back to `cwd` when `baseUrl` is omitted.
2086
- */
2087
- function resolveBaseUrlForCompilerOptions(baseUrl, tsconfigFile, cwd) {
2088
- if (baseUrl == null) return cwd;
2089
- if (baseUrl.startsWith("${")) return baseUrl;
2090
- if (node_path.default.isAbsolute(baseUrl)) return baseUrl;
2091
- return node_path.default.resolve(node_path.default.dirname(tsconfigFile), baseUrl);
2092
- }
2093
- const SOURCE_EXTENSIONS = [
2094
- ".ts",
2095
- ".tsx",
2096
- ".mts",
2097
- ".cts"
2098
- ];
2099
- function resolveReferencedTsconfigPath(refPath, fromDir, configName = "tsconfig.json") {
2100
- const p = refPath.endsWith(".json") ? refPath : node_path.default.join(refPath, configName);
2101
- return node_path.default.resolve(fromDir, p);
2102
- }
2103
- /**
2104
- * When a file belongs to a referenced project (TypeScript project references),
2105
- * return that project's merged tsconfig for `compilerOptions`.
2106
- */
2107
- async function resolveSolutionTsconfigForFile(absoluteFilename, rootTsconfigPath, rootParsed, getTsconfigModule) {
2108
- const { parseTsconfig } = getTsconfigModule;
2109
- if (isSourceFileIncludedInTsconfig(absoluteFilename, rootTsconfigPath, rootParsed)) return {
2110
- tsconfig: rootParsed,
2111
- tsconfigFile: rootTsconfigPath
2112
- };
2113
- const refs = rootParsed.references;
2114
- if (!refs?.length) return {
2115
- tsconfig: rootParsed,
2116
- tsconfigFile: rootTsconfigPath
2117
- };
2118
- if (!SOURCE_EXTENSIONS.some((ext) => absoluteFilename.endsWith(ext))) return {
2119
- tsconfig: rootParsed,
2120
- tsconfigFile: rootTsconfigPath
2121
- };
2122
- const rootDir = node_path.default.dirname(rootTsconfigPath);
2123
- for (const ref of refs) {
2124
- const refPath = resolveReferencedTsconfigPath(ref.path, rootDir);
2125
- try {
2126
- await node_fs.promises.access(refPath);
2127
- } catch {
2128
- continue;
2129
- }
2130
- const childParsed = parseTsconfig(refPath);
2131
- if (isSourceFileIncludedInTsconfig(absoluteFilename, refPath, childParsed)) return {
2132
- tsconfig: childParsed,
2133
- tsconfigFile: refPath
2134
- };
2135
- }
2136
- return {
2137
- tsconfig: rootParsed,
2138
- tsconfigFile: rootTsconfigPath
2139
- };
2140
- }
2141
- const POSIX_SEP_RE = new RegExp("\\" + node_path.default.posix.sep, "g");
2142
- const NATIVE_SEP_RE = new RegExp("\\" + node_path.default.sep, "g");
2143
- const PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
2144
- const GLOB_ALL_PATTERN = `**/*`;
2145
- const TS_EXTENSIONS = [
2146
- ".ts",
2147
- ".tsx",
2148
- ".mts",
2149
- ".cts"
2150
- ];
2151
- const TSJS_EXTENSIONS = TS_EXTENSIONS.concat([
2152
- ".js",
2153
- ".jsx",
2154
- ".mjs",
2155
- ".cjs"
2156
- ]);
2157
- const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
2158
- const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
2159
- const IS_POSIX = node_path.default.posix.sep === node_path.default.sep;
2160
- const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, node_path.default.posix.sep);
2161
- const resolve2posix = IS_POSIX ? (dir, filename) => dir ? node_path.default.resolve(dir, filename) : node_path.default.resolve(filename) : (dir, filename) => {
2162
- const posix2native = (f) => f.replace(POSIX_SEP_RE, node_path.default.sep);
2163
- return native2posix(dir ? node_path.default.resolve(posix2native(dir), posix2native(filename)) : node_path.default.resolve(posix2native(filename)));
2164
- };
2165
- function isGlobMatch(filename, dir, patterns, allowJs) {
2166
- const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
2167
- return patterns.some((patternArg) => {
2168
- let pattern = patternArg;
2169
- let lastWildcardIndex = pattern.length;
2170
- let hasWildcard = false;
2171
- let hasExtension = false;
2172
- let hasSlash = false;
2173
- let lastSlashIndex = -1;
2174
- for (let i = pattern.length - 1; i > -1; i--) {
2175
- const c = pattern[i];
2176
- if (!hasWildcard) {
2177
- if (c === "*" || c === "?") {
2178
- lastWildcardIndex = i;
2179
- hasWildcard = true;
2180
- }
2181
- }
2182
- if (!hasSlash) {
2183
- if (c === ".") hasExtension = true;
2184
- else if (c === "/") {
2185
- lastSlashIndex = i;
2186
- hasSlash = true;
2187
- }
2188
- }
2189
- if (hasWildcard && hasSlash) break;
2190
- }
2191
- if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
2192
- pattern += `${pattern.endsWith("/") ? "" : "/"}${GLOB_ALL_PATTERN}`;
2193
- lastWildcardIndex = pattern.length - 1;
2194
- hasWildcard = true;
2195
- }
2196
- if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
2197
- if (pattern.endsWith("*") && !extensions.some((ext) => filename.endsWith(ext))) return false;
2198
- if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
2199
- const resolvedPattern = resolve2posix(dir, pattern);
2200
- let firstWildcardIndex = -1;
2201
- for (let i = 0; i < resolvedPattern.length; i++) if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
2202
- firstWildcardIndex = i;
2203
- hasWildcard = true;
2204
- break;
2205
- }
2206
- if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
2207
- if (!hasWildcard) return filename === resolvedPattern;
2208
- if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) return true;
2209
- if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
2210
- const regex = pattern2regex(resolvedPattern, allowJs);
2211
- PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
2212
- return regex.test(filename);
2213
- });
2214
- }
2215
- function pattern2regex(resolvedPattern, allowJs) {
2216
- let regexStr = "^";
2217
- for (let i = 0; i < resolvedPattern.length; i++) {
2218
- const char = resolvedPattern[i];
2219
- if (char === "?") {
2220
- regexStr += "[^\\/]";
2221
- continue;
2222
- }
2223
- if (char === "*") {
2224
- if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
2225
- i += 2;
2226
- regexStr += "(?:[^\\/]*\\/)*";
2227
- continue;
2228
- }
2229
- regexStr += "[^\\/]*";
2230
- continue;
2231
- }
2232
- if ("/.+^${}()|[]\\".includes(char)) regexStr += "\\";
2233
- regexStr += char;
2234
- }
2235
- if (resolvedPattern.endsWith("*")) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
2236
- regexStr += "$";
2237
- return new RegExp(regexStr);
2238
- }
2239
- function isIncluded(filename, tsconfigFile, tsconfig) {
2240
- const dir = native2posix(node_path.default.dirname(tsconfigFile));
2241
- const files = (tsconfig.files || []).map((file) => resolve2posix(dir, file));
2242
- const absoluteFilename = resolve2posix(null, filename);
2243
- if (files.includes(filename)) return true;
2244
- const allowJs = tsconfig.compilerOptions?.allowJs;
2245
- if (isGlobMatch(absoluteFilename, dir, tsconfig.include || (tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs)) return !isGlobMatch(absoluteFilename, dir, tsconfig.exclude || [], allowJs);
2246
- return false;
2247
- }
2248
- /** Whether `absoluteFilename` is part of the compilation set defined by this tsconfig. */
2249
- function isSourceFileIncludedInTsconfig(absoluteFilename, tsconfigFile, tsconfig) {
2250
- return isIncluded(absoluteFilename, tsconfigFile, tsconfig);
2251
- }
2252
- //#endregion
2253
- //#region src/load-tsconfig.ts
2254
- async function loadTsConfig(conf, cwd) {
2255
- const root = cwd;
2256
- let tsconfigFile = await resolveDirectTsconfigJson(conf.path);
2257
- if (!tsconfigFile) tsconfigFile = await findClosestTsconfig(conf.path, root, "tsconfig.json");
2258
- if (!tsconfigFile) return {
2259
- tsconfig: {},
2260
- tsconfigFile: void 0
2261
- };
2262
- const gtc = await import("get-tsconfig");
2263
- const rootParsed = gtc.parseTsconfig(tsconfigFile);
2264
- const { tsconfig, tsconfigFile: effectiveTsconfigPath } = await resolveSolutionTsconfigForFile(node_path.default.resolve(conf.path), tsconfigFile, rootParsed, gtc);
2265
- const compilerOptions = tsconfig?.compilerOptions;
2266
- const result = {
2267
- tsconfig,
2268
- tsconfigFile: effectiveTsconfigPath
2269
- };
2270
- if (compilerOptions?.paths) {
2271
- const baseUrl = compilerOptions.baseUrl;
2272
- result.tsOptions = {
2273
- baseUrl,
2274
- pathMappings: (0, _bamboocss_config.convertTsPathsToRegexes)(compilerOptions.paths, resolveBaseUrlForCompilerOptions(baseUrl, effectiveTsconfigPath, cwd))
2275
- };
2276
- }
2277
- return result;
2278
- }
2279
- //#endregion
2280
2396
  //#region src/config.ts
2281
2397
  const RESOLVED_HOOKS_NAME = "__resolved__";
2398
+ const AUTO_PARSER_HOOKS = Object.freeze(["vue", "svelte"]);
2399
+ const autoPluginFactories = {
2400
+ svelte: _bamboocss_plugin_svelte.pluginSvelte,
2401
+ vue: _bamboocss_plugin_vue.pluginVue
2402
+ };
2282
2403
  /**
2283
2404
  * Built-in plugins that are auto-injected when using the CLI or PostCSS plugin.
2284
2405
  * These provide Vue/Svelte single-file-component support.
@@ -2291,13 +2412,10 @@ const RESOLVED_HOOKS_NAME = "__resolved__";
2291
2412
  * ever set. List the plugin yourself to use it.
2292
2413
  */
2293
2414
  function getAutoPlugins() {
2294
- return [(0, _bamboocss_plugin_vue.pluginVue)(), (0, _bamboocss_plugin_svelte.pluginSvelte)()];
2415
+ return AUTO_PARSER_HOOKS.map((identity) => autoPluginFactories[identity]());
2295
2416
  }
2296
- /**
2297
- * Load config and create context with auto-injected plugins.
2298
- * Used by the CLI and PostCSS plugin.
2299
- */
2300
- async function loadConfigAndCreateContext(options = {}) {
2417
+ /** Resolve all config state without constructing the parser Project owned by BambooContext. */
2418
+ async function prepareNodeConfig(options = {}) {
2301
2419
  const { config, configPath } = options;
2302
2420
  const cwd = options.cwd ?? options?.config?.cwd ?? process.cwd();
2303
2421
  const conf = await (0, _bamboocss_config.loadConfig)({
@@ -2313,8 +2431,18 @@ async function loadConfigAndCreateContext(options = {}) {
2313
2431
  hooks: conf.hooks
2314
2432
  }]);
2315
2433
  conf.config.plugins = [...autoPlugins, ...conf.config.plugins ?? []];
2316
- const tsConfResult = await loadTsConfig(conf, cwd);
2434
+ const tsconfigResolutionFiles = {};
2435
+ const tsConfResult = await loadTsConfig(conf, cwd, void 0, tsconfigResolutionFiles);
2317
2436
  if (tsConfResult) Object.assign(conf, tsConfResult);
2437
+ rememberTsConfigResolutionFiles(conf, tsconfigResolutionFiles.value ?? []);
2438
+ return { conf };
2439
+ }
2440
+ /**
2441
+ * Load config and create context with auto-injected plugins.
2442
+ * Used by the CLI and PostCSS plugin.
2443
+ */
2444
+ async function loadConfigAndCreateContext(options = {}) {
2445
+ const { conf } = await prepareNodeConfig(options);
2318
2446
  return new BambooContext(conf);
2319
2447
  }
2320
2448
  //#endregion
@@ -3128,20 +3256,84 @@ var Builder = class {
3128
3256
  explicitDepsMeta;
3129
3257
  affecteds;
3130
3258
  configDependencies = /* @__PURE__ */ new Set();
3259
+ pendingConfigCrawl;
3260
+ /** Last complete included inventory, including members which have since been deleted. */
3261
+ sourceInventory;
3262
+ /** Existing included owners selected by the last resolution-ledger invalidation pass. */
3263
+ affectedFiles;
3264
+ /** Dependency-before-importer parse order for the selected owners. */
3265
+ extractionOrder;
3266
+ /** Exact cross-file semantic reads retained per included extraction owner. */
3267
+ resolutionReadSets = /* @__PURE__ */ new Map();
3268
+ /** Previously semantic paths which are absent, retained only while their owner is unchanged. */
3269
+ pendingResolutionReadSets = /* @__PURE__ */ new Map();
3270
+ /** Missing local priority candidates which can redirect a current semantic resolution. */
3271
+ resolutionCandidateSets = /* @__PURE__ */ new Map();
3272
+ /** Exact resolver configuration reads retained per included semantic owner. */
3273
+ resolutionConfigurationSets = /* @__PURE__ */ new Map();
3274
+ /** Byte snapshots for resolver configuration files, independent of filesystem mtimes. */
3275
+ resolutionConfigurationBytes = /* @__PURE__ */ new Map();
3276
+ /** Previous effective tsconfig read-set, needed to classify its deletion as an option reload. */
3277
+ tsconfigResolutionFiles = [];
3278
+ /** Config-graph mtimes as of the last completed setup, consulted by the dev fast path. */
3279
+ configGraphMtimes;
3280
+ /** @internal Current and missing resolver paths which can change the stylesheet. */
3281
+ getResolutionReadFiles = () => {
3282
+ const files = /* @__PURE__ */ new Set();
3283
+ for (const readSets of [
3284
+ this.resolutionReadSets,
3285
+ this.pendingResolutionReadSets,
3286
+ this.resolutionCandidateSets
3287
+ ]) for (const dependencies of readSets.values()) for (const dependency of dependencies) files.add(dependency);
3288
+ return Object.freeze([...files].sort());
3289
+ };
3290
+ /** @internal Exact local package/tsconfig files which can change semantic resolution. */
3291
+ getResolutionConfigurationFiles = () => {
3292
+ const files = /* @__PURE__ */ new Set();
3293
+ for (const configurations of this.resolutionConfigurationSets.values()) for (const configuration of configurations) files.add(configuration);
3294
+ return Object.freeze([...files].sort());
3295
+ };
3296
+ readResolutionConfiguration = (file) => {
3297
+ try {
3298
+ return (0, fs.readFileSync)(file).toString("base64");
3299
+ } catch (error) {
3300
+ if (error?.code === "ENOENT") return void 0;
3301
+ throw error;
3302
+ }
3303
+ };
3304
+ changedResolutionConfigurations = () => this.getResolutionConfigurationFiles().filter((file) => this.resolutionConfigurationBytes.get(file) !== this.readResolutionConfiguration(file));
3305
+ snapshotResolutionConfigurations = () => {
3306
+ const current = new Set(this.getResolutionConfigurationFiles());
3307
+ for (const file of current) this.resolutionConfigurationBytes.set(file, this.readResolutionConfiguration(file));
3308
+ for (const file of this.resolutionConfigurationBytes.keys()) if (!current.has(file)) this.resolutionConfigurationBytes.delete(file);
3309
+ };
3310
+ /**
3311
+ * Remember what to crawl; do not crawl yet.
3312
+ *
3313
+ * The crawl walks the config's own import graph, and resolving a bare specifier there loads a
3314
+ * whole TypeScript compiler. Only `registerDependency` reads the result, and only the PostCSS
3315
+ * plugin calls that — the CLI and the Vite plugin (which crawls separately, when it watches)
3316
+ * paid ~155ms of compiler load per build for a set neither of them ever read.
3317
+ */
3131
3318
  setConfigDependencies(options) {
3319
+ this.pendingConfigCrawl = options;
3320
+ const cwd = options?.cwd ?? this.context?.config.cwd ?? process.cwd();
3321
+ for (const file of this.context?.conf.dependencies ?? []) this.configDependencies.add((0, path.resolve)(cwd, file));
3322
+ }
3323
+ /** Crawl on first read, once per `setConfigDependencies`. */
3324
+ crawlConfigDependencies() {
3325
+ const options = this.pendingConfigCrawl;
3326
+ if (!options) return;
3327
+ this.pendingConfigCrawl = void 0;
3132
3328
  const tsOptions = this.context?.conf.tsOptions ?? {
3133
3329
  baseUrl: void 0,
3134
3330
  pathMappings: []
3135
3331
  };
3136
3332
  const compilerOptions = this.context?.conf.tsconfig?.compilerOptions ?? {};
3137
- const { deps: foundDeps } = (0, _bamboocss_config.getConfigDependencies)(options.configPath, tsOptions, compilerOptions);
3138
- const cwd = options?.cwd ?? this.context?.config.cwd ?? process.cwd();
3139
- const configDeps = new Set([...foundDeps, ...(this.context?.conf.dependencies ?? []).map((file) => (0, path.resolve)(cwd, file))]);
3140
- configDeps.forEach((file) => {
3141
- this.configDependencies.add(file);
3142
- });
3333
+ const { deps } = (0, _bamboocss_config.getConfigDependencies)(options.configPath, tsOptions, compilerOptions);
3334
+ deps.forEach((file) => this.configDependencies.add(file));
3143
3335
  _bamboocss_logger.logger.debug("builder", "Config dependencies");
3144
- _bamboocss_logger.logger.debug("builder", configDeps);
3336
+ _bamboocss_logger.logger.debug("builder", deps);
3145
3337
  }
3146
3338
  setup = async (options = {}) => {
3147
3339
  _bamboocss_logger.logger.debug("builder", "🚧 Setup");
@@ -3156,9 +3348,38 @@ var Builder = class {
3156
3348
  dev: options.dev
3157
3349
  });
3158
3350
  const ctx = this.getContextOrThrow();
3351
+ const previousTsconfigFiles = this.tsconfigResolutionFiles.length ? this.tsconfigResolutionFiles : ctx.diff.getResolutionConfigFiles();
3352
+ /**
3353
+ * Dev fast path: skip the config reload when nothing that can change the resolved config
3354
+ * has moved on disk.
3355
+ *
3356
+ * `reloadConfigAndRefreshContext` re-bundles and re-evaluates the config file and the
3357
+ * tsconfig chain on every call, and a dev server reaches `setup` on every stylesheet
3358
+ * rebuild — that is 10–18ms paid per source edit for a config that cannot have changed,
3359
+ * since editing the config restarts the dev server outside this method's control anyway.
3360
+ * The guard set is exactly what the reload would re-read: the config file, its bundled
3361
+ * import graph, the explicit `dependencies`, and the tsconfig files behind resolution. Any
3362
+ * of them moving — including appearing or disappearing, which `getFileMeta` reports as a
3363
+ * changed mtime — takes the full reload below, as does a file the last snapshot never saw.
3364
+ *
3365
+ * Dev-only because the reload is also the recovery for edits this guard cannot see — a
3366
+ * preset external to the config bundle — and a one-shot build keeps paying the reload
3367
+ * rather than trading that recovery for a latency only watch mode feels.
3368
+ */
3369
+ if (options.dev && this.configGraphUnchanged(configPath)) {
3370
+ this.affecteds = {
3371
+ artifacts: /* @__PURE__ */ new Set(),
3372
+ hasConfigChanged: false,
3373
+ diffs: []
3374
+ };
3375
+ this.explicitDepsMeta = this.checkFilesChanged(this.context.explicitDeps);
3376
+ this.refreshSourceState(ctx, previousTsconfigFiles);
3377
+ return;
3378
+ }
3159
3379
  this.affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
3160
3380
  this.context = new BambooContext(conf);
3161
3381
  });
3382
+ this.tsconfigResolutionFiles = this.getContextOrThrow().diff.getResolutionConfigFiles();
3162
3383
  _bamboocss_logger.logger.debug("builder", this.affecteds);
3163
3384
  this.explicitDepsMeta = this.checkFilesChanged(this.context.explicitDeps);
3164
3385
  if (this.explicitDepsMeta.hasFilesChanged) {
@@ -3170,17 +3391,152 @@ var Builder = class {
3170
3391
  }
3171
3392
  if (this.affecteds.hasConfigChanged) {
3172
3393
  _bamboocss_logger.logger.debug("builder", "⚙️ Config changed, reloading");
3394
+ this.filesMeta = void 0;
3395
+ this.affectedFiles = void 0;
3396
+ this.extractionOrder = void 0;
3397
+ this.sourceInventory = void 0;
3398
+ this.resolutionReadSets.clear();
3399
+ this.pendingResolutionReadSets.clear();
3400
+ this.resolutionCandidateSets.clear();
3401
+ this.resolutionConfigurationSets.clear();
3402
+ this.resolutionConfigurationBytes.clear();
3173
3403
  await ctx.hooks["config:change"]?.({
3174
3404
  config: ctx.config,
3175
3405
  changes: this.affecteds
3176
3406
  });
3407
+ this.snapshotConfigGraphMtimes(configPath);
3177
3408
  return;
3178
3409
  }
3179
- this.filesMeta = this.checkFilesChanged(ctx.getFiles());
3410
+ this.refreshSourceState(ctx, previousTsconfigFiles);
3411
+ this.snapshotConfigGraphMtimes(configPath);
3412
+ };
3413
+ /** Every file whose content participates in the resolved config, for the dev fast path. */
3414
+ configGraphFiles = (configPath) => (0, _bamboocss_shared.uniq)([
3415
+ ...configPath ? [configPath] : [],
3416
+ ...this.configDependencies,
3417
+ ...this.tsconfigResolutionFiles,
3418
+ ...this.context?.explicitDeps ?? []
3419
+ ].map(path.normalize));
3420
+ configGraphUnchanged = (configPath) => {
3421
+ const snapshot = this.configGraphMtimes;
3422
+ if (!snapshot) return false;
3423
+ for (const file of this.configGraphFiles(configPath)) {
3424
+ const recorded = snapshot.get(file);
3425
+ if (recorded === void 0 || recorded !== this.getFileMeta(file).mtime) return false;
3426
+ }
3427
+ return true;
3428
+ };
3429
+ snapshotConfigGraphMtimes = (configPath) => {
3430
+ const snapshot = /* @__PURE__ */ new Map();
3431
+ for (const file of this.configGraphFiles(configPath)) snapshot.set(file, this.getFileMeta(file).mtime);
3432
+ this.configGraphMtimes = snapshot;
3433
+ };
3434
+ /** The per-pass source bookkeeping every setup ends with, config reload or not. */
3435
+ refreshSourceState = (ctx, previousTsconfigFiles) => {
3436
+ const changedResolutionConfigurations = this.changedResolutionConfigurations();
3437
+ const changedResolutionSet = new Set(changedResolutionConfigurations);
3438
+ const resolutionAffected = /* @__PURE__ */ new Set();
3439
+ const resolutionLedger = changedResolutionConfigurations.length ? ctx.project.getResolutionLedger() : void 0;
3440
+ for (const [owner, configurations] of this.resolutionConfigurationSets) if (configurations.some((file) => changedResolutionSet.has(file))) resolutionAffected.add(owner);
3441
+ if (changedResolutionConfigurations.length) {
3442
+ const tsconfigCandidates = new Set([...previousTsconfigFiles, ...this.tsconfigResolutionFiles]);
3443
+ const replaceCompilerOptions = changedResolutionConfigurations.some((file) => tsconfigCandidates.has(file));
3444
+ ctx.project.refreshResolutionConfiguration(ctx.conf.tsconfig?.compilerOptions, this.tsconfigResolutionFiles, replaceCompilerOptions);
3445
+ }
3446
+ const inventory = ctx.getFiles();
3447
+ const tracked = (0, _bamboocss_shared.uniq)([
3448
+ ...this.sourceInventory ?? inventory,
3449
+ ...inventory,
3450
+ ...this.getResolutionReadFiles()
3451
+ ]);
3452
+ this.filesMeta = this.checkFilesChanged(tracked);
3180
3453
  if (this.filesMeta.hasFilesChanged) {
3181
3454
  _bamboocss_logger.logger.debug("builder", "Files changed, invalidating them");
3182
- ctx.project.reloadSourceFiles();
3455
+ this.invalidateChangedSources(ctx, inventory, resolutionAffected, resolutionLedger);
3456
+ } else if (changedResolutionConfigurations.length) {
3457
+ ctx.encoder?.reconcileFileOwnerOrder("extract", inventory);
3458
+ this.extractionOrder = this.orderAffectedFiles(inventory, resolutionAffected, resolutionLedger ?? [], []);
3459
+ this.affectedFiles = new Set(this.extractionOrder.map(this.sourcePath));
3460
+ } else {
3461
+ this.affectedFiles = /* @__PURE__ */ new Set();
3462
+ this.extractionOrder = [];
3183
3463
  }
3464
+ this.sourceInventory = [...inventory];
3465
+ };
3466
+ /** Normalize the path identity shared by the Project ledger and file-owner keys. */
3467
+ sourcePath = (file) => file.replaceAll("\\", "/");
3468
+ /**
3469
+ * Reload only changed ledger members, then select their transitive included consumers.
3470
+ *
3471
+ * The dependency graph is snapshotted before mutation: reloading an importer retracts its
3472
+ * old forward edges, while deletion removes the target. Waiting until afterwards loses the
3473
+ * very closure the rebuild needs. New targets also select every pending importer and each
3474
+ * pending importer's dependent closure, because no edge to the new path existed yet.
3475
+ */
3476
+ invalidateChangedSources = (ctx, inventory, seededAffected = /* @__PURE__ */ new Set(), previousLedger) => {
3477
+ const project = ctx.project;
3478
+ const current = new Set(inventory.map(this.sourcePath));
3479
+ const changed = [...this.filesMeta?.changes ?? []].filter(([, meta]) => !meta.isUnchanged).map(([file]) => this.sourcePath(file));
3480
+ const ledger = previousLedger ?? project.getResolutionLedger();
3481
+ const pending = project.getUnresolvedImporters().map(this.sourcePath);
3482
+ const affected = new Set(seededAffected);
3483
+ const added = [];
3484
+ for (const file of changed) {
3485
+ if (current.has(file)) affected.add(file);
3486
+ for (const dependent of project.getDependents(file)) affected.add(this.sourcePath(dependent));
3487
+ if ((0, fs.existsSync)(file) && !project.getSourceFile(file)) added.push(file);
3488
+ }
3489
+ if (added.length) for (const importer of pending) {
3490
+ affected.add(importer);
3491
+ for (const dependent of project.getDependents(importer)) affected.add(this.sourcePath(dependent));
3492
+ }
3493
+ for (const file of changed) if (!(0, fs.existsSync)(file)) {
3494
+ project.removeSourceFile(file);
3495
+ fileModifiedMap.set(file, -Infinity);
3496
+ } else if (project.getSourceFile(file)) project.reloadSourceFile(file);
3497
+ else project.createSourceFile(file);
3498
+ ctx.encoder?.reconcileFileOwnerOrder("extract", inventory);
3499
+ const syntheticEdges = added.flatMap((target) => pending.map((importer) => [target, importer]));
3500
+ this.extractionOrder = this.orderAffectedFiles(inventory, affected, ledger, syntheticEdges);
3501
+ this.affectedFiles = new Set(this.extractionOrder.map(this.sourcePath));
3502
+ };
3503
+ /** Deterministic topological order, with current inventory order as the stable tie-break. */
3504
+ orderAffectedFiles = (inventory, affected, ledger, syntheticEdges) => {
3505
+ const files = inventory.filter((file) => affected.has(this.sourcePath(file)));
3506
+ const byPath = new Map(files.map((file) => [this.sourcePath(file), file]));
3507
+ const inventoryRank = new Map(files.map((file, index) => [this.sourcePath(file), index]));
3508
+ const outgoing = /* @__PURE__ */ new Map();
3509
+ const indegree = new Map(files.map((file) => [this.sourcePath(file), 0]));
3510
+ const addEdge = (rawTarget, rawImporter) => {
3511
+ if (!rawTarget) return;
3512
+ const target = this.sourcePath(rawTarget);
3513
+ const importer = this.sourcePath(rawImporter);
3514
+ if (target === importer || !byPath.has(target) || !byPath.has(importer)) return;
3515
+ const importers = outgoing.get(target) ?? /* @__PURE__ */ new Set();
3516
+ if (importers.has(importer)) return;
3517
+ importers.add(importer);
3518
+ outgoing.set(target, importers);
3519
+ indegree.set(importer, (indegree.get(importer) ?? 0) + 1);
3520
+ };
3521
+ for (const fact of ledger) addEdge(fact.target, fact.importer);
3522
+ for (const [target, importer] of syntheticEdges) addEdge(target, importer);
3523
+ const compare = (left, right) => (inventoryRank.get(left) ?? 0) - (inventoryRank.get(right) ?? 0);
3524
+ const ready = [...indegree].filter(([, degree]) => degree === 0).map(([file]) => file).sort(compare);
3525
+ const ordered = [];
3526
+ while (ready.length) {
3527
+ const file = ready.shift();
3528
+ ordered.push(file);
3529
+ for (const importer of [...outgoing.get(file) ?? []].sort(compare)) {
3530
+ const next = (indegree.get(importer) ?? 0) - 1;
3531
+ indegree.set(importer, next);
3532
+ if (next === 0) {
3533
+ ready.push(importer);
3534
+ ready.sort(compare);
3535
+ }
3536
+ }
3537
+ }
3538
+ for (const file of [...byPath.keys()].sort(compare)) if (!ordered.includes(file)) ordered.push(file);
3539
+ return ordered.map((file) => byPath.get(file));
3184
3540
  };
3185
3541
  /**
3186
3542
  * Write the generated `styled-system`, so an integration can be a project's only codegen.
@@ -3221,6 +3577,7 @@ var Builder = class {
3221
3577
  this.configDependencies.add((0, path.resolve)(cwd || ctx.conf.config.cwd, file));
3222
3578
  });
3223
3579
  this.context = ctx;
3580
+ this.tsconfigResolutionFiles = ctx.diff.getResolutionConfigFiles();
3224
3581
  return ctx;
3225
3582
  };
3226
3583
  getContextOrThrow = () => {
@@ -3250,9 +3607,32 @@ var Builder = class {
3250
3607
  extractFile = (ctx, file) => {
3251
3608
  const meta = this.filesMeta?.changes.get(file) ?? this.getFileMeta(file);
3252
3609
  const hasConfigChanged = this.affecteds ? this.affecteds.hasConfigChanged : true;
3253
- if (meta.isUnchanged && !hasConfigChanged) return;
3610
+ if (meta.isUnchanged && !hasConfigChanged && !this.affectedFiles?.has(this.sourcePath(file))) return;
3611
+ const owner = this.sourcePath(file);
3612
+ const previousReads = this.resolutionReadSets.get(owner) ?? [];
3613
+ const previousPending = this.pendingResolutionReadSets.get(owner) ?? [];
3614
+ const previousCandidates = this.resolutionCandidateSets.get(owner) ?? [];
3615
+ const previousConfigurations = this.resolutionConfigurationSets.get(owner) ?? [];
3254
3616
  const parserResult = ctx.parseFile(file);
3255
3617
  fileModifiedMap.set(file, meta.mtime);
3618
+ if (parserResult) {
3619
+ const previousReadSet = meta.isUnchanged ? {
3620
+ dependencies: (0, _bamboocss_shared.uniq)([...previousReads, ...previousPending]).sort(),
3621
+ pendingCandidates: previousCandidates
3622
+ } : void 0;
3623
+ const readSet = ctx.project.getResolutionReadSet(file, parserResult.getDependencies(), previousReadSet);
3624
+ const currentReads = readSet.dependencies;
3625
+ const currentConfigurations = ctx.project.getResolutionConfigurationFiles(file, parserResult.getDependencies(), meta.isUnchanged ? previousConfigurations : []);
3626
+ this.resolutionReadSets.set(owner, currentReads);
3627
+ if (readSet.pendingCandidates.length) this.resolutionCandidateSets.set(owner, readSet.pendingCandidates);
3628
+ else this.resolutionCandidateSets.delete(owner);
3629
+ const pending = meta.isUnchanged ? (0, _bamboocss_shared.uniq)([...previousPending, ...previousReads]).filter((dependency) => !(0, fs.existsSync)(dependency) && !currentReads.includes(dependency) && (!previousCandidates.includes(dependency) || readSet.pendingCandidates.includes(dependency))).sort() : [];
3630
+ if (pending.length) this.pendingResolutionReadSets.set(owner, pending);
3631
+ else this.pendingResolutionReadSets.delete(owner);
3632
+ const configurations = currentConfigurations.length || !meta.isUnchanged ? currentConfigurations : previousConfigurations;
3633
+ if (configurations.length) this.resolutionConfigurationSets.set(owner, configurations);
3634
+ else this.resolutionConfigurationSets.delete(owner);
3635
+ }
3256
3636
  return parserResult;
3257
3637
  };
3258
3638
  extract = () => {
@@ -3263,10 +3643,29 @@ var Builder = class {
3263
3643
  ctx.assertExtracted();
3264
3644
  return ctx.assertNoDeadCalls();
3265
3645
  }
3266
- const files = ctx.getFiles();
3646
+ const files = !hasConfigChanged && this.sourceInventory ? [...this.sourceInventory] : ctx.getFiles();
3647
+ const inventory = new Set(files.map(this.sourcePath));
3648
+ if (hasConfigChanged) {
3649
+ this.resolutionReadSets.clear();
3650
+ this.pendingResolutionReadSets.clear();
3651
+ this.resolutionCandidateSets.clear();
3652
+ this.resolutionConfigurationSets.clear();
3653
+ } else {
3654
+ for (const owner of this.resolutionReadSets.keys()) if (!inventory.has(owner)) this.resolutionReadSets.delete(owner);
3655
+ for (const owner of this.pendingResolutionReadSets.keys()) if (!inventory.has(owner)) this.pendingResolutionReadSets.delete(owner);
3656
+ for (const owner of this.resolutionCandidateSets.keys()) if (!inventory.has(owner)) this.resolutionCandidateSets.delete(owner);
3657
+ for (const owner of this.resolutionConfigurationSets.keys()) if (!inventory.has(owner)) this.resolutionConfigurationSets.delete(owner);
3658
+ }
3659
+ ctx.encoder?.reconcileFileOwnerOrder("extract", files);
3660
+ const filesToExtract = hasConfigChanged ? files : this.extractionOrder ?? files;
3267
3661
  const done = _bamboocss_logger.logger.time.info("Extracted in");
3268
- for (const file of files) this.extractFile(ctx, file);
3662
+ for (const file of filesToExtract) this.extractFile(ctx, file);
3269
3663
  done();
3664
+ this.sourceInventory = [...files];
3665
+ for (const file of (0, _bamboocss_shared.uniq)([...files, ...this.getResolutionReadFiles()])) fileModifiedMap.set(file, this.getFileMeta(file).mtime);
3666
+ this.snapshotResolutionConfigurations();
3667
+ this.affectedFiles = void 0;
3668
+ this.extractionOrder = void 0;
3270
3669
  ctx.assertExtracted(files);
3271
3670
  ctx.assertNoDeadCalls(files);
3272
3671
  };
@@ -3322,6 +3721,7 @@ var Builder = class {
3322
3721
  };
3323
3722
  registerDependency = (fn) => {
3324
3723
  const ctx = this.getContextOrThrow();
3724
+ this.crawlConfigDependencies();
3325
3725
  for (const fileOrGlob of ctx.config.include) {
3326
3726
  const dependency = parseDependency(fileOrGlob);
3327
3727
  if (dependency) fn(dependency);
@@ -3528,7 +3928,8 @@ async function generate(config, configPath) {
3528
3928
  */
3529
3929
  const bundleStyles = async (ctx, changedFilePaths) => {
3530
3930
  let parsed = 0;
3531
- for (const filePath of changedFilePaths) if (ctx.project.parseSourceFile(filePath)) parsed++;
3931
+ const encoder = ctx.parserOptions.encoder;
3932
+ for (const filePath of changedFilePaths) if (encoder.withOwner("extract", filePath, () => ctx.project.parseSourceFile(filePath, encoder))) parsed++;
3532
3933
  if (parsed === 0) return;
3533
3934
  const outfile = ctx.runtime.path.join(...ctx.paths.root, "styles.css");
3534
3935
  const done = _bamboocss_logger.logger.time.info(ctx.messages.buildComplete(parsed));
@@ -3553,12 +3954,13 @@ async function generate(config, configPath) {
3553
3954
  ctx.project.reloadSourceFile(filePath);
3554
3955
  await bundleStyles(ctx, [filePath, ...ctx.project.getDependents(filePath)]);
3555
3956
  } else if (event === "add") {
3957
+ const pendingClosure = ctx.project.getUnresolvedImporters().flatMap((importer) => [importer, ...ctx.project.getDependents(importer)]);
3556
3958
  ctx.project.createSourceFile(filePath);
3557
- await bundleStyles(ctx, [
3959
+ await bundleStyles(ctx, [...new Set([
3558
3960
  filePath,
3559
3961
  ...ctx.project.getDependents(filePath),
3560
- ...ctx.project.getUnresolvedImporters()
3561
- ]);
3962
+ ...pendingClosure
3963
+ ])]);
3562
3964
  }
3563
3965
  });
3564
3966
  }
@@ -3611,33 +4013,6 @@ const ensure = (outPath) => {
3611
4013
  //#endregion
3612
4014
  //#region src/vite-integration.ts
3613
4015
  /**
3614
- * Whether a Bamboo source compiler is running in this process.
3615
- *
3616
- * Two integrations can emit the stylesheet, and only one of them also compiles source.
3617
- * `@bamboocss/postcss` emits CSS and nothing else, so under it every `css()` and `cva()` call
3618
- * stays a runtime call and the generated style engine ships in the client bundle. That is a
3619
- * legitimate integration for a bundler with no Vite plugin — and a silent downgrade for a
3620
- * project that has Vite and simply did not add `@bamboocss/vite`, which is a setup Bamboo's
3621
- * own React Router guide used to describe. Nothing failed: the stylesheet was correct, the app
3622
- * rendered, and 20 kB of engine went out with it.
3623
- *
3624
- * On `globalThis` under a registered symbol rather than in a module variable, because the two
3625
- * packages that have to agree do not share a module instance. `@bamboocss/postcss` is required
3626
- * as CommonJS by a PostCSS config while `@bamboocss/vite` is imported as ESM by a Vite config,
3627
- * so even one installed copy of a shared dependency is loaded twice, once per format, with a
3628
- * variable each. The symbol is one value per realm regardless.
3629
- *
3630
- * A realm is as far as it goes: a worker thread, or PostCSS run from a separate process
3631
- * alongside the Vite build, sees no flag. Both fail towards saying something rather than
3632
- * staying quiet, and what they say names the option that silences it.
3633
- */
3634
- const FLAG = Symbol.for("bamboocss.static-compiler");
3635
- /** Called by an integration that compiles source, as it is constructed. */
3636
- const markStaticCompilerActive = () => {
3637
- globalThis[FLAG] = true;
3638
- };
3639
- const isStaticCompilerActive = () => Boolean(globalThis[FLAG]);
3640
- /**
3641
4016
  * Every extension Vite accepts for its config, so "is this a Vite project" is answered by the
3642
4017
  * same file Vite itself would load.
3643
4018
  *
@@ -3805,9 +4180,9 @@ Object.defineProperty(exports, "generatePackageExports", {
3805
4180
  }
3806
4181
  });
3807
4182
  exports.hasUncompilableSources = hasUncompilableSources;
3808
- exports.isStaticCompilerActive = isStaticCompilerActive;
4183
+ exports.isStaticCompilerActive = require_static_compiler.isStaticCompilerActive;
3809
4184
  exports.loadConfigAndCreateContext = loadConfigAndCreateContext;
3810
- exports.markStaticCompilerActive = markStaticCompilerActive;
4185
+ exports.markStaticCompilerActive = require_static_compiler.markStaticCompilerActive;
3811
4186
  exports.parseDependency = parseDependency;
3812
4187
  exports.setLogStream = setLogStream;
3813
4188
  exports.setupConfig = setupConfig;