token-goat 2.9.2 → 2.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/README.md +22 -50
  2. package/dist/{token-goat-chunk-UZ2NFOOZ.mjs → token-goat-chunk-3ZR4NLB3.mjs} +165 -8
  3. package/dist/{token-goat-chunk-NY4HYRSK.mjs → token-goat-chunk-5BHXZEOI.mjs} +10 -12
  4. package/dist/{token-goat-chunk-Q4LOQY44.mjs → token-goat-chunk-63XEQMNU.mjs} +137 -12
  5. package/dist/{token-goat-chunk-KKIB7O3Z.mjs → token-goat-chunk-6MU6FHE3.mjs} +463 -106
  6. package/dist/token-goat-chunk-A37V4PBF.mjs +56 -0
  7. package/dist/{token-goat-chunk-LJ3CHCTT.mjs → token-goat-chunk-CBO45DYZ.mjs} +3728 -61
  8. package/dist/{token-goat-chunk-G6XLWJWI.mjs → token-goat-chunk-E3K3BTEQ.mjs} +5 -2
  9. package/dist/{token-goat-chunk-AO2QD2AG.mjs → token-goat-chunk-EEIDFMEM.mjs} +4 -0
  10. package/dist/{token-goat-chunk-CGWACYYZ.mjs → token-goat-chunk-EPX5DWGM.mjs} +6 -1
  11. package/dist/token-goat-chunk-EQKNR7CN.mjs +23 -0
  12. package/dist/{token-goat-chunk-324QOJYZ.mjs → token-goat-chunk-EVC4TOLE.mjs} +4 -1
  13. package/dist/{token-goat-chunk-WN5T5EW5.mjs → token-goat-chunk-FQD3OB5W.mjs} +98 -2
  14. package/dist/{token-goat-chunk-VCNW7BGU.mjs → token-goat-chunk-FSC44QOH.mjs} +20 -3
  15. package/dist/{token-goat-chunk-JMUBXBG7.mjs → token-goat-chunk-GEXHIIKM.mjs} +7 -7
  16. package/dist/{token-goat-chunk-5CVKO3DA.mjs → token-goat-chunk-LYWIRYCF.mjs} +5 -2
  17. package/dist/{token-goat-chunk-LEBYARO3.mjs → token-goat-chunk-OZAEJQ7L.mjs} +9 -6
  18. package/dist/{token-goat-chunk-R4SR7MQY.mjs → token-goat-chunk-PXWBHSFB.mjs} +2 -2
  19. package/dist/{token-goat-chunk-FXAPKVRG.mjs → token-goat-chunk-US57I7GN.mjs} +26 -5
  20. package/dist/token-goat-hook.mjs +12 -7
  21. package/dist/token-goat.core.mjs +10 -7
  22. package/docs/cli.md +68 -8
  23. package/docs/security.md +6 -2
  24. package/package.json +8 -2
  25. package/dist/token-goat-chunk-AEX54RUZ.mjs +0 -11
  26. package/dist/token-goat-chunk-ZVN5WHTO.mjs +0 -23
@@ -96,15 +96,2742 @@ import {
96
96
  toDisplayPath,
97
97
  toKB,
98
98
  withFileLock
99
- } from "./token-goat-chunk-UZ2NFOOZ.mjs";
99
+ } from "./token-goat-chunk-3ZR4NLB3.mjs";
100
100
  import {
101
101
  registerReset
102
- } from "./token-goat-chunk-AO2QD2AG.mjs";
102
+ } from "./token-goat-chunk-EEIDFMEM.mjs";
103
+ import {
104
+ __commonJS,
105
+ __toESM,
106
+ init_define_import_meta_env
107
+ } from "./token-goat-chunk-A37V4PBF.mjs";
108
+
109
+ // node_modules/omggif/omggif.js
110
+ var require_omggif = __commonJS({
111
+ "node_modules/omggif/omggif.js"(exports) {
112
+ "use strict";
113
+ init_define_import_meta_env();
114
+ function GifWriter(buf, width, height, gopts) {
115
+ var p = 0;
116
+ var gopts = gopts === void 0 ? {} : gopts;
117
+ var loop_count = gopts.loop === void 0 ? null : gopts.loop;
118
+ var global_palette = gopts.palette === void 0 ? null : gopts.palette;
119
+ if (width <= 0 || height <= 0 || width > 65535 || height > 65535)
120
+ throw new Error("Width/Height invalid.");
121
+ function check_palette_and_num_colors(palette) {
122
+ var num_colors = palette.length;
123
+ if (num_colors < 2 || num_colors > 256 || num_colors & num_colors - 1) {
124
+ throw new Error(
125
+ "Invalid code/color length, must be power of 2 and 2 .. 256."
126
+ );
127
+ }
128
+ return num_colors;
129
+ }
130
+ buf[p++] = 71;
131
+ buf[p++] = 73;
132
+ buf[p++] = 70;
133
+ buf[p++] = 56;
134
+ buf[p++] = 57;
135
+ buf[p++] = 97;
136
+ var gp_num_colors_pow2 = 0;
137
+ var background = 0;
138
+ if (global_palette !== null) {
139
+ var gp_num_colors = check_palette_and_num_colors(global_palette);
140
+ while (gp_num_colors >>= 1) ++gp_num_colors_pow2;
141
+ gp_num_colors = 1 << gp_num_colors_pow2;
142
+ --gp_num_colors_pow2;
143
+ if (gopts.background !== void 0) {
144
+ background = gopts.background;
145
+ if (background >= gp_num_colors)
146
+ throw new Error("Background index out of range.");
147
+ if (background === 0)
148
+ throw new Error("Background index explicitly passed as 0.");
149
+ }
150
+ }
151
+ buf[p++] = width & 255;
152
+ buf[p++] = width >> 8 & 255;
153
+ buf[p++] = height & 255;
154
+ buf[p++] = height >> 8 & 255;
155
+ buf[p++] = (global_palette !== null ? 128 : 0) | // Global Color Table Flag.
156
+ gp_num_colors_pow2;
157
+ buf[p++] = background;
158
+ buf[p++] = 0;
159
+ if (global_palette !== null) {
160
+ for (var i = 0, il = global_palette.length; i < il; ++i) {
161
+ var rgb = global_palette[i];
162
+ buf[p++] = rgb >> 16 & 255;
163
+ buf[p++] = rgb >> 8 & 255;
164
+ buf[p++] = rgb & 255;
165
+ }
166
+ }
167
+ if (loop_count !== null) {
168
+ if (loop_count < 0 || loop_count > 65535)
169
+ throw new Error("Loop count invalid.");
170
+ buf[p++] = 33;
171
+ buf[p++] = 255;
172
+ buf[p++] = 11;
173
+ buf[p++] = 78;
174
+ buf[p++] = 69;
175
+ buf[p++] = 84;
176
+ buf[p++] = 83;
177
+ buf[p++] = 67;
178
+ buf[p++] = 65;
179
+ buf[p++] = 80;
180
+ buf[p++] = 69;
181
+ buf[p++] = 50;
182
+ buf[p++] = 46;
183
+ buf[p++] = 48;
184
+ buf[p++] = 3;
185
+ buf[p++] = 1;
186
+ buf[p++] = loop_count & 255;
187
+ buf[p++] = loop_count >> 8 & 255;
188
+ buf[p++] = 0;
189
+ }
190
+ var ended = false;
191
+ this.addFrame = function(x, y, w, h, indexed_pixels, opts) {
192
+ if (ended === true) {
193
+ --p;
194
+ ended = false;
195
+ }
196
+ opts = opts === void 0 ? {} : opts;
197
+ if (x < 0 || y < 0 || x > 65535 || y > 65535)
198
+ throw new Error("x/y invalid.");
199
+ if (w <= 0 || h <= 0 || w > 65535 || h > 65535)
200
+ throw new Error("Width/Height invalid.");
201
+ if (indexed_pixels.length < w * h)
202
+ throw new Error("Not enough pixels for the frame size.");
203
+ var using_local_palette = true;
204
+ var palette = opts.palette;
205
+ if (palette === void 0 || palette === null) {
206
+ using_local_palette = false;
207
+ palette = global_palette;
208
+ }
209
+ if (palette === void 0 || palette === null)
210
+ throw new Error("Must supply either a local or global palette.");
211
+ var num_colors = check_palette_and_num_colors(palette);
212
+ var min_code_size = 0;
213
+ while (num_colors >>= 1) ++min_code_size;
214
+ num_colors = 1 << min_code_size;
215
+ var delay = opts.delay === void 0 ? 0 : opts.delay;
216
+ var disposal = opts.disposal === void 0 ? 0 : opts.disposal;
217
+ if (disposal < 0 || disposal > 3)
218
+ throw new Error("Disposal out of range.");
219
+ var use_transparency = false;
220
+ var transparent_index = 0;
221
+ if (opts.transparent !== void 0 && opts.transparent !== null) {
222
+ use_transparency = true;
223
+ transparent_index = opts.transparent;
224
+ if (transparent_index < 0 || transparent_index >= num_colors)
225
+ throw new Error("Transparent color index.");
226
+ }
227
+ if (disposal !== 0 || use_transparency || delay !== 0) {
228
+ buf[p++] = 33;
229
+ buf[p++] = 249;
230
+ buf[p++] = 4;
231
+ buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0);
232
+ buf[p++] = delay & 255;
233
+ buf[p++] = delay >> 8 & 255;
234
+ buf[p++] = transparent_index;
235
+ buf[p++] = 0;
236
+ }
237
+ buf[p++] = 44;
238
+ buf[p++] = x & 255;
239
+ buf[p++] = x >> 8 & 255;
240
+ buf[p++] = y & 255;
241
+ buf[p++] = y >> 8 & 255;
242
+ buf[p++] = w & 255;
243
+ buf[p++] = w >> 8 & 255;
244
+ buf[p++] = h & 255;
245
+ buf[p++] = h >> 8 & 255;
246
+ buf[p++] = using_local_palette === true ? 128 | min_code_size - 1 : 0;
247
+ if (using_local_palette === true) {
248
+ for (var i2 = 0, il2 = palette.length; i2 < il2; ++i2) {
249
+ var rgb2 = palette[i2];
250
+ buf[p++] = rgb2 >> 16 & 255;
251
+ buf[p++] = rgb2 >> 8 & 255;
252
+ buf[p++] = rgb2 & 255;
253
+ }
254
+ }
255
+ p = GifWriterOutputLZWCodeStream(
256
+ buf,
257
+ p,
258
+ min_code_size < 2 ? 2 : min_code_size,
259
+ indexed_pixels
260
+ );
261
+ return p;
262
+ };
263
+ this.end = function() {
264
+ if (ended === false) {
265
+ buf[p++] = 59;
266
+ ended = true;
267
+ }
268
+ return p;
269
+ };
270
+ this.getOutputBuffer = function() {
271
+ return buf;
272
+ };
273
+ this.setOutputBuffer = function(v) {
274
+ buf = v;
275
+ };
276
+ this.getOutputBufferPosition = function() {
277
+ return p;
278
+ };
279
+ this.setOutputBufferPosition = function(v) {
280
+ p = v;
281
+ };
282
+ }
283
+ function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {
284
+ buf[p++] = min_code_size;
285
+ var cur_subblock = p++;
286
+ var clear_code = 1 << min_code_size;
287
+ var code_mask = clear_code - 1;
288
+ var eoi_code = clear_code + 1;
289
+ var next_code = eoi_code + 1;
290
+ var cur_code_size = min_code_size + 1;
291
+ var cur_shift = 0;
292
+ var cur = 0;
293
+ function emit_bytes_to_buffer(bit_block_size) {
294
+ while (cur_shift >= bit_block_size) {
295
+ buf[p++] = cur & 255;
296
+ cur >>= 8;
297
+ cur_shift -= 8;
298
+ if (p === cur_subblock + 256) {
299
+ buf[cur_subblock] = 255;
300
+ cur_subblock = p++;
301
+ }
302
+ }
303
+ }
304
+ function emit_code(c) {
305
+ cur |= c << cur_shift;
306
+ cur_shift += cur_code_size;
307
+ emit_bytes_to_buffer(8);
308
+ }
309
+ var ib_code = index_stream[0] & code_mask;
310
+ var code_table = {};
311
+ emit_code(clear_code);
312
+ for (var i = 1, il = index_stream.length; i < il; ++i) {
313
+ var k = index_stream[i] & code_mask;
314
+ var cur_key = ib_code << 8 | k;
315
+ var cur_code = code_table[cur_key];
316
+ if (cur_code === void 0) {
317
+ cur |= ib_code << cur_shift;
318
+ cur_shift += cur_code_size;
319
+ while (cur_shift >= 8) {
320
+ buf[p++] = cur & 255;
321
+ cur >>= 8;
322
+ cur_shift -= 8;
323
+ if (p === cur_subblock + 256) {
324
+ buf[cur_subblock] = 255;
325
+ cur_subblock = p++;
326
+ }
327
+ }
328
+ if (next_code === 4096) {
329
+ emit_code(clear_code);
330
+ next_code = eoi_code + 1;
331
+ cur_code_size = min_code_size + 1;
332
+ code_table = {};
333
+ } else {
334
+ if (next_code >= 1 << cur_code_size) ++cur_code_size;
335
+ code_table[cur_key] = next_code++;
336
+ }
337
+ ib_code = k;
338
+ } else {
339
+ ib_code = cur_code;
340
+ }
341
+ }
342
+ emit_code(ib_code);
343
+ emit_code(eoi_code);
344
+ emit_bytes_to_buffer(1);
345
+ if (cur_subblock + 1 === p) {
346
+ buf[cur_subblock] = 0;
347
+ } else {
348
+ buf[cur_subblock] = p - cur_subblock - 1;
349
+ buf[p++] = 0;
350
+ }
351
+ return p;
352
+ }
353
+ function GifReader(buf) {
354
+ var p = 0;
355
+ if (buf[p++] !== 71 || buf[p++] !== 73 || buf[p++] !== 70 || buf[p++] !== 56 || (buf[p++] + 1 & 253) !== 56 || buf[p++] !== 97) {
356
+ throw new Error("Invalid GIF 87a/89a header.");
357
+ }
358
+ var width = buf[p++] | buf[p++] << 8;
359
+ var height = buf[p++] | buf[p++] << 8;
360
+ var pf0 = buf[p++];
361
+ var global_palette_flag = pf0 >> 7;
362
+ var num_global_colors_pow2 = pf0 & 7;
363
+ var num_global_colors = 1 << num_global_colors_pow2 + 1;
364
+ var background = buf[p++];
365
+ buf[p++];
366
+ var global_palette_offset = null;
367
+ var global_palette_size = null;
368
+ if (global_palette_flag) {
369
+ global_palette_offset = p;
370
+ global_palette_size = num_global_colors;
371
+ p += num_global_colors * 3;
372
+ }
373
+ var no_eof = true;
374
+ var frames = [];
375
+ var delay = 0;
376
+ var transparent_index = null;
377
+ var disposal = 0;
378
+ var loop_count = null;
379
+ this.width = width;
380
+ this.height = height;
381
+ while (no_eof && p < buf.length) {
382
+ switch (buf[p++]) {
383
+ case 33:
384
+ switch (buf[p++]) {
385
+ case 255:
386
+ if (buf[p] !== 11 || // 21 FF already read, check block size.
387
+ // NETSCAPE2.0
388
+ buf[p + 1] == 78 && buf[p + 2] == 69 && buf[p + 3] == 84 && buf[p + 4] == 83 && buf[p + 5] == 67 && buf[p + 6] == 65 && buf[p + 7] == 80 && buf[p + 8] == 69 && buf[p + 9] == 50 && buf[p + 10] == 46 && buf[p + 11] == 48 && // Sub-block
389
+ buf[p + 12] == 3 && buf[p + 13] == 1 && buf[p + 16] == 0) {
390
+ p += 14;
391
+ loop_count = buf[p++] | buf[p++] << 8;
392
+ p++;
393
+ } else {
394
+ p += 12;
395
+ while (true) {
396
+ var block_size = buf[p++];
397
+ if (!(block_size >= 0)) throw Error("Invalid block size");
398
+ if (block_size === 0) break;
399
+ p += block_size;
400
+ }
401
+ }
402
+ break;
403
+ case 249:
404
+ if (buf[p++] !== 4 || buf[p + 4] !== 0)
405
+ throw new Error("Invalid graphics extension block.");
406
+ var pf1 = buf[p++];
407
+ delay = buf[p++] | buf[p++] << 8;
408
+ transparent_index = buf[p++];
409
+ if ((pf1 & 1) === 0) transparent_index = null;
410
+ disposal = pf1 >> 2 & 7;
411
+ p++;
412
+ break;
413
+ case 254:
414
+ while (true) {
415
+ var block_size = buf[p++];
416
+ if (!(block_size >= 0)) throw Error("Invalid block size");
417
+ if (block_size === 0) break;
418
+ p += block_size;
419
+ }
420
+ break;
421
+ default:
422
+ throw new Error(
423
+ "Unknown graphic control label: 0x" + buf[p - 1].toString(16)
424
+ );
425
+ }
426
+ break;
427
+ case 44:
428
+ var x = buf[p++] | buf[p++] << 8;
429
+ var y = buf[p++] | buf[p++] << 8;
430
+ var w = buf[p++] | buf[p++] << 8;
431
+ var h = buf[p++] | buf[p++] << 8;
432
+ var pf2 = buf[p++];
433
+ var local_palette_flag = pf2 >> 7;
434
+ var interlace_flag = pf2 >> 6 & 1;
435
+ var num_local_colors_pow2 = pf2 & 7;
436
+ var num_local_colors = 1 << num_local_colors_pow2 + 1;
437
+ var palette_offset = global_palette_offset;
438
+ var palette_size = global_palette_size;
439
+ var has_local_palette = false;
440
+ if (local_palette_flag) {
441
+ var has_local_palette = true;
442
+ palette_offset = p;
443
+ palette_size = num_local_colors;
444
+ p += num_local_colors * 3;
445
+ }
446
+ var data_offset = p;
447
+ p++;
448
+ while (true) {
449
+ var block_size = buf[p++];
450
+ if (!(block_size >= 0)) throw Error("Invalid block size");
451
+ if (block_size === 0) break;
452
+ p += block_size;
453
+ }
454
+ frames.push({
455
+ x,
456
+ y,
457
+ width: w,
458
+ height: h,
459
+ has_local_palette,
460
+ palette_offset,
461
+ palette_size,
462
+ data_offset,
463
+ data_length: p - data_offset,
464
+ transparent_index,
465
+ interlaced: !!interlace_flag,
466
+ delay,
467
+ disposal
468
+ });
469
+ break;
470
+ case 59:
471
+ no_eof = false;
472
+ break;
473
+ default:
474
+ throw new Error("Unknown gif block: 0x" + buf[p - 1].toString(16));
475
+ break;
476
+ }
477
+ }
478
+ this.numFrames = function() {
479
+ return frames.length;
480
+ };
481
+ this.loopCount = function() {
482
+ return loop_count;
483
+ };
484
+ this.frameInfo = function(frame_num) {
485
+ if (frame_num < 0 || frame_num >= frames.length)
486
+ throw new Error("Frame index out of range.");
487
+ return frames[frame_num];
488
+ };
489
+ this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {
490
+ var frame = this.frameInfo(frame_num);
491
+ var num_pixels = frame.width * frame.height;
492
+ var index_stream = new Uint8Array(num_pixels);
493
+ GifReaderLZWOutputIndexStream(
494
+ buf,
495
+ frame.data_offset,
496
+ index_stream,
497
+ num_pixels
498
+ );
499
+ var palette_offset2 = frame.palette_offset;
500
+ var trans = frame.transparent_index;
501
+ if (trans === null) trans = 256;
502
+ var framewidth = frame.width;
503
+ var framestride = width - framewidth;
504
+ var xleft = framewidth;
505
+ var opbeg = (frame.y * width + frame.x) * 4;
506
+ var opend = ((frame.y + frame.height) * width + frame.x) * 4;
507
+ var op = opbeg;
508
+ var scanstride = framestride * 4;
509
+ if (frame.interlaced === true) {
510
+ scanstride += width * 4 * 7;
511
+ }
512
+ var interlaceskip = 8;
513
+ for (var i = 0, il = index_stream.length; i < il; ++i) {
514
+ var index = index_stream[i];
515
+ if (xleft === 0) {
516
+ op += scanstride;
517
+ xleft = framewidth;
518
+ if (op >= opend) {
519
+ scanstride = framestride * 4 + width * 4 * (interlaceskip - 1);
520
+ op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
521
+ interlaceskip >>= 1;
522
+ }
523
+ }
524
+ if (index === trans) {
525
+ op += 4;
526
+ } else {
527
+ var r = buf[palette_offset2 + index * 3];
528
+ var g = buf[palette_offset2 + index * 3 + 1];
529
+ var b = buf[palette_offset2 + index * 3 + 2];
530
+ pixels[op++] = b;
531
+ pixels[op++] = g;
532
+ pixels[op++] = r;
533
+ pixels[op++] = 255;
534
+ }
535
+ --xleft;
536
+ }
537
+ };
538
+ this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {
539
+ var frame = this.frameInfo(frame_num);
540
+ var num_pixels = frame.width * frame.height;
541
+ var index_stream = new Uint8Array(num_pixels);
542
+ GifReaderLZWOutputIndexStream(
543
+ buf,
544
+ frame.data_offset,
545
+ index_stream,
546
+ num_pixels
547
+ );
548
+ var palette_offset2 = frame.palette_offset;
549
+ var trans = frame.transparent_index;
550
+ if (trans === null) trans = 256;
551
+ var framewidth = frame.width;
552
+ var framestride = width - framewidth;
553
+ var xleft = framewidth;
554
+ var opbeg = (frame.y * width + frame.x) * 4;
555
+ var opend = ((frame.y + frame.height) * width + frame.x) * 4;
556
+ var op = opbeg;
557
+ var scanstride = framestride * 4;
558
+ if (frame.interlaced === true) {
559
+ scanstride += width * 4 * 7;
560
+ }
561
+ var interlaceskip = 8;
562
+ for (var i = 0, il = index_stream.length; i < il; ++i) {
563
+ var index = index_stream[i];
564
+ if (xleft === 0) {
565
+ op += scanstride;
566
+ xleft = framewidth;
567
+ if (op >= opend) {
568
+ scanstride = framestride * 4 + width * 4 * (interlaceskip - 1);
569
+ op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
570
+ interlaceskip >>= 1;
571
+ }
572
+ }
573
+ if (index === trans) {
574
+ op += 4;
575
+ } else {
576
+ var r = buf[palette_offset2 + index * 3];
577
+ var g = buf[palette_offset2 + index * 3 + 1];
578
+ var b = buf[palette_offset2 + index * 3 + 2];
579
+ pixels[op++] = r;
580
+ pixels[op++] = g;
581
+ pixels[op++] = b;
582
+ pixels[op++] = 255;
583
+ }
584
+ --xleft;
585
+ }
586
+ };
587
+ }
588
+ function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {
589
+ var min_code_size = code_stream[p++];
590
+ var clear_code = 1 << min_code_size;
591
+ var eoi_code = clear_code + 1;
592
+ var next_code = eoi_code + 1;
593
+ var cur_code_size = min_code_size + 1;
594
+ var code_mask = (1 << cur_code_size) - 1;
595
+ var cur_shift = 0;
596
+ var cur = 0;
597
+ var op = 0;
598
+ var subblock_size = code_stream[p++];
599
+ var code_table = new Int32Array(4096);
600
+ var prev_code = null;
601
+ while (true) {
602
+ while (cur_shift < 16) {
603
+ if (subblock_size === 0) break;
604
+ cur |= code_stream[p++] << cur_shift;
605
+ cur_shift += 8;
606
+ if (subblock_size === 1) {
607
+ subblock_size = code_stream[p++];
608
+ } else {
609
+ --subblock_size;
610
+ }
611
+ }
612
+ if (cur_shift < cur_code_size)
613
+ break;
614
+ var code = cur & code_mask;
615
+ cur >>= cur_code_size;
616
+ cur_shift -= cur_code_size;
617
+ if (code === clear_code) {
618
+ next_code = eoi_code + 1;
619
+ cur_code_size = min_code_size + 1;
620
+ code_mask = (1 << cur_code_size) - 1;
621
+ prev_code = null;
622
+ continue;
623
+ } else if (code === eoi_code) {
624
+ break;
625
+ }
626
+ var chase_code = code < next_code ? code : prev_code;
627
+ var chase_length = 0;
628
+ var chase = chase_code;
629
+ while (chase > clear_code) {
630
+ chase = code_table[chase] >> 8;
631
+ ++chase_length;
632
+ }
633
+ var k = chase;
634
+ var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
635
+ if (op_end > output_length) {
636
+ console.log("Warning, gif stream longer than expected.");
637
+ return;
638
+ }
639
+ output[op++] = k;
640
+ op += chase_length;
641
+ var b = op;
642
+ if (chase_code !== code)
643
+ output[op++] = k;
644
+ chase = chase_code;
645
+ while (chase_length--) {
646
+ chase = code_table[chase];
647
+ output[--b] = chase & 255;
648
+ chase >>= 8;
649
+ }
650
+ if (prev_code !== null && next_code < 4096) {
651
+ code_table[next_code++] = prev_code << 8 | k;
652
+ if (next_code >= code_mask + 1 && cur_code_size < 12) {
653
+ ++cur_code_size;
654
+ code_mask = code_mask << 1 | 1;
655
+ }
656
+ }
657
+ prev_code = code;
658
+ }
659
+ if (op !== output_length) {
660
+ console.log("Warning, gif stream shorter than expected.");
661
+ }
662
+ return output;
663
+ }
664
+ try {
665
+ exports.GifWriter = GifWriter;
666
+ exports.GifReader = GifReader;
667
+ } catch (e) {
668
+ }
669
+ }
670
+ });
671
+
672
+ // node_modules/jpeg-js/lib/encoder.js
673
+ var require_encoder = __commonJS({
674
+ "node_modules/jpeg-js/lib/encoder.js"(exports, module) {
675
+ init_define_import_meta_env();
676
+ var btoa = btoa || function(buf) {
677
+ return Buffer.from(buf).toString("base64");
678
+ };
679
+ function JPEGEncoder(quality) {
680
+ var self = this;
681
+ var fround = Math.round;
682
+ var ffloor = Math.floor;
683
+ var YTable = new Array(64);
684
+ var UVTable = new Array(64);
685
+ var fdtbl_Y = new Array(64);
686
+ var fdtbl_UV = new Array(64);
687
+ var YDC_HT;
688
+ var UVDC_HT;
689
+ var YAC_HT;
690
+ var UVAC_HT;
691
+ var bitcode = new Array(65535);
692
+ var category = new Array(65535);
693
+ var outputfDCTQuant = new Array(64);
694
+ var DU = new Array(64);
695
+ var byteout = [];
696
+ var bytenew = 0;
697
+ var bytepos = 7;
698
+ var YDU = new Array(64);
699
+ var UDU = new Array(64);
700
+ var VDU = new Array(64);
701
+ var clt = new Array(256);
702
+ var RGB_YUV_TABLE = new Array(2048);
703
+ var currentQuality;
704
+ var ZigZag = [
705
+ 0,
706
+ 1,
707
+ 5,
708
+ 6,
709
+ 14,
710
+ 15,
711
+ 27,
712
+ 28,
713
+ 2,
714
+ 4,
715
+ 7,
716
+ 13,
717
+ 16,
718
+ 26,
719
+ 29,
720
+ 42,
721
+ 3,
722
+ 8,
723
+ 12,
724
+ 17,
725
+ 25,
726
+ 30,
727
+ 41,
728
+ 43,
729
+ 9,
730
+ 11,
731
+ 18,
732
+ 24,
733
+ 31,
734
+ 40,
735
+ 44,
736
+ 53,
737
+ 10,
738
+ 19,
739
+ 23,
740
+ 32,
741
+ 39,
742
+ 45,
743
+ 52,
744
+ 54,
745
+ 20,
746
+ 22,
747
+ 33,
748
+ 38,
749
+ 46,
750
+ 51,
751
+ 55,
752
+ 60,
753
+ 21,
754
+ 34,
755
+ 37,
756
+ 47,
757
+ 50,
758
+ 56,
759
+ 59,
760
+ 61,
761
+ 35,
762
+ 36,
763
+ 48,
764
+ 49,
765
+ 57,
766
+ 58,
767
+ 62,
768
+ 63
769
+ ];
770
+ var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
771
+ var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
772
+ var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125];
773
+ var std_ac_luminance_values = [
774
+ 1,
775
+ 2,
776
+ 3,
777
+ 0,
778
+ 4,
779
+ 17,
780
+ 5,
781
+ 18,
782
+ 33,
783
+ 49,
784
+ 65,
785
+ 6,
786
+ 19,
787
+ 81,
788
+ 97,
789
+ 7,
790
+ 34,
791
+ 113,
792
+ 20,
793
+ 50,
794
+ 129,
795
+ 145,
796
+ 161,
797
+ 8,
798
+ 35,
799
+ 66,
800
+ 177,
801
+ 193,
802
+ 21,
803
+ 82,
804
+ 209,
805
+ 240,
806
+ 36,
807
+ 51,
808
+ 98,
809
+ 114,
810
+ 130,
811
+ 9,
812
+ 10,
813
+ 22,
814
+ 23,
815
+ 24,
816
+ 25,
817
+ 26,
818
+ 37,
819
+ 38,
820
+ 39,
821
+ 40,
822
+ 41,
823
+ 42,
824
+ 52,
825
+ 53,
826
+ 54,
827
+ 55,
828
+ 56,
829
+ 57,
830
+ 58,
831
+ 67,
832
+ 68,
833
+ 69,
834
+ 70,
835
+ 71,
836
+ 72,
837
+ 73,
838
+ 74,
839
+ 83,
840
+ 84,
841
+ 85,
842
+ 86,
843
+ 87,
844
+ 88,
845
+ 89,
846
+ 90,
847
+ 99,
848
+ 100,
849
+ 101,
850
+ 102,
851
+ 103,
852
+ 104,
853
+ 105,
854
+ 106,
855
+ 115,
856
+ 116,
857
+ 117,
858
+ 118,
859
+ 119,
860
+ 120,
861
+ 121,
862
+ 122,
863
+ 131,
864
+ 132,
865
+ 133,
866
+ 134,
867
+ 135,
868
+ 136,
869
+ 137,
870
+ 138,
871
+ 146,
872
+ 147,
873
+ 148,
874
+ 149,
875
+ 150,
876
+ 151,
877
+ 152,
878
+ 153,
879
+ 154,
880
+ 162,
881
+ 163,
882
+ 164,
883
+ 165,
884
+ 166,
885
+ 167,
886
+ 168,
887
+ 169,
888
+ 170,
889
+ 178,
890
+ 179,
891
+ 180,
892
+ 181,
893
+ 182,
894
+ 183,
895
+ 184,
896
+ 185,
897
+ 186,
898
+ 194,
899
+ 195,
900
+ 196,
901
+ 197,
902
+ 198,
903
+ 199,
904
+ 200,
905
+ 201,
906
+ 202,
907
+ 210,
908
+ 211,
909
+ 212,
910
+ 213,
911
+ 214,
912
+ 215,
913
+ 216,
914
+ 217,
915
+ 218,
916
+ 225,
917
+ 226,
918
+ 227,
919
+ 228,
920
+ 229,
921
+ 230,
922
+ 231,
923
+ 232,
924
+ 233,
925
+ 234,
926
+ 241,
927
+ 242,
928
+ 243,
929
+ 244,
930
+ 245,
931
+ 246,
932
+ 247,
933
+ 248,
934
+ 249,
935
+ 250
936
+ ];
937
+ var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
938
+ var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
939
+ var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119];
940
+ var std_ac_chrominance_values = [
941
+ 0,
942
+ 1,
943
+ 2,
944
+ 3,
945
+ 17,
946
+ 4,
947
+ 5,
948
+ 33,
949
+ 49,
950
+ 6,
951
+ 18,
952
+ 65,
953
+ 81,
954
+ 7,
955
+ 97,
956
+ 113,
957
+ 19,
958
+ 34,
959
+ 50,
960
+ 129,
961
+ 8,
962
+ 20,
963
+ 66,
964
+ 145,
965
+ 161,
966
+ 177,
967
+ 193,
968
+ 9,
969
+ 35,
970
+ 51,
971
+ 82,
972
+ 240,
973
+ 21,
974
+ 98,
975
+ 114,
976
+ 209,
977
+ 10,
978
+ 22,
979
+ 36,
980
+ 52,
981
+ 225,
982
+ 37,
983
+ 241,
984
+ 23,
985
+ 24,
986
+ 25,
987
+ 26,
988
+ 38,
989
+ 39,
990
+ 40,
991
+ 41,
992
+ 42,
993
+ 53,
994
+ 54,
995
+ 55,
996
+ 56,
997
+ 57,
998
+ 58,
999
+ 67,
1000
+ 68,
1001
+ 69,
1002
+ 70,
1003
+ 71,
1004
+ 72,
1005
+ 73,
1006
+ 74,
1007
+ 83,
1008
+ 84,
1009
+ 85,
1010
+ 86,
1011
+ 87,
1012
+ 88,
1013
+ 89,
1014
+ 90,
1015
+ 99,
1016
+ 100,
1017
+ 101,
1018
+ 102,
1019
+ 103,
1020
+ 104,
1021
+ 105,
1022
+ 106,
1023
+ 115,
1024
+ 116,
1025
+ 117,
1026
+ 118,
1027
+ 119,
1028
+ 120,
1029
+ 121,
1030
+ 122,
1031
+ 130,
1032
+ 131,
1033
+ 132,
1034
+ 133,
1035
+ 134,
1036
+ 135,
1037
+ 136,
1038
+ 137,
1039
+ 138,
1040
+ 146,
1041
+ 147,
1042
+ 148,
1043
+ 149,
1044
+ 150,
1045
+ 151,
1046
+ 152,
1047
+ 153,
1048
+ 154,
1049
+ 162,
1050
+ 163,
1051
+ 164,
1052
+ 165,
1053
+ 166,
1054
+ 167,
1055
+ 168,
1056
+ 169,
1057
+ 170,
1058
+ 178,
1059
+ 179,
1060
+ 180,
1061
+ 181,
1062
+ 182,
1063
+ 183,
1064
+ 184,
1065
+ 185,
1066
+ 186,
1067
+ 194,
1068
+ 195,
1069
+ 196,
1070
+ 197,
1071
+ 198,
1072
+ 199,
1073
+ 200,
1074
+ 201,
1075
+ 202,
1076
+ 210,
1077
+ 211,
1078
+ 212,
1079
+ 213,
1080
+ 214,
1081
+ 215,
1082
+ 216,
1083
+ 217,
1084
+ 218,
1085
+ 226,
1086
+ 227,
1087
+ 228,
1088
+ 229,
1089
+ 230,
1090
+ 231,
1091
+ 232,
1092
+ 233,
1093
+ 234,
1094
+ 242,
1095
+ 243,
1096
+ 244,
1097
+ 245,
1098
+ 246,
1099
+ 247,
1100
+ 248,
1101
+ 249,
1102
+ 250
1103
+ ];
1104
+ function initQuantTables(sf) {
1105
+ var YQT = [
1106
+ 16,
1107
+ 11,
1108
+ 10,
1109
+ 16,
1110
+ 24,
1111
+ 40,
1112
+ 51,
1113
+ 61,
1114
+ 12,
1115
+ 12,
1116
+ 14,
1117
+ 19,
1118
+ 26,
1119
+ 58,
1120
+ 60,
1121
+ 55,
1122
+ 14,
1123
+ 13,
1124
+ 16,
1125
+ 24,
1126
+ 40,
1127
+ 57,
1128
+ 69,
1129
+ 56,
1130
+ 14,
1131
+ 17,
1132
+ 22,
1133
+ 29,
1134
+ 51,
1135
+ 87,
1136
+ 80,
1137
+ 62,
1138
+ 18,
1139
+ 22,
1140
+ 37,
1141
+ 56,
1142
+ 68,
1143
+ 109,
1144
+ 103,
1145
+ 77,
1146
+ 24,
1147
+ 35,
1148
+ 55,
1149
+ 64,
1150
+ 81,
1151
+ 104,
1152
+ 113,
1153
+ 92,
1154
+ 49,
1155
+ 64,
1156
+ 78,
1157
+ 87,
1158
+ 103,
1159
+ 121,
1160
+ 120,
1161
+ 101,
1162
+ 72,
1163
+ 92,
1164
+ 95,
1165
+ 98,
1166
+ 112,
1167
+ 100,
1168
+ 103,
1169
+ 99
1170
+ ];
1171
+ for (var i = 0; i < 64; i++) {
1172
+ var t = ffloor((YQT[i] * sf + 50) / 100);
1173
+ if (t < 1) {
1174
+ t = 1;
1175
+ } else if (t > 255) {
1176
+ t = 255;
1177
+ }
1178
+ YTable[ZigZag[i]] = t;
1179
+ }
1180
+ var UVQT = [
1181
+ 17,
1182
+ 18,
1183
+ 24,
1184
+ 47,
1185
+ 99,
1186
+ 99,
1187
+ 99,
1188
+ 99,
1189
+ 18,
1190
+ 21,
1191
+ 26,
1192
+ 66,
1193
+ 99,
1194
+ 99,
1195
+ 99,
1196
+ 99,
1197
+ 24,
1198
+ 26,
1199
+ 56,
1200
+ 99,
1201
+ 99,
1202
+ 99,
1203
+ 99,
1204
+ 99,
1205
+ 47,
1206
+ 66,
1207
+ 99,
1208
+ 99,
1209
+ 99,
1210
+ 99,
1211
+ 99,
1212
+ 99,
1213
+ 99,
1214
+ 99,
1215
+ 99,
1216
+ 99,
1217
+ 99,
1218
+ 99,
1219
+ 99,
1220
+ 99,
1221
+ 99,
1222
+ 99,
1223
+ 99,
1224
+ 99,
1225
+ 99,
1226
+ 99,
1227
+ 99,
1228
+ 99,
1229
+ 99,
1230
+ 99,
1231
+ 99,
1232
+ 99,
1233
+ 99,
1234
+ 99,
1235
+ 99,
1236
+ 99,
1237
+ 99,
1238
+ 99,
1239
+ 99,
1240
+ 99,
1241
+ 99,
1242
+ 99,
1243
+ 99,
1244
+ 99
1245
+ ];
1246
+ for (var j = 0; j < 64; j++) {
1247
+ var u = ffloor((UVQT[j] * sf + 50) / 100);
1248
+ if (u < 1) {
1249
+ u = 1;
1250
+ } else if (u > 255) {
1251
+ u = 255;
1252
+ }
1253
+ UVTable[ZigZag[j]] = u;
1254
+ }
1255
+ var aasf = [
1256
+ 1,
1257
+ 1.387039845,
1258
+ 1.306562965,
1259
+ 1.175875602,
1260
+ 1,
1261
+ 0.785694958,
1262
+ 0.5411961,
1263
+ 0.275899379
1264
+ ];
1265
+ var k = 0;
1266
+ for (var row = 0; row < 8; row++) {
1267
+ for (var col = 0; col < 8; col++) {
1268
+ fdtbl_Y[k] = 1 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8);
1269
+ fdtbl_UV[k] = 1 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8);
1270
+ k++;
1271
+ }
1272
+ }
1273
+ }
1274
+ function computeHuffmanTbl(nrcodes, std_table) {
1275
+ var codevalue = 0;
1276
+ var pos_in_table = 0;
1277
+ var HT = new Array();
1278
+ for (var k = 1; k <= 16; k++) {
1279
+ for (var j = 1; j <= nrcodes[k]; j++) {
1280
+ HT[std_table[pos_in_table]] = [];
1281
+ HT[std_table[pos_in_table]][0] = codevalue;
1282
+ HT[std_table[pos_in_table]][1] = k;
1283
+ pos_in_table++;
1284
+ codevalue++;
1285
+ }
1286
+ codevalue *= 2;
1287
+ }
1288
+ return HT;
1289
+ }
1290
+ function initHuffmanTbl() {
1291
+ YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values);
1292
+ UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values);
1293
+ YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values);
1294
+ UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values);
1295
+ }
1296
+ function initCategoryNumber() {
1297
+ var nrlower = 1;
1298
+ var nrupper = 2;
1299
+ for (var cat = 1; cat <= 15; cat++) {
1300
+ for (var nr = nrlower; nr < nrupper; nr++) {
1301
+ category[32767 + nr] = cat;
1302
+ bitcode[32767 + nr] = [];
1303
+ bitcode[32767 + nr][1] = cat;
1304
+ bitcode[32767 + nr][0] = nr;
1305
+ }
1306
+ for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) {
1307
+ category[32767 + nrneg] = cat;
1308
+ bitcode[32767 + nrneg] = [];
1309
+ bitcode[32767 + nrneg][1] = cat;
1310
+ bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg;
1311
+ }
1312
+ nrlower <<= 1;
1313
+ nrupper <<= 1;
1314
+ }
1315
+ }
1316
+ function initRGBYUVTable() {
1317
+ for (var i = 0; i < 256; i++) {
1318
+ RGB_YUV_TABLE[i] = 19595 * i;
1319
+ RGB_YUV_TABLE[i + 256 >> 0] = 38470 * i;
1320
+ RGB_YUV_TABLE[i + 512 >> 0] = 7471 * i + 32768;
1321
+ RGB_YUV_TABLE[i + 768 >> 0] = -11059 * i;
1322
+ RGB_YUV_TABLE[i + 1024 >> 0] = -21709 * i;
1323
+ RGB_YUV_TABLE[i + 1280 >> 0] = 32768 * i + 8421375;
1324
+ RGB_YUV_TABLE[i + 1536 >> 0] = -27439 * i;
1325
+ RGB_YUV_TABLE[i + 1792 >> 0] = -5329 * i;
1326
+ }
1327
+ }
1328
+ function writeBits(bs) {
1329
+ var value = bs[0];
1330
+ var posval = bs[1] - 1;
1331
+ while (posval >= 0) {
1332
+ if (value & 1 << posval) {
1333
+ bytenew |= 1 << bytepos;
1334
+ }
1335
+ posval--;
1336
+ bytepos--;
1337
+ if (bytepos < 0) {
1338
+ if (bytenew == 255) {
1339
+ writeByte(255);
1340
+ writeByte(0);
1341
+ } else {
1342
+ writeByte(bytenew);
1343
+ }
1344
+ bytepos = 7;
1345
+ bytenew = 0;
1346
+ }
1347
+ }
1348
+ }
1349
+ function writeByte(value) {
1350
+ byteout.push(value);
1351
+ }
1352
+ function writeWord(value) {
1353
+ writeByte(value >> 8 & 255);
1354
+ writeByte(value & 255);
1355
+ }
1356
+ function fDCTQuant(data, fdtbl) {
1357
+ var d0, d1, d2, d3, d4, d5, d6, d7;
1358
+ var dataOff = 0;
1359
+ var i;
1360
+ var I8 = 8;
1361
+ var I64 = 64;
1362
+ for (i = 0; i < I8; ++i) {
1363
+ d0 = data[dataOff];
1364
+ d1 = data[dataOff + 1];
1365
+ d2 = data[dataOff + 2];
1366
+ d3 = data[dataOff + 3];
1367
+ d4 = data[dataOff + 4];
1368
+ d5 = data[dataOff + 5];
1369
+ d6 = data[dataOff + 6];
1370
+ d7 = data[dataOff + 7];
1371
+ var tmp0 = d0 + d7;
1372
+ var tmp7 = d0 - d7;
1373
+ var tmp1 = d1 + d6;
1374
+ var tmp6 = d1 - d6;
1375
+ var tmp2 = d2 + d5;
1376
+ var tmp5 = d2 - d5;
1377
+ var tmp3 = d3 + d4;
1378
+ var tmp4 = d3 - d4;
1379
+ var tmp10 = tmp0 + tmp3;
1380
+ var tmp13 = tmp0 - tmp3;
1381
+ var tmp11 = tmp1 + tmp2;
1382
+ var tmp12 = tmp1 - tmp2;
1383
+ data[dataOff] = tmp10 + tmp11;
1384
+ data[dataOff + 4] = tmp10 - tmp11;
1385
+ var z1 = (tmp12 + tmp13) * 0.707106781;
1386
+ data[dataOff + 2] = tmp13 + z1;
1387
+ data[dataOff + 6] = tmp13 - z1;
1388
+ tmp10 = tmp4 + tmp5;
1389
+ tmp11 = tmp5 + tmp6;
1390
+ tmp12 = tmp6 + tmp7;
1391
+ var z5 = (tmp10 - tmp12) * 0.382683433;
1392
+ var z2 = 0.5411961 * tmp10 + z5;
1393
+ var z4 = 1.306562965 * tmp12 + z5;
1394
+ var z3 = tmp11 * 0.707106781;
1395
+ var z11 = tmp7 + z3;
1396
+ var z13 = tmp7 - z3;
1397
+ data[dataOff + 5] = z13 + z2;
1398
+ data[dataOff + 3] = z13 - z2;
1399
+ data[dataOff + 1] = z11 + z4;
1400
+ data[dataOff + 7] = z11 - z4;
1401
+ dataOff += 8;
1402
+ }
1403
+ dataOff = 0;
1404
+ for (i = 0; i < I8; ++i) {
1405
+ d0 = data[dataOff];
1406
+ d1 = data[dataOff + 8];
1407
+ d2 = data[dataOff + 16];
1408
+ d3 = data[dataOff + 24];
1409
+ d4 = data[dataOff + 32];
1410
+ d5 = data[dataOff + 40];
1411
+ d6 = data[dataOff + 48];
1412
+ d7 = data[dataOff + 56];
1413
+ var tmp0p2 = d0 + d7;
1414
+ var tmp7p2 = d0 - d7;
1415
+ var tmp1p2 = d1 + d6;
1416
+ var tmp6p2 = d1 - d6;
1417
+ var tmp2p2 = d2 + d5;
1418
+ var tmp5p2 = d2 - d5;
1419
+ var tmp3p2 = d3 + d4;
1420
+ var tmp4p2 = d3 - d4;
1421
+ var tmp10p2 = tmp0p2 + tmp3p2;
1422
+ var tmp13p2 = tmp0p2 - tmp3p2;
1423
+ var tmp11p2 = tmp1p2 + tmp2p2;
1424
+ var tmp12p2 = tmp1p2 - tmp2p2;
1425
+ data[dataOff] = tmp10p2 + tmp11p2;
1426
+ data[dataOff + 32] = tmp10p2 - tmp11p2;
1427
+ var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781;
1428
+ data[dataOff + 16] = tmp13p2 + z1p2;
1429
+ data[dataOff + 48] = tmp13p2 - z1p2;
1430
+ tmp10p2 = tmp4p2 + tmp5p2;
1431
+ tmp11p2 = tmp5p2 + tmp6p2;
1432
+ tmp12p2 = tmp6p2 + tmp7p2;
1433
+ var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433;
1434
+ var z2p2 = 0.5411961 * tmp10p2 + z5p2;
1435
+ var z4p2 = 1.306562965 * tmp12p2 + z5p2;
1436
+ var z3p2 = tmp11p2 * 0.707106781;
1437
+ var z11p2 = tmp7p2 + z3p2;
1438
+ var z13p2 = tmp7p2 - z3p2;
1439
+ data[dataOff + 40] = z13p2 + z2p2;
1440
+ data[dataOff + 24] = z13p2 - z2p2;
1441
+ data[dataOff + 8] = z11p2 + z4p2;
1442
+ data[dataOff + 56] = z11p2 - z4p2;
1443
+ dataOff++;
1444
+ }
1445
+ var fDCTQuant2;
1446
+ for (i = 0; i < I64; ++i) {
1447
+ fDCTQuant2 = data[i] * fdtbl[i];
1448
+ outputfDCTQuant[i] = fDCTQuant2 > 0 ? fDCTQuant2 + 0.5 | 0 : fDCTQuant2 - 0.5 | 0;
1449
+ }
1450
+ return outputfDCTQuant;
1451
+ }
1452
+ function writeAPP0() {
1453
+ writeWord(65504);
1454
+ writeWord(16);
1455
+ writeByte(74);
1456
+ writeByte(70);
1457
+ writeByte(73);
1458
+ writeByte(70);
1459
+ writeByte(0);
1460
+ writeByte(1);
1461
+ writeByte(1);
1462
+ writeByte(0);
1463
+ writeWord(1);
1464
+ writeWord(1);
1465
+ writeByte(0);
1466
+ writeByte(0);
1467
+ }
1468
+ function writeAPP1(exifBuffer) {
1469
+ if (!exifBuffer) return;
1470
+ writeWord(65505);
1471
+ if (exifBuffer[0] === 69 && exifBuffer[1] === 120 && exifBuffer[2] === 105 && exifBuffer[3] === 102) {
1472
+ writeWord(exifBuffer.length + 2);
1473
+ } else {
1474
+ writeWord(exifBuffer.length + 5 + 2);
1475
+ writeByte(69);
1476
+ writeByte(120);
1477
+ writeByte(105);
1478
+ writeByte(102);
1479
+ writeByte(0);
1480
+ }
1481
+ for (var i = 0; i < exifBuffer.length; i++) {
1482
+ writeByte(exifBuffer[i]);
1483
+ }
1484
+ }
1485
+ function writeSOF0(width, height) {
1486
+ writeWord(65472);
1487
+ writeWord(17);
1488
+ writeByte(8);
1489
+ writeWord(height);
1490
+ writeWord(width);
1491
+ writeByte(3);
1492
+ writeByte(1);
1493
+ writeByte(17);
1494
+ writeByte(0);
1495
+ writeByte(2);
1496
+ writeByte(17);
1497
+ writeByte(1);
1498
+ writeByte(3);
1499
+ writeByte(17);
1500
+ writeByte(1);
1501
+ }
1502
+ function writeDQT() {
1503
+ writeWord(65499);
1504
+ writeWord(132);
1505
+ writeByte(0);
1506
+ for (var i = 0; i < 64; i++) {
1507
+ writeByte(YTable[i]);
1508
+ }
1509
+ writeByte(1);
1510
+ for (var j = 0; j < 64; j++) {
1511
+ writeByte(UVTable[j]);
1512
+ }
1513
+ }
1514
+ function writeDHT() {
1515
+ writeWord(65476);
1516
+ writeWord(418);
1517
+ writeByte(0);
1518
+ for (var i = 0; i < 16; i++) {
1519
+ writeByte(std_dc_luminance_nrcodes[i + 1]);
1520
+ }
1521
+ for (var j = 0; j <= 11; j++) {
1522
+ writeByte(std_dc_luminance_values[j]);
1523
+ }
1524
+ writeByte(16);
1525
+ for (var k = 0; k < 16; k++) {
1526
+ writeByte(std_ac_luminance_nrcodes[k + 1]);
1527
+ }
1528
+ for (var l = 0; l <= 161; l++) {
1529
+ writeByte(std_ac_luminance_values[l]);
1530
+ }
1531
+ writeByte(1);
1532
+ for (var m = 0; m < 16; m++) {
1533
+ writeByte(std_dc_chrominance_nrcodes[m + 1]);
1534
+ }
1535
+ for (var n = 0; n <= 11; n++) {
1536
+ writeByte(std_dc_chrominance_values[n]);
1537
+ }
1538
+ writeByte(17);
1539
+ for (var o = 0; o < 16; o++) {
1540
+ writeByte(std_ac_chrominance_nrcodes[o + 1]);
1541
+ }
1542
+ for (var p = 0; p <= 161; p++) {
1543
+ writeByte(std_ac_chrominance_values[p]);
1544
+ }
1545
+ }
1546
+ function writeCOM(comments) {
1547
+ if (typeof comments === "undefined" || comments.constructor !== Array) return;
1548
+ comments.forEach((e) => {
1549
+ if (typeof e !== "string") return;
1550
+ writeWord(65534);
1551
+ var l = e.length;
1552
+ writeWord(l + 2);
1553
+ var i;
1554
+ for (i = 0; i < l; i++)
1555
+ writeByte(e.charCodeAt(i));
1556
+ });
1557
+ }
1558
+ function writeSOS() {
1559
+ writeWord(65498);
1560
+ writeWord(12);
1561
+ writeByte(3);
1562
+ writeByte(1);
1563
+ writeByte(0);
1564
+ writeByte(2);
1565
+ writeByte(17);
1566
+ writeByte(3);
1567
+ writeByte(17);
1568
+ writeByte(0);
1569
+ writeByte(63);
1570
+ writeByte(0);
1571
+ }
1572
+ function processDU(CDU, fdtbl, DC, HTDC, HTAC) {
1573
+ var EOB = HTAC[0];
1574
+ var M16zeroes = HTAC[240];
1575
+ var pos;
1576
+ var I16 = 16;
1577
+ var I63 = 63;
1578
+ var I64 = 64;
1579
+ var DU_DCT = fDCTQuant(CDU, fdtbl);
1580
+ for (var j = 0; j < I64; ++j) {
1581
+ DU[ZigZag[j]] = DU_DCT[j];
1582
+ }
1583
+ var Diff = DU[0] - DC;
1584
+ DC = DU[0];
1585
+ if (Diff == 0) {
1586
+ writeBits(HTDC[0]);
1587
+ } else {
1588
+ pos = 32767 + Diff;
1589
+ writeBits(HTDC[category[pos]]);
1590
+ writeBits(bitcode[pos]);
1591
+ }
1592
+ var end0pos = 63;
1593
+ for (; end0pos > 0 && DU[end0pos] == 0; end0pos--) {
1594
+ }
1595
+ ;
1596
+ if (end0pos == 0) {
1597
+ writeBits(EOB);
1598
+ return DC;
1599
+ }
1600
+ var i = 1;
1601
+ var lng;
1602
+ while (i <= end0pos) {
1603
+ var startpos = i;
1604
+ for (; DU[i] == 0 && i <= end0pos; ++i) {
1605
+ }
1606
+ var nrzeroes = i - startpos;
1607
+ if (nrzeroes >= I16) {
1608
+ lng = nrzeroes >> 4;
1609
+ for (var nrmarker = 1; nrmarker <= lng; ++nrmarker)
1610
+ writeBits(M16zeroes);
1611
+ nrzeroes = nrzeroes & 15;
1612
+ }
1613
+ pos = 32767 + DU[i];
1614
+ writeBits(HTAC[(nrzeroes << 4) + category[pos]]);
1615
+ writeBits(bitcode[pos]);
1616
+ i++;
1617
+ }
1618
+ if (end0pos != I63) {
1619
+ writeBits(EOB);
1620
+ }
1621
+ return DC;
1622
+ }
1623
+ function initCharLookupTable() {
1624
+ var sfcc = String.fromCharCode;
1625
+ for (var i = 0; i < 256; i++) {
1626
+ clt[i] = sfcc(i);
1627
+ }
1628
+ }
1629
+ this.encode = function(image, quality2) {
1630
+ var time_start = (/* @__PURE__ */ new Date()).getTime();
1631
+ if (quality2) setQuality(quality2);
1632
+ byteout = new Array();
1633
+ bytenew = 0;
1634
+ bytepos = 7;
1635
+ writeWord(65496);
1636
+ writeAPP0();
1637
+ writeCOM(image.comments);
1638
+ writeAPP1(image.exifBuffer);
1639
+ writeDQT();
1640
+ writeSOF0(image.width, image.height);
1641
+ writeDHT();
1642
+ writeSOS();
1643
+ var DCY = 0;
1644
+ var DCU = 0;
1645
+ var DCV = 0;
1646
+ bytenew = 0;
1647
+ bytepos = 7;
1648
+ this.encode.displayName = "_encode_";
1649
+ var imageData = image.data;
1650
+ var width = image.width;
1651
+ var height = image.height;
1652
+ var quadWidth = width * 4;
1653
+ var tripleWidth = width * 3;
1654
+ var x, y = 0;
1655
+ var r, g, b;
1656
+ var start, p, col, row, pos;
1657
+ while (y < height) {
1658
+ x = 0;
1659
+ while (x < quadWidth) {
1660
+ start = quadWidth * y + x;
1661
+ p = start;
1662
+ col = -1;
1663
+ row = 0;
1664
+ for (pos = 0; pos < 64; pos++) {
1665
+ row = pos >> 3;
1666
+ col = (pos & 7) * 4;
1667
+ p = start + row * quadWidth + col;
1668
+ if (y + row >= height) {
1669
+ p -= quadWidth * (y + 1 + row - height);
1670
+ }
1671
+ if (x + col >= quadWidth) {
1672
+ p -= x + col - quadWidth + 4;
1673
+ }
1674
+ r = imageData[p++];
1675
+ g = imageData[p++];
1676
+ b = imageData[p++];
1677
+ YDU[pos] = (RGB_YUV_TABLE[r] + RGB_YUV_TABLE[g + 256 >> 0] + RGB_YUV_TABLE[b + 512 >> 0] >> 16) - 128;
1678
+ UDU[pos] = (RGB_YUV_TABLE[r + 768 >> 0] + RGB_YUV_TABLE[g + 1024 >> 0] + RGB_YUV_TABLE[b + 1280 >> 0] >> 16) - 128;
1679
+ VDU[pos] = (RGB_YUV_TABLE[r + 1280 >> 0] + RGB_YUV_TABLE[g + 1536 >> 0] + RGB_YUV_TABLE[b + 1792 >> 0] >> 16) - 128;
1680
+ }
1681
+ DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
1682
+ DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
1683
+ DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
1684
+ x += 32;
1685
+ }
1686
+ y += 8;
1687
+ }
1688
+ if (bytepos >= 0) {
1689
+ var fillbits = [];
1690
+ fillbits[1] = bytepos + 1;
1691
+ fillbits[0] = (1 << bytepos + 1) - 1;
1692
+ writeBits(fillbits);
1693
+ }
1694
+ writeWord(65497);
1695
+ if (typeof module === "undefined") return new Uint8Array(byteout);
1696
+ return Buffer.from(byteout);
1697
+ var jpegDataUri = "data:image/jpeg;base64," + btoa(byteout.join(""));
1698
+ byteout = [];
1699
+ var duration = (/* @__PURE__ */ new Date()).getTime() - time_start;
1700
+ return jpegDataUri;
1701
+ };
1702
+ function setQuality(quality2) {
1703
+ if (quality2 <= 0) {
1704
+ quality2 = 1;
1705
+ }
1706
+ if (quality2 > 100) {
1707
+ quality2 = 100;
1708
+ }
1709
+ if (currentQuality == quality2) return;
1710
+ var sf = 0;
1711
+ if (quality2 < 50) {
1712
+ sf = Math.floor(5e3 / quality2);
1713
+ } else {
1714
+ sf = Math.floor(200 - quality2 * 2);
1715
+ }
1716
+ initQuantTables(sf);
1717
+ currentQuality = quality2;
1718
+ }
1719
+ function init() {
1720
+ var time_start = (/* @__PURE__ */ new Date()).getTime();
1721
+ if (!quality) quality = 50;
1722
+ initCharLookupTable();
1723
+ initHuffmanTbl();
1724
+ initCategoryNumber();
1725
+ initRGBYUVTable();
1726
+ setQuality(quality);
1727
+ var duration = (/* @__PURE__ */ new Date()).getTime() - time_start;
1728
+ }
1729
+ init();
1730
+ }
1731
+ if (typeof module !== "undefined") {
1732
+ module.exports = encode;
1733
+ } else if (typeof window !== "undefined") {
1734
+ window["jpeg-js"] = window["jpeg-js"] || {};
1735
+ window["jpeg-js"].encode = encode;
1736
+ }
1737
+ function encode(imgData, qu) {
1738
+ if (typeof qu === "undefined") qu = 50;
1739
+ var encoder = new JPEGEncoder(qu);
1740
+ var data = encoder.encode(imgData, qu);
1741
+ return {
1742
+ data,
1743
+ width: imgData.width,
1744
+ height: imgData.height
1745
+ };
1746
+ }
1747
+ }
1748
+ });
1749
+
1750
+ // node_modules/jpeg-js/lib/decoder.js
1751
+ var require_decoder = __commonJS({
1752
+ "node_modules/jpeg-js/lib/decoder.js"(exports, module) {
1753
+ init_define_import_meta_env();
1754
+ var JpegImage = (function jpegImage() {
1755
+ "use strict";
1756
+ var dctZigZag = new Int32Array([
1757
+ 0,
1758
+ 1,
1759
+ 8,
1760
+ 16,
1761
+ 9,
1762
+ 2,
1763
+ 3,
1764
+ 10,
1765
+ 17,
1766
+ 24,
1767
+ 32,
1768
+ 25,
1769
+ 18,
1770
+ 11,
1771
+ 4,
1772
+ 5,
1773
+ 12,
1774
+ 19,
1775
+ 26,
1776
+ 33,
1777
+ 40,
1778
+ 48,
1779
+ 41,
1780
+ 34,
1781
+ 27,
1782
+ 20,
1783
+ 13,
1784
+ 6,
1785
+ 7,
1786
+ 14,
1787
+ 21,
1788
+ 28,
1789
+ 35,
1790
+ 42,
1791
+ 49,
1792
+ 56,
1793
+ 57,
1794
+ 50,
1795
+ 43,
1796
+ 36,
1797
+ 29,
1798
+ 22,
1799
+ 15,
1800
+ 23,
1801
+ 30,
1802
+ 37,
1803
+ 44,
1804
+ 51,
1805
+ 58,
1806
+ 59,
1807
+ 52,
1808
+ 45,
1809
+ 38,
1810
+ 31,
1811
+ 39,
1812
+ 46,
1813
+ 53,
1814
+ 60,
1815
+ 61,
1816
+ 54,
1817
+ 47,
1818
+ 55,
1819
+ 62,
1820
+ 63
1821
+ ]);
1822
+ var dctCos1 = 4017;
1823
+ var dctSin1 = 799;
1824
+ var dctCos3 = 3406;
1825
+ var dctSin3 = 2276;
1826
+ var dctCos6 = 1567;
1827
+ var dctSin6 = 3784;
1828
+ var dctSqrt2 = 5793;
1829
+ var dctSqrt1d2 = 2896;
1830
+ function constructor() {
1831
+ }
1832
+ function buildHuffmanTable(codeLengths, values) {
1833
+ var k = 0, code = [], i, j, length = 16;
1834
+ while (length > 0 && !codeLengths[length - 1])
1835
+ length--;
1836
+ code.push({ children: [], index: 0 });
1837
+ var p = code[0], q;
1838
+ for (i = 0; i < length; i++) {
1839
+ for (j = 0; j < codeLengths[i]; j++) {
1840
+ p = code.pop();
1841
+ p.children[p.index] = values[k];
1842
+ while (p.index > 0) {
1843
+ if (code.length === 0)
1844
+ throw new Error("Could not recreate Huffman Table");
1845
+ p = code.pop();
1846
+ }
1847
+ p.index++;
1848
+ code.push(p);
1849
+ while (code.length <= i) {
1850
+ code.push(q = { children: [], index: 0 });
1851
+ p.children[p.index] = q.children;
1852
+ p = q;
1853
+ }
1854
+ k++;
1855
+ }
1856
+ if (i + 1 < length) {
1857
+ code.push(q = { children: [], index: 0 });
1858
+ p.children[p.index] = q.children;
1859
+ p = q;
1860
+ }
1861
+ }
1862
+ return code[0].children;
1863
+ }
1864
+ function decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive, opts) {
1865
+ var precision = frame.precision;
1866
+ var samplesPerLine = frame.samplesPerLine;
1867
+ var scanLines = frame.scanLines;
1868
+ var mcusPerLine = frame.mcusPerLine;
1869
+ var progressive = frame.progressive;
1870
+ var maxH = frame.maxH, maxV = frame.maxV;
1871
+ var startOffset = offset, bitsData = 0, bitsCount = 0;
1872
+ function readBit() {
1873
+ if (bitsCount > 0) {
1874
+ bitsCount--;
1875
+ return bitsData >> bitsCount & 1;
1876
+ }
1877
+ bitsData = data[offset++];
1878
+ if (bitsData == 255) {
1879
+ var nextByte = data[offset++];
1880
+ if (nextByte) {
1881
+ throw new Error("unexpected marker: " + (bitsData << 8 | nextByte).toString(16));
1882
+ }
1883
+ }
1884
+ bitsCount = 7;
1885
+ return bitsData >>> 7;
1886
+ }
1887
+ function decodeHuffman(tree) {
1888
+ var node = tree, bit;
1889
+ while ((bit = readBit()) !== null) {
1890
+ node = node[bit];
1891
+ if (typeof node === "number")
1892
+ return node;
1893
+ if (typeof node !== "object")
1894
+ throw new Error("invalid huffman sequence");
1895
+ }
1896
+ return null;
1897
+ }
1898
+ function receive(length) {
1899
+ var n2 = 0;
1900
+ while (length > 0) {
1901
+ var bit = readBit();
1902
+ if (bit === null) return;
1903
+ n2 = n2 << 1 | bit;
1904
+ length--;
1905
+ }
1906
+ return n2;
1907
+ }
1908
+ function receiveAndExtend(length) {
1909
+ var n2 = receive(length);
1910
+ if (n2 >= 1 << length - 1)
1911
+ return n2;
1912
+ return n2 + (-1 << length) + 1;
1913
+ }
1914
+ function decodeBaseline(component2, zz) {
1915
+ var t = decodeHuffman(component2.huffmanTableDC);
1916
+ var diff = t === 0 ? 0 : receiveAndExtend(t);
1917
+ zz[0] = component2.pred += diff;
1918
+ var k2 = 1;
1919
+ while (k2 < 64) {
1920
+ var rs = decodeHuffman(component2.huffmanTableAC);
1921
+ var s = rs & 15, r = rs >> 4;
1922
+ if (s === 0) {
1923
+ if (r < 15)
1924
+ break;
1925
+ k2 += 16;
1926
+ continue;
1927
+ }
1928
+ k2 += r;
1929
+ var z = dctZigZag[k2];
1930
+ zz[z] = receiveAndExtend(s);
1931
+ k2++;
1932
+ }
1933
+ }
1934
+ function decodeDCFirst(component2, zz) {
1935
+ var t = decodeHuffman(component2.huffmanTableDC);
1936
+ var diff = t === 0 ? 0 : receiveAndExtend(t) << successive;
1937
+ zz[0] = component2.pred += diff;
1938
+ }
1939
+ function decodeDCSuccessive(component2, zz) {
1940
+ zz[0] |= readBit() << successive;
1941
+ }
1942
+ var eobrun = 0;
1943
+ function decodeACFirst(component2, zz) {
1944
+ if (eobrun > 0) {
1945
+ eobrun--;
1946
+ return;
1947
+ }
1948
+ var k2 = spectralStart, e = spectralEnd;
1949
+ while (k2 <= e) {
1950
+ var rs = decodeHuffman(component2.huffmanTableAC);
1951
+ var s = rs & 15, r = rs >> 4;
1952
+ if (s === 0) {
1953
+ if (r < 15) {
1954
+ eobrun = receive(r) + (1 << r) - 1;
1955
+ break;
1956
+ }
1957
+ k2 += 16;
1958
+ continue;
1959
+ }
1960
+ k2 += r;
1961
+ var z = dctZigZag[k2];
1962
+ zz[z] = receiveAndExtend(s) * (1 << successive);
1963
+ k2++;
1964
+ }
1965
+ }
1966
+ var successiveACState = 0, successiveACNextValue;
1967
+ function decodeACSuccessive(component2, zz) {
1968
+ var k2 = spectralStart, e = spectralEnd, r = 0;
1969
+ while (k2 <= e) {
1970
+ var z = dctZigZag[k2];
1971
+ var direction = zz[z] < 0 ? -1 : 1;
1972
+ switch (successiveACState) {
1973
+ case 0:
1974
+ var rs = decodeHuffman(component2.huffmanTableAC);
1975
+ var s = rs & 15, r = rs >> 4;
1976
+ if (s === 0) {
1977
+ if (r < 15) {
1978
+ eobrun = receive(r) + (1 << r);
1979
+ successiveACState = 4;
1980
+ } else {
1981
+ r = 16;
1982
+ successiveACState = 1;
1983
+ }
1984
+ } else {
1985
+ if (s !== 1)
1986
+ throw new Error("invalid ACn encoding");
1987
+ successiveACNextValue = receiveAndExtend(s);
1988
+ successiveACState = r ? 2 : 3;
1989
+ }
1990
+ continue;
1991
+ case 1:
1992
+ // skipping r zero items
1993
+ case 2:
1994
+ if (zz[z])
1995
+ zz[z] += (readBit() << successive) * direction;
1996
+ else {
1997
+ r--;
1998
+ if (r === 0)
1999
+ successiveACState = successiveACState == 2 ? 3 : 0;
2000
+ }
2001
+ break;
2002
+ case 3:
2003
+ if (zz[z])
2004
+ zz[z] += (readBit() << successive) * direction;
2005
+ else {
2006
+ zz[z] = successiveACNextValue << successive;
2007
+ successiveACState = 0;
2008
+ }
2009
+ break;
2010
+ case 4:
2011
+ if (zz[z])
2012
+ zz[z] += (readBit() << successive) * direction;
2013
+ break;
2014
+ }
2015
+ k2++;
2016
+ }
2017
+ if (successiveACState === 4) {
2018
+ eobrun--;
2019
+ if (eobrun === 0)
2020
+ successiveACState = 0;
2021
+ }
2022
+ }
2023
+ function decodeMcu(component2, decode2, mcu2, row, col) {
2024
+ var mcuRow = mcu2 / mcusPerLine | 0;
2025
+ var mcuCol = mcu2 % mcusPerLine;
2026
+ var blockRow = mcuRow * component2.v + row;
2027
+ var blockCol = mcuCol * component2.h + col;
2028
+ if (component2.blocks[blockRow] === void 0 && opts.tolerantDecoding)
2029
+ return;
2030
+ decode2(component2, component2.blocks[blockRow][blockCol]);
2031
+ }
2032
+ function decodeBlock(component2, decode2, mcu2) {
2033
+ var blockRow = mcu2 / component2.blocksPerLine | 0;
2034
+ var blockCol = mcu2 % component2.blocksPerLine;
2035
+ if (component2.blocks[blockRow] === void 0 && opts.tolerantDecoding)
2036
+ return;
2037
+ decode2(component2, component2.blocks[blockRow][blockCol]);
2038
+ }
2039
+ var componentsLength = components.length;
2040
+ var component, i, j, k, n;
2041
+ var decodeFn;
2042
+ if (progressive) {
2043
+ if (spectralStart === 0)
2044
+ decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
2045
+ else
2046
+ decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
2047
+ } else {
2048
+ decodeFn = decodeBaseline;
2049
+ }
2050
+ var mcu = 0, marker;
2051
+ var mcuExpected;
2052
+ if (componentsLength == 1) {
2053
+ mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
2054
+ } else {
2055
+ mcuExpected = mcusPerLine * frame.mcusPerColumn;
2056
+ }
2057
+ if (!resetInterval) resetInterval = mcuExpected;
2058
+ var h, v;
2059
+ while (mcu < mcuExpected) {
2060
+ for (i = 0; i < componentsLength; i++)
2061
+ components[i].pred = 0;
2062
+ eobrun = 0;
2063
+ if (componentsLength == 1) {
2064
+ component = components[0];
2065
+ for (n = 0; n < resetInterval; n++) {
2066
+ decodeBlock(component, decodeFn, mcu);
2067
+ mcu++;
2068
+ }
2069
+ } else {
2070
+ for (n = 0; n < resetInterval; n++) {
2071
+ for (i = 0; i < componentsLength; i++) {
2072
+ component = components[i];
2073
+ h = component.h;
2074
+ v = component.v;
2075
+ for (j = 0; j < v; j++) {
2076
+ for (k = 0; k < h; k++) {
2077
+ decodeMcu(component, decodeFn, mcu, j, k);
2078
+ }
2079
+ }
2080
+ }
2081
+ mcu++;
2082
+ if (mcu === mcuExpected) break;
2083
+ }
2084
+ }
2085
+ if (mcu === mcuExpected) {
2086
+ do {
2087
+ if (data[offset] === 255) {
2088
+ if (data[offset + 1] !== 0) {
2089
+ break;
2090
+ }
2091
+ }
2092
+ offset += 1;
2093
+ } while (offset < data.length - 2);
2094
+ }
2095
+ bitsCount = 0;
2096
+ marker = data[offset] << 8 | data[offset + 1];
2097
+ if (marker < 65280) {
2098
+ throw new Error("marker was not found");
2099
+ }
2100
+ if (marker >= 65488 && marker <= 65495) {
2101
+ offset += 2;
2102
+ } else
2103
+ break;
2104
+ }
2105
+ return offset - startOffset;
2106
+ }
2107
+ function buildComponentData(frame, component) {
2108
+ var lines2 = [];
2109
+ var blocksPerLine = component.blocksPerLine;
2110
+ var blocksPerColumn = component.blocksPerColumn;
2111
+ var samplesPerLine = blocksPerLine << 3;
2112
+ var R = new Int32Array(64), r = new Uint8Array(64);
2113
+ function quantizeAndInverse(zz, dataOut, dataIn) {
2114
+ var qt = component.quantizationTable;
2115
+ var v0, v1, v2, v3, v4, v5, v6, v7, t;
2116
+ var p = dataIn;
2117
+ var i2;
2118
+ for (i2 = 0; i2 < 64; i2++)
2119
+ p[i2] = zz[i2] * qt[i2];
2120
+ for (i2 = 0; i2 < 8; ++i2) {
2121
+ var row = 8 * i2;
2122
+ if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && p[7 + row] == 0) {
2123
+ t = dctSqrt2 * p[0 + row] + 512 >> 10;
2124
+ p[0 + row] = t;
2125
+ p[1 + row] = t;
2126
+ p[2 + row] = t;
2127
+ p[3 + row] = t;
2128
+ p[4 + row] = t;
2129
+ p[5 + row] = t;
2130
+ p[6 + row] = t;
2131
+ p[7 + row] = t;
2132
+ continue;
2133
+ }
2134
+ v0 = dctSqrt2 * p[0 + row] + 128 >> 8;
2135
+ v1 = dctSqrt2 * p[4 + row] + 128 >> 8;
2136
+ v2 = p[2 + row];
2137
+ v3 = p[6 + row];
2138
+ v4 = dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128 >> 8;
2139
+ v7 = dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128 >> 8;
2140
+ v5 = p[3 + row] << 4;
2141
+ v6 = p[5 + row] << 4;
2142
+ t = v0 - v1 + 1 >> 1;
2143
+ v0 = v0 + v1 + 1 >> 1;
2144
+ v1 = t;
2145
+ t = v2 * dctSin6 + v3 * dctCos6 + 128 >> 8;
2146
+ v2 = v2 * dctCos6 - v3 * dctSin6 + 128 >> 8;
2147
+ v3 = t;
2148
+ t = v4 - v6 + 1 >> 1;
2149
+ v4 = v4 + v6 + 1 >> 1;
2150
+ v6 = t;
2151
+ t = v7 + v5 + 1 >> 1;
2152
+ v5 = v7 - v5 + 1 >> 1;
2153
+ v7 = t;
2154
+ t = v0 - v3 + 1 >> 1;
2155
+ v0 = v0 + v3 + 1 >> 1;
2156
+ v3 = t;
2157
+ t = v1 - v2 + 1 >> 1;
2158
+ v1 = v1 + v2 + 1 >> 1;
2159
+ v2 = t;
2160
+ t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12;
2161
+ v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12;
2162
+ v7 = t;
2163
+ t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12;
2164
+ v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12;
2165
+ v6 = t;
2166
+ p[0 + row] = v0 + v7;
2167
+ p[7 + row] = v0 - v7;
2168
+ p[1 + row] = v1 + v6;
2169
+ p[6 + row] = v1 - v6;
2170
+ p[2 + row] = v2 + v5;
2171
+ p[5 + row] = v2 - v5;
2172
+ p[3 + row] = v3 + v4;
2173
+ p[4 + row] = v3 - v4;
2174
+ }
2175
+ for (i2 = 0; i2 < 8; ++i2) {
2176
+ var col = i2;
2177
+ if (p[1 * 8 + col] == 0 && p[2 * 8 + col] == 0 && p[3 * 8 + col] == 0 && p[4 * 8 + col] == 0 && p[5 * 8 + col] == 0 && p[6 * 8 + col] == 0 && p[7 * 8 + col] == 0) {
2178
+ t = dctSqrt2 * dataIn[i2 + 0] + 8192 >> 14;
2179
+ p[0 * 8 + col] = t;
2180
+ p[1 * 8 + col] = t;
2181
+ p[2 * 8 + col] = t;
2182
+ p[3 * 8 + col] = t;
2183
+ p[4 * 8 + col] = t;
2184
+ p[5 * 8 + col] = t;
2185
+ p[6 * 8 + col] = t;
2186
+ p[7 * 8 + col] = t;
2187
+ continue;
2188
+ }
2189
+ v0 = dctSqrt2 * p[0 * 8 + col] + 2048 >> 12;
2190
+ v1 = dctSqrt2 * p[4 * 8 + col] + 2048 >> 12;
2191
+ v2 = p[2 * 8 + col];
2192
+ v3 = p[6 * 8 + col];
2193
+ v4 = dctSqrt1d2 * (p[1 * 8 + col] - p[7 * 8 + col]) + 2048 >> 12;
2194
+ v7 = dctSqrt1d2 * (p[1 * 8 + col] + p[7 * 8 + col]) + 2048 >> 12;
2195
+ v5 = p[3 * 8 + col];
2196
+ v6 = p[5 * 8 + col];
2197
+ t = v0 - v1 + 1 >> 1;
2198
+ v0 = v0 + v1 + 1 >> 1;
2199
+ v1 = t;
2200
+ t = v2 * dctSin6 + v3 * dctCos6 + 2048 >> 12;
2201
+ v2 = v2 * dctCos6 - v3 * dctSin6 + 2048 >> 12;
2202
+ v3 = t;
2203
+ t = v4 - v6 + 1 >> 1;
2204
+ v4 = v4 + v6 + 1 >> 1;
2205
+ v6 = t;
2206
+ t = v7 + v5 + 1 >> 1;
2207
+ v5 = v7 - v5 + 1 >> 1;
2208
+ v7 = t;
2209
+ t = v0 - v3 + 1 >> 1;
2210
+ v0 = v0 + v3 + 1 >> 1;
2211
+ v3 = t;
2212
+ t = v1 - v2 + 1 >> 1;
2213
+ v1 = v1 + v2 + 1 >> 1;
2214
+ v2 = t;
2215
+ t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12;
2216
+ v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12;
2217
+ v7 = t;
2218
+ t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12;
2219
+ v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12;
2220
+ v6 = t;
2221
+ p[0 * 8 + col] = v0 + v7;
2222
+ p[7 * 8 + col] = v0 - v7;
2223
+ p[1 * 8 + col] = v1 + v6;
2224
+ p[6 * 8 + col] = v1 - v6;
2225
+ p[2 * 8 + col] = v2 + v5;
2226
+ p[5 * 8 + col] = v2 - v5;
2227
+ p[3 * 8 + col] = v3 + v4;
2228
+ p[4 * 8 + col] = v3 - v4;
2229
+ }
2230
+ for (i2 = 0; i2 < 64; ++i2) {
2231
+ var sample2 = 128 + (p[i2] + 8 >> 4);
2232
+ dataOut[i2] = sample2 < 0 ? 0 : sample2 > 255 ? 255 : sample2;
2233
+ }
2234
+ }
2235
+ requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);
2236
+ var i, j;
2237
+ for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
2238
+ var scanLine = blockRow << 3;
2239
+ for (i = 0; i < 8; i++)
2240
+ lines2.push(new Uint8Array(samplesPerLine));
2241
+ for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
2242
+ quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);
2243
+ var offset = 0, sample = blockCol << 3;
2244
+ for (j = 0; j < 8; j++) {
2245
+ var line = lines2[scanLine + j];
2246
+ for (i = 0; i < 8; i++)
2247
+ line[sample + i] = r[offset++];
2248
+ }
2249
+ }
2250
+ }
2251
+ return lines2;
2252
+ }
2253
+ function clampTo8bit(a) {
2254
+ return a < 0 ? 0 : a > 255 ? 255 : a;
2255
+ }
2256
+ constructor.prototype = {
2257
+ load: function load3(path26) {
2258
+ var xhr = new XMLHttpRequest();
2259
+ xhr.open("GET", path26, true);
2260
+ xhr.responseType = "arraybuffer";
2261
+ xhr.onload = (function() {
2262
+ var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
2263
+ this.parse(data);
2264
+ if (this.onload)
2265
+ this.onload();
2266
+ }).bind(this);
2267
+ xhr.send(null);
2268
+ },
2269
+ parse: function parse2(data) {
2270
+ var maxResolutionInPixels = this.opts.maxResolutionInMP * 1e3 * 1e3;
2271
+ var offset = 0, length = data.length;
2272
+ function readUint16() {
2273
+ var value = data[offset] << 8 | data[offset + 1];
2274
+ offset += 2;
2275
+ return value;
2276
+ }
2277
+ function readDataBlock() {
2278
+ var length2 = readUint16();
2279
+ var array = data.subarray(offset, offset + length2 - 2);
2280
+ offset += array.length;
2281
+ return array;
2282
+ }
2283
+ function prepareComponents(frame2) {
2284
+ var maxH2 = 1, maxV2 = 1;
2285
+ var component2, componentId2;
2286
+ for (componentId2 in frame2.components) {
2287
+ if (frame2.components.hasOwnProperty(componentId2)) {
2288
+ component2 = frame2.components[componentId2];
2289
+ if (maxH2 < component2.h) maxH2 = component2.h;
2290
+ if (maxV2 < component2.v) maxV2 = component2.v;
2291
+ }
2292
+ }
2293
+ var mcusPerLine = Math.ceil(frame2.samplesPerLine / 8 / maxH2);
2294
+ var mcusPerColumn = Math.ceil(frame2.scanLines / 8 / maxV2);
2295
+ for (componentId2 in frame2.components) {
2296
+ if (frame2.components.hasOwnProperty(componentId2)) {
2297
+ component2 = frame2.components[componentId2];
2298
+ var blocksPerLine = Math.ceil(Math.ceil(frame2.samplesPerLine / 8) * component2.h / maxH2);
2299
+ var blocksPerColumn = Math.ceil(Math.ceil(frame2.scanLines / 8) * component2.v / maxV2);
2300
+ var blocksPerLineForMcu = mcusPerLine * component2.h;
2301
+ var blocksPerColumnForMcu = mcusPerColumn * component2.v;
2302
+ var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;
2303
+ var blocks = [];
2304
+ requestMemoryAllocation(blocksToAllocate * 256);
2305
+ for (var i2 = 0; i2 < blocksPerColumnForMcu; i2++) {
2306
+ var row = [];
2307
+ for (var j2 = 0; j2 < blocksPerLineForMcu; j2++)
2308
+ row.push(new Int32Array(64));
2309
+ blocks.push(row);
2310
+ }
2311
+ component2.blocksPerLine = blocksPerLine;
2312
+ component2.blocksPerColumn = blocksPerColumn;
2313
+ component2.blocks = blocks;
2314
+ }
2315
+ }
2316
+ frame2.maxH = maxH2;
2317
+ frame2.maxV = maxV2;
2318
+ frame2.mcusPerLine = mcusPerLine;
2319
+ frame2.mcusPerColumn = mcusPerColumn;
2320
+ }
2321
+ var jfif = null;
2322
+ var adobe = null;
2323
+ var pixels = null;
2324
+ var frame, resetInterval;
2325
+ var quantizationTables = [], frames = [];
2326
+ var huffmanTablesAC = [], huffmanTablesDC = [];
2327
+ var fileMarker = readUint16();
2328
+ var malformedDataOffset = -1;
2329
+ this.comments = [];
2330
+ if (fileMarker != 65496) {
2331
+ throw new Error("SOI not found");
2332
+ }
2333
+ fileMarker = readUint16();
2334
+ while (fileMarker != 65497) {
2335
+ var i, j, l;
2336
+ switch (fileMarker) {
2337
+ case 65280:
2338
+ break;
2339
+ case 65504:
2340
+ // APP0 (Application Specific)
2341
+ case 65505:
2342
+ // APP1
2343
+ case 65506:
2344
+ // APP2
2345
+ case 65507:
2346
+ // APP3
2347
+ case 65508:
2348
+ // APP4
2349
+ case 65509:
2350
+ // APP5
2351
+ case 65510:
2352
+ // APP6
2353
+ case 65511:
2354
+ // APP7
2355
+ case 65512:
2356
+ // APP8
2357
+ case 65513:
2358
+ // APP9
2359
+ case 65514:
2360
+ // APP10
2361
+ case 65515:
2362
+ // APP11
2363
+ case 65516:
2364
+ // APP12
2365
+ case 65517:
2366
+ // APP13
2367
+ case 65518:
2368
+ // APP14
2369
+ case 65519:
2370
+ // APP15
2371
+ case 65534:
2372
+ var appData = readDataBlock();
2373
+ if (fileMarker === 65534) {
2374
+ var comment = String.fromCharCode.apply(null, appData);
2375
+ this.comments.push(comment);
2376
+ }
2377
+ if (fileMarker === 65504) {
2378
+ if (appData[0] === 74 && appData[1] === 70 && appData[2] === 73 && appData[3] === 70 && appData[4] === 0) {
2379
+ jfif = {
2380
+ version: { major: appData[5], minor: appData[6] },
2381
+ densityUnits: appData[7],
2382
+ xDensity: appData[8] << 8 | appData[9],
2383
+ yDensity: appData[10] << 8 | appData[11],
2384
+ thumbWidth: appData[12],
2385
+ thumbHeight: appData[13],
2386
+ thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
2387
+ };
2388
+ }
2389
+ }
2390
+ if (fileMarker === 65505) {
2391
+ if (appData[0] === 69 && appData[1] === 120 && appData[2] === 105 && appData[3] === 102 && appData[4] === 0) {
2392
+ this.exifBuffer = appData.subarray(5, appData.length);
2393
+ }
2394
+ }
2395
+ if (fileMarker === 65518) {
2396
+ if (appData[0] === 65 && appData[1] === 100 && appData[2] === 111 && appData[3] === 98 && appData[4] === 101 && appData[5] === 0) {
2397
+ adobe = {
2398
+ version: appData[6],
2399
+ flags0: appData[7] << 8 | appData[8],
2400
+ flags1: appData[9] << 8 | appData[10],
2401
+ transformCode: appData[11]
2402
+ };
2403
+ }
2404
+ }
2405
+ break;
2406
+ case 65499:
2407
+ var quantizationTablesLength = readUint16();
2408
+ var quantizationTablesEnd = quantizationTablesLength + offset - 2;
2409
+ while (offset < quantizationTablesEnd) {
2410
+ var quantizationTableSpec = data[offset++];
2411
+ requestMemoryAllocation(64 * 4);
2412
+ var tableData = new Int32Array(64);
2413
+ if (quantizationTableSpec >> 4 === 0) {
2414
+ for (j = 0; j < 64; j++) {
2415
+ var z = dctZigZag[j];
2416
+ tableData[z] = data[offset++];
2417
+ }
2418
+ } else if (quantizationTableSpec >> 4 === 1) {
2419
+ for (j = 0; j < 64; j++) {
2420
+ var z = dctZigZag[j];
2421
+ tableData[z] = readUint16();
2422
+ }
2423
+ } else
2424
+ throw new Error("DQT: invalid table spec");
2425
+ quantizationTables[quantizationTableSpec & 15] = tableData;
2426
+ }
2427
+ break;
2428
+ case 65472:
2429
+ // SOF0 (Start of Frame, Baseline DCT)
2430
+ case 65473:
2431
+ // SOF1 (Start of Frame, Extended DCT)
2432
+ case 65474:
2433
+ readUint16();
2434
+ frame = {};
2435
+ frame.extended = fileMarker === 65473;
2436
+ frame.progressive = fileMarker === 65474;
2437
+ frame.precision = data[offset++];
2438
+ frame.scanLines = readUint16();
2439
+ frame.samplesPerLine = readUint16();
2440
+ frame.components = {};
2441
+ frame.componentsOrder = [];
2442
+ var pixelsInFrame = frame.scanLines * frame.samplesPerLine;
2443
+ if (pixelsInFrame > maxResolutionInPixels) {
2444
+ var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);
2445
+ throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);
2446
+ }
2447
+ var componentsCount = data[offset++], componentId;
2448
+ var maxH = 0, maxV = 0;
2449
+ for (i = 0; i < componentsCount; i++) {
2450
+ componentId = data[offset];
2451
+ var h = data[offset + 1] >> 4;
2452
+ var v = data[offset + 1] & 15;
2453
+ var qId = data[offset + 2];
2454
+ if (h <= 0 || v <= 0) {
2455
+ throw new Error("Invalid sampling factor, expected values above 0");
2456
+ }
2457
+ frame.componentsOrder.push(componentId);
2458
+ frame.components[componentId] = {
2459
+ h,
2460
+ v,
2461
+ quantizationIdx: qId
2462
+ };
2463
+ offset += 3;
2464
+ }
2465
+ prepareComponents(frame);
2466
+ frames.push(frame);
2467
+ break;
2468
+ case 65476:
2469
+ var huffmanLength = readUint16();
2470
+ for (i = 2; i < huffmanLength; ) {
2471
+ var huffmanTableSpec = data[offset++];
2472
+ var codeLengths = new Uint8Array(16);
2473
+ var codeLengthSum = 0;
2474
+ for (j = 0; j < 16; j++, offset++) {
2475
+ codeLengthSum += codeLengths[j] = data[offset];
2476
+ }
2477
+ requestMemoryAllocation(16 + codeLengthSum);
2478
+ var huffmanValues = new Uint8Array(codeLengthSum);
2479
+ for (j = 0; j < codeLengthSum; j++, offset++)
2480
+ huffmanValues[j] = data[offset];
2481
+ i += 17 + codeLengthSum;
2482
+ (huffmanTableSpec >> 4 === 0 ? huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues);
2483
+ }
2484
+ break;
2485
+ case 65501:
2486
+ readUint16();
2487
+ resetInterval = readUint16();
2488
+ break;
2489
+ case 65500:
2490
+ readUint16();
2491
+ readUint16();
2492
+ break;
2493
+ case 65498:
2494
+ var scanLength = readUint16();
2495
+ var selectorsCount = data[offset++];
2496
+ var components = [], component;
2497
+ for (i = 0; i < selectorsCount; i++) {
2498
+ component = frame.components[data[offset++]];
2499
+ var tableSpec = data[offset++];
2500
+ component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
2501
+ component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
2502
+ components.push(component);
2503
+ }
2504
+ var spectralStart = data[offset++];
2505
+ var spectralEnd = data[offset++];
2506
+ var successiveApproximation = data[offset++];
2507
+ var processed = decodeScan(
2508
+ data,
2509
+ offset,
2510
+ frame,
2511
+ components,
2512
+ resetInterval,
2513
+ spectralStart,
2514
+ spectralEnd,
2515
+ successiveApproximation >> 4,
2516
+ successiveApproximation & 15,
2517
+ this.opts
2518
+ );
2519
+ offset += processed;
2520
+ break;
2521
+ case 65535:
2522
+ if (data[offset] !== 255) {
2523
+ offset--;
2524
+ }
2525
+ break;
2526
+ default:
2527
+ if (data[offset - 3] == 255 && data[offset - 2] >= 192 && data[offset - 2] <= 254) {
2528
+ offset -= 3;
2529
+ break;
2530
+ } else if (fileMarker === 224 || fileMarker == 225) {
2531
+ if (malformedDataOffset !== -1) {
2532
+ throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);
2533
+ }
2534
+ malformedDataOffset = offset - 1;
2535
+ const nextOffset = readUint16();
2536
+ if (data[offset + nextOffset - 2] === 255) {
2537
+ offset += nextOffset - 2;
2538
+ break;
2539
+ }
2540
+ }
2541
+ throw new Error("unknown JPEG marker " + fileMarker.toString(16));
2542
+ }
2543
+ fileMarker = readUint16();
2544
+ }
2545
+ if (frames.length != 1)
2546
+ throw new Error("only single frame JPEGs supported");
2547
+ for (var i = 0; i < frames.length; i++) {
2548
+ var cp = frames[i].components;
2549
+ for (var j in cp) {
2550
+ cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
2551
+ delete cp[j].quantizationIdx;
2552
+ }
2553
+ }
2554
+ this.width = frame.samplesPerLine;
2555
+ this.height = frame.scanLines;
2556
+ this.jfif = jfif;
2557
+ this.adobe = adobe;
2558
+ this.components = [];
2559
+ for (var i = 0; i < frame.componentsOrder.length; i++) {
2560
+ var component = frame.components[frame.componentsOrder[i]];
2561
+ this.components.push({
2562
+ lines: buildComponentData(frame, component),
2563
+ scaleX: component.h / frame.maxH,
2564
+ scaleY: component.v / frame.maxV
2565
+ });
2566
+ }
2567
+ },
2568
+ getData: function getData(width, height) {
2569
+ var scaleX = this.width / width, scaleY = this.height / height;
2570
+ var component1, component2, component3, component4;
2571
+ var component1Line, component2Line, component3Line, component4Line;
2572
+ var x, y;
2573
+ var offset = 0;
2574
+ var Y, Cb, Cr, K, C, M, Ye, R, G, B;
2575
+ var colorTransform;
2576
+ var dataLength = width * height * this.components.length;
2577
+ requestMemoryAllocation(dataLength);
2578
+ var data = new Uint8Array(dataLength);
2579
+ switch (this.components.length) {
2580
+ case 1:
2581
+ component1 = this.components[0];
2582
+ for (y = 0; y < height; y++) {
2583
+ component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
2584
+ for (x = 0; x < width; x++) {
2585
+ Y = component1Line[0 | x * component1.scaleX * scaleX];
2586
+ data[offset++] = Y;
2587
+ }
2588
+ }
2589
+ break;
2590
+ case 2:
2591
+ component1 = this.components[0];
2592
+ component2 = this.components[1];
2593
+ for (y = 0; y < height; y++) {
2594
+ component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
2595
+ component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
2596
+ for (x = 0; x < width; x++) {
2597
+ Y = component1Line[0 | x * component1.scaleX * scaleX];
2598
+ data[offset++] = Y;
2599
+ Y = component2Line[0 | x * component2.scaleX * scaleX];
2600
+ data[offset++] = Y;
2601
+ }
2602
+ }
2603
+ break;
2604
+ case 3:
2605
+ colorTransform = true;
2606
+ if (this.adobe && this.adobe.transformCode)
2607
+ colorTransform = true;
2608
+ else if (typeof this.opts.colorTransform !== "undefined")
2609
+ colorTransform = !!this.opts.colorTransform;
2610
+ component1 = this.components[0];
2611
+ component2 = this.components[1];
2612
+ component3 = this.components[2];
2613
+ for (y = 0; y < height; y++) {
2614
+ component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
2615
+ component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
2616
+ component3Line = component3.lines[0 | y * component3.scaleY * scaleY];
2617
+ for (x = 0; x < width; x++) {
2618
+ if (!colorTransform) {
2619
+ R = component1Line[0 | x * component1.scaleX * scaleX];
2620
+ G = component2Line[0 | x * component2.scaleX * scaleX];
2621
+ B = component3Line[0 | x * component3.scaleX * scaleX];
2622
+ } else {
2623
+ Y = component1Line[0 | x * component1.scaleX * scaleX];
2624
+ Cb = component2Line[0 | x * component2.scaleX * scaleX];
2625
+ Cr = component3Line[0 | x * component3.scaleX * scaleX];
2626
+ R = clampTo8bit(Y + 1.402 * (Cr - 128));
2627
+ G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
2628
+ B = clampTo8bit(Y + 1.772 * (Cb - 128));
2629
+ }
2630
+ data[offset++] = R;
2631
+ data[offset++] = G;
2632
+ data[offset++] = B;
2633
+ }
2634
+ }
2635
+ break;
2636
+ case 4:
2637
+ if (!this.adobe)
2638
+ throw new Error("Unsupported color mode (4 components)");
2639
+ colorTransform = false;
2640
+ if (this.adobe && this.adobe.transformCode)
2641
+ colorTransform = true;
2642
+ else if (typeof this.opts.colorTransform !== "undefined")
2643
+ colorTransform = !!this.opts.colorTransform;
2644
+ component1 = this.components[0];
2645
+ component2 = this.components[1];
2646
+ component3 = this.components[2];
2647
+ component4 = this.components[3];
2648
+ for (y = 0; y < height; y++) {
2649
+ component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
2650
+ component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
2651
+ component3Line = component3.lines[0 | y * component3.scaleY * scaleY];
2652
+ component4Line = component4.lines[0 | y * component4.scaleY * scaleY];
2653
+ for (x = 0; x < width; x++) {
2654
+ if (!colorTransform) {
2655
+ C = component1Line[0 | x * component1.scaleX * scaleX];
2656
+ M = component2Line[0 | x * component2.scaleX * scaleX];
2657
+ Ye = component3Line[0 | x * component3.scaleX * scaleX];
2658
+ K = component4Line[0 | x * component4.scaleX * scaleX];
2659
+ } else {
2660
+ Y = component1Line[0 | x * component1.scaleX * scaleX];
2661
+ Cb = component2Line[0 | x * component2.scaleX * scaleX];
2662
+ Cr = component3Line[0 | x * component3.scaleX * scaleX];
2663
+ K = component4Line[0 | x * component4.scaleX * scaleX];
2664
+ C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));
2665
+ M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
2666
+ Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));
2667
+ }
2668
+ data[offset++] = 255 - C;
2669
+ data[offset++] = 255 - M;
2670
+ data[offset++] = 255 - Ye;
2671
+ data[offset++] = 255 - K;
2672
+ }
2673
+ }
2674
+ break;
2675
+ default:
2676
+ throw new Error("Unsupported color mode");
2677
+ }
2678
+ return data;
2679
+ },
2680
+ copyToImageData: function copyToImageData(imageData, formatAsRGBA) {
2681
+ var width = imageData.width, height = imageData.height;
2682
+ var imageDataArray = imageData.data;
2683
+ var data = this.getData(width, height);
2684
+ var i = 0, j = 0, x, y;
2685
+ var Y, K, C, M, R, G, B;
2686
+ switch (this.components.length) {
2687
+ case 1:
2688
+ for (y = 0; y < height; y++) {
2689
+ for (x = 0; x < width; x++) {
2690
+ Y = data[i++];
2691
+ imageDataArray[j++] = Y;
2692
+ imageDataArray[j++] = Y;
2693
+ imageDataArray[j++] = Y;
2694
+ if (formatAsRGBA) {
2695
+ imageDataArray[j++] = 255;
2696
+ }
2697
+ }
2698
+ }
2699
+ break;
2700
+ case 3:
2701
+ for (y = 0; y < height; y++) {
2702
+ for (x = 0; x < width; x++) {
2703
+ R = data[i++];
2704
+ G = data[i++];
2705
+ B = data[i++];
2706
+ imageDataArray[j++] = R;
2707
+ imageDataArray[j++] = G;
2708
+ imageDataArray[j++] = B;
2709
+ if (formatAsRGBA) {
2710
+ imageDataArray[j++] = 255;
2711
+ }
2712
+ }
2713
+ }
2714
+ break;
2715
+ case 4:
2716
+ for (y = 0; y < height; y++) {
2717
+ for (x = 0; x < width; x++) {
2718
+ C = data[i++];
2719
+ M = data[i++];
2720
+ Y = data[i++];
2721
+ K = data[i++];
2722
+ R = 255 - clampTo8bit(C * (1 - K / 255) + K);
2723
+ G = 255 - clampTo8bit(M * (1 - K / 255) + K);
2724
+ B = 255 - clampTo8bit(Y * (1 - K / 255) + K);
2725
+ imageDataArray[j++] = R;
2726
+ imageDataArray[j++] = G;
2727
+ imageDataArray[j++] = B;
2728
+ if (formatAsRGBA) {
2729
+ imageDataArray[j++] = 255;
2730
+ }
2731
+ }
2732
+ }
2733
+ break;
2734
+ default:
2735
+ throw new Error("Unsupported color mode");
2736
+ }
2737
+ }
2738
+ };
2739
+ var totalBytesAllocated = 0;
2740
+ var maxMemoryUsageBytes = 0;
2741
+ function requestMemoryAllocation(increaseAmount = 0) {
2742
+ var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;
2743
+ if (totalMemoryImpactBytes > maxMemoryUsageBytes) {
2744
+ var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);
2745
+ throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`);
2746
+ }
2747
+ totalBytesAllocated = totalMemoryImpactBytes;
2748
+ }
2749
+ constructor.resetMaxMemoryUsage = function(maxMemoryUsageBytes_) {
2750
+ totalBytesAllocated = 0;
2751
+ maxMemoryUsageBytes = maxMemoryUsageBytes_;
2752
+ };
2753
+ constructor.getBytesAllocated = function() {
2754
+ return totalBytesAllocated;
2755
+ };
2756
+ constructor.requestMemoryAllocation = requestMemoryAllocation;
2757
+ return constructor;
2758
+ })();
2759
+ if (typeof module !== "undefined") {
2760
+ module.exports = decode;
2761
+ } else if (typeof window !== "undefined") {
2762
+ window["jpeg-js"] = window["jpeg-js"] || {};
2763
+ window["jpeg-js"].decode = decode;
2764
+ }
2765
+ function decode(jpegData, userOpts = {}) {
2766
+ var defaultOpts = {
2767
+ // "undefined" means "Choose whether to transform colors based on the image’s color model."
2768
+ colorTransform: void 0,
2769
+ useTArray: false,
2770
+ formatAsRGBA: true,
2771
+ tolerantDecoding: true,
2772
+ maxResolutionInMP: 100,
2773
+ // Don't decode more than 100 megapixels
2774
+ maxMemoryUsageInMB: 512
2775
+ // Don't decode if memory footprint is more than 512MB
2776
+ };
2777
+ var opts = { ...defaultOpts, ...userOpts };
2778
+ var arr = new Uint8Array(jpegData);
2779
+ var decoder = new JpegImage();
2780
+ decoder.opts = opts;
2781
+ JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024);
2782
+ decoder.parse(arr);
2783
+ var channels = opts.formatAsRGBA ? 4 : 3;
2784
+ var bytesNeeded = decoder.width * decoder.height * channels;
2785
+ try {
2786
+ JpegImage.requestMemoryAllocation(bytesNeeded);
2787
+ var image = {
2788
+ width: decoder.width,
2789
+ height: decoder.height,
2790
+ exifBuffer: decoder.exifBuffer,
2791
+ data: opts.useTArray ? new Uint8Array(bytesNeeded) : Buffer.alloc(bytesNeeded)
2792
+ };
2793
+ if (decoder.comments.length > 0) {
2794
+ image["comments"] = decoder.comments;
2795
+ }
2796
+ } catch (err) {
2797
+ if (err instanceof RangeError) {
2798
+ throw new Error("Could not allocate enough memory for the image. Required: " + bytesNeeded);
2799
+ }
2800
+ if (err instanceof ReferenceError) {
2801
+ if (err.message === "Buffer is not defined") {
2802
+ throw new Error("Buffer is not globally defined in this environment. Consider setting useTArray to true");
2803
+ }
2804
+ }
2805
+ throw err;
2806
+ }
2807
+ decoder.copyToImageData(image, opts.formatAsRGBA);
2808
+ return image;
2809
+ }
2810
+ }
2811
+ });
2812
+
2813
+ // node_modules/jpeg-js/index.js
2814
+ var require_jpeg_js = __commonJS({
2815
+ "node_modules/jpeg-js/index.js"(exports, module) {
2816
+ init_define_import_meta_env();
2817
+ var encode = require_encoder();
2818
+ var decode = require_decoder();
2819
+ module.exports = {
2820
+ encode,
2821
+ decode
2822
+ };
2823
+ }
2824
+ });
2825
+
2826
+ // src/docx_extract.ts
2827
+ init_define_import_meta_env();
103
2828
 
104
2829
  // src/ooxml_extract.ts
2830
+ init_define_import_meta_env();
105
2831
  import * as fs from "node:fs";
106
2832
 
107
2833
  // src/lazy_module.ts
2834
+ init_define_import_meta_env();
108
2835
  function createLazyModuleLoader(load3, errorLabel) {
109
2836
  let cache;
110
2837
  return async () => {
@@ -121,6 +2848,7 @@ function createLazyModuleLoader(load3, errorLabel) {
121
2848
  }
122
2849
 
123
2850
  // src/xml_parser.ts
2851
+ init_define_import_meta_env();
124
2852
  var MAX_XML_DEPTH = 512;
125
2853
  var NAMED_ENTITIES = {
126
2854
  lt: "<",
@@ -331,6 +3059,7 @@ function parseXml(xml) {
331
3059
  }
332
3060
 
333
3061
  // src/zip_bounds.ts
3062
+ init_define_import_meta_env();
334
3063
  var MAX_ZIP_INPUT_BYTES = 50 * 1024 * 1024;
335
3064
  var MAX_ZIP_OUTPUT_BYTES = 500 * 1024 * 1024;
336
3065
  var STREAM_CHUNK_BYTES = 64 * 1024;
@@ -541,6 +3270,7 @@ async function docxText(filePath) {
541
3270
  }
542
3271
 
543
3272
  // src/pptx_extract.ts
3273
+ init_define_import_meta_env();
544
3274
  function shapePlaceholderType(shape) {
545
3275
  const sp = shape;
546
3276
  return sp["p:nvSpPr"]?.["p:nvPr"]?.["p:ph"]?.["@_type"];
@@ -699,7 +3429,20 @@ async function pptxTextGrep(filePath, pattern) {
699
3429
  return out;
700
3430
  }
701
3431
 
3432
+ // src/csv_query.ts
3433
+ init_define_import_meta_env();
3434
+
3435
+ // node_modules/csv-parse/lib/sync.js
3436
+ init_define_import_meta_env();
3437
+
3438
+ // node_modules/csv-parse/lib/api/index.js
3439
+ init_define_import_meta_env();
3440
+
3441
+ // node_modules/csv-parse/lib/api/normalize_columns_array.js
3442
+ init_define_import_meta_env();
3443
+
702
3444
  // node_modules/csv-parse/lib/api/CsvError.js
3445
+ init_define_import_meta_env();
703
3446
  var CsvError = class _CsvError extends Error {
704
3447
  constructor(code, message, options, ...contexts) {
705
3448
  if (Array.isArray(message)) message = message.join(" ").trim();
@@ -718,6 +3461,7 @@ var CsvError = class _CsvError extends Error {
718
3461
  };
719
3462
 
720
3463
  // node_modules/csv-parse/lib/utils/is_object.js
3464
+ init_define_import_meta_env();
721
3465
  var is_object = function(obj) {
722
3466
  return typeof obj === "object" && obj !== null && !Array.isArray(obj);
723
3467
  };
@@ -751,7 +3495,11 @@ var normalize_columns_array = function(columns) {
751
3495
  return normalizedColumns;
752
3496
  };
753
3497
 
3498
+ // node_modules/csv-parse/lib/api/init_state.js
3499
+ init_define_import_meta_env();
3500
+
754
3501
  // node_modules/csv-parse/lib/utils/ResizeableBuffer.js
3502
+ init_define_import_meta_env();
755
3503
  var ResizeableBuffer = class {
756
3504
  constructor(size = 100) {
757
3505
  this.size = size;
@@ -930,7 +3678,11 @@ var init_state = function(options) {
930
3678
  };
931
3679
  };
932
3680
 
3681
+ // node_modules/csv-parse/lib/api/normalize_options.js
3682
+ init_define_import_meta_env();
3683
+
933
3684
  // node_modules/csv-parse/lib/utils/underscore.js
3685
+ init_define_import_meta_env();
934
3686
  var underscore = function(str) {
935
3687
  return str.replace(/([A-Z])/g, function(_, match) {
936
3688
  return "_" + match.toLowerCase();
@@ -1524,6 +4276,7 @@ var normalize_options = function(opts) {
1524
4276
  };
1525
4277
 
1526
4278
  // node_modules/csv-parse/lib/utils/delimiter_discover.js
4279
+ init_define_import_meta_env();
1527
4280
  var delimiter_discover = function(records, options) {
1528
4281
  if (!options) {
1529
4282
  ({ delimiter_auto: options } = normalize_options({ delimiter_auto: true }));
@@ -2581,7 +5334,11 @@ function formatCsvProfile(profiles) {
2581
5334
  }).join("\n\n");
2582
5335
  }
2583
5336
 
5337
+ // src/xlsx_extract.ts
5338
+ init_define_import_meta_env();
5339
+
2584
5340
  // src/xlsx_reader.ts
5341
+ init_define_import_meta_env();
2585
5342
  var EMPTY_CELL = Object.freeze({ value: null, text: "" });
2586
5343
  function asArray(val) {
2587
5344
  if (val === void 0 || val === null) return [];
@@ -3004,10 +5761,12 @@ async function querySheet(filePath, sheetName, opts) {
3004
5761
  }
3005
5762
 
3006
5763
  // src/doc_embed_extract.ts
5764
+ init_define_import_meta_env();
3007
5765
  import * as fs2 from "node:fs";
3008
5766
  import * as path from "node:path";
3009
5767
 
3010
5768
  // src/pdf_extract.ts
5769
+ init_define_import_meta_env();
3011
5770
  var loadPdfjs = createLazyModuleLoader(async () => {
3012
5771
  const mod = await import("pdfjs-dist/legacy/build/pdf.mjs");
3013
5772
  if (typeof import.meta.resolve === "function") {
@@ -3218,9 +5977,11 @@ ${body}`);
3218
5977
  }
3219
5978
 
3220
5979
  // src/index_health.ts
5980
+ init_define_import_meta_env();
3221
5981
  import * as fs4 from "fs";
3222
5982
 
3223
5983
  // src/sql_path.ts
5984
+ init_define_import_meta_env();
3224
5985
  function pathEqClause(column) {
3225
5986
  return isCaseInsensitiveFs() ? `TG_LOWER(${column}) = ?` : `${column} = ?`;
3226
5987
  }
@@ -3251,6 +6012,7 @@ function projectScopeClause(column) {
3251
6012
  }
3252
6013
 
3253
6014
  // src/walk_mode.ts
6015
+ init_define_import_meta_env();
3254
6016
  import * as fs3 from "fs";
3255
6017
  import * as path2 from "path";
3256
6018
  function detectWalkMode(cwd) {
@@ -3295,6 +6057,18 @@ function getEmbeddingCoverage(dbPath, rootDir) {
3295
6057
  embeddedFiles: countScoped("SELECT COUNT(DISTINCT file_path) as c FROM chunks", "file_path")
3296
6058
  };
3297
6059
  }
6060
+ function getParserFreshness(dbPath, parserSha, rootDir) {
6061
+ const db = getDb(dbPath);
6062
+ const count = (extra, params) => {
6063
+ if (rootDir === void 0) {
6064
+ return db.prepare(`SELECT COUNT(*) as c FROM files${extra === "" ? "" : ` WHERE ${extra}`}`).get(...params).c;
6065
+ }
6066
+ const scope = projectScopeClause("path");
6067
+ const where = extra === "" ? scope.clause : `${scope.clause} AND ${extra}`;
6068
+ return db.prepare(`SELECT COUNT(*) as c FROM files WHERE ${where}`).get(...scope.params(rootDir), ...params).c;
6069
+ };
6070
+ return { indexedFiles: count("", []), currentFiles: count("parser_sha = ?", [parserSha]) };
6071
+ }
3298
6072
  function isIndexEmptyForProject(dbPath, rootDir) {
3299
6073
  if (!fs4.existsSync(dbPath)) return true;
3300
6074
  try {
@@ -3312,6 +6086,7 @@ function emptyIndexMessage(rootDir) {
3312
6086
  }
3313
6087
 
3314
6088
  // src/hint_stats.ts
6089
+ init_define_import_meta_env();
3315
6090
  var HINT_CATEGORIES = [
3316
6091
  "bash_redirect",
3317
6092
  "bash_recall",
@@ -3414,7 +6189,7 @@ function logHintEmission(category, sessionId, correlator, compensateSelfResolve
3414
6189
  const db = getDb(globalDbPath());
3415
6190
  const resolved = correlator === null ? 1 : 0;
3416
6191
  const actedOn = resolved === 1 && isSuppressionCategory(category) ? 1 : 0;
3417
- const window = ACTED_ON_WINDOW + (compensateSelfResolve ? 1 : 0);
6192
+ const window2 = ACTED_ON_WINDOW + (compensateSelfResolve ? 1 : 0);
3418
6193
  db.prepare(
3419
6194
  `INSERT INTO hint_emissions (category, session_id, harness, correlator, emitted_at, resolved, acted_on, calls_remaining, bytes_emitted)
3420
6195
  VALUES (@category, @sessionId, @harness, @correlator, @emittedAt, @resolved, @actedOn, @callsRemaining, @bytesEmitted)`
@@ -3426,7 +6201,7 @@ function logHintEmission(category, sessionId, correlator, compensateSelfResolve
3426
6201
  emittedAt: Date.now(),
3427
6202
  resolved,
3428
6203
  actedOn,
3429
- callsRemaining: correlator === null ? 0 : window,
6204
+ callsRemaining: correlator === null ? 0 : window2,
3430
6205
  bytesEmitted
3431
6206
  });
3432
6207
  } catch {
@@ -3616,6 +6391,7 @@ function markCategoryIneffective(category) {
3616
6391
  }
3617
6392
 
3618
6393
  // src/session.ts
6394
+ init_define_import_meta_env();
3619
6395
  import { randomBytes, randomUUID } from "node:crypto";
3620
6396
  import * as fs5 from "node:fs";
3621
6397
  var _files = /* @__PURE__ */ new Map();
@@ -4023,6 +6799,7 @@ registerReset(() => {
4023
6799
  });
4024
6800
 
4025
6801
  // src/index_reader.ts
6802
+ init_define_import_meta_env();
4026
6803
  function toSymbolEntry(row) {
4027
6804
  return {
4028
6805
  filePath: row.file_path,
@@ -4213,6 +6990,7 @@ function searchSymbolsFts(query, limit = 50, dbPath = globalDbPath(), rootDir) {
4213
6990
  }
4214
6991
 
4215
6992
  // src/recall_index.ts
6993
+ init_define_import_meta_env();
4216
6994
  var VALID_TYPES = ["bash", "web", "mcp"];
4217
6995
  var RECALL_DEFAULT_LIMIT = 10;
4218
6996
  function isRecallCacheType(value) {
@@ -4348,10 +7126,12 @@ function searchRecall(query, opts = {}) {
4348
7126
  }
4349
7127
 
4350
7128
  // src/bash_output_cache.ts
7129
+ init_define_import_meta_env();
4351
7130
  import { readdirSync as readdirSync2, readFileSync as readFileSync3, statSync as statSync4 } from "fs";
4352
7131
  import { resolve } from "path";
4353
7132
 
4354
7133
  // src/disk_cache.ts
7134
+ init_define_import_meta_env();
4355
7135
  import * as fs6 from "node:fs";
4356
7136
  import * as path3 from "node:path";
4357
7137
  import * as os from "node:os";
@@ -4571,6 +7351,7 @@ function sweepCacheRoots(extraRoots = []) {
4571
7351
  }
4572
7352
 
4573
7353
  // src/hints/lang_patterns.ts
7354
+ init_define_import_meta_env();
4574
7355
  var LOCK_FILE_NAMES = /* @__PURE__ */ new Set([
4575
7356
  "package-lock.json",
4576
7357
  "yarn.lock",
@@ -5197,6 +7978,7 @@ registerReset(() => {
5197
7978
  });
5198
7979
 
5199
7980
  // src/session_store.ts
7981
+ init_define_import_meta_env();
5200
7982
  import { createHash } from "node:crypto";
5201
7983
  import * as fs7 from "node:fs";
5202
7984
  import * as path4 from "node:path";
@@ -5555,6 +8337,7 @@ function saveSessionState(sessionId) {
5555
8337
  }
5556
8338
 
5557
8339
  // src/injection_scan.ts
8340
+ init_define_import_meta_env();
5558
8341
  var INJECTION_PATTERNS = [
5559
8342
  { name: "ignore-previous-instructions", re: /ignore\s+(all\s+)?(prior|previous|above)\s+instructions/i },
5560
8343
  { name: "disregard-previous-instructions", re: /disregard\s+(all\s+|the\s+)?(prior|previous|above)\s+instructions/i },
@@ -5578,7 +8361,12 @@ var UNTRUSTED_WEB_TAG = "untrusted-web-content";
5578
8361
  function neutralizeFenceMarkers(text, tag) {
5579
8362
  const escapedTag = tag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5580
8363
  const marker = new RegExp(`<\\s*/?\\s*${escapedTag}(?=[\\s/>])[^>]*>`, "gi");
5581
- return text.replace(marker, (m) => m.replace(/</g, "&lt;").replace(/>/g, "&gt;"));
8364
+ return neutralizeSpokenMarkers(
8365
+ text.replace(marker, (m) => m.replace(/</g, "&lt;").replace(/>/g, "&gt;"))
8366
+ );
8367
+ }
8368
+ function neutralizeSpokenMarkers(text) {
8369
+ return text.replace(/\[\s*token-goat\b/gi, (m) => m.replace("[", "&#91;"));
5582
8370
  }
5583
8371
  function fenceUntrustedContent(text, matchedPatternNames, tag = UNTRUSTED_WEB_TAG) {
5584
8372
  const label = matchedPatternNames.length === 1 ? "pattern" : "patterns";
@@ -5607,6 +8395,7 @@ var UNTRUSTED_TOOL_TAG = "untrusted-tool-output";
5607
8395
  var UNTRUSTED_GITHUB_TAG = "untrusted-github-content";
5608
8396
 
5609
8397
  // src/skill_cache.ts
8398
+ init_define_import_meta_env();
5610
8399
  import * as fs8 from "fs/promises";
5611
8400
  import { resolve as resolve2 } from "path";
5612
8401
  import { homedir as homedir2 } from "os";
@@ -6204,11 +8993,570 @@ function pruneSkillOutputs(maxCount = DEFAULT_MAX_COUNT, maxAgeMs = DEFAULT_MAX_
6204
8993
  }
6205
8994
 
6206
8995
  // src/image_shrink.ts
8996
+ init_define_import_meta_env();
8997
+ var import_omggif2 = __toESM(require_omggif(), 1);
6207
8998
  import { createHash as createHash3 } from "node:crypto";
6208
8999
  import * as fs10 from "node:fs";
6209
9000
  import * as path6 from "node:path";
6210
9001
 
9002
+ // src/image_engine.ts
9003
+ init_define_import_meta_env();
9004
+ var import_jpeg_js = __toESM(require_jpeg_js(), 1);
9005
+ var import_omggif = __toESM(require_omggif(), 1);
9006
+ import * as zlib from "node:zlib";
9007
+ var MAX_DECODED_BYTES = 256 * 1024 * 1024;
9008
+ function assertDecodableSize(what, width, height, bytesPerPixel, frames = 1) {
9009
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0 || frames <= 0) {
9010
+ throw new Error(`Invalid ${what} dimensions: ${width}x${height} (${frames} frame(s))`);
9011
+ }
9012
+ const bytes = width * height * bytesPerPixel * frames;
9013
+ if (bytes > MAX_DECODED_BYTES) {
9014
+ throw new Error(
9015
+ `${what} would allocate ${Math.round(bytes / 1048576)}MB, over the ${MAX_DECODED_BYTES / 1048576}MB decode ceiling`
9016
+ );
9017
+ }
9018
+ }
9019
+ var CRC_TABLE = new Int32Array(256);
9020
+ for (let i = 0; i < 256; i++) {
9021
+ let c = i;
9022
+ for (let k = 0; k < 8; k++) {
9023
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
9024
+ }
9025
+ CRC_TABLE[i] = c;
9026
+ }
9027
+ function crc32(buf) {
9028
+ let crc = -1;
9029
+ for (let i = 0; i < buf.length; i++) {
9030
+ const byte = buf[i] ?? 0;
9031
+ crc = (CRC_TABLE[(crc ^ byte) & 255] ?? 0) ^ crc >>> 8;
9032
+ }
9033
+ return (crc ^ -1) >>> 0;
9034
+ }
9035
+ function paethPredictor(a, b, c) {
9036
+ const p = a + b - c;
9037
+ const pa = Math.abs(p - a);
9038
+ const pb = Math.abs(p - b);
9039
+ const pc = Math.abs(p - c);
9040
+ if (pa <= pb && pa <= pc) return a;
9041
+ if (pb <= pc) return b;
9042
+ return c;
9043
+ }
9044
+ function probeBufferMeta(buf) {
9045
+ if (buf.length < 8) return null;
9046
+ if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71 && buf[4] === 13 && buf[5] === 10 && buf[6] === 26 && buf[7] === 10) {
9047
+ if (buf.length < 24) return null;
9048
+ const width = buf.readUInt32BE(16);
9049
+ const height = buf.readUInt32BE(20);
9050
+ return { width, height, format: "png", pages: 1 };
9051
+ }
9052
+ if (buf[0] === 255 && buf[1] === 216 && buf[2] === 255) {
9053
+ let pos = 2;
9054
+ let width = 0;
9055
+ let height = 0;
9056
+ let orientation = 1;
9057
+ while (pos < buf.length - 1) {
9058
+ if (buf[pos] !== 255) {
9059
+ pos++;
9060
+ continue;
9061
+ }
9062
+ const marker = buf[pos + 1];
9063
+ if (marker === void 0) break;
9064
+ pos += 2;
9065
+ if (marker === 216 || marker === 217 || marker === 0 || marker >= 208 && marker <= 215) {
9066
+ continue;
9067
+ }
9068
+ if (pos + 2 > buf.length) break;
9069
+ const length = buf.readUInt16BE(pos);
9070
+ if (length < 2 || pos + length > buf.length) break;
9071
+ if (marker === 225 && length >= 14) {
9072
+ const exifHeader = buf.toString("ascii", pos + 2, pos + 6);
9073
+ if (exifHeader === "Exif") {
9074
+ const tiffStart = pos + 8;
9075
+ if (tiffStart + 8 <= buf.length) {
9076
+ const isLE = buf[tiffStart] === 73 && buf[tiffStart + 1] === 73;
9077
+ const ifdOffset = isLE ? buf.readUInt32LE(tiffStart + 4) : buf.readUInt32BE(tiffStart + 4);
9078
+ let ifdPos = tiffStart + ifdOffset;
9079
+ if (ifdPos + 2 <= buf.length) {
9080
+ const numEntries = isLE ? buf.readUInt16LE(ifdPos) : buf.readUInt16BE(ifdPos);
9081
+ ifdPos += 2;
9082
+ for (let e = 0; e < numEntries && ifdPos + 12 <= buf.length; e++, ifdPos += 12) {
9083
+ const tag = isLE ? buf.readUInt16LE(ifdPos) : buf.readUInt16BE(ifdPos);
9084
+ if (tag === 274) {
9085
+ orientation = isLE ? buf.readUInt16LE(ifdPos + 8) : buf.readUInt16BE(ifdPos + 8);
9086
+ break;
9087
+ }
9088
+ }
9089
+ }
9090
+ }
9091
+ }
9092
+ }
9093
+ const isSof = marker >= 192 && marker <= 195 || marker >= 197 && marker <= 199 || marker >= 201 && marker <= 203 || marker >= 205 && marker <= 207;
9094
+ if (isSof && length >= 7) {
9095
+ height = buf.readUInt16BE(pos + 3);
9096
+ width = buf.readUInt16BE(pos + 5);
9097
+ break;
9098
+ }
9099
+ pos += length;
9100
+ }
9101
+ if (width > 0 && height > 0) {
9102
+ if (orientation >= 5 && orientation <= 8) {
9103
+ return { width: height, height: width, format: "jpeg", pages: 1 };
9104
+ }
9105
+ return { width, height, format: "jpeg", pages: 1 };
9106
+ }
9107
+ return null;
9108
+ }
9109
+ const gifSig = buf.toString("ascii", 0, 6);
9110
+ if (gifSig === "GIF87a" || gifSig === "GIF89a") {
9111
+ const width = buf.readUInt16LE(6);
9112
+ const height = buf.readUInt16LE(8);
9113
+ let pages;
9114
+ try {
9115
+ const reader = new import_omggif.default.GifReader(buf);
9116
+ pages = reader.numFrames();
9117
+ } catch {
9118
+ let count = 0;
9119
+ for (let i = 13; i < buf.length - 9; i++) {
9120
+ if (buf[i] === 44) count++;
9121
+ }
9122
+ pages = Math.max(1, count);
9123
+ }
9124
+ return { width, height, format: "gif", pages };
9125
+ }
9126
+ if (buf.toString("ascii", 0, 4) === "RIFF" && buf.toString("ascii", 8, 12) === "WEBP") {
9127
+ const chunkType = buf.toString("ascii", 12, 16);
9128
+ if (chunkType === "VP8 " && buf.length >= 30) {
9129
+ const width = buf.readUInt16LE(26) & 16383;
9130
+ const height = buf.readUInt16LE(28) & 16383;
9131
+ return { width, height, format: "webp", pages: 1 };
9132
+ }
9133
+ if (chunkType === "VP8L" && buf.length >= 25) {
9134
+ const b1 = buf[21] ?? 0;
9135
+ const b2 = buf[22] ?? 0;
9136
+ const b3 = buf[23] ?? 0;
9137
+ const b4 = buf[24] ?? 0;
9138
+ const width = 1 + ((b2 & 63) << 8 | b1);
9139
+ const height = 1 + ((b4 & 15) << 10 | b3 << 2 | (b2 & 192) >> 6);
9140
+ return { width, height, format: "webp", pages: 1 };
9141
+ }
9142
+ if (chunkType === "VP8X" && buf.length >= 30) {
9143
+ const b24 = buf[24] ?? 0;
9144
+ const b25 = buf[25] ?? 0;
9145
+ const b26 = buf[26] ?? 0;
9146
+ const b27 = buf[27] ?? 0;
9147
+ const b28 = buf[28] ?? 0;
9148
+ const b29 = buf[29] ?? 0;
9149
+ const b20 = buf[20] ?? 0;
9150
+ const width = 1 + (b24 | b25 << 8 | b26 << 16);
9151
+ const height = 1 + (b27 | b28 << 8 | b29 << 16);
9152
+ const isAnimated = (b20 & 2) !== 0;
9153
+ let pages = 1;
9154
+ if (isAnimated) {
9155
+ let count = 0;
9156
+ let pos = 30;
9157
+ while (pos < buf.length - 8) {
9158
+ const type = buf.toString("ascii", pos, pos + 4);
9159
+ const len = buf.readUInt32LE(pos + 4);
9160
+ if (type === "ANMF") count++;
9161
+ pos += 8 + len + (len & 1);
9162
+ }
9163
+ pages = Math.max(1, count);
9164
+ }
9165
+ return { width, height, format: "webp", pages };
9166
+ }
9167
+ }
9168
+ if (buf[0] === 66 && buf[1] === 77 && buf.length >= 26) {
9169
+ const width = buf.readInt32LE(18);
9170
+ const height = Math.abs(buf.readInt32LE(22));
9171
+ return { width, height, format: "bmp", pages: 1 };
9172
+ }
9173
+ const isTiffLE = buf[0] === 73 && buf[1] === 73 && buf[2] === 42 && buf[3] === 0;
9174
+ const isTiffBE = buf[0] === 77 && buf[1] === 77 && buf[2] === 0 && buf[3] === 42;
9175
+ if (isTiffLE || isTiffBE) {
9176
+ const isLE = isTiffLE;
9177
+ let ifdOffset = isLE ? buf.readUInt32LE(4) : buf.readUInt32BE(4);
9178
+ let width = 0;
9179
+ let height = 0;
9180
+ let pages = 0;
9181
+ const seenIfdOffsets = /* @__PURE__ */ new Set();
9182
+ while (ifdOffset > 0 && ifdOffset + 2 <= buf.length) {
9183
+ if (seenIfdOffsets.has(ifdOffset)) break;
9184
+ seenIfdOffsets.add(ifdOffset);
9185
+ pages++;
9186
+ const numEntries = isLE ? buf.readUInt16LE(ifdOffset) : buf.readUInt16BE(ifdOffset);
9187
+ let ifdPos = ifdOffset + 2;
9188
+ for (let e = 0; e < numEntries && ifdPos + 12 <= buf.length; e++, ifdPos += 12) {
9189
+ const tag = isLE ? buf.readUInt16LE(ifdPos) : buf.readUInt16BE(ifdPos);
9190
+ if (tag === 256 && width === 0) {
9191
+ const type = isLE ? buf.readUInt16LE(ifdPos + 2) : buf.readUInt16BE(ifdPos + 2);
9192
+ width = type === 3 ? isLE ? buf.readUInt16LE(ifdPos + 8) : buf.readUInt16BE(ifdPos + 8) : isLE ? buf.readUInt32LE(ifdPos + 8) : buf.readUInt32BE(ifdPos + 8);
9193
+ } else if (tag === 257 && height === 0) {
9194
+ const type = isLE ? buf.readUInt16LE(ifdPos + 2) : buf.readUInt16BE(ifdPos + 2);
9195
+ height = type === 3 ? isLE ? buf.readUInt16LE(ifdPos + 8) : buf.readUInt16BE(ifdPos + 8) : isLE ? buf.readUInt32LE(ifdPos + 8) : buf.readUInt32BE(ifdPos + 8);
9196
+ }
9197
+ }
9198
+ const nextIfdPos = ifdOffset + 2 + numEntries * 12;
9199
+ if (nextIfdPos + 4 <= buf.length) {
9200
+ ifdOffset = isLE ? buf.readUInt32LE(nextIfdPos) : buf.readUInt32BE(nextIfdPos);
9201
+ } else {
9202
+ break;
9203
+ }
9204
+ }
9205
+ if (width > 0 && height > 0) {
9206
+ return { width, height, format: "tiff", pages: Math.max(1, pages) };
9207
+ }
9208
+ }
9209
+ const sample = buf.subarray(0, Math.min(buf.length, 4096)).toString("utf8");
9210
+ if (sample.includes("<svg")) {
9211
+ const widthMatch = /width=["']([0-9.]+)(px)?["']/i.exec(sample);
9212
+ const heightMatch = /height=["']([0-9.]+)(px)?["']/i.exec(sample);
9213
+ const viewBoxMatch = /viewBox=["']([0-9. -]+)["']/i.exec(sample);
9214
+ let width = widthMatch && widthMatch[1] ? parseFloat(widthMatch[1]) : 0;
9215
+ let height = heightMatch && heightMatch[1] ? parseFloat(heightMatch[1]) : 0;
9216
+ if ((!width || !height) && viewBoxMatch && viewBoxMatch[1]) {
9217
+ const parts = viewBoxMatch[1].trim().split(/[\s,]+/).map(parseFloat);
9218
+ if (parts.length === 4 && parts[2] !== void 0 && parts[3] !== void 0) {
9219
+ width = parts[2];
9220
+ height = parts[3];
9221
+ }
9222
+ }
9223
+ if (width > 0 && height > 0) {
9224
+ return { width: Math.round(width), height: Math.round(height), format: "svg", pages: 1 };
9225
+ }
9226
+ return { width: 100, height: 100, format: "svg", pages: 1 };
9227
+ }
9228
+ return null;
9229
+ }
9230
+ function decodePng(buf) {
9231
+ if (buf.length < 8 || buf[0] !== 137 || buf[1] !== 80 || buf[2] !== 78 || buf[3] !== 71) {
9232
+ throw new Error("Invalid PNG signature");
9233
+ }
9234
+ let pos = 8;
9235
+ let width = 0;
9236
+ let height = 0;
9237
+ let colorType = 6;
9238
+ const idatChunks = [];
9239
+ let palette = null;
9240
+ let trns = null;
9241
+ while (pos < buf.length) {
9242
+ const len = buf.readUInt32BE(pos);
9243
+ const type = buf.toString("ascii", pos + 4, pos + 8);
9244
+ const data = buf.subarray(pos + 8, pos + 8 + len);
9245
+ pos += 8 + len + 4;
9246
+ if (type === "IHDR") {
9247
+ width = data.readUInt32BE(0);
9248
+ height = data.readUInt32BE(4);
9249
+ const bitDepth = data[8] ?? 8;
9250
+ colorType = data[9] ?? 6;
9251
+ if (bitDepth !== 8) {
9252
+ throw new Error("Unsupported PNG bit depth: " + bitDepth);
9253
+ }
9254
+ const interlace = data[12] ?? 0;
9255
+ if (interlace !== 0) {
9256
+ throw new Error("Unsupported PNG interlace method: " + interlace);
9257
+ }
9258
+ } else if (type === "PLTE") {
9259
+ palette = data;
9260
+ } else if (type === "tRNS") {
9261
+ trns = data;
9262
+ } else if (type === "IDAT") {
9263
+ idatChunks.push(data);
9264
+ } else if (type === "IEND") {
9265
+ break;
9266
+ }
9267
+ }
9268
+ if (width === 0 || height === 0) {
9269
+ throw new Error("Missing PNG IHDR chunk");
9270
+ }
9271
+ let bpp = 4;
9272
+ if (colorType === 0) bpp = 1;
9273
+ else if (colorType === 2) bpp = 3;
9274
+ else if (colorType === 3) bpp = 1;
9275
+ else if (colorType === 4) bpp = 2;
9276
+ else if (colorType === 6) bpp = 4;
9277
+ assertDecodableSize("PNG", width, height, 4);
9278
+ const rowBytes = width * bpp;
9279
+ const rowSize = 1 + rowBytes;
9280
+ const maxRawBytes = height * rowSize;
9281
+ const compressed = Buffer.concat(idatChunks);
9282
+ let decompressed;
9283
+ try {
9284
+ decompressed = zlib.inflateSync(compressed, { maxOutputLength: maxRawBytes });
9285
+ } catch (err) {
9286
+ const msg = err instanceof Error ? err.message : String(err);
9287
+ throw new Error(`PNG image data exceeds the ${maxRawBytes} bytes its ${width}x${height} header allows: ${msg}`, {
9288
+ cause: err
9289
+ });
9290
+ }
9291
+ const outRgba = Buffer.alloc(width * height * 4);
9292
+ const priorRow = Buffer.alloc(rowBytes);
9293
+ const currRow = Buffer.alloc(rowBytes);
9294
+ for (let y = 0; y < height; y++) {
9295
+ const filter = decompressed[y * rowSize] ?? 0;
9296
+ const rawOffset = y * rowSize + 1;
9297
+ for (let x = 0; x < rowBytes; x++) {
9298
+ const rawVal = decompressed[rawOffset + x] ?? 0;
9299
+ const a = x >= bpp ? currRow[x - bpp] ?? 0 : 0;
9300
+ const b = priorRow[x] ?? 0;
9301
+ const c = x >= bpp ? priorRow[x - bpp] ?? 0 : 0;
9302
+ let val = rawVal;
9303
+ if (filter === 0) {
9304
+ val = rawVal;
9305
+ } else if (filter === 1) {
9306
+ val = rawVal + a & 255;
9307
+ } else if (filter === 2) {
9308
+ val = rawVal + b & 255;
9309
+ } else if (filter === 3) {
9310
+ val = rawVal + Math.floor((a + b) / 2) & 255;
9311
+ } else if (filter === 4) {
9312
+ val = rawVal + paethPredictor(a, b, c) & 255;
9313
+ }
9314
+ currRow[x] = val;
9315
+ }
9316
+ for (let x = 0; x < width; x++) {
9317
+ const outIdx = (y * width + x) * 4;
9318
+ if (colorType === 6) {
9319
+ outRgba[outIdx] = currRow[x * 4] ?? 0;
9320
+ outRgba[outIdx + 1] = currRow[x * 4 + 1] ?? 0;
9321
+ outRgba[outIdx + 2] = currRow[x * 4 + 2] ?? 0;
9322
+ outRgba[outIdx + 3] = currRow[x * 4 + 3] ?? 255;
9323
+ } else if (colorType === 2) {
9324
+ outRgba[outIdx] = currRow[x * 3] ?? 0;
9325
+ outRgba[outIdx + 1] = currRow[x * 3 + 1] ?? 0;
9326
+ outRgba[outIdx + 2] = currRow[x * 3 + 2] ?? 0;
9327
+ outRgba[outIdx + 3] = 255;
9328
+ } else if (colorType === 0) {
9329
+ const g = currRow[x] ?? 0;
9330
+ outRgba[outIdx] = g;
9331
+ outRgba[outIdx + 1] = g;
9332
+ outRgba[outIdx + 2] = g;
9333
+ outRgba[outIdx + 3] = 255;
9334
+ } else if (colorType === 4) {
9335
+ const g = currRow[x * 2] ?? 0;
9336
+ outRgba[outIdx] = g;
9337
+ outRgba[outIdx + 1] = g;
9338
+ outRgba[outIdx + 2] = g;
9339
+ outRgba[outIdx + 3] = currRow[x * 2 + 1] ?? 255;
9340
+ } else if (colorType === 3 && palette) {
9341
+ const pVal = currRow[x] ?? 0;
9342
+ const pIdx = pVal * 3;
9343
+ outRgba[outIdx] = palette[pIdx] ?? 0;
9344
+ outRgba[outIdx + 1] = palette[pIdx + 1] ?? 0;
9345
+ outRgba[outIdx + 2] = palette[pIdx + 2] ?? 0;
9346
+ outRgba[outIdx + 3] = trns && trns.length > pVal ? trns[pVal] ?? 255 : 255;
9347
+ }
9348
+ }
9349
+ currRow.copy(priorRow);
9350
+ }
9351
+ return { width, height, data: outRgba };
9352
+ }
9353
+ function makePngChunk(type, data) {
9354
+ const len = data.length;
9355
+ const chunk = Buffer.alloc(8 + len + 4);
9356
+ chunk.writeUInt32BE(len, 0);
9357
+ chunk.write(type, 4, 4, "ascii");
9358
+ Buffer.from(data.buffer, data.byteOffset, data.byteLength).copy(chunk, 8);
9359
+ const typeAndData = chunk.subarray(4, 8 + len);
9360
+ chunk.writeUInt32BE(crc32(typeAndData), 8 + len);
9361
+ return chunk;
9362
+ }
9363
+ function encodePng(width, height, rgba) {
9364
+ const ihdr = Buffer.alloc(13);
9365
+ ihdr.writeUInt32BE(width, 0);
9366
+ ihdr.writeUInt32BE(height, 4);
9367
+ ihdr[8] = 8;
9368
+ ihdr[9] = 6;
9369
+ ihdr[10] = 0;
9370
+ ihdr[11] = 0;
9371
+ ihdr[12] = 0;
9372
+ const rowSize = 1 + width * 4;
9373
+ const rawData = Buffer.alloc(rowSize * height);
9374
+ for (let y = 0; y < height; y++) {
9375
+ const rowOffset = y * rowSize;
9376
+ rawData[rowOffset] = 0;
9377
+ Buffer.from(rgba.buffer, rgba.byteOffset + y * width * 4, width * 4).copy(rawData, rowOffset + 1);
9378
+ }
9379
+ const idatData = zlib.deflateSync(rawData, { level: 6 });
9380
+ const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
9381
+ const ihdrChunk = makePngChunk("IHDR", ihdr);
9382
+ const idatChunk = makePngChunk("IDAT", idatData);
9383
+ const iendChunk = makePngChunk("IEND", Buffer.alloc(0));
9384
+ return Buffer.concat([signature, ihdrChunk, idatChunk, iendChunk]);
9385
+ }
9386
+ function decodeBmp(buf) {
9387
+ if (buf.length < 54 || buf[0] !== 66 || buf[1] !== 77) {
9388
+ throw new Error("Invalid BMP signature");
9389
+ }
9390
+ const pixelOffset = buf.readUInt32LE(10);
9391
+ const width = buf.readInt32LE(18);
9392
+ let height = buf.readInt32LE(22);
9393
+ const topDown = height < 0;
9394
+ height = Math.abs(height);
9395
+ const bpp = buf.readUInt16LE(28);
9396
+ const compression = buf.readUInt32LE(30);
9397
+ if (compression !== 0 && compression !== 3) {
9398
+ throw new Error("Unsupported BMP compression: " + compression);
9399
+ }
9400
+ if (bpp !== 24 && bpp !== 32) {
9401
+ throw new Error("Unsupported BMP bit depth: " + bpp);
9402
+ }
9403
+ assertDecodableSize("BMP", width, height, 4);
9404
+ const outRgba = Buffer.alloc(width * height * 4);
9405
+ const rowStride = Math.floor((bpp * width + 31) / 32) * 4;
9406
+ for (let y = 0; y < height; y++) {
9407
+ const srcY = topDown ? y : height - 1 - y;
9408
+ const rowOffset = pixelOffset + srcY * rowStride;
9409
+ for (let x = 0; x < width; x++) {
9410
+ const outIdx = (y * width + x) * 4;
9411
+ if (bpp === 24) {
9412
+ const pxOffset = rowOffset + x * 3;
9413
+ outRgba[outIdx] = buf[pxOffset + 2] ?? 0;
9414
+ outRgba[outIdx + 1] = buf[pxOffset + 1] ?? 0;
9415
+ outRgba[outIdx + 2] = buf[pxOffset] ?? 0;
9416
+ outRgba[outIdx + 3] = 255;
9417
+ } else if (bpp === 32) {
9418
+ const pxOffset = rowOffset + x * 4;
9419
+ outRgba[outIdx] = buf[pxOffset + 2] ?? 0;
9420
+ outRgba[outIdx + 1] = buf[pxOffset + 1] ?? 0;
9421
+ outRgba[outIdx + 2] = buf[pxOffset] ?? 0;
9422
+ outRgba[outIdx + 3] = buf[pxOffset + 3] ?? 255;
9423
+ }
9424
+ }
9425
+ }
9426
+ return { width, height, data: outRgba };
9427
+ }
9428
+ function decodeGif(buf, opts) {
9429
+ const reader = new import_omggif.default.GifReader(buf);
9430
+ const width = reader.width;
9431
+ const height = reader.height;
9432
+ const wanted = Math.min(reader.numFrames(), opts?.maxFrames ?? Number.POSITIVE_INFINITY);
9433
+ assertDecodableSize("GIF", width, height, 4, wanted);
9434
+ const frames = [];
9435
+ for (let i = 0; i < wanted; i++) {
9436
+ const frameInfo = reader.frameInfo(i);
9437
+ const frameRgba = Buffer.alloc(width * height * 4);
9438
+ reader.decodeAndBlitFrameRGBA(i, frameRgba);
9439
+ frames.push({
9440
+ width,
9441
+ height,
9442
+ x: frameInfo.x,
9443
+ y: frameInfo.y,
9444
+ delay: frameInfo.delay,
9445
+ disposal: frameInfo.disposal,
9446
+ data: frameRgba
9447
+ });
9448
+ }
9449
+ return { width, height, frames };
9450
+ }
9451
+ function quantizeRgbaToIndexed(rgba, width, height) {
9452
+ const palette = [];
9453
+ for (let r = 0; r < 8; r++) {
9454
+ for (let g = 0; g < 8; g++) {
9455
+ for (let b = 0; b < 4; b++) {
9456
+ const red = Math.round(r / 7 * 255);
9457
+ const green = Math.round(g / 7 * 255);
9458
+ const blue = Math.round(b / 3 * 255);
9459
+ palette.push(red << 16 | green << 8 | blue);
9460
+ }
9461
+ }
9462
+ }
9463
+ const numPixels = width * height;
9464
+ const indexedPixels = new Array(numPixels);
9465
+ for (let i = 0; i < numPixels; i++) {
9466
+ const r = rgba[i * 4] ?? 0;
9467
+ const g = rgba[i * 4 + 1] ?? 0;
9468
+ const b = rgba[i * 4 + 2] ?? 0;
9469
+ const rIdx = Math.min(7, Math.floor(r / 256 * 8));
9470
+ const gIdx = Math.min(7, Math.floor(g / 256 * 8));
9471
+ const bIdx = Math.min(3, Math.floor(b / 256 * 4));
9472
+ indexedPixels[i] = rIdx << 5 | gIdx << 2 | bIdx;
9473
+ }
9474
+ return { indexedPixels, palette };
9475
+ }
9476
+ function decodeJpeg(buf) {
9477
+ const decoded = import_jpeg_js.default.decode(buf, { useTArray: true });
9478
+ return {
9479
+ width: decoded.width,
9480
+ height: decoded.height,
9481
+ data: Buffer.from(decoded.data)
9482
+ };
9483
+ }
9484
+ function encodeJpeg(width, height, rgba, quality = 80) {
9485
+ const encoded = import_jpeg_js.default.encode({
9486
+ data: Buffer.from(rgba.buffer, rgba.byteOffset, rgba.byteLength),
9487
+ width,
9488
+ height
9489
+ }, quality);
9490
+ return encoded.data;
9491
+ }
9492
+ function resizeRgba(srcRgba, srcW, srcH, dstW, dstH) {
9493
+ if (srcW === dstW && srcH === dstH) {
9494
+ return Buffer.from(srcRgba.buffer, srcRgba.byteOffset, srcRgba.byteLength);
9495
+ }
9496
+ const dst = Buffer.alloc(dstW * dstH * 4);
9497
+ const scaleX = srcW / dstW;
9498
+ const scaleY = srcH / dstH;
9499
+ for (let dy = 0; dy < dstH; dy++) {
9500
+ const srcY = (dy + 0.5) * scaleY - 0.5;
9501
+ const y0 = Math.max(0, Math.min(srcH - 1, Math.floor(srcY)));
9502
+ const y1 = Math.max(0, Math.min(srcH - 1, y0 + 1));
9503
+ const fy = Math.max(0, Math.min(1, srcY - y0));
9504
+ const fy1 = 1 - fy;
9505
+ const dstRowOffset = dy * dstW * 4;
9506
+ const srcRow0 = y0 * srcW * 4;
9507
+ const srcRow1 = y1 * srcW * 4;
9508
+ for (let dx = 0; dx < dstW; dx++) {
9509
+ const srcX = (dx + 0.5) * scaleX - 0.5;
9510
+ const x0 = Math.max(0, Math.min(srcW - 1, Math.floor(srcX)));
9511
+ const x1 = Math.max(0, Math.min(srcW - 1, x0 + 1));
9512
+ const fx = Math.max(0, Math.min(1, srcX - x0));
9513
+ const fx1 = 1 - fx;
9514
+ const w00 = fx1 * fy1;
9515
+ const w10 = fx * fy1;
9516
+ const w01 = fx1 * fy;
9517
+ const w11 = fx * fy;
9518
+ const idx00 = srcRow0 + x0 * 4;
9519
+ const idx10 = srcRow0 + x1 * 4;
9520
+ const idx01 = srcRow1 + x0 * 4;
9521
+ const idx11 = srcRow1 + x1 * 4;
9522
+ const p00_r = srcRgba[idx00] ?? 0;
9523
+ const p00_g = srcRgba[idx00 + 1] ?? 0;
9524
+ const p00_b = srcRgba[idx00 + 2] ?? 0;
9525
+ const p00_a = srcRgba[idx00 + 3] ?? 255;
9526
+ const p10_r = srcRgba[idx10] ?? 0;
9527
+ const p10_g = srcRgba[idx10 + 1] ?? 0;
9528
+ const p10_b = srcRgba[idx10 + 2] ?? 0;
9529
+ const p10_a = srcRgba[idx10 + 3] ?? 255;
9530
+ const p01_r = srcRgba[idx01] ?? 0;
9531
+ const p01_g = srcRgba[idx01 + 1] ?? 0;
9532
+ const p01_b = srcRgba[idx01 + 2] ?? 0;
9533
+ const p01_a = srcRgba[idx01 + 3] ?? 255;
9534
+ const p11_r = srcRgba[idx11] ?? 0;
9535
+ const p11_g = srcRgba[idx11 + 1] ?? 0;
9536
+ const p11_b = srcRgba[idx11 + 2] ?? 0;
9537
+ const p11_a = srcRgba[idx11 + 3] ?? 255;
9538
+ const dstIdx = dstRowOffset + dx * 4;
9539
+ dst[dstIdx] = Math.round(w00 * p00_r + w10 * p10_r + w01 * p01_r + w11 * p11_r);
9540
+ dst[dstIdx + 1] = Math.round(w00 * p00_g + w10 * p10_g + w01 * p01_g + w11 * p11_g);
9541
+ dst[dstIdx + 2] = Math.round(w00 * p00_b + w10 * p10_b + w01 * p01_b + w11 * p11_b);
9542
+ dst[dstIdx + 3] = Math.round(w00 * p00_a + w10 * p10_a + w01 * p01_a + w11 * p11_a);
9543
+ }
9544
+ }
9545
+ return dst;
9546
+ }
9547
+ function calculateFitInside(width, height, maxDimension) {
9548
+ if (width <= maxDimension && height <= maxDimension) {
9549
+ return { width, height };
9550
+ }
9551
+ const scale = maxDimension / Math.max(width, height);
9552
+ return {
9553
+ width: Math.max(1, Math.round(width * scale)),
9554
+ height: Math.max(1, Math.round(height * scale))
9555
+ };
9556
+ }
9557
+
6211
9558
  // src/image_ocr.ts
9559
+ init_define_import_meta_env();
6212
9560
  import { spawn } from "node:child_process";
6213
9561
  import { createHash as createHash2 } from "node:crypto";
6214
9562
  import * as fs9 from "node:fs";
@@ -6434,36 +9782,34 @@ function formatShrinkSummary(result, subject) {
6434
9782
  const dataUrl = `data:image/${result.format};base64,${result.data.toString("base64")}`;
6435
9783
  return { summary, dataUrl };
6436
9784
  }
6437
- var loadSharp = createLazyModuleLoader(async () => {
6438
- const mod = await import("sharp");
6439
- return mod.default;
6440
- }, "image shrink disabled (sharp unavailable)");
6441
9785
  function isImagePath(p) {
6442
9786
  return IMAGE_EXTENSIONS.has(path6.extname(p).toLowerCase());
6443
9787
  }
6444
9788
  var ImageDecodeError = class extends Error {
6445
9789
  };
6446
9790
  async function probeImageMeta(input) {
6447
- const sharp = await loadSharp();
6448
- if (sharp === null) return null;
6449
- try {
6450
- const cfg = loadConfig().image_shrink;
6451
- const limitInputPixels = cfg.max_image_pixels > 0 ? cfg.max_image_pixels : false;
6452
- const meta = await sharp(input, { limitInputPixels }).metadata();
6453
- return { width: meta.width ?? 0, height: meta.height ?? 0, format: meta.format ?? null, pages: meta.pages ?? 1 };
6454
- } catch (e) {
6455
- throw new ImageDecodeError(e?.message ?? "image could not be decoded");
9791
+ const meta = probeBufferMeta(input);
9792
+ if (meta === null) {
9793
+ throw new ImageDecodeError("image could not be decoded");
9794
+ }
9795
+ const cfg = loadConfig().image_shrink;
9796
+ const limitInputPixels = cfg.max_image_pixels > 0 ? cfg.max_image_pixels : false;
9797
+ if (limitInputPixels !== false && meta.width * meta.height > limitInputPixels) {
9798
+ throw new ImageDecodeError(`Input image exceeds pixel limit ${limitInputPixels}`);
6456
9799
  }
9800
+ return {
9801
+ width: meta.width,
9802
+ height: meta.height,
9803
+ format: meta.format,
9804
+ pages: meta.pages
9805
+ };
6457
9806
  }
6458
9807
  async function imageQualifiesForShrink(input) {
6459
9808
  if (input.length >= DEFAULT_SIZE_THRESHOLD_BYTES) return true;
6460
- const sharp = await loadSharp();
6461
- if (sharp === null) return false;
6462
9809
  try {
6463
- const cfg = loadConfig().image_shrink;
6464
- const limitInputPixels = cfg.max_image_pixels > 0 ? cfg.max_image_pixels : false;
6465
- const meta = await sharp(input, { limitInputPixels }).metadata();
6466
- return Math.max(meta.width ?? 0, meta.height ?? 0) > DEFAULT_MAX_DIMENSION;
9810
+ const meta = await probeImageMeta(input);
9811
+ if (meta === null) return false;
9812
+ return Math.max(meta.width, meta.height) > DEFAULT_MAX_DIMENSION;
6467
9813
  } catch {
6468
9814
  return false;
6469
9815
  }
@@ -6473,34 +9819,77 @@ async function shrinkImage(input, opts) {
6473
9819
  const maxDimension = opts?.maxDimension ?? DEFAULT_MAX_DIMENSION;
6474
9820
  const quality = opts?.quality ?? cfg.jpeg_quality;
6475
9821
  const sizeThreshold = opts?.sizeThresholdBytes ?? DEFAULT_SIZE_THRESHOLD_BYTES;
6476
- const limitInputPixels = cfg.max_image_pixels > 0 ? cfg.max_image_pixels : false;
6477
9822
  const originalBytes = input.length;
6478
9823
  if (originalBytes < sizeThreshold) return null;
6479
- const sharp = await loadSharp();
6480
- if (sharp === null) return null;
9824
+ let inputMeta;
9825
+ try {
9826
+ inputMeta = await probeImageMeta(input);
9827
+ } catch {
9828
+ return null;
9829
+ }
9830
+ if (!inputMeta || inputMeta.width <= 0 || inputMeta.height <= 0) return null;
6481
9831
  try {
6482
- const inputMeta = await sharp(input, { limitInputPixels }).metadata();
6483
9832
  const isAnimated = (inputMeta.pages ?? 1) > 1;
6484
- const webpBuf = await sharp(input, { limitInputPixels, animated: isAnimated }).rotate().resize({ width: maxDimension, height: maxDimension, fit: "inside", withoutEnlargement: true }).webp({ quality }).toBuffer();
6485
- let data = webpBuf;
6486
- let format = "webp";
6487
- if (!isAnimated) {
6488
- const jpegBuf = await sharp(input, { limitInputPixels }).rotate().resize({ width: maxDimension, height: maxDimension, fit: "inside", withoutEnlargement: true }).jpeg({ quality, mozjpeg: true }).toBuffer();
6489
- if (jpegBuf.length < webpBuf.length) {
6490
- data = jpegBuf;
6491
- format = "jpeg";
9833
+ const { width: targetW, height: targetH } = calculateFitInside(inputMeta.width, inputMeta.height, maxDimension);
9834
+ if (isAnimated && inputMeta.format === "gif") {
9835
+ const decodedGif = decodeGif(input);
9836
+ assertDecodableSize("GIF output", targetW, targetH, 5, decodedGif.frames.length);
9837
+ const outBuf = Buffer.alloc(targetW * targetH * 5 * decodedGif.frames.length + 4096);
9838
+ const gifWriter = new import_omggif2.default.GifWriter(outBuf, targetW, targetH, { loop: 0 });
9839
+ for (const frame of decodedGif.frames) {
9840
+ const resizedFrameRgba = resizeRgba(frame.data, frame.width, frame.height, targetW, targetH);
9841
+ const { indexedPixels, palette } = quantizeRgbaToIndexed(resizedFrameRgba, targetW, targetH);
9842
+ gifWriter.addFrame(0, 0, targetW, targetH, indexedPixels, {
9843
+ palette,
9844
+ delay: frame.delay,
9845
+ disposal: frame.disposal
9846
+ });
6492
9847
  }
9848
+ const data2 = outBuf.subarray(0, gifWriter.end());
9849
+ if (data2.length >= originalBytes) return null;
9850
+ return {
9851
+ data: data2,
9852
+ originalBytes,
9853
+ shrunkBytes: data2.length,
9854
+ originalWidth: inputMeta.width,
9855
+ originalHeight: inputMeta.height,
9856
+ width: targetW,
9857
+ height: targetH,
9858
+ format: "gif"
9859
+ };
9860
+ }
9861
+ let srcRgba;
9862
+ if (inputMeta.format === "png") {
9863
+ srcRgba = decodePng(input).data;
9864
+ } else if (inputMeta.format === "jpeg") {
9865
+ srcRgba = decodeJpeg(input).data;
9866
+ } else if (inputMeta.format === "bmp") {
9867
+ srcRgba = decodeBmp(input).data;
9868
+ } else if (inputMeta.format === "gif") {
9869
+ const firstFrame = decodeGif(input, { maxFrames: 1 }).frames[0];
9870
+ if (!firstFrame) return null;
9871
+ srcRgba = firstFrame.data;
9872
+ } else {
9873
+ return null;
9874
+ }
9875
+ const dstRgba = resizeRgba(srcRgba, inputMeta.width, inputMeta.height, targetW, targetH);
9876
+ const jpegBuf = encodeJpeg(targetW, targetH, dstRgba, quality);
9877
+ const pngBuf = encodePng(targetW, targetH, dstRgba);
9878
+ let data = jpegBuf;
9879
+ let format = "jpeg";
9880
+ if (pngBuf.length < jpegBuf.length) {
9881
+ data = pngBuf;
9882
+ format = "png";
6493
9883
  }
6494
9884
  if (data.length >= originalBytes) return null;
6495
- const meta = await sharp(data).metadata();
6496
9885
  return {
6497
9886
  data,
6498
9887
  originalBytes,
6499
9888
  shrunkBytes: data.length,
6500
- originalWidth: inputMeta.width ?? 0,
6501
- originalHeight: inputMeta.height ?? 0,
6502
- width: meta.width ?? 0,
6503
- height: meta.height ?? 0,
9889
+ originalWidth: inputMeta.width,
9890
+ originalHeight: inputMeta.height,
9891
+ width: targetW,
9892
+ height: targetH,
6504
9893
  format
6505
9894
  };
6506
9895
  } catch {
@@ -6521,6 +9910,17 @@ function imageShrinkCacheDir() {
6521
9910
  function shrinkCacheKey(originalPath, size, mtimeMs, quality) {
6522
9911
  return createHash3("sha256").update(`${originalPath}:${size}:${mtimeMs}:${quality}`).digest("hex").slice(0, 16);
6523
9912
  }
9913
+ var SHRINK_CACHE_EXTENSION = /* @__PURE__ */ new Map([
9914
+ ["jpeg", ".jpg"],
9915
+ ["png", ".png"],
9916
+ ["gif", ".gif"]
9917
+ ]);
9918
+ var SHRINK_CACHE_FORMAT = /* @__PURE__ */ new Map([
9919
+ [".jpg", "jpeg"],
9920
+ [".png", "png"],
9921
+ [".gif", "gif"],
9922
+ [".webp", "webp"]
9923
+ ]);
6524
9924
  function findCachedShrink(originalPath, size, mtimeMs, quality) {
6525
9925
  const prefix = `token-goat-shrink-${shrinkCacheKey(originalPath, size, mtimeMs, quality)}-`;
6526
9926
  const dir = imageShrinkCacheDir();
@@ -6532,11 +9932,13 @@ function findCachedShrink(originalPath, size, mtimeMs, quality) {
6532
9932
  }
6533
9933
  for (const file of entries) {
6534
9934
  if (!file.startsWith(prefix)) continue;
6535
- const m = /^(\d+)x(\d+)(\.webp|\.jpg)$/.exec(file.slice(prefix.length));
9935
+ const m = /^(\d+)x(\d+)(\.webp|\.jpg|\.png|\.gif)$/.exec(file.slice(prefix.length));
6536
9936
  if (m === null) continue;
9937
+ const format = SHRINK_CACHE_FORMAT.get(m[3] ?? "");
9938
+ if (format === void 0) continue;
6537
9939
  return {
6538
9940
  filePath: path6.join(dir, file),
6539
- format: m[3] === ".jpg" ? "jpeg" : "webp",
9941
+ format,
6540
9942
  originalWidth: Number(m[1]),
6541
9943
  originalHeight: Number(m[2])
6542
9944
  };
@@ -6548,7 +9950,8 @@ function writeCachedShrink(originalPath, result, mtimeMs, quality) {
6548
9950
  const dir = imageShrinkCacheDir();
6549
9951
  ensureDirSync(dir);
6550
9952
  const key = shrinkCacheKey(originalPath, result.originalBytes, mtimeMs, quality);
6551
- const ext = result.format === "jpeg" ? ".jpg" : ".webp";
9953
+ const ext = SHRINK_CACHE_EXTENSION.get(result.format);
9954
+ if (ext === void 0) return;
6552
9955
  atomicWriteBytes(path6.join(dir, `token-goat-shrink-${key}-${result.originalWidth}x${result.originalHeight}${ext}`), result.data);
6553
9956
  } catch {
6554
9957
  }
@@ -6655,7 +10058,11 @@ async function preReadImageHandler(event) {
6655
10058
  }
6656
10059
  registerHook("pre_tool_use", preReadImageHandler, { toolName: "Read" });
6657
10060
 
10061
+ // src/embeddings.ts
10062
+ init_define_import_meta_env();
10063
+
6658
10064
  // src/embed_model.ts
10065
+ init_define_import_meta_env();
6659
10066
  import { createHash as createHash4 } from "node:crypto";
6660
10067
  import * as fs11 from "node:fs";
6661
10068
  import { createRequire as createRequire2 } from "node:module";
@@ -6663,6 +10070,7 @@ import * as path7 from "node:path";
6663
10070
  import { pipeline } from "node:stream/promises";
6664
10071
 
6665
10072
  // src/embed_tokenizer.ts
10073
+ init_define_import_meta_env();
6666
10074
  var MAX_SEQUENCE_TOKENS = 512;
6667
10075
  var UnsupportedTokenizerError = class extends Error {
6668
10076
  constructor(message) {
@@ -7685,15 +11093,22 @@ function _pathPriorityPenalty(filePath) {
7685
11093
  return 0;
7686
11094
  }
7687
11095
 
11096
+ // src/parser_fingerprint.ts
11097
+ init_define_import_meta_env();
11098
+ var PARSER_FINGERPRINT = "4659c517f042a452";
11099
+
7688
11100
  // src/hooks_read.ts
11101
+ init_define_import_meta_env();
7689
11102
  import * as fs17 from "node:fs";
7690
11103
  import * as path13 from "node:path";
7691
11104
 
7692
11105
  // src/compact.ts
11106
+ init_define_import_meta_env();
7693
11107
  import * as fs12 from "node:fs";
7694
11108
  import * as path8 from "node:path";
7695
11109
 
7696
11110
  // src/overflow_guard.ts
11111
+ init_define_import_meta_env();
7697
11112
  function estimateTokensFromLength(length) {
7698
11113
  return Math.max(1, Math.floor(Math.max(0, length) / 3) + 1);
7699
11114
  }
@@ -7923,8 +11338,8 @@ function getContextPressure(cache) {
7923
11338
  const rawTotal = pressureRawTotal(cache);
7924
11339
  const baseline = cache.pressureBaselineTokens ?? 0;
7925
11340
  const total = Math.max(0, rawTotal - baseline);
7926
- const window = getEffectiveAutoTriggerWindow();
7927
- const fill = total / window;
11341
+ const window2 = getEffectiveAutoTriggerWindow();
11342
+ const fill = total / window2;
7928
11343
  return {
7929
11344
  fillFraction: fill,
7930
11345
  tier: tierForFraction(fill)
@@ -8278,6 +11693,7 @@ function buildManifestWithCount(sessionId, opts) {
8278
11693
  }
8279
11694
 
8280
11695
  // src/snapshots.ts
11696
+ init_define_import_meta_env();
8281
11697
  import * as fs13 from "node:fs";
8282
11698
  import * as path9 from "node:path";
8283
11699
  var MAX_SNAPSHOTS_PER_SESSION = 150;
@@ -8479,6 +11895,7 @@ function cleanup_stale(maxAgeHours = 24) {
8479
11895
  }
8480
11896
 
8481
11897
  // src/hints.ts
11898
+ init_define_import_meta_env();
8482
11899
  var HINT_PRIORITY_MEDIUM = 3;
8483
11900
  function buildPackageManifestHint(options) {
8484
11901
  try {
@@ -8508,7 +11925,11 @@ function _sanitizeHintPath(path26) {
8508
11925
  return path26.replace(/[\x00]/g, "").slice(0, 200);
8509
11926
  }
8510
11927
 
11928
+ // src/hints/markdown_hints.ts
11929
+ init_define_import_meta_env();
11930
+
8511
11931
  // src/markdown_lines.ts
11932
+ init_define_import_meta_env();
8512
11933
  function* eachUnfencedLine(lines2) {
8513
11934
  let fence = null;
8514
11935
  for (let i = 0; i < lines2.length; i++) {
@@ -8626,6 +12047,7 @@ function extractChangelogVersionHint(content, filePath) {
8626
12047
  }
8627
12048
 
8628
12049
  // src/hints/file_type_handler.ts
12050
+ init_define_import_meta_env();
8629
12051
  var FILE_TYPE_THRESHOLDS = {
8630
12052
  pdf: 0,
8631
12053
  // always intercept (any size)
@@ -8861,6 +12283,7 @@ function dispatchFileTypeHandler(filePath, content, contentLengthHint) {
8861
12283
  }
8862
12284
 
8863
12285
  // src/doc_compact.ts
12286
+ init_define_import_meta_env();
8864
12287
  import * as fs14 from "fs";
8865
12288
  import * as path10 from "path";
8866
12289
  var defaultSentencesPerSection = 2;
@@ -9072,6 +12495,7 @@ function compactDoc(filePath, heading) {
9072
12495
  }
9073
12496
 
9074
12497
  // src/evidence_cache.ts
12498
+ init_define_import_meta_env();
9075
12499
  import crypto from "node:crypto";
9076
12500
  import fs15 from "node:fs";
9077
12501
  import path11 from "node:path";
@@ -9201,6 +12625,7 @@ ${changed.map((entry) => `- ${entry.source} (use a fresh surgical read)`).join("
9201
12625
  }
9202
12626
 
9203
12627
  // src/notebook_compact.ts
12628
+ init_define_import_meta_env();
9204
12629
  import * as fs16 from "node:fs";
9205
12630
  import * as path12 from "node:path";
9206
12631
  var NB_STRIP_MIN_SAVINGS = 4096;
@@ -9294,6 +12719,120 @@ function getOrCreateSidecar(rawBytes, cacheRoot, opts = {}) {
9294
12719
  return [sidecarPath, true];
9295
12720
  }
9296
12721
 
12722
+ // src/code_fold.ts
12723
+ init_define_import_meta_env();
12724
+ var FOLDABLE_KINDS = /* @__PURE__ */ new Set(["function", "method", "func", "def", "fn", "procedure", "constructor", "variable"]);
12725
+ var MIN_FOLDED_ROWS = 3;
12726
+ function planBodyFolds(rows, spans, keep, minSpan) {
12727
+ if (rows.length === 0 || spans.length === 0 || keep < 1) return [];
12728
+ const rowAt = /* @__PURE__ */ new Map();
12729
+ for (let i = 0; i < rows.length; i++) {
12730
+ const row = rows[i];
12731
+ if (row !== void 0) rowAt.set(row.no, i);
12732
+ }
12733
+ const ordered = [...spans].sort((a, b) => a.lineStart - b.lineStart || b.lineEnd - a.lineEnd);
12734
+ const folds = [];
12735
+ let foldedThrough = -1;
12736
+ for (const span of ordered) {
12737
+ if (!FOLDABLE_KINDS.has(span.kind)) continue;
12738
+ if (span.lineEnd - span.lineStart + 1 < minSpan) continue;
12739
+ if (span.lineStart <= foldedThrough) continue;
12740
+ const firstFolded = span.lineStart + keep;
12741
+ if (firstFolded > span.lineEnd) continue;
12742
+ let startIdx = -1;
12743
+ let endIdx = -1;
12744
+ for (let line = firstFolded; line <= span.lineEnd; line++) {
12745
+ const idx = rowAt.get(line);
12746
+ if (idx === void 0) continue;
12747
+ if (startIdx < 0) startIdx = idx;
12748
+ endIdx = idx;
12749
+ }
12750
+ if (startIdx < 0 || endIdx < startIdx) continue;
12751
+ const len = endIdx - startIdx + 1;
12752
+ const firstRow = rows[startIdx];
12753
+ const lastRow = rows[endIdx];
12754
+ if (firstRow === void 0 || lastRow === void 0) continue;
12755
+ if (lastRow.no - firstRow.no + 1 !== len) continue;
12756
+ if (len < MIN_FOLDED_ROWS) continue;
12757
+ folds.push({ startIdx, len, name: span.name, kind: "body", firstLine: firstRow.no, lastLine: lastRow.no });
12758
+ foldedThrough = span.lineEnd;
12759
+ }
12760
+ return folds;
12761
+ }
12762
+ var SLASH_STAR = { line: ["//"], open: "/*", close: "*/" };
12763
+ var HASH = { line: ["#"] };
12764
+ var DOUBLE_DASH = { line: ["--"] };
12765
+ var COMMENT_SYNTAX = new Map([
12766
+ ...["ts", "tsx", "js", "jsx", "mjs", "cjs", "java", "c", "h", "cc", "cpp", "hpp", "cs", "go", "rs", "swift", "kt", "scala", "php", "dart"].map(
12767
+ (ext) => [ext, SLASH_STAR]
12768
+ ),
12769
+ ...["py", "rb", "sh", "bash", "zsh", "pl", "r"].map((ext) => [ext, HASH]),
12770
+ ...["sql", "lua", "hs"].map((ext) => [ext, DOUBLE_DASH])
12771
+ ]);
12772
+ function commentSyntaxFor(path26) {
12773
+ const dot = path26.lastIndexOf(".");
12774
+ if (dot < 0) return null;
12775
+ return COMMENT_SYNTAX.get(path26.slice(dot + 1).toLowerCase()) ?? null;
12776
+ }
12777
+ function planCommentFolds(rows, syntax, commentKeep, commentMinBlock, occupied) {
12778
+ if (syntax === null || rows.length === 0 || commentKeep < 1 || commentMinBlock < 1) return [];
12779
+ const folds = [];
12780
+ let i = 0;
12781
+ let inBlock = false;
12782
+ while (i < rows.length) {
12783
+ const start = i;
12784
+ while (i < rows.length) {
12785
+ const text = rows[i]?.text ?? "";
12786
+ const trimmed = text.trim();
12787
+ if (inBlock) {
12788
+ if (syntax.close !== void 0 && trimmed.includes(syntax.close)) inBlock = false;
12789
+ i++;
12790
+ continue;
12791
+ }
12792
+ if (syntax.open !== void 0 && trimmed.startsWith(syntax.open)) {
12793
+ if (syntax.close === void 0 || !trimmed.slice(syntax.open.length).includes(syntax.close)) inBlock = true;
12794
+ i++;
12795
+ continue;
12796
+ }
12797
+ if (syntax.line.some((p) => trimmed.startsWith(p))) {
12798
+ i++;
12799
+ continue;
12800
+ }
12801
+ break;
12802
+ }
12803
+ const runLen = i - start;
12804
+ if (runLen >= commentMinBlock) {
12805
+ const foldStart = start + commentKeep;
12806
+ const len = i - foldStart;
12807
+ const firstRow = rows[foldStart];
12808
+ const lastRow = rows[i - 1];
12809
+ if (len >= MIN_FOLDED_ROWS && firstRow !== void 0 && lastRow !== void 0 && lastRow.no - firstRow.no + 1 === len) {
12810
+ let clear = true;
12811
+ for (let k = foldStart; k < i; k++) {
12812
+ if (occupied.has(k)) {
12813
+ clear = false;
12814
+ break;
12815
+ }
12816
+ }
12817
+ if (clear) folds.push({ startIdx: foldStart, len, name: "comment", kind: "comment", firstLine: firstRow.no, lastLine: lastRow.no });
12818
+ }
12819
+ }
12820
+ if (i === start) i++;
12821
+ }
12822
+ return folds;
12823
+ }
12824
+ function mergeFolds(body, comment) {
12825
+ const merged = [...body, ...comment].sort((a, b) => a.startIdx - b.startIdx || b.len - a.len);
12826
+ const out = [];
12827
+ let through = -1;
12828
+ for (const fold of merged) {
12829
+ if (fold.startIdx <= through) continue;
12830
+ out.push(fold);
12831
+ through = fold.startIdx + fold.len - 1;
12832
+ }
12833
+ return out;
12834
+ }
12835
+
9297
12836
  // src/hooks_read.ts
9298
12837
  function isTsConfigFile(basename12) {
9299
12838
  const lower = basename12.toLowerCase();
@@ -9348,6 +12887,15 @@ function readIntToolInput(event, key) {
9348
12887
  }
9349
12888
  return void 0;
9350
12889
  }
12890
+ function readStartLine(event) {
12891
+ const resp = event.raw["tool_response"];
12892
+ if (resp === null || typeof resp !== "object") return 1;
12893
+ const file = resp["file"];
12894
+ if (file === null || typeof file !== "object") return 1;
12895
+ const start = file["startLine"];
12896
+ if (typeof start === "number" && Number.isSafeInteger(start) && start >= 1) return start;
12897
+ return 1;
12898
+ }
9351
12899
  var SLICE_ESTIMATE_SCAN_CAP_BYTES = 2 * 1024 * 1024;
9352
12900
  var NEAR_SINGLE_LINE_SCAN_THRESHOLD = 20;
9353
12901
  function scanRequestedSlice(absPath, offset, limit) {
@@ -9637,7 +13185,8 @@ function preReadHandlerInner(event) {
9637
13185
  } catch {
9638
13186
  }
9639
13187
  }
9640
- if (event.toolName !== "Grep" && loadConfig().hints.stable_doc_compacts && _isDocFile(normalized)) {
13188
+ const compactUnrangedRead = readIntToolInput(event, "offset") === void 0 && readIntToolInput(event, "limit") === void 0;
13189
+ if (event.toolName !== "Grep" && compactUnrangedRead && loadConfig().hints.stable_doc_compacts && _isDocFile(normalized)) {
9641
13190
  const compactPath = compactPathFor(normalized);
9642
13191
  if (isCompactFresh(compactPath, normalized)) {
9643
13192
  const compactBody = readCompactBody(compactPath);
@@ -9647,7 +13196,7 @@ function preReadHandlerInner(event) {
9647
13196
  const savedBytes = counterfactualCredit(fullSize, compactBody.length);
9648
13197
  recordStat("session_hint", savedBytes, savedTokensFromBytes(savedBytes));
9649
13198
  return denyOutput(
9650
- "Serving the extractive compact sidecar in place of the full file (source unchanged since the last `compact-doc` build):\n\n" + fenceUntrustedFileContent(compactBody) + '\n\nUse `token-goat compact-doc "' + shown + '" --force` to rebuild it, or `token-goat compact-doc "' + shown + '" --show` to view it directly. ' + editAnywayHint(normalized)
13199
+ "Serving the extractive compact sidecar in place of the full file (source unchanged since the last `compact-doc` build):\n\n" + fenceUntrustedFileContent(compactBody) + '\n\nThis is a lossy extract, not the whole file: front matter and any prose before the first heading are dropped entirely, each section is cut to its opening sentences, and long code fences are truncated. If you need content it left out, re-read with offset/limit for a line window, or `token-goat section "' + shown + '::Heading"` for one section in full. Use `token-goat compact-doc "' + shown + '" --force` to rebuild it, or `token-goat compact-doc "' + shown + '" --show` to view it directly. ' + editAnywayHint(normalized)
9651
13200
  );
9652
13201
  }
9653
13202
  }
@@ -10112,7 +13661,7 @@ function alreadyServedOutputId(event, normalized) {
10112
13661
  return null;
10113
13662
  }
10114
13663
  }
10115
- function recordReadAsServedOutput(event) {
13664
+ function recordReadAsServedOutput(event, deliveredRaw = null) {
10116
13665
  try {
10117
13666
  const cfg = loadConfig().bash_compress;
10118
13667
  if (!cfg.enabled) return;
@@ -10122,7 +13671,7 @@ function recordReadAsServedOutput(event) {
10122
13671
  if (isImagePath(normalized)) return;
10123
13672
  const respText = extractReadOutput(event.raw);
10124
13673
  if (respText.includes("[Truncated:") || respText.includes("Truncated: PARTIAL view")) return;
10125
- const served = readWindowFromDisk(event, normalized);
13674
+ const served = deliveredRaw ?? readWindowFromDisk(event, normalized);
10126
13675
  if (served === null) return;
10127
13676
  if (Buffer.byteLength(served, "utf-8") < Math.max(cfg.cache_min_bytes, IDENTICAL_READ_MIN_BODY_BYTES)) return;
10128
13677
  const id = storeBashOutputSync("Read " + normalized, served, 0, getCwd(event) ?? process.cwd());
@@ -10131,7 +13680,7 @@ function recordReadAsServedOutput(event) {
10131
13680
  }
10132
13681
  }
10133
13682
  var READ_NUMBERED_ROW_RE = /^\s*(\d+)[\t→](.*)$/;
10134
- function parseNumberedReadResult(respText) {
13683
+ function parseNumberedReadResult(respText, firstLine = 1) {
10135
13684
  const lines2 = respText.split("\n");
10136
13685
  const header = [];
10137
13686
  const rows = [];
@@ -10156,7 +13705,10 @@ function parseNumberedReadResult(respText) {
10156
13705
  rows.push({ no: prev.no + 1, text: m[2] ?? "", raw: line });
10157
13706
  }
10158
13707
  for (; i < lines2.length; i++) trailer.push(lines2[i] ?? "");
10159
- return rows.length > 0 ? { header, rows, trailer } : null;
13708
+ if (rows.length > 0) return { header, rows, trailer };
13709
+ if (respText === "") return null;
13710
+ const plain = lines2.map((text, idx) => ({ no: firstLine + idx, text, raw: text }));
13711
+ return { header: [], rows: plain, trailer: [] };
10160
13712
  }
10161
13713
  var SERVED_RUN_COMPARISON_BUDGET = 4e5;
10162
13714
  var SERVED_RUN_ANCHORS_PER_LINE = 32;
@@ -10211,7 +13763,7 @@ function elideAlreadyServedLines(event, respText) {
10211
13763
  if (respText.includes("[Truncated:") || respText.includes("Truncated: PARTIAL view")) return null;
10212
13764
  const ids = getFileServedOutputs(normalized);
10213
13765
  if (ids.length === 0) return null;
10214
- const parsed = parseNumberedReadResult(respText);
13766
+ const parsed = parseNumberedReadResult(respText, readStartLine(event));
10215
13767
  if (parsed === null) return null;
10216
13768
  if (redactSecrets(respText).count > 0) return null;
10217
13769
  const bodies = [];
@@ -10285,20 +13837,102 @@ function elideAlreadyServedLines(event, respText) {
10285
13837
  }
10286
13838
  return emitRewrite(rewritten, "read", { kind: "read:served_elide", originalBytes });
10287
13839
  }
13840
+ var BODY_FOLD_KEEP_LINES = 8;
13841
+ var BODY_FOLD_MIN_SPAN = 20;
13842
+ var COMMENT_FOLD_KEEP_LINES = 2;
13843
+ var COMMENT_FOLD_MIN_BLOCK = 12;
13844
+ var BODY_FOLD_SYMBOL_LIMIT = 1e4;
13845
+ function bodyFoldNotice(name, firstLine, lastLine, shownPath) {
13846
+ const n = lastLine - firstLine + 1;
13847
+ return `... ${n} more lines of ${name} (${firstLine}-${lastLine}) folded -- token-goat read "${shownPath}::${name}"`;
13848
+ }
13849
+ function commentFoldNotice(firstLine, lastLine, shownPath) {
13850
+ const n = lastLine - firstLine + 1;
13851
+ return `... ${n} more comment lines (${firstLine}-${lastLine}) folded -- Read "${shownPath}" with offset=${firstLine}, limit=${n}`;
13852
+ }
13853
+ function foldCodeBodies(event, respText) {
13854
+ if (!loadConfig().hints.fold_code_bodies) return null;
13855
+ const filePath = getFilePath(event);
13856
+ if (filePath === void 0) return null;
13857
+ const normalized = normalizePath(filePath);
13858
+ if (isImagePath(normalized)) return null;
13859
+ if (readIntToolInput(event, "offset") !== void 0 || readIntToolInput(event, "limit") !== void 0) return null;
13860
+ if (respText.includes("[Truncated:") || respText.includes("Truncated: PARTIAL view")) return null;
13861
+ if (redactSecrets(respText).count > 0) return null;
13862
+ const parsed = parseNumberedReadResult(respText, readStartLine(event));
13863
+ if (parsed === null) return null;
13864
+ let spans = [];
13865
+ try {
13866
+ const entry = getFileEntry(normalized);
13867
+ if (entry !== null && entry.sha !== "" && entry.sha === fingerprintFile(normalized) && entry.parserSha === PARSER_FINGERPRINT) {
13868
+ spans = querySymbols({ filePath: normalized, limit: BODY_FOLD_SYMBOL_LIMIT });
13869
+ }
13870
+ } catch {
13871
+ spans = [];
13872
+ }
13873
+ const bodyFolds = planBodyFolds(parsed.rows, spans, BODY_FOLD_KEEP_LINES, BODY_FOLD_MIN_SPAN);
13874
+ const claimed = /* @__PURE__ */ new Set();
13875
+ for (const fold of bodyFolds) for (let i = fold.startIdx; i < fold.startIdx + fold.len; i++) claimed.add(i);
13876
+ const commentFolds = planCommentFolds(
13877
+ parsed.rows,
13878
+ commentSyntaxFor(normalized),
13879
+ COMMENT_FOLD_KEEP_LINES,
13880
+ COMMENT_FOLD_MIN_BLOCK,
13881
+ claimed
13882
+ );
13883
+ const folds = mergeFolds(bodyFolds, commentFolds);
13884
+ if (folds.length === 0) return null;
13885
+ const shown = displaySafePath(normalized);
13886
+ const out = [...parsed.header];
13887
+ const rawOut = [];
13888
+ let at = 0;
13889
+ for (const fold of folds) {
13890
+ for (let i = at; i < fold.startIdx; i++) {
13891
+ out.push(parsed.rows[i]?.raw ?? "");
13892
+ rawOut.push(parsed.rows[i]?.text ?? "");
13893
+ }
13894
+ out.push(fold.kind === "comment" ? commentFoldNotice(fold.firstLine, fold.lastLine, shown) : bodyFoldNotice(fold.name, fold.firstLine, fold.lastLine, shown));
13895
+ at = fold.startIdx + fold.len;
13896
+ }
13897
+ for (let i = at; i < parsed.rows.length; i++) {
13898
+ out.push(parsed.rows[i]?.raw ?? "");
13899
+ rawOut.push(parsed.rows[i]?.text ?? "");
13900
+ }
13901
+ out.push(...parsed.trailer);
13902
+ const rewritten = out.join("\n");
13903
+ const originalBytes = Buffer.byteLength(respText, "utf-8");
13904
+ if (!isRewriteWorthwhile({
13905
+ originalBytes,
13906
+ rewrittenBytes: Buffer.byteLength(rewritten, "utf-8"),
13907
+ noticeBytes: 0,
13908
+ minNetSavingsBytes: resolveMinNetSavingsBytes()
13909
+ })) {
13910
+ return null;
13911
+ }
13912
+ return {
13913
+ output: emitRewrite(rewritten, "read", { kind: "read:body_fold", originalBytes }),
13914
+ deliveredRaw: rawOut.join("\n")
13915
+ };
13916
+ }
10288
13917
  function postReadHandler(event) {
10289
- const elided = elideAlreadyServedLines(event, extractReadOutput(event.raw));
10290
- const out = applyHintTracking(event, postReadHandlerInner(event, elided !== null), classifyReadHint);
10291
- recordReadAsServedOutput(event);
10292
- return elided ?? out;
13918
+ const respText = extractReadOutput(event.raw);
13919
+ const elided = elideAlreadyServedLines(event, respText);
13920
+ const folded = elided === null ? foldCodeBodies(event, respText) : null;
13921
+ const rewrite = elided ?? folded?.output ?? null;
13922
+ const out = applyHintTracking(event, postReadHandlerInner(event, rewrite !== null), classifyReadHint);
13923
+ recordReadAsServedOutput(event, folded?.deliveredRaw ?? null);
13924
+ return rewrite ?? out;
10293
13925
  }
10294
13926
  registerHook("post_tool_use", postReadHandler, { toolName: "Read" });
10295
13927
 
10296
13928
  // src/cli_context_stats.ts
13929
+ init_define_import_meta_env();
10297
13930
  import * as fs19 from "node:fs";
10298
13931
  import * as os2 from "node:os";
10299
13932
  import * as path15 from "node:path";
10300
13933
 
10301
13934
  // src/confirm_apply.ts
13935
+ init_define_import_meta_env();
10302
13936
  import * as readline from "node:readline";
10303
13937
  async function defaultConfirm(question) {
10304
13938
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
@@ -10350,6 +13984,7 @@ ${diff}
10350
13984
  }
10351
13985
 
10352
13986
  // src/memory_prune.ts
13987
+ init_define_import_meta_env();
10353
13988
  import * as fs18 from "node:fs";
10354
13989
  import * as path14 from "node:path";
10355
13990
  var ENTRY_RE = /^\s*-\s*\[(?<title>[^\]]+)\]\((?<target>[^)]+?\.md)\)/;
@@ -10814,6 +14449,7 @@ async function runContextStats(opts = {}) {
10814
14449
  }
10815
14450
 
10816
14451
  // src/baseline.ts
14452
+ init_define_import_meta_env();
10817
14453
  import * as fs20 from "node:fs";
10818
14454
  import * as path16 from "node:path";
10819
14455
  var SKIP_DIRS = /* @__PURE__ */ new Set([
@@ -11054,6 +14690,7 @@ function formatMemSuggestions(projectRoot) {
11054
14690
  }
11055
14691
 
11056
14692
  // src/untrusted_fence.ts
14693
+ init_define_import_meta_env();
11057
14694
  function injectionFencingEnabled() {
11058
14695
  try {
11059
14696
  return loadConfig().injection.enabled;
@@ -11082,6 +14719,7 @@ function scanAndRecord(text) {
11082
14719
  }
11083
14720
 
11084
14721
  // src/repomap.ts
14722
+ init_define_import_meta_env();
11085
14723
  import * as fs21 from "fs";
11086
14724
  import * as path17 from "path";
11087
14725
  function getTrackedFiles(cwd = process.cwd()) {
@@ -11106,15 +14744,14 @@ function getTrackedFiles(cwd = process.cwd()) {
11106
14744
  }
11107
14745
  }
11108
14746
 
11109
- // src/parser_fingerprint.ts
11110
- var PARSER_FINGERPRINT = "4659c517f042a452";
11111
-
11112
14747
  // src/parser.ts
14748
+ init_define_import_meta_env();
11113
14749
  import * as fs22 from "node:fs";
11114
14750
  import { createRequire as createRequire3 } from "node:module";
11115
14751
  import * as path22 from "node:path";
11116
14752
 
11117
14753
  // src/languages/csharp.ts
14754
+ init_define_import_meta_env();
11118
14755
  var IDENT = "@?[A-Za-z_][A-Za-z0-9_]*";
11119
14756
  var DOTTED_IDENT = `${IDENT}(?:\\.${IDENT})*`;
11120
14757
  function stripVerbatim(name) {
@@ -11299,6 +14936,7 @@ function extractCsharp(content, filePath) {
11299
14936
  }
11300
14937
 
11301
14938
  // src/languages/php.ts
14939
+ init_define_import_meta_env();
11302
14940
  var NAMESPACE_RE2 = /^namespace\s+([\w\\]+)\s*;/;
11303
14941
  var CLASS_RE = /^(?:(?:abstract|final|readonly)\s+)*(class|interface|trait|enum)\s+([A-Za-z_][A-Za-z0-9_]*)/;
11304
14942
  var METHOD_RE2 = new RegExp(
@@ -11435,6 +15073,7 @@ function extractPhp(content, filePath) {
11435
15073
  }
11436
15074
 
11437
15075
  // src/languages/html.ts
15076
+ init_define_import_meta_env();
11438
15077
  var ID_RE = /(?<![\w-])id=(["'])((?:(?!\1)[\s\S])+)\1/gi;
11439
15078
  var CLASS_RE2 = /(?<![\w-])class=(["'])((?:(?!\1)[\s\S])+)\1/gi;
11440
15079
  var LINK_RE = /<link[^>]*href=(["'])((?:(?!\1)[\s\S])+)\1/gi;
@@ -11556,6 +15195,7 @@ function extractHtml(content, filePath) {
11556
15195
  }
11557
15196
 
11558
15197
  // src/languages/liquid.ts
15198
+ init_define_import_meta_env();
11559
15199
  import * as path18 from "node:path";
11560
15200
  var INCLUDE_RE = /{%-?\s*include\s+(['"])((?:(?!\1)[\s\S])+?)\1/gi;
11561
15201
  var SECTION_RE = /{%-?\s*section\s+(['"])((?:(?!\1)[\s\S])+?)\1/gi;
@@ -11621,6 +15261,7 @@ function extractLiquid(content, filePath, relPath) {
11621
15261
  }
11622
15262
 
11623
15263
  // src/languages/kotlin.ts
15264
+ init_define_import_meta_env();
11624
15265
  var IMPORT_RE = /^import\s+([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*(?:\.\*)?)/;
11625
15266
  var LEADING_ANNOTATION_RE = /^\s*(?:@[A-Za-z_][A-Za-z0-9_.]*(?::[A-Za-z_][A-Za-z0-9_]*)?(?:\([^()]*\))?\s+)+/;
11626
15267
  function stripLeadingAnnotations(s) {
@@ -11768,6 +15409,7 @@ function extractKotlin(content, filePath) {
11768
15409
  }
11769
15410
 
11770
15411
  // src/languages/swift.ts
15412
+ init_define_import_meta_env();
11771
15413
  var IDENT_START = "A-Za-z_\\u00C0-\\uFFFF";
11772
15414
  var IDENT_CONT = "A-Za-z0-9_\\u00C0-\\uFFFF";
11773
15415
  var IDENT2 = `(?:\`[^\`]+\`|[${IDENT_START}][${IDENT_CONT}]*)`;
@@ -11940,6 +15582,7 @@ function extractSwift(content, filePath) {
11940
15582
  }
11941
15583
 
11942
15584
  // src/languages/scala.ts
15585
+ init_define_import_meta_env();
11943
15586
  var IMPORT_RE3 = /^import\s+([A-Za-z_][A-Za-z0-9_.]*(?:\._)?)/;
11944
15587
  var BRACE_IMPORT_RE = /^import\s+([A-Za-z_][A-Za-z0-9_.]*)\.\{([^}]*)\}/;
11945
15588
  var MODS = "(?:(?:implicit|lazy|sealed|abstract|final|private|protected|override|covariant|contravariant|case)\\s+)*";
@@ -12095,6 +15738,7 @@ function extractScala(content, filePath) {
12095
15738
  }
12096
15739
 
12097
15740
  // src/languages/lua.ts
15741
+ init_define_import_meta_env();
12098
15742
  function nearestFunctionName(stack) {
12099
15743
  for (let i = stack.length - 1; i >= 0; i--) {
12100
15744
  const frame = stack[i];
@@ -12260,6 +15904,7 @@ function extractLua(content, filePath) {
12260
15904
  }
12261
15905
 
12262
15906
  // src/languages/elixir.ts
15907
+ init_define_import_meta_env();
12263
15908
  function nearestDefName(stack) {
12264
15909
  for (let i = stack.length - 1; i >= 0; i--) {
12265
15910
  const frame = stack[i];
@@ -12359,6 +16004,7 @@ function extractElixir(content, filePath) {
12359
16004
  }
12360
16005
 
12361
16006
  // src/languages/dart.ts
16007
+ init_define_import_meta_env();
12362
16008
  var CLASS_RE4 = /^(?:(?:abstract|base|interface|final|sealed|mixin)\s+)*class\s+([A-Za-z_][A-Za-z0-9_]*)/;
12363
16009
  var ENUM_RE2 = /^enum\s+([A-Za-z_][A-Za-z0-9_]*)/;
12364
16010
  var MIXIN_RE = /^(?:base\s+)?mixin\s+([A-Za-z_][A-Za-z0-9_]*)/;
@@ -12503,6 +16149,7 @@ function extractDart(content, filePath) {
12503
16149
  }
12504
16150
 
12505
16151
  // src/languages/zig.ts
16152
+ init_define_import_meta_env();
12506
16153
  var VAR_PREFIX = String.raw`(?:pub\s+)?(?:export\s+|extern\s+(?:"[^"]*"\s+)?)?(?:threadlocal\s+)?`;
12507
16154
  var FN_PREFIX = String.raw`(?:pub\s+)?(?:export\s+|extern\s+(?:"[^"]*"\s+)?|inline\s+|noinline\s+)?`;
12508
16155
  var NAME2 = String.raw`([A-Za-z_][A-Za-z0-9_]*)`;
@@ -12606,6 +16253,7 @@ function extractZig(content, filePath) {
12606
16253
  }
12607
16254
 
12608
16255
  // src/languages/r.ts
16256
+ init_define_import_meta_env();
12609
16257
  var FUNC_ASSIGN_RE = /^(?:`([^`]+)`|([A-Za-z._][A-Za-z0-9_.]*))\s*(?:<-|=)\s*(?:function|\\)\s*\(/;
12610
16258
  var SETCLASS_RE = /^(?:[A-Za-z_][A-Za-z0-9_.]*\s*(?:<-|=)\s*)?setClass\s*\(\s*["']([A-Za-z_][A-Za-z0-9_.]*)/;
12611
16259
  var SETMETHOD_RE = /^(?:[A-Za-z_][A-Za-z0-9_.]*\s*(?:<-|=)\s*)?setMethod\s*\(\s*["']([A-Za-z_][A-Za-z0-9_.]*)/;
@@ -12699,6 +16347,7 @@ function extractR(content, filePath) {
12699
16347
  }
12700
16348
 
12701
16349
  // src/languages/graphql_idx.ts
16350
+ init_define_import_meta_env();
12702
16351
  function findUnquotedHash(line) {
12703
16352
  for (let i = 0; i < line.length; i++) {
12704
16353
  if (line[i] === "#" && !isInsideStringLiteral(line, i)) return i;
@@ -12829,6 +16478,7 @@ function extractGraphql(content, filePath) {
12829
16478
  }
12830
16479
 
12831
16480
  // src/languages/sql_idx.ts
16481
+ init_define_import_meta_env();
12832
16482
  var MAX_SYMBOLS3 = 500;
12833
16483
  var MAX_HEADING_LEN2 = 128;
12834
16484
  var BARE = "[A-Za-z_][A-Za-z0-9_$]*";
@@ -13091,6 +16741,7 @@ function extractSql(content, filePath) {
13091
16741
  }
13092
16742
 
13093
16743
  // src/languages/bash_idx.ts
16744
+ init_define_import_meta_env();
13094
16745
  var MAX_SYMBOLS4 = 500;
13095
16746
  var FUNC_NAME = "[A-Za-z_][A-Za-z0-9_.+:-]*";
13096
16747
  var FUNC_KEYWORD_RE = new RegExp(`^function\\s+(${FUNC_NAME})\\s*(?:\\(\\s*\\))?`);
@@ -13225,6 +16876,7 @@ function extractBash(content, filePath) {
13225
16876
  }
13226
16877
 
13227
16878
  // src/languages/makefile_idx.ts
16879
+ init_define_import_meta_env();
13228
16880
  var MAX_SYMBOLS5 = 500;
13229
16881
  var MAX_HEADING_LEN3 = 120;
13230
16882
  function stripComments(text) {
@@ -13338,6 +16990,7 @@ function extractMakefile(content, filePath) {
13338
16990
  }
13339
16991
 
13340
16992
  // src/languages/proto_idx.ts
16993
+ init_define_import_meta_env();
13341
16994
  var MAX_SYMBOLS6 = 500;
13342
16995
  var MAX_HEADING_LEN4 = 120;
13343
16996
  function stripComments2(text) {
@@ -13449,6 +17102,7 @@ function extractProto(content, filePath) {
13449
17102
  }
13450
17103
 
13451
17104
  // src/languages/terraform_idx.ts
17105
+ init_define_import_meta_env();
13452
17106
  var MAX_SYMBOLS7 = 500;
13453
17107
  var MAX_HEADING_LEN5 = 120;
13454
17108
  var HEREDOC_START_RE = /<<-?([A-Za-z_][A-Za-z0-9_]*)/g;
@@ -13569,6 +17223,7 @@ function extractTerraform(content, filePath) {
13569
17223
  }
13570
17224
 
13571
17225
  // src/languages/powershell_idx.ts
17226
+ init_define_import_meta_env();
13572
17227
  var MAX_SYMBOLS8 = 500;
13573
17228
  var IDENT_START2 = "A-Za-z_\\u00C0-\\uFFFF";
13574
17229
  var IDENT_CONT2 = "A-Za-z0-9_\\u00C0-\\uFFFF";
@@ -13798,6 +17453,7 @@ function extractPowershell(content, filePath) {
13798
17453
  }
13799
17454
 
13800
17455
  // src/languages/apex.ts
17456
+ init_define_import_meta_env();
13801
17457
  var MAX_SYMBOLS9 = 500;
13802
17458
  var IDENT4 = "[A-Za-z_][A-Za-z0-9_]*";
13803
17459
  var MODIFIER = "(?:public|private|protected|global|static|final|override|virtual|abstract|webservice|testMethod|transient|with|without|inherited|sharing)";
@@ -13953,6 +17609,7 @@ function extractApex(content, filePath) {
13953
17609
  }
13954
17610
 
13955
17611
  // src/languages/salesforce_metadata.ts
17612
+ init_define_import_meta_env();
13956
17613
  import * as path19 from "node:path";
13957
17614
  var MAX_SYMBOLS10 = 1e3;
13958
17615
  var MAX_REFS = 1e3;
@@ -14293,6 +17950,7 @@ function extractSalesforceMetadata(rawContent, filePath) {
14293
17950
  }
14294
17951
 
14295
17952
  // src/languages/salesforce_frontend.ts
17953
+ init_define_import_meta_env();
14296
17954
  import * as path20 from "node:path";
14297
17955
  function lines(content) {
14298
17956
  return content.split("\n");
@@ -14456,6 +18114,7 @@ function extractSalesforceMarkup(content, filePath) {
14456
18114
  }
14457
18115
 
14458
18116
  // src/languages/sfc_idx.ts
18117
+ init_define_import_meta_env();
14459
18118
  import * as path21 from "node:path";
14460
18119
  var MAX_SYMBOLS11 = 500;
14461
18120
  function dedupe2(values, key) {
@@ -14651,6 +18310,7 @@ function extractAstro(content, filePath) {
14651
18310
  }
14652
18311
 
14653
18312
  // src/languages/ipynb_idx.ts
18313
+ init_define_import_meta_env();
14654
18314
  function normalizeSource(source) {
14655
18315
  if (typeof source === "string") return source;
14656
18316
  if (!Array.isArray(source)) return "";
@@ -16737,6 +20397,7 @@ function safeMtime(filePath) {
16737
20397
  }
16738
20398
 
16739
20399
  // src/index_prune.ts
20400
+ init_define_import_meta_env();
16740
20401
  import * as fs23 from "node:fs";
16741
20402
  import * as path23 from "node:path";
16742
20403
  function removeFileFromIndex(db, filePath) {
@@ -16966,6 +20627,7 @@ function recordKnownRootThrottled(filePath, dir = dataDir(), dbPath = globalDbPa
16966
20627
  }
16967
20628
 
16968
20629
  // src/process_priority.ts
20630
+ init_define_import_meta_env();
16969
20631
  import * as os3 from "node:os";
16970
20632
  var PRIORITY_BY_NAME = {
16971
20633
  normal: os3.constants.priority.PRIORITY_NORMAL,
@@ -16987,6 +20649,7 @@ function applyIndexingPriority() {
16987
20649
  }
16988
20650
 
16989
20651
  // src/worker.ts
20652
+ init_define_import_meta_env();
16990
20653
  import { spawn as spawn2 } from "node:child_process";
16991
20654
  import * as fs24 from "node:fs";
16992
20655
  import * as path24 from "node:path";
@@ -17670,6 +21333,7 @@ function runDetachedWorkerDaemon() {
17670
21333
  }
17671
21334
 
17672
21335
  // src/hooks_index.ts
21336
+ init_define_import_meta_env();
17673
21337
  import * as fs25 from "node:fs";
17674
21338
  import * as path25 from "node:path";
17675
21339
  function dirtyQueuePath() {
@@ -17724,6 +21388,7 @@ function preCompactIndexHandler(_event) {
17724
21388
  registerHook("pre_compact", preCompactIndexHandler, { advisory: true });
17725
21389
 
17726
21390
  // src/url_policy.ts
21391
+ init_define_import_meta_env();
17727
21392
  import { domainToUnicode } from "node:url";
17728
21393
  function wildcardToRegExp(pattern) {
17729
21394
  const escaped = pattern.replace(/[.+^${}()|[\]\\?]/g, "\\$&").replace(/\*/g, ".*");
@@ -17941,12 +21606,14 @@ export {
17941
21606
  detectWalkMode,
17942
21607
  getProjectIndexCounts,
17943
21608
  getEmbeddingCoverage,
21609
+ getParserFreshness,
17944
21610
  isIndexEmptyForProject,
17945
21611
  emptyIndexMessage,
17946
21612
  isHintCategory,
17947
21613
  classifyBashHint,
17948
21614
  classifyEditHint,
17949
21615
  applyHintTracking,
21616
+ isSuppressionCategory,
17950
21617
  meetsSavingsFloor,
17951
21618
  getHintStatsSummary,
17952
21619
  getHintStatsTotals,
@@ -18096,6 +21763,7 @@ export {
18096
21763
  embeddingsDepsAvailable,
18097
21764
  searchEvidenceSemantically,
18098
21765
  buildDeltaCapsule,
21766
+ PARSER_FINGERPRINT,
18099
21767
  buildLineDiff,
18100
21768
  confirmAndApply,
18101
21769
  findContentDuplicates,
@@ -18117,7 +21785,6 @@ export {
18117
21785
  fenceWithMatches,
18118
21786
  scanAndRecord,
18119
21787
  getTrackedFiles,
18120
- PARSER_FINGERPRINT,
18121
21788
  stripLeadingAttributes2 as stripLeadingAttributes,
18122
21789
  IMPORT_RE2 as IMPORT_RE,
18123
21790
  yamlOpenQuoteAfter,