dsh-mobile 0.6.2 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/CONTRIBUTORS.md +19 -4
  3. package/README.en.md +16 -8
  4. package/README.md +16 -8
  5. package/SECURITY.md +3 -2
  6. package/THIRD_PARTY_NOTICES.md +29 -1
  7. package/apps/mobile/README.md +25 -5
  8. package/apps/mobile/release.json +3 -3
  9. package/cordis.patch.yml +7 -3
  10. package/docs/ATTACH_EXISTING_FRPS.en.md +1 -1
  11. package/docs/ATTACH_EXISTING_FRPS.md +2 -2
  12. package/docs/CADDY_MANAGED.en.md +15 -1
  13. package/docs/CADDY_MANAGED.md +15 -1
  14. package/docs/CLOUDFLARE_TUNNEL.en.md +2 -2
  15. package/docs/CLOUDFLARE_TUNNEL.md +3 -3
  16. package/docs/EXTENSION_WORKERS.en.md +49 -0
  17. package/docs/EXTENSION_WORKERS.md +49 -0
  18. package/docs/MOBILE_COMPOSER_TOOLBAR.en.md +27 -0
  19. package/docs/MOBILE_COMPOSER_TOOLBAR.md +27 -0
  20. package/docs/README.md +2 -0
  21. package/docs/SELF_HOSTED_FRP.en.md +4 -2
  22. package/docs/SELF_HOSTED_FRP.md +4 -2
  23. package/docs/SLOW_CONNECTIONS.en.md +6 -0
  24. package/docs/SLOW_CONNECTIONS.md +6 -0
  25. package/docs/TRUSTED_NETWORKS.en.md +1 -1
  26. package/docs/TRUSTED_NETWORKS.md +1 -1
  27. package/lib/cli.js +140 -19
  28. package/lib/cli.js.map +1 -1
  29. package/lib/client.js +1264 -106
  30. package/lib/client.js.map +1 -1
  31. package/lib/extension-worker-runtime.mjs +1646 -0
  32. package/lib/extension-worker-runtime.mjs.map +1 -0
  33. package/lib/index.d.mts +209 -12
  34. package/lib/index.mjs +2152 -811
  35. package/lib/index.mjs.map +1 -1
  36. package/lib/mobile-layout.js.map +1 -1
  37. package/package.json +17 -6
  38. package/packages/question-fixes/LICENSE +201 -0
  39. package/packages/question-fixes/package.json +9 -2
  40. package/node_modules/dsh-mobile-question-fixes/lib/client.js +0 -78
  41. package/node_modules/dsh-mobile-question-fixes/lib/client.js.map +0 -1
  42. package/node_modules/dsh-mobile-question-fixes/lib/index.mjs +0 -14
  43. package/node_modules/dsh-mobile-question-fixes/lib/index.mjs.map +0 -1
  44. package/node_modules/dsh-mobile-question-fixes/package.json +0 -25
@@ -0,0 +1,1646 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import { inspect } from "node:util";
3
+ import { randomUUID } from "node:crypto";
4
+ import { pathToFileURL } from "node:url";
5
+ //#region src/extension-worker-config.ts
6
+ function integer(value, name, fallback, minimum, maximum) {
7
+ const resolved = value ?? fallback;
8
+ if (typeof resolved !== "number" || !Number.isSafeInteger(resolved) || resolved < minimum || resolved > maximum) throw new Error(`hostExecution.${name} must be an integer from ${minimum} through ${maximum}`);
9
+ return resolved;
10
+ }
11
+ /** Resolve configuration once; reject malformed modes, ids and incoherent stream windows. */
12
+ function resolveHostExecution(raw) {
13
+ if (raw !== void 0 && (raw === null || typeof raw !== "object" || Array.isArray(raw))) throw new Error("hostExecution must be an object");
14
+ const value = raw ?? {};
15
+ const mode = value.mode ?? "in-process";
16
+ if (mode !== "worker" && mode !== "in-process") throw new Error("hostExecution.mode is invalid");
17
+ if (value.extensions !== void 0 && (!Array.isArray(value.extensions) || value.extensions.some((id) => typeof id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/u.test(id)) || new Set(value.extensions).size !== value.extensions.length)) throw new Error("hostExecution.extensions must contain unique local extension ids");
18
+ const streamWindowBytes = integer(value.streamWindowBytes, "streamWindowBytes", 262144, 1024, 4194304);
19
+ const streamChunkBytes = integer(value.streamChunkBytes, "streamChunkBytes", 65536, 1024, streamWindowBytes);
20
+ const streamAggregateBytes = integer(value.streamAggregateBytes, "streamAggregateBytes", 1048576, streamWindowBytes, 33554432);
21
+ return Object.freeze({
22
+ mode,
23
+ extensions: value.extensions === void 0 ? void 0 : Object.freeze([...value.extensions]),
24
+ maxWorkers: integer(value.maxWorkers, "maxWorkers", 8, 1, 128),
25
+ maxRegistrations: integer(value.maxRegistrations, "maxRegistrations", 256, 1, 4096),
26
+ maxOldGenerationSizeMb: integer(value.maxOldGenerationSizeMb, "maxOldGenerationSizeMb", 128, 16, 4096),
27
+ maxYoungGenerationSizeMb: integer(value.maxYoungGenerationSizeMb, "maxYoungGenerationSizeMb", 16, 1, 512),
28
+ stackSizeMb: integer(value.stackSizeMb, "stackSizeMb", 4, 1, 64),
29
+ activationTimeoutMs: integer(value.activationTimeoutMs, "activationTimeoutMs", 5e3, 1, 3e5),
30
+ operationTimeoutMs: integer(value.operationTimeoutMs, "operationTimeoutMs", 3e4, 1, 3e5),
31
+ cancelGraceMs: integer(value.cancelGraceMs, "cancelGraceMs", 250, 1, 3e4),
32
+ streamCancelGraceMs: integer(value.streamCancelGraceMs, "streamCancelGraceMs", 1e3, 1, 3e4),
33
+ disposeGraceMs: integer(value.disposeGraceMs, "disposeGraceMs", 2e3, 1, 3e4),
34
+ resultMaxBytes: integer(value.resultMaxBytes, "resultMaxBytes", 4194304, 1024, 4194304),
35
+ streamWindowBytes,
36
+ streamChunkBytes,
37
+ streamAggregateBytes,
38
+ logWindowMs: integer(value.logWindowMs, "logWindowMs", 1e3, 1, 6e4),
39
+ logMessagesPerWindow: integer(value.logMessagesPerWindow, "logMessagesPerWindow", 64, 1, 1024),
40
+ logMessageBytes: integer(value.logMessageBytes, "logMessageBytes", 4096, 128, 65536)
41
+ });
42
+ }
43
+ //#endregion
44
+ //#region node_modules/@deepseek-ai/cosmokit/lib/index.js
45
+ /** Return true when a value is `null` or `undefined`. */
46
+ function isNullable(value) {
47
+ return value === null || value === void 0;
48
+ }
49
+ /** Return true for non-array object values. */
50
+ function isPlainObject(data) {
51
+ return data && typeof data === "object" && !Array.isArray(data);
52
+ }
53
+ /** Filter object entries and return a new object. */
54
+ function filterKeys(object, filter) {
55
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
56
+ }
57
+ /** Map object values while preserving the original key set. */
58
+ function mapValues(object, transform) {
59
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
60
+ }
61
+ /** Pick selected keys from an object, optionally including `undefined` values. */
62
+ function pick(source, keys, forced) {
63
+ if (!keys) return { ...source };
64
+ const result = {};
65
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
66
+ return result;
67
+ }
68
+ /** Shared config references used by schema validators and plugin runtimes. */
69
+ const write = Symbol.for("cosmokit.volatile.write");
70
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
71
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
72
+ if (value === null || typeof value !== "object") return value;
73
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
74
+ ancestors.add(value);
75
+ try {
76
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
77
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
78
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
79
+ } finally {
80
+ ancestors.delete(value);
81
+ }
82
+ }
83
+ /**
84
+ * Create a detached reference containing an immutable copy of the supplied data.
85
+ * @param value - validated config data; class instances and functions are unsupported.
86
+ * @returns a reference whose value is updated only by its owning runtime.
87
+ */
88
+ function createVolatile(value) {
89
+ let current = snapshot(value);
90
+ return Object.freeze({
91
+ get: () => current,
92
+ [write]: (value) => {
93
+ current = value;
94
+ }
95
+ });
96
+ }
97
+ /**
98
+ * Identify references across ESM/CJS copies of the shared library.
99
+ * @param value - a parsed config value.
100
+ * @returns whether the value implements the shared reference protocol.
101
+ */
102
+ function isVolatile(value) {
103
+ return typeof value === "object" && value !== null && write in value;
104
+ }
105
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
106
+ function is(type, value) {
107
+ if (arguments.length === 1) return (value) => is(type, value);
108
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
109
+ }
110
+ function isArrayBufferLike(value) {
111
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
112
+ }
113
+ function isArrayBufferSource(value) {
114
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
115
+ }
116
+ /** Binary source detection and base64/hex conversion helpers. */
117
+ var Binary;
118
+ (function(Binary) {
119
+ Binary.is = isArrayBufferLike;
120
+ Binary.isSource = isArrayBufferSource;
121
+ function fromSource(source) {
122
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
123
+ else return source;
124
+ }
125
+ Binary.fromSource = fromSource;
126
+ function toBase64(source) {
127
+ source = fromSource(source);
128
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
129
+ let binary = "";
130
+ const bytes = new Uint8Array(source);
131
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
132
+ return btoa(binary);
133
+ }
134
+ Binary.toBase64 = toBase64;
135
+ function fromBase64(source) {
136
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
137
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
138
+ }
139
+ Binary.fromBase64 = fromBase64;
140
+ function toHex(source) {
141
+ source = fromSource(source);
142
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
143
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
144
+ }
145
+ Binary.toHex = toHex;
146
+ function fromHex(source) {
147
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
148
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
149
+ const buffer = [];
150
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
151
+ return Uint8Array.from(buffer).buffer;
152
+ }
153
+ Binary.fromHex = fromHex;
154
+ })(Binary || (Binary = {}));
155
+ Binary.fromBase64;
156
+ Binary.toBase64;
157
+ Binary.fromHex;
158
+ Binary.toHex;
159
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
160
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
161
+ if (!source || typeof source !== "object") return source;
162
+ if (is("Date", source)) return new Date(source.valueOf());
163
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
164
+ if (isArrayBufferLike(source)) return source.slice(0);
165
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
166
+ const cached = refs.get(source);
167
+ if (cached) return cached;
168
+ if (Array.isArray(source)) {
169
+ const result = [];
170
+ refs.set(source, result);
171
+ source.forEach((value, index) => {
172
+ result[index] = Reflect.apply(clone, null, [value, refs]);
173
+ });
174
+ return result;
175
+ }
176
+ const result = Object.create(Object.getPrototypeOf(source));
177
+ refs.set(source, result);
178
+ for (const key of Reflect.ownKeys(source)) {
179
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
180
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
181
+ Reflect.defineProperty(result, key, descriptor);
182
+ }
183
+ return result;
184
+ }
185
+ /**
186
+ * Compare values recursively, treating two volatile references as equal regardless of value.
187
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
188
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
189
+ * @param a - first value.
190
+ * @param b - second value.
191
+ * @param strict - whether to require strict data equality outside volatile references.
192
+ * @returns whether the values compare equal.
193
+ */
194
+ function deepEqual(a, b, strict) {
195
+ const ancestors = /* @__PURE__ */ new Set();
196
+ function compare(a, b) {
197
+ if (a === b) return true;
198
+ if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);
199
+ if (!strict && isNullable(a) && isNullable(b)) return true;
200
+ if (typeof a !== typeof b || typeof a !== "object" || !a || !b) return false;
201
+ if (ancestors.has(a)) return false;
202
+ function check(test, then) {
203
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
204
+ }
205
+ ancestors.add(a);
206
+ try {
207
+ return check(Array.isArray, (a, b) => {
208
+ if (a.length !== b.length) return false;
209
+ for (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;
210
+ return true;
211
+ }) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("URL"), (a, b) => a.href === b.href) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
212
+ if (a.byteLength !== b.byteLength) return false;
213
+ const viewA = new Uint8Array(a);
214
+ const viewB = new Uint8Array(b);
215
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
216
+ return true;
217
+ }) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
218
+ ...a,
219
+ ...b
220
+ }).every((key) => compare(a[key], b[key])));
221
+ } finally {
222
+ ancestors.delete(a);
223
+ }
224
+ }
225
+ return compare(a, b);
226
+ }
227
+ /** Time constants plus parsing and formatting helpers. */
228
+ var Time;
229
+ (function(Time) {
230
+ Time.millisecond = 1;
231
+ Time.second = 1e3;
232
+ Time.minute = Time.second * 60;
233
+ Time.hour = Time.minute * 60;
234
+ Time.day = Time.hour * 24;
235
+ Time.week = Time.day * 7;
236
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
237
+ function setTimezoneOffset(offset) {
238
+ timezoneOffset = offset;
239
+ }
240
+ Time.setTimezoneOffset = setTimezoneOffset;
241
+ function getTimezoneOffset() {
242
+ return timezoneOffset;
243
+ }
244
+ Time.getTimezoneOffset = getTimezoneOffset;
245
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
246
+ if (typeof date === "number") date = new Date(date);
247
+ if (offset === void 0) offset = timezoneOffset;
248
+ return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
249
+ }
250
+ Time.getDateNumber = getDateNumber;
251
+ function fromDateNumber(value, offset) {
252
+ const date = new Date(value * Time.day);
253
+ if (offset === void 0) offset = timezoneOffset;
254
+ return new Date(+date + offset * Time.minute);
255
+ }
256
+ Time.fromDateNumber = fromDateNumber;
257
+ const numeric = /\d+(?:\.\d+)?/.source;
258
+ const timeRegExp = new RegExp(`^${[
259
+ "w(?:eek(?:s)?)?",
260
+ "d(?:ay(?:s)?)?",
261
+ "h(?:our(?:s)?)?",
262
+ "m(?:in(?:ute)?(?:s)?)?",
263
+ "s(?:ec(?:ond)?(?:s)?)?"
264
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
265
+ function parseTime(source) {
266
+ const capture = timeRegExp.exec(source);
267
+ if (!capture) return 0;
268
+ return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
269
+ }
270
+ Time.parseTime = parseTime;
271
+ function parseDate(date) {
272
+ const parsed = parseTime(date);
273
+ if (parsed) date = Date.now() + parsed;
274
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
275
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
276
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
277
+ }
278
+ Time.parseDate = parseDate;
279
+ function format(ms) {
280
+ const abs = Math.abs(ms);
281
+ if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
282
+ else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
283
+ else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
284
+ else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
285
+ return ms + "ms";
286
+ }
287
+ Time.format = format;
288
+ function toDigits(source, length = 2) {
289
+ return source.toString().padStart(length, "0");
290
+ }
291
+ Time.toDigits = toDigits;
292
+ function template(template, time = /* @__PURE__ */ new Date()) {
293
+ return template.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
294
+ }
295
+ Time.template = template;
296
+ })(Time || (Time = {}));
297
+ //#endregion
298
+ //#region node_modules/@deepseek-ai/schemastery/lib/index.mjs
299
+ const kSchema = Symbol.for("schemastery");
300
+ const kValidationError = Symbol.for("ValidationError");
301
+ globalThis.__schemastery_index__ ??= 0;
302
+ globalThis.__schemastery_refs__ = void 0;
303
+ var ValidationError = class extends TypeError {
304
+ options;
305
+ name = "ValidationError";
306
+ constructor(message, options) {
307
+ let prefix = "$";
308
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
309
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
310
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
311
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
312
+ super((prefix === "$" ? "" : `${prefix} `) + message);
313
+ this.options = options;
314
+ }
315
+ static is(error) {
316
+ return !!error?.[kValidationError];
317
+ }
318
+ };
319
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
320
+ const Schema = function(options) {
321
+ const schema = function(data, options = {}) {
322
+ return Schema.resolve(data, schema, options)[0];
323
+ };
324
+ if (options.refs) {
325
+ const refs = mapValues(options.refs, (options) => new Schema(options));
326
+ const getRef = (uid) => refs[uid];
327
+ for (const key in refs) {
328
+ const options = refs[key];
329
+ options.sKey = getRef(options.sKey);
330
+ options.inner = getRef(options.inner);
331
+ options.list = options.list && options.list.map(getRef);
332
+ options.dict = options.dict && mapValues(options.dict, getRef);
333
+ }
334
+ return refs[options.uid];
335
+ }
336
+ Object.assign(schema, options);
337
+ if (typeof schema.callback === "string") try {
338
+ schema.callback = new Function("return " + schema.callback)();
339
+ } catch {}
340
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
341
+ Object.setPrototypeOf(schema, Schema.prototype);
342
+ schema.meta ||= {};
343
+ schema.toString = schema.toString.bind(schema);
344
+ return schema;
345
+ };
346
+ Schema.prototype = Object.create(Function.prototype);
347
+ Schema.prototype[kSchema] = true;
348
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
349
+ return {
350
+ version: 1,
351
+ vendor: "schemastery",
352
+ validate: (value) => {
353
+ try {
354
+ return { value: Schema.resolve(value, this, {})[0] };
355
+ } catch (error) {
356
+ if (ValidationError.is(error)) return { issues: [{
357
+ message: error.message,
358
+ path: error.options.path
359
+ }] };
360
+ throw error;
361
+ }
362
+ }
363
+ };
364
+ } });
365
+ Schema.ValidationError = ValidationError;
366
+ Schema.prototype.toJSON = function toJSON() {
367
+ if (globalThis.__schemastery_refs__) {
368
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
369
+ return this.uid;
370
+ }
371
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
372
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
373
+ const result = {
374
+ uid: this.uid,
375
+ refs: globalThis.__schemastery_refs__
376
+ };
377
+ globalThis.__schemastery_refs__ = void 0;
378
+ return result;
379
+ };
380
+ Schema.prototype.set = function set(key, value) {
381
+ this.dict[key] = value;
382
+ return this;
383
+ };
384
+ Schema.prototype.push = function push(value) {
385
+ this.list.push(value);
386
+ return this;
387
+ };
388
+ function mergeDesc(original, messages) {
389
+ const result = typeof original === "string" ? { "": original } : { ...original };
390
+ for (const locale in messages) {
391
+ const value = messages[locale];
392
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
393
+ else if (typeof value === "string") result[locale] = value;
394
+ }
395
+ return result;
396
+ }
397
+ function getInner(value) {
398
+ return value?.$value ?? value?.$inner;
399
+ }
400
+ function extractKeys(data) {
401
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
402
+ }
403
+ Schema.prototype.i18n = function i18n(messages) {
404
+ const schema = Schema(this);
405
+ const desc = mergeDesc(schema.meta.description, messages);
406
+ if (Object.keys(desc).length) schema.meta.description = desc;
407
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
408
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
409
+ });
410
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
411
+ return inner.i18n(mapValues(messages, (data = {}) => {
412
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
413
+ if (Array.isArray(data)) return data[index];
414
+ return extractKeys(data);
415
+ }));
416
+ });
417
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
418
+ if (getInner(data)) return getInner(data);
419
+ return extractKeys(data);
420
+ }));
421
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
422
+ return schema;
423
+ };
424
+ Schema.prototype.extra = function extra(key, value) {
425
+ const schema = Schema(this);
426
+ schema.meta = {
427
+ ...schema.meta,
428
+ [key]: value
429
+ };
430
+ return schema;
431
+ };
432
+ for (const key of [
433
+ "required",
434
+ "disabled",
435
+ "collapse",
436
+ "hidden",
437
+ "loose"
438
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
439
+ const schema = Schema(this);
440
+ schema.meta = {
441
+ ...schema.meta,
442
+ [key]: value
443
+ };
444
+ return schema;
445
+ } });
446
+ Schema.prototype.deprecated = function deprecated() {
447
+ const schema = Schema(this);
448
+ schema.meta.badges ||= [];
449
+ schema.meta.badges.push({
450
+ text: "deprecated",
451
+ type: "danger"
452
+ });
453
+ return schema;
454
+ };
455
+ Schema.prototype.experimental = function experimental() {
456
+ const schema = Schema(this);
457
+ schema.meta.badges ||= [];
458
+ schema.meta.badges.push({
459
+ text: "experimental",
460
+ type: "warning"
461
+ });
462
+ return schema;
463
+ };
464
+ Schema.prototype.pattern = function pattern(regexp) {
465
+ const schema = Schema(this);
466
+ const pattern = pick(regexp, ["source", "flags"]);
467
+ schema.meta = {
468
+ ...schema.meta,
469
+ pattern
470
+ };
471
+ return schema;
472
+ };
473
+ Schema.prototype.simplify = function simplify(value) {
474
+ if (isVolatile(value)) value = value.get();
475
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
476
+ if (isNullable(value)) return value;
477
+ if (this.type === "object" || this.type === "dict") {
478
+ const result = {};
479
+ for (const key in value) {
480
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
481
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
482
+ }
483
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
484
+ return result;
485
+ } else if (this.type === "array" || this.type === "tuple") {
486
+ const result = [];
487
+ value.forEach((value, index) => {
488
+ const schema = this.type === "array" ? this.inner : this.list[index];
489
+ const item = schema ? schema.simplify(value) : value;
490
+ result.push(item);
491
+ });
492
+ return result;
493
+ } else if (this.type === "intersect") {
494
+ const result = {};
495
+ for (const item of this.list) Object.assign(result, item.simplify(value));
496
+ return result;
497
+ } else if (this.type === "union") for (const schema of this.list) try {
498
+ Schema.resolve(value, schema, {});
499
+ return schema.simplify(value);
500
+ } catch {}
501
+ return value;
502
+ };
503
+ Schema.prototype.toString = function toString(inline) {
504
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
505
+ };
506
+ Schema.prototype.role = function role(role, extra) {
507
+ const schema = Schema(this);
508
+ schema.meta = {
509
+ ...schema.meta,
510
+ role,
511
+ extra
512
+ };
513
+ return schema;
514
+ };
515
+ for (const key of [
516
+ "default",
517
+ "link",
518
+ "comment",
519
+ "description",
520
+ "max",
521
+ "min",
522
+ "step"
523
+ ]) Object.assign(Schema.prototype, { [key](value) {
524
+ const schema = Schema(this);
525
+ schema.meta = {
526
+ ...schema.meta,
527
+ [key]: value
528
+ };
529
+ return schema;
530
+ } });
531
+ Schema.prototype.volatile = function volatile() {
532
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
533
+ return this.extra("volatile", true);
534
+ };
535
+ const resolvers = {};
536
+ const checkedVolatile = Symbol("checked-volatile-schema");
537
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
538
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
539
+ if (states.has(blocked)) return;
540
+ states.add(blocked);
541
+ seen.set(schema, states);
542
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
543
+ const nested = blocked || !!schema.meta?.volatile;
544
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
545
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
546
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
547
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
548
+ }
549
+ Schema.extend = function extend(type, resolve) {
550
+ resolvers[type] = resolve;
551
+ };
552
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
553
+ if (!schema) return [data];
554
+ if (!options[checkedVolatile]) {
555
+ validateVolatileSchema(schema, options.path);
556
+ options = {
557
+ ...options,
558
+ [checkedVolatile]: true
559
+ };
560
+ }
561
+ if (schema.meta?.volatile) {
562
+ const inner = Schema(schema);
563
+ inner.meta = {
564
+ ...schema.meta,
565
+ volatile: false
566
+ };
567
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
568
+ try {
569
+ return [createVolatile(value), adapted];
570
+ } catch (error) {
571
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
572
+ }
573
+ }
574
+ if (options.ignore?.(data, schema)) return [data];
575
+ if (isNullable(data) && schema.type !== "lazy") {
576
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
577
+ let current = schema;
578
+ let fallback = schema.meta.default;
579
+ while (current?.type === "intersect" && isNullable(fallback)) {
580
+ current = current.list[0];
581
+ fallback = current?.meta.default;
582
+ }
583
+ if (isNullable(fallback)) return [data];
584
+ data = clone(fallback);
585
+ }
586
+ const callback = resolvers[schema.type];
587
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
588
+ try {
589
+ return callback(data, schema, options, strict);
590
+ } catch (error) {
591
+ if (!schema.meta.loose) throw error;
592
+ return [schema.meta.default];
593
+ }
594
+ };
595
+ Schema.from = function from(source) {
596
+ if (isNullable(source)) return Schema.any();
597
+ else if ([
598
+ "string",
599
+ "number",
600
+ "boolean"
601
+ ].includes(typeof source)) return Schema.const(source).required();
602
+ else if (source[kSchema]) return source;
603
+ else if (typeof source === "function") switch (source) {
604
+ case String: return Schema.string().required();
605
+ case Number: return Schema.number().required();
606
+ case Boolean: return Schema.boolean().required();
607
+ case Function: return Schema.function().required();
608
+ default: return Schema.is(source).required();
609
+ }
610
+ else throw new TypeError(`cannot infer schema from ${source}`);
611
+ };
612
+ Schema.lazy = function lazy(builder) {
613
+ const toJSON = () => {
614
+ if (!schema.inner[kSchema]) {
615
+ schema.inner = schema.builder();
616
+ schema.inner.meta = {
617
+ ...schema.meta,
618
+ ...schema.inner.meta
619
+ };
620
+ }
621
+ return schema.inner.toJSON();
622
+ };
623
+ const schema = new Schema({
624
+ type: "lazy",
625
+ builder,
626
+ inner: { toJSON }
627
+ });
628
+ return schema;
629
+ };
630
+ Schema.natural = function natural() {
631
+ return Schema.number().step(1).min(0);
632
+ };
633
+ Schema.percent = function percent() {
634
+ return Schema.number().step(.01).min(0).max(1).role("slider");
635
+ };
636
+ Schema.date = function date() {
637
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
638
+ const date = new Date(value);
639
+ if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
640
+ return date;
641
+ }, true)]);
642
+ };
643
+ Schema.regExp = function regExp(flag = "") {
644
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
645
+ try {
646
+ return new RegExp(value, flag);
647
+ } catch (e) {
648
+ throw new ValidationError(e.message, options);
649
+ }
650
+ }, true)]);
651
+ };
652
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
653
+ return Schema.union([
654
+ Schema.is(ArrayBuffer),
655
+ Schema.is(SharedArrayBuffer),
656
+ Schema.transform(Schema.any(), (value, options) => {
657
+ if (Binary.isSource(value)) return Binary.fromSource(value);
658
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
659
+ }, true),
660
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
661
+ try {
662
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
663
+ } catch (e) {
664
+ throw new ValidationError(e.message, options);
665
+ }
666
+ }, true)] : []
667
+ ]);
668
+ };
669
+ Schema.extend("lazy", (data, schema, options, strict) => {
670
+ if (!schema.inner[kSchema]) {
671
+ schema.inner = schema.builder();
672
+ schema.inner.meta = {
673
+ ...schema.meta,
674
+ ...schema.inner.meta
675
+ };
676
+ validateVolatileSchema(schema.inner, options.path, true);
677
+ }
678
+ return Schema.resolve(data, schema.inner, options, strict);
679
+ });
680
+ Schema.extend("any", (data) => {
681
+ return [data];
682
+ });
683
+ Schema.extend("never", (data, _, options) => {
684
+ throw new ValidationError(`expected nullable but got ${data}`, options);
685
+ });
686
+ Schema.extend("const", (data, { value }, options) => {
687
+ if (deepEqual(data, value)) return [value];
688
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
689
+ });
690
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
691
+ const { max = Infinity, min = -Infinity } = meta;
692
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
693
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
694
+ }
695
+ Schema.extend("string", (data, { meta }, options) => {
696
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
697
+ if (meta.pattern) {
698
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
699
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
700
+ }
701
+ checkWithinRange(data.length, meta, "string length", options);
702
+ return [data];
703
+ });
704
+ function decimalShift(data, digits) {
705
+ const str = data.toString();
706
+ if (str.includes("e")) return data * Math.pow(10, digits);
707
+ const index = str.indexOf(".");
708
+ if (index === -1) return data * Math.pow(10, digits);
709
+ const frac = str.slice(index + 1);
710
+ const integer = str.slice(0, index);
711
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
712
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
713
+ }
714
+ function isMultipleOf(data, min, step) {
715
+ step = Math.abs(step);
716
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
717
+ const index = step.toString().indexOf(".");
718
+ const digits = step.toString().slice(index + 1).length;
719
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
720
+ }
721
+ Schema.extend("number", (data, { meta }, options) => {
722
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
723
+ checkWithinRange(data, meta, "number", options);
724
+ const { step } = meta;
725
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
726
+ return [data];
727
+ });
728
+ Schema.extend("boolean", (data, _, options) => {
729
+ if (typeof data === "boolean") return [data];
730
+ throw new ValidationError(`expected boolean but got ${data}`, options);
731
+ });
732
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
733
+ let value = 0, keys = [];
734
+ if (typeof data === "number") {
735
+ value = data;
736
+ for (const key in bits) if (data & bits[key]) keys.push(key);
737
+ } else if (Array.isArray(data)) {
738
+ keys = data;
739
+ for (const key of keys) {
740
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
741
+ if (key in bits) value |= bits[key];
742
+ }
743
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
744
+ if (value === meta.default) return [value];
745
+ return [value, keys];
746
+ });
747
+ Schema.extend("function", (data, _, options) => {
748
+ if (typeof data === "function") return [data];
749
+ throw new ValidationError(`expected function but got ${data}`, options);
750
+ });
751
+ Schema.extend("is", (data, { constructor }, options) => {
752
+ if (typeof constructor === "function") {
753
+ if (data instanceof constructor) return [data];
754
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
755
+ } else {
756
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
757
+ let prototype = Object.getPrototypeOf(data);
758
+ while (prototype) {
759
+ if (prototype.constructor?.name === constructor) return [data];
760
+ prototype = Object.getPrototypeOf(prototype);
761
+ }
762
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
763
+ }
764
+ });
765
+ function property(data, key, schema, options) {
766
+ try {
767
+ const [value, adapted] = Schema.resolve(data[key], schema, {
768
+ ...options,
769
+ path: [...options.path || [], key]
770
+ });
771
+ if (adapted !== void 0) data[key] = adapted;
772
+ return value;
773
+ } catch (e) {
774
+ if (!options?.autofix) throw e;
775
+ delete data[key];
776
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
777
+ }
778
+ }
779
+ Schema.extend("array", (data, { inner, meta }, options) => {
780
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
781
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
782
+ return [data.map((_, index) => property(data, index, inner, options))];
783
+ });
784
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
785
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
786
+ const result = {};
787
+ for (const key in data) {
788
+ let rKey;
789
+ try {
790
+ rKey = Schema.resolve(key, sKey, options)[0];
791
+ } catch (error) {
792
+ if (strict) continue;
793
+ throw error;
794
+ }
795
+ result[rKey] = property(data, key, inner, options);
796
+ data[rKey] = data[key];
797
+ if (key !== rKey) delete data[key];
798
+ }
799
+ return [result];
800
+ });
801
+ Schema.extend("tuple", (data, { list }, options, strict) => {
802
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
803
+ const result = list.map((inner, index) => property(data, index, inner, options));
804
+ if (strict) return [result];
805
+ result.push(...data.slice(list.length));
806
+ return [result];
807
+ });
808
+ function merge(result, data) {
809
+ for (const key in data) {
810
+ if (key in result) continue;
811
+ result[key] = data[key];
812
+ }
813
+ }
814
+ Schema.extend("object", (data, { dict }, options, strict) => {
815
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
816
+ const result = {};
817
+ for (const key in dict) {
818
+ const value = property(data, key, dict[key], options);
819
+ if (!isNullable(value) || key in data) result[key] = value;
820
+ }
821
+ if (!strict) merge(result, data);
822
+ return [result];
823
+ });
824
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
825
+ const messages = [];
826
+ for (const inner of list) try {
827
+ return Schema.resolve(data, inner, options, strict);
828
+ } catch (error) {
829
+ messages.push(error);
830
+ }
831
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
832
+ });
833
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
834
+ if (!list.length) return [data];
835
+ let result;
836
+ for (const inner of list) {
837
+ const value = Schema.resolve(data, inner, options, true)[0];
838
+ if (isNullable(value)) continue;
839
+ if (isNullable(result)) result = value;
840
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
841
+ else if (typeof value === "object") merge(result ??= {}, value);
842
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
843
+ }
844
+ if (!strict && isPlainObject(data)) merge(result, data);
845
+ return [result];
846
+ });
847
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
848
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
849
+ if (preserve) return [callback(result)];
850
+ else return [callback(result), callback(adapted)];
851
+ });
852
+ const formatters = {};
853
+ function defineMethod(name, keys, format) {
854
+ formatters[name] = format;
855
+ Object.assign(Schema, { [name](...args) {
856
+ const schema = new Schema({ type: name });
857
+ keys.forEach((key, index) => {
858
+ switch (key) {
859
+ case "sKey":
860
+ schema.sKey = args[index] ?? Schema.string();
861
+ break;
862
+ case "inner":
863
+ schema.inner = Schema.from(args[index]);
864
+ break;
865
+ case "list":
866
+ schema.list = args[index].map(Schema.from);
867
+ break;
868
+ case "dict":
869
+ schema.dict = mapValues(args[index], Schema.from);
870
+ break;
871
+ case "bits":
872
+ schema.bits = {};
873
+ for (const key in args[index]) {
874
+ if (typeof args[index][key] !== "number") continue;
875
+ schema.bits[key] = args[index][key];
876
+ }
877
+ break;
878
+ case "callback": {
879
+ const callback = schema.callback = args[index];
880
+ callback["toJSON"] ||= () => callback.toString();
881
+ break;
882
+ }
883
+ case "constructor": {
884
+ const constructor = schema.constructor = args[index];
885
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
886
+ break;
887
+ }
888
+ default: schema[key] = args[index];
889
+ }
890
+ });
891
+ if (name === "object" || name === "dict") schema.meta.default = {};
892
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
893
+ else if (name === "bitset") schema.meta.default = 0;
894
+ return schema;
895
+ } });
896
+ }
897
+ defineMethod("is", ["constructor"], ({ constructor }) => {
898
+ if (typeof constructor === "function") return constructor.name;
899
+ else return constructor;
900
+ });
901
+ defineMethod("any", [], () => "any");
902
+ defineMethod("never", [], () => "never");
903
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
904
+ defineMethod("string", [], () => "string");
905
+ defineMethod("number", [], () => "number");
906
+ defineMethod("boolean", [], () => "boolean");
907
+ defineMethod("bitset", ["bits"], () => "bitset");
908
+ defineMethod("function", [], () => "function");
909
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
910
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
911
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
912
+ defineMethod("object", ["dict"], ({ dict }) => {
913
+ if (Object.keys(dict).length === 0) return "{}";
914
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
915
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
916
+ }).join(", ")} }`;
917
+ });
918
+ defineMethod("union", ["list"], ({ list }, inline) => {
919
+ const result = list.map(({ toString: format }) => format()).join(" | ");
920
+ return inline ? `(${result})` : result;
921
+ });
922
+ defineMethod("intersect", ["list"], ({ list }) => {
923
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
924
+ });
925
+ defineMethod("transform", [
926
+ "inner",
927
+ "callback",
928
+ "preserve"
929
+ ], ({ inner }, isInner) => inner.toString(isInner));
930
+ /** Validate an optional per-operation timeout override against the same bounds as in-process. */
931
+ function validOperationTimeout(value) {
932
+ if (value === void 0) return void 0;
933
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 3e5) return void 0;
934
+ return value;
935
+ }
936
+ /** Normalize an extension route path exactly like the in-process registry. */
937
+ function normalizeWorkerRoutePath(value) {
938
+ if (typeof value !== "string" || value.length === 0 || value.length > 256 || value.includes("?") || value.includes("#") || value.includes("\\") || /[\u0000-\u001f\u007f]/u.test(value)) throw new Error("invalid route path");
939
+ const normalizedInput = value.startsWith("/") ? value : `/${value}`;
940
+ if (normalizedInput.split("/").some((part) => part === ".." || part === ".")) throw new Error("invalid route path");
941
+ return normalizedInput === "/" ? "/" : normalizedInput.replace(/\/+$/u, "");
942
+ }
943
+ /**
944
+ * Recognize a controlled business error (MobileExtensionError shape) thrown by
945
+ * host code so its code/status survive the boundary instead of collapsing to
946
+ * a generic 500. Pure duck-typing keeps the runtime Cordis-free.
947
+ */
948
+ function businessErrorShape(error) {
949
+ if (error === null || typeof error !== "object") return void 0;
950
+ const candidate = error;
951
+ if (typeof candidate.code !== "string" || candidate.code.length === 0 || candidate.code.length > 64) return void 0;
952
+ if (typeof candidate.message !== "string" || candidate.message.length > 500) return void 0;
953
+ if (typeof candidate.status !== "number" || !Number.isInteger(candidate.status) || candidate.status < 400 || candidate.status > 599) return void 0;
954
+ return {
955
+ code: candidate.code,
956
+ message: candidate.message,
957
+ status: candidate.status
958
+ };
959
+ }
960
+ /**
961
+ * Serialize an action result to JSON bytes worker-side.
962
+ *
963
+ * Plain JSON.stringify, matching the in-process gateway contract exactly:
964
+ * non-JSON-serializable values (e.g. BigInt) throw and surface as
965
+ * `extension_failed`, same as in-process mode today.
966
+ */
967
+ function serializeWorkerResult(value) {
968
+ const serialized = JSON.stringify(value);
969
+ if (serialized === void 0) throw new Error("extension result is not JSON serializable");
970
+ return new TextEncoder().encode(serialized);
971
+ }
972
+ //#endregion
973
+ //#region src/extension-worker-runtime.ts
974
+ /**
975
+ * Worker-side runtime for opt-in local extension hosts.
976
+ *
977
+ * This file is a standalone tsdown entry (lib/extension-worker-runtime.mjs).
978
+ * It executes ALL host behavior inside the worker thread — module import,
979
+ * activation, input validation, actions, effects and cleanup — and answers the
980
+ * parent with metadata and pre-serialized bytes only. It must never import
981
+ * Cordis or any DSH service.
982
+ */
983
+ const parentChannel = parentPort;
984
+ if (parentChannel === null) throw new Error("extension-worker-runtime must run inside a Worker");
985
+ const port = parentChannel;
986
+ const limits = resolveHostExecution(workerData?.limits);
987
+ /** Logger-adapter burst budget per time window; the budget resets each window. */
988
+ const LOG_QUEUE_LIMIT = limits.logMessagesPerWindow;
989
+ const runtimeId = randomUUID();
990
+ const generationController = new AbortController();
991
+ const actions = /* @__PURE__ */ new Map();
992
+ const routes = [];
993
+ const cleanups = [];
994
+ let logWindowCount = 0;
995
+ let logWindowStartedAt = Date.now();
996
+ function send(message) {
997
+ port.postMessage(message);
998
+ }
999
+ /** Upper bound for one stringified log argument forwarded to the parent. */
1000
+ const LOG_ARG_MAX_CHARS = limits.logMessageBytes;
1001
+ /** Render a log argument that structured cloning cannot carry (or that is huge). */
1002
+ function sanitizeLogArg(value) {
1003
+ return (typeof value === "string" ? value : inspect(value, {
1004
+ depth: 2,
1005
+ maxArrayLength: 16,
1006
+ maxStringLength: 256,
1007
+ customInspect: false,
1008
+ getters: false
1009
+ })).slice(0, LOG_ARG_MAX_CHARS);
1010
+ }
1011
+ function log(level, args) {
1012
+ const now = Date.now();
1013
+ if (now - logWindowStartedAt >= limits.logWindowMs) {
1014
+ logWindowStartedAt = now;
1015
+ logWindowCount = 0;
1016
+ }
1017
+ if (logWindowCount >= LOG_QUEUE_LIMIT) return;
1018
+ logWindowCount += 1;
1019
+ try {
1020
+ let remaining = limits.logMessageBytes;
1021
+ const rendered = [];
1022
+ for (const arg of args) {
1023
+ if (remaining <= 0) break;
1024
+ const text = Buffer.from(sanitizeLogArg(arg)).subarray(0, remaining).toString("utf8").replace(/\uFFFD$/u, "");
1025
+ rendered.push(text);
1026
+ remaining -= Buffer.byteLength(text);
1027
+ }
1028
+ send({
1029
+ kind: "log",
1030
+ level,
1031
+ args: rendered
1032
+ });
1033
+ } catch (error) {}
1034
+ }
1035
+ /** Bound a forwarded error message so it cannot carry unbounded text. */
1036
+ function boundedMessage(error) {
1037
+ const text = error instanceof Error ? error.message : String(error);
1038
+ return text.length > 500 ? text.slice(0, 500) : text;
1039
+ }
1040
+ const loggerAdapter = {
1041
+ debug: (...args) => {
1042
+ log("debug", args);
1043
+ },
1044
+ info: (...args) => {
1045
+ log("info", args);
1046
+ },
1047
+ warn: (...args) => {
1048
+ log("warn", args);
1049
+ },
1050
+ error: (...args) => {
1051
+ log("error", args);
1052
+ }
1053
+ };
1054
+ /** The lifecycle RPC id currently in flight, for outer-catch replies. */
1055
+ let lifecycleReplyId = "lifecycle";
1056
+ port.on("message", (message) => {
1057
+ handleMessage(message).catch((error) => {
1058
+ send({
1059
+ kind: "error",
1060
+ runtimeId,
1061
+ id: lifecycleReplyId,
1062
+ code: "extension_failed",
1063
+ message: boundedMessage(error),
1064
+ status: 500
1065
+ });
1066
+ });
1067
+ });
1068
+ /** Live per-request controllers, so parent cancel messages abort running work. */
1069
+ const requestControllers = /* @__PURE__ */ new Map();
1070
+ function abortRequest(id) {
1071
+ requestControllers.get(id)?.abort(/* @__PURE__ */ new Error("request cancelled"));
1072
+ }
1073
+ /** Live stream sources by request id, so generation abort can destroy them. */
1074
+ const activeSources = /* @__PURE__ */ new Map();
1075
+ /** Credit per stream id; the worker pauses a source when its window is exhausted. */
1076
+ const streamCredit = /* @__PURE__ */ new Map();
1077
+ /** Sent and acknowledged bytes per stream; their difference is in-flight load. */
1078
+ const streamSent = /* @__PURE__ */ new Map();
1079
+ const streamAcked = /* @__PURE__ */ new Map();
1080
+ /** FIFO demands reserve aggregate bytes before waking a source pump. */
1081
+ const sendBudgetWaiters = [];
1082
+ const finishedStreams = /* @__PURE__ */ new Set();
1083
+ let drainingBudget = false;
1084
+ /** Bytes sent but not yet acknowledged, across all live streams. */
1085
+ function inFlightTotal() {
1086
+ let total = 0;
1087
+ for (const [id, sent] of streamSent) total += sent - (streamAcked.get(id) ?? 0);
1088
+ return total;
1089
+ }
1090
+ function wakeSendBudgetWaiters() {
1091
+ if (drainingBudget) return;
1092
+ drainingBudget = true;
1093
+ try {
1094
+ for (let index = 0; index < sendBudgetWaiters.length;) {
1095
+ const waiter = sendBudgetWaiters[index];
1096
+ if (waiter.bail()) {
1097
+ sendBudgetWaiters.splice(index, 1);
1098
+ waiter.resolve(false);
1099
+ continue;
1100
+ }
1101
+ if ((streamCredit.get(waiter.id) ?? 0) < waiter.length) {
1102
+ index += 1;
1103
+ continue;
1104
+ }
1105
+ if (inFlightTotal() + waiter.length > limits.streamAggregateBytes) break;
1106
+ if (!tryReserve(waiter.id, waiter.length)) throw new Error("worker stream reservation failed");
1107
+ sendBudgetWaiters.splice(index, 1);
1108
+ waiter.resolve(true);
1109
+ }
1110
+ } finally {
1111
+ drainingBudget = false;
1112
+ }
1113
+ }
1114
+ /**
1115
+ * Atomically check and debit send budget for one piece: the per-stream window
1116
+ * must hold it AND the per-worker aggregate in-flight bound must hold. Check
1117
+ * and debit are one synchronous step, so concurrently awakened pumps can never
1118
+ * double-reserve the same freed capacity.
1119
+ */
1120
+ function tryReserve(id, length) {
1121
+ const credit = streamCredit.get(id) ?? 0;
1122
+ if (credit < length) return false;
1123
+ if (inFlightTotal() + length > limits.streamAggregateBytes) return false;
1124
+ streamCredit.set(id, credit - length);
1125
+ streamSent.set(id, (streamSent.get(id) ?? 0) + length);
1126
+ return true;
1127
+ }
1128
+ /** Wait until a piece may be sent; resolves false when the caller bailed. */
1129
+ async function acquireSendBudget(id, length, bail) {
1130
+ if (bail()) return false;
1131
+ return new Promise((resolve) => {
1132
+ sendBudgetWaiters.push({
1133
+ id,
1134
+ length,
1135
+ bail,
1136
+ resolve
1137
+ });
1138
+ wakeSendBudgetWaiters();
1139
+ });
1140
+ }
1141
+ async function handleMessage(message) {
1142
+ if (message.kind === "activate") {
1143
+ lifecycleReplyId = message.id;
1144
+ await activate(message.id, message.hostFile, message.generation, message.manifest);
1145
+ return;
1146
+ }
1147
+ if (message.kind === "invoke") {
1148
+ await runAction(message.id, message.action, message.deviceId, message.input);
1149
+ return;
1150
+ }
1151
+ if (message.kind === "route") {
1152
+ await runRoute(message);
1153
+ return;
1154
+ }
1155
+ if (message.kind === "stream-ack") {
1156
+ if (!streamSent.has(message.id) || !Number.isInteger(message.bytes) || message.bytes < 0 || message.bytes > (streamSent.get(message.id) ?? 0) - (streamAcked.get(message.id) ?? 0)) return;
1157
+ streamAcked.set(message.id, (streamAcked.get(message.id) ?? 0) + message.bytes);
1158
+ if (!finishedStreams.has(message.id)) streamCredit.set(message.id, (streamCredit.get(message.id) ?? 0) + message.bytes);
1159
+ if (finishedStreams.has(message.id) && streamSent.get(message.id) === streamAcked.get(message.id)) releaseStreamAccounting(message.id);
1160
+ wakeSendBudgetWaiters();
1161
+ return;
1162
+ }
1163
+ if (message.kind === "stream-cancel") {
1164
+ activeSources.get(message.id)?.destroy();
1165
+ if (finishedStreams.has(message.id)) releaseStreamAccounting(message.id);
1166
+ wakeSendBudgetWaiters();
1167
+ return;
1168
+ }
1169
+ if (message.kind === "cancel") {
1170
+ abortRequest(message.id);
1171
+ return;
1172
+ }
1173
+ if (message.kind === "dispose") {
1174
+ lifecycleReplyId = message.id;
1175
+ generationController.abort();
1176
+ for (const source of activeSources.values()) source.destroy();
1177
+ const pending = [];
1178
+ for (const cleanup of [...cleanups].reverse()) try {
1179
+ pending.push(Promise.resolve(cleanup()));
1180
+ } catch {}
1181
+ await Promise.allSettled(pending);
1182
+ send({
1183
+ kind: "result",
1184
+ runtimeId,
1185
+ id: message.id,
1186
+ bytes: /* @__PURE__ */ new Uint8Array()
1187
+ });
1188
+ return;
1189
+ }
1190
+ }
1191
+ async function runRoute(message) {
1192
+ const spec = routes[message.routeIndex];
1193
+ if (spec === void 0) {
1194
+ send({
1195
+ kind: "error",
1196
+ runtimeId,
1197
+ id: message.id,
1198
+ code: "route_not_found",
1199
+ message: "route not found",
1200
+ status: 404
1201
+ });
1202
+ return;
1203
+ }
1204
+ const controller = new AbortController();
1205
+ requestControllers.set(message.id, controller);
1206
+ const onGenerationAbort = () => {
1207
+ controller.abort(generationController.signal.reason);
1208
+ };
1209
+ if (generationController.signal.aborted) controller.abort();
1210
+ else generationController.signal.addEventListener("abort", onGenerationAbort, { once: true });
1211
+ try {
1212
+ const response = await spec.handle({
1213
+ method: message.method,
1214
+ pathname: message.path,
1215
+ query: new URLSearchParams([...message.query].map(([key, value]) => [key, value])),
1216
+ headers: message.headers,
1217
+ body: Buffer.from(message.body),
1218
+ signal: controller.signal,
1219
+ deviceId: message.deviceId
1220
+ });
1221
+ if (response === null || typeof response !== "object") {
1222
+ send({
1223
+ kind: "error",
1224
+ runtimeId,
1225
+ id: message.id,
1226
+ code: "invalid_route_response",
1227
+ message: "extension returned an invalid response",
1228
+ status: 500
1229
+ });
1230
+ return;
1231
+ }
1232
+ const body = response.body;
1233
+ if (typeof body !== "string" && !(body instanceof Uint8Array) && !isStream(body)) throw Object.assign(/* @__PURE__ */ new Error("extension returned an invalid response"), {
1234
+ code: "invalid_route_response",
1235
+ status: 500
1236
+ });
1237
+ let wireMeta;
1238
+ try {
1239
+ wireMeta = snapshotResponseMetadata(response);
1240
+ } catch (error) {
1241
+ if (isStream(body)) {
1242
+ body.once("error", () => void 0);
1243
+ body.destroy();
1244
+ }
1245
+ throw error;
1246
+ }
1247
+ if (isStream(body)) {
1248
+ await pumpStream(message.id, body, wireMeta);
1249
+ return;
1250
+ }
1251
+ const bytes = typeof body === "string" ? new TextEncoder().encode(body) : new Uint8Array(body);
1252
+ if (bytes.byteLength > limits.resultMaxBytes) {
1253
+ send({
1254
+ kind: "error",
1255
+ runtimeId,
1256
+ id: message.id,
1257
+ code: "extension_result_too_large",
1258
+ message: "extension response is too large",
1259
+ status: 500
1260
+ });
1261
+ return;
1262
+ }
1263
+ send({
1264
+ kind: "route-response",
1265
+ runtimeId,
1266
+ id: message.id,
1267
+ ...wireMeta,
1268
+ bytes
1269
+ });
1270
+ } catch (error) {
1271
+ const business = businessErrorShape(error);
1272
+ if (business !== void 0) {
1273
+ send({
1274
+ kind: "error",
1275
+ runtimeId,
1276
+ id: message.id,
1277
+ code: business.code,
1278
+ message: business.message,
1279
+ status: business.status
1280
+ });
1281
+ return;
1282
+ }
1283
+ send({
1284
+ kind: "error",
1285
+ runtimeId,
1286
+ id: message.id,
1287
+ code: "extension_failed",
1288
+ message: boundedMessage(error),
1289
+ status: 500
1290
+ });
1291
+ } finally {
1292
+ requestControllers.delete(message.id);
1293
+ generationController.signal.removeEventListener("abort", onGenerationAbort);
1294
+ }
1295
+ }
1296
+ function isStream(value) {
1297
+ return value !== null && typeof value === "object" && typeof value.pipe === "function";
1298
+ }
1299
+ async function pumpStream(id, source, meta) {
1300
+ activeSources.set(id, source);
1301
+ streamCredit.set(id, limits.streamWindowBytes);
1302
+ streamSent.set(id, 0);
1303
+ streamAcked.set(id, 0);
1304
+ send({
1305
+ kind: "stream-start",
1306
+ runtimeId,
1307
+ id,
1308
+ ...meta.status === void 0 ? {} : { status: meta.status },
1309
+ ...meta.contentType === void 0 ? {} : { contentType: meta.contentType },
1310
+ ...meta.headers === void 0 ? {} : { headers: meta.headers }
1311
+ });
1312
+ let ended = false;
1313
+ const finish = () => {
1314
+ if (ended) return;
1315
+ ended = true;
1316
+ activeSources.delete(id);
1317
+ streamCredit.delete(id);
1318
+ finishedStreams.add(id);
1319
+ if (source.destroyed && !source.readableEnded || streamSent.get(id) === streamAcked.get(id)) releaseStreamAccounting(id);
1320
+ wakeSendBudgetWaiters();
1321
+ };
1322
+ source.once("error", (error) => {
1323
+ if (ended) return;
1324
+ finish();
1325
+ send({
1326
+ kind: "stream-error",
1327
+ runtimeId,
1328
+ id,
1329
+ message: boundedMessage(error)
1330
+ });
1331
+ });
1332
+ try {
1333
+ for await (const chunk of source) {
1334
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1335
+ if (ended) return;
1336
+ for (let offset = 0; offset < bytes.byteLength;) {
1337
+ const piece = bytes.subarray(offset, Math.min(offset + limits.streamChunkBytes, bytes.byteLength));
1338
+ if (!await acquireSendBudget(id, piece.byteLength, () => source.destroyed || ended)) {
1339
+ finish();
1340
+ send({
1341
+ kind: "stream-end",
1342
+ runtimeId,
1343
+ id
1344
+ });
1345
+ source.destroy();
1346
+ return;
1347
+ }
1348
+ send({
1349
+ kind: "stream-chunk",
1350
+ runtimeId,
1351
+ id,
1352
+ bytes: new Uint8Array(piece)
1353
+ });
1354
+ offset += piece.byteLength;
1355
+ }
1356
+ }
1357
+ finish();
1358
+ send({
1359
+ kind: "stream-end",
1360
+ runtimeId,
1361
+ id
1362
+ });
1363
+ } catch (error) {
1364
+ if (ended) return;
1365
+ finish();
1366
+ send({
1367
+ kind: "stream-error",
1368
+ runtimeId,
1369
+ id,
1370
+ message: boundedMessage(error)
1371
+ });
1372
+ }
1373
+ }
1374
+ /** Evaluate extension metadata only in the worker and forward the Gateway's existing safe headers. */
1375
+ function snapshotResponseMetadata(response) {
1376
+ const status = response.status;
1377
+ const contentType = response.contentType;
1378
+ if (status !== void 0 && (!Number.isSafeInteger(status) || status < 200 || status > 599)) throw Object.assign(/* @__PURE__ */ new Error("invalid HTTP status"), {
1379
+ code: "invalid_route_response",
1380
+ status: 500
1381
+ });
1382
+ if (contentType !== void 0 && (typeof contentType !== "string" || contentType.length > 1024 || !/^[\x20-\x7e]+$/u.test(contentType) || !/^[\w!#$&+.^-]+\/[\w!#$&+.^-]+(?:;[\x20-\x7e]*)?$/u.test(contentType))) throw Object.assign(/* @__PURE__ */ new Error("invalid content type"), {
1383
+ code: "invalid_route_response",
1384
+ status: 500
1385
+ });
1386
+ const headers = {};
1387
+ const source = response.headers;
1388
+ let bytes = Buffer.byteLength(contentType ?? "");
1389
+ if (source !== void 0) {
1390
+ if (source === null || typeof source !== "object" || Array.isArray(source)) throw Object.assign(/* @__PURE__ */ new Error("invalid response headers"), {
1391
+ code: "invalid_route_response",
1392
+ status: 500
1393
+ });
1394
+ for (const name of Object.keys(source)) {
1395
+ if (!/^(?:content-disposition|cache-control|etag)$/iu.test(name)) continue;
1396
+ const value = source[name];
1397
+ if (typeof value !== "string") throw Object.assign(/* @__PURE__ */ new Error("invalid response header"), {
1398
+ code: "invalid_route_response",
1399
+ status: 500
1400
+ });
1401
+ if (/[\r\n]/u.test(value)) continue;
1402
+ bytes += Buffer.byteLength(name) + Buffer.byteLength(value);
1403
+ if (bytes > 16384) throw Object.assign(/* @__PURE__ */ new Error("response headers are too large"), {
1404
+ code: "invalid_route_response",
1405
+ status: 500
1406
+ });
1407
+ headers[name.toLowerCase()] = value;
1408
+ }
1409
+ }
1410
+ return {
1411
+ ...status === void 0 ? {} : { status },
1412
+ ...contentType === void 0 ? {} : { contentType },
1413
+ ...source === void 0 ? {} : { headers }
1414
+ };
1415
+ }
1416
+ function releaseStreamAccounting(id) {
1417
+ finishedStreams.delete(id);
1418
+ streamCredit.delete(id);
1419
+ streamSent.delete(id);
1420
+ streamAcked.delete(id);
1421
+ wakeSendBudgetWaiters();
1422
+ }
1423
+ async function activate(replyId, hostFile, generation, manifest) {
1424
+ const pendingEffects = [];
1425
+ let activationOpen = true;
1426
+ const ensureOpen = () => {
1427
+ if (!activationOpen || generationController.signal.aborted) throw new Error("host activation is closed");
1428
+ };
1429
+ const api = {
1430
+ manifest: Object.freeze(manifest),
1431
+ context: Object.freeze({ logger: Object.freeze(loggerAdapter) }),
1432
+ schema: Schema,
1433
+ signal: generationController.signal,
1434
+ action(name, spec) {
1435
+ ensureOpen();
1436
+ if (!/^[a-z][a-z0-9-]{0,63}$/u.test(name) || typeof spec?.run !== "function") throw runtimeError("invalid_action", `invalid action ${name}`);
1437
+ if (actions.has(name)) throw runtimeError("duplicate_action", `duplicate action ${name}`);
1438
+ if (actions.size + routes.length >= limits.maxRegistrations) throw runtimeError("extension_registration_limit", "local worker registration limit reached");
1439
+ const timeoutMs = checkedTimeout(spec.timeoutMs, "invalid_action");
1440
+ const input = spec.input;
1441
+ actions.set(name, Object.freeze({
1442
+ run: spec.run.bind(spec),
1443
+ ...input === void 0 ? {} : { input: typeof input === "function" ? input : Object.freeze({ parse: input.parse.bind(input) }) },
1444
+ ...timeoutMs === void 0 ? {} : { timeoutMs }
1445
+ }));
1446
+ },
1447
+ route(spec) {
1448
+ ensureOpen();
1449
+ if (typeof spec?.handle !== "function") throw runtimeError("invalid_route", "invalid route");
1450
+ if (actions.size + routes.length >= limits.maxRegistrations) throw runtimeError("extension_registration_limit", "local worker registration limit reached");
1451
+ const method = spec.method.toUpperCase();
1452
+ if (![
1453
+ "GET",
1454
+ "HEAD",
1455
+ "POST",
1456
+ "PUT",
1457
+ "PATCH",
1458
+ "DELETE"
1459
+ ].includes(method) || spec.kind !== void 0 && spec.kind !== "exact" && spec.kind !== "prefix") throw new Error("invalid route");
1460
+ const path = normalizeWorkerRoutePath(spec.path);
1461
+ const kind = spec.kind ?? "exact";
1462
+ if (routes.some((route) => route.method === method && route.path === path && (route.kind ?? "exact") === kind)) throw new Error("duplicate route");
1463
+ const timeoutMs = checkedTimeout(spec.timeoutMs, "invalid_route");
1464
+ routes.push(Object.freeze({
1465
+ method,
1466
+ path,
1467
+ kind,
1468
+ handle: spec.handle.bind(spec),
1469
+ ...timeoutMs === void 0 ? {} : { timeoutMs }
1470
+ }));
1471
+ },
1472
+ effect(setup) {
1473
+ ensureOpen();
1474
+ const result = setup();
1475
+ if (result instanceof Promise) {
1476
+ const pending = result.then(async (cleanup) => {
1477
+ if (typeof cleanup !== "function") return;
1478
+ if (activationOpen && !generationController.signal.aborted) cleanups.push(cleanup);
1479
+ else await cleanup();
1480
+ });
1481
+ pendingEffects.push(pending);
1482
+ pending.catch(() => void 0);
1483
+ } else if (typeof result === "function") cleanups.push(result);
1484
+ }
1485
+ };
1486
+ let imported;
1487
+ try {
1488
+ imported = await import(`${pathToFileURL(hostFile).href}?dsh_generation=${generation}`);
1489
+ } catch {
1490
+ send({
1491
+ kind: "error",
1492
+ runtimeId,
1493
+ id: replyId,
1494
+ code: "host_load_failed",
1495
+ message: "could not load host.mjs",
1496
+ status: 500
1497
+ });
1498
+ return;
1499
+ }
1500
+ if (generationController.signal.aborted) return;
1501
+ try {
1502
+ if (imported.default !== void 0) await imported.default(api);
1503
+ await Promise.all(pendingEffects);
1504
+ } catch (error) {
1505
+ activationOpen = false;
1506
+ const business = businessErrorShape(error);
1507
+ send({
1508
+ kind: "error",
1509
+ runtimeId,
1510
+ id: replyId,
1511
+ code: business?.code ?? "host_activation_failed",
1512
+ message: boundedMessage(error),
1513
+ status: business?.status ?? 500
1514
+ });
1515
+ return;
1516
+ }
1517
+ activationOpen = false;
1518
+ const actionMetadata = [...actions.entries()].map(([name, spec]) => {
1519
+ const timeoutMs = validOperationTimeout(spec.timeoutMs);
1520
+ return {
1521
+ name,
1522
+ ...timeoutMs === void 0 ? {} : { timeoutMs }
1523
+ };
1524
+ });
1525
+ const routeMetadata = routes.map((route) => {
1526
+ const timeoutMs = validOperationTimeout(route.timeoutMs);
1527
+ return {
1528
+ method: String(route.method).toUpperCase(),
1529
+ path: normalizeWorkerRoutePath(route.path),
1530
+ kind: route.kind ?? "exact",
1531
+ ...timeoutMs === void 0 ? {} : { timeoutMs }
1532
+ };
1533
+ });
1534
+ send({
1535
+ kind: "activated",
1536
+ runtimeId,
1537
+ actions: actionMetadata,
1538
+ routes: routeMetadata
1539
+ });
1540
+ }
1541
+ function checkedTimeout(value, code) {
1542
+ if (value === void 0) return void 0;
1543
+ const timeout = validOperationTimeout(value);
1544
+ if (timeout === void 0) throw Object.assign(/* @__PURE__ */ new Error("operation timeoutMs is invalid"), {
1545
+ code,
1546
+ status: 400
1547
+ });
1548
+ return timeout;
1549
+ }
1550
+ function runtimeError(code, message) {
1551
+ return Object.assign(new Error(message), {
1552
+ code,
1553
+ status: 400
1554
+ });
1555
+ }
1556
+ async function runAction(id, name, deviceId, input) {
1557
+ const spec = actions.get(name);
1558
+ if (spec === void 0) {
1559
+ send({
1560
+ kind: "error",
1561
+ runtimeId,
1562
+ id,
1563
+ code: "action_not_found",
1564
+ message: `action ${name} not found`,
1565
+ status: 404
1566
+ });
1567
+ return;
1568
+ }
1569
+ const controller = new AbortController();
1570
+ requestControllers.set(id, controller);
1571
+ const onGenerationAbort = () => {
1572
+ controller.abort(generationController.signal.reason);
1573
+ };
1574
+ if (generationController.signal.aborted) controller.abort();
1575
+ else generationController.signal.addEventListener("abort", onGenerationAbort, { once: true });
1576
+ const errorReply = (error) => {
1577
+ const business = businessErrorShape(error);
1578
+ if (business !== void 0) {
1579
+ send({
1580
+ kind: "error",
1581
+ runtimeId,
1582
+ id,
1583
+ code: business.code,
1584
+ message: business.message,
1585
+ status: business.status
1586
+ });
1587
+ return;
1588
+ }
1589
+ send({
1590
+ kind: "error",
1591
+ runtimeId,
1592
+ id,
1593
+ code: "extension_failed",
1594
+ message: boundedMessage(error),
1595
+ status: 500
1596
+ });
1597
+ };
1598
+ try {
1599
+ let parsed = input;
1600
+ if (spec.input !== void 0) try {
1601
+ parsed = typeof spec.input === "function" ? spec.input(input) : spec.input.parse(input) ?? input;
1602
+ parsed = await parsed;
1603
+ } catch {
1604
+ send({
1605
+ kind: "error",
1606
+ runtimeId,
1607
+ id,
1608
+ code: "invalid_action_input",
1609
+ message: "action input is invalid",
1610
+ status: 400
1611
+ });
1612
+ return;
1613
+ }
1614
+ controller.signal.throwIfAborted();
1615
+ const bytes = serializeWorkerResult(await spec.run({
1616
+ signal: controller.signal,
1617
+ deviceId
1618
+ }, parsed));
1619
+ if (bytes.byteLength > limits.resultMaxBytes) {
1620
+ send({
1621
+ kind: "error",
1622
+ runtimeId,
1623
+ id,
1624
+ code: "extension_result_too_large",
1625
+ message: "extension result is too large",
1626
+ status: 500
1627
+ });
1628
+ return;
1629
+ }
1630
+ send({
1631
+ kind: "result",
1632
+ runtimeId,
1633
+ id,
1634
+ bytes
1635
+ });
1636
+ } catch (error) {
1637
+ errorReply(error);
1638
+ } finally {
1639
+ requestControllers.delete(id);
1640
+ generationController.signal.removeEventListener("abort", onGenerationAbort);
1641
+ }
1642
+ }
1643
+ //#endregion
1644
+ export {};
1645
+
1646
+ //# sourceMappingURL=extension-worker-runtime.mjs.map