eliscript 0.0.1

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 (195) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +135 -0
  3. package/bin/eliscript +16 -0
  4. package/bin/eliscript-bootstrap +15 -0
  5. package/bin/eliscript-build +15 -0
  6. package/bin/eliscript-check +15 -0
  7. package/bin/eliscript-eval +15 -0
  8. package/bin/eliscript-format +15 -0
  9. package/bin/eliscript-org +10 -0
  10. package/bin/eliscript-portable +17 -0
  11. package/bin/eliscript-seed +10 -0
  12. package/bin/eliscript-seed-build +10 -0
  13. package/bin/eliscript-watch +15 -0
  14. package/bootstrap/README.md +100 -0
  15. package/bootstrap/compiler/analyzer.eli +1426 -0
  16. package/bootstrap/compiler/compiler.eli +472 -0
  17. package/bootstrap/compiler/emitter.eli +1745 -0
  18. package/bootstrap/compiler/expander.eli +2522 -0
  19. package/bootstrap/compiler/formatter.eli +359 -0
  20. package/bootstrap/compiler/ir.eli +297 -0
  21. package/bootstrap/compiler/lower.eli +661 -0
  22. package/bootstrap/compiler/project.eli +1120 -0
  23. package/bootstrap/compiler/reader.eli +321 -0
  24. package/bootstrap/compiler/source-map.eli +165 -0
  25. package/bootstrap/compiler/symbol.eli +92 -0
  26. package/bootstrap/compiler/syntax.eli +54 -0
  27. package/bootstrap/compiler/transient-analysis.eli +825 -0
  28. package/bootstrap/host/build.mjs +28 -0
  29. package/bootstrap/host/bun.mjs +282 -0
  30. package/bootstrap/host/check-cli.mjs +163 -0
  31. package/bootstrap/host/eliscript-cli.mjs +36 -0
  32. package/bootstrap/host/evaluation-cli.mjs +401 -0
  33. package/bootstrap/host/evaluation.mjs +560 -0
  34. package/bootstrap/host/format-cli.mjs +139 -0
  35. package/bootstrap/host/project-cli.mjs +295 -0
  36. package/bootstrap/host/project.mjs +1080 -0
  37. package/bootstrap/host/watch-cli.mjs +129 -0
  38. package/bootstrap/host/watch.mjs +267 -0
  39. package/browser/host.mjs +357 -0
  40. package/browser/worker.mjs +60 -0
  41. package/compiler/README.md +118 -0
  42. package/compiler/eliscript-analyzer.el +716 -0
  43. package/compiler/eliscript-cli.el +108 -0
  44. package/compiler/eliscript-diagnostic.el +158 -0
  45. package/compiler/eliscript-emitter.el +1351 -0
  46. package/compiler/eliscript-evaluation.el +259 -0
  47. package/compiler/eliscript-expander.el +1630 -0
  48. package/compiler/eliscript-form.el +79 -0
  49. package/compiler/eliscript-ir-emitter.el +1460 -0
  50. package/compiler/eliscript-ir.el +356 -0
  51. package/compiler/eliscript-lower.el +463 -0
  52. package/compiler/eliscript-macro-eval.el +811 -0
  53. package/compiler/eliscript-parameters.el +324 -0
  54. package/compiler/eliscript-portable.el +492 -0
  55. package/compiler/eliscript-project-cli.el +156 -0
  56. package/compiler/eliscript-project.el +1676 -0
  57. package/compiler/eliscript-reader.el +421 -0
  58. package/compiler/eliscript-source-map.el +192 -0
  59. package/compiler/eliscript-symbol.el +101 -0
  60. package/compiler/eliscript-transient-analysis.el +817 -0
  61. package/compiler/eliscript.el +239 -0
  62. package/dist/bootstrap/analyzer.mjs +968 -0
  63. package/dist/bootstrap/analyzer.mjs.map +1 -0
  64. package/dist/bootstrap/compiler.mjs +228 -0
  65. package/dist/bootstrap/compiler.mjs.map +1 -0
  66. package/dist/bootstrap/emitter.mjs +1173 -0
  67. package/dist/bootstrap/emitter.mjs.map +1 -0
  68. package/dist/bootstrap/expander.mjs +1469 -0
  69. package/dist/bootstrap/expander.mjs.map +1 -0
  70. package/dist/bootstrap/formatter.mjs +304 -0
  71. package/dist/bootstrap/formatter.mjs.map +1 -0
  72. package/dist/bootstrap/ir.mjs +193 -0
  73. package/dist/bootstrap/ir.mjs.map +1 -0
  74. package/dist/bootstrap/lower.mjs +344 -0
  75. package/dist/bootstrap/lower.mjs.map +1 -0
  76. package/dist/bootstrap/project.mjs +585 -0
  77. package/dist/bootstrap/project.mjs.map +1 -0
  78. package/dist/bootstrap/reader.mjs +259 -0
  79. package/dist/bootstrap/reader.mjs.map +1 -0
  80. package/dist/bootstrap/source-map.mjs +154 -0
  81. package/dist/bootstrap/source-map.mjs.map +1 -0
  82. package/dist/bootstrap/symbol.mjs +74 -0
  83. package/dist/bootstrap/symbol.mjs.map +1 -0
  84. package/dist/bootstrap/syntax.mjs +38 -0
  85. package/dist/bootstrap/syntax.mjs.map +1 -0
  86. package/dist/bootstrap/transient-analysis.mjs +660 -0
  87. package/dist/bootstrap/transient-analysis.mjs.map +1 -0
  88. package/dist/browser/compiler.js +6491 -0
  89. package/editor/README.md +83 -0
  90. package/editor/eliscript-mode.el +878 -0
  91. package/editor/eliscript-repl.el +501 -0
  92. package/package.json +163 -0
  93. package/platform/README.md +48 -0
  94. package/platform/browser.mjs +204 -0
  95. package/platform/worker.mjs +166 -0
  96. package/runtime/README.md +296 -0
  97. package/runtime/core/collection-internals.mjs +512 -0
  98. package/runtime/core/collection.mjs +645 -0
  99. package/runtime/core/data-text.mjs +532 -0
  100. package/runtime/core/data.mjs +268 -0
  101. package/runtime/core/identifier.mjs +314 -0
  102. package/runtime/core/lazy-sequence.mjs +244 -0
  103. package/runtime/core/list-internals.mjs +18 -0
  104. package/runtime/core/list.mjs +273 -0
  105. package/runtime/core/map-internals.mjs +793 -0
  106. package/runtime/core/map.mjs +394 -0
  107. package/runtime/core/metadata-internals.mjs +14 -0
  108. package/runtime/core/metadata.mjs +44 -0
  109. package/runtime/core/object-impl.mjs +65 -0
  110. package/runtime/core/object-impl.mjs.map +1 -0
  111. package/runtime/core/object.mjs +13 -0
  112. package/runtime/core/order.mjs +234 -0
  113. package/runtime/core/persistent-kind.mjs +43 -0
  114. package/runtime/core/protocol-error.mjs +36 -0
  115. package/runtime/core/protocol-impl.mjs +326 -0
  116. package/runtime/core/protocol-impl.mjs.map +1 -0
  117. package/runtime/core/protocol.mjs +14 -0
  118. package/runtime/core/queue-internals.mjs +27 -0
  119. package/runtime/core/queue.mjs +238 -0
  120. package/runtime/core/record.mjs +346 -0
  121. package/runtime/core/regex.mjs +184 -0
  122. package/runtime/core/sequence.mjs +632 -0
  123. package/runtime/core/set-algebra.mjs +287 -0
  124. package/runtime/core/set-internals.mjs +33 -0
  125. package/runtime/core/set.mjs +378 -0
  126. package/runtime/core/sorted-internals.mjs +215 -0
  127. package/runtime/core/sorted.mjs +598 -0
  128. package/runtime/core/text-impl.mjs +95 -0
  129. package/runtime/core/text-impl.mjs.map +1 -0
  130. package/runtime/core/text.mjs +15 -0
  131. package/runtime/core/transducer.mjs +668 -0
  132. package/runtime/core/transient-internals.mjs +38 -0
  133. package/runtime/core/transient.mjs +53 -0
  134. package/runtime/core/truth.mjs +3 -0
  135. package/runtime/core/type.mjs +262 -0
  136. package/runtime/core/value-internals.mjs +188 -0
  137. package/runtime/core/value.mjs +93 -0
  138. package/runtime/core/vector-internals.mjs +102 -0
  139. package/runtime/core/vector.mjs +951 -0
  140. package/runtime/literals.mjs +34 -0
  141. package/runtime/source-mapping.mjs +220 -0
  142. package/runtime/testing/list.mjs +52 -0
  143. package/runtime/testing/map.mjs +145 -0
  144. package/runtime/testing/queue.mjs +49 -0
  145. package/runtime/testing/set.mjs +61 -0
  146. package/runtime/testing/sorted.mjs +105 -0
  147. package/runtime/testing/value.mjs +17 -0
  148. package/runtime/testing/vector.mjs +102 -0
  149. package/runtime/worker-value-codec.mjs +565 -0
  150. package/runtime/worker-value-stream.mjs +786 -0
  151. package/runtime/worker.mjs +975 -0
  152. package/stdlib/README.md +774 -0
  153. package/stdlib/bit.eli +36 -0
  154. package/stdlib/core/collection.eli +134 -0
  155. package/stdlib/core/data-text.eli +16 -0
  156. package/stdlib/core/data.eli +306 -0
  157. package/stdlib/core/identifier.eli +32 -0
  158. package/stdlib/core/lazy-sequence.eli +63 -0
  159. package/stdlib/core/metadata.eli +20 -0
  160. package/stdlib/core/object.eli +89 -0
  161. package/stdlib/core/order.eli +133 -0
  162. package/stdlib/core/protocol.eli +387 -0
  163. package/stdlib/core/record.eli +16 -0
  164. package/stdlib/core/regex.eli +17 -0
  165. package/stdlib/core/seq.eli +701 -0
  166. package/stdlib/core/set.eli +312 -0
  167. package/stdlib/core/sorted.eli +53 -0
  168. package/stdlib/core/text.eli +103 -0
  169. package/stdlib/core/transducer.eli +59 -0
  170. package/stdlib/core/transient.eli +24 -0
  171. package/stdlib/core/type.eli +19 -0
  172. package/stdlib/core/walk.eli +195 -0
  173. package/stdlib/core/zipper.eli +508 -0
  174. package/stdlib/data-text.eli +1092 -0
  175. package/stdlib/data.eli +42 -0
  176. package/stdlib/deferred.eli +70 -0
  177. package/stdlib/function.eli +120 -0
  178. package/stdlib/hierarchy.eli +245 -0
  179. package/stdlib/identifier.eli +147 -0
  180. package/stdlib/interop/js.eli +616 -0
  181. package/stdlib/json.eli +870 -0
  182. package/stdlib/metadata.eli +56 -0
  183. package/stdlib/multimethod.eli +464 -0
  184. package/stdlib/numeric.eli +193 -0
  185. package/stdlib/object.eli +96 -0
  186. package/stdlib/persistent-list.eli +145 -0
  187. package/stdlib/persistent-map.eli +724 -0
  188. package/stdlib/persistent-queue.eli +32 -0
  189. package/stdlib/persistent-set.eli +236 -0
  190. package/stdlib/persistent-vector.eli +342 -0
  191. package/stdlib/result.eli +141 -0
  192. package/stdlib/sequence.eli +106 -0
  193. package/stdlib/state/atom.eli +265 -0
  194. package/stdlib/text.eli +88 -0
  195. package/stdlib/value.eli +325 -0
@@ -0,0 +1,975 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { createHash } from "node:crypto";
4
+ import { once } from "node:events";
5
+ import { readFile, realpath, stat } from "node:fs/promises";
6
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
7
+ import { createInterface } from "node:readline";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { workerCapabilities } from "../platform/worker.mjs";
10
+ import {
11
+ decodeWorkerValues,
12
+ encodeWorkerValue,
13
+ workerValueEncoding,
14
+ } from "./worker-value-codec.mjs";
15
+ import {
16
+ WorkerValueStreamDecoder,
17
+ encodeWorkerValueChunks,
18
+ workerValueFraming,
19
+ workerValueStreamLimits,
20
+ } from "./worker-value-stream.mjs";
21
+ import {
22
+ decodeSourceMappings,
23
+ mapSourceFrames,
24
+ parseJavaScriptStack,
25
+ } from "./source-mapping.mjs";
26
+
27
+ export const protocolVersion = 1;
28
+ const runtimeDirectory = dirname(fileURLToPath(import.meta.url));
29
+ const packageDirectories = new Map([
30
+ ["eliscript/platform/", resolve(runtimeDirectory, "../platform")],
31
+ ["eliscript/runtime/", runtimeDirectory],
32
+ ]);
33
+
34
+ function installPackageResolver() {
35
+ Bun.plugin({
36
+ name: "eliscript-worker-package",
37
+ setup(build) {
38
+ build.onResolve(
39
+ { filter: /^eliscript\/(?:platform|runtime)\// },
40
+ ({ path: specifier }) => {
41
+ const [prefix, directory] = [...packageDirectories].find(
42
+ ([candidate]) => specifier.startsWith(candidate),
43
+ );
44
+ const suffix = specifier.slice(prefix.length);
45
+ const target = resolve(directory, suffix);
46
+ const local = relative(directory, target);
47
+ if (suffix.length === 0 || isAbsolute(local) ||
48
+ local === ".." || local.startsWith(`..${sep}`)) {
49
+ const area = prefix.split("/")[1];
50
+ throw new Error(
51
+ `worker ${area} import escapes package ${area}: ${specifier}`,
52
+ );
53
+ }
54
+ return { namespace: "file", path: target };
55
+ },
56
+ );
57
+ },
58
+ });
59
+ }
60
+
61
+ installPackageResolver();
62
+
63
+ export const capabilities = Object.freeze([
64
+ "request",
65
+ "progress",
66
+ "cancel",
67
+ "timeout",
68
+ "shutdown",
69
+ "module-cache",
70
+ "module-version",
71
+ "operation-capabilities-v1",
72
+ "project-manifest",
73
+ "portable-manifest",
74
+ "runtime-resolution",
75
+ "value-codec-v1",
76
+ "value-chunks-v1",
77
+ ]);
78
+
79
+ const maximumLineBytes = 16 * 1024 * 1024;
80
+ const maximumValueChunkLineBytes = workerValueStreamLimits.maxChunkBytes + 4096;
81
+ const maximumValueStreamBytes = 768 * 1024 * 1024;
82
+ const moduleCache = new Map();
83
+ const pending = new Map();
84
+ const protocolOutput = process.stdout;
85
+ let shuttingDown = false;
86
+
87
+ for (const method of ["log", "info", "debug"]) {
88
+ console[method] = (...values) => console.error(...values);
89
+ }
90
+
91
+ function normalizeWorkerStackFile(file) {
92
+ if (!file.startsWith("file:")) return file;
93
+ try {
94
+ return fileURLToPath(file);
95
+ } catch {
96
+ return file;
97
+ }
98
+ }
99
+
100
+ function errorPayload(code, message, error, sourceMaps) {
101
+ const payload = { code, message };
102
+ if (error?.name) payload.name = error.name;
103
+ if (error?.path) payload.path = error.path;
104
+ if (error?.stack) {
105
+ payload.stack = error.stack;
106
+ const frames = mapSourceFrames(
107
+ parseJavaScriptStack(error.stack, { normalizeFile: normalizeWorkerStackFile }),
108
+ sourceMaps ?? [],
109
+ );
110
+ if (frames.length > 0) {
111
+ payload.frames = frames;
112
+ payload.location = frames.find((frame) => frame.file.endsWith(".eli")) ??
113
+ frames[0];
114
+ }
115
+ }
116
+ return payload;
117
+ }
118
+
119
+ function encodeMessage(message) {
120
+ let encoded;
121
+ try {
122
+ encoded = JSON.stringify(message);
123
+ } catch (error) {
124
+ encoded = JSON.stringify({
125
+ version: protocolVersion,
126
+ type: "protocol-error",
127
+ error: errorPayload(
128
+ "serialization",
129
+ `worker could not serialize a protocol message: ${error.message}`,
130
+ error,
131
+ ),
132
+ });
133
+ }
134
+ return `${encoded}\n`;
135
+ }
136
+
137
+ function writeMessage(message) {
138
+ protocolOutput.write(encodeMessage(message));
139
+ }
140
+
141
+ async function writeMessageAsync(message) {
142
+ if (!protocolOutput.write(encodeMessage(message))) {
143
+ await once(protocolOutput, "drain");
144
+ }
145
+ }
146
+
147
+ function jsonValue(value, label) {
148
+ let encoded;
149
+ try {
150
+ encoded = JSON.stringify(value);
151
+ } catch (error) {
152
+ const wrapped = new Error(`${label} is not JSON-serializable: ${error.message}`);
153
+ wrapped.code = "serialization";
154
+ throw wrapped;
155
+ }
156
+ if (encoded === undefined) {
157
+ const error = new Error(`${label} is not JSON-serializable`);
158
+ error.code = "serialization";
159
+ throw error;
160
+ }
161
+ return JSON.parse(encoded);
162
+ }
163
+
164
+ function requestError(id, code, message, error, timing, sourceMaps) {
165
+ const response = {
166
+ version: protocolVersion,
167
+ type: "response",
168
+ id,
169
+ ok: false,
170
+ error: errorPayload(code, message, error, sourceMaps),
171
+ };
172
+ if (timing) response.timing = timing;
173
+ writeMessage(response);
174
+ }
175
+
176
+ function protocolError(code, message, id) {
177
+ const response = {
178
+ version: protocolVersion,
179
+ type: "protocol-error",
180
+ error: errorPayload(code, message),
181
+ };
182
+ if (id !== undefined) response.id = id;
183
+ writeMessage(response);
184
+ }
185
+
186
+ function moduleUrl(identity) {
187
+ let url;
188
+ try {
189
+ url = new URL(identity);
190
+ } catch {
191
+ url = pathToFileURL(resolve(identity));
192
+ }
193
+ if (url.protocol !== "file:") {
194
+ throw new Error(`worker modules must use local file URLs: ${identity}`);
195
+ }
196
+ return url.href;
197
+ }
198
+
199
+ export async function loadSourceMap(moduleUrl_) {
200
+ try {
201
+ const cleanUrl = new URL(moduleUrl_);
202
+ cleanUrl.search = "";
203
+ cleanUrl.hash = "";
204
+ const javascript = await readFile(fileURLToPath(cleanUrl), "utf8");
205
+ const match = javascript.match(/\/\/# sourceMappingURL=([^\s]+)\s*$/);
206
+ if (!match || match[1].startsWith("data:")) return undefined;
207
+ const mapUrl = new URL(match[1], cleanUrl);
208
+ const map = JSON.parse(await readFile(fileURLToPath(mapUrl), "utf8"));
209
+ if (map.version !== 3 || typeof map.mappings !== "string" ||
210
+ !Array.isArray(map.sources)) return undefined;
211
+ return {
212
+ generatedFile: resolve(await realpath(fileURLToPath(cleanUrl))),
213
+ sources: map.sources.map((source) => {
214
+ const sourceUrl = new URL(source, mapUrl);
215
+ return sourceUrl.protocol === "file:"
216
+ ? resolve(fileURLToPath(sourceUrl))
217
+ : sourceUrl.href;
218
+ }),
219
+ lines: decodeSourceMappings(map.mappings),
220
+ };
221
+ } catch (error) {
222
+ console.error(`could not load source map for ${moduleUrl_}: ${error.message}`);
223
+ return undefined;
224
+ }
225
+ }
226
+
227
+ async function moduleFingerprint(url) {
228
+ const fileUrl = new URL(url);
229
+ fileUrl.search = "";
230
+ fileUrl.hash = "";
231
+ const metadata = await stat(fileURLToPath(fileUrl), { bigint: true });
232
+ return `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeNs}`;
233
+ }
234
+
235
+ function projectManifestError(message) {
236
+ const error = new Error(message);
237
+ error.code = "invalid-project-manifest";
238
+ return error;
239
+ }
240
+
241
+ function projectFile(root, value, label) {
242
+ if (typeof value !== "string" || value.length === 0 || isAbsolute(value)) {
243
+ throw projectManifestError(`${label} must be a non-empty relative path`);
244
+ }
245
+ const path = resolve(root, value);
246
+ const fromRoot = relative(root, path);
247
+ if (fromRoot === ".." || fromRoot.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ||
248
+ isAbsolute(fromRoot)) {
249
+ throw projectManifestError(`${label} escapes the project output directory`);
250
+ }
251
+ return path;
252
+ }
253
+
254
+ async function fileDigest(path) {
255
+ return createHash("sha256").update(await readFile(path)).digest("hex");
256
+ }
257
+
258
+ function textDigest(value) {
259
+ return createHash("sha256").update(value, "utf8").digest("hex");
260
+ }
261
+
262
+ async function readProjectManifest(identity, entryUrl) {
263
+ const url = moduleUrl(identity);
264
+ let path;
265
+ try {
266
+ path = await realpath(fileURLToPath(url));
267
+ } catch (error) {
268
+ throw projectManifestError(`could not resolve project manifest: ${error.message}`);
269
+ }
270
+ const root = dirname(path);
271
+ let manifest;
272
+ try {
273
+ manifest = JSON.parse(await readFile(path, "utf8"));
274
+ } catch (error) {
275
+ throw projectManifestError(`could not read project manifest: ${error.message}`);
276
+ }
277
+ if (manifest.format !== "eliscript-project" ||
278
+ (manifest.version !== 1 && manifest.version !== 2) ||
279
+ typeof manifest.digest !== "string" ||
280
+ !/^[0-9a-f]{64}$/.test(manifest.digest) ||
281
+ !Array.isArray(manifest.modules)) {
282
+ throw projectManifestError("project manifest has an unsupported shape");
283
+ }
284
+ const manifestEntries = manifest.version === 1
285
+ ? [manifest.entry]
286
+ : manifest.entries;
287
+ if (!Array.isArray(manifestEntries) || manifestEntries.length === 0 ||
288
+ new Set(manifestEntries).size !== manifestEntries.length ||
289
+ [...manifestEntries].sort().some((entry, index) =>
290
+ entry !== manifestEntries[index])) {
291
+ throw projectManifestError("project manifest entries have an unsupported shape");
292
+ }
293
+ const entries = manifestEntries.map((entry, index) =>
294
+ projectFile(root, entry, `manifest entry ${index}`));
295
+ let canonicalEntries;
296
+ let canonicalModule;
297
+ try {
298
+ [canonicalEntries, canonicalModule] = await Promise.all([
299
+ Promise.all(entries.map((entry) => realpath(entry))),
300
+ realpath(fileURLToPath(entryUrl)),
301
+ ]);
302
+ } catch (error) {
303
+ throw projectManifestError(`could not resolve project entry: ${error.message}`);
304
+ }
305
+ if (!canonicalEntries.includes(canonicalModule)) {
306
+ throw projectManifestError("project manifest entry does not match request module");
307
+ }
308
+ const identityModules = [];
309
+ const modules = manifest.modules.map((module, index) => {
310
+ if (!module || typeof module !== "object" ||
311
+ typeof module.source !== "string" || module.source.length === 0 ||
312
+ isAbsolute(module.source) ||
313
+ module.source.split(/[\\/]/).includes("..") ||
314
+ !/^[0-9a-f]{64}$/.test(module.sourceDigest ?? "") ||
315
+ !/^[0-9a-f]{64}$/.test(module.outputDigest ?? "") ||
316
+ !/^[0-9a-f]{64}$/.test(module.sourceMapDigest ?? "")) {
317
+ throw projectManifestError(`manifest module ${index} has an unsupported shape`);
318
+ }
319
+ identityModules.push({
320
+ source: module.source,
321
+ output: module.output,
322
+ sourceMap: module.sourceMap,
323
+ sourceDigest: module.sourceDigest,
324
+ outputDigest: module.outputDigest,
325
+ sourceMapDigest: module.sourceMapDigest,
326
+ });
327
+ return {
328
+ output: projectFile(root, module.output, `manifest module ${index} output`),
329
+ sourceMap: projectFile(
330
+ root,
331
+ module.sourceMap,
332
+ `manifest module ${index} source map`,
333
+ ),
334
+ outputDigest: module.outputDigest,
335
+ sourceMapDigest: module.sourceMapDigest,
336
+ };
337
+ });
338
+ const declaredOutputs = new Set(identityModules.map((module) => module.output));
339
+ if (manifestEntries.some((entry) => !declaredOutputs.has(entry))) {
340
+ throw projectManifestError("project manifest does not describe every entry artifact");
341
+ }
342
+ const graphIdentity = manifest.version === 1
343
+ ? {
344
+ format: manifest.format,
345
+ version: manifest.version,
346
+ entry: manifest.entry,
347
+ modules: identityModules,
348
+ }
349
+ : {
350
+ format: manifest.format,
351
+ version: manifest.version,
352
+ entries: manifest.entries,
353
+ modules: identityModules,
354
+ };
355
+ if (textDigest(JSON.stringify(graphIdentity)) !== manifest.digest) {
356
+ throw projectManifestError("project manifest graph digest does not match its records");
357
+ }
358
+ return { digest: manifest.digest, modules };
359
+ }
360
+
361
+ async function loadProjectArtifacts(project) {
362
+ const sourceMaps = await Promise.all(project.modules.map(async (module) => {
363
+ let outputDigest;
364
+ let sourceMapDigest;
365
+ try {
366
+ [outputDigest, sourceMapDigest] = await Promise.all([
367
+ fileDigest(module.output),
368
+ fileDigest(module.sourceMap),
369
+ ]);
370
+ } catch (error) {
371
+ throw projectManifestError(
372
+ `could not verify generated module ${module.output}: ${error.message}`,
373
+ );
374
+ }
375
+ if (outputDigest !== module.outputDigest ||
376
+ sourceMapDigest !== module.sourceMapDigest) {
377
+ throw projectManifestError(
378
+ `generated module does not match project manifest: ${module.output}`,
379
+ );
380
+ }
381
+ return loadSourceMap(pathToFileURL(module.output).href);
382
+ }));
383
+ return sourceMaps.filter(Boolean);
384
+ }
385
+
386
+ async function loadModule(identity, requestedVersion, projectManifest) {
387
+ const url = moduleUrl(identity);
388
+ const projectPromise = projectManifest === undefined
389
+ ? Promise.resolve(undefined)
390
+ : readProjectManifest(projectManifest, url);
391
+ const discoveredProject = projectManifest !== undefined &&
392
+ requestedVersion === undefined
393
+ ? await projectPromise
394
+ : undefined;
395
+ const version = discoveredProject?.digest ?? requestedVersion ??
396
+ await moduleFingerprint(url);
397
+ const cacheKey = `${url}\n${projectManifest === undefined ? "" : moduleUrl(projectManifest)}`;
398
+ const cached = moduleCache.get(cacheKey);
399
+ if (cached?.version === version) {
400
+ const loaded = await cached.promise;
401
+ return { ...loaded, cacheHit: true, version };
402
+ }
403
+ if (cached) {
404
+ const error = new Error(
405
+ `module version changed from ${cached.version} to ${version}; restart the worker before loading it`,
406
+ );
407
+ error.code = "module-version-changed";
408
+ throw error;
409
+ }
410
+ const importUrl = new URL(url);
411
+ importUrl.searchParams.set("__eliscript_worker_version", version);
412
+ const entry = {
413
+ version,
414
+ promise: (async () => {
415
+ const project = discoveredProject ?? await projectPromise;
416
+ if (project && version !== project.digest) {
417
+ const error = new Error(
418
+ `requested module version ${version} does not match project manifest ${project.digest}`,
419
+ );
420
+ error.code = "module-version-mismatch";
421
+ throw error;
422
+ }
423
+ const [module, sourceMaps] = await Promise.all([
424
+ import(importUrl.href),
425
+ project
426
+ ? loadProjectArtifacts(project)
427
+ : loadSourceMap(url).then((sourceMap) => sourceMap ? [sourceMap] : []),
428
+ ]);
429
+ return { module, sourceMaps };
430
+ })(),
431
+ };
432
+ moduleCache.set(cacheKey, entry);
433
+ try {
434
+ const loaded = await entry.promise;
435
+ return { ...loaded, cacheHit: false, version };
436
+ } catch (error) {
437
+ if (moduleCache.get(cacheKey) === entry) moduleCache.delete(cacheKey);
438
+ throw error;
439
+ }
440
+ }
441
+
442
+ function validateRequest(message) {
443
+ if (typeof message.id !== "string" || message.id.length === 0) {
444
+ throw new Error("request id must be a non-empty string");
445
+ }
446
+ if (typeof message.module !== "string" || message.module.length === 0) {
447
+ throw new Error("request module must be a non-empty string");
448
+ }
449
+ const hasExport = typeof message.export === "string" && message.export.length > 0;
450
+ const hasOperation = typeof message.operation === "string" &&
451
+ message.operation.length > 0;
452
+ if (hasExport === hasOperation) {
453
+ throw new Error(
454
+ "request must contain exactly one non-empty export or operation",
455
+ );
456
+ }
457
+ const usesValueChunks = message.valueFraming === workerValueFraming;
458
+ if (message.valueFraming !== undefined && !usesValueChunks) {
459
+ throw new Error(`request valueFraming must be ${workerValueFraming}`);
460
+ }
461
+ if (usesValueChunks) {
462
+ if (message.valueEncoding !== workerValueEncoding) {
463
+ throw new Error(
464
+ `chunked requests require valueEncoding ${workerValueEncoding}`,
465
+ );
466
+ }
467
+ if (message.arguments !== undefined) {
468
+ throw new Error("chunked requests must stream arguments after the request header");
469
+ }
470
+ } else if (!Array.isArray(message.arguments)) {
471
+ throw new Error("request arguments must be an array");
472
+ }
473
+ if (message.valueEncoding !== undefined &&
474
+ message.valueEncoding !== workerValueEncoding) {
475
+ throw new Error(
476
+ `request valueEncoding must be ${workerValueEncoding}`,
477
+ );
478
+ }
479
+ if (message.moduleVersion !== undefined &&
480
+ (typeof message.moduleVersion !== "string" ||
481
+ message.moduleVersion.length === 0 || message.moduleVersion.length > 512)) {
482
+ throw new Error("request moduleVersion must be a non-empty string up to 512 characters");
483
+ }
484
+ if (message.projectManifest !== undefined &&
485
+ (typeof message.projectManifest !== "string" ||
486
+ message.projectManifest.length === 0)) {
487
+ throw new Error("request projectManifest must be a non-empty string");
488
+ }
489
+ if (message.timeoutMs !== undefined &&
490
+ (!Number.isInteger(message.timeoutMs) || message.timeoutMs <= 0 ||
491
+ message.timeoutMs > 2_147_483_647)) {
492
+ throw new Error("request timeoutMs must be a positive 32-bit integer");
493
+ }
494
+ }
495
+
496
+ function closeEntry(id, entry) {
497
+ if (entry.timer !== undefined) clearTimeout(entry.timer);
498
+ if (pending.get(id) === entry) pending.delete(id);
499
+ }
500
+
501
+ function receivingError(entry, code, message, error = undefined) {
502
+ requestError(entry.message.id, code, message, error);
503
+ closeEntry(entry.message.id, entry);
504
+ }
505
+
506
+ function createEntry(message, phase) {
507
+ const entry = {
508
+ controller: new AbortController(),
509
+ abortCode: "cancelled",
510
+ timer: undefined,
511
+ phase,
512
+ message,
513
+ startedAt: performance.now(),
514
+ progressIndex: 0,
515
+ progressQueue: Promise.resolve(),
516
+ progressError: undefined,
517
+ };
518
+ pending.set(message.id, entry);
519
+ if (message.timeoutMs !== undefined) {
520
+ entry.timer = setTimeout(() => {
521
+ entry.abortCode = "timeout";
522
+ entry.controller.abort();
523
+ if (entry.phase === "receiving") {
524
+ const error = new Error("request timed out while receiving value chunks");
525
+ error.code = "timeout";
526
+ receivingError(entry, "timeout", error.message, error);
527
+ }
528
+ }, message.timeoutMs);
529
+ }
530
+ return entry;
531
+ }
532
+
533
+ function abortPromise(entry) {
534
+ return new Promise((_, reject) => {
535
+ entry.controller.signal.addEventListener("abort", () => {
536
+ const error = new Error(
537
+ entry.abortCode === "timeout" ? "request timed out" : "request cancelled",
538
+ );
539
+ error.code = entry.abortCode;
540
+ reject(error);
541
+ }, { once: true });
542
+ });
543
+ }
544
+
545
+ async function writeValueStream({
546
+ id,
547
+ channel,
548
+ stream,
549
+ value,
550
+ signal,
551
+ finalFields,
552
+ }) {
553
+ const iterator = encodeWorkerValueChunks(value, { signal })[Symbol.asyncIterator]();
554
+ let sequence = 0;
555
+ let current = await iterator.next();
556
+ if (current.done) {
557
+ throw new Error("value stream encoder produced no events");
558
+ }
559
+ while (!current.done) {
560
+ const next = await iterator.next();
561
+ const final = next.done;
562
+ const message = {
563
+ version: protocolVersion,
564
+ type: "value-chunk",
565
+ id,
566
+ channel,
567
+ sequence,
568
+ final,
569
+ valueEncoding: workerValueEncoding,
570
+ valueFraming: workerValueFraming,
571
+ events: current.value,
572
+ };
573
+ if (stream !== undefined) message.stream = stream;
574
+ if (final && finalFields) {
575
+ Object.assign(message, finalFields({
576
+ sequence,
577
+ chunkCount: sequence + 1,
578
+ }));
579
+ }
580
+ await writeMessageAsync(message);
581
+ current = next;
582
+ sequence += 1;
583
+ }
584
+ }
585
+
586
+ function queueProgress(entry, value) {
587
+ const stream = String(++entry.progressIndex);
588
+ const task = entry.progressQueue.then(() => writeValueStream({
589
+ id: entry.message.id,
590
+ channel: "progress",
591
+ stream,
592
+ value,
593
+ signal: entry.controller.signal,
594
+ }));
595
+ entry.progressQueue = task.catch((error) => {
596
+ if (entry.progressError === undefined) entry.progressError = error;
597
+ });
598
+ return task;
599
+ }
600
+
601
+ async function executeRequest(message, entry, streamedArguments = undefined) {
602
+ const startedAt = entry.startedAt;
603
+ let moduleLoadMs = 0;
604
+ let executionMs = 0;
605
+ let serializationMs = 0;
606
+ let moduleCacheHit = false;
607
+ let moduleVersion;
608
+ let sourceMaps = [];
609
+ let executionStartedAt;
610
+ entry.phase = "executing";
611
+
612
+ try {
613
+ const moduleLoadStartedAt = performance.now();
614
+ const loaded = await loadModule(
615
+ message.module,
616
+ message.moduleVersion,
617
+ message.projectManifest,
618
+ );
619
+ const module = loaded.module;
620
+ sourceMaps = loaded.sourceMaps;
621
+ moduleCacheHit = loaded.cacheHit;
622
+ moduleVersion = loaded.version;
623
+ moduleLoadMs = performance.now() - moduleLoadStartedAt;
624
+ const manifest = module.__eliscript_portable__;
625
+ const operation = message.operation === undefined
626
+ ? module[message.export]
627
+ : manifest && Object.hasOwn(manifest, message.operation)
628
+ ? manifest[message.operation]
629
+ : undefined;
630
+ if (typeof operation !== "function") {
631
+ const operationName = message.operation ?? message.export;
632
+ const error = new Error(
633
+ message.operation === undefined
634
+ ? `module does not export a function named ${operationName}`
635
+ : `module does not declare a portable function named ${operationName}`,
636
+ );
637
+ error.code = message.operation === undefined
638
+ ? "missing-export"
639
+ : "missing-portable";
640
+ throw error;
641
+ }
642
+ const usesValueCodec = message.valueEncoding === workerValueEncoding;
643
+ const usesValueChunks = message.valueFraming === workerValueFraming;
644
+ const arguments_ = streamedArguments !== undefined
645
+ ? streamedArguments
646
+ : usesValueCodec
647
+ ? decodeWorkerValues(message.arguments)
648
+ : message.arguments;
649
+ const progress = (value) => {
650
+ if (entry.controller.signal.aborted) return;
651
+ if (usesValueChunks) return queueProgress(entry, value);
652
+ const response = {
653
+ version: protocolVersion,
654
+ type: "progress",
655
+ id: message.id,
656
+ value: usesValueCodec
657
+ ? encodeWorkerValue(value)
658
+ : jsonValue(value, "progress value"),
659
+ };
660
+ if (usesValueCodec) response.valueEncoding = workerValueEncoding;
661
+ writeMessage(response);
662
+ };
663
+ const context = Object.freeze({
664
+ signal: entry.controller.signal,
665
+ progress,
666
+ capabilities: workerCapabilities(
667
+ { signal: entry.controller.signal, progress },
668
+ ["cancellation", "progress"],
669
+ ),
670
+ });
671
+ executionStartedAt = performance.now();
672
+ const operationPromise = Promise.resolve(
673
+ operation(...arguments_, context),
674
+ );
675
+ const value = await Promise.race([operationPromise, abortPromise(entry)]);
676
+ executionMs = performance.now() - executionStartedAt;
677
+ await entry.progressQueue;
678
+ if (entry.progressError !== undefined) throw entry.progressError;
679
+ const serializationStartedAt = performance.now();
680
+ if (usesValueChunks) {
681
+ await writeValueStream({
682
+ id: message.id,
683
+ channel: "response",
684
+ value,
685
+ signal: entry.controller.signal,
686
+ finalFields({ chunkCount }) {
687
+ serializationMs = performance.now() - serializationStartedAt;
688
+ return {
689
+ timing: {
690
+ moduleLoadMs,
691
+ moduleCacheHit,
692
+ moduleVersion,
693
+ sourceMapLoaded: sourceMaps.length > 0,
694
+ sourceMapCount: sourceMaps.length,
695
+ executionMs,
696
+ serializationMs,
697
+ workerMs: performance.now() - startedAt,
698
+ valueStream: {
699
+ framing: workerValueFraming,
700
+ argumentChunks: entry.sequence,
701
+ responseChunks: chunkCount,
702
+ maxChunkBytes: workerValueStreamLimits.maxChunkBytes,
703
+ maxEventsPerChunk: workerValueStreamLimits.maxEventsPerChunk,
704
+ maxTextPartUnits: workerValueStreamLimits.maxTextPartUnits,
705
+ },
706
+ },
707
+ };
708
+ },
709
+ });
710
+ return;
711
+ }
712
+ const serializedValue = usesValueCodec
713
+ ? encodeWorkerValue(value)
714
+ : jsonValue(value, "response value");
715
+ serializationMs = performance.now() - serializationStartedAt;
716
+ const response = {
717
+ version: protocolVersion,
718
+ type: "response",
719
+ id: message.id,
720
+ ok: true,
721
+ value: serializedValue,
722
+ timing: {
723
+ moduleLoadMs,
724
+ moduleCacheHit,
725
+ moduleVersion,
726
+ sourceMapLoaded: sourceMaps.length > 0,
727
+ sourceMapCount: sourceMaps.length,
728
+ executionMs,
729
+ serializationMs,
730
+ workerMs: performance.now() - startedAt,
731
+ },
732
+ };
733
+ if (usesValueCodec) response.valueEncoding = workerValueEncoding;
734
+ writeMessage(response);
735
+ } catch (error) {
736
+ if (executionStartedAt !== undefined && executionMs === 0) {
737
+ executionMs = performance.now() - executionStartedAt;
738
+ }
739
+ const code = entry.controller.signal.aborted
740
+ ? entry.abortCode
741
+ : error.code ?? "runtime";
742
+ requestError(
743
+ message.id,
744
+ code,
745
+ error.message,
746
+ error,
747
+ {
748
+ moduleLoadMs,
749
+ moduleCacheHit,
750
+ moduleVersion,
751
+ sourceMapLoaded: sourceMaps.length > 0,
752
+ sourceMapCount: sourceMaps.length,
753
+ executionMs,
754
+ serializationMs,
755
+ workerMs: performance.now() - startedAt,
756
+ },
757
+ sourceMaps,
758
+ );
759
+ } finally {
760
+ closeEntry(message.id, entry);
761
+ }
762
+ }
763
+
764
+ function valueAck(id, sequence, final = false) {
765
+ writeMessage({
766
+ version: protocolVersion,
767
+ type: "value-ack",
768
+ id,
769
+ channel: "arguments",
770
+ sequence,
771
+ final,
772
+ valueEncoding: workerValueEncoding,
773
+ valueFraming: workerValueFraming,
774
+ });
775
+ }
776
+
777
+ function startRequest(message) {
778
+ validateRequest(message);
779
+ if (pending.has(message.id)) {
780
+ throw new Error(`request id is already pending: ${message.id}`);
781
+ }
782
+ if (message.valueFraming === workerValueFraming) {
783
+ const entry = createEntry(message, "receiving");
784
+ entry.decoder = new WorkerValueStreamDecoder({
785
+ signal: entry.controller.signal,
786
+ });
787
+ entry.sequence = 0;
788
+ entry.framedBytes = 0;
789
+ valueAck(message.id, -1);
790
+ return;
791
+ }
792
+ const entry = createEntry(message, "executing");
793
+ void executeRequest(message, entry);
794
+ }
795
+
796
+ function receiveValueChunk(message, lineBytes) {
797
+ if (typeof message.id !== "string" || message.id.length === 0) {
798
+ protocolError("invalid-message", "value chunk id must be a non-empty string");
799
+ return;
800
+ }
801
+ const entry = pending.get(message.id);
802
+ if (!entry || entry.phase !== "receiving") {
803
+ protocolError(
804
+ "invalid-message",
805
+ `no request is receiving value chunks for id ${message.id}`,
806
+ message.id,
807
+ );
808
+ return;
809
+ }
810
+ try {
811
+ if (lineBytes > maximumValueChunkLineBytes) {
812
+ throw new Error(
813
+ `value chunk exceeds ${maximumValueChunkLineBytes} framed bytes`,
814
+ );
815
+ }
816
+ if (message.channel !== "arguments") {
817
+ throw new Error("incoming value chunk channel must be arguments");
818
+ }
819
+ if (message.valueEncoding !== workerValueEncoding ||
820
+ message.valueFraming !== workerValueFraming) {
821
+ throw new Error("incoming value chunk encoding or framing mismatch");
822
+ }
823
+ if (!Number.isSafeInteger(message.sequence) || message.sequence < 0 ||
824
+ message.sequence !== entry.sequence) {
825
+ throw new Error(
826
+ `value chunk sequence ${String(message.sequence)} does not match ${entry.sequence}`,
827
+ );
828
+ }
829
+ if (typeof message.final !== "boolean") {
830
+ throw new Error("value chunk final must be a boolean");
831
+ }
832
+ if (!Array.isArray(message.events)) {
833
+ throw new Error("value chunk events must be an array");
834
+ }
835
+ entry.framedBytes += lineBytes;
836
+ if (entry.framedBytes > maximumValueStreamBytes) {
837
+ throw new Error(
838
+ `value stream exceeds ${maximumValueStreamBytes} framed bytes`,
839
+ );
840
+ }
841
+ entry.decoder.write(message.events);
842
+ const sequence = entry.sequence;
843
+ entry.sequence += 1;
844
+ if (!message.final) {
845
+ valueAck(message.id, sequence);
846
+ return;
847
+ }
848
+ const arguments_ = entry.decoder.finish();
849
+ if (!Array.isArray(arguments_)) {
850
+ throw new Error("chunked request root must decode to an argument array");
851
+ }
852
+ entry.decoder = undefined;
853
+ entry.phase = "executing";
854
+ valueAck(message.id, sequence, true);
855
+ void executeRequest(entry.message, entry, arguments_);
856
+ } catch (error) {
857
+ entry.controller.abort();
858
+ receivingError(
859
+ entry,
860
+ error.code ?? "invalid-value-chunk",
861
+ error.message,
862
+ error,
863
+ );
864
+ }
865
+ }
866
+
867
+ function cancelRequest(message) {
868
+ if (typeof message.id !== "string" || message.id.length === 0) {
869
+ protocolError("invalid-message", "cancel id must be a non-empty string");
870
+ return;
871
+ }
872
+ const entry = pending.get(message.id);
873
+ const accepted = Boolean(entry);
874
+ if (entry) {
875
+ entry.abortCode = "cancelled";
876
+ entry.controller.abort();
877
+ }
878
+ writeMessage({
879
+ version: protocolVersion,
880
+ type: "cancel",
881
+ id: message.id,
882
+ accepted,
883
+ });
884
+ if (entry?.phase === "receiving") {
885
+ const error = new Error("request cancelled while receiving value chunks");
886
+ error.code = "cancelled";
887
+ receivingError(entry, "cancelled", error.message, error);
888
+ }
889
+ }
890
+
891
+ function shutdown(lines) {
892
+ shuttingDown = true;
893
+ for (const entry of pending.values()) {
894
+ entry.abortCode = "shutdown";
895
+ entry.controller.abort();
896
+ }
897
+ writeMessage({
898
+ version: protocolVersion,
899
+ type: "shutdown",
900
+ ok: true,
901
+ });
902
+ lines.close();
903
+ setTimeout(() => process.exit(0), 0);
904
+ }
905
+
906
+ function handleMessage(message, lines, lineBytes) {
907
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
908
+ protocolError("invalid-message", "protocol message must be an object");
909
+ return;
910
+ }
911
+ if (message.version !== protocolVersion) {
912
+ protocolError(
913
+ "version-mismatch",
914
+ `worker protocol version ${protocolVersion} required`,
915
+ message.id,
916
+ );
917
+ return;
918
+ }
919
+ if (message.type === "request") {
920
+ try {
921
+ startRequest(message);
922
+ } catch (error) {
923
+ requestError(message.id, "invalid-request", error.message, error);
924
+ }
925
+ } else if (message.type === "value-chunk") {
926
+ receiveValueChunk(message, lineBytes);
927
+ } else if (message.type === "cancel") {
928
+ cancelRequest(message);
929
+ } else if (message.type === "shutdown") {
930
+ shutdown(lines);
931
+ } else {
932
+ protocolError(
933
+ "invalid-message",
934
+ `unknown protocol message type: ${message.type}`,
935
+ message.id,
936
+ );
937
+ }
938
+ }
939
+
940
+ export async function runWorker() {
941
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
942
+ writeMessage({
943
+ version: protocolVersion,
944
+ type: "ready",
945
+ capabilities,
946
+ pid: process.pid,
947
+ });
948
+ lines.on("close", () => {
949
+ if (shuttingDown) return;
950
+ for (const entry of pending.values()) {
951
+ entry.abortCode = "shutdown";
952
+ entry.controller.abort();
953
+ }
954
+ });
955
+ for await (const line of lines) {
956
+ const lineBytes = Buffer.byteLength(line, "utf8");
957
+ if (lineBytes > maximumLineBytes) {
958
+ protocolError("line-too-large", "protocol line exceeds 16 MiB");
959
+ continue;
960
+ }
961
+ if (line.trim().length === 0) continue;
962
+ try {
963
+ handleMessage(JSON.parse(line), lines, lineBytes);
964
+ } catch (error) {
965
+ protocolError("invalid-json", `invalid JSON: ${error.message}`);
966
+ }
967
+ }
968
+ }
969
+
970
+ if (import.meta.main) {
971
+ runWorker().catch((error) => {
972
+ console.error(error.stack ?? error.message);
973
+ process.exitCode = 1;
974
+ });
975
+ }