@ggui-ai/ui-gen 0.15.0 → 0.16.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.
Files changed (101) hide show
  1. package/dist/adapters/generation-dispatch.d.ts +21 -4
  2. package/dist/adapters/generation-dispatch.js +913 -350
  3. package/dist/adapters/generation-dispatch.js.map +1 -1
  4. package/dist/adapters/index.js +26 -22
  5. package/dist/adapters/index.js.map +1 -1
  6. package/dist/advanced/index.d.ts +17 -12
  7. package/dist/advanced/index.js +966 -374
  8. package/dist/advanced/index.js.map +1 -1
  9. package/dist/boilerplate.d.ts +16 -1
  10. package/dist/boilerplate.js +579 -245
  11. package/dist/boilerplate.js.map +1 -1
  12. package/dist/check/index.d.ts +17 -3
  13. package/dist/check/index.js +32 -25
  14. package/dist/check/index.js.map +1 -1
  15. package/dist/{create-ui-generator-D6TKuv9V.d.ts → create-ui-generator-CCIeQaEe.d.ts} +77 -10
  16. package/dist/design-mode-BHEE7flj.d.ts +67 -0
  17. package/dist/{dispatch-BuZfTh9r.d.ts → dispatch-BA5dJcg-.d.ts} +4 -1
  18. package/dist/evaluation/axis-checks/index.d.ts +4 -3
  19. package/dist/evaluation/axis-checks/index.js +3 -1
  20. package/dist/evaluation/axis-checks/index.js.map +1 -1
  21. package/dist/evaluation/axis-checks/registry.d.ts +2 -1
  22. package/dist/evaluation/axis-checks/registry.js +1 -0
  23. package/dist/evaluation/axis-checks/registry.js.map +1 -1
  24. package/dist/evaluation/index.d.ts +143 -3
  25. package/dist/evaluation/index.js +3866 -92
  26. package/dist/evaluation/index.js.map +1 -1
  27. package/dist/{generate-BTfvELgl.d.ts → generate-8L_bc2iP.d.ts} +10 -1
  28. package/dist/harness/check/runtime-render/index.d.ts +2 -1
  29. package/dist/harness/index.d.ts +2 -1
  30. package/dist/harness/index.js +589 -248
  31. package/dist/harness/index.js.map +1 -1
  32. package/dist/harness/llm-trace-sink.d.ts +3 -3
  33. package/dist/harness/llm-trace-sink.js.map +1 -1
  34. package/dist/harness/prompts.d.ts +2 -1
  35. package/dist/harness/prompts.js +3 -0
  36. package/dist/harness/prompts.js.map +1 -1
  37. package/dist/harness/result-types.d.ts +17 -5
  38. package/dist/harness/result-types.js.map +1 -1
  39. package/dist/harness/runtime.d.ts +19 -3
  40. package/dist/harness/runtime.js +602 -261
  41. package/dist/harness/runtime.js.map +1 -1
  42. package/dist/harness/types-public.d.ts +28 -1
  43. package/dist/harness/types-public.js +589 -248
  44. package/dist/harness/types-public.js.map +1 -1
  45. package/dist/harness/validator-trace-sink.d.ts +2 -1
  46. package/dist/index.d.ts +8 -4
  47. package/dist/index.js +973 -372
  48. package/dist/index.js.map +1 -1
  49. package/dist/patch.d.ts +2 -1
  50. package/dist/{prompts-BVhtH3M1.d.ts → prompts-k6m6reqe.d.ts} +11 -1
  51. package/dist/providers/index.d.ts +2 -2
  52. package/dist/providers/index.js.map +1 -1
  53. package/dist/tools/get-primitives-ts.d.ts +1 -1
  54. package/dist/tools/get-primitives-ts.js +1 -1
  55. package/dist/tools/get-primitives-ts.js.map +1 -1
  56. package/dist/{types-public-CkNWEov9.d.ts → types-public-D24JLJgl.d.ts} +49 -5
  57. package/dist/validation/index.d.ts +1 -1
  58. package/dist/validation/index.js +4 -4
  59. package/dist/validation/index.js.map +1 -1
  60. package/dist/workflows.d.ts +2 -1
  61. package/package.json +12 -12
  62. package/src/adapters/generation-dispatch.ts +57 -4
  63. package/src/adapters/provider-router.ts +7 -6
  64. package/src/adapters/tools.ts +5 -5
  65. package/src/advanced/generator.ts +11 -10
  66. package/src/advanced/index.ts +5 -4
  67. package/src/boilerplate/free-design-prompt.ts +329 -0
  68. package/src/boilerplate/generate.ts +10 -1
  69. package/src/boilerplate/hard-sections.ts +242 -0
  70. package/src/boilerplate/render.ts +32 -8
  71. package/src/boilerplate/system-prompt.ts +81 -229
  72. package/src/boilerplate/templates/base-free.tsx.tmpl +24 -0
  73. package/src/check/run-tier0.ts +80 -20
  74. package/src/coding-agent/tools.ts +8 -2
  75. package/src/contract-context.ts +28 -0
  76. package/src/create-harness.ts +11 -0
  77. package/src/create-ui-generator.ts +71 -25
  78. package/src/design-mode.ts +182 -0
  79. package/src/design-system-docs.ts +17 -13
  80. package/src/evaluation/axis-checks/dispatch.ts +4 -0
  81. package/src/evaluation/axis-checks/extras.ts +5 -0
  82. package/src/evaluation/cost-tracker.ts +2 -3
  83. package/src/evaluation/index.ts +46 -2
  84. package/src/evaluation/llm-evaluator.ts +77 -21
  85. package/src/evaluation/types-public.ts +103 -8
  86. package/src/evaluation/visual-evaluator.ts +301 -29
  87. package/src/harness/coding/dupe-break.ts +0 -0
  88. package/src/harness/coding/init-session.ts +1 -0
  89. package/src/harness/coding/run-coding-turn.ts +3 -0
  90. package/src/harness/coding/run-eval-round.ts +15 -2
  91. package/src/harness/llm-trace-sink.ts +3 -3
  92. package/src/harness/result-types.ts +15 -3
  93. package/src/harness/runtime.ts +18 -0
  94. package/src/harness/types-public.ts +27 -0
  95. package/src/index.ts +26 -0
  96. package/src/internal/extract-call-signatures.ts +2 -2
  97. package/src/providers/bedrock.ts +4 -4
  98. package/src/run-check.ts +1 -0
  99. package/src/tools/get-primitives-ts.ts +1 -1
  100. package/src/validation/allowed-imports.ts +8 -2
  101. package/src/validation/primitives.ts +1 -1
@@ -1,19 +1,56 @@
1
+ import { mkdirSync, writeFileSync, unlinkSync, existsSync, rm, createReadStream, createWriteStream } from 'fs';
2
+ import 'fs/promises';
3
+ import { tmpdir } from 'os';
4
+ import { resolve, dirname, join, basename } from 'path';
5
+ import { Readable } from 'stream';
6
+ import { pipeline } from 'stream/promises';
7
+ import { createBrotliDecompress, createUnzip } from 'zlib';
8
+ import { fileURLToPath } from 'url';
1
9
  import { query, createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
2
10
  import Anthropic from '@anthropic-ai/sdk';
3
11
  import { z } from 'zod';
4
12
  import { listContractGadgets, HOOK_NAME_RE, STDLIB_GADGETS_PACKAGE } from '@ggui-ai/protocol';
5
- import 'esbuild';
6
- import '@ggui-ai/design/rendering';
13
+ import { build } from 'esbuild';
14
+ import { getCssTokens } from '@ggui-ai/design/rendering';
7
15
 
16
+ var __create = Object.create;
8
17
  var __defProp = Object.defineProperty;
18
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
19
  var __getOwnPropNames = Object.getOwnPropertyNames;
20
+ var __getProtoOf = Object.getPrototypeOf;
21
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
22
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
23
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
24
+ }) : x)(function(x) {
25
+ if (typeof require !== "undefined") return require.apply(this, arguments);
26
+ throw Error('Dynamic require of "' + x + '" is not supported');
27
+ });
10
28
  var __esm = (fn, res) => function __init() {
11
29
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
30
  };
31
+ var __commonJS = (cb, mod) => function __require2() {
32
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
33
+ };
13
34
  var __export = (target, all) => {
14
35
  for (var name in all)
15
36
  __defProp(target, name, { get: all[name], enumerable: true });
16
37
  };
38
+ var __copyProps = (to, from, except, desc) => {
39
+ if (from && typeof from === "object" || typeof from === "function") {
40
+ for (let key of __getOwnPropNames(from))
41
+ if (!__hasOwnProp.call(to, key) && key !== except)
42
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
43
+ }
44
+ return to;
45
+ };
46
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
47
+ // If the importer is in node compatibility mode or this is not an ESM
48
+ // file that has been converted to a CommonJS file using a Babel-
49
+ // compatible transform (i.e. "__esModule" has not been set), then set
50
+ // "default" to the CommonJS "module.exports" for node compatibility.
51
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
52
+ mod
53
+ ));
17
54
 
18
55
  // src/adapters/openrouter/types.ts
19
56
  var OpenRouterError;
@@ -27,103 +64,3352 @@ var init_types = __esm({
27
64
  this.headers = headers;
28
65
  this.name = "OpenRouterError";
29
66
  }
30
- status;
31
- code;
32
- headers;
33
- get isTransient() {
34
- return this.status === 408 || this.status === 429 || this.status === 502 || this.status === 503;
67
+ status;
68
+ code;
69
+ headers;
70
+ get isTransient() {
71
+ return this.status === 408 || this.status === 429 || this.status === 502 || this.status === 503;
72
+ }
73
+ };
74
+ }
75
+ });
76
+
77
+ // src/adapters/openrouter/client.ts
78
+ var client_exports = {};
79
+ __export(client_exports, {
80
+ OpenRouterClient: () => OpenRouterClient
81
+ });
82
+ var DEFAULT_BASE_URL, OpenRouterClient;
83
+ var init_client = __esm({
84
+ "src/adapters/openrouter/client.ts"() {
85
+ init_types();
86
+ DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
87
+ OpenRouterClient = class {
88
+ constructor(config) {
89
+ this.config = config;
90
+ this.baseUrl = config.baseUrl ?? process.env.OPENROUTER_BASE_URL ?? DEFAULT_BASE_URL;
91
+ this.headers = {
92
+ "Authorization": `Bearer ${config.apiKey}`,
93
+ "Content-Type": "application/json",
94
+ "HTTP-Referer": config.siteUrl ?? process.env.OPENROUTER_SITE_URL ?? "https://ggui.ai",
95
+ "X-Title": config.siteName ?? process.env.OPENROUTER_SITE_NAME ?? "ggui"
96
+ };
97
+ }
98
+ config;
99
+ baseUrl;
100
+ headers;
101
+ /**
102
+ * Non-streaming chat completion.
103
+ */
104
+ async chatCompletion(params) {
105
+ const body = { ...params, stream: false };
106
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
107
+ method: "POST",
108
+ headers: this.headers,
109
+ body: JSON.stringify(body)
110
+ });
111
+ if (!response.ok) {
112
+ const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));
113
+ const message = errorBody.error?.message ?? response.statusText;
114
+ throw new OpenRouterError(message, response.status, void 0, response.headers);
115
+ }
116
+ return response.json();
117
+ }
118
+ /**
119
+ * Streaming chat completion via SSE.
120
+ * Yields delta chunks, accumulates the final usage from the last chunk.
121
+ */
122
+ async *chatCompletionStream(params) {
123
+ const body = { ...params, stream: true };
124
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
125
+ method: "POST",
126
+ headers: this.headers,
127
+ body: JSON.stringify(body)
128
+ });
129
+ if (!response.ok) {
130
+ const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));
131
+ const message = errorBody.error?.message ?? response.statusText;
132
+ throw new OpenRouterError(message, response.status, void 0, response.headers);
133
+ }
134
+ if (!response.body) {
135
+ throw new OpenRouterError("No response body for streaming request", 500);
136
+ }
137
+ const reader = response.body.getReader();
138
+ const decoder = new TextDecoder();
139
+ let buffer = "";
140
+ try {
141
+ while (true) {
142
+ const { done, value } = await reader.read();
143
+ if (done) break;
144
+ buffer += decoder.decode(value, { stream: true });
145
+ const lines = buffer.split("\n");
146
+ buffer = lines.pop() ?? "";
147
+ for (const line of lines) {
148
+ const trimmed = line.trim();
149
+ if (!trimmed || trimmed.startsWith(":")) continue;
150
+ if (trimmed === "data: [DONE]") return;
151
+ if (!trimmed.startsWith("data: ")) continue;
152
+ const json = trimmed.slice("data: ".length);
153
+ try {
154
+ yield JSON.parse(json);
155
+ } catch {
156
+ }
157
+ }
158
+ }
159
+ } finally {
160
+ reader.releaseLock();
161
+ }
162
+ }
163
+ };
164
+ }
165
+ });
166
+
167
+ // ../../node_modules/events-universal/default.js
168
+ var require_default = __commonJS({
169
+ "../../node_modules/events-universal/default.js"(exports, module) {
170
+ module.exports = __require("events");
171
+ }
172
+ });
173
+
174
+ // ../../node_modules/fast-fifo/fixed-size.js
175
+ var require_fixed_size = __commonJS({
176
+ "../../node_modules/fast-fifo/fixed-size.js"(exports, module) {
177
+ module.exports = class FixedFIFO {
178
+ constructor(hwm) {
179
+ if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two");
180
+ this.buffer = new Array(hwm);
181
+ this.mask = hwm - 1;
182
+ this.top = 0;
183
+ this.btm = 0;
184
+ this.next = null;
185
+ }
186
+ clear() {
187
+ this.top = this.btm = 0;
188
+ this.next = null;
189
+ this.buffer.fill(void 0);
190
+ }
191
+ push(data) {
192
+ if (this.buffer[this.top] !== void 0) return false;
193
+ this.buffer[this.top] = data;
194
+ this.top = this.top + 1 & this.mask;
195
+ return true;
196
+ }
197
+ shift() {
198
+ const last = this.buffer[this.btm];
199
+ if (last === void 0) return void 0;
200
+ this.buffer[this.btm] = void 0;
201
+ this.btm = this.btm + 1 & this.mask;
202
+ return last;
203
+ }
204
+ peek() {
205
+ return this.buffer[this.btm];
206
+ }
207
+ isEmpty() {
208
+ return this.buffer[this.btm] === void 0;
209
+ }
210
+ };
211
+ }
212
+ });
213
+
214
+ // ../../node_modules/fast-fifo/index.js
215
+ var require_fast_fifo = __commonJS({
216
+ "../../node_modules/fast-fifo/index.js"(exports, module) {
217
+ var FixedFIFO = require_fixed_size();
218
+ module.exports = class FastFIFO {
219
+ constructor(hwm) {
220
+ this.hwm = hwm || 16;
221
+ this.head = new FixedFIFO(this.hwm);
222
+ this.tail = this.head;
223
+ this.length = 0;
224
+ }
225
+ clear() {
226
+ this.head = this.tail;
227
+ this.head.clear();
228
+ this.length = 0;
229
+ }
230
+ push(val) {
231
+ this.length++;
232
+ if (!this.head.push(val)) {
233
+ const prev = this.head;
234
+ this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
235
+ this.head.push(val);
236
+ }
237
+ }
238
+ shift() {
239
+ if (this.length !== 0) this.length--;
240
+ const val = this.tail.shift();
241
+ if (val === void 0 && this.tail.next) {
242
+ const next = this.tail.next;
243
+ this.tail.next = null;
244
+ this.tail = next;
245
+ return this.tail.shift();
246
+ }
247
+ return val;
248
+ }
249
+ peek() {
250
+ const val = this.tail.peek();
251
+ if (val === void 0 && this.tail.next) return this.tail.next.peek();
252
+ return val;
253
+ }
254
+ isEmpty() {
255
+ return this.length === 0;
256
+ }
257
+ };
258
+ }
259
+ });
260
+
261
+ // ../../node_modules/b4a/index.js
262
+ var require_b4a = __commonJS({
263
+ "../../node_modules/b4a/index.js"(exports, module) {
264
+ function isBuffer(value) {
265
+ return Buffer.isBuffer(value) || value instanceof Uint8Array;
266
+ }
267
+ function isEncoding(encoding) {
268
+ return Buffer.isEncoding(encoding);
269
+ }
270
+ function alloc(size, fill2, encoding) {
271
+ return Buffer.alloc(size, fill2, encoding);
272
+ }
273
+ function allocUnsafe(size) {
274
+ return Buffer.allocUnsafe(size);
275
+ }
276
+ function allocUnsafeSlow(size) {
277
+ return Buffer.allocUnsafeSlow(size);
278
+ }
279
+ function byteLength(string, encoding) {
280
+ return Buffer.byteLength(string, encoding);
281
+ }
282
+ function compare(a, b) {
283
+ return Buffer.compare(a, b);
284
+ }
285
+ function concat(buffers, totalLength) {
286
+ return Buffer.concat(buffers, totalLength);
287
+ }
288
+ function copy(source, target, targetStart, start, end) {
289
+ return toBuffer(source).copy(target, targetStart, start, end);
290
+ }
291
+ function equals(a, b) {
292
+ return toBuffer(a).equals(b);
293
+ }
294
+ function fill(buffer, value, offset, end, encoding) {
295
+ return toBuffer(buffer).fill(value, offset, end, encoding);
296
+ }
297
+ function from(value, encodingOrOffset, length) {
298
+ return Buffer.from(value, encodingOrOffset, length);
299
+ }
300
+ function includes(buffer, value, byteOffset, encoding) {
301
+ return toBuffer(buffer).includes(value, byteOffset, encoding);
302
+ }
303
+ function indexOf(buffer, value, byfeOffset, encoding) {
304
+ return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
305
+ }
306
+ function lastIndexOf(buffer, value, byteOffset, encoding) {
307
+ return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
308
+ }
309
+ function swap16(buffer) {
310
+ return toBuffer(buffer).swap16();
311
+ }
312
+ function swap32(buffer) {
313
+ return toBuffer(buffer).swap32();
314
+ }
315
+ function swap64(buffer) {
316
+ return toBuffer(buffer).swap64();
317
+ }
318
+ function toBuffer(buffer) {
319
+ if (Buffer.isBuffer(buffer)) return buffer;
320
+ return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
321
+ }
322
+ function toString(buffer, encoding, start, end) {
323
+ return toBuffer(buffer).toString(encoding, start, end);
324
+ }
325
+ function write(buffer, string, offset, length, encoding) {
326
+ return toBuffer(buffer).write(string, offset, length, encoding);
327
+ }
328
+ function readDoubleBE(buffer, offset) {
329
+ return toBuffer(buffer).readDoubleBE(offset);
330
+ }
331
+ function readDoubleLE(buffer, offset) {
332
+ return toBuffer(buffer).readDoubleLE(offset);
333
+ }
334
+ function readFloatBE(buffer, offset) {
335
+ return toBuffer(buffer).readFloatBE(offset);
336
+ }
337
+ function readFloatLE(buffer, offset) {
338
+ return toBuffer(buffer).readFloatLE(offset);
339
+ }
340
+ function readInt32BE(buffer, offset) {
341
+ return toBuffer(buffer).readInt32BE(offset);
342
+ }
343
+ function readInt32LE(buffer, offset) {
344
+ return toBuffer(buffer).readInt32LE(offset);
345
+ }
346
+ function readUInt32BE(buffer, offset) {
347
+ return toBuffer(buffer).readUInt32BE(offset);
348
+ }
349
+ function readUInt32LE(buffer, offset) {
350
+ return toBuffer(buffer).readUInt32LE(offset);
351
+ }
352
+ function writeDoubleBE(buffer, value, offset) {
353
+ return toBuffer(buffer).writeDoubleBE(value, offset);
354
+ }
355
+ function writeDoubleLE(buffer, value, offset) {
356
+ return toBuffer(buffer).writeDoubleLE(value, offset);
357
+ }
358
+ function writeFloatBE(buffer, value, offset) {
359
+ return toBuffer(buffer).writeFloatBE(value, offset);
360
+ }
361
+ function writeFloatLE(buffer, value, offset) {
362
+ return toBuffer(buffer).writeFloatLE(value, offset);
363
+ }
364
+ function writeInt32BE(buffer, value, offset) {
365
+ return toBuffer(buffer).writeInt32BE(value, offset);
366
+ }
367
+ function writeInt32LE(buffer, value, offset) {
368
+ return toBuffer(buffer).writeInt32LE(value, offset);
369
+ }
370
+ function writeUInt32BE(buffer, value, offset) {
371
+ return toBuffer(buffer).writeUInt32BE(value, offset);
372
+ }
373
+ function writeUInt32LE(buffer, value, offset) {
374
+ return toBuffer(buffer).writeUInt32LE(value, offset);
375
+ }
376
+ module.exports = {
377
+ isBuffer,
378
+ isEncoding,
379
+ alloc,
380
+ allocUnsafe,
381
+ allocUnsafeSlow,
382
+ byteLength,
383
+ compare,
384
+ concat,
385
+ copy,
386
+ equals,
387
+ fill,
388
+ from,
389
+ includes,
390
+ indexOf,
391
+ lastIndexOf,
392
+ swap16,
393
+ swap32,
394
+ swap64,
395
+ toBuffer,
396
+ toString,
397
+ write,
398
+ readDoubleBE,
399
+ readDoubleLE,
400
+ readFloatBE,
401
+ readFloatLE,
402
+ readInt32BE,
403
+ readInt32LE,
404
+ readUInt32BE,
405
+ readUInt32LE,
406
+ writeDoubleBE,
407
+ writeDoubleLE,
408
+ writeFloatBE,
409
+ writeFloatLE,
410
+ writeInt32BE,
411
+ writeInt32LE,
412
+ writeUInt32BE,
413
+ writeUInt32LE
414
+ };
415
+ }
416
+ });
417
+
418
+ // ../../node_modules/text-decoder/lib/pass-through-decoder.js
419
+ var require_pass_through_decoder = __commonJS({
420
+ "../../node_modules/text-decoder/lib/pass-through-decoder.js"(exports, module) {
421
+ var b4a = require_b4a();
422
+ module.exports = class PassThroughDecoder {
423
+ constructor(encoding) {
424
+ this.encoding = encoding;
425
+ }
426
+ get remaining() {
427
+ return 0;
428
+ }
429
+ decode(data) {
430
+ return b4a.toString(data, this.encoding);
431
+ }
432
+ flush() {
433
+ return "";
434
+ }
435
+ };
436
+ }
437
+ });
438
+
439
+ // ../../node_modules/text-decoder/lib/utf8-decoder.js
440
+ var require_utf8_decoder = __commonJS({
441
+ "../../node_modules/text-decoder/lib/utf8-decoder.js"(exports, module) {
442
+ var b4a = require_b4a();
443
+ module.exports = class UTF8Decoder {
444
+ constructor() {
445
+ this._reset();
446
+ }
447
+ get remaining() {
448
+ return this.bytesSeen;
449
+ }
450
+ decode(data) {
451
+ if (data.byteLength === 0) return "";
452
+ if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
453
+ this.bytesSeen = trailingBytesSeen(data);
454
+ return b4a.toString(data, "utf8");
455
+ }
456
+ let result = "";
457
+ let start = 0;
458
+ if (this.bytesNeeded > 0) {
459
+ while (start < data.byteLength) {
460
+ const byte = data[start];
461
+ if (byte < this.lowerBoundary || byte > this.upperBoundary) {
462
+ result += "\uFFFD";
463
+ this._reset();
464
+ break;
465
+ }
466
+ this.lowerBoundary = 128;
467
+ this.upperBoundary = 191;
468
+ this.codePoint = this.codePoint << 6 | byte & 63;
469
+ this.bytesSeen++;
470
+ start++;
471
+ if (this.bytesSeen === this.bytesNeeded) {
472
+ result += String.fromCodePoint(this.codePoint);
473
+ this._reset();
474
+ break;
475
+ }
476
+ }
477
+ if (this.bytesNeeded > 0) return result;
478
+ }
479
+ const trailing = trailingIncomplete(data, start);
480
+ const end = data.byteLength - trailing;
481
+ if (end > start) result += b4a.toString(data, "utf8", start, end);
482
+ for (let i = end; i < data.byteLength; i++) {
483
+ const byte = data[i];
484
+ if (this.bytesNeeded === 0) {
485
+ if (byte <= 127) {
486
+ this.bytesSeen = 0;
487
+ result += String.fromCharCode(byte);
488
+ } else if (byte >= 194 && byte <= 223) {
489
+ this.bytesNeeded = 2;
490
+ this.bytesSeen = 1;
491
+ this.codePoint = byte & 31;
492
+ } else if (byte >= 224 && byte <= 239) {
493
+ if (byte === 224) this.lowerBoundary = 160;
494
+ else if (byte === 237) this.upperBoundary = 159;
495
+ this.bytesNeeded = 3;
496
+ this.bytesSeen = 1;
497
+ this.codePoint = byte & 15;
498
+ } else if (byte >= 240 && byte <= 244) {
499
+ if (byte === 240) this.lowerBoundary = 144;
500
+ else if (byte === 244) this.upperBoundary = 143;
501
+ this.bytesNeeded = 4;
502
+ this.bytesSeen = 1;
503
+ this.codePoint = byte & 7;
504
+ } else {
505
+ this.bytesSeen = 1;
506
+ result += "\uFFFD";
507
+ }
508
+ continue;
509
+ }
510
+ if (byte < this.lowerBoundary || byte > this.upperBoundary) {
511
+ result += "\uFFFD";
512
+ i--;
513
+ this._reset();
514
+ continue;
515
+ }
516
+ this.lowerBoundary = 128;
517
+ this.upperBoundary = 191;
518
+ this.codePoint = this.codePoint << 6 | byte & 63;
519
+ this.bytesSeen++;
520
+ if (this.bytesSeen === this.bytesNeeded) {
521
+ result += String.fromCodePoint(this.codePoint);
522
+ this._reset();
523
+ }
524
+ }
525
+ return result;
526
+ }
527
+ flush() {
528
+ const result = this.bytesNeeded > 0 ? "\uFFFD" : "";
529
+ this._reset();
530
+ return result;
531
+ }
532
+ _reset() {
533
+ this.codePoint = 0;
534
+ this.bytesNeeded = 0;
535
+ this.bytesSeen = 0;
536
+ this.lowerBoundary = 128;
537
+ this.upperBoundary = 191;
538
+ }
539
+ };
540
+ function trailingIncomplete(data, start) {
541
+ const len = data.byteLength;
542
+ if (len <= start) return 0;
543
+ const limit = Math.max(start, len - 4);
544
+ let i = len - 1;
545
+ while (i > limit && (data[i] & 192) === 128) i--;
546
+ if (i < start) return 0;
547
+ const byte = data[i];
548
+ let needed;
549
+ if (byte <= 127) return 0;
550
+ if (byte >= 194 && byte <= 223) needed = 2;
551
+ else if (byte >= 224 && byte <= 239) needed = 3;
552
+ else if (byte >= 240 && byte <= 244) needed = 4;
553
+ else return 0;
554
+ const available = len - i;
555
+ return available < needed ? available : 0;
556
+ }
557
+ function trailingBytesSeen(data) {
558
+ const len = data.byteLength;
559
+ if (len === 0) return 0;
560
+ const last = data[len - 1];
561
+ if (last <= 127) return 0;
562
+ if ((last & 192) !== 128) return 1;
563
+ const limit = Math.max(0, len - 4);
564
+ let i = len - 2;
565
+ while (i >= limit && (data[i] & 192) === 128) i--;
566
+ if (i < 0) return 1;
567
+ const first = data[i];
568
+ let needed;
569
+ if (first >= 194 && first <= 223) needed = 2;
570
+ else if (first >= 224 && first <= 239) needed = 3;
571
+ else if (first >= 240 && first <= 244) needed = 4;
572
+ else return 1;
573
+ if (len - i !== needed) return 1;
574
+ if (needed >= 3) {
575
+ const second = data[i + 1];
576
+ if (first === 224 && second < 160) return 1;
577
+ if (first === 237 && second > 159) return 1;
578
+ if (first === 240 && second < 144) return 1;
579
+ if (first === 244 && second > 143) return 1;
580
+ }
581
+ return 0;
582
+ }
583
+ }
584
+ });
585
+
586
+ // ../../node_modules/text-decoder/index.js
587
+ var require_text_decoder = __commonJS({
588
+ "../../node_modules/text-decoder/index.js"(exports, module) {
589
+ var PassThroughDecoder = require_pass_through_decoder();
590
+ var UTF8Decoder = require_utf8_decoder();
591
+ module.exports = class TextDecoder {
592
+ constructor(encoding = "utf8") {
593
+ this.encoding = normalizeEncoding(encoding);
594
+ switch (this.encoding) {
595
+ case "utf8":
596
+ this.decoder = new UTF8Decoder();
597
+ break;
598
+ case "utf16le":
599
+ case "base64":
600
+ throw new Error("Unsupported encoding: " + this.encoding);
601
+ default:
602
+ this.decoder = new PassThroughDecoder(this.encoding);
603
+ }
604
+ }
605
+ get remaining() {
606
+ return this.decoder.remaining;
607
+ }
608
+ push(data) {
609
+ if (typeof data === "string") return data;
610
+ return this.decoder.decode(data);
611
+ }
612
+ // For Node.js compatibility
613
+ write(data) {
614
+ return this.push(data);
615
+ }
616
+ end(data) {
617
+ let result = "";
618
+ if (data) result = this.push(data);
619
+ result += this.decoder.flush();
620
+ return result;
621
+ }
622
+ };
623
+ function normalizeEncoding(encoding) {
624
+ encoding = encoding.toLowerCase();
625
+ switch (encoding) {
626
+ case "utf8":
627
+ case "utf-8":
628
+ return "utf8";
629
+ case "ucs2":
630
+ case "ucs-2":
631
+ case "utf16le":
632
+ case "utf-16le":
633
+ return "utf16le";
634
+ case "latin1":
635
+ case "binary":
636
+ return "latin1";
637
+ case "base64":
638
+ case "ascii":
639
+ case "hex":
640
+ return encoding;
641
+ default:
642
+ throw new Error("Unknown encoding: " + encoding);
643
+ }
644
+ }
645
+ }
646
+ });
647
+
648
+ // ../../node_modules/streamx/lib/errors.js
649
+ var require_errors = __commonJS({
650
+ "../../node_modules/streamx/lib/errors.js"(exports, module) {
651
+ module.exports = class StreamError extends Error {
652
+ constructor(msg, code, fn = StreamError) {
653
+ super(msg);
654
+ this.code = code;
655
+ if (Error.captureStackTrace) {
656
+ Error.captureStackTrace(this, fn);
657
+ }
658
+ }
659
+ static isStreamDestroyed(err) {
660
+ return err && err.code === "STREAM_DESTROYED";
661
+ }
662
+ static isPrematureClose(err) {
663
+ return err && err.code === "PREMATURE_CLOSE";
664
+ }
665
+ static isAborted(err) {
666
+ return err && err.code === "ABORTED";
667
+ }
668
+ static isBadArgument(err) {
669
+ return err && err.code === "BAD_ARGUMENT";
670
+ }
671
+ get name() {
672
+ return "StreamError";
673
+ }
674
+ static STREAM_DESTROYED() {
675
+ return new StreamError("Stream was destroyed", "STREAM_DESTROYED", StreamError.STREAM_DESTROYED);
676
+ }
677
+ static PREMATURE_CLOSE(msg = "Premature close") {
678
+ return new StreamError(msg, "PREMATURE_CLOSE", StreamError.PREMATURE_CLOSE);
679
+ }
680
+ static ABORTED() {
681
+ return new StreamError("Stream aborted", "ABORTED", StreamError.ABORTED);
682
+ }
683
+ static BAD_ARGUMENT(msg = "Bad argument") {
684
+ return new StreamError(msg, "BAD_ARGUMENT", StreamError.BAD_ARGUMENT);
685
+ }
686
+ };
687
+ }
688
+ });
689
+
690
+ // ../../node_modules/streamx/index.js
691
+ var require_streamx = __commonJS({
692
+ "../../node_modules/streamx/index.js"(exports, module) {
693
+ var { EventEmitter } = require_default();
694
+ var FIFO = require_fast_fifo();
695
+ var TextDecoder2 = require_text_decoder();
696
+ var StreamError = require_errors();
697
+ var qmt = typeof queueMicrotask === "undefined" ? (fn) => global.process.nextTick(fn) : queueMicrotask;
698
+ var MAX = (1 << 29) - 1;
699
+ var OPENING = 1;
700
+ var PREDESTROYING = 2;
701
+ var DESTROYING = 4;
702
+ var DESTROYED = 8;
703
+ var NOT_OPENING = MAX ^ OPENING;
704
+ var NOT_PREDESTROYING = MAX ^ PREDESTROYING;
705
+ var READ_ACTIVE = 1 << 4;
706
+ var READ_UPDATING = 2 << 4;
707
+ var READ_PRIMARY = 4 << 4;
708
+ var READ_QUEUED = 8 << 4;
709
+ var READ_RESUMED = 16 << 4;
710
+ var READ_PIPE_DRAINED = 32 << 4;
711
+ var READ_ENDING = 64 << 4;
712
+ var READ_EMIT_DATA = 128 << 4;
713
+ var READ_EMIT_READABLE = 256 << 4;
714
+ var READ_EMITTED_READABLE = 512 << 4;
715
+ var READ_DONE = 1024 << 4;
716
+ var READ_NEXT_TICK = 2048 << 4;
717
+ var READ_NEEDS_PUSH = 4096 << 4;
718
+ var READ_READ_AHEAD = 8192 << 4;
719
+ var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED;
720
+ var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH;
721
+ var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE;
722
+ var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED;
723
+ var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD;
724
+ var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE;
725
+ var READ_NON_PRIMARY = MAX ^ READ_PRIMARY;
726
+ var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH);
727
+ var READ_PUSHED = MAX ^ READ_NEEDS_PUSH;
728
+ var READ_PAUSED = MAX ^ READ_RESUMED;
729
+ var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE);
730
+ var READ_NOT_ENDING = MAX ^ READ_ENDING;
731
+ var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING;
732
+ var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK;
733
+ var READ_NOT_UPDATING = MAX ^ READ_UPDATING;
734
+ var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD;
735
+ var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD;
736
+ var WRITE_ACTIVE = 1 << 18;
737
+ var WRITE_UPDATING = 2 << 18;
738
+ var WRITE_PRIMARY = 4 << 18;
739
+ var WRITE_QUEUED = 8 << 18;
740
+ var WRITE_UNDRAINED = 16 << 18;
741
+ var WRITE_DONE = 32 << 18;
742
+ var WRITE_EMIT_DRAIN = 64 << 18;
743
+ var WRITE_NEXT_TICK = 128 << 18;
744
+ var WRITE_WRITING = 256 << 18;
745
+ var WRITE_FINISHING = 512 << 18;
746
+ var WRITE_CORKED = 1024 << 18;
747
+ var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING);
748
+ var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY;
749
+ var WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING);
750
+ var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED;
751
+ var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED;
752
+ var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK;
753
+ var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING;
754
+ var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED;
755
+ var ACTIVE = READ_ACTIVE | WRITE_ACTIVE;
756
+ var NOT_ACTIVE = MAX ^ ACTIVE;
757
+ var DONE = READ_DONE | WRITE_DONE;
758
+ var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING;
759
+ var OPEN_STATUS = DESTROY_STATUS | OPENING;
760
+ var AUTO_DESTROY = DESTROY_STATUS | DONE;
761
+ var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY;
762
+ var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK;
763
+ var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE;
764
+ var IS_OPENING = OPEN_STATUS | TICKING;
765
+ var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE;
766
+ var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED;
767
+ var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED;
768
+ var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE;
769
+ var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD;
770
+ var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE;
771
+ var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY;
772
+ var READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING;
773
+ var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE;
774
+ var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED;
775
+ var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE;
776
+ var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE;
777
+ var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED;
778
+ var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE;
779
+ var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING;
780
+ var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE;
781
+ var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE;
782
+ var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY;
783
+ var WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS;
784
+ var asyncIterator = Symbol.asyncIterator || /* @__PURE__ */ Symbol("asyncIterator");
785
+ var WritableState = class {
786
+ constructor(stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) {
787
+ this.stream = stream;
788
+ this.queue = new FIFO();
789
+ this.highWaterMark = highWaterMark;
790
+ this.buffered = 0;
791
+ this.error = null;
792
+ this.pipeline = null;
793
+ this.drains = null;
794
+ this.byteLength = byteLengthWritable || byteLength || defaultByteLength;
795
+ this.map = mapWritable || map;
796
+ this.afterWrite = afterWrite.bind(this);
797
+ this.afterUpdateNextTick = updateWriteNT.bind(this);
798
+ }
799
+ get ending() {
800
+ return (this.stream._duplexState & WRITE_FINISHING) !== 0;
801
+ }
802
+ get ended() {
803
+ return (this.stream._duplexState & WRITE_DONE) !== 0;
804
+ }
805
+ push(data) {
806
+ if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false;
807
+ if (this.map !== null) data = this.map(data);
808
+ this.buffered += this.byteLength(data);
809
+ this.queue.push(data);
810
+ if (this.buffered < this.highWaterMark) {
811
+ this.stream._duplexState |= WRITE_QUEUED;
812
+ return true;
813
+ }
814
+ this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
815
+ return false;
816
+ }
817
+ shift() {
818
+ const data = this.queue.shift();
819
+ this.buffered -= this.byteLength(data);
820
+ if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
821
+ return data;
822
+ }
823
+ end(data) {
824
+ if (typeof data === "function") {
825
+ this.stream.once("finish", data);
826
+ } else if (data !== void 0 && data !== null) {
827
+ this.push(data);
828
+ }
829
+ this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
830
+ }
831
+ autoBatch(data, cb) {
832
+ const buffer = [];
833
+ const stream = this.stream;
834
+ buffer.push(data);
835
+ while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
836
+ buffer.push(stream._writableState.shift());
837
+ }
838
+ if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null);
839
+ stream._writev(buffer, cb);
840
+ }
841
+ update() {
842
+ const stream = this.stream;
843
+ stream._duplexState |= WRITE_UPDATING;
844
+ do {
845
+ while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
846
+ const data = this.shift();
847
+ stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
848
+ stream._write(data, this.afterWrite);
849
+ }
850
+ if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
851
+ } while (this.continueUpdate() === true);
852
+ stream._duplexState &= WRITE_NOT_UPDATING;
853
+ }
854
+ updateNonPrimary() {
855
+ const stream = this.stream;
856
+ if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
857
+ stream._duplexState = stream._duplexState | WRITE_ACTIVE;
858
+ stream._final(afterFinal.bind(this));
859
+ return;
860
+ }
861
+ if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
862
+ if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
863
+ stream._duplexState |= ACTIVE;
864
+ stream._destroy(afterDestroy.bind(this));
865
+ }
866
+ return;
867
+ }
868
+ if ((stream._duplexState & IS_OPENING) === OPENING) {
869
+ stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
870
+ stream._open(afterOpen.bind(this));
871
+ }
872
+ }
873
+ continueUpdate() {
874
+ if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false;
875
+ this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
876
+ return true;
877
+ }
878
+ updateCallback() {
879
+ if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
880
+ this.update();
881
+ } else {
882
+ this.updateNextTick();
883
+ }
884
+ }
885
+ updateNextTick() {
886
+ if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return;
887
+ this.stream._duplexState |= WRITE_NEXT_TICK;
888
+ if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick);
889
+ }
890
+ };
891
+ var ReadableState = class {
892
+ constructor(stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) {
893
+ this.stream = stream;
894
+ this.queue = new FIFO();
895
+ this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark;
896
+ this.buffered = 0;
897
+ this.readAhead = highWaterMark > 0;
898
+ this.error = null;
899
+ this.pipeline = null;
900
+ this.byteLength = byteLengthReadable || byteLength || defaultByteLength;
901
+ this.map = mapReadable || map;
902
+ this.pipeTo = null;
903
+ this.afterRead = afterRead.bind(this);
904
+ this.afterUpdateNextTick = updateReadNT.bind(this);
905
+ }
906
+ get ending() {
907
+ return (this.stream._duplexState & READ_ENDING) !== 0;
908
+ }
909
+ get ended() {
910
+ return (this.stream._duplexState & READ_DONE) !== 0;
911
+ }
912
+ pipe(pipeTo, cb) {
913
+ if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT("Can only pipe to one destination");
914
+ if (typeof cb !== "function") cb = null;
915
+ this.stream._duplexState |= READ_PIPE_DRAINED;
916
+ this.pipeTo = pipeTo;
917
+ this.pipeline = new Pipeline(this.stream, pipeTo, cb);
918
+ if (cb) this.stream.on("error", noop);
919
+ if (isStreamx(pipeTo)) {
920
+ pipeTo._writableState.pipeline = this.pipeline;
921
+ if (cb) pipeTo.on("error", noop);
922
+ pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
923
+ } else {
924
+ const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
925
+ const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
926
+ pipeTo.on("error", onerror);
927
+ pipeTo.on("close", onclose);
928
+ pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
929
+ }
930
+ pipeTo.on("drain", afterDrain.bind(this));
931
+ this.stream.emit("piping", pipeTo);
932
+ pipeTo.emit("pipe", this.stream);
933
+ }
934
+ push(data) {
935
+ const stream = this.stream;
936
+ if (data === null) {
937
+ this.highWaterMark = 0;
938
+ stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
939
+ return false;
940
+ }
941
+ if (this.map !== null) {
942
+ data = this.map(data);
943
+ if (data === null) {
944
+ stream._duplexState &= READ_PUSHED;
945
+ return this.buffered < this.highWaterMark;
946
+ }
947
+ }
948
+ this.buffered += this.byteLength(data);
949
+ this.queue.push(data);
950
+ stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
951
+ return this.buffered < this.highWaterMark;
952
+ }
953
+ shift() {
954
+ const data = this.queue.shift();
955
+ this.buffered -= this.byteLength(data);
956
+ if (this.buffered === 0) {
957
+ this.stream._duplexState &= READ_NOT_QUEUED;
958
+ }
959
+ return data;
960
+ }
961
+ unshift(data) {
962
+ const pending = [this.map !== null ? this.map(data) : data];
963
+ while (this.buffered > 0) pending.push(this.shift());
964
+ for (let i = 0; i < pending.length - 1; i++) {
965
+ const data2 = pending[i];
966
+ this.buffered += this.byteLength(data2);
967
+ this.queue.push(data2);
968
+ }
969
+ this.push(pending[pending.length - 1]);
970
+ }
971
+ read() {
972
+ const stream = this.stream;
973
+ if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
974
+ const data = this.shift();
975
+ if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
976
+ stream._duplexState &= READ_PIPE_NOT_DRAINED;
977
+ }
978
+ if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
979
+ stream.emit("data", data);
980
+ }
981
+ return data;
982
+ }
983
+ if (this.readAhead === false) {
984
+ stream._duplexState |= READ_READ_AHEAD;
985
+ this.updateNextTick();
986
+ }
987
+ return null;
988
+ }
989
+ drain() {
990
+ const stream = this.stream;
991
+ while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
992
+ const data = this.shift();
993
+ if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
994
+ stream._duplexState &= READ_PIPE_NOT_DRAINED;
995
+ }
996
+ if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
997
+ stream.emit("data", data);
998
+ }
999
+ }
1000
+ }
1001
+ update() {
1002
+ const stream = this.stream;
1003
+ stream._duplexState |= READ_UPDATING;
1004
+ do {
1005
+ this.drain();
1006
+ while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
1007
+ stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
1008
+ stream._read(this.afterRead);
1009
+ this.drain();
1010
+ }
1011
+ if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
1012
+ stream._duplexState |= READ_EMITTED_READABLE;
1013
+ stream.emit("readable");
1014
+ }
1015
+ if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
1016
+ this.updateNonPrimary();
1017
+ }
1018
+ } while (this.continueUpdate() === true);
1019
+ stream._duplexState &= READ_NOT_UPDATING;
1020
+ }
1021
+ updateNonPrimary() {
1022
+ const stream = this.stream;
1023
+ if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
1024
+ stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
1025
+ stream.emit("end");
1026
+ if ((stream._duplexState & AUTO_DESTROY) === DONE) {
1027
+ stream._duplexState |= DESTROYING;
1028
+ }
1029
+ if (this.pipeTo !== null) {
1030
+ this.pipeTo.end();
1031
+ }
1032
+ }
1033
+ if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
1034
+ if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
1035
+ stream._duplexState |= ACTIVE;
1036
+ stream._destroy(afterDestroy.bind(this));
1037
+ }
1038
+ return;
1039
+ }
1040
+ if ((stream._duplexState & IS_OPENING) === OPENING) {
1041
+ stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
1042
+ stream._open(afterOpen.bind(this));
1043
+ }
1044
+ }
1045
+ continueUpdate() {
1046
+ if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false;
1047
+ this.stream._duplexState &= READ_NOT_NEXT_TICK;
1048
+ return true;
1049
+ }
1050
+ updateCallback() {
1051
+ if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
1052
+ this.update();
1053
+ } else {
1054
+ this.updateNextTick();
1055
+ }
1056
+ }
1057
+ updateNextTickIfOpen() {
1058
+ if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return;
1059
+ this.stream._duplexState |= READ_NEXT_TICK;
1060
+ if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
1061
+ }
1062
+ updateNextTick() {
1063
+ if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return;
1064
+ this.stream._duplexState |= READ_NEXT_TICK;
1065
+ if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
1066
+ }
1067
+ };
1068
+ var TransformState = class {
1069
+ constructor(stream) {
1070
+ this.data = null;
1071
+ this.afterTransform = afterTransform.bind(stream);
1072
+ this.afterFinal = null;
1073
+ }
1074
+ };
1075
+ var Pipeline = class {
1076
+ constructor(src, dst, cb) {
1077
+ this.from = src;
1078
+ this.to = dst;
1079
+ this.afterPipe = cb;
1080
+ this.error = null;
1081
+ this.pipeToFinished = false;
1082
+ }
1083
+ finished() {
1084
+ this.pipeToFinished = true;
1085
+ }
1086
+ done(stream, err) {
1087
+ if (err) this.error = err;
1088
+ if (stream === this.to) {
1089
+ this.to = null;
1090
+ if (this.from !== null) {
1091
+ if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
1092
+ this.from.destroy(this.error || StreamError.PREMATURE_CLOSE("Writable stream closed"));
1093
+ }
1094
+ return;
1095
+ }
1096
+ }
1097
+ if (stream === this.from) {
1098
+ this.from = null;
1099
+ if (this.to !== null) {
1100
+ if ((stream._duplexState & READ_DONE) === 0) {
1101
+ this.to.destroy(this.error || StreamError.PREMATURE_CLOSE("Readable stream closed"));
1102
+ }
1103
+ return;
1104
+ }
1105
+ }
1106
+ if (this.afterPipe !== null) this.afterPipe(this.error);
1107
+ this.to = this.from = this.afterPipe = null;
1108
+ }
1109
+ };
1110
+ function afterDrain() {
1111
+ this.stream._duplexState |= READ_PIPE_DRAINED;
1112
+ this.updateCallback();
1113
+ }
1114
+ function afterFinal(err) {
1115
+ const stream = this.stream;
1116
+ if (err) stream.destroy(err);
1117
+ if ((stream._duplexState & DESTROY_STATUS) === 0) {
1118
+ stream._duplexState |= WRITE_DONE;
1119
+ stream.emit("finish");
1120
+ }
1121
+ if ((stream._duplexState & AUTO_DESTROY) === DONE) {
1122
+ stream._duplexState |= DESTROYING;
1123
+ }
1124
+ stream._duplexState &= WRITE_NOT_FINISHING;
1125
+ if ((stream._duplexState & WRITE_UPDATING) === 0) {
1126
+ this.update();
1127
+ } else {
1128
+ this.updateNextTick();
1129
+ }
1130
+ }
1131
+ function afterDestroy(err) {
1132
+ const stream = this.stream;
1133
+ if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error;
1134
+ if (err) stream.emit("error", err);
1135
+ stream._duplexState |= DESTROYED;
1136
+ stream.emit("close");
1137
+ const rs = stream._readableState;
1138
+ const ws = stream._writableState;
1139
+ if (rs !== null && rs.pipeline !== null) {
1140
+ rs.pipeline.done(stream, err);
1141
+ }
1142
+ if (ws !== null) {
1143
+ while (ws.drains !== null && ws.drains.length > 0) {
1144
+ ws.drains.shift().resolve(false);
1145
+ }
1146
+ if (ws.pipeline !== null) {
1147
+ ws.pipeline.done(stream, err);
1148
+ }
1149
+ }
1150
+ }
1151
+ function afterWrite(err) {
1152
+ const stream = this.stream;
1153
+ if (err) stream.destroy(err);
1154
+ stream._duplexState &= WRITE_NOT_ACTIVE;
1155
+ if (this.drains !== null) tickDrains(this.drains);
1156
+ if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
1157
+ stream._duplexState &= WRITE_DRAINED;
1158
+ if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
1159
+ stream.emit("drain");
1160
+ }
1161
+ }
1162
+ this.updateCallback();
1163
+ }
1164
+ function afterRead(err) {
1165
+ if (err) this.stream.destroy(err);
1166
+ this.stream._duplexState &= READ_NOT_ACTIVE;
1167
+ if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
1168
+ this.stream._duplexState &= READ_NO_READ_AHEAD;
1169
+ }
1170
+ this.updateCallback();
1171
+ }
1172
+ function updateReadNT() {
1173
+ if ((this.stream._duplexState & READ_UPDATING) === 0) {
1174
+ this.stream._duplexState &= READ_NOT_NEXT_TICK;
1175
+ this.update();
1176
+ }
1177
+ }
1178
+ function updateWriteNT() {
1179
+ if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
1180
+ this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
1181
+ this.update();
1182
+ }
1183
+ }
1184
+ function tickDrains(drains) {
1185
+ for (let i = 0; i < drains.length; i++) {
1186
+ if (--drains[i].writes === 0) {
1187
+ drains.shift().resolve(true);
1188
+ i--;
1189
+ }
1190
+ }
1191
+ }
1192
+ function afterOpen(err) {
1193
+ const stream = this.stream;
1194
+ if (err) stream.destroy(err);
1195
+ if ((stream._duplexState & DESTROYING) === 0) {
1196
+ if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
1197
+ stream._duplexState |= READ_PRIMARY;
1198
+ }
1199
+ if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
1200
+ stream._duplexState |= WRITE_PRIMARY;
1201
+ }
1202
+ stream.emit("open");
1203
+ }
1204
+ stream._duplexState &= NOT_ACTIVE;
1205
+ if (stream._writableState !== null) {
1206
+ stream._writableState.updateCallback();
1207
+ }
1208
+ if (stream._readableState !== null) {
1209
+ stream._readableState.updateCallback();
1210
+ }
1211
+ }
1212
+ function afterTransform(err, data) {
1213
+ if (data !== void 0 && data !== null) this.push(data);
1214
+ this._writableState.afterWrite(err);
1215
+ }
1216
+ function newListener(name) {
1217
+ if (this._readableState !== null) {
1218
+ if (name === "data") {
1219
+ this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD;
1220
+ this._readableState.updateNextTick();
1221
+ }
1222
+ if (name === "readable") {
1223
+ this._duplexState |= READ_EMIT_READABLE;
1224
+ this._readableState.updateNextTick();
1225
+ }
1226
+ }
1227
+ if (this._writableState !== null) {
1228
+ if (name === "drain") {
1229
+ this._duplexState |= WRITE_EMIT_DRAIN;
1230
+ this._writableState.updateNextTick();
1231
+ }
1232
+ }
1233
+ }
1234
+ var Stream = class extends EventEmitter {
1235
+ constructor(opts) {
1236
+ super();
1237
+ this._duplexState = 0;
1238
+ this._readableState = null;
1239
+ this._writableState = null;
1240
+ if (opts) {
1241
+ if (opts.open) this._open = opts.open;
1242
+ if (opts.destroy) this._destroy = opts.destroy;
1243
+ if (opts.predestroy) this._predestroy = opts.predestroy;
1244
+ if (opts.signal) opts.signal.addEventListener("abort", abort.bind(this));
1245
+ }
1246
+ this.on("newListener", newListener);
1247
+ }
1248
+ _open(cb) {
1249
+ cb(null);
1250
+ }
1251
+ _destroy(cb) {
1252
+ cb(null);
1253
+ }
1254
+ _predestroy() {
1255
+ }
1256
+ get readable() {
1257
+ return this._readableState !== null ? true : void 0;
1258
+ }
1259
+ get writable() {
1260
+ return this._writableState !== null ? true : void 0;
1261
+ }
1262
+ get destroyed() {
1263
+ return (this._duplexState & DESTROYED) !== 0;
1264
+ }
1265
+ get destroying() {
1266
+ return (this._duplexState & DESTROY_STATUS) !== 0;
1267
+ }
1268
+ destroy(err) {
1269
+ if ((this._duplexState & DESTROY_STATUS) === 0) {
1270
+ if (!err) err = StreamError.STREAM_DESTROYED();
1271
+ this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY;
1272
+ if (this._readableState !== null) {
1273
+ this._readableState.highWaterMark = 0;
1274
+ this._readableState.error = err;
1275
+ }
1276
+ if (this._writableState !== null) {
1277
+ this._writableState.highWaterMark = 0;
1278
+ this._writableState.error = err;
1279
+ }
1280
+ this._duplexState |= PREDESTROYING;
1281
+ this._predestroy();
1282
+ this._duplexState &= NOT_PREDESTROYING;
1283
+ if (this._readableState !== null) {
1284
+ this._readableState.updateNextTick();
1285
+ }
1286
+ if (this._writableState !== null) {
1287
+ this._writableState.updateNextTick();
1288
+ }
1289
+ }
1290
+ }
1291
+ };
1292
+ var Readable2 = class _Readable extends Stream {
1293
+ constructor(opts) {
1294
+ super(opts);
1295
+ this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD;
1296
+ this._readableState = new ReadableState(this, opts);
1297
+ if (opts) {
1298
+ if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD;
1299
+ if (opts.read) this._read = opts.read;
1300
+ if (opts.eagerOpen) this._readableState.updateNextTick();
1301
+ if (opts.encoding) this.setEncoding(opts.encoding);
1302
+ }
1303
+ }
1304
+ static deferred(fn, opts) {
1305
+ const out = new PassThrough(opts);
1306
+ fn().then((src) => {
1307
+ if (src === null) return out.end();
1308
+ if (out.destroying) return;
1309
+ pipeline2(src, out, noop);
1310
+ }).catch((err) => out.destroy(err));
1311
+ return out;
1312
+ }
1313
+ setEncoding(encoding) {
1314
+ const dec = new TextDecoder2(encoding);
1315
+ const map = this._readableState.map || echo;
1316
+ this._readableState.map = mapOrSkip;
1317
+ return this;
1318
+ function mapOrSkip(data) {
1319
+ const next = dec.push(data);
1320
+ return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next);
1321
+ }
1322
+ }
1323
+ _read(cb) {
1324
+ cb(null);
1325
+ }
1326
+ pipe(dest, cb) {
1327
+ this._readableState.updateNextTick();
1328
+ this._readableState.pipe(dest, cb);
1329
+ return dest;
1330
+ }
1331
+ read() {
1332
+ this._readableState.updateNextTick();
1333
+ return this._readableState.read();
1334
+ }
1335
+ push(data) {
1336
+ this._readableState.updateNextTickIfOpen();
1337
+ return this._readableState.push(data);
1338
+ }
1339
+ unshift(data) {
1340
+ this._readableState.updateNextTickIfOpen();
1341
+ return this._readableState.unshift(data);
1342
+ }
1343
+ resume() {
1344
+ this._duplexState |= READ_RESUMED_READ_AHEAD;
1345
+ this._readableState.updateNextTick();
1346
+ return this;
1347
+ }
1348
+ pause() {
1349
+ this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
1350
+ return this;
1351
+ }
1352
+ static _fromAsyncIterator(ite, opts) {
1353
+ let destroy;
1354
+ const rs = new _Readable({
1355
+ ...opts,
1356
+ read(cb) {
1357
+ ite.next().then(push).then(cb.bind(null, null)).catch(cb);
1358
+ },
1359
+ predestroy() {
1360
+ destroy = ite.return();
1361
+ },
1362
+ destroy(cb) {
1363
+ if (!destroy) return cb(null);
1364
+ destroy.then(cb.bind(null, null)).catch(cb);
1365
+ }
1366
+ });
1367
+ return rs;
1368
+ function push(data) {
1369
+ if (data.done) rs.push(null);
1370
+ else rs.push(data.value);
1371
+ }
1372
+ }
1373
+ static from(data, opts) {
1374
+ if (isReadStreamx(data)) return data;
1375
+ if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts);
1376
+ if (!Array.isArray(data)) data = data === void 0 ? [] : [data];
1377
+ let i = 0;
1378
+ return new _Readable({
1379
+ ...opts,
1380
+ read(cb) {
1381
+ this.push(i === data.length ? null : data[i++]);
1382
+ cb(null);
1383
+ }
1384
+ });
1385
+ }
1386
+ static isBackpressured(rs) {
1387
+ return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
1388
+ }
1389
+ static isPaused(rs) {
1390
+ return (rs._duplexState & READ_RESUMED) === 0;
1391
+ }
1392
+ [asyncIterator]() {
1393
+ const stream = this;
1394
+ let error = null;
1395
+ let promiseResolve = null;
1396
+ let promiseReject = null;
1397
+ this.on("error", (err) => {
1398
+ error = err;
1399
+ });
1400
+ this.on("readable", onreadable);
1401
+ this.on("close", onclose);
1402
+ return {
1403
+ [asyncIterator]() {
1404
+ return this;
1405
+ },
1406
+ next() {
1407
+ return new Promise(function(resolve2, reject) {
1408
+ promiseResolve = resolve2;
1409
+ promiseReject = reject;
1410
+ const data = stream.read();
1411
+ if (data !== null) ondata(data);
1412
+ else if ((stream._duplexState & DESTROYED) !== 0) ondata(null);
1413
+ });
1414
+ },
1415
+ return() {
1416
+ return destroy(null);
1417
+ },
1418
+ throw(err) {
1419
+ return destroy(err);
1420
+ }
1421
+ };
1422
+ function onreadable() {
1423
+ if (promiseResolve !== null) ondata(stream.read());
1424
+ }
1425
+ function onclose() {
1426
+ if (promiseResolve !== null) ondata(null);
1427
+ }
1428
+ function ondata(data) {
1429
+ if (promiseReject === null) return;
1430
+ if (error) {
1431
+ promiseReject(error);
1432
+ } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
1433
+ promiseReject(StreamError.STREAM_DESTROYED());
1434
+ } else {
1435
+ promiseResolve({ value: data, done: data === null });
1436
+ }
1437
+ promiseReject = promiseResolve = null;
1438
+ }
1439
+ function destroy(err) {
1440
+ stream.destroy(err);
1441
+ return new Promise((resolve2, reject) => {
1442
+ if (stream._duplexState & DESTROYED) return resolve2({ value: void 0, done: true });
1443
+ stream.once("close", function() {
1444
+ if (err) reject(err);
1445
+ else resolve2({ value: void 0, done: true });
1446
+ });
1447
+ });
1448
+ }
1449
+ }
1450
+ };
1451
+ var Writable = class extends Stream {
1452
+ constructor(opts) {
1453
+ super(opts);
1454
+ this._duplexState |= OPENING | READ_DONE;
1455
+ this._writableState = new WritableState(this, opts);
1456
+ if (opts) {
1457
+ if (opts.writev) this._writev = opts.writev;
1458
+ if (opts.write) this._write = opts.write;
1459
+ if (opts.final) this._final = opts.final;
1460
+ if (opts.eagerOpen) this._writableState.updateNextTick();
1461
+ }
1462
+ }
1463
+ cork() {
1464
+ this._duplexState |= WRITE_CORKED;
1465
+ }
1466
+ uncork() {
1467
+ this._duplexState &= WRITE_NOT_CORKED;
1468
+ this._writableState.updateNextTick();
1469
+ }
1470
+ _writev(batch, cb) {
1471
+ cb(null);
1472
+ }
1473
+ _write(data, cb) {
1474
+ this._writableState.autoBatch(data, cb);
1475
+ }
1476
+ _final(cb) {
1477
+ cb(null);
1478
+ }
1479
+ static isBackpressured(ws) {
1480
+ return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
1481
+ }
1482
+ static drained(ws) {
1483
+ if (ws.destroyed) return Promise.resolve(false);
1484
+ const state = ws._writableState;
1485
+ const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length;
1486
+ const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
1487
+ if (writes === 0) return Promise.resolve(true);
1488
+ if (state.drains === null) state.drains = [];
1489
+ return new Promise((resolve2) => {
1490
+ state.drains.push({ writes, resolve: resolve2 });
1491
+ });
1492
+ }
1493
+ write(data) {
1494
+ this._writableState.updateNextTick();
1495
+ return this._writableState.push(data);
1496
+ }
1497
+ end(data) {
1498
+ this._writableState.updateNextTick();
1499
+ this._writableState.end(data);
1500
+ return this;
1501
+ }
1502
+ };
1503
+ var Duplex = class extends Readable2 {
1504
+ // and Writable
1505
+ constructor(opts) {
1506
+ super(opts);
1507
+ this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
1508
+ this._writableState = new WritableState(this, opts);
1509
+ if (opts) {
1510
+ if (opts.writev) this._writev = opts.writev;
1511
+ if (opts.write) this._write = opts.write;
1512
+ if (opts.final) this._final = opts.final;
1513
+ }
1514
+ }
1515
+ cork() {
1516
+ this._duplexState |= WRITE_CORKED;
1517
+ }
1518
+ uncork() {
1519
+ this._duplexState &= WRITE_NOT_CORKED;
1520
+ this._writableState.updateNextTick();
1521
+ }
1522
+ _writev(batch, cb) {
1523
+ cb(null);
1524
+ }
1525
+ _write(data, cb) {
1526
+ this._writableState.autoBatch(data, cb);
1527
+ }
1528
+ _final(cb) {
1529
+ cb(null);
1530
+ }
1531
+ write(data) {
1532
+ this._writableState.updateNextTick();
1533
+ return this._writableState.push(data);
1534
+ }
1535
+ end(data) {
1536
+ this._writableState.updateNextTick();
1537
+ this._writableState.end(data);
1538
+ return this;
1539
+ }
1540
+ };
1541
+ var Transform = class extends Duplex {
1542
+ constructor(opts) {
1543
+ super(opts);
1544
+ this._transformState = new TransformState(this);
1545
+ if (opts) {
1546
+ if (opts.transform) this._transform = opts.transform;
1547
+ if (opts.flush) this._flush = opts.flush;
1548
+ }
1549
+ }
1550
+ _write(data, cb) {
1551
+ if (this._readableState.buffered >= this._readableState.highWaterMark) {
1552
+ this._transformState.data = data;
1553
+ } else {
1554
+ this._transform(data, this._transformState.afterTransform);
1555
+ }
1556
+ }
1557
+ _read(cb) {
1558
+ if (this._transformState.data !== null) {
1559
+ const data = this._transformState.data;
1560
+ this._transformState.data = null;
1561
+ cb(null);
1562
+ this._transform(data, this._transformState.afterTransform);
1563
+ } else {
1564
+ cb(null);
1565
+ }
1566
+ }
1567
+ destroy(err) {
1568
+ super.destroy(err);
1569
+ if (this._transformState.data !== null) {
1570
+ this._transformState.data = null;
1571
+ this._transformState.afterTransform();
1572
+ }
1573
+ }
1574
+ _transform(data, cb) {
1575
+ cb(null, data);
1576
+ }
1577
+ _flush(cb) {
1578
+ cb(null);
1579
+ }
1580
+ _final(cb) {
1581
+ this._transformState.afterFinal = cb;
1582
+ this._flush(transformAfterFlush.bind(this));
1583
+ }
1584
+ };
1585
+ var PassThrough = class extends Transform {
1586
+ };
1587
+ function transformAfterFlush(err, data) {
1588
+ const cb = this._transformState.afterFinal;
1589
+ if (err) return cb(err);
1590
+ if (data !== null && data !== void 0) this.push(data);
1591
+ this.push(null);
1592
+ cb(null);
1593
+ }
1594
+ function pipelinePromise(...streams) {
1595
+ return new Promise((resolve2, reject) => {
1596
+ return pipeline2(...streams, (err) => {
1597
+ if (err) return reject(err);
1598
+ resolve2();
1599
+ });
1600
+ });
1601
+ }
1602
+ function pipeline2(stream, ...streams) {
1603
+ const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
1604
+ const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
1605
+ if (all.length < 2) throw StreamError.BAD_ARGUMENT("Pipeline requires at least 2 streams");
1606
+ let src = all[0];
1607
+ let dest = null;
1608
+ let error = null;
1609
+ for (let i = 1; i < all.length; i++) {
1610
+ dest = all[i];
1611
+ if (isStreamx(src)) {
1612
+ src.pipe(dest, onerror);
1613
+ } else {
1614
+ errorHandle(src, true, i > 1, onerror);
1615
+ src.pipe(dest);
1616
+ }
1617
+ src = dest;
1618
+ }
1619
+ if (done) {
1620
+ let fin = false;
1621
+ const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy);
1622
+ dest.on("error", (err) => {
1623
+ if (error === null) error = err;
1624
+ });
1625
+ dest.on("finish", () => {
1626
+ fin = true;
1627
+ if (!autoDestroy) done(error);
1628
+ });
1629
+ if (autoDestroy) {
1630
+ dest.on("close", () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())));
1631
+ }
1632
+ }
1633
+ return dest;
1634
+ function errorHandle(s, rd, wr, onerror2) {
1635
+ s.on("error", onerror2);
1636
+ s.on("close", onclose);
1637
+ function onclose() {
1638
+ if (s._readableState && !s._readableState.ended) {
1639
+ return onerror2(StreamError.PREMATURE_CLOSE());
1640
+ }
1641
+ if (wr && s._writableState && !s._writableState.ended) {
1642
+ return onerror2(StreamError.PREMATURE_CLOSE());
1643
+ }
1644
+ }
1645
+ }
1646
+ function onerror(err) {
1647
+ if (!err || error) return;
1648
+ error = err;
1649
+ for (const s of all) {
1650
+ s.destroy(err);
1651
+ }
1652
+ }
1653
+ }
1654
+ function echo(s) {
1655
+ return s;
1656
+ }
1657
+ function isStream(stream) {
1658
+ return !!stream._readableState || !!stream._writableState;
1659
+ }
1660
+ function isStreamx(stream) {
1661
+ return typeof stream._duplexState === "number" && isStream(stream);
1662
+ }
1663
+ function isEnding(stream) {
1664
+ return !!stream._readableState && stream._readableState.ending;
1665
+ }
1666
+ function isEnded(stream) {
1667
+ return !!stream._readableState && stream._readableState.ended;
1668
+ }
1669
+ function isFinishing(stream) {
1670
+ return !!stream._writableState && stream._writableState.ending;
1671
+ }
1672
+ function isFinished(stream) {
1673
+ return !!stream._writableState && stream._writableState.ended;
1674
+ }
1675
+ function getStreamError(stream, opts = {}) {
1676
+ const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error;
1677
+ return !opts.all && StreamError.isStreamDestroyed(err) ? null : err;
1678
+ }
1679
+ function isReadStreamx(stream) {
1680
+ return isStreamx(stream) && stream.readable;
1681
+ }
1682
+ function isDisturbed(stream) {
1683
+ return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & DESTROYING) === DESTROYING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0;
1684
+ }
1685
+ function isTypedArray(data) {
1686
+ return typeof data === "object" && data !== null && typeof data.byteLength === "number";
1687
+ }
1688
+ function defaultByteLength(data) {
1689
+ return isTypedArray(data) ? data.byteLength : 1024;
1690
+ }
1691
+ function noop() {
1692
+ }
1693
+ function abort() {
1694
+ this.destroy(StreamError.ABORTED());
1695
+ }
1696
+ function isWritev(s) {
1697
+ return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
1698
+ }
1699
+ module.exports = {
1700
+ pipeline: pipeline2,
1701
+ pipelinePromise,
1702
+ isStream,
1703
+ isStreamx,
1704
+ isEnding,
1705
+ isEnded,
1706
+ isFinishing,
1707
+ isFinished,
1708
+ isDisturbed,
1709
+ getStreamError,
1710
+ Stream,
1711
+ Writable,
1712
+ Readable: Readable2,
1713
+ Duplex,
1714
+ Transform,
1715
+ // Export PassThrough for compatibility with Node.js core's stream module
1716
+ PassThrough
1717
+ };
1718
+ }
1719
+ });
1720
+
1721
+ // ../../node_modules/@sparticuz/chromium/node_modules/tar-stream/headers.js
1722
+ var require_headers = __commonJS({
1723
+ "../../node_modules/@sparticuz/chromium/node_modules/tar-stream/headers.js"(exports) {
1724
+ var b4a = require_b4a();
1725
+ var ZEROS = "0000000000000000000";
1726
+ var SEVENS = "7777777777777777777";
1727
+ var ZERO_OFFSET = "0".charCodeAt(0);
1728
+ var USTAR_MAGIC = b4a.from([117, 115, 116, 97, 114, 0]);
1729
+ var USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]);
1730
+ var GNU_MAGIC = b4a.from([117, 115, 116, 97, 114, 32]);
1731
+ var GNU_VER = b4a.from([32, 0]);
1732
+ var MASK = 4095;
1733
+ var MAGIC_OFFSET = 257;
1734
+ var VERSION_OFFSET = 263;
1735
+ exports.decodeLongPath = function decodeLongPath(buf, encoding) {
1736
+ return decodeStr(buf, 0, buf.length, encoding);
1737
+ };
1738
+ exports.encodePax = function encodePax(opts) {
1739
+ let result = "";
1740
+ if (opts.name) result += addLength(" path=" + opts.name + "\n");
1741
+ if (opts.linkname) result += addLength(" linkpath=" + opts.linkname + "\n");
1742
+ const pax = opts.pax;
1743
+ if (pax) {
1744
+ for (const key in pax) {
1745
+ result += addLength(" " + key + "=" + pax[key] + "\n");
1746
+ }
1747
+ }
1748
+ return b4a.from(result);
1749
+ };
1750
+ exports.decodePax = function decodePax(buf) {
1751
+ const result = {};
1752
+ while (buf.length) {
1753
+ let i = 0;
1754
+ while (i < buf.length && buf[i] !== 32) i++;
1755
+ const len = parseInt(b4a.toString(buf.subarray(0, i)), 10);
1756
+ if (!len) return result;
1757
+ const b = b4a.toString(buf.subarray(i + 1, len - 1));
1758
+ const keyIndex = b.indexOf("=");
1759
+ if (keyIndex === -1) return result;
1760
+ result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1);
1761
+ buf = buf.subarray(len);
1762
+ }
1763
+ return result;
1764
+ };
1765
+ exports.encode = function encode(opts) {
1766
+ const buf = b4a.alloc(512);
1767
+ let name = opts.name;
1768
+ let prefix = "";
1769
+ if (opts.typeflag === 5 && name[name.length - 1] !== "/") name += "/";
1770
+ if (b4a.byteLength(name) !== name.length) return null;
1771
+ while (b4a.byteLength(name) > 100) {
1772
+ const i = name.indexOf("/");
1773
+ if (i === -1) return null;
1774
+ prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i);
1775
+ name = name.slice(i + 1);
1776
+ }
1777
+ if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null;
1778
+ if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null;
1779
+ b4a.write(buf, name);
1780
+ b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100);
1781
+ b4a.write(buf, encodeOct(opts.uid, 6), 108);
1782
+ b4a.write(buf, encodeOct(opts.gid, 6), 116);
1783
+ encodeSize(opts.size, buf, 124);
1784
+ b4a.write(buf, encodeOct(opts.mtime.getTime() / 1e3 | 0, 11), 136);
1785
+ buf[156] = ZERO_OFFSET + toTypeflag(opts.type);
1786
+ if (opts.linkname) b4a.write(buf, opts.linkname, 157);
1787
+ b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET);
1788
+ b4a.copy(USTAR_VER, buf, VERSION_OFFSET);
1789
+ if (opts.uname) b4a.write(buf, opts.uname, 265);
1790
+ if (opts.gname) b4a.write(buf, opts.gname, 297);
1791
+ b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329);
1792
+ b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337);
1793
+ if (prefix) b4a.write(buf, prefix, 345);
1794
+ b4a.write(buf, encodeOct(cksum(buf), 6), 148);
1795
+ return buf;
1796
+ };
1797
+ exports.decode = function decode(buf, filenameEncoding, allowUnknownFormat) {
1798
+ let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET;
1799
+ let name = decodeStr(buf, 0, 100, filenameEncoding);
1800
+ const mode = decodeOct(buf, 100, 8);
1801
+ const uid = decodeOct(buf, 108, 8);
1802
+ const gid = decodeOct(buf, 116, 8);
1803
+ const size = decodeOct(buf, 124, 12);
1804
+ const mtime = decodeOct(buf, 136, 12);
1805
+ const type = toType(typeflag);
1806
+ const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding);
1807
+ const uname = decodeStr(buf, 265, 32);
1808
+ const gname = decodeStr(buf, 297, 32);
1809
+ const devmajor = decodeOct(buf, 329, 8);
1810
+ const devminor = decodeOct(buf, 337, 8);
1811
+ const c = cksum(buf);
1812
+ if (c === 8 * 32) return null;
1813
+ if (c !== decodeOct(buf, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");
1814
+ if (isUSTAR(buf)) {
1815
+ if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name;
1816
+ } else if (isGNU(buf)) ; else {
1817
+ if (!allowUnknownFormat) {
1818
+ throw new Error("Invalid tar header: unknown format.");
1819
+ }
1820
+ }
1821
+ if (typeflag === 0 && name && name[name.length - 1] === "/") typeflag = 5;
1822
+ return {
1823
+ name,
1824
+ mode,
1825
+ uid,
1826
+ gid,
1827
+ size,
1828
+ mtime: new Date(1e3 * mtime),
1829
+ type,
1830
+ linkname,
1831
+ uname,
1832
+ gname,
1833
+ devmajor,
1834
+ devminor,
1835
+ pax: null
1836
+ };
1837
+ };
1838
+ function isUSTAR(buf) {
1839
+ return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6));
1840
+ }
1841
+ function isGNU(buf) {
1842
+ return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2));
1843
+ }
1844
+ function clamp(index, len, defaultValue) {
1845
+ if (typeof index !== "number") return defaultValue;
1846
+ index = ~~index;
1847
+ if (index >= len) return len;
1848
+ if (index >= 0) return index;
1849
+ index += len;
1850
+ if (index >= 0) return index;
1851
+ return 0;
1852
+ }
1853
+ function toType(flag) {
1854
+ switch (flag) {
1855
+ case 0:
1856
+ return "file";
1857
+ case 1:
1858
+ return "link";
1859
+ case 2:
1860
+ return "symlink";
1861
+ case 3:
1862
+ return "character-device";
1863
+ case 4:
1864
+ return "block-device";
1865
+ case 5:
1866
+ return "directory";
1867
+ case 6:
1868
+ return "fifo";
1869
+ case 7:
1870
+ return "contiguous-file";
1871
+ case 72:
1872
+ return "pax-header";
1873
+ case 55:
1874
+ return "pax-global-header";
1875
+ case 27:
1876
+ return "gnu-long-link-path";
1877
+ case 28:
1878
+ case 30:
1879
+ return "gnu-long-path";
1880
+ }
1881
+ return null;
1882
+ }
1883
+ function toTypeflag(flag) {
1884
+ switch (flag) {
1885
+ case "file":
1886
+ return 0;
1887
+ case "link":
1888
+ return 1;
1889
+ case "symlink":
1890
+ return 2;
1891
+ case "character-device":
1892
+ return 3;
1893
+ case "block-device":
1894
+ return 4;
1895
+ case "directory":
1896
+ return 5;
1897
+ case "fifo":
1898
+ return 6;
1899
+ case "contiguous-file":
1900
+ return 7;
1901
+ case "pax-header":
1902
+ return 72;
1903
+ }
1904
+ return 0;
1905
+ }
1906
+ function indexOf(block, num, offset, end) {
1907
+ for (; offset < end; offset++) {
1908
+ if (block[offset] === num) return offset;
1909
+ }
1910
+ return end;
1911
+ }
1912
+ function cksum(block) {
1913
+ let sum = 8 * 32;
1914
+ for (let i = 0; i < 148; i++) sum += block[i];
1915
+ for (let j = 156; j < 512; j++) sum += block[j];
1916
+ return sum;
1917
+ }
1918
+ function encodeOct(val, n) {
1919
+ val = val.toString(8);
1920
+ if (val.length > n) return SEVENS.slice(0, n) + " ";
1921
+ return ZEROS.slice(0, n - val.length) + val + " ";
1922
+ }
1923
+ function encodeSizeBin(num, buf, off) {
1924
+ buf[off] = 128;
1925
+ for (let i = 11; i > 0; i--) {
1926
+ buf[off + i] = num & 255;
1927
+ num = Math.floor(num / 256);
1928
+ }
1929
+ }
1930
+ function encodeSize(num, buf, off) {
1931
+ if (num.toString(8).length > 11) {
1932
+ encodeSizeBin(num, buf, off);
1933
+ } else {
1934
+ b4a.write(buf, encodeOct(num, 11), off);
1935
+ }
1936
+ }
1937
+ function parse256(buf) {
1938
+ let positive;
1939
+ if (buf[0] === 128) positive = true;
1940
+ else if (buf[0] === 255) positive = false;
1941
+ else return null;
1942
+ const tuple = [];
1943
+ let i;
1944
+ for (i = buf.length - 1; i > 0; i--) {
1945
+ const byte = buf[i];
1946
+ if (positive) tuple.push(byte);
1947
+ else tuple.push(255 - byte);
1948
+ }
1949
+ let sum = 0;
1950
+ const l = tuple.length;
1951
+ for (i = 0; i < l; i++) {
1952
+ sum += tuple[i] * Math.pow(256, i);
1953
+ }
1954
+ return positive ? sum : -1 * sum;
1955
+ }
1956
+ function decodeOct(val, offset, length) {
1957
+ val = val.subarray(offset, offset + length);
1958
+ offset = 0;
1959
+ if (val[offset] & 128) {
1960
+ return parse256(val);
1961
+ } else {
1962
+ while (offset < val.length && val[offset] === 32) offset++;
1963
+ const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length);
1964
+ while (offset < end && val[offset] === 0) offset++;
1965
+ if (end === offset) return 0;
1966
+ return parseInt(b4a.toString(val.subarray(offset, end)), 8);
1967
+ }
1968
+ }
1969
+ function decodeStr(val, offset, length, encoding) {
1970
+ return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding);
1971
+ }
1972
+ function addLength(str) {
1973
+ const len = b4a.byteLength(str);
1974
+ let digits = Math.floor(Math.log(len) / Math.log(10)) + 1;
1975
+ if (len + digits >= Math.pow(10, digits)) digits++;
1976
+ return len + digits + str;
1977
+ }
1978
+ }
1979
+ });
1980
+
1981
+ // ../../node_modules/@sparticuz/chromium/node_modules/tar-stream/extract.js
1982
+ var require_extract = __commonJS({
1983
+ "../../node_modules/@sparticuz/chromium/node_modules/tar-stream/extract.js"(exports, module) {
1984
+ var { Writable, Readable: Readable2, getStreamError } = require_streamx();
1985
+ var FIFO = require_fast_fifo();
1986
+ var b4a = require_b4a();
1987
+ var headers = require_headers();
1988
+ var EMPTY = b4a.alloc(0);
1989
+ var BufferList = class {
1990
+ constructor() {
1991
+ this.buffered = 0;
1992
+ this.shifted = 0;
1993
+ this.queue = new FIFO();
1994
+ this._offset = 0;
1995
+ }
1996
+ push(buffer) {
1997
+ this.buffered += buffer.byteLength;
1998
+ this.queue.push(buffer);
1999
+ }
2000
+ shiftFirst(size) {
2001
+ return this._buffered === 0 ? null : this._next(size);
2002
+ }
2003
+ shift(size) {
2004
+ if (size > this.buffered) return null;
2005
+ if (size === 0) return EMPTY;
2006
+ let chunk = this._next(size);
2007
+ if (size === chunk.byteLength) return chunk;
2008
+ const chunks = [chunk];
2009
+ while ((size -= chunk.byteLength) > 0) {
2010
+ chunk = this._next(size);
2011
+ chunks.push(chunk);
2012
+ }
2013
+ return b4a.concat(chunks);
2014
+ }
2015
+ _next(size) {
2016
+ const buf = this.queue.peek();
2017
+ const rem = buf.byteLength - this._offset;
2018
+ if (size >= rem) {
2019
+ const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf;
2020
+ this.queue.shift();
2021
+ this._offset = 0;
2022
+ this.buffered -= rem;
2023
+ this.shifted += rem;
2024
+ return sub;
2025
+ }
2026
+ this.buffered -= size;
2027
+ this.shifted += size;
2028
+ return buf.subarray(this._offset, this._offset += size);
2029
+ }
2030
+ };
2031
+ var Source = class extends Readable2 {
2032
+ constructor(self, header, offset) {
2033
+ super();
2034
+ this.header = header;
2035
+ this.offset = offset;
2036
+ this._parent = self;
2037
+ }
2038
+ _read(cb) {
2039
+ if (this.header.size === 0) {
2040
+ this.push(null);
2041
+ }
2042
+ if (this._parent._stream === this) {
2043
+ this._parent._update();
2044
+ }
2045
+ cb(null);
2046
+ }
2047
+ _predestroy() {
2048
+ this._parent.destroy(getStreamError(this));
2049
+ }
2050
+ _detach() {
2051
+ if (this._parent._stream === this) {
2052
+ this._parent._stream = null;
2053
+ this._parent._missing = overflow(this.header.size);
2054
+ this._parent._update();
2055
+ }
2056
+ }
2057
+ _destroy(cb) {
2058
+ this._detach();
2059
+ cb(null);
2060
+ }
2061
+ };
2062
+ var Extract = class extends Writable {
2063
+ constructor(opts) {
2064
+ super(opts);
2065
+ if (!opts) opts = {};
2066
+ this._buffer = new BufferList();
2067
+ this._offset = 0;
2068
+ this._header = null;
2069
+ this._stream = null;
2070
+ this._missing = 0;
2071
+ this._longHeader = false;
2072
+ this._callback = noop;
2073
+ this._locked = false;
2074
+ this._finished = false;
2075
+ this._pax = null;
2076
+ this._paxGlobal = null;
2077
+ this._gnuLongPath = null;
2078
+ this._gnuLongLinkPath = null;
2079
+ this._filenameEncoding = opts.filenameEncoding || "utf-8";
2080
+ this._allowUnknownFormat = !!opts.allowUnknownFormat;
2081
+ this._unlockBound = this._unlock.bind(this);
2082
+ }
2083
+ _unlock(err) {
2084
+ this._locked = false;
2085
+ if (err) {
2086
+ this.destroy(err);
2087
+ this._continueWrite(err);
2088
+ return;
2089
+ }
2090
+ this._update();
2091
+ }
2092
+ _consumeHeader() {
2093
+ if (this._locked) return false;
2094
+ this._offset = this._buffer.shifted;
2095
+ try {
2096
+ this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat);
2097
+ } catch (err) {
2098
+ this._continueWrite(err);
2099
+ return false;
2100
+ }
2101
+ if (!this._header) return true;
2102
+ switch (this._header.type) {
2103
+ case "gnu-long-path":
2104
+ case "gnu-long-link-path":
2105
+ case "pax-global-header":
2106
+ case "pax-header":
2107
+ this._longHeader = true;
2108
+ this._missing = this._header.size;
2109
+ return true;
2110
+ }
2111
+ this._locked = true;
2112
+ this._applyLongHeaders();
2113
+ if (this._header.size === 0 || this._header.type === "directory") {
2114
+ this.emit("entry", this._header, this._createStream(), this._unlockBound);
2115
+ return true;
2116
+ }
2117
+ this._stream = this._createStream();
2118
+ this._missing = this._header.size;
2119
+ this.emit("entry", this._header, this._stream, this._unlockBound);
2120
+ return true;
2121
+ }
2122
+ _applyLongHeaders() {
2123
+ if (this._gnuLongPath) {
2124
+ this._header.name = this._gnuLongPath;
2125
+ this._gnuLongPath = null;
2126
+ }
2127
+ if (this._gnuLongLinkPath) {
2128
+ this._header.linkname = this._gnuLongLinkPath;
2129
+ this._gnuLongLinkPath = null;
2130
+ }
2131
+ if (this._pax) {
2132
+ if (this._pax.path) this._header.name = this._pax.path;
2133
+ if (this._pax.linkpath) this._header.linkname = this._pax.linkpath;
2134
+ if (this._pax.size) this._header.size = parseInt(this._pax.size, 10);
2135
+ this._header.pax = this._pax;
2136
+ this._pax = null;
2137
+ }
2138
+ }
2139
+ _decodeLongHeader(buf) {
2140
+ switch (this._header.type) {
2141
+ case "gnu-long-path":
2142
+ this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding);
2143
+ break;
2144
+ case "gnu-long-link-path":
2145
+ this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding);
2146
+ break;
2147
+ case "pax-global-header":
2148
+ this._paxGlobal = headers.decodePax(buf);
2149
+ break;
2150
+ case "pax-header":
2151
+ this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf));
2152
+ break;
2153
+ }
2154
+ }
2155
+ _consumeLongHeader() {
2156
+ this._longHeader = false;
2157
+ this._missing = overflow(this._header.size);
2158
+ const buf = this._buffer.shift(this._header.size);
2159
+ try {
2160
+ this._decodeLongHeader(buf);
2161
+ } catch (err) {
2162
+ this._continueWrite(err);
2163
+ return false;
2164
+ }
2165
+ return true;
2166
+ }
2167
+ _consumeStream() {
2168
+ const buf = this._buffer.shiftFirst(this._missing);
2169
+ if (buf === null) return false;
2170
+ this._missing -= buf.byteLength;
2171
+ const drained = this._stream.push(buf);
2172
+ if (this._missing === 0) {
2173
+ this._stream.push(null);
2174
+ if (drained) this._stream._detach();
2175
+ return drained && this._locked === false;
2176
+ }
2177
+ return drained;
2178
+ }
2179
+ _createStream() {
2180
+ return new Source(this, this._header, this._offset);
2181
+ }
2182
+ _update() {
2183
+ while (this._buffer.buffered > 0 && !this.destroying) {
2184
+ if (this._missing > 0) {
2185
+ if (this._stream !== null) {
2186
+ if (this._consumeStream() === false) return;
2187
+ continue;
2188
+ }
2189
+ if (this._longHeader === true) {
2190
+ if (this._missing > this._buffer.buffered) break;
2191
+ if (this._consumeLongHeader() === false) return false;
2192
+ continue;
2193
+ }
2194
+ const ignore = this._buffer.shiftFirst(this._missing);
2195
+ if (ignore !== null) this._missing -= ignore.byteLength;
2196
+ continue;
2197
+ }
2198
+ if (this._buffer.buffered < 512) break;
2199
+ if (this._stream !== null || this._consumeHeader() === false) return;
2200
+ }
2201
+ this._continueWrite(null);
2202
+ }
2203
+ _continueWrite(err) {
2204
+ const cb = this._callback;
2205
+ this._callback = noop;
2206
+ cb(err);
2207
+ }
2208
+ _write(data, cb) {
2209
+ this._callback = cb;
2210
+ this._buffer.push(data);
2211
+ this._update();
2212
+ }
2213
+ _final(cb) {
2214
+ this._finished = this._missing === 0 && this._buffer.buffered === 0;
2215
+ cb(this._finished ? null : new Error("Unexpected end of data"));
2216
+ }
2217
+ _predestroy() {
2218
+ this._continueWrite(null);
2219
+ }
2220
+ _destroy(cb) {
2221
+ if (this._stream) this._stream.destroy(getStreamError(this));
2222
+ cb(null);
2223
+ }
2224
+ [Symbol.asyncIterator]() {
2225
+ let error = null;
2226
+ let promiseResolve = null;
2227
+ let promiseReject = null;
2228
+ let entryStream = null;
2229
+ let entryCallback = null;
2230
+ const extract3 = this;
2231
+ this.on("entry", onentry);
2232
+ this.on("error", (err) => {
2233
+ error = err;
2234
+ });
2235
+ this.on("close", onclose);
2236
+ return {
2237
+ [Symbol.asyncIterator]() {
2238
+ return this;
2239
+ },
2240
+ next() {
2241
+ return new Promise(onnext);
2242
+ },
2243
+ return() {
2244
+ return destroy(null);
2245
+ },
2246
+ throw(err) {
2247
+ return destroy(err);
2248
+ }
2249
+ };
2250
+ function consumeCallback(err) {
2251
+ if (!entryCallback) return;
2252
+ const cb = entryCallback;
2253
+ entryCallback = null;
2254
+ cb(err);
2255
+ }
2256
+ function onnext(resolve2, reject) {
2257
+ if (error) {
2258
+ return reject(error);
2259
+ }
2260
+ if (entryStream) {
2261
+ resolve2({ value: entryStream, done: false });
2262
+ entryStream = null;
2263
+ return;
2264
+ }
2265
+ promiseResolve = resolve2;
2266
+ promiseReject = reject;
2267
+ consumeCallback(null);
2268
+ if (extract3._finished && promiseResolve) {
2269
+ promiseResolve({ value: void 0, done: true });
2270
+ promiseResolve = promiseReject = null;
2271
+ }
2272
+ }
2273
+ function onentry(header, stream, callback) {
2274
+ entryCallback = callback;
2275
+ stream.on("error", noop);
2276
+ if (promiseResolve) {
2277
+ promiseResolve({ value: stream, done: false });
2278
+ promiseResolve = promiseReject = null;
2279
+ } else {
2280
+ entryStream = stream;
2281
+ }
2282
+ }
2283
+ function onclose() {
2284
+ consumeCallback(error);
2285
+ if (!promiseResolve) return;
2286
+ if (error) promiseReject(error);
2287
+ else promiseResolve({ value: void 0, done: true });
2288
+ promiseResolve = promiseReject = null;
2289
+ }
2290
+ function destroy(err) {
2291
+ extract3.destroy(err);
2292
+ consumeCallback(err);
2293
+ return new Promise((resolve2, reject) => {
2294
+ if (extract3.destroyed) return resolve2({ value: void 0, done: true });
2295
+ extract3.once("close", function() {
2296
+ if (err) reject(err);
2297
+ else resolve2({ value: void 0, done: true });
2298
+ });
2299
+ });
2300
+ }
2301
+ }
2302
+ };
2303
+ module.exports = function extract3(opts) {
2304
+ return new Extract(opts);
2305
+ };
2306
+ function noop() {
2307
+ }
2308
+ function overflow(size) {
2309
+ size &= 511;
2310
+ return size && 512 - size;
2311
+ }
2312
+ }
2313
+ });
2314
+
2315
+ // ../../node_modules/@sparticuz/chromium/node_modules/tar-stream/constants.js
2316
+ var require_constants = __commonJS({
2317
+ "../../node_modules/@sparticuz/chromium/node_modules/tar-stream/constants.js"(exports, module) {
2318
+ var constants = {
2319
+ // just for envs without fs
2320
+ S_IFMT: 61440,
2321
+ S_IFDIR: 16384,
2322
+ S_IFCHR: 8192,
2323
+ S_IFBLK: 24576,
2324
+ S_IFIFO: 4096,
2325
+ S_IFLNK: 40960
2326
+ };
2327
+ try {
2328
+ module.exports = __require("fs").constants || constants;
2329
+ } catch {
2330
+ module.exports = constants;
2331
+ }
2332
+ }
2333
+ });
2334
+
2335
+ // ../../node_modules/@sparticuz/chromium/node_modules/tar-stream/pack.js
2336
+ var require_pack = __commonJS({
2337
+ "../../node_modules/@sparticuz/chromium/node_modules/tar-stream/pack.js"(exports, module) {
2338
+ var { Readable: Readable2, Writable, getStreamError } = require_streamx();
2339
+ var b4a = require_b4a();
2340
+ var constants = require_constants();
2341
+ var headers = require_headers();
2342
+ var DMODE = 493;
2343
+ var FMODE = 420;
2344
+ var END_OF_TAR = b4a.alloc(1024);
2345
+ var Sink = class extends Writable {
2346
+ constructor(pack, header, callback) {
2347
+ super({ mapWritable, eagerOpen: true });
2348
+ this.written = 0;
2349
+ this.header = header;
2350
+ this._callback = callback;
2351
+ this._linkname = null;
2352
+ this._isLinkname = header.type === "symlink" && !header.linkname;
2353
+ this._isVoid = header.type !== "file" && header.type !== "contiguous-file";
2354
+ this._finished = false;
2355
+ this._pack = pack;
2356
+ this._openCallback = null;
2357
+ if (this._pack._stream === null) this._pack._stream = this;
2358
+ else this._pack._pending.push(this);
2359
+ }
2360
+ _open(cb) {
2361
+ this._openCallback = cb;
2362
+ if (this._pack._stream === this) this._continueOpen();
2363
+ }
2364
+ _continuePack(err) {
2365
+ if (this._callback === null) return;
2366
+ const callback = this._callback;
2367
+ this._callback = null;
2368
+ callback(err);
2369
+ }
2370
+ _continueOpen() {
2371
+ if (this._pack._stream === null) this._pack._stream = this;
2372
+ const cb = this._openCallback;
2373
+ this._openCallback = null;
2374
+ if (cb === null) return;
2375
+ if (this._pack.destroying) return cb(new Error("pack stream destroyed"));
2376
+ if (this._pack._finalized) return cb(new Error("pack stream is already finalized"));
2377
+ this._pack._stream = this;
2378
+ if (!this._isLinkname) {
2379
+ this._pack._encode(this.header);
2380
+ }
2381
+ if (this._isVoid) {
2382
+ this._finish();
2383
+ this._continuePack(null);
2384
+ }
2385
+ cb(null);
2386
+ }
2387
+ _write(data, cb) {
2388
+ if (this._isLinkname) {
2389
+ this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data;
2390
+ return cb(null);
2391
+ }
2392
+ if (this._isVoid) {
2393
+ if (data.byteLength > 0) {
2394
+ return cb(new Error("No body allowed for this entry"));
2395
+ }
2396
+ return cb();
2397
+ }
2398
+ this.written += data.byteLength;
2399
+ if (this._pack.push(data)) return cb();
2400
+ this._pack._drain = cb;
2401
+ }
2402
+ _finish() {
2403
+ if (this._finished) return;
2404
+ this._finished = true;
2405
+ if (this._isLinkname) {
2406
+ this.header.linkname = this._linkname ? b4a.toString(this._linkname, "utf-8") : "";
2407
+ this._pack._encode(this.header);
2408
+ }
2409
+ overflow(this._pack, this.header.size);
2410
+ this._pack._done(this);
2411
+ }
2412
+ _final(cb) {
2413
+ if (this.written !== this.header.size) {
2414
+ return cb(new Error("Size mismatch"));
2415
+ }
2416
+ this._finish();
2417
+ cb(null);
2418
+ }
2419
+ _getError() {
2420
+ return getStreamError(this) || new Error("tar entry destroyed");
2421
+ }
2422
+ _predestroy() {
2423
+ this._pack.destroy(this._getError());
2424
+ }
2425
+ _destroy(cb) {
2426
+ this._pack._done(this);
2427
+ this._continuePack(this._finished ? null : this._getError());
2428
+ cb();
2429
+ }
2430
+ };
2431
+ var Pack = class extends Readable2 {
2432
+ constructor(opts) {
2433
+ super(opts);
2434
+ this._drain = noop;
2435
+ this._finalized = false;
2436
+ this._finalizing = false;
2437
+ this._pending = [];
2438
+ this._stream = null;
2439
+ }
2440
+ entry(header, buffer, callback) {
2441
+ if (this._finalized || this.destroying) throw new Error("already finalized or destroyed");
2442
+ if (typeof buffer === "function") {
2443
+ callback = buffer;
2444
+ buffer = null;
2445
+ }
2446
+ if (!callback) callback = noop;
2447
+ if (!header.size || header.type === "symlink") header.size = 0;
2448
+ if (!header.type) header.type = modeToType(header.mode);
2449
+ if (!header.mode) header.mode = header.type === "directory" ? DMODE : FMODE;
2450
+ if (!header.uid) header.uid = 0;
2451
+ if (!header.gid) header.gid = 0;
2452
+ if (!header.mtime) header.mtime = /* @__PURE__ */ new Date();
2453
+ if (typeof buffer === "string") buffer = b4a.from(buffer);
2454
+ const sink = new Sink(this, header, callback);
2455
+ if (b4a.isBuffer(buffer)) {
2456
+ header.size = buffer.byteLength;
2457
+ sink.write(buffer);
2458
+ sink.end();
2459
+ return sink;
2460
+ }
2461
+ if (sink._isVoid) {
2462
+ return sink;
2463
+ }
2464
+ return sink;
2465
+ }
2466
+ finalize() {
2467
+ if (this._stream || this._pending.length > 0) {
2468
+ this._finalizing = true;
2469
+ return;
2470
+ }
2471
+ if (this._finalized) return;
2472
+ this._finalized = true;
2473
+ this.push(END_OF_TAR);
2474
+ this.push(null);
2475
+ }
2476
+ _done(stream) {
2477
+ if (stream !== this._stream) return;
2478
+ this._stream = null;
2479
+ if (this._finalizing) this.finalize();
2480
+ if (this._pending.length) this._pending.shift()._continueOpen();
2481
+ }
2482
+ _encode(header) {
2483
+ if (!header.pax) {
2484
+ const buf = headers.encode(header);
2485
+ if (buf) {
2486
+ this.push(buf);
2487
+ return;
2488
+ }
2489
+ }
2490
+ this._encodePax(header);
2491
+ }
2492
+ _encodePax(header) {
2493
+ const paxHeader = headers.encodePax({
2494
+ name: header.name,
2495
+ linkname: header.linkname,
2496
+ pax: header.pax
2497
+ });
2498
+ const newHeader = {
2499
+ name: "PaxHeader",
2500
+ mode: header.mode,
2501
+ uid: header.uid,
2502
+ gid: header.gid,
2503
+ size: paxHeader.byteLength,
2504
+ mtime: header.mtime,
2505
+ type: "pax-header",
2506
+ linkname: header.linkname && "PaxHeader",
2507
+ uname: header.uname,
2508
+ gname: header.gname,
2509
+ devmajor: header.devmajor,
2510
+ devminor: header.devminor
2511
+ };
2512
+ this.push(headers.encode(newHeader));
2513
+ this.push(paxHeader);
2514
+ overflow(this, paxHeader.byteLength);
2515
+ newHeader.size = header.size;
2516
+ newHeader.type = header.type;
2517
+ this.push(headers.encode(newHeader));
2518
+ }
2519
+ _doDrain() {
2520
+ const drain = this._drain;
2521
+ this._drain = noop;
2522
+ drain();
2523
+ }
2524
+ _predestroy() {
2525
+ const err = getStreamError(this);
2526
+ if (this._stream) this._stream.destroy(err);
2527
+ while (this._pending.length) {
2528
+ const stream = this._pending.shift();
2529
+ stream.destroy(err);
2530
+ stream._continueOpen();
2531
+ }
2532
+ this._doDrain();
2533
+ }
2534
+ _read(cb) {
2535
+ this._doDrain();
2536
+ cb();
2537
+ }
2538
+ };
2539
+ module.exports = function pack(opts) {
2540
+ return new Pack(opts);
2541
+ };
2542
+ function modeToType(mode) {
2543
+ switch (mode & constants.S_IFMT) {
2544
+ case constants.S_IFBLK:
2545
+ return "block-device";
2546
+ case constants.S_IFCHR:
2547
+ return "character-device";
2548
+ case constants.S_IFDIR:
2549
+ return "directory";
2550
+ case constants.S_IFIFO:
2551
+ return "fifo";
2552
+ case constants.S_IFLNK:
2553
+ return "symlink";
2554
+ }
2555
+ return "file";
2556
+ }
2557
+ function noop() {
2558
+ }
2559
+ function overflow(self, size) {
2560
+ size &= 511;
2561
+ if (size) self.push(END_OF_TAR.subarray(0, 512 - size));
2562
+ }
2563
+ function mapWritable(buf) {
2564
+ return b4a.isBuffer(buf) ? buf : b4a.from(buf);
2565
+ }
2566
+ }
2567
+ });
2568
+
2569
+ // ../../node_modules/@sparticuz/chromium/node_modules/tar-stream/index.js
2570
+ var require_tar_stream = __commonJS({
2571
+ "../../node_modules/@sparticuz/chromium/node_modules/tar-stream/index.js"(exports) {
2572
+ exports.extract = require_extract();
2573
+ exports.pack = require_pack();
2574
+ }
2575
+ });
2576
+
2577
+ // ../../node_modules/wrappy/wrappy.js
2578
+ var require_wrappy = __commonJS({
2579
+ "../../node_modules/wrappy/wrappy.js"(exports, module) {
2580
+ module.exports = wrappy;
2581
+ function wrappy(fn, cb) {
2582
+ if (fn && cb) return wrappy(fn)(cb);
2583
+ if (typeof fn !== "function")
2584
+ throw new TypeError("need wrapper function");
2585
+ Object.keys(fn).forEach(function(k) {
2586
+ wrapper[k] = fn[k];
2587
+ });
2588
+ return wrapper;
2589
+ function wrapper() {
2590
+ var args = new Array(arguments.length);
2591
+ for (var i = 0; i < args.length; i++) {
2592
+ args[i] = arguments[i];
2593
+ }
2594
+ var ret = fn.apply(this, args);
2595
+ var cb2 = args[args.length - 1];
2596
+ if (typeof ret === "function" && ret !== cb2) {
2597
+ Object.keys(cb2).forEach(function(k) {
2598
+ ret[k] = cb2[k];
2599
+ });
2600
+ }
2601
+ return ret;
2602
+ }
2603
+ }
2604
+ }
2605
+ });
2606
+
2607
+ // ../../node_modules/once/once.js
2608
+ var require_once = __commonJS({
2609
+ "../../node_modules/once/once.js"(exports, module) {
2610
+ var wrappy = require_wrappy();
2611
+ module.exports = wrappy(once);
2612
+ module.exports.strict = wrappy(onceStrict);
2613
+ once.proto = once(function() {
2614
+ Object.defineProperty(Function.prototype, "once", {
2615
+ value: function() {
2616
+ return once(this);
2617
+ },
2618
+ configurable: true
2619
+ });
2620
+ Object.defineProperty(Function.prototype, "onceStrict", {
2621
+ value: function() {
2622
+ return onceStrict(this);
2623
+ },
2624
+ configurable: true
2625
+ });
2626
+ });
2627
+ function once(fn) {
2628
+ var f = function() {
2629
+ if (f.called) return f.value;
2630
+ f.called = true;
2631
+ return f.value = fn.apply(this, arguments);
2632
+ };
2633
+ f.called = false;
2634
+ return f;
2635
+ }
2636
+ function onceStrict(fn) {
2637
+ var f = function() {
2638
+ if (f.called)
2639
+ throw new Error(f.onceError);
2640
+ f.called = true;
2641
+ return f.value = fn.apply(this, arguments);
2642
+ };
2643
+ var name = fn.name || "Function wrapped with `once`";
2644
+ f.onceError = name + " shouldn't be called more than once";
2645
+ f.called = false;
2646
+ return f;
2647
+ }
2648
+ }
2649
+ });
2650
+
2651
+ // ../../node_modules/end-of-stream/index.js
2652
+ var require_end_of_stream = __commonJS({
2653
+ "../../node_modules/end-of-stream/index.js"(exports, module) {
2654
+ var once = require_once();
2655
+ var noop = function() {
2656
+ };
2657
+ var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process);
2658
+ var isRequest = function(stream) {
2659
+ return stream.setHeader && typeof stream.abort === "function";
2660
+ };
2661
+ var isChildProcess = function(stream) {
2662
+ return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3;
2663
+ };
2664
+ var eos = function(stream, opts, callback) {
2665
+ if (typeof opts === "function") return eos(stream, null, opts);
2666
+ if (!opts) opts = {};
2667
+ callback = once(callback || noop);
2668
+ var ws = stream._writableState;
2669
+ var rs = stream._readableState;
2670
+ var readable = opts.readable || opts.readable !== false && stream.readable;
2671
+ var writable = opts.writable || opts.writable !== false && stream.writable;
2672
+ var cancelled = false;
2673
+ var onlegacyfinish = function() {
2674
+ if (!stream.writable) onfinish();
2675
+ };
2676
+ var onfinish = function() {
2677
+ writable = false;
2678
+ if (!readable) callback.call(stream);
2679
+ };
2680
+ var onend = function() {
2681
+ readable = false;
2682
+ if (!writable) callback.call(stream);
2683
+ };
2684
+ var onexit = function(exitCode) {
2685
+ callback.call(stream, exitCode ? new Error("exited with error code: " + exitCode) : null);
2686
+ };
2687
+ var onerror = function(err) {
2688
+ callback.call(stream, err);
2689
+ };
2690
+ var onclose = function() {
2691
+ qnt(onclosenexttick);
2692
+ };
2693
+ var onclosenexttick = function() {
2694
+ if (cancelled) return;
2695
+ if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error("premature close"));
2696
+ if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error("premature close"));
2697
+ };
2698
+ var onrequest = function() {
2699
+ stream.req.on("finish", onfinish);
2700
+ };
2701
+ if (isRequest(stream)) {
2702
+ stream.on("complete", onfinish);
2703
+ stream.on("abort", onclose);
2704
+ if (stream.req) onrequest();
2705
+ else stream.on("request", onrequest);
2706
+ } else if (writable && !ws) {
2707
+ stream.on("end", onlegacyfinish);
2708
+ stream.on("close", onlegacyfinish);
2709
+ }
2710
+ if (isChildProcess(stream)) stream.on("exit", onexit);
2711
+ stream.on("end", onend);
2712
+ stream.on("finish", onfinish);
2713
+ if (opts.error !== false) stream.on("error", onerror);
2714
+ stream.on("close", onclose);
2715
+ return function() {
2716
+ cancelled = true;
2717
+ stream.removeListener("complete", onfinish);
2718
+ stream.removeListener("abort", onclose);
2719
+ stream.removeListener("request", onrequest);
2720
+ if (stream.req) stream.req.removeListener("finish", onfinish);
2721
+ stream.removeListener("end", onlegacyfinish);
2722
+ stream.removeListener("close", onlegacyfinish);
2723
+ stream.removeListener("finish", onfinish);
2724
+ stream.removeListener("exit", onexit);
2725
+ stream.removeListener("end", onend);
2726
+ stream.removeListener("error", onerror);
2727
+ stream.removeListener("close", onclose);
2728
+ };
2729
+ };
2730
+ module.exports = eos;
2731
+ }
2732
+ });
2733
+
2734
+ // ../../node_modules/pump/index.js
2735
+ var require_pump = __commonJS({
2736
+ "../../node_modules/pump/index.js"(exports, module) {
2737
+ var once = require_once();
2738
+ var eos = require_end_of_stream();
2739
+ var fs;
2740
+ try {
2741
+ fs = __require("fs");
2742
+ } catch (e) {
2743
+ }
2744
+ var noop = function() {
2745
+ };
2746
+ var ancient = typeof process === "undefined" ? false : /^v?\.0/.test(process.version);
2747
+ var isFn = function(fn) {
2748
+ return typeof fn === "function";
2749
+ };
2750
+ var isFS = function(stream) {
2751
+ if (!ancient) return false;
2752
+ if (!fs) return false;
2753
+ return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close);
2754
+ };
2755
+ var isRequest = function(stream) {
2756
+ return stream.setHeader && isFn(stream.abort);
2757
+ };
2758
+ var destroyer = function(stream, reading, writing, callback) {
2759
+ callback = once(callback);
2760
+ var closed = false;
2761
+ stream.on("close", function() {
2762
+ closed = true;
2763
+ });
2764
+ eos(stream, { readable: reading, writable: writing }, function(err) {
2765
+ if (err) return callback(err);
2766
+ closed = true;
2767
+ callback();
2768
+ });
2769
+ var destroyed = false;
2770
+ return function(err) {
2771
+ if (closed) return;
2772
+ if (destroyed) return;
2773
+ destroyed = true;
2774
+ if (isFS(stream)) return stream.close(noop);
2775
+ if (isRequest(stream)) return stream.abort();
2776
+ if (isFn(stream.destroy)) return stream.destroy();
2777
+ callback(err || new Error("stream was destroyed"));
2778
+ };
2779
+ };
2780
+ var call = function(fn) {
2781
+ fn();
2782
+ };
2783
+ var pipe = function(from, to) {
2784
+ return from.pipe(to);
2785
+ };
2786
+ var pump = function() {
2787
+ var streams = Array.prototype.slice.call(arguments);
2788
+ var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;
2789
+ if (Array.isArray(streams[0])) streams = streams[0];
2790
+ if (streams.length < 2) throw new Error("pump requires two streams per minimum");
2791
+ var error;
2792
+ var destroys = streams.map(function(stream, i) {
2793
+ var reading = i < streams.length - 1;
2794
+ var writing = i > 0;
2795
+ return destroyer(stream, reading, writing, function(err) {
2796
+ if (!error) error = err;
2797
+ if (err) destroys.forEach(call);
2798
+ if (reading) return;
2799
+ destroys.forEach(call);
2800
+ callback(error);
2801
+ });
2802
+ });
2803
+ return streams.reduce(pipe);
2804
+ };
2805
+ module.exports = pump;
2806
+ }
2807
+ });
2808
+
2809
+ // ../../node_modules/@sparticuz/chromium/node_modules/tar-fs/index.js
2810
+ var require_tar_fs = __commonJS({
2811
+ "../../node_modules/@sparticuz/chromium/node_modules/tar-fs/index.js"(exports) {
2812
+ var tar = require_tar_stream();
2813
+ var pump = require_pump();
2814
+ var fs = __require("fs");
2815
+ var path = __require("path");
2816
+ var win32 = (global.Bare ? global.Bare.platform : process.platform) === "win32";
2817
+ exports.pack = function pack(cwd, opts) {
2818
+ if (!cwd) cwd = ".";
2819
+ if (!opts) opts = {};
2820
+ const xfs = opts.fs || fs;
2821
+ const ignore = opts.ignore || opts.filter || noop;
2822
+ const mapStream = opts.mapStream || echo;
2823
+ const statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort);
2824
+ const strict = opts.strict !== false;
2825
+ const umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask();
2826
+ const pack2 = opts.pack || tar.pack();
2827
+ const finish = opts.finish || noop;
2828
+ let map = opts.map || noop;
2829
+ let dmode = typeof opts.dmode === "number" ? opts.dmode : 0;
2830
+ let fmode = typeof opts.fmode === "number" ? opts.fmode : 0;
2831
+ if (opts.strip) map = strip(map, opts.strip);
2832
+ if (opts.readable) {
2833
+ dmode |= parseInt(555, 8);
2834
+ fmode |= parseInt(444, 8);
2835
+ }
2836
+ if (opts.writable) {
2837
+ dmode |= parseInt(333, 8);
2838
+ fmode |= parseInt(222, 8);
2839
+ }
2840
+ onnextentry();
2841
+ function onsymlink(filename, header) {
2842
+ xfs.readlink(path.join(cwd, filename), function(err, linkname) {
2843
+ if (err) return pack2.destroy(err);
2844
+ header.linkname = normalize(linkname);
2845
+ pack2.entry(header, onnextentry);
2846
+ });
2847
+ }
2848
+ function onstat(err, filename, stat) {
2849
+ if (pack2.destroyed) return;
2850
+ if (err) return pack2.destroy(err);
2851
+ if (!filename) {
2852
+ if (opts.finalize !== false) pack2.finalize();
2853
+ return finish(pack2);
2854
+ }
2855
+ if (stat.isSocket()) return onnextentry();
2856
+ let header = {
2857
+ name: normalize(filename),
2858
+ mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
2859
+ mtime: stat.mtime,
2860
+ size: stat.size,
2861
+ type: "file",
2862
+ uid: stat.uid,
2863
+ gid: stat.gid
2864
+ };
2865
+ if (stat.isDirectory()) {
2866
+ header.size = 0;
2867
+ header.type = "directory";
2868
+ header = map(header) || header;
2869
+ return pack2.entry(header, onnextentry);
2870
+ }
2871
+ if (stat.isSymbolicLink()) {
2872
+ header.size = 0;
2873
+ header.type = "symlink";
2874
+ header = map(header) || header;
2875
+ return onsymlink(filename, header);
2876
+ }
2877
+ header = map(header) || header;
2878
+ if (!stat.isFile()) {
2879
+ if (strict) return pack2.destroy(new Error("unsupported type for " + filename));
2880
+ return onnextentry();
2881
+ }
2882
+ const entry = pack2.entry(header, onnextentry);
2883
+ const rs = mapStream(xfs.createReadStream(path.join(cwd, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header);
2884
+ rs.on("error", function(err2) {
2885
+ entry.destroy(err2);
2886
+ });
2887
+ pump(rs, entry);
2888
+ }
2889
+ function onnextentry(err) {
2890
+ if (err) return pack2.destroy(err);
2891
+ statNext(onstat);
2892
+ }
2893
+ return pack2;
2894
+ };
2895
+ function head(list) {
2896
+ return list.length ? list[list.length - 1] : null;
2897
+ }
2898
+ function processGetuid() {
2899
+ return !global.Bare && process.getuid ? process.getuid() : -1;
2900
+ }
2901
+ function processUmask() {
2902
+ return !global.Bare && process.umask ? process.umask() : 0;
2903
+ }
2904
+ exports.extract = function extract3(cwd, opts) {
2905
+ if (!cwd) cwd = ".";
2906
+ if (!opts) opts = {};
2907
+ cwd = path.resolve(cwd);
2908
+ const xfs = opts.fs || fs;
2909
+ const ignore = opts.ignore || opts.filter || noop;
2910
+ const mapStream = opts.mapStream || echo;
2911
+ const own = opts.chown !== false && !win32 && processGetuid() === 0;
2912
+ const extract4 = opts.extract || tar.extract();
2913
+ const stack = [];
2914
+ const now = /* @__PURE__ */ new Date();
2915
+ const umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask();
2916
+ const strict = opts.strict !== false;
2917
+ const validateSymLinks = opts.validateSymlinks !== false;
2918
+ let map = opts.map || noop;
2919
+ let dmode = typeof opts.dmode === "number" ? opts.dmode : 0;
2920
+ let fmode = typeof opts.fmode === "number" ? opts.fmode : 0;
2921
+ if (opts.strip) map = strip(map, opts.strip);
2922
+ if (opts.readable) {
2923
+ dmode |= parseInt(555, 8);
2924
+ fmode |= parseInt(444, 8);
2925
+ }
2926
+ if (opts.writable) {
2927
+ dmode |= parseInt(333, 8);
2928
+ fmode |= parseInt(222, 8);
2929
+ }
2930
+ extract4.on("entry", onentry);
2931
+ if (opts.finish) extract4.on("finish", opts.finish);
2932
+ return extract4;
2933
+ function onentry(header, stream, next) {
2934
+ header = map(header) || header;
2935
+ header.name = normalize(header.name);
2936
+ const name = path.join(cwd, path.join("/", header.name));
2937
+ if (ignore(name, header)) {
2938
+ stream.resume();
2939
+ return next();
2940
+ }
2941
+ const dir = path.join(name, ".") === path.join(cwd, ".") ? cwd : path.dirname(name);
2942
+ validate(xfs, dir, path.join(cwd, "."), function(err, valid) {
2943
+ if (err) return next(err);
2944
+ if (!valid) return next(new Error(dir + " is not a valid path"));
2945
+ if (header.type === "directory") {
2946
+ stack.push([name, header.mtime]);
2947
+ return mkdirfix(name, {
2948
+ uid: header.uid,
2949
+ gid: header.gid,
2950
+ mode: header.mode
2951
+ }, stat);
2952
+ }
2953
+ mkdirfix(dir, {
2954
+ uid: header.uid,
2955
+ gid: header.gid,
2956
+ // normally, the folders with rights and owner should be part of the TAR file
2957
+ // if this is not the case, create folder for same user as file and with
2958
+ // standard permissions of 0o755 (rwxr-xr-x)
2959
+ mode: 493
2960
+ }, function(err2) {
2961
+ if (err2) return next(err2);
2962
+ switch (header.type) {
2963
+ case "file":
2964
+ return onfile();
2965
+ case "link":
2966
+ return onlink();
2967
+ case "symlink":
2968
+ return onsymlink();
2969
+ }
2970
+ if (strict) return next(new Error("unsupported type for " + name + " (" + header.type + ")"));
2971
+ stream.resume();
2972
+ next();
2973
+ });
2974
+ });
2975
+ function stat(err) {
2976
+ if (err) return next(err);
2977
+ if (path.join(name, ".") === path.join(cwd, ".")) return next();
2978
+ utimes(name, header, function(err2) {
2979
+ if (err2) return next(err2);
2980
+ if (win32) return next();
2981
+ chperm(name, header, next);
2982
+ });
2983
+ }
2984
+ function onsymlink() {
2985
+ if (win32) return next();
2986
+ xfs.unlink(name, function() {
2987
+ const dst = path.resolve(path.dirname(name), header.linkname);
2988
+ if (!inCwd(dst) && (validateSymLinks || opts.strip)) return next(new Error(name + " is not a valid symlink"));
2989
+ validateNotSymlink(xfs, dst, path.join(cwd, "."), function(err, valid) {
2990
+ if (err) return next(err);
2991
+ if (!valid && validateSymLinks) return next(new Error(name + " is not a valid symlink"));
2992
+ xfs.symlink(header.linkname, name, stat);
2993
+ });
2994
+ });
2995
+ }
2996
+ function onlink() {
2997
+ if (win32) return next();
2998
+ xfs.unlink(name, function() {
2999
+ const link = path.join(cwd, path.join("/", header.linkname));
3000
+ xfs.realpath(link, function(err, dst) {
3001
+ if (err || !inCwd(dst)) return next(new Error(name + " is not a valid hardlink"));
3002
+ xfs.link(dst, name, function(err2) {
3003
+ if (err2 && err2.code === "EPERM" && opts.hardlinkAsFilesFallback) {
3004
+ stream = xfs.createReadStream(dst);
3005
+ return onfile();
3006
+ }
3007
+ stat(err2);
3008
+ });
3009
+ });
3010
+ });
3011
+ }
3012
+ function inCwd(dst) {
3013
+ return dst === cwd || dst.startsWith(cwd + path.sep);
3014
+ }
3015
+ function onfile() {
3016
+ xfs.lstat(name, function(err, st) {
3017
+ if (!err && st.isSymbolicLink()) return xfs.unlink(name, onwrite);
3018
+ onwrite();
3019
+ });
3020
+ function onwrite(err) {
3021
+ if (err) return next(err);
3022
+ const ws = xfs.createWriteStream(name);
3023
+ const rs = mapStream(stream, header);
3024
+ ws.on("error", function(err2) {
3025
+ rs.destroy(err2);
3026
+ });
3027
+ pump(rs, ws, function(err2) {
3028
+ if (err2) return next(err2);
3029
+ ws.on("close", stat);
3030
+ });
3031
+ }
3032
+ }
3033
+ }
3034
+ function utimesParent(name, cb) {
3035
+ let top;
3036
+ while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop();
3037
+ if (!top) return cb();
3038
+ xfs.utimes(top[0], now, top[1], cb);
3039
+ }
3040
+ function utimes(name, header, cb) {
3041
+ if (opts.utimes === false) return cb();
3042
+ if (header.type === "directory") return xfs.utimes(name, now, header.mtime, cb);
3043
+ if (header.type === "symlink") return utimesParent(name, cb);
3044
+ xfs.utimes(name, now, header.mtime, function(err) {
3045
+ if (err) return cb(err);
3046
+ utimesParent(name, cb);
3047
+ });
3048
+ }
3049
+ function chperm(name, header, cb) {
3050
+ const link = header.type === "symlink";
3051
+ const chmod = link ? xfs.lchmod : xfs.chmod;
3052
+ const chown = link ? xfs.lchown : xfs.chown;
3053
+ if (!chmod) return cb();
3054
+ const mode = (header.mode | (header.type === "directory" ? dmode : fmode)) & umask & 511;
3055
+ if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown);
3056
+ else onchown(null);
3057
+ function onchown(err) {
3058
+ if (err) return cb(err);
3059
+ if (!chmod) return cb();
3060
+ chmod.call(xfs, name, mode, cb);
3061
+ }
3062
+ }
3063
+ function mkdirfix(name, opts2, cb) {
3064
+ xfs.stat(name, function(err) {
3065
+ if (!err) return cb(null);
3066
+ if (err.code !== "ENOENT") return cb(err);
3067
+ xfs.mkdir(name, { mode: opts2.mode, recursive: true }, function(err2, made) {
3068
+ if (err2) return cb(err2);
3069
+ chperm(name, opts2, cb);
3070
+ });
3071
+ });
3072
+ }
3073
+ };
3074
+ function validateNotSymlink(fs2, name, root, cb) {
3075
+ if (name === root) return cb(null, true);
3076
+ if (!name.startsWith(root + path.sep)) return cb(null, false);
3077
+ fs2.lstat(name, function(err, st) {
3078
+ if (err && err.code !== "ENOENT" && err.code !== "EPERM") return cb(err);
3079
+ if (err || !st.isSymbolicLink()) return validateNotSymlink(fs2, path.join(name, ".."), root, cb);
3080
+ cb(null, false);
3081
+ });
3082
+ }
3083
+ function validate(fs2, name, root, cb) {
3084
+ if (name === root) return cb(null, true);
3085
+ fs2.lstat(name, function(err, st) {
3086
+ if (err && err.code !== "ENOENT" && err.code !== "EPERM") return cb(err);
3087
+ if (err || st.isDirectory()) return validate(fs2, path.join(name, ".."), root, cb);
3088
+ cb(null, false);
3089
+ });
3090
+ }
3091
+ function inside(root, name) {
3092
+ return name === root || name.startsWith(root + path.sep);
3093
+ }
3094
+ function noop() {
3095
+ }
3096
+ function echo(name) {
3097
+ return name;
3098
+ }
3099
+ function normalize(name) {
3100
+ return win32 ? name.replace(/\\/g, "/").replace(/[:?<>|]/g, "_") : name;
3101
+ }
3102
+ function statAll(fs2, stat, cwd, ignore, entries, sort) {
3103
+ if (!entries) entries = ["."];
3104
+ const queue = entries.slice(0);
3105
+ const root = path.resolve(cwd);
3106
+ return function loop(callback) {
3107
+ if (!queue.length) return callback(null);
3108
+ const next = queue.shift();
3109
+ const nextAbs = path.join(cwd, next);
3110
+ if (!inside(root, path.resolve(cwd, next))) return callback(new Error(next + " is not a valid path"));
3111
+ stat.call(fs2, nextAbs, function(err, stat2) {
3112
+ if (err) return callback(entries.indexOf(next) === -1 && err.code === "ENOENT" ? null : err);
3113
+ if (!stat2.isDirectory()) return callback(null, next, stat2);
3114
+ fs2.readdir(nextAbs, function(err2, files) {
3115
+ if (err2) return callback(err2);
3116
+ if (sort) files.sort();
3117
+ for (let i = 0; i < files.length; i++) {
3118
+ if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]));
3119
+ }
3120
+ callback(null, next, stat2);
3121
+ });
3122
+ });
3123
+ };
3124
+ }
3125
+ function strip(map, level) {
3126
+ return function(header) {
3127
+ header.name = header.name.split("/").slice(level).join("/");
3128
+ const linkname = header.linkname;
3129
+ if (linkname && (header.type === "link" || path.isAbsolute(linkname))) {
3130
+ header.linkname = linkname.split("/").slice(level).join("/");
3131
+ }
3132
+ return map(header);
3133
+ };
3134
+ }
3135
+ }
3136
+ });
3137
+ var import_tar_fs, setupLambdaEnvironment, isValidUrl, isRunningInAmazonLinux2023, downloadAndExtract;
3138
+ var init_helper = __esm({
3139
+ "../../node_modules/@sparticuz/chromium/build/helper.js"() {
3140
+ import_tar_fs = __toESM(require_tar_fs());
3141
+ setupLambdaEnvironment = (baseLibPath) => {
3142
+ process.env["FONTCONFIG_PATH"] ??= join(tmpdir(), "fonts");
3143
+ process.env["HOME"] ??= tmpdir();
3144
+ if (process.env["LD_LIBRARY_PATH"] === void 0) {
3145
+ process.env["LD_LIBRARY_PATH"] = baseLibPath;
3146
+ } else if (!process.env["LD_LIBRARY_PATH"].startsWith(baseLibPath)) {
3147
+ process.env["LD_LIBRARY_PATH"] = [
3148
+ baseLibPath,
3149
+ ...new Set(process.env["LD_LIBRARY_PATH"].split(":"))
3150
+ ].join(":");
3151
+ }
3152
+ };
3153
+ isValidUrl = (input) => {
3154
+ try {
3155
+ const url = new URL(input);
3156
+ if (url.protocol === "https:")
3157
+ return true;
3158
+ if (url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]")) {
3159
+ return true;
3160
+ }
3161
+ return false;
3162
+ } catch {
3163
+ return false;
3164
+ }
3165
+ };
3166
+ isRunningInAmazonLinux2023 = (nodeMajorVersion2) => {
3167
+ const awsExecEnv = process.env["AWS_EXECUTION_ENV"] ?? "";
3168
+ const awsLambdaJsRuntime = process.env["AWS_LAMBDA_JS_RUNTIME"] ?? "";
3169
+ const codebuildImage = process.env["CODEBUILD_BUILD_IMAGE"] ?? "";
3170
+ if (awsExecEnv.includes("20.x") || awsExecEnv.includes("22.x") || awsExecEnv.includes("24.x") || awsLambdaJsRuntime.includes("20.x") || awsLambdaJsRuntime.includes("22.x") || awsLambdaJsRuntime.includes("24.x") || codebuildImage.includes("nodejs20") || codebuildImage.includes("nodejs22") || codebuildImage.includes("nodejs24")) {
3171
+ return true;
3172
+ }
3173
+ if (process.env["VERCEL"] && nodeMajorVersion2 >= 20) {
3174
+ return true;
3175
+ }
3176
+ return false;
3177
+ };
3178
+ downloadAndExtract = async (url) => {
3179
+ const destDir = join(tmpdir(), "chromium-pack");
3180
+ const response = await fetch(url, {
3181
+ redirect: "follow",
3182
+ signal: AbortSignal.timeout(3e5)
3183
+ });
3184
+ if (!response.ok) {
3185
+ throw new Error(`Unexpected status code: ${String(response.status)}.`);
3186
+ }
3187
+ if (!response.body) {
3188
+ throw new Error("Response body is empty.");
3189
+ }
3190
+ try {
3191
+ await pipeline(Readable.fromWeb(response.body), (0, import_tar_fs.extract)(destDir));
3192
+ } catch (error) {
3193
+ await new Promise((resolve2) => {
3194
+ rm(destDir, { force: true, recursive: true }, () => {
3195
+ resolve2();
3196
+ });
3197
+ });
3198
+ throw error;
35
3199
  }
3200
+ return destDir;
3201
+ };
3202
+ }
3203
+ });
3204
+ var import_tar_fs2, ARCHIVE_EXTENSION_REGEX, TAR_EXTENSION_REGEX, BROTLI_EXTENSION_REGEX, GZIP_EXTENSION_REGEX, inflate;
3205
+ var init_lambdafs = __esm({
3206
+ "../../node_modules/@sparticuz/chromium/build/lambdafs.js"() {
3207
+ import_tar_fs2 = __toESM(require_tar_fs());
3208
+ ARCHIVE_EXTENSION_REGEX = /\.(?:t(?:ar(?:\.(?:br|gz))?|br|gz)|br|gz)$/i;
3209
+ TAR_EXTENSION_REGEX = /\.t(?:ar(?:\.(?:br|gz))?|br|gz)$/i;
3210
+ BROTLI_EXTENSION_REGEX = /br$/i;
3211
+ GZIP_EXTENSION_REGEX = /gz$/i;
3212
+ inflate = (filePath) => {
3213
+ const output = filePath.includes("swiftshader") ? tmpdir() : join(tmpdir(), basename(filePath).replace(ARCHIVE_EXTENSION_REGEX, ""));
3214
+ return new Promise((resolve2, reject) => {
3215
+ if (filePath.includes("swiftshader")) {
3216
+ if (existsSync(`${output}/libGLESv2.so`)) {
3217
+ resolve2(output);
3218
+ return;
3219
+ }
3220
+ } else if (existsSync(output)) {
3221
+ resolve2(output);
3222
+ return;
3223
+ }
3224
+ const isBrotli = BROTLI_EXTENSION_REGEX.test(filePath);
3225
+ const isGzip = GZIP_EXTENSION_REGEX.test(filePath);
3226
+ const isTar = TAR_EXTENSION_REGEX.test(filePath);
3227
+ const highWaterMark = 2 ** 22;
3228
+ const source = createReadStream(filePath, { highWaterMark });
3229
+ let target;
3230
+ const handleError = (error) => {
3231
+ reject(error);
3232
+ };
3233
+ source.once("error", handleError);
3234
+ if (isTar) {
3235
+ target = (0, import_tar_fs2.extract)(output);
3236
+ target.once("finish", () => {
3237
+ resolve2(output);
3238
+ });
3239
+ } else {
3240
+ target = createWriteStream(output, { mode: 448 });
3241
+ target.once("close", () => {
3242
+ resolve2(output);
3243
+ });
3244
+ }
3245
+ target.once("error", handleError);
3246
+ if (isBrotli || isGzip) {
3247
+ const decompressor = isBrotli ? createBrotliDecompress({ chunkSize: 2 ** 21 }) : createUnzip({ chunkSize: 2 ** 21 });
3248
+ decompressor.once("error", handleError);
3249
+ source.pipe(decompressor).pipe(target);
3250
+ } else {
3251
+ source.pipe(target);
3252
+ }
3253
+ });
36
3254
  };
37
3255
  }
38
3256
  });
3257
+ function getBinPath() {
3258
+ return join(dirname(fileURLToPath(import.meta.url)), "..", "bin");
3259
+ }
3260
+ var init_paths = __esm({
3261
+ "../../node_modules/@sparticuz/chromium/build/paths.js"() {
3262
+ }
3263
+ });
39
3264
 
40
- // src/adapters/openrouter/client.ts
41
- var client_exports = {};
42
- __export(client_exports, {
43
- OpenRouterClient: () => OpenRouterClient
3265
+ // ../../node_modules/@sparticuz/chromium/build/index.js
3266
+ var build_exports = {};
3267
+ __export(build_exports, {
3268
+ default: () => build_default,
3269
+ inflate: () => inflate,
3270
+ setupLambdaEnvironment: () => setupLambdaEnvironment
44
3271
  });
45
- var DEFAULT_BASE_URL, OpenRouterClient;
46
- var init_client = __esm({
47
- "src/adapters/openrouter/client.ts"() {
48
- init_types();
49
- DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
50
- OpenRouterClient = class {
51
- constructor(config) {
52
- this.config = config;
53
- this.baseUrl = config.baseUrl ?? process.env.OPENROUTER_BASE_URL ?? DEFAULT_BASE_URL;
54
- this.headers = {
55
- "Authorization": `Bearer ${config.apiKey}`,
56
- "Content-Type": "application/json",
57
- "HTTP-Referer": config.siteUrl ?? process.env.OPENROUTER_SITE_URL ?? "https://ggui.ai",
58
- "X-Title": config.siteName ?? process.env.OPENROUTER_SITE_NAME ?? "ggui"
59
- };
3272
+ var nodeMajorVersion, Chromium, build_default;
3273
+ var init_build = __esm({
3274
+ "../../node_modules/@sparticuz/chromium/build/index.js"() {
3275
+ init_helper();
3276
+ init_lambdafs();
3277
+ init_paths();
3278
+ init_helper();
3279
+ init_lambdafs();
3280
+ nodeMajorVersion = Number.parseInt(process.versions.node.split(".")[0] ?? "");
3281
+ if (isRunningInAmazonLinux2023(nodeMajorVersion)) {
3282
+ setupLambdaEnvironment(join(tmpdir(), "al2023", "lib"));
3283
+ }
3284
+ Chromium = class {
3285
+ /**
3286
+ * Returns a list of additional Chromium flags recommended for serverless environments.
3287
+ * The canonical list of flags can be found on https://peter.sh/experiments/chromium-command-line-switches/.
3288
+ * Most of below can be found here: https://github.com/GoogleChrome/chrome-launcher/blob/main/docs/chrome-flags-for-tools.md
3289
+ */
3290
+ static get args() {
3291
+ const chromiumFlags = [
3292
+ "--ash-no-nudges",
3293
+ // Avoids blue bubble "user education" nudges (eg., "… give your browser a new look", Memory Saver)
3294
+ "--disable-domain-reliability",
3295
+ // Disables Domain Reliability Monitoring, which tracks whether the browser has difficulty contacting Google-owned sites and uploads reports to Google.
3296
+ "--disable-print-preview",
3297
+ // https://source.chromium.org/search?q=lang:cpp+symbol:kDisablePrintPreview&ss=chromium
3298
+ "--disk-cache-size=33554432",
3299
+ // https://source.chromium.org/search?q=lang:cpp+symbol:kDiskCacheSize&ss=chromium Forces the maximum disk space to be used by the disk cache, in bytes.
3300
+ "--no-default-browser-check",
3301
+ // Disable the default browser check, do not prompt to set it as such. (This is already set by Playwright, but not Puppeteer)
3302
+ "--no-pings",
3303
+ // Don't send hyperlink auditing pings
3304
+ "--single-process",
3305
+ // Runs the renderer and plugins in the same process as the browser. NOTES: Needs to be single-process to avoid `prctl(PR_SET_NO_NEW_PRIVS) failed` error
3306
+ "--font-render-hinting=none"
3307
+ // https://github.com/puppeteer/puppeteer/issues/2410#issuecomment-560573612
3308
+ ];
3309
+ const chromiumDisableFeatures = [
3310
+ "AudioServiceOutOfProcess",
3311
+ "IsolateOrigins",
3312
+ "site-per-process"
3313
+ // Disables OOPIF. https://www.chromium.org/Home/chromium-security/site-isolation
3314
+ ];
3315
+ const chromiumEnableFeatures = ["SharedArrayBuffer"];
3316
+ const graphicsFlags = [
3317
+ "--ignore-gpu-blocklist",
3318
+ // https://source.chromium.org/search?q=lang:cpp+symbol:kIgnoreGpuBlocklist&ss=chromium
3319
+ "--in-process-gpu"
3320
+ // Saves some memory by moving GPU process into a browser process thread
3321
+ ];
3322
+ if (this.graphics) {
3323
+ graphicsFlags.push(
3324
+ // As the unsafe WebGL fallback, SwANGLE (ANGLE + SwiftShader Vulkan)
3325
+ "--use-gl=angle",
3326
+ "--use-angle=swiftshader",
3327
+ "--enable-unsafe-swiftshader"
3328
+ );
3329
+ } else {
3330
+ graphicsFlags.push("--disable-webgl");
3331
+ }
3332
+ const insecureFlags = [
3333
+ "--allow-running-insecure-content",
3334
+ // https://source.chromium.org/search?q=lang:cpp+symbol:kAllowRunningInsecureContent&ss=chromium
3335
+ "--disable-setuid-sandbox",
3336
+ // Lambda runs as root, so this is required to allow Chromium to run as root
3337
+ "--disable-site-isolation-trials",
3338
+ // https://source.chromium.org/search?q=lang:cpp+symbol:kDisableSiteIsolation&ss=chromium
3339
+ "--disable-web-security"
3340
+ // https://source.chromium.org/search?q=lang:cpp+symbol:kDisableWebSecurity&ss=chromium
3341
+ ];
3342
+ const headlessFlags = [
3343
+ "--headless='shell'",
3344
+ // We only support running chrome-headless-shell
3345
+ "--no-sandbox",
3346
+ // https://source.chromium.org/search?q=lang:cpp+symbol:kNoSandbox&ss=chromium
3347
+ "--no-zygote"
3348
+ // https://source.chromium.org/search?q=lang:cpp+symbol:kNoZygote&ss=chromium
3349
+ ];
3350
+ return [
3351
+ ...chromiumFlags,
3352
+ `--disable-features=${[...chromiumDisableFeatures].join(",")}`,
3353
+ `--enable-features=${[...chromiumEnableFeatures].join(",")}`,
3354
+ ...graphicsFlags,
3355
+ ...insecureFlags,
3356
+ ...headlessFlags
3357
+ ];
60
3358
  }
61
- config;
62
- baseUrl;
63
- headers;
64
3359
  /**
65
- * Non-streaming chat completion.
3360
+ * Returns whether the graphics stack is enabled or disabled
3361
+ * @returns boolean
66
3362
  */
67
- async chatCompletion(params) {
68
- const body = { ...params, stream: false };
69
- const response = await fetch(`${this.baseUrl}/chat/completions`, {
70
- method: "POST",
71
- headers: this.headers,
72
- body: JSON.stringify(body)
73
- });
74
- if (!response.ok) {
75
- const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));
76
- const message = errorBody.error?.message ?? response.statusText;
77
- throw new OpenRouterError(message, response.status, void 0, response.headers);
3363
+ static get graphics() {
3364
+ return this.graphicsMode;
3365
+ }
3366
+ /**
3367
+ * Sets whether the graphics stack is enabled or disabled.
3368
+ * @param true means the stack is enabled. WebGL will work.
3369
+ * @param false means that the stack is disabled. WebGL will not work.
3370
+ * @default true
3371
+ */
3372
+ static set setGraphicsMode(value) {
3373
+ if (typeof value !== "boolean") {
3374
+ throw new TypeError(`Graphics mode must be a boolean, you entered '${String(value)}'`);
78
3375
  }
79
- return response.json();
3376
+ this.graphicsMode = value;
80
3377
  }
81
3378
  /**
82
- * Streaming chat completion via SSE.
83
- * Yields delta chunks, accumulates the final usage from the last chunk.
3379
+ * If true, the graphics stack and webgl is enabled,
3380
+ * If false, webgl will be disabled.
3381
+ * (If false, the swiftshader.tar.br file will also not extract)
84
3382
  */
85
- async *chatCompletionStream(params) {
86
- const body = { ...params, stream: true };
87
- const response = await fetch(`${this.baseUrl}/chat/completions`, {
88
- method: "POST",
89
- headers: this.headers,
90
- body: JSON.stringify(body)
91
- });
92
- if (!response.ok) {
93
- const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));
94
- const message = errorBody.error?.message ?? response.statusText;
95
- throw new OpenRouterError(message, response.status, void 0, response.headers);
3383
+ static graphicsMode = true;
3384
+ /**
3385
+ * Inflates the included version of Chromium
3386
+ * @param input The location of the `bin` folder
3387
+ * @returns The path to the `chromium` binary
3388
+ */
3389
+ static async executablePath(input) {
3390
+ if (existsSync(join(tmpdir(), "chromium"))) {
3391
+ return join(tmpdir(), "chromium");
96
3392
  }
97
- if (!response.body) {
98
- throw new OpenRouterError("No response body for streaming request", 500);
3393
+ if (input && isValidUrl(input)) {
3394
+ return this.executablePath(await downloadAndExtract(input));
99
3395
  }
100
- const reader = response.body.getReader();
101
- const decoder = new TextDecoder();
102
- let buffer = "";
103
- try {
104
- while (true) {
105
- const { done, value } = await reader.read();
106
- if (done) break;
107
- buffer += decoder.decode(value, { stream: true });
108
- const lines = buffer.split("\n");
109
- buffer = lines.pop() ?? "";
110
- for (const line of lines) {
111
- const trimmed = line.trim();
112
- if (!trimmed || trimmed.startsWith(":")) continue;
113
- if (trimmed === "data: [DONE]") return;
114
- if (!trimmed.startsWith("data: ")) continue;
115
- const json = trimmed.slice("data: ".length);
116
- try {
117
- yield JSON.parse(json);
118
- } catch {
119
- }
120
- }
121
- }
122
- } finally {
123
- reader.releaseLock();
3396
+ input ??= getBinPath();
3397
+ if (!existsSync(input)) {
3398
+ throw new Error(`The input directory "${input}" does not exist. If you are using a bundler (esbuild, webpack, etc.), you must externalize @sparticuz/chromium so it is not relocated. See: https://github.com/Sparticuz/chromium#bundler-configuration`);
124
3399
  }
3400
+ const promises = [
3401
+ inflate(join(input, "chromium.br")),
3402
+ inflate(join(input, "fonts.tar.br")),
3403
+ inflate(join(input, "swiftshader.tar.br"))
3404
+ ];
3405
+ if (isRunningInAmazonLinux2023(nodeMajorVersion)) {
3406
+ promises.push(inflate(join(input, "al2023.tar.br")));
3407
+ }
3408
+ const result = await Promise.all(promises);
3409
+ return result.shift();
125
3410
  }
126
3411
  };
3412
+ build_default = Chromium;
127
3413
  }
128
3414
  });
129
3415
 
@@ -354,20 +3640,51 @@ Intentional custom colors (status indicators) are acceptable when no semantic to
354
3640
  Only list ACTUAL violations. Use 'fail' only for pervasive violations.`
355
3641
  }
356
3642
  ];
357
- function getCriteriaByPriority(priority) {
358
- return CRITERIA.filter((c) => c.priority === priority);
3643
+ var FREE_DESIGN_CRITERIA_OVERRIDES = [
3644
+ {
3645
+ id: "tokens",
3646
+ name: "Color tokens",
3647
+ priority: "P1",
3648
+ tier: 0,
3649
+ failOutcome: "warn",
3650
+ codingGuidance: "Every color is a bare var(--ggui-color-*) from the token manifest \u2014 no hex, rgb()/hsl(), CSS named colors or literal fallbacks, in style props and <style> blocks alike. Spacing, typography, radius and shadow geometry may be literals.",
3651
+ evalInstruction: "Flag hardcoded hex colors, rgba/hsl functions, CSS named colors, and literal fallbacks inside var(--ggui-*) references. Do NOT flag literal spacing, font sizes, radii or pixel values \u2014 they are allowed in this mode."
3652
+ },
3653
+ {
3654
+ id: "visual",
3655
+ name: "Visual composition",
3656
+ priority: "P2",
3657
+ tier: 2,
3658
+ failOutcome: "warn",
3659
+ codingGuidance: "Compose deliberately: one clear focal point, consistent spacing rhythm, a coherent theme-token palette, a fit to the rendering canvas.",
3660
+ evalInstruction: `Evaluate VISUAL COMPOSITION: Is the component composed deliberately for its canvas?
3661
+
3662
+ Judge: visual hierarchy (one clear focal point, headings distinct from body text), consistent spacing rhythm and alignment, a coherent palette drawn from the theme tokens, fit to the canvas (fluid width, no fixed widths, nothing cramped or stretched).
3663
+ Do NOT reward or penalise the use of design-system primitives \u2014 raw HTML with inline CSS is a first-class choice here. Literal spacing / typography / radius values are fine.
3664
+
3665
+ Only list ACTUAL composition problems. Use 'fail' only for a fundamentally incoherent composition.`
3666
+ }
3667
+ ];
3668
+ function criteriaFor(designMode = "constrained") {
3669
+ if (designMode === "constrained") return CRITERIA;
3670
+ return CRITERIA.map(
3671
+ (c) => FREE_DESIGN_CRITERIA_OVERRIDES.find((o) => o.id === c.id) ?? c
3672
+ );
3673
+ }
3674
+ function getCriteriaByPriority(priority, designMode = "constrained") {
3675
+ return criteriaFor(designMode).filter((c) => c.priority === priority);
359
3676
  }
360
- function getCriterionById(id) {
361
- return CRITERIA.find((c) => c.id === id);
3677
+ function getCriterionById(id, designMode = "constrained") {
3678
+ return criteriaFor(designMode).find((c) => c.id === id);
362
3679
  }
363
- function getLLMCriteria() {
364
- return CRITERIA.filter((c) => c.tier > 0);
3680
+ function getLLMCriteria(designMode = "constrained") {
3681
+ return criteriaFor(designMode).filter((c) => c.tier > 0);
365
3682
  }
366
- function buildCodingCriteriaSummary() {
3683
+ function buildCodingCriteriaSummary(designMode = "constrained") {
367
3684
  const lines = ["## Priority (P0 first, then P1, then P2)", ""];
368
3685
  for (const priority of ["P0", "P1", "P2"]) {
369
3686
  const label = priority === "P0" ? "Must (compile + complete)" : priority === "P1" ? "Should (safety)" : "Nice (quality)";
370
- const criteria = getCriteriaByPriority(priority);
3687
+ const criteria = getCriteriaByPriority(priority, designMode);
371
3688
  lines.push(`**${priority} \u2014 ${label}:**`);
372
3689
  for (const c of criteria) {
373
3690
  lines.push(`- ${c.codingGuidance}`);
@@ -501,7 +3818,7 @@ function extractRetryAfterSec(e) {
501
3818
  return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : void 0;
502
3819
  }
503
3820
  function sleep(ms) {
504
- return new Promise((resolve) => setTimeout(resolve, ms));
3821
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
505
3822
  }
506
3823
  var MAX_RETRY_ATTEMPTS = 2;
507
3824
  var RETRY_AFTER_CAP_SEC = 15;
@@ -3233,6 +6550,7 @@ var stepperAdopted = {
3233
6550
  values: ["multi-step"],
3234
6551
  run(input) {
3235
6552
  if (input.compiledCode === null) return [];
6553
+ if (input.designMode === "free") return [];
3236
6554
  if (/<Stepper[\s/>]/.test(input.sourceCode)) return [];
3237
6555
  return [
3238
6556
  mkIssue2(
@@ -3293,7 +6611,8 @@ function runAxisChecks(classification, input) {
3293
6611
  compiledCode: input.compiledCode,
3294
6612
  ...input.contract !== void 0 ? { contract: input.contract } : {},
3295
6613
  originalPrompt: input.originalPrompt,
3296
- classification
6614
+ classification,
6615
+ ...input.designMode !== void 0 ? { designMode: input.designMode } : {}
3297
6616
  };
3298
6617
  const issues = [];
3299
6618
  const firedIds = /* @__PURE__ */ new Set();
@@ -3305,6 +6624,296 @@ function runAxisChecks(classification, input) {
3305
6624
  }
3306
6625
  return issues;
3307
6626
  }
6627
+
6628
+ // src/design-mode.ts
6629
+ var CANVAS_CLASSES = [
6630
+ "xs-chat-card",
6631
+ "mobile-fullscreen-small",
6632
+ "md",
6633
+ "lg",
6634
+ "xl"
6635
+ ];
6636
+ var CANVAS_VIEWPORTS = {
6637
+ "xs-chat-card": { width: 400, height: 640 },
6638
+ "mobile-fullscreen-small": { width: 390, height: 844 },
6639
+ md: { width: 768, height: 1024 },
6640
+ lg: { width: 1024, height: 768 },
6641
+ xl: { width: 1440, height: 900 }
6642
+ };
6643
+ function canvasDisplayModeForShell(shell) {
6644
+ return shell === "chat" || shell === "inline" ? "inline" : "fullscreen";
6645
+ }
6646
+ var CANVAS_BREAKPOINTS = { md: 600, lg: 1024, xl: 1440 };
6647
+ function canvasForViewportWidth(mode, width) {
6648
+ if (mode === "inline") return "xs-chat-card";
6649
+ if (width < CANVAS_BREAKPOINTS.md) return "mobile-fullscreen-small";
6650
+ if (width < CANVAS_BREAKPOINTS.lg) return "md";
6651
+ if (width < CANVAS_BREAKPOINTS.xl) return "lg";
6652
+ return "xl";
6653
+ }
6654
+ function canvasForRendering(shellType, screen) {
6655
+ const shell = shellType ?? "fullscreen";
6656
+ if (canvasDisplayModeForShell(shell) === "inline") return "xs-chat-card";
6657
+ if (shell === "spatial") return "md";
6658
+ switch (screen ?? "universal") {
6659
+ case "mobile":
6660
+ return "mobile-fullscreen-small";
6661
+ case "tablet":
6662
+ return "md";
6663
+ default:
6664
+ return "lg";
6665
+ }
6666
+ }
6667
+ var CANVAS_DESCRIPTORS = {
6668
+ "xs-chat-card": {
6669
+ label: "extra-small chat card",
6670
+ minWidthPx: 320,
6671
+ maxWidthPx: 480,
6672
+ host: "an inline card inside a chat message bubble \u2014 the host draws the card border, shadow and rounded corners; the component fills the bubble width and takes its natural height"
6673
+ },
6674
+ "mobile-fullscreen-small": {
6675
+ label: "small mobile fullscreen",
6676
+ minWidthPx: 320,
6677
+ maxWidthPx: 599,
6678
+ host: "a phone-sized viewport the component owns edge to edge \u2014 single column, touch targets at least 44px, the component manages its own scroll"
6679
+ },
6680
+ md: {
6681
+ label: "medium panel",
6682
+ minWidthPx: 600,
6683
+ maxWidthPx: 1023,
6684
+ host: "a tablet viewport or a floating panel (spatial / picture-in-picture) \u2014 one or two columns, medium density"
6685
+ },
6686
+ lg: {
6687
+ label: "large fullscreen",
6688
+ minWidthPx: 1024,
6689
+ maxWidthPx: 1439,
6690
+ host: "a desktop viewport the component owns edge to edge \u2014 multi-column layouts, hover states and pointer interactions are available"
6691
+ },
6692
+ xl: {
6693
+ label: "extra-large fullscreen",
6694
+ minWidthPx: 1440,
6695
+ maxWidthPx: 1920,
6696
+ host: "a wide desktop viewport the component owns edge to edge \u2014 cap content width or use the extra room deliberately; never stretch a single column across the whole width"
6697
+ }
6698
+ };
6699
+ function describeCanvas(canvas) {
6700
+ const d = CANVAS_DESCRIPTORS[canvas];
6701
+ return `This component renders on the \`${canvas}\` canvas (${d.label}): ${d.minWidthPx}\u2013${d.maxWidthPx}px wide, ${d.host}. Design for the whole range \u2014 the host may size the iframe anywhere inside it.`;
6702
+ }
6703
+
6704
+ // src/evaluation/visual-evaluator.ts
6705
+ function resolveUiGenPackageDir() {
6706
+ const selfDir = dirname(fileURLToPath(import.meta.url));
6707
+ return resolve(selfDir, "..", "..");
6708
+ }
6709
+ function resolveDesignPackageDir() {
6710
+ const selfDir = dirname(fileURLToPath(import.meta.url));
6711
+ return resolve(selfDir, "..", "..", "..", "design");
6712
+ }
6713
+ async function bundleForRendering(compiledCode, sampleProps) {
6714
+ const tmpDir = resolve(tmpdir(), "ggui-visual-eval-" + Date.now());
6715
+ mkdirSync(tmpDir, { recursive: true });
6716
+ const componentFile = resolve(tmpDir, "component.tsx");
6717
+ const entryFile = resolve(tmpDir, "entry.tsx");
6718
+ const designPkgDir = resolveDesignPackageDir();
6719
+ writeFileSync(componentFile, compiledCode);
6720
+ const entryCode = `
6721
+ import React from 'react';
6722
+ import { createRoot } from 'react-dom/client';
6723
+ import { GguiWireProvider } from '@ggui-ai/wire';
6724
+ import Component from './component.tsx';
6725
+
6726
+ const props = ${JSON.stringify(sampleProps)};
6727
+ const wireConfig = {
6728
+ app: { appId: 'visual-eval', appName: 'Visual evaluation' },
6729
+ render: { sessionId: 'visual-eval', isConnected: true },
6730
+ auth: { isAuthenticated: false },
6731
+ dispatch: () => {},
6732
+ subscribe: () => () => {},
6733
+ };
6734
+ class RenderErrorBoundary extends React.Component<{ children: React.ReactNode }, { message: string | null }> {
6735
+ state = { message: null as string | null };
6736
+ static getDerivedStateFromError(err: unknown) { return { message: err instanceof Error ? err.message : String(err) }; }
6737
+ render() {
6738
+ return this.state.message === null
6739
+ ? this.props.children
6740
+ : React.createElement('div', { className: 'error' }, 'Render error: ' + this.state.message);
6741
+ }
6742
+ }
6743
+ const root = createRoot(document.getElementById('root')!);
6744
+ try {
6745
+ root.render(
6746
+ React.createElement(GguiWireProvider, { config: wireConfig },
6747
+ React.createElement(RenderErrorBoundary, null, React.createElement(Component, props))),
6748
+ );
6749
+ } catch (err) {
6750
+ root.render(React.createElement('div', { className: 'error' }, 'Render error: ' + (err as Error).message));
6751
+ }
6752
+ `;
6753
+ writeFileSync(entryFile, entryCode);
6754
+ try {
6755
+ const result = await build({
6756
+ entryPoints: [entryFile],
6757
+ bundle: true,
6758
+ write: false,
6759
+ format: "esm",
6760
+ platform: "browser",
6761
+ target: "es2020",
6762
+ jsx: "automatic",
6763
+ jsxImportSource: "react",
6764
+ external: ["react", "react-dom", "react-dom/client", "react/jsx-runtime"],
6765
+ alias: {
6766
+ // D1: generated code imports the single `@ggui-ai/design` barrel.
6767
+ // The subpath aliases stay for any first-party / legacy code.
6768
+ "@ggui-ai/design": resolve(designPkgDir, "src", "index.ts"),
6769
+ "@ggui-ai/design/primitives": resolve(designPkgDir, "src", "primitives", "index.ts"),
6770
+ "@ggui-ai/design/components": resolve(designPkgDir, "src", "components", "index.ts"),
6771
+ "@ggui-ai/design/compositions": resolve(designPkgDir, "src", "compositions", "index.ts"),
6772
+ "@ggui-ai/design/interact": resolve(designPkgDir, "src", "interact", "index.ts")
6773
+ },
6774
+ // Bare imports in the generated component resolve against ui-gen's
6775
+ // own node_modules — the temp entry dir has none. Without this every
6776
+ // wire-bearing component (`@ggui-ai/wire`) failed to bundle.
6777
+ nodePaths: [resolve(resolveUiGenPackageDir(), "node_modules")],
6778
+ logLevel: "silent"
6779
+ });
6780
+ return result.outputFiles[0]?.text ?? "";
6781
+ } finally {
6782
+ try {
6783
+ unlinkSync(entryFile);
6784
+ } catch {
6785
+ }
6786
+ try {
6787
+ unlinkSync(componentFile);
6788
+ } catch {
6789
+ }
6790
+ }
6791
+ }
6792
+ function buildRenderHTML(bundledCode, cssTokens) {
6793
+ const tokens = cssTokens ?? getCssTokens();
6794
+ return `<!DOCTYPE html>
6795
+ <html>
6796
+ <head>
6797
+ <meta charset="utf-8">
6798
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6799
+ <style>
6800
+ ${tokens}
6801
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
6802
+ body {
6803
+ font-family: var(--ggui-font-family-sans, system-ui, -apple-system, sans-serif);
6804
+ background: var(--ggui-color-neutral-50, #ffffff);
6805
+ color: var(--ggui-color-neutral-900, #111827);
6806
+ }
6807
+ .error { color: #dc2626; padding: 16px; font-family: monospace; white-space: pre-wrap; }
6808
+ </style>
6809
+ </head>
6810
+ <body>
6811
+ <div id="root"></div>
6812
+ <script type="importmap">
6813
+ {
6814
+ "imports": {
6815
+ "react": "https://esm.sh/react@18",
6816
+ "react-dom": "https://esm.sh/react-dom@18",
6817
+ "react-dom/client": "https://esm.sh/react-dom@18/client",
6818
+ "react/jsx-runtime": "https://esm.sh/react@18/jsx-runtime"
6819
+ }
6820
+ }
6821
+ </script>
6822
+ <script type="module">
6823
+ ${bundledCode}
6824
+ </script>
6825
+ </body>
6826
+ </html>`;
6827
+ }
6828
+ var EXECUTABLE_PATH_LAUNCH_ARGS = ["--no-sandbox", "--disable-dev-shm-usage"];
6829
+ var DEFAULT_SCREENSHOT_VIEWPORT = { width: 1280, height: 800 };
6830
+ async function loadSparticuzChromium() {
6831
+ const chromium = await Promise.resolve().then(() => (init_build(), build_exports));
6832
+ return chromium.default;
6833
+ }
6834
+ async function resolveLaunchOptions(viewport, deps = {}) {
6835
+ const env = deps.env ?? process.env;
6836
+ const override = env.PUPPETEER_EXECUTABLE_PATH?.trim();
6837
+ if (override) {
6838
+ return {
6839
+ executablePath: override,
6840
+ args: [...EXECUTABLE_PATH_LAUNCH_ARGS],
6841
+ defaultViewport: viewport,
6842
+ headless: true
6843
+ };
6844
+ }
6845
+ const chromium = await (deps.loadChromium ?? loadSparticuzChromium)();
6846
+ return {
6847
+ args: chromium.args,
6848
+ defaultViewport: viewport,
6849
+ executablePath: await chromium.executablePath(),
6850
+ headless: true
6851
+ };
6852
+ }
6853
+ async function launchWithPuppeteer(options) {
6854
+ const puppeteer = await import('puppeteer-core');
6855
+ return puppeteer.default.launch(options);
6856
+ }
6857
+ async function captureScreenshot(html, viewport = DEFAULT_SCREENSHOT_VIEWPORT, deps = {}) {
6858
+ try {
6859
+ const launchOptions = await resolveLaunchOptions(viewport, deps);
6860
+ const browser = await (deps.launch ?? launchWithPuppeteer)(launchOptions);
6861
+ try {
6862
+ const page = await browser.newPage();
6863
+ await page.setContent(html, { waitUntil: "load", timeout: 15e3 });
6864
+ await page.waitForNetworkIdle({ idleTime: 500, timeout: 15e3 }).catch(() => {
6865
+ });
6866
+ await page.waitForSelector("#root > *", { timeout: 1e4 }).catch(() => {
6867
+ });
6868
+ await new Promise((r) => setTimeout(r, deps.settleMs ?? 1e3));
6869
+ const screenshot = await page.screenshot({ type: "png", fullPage: true });
6870
+ return Buffer.from(screenshot);
6871
+ } finally {
6872
+ await browser.close();
6873
+ }
6874
+ } catch (e) {
6875
+ console.warn(`[visual-eval] screenshot failed: ${e instanceof Error ? e.message : e}`);
6876
+ return null;
6877
+ }
6878
+ }
6879
+ var VISUAL_EVAL_PROMPT = `You are a visual quality evaluator for ggui \u2014 a platform where AI agents generate React UI components on demand.
6880
+
6881
+ ## Context
6882
+ The screenshot shows a generated React component built from a design system with CSS variable theming. The component was created by an LLM to fulfill a user's request. Your job is to evaluate whether the generated UI achieves the user's goal AND looks professionally designed.
6883
+
6884
+ ## Scoring Dimensions (0-100 each)
6885
+
6886
+ 1. **completeness** (25%): Does the screenshot show ALL features the user requested? Are all sections, controls, data fields, and interactive elements present? Missing features or sections = major deduction. Compare against the original request carefully.
6887
+
6888
+ 2. **layout** (25%): Is the layout well-composed? Clear sections and grouping? No overlapping elements? Proper spacing between elements? Responsive-looking? Does it look like a professional app UI, not a homework project?
6889
+
6890
+ 3. **hierarchy** (25%): Clear visual hierarchy? Headings are visually distinct from body text? Primary actions (buttons) are prominent? Information grouped logically with clear section breaks? Color and size used to guide the eye?
6891
+
6892
+ 4. **aesthetics** (25%): Professional, polished appearance? Consistent color palette? Good use of whitespace \u2014 not too sparse, not too cluttered? Cards, shadows, and borders used effectively? Does it look like something a designer would approve? Would you be comfortable showing this to a client?
6893
+
6894
+ ## Scoring Guide
6895
+ - 90-100: Production-ready. Would ship to real users. Polished layout, clear hierarchy, professional aesthetics.
6896
+ - 80-89: Good quality. Minor improvements needed (slightly tight spacing, one section could be better grouped).
6897
+ - 70-79: Acceptable but generic. Works correctly but lacks design polish or visual refinement.
6898
+ - 60-69: Below standard. Noticeable problems \u2014 cramped layout, poor hierarchy, or missing sections.
6899
+ - Below 60: Broken or fundamentally incomplete. Error messages visible, blank areas, or critical features missing.
6900
+
6901
+ ## Important
6902
+ - Check the screenshot against the "Original Request" \u2014 does it actually deliver what was asked for?
6903
+ - Error messages like "Render error" or blank white space = rendering score 0
6904
+ - A component that renders but is just a wall of text with no structure should score low on layout and hierarchy
6905
+
6906
+ Respond with ONLY a JSON object (no markdown, no explanation):
6907
+ {
6908
+ "completeness": <0-100>,
6909
+ "layout": <0-100>,
6910
+ "hierarchy": <0-100>,
6911
+ "aesthetics": <0-100>,
6912
+ "issues": [
6913
+ { "dimension": "<dimension>", "severity": "<critical|major|minor>", "description": "<what's wrong>", "fix": "<specific fix>" }
6914
+ ],
6915
+ "critique": "<2-3 sentences: what's good, what needs improvement, does it achieve the user's goal?>"
6916
+ }`;
3308
6917
  async function callMultimodalLLM(config, model, prompt, screenshot, originalPrompt) {
3309
6918
  const userPrompt = `## Original Request
3310
6919
  ${originalPrompt}
@@ -3323,7 +6932,172 @@ Evaluate the screenshot of the generated component.`;
3323
6932
  1500
3324
6933
  );
3325
6934
  }
6935
+ async function runVisualEvaluation(context, config, deps = {}) {
6936
+ const startTime = Date.now();
6937
+ const judge = deps.judge ?? callMultimodalLLM;
6938
+ const bundledCode = await bundleForRendering(
6939
+ context.compiledCode,
6940
+ config.sampleProps ?? {}
6941
+ );
6942
+ console.log(`[visual-eval] bundled: ${bundledCode.length}B (${Date.now() - startTime}ms)`);
6943
+ const html = buildRenderHTML(bundledCode, context.cssTokens);
6944
+ const model = config.model ?? getDefaultVisualModel(config.provider);
6945
+ if (config.canvases !== void 0 && config.canvases.length > 0) {
6946
+ const perCanvas = [];
6947
+ const perCanvasResults = [];
6948
+ for (const canvas of config.canvases) {
6949
+ const viewport = CANVAS_VIEWPORTS[canvas];
6950
+ const screenshot2 = await captureScreenshot(html, viewport, deps);
6951
+ if (!screenshot2) {
6952
+ console.warn(`[visual-eval] no browser available at canvas ${canvas} \u2014 skipping visual evaluation`);
6953
+ return null;
6954
+ }
6955
+ const response2 = await judge(config, model, VISUAL_EVAL_PROMPT, screenshot2, context.originalPrompt);
6956
+ const result2 = parseVisualResponse(response2.text, config.passThreshold);
6957
+ result2.inputTokens = response2.inputTokens;
6958
+ result2.outputTokens = response2.outputTokens;
6959
+ perCanvasResults.push(result2);
6960
+ perCanvas.push({
6961
+ canvas,
6962
+ viewport,
6963
+ score: result2.finalScore,
6964
+ passed: result2.passed,
6965
+ screenshotPng: screenshot2
6966
+ });
6967
+ console.log(
6968
+ `[visual-eval] canvas=${canvas} ${viewport.width}\xD7${viewport.height} score=${result2.finalScore} ${result2.passed ? "pass" : "FAIL"} | in=${response2.inputTokens} out=${response2.outputTokens}`
6969
+ );
6970
+ }
6971
+ const aggregate = aggregateCanvasResults(perCanvas, perCanvasResults);
6972
+ const elapsed2 = Date.now() - startTime;
6973
+ console.log(
6974
+ `[visual-eval] score=${aggregate.finalScore} (mean of ${perCanvas.length} canvases; ${aggregate.passed ? "every canvas passed" : `${perCanvas.filter((c) => !c.passed).length} failed`}) (${elapsed2}ms)`
6975
+ );
6976
+ return aggregate;
6977
+ }
6978
+ const screenshot = await captureScreenshot(html, config.viewport, deps);
6979
+ if (!screenshot) {
6980
+ console.warn("[visual-eval] no browser available \u2014 skipping visual evaluation");
6981
+ return null;
6982
+ }
6983
+ console.log(`[visual-eval] screenshot: ${screenshot.length}B (${Date.now() - startTime}ms)`);
6984
+ const response = await judge(
6985
+ config,
6986
+ model,
6987
+ VISUAL_EVAL_PROMPT,
6988
+ screenshot,
6989
+ context.originalPrompt
6990
+ );
6991
+ const result = parseVisualResponse(response.text, config.passThreshold);
6992
+ result.inputTokens = response.inputTokens;
6993
+ result.outputTokens = response.outputTokens;
6994
+ const elapsed = Date.now() - startTime;
6995
+ console.log(`[visual-eval] score=${result.finalScore} (${elapsed}ms) | in=${response.inputTokens} out=${response.outputTokens}`);
6996
+ return result;
6997
+ }
6998
+ function aggregateCanvasResults(perCanvas, results) {
6999
+ const n = results.length;
7000
+ const mean = (pick) => Math.round(results.reduce((sum, r) => sum + pick(r), 0) / n);
7001
+ const dimensions = {
7002
+ completeness: mean((r) => r.dimensions.completeness),
7003
+ visualPolish: mean((r) => r.dimensions.visualPolish),
7004
+ interactivity: mean((r) => r.dimensions.interactivity),
7005
+ accessibility: mean((r) => r.dimensions.accessibility),
7006
+ codeQuality: mean((r) => r.dimensions.codeQuality)
7007
+ };
7008
+ const issues = [];
7009
+ const critiques = [];
7010
+ let inputTokens = 0;
7011
+ let outputTokens = 0;
7012
+ results.forEach((r, i) => {
7013
+ const canvas = perCanvas[i].canvas;
7014
+ for (const issue of r.issues) issues.push({ ...issue, description: `[${canvas}] ${issue.description}` });
7015
+ if (r.critique) critiques.push(`${canvas}: ${r.critique}`);
7016
+ inputTokens += r.inputTokens ?? 0;
7017
+ outputTokens += r.outputTokens ?? 0;
7018
+ });
7019
+ return {
7020
+ passed: perCanvas.every((c) => c.passed),
7021
+ finalScore: mean((r) => r.finalScore),
7022
+ dimensions,
7023
+ issues,
7024
+ ...critiques.length > 0 ? { critique: critiques.join("\n") } : {},
7025
+ inputTokens,
7026
+ outputTokens,
7027
+ canvases: [...perCanvas]
7028
+ };
7029
+ }
7030
+ function summarizeVisualResult(result) {
7031
+ if (result.canvases === void 0) return void 0;
7032
+ const canvases = result.canvases.map((c) => ({
7033
+ canvas: c.canvas,
7034
+ viewport: c.viewport,
7035
+ score: c.score,
7036
+ passed: c.passed
7037
+ }));
7038
+ return { score: result.finalScore, passed: result.passed, canvases };
7039
+ }
7040
+ function parseVisualResponse(text, passThreshold) {
7041
+ const jsonMatch = text.match(/\{[\s\S]*\}/);
7042
+ if (!jsonMatch) {
7043
+ throw new Error("Visual evaluator did not return valid JSON: " + text.slice(0, 200));
7044
+ }
7045
+ const raw = JSON.parse(jsonMatch[0]);
7046
+ const completeness = raw.completeness ?? 0;
7047
+ const layout = raw.layout ?? 0;
7048
+ const hierarchy = raw.hierarchy ?? 0;
7049
+ const aesthetics = raw.aesthetics ?? 0;
7050
+ const finalScore = Math.round(
7051
+ completeness * 0.25 + layout * 0.25 + hierarchy * 0.25 + aesthetics * 0.25
7052
+ );
7053
+ const dimensions = {
7054
+ completeness,
7055
+ visualPolish: aesthetics,
7056
+ interactivity: 0,
7057
+ // can't assess interactivity from screenshot
7058
+ accessibility: 0,
7059
+ // can't assess a11y from screenshot
7060
+ codeQuality: 0
7061
+ // can't assess code from screenshot
7062
+ };
7063
+ const issues = (raw.issues || []).map((i) => ({
7064
+ dimension: i.dimension || "visual",
7065
+ severity: i.severity || "minor",
7066
+ description: i.description || "",
7067
+ fix: i.fix || ""
7068
+ }));
7069
+ return {
7070
+ passed: finalScore >= passThreshold,
7071
+ finalScore,
7072
+ dimensions,
7073
+ issues,
7074
+ critique: raw.critique
7075
+ };
7076
+ }
7077
+ function getDefaultVisualModel(provider) {
7078
+ switch (provider) {
7079
+ case "claude":
7080
+ return "claude-haiku-4-5-20251001";
7081
+ case "google":
7082
+ return "gemini-3-flash-preview";
7083
+ }
7084
+ }
7085
+ async function runVisualEval(context, config) {
7086
+ const result = await runVisualEvaluation(context, config);
7087
+ if (!result) return { issues: [] };
7088
+ const issues = (result.issues || []).map((issue) => ({
7089
+ tier: 2,
7090
+ result: issue.severity === "critical" ? "fail" : "warn",
7091
+ category: "visual",
7092
+ subcategory: issue.dimension,
7093
+ severity: issue.severity === "critical" ? "critical" : "major",
7094
+ description: issue.description,
7095
+ fix: issue.fix || ""
7096
+ }));
7097
+ const summary = summarizeVisualResult(result);
7098
+ return summary === void 0 ? { issues } : { issues, summary };
7099
+ }
3326
7100
 
3327
- export { CRITERIA, DEFAULT_EVAL_MAX_ROUNDS, DEFAULT_QUALITY_CONFIG, LLM_EVAL_STATIC_CRITERIA, MAX_EVAL_ROUNDS_HARD_LIMIT, buildCodingCriteriaSummary, buildFixPrompt, callMultimodalLLM, computeEvaluationScore, createEvaluationToolsServer, extractCompiledCode, extractCompiledCodeFromMessage, extractEvalResult, extractSourceCode, extractSourceCodeFromMessage, extractToolResultTexts, getActionableIssues, getCriteriaByPriority, getCriterionById, getEvaluatorSystemPrompt, getLLMCriteria, isBlocked, matches, notApplicableCoverage, priorityForIssue, runAxisChecks, runEvaluation, runEvaluationLoop };
7101
+ export { CANVAS_BREAKPOINTS, CANVAS_CLASSES, CANVAS_DESCRIPTORS, CANVAS_VIEWPORTS, CRITERIA, DEFAULT_EVAL_MAX_ROUNDS, DEFAULT_QUALITY_CONFIG, LLM_EVAL_STATIC_CRITERIA, MAX_EVAL_ROUNDS_HARD_LIMIT, buildCodingCriteriaSummary, buildFixPrompt, callMultimodalLLM, canvasDisplayModeForShell, canvasForRendering, canvasForViewportWidth, captureScreenshot, computeEvaluationScore, createEvaluationToolsServer, criteriaFor, describeCanvas, extractCompiledCode, extractCompiledCodeFromMessage, extractEvalResult, extractSourceCode, extractSourceCodeFromMessage, extractToolResultTexts, getActionableIssues, getCriteriaByPriority, getCriterionById, getEvaluatorSystemPrompt, getLLMCriteria, isBlocked, matches, notApplicableCoverage, priorityForIssue, resolveLaunchOptions, runAxisChecks, runEvaluation, runEvaluationLoop, runVisualEval, runVisualEvaluation, summarizeVisualResult };
3328
7102
  //# sourceMappingURL=index.js.map
3329
7103
  //# sourceMappingURL=index.js.map