@nanobpm/urban-pr-review-codefirst 0.1.0

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.
@@ -0,0 +1,250 @@
1
+ // nanobpmn Deno global shim for the Node fallback runtime (ADR 0036).
2
+ //
3
+ // The Node-first Run path (ADR 0038) spawns app code with
4
+ // `--experimental-strip-types` but no `Deno` global, so app/template sources
5
+ // that call `Deno.serve`/`Deno.env`/`Deno.readTextFile` throw "Deno is not
6
+ // defined". This module installs a minimal `globalThis.Deno` backed by Node
7
+ // built-ins so Deno-authored apps — and the scaffolder's URBAN/GUI templates —
8
+ // run unchanged under Node, honoring node-loader.mjs's stated intent.
9
+ //
10
+ // Scope: the surface the app tier + embedded SDK adapters actually use. The
11
+ // portable SDK adapters (`globalThis.Deno ?? process`) branch on this global,
12
+ // so it must satisfy every method they call (env/cwd/exit/readTextFile/
13
+ // writeTextFile/mkdir/readDir/stdin/stdout/addSignalListener) as well as
14
+ // `Deno.serve`. Loaded before app code via `--import node-register.mjs`.
15
+ import { writeSync as fsWriteSync } from "node:fs";
16
+ import {
17
+ mkdir as fsMkdir,
18
+ readdir as fsReaddir,
19
+ readFile as fsReadFile,
20
+ rm as fsRm,
21
+ stat as fsStat,
22
+ writeFile as fsWriteFile,
23
+ } from "node:fs/promises";
24
+ import { createServer } from "node:http";
25
+ import { Readable } from "node:stream";
26
+
27
+ // Real Deno (or an earlier shim) already present — leave it untouched.
28
+ if (globalThis.Deno === undefined) {
29
+ const enc = new TextEncoder();
30
+
31
+ async function* readDir(path) {
32
+ const ents = await fsReaddir(path, { withFileTypes: true });
33
+ for (const e of ents) {
34
+ yield {
35
+ name: e.name,
36
+ isFile: e.isFile(),
37
+ isDirectory: e.isDirectory(),
38
+ isSymlink: e.isSymbolicLink(),
39
+ };
40
+ }
41
+ }
42
+
43
+ function toBytes(data) {
44
+ return typeof data === "string" ? enc.encode(data) : data;
45
+ }
46
+
47
+ // Bridge one Node request/response pair through a web-standard handler, the
48
+ // contract `Deno.serve` hands callers (Web `Request` in, `Response` out).
49
+ function bridge(handler, hostname) {
50
+ return async (nodeReq, nodeRes) => {
51
+ try {
52
+ // Node's IncomingMessage can leave `url`/`method` undefined on atypical
53
+ // requests; default them so we never build a malformed web `Request`.
54
+ const method = nodeReq.method ?? "GET";
55
+ const path = nodeReq.url ?? "/";
56
+ const url = `http://${nodeReq.headers.host ?? hostname}${path}`;
57
+ const headers = new Headers();
58
+ for (const [k, v] of Object.entries(nodeReq.headers)) {
59
+ if (Array.isArray(v)) for (const vv of v) headers.append(k, vv);
60
+ else if (v != null) headers.set(k, v);
61
+ }
62
+ const hasBody = method !== "GET" && method !== "HEAD";
63
+ const init = { method, headers };
64
+ if (hasBody) {
65
+ const chunks = [];
66
+ for await (const c of nodeReq) chunks.push(c);
67
+ init.body = Buffer.concat(chunks);
68
+ }
69
+ const remoteAddr = {
70
+ transport: "tcp",
71
+ hostname: nodeReq.socket?.remoteAddress ?? "",
72
+ port: nodeReq.socket?.remotePort ?? 0,
73
+ };
74
+ const webRes = await handler(new Request(url, init), { remoteAddr });
75
+ nodeRes.statusCode = webRes.status;
76
+ // `Headers.forEach` comma-joins duplicates, which is invalid for
77
+ // `Set-Cookie` (Node wants an array). Set those separately from
78
+ // `getSetCookie()` and skip the joined value in the general copy.
79
+ webRes.headers.forEach((value, key) => {
80
+ if (key.toLowerCase() !== "set-cookie") nodeRes.setHeader(key, value);
81
+ });
82
+ const cookies = webRes.headers.getSetCookie?.() ?? [];
83
+ if (cookies.length) nodeRes.setHeader("set-cookie", cookies);
84
+ // Honour backpressure: when `write` returns false the socket buffer is
85
+ // full, so await `drain` before writing more — otherwise a large
86
+ // response accumulates in memory and stalls the event loop.
87
+ const writeChunk = (chunk) =>
88
+ nodeRes.write(chunk)
89
+ ? Promise.resolve()
90
+ : new Promise((resolve) => nodeRes.once("drain", resolve));
91
+ if (webRes.body) {
92
+ const reader = webRes.body.getReader();
93
+ for (;;) {
94
+ const { done, value } = await reader.read();
95
+ if (done) break;
96
+ if (value) await writeChunk(value);
97
+ }
98
+ } else {
99
+ const buf = Buffer.from(await webRes.arrayBuffer());
100
+ if (buf.length) await writeChunk(buf);
101
+ }
102
+ nodeRes.end();
103
+ } catch (err) {
104
+ // Match Deno's default: log the handler error server-side and return a
105
+ // generic 500 body, never the stack trace — leaking internals over the
106
+ // wire is both an info-disclosure risk and a divergence from Deno.
107
+ console.error(err);
108
+ if (!nodeRes.headersSent) nodeRes.statusCode = 500;
109
+ try {
110
+ nodeRes.end("Internal Server Error");
111
+ } catch {
112
+ // response already destroyed — nothing more to do
113
+ }
114
+ }
115
+ };
116
+ }
117
+
118
+ // Deno.serve(handler) | Deno.serve(options, handler) | Deno.serve({...,handler})
119
+ function serve(arg1, arg2) {
120
+ let options = {};
121
+ let handler;
122
+ if (typeof arg1 === "function") {
123
+ handler = arg1;
124
+ } else {
125
+ options = arg1 ?? {};
126
+ handler = arg2 ?? options.handler;
127
+ }
128
+ const port = options.port ?? 8000;
129
+ const hostname = options.hostname ?? "0.0.0.0";
130
+ // Real `Deno.serve` rejects a missing/invalid handler synchronously with a
131
+ // TypeError; match that so misuse surfaces at call time, not on the first
132
+ // request (where an undefined handler would otherwise 500 late).
133
+ if (typeof handler !== "function") {
134
+ throw new TypeError("Deno.serve requires a handler function");
135
+ }
136
+ // The actually-bound port; with `port: 0` Node picks an ephemeral one, so
137
+ // resolve it from `server.address()` after listen (Deno reports the real
138
+ // port, not the requested 0).
139
+ let boundPort = port;
140
+ const server = createServer(bridge(handler, hostname));
141
+ // A Server-level `error` is a bind failure (e.g. AddrInUse); Deno.serve
142
+ // treats that as fatal. Surface it cleanly instead of crashing on an
143
+ // unhandled `error` event.
144
+ server.on("error", (err) => {
145
+ console.error(err);
146
+ process.exit(1);
147
+ });
148
+ const finished = new Promise((resolve) => server.once("close", resolve));
149
+ server.listen(port, hostname, () => {
150
+ const bound = server.address();
151
+ if (bound && typeof bound === "object") boundPort = bound.port;
152
+ const addr = { hostname, port: boundPort, transport: "tcp" };
153
+ if (typeof options.onListen === "function") options.onListen(addr);
154
+ });
155
+ const shutdown = () =>
156
+ new Promise((resolve) => server.close(() => resolve()));
157
+ if (options.signal instanceof AbortSignal) {
158
+ options.signal.addEventListener("abort", () => void shutdown(), { once: true });
159
+ }
160
+ return {
161
+ finished,
162
+ shutdown,
163
+ ref: () => server.ref(),
164
+ unref: () => server.unref(),
165
+ get addr() {
166
+ return { hostname, port: boundPort, transport: "tcp" };
167
+ },
168
+ };
169
+ }
170
+
171
+ class NotFound extends Error {}
172
+
173
+ globalThis.Deno = {
174
+ args: process.argv.slice(2),
175
+ pid: process.pid,
176
+ env: {
177
+ get: (k) => process.env[k],
178
+ set: (k, v) => {
179
+ process.env[k] = v;
180
+ },
181
+ has: (k) => Object.prototype.hasOwnProperty.call(process.env, k),
182
+ delete: (k) => {
183
+ delete process.env[k];
184
+ },
185
+ toObject: () => ({ ...process.env }),
186
+ },
187
+ cwd: () => process.cwd(),
188
+ exit: (code) => process.exit(code),
189
+ addSignalListener: (sig, handler) => {
190
+ process.on(sig, handler);
191
+ },
192
+ removeSignalListener: (sig, handler) => {
193
+ process.off(sig, handler);
194
+ },
195
+ readTextFile: (path) => fsReadFile(path, "utf8"),
196
+ writeTextFile: (path, data) => fsWriteFile(path, data),
197
+ readFile: async (path) => new Uint8Array(await fsReadFile(path)),
198
+ writeFile: (path, data) => fsWriteFile(path, data),
199
+ mkdir: (path, opts) => fsMkdir(path, opts ?? {}),
200
+ // Real `Deno.remove` throws `NotFound` on a missing path (no `force`), so
201
+ // map Node's ENOENT to it rather than silently succeeding — otherwise
202
+ // `Deno.errors.NotFound` would be unreachable and mask app bugs.
203
+ remove: async (path, opts) => {
204
+ try {
205
+ await fsRm(path, { recursive: !!opts?.recursive });
206
+ } catch (err) {
207
+ if (err && err.code === "ENOENT") {
208
+ throw new NotFound(`No such file or directory: remove '${path}'`);
209
+ }
210
+ throw err;
211
+ }
212
+ },
213
+ readDir,
214
+ stat: async (path) => {
215
+ const s = await fsStat(path);
216
+ return { isFile: s.isFile(), isDirectory: s.isDirectory(), size: s.size, mtime: s.mtime };
217
+ },
218
+ stdout: {
219
+ writeSync: (data) => fsWriteSync(1, toBytes(data)),
220
+ // Deno's async `write` resolves to the byte count; use the non-blocking
221
+ // stream write so heavy telemetry doesn't stall the event loop.
222
+ write: (data) => {
223
+ const bytes = toBytes(data);
224
+ return new Promise((resolve, reject) =>
225
+ process.stdout.write(bytes, (err) =>
226
+ err ? reject(err) : resolve(bytes.length),
227
+ ),
228
+ );
229
+ },
230
+ },
231
+ stderr: {
232
+ writeSync: (data) => fsWriteSync(2, toBytes(data)),
233
+ write: (data) => {
234
+ const bytes = toBytes(data);
235
+ return new Promise((resolve, reject) =>
236
+ process.stderr.write(bytes, (err) =>
237
+ err ? reject(err) : resolve(bytes.length),
238
+ ),
239
+ );
240
+ },
241
+ },
242
+ stdin: {
243
+ get readable() {
244
+ return Readable.toWeb(process.stdin);
245
+ },
246
+ },
247
+ errors: { NotFound },
248
+ serve,
249
+ };
250
+ }
@@ -0,0 +1,60 @@
1
+ // nanobpmn Node ESM loader (ADR 0036).
2
+ //
3
+ // Makes Node honor the project's `deno.json` import map so worker/App code
4
+ // authored for Deno runs unchanged under Node — the fallback worker runtime on
5
+ // hosts with no Deno build (e.g. 32-bit ARM). Node's built-in type stripping
6
+ // (`--experimental-strip-types`) handles the `.ts` sources; this loader only
7
+ // rewrites *specifiers*. Registered off-thread by `node-register.mjs`.
8
+ import { readFileSync } from "node:fs";
9
+ import { pathToFileURL } from "node:url";
10
+ import { resolve as resolvePath } from "node:path";
11
+
12
+ // The run's working directory is the directory that holds the `deno.json` whose
13
+ // import map applies — the project root for a RAD project run (`main.ts`), or the
14
+ // worker directory for a standalone worker (`worker.ts`). Both the map file and
15
+ // its relative values are resolved against it.
16
+ const baseDir = process.cwd();
17
+
18
+ function readImportMap() {
19
+ for (const name of ["deno.json", "deno.jsonc"]) {
20
+ try {
21
+ const raw = readFileSync(resolvePath(baseDir, name), "utf8");
22
+ return JSON.parse(raw).imports ?? {};
23
+ } catch {
24
+ // not present / unreadable — try the next candidate
25
+ }
26
+ }
27
+ return {};
28
+ }
29
+ const MAP = readImportMap();
30
+
31
+ // Deno import maps support exact keys and "prefix" keys ending in `/`.
32
+ function mapSpecifier(spec) {
33
+ if (Object.prototype.hasOwnProperty.call(MAP, spec)) return MAP[spec];
34
+ for (const [key, val] of Object.entries(MAP)) {
35
+ if (key.endsWith("/") && spec.startsWith(key)) return val + spec.slice(key.length);
36
+ }
37
+ return null;
38
+ }
39
+
40
+ export async function resolve(specifier, context, next) {
41
+ const mapped = mapSpecifier(specifier);
42
+ if (mapped == null) return next(specifier, context);
43
+
44
+ if (mapped.startsWith("npm:")) {
45
+ // `npm:pkg@range` -> bare `pkg`, resolved from node_modules (run
46
+ // `npm install` first). Strips the version range; keeps a leading @scope.
47
+ let bare = mapped.slice(4);
48
+ const at = bare.lastIndexOf("@");
49
+ if (at > 0) bare = bare.slice(0, at);
50
+ return next(bare, context);
51
+ }
52
+ if (mapped.startsWith("jsr:") || mapped.startsWith("http:") || mapped.startsWith("https:")) {
53
+ throw new Error(
54
+ `Node worker runtime cannot resolve '${specifier}' -> '${mapped}': ` +
55
+ `jsr:/https: imports require Deno. Install Deno, or vendor the dependency via npm.`,
56
+ );
57
+ }
58
+ // A relative path from the import map, resolved against the base dir.
59
+ return next(pathToFileURL(resolvePath(baseDir, mapped)).href, context);
60
+ }
@@ -0,0 +1,11 @@
1
+ // nanobpmn Node loader bootstrap (ADR 0036).
2
+ //
3
+ // Runs on the main thread via `--import ./nano-generated/node-register.mjs` when
4
+ // a project runs under the Node fallback runtime (no Deno build available). Two
5
+ // jobs: (1) install the `Deno` global shim so Deno-authored app/template code
6
+ // runs unchanged (node-deno-shim.mjs); (2) register the import-map loader
7
+ // (node-loader.mjs) on the module resolution thread.
8
+ import "./node-deno-shim.mjs";
9
+ import { register } from "node:module";
10
+
11
+ register("./node-loader.mjs", import.meta.url);
@@ -0,0 +1,28 @@
1
+ // AUTO-GENERATED by nanobpmn from the App manifest (ADR 0033 §3).
2
+ // The bridge from the process model to the worker type system: each declared
3
+ // worker's `taskType` maps to the TS type of its input payload (`job.variables`)
4
+ // and result, so the typed `defineWorker` types a handler by its job type. Do
5
+ // not edit — regenerated from the manifest. Erased to plain JS at compile.
6
+ // eslint-disable
7
+
8
+
9
+ /** Untyped fallback for a job whose worker declares no input/output type. */
10
+ export type WorkerVars = Record<string, unknown>;
11
+
12
+ /** Untyped fallback for a job whose worker declares no custom headers. */
13
+ export type WorkerHdrs = Record<string, unknown>;
14
+
15
+ /** Every declared worker `taskType` (ADR 0033 §3): the model-derived set the
16
+ * typed `defineWorker` accepts, so `type` autocompletes and rejects unknown jobs. */
17
+ export type WorkerTaskType = string;
18
+
19
+ /** Input payload (`job.variables`) per declared worker, keyed by `taskType`. */
20
+ export interface WorkerInputs {}
21
+
22
+ /** Output payload (worker result) per declared worker, keyed by `taskType`. */
23
+ export interface WorkerOutputs {}
24
+
25
+ /** Custom headers (`job.customHeaders`) per declared worker, keyed by `taskType`.
26
+ * Header values are strings on the wire, so each declared key maps to `string`;
27
+ * the extra index signature keeps undeclared headers accessible (non-breaking). */
28
+ export interface WorkerHeaders {}