reg-cli 0.18.16 → 0.19.0-rc0

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 (46) hide show
  1. package/README.md +155 -46
  2. package/dist/cli.cjs +221 -0
  3. package/dist/cli.d.cts +1 -0
  4. package/dist/cli.d.mts +1 -0
  5. package/dist/cli.mjs +221 -0
  6. package/dist/entry.cjs +119 -0
  7. package/dist/entry.d.cts +15 -0
  8. package/dist/entry.d.mts +15 -0
  9. package/dist/entry.mjs +118 -0
  10. package/dist/index.cjs +212 -0
  11. package/dist/index.d.cts +52 -0
  12. package/dist/index.d.mts +52 -0
  13. package/dist/index.mjs +206 -0
  14. package/dist/progress-BB7D-xke.mjs +28 -0
  15. package/dist/progress-UOiKHaTY.cjs +33 -0
  16. package/dist/reg.wasm +0 -0
  17. package/dist/rolldown-runtime-D_mwlA32.cjs +43 -0
  18. package/{report/ui/dist/worker.js → dist/shared/report-worker.js} +859 -247
  19. package/dist/tracing-7HO8hac9.mjs +378 -0
  20. package/dist/tracing-DlLL541f.cjs +445 -0
  21. package/dist/worker.cjs +143 -0
  22. package/dist/worker.d.cts +1 -0
  23. package/dist/worker.d.mts +1 -0
  24. package/dist/worker.mjs +142 -0
  25. package/dist/ximgdiff-DzkRRnkW.mjs +41 -0
  26. package/dist/ximgdiff-wmW1BH1H.cjs +41 -0
  27. package/package.json +61 -112
  28. package/dist/.keep +0 -0
  29. package/dist/cli.js +0 -214
  30. package/dist/diff.js +0 -80
  31. package/dist/icon.js +0 -12
  32. package/dist/image-finder.js +0 -25
  33. package/dist/index.js +0 -200
  34. package/dist/log.js +0 -21
  35. package/dist/process-adaptor.js +0 -40
  36. package/dist/report.js +0 -170
  37. package/dist/tracing.js +0 -169
  38. package/report/assets/favicon_failure.png +0 -0
  39. package/report/assets/favicon_success.png +0 -0
  40. package/report/sample/actual/sample.png +0 -0
  41. package/report/sample/diff/sample.png +0 -0
  42. package/report/sample/expected/sample.png +0 -0
  43. package/report/ui/dist/report.js +0 -123
  44. package/report/ui/dist/style.css +0 -1
  45. package/template/template.html +0 -20
  46. /package/{template → dist/shared}/worker_pre.js +0 -0
@@ -0,0 +1,445 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-D_mwlA32.cjs");
2
+ let path = require("path");
3
+ path = require_rolldown_runtime.__toESM(path, 1);
4
+ let url = require("url");
5
+ let node_fs_promises = require("node:fs/promises");
6
+ let node_path = require("node:path");
7
+ let node_process = require("node:process");
8
+ let node_module = require("node:module");
9
+ //#region src/utils.ts
10
+ const isCJS = typeof __dirname !== "undefined";
11
+ const readWasm = () => {
12
+ return (0, node_fs_promises.readFile)((0, node_path.join)(isCJS ? __dirname : path.default.dirname((0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href)), "./reg.wasm"));
13
+ };
14
+ const resolveExtention = () => {
15
+ return isCJS ? "cjs" : "mjs";
16
+ };
17
+ /**
18
+ * Host environment variables intentionally forwarded into the Wasm sandbox.
19
+ * Everything else (shell secrets, CI credentials, AWS_*, NPM_TOKEN, ...) is
20
+ * filtered out.
21
+ */
22
+ const FORWARDED_ENV = [
23
+ "OTEL_ENABLED",
24
+ "JAEGER_ENABLED",
25
+ "OTEL_DEBUG",
26
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
27
+ "OTEL_EXPORTER_OTLP_PROTOCOL",
28
+ "OTEL_SERVICE_NAME",
29
+ "OTEL_TRACES_EXPORTER",
30
+ "OTEL_RESOURCE_ATTRIBUTES"
31
+ ];
32
+ /**
33
+ * Longest directory path that every input in `paths` lives under. Treats
34
+ * each path as a sequence of "/"-separated segments; absolute-vs-relative
35
+ * mixes fall back to '.'.
36
+ */
37
+ const commonAncestor = (paths) => {
38
+ const defined = paths.filter(Boolean);
39
+ if (defined.length === 0) return ".";
40
+ if (defined.length === 1) return defined[0];
41
+ const isAbs = (p) => p.startsWith("/");
42
+ const anyAbs = defined.some(isAbs);
43
+ const allAbs = defined.every(isAbs);
44
+ if (anyAbs && !allAbs) return ".";
45
+ const split = defined.map((p) => p.split("/").filter(Boolean));
46
+ const shortest = Math.min(...split.map((s) => s.length));
47
+ const common = [];
48
+ for (let i = 0; i < shortest; i++) {
49
+ const seg = split[0][i];
50
+ if (split.every((s) => s[i] === seg)) common.push(seg);
51
+ else break;
52
+ }
53
+ if (common.length === 0) return allAbs ? "/" : ".";
54
+ return (allAbs ? "/" : "") + common.join("/");
55
+ };
56
+ /**
57
+ * Compute the minimum-capability WASI sandbox for a given reg-cli invocation:
58
+ *
59
+ * - preopen only the smallest ancestor directory that covers every path
60
+ * this run touches (actualDir, expectedDir, diffDir, and the parents
61
+ * of --report / --json)
62
+ * - forward only an allowlisted subset of host env into Wasm
63
+ *
64
+ * Before this, entry.ts / worker.ts did `preopens: { './': './' }` which
65
+ * exposed the entire cwd (and therefore `.npmrc`, `.env`, `node_modules`,
66
+ * etc.) to whatever runs inside Wasm. Narrowing matters because reg-cli
67
+ * deliberately ingests untrusted images from CI and image decoders
68
+ * (libpng, libwebp, libjpeg) have a long history of RCE-class CVEs.
69
+ *
70
+ * Why a single common-ancestor and not one preopen per directory:
71
+ * On the `wasm32-wasip1-threads` target, Rust's libstd only enumerates
72
+ * the first preopen returned by WASI (`fd_prestat_get(3)` is queried but
73
+ * `fd_prestat_get(4)` is never issued). Until that's fixed upstream,
74
+ * registering one preopen per dir effectively hides every dir but the
75
+ * first. Picking the narrowest *single* ancestor that still contains
76
+ * every touched path gives us a real-world win without tripping the bug.
77
+ *
78
+ * Caveats (follow-ups, not in this PR):
79
+ * - Symlinks and FIFOs inside the preopened directory are still resolved
80
+ * by the host, so an attacker who can plant files under `./diff/` could
81
+ * still exfiltrate via an evil symlink pointing outside the sandbox.
82
+ * Addressing this needs host-side WASI changes.
83
+ * - `@tybys/wasm-util`'s WASI still runs on top of Node's `fs` with full
84
+ * privilege (`fs: fs as IFs`); we only constrain *what paths Wasm is
85
+ * allowed to name*, not what the host fs underneath could do.
86
+ * - One-preopen-per-dir limitation above.
87
+ */
88
+ const computeWasiSandbox = (argv) => {
89
+ const args = argv[0] === "--" ? argv.slice(1) : argv;
90
+ const positional = [];
91
+ for (let i = 0; i < args.length && positional.length < 3; i++) {
92
+ if (args[i].startsWith("--")) break;
93
+ positional.push(args[i]);
94
+ }
95
+ const flagValue = (name) => {
96
+ const i = args.indexOf(name);
97
+ return i >= 0 && i + 1 < args.length ? args[i + 1] : void 0;
98
+ };
99
+ const dirs = [];
100
+ for (const p of positional) if (p) dirs.push(p);
101
+ const report = flagValue("--report");
102
+ const json = flagValue("--json");
103
+ const junit = flagValue("--junit");
104
+ const from = flagValue("--from") ?? flagValue("-F");
105
+ if (report) dirs.push((0, node_path.dirname)(report) || ".");
106
+ if (json) dirs.push((0, node_path.dirname)(json) || ".");
107
+ if (junit) dirs.push((0, node_path.dirname)(junit) || ".");
108
+ if (from) dirs.push((0, node_path.dirname)(from) || ".");
109
+ const preopenRoot = commonAncestor(dirs) || ".";
110
+ const mapWasm = (p) => p === "." || p === "./" || p.startsWith("/") || p.startsWith("./") ? p : `./${p}`;
111
+ const preopens = { [mapWasm(preopenRoot)]: preopenRoot };
112
+ if (!preopenRoot || preopenRoot === "." || preopenRoot === "./") preopens["./"] = "./";
113
+ const env = {};
114
+ for (const k of FORWARDED_ENV) {
115
+ const v = node_process.env[k];
116
+ if (v !== void 0) env[k] = v;
117
+ }
118
+ return {
119
+ preopens,
120
+ env
121
+ };
122
+ };
123
+ //#endregion
124
+ //#region src/tracing.ts
125
+ /**
126
+ * OpenTelemetry tracing utilities for reg-cli
127
+ *
128
+ * This module receives trace data from the Rust/WASM side and converts it
129
+ * to OpenTelemetry spans that can be exported to Jaeger or other backends.
130
+ *
131
+ * The @opentelemetry/* packages are declared as **optional peer
132
+ * dependencies** — they are loaded lazily inside `initTracing()` only when
133
+ * `OTEL_ENABLED=true` (or `JAEGER_ENABLED=true`). Default installs of this
134
+ * package therefore pay zero install or runtime cost for OTel.
135
+ */
136
+ const PKG_VERSION = (() => {
137
+ try {
138
+ return (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)("../package.json").version ?? "unknown";
139
+ } catch {
140
+ return "unknown";
141
+ }
142
+ })();
143
+ let otel = null;
144
+ let provider = null;
145
+ let isInitialized = false;
146
+ let currentRootSpan = null;
147
+ let currentRootContext = null;
148
+ /**
149
+ * Check if tracing is enabled via environment variable
150
+ */
151
+ const isTracingEnabled = () => {
152
+ return process.env.OTEL_ENABLED === "true" || process.env.JAEGER_ENABLED === "true";
153
+ };
154
+ /**
155
+ * Lazily import the @opentelemetry/* packages. Returns null and prints a
156
+ * single warning if any are missing — keeps the CLI working without OTel
157
+ * installed even when the env vars are set.
158
+ */
159
+ const loadOtel = async () => {
160
+ if (otel) return otel;
161
+ try {
162
+ const [api, resources, sdkBase, sdkNode, exporter, semconv] = await Promise.all([
163
+ import("@opentelemetry/api"),
164
+ import("@opentelemetry/resources"),
165
+ import("@opentelemetry/sdk-trace-base"),
166
+ import("@opentelemetry/sdk-trace-node"),
167
+ import("@opentelemetry/exporter-trace-otlp-http"),
168
+ import("@opentelemetry/semantic-conventions")
169
+ ]);
170
+ otel = {
171
+ api,
172
+ resources,
173
+ sdkBase,
174
+ sdkNode,
175
+ exporter,
176
+ semconv
177
+ };
178
+ return otel;
179
+ } catch (err) {
180
+ const pkgs = [
181
+ "@opentelemetry/api",
182
+ "@opentelemetry/exporter-trace-otlp-http",
183
+ "@opentelemetry/resources",
184
+ "@opentelemetry/sdk-trace-base",
185
+ "@opentelemetry/sdk-trace-node",
186
+ "@opentelemetry/semantic-conventions"
187
+ ].join(" ");
188
+ console.warn(`[Tracing] OTEL_ENABLED is set but the @opentelemetry/* peer dependencies are not installed. Continuing without tracing. To enable, install the peers alongside reg-cli, e.g.:
189
+ npm i -g ${pkgs} # if reg-cli is installed globally\n npm i ${pkgs} # if reg-cli is a project dependency`);
190
+ if (process.env.OTEL_DEBUG === "true") console.warn("[Tracing] Import error:", err);
191
+ return null;
192
+ }
193
+ };
194
+ /**
195
+ * Initialize OpenTelemetry SDK
196
+ */
197
+ const initTracing = async () => {
198
+ if (!isTracingEnabled() || isInitialized) return;
199
+ const mods = await loadOtel();
200
+ if (!mods) return;
201
+ const otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318/v1/traces";
202
+ const otlpExporter = new mods.exporter.OTLPTraceExporter({ url: otlpEndpoint });
203
+ provider = new mods.sdkNode.NodeTracerProvider({
204
+ resource: mods.resources.resourceFromAttributes({
205
+ [mods.semconv.ATTR_SERVICE_NAME]: "reg-cli",
206
+ [mods.semconv.ATTR_SERVICE_VERSION]: "0.18.10"
207
+ }),
208
+ spanProcessors: [new mods.sdkBase.BatchSpanProcessor(otlpExporter)]
209
+ });
210
+ provider.register();
211
+ isInitialized = true;
212
+ if (process.env.OTEL_DEBUG === "true") {
213
+ console.log("[Tracing] OpenTelemetry initialized");
214
+ console.log(`[Tracing] OTLP endpoint: ${otlpEndpoint}`);
215
+ }
216
+ };
217
+ /**
218
+ * Shutdown OpenTelemetry SDK gracefully
219
+ */
220
+ const shutdownTracing = async () => {
221
+ if (!provider || !isInitialized) return;
222
+ if (process.env.OTEL_DEBUG === "true") console.log("[Tracing] Starting SDK shutdown...");
223
+ try {
224
+ await provider.shutdown();
225
+ } catch (err) {
226
+ console.error("[Tracing] Error during shutdown:", err);
227
+ }
228
+ isInitialized = false;
229
+ provider = null;
230
+ if (process.env.OTEL_DEBUG === "true") console.log("[Tracing] OpenTelemetry SDK shut down");
231
+ };
232
+ /**
233
+ * Get the tracer instance
234
+ */
235
+ const getTracer = () => {
236
+ return otel.api.trace.getTracer("reg-cli", PKG_VERSION);
237
+ };
238
+ /**
239
+ * Start a root span and return context info to pass to Rust
240
+ */
241
+ const startRootSpan = (name) => {
242
+ if (!isTracingEnabled() || !isInitialized || !otel) return null;
243
+ currentRootSpan = getTracer().startSpan(name);
244
+ currentRootContext = otel.api.trace.setSpan(otel.api.ROOT_CONTEXT, currentRootSpan);
245
+ const spanContext = currentRootSpan.spanContext();
246
+ if (process.env.OTEL_DEBUG === "true") {
247
+ console.log(`[Tracing] Started root span: ${name}`);
248
+ console.log(`[Tracing] Trace ID: ${spanContext.traceId}`);
249
+ console.log(`[Tracing] Span ID: ${spanContext.spanId}`);
250
+ }
251
+ return {
252
+ traceId: spanContext.traceId,
253
+ spanId: spanContext.spanId
254
+ };
255
+ };
256
+ /**
257
+ * End the current root span
258
+ */
259
+ const endRootSpan = (success = true) => {
260
+ if (currentRootSpan && otel) {
261
+ if (success) currentRootSpan.setStatus({ code: otel.api.SpanStatusCode.OK });
262
+ else currentRootSpan.setStatus({ code: otel.api.SpanStatusCode.ERROR });
263
+ currentRootSpan.end();
264
+ if (process.env.OTEL_DEBUG === "true") console.log("[Tracing] Ended root span");
265
+ currentRootSpan = null;
266
+ currentRootContext = null;
267
+ }
268
+ };
269
+ /**
270
+ * Topologically sort spans so parents are always processed before children
271
+ */
272
+ const topologicalSortSpans = (spans) => {
273
+ const spanMap = /* @__PURE__ */ new Map();
274
+ const childrenMap = /* @__PURE__ */ new Map();
275
+ const rootSpans = [];
276
+ for (const span of spans) {
277
+ spanMap.set(span.span_id, span);
278
+ if (!span.parent_span_id) rootSpans.push(span.span_id);
279
+ else {
280
+ const children = childrenMap.get(span.parent_span_id) || [];
281
+ children.push(span.span_id);
282
+ childrenMap.set(span.parent_span_id, children);
283
+ }
284
+ }
285
+ if (process.env.OTEL_DEBUG === "true") {
286
+ console.log(`[Tracing] Total spans: ${spans.length}, Unique IDs in spanMap: ${spanMap.size}`);
287
+ console.log(`[Tracing] Root spans: ${rootSpans.join(", ")}`);
288
+ console.log(`[Tracing] All spans:`);
289
+ for (const span of spans) console.log(` ${span.span_id}: ${span.name} (parent: ${span.parent_span_id || "none"})`);
290
+ console.log(`[Tracing] Parent->Children map:`);
291
+ for (const [parent, children] of childrenMap.entries()) console.log(` ${parent} -> ${children.join(", ")}`);
292
+ }
293
+ const result = [];
294
+ const queue = [...rootSpans];
295
+ const visited = /* @__PURE__ */ new Set();
296
+ while (queue.length > 0) {
297
+ const spanId = queue.shift();
298
+ if (visited.has(spanId)) continue;
299
+ visited.add(spanId);
300
+ const span = spanMap.get(spanId);
301
+ if (span) {
302
+ result.push(span);
303
+ const children = childrenMap.get(spanId) || [];
304
+ queue.push(...children);
305
+ }
306
+ }
307
+ for (const span of spans) if (!visited.has(span.span_id)) {
308
+ if (process.env.OTEL_DEBUG === "true") console.log(`[Tracing] Orphan span: ${span.name} (id: ${span.span_id}, parent: ${span.parent_span_id})`);
309
+ result.push(span);
310
+ }
311
+ return result;
312
+ };
313
+ /**
314
+ * Convert Rust trace data to OpenTelemetry spans
315
+ *
316
+ * Since Rust spans have already ended by the time we receive them,
317
+ * we reconstruct them with their recorded timestamps.
318
+ */
319
+ const processRustTraceData = (traceData) => {
320
+ if (!isTracingEnabled() || !isInitialized || !otel) return;
321
+ const tracer = getTracer();
322
+ if (process.env.OTEL_DEBUG === "true") {
323
+ console.log(`[Tracing] Processing ${traceData.spans.length} spans from Rust`);
324
+ console.log(`[Tracing] JS parent context available: ${currentRootContext !== null}`);
325
+ }
326
+ const sortedSpans = topologicalSortSpans(traceData.spans);
327
+ const spanContextMap = /* @__PURE__ */ new Map();
328
+ for (const rustSpan of sortedSpans) {
329
+ const startTimeNs = rustSpan.start_time_ms * 1e6;
330
+ const endTimeNs = rustSpan.end_time_ms * 1e6;
331
+ let parentContext;
332
+ let parentInfo;
333
+ if (rustSpan.parent_span_id && spanContextMap.has(rustSpan.parent_span_id)) {
334
+ parentContext = spanContextMap.get(rustSpan.parent_span_id);
335
+ parentInfo = `rust parent: ${rustSpan.parent_span_id}`;
336
+ } else if (!rustSpan.parent_span_id && currentRootContext) {
337
+ parentContext = currentRootContext;
338
+ parentInfo = `js parent: ${currentRootSpan?.spanContext().spanId}`;
339
+ } else {
340
+ parentContext = currentRootContext || otel.api.ROOT_CONTEXT;
341
+ parentInfo = rustSpan.parent_span_id ? `orphan (parent ${rustSpan.parent_span_id} not found)` : "root (no js context)";
342
+ }
343
+ const span = tracer.startSpan(rustSpan.name, { startTime: [Math.floor(startTimeNs / 1e9), startTimeNs % 1e9] }, parentContext);
344
+ span.setAttribute("rust.target", rustSpan.target);
345
+ span.setAttribute("rust.level", rustSpan.level);
346
+ span.setAttribute("rust.span_id", rustSpan.span_id);
347
+ span.setAttribute("duration_ms", rustSpan.duration_ms);
348
+ for (const [key, value] of Object.entries(rustSpan.attributes)) span.setAttribute(`rust.${key}`, value);
349
+ if (rustSpan.status === "error") span.setStatus({
350
+ code: otel.api.SpanStatusCode.ERROR,
351
+ message: rustSpan.error_message || "Unknown error"
352
+ });
353
+ else span.setStatus({ code: otel.api.SpanStatusCode.OK });
354
+ span.end([Math.floor(endTimeNs / 1e9), endTimeNs % 1e9]);
355
+ const ctx = otel.api.trace.setSpan(parentContext, span);
356
+ spanContextMap.set(rustSpan.span_id, ctx);
357
+ if (process.env.OTEL_DEBUG === "true") console.log(`[Tracing] Created span: ${rustSpan.name} (${rustSpan.duration_ms}ms) [${parentInfo}] start=${rustSpan.start_time_ms}, end=${rustSpan.end_time_ms}`);
358
+ }
359
+ };
360
+ /**
361
+ * Convert worker-side timing events to OpenTelemetry spans attached under the
362
+ * current root span. Used to surface JS-bridge costs (Worker creation, wasm
363
+ * compile / instantiate, message round-trips) that Rust-side tracing cannot see.
364
+ */
365
+ const processWorkerSpans = (spans, workerLabel) => {
366
+ if (!isTracingEnabled() || !isInitialized || !otel || !spans?.length) return;
367
+ const tracer = getTracer();
368
+ const parentCtx = currentRootContext ?? otel.api.ROOT_CONTEXT;
369
+ for (const s of spans) {
370
+ const startNs = s.start_ms * 1e6;
371
+ const endNs = s.end_ms * 1e6;
372
+ const span = tracer.startSpan(s.name, { startTime: [Math.floor(startNs / 1e9), startNs % 1e9] }, parentCtx);
373
+ span.setAttribute("worker", s.worker_label ?? workerLabel);
374
+ span.setAttribute("duration_ms", s.end_ms - s.start_ms);
375
+ if (s.attributes) for (const [k, v] of Object.entries(s.attributes)) span.setAttribute(k, v);
376
+ span.end([Math.floor(endNs / 1e9), endNs % 1e9]);
377
+ }
378
+ };
379
+ //#endregion
380
+ Object.defineProperty(exports, "computeWasiSandbox", {
381
+ enumerable: true,
382
+ get: function() {
383
+ return computeWasiSandbox;
384
+ }
385
+ });
386
+ Object.defineProperty(exports, "endRootSpan", {
387
+ enumerable: true,
388
+ get: function() {
389
+ return endRootSpan;
390
+ }
391
+ });
392
+ Object.defineProperty(exports, "initTracing", {
393
+ enumerable: true,
394
+ get: function() {
395
+ return initTracing;
396
+ }
397
+ });
398
+ Object.defineProperty(exports, "isCJS", {
399
+ enumerable: true,
400
+ get: function() {
401
+ return isCJS;
402
+ }
403
+ });
404
+ Object.defineProperty(exports, "isTracingEnabled", {
405
+ enumerable: true,
406
+ get: function() {
407
+ return isTracingEnabled;
408
+ }
409
+ });
410
+ Object.defineProperty(exports, "processRustTraceData", {
411
+ enumerable: true,
412
+ get: function() {
413
+ return processRustTraceData;
414
+ }
415
+ });
416
+ Object.defineProperty(exports, "processWorkerSpans", {
417
+ enumerable: true,
418
+ get: function() {
419
+ return processWorkerSpans;
420
+ }
421
+ });
422
+ Object.defineProperty(exports, "readWasm", {
423
+ enumerable: true,
424
+ get: function() {
425
+ return readWasm;
426
+ }
427
+ });
428
+ Object.defineProperty(exports, "resolveExtention", {
429
+ enumerable: true,
430
+ get: function() {
431
+ return resolveExtention;
432
+ }
433
+ });
434
+ Object.defineProperty(exports, "shutdownTracing", {
435
+ enumerable: true,
436
+ get: function() {
437
+ return shutdownTracing;
438
+ }
439
+ });
440
+ Object.defineProperty(exports, "startRootSpan", {
441
+ enumerable: true,
442
+ get: function() {
443
+ return startRootSpan;
444
+ }
445
+ });
@@ -0,0 +1,143 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-D_mwlA32.cjs");
2
+ const require_tracing = require("./tracing-DlLL541f.cjs");
3
+ const require_progress = require("./progress-UOiKHaTY.cjs");
4
+ let node_worker_threads = require("node:worker_threads");
5
+ let node_process = require("node:process");
6
+ let node_fs = require("node:fs");
7
+ node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
8
+ let _tybys_wasm_util = require("@tybys/wasm-util");
9
+ //#region src/proxy.ts
10
+ const kIsProxy = Symbol("kIsProxy");
11
+ const createInstanceProxy = (instance, memory) => {
12
+ if (instance[kIsProxy]) return instance;
13
+ const originalExports = instance.exports;
14
+ const createHandler = function(target) {
15
+ const handlers = [
16
+ "apply",
17
+ "construct",
18
+ "defineProperty",
19
+ "deleteProperty",
20
+ "get",
21
+ "getOwnPropertyDescriptor",
22
+ "getPrototypeOf",
23
+ "has",
24
+ "isExtensible",
25
+ "ownKeys",
26
+ "preventExtensions",
27
+ "set",
28
+ "setPrototypeOf"
29
+ ];
30
+ const handler = {};
31
+ for (let i = 0; i < handlers.length; i++) {
32
+ const name = handlers[i];
33
+ handler[name] = function() {
34
+ const args = Array.prototype.slice.call(arguments, 1);
35
+ args.unshift(target);
36
+ return Reflect[name].apply(Reflect, args);
37
+ };
38
+ }
39
+ return handler;
40
+ };
41
+ const handler = createHandler(originalExports);
42
+ const _initialize = () => {};
43
+ const _start = () => 0;
44
+ handler.get = function(_target, p, receiver) {
45
+ if (p === "memory") return (typeof memory === "function" ? memory() : memory) ?? Reflect.get(originalExports, p, receiver);
46
+ if (p === "_initialize") return p in originalExports ? _initialize : void 0;
47
+ if (p === "_start") return p in originalExports ? _start : void 0;
48
+ return Reflect.get(originalExports, p, receiver);
49
+ };
50
+ handler.has = function(_target, p) {
51
+ if (p === "memory") return true;
52
+ return Reflect.has(originalExports, p);
53
+ };
54
+ const exportsProxy = new Proxy(Object.create(null), handler);
55
+ return new Proxy(instance, { get(target, p, receiver) {
56
+ if (p === "exports") return exportsProxy;
57
+ if (p === kIsProxy) return true;
58
+ return Reflect.get(target, p, receiver);
59
+ } });
60
+ };
61
+ //#endregion
62
+ //#region src/worker.ts
63
+ const isTracingEnabled = () => node_process.env.OTEL_ENABLED === "true" || node_process.env.JAEGER_ENABLED === "true";
64
+ const sandbox = require_tracing.computeWasiSandbox(node_worker_threads.workerData.argv);
65
+ const printErr = require_progress.createPrintErrHook((ev) => {
66
+ node_worker_threads.parentPort?.postMessage({
67
+ cmd: "compare-event",
68
+ event: ev
69
+ });
70
+ });
71
+ const wasi = new _tybys_wasm_util.WASI({
72
+ version: "preview1",
73
+ args: node_worker_threads.workerData.argv,
74
+ env: sandbox.env,
75
+ returnOnExit: true,
76
+ preopens: sandbox.preopens,
77
+ fs: node_fs.default,
78
+ printErr
79
+ });
80
+ const imports = wasi.getImportObject();
81
+ const file = require_tracing.readWasm();
82
+ const handler = async ({ startArg, tid, memory }) => {
83
+ const workerSpans = [];
84
+ const workerLabel = `thread-${tid}`;
85
+ const handler_start_ms = Date.now();
86
+ const tSpan = async (name, fn, attributes) => {
87
+ if (!isTracingEnabled()) return fn();
88
+ const start_ms = Date.now();
89
+ const r = await fn();
90
+ workerSpans.push({
91
+ name,
92
+ start_ms,
93
+ end_ms: Date.now(),
94
+ attributes,
95
+ worker_label: workerLabel
96
+ });
97
+ return r;
98
+ };
99
+ try {
100
+ const wasm = await tSpan("worker.wasm_compile", async () => WebAssembly.compile(await file));
101
+ let instance = await tSpan("worker.wasm_instantiate", async () => WebAssembly.instantiate(wasm, {
102
+ ...imports,
103
+ wasi: { "thread-spawn": (startArg) => {
104
+ const threadIdBuffer = new SharedArrayBuffer(4);
105
+ const id = new Int32Array(threadIdBuffer);
106
+ Atomics.store(id, 0, -1);
107
+ node_worker_threads.parentPort?.postMessage({
108
+ cmd: "thread-spawn",
109
+ startArg,
110
+ threadId: id,
111
+ memory
112
+ });
113
+ Atomics.wait(id, 0, -1);
114
+ return Atomics.load(id, 0);
115
+ } },
116
+ env: { memory }
117
+ }));
118
+ instance = createInstanceProxy(instance, memory);
119
+ await tSpan("worker.wasi_start", async () => {
120
+ wasi.start(instance);
121
+ });
122
+ await tSpan("worker.wasi_thread_start", async () => {
123
+ instance.exports.wasi_thread_start(tid, startArg);
124
+ }, { tid });
125
+ if (isTracingEnabled()) {
126
+ workerSpans.push({
127
+ name: "worker.thread_total",
128
+ start_ms: handler_start_ms,
129
+ end_ms: Date.now(),
130
+ worker_label: workerLabel,
131
+ attributes: { tid }
132
+ });
133
+ node_worker_threads.parentPort?.postMessage({
134
+ cmd: "worker-spans",
135
+ workerSpans
136
+ });
137
+ }
138
+ } catch (e) {
139
+ throw e;
140
+ }
141
+ };
142
+ node_worker_threads.parentPort?.addListener("message", handler);
143
+ //#endregion
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1 @@
1
+ export { };