@genroc/eval-node 0.0.0-edge.d8176a7 → 0.0.0-edge.e7d3ef7

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.
package/README.md CHANGED
@@ -11,8 +11,9 @@ Script tasks for Node. Two halves with different jobs:
11
11
 
12
12
  npm i -D @genroc/eval-node
13
13
 
14
- Then register the resolver in a `genroc.yaml` beside your definitions — discovery walks up from
15
- the file, so nothing depends on the cwd:
14
+ Then register the resolver in a `.genroc` beside your definitions — a dotfile, so it does not
15
+ read as another process definition. Discovery walks up from the source file, so nothing depends
16
+ on the cwd:
16
17
 
17
18
  resolvers:
18
19
  import:
@@ -23,6 +24,16 @@ the file, so nothing depends on the cwd:
23
24
  `genctl apply` and `genctl types` now resolve `$import` directives. Typechecking is the
24
25
  resolver's exit code, so a stored definition cannot hold code that failed to typecheck.
25
26
 
27
+ ## Building
28
+
29
+ npm run build # tsc -p tsconfig.build.json -> dist/
30
+
31
+ The published package is JavaScript, not TypeScript. **Node refuses to strip types for files
32
+ under `node_modules`**, so shipping `.ts` works from a checkout and fails for every consumer —
33
+ which is why `prepublishOnly` builds and CI installs the packed tarball rather than only running
34
+ from source. The source keeps its `.ts` import extensions; `rewriteRelativeImportExtensions`
35
+ turns them into `.js` on the way out.
36
+
26
37
  ## Running the worker
27
38
 
28
39
  docker run -e GENROC_SERVER=http://host:8448 ghcr.io/genroc/eval-node:preview
@@ -85,15 +96,18 @@ The `input` of the external task IS the evaluation request:
85
96
 
86
97
  ```jsonc
87
98
  {
88
- "code": "return { fee: input.amount * 0.1 };", // required — an async function body
89
- "input": { "amount": 250 }, // optional — bound as `input`
90
- "timeout_ms": 5000 // optional — default 5000
99
+ "code": "export default (input) => ({ fee: input.amount * 0.1 });", // required — a module
100
+ "input": { "amount": 250 }, // optional — its argument
101
+ "timeout_ms": 5000 // optional — default 5000
91
102
  }
92
103
  ```
93
104
 
94
- `code` is the **body of an async function**, so `await` works and the value reaches genroc
95
- through `return`. It is compiled with `input` and `require` as parameters, under
96
- `"use strict"` `require` is what a bundled `import` of a node builtin lands on.
105
+ `code` is an **ES module**, and the evaluator imports it and calls its **default export** with
106
+ `input`. The value it returns reaches genroc; the function may be async, and so may the module's
107
+ top level. A module exporting anything else or nothing — is a `compile_error`: there is
108
+ nothing to call, and so is one that will not parse; a throw from its top level is a `threw`
109
+ like any other. `import` of a node builtin resolves as it does anywhere else, and that is what
110
+ a bundled builtin lands on.
97
111
 
98
112
  ## The answer — the failure kind IS the error code
99
113
 
@@ -129,12 +143,14 @@ no retry policy to write.
129
143
  type: external
130
144
  input:
131
145
  code: |
132
- if (input.amount > 100) {
133
- const e = new Error('amount over the limit');
134
- e.name = 'LimitExceeded';
135
- throw e;
146
+ export default function (input) {
147
+ if (input.amount > 100) {
148
+ const e = new Error('amount over the limit');
149
+ e.name = 'LimitExceeded';
150
+ throw e;
151
+ }
152
+ return { fee: input.amount * 0.1 };
136
153
  }
137
- return { fee: input.amount * 0.1 };
138
154
  input: "$: input"
139
155
  result_schema: { type: object, properties: { fee: { type: number } }, required: [fee] }
140
156
  raises:
@@ -153,7 +169,7 @@ no retry policy to write.
153
169
 
154
170
  - id: script_failed
155
171
  switch:
156
- - case: 'error.data.name == "LimitExceeded"'
172
+ - case: 'last_error.data.name == "LimitExceeded"'
157
173
  raise: { code: limit_exceeded, message: "the script rejected the amount" }
158
174
  - raise: { code: script_failed, message: "the script failed" }
159
175
  ```
@@ -186,7 +202,7 @@ never touches the queue and the worker never runs it; the two halves share this
186
202
  because they share a calling convention, which is exactly the coupling that breaks silently
187
203
  if they version apart.
188
204
 
189
- Register it in the project's `genroc.yaml`:
205
+ Register it in the project's `.genroc`:
190
206
 
191
207
  ```yaml
192
208
  resolvers:
@@ -216,12 +232,14 @@ the inferred type of what the definition passes; `Output` is what it declares
216
232
  `tsc --noEmit`, and bundles — so **a type error is a failed apply**, and a stored definition
217
233
  cannot hold code that failed to typecheck.
218
234
 
219
- The bundle is emitted as CJS and wrapped as a function body, so the evaluator needs to know
220
- nothing about modules. Imports resolve through TypeScript under the same config the check
221
- ran with, so a `paths` alias that typechecks also bundles. They are inlined at build time, so the string a
222
- definition version stores is self-contained forever with one exception: **node builtins
223
- stay as `require` calls**, which the realm satisfies. A package is frozen into the
224
- definition; `node:fs` is resolved by whatever runner executes it.
235
+ The bundle is one self-contained ES module whose default export is the author's own nothing
236
+ wraps or rewrites it, so what the editor checks and what the realm runs are the same module, and
237
+ **a missing default export is a failed apply** rather than a fault at run time. Imports resolve
238
+ through TypeScript under the same config the check ran with, so a `paths` alias that typechecks
239
+ also bundles. They are inlined at build time, so the string a definition version stores is
240
+ self-contained forever — with one exception: **node builtins stay as imports**, which the realm
241
+ resolves. A package is frozen into the definition; `node:fs` is resolved by whatever runner
242
+ executes it.
225
243
 
226
244
  ### Your tsconfig, your types
227
245
 
@@ -247,8 +265,9 @@ never read by genroc, because genctl doubles every `$` on splice.
247
265
 
248
266
  ## The realm — one Worker per execution
249
267
 
250
- `evaluate()` starts a Worker (`realm.ts`), posts the code into it, and races the reply against the budget;
251
- `terminate()` runs on every path. That thread is what the contract rests on, and it buys
268
+ `evaluate()` starts a Worker (`realm.ts`), posts the code into it where a module loader hook
269
+ serves it to `import()`, so the engine numbers the script's frames from the author's own source
270
+ and races the reply against the budget; `terminate()` runs on every path. That thread is what the contract rests on, and it buys
252
271
  exactly three things the previous in-process evaluator could not:
253
272
 
254
273
  - **The budget is enforced, not merely reported.** A synchronous `while(true){}` never
@@ -260,16 +279,15 @@ exactly three things the previous in-process evaluator could not:
260
279
  - **The script's mistakes stay the script's.** An uncaught throw, and `process.exit()`, end
261
280
  the realm and come back as a `422` — neither reaches the runner.
262
281
 
263
- It costs about **50ms per execution** end to end for a trivial script (Node 24, M-series
264
- laptop), a 200 KiB body about 63ms. Roughly 19ms of that is Node re-stripping `worker.ts`'s
265
- types on every realm — precompiling it to JavaScript would buy that back, and is deliberately
266
- not done: a build artefact that goes stale against its source fails silently, and this file
267
- is the one where a wrong line number is invisible.
282
+ It costs about **27ms per execution** end to end for a trivial script (Node 24, M-series
283
+ laptop), a 200 KiB body about 30ms. Roughly 11ms of that is Node re-stripping `realm.ts`'s
284
+ types on every realm — precompiling it to JavaScript measures 17ms and would buy that back, and
285
+ is deliberately not done: a build artefact that goes stale against its source fails silently,
286
+ and this file is the one where a wrong line number is invisible.
268
287
 
269
- That also changes an old trade-off. A subprocess per execution measures ~48ms here within
270
- noise of the thread where on the previous runtime it was ten times the thread's cost. The
271
- thread no longer wins on price, and a subprocess contains the two things a thread cannot
272
- (below), so it is the live upgrade path rather than a theoretical one.
288
+ A subprocess per execution measures ~55ms here, twice the thread rather than the ten times it
289
+ cost on the previous runtime. It contains the two things a thread cannot (below), so the upgrade
290
+ path is a live one at a price worth naming rather than a theoretical one.
273
291
 
274
292
  ## What this is not
275
293
 
@@ -280,7 +298,7 @@ thread no longer wins on price, and a subprocess contains the two things a threa
280
298
  it needed was surface with nothing behind it. A value that must survive a retry belongs in
281
299
  the definition, passed through `input`.
282
300
  - **Not a sandbox.** The realm isolates *execution*, not *authority*: a script gets the
283
- worker's filesystem, network and environment, and `require` of any node builtin. That is
301
+ worker's filesystem, network and environment, and any node builtin it imports. That is
284
302
  deliberate — a script task is meant to do real work — but the trust boundary stays the
285
303
  same-trust-domain one (your genroc, your worker host). It is not the multi-tenant story, and
286
304
  nothing here should be mistaken for one. Pulling does move the boundary in one useful way:
@@ -294,9 +312,9 @@ thread no longer wins on price, and a subprocess contains the two things a threa
294
312
  - **Concurrency is capped by this worker, not by genroc.** Each evaluation is a thread, and
295
313
  `CONCURRENCY` is how many it will claim at once. Raising it past what the host can run turns
296
314
  a queue back into threads fighting over a core.
297
- - **Not where imports and type checking happen.** The evaluator still takes one
298
- self-contained function body and knows nothing about TypeScript; `import.ts` is what turns
299
- a module into that body, at author time. See above.
315
+ - **Not where imports and type checking happen.** The evaluator takes one self-contained
316
+ module and knows nothing about TypeScript; `import.ts` is what bundles an author's script and
317
+ its dependencies into that module, at author time. See above.
300
318
  - **`eval.ts` and `realm.ts` know nothing about genroc.** `worker.ts` is the entire
301
319
  queue-facing half, which is what keeps the containment strategy swappable — and what lets
302
320
  the realm's own properties be tested by calling `evaluate()` directly.
package/dist/eval.js ADDED
@@ -0,0 +1,65 @@
1
+ // Evaluation core: import a script module in its OWN realm, call its default export, and
2
+ // classify every outcome into one of the failure kinds in README.md. Nothing here knows about
3
+ // genroc — worker.ts is the only thing that talks to the queue — so this stays testable and
4
+ // the containment stays swappable.
5
+ //
6
+ // The containment is a Worker per execution (realm.ts). It is what makes the budget real:
7
+ // a synchronous busy loop never yields, so no in-process timer can interrupt it, and only a
8
+ // thread the host can kill bounds it.
9
+ import { Worker } from "node:worker_threads";
10
+ const DEFAULT_TIMEOUT_MS = 5_000;
11
+ // Resolved from THIS file's own extension: run from a checkout it is `.ts`, and from the
12
+ // published package `.js`, because Node will not strip types under node_modules.
13
+ const REALM_URL = new URL(import.meta.url.endsWith(".ts") ? "./realm.ts" : "./realm.js", import.meta.url);
14
+ /** Thrown, not returned: a realm that fails to start is the RUNNER faulting, which worker.ts
15
+ * answers by releasing the claim rather than by reporting an outcome. A script fault is a
16
+ * return value. */
17
+ class RealmFault extends Error {
18
+ constructor(message) {
19
+ super(message);
20
+ this.name = "RealmFault";
21
+ }
22
+ }
23
+ export async function evaluate(req) {
24
+ const budget = typeof req.timeout_ms === "number" ? req.timeout_ms : DEFAULT_TIMEOUT_MS;
25
+ const worker = new Worker(REALM_URL);
26
+ let timer;
27
+ try {
28
+ return await new Promise((resolve, reject) => {
29
+ timer = setTimeout(() => resolve(timedOut(budget)), budget);
30
+ worker.once("message", (reply) => resolve(reply));
31
+ // A script may end its own realm (`process.exit()`), which is not a throw and would
32
+ // otherwise present as a hang until the budget expired. Our own terminate() raises
33
+ // this too, by which time the promise has settled and the first result stands.
34
+ worker.once("exit", (code) => resolve(exited(code)));
35
+ worker.once("error", (err) => reject(new RealmFault(errorText(err))));
36
+ worker.postMessage({ code: req.code, input: req.input });
37
+ });
38
+ }
39
+ finally {
40
+ clearTimeout(timer);
41
+ // Awaited, and the whole point: on the timeout path a thread is still burning a core, and
42
+ // resolving before it is gone would report an evaluation the machine is still running.
43
+ await worker.terminate();
44
+ }
45
+ }
46
+ function timedOut(ms) {
47
+ return {
48
+ ok: false,
49
+ failure: { kind: "timeout", name: "TimeoutError", message: `script exceeded its ${ms}ms budget` },
50
+ };
51
+ }
52
+ function exited(code) {
53
+ return {
54
+ ok: false,
55
+ failure: {
56
+ kind: "exited",
57
+ name: "RealmExited",
58
+ message: `the script ended its own realm with code ${code} instead of returning`,
59
+ },
60
+ };
61
+ }
62
+ function errorText(e) {
63
+ const message = e?.message;
64
+ return typeof message === "string" && message !== "" ? message : "the evaluation realm failed to start";
65
+ }
package/dist/import.js ADDED
@@ -0,0 +1,361 @@
1
+ #!/usr/bin/env node
2
+ // The code-phase resolver: manifest on stdin, `{"code": [...]}` on stdout, non-zero exit
3
+ // with the diagnostic on stderr. genctl never parses TypeScript and this never parses YAML
4
+ // — the manifest is the whole contract. See specs/source-resolution.md.
5
+ //
6
+ // Two modes, one binary: "types" writes the declarations an editor needs and returns no
7
+ // code; "build" typechecks and bundles. A separate types hook would mean a second `tsc`
8
+ // over the same project.
9
+ import { spawn } from "node:child_process";
10
+ import { access, mkdir, writeFile } from "node:fs/promises";
11
+ import { builtinModules } from "node:module";
12
+ import { dirname, join, relative } from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ import commonjs from "@rollup/plugin-commonjs";
15
+ import json from "@rollup/plugin-json";
16
+ import { nodeResolve } from "@rollup/plugin-node-resolve";
17
+ import { rollup } from "rollup";
18
+ import ts from "typescript";
19
+ function die(message) {
20
+ console.error(message);
21
+ process.exit(1);
22
+ }
23
+ async function exists(path) {
24
+ try {
25
+ await access(path);
26
+ return true;
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ /** Creates the parent directory, which `.genroc-cache/` relies on: nothing else makes it. */
33
+ async function write(path, content) {
34
+ await mkdir(dirname(path), { recursive: true });
35
+ await writeFile(path, content);
36
+ }
37
+ // ── JSON Schema → TypeScript ───────────────────────────────────────────────────
38
+ /** Only genroc's keyword set is handled; anything else its strict decoder would have
39
+ * refused before this ran (internal/schema, allowedKeywords). */
40
+ function tsType(s, used) {
41
+ if (s === undefined || s === null)
42
+ return "unknown";
43
+ if (typeof s.$ref === "string") {
44
+ const name = s.$ref.replace(/^#\/\$defs\//, "");
45
+ used.add(name);
46
+ return identifier(name);
47
+ }
48
+ if (Array.isArray(s.enum)) {
49
+ return s.enum.map((v) => JSON.stringify(v)).join(" | ") || "never";
50
+ }
51
+ if (Array.isArray(s.anyOf))
52
+ return union(s.anyOf.map((a) => tsType(a, used)));
53
+ if (Array.isArray(s.oneOf))
54
+ return union(s.oneOf.map((a) => tsType(a, used)));
55
+ if (Array.isArray(s.allOf)) {
56
+ return s.allOf.map((a) => tsType(a, used)).join(" & ") || "unknown";
57
+ }
58
+ const types = s.type === undefined ? [] : Array.isArray(s.type) ? s.type : [s.type];
59
+ if (types.length === 0) {
60
+ // The top type: `{}` means unknown, not "an empty object". specs/unknown-type.md.
61
+ return s.properties ? objectType(s, used) : "unknown";
62
+ }
63
+ return union(types.map((t) => scalarType(t, s, used)));
64
+ }
65
+ function scalarType(t, s, used) {
66
+ switch (t) {
67
+ case "object":
68
+ return objectType(s, used);
69
+ case "array":
70
+ return s.items ? `Array<${tsType(s.items, used)}>` : "unknown[]";
71
+ case "string":
72
+ return "string";
73
+ case "number":
74
+ case "integer":
75
+ return "number";
76
+ case "boolean":
77
+ return "boolean";
78
+ case "null":
79
+ return "null";
80
+ default:
81
+ return "unknown";
82
+ }
83
+ }
84
+ function objectType(s, used) {
85
+ const props = s.properties ?? {};
86
+ const required = new Set(s.required ?? []);
87
+ const lines = [];
88
+ for (const [key, sub] of Object.entries(props)) {
89
+ const doc = typeof sub.description === "string"
90
+ ? ` /** ${sub.description} */\n`
91
+ : "";
92
+ lines.push(`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${tsType(sub, used)};`);
93
+ }
94
+ if (s.additionalProperties && typeof s.additionalProperties === "object") {
95
+ lines.push(` [key: string]: ${tsType(s.additionalProperties, used)};`);
96
+ }
97
+ if (lines.length === 0)
98
+ return "Record<string, unknown>";
99
+ return `{\n${lines.join("\n")}\n}`;
100
+ }
101
+ function union(parts) {
102
+ const seen = [...new Set(parts)];
103
+ return seen.length === 0 ? "unknown" : seen.join(" | ");
104
+ }
105
+ const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
106
+ const propKey = (k) => (IDENT.test(k) ? k : JSON.stringify(k));
107
+ const identifier = (n) => IDENT.test(n) ? n : `Def_${n.replace(/[^A-Za-z0-9_$]/g, "_")}`;
108
+ function deref(s, defs) {
109
+ let cur = s;
110
+ for (let i = 0; cur && typeof cur.$ref === "string" && i < 16; i++) {
111
+ cur = defs[cur.$ref.replace(/^#\/\$defs\//, "")];
112
+ }
113
+ return cur;
114
+ }
115
+ /** The manifest's `input` is the type of the whole ACTION input — for /eval that is
116
+ * `{code, input, timeout_ms, …}`, and only its `input` field is bound as the script's
117
+ * parameter. genroc cannot know that; this file owns the evaluator's wire contract, so
118
+ * the navigation belongs here rather than in genctl. */
119
+ function scriptInput(site, defs) {
120
+ const action = deref(site.input, defs);
121
+ const bound = action?.properties?.input;
122
+ return bound ?? site.input;
123
+ }
124
+ /** Emits one named type per reachable $def rather than inlining: a task output may
125
+ * reference itself (specs/recursive-type-inference.md) and inlining would not terminate. */
126
+ function declarations(site, defs) {
127
+ const used = new Set();
128
+ const input = tsType(scriptInput(site, defs), used);
129
+ const output = tsType(site.output, used);
130
+ const emitted = [];
131
+ const done = new Set();
132
+ while (true) {
133
+ const next = [...used].find((n) => !done.has(n));
134
+ if (next === undefined)
135
+ break;
136
+ done.add(next);
137
+ const body = tsType(defs[next], used);
138
+ emitted.push(`export type ${identifier(next)} = ${body};`);
139
+ }
140
+ return [
141
+ "// Generated by genroc. Do not edit - regenerate with `genctl types`.",
142
+ `// ${site.process}${site.task ? ` / ${site.task}` : ""} (${site.pointer})`,
143
+ "",
144
+ ...emitted,
145
+ emitted.length ? "" : "",
146
+ `export type Input = ${input};`,
147
+ "",
148
+ `export type Output = ${output};`,
149
+ "",
150
+ ].join("\n");
151
+ }
152
+ /** Keyed by the script's PATH, not the task id: keyed by task, renaming a task would break
153
+ * the author's `import type` line with the error landing nowhere near the rename. */
154
+ function typesPathFor(scriptPath) {
155
+ return scriptPath.replace(/\.[^.\/]+$/, "") + ".genroc.d.ts";
156
+ }
157
+ // ── typecheck ──────────────────────────────────────────────────────────────────
158
+ /** The nearest tsconfig above the script — the one the author's editor already reads. Two
159
+ * different configs mean a red editor over a clean apply, or the reverse. The walk stops at
160
+ * the project root: above it is not this project. */
161
+ async function nearestTsconfig(from, root) {
162
+ for (let dir = from;; dir = dirname(dir)) {
163
+ const candidate = join(dir, "tsconfig.json");
164
+ if (await exists(candidate))
165
+ return candidate;
166
+ if (dir === root || dirname(dir) === dir)
167
+ return null;
168
+ }
169
+ }
170
+ async function typecheck(root, sites) {
171
+ // NOT `.genroc`: that is the project config FILE, and a directory of the same name cannot
172
+ // coexist with it. The suffix is what keeps the scratch area out of its way.
173
+ const dir = join(root, ".genroc-cache");
174
+ await write(join(dir, ".gitignore"), "*\n");
175
+ // One tsc per distinct base config: `extends` takes a single base, so merging two would
176
+ // check each script under the other author's options.
177
+ const groups = new Map();
178
+ for (const site of sites) {
179
+ const base = (await nearestTsconfig(dirname(site.path), root)) ?? "";
180
+ const group = groups.get(base);
181
+ if (group)
182
+ group.push(site);
183
+ else
184
+ groups.set(base, [site]);
185
+ }
186
+ let n = 0;
187
+ for (const [base, group] of groups) {
188
+ const config = {
189
+ ...(base ? { extends: relative(dir, base) } : {}),
190
+ compilerOptions: {
191
+ noEmit: true,
192
+ strict: true,
193
+ skipLibCheck: true,
194
+ moduleDetection: "force",
195
+ module: "preserve",
196
+ target: "esnext",
197
+ // `lib` DESCRIBES the realm and is written after `extends` so a base cannot widen it:
198
+ // a worker thread has no document, whatever an author's config claims.
199
+ lib: ["esnext", "webworker"],
200
+ // `types` is the author's, and it is how a script opts into the node globals —
201
+ // the worker realm has them, so refusing the declarations would only lie. With no
202
+ // base config there is nothing to opt in with, so the default stays none.
203
+ ...(base ? {} : { types: [] }),
204
+ },
205
+ files: group.flatMap((s) => [
206
+ relative(dir, s.path),
207
+ relative(dir, typesPathFor(s.path)),
208
+ ]),
209
+ // `files` overrides the base's, but a base `include` survives beside it and would
210
+ // drag the author's whole tree in, to be checked under the worker lib.
211
+ include: [],
212
+ };
213
+ const configPath = join(dir, groups.size === 1 ? "tsconfig.json" : `tsconfig.${n++}.json`);
214
+ await write(configPath, JSON.stringify(config, null, 2));
215
+ await runTsc(root, configPath);
216
+ }
217
+ }
218
+ async function runTsc(root, configPath) {
219
+ const tsc = fileURLToPath(import.meta.resolve("typescript/bin/tsc"));
220
+ const proc = spawn(process.execPath, [tsc, "--noEmit", "-p", configPath], {
221
+ cwd: root,
222
+ stdio: ["ignore", "pipe", "pipe"],
223
+ });
224
+ let out = "";
225
+ let err = "";
226
+ proc.stdout.on("data", (c) => (out += c));
227
+ proc.stderr.on("data", (c) => (err += c));
228
+ const code = await new Promise((resolve, reject) => {
229
+ proc.on("error", reject);
230
+ proc.on("close", (c) => resolve(c ?? 1));
231
+ });
232
+ if (code !== 0) {
233
+ // tsc reports on stdout; the exit code IS the type check, so this is the diagnostic
234
+ // genctl surfaces and the reason a failed import never produces a string.
235
+ die([out, err].filter(Boolean).join("\n").trimEnd());
236
+ }
237
+ }
238
+ // ── bundle ─────────────────────────────────────────────────────────────────────
239
+ /** Transpiles only. The typecheck above already ran over the author's OWN tsconfig, and a
240
+ * second opinion from a config they do not control could fail a build they cannot fix. */
241
+ const transpile = {
242
+ name: "genroc-transpile",
243
+ transform(code, id) {
244
+ if (!id.endsWith(".ts") && !id.endsWith(".tsx"))
245
+ return null;
246
+ const out = ts.transpileModule(code, {
247
+ fileName: id,
248
+ compilerOptions: {
249
+ target: ts.ScriptTarget.ESNext,
250
+ module: ts.ModuleKind.ESNext,
251
+ verbatimModuleSyntax: false,
252
+ jsx: id.endsWith(".tsx") ? ts.JsxEmit.ReactJSX : undefined,
253
+ },
254
+ });
255
+ return { code: out.outputText, map: out.sourceMapText ?? null };
256
+ },
257
+ };
258
+ const BUILTIN = new Set([
259
+ ...builtinModules,
260
+ ...builtinModules.map((m) => `node:${m}`),
261
+ ]);
262
+ /** Resolves imports through TYPESCRIPT, using the same config the typecheck ran under, so a
263
+ * `paths` alias that compiles also bundles. Reimplementing `paths` here would be a second
264
+ * resolver to keep in agreement with tsc; this one cannot disagree.
265
+ * A package resolving to a `.d.ts` is declined — that is a type, not the implementation —
266
+ * which leaves node_modules to nodeResolve. */
267
+ function tsResolve(configPath) {
268
+ let options = {};
269
+ if (configPath) {
270
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
271
+ options = ts.parseJsonConfigFileContent(read.config ?? {}, ts.sys, dirname(configPath)).options;
272
+ }
273
+ return {
274
+ name: "genroc-ts-resolve",
275
+ resolveId(source, importer) {
276
+ if (!importer || BUILTIN.has(source))
277
+ return null;
278
+ const { resolvedModule } = ts.resolveModuleName(source, importer, options, ts.sys);
279
+ if (!resolvedModule || resolvedModule.isExternalLibraryImport)
280
+ return null;
281
+ return resolvedModule.resolvedFileName.endsWith(".d.ts")
282
+ ? null
283
+ : resolvedModule.resolvedFileName;
284
+ },
285
+ };
286
+ }
287
+ /** Bundles to a self-contained ES module, which is what the evaluator imports: the default
288
+ * export it calls is the author's own, so nothing wraps or rewrites the code between the two.
289
+ * Bundling is entirely the importer's job, so a definition version pins its code forever. */
290
+ async function bundle(site, root) {
291
+ // Builtins are EXTERNALISED as imports the realm resolves natively. Anything else
292
+ // unresolved is a REFUSAL, not an external: rollup's default is to leave it as an import
293
+ // of a module that will not be there, which bundles clean and fails at runtime.
294
+ const built = await rollup({
295
+ input: site.path,
296
+ external: (id) => BUILTIN.has(id),
297
+ plugins: [
298
+ tsResolve(await nearestTsconfig(dirname(site.path), root)),
299
+ nodeResolve({ extensions: [".ts", ".tsx", ".mjs", ".js", ".json"] }),
300
+ commonjs(),
301
+ // A `.json` import is a data file inlined at build time, which the previous bundler
302
+ // did natively; without it rollup hands the JSON to the JS parser.
303
+ json(),
304
+ transpile,
305
+ ],
306
+ onwarn(warning) {
307
+ if (warning.code === "UNRESOLVED_IMPORT") {
308
+ die(`${site.path}: cannot resolve ${warning.exporter ?? "an import"} — is it installed?`);
309
+ }
310
+ },
311
+ }).catch((e) => die(`${site.path}: ${e instanceof Error ? e.message : String(e)}`));
312
+ const { output } = await built.generate({
313
+ format: "es",
314
+ inlineDynamicImports: true,
315
+ });
316
+ await built.close();
317
+ // Refused here rather than in the realm: the evaluator can only report it against a running
318
+ // instance, and the file it names is on this machine.
319
+ if (!output[0].exports.includes("default")) {
320
+ die(`${site.path}: a script must \`export default\` the function to run`);
321
+ }
322
+ return output[0].code;
323
+ }
324
+ // ── main ───────────────────────────────────────────────────────────────────────
325
+ const stdin = await new Promise((resolve, reject) => {
326
+ let raw = "";
327
+ process.stdin.setEncoding("utf8");
328
+ process.stdin.on("data", (c) => (raw += c));
329
+ process.stdin.on("end", () => resolve(raw));
330
+ process.stdin.on("error", reject);
331
+ });
332
+ const manifest = JSON.parse(stdin);
333
+ if (!manifest || !Array.isArray(manifest.sites))
334
+ die("stdin is not a genroc resolver manifest");
335
+ // One script at two sites with different input types is a refusal, not a union: the union
336
+ // is sound and would typecheck a body that is wrong at one of the sites.
337
+ const byPath = new Map();
338
+ for (const site of manifest.sites) {
339
+ const seen = byPath.get(site.path);
340
+ const defsOf = (x) => (manifest.schemas[x.process]?.$defs ?? {});
341
+ if (seen &&
342
+ JSON.stringify(scriptInput(seen, defsOf(seen))) !==
343
+ JSON.stringify(scriptInput(site, defsOf(site)))) {
344
+ die(`${site.path} is imported at ${seen.pointer} and ${site.pointer} with different input types.\n` +
345
+ "Split it into two scripts, or make the two call sites pass the same shape.");
346
+ }
347
+ byPath.set(site.path, site);
348
+ }
349
+ for (const site of byPath.values()) {
350
+ const defs = (manifest.schemas[site.process]?.$defs ?? {});
351
+ await write(typesPathFor(site.path), declarations(site, defs));
352
+ }
353
+ if (manifest.mode === "types") {
354
+ process.exit(0);
355
+ }
356
+ await typecheck(manifest.root, [...byPath.values()]);
357
+ const code = [];
358
+ for (const site of manifest.sites) {
359
+ code.push(await bundle(site, manifest.root));
360
+ }
361
+ process.stdout.write(JSON.stringify({ code }));