VladZpp commited on
Commit
fe4e4c5
·
verified ·
1 Parent(s): c999e74

libjpeg-turbo 3 decoder, Pillow-exact EXIF/PNG/WebP handling, bounded inflate, preview from decoded pixels

Browse files
README.md CHANGED
@@ -15,7 +15,7 @@ Upload a photo of one waste item: the model returns the probability of each of s
15
 
16
  - **Runs entirely in your browser** with [ONNX Runtime Web](https://onnxruntime.ai): photos are never uploaded anywhere. The page checks the model file against its recorded SHA-256 before using it.
17
  - **Model:** EfficientNet-B0 fine-tuned on [TrashNet](https://github.com/garythung/trashnet). On 366 test photos with no near-duplicate in training: 94.3% accuracy (95% CI 90.3–96.9%), macro F1 0.936. The weakest class is trash (F1 0.89, 19 photos). On the 25 test photos least like any training photo of their class, accuracy was 68%.
18
- - **Same numbers as the Python pipeline, in every browser:** the page decodes images itself, with WebAssembly builds of the libraries Pillow uses, and reproduces Pillow's resize exactly. Checked in Chrome, Safari's engine (WebKit) and Firefox: on all 360 validation photos the decoded pixels are identical to Python's and the predictions match, with probabilities within 3e-6; so do 109 unusual files (every EXIF orientation, transparency, 1- to 16-bit PNG, MPO), and damaged files are refused like the API refuses them. Only CMYK JPEGs and animated WebP are refused here although the API accepts them.
19
  - **Scope:** TrashNet photos show one object on a plain background. Busy scenes, several objects or unusual lighting are outside what the model has learned.
20
  - **Examples:** the first validation photo per class that the model gets right. They show what it handles, not its error rate.
21
  - **Code, data handling and evaluation:** [github.com/vladzpop11/waste-sorting-classifier](https://github.com/vladzpop11/waste-sorting-classifier)
 
15
 
16
  - **Runs entirely in your browser** with [ONNX Runtime Web](https://onnxruntime.ai): photos are never uploaded anywhere. The page checks the model file against its recorded SHA-256 before using it.
17
  - **Model:** EfficientNet-B0 fine-tuned on [TrashNet](https://github.com/garythung/trashnet). On 366 test photos with no near-duplicate in training: 94.3% accuracy (95% CI 90.3–96.9%), macro F1 0.936. The weakest class is trash (F1 0.89, 19 photos). On the 25 test photos least like any training photo of their class, accuracy was 68%.
18
+ - **Same numbers as the Python pipeline, in every browser:** the page decodes images itself, with WebAssembly builds of the libraries Pillow uses (libjpeg-turbo 3, libwebp) and its own PNG decoder, and reproduces Pillow's resize exactly. Checked in Chrome, Safari's engine (WebKit) and Firefox: on all 360 validation photos the decoded pixels are identical to Python's and the predictions match, with probabilities within 3e-6; so do 129 unusual files (every EXIF orientation layout, transparency, 1- to 16-bit PNG, MPO, arithmetic and lossless JPEG), and damaged files are refused like the API refuses them. CMYK JPEGs and animated WebP are refused here although the API accepts them.
19
  - **Scope:** TrashNet photos show one object on a plain background. Busy scenes, several objects or unusual lighting are outside what the model has learned.
20
  - **Examples:** the first validation photo per class that the model gets right. They show what it handles, not its error rate.
21
  - **Code, data handling and evaluation:** [github.com/vladzpop11/waste-sorting-classifier](https://github.com/vladzpop11/waste-sorting-classifier)
app.js CHANGED
@@ -3,8 +3,9 @@
3
  // against the SHA-256 in model-info.js (part of the page's own code) before use: the model
4
  // and the three WebAssembly files (ONNX Runtime, the JPEG and WebP decoders). Images are
5
  // decoded by decode.js, not by the browser, so every browser gets Python's pixels.
 
 
6
  import * as ort from "./vendor/ort.wasm.min.mjs";
7
- import jpegFactory from "./vendor/mozjpeg_dec.js";
8
  import webpFactory from "./vendor/webp_dec.js";
9
  import { decodeImage, makeCodecs } from "./decode.js";
10
  import { MODEL, WASM } from "./model-info.js";
@@ -42,7 +43,7 @@ async function fetchVerified(url, expected) {
42
  async function load() {
43
  const [model, ortWasm, jpegWasm, webpWasm] = await Promise.all([
44
  fetchVerified("model.onnx", MODEL.sha256),
45
- ...["ort-wasm-simd-threaded.wasm", "mozjpeg_dec.wasm", "webp_dec.wasm"].map((name) =>
46
  fetchVerified(`vendor/${name}`, WASM[name])),
47
  ]);
48
  ort.env.wasm.wasmBinary = ortWasm;
@@ -100,6 +101,27 @@ function showResult(probabilities) {
100
  }
101
  }
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  function showError(message) {
104
  const result = $("result");
105
  delete result.dataset.label;
@@ -119,9 +141,9 @@ async function classify(blob, id = ++latest) {
119
  if (blob.size > MAX_BYTES) throw new Error("That file is larger than 20 MB.");
120
  const { rgb, width, height } = await decodeImage(new Uint8Array(await blob.arrayBuffer()), codecs);
121
  if (id !== latest) return;
122
- // The browser shows the photo only once it is known to be readable.
123
- if (preview.src) URL.revokeObjectURL(preview.src);
124
- preview.src = URL.createObjectURL(blob);
125
  preview.hidden = false;
126
  $("drop-hint").hidden = true;
127
  const input = new ort.Tensor("float32", preprocess(rgb, width, height), [1, 3, 224, 224]);
 
3
  // against the SHA-256 in model-info.js (part of the page's own code) before use: the model
4
  // and the three WebAssembly files (ONNX Runtime, the JPEG and WebP decoders). Images are
5
  // decoded by decode.js, not by the browser, so every browser gets Python's pixels.
6
+ // The JPEG decoder's loader is a classic script (index.html) that defines one global.
7
+ const jpegFactory = globalThis.libjpegturbowasm_decode;
8
  import * as ort from "./vendor/ort.wasm.min.mjs";
 
9
  import webpFactory from "./vendor/webp_dec.js";
10
  import { decodeImage, makeCodecs } from "./decode.js";
11
  import { MODEL, WASM } from "./model-info.js";
 
43
  async function load() {
44
  const [model, ortWasm, jpegWasm, webpWasm] = await Promise.all([
45
  fetchVerified("model.onnx", MODEL.sha256),
46
+ ...["ort-wasm-simd-threaded.wasm", "libjpegturbowasm_decode.wasm", "webp_dec.wasm"].map((name) =>
47
  fetchVerified(`vendor/${name}`, WASM[name])),
48
  ]);
49
  ort.env.wasm.wasmBinary = ortWasm;
 
101
  }
102
  }
103
 
104
+ // Upright RGB -> the preview canvas, at most 600 px on its longer side (nearest pixel).
105
+ function drawPreview(canvas, rgb, width, height) {
106
+ const scale = Math.min(1, 600 / Math.max(width, height));
107
+ const w = Math.max(1, Math.round(width * scale)), h = Math.max(1, Math.round(height * scale));
108
+ canvas.width = w;
109
+ canvas.height = h;
110
+ const ctx = canvas.getContext("2d");
111
+ const image = ctx.createImageData(w, h);
112
+ for (let y = 0, o = 0; y < h; y++) {
113
+ const sy = Math.min(height - 1, Math.floor(y / scale));
114
+ for (let x = 0; x < w; x++, o += 4) {
115
+ const s = (sy * width + Math.min(width - 1, Math.floor(x / scale))) * 3;
116
+ image.data[o] = rgb[s];
117
+ image.data[o + 1] = rgb[s + 1];
118
+ image.data[o + 2] = rgb[s + 2];
119
+ image.data[o + 3] = 255;
120
+ }
121
+ }
122
+ ctx.putImageData(image, 0, 0);
123
+ }
124
+
125
  function showError(message) {
126
  const result = $("result");
127
  delete result.dataset.label;
 
141
  if (blob.size > MAX_BYTES) throw new Error("That file is larger than 20 MB.");
142
  const { rgb, width, height } = await decodeImage(new Uint8Array(await blob.arrayBuffer()), codecs);
143
  if (id !== latest) return;
144
+ // The preview is drawn from the decoded pixels: the photo as the model sees it,
145
+ // including formats the browser itself cannot display.
146
+ drawPreview(preview, rgb, width, height);
147
  preview.hidden = false;
148
  $("drop-hint").hidden = true;
149
  const input = new ort.Tensor("float32", preprocess(rgb, width, height), [1, 3, 224, 224]);
decode.js CHANGED
@@ -1,10 +1,10 @@
1
  // Uploaded bytes -> upright 8-bit RGB, exactly as preprocess.py's load_rgb produces it, in
2
  // every browser: the page decodes images itself instead of asking the browser, whose
3
  // decoders differ (Safari's JPEG decoder, colour management, premultiplied alpha).
4
- // - JPEG and WebP: libjpeg-turbo (via MozJPEG) and libwebp compiled to WebAssembly, the
5
- // libraries Pillow uses; PNG: png.js. `codecs` supplies the two WebAssembly decoders.
6
- // - Transparency is flattened onto white with Pillow's arithmetic, then the EXIF
7
- // orientation is applied like ImageOps.exif_transpose.
8
  // - Refused before decoding: unknown formats, out-of-limit sizes (as the API) and
9
  // incomplete files. Refused although Python accepts them (a known, documented
10
  // difference): CMYK JPEGs and animated WebP, which the WebAssembly decoders do not read.
@@ -14,42 +14,41 @@ import { checkSize } from "./preprocess.js";
14
 
15
  const damaged = () => new ImageError("That file could not be read as an image: it may be damaged.");
16
 
17
- // Pillow's alpha_composite onto opaque white, then dropping alpha (checked against Pillow
18
- // for every colour and alpha value).
19
- function flatten({ width, height, channels, data }) {
20
- if (channels === 3) return data;
21
- const rgb = new Uint8Array(width * height * 3);
22
- for (let i = 0, j = 0; j < rgb.length; i += 4, j += 3) {
23
- const a = data[i + 3], back = 255 * (255 - a) + 127;
24
- rgb[j] = Math.floor((data[i] * a + back) / 255);
25
- rgb[j + 1] = Math.floor((data[i + 1] * a + back) / 255);
26
- rgb[j + 2] = Math.floor((data[i + 2] * a + back) / 255);
27
- }
28
- return rgb;
29
- }
30
 
31
- // ImageOps.exif_transpose: orientation 2-8 -> Pillow's transpose methods.
32
- function orient(rgb, w, h, orientation) {
33
- if (orientation === 1) return { rgb, width: w, height: h };
34
  const swap = orientation >= 5;
35
  const W = swap ? h : w, H = swap ? w : h;
36
- const source = {
37
- 2: (x, y) => [w - 1 - x, y], // FLIP_LEFT_RIGHT
38
- 3: (x, y) => [w - 1 - x, h - 1 - y], // ROTATE_180
39
- 4: (x, y) => [x, h - 1 - y], // FLIP_TOP_BOTTOM
40
- 5: (x, y) => [y, x], // TRANSPOSE
41
- 6: (x, y) => [y, h - 1 - x], // ROTATE_270
42
- 7: (x, y) => [w - 1 - y, h - 1 - x], // TRANSVERSE
43
- 8: (x, y) => [w - 1 - y, x], // ROTATE_90
44
- }[orientation];
45
- const out = new Uint8Array(rgb.length);
46
- for (let y = 0; y < H; y++) {
47
- for (let x = 0; x < W; x++) {
48
- const [sx, sy] = source(x, y);
49
- const s = (sy * w + sx) * 3, o = (y * W + x) * 3;
50
- out[o] = rgb[s];
51
- out[o + 1] = rgb[s + 1];
52
- out[o + 2] = rgb[s + 2];
53
  }
54
  }
55
  return { rgb: out, width: W, height: H };
@@ -74,31 +73,40 @@ export async function decodeImage(bytes, codecs) {
74
  if (header.format === "png") {
75
  image = await decodePng(bytes);
76
  } else {
77
- let out;
78
  try {
79
- out = await codecs[header.format](bytes);
80
  } catch {
81
  throw damaged();
82
  }
83
- image = { width: out.width, height: out.height, channels: 4, data: out.data };
 
84
  }
85
  if (image.width !== header.width || image.height !== header.height) throw damaged();
86
- return orient(flatten(image), image.width, image.height, header.orientation);
 
 
 
 
 
 
 
 
 
 
87
  }
88
 
89
- // The two WebAssembly decoders from their Emscripten factories (vendor/*_dec.js) and
90
- // their already verified .wasm bytes. A decoder that fails is rebuilt for the next file.
 
 
91
  export function makeCodecs({ jpegFactory, jpegWasm, webpFactory, webpWasm }) {
92
  const options = (wasmBinary) => ({ noInitialRun: true, wasmBinary, print: () => {}, printErr: () => {} });
93
  const wrap = (factory, wasm, call) => {
94
  let module = null;
95
  return async (bytes) => {
96
  module ??= await factory(options(wasm));
97
- const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
98
  try {
99
- const out = call(module, buffer);
100
- if (!out) throw new Error("decoding failed");
101
- return out;
102
  } catch (err) {
103
  module = null;
104
  throw err;
@@ -106,7 +114,26 @@ export function makeCodecs({ jpegFactory, jpegWasm, webpFactory, webpWasm }) {
106
  };
107
  };
108
  return {
109
- jpeg: wrap(jpegFactory, jpegWasm, (m, buffer) => m.decode(buffer, false)), // no auto-rotation
110
- webp: wrap(webpFactory, webpWasm, (m, buffer) => m.decode(buffer)),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  };
112
  }
 
1
  // Uploaded bytes -> upright 8-bit RGB, exactly as preprocess.py's load_rgb produces it, in
2
  // every browser: the page decodes images itself instead of asking the browser, whose
3
  // decoders differ (Safari's JPEG decoder, colour management, premultiplied alpha).
4
+ // - JPEG and WebP: libjpeg-turbo 3 and libwebp compiled to WebAssembly, the libraries
5
+ // Pillow uses; PNG: png.js. `codecs` supplies the two WebAssembly decoders.
6
+ // - Transparency is flattened onto white with Pillow's arithmetic and the EXIF orientation
7
+ // applied like ImageOps.exif_transpose, in one pass.
8
  // - Refused before decoding: unknown formats, out-of-limit sizes (as the API) and
9
  // incomplete files. Refused although Python accepts them (a known, documented
10
  // difference): CMYK JPEGs and animated WebP, which the WebAssembly decoders do not read.
 
14
 
15
  const damaged = () => new ImageError("That file could not be read as an image: it may be damaged.");
16
 
17
+ // Source pixel index for output pixel (x, y) under each orientation (2-8), like Pillow's
18
+ // transpose methods; w, h are the stored (unrotated) width and height.
19
+ const SOURCE = {
20
+ 1: (x, y, w) => y * w + x,
21
+ 2: (x, y, w) => y * w + (w - 1 - x), // FLIP_LEFT_RIGHT
22
+ 3: (x, y, w, h) => (h - 1 - y) * w + (w - 1 - x), // ROTATE_180
23
+ 4: (x, y, w, h) => (h - 1 - y) * w + x, // FLIP_TOP_BOTTOM
24
+ 5: (x, y, w) => x * w + y, // TRANSPOSE
25
+ 6: (x, y, w, h) => (h - 1 - x) * w + y, // ROTATE_270
26
+ 7: (x, y, w, h) => (h - 1 - x) * w + (w - 1 - y), // TRANSVERSE
27
+ 8: (x, y, w) => x * w + (w - 1 - y), // ROTATE_90
28
+ };
 
29
 
30
+ // Decoded pixels (1, 3 or 4 channels) -> upright RGB. Alpha is flattened onto white with
31
+ // Pillow's alpha_composite arithmetic (checked against Pillow for every colour and alpha).
32
+ function toUprightRgb({ width: w, height: h, channels, data }, orientation) {
33
  const swap = orientation >= 5;
34
  const W = swap ? h : w, H = swap ? w : h;
35
+ const source = SOURCE[orientation];
36
+ const out = new Uint8Array(W * H * 3);
37
+ for (let y = 0, o = 0; y < H; y++) {
38
+ for (let x = 0; x < W; x++, o += 3) {
39
+ const i = source(x, y, w, h) * channels;
40
+ if (channels === 1) {
41
+ out[o] = out[o + 1] = out[o + 2] = data[i];
42
+ } else if (channels === 3) {
43
+ out[o] = data[i];
44
+ out[o + 1] = data[i + 1];
45
+ out[o + 2] = data[i + 2];
46
+ } else {
47
+ const a = data[i + 3], back = 255 * (255 - a) + 127;
48
+ out[o] = Math.floor((data[i] * a + back) / 255);
49
+ out[o + 1] = Math.floor((data[i + 1] * a + back) / 255);
50
+ out[o + 2] = Math.floor((data[i + 2] * a + back) / 255);
51
+ }
52
  }
53
  }
54
  return { rgb: out, width: W, height: H };
 
73
  if (header.format === "png") {
74
  image = await decodePng(bytes);
75
  } else {
 
76
  try {
77
+ image = await codecs[header.format](header.decodeBytes ?? bytes);
78
  } catch {
79
  throw damaged();
80
  }
81
+ // WebP without an alpha channel in Pillow's eyes: its colours are used as they are.
82
+ if (header.format === "webp" && !header.alpha) image = dropAlpha(image);
83
  }
84
  if (image.width !== header.width || image.height !== header.height) throw damaged();
85
+ return toUprightRgb(image, header.orientation);
86
+ }
87
+
88
+ function dropAlpha({ width, height, data }) {
89
+ const rgb = new Uint8Array(width * height * 3);
90
+ for (let i = 0, j = 0; j < rgb.length; i += 4, j += 3) {
91
+ rgb[j] = data[i];
92
+ rgb[j + 1] = data[i + 1];
93
+ rgb[j + 2] = data[i + 2];
94
+ }
95
+ return { width, height, channels: 3, data: rgb };
96
  }
97
 
98
+ // The two WebAssembly decoders from their Emscripten factories (the vendored
99
+ // libjpegturbowasm_decode.js and webp_dec.js) and their already verified .wasm bytes.
100
+ // Each returns { width, height, channels, data }. A decoder that fails is rebuilt for the
101
+ // next file.
102
  export function makeCodecs({ jpegFactory, jpegWasm, webpFactory, webpWasm }) {
103
  const options = (wasmBinary) => ({ noInitialRun: true, wasmBinary, print: () => {}, printErr: () => {} });
104
  const wrap = (factory, wasm, call) => {
105
  let module = null;
106
  return async (bytes) => {
107
  module ??= await factory(options(wasm));
 
108
  try {
109
+ return call(module, bytes);
 
 
110
  } catch (err) {
111
  module = null;
112
  throw err;
 
114
  };
115
  };
116
  return {
117
+ // libjpeg-turbo: RGB or greyscale output, no EXIF rotation.
118
+ jpeg: wrap(jpegFactory, jpegWasm, (m, bytes) => {
119
+ const decoder = new m.JPEGDecoder();
120
+ try {
121
+ decoder.getEncodedBuffer(bytes.length).set(bytes);
122
+ decoder.decode();
123
+ const info = decoder.getFrameInfo();
124
+ if (info.componentCount !== 1 && info.componentCount !== 3) throw new Error("unsupported");
125
+ return { width: info.width, height: info.height, channels: info.componentCount,
126
+ data: new Uint8Array(decoder.getDecodedBuffer()) }; // copied out of the WebAssembly heap
127
+ } finally {
128
+ decoder.delete();
129
+ }
130
+ }),
131
+ // libwebp: RGBA output.
132
+ webp: wrap(webpFactory, webpWasm, (m, bytes) => {
133
+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
134
+ const out = m.decode(buffer);
135
+ if (!out) throw new Error("decoding failed");
136
+ return { width: out.width, height: out.height, channels: 4, data: out.data };
137
+ }),
138
  };
139
  }
image-header.js CHANGED
@@ -4,11 +4,14 @@
4
  // finds it (src/waste_sorting_classifier/preprocess.py):
5
  // - JPEG: every APP1 "Exif" segment, concatenated; XMP from the last XMP segment;
6
  // - PNG: the last eXIf chunk, else a "Raw profile type exif" text chunk; XMP from iTXt;
7
- // - WebP: the first EXIF and XMP chunks, when the VP8X header announces them;
8
- // - in EXIF, any number of "Exif\0\0" prefixes, then a TIFF directory whose last
9
- // orientation entry wins; XMP's tiff:Orientation only when EXIF has none.
10
  // Every read is bounded by the file and by the block it belongs to: hostile files are
11
- // refused or ignored, never followed outside their data.
 
 
 
12
 
13
  const u16 = (b, o, le) => (le ? b[o] | (b[o + 1] << 8) : (b[o] << 8) | b[o + 1]);
14
  const u32 = (b, o, le) =>
@@ -29,26 +32,34 @@ export function sniffFormat(b) {
29
 
30
  // --- EXIF and XMP ----------------------------------------------------------------------
31
 
32
- // Orientation from a TIFF-structured EXIF block, as Pillow reads it: the first value of a
33
- // numeric entry (byte-typed entries are ignored), stored inline when it fits in 4 bytes and
34
- // at its offset otherwise; the last entry for the tag wins; a directory damaged part-way
35
- // keeps the entries read before the damage. Returns null when there is none.
36
- const SIZES = { 3: 2, 4: 4, 5: 8, 8: 2, 9: 4, 10: 8, 11: 4, 12: 8 }; // numeric TIFF types
 
 
 
 
 
37
 
38
  function firstValue(b, at, type, le) {
39
- const dv = new DataView(b.buffer, b.byteOffset + at, SIZES[type]);
40
  switch (type) {
41
  case 3: return dv.getUint16(0, le);
42
- case 4: return dv.getUint32(0, le);
 
43
  case 8: return dv.getInt16(0, le);
44
  case 9: return dv.getInt32(0, le);
45
  case 11: return dv.getFloat32(0, le);
46
  case 12: return dv.getFloat64(0, le);
47
- default: { // rationals: Pillow compares the fraction with the orientation numbers
 
48
  const n = type === 5 ? dv.getUint32(0, le) : dv.getInt32(0, le);
49
  const d = type === 5 ? dv.getUint32(4, le) : dv.getInt32(4, le);
50
  return d !== 0 ? n / d : NaN;
51
  }
 
52
  }
53
  }
54
 
@@ -56,11 +67,13 @@ export function exifOrientation(exif) {
56
  let s = 0;
57
  while (s + 6 <= exif.length && ascii(exif, s, 6) === "Exif\0\0") s += 6;
58
  const b = exif.subarray(s);
59
- if (b.length < 8) return null;
60
- const order = ascii(b, 0, 2);
61
- if (order !== "II" && order !== "MM") return null;
62
- const le = order === "II";
63
- if (u16(b, 2, le) !== 42 && u16(b, 2, !le) !== 42) return null;
 
 
64
  const ifd = u32(b, 4, le);
65
  if (ifd + 2 > b.length) return null;
66
  let found = null;
@@ -68,13 +81,16 @@ export function exifOrientation(exif) {
68
  for (let i = 0; i < count; i++) {
69
  const e = ifd + 2 + i * 12;
70
  if (e + 12 > b.length) break;
71
- if (u16(b, e, le) !== 0x0112) continue;
72
- const type = u16(b, e + 2, le), n = u32(b, e + 4, le);
73
- if (!SIZES[type] || n === 0) continue;
74
- const size = SIZES[type] * n;
75
- const at = size <= 4 ? e + 8 : u32(b, e + 8, le);
76
- if (at + size > b.length) continue; // Pillow skips a tag whose data is out of range
77
- found = firstValue(b, at, type, le);
 
 
 
78
  }
79
  return found;
80
  }
@@ -87,8 +103,18 @@ function xmpOrientation(text) {
87
  // What exif_transpose does with the value: 2-8 transform the image, anything else nothing.
88
  const effective = (value) => (Number.isInteger(value) && value >= 2 && value <= 8 ? value : 1);
89
 
90
- function orientationOf(exif, xmp) {
91
- const fromExif = exif ? exifOrientation(exif) : null;
 
 
 
 
 
 
 
 
 
 
92
  if (fromExif !== null) return effective(fromExif);
93
  return effective(xmp !== null ? xmpOrientation(xmp) : null);
94
  }
@@ -108,28 +134,11 @@ const MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK;
108
  const tooMuch = () => new ImageError("That file carries too much metadata to be read safely.");
109
 
110
  // -> Uint8Array, or null when the data is corrupt; throws when it expands past the limit.
111
- async function inflateLimited(data) {
112
- const reader = new Blob([data]).stream().pipeThrough(new DecompressionStream("deflate")).getReader();
113
- const parts = [];
114
- let total = 0;
115
- try {
116
- for (;;) {
117
- const { done, value } = await reader.read();
118
- if (done) break;
119
- total += value.length;
120
- if (total > MAX_TEXT_CHUNK) {
121
- reader.cancel().catch(() => {});
122
- throw tooMuch();
123
- }
124
- parts.push(value);
125
- }
126
- } catch (err) {
127
- if (err instanceof ImageError) throw err;
128
- // Pillow's zlib keeps what it decoded before the damage; a partial result never matters
129
- // here (keys are compared whole), so damaged data counts as empty.
130
- return null;
131
- }
132
- return concat(parts);
133
  }
134
 
135
  // --- Containers ------------------------------------------------------------------------
@@ -139,19 +148,25 @@ async function inflateLimited(data) {
139
  function jpegHeader(b) {
140
  let width = 0, height = 0, components = 0, scanAt = -1;
141
  const exif = [];
142
- let xmp = null;
 
143
  let o = 2;
144
  while (o < b.length) {
145
- if (b[o] !== 0xff) { o++; continue; }
 
 
 
146
  while (o < b.length && b[o] === 0xff) o++;
147
  if (o >= b.length) break;
148
  const marker = b[o++];
149
- if (marker === 0x00 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
 
150
  if (marker === 0xd9 || o + 2 > b.length) break;
151
  const length = u16(b, o, false);
152
  if (length < 2 || o + length > b.length) break;
153
  const data = b.subarray(o + 2, o + length);
154
  if (marker === 0xda) { scanAt = o + length; break; }
 
155
  if (marker === 0xe1 && ascii(data, 0, 6) === "Exif\0\0") exif.push(exif.length ? data.subarray(6) : data);
156
  else if (marker === 0xe1 && ascii(data, 0, 29) === "http://ns.adobe.com/xap/1.0/\0") xmp = latin1(data.subarray(29));
157
  const sof = marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker);
@@ -168,38 +183,61 @@ function jpegHeader(b) {
168
  for (let i = scanAt; scanAt >= 0 && i + 1 < b.length; i++) {
169
  if (b[i] === 0xff && b[i + 1] === 0xd9) { complete = true; break; }
170
  }
171
- const orientation = orientationOf(exif.length ? concat(exif) : null, xmp);
172
- return { width, height, components, complete, orientation };
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  }
174
 
175
- // PNG chunks; a chunk that does not fit in the file ends the walk.
176
  export function* pngChunks(b) {
177
  for (let o = 8; o + 12 <= b.length; ) {
178
  const size = u32(b, o, false);
179
  if (o + 12 + size > b.length) return;
180
- yield { type: ascii(b, o + 4, 4), at: o, data: b.subarray(o + 8, o + 8 + size) };
 
 
181
  o += 12 + size;
182
  }
183
  }
184
 
185
- // Characters in a decoded string, counted like Python's len() (code points).
186
- const codePoints = (bytes, utf8) => (utf8 ? bytes.reduce((n, x) => n + ((x & 0xc0) !== 0x80), 0) : bytes.length);
 
 
 
 
 
 
 
 
187
 
188
  // A PNG text chunk as Pillow reads it -> { key, text, xmpBytes, length } or null (ignored).
189
- async function pngText(chunk) {
190
  const d = chunk.data;
191
  const nul = d.indexOf(0);
192
  if (chunk.type === "tEXt") {
193
  const key = latin1(nul < 0 ? d : d.subarray(0, nul));
194
  const value = nul < 0 ? new Uint8Array() : d.subarray(nul + 1);
195
- return key ? { key, text: latin1(value), length: value.length } : null;
196
  }
197
  if (chunk.type === "zTXt") {
198
  const key = latin1(nul < 0 ? d : d.subarray(0, nul));
199
  const rest = nul < 0 ? new Uint8Array() : d.subarray(nul + 1);
200
  if (rest.length && rest[0] !== 0) throw new ImageError("That file could not be read as an image.");
201
- const value = (await inflateLimited(rest.subarray(1))) ?? new Uint8Array();
202
- return key ? { key, text: latin1(value), length: value.length } : null;
203
  }
204
  // iTXt: keyword, compression flag, method, language tag, translated keyword, text.
205
  if (nul < 0 || d.length - nul - 1 < 2) return null;
@@ -210,7 +248,7 @@ async function pngText(chunk) {
210
  let value = d.subarray(translated + 1);
211
  if (flag !== 0) {
212
  if (method !== 0) return null;
213
- value = await inflateLimited(value);
214
  if (value === null) return null;
215
  }
216
  const key = latin1(d.subarray(0, nul));
@@ -223,26 +261,27 @@ async function pngText(chunk) {
223
  } catch {
224
  return { key: null, xmpBytes };
225
  }
226
- return { key, text, xmpBytes, length: codePoints(value, true) };
227
  }
228
 
229
  // An iCCP colour profile is not used, but Pillow refuses one it cannot safely decompress.
230
- async function checkIccp(chunk) {
231
  const d = chunk.data;
232
  const nul = d.indexOf(0);
233
  if (nul < 0 || d[nul + 1] !== 0) throw new ImageError("That file could not be read as an image.");
234
- await inflateLimited(d.subarray(nul + 2));
235
  }
236
 
237
  async function pngHeader(b) {
238
- let exif = null, ihdr = false, memory = 0, xmpRaw = null;
239
  const info = {}; // Pillow's im_info for the keys that matter: the last chunk wins
240
  for (const c of pngChunks(b)) {
241
- if (c.type === "IHDR" && c.data.length >= 8) ihdr = true;
 
242
  if (c.type === "eXIf") exif = c.data; // Pillow keeps the last
243
- if (c.type === "iCCP") await checkIccp(c);
244
  if (c.type === "tEXt" || c.type === "zTXt" || c.type === "iTXt") {
245
- const t = await pngText(c);
246
  if (!t) continue;
247
  if (t.xmpBytes !== null && t.xmpBytes !== undefined) xmpRaw = t.xmpBytes;
248
  if (t.key === null) continue;
@@ -260,24 +299,85 @@ async function pngHeader(b) {
260
  // Pillow: XMP stored under its own key (any text chunk) first, then raw iTXt XMP.
261
  const xmp = info["XML:com.adobe.xmp"] || xmpRaw || null;
262
  return {
263
- width: ihdr ? u32(b, 16, false) : 0,
264
- height: ihdr ? u32(b, 20, false) : 0,
265
  complete: true, // whether all pixel data is there is judged by png.js, like Pillow
266
  orientation: orientationOf(exif && exif.length ? exif : null, xmp),
267
  };
268
  }
269
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  function webpHeader(b) {
271
- let width = 0, height = 0, flags = 0, exif = null, xmp = null, animated = false;
272
  const declared = u32(b, 4, true) + 8;
273
  for (let o = 12; o + 8 <= b.length; ) {
274
  const id = ascii(b, o, 4), size = u32(b, o + 4, true);
275
  if (o + 8 + size > b.length) break;
276
  const data = b.subarray(o + 8, o + 8 + size);
277
- if (id === "VP8X" && size >= 10) {
278
  flags = data[0];
279
  width = 1 + (data[4] | (data[5] << 8) | (data[6] << 16));
280
  height = 1 + (data[7] | (data[8] << 8) | (data[9] << 16));
 
281
  } else if (id === "VP8 " && !width && size >= 10) {
282
  width = u16(data, 6, true) & 0x3fff;
283
  height = u16(data, 8, true) & 0x3fff;
@@ -285,8 +385,7 @@ function webpHeader(b) {
285
  const bits = u32(data, 1, true);
286
  width = 1 + (bits & 0x3fff);
287
  height = 1 + ((bits >> 14) & 0x3fff);
288
- } else if (id === "ANIM" || id === "ANMF") {
289
- animated = true;
290
  } else if (id === "EXIF" && exif === null) {
291
  exif = data;
292
  } else if (id === "XMP " && xmp === null) {
@@ -294,10 +393,17 @@ function webpHeader(b) {
294
  }
295
  o += 8 + size + (size & 1);
296
  }
297
- // libwebp's demuxer (used by Pillow) only exposes metadata the VP8X header announces.
298
  if (!(flags & 0x08)) exif = null;
299
  if (!(flags & 0x04)) xmp = null;
300
- return { width, height, animated, complete: declared <= b.length, orientation: orientationOf(exif, xmp) };
 
 
 
 
 
 
 
301
  }
302
 
303
  // { format, width, height, orientation, complete, components (JPEG), animated (WebP) }
 
4
  // finds it (src/waste_sorting_classifier/preprocess.py):
5
  // - JPEG: every APP1 "Exif" segment, concatenated; XMP from the last XMP segment;
6
  // - PNG: the last eXIf chunk, else a "Raw profile type exif" text chunk; XMP from iTXt;
7
+ // - WebP: the first EXIF and XMP chunks, when the VP8X header (first chunk) announces them;
8
+ // - in EXIF, any number of "Exif\0\0" prefixes, then a TIFF directory read like Pillow's
9
+ // ImageFileDirectory_v2; XMP's tiff:Orientation only when EXIF has none.
10
  // Every read is bounded by the file and by the block it belongs to: hostile files are
11
+ // refused or ignored, never followed outside their data. Valid files match Pillow exactly;
12
+ // for files that break their format's rules the page aims to match Pillow too, but only
13
+ // guarantees to stay safe (bounded time and memory).
14
+ import { inflateInto } from "./inflate.js";
15
 
16
  const u16 = (b, o, le) => (le ? b[o] | (b[o + 1] << 8) : (b[o] << 8) | b[o + 1]);
17
  const u32 = (b, o, le) =>
 
32
 
33
  // --- EXIF and XMP ----------------------------------------------------------------------
34
 
35
+ // Orientation from a TIFF-structured EXIF block, read like Pillow's Exif.load and
36
+ // ImageFileDirectory_v2.load:
37
+ // - the header must be one of Pillow's TIFF prefixes, or Pillow raises (ExifError here);
38
+ // - entries of unknown type are skipped; an entry whose data lies outside the block stops
39
+ // the whole directory, keeping what was read before it (Pillow's truncated-read path);
40
+ // - the last entry for a tag wins, whatever its type; numeric types give their first
41
+ // value, byte and string types never match an orientation.
42
+ // Returns the value (NaN when not numeric) or null when there is none.
43
+ export class ExifError extends Error {}
44
+ const UNIT = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 6: 1, 7: 1, 8: 2, 9: 4, 10: 8, 11: 4, 12: 8, 13: 4, 16: 8 };
45
 
46
  function firstValue(b, at, type, le) {
47
+ const dv = new DataView(b.buffer, b.byteOffset + at, UNIT[type]);
48
  switch (type) {
49
  case 3: return dv.getUint16(0, le);
50
+ case 4: case 13: return dv.getUint32(0, le);
51
+ case 6: return dv.getInt8(0);
52
  case 8: return dv.getInt16(0, le);
53
  case 9: return dv.getInt32(0, le);
54
  case 11: return dv.getFloat32(0, le);
55
  case 12: return dv.getFloat64(0, le);
56
+ case 16: return Number(dv.getBigUint64(0, le));
57
+ case 5: case 10: { // rationals: Pillow compares the fraction with the orientation numbers
58
  const n = type === 5 ? dv.getUint32(0, le) : dv.getInt32(0, le);
59
  const d = type === 5 ? dv.getUint32(4, le) : dv.getInt32(4, le);
60
  return d !== 0 ? n / d : NaN;
61
  }
62
+ default: return NaN; // BYTE, ASCII, UNDEFINED
63
  }
64
  }
65
 
 
67
  let s = 0;
68
  while (s + 6 <= exif.length && ascii(exif, s, 6) === "Exif\0\0") s += 6;
69
  const b = exif.subarray(s);
70
+ if (b.length === 0) return null;
71
+ const prefix = ascii(b, 0, 4);
72
+ if (!["MM\0*", "II*\0", "MM*\0", "II\0*", "MM\0+", "II+\0"].includes(prefix)) {
73
+ throw new ExifError("not a TIFF header");
74
+ }
75
+ if (b[2] === 43 || b.length < 8) throw new ExifError("truncated TIFF header"); // BigTIFF too
76
+ const le = prefix.startsWith("II");
77
  const ifd = u32(b, 4, le);
78
  if (ifd + 2 > b.length) return null;
79
  let found = null;
 
81
  for (let i = 0; i < count; i++) {
82
  const e = ifd + 2 + i * 12;
83
  if (e + 12 > b.length) break;
84
+ const tag = u16(b, e, le), type = u16(b, e + 2, le), n = u32(b, e + 4, le);
85
+ if (!UNIT[type]) continue;
86
+ const size = UNIT[type] * n;
87
+ let at = e + 8;
88
+ if (size > 4) {
89
+ at = u32(b, e + 8, le);
90
+ if (at + size > b.length) break;
91
+ }
92
+ if (size === 0) continue;
93
+ if (tag === 0x0112) found = firstValue(b, at, type, le);
94
  }
95
  return found;
96
  }
 
103
  // What exif_transpose does with the value: 2-8 transform the image, anything else nothing.
104
  const effective = (value) => (Number.isInteger(value) && value >= 2 && value <= 8 ? value : 1);
105
 
106
+ // onBadExif: "refuse" (what happens in Pillow for PNG, WebP and most JPEGs) or "upright"
107
+ // (a JPEG without a JFIF dpi: Pillow reads its EXIF early, swallows the error and then
108
+ // ignores XMP too).
109
+ function orientationOf(exif, xmp, onBadExif = "refuse") {
110
+ let fromExif = null;
111
+ try {
112
+ fromExif = exif ? exifOrientation(exif) : null;
113
+ } catch (err) {
114
+ if (!(err instanceof ExifError)) throw err;
115
+ if (onBadExif === "upright") return 1;
116
+ throw new ImageError("That file's metadata is damaged, so it could not be read.");
117
+ }
118
  if (fromExif !== null) return effective(fromExif);
119
  return effective(xmp !== null ? xmpOrientation(xmp) : null);
120
  }
 
134
  const tooMuch = () => new ImageError("That file carries too much metadata to be read safely.");
135
 
136
  // -> Uint8Array, or null when the data is corrupt; throws when it expands past the limit.
137
+ function inflateLimited(data) {
138
+ const out = new Uint8Array(MAX_TEXT_CHUNK);
139
+ const { filled, overflow, error } = inflateInto(data, out);
140
+ if (overflow) throw tooMuch();
141
+ return error ? null : out.slice(0, filled);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  }
143
 
144
  // --- Containers ------------------------------------------------------------------------
 
148
  function jpegHeader(b) {
149
  let width = 0, height = 0, components = 0, scanAt = -1;
150
  const exif = [];
151
+ let xmp = null, dpi = false;
152
+ const junk = []; // stray bytes before markers, which libjpeg skips with a warning
153
  let o = 2;
154
  while (o < b.length) {
155
+ if (b[o] !== 0xff) {
156
+ junk.push(o++);
157
+ continue;
158
+ }
159
  while (o < b.length && b[o] === 0xff) o++;
160
  if (o >= b.length) break;
161
  const marker = b[o++];
162
+ if (marker === 0x01) throw new ImageError("That file could not be read as an image."); // TEM: Pillow refuses
163
+ if (marker === 0x00 || (marker >= 0xd0 && marker <= 0xd8)) continue;
164
  if (marker === 0xd9 || o + 2 > b.length) break;
165
  const length = u16(b, o, false);
166
  if (length < 2 || o + length > b.length) break;
167
  const data = b.subarray(o + 2, o + length);
168
  if (marker === 0xda) { scanAt = o + length; break; }
169
+ if (marker === 0xe0 && ascii(data, 0, 5) === "JFIF\0" && data.length >= 12 && (data[7] === 1 || data[7] === 2)) dpi = true;
170
  if (marker === 0xe1 && ascii(data, 0, 6) === "Exif\0\0") exif.push(exif.length ? data.subarray(6) : data);
171
  else if (marker === 0xe1 && ascii(data, 0, 29) === "http://ns.adobe.com/xap/1.0/\0") xmp = latin1(data.subarray(29));
172
  const sof = marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker);
 
183
  for (let i = scanAt; scanAt >= 0 && i + 1 < b.length; i++) {
184
  if (b[i] === 0xff && b[i + 1] === 0xd9) { complete = true; break; }
185
  }
186
+ const orientation = orientationOf(exif.length ? concat(exif) : null, xmp, dpi ? "refuse" : "upright");
187
+ // The WebAssembly decoder treats libjpeg's warning as an error, so it gets the file
188
+ // without the stray bytes, which is what libjpeg (and so Pillow) decodes.
189
+ let decodeBytes = null;
190
+ if (junk.length) {
191
+ decodeBytes = new Uint8Array(b.length - junk.length);
192
+ let from = 0, to = 0;
193
+ for (const at of junk) {
194
+ decodeBytes.set(b.subarray(from, at), to);
195
+ to += at - from;
196
+ from = at + 1;
197
+ }
198
+ decodeBytes.set(b.subarray(from), to);
199
+ }
200
+ return { width, height, components, complete, orientation, decodeBytes };
201
  }
202
 
203
+ // PNG chunks up to IEND; a chunk that does not fit in the file ends the walk.
204
  export function* pngChunks(b) {
205
  for (let o = 8; o + 12 <= b.length; ) {
206
  const size = u32(b, o, false);
207
  if (o + 12 + size > b.length) return;
208
+ const type = ascii(b, o + 4, 4);
209
+ yield { type, at: o, data: b.subarray(o + 8, o + 8 + size) };
210
+ if (type === "IEND") return; // Pillow stops here
211
  o += 12 + size;
212
  }
213
  }
214
 
215
+ // Characters of valid UTF-8, counted like Python's len() (code points).
216
+ function codePoints(bytes) {
217
+ let n = 0;
218
+ for (let i = 0; i < bytes.length; i++) if ((bytes[i] & 0xc0) !== 0x80) n++;
219
+ return n;
220
+ }
221
+
222
+ // Only these text keys are used; other text only counts towards Pillow's memory limit.
223
+ const NEEDED = new Set(["Raw profile type exif", "XML:com.adobe.xmp"]);
224
+ const textOf = (key, value) => (NEEDED.has(key) ? latin1(value) : "");
225
 
226
  // A PNG text chunk as Pillow reads it -> { key, text, xmpBytes, length } or null (ignored).
227
+ function pngText(chunk) {
228
  const d = chunk.data;
229
  const nul = d.indexOf(0);
230
  if (chunk.type === "tEXt") {
231
  const key = latin1(nul < 0 ? d : d.subarray(0, nul));
232
  const value = nul < 0 ? new Uint8Array() : d.subarray(nul + 1);
233
+ return key ? { key, text: textOf(key, value), length: value.length } : null;
234
  }
235
  if (chunk.type === "zTXt") {
236
  const key = latin1(nul < 0 ? d : d.subarray(0, nul));
237
  const rest = nul < 0 ? new Uint8Array() : d.subarray(nul + 1);
238
  if (rest.length && rest[0] !== 0) throw new ImageError("That file could not be read as an image.");
239
+ const value = inflateLimited(rest.subarray(1)) ?? new Uint8Array();
240
+ return key ? { key, text: textOf(key, value), length: value.length } : null;
241
  }
242
  // iTXt: keyword, compression flag, method, language tag, translated keyword, text.
243
  if (nul < 0 || d.length - nul - 1 < 2) return null;
 
248
  let value = d.subarray(translated + 1);
249
  if (flag !== 0) {
250
  if (method !== 0) return null;
251
+ value = inflateLimited(value);
252
  if (value === null) return null;
253
  }
254
  const key = latin1(d.subarray(0, nul));
 
261
  } catch {
262
  return { key: null, xmpBytes };
263
  }
264
+ return { key, text: NEEDED.has(key) ? text : "", xmpBytes, length: codePoints(value) };
265
  }
266
 
267
  // An iCCP colour profile is not used, but Pillow refuses one it cannot safely decompress.
268
+ function checkIccp(chunk) {
269
  const d = chunk.data;
270
  const nul = d.indexOf(0);
271
  if (nul < 0 || d[nul + 1] !== 0) throw new ImageError("That file could not be read as an image.");
272
+ inflateLimited(d.subarray(nul + 2));
273
  }
274
 
275
  async function pngHeader(b) {
276
+ let exif = null, ihdr = null, seenData = false, memory = 0, xmpRaw = null;
277
  const info = {}; // Pillow's im_info for the keys that matter: the last chunk wins
278
  for (const c of pngChunks(b)) {
279
+ if (c.type === "IDAT") seenData = true;
280
+ if (c.type === "IHDR" && !seenData && c.data.length >= 13) ihdr = c.data; // as png.js uses
281
  if (c.type === "eXIf") exif = c.data; // Pillow keeps the last
282
+ if (c.type === "iCCP") checkIccp(c);
283
  if (c.type === "tEXt" || c.type === "zTXt" || c.type === "iTXt") {
284
+ const t = pngText(c);
285
  if (!t) continue;
286
  if (t.xmpBytes !== null && t.xmpBytes !== undefined) xmpRaw = t.xmpBytes;
287
  if (t.key === null) continue;
 
299
  // Pillow: XMP stored under its own key (any text chunk) first, then raw iTXt XMP.
300
  const xmp = info["XML:com.adobe.xmp"] || xmpRaw || null;
301
  return {
302
+ width: ihdr ? u32(ihdr, 0, false) : 0,
303
+ height: ihdr ? u32(ihdr, 4, false) : 0,
304
  complete: true, // whether all pixel data is there is judged by png.js, like Pillow
305
  orientation: orientationOf(exif && exif.length ? exif : null, xmp),
306
  };
307
  }
308
 
309
+ // libwebp's WebPDemux acceptance rules (non-incremental), which Pillow's WebP reader uses:
310
+ // a file it would reject is refused here too. (Reviewed port of libwebp's demux.c checks.)
311
+ function webpDemuxOk(b) {
312
+ const riffSize = u32(b, 4, true);
313
+ if (riffSize < 8 || riffSize > 0xfffffff6) return false;
314
+ const end = Math.min(b.length, riffSize + 8);
315
+ if (riffSize + 8 > b.length) return false; // incomplete
316
+ let o = 12;
317
+ const chunkAt = (p) => (p + 8 <= end ? { id: ascii(b, p, 4), size: u32(b, p + 4, true) } : null);
318
+ const first = chunkAt(o);
319
+ if (!first) return false;
320
+ const fits = (p, size) => size <= 0xfffffff6 && p + 8 + size + (size & 1) <= end;
321
+ // StoreFrame: ALPH? then VP8/VP8L; returns { next, ok, image, alphaAfter }
322
+ const storeFrame = (p) => {
323
+ let alpha = 0, image = 0, alphaAt = -1, imageAt = -1;
324
+ for (;;) {
325
+ const c = chunkAt(p);
326
+ if (!c) return { ok: false };
327
+ if (!fits(p, c.size)) return { ok: false };
328
+ const padded = c.size + (c.size & 1);
329
+ if (c.id === "ALPH" && alpha === 0) { alpha++; alphaAt = p; p += 8 + padded; }
330
+ else if ((c.id === "VP8 " || c.id === "VP8L") && image === 0) {
331
+ if (c.id === "VP8L" && alpha > 0) return { ok: false };
332
+ image++; imageAt = p; p += 8 + padded;
333
+ } else break;
334
+ if (p === end) break;
335
+ if (end - p < 8) return { ok: false };
336
+ }
337
+ if (!image) return { ok: false };
338
+ if (alpha && alphaAt > imageAt) return { ok: false };
339
+ return { ok: true, next: p, alphaAt };
340
+ };
341
+ if (first.id === "VP8 " || first.id === "VP8L") return storeFrame(o).ok;
342
+ if (first.id !== "VP8X") return false;
343
+ if (first.size < 10 || !fits(o, first.size)) return false;
344
+ const flags = b[o + 8];
345
+ if (flags & ~0x3e) return false;
346
+ if (flags & 0x02) return true; // animations are refused by the page anyway
347
+ o += 8 + first.size + (first.size & 1);
348
+ if (end - o < 8) return false;
349
+ let frames = 0;
350
+ while (o < end) {
351
+ const c = chunkAt(o);
352
+ if (!c || !fits(o, c.size)) return false;
353
+ if (c.id === "VP8X" || c.id === "ANMF") return false;
354
+ if (c.id === "ALPH" || c.id === "VP8 " || c.id === "VP8L") {
355
+ if (frames) return false;
356
+ const f = storeFrame(o);
357
+ if (!f.ok) return false;
358
+ frames++;
359
+ o = f.next;
360
+ } else {
361
+ o += 8 + c.size + (c.size & 1);
362
+ }
363
+ if (o === end) break;
364
+ if (end - o < 8) return false;
365
+ }
366
+ return frames === 1;
367
+ }
368
+
369
  function webpHeader(b) {
370
+ let width = 0, height = 0, flags = 0, exif = null, xmp = null, alpha = false;
371
  const declared = u32(b, 4, true) + 8;
372
  for (let o = 12; o + 8 <= b.length; ) {
373
  const id = ascii(b, o, 4), size = u32(b, o + 4, true);
374
  if (o + 8 + size > b.length) break;
375
  const data = b.subarray(o + 8, o + 8 + size);
376
+ if (id === "VP8X" && size >= 10 && o === 12) { // only as the first chunk, as in libwebp
377
  flags = data[0];
378
  width = 1 + (data[4] | (data[5] << 8) | (data[6] << 16));
379
  height = 1 + (data[7] | (data[8] << 8) | (data[9] << 16));
380
+ alpha = Boolean(flags & 0x10);
381
  } else if (id === "VP8 " && !width && size >= 10) {
382
  width = u16(data, 6, true) & 0x3fff;
383
  height = u16(data, 8, true) & 0x3fff;
 
385
  const bits = u32(data, 1, true);
386
  width = 1 + (bits & 0x3fff);
387
  height = 1 + ((bits >> 14) & 0x3fff);
388
+ alpha = Boolean((bits >>> 28) & 1); // the alpha_is_used bit of a simple lossless file
 
389
  } else if (id === "EXIF" && exif === null) {
390
  exif = data;
391
  } else if (id === "XMP " && xmp === null) {
 
393
  }
394
  o += 8 + size + (size & 1);
395
  }
396
+ // libwebp's demuxer only exposes metadata the VP8X header announces.
397
  if (!(flags & 0x08)) exif = null;
398
  if (!(flags & 0x04)) xmp = null;
399
+ const animated = Boolean(flags & 0x02);
400
+ const complete = declared <= b.length;
401
+ if (complete && !animated && !webpDemuxOk(b)) {
402
+ throw new ImageError("That file could not be read as an image: it may be damaged.");
403
+ }
404
+ // alpha: whether Pillow keeps the alpha channel (otherwise the decoded colours are used
405
+ // as they are, without flattening).
406
+ return { width, height, animated, alpha, complete, orientation: orientationOf(exif, xmp) };
407
  }
408
 
409
  // { format, width, height, orientation, complete, components (JPEG), animated (WebP) }
index.html CHANGED
@@ -5,7 +5,7 @@
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <!-- Hugging Face serves large files (model.onnx, the WebAssembly runtime) from its CDN via a redirect;
7
  the model is still checked against its SHA-256 in model-info.js before use. -->
8
- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self' https://*.hf.co https://*.huggingface.co; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; worker-src 'self' blob:; base-uri 'none'; form-action 'none'; object-src 'none'">
9
  <title>Waste Sorting Classifier</title>
10
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E%E2%99%BB%EF%B8%8F%3C/text%3E%3C/svg%3E">
11
  <meta name="description" content="Classify a photo of waste into six recycling categories. The model runs in your browser: photos never leave your device.">
@@ -66,7 +66,7 @@
66
  }
67
  .drop.over { border-color: var(--accent); }
68
  button:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
69
- .drop img { max-width: 100%; max-height: 300px; border-radius: 8px; }
70
  .drop strong { color: var(--text); }
71
  button.pick {
72
  font: inherit; font-weight: 600; background: var(--accent); color: #fff; border: 0;
@@ -112,7 +112,7 @@
112
  <section class="card">
113
  <div class="drop" id="drop">
114
  <span id="drop-hint"><strong>Drop a photo here</strong><br>JPEG, PNG or WebP</span>
115
- <img id="preview" alt="Your photo" hidden>
116
  <button class="pick" type="button" id="pick">Choose a photo</button>
117
  <input id="file" type="file" accept="image/jpeg,image/png,image/webp" hidden>
118
  </div>
@@ -134,6 +134,7 @@
134
  <p><a href="https://github.com/vladzpop11/waste-sorting-classifier">Code, data handling and evaluation on GitHub</a></p>
135
  </footer>
136
  </main>
 
137
  <script type="module" src="app.js"></script>
138
  </body>
139
  </html>
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <!-- Hugging Face serves large files (model.onnx, the WebAssembly runtime) from its CDN via a redirect;
7
  the model is still checked against its SHA-256 in model-info.js before use. -->
8
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self' https://*.hf.co https://*.huggingface.co; img-src 'self' data:; style-src 'self' 'unsafe-inline'; worker-src 'self' blob:; base-uri 'none'; form-action 'none'; object-src 'none'">
9
  <title>Waste Sorting Classifier</title>
10
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E%E2%99%BB%EF%B8%8F%3C/text%3E%3C/svg%3E">
11
  <meta name="description" content="Classify a photo of waste into six recycling categories. The model runs in your browser: photos never leave your device.">
 
66
  }
67
  .drop.over { border-color: var(--accent); }
68
  button:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
69
+ .drop canvas { max-width: 100%; max-height: 300px; border-radius: 8px; }
70
  .drop strong { color: var(--text); }
71
  button.pick {
72
  font: inherit; font-weight: 600; background: var(--accent); color: #fff; border: 0;
 
112
  <section class="card">
113
  <div class="drop" id="drop">
114
  <span id="drop-hint"><strong>Drop a photo here</strong><br>JPEG, PNG or WebP</span>
115
+ <canvas id="preview" role="img" aria-label="Your photo, as the model sees it" hidden></canvas>
116
  <button class="pick" type="button" id="pick">Choose a photo</button>
117
  <input id="file" type="file" accept="image/jpeg,image/png,image/webp" hidden>
118
  </div>
 
134
  <p><a href="https://github.com/vladzpop11/waste-sorting-classifier">Code, data handling and evaluation on GitHub</a></p>
135
  </footer>
136
  </main>
137
+ <script src="vendor/libjpegturbowasm_decode.js"></script>
138
  <script type="module" src="app.js"></script>
139
  </body>
140
  </html>
inflate.js ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // zlib decompression with a hard output limit, in plain JavaScript (fflate), so that the
2
+ // result is the same in every browser, including those without DecompressionStream.
3
+ import { Unzlib } from "./vendor/fflate.mjs";
4
+
5
+ const STOP = Symbol("stop");
6
+ const SLICE = 4 * 1024; // deflate expands at most ~1032x, so a slice yields at most ~4 MiB
7
+
8
+ // Inflate `data` into `out` (a preallocated Uint8Array) and stop once it is full.
9
+ // -> { filled: bytes written, overflow: the stream had more, error: the stream is corrupt
10
+ // (or ended early) before `out` was full }
11
+ export function inflateInto(data, out) {
12
+ let filled = 0, overflow = false, ended = false;
13
+ const z = new Unzlib((chunk, final) => {
14
+ const n = Math.min(chunk.length, out.length - filled);
15
+ out.set(chunk.subarray(0, n), filled);
16
+ filled += n;
17
+ if (n < chunk.length) {
18
+ overflow = true;
19
+ throw STOP;
20
+ }
21
+ if (final) ended = true;
22
+ });
23
+ let error = false;
24
+ try {
25
+ // In slices, so that fflate hands over output as it goes instead of building the
26
+ // whole stream in one buffer first.
27
+ for (let at = 0; at < data.length; at += SLICE) {
28
+ z.push(data.subarray(at, at + SLICE), at + SLICE >= data.length);
29
+ }
30
+ if (!data.length) z.push(data, true);
31
+ } catch (err) {
32
+ if (err !== STOP) error = true;
33
+ }
34
+ return { filled, overflow, error: error || (!ended && !overflow && filled < out.length) };
35
+ }
model-info.js CHANGED
@@ -19,6 +19,6 @@ export const MODEL = {
19
  };
20
  export const WASM = {
21
  "ort-wasm-simd-threaded.wasm": "3398c10d07d229bd91b364548e130e0e51a8e5704b88c7c083ebbeb78842dee2",
22
- "mozjpeg_dec.wasm": "a7c4b12169817e779ff4af137981393ae924944e167ad1bd95747c9199162d3e",
23
  "webp_dec.wasm": "30fb52fa2a80166d25ba7debf902218904ba1f05ccce9f959f722beff9e2f344"
24
  };
 
19
  };
20
  export const WASM = {
21
  "ort-wasm-simd-threaded.wasm": "3398c10d07d229bd91b364548e130e0e51a8e5704b88c7c083ebbeb78842dee2",
22
+ "libjpegturbowasm_decode.wasm": "a8d104602540b9e7aeefeaac23af7380f40c5a3460291d40246a26783929a696",
23
  "webp_dec.wasm": "30fb52fa2a80166d25ba7debf902218904ba1f05ccce9f959f722beff9e2f344"
24
  };
png.js CHANGED
@@ -7,7 +7,10 @@
7
  // - the default image (IDAT) of an animated PNG, as Pillow uses;
8
  // - damaged files are refused where Pillow refuses them: a bad checksum in a chunk before
9
  // the image data, image data that ends early, an unknown filter.
 
 
10
  import { ImageError, pngChunks } from "./image-header.js";
 
11
 
12
  const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
13
  let c = n;
@@ -27,39 +30,18 @@ const DEPTHS = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6
27
  // Adam7 passes: x0, y0, dx, dy.
28
  const ADAM7 = [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]];
29
 
30
- // Inflate until `expected` bytes have arrived. Like Pillow, a stream that is damaged only
31
- // after the pixel data (e.g. a missing checksum) is accepted; one that ends early is not.
32
- async function inflateAtLeast(data, expected) {
33
- const reader = new Blob([data]).stream().pipeThrough(new DecompressionStream("deflate")).getReader();
34
- const out = new Uint8Array(expected);
35
- let filled = 0;
36
- try {
37
- while (filled < expected) {
38
- const { done, value } = await reader.read();
39
- if (done) break;
40
- const n = Math.min(value.length, expected - filled);
41
- out.set(value.subarray(0, n), filled);
42
- filled += n;
43
- }
44
- } catch {
45
- // corrupt or truncated stream: judged by how much pixel data arrived
46
- }
47
- reader.cancel().catch(() => {});
48
- if (filled < expected) throw damaged();
49
- return out;
50
- }
51
-
52
- function unfilter(raw, offset, rows, rowBytes, bpp) {
53
- const out = new Uint8Array(rows * rowBytes);
54
  for (let y = 0; y < rows; y++) {
55
- const type = raw[offset + y * (rowBytes + 1)];
56
- const src = offset + y * (rowBytes + 1) + 1;
57
- const cur = y * rowBytes, prev = cur - rowBytes;
58
  for (let x = 0; x < rowBytes; x++) {
59
- const a = x >= bpp ? out[cur + x - bpp] : 0;
60
- const b = y > 0 ? out[prev + x] : 0;
61
- const c = x >= bpp && y > 0 ? out[prev + x - bpp] : 0;
62
- let v = raw[src + x];
63
  if (type === 1) v += a;
64
  else if (type === 2) v += b;
65
  else if (type === 3) v += (a + b) >> 1;
@@ -67,10 +49,9 @@ function unfilter(raw, offset, rows, rowBytes, bpp) {
67
  const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
68
  v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
69
  } else if (type !== 0) throw damaged();
70
- out[cur + x] = v & 0xff;
71
  }
72
  }
73
- return out;
74
  }
75
 
76
  // One sample (channel value) of a row, at full precision.
@@ -97,7 +78,7 @@ export async function decodePng(bytes) {
97
  const typeAndData = bytes.subarray(c.at + 4, c.at + 8 + c.data.length);
98
  const stored = new DataView(bytes.buffer, bytes.byteOffset + c.at + 8 + c.data.length, 4).getUint32(0);
99
  if (crc32(typeAndData) !== stored) throw damaged(); // Pillow checks every chunk before IDAT
100
- if (c.type === "IHDR") ihdr = c.data;
101
  else if (c.type === "PLTE") palette = c.data;
102
  else if (c.type === "tRNS") trns = c.data;
103
  }
@@ -119,7 +100,9 @@ export async function decodePng(bytes) {
119
  const total = idat.reduce((n, d) => n + d.length, 0);
120
  const compressed = new Uint8Array(total);
121
  idat.reduce((o, d) => (compressed.set(d, o), o + d.length), 0);
122
- const raw = await inflateAtLeast(compressed, expected);
 
 
123
 
124
  // Transparency, as Pillow's convert("RGBA") applies it.
125
  let alphaOfIndex = null, transparent = null;
@@ -137,10 +120,12 @@ export async function decodePng(bytes) {
137
  let offset = 0;
138
  for (const p of passes) {
139
  if (!p.w || !p.h) continue;
140
- const pixels = unfilter(raw, offset, p.h, p.rowBytes, bpp);
 
141
  offset += p.h * (p.rowBytes + 1);
142
  for (let y = 0; y < p.h; y++) {
143
- const row = pixels.subarray(y * p.rowBytes, (y + 1) * p.rowBytes);
 
144
  for (let x = 0; x < p.w; x++) {
145
  const o = ((p.y0 + y * p.dy) * width + p.x0 + x * p.dx) * outChannels;
146
  let r, g, b, a = 255;
 
7
  // - the default image (IDAT) of an animated PNG, as Pillow uses;
8
  // - damaged files are refused where Pillow refuses them: a bad checksum in a chunk before
9
  // the image data, image data that ends early, an unknown filter.
10
+ // Memory: the inflated rows are unfiltered in place, so a decode holds the compressed
11
+ // data, the raw rows and the 8-bit output.
12
  import { ImageError, pngChunks } from "./image-header.js";
13
+ import { inflateInto } from "./inflate.js";
14
 
15
  const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
16
  let c = n;
 
30
  // Adam7 passes: x0, y0, dx, dy.
31
  const ADAM7 = [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]];
32
 
33
+ // Undo the row filters in place: raw holds rows of [filter type][rowBytes bytes].
34
+ function unfilterInPlace(raw, offset, rows, rowBytes, bpp) {
35
+ const stride = rowBytes + 1;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  for (let y = 0; y < rows; y++) {
37
+ const start = offset + y * stride;
38
+ const type = raw[start];
39
+ const cur = start + 1, prev = cur - stride;
40
  for (let x = 0; x < rowBytes; x++) {
41
+ const a = x >= bpp ? raw[cur + x - bpp] : 0;
42
+ const b = y > 0 ? raw[prev + x] : 0;
43
+ const c = x >= bpp && y > 0 ? raw[prev + x - bpp] : 0;
44
+ let v = raw[cur + x];
45
  if (type === 1) v += a;
46
  else if (type === 2) v += b;
47
  else if (type === 3) v += (a + b) >> 1;
 
49
  const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
50
  v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
51
  } else if (type !== 0) throw damaged();
52
+ raw[cur + x] = v & 0xff;
53
  }
54
  }
 
55
  }
56
 
57
  // One sample (channel value) of a row, at full precision.
 
78
  const typeAndData = bytes.subarray(c.at + 4, c.at + 8 + c.data.length);
79
  const stored = new DataView(bytes.buffer, bytes.byteOffset + c.at + 8 + c.data.length, 4).getUint32(0);
80
  if (crc32(typeAndData) !== stored) throw damaged(); // Pillow checks every chunk before IDAT
81
+ if (c.type === "IHDR") ihdr = c.data; // the last one before IDAT, like Pillow
82
  else if (c.type === "PLTE") palette = c.data;
83
  else if (c.type === "tRNS") trns = c.data;
84
  }
 
100
  const total = idat.reduce((n, d) => n + d.length, 0);
101
  const compressed = new Uint8Array(total);
102
  idat.reduce((o, d) => (compressed.set(d, o), o + d.length), 0);
103
+ // Like Pillow, a stream damaged only after the pixel data (e.g. its checksum) is fine.
104
+ const raw = new Uint8Array(expected);
105
+ if (inflateInto(compressed, raw).filled < expected) throw damaged();
106
 
107
  // Transparency, as Pillow's convert("RGBA") applies it.
108
  let alphaOfIndex = null, transparent = null;
 
120
  let offset = 0;
121
  for (const p of passes) {
122
  if (!p.w || !p.h) continue;
123
+ unfilterInPlace(raw, offset, p.h, p.rowBytes, bpp);
124
+ const passStart = offset;
125
  offset += p.h * (p.rowBytes + 1);
126
  for (let y = 0; y < p.h; y++) {
127
+ const rowStart = passStart + y * (p.rowBytes + 1) + 1;
128
+ const row = raw.subarray(rowStart, rowStart + p.rowBytes);
129
  for (let x = 0; x < p.w; x++) {
130
  const o = ((p.y0 + y * p.dy) * width + p.x0 + x * p.dx) * outChannels;
131
  let r, g, b, a = 255;
vendor/fflate.mjs ADDED
@@ -0,0 +1,2665 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // DEFLATE is a complex format; to read this code, you should probably check the RFC first:
2
+ // https://tools.ietf.org/html/rfc1951
3
+ // You may also wish to take a look at the guide I made about this program:
4
+ // https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
5
+ // Some of the following code is similar to that of UZIP.js:
6
+ // https://github.com/photopea/UZIP.js
7
+ // However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
8
+ // Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
9
+ // is better for memory in most engines (I *think*).
10
+ var ch2 = {};
11
+ var wk = (function (c, id, msg, transfer, cb) {
12
+ var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([
13
+ c + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'
14
+ ], { type: 'text/javascript' }))));
15
+ w.onmessage = function (e) {
16
+ var d = e.data, ed = d.$e$;
17
+ if (ed) {
18
+ var err = new Error(ed[0]);
19
+ err['code'] = ed[1];
20
+ err.stack = ed[2];
21
+ cb(err, null);
22
+ }
23
+ else
24
+ cb(null, d);
25
+ };
26
+ w.postMessage(msg, transfer);
27
+ return w;
28
+ });
29
+
30
+ // aliases for shorter compressed code (most minifers don't do this)
31
+ var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;
32
+ // fixed length extra bits
33
+ var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
34
+ // fixed distance extra bits
35
+ var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
36
+ // code length index map
37
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
38
+ // get base, reverse index map from extra bits
39
+ var freb = function (eb, start) {
40
+ var b = new u16(31);
41
+ for (var i = 0; i < 31; ++i) {
42
+ b[i] = start += 1 << eb[i - 1];
43
+ }
44
+ // numbers here are at max 18 bits
45
+ var r = new i32(b[30]);
46
+ for (var i = 1; i < 30; ++i) {
47
+ for (var j = b[i]; j < b[i + 1]; ++j) {
48
+ r[j] = ((j - b[i]) << 5) | i;
49
+ }
50
+ }
51
+ return { b: b, r: r };
52
+ };
53
+ var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;
54
+ // we can ignore the fact that the other numbers are wrong; they never happen anyway
55
+ fl[28] = 258, revfl[258] = 28;
56
+ var _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r;
57
+ // map of value to reverse (assuming 16 bits)
58
+ var rev = new u16(32768);
59
+ for (var i = 0; i < 32768; ++i) {
60
+ // reverse table algorithm from SO
61
+ var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);
62
+ x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2);
63
+ x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4);
64
+ rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1;
65
+ }
66
+ // create huffman tree from u8 "map": index -> code length for code index
67
+ // mb (max bits) must be at most 15
68
+ // TODO: optimize/split up?
69
+ var hMap = (function (cd, mb, r) {
70
+ var s = cd.length;
71
+ // index
72
+ var i = 0;
73
+ // u16 "map": index -> # of codes with bit length = index
74
+ var l = new u16(mb);
75
+ // length of cd must be 288 (total # of codes)
76
+ for (; i < s; ++i) {
77
+ if (cd[i])
78
+ ++l[cd[i] - 1];
79
+ }
80
+ // u16 "map": index -> minimum code for bit length = index
81
+ var le = new u16(mb);
82
+ for (i = 1; i < mb; ++i) {
83
+ le[i] = (le[i - 1] + l[i - 1]) << 1;
84
+ }
85
+ var co;
86
+ if (r) {
87
+ // u16 "map": index -> number of actual bits, symbol for code
88
+ co = new u16(1 << mb);
89
+ // bits to remove for reverser
90
+ var rvb = 15 - mb;
91
+ for (i = 0; i < s; ++i) {
92
+ // ignore 0 lengths
93
+ if (cd[i]) {
94
+ // num encoding both symbol and bits read
95
+ var sv = (i << 4) | cd[i];
96
+ // free bits
97
+ var r_1 = mb - cd[i];
98
+ // start value
99
+ var v = le[cd[i] - 1]++ << r_1;
100
+ // m is end value
101
+ for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
102
+ // every 16 bit value starting with the code yields the same result
103
+ co[rev[v] >> rvb] = sv;
104
+ }
105
+ }
106
+ }
107
+ }
108
+ else {
109
+ co = new u16(s);
110
+ for (i = 0; i < s; ++i) {
111
+ if (cd[i]) {
112
+ co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);
113
+ }
114
+ }
115
+ }
116
+ return co;
117
+ });
118
+ // fixed length tree
119
+ var flt = new u8(288);
120
+ for (var i = 0; i < 144; ++i)
121
+ flt[i] = 8;
122
+ for (var i = 144; i < 256; ++i)
123
+ flt[i] = 9;
124
+ for (var i = 256; i < 280; ++i)
125
+ flt[i] = 7;
126
+ for (var i = 280; i < 288; ++i)
127
+ flt[i] = 8;
128
+ // fixed distance tree
129
+ var fdt = new u8(32);
130
+ for (var i = 0; i < 32; ++i)
131
+ fdt[i] = 5;
132
+ // fixed length map
133
+ var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);
134
+ // fixed distance map
135
+ var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
136
+ // find max of array
137
+ var max = function (a) {
138
+ var m = a[0];
139
+ for (var i = 1; i < a.length; ++i) {
140
+ if (a[i] > m)
141
+ m = a[i];
142
+ }
143
+ return m;
144
+ };
145
+ // read d, starting at bit p and mask with m
146
+ var bits = function (d, p, m) {
147
+ var o = (p / 8) | 0;
148
+ return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
149
+ };
150
+ // read d, starting at bit p continuing for at least 16 bits
151
+ var bits16 = function (d, p) {
152
+ var o = (p / 8) | 0;
153
+ return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
154
+ };
155
+ // get end of byte
156
+ var shft = function (p) { return ((p + 7) / 8) | 0; };
157
+ // typed array slice - allows garbage collector to free original reference,
158
+ // while being more compatible than .slice
159
+ var slc = function (v, s, e) {
160
+ if (s == null || s < 0)
161
+ s = 0;
162
+ if (e == null || e > v.length)
163
+ e = v.length;
164
+ // can't use .constructor in case user-supplied
165
+ return new u8(v.subarray(s, e));
166
+ };
167
+ /**
168
+ * Codes for errors generated within this library
169
+ */
170
+ export var FlateErrorCode = {
171
+ UnexpectedEOF: 0,
172
+ InvalidBlockType: 1,
173
+ InvalidLengthLiteral: 2,
174
+ InvalidDistance: 3,
175
+ StreamFinished: 4,
176
+ NoStreamHandler: 5,
177
+ InvalidHeader: 6,
178
+ NoCallback: 7,
179
+ InvalidUTF8: 8,
180
+ ExtraFieldTooLong: 9,
181
+ InvalidDate: 10,
182
+ FilenameTooLong: 11,
183
+ StreamFinishing: 12,
184
+ InvalidZipData: 13,
185
+ UnknownCompressionMethod: 14
186
+ };
187
+ // error codes
188
+ var ec = [
189
+ 'unexpected EOF',
190
+ 'invalid block type',
191
+ 'invalid length/literal',
192
+ 'invalid distance',
193
+ 'stream finished',
194
+ 'no stream handler',
195
+ ,
196
+ 'no callback',
197
+ 'invalid UTF-8 data',
198
+ 'extra field too long',
199
+ 'date not in range 1980-2099',
200
+ 'filename too long',
201
+ 'stream finishing',
202
+ 'invalid zip data'
203
+ // determined by unknown compression method
204
+ ];
205
+ ;
206
+ var err = function (ind, msg, nt) {
207
+ var e = new Error(msg || ec[ind]);
208
+ e.code = ind;
209
+ if (Error.captureStackTrace)
210
+ Error.captureStackTrace(e, err);
211
+ if (!nt)
212
+ throw e;
213
+ return e;
214
+ };
215
+ // expands raw DEFLATE data
216
+ var inflt = function (dat, st, buf, dict) {
217
+ // source length dict length
218
+ var sl = dat.length, dl = dict ? dict.length : 0;
219
+ if (!sl || st.f && !st.l)
220
+ return buf || new u8(0);
221
+ var noBuf = !buf;
222
+ // have to estimate size
223
+ var resize = noBuf || st.i != 2;
224
+ // no state
225
+ var noSt = st.i;
226
+ // Assumes roughly 33% compression ratio average
227
+ if (noBuf)
228
+ buf = new u8(sl * 3);
229
+ // ensure buffer can fit at least l elements
230
+ var cbuf = function (l) {
231
+ var bl = buf.length;
232
+ // need to increase size to fit
233
+ if (l > bl) {
234
+ // Double or set to necessary, whichever is greater
235
+ var nbuf = new u8(Math.max(bl * 2, l));
236
+ nbuf.set(buf);
237
+ buf = nbuf;
238
+ }
239
+ };
240
+ // last chunk bitpos bytes
241
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
242
+ // total bits
243
+ var tbts = sl * 8;
244
+ do {
245
+ if (!lm) {
246
+ // BFINAL - this is only 1 when last chunk is next
247
+ final = bits(dat, pos, 1);
248
+ // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
249
+ var type = bits(dat, pos + 1, 3);
250
+ pos += 3;
251
+ if (!type) {
252
+ // go to end of byte boundary
253
+ var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
254
+ if (t > sl) {
255
+ if (noSt)
256
+ err(0);
257
+ break;
258
+ }
259
+ // ensure size
260
+ if (resize)
261
+ cbuf(bt + l);
262
+ // Copy over uncompressed data
263
+ buf.set(dat.subarray(s, t), bt);
264
+ // Get new bitpos, update byte count
265
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
266
+ continue;
267
+ }
268
+ else if (type == 1)
269
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
270
+ else if (type == 2) {
271
+ // literal lengths
272
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
273
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
274
+ pos += 14;
275
+ // length+distance tree
276
+ var ldt = new u8(tl);
277
+ // code length tree
278
+ var clt = new u8(19);
279
+ for (var i = 0; i < hcLen; ++i) {
280
+ // use index map to get real code
281
+ clt[clim[i]] = bits(dat, pos + i * 3, 7);
282
+ }
283
+ pos += hcLen * 3;
284
+ // code lengths bits
285
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
286
+ // code lengths map
287
+ var clm = hMap(clt, clb, 1);
288
+ for (var i = 0; i < tl;) {
289
+ var r = clm[bits(dat, pos, clbmsk)];
290
+ // bits read
291
+ pos += r & 15;
292
+ // symbol
293
+ var s = r >> 4;
294
+ // code length to copy
295
+ if (s < 16) {
296
+ ldt[i++] = s;
297
+ }
298
+ else {
299
+ // copy count
300
+ var c = 0, n = 0;
301
+ if (s == 16)
302
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
303
+ else if (s == 17)
304
+ n = 3 + bits(dat, pos, 7), pos += 3;
305
+ else if (s == 18)
306
+ n = 11 + bits(dat, pos, 127), pos += 7;
307
+ while (n--)
308
+ ldt[i++] = c;
309
+ }
310
+ }
311
+ // length tree distance tree
312
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
313
+ // max length bits
314
+ lbt = max(lt);
315
+ // max dist bits
316
+ dbt = max(dt);
317
+ lm = hMap(lt, lbt, 1);
318
+ dm = hMap(dt, dbt, 1);
319
+ }
320
+ else
321
+ err(1);
322
+ if (pos > tbts) {
323
+ if (noSt)
324
+ err(0);
325
+ break;
326
+ }
327
+ }
328
+ // Make sure the buffer can hold this + the largest possible addition
329
+ // Maximum chunk size (practically, theoretically infinite) is 2^17
330
+ if (resize)
331
+ cbuf(bt + 131072);
332
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
333
+ var lpos = pos;
334
+ for (;; lpos = pos) {
335
+ // bits read, code
336
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
337
+ pos += c & 15;
338
+ if (pos > tbts) {
339
+ if (noSt)
340
+ err(0);
341
+ break;
342
+ }
343
+ if (!c)
344
+ err(2);
345
+ if (sym < 256)
346
+ buf[bt++] = sym;
347
+ else if (sym == 256) {
348
+ lpos = pos, lm = null;
349
+ break;
350
+ }
351
+ else {
352
+ var add = sym - 254;
353
+ // no extra bits needed if less
354
+ if (sym > 264) {
355
+ // index
356
+ var i = sym - 257, b = fleb[i];
357
+ add = bits(dat, pos, (1 << b) - 1) + fl[i];
358
+ pos += b;
359
+ }
360
+ // dist
361
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
362
+ if (!d)
363
+ err(3);
364
+ pos += d & 15;
365
+ var dt = fd[dsym];
366
+ if (dsym > 3) {
367
+ var b = fdeb[dsym];
368
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
369
+ }
370
+ if (pos > tbts) {
371
+ if (noSt)
372
+ err(0);
373
+ break;
374
+ }
375
+ if (resize)
376
+ cbuf(bt + 131072);
377
+ var end = bt + add;
378
+ if (bt < dt) {
379
+ var shift = dl - dt, dend = Math.min(dt, end);
380
+ if (shift + bt < 0)
381
+ err(3);
382
+ for (; bt < dend; ++bt)
383
+ buf[bt] = dict[shift + bt];
384
+ }
385
+ for (; bt < end; ++bt)
386
+ buf[bt] = buf[bt - dt];
387
+ }
388
+ }
389
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
390
+ if (lm)
391
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
392
+ } while (!final);
393
+ // don't reallocate for streams or user buffers
394
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
395
+ };
396
+ // starting at p, write the minimum number of bits that can hold v to d
397
+ var wbits = function (d, p, v) {
398
+ v <<= p & 7;
399
+ var o = (p / 8) | 0;
400
+ d[o] |= v;
401
+ d[o + 1] |= v >> 8;
402
+ };
403
+ // starting at p, write the minimum number of bits (>8) that can hold v to d
404
+ var wbits16 = function (d, p, v) {
405
+ v <<= p & 7;
406
+ var o = (p / 8) | 0;
407
+ d[o] |= v;
408
+ d[o + 1] |= v >> 8;
409
+ d[o + 2] |= v >> 16;
410
+ };
411
+ // creates code lengths from a frequency table
412
+ var hTree = function (d, mb) {
413
+ // Need extra info to make a tree
414
+ var t = [];
415
+ for (var i = 0; i < d.length; ++i) {
416
+ if (d[i])
417
+ t.push({ s: i, f: d[i] });
418
+ }
419
+ var s = t.length;
420
+ var t2 = t.slice();
421
+ if (!s)
422
+ return { t: et, l: 0 };
423
+ if (s == 1) {
424
+ var v = new u8(t[0].s + 1);
425
+ v[t[0].s] = 1;
426
+ return { t: v, l: 1 };
427
+ }
428
+ t.sort(function (a, b) { return a.f - b.f; });
429
+ // after i2 reaches last ind, will be stopped
430
+ // freq must be greater than largest possible number of symbols
431
+ t.push({ s: -1, f: 25001 });
432
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
433
+ t[0] = { s: -1, f: l.f + r.f, l: l, r: r };
434
+ // efficient algorithm from UZIP.js
435
+ // i0 is lookbehind, i2 is lookahead - after processing two low-freq
436
+ // symbols that combined have high freq, will start processing i2 (high-freq,
437
+ // non-composite) symbols instead
438
+ // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/
439
+ while (i1 != s - 1) {
440
+ l = t[t[i0].f < t[i2].f ? i0++ : i2++];
441
+ r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
442
+ t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };
443
+ }
444
+ var maxSym = t2[0].s;
445
+ for (var i = 1; i < s; ++i) {
446
+ if (t2[i].s > maxSym)
447
+ maxSym = t2[i].s;
448
+ }
449
+ // code lengths
450
+ var tr = new u16(maxSym + 1);
451
+ // max bits in tree
452
+ var mbt = ln(t[i1 - 1], tr, 0);
453
+ if (mbt > mb) {
454
+ // more algorithms from UZIP.js
455
+ // TODO: find out how this code works (debt)
456
+ // ind debt
457
+ var i = 0, dt = 0;
458
+ // left cost
459
+ var lft = mbt - mb, cst = 1 << lft;
460
+ t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });
461
+ for (; i < s; ++i) {
462
+ var i2_1 = t2[i].s;
463
+ if (tr[i2_1] > mb) {
464
+ dt += cst - (1 << (mbt - tr[i2_1]));
465
+ tr[i2_1] = mb;
466
+ }
467
+ else
468
+ break;
469
+ }
470
+ dt >>= lft;
471
+ while (dt > 0) {
472
+ var i2_2 = t2[i].s;
473
+ if (tr[i2_2] < mb)
474
+ dt -= 1 << (mb - tr[i2_2]++ - 1);
475
+ else
476
+ ++i;
477
+ }
478
+ for (; i >= 0 && dt; --i) {
479
+ var i2_3 = t2[i].s;
480
+ if (tr[i2_3] == mb) {
481
+ --tr[i2_3];
482
+ ++dt;
483
+ }
484
+ }
485
+ mbt = mb;
486
+ }
487
+ return { t: new u8(tr), l: mbt };
488
+ };
489
+ // get the max length and assign length codes
490
+ var ln = function (n, l, d) {
491
+ return n.s == -1
492
+ ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))
493
+ : (l[n.s] = d);
494
+ };
495
+ // length codes generation
496
+ var lc = function (c) {
497
+ var s = c.length;
498
+ // Note that the semicolon was intentional
499
+ while (s && !c[--s])
500
+ ;
501
+ var cl = new u16(++s);
502
+ // ind num streak
503
+ var cli = 0, cln = c[0], cls = 1;
504
+ var w = function (v) { cl[cli++] = v; };
505
+ for (var i = 1; i <= s; ++i) {
506
+ if (c[i] == cln && i != s)
507
+ ++cls;
508
+ else {
509
+ if (!cln && cls > 2) {
510
+ for (; cls > 138; cls -= 138)
511
+ w(32754);
512
+ if (cls > 2) {
513
+ w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);
514
+ cls = 0;
515
+ }
516
+ }
517
+ else if (cls > 3) {
518
+ w(cln), --cls;
519
+ for (; cls > 6; cls -= 6)
520
+ w(8304);
521
+ if (cls > 2)
522
+ w(((cls - 3) << 5) | 8208), cls = 0;
523
+ }
524
+ while (cls--)
525
+ w(cln);
526
+ cls = 1;
527
+ cln = c[i];
528
+ }
529
+ }
530
+ return { c: cl.subarray(0, cli), n: s };
531
+ };
532
+ // calculate the length of output from tree, code lengths
533
+ var clen = function (cf, cl) {
534
+ var l = 0;
535
+ for (var i = 0; i < cl.length; ++i)
536
+ l += cf[i] * cl[i];
537
+ return l;
538
+ };
539
+ // writes a fixed block
540
+ // returns the new bit pos
541
+ var wfblk = function (out, pos, dat) {
542
+ // no need to write 00 as type: TypedArray defaults to 0
543
+ var s = dat.length;
544
+ var o = shft(pos + 2);
545
+ out[o] = s & 255;
546
+ out[o + 1] = s >> 8;
547
+ out[o + 2] = out[o] ^ 255;
548
+ out[o + 3] = out[o + 1] ^ 255;
549
+ for (var i = 0; i < s; ++i)
550
+ out[o + i + 4] = dat[i];
551
+ return (o + 4 + s) * 8;
552
+ };
553
+ // writes a block
554
+ var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
555
+ wbits(out, p++, final);
556
+ ++lf[256];
557
+ var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;
558
+ var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;
559
+ var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
560
+ var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
561
+ var lcfreq = new u16(19);
562
+ for (var i = 0; i < lclt.length; ++i)
563
+ ++lcfreq[lclt[i] & 31];
564
+ for (var i = 0; i < lcdt.length; ++i)
565
+ ++lcfreq[lcdt[i] & 31];
566
+ var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
567
+ var nlcc = 19;
568
+ for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
569
+ ;
570
+ var flen = (bl + 5) << 3;
571
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
572
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
573
+ if (bs >= 0 && flen <= ftlen && flen <= dtlen)
574
+ return wfblk(out, p, dat.subarray(bs, bs + bl));
575
+ var lm, ll, dm, dl;
576
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
577
+ if (dtlen < ftlen) {
578
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
579
+ var llm = hMap(lct, mlcb, 0);
580
+ wbits(out, p, nlc - 257);
581
+ wbits(out, p + 5, ndc - 1);
582
+ wbits(out, p + 10, nlcc - 4);
583
+ p += 14;
584
+ for (var i = 0; i < nlcc; ++i)
585
+ wbits(out, p + 3 * i, lct[clim[i]]);
586
+ p += 3 * nlcc;
587
+ var lcts = [lclt, lcdt];
588
+ for (var it = 0; it < 2; ++it) {
589
+ var clct = lcts[it];
590
+ for (var i = 0; i < clct.length; ++i) {
591
+ var len = clct[i] & 31;
592
+ wbits(out, p, llm[len]), p += lct[len];
593
+ if (len > 15)
594
+ wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12;
595
+ }
596
+ }
597
+ }
598
+ else {
599
+ lm = flm, ll = flt, dm = fdm, dl = fdt;
600
+ }
601
+ for (var i = 0; i < li; ++i) {
602
+ var sym = syms[i];
603
+ if (sym > 255) {
604
+ var len = (sym >> 18) & 31;
605
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
606
+ if (len > 7)
607
+ wbits(out, p, (sym >> 23) & 31), p += fleb[len];
608
+ var dst = sym & 31;
609
+ wbits16(out, p, dm[dst]), p += dl[dst];
610
+ if (dst > 3)
611
+ wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst];
612
+ }
613
+ else {
614
+ wbits16(out, p, lm[sym]), p += ll[sym];
615
+ }
616
+ }
617
+ wbits16(out, p, lm[256]);
618
+ return p + ll[256];
619
+ };
620
+ // deflate options (nice << 13) | chain
621
+ var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
622
+ // empty
623
+ var et = /*#__PURE__*/ new u8(0);
624
+ // compresses data into a raw DEFLATE buffer
625
+ var dflt = function (dat, lvl, plvl, pre, post, st) {
626
+ var s = st.z || dat.length;
627
+ var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
628
+ // writing to this writes to the output buffer
629
+ var w = o.subarray(pre, o.length - post);
630
+ var lst = st.l;
631
+ var pos = (st.r || 0) & 7;
632
+ if (lvl) {
633
+ if (pos)
634
+ w[0] = st.r >> 3;
635
+ var opt = deo[lvl - 1];
636
+ var n = opt >> 13, c = opt & 8191;
637
+ var msk_1 = (1 << plvl) - 1;
638
+ // prev 2-byte val map curr 2-byte val map
639
+ var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
640
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
641
+ var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };
642
+ // 24576 is an arbitrary number of maximum symbols per block
643
+ // 424 buffer for last block
644
+ var syms = new i32(25000);
645
+ // length/literal freq distance freq
646
+ var lf = new u16(288), df = new u16(32);
647
+ // l/lcnt exbits index l/lind waitdx blkpos
648
+ var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
649
+ for (; i + 2 < s; ++i) {
650
+ // hash value
651
+ var hv = hsh(i);
652
+ // index mod 32768 previous index mod
653
+ var imod = i & 32767, pimod = head[hv];
654
+ prev[imod] = pimod;
655
+ head[hv] = imod;
656
+ // We always should modify head and prev, but only add symbols if
657
+ // this data is not yet processed ("wait" for wait index)
658
+ if (wi <= i) {
659
+ // bytes remaining
660
+ var rem = s - i;
661
+ if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {
662
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
663
+ li = lc_1 = eb = 0, bs = i;
664
+ for (var j = 0; j < 286; ++j)
665
+ lf[j] = 0;
666
+ for (var j = 0; j < 30; ++j)
667
+ df[j] = 0;
668
+ }
669
+ // len dist chain
670
+ var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
671
+ if (rem > 2 && hv == hsh(i - dif)) {
672
+ var maxn = Math.min(n, rem) - 1;
673
+ var maxd = Math.min(32767, i);
674
+ // max possible length
675
+ // not capped at dif because decompressors implement "rolling" index population
676
+ var ml = Math.min(258, rem);
677
+ while (dif <= maxd && --ch_1 && imod != pimod) {
678
+ if (dat[i + l] == dat[i + l - dif]) {
679
+ var nl = 0;
680
+ for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
681
+ ;
682
+ if (nl > l) {
683
+ l = nl, d = dif;
684
+ // break out early when we reach "nice" (we are satisfied enough)
685
+ if (nl > maxn)
686
+ break;
687
+ // now, find the rarest 2-byte sequence within this
688
+ // length of literals and search for that instead.
689
+ // Much faster than just using the start
690
+ var mmd = Math.min(dif, nl - 2);
691
+ var md = 0;
692
+ for (var j = 0; j < mmd; ++j) {
693
+ var ti = i - dif + j & 32767;
694
+ var pti = prev[ti];
695
+ var cd = ti - pti & 32767;
696
+ if (cd > md)
697
+ md = cd, pimod = ti;
698
+ }
699
+ }
700
+ }
701
+ // check the previous match
702
+ imod = pimod, pimod = prev[imod];
703
+ dif += imod - pimod & 32767;
704
+ }
705
+ }
706
+ // d will be nonzero only when a match was found
707
+ if (d) {
708
+ // store both dist and len data in one int32
709
+ // Make sure this is recognized as a len/dist with 28th bit (2^28)
710
+ syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];
711
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
712
+ eb += fleb[lin] + fdeb[din];
713
+ ++lf[257 + lin];
714
+ ++df[din];
715
+ wi = i + l;
716
+ ++lc_1;
717
+ }
718
+ else {
719
+ syms[li++] = dat[i];
720
+ ++lf[dat[i]];
721
+ }
722
+ }
723
+ }
724
+ for (i = Math.max(i, wi); i < s; ++i) {
725
+ syms[li++] = dat[i];
726
+ ++lf[dat[i]];
727
+ }
728
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
729
+ if (!lst) {
730
+ st.r = (pos & 7) | w[(pos / 8) | 0] << 3;
731
+ // shft(pos) now 1 less if pos & 7 != 0
732
+ pos -= 7;
733
+ st.h = head, st.p = prev, st.i = i, st.w = wi;
734
+ }
735
+ }
736
+ else {
737
+ for (var i = st.w || 0; i < s + lst; i += 65535) {
738
+ // end
739
+ var e = i + 65535;
740
+ if (e >= s) {
741
+ // write final block
742
+ w[(pos / 8) | 0] = lst;
743
+ e = s;
744
+ }
745
+ pos = wfblk(w, pos + 1, dat.subarray(i, e));
746
+ }
747
+ st.i = s;
748
+ }
749
+ return slc(o, 0, pre + shft(pos) + post);
750
+ };
751
+ // CRC32 table
752
+ var crct = /*#__PURE__*/ (function () {
753
+ var t = new Int32Array(256);
754
+ for (var i = 0; i < 256; ++i) {
755
+ var c = i, k = 9;
756
+ while (--k)
757
+ c = ((c & 1) && -306674912) ^ (c >>> 1);
758
+ t[i] = c;
759
+ }
760
+ return t;
761
+ })();
762
+ // CRC32
763
+ var crc = function () {
764
+ var c = -1;
765
+ return {
766
+ p: function (d) {
767
+ // closures have awful performance
768
+ var cr = c;
769
+ for (var i = 0; i < d.length; ++i)
770
+ cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);
771
+ c = cr;
772
+ },
773
+ d: function () { return ~c; }
774
+ };
775
+ };
776
+ // Adler32
777
+ var adler = function () {
778
+ var a = 1, b = 0;
779
+ return {
780
+ p: function (d) {
781
+ // closures have awful performance
782
+ var n = a, m = b;
783
+ var l = d.length | 0;
784
+ for (var i = 0; i != l;) {
785
+ var e = Math.min(i + 2655, l);
786
+ for (; i < e; ++i)
787
+ m += n += d[i];
788
+ n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);
789
+ }
790
+ a = n, b = m;
791
+ },
792
+ d: function () {
793
+ a %= 65521, b %= 65521;
794
+ return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8);
795
+ }
796
+ };
797
+ };
798
+ ;
799
+ // deflate with opts
800
+ var dopt = function (dat, opt, pre, post, st) {
801
+ if (!st) {
802
+ st = { l: 1 };
803
+ if (opt.dictionary) {
804
+ var dict = opt.dictionary.subarray(-32768);
805
+ var newDat = new u8(dict.length + dat.length);
806
+ newDat.set(dict);
807
+ newDat.set(dat, dict.length);
808
+ dat = newDat;
809
+ st.w = dict.length;
810
+ }
811
+ }
812
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st);
813
+ };
814
+ // Walmart object spread
815
+ var mrg = function (a, b) {
816
+ var o = {};
817
+ for (var k in a)
818
+ o[k] = a[k];
819
+ for (var k in b)
820
+ o[k] = b[k];
821
+ return o;
822
+ };
823
+ // worker clone
824
+ // This is possibly the craziest part of the entire codebase, despite how simple it may seem.
825
+ // The only parameter to this function is a closure that returns an array of variables outside of the function scope.
826
+ // We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.
827
+ // We will return an object mapping of true variable name to value (basically, the current scope as a JS object).
828
+ // The reason we can't just use the original variable names is minifiers mangling the toplevel scope.
829
+ // This took me three weeks to figure out how to do.
830
+ var wcln = function (fn, fnStr, td) {
831
+ var dt = fn();
832
+ var st = fn.toString();
833
+ var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(',');
834
+ for (var i = 0; i < dt.length; ++i) {
835
+ var v = dt[i], k = ks[i];
836
+ if (typeof v == 'function') {
837
+ fnStr += ';' + k + '=';
838
+ var st_1 = v.toString();
839
+ if (v.prototype) {
840
+ // for global objects
841
+ if (st_1.indexOf('[native code]') != -1) {
842
+ var spInd = st_1.indexOf(' ', 8) + 1;
843
+ fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));
844
+ }
845
+ else {
846
+ fnStr += st_1;
847
+ for (var t in v.prototype)
848
+ fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();
849
+ }
850
+ }
851
+ else
852
+ fnStr += st_1;
853
+ }
854
+ else
855
+ td[k] = v;
856
+ }
857
+ return fnStr;
858
+ };
859
+ var ch = [];
860
+ // clone bufs
861
+ var cbfs = function (v) {
862
+ var tl = [];
863
+ for (var k in v) {
864
+ if (v[k].buffer) {
865
+ tl.push((v[k] = new v[k].constructor(v[k])).buffer);
866
+ }
867
+ }
868
+ return tl;
869
+ };
870
+ // use a worker to execute code
871
+ var wrkr = function (fns, init, id, cb) {
872
+ if (!ch[id]) {
873
+ var fnStr = '', td_1 = {}, m = fns.length - 1;
874
+ for (var i = 0; i < m; ++i)
875
+ fnStr = wcln(fns[i], fnStr, td_1);
876
+ ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };
877
+ }
878
+ var td = mrg({}, ch[id].e);
879
+ return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);
880
+ };
881
+ // base async inflate fn
882
+ var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; };
883
+ var bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };
884
+ // gzip extra
885
+ var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };
886
+ // gunzip extra
887
+ var guze = function () { return [gzs, gzl]; };
888
+ // zlib extra
889
+ var zle = function () { return [zlh, wbytes, adler]; };
890
+ // unzlib extra
891
+ var zule = function () { return [zls]; };
892
+ // post buf
893
+ var pbf = function (msg) { return postMessage(msg, [msg.buffer]); };
894
+ // get opts
895
+ var gopt = function (o) { return o && {
896
+ out: o.size && new u8(o.size),
897
+ dictionary: o.dictionary
898
+ }; };
899
+ // async helper
900
+ var cbify = function (dat, opts, fns, init, id, cb) {
901
+ var w = wrkr(fns, init, id, function (err, dat) {
902
+ w.terminate();
903
+ cb(err, dat);
904
+ });
905
+ w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
906
+ return function () { w.terminate(); };
907
+ };
908
+ // auto stream
909
+ var astrm = function (strm) {
910
+ strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };
911
+ return function (ev) {
912
+ if (ev.data.length) {
913
+ strm.push(ev.data[0], ev.data[1]);
914
+ postMessage([ev.data[0].length]);
915
+ }
916
+ else
917
+ strm.flush();
918
+ };
919
+ };
920
+ // async stream attach
921
+ var astrmify = function (fns, strm, opts, init, id, flush, ext) {
922
+ var t;
923
+ var w = wrkr(fns, init, id, function (err, dat) {
924
+ if (err)
925
+ w.terminate(), strm.ondata.call(strm, err);
926
+ else if (!Array.isArray(dat))
927
+ ext(dat);
928
+ else if (dat.length == 1) {
929
+ strm.queuedSize -= dat[0];
930
+ if (strm.ondrain)
931
+ strm.ondrain(dat[0]);
932
+ }
933
+ else {
934
+ if (dat[1])
935
+ w.terminate();
936
+ strm.ondata.call(strm, err, dat[0], dat[1]);
937
+ }
938
+ });
939
+ w.postMessage(opts);
940
+ strm.queuedSize = 0;
941
+ strm.push = function (d, f) {
942
+ if (!strm.ondata)
943
+ err(5);
944
+ if (t)
945
+ strm.ondata(err(4, 0, 1), null, !!f);
946
+ strm.queuedSize += d.length;
947
+ w.postMessage([d, t = f], [d.buffer]);
948
+ };
949
+ strm.terminate = function () { w.terminate(); };
950
+ if (flush) {
951
+ strm.flush = function () { w.postMessage([]); };
952
+ }
953
+ };
954
+ // read 2 bytes
955
+ var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };
956
+ // read 4 bytes
957
+ var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };
958
+ var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };
959
+ // write bytes
960
+ var wbytes = function (d, b, v) {
961
+ for (; v; ++b)
962
+ d[b] = v, v >>>= 8;
963
+ };
964
+ // gzip header
965
+ var gzh = function (c, o) {
966
+ var fn = o.filename;
967
+ c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix
968
+ if (o.mtime != 0)
969
+ wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));
970
+ if (fn) {
971
+ c[3] = 8;
972
+ for (var i = 0; i <= fn.length; ++i)
973
+ c[i + 10] = fn.charCodeAt(i);
974
+ }
975
+ };
976
+ // gzip footer: -8 to -4 = CRC, -4 to -0 is length
977
+ // gzip start
978
+ var gzs = function (d) {
979
+ if (d[0] != 31 || d[1] != 139 || d[2] != 8)
980
+ err(6, 'invalid gzip data');
981
+ var flg = d[3];
982
+ var st = 10;
983
+ if (flg & 4)
984
+ st += (d[10] | d[11] << 8) + 2;
985
+ for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
986
+ ;
987
+ return st + (flg & 2);
988
+ };
989
+ // gzip length
990
+ var gzl = function (d) {
991
+ var l = d.length;
992
+ return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
993
+ };
994
+ // gzip header length
995
+ var gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); };
996
+ // zlib header
997
+ var zlh = function (c, o) {
998
+ var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
999
+ c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32);
1000
+ c[1] |= 31 - ((c[0] << 8) | c[1]) % 31;
1001
+ if (o.dictionary) {
1002
+ var h = adler();
1003
+ h.p(o.dictionary);
1004
+ wbytes(c, 2, h.d());
1005
+ }
1006
+ };
1007
+ // zlib start
1008
+ var zls = function (d, dict) {
1009
+ if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
1010
+ err(6, 'invalid zlib data');
1011
+ if ((d[1] >> 5 & 1) == +!dict)
1012
+ err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');
1013
+ return (d[1] >> 3 & 4) + 2;
1014
+ };
1015
+ function StrmOpt(opts, cb) {
1016
+ if (typeof opts == 'function')
1017
+ cb = opts, opts = {};
1018
+ this.ondata = cb;
1019
+ return opts;
1020
+ }
1021
+ /**
1022
+ * Streaming DEFLATE compression
1023
+ */
1024
+ var Deflate = /*#__PURE__*/ (function () {
1025
+ function Deflate(opts, cb) {
1026
+ if (typeof opts == 'function')
1027
+ cb = opts, opts = {};
1028
+ this.ondata = cb;
1029
+ this.o = opts || {};
1030
+ this.s = { l: 0, i: 32768, w: 32768, z: 32768 };
1031
+ // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev
1032
+ // 98304 = 32768 (lookback) + 65536 (common chunk size)
1033
+ this.b = new u8(98304);
1034
+ if (this.o.dictionary) {
1035
+ var dict = this.o.dictionary.subarray(-32768);
1036
+ this.b.set(dict, 32768 - dict.length);
1037
+ this.s.i = 32768 - dict.length;
1038
+ }
1039
+ }
1040
+ Deflate.prototype.p = function (c, f) {
1041
+ this.ondata(dopt(c, this.o, 0, 0, this.s), f);
1042
+ };
1043
+ /**
1044
+ * Pushes a chunk to be deflated
1045
+ * @param chunk The chunk to push
1046
+ * @param final Whether this is the last chunk
1047
+ */
1048
+ Deflate.prototype.push = function (chunk, final) {
1049
+ if (!this.ondata)
1050
+ err(5);
1051
+ if (this.s.l)
1052
+ err(4);
1053
+ var endLen = chunk.length + this.s.z;
1054
+ if (endLen > this.b.length) {
1055
+ if (endLen > 2 * this.b.length - 32768) {
1056
+ var newBuf = new u8(endLen & -32768);
1057
+ newBuf.set(this.b.subarray(0, this.s.z));
1058
+ this.b = newBuf;
1059
+ }
1060
+ var split = this.b.length - this.s.z;
1061
+ this.b.set(chunk.subarray(0, split), this.s.z);
1062
+ this.s.z = this.b.length;
1063
+ this.p(this.b, false);
1064
+ this.b.set(this.b.subarray(-32768));
1065
+ this.b.set(chunk.subarray(split), 32768);
1066
+ this.s.z = chunk.length - split + 32768;
1067
+ this.s.i = 32766, this.s.w = 32768;
1068
+ }
1069
+ else {
1070
+ this.b.set(chunk, this.s.z);
1071
+ this.s.z += chunk.length;
1072
+ }
1073
+ this.s.l = final & 1;
1074
+ if (this.s.z > this.s.w + 8191 || final) {
1075
+ this.p(this.b, final || false);
1076
+ this.s.w = this.s.i, this.s.i -= 2;
1077
+ }
1078
+ };
1079
+ /**
1080
+ * Flushes buffered uncompressed data. Useful to immediately retrieve the
1081
+ * deflated output for small inputs.
1082
+ */
1083
+ Deflate.prototype.flush = function () {
1084
+ if (!this.ondata)
1085
+ err(5);
1086
+ if (this.s.l)
1087
+ err(4);
1088
+ this.p(this.b, false);
1089
+ this.s.w = this.s.i, this.s.i -= 2;
1090
+ };
1091
+ return Deflate;
1092
+ }());
1093
+ export { Deflate };
1094
+ /**
1095
+ * Asynchronous streaming DEFLATE compression
1096
+ */
1097
+ var AsyncDeflate = /*#__PURE__*/ (function () {
1098
+ function AsyncDeflate(opts, cb) {
1099
+ astrmify([
1100
+ bDflt,
1101
+ function () { return [astrm, Deflate]; }
1102
+ ], this, StrmOpt.call(this, opts, cb), function (ev) {
1103
+ var strm = new Deflate(ev.data);
1104
+ onmessage = astrm(strm);
1105
+ }, 6, 1);
1106
+ }
1107
+ return AsyncDeflate;
1108
+ }());
1109
+ export { AsyncDeflate };
1110
+ export function deflate(data, opts, cb) {
1111
+ if (!cb)
1112
+ cb = opts, opts = {};
1113
+ if (typeof cb != 'function')
1114
+ err(7);
1115
+ return cbify(data, opts, [
1116
+ bDflt,
1117
+ ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);
1118
+ }
1119
+ /**
1120
+ * Compresses data with DEFLATE without any wrapper
1121
+ * @param data The data to compress
1122
+ * @param opts The compression options
1123
+ * @returns The deflated version of the data
1124
+ */
1125
+ export function deflateSync(data, opts) {
1126
+ return dopt(data, opts || {}, 0, 0);
1127
+ }
1128
+ /**
1129
+ * Streaming DEFLATE decompression
1130
+ */
1131
+ var Inflate = /*#__PURE__*/ (function () {
1132
+ function Inflate(opts, cb) {
1133
+ // no StrmOpt here to avoid adding to workerizer
1134
+ if (typeof opts == 'function')
1135
+ cb = opts, opts = {};
1136
+ this.ondata = cb;
1137
+ var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
1138
+ this.s = { i: 0, b: dict ? dict.length : 0 };
1139
+ this.o = new u8(32768);
1140
+ this.p = new u8(0);
1141
+ if (dict)
1142
+ this.o.set(dict);
1143
+ }
1144
+ Inflate.prototype.e = function (c) {
1145
+ if (!this.ondata)
1146
+ err(5);
1147
+ if (this.d)
1148
+ err(4);
1149
+ if (!this.p.length)
1150
+ this.p = c;
1151
+ else if (c.length) {
1152
+ var n = new u8(this.p.length + c.length);
1153
+ n.set(this.p), n.set(c, this.p.length), this.p = n;
1154
+ }
1155
+ };
1156
+ Inflate.prototype.c = function (final) {
1157
+ this.s.i = +(this.d = final || false);
1158
+ var bts = this.s.b;
1159
+ var dt = inflt(this.p, this.s, this.o);
1160
+ this.ondata(slc(dt, bts, this.s.b), this.d);
1161
+ this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
1162
+ this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;
1163
+ };
1164
+ /**
1165
+ * Pushes a chunk to be inflated
1166
+ * @param chunk The chunk to push
1167
+ * @param final Whether this is the final chunk
1168
+ */
1169
+ Inflate.prototype.push = function (chunk, final) {
1170
+ this.e(chunk), this.c(final);
1171
+ };
1172
+ return Inflate;
1173
+ }());
1174
+ export { Inflate };
1175
+ /**
1176
+ * Asynchronous streaming DEFLATE decompression
1177
+ */
1178
+ var AsyncInflate = /*#__PURE__*/ (function () {
1179
+ function AsyncInflate(opts, cb) {
1180
+ astrmify([
1181
+ bInflt,
1182
+ function () { return [astrm, Inflate]; }
1183
+ ], this, StrmOpt.call(this, opts, cb), function (ev) {
1184
+ var strm = new Inflate(ev.data);
1185
+ onmessage = astrm(strm);
1186
+ }, 7, 0);
1187
+ }
1188
+ return AsyncInflate;
1189
+ }());
1190
+ export { AsyncInflate };
1191
+ export function inflate(data, opts, cb) {
1192
+ if (!cb)
1193
+ cb = opts, opts = {};
1194
+ if (typeof cb != 'function')
1195
+ err(7);
1196
+ return cbify(data, opts, [
1197
+ bInflt
1198
+ ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb);
1199
+ }
1200
+ /**
1201
+ * Expands DEFLATE data with no wrapper
1202
+ * @param data The data to decompress
1203
+ * @param opts The decompression options
1204
+ * @returns The decompressed version of the data
1205
+ */
1206
+ export function inflateSync(data, opts) {
1207
+ return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
1208
+ }
1209
+ // before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.
1210
+ /**
1211
+ * Streaming GZIP compression
1212
+ */
1213
+ var Gzip = /*#__PURE__*/ (function () {
1214
+ function Gzip(opts, cb) {
1215
+ this.c = crc();
1216
+ this.l = 0;
1217
+ this.v = 1;
1218
+ Deflate.call(this, opts, cb);
1219
+ }
1220
+ /**
1221
+ * Pushes a chunk to be GZIPped
1222
+ * @param chunk The chunk to push
1223
+ * @param final Whether this is the last chunk
1224
+ */
1225
+ Gzip.prototype.push = function (chunk, final) {
1226
+ this.c.p(chunk);
1227
+ this.l += chunk.length;
1228
+ Deflate.prototype.push.call(this, chunk, final);
1229
+ };
1230
+ Gzip.prototype.p = function (c, f) {
1231
+ var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s);
1232
+ if (this.v)
1233
+ gzh(raw, this.o), this.v = 0;
1234
+ if (f)
1235
+ wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);
1236
+ this.ondata(raw, f);
1237
+ };
1238
+ /**
1239
+ * Flushes buffered uncompressed data. Useful to immediately retrieve the
1240
+ * GZIPped output for small inputs.
1241
+ */
1242
+ Gzip.prototype.flush = function () {
1243
+ Deflate.prototype.flush.call(this);
1244
+ };
1245
+ return Gzip;
1246
+ }());
1247
+ export { Gzip };
1248
+ /**
1249
+ * Asynchronous streaming GZIP compression
1250
+ */
1251
+ var AsyncGzip = /*#__PURE__*/ (function () {
1252
+ function AsyncGzip(opts, cb) {
1253
+ astrmify([
1254
+ bDflt,
1255
+ gze,
1256
+ function () { return [astrm, Deflate, Gzip]; }
1257
+ ], this, StrmOpt.call(this, opts, cb), function (ev) {
1258
+ var strm = new Gzip(ev.data);
1259
+ onmessage = astrm(strm);
1260
+ }, 8, 1);
1261
+ }
1262
+ return AsyncGzip;
1263
+ }());
1264
+ export { AsyncGzip };
1265
+ export function gzip(data, opts, cb) {
1266
+ if (!cb)
1267
+ cb = opts, opts = {};
1268
+ if (typeof cb != 'function')
1269
+ err(7);
1270
+ return cbify(data, opts, [
1271
+ bDflt,
1272
+ gze,
1273
+ function () { return [gzipSync]; }
1274
+ ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);
1275
+ }
1276
+ /**
1277
+ * Compresses data with GZIP
1278
+ * @param data The data to compress
1279
+ * @param opts The compression options
1280
+ * @returns The gzipped version of the data
1281
+ */
1282
+ export function gzipSync(data, opts) {
1283
+ if (!opts)
1284
+ opts = {};
1285
+ var c = crc(), l = data.length;
1286
+ c.p(data);
1287
+ var d = dopt(data, opts, gzhl(opts), 8), s = d.length;
1288
+ return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;
1289
+ }
1290
+ /**
1291
+ * Streaming single or multi-member GZIP decompression
1292
+ */
1293
+ var Gunzip = /*#__PURE__*/ (function () {
1294
+ function Gunzip(opts, cb) {
1295
+ this.v = 1;
1296
+ this.r = 0;
1297
+ Inflate.call(this, opts, cb);
1298
+ }
1299
+ /**
1300
+ * Pushes a chunk to be GUNZIPped
1301
+ * @param chunk The chunk to push
1302
+ * @param final Whether this is the last chunk
1303
+ */
1304
+ Gunzip.prototype.push = function (chunk, final) {
1305
+ Inflate.prototype.e.call(this, chunk);
1306
+ this.r += chunk.length;
1307
+ if (this.v) {
1308
+ var p = this.p.subarray(this.v - 1);
1309
+ var s = p.length > 3 ? gzs(p) : 4;
1310
+ if (s > p.length) {
1311
+ if (!final)
1312
+ return;
1313
+ }
1314
+ else if (this.v > 1 && this.onmember) {
1315
+ this.onmember(this.r - p.length);
1316
+ }
1317
+ this.p = p.subarray(s), this.v = 0;
1318
+ }
1319
+ // necessary to prevent TS from using the closure value
1320
+ // This allows for workerization to function correctly
1321
+ Inflate.prototype.c.call(this, final);
1322
+ // process concatenated GZIP
1323
+ if (this.s.f && !this.s.l && !final) {
1324
+ this.v = shft(this.s.p) + 9;
1325
+ this.s = { i: 0 };
1326
+ this.o = new u8(0);
1327
+ this.push(new u8(0), final);
1328
+ }
1329
+ };
1330
+ return Gunzip;
1331
+ }());
1332
+ export { Gunzip };
1333
+ /**
1334
+ * Asynchronous streaming single or multi-member GZIP decompression
1335
+ */
1336
+ var AsyncGunzip = /*#__PURE__*/ (function () {
1337
+ function AsyncGunzip(opts, cb) {
1338
+ var _this = this;
1339
+ astrmify([
1340
+ bInflt,
1341
+ guze,
1342
+ function () { return [astrm, Inflate, Gunzip]; }
1343
+ ], this, StrmOpt.call(this, opts, cb), function (ev) {
1344
+ var strm = new Gunzip(ev.data);
1345
+ strm.onmember = function (offset) { return postMessage(offset); };
1346
+ onmessage = astrm(strm);
1347
+ }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); });
1348
+ }
1349
+ return AsyncGunzip;
1350
+ }());
1351
+ export { AsyncGunzip };
1352
+ export function gunzip(data, opts, cb) {
1353
+ if (!cb)
1354
+ cb = opts, opts = {};
1355
+ if (typeof cb != 'function')
1356
+ err(7);
1357
+ return cbify(data, opts, [
1358
+ bInflt,
1359
+ guze,
1360
+ function () { return [gunzipSync]; }
1361
+ ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb);
1362
+ }
1363
+ /**
1364
+ * Expands GZIP data
1365
+ * @param data The data to decompress
1366
+ * @param opts The decompression options
1367
+ * @returns The decompressed version of the data
1368
+ */
1369
+ export function gunzipSync(data, opts) {
1370
+ var st = gzs(data);
1371
+ if (st + 8 > data.length)
1372
+ err(6, 'invalid gzip data');
1373
+ return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);
1374
+ }
1375
+ /**
1376
+ * Streaming Zlib compression
1377
+ */
1378
+ var Zlib = /*#__PURE__*/ (function () {
1379
+ function Zlib(opts, cb) {
1380
+ this.c = adler();
1381
+ this.v = 1;
1382
+ Deflate.call(this, opts, cb);
1383
+ }
1384
+ /**
1385
+ * Pushes a chunk to be zlibbed
1386
+ * @param chunk The chunk to push
1387
+ * @param final Whether this is the last chunk
1388
+ */
1389
+ Zlib.prototype.push = function (chunk, final) {
1390
+ this.c.p(chunk);
1391
+ Deflate.prototype.push.call(this, chunk, final);
1392
+ };
1393
+ Zlib.prototype.p = function (c, f) {
1394
+ var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);
1395
+ if (this.v)
1396
+ zlh(raw, this.o), this.v = 0;
1397
+ if (f)
1398
+ wbytes(raw, raw.length - 4, this.c.d());
1399
+ this.ondata(raw, f);
1400
+ };
1401
+ /**
1402
+ * Flushes buffered uncompressed data. Useful to immediately retrieve the
1403
+ * zlibbed output for small inputs.
1404
+ */
1405
+ Zlib.prototype.flush = function () {
1406
+ Deflate.prototype.flush.call(this);
1407
+ };
1408
+ return Zlib;
1409
+ }());
1410
+ export { Zlib };
1411
+ /**
1412
+ * Asynchronous streaming Zlib compression
1413
+ */
1414
+ var AsyncZlib = /*#__PURE__*/ (function () {
1415
+ function AsyncZlib(opts, cb) {
1416
+ astrmify([
1417
+ bDflt,
1418
+ zle,
1419
+ function () { return [astrm, Deflate, Zlib]; }
1420
+ ], this, StrmOpt.call(this, opts, cb), function (ev) {
1421
+ var strm = new Zlib(ev.data);
1422
+ onmessage = astrm(strm);
1423
+ }, 10, 1);
1424
+ }
1425
+ return AsyncZlib;
1426
+ }());
1427
+ export { AsyncZlib };
1428
+ export function zlib(data, opts, cb) {
1429
+ if (!cb)
1430
+ cb = opts, opts = {};
1431
+ if (typeof cb != 'function')
1432
+ err(7);
1433
+ return cbify(data, opts, [
1434
+ bDflt,
1435
+ zle,
1436
+ function () { return [zlibSync]; }
1437
+ ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);
1438
+ }
1439
+ /**
1440
+ * Compress data with Zlib
1441
+ * @param data The data to compress
1442
+ * @param opts The compression options
1443
+ * @returns The zlib-compressed version of the data
1444
+ */
1445
+ export function zlibSync(data, opts) {
1446
+ if (!opts)
1447
+ opts = {};
1448
+ var a = adler();
1449
+ a.p(data);
1450
+ var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);
1451
+ return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;
1452
+ }
1453
+ /**
1454
+ * Streaming Zlib decompression
1455
+ */
1456
+ var Unzlib = /*#__PURE__*/ (function () {
1457
+ function Unzlib(opts, cb) {
1458
+ Inflate.call(this, opts, cb);
1459
+ this.v = opts && opts.dictionary ? 2 : 1;
1460
+ }
1461
+ /**
1462
+ * Pushes a chunk to be unzlibbed
1463
+ * @param chunk The chunk to push
1464
+ * @param final Whether this is the last chunk
1465
+ */
1466
+ Unzlib.prototype.push = function (chunk, final) {
1467
+ Inflate.prototype.e.call(this, chunk);
1468
+ if (this.v) {
1469
+ if (this.p.length < 6 && !final)
1470
+ return;
1471
+ this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;
1472
+ }
1473
+ if (final) {
1474
+ if (this.p.length < 4)
1475
+ err(6, 'invalid zlib data');
1476
+ this.p = this.p.subarray(0, -4);
1477
+ }
1478
+ // necessary to prevent TS from using the closure value
1479
+ // This allows for workerization to function correctly
1480
+ Inflate.prototype.c.call(this, final);
1481
+ };
1482
+ return Unzlib;
1483
+ }());
1484
+ export { Unzlib };
1485
+ /**
1486
+ * Asynchronous streaming Zlib decompression
1487
+ */
1488
+ var AsyncUnzlib = /*#__PURE__*/ (function () {
1489
+ function AsyncUnzlib(opts, cb) {
1490
+ astrmify([
1491
+ bInflt,
1492
+ zule,
1493
+ function () { return [astrm, Inflate, Unzlib]; }
1494
+ ], this, StrmOpt.call(this, opts, cb), function (ev) {
1495
+ var strm = new Unzlib(ev.data);
1496
+ onmessage = astrm(strm);
1497
+ }, 11, 0);
1498
+ }
1499
+ return AsyncUnzlib;
1500
+ }());
1501
+ export { AsyncUnzlib };
1502
+ export function unzlib(data, opts, cb) {
1503
+ if (!cb)
1504
+ cb = opts, opts = {};
1505
+ if (typeof cb != 'function')
1506
+ err(7);
1507
+ return cbify(data, opts, [
1508
+ bInflt,
1509
+ zule,
1510
+ function () { return [unzlibSync]; }
1511
+ ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb);
1512
+ }
1513
+ /**
1514
+ * Expands Zlib data
1515
+ * @param data The data to decompress
1516
+ * @param opts The decompression options
1517
+ * @returns The decompressed version of the data
1518
+ */
1519
+ export function unzlibSync(data, opts) {
1520
+ return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
1521
+ }
1522
+ // Default algorithm for compression (used because having a known output size allows faster decompression)
1523
+ export { gzip as compress, AsyncGzip as AsyncCompress };
1524
+ export { gzipSync as compressSync, Gzip as Compress };
1525
+ /**
1526
+ * Streaming GZIP, Zlib, or raw DEFLATE decompression
1527
+ */
1528
+ var Decompress = /*#__PURE__*/ (function () {
1529
+ function Decompress(opts, cb) {
1530
+ this.o = StrmOpt.call(this, opts, cb) || {};
1531
+ this.G = Gunzip;
1532
+ this.I = Inflate;
1533
+ this.Z = Unzlib;
1534
+ }
1535
+ // init substream
1536
+ // overriden by AsyncDecompress
1537
+ Decompress.prototype.i = function () {
1538
+ var _this = this;
1539
+ this.s.ondata = function (dat, final) {
1540
+ _this.ondata(dat, final);
1541
+ };
1542
+ };
1543
+ /**
1544
+ * Pushes a chunk to be decompressed
1545
+ * @param chunk The chunk to push
1546
+ * @param final Whether this is the last chunk
1547
+ */
1548
+ Decompress.prototype.push = function (chunk, final) {
1549
+ if (!this.ondata)
1550
+ err(5);
1551
+ if (!this.s) {
1552
+ if (this.p && this.p.length) {
1553
+ var n = new u8(this.p.length + chunk.length);
1554
+ n.set(this.p), n.set(chunk, this.p.length);
1555
+ }
1556
+ else
1557
+ this.p = chunk;
1558
+ if (this.p.length > 2) {
1559
+ this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)
1560
+ ? new this.G(this.o)
1561
+ : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))
1562
+ ? new this.I(this.o)
1563
+ : new this.Z(this.o);
1564
+ this.i();
1565
+ this.s.push(this.p, final);
1566
+ this.p = null;
1567
+ }
1568
+ }
1569
+ else
1570
+ this.s.push(chunk, final);
1571
+ };
1572
+ return Decompress;
1573
+ }());
1574
+ export { Decompress };
1575
+ /**
1576
+ * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression
1577
+ */
1578
+ var AsyncDecompress = /*#__PURE__*/ (function () {
1579
+ function AsyncDecompress(opts, cb) {
1580
+ Decompress.call(this, opts, cb);
1581
+ this.queuedSize = 0;
1582
+ this.G = AsyncGunzip;
1583
+ this.I = AsyncInflate;
1584
+ this.Z = AsyncUnzlib;
1585
+ }
1586
+ AsyncDecompress.prototype.i = function () {
1587
+ var _this = this;
1588
+ this.s.ondata = function (err, dat, final) {
1589
+ _this.ondata(err, dat, final);
1590
+ };
1591
+ this.s.ondrain = function (size) {
1592
+ _this.queuedSize -= size;
1593
+ if (_this.ondrain)
1594
+ _this.ondrain(size);
1595
+ };
1596
+ };
1597
+ /**
1598
+ * Pushes a chunk to be decompressed
1599
+ * @param chunk The chunk to push
1600
+ * @param final Whether this is the last chunk
1601
+ */
1602
+ AsyncDecompress.prototype.push = function (chunk, final) {
1603
+ this.queuedSize += chunk.length;
1604
+ Decompress.prototype.push.call(this, chunk, final);
1605
+ };
1606
+ return AsyncDecompress;
1607
+ }());
1608
+ export { AsyncDecompress };
1609
+ export function decompress(data, opts, cb) {
1610
+ if (!cb)
1611
+ cb = opts, opts = {};
1612
+ if (typeof cb != 'function')
1613
+ err(7);
1614
+ return (data[0] == 31 && data[1] == 139 && data[2] == 8)
1615
+ ? gunzip(data, opts, cb)
1616
+ : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
1617
+ ? inflate(data, opts, cb)
1618
+ : unzlib(data, opts, cb);
1619
+ }
1620
+ /**
1621
+ * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format
1622
+ * @param data The data to decompress
1623
+ * @param opts The decompression options
1624
+ * @returns The decompressed version of the data
1625
+ */
1626
+ export function decompressSync(data, opts) {
1627
+ return (data[0] == 31 && data[1] == 139 && data[2] == 8)
1628
+ ? gunzipSync(data, opts)
1629
+ : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
1630
+ ? inflateSync(data, opts)
1631
+ : unzlibSync(data, opts);
1632
+ }
1633
+ // flatten a directory structure
1634
+ var fltn = function (d, p, t, o) {
1635
+ for (var k in d) {
1636
+ var val = d[k], n = p + k, op = o;
1637
+ if (Array.isArray(val))
1638
+ op = mrg(o, val[1]), val = val[0];
1639
+ if (val instanceof u8)
1640
+ t[n] = [val, op];
1641
+ else {
1642
+ t[n += '/'] = [new u8(0), op];
1643
+ fltn(val, n, t, o);
1644
+ }
1645
+ }
1646
+ };
1647
+ // text encoder
1648
+ var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();
1649
+ // text decoder
1650
+ var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
1651
+ // text decoder stream
1652
+ var tds = 0;
1653
+ try {
1654
+ td.decode(et, { stream: true });
1655
+ tds = 1;
1656
+ }
1657
+ catch (e) { }
1658
+ // decode UTF8
1659
+ var dutf8 = function (d) {
1660
+ for (var r = '', i = 0;;) {
1661
+ var c = d[i++];
1662
+ var eb = (c > 127) + (c > 223) + (c > 239);
1663
+ if (i + eb > d.length)
1664
+ return { s: r, r: slc(d, i - 1) };
1665
+ if (!eb)
1666
+ r += String.fromCharCode(c);
1667
+ else if (eb == 3) {
1668
+ c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,
1669
+ r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));
1670
+ }
1671
+ else if (eb & 1)
1672
+ r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));
1673
+ else
1674
+ r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));
1675
+ }
1676
+ };
1677
+ /**
1678
+ * Streaming UTF-8 decoding
1679
+ */
1680
+ var DecodeUTF8 = /*#__PURE__*/ (function () {
1681
+ /**
1682
+ * Creates a UTF-8 decoding stream
1683
+ * @param cb The callback to call whenever data is decoded
1684
+ */
1685
+ function DecodeUTF8(cb) {
1686
+ this.ondata = cb;
1687
+ if (tds)
1688
+ this.t = new TextDecoder();
1689
+ else
1690
+ this.p = et;
1691
+ }
1692
+ /**
1693
+ * Pushes a chunk to be decoded from UTF-8 binary
1694
+ * @param chunk The chunk to push
1695
+ * @param final Whether this is the last chunk
1696
+ */
1697
+ DecodeUTF8.prototype.push = function (chunk, final) {
1698
+ if (!this.ondata)
1699
+ err(5);
1700
+ final = !!final;
1701
+ if (this.t) {
1702
+ this.ondata(this.t.decode(chunk, { stream: true }), final);
1703
+ if (final) {
1704
+ if (this.t.decode().length)
1705
+ err(8);
1706
+ this.t = null;
1707
+ }
1708
+ return;
1709
+ }
1710
+ if (!this.p)
1711
+ err(4);
1712
+ var dat = new u8(this.p.length + chunk.length);
1713
+ dat.set(this.p);
1714
+ dat.set(chunk, this.p.length);
1715
+ var _a = dutf8(dat), s = _a.s, r = _a.r;
1716
+ if (final) {
1717
+ if (r.length)
1718
+ err(8);
1719
+ this.p = null;
1720
+ }
1721
+ else
1722
+ this.p = r;
1723
+ this.ondata(s, final);
1724
+ };
1725
+ return DecodeUTF8;
1726
+ }());
1727
+ export { DecodeUTF8 };
1728
+ /**
1729
+ * Streaming UTF-8 encoding
1730
+ */
1731
+ var EncodeUTF8 = /*#__PURE__*/ (function () {
1732
+ /**
1733
+ * Creates a UTF-8 decoding stream
1734
+ * @param cb The callback to call whenever data is encoded
1735
+ */
1736
+ function EncodeUTF8(cb) {
1737
+ this.ondata = cb;
1738
+ }
1739
+ /**
1740
+ * Pushes a chunk to be encoded to UTF-8
1741
+ * @param chunk The string data to push
1742
+ * @param final Whether this is the last chunk
1743
+ */
1744
+ EncodeUTF8.prototype.push = function (chunk, final) {
1745
+ if (!this.ondata)
1746
+ err(5);
1747
+ if (this.d)
1748
+ err(4);
1749
+ this.ondata(strToU8(chunk), this.d = final || false);
1750
+ };
1751
+ return EncodeUTF8;
1752
+ }());
1753
+ export { EncodeUTF8 };
1754
+ /**
1755
+ * Converts a string into a Uint8Array for use with compression/decompression methods
1756
+ * @param str The string to encode
1757
+ * @param latin1 Whether or not to interpret the data as Latin-1. This should
1758
+ * not need to be true unless decoding a binary string.
1759
+ * @returns The string encoded in UTF-8/Latin-1 binary
1760
+ */
1761
+ export function strToU8(str, latin1) {
1762
+ if (latin1) {
1763
+ var ar_1 = new u8(str.length);
1764
+ for (var i = 0; i < str.length; ++i)
1765
+ ar_1[i] = str.charCodeAt(i);
1766
+ return ar_1;
1767
+ }
1768
+ if (te)
1769
+ return te.encode(str);
1770
+ var l = str.length;
1771
+ var ar = new u8(str.length + (str.length >> 1));
1772
+ var ai = 0;
1773
+ var w = function (v) { ar[ai++] = v; };
1774
+ for (var i = 0; i < l; ++i) {
1775
+ if (ai + 5 > ar.length) {
1776
+ var n = new u8(ai + 8 + ((l - i) << 1));
1777
+ n.set(ar);
1778
+ ar = n;
1779
+ }
1780
+ var c = str.charCodeAt(i);
1781
+ if (c < 128 || latin1)
1782
+ w(c);
1783
+ else if (c < 2048)
1784
+ w(192 | (c >> 6)), w(128 | (c & 63));
1785
+ else if (c > 55295 && c < 57344)
1786
+ c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),
1787
+ w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
1788
+ else
1789
+ w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
1790
+ }
1791
+ return slc(ar, 0, ai);
1792
+ }
1793
+ /**
1794
+ * Converts a Uint8Array to a string
1795
+ * @param dat The data to decode to string
1796
+ * @param latin1 Whether or not to interpret the data as Latin-1. This should
1797
+ * not need to be true unless encoding to binary string.
1798
+ * @returns The original UTF-8/Latin-1 string
1799
+ */
1800
+ export function strFromU8(dat, latin1) {
1801
+ if (latin1) {
1802
+ var r = '';
1803
+ for (var i = 0; i < dat.length; i += 16384)
1804
+ r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
1805
+ return r;
1806
+ }
1807
+ else if (td) {
1808
+ return td.decode(dat);
1809
+ }
1810
+ else {
1811
+ var _a = dutf8(dat), s = _a.s, r = _a.r;
1812
+ if (r.length)
1813
+ err(8);
1814
+ return s;
1815
+ }
1816
+ }
1817
+ ;
1818
+ // deflate bit flag
1819
+ var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };
1820
+ // skip local zip header
1821
+ var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };
1822
+ // read zip header
1823
+ var zh = function (d, b, z) {
1824
+ var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);
1825
+ var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];
1826
+ return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];
1827
+ };
1828
+ // read zip64 extra field
1829
+ var z64e = function (d, b) {
1830
+ for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))
1831
+ ;
1832
+ return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];
1833
+ };
1834
+ // extra field length
1835
+ var exfl = function (ex) {
1836
+ var le = 0;
1837
+ if (ex) {
1838
+ for (var k in ex) {
1839
+ var l = ex[k].length;
1840
+ if (l > 65535)
1841
+ err(9);
1842
+ le += l + 4;
1843
+ }
1844
+ }
1845
+ return le;
1846
+ };
1847
+ // write zip header
1848
+ var wzh = function (d, b, f, fn, u, c, ce, co) {
1849
+ var fl = fn.length, ex = f.extra, col = co && co.length;
1850
+ var exl = exfl(ex);
1851
+ wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;
1852
+ if (ce != null)
1853
+ d[b++] = 20, d[b++] = f.os;
1854
+ d[b] = 20, b += 2; // spec compliance? what's that?
1855
+ d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;
1856
+ d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
1857
+ var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
1858
+ if (y < 0 || y > 119)
1859
+ err(10);
1860
+ wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4;
1861
+ if (c != -1) {
1862
+ wbytes(d, b, f.crc);
1863
+ wbytes(d, b + 4, c < 0 ? -c - 2 : c);
1864
+ wbytes(d, b + 8, f.size);
1865
+ }
1866
+ wbytes(d, b + 12, fl);
1867
+ wbytes(d, b + 14, exl), b += 16;
1868
+ if (ce != null) {
1869
+ wbytes(d, b, col);
1870
+ wbytes(d, b + 6, f.attrs);
1871
+ wbytes(d, b + 10, ce), b += 14;
1872
+ }
1873
+ d.set(fn, b);
1874
+ b += fl;
1875
+ if (exl) {
1876
+ for (var k in ex) {
1877
+ var exf = ex[k], l = exf.length;
1878
+ wbytes(d, b, +k);
1879
+ wbytes(d, b + 2, l);
1880
+ d.set(exf, b + 4), b += 4 + l;
1881
+ }
1882
+ }
1883
+ if (col)
1884
+ d.set(co, b), b += col;
1885
+ return b;
1886
+ };
1887
+ // write zip footer (end of central directory)
1888
+ var wzf = function (o, b, c, d, e) {
1889
+ wbytes(o, b, 0x6054B50); // skip disk
1890
+ wbytes(o, b + 8, c);
1891
+ wbytes(o, b + 10, c);
1892
+ wbytes(o, b + 12, d);
1893
+ wbytes(o, b + 16, e);
1894
+ };
1895
+ /**
1896
+ * A pass-through stream to keep data uncompressed in a ZIP archive.
1897
+ */
1898
+ var ZipPassThrough = /*#__PURE__*/ (function () {
1899
+ /**
1900
+ * Creates a pass-through stream that can be added to ZIP archives
1901
+ * @param filename The filename to associate with this data stream
1902
+ */
1903
+ function ZipPassThrough(filename) {
1904
+ this.filename = filename;
1905
+ this.c = crc();
1906
+ this.size = 0;
1907
+ this.compression = 0;
1908
+ }
1909
+ /**
1910
+ * Processes a chunk and pushes to the output stream. You can override this
1911
+ * method in a subclass for custom behavior, but by default this passes
1912
+ * the data through. You must call this.ondata(err, chunk, final) at some
1913
+ * point in this method.
1914
+ * @param chunk The chunk to process
1915
+ * @param final Whether this is the last chunk
1916
+ */
1917
+ ZipPassThrough.prototype.process = function (chunk, final) {
1918
+ this.ondata(null, chunk, final);
1919
+ };
1920
+ /**
1921
+ * Pushes a chunk to be added. If you are subclassing this with a custom
1922
+ * compression algorithm, note that you must push data from the source
1923
+ * file only, pre-compression.
1924
+ * @param chunk The chunk to push
1925
+ * @param final Whether this is the last chunk
1926
+ */
1927
+ ZipPassThrough.prototype.push = function (chunk, final) {
1928
+ if (!this.ondata)
1929
+ err(5);
1930
+ this.c.p(chunk);
1931
+ this.size += chunk.length;
1932
+ if (final)
1933
+ this.crc = this.c.d();
1934
+ this.process(chunk, final || false);
1935
+ };
1936
+ return ZipPassThrough;
1937
+ }());
1938
+ export { ZipPassThrough };
1939
+ // I don't extend because TypeScript extension adds 1kB of runtime bloat
1940
+ /**
1941
+ * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate
1942
+ * for better performance
1943
+ */
1944
+ var ZipDeflate = /*#__PURE__*/ (function () {
1945
+ /**
1946
+ * Creates a DEFLATE stream that can be added to ZIP archives
1947
+ * @param filename The filename to associate with this data stream
1948
+ * @param opts The compression options
1949
+ */
1950
+ function ZipDeflate(filename, opts) {
1951
+ var _this = this;
1952
+ if (!opts)
1953
+ opts = {};
1954
+ ZipPassThrough.call(this, filename);
1955
+ this.d = new Deflate(opts, function (dat, final) {
1956
+ _this.ondata(null, dat, final);
1957
+ });
1958
+ this.compression = 8;
1959
+ this.flag = dbf(opts.level);
1960
+ }
1961
+ ZipDeflate.prototype.process = function (chunk, final) {
1962
+ try {
1963
+ this.d.push(chunk, final);
1964
+ }
1965
+ catch (e) {
1966
+ this.ondata(e, null, final);
1967
+ }
1968
+ };
1969
+ /**
1970
+ * Pushes a chunk to be deflated
1971
+ * @param chunk The chunk to push
1972
+ * @param final Whether this is the last chunk
1973
+ */
1974
+ ZipDeflate.prototype.push = function (chunk, final) {
1975
+ ZipPassThrough.prototype.push.call(this, chunk, final);
1976
+ };
1977
+ return ZipDeflate;
1978
+ }());
1979
+ export { ZipDeflate };
1980
+ /**
1981
+ * Asynchronous streaming DEFLATE compression for ZIP archives
1982
+ */
1983
+ var AsyncZipDeflate = /*#__PURE__*/ (function () {
1984
+ /**
1985
+ * Creates an asynchronous DEFLATE stream that can be added to ZIP archives
1986
+ * @param filename The filename to associate with this data stream
1987
+ * @param opts The compression options
1988
+ */
1989
+ function AsyncZipDeflate(filename, opts) {
1990
+ var _this = this;
1991
+ if (!opts)
1992
+ opts = {};
1993
+ ZipPassThrough.call(this, filename);
1994
+ this.d = new AsyncDeflate(opts, function (err, dat, final) {
1995
+ _this.ondata(err, dat, final);
1996
+ });
1997
+ this.compression = 8;
1998
+ this.flag = dbf(opts.level);
1999
+ this.terminate = this.d.terminate;
2000
+ }
2001
+ AsyncZipDeflate.prototype.process = function (chunk, final) {
2002
+ this.d.push(chunk, final);
2003
+ };
2004
+ /**
2005
+ * Pushes a chunk to be deflated
2006
+ * @param chunk The chunk to push
2007
+ * @param final Whether this is the last chunk
2008
+ */
2009
+ AsyncZipDeflate.prototype.push = function (chunk, final) {
2010
+ ZipPassThrough.prototype.push.call(this, chunk, final);
2011
+ };
2012
+ return AsyncZipDeflate;
2013
+ }());
2014
+ export { AsyncZipDeflate };
2015
+ // TODO: Better tree shaking
2016
+ /**
2017
+ * A zippable archive to which files can incrementally be added
2018
+ */
2019
+ var Zip = /*#__PURE__*/ (function () {
2020
+ /**
2021
+ * Creates an empty ZIP archive to which files can be added
2022
+ * @param cb The callback to call whenever data for the generated ZIP archive
2023
+ * is available
2024
+ */
2025
+ function Zip(cb) {
2026
+ this.ondata = cb;
2027
+ this.u = [];
2028
+ this.d = 1;
2029
+ }
2030
+ /**
2031
+ * Adds a file to the ZIP archive
2032
+ * @param file The file stream to add
2033
+ */
2034
+ Zip.prototype.add = function (file) {
2035
+ var _this = this;
2036
+ if (!this.ondata)
2037
+ err(5);
2038
+ // finishing or finished
2039
+ if (this.d & 2)
2040
+ this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);
2041
+ else {
2042
+ var f = strToU8(file.filename), fl_1 = f.length;
2043
+ var com = file.comment, o = com && strToU8(com);
2044
+ var u = fl_1 != file.filename.length || (o && (com.length != o.length));
2045
+ var hl_1 = fl_1 + exfl(file.extra) + 30;
2046
+ if (fl_1 > 65535)
2047
+ this.ondata(err(11, 0, 1), null, false);
2048
+ var header = new u8(hl_1);
2049
+ wzh(header, 0, file, f, u, -1);
2050
+ var chks_1 = [header];
2051
+ var pAll_1 = function () {
2052
+ for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {
2053
+ var chk = chks_2[_i];
2054
+ _this.ondata(null, chk, false);
2055
+ }
2056
+ chks_1 = [];
2057
+ };
2058
+ var tr_1 = this.d;
2059
+ this.d = 0;
2060
+ var ind_1 = this.u.length;
2061
+ var uf_1 = mrg(file, {
2062
+ f: f,
2063
+ u: u,
2064
+ o: o,
2065
+ t: function () {
2066
+ if (file.terminate)
2067
+ file.terminate();
2068
+ },
2069
+ r: function () {
2070
+ pAll_1();
2071
+ if (tr_1) {
2072
+ var nxt = _this.u[ind_1 + 1];
2073
+ if (nxt)
2074
+ nxt.r();
2075
+ else
2076
+ _this.d = 1;
2077
+ }
2078
+ tr_1 = 1;
2079
+ }
2080
+ });
2081
+ var cl_1 = 0;
2082
+ file.ondata = function (err, dat, final) {
2083
+ if (err) {
2084
+ _this.ondata(err, dat, final);
2085
+ _this.terminate();
2086
+ }
2087
+ else {
2088
+ cl_1 += dat.length;
2089
+ chks_1.push(dat);
2090
+ if (final) {
2091
+ var dd = new u8(16);
2092
+ wbytes(dd, 0, 0x8074B50);
2093
+ wbytes(dd, 4, file.crc);
2094
+ wbytes(dd, 8, cl_1);
2095
+ wbytes(dd, 12, file.size);
2096
+ chks_1.push(dd);
2097
+ uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;
2098
+ if (tr_1)
2099
+ uf_1.r();
2100
+ tr_1 = 1;
2101
+ }
2102
+ else if (tr_1)
2103
+ pAll_1();
2104
+ }
2105
+ };
2106
+ this.u.push(uf_1);
2107
+ }
2108
+ };
2109
+ /**
2110
+ * Ends the process of adding files and prepares to emit the final chunks.
2111
+ * This *must* be called after adding all desired files for the resulting
2112
+ * ZIP file to work properly.
2113
+ */
2114
+ Zip.prototype.end = function () {
2115
+ var _this = this;
2116
+ if (this.d & 2) {
2117
+ this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);
2118
+ return;
2119
+ }
2120
+ if (this.d)
2121
+ this.e();
2122
+ else
2123
+ this.u.push({
2124
+ r: function () {
2125
+ if (!(_this.d & 1))
2126
+ return;
2127
+ _this.u.splice(-1, 1);
2128
+ _this.e();
2129
+ },
2130
+ t: function () { }
2131
+ });
2132
+ this.d = 3;
2133
+ };
2134
+ Zip.prototype.e = function () {
2135
+ var bt = 0, l = 0, tl = 0;
2136
+ for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
2137
+ var f = _a[_i];
2138
+ tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);
2139
+ }
2140
+ var out = new u8(tl + 22);
2141
+ for (var _b = 0, _c = this.u; _b < _c.length; _b++) {
2142
+ var f = _c[_b];
2143
+ wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);
2144
+ bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;
2145
+ }
2146
+ wzf(out, bt, this.u.length, tl, l);
2147
+ this.ondata(null, out, true);
2148
+ this.d = 2;
2149
+ };
2150
+ /**
2151
+ * A method to terminate any internal workers used by the stream. Subsequent
2152
+ * calls to add() will fail.
2153
+ */
2154
+ Zip.prototype.terminate = function () {
2155
+ for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
2156
+ var f = _a[_i];
2157
+ f.t();
2158
+ }
2159
+ this.d = 2;
2160
+ };
2161
+ return Zip;
2162
+ }());
2163
+ export { Zip };
2164
+ export function zip(data, opts, cb) {
2165
+ if (!cb)
2166
+ cb = opts, opts = {};
2167
+ if (typeof cb != 'function')
2168
+ err(7);
2169
+ var r = {};
2170
+ fltn(data, '', r, opts);
2171
+ var k = Object.keys(r);
2172
+ var lft = k.length, o = 0, tot = 0;
2173
+ var slft = lft, files = new Array(lft);
2174
+ var term = [];
2175
+ var tAll = function () {
2176
+ for (var i = 0; i < term.length; ++i)
2177
+ term[i]();
2178
+ };
2179
+ var cbd = function (a, b) {
2180
+ mt(function () { cb(a, b); });
2181
+ };
2182
+ mt(function () { cbd = cb; });
2183
+ var cbf = function () {
2184
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
2185
+ tot = 0;
2186
+ for (var i = 0; i < slft; ++i) {
2187
+ var f = files[i];
2188
+ try {
2189
+ var l = f.c.length;
2190
+ wzh(out, tot, f, f.f, f.u, l);
2191
+ var badd = 30 + f.f.length + exfl(f.extra);
2192
+ var loc = tot + badd;
2193
+ out.set(f.c, loc);
2194
+ wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;
2195
+ }
2196
+ catch (e) {
2197
+ return cbd(e, null);
2198
+ }
2199
+ }
2200
+ wzf(out, o, files.length, cdl, oe);
2201
+ cbd(null, out);
2202
+ };
2203
+ if (!lft)
2204
+ cbf();
2205
+ var _loop_1 = function (i) {
2206
+ var fn = k[i];
2207
+ var _a = r[fn], file = _a[0], p = _a[1];
2208
+ var c = crc(), size = file.length;
2209
+ c.p(file);
2210
+ var f = strToU8(fn), s = f.length;
2211
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
2212
+ var exl = exfl(p.extra);
2213
+ var compression = p.level == 0 ? 0 : 8;
2214
+ var cbl = function (e, d) {
2215
+ if (e) {
2216
+ tAll();
2217
+ cbd(e, null);
2218
+ }
2219
+ else {
2220
+ var l = d.length;
2221
+ files[i] = mrg(p, {
2222
+ size: size,
2223
+ crc: c.d(),
2224
+ c: d,
2225
+ f: f,
2226
+ m: m,
2227
+ u: s != fn.length || (m && (com.length != ms)),
2228
+ compression: compression
2229
+ });
2230
+ o += 30 + s + exl + l;
2231
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
2232
+ if (!--lft)
2233
+ cbf();
2234
+ }
2235
+ };
2236
+ if (s > 65535)
2237
+ cbl(err(11, 0, 1), null);
2238
+ if (!compression)
2239
+ cbl(null, file);
2240
+ else if (size < 160000) {
2241
+ try {
2242
+ cbl(null, deflateSync(file, p));
2243
+ }
2244
+ catch (e) {
2245
+ cbl(e, null);
2246
+ }
2247
+ }
2248
+ else
2249
+ term.push(deflate(file, p, cbl));
2250
+ };
2251
+ // Cannot use lft because it can decrease
2252
+ for (var i = 0; i < slft; ++i) {
2253
+ _loop_1(i);
2254
+ }
2255
+ return tAll;
2256
+ }
2257
+ /**
2258
+ * Synchronously creates a ZIP file. Prefer using `zip` for better performance
2259
+ * with more than one file.
2260
+ * @param data The directory structure for the ZIP archive
2261
+ * @param opts The main options, merged with per-file options
2262
+ * @returns The generated ZIP archive
2263
+ */
2264
+ export function zipSync(data, opts) {
2265
+ if (!opts)
2266
+ opts = {};
2267
+ var r = {};
2268
+ var files = [];
2269
+ fltn(data, '', r, opts);
2270
+ var o = 0;
2271
+ var tot = 0;
2272
+ for (var fn in r) {
2273
+ var _a = r[fn], file = _a[0], p = _a[1];
2274
+ var compression = p.level == 0 ? 0 : 8;
2275
+ var f = strToU8(fn), s = f.length;
2276
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
2277
+ var exl = exfl(p.extra);
2278
+ if (s > 65535)
2279
+ err(11);
2280
+ var d = compression ? deflateSync(file, p) : file, l = d.length;
2281
+ var c = crc();
2282
+ c.p(file);
2283
+ files.push(mrg(p, {
2284
+ size: file.length,
2285
+ crc: c.d(),
2286
+ c: d,
2287
+ f: f,
2288
+ m: m,
2289
+ u: s != fn.length || (m && (com.length != ms)),
2290
+ o: o,
2291
+ compression: compression
2292
+ }));
2293
+ o += 30 + s + exl + l;
2294
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
2295
+ }
2296
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
2297
+ for (var i = 0; i < files.length; ++i) {
2298
+ var f = files[i];
2299
+ wzh(out, f.o, f, f.f, f.u, f.c.length);
2300
+ var badd = 30 + f.f.length + exfl(f.extra);
2301
+ out.set(f.c, f.o + badd);
2302
+ wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
2303
+ }
2304
+ wzf(out, o, files.length, cdl, oe);
2305
+ return out;
2306
+ }
2307
+ /**
2308
+ * Streaming pass-through decompression for ZIP archives
2309
+ */
2310
+ var UnzipPassThrough = /*#__PURE__*/ (function () {
2311
+ function UnzipPassThrough() {
2312
+ }
2313
+ UnzipPassThrough.prototype.push = function (data, final) {
2314
+ this.ondata(null, data, final);
2315
+ };
2316
+ UnzipPassThrough.compression = 0;
2317
+ return UnzipPassThrough;
2318
+ }());
2319
+ export { UnzipPassThrough };
2320
+ /**
2321
+ * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for
2322
+ * better performance.
2323
+ */
2324
+ var UnzipInflate = /*#__PURE__*/ (function () {
2325
+ /**
2326
+ * Creates a DEFLATE decompression that can be used in ZIP archives
2327
+ */
2328
+ function UnzipInflate() {
2329
+ var _this = this;
2330
+ this.i = new Inflate(function (dat, final) {
2331
+ _this.ondata(null, dat, final);
2332
+ });
2333
+ }
2334
+ UnzipInflate.prototype.push = function (data, final) {
2335
+ try {
2336
+ this.i.push(data, final);
2337
+ }
2338
+ catch (e) {
2339
+ this.ondata(e, null, final);
2340
+ }
2341
+ };
2342
+ UnzipInflate.compression = 8;
2343
+ return UnzipInflate;
2344
+ }());
2345
+ export { UnzipInflate };
2346
+ /**
2347
+ * Asynchronous streaming DEFLATE decompression for ZIP archives
2348
+ */
2349
+ var AsyncUnzipInflate = /*#__PURE__*/ (function () {
2350
+ /**
2351
+ * Creates a DEFLATE decompression that can be used in ZIP archives
2352
+ */
2353
+ function AsyncUnzipInflate(_, sz) {
2354
+ var _this = this;
2355
+ if (sz < 320000) {
2356
+ this.i = new Inflate(function (dat, final) {
2357
+ _this.ondata(null, dat, final);
2358
+ });
2359
+ }
2360
+ else {
2361
+ this.i = new AsyncInflate(function (err, dat, final) {
2362
+ _this.ondata(err, dat, final);
2363
+ });
2364
+ this.terminate = this.i.terminate;
2365
+ }
2366
+ }
2367
+ AsyncUnzipInflate.prototype.push = function (data, final) {
2368
+ if (this.i.terminate)
2369
+ data = slc(data, 0);
2370
+ this.i.push(data, final);
2371
+ };
2372
+ AsyncUnzipInflate.compression = 8;
2373
+ return AsyncUnzipInflate;
2374
+ }());
2375
+ export { AsyncUnzipInflate };
2376
+ /**
2377
+ * A ZIP archive decompression stream that emits files as they are discovered
2378
+ */
2379
+ var Unzip = /*#__PURE__*/ (function () {
2380
+ /**
2381
+ * Creates a ZIP decompression stream
2382
+ * @param cb The callback to call whenever a file in the ZIP archive is found
2383
+ */
2384
+ function Unzip(cb) {
2385
+ this.onfile = cb;
2386
+ this.k = [];
2387
+ this.o = {
2388
+ 0: UnzipPassThrough
2389
+ };
2390
+ this.p = et;
2391
+ }
2392
+ /**
2393
+ * Pushes a chunk to be unzipped
2394
+ * @param chunk The chunk to push
2395
+ * @param final Whether this is the last chunk
2396
+ */
2397
+ Unzip.prototype.push = function (chunk, final) {
2398
+ var _this = this;
2399
+ if (!this.onfile)
2400
+ err(5);
2401
+ if (!this.p)
2402
+ err(4);
2403
+ if (this.c > 0) {
2404
+ var len = Math.min(this.c, chunk.length);
2405
+ var toAdd = chunk.subarray(0, len);
2406
+ this.c -= len;
2407
+ if (this.d)
2408
+ this.d.push(toAdd, !this.c);
2409
+ else
2410
+ this.k[0].push(toAdd);
2411
+ chunk = chunk.subarray(len);
2412
+ if (chunk.length)
2413
+ return this.push(chunk, final);
2414
+ }
2415
+ else {
2416
+ var f = 0, i = 0, is = void 0, buf = void 0;
2417
+ if (!this.p.length)
2418
+ buf = chunk;
2419
+ else if (!chunk.length)
2420
+ buf = this.p;
2421
+ else {
2422
+ buf = new u8(this.p.length + chunk.length);
2423
+ buf.set(this.p), buf.set(chunk, this.p.length);
2424
+ }
2425
+ var l = buf.length, oc = this.c, add = oc && this.d;
2426
+ var _loop_2 = function () {
2427
+ var _a;
2428
+ var sig = b4(buf, i);
2429
+ if (sig == 0x4034B50) {
2430
+ f = 1, is = i;
2431
+ this_1.d = null;
2432
+ this_1.c = 0;
2433
+ var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);
2434
+ if (l > i + 30 + fnl + es) {
2435
+ var chks_3 = [];
2436
+ this_1.k.unshift(chks_3);
2437
+ f = 2;
2438
+ var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);
2439
+ var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);
2440
+ if (sc_1 == 4294967295) {
2441
+ _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];
2442
+ }
2443
+ else if (dd)
2444
+ sc_1 = -1;
2445
+ i += es;
2446
+ this_1.c = sc_1;
2447
+ var d_1;
2448
+ var file_1 = {
2449
+ name: fn_1,
2450
+ compression: cmp_1,
2451
+ start: function () {
2452
+ if (!file_1.ondata)
2453
+ err(5);
2454
+ if (!sc_1)
2455
+ file_1.ondata(null, et, true);
2456
+ else {
2457
+ var ctr = _this.o[cmp_1];
2458
+ if (!ctr)
2459
+ file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);
2460
+ d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);
2461
+ d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };
2462
+ for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {
2463
+ var dat = chks_4[_i];
2464
+ d_1.push(dat, false);
2465
+ }
2466
+ if (_this.k[0] == chks_3 && _this.c)
2467
+ _this.d = d_1;
2468
+ else
2469
+ d_1.push(et, true);
2470
+ }
2471
+ },
2472
+ terminate: function () {
2473
+ if (d_1 && d_1.terminate)
2474
+ d_1.terminate();
2475
+ }
2476
+ };
2477
+ if (sc_1 >= 0)
2478
+ file_1.size = sc_1, file_1.originalSize = su_1;
2479
+ this_1.onfile(file_1);
2480
+ }
2481
+ return "break";
2482
+ }
2483
+ else if (oc) {
2484
+ if (sig == 0x8074B50) {
2485
+ is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;
2486
+ return "break";
2487
+ }
2488
+ else if (sig == 0x2014B50) {
2489
+ is = i -= 4, f = 3, this_1.c = 0;
2490
+ return "break";
2491
+ }
2492
+ }
2493
+ };
2494
+ var this_1 = this;
2495
+ for (; i < l - 4; ++i) {
2496
+ var state_1 = _loop_2();
2497
+ if (state_1 === "break")
2498
+ break;
2499
+ }
2500
+ this.p = et;
2501
+ if (oc < 0) {
2502
+ var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);
2503
+ if (add)
2504
+ add.push(dat, !!f);
2505
+ else
2506
+ this.k[+(f == 2)].push(dat);
2507
+ }
2508
+ if (f & 2)
2509
+ return this.push(buf.subarray(i), final);
2510
+ this.p = buf.subarray(i);
2511
+ }
2512
+ if (final) {
2513
+ if (this.c)
2514
+ err(13);
2515
+ this.p = null;
2516
+ }
2517
+ };
2518
+ /**
2519
+ * Registers a decoder with the stream, allowing for files compressed with
2520
+ * the compression type provided to be expanded correctly
2521
+ * @param decoder The decoder constructor
2522
+ */
2523
+ Unzip.prototype.register = function (decoder) {
2524
+ this.o[decoder.compression] = decoder;
2525
+ };
2526
+ return Unzip;
2527
+ }());
2528
+ export { Unzip };
2529
+ var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };
2530
+ export function unzip(data, opts, cb) {
2531
+ if (!cb)
2532
+ cb = opts, opts = {};
2533
+ if (typeof cb != 'function')
2534
+ err(7);
2535
+ var term = [];
2536
+ var tAll = function () {
2537
+ for (var i = 0; i < term.length; ++i)
2538
+ term[i]();
2539
+ };
2540
+ var files = {};
2541
+ var cbd = function (a, b) {
2542
+ mt(function () { cb(a, b); });
2543
+ };
2544
+ mt(function () { cbd = cb; });
2545
+ var e = data.length - 22;
2546
+ for (; b4(data, e) != 0x6054B50; --e) {
2547
+ if (!e || data.length - e > 65558) {
2548
+ cbd(err(13, 0, 1), null);
2549
+ return tAll;
2550
+ }
2551
+ }
2552
+ ;
2553
+ var lft = b2(data, e + 8);
2554
+ if (lft) {
2555
+ var c = lft;
2556
+ var o = b4(data, e + 16);
2557
+ var z = o == 4294967295 || c == 65535;
2558
+ if (z) {
2559
+ var ze = b4(data, e - 12);
2560
+ z = b4(data, ze) == 0x6064B50;
2561
+ if (z) {
2562
+ c = lft = b4(data, ze + 32);
2563
+ o = b4(data, ze + 48);
2564
+ }
2565
+ }
2566
+ var fltr = opts && opts.filter;
2567
+ var _loop_3 = function (i) {
2568
+ var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
2569
+ o = no;
2570
+ var cbl = function (e, d) {
2571
+ if (e) {
2572
+ tAll();
2573
+ cbd(e, null);
2574
+ }
2575
+ else {
2576
+ if (d)
2577
+ files[fn] = d;
2578
+ if (!--lft)
2579
+ cbd(null, files);
2580
+ }
2581
+ };
2582
+ if (!fltr || fltr({
2583
+ name: fn,
2584
+ size: sc,
2585
+ originalSize: su,
2586
+ compression: c_1
2587
+ })) {
2588
+ if (!c_1)
2589
+ cbl(null, slc(data, b, b + sc));
2590
+ else if (c_1 == 8) {
2591
+ var infl = data.subarray(b, b + sc);
2592
+ // Synchronously decompress under 512KB, or barely-compressed data
2593
+ if (su < 524288 || sc > 0.8 * su) {
2594
+ try {
2595
+ cbl(null, inflateSync(infl, { out: new u8(su) }));
2596
+ }
2597
+ catch (e) {
2598
+ cbl(e, null);
2599
+ }
2600
+ }
2601
+ else
2602
+ term.push(inflate(infl, { size: su }, cbl));
2603
+ }
2604
+ else
2605
+ cbl(err(14, 'unknown compression type ' + c_1, 1), null);
2606
+ }
2607
+ else
2608
+ cbl(null, null);
2609
+ };
2610
+ for (var i = 0; i < c; ++i) {
2611
+ _loop_3(i);
2612
+ }
2613
+ }
2614
+ else
2615
+ cbd(null, {});
2616
+ return tAll;
2617
+ }
2618
+ /**
2619
+ * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better
2620
+ * performance with more than one file.
2621
+ * @param data The raw compressed ZIP file
2622
+ * @param opts The ZIP extraction options
2623
+ * @returns The decompressed files
2624
+ */
2625
+ export function unzipSync(data, opts) {
2626
+ var files = {};
2627
+ var e = data.length - 22;
2628
+ for (; b4(data, e) != 0x6054B50; --e) {
2629
+ if (!e || data.length - e > 65558)
2630
+ err(13);
2631
+ }
2632
+ ;
2633
+ var c = b2(data, e + 8);
2634
+ if (!c)
2635
+ return {};
2636
+ var o = b4(data, e + 16);
2637
+ var z = o == 4294967295 || c == 65535;
2638
+ if (z) {
2639
+ var ze = b4(data, e - 12);
2640
+ z = b4(data, ze) == 0x6064B50;
2641
+ if (z) {
2642
+ c = b4(data, ze + 32);
2643
+ o = b4(data, ze + 48);
2644
+ }
2645
+ }
2646
+ var fltr = opts && opts.filter;
2647
+ for (var i = 0; i < c; ++i) {
2648
+ var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
2649
+ o = no;
2650
+ if (!fltr || fltr({
2651
+ name: fn,
2652
+ size: sc,
2653
+ originalSize: su,
2654
+ compression: c_2
2655
+ })) {
2656
+ if (!c_2)
2657
+ files[fn] = slc(data, b, b + sc);
2658
+ else if (c_2 == 8)
2659
+ files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
2660
+ else
2661
+ err(14, 'unknown compression type ' + c_2);
2662
+ }
2663
+ }
2664
+ return files;
2665
+ }
vendor/libjpegturbowasm_decode.js ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ var libjpegturbowasm_decode = (() => {
3
+ var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;
4
+ if (typeof __filename != 'undefined') _scriptName = _scriptName || __filename;
5
+ return (
6
+ function(moduleArg = {}) {
7
+ var moduleRtn;
8
+
9
+ var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){}var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(!Module["thisProgram"]&&process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptName){scriptDirectory=_scriptName}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";var isDataURI=filename=>filename.startsWith(dataURIPrefix);var isFileURI=filename=>filename.startsWith("file://");function findWasmBinary(){var f="libjpegturbowasm_decode.wasm";if(!isDataURI(f)){return locateFile(f)}return f}var wasmBinaryFile;function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(binaryFile)&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["N"];updateMemoryViews();wasmTable=wasmExports["Q"];addOnInit(wasmExports["O"]);removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){try{return Module["instantiateWasm"](info,receiveInstance)}catch(e){err(`Module.instantiateWasm callback failed with error: ${e}`);readyPromiseReject(e)}}wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);receiveInstantiationResult(result);return result}catch(e){readyPromiseReject(e);return}}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var noExitRuntime=Module["noExitRuntime"]||true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var __abort_js=()=>abort("");var structRegistrations={};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function readPointer(pointer){return this["fromWireType"](HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var InternalError;var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;dependentTypes.forEach((dt,i)=>{if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}});if(0===unregisteredTypes.length){onComplete(typeConverters)}};var __embind_finalize_value_object=structType=>{var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};fieldRecords.forEach((field,i)=>{var fieldName=field.fieldName;var getterReturnType=fieldTypes[i];var getter=field.getter;var getterContext=field.getterContext;var setterArgumentType=fieldTypes[i+fieldRecords.length];var setter=field.setter;var setterContext=field.setterContext;fields[fieldName]={read:ptr=>getterReturnType["fromWireType"](getter(getterContext,ptr)),write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,o));runDestructors(destructors)}}});return[{name:reg.name,fromWireType:ptr=>{var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},toWireType:(destructors,o)=>{for(var fieldName in fields){if(!(fieldName in o)){throw new TypeError(`Missing field: "${fieldName}"`)}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},argPackAdvance:GenericWireTypeSize,readValueFromPointer:readPointer,destructorFunction:rawDestructor}]})};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{};var embind_init_charCodes=()=>{var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes};var embind_charCodes;var readLatin1String=ptr=>{var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret};var BindingError;var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var GenericWireTypeSize=8;var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=readLatin1String(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},argPackAdvance:GenericWireTypeSize,readValueFromPointer:function(pointer){return this["fromWireType"](HEAPU8[pointer])},destructorFunction:null})};var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredPointers={};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record,writable:true}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var attachFinalizer=handle=>{if("undefined"===typeof FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var init_ClassHandle=()=>{Object.assign(ClassHandle.prototype,{isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},isDeleted(){return!this.$$.ptr},deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}})};function ClassHandle(){}var createNamedFunction=(name,body)=>Object.defineProperty(body,"name",{value:name});var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle||!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){this.rawDestructor?.(ptr)},argPackAdvance:GenericWireTypeSize,readValueFromPointer:readPointer,fromWireType:RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&&registeredClass.baseClass===undefined){if(isConst){this["toWireType"]=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this["toWireType"]=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this["toWireType"]=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var dynCallLegacy=(sig,ptr,args)=>{sig=sig.replace(/p/g,"i");var f=Module["dynCall_"+sig];return f(ptr,...args)};var wasmTableMirror=[];var wasmTable;var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){if(funcPtr>=wasmTableMirror.length)wasmTableMirror.length=funcPtr+1;wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var dynCall=(sig,ptr,args=[])=>{if(sig.includes("j")){return dynCallLegacy(sig,ptr,args)}var rtn=getWasmTableEntry(ptr)(...args);return rtn};var getDynCaller=(sig,ptr)=>(...args)=>dynCall(sig,ptr,args);var embind__requireFunction=(signature,rawFunction)=>{signature=readLatin1String(signature);function makeDynCaller(){if(signature.includes("j")){return getDynCaller(signature,rawFunction)}return getWasmTableEntry(rawFunction)}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};var extendError=(baseErrorType,errorName)=>{var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return`${this.name}: ${this.message}`}};return errorClass};var UnboundTypeError;var getTypeName=type=>{var ptr=___getTypeName(type);var rv=readLatin1String(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var __embind_register_class=(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor)=>{name=readLatin1String(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);upcast&&=embind__requireFunction(upcastSignature,upcast);downcast&&=embind__requireFunction(downcastSignature,downcast);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],base=>{base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(name,function(...args){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError("Use 'new' to construct "+name)}if(undefined===registeredClass.constructor_body){throw new BindingError(name+" has no accessible constructor")}var body=registeredClass.constructor_body[args.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,args)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){registeredClass.baseClass.__derivedClasses??=[];registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}var InvokerFunctions={ftf:function(humanName,throwBindingError,invoker,fn,runDestructors,retType,classParam){return function(){var rv=invoker(fn);var ret=retType["fromWireType"](rv);return ret}},ttfnn:function(humanName,throwBindingError,invoker,fn,runDestructors,retType,classParam,argType0){return function(arg0){var thisWired=classParam["toWireType"](null,this);var arg0Wired=argType0["toWireType"](null,arg0);var rv=invoker(fn,thisWired,arg0Wired);var ret=retType["fromWireType"](rv);return ret}},ttfn:function(humanName,throwBindingError,invoker,fn,runDestructors,retType,classParam){return function(){var thisWired=classParam["toWireType"](null,this);var rv=invoker(fn,thisWired);var ret=retType["fromWireType"](rv);return ret}},tffn:function(humanName,throwBindingError,invoker,fn,runDestructors,retType,classParam){return function(){var thisWired=classParam["toWireType"](null,this);invoker(fn,thisWired)}}};function createJsInvokerSignature(argTypes,isClassMethodFunc,returns,isAsync){const signature=[isClassMethodFunc?"t":"f",returns?"t":"f",isAsync?"t":"f"];for(let i=isClassMethodFunc?1:2;i<argTypes.length;++i){const arg=argTypes[i];let destructorSig="";if(arg.destructorFunction===undefined){destructorSig="u"}else if(arg.destructorFunction===null){destructorSig="n"}else{destructorSig="t"}signature.push(destructorSig)}return signature.join("")}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=argTypes[0].name!=="void";var closureArgs=[humanName,throwBindingError,cppInvokerFunc,cppTargetFunc,runDestructors,argTypes[0],argTypes[1]];for(var i=0;i<argCount-2;++i){closureArgs.push(argTypes[i+2])}if(!needsDestructorStack){for(var i=isClassMethodFunc?1:2;i<argTypes.length;++i){if(argTypes[i].destructorFunction!==null){closureArgs.push(argTypes[i].destructorFunction)}}}var signature=createJsInvokerSignature(argTypes,isClassMethodFunc,returns,isAsync);var invokerFn=InvokerFunctions[signature](...closureArgs);return createNamedFunction(humanName,invokerFn)}var __embind_register_class_constructor=(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex!==-1){return signature.substr(0,argsIndex)}else{return signature}};var __embind_register_class_function=(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync,isNonnullReturn)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);methodName=getFunctionName(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var emval_freelist=[];var emval_handles=[];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var count_emval_handles=()=>emval_handles.length/2-5-emval_freelist.length;var init_emval=()=>{emval_handles.push(0,1,undefined,1,null,1,true,1,false,1);Module["count_emval_handles"]=count_emval_handles};var Emval={toValue:handle=>{if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),argPackAdvance:GenericWireTypeSize,readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 8:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=readLatin1String(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,argPackAdvance:GenericWireTypeSize,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var fromWireType=value=>value;if(minRange===0){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift}var isUnsignedType=name.includes("unsigned");var checkAssertions=(value,toTypeName)=>{};var toWireType;if(isUnsignedType){toWireType=function(destructors,value){checkAssertions(value,this.name);return value>>>0}}else{toWireType=function(destructors,value){checkAssertions(value,this.name);return value}}registerType(primitiveType,{name,fromWireType,toWireType,argPackAdvance:GenericWireTypeSize,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name,fromWireType:decodeMemoryView,argPackAdvance:GenericWireTypeSize,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder:undefined;var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead=NaN)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var __embind_register_std_string=(rawType,name)=>{name=readLatin1String(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){var decodeStartPtr=payload;for(var i=0;i<=length;++i){var currentBytePtr=payload+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i<length;++i){a[i]=String.fromCharCode(HEAPU8[payload+i])}str=a.join("")}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||value instanceof Uint8Array||value instanceof Uint8ClampedArray||value instanceof Int8Array)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr,length+1)}else{if(valueIsOfTypeString){for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}else{for(var i=0;i<length;++i){HEAPU8[ptr+i]=value[i]}}}if(destructors!==null){destructors.push(_free,base)}return base},argPackAdvance:GenericWireTypeSize,readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead)=>{var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder)return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr));var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead)=>{var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343)++i;len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=readLatin1String(name);var decodeString,encodeString,readCharAt,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16;readCharAt=pointer=>HEAPU16[pointer>>1]}else if(charSize===4){decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32;readCharAt=pointer=>HEAPU32[pointer>>2]}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||readCharAt(currentBytePtr)==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},argPackAdvance:GenericWireTypeSize,readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_value_object=(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor)=>{structRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}};var __embind_register_value_object_field=(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{structRegistrations[structType].fields.push({fieldName:readLatin1String(fieldName),getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext,setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext})};var __embind_register_void=(rawType,name)=>{name=readLatin1String(name);registerType(rawType,{isVoid:true,name,argPackAdvance:0,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var __emscripten_memcpy_js=(dest,src,num)=>HEAPU8.copyWithin(dest,src,src+num);var __emscripten_throw_longjmp=()=>{throw Infinity};var emval_methodCallers=[];var __emval_call=(caller,handle,destructorsRef,args)=>{caller=emval_methodCallers[caller];handle=Emval.toValue(handle);return caller(null,handle,destructorsRef,args)};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}return symbol};var emval_get_global=()=>{if(typeof globalThis=="object"){return globalThis}function testGlobal(obj){obj["$$$embind_global$$$"]=obj;var success=typeof $$$embind_global$$$=="object"&&obj["$$$embind_global$$$"]==obj;if(!success){delete obj["$$$embind_global$$$"]}return success}if(typeof $$$embind_global$$$=="object"){return $$$embind_global$$$}if(typeof global=="object"&&testGlobal(global)){$$$embind_global$$$=global}else if(typeof self=="object"&&testGlobal(self)){$$$embind_global$$$=self}if(typeof $$$embind_global$$$=="object"){return $$$embind_global$$$}throw Error("unable to get global object.")};var __emval_get_global=name=>{if(name===0){return Emval.toHandle(emval_get_global())}else{name=getStringOrSymbol(name);return Emval.toHandle(emval_get_global()[name])}};var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],"parameter "+i)}return a};var reflectConstruct=Reflect.construct;var emval_returnValue=(returnType,destructorsRef,handle)=>{var destructors=[];var result=returnType["toWireType"](destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var __emval_get_method_caller=(argCount,argTypes,kind)=>{var types=emval_lookupTypes(argCount,argTypes);var retType=types.shift();argCount--;var argN=new Array(argCount);var invokerFunction=(obj,func,destructorsRef,args)=>{var offset=0;for(var i=0;i<argCount;++i){argN[i]=types[i]["readValueFromPointer"](args+offset);offset+=types[i].argPackAdvance}var rv=kind===1?reflectConstruct(func,argN):func.apply(obj,argN);return emval_returnValue(retType,destructorsRef,rv)};var functionName=`methodCaller<(${types.map(t=>t.name).join(", ")}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_take_value=(type,arg)=>{type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](arg);return Emval.toHandle(v)};var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var stringToAscii=(str,buffer)=>{for(var i=0;i<str.length;++i){HEAP8[buffer++]=str.charCodeAt(i)}HEAP8[buffer]=0};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;getEnvStrings().forEach((string,i)=>{var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;stringToAscii(string,ptr);bufSize+=string.length+1});return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(string=>bufSize+=string.length+1);HEAPU32[penviron_buf_size>>2]=bufSize;return 0};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var _fd_close=fd=>52;var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function _fd_seek(fd,offset_low,offset_high,whence,newOffset){var offset=convertI32PairToI53Checked(offset_low,offset_high);return 70}var printCharBuffers=[null,[],[]];var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer));buffer.length=0}else{buffer.push(curr)}};var _fd_write=(fd,iov,iovcnt,pnum)=>{var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j<len;j++){printChar(fd,HEAPU8[ptr+j])}num+=len}HEAPU32[pnum>>2]=num;return 0};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};InternalError=Module["InternalError"]=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};embind_init_charCodes();BindingError=Module["BindingError"]=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};init_ClassHandle();init_RegisteredPointer();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();var wasmImports={i:___cxa_throw,v:__abort_js,s:__embind_finalize_value_object,u:__embind_register_bigint,H:__embind_register_bool,r:__embind_register_class,q:__embind_register_class_constructor,f:__embind_register_class_function,F:__embind_register_emval,n:__embind_register_float,c:__embind_register_integer,b:__embind_register_memory_view,G:__embind_register_std_string,k:__embind_register_std_wstring,E:__embind_register_value_object,g:__embind_register_value_object_field,I:__embind_register_void,B:__emscripten_memcpy_js,w:__emscripten_throw_longjmp,K:__emval_call,L:__emval_decref,M:__emval_get_global,o:__emval_get_method_caller,J:__emval_run_destructors,p:__emval_take_value,x:_emscripten_resize_heap,y:_environ_get,z:_environ_sizes_get,D:_exit,A:_fd_close,t:_fd_seek,l:_fd_write,m:invoke_ii,e:invoke_iii,j:invoke_iiii,a:invoke_iiiii,C:invoke_iiiiiii,h:invoke_vi,d:invoke_viii};var wasmExports;createWasm();var ___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports["O"])();var ___getTypeName=a0=>(___getTypeName=wasmExports["P"])(a0);var _free=a0=>(_free=wasmExports["R"])(a0);var _malloc=a0=>(_malloc=wasmExports["S"])(a0);var _setThrew=(a0,a1)=>(_setThrew=wasmExports["T"])(a0,a1);var __emscripten_stack_restore=a0=>(__emscripten_stack_restore=wasmExports["U"])(a0);var __emscripten_stack_alloc=a0=>(__emscripten_stack_alloc=wasmExports["V"])(a0);var _emscripten_stack_get_current=()=>(_emscripten_stack_get_current=wasmExports["W"])();var dynCall_jiji=Module["dynCall_jiji"]=(a0,a1,a2,a3,a4)=>(dynCall_jiji=Module["dynCall_jiji"]=wasmExports["X"])(a0,a1,a2,a3,a4);function invoke_ii(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(index,a1,a2,a3){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_vi(index,a1){var sp=stackSave();try{getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiii(index,a1,a2,a3){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iii(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}Module["ccall"]=ccall;var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(){if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();moduleRtn=readyPromise;
10
+
11
+
12
+ return moduleRtn;
13
+ }
14
+ );
15
+ })();
16
+ if (typeof exports === 'object' && typeof module === 'object') {
17
+ module.exports = libjpegturbowasm_decode;
18
+ // This default export looks redundant, but it allows TS to import this
19
+ // commonjs style module.
20
+ module.exports.default = libjpegturbowasm_decode;
21
+ } else if (typeof define === 'function' && define['amd'])
22
+ define([], () => libjpegturbowasm_decode);
vendor/{mozjpeg_dec.wasm → libjpegturbowasm_decode.wasm} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:a7c4b12169817e779ff4af137981393ae924944e167ad1bd95747c9199162d3e
3
- size 166470
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8d104602540b9e7aeefeaac23af7380f40c5a3460291d40246a26783929a696
3
+ size 299002
vendor/mozjpeg_dec.js DELETED
@@ -1,15 +0,0 @@
1
-
2
- var Module = (() => {
3
- var _scriptDir = import.meta.url;
4
-
5
- return (
6
- function(moduleArg = {}) {
7
-
8
- var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});const isServiceWorker=globalThis.ServiceWorkerGlobalScope!==undefined;const isRunningInCloudFlareWorkers=isServiceWorker&&typeof self!=="undefined"&&globalThis.caches&&globalThis.caches.default!==undefined;const isRunningInNode=typeof process==="object"&&process.release&&process.release.name==="node";if(isRunningInCloudFlareWorkers||isRunningInNode){if(!globalThis.ImageData){globalThis.ImageData=class ImageData{constructor(data,width,height){this.data=data;this.width=width;this.height=height}}}if(import.meta.url===undefined){import.meta.url="https://localhost"}if(typeof self!=="undefined"&&self.location===undefined){self.location={href:""}}}var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof importScripts=="function";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";var isDataURI=filename=>filename.startsWith(dataURIPrefix);var wasmBinaryFile;if(Module["locateFile"]){wasmBinaryFile="mozjpeg_dec.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}}else{wasmBinaryFile=new URL("mozjpeg_dec.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(binaryFile){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{if(!response["ok"]){throw`failed to load wasm binary file at '${binaryFile}'`}return response["arrayBuffer"]()}).catch(()=>getBinarySync(binaryFile))}}return Promise.resolve().then(()=>getBinarySync(binaryFile))}function instantiateArrayBuffer(binaryFile,imports,receiver){return getBinaryPromise(binaryFile).then(binary=>WebAssembly.instantiate(binary,imports)).then(receiver,reason=>{err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)})}function instantiateAsync(binary,binaryFile,imports,callback){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(binaryFile)&&typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{var result=WebAssembly.instantiateStreaming(response,imports);return result.then(callback,function(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(binaryFile,imports,callback)})})}return instantiateArrayBuffer(binaryFile,imports,callback)}function createWasm(){var info={"a":wasmImports};function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["A"];updateMemoryViews();wasmTable=wasmExports["F"];addOnInit(wasmExports["B"]);removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}if(Module["instantiateWasm"]){try{return Module["instantiateWasm"](info,receiveInstance)}catch(e){err(`Module.instantiateWasm callback failed with error: ${e}`);readyPromiseReject(e)}}instantiateAsync(wasmBinary,wasmBinaryFile,info,receiveInstantiationResult).catch(readyPromiseReject);return{}}function ExitStatus(status){this.name="ExitStatus";this.message=`Program terminated with exit(${status})`;this.status=status}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var noExitRuntime=Module["noExitRuntime"]||true;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}get_exception_ptr(){var isPointer=___cxa_is_pointer_type(this.get_type());if(isPointer){return HEAPU32[this.excPtr>>2]}var adjusted=this.get_adjusted_ptr();if(adjusted!==0)return adjusted;return this.excPtr}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{};var embind_init_charCodes=()=>{var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes};var embind_charCodes;var readLatin1String=ptr=>{var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret};var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var BindingError;var throwBindingError=message=>{throw new BindingError(message)};var InternalError;var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;dependentTypes.forEach((dt,i)=>{if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}});if(0===unregisteredTypes.length){onComplete(typeConverters)}};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){if(!("argPackAdvance"in registeredInstance)){throw new TypeError("registerType registeredInstance requires argPackAdvance")}return sharedRegisterType(rawType,registeredInstance,options)}var GenericWireTypeSize=8;var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(wt){return!!wt},"toWireType":function(destructors,o){return o?trueValue:falseValue},"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":function(pointer){return this["fromWireType"](HEAPU8[pointer])},destructorFunction:null})};var emval_freelist=[];var emval_handles=[];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var count_emval_handles=()=>emval_handles.length/2-5-emval_freelist.length;var init_emval=()=>{emval_handles.push(0,1,undefined,1,null,1,true,1,false,1);Module["count_emval_handles"]=count_emval_handles};var Emval={toValue:handle=>{if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};function readPointer(pointer){return this["fromWireType"](HEAPU32[pointer>>2])}var EmValType={name:"emscripten::val","fromWireType":handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},"toWireType":(destructors,value)=>Emval.toHandle(value),"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 8:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":value=>value,"toWireType":(destructors,value)=>value,"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":floatReadValueFromPointer(name,size),destructorFunction:null})};var createNamedFunction=(name,body)=>Object.defineProperty(body,"name",{value:name});var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=argTypes[0].name!=="void";var expectedArgCount=argCount-2;var argsWired=new Array(expectedArgCount);var invokerFuncArgs=[];var destructors=[];var invokerFn=function(...args){if(args.length!==expectedArgCount){throwBindingError(`function ${humanName} called with ${args.length} arguments, expected ${expectedArgCount}`)}destructors.length=0;var thisWired;invokerFuncArgs.length=isClassMethodFunc?2:1;invokerFuncArgs[0]=cppTargetFunc;if(isClassMethodFunc){thisWired=argTypes[1]["toWireType"](destructors,this);invokerFuncArgs[1]=thisWired}for(var i=0;i<expectedArgCount;++i){argsWired[i]=argTypes[i+2]["toWireType"](destructors,args[i]);invokerFuncArgs.push(argsWired[i])}var rv=cppInvokerFunc(...invokerFuncArgs);function onDone(rv){if(needsDestructorStack){runDestructors(destructors)}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;i++){var param=i===1?thisWired:argsWired[i-2];if(argTypes[i].destructorFunction!==null){argTypes[i].destructorFunction(param)}}}if(returns){return argTypes[0]["fromWireType"](rv)}}return onDone(rv)};return createNamedFunction(humanName,invokerFn)}var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;if(undefined!==numArguments){Module[name].numArguments=numArguments}}};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var dynCallLegacy=(sig,ptr,args)=>{sig=sig.replace(/p/g,"i");var f=Module["dynCall_"+sig];return f(ptr,...args)};var wasmTableMirror=[];var wasmTable;var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){if(funcPtr>=wasmTableMirror.length)wasmTableMirror.length=funcPtr+1;wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var dynCall=(sig,ptr,args=[])=>{if(sig.includes("j")){return dynCallLegacy(sig,ptr,args)}var rtn=getWasmTableEntry(ptr)(...args);return rtn};var getDynCaller=(sig,ptr)=>(...args)=>dynCall(sig,ptr,args);var embind__requireFunction=(signature,rawFunction)=>{signature=readLatin1String(signature);function makeDynCaller(){if(signature.includes("j")){return getDynCaller(signature,rawFunction)}return getWasmTableEntry(rawFunction)}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};var extendError=(baseErrorType,errorName)=>{var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return`${this.name}: ${this.message}`}};return errorClass};var UnboundTypeError;var getTypeName=type=>{var ptr=___getTypeName(type);var rv=readLatin1String(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex!==-1){return signature.substr(0,argsIndex)}else{return signature}};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=readLatin1String(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var fromWireType=value=>value;if(minRange===0){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift}var isUnsignedType=name.includes("unsigned");var checkAssertions=(value,toTypeName)=>{};var toWireType;if(isUnsignedType){toWireType=function(destructors,value){checkAssertions(value,this.name);return value>>>0}}else{toWireType=function(destructors,value){checkAssertions(value,this.name);return value}}registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":toWireType,"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var UTF8ArrayToString=(heapOrArray,idx,maxBytesToRead)=>{var endIdx=idx+maxBytesToRead;var str="";while(!(idx>=endIdx)){var u0=heapOrArray[idx++];if(!u0)return str;if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var __embind_register_std_string=(rawType,name)=>{name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType"(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){var decodeStartPtr=payload;for(var i=0;i<=length;++i){var currentBytePtr=payload+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i<length;++i){a[i]=String.fromCharCode(HEAPU8[payload+i])}str=a.join("")}_free(value);return str},"toWireType"(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||value instanceof Uint8Array||value instanceof Uint8ClampedArray||value instanceof Int8Array)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr,length+1)}else{if(valueIsOfTypeString){for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}else{for(var i=0;i<length;++i){HEAPU8[ptr+i]=value[i]}}}if(destructors!==null){destructors.push(_free,base)}return base},"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16ToString=(ptr,maxBytesToRead)=>{var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead)=>{var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343)++i;len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=readLatin1String(name);var decodeString,encodeString,readCharAt,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16;readCharAt=pointer=>HEAPU16[pointer>>1]}else if(charSize===4){decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32;readCharAt=pointer=>HEAPU32[pointer>>2]}registerType(rawType,{name:name,"fromWireType":value=>{var length=HEAPU32[value>>2];var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||readCharAt(currentBytePtr)==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_void=(rawType,name)=>{name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":()=>undefined,"toWireType":(destructors,o)=>undefined})};var __emscripten_memcpy_js=(dest,src,num)=>HEAPU8.copyWithin(dest,src,src+num);var emval_methodCallers=[];var __emval_call=(caller,handle,destructorsRef,args)=>{caller=emval_methodCallers[caller];handle=Emval.toValue(handle);return caller(null,handle,destructorsRef,args)};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}return symbol};var emval_get_global=()=>{if(typeof globalThis=="object"){return globalThis}function testGlobal(obj){obj["$$$embind_global$$$"]=obj;var success=typeof $$$embind_global$$$=="object"&&obj["$$$embind_global$$$"]==obj;if(!success){delete obj["$$$embind_global$$$"]}return success}if(typeof $$$embind_global$$$=="object"){return $$$embind_global$$$}if(typeof global=="object"&&testGlobal(global)){$$$embind_global$$$=global}else if(typeof self=="object"&&testGlobal(self)){$$$embind_global$$$=self}if(typeof $$$embind_global$$$=="object"){return $$$embind_global$$$}throw Error("unable to get global object.")};var __emval_get_global=name=>{if(name===0){return Emval.toHandle(emval_get_global())}else{name=getStringOrSymbol(name);return Emval.toHandle(emval_get_global()[name])}};var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],"parameter "+i)}return a};var reflectConstruct=Reflect.construct;var emval_returnValue=(returnType,destructorsRef,handle)=>{var destructors=[];var result=returnType["toWireType"](destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var __emval_get_method_caller=(argCount,argTypes,kind)=>{var types=emval_lookupTypes(argCount,argTypes);var retType=types.shift();argCount--;var argN=new Array(argCount);var invokerFunction=(obj,func,destructorsRef,args)=>{var offset=0;for(var i=0;i<argCount;++i){argN[i]=types[i]["readValueFromPointer"](args+offset);offset+=types[i]["argPackAdvance"]}var rv=kind===1?reflectConstruct(func,argN):func.apply(obj,argN);return emval_returnValue(retType,destructorsRef,rv)};var functionName=`methodCaller<(${types.map(t=>t.name).join(", ")}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_incref=handle=>{if(handle>9){emval_handles[handle+1]+=1}};var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var _abort=()=>{abort("")};var getHeapMax=()=>2147483648;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}var alignUp=(x,multiple)=>x+(multiple-x%multiple)%multiple;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={"USER":"web_user","LOGNAME":"web_user","PATH":"/","PWD":"/","HOME":"/home/web_user","LANG":lang,"_":getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var stringToAscii=(str,buffer)=>{for(var i=0;i<str.length;++i){HEAP8[buffer++]=str.charCodeAt(i)}HEAP8[buffer]=0};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;getEnvStrings().forEach((string,i)=>{var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;stringToAscii(string,ptr);bufSize+=string.length+1});return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(string=>bufSize+=string.length+1);HEAPU32[penviron_buf_size>>2]=bufSize;return 0};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var _fd_close=fd=>52;var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function _fd_seek(fd,offset_low,offset_high,whence,newOffset){var offset=convertI32PairToI53Checked(offset_low,offset_high);return 70}var printCharBuffers=[null,[],[]];var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}};var _fd_write=(fd,iov,iovcnt,pnum)=>{var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j<len;j++){printChar(fd,HEAPU8[ptr+j])}num+=len}HEAPU32[pnum>>2]=num;return 0};embind_init_charCodes();BindingError=Module["BindingError"]=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};InternalError=Module["InternalError"]=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};init_emval();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");var wasmImports={o:___cxa_throw,q:__embind_register_bigint,m:__embind_register_bool,l:__embind_register_emval,j:__embind_register_float,f:__embind_register_function,b:__embind_register_integer,a:__embind_register_memory_view,e:__embind_register_std_string,c:__embind_register_std_wstring,n:__embind_register_void,v:__emscripten_memcpy_js,i:__emval_call,d:__emval_decref,k:__emval_get_global,h:__emval_get_method_caller,y:__emval_incref,g:__emval_run_destructors,r:_abort,s:_emscripten_resize_heap,t:_environ_get,u:_environ_sizes_get,z:_exit,w:_fd_close,p:_fd_seek,x:_fd_write};var wasmExports=createWasm();var ___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports["B"])();var ___getTypeName=a0=>(___getTypeName=wasmExports["C"])(a0);var _malloc=a0=>(_malloc=wasmExports["D"])(a0);var _free=a0=>(_free=wasmExports["E"])(a0);var __emscripten_stack_restore=a0=>(__emscripten_stack_restore=wasmExports["_emscripten_stack_restore"])(a0);var __emscripten_stack_alloc=a0=>(__emscripten_stack_alloc=wasmExports["_emscripten_stack_alloc"])(a0);var _emscripten_stack_get_current=()=>(_emscripten_stack_get_current=wasmExports["emscripten_stack_get_current"])();var ___cxa_increment_exception_refcount=a0=>(___cxa_increment_exception_refcount=wasmExports["__cxa_increment_exception_refcount"])(a0);var ___cxa_is_pointer_type=a0=>(___cxa_is_pointer_type=wasmExports["G"])(a0);var dynCall_jiji=Module["dynCall_jiji"]=(a0,a1,a2,a3,a4)=>(dynCall_jiji=Module["dynCall_jiji"]=wasmExports["H"])(a0,a1,a2,a3,a4);var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(){if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();
9
-
10
-
11
- return readyPromise
12
- }
13
- );
14
- })();
15
- export default Module;