eliscript 0.0.1 → 0.0.3

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 (417) hide show
  1. package/README.md +61 -0
  2. package/bootstrap/README.md +26 -0
  3. package/bootstrap/backends/README.md +515 -0
  4. package/bootstrap/backends/async.eli +230 -0
  5. package/bootstrap/backends/binary.eli +173 -0
  6. package/bootstrap/backends/capabilities.eli +74 -0
  7. package/bootstrap/backends/elf.eli +246 -0
  8. package/bootstrap/backends/managed.eli +5976 -0
  9. package/bootstrap/backends/memory.eli +100 -0
  10. package/bootstrap/backends/native.eli +2000 -0
  11. package/bootstrap/backends/numeric.eli +1362 -0
  12. package/bootstrap/backends/optimize.eli +79 -0
  13. package/bootstrap/backends/regexp.eli +2263 -0
  14. package/bootstrap/backends/sha256.eli +138 -0
  15. package/bootstrap/backends/wasm.eli +1161 -0
  16. package/bootstrap/compiler/analyzer.eli +165 -77
  17. package/bootstrap/compiler/compiler.eli +43 -19
  18. package/bootstrap/compiler/emitter.eli +780 -170
  19. package/bootstrap/compiler/expander.eli +136 -45
  20. package/bootstrap/compiler/formatter.eli +8 -1
  21. package/bootstrap/compiler/ir.eli +148 -45
  22. package/bootstrap/compiler/lower.eli +29 -2
  23. package/bootstrap/compiler/project.eli +51 -21
  24. package/bootstrap/compiler/reader.eli +128 -36
  25. package/bootstrap/compiler/source-map.eli +46 -4
  26. package/bootstrap/compiler/symbol.eli +2 -1
  27. package/bootstrap/compiler/syntax.eli +47 -12
  28. package/bootstrap/compiler/transient-analysis.eli +40 -4
  29. package/bootstrap/host/check-cli-legacy.mjs +163 -0
  30. package/bootstrap/host/check-cli.mjs +59 -158
  31. package/bootstrap/host/check-cli.mjs.map +1 -0
  32. package/bootstrap/host/compiler-session.eli +1579 -0
  33. package/bootstrap/host/compiler-tools.eli +513 -0
  34. package/bootstrap/host/eliscript-cli.mjs +53 -33
  35. package/bootstrap/host/eliscript-cli.mjs.map +1 -0
  36. package/bootstrap/host/project-cli-legacy.mjs +295 -0
  37. package/bootstrap/host/project-cli.mjs +74 -289
  38. package/bootstrap/host/project-cli.mjs.map +1 -0
  39. package/bootstrap/host/project-legacy.mjs +1080 -0
  40. package/bootstrap/host/project.mjs +210 -1060
  41. package/bootstrap/host/project.mjs.map +1 -0
  42. package/bootstrap/runtime/UNICODE-LICENSE.txt +39 -0
  43. package/bootstrap/runtime/memory.eli +30379 -0
  44. package/browser/host.mjs +732 -11
  45. package/browser/worker.mjs +6 -3
  46. package/compiler/eliscript-analyzer.el +371 -4
  47. package/compiler/eliscript-cli.el +84 -1
  48. package/compiler/eliscript-emitter.el +1189 -256
  49. package/compiler/eliscript-expander.el +147 -10
  50. package/compiler/eliscript-ir-emitter.el +725 -208
  51. package/compiler/eliscript-lower.el +127 -1
  52. package/compiler/eliscript-portable.el +177 -51
  53. package/compiler/eliscript-project.el +20 -2
  54. package/compiler/eliscript-reader.el +141 -57
  55. package/compiler/eliscript-source-map.el +26 -12
  56. package/compiler/eliscript-transient-analysis.el +382 -19
  57. package/dist/backends/async.mjs +561 -0
  58. package/dist/backends/async.mjs.macro-origins.json +1 -0
  59. package/dist/backends/async.mjs.map +1 -0
  60. package/dist/backends/binary.mjs +381 -0
  61. package/dist/backends/binary.mjs.macro-origins.json +1 -0
  62. package/dist/backends/binary.mjs.map +1 -0
  63. package/dist/backends/capabilities.mjs +237 -0
  64. package/dist/backends/capabilities.mjs.macro-origins.json +1 -0
  65. package/dist/backends/capabilities.mjs.map +1 -0
  66. package/dist/backends/elf.mjs +540 -0
  67. package/dist/backends/elf.mjs.macro-origins.json +1 -0
  68. package/dist/backends/elf.mjs.map +1 -0
  69. package/dist/backends/managed.mjs +10616 -0
  70. package/dist/backends/managed.mjs.macro-origins.json +1 -0
  71. package/dist/backends/managed.mjs.map +1 -0
  72. package/dist/backends/memory.mjs +278 -0
  73. package/dist/backends/memory.mjs.macro-origins.json +1 -0
  74. package/dist/backends/memory.mjs.map +1 -0
  75. package/dist/backends/native.mjs +4099 -0
  76. package/dist/backends/native.mjs.macro-origins.json +1 -0
  77. package/dist/backends/native.mjs.map +1 -0
  78. package/dist/backends/numeric.mjs +2458 -0
  79. package/dist/backends/numeric.mjs.macro-origins.json +1 -0
  80. package/dist/backends/numeric.mjs.map +1 -0
  81. package/dist/backends/optimize.mjs +204 -0
  82. package/dist/backends/optimize.mjs.macro-origins.json +1 -0
  83. package/dist/backends/optimize.mjs.map +1 -0
  84. package/dist/backends/regexp.mjs +2033 -0
  85. package/dist/backends/regexp.mjs.macro-origins.json +1 -0
  86. package/dist/backends/regexp.mjs.map +1 -0
  87. package/dist/backends/sha256.mjs +310 -0
  88. package/dist/backends/sha256.mjs.macro-origins.json +1 -0
  89. package/dist/backends/sha256.mjs.map +1 -0
  90. package/dist/backends/wasm.mjs +2258 -0
  91. package/dist/backends/wasm.mjs.macro-origins.json +1 -0
  92. package/dist/backends/wasm.mjs.map +1 -0
  93. package/dist/bootstrap/analyzer.mjs +1908 -776
  94. package/dist/bootstrap/analyzer.mjs.macro-origins.json +1 -0
  95. package/dist/bootstrap/analyzer.mjs.map +1 -1
  96. package/dist/bootstrap/compiler.mjs +450 -142
  97. package/dist/bootstrap/compiler.mjs.macro-origins.json +1 -0
  98. package/dist/bootstrap/compiler.mjs.map +1 -1
  99. package/dist/bootstrap/emitter.mjs +3083 -909
  100. package/dist/bootstrap/emitter.mjs.macro-origins.json +1 -0
  101. package/dist/bootstrap/emitter.mjs.map +1 -1
  102. package/dist/bootstrap/expander.mjs +2887 -1233
  103. package/dist/bootstrap/expander.mjs.macro-origins.json +1 -0
  104. package/dist/bootstrap/expander.mjs.map +1 -1
  105. package/dist/bootstrap/formatter.mjs +582 -218
  106. package/dist/bootstrap/formatter.mjs.macro-origins.json +1 -0
  107. package/dist/bootstrap/formatter.mjs.map +1 -1
  108. package/dist/bootstrap/ir.mjs +670 -116
  109. package/dist/bootstrap/ir.mjs.macro-origins.json +1 -0
  110. package/dist/bootstrap/ir.mjs.map +1 -1
  111. package/dist/bootstrap/lower.mjs +866 -257
  112. package/dist/bootstrap/lower.mjs.macro-origins.json +1 -0
  113. package/dist/bootstrap/lower.mjs.map +1 -1
  114. package/dist/bootstrap/package.json +1 -0
  115. package/dist/bootstrap/project.mjs +1168 -498
  116. package/dist/bootstrap/project.mjs.macro-origins.json +1 -0
  117. package/dist/bootstrap/project.mjs.map +1 -1
  118. package/dist/bootstrap/reader.mjs +674 -175
  119. package/dist/bootstrap/reader.mjs.macro-origins.json +1 -0
  120. package/dist/bootstrap/reader.mjs.map +1 -1
  121. package/dist/bootstrap/runtime/math.mjs +1117 -0
  122. package/dist/bootstrap/runtime/math.mjs.map +1 -0
  123. package/dist/bootstrap/runtime/unicode-case-data.mjs +10125 -0
  124. package/dist/bootstrap/runtime/unicode-case-data.mjs.map +1 -0
  125. package/dist/bootstrap/runtime/unicode-case.mjs +281 -0
  126. package/dist/bootstrap/runtime/unicode-case.mjs.map +1 -0
  127. package/dist/bootstrap/source-map.mjs +430 -119
  128. package/dist/bootstrap/source-map.mjs.macro-origins.json +1 -0
  129. package/dist/bootstrap/source-map.mjs.map +1 -1
  130. package/dist/bootstrap/symbol.mjs +229 -53
  131. package/dist/bootstrap/symbol.mjs.macro-origins.json +1 -0
  132. package/dist/bootstrap/symbol.mjs.map +1 -1
  133. package/dist/bootstrap/syntax.mjs +205 -7
  134. package/dist/bootstrap/syntax.mjs.macro-origins.json +1 -0
  135. package/dist/bootstrap/syntax.mjs.map +1 -1
  136. package/dist/bootstrap/transient-analysis.mjs +1185 -489
  137. package/dist/bootstrap/transient-analysis.mjs.macro-origins.json +1 -0
  138. package/dist/bootstrap/transient-analysis.mjs.map +1 -1
  139. package/dist/browser/compiler.js +199 -6478
  140. package/dist/browser/host.mjs +1078 -0
  141. package/dist/browser/loader.js +1 -0
  142. package/dist/browser/loader.mjs +231 -0
  143. package/dist/browser/worker.mjs +63 -0
  144. package/dist/compiler-artifact.json +1 -0
  145. package/dist/host/compiler-session.mjs +2980 -0
  146. package/dist/host/compiler-session.mjs.macro-origins.json +1 -0
  147. package/dist/host/compiler-session.mjs.map +1 -0
  148. package/dist/host/compiler-tools.mjs +1084 -0
  149. package/dist/host/compiler-tools.mjs.macro-origins.json +1 -0
  150. package/dist/host/compiler-tools.mjs.map +1 -0
  151. package/dist/literal-sources/runtime/core/collection-internals.eli +60 -0
  152. package/dist/literal-sources/runtime/core/collection.eli +639 -0
  153. package/dist/literal-sources/runtime/core/data-text.eli +290 -0
  154. package/dist/literal-sources/runtime/core/data.eli +22 -0
  155. package/dist/literal-sources/runtime/core/identifier.eli +44 -0
  156. package/dist/literal-sources/runtime/core/lazy-sequence.eli +131 -0
  157. package/dist/literal-sources/runtime/core/list.eli +19 -0
  158. package/dist/literal-sources/runtime/core/map.eli +9 -0
  159. package/dist/literal-sources/runtime/core/metadata-internals.eli +6 -0
  160. package/dist/literal-sources/runtime/core/metadata.eli +40 -0
  161. package/dist/literal-sources/runtime/core/object.eli +8 -0
  162. package/dist/literal-sources/runtime/core/order.eli +123 -0
  163. package/dist/literal-sources/runtime/core/persistent-kind.eli +28 -0
  164. package/dist/literal-sources/runtime/core/protocol-error.eli +32 -0
  165. package/dist/literal-sources/runtime/core/protocol.eli +28 -0
  166. package/dist/literal-sources/runtime/core/queue.eli +9 -0
  167. package/dist/literal-sources/runtime/core/record.eli +191 -0
  168. package/dist/literal-sources/runtime/core/regex.eli +158 -0
  169. package/dist/literal-sources/runtime/core/sequence.eli +305 -0
  170. package/dist/literal-sources/runtime/core/set-algebra.eli +28 -0
  171. package/dist/literal-sources/runtime/core/set.eli +9 -0
  172. package/dist/literal-sources/runtime/core/sorted.eli +408 -0
  173. package/dist/literal-sources/runtime/core/text.eli +14 -0
  174. package/dist/literal-sources/runtime/core/transducer.eli +268 -0
  175. package/dist/literal-sources/runtime/core/transient.eli +17 -0
  176. package/dist/literal-sources/runtime/core/truth.eli +4 -0
  177. package/dist/literal-sources/runtime/core/type.eli +232 -0
  178. package/dist/literal-sources/runtime/core/value-internals.eli +13 -0
  179. package/dist/literal-sources/runtime/core/value.eli +19 -0
  180. package/dist/literal-sources/runtime/core/vector.eli +25 -0
  181. package/dist/literal-sources/runtime/literals.eli +23 -0
  182. package/dist/literal-sources/runtime/testing/value.eli +6 -0
  183. package/dist/literal-sources/runtime/wire/http-rpc.eli +362 -0
  184. package/dist/literal-sources/runtime/wire/markdown.eli +275 -0
  185. package/dist/literal-sources/runtime/wire/schema.eli +193 -0
  186. package/dist/literal-sources/stdlib/bit.eli +36 -0
  187. package/dist/literal-sources/stdlib/core/data.eli +306 -0
  188. package/dist/literal-sources/stdlib/core/object.eli +89 -0
  189. package/dist/literal-sources/stdlib/core/protocol.eli +451 -0
  190. package/dist/literal-sources/stdlib/core/set.eli +312 -0
  191. package/dist/literal-sources/stdlib/core/text.eli +103 -0
  192. package/dist/literal-sources/stdlib/managed-literal-protocols.eli +494 -0
  193. package/dist/literal-sources/stdlib/managed-literals.eli +1469 -0
  194. package/dist/literal-sources/stdlib/managed-queue-state.eli +65 -0
  195. package/dist/literal-sources/stdlib/managed-sorted-state.eli +233 -0
  196. package/dist/literal-sources/stdlib/managed-transient-state.eli +348 -0
  197. package/dist/literal-sources/stdlib/managed-value-state.eli +153 -0
  198. package/dist/literal-sources/stdlib/managed-vector-view-state.eli +102 -0
  199. package/dist/literal-sources/stdlib/persistent-list.eli +145 -0
  200. package/dist/literal-sources/stdlib/persistent-map.eli +724 -0
  201. package/dist/literal-sources/stdlib/persistent-set.eli +236 -0
  202. package/dist/literal-sources/stdlib/persistent-vector.eli +359 -0
  203. package/dist/literal-sources/stdlib/value.eli +325 -0
  204. package/dist/package.json +10 -0
  205. package/dist/runtime/math.mjs +1116 -0
  206. package/dist/runtime/math.mjs.macro-origins.json +1 -0
  207. package/dist/runtime/math.mjs.map +1 -0
  208. package/dist/runtime/unicode-case-data.mjs +10124 -0
  209. package/dist/runtime/unicode-case-data.mjs.macro-origins.json +1 -0
  210. package/dist/runtime/unicode-case-data.mjs.map +1 -0
  211. package/dist/runtime/unicode-case.mjs +280 -0
  212. package/dist/runtime/unicode-case.mjs.macro-origins.json +1 -0
  213. package/dist/runtime/unicode-case.mjs.map +1 -0
  214. package/dist/runtime.eli +30379 -0
  215. package/dist/stage3-release.json +1 -0
  216. package/editor/README.md +1 -1
  217. package/editor/eliscript-mode.el +1 -1
  218. package/editor/eliscript-repl.el +1 -1
  219. package/package.json +106 -11
  220. package/platform/http.mjs +20 -0
  221. package/runtime/array-text.mjs +159 -0
  222. package/runtime/core/map-internals.mjs +27 -9
  223. package/runtime/core/object-impl.mjs +26 -17
  224. package/runtime/core/object-impl.mjs.map +1 -1
  225. package/runtime/core/protocol-impl.mjs +682 -255
  226. package/runtime/core/protocol-impl.mjs.map +1 -1
  227. package/runtime/core/protocol.mjs +4 -0
  228. package/runtime/core/record.mjs +23 -2
  229. package/runtime/core/regex.mjs +4 -0
  230. package/runtime/core/sorted.mjs +53 -0
  231. package/runtime/core/text-impl.mjs +167 -48
  232. package/runtime/core/text-impl.mjs.map +1 -1
  233. package/runtime/core/type.mjs +75 -3
  234. package/runtime/core/vector.mjs +6 -0
  235. package/runtime/math.eli +429 -0
  236. package/runtime/math.mjs +1116 -0
  237. package/runtime/math.mjs.map +1 -0
  238. package/runtime/number-radix.mjs +105 -0
  239. package/runtime/unicode-case-data.eli +29 -0
  240. package/runtime/unicode-case-data.mjs +10124 -0
  241. package/runtime/unicode-case-data.mjs.map +1 -0
  242. package/runtime/unicode-case.eli +100 -0
  243. package/runtime/unicode-case.mjs +280 -0
  244. package/runtime/unicode-case.mjs.map +1 -0
  245. package/runtime/wire/http-rpc.mjs +168 -0
  246. package/runtime/wire/markdown.mjs +196 -0
  247. package/runtime/wire/schema.mjs +109 -0
  248. package/stdlib/README.md +54 -0
  249. package/stdlib/core/protocol.eli +81 -17
  250. package/stdlib/core/seq.eli +1 -1
  251. package/stdlib/core/zipper.eli +172 -72
  252. package/stdlib/gepo.eli +12 -0
  253. package/stdlib/interop/js.eli +56 -15
  254. package/stdlib/managed-literal-protocols.eli +494 -0
  255. package/stdlib/managed-literals.eli +1469 -0
  256. package/stdlib/managed-protocol-error.eli +32 -0
  257. package/stdlib/managed-queue-state.eli +65 -0
  258. package/stdlib/managed-runtime-collection-internals.eli +60 -0
  259. package/stdlib/managed-runtime-collection.eli +639 -0
  260. package/stdlib/managed-runtime-data-text.eli +290 -0
  261. package/stdlib/managed-runtime-data.eli +22 -0
  262. package/stdlib/managed-runtime-identifier.eli +44 -0
  263. package/stdlib/managed-runtime-lazy-sequence.eli +131 -0
  264. package/stdlib/managed-runtime-list.eli +19 -0
  265. package/stdlib/managed-runtime-literals.eli +23 -0
  266. package/stdlib/managed-runtime-map.eli +9 -0
  267. package/stdlib/managed-runtime-metadata-internals.eli +6 -0
  268. package/stdlib/managed-runtime-metadata.eli +40 -0
  269. package/stdlib/managed-runtime-object.eli +8 -0
  270. package/stdlib/managed-runtime-order.eli +123 -0
  271. package/stdlib/managed-runtime-persistent-kind.eli +28 -0
  272. package/stdlib/managed-runtime-protocol.eli +28 -0
  273. package/stdlib/managed-runtime-queue.eli +9 -0
  274. package/stdlib/managed-runtime-record.eli +191 -0
  275. package/stdlib/managed-runtime-regex.eli +158 -0
  276. package/stdlib/managed-runtime-sequence.eli +305 -0
  277. package/stdlib/managed-runtime-set-algebra.eli +28 -0
  278. package/stdlib/managed-runtime-set.eli +9 -0
  279. package/stdlib/managed-runtime-sorted.eli +408 -0
  280. package/stdlib/managed-runtime-text.eli +14 -0
  281. package/stdlib/managed-runtime-transducer.eli +268 -0
  282. package/stdlib/managed-runtime-transient.eli +17 -0
  283. package/stdlib/managed-runtime-truth.eli +4 -0
  284. package/stdlib/managed-runtime-type.eli +232 -0
  285. package/stdlib/managed-runtime-value-internals.eli +13 -0
  286. package/stdlib/managed-runtime-value.eli +19 -0
  287. package/stdlib/managed-runtime-vector.eli +25 -0
  288. package/stdlib/managed-sorted-state.eli +233 -0
  289. package/stdlib/managed-testing-value.eli +6 -0
  290. package/stdlib/managed-transient-state.eli +348 -0
  291. package/stdlib/managed-value-state.eli +153 -0
  292. package/stdlib/managed-vector-view-state.eli +102 -0
  293. package/stdlib/managed-wire-http-rpc.eli +362 -0
  294. package/stdlib/managed-wire-markdown.eli +275 -0
  295. package/stdlib/managed-wire-schema.eli +193 -0
  296. package/stdlib/mdp.eli +7 -0
  297. package/stdlib/mds.eli +4 -0
  298. package/stdlib/persistent-vector.eli +23 -6
  299. package/tools/acceptance/check-legacy.mjs +687 -0
  300. package/tools/acceptance/check.eli +431 -0
  301. package/tools/acceptance/compile-evidence.el +49 -0
  302. package/tools/acceptance/finalize-legacy.mjs +498 -0
  303. package/tools/acceptance/finalize.eli +270 -0
  304. package/tools/backends/benchmark.mjs +175 -0
  305. package/tools/backends/build.mjs +135 -0
  306. package/tools/backends/compile.mjs +94 -0
  307. package/tools/backends/compiler-bootstrap.mjs +1001 -0
  308. package/tools/backends/compiler-browser.mjs +361 -0
  309. package/tools/backends/compiler-build.mjs +1628 -0
  310. package/tools/backends/compiler-cli-legacy.mjs +334 -0
  311. package/tools/backends/compiler-cli.mjs +29 -0
  312. package/tools/backends/compiler-corpus-bit.mjs +234 -0
  313. package/tools/backends/compiler-corpus-cli-adapters-legacy.mjs +362 -0
  314. package/tools/backends/compiler-corpus-cli-adapters.mjs +247 -0
  315. package/tools/backends/compiler-corpus-debugging.mjs +221 -0
  316. package/tools/backends/compiler-corpus-emitter.mjs +324 -0
  317. package/tools/backends/compiler-corpus-evaluation-adapters.mjs +65 -0
  318. package/tools/backends/compiler-corpus-execution-legacy.mjs +769 -0
  319. package/tools/backends/compiler-corpus-execution.mjs +3324 -0
  320. package/tools/backends/compiler-corpus-fuzz.mjs +229 -0
  321. package/tools/backends/compiler-corpus-generations.mjs +208 -0
  322. package/tools/backends/compiler-corpus-host-context-legacy.mjs +114 -0
  323. package/tools/backends/compiler-corpus-host-context.mjs +550 -0
  324. package/tools/backends/compiler-corpus-identity-host.mjs +553 -0
  325. package/tools/backends/compiler-corpus-identity-value-adapters-legacy.mjs +298 -0
  326. package/tools/backends/compiler-corpus-identity-value-adapters.mjs +69 -0
  327. package/tools/backends/compiler-corpus-isolated-exports.mjs +21 -0
  328. package/tools/backends/compiler-corpus-legacy.mjs +1155 -0
  329. package/tools/backends/compiler-corpus-literal-provider.mjs +282 -0
  330. package/tools/backends/compiler-corpus-managed-adapters-legacy.mjs +334 -0
  331. package/tools/backends/compiler-corpus-managed-adapters.mjs +937 -0
  332. package/tools/backends/compiler-corpus-managed-cases.mjs +179 -0
  333. package/tools/backends/compiler-corpus-managed-fixtures-legacy.mjs +879 -0
  334. package/tools/backends/compiler-corpus-managed-fixtures.mjs +1287 -0
  335. package/tools/backends/compiler-corpus-matchers.mjs +173 -0
  336. package/tools/backends/compiler-corpus-original-program.mjs +612 -0
  337. package/tools/backends/compiler-corpus-process.mjs +765 -0
  338. package/tools/backends/compiler-corpus-program-driver.mjs +306 -0
  339. package/tools/backends/compiler-corpus-project-adapters-legacy.mjs +497 -0
  340. package/tools/backends/compiler-corpus-project-adapters.mjs +340 -0
  341. package/tools/backends/compiler-corpus-project-entry-host.mjs +511 -0
  342. package/tools/backends/compiler-corpus-project-transport.mjs +151 -0
  343. package/tools/backends/compiler-corpus-raw-fixture-observer.mjs +1438 -0
  344. package/tools/backends/compiler-corpus-raw-language-fixtures.mjs +1456 -0
  345. package/tools/backends/compiler-corpus-raw-math-fixture.mjs +346 -0
  346. package/tools/backends/compiler-corpus-raw-special-fixtures.mjs +523 -0
  347. package/tools/backends/compiler-corpus-reference-legacy.mjs +263 -0
  348. package/tools/backends/compiler-corpus-reference.mjs +241 -0
  349. package/tools/backends/compiler-corpus-runtime-adapters-legacy.mjs +843 -0
  350. package/tools/backends/compiler-corpus-runtime-adapters.mjs +663 -0
  351. package/tools/backends/compiler-corpus-source-archive.mjs +206 -0
  352. package/tools/backends/compiler-corpus-tools-artifact-adapters.mjs +410 -0
  353. package/tools/backends/compiler-corpus-tools-cli.mjs +363 -0
  354. package/tools/backends/compiler-corpus-tools-reference.mjs +264 -0
  355. package/tools/backends/compiler-corpus.mjs +2054 -0
  356. package/tools/backends/compiler-debug.mjs +142 -0
  357. package/tools/backends/compiler-matrix.mjs +1955 -0
  358. package/tools/backends/compiler-metadata.mjs +203 -0
  359. package/tools/backends/compiler-package-browser.mjs +120 -0
  360. package/tools/backends/compiler-package-legacy.mjs +654 -0
  361. package/tools/backends/compiler-package.mjs +464 -0
  362. package/tools/backends/compiler-project.mjs +126 -0
  363. package/tools/backends/compiler-session.mjs +843 -0
  364. package/tools/backends/compiler-sha256.mjs +152 -0
  365. package/tools/backends/compiler-unicode-profile-host.mjs +196 -0
  366. package/tools/backends/compiler-worker.mjs +573 -0
  367. package/tools/backends/dist/bootstrap-js-stages.mjs +919 -0
  368. package/tools/backends/dist/bootstrap-js-stages.mjs.map +1 -0
  369. package/tools/backends/dist/managed-ir-inventory.mjs +488 -0
  370. package/tools/backends/dist/managed-ir-inventory.mjs.map +1 -0
  371. package/tools/backends/dist/record-grid.mjs +1256 -0
  372. package/tools/backends/dist/record-grid.mjs.map +1 -0
  373. package/tools/backends/dist/release-cli.mjs +462 -0
  374. package/tools/backends/dist/release-cli.mjs.map +1 -0
  375. package/tools/backends/dist/run-artifact.mjs +517 -0
  376. package/tools/backends/dist/run-artifact.mjs.map +1 -0
  377. package/tools/backends/eliscript/compiler-corpus-bit.eli +77 -0
  378. package/tools/backends/eliscript/compiler-corpus-debugging.eli +70 -0
  379. package/tools/backends/eliscript/compiler-corpus-project-entry-host.eli +256 -0
  380. package/tools/backends/managed-foreign-binding.mjs +497 -0
  381. package/tools/backends/managed-host-legacy.mjs +1181 -0
  382. package/tools/backends/managed-host-lifecycle.mjs +310 -0
  383. package/tools/backends/managed-host-object-provider.mjs +155 -0
  384. package/tools/backends/managed-host-object-realm.mjs +797 -0
  385. package/tools/backends/managed-host-proxy.mjs +71 -0
  386. package/tools/backends/managed-host-runtime.mjs +5868 -0
  387. package/tools/backends/managed-host.mjs +716 -0
  388. package/tools/backends/managed-module-graph-legacy.mjs +308 -0
  389. package/tools/backends/managed-module-graph.mjs +694 -0
  390. package/tools/backends/managed-runtime-host-legacy.mjs +195 -0
  391. package/tools/backends/managed-runtime.mjs +939 -0
  392. package/tools/backends/managed-source-view-legacy.mjs +332 -0
  393. package/tools/backends/managed-source-view.mjs +959 -0
  394. package/tools/backends/memory-runtime.mjs +100 -0
  395. package/tools/backends/native-benchmark.mjs +88 -0
  396. package/tools/backends/native-managed-runtime.mjs +677 -0
  397. package/tools/backends/native-memory.mjs +768 -0
  398. package/tools/backends/native-node-memory.mjs +142 -0
  399. package/tools/backends/native-node-runner.mjs +99 -0
  400. package/tools/backends/native-node-watchdog.mjs +19 -0
  401. package/tools/backends/native-node-worker.mjs +75 -0
  402. package/tools/backends/stage3-targets.mjs +493 -0
  403. package/tools/bootstrap-command.el +13 -0
  404. package/tools/bootstrap-runtime.el +101 -0
  405. package/tools/bootstrap-seed.el +55 -0
  406. package/tools/project/check-cli.eli +31 -0
  407. package/tools/project/project-cli.eli +42 -0
  408. package/tools/project/project.eli +122 -0
  409. package/tools/runtime/unicode-case-profiles.mjs +13 -0
  410. package/tools/runtime/unicode-case-runtime.el +57 -0
  411. package/tools/testing/source-debugging-corpus-host.eli +16 -0
  412. package/tools/testing/source-debugging.eli +139 -0
  413. package/tools/testing/stdlib-bit-corpus-host.eli +21 -0
  414. package/tools/testing/stdlib-bit-corpus-host.mjs +118 -0
  415. package/tools/testing/stdlib-bit.eli +104 -0
  416. package/tools/testing/stdlib-bit.mjs +255 -0
  417. package/bin/eliscript-bootstrap +0 -15
@@ -0,0 +1,1001 @@
1
+ import {createHash,randomUUID} from 'node:crypto';
2
+ import {mkdir,readFile,writeFile,rename,mkdtemp,lstat,open} from 'node:fs/promises';
3
+ import {createReadStream} from 'node:fs';
4
+ import {resolve,join,dirname,relative,sep} from 'node:path';
5
+ import {pathToFileURL} from 'node:url';
6
+ import {root} from './build.mjs';
7
+ import {loadCompilerSources,buildIndependentCompiler,independentCompilerProductIdentity,compilerMetadataDigest,writeCompilerMetadata} from './compiler-build.mjs';
8
+ import {createCompilerSession,registerCompilerBuildProductForwarder,registerVerifiedCompilerBuildConsumption} from './compiler-session.mjs';
9
+ import {decodeCompilerMetadataBytes,createCompilerMetadataDecoder} from './compiler-metadata.mjs';
10
+ import {ownCompilerDebugDocument} from './compiler-debug.mjs';
11
+
12
+ export const compilerHosts=Object.freeze(['javascript','wasm','native']);
13
+ const verifiedCompilerBuildSessions=new WeakSet();
14
+
15
+ export function isVerifiedCompilerBuildSession(session) {
16
+ return verifiedCompilerBuildSessions.has(session);
17
+ }
18
+
19
+ export function normalizeCompilerHost(value) {
20
+ const host=value==='js'?'javascript':value;
21
+ if(!compilerHosts.includes(host))throw new TypeError('compiler host must be javascript, wasm or native');
22
+ return host;
23
+ }
24
+
25
+ export function compilerDigest(bytes) {
26
+ return createHash('sha256').update(bytes).digest('hex');
27
+ }
28
+
29
+ export async function saveCompilerMetadata(path,value) {
30
+ const temporary=path+'.'+randomUUID()+'.tmp';
31
+ await writeCompilerMetadata(temporary,value,{flag:'wx'});
32
+ await rename(temporary,path);
33
+ }
34
+
35
+ function failureProperty(value,name) {
36
+ try{return value?.[name];}catch{return undefined;}
37
+ }
38
+
39
+ function failureText(value,fallback) {
40
+ try{return String(value);}catch{return fallback;}
41
+ }
42
+
43
+ function failureData(value,ancestors=new Set()) {
44
+ if(value===null||value===undefined||typeof value==='string'||typeof value==='boolean'||typeof value==='number')return value;
45
+ if(typeof value==='bigint')return value.toString();
46
+ if(typeof value!=='object')return undefined;
47
+ if(ancestors.has(value)||ancestors.size>=64)return {truncatedCause:true};
48
+ const path=new Set(ancestors);path.add(value);
49
+ try{
50
+ if(Array.isArray(value)){
51
+ const result=[];
52
+ for(let index=0;index<value.length;index++)result.push(failureData(failureProperty(value,index),path));
53
+ return result;
54
+ }
55
+ const result={};
56
+ for(const key of Object.keys(value)){
57
+ const item=failureData(failureProperty(value,key),path);
58
+ if(item!==undefined)Object.defineProperty(result,key,{value:item,enumerable:true,writable:true,configurable:true});
59
+ }
60
+ return result;
61
+ }catch{return {truncatedCause:true};}
62
+ }
63
+
64
+ export function compilerFailure(error,ancestors=new Set()) {
65
+ const name=failureProperty(error,'name'),message=failureProperty(error,'message');
66
+ const record={name:name==null?'Error':failureText(name,'Error'),
67
+ message:message==null?failureText(error,'unavailable error'):failureText(message,'unavailable error')};
68
+ if(error!==null&&(typeof error==='object'||typeof error==='function')){
69
+ if(ancestors.has(error)||ancestors.size>=64)return {...record,truncatedCause:true};
70
+ ancestors=new Set(ancestors);ancestors.add(error);
71
+ }
72
+ const stack=failureProperty(error,'stack');
73
+ if(stack!==undefined)record.stack=failureText(stack,'unavailable stack');
74
+ for(const key of ['eliscriptDiagnostic','diagnostics','macroOrigins','code','eliscriptFrames','eliscriptSourceFrames']){
75
+ const field=failureProperty(error,key);
76
+ if(field===undefined)continue;
77
+ if(key==='eliscriptFrames'||key==='eliscriptSourceFrames'){
78
+ try{if(!Array.isArray(field))continue;}catch{continue;}
79
+ }
80
+ const data=failureData(field,ancestors);
81
+ if(data!==undefined)record[key]=data;
82
+ }
83
+ const errors=failureProperty(error,'errors');
84
+ if(errors!==undefined){
85
+ try{
86
+ if(Array.isArray(errors)){
87
+ if(ancestors.has(errors)||ancestors.size>=64)record.errors={truncatedCause:true};
88
+ else{
89
+ const path=new Set(ancestors);path.add(errors);
90
+ record.errors=[];
91
+ for(let index=0;index<errors.length;index++)record.errors.push(compilerFailure(failureProperty(errors,index),path));
92
+ }
93
+ }else record.errors=failureData(errors,ancestors);
94
+ }catch{record.errors={truncatedCause:true};}
95
+ }
96
+ const cause=failureProperty(error,'cause');
97
+ if(cause!==undefined)record.cause=compilerFailure(cause,ancestors);
98
+ return record;
99
+ }
100
+
101
+ function moduleId(id) {
102
+ if(typeof id!=='string'||!id||/[\\:\u0000]/.test(id)||id.split('/').some(part=>!part||part==='.'||part==='..'))
103
+ throw new TypeError('compiler module requires a relative source identity');
104
+ return id;
105
+ }
106
+
107
+ function sourceDeclarationData(value,ancestors=new Set()) {
108
+ if(value===null||typeof value==='string'||typeof value==='boolean')return value;
109
+ if(typeof value==='number'&&Number.isFinite(value))return value;
110
+ if(typeof value!=='object'||ancestors.has(value))throw new TypeError('host declarations require finite JSON data');
111
+ const prototype=Object.getPrototypeOf(value);
112
+ if(!Array.isArray(value)&&prototype!==Object.prototype&&prototype!==null)
113
+ throw new TypeError('host declarations require plain JSON records');
114
+ if(Object.getOwnPropertySymbols(value).length)throw new TypeError('host declarations cannot contain symbol keys');
115
+ const path=new Set(ancestors);path.add(value);
116
+ if(Array.isArray(value)){
117
+ const result=[];
118
+ if(Object.keys(value).length!==value.length)throw new TypeError('host declarations require dense JSON arrays');
119
+ for(let index=0;index<value.length;index++){
120
+ if(!Object.hasOwn(value,index))throw new TypeError('host declarations require dense JSON arrays');
121
+ result.push(sourceDeclarationData(value[index],path));
122
+ }
123
+ return result;
124
+ }
125
+ return Object.fromEntries(Object.keys(value).sort().map(key=>[key,sourceDeclarationData(value[key],path)]));
126
+ }
127
+
128
+ function compilerSourceTextDigest(source) {
129
+ // Source identities bind code units, including lone surrogates and BOM.
130
+ // Keep compilerDigest byte-oriented for emitted binaries and other assets.
131
+ const hash=createHash('sha256');
132
+ forEachCompilerSourceBytes(source,'utf16le',bytes=>hash.update(bytes));
133
+ return {encoding:'utf16le',sha256:hash.digest('hex'),bytes:source.length*2};
134
+ }
135
+
136
+ function compilerSourceDeclaration(sources) {
137
+ const inputModules=sources?.modules;
138
+ if(!Array.isArray(inputModules)||!inputModules.length)
139
+ throw new TypeError('complete compiler modules and runtime source are required');
140
+ const inputRuntime=sources.runtime,runtimeSource=inputRuntime?.source;
141
+ if(!inputRuntime||typeof runtimeSource!=='string')throw new TypeError('complete compiler modules and runtime source are required');
142
+ const snapshot={modules:[]};
143
+ const ids=new Set();
144
+ const modules=inputModules.map(record=>{
145
+ const id=moduleId(record?.id);
146
+ if(ids.has(id))throw new TypeError('invalid compiler source record');
147
+ const source=record.source;
148
+ if(typeof source!=='string')throw new TypeError('invalid compiler source record');
149
+ const filename=record.filename;
150
+ if(typeof filename!=='string')throw new TypeError('invalid compiler source record');
151
+ ids.add(id);
152
+ snapshot.modules.push({id,filename,source});
153
+ return {id,filename,...compilerSourceTextDigest(source)};
154
+ }).sort((a,b)=>a.id<b.id?-1:a.id>b.id?1:0);
155
+ const entry=sources.entry;
156
+ if(!ids.has(entry))throw new TypeError('compiler entry and runtime filename are required');
157
+ const runtimeFilename=inputRuntime.filename;
158
+ if(typeof runtimeFilename!=='string')throw new TypeError('compiler entry and runtime filename are required');
159
+ snapshot.entry=entry;snapshot.runtime={filename:runtimeFilename,source:runtimeSource};
160
+ const identity={encoding:'utf16le',entry,modules,runtime:{filename:runtimeFilename,...compilerSourceTextDigest(runtimeSource)}};
161
+ if(Object.hasOwn(sources,'hostModules')){
162
+ const records=sources.hostModules;
163
+ if(!Array.isArray(records))throw new TypeError('compiler hostModules must be an array');
164
+ identity.hostModules=sourceDeclarationData(records);snapshot.hostModules=identity.hostModules;
165
+ }
166
+ if(Object.hasOwn(sources,'hostSources')){
167
+ const records=sources.hostSources;
168
+ if(!Array.isArray(records))throw new TypeError('compiler hostSources must be an array');
169
+ snapshot.hostSources=[];
170
+ identity.hostSources=records.map(record=>{
171
+ const id=moduleId(record?.id),filename=record.filename??id;
172
+ if(ids.has(id))throw new TypeError('invalid compiler host source record');
173
+ const source=record.source;
174
+ if(typeof source!=='string'||typeof filename!=='string')throw new TypeError('invalid compiler host source record');
175
+ ids.add(id);
176
+ snapshot.hostSources.push({id,filename,source});return {id,filename,...compilerSourceTextDigest(source)};
177
+ });
178
+ }
179
+ if(Object.hasOwn(sources,'phased')){
180
+ const phased=sources.phased;
181
+ if(typeof phased!=='boolean')throw new TypeError('compiler phased input must be boolean');
182
+ identity.phased=phased;snapshot.phased=phased;
183
+ }
184
+ if(Object.hasOwn(sources,'literalSources')){
185
+ const records=sources.literalSources;
186
+ if(!Array.isArray(records))throw new TypeError('compiler literalSources must be an array');
187
+ snapshot.literalSources=[];
188
+ identity.literalSources=records.map(record=>{
189
+ const id=moduleId(record?.id);
190
+ if(ids.has(id))throw new TypeError('invalid or colliding persistent literal source');
191
+ const filename=record.filename;
192
+ if(typeof filename!=='string')throw new TypeError('invalid or colliding persistent literal source');
193
+ const source=record.source;
194
+ if(typeof source!=='string')throw new TypeError('invalid or colliding persistent literal source');
195
+ ids.add(id);
196
+ snapshot.literalSources.push({id,filename,source});return {id,filename,...compilerSourceTextDigest(source)};
197
+ });
198
+ }
199
+ return {sources:snapshot,identity:{...identity,sha256:compilerSourceTextDigest(JSON.stringify(identity)).sha256}};
200
+ }
201
+
202
+ export function compilerSourceIdentity(sources) {return compilerSourceDeclaration(sources).identity;}
203
+
204
+ function forEachCompilerSourceBytes(source,encoding,consume){
205
+ for(let offset=0;offset<source.length;){
206
+ let end=Math.min(source.length,offset+(encoding==='utf8'?16384:32768));
207
+ // UTF8 replaces lone halves but must not manufacture them at our boundary.
208
+ if(encoding==='utf8'&&end<source.length&&source.charCodeAt(end-1)>=0xd800&&source.charCodeAt(end-1)<=0xdbff&&
209
+ source.charCodeAt(end)>=0xdc00&&source.charCodeAt(end)<=0xdfff)end--;
210
+ consume(Buffer.from(source.slice(offset,end),encoding));offset=end;
211
+ }
212
+ }
213
+
214
+ async function writeCompilerSourceText(path,source,encoding){
215
+ const file=await open(path,'wx'),hash=createHash('sha256');let bytes=0,failed=false;
216
+ try{
217
+ // Each block is consumed before its source slice can be released. Avoid
218
+ // either full encoded representation beside the complete source string.
219
+ for(let offset=0;offset<source.length;){
220
+ let end=Math.min(source.length,offset+(encoding==='utf8'?16384:32768));
221
+ if(encoding==='utf8'&&end<source.length&&source.charCodeAt(end-1)>=0xd800&&source.charCodeAt(end-1)<=0xdbff&&
222
+ source.charCodeAt(end)>=0xdc00&&source.charCodeAt(end)<=0xdfff)end--;
223
+ const block=Buffer.from(source.slice(offset,end),encoding);hash.update(block);bytes+=block.length;
224
+ let position=0;
225
+ while(position<block.length){
226
+ const {bytesWritten}=await file.write(block,position,block.length-position,null);
227
+ if(!Number.isInteger(bytesWritten)||bytesWritten<1||bytesWritten>block.length-position)
228
+ throw new Error('compiler source archive write did not advance');
229
+ position+=bytesWritten;
230
+ }
231
+ offset=end;
232
+ }
233
+ return{bytes,sha256:hash.digest('hex')};
234
+ }catch(error){failed=true;throw error;}
235
+ finally{try{await file.close();}catch(error){if(!failed)throw error;}}
236
+ }
237
+
238
+ export async function archiveCompilerSources(sources,directory) {
239
+ // Only declaration fields participate. Capture primitive source values
240
+ // synchronously, without cloning unrelated caller fields or rereading a
241
+ // source getter after the first asynchronous filesystem operation.
242
+ const declaration=compilerSourceDeclaration(sources),identity=declaration.identity;
243
+ sources=declaration.sources;
244
+ await mkdir(directory,{recursive:true});
245
+ const records=[];
246
+ async function archive(kind,record,index){
247
+ const path=kind==='runtime'?'source-codeunits/runtime.utf16le':
248
+ 'source-codeunits/'+kind+'/'+String(index).padStart(4,'0')+'.utf16le';
249
+ const toolPath=compilerArchivedToolPath(kind,record.id);
250
+ await mkdir(dirname(join(directory,path)),{recursive:true});
251
+ await mkdir(dirname(join(directory,toolPath)),{recursive:true});
252
+ const raw=await writeCompilerSourceText(join(directory,path),record.source,'utf16le');
253
+ const tool=await writeCompilerSourceText(join(directory,toolPath),record.source,'utf8');
254
+ records.push({kind,id:kind==='runtime'?null:record.id,filename:record.filename,
255
+ path,encoding:'utf16le',...raw,
256
+ tool:{path:toolPath,encoding:'utf8',...tool,
257
+ role:'tool-projection',lossless:compilerSourceToolLossless(record.source)}});
258
+ }
259
+ for(let index=0;index<sources.modules.length;index++)await archive('module',sources.modules[index],index);
260
+ for(let index=0;index<(sources.hostSources?.length??0);index++)await archive('host',sources.hostSources[index],index);
261
+ for(let index=0;index<(sources.literalSources?.length??0);index++)await archive('literal',sources.literalSources[index],index);
262
+ await archive('runtime',sources.runtime,0);
263
+ await saveCompilerMetadata(join(directory,'identity.json'),identity);
264
+ await saveCompilerMetadata(join(directory,'source-archive.json'),{
265
+ format:'eliscript-compiler-source-archive',version:1,encoding:'utf16le',
266
+ identityPath:'identity.json',identitySha256:identity.sha256,records,
267
+ });
268
+ return identity;
269
+ }
270
+
271
+ function compilerArchivedToolPath(kind,id){
272
+ if(kind==='runtime')return'runtime.eli';
273
+ if(kind==='module')return'modules/'+moduleId(id)+'.eli';
274
+ if(kind==='host')return'host-sources/'+moduleId(id);
275
+ if(kind==='literal')return'literal-sources/'+moduleId(id)+'.eli';
276
+ throw new TypeError('unknown archived compiler source kind');
277
+ }
278
+
279
+ function compilerSourceToolLossless(source){
280
+ for(let index=0;index<source.length;index++){
281
+ const unit=source.charCodeAt(index);
282
+ if(unit>=0xd800&&unit<=0xdbff){
283
+ const next=source.charCodeAt(index+1);if(!(next>=0xdc00&&next<=0xdfff))return false;index++;
284
+ }else if(unit>=0xdc00&&unit<=0xdfff)return false;
285
+ }
286
+ return true;
287
+ }
288
+
289
+ async function compilerArchivedSourceBytes(directory,path,consume){
290
+ moduleId(path);
291
+ const parts=path.split('/');
292
+ for(let index=0;index<parts.length;index++){
293
+ const stat=await lstat(resolve(directory,...parts.slice(0,index+1)));
294
+ if(index===parts.length-1?!stat.isFile():!stat.isDirectory())
295
+ throw new Error('compiler source archive contains an unsupported file entry: '+path);
296
+ }
297
+ const file=await open(resolve(directory,path),'r'),buffer=Buffer.allocUnsafe(65536),hash=createHash('sha256');
298
+ let bytes=0,failed=false;
299
+ try{
300
+ for(;;){
301
+ const {bytesRead}=await file.read(buffer,0,buffer.length,null);
302
+ if(!Number.isInteger(bytesRead)||bytesRead<0||bytesRead>buffer.length)
303
+ throw new Error('compiler source archive read returned an invalid byte count');
304
+ if(bytesRead===0)break;
305
+ const block=buffer.subarray(0,bytesRead);hash.update(block);bytes+=bytesRead;consume(block);
306
+ }
307
+ return{bytes,sha256:hash.digest('hex')};
308
+ }catch(error){failed=true;throw error;}
309
+ finally{try{await file.close();}catch(error){if(!failed)throw error;}}
310
+ }
311
+
312
+ function compilerArchivedSourceFile(record,actual,label){
313
+ if(!Number.isSafeInteger(record?.bytes)||record.bytes<0||!/^[0-9a-f]{64}$/.test(record.sha256??'')||
314
+ actual.bytes!==record.bytes||actual.sha256!==record.sha256)
315
+ throw new Error('compiler source archive '+label+' bytes differ from their identity');
316
+ }
317
+
318
+ async function readCompilerArchivedJSON(directory,path){
319
+ const decoder=new TextDecoder('utf-8',{fatal:true}),parser=createCompilerMetadataDecoder();
320
+ let decodeFailed=false,decodeFailure,parseFailed=false,parseFailure;
321
+ // readFile used to finish before UTF8 decoding, then JSON parsing. Continue
322
+ // bounded reads after a parser failure so later I/O/UTF8 failures retain
323
+ // their original higher priority, including failures across byte seams.
324
+ await compilerArchivedSourceBytes(directory,path,block=>{
325
+ if(decodeFailed)return;
326
+ let text;
327
+ try{text=decoder.decode(block,{stream:true});}
328
+ catch(error){decodeFailed=true;decodeFailure=error;return;}
329
+ if(!parseFailed)try{parser.write(text);}catch(error){parseFailed=true;parseFailure=error;}
330
+ });
331
+ if(decodeFailed)throw decodeFailure;
332
+ const tail=decoder.decode();
333
+ if(parseFailed)throw parseFailure;
334
+ parser.write(tail);return parser.finish();
335
+ }
336
+
337
+ function* compilerSourceUTF8Blocks(source){
338
+ for(let offset=0;offset<source.length;){
339
+ let end=Math.min(source.length,offset+16384);
340
+ if(end<source.length&&source.charCodeAt(end-1)>=0xd800&&source.charCodeAt(end-1)<=0xdbff&&
341
+ source.charCodeAt(end)>=0xdc00&&source.charCodeAt(end)<=0xdfff)end--;
342
+ yield Buffer.from(source.slice(offset,end),'utf8');offset=end;
343
+ }
344
+ }
345
+
346
+ export async function readArchivedCompilerSources(directory,{expectedIdentity}={}){
347
+ const readJSON=path=>readCompilerArchivedJSON(directory,path);
348
+ const manifest=await readJSON('source-archive.json'),identity=await readJSON('identity.json');
349
+ if(manifest?.format!=='eliscript-compiler-source-archive'||manifest.version!==1||manifest.encoding!=='utf16le'||
350
+ manifest.identityPath!=='identity.json'||!Array.isArray(manifest.records)||identity?.encoding!=='utf16le'||
351
+ !/^[0-9a-f]{64}$/.test(identity.sha256??'')||manifest.identitySha256!==identity.sha256)
352
+ throw new TypeError('invalid compiler source archive identity');
353
+ if(expectedIdentity!==undefined){
354
+ const expected=typeof expectedIdentity==='string'?expectedIdentity:expectedIdentity?.sha256;
355
+ if(!/^[0-9a-f]{64}$/.test(expected??'')||expected!==identity.sha256)
356
+ throw new Error('compiler source archive differs from the expected source identity');
357
+ }
358
+ const expected=new Map(),seenIds=new Set();
359
+ const sources={entry:identity.entry,modules:[],runtime:undefined};
360
+ function inventory(kind,records){
361
+ if(!Array.isArray(records))throw new TypeError('compiler source archive has an incomplete source inventory');
362
+ for(const record of records){
363
+ const id=moduleId(record?.id);
364
+ if(seenIds.has(id)||typeof record.filename!=='string')throw new TypeError('duplicate or invalid archived compiler source identity');
365
+ seenIds.add(id);expected.set(kind+':'+id,record);
366
+ }
367
+ }
368
+ inventory('module',identity.modules);
369
+ if(!identity.runtime||typeof identity.runtime.filename!=='string')throw new TypeError('compiler source archive omits runtime identity');
370
+ expected.set('runtime',identity.runtime);
371
+ for(const[field,kind]of[['hostSources','host'],['literalSources','literal']])if(Object.hasOwn(identity,field)){
372
+ inventory(kind,identity[field]);sources[field]=[];
373
+ }
374
+ for(const field of ['hostModules','phased'])if(Object.hasOwn(identity,field))sources[field]=structuredClone(identity[field]);
375
+ const paths=new Set(),seen=new Set();
376
+ for(const record of manifest.records){
377
+ const kind=record?.kind;
378
+ if(!['module','host','literal','runtime'].includes(kind))throw new TypeError('invalid archived compiler source kind');
379
+ const key=kind==='runtime'?'runtime':kind+':'+moduleId(record.id),bound=expected.get(key);
380
+ if(!bound||seen.has(key)||kind==='runtime'&&record.id!==null||record.filename!==bound.filename||
381
+ record.encoding!=='utf16le'||bound.encoding!=='utf16le'||record.bytes!==bound.bytes||record.sha256!==bound.sha256)
382
+ throw new Error('compiler source archive record differs from its source identity');
383
+ seen.add(key);
384
+ const path=moduleId(record.path),tool=record.tool;
385
+ if(!/^source-codeunits\/(?:runtime[.]utf16le|(?:module|host|literal)\/[0-9]+[.]utf16le)$/.test(path)||paths.has(path))
386
+ throw new TypeError('invalid or duplicate archived compiler source path');
387
+ paths.add(path);
388
+ if(!tool||tool.path!==compilerArchivedToolPath(kind,record.id)||tool.encoding!=='utf8'||tool.role!=='tool-projection'||typeof tool.lossless!=='boolean')
389
+ throw new TypeError('invalid archived compiler tool projection');
390
+ if(paths.has(tool.path))throw new TypeError('duplicate archived compiler tool projection path');
391
+ paths.add(tool.path);
392
+ const pieces=[];let pendingByte=-1;
393
+ const bytes=await compilerArchivedSourceBytes(directory,path,block=>{
394
+ let offset=0;
395
+ if(pendingByte>=0){pieces.push(String.fromCharCode(pendingByte|(block[0]<<8)));pendingByte=-1;offset=1;}
396
+ const end=block.length-((block.length-offset)%2);
397
+ if(end>offset)pieces.push(block.subarray(offset,end).toString('utf16le'));
398
+ if(end<block.length)pendingByte=block[end];
399
+ });
400
+ compilerArchivedSourceFile(record,bytes,'UTF-16 source');
401
+ if(pendingByte>=0)throw new Error('compiler source archive has an incomplete UTF-16 code unit');
402
+ const source=pieces.join('');pieces.length=0;
403
+ const expectedProjection=compilerSourceUTF8Blocks(source);
404
+ let expectedBlock=expectedProjection.next(),expectedOffset=0,projectionMismatch=false;
405
+ const projection=await compilerArchivedSourceBytes(directory,tool.path,block=>{
406
+ let offset=0;
407
+ while(offset<block.length){
408
+ if(expectedBlock.done){projectionMismatch=true;break;}
409
+ const count=Math.min(block.length-offset,expectedBlock.value.length-expectedOffset);
410
+ if(!block.subarray(offset,offset+count).equals(expectedBlock.value.subarray(expectedOffset,expectedOffset+count)))projectionMismatch=true;
411
+ offset+=count;expectedOffset+=count;
412
+ if(expectedOffset===expectedBlock.value.length){expectedBlock=expectedProjection.next();expectedOffset=0;}
413
+ }
414
+ });
415
+ compilerArchivedSourceFile(tool,projection,'tool projection');
416
+ if(projectionMismatch||!expectedBlock.done||tool.lossless!==compilerSourceToolLossless(source))
417
+ throw new Error('compiler source archive tool projection differs from the exact source');
418
+ if(kind==='runtime')sources.runtime={filename:record.filename,source};
419
+ else sources[kind==='module'?'modules':kind==='host'?'hostSources':'literalSources'].push({id:record.id,filename:record.filename,source});
420
+ }
421
+ if(seen.size!==expected.size||sources.runtime===undefined)
422
+ throw new Error('compiler source archive omits original source records');
423
+ const restored=compilerSourceIdentity(sources);
424
+ if(JSON.stringify(sourceDeclarationData(restored))!==JSON.stringify(sourceDeclarationData(identity)))
425
+ throw new Error('compiler source archive does not restore its complete source identity');
426
+ return sources;
427
+ }
428
+
429
+ async function completeSources(sourceRoot,supplied) {
430
+ const actual=await loadCompilerSources({sourceRoot});
431
+ const expected=compilerSourceIdentity(actual);
432
+ if(supplied&&compilerSourceIdentity(supplied).sha256!==expected.sha256)
433
+ throw new Error('supplied compiler sources differ from the complete source graph');
434
+ return structuredClone(supplied??actual);
435
+ }
436
+
437
+ function assertProducer(artifact,session,sources) {
438
+ assertCompilerArtifactSources(artifact,sources);
439
+ const provenance=artifact?.provenance;
440
+ if(!provenance||provenance.mode!==(session?'session':'seed')||provenance.runtimeCompiled!==true)
441
+ throw new Error('compiler build did not record a complete runtime compilation');
442
+ const wanted=sources.modules.map(record=>record.id).sort();
443
+ const received=provenance.compiledModuleIds;
444
+ if(!Array.isArray(received)||JSON.stringify([...received].sort())!==JSON.stringify(wanted))
445
+ throw new Error('compiler build did not compile every original module');
446
+ if(session&&normalizeCompilerHost(provenance.producerHost)!==normalizeCompilerHost(session.host))
447
+ throw new Error('compiler build producer differs from the active independent session');
448
+ }
449
+
450
+ // Producer metadata is checked against the same complete source bundle that is
451
+ // handed to its session. A matching module inventory alone cannot authenticate
452
+ // a compiler or a cached literal/runtime bundle from an earlier revision.
453
+ export function assertCompilerArtifactSources(artifact,sources) {
454
+ compilerSourceIdentity(sources);
455
+ const identity=artifact?.sourceIdentity;
456
+ if(identity?.algorithm!=='sha256'||identity.encoding!=='utf16le'||artifact.entry!==sources.entry)
457
+ throw new Error('compiler artifact has no complete UTF-16 source identity');
458
+ const record=source=>({id:source.id,filename:source.filename,
459
+ sha256:compilerDigest(Buffer.from(source.source,'utf16le'))});
460
+ const same=(left,right)=>JSON.stringify(left)===JSON.stringify(right);
461
+ const ordered=records=>[...records].sort((left,right)=>left.id<right.id?-1:left.id>right.id?1:0);
462
+ if(!Array.isArray(identity.modules)||!same(ordered(identity.modules),ordered(sources.modules.map(record))))
463
+ throw new Error('compiler artifact differs from the complete frontend/backend/driver source graph');
464
+ const runtime={filename:sources.runtime.filename,sha256:compilerDigest(Buffer.from(sources.runtime.source,'utf16le'))};
465
+ if(!same(identity.runtime,runtime))throw new Error('compiler artifact runtime source is stale');
466
+ for(const field of ['literalSources','hostSources']){
467
+ if(Object.hasOwn(sources,field)){
468
+ if(!Array.isArray(identity[field])||!same(ordered(identity[field]),ordered(sources[field].map(record))))
469
+ throw new Error('compiler artifact '+field+' source graph is stale or incomplete');
470
+ }else if(Object.hasOwn(identity,field))throw new Error('compiler artifact contains undeclared '+field);
471
+ }
472
+ return artifact;
473
+ }
474
+
475
+ async function emittedFileIdentity(path) {
476
+ const hash=createHash('sha256');let bytes=0;
477
+ for await(const chunk of createReadStream(path,{highWaterMark:65536})){
478
+ hash.update(chunk);bytes+=chunk.length;
479
+ }
480
+ return{bytes,sha256:hash.digest('hex')};
481
+ }
482
+
483
+ async function declaredEmittedFiles(directory,declarations) {
484
+ if(!Array.isArray(declarations))throw new TypeError('compiler artifact files must be an array');
485
+ const files=[],seen=new Set();
486
+ for(const declared of declarations){
487
+ const path=moduleId(declared?.path);
488
+ if(seen.has(path))throw new TypeError('duplicate compiler artifact file: '+path);
489
+ seen.add(path);
490
+ const parts=path.split('/');
491
+ for(let index=0;index<parts.length;index++){
492
+ const stat=await lstat(resolve(directory,...parts.slice(0,index+1)));
493
+ if(index===parts.length-1?!stat.isFile():!stat.isDirectory())
494
+ throw new Error('compiler artifact contains an unsupported file entry: '+path);
495
+ }
496
+ const record={path,...await emittedFileIdentity(resolve(directory,path))};
497
+ if(record.sha256!==declared.sha256||record.bytes!==declared.bytes)
498
+ throw new Error('compiler artifact changed after emission: '+path);
499
+ files.push(record);
500
+ }
501
+ return files.sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
502
+ }
503
+
504
+ export async function archiveCompilerArtifact(artifact,directory) {
505
+ const host=normalizeCompilerHost(artifact?.host);
506
+ if(typeof artifact.path!=='string'||typeof artifact.directory!=='string')throw new TypeError('compiler artifact paths are required');
507
+ await mkdir(directory,{recursive:true});
508
+ // Build dependencies are outside the emitted product. Bind only the exact
509
+ // declared deliverables, checking every path component before reading bytes.
510
+ const files=await declaredEmittedFiles(artifact.directory,artifact.artifactIdentity?.files);
511
+ if(!files.length)throw new Error('compiler artifact has no emitted files');
512
+ const entry=relative(resolve(artifact.directory),resolve(artifact.path)).split(sep).join('/');
513
+ if(!files.some(record=>record.path===entry))throw new Error('compiler artifact entry is not an emitted file');
514
+ const payload=await emittedFileIdentity(artifact.path);
515
+ const result={host,entry:artifact.entry,path:artifact.path,directory:artifact.directory,sha256:payload.sha256,bytes:payload.bytes,files,
516
+ provenance:structuredClone(artifact.provenance),sourceIdentity:structuredClone(artifact.sourceIdentity),
517
+ profile:artifact.profile,budget:artifact.budget,memory:artifact.memory,auto:artifact.auto};
518
+ if(artifact.artifactIdentity?.files){
519
+ const actual=new Map(files.map(record=>[record.path,record])),bound=[];
520
+ for(const declared of artifact.artifactIdentity.files){
521
+ const record=actual.get(declared.path);
522
+ if(!record||record.sha256!==declared.sha256||record.bytes!==declared.bytes)throw new Error('compiler artifact changed after emission: '+declared.path);
523
+ bound.push(record);
524
+ }
525
+ result.productIdentity=independentCompilerProductIdentity({host,nativeTarget:artifact.nativeTarget,files:bound,descriptor:artifact.descriptor,typed:artifact.typed});
526
+ if(artifact.productIdentity?.sha256!==result.productIdentity.sha256)throw new Error('compiler product identity differs from its emitted bytes');
527
+ }
528
+ if(artifact.descriptor!==undefined){
529
+ await saveCompilerMetadata(join(directory,'descriptor.json'),artifact.descriptor);
530
+ result.descriptorSha256=compilerMetadataDigest(artifact.descriptor);
531
+ }
532
+ if(artifact.typed!==undefined){
533
+ await saveCompilerMetadata(join(directory,'typed.json'),artifact.typed);
534
+ result.typedSha256=compilerMetadataDigest(artifact.typed);
535
+ }
536
+ await saveCompilerMetadata(join(directory,'artifact.json'),result);
537
+ return result;
538
+ }
539
+
540
+ function compilerArtifactResources(artifact,directory) {
541
+ const declarations=new Map(),declared=artifact.artifactIdentity!==undefined;
542
+ if(declared){
543
+ const identity=artifact.artifactIdentity;
544
+ if(identity?.algorithm!=='sha256'||!Array.isArray(identity.files)||!identity.files.length)
545
+ throw new TypeError('compiler artifact requires a nonempty SHA-256 file identity');
546
+ for(const entry of identity.files){
547
+ const path=moduleId(entry?.path);
548
+ if(declarations.has(path)||!Number.isSafeInteger(entry.bytes)||entry.bytes<0||!/^[0-9a-f]{64}$/.test(entry.sha256??''))
549
+ throw new TypeError('invalid or duplicate compiler resource identity: '+path);
550
+ declarations.set(path,{path,bytes:entry.bytes,sha256:entry.sha256});
551
+ }
552
+ }
553
+ function pathFor(path){
554
+ if(typeof path!=='string'||!path)throw new TypeError('compiler resource path is required');
555
+ return moduleId(relative(directory,resolve(directory,path)).split(sep).join('/'));
556
+ }
557
+ function binding(path){
558
+ const key=pathFor(path),entry=declarations.get(key);
559
+ if(declared&&!entry)throw new Error('compiler resource has no emitted file identity: '+key);
560
+ return{key,entry};
561
+ }
562
+ function check(path,bytes){
563
+ const {key,entry}=binding(path);
564
+ if(entry&&(bytes.byteLength!==entry.bytes||compilerDigest(bytes)!==entry.sha256))
565
+ throw new Error('compiler resource SHA-256 or byte length identity changed after emission: '+key);
566
+ return bytes;
567
+ }
568
+ async function prepare(path){
569
+ const resource=binding(path),{key}=resource,parts=key.split('/');
570
+ for(let index=0;index<parts.length;index++){
571
+ const stat=await lstat(resolve(directory,...parts.slice(0,index+1)));
572
+ if(index===parts.length-1?!stat.isFile():!stat.isDirectory())
573
+ throw new Error('compiler resource contains an unsupported file entry: '+key);
574
+ }
575
+ return resource;
576
+ }
577
+ async function read(path){
578
+ const {key}=await prepare(path);
579
+ return check(path,await readFile(resolve(directory,key)));
580
+ }
581
+ async function consume(path,receive){
582
+ const {key,entry}=await prepare(path),file=await open(resolve(directory,key),'r');
583
+ const hash=createHash('sha256'),buffer=new Uint8Array(65536);let bytes=0,failed=false;
584
+ try{
585
+ for(;;){
586
+ const {bytesRead}=await file.read(buffer,0,buffer.length,null);
587
+ if(!Number.isInteger(bytesRead)||bytesRead<0||bytesRead>buffer.length)
588
+ throw new Error('compiler resource read returned an invalid byte count');
589
+ if(bytesRead===0)break;
590
+ const block=buffer.subarray(0,bytesRead);hash.update(block);bytes+=bytesRead;receive(block);
591
+ }
592
+ if(entry&&(bytes!==entry.bytes||hash.digest('hex')!==entry.sha256))
593
+ throw new Error('compiler resource SHA-256 or byte length identity changed after emission: '+key);
594
+ }catch(error){failed=true;throw error;}
595
+ finally{try{await file.close();}catch(error){if(!failed)throw error;}}
596
+ }
597
+ async function verify(path){await consume(path,()=>{});}
598
+ async function readSource(path,encoding='utf8',beforeDecode=()=>{}){
599
+ const supported=encoding==='utf8'||encoding==='json-utf16';
600
+ const decoder=supported?new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}):undefined;
601
+ const parser=encoding==='json-utf16'?createCompilerMetadataDecoder():undefined,pieces=[];
602
+ let decodeFailed=false,decodeFailure,parseFailed=false,parseFailure;
603
+ await consume(path,block=>{
604
+ if(!supported||decodeFailed)return;
605
+ let text;
606
+ try{text=decoder.decode(block,{stream:true});}
607
+ catch(error){decodeFailed=true;decodeFailure=error;return;}
608
+ if(parser){if(!parseFailed)try{parser.write(text);}catch(error){parseFailed=true;parseFailure=error;}}
609
+ else pieces.push(text);
610
+ });
611
+ // Original order: resource hash, cancellation/close, encoding, UTF8, JSON.
612
+ // Deferring decode failures preserves that order without retaining bytes.
613
+ beforeDecode();
614
+ if(!supported)throw new TypeError('unsupported compiler source asset encoding');
615
+ if(decodeFailed)throw decodeFailure;
616
+ const tail=decoder.decode();
617
+ if(parser){
618
+ if(parseFailed)throw parseFailure;
619
+ parser.write(tail);const source=parser.finish();
620
+ if(typeof source!=='string')throw new TypeError('encoded compiler source asset must contain a JSON string');
621
+ return source;
622
+ }
623
+ pieces.push(tail);const source=pieces.join('');pieces.length=0;return source;
624
+ }
625
+ async function readMetadata(path){
626
+ const {key,entry}=await prepare(path),file=await open(resolve(directory,key),'r');
627
+ let failed=false;
628
+ try{
629
+ const hash=createHash('sha256'),buffer=new Uint8Array(65536);
630
+ const decoder=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}),parser=createCompilerMetadataDecoder();
631
+ let bytes=0,decodeFailed=false,decodeFailure;
632
+ for(;;){
633
+ const {bytesRead}=await file.read(buffer,0,buffer.length,null);
634
+ if(!bytesRead)break;
635
+ const part=buffer.subarray(0,bytesRead);hash.update(part);bytes+=bytesRead;
636
+ // Resource identity preceded JSON parsing in the original loader.
637
+ // Retain that priority even if corrupt JSON is detected mid-stream.
638
+ if(!decodeFailed)try{parser.write(decoder.decode(part,{stream:true}));}
639
+ catch(error){decodeFailed=true;decodeFailure=error;}
640
+ }
641
+ if(entry&&(bytes!==entry.bytes||hash.digest('hex')!==entry.sha256))
642
+ throw new Error('compiler resource SHA-256 or byte length identity changed after emission: '+key);
643
+ if(decodeFailed)throw decodeFailure;
644
+ parser.write(decoder.decode());
645
+ return parser.finish();
646
+ }catch(error){failed=true;throw error;}
647
+ finally{try{await file.close();}catch(error){if(!failed)throw error;}}
648
+ }
649
+ return{declared,declarations,pathFor,binding,check,read,verify,readSource,readMetadata};
650
+ }
651
+
652
+ function compilerArtifactMemoryBytes(value){
653
+ if(value instanceof Uint8Array)return Uint8Array.from(value);
654
+ if(value instanceof ArrayBuffer)return new Uint8Array(value.slice(0));
655
+ if(Array.isArray(value)&&value.every(byte=>Number.isInteger(byte)&&byte>=0&&byte<=255))return Uint8Array.from(value);
656
+ throw new TypeError('compiler WASM bytes must contain actual bytes');
657
+ }
658
+
659
+ function compilerLiteralSourceIdentity(identity,asset,source,required){
660
+ if(identity===undefined){
661
+ if(required)throw new Error('compiler literal source has no UTF-16 source identity: '+asset.id);
662
+ return;
663
+ }
664
+ if(identity?.algorithm!=='sha256'||identity.encoding!=='utf16le'||!Array.isArray(identity.literalSources))
665
+ throw new TypeError('compiler literal sources require a complete UTF-16 source identity');
666
+ const matches=identity.literalSources.filter(record=>record?.id===asset.id);
667
+ const expected=matches[0];
668
+ if(matches.length!==1||expected.filename!==asset.filename||!/^[0-9a-f]{64}$/.test(expected.sha256??'')||
669
+ expected.encoding!==undefined&&expected.encoding!=='utf16le'||
670
+ expected.bytes!==undefined&&expected.bytes!==source.length*2||
671
+ compilerSourceTextDigest(source).sha256!==expected.sha256)
672
+ throw new Error('compiler literal source differs from its UTF-16 source identity: '+asset.id);
673
+ }
674
+
675
+ function compilerRuntimeSourceIdentity(identity,source,required){
676
+ if(identity===undefined){
677
+ if(required)throw new Error('compiler runtime source has no UTF-16 source identity');
678
+ return;
679
+ }
680
+ const expected=identity.runtime;
681
+ if(identity.algorithm!=='sha256'||identity.encoding!=='utf16le'||typeof expected?.filename!=='string'||
682
+ !/^[0-9a-f]{64}$/.test(expected.sha256??'')||
683
+ expected.encoding!==undefined&&expected.encoding!=='utf16le'||
684
+ expected.bytes!==undefined&&expected.bytes!==source.length*2||
685
+ compilerSourceTextDigest(source).sha256!==expected.sha256)
686
+ throw new Error('compiler runtime source differs from its UTF-16 source identity');
687
+ }
688
+
689
+ function compilerArtifactRequestActive(session,options){
690
+ if(session.closed)throw new Error('compiler session is closed');
691
+ if(options?.signal?.aborted)throw options.signal.reason===undefined?new Error('compiler request aborted'):options.signal.reason;
692
+ }
693
+
694
+ export async function openCompilerArtifact(artifact,options={}) {
695
+ const host=normalizeCompilerHost(artifact?.host);
696
+ const artifactDirectory=artifact.directory??(artifact.metadataPath?dirname(artifact.metadataPath):dirname(artifact.path));
697
+ const artifactPath=artifact.directory||artifact.metadataPath?resolve(artifactDirectory,artifact.path):resolve(artifact.path);
698
+ const resources=compilerArtifactResources(artifact,resolve(artifactDirectory));
699
+ const sourceIdentity=artifact.sourceIdentity===undefined?undefined:structuredClone(artifact.sourceIdentity);
700
+ const literalAssets=artifact.literalSources===undefined?undefined:structuredClone(artifact.literalSources);
701
+ const runtimeAsset={path:artifact.runtimePath,encoding:artifact.runtimeEncoding};
702
+ // Snapshot caller-owned bytes before resource I/O. Both the on-disk entry
703
+ // and the exact bytes passed to WASM must satisfy the emitted declaration.
704
+ const suppliedBytes=host==='wasm'&&artifact.bytes!==undefined?compilerArtifactMemoryBytes(artifact.bytes):undefined;
705
+ let configuration={host,memory:artifact.memory,options:{...artifact.budget,auto:artifact.auto,nativeTarget:artifact.nativeTarget,...options}};
706
+ if(options.debug===undefined&&artifact.debugPath){
707
+ const document=await resources.readMetadata(artifact.debugPath);
708
+ configuration.options.debug=resources.declared?ownCompilerDebugDocument(document):document;
709
+ }
710
+ if(host==='javascript'){
711
+ if(resources.declared){
712
+ if(!Array.isArray(artifact.modules)||!artifact.modules.length)throw new TypeError('compiler JavaScript module graph is required');
713
+ const ids=new Set(),paths=new Set();
714
+ for(const module of artifact.modules){
715
+ const id=moduleId(module?.id),path=resources.pathFor(module.path);
716
+ if(ids.has(id)||paths.has(path))throw new TypeError('duplicate compiler JavaScript module');
717
+ ids.add(id);paths.add(path);resources.binding(module.path);
718
+ }
719
+ if(!paths.has(resources.pathFor(artifactPath)))throw new Error('compiler entry is absent from its JavaScript module graph');
720
+ if(Array.isArray(sourceIdentity?.modules))for(const module of sourceIdentity.modules)
721
+ if(!ids.has(module.id))throw new Error('compiler JavaScript module graph omits a source module: '+module.id);
722
+ // Validate executable modules and providers, rather than rescanning
723
+ // unused frontend IR, source maps, runtime text or other deliverables.
724
+ const executable=new Set([...paths,...[...resources.declarations.keys()].filter(path=>/\.(?:mjs|js)$/.test(path))]);
725
+ for(const path of executable)await resources.verify(path);
726
+ }
727
+ // The ESM loader opens these paths again; preflight verification does not
728
+ // claim that import() consumes our buffers or eliminates that TOCTOU gap.
729
+ configuration.compiler=await import(pathToFileURL(artifactPath).href);
730
+ }else if(host==='wasm'){
731
+ const disk=resources.declared||suppliedBytes===undefined?await resources.read(artifactPath):undefined;
732
+ configuration.bytes=suppliedBytes===undefined?Uint8Array.from(disk):resources.check(artifactPath,suppliedBytes);
733
+ }else{
734
+ await resources.verify(artifactPath);
735
+ // dlopen likewise reopens the verified path using the platform loader.
736
+ configuration.path=artifactPath;configuration.descriptor=artifact.lowered??{typed:artifact.typed,descriptor:artifact.descriptor};
737
+ }
738
+ const session=await createCompilerSession(configuration);
739
+ if(normalizeCompilerHost(session.host)!==host){await session.close();throw new Error('compiler session changed its requested host');}
740
+ if(host==='javascript'&&resources.declared){
741
+ verifiedCompilerBuildSessions.add(session);
742
+ try{await registerVerifiedCompilerBuildConsumption(session);}
743
+ catch(error){verifiedCompilerBuildSessions.delete(session);try{await session.close();}catch{}throw error;}
744
+ }
745
+ let literalSourcesLoading,runtimeSourceLoading;
746
+ function dispatchRuntime(record,requestOptions){
747
+ compilerArtifactRequestActive(session,requestOptions);
748
+ if(Object.hasOwn(record,'literalSources')||literalAssets===undefined)return session.request(record,requestOptions);
749
+ if(!literalSourcesLoading)literalSourcesLoading=(async()=>{
750
+ if(!Array.isArray(literalAssets))throw new TypeError('compiler literalSources must be an array');
751
+ const ids=new Set();
752
+ for(const item of literalAssets){
753
+ const id=moduleId(item?.id);
754
+ if(ids.has(id)||typeof item.filename!=='string'||typeof item.path!=='string')throw new TypeError('invalid compiler literal source asset');
755
+ ids.add(id);
756
+ }
757
+ if(sourceIdentity?.literalSources!==undefined&&(!Array.isArray(sourceIdentity.literalSources)||sourceIdentity.literalSources.length!==literalAssets.length))
758
+ throw new Error('compiler literal source inventory differs from its source identity');
759
+ return Promise.all(literalAssets.map(async item=>{
760
+ if(typeof item?.id!=='string'||typeof item.filename!=='string'||typeof item.path!=='string')throw new TypeError('invalid compiler literal source asset');
761
+ const source=await resources.readSource(item.path,item.encoding,
762
+ ()=>compilerArtifactRequestActive(session,requestOptions));
763
+ compilerLiteralSourceIdentity(sourceIdentity,item,source,resources.declared);
764
+ return{id:item.id,filename:item.filename,source};
765
+ }));
766
+ })().catch(error=>{literalSourcesLoading=undefined;throw error;});
767
+ return literalSourcesLoading.then(literalSources=>{
768
+ compilerArtifactRequestActive(session,requestOptions);
769
+ return session.request({...record,literalSources},requestOptions);
770
+ });
771
+ }
772
+ const adapter=Object.freeze({host:session.host,get closed(){return session.closed;},close:()=>session.close(),
773
+ request(request,requestOptions){
774
+ const record=typeof request==='string'?JSON.parse(request):request;
775
+ if(record?.operation!=='runtime')return session.request(request,requestOptions);
776
+ compilerArtifactRequestActive(session,requestOptions);
777
+ if(Object.hasOwn(record,'source'))return dispatchRuntime(record,requestOptions);
778
+ if(!runtimeSourceLoading)runtimeSourceLoading=(async()=>{
779
+ if(typeof runtimeAsset.path!=='string')throw new TypeError('compiler artifact has no runtime source asset');
780
+ const source=await resources.readSource(runtimeAsset.path,runtimeAsset.encoding,
781
+ ()=>compilerArtifactRequestActive(session,requestOptions));
782
+ compilerRuntimeSourceIdentity(sourceIdentity,source,resources.declared);
783
+ return source;
784
+ })().catch(error=>{runtimeSourceLoading=undefined;throw error;});
785
+ return runtimeSourceLoading.then(source=>{
786
+ compilerArtifactRequestActive(session,requestOptions);
787
+ const payload={...record,source};
788
+ if(!Object.hasOwn(record,'filename'))payload.filename=sourceIdentity?.runtime?.filename??'bootstrap/runtime/memory.eli';
789
+ return dispatchRuntime(payload,requestOptions);
790
+ });
791
+ },
792
+ });
793
+ return registerCompilerBuildProductForwarder(adapter,session);
794
+ }
795
+
796
+ function abort(signal) {
797
+ if(signal?.aborted)throw signal.reason===undefined?new Error('compiler bootstrap aborted'):signal.reason;
798
+ }
799
+
800
+ function sequence(options) {
801
+ if(options.hosts!==undefined){
802
+ if(!Array.isArray(options.hosts)||!options.hosts.length)throw new TypeError('bootstrap host sequence must be nonempty');
803
+ if(options.generations!==undefined&&options.generations!==options.hosts.length)throw new TypeError('generation count differs from host sequence');
804
+ return options.hosts.map(normalizeCompilerHost);
805
+ }
806
+ const count=options.generations??3;
807
+ if(!Number.isSafeInteger(count)||count<1)throw new TypeError('bootstrap generations must be positive');
808
+ return Array.from({length:count},()=>normalizeCompilerHost(options.host??'javascript'));
809
+ }
810
+
811
+ async function seedCompiler(options,sources,directory) {
812
+ if(options.seedArtifact){
813
+ const artifact=options.seedArtifact,mode=artifact.provenance?.mode;
814
+ if(mode!=='seed'&&mode!=='session')throw new Error('initial compiler has no recorded producer');
815
+ assertProducer(artifact,mode==='session'?{host:artifact.provenance.producerHost}:null,sources);
816
+ return artifact;
817
+ }
818
+ const artifact=await buildIndependentCompiler({host:'javascript',outputRoot:directory,sources,
819
+ profile:options.profile,budget:options.budget,memory:options.memory,auto:options.auto,nativeTarget:options.nativeTarget,signal:options.signal,
820
+ retainIR:options.retainIR??true,debug:options.debug??true});
821
+ assertProducer(artifact,null,sources);
822
+ return artifact;
823
+ }
824
+
825
+ // This is production construction orchestration. Completion means construction
826
+ // returned artifacts; semantic consistency remains explicitly unverified.
827
+ export async function bootstrapCompilerChain(options={}) {
828
+ if(typeof options.outputRoot!=='string')throw new TypeError('bootstrap outputRoot is required');
829
+ const hosts=sequence(options),sources=await completeSources(options.sourceRoot??root,options.sources);
830
+ await mkdir(options.outputRoot,{recursive:true});
831
+ const directory=await mkdtemp(join(resolve(options.outputRoot),'compiler-chain-'));
832
+ const sourceIdentity=await archiveCompilerSources(sources,join(directory,'sources'));
833
+ const metadata={format:'eliscript-compiler-bootstrap',version:1,directory,hosts,sourceIdentity,status:'created',verification:'unverified',generations:[]};
834
+ metadata.fixedPoint={status:'insufficient-generations',comparisons:[]};
835
+ const manifest=join(directory,'bootstrap.json');
836
+ await saveCompilerMetadata(manifest,metadata);
837
+ let active=null,artifact=null,phase='seed';
838
+ try {
839
+ abort(options.signal);
840
+ artifact=await seedCompiler(options,sources,join(directory,'seed'));
841
+ metadata.seed=await archiveCompilerArtifact(artifact,join(directory,'seed-metadata'));
842
+ phase='instantiate-seed';active=await openCompilerArtifact(artifact,options.sessionOptions);
843
+ for(let index=0;index<hosts.length;index++){
844
+ abort(options.signal);
845
+ const target=hosts[index],generation=index+1;
846
+ const record={generation,producerHost:active.host,target,sourceSha256:sourceIdentity.sha256,status:'building',verification:'unverified'};
847
+ metadata.generations.push(record);metadata.status='building';phase='generation-'+generation+'-build';
848
+ await saveCompilerMetadata(manifest,metadata);
849
+ await options.onStage?.({directory,generation,producerHost:active.host,target,phase:'build'});
850
+ const nextArtifact=await buildIndependentCompiler({host:target,outputRoot:join(directory,'generation-'+generation+'-'+target),session:active,
851
+ sources:structuredClone(sources),profile:options.profile,budget:options.budget,memory:options.memory,auto:options.auto,
852
+ nativeTarget:options.nativeTarget,signal:options.signal,retainIR:options.retainIR??true,debug:options.debug??true});
853
+ assertProducer(nextArtifact,active,sources);
854
+ if(normalizeCompilerHost(nextArtifact.host)!==target)throw new Error('compiler build changed its requested target');
855
+ record.artifact=await archiveCompilerArtifact(nextArtifact,join(directory,'generation-'+generation+'-metadata'));
856
+ const previous=metadata.generations.slice(0,-1).findLast(item=>item.target===target);
857
+ if(previous){
858
+ const left=previous.artifact?.productIdentity?.sha256,right=record.artifact.productIdentity?.sha256;
859
+ metadata.fixedPoint.comparisons.push({target,from:previous.generation,to:generation,
860
+ status:left&&right?(left===right?'identical':'different'):'unverified',identities:[left??null,right??null]});
861
+ }
862
+ record.status='built';await saveCompilerMetadata(manifest,metadata);
863
+ phase='generation-'+generation+'-instantiate';
864
+ const next=await openCompilerArtifact(nextArtifact,options.sessionOptions);
865
+ const previousSession=active;active=next;artifact=nextArtifact;
866
+ await previousSession.close();
867
+ record.status='instantiated';await saveCompilerMetadata(manifest,metadata);
868
+ await options.onStage?.({directory,generation,producerHost:record.producerHost,target,phase:'instantiated'});
869
+ }
870
+ const complete=compilerHosts.filter(host=>hosts.includes(host)).every(host=>{
871
+ const records=metadata.generations.filter(record=>record.target===host);
872
+ const comparisons=metadata.fixedPoint.comparisons.filter(item=>item.target===host);
873
+ return records.length>=3&&comparisons.length===records.length-1&&comparisons.every(item=>item.status==='identical');
874
+ });
875
+ metadata.fixedPoint.status=complete?'identical':metadata.fixedPoint.comparisons.some(item=>item.status==='different')?'different':'insufficient-generations';
876
+ metadata.status='constructed';await saveCompilerMetadata(manifest,metadata);
877
+ return {directory,artifact,metadata};
878
+ }catch(error){
879
+ metadata.status='failed';metadata.failure={phase,...compilerFailure(error)};
880
+ await saveCompilerMetadata(manifest,metadata);throw error;
881
+ }finally{
882
+ if(active){try{await active.close();}catch(error){const failed=metadata.status==='failed';metadata.cleanupFailure=compilerFailure(error);metadata.status='failed';await saveCompilerMetadata(manifest,metadata);if(!failed)throw error;}}
883
+ }
884
+ }
885
+
886
+ export async function bootstrapIndependentCompilers(options={}) {
887
+ if(typeof options.outputRoot!=='string')throw new TypeError('bootstrap outputRoot is required');
888
+ const requested=options.chains??compilerHosts.map(host=>sequence({host,generations:options.generations}));
889
+ if(!Array.isArray(requested)||!requested.length)throw new TypeError('independent bootstrap chains are required');
890
+ const chains=requested.map(hosts=>sequence({hosts}));
891
+ const sources=await completeSources(options.sourceRoot??root,options.sources);
892
+ await mkdir(options.outputRoot,{recursive:true});
893
+ const directory=await mkdtemp(join(resolve(options.outputRoot),'compiler-bootstrap-'));
894
+ const seed=await seedCompiler(options,sources,join(directory,'seed'));
895
+ const metadata={format:'eliscript-independent-compiler-bootstrap',version:1,status:'building',verification:'unverified',
896
+ sourceIdentity:await archiveCompilerSources(sources,join(directory,'sources')),chains:[]};
897
+ const manifest=join(directory,'bootstrap.json');await saveCompilerMetadata(manifest,metadata);
898
+ const artifacts=[];
899
+ for(let index=0;index<chains.length;index++){
900
+ const hosts=chains[index].map(normalizeCompilerHost);
901
+ try {
902
+ const result=await bootstrapCompilerChain({...options,generations:undefined,hosts,sources,seedArtifact:seed,outputRoot:join(directory,'chain-'+index)});
903
+ artifacts.push(result.artifact);metadata.chains.push({hosts,directory:result.directory,status:'constructed',verification:'unverified',
904
+ sourceIdentity:result.metadata.sourceIdentity,artifact:result.metadata.generations.at(-1)?.artifact,
905
+ fixedPoint:result.metadata.fixedPoint});
906
+ }catch(error){
907
+ metadata.chains.push({hosts,status:'failed',failure:compilerFailure(error),verification:'unverified'});
908
+ await saveCompilerMetadata(manifest,metadata);
909
+ if(options.continueOnError!==true){metadata.status='failed';await saveCompilerMetadata(manifest,metadata);throw error;}
910
+ }
911
+ await saveCompilerMetadata(manifest,metadata);
912
+ }
913
+ metadata.status=metadata.chains.some(chain=>chain.status==='failed')?'incomplete':'constructed';
914
+ metadata.fixedPoint={status:metadata.chains.every(chain=>chain.fixedPoint?.status==='identical')?'identical':'unverified'};
915
+ await saveCompilerMetadata(manifest,metadata);
916
+ return {directory,artifacts,metadata};
917
+ }
918
+
919
+ // Rebuild the entire compiler once for each producer/target pair. These records
920
+ // are distinct from the language-program matrix and from self-host generations.
921
+ export async function bootstrapCompilerGrid(options={}) {
922
+ if(typeof options.outputRoot!=='string')throw new TypeError('compiler grid outputRoot is required');
923
+ const sources=await completeSources(options.sourceRoot??root,options.sources);
924
+ await mkdir(options.outputRoot,{recursive:true});
925
+ const directory=await mkdtemp(join(resolve(options.outputRoot),'compiler-grid-'));
926
+ const metadata={format:'eliscript-independent-compiler-grid',version:1,status:'building',verification:'unverified',
927
+ sourceIdentity:await archiveCompilerSources(sources,join(directory,'sources')),cells:[],comparisons:[]};
928
+ const manifest=join(directory,'grid.json'),artifacts=[],producers=new Map();
929
+ await saveCompilerMetadata(manifest,metadata);
930
+ try{
931
+ let supplied=options.compilerArtifacts;
932
+ if(!supplied){
933
+ const baseline=await bootstrapIndependentCompilers({...options,sources,outputRoot:join(directory,'generations')});
934
+ metadata.generations={directory:baseline.directory,status:baseline.metadata.status,
935
+ sourceIdentity:baseline.metadata.sourceIdentity,chains:baseline.metadata.chains,fixedPoint:baseline.metadata.fixedPoint};
936
+ supplied=baseline.artifacts;
937
+ }
938
+ for(const artifact of Array.isArray(supplied)?supplied:Object.values(supplied)){
939
+ const host=normalizeCompilerHost(artifact?.host);
940
+ if(producers.has(host))throw new TypeError('compiler grid has duplicate producer hosts');
941
+ assertCompilerArtifactSources(artifact,sources);
942
+ producers.set(host,artifact);
943
+ }
944
+ for(const host of compilerHosts)if(!producers.has(host))throw new TypeError('compiler grid is missing producer '+host);
945
+ for(const host of compilerHosts){
946
+ abort(options.signal);let producer;
947
+ try{
948
+ producer=await openCompilerArtifact(producers.get(host),options.sessionOptions);
949
+ for(const target of compilerHosts){
950
+ abort(options.signal);
951
+ const cell={host,target,status:'building',execution:'unverified'},cellDirectory=join(directory,host+'-to-'+target);
952
+ metadata.cells.push(cell);await mkdir(cellDirectory,{recursive:true});await saveCompilerMetadata(manifest,metadata);
953
+ let emitted,instance;
954
+ try{
955
+ await options.onStage?.({directory,host,target,phase:'compiler-build'});
956
+ emitted=await buildIndependentCompiler({...options,sources,session:producer,host:target,outputRoot:join(cellDirectory,'artifact'),
957
+ retainIR:options.retainIR??true,debug:options.debug??true});
958
+ assertProducer(emitted,producer,sources);
959
+ if(normalizeCompilerHost(emitted.host)!==target)throw new Error('compiler grid emitted a different host');
960
+ cell.artifact=await archiveCompilerArtifact(emitted,join(cellDirectory,'metadata'));
961
+ cell.status='built';await saveCompilerMetadata(manifest,metadata);
962
+ await options.onStage?.({directory,host,target,phase:'compiler-initialize'});
963
+ instance=await openCompilerArtifact(emitted,options.sessionOptions);
964
+ const capabilities=await instance.request({operation:'capabilities'},{signal:options.signal});
965
+ await saveCompilerMetadata(join(cellDirectory,'capabilities.json'),capabilities);
966
+ cell.execution='initialized';cell.status='constructed';artifacts.push(emitted);
967
+ }catch(error){
968
+ cell.status='failed';cell.failure=compilerFailure(error);
969
+ if(options.continueOnError!==true)throw error;
970
+ }finally{
971
+ if(instance)try{await instance.close();}catch(error){cell.cleanupFailure=compilerFailure(error);cell.status='failed';}
972
+ await saveCompilerMetadata(manifest,metadata);
973
+ }
974
+ }
975
+ }finally{
976
+ if(producer)try{await producer.close();}catch(error){
977
+ metadata.cleanupFailures??=[];metadata.cleanupFailures.push({host,...compilerFailure(error)});
978
+ await saveCompilerMetadata(manifest,metadata);
979
+ }
980
+ }
981
+ }
982
+ const canonicalArtifacts=[];
983
+ for(const target of compilerHosts){
984
+ const cells=metadata.cells.filter(cell=>cell.target===target);
985
+ const identities=cells.map(cell=>cell.artifact?.productIdentity?.sha256??null);
986
+ const complete=cells.length===3&&cells.every(cell=>cell.status==='constructed'&&cell.execution==='initialized');
987
+ const status=complete&&identities.every(Boolean)?new Set(identities).size===1?'identical':'different':'unverified';
988
+ metadata.comparisons.push({target,status,identities});
989
+ if(status==='identical')canonicalArtifacts.push(artifacts.find(artifact=>artifact.host===target));
990
+ }
991
+ const constructed=metadata.cells.length===9&&metadata.cells.every(cell=>cell.status==='constructed')&&!metadata.cleanupFailures?.length;
992
+ metadata.identityVerification=constructed&&metadata.comparisons.every(item=>item.status==='identical')?'identical':'unverified';
993
+ metadata.status=constructed?'constructed':'incomplete';
994
+ // Language semantics, original gates, performance, and release acceptance
995
+ // are separate evidence; byte identity alone cannot mark them verified.
996
+ await saveCompilerMetadata(manifest,metadata);
997
+ return {directory,artifacts,canonicalArtifacts,metadata};
998
+ }catch(error){
999
+ metadata.status='failed';metadata.failure=compilerFailure(error);await saveCompilerMetadata(manifest,metadata);throw error;
1000
+ }
1001
+ }