@seanhogg/builderforce-webcontainers-core 2026.10.7 → 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 (385) hide show
  1. package/dist/archive.d.ts +2 -0
  2. package/dist/archive.d.ts.map +1 -1
  3. package/dist/archive.js +6 -4
  4. package/dist/archive.js.map +1 -1
  5. package/dist/build.d.ts +6 -0
  6. package/dist/build.d.ts.map +1 -1
  7. package/dist/build.js +9 -1
  8. package/dist/build.js.map +1 -1
  9. package/dist/buildHost.d.ts +3 -0
  10. package/dist/buildHost.d.ts.map +1 -1
  11. package/dist/buildHost.js +25 -12
  12. package/dist/buildHost.js.map +1 -1
  13. package/dist/compileComponent.d.ts.map +1 -1
  14. package/dist/compileComponent.js +4 -1
  15. package/dist/compileComponent.js.map +1 -1
  16. package/dist/compileScript.d.ts +12 -4
  17. package/dist/compileScript.d.ts.map +1 -1
  18. package/dist/compileScript.js +26 -13
  19. package/dist/compileScript.js.map +1 -1
  20. package/dist/components.d.ts +5 -0
  21. package/dist/components.d.ts.map +1 -1
  22. package/dist/components.js.map +1 -1
  23. package/dist/detectProject.d.ts +2 -0
  24. package/dist/detectProject.d.ts.map +1 -1
  25. package/dist/detectProject.js +13 -7
  26. package/dist/detectProject.js.map +1 -1
  27. package/dist/devServer.d.ts +38 -4
  28. package/dist/devServer.d.ts.map +1 -1
  29. package/dist/devServer.js +140 -24
  30. package/dist/devServer.js.map +1 -1
  31. package/dist/devStyles.d.ts +27 -0
  32. package/dist/devStyles.d.ts.map +1 -0
  33. package/dist/devStyles.js +52 -0
  34. package/dist/devStyles.js.map +1 -0
  35. package/dist/hot/client.d.ts +33 -0
  36. package/dist/hot/client.d.ts.map +1 -0
  37. package/dist/hot/client.js +46 -0
  38. package/dist/hot/client.js.map +1 -0
  39. package/dist/hot/moduleGraph.d.ts +39 -0
  40. package/dist/hot/moduleGraph.d.ts.map +1 -0
  41. package/dist/hot/moduleGraph.js +69 -0
  42. package/dist/hot/moduleGraph.js.map +1 -0
  43. package/dist/hot/planUpdate.d.ts +33 -0
  44. package/dist/hot/planUpdate.d.ts.map +1 -0
  45. package/dist/hot/planUpdate.js +43 -0
  46. package/dist/hot/planUpdate.js.map +1 -0
  47. package/dist/hot/reactRefresh.d.ts +45 -0
  48. package/dist/hot/reactRefresh.d.ts.map +1 -0
  49. package/dist/hot/reactRefresh.js +86 -0
  50. package/dist/hot/reactRefresh.js.map +1 -0
  51. package/dist/html.d.ts +4 -8
  52. package/dist/html.d.ts.map +1 -1
  53. package/dist/html.js +15 -19
  54. package/dist/html.js.map +1 -1
  55. package/dist/index.d.ts +20 -1
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +12 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/installer/tree.d.ts.map +1 -1
  60. package/dist/installer/tree.js +22 -4
  61. package/dist/installer/tree.js.map +1 -1
  62. package/dist/installer/wasmBuilds.d.ts +27 -0
  63. package/dist/installer/wasmBuilds.d.ts.map +1 -0
  64. package/dist/installer/wasmBuilds.js +32 -0
  65. package/dist/installer/wasmBuilds.js.map +1 -0
  66. package/dist/node/builtins.d.ts +6 -1
  67. package/dist/node/builtins.d.ts.map +1 -1
  68. package/dist/node/builtins.js +15 -10
  69. package/dist/node/builtins.js.map +1 -1
  70. package/dist/node/childProcess.d.ts +3 -3
  71. package/dist/node/childProcess.d.ts.map +1 -1
  72. package/dist/node/childProcess.js +68 -16
  73. package/dist/node/childProcess.js.map +1 -1
  74. package/dist/node/crypto.d.ts.map +1 -1
  75. package/dist/node/crypto.js +5 -4
  76. package/dist/node/crypto.js.map +1 -1
  77. package/dist/node/esm.d.ts +7 -0
  78. package/dist/node/esm.d.ts.map +1 -1
  79. package/dist/node/esm.js +28 -2
  80. package/dist/node/esm.js.map +1 -1
  81. package/dist/node/fs/index.d.ts +3 -0
  82. package/dist/node/fs/index.d.ts.map +1 -1
  83. package/dist/node/fs/index.js +22 -106
  84. package/dist/node/fs/index.js.map +1 -1
  85. package/dist/node/fs/stdinFd.d.ts +10 -0
  86. package/dist/node/fs/stdinFd.d.ts.map +1 -0
  87. package/dist/node/fs/stdinFd.js +40 -0
  88. package/dist/node/fs/stdinFd.js.map +1 -0
  89. package/dist/node/fs/streams.d.ts +24 -0
  90. package/dist/node/fs/streams.d.ts.map +1 -0
  91. package/dist/node/fs/streams.js +144 -0
  92. package/dist/node/fs/streams.js.map +1 -0
  93. package/dist/node/fs/sync.d.ts +2 -0
  94. package/dist/node/fs/sync.d.ts.map +1 -1
  95. package/dist/node/fs/sync.js +17 -0
  96. package/dist/node/fs/sync.js.map +1 -1
  97. package/dist/node/globalObject.d.ts +25 -0
  98. package/dist/node/globalObject.d.ts.map +1 -0
  99. package/dist/node/globalObject.js +83 -0
  100. package/dist/node/globalObject.js.map +1 -0
  101. package/dist/node/http/client.d.ts +3 -1
  102. package/dist/node/http/client.d.ts.map +1 -1
  103. package/dist/node/http/client.js +74 -5
  104. package/dist/node/http/client.js.map +1 -1
  105. package/dist/node/http/index.d.ts.map +1 -1
  106. package/dist/node/http/index.js +6 -4
  107. package/dist/node/http/index.js.map +1 -1
  108. package/dist/node/http/messages.d.ts +87 -0
  109. package/dist/node/http/messages.d.ts.map +1 -0
  110. package/dist/node/http/messages.js +146 -0
  111. package/dist/node/http/messages.js.map +1 -0
  112. package/dist/node/http/server.d.ts +13 -98
  113. package/dist/node/http/server.d.ts.map +1 -1
  114. package/dist/node/http/server.js +41 -206
  115. package/dist/node/http/server.js.map +1 -1
  116. package/dist/node/http/serverResponse.d.ts +45 -0
  117. package/dist/node/http/serverResponse.d.ts.map +1 -0
  118. package/dist/node/http/serverResponse.js +96 -0
  119. package/dist/node/http/serverResponse.js.map +1 -0
  120. package/dist/node/http/upgradeSocket.d.ts +34 -0
  121. package/dist/node/http/upgradeSocket.d.ts.map +1 -0
  122. package/dist/node/http/upgradeSocket.js +73 -0
  123. package/dist/node/http/upgradeSocket.js.map +1 -0
  124. package/dist/node/ipc.d.ts +26 -0
  125. package/dist/node/ipc.d.ts.map +1 -0
  126. package/dist/node/ipc.js +76 -0
  127. package/dist/node/ipc.js.map +1 -0
  128. package/dist/node/loader.d.ts +2 -0
  129. package/dist/node/loader.d.ts.map +1 -1
  130. package/dist/node/loader.js +79 -14
  131. package/dist/node/loader.js.map +1 -1
  132. package/dist/node/misc.d.ts.map +1 -1
  133. package/dist/node/misc.js +20 -5
  134. package/dist/node/misc.js.map +1 -1
  135. package/dist/node/process.d.ts +2 -5
  136. package/dist/node/process.d.ts.map +1 -1
  137. package/dist/node/process.js +16 -11
  138. package/dist/node/process.js.map +1 -1
  139. package/dist/node/processExit.d.ts +13 -0
  140. package/dist/node/processExit.d.ts.map +1 -0
  141. package/dist/node/processExit.js +25 -0
  142. package/dist/node/processExit.js.map +1 -0
  143. package/dist/node/program.d.ts.map +1 -1
  144. package/dist/node/program.js +6 -5
  145. package/dist/node/program.js.map +1 -1
  146. package/dist/node/runtime.d.ts +6 -1
  147. package/dist/node/runtime.d.ts.map +1 -1
  148. package/dist/node/runtime.js +25 -17
  149. package/dist/node/runtime.js.map +1 -1
  150. package/dist/node/stream/readable.d.ts +2 -1
  151. package/dist/node/stream/readable.d.ts.map +1 -1
  152. package/dist/node/stream/readable.js +2 -1
  153. package/dist/node/stream/readable.js.map +1 -1
  154. package/dist/node/urlqs.d.ts +1 -1
  155. package/dist/node/urlqs.d.ts.map +1 -1
  156. package/dist/node/urlqs.js +11 -2
  157. package/dist/node/urlqs.js.map +1 -1
  158. package/dist/node/workerThreads.d.ts +31 -0
  159. package/dist/node/workerThreads.d.ts.map +1 -0
  160. package/dist/node/workerThreads.js +165 -0
  161. package/dist/node/workerThreads.js.map +1 -0
  162. package/dist/node/zlib.d.ts.map +1 -1
  163. package/dist/node/zlib.js +23 -2
  164. package/dist/node/zlib.js.map +1 -1
  165. package/dist/previewBridge.d.ts +42 -0
  166. package/dist/previewBridge.d.ts.map +1 -0
  167. package/dist/previewBridge.js +192 -0
  168. package/dist/previewBridge.js.map +1 -0
  169. package/dist/shell/ast.d.ts +101 -0
  170. package/dist/shell/ast.d.ts.map +1 -0
  171. package/dist/shell/ast.js +7 -0
  172. package/dist/shell/ast.js.map +1 -0
  173. package/dist/shell/builtins.d.ts +14 -0
  174. package/dist/shell/builtins.d.ts.map +1 -1
  175. package/dist/shell/builtins.js +87 -7
  176. package/dist/shell/builtins.js.map +1 -1
  177. package/dist/shell/compound.d.ts +30 -0
  178. package/dist/shell/compound.d.ts.map +1 -0
  179. package/dist/shell/compound.js +73 -0
  180. package/dist/shell/compound.js.map +1 -0
  181. package/dist/shell/context.d.ts.map +1 -1
  182. package/dist/shell/context.js +2 -2
  183. package/dist/shell/context.js.map +1 -1
  184. package/dist/shell/devHandoff.d.ts +10 -4
  185. package/dist/shell/devHandoff.d.ts.map +1 -1
  186. package/dist/shell/devHandoff.js +7 -5
  187. package/dist/shell/devHandoff.js.map +1 -1
  188. package/dist/shell/exec.d.ts +27 -6
  189. package/dist/shell/exec.d.ts.map +1 -1
  190. package/dist/shell/exec.js +133 -46
  191. package/dist/shell/exec.js.map +1 -1
  192. package/dist/shell/expand.d.ts +5 -1
  193. package/dist/shell/expand.d.ts.map +1 -1
  194. package/dist/shell/expand.js +7 -5
  195. package/dist/shell/expand.js.map +1 -1
  196. package/dist/shell/lineReader.d.ts +9 -0
  197. package/dist/shell/lineReader.d.ts.map +1 -0
  198. package/dist/shell/lineReader.js +42 -0
  199. package/dist/shell/lineReader.js.map +1 -0
  200. package/dist/shell/npm.js +2 -2
  201. package/dist/shell/npm.js.map +1 -1
  202. package/dist/shell/packageManagers.d.ts +20 -0
  203. package/dist/shell/packageManagers.d.ts.map +1 -0
  204. package/dist/shell/packageManagers.js +74 -0
  205. package/dist/shell/packageManagers.js.map +1 -0
  206. package/dist/shell/parse.d.ts +16 -66
  207. package/dist/shell/parse.d.ts.map +1 -1
  208. package/dist/shell/parse.js +244 -243
  209. package/dist/shell/parse.js.map +1 -1
  210. package/dist/shell/program.d.ts.map +1 -1
  211. package/dist/shell/program.js +7 -6
  212. package/dist/shell/program.js.map +1 -1
  213. package/dist/shell/testCommand.d.ts +9 -0
  214. package/dist/shell/testCommand.d.ts.map +1 -0
  215. package/dist/shell/testCommand.js +105 -0
  216. package/dist/shell/testCommand.js.map +1 -0
  217. package/dist/shell/tokenize.d.ts +25 -0
  218. package/dist/shell/tokenize.d.ts.map +1 -0
  219. package/dist/shell/tokenize.js +279 -0
  220. package/dist/shell/tokenize.js.map +1 -0
  221. package/dist/styleModules.d.ts +2 -5
  222. package/dist/styleModules.d.ts.map +1 -1
  223. package/dist/styleModules.js +23 -14
  224. package/dist/styleModules.js.map +1 -1
  225. package/dist/styles/compile.d.ts +18 -0
  226. package/dist/styles/compile.d.ts.map +1 -0
  227. package/dist/styles/compile.js +34 -0
  228. package/dist/styles/compile.js.map +1 -0
  229. package/dist/styles/compilers.d.ts +75 -0
  230. package/dist/styles/compilers.d.ts.map +1 -0
  231. package/dist/styles/compilers.js +77 -0
  232. package/dist/styles/compilers.js.map +1 -0
  233. package/dist/styles/cssModules.d.ts +40 -0
  234. package/dist/styles/cssModules.d.ts.map +1 -0
  235. package/dist/styles/cssModules.js +239 -0
  236. package/dist/styles/cssModules.js.map +1 -0
  237. package/dist/styles/imports.d.ts +37 -0
  238. package/dist/styles/imports.d.ts.map +1 -0
  239. package/dist/styles/imports.js +88 -0
  240. package/dist/styles/imports.js.map +1 -0
  241. package/dist/styles/languages.d.ts +13 -0
  242. package/dist/styles/languages.d.ts.map +1 -0
  243. package/dist/styles/languages.js +20 -0
  244. package/dist/styles/languages.js.map +1 -0
  245. package/dist/styles/packageStyles.d.ts +19 -0
  246. package/dist/styles/packageStyles.d.ts.map +1 -0
  247. package/dist/styles/packageStyles.js +32 -0
  248. package/dist/styles/packageStyles.js.map +1 -0
  249. package/dist/svelteCompiler.d.ts.map +1 -1
  250. package/dist/svelteCompiler.js +19 -2
  251. package/dist/svelteCompiler.js.map +1 -1
  252. package/dist/system/commands.d.ts +2 -0
  253. package/dist/system/commands.d.ts.map +1 -1
  254. package/dist/system/commands.js +18 -0
  255. package/dist/system/commands.js.map +1 -1
  256. package/dist/system/cookieJar.d.ts +59 -0
  257. package/dist/system/cookieJar.d.ts.map +1 -0
  258. package/dist/system/cookieJar.js +187 -0
  259. package/dist/system/cookieJar.js.map +1 -0
  260. package/dist/system/httpStream.d.ts +40 -0
  261. package/dist/system/httpStream.d.ts.map +1 -0
  262. package/dist/system/httpStream.js +156 -0
  263. package/dist/system/httpStream.js.map +1 -0
  264. package/dist/system/index.d.ts +11 -1
  265. package/dist/system/index.d.ts.map +1 -1
  266. package/dist/system/index.js +5 -0
  267. package/dist/system/index.js.map +1 -1
  268. package/dist/system/ipc.d.ts +33 -0
  269. package/dist/system/ipc.d.ts.map +1 -0
  270. package/dist/system/ipc.js +65 -0
  271. package/dist/system/ipc.js.map +1 -0
  272. package/dist/system/kernel.d.ts +10 -2
  273. package/dist/system/kernel.d.ts.map +1 -1
  274. package/dist/system/kernel.js +18 -6
  275. package/dist/system/kernel.js.map +1 -1
  276. package/dist/system/ports.d.ts +9 -4
  277. package/dist/system/ports.d.ts.map +1 -1
  278. package/dist/system/ports.js +21 -2
  279. package/dist/system/ports.js.map +1 -1
  280. package/dist/system/process.d.ts +3 -0
  281. package/dist/system/process.d.ts.map +1 -1
  282. package/dist/system/process.js +50 -26
  283. package/dist/system/process.js.map +1 -1
  284. package/dist/system/programs.d.ts +1 -1
  285. package/dist/system/programs.d.ts.map +1 -1
  286. package/dist/system/programs.js +2 -0
  287. package/dist/system/programs.js.map +1 -1
  288. package/dist/system/terminal.d.ts +10 -4
  289. package/dist/system/terminal.d.ts.map +1 -1
  290. package/dist/system/terminal.js +21 -13
  291. package/dist/system/terminal.js.map +1 -1
  292. package/dist/system/types.d.ts +65 -13
  293. package/dist/system/types.d.ts.map +1 -1
  294. package/dist/system/webSocketClient.d.ts +37 -0
  295. package/dist/system/webSocketClient.d.ts.map +1 -0
  296. package/dist/system/webSocketClient.js +152 -0
  297. package/dist/system/webSocketClient.js.map +1 -0
  298. package/dist/system/webSocketFrames.d.ts +39 -0
  299. package/dist/system/webSocketFrames.d.ts.map +1 -0
  300. package/dist/system/webSocketFrames.js +117 -0
  301. package/dist/system/webSocketFrames.js.map +1 -0
  302. package/dist/vueCompiler.d.ts.map +1 -1
  303. package/dist/vueCompiler.js +11 -8
  304. package/dist/vueCompiler.js.map +1 -1
  305. package/package.json +4 -1
  306. package/src/archive.ts +8 -4
  307. package/src/build.ts +13 -1
  308. package/src/buildHost.ts +23 -10
  309. package/src/compileComponent.ts +4 -1
  310. package/src/compileScript.ts +30 -11
  311. package/src/components.ts +5 -0
  312. package/src/detectProject.ts +13 -6
  313. package/src/devServer.ts +148 -23
  314. package/src/devStyles.ts +70 -0
  315. package/src/hot/client.ts +70 -0
  316. package/src/hot/moduleGraph.ts +90 -0
  317. package/src/hot/planUpdate.ts +66 -0
  318. package/src/hot/reactRefresh.ts +93 -0
  319. package/src/html.ts +17 -21
  320. package/src/index.ts +20 -1
  321. package/src/installer/tree.ts +22 -4
  322. package/src/installer/wasmBuilds.ts +45 -0
  323. package/src/node/builtins.ts +21 -12
  324. package/src/node/childProcess.ts +73 -20
  325. package/src/node/crypto.ts +5 -4
  326. package/src/node/esm.ts +26 -2
  327. package/src/node/fs/index.ts +26 -103
  328. package/src/node/fs/stdinFd.ts +44 -0
  329. package/src/node/fs/streams.ts +177 -0
  330. package/src/node/fs/sync.ts +15 -0
  331. package/src/node/globalObject.ts +82 -0
  332. package/src/node/http/client.ts +69 -6
  333. package/src/node/http/index.ts +6 -4
  334. package/src/node/http/messages.ts +150 -0
  335. package/src/node/http/server.ts +44 -206
  336. package/src/node/http/serverResponse.ts +105 -0
  337. package/src/node/http/upgradeSocket.ts +79 -0
  338. package/src/node/ipc.ts +91 -0
  339. package/src/node/loader.ts +78 -14
  340. package/src/node/misc.ts +19 -5
  341. package/src/node/process.ts +15 -8
  342. package/src/node/processExit.ts +21 -0
  343. package/src/node/program.ts +12 -9
  344. package/src/node/runtime.ts +29 -17
  345. package/src/node/stream/readable.ts +2 -1
  346. package/src/node/urlqs.ts +10 -2
  347. package/src/node/workerThreads.ts +198 -0
  348. package/src/node/zlib.ts +24 -2
  349. package/src/previewBridge.ts +194 -0
  350. package/src/shell/ast.ts +85 -0
  351. package/src/shell/builtins.ts +97 -7
  352. package/src/shell/compound.ts +89 -0
  353. package/src/shell/context.ts +2 -2
  354. package/src/shell/devHandoff.ts +16 -9
  355. package/src/shell/exec.ts +134 -45
  356. package/src/shell/expand.ts +8 -6
  357. package/src/shell/lineReader.ts +46 -0
  358. package/src/shell/npm.ts +2 -2
  359. package/src/shell/packageManagers.ts +75 -0
  360. package/src/shell/parse.ts +233 -236
  361. package/src/shell/program.ts +7 -6
  362. package/src/shell/testCommand.ts +105 -0
  363. package/src/shell/tokenize.ts +257 -0
  364. package/src/styleModules.ts +30 -14
  365. package/src/styles/compile.ts +43 -0
  366. package/src/styles/compilers.ts +143 -0
  367. package/src/styles/cssModules.ts +254 -0
  368. package/src/styles/imports.ts +125 -0
  369. package/src/styles/languages.ts +29 -0
  370. package/src/styles/packageStyles.ts +35 -0
  371. package/src/svelteCompiler.ts +20 -3
  372. package/src/system/commands.ts +17 -0
  373. package/src/system/cookieJar.ts +187 -0
  374. package/src/system/httpStream.ts +168 -0
  375. package/src/system/index.ts +28 -1
  376. package/src/system/ipc.ts +89 -0
  377. package/src/system/kernel.ts +22 -7
  378. package/src/system/ports.ts +23 -4
  379. package/src/system/process.ts +57 -30
  380. package/src/system/programs.ts +3 -1
  381. package/src/system/terminal.ts +34 -12
  382. package/src/system/types.ts +71 -13
  383. package/src/system/webSocketClient.ts +177 -0
  384. package/src/system/webSocketFrames.ts +118 -0
  385. package/src/vueCompiler.ts +11 -8
@@ -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';
@@ -14,9 +14,10 @@ import { Shell, type JobInput, type ShellCommand, type ShellIO } from './exec.js
14
14
  import { LineEditor } from './lineEditor.js';
15
15
  import { BUILTINS, COREUTILS, SYSTEM_PROGRAMS } from './builtins.js';
16
16
  import { npmCommand, npxCommand } from './npm.js';
17
+ import { pnpmCommand, yarnCommand } from './packageManagers.js';
17
18
  import { glob } from './expand.js';
18
19
 
19
- export const SHELL_COMMANDS: Record<string, ShellCommand> = { npm: npmCommand, npx: npxCommand };
20
+ export const SHELL_COMMANDS: Record<string, ShellCommand> = { npm: npmCommand, npx: npxCommand, pnpm: pnpmCommand, yarn: yarnCommand };
20
21
 
21
22
  function createShell(ctx: ProgramContext, positional: string[] = []): Shell {
22
23
  return new Shell({
@@ -39,7 +40,7 @@ function stdinJob(ctx: ProgramContext, controller?: AbortController): { input: J
39
40
  const queue = new InputQueue();
40
41
  const terminal = ctx.io.terminal;
41
42
  if (!terminal) {
42
- const stop = ctx.io.onStdin((chunk) => queue.push(chunk));
43
+ const stop = ctx.io.onStdin(textChunks((chunk) => queue.push(chunk)));
43
44
  return { input: { queue }, stop };
44
45
  }
45
46
  terminal.setRawMode(true);
@@ -49,11 +50,11 @@ function stdinJob(ctx: ProgramContext, controller?: AbortController): { input: J
49
50
  deliver: (chunk) => queue.push(chunk),
50
51
  signal: (name) => controller?.abort(name),
51
52
  });
52
- const stop = ctx.io.onStdin((chunk) => {
53
+ const stop = ctx.io.onStdin(textChunks((chunk) => {
53
54
  if (chunk === null) queue.push(null);
54
55
  else if (rawSink) rawSink(chunk);
55
56
  else discipline.input(chunk);
56
- });
57
+ }));
57
58
  return {
58
59
  input: { queue, setRawSink: (sink) => void (rawSink = sink) },
59
60
  stop() {
@@ -185,7 +186,7 @@ async function interactive(ctx: ProgramContext): Promise<number> {
185
186
  }
186
187
  };
187
188
 
188
- 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))));
189
190
  const onAbort = () => {
190
191
  job?.controller.abort('SIGHUP');
191
192
  finish(129);
@@ -0,0 +1,105 @@
1
+ /**
2
+ * `test` and `[ … ]`: file tests (-e -f -d -s -r -w -x), string tests (-z -n,
3
+ * = == !=), integer comparisons (-eq -ne -lt -le -gt -ge), `!`, `-a`/`-o` and
4
+ * parentheses. Exit 0 for true, 1 for false, 2 for a malformed expression.
5
+ */
6
+ import type { Command, CommandContext } from './context.js';
7
+ import { resolvePath } from './context.js';
8
+
9
+ class TestSyntaxError extends Error {}
10
+
11
+ const FILE_TESTS = new Set(['-e', '-f', '-d', '-s', '-r', '-w', '-x', '-L', '-h']);
12
+ const INT_OPS = new Set(['-eq', '-ne', '-lt', '-le', '-gt', '-ge']);
13
+
14
+ function evaluate(ctx: CommandContext, args: string[]): boolean {
15
+ let pos = 0;
16
+ const peek = () => args[pos];
17
+ const next = () => {
18
+ if (pos >= args.length) throw new TestSyntaxError('argument expected');
19
+ return args[pos++]!;
20
+ };
21
+ const integer = (value: string) => {
22
+ if (!/^\s*-?\d+\s*$/.test(value)) throw new TestSyntaxError(`${value}: integer expression expected`);
23
+ return Number(value);
24
+ };
25
+
26
+ const primary = (): boolean => {
27
+ const token = next();
28
+ if (token === '!') return !primary();
29
+ if (token === '(') {
30
+ const value = or();
31
+ if (next() !== ')') throw new TestSyntaxError("')' expected");
32
+ return value;
33
+ }
34
+ const op = peek();
35
+ if (op !== undefined && (op === '=' || op === '==' || op === '!=' || INT_OPS.has(op)) && args[pos + 1] !== undefined) {
36
+ pos++;
37
+ const right = next();
38
+ if (op === '=' || op === '==') return token === right;
39
+ if (op === '!=') return token !== right;
40
+ const [a, b] = [integer(token), integer(right)];
41
+ return op === '-eq' ? a === b : op === '-ne' ? a !== b : op === '-lt' ? a < b : op === '-le' ? a <= b : op === '-gt' ? a > b : a >= b;
42
+ }
43
+ if (token === '-z' && peek() !== undefined) return next().length === 0;
44
+ if (token === '-n' && peek() !== undefined) return next().length > 0;
45
+ if (FILE_TESTS.has(token) && peek() !== undefined) {
46
+ const path = resolvePath(ctx, next());
47
+ const fs = ctx.fs;
48
+ switch (token) {
49
+ case '-f': return fs.isFile(path);
50
+ case '-d': return fs.isDirectory(path);
51
+ case '-s': {
52
+ const contents = fs.readFile(path);
53
+ return contents !== undefined && contents.length > 0;
54
+ }
55
+ case '-L':
56
+ case '-h': return false;
57
+ default: return fs.exists(path);
58
+ }
59
+ }
60
+ return token.length > 0;
61
+ };
62
+ const and = (): boolean => {
63
+ let value = primary();
64
+ while (peek() === '-a') {
65
+ pos++;
66
+ const right = primary();
67
+ value = value && right;
68
+ }
69
+ return value;
70
+ };
71
+ const or = (): boolean => {
72
+ let value = and();
73
+ while (peek() === '-o') {
74
+ pos++;
75
+ const right = and();
76
+ value = value || right;
77
+ }
78
+ return value;
79
+ };
80
+
81
+ if (!args.length) return false;
82
+ const result = or();
83
+ if (pos < args.length) throw new TestSyntaxError(`${args[pos]}: unexpected argument`);
84
+ return result;
85
+ }
86
+
87
+ function run(ctx: CommandContext, args: string[]): number {
88
+ try {
89
+ return evaluate(ctx, args) ? 0 : 1;
90
+ } catch (error) {
91
+ if (!(error instanceof TestSyntaxError)) throw error;
92
+ ctx.io.stderr(`${ctx.name}: ${error.message}\n`);
93
+ return 2;
94
+ }
95
+ }
96
+
97
+ export const test: Command = async (ctx) => run(ctx, ctx.args);
98
+
99
+ export const bracket: Command = async (ctx) => {
100
+ if (ctx.args[ctx.args.length - 1] !== ']') {
101
+ ctx.io.stderr("[: missing ']'\n");
102
+ return 2;
103
+ }
104
+ return run(ctx, ctx.args.slice(0, -1));
105
+ };
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Shell tokens: words (with their quoting, as segments) and operators. Here-
3
+ * documents are read here too — `<<EOF` is followed, after the end of its line,
4
+ * by body lines up to the delimiter — so the parser sees each body attached to
5
+ * its redirect.
6
+ */
7
+ import type { Segment, Word } from './ast.js';
8
+
9
+ export type Token =
10
+ | { type: 'word'; word: Word; raw: string }
11
+ | { type: 'op'; op: string }
12
+ | { type: 'heredoc'; body?: Word };
13
+
14
+ export class ShellSyntaxError extends Error {
15
+ /** The input ended inside a quote, a block or a here-document: an interactive shell asks for more. */
16
+ constructor(message: string, readonly incomplete = false) {
17
+ super(message);
18
+ }
19
+ }
20
+
21
+ const OPERATORS = ['2>&1', '>&2', '2>>', '<<-', '&&', '||', ';;', '>>', '<<', '2>', '&>', '|', '&', ';', '>', '<', '(', ')', '\n'];
22
+ const SPECIAL_VARS = /^[?$#@*!0-9]/;
23
+ /** Unquoted characters that end a word. */
24
+ const WORD_BREAK = /[;|&<>()]/;
25
+
26
+ /** Find the `)` closing a `$(` at `start` (just after the paren), honouring quotes and nesting. */
27
+ function matchParen(input: string, start: number): number {
28
+ let depth = 1;
29
+ for (let i = start; i < input.length; i++) {
30
+ const ch = input[i];
31
+ if (ch === '\\') i++;
32
+ else if (ch === "'") i = input.indexOf("'", i + 1) < 0 ? input.length : input.indexOf("'", i + 1);
33
+ else if (ch === '"') {
34
+ for (i++; i < input.length && input[i] !== '"'; i++) if (input[i] === '\\') i++;
35
+ } else if (ch === '(') depth++;
36
+ else if (ch === ')' && --depth === 0) return i;
37
+ }
38
+ throw new ShellSyntaxError('unexpected end of input: missing )', true);
39
+ }
40
+
41
+ /** Parse `$…` at `i` (pointing at `$`); returns the segment and the index after it. */
42
+ function readDollar(input: string, i: number, quoted: boolean): [Segment, number] {
43
+ const next = input[i + 1];
44
+ if (next === '(') {
45
+ const end = matchParen(input, i + 2);
46
+ return [{ kind: 'cmd', source: input.slice(i + 2, end), quoted }, end + 1];
47
+ }
48
+ if (next === '{') {
49
+ const end = input.indexOf('}', i + 2);
50
+ if (end < 0) throw new ShellSyntaxError('unexpected end of input: missing }', true);
51
+ const body = input.slice(i + 2, end);
52
+ const m = /^([A-Za-z_][\w]*|[?$#@*!0-9])(?:(:-|-|:=|:\+)(.*))?$/s.exec(body);
53
+ if (!m) throw new ShellSyntaxError(`bad substitution: \${${body}}`);
54
+ const seg: Segment = { kind: 'var', name: m[1]!, quoted };
55
+ if (m[2]) {
56
+ seg.op = m[2] as ':-';
57
+ seg.arg = tokenizeWord(m[3] ?? '', quoted);
58
+ }
59
+ return [seg, end + 1];
60
+ }
61
+ if (next && SPECIAL_VARS.test(next)) return [{ kind: 'var', name: next, quoted }, i + 2];
62
+ const m = /^[A-Za-z_]\w*/.exec(input.slice(i + 1));
63
+ if (!m) return [{ kind: 'text', value: '$', quoted }, i + 1];
64
+ return [{ kind: 'var', name: m[0], quoted }, i + 1 + m[0].length];
65
+ }
66
+
67
+ /** Segments of a word body (used for `${x:-default}` arguments). */
68
+ function tokenizeWord(text: string, quoted: boolean): Word {
69
+ const tokens = tokenize(text, true);
70
+ const word: Word = [];
71
+ for (const t of tokens) if (t.type === 'word') word.push(...t.word.map((s) => (s.kind === 'tilde' ? s : { ...s, quoted: quoted || ('quoted' in s && s.quoted) } as Segment)));
72
+ return word;
73
+ }
74
+
75
+ /** A here-document body as a word: `$VAR`, `$(…)` and backticks expand, nothing splits or globs. */
76
+ function heredocWord(body: string): Word {
77
+ const word: Word = [];
78
+ let text = '';
79
+ const flush = () => {
80
+ if (text) word.push({ kind: 'text', value: text, quoted: true });
81
+ text = '';
82
+ };
83
+ for (let i = 0; i < body.length;) {
84
+ const c = body[i]!;
85
+ if (c === '\\' && /[$`\\\n]/.test(body[i + 1] ?? '')) {
86
+ if (body[i + 1] !== '\n') text += body[i + 1];
87
+ i += 2;
88
+ } else if (c === '$') {
89
+ flush();
90
+ const [seg, next] = readDollar(body, i, true);
91
+ word.push(seg);
92
+ i = next;
93
+ } else if (c === '`') {
94
+ flush();
95
+ const end = body.indexOf('`', i + 1);
96
+ if (end < 0) throw new ShellSyntaxError('unterminated ` in here-document');
97
+ word.push({ kind: 'cmd', source: body.slice(i + 1, end), quoted: true });
98
+ i = end + 1;
99
+ } else {
100
+ text += c;
101
+ i++;
102
+ }
103
+ }
104
+ flush();
105
+ return word.length ? word : [{ kind: 'text', value: '', quoted: true }];
106
+ }
107
+
108
+ interface PendingHeredoc {
109
+ token: { type: 'heredoc'; body?: Word };
110
+ delimiter: string;
111
+ strip: boolean;
112
+ quoted: boolean;
113
+ }
114
+
115
+ /** Read the bodies of pending here-documents starting at `i` (the start of a line); returns the index after them. */
116
+ function readHeredocs(input: string, i: number, pending: PendingHeredoc[]): number {
117
+ for (const doc of pending) {
118
+ const lines: string[] = [];
119
+ for (;;) {
120
+ if (i >= input.length) throw new ShellSyntaxError(`unexpected end of input: here-document delimited by ${doc.delimiter}`, true);
121
+ const end = input.indexOf('\n', i);
122
+ let line = input.slice(i, end < 0 ? input.length : end).replace(/\r$/, '');
123
+ i = end < 0 ? input.length : end + 1;
124
+ if (doc.strip) line = line.replace(/^\t+/, '');
125
+ if (line === doc.delimiter) break;
126
+ if (end < 0) throw new ShellSyntaxError(`unexpected end of input: here-document delimited by ${doc.delimiter}`, true);
127
+ lines.push(line);
128
+ }
129
+ const body = lines.map((l) => l + '\n').join('');
130
+ doc.token.body = doc.quoted ? [{ kind: 'text', value: body, quoted: true }] : heredocWord(body);
131
+ }
132
+ pending.length = 0;
133
+ return i;
134
+ }
135
+
136
+ export function tokenize(input: string, wordOnly = false): Token[] {
137
+ const tokens: Token[] = [];
138
+ const pending: PendingHeredoc[] = [];
139
+ let i = 0;
140
+ while (i < input.length) {
141
+ const ch = input[i]!;
142
+ if (ch === ' ' || ch === '\t' || ch === '\r') {
143
+ i++;
144
+ continue;
145
+ }
146
+ if (ch === '\\' && input[i + 1] === '\n') {
147
+ i += 2;
148
+ continue;
149
+ }
150
+ if (ch === '#') {
151
+ while (i < input.length && input[i] !== '\n') i++;
152
+ continue;
153
+ }
154
+ if (!wordOnly) {
155
+ const op = OPERATORS.find((o) => input.startsWith(o, i));
156
+ if (op) {
157
+ tokens.push({ type: 'op', op });
158
+ i += op.length;
159
+ if (op === '\n' && pending.length) i = readHeredocs(input, i, pending);
160
+ if (op === '<<' || op === '<<-') {
161
+ while (input[i] === ' ' || input[i] === '\t') i++;
162
+ const start = i;
163
+ while (i < input.length && !/[\s;|&<>()]/.test(input[i]!)) i++;
164
+ const raw = input.slice(start, i);
165
+ if (!raw) throw new ShellSyntaxError('syntax error: here-document needs a delimiter');
166
+ const token: PendingHeredoc['token'] = { type: 'heredoc' };
167
+ tokens.push(token);
168
+ pending.push({ token, delimiter: raw.replace(/["'\\]/g, ''), strip: op === '<<-', quoted: /["'\\]/.test(raw) });
169
+ }
170
+ continue;
171
+ }
172
+ }
173
+ // A word: runs until unquoted whitespace or an operator character.
174
+ const word: Word = [];
175
+ const start = i;
176
+ let text = '';
177
+ const flush = () => {
178
+ if (text) word.push({ kind: 'text', value: text, quoted: false });
179
+ text = '';
180
+ };
181
+ if (input[i] === '~' && (i + 1 >= input.length || /[\s/;|&<>()]/.test(input[i + 1]!))) {
182
+ word.push({ kind: 'tilde' });
183
+ i++;
184
+ }
185
+ while (i < input.length) {
186
+ const c = input[i]!;
187
+ if (/[\s]/.test(c) && !wordOnly) break;
188
+ if (!wordOnly && WORD_BREAK.test(c)) break;
189
+ if (c === '\\') {
190
+ text += input[i + 1] ?? '';
191
+ i += 2;
192
+ } else if (c === "'") {
193
+ const end = input.indexOf("'", i + 1);
194
+ if (end < 0) throw new ShellSyntaxError('unexpected end of input: unterminated quote', true);
195
+ flush();
196
+ word.push({ kind: 'text', value: input.slice(i + 1, end), quoted: true });
197
+ i = end + 1;
198
+ } else if (c === '"') {
199
+ flush();
200
+ i++;
201
+ let inner = '';
202
+ const pushInner = () => {
203
+ if (inner) word.push({ kind: 'text', value: inner, quoted: true });
204
+ inner = '';
205
+ };
206
+ let closed = false;
207
+ while (i < input.length) {
208
+ const d = input[i]!;
209
+ if (d === '"') {
210
+ closed = true;
211
+ i++;
212
+ break;
213
+ }
214
+ if (d === '\\' && /["\\$`\n]/.test(input[i + 1] ?? '')) {
215
+ inner += input[i + 1];
216
+ i += 2;
217
+ } else if (d === '$') {
218
+ pushInner();
219
+ const [seg, next] = readDollar(input, i, true);
220
+ word.push(seg);
221
+ i = next;
222
+ } else if (d === '`') {
223
+ pushInner();
224
+ const end = input.indexOf('`', i + 1);
225
+ if (end < 0) throw new ShellSyntaxError('unexpected end of input: unterminated `', true);
226
+ word.push({ kind: 'cmd', source: input.slice(i + 1, end), quoted: true });
227
+ i = end + 1;
228
+ } else {
229
+ inner += d;
230
+ i++;
231
+ }
232
+ }
233
+ if (!closed) throw new ShellSyntaxError('unexpected end of input: unterminated quote', true);
234
+ pushInner();
235
+ if (!word.length || word[word.length - 1]!.kind !== 'text') word.push({ kind: 'text', value: '', quoted: true });
236
+ } else if (c === '$') {
237
+ flush();
238
+ const [seg, next] = readDollar(input, i, false);
239
+ word.push(seg);
240
+ i = next;
241
+ } else if (c === '`') {
242
+ flush();
243
+ const end = input.indexOf('`', i + 1);
244
+ if (end < 0) throw new ShellSyntaxError('unexpected end of input: unterminated `', true);
245
+ word.push({ kind: 'cmd', source: input.slice(i + 1, end), quoted: false });
246
+ i = end + 1;
247
+ } else {
248
+ text += c;
249
+ i++;
250
+ }
251
+ }
252
+ flush();
253
+ tokens.push({ type: 'word', word, raw: input.slice(start, i) });
254
+ }
255
+ if (pending.length) throw new ShellSyntaxError(`unexpected end of input: here-document delimited by ${pending[0]!.delimiter}`, true);
256
+ return tokens;
257
+ }
@@ -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
+ }