@bamboocss/node 1.45.5 → 1.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,82 @@ 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
+ /** @internal Current and missing resolver paths which can change the stylesheet. */
3265
+ getResolutionReadFiles = () => {
3266
+ const files = /* @__PURE__ */ new Set();
3267
+ for (const readSets of [
3268
+ this.resolutionReadSets,
3269
+ this.pendingResolutionReadSets,
3270
+ this.resolutionCandidateSets
3271
+ ]) for (const dependencies of readSets.values()) for (const dependency of dependencies) files.add(dependency);
3272
+ return Object.freeze([...files].sort());
3273
+ };
3274
+ /** @internal Exact local package/tsconfig files which can change semantic resolution. */
3275
+ getResolutionConfigurationFiles = () => {
3276
+ const files = /* @__PURE__ */ new Set();
3277
+ for (const configurations of this.resolutionConfigurationSets.values()) for (const configuration of configurations) files.add(configuration);
3278
+ return Object.freeze([...files].sort());
3279
+ };
3280
+ readResolutionConfiguration = (file) => {
3281
+ try {
3282
+ return readFileSync(file).toString("base64");
3283
+ } catch (error) {
3284
+ if (error?.code === "ENOENT") return void 0;
3285
+ throw error;
3286
+ }
3287
+ };
3288
+ changedResolutionConfigurations = () => this.getResolutionConfigurationFiles().filter((file) => this.resolutionConfigurationBytes.get(file) !== this.readResolutionConfiguration(file));
3289
+ snapshotResolutionConfigurations = () => {
3290
+ const current = new Set(this.getResolutionConfigurationFiles());
3291
+ for (const file of current) this.resolutionConfigurationBytes.set(file, this.readResolutionConfiguration(file));
3292
+ for (const file of this.resolutionConfigurationBytes.keys()) if (!current.has(file)) this.resolutionConfigurationBytes.delete(file);
3293
+ };
3294
+ /**
3295
+ * Remember what to crawl; do not crawl yet.
3296
+ *
3297
+ * The crawl walks the config's own import graph, and resolving a bare specifier there loads a
3298
+ * whole TypeScript compiler. Only `registerDependency` reads the result, and only the PostCSS
3299
+ * plugin calls that — the CLI and the Vite plugin (which crawls separately, when it watches)
3300
+ * paid ~155ms of compiler load per build for a set neither of them ever read.
3301
+ */
3117
3302
  setConfigDependencies(options) {
3303
+ this.pendingConfigCrawl = options;
3304
+ const cwd = options?.cwd ?? this.context?.config.cwd ?? process.cwd();
3305
+ for (const file of this.context?.conf.dependencies ?? []) this.configDependencies.add(resolve(cwd, file));
3306
+ }
3307
+ /** Crawl on first read, once per `setConfigDependencies`. */
3308
+ crawlConfigDependencies() {
3309
+ const options = this.pendingConfigCrawl;
3310
+ if (!options) return;
3311
+ this.pendingConfigCrawl = void 0;
3118
3312
  const tsOptions = this.context?.conf.tsOptions ?? {
3119
3313
  baseUrl: void 0,
3120
3314
  pathMappings: []
3121
3315
  };
3122
3316
  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
- });
3317
+ const { deps } = getConfigDependencies(options.configPath, tsOptions, compilerOptions);
3318
+ deps.forEach((file) => this.configDependencies.add(file));
3129
3319
  logger.debug("builder", "Config dependencies");
3130
- logger.debug("builder", configDeps);
3320
+ logger.debug("builder", deps);
3131
3321
  }
3132
3322
  setup = async (options = {}) => {
3133
3323
  logger.debug("builder", "🚧 Setup");
@@ -3142,9 +3332,11 @@ var Builder = class {
3142
3332
  dev: options.dev
3143
3333
  });
3144
3334
  const ctx = this.getContextOrThrow();
3335
+ const previousTsconfigFiles = this.tsconfigResolutionFiles.length ? this.tsconfigResolutionFiles : ctx.diff.getResolutionConfigFiles();
3145
3336
  this.affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
3146
3337
  this.context = new BambooContext(conf);
3147
3338
  });
3339
+ this.tsconfigResolutionFiles = this.getContextOrThrow().diff.getResolutionConfigFiles();
3148
3340
  logger.debug("builder", this.affecteds);
3149
3341
  this.explicitDepsMeta = this.checkFilesChanged(this.context.explicitDeps);
3150
3342
  if (this.explicitDepsMeta.hasFilesChanged) {
@@ -3156,17 +3348,125 @@ var Builder = class {
3156
3348
  }
3157
3349
  if (this.affecteds.hasConfigChanged) {
3158
3350
  logger.debug("builder", "⚙️ Config changed, reloading");
3351
+ this.filesMeta = void 0;
3352
+ this.affectedFiles = void 0;
3353
+ this.extractionOrder = void 0;
3354
+ this.sourceInventory = void 0;
3355
+ this.resolutionReadSets.clear();
3356
+ this.pendingResolutionReadSets.clear();
3357
+ this.resolutionCandidateSets.clear();
3358
+ this.resolutionConfigurationSets.clear();
3359
+ this.resolutionConfigurationBytes.clear();
3159
3360
  await ctx.hooks["config:change"]?.({
3160
3361
  config: ctx.config,
3161
3362
  changes: this.affecteds
3162
3363
  });
3163
3364
  return;
3164
3365
  }
3165
- this.filesMeta = this.checkFilesChanged(ctx.getFiles());
3366
+ const changedResolutionConfigurations = this.changedResolutionConfigurations();
3367
+ const changedResolutionSet = new Set(changedResolutionConfigurations);
3368
+ const resolutionAffected = /* @__PURE__ */ new Set();
3369
+ const resolutionLedger = changedResolutionConfigurations.length ? ctx.project.getResolutionLedger() : void 0;
3370
+ for (const [owner, configurations] of this.resolutionConfigurationSets) if (configurations.some((file) => changedResolutionSet.has(file))) resolutionAffected.add(owner);
3371
+ if (changedResolutionConfigurations.length) {
3372
+ const tsconfigCandidates = new Set([...previousTsconfigFiles, ...this.tsconfigResolutionFiles]);
3373
+ const replaceCompilerOptions = changedResolutionConfigurations.some((file) => tsconfigCandidates.has(file));
3374
+ ctx.project.refreshResolutionConfiguration(ctx.conf.tsconfig?.compilerOptions, this.tsconfigResolutionFiles, replaceCompilerOptions);
3375
+ }
3376
+ const inventory = ctx.getFiles();
3377
+ const tracked = uniq([
3378
+ ...this.sourceInventory ?? inventory,
3379
+ ...inventory,
3380
+ ...this.getResolutionReadFiles()
3381
+ ]);
3382
+ this.filesMeta = this.checkFilesChanged(tracked);
3166
3383
  if (this.filesMeta.hasFilesChanged) {
3167
3384
  logger.debug("builder", "Files changed, invalidating them");
3168
- ctx.project.reloadSourceFiles();
3385
+ this.invalidateChangedSources(ctx, inventory, resolutionAffected, resolutionLedger);
3386
+ } else if (changedResolutionConfigurations.length) {
3387
+ ctx.encoder?.reconcileFileOwnerOrder("extract", inventory);
3388
+ this.extractionOrder = this.orderAffectedFiles(inventory, resolutionAffected, resolutionLedger ?? [], []);
3389
+ this.affectedFiles = new Set(this.extractionOrder.map(this.sourcePath));
3390
+ } else {
3391
+ this.affectedFiles = /* @__PURE__ */ new Set();
3392
+ this.extractionOrder = [];
3169
3393
  }
3394
+ this.sourceInventory = [...inventory];
3395
+ };
3396
+ /** Normalize the path identity shared by the Project ledger and file-owner keys. */
3397
+ sourcePath = (file) => file.replaceAll("\\", "/");
3398
+ /**
3399
+ * Reload only changed ledger members, then select their transitive included consumers.
3400
+ *
3401
+ * The dependency graph is snapshotted before mutation: reloading an importer retracts its
3402
+ * old forward edges, while deletion removes the target. Waiting until afterwards loses the
3403
+ * very closure the rebuild needs. New targets also select every pending importer and each
3404
+ * pending importer's dependent closure, because no edge to the new path existed yet.
3405
+ */
3406
+ invalidateChangedSources = (ctx, inventory, seededAffected = /* @__PURE__ */ new Set(), previousLedger) => {
3407
+ const project = ctx.project;
3408
+ const current = new Set(inventory.map(this.sourcePath));
3409
+ const changed = [...this.filesMeta?.changes ?? []].filter(([, meta]) => !meta.isUnchanged).map(([file]) => this.sourcePath(file));
3410
+ const ledger = previousLedger ?? project.getResolutionLedger();
3411
+ const pending = project.getUnresolvedImporters().map(this.sourcePath);
3412
+ const affected = new Set(seededAffected);
3413
+ const added = [];
3414
+ for (const file of changed) {
3415
+ if (current.has(file)) affected.add(file);
3416
+ for (const dependent of project.getDependents(file)) affected.add(this.sourcePath(dependent));
3417
+ if (existsSync(file) && !project.getSourceFile(file)) added.push(file);
3418
+ }
3419
+ if (added.length) for (const importer of pending) {
3420
+ affected.add(importer);
3421
+ for (const dependent of project.getDependents(importer)) affected.add(this.sourcePath(dependent));
3422
+ }
3423
+ for (const file of changed) if (!existsSync(file)) {
3424
+ project.removeSourceFile(file);
3425
+ fileModifiedMap.set(file, -Infinity);
3426
+ } else if (project.getSourceFile(file)) project.reloadSourceFile(file);
3427
+ else project.createSourceFile(file);
3428
+ ctx.encoder?.reconcileFileOwnerOrder("extract", inventory);
3429
+ const syntheticEdges = added.flatMap((target) => pending.map((importer) => [target, importer]));
3430
+ this.extractionOrder = this.orderAffectedFiles(inventory, affected, ledger, syntheticEdges);
3431
+ this.affectedFiles = new Set(this.extractionOrder.map(this.sourcePath));
3432
+ };
3433
+ /** Deterministic topological order, with current inventory order as the stable tie-break. */
3434
+ orderAffectedFiles = (inventory, affected, ledger, syntheticEdges) => {
3435
+ const files = inventory.filter((file) => affected.has(this.sourcePath(file)));
3436
+ const byPath = new Map(files.map((file) => [this.sourcePath(file), file]));
3437
+ const inventoryRank = new Map(files.map((file, index) => [this.sourcePath(file), index]));
3438
+ const outgoing = /* @__PURE__ */ new Map();
3439
+ const indegree = new Map(files.map((file) => [this.sourcePath(file), 0]));
3440
+ const addEdge = (rawTarget, rawImporter) => {
3441
+ if (!rawTarget) return;
3442
+ const target = this.sourcePath(rawTarget);
3443
+ const importer = this.sourcePath(rawImporter);
3444
+ if (target === importer || !byPath.has(target) || !byPath.has(importer)) return;
3445
+ const importers = outgoing.get(target) ?? /* @__PURE__ */ new Set();
3446
+ if (importers.has(importer)) return;
3447
+ importers.add(importer);
3448
+ outgoing.set(target, importers);
3449
+ indegree.set(importer, (indegree.get(importer) ?? 0) + 1);
3450
+ };
3451
+ for (const fact of ledger) addEdge(fact.target, fact.importer);
3452
+ for (const [target, importer] of syntheticEdges) addEdge(target, importer);
3453
+ const compare = (left, right) => (inventoryRank.get(left) ?? 0) - (inventoryRank.get(right) ?? 0);
3454
+ const ready = [...indegree].filter(([, degree]) => degree === 0).map(([file]) => file).sort(compare);
3455
+ const ordered = [];
3456
+ while (ready.length) {
3457
+ const file = ready.shift();
3458
+ ordered.push(file);
3459
+ for (const importer of [...outgoing.get(file) ?? []].sort(compare)) {
3460
+ const next = (indegree.get(importer) ?? 0) - 1;
3461
+ indegree.set(importer, next);
3462
+ if (next === 0) {
3463
+ ready.push(importer);
3464
+ ready.sort(compare);
3465
+ }
3466
+ }
3467
+ }
3468
+ for (const file of [...byPath.keys()].sort(compare)) if (!ordered.includes(file)) ordered.push(file);
3469
+ return ordered.map((file) => byPath.get(file));
3170
3470
  };
3171
3471
  /**
3172
3472
  * Write the generated `styled-system`, so an integration can be a project's only codegen.
@@ -3207,6 +3507,7 @@ var Builder = class {
3207
3507
  this.configDependencies.add(resolve(cwd || ctx.conf.config.cwd, file));
3208
3508
  });
3209
3509
  this.context = ctx;
3510
+ this.tsconfigResolutionFiles = ctx.diff.getResolutionConfigFiles();
3210
3511
  return ctx;
3211
3512
  };
3212
3513
  getContextOrThrow = () => {
@@ -3236,9 +3537,32 @@ var Builder = class {
3236
3537
  extractFile = (ctx, file) => {
3237
3538
  const meta = this.filesMeta?.changes.get(file) ?? this.getFileMeta(file);
3238
3539
  const hasConfigChanged = this.affecteds ? this.affecteds.hasConfigChanged : true;
3239
- if (meta.isUnchanged && !hasConfigChanged) return;
3540
+ if (meta.isUnchanged && !hasConfigChanged && !this.affectedFiles?.has(this.sourcePath(file))) return;
3541
+ const owner = this.sourcePath(file);
3542
+ const previousReads = this.resolutionReadSets.get(owner) ?? [];
3543
+ const previousPending = this.pendingResolutionReadSets.get(owner) ?? [];
3544
+ const previousCandidates = this.resolutionCandidateSets.get(owner) ?? [];
3545
+ const previousConfigurations = this.resolutionConfigurationSets.get(owner) ?? [];
3240
3546
  const parserResult = ctx.parseFile(file);
3241
3547
  fileModifiedMap.set(file, meta.mtime);
3548
+ if (parserResult) {
3549
+ const previousReadSet = meta.isUnchanged ? {
3550
+ dependencies: uniq([...previousReads, ...previousPending]).sort(),
3551
+ pendingCandidates: previousCandidates
3552
+ } : void 0;
3553
+ const readSet = ctx.project.getResolutionReadSet(file, parserResult.getDependencies(), previousReadSet);
3554
+ const currentReads = readSet.dependencies;
3555
+ const currentConfigurations = ctx.project.getResolutionConfigurationFiles(file, parserResult.getDependencies(), meta.isUnchanged ? previousConfigurations : []);
3556
+ this.resolutionReadSets.set(owner, currentReads);
3557
+ if (readSet.pendingCandidates.length) this.resolutionCandidateSets.set(owner, readSet.pendingCandidates);
3558
+ else this.resolutionCandidateSets.delete(owner);
3559
+ const pending = meta.isUnchanged ? uniq([...previousPending, ...previousReads]).filter((dependency) => !existsSync(dependency) && !currentReads.includes(dependency) && (!previousCandidates.includes(dependency) || readSet.pendingCandidates.includes(dependency))).sort() : [];
3560
+ if (pending.length) this.pendingResolutionReadSets.set(owner, pending);
3561
+ else this.pendingResolutionReadSets.delete(owner);
3562
+ const configurations = currentConfigurations.length || !meta.isUnchanged ? currentConfigurations : previousConfigurations;
3563
+ if (configurations.length) this.resolutionConfigurationSets.set(owner, configurations);
3564
+ else this.resolutionConfigurationSets.delete(owner);
3565
+ }
3242
3566
  return parserResult;
3243
3567
  };
3244
3568
  extract = () => {
@@ -3250,9 +3574,28 @@ var Builder = class {
3250
3574
  return ctx.assertNoDeadCalls();
3251
3575
  }
3252
3576
  const files = ctx.getFiles();
3577
+ const inventory = new Set(files.map(this.sourcePath));
3578
+ if (hasConfigChanged) {
3579
+ this.resolutionReadSets.clear();
3580
+ this.pendingResolutionReadSets.clear();
3581
+ this.resolutionCandidateSets.clear();
3582
+ this.resolutionConfigurationSets.clear();
3583
+ } else {
3584
+ for (const owner of this.resolutionReadSets.keys()) if (!inventory.has(owner)) this.resolutionReadSets.delete(owner);
3585
+ for (const owner of this.pendingResolutionReadSets.keys()) if (!inventory.has(owner)) this.pendingResolutionReadSets.delete(owner);
3586
+ for (const owner of this.resolutionCandidateSets.keys()) if (!inventory.has(owner)) this.resolutionCandidateSets.delete(owner);
3587
+ for (const owner of this.resolutionConfigurationSets.keys()) if (!inventory.has(owner)) this.resolutionConfigurationSets.delete(owner);
3588
+ }
3589
+ ctx.encoder?.reconcileFileOwnerOrder("extract", files);
3590
+ const filesToExtract = hasConfigChanged ? files : this.extractionOrder ?? files;
3253
3591
  const done = logger.time.info("Extracted in");
3254
- for (const file of files) this.extractFile(ctx, file);
3592
+ for (const file of filesToExtract) this.extractFile(ctx, file);
3255
3593
  done();
3594
+ this.sourceInventory = [...files];
3595
+ for (const file of uniq([...files, ...this.getResolutionReadFiles()])) fileModifiedMap.set(file, this.getFileMeta(file).mtime);
3596
+ this.snapshotResolutionConfigurations();
3597
+ this.affectedFiles = void 0;
3598
+ this.extractionOrder = void 0;
3256
3599
  ctx.assertExtracted(files);
3257
3600
  ctx.assertNoDeadCalls(files);
3258
3601
  };
@@ -3308,6 +3651,7 @@ var Builder = class {
3308
3651
  };
3309
3652
  registerDependency = (fn) => {
3310
3653
  const ctx = this.getContextOrThrow();
3654
+ this.crawlConfigDependencies();
3311
3655
  for (const fileOrGlob of ctx.config.include) {
3312
3656
  const dependency = parseDependency(fileOrGlob);
3313
3657
  if (dependency) fn(dependency);
@@ -3514,7 +3858,8 @@ async function generate(config, configPath) {
3514
3858
  */
3515
3859
  const bundleStyles = async (ctx, changedFilePaths) => {
3516
3860
  let parsed = 0;
3517
- for (const filePath of changedFilePaths) if (ctx.project.parseSourceFile(filePath)) parsed++;
3861
+ const encoder = ctx.parserOptions.encoder;
3862
+ for (const filePath of changedFilePaths) if (encoder.withOwner("extract", filePath, () => ctx.project.parseSourceFile(filePath, encoder))) parsed++;
3518
3863
  if (parsed === 0) return;
3519
3864
  const outfile = ctx.runtime.path.join(...ctx.paths.root, "styles.css");
3520
3865
  const done = logger.time.info(ctx.messages.buildComplete(parsed));
@@ -3539,12 +3884,13 @@ async function generate(config, configPath) {
3539
3884
  ctx.project.reloadSourceFile(filePath);
3540
3885
  await bundleStyles(ctx, [filePath, ...ctx.project.getDependents(filePath)]);
3541
3886
  } else if (event === "add") {
3887
+ const pendingClosure = ctx.project.getUnresolvedImporters().flatMap((importer) => [importer, ...ctx.project.getDependents(importer)]);
3542
3888
  ctx.project.createSourceFile(filePath);
3543
- await bundleStyles(ctx, [
3889
+ await bundleStyles(ctx, [...new Set([
3544
3890
  filePath,
3545
3891
  ...ctx.project.getDependents(filePath),
3546
- ...ctx.project.getUnresolvedImporters()
3547
- ]);
3892
+ ...pendingClosure
3893
+ ])]);
3548
3894
  }
3549
3895
  });
3550
3896
  }
@@ -3597,33 +3943,6 @@ const ensure = (outPath) => {
3597
3943
  //#endregion
3598
3944
  //#region src/vite-integration.ts
3599
3945
  /**
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
3946
  * Every extension Vite accepts for its config, so "is this a Vite project" is answered by the
3628
3947
  * same file Vite itself would load.
3629
3948
  *