@seanhogg/builderforce-webcontainers-core 2026.10.8 → 2026.10.10

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 (296) 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 +30 -5
  57. package/dist/installer/tree.js.map +1 -1
  58. package/dist/installer/wasmBuilds.d.ts +34 -0
  59. package/dist/installer/wasmBuilds.d.ts.map +1 -0
  60. package/dist/installer/wasmBuilds.js +41 -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 +17 -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 -6
  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/wasi/abi.d.ts +82 -0
  142. package/dist/node/wasi/abi.d.ts.map +1 -0
  143. package/dist/node/wasi/abi.js +144 -0
  144. package/dist/node/wasi/abi.js.map +1 -0
  145. package/dist/node/wasi/files.d.ts +67 -0
  146. package/dist/node/wasi/files.d.ts.map +1 -0
  147. package/dist/node/wasi/files.js +319 -0
  148. package/dist/node/wasi/files.js.map +1 -0
  149. package/dist/node/wasi/index.d.ts +17 -0
  150. package/dist/node/wasi/index.d.ts.map +1 -0
  151. package/dist/node/wasi/index.js +129 -0
  152. package/dist/node/wasi/index.js.map +1 -0
  153. package/dist/node/workerThreads.d.ts +31 -0
  154. package/dist/node/workerThreads.d.ts.map +1 -0
  155. package/dist/node/workerThreads.js +165 -0
  156. package/dist/node/workerThreads.js.map +1 -0
  157. package/dist/node/zlib.d.ts.map +1 -1
  158. package/dist/node/zlib.js +23 -2
  159. package/dist/node/zlib.js.map +1 -1
  160. package/dist/shell/context.d.ts.map +1 -1
  161. package/dist/shell/context.js +2 -2
  162. package/dist/shell/context.js.map +1 -1
  163. package/dist/shell/devHandoff.d.ts +10 -4
  164. package/dist/shell/devHandoff.d.ts.map +1 -1
  165. package/dist/shell/devHandoff.js +7 -5
  166. package/dist/shell/devHandoff.js.map +1 -1
  167. package/dist/shell/exec.d.ts.map +1 -1
  168. package/dist/shell/exec.js +6 -5
  169. package/dist/shell/exec.js.map +1 -1
  170. package/dist/shell/npm.js +2 -2
  171. package/dist/shell/npm.js.map +1 -1
  172. package/dist/shell/program.js +5 -5
  173. package/dist/shell/program.js.map +1 -1
  174. package/dist/styleModules.d.ts +2 -5
  175. package/dist/styleModules.d.ts.map +1 -1
  176. package/dist/styleModules.js +23 -14
  177. package/dist/styleModules.js.map +1 -1
  178. package/dist/styles/compile.d.ts +18 -0
  179. package/dist/styles/compile.d.ts.map +1 -0
  180. package/dist/styles/compile.js +34 -0
  181. package/dist/styles/compile.js.map +1 -0
  182. package/dist/styles/compilers.d.ts +75 -0
  183. package/dist/styles/compilers.d.ts.map +1 -0
  184. package/dist/styles/compilers.js +77 -0
  185. package/dist/styles/compilers.js.map +1 -0
  186. package/dist/styles/cssModules.d.ts +40 -0
  187. package/dist/styles/cssModules.d.ts.map +1 -0
  188. package/dist/styles/cssModules.js +239 -0
  189. package/dist/styles/cssModules.js.map +1 -0
  190. package/dist/styles/imports.d.ts +37 -0
  191. package/dist/styles/imports.d.ts.map +1 -0
  192. package/dist/styles/imports.js +88 -0
  193. package/dist/styles/imports.js.map +1 -0
  194. package/dist/styles/languages.d.ts +13 -0
  195. package/dist/styles/languages.d.ts.map +1 -0
  196. package/dist/styles/languages.js +20 -0
  197. package/dist/styles/languages.js.map +1 -0
  198. package/dist/styles/packageStyles.d.ts +19 -0
  199. package/dist/styles/packageStyles.d.ts.map +1 -0
  200. package/dist/styles/packageStyles.js +32 -0
  201. package/dist/styles/packageStyles.js.map +1 -0
  202. package/dist/svelteCompiler.d.ts.map +1 -1
  203. package/dist/svelteCompiler.js +19 -2
  204. package/dist/svelteCompiler.js.map +1 -1
  205. package/dist/system/commands.d.ts +2 -0
  206. package/dist/system/commands.d.ts.map +1 -1
  207. package/dist/system/commands.js +18 -0
  208. package/dist/system/commands.js.map +1 -1
  209. package/dist/system/index.d.ts +3 -1
  210. package/dist/system/index.d.ts.map +1 -1
  211. package/dist/system/index.js +1 -0
  212. package/dist/system/index.js.map +1 -1
  213. package/dist/system/ipc.d.ts +33 -0
  214. package/dist/system/ipc.d.ts.map +1 -0
  215. package/dist/system/ipc.js +65 -0
  216. package/dist/system/ipc.js.map +1 -0
  217. package/dist/system/kernel.d.ts.map +1 -1
  218. package/dist/system/kernel.js +6 -3
  219. package/dist/system/kernel.js.map +1 -1
  220. package/dist/system/process.d.ts +3 -0
  221. package/dist/system/process.d.ts.map +1 -1
  222. package/dist/system/process.js +50 -26
  223. package/dist/system/process.js.map +1 -1
  224. package/dist/system/terminal.d.ts +10 -4
  225. package/dist/system/terminal.d.ts.map +1 -1
  226. package/dist/system/terminal.js +21 -13
  227. package/dist/system/terminal.js.map +1 -1
  228. package/dist/system/types.d.ts +29 -7
  229. package/dist/system/types.d.ts.map +1 -1
  230. package/dist/vueCompiler.d.ts.map +1 -1
  231. package/dist/vueCompiler.js +11 -8
  232. package/dist/vueCompiler.js.map +1 -1
  233. package/package.json +4 -1
  234. package/src/build.ts +13 -1
  235. package/src/buildHost.ts +23 -10
  236. package/src/compileComponent.ts +4 -1
  237. package/src/compileScript.ts +30 -11
  238. package/src/components.ts +5 -0
  239. package/src/detectProject.ts +13 -6
  240. package/src/devServer.ts +148 -23
  241. package/src/devStyles.ts +70 -0
  242. package/src/hot/client.ts +70 -0
  243. package/src/hot/moduleGraph.ts +90 -0
  244. package/src/hot/planUpdate.ts +66 -0
  245. package/src/hot/reactRefresh.ts +93 -0
  246. package/src/html.ts +13 -19
  247. package/src/index.ts +19 -1
  248. package/src/installer/tree.ts +32 -5
  249. package/src/installer/wasmBuilds.ts +60 -0
  250. package/src/node/builtins.ts +23 -12
  251. package/src/node/childProcess.ts +73 -20
  252. package/src/node/crypto.ts +5 -4
  253. package/src/node/esm.ts +26 -2
  254. package/src/node/fs/index.ts +26 -103
  255. package/src/node/fs/stdinFd.ts +44 -0
  256. package/src/node/fs/streams.ts +177 -0
  257. package/src/node/fs/sync.ts +15 -0
  258. package/src/node/globalObject.ts +82 -0
  259. package/src/node/http/index.ts +4 -3
  260. package/src/node/http/server.ts +8 -5
  261. package/src/node/http/serverResponse.ts +7 -0
  262. package/src/node/ipc.ts +91 -0
  263. package/src/node/loader.ts +78 -14
  264. package/src/node/misc.ts +19 -6
  265. package/src/node/process.ts +15 -8
  266. package/src/node/processExit.ts +21 -0
  267. package/src/node/program.ts +12 -9
  268. package/src/node/runtime.ts +27 -15
  269. package/src/node/stream/readable.ts +2 -1
  270. package/src/node/urlqs.ts +10 -2
  271. package/src/node/wasi/abi.ts +151 -0
  272. package/src/node/wasi/files.ts +350 -0
  273. package/src/node/wasi/index.ts +149 -0
  274. package/src/node/workerThreads.ts +198 -0
  275. package/src/node/zlib.ts +24 -2
  276. package/src/shell/context.ts +2 -2
  277. package/src/shell/devHandoff.ts +16 -9
  278. package/src/shell/exec.ts +6 -5
  279. package/src/shell/npm.ts +2 -2
  280. package/src/shell/program.ts +5 -5
  281. package/src/styleModules.ts +30 -14
  282. package/src/styles/compile.ts +43 -0
  283. package/src/styles/compilers.ts +143 -0
  284. package/src/styles/cssModules.ts +254 -0
  285. package/src/styles/imports.ts +125 -0
  286. package/src/styles/languages.ts +29 -0
  287. package/src/styles/packageStyles.ts +35 -0
  288. package/src/svelteCompiler.ts +20 -3
  289. package/src/system/commands.ts +17 -0
  290. package/src/system/index.ts +4 -0
  291. package/src/system/ipc.ts +89 -0
  292. package/src/system/kernel.ts +6 -3
  293. package/src/system/process.ts +57 -30
  294. package/src/system/terminal.ts +34 -12
  295. package/src/system/types.ts +31 -7
  296. package/src/vueCompiler.ts +11 -8
@@ -0,0 +1,198 @@
1
+ /**
2
+ * `worker_threads`, as processes. A `Worker` is a node process started with a
3
+ * message channel and its `workerData` — in the browser runtime, its own Web
4
+ * Worker, so it really runs in parallel. Inside it, `isMainThread` is false and
5
+ * `parentPort` is that channel. There is no shared memory (no SharedArrayBuffer
6
+ * without cross-origin isolation, which this runtime never requires), so
7
+ * messages are copied and `transferList` ports cannot move between threads.
8
+ *
9
+ * On the wire every message is an envelope, so a worker's uncaught error reaches
10
+ * the parent's `'error'` listener as an Error, the way Node reports it.
11
+ */
12
+ import { EventEmitterBase } from './events.js';
13
+ import { Readable } from './stream/readable.js';
14
+ import type { EventLoop } from './loop.js';
15
+ import type { ChildHandle, StdioChunk, System, ThreadInfo } from '../system/types.js';
16
+ import { Buffer } from './buffer.js';
17
+ import type { IpcEndpoint } from '../system/ipc.js';
18
+ import { join } from '../paths.js';
19
+ import { keepAliveWhileListened, type ChannelKeepAlive } from './ipc.js';
20
+
21
+ type Envelope = { kind: 'message'; value: unknown } | { kind: 'error'; error: { name: string; message: string; stack?: string } };
22
+
23
+ /** The envelope a worker thread sends its parent when it dies of an uncaught error. */
24
+ export function threadErrorEnvelope(error: unknown): Envelope {
25
+ const e = error instanceof Error ? error : new Error(String(error));
26
+ return { kind: 'error', error: { name: e.name, message: e.message, stack: e.stack } };
27
+ }
28
+
29
+ function errorFrom(envelope: Extract<Envelope, { kind: 'error' }>): Error {
30
+ const error = new Error(envelope.error.message);
31
+ error.name = envelope.error.name;
32
+ if (envelope.error.stack) error.stack = envelope.error.stack;
33
+ return error;
34
+ }
35
+
36
+ export interface WorkerThreadsDeps {
37
+ system: System;
38
+ loop: EventLoop;
39
+ cwd(): string;
40
+ env(): Record<string, string | undefined>;
41
+ stdout(chunk: StdioChunk): void;
42
+ stderr(chunk: StdioChunk): void;
43
+ /** Set when this process is itself a worker thread. */
44
+ thread?: ThreadInfo;
45
+ /** Its channel to the parent (the thread's `parentPort`). */
46
+ ipc?: IpcEndpoint;
47
+ }
48
+
49
+ interface WorkerOptions {
50
+ workerData?: unknown;
51
+ eval?: boolean;
52
+ argv?: unknown[];
53
+ env?: Record<string, string | undefined> | symbol;
54
+ stdout?: boolean;
55
+ stderr?: boolean;
56
+ name?: string;
57
+ }
58
+
59
+ let nextThreadId = 1;
60
+
61
+ /** The `parentPort` of a worker thread: messages to and from the parent. */
62
+ class ParentPort extends EventEmitterBase {
63
+ private readonly keepAlive: ChannelKeepAlive;
64
+
65
+ constructor(private readonly ipc: IpcEndpoint, loop: EventLoop) {
66
+ super();
67
+ this.keepAlive = keepAliveWhileListened(this, ['message'], loop, () => ipc.connected, () => {
68
+ ipc.onMessage((envelope) => {
69
+ const { kind, value } = envelope as Extract<Envelope, { kind: 'message' }>;
70
+ if (kind === 'message') loop._run(() => this.emit('message', value));
71
+ });
72
+ });
73
+ ipc.onDisconnect(() => {
74
+ loop._run(() => this.emit('close'));
75
+ this.keepAlive.update();
76
+ });
77
+ }
78
+
79
+ postMessage(value: unknown): void {
80
+ this.ipc.send({ kind: 'message', value } satisfies Envelope);
81
+ }
82
+ close(): void {
83
+ this.ipc.disconnect();
84
+ }
85
+ start(): void {}
86
+ ref(): this {
87
+ this.keepAlive.ref();
88
+ return this;
89
+ }
90
+ unref(): this {
91
+ this.keepAlive.unref();
92
+ return this;
93
+ }
94
+ }
95
+
96
+ export function createWorkerThreadsModule(deps: WorkerThreadsDeps): Record<string, unknown> {
97
+ const { loop } = deps;
98
+ const environmentData = new Map<unknown, unknown>();
99
+
100
+ class Worker extends EventEmitterBase {
101
+ readonly threadId = nextThreadId++;
102
+ readonly resourceLimits = {};
103
+ readonly stdin = null;
104
+ readonly stdout: Readable;
105
+ readonly stderr: Readable;
106
+ private readonly handle?: ChildHandle;
107
+ private release?: () => void;
108
+ private terminated = false;
109
+
110
+ constructor(filename: string | URL, options: WorkerOptions = {}) {
111
+ super();
112
+ this.stdout = new Readable({ read() {} });
113
+ this.stderr = new Readable({ read() {} });
114
+ const source = filename instanceof URL ? decodeURIComponent(filename.pathname) : String(filename);
115
+ const script = options.eval ? ['-e', source] : [source.startsWith('/') ? source : join(deps.cwd(), source)];
116
+ const env: Record<string, string> = {};
117
+ const fromParent = typeof options.env === 'object' ? options.env : deps.env();
118
+ for (const [key, value] of Object.entries(fromParent)) if (value !== undefined) env[key] = String(value);
119
+
120
+ this.release = loop.hold();
121
+ try {
122
+ this.handle = deps.system.spawn('node', [...script, ...(options.argv ?? []).map(String)], {
123
+ cwd: deps.cwd(),
124
+ env,
125
+ ipc: true,
126
+ thread: { threadId: this.threadId, workerData: options.workerData ?? null },
127
+ });
128
+ } catch (error) {
129
+ this.releaseLoop();
130
+ queueMicrotask(() => loop._run(() => this.emit('error', error)));
131
+ return;
132
+ }
133
+ const handle = this.handle;
134
+ handle.onStdout((chunk) => (options.stdout ? this.stdout.push(Buffer.from(chunk)) : deps.stdout(chunk)));
135
+ handle.onStderr((chunk) => (options.stderr ? this.stderr.push(Buffer.from(chunk)) : deps.stderr(chunk)));
136
+ handle.ipc?.onMessage((message) => {
137
+ const envelope = message as Envelope;
138
+ loop._run(() => (envelope.kind === 'error' ? this.emit('error', errorFrom(envelope)) : this.emit('message', envelope.value)));
139
+ });
140
+ queueMicrotask(() => loop._run(() => this.emit('online')));
141
+ void handle.exit.then((code) => {
142
+ this.stdout.push(null);
143
+ this.stderr.push(null);
144
+ loop._run(() => this.emit('exit', this.terminated ? 1 : code));
145
+ this.releaseLoop();
146
+ });
147
+ }
148
+
149
+ postMessage(value: unknown): void {
150
+ this.handle?.ipc?.send({ kind: 'message', value } satisfies Envelope);
151
+ }
152
+
153
+ /** Stop the thread; resolves with its exit code. */
154
+ terminate(): Promise<number> {
155
+ if (!this.handle) return Promise.resolve(1);
156
+ this.terminated = true;
157
+ this.handle.kill('SIGKILL');
158
+ return this.handle.exit.then(() => 1);
159
+ }
160
+
161
+ ref(): this {
162
+ if (!this.release && !this.terminated) this.release = loop.hold();
163
+ return this;
164
+ }
165
+ unref(): this {
166
+ this.releaseLoop();
167
+ return this;
168
+ }
169
+ getHeapSnapshot(): Promise<never> {
170
+ return Promise.reject(Object.assign(new Error('Heap snapshots are not available in the browser runtime'), { code: 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM' }));
171
+ }
172
+
173
+ private releaseLoop(): void {
174
+ this.release?.();
175
+ this.release = undefined;
176
+ }
177
+ }
178
+
179
+ const inThread = !!deps.thread && !!deps.ipc;
180
+ return {
181
+ isMainThread: !inThread,
182
+ parentPort: inThread ? new ParentPort(deps.ipc!, loop) : null,
183
+ workerData: deps.thread?.workerData ?? null,
184
+ threadId: deps.thread?.threadId ?? 0,
185
+ resourceLimits: {},
186
+ Worker,
187
+ MessageChannel: globalThis.MessageChannel,
188
+ MessagePort: globalThis.MessagePort,
189
+ BroadcastChannel: globalThis.BroadcastChannel,
190
+ receiveMessageOnPort: () => undefined,
191
+ markAsUntransferable: () => undefined,
192
+ isMarkedAsUntransferable: () => false,
193
+ moveMessagePortToContext: (port: unknown) => port,
194
+ setEnvironmentData: (key: unknown, value: unknown) => void environmentData.set(key, value),
195
+ getEnvironmentData: (key: unknown) => environmentData.get(key),
196
+ SHARE_ENV: Symbol.for('nodejs.worker_threads.SHARE_ENV'),
197
+ };
198
+ }
package/src/node/zlib.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import * as fflate from 'fflate';
7
7
  import { Buffer } from './buffer.js';
8
8
  import { Transform } from './stream/index.js';
9
+ import { queueCallback } from './processExit.js';
9
10
 
10
11
  type Input = string | ArrayBufferView | ArrayBuffer;
11
12
  type Options = { level?: number };
@@ -36,6 +37,8 @@ const STREAMS: Record<string, (options?: Options) => InstanceType<StreamCtor>> =
36
37
  Unzip: () => new fflate.Decompress() as unknown as InstanceType<StreamCtor>,
37
38
  };
38
39
 
40
+ const Z_FINISH = 4;
41
+
39
42
  function zlibError(error: unknown): Error {
40
43
  const message = error instanceof Error ? error.message : String(error);
41
44
  return Object.assign(new Error(message || 'invalid compressed data'), { code: 'Z_DATA_ERROR', errno: -3 });
@@ -72,6 +75,25 @@ class ZlibStream extends Transform {
72
75
  }
73
76
  }
74
77
 
78
+ /** Node's native handle, which minizlib (tar) briefly patches around `_processChunk`. */
79
+ _handle = { close: () => undefined };
80
+
81
+ /** Node's internal synchronous step: minizlib drives it directly instead of `write`. */
82
+ _processChunk(chunk: Uint8Array, flushFlag: number): Buffer {
83
+ const out: Uint8Array[] = [];
84
+ const ondata = this.engine.ondata;
85
+ this.engine.ondata = (data: Uint8Array) => void (data.length && out.push(data));
86
+ try {
87
+ this.bytesWritten += chunk.length;
88
+ this.engine.push(chunk, flushFlag === Z_FINISH);
89
+ } catch (error) {
90
+ throw zlibError(error);
91
+ } finally {
92
+ this.engine.ondata = ondata;
93
+ }
94
+ return Buffer.concat(out);
95
+ }
96
+
75
97
  flush(_kind?: unknown, callback?: () => void): void {
76
98
  callback?.();
77
99
  }
@@ -93,7 +115,7 @@ const noBrotli = () => {
93
115
  export function createZlibModule(): Record<string, unknown> {
94
116
  const mod: Record<string, unknown> = {
95
117
  constants: {
96
- Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5,
118
+ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH, Z_BLOCK: 5,
97
119
  Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_BUF_ERROR: -5,
98
120
  Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1,
99
121
  Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0,
@@ -124,7 +146,7 @@ export function createZlibModule(): Record<string, unknown> {
124
146
  };
125
147
  mod[name] = (input: Input, options: Options | ((e: Error | null, r?: Buffer) => void), callback?: (e: Error | null, r?: Buffer) => void) => {
126
148
  const cb = (typeof options === 'function' ? options : callback)!;
127
- queueMicrotask(() => {
149
+ queueCallback(() => {
128
150
  try {
129
151
  cb(null, Buffer.from(fn(bytes(input), typeof options === 'object' ? options : undefined)));
130
152
  } catch (error) {
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import type { VirtualFileSystem } from '../vfs.js';
7
7
  import type { Program, System } from '../system/types.js';
8
- import { InputQueue } from '../system/terminal.js';
8
+ import { InputQueue, textChunks } from '../system/terminal.js';
9
9
  import { join, normalizePath } from '../paths.js';
10
10
 
11
11
  export interface CommandIO {
@@ -70,7 +70,7 @@ export function parseFlags(args: string[], withValue: string[] = []): { flags: S
70
70
  export function asProgram(command: Command, name: string): Program {
71
71
  return async (ctx) => {
72
72
  const stdin = new InputQueue();
73
- const stop = ctx.io.onStdin((chunk) => stdin.push(chunk));
73
+ const stop = ctx.io.onStdin(textChunks((chunk) => stdin.push(chunk)));
74
74
  try {
75
75
  return await command({
76
76
  args: ctx.args,
@@ -1,12 +1,17 @@
1
1
  /**
2
2
  * Dev-server handoff. `vite`, `vite dev`, `react-scripts start` (what `npm run
3
- * dev` / `npm start` usually run) cannot run here as-is — Vite itself needs
4
- * esbuild's native binary — but the runtime already IS a Vite-style dev server:
5
- * the in-browser DevServer serving the preview. So these commands announce that
6
- * preview as their server (a listening announcement) and stay "running" until Ctrl-C,
3
+ * dev` / `npm start` usually run) need not boot a bundler at all: the runtime
4
+ * already IS a Vite-style dev server, the in-browser DevServer serving the
5
+ * preview, and it starts instantly. So these commands announce that preview as
6
+ * their server (a listening announcement) and stay "running" until Ctrl-C,
7
7
  * which is exactly what a host waiting on `npm run dev` expects.
8
+ *
9
+ * Not for a framework that runs its own server on top of Vite (SvelteKit, Nuxt…,
10
+ * `ownServerReason`): those run the real, installed Vite, on esbuild's and
11
+ * Rollup's wasm builds (installer/wasmBuilds.ts). Nor when no preview is attached.
8
12
  */
9
13
  import type { CommandContext } from './context.js';
14
+ import { ownServerReason } from '../detectProject.js';
10
15
 
11
16
  interface Handoff {
12
17
  tool: string;
@@ -22,6 +27,12 @@ export function matchDevServer(argv: string[]): Handoff | undefined {
22
27
  return undefined;
23
28
  }
24
29
 
30
+ /** The handoff for this command line, when the attached preview can serve the project instead. */
31
+ export function devServerHandoff(ctx: CommandContext, argv: string[]): Handoff | undefined {
32
+ const handoff = matchDevServer(argv);
33
+ return handoff && ctx.system.previewUrl && !ownServerReason(ctx.fs) ? handoff : undefined;
34
+ }
35
+
25
36
  function portOf(argv: string[], fallback: number, env: Record<string, string>): number {
26
37
  const at = argv.findIndex((a) => a === '--port' || a.startsWith('--port='));
27
38
  const value = at < 0 ? env.PORT : argv[at]!.includes('=') ? argv[at]!.split('=')[1] : argv[at + 1];
@@ -30,11 +41,7 @@ function portOf(argv: string[], fallback: number, env: Record<string, string>):
30
41
  }
31
42
 
32
43
  export async function runDevServerHandoff(ctx: CommandContext, argv: string[], handoff: Handoff): Promise<number> {
33
- const url = ctx.system.previewUrl;
34
- if (!url) {
35
- ctx.io.stderr(`${handoff.tool}: no in-browser preview is attached to this runtime, so there is nothing to serve.\n`);
36
- return 1;
37
- }
44
+ const url = ctx.system.previewUrl!; // devServerHandoff only matches with a preview attached
38
45
  const port = portOf(argv, handoff.defaultPort, ctx.env);
39
46
  const banner = handoff.tool === 'vite'
40
47
  ? `\n VITE (BuilderForce in-browser dev server) ready\n\n ➜ Local: ${url}\n\n`
package/src/shell/exec.ts CHANGED
@@ -8,13 +8,13 @@
8
8
  * browser is a separate Web Worker.
9
9
  */
10
10
  import type { System } from '../system/types.js';
11
- import { InputQueue } from '../system/terminal.js';
11
+ import { InputQueue, textChunks } from '../system/terminal.js';
12
12
  import type { Command as CommandNode, FunctionDefinition, Pipeline, Redirect, Script, SimpleCommand, Word } from './ast.js';
13
13
  import { parse, ShellSyntaxError } from './parse.js';
14
14
  import { expandWord, expandWords, type ExpandContext } from './expand.js';
15
15
  import { BUILTINS, COREUTILS, type BackgroundJob, type ShellState } from './builtins.js';
16
16
  import { resolvePath, type CommandContext } from './context.js';
17
- import { matchDevServer, runDevServerHandoff } from './devHandoff.js';
17
+ import { devServerHandoff, runDevServerHandoff } from './devHandoff.js';
18
18
  import { runCompound, type Flow, type ScriptRunner } from './compound.js';
19
19
 
20
20
  export interface ShellIO {
@@ -291,7 +291,7 @@ export class Shell implements ShellState, ScriptRunner {
291
291
  if (builtin) return builtin(ctx, this);
292
292
  const command = this.options.commands?.[name];
293
293
  if (command) return command(ctx, this, input);
294
- const handoff = matchDevServer(argv);
294
+ const handoff = devServerHandoff(ctx, argv);
295
295
  if (handoff) return runDevServerHandoff(ctx, argv, handoff);
296
296
  const coreutil = COREUTILS[name];
297
297
  if (coreutil) return coreutil(ctx);
@@ -331,8 +331,9 @@ export class Shell implements ShellState, ScriptRunner {
331
331
  io.stderr(`bfsh: command not found: ${name}\n`);
332
332
  return 127;
333
333
  }
334
- child.onStdout(io.stdout);
335
- child.onStderr(io.stderr);
334
+ // The shell's own IO is text; a child's bytes are decoded as they enter it.
335
+ child.onStdout(textChunks((text) => text !== null && io.stdout(text)));
336
+ child.onStderr(textChunks((text) => text !== null && io.stderr(text)));
336
337
  let stop: (() => void) | undefined;
337
338
  if (size && input.setRawSink) input.setRawSink((data) => child.write(data));
338
339
  else stop = input.queue.subscribe((chunk) => (chunk === null ? child.closeStdin() : child.write(chunk)));
package/src/shell/npm.ts CHANGED
@@ -13,7 +13,7 @@ import { binDirectories, findExecutable } from '../system/commands.js';
13
13
  import { findPackageScope } from '../node/resolve.js';
14
14
  import { parseFlags, type CommandContext } from './context.js';
15
15
  import type { JobInput, Shell } from './exec.js';
16
- import { matchDevServer } from './devHandoff.js';
16
+ import { devServerHandoff } from './devHandoff.js';
17
17
 
18
18
  export const NPM_VERSION = '10.8.2';
19
19
 
@@ -213,7 +213,7 @@ export async function npxCommand(ctx: CommandContext, shell: Shell, input: JobIn
213
213
  }
214
214
  const binName = bin.replace(/^@[^/]+\//, '').replace(/@[^@]*$/, '');
215
215
  const io = { stdout: ctx.io.stdout, stderr: ctx.io.stderr, isTerminal: ctx.io.isTerminal };
216
- if (matchDevServer([binName, ...rest])) return shell.fork({}).exec([binName, ...rest].map(quote).join(' '), io, input, ctx.signal);
216
+ if (devServerHandoff(ctx, [binName, ...rest])) return shell.fork({}).exec([binName, ...rest].map(quote).join(' '), io, input, ctx.signal);
217
217
  let found = findExecutable(ctx.fs, binName, ctx.cwd, { PATH: '' });
218
218
  if (!found) {
219
219
  // Not installed locally: install into a scratch project, as npx does.
@@ -6,7 +6,7 @@
6
6
  * own line discipline), or cooked by the shell for everything else.
7
7
  */
8
8
  import type { Program, ProgramContext } from '../system/types.js';
9
- import { InputQueue, LineDiscipline } from '../system/terminal.js';
9
+ import { InputQueue, LineDiscipline, textChunks } from '../system/terminal.js';
10
10
  import { join } from '../paths.js';
11
11
  import { binDirectories } from '../system/commands.js';
12
12
  import { parse, ShellSyntaxError } from './parse.js';
@@ -40,7 +40,7 @@ function stdinJob(ctx: ProgramContext, controller?: AbortController): { input: J
40
40
  const queue = new InputQueue();
41
41
  const terminal = ctx.io.terminal;
42
42
  if (!terminal) {
43
- const stop = ctx.io.onStdin((chunk) => queue.push(chunk));
43
+ const stop = ctx.io.onStdin(textChunks((chunk) => queue.push(chunk)));
44
44
  return { input: { queue }, stop };
45
45
  }
46
46
  terminal.setRawMode(true);
@@ -50,11 +50,11 @@ function stdinJob(ctx: ProgramContext, controller?: AbortController): { input: J
50
50
  deliver: (chunk) => queue.push(chunk),
51
51
  signal: (name) => controller?.abort(name),
52
52
  });
53
- const stop = ctx.io.onStdin((chunk) => {
53
+ const stop = ctx.io.onStdin(textChunks((chunk) => {
54
54
  if (chunk === null) queue.push(null);
55
55
  else if (rawSink) rawSink(chunk);
56
56
  else discipline.input(chunk);
57
- });
57
+ }));
58
58
  return {
59
59
  input: { queue, setRawSink: (sink) => void (rawSink = sink) },
60
60
  stop() {
@@ -186,7 +186,7 @@ async function interactive(ctx: ProgramContext): Promise<number> {
186
186
  }
187
187
  };
188
188
 
189
- const stopInput = ctx.io.onStdin((chunk) => (chunk === null ? finish(shell.lastStatus) : onInput(chunk)));
189
+ const stopInput = ctx.io.onStdin(textChunks((chunk) => (chunk === null ? finish(shell.lastStatus) : onInput(chunk))));
190
190
  const onAbort = () => {
191
191
  job?.controller.abort('SIGHUP');
192
192
  finish(129);
@@ -1,6 +1,6 @@
1
1
  import type { VirtualFileSystem } from './vfs.js';
2
2
  import { dirname } from './paths.js';
3
- import { resolveLocal } from './resolve.js';
3
+ import { isBareSpecifier, resolveLocal } from './resolve.js';
4
4
 
5
5
  /**
6
6
  * CSS handling. A stylesheet imported from JS is served as a JS module that
@@ -23,6 +23,33 @@ export function rewriteCssUrls(fs: VirtualFileSystem, cssPath: string, css: stri
23
23
  });
24
24
  }
25
25
 
26
+ /**
27
+ * A stylesheet's `@import`s, once its text sits in a <style> tag: a relative one
28
+ * (`@import './base.css'`) resolves against the DOCUMENT there, so it becomes the
29
+ * file's preview URL; a package one (`'bootstrap/dist/css/bootstrap.css'`, or
30
+ * `~bootstrap/…`) is fetched from the package CDN, as the build's CSS bundle does.
31
+ */
32
+ const CSS_IMPORT = /@import\s+(?:url\(\s*)?(['"]?)([^'")\s;]+)\1\s*\)?/g;
33
+
34
+ export function rewriteCssImports(
35
+ fs: VirtualFileSystem,
36
+ cssPath: string,
37
+ css: string,
38
+ base: string,
39
+ packageUrl: (specifier: string) => string,
40
+ ): string {
41
+ return css.replace(CSS_IMPORT, (match, _quote: string, ref: string) => {
42
+ if (/^(data|https?):|^\/\//i.test(ref)) return match;
43
+ const specifier = ref.startsWith('~') ? ref.slice(1) : ref;
44
+ if (isBareSpecifier(specifier)) {
45
+ const local = !ref.startsWith('~') && resolveLocal(fs, dirname(cssPath), `./${specifier}`);
46
+ return `@import url(${JSON.stringify(local ? base + local.slice(1) : packageUrl(specifier))})`;
47
+ }
48
+ const resolved = resolveLocal(fs, dirname(cssPath), specifier);
49
+ return resolved ? `@import url(${JSON.stringify(base + resolved.slice(1))})` : match;
50
+ });
51
+ }
52
+
26
53
  /**
27
54
  * A statement that puts `cssExpression` (JS source evaluating to a string) in a
28
55
  * <style> tag keyed by `path`: re-evaluating the module replaces the tag's text
@@ -37,20 +64,9 @@ export function injectStyleStatement(path: string, cssExpression: string): strin
37
64
  ].join('\n');
38
65
  }
39
66
 
40
- /**
41
- * The JS module for an imported stylesheet. `.module.css` exports an identity map
42
- * (class name → itself): real scoping needs the build API, so for now CSS Modules
43
- * render correctly as long as class names don't collide.
44
- */
67
+ /** The JS module for an imported (plain) stylesheet: inject it, export its text. CSS Modules: `styles/cssModules.ts`. */
45
68
  export function cssToModule(path: string, css: string): string {
46
- const exportsCssModule = /\.module\.css$/i.test(path);
47
- return [
48
- `const css = ${JSON.stringify(css)};`,
49
- injectStyleStatement(path, 'css'),
50
- exportsCssModule
51
- ? `export default new Proxy({}, { get: (_, key) => typeof key === 'string' ? key : undefined });`
52
- : `export default css;`,
53
- ].join('\n');
69
+ return [`const css = ${JSON.stringify(css)};`, injectStyleStatement(path, 'css'), `export default css;`].join('\n');
54
70
  }
55
71
 
56
72
  export function jsonToModule(text: string): string {
@@ -0,0 +1,43 @@
1
+ import type { VirtualFileSystem } from '../vfs.js';
2
+ import type { CompiledStyle, StyleCompilers } from './compilers.js';
3
+ import type { StyleImportHost } from './imports.js';
4
+ import { styleLanguageOf, styleLanguageOfLang } from './languages.js';
5
+
6
+ /** What turning a stylesheet into CSS needs; shared by the dev server and the build. */
7
+ export interface StylesheetContext {
8
+ fs: VirtualFileSystem;
9
+ dependencies: Readonly<Record<string, string>>;
10
+ styles: StyleCompilers;
11
+ imports: StyleImportHost;
12
+ }
13
+
14
+ /**
15
+ * CSS for `source` written in `language`, read as the file `path` (its imports
16
+ * resolve beside it). Plain CSS comes back unchanged.
17
+ */
18
+ async function toCss(ctx: StylesheetContext, path: string, language: ReturnType<typeof styleLanguageOf>, source: string): Promise<CompiledStyle> {
19
+ if (!language) throw new Error(`${path}: not a stylesheet`);
20
+ if (language === 'css') return { css: source, loaded: [path] };
21
+ const compiler = await ctx.styles(language, ctx.dependencies);
22
+ try {
23
+ return await compiler.compile(source, { path, language, imports: ctx.imports });
24
+ } catch (error) {
25
+ const message = error instanceof Error ? error.message : String(error);
26
+ throw new Error(message.includes(path) ? message : `${path}: ${message}`);
27
+ }
28
+ }
29
+
30
+ /** A stylesheet file (`.css`, `.scss`, `.sass`, `.less`) as CSS, with every file it read. */
31
+ export function compileStylesheet(ctx: StylesheetContext, path: string, source = ctx.fs.readText(path) ?? ''): Promise<CompiledStyle> {
32
+ return toCss(ctx, path, styleLanguageOf(path), source);
33
+ }
34
+
35
+ /**
36
+ * A component's `<style lang="…">` block as CSS. The block belongs to `path` (the
37
+ * component), so its imports resolve beside the component.
38
+ */
39
+ export async function preprocessStyleBlock(ctx: StylesheetContext, lang: string | undefined, source: string, path: string): Promise<string> {
40
+ const language = styleLanguageOfLang(lang);
41
+ if (!language) throw new Error(`${path}: <style lang="${lang}"> is not a stylesheet language this runtime compiles.`);
42
+ return (await toCss(ctx, path, language, source)).css;
43
+ }
@@ -0,0 +1,143 @@
1
+ import type { StyleImportHost } from './imports.js';
2
+ import type { StyleLanguage } from './languages.js';
3
+
4
+ /**
5
+ * CSS preprocessors (Sass, Less) as a PORT, like the Transformer and the
6
+ * component compilers: the core never imports one. The browser runtime loads the
7
+ * official pure-JS builds from a CDN the first time a project needs one; Node
8
+ * tests pass the npm packages in. Every `@use` / `@import` goes through a
9
+ * {@link StyleImportHost}, so a compiler never touches a real file system.
10
+ */
11
+ export type PreprocessedLanguage = Exclude<StyleLanguage, 'css'>;
12
+
13
+ export interface StyleCompileRequest {
14
+ /** The stylesheet's id (a VFS path) — its imports resolve against it. */
15
+ path: string;
16
+ language: PreprocessedLanguage;
17
+ imports: StyleImportHost;
18
+ }
19
+
20
+ export interface CompiledStyle {
21
+ css: string;
22
+ /** Every file the compile read, by id, the entry included — what an edit to must recompile. */
23
+ loaded: string[];
24
+ }
25
+
26
+ export interface StyleCompiler {
27
+ compile(source: string, request: StyleCompileRequest): Promise<CompiledStyle>;
28
+ }
29
+
30
+ /** Supplies the compiler for a language, given the project's ranges to pick a matching version. */
31
+ export type StyleCompilers = (language: PreprocessedLanguage, dependencies: Readonly<Record<string, string>>) => Promise<StyleCompiler>;
32
+
33
+ /** Compilers already in hand (tests, a host that bundles them). Sass serves `.scss` and `.sass`. */
34
+ export function staticStyleCompilers(compilers: { sass?: StyleCompiler; less?: StyleCompiler }): StyleCompilers {
35
+ return (language) => {
36
+ const compiler = language === 'less' ? compilers.less : compilers.sass;
37
+ return compiler ? Promise.resolve(compiler) : Promise.reject(new Error(`No compiler for .${language} files is configured.`));
38
+ };
39
+ }
40
+
41
+ export const noStyleCompilers: StyleCompilers = staticStyleCompilers({});
42
+
43
+ // ---- Sass -------------------------------------------------------------------
44
+
45
+ type SassSyntax = 'scss' | 'indented' | 'css';
46
+
47
+ interface SassImporter {
48
+ canonicalize(url: string, context: { fromImport: boolean; containingUrl?: URL | null }): Promise<URL | null>;
49
+ load(canonicalUrl: URL): Promise<{ contents: string; syntax: SassSyntax } | null>;
50
+ }
51
+
52
+ /** The subset of the `sass` package's API (its browser and Node builds share it) the adapter uses. */
53
+ export interface SassLike {
54
+ compileStringAsync(
55
+ source: string,
56
+ options: { syntax: SassSyntax; url: URL; importer: SassImporter; importers: SassImporter[]; style: 'expanded' },
57
+ ): Promise<{ css: string; loadedUrls: URL[] }>;
58
+ }
59
+
60
+ /** Project and installed files live under this scheme, so Sass resolves their relative imports itself. */
61
+ const VFS_SCHEME = 'bfwc:';
62
+ const toSassUrl = (id: string) => new URL(/^https?:/i.test(id) ? id : `${VFS_SCHEME}${id}`);
63
+ const fromSassUrl = (url: URL) => (url.protocol === VFS_SCHEME ? decodeURI(url.pathname) : url.href);
64
+
65
+ /** Partials, extensions and index files, in Sass's own order. */
66
+ export function sassCandidates(path: string): string[] {
67
+ const slash = path.lastIndexOf('/') + 1;
68
+ const dir = path.slice(0, slash);
69
+ const base = path.slice(slash);
70
+ if (/\.(s[ac]ss|css)$/i.test(base)) return [path, `${dir}_${base}`];
71
+ return [
72
+ `${path}.scss`, `${dir}_${base}.scss`, `${path}.sass`, `${dir}_${base}.sass`, `${path}.css`,
73
+ `${path}/_index.scss`, `${path}/index.scss`, `${path}/_index.sass`, `${path}/index.sass`,
74
+ ];
75
+ }
76
+
77
+ const sassSyntax = (language: StyleLanguage): SassSyntax => (language === 'sass' ? 'indented' : language === 'css' ? 'css' : 'scss');
78
+
79
+ export function createSassCompiler(sass: SassLike): StyleCompiler {
80
+ return {
81
+ async compile(source, { path, language, imports }) {
82
+ const importer: SassImporter = {
83
+ async canonicalize(url, { containingUrl }) {
84
+ const from = containingUrl ? fromSassUrl(containingUrl) : path;
85
+ const absolute = url.startsWith(VFS_SCHEME) ? decodeURI(url.slice(VFS_SCHEME.length)) : url;
86
+ const id = await imports.resolve(absolute, from, sassCandidates);
87
+ return id ? toSassUrl(id) : null;
88
+ },
89
+ async load(canonicalUrl) {
90
+ const file = await imports.load(fromSassUrl(canonicalUrl));
91
+ return { contents: file.contents, syntax: sassSyntax(file.language) };
92
+ },
93
+ };
94
+ const result = await sass.compileStringAsync(source, { syntax: sassSyntax(language), url: toSassUrl(path), importer, importers: [importer], style: 'expanded' });
95
+ return { css: result.css, loaded: [path, ...result.loadedUrls.map(fromSassUrl).filter((id) => id !== path)] };
96
+ },
97
+ };
98
+ }
99
+
100
+ // ---- Less -------------------------------------------------------------------
101
+
102
+ interface LessLoadedFile {
103
+ filename: string;
104
+ contents: string;
105
+ }
106
+
107
+ /** The subset of the `less` package's API the adapter uses. */
108
+ export interface LessLike {
109
+ render(input: string, options: { filename: string; plugins: unknown[]; javascriptEnabled: false }): Promise<{ css: string; imports: string[] }>;
110
+ FileManager: new () => object;
111
+ }
112
+
113
+ export function lessCandidates(path: string): string[] {
114
+ return /\.[a-z]+$/i.test(path.slice(path.lastIndexOf('/') + 1)) ? [path] : [`${path}.less`, path];
115
+ }
116
+
117
+ export function createLessCompiler(less: LessLike): StyleCompiler {
118
+ return {
119
+ async compile(source, { path, imports }) {
120
+ // Less hands a file manager the importing file's DIRECTORY; resolution wants a
121
+ // file in it, so name a placeholder beside the real files.
122
+ const fromDirectory = (directory: string) => `${directory.endsWith('/') ? directory : `${directory}/`}__importer.less`;
123
+ const Base = less.FileManager as new () => object;
124
+ class ProjectFiles extends Base {
125
+ supports() {
126
+ return true;
127
+ }
128
+ supportsSync() {
129
+ return false;
130
+ }
131
+ async loadFile(filename: string, currentDirectory: string): Promise<LessLoadedFile> {
132
+ const id = await imports.resolve(filename, currentDirectory ? fromDirectory(currentDirectory) : path, lessCandidates);
133
+ if (!id) throw Object.assign(new Error(`'${filename}' wasn't found`), { type: 'File' });
134
+ const file = await imports.load(id);
135
+ return { filename: file.id, contents: file.contents };
136
+ }
137
+ }
138
+ const plugin = { install: (_less: unknown, manager: { addFileManager(manager: object): void }) => manager.addFileManager(new ProjectFiles()) };
139
+ const result = await less.render(source, { filename: path, plugins: [plugin], javascriptEnabled: false });
140
+ return { css: result.css, loaded: [path, ...result.imports.filter((id) => id !== path)] };
141
+ },
142
+ };
143
+ }