@seanhogg/builderforce-webcontainers-core 2026.10.8 → 2026.10.9

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.
Files changed (281) hide show
  1. package/dist/build.d.ts +6 -0
  2. package/dist/build.d.ts.map +1 -1
  3. package/dist/build.js +9 -1
  4. package/dist/build.js.map +1 -1
  5. package/dist/buildHost.d.ts +3 -0
  6. package/dist/buildHost.d.ts.map +1 -1
  7. package/dist/buildHost.js +25 -12
  8. package/dist/buildHost.js.map +1 -1
  9. package/dist/compileComponent.d.ts.map +1 -1
  10. package/dist/compileComponent.js +4 -1
  11. package/dist/compileComponent.js.map +1 -1
  12. package/dist/compileScript.d.ts +12 -4
  13. package/dist/compileScript.d.ts.map +1 -1
  14. package/dist/compileScript.js +26 -13
  15. package/dist/compileScript.js.map +1 -1
  16. package/dist/components.d.ts +5 -0
  17. package/dist/components.d.ts.map +1 -1
  18. package/dist/components.js.map +1 -1
  19. package/dist/detectProject.d.ts +2 -0
  20. package/dist/detectProject.d.ts.map +1 -1
  21. package/dist/detectProject.js +13 -7
  22. package/dist/detectProject.js.map +1 -1
  23. package/dist/devServer.d.ts +38 -4
  24. package/dist/devServer.d.ts.map +1 -1
  25. package/dist/devServer.js +140 -24
  26. package/dist/devServer.js.map +1 -1
  27. package/dist/devStyles.d.ts +27 -0
  28. package/dist/devStyles.d.ts.map +1 -0
  29. package/dist/devStyles.js +52 -0
  30. package/dist/devStyles.js.map +1 -0
  31. package/dist/hot/client.d.ts +33 -0
  32. package/dist/hot/client.d.ts.map +1 -0
  33. package/dist/hot/client.js +46 -0
  34. package/dist/hot/client.js.map +1 -0
  35. package/dist/hot/moduleGraph.d.ts +39 -0
  36. package/dist/hot/moduleGraph.d.ts.map +1 -0
  37. package/dist/hot/moduleGraph.js +69 -0
  38. package/dist/hot/moduleGraph.js.map +1 -0
  39. package/dist/hot/planUpdate.d.ts +33 -0
  40. package/dist/hot/planUpdate.d.ts.map +1 -0
  41. package/dist/hot/planUpdate.js +43 -0
  42. package/dist/hot/planUpdate.js.map +1 -0
  43. package/dist/hot/reactRefresh.d.ts +45 -0
  44. package/dist/hot/reactRefresh.d.ts.map +1 -0
  45. package/dist/hot/reactRefresh.js +86 -0
  46. package/dist/hot/reactRefresh.js.map +1 -0
  47. package/dist/html.d.ts +2 -8
  48. package/dist/html.d.ts.map +1 -1
  49. package/dist/html.js +11 -17
  50. package/dist/html.js.map +1 -1
  51. package/dist/index.d.ts +19 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +11 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/installer/tree.d.ts.map +1 -1
  56. package/dist/installer/tree.js +22 -4
  57. package/dist/installer/tree.js.map +1 -1
  58. package/dist/installer/wasmBuilds.d.ts +27 -0
  59. package/dist/installer/wasmBuilds.d.ts.map +1 -0
  60. package/dist/installer/wasmBuilds.js +32 -0
  61. package/dist/installer/wasmBuilds.js.map +1 -0
  62. package/dist/node/builtins.d.ts +6 -1
  63. package/dist/node/builtins.d.ts.map +1 -1
  64. package/dist/node/builtins.js +15 -10
  65. package/dist/node/builtins.js.map +1 -1
  66. package/dist/node/childProcess.d.ts +3 -3
  67. package/dist/node/childProcess.d.ts.map +1 -1
  68. package/dist/node/childProcess.js +68 -16
  69. package/dist/node/childProcess.js.map +1 -1
  70. package/dist/node/crypto.d.ts.map +1 -1
  71. package/dist/node/crypto.js +5 -4
  72. package/dist/node/crypto.js.map +1 -1
  73. package/dist/node/esm.d.ts +7 -0
  74. package/dist/node/esm.d.ts.map +1 -1
  75. package/dist/node/esm.js +28 -2
  76. package/dist/node/esm.js.map +1 -1
  77. package/dist/node/fs/index.d.ts +3 -0
  78. package/dist/node/fs/index.d.ts.map +1 -1
  79. package/dist/node/fs/index.js +22 -106
  80. package/dist/node/fs/index.js.map +1 -1
  81. package/dist/node/fs/stdinFd.d.ts +10 -0
  82. package/dist/node/fs/stdinFd.d.ts.map +1 -0
  83. package/dist/node/fs/stdinFd.js +40 -0
  84. package/dist/node/fs/stdinFd.js.map +1 -0
  85. package/dist/node/fs/streams.d.ts +24 -0
  86. package/dist/node/fs/streams.d.ts.map +1 -0
  87. package/dist/node/fs/streams.js +144 -0
  88. package/dist/node/fs/streams.js.map +1 -0
  89. package/dist/node/fs/sync.d.ts +2 -0
  90. package/dist/node/fs/sync.d.ts.map +1 -1
  91. package/dist/node/fs/sync.js +17 -0
  92. package/dist/node/fs/sync.js.map +1 -1
  93. package/dist/node/globalObject.d.ts +25 -0
  94. package/dist/node/globalObject.d.ts.map +1 -0
  95. package/dist/node/globalObject.js +83 -0
  96. package/dist/node/globalObject.js.map +1 -0
  97. package/dist/node/http/index.d.ts.map +1 -1
  98. package/dist/node/http/index.js +4 -3
  99. package/dist/node/http/index.js.map +1 -1
  100. package/dist/node/http/server.d.ts.map +1 -1
  101. package/dist/node/http/server.js +8 -5
  102. package/dist/node/http/server.js.map +1 -1
  103. package/dist/node/http/serverResponse.d.ts +3 -0
  104. package/dist/node/http/serverResponse.d.ts.map +1 -1
  105. package/dist/node/http/serverResponse.js +7 -0
  106. package/dist/node/http/serverResponse.js.map +1 -1
  107. package/dist/node/ipc.d.ts +26 -0
  108. package/dist/node/ipc.d.ts.map +1 -0
  109. package/dist/node/ipc.js +76 -0
  110. package/dist/node/ipc.js.map +1 -0
  111. package/dist/node/loader.d.ts +2 -0
  112. package/dist/node/loader.d.ts.map +1 -1
  113. package/dist/node/loader.js +79 -14
  114. package/dist/node/loader.js.map +1 -1
  115. package/dist/node/misc.d.ts.map +1 -1
  116. package/dist/node/misc.js +20 -5
  117. package/dist/node/misc.js.map +1 -1
  118. package/dist/node/process.d.ts +2 -5
  119. package/dist/node/process.d.ts.map +1 -1
  120. package/dist/node/process.js +16 -11
  121. package/dist/node/process.js.map +1 -1
  122. package/dist/node/processExit.d.ts +13 -0
  123. package/dist/node/processExit.d.ts.map +1 -0
  124. package/dist/node/processExit.js +25 -0
  125. package/dist/node/processExit.js.map +1 -0
  126. package/dist/node/program.d.ts.map +1 -1
  127. package/dist/node/program.js +6 -5
  128. package/dist/node/program.js.map +1 -1
  129. package/dist/node/runtime.d.ts +6 -1
  130. package/dist/node/runtime.d.ts.map +1 -1
  131. package/dist/node/runtime.js +23 -15
  132. package/dist/node/runtime.js.map +1 -1
  133. package/dist/node/stream/readable.d.ts +2 -1
  134. package/dist/node/stream/readable.d.ts.map +1 -1
  135. package/dist/node/stream/readable.js +2 -1
  136. package/dist/node/stream/readable.js.map +1 -1
  137. package/dist/node/urlqs.d.ts +1 -1
  138. package/dist/node/urlqs.d.ts.map +1 -1
  139. package/dist/node/urlqs.js +11 -2
  140. package/dist/node/urlqs.js.map +1 -1
  141. package/dist/node/workerThreads.d.ts +31 -0
  142. package/dist/node/workerThreads.d.ts.map +1 -0
  143. package/dist/node/workerThreads.js +165 -0
  144. package/dist/node/workerThreads.js.map +1 -0
  145. package/dist/node/zlib.d.ts.map +1 -1
  146. package/dist/node/zlib.js +23 -2
  147. package/dist/node/zlib.js.map +1 -1
  148. package/dist/shell/context.d.ts.map +1 -1
  149. package/dist/shell/context.js +2 -2
  150. package/dist/shell/context.js.map +1 -1
  151. package/dist/shell/devHandoff.d.ts +10 -4
  152. package/dist/shell/devHandoff.d.ts.map +1 -1
  153. package/dist/shell/devHandoff.js +7 -5
  154. package/dist/shell/devHandoff.js.map +1 -1
  155. package/dist/shell/exec.d.ts.map +1 -1
  156. package/dist/shell/exec.js +6 -5
  157. package/dist/shell/exec.js.map +1 -1
  158. package/dist/shell/npm.js +2 -2
  159. package/dist/shell/npm.js.map +1 -1
  160. package/dist/shell/program.js +5 -5
  161. package/dist/shell/program.js.map +1 -1
  162. package/dist/styleModules.d.ts +2 -5
  163. package/dist/styleModules.d.ts.map +1 -1
  164. package/dist/styleModules.js +23 -14
  165. package/dist/styleModules.js.map +1 -1
  166. package/dist/styles/compile.d.ts +18 -0
  167. package/dist/styles/compile.d.ts.map +1 -0
  168. package/dist/styles/compile.js +34 -0
  169. package/dist/styles/compile.js.map +1 -0
  170. package/dist/styles/compilers.d.ts +75 -0
  171. package/dist/styles/compilers.d.ts.map +1 -0
  172. package/dist/styles/compilers.js +77 -0
  173. package/dist/styles/compilers.js.map +1 -0
  174. package/dist/styles/cssModules.d.ts +40 -0
  175. package/dist/styles/cssModules.d.ts.map +1 -0
  176. package/dist/styles/cssModules.js +239 -0
  177. package/dist/styles/cssModules.js.map +1 -0
  178. package/dist/styles/imports.d.ts +37 -0
  179. package/dist/styles/imports.d.ts.map +1 -0
  180. package/dist/styles/imports.js +88 -0
  181. package/dist/styles/imports.js.map +1 -0
  182. package/dist/styles/languages.d.ts +13 -0
  183. package/dist/styles/languages.d.ts.map +1 -0
  184. package/dist/styles/languages.js +20 -0
  185. package/dist/styles/languages.js.map +1 -0
  186. package/dist/styles/packageStyles.d.ts +19 -0
  187. package/dist/styles/packageStyles.d.ts.map +1 -0
  188. package/dist/styles/packageStyles.js +32 -0
  189. package/dist/styles/packageStyles.js.map +1 -0
  190. package/dist/svelteCompiler.d.ts.map +1 -1
  191. package/dist/svelteCompiler.js +19 -2
  192. package/dist/svelteCompiler.js.map +1 -1
  193. package/dist/system/commands.d.ts +2 -0
  194. package/dist/system/commands.d.ts.map +1 -1
  195. package/dist/system/commands.js +18 -0
  196. package/dist/system/commands.js.map +1 -1
  197. package/dist/system/index.d.ts +3 -1
  198. package/dist/system/index.d.ts.map +1 -1
  199. package/dist/system/index.js +1 -0
  200. package/dist/system/index.js.map +1 -1
  201. package/dist/system/ipc.d.ts +33 -0
  202. package/dist/system/ipc.d.ts.map +1 -0
  203. package/dist/system/ipc.js +65 -0
  204. package/dist/system/ipc.js.map +1 -0
  205. package/dist/system/kernel.d.ts.map +1 -1
  206. package/dist/system/kernel.js +6 -3
  207. package/dist/system/kernel.js.map +1 -1
  208. package/dist/system/process.d.ts +3 -0
  209. package/dist/system/process.d.ts.map +1 -1
  210. package/dist/system/process.js +50 -26
  211. package/dist/system/process.js.map +1 -1
  212. package/dist/system/terminal.d.ts +10 -4
  213. package/dist/system/terminal.d.ts.map +1 -1
  214. package/dist/system/terminal.js +21 -13
  215. package/dist/system/terminal.js.map +1 -1
  216. package/dist/system/types.d.ts +29 -7
  217. package/dist/system/types.d.ts.map +1 -1
  218. package/dist/vueCompiler.d.ts.map +1 -1
  219. package/dist/vueCompiler.js +11 -8
  220. package/dist/vueCompiler.js.map +1 -1
  221. package/package.json +4 -1
  222. package/src/build.ts +13 -1
  223. package/src/buildHost.ts +23 -10
  224. package/src/compileComponent.ts +4 -1
  225. package/src/compileScript.ts +30 -11
  226. package/src/components.ts +5 -0
  227. package/src/detectProject.ts +13 -6
  228. package/src/devServer.ts +148 -23
  229. package/src/devStyles.ts +70 -0
  230. package/src/hot/client.ts +70 -0
  231. package/src/hot/moduleGraph.ts +90 -0
  232. package/src/hot/planUpdate.ts +66 -0
  233. package/src/hot/reactRefresh.ts +93 -0
  234. package/src/html.ts +13 -19
  235. package/src/index.ts +19 -1
  236. package/src/installer/tree.ts +22 -4
  237. package/src/installer/wasmBuilds.ts +45 -0
  238. package/src/node/builtins.ts +21 -12
  239. package/src/node/childProcess.ts +73 -20
  240. package/src/node/crypto.ts +5 -4
  241. package/src/node/esm.ts +26 -2
  242. package/src/node/fs/index.ts +26 -103
  243. package/src/node/fs/stdinFd.ts +44 -0
  244. package/src/node/fs/streams.ts +177 -0
  245. package/src/node/fs/sync.ts +15 -0
  246. package/src/node/globalObject.ts +82 -0
  247. package/src/node/http/index.ts +4 -3
  248. package/src/node/http/server.ts +8 -5
  249. package/src/node/http/serverResponse.ts +7 -0
  250. package/src/node/ipc.ts +91 -0
  251. package/src/node/loader.ts +78 -14
  252. package/src/node/misc.ts +19 -5
  253. package/src/node/process.ts +15 -8
  254. package/src/node/processExit.ts +21 -0
  255. package/src/node/program.ts +12 -9
  256. package/src/node/runtime.ts +27 -15
  257. package/src/node/stream/readable.ts +2 -1
  258. package/src/node/urlqs.ts +10 -2
  259. package/src/node/workerThreads.ts +198 -0
  260. package/src/node/zlib.ts +24 -2
  261. package/src/shell/context.ts +2 -2
  262. package/src/shell/devHandoff.ts +16 -9
  263. package/src/shell/exec.ts +6 -5
  264. package/src/shell/npm.ts +2 -2
  265. package/src/shell/program.ts +5 -5
  266. package/src/styleModules.ts +30 -14
  267. package/src/styles/compile.ts +43 -0
  268. package/src/styles/compilers.ts +143 -0
  269. package/src/styles/cssModules.ts +254 -0
  270. package/src/styles/imports.ts +125 -0
  271. package/src/styles/languages.ts +29 -0
  272. package/src/styles/packageStyles.ts +35 -0
  273. package/src/svelteCompiler.ts +20 -3
  274. package/src/system/commands.ts +17 -0
  275. package/src/system/index.ts +4 -0
  276. package/src/system/ipc.ts +89 -0
  277. package/src/system/kernel.ts +6 -3
  278. package/src/system/process.ts +57 -30
  279. package/src/system/terminal.ts +34 -12
  280. package/src/system/types.ts +31 -7
  281. package/src/vueCompiler.ts +11 -8
package/src/devServer.ts CHANGED
@@ -5,13 +5,22 @@ import { esmShCdnFactory } from './packageCdn.js';
5
5
  import { noComponentCompilers, type ComponentCompilers } from './components.js';
6
6
  import { isConfigFile, readProjectConfig, type ProjectConfig } from './projectConfig.js';
7
7
  import { detectProject, type ProjectProfile } from './detectProject.js';
8
- import { compileScript, isScriptPath, type CompileContext, type ImportQuery } from './compileScript.js';
8
+ import { compileScript, isScriptPath, moduleUrl, type ImportQuery } from './compileScript.js';
9
9
  import { compileComponent } from './compileComponent.js';
10
10
  import { transformHtml } from './html.js';
11
- import { cssToModule, jsonToModule, rawToModule, rewriteCssUrls, urlToModule } from './styleModules.js';
11
+ import { jsonToModule, rawToModule, urlToModule } from './styleModules.js';
12
+ import { packageStylesheetModule, previewCss, stylesheetModule, type DevStyleContext } from './devStyles.js';
12
13
  import { loaderFor } from './transformer.js';
13
14
  import { extname, join, normalizePath } from './paths.js';
14
15
  import { JS_MIME, mimeFor } from './mime.js';
16
+ import { noStyleCompilers, type StyleCompilers } from './styles/compilers.js';
17
+ import { createStyleImportHost, type StyleImportHost, type StyleImportHostOptions } from './styles/imports.js';
18
+ import { isStylesheet } from './styles/languages.js';
19
+ import { packageStyleSpecifier } from './styles/packageStyles.js';
20
+ import { ModuleGraph } from './hot/moduleGraph.js';
21
+ import { planUpdate } from './hot/planUpdate.js';
22
+ import { componentNames, hookSignature, refreshFacts, refreshFooter, usesReactRefresh } from './hot/reactRefresh.js';
23
+ import type { PreviewUpdate } from './hot/client.js';
15
24
 
16
25
  export interface ServedFile {
17
26
  status: number;
@@ -28,13 +37,23 @@ export interface DevServerOptions {
28
37
  cdn?: PackageCdnFactory;
29
38
  /** `.vue` / `.svelte` compilers. Without them, requesting a component is an error. */
30
39
  components?: ComponentCompilers;
40
+ /** Sass / Less compilers. Without them, requesting a `.scss` or `.less` file is an error. */
41
+ styles?: StyleCompilers;
42
+ /** Where Sass/Less package imports are fetched from when not installed (default jsDelivr). */
43
+ styleImports?: Pick<StyleImportHostOptions, 'fetchText' | 'packageFileUrl'>;
31
44
  /** The "Built with Builderforce.ai" badge in served pages. Default true. */
32
45
  attribution?: boolean;
33
46
  /** Host scripts (JavaScript source) run in every preview page before the app. */
34
47
  previewScripts?: readonly string[];
48
+ /**
49
+ * Hot updates: stylesheets swap and React components re-render in place on an
50
+ * edit, keeping state (see {@link DevServer.planUpdate}). Default true.
51
+ */
52
+ hot?: boolean;
35
53
  }
36
54
 
37
55
  const NO_STORE = { 'cache-control': 'no-store' };
56
+ const CSS_MIME = mimeFor('.css');
38
57
 
39
58
  /**
40
59
  * Documents opt into COEP so the preview can be framed by a cross-origin-isolated
@@ -67,33 +86,45 @@ function parseQuery(search: string): ImportQuery | undefined {
67
86
  return undefined;
68
87
  }
69
88
 
89
+ /** Adding or removing a file, or touching config or HTML, can change how OTHER files resolve. */
90
+ function isStructuralChange(change: FsChange): boolean {
91
+ return change.type !== 'write' || change.created === true || isConfigFile(change.path) || extname(change.path) === '.html';
92
+ }
93
+
70
94
  /**
71
95
  * The dev server: request path in, response out. It does not listen on anything —
72
96
  * the host decides how requests arrive (a service worker in the browser, a plain
73
97
  * function call in tests), which is what keeps it runtime-agnostic.
74
98
  *
75
99
  * Responses are cached per (file, query) and validated against the file's VFS
76
- * version. Edits to an existing file evict only that file; creating or deleting a
77
- * file, or touching a config file, clears everything, since either can change how
78
- * OTHER files' imports resolve.
100
+ * version. Editing a file evicts it and everything that read it; creating or
101
+ * deleting a file, or touching a config file, clears everything.
102
+ *
103
+ * While serving, it records what the preview loaded and what imports what (the
104
+ * {@link ModuleGraph}); {@link planUpdate} turns an edit into a hot update from it.
79
105
  */
80
106
  export class DevServer {
81
107
  private config?: ProjectConfig;
82
108
  private cdn?: Promise<PackageCdn>;
109
+ private styleImports?: StyleImportHost;
83
110
  private profileCache?: ProjectProfile;
84
111
  private readonly cache = new Map<string, { version: number; file: ServedFile }>();
112
+ private readonly graph = new ModuleGraph();
85
113
  private readonly unwatch: () => void;
114
+ private readonly hot: boolean;
86
115
  private previewScripts: readonly string[];
87
116
 
88
117
  constructor(private readonly options: DevServerOptions) {
89
118
  if (!options.base.endsWith('/')) throw new Error('DevServer base must end with "/"');
90
119
  this.previewScripts = options.previewScripts ?? [];
120
+ this.hot = options.hot !== false;
91
121
  this.unwatch = options.fs.watch((change) => this.onChange(change));
92
122
  }
93
123
 
94
124
  dispose(): void {
95
125
  this.unwatch();
96
126
  this.cache.clear();
127
+ this.graph.clear();
97
128
  }
98
129
 
99
130
  /** Replace the host scripts injected into preview pages; takes effect on the next page load. */
@@ -114,6 +145,9 @@ export class DevServer {
114
145
 
115
146
  if (path === '/' || path === '/index.html' || path === profile.htmlPath) return this.serveDocument(profile);
116
147
 
148
+ const specifier = packageStyleSpecifier(path);
149
+ if (specifier !== undefined) return this.cached(path, `${path}?`, 0, () => this.producePackageStyle(specifier));
150
+
117
151
  const publicPath = join(profile.publicDir, path);
118
152
  const file = fs.isFile(path) ? path : fs.isFile(publicPath) ? publicPath : undefined;
119
153
  if (!file) {
@@ -121,30 +155,70 @@ export class DevServer {
121
155
  if (!extname(path) && !query) return this.serveDocument(profile);
122
156
  return query || isScriptPath(path) ? errorModule(`Cannot find module ${path}`) : reply(404, 'text/plain; charset=utf-8', `Not found: ${path}`);
123
157
  }
158
+ return this.cached(file, `${file}?${query ?? ''}`, fs.version(file) ?? 0, () => this.produce(file, query));
159
+ }
160
+
161
+ /**
162
+ * What open previews should do about `changes` (one burst of edits): swap
163
+ * stylesheets and re-render React components in place, or reload. Undefined
164
+ * when nothing the preview loaded changed. Bumps the stamps of re-run modules,
165
+ * so call it once per burst and send the result.
166
+ */
167
+ planUpdate(changes: readonly FsChange[]): PreviewUpdate | undefined {
168
+ if (!changes.length) return undefined;
169
+ if (!this.hot || changes.some(isStructuralChange)) return { type: 'reload' };
170
+ const plan = planUpdate({
171
+ changed: [...new Set(changes.map((change) => change.path))],
172
+ graph: this.graph,
173
+ refresh: this.refreshEnabled(),
174
+ hooksChanged: (path) => this.hooksChanged(path),
175
+ });
176
+ if (plan.reload) return { type: 'reload' };
177
+ if (!plan.styles.length && !plan.boundaries.length) return undefined;
178
+
179
+ const stamp = this.graph.bump(plan.touched);
180
+ // Their importers' compiled output names the old stamps.
181
+ for (const path of plan.touched) {
182
+ this.evict(path);
183
+ for (const importer of this.graph.importers(path)) this.evict(importer);
184
+ }
185
+ const { base } = this.options;
186
+ return {
187
+ type: 'update',
188
+ styles: plan.styles.map((path) => ({ path: base + path.slice(1), url: moduleUrl(base, path, undefined, stamp), stamp })),
189
+ modules: plan.boundaries.map((path) => moduleUrl(base, path, undefined, stamp)),
190
+ };
191
+ }
124
192
 
125
- const key = `${file}?${query ?? ''}`;
126
- const version = fs.version(file) ?? 0;
193
+ private async cached(file: string, key: string, version: number, produce: () => Promise<ServedFile>): Promise<ServedFile> {
194
+ this.graph.markServed(file);
127
195
  const hit = this.cache.get(key);
128
196
  if (hit && hit.version === version) return hit.file;
129
-
130
- const served = await this.produce(file, query);
197
+ const served = await produce();
131
198
  this.cache.set(key, { version, file: served });
132
199
  return served;
133
200
  }
134
201
 
202
+ private evict(file: string): void {
203
+ for (const key of [...this.cache.keys()]) if (key.startsWith(file + '?')) this.cache.delete(key);
204
+ }
205
+
135
206
  private async produce(file: string, query: ImportQuery | undefined): Promise<ServedFile> {
136
207
  const { fs, base } = this.options;
137
208
  const ext = extname(file);
209
+ const dependencies = new Set<string>();
138
210
  try {
139
211
  if (query === 'raw') return reply(200, JS_MIME, rawToModule(fs.readText(file) ?? ''));
140
212
  if (query === 'url') return reply(200, JS_MIME, urlToModule(base + file.slice(1)));
141
- if (ext === '.css') {
142
- const css = rewriteCssUrls(fs, file, fs.readText(file) ?? '', base);
143
- return query === 'import' ? reply(200, JS_MIME, cssToModule(file, css)) : reply(200, mimeFor(ext), css);
213
+ const ctx = await this.context(dependencies);
214
+ if (isStylesheet(file)) {
215
+ const style = query === 'import' ? await stylesheetModule(ctx, file) : await previewCss(ctx, file);
216
+ for (const loaded of style.loaded) dependencies.add(loaded);
217
+ return reply(200, query === 'import' ? JS_MIME : CSS_MIME, style.body);
144
218
  }
145
219
  if (ext === '.json' && query === 'import') return reply(200, JS_MIME, jsonToModule(fs.readText(file) ?? ''));
146
- if (loaderFor(ext)) return reply(200, JS_MIME, await compileScript(await this.context(), file));
147
- if (isScriptPath(file)) return reply(200, JS_MIME, await compileComponent(await this.context(), file));
220
+ if (loaderFor(ext)) return reply(200, JS_MIME, await this.compileWithRefresh(ctx, file));
221
+ if (isScriptPath(file)) return reply(200, JS_MIME, await compileComponent(ctx, file));
148
222
  if (ext === '.html' || ext === '.htm') {
149
223
  return reply(200, mimeFor(ext), transformHtml(fs.readText(file) ?? '', { base, attribution: this.options.attribution, scripts: this.previewScripts }));
150
224
  }
@@ -152,34 +226,85 @@ export class DevServer {
152
226
  } catch (error) {
153
227
  const message = error instanceof Error ? error.message : String(error);
154
228
  return query || isScriptPath(file) ? errorModule(`${file}: ${message}`) : reply(500, 'text/plain; charset=utf-8', message);
229
+ } finally {
230
+ this.graph.setDependencies(file, dependencies);
155
231
  }
156
232
  }
157
233
 
158
- private serveDocument(profile: ProjectProfile): ServedFile {
234
+ private async producePackageStyle(specifier: string): Promise<ServedFile> {
235
+ try {
236
+ return reply(200, JS_MIME, (await packageStylesheetModule(await this.context(new Set()), specifier)).body);
237
+ } catch (error) {
238
+ return errorModule(`${specifier}: ${error instanceof Error ? error.message : String(error)}`);
239
+ }
240
+ }
241
+
242
+ /** A script, with React Refresh registration appended when the preview runs it. */
243
+ private async compileWithRefresh(ctx: DevStyleContext, file: string): Promise<string> {
244
+ const code = await compileScript(ctx, file);
245
+ if (!this.refreshEnabled()) return code;
246
+ const names = componentNames(code);
247
+ this.graph.setFacts(file, await refreshFacts(code, this.options.fs.readText(file) ?? '', names));
248
+ return code + refreshFooter(file, names);
249
+ }
250
+
251
+ private hooksChanged(path: string): boolean {
252
+ const facts = this.graph.factsOf(path);
253
+ return !!facts && !!loaderFor(extname(path)) && hookSignature(this.options.fs.readText(path) ?? '') !== facts.hooks;
254
+ }
255
+
256
+ private projectConfig(): ProjectConfig {
257
+ return (this.config ??= readProjectConfig(this.options.fs));
258
+ }
259
+
260
+ private refreshEnabled(): boolean {
261
+ return this.hot && usesReactRefresh(this.projectConfig());
262
+ }
263
+
264
+ private async serveDocument(profile: ProjectProfile): Promise<ServedFile> {
159
265
  if (!profile.supported || !profile.htmlPath) {
160
266
  return reply(501, 'text/html; charset=utf-8', `<!doctype html><meta charset="utf-8"><p>${profile.reason ?? 'Unsupported project.'}</p>`);
161
267
  }
162
268
  const html = this.options.fs.readText(profile.htmlPath) ?? '';
163
269
  const { base, attribution } = this.options;
164
- return reply(200, 'text/html; charset=utf-8', transformHtml(html, { base, entry: profile.entry, attribution, scripts: this.previewScripts }));
270
+ const refreshRuntime = this.refreshEnabled() ? (await this.packageCdn()).urlFor('react-refresh', '/runtime') : undefined;
271
+ return reply(200, 'text/html; charset=utf-8', transformHtml(html, { base, entry: profile.entry, attribution, scripts: this.previewScripts, refreshRuntime }));
272
+ }
273
+
274
+ private packageCdn(): Promise<PackageCdn> {
275
+ const config = this.projectConfig();
276
+ return (this.cdn ??= Promise.resolve((this.options.cdn ?? esmShCdnFactory)(config.dependencies, { dev: true })));
165
277
  }
166
278
 
167
- private async context(): Promise<CompileContext> {
279
+ /** The compile context for one response; `dependencies` collects the local files it reads. */
280
+ private async context(dependencies: Set<string>): Promise<DevStyleContext> {
168
281
  const { fs, transformer, base } = this.options;
169
- this.config ??= readProjectConfig(fs);
170
- this.cdn ??= Promise.resolve((this.options.cdn ?? esmShCdnFactory)(this.config.dependencies, { dev: true }));
171
- return { fs, config: this.config, cdn: await this.cdn, transformer, base, components: this.options.components ?? noComponentCompilers };
282
+ const config = this.projectConfig();
283
+ this.styleImports ??= createStyleImportHost({ fs, dependencies: config.dependencies, ...this.options.styleImports });
284
+ return {
285
+ fs,
286
+ config,
287
+ cdn: await this.packageCdn(),
288
+ transformer,
289
+ base,
290
+ components: this.options.components ?? noComponentCompilers,
291
+ styles: { fs, dependencies: config.dependencies, styles: this.options.styles ?? noStyleCompilers, imports: this.styleImports },
292
+ track: (path) => dependencies.add(path),
293
+ stampOf: (path) => this.graph.stampOf(path),
294
+ };
172
295
  }
173
296
 
174
297
  private onChange(change: FsChange): void {
175
- const structural = change.type === 'remove' || change.created === true || isConfigFile(change.path) || extname(change.path) === '.html';
176
- if (!structural) {
177
- for (const key of [...this.cache.keys()]) if (key.startsWith(change.path + '?')) this.cache.delete(key);
298
+ if (!isStructuralChange(change)) {
299
+ this.evict(change.path);
300
+ for (const dependent of this.graph.dependents(change.path)) this.evict(dependent);
178
301
  return;
179
302
  }
180
303
  this.cache.clear();
304
+ this.graph.clear();
181
305
  this.config = undefined;
182
306
  this.cdn = undefined;
307
+ this.styleImports = undefined;
183
308
  this.profileCache = undefined;
184
309
  }
185
310
  }
@@ -0,0 +1,70 @@
1
+ import type { CompileContext } from './compileScript.js';
2
+ import { mapSpecifier } from './compileScript.js';
3
+ import { dirname } from './paths.js';
4
+ import { resolvePackage } from './resolve.js';
5
+ import { cssToModule, injectStyleStatement, rewriteCssImports, rewriteCssUrls } from './styleModules.js';
6
+ import { compileStylesheet, type StylesheetContext } from './styles/compile.js';
7
+ import { cssModuleToModule, scopeCssModule } from './styles/cssModules.js';
8
+ import { lessCandidates, sassCandidates } from './styles/compilers.js';
9
+ import { isCssModule, styleLanguageOf } from './styles/languages.js';
10
+ import { linkStylesheetModule } from './styles/packageStyles.js';
11
+
12
+ /**
13
+ * How the dev server serves stylesheets: compiled (Sass/Less), with `url()`s and
14
+ * `@import`s pointed where the preview can load them, as CSS (a `<link>`) or as
15
+ * the JS module an import from code becomes — a <style> tag, plus the scoped
16
+ * class map for a CSS Module.
17
+ */
18
+ export interface DevStyleContext extends CompileContext {
19
+ styles: StylesheetContext;
20
+ }
21
+
22
+ export interface PreviewStyle {
23
+ body: string;
24
+ /** VFS files read, the stylesheet's partials included — the hot-update graph's edges. */
25
+ loaded: string[];
26
+ }
27
+
28
+ const isUrl = (id: string) => /^https?:/i.test(id);
29
+
30
+ async function previewCssOf(ctx: DevStyleContext, path: string, source?: string): Promise<PreviewStyle> {
31
+ const compiled = await compileStylesheet(ctx.styles, path, source);
32
+ const packageUrl = (specifier: string) => {
33
+ const { name, subpath } = resolvePackage(ctx.config.packageAliases, specifier);
34
+ return ctx.cdn.urlFor(name, subpath);
35
+ };
36
+ const css = rewriteCssImports(ctx.fs, path, rewriteCssUrls(ctx.fs, path, compiled.css, ctx.base), ctx.base, packageUrl);
37
+ return { body: css, loaded: compiled.loaded.filter((id) => !isUrl(id)) };
38
+ }
39
+
40
+ /** A stylesheet requested as CSS (a `<link>`, a CSS `@import`). */
41
+ export function previewCss(ctx: DevStyleContext, path: string): Promise<PreviewStyle> {
42
+ return previewCssOf(ctx, path);
43
+ }
44
+
45
+ /** A stylesheet imported from JS: a module injecting it, exporting the class map for a CSS Module. */
46
+ export async function stylesheetModule(ctx: DevStyleContext, path: string): Promise<PreviewStyle> {
47
+ const { body: css, loaded } = await previewCssOf(ctx, path);
48
+ if (!isCssModule(path)) return { body: cssToModule(path, css), loaded };
49
+ const scoped = scopeCssModule(css, path);
50
+ const body = cssModuleToModule(scoped, path, (expression) => injectStyleStatement(path, expression), (from) => mapSpecifier(ctx, dirname(path), from));
51
+ return { body, loaded };
52
+ }
53
+
54
+ /**
55
+ * `import 'bootstrap/dist/css/bootstrap.css'`: a plain package stylesheet is
56
+ * linked from the package CDN; a Sass/Less one (`bootstrap/scss/bootstrap.scss`)
57
+ * is found the way its own imports are (installed, else the CDN) and compiled.
58
+ */
59
+ export async function packageStylesheetModule(ctx: DevStyleContext, specifier: string): Promise<PreviewStyle> {
60
+ const { name, subpath } = resolvePackage(ctx.config.packageAliases, specifier);
61
+ const language = styleLanguageOf(subpath);
62
+ if (language === 'css') return { body: linkStylesheetModule(specifier, ctx.cdn.urlFor(name, subpath)), loaded: [] };
63
+ const id = await ctx.styles.imports.resolve(`~${name}${subpath}`, undefined, language === 'less' ? lessCandidates : sassCandidates);
64
+ if (!id) throw new Error(`Cannot find the stylesheet ${specifier}`);
65
+ const file = await ctx.styles.imports.load(id);
66
+ const compiled = await compileStylesheet(ctx.styles, id, file.contents);
67
+ // In a <style> tag a relative `url()` would resolve against the page; anchor it to the file.
68
+ const css = isUrl(id) ? compiled.css.replace(/url\(\s*(['"]?)(?!data:|https?:|\/|#)([^'")]+)\1\s*\)/g, (_m, quote: string, ref: string) => `url(${quote}${new URL(ref, id).href}${quote})`) : rewriteCssUrls(ctx.fs, id, compiled.css, ctx.base);
69
+ return { body: cssToModule(`/${specifier}`, css), loaded: compiled.loaded.filter((loaded) => !isUrl(loaded)) };
70
+ }
@@ -0,0 +1,70 @@
1
+ import { REFRESH_GLOBAL } from './reactRefresh.js';
2
+
3
+ /**
4
+ * What the host tells open previews after an edit. Old pages reload on any
5
+ * message, and new pages treat anything that is not an `update` as a reload,
6
+ * so a host and a preview from different releases still agree.
7
+ */
8
+ export type PreviewUpdate = { type: 'reload' } | HotUpdate;
9
+
10
+ export interface HotUpdate {
11
+ type: 'update';
12
+ /** Stylesheets to swap without reloading. */
13
+ styles: HotStyle[];
14
+ /** Module URLs (fresh stamps) to re-run, then let React Refresh re-render. */
15
+ modules: string[];
16
+ }
17
+
18
+ export interface HotStyle {
19
+ /** The stylesheet's URL path, as a `<link href>` names it. */
20
+ path: string;
21
+ /** Its JS module URL with a fresh stamp, for a stylesheet imported from JS. */
22
+ url: string;
23
+ stamp: number;
24
+ }
25
+
26
+ /** The BroadcastChannel previews of `base` listen on — keyed, so two runtimes never cross. */
27
+ export function updateChannelName(base: string): string {
28
+ return `bfwc:reload:${base}`;
29
+ }
30
+
31
+ /**
32
+ * Runs in every preview page. A stylesheet `<link>` gets a cache-busted `href`;
33
+ * one imported from JS is re-imported, which replaces its <style> tag. Changed
34
+ * modules are re-imported in order, then React Refresh re-renders what they
35
+ * define. An update that fails to apply (a syntax error mid-edit) is reported
36
+ * as an uncaught error and leaves the page as it was; the next edit applies on top.
37
+ */
38
+ export function hotUpdateScript(base: string): string {
39
+ return `<script>(function(){
40
+ if (typeof BroadcastChannel === 'undefined') return;
41
+ var pending = Promise.resolve();
42
+ function swapStyle(style) {
43
+ var swapped = false;
44
+ document.querySelectorAll('link[rel="stylesheet"]').forEach(function (link) {
45
+ var url = new URL(link.href, location.href);
46
+ if (url.pathname !== style.path) return;
47
+ url.searchParams.set('t', String(style.stamp));
48
+ link.href = url.href;
49
+ swapped = true;
50
+ });
51
+ return swapped ? undefined : import(style.url);
52
+ }
53
+ function apply(update) {
54
+ return Promise.all(update.styles.map(swapStyle)).then(function () {
55
+ if (!update.modules.length) return;
56
+ var refresh = window[${JSON.stringify(REFRESH_GLOBAL)}];
57
+ if (!refresh) return location.reload();
58
+ return update.modules.reduce(function (chain, url) { return chain.then(function () { return import(url); }); }, Promise.resolve())
59
+ .then(function () { refresh.performReactRefresh(); });
60
+ });
61
+ }
62
+ new BroadcastChannel(${JSON.stringify(updateChannelName(base))}).onmessage = function (event) {
63
+ var update = event.data;
64
+ if (!update || update.type !== 'update') return location.reload();
65
+ pending = pending.then(function () { return apply(update); }).catch(function (error) {
66
+ setTimeout(function () { throw error; });
67
+ });
68
+ };
69
+ })();</script>`;
70
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * What the open preview has loaded, and what depends on what — the graph a hot
3
+ * update walks. Nodes are VFS paths. An edge `a → b` means serving `a` read `b`:
4
+ * a module's local imports, or the partials a Sass/Less stylesheet pulled in.
5
+ *
6
+ * Each module may carry a STAMP: bumped when a hot update re-runs it, and
7
+ * written into the import URLs that point at it (`?t=3`), so the browser — whose
8
+ * module map is keyed by URL — fetches a fresh copy instead of the one it holds.
9
+ */
10
+ export interface ModuleFacts {
11
+ /** Every export is a React component, so React Refresh can swap it in place. */
12
+ refreshBoundary: boolean;
13
+ /** The hooks the module calls, in order; a change means component state cannot survive. */
14
+ hooks: string;
15
+ }
16
+
17
+ export class ModuleGraph {
18
+ private readonly importsOf = new Map<string, Set<string>>();
19
+ private readonly importersOf = new Map<string, Set<string>>();
20
+ private readonly stamps = new Map<string, number>();
21
+ private readonly facts = new Map<string, ModuleFacts>();
22
+ private readonly served = new Set<string>();
23
+ private clock = 0;
24
+
25
+ /** Replace what `module` reads; called each time it is compiled. */
26
+ setDependencies(module: string, dependencies: Iterable<string>): void {
27
+ for (const old of this.importsOf.get(module) ?? []) this.importersOf.get(old)?.delete(module);
28
+ const next = new Set([...dependencies].filter((dependency) => dependency !== module));
29
+ this.importsOf.set(module, next);
30
+ for (const dependency of next) {
31
+ let importers = this.importersOf.get(dependency);
32
+ if (!importers) this.importersOf.set(dependency, (importers = new Set()));
33
+ importers.add(module);
34
+ }
35
+ }
36
+
37
+ importers(path: string): ReadonlySet<string> {
38
+ return this.importersOf.get(path) ?? new Set();
39
+ }
40
+
41
+ /** Everything that reads `path`, directly or through others (`path` itself excluded). */
42
+ dependents(path: string): Set<string> {
43
+ const found = new Set<string>();
44
+ const queue = [...this.importers(path)];
45
+ while (queue.length) {
46
+ const next = queue.pop()!;
47
+ if (found.has(next) || next === path) continue;
48
+ found.add(next);
49
+ queue.push(...this.importers(next));
50
+ }
51
+ return found;
52
+ }
53
+
54
+ markServed(path: string): void {
55
+ this.served.add(path);
56
+ }
57
+
58
+ /** The preview requested `path` itself (a module, a stylesheet, an image). */
59
+ isServed(path: string): boolean {
60
+ return this.served.has(path);
61
+ }
62
+
63
+ setFacts(path: string, facts: ModuleFacts): void {
64
+ this.facts.set(path, facts);
65
+ }
66
+
67
+ factsOf(path: string): ModuleFacts | undefined {
68
+ return this.facts.get(path);
69
+ }
70
+
71
+ stampOf(path: string): number | undefined {
72
+ return this.stamps.get(path);
73
+ }
74
+
75
+ /** Give every path in `paths` one new stamp, and return it. */
76
+ bump(paths: Iterable<string>): number {
77
+ const stamp = ++this.clock;
78
+ for (const path of paths) this.stamps.set(path, stamp);
79
+ return stamp;
80
+ }
81
+
82
+ /** Forget everything: the page is reloading and will request it all again. Stamps keep rising. */
83
+ clear(): void {
84
+ this.importsOf.clear();
85
+ this.importersOf.clear();
86
+ this.facts.clear();
87
+ this.served.clear();
88
+ this.stamps.clear();
89
+ }
90
+ }
@@ -0,0 +1,66 @@
1
+ import type { ModuleGraph } from './moduleGraph.js';
2
+ import { isCssModule, isStylesheet } from '../styles/languages.js';
3
+
4
+ /**
5
+ * Decide what an edit means for the open preview, from the module graph:
6
+ *
7
+ * • a plain stylesheet (or a partial one pulls in) is swapped in place;
8
+ * • a module is re-run at the nearest refresh BOUNDARIES above it — the
9
+ * changed module itself when it only exports components, else the modules
10
+ * importing it, and so on — when React Refresh is on;
11
+ * • reaching a module nothing imports (the entry) without a boundary, or a
12
+ * component whose hooks changed, means a full reload;
13
+ * • a file the page never loaded changes nothing.
14
+ *
15
+ * `touched` is every module the update re-runs or passes through: each needs a
16
+ * fresh stamp, so the re-run imports fresh copies all the way down.
17
+ */
18
+ export type UpdatePlan = { reload: true } | { reload: false; styles: string[]; boundaries: string[]; touched: string[] };
19
+
20
+ export interface PlanInput {
21
+ changed: readonly string[];
22
+ graph: ModuleGraph;
23
+ /** React Refresh is available in this preview. */
24
+ refresh: boolean;
25
+ /** The module's hook calls differ from the ones the preview is running. */
26
+ hooksChanged(path: string): boolean;
27
+ }
28
+
29
+ /** A stylesheet whose edit is only a style swap: not a CSS Module, whose class map is JS. */
30
+ const isPlainStylesheet = (path: string) => isStylesheet(path) && !isCssModule(path);
31
+
32
+ export function planUpdate({ changed, graph, refresh, hooksChanged }: PlanInput): UpdatePlan {
33
+ const styles = new Set<string>();
34
+ const boundaries = new Set<string>();
35
+ const touched = new Set<string>();
36
+ const seen = new Set<string>();
37
+
38
+ for (const start of changed) {
39
+ if (!graph.isServed(start) && graph.importers(start).size === 0) continue;
40
+ const queue = [start];
41
+ while (queue.length) {
42
+ const path = queue.shift()!;
43
+ if (seen.has(path)) continue;
44
+ seen.add(path);
45
+ touched.add(path);
46
+
47
+ if (isPlainStylesheet(path)) {
48
+ if (graph.isServed(path)) styles.add(path);
49
+ // A partial's edit reaches the stylesheets that pulled it in — never the JS
50
+ // importing a stylesheet, which a swap leaves untouched.
51
+ for (const importer of graph.importers(path)) if (isStylesheet(importer)) queue.push(importer);
52
+ continue;
53
+ }
54
+
55
+ if (refresh && hooksChanged(path)) return { reload: true };
56
+ if (refresh && graph.factsOf(path)?.refreshBoundary) {
57
+ boundaries.add(path);
58
+ continue;
59
+ }
60
+ const importers = graph.importers(path);
61
+ if (importers.size === 0) return { reload: true };
62
+ queue.push(...importers);
63
+ }
64
+ }
65
+ return { reload: false, styles: [...styles], boundaries: [...boundaries], touched: [...touched] };
66
+ }