balm-core 6.0.0-alpha.6 → 6.0.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -61,12 +61,15 @@ __export(index_exports, {
61
61
  VirtualFile: () => VirtualFile,
62
62
  ZipTask: () => ZipTask,
63
63
  balm: () => balm,
64
+ buildEsbuildOptions: () => buildEsbuildOptions,
64
65
  createDefaultConfig: () => createDefaultConfig,
65
66
  createDevServerApp: () => createDevServerApp,
67
+ createEsbuildRunner: () => createEsbuildRunner,
66
68
  createHistoryFallbackMiddleware: () => createHistoryFallbackMiddleware,
67
69
  deepMerge: () => deepMerge,
68
70
  default: () => index_default,
69
71
  file: () => file,
72
+ getNetworkAddresses: () => getNetworkAddresses,
70
73
  getWorkspaces: () => getWorkspaces,
71
74
  globalResolve: () => globalResolve,
72
75
  globalWorkspace: () => globalWorkspace,
@@ -81,6 +84,7 @@ __export(index_exports, {
81
84
  logger: () => logger,
82
85
  resolveConfig: () => resolveConfig,
83
86
  resolveDefaultEntry: () => resolveDefaultEntry,
87
+ resolveServerHost: () => resolveServerHost,
84
88
  rewriteCssAssetUrls: () => rewriteCssAssetUrls,
85
89
  rewriteHtmlAssetPaths: () => rewriteHtmlAssetPaths,
86
90
  runEsbuild: () => runEsbuild,
@@ -757,11 +761,18 @@ var CleanTask = class extends BaseTask {
757
761
  super({ name: "clean", description: "Clean output directories" });
758
762
  }
759
763
  async run(config) {
760
- const targets = [
761
- import_node_path5.default.join(config.workspace, config.roots.tmp),
762
- import_node_path5.default.join(config.workspace, config.roots.target)
763
- ];
764
- const deleted = await file.remove(targets);
764
+ const workspaceRoot = import_node_path5.default.resolve(config.workspace);
765
+ const activeDestBase = import_node_path5.default.resolve(
766
+ config.dest?.base || import_node_path5.default.join(
767
+ workspaceRoot,
768
+ config.env.isProd || !config.inFrontend ? config.roots.target : config.roots.tmp
769
+ )
770
+ );
771
+ if (activeDestBase === workspaceRoot || workspaceRoot.startsWith(`${activeDestBase}${import_node_path5.default.sep}`)) {
772
+ logger.warn("clean", `Skipping unsafe clean target: ${activeDestBase}`);
773
+ return;
774
+ }
775
+ const deleted = await file.remove([activeDestBase]);
765
776
  logger.info("clean", `Deleted ${deleted.length} directories`);
766
777
  }
767
778
  };
@@ -1573,13 +1584,13 @@ async function runRollup(config, customInputOptions = {}, customOutputOptions =
1573
1584
 
1574
1585
  // src/bundler/esbuild.ts
1575
1586
  var esbuild = __toESM(require("esbuild"), 1);
1576
- async function runEsbuild(config, customOptions = {}) {
1587
+ function buildEsbuildOptions(config, customOptions = {}) {
1577
1588
  const isProd = config.env.isProd;
1578
1589
  let entryPoints = customOptions.entryPoints || config.scripts.entry;
1579
1590
  if (!entryPoints) {
1580
1591
  entryPoints = [resolveDefaultEntry(config.src.js)];
1581
1592
  }
1582
- const defaultOptions = {
1593
+ return {
1583
1594
  entryPoints: Array.isArray(entryPoints) ? entryPoints : typeof entryPoints === "string" ? [entryPoints] : entryPoints,
1584
1595
  absWorkingDir: config.workspace,
1585
1596
  bundle: true,
@@ -1595,18 +1606,53 @@ async function runEsbuild(config, customOptions = {}) {
1595
1606
  ...config.scripts.esbuildOptions,
1596
1607
  ...customOptions
1597
1608
  };
1609
+ }
1610
+ async function runEsbuild(config, customOptions = {}) {
1611
+ const options = buildEsbuildOptions(config, customOptions);
1598
1612
  try {
1599
- return await esbuild.build(defaultOptions);
1613
+ return await esbuild.build(options);
1600
1614
  } catch (err) {
1601
1615
  logger.error("esbuild", err.message || err);
1602
1616
  throw err;
1603
1617
  }
1604
1618
  }
1619
+ async function createEsbuildRunner(config, customOptions = {}) {
1620
+ const options = buildEsbuildOptions(config, customOptions);
1621
+ const ctx = await esbuild.context(options);
1622
+ return {
1623
+ async rebuild() {
1624
+ try {
1625
+ return await ctx.rebuild();
1626
+ } catch (err) {
1627
+ logger.error("esbuild", err.message || err);
1628
+ throw err;
1629
+ }
1630
+ },
1631
+ async dispose() {
1632
+ await ctx.dispose();
1633
+ }
1634
+ };
1635
+ }
1605
1636
 
1606
1637
  // src/tasks/script.ts
1607
1638
  var ScriptTask = class extends BaseTask {
1608
- constructor() {
1639
+ incremental;
1640
+ esbuildRunner = null;
1641
+ esbuildConfigKey = null;
1642
+ constructor(options = {}) {
1609
1643
  super({ name: "script", description: "Bundle JavaScript/TypeScript" });
1644
+ this.incremental = Boolean(options.incremental);
1645
+ }
1646
+ getEsbuildConfigKey(config) {
1647
+ return JSON.stringify({
1648
+ workspace: config.workspace,
1649
+ outdir: config.dest.js,
1650
+ entry: config.scripts.entry,
1651
+ alias: config.alias,
1652
+ scriptAlias: config.scripts.alias,
1653
+ target: config.scripts.target,
1654
+ minify: config.env.isProd || config.scripts.minify
1655
+ });
1610
1656
  }
1611
1657
  async run(config) {
1612
1658
  const bundler = config.scripts.bundler;
@@ -1615,7 +1661,17 @@ var ScriptTask = class extends BaseTask {
1615
1661
  await runRollup(config);
1616
1662
  break;
1617
1663
  case "esbuild" /* esbuild */:
1618
- await runEsbuild(config);
1664
+ if (this.incremental && !config.env.isProd) {
1665
+ const nextKey = this.getEsbuildConfigKey(config);
1666
+ if (!this.esbuildRunner || this.esbuildConfigKey !== nextKey) {
1667
+ await this.dispose();
1668
+ this.esbuildRunner = await createEsbuildRunner(config);
1669
+ this.esbuildConfigKey = nextKey;
1670
+ }
1671
+ await this.esbuildRunner.rebuild();
1672
+ } else {
1673
+ await runEsbuild(config);
1674
+ }
1619
1675
  break;
1620
1676
  case "webpack" /* webpack */:
1621
1677
  default:
@@ -1623,6 +1679,14 @@ var ScriptTask = class extends BaseTask {
1623
1679
  break;
1624
1680
  }
1625
1681
  }
1682
+ async dispose() {
1683
+ if (this.esbuildRunner) {
1684
+ const runner = this.esbuildRunner;
1685
+ this.esbuildRunner = null;
1686
+ this.esbuildConfigKey = null;
1687
+ await runner.dispose();
1688
+ }
1689
+ }
1626
1690
  };
1627
1691
 
1628
1692
  // src/tasks/html.ts
@@ -1683,28 +1747,175 @@ var LIVE_RELOAD_SCRIPT = `
1683
1747
  <!-- BalmJS Live Reload -->
1684
1748
  <script>
1685
1749
  (() => {
1750
+ if (window.__BALM_LIVE_RELOAD__) return;
1751
+ window.__BALM_LIVE_RELOAD__ = true;
1752
+
1686
1753
  const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
1687
- const ws = new WebSocket(\`\${protocol}//\${location.host}/__balm_ws\`);
1688
- ws.onmessage = (e) => {
1754
+ const wsUrl = \`\${protocol}//\${location.host}/__balm_ws\`;
1755
+ let ws = null;
1756
+ let reconnectTimer = null;
1757
+ let syncTimeout = null;
1758
+ let retryDelay = 500;
1759
+ let serverId = null;
1760
+ let lastBuildVersion = null;
1761
+ let reloading = false;
1762
+
1763
+ const clearTimers = () => {
1764
+ if (reconnectTimer) {
1765
+ clearTimeout(reconnectTimer);
1766
+ reconnectTimer = null;
1767
+ }
1768
+ if (syncTimeout) {
1769
+ clearTimeout(syncTimeout);
1770
+ syncTimeout = null;
1771
+ }
1772
+ };
1773
+
1774
+ const triggerReload = (reason) => {
1775
+ if (reloading) return;
1776
+ reloading = true;
1777
+ clearTimers();
1778
+ console.log(\`[BalmJS] Reloading page (\${reason})...\`);
1779
+ location.reload();
1780
+ };
1781
+
1782
+ const reloadLocalStylesheets = () => {
1783
+ const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
1784
+ const stamp = Date.now().toString();
1785
+ for (const link of links) {
1786
+ if (!link.href || link.dataset.balmStale === '1') continue;
1787
+ let url;
1788
+ try {
1789
+ url = new URL(link.href, location.href);
1790
+ } catch {
1791
+ continue;
1792
+ }
1793
+ if (url.origin !== location.origin) continue;
1794
+ url.searchParams.set('_balm_t', stamp);
1795
+
1796
+ const next = link.cloneNode(false);
1797
+ next.href = url.href;
1798
+ link.dataset.balmStale = '1';
1799
+ const cleanupOld = () => {
1800
+ if (link.parentNode) link.parentNode.removeChild(link);
1801
+ };
1802
+ next.addEventListener('load', cleanupOld, { once: true });
1803
+ next.addEventListener('error', cleanupOld, { once: true });
1804
+ if (link.parentNode) {
1805
+ link.parentNode.insertBefore(next, link.nextSibling);
1806
+ }
1807
+ }
1808
+ };
1809
+
1810
+ const scheduleReconnect = () => {
1811
+ if (reconnectTimer || reloading) return;
1812
+ reconnectTimer = setTimeout(() => {
1813
+ reconnectTimer = null;
1814
+ connect();
1815
+ }, retryDelay);
1816
+ retryDelay = Math.min(retryDelay * 2, 3000);
1817
+ };
1818
+
1819
+ const connect = () => {
1820
+ if (reloading) return;
1821
+ if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
1822
+ return;
1823
+ }
1824
+
1689
1825
  try {
1690
- const msg = JSON.parse(e.data);
1691
- if (msg.type === 'reload') {
1692
- console.log('[BalmJS] Reloading page...');
1693
- location.reload();
1694
- } else if (msg.type === 'reload-css') {
1695
- console.log('[BalmJS] Reloading CSS...');
1696
- const links = document.querySelectorAll('link[rel="stylesheet"]');
1697
- for (const link of links) {
1698
- const url = new URL(link.href);
1699
- url.searchParams.set('_balm_t', Date.now().toString());
1700
- link.href = url.href;
1826
+ ws = new WebSocket(wsUrl);
1827
+ } catch {
1828
+ scheduleReconnect();
1829
+ return;
1830
+ }
1831
+
1832
+ ws.onopen = () => {
1833
+ retryDelay = 500;
1834
+ };
1835
+
1836
+ ws.onmessage = (e) => {
1837
+ try {
1838
+ const msg = JSON.parse(e.data);
1839
+ if (syncTimeout) {
1840
+ clearTimeout(syncTimeout);
1841
+ syncTimeout = null;
1842
+ }
1843
+ if (msg.type === 'connected') {
1844
+ if (serverId !== null && msg.serverId && msg.serverId !== serverId) {
1845
+ triggerReload('server restarted');
1846
+ return;
1847
+ }
1848
+ if (
1849
+ lastBuildVersion !== null &&
1850
+ typeof msg.buildVersion === 'number' &&
1851
+ msg.buildVersion > lastBuildVersion
1852
+ ) {
1853
+ triggerReload('missed rebuild');
1854
+ return;
1855
+ }
1856
+ if (msg.serverId) serverId = msg.serverId;
1857
+ if (typeof msg.buildVersion === 'number') lastBuildVersion = msg.buildVersion;
1858
+ } else if (msg.type === 'reload') {
1859
+ if (typeof msg.buildVersion === 'number') lastBuildVersion = msg.buildVersion;
1860
+ triggerReload('file changed');
1861
+ } else if (msg.type === 'reload-css') {
1862
+ if (typeof msg.buildVersion === 'number') lastBuildVersion = msg.buildVersion;
1863
+ console.log('[BalmJS] Reloading CSS...');
1864
+ reloadLocalStylesheets();
1701
1865
  }
1866
+ } catch {}
1867
+ };
1868
+
1869
+ ws.onerror = () => {
1870
+ try {
1871
+ ws?.close();
1872
+ } catch {}
1873
+ };
1874
+
1875
+ ws.onclose = () => {
1876
+ ws = null;
1877
+ if (syncTimeout) {
1878
+ clearTimeout(syncTimeout);
1879
+ syncTimeout = null;
1702
1880
  }
1703
- } catch {}
1881
+ scheduleReconnect();
1882
+ };
1704
1883
  };
1705
- ws.onclose = () => {
1706
- setTimeout(() => location.reload(), 2000);
1884
+
1885
+ const syncOrReconnect = () => {
1886
+ if (reloading) return;
1887
+ retryDelay = 500;
1888
+ if (reconnectTimer) {
1889
+ clearTimeout(reconnectTimer);
1890
+ reconnectTimer = null;
1891
+ }
1892
+ if (ws && ws.readyState === WebSocket.OPEN) {
1893
+ try {
1894
+ ws.send(JSON.stringify({ type: 'sync' }));
1895
+ if (syncTimeout) clearTimeout(syncTimeout);
1896
+ syncTimeout = setTimeout(() => {
1897
+ syncTimeout = null;
1898
+ try {
1899
+ ws?.close();
1900
+ } catch {}
1901
+ ws = null;
1902
+ connect();
1903
+ }, 1500);
1904
+ return;
1905
+ } catch {}
1906
+ }
1907
+ connect();
1707
1908
  };
1909
+
1910
+ document.addEventListener('visibilitychange', () => {
1911
+ if (document.visibilityState === 'visible') {
1912
+ syncOrReconnect();
1913
+ }
1914
+ });
1915
+
1916
+ window.addEventListener('online', syncOrReconnect);
1917
+
1918
+ connect();
1708
1919
  })();
1709
1920
  </script>
1710
1921
  `;
@@ -2425,83 +2636,361 @@ var FtpTask = class extends BaseTask {
2425
2636
 
2426
2637
  // src/tasks/server.ts
2427
2638
  var import_node_http = __toESM(require("http"), 1);
2428
- var import_node_fs8 = __toESM(require("fs"), 1);
2429
- var import_node_path24 = __toESM(require("path"), 1);
2639
+ var import_node_crypto2 = __toESM(require("crypto"), 1);
2640
+ var import_node_fs9 = __toESM(require("fs"), 1);
2641
+ var import_node_os = __toESM(require("os"), 1);
2642
+ var import_node_path25 = __toESM(require("path"), 1);
2430
2643
  var import_connect = __toESM(require("connect"), 1);
2431
2644
  var import_serve_static = __toESM(require("serve-static"), 1);
2432
2645
  var import_ws = require("ws");
2433
2646
  var import_http_proxy_middleware = require("http-proxy-middleware");
2434
2647
 
2435
2648
  // src/watcher/index.ts
2436
- var import_node_fs7 = __toESM(require("fs"), 1);
2649
+ var import_node_fs8 = __toESM(require("fs"), 1);
2650
+ var import_node_path24 = __toESM(require("path"), 1);
2651
+
2652
+ // src/tasks/static.ts
2437
2653
  var import_node_path23 = __toESM(require("path"), 1);
2654
+ var import_node_fs7 = require("fs");
2655
+ var StaticTask = class extends BaseTask {
2656
+ constructor() {
2657
+ super({ name: "static", description: "Copy static assets, images, fonts, and manifest" });
2658
+ }
2659
+ async run(config) {
2660
+ const srcBase = config.src.base;
2661
+ const destBase = config.dest.base;
2662
+ const staticPatterns = [
2663
+ import_node_path23.default.join(srcBase, "*.{ico,png,svg,json,txt,xml,webmanifest}"),
2664
+ `!${import_node_path23.default.join(srcBase, "*.html")}`
2665
+ ];
2666
+ const extraIncludes = [
2667
+ ...config.extras?.includes || [],
2668
+ ...config.assets?.includes || []
2669
+ ];
2670
+ const extraExcludes = [
2671
+ ...config.extras?.excludes || [],
2672
+ ...config.assets?.excludes || []
2673
+ ];
2674
+ for (const inc of extraIncludes) {
2675
+ const pattern = import_node_path23.default.isAbsolute(inc) ? inc : import_node_path23.default.join(srcBase, inc);
2676
+ staticPatterns.push(pattern);
2677
+ }
2678
+ for (const exc of extraExcludes) {
2679
+ const pattern = import_node_path23.default.isAbsolute(exc) ? exc : import_node_path23.default.join(srcBase, exc);
2680
+ staticPatterns.push(`!${pattern}`);
2681
+ }
2682
+ const pipeline = Pipeline.from(staticPatterns, {
2683
+ cwd: config.workspace,
2684
+ base: srcBase
2685
+ });
2686
+ const publicUrlReplacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
2687
+ pipeline.pipe(async (file2) => {
2688
+ const isManifest = isManifestFile(file2, config);
2689
+ if (isManifest || file2.extname === ".json") {
2690
+ let content = file2.toString();
2691
+ content = content.replaceAll(PUBLIC_URL, publicUrlReplacement);
2692
+ if (isManifest) {
2693
+ content = rewriteHtmlAssetPaths(content, config);
2694
+ }
2695
+ file2.contents = Buffer.from(content);
2696
+ }
2697
+ return file2;
2698
+ });
2699
+ await pipeline.dest(destBase);
2700
+ if (config.src.img && (0, import_node_fs7.existsSync)(config.src.img)) {
2701
+ const imgPipeline = Pipeline.from(import_node_path23.default.join(config.src.img, "**/*"), {
2702
+ cwd: config.workspace,
2703
+ base: config.src.img
2704
+ });
2705
+ await imgPipeline.dest(config.dest.img);
2706
+ }
2707
+ if (config.src.font && (0, import_node_fs7.existsSync)(config.src.font)) {
2708
+ const fontPipeline = Pipeline.from(import_node_path23.default.join(config.src.font, "**/*"), {
2709
+ cwd: config.workspace,
2710
+ base: config.src.font
2711
+ });
2712
+ await fontPipeline.dest(config.dest.font);
2713
+ }
2714
+ if (config.src.media && (0, import_node_fs7.existsSync)(config.src.media)) {
2715
+ const mediaPipeline = Pipeline.from(import_node_path23.default.join(config.src.media, "**/*"), {
2716
+ cwd: config.workspace,
2717
+ base: config.src.media
2718
+ });
2719
+ await mediaPipeline.dest(config.dest.media);
2720
+ }
2721
+ const publicDir = import_node_path23.default.join(config.workspace, "public");
2722
+ if ((0, import_node_fs7.existsSync)(publicDir)) {
2723
+ const pubPipeline = Pipeline.from(import_node_path23.default.join(publicDir, "**/*"), {
2724
+ cwd: config.workspace,
2725
+ base: publicDir
2726
+ });
2727
+ await pubPipeline.dest(destBase);
2728
+ }
2729
+ }
2730
+ };
2731
+
2732
+ // src/watcher/index.ts
2438
2733
  var import_picocolors3 = __toESM(require("picocolors"), 1);
2734
+ var IGNORED_BASENAMES = /* @__PURE__ */ new Set([".DS_Store", "Thumbs.db", "4913"]);
2735
+ var CONFIG_FILENAMES = [
2736
+ "balm.config.js",
2737
+ "balm.config.mjs",
2738
+ "balm.config.cjs",
2739
+ "balm.config.ts"
2740
+ ];
2741
+ function isSubPath(targetPath, parentDir) {
2742
+ const normalizedTarget = import_node_path24.default.resolve(targetPath);
2743
+ const normalizedParent = import_node_path24.default.resolve(parentDir);
2744
+ return normalizedTarget === normalizedParent || normalizedTarget.startsWith(`${normalizedParent}${import_node_path24.default.sep}`);
2745
+ }
2746
+ function isIgnoredWatchFile(filePath, excludedDirs = []) {
2747
+ if (!filePath) return true;
2748
+ const normalized = filePath.replace(/\\/g, "/");
2749
+ if (normalized.includes("/node_modules/") || normalized.startsWith("node_modules/") || normalized.includes("/.git/") || normalized.startsWith(".git/")) {
2750
+ return true;
2751
+ }
2752
+ const base = import_node_path24.default.basename(normalized);
2753
+ if (IGNORED_BASENAMES.has(base) || base.startsWith(".#") || base.startsWith("#") || base.startsWith(".~") || /(\.(swp|swo|swx|tmp|bak)|~)$/i.test(base)) {
2754
+ return true;
2755
+ }
2756
+ if (import_node_path24.default.isAbsolute(filePath)) {
2757
+ for (const dir of excludedDirs) {
2758
+ if (dir && isSubPath(filePath, dir)) {
2759
+ return true;
2760
+ }
2761
+ }
2762
+ }
2763
+ return false;
2764
+ }
2439
2765
  var FileWatcher = class {
2440
2766
  config;
2441
2767
  broadcast;
2442
2768
  debounceTimer = null;
2769
+ configWarnTimer = null;
2443
2770
  pendingFiles = /* @__PURE__ */ new Set();
2444
2771
  styleTask;
2445
2772
  scriptTask;
2446
2773
  htmlTask;
2774
+ staticTask;
2447
2775
  watchers = [];
2448
2776
  isRebuilding = false;
2777
+ needsRebuild = false;
2778
+ recoveryPromise = null;
2449
2779
  constructor(config, broadcast) {
2450
2780
  this.config = config;
2451
2781
  this.broadcast = broadcast;
2452
2782
  this.styleTask = new StyleTask();
2453
- this.scriptTask = new ScriptTask();
2783
+ this.scriptTask = new ScriptTask({ incremental: true });
2454
2784
  this.htmlTask = new HtmlTask();
2785
+ this.staticTask = new StaticTask();
2786
+ }
2787
+ getExcludedOutputDirs() {
2788
+ const workspaceRoot = import_node_path24.default.resolve(this.config.workspace);
2789
+ const candidates = [
2790
+ this.config.dest?.base,
2791
+ this.config.roots?.tmp ? import_node_path24.default.join(workspaceRoot, this.config.roots.tmp) : "",
2792
+ this.config.roots?.target ? import_node_path24.default.join(workspaceRoot, this.config.roots.target) : ""
2793
+ ].filter((dir) => Boolean(dir));
2794
+ return Array.from(
2795
+ new Set(
2796
+ candidates.map((dir) => import_node_path24.default.resolve(dir)).filter((dir) => dir !== workspaceRoot)
2797
+ )
2798
+ );
2799
+ }
2800
+ resolveAliasWatchDirs(excludedDirs) {
2801
+ const workspaceRoot = import_node_path24.default.resolve(this.config.workspace);
2802
+ const mergedAliases = {
2803
+ ...this.config.alias,
2804
+ ...this.config.scripts?.alias,
2805
+ ...this.config.styles?.alias
2806
+ };
2807
+ const dirs = [];
2808
+ for (const target of Object.values(mergedAliases)) {
2809
+ if (typeof target !== "string" || !target.trim()) continue;
2810
+ const resolved = import_node_path24.default.isAbsolute(target) ? import_node_path24.default.resolve(target) : import_node_path24.default.resolve(workspaceRoot, target);
2811
+ if (resolved.includes(`${import_node_path24.default.sep}node_modules`)) continue;
2812
+ if (!import_node_fs8.default.existsSync(resolved)) continue;
2813
+ try {
2814
+ const stat = import_node_fs8.default.statSync(resolved);
2815
+ const watchDir = stat.isDirectory() ? resolved : import_node_path24.default.dirname(resolved);
2816
+ if (watchDir === workspaceRoot || watchDir.includes(`${import_node_path24.default.sep}node_modules`) || excludedDirs.some((excluded) => isSubPath(watchDir, excluded))) {
2817
+ continue;
2818
+ }
2819
+ dirs.push(watchDir);
2820
+ } catch {
2821
+ }
2822
+ }
2823
+ return dirs;
2455
2824
  }
2456
2825
  getWatchDirs() {
2826
+ const workspaceRoot = import_node_path24.default.resolve(this.config.workspace);
2827
+ const excludedDirs = this.getExcludedOutputDirs();
2828
+ const publicDir = import_node_path24.default.join(workspaceRoot, "public");
2829
+ const customTemplate = this.config.scripts?.htmlPluginOptions?.template;
2830
+ const customTemplateDir = typeof customTemplate === "string" && customTemplate.trim() ? import_node_path24.default.dirname(import_node_path24.default.resolve(workspaceRoot, customTemplate)) : "";
2457
2831
  const candidates = [
2458
2832
  this.config.src.base,
2833
+ publicDir,
2834
+ customTemplateDir,
2459
2835
  ...this.config.scripts.includeJsResource || [],
2460
- ...this.config.styles.atImportPaths || []
2836
+ ...this.config.styles.atImportPaths || [],
2837
+ ...this.resolveAliasWatchDirs(excludedDirs)
2461
2838
  ];
2462
- const resolved = candidates.filter(Boolean).map((dir) => import_node_path23.default.isAbsolute(dir) ? dir : import_node_path23.default.resolve(this.config.workspace, dir)).filter((dir) => import_node_fs7.default.existsSync(dir) && !dir.includes(`${import_node_path23.default.sep}node_modules`));
2839
+ const resolved = candidates.filter(Boolean).map(
2840
+ (dir) => import_node_path24.default.isAbsolute(dir) ? import_node_path24.default.resolve(dir) : import_node_path24.default.resolve(workspaceRoot, dir)
2841
+ ).filter((dir) => {
2842
+ if (dir.includes(`${import_node_path24.default.sep}node_modules`)) return false;
2843
+ if (excludedDirs.some((excluded) => isSubPath(dir, excluded))) return false;
2844
+ try {
2845
+ return import_node_fs8.default.existsSync(dir) && import_node_fs8.default.statSync(dir).isDirectory();
2846
+ } catch {
2847
+ return false;
2848
+ }
2849
+ });
2463
2850
  const unique = Array.from(new Set(resolved)).sort((a, b) => a.length - b.length);
2464
2851
  return unique.filter(
2465
- (dir, index) => !unique.slice(0, index).some((parent) => dir.startsWith(`${parent}${import_node_path23.default.sep}`))
2852
+ (dir, index) => !unique.slice(0, index).some((parent) => dir.startsWith(`${parent}${import_node_path24.default.sep}`))
2466
2853
  );
2467
2854
  }
2855
+ watchConfigFile() {
2856
+ const workspaceRoot = import_node_path24.default.resolve(this.config.workspace);
2857
+ for (const name of CONFIG_FILENAMES) {
2858
+ const configPath = import_node_path24.default.join(workspaceRoot, name);
2859
+ if (!import_node_fs8.default.existsSync(configPath)) continue;
2860
+ try {
2861
+ const watcher = import_node_fs8.default.watch(configPath, () => {
2862
+ if (this.configWarnTimer) clearTimeout(this.configWarnTimer);
2863
+ this.configWarnTimer = setTimeout(() => {
2864
+ logger.warn(
2865
+ "watch",
2866
+ `${import_picocolors3.default.yellow(name)} changed \u2014 restart dev server to apply config updates`
2867
+ );
2868
+ }, 200);
2869
+ });
2870
+ watcher.on("error", (err) => {
2871
+ logger.warn("watch", `Config watcher error for ${name}: ${err.message}`);
2872
+ });
2873
+ this.watchers.push(watcher);
2874
+ } catch {
2875
+ }
2876
+ break;
2877
+ }
2878
+ }
2468
2879
  start() {
2469
2880
  const watchDirs = this.getWatchDirs();
2470
- if (!watchDirs.length) return;
2881
+ const excludedDirs = this.getExcludedOutputDirs();
2471
2882
  for (const watchDir of watchDirs) {
2472
2883
  logger.info("watch", `Watching for file changes in ${import_picocolors3.default.cyan(watchDir)}`);
2473
2884
  try {
2474
- const watcher = import_node_fs7.default.watch(watchDir, { recursive: true }, (_eventType, filename) => {
2885
+ const watcher = import_node_fs8.default.watch(watchDir, { recursive: true }, (_eventType, filename) => {
2475
2886
  if (!filename) return;
2476
- const normalized = filename.replace(/\\/g, "/");
2477
- if (normalized.includes("node_modules/") || normalized.startsWith(".git/")) {
2887
+ const fullPath = import_node_path24.default.join(watchDir, filename.toString());
2888
+ if (isIgnoredWatchFile(fullPath, excludedDirs)) {
2478
2889
  return;
2479
2890
  }
2480
- this.pendingFiles.add(filename);
2891
+ this.pendingFiles.add(fullPath);
2481
2892
  if (this.debounceTimer) clearTimeout(this.debounceTimer);
2482
2893
  this.debounceTimer = setTimeout(() => {
2483
- this.handleChanges();
2894
+ void this.handleChanges();
2484
2895
  }, 50);
2485
2896
  });
2897
+ watcher.on("error", (err) => {
2898
+ logger.warn("watch", `Watcher error for ${watchDir}: ${err.message}`);
2899
+ });
2486
2900
  this.watchers.push(watcher);
2487
2901
  } catch (err) {
2488
2902
  logger.warn("watch", `Native recursive watch failed for ${watchDir}: ${err.message}`);
2489
2903
  }
2490
2904
  }
2905
+ this.watchConfigFile();
2906
+ }
2907
+ async rebuildAll() {
2908
+ if (this.recoveryPromise) {
2909
+ return this.recoveryPromise;
2910
+ }
2911
+ this.recoveryPromise = (async () => {
2912
+ this.isRebuilding = true;
2913
+ try {
2914
+ const start = performance.now();
2915
+ await this.styleTask.run(this.config);
2916
+ await this.scriptTask.run(this.config);
2917
+ await this.staticTask.run(this.config);
2918
+ await this.htmlTask.run(this.config);
2919
+ const duration = (performance.now() - start).toFixed(1);
2920
+ logger.info("watch", `Recovered dev workspace in ${import_picocolors3.default.bold(duration + "ms")}`);
2921
+ } finally {
2922
+ this.isRebuilding = false;
2923
+ }
2924
+ })();
2925
+ try {
2926
+ await this.recoveryPromise;
2927
+ } finally {
2928
+ this.recoveryPromise = null;
2929
+ }
2930
+ }
2931
+ classifyChanges(changed) {
2932
+ const publicDir = import_node_path24.default.resolve(this.config.workspace, "public");
2933
+ const staticAssetDirs = [
2934
+ this.config.src.img,
2935
+ this.config.src.font,
2936
+ this.config.src.media
2937
+ ].filter(Boolean).map((dir) => import_node_path24.default.resolve(dir));
2938
+ const manifestBasename = import_node_path24.default.basename(this.config.pwa?.manifest || "manifest.json");
2939
+ let hasStyle = false;
2940
+ let hasScript = false;
2941
+ let hasHtml = false;
2942
+ let hasStatic = false;
2943
+ let hasOther = false;
2944
+ for (const filePath of changed) {
2945
+ const isAbs = import_node_path24.default.isAbsolute(filePath);
2946
+ const base = import_node_path24.default.basename(filePath);
2947
+ if (isAbs && isSubPath(filePath, publicDir)) {
2948
+ hasStatic = true;
2949
+ continue;
2950
+ }
2951
+ if (isAbs && staticAssetDirs.some((dir) => isSubPath(filePath, dir))) {
2952
+ hasStatic = true;
2953
+ continue;
2954
+ }
2955
+ if (base === manifestBasename || /\.webmanifest$/i.test(base)) {
2956
+ hasStatic = true;
2957
+ hasHtml = true;
2958
+ continue;
2959
+ }
2960
+ if (/\.html?$/i.test(base)) {
2961
+ hasHtml = true;
2962
+ continue;
2963
+ }
2964
+ if (/\.(scss|sass|less|css)$/i.test(base)) {
2965
+ hasStyle = true;
2966
+ continue;
2967
+ }
2968
+ if (/\.(js|mjs|cjs|ts|jsx|tsx|vue|md|json)$/i.test(base)) {
2969
+ hasScript = true;
2970
+ continue;
2971
+ }
2972
+ if (/\.(ico|png|jpe?g|gif|webp|avif|svg|txt|xml|woff2?|ttf|eot|otf|mp4|webm|mp3|ogg|wav)$/i.test(
2973
+ base
2974
+ )) {
2975
+ hasStatic = true;
2976
+ continue;
2977
+ }
2978
+ hasOther = true;
2979
+ }
2980
+ return { hasStyle, hasScript, hasHtml, hasStatic, hasOther };
2491
2981
  }
2492
2982
  async handleChanges() {
2493
2983
  if (this.isRebuilding) {
2494
- this.debounceTimer = setTimeout(() => this.handleChanges(), 50);
2984
+ this.needsRebuild = true;
2495
2985
  return;
2496
2986
  }
2497
- const changed = Array.from(this.pendingFiles);
2987
+ const excludedDirs = this.getExcludedOutputDirs();
2988
+ const changed = Array.from(this.pendingFiles).filter(
2989
+ (f) => !isIgnoredWatchFile(f, excludedDirs)
2990
+ );
2498
2991
  this.pendingFiles.clear();
2499
2992
  if (!changed.length) return;
2500
- const hasStyle = changed.some((f) => /\.(scss|sass|less|css)$/i.test(f));
2501
- const hasScript = changed.some(
2502
- (f) => /\.(js|mjs|cjs|ts|jsx|tsx|vue|md|json)$/i.test(f)
2503
- );
2504
- const hasHtml = changed.some((f) => /\.html$/i.test(f));
2993
+ const { hasStyle, hasScript, hasHtml, hasStatic, hasOther } = this.classifyChanges(changed);
2505
2994
  this.isRebuilding = true;
2506
2995
  try {
2507
2996
  if (hasStyle) {
@@ -2509,29 +2998,40 @@ var FileWatcher = class {
2509
2998
  await this.styleTask.run(this.config);
2510
2999
  const duration = (performance.now() - start).toFixed(1);
2511
3000
  logger.info("watch", `Recompiled styles in ${import_picocolors3.default.bold(duration + "ms")}`);
2512
- this.broadcast({ type: "reload-css" });
2513
3001
  }
2514
3002
  if (hasScript) {
2515
3003
  const start = performance.now();
2516
3004
  await this.scriptTask.run(this.config);
2517
3005
  const duration = (performance.now() - start).toFixed(1);
2518
3006
  logger.info("watch", `Rebundled scripts in ${import_picocolors3.default.bold(duration + "ms")}`);
2519
- this.broadcast({ type: "reload" });
3007
+ }
3008
+ if (hasStatic) {
3009
+ const start = performance.now();
3010
+ await this.staticTask.run(this.config);
3011
+ const duration = (performance.now() - start).toFixed(1);
3012
+ logger.info("watch", `Synced static assets in ${import_picocolors3.default.bold(duration + "ms")}`);
2520
3013
  }
2521
3014
  if (hasHtml) {
2522
3015
  const start = performance.now();
2523
3016
  await this.htmlTask.run(this.config);
2524
3017
  const duration = (performance.now() - start).toFixed(1);
2525
3018
  logger.info("watch", `Recompiled HTML in ${import_picocolors3.default.bold(duration + "ms")}`);
2526
- this.broadcast({ type: "reload" });
2527
3019
  }
2528
- if (!hasStyle && !hasScript && !hasHtml && changed.length > 0) {
3020
+ if (hasScript || hasHtml || hasStatic || hasOther) {
2529
3021
  this.broadcast({ type: "reload" });
3022
+ } else if (hasStyle) {
3023
+ this.broadcast({ type: "reload-css" });
2530
3024
  }
2531
3025
  } catch (err) {
2532
3026
  logger.error("watch", `Incremental rebuild failed: ${err?.message || err}`);
2533
3027
  } finally {
2534
3028
  this.isRebuilding = false;
3029
+ if (this.needsRebuild || this.pendingFiles.size > 0) {
3030
+ this.needsRebuild = false;
3031
+ this.debounceTimer = setTimeout(() => {
3032
+ void this.handleChanges();
3033
+ }, 50);
3034
+ }
2535
3035
  }
2536
3036
  }
2537
3037
  stop() {
@@ -2539,25 +3039,35 @@ var FileWatcher = class {
2539
3039
  clearTimeout(this.debounceTimer);
2540
3040
  this.debounceTimer = null;
2541
3041
  }
3042
+ if (this.configWarnTimer) {
3043
+ clearTimeout(this.configWarnTimer);
3044
+ this.configWarnTimer = null;
3045
+ }
2542
3046
  for (const watcher of this.watchers) {
2543
3047
  watcher.close();
2544
3048
  }
2545
3049
  this.watchers = [];
3050
+ void this.scriptTask.dispose();
2546
3051
  }
2547
3052
  };
2548
3053
 
2549
3054
  // src/tasks/server.ts
2550
3055
  var import_picocolors4 = __toESM(require("picocolors"), 1);
3056
+ var DEV_STATIC_OPTIONS = {
3057
+ etag: false,
3058
+ lastModified: false,
3059
+ cacheControl: false
3060
+ };
2551
3061
  function resolveServedFile(config, targetPath) {
2552
3062
  const normalizedTarget = targetPath.split("?")[0].replace(/^\/+/, "");
2553
3063
  const candidates = [
2554
- import_node_path24.default.join(config.dest.html, normalizedTarget),
2555
- import_node_path24.default.join(config.dest.base, normalizedTarget),
2556
- import_node_path24.default.join(config.src.base, normalizedTarget)
3064
+ import_node_path25.default.join(config.dest.html, normalizedTarget),
3065
+ import_node_path25.default.join(config.dest.base, normalizedTarget),
3066
+ import_node_path25.default.join(config.src.base, normalizedTarget)
2557
3067
  ];
2558
3068
  return candidates.find((filePath) => {
2559
3069
  try {
2560
- return import_node_fs8.default.existsSync(filePath) && import_node_fs8.default.statSync(filePath).isFile();
3070
+ return import_node_fs9.default.existsSync(filePath) && import_node_fs9.default.statSync(filePath).isFile();
2561
3071
  } catch {
2562
3072
  return false;
2563
3073
  }
@@ -2610,14 +3120,34 @@ function createHistoryFallbackMiddleware(config) {
2610
3120
  if (req.method === "HEAD") {
2611
3121
  return res.end();
2612
3122
  }
2613
- return import_node_fs8.default.createReadStream(fileToServe).pipe(res);
3123
+ return import_node_fs9.default.createReadStream(fileToServe).pipe(res);
2614
3124
  }
2615
3125
  req.url = rewriteTarget;
2616
3126
  return next();
2617
3127
  };
2618
3128
  }
2619
- function createDevServerApp(config) {
3129
+ function createDevServerApp(config, options = {}) {
2620
3130
  const app = (0, import_connect.default)();
3131
+ app.use((_req, res, next) => {
3132
+ res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
3133
+ res.setHeader("Pragma", "no-cache");
3134
+ res.setHeader("Expires", "0");
3135
+ next();
3136
+ });
3137
+ if (options.ensureBuildReady) {
3138
+ app.use((_req, _res, next) => {
3139
+ try {
3140
+ const result = options.ensureBuildReady();
3141
+ if (result && typeof result.then === "function") {
3142
+ result.then(() => next()).catch((err) => next(err));
3143
+ } else {
3144
+ next();
3145
+ }
3146
+ } catch (err) {
3147
+ next(err);
3148
+ }
3149
+ });
3150
+ }
2621
3151
  app.use((req, _res, next) => {
2622
3152
  if (req.url?.includes("%PUBLIC_URL%")) {
2623
3153
  req.url = req.url.replace("/%PUBLIC_URL%", "").replace("%PUBLIC_URL%", "") || "/";
@@ -2627,13 +3157,13 @@ function createDevServerApp(config) {
2627
3157
  app.use((req, res, next) => {
2628
3158
  if (req.url === "/manifest.json" || req.url?.endsWith("/manifest.json")) {
2629
3159
  const candidates = [
2630
- import_node_path24.default.join(config.dest.base, "manifest.json"),
2631
- import_node_path24.default.join(config.src.base, "manifest.json"),
2632
- import_node_path24.default.join(config.workspace, "manifest.json")
3160
+ import_node_path25.default.join(config.dest.base, "manifest.json"),
3161
+ import_node_path25.default.join(config.src.base, "manifest.json"),
3162
+ import_node_path25.default.join(config.workspace, "manifest.json")
2633
3163
  ];
2634
- const file2 = candidates.find((f) => import_node_fs8.default.existsSync(f));
3164
+ const file2 = candidates.find((f) => import_node_fs9.default.existsSync(f));
2635
3165
  if (file2) {
2636
- let content = import_node_fs8.default.readFileSync(file2, "utf-8");
3166
+ let content = import_node_fs9.default.readFileSync(file2, "utf-8");
2637
3167
  const replacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
2638
3168
  content = content.replaceAll("%PUBLIC_URL%", replacement);
2639
3169
  res.setHeader("Content-Type", "application/json; charset=utf-8");
@@ -2656,203 +3186,242 @@ function createDevServerApp(config) {
2656
3186
  app.use(createHistoryFallbackMiddleware(config));
2657
3187
  }
2658
3188
  if (config.paths.source.css) {
2659
- app.use("/" + config.paths.source.css, (0, import_serve_static.default)(config.dest.css));
3189
+ app.use("/" + config.paths.source.css, (0, import_serve_static.default)(config.dest.css, DEV_STATIC_OPTIONS));
2660
3190
  }
2661
3191
  if (config.paths.tmp.css && config.paths.tmp.css !== config.paths.source.css) {
2662
- app.use("/" + config.paths.tmp.css, (0, import_serve_static.default)(config.dest.css));
3192
+ app.use("/" + config.paths.tmp.css, (0, import_serve_static.default)(config.dest.css, DEV_STATIC_OPTIONS));
2663
3193
  }
2664
3194
  if (config.paths.source.js) {
2665
- app.use("/" + config.paths.source.js, (0, import_serve_static.default)(config.dest.js));
3195
+ app.use("/" + config.paths.source.js, (0, import_serve_static.default)(config.dest.js, DEV_STATIC_OPTIONS));
2666
3196
  }
2667
3197
  if (config.paths.tmp.js && config.paths.tmp.js !== config.paths.source.js) {
2668
- app.use("/" + config.paths.tmp.js, (0, import_serve_static.default)(config.dest.js));
3198
+ app.use("/" + config.paths.tmp.js, (0, import_serve_static.default)(config.dest.js, DEV_STATIC_OPTIONS));
2669
3199
  }
2670
- app.use("/chunk", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "chunk")));
2671
- app.use("/chunk", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "chunk")));
3200
+ app.use("/chunk", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.js, "chunk"), DEV_STATIC_OPTIONS));
3201
+ app.use("/chunk", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.base, "chunk"), DEV_STATIC_OPTIONS));
2672
3202
  if (config.paths.source.img) {
2673
3203
  app.use(
2674
3204
  "/" + config.paths.source.img,
2675
- (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, config.paths.source.img))
3205
+ (0, import_serve_static.default)(import_node_path25.default.join(config.src.base, config.paths.source.img), DEV_STATIC_OPTIONS)
2676
3206
  );
2677
3207
  }
2678
3208
  if (config.paths.tmp.img) {
2679
- app.use("/" + config.paths.tmp.img, (0, import_serve_static.default)(config.dest.img));
3209
+ app.use("/" + config.paths.tmp.img, (0, import_serve_static.default)(config.dest.img, DEV_STATIC_OPTIONS));
2680
3210
  }
2681
- app.use("/img", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "img")));
2682
- app.use("/img", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "img")));
3211
+ app.use("/img", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.base, "img"), DEV_STATIC_OPTIONS));
3212
+ app.use("/img", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.js, "img"), DEV_STATIC_OPTIONS));
2683
3213
  if (config.paths.source.font) {
2684
3214
  app.use(
2685
3215
  "/" + config.paths.source.font,
2686
- (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, config.paths.source.font))
3216
+ (0, import_serve_static.default)(import_node_path25.default.join(config.src.base, config.paths.source.font), DEV_STATIC_OPTIONS)
2687
3217
  );
2688
3218
  }
2689
3219
  if (config.paths.tmp.font) {
2690
- app.use("/" + config.paths.tmp.font, (0, import_serve_static.default)(config.dest.font));
3220
+ app.use("/" + config.paths.tmp.font, (0, import_serve_static.default)(config.dest.font, DEV_STATIC_OPTIONS));
2691
3221
  }
2692
- app.use("/font", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "font")));
2693
- app.use("/font", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.js, "font")));
2694
- app.use("/fonts", (0, import_serve_static.default)(import_node_path24.default.join(config.src.base, "fonts")));
2695
- app.use("/fonts", (0, import_serve_static.default)(import_node_path24.default.join(config.dest.base, "fonts")));
3222
+ app.use("/font", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.base, "font"), DEV_STATIC_OPTIONS));
3223
+ app.use("/font", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.js, "font"), DEV_STATIC_OPTIONS));
3224
+ app.use("/fonts", (0, import_serve_static.default)(import_node_path25.default.join(config.src.base, "fonts"), DEV_STATIC_OPTIONS));
3225
+ app.use("/fonts", (0, import_serve_static.default)(import_node_path25.default.join(config.dest.base, "fonts"), DEV_STATIC_OPTIONS));
2696
3226
  if (config.server.serveStatic) {
2697
3227
  const staticEntries = Array.isArray(config.server.serveStatic) ? config.server.serveStatic : [config.server.serveStatic];
2698
3228
  for (const entry of staticEntries) {
2699
3229
  if (typeof entry === "string") {
2700
- const absoluteDir = import_node_path24.default.isAbsolute(entry) ? entry : import_node_path24.default.join(config.workspace, entry);
2701
- if (import_node_fs8.default.existsSync(absoluteDir)) {
2702
- app.use((0, import_serve_static.default)(absoluteDir));
3230
+ const absoluteDir = import_node_path25.default.isAbsolute(entry) ? entry : import_node_path25.default.join(config.workspace, entry);
3231
+ if (import_node_fs9.default.existsSync(absoluteDir)) {
3232
+ app.use((0, import_serve_static.default)(absoluteDir, DEV_STATIC_OPTIONS));
2703
3233
  }
2704
3234
  } else if (entry && typeof entry === "object") {
2705
3235
  const route = entry.route ? entry.route.startsWith("/") ? entry.route : `/${entry.route}` : "";
2706
3236
  const dirs = Array.isArray(entry.dir) ? entry.dir : [entry.dir];
2707
3237
  for (const dir of dirs) {
2708
- const absoluteDir = import_node_path24.default.isAbsolute(dir) ? dir : import_node_path24.default.join(config.workspace, dir);
2709
- if (import_node_fs8.default.existsSync(absoluteDir)) {
3238
+ const absoluteDir = import_node_path25.default.isAbsolute(dir) ? dir : import_node_path25.default.join(config.workspace, dir);
3239
+ if (import_node_fs9.default.existsSync(absoluteDir)) {
2710
3240
  if (route) {
2711
- app.use(route, (0, import_serve_static.default)(absoluteDir));
3241
+ app.use(route, (0, import_serve_static.default)(absoluteDir, DEV_STATIC_OPTIONS));
2712
3242
  } else {
2713
- app.use((0, import_serve_static.default)(absoluteDir));
3243
+ app.use((0, import_serve_static.default)(absoluteDir, DEV_STATIC_OPTIONS));
2714
3244
  }
2715
3245
  }
2716
3246
  }
2717
3247
  }
2718
3248
  }
2719
3249
  }
2720
- app.use((0, import_serve_static.default)(config.dest.base));
2721
- app.use((0, import_serve_static.default)(config.src.base));
2722
- app.use((0, import_serve_static.default)(config.workspace));
3250
+ app.use((0, import_serve_static.default)(config.dest.base, DEV_STATIC_OPTIONS));
3251
+ app.use((0, import_serve_static.default)(config.src.base, DEV_STATIC_OPTIONS));
3252
+ app.use((0, import_serve_static.default)(config.workspace, DEV_STATIC_OPTIONS));
2723
3253
  return app;
2724
3254
  }
3255
+ function getNetworkAddresses() {
3256
+ const addresses = [];
3257
+ const interfaces = import_node_os.default.networkInterfaces();
3258
+ for (const entries of Object.values(interfaces)) {
3259
+ for (const net of entries || []) {
3260
+ if (net.family === "IPv4" && !net.internal) {
3261
+ addresses.push(net.address);
3262
+ }
3263
+ }
3264
+ }
3265
+ return addresses;
3266
+ }
3267
+ function resolveServerHost(rawHost, envHost = process.env.HOST) {
3268
+ let host = "localhost";
3269
+ if (rawHost === true) {
3270
+ host = "0.0.0.0";
3271
+ } else if (typeof rawHost === "string" && rawHost.trim()) {
3272
+ host = rawHost.trim();
3273
+ } else if (rawHost !== false && typeof envHost === "string" && envHost.trim()) {
3274
+ const trimmed = envHost.trim();
3275
+ host = trimmed === "true" ? "0.0.0.0" : trimmed;
3276
+ }
3277
+ return {
3278
+ host,
3279
+ isWildcard: host === "0.0.0.0" || host === "::"
3280
+ };
3281
+ }
2725
3282
  var ServerTask = class extends BaseTask {
2726
3283
  watcher = null;
2727
3284
  wsServer = null;
2728
3285
  clients = /* @__PURE__ */ new Set();
3286
+ serverId = import_node_crypto2.default.randomUUID();
3287
+ buildVersion = 1;
3288
+ recoveryPromise = null;
2729
3289
  constructor() {
2730
3290
  super({ name: "serve", description: "Start development server with live reload" });
2731
3291
  }
3292
+ getHandshakePayload() {
3293
+ return JSON.stringify({
3294
+ type: "connected",
3295
+ serverId: this.serverId,
3296
+ buildVersion: this.buildVersion
3297
+ });
3298
+ }
2732
3299
  broadcast(data) {
2733
- const payload = JSON.stringify(data);
3300
+ this.buildVersion += 1;
3301
+ const payload = JSON.stringify({
3302
+ ...data,
3303
+ serverId: this.serverId,
3304
+ buildVersion: this.buildVersion
3305
+ });
2734
3306
  for (const client of this.clients) {
2735
3307
  if (client.readyState === import_ws.WebSocket.OPEN) {
2736
3308
  client.send(payload);
2737
3309
  }
2738
3310
  }
2739
3311
  }
2740
- async run(config) {
2741
- if (config.env.isProd) {
2742
- logger.warn("server", "Development server is disabled in production mode");
3312
+ ensureBuildReady(config) {
3313
+ if (import_node_fs9.default.existsSync(config.dest.base)) {
2743
3314
  return;
2744
3315
  }
2745
- const app = createDevServerApp(config);
2746
- const port = config.server.port || 3e3;
2747
- const host = config.server.host || "localhost";
2748
- const server = import_node_http.default.createServer(app);
2749
- this.wsServer = new import_ws.WebSocketServer({ server, path: "/__balm_ws" });
2750
- this.wsServer.on("connection", (socket) => {
3316
+ if (!this.watcher) {
3317
+ return;
3318
+ }
3319
+ if (this.recoveryPromise) {
3320
+ return this.recoveryPromise;
3321
+ }
3322
+ logger.warn(
3323
+ "server",
3324
+ `Dev output directory (${config.dest.base}) missing \u2014 rebuilding workspace...`
3325
+ );
3326
+ const activeRecovery = this.watcher.rebuildAll().then(() => {
3327
+ this.buildVersion += 1;
3328
+ }).finally(() => {
3329
+ if (this.recoveryPromise === activeRecovery) {
3330
+ this.recoveryPromise = null;
3331
+ }
3332
+ });
3333
+ this.recoveryPromise = activeRecovery;
3334
+ return activeRecovery;
3335
+ }
3336
+ attachLiveReloadServer(server) {
3337
+ const wsServer = new import_ws.WebSocketServer({ server, path: "/__balm_ws" });
3338
+ wsServer.on("connection", (socket) => {
2751
3339
  this.clients.add(socket);
3340
+ socket.send(this.getHandshakePayload());
3341
+ socket.on("message", (raw) => {
3342
+ try {
3343
+ const msg = JSON.parse(raw.toString());
3344
+ if (msg?.type === "sync" && socket.readyState === import_ws.WebSocket.OPEN) {
3345
+ socket.send(this.getHandshakePayload());
3346
+ }
3347
+ } catch {
3348
+ }
3349
+ });
2752
3350
  socket.on("close", () => this.clients.delete(socket));
2753
3351
  });
3352
+ this.wsServer = wsServer;
3353
+ return wsServer;
3354
+ }
3355
+ async run(config) {
3356
+ if (config.env.isProd) {
3357
+ logger.warn("server", "Development server is disabled in production mode");
3358
+ return;
3359
+ }
2754
3360
  this.watcher = new FileWatcher(config, (data) => {
2755
3361
  this.broadcast(data);
2756
3362
  });
2757
3363
  this.watcher.start();
3364
+ const app = createDevServerApp(config, {
3365
+ ensureBuildReady: () => this.ensureBuildReady(config)
3366
+ });
3367
+ const port = config.server.port ?? 3e3;
3368
+ const { host, isWildcard } = resolveServerHost(config.server.host);
3369
+ const server = import_node_http.default.createServer(app);
3370
+ this.attachLiveReloadServer(server);
2758
3371
  return new Promise((resolve) => {
2759
3372
  server.listen(port, host, () => {
3373
+ const address = server.address();
3374
+ const activePort = address && typeof address === "object" ? address.port : port;
3375
+ const localHost = isWildcard ? "localhost" : host;
2760
3376
  console.log("");
2761
3377
  logger.success("server", import_picocolors4.default.bold("BalmJS Dev Server is ready!"));
2762
- console.log(` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Local:")} ${import_picocolors4.default.cyan(`http://${host}:${port}/`)}`);
2763
- console.log(` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Network:")} ${import_picocolors4.default.cyan(`http://127.0.0.1:${port}/`)}`);
3378
+ console.log(
3379
+ ` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Local:")} ${import_picocolors4.default.cyan(`http://${localHost}:${activePort}/`)}`
3380
+ );
3381
+ if (isWildcard) {
3382
+ const networkIps = getNetworkAddresses();
3383
+ if (networkIps.length > 0) {
3384
+ for (const ip of networkIps) {
3385
+ console.log(
3386
+ ` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Network:")} ${import_picocolors4.default.cyan(`http://${ip}:${activePort}/`)}`
3387
+ );
3388
+ }
3389
+ } else {
3390
+ console.log(
3391
+ ` ${import_picocolors4.default.green("\u279C")} ${import_picocolors4.default.bold("Network:")} ${import_picocolors4.default.cyan(`http://127.0.0.1:${activePort}/`)}`
3392
+ );
3393
+ }
3394
+ } else if (host === "localhost" || host === "127.0.0.1" || host === "::1") {
3395
+ console.log(
3396
+ ` ${import_picocolors4.default.dim("\u279C Network: use --host or server.host = true to expose")}`
3397
+ );
3398
+ }
2764
3399
  console.log("");
2765
3400
  if (config.env.isTest) {
2766
3401
  this.watcher?.stop();
2767
3402
  this.wsServer?.close();
2768
3403
  server.close();
2769
3404
  resolve();
3405
+ } else {
3406
+ const cleanup = () => {
3407
+ this.watcher?.stop();
3408
+ this.wsServer?.close();
3409
+ server.close();
3410
+ };
3411
+ process.once("SIGINT", () => {
3412
+ cleanup();
3413
+ process.exit(0);
3414
+ });
3415
+ process.once("SIGTERM", () => {
3416
+ cleanup();
3417
+ process.exit(0);
3418
+ });
2770
3419
  }
2771
3420
  });
2772
3421
  });
2773
3422
  }
2774
3423
  };
2775
3424
 
2776
- // src/tasks/static.ts
2777
- var import_node_path25 = __toESM(require("path"), 1);
2778
- var import_node_fs9 = require("fs");
2779
- var StaticTask = class extends BaseTask {
2780
- constructor() {
2781
- super({ name: "static", description: "Copy static assets, images, fonts, and manifest" });
2782
- }
2783
- async run(config) {
2784
- const srcBase = config.src.base;
2785
- const destBase = config.dest.base;
2786
- const staticPatterns = [
2787
- import_node_path25.default.join(srcBase, "*.{ico,png,svg,json,txt,xml,webmanifest}"),
2788
- `!${import_node_path25.default.join(srcBase, "*.html")}`
2789
- ];
2790
- const extraIncludes = [
2791
- ...config.extras?.includes || [],
2792
- ...config.assets?.includes || []
2793
- ];
2794
- const extraExcludes = [
2795
- ...config.extras?.excludes || [],
2796
- ...config.assets?.excludes || []
2797
- ];
2798
- for (const inc of extraIncludes) {
2799
- const pattern = import_node_path25.default.isAbsolute(inc) ? inc : import_node_path25.default.join(srcBase, inc);
2800
- staticPatterns.push(pattern);
2801
- }
2802
- for (const exc of extraExcludes) {
2803
- const pattern = import_node_path25.default.isAbsolute(exc) ? exc : import_node_path25.default.join(srcBase, exc);
2804
- staticPatterns.push(`!${pattern}`);
2805
- }
2806
- const pipeline = Pipeline.from(staticPatterns, {
2807
- cwd: config.workspace,
2808
- base: srcBase
2809
- });
2810
- const publicUrlReplacement = config.assets.virtualDir ? `/${config.assets.virtualDir}` : "";
2811
- pipeline.pipe(async (file2) => {
2812
- const isManifest = isManifestFile(file2, config);
2813
- if (isManifest || file2.extname === ".json") {
2814
- let content = file2.toString();
2815
- content = content.replaceAll(PUBLIC_URL, publicUrlReplacement);
2816
- if (isManifest) {
2817
- content = rewriteHtmlAssetPaths(content, config);
2818
- }
2819
- file2.contents = Buffer.from(content);
2820
- }
2821
- return file2;
2822
- });
2823
- await pipeline.dest(destBase);
2824
- if (config.src.img && (0, import_node_fs9.existsSync)(config.src.img)) {
2825
- const imgPipeline = Pipeline.from(import_node_path25.default.join(config.src.img, "**/*"), {
2826
- cwd: config.workspace,
2827
- base: config.src.img
2828
- });
2829
- await imgPipeline.dest(config.dest.img);
2830
- }
2831
- if (config.src.font && (0, import_node_fs9.existsSync)(config.src.font)) {
2832
- const fontPipeline = Pipeline.from(import_node_path25.default.join(config.src.font, "**/*"), {
2833
- cwd: config.workspace,
2834
- base: config.src.font
2835
- });
2836
- await fontPipeline.dest(config.dest.font);
2837
- }
2838
- if (config.src.media && (0, import_node_fs9.existsSync)(config.src.media)) {
2839
- const mediaPipeline = Pipeline.from(import_node_path25.default.join(config.src.media, "**/*"), {
2840
- cwd: config.workspace,
2841
- base: config.src.media
2842
- });
2843
- await mediaPipeline.dest(config.dest.media);
2844
- }
2845
- const publicDir = import_node_path25.default.join(config.workspace, "public");
2846
- if ((0, import_node_fs9.existsSync)(publicDir)) {
2847
- const pubPipeline = Pipeline.from(import_node_path25.default.join(publicDir, "**/*"), {
2848
- cwd: config.workspace,
2849
- base: publicDir
2850
- });
2851
- await pubPipeline.dest(destBase);
2852
- }
2853
- }
2854
- };
2855
-
2856
3425
  // src/hooks/index.ts
2857
3426
  var BalmHooks = class {
2858
3427
  dag;
@@ -3138,11 +3707,14 @@ var index_default = balm;
3138
3707
  VirtualFile,
3139
3708
  ZipTask,
3140
3709
  balm,
3710
+ buildEsbuildOptions,
3141
3711
  createDefaultConfig,
3142
3712
  createDevServerApp,
3713
+ createEsbuildRunner,
3143
3714
  createHistoryFallbackMiddleware,
3144
3715
  deepMerge,
3145
3716
  file,
3717
+ getNetworkAddresses,
3146
3718
  getWorkspaces,
3147
3719
  globalResolve,
3148
3720
  globalWorkspace,
@@ -3157,6 +3729,7 @@ var index_default = balm;
3157
3729
  logger,
3158
3730
  resolveConfig,
3159
3731
  resolveDefaultEntry,
3732
+ resolveServerHost,
3160
3733
  rewriteCssAssetUrls,
3161
3734
  rewriteHtmlAssetPaths,
3162
3735
  runEsbuild,