@rin-chat/rinext 0.0.0-stage → 1.0.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,4693 @@
1
+ import { readFileSync, existsSync, statSync } from "node:fs";
2
+ import { resolve, join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { createRequire } from "node:module";
5
+ const LOG_MAX_LINES = 500;
6
+ const LOG_MAX_LINE = 2e3;
7
+ const logs = /* @__PURE__ */ new Map();
8
+ const listeners = /* @__PURE__ */ new Set();
9
+ function appendExtLog(id, text) {
10
+ let list = logs.get(id);
11
+ if (!list) logs.set(id, list = []);
12
+ const line = { t: Date.now(), text: text.slice(0, LOG_MAX_LINE) };
13
+ list.push(line);
14
+ if (list.length > LOG_MAX_LINES) list.splice(0, list.length - LOG_MAX_LINES);
15
+ for (const fn of listeners) fn(id);
16
+ }
17
+ const extLogLines = (id) => logs.get(id) ?? [];
18
+ function clearExtLog(id) {
19
+ logs.delete(id);
20
+ for (const fn of listeners) fn(id);
21
+ }
22
+ const DEFAULT_LIMITS = { memoryBytes: 32 * 1024 * 1024, wasmBytes: 64 * 1024 * 1024, stackBytes: 96 * 1024 };
23
+ const MAX_PAYLOAD = 1024 * 1024;
24
+ const MAX_SOURCE = 2 * 1024 * 1024;
25
+ const MAX_DEPTH = 64;
26
+ const MAX_PENDING = 32;
27
+ const MAX_NAME = 64;
28
+ const BANNED = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
29
+ function safeParse(text, max = MAX_PAYLOAD) {
30
+ if (typeof text !== "string") return { ok: false, error: "bad_value" };
31
+ if (text.length > max) return { ok: false, error: "too_large" };
32
+ let value;
33
+ try {
34
+ value = JSON.parse(text);
35
+ } catch {
36
+ return { ok: false, error: "bad_value" };
37
+ }
38
+ const stack = [[value, 0]];
39
+ while (stack.length) {
40
+ const [v, depth] = stack.pop();
41
+ if (v === null || typeof v !== "object") continue;
42
+ if (depth >= MAX_DEPTH) return { ok: false, error: "bad_value" };
43
+ for (const k of Object.keys(v)) {
44
+ if (BANNED.has(k)) return { ok: false, error: "bad_value" };
45
+ stack.push([v[k], depth + 1]);
46
+ }
47
+ }
48
+ return { ok: true, value };
49
+ }
50
+ function safeStringify(value, max = MAX_PAYLOAD) {
51
+ let text;
52
+ try {
53
+ text = JSON.stringify(value === void 0 ? null : value);
54
+ } catch {
55
+ return { ok: false, error: "bad_value" };
56
+ }
57
+ if (text === void 0) return { ok: false, error: "bad_value" };
58
+ if (text.length > max) return { ok: false, error: "too_large" };
59
+ return { ok: true, text };
60
+ }
61
+ const isId = (v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0;
62
+ const isName = (v) => typeof v === "string" && v.length > 0 && v.length <= MAX_NAME;
63
+ const isPayload = (v) => typeof v === "string" && v.length <= MAX_PAYLOAD;
64
+ const ERROR_CODES = /* @__PURE__ */ new Set(["timeout", "cpu", "memory", "threw", "too_large", "bad_value", "no_hook", "denied", "bad_request", "too_many_requests", "killed", "crashed", "not_loaded", "quota", "budget", "no_model", "model_failed"]);
65
+ const NET_ERRORS = ["net_blocked", "net_needs_approval", "net_denied", "net_refused", "net_failed", "net_rate_limited"];
66
+ for (const c of NET_ERRORS) ERROR_CODES.add(c);
67
+ function netCode(raw) {
68
+ const c = /(?:ext_err:)?(net_[a-z_]+)/.exec(raw)?.[1] ?? "";
69
+ if (c === "net_blocked" || c === "net_needs_approval" || c === "net_denied" || c === "net_rate_limited") return c;
70
+ if (["net_dns", "net_timeout", "net_connect", "net_response_too_large", "net_failed"].includes(c)) return "net_failed";
71
+ if (c) return "net_refused";
72
+ return /ext_err:bad_request/.test(raw) ? "bad_request" : "denied";
73
+ }
74
+ function checkWorkerMsg(m) {
75
+ if (m === null || typeof m !== "object") return null;
76
+ const o = m;
77
+ switch (o.t) {
78
+ case "ready":
79
+ return { t: "ready" };
80
+ case "req":
81
+ return isId(o.id) && isName(o.method) && isPayload(o.args) ? { t: "req", id: o.id, method: o.method, args: o.args } : null;
82
+ case "done":
83
+ if (!isId(o.id)) return null;
84
+ if (o.ok === true) return isPayload(o.value) ? { t: "done", id: o.id, ok: true, value: o.value } : null;
85
+ if (o.ok === false && typeof o.error === "string" && ERROR_CODES.has(o.error)) {
86
+ const message = typeof o.message === "string" ? o.message.slice(0, 500) : void 0;
87
+ return { t: "done", id: o.id, ok: false, error: o.error, message };
88
+ }
89
+ return null;
90
+ default:
91
+ return null;
92
+ }
93
+ }
94
+ const TERM_RE = /([+-]?)\s*(?:([0-9]*)d([0-9]+|F)(!?)(?:(kh|kl)([0-9]+))?|([0-9]+))/giy;
95
+ const rollFaces = (n, sides, rng) => Array.from({ length: n }, () => sides === "F" ? Math.floor(rng() * 3) - 1 : 1 + Math.floor(rng() * sides));
96
+ const MAX_ACES = 10;
97
+ function aceChain(sides, rng, explode) {
98
+ const faces = [1 + Math.floor(rng() * sides)];
99
+ while (explode && sides > 1 && faces.length <= MAX_ACES && faces[faces.length - 1] === sides) faces.push(1 + Math.floor(rng() * sides));
100
+ return faces;
101
+ }
102
+ const chainText = (faces) => faces.map((f, i) => i < faces.length - 1 ? `${f}!` : String(f)).join("+");
103
+ const sumOf = (a) => a.reduce((x, y) => x + y, 0);
104
+ function keptFaces(faces, keep) {
105
+ if (!keep) return faces;
106
+ const sorted = [...faces].sort((a, b) => keep.mode === "h" ? b - a : a - b);
107
+ return sorted.slice(0, Math.max(1, Math.min(keep.count, faces.length)));
108
+ }
109
+ const GROUP_RE = /^\((.+)\)(kh|kl)([0-9]+)(.*)$/i;
110
+ function parseTerms(flat) {
111
+ const terms = [];
112
+ let constant = 0;
113
+ TERM_RE.lastIndex = 0;
114
+ let hit;
115
+ let consumed = 0;
116
+ while (hit = TERM_RE.exec(flat)) {
117
+ if (consumed > 0 && !hit[1]) return null;
118
+ consumed = TERM_RE.lastIndex;
119
+ const sign = hit[1] === "-" ? -1 : 1;
120
+ if (hit[7] !== void 0) {
121
+ constant += sign * Number(hit[7]);
122
+ continue;
123
+ }
124
+ const n = Math.min(hit[2] ? Number(hit[2]) : 1, 100);
125
+ const sides = hit[3].toUpperCase() === "F" ? "F" : Math.min(Number(hit[3]), 1e3);
126
+ if (n < 1 || sides !== "F" && sides < 2) return null;
127
+ if (hit[4] && sides === "F") return null;
128
+ const keep = hit[5] ? { mode: hit[5].toLowerCase() === "kh" ? "h" : "l", count: Number(hit[6]) } : void 0;
129
+ if (keep && keep.count < 1) return null;
130
+ terms.push({ sign, n, sides, keep, ...hit[4] ? { explode: true } : {} });
131
+ }
132
+ if (consumed !== flat.length) return null;
133
+ return { terms, constant };
134
+ }
135
+ function rollDice(expr, rng = Math.random, edge) {
136
+ const flat = expr.replace(/\s+/g, "");
137
+ const g = GROUP_RE.exec(flat);
138
+ if (g) return rollGroup(g[1], g[2].toLowerCase() === "kh" ? "h" : "l", Number(g[3]), g[4], rng);
139
+ const parsed = parseTerms(flat);
140
+ if (!parsed || !parsed.terms.length) return null;
141
+ const { terms, constant } = parsed;
142
+ const simple = terms.length === 1 && terms[0].sign === 1 && terms[0].sides !== "F" && !terms[0].keep;
143
+ if (!simple) return rollGeneral(terms, constant, rng);
144
+ const n = terms[0].n;
145
+ const sides = terms[0].sides;
146
+ const modifier = constant;
147
+ const die = () => aceChain(sides, rng, terms[0].explode);
148
+ const chains = Array.from({ length: n }, die);
149
+ const rolls = chains.map(sumOf);
150
+ const sum = sumOf(rolls);
151
+ const total = sum + modifier;
152
+ const breakdown = (n > 1 ? `${chains.map(chainText).join(" + ")} = ${sum}` : chains[0].length > 1 ? `${chainText(chains[0])} = ${sum}` : String(sum)) + (modifier ? ` ${modifier > 0 ? "+" : "−"} ${Math.abs(modifier)} = ${total}` : "");
153
+ return { total, rolls, modifier, breakdown };
154
+ }
155
+ function rollGroup(inner, mode, count2, rest, rng) {
156
+ if (count2 < 1) return null;
157
+ const parsed = parseTerms(inner);
158
+ if (!parsed || !parsed.terms.length || parsed.constant) return null;
159
+ const dice = [];
160
+ for (const t of parsed.terms) {
161
+ if (t.sign < 0) return null;
162
+ if (t.explode) {
163
+ for (let i = 0; i < t.n; i++) {
164
+ const chain = aceChain(t.sides, rng, true);
165
+ dice.push({ sides: t.sides, face: sumOf(chain), chain });
166
+ }
167
+ } else for (const face of rollFaces(t.n, t.sides, rng)) dice.push({ sides: t.sides, face });
168
+ }
169
+ if (count2 > dice.length) return null;
170
+ const order = [...dice].sort((a, b) => mode === "h" ? b.face - a.face : a.face - b.face);
171
+ const kept = order.slice(0, count2);
172
+ const tail = rest ? parseTerms(rest) : { terms: [], constant: 0 };
173
+ if (!tail || tail.terms.length) return null;
174
+ const total = kept.reduce((a, d) => a + d.face, 0) + tail.constant;
175
+ const die = (d) => `d${d.sides}=${d.chain ? chainText(d.chain) : d.face}`;
176
+ const breakdown = `(${parsed.terms.map((t) => `${t.n}d${t.sides}${t.explode ? "!" : ""}`).join(" + ")})${mode === "h" ? "kh" : "kl"}${count2} [${dice.map(die).join(" ")} keep ${kept.map(die).join(" ")}]` + (tail.constant ? ` ${tail.constant > 0 ? "+" : "−"} ${Math.abs(tail.constant)}` : "") + ` = ${total}`;
177
+ return { total, rolls: kept.map((d) => d.face), modifier: tail.constant, breakdown };
178
+ }
179
+ function rollGeneral(terms, constant, rng) {
180
+ const rolls = [];
181
+ const parts = [];
182
+ let sum = 0;
183
+ for (const t of terms) {
184
+ const chains = t.explode ? Array.from({ length: t.n }, () => aceChain(t.sides, rng, true)) : null;
185
+ const faces = chains ? chains.map(sumOf) : rollFaces(t.n, t.sides, rng);
186
+ const kept = keptFaces(faces, t.keep);
187
+ rolls.push(...kept);
188
+ sum += t.sign * kept.reduce((a, b) => a + b, 0);
189
+ const bare = terms.length === 1 && !t.keep;
190
+ const label = bare ? "" : `${t.n}d${t.sides}${t.explode ? "!" : ""}${t.keep ? `${t.keep.mode === "h" ? "kh" : "kl"}${t.keep.count}` : ""} `;
191
+ const shown = t.sides === "F" ? faces.map((f) => f > 0 ? "+" : f < 0 ? "−" : "0").join(" ") : chains ? chains.map(chainText).join(" ") : faces.join(" ");
192
+ parts.push(`${t.sign < 0 ? "− " : parts.length ? "+ " : ""}${label}[${shown}${t.keep ? ` keep ${kept.join(" ")}` : ""}]`);
193
+ }
194
+ const total = sum + constant;
195
+ const breakdown = parts.join(" ") + (constant ? ` ${constant > 0 ? "+" : "−"} ${Math.abs(constant)}` : "") + ` = ${total}`;
196
+ return { total, rolls, modifier: constant, breakdown };
197
+ }
198
+ const HUD_ICONS = [
199
+ "heart",
200
+ "heart-pulse",
201
+ "sparkles",
202
+ "wand-sparkles",
203
+ "zap",
204
+ "shield",
205
+ "swords",
206
+ "dumbbell",
207
+ "feather",
208
+ "brain",
209
+ "lightbulb",
210
+ "message-circle",
211
+ "eye",
212
+ "eye-off",
213
+ "clover",
214
+ "ghost",
215
+ "star",
216
+ "trophy",
217
+ "award",
218
+ "coins",
219
+ "gem",
220
+ "crown",
221
+ "map-pin",
222
+ "sun",
223
+ "clock",
224
+ "calendar",
225
+ "hourglass",
226
+ "gauge",
227
+ "smile",
228
+ "flame",
229
+ "droplet",
230
+ "utensils",
231
+ "moon",
232
+ "skull",
233
+ "backpack",
234
+ "flask-conical",
235
+ "battery-medium",
236
+ "footprints",
237
+ "compass",
238
+ "book-open",
239
+ "users",
240
+ "circle-dot"
241
+ ];
242
+ const ICON_SET = new Set(HUD_ICONS);
243
+ const stripAdv = (s) => s.startsWith("adv_") ? s.slice(4) : s;
244
+ const ICON_RULES = [
245
+ ["heart", /\b(hp|health|hit ?points|hitpoints|life|vitality|vigor|wounds?)\b/],
246
+ ["award", /\b(skill|stat|ability|perk|talent|attribute|feat) ?points?\b|\bpoints\b/],
247
+ ["heart-pulse", /\b(con|constitution|endurance|toughness|fortitude|resilience)\b/],
248
+ ["sparkles", /\b(mp|mana|ether|chi|ki|qi|essence)\b/],
249
+ ["wand-sparkles", /\b(magic|spells?|arcana|sorcery)\b/],
250
+ ["zap", /\b(energy|stamina|ap|fatigue|focus)\b/],
251
+ ["shield", /\b(ac|armor|defen[cs]e|guard|ward|protection)\b/],
252
+ ["feather", /\b(dex|dexterity|agi|agility|reflexes|nimbleness|finesse)\b/],
253
+ ["dumbbell", /\b(str|strength|might|brawn|athletics)\b/],
254
+ ["message-circle", /\b(cha|charisma|charm|presence|persuasion|speech|eloquence)\b/],
255
+ ["lightbulb", /\b(wis|wisdom|insight|intuition)\b/],
256
+ ["eye-off", /\b(stealth|sneak|sneaking|hiding|hidden)\b/],
257
+ ["clover", /\b(luck|lck|fortune|karma)\b/],
258
+ ["ghost", /\b(sanity|madness|insanity|fear|terror|horror)\b/],
259
+ ["star", /\b(level|lvl|rank|tier)\b/],
260
+ ["trophy", /\b(xp|exp|experience|score)\b/],
261
+ ["coins", /\b(gold|silver|copper|coins?|money|cash|credits?|gp|sp|cp|bills|funds|wealth|dollars?|yen)\b/],
262
+ ["gem", /\b(gems?|crystals?|jewels?|diamonds?|souls?|shards?)\b/],
263
+ ["map-pin", /\b(location|place|area|region|zone|room|position|scene|city|town)\b/],
264
+ ["sun", /\b(days?)\b/],
265
+ ["clock", /\b(time|hours?|turns?)\b/],
266
+ ["calendar", /\b(date|month|year|season|week)\b/],
267
+ ["brain", /\b(mind|stress|intelligence|int|intellect|willpower|resolve)\b/],
268
+ ["smile", /\b(mood|happiness|morale|joy|affection|love|trust|friendship|relationship|bond|loyalty)\b/],
269
+ ["flame", /\b(heat|rage|fury|anger|arousal|lust|desire|fire|temper|passion)\b/],
270
+ ["droplet", /\b(thirst|water|blood|hydration)\b/],
271
+ ["utensils", /\b(hunger|food|rations?|satiety)\b/],
272
+ ["moon", /\b(night|sleep|rest|tired|exhaustion)\b/],
273
+ ["skull", /\b(doom|danger|corruption|death|curse|threat|infection|poison)\b/],
274
+ ["swords", /\b(attack|power|combat|damage|kills?)\b/],
275
+ ["eye", /\b(perception|per|alert|alertness|suspicion|awareness|notice|detection|wanted)\b/],
276
+ ["crown", /\b(reputation|fame|renown|honor|status|influence|favor|prestige)\b/],
277
+ ["backpack", /\b(weight|load|carry|encumbrance|inventory|items?)\b/],
278
+ ["flask-conical", /\b(potions?|elixirs?|vials?)\b/],
279
+ ["battery-medium", /\b(charge|battery|fuel|ammo|oxygen)\b/],
280
+ ["footprints", /\b(distance|steps|speed|travel|miles)\b/],
281
+ ["compass", /\b(quest|chapter|act|objective|direction)\b/],
282
+ ["book-open", /\b(knowledge|lore|clues?|secrets?)\b/],
283
+ ["users", /\b(party|followers|allies|crew|companions)\b/]
284
+ ];
285
+ const statWords = (stat, personaSlug) => {
286
+ let n = stripAdv(stat).toLowerCase();
287
+ return n.replace(/^(?:money|inv|meter|clock)_/, "").replace(/_/g, " ").trim();
288
+ };
289
+ function hudIconFor(name, personaSlug) {
290
+ const w = statWords(name);
291
+ for (const [k, re] of ICON_RULES) if (re.test(w)) return k;
292
+ const n = stripAdv(name).toLowerCase();
293
+ if (n.startsWith("meter_")) return "gauge";
294
+ if (n.startsWith("clock_")) return "hourglass";
295
+ if (n.startsWith("money_")) return "coins";
296
+ return "circle-dot";
297
+ }
298
+ function hudItem(ext, e) {
299
+ const icon = e.icon ?? hudIconFor(e.label);
300
+ const base = { stat: `ext.${ext}.${e.key}`, label: e.label, icon, value: e.value };
301
+ return e.bar ? { ...base, kind: "bar", num: e.bar.value, min: 0, max: e.bar.max } : { ...base, kind: "value" };
302
+ }
303
+ function codeBlock(text) {
304
+ let s = text ?? "";
305
+ for (let prev = ""; prev !== s; ) {
306
+ prev = s;
307
+ s = s.replace(/\[\/?code\]/gi, "");
308
+ }
309
+ return `[code]${s}[/code]`;
310
+ }
311
+ const estimateTokens = (text) => Math.ceil((text?.length ?? 0) / 4);
312
+ const unescapeCss = (text) => text.replace(/\\(?:([0-9a-f]{1,6})\s?|([^\n]))/gi, (_, hex, ch) => {
313
+ if (!hex) return ch ?? "";
314
+ const n = parseInt(hex, 16);
315
+ return n && n <= 1114111 ? String.fromCodePoint(n) : "�";
316
+ });
317
+ const SNAPSHOT_CHARS = 6e5;
318
+ const ACTIVE = /\{\{|\}\}|\[\[|\[\/?(?:h|hide|co|chatonly|once|ooc|code)\]|\[create\b|<!--/gi;
319
+ const actives = (s) => {
320
+ const n = /* @__PURE__ */ new Map();
321
+ for (const m of s.matchAll(ACTIVE)) {
322
+ const k = m[0].toLowerCase();
323
+ n.set(k, (n.get(k) ?? 0) + 1);
324
+ }
325
+ return n;
326
+ };
327
+ const SPANS = /\{\{[\s\S]*?\}\}|\[\[(?:[^\]]|\](?!\]))*\]\](?:[ \t]*\|[^\]\n]+)*|\[create\b[^\]\n]*\]|<!--[\s\S]*?-->/gi;
328
+ function addsSyntax(base, next) {
329
+ if (addsReach(base, next)) return true;
330
+ const b = actives(base);
331
+ for (const [k, v] of actives(next)) if (v > (b.get(k) ?? 0)) return true;
332
+ const have = /* @__PURE__ */ new Map();
333
+ for (const m of base.matchAll(SPANS)) have.set(m[0], (have.get(m[0]) ?? 0) + 1);
334
+ for (const m of next.matchAll(SPANS)) {
335
+ const n = have.get(m[0]) ?? 0;
336
+ if (!n) return true;
337
+ have.set(m[0], n - 1);
338
+ }
339
+ return false;
340
+ }
341
+ const REACH = /(?:https?|wss?):|[/\\]{2}|z-index/g;
342
+ const NAMED = { sol: "/", bsol: "\\", colon: ":", tab: "", newline: "" };
343
+ const entities = (s) => s.replace(/&#(x[0-9a-f]+|\d+);?/gi, (_, n) => {
344
+ const c = /^x/i.test(n) ? parseInt(n.slice(1), 16) : parseInt(n, 10);
345
+ return c > 0 && c <= 1114111 ? String.fromCodePoint(c) : "";
346
+ }).replace(/&(sol|bsol|colon|tab|newline);/gi, (_, k) => NAMED[k.toLowerCase()]);
347
+ const count = (s, n) => {
348
+ const here = /* @__PURE__ */ new Map();
349
+ for (const m of s.replace(/[\t\n\r]/g, "").toLowerCase().matchAll(REACH)) {
350
+ const k = m[0].replace(/\\/g, "/");
351
+ here.set(k, (here.get(k) ?? 0) + 1);
352
+ }
353
+ for (const [k, v] of here) n.set(k, Math.max(v, n.get(k) ?? 0));
354
+ return n;
355
+ };
356
+ const reach = (s) => {
357
+ const e = entities(s);
358
+ return count(unescapeCss(e), count(e, /* @__PURE__ */ new Map()));
359
+ };
360
+ function addsReach(base, next) {
361
+ const b = reach(base);
362
+ for (const [k, v] of reach(next)) if (v > (b.get(k) ?? 0)) return true;
363
+ return false;
364
+ }
365
+ const ZW = "‌";
366
+ const POST_WIDGETS = /* @__PURE__ */ new Set(["choice", "ask", "pick", "form", "doc", "bar"]);
367
+ function inertPost(text, widgets) {
368
+ return text.replace(/\{\{/g, `{${ZW}{`).replace(/\}\}/g, `}${ZW}}`).replace(/\[(\/?)(h|hide|co|chatonly|once|ooc|code)\]/gi, `[${ZW}$1$2]`).replace(/\[(create\b)/gi, `[${ZW}$1`).replace(/<!--/g, `<${ZW}!--`).replace(/\[\[(\s*\/?\s*)([A-Za-z]*)/g, (m, pre, name) => widgets && POST_WIDGETS.has(name.toLowerCase()) ? m : `[${ZW}[${pre}${name}`);
369
+ }
370
+ function applyRewrite(orig, next) {
371
+ const used = /* @__PURE__ */ new Set();
372
+ const added = [];
373
+ let last = -1;
374
+ let reordered = false;
375
+ const messages = next.map((m) => {
376
+ const j = orig.findIndex((o, k) => !used.has(k) && o.role === m.role && o.content === m.content);
377
+ if (j < 0) {
378
+ const fresh = { role: m.role, content: m.content };
379
+ added.push(fresh);
380
+ return fresh;
381
+ }
382
+ used.add(j);
383
+ if (j < last) reordered = true;
384
+ last = j;
385
+ return orig[j];
386
+ });
387
+ const dropped = orig.length - used.size;
388
+ return { messages, added, dropped, reordered, changed: dropped > 0 || reordered || added.length > 0 };
389
+ }
390
+ function chatSnapshot(input) {
391
+ const cards = input.cards.map((c) => {
392
+ const data = { ...c.data };
393
+ delete data.assets;
394
+ return { id: c.id, data };
395
+ });
396
+ let left = SNAPSHOT_CHARS - JSON.stringify(cards).length;
397
+ const messages = [];
398
+ for (let i = input.messages.length - 1; i >= 0; i--) {
399
+ const m = input.messages[i];
400
+ left -= m.text.length + m.name.length + 32;
401
+ if (left < 0) break;
402
+ messages.unshift({ role: m.role, name: m.name, text: m.text });
403
+ }
404
+ return { messages, cards, vars: stringVars(input.vars) };
405
+ }
406
+ function stringVars(vars) {
407
+ const out = {};
408
+ for (const [k, v] of Object.entries(vars)) out[k] = typeof v === "string" ? v : JSON.stringify(v) ?? String(v);
409
+ return out;
410
+ }
411
+ const PANEL_MAX_ITEMS = 40;
412
+ const HUD_MAX_ITEMS = 6;
413
+ const CHOICES_MAX = 6;
414
+ const NOTE_MAX = 2e3;
415
+ const NOTIFY_MAX = 200;
416
+ const DRAFT_MAX = 8e3;
417
+ const SPEAK_MAX = 2e3;
418
+ const SOUND_NAME = /^(?:[A-Za-z0-9_-][A-Za-z0-9._-]*\/){0,3}[A-Za-z0-9_-][A-Za-z0-9._-]*\.(?:wav|ogg|mp3)$/i;
419
+ function uiCapabilities() {
420
+ const isObj2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
421
+ const line = (v, max) => typeof v === "string" && v.length <= max && !new RegExp("\\p{Cc}", "u").test(v);
422
+ const text = (v, max) => typeof v === "string" && v.length <= max && !/[\0-\x08\x0b-\x1f\x7f]/.test(v);
423
+ const num = (v) => typeof v === "number" && Number.isFinite(v);
424
+ const ID = /^[a-z0-9_-]{1,32}$/;
425
+ const keys = (o, allowed) => Object.keys(o).every((k) => allowed.includes(k));
426
+ const item = (v) => {
427
+ if (!isObj2(v)) return false;
428
+ switch (v.type) {
429
+ case "text":
430
+ return keys(v, ["type", "text", "muted"]) && text(v.text, 500) && (v.muted === void 0 || typeof v.muted === "boolean");
431
+ case "meter":
432
+ return keys(v, ["type", "label", "value", "max"]) && line(v.label, 40) && num(v.value) && num(v.max) && v.max > 0;
433
+ case "list":
434
+ return keys(v, ["type", "items"]) && Array.isArray(v.items) && v.items.length <= 20 && v.items.every((x) => line(x, 200));
435
+ case "button":
436
+ return keys(v, ["type", "id", "label"]) && typeof v.id === "string" && ID.test(v.id) && line(v.label, 40) && v.label.trim().length > 0;
437
+ case "toggle":
438
+ return keys(v, ["type", "id", "label", "on"]) && typeof v.id === "string" && ID.test(v.id) && line(v.label, 40) && typeof v.on === "boolean";
439
+ case "table": {
440
+ const row = (r) => Array.isArray(r) && r.length >= 1 && r.length <= 6 && r.every((c) => line(c, 100));
441
+ return keys(v, ["type", "header", "rows"]) && Array.isArray(v.rows) && v.rows.length <= 12 && v.rows.every(row) && (v.header === void 0 || row(v.header));
442
+ }
443
+ default:
444
+ return false;
445
+ }
446
+ };
447
+ const panel = (v) => isObj2(v) && keys(v, ["title", "items"]) && line(v.title, 60) && Array.isArray(v.items) && v.items.length <= PANEL_MAX_ITEMS && v.items.every(item) && new Set(v.items.flatMap((i) => "id" in i ? [i.id] : [])).size === v.items.filter((i) => "id" in i).length;
448
+ const hudEntry = (v) => isObj2(v) && keys(v, ["key", "label", "icon", "value", "bar"]) && typeof v.key === "string" && /^[a-z0-9_]{1,32}$/.test(v.key) && line(v.label, 24) && v.label.trim().length > 0 && line(v.value, 24) && (v.icon === void 0 || typeof v.icon === "string" && ICON_SET.has(v.icon)) && (v.bar === void 0 || isObj2(v.bar) && keys(v.bar, ["value", "max"]) && num(v.bar.value) && num(v.bar.max) && v.bar.max > 0);
449
+ const choice = (v) => isObj2(v) && keys(v, ["label", "text", "send"]) && line(v.label, 40) && v.label.trim().length > 0 && text(v.text, 2e3) && v.text.trim().length > 0 && (v.send === void 0 || typeof v.send === "boolean");
450
+ const ui = (ctx) => {
451
+ const o = ctx.uiOps;
452
+ if (!o) throw new Error("no chat");
453
+ return o;
454
+ };
455
+ return [
456
+ ["ui.panel", {
457
+ permission: "ui.panel",
458
+ check: (a) => a.length === 1 && (a[0] === null || panel(a[0])),
459
+ run: (a, ctx) => (ui(ctx).panel(a[0]), null)
460
+ }],
461
+ ["ui.hud", {
462
+ permission: "ui.hud",
463
+ check: (a) => a.length === 1 && Array.isArray(a[0]) && a[0].length <= HUD_MAX_ITEMS && a[0].every(hudEntry) && new Set(a[0].map((e) => e.key)).size === a[0].length,
464
+ run: (a, ctx) => (ui(ctx).hud(a[0]), null)
465
+ }],
466
+ ["ui.annotate", {
467
+ permission: "ui.annotate",
468
+ check: (a) => a.length === 1 && isObj2(a[0]) && keys(a[0], ["back", "text", "title", "badge"]) && (a[0].back === void 0 || Number.isInteger(a[0].back) && a[0].back >= 0 && a[0].back <= 1e3) && text(a[0].text, NOTE_MAX) && (a[0].title === void 0 || line(a[0].title, 40)) && (a[0].badge === void 0 || typeof a[0].badge === "boolean") && (a[0].badge !== true || line(a[0].text, 40)),
469
+ run: (a, ctx) => {
470
+ const o = a[0];
471
+ return ui(ctx).annotate({ back: o.back ?? 0, text: o.text, title: o.title?.trim() ?? "", badge: o.badge === true });
472
+ }
473
+ }],
474
+ ["ui.choices", {
475
+ permission: "ui.choices",
476
+ check: (a) => a.length === 1 && Array.isArray(a[0]) && a[0].length <= CHOICES_MAX && a[0].every(choice),
477
+ run: (a, ctx) => (ui(ctx).choices(a[0].map((c) => ({ label: c.label.trim(), text: c.text, send: c.send === true }))), null)
478
+ }],
479
+ ["composer.draft", {
480
+ permission: "composer.draft",
481
+ check: (a) => a.length === 1 && text(a[0], DRAFT_MAX),
482
+ run: (a, ctx) => ui(ctx).draft(a[0])
483
+ }],
484
+ ["ui.notify", {
485
+ permission: "ui.notify",
486
+ check: (a) => a.length === 1 && line(a[0], NOTIFY_MAX) && a[0].trim().length > 0,
487
+ run: (a, ctx) => (ui(ctx).notify(a[0].trim()), null)
488
+ }],
489
+ ["audio.play", {
490
+ permission: "audio.play",
491
+ check: (a) => a.length >= 1 && a.length <= 2 && typeof a[0] === "string" && a[0].length <= 128 && SOUND_NAME.test(a[0]) && (a.length === 1 || isObj2(a[1]) && keys(a[1], ["volume", "loop"]) && (a[1].volume === void 0 || num(a[1].volume) && a[1].volume >= 0 && a[1].volume <= 1) && (a[1].loop === void 0 || typeof a[1].loop === "boolean")),
492
+ run: (a, ctx) => {
493
+ const o = a[1] ?? {};
494
+ return ui(ctx).play(a[0], { volume: o.volume ?? 1, loop: o.loop === true });
495
+ }
496
+ }],
497
+ ["audio.stop", {
498
+ permission: "audio.play",
499
+ check: (a) => a.length === 0 || a.length === 1 && typeof a[0] === "string" && a[0].length <= 128,
500
+ run: (a, ctx) => (ui(ctx).stop(a[0]), null)
501
+ }],
502
+ ["voice.speak", {
503
+ permission: "voice.speak",
504
+ check: (a) => a.length === 1 && text(a[0], SPEAK_MAX) && a[0].trim().length > 0,
505
+ run: (a, ctx) => ui(ctx).speak(a[0])
506
+ }],
507
+ // ---- App services: no permission, nothing of the chat ----
508
+ ["dice.roll", {
509
+ permission: null,
510
+ check: (a) => a.length === 1 && typeof a[0] === "string" && a[0].length > 0 && a[0].length <= 64,
511
+ run: (a) => {
512
+ const r = rollDice(a[0]);
513
+ if (!r) throw new CapabilityError("bad_request");
514
+ return { expr: a[0], total: r.total, rolls: r.rolls, modifier: r.modifier, breakdown: r.breakdown };
515
+ }
516
+ }],
517
+ ["time.now", {
518
+ permission: null,
519
+ check: (a) => a.length === 0,
520
+ run: () => {
521
+ const d = /* @__PURE__ */ new Date();
522
+ const o = Intl.DateTimeFormat().resolvedOptions();
523
+ return { iso: d.toISOString(), epochMs: d.getTime(), timeZone: o.timeZone, locale: o.locale, offsetMinutes: -d.getTimezoneOffset() };
524
+ }
525
+ }],
526
+ ["text.tokens", {
527
+ permission: null,
528
+ check: (a) => a.length === 1 && typeof a[0] === "string" && a[0].length <= 4e5,
529
+ run: (a) => estimateTokens(a[0])
530
+ }]
531
+ ];
532
+ }
533
+ const GEN_PARAMS = {
534
+ temperature: { field: "temperature", min: 0, max: 2, int: false },
535
+ top_p: { field: "topP", min: 0, max: 1, int: false },
536
+ top_k: { field: "topK", min: 0, max: 500, int: true },
537
+ min_p: { field: "minP", min: 0, max: 1, int: false },
538
+ frequency_penalty: { field: "frequencyPenalty", min: -2, max: 2, int: false },
539
+ presence_penalty: { field: "presencePenalty", min: -2, max: 2, int: false },
540
+ repetition_penalty: { field: "repetitionPenalty", min: 0.5, max: 2, int: false }
541
+ };
542
+ const isGenParam = (k) => Object.hasOwn(GEN_PARAMS, k);
543
+ function clampParams(req, ranges) {
544
+ const applied = {};
545
+ const refused = [];
546
+ for (const [k, v] of Object.entries(req)) {
547
+ const r = ranges[k];
548
+ if (!r) {
549
+ refused.push(k);
550
+ continue;
551
+ }
552
+ const n = Math.min(r[1], Math.max(r[0], v));
553
+ applied[k] = GEN_PARAMS[k].int ? Math.round(n) : n;
554
+ }
555
+ return { applied, refused };
556
+ }
557
+ const toFields = (applied) => Object.fromEntries(Object.entries(applied).map(([k, v]) => [GEN_PARAMS[k].field, v]));
558
+ const EXT_STYLE_MAX = 64 * 1024;
559
+ const EXT_STYLED_CLASS = "ext-styled";
560
+ const hash = (s) => {
561
+ let h = 2166136261;
562
+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
563
+ return (h >>> 0).toString(36);
564
+ };
565
+ const slug = (id) => id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
566
+ const extChatClass = (id) => `ext-cs-${slug(id)}-${hash(id)}`;
567
+ function rgbOf(color) {
568
+ const t = color.trim();
569
+ let m = /^#?([0-9a-f]{6})$/i.exec(t)?.[1];
570
+ const short = /^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(t);
571
+ if (!m && short) m = short[1] + short[1] + short[2] + short[2] + short[3] + short[3];
572
+ if (m) {
573
+ const n = parseInt(m, 16);
574
+ return [n >> 16 & 255, n >> 8 & 255, n & 255];
575
+ }
576
+ const rgb = /^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})/i.exec(t);
577
+ return rgb ? [Math.min(255, +rgb[1]), Math.min(255, +rgb[2]), Math.min(255, +rgb[3])] : null;
578
+ }
579
+ function luminance(hex) {
580
+ const c = rgbOf(hex);
581
+ if (!c) return 0.2;
582
+ const chan = (v) => {
583
+ v /= 255;
584
+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
585
+ };
586
+ return 0.2126 * chan(c[0]) + 0.7152 * chan(c[1]) + 0.0722 * chan(c[2]);
587
+ }
588
+ function contrastRatio(a, b) {
589
+ const la = luminance(a);
590
+ const lb = luminance(b);
591
+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
592
+ }
593
+ const THEME_TOKENS = [
594
+ "--bg",
595
+ "--bg-alt",
596
+ "--surface",
597
+ "--surface-accent",
598
+ "--surface-2",
599
+ "--color-nav-header",
600
+ "--foreground",
601
+ "--muted",
602
+ "--border",
603
+ "--border-accent",
604
+ "--purple",
605
+ "--highlight",
606
+ "--button-border",
607
+ "--purple-light",
608
+ "--purple-dark",
609
+ "--reply-bg",
610
+ "--selected-bg",
611
+ "--tab-bg",
612
+ "--orange",
613
+ "--orange-dark",
614
+ "--green",
615
+ "--danger",
616
+ "--warning"
617
+ ];
618
+ const CHAT_COLORS = ["quoteColor", "italicColor", "boldColor", "textColor"];
619
+ const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
620
+ const TOKENS = new Set(THEME_TOKENS);
621
+ const THEME_NAME_MAX = 40;
622
+ const isObj$2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
623
+ function isExtTheme(v) {
624
+ if (!isObj$2(v) || !Object.keys(v).every((k) => ["name", "mode", "colors", "chat"].includes(k))) return false;
625
+ const { name, mode, colors, chat } = v;
626
+ if (typeof name !== "string" || !name.trim() || name.length > THEME_NAME_MAX || new RegExp("\\p{Cc}", "u").test(name)) return false;
627
+ if (mode !== "dark" && mode !== "light") return false;
628
+ if (!isObj$2(colors) || !Object.keys(colors).length) return false;
629
+ if (!Object.entries(colors).every(([k, c]) => TOKENS.has(k) && typeof c === "string" && HEX.test(c))) return false;
630
+ if (!readable(colors)) return false;
631
+ if (chat === void 0) return true;
632
+ return isObj$2(chat) && Object.entries(chat).every(([k, c]) => CHAT_COLORS.includes(k) && typeof c === "string" && HEX.test(c));
633
+ }
634
+ const INKS = ["--foreground", "--muted"];
635
+ const GROUNDS = ["--bg", "--bg-alt", "--surface", "--surface-accent", "--surface-2", "--reply-bg"];
636
+ const THEME_MIN_CONTRAST = 3;
637
+ function readable(colors) {
638
+ return INKS.every((i) => !colors[i] || GROUNDS.every((g) => !colors[g] || contrastRatio(colors[i], colors[g]) >= THEME_MIN_CONTRAST));
639
+ }
640
+ const css = (v) => v === null || typeof v === "string" && v.length <= EXT_STYLE_MAX && !v.includes("\0");
641
+ function p6bCapabilities() {
642
+ const p6b = (ctx) => {
643
+ const o = ctx.p6bOps;
644
+ if (!o) throw new Error("no chat");
645
+ return o;
646
+ };
647
+ return [
648
+ ["ui.style", {
649
+ permission: "ui.style",
650
+ check: (a) => a.length === 1 && css(a[0]),
651
+ run: (a, ctx) => (p6b(ctx).style(a[0]), null)
652
+ }],
653
+ ["ui.partStyle", {
654
+ // Implied by any `ui.*` permission (the runtime checks the manifest): it styles only what that one draws.
655
+ permission: null,
656
+ check: (a) => a.length === 1 && css(a[0]),
657
+ run: (a, ctx) => p6b(ctx).partStyle(a[0])
658
+ }],
659
+ ["ui.theme", {
660
+ permission: "ui.theme",
661
+ check: (a) => a.length === 1 && (a[0] === null || isExtTheme(a[0])),
662
+ run: async (a, ctx) => (await p6b(ctx).theme(a[0]), null)
663
+ }],
664
+ ["chat.generate", {
665
+ permission: "chat.generate",
666
+ check: (a) => a.length === 1 && (a[0] === "swipe" || a[0] === "continue"),
667
+ run: (a, ctx) => p6b(ctx).generate(a[0])
668
+ }],
669
+ ["gen.params", {
670
+ permission: "gen.params",
671
+ check: (a) => a.length === 1 && (a[0] === null || a[0] !== null && typeof a[0] === "object" && !Array.isArray(a[0]) && Object.entries(a[0]).length > 0 && Object.entries(a[0]).every(([k, v]) => isGenParam(k) && typeof v === "number" && Number.isFinite(v) && v >= GEN_PARAMS[k].min && v <= GEN_PARAMS[k].max)),
672
+ run: (a, ctx) => p6b(ctx).params(a[0])
673
+ }],
674
+ ["prompt.macro", {
675
+ permission: "prompt.macro",
676
+ check: (a) => a.length === 1 && typeof a[0] === "string" && MACRO_NAME.test(a[0]),
677
+ run: (a, ctx) => p6b(ctx).macro(a[0])
678
+ }]
679
+ ];
680
+ }
681
+ const MACRO_NAME = /^[a-z][a-z0-9_]{0,31}$/;
682
+ function pureDuring(capabilities, isPure) {
683
+ return new Map([...capabilities].map(([k, c]) => [k, k === "log" ? c : {
684
+ ...c,
685
+ run: (a, ctx) => {
686
+ if (isPure()) throw new CapabilityError("denied");
687
+ return c.run(a, ctx);
688
+ }
689
+ }]));
690
+ }
691
+ class CapabilityError extends Error {
692
+ constructor(code) {
693
+ super(code);
694
+ this.code = code;
695
+ }
696
+ code;
697
+ }
698
+ const SPIKE_CAPABILITIES = new Map([
699
+ [
700
+ "log",
701
+ {
702
+ permission: null,
703
+ check: (a) => a.length === 1 && typeof a[0] === "string",
704
+ run: (a, ctx) => {
705
+ ctx.log.push(a[0].slice(0, LOG_MAX_LINE));
706
+ if (ctx.log.length > LOG_MAX_LINES) ctx.log.splice(0, ctx.log.length - LOG_MAX_LINES);
707
+ appendExtLog(ctx.extensionId, a[0]);
708
+ return null;
709
+ }
710
+ }
711
+ ],
712
+ [
713
+ "chat.read",
714
+ {
715
+ permission: "chat.read",
716
+ check: (a) => a.length === 0,
717
+ // A copy: the broker serializes whatever this returns, so the extension never holds a host object.
718
+ run: (_a, ctx) => ctx.chat()
719
+ }
720
+ ],
721
+ ...storageCapabilities()
722
+ ]);
723
+ const storageKey = (k) => typeof k === "string" && k.length > 0 && k.length <= 128 && !k.startsWith("rin:") && !new RegExp("\\p{Cc}", "u").test(k);
724
+ function rustCall(ctx, cmd, args) {
725
+ if (!ctx.rust) throw new Error("no storage");
726
+ return ctx.rust(cmd, args).catch((e) => {
727
+ const code = /ext_err:([a-z_]+)/.exec(String(e))?.[1];
728
+ throw new CapabilityError(code === "quota" ? "quota" : code === "too_large" ? "too_large" : "bad_request");
729
+ });
730
+ }
731
+ function storageCapabilities() {
732
+ return [
733
+ ["storage.get", {
734
+ permission: "storage",
735
+ check: (a) => a.length === 1 && storageKey(a[0]),
736
+ run: async (a, ctx) => {
737
+ const text = await rustCall(ctx, "ext_storage_get", { id: ctx.extensionId, key: a[0] });
738
+ if (text === null) return null;
739
+ const p = safeParse(text);
740
+ if (!p.ok) throw new CapabilityError(p.error);
741
+ return p.value;
742
+ }
743
+ }],
744
+ ["storage.set", {
745
+ permission: "storage",
746
+ check: (a) => a.length === 2 && storageKey(a[0]),
747
+ run: async (a, ctx) => {
748
+ const s = safeStringify(a[1]);
749
+ if (!s.ok) throw new CapabilityError(s.error);
750
+ await rustCall(ctx, "ext_storage_set", { id: ctx.extensionId, key: a[0], value: s.text });
751
+ return null;
752
+ }
753
+ }],
754
+ ["storage.delete", {
755
+ permission: "storage",
756
+ check: (a) => a.length === 1 && storageKey(a[0]),
757
+ run: async (a, ctx) => {
758
+ await rustCall(ctx, "ext_storage_delete", { id: ctx.extensionId, key: a[0] });
759
+ return null;
760
+ }
761
+ }],
762
+ ["storage.keys", {
763
+ permission: "storage",
764
+ check: (a) => a.length === 0,
765
+ // An array, never an object keyed by the extension's own key names.
766
+ run: (_a, ctx) => rustCall(ctx, "ext_storage_keys", { id: ctx.extensionId })
767
+ }],
768
+ ["settings.get", {
769
+ permission: "ui.settings",
770
+ check: (a) => a.length === 0,
771
+ // Resolved in Rust against the manifest's form: every value fits its field. Keys are form keys, which
772
+ // validate_settings keeps to `[a-z][A-Za-z0-9_]*` minus the names safeParse refuses.
773
+ run: (_a, ctx) => rustCall(ctx, "ext_settings_get", { id: ctx.extensionId })
774
+ }]
775
+ ];
776
+ }
777
+ function netCapabilities() {
778
+ const str = (v, max) => typeof v === "string" && v.length <= max;
779
+ const net = (ctx) => {
780
+ if (!ctx.net) throw new Error("no chat");
781
+ return ctx.net;
782
+ };
783
+ return [
784
+ ["net.request", {
785
+ permission: null,
786
+ check: (a) => {
787
+ if (a.length !== 1 || a[0] === null || typeof a[0] !== "object" || Array.isArray(a[0])) return false;
788
+ const { method, url, headers, body, ...rest } = a[0];
789
+ return Object.keys(rest).length === 0 && str(method, 16) && str(url, 8192) && (body === void 0 || str(body, 65536)) && (headers === void 0 || Array.isArray(headers) && headers.length <= 32 && headers.every((h) => Array.isArray(h) && h.length === 2 && str(h[0], 64) && str(h[1], 4096)));
790
+ },
791
+ run: (a, ctx) => net(ctx).request(a[0])
792
+ }],
793
+ ["open.url", {
794
+ permission: "open.url",
795
+ check: (a) => a.length === 1 && str(a[0], 8192),
796
+ run: (a, ctx) => net(ctx).open(a[0])
797
+ }]
798
+ ];
799
+ }
800
+ const VAR_NAME = /^[A-Za-z_]\w{0,40}$/;
801
+ const RESERVED_VAR = /^(?:lore_|roster_|adv_(?:npc|dm)_)/i;
802
+ const MAX_VARS_PER_CALL = 32;
803
+ const MAX_VAR_VALUE = 4e3;
804
+ const MAX_INJECTION = 8e3;
805
+ const MAX_DEPTH_IN_HISTORY = 1e3;
806
+ const COMMAND_NAME = /^[a-z][a-z0-9_]{0,31}$/;
807
+ const MAX_COMMAND_DESC = 120;
808
+ const isObj$1 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
809
+ const ops = (ctx) => {
810
+ const o = ctx.chatOps;
811
+ if (!o) throw new Error("no chat");
812
+ return o;
813
+ };
814
+ const CHAT_CAPABILITIES = new Map([
815
+ ...SPIKE_CAPABILITIES,
816
+ ...netCapabilities(),
817
+ [
818
+ "chat.vars.get",
819
+ { permission: "chat.vars", check: (a) => a.length === 0, run: (_a, ctx) => ops(ctx).vars() }
820
+ ],
821
+ [
822
+ "chat.vars.set",
823
+ {
824
+ permission: "chat.vars",
825
+ check: (a) => {
826
+ if (a.length !== 1 || !isObj$1(a[0])) return false;
827
+ const e = Object.entries(a[0]);
828
+ return e.length > 0 && e.length <= MAX_VARS_PER_CALL && e.every(([k, v]) => VAR_NAME.test(k) && !RESERVED_VAR.test(k) && (typeof v === "number" ? Number.isFinite(v) : typeof v === "boolean" || typeof v === "string" && v.length <= MAX_VAR_VALUE));
829
+ },
830
+ run: (a, ctx) => {
831
+ const out = {};
832
+ for (const [k, v] of Object.entries(a[0])) out[k] = String(v);
833
+ if (!ops(ctx).setVars(out)) throw new CapabilityError("too_many_requests");
834
+ return null;
835
+ }
836
+ }
837
+ ],
838
+ [
839
+ "prompt.inject",
840
+ {
841
+ permission: "prompt.inject",
842
+ check: (a) => {
843
+ if (a.length !== 1 || !isObj$1(a[0])) return false;
844
+ const { text, depth, role, ...rest } = a[0];
845
+ return Object.keys(rest).length === 0 && typeof text === "string" && text.trim().length > 0 && text.length <= MAX_INJECTION && (depth === void 0 || Number.isInteger(depth) && depth >= 0 && depth <= MAX_DEPTH_IN_HISTORY) && (role === void 0 || role === "system" || role === "user" || role === "assistant");
846
+ },
847
+ run: (a, ctx) => {
848
+ const o = a[0];
849
+ return ops(ctx).inject({ text: o.text, depth: o.depth ?? 0, role: o.role ?? "system" });
850
+ }
851
+ }
852
+ ],
853
+ [
854
+ "ui.command",
855
+ {
856
+ permission: "ui.command",
857
+ check: (a) => a.length === 1 && isObj$1(a[0]) && typeof a[0].name === "string" && COMMAND_NAME.test(a[0].name) && (a[0].description === void 0 || typeof a[0].description === "string" && a[0].description.length <= MAX_COMMAND_DESC),
858
+ run: (a, ctx) => {
859
+ const o = a[0];
860
+ return ops(ctx).command({ name: o.name, description: o.description?.trim() ?? "" });
861
+ }
862
+ }
863
+ ],
864
+ ...turnCapabilities(),
865
+ ...uiCapabilities(),
866
+ // P6a
867
+ ...p6bCapabilities()
868
+ // P6b
869
+ ]);
870
+ function turnCapabilities() {
871
+ const MSG_MAX = 4e5;
872
+ const ROLES = /* @__PURE__ */ new Set(["system", "user", "assistant"]);
873
+ const obj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
874
+ const message = (v, max) => {
875
+ if (!obj(v)) return false;
876
+ const { role, content, ...rest } = v;
877
+ return Object.keys(rest).length === 0 && typeof role === "string" && ROLES.has(role) && typeof content === "string" && content.length <= max;
878
+ };
879
+ const turn = (ctx) => {
880
+ const o = ctx.turnOps;
881
+ if (!o) throw new Error("no chat");
882
+ return o;
883
+ };
884
+ return [
885
+ ["model.run", {
886
+ permission: "model.run",
887
+ check: (a) => {
888
+ if (a.length !== 1 || !obj(a[0])) return false;
889
+ const { messages, maxTokens, temperature, ...rest } = a[0];
890
+ return Object.keys(rest).length === 0 && Array.isArray(messages) && messages.length > 0 && messages.length <= 64 && messages.every((m) => message(m, 1e5)) && messages.reduce((n, m) => n + m.content.length, 0) <= MSG_MAX && (maxTokens === void 0 || Number.isInteger(maxTokens) && maxTokens >= 1 && maxTokens <= 4096) && (temperature === void 0 || typeof temperature === "number" && temperature >= 0 && temperature <= 2);
891
+ },
892
+ run: (a, ctx) => turn(ctx).model(a[0])
893
+ }],
894
+ ["prompt.rewrite", {
895
+ permission: "prompt.rewrite",
896
+ check: (a) => a.length === 1 && Array.isArray(a[0]) && a[0].length > 0 && a[0].length <= 2e3 && a[0].every((m) => message(m, MSG_MAX)),
897
+ run: (a, ctx) => turn(ctx).rewrite(a[0])
898
+ }],
899
+ ["reply.transform", {
900
+ permission: "reply.transform",
901
+ check: (a) => a.length === 1 && typeof a[0] === "string" && a[0].length <= MSG_MAX,
902
+ run: (a, ctx) => turn(ctx).transform(a[0])
903
+ }],
904
+ ["chat.send", {
905
+ permission: "chat.send",
906
+ check: (a) => a.length === 1 && typeof a[0] === "string" && a[0].trim().length > 0 && a[0].length <= 8e3,
907
+ run: (a, ctx) => turn(ctx).send(a[0])
908
+ }]
909
+ ];
910
+ }
911
+ const HOOK_DEADLINE_MS = 1e3;
912
+ const MODEL_HOOK_DEADLINE_MS = 6e4;
913
+ const CLOSE_DEADLINE_MS = 300;
914
+ const USER_STARTED = /* @__PURE__ */ new Set(["onCommand", "onWidget", "onPanel"]);
915
+ const REPLY_EVERY_MS = 500;
916
+ const MAX_INJECTIONS = 4;
917
+ const MAX_COMMANDS = 16;
918
+ const MAX_VAR_WRITES = 8;
919
+ const RESERVED_COMMANDS = /* @__PURE__ */ new Set(["continue", "impersonate", "image", "img", "sd"]);
920
+ const SEND_HOOKS = /* @__PURE__ */ new Set(["onCommand", "onWidget", "onChatOpen", "onReplyDone"]);
921
+ const MAX_SENDS_PER_CALL = 2;
922
+ const MAX_SENDS_PER_WINDOW = 6;
923
+ const SEND_WINDOW_MS = 6e4;
924
+ const MAX_MACROS = 16;
925
+ const MACRO_DEADLINE_MS = 200;
926
+ const MACRO_MAX = 4e3;
927
+ const RENDER_DEADLINE_MS = 300;
928
+ const RENDER_BATCH = 20;
929
+ const RENDER_MAX = 1e5;
930
+ const NOTES_PER_EXT = 50;
931
+ const NOTIFY_PER_WINDOW = 3;
932
+ const NOTIFY_WINDOW_MS = 2e4;
933
+ const SPEAK_PER_MINUTE = 6;
934
+ const SOUNDS_AT_ONCE = 4;
935
+ const FAIL_LIMIT = 3;
936
+ const NOT_A_FAILURE = /* @__PURE__ */ new Set(["no_hook", "killed"]);
937
+ const OPEN_DECLINES = 3;
938
+ const NET_LOG_MAX = 200;
939
+ const EXT_USAGE_KIND = "extension";
940
+ const DEFAULT_MAX_TOKENS = 512;
941
+ const MIN_LEFT = 16;
942
+ const own = (r, k) => Object.hasOwn(r, k) ? r[k] : void 0;
943
+ const localDate = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
944
+ const usedToday = (use, id, now = /* @__PURE__ */ new Date()) => {
945
+ const u = own(use, id);
946
+ const date = localDate(now);
947
+ return u && u.date === date ? u : { date, requests: 0, tokens: 0 };
948
+ };
949
+ let queue = Promise.resolve();
950
+ const serial = (fn) => {
951
+ const next = queue.then(fn, fn);
952
+ queue = next.catch(() => void 0);
953
+ return next;
954
+ };
955
+ async function runModel(id, req, signal, deps) {
956
+ const prompt = req.messages.reduce((n, m) => n + estimateTokens(m.content) + 4, 0);
957
+ const { provider, maxTokens } = await serial(async () => {
958
+ const pref = own(await deps.prefs(), id);
959
+ if (!pref?.config) throw new CapabilityError("no_model");
960
+ const cfg = (await deps.configs()).find((c) => c.id === pref.config);
961
+ if (!cfg || !deps.usable(cfg)) throw new CapabilityError("no_model");
962
+ const all = await deps.use();
963
+ const today = usedToday(all, id, deps.now());
964
+ const left = pref.tokens - today.tokens - prompt;
965
+ if (today.requests >= pref.requests || left < MIN_LEFT) throw new CapabilityError("budget");
966
+ await deps.saveUse({ ...all, [id]: { ...today, requests: today.requests + 1, tokens: today.tokens + prompt } });
967
+ return { provider: deps.provider(cfg), maxTokens: Math.min(req.maxTokens ?? DEFAULT_MAX_TOKENS, left) };
968
+ });
969
+ let text;
970
+ try {
971
+ text = await provider.complete({ messages: req.messages, maxTokens, temperature: req.temperature, signal, context: EXT_USAGE_KIND });
972
+ } catch {
973
+ throw new CapabilityError("model_failed");
974
+ }
975
+ const completion = estimateTokens(text);
976
+ await serial(async () => {
977
+ const all = await deps.use();
978
+ const today = usedToday(all, id, deps.now());
979
+ await deps.saveUse({ ...all, [id]: { ...today, tokens: today.tokens + completion } });
980
+ }).catch(() => {
981
+ });
982
+ return { text, usage: { prompt, completion } };
983
+ }
984
+ var EvalFlags = { JS_EVAL_TYPE_GLOBAL: 0, JS_EVAL_TYPE_MODULE: 1, JS_EVAL_FLAG_STRICT: 8, JS_EVAL_FLAG_STRIP: 16, JS_EVAL_FLAG_COMPILE_ONLY: 32, JS_EVAL_FLAG_BACKTRACE_BARRIER: 64 }, IntrinsicsFlags = { BaseObjects: 1, Date: 2, Eval: 4, StringNormalize: 8, RegExp: 16, RegExpCompiler: 32, JSON: 64, Proxy: 128, MapSet: 256, TypedArrays: 512, Promise: 1024, BigInt: 2048, BigFloat: 4096, BigDecimal: 8192, OperatorOverloading: 16384, BignumExt: 32768 }, JSPromiseStateEnum = { Pending: 0, Fulfilled: 1, Rejected: 2 }, GetOwnPropertyNamesFlags = { JS_GPN_STRING_MASK: 1, JS_GPN_SYMBOL_MASK: 2, JS_GPN_PRIVATE_MASK: 4, JS_GPN_ENUM_ONLY: 16, QTS_GPN_NUMBER_MASK: 64, QTS_STANDARD_COMPLIANT_NUMBER: 128 }, IsEqualOp = { IsStrictlyEqual: 0, IsSameValue: 1, IsSameValueZero: 2 };
985
+ var __defProp = Object.defineProperty;
986
+ var __export = (target, all) => {
987
+ for (var name in all) __defProp(target, name, { get: all[name], enumerable: true });
988
+ };
989
+ function debugLog(...args) {
990
+ }
991
+ var errors_exports = {};
992
+ __export(errors_exports, { QuickJSAsyncifyError: () => QuickJSAsyncifyError, QuickJSAsyncifySuspended: () => QuickJSAsyncifySuspended, QuickJSEmptyGetOwnPropertyNames: () => QuickJSEmptyGetOwnPropertyNames, QuickJSEmscriptenModuleError: () => QuickJSEmscriptenModuleError, QuickJSHostRefInvalid: () => QuickJSHostRefInvalid, QuickJSHostRefRangeExceeded: () => QuickJSHostRefRangeExceeded, QuickJSMemoryLeakDetected: () => QuickJSMemoryLeakDetected, QuickJSNotImplemented: () => QuickJSNotImplemented, QuickJSPromisePending: () => QuickJSPromisePending, QuickJSUnknownIntrinsic: () => QuickJSUnknownIntrinsic, QuickJSUnwrapError: () => QuickJSUnwrapError, QuickJSUseAfterFree: () => QuickJSUseAfterFree, QuickJSWrongOwner: () => QuickJSWrongOwner });
993
+ var QuickJSUnwrapError = class extends Error {
994
+ constructor(cause, context) {
995
+ let message = typeof cause == "object" && cause && "message" in cause ? String(cause.message) : String(cause);
996
+ super(message);
997
+ this.cause = cause;
998
+ this.context = context;
999
+ this.name = "QuickJSUnwrapError";
1000
+ }
1001
+ }, QuickJSWrongOwner = class extends Error {
1002
+ constructor() {
1003
+ super(...arguments);
1004
+ this.name = "QuickJSWrongOwner";
1005
+ }
1006
+ }, QuickJSUseAfterFree = class extends Error {
1007
+ constructor() {
1008
+ super(...arguments);
1009
+ this.name = "QuickJSUseAfterFree";
1010
+ }
1011
+ }, QuickJSNotImplemented = class extends Error {
1012
+ constructor() {
1013
+ super(...arguments);
1014
+ this.name = "QuickJSNotImplemented";
1015
+ }
1016
+ }, QuickJSAsyncifyError = class extends Error {
1017
+ constructor() {
1018
+ super(...arguments);
1019
+ this.name = "QuickJSAsyncifyError";
1020
+ }
1021
+ }, QuickJSAsyncifySuspended = class extends Error {
1022
+ constructor() {
1023
+ super(...arguments);
1024
+ this.name = "QuickJSAsyncifySuspended";
1025
+ }
1026
+ }, QuickJSMemoryLeakDetected = class extends Error {
1027
+ constructor() {
1028
+ super(...arguments);
1029
+ this.name = "QuickJSMemoryLeakDetected";
1030
+ }
1031
+ }, QuickJSEmscriptenModuleError = class extends Error {
1032
+ constructor() {
1033
+ super(...arguments);
1034
+ this.name = "QuickJSEmscriptenModuleError";
1035
+ }
1036
+ }, QuickJSUnknownIntrinsic = class extends TypeError {
1037
+ constructor() {
1038
+ super(...arguments);
1039
+ this.name = "QuickJSUnknownIntrinsic";
1040
+ }
1041
+ }, QuickJSPromisePending = class extends Error {
1042
+ constructor() {
1043
+ super(...arguments);
1044
+ this.name = "QuickJSPromisePending";
1045
+ }
1046
+ }, QuickJSEmptyGetOwnPropertyNames = class extends Error {
1047
+ constructor() {
1048
+ super(...arguments);
1049
+ this.name = "QuickJSEmptyGetOwnPropertyNames";
1050
+ }
1051
+ }, QuickJSHostRefRangeExceeded = class extends Error {
1052
+ constructor() {
1053
+ super(...arguments);
1054
+ this.name = "QuickJSHostRefRangeExceeded";
1055
+ }
1056
+ }, QuickJSHostRefInvalid = class extends Error {
1057
+ constructor() {
1058
+ super(...arguments);
1059
+ this.name = "QuickJSHostRefInvalid";
1060
+ }
1061
+ };
1062
+ function* awaitYield(value) {
1063
+ return yield value;
1064
+ }
1065
+ function awaitYieldOf(generator) {
1066
+ return awaitYield(awaitEachYieldedPromise(generator));
1067
+ }
1068
+ var AwaitYield = awaitYield;
1069
+ AwaitYield.of = awaitYieldOf;
1070
+ function maybeAsyncFn(that, fn) {
1071
+ return (...args) => {
1072
+ let generator = fn.call(that, AwaitYield, ...args);
1073
+ return awaitEachYieldedPromise(generator);
1074
+ };
1075
+ }
1076
+ function maybeAsync(that, startGenerator) {
1077
+ let generator = startGenerator.call(that, AwaitYield);
1078
+ return awaitEachYieldedPromise(generator);
1079
+ }
1080
+ function awaitEachYieldedPromise(gen) {
1081
+ function handleNextStep(step) {
1082
+ return step.done ? step.value : step.value instanceof Promise ? step.value.then((value) => handleNextStep(gen.next(value)), (error) => handleNextStep(gen.throw(error))) : handleNextStep(gen.next(step.value));
1083
+ }
1084
+ return handleNextStep(gen.next());
1085
+ }
1086
+ var UsingDisposable = class {
1087
+ [Symbol.dispose]() {
1088
+ return this.dispose();
1089
+ }
1090
+ }, SymbolDispose = Symbol.dispose ?? /* @__PURE__ */ Symbol.for("Symbol.dispose"), prototypeAsAny = UsingDisposable.prototype;
1091
+ prototypeAsAny[SymbolDispose] || (prototypeAsAny[SymbolDispose] = function() {
1092
+ return this.dispose();
1093
+ });
1094
+ var Lifetime = class _Lifetime extends UsingDisposable {
1095
+ constructor(_value, copier, disposer, _owner) {
1096
+ super();
1097
+ this._value = _value;
1098
+ this.copier = copier;
1099
+ this.disposer = disposer;
1100
+ this._owner = _owner;
1101
+ this._alive = true;
1102
+ this._constructorStack = void 0;
1103
+ }
1104
+ get alive() {
1105
+ return this._alive;
1106
+ }
1107
+ get value() {
1108
+ return this.assertAlive(), this._value;
1109
+ }
1110
+ get owner() {
1111
+ return this._owner;
1112
+ }
1113
+ get dupable() {
1114
+ return !!this.copier;
1115
+ }
1116
+ dup() {
1117
+ if (this.assertAlive(), !this.copier) throw new Error("Non-dupable lifetime");
1118
+ return new _Lifetime(this.copier(this._value), this.copier, this.disposer, this._owner);
1119
+ }
1120
+ consume(map) {
1121
+ this.assertAlive();
1122
+ let result = map(this);
1123
+ return this.dispose(), result;
1124
+ }
1125
+ map(map) {
1126
+ return this.assertAlive(), map(this);
1127
+ }
1128
+ tap(fn) {
1129
+ return fn(this), this;
1130
+ }
1131
+ dispose() {
1132
+ this.assertAlive(), this.disposer && this.disposer(this._value), this._alive = false;
1133
+ }
1134
+ assertAlive() {
1135
+ if (!this.alive) throw this._constructorStack ? new QuickJSUseAfterFree(`Lifetime not alive
1136
+ ${this._constructorStack}
1137
+ Lifetime used`) : new QuickJSUseAfterFree("Lifetime not alive");
1138
+ }
1139
+ }, StaticLifetime = class extends Lifetime {
1140
+ constructor(value, owner) {
1141
+ super(value, void 0, void 0, owner);
1142
+ }
1143
+ get dupable() {
1144
+ return true;
1145
+ }
1146
+ dup() {
1147
+ return this;
1148
+ }
1149
+ dispose() {
1150
+ }
1151
+ }, WeakLifetime = class extends Lifetime {
1152
+ constructor(value, copier, disposer, owner) {
1153
+ super(value, copier, disposer, owner);
1154
+ }
1155
+ dispose() {
1156
+ this._alive = false;
1157
+ }
1158
+ };
1159
+ function scopeFinally(scope, blockError) {
1160
+ let disposeError;
1161
+ try {
1162
+ scope.dispose();
1163
+ } catch (error) {
1164
+ disposeError = error;
1165
+ }
1166
+ if (blockError && disposeError) throw Object.assign(blockError, { message: `${blockError.message}
1167
+ Then, failed to dispose scope: ${disposeError.message}`, disposeError }), blockError;
1168
+ if (blockError || disposeError) throw blockError || disposeError;
1169
+ }
1170
+ var Scope = class _Scope extends UsingDisposable {
1171
+ constructor() {
1172
+ super(...arguments);
1173
+ this._disposables = new Lifetime(/* @__PURE__ */ new Set());
1174
+ this.manage = (lifetime) => (this._disposables.value.add(lifetime), lifetime);
1175
+ }
1176
+ static withScope(block) {
1177
+ let scope = new _Scope(), blockError;
1178
+ try {
1179
+ return block(scope);
1180
+ } catch (error) {
1181
+ throw blockError = error, error;
1182
+ } finally {
1183
+ scopeFinally(scope, blockError);
1184
+ }
1185
+ }
1186
+ static withScopeMaybeAsync(_this, block) {
1187
+ return maybeAsync(void 0, function* (awaited) {
1188
+ let scope = new _Scope(), blockError;
1189
+ try {
1190
+ return yield* awaited.of(block.call(_this, awaited, scope));
1191
+ } catch (error) {
1192
+ throw blockError = error, error;
1193
+ } finally {
1194
+ scopeFinally(scope, blockError);
1195
+ }
1196
+ });
1197
+ }
1198
+ static async withScopeAsync(block) {
1199
+ let scope = new _Scope(), blockError;
1200
+ try {
1201
+ return await block(scope);
1202
+ } catch (error) {
1203
+ throw blockError = error, error;
1204
+ } finally {
1205
+ scopeFinally(scope, blockError);
1206
+ }
1207
+ }
1208
+ get alive() {
1209
+ return this._disposables.alive;
1210
+ }
1211
+ dispose() {
1212
+ let lifetimes = Array.from(this._disposables.value.values()).reverse();
1213
+ for (let lifetime of lifetimes) lifetime.alive && lifetime.dispose();
1214
+ this._disposables.dispose();
1215
+ }
1216
+ };
1217
+ function createDisposableArray(items) {
1218
+ let array = items ? Array.from(items) : [];
1219
+ function disposeAlive() {
1220
+ return array.forEach((disposable) => disposable.alive ? disposable.dispose() : void 0);
1221
+ }
1222
+ function someIsAlive() {
1223
+ return array.some((disposable) => disposable.alive);
1224
+ }
1225
+ return Object.defineProperty(array, SymbolDispose, { configurable: true, enumerable: false, value: disposeAlive }), Object.defineProperty(array, "dispose", { configurable: true, enumerable: false, value: disposeAlive }), Object.defineProperty(array, "alive", { configurable: true, enumerable: false, get: someIsAlive }), array;
1226
+ }
1227
+ function isDisposable(value) {
1228
+ return !!(value && (typeof value == "object" || typeof value == "function") && "alive" in value && typeof value.alive == "boolean" && "dispose" in value && typeof value.dispose == "function");
1229
+ }
1230
+ var AbstractDisposableResult = class _AbstractDisposableResult extends UsingDisposable {
1231
+ static success(value) {
1232
+ return new DisposableSuccess(value);
1233
+ }
1234
+ static fail(error, onUnwrap) {
1235
+ return new DisposableFail(error, onUnwrap);
1236
+ }
1237
+ static is(result) {
1238
+ return result instanceof _AbstractDisposableResult;
1239
+ }
1240
+ }, DisposableSuccess = class extends AbstractDisposableResult {
1241
+ constructor(value) {
1242
+ super();
1243
+ this.value = value;
1244
+ }
1245
+ get alive() {
1246
+ return isDisposable(this.value) ? this.value.alive : true;
1247
+ }
1248
+ dispose() {
1249
+ isDisposable(this.value) && this.value.dispose();
1250
+ }
1251
+ unwrap() {
1252
+ return this.value;
1253
+ }
1254
+ unwrapOr(_fallback) {
1255
+ return this.value;
1256
+ }
1257
+ }, DisposableFail = class extends AbstractDisposableResult {
1258
+ constructor(error, onUnwrap) {
1259
+ super();
1260
+ this.error = error;
1261
+ this.onUnwrap = onUnwrap;
1262
+ }
1263
+ get alive() {
1264
+ return isDisposable(this.error) ? this.error.alive : true;
1265
+ }
1266
+ dispose() {
1267
+ isDisposable(this.error) && this.error.dispose();
1268
+ }
1269
+ unwrap() {
1270
+ throw this.onUnwrap(this), this.error;
1271
+ }
1272
+ unwrapOr(fallback) {
1273
+ return fallback;
1274
+ }
1275
+ }, DisposableResult = AbstractDisposableResult;
1276
+ var QuickJSDeferredPromise = class extends UsingDisposable {
1277
+ constructor(args) {
1278
+ super();
1279
+ this.resolve = (value) => {
1280
+ this.resolveHandle.alive && (this.context.unwrapResult(this.context.callFunction(this.resolveHandle, this.context.undefined, value || this.context.undefined)).dispose(), this.disposeResolvers(), this.onSettled());
1281
+ };
1282
+ this.reject = (value) => {
1283
+ this.rejectHandle.alive && (this.context.unwrapResult(this.context.callFunction(this.rejectHandle, this.context.undefined, value || this.context.undefined)).dispose(), this.disposeResolvers(), this.onSettled());
1284
+ };
1285
+ this.dispose = () => {
1286
+ this.handle.alive && this.handle.dispose(), this.disposeResolvers();
1287
+ };
1288
+ this.context = args.context, this.owner = args.context.runtime, this.handle = args.promiseHandle, this.settled = new Promise((resolve2) => {
1289
+ this.onSettled = resolve2;
1290
+ }), this.resolveHandle = args.resolveHandle, this.rejectHandle = args.rejectHandle;
1291
+ }
1292
+ get alive() {
1293
+ return this.handle.alive || this.resolveHandle.alive || this.rejectHandle.alive;
1294
+ }
1295
+ disposeResolvers() {
1296
+ this.resolveHandle.alive && this.resolveHandle.dispose(), this.rejectHandle.alive && this.rejectHandle.dispose();
1297
+ }
1298
+ };
1299
+ var ModuleMemory = class {
1300
+ constructor(module) {
1301
+ this.module = module;
1302
+ }
1303
+ toPointerArray(handleArray) {
1304
+ let typedArray = new Int32Array(handleArray.map((handle) => handle.value)), numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT, ptr = this.module._malloc(numBytes);
1305
+ return new Uint8Array(this.module.HEAPU8.buffer, ptr, numBytes).set(new Uint8Array(typedArray.buffer)), new Lifetime(ptr, void 0, (ptr2) => this.module._free(ptr2));
1306
+ }
1307
+ newTypedArray(kind, length) {
1308
+ let zeros = new kind(new Array(length).fill(0)), numBytes = zeros.length * zeros.BYTES_PER_ELEMENT, ptr = this.module._malloc(numBytes), typedArray = new kind(this.module.HEAPU8.buffer, ptr, length);
1309
+ return typedArray.set(zeros), new Lifetime({ typedArray, ptr }, void 0, (value) => this.module._free(value.ptr));
1310
+ }
1311
+ newMutablePointerArray(length) {
1312
+ return this.newTypedArray(Int32Array, length);
1313
+ }
1314
+ newHeapCharPointer(string) {
1315
+ let strlen = this.module.lengthBytesUTF8(string), dataBytes = strlen + 1, ptr = this.module._malloc(dataBytes);
1316
+ return this.module.stringToUTF8(string, ptr, dataBytes), new Lifetime({ ptr, strlen }, void 0, (value) => this.module._free(value.ptr));
1317
+ }
1318
+ newHeapBufferPointer(buffer) {
1319
+ let numBytes = buffer.byteLength, ptr = this.module._malloc(numBytes);
1320
+ return this.module.HEAPU8.set(buffer, ptr), new Lifetime({ pointer: ptr, numBytes }, void 0, (value) => this.module._free(value.pointer));
1321
+ }
1322
+ consumeHeapCharPointer(ptr) {
1323
+ let str = this.module.UTF8ToString(ptr);
1324
+ return this.module._free(ptr), str;
1325
+ }
1326
+ };
1327
+ function intrinsicsToFlags(intrinsics) {
1328
+ if (!intrinsics) return 0;
1329
+ let result = 0;
1330
+ for (let [maybeIntrinsicName, enabled] of Object.entries(intrinsics)) {
1331
+ if (!(maybeIntrinsicName in IntrinsicsFlags)) throw new QuickJSUnknownIntrinsic(maybeIntrinsicName);
1332
+ enabled && (result |= IntrinsicsFlags[maybeIntrinsicName]);
1333
+ }
1334
+ return result;
1335
+ }
1336
+ function evalOptionsToFlags(evalOptions) {
1337
+ if (typeof evalOptions == "number") return evalOptions;
1338
+ if (evalOptions === void 0) return 0;
1339
+ let { type, strict, strip, compileOnly, backtraceBarrier } = evalOptions, flags = 0;
1340
+ return type === "global" && (flags |= EvalFlags.JS_EVAL_TYPE_GLOBAL), type === "module" && (flags |= EvalFlags.JS_EVAL_TYPE_MODULE), strict && (flags |= EvalFlags.JS_EVAL_FLAG_STRICT), strip && (flags |= EvalFlags.JS_EVAL_FLAG_STRIP), compileOnly && (flags |= EvalFlags.JS_EVAL_FLAG_COMPILE_ONLY), backtraceBarrier && (flags |= EvalFlags.JS_EVAL_FLAG_BACKTRACE_BARRIER), flags;
1341
+ }
1342
+ function getOwnPropertyNamesOptionsToFlags(options) {
1343
+ if (typeof options == "number") return options;
1344
+ if (options === void 0) return 0;
1345
+ let { strings: includeStrings, symbols: includeSymbols, quickjsPrivate: includePrivate, onlyEnumerable, numbers: includeNumbers, numbersAsStrings } = options, flags = 0;
1346
+ return includeStrings && (flags |= GetOwnPropertyNamesFlags.JS_GPN_STRING_MASK), includeSymbols && (flags |= GetOwnPropertyNamesFlags.JS_GPN_SYMBOL_MASK), includePrivate && (flags |= GetOwnPropertyNamesFlags.JS_GPN_PRIVATE_MASK), onlyEnumerable && (flags |= GetOwnPropertyNamesFlags.JS_GPN_ENUM_ONLY), includeNumbers && (flags |= GetOwnPropertyNamesFlags.QTS_GPN_NUMBER_MASK), numbersAsStrings && (flags |= GetOwnPropertyNamesFlags.QTS_STANDARD_COMPLIANT_NUMBER), flags;
1347
+ }
1348
+ function concat(...values) {
1349
+ let result = [];
1350
+ for (let value of values) value !== void 0 && (result = result.concat(value));
1351
+ return result;
1352
+ }
1353
+ var QuickJSIterator = class extends UsingDisposable {
1354
+ constructor(handle, context) {
1355
+ super();
1356
+ this.handle = handle;
1357
+ this.context = context;
1358
+ this._isDone = false;
1359
+ this.owner = context.runtime;
1360
+ }
1361
+ [Symbol.iterator]() {
1362
+ return this;
1363
+ }
1364
+ next(value) {
1365
+ if (!this.alive || this._isDone) return { done: true, value: void 0 };
1366
+ let nextMethod = this._next ?? (this._next = this.context.getProp(this.handle, "next"));
1367
+ return this.callIteratorMethod(nextMethod, value);
1368
+ }
1369
+ return(value) {
1370
+ if (!this.alive) return { done: true, value: void 0 };
1371
+ let returnMethod = this.context.getProp(this.handle, "return");
1372
+ if (returnMethod === this.context.undefined && value === void 0) return this.dispose(), { done: true, value: void 0 };
1373
+ let result = this.callIteratorMethod(returnMethod, value);
1374
+ return returnMethod.dispose(), this.dispose(), result;
1375
+ }
1376
+ throw(e) {
1377
+ if (!this.alive) return { done: true, value: void 0 };
1378
+ let errorHandle = e instanceof Lifetime ? e : this.context.newError(e), throwMethod = this.context.getProp(this.handle, "throw"), result = this.callIteratorMethod(throwMethod, e);
1379
+ return errorHandle.alive && errorHandle.dispose(), throwMethod.dispose(), this.dispose(), result;
1380
+ }
1381
+ get alive() {
1382
+ return this.handle.alive;
1383
+ }
1384
+ dispose() {
1385
+ this._isDone = true, this.handle.dispose(), this._next?.dispose();
1386
+ }
1387
+ callIteratorMethod(method, input) {
1388
+ let callResult = input ? this.context.callFunction(method, this.handle, input) : this.context.callFunction(method, this.handle);
1389
+ if (callResult.error) return this.dispose(), { value: callResult };
1390
+ let done = this.context.getProp(callResult.value, "done").consume((v) => this.context.dump(v)), value = this.context.getProp(callResult.value, "value");
1391
+ return callResult.value.dispose(), done && this.dispose(), { value: DisposableResult.success(value), done };
1392
+ }
1393
+ };
1394
+ var INT32_MIN = -2147483648, INT32_MAX = 2147483647, INVALID_HOST_REF_ID = 0;
1395
+ function getGroupId(id) {
1396
+ return id >> 8;
1397
+ }
1398
+ var HostRefMap = class {
1399
+ constructor() {
1400
+ this.nextId = INT32_MIN;
1401
+ this.freelist = [];
1402
+ this.groups = /* @__PURE__ */ new Map();
1403
+ }
1404
+ put(value) {
1405
+ let id = this.allocateId(), groupId = getGroupId(id), group = this.groups.get(groupId);
1406
+ return group || (group = /* @__PURE__ */ new Map(), this.groups.set(groupId, group)), group.set(id, value), id;
1407
+ }
1408
+ get(id) {
1409
+ if (id === INVALID_HOST_REF_ID) throw new QuickJSHostRefInvalid("no host reference id defined");
1410
+ let groupId = getGroupId(id), group = this.groups.get(groupId);
1411
+ if (!group) throw new QuickJSHostRefInvalid(`host reference id ${id} is not defined`);
1412
+ let value = group.get(id);
1413
+ if (!value) throw new QuickJSHostRefInvalid(`host reference id ${id} is not defined`);
1414
+ return value;
1415
+ }
1416
+ delete(id) {
1417
+ if (id === INVALID_HOST_REF_ID) throw new QuickJSHostRefInvalid("no host reference id defined");
1418
+ let groupId = getGroupId(id), group = this.groups.get(groupId);
1419
+ if (!group) throw new QuickJSHostRefInvalid(`host reference id ${id} is not defined`);
1420
+ group.delete(id), group.size === 0 && this.groups.delete(groupId), this.freelist.push(id);
1421
+ }
1422
+ allocateId() {
1423
+ if (this.freelist.length > 0) return this.freelist.shift();
1424
+ if (this.nextId === INVALID_HOST_REF_ID && this.nextId++, this.nextId > INT32_MAX) throw new QuickJSHostRefRangeExceeded(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${INT32_MAX - INT32_MIN}`);
1425
+ return this.nextId++;
1426
+ }
1427
+ }, HostRef = class extends UsingDisposable {
1428
+ constructor(runtime, handle, id) {
1429
+ if (id === INVALID_HOST_REF_ID) throw new QuickJSHostRefInvalid("cannot create HostRef with undefined id");
1430
+ super();
1431
+ this.runtime = runtime;
1432
+ this.handle = handle;
1433
+ this.id = id;
1434
+ }
1435
+ get alive() {
1436
+ return this.handle.alive;
1437
+ }
1438
+ dispose() {
1439
+ this.handle.dispose();
1440
+ }
1441
+ get value() {
1442
+ return this.runtime.hostRefs.get(this.id);
1443
+ }
1444
+ };
1445
+ var ContextMemory = class extends ModuleMemory {
1446
+ constructor(args) {
1447
+ super(args.module);
1448
+ this.scope = new Scope();
1449
+ this.copyJSValue = (ptr) => this.ffi.QTS_DupValuePointer(this.ctx.value, ptr);
1450
+ this.freeJSValue = (ptr) => {
1451
+ this.ffi.QTS_FreeValuePointer(this.ctx.value, ptr);
1452
+ };
1453
+ args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime)), this.owner = args.owner, this.module = args.module, this.ffi = args.ffi, this.rt = args.rt, this.ctx = this.scope.manage(args.ctx);
1454
+ }
1455
+ get alive() {
1456
+ return this.scope.alive;
1457
+ }
1458
+ dispose() {
1459
+ return this.scope.dispose();
1460
+ }
1461
+ [Symbol.dispose]() {
1462
+ return this.dispose();
1463
+ }
1464
+ manage(lifetime) {
1465
+ return this.scope.manage(lifetime);
1466
+ }
1467
+ consumeJSCharPointer(ptr) {
1468
+ let str = this.module.UTF8ToString(ptr);
1469
+ return this.ffi.QTS_FreeCString(this.ctx.value, ptr), str;
1470
+ }
1471
+ heapValueHandle(ptr, extraDispose) {
1472
+ let dispose = extraDispose ? (val) => {
1473
+ extraDispose(), this.freeJSValue(val);
1474
+ } : this.freeJSValue;
1475
+ return new Lifetime(ptr, this.copyJSValue, dispose, this.owner);
1476
+ }
1477
+ staticHeapValueHandle(ptr) {
1478
+ return this.manage(this.heapValueHandle(ptr)), new StaticLifetime(ptr, this.owner);
1479
+ }
1480
+ }, QuickJSContext = class extends UsingDisposable {
1481
+ constructor(args) {
1482
+ super();
1483
+ this._undefined = void 0;
1484
+ this._null = void 0;
1485
+ this._false = void 0;
1486
+ this._true = void 0;
1487
+ this._global = void 0;
1488
+ this._BigInt = void 0;
1489
+ this._Symbol = void 0;
1490
+ this._SymbolIterator = void 0;
1491
+ this._SymbolAsyncIterator = void 0;
1492
+ this.cToHostCallbacks = { callFunction: (ctx, this_ptr, argc, argv, fn_id) => {
1493
+ if (ctx !== this.ctx.value) throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");
1494
+ let fn = this.getFunction(fn_id);
1495
+ return Scope.withScopeMaybeAsync(this, function* (awaited, scope) {
1496
+ let thisHandle = scope.manage(new WeakLifetime(this_ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime)), argHandles = new Array(argc);
1497
+ for (let i = 0; i < argc; i++) {
1498
+ let ptr = this.ffi.QTS_ArgvGetJSValueConstPointer(argv, i);
1499
+ argHandles[i] = scope.manage(new WeakLifetime(ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime));
1500
+ }
1501
+ try {
1502
+ let result = yield* awaited(fn.apply(thisHandle, argHandles));
1503
+ if (result) {
1504
+ if ("error" in result && result.error) throw this.runtime.debugLog("throw error", result.error), result.error;
1505
+ let handle = scope.manage(result instanceof Lifetime ? result : result.value);
1506
+ return this.ffi.QTS_DupValuePointer(this.ctx.value, handle.value);
1507
+ }
1508
+ return 0;
1509
+ } catch (error) {
1510
+ return this.errorToHandle(error).consume((errorHandle) => this.ffi.QTS_Throw(this.ctx.value, errorHandle.value));
1511
+ }
1512
+ });
1513
+ } };
1514
+ this.runtime = args.runtime, this.module = args.module, this.ffi = args.ffi, this.rt = args.rt, this.ctx = args.ctx, this.memory = new ContextMemory({ ...args, owner: this.runtime }), args.callbacks.setContextCallbacks(this.ctx.value, this.cToHostCallbacks), this.dump = this.dump.bind(this), this.getString = this.getString.bind(this), this.getNumber = this.getNumber.bind(this), this.resolvePromise = this.resolvePromise.bind(this), this.uint32Out = this.memory.manage(this.memory.newTypedArray(Uint32Array, 1));
1515
+ }
1516
+ get alive() {
1517
+ return this.memory.alive;
1518
+ }
1519
+ dispose() {
1520
+ this.memory.dispose();
1521
+ }
1522
+ get undefined() {
1523
+ if (this._undefined) return this._undefined;
1524
+ let ptr = this.ffi.QTS_GetUndefined();
1525
+ return this._undefined = new StaticLifetime(ptr);
1526
+ }
1527
+ get null() {
1528
+ if (this._null) return this._null;
1529
+ let ptr = this.ffi.QTS_GetNull();
1530
+ return this._null = new StaticLifetime(ptr);
1531
+ }
1532
+ get true() {
1533
+ if (this._true) return this._true;
1534
+ let ptr = this.ffi.QTS_GetTrue();
1535
+ return this._true = new StaticLifetime(ptr);
1536
+ }
1537
+ get false() {
1538
+ if (this._false) return this._false;
1539
+ let ptr = this.ffi.QTS_GetFalse();
1540
+ return this._false = new StaticLifetime(ptr);
1541
+ }
1542
+ get global() {
1543
+ if (this._global) return this._global;
1544
+ let ptr = this.ffi.QTS_GetGlobalObject(this.ctx.value);
1545
+ return this._global = this.memory.staticHeapValueHandle(ptr), this._global;
1546
+ }
1547
+ newNumber(num) {
1548
+ return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value, num));
1549
+ }
1550
+ newString(str) {
1551
+ let ptr = this.memory.newHeapCharPointer(str).consume((charHandle) => this.ffi.QTS_NewString(this.ctx.value, charHandle.value.ptr));
1552
+ return this.memory.heapValueHandle(ptr);
1553
+ }
1554
+ newUniqueSymbol(description) {
1555
+ let key = (typeof description == "symbol" ? description.description : description) ?? "", ptr = this.memory.newHeapCharPointer(key).consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value.ptr, 0));
1556
+ return this.memory.heapValueHandle(ptr);
1557
+ }
1558
+ newSymbolFor(key) {
1559
+ let description = (typeof key == "symbol" ? key.description : key) ?? "", ptr = this.memory.newHeapCharPointer(description).consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value.ptr, 1));
1560
+ return this.memory.heapValueHandle(ptr);
1561
+ }
1562
+ getWellKnownSymbol(name) {
1563
+ return this._Symbol ?? (this._Symbol = this.memory.manage(this.getProp(this.global, "Symbol"))), this.getProp(this._Symbol, name);
1564
+ }
1565
+ newBigInt(num) {
1566
+ if (!this._BigInt) {
1567
+ let bigIntHandle2 = this.getProp(this.global, "BigInt");
1568
+ this.memory.manage(bigIntHandle2), this._BigInt = new StaticLifetime(bigIntHandle2.value, this.runtime);
1569
+ }
1570
+ let bigIntHandle = this._BigInt, asString = String(num);
1571
+ return this.newString(asString).consume((handle) => this.unwrapResult(this.callFunction(bigIntHandle, this.undefined, handle)));
1572
+ }
1573
+ newObject(prototype) {
1574
+ prototype && this.runtime.assertOwned(prototype);
1575
+ let ptr = prototype ? this.ffi.QTS_NewObjectProto(this.ctx.value, prototype.value) : this.ffi.QTS_NewObject(this.ctx.value);
1576
+ return this.memory.heapValueHandle(ptr);
1577
+ }
1578
+ newArray() {
1579
+ let ptr = this.ffi.QTS_NewArray(this.ctx.value);
1580
+ return this.memory.heapValueHandle(ptr);
1581
+ }
1582
+ newArrayBuffer(buffer) {
1583
+ let array = new Uint8Array(buffer), handle = this.memory.newHeapBufferPointer(array), ptr = this.ffi.QTS_NewArrayBuffer(this.ctx.value, handle.value.pointer, array.length);
1584
+ return this.memory.heapValueHandle(ptr);
1585
+ }
1586
+ newPromise(value) {
1587
+ let deferredPromise = Scope.withScope((scope) => {
1588
+ let mutablePointerArray = scope.manage(this.memory.newMutablePointerArray(2)), promisePtr = this.ffi.QTS_NewPromiseCapability(this.ctx.value, mutablePointerArray.value.ptr), promiseHandle = this.memory.heapValueHandle(promisePtr), [resolveHandle, rejectHandle] = Array.from(mutablePointerArray.value.typedArray).map((jsvaluePtr) => this.memory.heapValueHandle(jsvaluePtr));
1589
+ return new QuickJSDeferredPromise({ context: this, promiseHandle, resolveHandle, rejectHandle });
1590
+ });
1591
+ return value && typeof value == "function" && (value = new Promise(value)), value && Promise.resolve(value).then(deferredPromise.resolve, (error) => error instanceof Lifetime ? deferredPromise.reject(error) : this.newError(error).consume(deferredPromise.reject)), deferredPromise;
1592
+ }
1593
+ newFunction(nameOrFn, maybeFn) {
1594
+ let fn = typeof nameOrFn == "function" ? nameOrFn : maybeFn;
1595
+ if (!fn) throw new TypeError("Expected a function");
1596
+ return this.newFunctionWithOptions({ name: typeof nameOrFn == "string" ? nameOrFn : void 0, length: fn.length, isConstructor: false, fn });
1597
+ }
1598
+ newConstructorFunction(nameOrFn, maybeFn) {
1599
+ let fn = typeof nameOrFn == "function" ? nameOrFn : maybeFn;
1600
+ if (!fn) throw new TypeError("Expected a function");
1601
+ return this.newFunctionWithOptions({ name: typeof nameOrFn == "string" ? nameOrFn : void 0, length: fn.length, isConstructor: true, fn });
1602
+ }
1603
+ newFunctionWithOptions(args) {
1604
+ let { name, length, isConstructor, fn } = args, refId = this.runtime.hostRefs.put(fn);
1605
+ try {
1606
+ return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value, name ?? "", length, isConstructor, refId));
1607
+ } catch (error) {
1608
+ throw this.runtime.hostRefs.delete(refId), error;
1609
+ }
1610
+ }
1611
+ newError(error) {
1612
+ let errorHandle = this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));
1613
+ return error && typeof error == "object" ? (error.name !== void 0 && this.newString(error.name).consume((handle) => this.setProp(errorHandle, "name", handle)), error.message !== void 0 && this.newString(error.message).consume((handle) => this.setProp(errorHandle, "message", handle))) : typeof error == "string" ? this.newString(error).consume((handle) => this.setProp(errorHandle, "message", handle)) : error !== void 0 && this.newString(String(error)).consume((handle) => this.setProp(errorHandle, "message", handle)), errorHandle;
1614
+ }
1615
+ newHostRef(value) {
1616
+ let id = this.runtime.hostRefs.put(value);
1617
+ try {
1618
+ let handle = this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value, id));
1619
+ return new HostRef(this.runtime, handle, id);
1620
+ } catch (error) {
1621
+ throw this.runtime.hostRefs.delete(id), error;
1622
+ }
1623
+ }
1624
+ toHostRef(handle) {
1625
+ let id = this.ffi.QTS_GetHostRefId(handle.value);
1626
+ if (id !== 0) return this.runtime.hostRefs.get(id), new HostRef(this.runtime, handle.dup(), id);
1627
+ }
1628
+ unwrapHostRef(handle) {
1629
+ let id = this.ffi.QTS_GetHostRefId(handle.value);
1630
+ if (id === 0) throw new QuickJSHostRefInvalid("handle is not a HostRef");
1631
+ return this.runtime.hostRefs.get(id);
1632
+ }
1633
+ typeof(handle) {
1634
+ return this.runtime.assertOwned(handle), this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value, handle.value));
1635
+ }
1636
+ getNumber(handle) {
1637
+ return this.runtime.assertOwned(handle), this.ffi.QTS_GetFloat64(this.ctx.value, handle.value);
1638
+ }
1639
+ getString(handle) {
1640
+ return this.runtime.assertOwned(handle), this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value, handle.value));
1641
+ }
1642
+ getSymbol(handle) {
1643
+ this.runtime.assertOwned(handle);
1644
+ let key = this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value, handle.value));
1645
+ return this.ffi.QTS_IsGlobalSymbol(this.ctx.value, handle.value) ? Symbol.for(key) : Symbol(key);
1646
+ }
1647
+ getBigInt(handle) {
1648
+ this.runtime.assertOwned(handle);
1649
+ let asString = this.getString(handle);
1650
+ return BigInt(asString);
1651
+ }
1652
+ getArrayBuffer(handle) {
1653
+ this.runtime.assertOwned(handle);
1654
+ let len = this.ffi.QTS_GetArrayBufferLength(this.ctx.value, handle.value), ptr = this.ffi.QTS_GetArrayBuffer(this.ctx.value, handle.value);
1655
+ if (!ptr) throw new Error("Couldn't allocate memory to get ArrayBuffer");
1656
+ return new Lifetime(this.module.HEAPU8.subarray(ptr, ptr + len), void 0, () => this.module._free(ptr));
1657
+ }
1658
+ getPromiseState(handle) {
1659
+ this.runtime.assertOwned(handle);
1660
+ let state = this.ffi.QTS_PromiseState(this.ctx.value, handle.value);
1661
+ if (state < 0) return { type: "fulfilled", value: handle, notAPromise: true };
1662
+ if (state === JSPromiseStateEnum.Pending) return { type: "pending", get error() {
1663
+ return new QuickJSPromisePending("Cannot unwrap a pending promise");
1664
+ } };
1665
+ let ptr = this.ffi.QTS_PromiseResult(this.ctx.value, handle.value), result = this.memory.heapValueHandle(ptr);
1666
+ if (state === JSPromiseStateEnum.Fulfilled) return { type: "fulfilled", value: result };
1667
+ if (state === JSPromiseStateEnum.Rejected) return { type: "rejected", error: result };
1668
+ throw result.dispose(), new Error(`Unknown JSPromiseStateEnum: ${state}`);
1669
+ }
1670
+ resolvePromise(promiseLikeHandle) {
1671
+ this.runtime.assertOwned(promiseLikeHandle);
1672
+ let vmResolveResult = Scope.withScope((scope) => {
1673
+ let vmPromise = scope.manage(this.getProp(this.global, "Promise")), vmPromiseResolve = scope.manage(this.getProp(vmPromise, "resolve"));
1674
+ return this.callFunction(vmPromiseResolve, vmPromise, promiseLikeHandle);
1675
+ });
1676
+ return vmResolveResult.error ? Promise.resolve(vmResolveResult) : new Promise((resolve2) => {
1677
+ Scope.withScope((scope) => {
1678
+ let resolveHandle = scope.manage(this.newFunction("resolve", (value) => {
1679
+ resolve2(this.success(value && value.dup()));
1680
+ })), rejectHandle = scope.manage(this.newFunction("reject", (error) => {
1681
+ resolve2(this.fail(error && error.dup()));
1682
+ })), promiseHandle = scope.manage(vmResolveResult.value), promiseThenHandle = scope.manage(this.getProp(promiseHandle, "then"));
1683
+ this.callFunction(promiseThenHandle, promiseHandle, resolveHandle, rejectHandle).unwrap().dispose();
1684
+ });
1685
+ });
1686
+ }
1687
+ isEqual(a, b, equalityType = IsEqualOp.IsStrictlyEqual) {
1688
+ if (a === b) return true;
1689
+ this.runtime.assertOwned(a), this.runtime.assertOwned(b);
1690
+ let result = this.ffi.QTS_IsEqual(this.ctx.value, a.value, b.value, equalityType);
1691
+ if (result === -1) throw new QuickJSNotImplemented("WASM variant does not expose equality");
1692
+ return !!result;
1693
+ }
1694
+ eq(handle, other) {
1695
+ return this.isEqual(handle, other, IsEqualOp.IsStrictlyEqual);
1696
+ }
1697
+ sameValue(handle, other) {
1698
+ return this.isEqual(handle, other, IsEqualOp.IsSameValue);
1699
+ }
1700
+ sameValueZero(handle, other) {
1701
+ return this.isEqual(handle, other, IsEqualOp.IsSameValueZero);
1702
+ }
1703
+ getProp(handle, key) {
1704
+ this.runtime.assertOwned(handle);
1705
+ let ptr;
1706
+ return typeof key == "number" && key >= 0 ? ptr = this.ffi.QTS_GetPropNumber(this.ctx.value, handle.value, key) : ptr = this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_GetProp(this.ctx.value, handle.value, quickJSKey.value)), this.memory.heapValueHandle(ptr);
1707
+ }
1708
+ getLength(handle) {
1709
+ if (this.runtime.assertOwned(handle), !(this.ffi.QTS_GetLength(this.ctx.value, this.uint32Out.value.ptr, handle.value) < 0)) return this.uint32Out.value.typedArray[0];
1710
+ }
1711
+ getOwnPropertyNames(handle, options = { strings: true, numbersAsStrings: true }) {
1712
+ this.runtime.assertOwned(handle), handle.value;
1713
+ let flags = getOwnPropertyNamesOptionsToFlags(options);
1714
+ if (flags === 0) throw new QuickJSEmptyGetOwnPropertyNames("No options set, will return an empty array");
1715
+ return Scope.withScope((scope) => {
1716
+ let outPtr = scope.manage(this.memory.newMutablePointerArray(1)), errorPtr = this.ffi.QTS_GetOwnPropertyNames(this.ctx.value, outPtr.value.ptr, this.uint32Out.value.ptr, handle.value, flags);
1717
+ if (errorPtr) return this.fail(this.memory.heapValueHandle(errorPtr));
1718
+ let len = this.uint32Out.value.typedArray[0], ptr = outPtr.value.typedArray[0], pointerArray = new Uint32Array(this.module.HEAP8.buffer, ptr, len), handles = Array.from(pointerArray).map((ptr2) => this.memory.heapValueHandle(ptr2));
1719
+ return this.ffi.QTS_FreeVoidPointer(this.ctx.value, ptr), this.success(createDisposableArray(handles));
1720
+ });
1721
+ }
1722
+ getIterator(iterableHandle) {
1723
+ let SymbolIterator = this._SymbolIterator ?? (this._SymbolIterator = this.memory.manage(this.getWellKnownSymbol("iterator")));
1724
+ return Scope.withScope((scope) => {
1725
+ let methodHandle = scope.manage(this.getProp(iterableHandle, SymbolIterator)), iteratorCallResult = this.callFunction(methodHandle, iterableHandle);
1726
+ return iteratorCallResult.error ? iteratorCallResult : this.success(new QuickJSIterator(iteratorCallResult.value, this));
1727
+ });
1728
+ }
1729
+ setProp(handle, key, value) {
1730
+ this.runtime.assertOwned(handle), this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_SetProp(this.ctx.value, handle.value, quickJSKey.value, value.value));
1731
+ }
1732
+ defineProp(handle, key, descriptor) {
1733
+ this.runtime.assertOwned(handle), Scope.withScope((scope) => {
1734
+ let quickJSKey = scope.manage(this.borrowPropertyKey(key)), value = descriptor.value || this.undefined, configurable = !!descriptor.configurable, enumerable = !!descriptor.enumerable, hasValue = !!descriptor.value, get = descriptor.get ? scope.manage(this.newFunction(descriptor.get.name, descriptor.get)) : this.undefined, set = descriptor.set ? scope.manage(this.newFunction(descriptor.set.name, descriptor.set)) : this.undefined;
1735
+ this.ffi.QTS_DefineProp(this.ctx.value, handle.value, quickJSKey.value, value.value, get.value, set.value, configurable, enumerable, hasValue);
1736
+ });
1737
+ }
1738
+ callFunction(func, thisVal, ...restArgs) {
1739
+ this.runtime.assertOwned(func);
1740
+ let args, firstArg = restArgs[0];
1741
+ firstArg === void 0 || Array.isArray(firstArg) ? args = firstArg ?? [] : args = restArgs;
1742
+ let resultPtr = this.memory.toPointerArray(args).consume((argsArrayPtr) => this.ffi.QTS_Call(this.ctx.value, func.value, thisVal.value, args.length, argsArrayPtr.value)), errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
1743
+ return errorPtr ? (this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr), this.fail(this.memory.heapValueHandle(errorPtr))) : this.success(this.memory.heapValueHandle(resultPtr));
1744
+ }
1745
+ callMethod(thisHandle, key, args = []) {
1746
+ return this.getProp(thisHandle, key).consume((func) => this.callFunction(func, thisHandle, args));
1747
+ }
1748
+ evalCode(code, filename = "eval.js", options) {
1749
+ let detectModule = options === void 0 ? 1 : 0, flags = evalOptionsToFlags(options), resultPtr = this.memory.newHeapCharPointer(code).consume((charHandle) => this.ffi.QTS_Eval(this.ctx.value, charHandle.value.ptr, charHandle.value.strlen, filename, detectModule, flags)), errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
1750
+ return errorPtr ? (this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr), this.fail(this.memory.heapValueHandle(errorPtr))) : this.success(this.memory.heapValueHandle(resultPtr));
1751
+ }
1752
+ throw(error) {
1753
+ return this.errorToHandle(error).consume((handle) => this.ffi.QTS_Throw(this.ctx.value, handle.value));
1754
+ }
1755
+ borrowPropertyKey(key) {
1756
+ return typeof key == "number" ? this.newNumber(key) : typeof key == "string" ? this.newString(key) : new StaticLifetime(key.value, this.runtime);
1757
+ }
1758
+ getMemory(rt) {
1759
+ if (rt === this.rt.value) return this.memory;
1760
+ throw new Error("Private API. Cannot get memory from a different runtime");
1761
+ }
1762
+ dump(handle) {
1763
+ this.runtime.assertOwned(handle);
1764
+ let type = this.typeof(handle);
1765
+ if (type === "string") return this.getString(handle);
1766
+ if (type === "number") return this.getNumber(handle);
1767
+ if (type === "bigint") return this.getBigInt(handle);
1768
+ if (type === "undefined") return;
1769
+ if (type === "symbol") return this.getSymbol(handle);
1770
+ let asPromiseState = this.getPromiseState(handle);
1771
+ if (asPromiseState.type === "fulfilled" && !asPromiseState.notAPromise) return handle.dispose(), { type: asPromiseState.type, value: asPromiseState.value.consume(this.dump) };
1772
+ if (asPromiseState.type === "pending") return handle.dispose(), { type: asPromiseState.type };
1773
+ if (asPromiseState.type === "rejected") return handle.dispose(), { type: asPromiseState.type, error: asPromiseState.error.consume(this.dump) };
1774
+ let str = this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value, handle.value));
1775
+ try {
1776
+ return JSON.parse(str);
1777
+ } catch {
1778
+ return str;
1779
+ }
1780
+ }
1781
+ unwrapResult(result) {
1782
+ if (result.error) {
1783
+ let context = "context" in result.error ? result.error.context : this, cause = result.error.consume((error) => this.dump(error));
1784
+ if (cause && typeof cause == "object" && typeof cause.message == "string") {
1785
+ let { message, name, stack, ...rest } = cause, exception = new QuickJSUnwrapError(cause, context);
1786
+ typeof name == "string" && (exception.name = cause.name), exception.message = message;
1787
+ let hostStack = exception.stack;
1788
+ throw typeof stack == "string" && (exception.stack = `${name}: ${message}
1789
+ ${cause.stack}Host: ${hostStack}`), Object.assign(exception, rest), exception;
1790
+ }
1791
+ throw new QuickJSUnwrapError(cause);
1792
+ }
1793
+ return result.value;
1794
+ }
1795
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1796
+ return this.alive ? `${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }` : `${this.constructor.name} { disposed }`;
1797
+ }
1798
+ getFunction(fn_id) {
1799
+ let fn = this.runtime.hostRefs.get(fn_id);
1800
+ if (typeof fn != "function") throw new Error(`Host reference ${fn_id} is not a function`);
1801
+ return fn;
1802
+ }
1803
+ errorToHandle(error) {
1804
+ return error instanceof Lifetime ? error : this.newError(error);
1805
+ }
1806
+ encodeBinaryJSON(handle) {
1807
+ let ptr = this.ffi.QTS_bjson_encode(this.ctx.value, handle.value);
1808
+ return this.memory.heapValueHandle(ptr);
1809
+ }
1810
+ decodeBinaryJSON(handle) {
1811
+ let ptr = this.ffi.QTS_bjson_decode(this.ctx.value, handle.value);
1812
+ return this.memory.heapValueHandle(ptr);
1813
+ }
1814
+ success(value) {
1815
+ return DisposableResult.success(value);
1816
+ }
1817
+ fail(error) {
1818
+ return DisposableResult.fail(error, (error2) => this.unwrapResult(error2));
1819
+ }
1820
+ };
1821
+ var QuickJSRuntime = class extends UsingDisposable {
1822
+ constructor(args) {
1823
+ super();
1824
+ this.scope = new Scope();
1825
+ this.contextMap = /* @__PURE__ */ new Map();
1826
+ this.hostRefs = new HostRefMap();
1827
+ this._debugMode = false;
1828
+ this.cToHostCallbacks = { freeHostRef: (rt, host_ref_id) => {
1829
+ if (rt !== this.rt.value) throw new Error("Runtime pointer mismatch");
1830
+ this.hostRefs.delete(host_ref_id);
1831
+ }, shouldInterrupt: (rt) => {
1832
+ if (rt !== this.rt.value) throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");
1833
+ let fn = this.interruptHandler;
1834
+ if (!fn) throw new Error("QuickJSContext had no interrupt handler");
1835
+ return fn(this) ? 1 : 0;
1836
+ }, loadModuleSource: maybeAsyncFn(this, function* (awaited, rt, ctx, moduleName) {
1837
+ let moduleLoader = this.moduleLoader;
1838
+ if (!moduleLoader) throw new Error("Runtime has no module loader");
1839
+ if (rt !== this.rt.value) throw new Error("Runtime pointer mismatch");
1840
+ let context = this.contextMap.get(ctx) ?? this.newContext({ contextPointer: ctx });
1841
+ try {
1842
+ let result = yield* awaited(moduleLoader(moduleName, context));
1843
+ if (typeof result == "object" && "error" in result && result.error) throw this.debugLog("cToHostLoadModule: loader returned error", result.error), result.error;
1844
+ let moduleSource = typeof result == "string" ? result : "value" in result ? result.value : result;
1845
+ return this.memory.newHeapCharPointer(moduleSource).value.ptr;
1846
+ } catch (error) {
1847
+ return this.debugLog("cToHostLoadModule: caught error", error), context.throw(error), 0;
1848
+ }
1849
+ }), normalizeModule: maybeAsyncFn(this, function* (awaited, rt, ctx, baseModuleName, moduleNameRequest) {
1850
+ let moduleNormalizer = this.moduleNormalizer;
1851
+ if (!moduleNormalizer) throw new Error("Runtime has no module normalizer");
1852
+ if (rt !== this.rt.value) throw new Error("Runtime pointer mismatch");
1853
+ let context = this.contextMap.get(ctx) ?? this.newContext({ contextPointer: ctx });
1854
+ try {
1855
+ let result = yield* awaited(moduleNormalizer(baseModuleName, moduleNameRequest, context));
1856
+ if (typeof result == "object" && "error" in result && result.error) throw this.debugLog("cToHostNormalizeModule: normalizer returned error", result.error), result.error;
1857
+ let name = typeof result == "string" ? result : result.value;
1858
+ return context.getMemory(this.rt.value).newHeapCharPointer(name).value.ptr;
1859
+ } catch (error) {
1860
+ return this.debugLog("normalizeModule: caught error", error), context.throw(error), 0;
1861
+ }
1862
+ }) };
1863
+ args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime)), this.module = args.module, this.memory = new ModuleMemory(this.module), this.ffi = args.ffi, this.rt = args.rt, this.callbacks = args.callbacks, this.scope.manage(this.rt), this.callbacks.setRuntimeCallbacks(this.rt.value, this.cToHostCallbacks), this.executePendingJobs = this.executePendingJobs.bind(this);
1864
+ }
1865
+ get alive() {
1866
+ return this.scope.alive;
1867
+ }
1868
+ dispose() {
1869
+ return this.scope.dispose();
1870
+ }
1871
+ newContext(options = {}) {
1872
+ let intrinsics = intrinsicsToFlags(options.intrinsics), ctx = new Lifetime(options.contextPointer || this.ffi.QTS_NewContext(this.rt.value, intrinsics), void 0, (ctx_ptr) => {
1873
+ this.contextMap.delete(ctx_ptr), this.callbacks.deleteContext(ctx_ptr), this.ffi.QTS_FreeContext(ctx_ptr);
1874
+ }), context = new QuickJSContext({ module: this.module, ctx, ffi: this.ffi, rt: this.rt, ownedLifetimes: options.ownedLifetimes, runtime: this, callbacks: this.callbacks });
1875
+ return this.contextMap.set(ctx.value, context), context;
1876
+ }
1877
+ setModuleLoader(moduleLoader, moduleNormalizer) {
1878
+ this.moduleLoader = moduleLoader, this.moduleNormalizer = moduleNormalizer, this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value, this.moduleNormalizer ? 1 : 0);
1879
+ }
1880
+ removeModuleLoader() {
1881
+ this.moduleLoader = void 0, this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value);
1882
+ }
1883
+ hasPendingJob() {
1884
+ return !!this.ffi.QTS_IsJobPending(this.rt.value);
1885
+ }
1886
+ setInterruptHandler(cb) {
1887
+ let prevInterruptHandler = this.interruptHandler;
1888
+ this.interruptHandler = cb, prevInterruptHandler || this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value);
1889
+ }
1890
+ removeInterruptHandler() {
1891
+ this.interruptHandler && (this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value), this.interruptHandler = void 0);
1892
+ }
1893
+ executePendingJobs(maxJobsToExecute = -1) {
1894
+ let ctxPtrOut = this.memory.newMutablePointerArray(1), valuePtr = this.ffi.QTS_ExecutePendingJob(this.rt.value, maxJobsToExecute ?? -1, ctxPtrOut.value.ptr), ctxPtr = ctxPtrOut.value.typedArray[0];
1895
+ if (ctxPtrOut.dispose(), ctxPtr === 0) return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value, valuePtr), DisposableResult.success(0);
1896
+ let context = this.contextMap.get(ctxPtr) ?? this.newContext({ contextPointer: ctxPtr }), resultValue = context.getMemory(this.rt.value).heapValueHandle(valuePtr);
1897
+ if (context.typeof(resultValue) === "number") {
1898
+ let executedJobs = context.getNumber(resultValue);
1899
+ return resultValue.dispose(), DisposableResult.success(executedJobs);
1900
+ } else {
1901
+ let error = Object.assign(resultValue, { context });
1902
+ return DisposableResult.fail(error, (error2) => context.unwrapResult(error2));
1903
+ }
1904
+ }
1905
+ setMemoryLimit(limitBytes) {
1906
+ if (limitBytes < 0 && limitBytes !== -1) throw new Error("Cannot set memory limit to negative number. To unset, pass -1");
1907
+ this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value, limitBytes);
1908
+ }
1909
+ computeMemoryUsage() {
1910
+ let serviceContextMemory = this.getSystemContext().getMemory(this.rt.value);
1911
+ return serviceContextMemory.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value, serviceContextMemory.ctx.value));
1912
+ }
1913
+ dumpMemoryUsage() {
1914
+ return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value));
1915
+ }
1916
+ setMaxStackSize(stackSize) {
1917
+ if (stackSize < 0) throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");
1918
+ this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value, stackSize);
1919
+ }
1920
+ assertOwned(handle) {
1921
+ if (handle.owner && handle.owner.rt !== this.rt) throw new QuickJSWrongOwner(`Handle is not owned by this runtime: ${handle.owner.rt.value} != ${this.rt.value}`);
1922
+ }
1923
+ setDebugMode(enabled) {
1924
+ this._debugMode = enabled, this.ffi.DEBUG && this.rt.alive && this.ffi.QTS_SetDebugLogEnabled(this.rt.value, enabled ? 1 : 0);
1925
+ }
1926
+ isDebugMode() {
1927
+ return this._debugMode;
1928
+ }
1929
+ debugLog(...msg) {
1930
+ this._debugMode && console.log("quickjs-emscripten:", ...msg);
1931
+ }
1932
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1933
+ return this.alive ? `${this.constructor.name} { rt: ${this.rt.value} }` : `${this.constructor.name} { disposed }`;
1934
+ }
1935
+ getSystemContext() {
1936
+ return this.context || (this.context = this.scope.manage(this.newContext())), this.context;
1937
+ }
1938
+ };
1939
+ var QuickJSEmscriptenModuleCallbacks = class {
1940
+ constructor(args) {
1941
+ this.freeHostRef = args.freeHostRef, this.callFunction = args.callFunction, this.shouldInterrupt = args.shouldInterrupt, this.loadModuleSource = args.loadModuleSource, this.normalizeModule = args.normalizeModule;
1942
+ }
1943
+ }, QuickJSModuleCallbacks = class {
1944
+ constructor(module) {
1945
+ this.contextCallbacks = /* @__PURE__ */ new Map();
1946
+ this.runtimeCallbacks = /* @__PURE__ */ new Map();
1947
+ this.suspendedCount = 0;
1948
+ this.cToHostCallbacks = new QuickJSEmscriptenModuleCallbacks({ freeHostRef: (_asyncify, rt, host_ref_id) => {
1949
+ let runtimeCallbacks = this.runtimeCallbacks.get(rt);
1950
+ if (!runtimeCallbacks) throw new Error(`QuickJSRuntime(rt = ${rt}) not found when trying to free HostRef(id = ${host_ref_id})`);
1951
+ runtimeCallbacks.freeHostRef(rt, host_ref_id);
1952
+ }, callFunction: (asyncify, ctx, this_ptr, argc, argv, fn_id) => this.handleAsyncify(asyncify, () => {
1953
+ try {
1954
+ let vm = this.contextCallbacks.get(ctx);
1955
+ if (!vm) throw new Error(`QuickJSContext(ctx = ${ctx}) not found for C function call "${fn_id}"`);
1956
+ return vm.callFunction(ctx, this_ptr, argc, argv, fn_id);
1957
+ } catch (error) {
1958
+ return console.error("[C to host error: returning null]", error), 0;
1959
+ }
1960
+ }), shouldInterrupt: (asyncify, rt) => this.handleAsyncify(asyncify, () => {
1961
+ try {
1962
+ let vm = this.runtimeCallbacks.get(rt);
1963
+ if (!vm) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C interrupt`);
1964
+ return vm.shouldInterrupt(rt);
1965
+ } catch (error) {
1966
+ return console.error("[C to host interrupt: returning error]", error), 1;
1967
+ }
1968
+ }), loadModuleSource: (asyncify, rt, ctx, moduleName) => this.handleAsyncify(asyncify, () => {
1969
+ try {
1970
+ let runtimeCallbacks = this.runtimeCallbacks.get(rt);
1971
+ if (!runtimeCallbacks) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
1972
+ let loadModule = runtimeCallbacks.loadModuleSource;
1973
+ if (!loadModule) throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
1974
+ return loadModule(rt, ctx, moduleName);
1975
+ } catch (error) {
1976
+ return console.error("[C to host module loader error: returning null]", error), 0;
1977
+ }
1978
+ }), normalizeModule: (asyncify, rt, ctx, moduleBaseName, moduleName) => this.handleAsyncify(asyncify, () => {
1979
+ try {
1980
+ let runtimeCallbacks = this.runtimeCallbacks.get(rt);
1981
+ if (!runtimeCallbacks) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
1982
+ let normalizeModule = runtimeCallbacks.normalizeModule;
1983
+ if (!normalizeModule) throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
1984
+ return normalizeModule(rt, ctx, moduleBaseName, moduleName);
1985
+ } catch (error) {
1986
+ return console.error("[C to host module loader error: returning null]", error), 0;
1987
+ }
1988
+ }) });
1989
+ this.module = module, this.module.callbacks = this.cToHostCallbacks;
1990
+ }
1991
+ setRuntimeCallbacks(rt, callbacks) {
1992
+ this.runtimeCallbacks.set(rt, callbacks);
1993
+ }
1994
+ deleteRuntime(rt) {
1995
+ this.runtimeCallbacks.delete(rt);
1996
+ }
1997
+ setContextCallbacks(ctx, callbacks) {
1998
+ this.contextCallbacks.set(ctx, callbacks);
1999
+ }
2000
+ deleteContext(ctx) {
2001
+ this.contextCallbacks.delete(ctx);
2002
+ }
2003
+ handleAsyncify(asyncify, fn) {
2004
+ if (asyncify) return asyncify.handleSleep((done) => {
2005
+ try {
2006
+ let result = fn();
2007
+ if (!(result instanceof Promise)) {
2008
+ debugLog("asyncify.handleSleep: not suspending:", result), done(result);
2009
+ return;
2010
+ }
2011
+ if (this.suspended) throw new QuickJSAsyncifyError(`Already suspended at: ${this.suspended.stack}
2012
+ Attempted to suspend at:`);
2013
+ this.suspended = new QuickJSAsyncifySuspended(`(${this.suspendedCount++})`), debugLog("asyncify.handleSleep: suspending:", this.suspended), result.then((resolvedResult) => {
2014
+ this.suspended = void 0, debugLog("asyncify.handleSleep: resolved:", resolvedResult), done(resolvedResult);
2015
+ }, (error) => {
2016
+ debugLog("asyncify.handleSleep: rejected:", error), console.error("QuickJS: cannot handle error in suspended function", error), this.suspended = void 0;
2017
+ });
2018
+ } catch (error) {
2019
+ throw this.suspended = void 0, error;
2020
+ }
2021
+ });
2022
+ let value = fn();
2023
+ if (value instanceof Promise) throw new Error("Promise return value not supported in non-asyncify context.");
2024
+ return value;
2025
+ }
2026
+ };
2027
+ function applyBaseRuntimeOptions(runtime, options) {
2028
+ options.interruptHandler && runtime.setInterruptHandler(options.interruptHandler), options.maxStackSizeBytes !== void 0 && runtime.setMaxStackSize(options.maxStackSizeBytes), options.memoryLimitBytes !== void 0 && runtime.setMemoryLimit(options.memoryLimitBytes);
2029
+ }
2030
+ function applyModuleEvalRuntimeOptions(runtime, options) {
2031
+ options.moduleLoader && runtime.setModuleLoader(options.moduleLoader), options.shouldInterrupt && runtime.setInterruptHandler(options.shouldInterrupt), options.memoryLimitBytes !== void 0 && runtime.setMemoryLimit(options.memoryLimitBytes), options.maxStackSizeBytes !== void 0 && runtime.setMaxStackSize(options.maxStackSizeBytes);
2032
+ }
2033
+ var QuickJSWASMModule = class {
2034
+ constructor(module, ffi2) {
2035
+ this.module = module, this.ffi = ffi2, this.callbacks = new QuickJSModuleCallbacks(module);
2036
+ }
2037
+ newRuntime(options = {}) {
2038
+ let rt = new Lifetime(this.ffi.QTS_NewRuntime(), void 0, (rt_ptr) => {
2039
+ this.ffi.QTS_FreeRuntime(rt_ptr), this.callbacks.deleteRuntime(rt_ptr);
2040
+ }), runtime = new QuickJSRuntime({ module: this.module, callbacks: this.callbacks, ffi: this.ffi, rt });
2041
+ return applyBaseRuntimeOptions(runtime, options), options.moduleLoader && runtime.setModuleLoader(options.moduleLoader), runtime;
2042
+ }
2043
+ newContext(options = {}) {
2044
+ let runtime = this.newRuntime(), context = runtime.newContext({ ...options, ownedLifetimes: concat(runtime, options.ownedLifetimes) });
2045
+ return runtime.context = context, context;
2046
+ }
2047
+ evalCode(code, options = {}) {
2048
+ return Scope.withScope((scope) => {
2049
+ let vm = scope.manage(this.newContext());
2050
+ applyModuleEvalRuntimeOptions(vm.runtime, options);
2051
+ let result = vm.evalCode(code, "eval.js");
2052
+ if (options.memoryLimitBytes !== void 0 && vm.runtime.setMemoryLimit(-1), result.error) throw vm.dump(scope.manage(result.error));
2053
+ return vm.dump(scope.manage(result.value));
2054
+ });
2055
+ }
2056
+ getWasmMemory() {
2057
+ let memory = this.module.quickjsEmscriptenInit?.(() => {
2058
+ })?.getWasmMemory?.();
2059
+ if (!memory) throw new Error("Variant does not support getting WebAssembly.Memory");
2060
+ return memory;
2061
+ }
2062
+ getFFI() {
2063
+ return this.ffi;
2064
+ }
2065
+ };
2066
+ async function newQuickJSWASMModuleFromVariant(variantOrPromise) {
2067
+ let variant2 = smartUnwrap(await variantOrPromise), [wasmModuleLoader, QuickJSFFI2, { QuickJSWASMModule: QuickJSWASMModule2 }] = await Promise.all([variant2.importModuleLoader().then(smartUnwrap), variant2.importFFI(), Promise.resolve().then(() => moduleES6BEMUI).then(smartUnwrap)]), wasmModule = await wasmModuleLoader();
2068
+ wasmModule.type = "sync";
2069
+ let ffi2 = new QuickJSFFI2(wasmModule);
2070
+ return new QuickJSWASMModule2(wasmModule, ffi2);
2071
+ }
2072
+ function smartUnwrap(val) {
2073
+ return val && "default" in val && val.default ? val.default && "default" in val.default && val.default.default ? val.default.default : val.default : val;
2074
+ }
2075
+ function newVariant(baseVariant, options) {
2076
+ return { ...baseVariant, async importModuleLoader() {
2077
+ let moduleLoader = smartUnwrap(await baseVariant.importModuleLoader());
2078
+ return async function() {
2079
+ let moduleLoaderArg = options.emscriptenModule ? { ...options.emscriptenModule } : {}, log = options.log ?? ((...args) => debugLog("newVariant moduleLoader:", ...args)), tapValue = (message, val) => (log(...message, val), val), force = (val) => typeof val == "function" ? val() : val;
2080
+ (options.wasmLocation || options.wasmSourceMapLocation || options.locateFile) && (moduleLoaderArg.locateFile = (fileName, relativeTo) => {
2081
+ let args = { fileName, relativeTo };
2082
+ if (fileName.endsWith(".wasm") && options.wasmLocation !== void 0) return tapValue(["locateFile .wasm: provide wasmLocation", args], options.wasmLocation);
2083
+ if (fileName.endsWith(".map")) {
2084
+ if (options.wasmSourceMapLocation !== void 0) return tapValue(["locateFile .map: provide wasmSourceMapLocation", args], options.wasmSourceMapLocation);
2085
+ if (options.wasmLocation && !options.locateFile) return tapValue(["locateFile .map: infer from wasmLocation", args], options.wasmLocation + ".map");
2086
+ }
2087
+ return options.locateFile ? tapValue(["locateFile: use provided fn", args], options.locateFile(fileName, relativeTo)) : tapValue(["locateFile: unhandled, passthrough", args], fileName);
2088
+ }), options.wasmBinary && (moduleLoaderArg.wasmBinary = await force(options.wasmBinary)), options.wasmMemory && (moduleLoaderArg.wasmMemory = await force(options.wasmMemory));
2089
+ let optionsWasmModule = options.wasmModule, modulePromise;
2090
+ optionsWasmModule && (moduleLoaderArg.instantiateWasm = async (imports, onSuccess) => {
2091
+ modulePromise ?? (modulePromise = Promise.resolve(force(optionsWasmModule)));
2092
+ let wasmModule = await modulePromise;
2093
+ if (!wasmModule) throw new QuickJSEmscriptenModuleError(`options.wasmModule returned ${String(wasmModule)}`);
2094
+ let instance = await WebAssembly.instantiate(wasmModule, imports);
2095
+ return onSuccess(instance), instance.exports;
2096
+ }), moduleLoaderArg.monitorRunDependencies = (left) => {
2097
+ log("monitorRunDependencies:", left);
2098
+ }, moduleLoaderArg.quickjsEmscriptenInit = () => newMockExtensions(log);
2099
+ let resultPromise = moduleLoader(moduleLoaderArg), extensions = moduleLoaderArg.quickjsEmscriptenInit?.(log);
2100
+ if (optionsWasmModule && extensions?.receiveWasmOffsetConverter && !extensions.existingWasmOffsetConverter) {
2101
+ let wasmBinary = await force(options.wasmBinary) ?? new ArrayBuffer(0);
2102
+ modulePromise ?? (modulePromise = Promise.resolve(force(optionsWasmModule)));
2103
+ let wasmModule = await modulePromise;
2104
+ if (!wasmModule) throw new QuickJSEmscriptenModuleError(`options.wasmModule returned ${String(wasmModule)}`);
2105
+ extensions.receiveWasmOffsetConverter(wasmBinary, wasmModule);
2106
+ }
2107
+ if (extensions?.receiveSourceMapJSON) {
2108
+ let loadedSourceMapData = await force(options.wasmSourceMapData);
2109
+ typeof loadedSourceMapData == "string" ? extensions.receiveSourceMapJSON(JSON.parse(loadedSourceMapData)) : loadedSourceMapData ? extensions.receiveSourceMapJSON(loadedSourceMapData) : extensions.receiveSourceMapJSON({ version: 3, names: [], sources: [], mappings: "" });
2110
+ }
2111
+ return resultPromise;
2112
+ };
2113
+ } };
2114
+ }
2115
+ function newMockExtensions(log) {
2116
+ let mockMessage = "mock called, emscripten module may not be initialized yet";
2117
+ return { mock: true, removeRunDependency(name) {
2118
+ log(`${mockMessage}: removeRunDependency called:`, name);
2119
+ }, receiveSourceMapJSON(data) {
2120
+ log(`${mockMessage}: receiveSourceMapJSON called:`, data);
2121
+ }, WasmOffsetConverter: void 0, receiveWasmOffsetConverter(bytes2, mod) {
2122
+ log(`${mockMessage}: receiveWasmOffsetConverter called:`, bytes2, mod);
2123
+ } };
2124
+ }
2125
+ var variant = { type: "sync", importFFI: () => Promise.resolve().then(() => ffi).then((mod) => mod.QuickJSFFI), importModuleLoader: () => Promise.resolve().then(() => emscriptenModule).then((mod) => mod.default) }, src_default = variant;
2126
+ const PRELUDE = `(function (call) {
2127
+ "use strict";
2128
+ const parse = JSON.parse, stringify = JSON.stringify, hooks = new Map(), freeze = Object.freeze;
2129
+ const req = (method, args) => call(method, stringify(args)).then((v) => parse(v));
2130
+ const text = (a) => a.map((x) => { if (typeof x === "string") return x; try { return stringify(x); } catch (e) { return String(x); } }).join(" ");
2131
+ const log = (...a) => { req("log", [text(a)]).catch(() => {}); };
2132
+ globalThis.rin = freeze({
2133
+ on(name, fn) {
2134
+ if (typeof name !== "string" || typeof fn !== "function") throw new TypeError("rin.on(name, fn)");
2135
+ hooks.set(name, fn);
2136
+ },
2137
+ log,
2138
+ chat: freeze({
2139
+ read: () => req("chat.read", []),
2140
+ vars: freeze({ get: () => req("chat.vars.get", []), set: (vars) => req("chat.vars.set", [vars]) }),
2141
+ send: (text) => req("chat.send", [text]),
2142
+ generate: (kind) => req("chat.generate", [kind]), // P6b
2143
+ }),
2144
+ prompt: freeze({ inject: (o) => req("prompt.inject", [o]), rewrite: (messages) => req("prompt.rewrite", [messages]), macro: (name) => req("prompt.macro", [name]) }),
2145
+ reply: freeze({ transform: (text) => req("reply.transform", [text]) }),
2146
+ model: freeze({ run: (o) => req("model.run", [o]) }),
2147
+ gen: freeze({ params: (o) => req("gen.params", [o === undefined ? null : o]) }), // P6b
2148
+ ui: freeze({
2149
+ command: (name, description) => req("ui.command", [description === undefined ? { name } : { name, description }]),
2150
+ // P6a (uiCaps.ts): drawn by the app from these records.
2151
+ panel: (p) => req("ui.panel", [p === undefined ? null : p]),
2152
+ hud: (items) => req("ui.hud", [items]),
2153
+ annotate: (o) => req("ui.annotate", [o]),
2154
+ choices: (list) => req("ui.choices", [list]),
2155
+ notify: (text) => req("ui.notify", [text]),
2156
+ // P6b (p6bCaps.ts): CSS text the host scopes through the card chat style sanitizer.
2157
+ style: (css) => req("ui.style", [css === undefined ? null : css]),
2158
+ partStyle: (css) => req("ui.partStyle", [css === undefined ? null : css]),
2159
+ theme: (o) => req("ui.theme", [o === undefined ? null : o]),
2160
+ }),
2161
+ composer: freeze({ draft: (text) => req("composer.draft", [text]) }),
2162
+ audio: freeze({ play: (name, o) => req("audio.play", o === undefined ? [name] : [name, o]), stop: (name) => req("audio.stop", name === undefined ? [] : [name]) }),
2163
+ voice: freeze({ speak: (text) => req("voice.speak", [text]) }),
2164
+ dice: freeze({ roll: (expr) => req("dice.roll", [expr]) }),
2165
+ time: freeze({ now: () => req("time.now", []) }),
2166
+ text: freeze({ tokens: (s) => req("text.tokens", [s]) }),
2167
+ storage: freeze({
2168
+ get: (key) => req("storage.get", [key]),
2169
+ set: (key, value) => req("storage.set", [key, value === undefined ? null : value]),
2170
+ delete: (key) => req("storage.delete", [key]),
2171
+ keys: () => req("storage.keys", []),
2172
+ }),
2173
+ settings: freeze({ get: () => req("settings.get", []) }),
2174
+ net: freeze({
2175
+ // Headers as an object or as [name, value] pairs; they cross as pairs, so a repeated name is seen (and refused).
2176
+ request: (o) => req("net.request", [o && typeof o === "object" && o.headers && !Array.isArray(o.headers) ? Object.assign({}, o, { headers: Object.entries(o.headers) }) : o]),
2177
+ }),
2178
+ open: freeze({ url: (u) => req("open.url", [u]) }),
2179
+ });
2180
+ globalThis.console = freeze({ log, info: log, warn: log, error: log, debug: log });
2181
+ return (name, args) => {
2182
+ const fn = hooks.get(name);
2183
+ if (typeof fn !== "function") return null;
2184
+ return Promise.resolve().then(() => fn(parse(args))).then((v) => { const s = stringify(v === undefined ? null : v); return s === undefined ? "null" : s; });
2185
+ };
2186
+ })`;
2187
+ const PRELUDE_CPU_MS = 200;
2188
+ async function createSandbox(wasmModule, limits, post) {
2189
+ const wasmMemory = new WebAssembly.Memory({ initial: 256, maximum: Math.max(256, Math.floor(limits.wasmBytes / 65536)) });
2190
+ const qjs = await newQuickJSWASMModuleFromVariant(newVariant(src_default, { wasmModule, wasmMemory }));
2191
+ const rt = qjs.newRuntime();
2192
+ rt.setMemoryLimit(limits.memoryBytes);
2193
+ rt.setMaxStackSize(limits.stackBytes);
2194
+ let deadline = 0;
2195
+ let interrupted = false;
2196
+ rt.setInterruptHandler(() => {
2197
+ if (performance.now() <= deadline) return false;
2198
+ interrupted = true;
2199
+ return true;
2200
+ });
2201
+ const vm = rt.newContext();
2202
+ const pending = /* @__PURE__ */ new Map();
2203
+ let seq2 = 0;
2204
+ let dispatch = null;
2205
+ let current = null;
2206
+ let loaded = false;
2207
+ const refuse2 = (d, code) => {
2208
+ const err = vm.newError({ name: "RinError", message: code });
2209
+ d.reject(err);
2210
+ err.dispose();
2211
+ d.dispose();
2212
+ };
2213
+ const callFn = vm.newFunction("call", (mH, aH) => {
2214
+ const d = vm.newPromise();
2215
+ const out = d.handle.dup();
2216
+ if (vm.typeof(mH) !== "string" || vm.typeof(aH) !== "string") {
2217
+ refuse2(d, "bad_request");
2218
+ return out;
2219
+ }
2220
+ const lenH = vm.getProp(aH, "length");
2221
+ const len = vm.getNumber(lenH);
2222
+ lenH.dispose();
2223
+ const method = vm.getString(mH);
2224
+ if (len > MAX_PAYLOAD) refuse2(d, "too_large");
2225
+ else if (method.length === 0 || method.length > MAX_NAME) refuse2(d, "bad_request");
2226
+ else if (pending.size >= MAX_PENDING) refuse2(d, "too_many_requests");
2227
+ else {
2228
+ const id = ++seq2;
2229
+ pending.set(id, d);
2230
+ post({ t: "req", id, method, args: vm.getString(aH) });
2231
+ }
2232
+ return out;
2233
+ });
2234
+ function guarded(remaining, fn) {
2235
+ const start = performance.now();
2236
+ deadline = start + remaining;
2237
+ interrupted = false;
2238
+ try {
2239
+ return { value: fn(), remaining: remaining - (performance.now() - start) };
2240
+ } finally {
2241
+ deadline = 0;
2242
+ }
2243
+ }
2244
+ function classify(errH) {
2245
+ if (interrupted) return { error: "cpu" };
2246
+ let message = "";
2247
+ let isError = false;
2248
+ try {
2249
+ const e = vm.dump(errH);
2250
+ isError = !!e && typeof e === "object" && "message" in e;
2251
+ message = isError ? `${e.name ?? "Error"}: ${e.message ?? ""}` : String(e);
2252
+ } catch {
2253
+ message = "error";
2254
+ }
2255
+ if (/out of memory/i.test(message)) return { error: "memory" };
2256
+ if (!isError && wasmMemory.buffer.byteLength >= limits.memoryBytes) return { error: "memory" };
2257
+ return { error: "threw", message: message.slice(0, 500) };
2258
+ }
2259
+ const finish = (m) => {
2260
+ if (current) current.promise.dispose();
2261
+ current = null;
2262
+ post(m);
2263
+ };
2264
+ function pump() {
2265
+ const c = current;
2266
+ if (!c) return;
2267
+ const run = guarded(c.remaining, () => rt.executePendingJobs());
2268
+ c.remaining = run.remaining;
2269
+ if (interrupted) {
2270
+ run.value.error?.dispose();
2271
+ return finish({ t: "done", id: c.id, ok: false, error: "cpu" });
2272
+ }
2273
+ if (run.value.error) {
2274
+ const r = classify(run.value.error);
2275
+ run.value.error.dispose();
2276
+ if (r.error !== "threw") return finish({ t: "done", id: c.id, ok: false, ...r });
2277
+ }
2278
+ const state = vm.getPromiseState(c.promise);
2279
+ if (state.type === "pending") return;
2280
+ if (state.type === "rejected") {
2281
+ const r = classify(state.error);
2282
+ state.error.dispose();
2283
+ return finish({ t: "done", id: c.id, ok: false, ...r });
2284
+ }
2285
+ const v = state.value;
2286
+ try {
2287
+ if (vm.typeof(v) !== "string") return finish({ t: "done", id: c.id, ok: false, error: "bad_value" });
2288
+ const lenH = vm.getProp(v, "length");
2289
+ const len = vm.getNumber(lenH);
2290
+ lenH.dispose();
2291
+ if (len > MAX_PAYLOAD) return finish({ t: "done", id: c.id, ok: false, error: "too_large" });
2292
+ finish({ t: "done", id: c.id, ok: true, value: vm.getString(v) });
2293
+ } finally {
2294
+ v.dispose();
2295
+ }
2296
+ }
2297
+ function load(id, source, cpuMs) {
2298
+ if (dispatch) return post({ t: "done", id, ok: false, error: "bad_request" });
2299
+ const pre = guarded(PRELUDE_CPU_MS, () => vm.evalCode(PRELUDE, "rin-prelude.js", { type: "global" })).value;
2300
+ if (pre.error) {
2301
+ pre.error.dispose();
2302
+ return post({ t: "done", id, ok: false, error: "not_loaded" });
2303
+ }
2304
+ const made = guarded(PRELUDE_CPU_MS, () => vm.callFunction(pre.value, vm.undefined, callFn)).value;
2305
+ pre.value.dispose();
2306
+ if (made.error) {
2307
+ made.error.dispose();
2308
+ return post({ t: "done", id, ok: false, error: "not_loaded" });
2309
+ }
2310
+ dispatch = made.value;
2311
+ const run = guarded(cpuMs, () => vm.evalCode(source, "extension.js", { type: "global" }));
2312
+ if (run.value.error) {
2313
+ const r = classify(run.value.error);
2314
+ run.value.error.dispose();
2315
+ return post({ t: "done", id, ok: false, ...r });
2316
+ }
2317
+ run.value.value.dispose();
2318
+ loaded = true;
2319
+ post({ t: "done", id, ok: true, value: "null" });
2320
+ }
2321
+ function call(id, hook, args, cpuMs) {
2322
+ if (!loaded || !dispatch) return post({ t: "done", id, ok: false, error: "not_loaded" });
2323
+ if (current) return post({ t: "done", id, ok: false, error: "bad_request" });
2324
+ const nameH = vm.newString(hook);
2325
+ const argsH = vm.newString(args);
2326
+ const run = guarded(cpuMs, () => vm.callFunction(dispatch, vm.undefined, nameH, argsH));
2327
+ nameH.dispose();
2328
+ argsH.dispose();
2329
+ if (run.value.error) {
2330
+ const r = classify(run.value.error);
2331
+ run.value.error.dispose();
2332
+ return post({ t: "done", id, ok: false, ...r });
2333
+ }
2334
+ const h = run.value.value;
2335
+ if (vm.sameValue(h, vm.null)) {
2336
+ h.dispose();
2337
+ return post({ t: "done", id, ok: false, error: "no_hook" });
2338
+ }
2339
+ current = { id, promise: h, remaining: run.remaining };
2340
+ pump();
2341
+ }
2342
+ function reply(m) {
2343
+ const d = pending.get(m.id);
2344
+ if (!d) return;
2345
+ pending.delete(m.id);
2346
+ if (m.ok) {
2347
+ const s = vm.newString(m.value);
2348
+ d.resolve(s);
2349
+ s.dispose();
2350
+ d.dispose();
2351
+ } else refuse2(d, m.error);
2352
+ pump();
2353
+ }
2354
+ let crashed = false;
2355
+ const idOf = (m) => m.t === "load" || m.t === "call" ? m.id : current?.id;
2356
+ return {
2357
+ handle(m) {
2358
+ try {
2359
+ if (!crashed) return dispatchMsg(m);
2360
+ } catch {
2361
+ crashed = true;
2362
+ }
2363
+ const id = idOf(m);
2364
+ current = null;
2365
+ if (id) post({ t: "done", id, ok: false, error: "crashed" });
2366
+ }
2367
+ };
2368
+ function dispatchMsg(m) {
2369
+ switch (m.t) {
2370
+ case "load":
2371
+ return load(m.id, m.source, m.cpuMs);
2372
+ case "call":
2373
+ return call(m.id, m.hook, m.args, m.cpuMs);
2374
+ case "reply":
2375
+ return reply(m);
2376
+ default:
2377
+ return;
2378
+ }
2379
+ }
2380
+ }
2381
+ async function compileQuickJs() {
2382
+ const path = createRequire(import.meta.url).resolve("@jitl/quickjs-wasmfile-release-sync/wasm");
2383
+ return WebAssembly.compile(readFileSync(path));
2384
+ }
2385
+ function inProcess() {
2386
+ let box = null;
2387
+ const port = {
2388
+ terminated: false,
2389
+ onmessage: null,
2390
+ postMessage(m) {
2391
+ if (port.terminated) return;
2392
+ const copy = m.t === "init" ? m : structuredClone(m);
2393
+ setTimeout(async () => {
2394
+ if (port.terminated) return;
2395
+ if (copy.t === "init") {
2396
+ box = await createSandbox(copy.module, copy.limits, toHost);
2397
+ toHost({ t: "ready" });
2398
+ } else box?.handle(copy);
2399
+ });
2400
+ },
2401
+ terminate() {
2402
+ port.terminated = true;
2403
+ box = null;
2404
+ }
2405
+ };
2406
+ const toHost = (m) => {
2407
+ if (port.terminated) return;
2408
+ const copy = structuredClone(m);
2409
+ setTimeout(() => !port.terminated && port.onmessage?.({ data: copy }));
2410
+ };
2411
+ return port;
2412
+ }
2413
+ const RULES = {
2414
+ "maxPackage": 2097152,
2415
+ "maxManifest": 65536,
2416
+ "maxNetHosts": 32,
2417
+ "maxSettings": 32,
2418
+ "maxText": 4e3,
2419
+ "textMaxDefault": 500,
2420
+ "maxOptions": 32,
2421
+ "maxSliderSteps": 1e4,
2422
+ "storageQuota": 1048576,
2423
+ "storageValueMax": 262144,
2424
+ "storageKeyMax": 128,
2425
+ "storageKeysMax": 1024,
2426
+ "permissions": [
2427
+ "chat.read",
2428
+ "prompt.inject",
2429
+ "prompt.rewrite",
2430
+ "reply.transform",
2431
+ "chat.send",
2432
+ "chat.vars",
2433
+ "storage",
2434
+ "ui.command",
2435
+ "ui.settings",
2436
+ "ui.widget",
2437
+ "model.run",
2438
+ "open.url",
2439
+ "ui.panel",
2440
+ "ui.hud",
2441
+ "ui.annotate",
2442
+ "ui.choices",
2443
+ "composer.draft",
2444
+ "ui.notify",
2445
+ "audio.play",
2446
+ "voice.speak",
2447
+ "ui.style",
2448
+ "ui.theme",
2449
+ "prompt.macro",
2450
+ "render.transform",
2451
+ "chat.generate",
2452
+ "gen.params"
2453
+ ],
2454
+ "iconExts": ["png", "webp", "jpg", "jpeg"],
2455
+ "audioMax": 1048576,
2456
+ "reservedHostSuffixes": ["localhost", "local", "internal", "lan", "home", "arpa"],
2457
+ "net": {
2458
+ "methods": ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"],
2459
+ "bodyMax": 65536,
2460
+ "urlMax": 8192,
2461
+ "headersMax": 32,
2462
+ "forbiddenHeaders": ["accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "date", "dnt", "expect", "forwarded", "host", "keep-alive", "origin", "referer", "set-cookie", "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via", "x-http-method", "x-http-method-override", "x-method-override"],
2463
+ "forbiddenHeaderPrefixes": ["proxy-", "sec-", "x-forwarded-"],
2464
+ "rateBurst": 5,
2465
+ "ratePerMinute": 15,
2466
+ "denialsToBlock": 3
2467
+ }
2468
+ };
2469
+ const R = RULES;
2470
+ class Refusal extends Error {
2471
+ constructor(code, detail) {
2472
+ const d = detail === void 0 ? void 0 : [...String(detail)].filter((c) => !new RegExp("\\p{Cc}", "u").test(c)).slice(0, 80).join("");
2473
+ super(d === void 0 ? `ext_err:${code}` : `ext_err:${code}:${d}`);
2474
+ this.code = code;
2475
+ this.detail = d;
2476
+ }
2477
+ }
2478
+ const refuse = (code, detail) => {
2479
+ throw new Refusal(code, detail);
2480
+ };
2481
+ const isControl = (c) => new RegExp("\\p{Cc}", "u").test(c);
2482
+ const chars = (s) => [...s];
2483
+ const plainText = (s, max) => !new RegExp("^\\p{White_Space}*$", "u").test(s) && chars(s).length <= max && !chars(s).some(isControl);
2484
+ const rustTrim = (s) => s.replace(new RegExp("^\\p{White_Space}+|\\p{White_Space}+$", "gu"), "");
2485
+ const asciiLowerDigitDash = (s) => /^[a-z0-9-]*$/.test(s);
2486
+ const byteLen = (s) => Buffer.byteLength(s, "utf8");
2487
+ function validId(id) {
2488
+ const labels = id.split(".");
2489
+ return byteLen(id) <= 64 && labels.length >= 2 && labels.every((l) => l.length > 0 && l.length <= 63 && asciiLowerDigitDash(l) && !l.startsWith("-") && !l.endsWith("-")) && /^[a-z]/.test(labels[0]);
2490
+ }
2491
+ const splitOnce = (s, c) => {
2492
+ const i = s.indexOf(c);
2493
+ return i < 0 ? [s, void 0] : [s.slice(0, i), s.slice(i + 1)];
2494
+ };
2495
+ function validSemver(v) {
2496
+ if (byteLen(v) > 64) return false;
2497
+ const [rest, build] = splitOnce(v, "+");
2498
+ const [core, pre] = splitOnce(rest, "-");
2499
+ const num = (s) => /^[0-9]+$/.test(s) && (s === "0" || !s.startsWith("0"));
2500
+ const ident = (s) => /^[A-Za-z0-9-]+$/.test(s);
2501
+ const parts = core.split(".");
2502
+ return parts.length === 3 && parts.every(num) && (pre === void 0 || pre.split(".").every((x) => ident(x) && (!/^[0-9]+$/.test(x) || num(x)))) && (build === void 0 || build.split(".").every(ident));
2503
+ }
2504
+ function validHost(h) {
2505
+ const labels = h.split(".");
2506
+ const last = labels[labels.length - 1];
2507
+ return byteLen(h) <= 253 && labels.length >= 2 && labels.every((l) => l.length > 0 && l.length <= 63 && asciiLowerDigitDash(l) && !l.startsWith("-") && !l.endsWith("-")) && !/^[0-9]+$/.test(last) && !R.reservedHostSuffixes.includes(last);
2508
+ }
2509
+ function validFileName(n) {
2510
+ const segs = n.split("/");
2511
+ return n.length > 0 && byteLen(n) <= 128 && segs.length <= 4 && segs.every((s) => s.length > 0 && s !== "." && s !== ".." && /^[A-Za-z0-9._-]+$/.test(s));
2512
+ }
2513
+ const extOf = (n) => {
2514
+ const i = n.lastIndexOf(".");
2515
+ return i < 0 ? "" : n.slice(i + 1).replace(/[A-Z]/g, (c) => c.toLowerCase());
2516
+ };
2517
+ function decodeB64Url(s) {
2518
+ if (!/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1) return null;
2519
+ const b = Buffer.from(s, "base64url");
2520
+ return b.toString("base64url") === s ? b : null;
2521
+ }
2522
+ function decodeKey(k) {
2523
+ const b = decodeB64Url(rustTrim(k));
2524
+ return b && b.length === 32 ? b : null;
2525
+ }
2526
+ class Num {
2527
+ constructor(raw) {
2528
+ this.raw = raw;
2529
+ this.value = Number(raw);
2530
+ this.int = /^-?[0-9]+$/.test(raw);
2531
+ }
2532
+ }
2533
+ const NUM = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
2534
+ const STR = /"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/y;
2535
+ function parseStrictJson(text) {
2536
+ let i = 0;
2537
+ const bad = () => {
2538
+ throw new Refusal("bad_manifest");
2539
+ };
2540
+ const ws = () => {
2541
+ while (i < text.length && " \n\r".includes(text[i])) i++;
2542
+ };
2543
+ const lit = (re) => {
2544
+ re.lastIndex = i;
2545
+ const m = re.exec(text);
2546
+ if (!m) bad();
2547
+ i = re.lastIndex;
2548
+ return m[0];
2549
+ };
2550
+ const string = () => {
2551
+ const s = JSON.parse(lit(STR));
2552
+ if (!s.isWellFormed()) bad();
2553
+ return s;
2554
+ };
2555
+ const value = (depth) => {
2556
+ if (depth > 128) bad();
2557
+ ws();
2558
+ const c = text[i];
2559
+ if (c === "{") {
2560
+ i++;
2561
+ const o = /* @__PURE__ */ Object.create(null);
2562
+ ws();
2563
+ if (text[i] === "}") return i++, o;
2564
+ for (; ; ) {
2565
+ ws();
2566
+ if (text[i] !== '"') bad();
2567
+ const k = string();
2568
+ if (Object.prototype.hasOwnProperty.call(o, k)) bad();
2569
+ ws();
2570
+ if (text[i++] !== ":") bad();
2571
+ o[k] = value(depth + 1);
2572
+ ws();
2573
+ const d = text[i++];
2574
+ if (d === "}") return o;
2575
+ if (d !== ",") bad();
2576
+ }
2577
+ }
2578
+ if (c === "[") {
2579
+ i++;
2580
+ const a = [];
2581
+ ws();
2582
+ if (text[i] === "]") return i++, a;
2583
+ for (; ; ) {
2584
+ a.push(value(depth + 1));
2585
+ ws();
2586
+ const d = text[i++];
2587
+ if (d === "]") return a;
2588
+ if (d !== ",") bad();
2589
+ }
2590
+ }
2591
+ if (c === '"') return string();
2592
+ for (const [w, v2] of [["true", true], ["false", false], ["null", null]]) if (text.startsWith(w, i)) return i += w.length, v2;
2593
+ const n = new Num(lit(NUM));
2594
+ if (!Number.isFinite(n.value)) bad();
2595
+ return n;
2596
+ };
2597
+ const v = value(0);
2598
+ ws();
2599
+ if (i !== text.length) bad();
2600
+ return v;
2601
+ }
2602
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Num);
2603
+ const isStr = (v) => typeof v === "string";
2604
+ const isNum = (v) => v instanceof Num;
2605
+ function shape(v, spec) {
2606
+ if (!isObj(v)) throw new Refusal("bad_manifest");
2607
+ const out = {};
2608
+ for (const k of Object.keys(v)) if (!Object.hasOwn(spec, k)) throw new Refusal("bad_manifest");
2609
+ for (const [k, [kind, dflt]] of Object.entries(spec)) {
2610
+ let x = v[k];
2611
+ if (kind.startsWith("opt:")) {
2612
+ if (x === void 0 || x === null) continue;
2613
+ kind === "opt:str" && !isStr(x) && refuse("bad_manifest");
2614
+ out[k] = x;
2615
+ continue;
2616
+ }
2617
+ if (x === void 0) {
2618
+ if (dflt === void 0) refuse("bad_manifest");
2619
+ out[k] = typeof dflt === "function" ? dflt() : dflt;
2620
+ continue;
2621
+ }
2622
+ const ok = {
2623
+ str: isStr,
2624
+ bool: (y) => typeof y === "boolean",
2625
+ f64: isNum,
2626
+ usize: (y) => isNum(y) && y.int && (!y.raw.startsWith("-") || BigInt(y.raw) === 0n) && BigInt(y.raw) <= 2n ** 64n - 1n,
2627
+ strs: (y) => Array.isArray(y) && y.every(isStr),
2628
+ any: () => true
2629
+ }[kind];
2630
+ if (!ok(x)) refuse("bad_manifest");
2631
+ if (kind === "f64" || kind === "usize") x = x.value;
2632
+ out[k] = x;
2633
+ }
2634
+ return out;
2635
+ }
2636
+ const FIELD_COMMON = { type: ["str"], key: ["str"], label: ["str"], description: ["opt:str"] };
2637
+ const FIELD_SPECS = {
2638
+ toggle: { ...FIELD_COMMON, default: ["bool", false] },
2639
+ slider: { ...FIELD_COMMON, min: ["f64"], max: ["f64"], step: ["f64"], default: ["f64"] },
2640
+ text: { ...FIELD_COMMON, default: ["str", ""], maxLength: ["usize", R.textMaxDefault], multiline: ["bool", false] },
2641
+ choice: { ...FIELD_COMMON, options: ["any"], default: ["str"] }
2642
+ };
2643
+ function settingField(v) {
2644
+ if (!isObj(v) || !isStr(v.type) || !Object.hasOwn(FIELD_SPECS, v.type)) refuse("bad_manifest");
2645
+ const f = shape(v, FIELD_SPECS[v.type]);
2646
+ if (f.type === "choice") {
2647
+ if (!Array.isArray(f.options)) refuse("bad_manifest");
2648
+ f.options = f.options.map((o) => shape(o, { value: ["str"], label: ["str"] }));
2649
+ }
2650
+ return f;
2651
+ }
2652
+ const validSettingKey = (k) => /^[a-z][A-Za-z0-9_]{0,31}$/.test(k) && k !== "constructor" && k !== "prototype";
2653
+ const textOk$1 = (s, max, multiline) => chars(s).length <= max && !chars(s).some((c) => isControl(c) && !(multiline && c === "\n"));
2654
+ function validateSettings(m) {
2655
+ const fields = m.settings;
2656
+ if (!fields.length) return;
2657
+ if (!m.permissions.includes("ui.settings")) refuse("bad_setting", "needs ui.settings");
2658
+ if (fields.length > R.maxSettings) refuse("bad_setting", "too many");
2659
+ const seen = /* @__PURE__ */ new Set();
2660
+ fields.forEach((f, i) => {
2661
+ const at = validSettingKey(f.key) ? f.key : String(i + 1);
2662
+ const bad = () => refuse("bad_setting", at);
2663
+ if (!validSettingKey(f.key) || seen.has(f.key)) bad();
2664
+ seen.add(f.key);
2665
+ if (!plainText(f.label, 64) || f.description !== void 0 && !plainText(f.description, 200)) bad();
2666
+ let ok = true;
2667
+ if (f.type === "slider") {
2668
+ const { min, max, step, default: d } = f;
2669
+ ok = [min, max, step, d].every(Number.isFinite) && min < max && step > 0 && (max - min) / step <= R.maxSliderSteps && d >= min && d <= max;
2670
+ } else if (f.type === "text") {
2671
+ ok = f.maxLength >= 1 && f.maxLength <= R.maxText && textOk$1(f.default, f.maxLength, f.multiline);
2672
+ } else if (f.type === "choice") {
2673
+ const vals = /* @__PURE__ */ new Set();
2674
+ ok = f.options.length >= 1 && f.options.length <= R.maxOptions && f.options.every((o) => plainText(o.value, 64) && plainText(o.label, 64) && !vals.has(o.value) && vals.add(o.value)) && vals.has(f.default);
2675
+ }
2676
+ if (!ok) bad();
2677
+ });
2678
+ }
2679
+ function parseManifest(bytes2, hasFile) {
2680
+ if (bytes2.length > R.maxManifest) refuse("bad_manifest");
2681
+ let text;
2682
+ try {
2683
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes2);
2684
+ } catch {
2685
+ refuse("bad_manifest");
2686
+ }
2687
+ const m = shape(parseStrictJson(text), {
2688
+ id: ["str"],
2689
+ name: ["str"],
2690
+ version: ["str"],
2691
+ entry: ["str"],
2692
+ description: ["opt:str"],
2693
+ permissions: ["strs", () => []],
2694
+ net: ["strs", () => []],
2695
+ icon: ["opt:str"],
2696
+ author: ["any"],
2697
+ settings: ["any", () => []]
2698
+ });
2699
+ m.author = shape(m.author, { name: ["opt:str"], key: ["str"] });
2700
+ if (!Array.isArray(m.settings)) refuse("bad_manifest");
2701
+ m.settings = m.settings.map(settingField);
2702
+ if (!validId(m.id)) refuse("bad_id");
2703
+ if (!plainText(m.name, 64)) refuse("bad_field", "name");
2704
+ if (m.description !== void 0 && (chars(m.description).length > 500 || chars(m.description).some((c) => isControl(c) && c !== "\n"))) refuse("bad_field", "description");
2705
+ if (m.author.name !== void 0 && !plainText(m.author.name, 64)) refuse("bad_field", "author.name");
2706
+ if (!validSemver(m.version)) refuse("bad_version");
2707
+ if (!validFileName(m.entry) || extOf(m.entry) !== "js" || !hasFile(m.entry)) refuse("bad_entry");
2708
+ if (m.icon !== void 0 && (!validFileName(m.icon) || !R.iconExts.includes(extOf(m.icon)) || !hasFile(m.icon))) refuse("bad_field", "icon");
2709
+ const seenP = /* @__PURE__ */ new Set();
2710
+ for (const p of m.permissions) {
2711
+ if (!R.permissions.includes(p) || seenP.has(p)) refuse("bad_permission", p);
2712
+ seenP.add(p);
2713
+ }
2714
+ if (m.net.length > R.maxNetHosts) refuse("bad_host", "too many");
2715
+ const seenH = /* @__PURE__ */ new Set();
2716
+ for (const h of m.net) {
2717
+ if (!validHost(h) || seenH.has(h)) refuse("bad_host", h);
2718
+ seenH.add(h);
2719
+ }
2720
+ if (!decodeKey(m.author.key)) refuse("bad_key");
2721
+ validateSettings(m);
2722
+ return m;
2723
+ }
2724
+ function audioOk(ext, b) {
2725
+ if (b.length > R.audioMax) return false;
2726
+ if (ext === "wav") return b.length >= 12 && b.toString("latin1", 0, 4) === "RIFF" && b.toString("latin1", 8, 12) === "WAVE";
2727
+ if (ext === "ogg") return b.toString("latin1", 0, 4) === "OggS";
2728
+ if (ext === "mp3") return b.toString("latin1", 0, 3) === "ID3" || b.length >= 2 && b[0] === 255 && (b[1] & 224) === 224;
2729
+ return false;
2730
+ }
2731
+ function refusalText(code, d = "") {
2732
+ return {
2733
+ too_large: "The extension is larger than 2 MB.",
2734
+ not_zip: "This is not an extension package (.rinext).",
2735
+ bad_name: `The package holds a file whose name is not allowed: ${d}.`,
2736
+ duplicate_file: "The package holds the same file twice.",
2737
+ too_many_files: "The package holds too many files.",
2738
+ unexpected_file: `The package holds a kind of file extensions may not carry: ${d}.`,
2739
+ extra_script: `The package holds a second script (${d}); an extension is one bundled script.`,
2740
+ no_manifest: "The package has no manifest.json.",
2741
+ bad_manifest: "The package's manifest.json is not valid.",
2742
+ bad_id: "The extension's id is not valid.",
2743
+ bad_field: `The manifest's ${d} field is not valid.`,
2744
+ bad_version: "The extension's version is not a valid version number.",
2745
+ bad_entry: "The manifest's entry script is missing or is not text.",
2746
+ bad_permission: `The extension asks for a permission this version of Rin Chat does not know: ${d}.`,
2747
+ bad_host: `The extension names a network host that is not allowed: ${d}.`,
2748
+ bad_key: "The manifest's author key is not valid.",
2749
+ unsigned: "The package is not signed by its author.",
2750
+ bad_signature: "The package's signature does not match its contents.",
2751
+ bad_setting: `The extension's settings form is not valid: ${d}.`,
2752
+ bad_audio: `The package holds a sound that is not a WAV, OGG or MP3 file of at most 1 MB: ${d}.`
2753
+ }[code] ?? `ext_err:${code}${d ? `:${d}` : ""}`;
2754
+ }
2755
+ const N = RULES.net;
2756
+ const TOKEN = /^[a-z0-9!#$%&'*+\-.^_`|~]{1,64}$/;
2757
+ const bytes$1 = (s) => Buffer.byteLength(s, "utf8");
2758
+ class FakeNet {
2759
+ /** `lines`: the runtime's network log for the extension (net.ts in the app's, kit-runtime.ts in the kit's). */
2760
+ constructor(declared, lines) {
2761
+ this.declared = declared;
2762
+ this.lines = lines;
2763
+ }
2764
+ declared;
2765
+ lines;
2766
+ /** The extension's level in Settings > Extensions. Setting it clears the denial streaks, as in the app. */
2767
+ get level() {
2768
+ return this.lvl;
2769
+ }
2770
+ set level(l) {
2771
+ this.lvl = l;
2772
+ this.denials.clear();
2773
+ }
2774
+ lvl = "blocked";
2775
+ /** "Block network for all extensions". */
2776
+ blockAll = false;
2777
+ /** Hosts the user allowed for the extension (any scope here). "Always allow" adds to it. */
2778
+ allowed = /* @__PURE__ */ new Set();
2779
+ /** Local services the user added, as `host:port` ("localhost:8123"). */
2780
+ local = /* @__PURE__ */ new Set();
2781
+ /** The user's answer in the review dialog. */
2782
+ review = () => "once";
2783
+ /** The user's answer to an open.url confirmation; `opened` lists what went to the browser. */
2784
+ confirmOpen = () => true;
2785
+ opened = [];
2786
+ /** The server: what a request that went gets back. */
2787
+ respond = () => ({ status: 404, body: "" });
2788
+ /** Every request that reached `respond`. */
2789
+ sent = [];
2790
+ held = /* @__PURE__ */ new Map();
2791
+ denials = /* @__PURE__ */ new Map();
2792
+ tokens = N.rateBurst;
2793
+ at = Date.now();
2794
+ seq = 0;
2795
+ /** The extension's network log, as its page in Settings > Extensions shows it. */
2796
+ log() {
2797
+ return this.lines();
2798
+ }
2799
+ /** extnet::plan's checks, without DNS. A string is the refusal's code. */
2800
+ plan(req) {
2801
+ const method = String(req.method ?? "").toUpperCase();
2802
+ if (!N.methods.includes(method)) return "net_method";
2803
+ const raw = String(req.url ?? "");
2804
+ if (raw.length > N.urlMax) return "net_url_too_long";
2805
+ let u;
2806
+ try {
2807
+ u = new URL(raw);
2808
+ } catch {
2809
+ return "net_bad_url";
2810
+ }
2811
+ u.hash = "";
2812
+ if (u.username || u.password) return "net_userinfo";
2813
+ const port = Number(u.port) || (u.protocol === "https:" ? 443 : 80);
2814
+ const isLocal = this.local.has(`${u.hostname}:${port}`);
2815
+ if (!(u.protocol === "https:" || u.protocol === "http:" && isLocal)) return "net_https_only";
2816
+ if (!isLocal) {
2817
+ if (/^\[.*\]$/.test(u.hostname) || /^\d+\.\d+\.\d+\.\d+$/.test(u.hostname)) return "net_ip_literal";
2818
+ if (!validHost(u.hostname)) return "net_bad_host";
2819
+ if (!this.declared.includes(u.hostname)) return "net_undeclared_host";
2820
+ }
2821
+ const given = Array.isArray(req.headers) ? req.headers : [];
2822
+ if (given.length > N.headersMax) return "net_too_many_headers";
2823
+ const headers = [];
2824
+ for (const [name, value] of given) {
2825
+ const n = name.toLowerCase();
2826
+ if (!TOKEN.test(n)) return "net_header";
2827
+ const forbidden = N.forbiddenHeaders.includes(n) || N.forbiddenHeaderPrefixes.some((p) => n.startsWith(p));
2828
+ if (forbidden || value.length > 4096 || !/^[\t\x20-\x7e]*$/.test(value) || headers.some(([h]) => h === n)) return `net_header:${n}`;
2829
+ headers.push([n, value]);
2830
+ }
2831
+ let body = typeof req.body === "string" ? req.body : null;
2832
+ if (body !== null && (method === "GET" || method === "HEAD")) return "net_body_not_allowed";
2833
+ if (body !== null && bytes$1(body) > N.bodyMax) return "net_body_too_large";
2834
+ if (body === null && ["POST", "PUT", "PATCH"].includes(method)) body = "";
2835
+ return { method, url: u.href, host: u.hostname, headers, body };
2836
+ }
2837
+ entry(req, decision, error, status = null, responseBytes = null) {
2838
+ return {
2839
+ atMs: Date.now(),
2840
+ method: String(req.method ?? "").toUpperCase(),
2841
+ url: String(req.url ?? ""),
2842
+ ip: null,
2843
+ status,
2844
+ requestBytes: typeof req.body === "string" ? bytes$1(req.body) : 0,
2845
+ responseBytes,
2846
+ decision,
2847
+ error
2848
+ };
2849
+ }
2850
+ refused(req, decision, error) {
2851
+ return { review: null, response: null, error, log: this.entry(req, decision, error), streakBlocked: false };
2852
+ }
2853
+ async go(plan, decision) {
2854
+ this.sent.push(plan);
2855
+ const r = await this.respond(plan);
2856
+ const response = { status: r.status ?? 200, headers: r.headers ?? [], body: r.body ?? "" };
2857
+ return { review: null, response, error: null, log: this.entry(plan, decision, null, response.status, bytes$1(response.body)), streakBlocked: false };
2858
+ }
2859
+ takeToken() {
2860
+ const now = Date.now();
2861
+ this.tokens = Math.min(N.rateBurst, this.tokens + (now - this.at) / 6e4 * N.ratePerMinute);
2862
+ this.at = now;
2863
+ if (this.tokens < 1) return false;
2864
+ this.tokens -= 1;
2865
+ return true;
2866
+ }
2867
+ /** ext_net_request and ext_net_answer, for the runner's transport. */
2868
+ async handle(cmd, a) {
2869
+ if (cmd === "ext_net_request") {
2870
+ const req = a.request ?? {};
2871
+ const chat = String(a.chatId);
2872
+ if (this.blockAll || this.level === "blocked" || (this.denials.get(chat) ?? 0) >= N.denialsToBlock) return this.refused(req, "blocked", "net_blocked");
2873
+ let host = "", port = 0;
2874
+ try {
2875
+ const u = new URL(String(req.url));
2876
+ host = u.hostname;
2877
+ port = Number(u.port) || (u.protocol === "https:" ? 443 : 80);
2878
+ } catch {
2879
+ }
2880
+ const review = this.level === "ask" || !(this.allowed.has(host) || this.local.has(`${host}:${port}`));
2881
+ if (review && !a.userStarted) {
2882
+ const p2 = this.plan(req);
2883
+ return typeof p2 === "string" ? this.refused(req, "invalid", p2) : this.refused(req, "needs_approval", "net_needs_approval");
2884
+ }
2885
+ if (!this.takeToken()) return this.refused(req, "rate_limited", "net_rate_limited");
2886
+ const p = this.plan(req);
2887
+ if (typeof p === "string") return this.refused(req, "invalid", p);
2888
+ if (!review) return this.go(p, "allowed_host");
2889
+ const planId = `fake-plan-${++this.seq}`;
2890
+ this.held.set(planId, { plan: p, chat });
2891
+ const view = { method: p.method, url: p.url, urlDecoded: p.url, host: p.host, port, addrs: [], localService: false, headers: p.headers.map(([name, value]) => ({ name, value, by: "extension" })), body: p.body, bodyBytes: bytes$1(p.body ?? "") };
2892
+ return { review: { planId, plan: view, scope: a.scopes[0] }, response: null, error: null, log: null, streakBlocked: false };
2893
+ }
2894
+ if (cmd === "ext_net_answer") {
2895
+ const h = this.held.get(String(a.planId));
2896
+ this.held.delete(String(a.planId));
2897
+ if (!h) throw "ext_err:net_unknown_plan";
2898
+ if (a.answer === "deny") {
2899
+ const n = Math.min(N.denialsToBlock, (this.denials.get(h.chat) ?? 0) + 1);
2900
+ const blocks = n === N.denialsToBlock && (this.denials.get(h.chat) ?? 0) < N.denialsToBlock;
2901
+ this.denials.set(h.chat, n);
2902
+ return { ...this.refused(h.plan, "denied", "net_denied"), streakBlocked: blocks };
2903
+ }
2904
+ this.denials.set(h.chat, 0);
2905
+ if (a.answer === "always") {
2906
+ this.allowed.add(h.plan.host);
2907
+ if (this.lvl === "ask") this.lvl = "allowed";
2908
+ }
2909
+ return this.go(h.plan, a.answer === "always" ? "allowed_host" : "allowed_once");
2910
+ }
2911
+ throw "ext_err:not_found";
2912
+ }
2913
+ }
2914
+ function loadFolder(dir) {
2915
+ const at = (n) => join(dir, ...n.split("/"));
2916
+ const has = (n) => validFileName(n) && existsSync(at(n)) && statSync(at(n)).isFile();
2917
+ if (!has("manifest.json")) throw new Refusal("no_manifest");
2918
+ const manifest = parseManifest(readFileSync(at("manifest.json")), has);
2919
+ const bytes2 = readFileSync(at(manifest.entry));
2920
+ if (bytes2.length > RULES.maxPackage) throw new Refusal("too_large");
2921
+ let source;
2922
+ try {
2923
+ source = new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
2924
+ } catch {
2925
+ throw new Refusal("bad_entry");
2926
+ }
2927
+ return { manifest, source };
2928
+ }
2929
+ const bytes = (s) => Buffer.byteLength(s, "utf8");
2930
+ const textOk = (s, max, multiline) => [...s].length <= max && ![...s].some((c) => new RegExp("\\p{Cc}", "u").test(c) && !(multiline && c === "\n"));
2931
+ const accepts = (f, v) => f.type === "toggle" ? typeof v === "boolean" : f.type === "slider" ? typeof v === "number" && Number.isFinite(v) && v >= f.min && v <= f.max : f.type === "text" ? typeof v === "string" && textOk(v, f.maxLength, !!f.multiline) : typeof v === "string" && f.options.some((o) => o.value === v);
2932
+ class FakeStorage {
2933
+ constructor(fields) {
2934
+ this.fields = fields;
2935
+ }
2936
+ fields;
2937
+ rows = /* @__PURE__ */ new Map();
2938
+ /** Seed values as the extension would have written them. */
2939
+ seed(values) {
2940
+ for (const [k, v] of Object.entries(values)) this.put(k, JSON.stringify(v), true);
2941
+ }
2942
+ /** What the user saved in the settings form; strict, like ext_settings_save. */
2943
+ saveSettings(values) {
2944
+ for (const [k, v] of Object.entries(values)) {
2945
+ const f = this.fields.find((x) => x.key === k);
2946
+ if (!f || !accepts(f, v)) throw new Error(`settings.${k}: the extension's form cannot save ${JSON.stringify(v)} there`);
2947
+ }
2948
+ this.put("rin:settings", JSON.stringify({ ...this.settings(), ...values }), true);
2949
+ }
2950
+ settings() {
2951
+ let stored = {};
2952
+ try {
2953
+ stored = JSON.parse(this.rows.get("rin:settings") ?? "{}");
2954
+ } catch {
2955
+ }
2956
+ return Object.fromEntries(this.fields.map((f) => [f.key, Object.hasOwn(stored, f.key) && accepts(f, stored[f.key]) ? stored[f.key] : f.default]));
2957
+ }
2958
+ validKey = (k) => k.length > 0 && bytes(k) <= RULES.storageKeyMax && !new RegExp("\\p{Cc}", "u").test(k) && !k.startsWith("rin:");
2959
+ put(key, value, host = false) {
2960
+ if (!host && !this.validKey(key)) throw "ext_err:bad_key_name";
2961
+ if (bytes(value) > RULES.storageValueMax) throw "ext_err:too_large";
2962
+ try {
2963
+ JSON.parse(value);
2964
+ } catch {
2965
+ throw "ext_err:bad_value";
2966
+ }
2967
+ let used = 0, others = 0;
2968
+ for (const [k, v] of this.rows) if (k !== key) used += bytes(k) + bytes(v), others++;
2969
+ if (used + bytes(key) + bytes(value) > RULES.storageQuota || others + 1 > RULES.storageKeysMax) throw "ext_err:quota";
2970
+ this.rows.set(key, value);
2971
+ }
2972
+ /** The ext_storage_* and ext_settings_get commands. */
2973
+ handle(cmd, a) {
2974
+ const key = a.key;
2975
+ switch (cmd) {
2976
+ case "ext_storage_get":
2977
+ if (!this.validKey(key)) throw "ext_err:bad_key_name";
2978
+ return this.rows.get(key) ?? null;
2979
+ case "ext_storage_set":
2980
+ return this.put(key, a.value), null;
2981
+ case "ext_storage_delete":
2982
+ if (!this.validKey(key)) throw "ext_err:bad_key_name";
2983
+ return this.rows.delete(key), null;
2984
+ case "ext_storage_keys":
2985
+ return [...this.rows.keys()].filter((k) => !k.startsWith("rin:")).sort((x, y) => Buffer.compare(Buffer.from(x), Buffer.from(y)));
2986
+ case "ext_settings_get":
2987
+ return this.settings();
2988
+ }
2989
+ throw `ext_err:not_found`;
2990
+ }
2991
+ }
2992
+ class FakeModel {
2993
+ /** What the user set in Settings > Extensions. `picked: false` is "no model picked" (`no_model`). */
2994
+ budget = { requests: 20, tokens: 2e4 };
2995
+ picked = true;
2996
+ /** The model's answer to each request; throw to fail the call (`model_failed`). */
2997
+ reply = () => "OK";
2998
+ /** Every request the extension made, as the provider received it. */
2999
+ calls = [];
3000
+ use = {};
3001
+ /** Today's count for the extension. */
3002
+ used(id) {
3003
+ const u = this.use[id];
3004
+ return { requests: u?.requests ?? 0, tokens: u?.tokens ?? 0 };
3005
+ }
3006
+ run(id, req, signal) {
3007
+ const fake = { id: "fake-config" };
3008
+ return runModel(id, req, signal, {
3009
+ prefs: async () => ({ [id]: { config: this.picked ? fake.id : "", ...this.budget } }),
3010
+ use: async () => this.use,
3011
+ saveUse: async (u) => {
3012
+ this.use = u;
3013
+ },
3014
+ configs: async () => [fake],
3015
+ usable: () => true,
3016
+ // the user's own endpoint (model.ts pickable)
3017
+ provider: () => ({
3018
+ complete: async (r) => {
3019
+ this.calls.push({ messages: r.messages, maxTokens: r.maxTokens, temperature: r.temperature });
3020
+ return this.reply(req);
3021
+ }
3022
+ }),
3023
+ now: () => /* @__PURE__ */ new Date()
3024
+ });
3025
+ }
3026
+ }
3027
+ const DEFAULT_CHAT = {
3028
+ messages: [
3029
+ { role: "assistant", name: "Rin", text: "Hello! What shall we do today?" },
3030
+ { role: "user", name: "You", text: "Roll for initiative." }
3031
+ ],
3032
+ cards: [{ id: "card-test", data: { name: "Rin", description: "A test character.", first_mes: "Hello! What shall we do today?" } }],
3033
+ vars: {}
3034
+ };
3035
+ let wasm = null;
3036
+ const BUNDLED_WASM = new URL("./quickjs.wasm", import.meta.url);
3037
+ const quickJs = () => existsSync(BUNDLED_WASM) ? WebAssembly.compile(readFileSync(BUNDLED_WASM)) : compileQuickJs();
3038
+ let seq = 0;
3039
+ const TEST_TIMEOUT_MS = 3e4;
3040
+ function runner(kind) {
3041
+ let storageNow = null;
3042
+ let netNow = null;
3043
+ const rust = async (cmd, args = {}) => {
3044
+ if (cmd.startsWith("ext_net_")) {
3045
+ if (!netNow) throw "ext_err:not_found";
3046
+ return netNow.handle(cmd, args);
3047
+ }
3048
+ if (!storageNow) throw "ext_err:not_found";
3049
+ return storageNow.handle(cmd, args);
3050
+ };
3051
+ function harness2(dir) {
3052
+ const { manifest } = loadFolder(dir);
3053
+ const net = new FakeNet(manifest.net ?? [], () => kind.netLog(manifest.id));
3054
+ const storage = new FakeStorage(manifest.settings ?? []);
3055
+ const model = new FakeModel();
3056
+ const p6b = { ranges: {}, themes: [], generateLeft: 20 };
3057
+ const open = async (input = {}) => {
3058
+ const posts = [];
3059
+ storageNow = storage;
3060
+ netNow = net;
3061
+ const chatId = `chat-test-${++seq}`;
3062
+ const state = { ...structuredClone(DEFAULT_CHAT), ...structuredClone(input) };
3063
+ const errors = [];
3064
+ const notices = [];
3065
+ let commands = [];
3066
+ const info = { id: manifest.id, manifest, sha256: "", source: "file", path: dir, fingerprint: null, unreviewed: true, installed_at: 0, updated_at: 0 };
3067
+ const binding = {
3068
+ chatId,
3069
+ cardIds: state.cards.map((c) => c.id),
3070
+ isCurrent: () => true,
3071
+ // one fake chat per open(), never switched away from
3072
+ read: () => chatSnapshot(state),
3073
+ vars: () => stringVars(state.vars),
3074
+ writeVars: (v) => Object.assign(state.vars, v),
3075
+ notice: (m) => notices.push(m),
3076
+ onCommands: (l) => commands = l,
3077
+ post: (p) => posts.push(p),
3078
+ // P6a. Messages have no ids here: a note's key is the message's index from the start.
3079
+ onUi: (s) => ui = s,
3080
+ messageKey: (back) => back < state.messages.length ? String(state.messages.length - 1 - back) : null,
3081
+ draft: (text) => void (fake.draft = text),
3082
+ speak: async (text) => (spoken.push(text), true),
3083
+ // P6b
3084
+ style: (s) => void (style = s),
3085
+ generate: (k) => (generated.push(k), true)
3086
+ };
3087
+ let style = { cls: "", css: "" };
3088
+ const generated = [];
3089
+ let ui = null;
3090
+ const spoken = [];
3091
+ const sounds = [];
3092
+ const fake = { draft: "" };
3093
+ const audio = {
3094
+ asset: async (_id, name) => {
3095
+ const p = join(dir, name);
3096
+ if (!validFileName(name) || !existsSync(p)) throw "ext_err:not_found";
3097
+ const b = readFileSync(p);
3098
+ if (!audioOk(name.slice(name.lastIndexOf(".") + 1).toLowerCase(), b)) throw `ext_err:bad_audio:${name}`;
3099
+ return b.toString("base64");
3100
+ },
3101
+ url: () => "",
3102
+ revoke: () => {
3103
+ },
3104
+ make: () => {
3105
+ const name = playing.shift() ?? "";
3106
+ return { volume: 1, loop: false, onended: null, pause() {
3107
+ }, play: () => void sounds.push(name) };
3108
+ }
3109
+ };
3110
+ const playing = [];
3111
+ const assetOf = audio.asset;
3112
+ audio.asset = (id, name) => assetOf(id, name).then((b) => (playing.push(name), b));
3113
+ const spawn = () => {
3114
+ const port = inProcess();
3115
+ const inFlight = /* @__PURE__ */ new Map();
3116
+ let inner = null;
3117
+ const post = port.postMessage.bind(port);
3118
+ const kill = port.terminate.bind(port);
3119
+ port.postMessage = (m) => {
3120
+ if (m.t === "load") inFlight.set(m.id, "load");
3121
+ if (m.t === "call") inFlight.set(m.id, m.hook);
3122
+ post(m);
3123
+ };
3124
+ port.terminate = () => {
3125
+ for (const hook of inFlight.values()) errors.push(`${hook}: timeout (no answer within the deadline, so the instance was stopped)`);
3126
+ inFlight.clear();
3127
+ kill();
3128
+ };
3129
+ Object.defineProperty(port, "onmessage", {
3130
+ get: () => inner && ((e) => {
3131
+ const d = e.data;
3132
+ if (d.t === "done") {
3133
+ const hook = inFlight.get(d.id) ?? "?";
3134
+ inFlight.delete(d.id);
3135
+ if (!d.ok && d.error !== "no_hook") errors.push(`${hook}: ${d.error}${d.message ? `: ${d.message}` : ""}`);
3136
+ }
3137
+ inner(e);
3138
+ }),
3139
+ set: (f) => inner = f
3140
+ });
3141
+ return port;
3142
+ };
3143
+ const rt = kind.make(binding, {
3144
+ list: async () => [info],
3145
+ load: async () => loadFolder(dir),
3146
+ remote: () => false,
3147
+ running: (fn) => fn(),
3148
+ review: async ({ plan: p }) => net.review({ method: p.method, url: p.url, host: p.host, headers: p.headers.map((h) => [h.name, h.value]), body: p.body }),
3149
+ confirmOpen: async ({ url }) => net.confirmOpen(url),
3150
+ openUrl: async (url) => void net.opened.push(url),
3151
+ spawn,
3152
+ wasm: () => wasm ??= quickJs(),
3153
+ model: (id, req, signal) => model.run(id, req, signal),
3154
+ audio,
3155
+ // P6b
3156
+ charge: async () => {
3157
+ if (p6b.generateLeft <= 0) throw new CapabilityError("budget");
3158
+ p6b.generateLeft--;
3159
+ },
3160
+ genRanges: async () => ({ [manifest.id]: p6b.ranges }),
3161
+ offerTheme: async (_id, _name, theme) => void p6b.themes.push(theme),
3162
+ rust
3163
+ }, manifest);
3164
+ clearExtLog(manifest.id);
3165
+ kind.clearNetLog(manifest.id);
3166
+ await rt.start();
3167
+ const turn = { continuation: false, asUser: false };
3168
+ return {
3169
+ id: chatId,
3170
+ messages: state.messages,
3171
+ vars: state.vars,
3172
+ get running() {
3173
+ return rt.running.includes(manifest.id);
3174
+ },
3175
+ errors,
3176
+ notices,
3177
+ logs: () => extLogLines(manifest.id).map((l) => l.text),
3178
+ commands: () => commands,
3179
+ turn: (t = {}) => (storageNow = storage, rt.beforeAssemble({ continuation: !!t.continuation, asUser: !!t.asUser })),
3180
+ command: (text) => (storageNow = storage, rt.runCommand(text)),
3181
+ assembled: async (messages) => {
3182
+ storageNow = storage;
3183
+ const r = await rt.assembled({ messages, injections: [] });
3184
+ return r && r.messages.map((m) => ({ role: m.role, content: m.content }));
3185
+ },
3186
+ replyDone: async (text) => {
3187
+ storageNow = storage;
3188
+ const r = await rt.replyDone(text, turn);
3189
+ return { text: r.text, by: r.by };
3190
+ },
3191
+ streaming: (text) => rt.streaming(text),
3192
+ posts,
3193
+ widget: (post, kind2, value) => {
3194
+ storageNow = storage;
3195
+ const p = posts.find((x) => x.id === post);
3196
+ return rt.runWidget(p?.ext ?? manifest.id, { post, kind: kind2, value });
3197
+ },
3198
+ ui: () => ui,
3199
+ panel: (id, on) => (storageNow = storage, rt.runPanel(manifest.id, { id, on })),
3200
+ get draft() {
3201
+ return fake.draft;
3202
+ },
3203
+ spoken,
3204
+ sounds,
3205
+ style: () => style,
3206
+ generated,
3207
+ params: () => rt.takeParams(),
3208
+ macros: async () => {
3209
+ storageNow = storage;
3210
+ return (await rt.resolveMacros(turn))?.values ?? {};
3211
+ },
3212
+ restyle: async (text, role = "assistant") => {
3213
+ storageNow = storage;
3214
+ return (await rt.restyle([{ role, text }])).get(`${role}
3215
+ ${text}`)?.text ?? text;
3216
+ },
3217
+ close: () => rt.stop()
3218
+ };
3219
+ };
3220
+ return { open, storage, model, net, manifest, p6b };
3221
+ }
3222
+ async function runOne(dir, fn) {
3223
+ const h = harness2(dir);
3224
+ const chats = [];
3225
+ const open = h.open;
3226
+ h.open = async (c) => {
3227
+ const chat = await open(c);
3228
+ chats.push(chat);
3229
+ return chat;
3230
+ };
3231
+ const problems = [];
3232
+ try {
3233
+ await Promise.race([fn(h), new Promise((_, no) => setTimeout(() => no(new Error(`did not finish within ${TEST_TIMEOUT_MS / 1e3} s`)), TEST_TIMEOUT_MS).unref())]);
3234
+ } catch (e) {
3235
+ problems.push(e instanceof Error ? e.message : String(e));
3236
+ }
3237
+ for (const c of chats) {
3238
+ await c.close();
3239
+ problems.push(...c.errors);
3240
+ }
3241
+ return problems;
3242
+ }
3243
+ let smokeOut = [];
3244
+ const SMOKE = async ({ open }) => {
3245
+ const chat = await open();
3246
+ if (!chat.running) {
3247
+ if (!chat.errors.length) throw new Error("the extension did not start");
3248
+ return;
3249
+ }
3250
+ const injected = await chat.turn();
3251
+ smokeOut.push(
3252
+ "Opened a chat, ran one turn, closed it.",
3253
+ ` commands: ${chat.commands().map((c) => c.cmd).join(", ") || "none"}`,
3254
+ ` injected: ${injected.length ? "" : "nothing"}`,
3255
+ ...injected.map((i) => ` depth ${i.depth}, ${i.role}: ${i.text.slice(0, 200)}`),
3256
+ ` log: ${chat.logs().length ? "" : "empty"}`,
3257
+ ...chat.logs().map((l) => ` ${l.slice(0, 200)}`)
3258
+ );
3259
+ };
3260
+ async function runTests2(folder, testFile) {
3261
+ const dir = resolve(folder);
3262
+ try {
3263
+ loadFolder(dir);
3264
+ } catch (e) {
3265
+ if (e instanceof Refusal) {
3266
+ const r = e;
3267
+ return { ok: false, out: [`Rin Chat would not load this folder: ${refusalText(r.code, r.detail)} [${r.message}]`] };
3268
+ }
3269
+ return { ok: false, out: [`${dir}: ${e.message}`] };
3270
+ }
3271
+ let tests;
3272
+ if (testFile) {
3273
+ const mod = await import(
3274
+ /* @vite-ignore */
3275
+ pathToFileURL(resolve(testFile)).href
3276
+ );
3277
+ tests = Object.entries(mod).filter((e) => typeof e[1] === "function").sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
3278
+ if (!tests.length) return { ok: false, out: [`${testFile} exports no test functions.`] };
3279
+ } else tests = [["smoke", SMOKE]];
3280
+ const out = [];
3281
+ let failed = 0;
3282
+ for (const [name, fn] of tests) {
3283
+ smokeOut = [];
3284
+ const problems = await runOne(dir, fn);
3285
+ if (problems.length) failed++;
3286
+ out.push(`${problems.length ? "FAIL" : "ok "} ${name}`, ...problems.map((p) => ` ${p}`), ...smokeOut);
3287
+ }
3288
+ out.push("", `${tests.length - failed} passed, ${failed} failed`);
3289
+ return { ok: failed === 0, out };
3290
+ }
3291
+ return { harness: harness2, runTests: runTests2, rust };
3292
+ }
3293
+ function main(runTests2) {
3294
+ if (process.env.RINEXT_TEST_MAIN !== "1") return;
3295
+ const [folder, file] = process.argv.slice(2);
3296
+ void runTests2(folder, file).then((r) => {
3297
+ (r.ok ? console.log : console.error)(r.out.join("\n"));
3298
+ process.exit(r.ok ? 0 : 1);
3299
+ });
3300
+ }
3301
+ const DEFAULT_CALL = { deadlineMs: 1e3, cpuMs: 100 };
3302
+ const DEFAULT_LOAD = { deadlineMs: 3e3, cpuMs: 500 };
3303
+ const FATAL = /* @__PURE__ */ new Set(["timeout", "cpu", "memory", "crashed"]);
3304
+ class ExtensionHost {
3305
+ o;
3306
+ caps;
3307
+ port = null;
3308
+ seq = 0;
3309
+ waiting = /* @__PURE__ */ new Map();
3310
+ serving = /* @__PURE__ */ new Set();
3311
+ onReady = null;
3312
+ queue = Promise.resolve();
3313
+ loaded = false;
3314
+ constructor(o) {
3315
+ this.o = o;
3316
+ this.caps = o.capabilities ?? SPIKE_CAPABILITIES;
3317
+ }
3318
+ get running() {
3319
+ return this.loaded && this.port !== null;
3320
+ }
3321
+ /** Spawn a fresh Worker, hand it the compiled interpreter, and load the script. */
3322
+ start() {
3323
+ return this.serial(() => this.boot());
3324
+ }
3325
+ /** Call a hook. Starts (or restarts) the instance first when it is not running. */
3326
+ call(hook, args, opts = {}) {
3327
+ return this.serial(async () => {
3328
+ if (!this.running) {
3329
+ const r = await this.boot();
3330
+ if (!r.ok) return r;
3331
+ }
3332
+ const payload = safeStringify(args);
3333
+ if (!payload.ok) return { ok: false, error: payload.error };
3334
+ const { deadlineMs, cpuMs } = { ...DEFAULT_CALL, ...opts };
3335
+ this.now = { hook, deadlineAt: Date.now() + deadlineMs };
3336
+ try {
3337
+ return await this.send({ t: "call", id: 0, hook, args: payload.text, cpuMs }, deadlineMs);
3338
+ } finally {
3339
+ this.now = null;
3340
+ }
3341
+ });
3342
+ }
3343
+ /** The hook call running now and its wall-clock end (P3: a capability's rules depend on the hook it is called
3344
+ * from, and model.run aborts at the deadline). Capability requests only arrive during a call, since the
3345
+ * interpreter runs only inside one. */
3346
+ get current() {
3347
+ return this.now;
3348
+ }
3349
+ now = null;
3350
+ /** The hard kill. Every call in flight resolves with `killed`. */
3351
+ terminate() {
3352
+ const port = this.port;
3353
+ this.port = null;
3354
+ this.loaded = false;
3355
+ this.onReady = null;
3356
+ this.serving.clear();
3357
+ if (port) {
3358
+ port.onmessage = null;
3359
+ port.terminate();
3360
+ }
3361
+ const w = [...this.waiting.values()];
3362
+ this.waiting.clear();
3363
+ for (const done of w) done({ ok: false, error: "killed" });
3364
+ }
3365
+ restart() {
3366
+ this.terminate();
3367
+ return this.start();
3368
+ }
3369
+ serial(fn) {
3370
+ const next = this.queue.then(fn, fn);
3371
+ this.queue = next.catch(() => void 0);
3372
+ return next;
3373
+ }
3374
+ async boot() {
3375
+ this.terminate();
3376
+ if (this.o.source.length > MAX_SOURCE) return { ok: false, error: "too_large" };
3377
+ const module = await this.o.wasm();
3378
+ const port = this.o.spawn();
3379
+ this.port = port;
3380
+ port.onmessage = (e) => this.receive(port, e.data);
3381
+ const load = this.o.load ?? DEFAULT_LOAD;
3382
+ const ready = await new Promise((resolve2) => {
3383
+ const timer = setTimeout(() => resolve2(false), load.deadlineMs);
3384
+ this.onReady = () => {
3385
+ clearTimeout(timer);
3386
+ resolve2(true);
3387
+ };
3388
+ port.postMessage({ t: "init", module, limits: this.o.limits ?? DEFAULT_LIMITS });
3389
+ });
3390
+ if (!ready || this.port !== port) {
3391
+ this.terminate();
3392
+ return { ok: false, error: "timeout" };
3393
+ }
3394
+ const r = await this.send({ t: "load", id: 0, source: this.o.source, cpuMs: load.cpuMs }, load.deadlineMs);
3395
+ if (r.ok) this.loaded = true;
3396
+ else this.terminate();
3397
+ return r;
3398
+ }
3399
+ /** Post a load or call and wait for its `done`, or the deadline. */
3400
+ send(m, deadlineMs) {
3401
+ const port = this.port;
3402
+ if (!port) return Promise.resolve({ ok: false, error: "killed" });
3403
+ const id = ++this.seq;
3404
+ return new Promise((resolve2) => {
3405
+ const clock = {
3406
+ left: deadlineMs,
3407
+ since: 0,
3408
+ timer: null,
3409
+ holds: 0,
3410
+ fire: () => {
3411
+ this.waiting.delete(id);
3412
+ this.terminate();
3413
+ resolve2({ ok: false, error: "timeout" });
3414
+ }
3415
+ };
3416
+ this.clock = clock;
3417
+ this.arm();
3418
+ this.waiting.set(id, (r) => {
3419
+ if (clock.timer !== null) clearTimeout(clock.timer);
3420
+ if (this.clock === clock) this.clock = null;
3421
+ if (!r.ok && FATAL.has(r.error)) this.terminate();
3422
+ resolve2(r);
3423
+ });
3424
+ port.postMessage({ ...m, id });
3425
+ });
3426
+ }
3427
+ // P4: the running call's wall clock can pause. Calls are serialized, so one clock at most.
3428
+ clock = null;
3429
+ arm() {
3430
+ const c = this.clock;
3431
+ if (!c || c.holds > 0 || c.timer !== null) return;
3432
+ c.since = Date.now();
3433
+ c.timer = setTimeout(c.fire, Math.max(0, c.left));
3434
+ if (this.now) this.now.deadlineAt = c.since + c.left;
3435
+ }
3436
+ /** Pause the running call's deadline while `p` waits on the user (a network review, an open.url confirmation)
3437
+ * and on the request it allows. The CPU budget still holds, and nothing runs in the interpreter meanwhile: it
3438
+ * waits on this very reply. Only user-started code is given this (net.ts); a turn hook's deadline never moves.
3439
+ * A hold belongs to the call it started in: one still open when that call ends pauses nothing after it. */
3440
+ async hold(p) {
3441
+ const c = this.clock;
3442
+ if (!c) return p;
3443
+ if (c.holds++ === 0 && c.timer !== null) {
3444
+ clearTimeout(c.timer);
3445
+ c.timer = null;
3446
+ c.left -= Date.now() - c.since;
3447
+ }
3448
+ try {
3449
+ return await p;
3450
+ } finally {
3451
+ if (--c.holds === 0 && this.clock === c) this.arm();
3452
+ }
3453
+ }
3454
+ receive(port, raw) {
3455
+ if (port !== this.port) return;
3456
+ const m = checkWorkerMsg(raw);
3457
+ if (!m) return;
3458
+ if (m.t === "ready") {
3459
+ const r = this.onReady;
3460
+ this.onReady = null;
3461
+ r?.();
3462
+ } else if (m.t === "done") {
3463
+ const w = this.waiting.get(m.id);
3464
+ if (!w) return;
3465
+ this.waiting.delete(m.id);
3466
+ if (!m.ok) return w({ ok: false, error: m.error, message: m.message });
3467
+ const p = safeParse(m.value);
3468
+ w(p.ok ? { ok: true, value: p.value } : { ok: false, error: p.error });
3469
+ } else void this.serve(port, m);
3470
+ }
3471
+ async serve(port, m) {
3472
+ const answer = (r) => {
3473
+ if (port === this.port) port.postMessage({ t: "reply", id: m.id, ...r });
3474
+ };
3475
+ if (this.serving.has(m.id)) return;
3476
+ if (this.serving.size >= MAX_PENDING) return answer({ ok: false, error: "too_many_requests" });
3477
+ const cap = this.caps.get(m.method);
3478
+ if (!cap || cap.permission !== null && !this.o.manifest.permissions.includes(cap.permission)) return answer({ ok: false, error: "denied" });
3479
+ const p = safeParse(m.args);
3480
+ if (!p.ok) return answer({ ok: false, error: p.error });
3481
+ if (!Array.isArray(p.value) || !cap.check(p.value)) return answer({ ok: false, error: "bad_request" });
3482
+ this.serving.add(m.id);
3483
+ try {
3484
+ const out = safeStringify(await cap.run(p.value, this.o.ctx));
3485
+ answer(out.ok ? { ok: true, value: out.text } : { ok: false, error: out.error });
3486
+ } catch (e) {
3487
+ answer({ ok: false, error: e instanceof CapabilityError ? e.code : "bad_request" });
3488
+ } finally {
3489
+ this.serving.delete(m.id);
3490
+ }
3491
+ }
3492
+ }
3493
+ const within = (ms, p) => new Promise((resolve2) => {
3494
+ const timer = setTimeout(() => resolve2({ ok: false, error: "timeout" }), ms);
3495
+ p.then((r) => {
3496
+ clearTimeout(timer);
3497
+ resolve2(r);
3498
+ }, () => {
3499
+ clearTimeout(timer);
3500
+ resolve2({ ok: false, error: "crashed" });
3501
+ });
3502
+ });
3503
+ const netLogs = /* @__PURE__ */ new Map();
3504
+ const kitNetLog = (id) => netLogs.get(id) ?? [];
3505
+ const clearKitNetLog = (id) => void netLogs.delete(id);
3506
+ const MIME = { wav: "audio/wav", ogg: "audio/ogg", mp3: "audio/mpeg" };
3507
+ const VOLUME = 0.8;
3508
+ let notifySeq = 0;
3509
+ class KitRuntime {
3510
+ constructor(b, d, m) {
3511
+ this.b = b;
3512
+ this.d = d;
3513
+ this.m = m;
3514
+ }
3515
+ b;
3516
+ d;
3517
+ m;
3518
+ inst = null;
3519
+ stopped = false;
3520
+ /** The failure pause (pause.ts): failures in a row per hook, and whether it paused. */
3521
+ fails = /* @__PURE__ */ new Map();
3522
+ paused = false;
3523
+ name = "";
3524
+ sendLog = [];
3525
+ rates = /* @__PURE__ */ new Map();
3526
+ styles = {};
3527
+ macroNames = [];
3528
+ genReq = null;
3529
+ shown = /* @__PURE__ */ new Map();
3530
+ get running() {
3531
+ return this.inst ? [this.m.id] : [];
3532
+ }
3533
+ async start() {
3534
+ if (this.stopped) return;
3535
+ const [info] = await this.d.list();
3536
+ this.name = info.unreviewed ? `${info.manifest.name} (Unreviewed)` : info.manifest.name;
3537
+ let source;
3538
+ try {
3539
+ source = (await this.d.load(info.id)).source;
3540
+ } catch {
3541
+ return;
3542
+ }
3543
+ const inst = {
3544
+ host: null,
3545
+ pending: [],
3546
+ writes: 0,
3547
+ sends: 0,
3548
+ generated: false,
3549
+ bucket: null,
3550
+ commands: [],
3551
+ dead: false,
3552
+ rewrite: null,
3553
+ transform: null,
3554
+ noHook: /* @__PURE__ */ new Set(),
3555
+ replyBusy: false,
3556
+ replyAt: 0
3557
+ };
3558
+ inst.host = this.hostFor(inst, source);
3559
+ this.inst = inst;
3560
+ if (!await this.open(inst)) this.drop(inst);
3561
+ this.emitCommands();
3562
+ }
3563
+ async stop() {
3564
+ this.stopped = true;
3565
+ const inst = this.inst;
3566
+ this.inst = null;
3567
+ this.clearUi();
3568
+ this.styles = {};
3569
+ this.macroNames = [];
3570
+ this.shown.clear();
3571
+ this.emitStyles();
3572
+ this.stopSounds();
3573
+ this.soundUrls.clear();
3574
+ this.emitCommands();
3575
+ if (!inst) return;
3576
+ inst.dead = true;
3577
+ inst.writes = 0;
3578
+ if (inst.host.running && !this.paused) await within(CLOSE_DEADLINE_MS, inst.host.call("onChatClose", {}, { deadlineMs: CLOSE_DEADLINE_MS }));
3579
+ inst.host.terminate();
3580
+ }
3581
+ async open(inst) {
3582
+ const r = await inst.host.start();
3583
+ if (inst.dead) {
3584
+ inst.host.terminate();
3585
+ return false;
3586
+ }
3587
+ if (!r.ok) {
3588
+ this.record(r, "");
3589
+ return false;
3590
+ }
3591
+ await this.hook(inst, "onChatOpen", {}, HOOK_DEADLINE_MS);
3592
+ return true;
3593
+ }
3594
+ drop(inst) {
3595
+ inst.dead = true;
3596
+ this.dropUi();
3597
+ inst.host.terminate();
3598
+ this.inst = null;
3599
+ this.emitCommands();
3600
+ }
3601
+ hostFor(inst, source) {
3602
+ const m = this.m;
3603
+ const ctx = {
3604
+ extensionId: m.id,
3605
+ log: [],
3606
+ rust: this.d.rust,
3607
+ chat: () => this.b.read(),
3608
+ net: this.netFor(inst),
3609
+ chatOps: {
3610
+ vars: () => this.b.vars(),
3611
+ setVars: (v) => {
3612
+ if (++inst.writes > MAX_VAR_WRITES) return false;
3613
+ this.b.writeVars(v);
3614
+ return true;
3615
+ },
3616
+ inject: (i) => {
3617
+ const b = inst.bucket;
3618
+ const list = b ? b.items : inst.pending;
3619
+ if (b && !b.open || list.length >= MAX_INJECTIONS) return false;
3620
+ list.push(i);
3621
+ return true;
3622
+ },
3623
+ command: (c) => {
3624
+ if (inst.dead || RESERVED_COMMANDS.has(c.name) || inst.commands.length >= MAX_COMMANDS || inst.commands.some((x) => x.name === c.name)) return false;
3625
+ inst.commands.push(c);
3626
+ this.emitCommands();
3627
+ return true;
3628
+ }
3629
+ },
3630
+ turnOps: {
3631
+ model: async (req) => {
3632
+ const left = (inst.host.current?.deadlineAt ?? 0) - Date.now();
3633
+ if (left <= 0) throw new CapabilityError("model_failed");
3634
+ const ctl = new AbortController();
3635
+ const timer = setTimeout(() => ctl.abort(), left);
3636
+ try {
3637
+ return await this.d.model(m.id, req, ctl.signal);
3638
+ } finally {
3639
+ clearTimeout(timer);
3640
+ }
3641
+ },
3642
+ rewrite: (messages) => {
3643
+ const s = inst.rewrite;
3644
+ if (!s?.open) return false;
3645
+ s.messages = messages;
3646
+ return true;
3647
+ },
3648
+ transform: (text) => {
3649
+ const s = inst.transform;
3650
+ if (!s?.open) return false;
3651
+ if (addsSyntax(s.base, text)) throw new CapabilityError("bad_request");
3652
+ s.text = text;
3653
+ return true;
3654
+ },
3655
+ send: (text) => {
3656
+ const hook = inst.host.current?.hook;
3657
+ if (!this.b.post || !hook || !SEND_HOOKS.has(hook)) return null;
3658
+ if (addsReach("", text)) throw new CapabilityError("bad_request");
3659
+ if (++inst.sends > MAX_SENDS_PER_CALL) throw new CapabilityError("too_many_requests");
3660
+ const now = Date.now();
3661
+ const recent = this.sendLog.filter((at) => now - at < SEND_WINDOW_MS);
3662
+ if (recent.length >= MAX_SENDS_PER_WINDOW) throw new CapabilityError("too_many_requests");
3663
+ this.sendLog = [...recent, now];
3664
+ const id = crypto.randomUUID();
3665
+ this.b.post({ id, ext: m.id, name: this.name, text: inertPost(text, m.permissions.includes("ui.widget")) });
3666
+ return id;
3667
+ }
3668
+ },
3669
+ uiOps: this.uiOps(inst),
3670
+ p6bOps: this.p6bOps(inst)
3671
+ };
3672
+ return new ExtensionHost({
3673
+ manifest: { id: m.id, version: m.version, permissions: m.permissions },
3674
+ source,
3675
+ ctx,
3676
+ // Inside onMacro nothing but log answers (a macro is pure).
3677
+ capabilities: pureDuring(CHAT_CAPABILITIES, () => inst.host.current?.hook === "onMacro"),
3678
+ spawn: this.d.spawn,
3679
+ wasm: this.d.wasm
3680
+ });
3681
+ }
3682
+ // --------------------------------------------------------------------------------------------- hooks ---
3683
+ userStarted(inst) {
3684
+ return USER_STARTED.has(inst.host.current?.hook ?? "");
3685
+ }
3686
+ userDeadline() {
3687
+ return this.m.permissions.includes("model.run") ? MODEL_HOOK_DEADLINE_MS : HOOK_DEADLINE_MS;
3688
+ }
3689
+ /** pause.ts recordHookResult: three failures in a row of one hook pause the extension in this chat. */
3690
+ record(r, hook) {
3691
+ if (this.paused) return;
3692
+ if (r.ok) {
3693
+ this.fails.delete(hook);
3694
+ return;
3695
+ }
3696
+ if (NOT_A_FAILURE.has(r.error)) return;
3697
+ const n = (this.fails.get(hook) ?? 0) + 1;
3698
+ if (n < FAIL_LIMIT) {
3699
+ this.fails.set(hook, n);
3700
+ return;
3701
+ }
3702
+ this.fails.clear();
3703
+ this.paused = true;
3704
+ const name = this.m.name;
3705
+ this.b.notice(`${name} failed three times in a row, so it is paused in this chat. Resume it from the chat menu.`, `ext-paused:${this.b.chatId}
3706
+ ${this.m.id}`, name);
3707
+ }
3708
+ async hook(inst, name, args, deadlineMs) {
3709
+ if (inst.dead) return { ok: false, error: "killed" };
3710
+ if (this.paused) return { ok: false, error: "denied" };
3711
+ inst.writes = 0;
3712
+ inst.sends = 0;
3713
+ inst.generated = false;
3714
+ const call = inst.host.call(name, args, { deadlineMs });
3715
+ const r = USER_STARTED.has(name) ? await call.catch(() => ({ ok: false, error: "crashed" })) : await within(deadlineMs, call);
3716
+ if (!r.ok && r.error === "no_hook") inst.noHook.add(name);
3717
+ this.record(r, name);
3718
+ return r;
3719
+ }
3720
+ takes(inst, hook, ...perms) {
3721
+ return !inst.dead && !inst.noHook.has(hook) && !this.paused && perms.some((p) => this.m.permissions.includes(p));
3722
+ }
3723
+ async beforeAssemble(turn) {
3724
+ const inst = this.inst;
3725
+ if (!inst) return [];
3726
+ const queued = inst.pending.splice(0).slice(-MAX_INJECTIONS);
3727
+ if (this.paused) return [];
3728
+ const bucket = { open: true, items: [] };
3729
+ inst.bucket = bucket;
3730
+ const work = this.hook(inst, "onBeforeAssemble", turn, HOOK_DEADLINE_MS);
3731
+ void work.finally(() => {
3732
+ if (inst.bucket === bucket) inst.bucket = null;
3733
+ });
3734
+ const r = await within(HOOK_DEADLINE_MS, work);
3735
+ bucket.open = false;
3736
+ const added = r.ok || r.error === "no_hook" ? bucket.items : [];
3737
+ return [...queued, ...added].map((i) => ({ text: codeBlock(i.text), depth: i.depth, role: i.role, name: `Extension: ${this.name}` }));
3738
+ }
3739
+ commands() {
3740
+ const n = this.name;
3741
+ return (this.inst?.commands ?? []).map((c) => ({ cmd: `/${c.name}`, desc: c.description ? `${n}: ${c.description}` : n }));
3742
+ }
3743
+ emitCommands() {
3744
+ this.b.onCommands?.(this.commands());
3745
+ }
3746
+ async runCommand(text) {
3747
+ const m = /^\/(\w+)(?:\s+([\s\S]*))?$/.exec(text.trim());
3748
+ const inst = this.inst;
3749
+ if (!m || !inst?.commands.some((c) => c.name === m[1])) return false;
3750
+ const n = this.name;
3751
+ if (this.paused) {
3752
+ this.b.notice(`${n} is paused in this chat.`, void 0, n);
3753
+ return true;
3754
+ }
3755
+ const r = await this.hook(inst, "onCommand", { name: m[1], args: (m[2] ?? "").trim() }, this.userDeadline());
3756
+ if (!r.ok && r.error !== "denied") this.b.notice(`The command from ${n} did not finish.`, void 0, n);
3757
+ return true;
3758
+ }
3759
+ async assembled(input) {
3760
+ const end = Date.now() + HOOK_DEADLINE_MS;
3761
+ const inst = this.inst;
3762
+ const cur = input.messages;
3763
+ const left = end - Date.now();
3764
+ if (!inst || left <= 0 || !this.takes(inst, "onAssembled", "prompt.rewrite")) return null;
3765
+ if (cur.some((m) => m.role !== "system" && m.role !== "user" && m.role !== "assistant")) return null;
3766
+ const view = cur.map((m) => ({ role: m.role, content: typeof m.content === "string" ? m.content : "" }));
3767
+ if (JSON.stringify(view).length > MAX_PAYLOAD - 1024) return null;
3768
+ const slot = { open: true, messages: null };
3769
+ inst.rewrite = slot;
3770
+ const r = await this.hook(inst, "onAssembled", { messages: view }, left);
3771
+ slot.open = false;
3772
+ if (inst.rewrite === slot) inst.rewrite = null;
3773
+ if (!r.ok || !slot.messages) return null;
3774
+ const out = applyRewrite(cur, slot.messages);
3775
+ return out.changed ? { messages: out.messages } : null;
3776
+ }
3777
+ async replyDone(text, turn) {
3778
+ const end = Date.now() + HOOK_DEADLINE_MS;
3779
+ const inst = this.inst;
3780
+ if (!text.trim()) return { text, by: [], raw: text };
3781
+ const left = end - Date.now();
3782
+ if (!inst || left <= 0 || !this.takes(inst, "onReplyDone", "chat.read", "reply.transform")) return { text, by: [], raw: text };
3783
+ const slot = { open: true, base: text, text: null };
3784
+ inst.transform = slot;
3785
+ const r = await this.hook(inst, "onReplyDone", { text, ...turn }, left);
3786
+ slot.open = false;
3787
+ if (inst.transform === slot) inst.transform = null;
3788
+ return r.ok && slot.text !== null && slot.text !== text ? { text: slot.text, by: [this.name], raw: text } : { text, by: [], raw: text };
3789
+ }
3790
+ streaming(text) {
3791
+ const now = Date.now();
3792
+ const inst = this.inst;
3793
+ if (!inst || inst.replyBusy || now - inst.replyAt < REPLY_EVERY_MS || !this.takes(inst, "onReply", "chat.read", "reply.transform")) return;
3794
+ inst.replyBusy = true;
3795
+ inst.replyAt = now;
3796
+ void this.hook(inst, "onReply", { text }, HOOK_DEADLINE_MS).finally(() => {
3797
+ inst.replyBusy = false;
3798
+ });
3799
+ }
3800
+ /** A click in one of its posts (onWidget) or its panel (onPanel), user-started like a command. */
3801
+ async userHook(extId, hook, args) {
3802
+ const inst = this.inst;
3803
+ if (!inst || extId !== this.m.id) return false;
3804
+ const n = this.name;
3805
+ if (this.paused) {
3806
+ this.b.notice(`${n} is paused in this chat.`, void 0, n);
3807
+ return true;
3808
+ }
3809
+ const r = await this.hook(inst, hook, args, this.userDeadline());
3810
+ if (!r.ok && r.error !== "denied" && r.error !== "no_hook") this.b.notice(`${n} did not finish handling that.`, void 0, n);
3811
+ return true;
3812
+ }
3813
+ runWidget(extId, w) {
3814
+ return this.userHook(extId, "onWidget", w);
3815
+ }
3816
+ runPanel(extId, ev) {
3817
+ return this.userHook(extId, "onPanel", ev.on === void 0 ? { id: ev.id } : { id: ev.id, on: ev.on });
3818
+ }
3819
+ // ----------------------------------------------------------------------------------------------- P6b ---
3820
+ async restyle(items) {
3821
+ let fresh = 0;
3822
+ for (const it of items) {
3823
+ const k = `${it.role}
3824
+ ${it.text}`;
3825
+ if (this.shown.has(k) || !it.text.trim() || it.text.length > RENDER_MAX || fresh >= RENDER_BATCH) continue;
3826
+ fresh++;
3827
+ let cur = it.text;
3828
+ const by = [];
3829
+ const inst = this.inst;
3830
+ if (inst && this.takes(inst, "onRender", "render.transform")) {
3831
+ const r = await this.hook(inst, "onRender", { text: cur, role: it.role }, RENDER_DEADLINE_MS);
3832
+ if (r.ok && typeof r.value === "string" && r.value !== cur && r.value.length <= RENDER_MAX && !addsSyntax(cur, r.value)) {
3833
+ cur = r.value;
3834
+ by.push(this.name);
3835
+ }
3836
+ }
3837
+ this.shown.set(k, by.length ? { text: cur, by } : null);
3838
+ }
3839
+ const out = /* @__PURE__ */ new Map();
3840
+ for (const it of items) {
3841
+ const k = `${it.role}
3842
+ ${it.text}`;
3843
+ const v = this.shown.get(k);
3844
+ if (v) out.set(k, v);
3845
+ }
3846
+ return out;
3847
+ }
3848
+ async resolveMacros(turn) {
3849
+ const end = Date.now() + HOOK_DEADLINE_MS;
3850
+ const values = {};
3851
+ const done = [];
3852
+ const inst = this.inst;
3853
+ if (inst && this.macroNames.length && this.takes(inst, "onMacro", "prompt.macro")) {
3854
+ for (const name of this.macroNames) {
3855
+ const left = Math.min(MACRO_DEADLINE_MS, end - Date.now());
3856
+ let v = "";
3857
+ if (left > 0) {
3858
+ const r = await this.hook(inst, "onMacro", { name, ...turn }, left);
3859
+ if (r.ok && typeof r.value === "string") v = r.value.slice(0, MACRO_MAX);
3860
+ }
3861
+ values[`ext.${name}`] = v ? codeBlock(v) : "";
3862
+ if (v) done.push(`{{ext.${name}}}`);
3863
+ }
3864
+ }
3865
+ return Object.keys(values).length ? { values, note: done.length ? `Macros from ${this.name}: ${done.join(", ")}` : "" } : null;
3866
+ }
3867
+ takeParams() {
3868
+ const a = this.genReq;
3869
+ this.genReq = null;
3870
+ if (!a || !this.inst || this.paused) return null;
3871
+ const list = Object.entries(a).map(([k, v]) => `${k} ${v}`).join(", ");
3872
+ return { fields: toFields(a), note: `Samplers from ${this.name}: ${list}` };
3873
+ }
3874
+ emitStyles() {
3875
+ const chat = this.stopped ? void 0 : this.styles.chat;
3876
+ this.b.style?.(chat ? { cls: `${EXT_STYLED_CLASS} ${extChatClass(this.m.id)}`, css: `${chat}
3877
+ ` } : { cls: "", css: "" });
3878
+ }
3879
+ p6bOps(inst) {
3880
+ const m = this.m;
3881
+ const set = (k, css2) => {
3882
+ if (inst.dead) return;
3883
+ const s = { ...this.styles };
3884
+ if (css2?.trim()) s[k] = css2;
3885
+ else delete s[k];
3886
+ this.styles = s;
3887
+ this.emitStyles();
3888
+ };
3889
+ return {
3890
+ style: (css2) => set("chat", css2),
3891
+ partStyle: (css2) => {
3892
+ if (!m.permissions.some((p) => p.startsWith("ui.") && p !== "ui.settings" && p !== "ui.command")) return false;
3893
+ set("parts", css2);
3894
+ return true;
3895
+ },
3896
+ theme: async (theme) => {
3897
+ await this.d.offerTheme(m.id, m.name, theme);
3898
+ },
3899
+ generate: async (kind) => {
3900
+ if (!this.b.generate || !this.userStarted(inst) || inst.generated) return false;
3901
+ await this.d.charge(m.id);
3902
+ inst.generated = this.b.generate(kind);
3903
+ return inst.generated;
3904
+ },
3905
+ macro: (name) => {
3906
+ if (inst.dead) return false;
3907
+ if (this.macroNames.includes(name)) return true;
3908
+ if (this.macroNames.length >= MAX_MACROS) return false;
3909
+ this.macroNames = [...this.macroNames, name];
3910
+ return true;
3911
+ },
3912
+ params: async (p) => {
3913
+ if (!p) {
3914
+ this.genReq = null;
3915
+ return {};
3916
+ }
3917
+ const ranges = (await this.d.genRanges())[m.id] ?? {};
3918
+ const { applied } = clampParams(p, ranges);
3919
+ this.genReq = Object.keys(applied).length ? applied : null;
3920
+ return applied;
3921
+ }
3922
+ };
3923
+ }
3924
+ // ----------------------------------------------------------------------------------------- P6a (UI) ---
3925
+ /** The extension's surfaces (surfaces.ts ExtSurfaces), null until it draws any. */
3926
+ surface = null;
3927
+ uiQueued = false;
3928
+ updateUi(fn) {
3929
+ fn(this.surface ??= { panel: null, hud: [], notes: /* @__PURE__ */ new Map(), choices: [] });
3930
+ this.uiChanged();
3931
+ }
3932
+ /** Coalesced, like ExtSurfaces: one snapshot after the changes of one task. */
3933
+ uiChanged() {
3934
+ if (this.uiQueued) return;
3935
+ this.uiQueued = true;
3936
+ queueMicrotask(() => {
3937
+ if (!this.uiQueued) return;
3938
+ this.uiQueued = false;
3939
+ this.b.onUi?.(this.uiSnapshot());
3940
+ });
3941
+ }
3942
+ uiSnapshot() {
3943
+ const s = { panels: [], hud: [], notes: {}, choices: [] };
3944
+ const p = this.surface;
3945
+ const ext = this.m.id, name = this.name;
3946
+ if (p) {
3947
+ if (p.panel) s.panels.push({ ext, name, panel: p.panel });
3948
+ for (const e of p.hud) s.hud.push({ ...hudItem(ext, e), ext, name });
3949
+ for (const [key, n] of p.notes) (s.notes[key] ??= []).push({ ext, name, ...n });
3950
+ for (const c of p.choices) s.choices.push({ ...c, ext, name });
3951
+ }
3952
+ return !s.panels.length && !s.hud.length && !s.choices.length && !Object.keys(s.notes).length ? null : s;
3953
+ }
3954
+ clearUi() {
3955
+ this.surface = null;
3956
+ this.uiQueued = false;
3957
+ this.b.onUi?.(null);
3958
+ }
3959
+ /** The instance stopped: its surfaces, styles, macros and sounds go with it. */
3960
+ dropUi() {
3961
+ if (this.styles.chat || this.styles.parts) {
3962
+ this.styles = {};
3963
+ this.emitStyles();
3964
+ }
3965
+ this.macroNames = [];
3966
+ this.shown.clear();
3967
+ if (this.surface) {
3968
+ this.surface = null;
3969
+ this.uiChanged();
3970
+ }
3971
+ this.stopSounds();
3972
+ }
3973
+ /** Sliding-window counts (surfaces.ts underRate). */
3974
+ underRate(key, max, windowMs) {
3975
+ const now = Date.now();
3976
+ const recent = (this.rates.get(key) ?? []).filter((at) => now - at < windowMs);
3977
+ if (recent.length >= max) {
3978
+ this.rates.set(key, recent);
3979
+ return false;
3980
+ }
3981
+ this.rates.set(key, [...recent, now]);
3982
+ return true;
3983
+ }
3984
+ uiOps(inst) {
3985
+ const m = this.m;
3986
+ return {
3987
+ panel: (p) => this.updateUi((s) => {
3988
+ s.panel = p;
3989
+ }),
3990
+ hud: (items) => this.updateUi((s) => {
3991
+ s.hud = items;
3992
+ }),
3993
+ annotate: (n) => {
3994
+ const key = this.b.messageKey?.(n.back) ?? null;
3995
+ if (!key) return false;
3996
+ this.updateUi((s) => {
3997
+ s.notes.delete(key);
3998
+ if (n.text.trim()) s.notes.set(key, { title: n.title, text: n.text, badge: n.badge });
3999
+ while (s.notes.size > NOTES_PER_EXT) s.notes.delete(s.notes.keys().next().value);
4000
+ });
4001
+ return true;
4002
+ },
4003
+ choices: (c) => {
4004
+ if (c.some((x) => x.send) && !m.permissions.includes("chat.send")) throw new CapabilityError("denied");
4005
+ if (c.some((x) => x.send && /^\s*\//.test(x.text))) throw new CapabilityError("bad_request");
4006
+ this.updateUi((s) => {
4007
+ s.choices = c.map((x) => ({ ...x, text: inertPost(x.text, false) }));
4008
+ });
4009
+ },
4010
+ draft: (text) => {
4011
+ if (!this.b.draft || !this.userStarted(inst)) return false;
4012
+ this.b.draft(inertPost(text, false));
4013
+ return true;
4014
+ },
4015
+ notify: (text) => {
4016
+ if (!this.underRate("notify", NOTIFY_PER_WINDOW, NOTIFY_WINDOW_MS)) throw new CapabilityError("too_many_requests");
4017
+ const n = this.name;
4018
+ this.b.notice(`${n}: ${text}`, `ext-notify:${m.id}:${++notifySeq}`, n);
4019
+ },
4020
+ play: (name, o) => this.play(name, o),
4021
+ stop: (name) => this.stopSounds(name),
4022
+ speak: async (text) => {
4023
+ if (!this.b.speak) return false;
4024
+ if (!this.underRate("speak", SPEAK_PER_MINUTE, 6e4)) throw new CapabilityError("too_many_requests");
4025
+ return this.b.speak(text);
4026
+ }
4027
+ };
4028
+ }
4029
+ // ----------------------------------------------------------------------------------------- sounds ---
4030
+ sounds = /* @__PURE__ */ new Set();
4031
+ soundUrls = /* @__PURE__ */ new Map();
4032
+ /** surfaces.ts playSound: a package file (checked where Rust's ext_asset checks it), at most SOUNDS_AT_ONCE. */
4033
+ async play(name, o) {
4034
+ const audio = this.d.audio;
4035
+ if (this.sounds.size >= SOUNDS_AT_ONCE) throw new CapabilityError("too_many_requests");
4036
+ let url = this.soundUrls.get(name);
4037
+ if (!url) {
4038
+ const kind = name.slice(name.lastIndexOf(".") + 1).toLowerCase();
4039
+ url = audio.asset(this.m.id, name).then((b64) => audio.url(Buffer.from(b64, "base64"), MIME[kind] ?? "application/octet-stream"));
4040
+ this.soundUrls.set(name, url);
4041
+ url.catch(() => this.soundUrls.delete(name));
4042
+ }
4043
+ const u = await url.catch(() => {
4044
+ throw new CapabilityError("bad_request");
4045
+ });
4046
+ const el = audio.make(u);
4047
+ const s = { name, el };
4048
+ el.loop = o.loop;
4049
+ el.volume = Math.max(0, Math.min(1, o.volume * VOLUME));
4050
+ this.sounds.add(s);
4051
+ el.onended = () => void this.sounds.delete(s);
4052
+ try {
4053
+ await el.play();
4054
+ } catch {
4055
+ this.sounds.delete(s);
4056
+ return false;
4057
+ }
4058
+ return true;
4059
+ }
4060
+ stopSounds(name) {
4061
+ for (const s of [...this.sounds]) {
4062
+ if (name !== void 0 && s.name !== name) continue;
4063
+ s.el.pause();
4064
+ this.sounds.delete(s);
4065
+ }
4066
+ }
4067
+ // ----------------------------------------------------------------------------------------- network ---
4068
+ /** net.ts netOps: Rust (fake-net.ts) decides; this carries the request, asks the user through the review, keeps
4069
+ * the log, and confirms open.url. User-started calls run one at a time, under host.hold. */
4070
+ netFor(inst) {
4071
+ const m = this.m;
4072
+ let chain = Promise.resolve();
4073
+ const serial2 = (fn) => {
4074
+ const next = chain.then(fn, fn);
4075
+ chain = next.catch(() => void 0);
4076
+ return next;
4077
+ };
4078
+ let declined = 0;
4079
+ const alive = () => !inst.dead && !this.stopped;
4080
+ const scopes = [`chat:${this.b.chatId}`];
4081
+ const call = (cmd, args) => this.d.rust(cmd, args).catch((e) => {
4082
+ throw new CapabilityError(netCode(String(e)));
4083
+ });
4084
+ const log = (o) => {
4085
+ if (!o.log) return;
4086
+ const list = netLogs.get(m.id) ?? [];
4087
+ list.push({ ...o.log, scope: scopes[0] });
4088
+ if (list.length > NET_LOG_MAX) list.splice(0, list.length - NET_LOG_MAX);
4089
+ netLogs.set(m.id, list);
4090
+ };
4091
+ const request = async (req, user) => {
4092
+ let o = await call("ext_net_request", { id: m.id, chatId: this.b.chatId, scopes, userStarted: user, request: req });
4093
+ log(o);
4094
+ if (o.review) {
4095
+ const answer = await this.d.review({ extName: m.name, unreviewed: true, plan: o.review.plan, scopeLabel: "in this chat", chat: this.b.read().messages.map((x) => x.text) }, alive);
4096
+ if (!alive()) throw new CapabilityError("denied");
4097
+ o = await call("ext_net_answer", { id: m.id, planId: o.review.planId, answer });
4098
+ log(o);
4099
+ }
4100
+ if (o.streakBlocked) {
4101
+ this.b.notice(`You denied ${m.name} three times in a row, so its network requests are blocked in this chat until you change its network setting.`, `ext-net-blocked:${this.b.chatId}
4102
+ ${m.id}`, this.name);
4103
+ }
4104
+ if (o.error || !o.response) throw new CapabilityError(netCode(o.error ?? ""));
4105
+ return o.response;
4106
+ };
4107
+ return {
4108
+ request: (req) => this.userStarted(inst) ? inst.host.hold(serial2(() => request(req, true))) : request(req, false),
4109
+ open: async (url) => {
4110
+ if (!this.userStarted(inst) || declined >= OPEN_DECLINES) throw new CapabilityError("denied");
4111
+ let u;
4112
+ try {
4113
+ u = new URL(url);
4114
+ } catch {
4115
+ throw new CapabilityError("bad_request");
4116
+ }
4117
+ if (u.protocol !== "https:" && u.protocol !== "http:" || u.username || u.password) throw new CapabilityError("bad_request");
4118
+ return inst.host.hold(serial2(async () => {
4119
+ const ok = await this.d.confirmOpen({ extName: m.name, unreviewed: true, url: u.href }, alive) && alive();
4120
+ declined = ok ? 0 : declined + 1;
4121
+ if (ok) await this.d.openUrl(u.href);
4122
+ return ok;
4123
+ }));
4124
+ }
4125
+ };
4126
+ }
4127
+ }
4128
+ const kit = runner({ make: (b, d, manifest) => new KitRuntime(b, d, manifest), netLog: kitNetLog, clearNetLog: clearKitNetLog });
4129
+ const { harness, runTests } = kit;
4130
+ main(runTests);
4131
+ const moduleES6BEMUI = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4132
+ __proto__: null,
4133
+ QuickJSModuleCallbacks,
4134
+ QuickJSWASMModule,
4135
+ applyBaseRuntimeOptions,
4136
+ applyModuleEvalRuntimeOptions
4137
+ }, Symbol.toStringTag, { value: "Module" }));
4138
+ var QuickJSFFI = class {
4139
+ constructor(module) {
4140
+ this.module = module;
4141
+ this.DEBUG = false;
4142
+ this.QTS_Throw = this.module.cwrap("QTS_Throw", "number", ["number", "number"]);
4143
+ this.QTS_NewError = this.module.cwrap("QTS_NewError", "number", ["number"]);
4144
+ this.QTS_RuntimeSetMemoryLimit = this.module.cwrap("QTS_RuntimeSetMemoryLimit", null, ["number", "number"]);
4145
+ this.QTS_RuntimeComputeMemoryUsage = this.module.cwrap("QTS_RuntimeComputeMemoryUsage", "number", ["number", "number"]);
4146
+ this.QTS_RuntimeDumpMemoryUsage = this.module.cwrap("QTS_RuntimeDumpMemoryUsage", "number", ["number"]);
4147
+ this.QTS_RecoverableLeakCheck = this.module.cwrap("QTS_RecoverableLeakCheck", "number", []);
4148
+ this.QTS_BuildIsSanitizeLeak = this.module.cwrap("QTS_BuildIsSanitizeLeak", "number", []);
4149
+ this.QTS_RuntimeSetMaxStackSize = this.module.cwrap("QTS_RuntimeSetMaxStackSize", null, ["number", "number"]);
4150
+ this.QTS_GetUndefined = this.module.cwrap("QTS_GetUndefined", "number", []);
4151
+ this.QTS_GetNull = this.module.cwrap("QTS_GetNull", "number", []);
4152
+ this.QTS_GetFalse = this.module.cwrap("QTS_GetFalse", "number", []);
4153
+ this.QTS_GetTrue = this.module.cwrap("QTS_GetTrue", "number", []);
4154
+ this.QTS_NewHostRef = this.module.cwrap("QTS_NewHostRef", "number", ["number", "number"]);
4155
+ this.QTS_GetHostRefId = this.module.cwrap("QTS_GetHostRefId", "number", ["number"]);
4156
+ this.QTS_NewRuntime = this.module.cwrap("QTS_NewRuntime", "number", []);
4157
+ this.QTS_FreeRuntime = this.module.cwrap("QTS_FreeRuntime", null, ["number"]);
4158
+ this.QTS_NewContext = this.module.cwrap("QTS_NewContext", "number", ["number", "number"]);
4159
+ this.QTS_FreeContext = this.module.cwrap("QTS_FreeContext", null, ["number"]);
4160
+ this.QTS_FreeValuePointer = this.module.cwrap("QTS_FreeValuePointer", null, ["number", "number"]);
4161
+ this.QTS_FreeValuePointerRuntime = this.module.cwrap("QTS_FreeValuePointerRuntime", null, ["number", "number"]);
4162
+ this.QTS_FreeVoidPointer = this.module.cwrap("QTS_FreeVoidPointer", null, ["number", "number"]);
4163
+ this.QTS_FreeCString = this.module.cwrap("QTS_FreeCString", null, ["number", "number"]);
4164
+ this.QTS_DupValuePointer = this.module.cwrap("QTS_DupValuePointer", "number", ["number", "number"]);
4165
+ this.QTS_NewObject = this.module.cwrap("QTS_NewObject", "number", ["number"]);
4166
+ this.QTS_NewObjectProto = this.module.cwrap("QTS_NewObjectProto", "number", ["number", "number"]);
4167
+ this.QTS_NewArray = this.module.cwrap("QTS_NewArray", "number", ["number"]);
4168
+ this.QTS_NewArrayBuffer = this.module.cwrap("QTS_NewArrayBuffer", "number", ["number", "number", "number"]);
4169
+ this.QTS_NewFloat64 = this.module.cwrap("QTS_NewFloat64", "number", ["number", "number"]);
4170
+ this.QTS_GetFloat64 = this.module.cwrap("QTS_GetFloat64", "number", ["number", "number"]);
4171
+ this.QTS_NewString = this.module.cwrap("QTS_NewString", "number", ["number", "number"]);
4172
+ this.QTS_GetString = this.module.cwrap("QTS_GetString", "number", ["number", "number"]);
4173
+ this.QTS_GetArrayBuffer = this.module.cwrap("QTS_GetArrayBuffer", "number", ["number", "number"]);
4174
+ this.QTS_GetArrayBufferLength = this.module.cwrap("QTS_GetArrayBufferLength", "number", ["number", "number"]);
4175
+ this.QTS_NewSymbol = this.module.cwrap("QTS_NewSymbol", "number", ["number", "number", "number"]);
4176
+ this.QTS_GetSymbolDescriptionOrKey = this.module.cwrap("QTS_GetSymbolDescriptionOrKey", "number", ["number", "number"]);
4177
+ this.QTS_IsGlobalSymbol = this.module.cwrap("QTS_IsGlobalSymbol", "number", ["number", "number"]);
4178
+ this.QTS_IsJobPending = this.module.cwrap("QTS_IsJobPending", "number", ["number"]);
4179
+ this.QTS_ExecutePendingJob = this.module.cwrap("QTS_ExecutePendingJob", "number", ["number", "number", "number"]);
4180
+ this.QTS_GetProp = this.module.cwrap("QTS_GetProp", "number", ["number", "number", "number"]);
4181
+ this.QTS_GetPropNumber = this.module.cwrap("QTS_GetPropNumber", "number", ["number", "number", "number"]);
4182
+ this.QTS_SetProp = this.module.cwrap("QTS_SetProp", null, ["number", "number", "number", "number"]);
4183
+ this.QTS_DefineProp = this.module.cwrap("QTS_DefineProp", null, ["number", "number", "number", "number", "number", "number", "boolean", "boolean", "boolean"]);
4184
+ this.QTS_GetOwnPropertyNames = this.module.cwrap("QTS_GetOwnPropertyNames", "number", ["number", "number", "number", "number", "number"]);
4185
+ this.QTS_Call = this.module.cwrap("QTS_Call", "number", ["number", "number", "number", "number", "number"]);
4186
+ this.QTS_ResolveException = this.module.cwrap("QTS_ResolveException", "number", ["number", "number"]);
4187
+ this.QTS_Dump = this.module.cwrap("QTS_Dump", "number", ["number", "number"]);
4188
+ this.QTS_Eval = this.module.cwrap("QTS_Eval", "number", ["number", "number", "number", "string", "number", "number"]);
4189
+ this.QTS_GetModuleNamespace = this.module.cwrap("QTS_GetModuleNamespace", "number", ["number", "number"]);
4190
+ this.QTS_Typeof = this.module.cwrap("QTS_Typeof", "number", ["number", "number"]);
4191
+ this.QTS_GetLength = this.module.cwrap("QTS_GetLength", "number", ["number", "number", "number"]);
4192
+ this.QTS_IsEqual = this.module.cwrap("QTS_IsEqual", "number", ["number", "number", "number", "number"]);
4193
+ this.QTS_GetGlobalObject = this.module.cwrap("QTS_GetGlobalObject", "number", ["number"]);
4194
+ this.QTS_NewPromiseCapability = this.module.cwrap("QTS_NewPromiseCapability", "number", ["number", "number"]);
4195
+ this.QTS_PromiseState = this.module.cwrap("QTS_PromiseState", "number", ["number", "number"]);
4196
+ this.QTS_PromiseResult = this.module.cwrap("QTS_PromiseResult", "number", ["number", "number"]);
4197
+ this.QTS_TestStringArg = this.module.cwrap("QTS_TestStringArg", null, ["string"]);
4198
+ this.QTS_GetDebugLogEnabled = this.module.cwrap("QTS_GetDebugLogEnabled", "number", ["number"]);
4199
+ this.QTS_SetDebugLogEnabled = this.module.cwrap("QTS_SetDebugLogEnabled", null, ["number", "number"]);
4200
+ this.QTS_BuildIsDebug = this.module.cwrap("QTS_BuildIsDebug", "number", []);
4201
+ this.QTS_BuildIsAsyncify = this.module.cwrap("QTS_BuildIsAsyncify", "number", []);
4202
+ this.QTS_NewFunction = this.module.cwrap("QTS_NewFunction", "number", ["number", "string", "number", "boolean", "number"]);
4203
+ this.QTS_ArgvGetJSValueConstPointer = this.module.cwrap("QTS_ArgvGetJSValueConstPointer", "number", ["number", "number"]);
4204
+ this.QTS_RuntimeEnableInterruptHandler = this.module.cwrap("QTS_RuntimeEnableInterruptHandler", null, ["number"]);
4205
+ this.QTS_RuntimeDisableInterruptHandler = this.module.cwrap("QTS_RuntimeDisableInterruptHandler", null, ["number"]);
4206
+ this.QTS_RuntimeEnableModuleLoader = this.module.cwrap("QTS_RuntimeEnableModuleLoader", null, ["number", "number"]);
4207
+ this.QTS_RuntimeDisableModuleLoader = this.module.cwrap("QTS_RuntimeDisableModuleLoader", null, ["number"]);
4208
+ this.QTS_bjson_encode = this.module.cwrap("QTS_bjson_encode", "number", ["number", "number"]);
4209
+ this.QTS_bjson_decode = this.module.cwrap("QTS_bjson_decode", "number", ["number", "number"]);
4210
+ }
4211
+ };
4212
+ const ffi = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4213
+ __proto__: null,
4214
+ QuickJSFFI
4215
+ }, Symbol.toStringTag, { value: "Module" }));
4216
+ async function QuickJSRaw(moduleArg = {}) {
4217
+ var moduleRtn;
4218
+ var d = moduleArg, aa = !!globalThis.window, n = !!globalThis.WorkerGlobalScope, q = globalThis.process?.versions?.node && "renderer" != globalThis.process?.type;
4219
+ if (q) {
4220
+ const { createRequire: a } = await import("node:module");
4221
+ var require2 = a(import.meta.url);
4222
+ }
4223
+ function r(a) {
4224
+ a = { log: a || function() {
4225
+ } };
4226
+ for (const c of r.Pa) c(a);
4227
+ return d.quickJSEmscriptenExtensions = a;
4228
+ }
4229
+ r.Pa = [];
4230
+ d.quickjsEmscriptenInit = r;
4231
+ r.Pa.push((a) => {
4232
+ a.getWasmMemory = function() {
4233
+ return t;
4234
+ };
4235
+ });
4236
+ var u = "./this.program", v = (a, c) => {
4237
+ throw c;
4238
+ }, w = import.meta.url, y = "", z, A;
4239
+ if (q) {
4240
+ var fs = require2("node:fs");
4241
+ w.startsWith("file:") && (y = require2("node:path").dirname(require2("node:url").fileURLToPath(w)) + "/");
4242
+ A = (a) => {
4243
+ a = B(a) ? new URL(a) : a;
4244
+ return fs.readFileSync(a);
4245
+ };
4246
+ z = async (a) => {
4247
+ a = B(a) ? new URL(a) : a;
4248
+ return fs.readFileSync(a, void 0);
4249
+ };
4250
+ 1 < process.argv.length && (u = process.argv[1].replace(/\\/g, "/"));
4251
+ process.argv.slice(2);
4252
+ v = (a, c) => {
4253
+ process.exitCode = a;
4254
+ throw c;
4255
+ };
4256
+ } else if (aa || n) {
4257
+ try {
4258
+ y = new URL(".", w).href;
4259
+ } catch {
4260
+ }
4261
+ n && (A = (a) => {
4262
+ var c = new XMLHttpRequest();
4263
+ c.open("GET", a, false);
4264
+ c.responseType = "arraybuffer";
4265
+ c.send(null);
4266
+ return new Uint8Array(c.response);
4267
+ });
4268
+ z = async (a) => {
4269
+ if (B(a)) return new Promise((b, e) => {
4270
+ var f = new XMLHttpRequest();
4271
+ f.open("GET", a, true);
4272
+ f.responseType = "arraybuffer";
4273
+ f.onload = () => {
4274
+ 200 == f.status || 0 == f.status && f.response ? b(f.response) : e(f.status);
4275
+ };
4276
+ f.onerror = e;
4277
+ f.send(null);
4278
+ });
4279
+ var c = await fetch(a, { credentials: "same-origin" });
4280
+ if (c.ok) return c.arrayBuffer();
4281
+ throw Error(c.status + " : " + c.url);
4282
+ };
4283
+ }
4284
+ var C = console.log.bind(console), D = console.error.bind(console), E, F = false, G, B = (a) => a.startsWith("file://"), H, I, J, K, L, M, ba = false;
4285
+ function ca() {
4286
+ var a = t.buffer;
4287
+ d.HEAP8 = J = new Int8Array(a);
4288
+ d.HEAPU8 = K = new Uint8Array(a);
4289
+ L = new Int32Array(a);
4290
+ M = new Uint32Array(a);
4291
+ new BigInt64Array(a);
4292
+ new BigUint64Array(a);
4293
+ }
4294
+ function N2(a) {
4295
+ d.onAbort?.(a);
4296
+ a = "Aborted(" + a + ")";
4297
+ D(a);
4298
+ F = true;
4299
+ a = new WebAssembly.RuntimeError(a + ". Build with -sASSERTIONS for more info.");
4300
+ I?.(a);
4301
+ throw a;
4302
+ }
4303
+ var O;
4304
+ async function da(a) {
4305
+ if (!E) try {
4306
+ var c = await z(a);
4307
+ return new Uint8Array(c);
4308
+ } catch {
4309
+ }
4310
+ if (a == O && E) a = new Uint8Array(E);
4311
+ else if (A) a = A(a);
4312
+ else throw "both async and sync fetching of the wasm failed";
4313
+ return a;
4314
+ }
4315
+ async function ea(a, c) {
4316
+ try {
4317
+ var b = await da(a);
4318
+ return await WebAssembly.instantiate(b, c);
4319
+ } catch (e) {
4320
+ D(`failed to asynchronously prepare wasm: ${e}`), N2(e);
4321
+ }
4322
+ }
4323
+ async function fa(a) {
4324
+ var c = O;
4325
+ if (!E && !B(c) && !q) try {
4326
+ var b = fetch(c, { credentials: "same-origin" });
4327
+ return await WebAssembly.instantiateStreaming(b, a);
4328
+ } catch (e) {
4329
+ D(`wasm streaming compile failed: ${e}`), D("falling back to ArrayBuffer instantiation");
4330
+ }
4331
+ return ea(c, a);
4332
+ }
4333
+ class P {
4334
+ name = "ExitStatus";
4335
+ constructor(a) {
4336
+ this.message = `Program terminated with exit(${a})`;
4337
+ this.status = a;
4338
+ }
4339
+ }
4340
+ var ha = (a) => {
4341
+ for (; 0 < a.length; ) a.shift()(d);
4342
+ }, ia = [], ja = [], ka = () => {
4343
+ var a = d.preRun.shift();
4344
+ ja.push(a);
4345
+ }, Q = true, t, la = new TextDecoder(), ma = (a, c, b, e) => {
4346
+ b = c + b;
4347
+ if (e) return b;
4348
+ for (; a[c] && !(c >= b); ) ++c;
4349
+ return c;
4350
+ }, R2 = (a, c, b) => a ? la.decode(K.subarray(a, ma(K, a, c, b))) : "", S = 0, na = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], oa = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], T = {}, pa = (a) => {
4351
+ G = a;
4352
+ Q || 0 < S || (d.onExit?.(a), F = true);
4353
+ v(a, new P(a));
4354
+ }, qa = (a) => {
4355
+ if (!F) try {
4356
+ a();
4357
+ } catch (c) {
4358
+ c instanceof P || "unwind" == c || v(1, c);
4359
+ } finally {
4360
+ if (!(Q || 0 < S)) try {
4361
+ G = a = G, pa(a);
4362
+ } catch (c) {
4363
+ c instanceof P || "unwind" == c || v(1, c);
4364
+ }
4365
+ }
4366
+ }, U = (a, c, b) => {
4367
+ var e = K;
4368
+ if (!(0 < b)) return 0;
4369
+ var f = c;
4370
+ b = c + b - 1;
4371
+ for (var g = 0; g < a.length; ++g) {
4372
+ var h = a.codePointAt(g);
4373
+ if (127 >= h) {
4374
+ if (c >= b) break;
4375
+ e[c++] = h;
4376
+ } else if (2047 >= h) {
4377
+ if (c + 1 >= b) break;
4378
+ e[c++] = 192 | h >> 6;
4379
+ e[c++] = 128 | h & 63;
4380
+ } else if (65535 >= h) {
4381
+ if (c + 2 >= b) break;
4382
+ e[c++] = 224 | h >> 12;
4383
+ e[c++] = 128 | h >> 6 & 63;
4384
+ e[c++] = 128 | h & 63;
4385
+ } else {
4386
+ if (c + 3 >= b) break;
4387
+ e[c++] = 240 | h >> 18;
4388
+ e[c++] = 128 | h >> 12 & 63;
4389
+ e[c++] = 128 | h >> 6 & 63;
4390
+ e[c++] = 128 | h & 63;
4391
+ g++;
4392
+ }
4393
+ }
4394
+ e[c] = 0;
4395
+ return c - f;
4396
+ }, V = {}, ra = () => {
4397
+ if (!W) {
4398
+ var a = {
4399
+ USER: "web_user",
4400
+ LOGNAME: "web_user",
4401
+ PATH: "/",
4402
+ PWD: "/",
4403
+ HOME: "/home/web_user",
4404
+ LANG: (globalThis.navigator?.language ?? "C").replace("-", "_") + ".UTF-8",
4405
+ _: u || "./this.program"
4406
+ }, c;
4407
+ for (c in V) void 0 === V[c] ? delete a[c] : a[c] = V[c];
4408
+ var b = [];
4409
+ for (c in a) b.push(`${c}=${a[c]}`);
4410
+ W = b;
4411
+ }
4412
+ return W;
4413
+ }, W, X = (a) => {
4414
+ for (var c = 0, b = 0; b < a.length; ++b) {
4415
+ var e = a.charCodeAt(b);
4416
+ 127 >= e ? c++ : 2047 >= e ? c += 2 : 55296 <= e && 57343 >= e ? (c += 4, ++b) : c += 3;
4417
+ }
4418
+ return c;
4419
+ }, sa = [null, [], []], va = (a, c, b, e) => {
4420
+ var f = { string: (k) => {
4421
+ var l = 0;
4422
+ if (null !== k && void 0 !== k && 0 !== k) {
4423
+ l = X(k) + 1;
4424
+ var p = Y(l);
4425
+ U(
4426
+ k,
4427
+ p,
4428
+ l
4429
+ );
4430
+ l = p;
4431
+ }
4432
+ return l;
4433
+ }, array: (k) => {
4434
+ var l = Y(k.length);
4435
+ J.set(k, l);
4436
+ return l;
4437
+ } };
4438
+ a = d["_" + a];
4439
+ var g = [], h = 0;
4440
+ if (e) for (var m = 0; m < e.length; m++) {
4441
+ var x = f[b[m]];
4442
+ x ? (0 === h && (h = ta()), g[m] = x(e[m])) : g[m] = e[m];
4443
+ }
4444
+ b = a(...g);
4445
+ return b = (function(k) {
4446
+ 0 !== h && ua(h);
4447
+ return "string" === c ? R2(k) : "boolean" === c ? !!k : k;
4448
+ })(b);
4449
+ };
4450
+ d.wasmMemory ? t = d.wasmMemory : t = new WebAssembly.Memory({ initial: (d.INITIAL_MEMORY || 16777216) / 65536, maximum: 32768 });
4451
+ ca();
4452
+ d.noExitRuntime && (Q = d.noExitRuntime);
4453
+ d.print && (C = d.print);
4454
+ d.printErr && (D = d.printErr);
4455
+ d.wasmBinary && (E = d.wasmBinary);
4456
+ d.thisProgram && (u = d.thisProgram);
4457
+ if (d.preInit) for ("function" == typeof d.preInit && (d.preInit = [d.preInit]); 0 < d.preInit.length; ) d.preInit.shift()();
4458
+ d.cwrap = (a, c, b, e) => {
4459
+ var f = !b || b.every((g) => "number" === g || "boolean" === g);
4460
+ return "string" !== c && f && !e ? d["_" + a] : (...g) => va(a, c, b, g);
4461
+ };
4462
+ d.UTF8ToString = R2;
4463
+ d.stringToUTF8 = (a, c, b) => U(a, c, b);
4464
+ d.lengthBytesUTF8 = X;
4465
+ var wa, ua, Y, ta, xa = { b: (a, c, b, e) => N2(`Assertion failed: ${R2(a)}, at: ` + [c ? R2(c) : "unknown filename", b, e ? R2(e) : "unknown function"]), q: () => N2(""), l: () => {
4466
+ Q = false;
4467
+ S = 0;
4468
+ }, m: function(a, c) {
4469
+ a = -9007199254740992 > a || 9007199254740992 < a ? NaN : Number(a);
4470
+ a = new Date(1e3 * a);
4471
+ L[c >> 2] = a.getSeconds();
4472
+ L[c + 4 >> 2] = a.getMinutes();
4473
+ L[c + 8 >> 2] = a.getHours();
4474
+ L[c + 12 >> 2] = a.getDate();
4475
+ L[c + 16 >> 2] = a.getMonth();
4476
+ L[c + 20 >> 2] = a.getFullYear() - 1900;
4477
+ L[c + 24 >> 2] = a.getDay();
4478
+ var b = a.getFullYear();
4479
+ L[c + 28 >> 2] = (0 !== b % 4 || 0 === b % 100 && 0 !== b % 400 ? oa : na)[a.getMonth()] + a.getDate() - 1 | 0;
4480
+ L[c + 36 >> 2] = -(60 * a.getTimezoneOffset());
4481
+ b = new Date(a.getFullYear(), 6, 1).getTimezoneOffset();
4482
+ var e = new Date(a.getFullYear(), 0, 1).getTimezoneOffset();
4483
+ L[c + 32 >> 2] = (b != e && a.getTimezoneOffset() == Math.min(e, b)) | 0;
4484
+ }, j: (a, c) => {
4485
+ T[a] && (clearTimeout(T[a].id), delete T[a]);
4486
+ if (!c) return 0;
4487
+ var b = setTimeout(() => {
4488
+ delete T[a];
4489
+ qa(() => wa(a, performance.now()));
4490
+ }, c);
4491
+ T[a] = { id: b, Qa: c };
4492
+ return 0;
4493
+ }, n: (a, c, b, e) => {
4494
+ var f = (/* @__PURE__ */ new Date()).getFullYear(), g = new Date(f, 0, 1).getTimezoneOffset();
4495
+ f = new Date(f, 6, 1).getTimezoneOffset();
4496
+ M[a >> 2] = 60 * Math.max(g, f);
4497
+ L[c >> 2] = Number(g != f);
4498
+ c = (h) => {
4499
+ var m = Math.abs(h);
4500
+ return `UTC${0 <= h ? "-" : "+"}${String(Math.floor(m / 60)).padStart(2, "0")}${String(m % 60).padStart(2, "0")}`;
4501
+ };
4502
+ a = c(g);
4503
+ c = c(f);
4504
+ f < g ? (U(a, b, 17), U(c, e, 17)) : (U(a, e, 17), U(c, b, 17));
4505
+ }, p: () => Date.now(), k: (a) => {
4506
+ var c = K.length;
4507
+ a >>>= 0;
4508
+ if (2147483648 < a) return false;
4509
+ for (var b = 1; 4 >= b; b *= 2) {
4510
+ var e = c * (1 + 0.2 / b);
4511
+ e = Math.min(e, a + 100663296);
4512
+ a: {
4513
+ e = (Math.min(2147483648, 65536 * Math.ceil(Math.max(a, e) / 65536)) - t.buffer.byteLength + 65535) / 65536 | 0;
4514
+ try {
4515
+ t.grow(e);
4516
+ ca();
4517
+ var f = 1;
4518
+ break a;
4519
+ } catch (g) {
4520
+ }
4521
+ f = void 0;
4522
+ }
4523
+ if (f) return true;
4524
+ }
4525
+ return false;
4526
+ }, e: (a, c) => {
4527
+ var b = 0, e = 0, f;
4528
+ for (f of ra()) {
4529
+ var g = c + b;
4530
+ M[a + e >> 2] = g;
4531
+ b += U(f, g, Infinity) + 1;
4532
+ e += 4;
4533
+ }
4534
+ return 0;
4535
+ }, f: (a, c) => {
4536
+ var b = ra();
4537
+ M[a >> 2] = b.length;
4538
+ a = 0;
4539
+ for (var e of b) a += X(e) + 1;
4540
+ M[c >> 2] = a;
4541
+ return 0;
4542
+ }, d: () => 52, o: function() {
4543
+ return 70;
4544
+ }, c: (a, c, b, e) => {
4545
+ for (var f = 0, g = 0; g < b; g++) {
4546
+ var h = M[c >> 2], m = M[c + 4 >> 2];
4547
+ c += 8;
4548
+ for (var x = 0; x < m; x++) {
4549
+ var k = a, l = K[h + x], p = sa[k];
4550
+ 0 === l || 10 === l ? (k = 1 === k ? C : D, l = ma(p, 0), l = la.decode(p.buffer ? p.subarray(0, l) : new Uint8Array(p.slice(0, l))), k(l), p.length = 0) : p.push(l);
4551
+ }
4552
+ f += m;
4553
+ }
4554
+ M[e >> 2] = f;
4555
+ return 0;
4556
+ }, a: t, r: pa, s: function(a, c, b, e, f) {
4557
+ return d.callbacks.callFunction(void 0, a, c, b, e, f);
4558
+ }, i: function(a) {
4559
+ return d.callbacks.shouldInterrupt(void 0, a);
4560
+ }, h: function(a, c, b) {
4561
+ b = R2(b);
4562
+ return d.callbacks.loadModuleSource(void 0, a, c, b);
4563
+ }, g: function(a, c, b, e) {
4564
+ b = R2(b);
4565
+ e = R2(e);
4566
+ return d.callbacks.normalizeModule(void 0, a, c, b, e);
4567
+ }, t: function(a, c) {
4568
+ d.callbacks.freeHostRef(void 0, a, c);
4569
+ } }, Z;
4570
+ Z = await (async function() {
4571
+ function a(b) {
4572
+ b = Z = b.exports;
4573
+ d._malloc = b.v;
4574
+ d._QTS_Throw = b.w;
4575
+ d._QTS_NewError = b.x;
4576
+ d._QTS_RuntimeSetMemoryLimit = b.y;
4577
+ d._QTS_RuntimeComputeMemoryUsage = b.z;
4578
+ d._QTS_RuntimeDumpMemoryUsage = b.A;
4579
+ d._QTS_RecoverableLeakCheck = b.B;
4580
+ d._QTS_BuildIsSanitizeLeak = b.C;
4581
+ d._QTS_RuntimeSetMaxStackSize = b.D;
4582
+ d._QTS_GetUndefined = b.E;
4583
+ d._QTS_GetNull = b.F;
4584
+ d._QTS_GetFalse = b.G;
4585
+ d._QTS_GetTrue = b.H;
4586
+ d._QTS_NewHostRef = b.I;
4587
+ d._QTS_GetHostRefId = b.J;
4588
+ d._QTS_NewRuntime = b.K;
4589
+ d._QTS_FreeRuntime = b.L;
4590
+ d._free = b.M;
4591
+ d._QTS_NewContext = b.N;
4592
+ d._QTS_FreeContext = b.O;
4593
+ d._QTS_FreeValuePointer = b.P;
4594
+ d._QTS_FreeValuePointerRuntime = b.Q;
4595
+ d._QTS_FreeVoidPointer = b.R;
4596
+ d._QTS_FreeCString = b.S;
4597
+ d._QTS_DupValuePointer = b.T;
4598
+ d._QTS_NewObject = b.U;
4599
+ d._QTS_NewObjectProto = b.V;
4600
+ d._QTS_NewArray = b.W;
4601
+ d._QTS_NewArrayBuffer = b.X;
4602
+ d._QTS_NewFloat64 = b.Y;
4603
+ d._QTS_GetFloat64 = b.Z;
4604
+ d._QTS_NewString = b._;
4605
+ d._QTS_GetString = b.$;
4606
+ d._QTS_GetArrayBuffer = b.aa;
4607
+ d._QTS_GetArrayBufferLength = b.ba;
4608
+ d._QTS_NewSymbol = b.ca;
4609
+ d._QTS_GetSymbolDescriptionOrKey = b.da;
4610
+ d._QTS_IsGlobalSymbol = b.ea;
4611
+ d._QTS_IsJobPending = b.fa;
4612
+ d._QTS_ExecutePendingJob = b.ga;
4613
+ d._QTS_GetProp = b.ha;
4614
+ d._QTS_GetPropNumber = b.ia;
4615
+ d._QTS_SetProp = b.ja;
4616
+ d._QTS_DefineProp = b.ka;
4617
+ d._QTS_GetOwnPropertyNames = b.la;
4618
+ d._QTS_Call = b.ma;
4619
+ d._QTS_ResolveException = b.na;
4620
+ d._QTS_Dump = b.oa;
4621
+ d._QTS_Eval = b.pa;
4622
+ d._QTS_GetModuleNamespace = b.qa;
4623
+ d._QTS_Typeof = b.ra;
4624
+ d._QTS_GetLength = b.sa;
4625
+ d._QTS_IsEqual = b.ta;
4626
+ d._QTS_GetGlobalObject = b.ua;
4627
+ d._QTS_NewPromiseCapability = b.va;
4628
+ d._QTS_PromiseState = b.wa;
4629
+ d._QTS_PromiseResult = b.xa;
4630
+ d._QTS_TestStringArg = b.ya;
4631
+ d._QTS_GetDebugLogEnabled = b.za;
4632
+ d._QTS_SetDebugLogEnabled = b.Aa;
4633
+ d._QTS_BuildIsDebug = b.Ba;
4634
+ d._QTS_BuildIsAsyncify = b.Ca;
4635
+ d._QTS_NewFunction = b.Da;
4636
+ d._QTS_ArgvGetJSValueConstPointer = b.Ea;
4637
+ d._QTS_RuntimeEnableInterruptHandler = b.Fa;
4638
+ d._QTS_RuntimeDisableInterruptHandler = b.Ga;
4639
+ d._QTS_RuntimeEnableModuleLoader = b.Ha;
4640
+ d._QTS_RuntimeDisableModuleLoader = b.Ia;
4641
+ d._QTS_bjson_encode = b.Ja;
4642
+ d._QTS_bjson_decode = b.Ka;
4643
+ wa = b.La;
4644
+ ua = b.Ma;
4645
+ Y = b.Na;
4646
+ ta = b.Oa;
4647
+ return Z;
4648
+ }
4649
+ var c = { a: xa };
4650
+ if (d.instantiateWasm) return new Promise((b) => {
4651
+ d.instantiateWasm(c, (e, f) => {
4652
+ b(a(e));
4653
+ });
4654
+ });
4655
+ O ??= d.locateFile ? d.locateFile ? d.locateFile("emscripten-module.wasm", y) : y + "emscripten-module.wasm" : new URL("emscripten-module.wasm", import.meta.url).href;
4656
+ return a((await fa(c)).instance);
4657
+ })();
4658
+ (function() {
4659
+ function a() {
4660
+ d.calledRun = true;
4661
+ if (!F) {
4662
+ ba = true;
4663
+ Z.u();
4664
+ H?.(d);
4665
+ d.onRuntimeInitialized?.();
4666
+ if (d.postRun) for ("function" == typeof d.postRun && (d.postRun = [d.postRun]); d.postRun.length; ) {
4667
+ var c = d.postRun.shift();
4668
+ ia.push(c);
4669
+ }
4670
+ ha(ia);
4671
+ }
4672
+ }
4673
+ if (d.preRun) for ("function" == typeof d.preRun && (d.preRun = [d.preRun]); d.preRun.length; ) ka();
4674
+ ha(ja);
4675
+ d.setStatus ? (d.setStatus("Running..."), setTimeout(() => {
4676
+ setTimeout(() => d.setStatus(""), 1);
4677
+ a();
4678
+ }, 1)) : a();
4679
+ })();
4680
+ ba ? moduleRtn = d : moduleRtn = new Promise((a, c) => {
4681
+ H = a;
4682
+ I = c;
4683
+ });
4684
+ return moduleRtn;
4685
+ }
4686
+ const emscriptenModule = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4687
+ __proto__: null,
4688
+ default: QuickJSRaw
4689
+ }, Symbol.toStringTag, { value: "Module" }));
4690
+ export {
4691
+ harness,
4692
+ runTests
4693
+ };