@pi-oxide/extension-js 0.3.0 → 0.4.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.
package/worker.js CHANGED
@@ -1,24 +1,36 @@
1
- import z, { setLogLevel as L, ExtensionSession as G, registerJsCallBatch as H } from "../../pkg/extension_js.js";
1
+ import Q, { setLogLevel as I, ExtensionSession as X, registerJsCallBatch as Z } from "../../pkg/extension_js.js";
2
2
  import "zod";
3
- const w = {
4
- debug: 0,
5
- info: 1,
6
- warn: 2,
7
- error: 3,
8
- none: 4
9
- };
10
- let E = "error", S = null;
11
- function J(r) {
12
- E = r, S && S(w[r]);
3
+ const R = {
4
+ trace: 0,
5
+ debug: 1,
6
+ info: 2,
7
+ warn: 3,
8
+ error: 4,
9
+ none: 5
10
+ }, x = [
11
+ "trace",
12
+ "debug",
13
+ "info",
14
+ "warn",
15
+ "error",
16
+ "none"
17
+ ];
18
+ function ee(r) {
19
+ const e = Math.max(0, Math.min(5, Math.round(r)));
20
+ return x[e] ?? "error";
21
+ }
22
+ let $ = "trace", L = null;
23
+ function re(r) {
24
+ $ = r, L && L(R[r]);
13
25
  }
14
- function V(r) {
15
- S = r, E !== "error" && r(w[E]);
26
+ function te(r) {
27
+ L = r, r(R[$]);
16
28
  }
17
- function q(r) {
18
- return w[r] >= w[E];
29
+ function ne(r) {
30
+ return R[r] >= R[$];
19
31
  }
20
- function U(r, e = "info") {
21
- var t;
32
+ function H(r, e = "info") {
33
+ var n;
22
34
  if (r === null) return "null";
23
35
  if (r === void 0) return "undefined";
24
36
  if (typeof r == "string") return r;
@@ -26,106 +38,109 @@ function U(r, e = "info") {
26
38
  return String(r);
27
39
  if (typeof r == "bigint") return `${r}n`;
28
40
  if (r instanceof Error) {
29
- const n = e === "debug" ? r.stack : (t = r.stack) == null ? void 0 : t.split(`
41
+ const t = e === "debug" || e === "trace" ? r.stack : (n = r.stack) == null ? void 0 : n.split(`
30
42
  `)[0];
31
- return JSON.stringify({ message: r.message, name: r.name, stack: n });
43
+ return JSON.stringify({ message: r.message, name: r.name, stack: t });
32
44
  }
33
45
  if (typeof r == "function") return "[Function]";
34
46
  if (typeof r == "symbol") return String(r);
35
47
  if (typeof r == "object")
36
48
  try {
37
49
  return JSON.stringify(r);
38
- } catch (n) {
39
- return n instanceof TypeError && n.message.includes("circular") ? "[Circular]" : `[Unserializable: ${n instanceof Error ? n.message : String(n)}]`;
50
+ } catch (t) {
51
+ return t instanceof TypeError && t.message.includes("circular") ? "[Circular]" : `[Unserializable: ${t instanceof Error ? t.message : String(t)}]`;
40
52
  }
41
53
  return String(r);
42
54
  }
43
- function K(r) {
55
+ function se(r) {
44
56
  return `[extension-js][${r}]`;
45
57
  }
46
- function X(r, e) {
58
+ function oe(r, e) {
47
59
  if (!r) return "";
48
- const t = [];
60
+ const n = [];
49
61
  try {
50
- for (const [n, s] of Object.entries(r))
51
- t.push(`${n}=${U(s, e)}`);
62
+ for (const [t, s] of Object.entries(r))
63
+ n.push(`${t}=${H(s, e)}`);
52
64
  } catch {
53
65
  return " metadata=[unreadable]";
54
66
  }
55
- return t.length > 0 ? ` ${t.join(" ")}` : "";
67
+ return n.length > 0 ? ` ${n.join(" ")}` : "";
56
68
  }
57
- function h(r, e) {
69
+ function b(r, e) {
58
70
  return e.length === 0 ? { event: r } : e.length === 1 && typeof e[0] == "object" && e[0] !== null && !Array.isArray(e[0]) ? { event: r, metadata: e[0] } : {
59
71
  event: r,
60
- metadata: { _args: e.map((t) => U(t)).join(" ") }
72
+ metadata: { _args: e.map((n) => H(n)).join(" ") }
61
73
  };
62
74
  }
63
- class I {
75
+ class P {
64
76
  constructor(e = "root") {
65
77
  this.namespace = e;
66
78
  }
67
- log(e, t, n) {
79
+ log(e, n, t) {
68
80
  try {
69
- if (!q(e)) return;
70
- const s = K(this.namespace), a = X(n, e), o = `${s} ${t}${a}`;
81
+ if (!ne(e)) return;
82
+ const s = se(this.namespace), o = oe(t, e), i = `${s} ${n}${o}`;
71
83
  switch (e) {
84
+ case "trace":
72
85
  case "debug":
73
- console.log(o);
74
- break;
75
86
  case "info":
76
- console.log(o);
87
+ console.log(i);
77
88
  break;
78
89
  case "warn":
79
- console.warn(o);
90
+ console.warn(i);
80
91
  break;
81
92
  case "error":
82
- console.error(o);
93
+ console.error(i);
83
94
  break;
84
95
  case "none":
85
96
  break;
86
97
  default: {
87
- const f = e;
98
+ const a = e;
88
99
  break;
89
100
  }
90
101
  }
91
102
  } catch {
92
103
  }
93
104
  }
94
- debug(e, ...t) {
95
- const { event: n, metadata: s } = h(e, t);
96
- this.log("debug", n, s);
105
+ trace(e, ...n) {
106
+ const { event: t, metadata: s } = b(e, n);
107
+ this.log("trace", t, s);
108
+ }
109
+ debug(e, ...n) {
110
+ const { event: t, metadata: s } = b(e, n);
111
+ this.log("debug", t, s);
97
112
  }
98
- info(e, ...t) {
99
- const { event: n, metadata: s } = h(e, t);
100
- this.log("info", n, s);
113
+ info(e, ...n) {
114
+ const { event: t, metadata: s } = b(e, n);
115
+ this.log("info", t, s);
101
116
  }
102
- warn(e, ...t) {
103
- const { event: n, metadata: s } = h(e, t);
104
- this.log("warn", n, s);
117
+ warn(e, ...n) {
118
+ const { event: t, metadata: s } = b(e, n);
119
+ this.log("warn", t, s);
105
120
  }
106
- error(e, ...t) {
107
- const { event: n, metadata: s } = h(e, t);
108
- this.log("error", n, s);
121
+ error(e, ...n) {
122
+ const { event: t, metadata: s } = b(e, n);
123
+ this.log("error", t, s);
109
124
  }
110
125
  child(e) {
111
- return new I(`${this.namespace}.${e}`);
126
+ return new P(`${this.namespace}.${e}`);
112
127
  }
113
- timer(e, t, n = "info") {
114
- const s = typeof performance < "u" && performance.now, a = s ? performance.now() : Date.now();
115
- return (o) => {
128
+ timer(e, n, t = "info") {
129
+ const s = typeof performance < "u" && performance.now, o = s ? performance.now() : Date.now();
130
+ return (i) => {
116
131
  try {
117
- const f = s ? performance.now() : Date.now(), l = Math.round(f - a), d = {
118
- ...t,
119
- ...o,
120
- duration_ms: l
132
+ const a = s ? performance.now() : Date.now(), g = Math.round(a - o), p = {
133
+ ...n,
134
+ ...i,
135
+ duration_ms: g
121
136
  };
122
- this.log(n, e, d);
137
+ this.log(t, e, p);
123
138
  } catch {
124
139
  }
125
140
  };
126
141
  }
127
142
  }
128
- const m = new I("root"), Y = /* @__PURE__ */ new Set([
143
+ const l = new P("root"), ae = /* @__PURE__ */ new Set([
129
144
  "page_url",
130
145
  "page_title",
131
146
  "page_click",
@@ -154,38 +169,38 @@ const m = new I("root"), Y = /* @__PURE__ */ new Set([
154
169
  "tab_dblclick",
155
170
  "tab_back"
156
171
  ]);
157
- function Q(r) {
158
- return Y.has(r);
172
+ function ie(r) {
173
+ return ae.has(r);
159
174
  }
160
- const Z = /* @__PURE__ */ new Map();
161
- function x(r, e) {
162
- Z.set(r, e);
175
+ const le = /* @__PURE__ */ new Map();
176
+ function ce(r, e) {
177
+ le.set(r, e);
163
178
  }
164
- function ee(r) {
179
+ function ue(r) {
165
180
  return r.startsWith("tab_") ? "required" : "active";
166
181
  }
167
- function re(r) {
182
+ function de(r) {
168
183
  return r === "content-script" ? "content-script" : r === "main-thread" ? "main-thread" : r === "worker" ? "worker:default" : r.startsWith("worker:") ? r : "main-thread";
169
184
  }
170
- function te(r, e) {
171
- return e !== "main-thread" ? e : Q(r) ? "content-script" : e;
185
+ function fe(r, e) {
186
+ return e !== "main-thread" ? e : ie(r) ? "content-script" : e;
172
187
  }
173
- function ne(r, e) {
188
+ function ge(r, e) {
174
189
  return {
175
- endpoint: re(te(r, e)),
176
- tabPolicy: ee(r)
190
+ endpoint: de(fe(r, e)),
191
+ tabPolicy: ue(r)
177
192
  };
178
193
  }
179
- function se(r) {
194
+ function pe(r) {
180
195
  for (const e of r)
181
- x(e.action, ne(e.action, e.owner));
196
+ ce(e.action, ge(e.action, e.owner));
182
197
  }
183
- function k(r) {
198
+ function T(r) {
184
199
  return r == null ? {} : r instanceof Map ? Object.fromEntries(
185
- [...r.entries()].map(([e, t]) => [e, k(t)])
186
- ) : Array.isArray(r) ? r.map(k) : r;
200
+ [...r.entries()].map(([e, n]) => [e, T(n)])
201
+ ) : Array.isArray(r) ? r.map(T) : r;
187
202
  }
188
- function oe(r) {
203
+ function me(r) {
189
204
  return {
190
205
  action: r.action,
191
206
  namespace: r.namespace,
@@ -209,251 +224,321 @@ function oe(r) {
209
224
  description: r.returnsDoc.description
210
225
  },
211
226
  errorCode: r.errorCode,
212
- errorCategory: r.errorCategory ?? null
227
+ errorCategory: r.errorCategory ?? null,
228
+ permission: r.permission ?? null,
229
+ example: r.example ?? null
213
230
  };
214
231
  }
215
- m.child("tool-registry");
216
- let c = null, T = !1;
217
- const y = /* @__PURE__ */ new Map();
218
- function R(r, e) {
232
+ l.child("tool-registry");
233
+ let y = null, v = !1;
234
+ const _ = /* @__PURE__ */ new Map();
235
+ function A(r, e) {
219
236
  try {
220
237
  return r.postMessage(e), !0;
221
- } catch (t) {
222
- const n = t instanceof Error ? t.message : String(t);
223
- return m.error("port_post_failed", { error: n }), !1;
238
+ } catch (n) {
239
+ const t = n instanceof Error ? n.message : String(n);
240
+ return l.error("port_post_failed", { error: t }), !1;
224
241
  }
225
242
  }
226
- const B = 1e3;
227
- function j(r, e, t) {
228
- e === "main-thread" || e === "content-script" ? R(t, { type: "relayCancel", id: r, owner: e }) : R(t, { type: "registryCallCancel", id: r });
243
+ const z = 1e3;
244
+ function J(r, e, n) {
245
+ e === "main-thread" || e === "content-script" ? A(n, { type: "relayCancel", id: r, owner: e }) : A(n, { type: "registryCallCancel", id: r });
229
246
  }
230
- function F(r, e) {
231
- for (const [t, n] of y)
232
- clearTimeout(n.timeoutId), j(t, n.owner, n.port), n.settle({
247
+ function G(r, e) {
248
+ for (const [n, t] of _)
249
+ clearTimeout(t.timeoutId), J(n, t.owner, t.port), t.settle({
233
250
  ok: !1,
234
251
  error: { message: e, code: r }
235
- }), y.delete(t);
252
+ }), _.delete(n);
253
+ }
254
+ const S = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new Map();
255
+ let q = Promise.resolve(), d = null;
256
+ function ye(r) {
257
+ l.trace("sessionQueue_enqueue");
258
+ const e = q.then(r);
259
+ return q = e.then(
260
+ () => {
261
+ },
262
+ () => {
263
+ }
264
+ ), e;
236
265
  }
237
- const A = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map();
238
- function i(r, e) {
239
- A.set(r, e);
266
+ function Y(r) {
267
+ d && (l.error("runCell_worker_failure", {
268
+ runId: d.runId,
269
+ callId: d.id,
270
+ error: r
271
+ }), self.postMessage({
272
+ type: "error",
273
+ id: d.id,
274
+ error: r,
275
+ runId: d.runId
276
+ }), d = null);
240
277
  }
241
- function ae() {
278
+ self.addEventListener("error", (r) => {
279
+ const e = r.message || (r.error instanceof Error ? r.error.message : "Worker uncaught error");
280
+ l.error("worker_uncaught_error", { error: e }), Y(e);
281
+ });
282
+ self.addEventListener("unhandledrejection", (r) => {
283
+ const e = r.reason, n = e instanceof Error ? e.message : String(e ?? "Unhandled rejection");
284
+ l.error("worker_unhandled_rejection", { error: n }), Y(n);
285
+ });
286
+ function c(r, e) {
287
+ S.set(r, e);
288
+ }
289
+ function _e() {
242
290
  const r = new Uint8Array(16);
243
291
  return crypto.getRandomValues(r), Array.from(r, (e) => e.toString(16).padStart(2, "0")).join("");
244
292
  }
245
- function ie(r) {
246
- return r <= 0 ? "debug" : r === 1 ? "info" : r === 2 ? "warn" : r === 3 ? "error" : "none";
293
+ function be(r) {
294
+ return ee(r);
247
295
  }
248
- const C = /* @__PURE__ */ new Map(), _ = /* @__PURE__ */ new Map();
249
- function le(r, e) {
250
- var t;
251
- if (C.has(r))
296
+ const O = /* @__PURE__ */ new Map(), M = /* @__PURE__ */ new Map();
297
+ function he(r, e) {
298
+ var n;
299
+ if (O.has(r))
252
300
  throw new Error(`Worker port already registered for owner: ${r}`);
253
301
  if (typeof e.addEventListener != "function")
254
302
  throw new Error(`Worker port for owner "${r}" cannot receive responses`);
255
- C.set(r, e), e.addEventListener("message", async (n) => {
256
- var a;
257
- const s = n.data;
303
+ O.set(r, e), e.addEventListener("message", async (t) => {
304
+ var o;
305
+ const s = t.data;
258
306
  if (s !== null && (s.type === "asyncRelayResult" || s.type === "registryCallResult") && typeof s.id == "string") {
259
- $(s.id, s.result);
307
+ N(s.id, s.result);
260
308
  return;
261
309
  }
262
310
  if (s !== null && s.type === "registryCallCancel" && typeof s.id == "string") {
263
- (a = _.get(s.id)) == null || a.abort(), _.delete(s.id);
311
+ (o = M.get(s.id)) == null || o.abort(), M.delete(s.id);
264
312
  return;
265
313
  }
266
314
  if (s !== null && s.type === "registryCall" && typeof s.id == "string" && typeof s.action == "string") {
267
- const o = s.id, f = new AbortController();
268
- _.set(o, f);
269
- const l = A.get(s.action);
270
- let d;
271
- if (!l)
272
- d = {
315
+ const i = s.id, a = new AbortController();
316
+ M.set(i, a);
317
+ const g = S.get(s.action);
318
+ let p;
319
+ if (!g)
320
+ p = {
273
321
  ok: !1,
274
322
  error: { message: `Unknown worker action: ${s.action}`, code: "E_UNKNOWN" }
275
323
  };
276
324
  else
277
325
  try {
278
- const u = await l(s.params, {
326
+ const u = await g(s.params, {
279
327
  action: s.action,
280
328
  callId: s.callId,
281
329
  runId: s.runId,
282
- signal: f.signal
330
+ signal: a.signal
283
331
  });
284
- d = f.signal.aborted ? { ok: !1, error: { message: "Relay aborted", code: "E_ABORT" } } : { ok: !0, value: u };
332
+ p = a.signal.aborted ? { ok: !1, error: { message: "Relay aborted", code: "E_ABORT" } } : { ok: !0, value: u };
285
333
  } catch (u) {
286
- d = {
334
+ p = {
287
335
  ok: !1,
288
336
  error: {
289
337
  message: u instanceof Error ? u.message : String(u),
290
- code: f.signal.aborted ? "E_ABORT" : "E_WORKER_HANDLER"
338
+ code: a.signal.aborted ? "E_ABORT" : "E_WORKER_HANDLER"
291
339
  }
292
340
  };
293
341
  }
294
- _.delete(o), R(e, { type: "registryCallResult", id: o, result: d }) || $(o, {
342
+ M.delete(i), A(e, { type: "registryCallResult", id: i, result: p }) || N(i, {
295
343
  ok: !1,
296
344
  error: { message: "Failed to deliver worker handler response", code: "E_PORT" }
297
345
  });
298
346
  }
299
- }), (t = e.start) == null || t.call(e);
347
+ }), (n = e.start) == null || n.call(e);
300
348
  }
301
- function $(r, e) {
302
- const t = y.get(r);
303
- return t ? (t.settle(e), !0) : (m.warn("asyncRelayResult_no_pending_relay", { id: r }), !1);
349
+ function N(r, e) {
350
+ l.trace("resolveAsyncRelayResult", { id: r });
351
+ const n = _.get(r);
352
+ return n ? (n.settle(e), !0) : (l.warn("asyncRelayResult_no_pending_relay", { id: r }), !1);
304
353
  }
305
- function ce(r) {
354
+ function Ee(r) {
306
355
  if (r === "main-thread" || r === "content-script")
307
356
  return self;
308
- const e = C.get(r);
357
+ const e = O.get(r);
309
358
  return e || null;
310
359
  }
311
- function fe(r) {
312
- const { owner: e, action: t, timeoutMs: n, tabPolicy: s } = r;
313
- return (a, o) => new Promise((f, l) => {
314
- var D;
315
- if ((D = o == null ? void 0 : o.signal) != null && D.aborted) {
316
- const g = new Error(`Relay aborted for action: ${t}`);
317
- g.code = "E_ABORT", l(g);
318
- return;
319
- }
320
- const d = ce(e);
321
- if (!d) {
322
- l(new Error(`No port available for action: ${t}`));
323
- return;
324
- }
325
- if (y.size >= B) {
326
- l(new Error(
327
- `Too many pending calls (${B} limit exceeded). Action: ${t}`
328
- ));
329
- return;
330
- }
331
- const u = ae();
332
- let O = !1;
333
- const b = (g) => {
334
- O || (O = !0, clearTimeout(v), o != null && o.signal && o.signal.removeEventListener("abort", M), y.delete(u), g());
335
- }, W = () => {
336
- j(u, e, d);
337
- }, M = () => {
338
- W();
339
- const g = new Error(`Relay aborted for action: ${t}`);
340
- g.code = "E_ABORT", b(() => l(g));
341
- };
342
- o != null && o.signal && o.signal.addEventListener("abort", M);
343
- const v = setTimeout(() => {
344
- W(), b(() => l(new Error(`Relay timeout for action: ${t}`)));
345
- }, n);
346
- y.set(u, {
347
- settle: (g) => b(() => f(g)),
348
- timeoutId: v,
349
- abort: M,
350
- owner: e,
351
- port: d
360
+ function we(r) {
361
+ const { owner: e, action: n, tabPolicy: t, resolveTimeoutMs: s } = r, o = r.timeoutMs ?? h;
362
+ return (i, a) => {
363
+ l.trace("safePostAsCall_invoke", { owner: e, action: n, callId: a == null ? void 0 : a.callId, runId: a == null ? void 0 : a.runId });
364
+ const g = (s == null ? void 0 : s(i)) ?? o;
365
+ return new Promise((p, u) => {
366
+ var j;
367
+ if ((j = a == null ? void 0 : a.signal) != null && j.aborted) {
368
+ const f = new Error(`Relay aborted for action: ${n}`);
369
+ f.code = "E_ABORT", u(f);
370
+ return;
371
+ }
372
+ const E = Ee(e);
373
+ if (!E) {
374
+ u(new Error(`No port available for action: ${n}`));
375
+ return;
376
+ }
377
+ if (_.size >= z) {
378
+ u(new Error(
379
+ `Too many pending calls (${z} limit exceeded). Action: ${n}`
380
+ ));
381
+ return;
382
+ }
383
+ const w = _e();
384
+ let W = !1;
385
+ const k = (f) => {
386
+ W || (W = !0, clearTimeout(U), a != null && a.signal && a.signal.removeEventListener("abort", C), _.delete(w), f());
387
+ }, D = () => {
388
+ J(w, e, E);
389
+ }, C = () => {
390
+ D();
391
+ const f = new Error(`Relay aborted for action: ${n}`);
392
+ f.code = "E_ABORT", k(() => u(f));
393
+ };
394
+ a != null && a.signal && a.signal.addEventListener("abort", C);
395
+ const U = setTimeout(() => {
396
+ D(), k(() => u(new Error(`Relay timeout for action: ${n}`)));
397
+ }, g);
398
+ _.set(w, {
399
+ settle: (f) => k(() => p(f)),
400
+ timeoutId: U,
401
+ abort: C,
402
+ owner: e,
403
+ port: E
404
+ });
405
+ const F = a == null ? void 0 : a.runId, B = a == null ? void 0 : a.callId;
406
+ A(E, {
407
+ type: e === "main-thread" || e === "content-script" ? "asyncRelay" : "registryCall",
408
+ id: w,
409
+ owner: e,
410
+ action: n,
411
+ params: i,
412
+ callId: B,
413
+ tabPolicy: t,
414
+ command: { action: n, params: i, runId: F, callId: B },
415
+ runId: F
416
+ }) || k(() => u(new Error(`Failed to post relay for action: ${n}`)));
352
417
  });
353
- const P = o == null ? void 0 : o.runId, N = o == null ? void 0 : o.callId;
354
- R(d, {
355
- type: e === "main-thread" || e === "content-script" ? "asyncRelay" : "registryCall",
356
- id: u,
357
- owner: e,
358
- action: t,
359
- params: a,
360
- callId: N,
361
- tabPolicy: s,
362
- command: { action: t, params: a, runId: P, callId: N },
363
- runId: P
364
- }) || b(() => l(new Error(`Failed to post relay for action: ${t}`)));
365
- });
418
+ };
366
419
  }
367
- const de = "worker", ue = 3e4;
368
- function ge(r) {
369
- if (r.owner === de) {
370
- const e = A.get(r.action);
420
+ const ke = "worker", h = 3e4, V = 5e3, Me = 500, Re = {
421
+ page_goto: "timeout",
422
+ page_wait_for: "timeout",
423
+ tab_wait_for_load: "timeout",
424
+ fetch: "timeout",
425
+ sleep: "duration",
426
+ page_wait: "duration",
427
+ sidepanel_wait: "duration"
428
+ }, K = /* @__PURE__ */ new Set(["page_goto"]);
429
+ function Te(r, e) {
430
+ if (r === null || typeof r != "object" || Array.isArray(r))
431
+ return null;
432
+ const n = r[e];
433
+ return typeof n == "bigint" ? Number(n) : typeof n == "number" && Number.isFinite(n) ? n : null;
434
+ }
435
+ function Ae(r, e) {
436
+ return K.has(r) ? e * 2 + Me + V : e + V;
437
+ }
438
+ function Se(r, e) {
439
+ const n = Re[r];
440
+ if (!n) return h;
441
+ let t = Te(e, n);
442
+ return t === null && K.has(r) && (t = h), t === null ? h : Math.max(
443
+ h,
444
+ Ae(r, t)
445
+ );
446
+ }
447
+ function Ce(r) {
448
+ if (r.owner === ke) {
449
+ const e = S.get(r.action);
371
450
  if (!e)
372
451
  throw new Error(
373
452
  `No worker-local handler registered for action: ${r.action}`
374
453
  );
375
- return async (t, n) => {
376
- var a;
377
- t = k(t);
378
- const s = (n == null ? void 0 : n.signal) ?? (n != null && n.runId ? (a = p.get(n.runId)) == null ? void 0 : a.signal : void 0);
454
+ return async (n, t) => {
455
+ var o;
456
+ n = T(n);
457
+ const s = (t == null ? void 0 : t.signal) ?? (t != null && t.runId ? (o = m.get(t.runId)) == null ? void 0 : o.signal : void 0);
379
458
  try {
380
- return { ok: !0, value: await e(t, { ...n, action: r.action, signal: s }) };
381
- } catch (o) {
382
- const f = o instanceof Error ? o.message : String(o), l = typeof o == "object" && o !== null && "code" in o && typeof o.code == "string" ? o.code : r.errorCode;
383
- return { ok: !1, error: { message: f, code: l } };
459
+ return { ok: !0, value: await e(n, { ...t, action: r.action, signal: s }) };
460
+ } catch (i) {
461
+ const a = i instanceof Error ? i.message : String(i), g = typeof i == "object" && i !== null && "code" in i && typeof i.code == "string" ? i.code : r.errorCode;
462
+ return { ok: !1, error: { message: a, code: g } };
384
463
  }
385
464
  };
386
465
  } else {
387
- const e = fe({
466
+ const e = we({
388
467
  owner: r.owner,
389
468
  action: r.action,
390
- timeoutMs: ue
469
+ resolveTimeoutMs: (n) => Se(r.action, n)
391
470
  });
392
- return (t, n) => {
471
+ return (n, t) => {
393
472
  var s;
394
- return e(k(t), {
395
- ...n,
396
- signal: (n == null ? void 0 : n.signal) ?? (n != null && n.runId ? (s = p.get(n.runId)) == null ? void 0 : s.signal : void 0)
473
+ return e(T(n), {
474
+ ...t,
475
+ signal: (t == null ? void 0 : t.signal) ?? (t != null && t.runId ? (s = m.get(t.runId)) == null ? void 0 : s.signal : void 0)
397
476
  });
398
477
  };
399
478
  }
400
479
  }
401
- function pe(r) {
402
- i("exists", (e) => r.fsExists(e)), i("stat", (e) => r.fsStat(e)), i("read", (e) => r.fsRead(e)), i("readText", (e) => r.fsReadText(e)), i("readBase64", (e) => r.fsReadBase64(e)), i("list", (e) => r.fsList(e)), i("mkdir", (e) => r.fsMkdir(e)), i("delete", (e) => r.fsDelete(e)), i("copy", (e) => r.fsCopy(e)), i("move", (e) => r.fsMove(e)), i("write", (e) => r.fsWrite(e)), i("writeText", (e) => r.fsWriteText(e)), i("writeBase64", (e) => r.fsWriteBase64(e)), i("append", (e) => r.fsAppend(e)), i("appendText", (e) => r.fsAppendText(e)), i("appendBase64", (e) => r.fsAppendBase64(e)), i("readRange", (e) => r.fsReadRange(e)), i("update", (e) => r.fsUpdate(e)), i("hash", (e) => r.fsHash(e));
403
- }
404
- async function me(r, e) {
405
- if (T) return;
406
- await z(), c = new G(), L(3), V(L), pe(c), se(r);
407
- const n = r.map((a) => ({
408
- entry: oe(a),
409
- callback: ge(a)
480
+ function Ie(r) {
481
+ c("exists", (e) => r.fsExists(e)), c("stat", (e) => r.fsStat(e)), c("read", (e) => r.fsRead(e)), c("readText", (e) => r.fsReadText(e)), c("readBase64", (e) => r.fsReadBase64(e)), c("list", (e) => r.fsList(e)), c("mkdir", (e) => r.fsMkdir(e)), c("delete", (e) => r.fsDelete(e)), c("copy", (e) => r.fsCopy(e)), c("move", (e) => r.fsMove(e)), c("write", (e) => r.fsWrite(e)), c("writeText", (e) => r.fsWriteText(e)), c("writeBase64", (e) => r.fsWriteBase64(e)), c("append", (e) => r.fsAppend(e)), c("appendText", (e) => r.fsAppendText(e)), c("appendBase64", (e) => r.fsAppendBase64(e)), c("readRange", (e) => r.fsReadRange(e)), c("update", (e) => r.fsUpdate(e)), c("hash", (e) => r.fsHash(e));
482
+ }
483
+ async function Le(r, e) {
484
+ if (v) return;
485
+ await Q(), y = new X(), I(0), te(I), l.trace("initWasm_start"), Ie(y), pe(r);
486
+ const t = r.map((o) => ({
487
+ entry: me(o),
488
+ callback: Ce(o)
410
489
  }));
411
490
  try {
412
- H(n);
413
- } catch (a) {
414
- const o = a instanceof Error ? a.message : String(a);
415
- throw new Error(`Registry registration failed: ${o}`);
491
+ Z(t);
492
+ } catch (o) {
493
+ const i = o instanceof Error ? o.message : String(o);
494
+ throw new Error(`Registry registration failed: ${i}`);
416
495
  }
417
496
  const { freezeManifest: s } = await import("../../pkg/extension_js.js");
418
- if (s(), c.injectRegistryBindings(), e) {
419
- const a = JSON.stringify(e);
420
- await c.runCellAsync(
421
- `(function(){var r=globalThis.chrome&&globalThis.chrome.runtime;if(!r){r={};if(!globalThis.chrome)globalThis.chrome={};globalThis.chrome.runtime=r;}r.id=${a};})();`,
497
+ try {
498
+ s();
499
+ } catch (o) {
500
+ const i = o instanceof Error ? o.message : String(o);
501
+ throw new Error(`Manifest freeze failed: ${i}`);
502
+ }
503
+ if (y.injectRegistryBindings(), e) {
504
+ const o = JSON.stringify(e);
505
+ await y.runCellAsync(
506
+ `(function(){var r=globalThis.chrome&&globalThis.chrome.runtime;if(!r){r={};if(!globalThis.chrome)globalThis.chrome={};globalThis.chrome.runtime=r;}r.id=${o};})();`,
422
507
  "",
423
508
  "inject-runtime-id"
424
509
  );
425
510
  }
426
- T = !0;
511
+ v = !0, l.trace("initWasm_done");
427
512
  }
428
513
  self.onmessage = async (r) => {
429
514
  const e = r.data;
430
- if (e.type === "asyncRelayResult") {
431
- $(e.id, e.result);
515
+ if (l.trace("onmessage", { type: e.type, id: "id" in e ? e.id : void 0 }), e.type === "asyncRelayResult") {
516
+ l.trace("asyncRelayResult", { id: e.id }), N(e.id, e.result);
432
517
  return;
433
518
  }
434
519
  if (e.type === "registerWorkerPort") {
435
520
  const t = r.ports[0];
436
521
  if (!t) {
437
- m.error("register_worker_port_missing", { owner: e.owner });
522
+ l.error("register_worker_port_missing", { owner: e.owner });
438
523
  return;
439
524
  }
440
- le(e.owner, t);
525
+ he(e.owner, t);
441
526
  return;
442
527
  }
443
528
  if (e.type === "init") {
444
529
  try {
445
- await me(e.manifest, e.extensionId), self.postMessage({ type: "ready" });
530
+ await Le(e.manifest, e.extensionId), self.postMessage({ type: "ready" });
446
531
  } catch (t) {
447
- const n = t instanceof Error ? t.message : String(t);
448
- m.error("worker_init_failed", { error: n }), self.postMessage({ type: "error", error: `WASM init failed: ${n}` });
532
+ const s = t instanceof Error ? t.message : String(t);
533
+ l.error("worker_init_failed", { error: s }), self.postMessage({ type: "error", error: `WASM init failed: ${s}` });
449
534
  }
450
535
  return;
451
536
  }
452
537
  if (e.type === "setLogLevel") {
453
- L(e.level), J(ie(e.level)), m.debug("set_log_level", { level: e.level });
538
+ I(e.level), re(be(e.level)), l.trace("set_log_level", { level: e.level });
454
539
  return;
455
540
  }
456
- if (!T || !c) {
541
+ if (!v || !y) {
457
542
  self.postMessage({
458
543
  type: "error",
459
544
  id: e.id,
@@ -461,107 +546,119 @@ self.onmessage = async (r) => {
461
546
  });
462
547
  return;
463
548
  }
464
- switch (e.type) {
465
- case "runCell": {
466
- const t = e.runId, n = new AbortController();
467
- t && p.set(t, n);
468
- try {
469
- const s = await c.runCellAsync(
470
- e.code,
471
- e.stdin || "",
472
- t || ""
473
- // propagate correlation ID to WASM so trace spans can be linked end-to-end
474
- );
475
- self.postMessage({
476
- type: "result",
477
- id: e.id,
478
- data: s,
479
- runId: t
480
- });
481
- } catch (s) {
482
- const a = s instanceof Error ? s.message : String(s);
483
- m.error("runCell_error", { runId: t, error: a }), self.postMessage({
484
- type: "error",
485
- id: e.id,
486
- error: a,
487
- runId: t
488
- });
489
- } finally {
490
- t && p.delete(t);
549
+ const n = y;
550
+ await ye(async () => {
551
+ switch (e.type) {
552
+ case "runCell": {
553
+ const t = e.runId, s = new AbortController();
554
+ t && m.set(t, s), d = { id: e.id, runId: t }, l.trace("runCell_start", { runId: t, callId: e.id, codeLen: e.code.length });
555
+ try {
556
+ const o = await n.runCellAsync(
557
+ e.code,
558
+ e.stdin || "",
559
+ t || ""
560
+ );
561
+ l.trace("runCell_done", { runId: t, callId: e.id, status: o.status }), self.postMessage({
562
+ type: "result",
563
+ id: e.id,
564
+ data: o,
565
+ runId: t
566
+ });
567
+ } catch (o) {
568
+ const i = o instanceof Error ? o.message : String(o);
569
+ l.error("runCell_error", { runId: t, error: i }), self.postMessage({
570
+ type: "error",
571
+ id: e.id,
572
+ error: i,
573
+ runId: t
574
+ });
575
+ } finally {
576
+ (d == null ? void 0 : d.id) === e.id && (d = null), t && m.delete(t);
577
+ }
578
+ break;
491
579
  }
492
- break;
493
- }
494
- case "reset": {
495
- c.setAborted(!0);
496
- for (const t of p.values()) t.abort();
497
- p.clear(), F("E_RESET", "Worker reset");
498
- try {
499
- c.reset(), self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
500
- } catch (t) {
501
- const n = t instanceof Error ? t.message : String(t);
502
- self.postMessage({ type: "error", id: e.id, error: n });
580
+ case "reset": {
581
+ n.setAborted(!0);
582
+ for (const t of m.values()) t.abort();
583
+ m.clear(), G("E_RESET", "Worker reset");
584
+ try {
585
+ n.reset(), self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
586
+ } catch (t) {
587
+ const s = t instanceof Error ? t.message : String(t);
588
+ self.postMessage({ type: "error", id: e.id, error: s });
589
+ }
590
+ break;
503
591
  }
504
- break;
505
- }
506
- case "stop": {
507
- c.setAborted(!0);
508
- for (const t of p.values()) t.abort();
509
- p.clear(), F("E_STOPPED", "Worker stopped"), self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
510
- break;
511
- }
512
- case "setFuelLimit": {
513
- try {
514
- c.set_fuel_limit(e.limit), e.id && self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
515
- } catch (t) {
516
- if (e.id) {
517
- const n = t instanceof Error ? t.message : String(t);
518
- self.postMessage({ type: "error", id: e.id, error: n });
592
+ case "stop": {
593
+ n.setAborted(!0);
594
+ for (const t of m.values()) t.abort();
595
+ m.clear(), G("E_STOPPED", "Worker stopped"), self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
596
+ break;
597
+ }
598
+ case "setFuelLimit": {
599
+ try {
600
+ n.set_fuel_limit(e.limit), e.id && self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
601
+ } catch (t) {
602
+ if (e.id) {
603
+ const s = t instanceof Error ? t.message : String(t);
604
+ self.postMessage({ type: "error", id: e.id, error: s });
605
+ }
519
606
  }
607
+ break;
520
608
  }
521
- break;
522
- }
523
- case "inspectGlobals": {
524
- try {
525
- const t = c.inspect_globals();
526
- self.postMessage({ type: "result", id: e.id, data: t });
527
- } catch (t) {
528
- const n = t instanceof Error ? t.message : String(t);
529
- self.postMessage({ type: "error", id: e.id, error: n });
609
+ case "inspectGlobals": {
610
+ try {
611
+ const t = n.inspect_globals();
612
+ self.postMessage({ type: "result", id: e.id, data: t });
613
+ } catch (t) {
614
+ const s = t instanceof Error ? t.message : String(t);
615
+ self.postMessage({ type: "error", id: e.id, error: s });
616
+ }
617
+ break;
530
618
  }
531
- break;
532
- }
533
- case "loadLibrary": {
534
- try {
535
- const t = c.load_library(e.source);
536
- self.postMessage({ type: "result", id: e.id, data: t });
537
- } catch (t) {
538
- const n = t instanceof Error ? t.message : String(t);
539
- self.postMessage({ type: "error", id: e.id, error: n });
619
+ case "apiDocs": {
620
+ try {
621
+ const t = n.apiDocs(e.format);
622
+ self.postMessage({ type: "result", id: e.id, data: t });
623
+ } catch (t) {
624
+ const s = t instanceof Error ? t.message : String(t);
625
+ self.postMessage({ type: "error", id: e.id, error: s });
626
+ }
627
+ break;
540
628
  }
541
- break;
542
- }
543
- case "fsCall": {
544
- const t = A.get(e.action);
545
- if (!t) {
546
- self.postMessage({
547
- type: "error",
548
- id: e.id,
549
- error: `Unknown fs action: ${e.action}`
550
- });
629
+ case "loadLibrary": {
630
+ try {
631
+ const t = n.load_library(e.source);
632
+ self.postMessage({ type: "result", id: e.id, data: t });
633
+ } catch (t) {
634
+ const s = t instanceof Error ? t.message : String(t);
635
+ self.postMessage({ type: "error", id: e.id, error: s });
636
+ }
551
637
  break;
552
638
  }
553
- try {
554
- const n = await t(e.params);
555
- self.postMessage({ type: "result", id: e.id, data: n });
556
- } catch (n) {
557
- const s = n instanceof Error ? n.message : String(n);
558
- self.postMessage({ type: "error", id: e.id, error: s });
639
+ case "fsCall": {
640
+ const t = S.get(e.action);
641
+ if (!t) {
642
+ self.postMessage({
643
+ type: "error",
644
+ id: e.id,
645
+ error: `Unknown fs action: ${e.action}`
646
+ });
647
+ break;
648
+ }
649
+ try {
650
+ const s = await t(e.params);
651
+ self.postMessage({ type: "result", id: e.id, data: s });
652
+ } catch (s) {
653
+ const o = s instanceof Error ? s.message : String(s);
654
+ self.postMessage({ type: "error", id: e.id, error: o });
655
+ }
656
+ break;
657
+ }
658
+ default: {
659
+ l.error("unhandled_worker_message", { type: e.type });
660
+ break;
559
661
  }
560
- break;
561
- }
562
- default: {
563
- m.error("unhandled_worker_message", { type: e.type });
564
- break;
565
662
  }
566
- }
663
+ });
567
664
  };