@genroc/eval-node 0.0.0-edge.f85ea85 → 0.0.0-edge.f8ffa72f

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/dist/import.js ADDED
@@ -0,0 +1,377 @@
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 { existsSync } from "node:fs";
10
+ import { access, writeFile } from "node:fs/promises";
11
+ import { builtinModules } from "node:module";
12
+ import { dirname, join, resolve } from "node:path";
13
+ import commonjs from "@rollup/plugin-commonjs";
14
+ import json from "@rollup/plugin-json";
15
+ import { nodeResolve } from "@rollup/plugin-node-resolve";
16
+ import { rollup } from "rollup";
17
+ import ts from "typescript";
18
+ function die(message) {
19
+ console.error(message);
20
+ process.exit(1);
21
+ }
22
+ async function exists(path) {
23
+ try {
24
+ await access(path);
25
+ return true;
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
31
+ // ── JSON Schema → TypeScript ───────────────────────────────────────────────────
32
+ /** Only genroc's keyword set is handled; anything else its strict decoder would have
33
+ * refused before this ran (internal/schema, allowedKeywords). */
34
+ function tsType(s, used) {
35
+ if (s === undefined || s === null)
36
+ return "unknown";
37
+ if (typeof s.$ref === "string") {
38
+ const name = s.$ref.replace(/^#\/\$defs\//, "");
39
+ used.add(name);
40
+ return identifier(name);
41
+ }
42
+ if (Array.isArray(s.enum)) {
43
+ return s.enum.map((v) => JSON.stringify(v)).join(" | ") || "never";
44
+ }
45
+ if (Array.isArray(s.anyOf))
46
+ return union(s.anyOf.map((a) => tsType(a, used)));
47
+ if (Array.isArray(s.oneOf))
48
+ return union(s.oneOf.map((a) => tsType(a, used)));
49
+ if (Array.isArray(s.allOf)) {
50
+ return s.allOf.map((a) => tsType(a, used)).join(" & ") || "unknown";
51
+ }
52
+ const types = s.type === undefined ? [] : Array.isArray(s.type) ? s.type : [s.type];
53
+ if (types.length === 0) {
54
+ // The top type: `{}` means unknown, not "an empty object". specs/unknown-type.md.
55
+ return s.properties ? objectType(s, used) : "unknown";
56
+ }
57
+ return union(types.map((t) => scalarType(t, s, used)));
58
+ }
59
+ function scalarType(t, s, used) {
60
+ switch (t) {
61
+ case "object":
62
+ return objectType(s, used);
63
+ case "array":
64
+ return s.items ? `Array<${tsType(s.items, used)}>` : "unknown[]";
65
+ case "string":
66
+ return "string";
67
+ case "number":
68
+ case "integer":
69
+ return "number";
70
+ case "boolean":
71
+ return "boolean";
72
+ case "null":
73
+ return "null";
74
+ default:
75
+ return "unknown";
76
+ }
77
+ }
78
+ function objectType(s, used) {
79
+ const props = s.properties ?? {};
80
+ const required = new Set(s.required ?? []);
81
+ const lines = [];
82
+ for (const [key, sub] of Object.entries(props)) {
83
+ const doc = typeof sub.description === "string"
84
+ ? ` /** ${sub.description} */\n`
85
+ : "";
86
+ lines.push(`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${nest(tsType(sub, used))};`);
87
+ }
88
+ if (s.additionalProperties && typeof s.additionalProperties === "object") {
89
+ lines.push(` [key: string]: ${nest(tsType(s.additionalProperties, used))};`);
90
+ }
91
+ if (lines.length === 0)
92
+ return "Record<string, unknown>";
93
+ return `{\n${lines.join("\n")}\n}`;
94
+ }
95
+ /** Every line but the first, which is already placed by the property that opens it. */
96
+ const nest = (t) => t.replace(/\n/g, "\n ");
97
+ function union(parts) {
98
+ const seen = [...new Set(parts)];
99
+ return seen.length === 0 ? "unknown" : seen.join(" | ");
100
+ }
101
+ const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
102
+ const propKey = (k) => (IDENT.test(k) ? k : JSON.stringify(k));
103
+ const identifier = (n) => IDENT.test(n) ? n : `Def_${n.replace(/[^A-Za-z0-9_$]/g, "_")}`;
104
+ /** Emits one named type per reachable $def rather than inlining: a task output may
105
+ * reference itself (specs/recursive-type-inference.md) and inlining would not terminate. */
106
+ function declarations(at) {
107
+ const { site, where } = at;
108
+ const defs = where.$defs ?? {};
109
+ const used = new Set();
110
+ const input = tsType(site.types?.Input, used);
111
+ const output = tsType(site.types?.Output, used);
112
+ const emitted = [];
113
+ const done = new Set();
114
+ while (true) {
115
+ const next = [...used].find((n) => !done.has(n));
116
+ if (next === undefined)
117
+ break;
118
+ done.add(next);
119
+ const body = tsType(defs[next], used);
120
+ emitted.push(`export type ${identifier(next)} = ${body};`);
121
+ }
122
+ return [
123
+ "// Generated by genroc. Do not edit - regenerate with `genctl types`.",
124
+ `// ${where.name} (${address(site.pointer)})`,
125
+ "",
126
+ ...emitted,
127
+ emitted.length ? "" : "",
128
+ `export type Input = ${input};`,
129
+ "",
130
+ `export type Output = ${output};`,
131
+ "",
132
+ ].join("\n");
133
+ }
134
+ /** Keyed by the script's PATH, not the task id: keyed by task, renaming a task would break
135
+ * the author's `import type` line with the error landing nowhere near the rename. */
136
+ function typesPathFor(scriptPath) {
137
+ return scriptPath.replace(/\.[^.\/]+$/, "") + ".genroc.d.ts";
138
+ }
139
+ // ── typecheck ──────────────────────────────────────────────────────────────────
140
+ /** The nearest tsconfig above the script — the one the author's editor already reads. Two
141
+ * different configs mean a red editor over a clean apply, or the reverse. The walk stops at
142
+ * the project root: above it is not this project. */
143
+ async function nearestTsconfig(from, root) {
144
+ for (let dir = from;; dir = dirname(dir)) {
145
+ const candidate = join(dir, "tsconfig.json");
146
+ if (await exists(candidate))
147
+ return candidate;
148
+ if (dir === root || dirname(dir) === dir)
149
+ return null;
150
+ }
151
+ }
152
+ async function typecheck(sites) {
153
+ // One program per distinct base config: `extends` takes a single base, so merging two would
154
+ // check each script under the other author's options.
155
+ const groups = new Map();
156
+ for (const at of sites) {
157
+ const base = (await nearestTsconfig(dirname(at.file), root)) ?? "";
158
+ const group = groups.get(base);
159
+ if (group)
160
+ group.push(at);
161
+ else
162
+ groups.set(base, [at]);
163
+ }
164
+ const diagnostics = [];
165
+ for (const [base, group] of groups) {
166
+ const config = {
167
+ ...(base ? { extends: base } : {}),
168
+ compilerOptions: {
169
+ noEmit: true,
170
+ strict: true,
171
+ skipLibCheck: true,
172
+ moduleDetection: "force",
173
+ module: "preserve",
174
+ target: "esnext",
175
+ // `lib` DESCRIBES the realm and is written after `extends` so a base cannot widen it:
176
+ // a worker thread has no document, whatever an author's config claims.
177
+ lib: ["esnext", "webworker"],
178
+ // `types` is the author's, and it is how a script opts into the node globals —
179
+ // the worker realm has them, so refusing the declarations would only lie. With no
180
+ // base config there is nothing to opt in with, so the default stays none.
181
+ ...(base ? {} : { types: [] }),
182
+ },
183
+ files: group.flatMap((s) => [s.file, typesPathFor(s.file)]),
184
+ // `files` overrides the base's, but a base `include` survives beside it and would
185
+ // drag the author's whole tree in, to be checked under the worker lib.
186
+ include: [],
187
+ };
188
+ // Never written: the name only anchors `@types` lookup at the root. It must not be
189
+ // `tsconfig.json`: that is the base the config `extends` whenever the author keeps one at
190
+ // the root, and tsc refuses a config that extends its own path as circular.
191
+ const parsed = ts.parseJsonConfigFileContent(config, ts.sys, root, undefined, join(root, "tsconfig.genroc.json"));
192
+ const program = ts.createProgram({
193
+ rootNames: parsed.fileNames,
194
+ options: parsed.options,
195
+ projectReferences: parsed.projectReferences,
196
+ configFileParsingDiagnostics: parsed.errors,
197
+ });
198
+ diagnostics.push(...parsed.errors, ...ts.getPreEmitDiagnostics(program));
199
+ }
200
+ if (diagnostics.length > 0) {
201
+ // The diagnostics are the whole type check: this is what genctl surfaces, and the reason a
202
+ // failed import never produces a string.
203
+ die(ts
204
+ .formatDiagnostics(diagnostics, {
205
+ getCanonicalFileName: (f) => f,
206
+ getCurrentDirectory: () => root,
207
+ getNewLine: () => "\n",
208
+ })
209
+ .trimEnd());
210
+ }
211
+ }
212
+ // ── bundle ─────────────────────────────────────────────────────────────────────
213
+ /** Transpiles only. The typecheck above already ran over the author's OWN tsconfig, and a
214
+ * second opinion from a config they do not control could fail a build they cannot fix. */
215
+ const transpile = {
216
+ name: "genroc-transpile",
217
+ transform(code, id) {
218
+ if (!id.endsWith(".ts") && !id.endsWith(".tsx"))
219
+ return null;
220
+ const out = ts.transpileModule(code, {
221
+ fileName: id,
222
+ compilerOptions: {
223
+ target: ts.ScriptTarget.ESNext,
224
+ module: ts.ModuleKind.ESNext,
225
+ verbatimModuleSyntax: false,
226
+ jsx: id.endsWith(".tsx") ? ts.JsxEmit.ReactJSX : undefined,
227
+ },
228
+ });
229
+ return { code: out.outputText, map: out.sourceMapText ?? null };
230
+ },
231
+ };
232
+ const BUILTIN = new Set([
233
+ ...builtinModules,
234
+ ...builtinModules.map((m) => `node:${m}`),
235
+ ]);
236
+ /** Resolves imports through TYPESCRIPT, using the same config the typecheck ran under, so a
237
+ * `paths` alias that compiles also bundles. Reimplementing `paths` here would be a second
238
+ * resolver to keep in agreement with tsc; this one cannot disagree.
239
+ * A package resolving to a `.d.ts` is declined — that is a type, not the implementation —
240
+ * which leaves node_modules to nodeResolve. */
241
+ function tsResolve(configPath) {
242
+ let options = {};
243
+ if (configPath) {
244
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
245
+ options = ts.parseJsonConfigFileContent(read.config ?? {}, ts.sys, dirname(configPath)).options;
246
+ }
247
+ return {
248
+ name: "genroc-ts-resolve",
249
+ resolveId(source, importer) {
250
+ if (!importer || BUILTIN.has(source))
251
+ return null;
252
+ const { resolvedModule } = ts.resolveModuleName(source, importer, options, ts.sys);
253
+ if (!resolvedModule || resolvedModule.isExternalLibraryImport)
254
+ return null;
255
+ return resolvedModule.resolvedFileName.endsWith(".d.ts")
256
+ ? null
257
+ : resolvedModule.resolvedFileName;
258
+ },
259
+ };
260
+ }
261
+ /** Bundles to a self-contained ES module, which is what the evaluator imports: the default
262
+ * export it calls is the author's own, so nothing wraps or rewrites the code between the two.
263
+ * Bundling is entirely the importer's job, so a definition version pins its code forever. */
264
+ async function bundle(at) {
265
+ const site = at.site;
266
+ // Builtins are EXTERNALISED as imports the realm resolves natively. Anything else
267
+ // unresolved is a REFUSAL, not an external: rollup's default is to leave it as an import
268
+ // of a module that will not be there, which bundles clean and fails at runtime.
269
+ const built = await rollup({
270
+ input: at.file,
271
+ external: (id) => BUILTIN.has(id),
272
+ plugins: [
273
+ tsResolve(await nearestTsconfig(dirname(at.file), root)),
274
+ nodeResolve({ extensions: [".ts", ".tsx", ".mjs", ".js", ".json"] }),
275
+ commonjs(),
276
+ // A `.json` import is a data file inlined at build time, which the previous bundler
277
+ // did natively; without it rollup hands the JSON to the JS parser.
278
+ json(),
279
+ transpile,
280
+ ],
281
+ onwarn(warning) {
282
+ if (warning.code === "UNRESOLVED_IMPORT") {
283
+ die(`${at.file}: cannot resolve ${warning.exporter ?? "an import"} — is it installed?`);
284
+ }
285
+ },
286
+ }).catch((e) => die(`${at.file}: ${e instanceof Error ? e.message : String(e)}`));
287
+ const { output } = await built.generate({
288
+ format: "es",
289
+ inlineDynamicImports: true,
290
+ });
291
+ await built.close();
292
+ // Refused here rather than in the realm: the evaluator can only report it against a running
293
+ // instance, and the file it names is on this machine.
294
+ if (!output[0].exports.includes("default")) {
295
+ die(`${at.file}: a script must \`export default\` the function to run`);
296
+ }
297
+ return output[0].code;
298
+ }
299
+ // ── main ───────────────────────────────────────────────────────────────────────
300
+ const stdin = await new Promise((resolve, reject) => {
301
+ let raw = "";
302
+ process.stdin.setEncoding("utf8");
303
+ process.stdin.on("data", (c) => (raw += c));
304
+ process.stdin.on("end", () => resolve(raw));
305
+ process.stdin.on("error", reject);
306
+ });
307
+ const manifest = JSON.parse(stdin);
308
+ // genctl runs a resolver with the project root as its cwd, so the manifest need not say so.
309
+ const root = process.cwd();
310
+ if (!manifest || !Array.isArray(manifest.processes))
311
+ die("stdin is not a genroc resolver manifest");
312
+ /** A pointer as the address it is, so a generated comment or an error can be pasted into
313
+ * `genctl schema`. A key no identifier can spell is bracketed, as the grammar spells it. */
314
+ function address(pointer) {
315
+ return pointer
316
+ .map((seg) => typeof seg === "string" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(seg)
317
+ ? `.${seg}`
318
+ : `[${JSON.stringify(seg)}]`)
319
+ .join("")
320
+ .replace(/^\./, "");
321
+ }
322
+ const located = manifest.processes.flatMap((where) => where.sites.map((site) => ({
323
+ site,
324
+ where,
325
+ file: resolve(where.dir, site.argument),
326
+ })));
327
+ // genctl is agnostic about what a script is for; the contract that an evaluation request carries
328
+ // its module in `code` is THIS resolver's, so it is the one that checks a directive landed there.
329
+ // `child` is the shape the scaffold uses — a call to a process that forwards to the evaluator —
330
+ // and `external` is the same request made directly.
331
+ for (const at of located) {
332
+ // Two halves, from the two places that carry them: the action's KIND is a field, and WHERE in
333
+ // it the directive sits is the pointer. A child call is the shape the scaffold generates — to a
334
+ // process that forwards to the evaluator — and an external task is the same request made
335
+ // directly.
336
+ const kind = at.site.level === "action" ? (at.site.action ?? "") : "";
337
+ const slot = at.site.pointer.slice(-2).join(".");
338
+ if ((kind !== "child" && kind !== "external") || slot !== "input.code") {
339
+ die(`${join(at.where.dir, at.where.file)}: ${address(at.site.pointer)}: an evaluated script ` +
340
+ "belongs in the `code` field of a child or external task's input, and this is " +
341
+ `${kind ? `a ${kind} task's ` : ""}\`${slot}\`.`);
342
+ }
343
+ }
344
+ // genctl no longer stats the argument — it does not know it is a file — so the resolver that
345
+ // does is the one that must say when it is not there.
346
+ for (const at of located) {
347
+ if (!existsSync(at.file)) {
348
+ die(`${join(at.where.dir, at.where.file)}: ${address(at.site.pointer)}: ` +
349
+ `"$import: ${at.site.argument}" names no file (looked at ${at.file})`);
350
+ }
351
+ }
352
+ // One script at two sites with different input types is a refusal, not a union: the union
353
+ // is sound and would typecheck a body that is wrong at one of the sites.
354
+ const byPath = new Map();
355
+ for (const at of located) {
356
+ const seen = byPath.get(at.file);
357
+ if (seen &&
358
+ JSON.stringify(seen.site.types) !== JSON.stringify(at.site.types)) {
359
+ die(`${at.file} is imported at ${address(seen.site.pointer)} and ` +
360
+ `${address(at.site.pointer)} with different input types.\n` +
361
+ "Split it into two scripts, or make the two call sites pass the same shape.");
362
+ }
363
+ byPath.set(at.file, at);
364
+ }
365
+ for (const at of byPath.values()) {
366
+ await writeFile(typesPathFor(at.file), declarations(at));
367
+ }
368
+ if (manifest.mode === "types") {
369
+ console.log(JSON.stringify(manifest, null, 2));
370
+ process.exit(0);
371
+ }
372
+ await typecheck([...byPath.values()]);
373
+ const code = [];
374
+ for (const at of located) {
375
+ code.push(await bundle(at));
376
+ }
377
+ process.stdout.write(JSON.stringify({ code }));
package/dist/realm.js ADDED
@@ -0,0 +1,113 @@
1
+ // The evaluation realm. One Worker per execution: a fresh global object per script, and a
2
+ // thread the host can kill mid-loop — the only thing that bounds a synchronous busy loop.
3
+ // eval.ts owns the budget and does the killing; nothing here knows about time.
4
+ //
5
+ // Everything that touches the script's VALUE lives on this side of the boundary — loading,
6
+ // classifying, serialising — because this is the only realm the value exists in.
7
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
8
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
9
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
10
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
11
+ });
12
+ }
13
+ return path;
14
+ };
15
+ import { registerHooks } from "node:module";
16
+ import { parentPort } from "node:worker_threads";
17
+ // The script is IMPORTED as a module under a URL of our own, not compiled from a string: its
18
+ // frames then carry the author's own line numbers, and an `import` of a node builtin resolves
19
+ // the way it does everywhere else.
20
+ const SCRIPT_URL = "script:main";
21
+ const STACK_BYTES = 2_048;
22
+ // The only channel a load hook has to the source. Written per request and read once — a realm
23
+ // evaluates one script and is then discarded, so no second execution can observe it.
24
+ let source = "";
25
+ registerHooks({
26
+ resolve: (specifier, context, next) => specifier === SCRIPT_URL ? { url: SCRIPT_URL, shortCircuit: true } : next(specifier, context),
27
+ load: (url, context, next) => url === SCRIPT_URL ? { format: "module", source, shortCircuit: true } : next(url, context),
28
+ });
29
+ /** Keeps the frames that are the script's own. Everything below the last of them is runner
30
+ * plumbing the author cannot act on, and V8 puts this file's path in it. */
31
+ function scriptStack(err) {
32
+ if (!(err instanceof Error) || typeof err.stack !== "string")
33
+ return undefined;
34
+ const lines = err.stack.split("\n");
35
+ let last = 0;
36
+ for (let i = 0; i < lines.length; i++)
37
+ if (lines[i].includes(SCRIPT_URL))
38
+ last = i;
39
+ const stack = lines.slice(0, last + 1).join("\n");
40
+ return stack.length > STACK_BYTES ? stack.slice(0, STACK_BYTES) : stack;
41
+ }
42
+ function describe(err, kind) {
43
+ if (err instanceof Error) {
44
+ return { kind, name: err.name, message: err.message, stack: scriptStack(err) };
45
+ }
46
+ // A script may throw a non-Error (`throw {code: "x"}`), so name/message must not assume one.
47
+ return { kind, name: "Thrown", message: safeText(err) };
48
+ }
49
+ function safeText(v) {
50
+ try {
51
+ return typeof v === "string" ? v : JSON.stringify(v) ?? String(v);
52
+ }
53
+ catch {
54
+ return String(v);
55
+ }
56
+ }
57
+ /** A module that will not parse, or names an import nothing resolves, is broken code — only
58
+ * editing it helps. Anything else thrown by the import is the module's top level running,
59
+ * which is the script throwing. */
60
+ function unloadable(err) {
61
+ const code = err?.code;
62
+ return err instanceof SyntaxError || (typeof code === "string" && code.startsWith("ERR_MODULE"));
63
+ }
64
+ async function run(req) {
65
+ source = req.code;
66
+ let main;
67
+ try {
68
+ main = (await import(__rewriteRelativeImportExtension(SCRIPT_URL))).default;
69
+ }
70
+ catch (err) {
71
+ return { ok: false, failure: describe(err, unloadable(err) ? "compile_error" : "threw") };
72
+ }
73
+ if (typeof main !== "function") {
74
+ const got = main === undefined ? "no default export" : `a ${typeof main}`;
75
+ return {
76
+ ok: false,
77
+ failure: {
78
+ kind: "compile_error",
79
+ name: "NoDefaultExport",
80
+ message: `a script must export default a function; this one has ${got}`,
81
+ },
82
+ };
83
+ }
84
+ let value;
85
+ try {
86
+ value = await main(req.input);
87
+ }
88
+ catch (err) {
89
+ return { ok: false, failure: describe(err, "threw") };
90
+ }
91
+ try {
92
+ // undefined stringifies to undefined, not "undefined"; an empty body is how genroc
93
+ // spells null, which is the right reading of a script that returned nothing.
94
+ return { ok: true, body: value === undefined ? "" : JSON.stringify(value) ?? "" };
95
+ }
96
+ catch (err) {
97
+ return { ok: false, failure: describe(err, "nonserializable") };
98
+ }
99
+ }
100
+ // The realm's stdio is a pipe to the host thread, and eval.ts terminates this thread the moment
101
+ // the reply lands — so whatever a script wrote last is still in the pipe when it dies. An empty
102
+ // write's callback fires once the queue ahead of it has drained, which makes the reply a barrier
103
+ // for `console` and a direct process.stdout.write alike: both are this stream.
104
+ function flush(stream) {
105
+ return new Promise((resolve) => stream.write("", () => resolve()));
106
+ }
107
+ // Non-null because this module only ever runs as a worker entry point; a null port here
108
+ // would mean eval.ts loaded it as a plain module, which nothing does.
109
+ parentPort.on("message", async (req) => {
110
+ const reply = await run(req);
111
+ await Promise.all([flush(process.stdout), flush(process.stderr)]);
112
+ parentPort.postMessage(reply);
113
+ });