relaxnative 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,431 @@
1
+ // src/worker/workerPool.ts
2
+ import { Worker } from "worker_threads";
3
+ import { existsSync } from "fs";
4
+ import { fileURLToPath } from "url";
5
+ var WORKER_ENTRY_TS_URL = new URL(
6
+ "./workerEntry.vitest.ts",
7
+ import.meta.url
8
+ );
9
+ var WORKER_ENTRY_JS_URL = new URL("./workerEntry.js", import.meta.url);
10
+ var worker = null;
11
+ var seq = 0;
12
+ var pending = /* @__PURE__ */ new Map();
13
+ function getWorker() {
14
+ if (!worker) {
15
+ if (existsSync(fileURLToPath(WORKER_ENTRY_JS_URL))) {
16
+ worker = new Worker(WORKER_ENTRY_JS_URL, {
17
+ env: { ...process.env }
18
+ });
19
+ } else {
20
+ const entryHref = WORKER_ENTRY_TS_URL.href;
21
+ const bootstrap = `import(${JSON.stringify(entryHref)});`;
22
+ worker = new Worker(bootstrap, {
23
+ eval: true,
24
+ env: { ...process.env }
25
+ });
26
+ }
27
+ worker.on("message", (msg) => {
28
+ const resolve = pending.get(msg.id);
29
+ if (resolve) {
30
+ resolve(msg);
31
+ pending.delete(msg.id);
32
+ }
33
+ });
34
+ }
35
+ return worker;
36
+ }
37
+ function runInWorker(req) {
38
+ const id = ++seq;
39
+ const w = getWorker();
40
+ return new Promise((resolve, reject) => {
41
+ pending.set(id, (res) => {
42
+ if (res.error) {
43
+ const err = new Error(res.error + (res.errorCallsite ? `
44
+ --- remote callsite ---
45
+ ${res.errorCallsite}` : ""));
46
+ reject(err);
47
+ } else resolve(res.result);
48
+ });
49
+ w.postMessage({ ...req, id });
50
+ });
51
+ }
52
+
53
+ // src/dx/logger.ts
54
+ var enabled = false;
55
+ function isDebugEnabled() {
56
+ return enabled || process.env.RELAXNATIVE_DEBUG === "1";
57
+ }
58
+ function logDebug(...args) {
59
+ if (!isDebugEnabled()) return;
60
+ console.log("[relaxnative]", ...args);
61
+ }
62
+
63
+ // src/utils/callsite.ts
64
+ function captureCallsite() {
65
+ const err = new Error();
66
+ if (!err.stack) return void 0;
67
+ const parts = err.stack.split("\n");
68
+ if (parts.length <= 2) return err.stack;
69
+ return parts.slice(2).join("\n");
70
+ }
71
+
72
+ // src/dx/trace.ts
73
+ import { performance } from "perf_hooks";
74
+ function envTraceEnabled() {
75
+ const v = process.env.RELAXNATIVE_TRACE;
76
+ return v === "1" || v === "true" || v === "yes";
77
+ }
78
+ function envTraceLevel() {
79
+ const v = (process.env.RELAXNATIVE_TRACE_LEVEL ?? "").toLowerCase();
80
+ if (v === "error" || v === "warn" || v === "info" || v === "debug") return v;
81
+ return "info";
82
+ }
83
+ var order = {
84
+ error: 0,
85
+ warn: 1,
86
+ info: 2,
87
+ debug: 3
88
+ };
89
+ function shouldTrace(level) {
90
+ if (!envTraceEnabled()) return false;
91
+ return order[level] <= order[envTraceLevel()];
92
+ }
93
+ function trace(level, event, data) {
94
+ if (!shouldTrace(level)) return;
95
+ const payload = {
96
+ t: Number(performance.now().toFixed(3)),
97
+ pid: process.pid,
98
+ level,
99
+ event
100
+ };
101
+ if (data !== void 0) payload.data = data;
102
+ console.log("[relaxnative:trace]", JSON.stringify(payload));
103
+ }
104
+ function traceError(event, data) {
105
+ trace("error", event, data);
106
+ }
107
+ function traceInfo(event, data) {
108
+ trace("info", event, data);
109
+ }
110
+ function traceDebug(event, data) {
111
+ trace("debug", event, data);
112
+ }
113
+ function formatBindingSignature(binding) {
114
+ if (!binding) return "";
115
+ const name = binding?.name ?? "<anonymous>";
116
+ const returns = binding?.returns ?? "void";
117
+ const args = Array.isArray(binding?.args) ? binding.args : [];
118
+ return `${returns} ${name}(${args.join(", ")})`;
119
+ }
120
+
121
+ // src/worker/workerClient.ts
122
+ function callAsync(libPath, bindings, fn, args) {
123
+ const callsite = captureCallsite();
124
+ logDebug("worker dispatch", { fn, callsite: !!callsite });
125
+ traceDebug("isolation.worker.dispatch", {
126
+ fn,
127
+ libPath,
128
+ argc: args?.length ?? 0,
129
+ argTypes: Array.isArray(args) ? args.map((a) => {
130
+ if (a == null) return String(a);
131
+ if (ArrayBuffer.isView(a)) return a.constructor?.name ?? "TypedArray";
132
+ return typeof a;
133
+ }) : [],
134
+ hasCallsite: !!callsite
135
+ });
136
+ return runInWorker({ libPath, bindings, fn, args, callsite });
137
+ }
138
+
139
+ // src/worker/processClient.ts
140
+ import { fork } from "child_process";
141
+ import { fileURLToPath as fileURLToPath2 } from "url";
142
+ import { dirname, join } from "path";
143
+ import { existsSync as existsSync2 } from "fs";
144
+ var ProcessIsolationError = class extends Error {
145
+ code;
146
+ details;
147
+ constructor(code, message, details) {
148
+ super(message);
149
+ this.code = code;
150
+ this.details = details;
151
+ }
152
+ };
153
+ var child = null;
154
+ var seq2 = 0;
155
+ var pending2 = /* @__PURE__ */ new Map();
156
+ function helperEntryPath() {
157
+ const here = dirname(fileURLToPath2(import.meta.url));
158
+ let cur = here;
159
+ for (let i = 0; i < 8; i++) {
160
+ const candidate = join(cur, "package.json");
161
+ if (existsSync2(candidate)) {
162
+ const pkgRoot2 = cur;
163
+ const distEntry2 = join(pkgRoot2, "dist", "worker", "processEntry.js");
164
+ return { distEntry: distEntry2, pkgRoot: pkgRoot2 };
165
+ }
166
+ const parent = join(cur, "..");
167
+ if (parent === cur) break;
168
+ cur = parent;
169
+ }
170
+ const pkgRoot = join(here, "..", "..");
171
+ const distEntry = join(pkgRoot, "dist", "worker", "processEntry.js");
172
+ return { distEntry, pkgRoot };
173
+ }
174
+ function startChild() {
175
+ if (child && child.connected) return child;
176
+ const { distEntry } = helperEntryPath();
177
+ if (!existsSync2(distEntry)) {
178
+ traceError("isolation.process.helper.missing", { distEntry });
179
+ throw new ProcessIsolationError(
180
+ "ISOLATED_PROCESS_START_FAILED",
181
+ `Process isolation helper was not found at: ${distEntry}. This usually means the package was published without dist/worker/processEntry.js`,
182
+ { distEntry }
183
+ );
184
+ }
185
+ const entry = distEntry;
186
+ traceInfo("isolation.process.helper.start", { entry });
187
+ const cp = fork(entry, {
188
+ stdio: ["ignore", "inherit", "inherit", "ipc"],
189
+ env: {
190
+ ...process.env,
191
+ RELAXNATIVE_PROCESS_ISOLATION: "1"
192
+ }
193
+ });
194
+ cp.on("message", (msg) => {
195
+ if (!msg || typeof msg.id !== "number") return;
196
+ const p = pending2.get(msg.id);
197
+ if (!p) return;
198
+ if (p.cp !== cp) return;
199
+ pending2.delete(msg.id);
200
+ const res = msg;
201
+ if (res.ok) p.resolve(res.result);
202
+ else {
203
+ const details = [res.error.message];
204
+ if (res.error.callsite) details.push("\n--- remote callsite ---\n" + res.error.callsite);
205
+ const err = new Error(details.join("\n"));
206
+ err.name = res.error.name;
207
+ err.stack = res.error.stack;
208
+ p.reject(err);
209
+ }
210
+ });
211
+ const rejectAll = (reason) => {
212
+ for (const [id, p] of pending2) {
213
+ if (p.cp !== cp) continue;
214
+ pending2.delete(id);
215
+ p.reject(reason);
216
+ }
217
+ };
218
+ cp.on("exit", (code, signal) => {
219
+ if (child === cp) child = null;
220
+ const reason = new ProcessIsolationError(
221
+ signal ? "ISOLATED_PROCESS_CRASH" : "ISOLATED_PROCESS_EXIT",
222
+ `Isolated runtime exited (code=${code}, signal=${signal ?? "none"})`,
223
+ { code, signal }
224
+ );
225
+ traceError("isolation.process.helper.exit", { code, signal });
226
+ rejectAll(reason);
227
+ });
228
+ cp.on("error", (err) => {
229
+ const reason = new ProcessIsolationError(
230
+ "ISOLATED_PROCESS_START_FAILED",
231
+ `Failed to start isolated runtime: ${String(err)}`,
232
+ { err }
233
+ );
234
+ traceError("isolation.process.helper.error", { message: String(err) });
235
+ child = null;
236
+ rejectAll(reason);
237
+ });
238
+ child = cp;
239
+ return cp;
240
+ }
241
+ async function ping(cp) {
242
+ const id = ++seq2;
243
+ const req = { id, type: "ping" };
244
+ traceDebug("isolation.process.ping", { id });
245
+ return new Promise((resolve, reject) => {
246
+ pending2.set(id, { resolve, reject, cp });
247
+ cp.send(req);
248
+ });
249
+ }
250
+ async function callIsolated(libPath, bindings, fn, args, safety, callsite) {
251
+ const originalArgs = Array.isArray(args) ? args : [];
252
+ const cp = startChild();
253
+ await ping(cp);
254
+ const id = ++seq2;
255
+ traceDebug("isolation.process.call", {
256
+ id,
257
+ fn,
258
+ argc: args?.length ?? 0,
259
+ hasSafety: !!safety,
260
+ hasCallsite: !!callsite
261
+ });
262
+ const req = {
263
+ id,
264
+ type: "call",
265
+ libPath,
266
+ bindings,
267
+ safety,
268
+ fn,
269
+ // Structured-clone can't send TypedArrays as "real" typed arrays through fork IPC
270
+ // in a way that koffi consistently recognizes in the helper.
271
+ // We serialize them explicitly and reconstruct in processEntry.
272
+ args: Array.isArray(args) ? args.map((a) => {
273
+ if (a && ArrayBuffer.isView(a)) {
274
+ const view = a;
275
+ return {
276
+ __relaxnative_typedarray: true,
277
+ type: a.constructor?.name ?? "TypedArray",
278
+ // clone exact bytes used by the view
279
+ bytes: Buffer.from(
280
+ view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)
281
+ )
282
+ };
283
+ }
284
+ return a;
285
+ }) : args,
286
+ // forward the captured JS callsite for richer crash diagnostics
287
+ ...callsite ? { callsite } : {}
288
+ };
289
+ const timeoutMs = safety?.limits?.timeoutMs;
290
+ const baseCall = new Promise((resolve, reject) => {
291
+ let t = null;
292
+ let timedOut = false;
293
+ const wrappedResolve = (v) => {
294
+ if (timedOut) return;
295
+ if (t) clearTimeout(t);
296
+ resolve(v);
297
+ };
298
+ const wrappedReject = (e) => {
299
+ if (timedOut) return;
300
+ if (t) clearTimeout(t);
301
+ reject(e);
302
+ };
303
+ if (typeof timeoutMs === "number" && timeoutMs > 0) {
304
+ t = setTimeout(() => {
305
+ timedOut = true;
306
+ pending2.delete(id);
307
+ try {
308
+ cp.kill();
309
+ } catch {
310
+ }
311
+ wrappedReject(
312
+ new ProcessIsolationError(
313
+ "ISOLATED_PROCESS_CRASH",
314
+ `Isolated runtime exceeded timeout (${timeoutMs}ms)`,
315
+ { timeoutMs }
316
+ )
317
+ );
318
+ }, timeoutMs);
319
+ }
320
+ pending2.set(id, { resolve: wrappedResolve, reject: wrappedReject, cp });
321
+ cp.send(req);
322
+ });
323
+ const withResult = async () => {
324
+ const result = await baseCall;
325
+ const returnedBoxedArgs = Array.isArray(result?.args) ? result.args : null;
326
+ if (returnedBoxedArgs) {
327
+ for (let i = 0; i < returnedBoxedArgs.length; i++) {
328
+ const orig = originalArgs[i];
329
+ const boxed = returnedBoxedArgs[i];
330
+ if (orig && ArrayBuffer.isView(orig) && boxed?.__relaxnative_typedarray === true) {
331
+ const bytesObj = boxed.bytes;
332
+ const buf = Buffer.isBuffer(bytesObj) ? bytesObj : bytesObj?.type === "Buffer" && Array.isArray(bytesObj?.data) ? Buffer.from(bytesObj.data) : Buffer.from([]);
333
+ const u8 = new Uint8Array(orig.buffer, orig.byteOffset ?? 0, orig.byteLength ?? 0);
334
+ u8.set(new Uint8Array(buf.buffer, buf.byteOffset, Math.min(buf.byteLength, u8.byteLength)));
335
+ }
336
+ }
337
+ }
338
+ return result?.result ?? result;
339
+ };
340
+ if (typeof timeoutMs === "number" && timeoutMs > 0) {
341
+ return Promise.race([
342
+ withResult(),
343
+ new Promise((_, reject) => {
344
+ setTimeout(() => {
345
+ reject(
346
+ new ProcessIsolationError(
347
+ "ISOLATED_PROCESS_CRASH",
348
+ `Isolated runtime exceeded timeout (${timeoutMs}ms)`,
349
+ { timeoutMs }
350
+ )
351
+ );
352
+ }, timeoutMs + 25);
353
+ })
354
+ ]);
355
+ }
356
+ return withResult();
357
+ }
358
+
359
+ // src/worker/wrapFunctions.ts
360
+ function wrapFunctions(api, libPath, bindings, opts) {
361
+ const wrapped = {};
362
+ const isolation = opts?.isolation ?? "worker";
363
+ const safety = bindings?.__safety ?? { trust: "local" };
364
+ const bindingNames = Object.keys(bindings?.functions ?? {});
365
+ const apiNames = Object.keys(api ?? {});
366
+ const names = Array.from(/* @__PURE__ */ new Set([...bindingNames, ...apiNames]));
367
+ for (const name of names) {
368
+ const fn = api?.[name];
369
+ const binding = bindings?.functions?.[name];
370
+ const isAsync = binding?.mode === "async" || binding?.async === true || binding?.thread === "worker" || binding?.cost === "high";
371
+ wrapped[name] = (...args) => {
372
+ traceDebug("dispatch", {
373
+ isolation,
374
+ fn: name,
375
+ argc: args?.length ?? 0,
376
+ mode: binding?.mode,
377
+ cost: binding?.cost
378
+ });
379
+ if (isolation === "process") {
380
+ return callIsolated(libPath, bindings, name, args, safety);
381
+ }
382
+ if (isolation === "worker") {
383
+ if (typeof fn === "function" && !isAsync) {
384
+ return fn(...args);
385
+ }
386
+ return callAsync(libPath, bindings, name, args);
387
+ }
388
+ if (typeof fn !== "function") {
389
+ const available = Object.keys(api ?? {});
390
+ const sig = binding ? formatBindingSignature(binding) : void 0;
391
+ const detail = [
392
+ `Function not found: ${name}`,
393
+ sig ? `Signature (from parser): ${sig}` : void 0,
394
+ available.length ? `Available exports: ${available.join(", ")}` : void 0
395
+ ].filter(Boolean);
396
+ throw new Error(detail.join("\n"));
397
+ }
398
+ return fn(...args);
399
+ };
400
+ }
401
+ if (isolation === "process") {
402
+ wrapped.__call = (fn, ...args) => callIsolated(libPath, bindings, fn, args, safety, captureCallsite());
403
+ return new Proxy(wrapped, {
404
+ get(target, prop) {
405
+ if (typeof prop !== "string") return target[prop];
406
+ if (prop === "then") return void 0;
407
+ if (prop in target) return target[prop];
408
+ return (...args) => callIsolated(libPath, bindings, prop, args, safety, captureCallsite());
409
+ }
410
+ });
411
+ }
412
+ if (isolation === "worker") {
413
+ return new Proxy(wrapped, {
414
+ get(target, prop) {
415
+ if (typeof prop !== "string") return target[prop];
416
+ if (prop === "then") return void 0;
417
+ if (prop in target) return target[prop];
418
+ return (...args) => callAsync(libPath, bindings, prop, args);
419
+ }
420
+ });
421
+ }
422
+ return wrapped;
423
+ }
424
+
425
+ export {
426
+ logDebug,
427
+ traceInfo,
428
+ traceDebug,
429
+ formatBindingSignature,
430
+ wrapFunctions
431
+ };