@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.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { isStaticCompilerActive, markStaticCompilerActive } from "./static-compiler.mjs";
1
2
  import { Reporter, formatRecipeReport, formatTokenReport } from "@bamboocss/reporter";
2
3
  import { colors, logger, quote } from "@bamboocss/logger";
3
4
  import { convertTsPathsToRegexes, diffConfigs, findConfig, getConfigDependencies, loadConfig, mergeHooks } from "@bamboocss/config";
@@ -13,17 +14,17 @@ import { debounce } from "perfect-debounce";
13
14
  import process$1 from "node:process";
14
15
  import os from "node:os";
15
16
  import tty from "node:tty";
17
+ import fs, { promises } from "node:fs";
18
+ import path from "node:path";
19
+ import { Node, SyntaxKind, ts } from "ts-morph";
16
20
  import chokidar from "chokidar";
17
21
  import glob from "fast-glob";
18
22
  import fsExtra from "fs-extra";
19
23
  import picomatch from "picomatch";
20
- import path from "node:path";
21
- import fs, { promises } from "node:fs";
22
24
  import isGlob from "is-glob";
23
25
  import globParent from "glob-parent";
24
26
  import { isMatch } from "matcher";
25
27
  import { resolveTsPathPattern } from "@bamboocss/config/ts-path";
26
- import { Node, SyntaxKind, ts } from "ts-morph";
27
28
  import readline from "node:readline";
28
29
  import { lookItUpSync } from "look-it-up";
29
30
  import outdent$1, { outdent } from "outdent";
@@ -1391,7 +1392,345 @@ const createBox = (options) => boxen(options.content, {
1391
1392
  titleAlignment: "center"
1392
1393
  });
1393
1394
  //#endregion
1395
+ //#region src/tsconfig-utils.ts
1396
+ /**
1397
+ * If `filename` points to a `.json` file that exists as a regular file, return its absolute path.
1398
+ */
1399
+ async function resolveDirectTsconfigJson(filename) {
1400
+ if (path.extname(filename) !== ".json") return null;
1401
+ const resolved = path.resolve(filename);
1402
+ try {
1403
+ const stat = await promises.stat(resolved);
1404
+ if (stat.isFile() || stat.isFIFO()) return resolved;
1405
+ throw new Error(`${filename} exists but is not a regular file.`);
1406
+ } catch (e) {
1407
+ if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return null;
1408
+ throw e;
1409
+ }
1410
+ }
1411
+ /**
1412
+ * Walk upward from `dirname(filename)` and return the first existing `configName`,
1413
+ * stopping at `root` (inclusive) or the filesystem root.
1414
+ */
1415
+ async function findClosestTsconfig(filename, root, configName = "tsconfig.json") {
1416
+ const resolvedRoot = path.resolve(root);
1417
+ let dir = path.dirname(path.resolve(filename));
1418
+ for (;;) {
1419
+ const candidate = path.join(dir, configName);
1420
+ try {
1421
+ const stat = await promises.stat(candidate);
1422
+ if (stat.isFile() || stat.isFIFO()) return candidate;
1423
+ } catch {}
1424
+ if (dir === resolvedRoot || path.dirname(dir) === dir) return null;
1425
+ dir = path.dirname(dir);
1426
+ }
1427
+ }
1428
+ /**
1429
+ * Resolve `compilerOptions.baseUrl` the same way TypeScript does: relative to the tsconfig file.
1430
+ * Falls back to `cwd` when `baseUrl` is omitted.
1431
+ */
1432
+ function resolveBaseUrlForCompilerOptions(baseUrl, tsconfigFile, cwd) {
1433
+ if (baseUrl == null) return cwd;
1434
+ if (baseUrl.startsWith("${")) return baseUrl;
1435
+ if (path.isAbsolute(baseUrl)) return baseUrl;
1436
+ return path.resolve(path.dirname(tsconfigFile), baseUrl);
1437
+ }
1438
+ const SOURCE_EXTENSIONS = [
1439
+ ".ts",
1440
+ ".tsx",
1441
+ ".mts",
1442
+ ".cts"
1443
+ ];
1444
+ function resolveReferencedTsconfigPath(refPath, fromDir, configName = "tsconfig.json") {
1445
+ const p = refPath.endsWith(".json") ? refPath : path.join(refPath, configName);
1446
+ return path.resolve(fromDir, p);
1447
+ }
1448
+ /**
1449
+ * When a file belongs to a referenced project (TypeScript project references),
1450
+ * return that project's merged tsconfig for `compilerOptions`.
1451
+ */
1452
+ async function resolveSolutionTsconfigForFile(absoluteFilename, rootTsconfigPath, rootParsed, getTsconfigModule, cache) {
1453
+ const { parseTsconfig } = getTsconfigModule;
1454
+ if (isSourceFileIncludedInTsconfig(absoluteFilename, rootTsconfigPath, rootParsed)) return {
1455
+ tsconfig: rootParsed,
1456
+ tsconfigFile: rootTsconfigPath
1457
+ };
1458
+ const refs = rootParsed.references;
1459
+ if (!refs?.length) return {
1460
+ tsconfig: rootParsed,
1461
+ tsconfigFile: rootTsconfigPath
1462
+ };
1463
+ if (!SOURCE_EXTENSIONS.some((ext) => absoluteFilename.endsWith(ext))) return {
1464
+ tsconfig: rootParsed,
1465
+ tsconfigFile: rootTsconfigPath
1466
+ };
1467
+ const rootDir = path.dirname(rootTsconfigPath);
1468
+ for (const ref of refs) {
1469
+ const refPath = resolveReferencedTsconfigPath(ref.path, rootDir);
1470
+ try {
1471
+ await promises.access(refPath);
1472
+ } catch {
1473
+ continue;
1474
+ }
1475
+ const childParsed = parseTsconfig(refPath, cache);
1476
+ if (isSourceFileIncludedInTsconfig(absoluteFilename, refPath, childParsed)) return {
1477
+ tsconfig: childParsed,
1478
+ tsconfigFile: refPath
1479
+ };
1480
+ }
1481
+ return {
1482
+ tsconfig: rootParsed,
1483
+ tsconfigFile: rootTsconfigPath
1484
+ };
1485
+ }
1486
+ const POSIX_SEP_RE = new RegExp("\\" + path.posix.sep, "g");
1487
+ const NATIVE_SEP_RE = new RegExp("\\" + path.sep, "g");
1488
+ const PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
1489
+ const GLOB_ALL_PATTERN = `**/*`;
1490
+ const TS_EXTENSIONS = [
1491
+ ".ts",
1492
+ ".tsx",
1493
+ ".mts",
1494
+ ".cts"
1495
+ ];
1496
+ const TSJS_EXTENSIONS = TS_EXTENSIONS.concat([
1497
+ ".js",
1498
+ ".jsx",
1499
+ ".mjs",
1500
+ ".cjs"
1501
+ ]);
1502
+ const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
1503
+ const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
1504
+ const IS_POSIX = path.posix.sep === path.sep;
1505
+ const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, path.posix.sep);
1506
+ const resolve2posix = IS_POSIX ? (dir, filename) => dir ? path.resolve(dir, filename) : path.resolve(filename) : (dir, filename) => {
1507
+ const posix2native = (f) => f.replace(POSIX_SEP_RE, path.sep);
1508
+ return native2posix(dir ? path.resolve(posix2native(dir), posix2native(filename)) : path.resolve(posix2native(filename)));
1509
+ };
1510
+ function isGlobMatch(filename, dir, patterns, allowJs) {
1511
+ const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
1512
+ return patterns.some((patternArg) => {
1513
+ let pattern = patternArg;
1514
+ let lastWildcardIndex = pattern.length;
1515
+ let hasWildcard = false;
1516
+ let hasExtension = false;
1517
+ let hasSlash = false;
1518
+ let lastSlashIndex = -1;
1519
+ for (let i = pattern.length - 1; i > -1; i--) {
1520
+ const c = pattern[i];
1521
+ if (!hasWildcard) {
1522
+ if (c === "*" || c === "?") {
1523
+ lastWildcardIndex = i;
1524
+ hasWildcard = true;
1525
+ }
1526
+ }
1527
+ if (!hasSlash) {
1528
+ if (c === ".") hasExtension = true;
1529
+ else if (c === "/") {
1530
+ lastSlashIndex = i;
1531
+ hasSlash = true;
1532
+ }
1533
+ }
1534
+ if (hasWildcard && hasSlash) break;
1535
+ }
1536
+ if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
1537
+ pattern += `${pattern.endsWith("/") ? "" : "/"}${GLOB_ALL_PATTERN}`;
1538
+ lastWildcardIndex = pattern.length - 1;
1539
+ hasWildcard = true;
1540
+ }
1541
+ if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
1542
+ if (pattern.endsWith("*") && !extensions.some((ext) => filename.endsWith(ext))) return false;
1543
+ if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
1544
+ const resolvedPattern = resolve2posix(dir, pattern);
1545
+ let firstWildcardIndex = -1;
1546
+ for (let i = 0; i < resolvedPattern.length; i++) if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
1547
+ firstWildcardIndex = i;
1548
+ hasWildcard = true;
1549
+ break;
1550
+ }
1551
+ if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
1552
+ if (!hasWildcard) return filename === resolvedPattern;
1553
+ 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;
1554
+ if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
1555
+ const regex = pattern2regex(resolvedPattern, allowJs);
1556
+ PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
1557
+ return regex.test(filename);
1558
+ });
1559
+ }
1560
+ function pattern2regex(resolvedPattern, allowJs) {
1561
+ let regexStr = "^";
1562
+ for (let i = 0; i < resolvedPattern.length; i++) {
1563
+ const char = resolvedPattern[i];
1564
+ if (char === "?") {
1565
+ regexStr += "[^\\/]";
1566
+ continue;
1567
+ }
1568
+ if (char === "*") {
1569
+ if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
1570
+ i += 2;
1571
+ regexStr += "(?:[^\\/]*\\/)*";
1572
+ continue;
1573
+ }
1574
+ regexStr += "[^\\/]*";
1575
+ continue;
1576
+ }
1577
+ if ("/.+^${}()|[]\\".includes(char)) regexStr += "\\";
1578
+ regexStr += char;
1579
+ }
1580
+ if (resolvedPattern.endsWith("*")) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
1581
+ regexStr += "$";
1582
+ return new RegExp(regexStr);
1583
+ }
1584
+ function isIncluded(filename, tsconfigFile, tsconfig) {
1585
+ const dir = native2posix(path.dirname(tsconfigFile));
1586
+ const files = (tsconfig.files || []).map((file) => resolve2posix(dir, file));
1587
+ const absoluteFilename = resolve2posix(null, filename);
1588
+ if (files.includes(filename)) return true;
1589
+ const allowJs = tsconfig.compilerOptions?.allowJs;
1590
+ if (isGlobMatch(absoluteFilename, dir, tsconfig.include || (tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs)) return !isGlobMatch(absoluteFilename, dir, tsconfig.exclude || [], allowJs);
1591
+ return false;
1592
+ }
1593
+ /** Whether `absoluteFilename` is part of the compilation set defined by this tsconfig. */
1594
+ function isSourceFileIncludedInTsconfig(absoluteFilename, tsconfigFile, tsconfig) {
1595
+ return isIncluded(absoluteFilename, tsconfigFile, tsconfig);
1596
+ }
1597
+ //#endregion
1598
+ //#region src/load-tsconfig.ts
1599
+ const readPathsFromCache = (cache) => {
1600
+ const prefix = "readFileSync:";
1601
+ const suffix = ":utf8";
1602
+ return Array.from(cache.keys()).filter((key) => key.startsWith(prefix) && key.endsWith(suffix)).map((key) => key.slice(13, -5));
1603
+ };
1604
+ /**
1605
+ * Exact tsconfig files read while producing one resolved Node config.
1606
+ *
1607
+ * This metadata is deliberately kept outside `LoadConfigResult`: it is incremental resolver
1608
+ * provenance, not Bamboo configuration, and must therefore neither participate in
1609
+ * `diffConfigs` nor become part of the public/serialized config shape.
1610
+ */
1611
+ const resolutionFilesByConfig = /* @__PURE__ */ new WeakMap();
1612
+ const rememberTsConfigResolutionFiles = (conf, files) => {
1613
+ resolutionFilesByConfig.set(conf, Object.freeze([...new Set(files)].sort()));
1614
+ };
1615
+ const getTsConfigResolutionFiles = (conf) => resolutionFilesByConfig.get(conf) ?? Object.freeze(conf.tsconfigFile ? [path.resolve(conf.tsconfigFile)] : []);
1616
+ const referencedTsconfigPath = (reference, rootPath) => path.resolve(path.dirname(rootPath), reference.endsWith(".json") ? reference : path.join(reference, "tsconfig.json"));
1617
+ const MAX_TSCONFIG_REFERENCE_FILES = 256;
1618
+ const getImplicitBaseUrl = (compilerOptions) => {
1619
+ if (!compilerOptions) return void 0;
1620
+ const matches = Object.getOwnPropertySymbols(compilerOptions).filter((candidate) => candidate.description === "implicitBaseUrl");
1621
+ if (matches.length !== 1) return void 0;
1622
+ const symbol = matches[0];
1623
+ const descriptor = Object.getOwnPropertyDescriptor(compilerOptions, symbol);
1624
+ if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "string") return void 0;
1625
+ return {
1626
+ owner: compilerOptions,
1627
+ symbol,
1628
+ value: descriptor.value
1629
+ };
1630
+ };
1631
+ const collectReferenceGraph = async (rootPath, rootParsed, parseTsconfig, cache) => {
1632
+ const references = [];
1633
+ const unresolvedReferences = [];
1634
+ let traversalLimitExceeded = false;
1635
+ const visited = new Set([path.resolve(rootPath)]);
1636
+ const queue = [{
1637
+ parsed: rootParsed,
1638
+ path: rootPath
1639
+ }];
1640
+ for (let index = 0; index < queue.length; index++) {
1641
+ const current = queue[index];
1642
+ for (const reference of current.parsed.references ?? []) {
1643
+ const referencedPath = referencedTsconfigPath(reference.path, current.path);
1644
+ references.push({
1645
+ from: current.path,
1646
+ path: referencedPath
1647
+ });
1648
+ if (visited.has(referencedPath)) continue;
1649
+ if (visited.size >= MAX_TSCONFIG_REFERENCE_FILES) {
1650
+ traversalLimitExceeded = true;
1651
+ unresolvedReferences.push(referencedPath);
1652
+ continue;
1653
+ }
1654
+ visited.add(referencedPath);
1655
+ try {
1656
+ const source = await promises.readFile(referencedPath, "utf8");
1657
+ if (ts.parseConfigFileTextToJson(referencedPath, source).error) throw new Error("Invalid tsconfig");
1658
+ queue.push({
1659
+ parsed: parseTsconfig(referencedPath, cache),
1660
+ path: referencedPath
1661
+ });
1662
+ } catch {
1663
+ unresolvedReferences.push(referencedPath);
1664
+ }
1665
+ }
1666
+ }
1667
+ return {
1668
+ references,
1669
+ traversalLimitExceeded,
1670
+ unresolvedReferences
1671
+ };
1672
+ };
1673
+ async function loadTsConfig(conf, cwd, provenance, resolutionFiles) {
1674
+ const root = cwd;
1675
+ let tsconfigFile = await resolveDirectTsconfigJson(conf.path);
1676
+ const direct = tsconfigFile !== null;
1677
+ if (!tsconfigFile) {
1678
+ if (resolutionFiles) resolutionFiles.value = Object.freeze([]);
1679
+ tsconfigFile = await findClosestTsconfig(conf.path, root, "tsconfig.json");
1680
+ }
1681
+ if (!tsconfigFile) {
1682
+ if (provenance) provenance.value = {
1683
+ direct: false,
1684
+ readPaths: [],
1685
+ references: [],
1686
+ traversalLimitExceeded: false,
1687
+ unresolvedReferences: []
1688
+ };
1689
+ return {
1690
+ tsconfig: {},
1691
+ tsconfigFile: void 0
1692
+ };
1693
+ }
1694
+ const gtc = await import("get-tsconfig");
1695
+ const cache = /* @__PURE__ */ new Map();
1696
+ const rootParsed = gtc.parseTsconfig(tsconfigFile, cache);
1697
+ const { tsconfig, tsconfigFile: effectiveTsconfigPath } = await resolveSolutionTsconfigForFile(path.resolve(conf.path), tsconfigFile, rootParsed, gtc, cache);
1698
+ const compilerOptions = tsconfig?.compilerOptions;
1699
+ const implicitBaseUrl = getImplicitBaseUrl(compilerOptions);
1700
+ const result = {
1701
+ tsconfig,
1702
+ tsconfigFile: effectiveTsconfigPath
1703
+ };
1704
+ if (resolutionFiles) resolutionFiles.value = Object.freeze([...new Set(readPathsFromCache(cache).map((file) => path.resolve(file)))].sort());
1705
+ if (compilerOptions?.paths) {
1706
+ const baseUrl = compilerOptions.baseUrl;
1707
+ result.tsOptions = {
1708
+ baseUrl,
1709
+ pathMappings: convertTsPathsToRegexes(compilerOptions.paths, resolveBaseUrlForCompilerOptions(baseUrl, effectiveTsconfigPath, cwd))
1710
+ };
1711
+ }
1712
+ if (provenance) {
1713
+ const referenceGraph = await collectReferenceGraph(tsconfigFile, rootParsed, gtc.parseTsconfig, cache);
1714
+ provenance.value = {
1715
+ direct,
1716
+ effectivePath: effectiveTsconfigPath,
1717
+ implicitBaseUrl,
1718
+ readPaths: readPathsFromCache(cache),
1719
+ references: referenceGraph.references,
1720
+ rootPath: tsconfigFile,
1721
+ traversalLimitExceeded: referenceGraph.traversalLimitExceeded,
1722
+ unresolvedReferences: referenceGraph.unresolvedReferences
1723
+ };
1724
+ }
1725
+ return result;
1726
+ }
1727
+ //#endregion
1394
1728
  //#region src/diff-engine.ts
1729
+ const applyTsConfig = (conf, next) => {
1730
+ conf.tsconfig = next?.tsconfig ?? {};
1731
+ conf.tsconfigFile = next?.tsconfigFile;
1732
+ conf.tsOptions = next?.tsOptions;
1733
+ };
1395
1734
  var DiffEngine = class {
1396
1735
  ctx;
1397
1736
  prevConfig;
@@ -1407,14 +1746,19 @@ var DiffEngine = class {
1407
1746
  cwd: this.ctx.config.cwd,
1408
1747
  file: this.ctx.conf.path
1409
1748
  });
1410
- const { tsconfig, tsconfigFile, tsOptions } = this.ctx.conf;
1411
- Object.assign(conf, {
1412
- tsconfig,
1413
- tsconfigFile,
1414
- tsOptions
1415
- });
1416
- return this.refresh(conf, fn);
1749
+ const resolutionFiles = {};
1750
+ const tsconfig = await loadTsConfig(conf, conf.config.cwd || this.ctx.config.cwd, void 0, resolutionFiles);
1751
+ applyTsConfig(conf, tsconfig);
1752
+ rememberTsConfigResolutionFiles(conf, resolutionFiles.value ?? []);
1753
+ const affected = this.refresh(conf, fn);
1754
+ if (!affected.hasConfigChanged) {
1755
+ applyTsConfig(this.ctx.conf, tsconfig);
1756
+ rememberTsConfigResolutionFiles(this.ctx.conf, resolutionFiles.value ?? []);
1757
+ }
1758
+ return affected;
1417
1759
  }
1760
+ /** @internal Exact tsconfig files behind the currently attached resolution options. */
1761
+ getResolutionConfigFiles = () => getTsConfigResolutionFiles(this.ctx.conf);
1418
1762
  /**
1419
1763
  * Update the context from the refreshed config
1420
1764
  * then persist the changes on each affected engines
@@ -1728,8 +2072,10 @@ var BambooContext = class extends Generator {
1728
2072
  if (config.logLevel) logger.level = config.logLevel;
1729
2073
  this.project = new Project({
1730
2074
  ...conf.tsconfig,
1731
- getFiles: this.getFiles.bind(this),
1732
- readFile: this.runtime.fs.readFileSync.bind(this),
2075
+ deferInitialSourceFiles: true,
2076
+ resolutionConfigFiles: getTsConfigResolutionFiles(conf),
2077
+ getFiles: () => this.getFiles(),
2078
+ readFile: (filePath) => this.runtime.fs.readFileSync(filePath),
1733
2079
  hooks: conf.hooks,
1734
2080
  parserOptions: {
1735
2081
  ...this.parserOptions,
@@ -2033,238 +2379,13 @@ async function reportRebuildFailure(run) {
2033
2379
  }
2034
2380
  }
2035
2381
  //#endregion
2036
- //#region src/tsconfig-utils.ts
2037
- /**
2038
- * If `filename` points to a `.json` file that exists as a regular file, return its absolute path.
2039
- */
2040
- async function resolveDirectTsconfigJson(filename) {
2041
- if (path.extname(filename) !== ".json") return null;
2042
- const resolved = path.resolve(filename);
2043
- try {
2044
- const stat = await promises.stat(resolved);
2045
- if (stat.isFile() || stat.isFIFO()) return resolved;
2046
- throw new Error(`${filename} exists but is not a regular file.`);
2047
- } catch (e) {
2048
- if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return null;
2049
- throw e;
2050
- }
2051
- }
2052
- /**
2053
- * Walk upward from `dirname(filename)` and return the first existing `configName`,
2054
- * stopping at `root` (inclusive) or the filesystem root.
2055
- */
2056
- async function findClosestTsconfig(filename, root, configName = "tsconfig.json") {
2057
- const resolvedRoot = path.resolve(root);
2058
- let dir = path.dirname(path.resolve(filename));
2059
- for (;;) {
2060
- const candidate = path.join(dir, configName);
2061
- try {
2062
- const stat = await promises.stat(candidate);
2063
- if (stat.isFile() || stat.isFIFO()) return candidate;
2064
- } catch {}
2065
- if (dir === resolvedRoot || path.dirname(dir) === dir) return null;
2066
- dir = path.dirname(dir);
2067
- }
2068
- }
2069
- /**
2070
- * Resolve `compilerOptions.baseUrl` the same way TypeScript does: relative to the tsconfig file.
2071
- * Falls back to `cwd` when `baseUrl` is omitted.
2072
- */
2073
- function resolveBaseUrlForCompilerOptions(baseUrl, tsconfigFile, cwd) {
2074
- if (baseUrl == null) return cwd;
2075
- if (baseUrl.startsWith("${")) return baseUrl;
2076
- if (path.isAbsolute(baseUrl)) return baseUrl;
2077
- return path.resolve(path.dirname(tsconfigFile), baseUrl);
2078
- }
2079
- const SOURCE_EXTENSIONS = [
2080
- ".ts",
2081
- ".tsx",
2082
- ".mts",
2083
- ".cts"
2084
- ];
2085
- function resolveReferencedTsconfigPath(refPath, fromDir, configName = "tsconfig.json") {
2086
- const p = refPath.endsWith(".json") ? refPath : path.join(refPath, configName);
2087
- return path.resolve(fromDir, p);
2088
- }
2089
- /**
2090
- * When a file belongs to a referenced project (TypeScript project references),
2091
- * return that project's merged tsconfig for `compilerOptions`.
2092
- */
2093
- async function resolveSolutionTsconfigForFile(absoluteFilename, rootTsconfigPath, rootParsed, getTsconfigModule) {
2094
- const { parseTsconfig } = getTsconfigModule;
2095
- if (isSourceFileIncludedInTsconfig(absoluteFilename, rootTsconfigPath, rootParsed)) return {
2096
- tsconfig: rootParsed,
2097
- tsconfigFile: rootTsconfigPath
2098
- };
2099
- const refs = rootParsed.references;
2100
- if (!refs?.length) return {
2101
- tsconfig: rootParsed,
2102
- tsconfigFile: rootTsconfigPath
2103
- };
2104
- if (!SOURCE_EXTENSIONS.some((ext) => absoluteFilename.endsWith(ext))) return {
2105
- tsconfig: rootParsed,
2106
- tsconfigFile: rootTsconfigPath
2107
- };
2108
- const rootDir = path.dirname(rootTsconfigPath);
2109
- for (const ref of refs) {
2110
- const refPath = resolveReferencedTsconfigPath(ref.path, rootDir);
2111
- try {
2112
- await promises.access(refPath);
2113
- } catch {
2114
- continue;
2115
- }
2116
- const childParsed = parseTsconfig(refPath);
2117
- if (isSourceFileIncludedInTsconfig(absoluteFilename, refPath, childParsed)) return {
2118
- tsconfig: childParsed,
2119
- tsconfigFile: refPath
2120
- };
2121
- }
2122
- return {
2123
- tsconfig: rootParsed,
2124
- tsconfigFile: rootTsconfigPath
2125
- };
2126
- }
2127
- const POSIX_SEP_RE = new RegExp("\\" + path.posix.sep, "g");
2128
- const NATIVE_SEP_RE = new RegExp("\\" + path.sep, "g");
2129
- const PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
2130
- const GLOB_ALL_PATTERN = `**/*`;
2131
- const TS_EXTENSIONS = [
2132
- ".ts",
2133
- ".tsx",
2134
- ".mts",
2135
- ".cts"
2136
- ];
2137
- const TSJS_EXTENSIONS = TS_EXTENSIONS.concat([
2138
- ".js",
2139
- ".jsx",
2140
- ".mjs",
2141
- ".cjs"
2142
- ]);
2143
- const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
2144
- const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
2145
- const IS_POSIX = path.posix.sep === path.sep;
2146
- const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, path.posix.sep);
2147
- const resolve2posix = IS_POSIX ? (dir, filename) => dir ? path.resolve(dir, filename) : path.resolve(filename) : (dir, filename) => {
2148
- const posix2native = (f) => f.replace(POSIX_SEP_RE, path.sep);
2149
- return native2posix(dir ? path.resolve(posix2native(dir), posix2native(filename)) : path.resolve(posix2native(filename)));
2150
- };
2151
- function isGlobMatch(filename, dir, patterns, allowJs) {
2152
- const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
2153
- return patterns.some((patternArg) => {
2154
- let pattern = patternArg;
2155
- let lastWildcardIndex = pattern.length;
2156
- let hasWildcard = false;
2157
- let hasExtension = false;
2158
- let hasSlash = false;
2159
- let lastSlashIndex = -1;
2160
- for (let i = pattern.length - 1; i > -1; i--) {
2161
- const c = pattern[i];
2162
- if (!hasWildcard) {
2163
- if (c === "*" || c === "?") {
2164
- lastWildcardIndex = i;
2165
- hasWildcard = true;
2166
- }
2167
- }
2168
- if (!hasSlash) {
2169
- if (c === ".") hasExtension = true;
2170
- else if (c === "/") {
2171
- lastSlashIndex = i;
2172
- hasSlash = true;
2173
- }
2174
- }
2175
- if (hasWildcard && hasSlash) break;
2176
- }
2177
- if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
2178
- pattern += `${pattern.endsWith("/") ? "" : "/"}${GLOB_ALL_PATTERN}`;
2179
- lastWildcardIndex = pattern.length - 1;
2180
- hasWildcard = true;
2181
- }
2182
- if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
2183
- if (pattern.endsWith("*") && !extensions.some((ext) => filename.endsWith(ext))) return false;
2184
- if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
2185
- const resolvedPattern = resolve2posix(dir, pattern);
2186
- let firstWildcardIndex = -1;
2187
- for (let i = 0; i < resolvedPattern.length; i++) if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
2188
- firstWildcardIndex = i;
2189
- hasWildcard = true;
2190
- break;
2191
- }
2192
- if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
2193
- if (!hasWildcard) return filename === resolvedPattern;
2194
- 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;
2195
- if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
2196
- const regex = pattern2regex(resolvedPattern, allowJs);
2197
- PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
2198
- return regex.test(filename);
2199
- });
2200
- }
2201
- function pattern2regex(resolvedPattern, allowJs) {
2202
- let regexStr = "^";
2203
- for (let i = 0; i < resolvedPattern.length; i++) {
2204
- const char = resolvedPattern[i];
2205
- if (char === "?") {
2206
- regexStr += "[^\\/]";
2207
- continue;
2208
- }
2209
- if (char === "*") {
2210
- if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
2211
- i += 2;
2212
- regexStr += "(?:[^\\/]*\\/)*";
2213
- continue;
2214
- }
2215
- regexStr += "[^\\/]*";
2216
- continue;
2217
- }
2218
- if ("/.+^${}()|[]\\".includes(char)) regexStr += "\\";
2219
- regexStr += char;
2220
- }
2221
- if (resolvedPattern.endsWith("*")) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
2222
- regexStr += "$";
2223
- return new RegExp(regexStr);
2224
- }
2225
- function isIncluded(filename, tsconfigFile, tsconfig) {
2226
- const dir = native2posix(path.dirname(tsconfigFile));
2227
- const files = (tsconfig.files || []).map((file) => resolve2posix(dir, file));
2228
- const absoluteFilename = resolve2posix(null, filename);
2229
- if (files.includes(filename)) return true;
2230
- const allowJs = tsconfig.compilerOptions?.allowJs;
2231
- if (isGlobMatch(absoluteFilename, dir, tsconfig.include || (tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs)) return !isGlobMatch(absoluteFilename, dir, tsconfig.exclude || [], allowJs);
2232
- return false;
2233
- }
2234
- /** Whether `absoluteFilename` is part of the compilation set defined by this tsconfig. */
2235
- function isSourceFileIncludedInTsconfig(absoluteFilename, tsconfigFile, tsconfig) {
2236
- return isIncluded(absoluteFilename, tsconfigFile, tsconfig);
2237
- }
2238
- //#endregion
2239
- //#region src/load-tsconfig.ts
2240
- async function loadTsConfig(conf, cwd) {
2241
- const root = cwd;
2242
- let tsconfigFile = await resolveDirectTsconfigJson(conf.path);
2243
- if (!tsconfigFile) tsconfigFile = await findClosestTsconfig(conf.path, root, "tsconfig.json");
2244
- if (!tsconfigFile) return {
2245
- tsconfig: {},
2246
- tsconfigFile: void 0
2247
- };
2248
- const gtc = await import("get-tsconfig");
2249
- const rootParsed = gtc.parseTsconfig(tsconfigFile);
2250
- const { tsconfig, tsconfigFile: effectiveTsconfigPath } = await resolveSolutionTsconfigForFile(path.resolve(conf.path), tsconfigFile, rootParsed, gtc);
2251
- const compilerOptions = tsconfig?.compilerOptions;
2252
- const result = {
2253
- tsconfig,
2254
- tsconfigFile: effectiveTsconfigPath
2255
- };
2256
- if (compilerOptions?.paths) {
2257
- const baseUrl = compilerOptions.baseUrl;
2258
- result.tsOptions = {
2259
- baseUrl,
2260
- pathMappings: convertTsPathsToRegexes(compilerOptions.paths, resolveBaseUrlForCompilerOptions(baseUrl, effectiveTsconfigPath, cwd))
2261
- };
2262
- }
2263
- return result;
2264
- }
2265
- //#endregion
2266
2382
  //#region src/config.ts
2267
2383
  const RESOLVED_HOOKS_NAME = "__resolved__";
2384
+ const AUTO_PARSER_HOOKS = Object.freeze(["vue", "svelte"]);
2385
+ const autoPluginFactories = {
2386
+ svelte: pluginSvelte,
2387
+ vue: pluginVue
2388
+ };
2268
2389
  /**
2269
2390
  * Built-in plugins that are auto-injected when using the CLI or PostCSS plugin.
2270
2391
  * These provide Vue/Svelte single-file-component support.
@@ -2277,13 +2398,10 @@ const RESOLVED_HOOKS_NAME = "__resolved__";
2277
2398
  * ever set. List the plugin yourself to use it.
2278
2399
  */
2279
2400
  function getAutoPlugins() {
2280
- return [pluginVue(), pluginSvelte()];
2401
+ return AUTO_PARSER_HOOKS.map((identity) => autoPluginFactories[identity]());
2281
2402
  }
2282
- /**
2283
- * Load config and create context with auto-injected plugins.
2284
- * Used by the CLI and PostCSS plugin.
2285
- */
2286
- async function loadConfigAndCreateContext(options = {}) {
2403
+ /** Resolve all config state without constructing the parser Project owned by BambooContext. */
2404
+ async function prepareNodeConfig(options = {}) {
2287
2405
  const { config, configPath } = options;
2288
2406
  const cwd = options.cwd ?? options?.config?.cwd ?? process.cwd();
2289
2407
  const conf = await loadConfig({
@@ -2299,8 +2417,18 @@ async function loadConfigAndCreateContext(options = {}) {
2299
2417
  hooks: conf.hooks
2300
2418
  }]);
2301
2419
  conf.config.plugins = [...autoPlugins, ...conf.config.plugins ?? []];
2302
- const tsConfResult = await loadTsConfig(conf, cwd);
2420
+ const tsconfigResolutionFiles = {};
2421
+ const tsConfResult = await loadTsConfig(conf, cwd, void 0, tsconfigResolutionFiles);
2303
2422
  if (tsConfResult) Object.assign(conf, tsConfResult);
2423
+ rememberTsConfigResolutionFiles(conf, tsconfigResolutionFiles.value ?? []);
2424
+ return { conf };
2425
+ }
2426
+ /**
2427
+ * Load config and create context with auto-injected plugins.
2428
+ * Used by the CLI and PostCSS plugin.
2429
+ */
2430
+ async function loadConfigAndCreateContext(options = {}) {
2431
+ const { conf } = await prepareNodeConfig(options);
2304
2432
  return new BambooContext(conf);
2305
2433
  }
2306
2434
  //#endregion
@@ -3114,20 +3242,84 @@ var Builder = class {
3114
3242
  explicitDepsMeta;
3115
3243
  affecteds;
3116
3244
  configDependencies = /* @__PURE__ */ new Set();
3245
+ pendingConfigCrawl;
3246
+ /** Last complete included inventory, including members which have since been deleted. */
3247
+ sourceInventory;
3248
+ /** Existing included owners selected by the last resolution-ledger invalidation pass. */
3249
+ affectedFiles;
3250
+ /** Dependency-before-importer parse order for the selected owners. */
3251
+ extractionOrder;
3252
+ /** Exact cross-file semantic reads retained per included extraction owner. */
3253
+ resolutionReadSets = /* @__PURE__ */ new Map();
3254
+ /** Previously semantic paths which are absent, retained only while their owner is unchanged. */
3255
+ pendingResolutionReadSets = /* @__PURE__ */ new Map();
3256
+ /** Missing local priority candidates which can redirect a current semantic resolution. */
3257
+ resolutionCandidateSets = /* @__PURE__ */ new Map();
3258
+ /** Exact resolver configuration reads retained per included semantic owner. */
3259
+ resolutionConfigurationSets = /* @__PURE__ */ new Map();
3260
+ /** Byte snapshots for resolver configuration files, independent of filesystem mtimes. */
3261
+ resolutionConfigurationBytes = /* @__PURE__ */ new Map();
3262
+ /** Previous effective tsconfig read-set, needed to classify its deletion as an option reload. */
3263
+ tsconfigResolutionFiles = [];
3264
+ /** Config-graph mtimes as of the last completed setup, consulted by the dev fast path. */
3265
+ configGraphMtimes;
3266
+ /** @internal Current and missing resolver paths which can change the stylesheet. */
3267
+ getResolutionReadFiles = () => {
3268
+ const files = /* @__PURE__ */ new Set();
3269
+ for (const readSets of [
3270
+ this.resolutionReadSets,
3271
+ this.pendingResolutionReadSets,
3272
+ this.resolutionCandidateSets
3273
+ ]) for (const dependencies of readSets.values()) for (const dependency of dependencies) files.add(dependency);
3274
+ return Object.freeze([...files].sort());
3275
+ };
3276
+ /** @internal Exact local package/tsconfig files which can change semantic resolution. */
3277
+ getResolutionConfigurationFiles = () => {
3278
+ const files = /* @__PURE__ */ new Set();
3279
+ for (const configurations of this.resolutionConfigurationSets.values()) for (const configuration of configurations) files.add(configuration);
3280
+ return Object.freeze([...files].sort());
3281
+ };
3282
+ readResolutionConfiguration = (file) => {
3283
+ try {
3284
+ return readFileSync(file).toString("base64");
3285
+ } catch (error) {
3286
+ if (error?.code === "ENOENT") return void 0;
3287
+ throw error;
3288
+ }
3289
+ };
3290
+ changedResolutionConfigurations = () => this.getResolutionConfigurationFiles().filter((file) => this.resolutionConfigurationBytes.get(file) !== this.readResolutionConfiguration(file));
3291
+ snapshotResolutionConfigurations = () => {
3292
+ const current = new Set(this.getResolutionConfigurationFiles());
3293
+ for (const file of current) this.resolutionConfigurationBytes.set(file, this.readResolutionConfiguration(file));
3294
+ for (const file of this.resolutionConfigurationBytes.keys()) if (!current.has(file)) this.resolutionConfigurationBytes.delete(file);
3295
+ };
3296
+ /**
3297
+ * Remember what to crawl; do not crawl yet.
3298
+ *
3299
+ * The crawl walks the config's own import graph, and resolving a bare specifier there loads a
3300
+ * whole TypeScript compiler. Only `registerDependency` reads the result, and only the PostCSS
3301
+ * plugin calls that — the CLI and the Vite plugin (which crawls separately, when it watches)
3302
+ * paid ~155ms of compiler load per build for a set neither of them ever read.
3303
+ */
3117
3304
  setConfigDependencies(options) {
3305
+ this.pendingConfigCrawl = options;
3306
+ const cwd = options?.cwd ?? this.context?.config.cwd ?? process.cwd();
3307
+ for (const file of this.context?.conf.dependencies ?? []) this.configDependencies.add(resolve(cwd, file));
3308
+ }
3309
+ /** Crawl on first read, once per `setConfigDependencies`. */
3310
+ crawlConfigDependencies() {
3311
+ const options = this.pendingConfigCrawl;
3312
+ if (!options) return;
3313
+ this.pendingConfigCrawl = void 0;
3118
3314
  const tsOptions = this.context?.conf.tsOptions ?? {
3119
3315
  baseUrl: void 0,
3120
3316
  pathMappings: []
3121
3317
  };
3122
3318
  const compilerOptions = this.context?.conf.tsconfig?.compilerOptions ?? {};
3123
- const { deps: foundDeps } = getConfigDependencies(options.configPath, tsOptions, compilerOptions);
3124
- const cwd = options?.cwd ?? this.context?.config.cwd ?? process.cwd();
3125
- const configDeps = new Set([...foundDeps, ...(this.context?.conf.dependencies ?? []).map((file) => resolve(cwd, file))]);
3126
- configDeps.forEach((file) => {
3127
- this.configDependencies.add(file);
3128
- });
3319
+ const { deps } = getConfigDependencies(options.configPath, tsOptions, compilerOptions);
3320
+ deps.forEach((file) => this.configDependencies.add(file));
3129
3321
  logger.debug("builder", "Config dependencies");
3130
- logger.debug("builder", configDeps);
3322
+ logger.debug("builder", deps);
3131
3323
  }
3132
3324
  setup = async (options = {}) => {
3133
3325
  logger.debug("builder", "🚧 Setup");
@@ -3142,9 +3334,38 @@ var Builder = class {
3142
3334
  dev: options.dev
3143
3335
  });
3144
3336
  const ctx = this.getContextOrThrow();
3337
+ const previousTsconfigFiles = this.tsconfigResolutionFiles.length ? this.tsconfigResolutionFiles : ctx.diff.getResolutionConfigFiles();
3338
+ /**
3339
+ * Dev fast path: skip the config reload when nothing that can change the resolved config
3340
+ * has moved on disk.
3341
+ *
3342
+ * `reloadConfigAndRefreshContext` re-bundles and re-evaluates the config file and the
3343
+ * tsconfig chain on every call, and a dev server reaches `setup` on every stylesheet
3344
+ * rebuild — that is 10–18ms paid per source edit for a config that cannot have changed,
3345
+ * since editing the config restarts the dev server outside this method's control anyway.
3346
+ * The guard set is exactly what the reload would re-read: the config file, its bundled
3347
+ * import graph, the explicit `dependencies`, and the tsconfig files behind resolution. Any
3348
+ * of them moving — including appearing or disappearing, which `getFileMeta` reports as a
3349
+ * changed mtime — takes the full reload below, as does a file the last snapshot never saw.
3350
+ *
3351
+ * Dev-only because the reload is also the recovery for edits this guard cannot see — a
3352
+ * preset external to the config bundle — and a one-shot build keeps paying the reload
3353
+ * rather than trading that recovery for a latency only watch mode feels.
3354
+ */
3355
+ if (options.dev && this.configGraphUnchanged(configPath)) {
3356
+ this.affecteds = {
3357
+ artifacts: /* @__PURE__ */ new Set(),
3358
+ hasConfigChanged: false,
3359
+ diffs: []
3360
+ };
3361
+ this.explicitDepsMeta = this.checkFilesChanged(this.context.explicitDeps);
3362
+ this.refreshSourceState(ctx, previousTsconfigFiles);
3363
+ return;
3364
+ }
3145
3365
  this.affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
3146
3366
  this.context = new BambooContext(conf);
3147
3367
  });
3368
+ this.tsconfigResolutionFiles = this.getContextOrThrow().diff.getResolutionConfigFiles();
3148
3369
  logger.debug("builder", this.affecteds);
3149
3370
  this.explicitDepsMeta = this.checkFilesChanged(this.context.explicitDeps);
3150
3371
  if (this.explicitDepsMeta.hasFilesChanged) {
@@ -3156,17 +3377,152 @@ var Builder = class {
3156
3377
  }
3157
3378
  if (this.affecteds.hasConfigChanged) {
3158
3379
  logger.debug("builder", "⚙️ Config changed, reloading");
3380
+ this.filesMeta = void 0;
3381
+ this.affectedFiles = void 0;
3382
+ this.extractionOrder = void 0;
3383
+ this.sourceInventory = void 0;
3384
+ this.resolutionReadSets.clear();
3385
+ this.pendingResolutionReadSets.clear();
3386
+ this.resolutionCandidateSets.clear();
3387
+ this.resolutionConfigurationSets.clear();
3388
+ this.resolutionConfigurationBytes.clear();
3159
3389
  await ctx.hooks["config:change"]?.({
3160
3390
  config: ctx.config,
3161
3391
  changes: this.affecteds
3162
3392
  });
3393
+ this.snapshotConfigGraphMtimes(configPath);
3163
3394
  return;
3164
3395
  }
3165
- this.filesMeta = this.checkFilesChanged(ctx.getFiles());
3396
+ this.refreshSourceState(ctx, previousTsconfigFiles);
3397
+ this.snapshotConfigGraphMtimes(configPath);
3398
+ };
3399
+ /** Every file whose content participates in the resolved config, for the dev fast path. */
3400
+ configGraphFiles = (configPath) => uniq([
3401
+ ...configPath ? [configPath] : [],
3402
+ ...this.configDependencies,
3403
+ ...this.tsconfigResolutionFiles,
3404
+ ...this.context?.explicitDeps ?? []
3405
+ ].map(normalize));
3406
+ configGraphUnchanged = (configPath) => {
3407
+ const snapshot = this.configGraphMtimes;
3408
+ if (!snapshot) return false;
3409
+ for (const file of this.configGraphFiles(configPath)) {
3410
+ const recorded = snapshot.get(file);
3411
+ if (recorded === void 0 || recorded !== this.getFileMeta(file).mtime) return false;
3412
+ }
3413
+ return true;
3414
+ };
3415
+ snapshotConfigGraphMtimes = (configPath) => {
3416
+ const snapshot = /* @__PURE__ */ new Map();
3417
+ for (const file of this.configGraphFiles(configPath)) snapshot.set(file, this.getFileMeta(file).mtime);
3418
+ this.configGraphMtimes = snapshot;
3419
+ };
3420
+ /** The per-pass source bookkeeping every setup ends with, config reload or not. */
3421
+ refreshSourceState = (ctx, previousTsconfigFiles) => {
3422
+ const changedResolutionConfigurations = this.changedResolutionConfigurations();
3423
+ const changedResolutionSet = new Set(changedResolutionConfigurations);
3424
+ const resolutionAffected = /* @__PURE__ */ new Set();
3425
+ const resolutionLedger = changedResolutionConfigurations.length ? ctx.project.getResolutionLedger() : void 0;
3426
+ for (const [owner, configurations] of this.resolutionConfigurationSets) if (configurations.some((file) => changedResolutionSet.has(file))) resolutionAffected.add(owner);
3427
+ if (changedResolutionConfigurations.length) {
3428
+ const tsconfigCandidates = new Set([...previousTsconfigFiles, ...this.tsconfigResolutionFiles]);
3429
+ const replaceCompilerOptions = changedResolutionConfigurations.some((file) => tsconfigCandidates.has(file));
3430
+ ctx.project.refreshResolutionConfiguration(ctx.conf.tsconfig?.compilerOptions, this.tsconfigResolutionFiles, replaceCompilerOptions);
3431
+ }
3432
+ const inventory = ctx.getFiles();
3433
+ const tracked = uniq([
3434
+ ...this.sourceInventory ?? inventory,
3435
+ ...inventory,
3436
+ ...this.getResolutionReadFiles()
3437
+ ]);
3438
+ this.filesMeta = this.checkFilesChanged(tracked);
3166
3439
  if (this.filesMeta.hasFilesChanged) {
3167
3440
  logger.debug("builder", "Files changed, invalidating them");
3168
- ctx.project.reloadSourceFiles();
3441
+ this.invalidateChangedSources(ctx, inventory, resolutionAffected, resolutionLedger);
3442
+ } else if (changedResolutionConfigurations.length) {
3443
+ ctx.encoder?.reconcileFileOwnerOrder("extract", inventory);
3444
+ this.extractionOrder = this.orderAffectedFiles(inventory, resolutionAffected, resolutionLedger ?? [], []);
3445
+ this.affectedFiles = new Set(this.extractionOrder.map(this.sourcePath));
3446
+ } else {
3447
+ this.affectedFiles = /* @__PURE__ */ new Set();
3448
+ this.extractionOrder = [];
3449
+ }
3450
+ this.sourceInventory = [...inventory];
3451
+ };
3452
+ /** Normalize the path identity shared by the Project ledger and file-owner keys. */
3453
+ sourcePath = (file) => file.replaceAll("\\", "/");
3454
+ /**
3455
+ * Reload only changed ledger members, then select their transitive included consumers.
3456
+ *
3457
+ * The dependency graph is snapshotted before mutation: reloading an importer retracts its
3458
+ * old forward edges, while deletion removes the target. Waiting until afterwards loses the
3459
+ * very closure the rebuild needs. New targets also select every pending importer and each
3460
+ * pending importer's dependent closure, because no edge to the new path existed yet.
3461
+ */
3462
+ invalidateChangedSources = (ctx, inventory, seededAffected = /* @__PURE__ */ new Set(), previousLedger) => {
3463
+ const project = ctx.project;
3464
+ const current = new Set(inventory.map(this.sourcePath));
3465
+ const changed = [...this.filesMeta?.changes ?? []].filter(([, meta]) => !meta.isUnchanged).map(([file]) => this.sourcePath(file));
3466
+ const ledger = previousLedger ?? project.getResolutionLedger();
3467
+ const pending = project.getUnresolvedImporters().map(this.sourcePath);
3468
+ const affected = new Set(seededAffected);
3469
+ const added = [];
3470
+ for (const file of changed) {
3471
+ if (current.has(file)) affected.add(file);
3472
+ for (const dependent of project.getDependents(file)) affected.add(this.sourcePath(dependent));
3473
+ if (existsSync(file) && !project.getSourceFile(file)) added.push(file);
3474
+ }
3475
+ if (added.length) for (const importer of pending) {
3476
+ affected.add(importer);
3477
+ for (const dependent of project.getDependents(importer)) affected.add(this.sourcePath(dependent));
3169
3478
  }
3479
+ for (const file of changed) if (!existsSync(file)) {
3480
+ project.removeSourceFile(file);
3481
+ fileModifiedMap.set(file, -Infinity);
3482
+ } else if (project.getSourceFile(file)) project.reloadSourceFile(file);
3483
+ else project.createSourceFile(file);
3484
+ ctx.encoder?.reconcileFileOwnerOrder("extract", inventory);
3485
+ const syntheticEdges = added.flatMap((target) => pending.map((importer) => [target, importer]));
3486
+ this.extractionOrder = this.orderAffectedFiles(inventory, affected, ledger, syntheticEdges);
3487
+ this.affectedFiles = new Set(this.extractionOrder.map(this.sourcePath));
3488
+ };
3489
+ /** Deterministic topological order, with current inventory order as the stable tie-break. */
3490
+ orderAffectedFiles = (inventory, affected, ledger, syntheticEdges) => {
3491
+ const files = inventory.filter((file) => affected.has(this.sourcePath(file)));
3492
+ const byPath = new Map(files.map((file) => [this.sourcePath(file), file]));
3493
+ const inventoryRank = new Map(files.map((file, index) => [this.sourcePath(file), index]));
3494
+ const outgoing = /* @__PURE__ */ new Map();
3495
+ const indegree = new Map(files.map((file) => [this.sourcePath(file), 0]));
3496
+ const addEdge = (rawTarget, rawImporter) => {
3497
+ if (!rawTarget) return;
3498
+ const target = this.sourcePath(rawTarget);
3499
+ const importer = this.sourcePath(rawImporter);
3500
+ if (target === importer || !byPath.has(target) || !byPath.has(importer)) return;
3501
+ const importers = outgoing.get(target) ?? /* @__PURE__ */ new Set();
3502
+ if (importers.has(importer)) return;
3503
+ importers.add(importer);
3504
+ outgoing.set(target, importers);
3505
+ indegree.set(importer, (indegree.get(importer) ?? 0) + 1);
3506
+ };
3507
+ for (const fact of ledger) addEdge(fact.target, fact.importer);
3508
+ for (const [target, importer] of syntheticEdges) addEdge(target, importer);
3509
+ const compare = (left, right) => (inventoryRank.get(left) ?? 0) - (inventoryRank.get(right) ?? 0);
3510
+ const ready = [...indegree].filter(([, degree]) => degree === 0).map(([file]) => file).sort(compare);
3511
+ const ordered = [];
3512
+ while (ready.length) {
3513
+ const file = ready.shift();
3514
+ ordered.push(file);
3515
+ for (const importer of [...outgoing.get(file) ?? []].sort(compare)) {
3516
+ const next = (indegree.get(importer) ?? 0) - 1;
3517
+ indegree.set(importer, next);
3518
+ if (next === 0) {
3519
+ ready.push(importer);
3520
+ ready.sort(compare);
3521
+ }
3522
+ }
3523
+ }
3524
+ for (const file of [...byPath.keys()].sort(compare)) if (!ordered.includes(file)) ordered.push(file);
3525
+ return ordered.map((file) => byPath.get(file));
3170
3526
  };
3171
3527
  /**
3172
3528
  * Write the generated `styled-system`, so an integration can be a project's only codegen.
@@ -3207,6 +3563,7 @@ var Builder = class {
3207
3563
  this.configDependencies.add(resolve(cwd || ctx.conf.config.cwd, file));
3208
3564
  });
3209
3565
  this.context = ctx;
3566
+ this.tsconfigResolutionFiles = ctx.diff.getResolutionConfigFiles();
3210
3567
  return ctx;
3211
3568
  };
3212
3569
  getContextOrThrow = () => {
@@ -3236,9 +3593,32 @@ var Builder = class {
3236
3593
  extractFile = (ctx, file) => {
3237
3594
  const meta = this.filesMeta?.changes.get(file) ?? this.getFileMeta(file);
3238
3595
  const hasConfigChanged = this.affecteds ? this.affecteds.hasConfigChanged : true;
3239
- if (meta.isUnchanged && !hasConfigChanged) return;
3596
+ if (meta.isUnchanged && !hasConfigChanged && !this.affectedFiles?.has(this.sourcePath(file))) return;
3597
+ const owner = this.sourcePath(file);
3598
+ const previousReads = this.resolutionReadSets.get(owner) ?? [];
3599
+ const previousPending = this.pendingResolutionReadSets.get(owner) ?? [];
3600
+ const previousCandidates = this.resolutionCandidateSets.get(owner) ?? [];
3601
+ const previousConfigurations = this.resolutionConfigurationSets.get(owner) ?? [];
3240
3602
  const parserResult = ctx.parseFile(file);
3241
3603
  fileModifiedMap.set(file, meta.mtime);
3604
+ if (parserResult) {
3605
+ const previousReadSet = meta.isUnchanged ? {
3606
+ dependencies: uniq([...previousReads, ...previousPending]).sort(),
3607
+ pendingCandidates: previousCandidates
3608
+ } : void 0;
3609
+ const readSet = ctx.project.getResolutionReadSet(file, parserResult.getDependencies(), previousReadSet);
3610
+ const currentReads = readSet.dependencies;
3611
+ const currentConfigurations = ctx.project.getResolutionConfigurationFiles(file, parserResult.getDependencies(), meta.isUnchanged ? previousConfigurations : []);
3612
+ this.resolutionReadSets.set(owner, currentReads);
3613
+ if (readSet.pendingCandidates.length) this.resolutionCandidateSets.set(owner, readSet.pendingCandidates);
3614
+ else this.resolutionCandidateSets.delete(owner);
3615
+ const pending = meta.isUnchanged ? uniq([...previousPending, ...previousReads]).filter((dependency) => !existsSync(dependency) && !currentReads.includes(dependency) && (!previousCandidates.includes(dependency) || readSet.pendingCandidates.includes(dependency))).sort() : [];
3616
+ if (pending.length) this.pendingResolutionReadSets.set(owner, pending);
3617
+ else this.pendingResolutionReadSets.delete(owner);
3618
+ const configurations = currentConfigurations.length || !meta.isUnchanged ? currentConfigurations : previousConfigurations;
3619
+ if (configurations.length) this.resolutionConfigurationSets.set(owner, configurations);
3620
+ else this.resolutionConfigurationSets.delete(owner);
3621
+ }
3242
3622
  return parserResult;
3243
3623
  };
3244
3624
  extract = () => {
@@ -3249,10 +3629,29 @@ var Builder = class {
3249
3629
  ctx.assertExtracted();
3250
3630
  return ctx.assertNoDeadCalls();
3251
3631
  }
3252
- const files = ctx.getFiles();
3632
+ const files = !hasConfigChanged && this.sourceInventory ? [...this.sourceInventory] : ctx.getFiles();
3633
+ const inventory = new Set(files.map(this.sourcePath));
3634
+ if (hasConfigChanged) {
3635
+ this.resolutionReadSets.clear();
3636
+ this.pendingResolutionReadSets.clear();
3637
+ this.resolutionCandidateSets.clear();
3638
+ this.resolutionConfigurationSets.clear();
3639
+ } else {
3640
+ for (const owner of this.resolutionReadSets.keys()) if (!inventory.has(owner)) this.resolutionReadSets.delete(owner);
3641
+ for (const owner of this.pendingResolutionReadSets.keys()) if (!inventory.has(owner)) this.pendingResolutionReadSets.delete(owner);
3642
+ for (const owner of this.resolutionCandidateSets.keys()) if (!inventory.has(owner)) this.resolutionCandidateSets.delete(owner);
3643
+ for (const owner of this.resolutionConfigurationSets.keys()) if (!inventory.has(owner)) this.resolutionConfigurationSets.delete(owner);
3644
+ }
3645
+ ctx.encoder?.reconcileFileOwnerOrder("extract", files);
3646
+ const filesToExtract = hasConfigChanged ? files : this.extractionOrder ?? files;
3253
3647
  const done = logger.time.info("Extracted in");
3254
- for (const file of files) this.extractFile(ctx, file);
3648
+ for (const file of filesToExtract) this.extractFile(ctx, file);
3255
3649
  done();
3650
+ this.sourceInventory = [...files];
3651
+ for (const file of uniq([...files, ...this.getResolutionReadFiles()])) fileModifiedMap.set(file, this.getFileMeta(file).mtime);
3652
+ this.snapshotResolutionConfigurations();
3653
+ this.affectedFiles = void 0;
3654
+ this.extractionOrder = void 0;
3256
3655
  ctx.assertExtracted(files);
3257
3656
  ctx.assertNoDeadCalls(files);
3258
3657
  };
@@ -3308,6 +3707,7 @@ var Builder = class {
3308
3707
  };
3309
3708
  registerDependency = (fn) => {
3310
3709
  const ctx = this.getContextOrThrow();
3710
+ this.crawlConfigDependencies();
3311
3711
  for (const fileOrGlob of ctx.config.include) {
3312
3712
  const dependency = parseDependency(fileOrGlob);
3313
3713
  if (dependency) fn(dependency);
@@ -3514,7 +3914,8 @@ async function generate(config, configPath) {
3514
3914
  */
3515
3915
  const bundleStyles = async (ctx, changedFilePaths) => {
3516
3916
  let parsed = 0;
3517
- for (const filePath of changedFilePaths) if (ctx.project.parseSourceFile(filePath)) parsed++;
3917
+ const encoder = ctx.parserOptions.encoder;
3918
+ for (const filePath of changedFilePaths) if (encoder.withOwner("extract", filePath, () => ctx.project.parseSourceFile(filePath, encoder))) parsed++;
3518
3919
  if (parsed === 0) return;
3519
3920
  const outfile = ctx.runtime.path.join(...ctx.paths.root, "styles.css");
3520
3921
  const done = logger.time.info(ctx.messages.buildComplete(parsed));
@@ -3539,12 +3940,13 @@ async function generate(config, configPath) {
3539
3940
  ctx.project.reloadSourceFile(filePath);
3540
3941
  await bundleStyles(ctx, [filePath, ...ctx.project.getDependents(filePath)]);
3541
3942
  } else if (event === "add") {
3943
+ const pendingClosure = ctx.project.getUnresolvedImporters().flatMap((importer) => [importer, ...ctx.project.getDependents(importer)]);
3542
3944
  ctx.project.createSourceFile(filePath);
3543
- await bundleStyles(ctx, [
3945
+ await bundleStyles(ctx, [...new Set([
3544
3946
  filePath,
3545
3947
  ...ctx.project.getDependents(filePath),
3546
- ...ctx.project.getUnresolvedImporters()
3547
- ]);
3948
+ ...pendingClosure
3949
+ ])]);
3548
3950
  }
3549
3951
  });
3550
3952
  }
@@ -3597,33 +3999,6 @@ const ensure = (outPath) => {
3597
3999
  //#endregion
3598
4000
  //#region src/vite-integration.ts
3599
4001
  /**
3600
- * Whether a Bamboo source compiler is running in this process.
3601
- *
3602
- * Two integrations can emit the stylesheet, and only one of them also compiles source.
3603
- * `@bamboocss/postcss` emits CSS and nothing else, so under it every `css()` and `cva()` call
3604
- * stays a runtime call and the generated style engine ships in the client bundle. That is a
3605
- * legitimate integration for a bundler with no Vite plugin — and a silent downgrade for a
3606
- * project that has Vite and simply did not add `@bamboocss/vite`, which is a setup Bamboo's
3607
- * own React Router guide used to describe. Nothing failed: the stylesheet was correct, the app
3608
- * rendered, and 20 kB of engine went out with it.
3609
- *
3610
- * On `globalThis` under a registered symbol rather than in a module variable, because the two
3611
- * packages that have to agree do not share a module instance. `@bamboocss/postcss` is required
3612
- * as CommonJS by a PostCSS config while `@bamboocss/vite` is imported as ESM by a Vite config,
3613
- * so even one installed copy of a shared dependency is loaded twice, once per format, with a
3614
- * variable each. The symbol is one value per realm regardless.
3615
- *
3616
- * A realm is as far as it goes: a worker thread, or PostCSS run from a separate process
3617
- * alongside the Vite build, sees no flag. Both fail towards saying something rather than
3618
- * staying quiet, and what they say names the option that silences it.
3619
- */
3620
- const FLAG = Symbol.for("bamboocss.static-compiler");
3621
- /** Called by an integration that compiles source, as it is constructed. */
3622
- const markStaticCompilerActive = () => {
3623
- globalThis[FLAG] = true;
3624
- };
3625
- const isStaticCompilerActive = () => Boolean(globalThis[FLAG]);
3626
- /**
3627
4002
  * Every extension Vite accepts for its config, so "is this a Vite project" is answered by the
3628
4003
  * same file Vite itself would load.
3629
4004
  *