@opentui/core
Version:
OpenTUI is a TypeScript library for building terminal user interfaces (TUIs)
34,042 lines • 1.13 MB
JavaScript
// @bun
import {
RGBA,
Renderable,
__commonJS,
__export,
__require,
__toESM
} from "./index-h3dbfsf6.js";
// ../../node_modules/.bun/omggif@1.0.10/node_modules/omggif/omggif.js
var require_omggif = __commonJS((exports) => {
function GifWriter(buf, width, height, gopts) {
var p = 0;
var gopts = gopts === undefined ? {} : gopts;
var loop_count = gopts.loop === undefined ? null : gopts.loop;
var global_palette = gopts.palette === undefined ? null : gopts.palette;
if (width <= 0 || height <= 0 || width > 65535 || height > 65535)
throw new Error("Width/Height invalid.");
function check_palette_and_num_colors(palette2) {
var num_colors = palette2.length;
if (num_colors < 2 || num_colors > 256 || num_colors & num_colors - 1) {
throw new Error("Invalid code/color length, must be power of 2 and 2 .. 256.");
}
return num_colors;
}
buf[p++] = 71;
buf[p++] = 73;
buf[p++] = 70;
buf[p++] = 56;
buf[p++] = 57;
buf[p++] = 97;
var gp_num_colors_pow2 = 0;
var background = 0;
if (global_palette !== null) {
var gp_num_colors = check_palette_and_num_colors(global_palette);
while (gp_num_colors >>= 1)
++gp_num_colors_pow2;
gp_num_colors = 1 << gp_num_colors_pow2;
--gp_num_colors_pow2;
if (gopts.background !== undefined) {
background = gopts.background;
if (background >= gp_num_colors)
throw new Error("Background index out of range.");
if (background === 0)
throw new Error("Background index explicitly passed as 0.");
}
}
buf[p++] = width & 255;
buf[p++] = width >> 8 & 255;
buf[p++] = height & 255;
buf[p++] = height >> 8 & 255;
buf[p++] = (global_palette !== null ? 128 : 0) | gp_num_colors_pow2;
buf[p++] = background;
buf[p++] = 0;
if (global_palette !== null) {
for (var i = 0, il = global_palette.length;i < il; ++i) {
var rgb = global_palette[i];
buf[p++] = rgb >> 16 & 255;
buf[p++] = rgb >> 8 & 255;
buf[p++] = rgb & 255;
}
}
if (loop_count !== null) {
if (loop_count < 0 || loop_count > 65535)
throw new Error("Loop count invalid.");
buf[p++] = 33;
buf[p++] = 255;
buf[p++] = 11;
buf[p++] = 78;
buf[p++] = 69;
buf[p++] = 84;
buf[p++] = 83;
buf[p++] = 67;
buf[p++] = 65;
buf[p++] = 80;
buf[p++] = 69;
buf[p++] = 50;
buf[p++] = 46;
buf[p++] = 48;
buf[p++] = 3;
buf[p++] = 1;
buf[p++] = loop_count & 255;
buf[p++] = loop_count >> 8 & 255;
buf[p++] = 0;
}
var ended = false;
this.addFrame = function(x, y, w, h, indexed_pixels, opts) {
if (ended === true) {
--p;
ended = false;
}
opts = opts === undefined ? {} : opts;
if (x < 0 || y < 0 || x > 65535 || y > 65535)
throw new Error("x/y invalid.");
if (w <= 0 || h <= 0 || w > 65535 || h > 65535)
throw new Error("Width/Height invalid.");
if (indexed_pixels.length < w * h)
throw new Error("Not enough pixels for the frame size.");
var using_local_palette = true;
var palette2 = opts.palette;
if (palette2 === undefined || palette2 === null) {
using_local_palette = false;
palette2 = global_palette;
}
if (palette2 === undefined || palette2 === null)
throw new Error("Must supply either a local or global palette.");
var num_colors = check_palette_and_num_colors(palette2);
var min_code_size = 0;
while (num_colors >>= 1)
++min_code_size;
num_colors = 1 << min_code_size;
var delay = opts.delay === undefined ? 0 : opts.delay;
var disposal = opts.disposal === undefined ? 0 : opts.disposal;
if (disposal < 0 || disposal > 3)
throw new Error("Disposal out of range.");
var use_transparency = false;
var transparent_index = 0;
if (opts.transparent !== undefined && opts.transparent !== null) {
use_transparency = true;
transparent_index = opts.transparent;
if (transparent_index < 0 || transparent_index >= num_colors)
throw new Error("Transparent color index.");
}
if (disposal !== 0 || use_transparency || delay !== 0) {
buf[p++] = 33;
buf[p++] = 249;
buf[p++] = 4;
buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0);
buf[p++] = delay & 255;
buf[p++] = delay >> 8 & 255;
buf[p++] = transparent_index;
buf[p++] = 0;
}
buf[p++] = 44;
buf[p++] = x & 255;
buf[p++] = x >> 8 & 255;
buf[p++] = y & 255;
buf[p++] = y >> 8 & 255;
buf[p++] = w & 255;
buf[p++] = w >> 8 & 255;
buf[p++] = h & 255;
buf[p++] = h >> 8 & 255;
buf[p++] = using_local_palette === true ? 128 | min_code_size - 1 : 0;
if (using_local_palette === true) {
for (var i2 = 0, il2 = palette2.length;i2 < il2; ++i2) {
var rgb2 = palette2[i2];
buf[p++] = rgb2 >> 16 & 255;
buf[p++] = rgb2 >> 8 & 255;
buf[p++] = rgb2 & 255;
}
}
p = GifWriterOutputLZWCodeStream(buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);
return p;
};
this.end = function() {
if (ended === false) {
buf[p++] = 59;
ended = true;
}
return p;
};
this.getOutputBuffer = function() {
return buf;
};
this.setOutputBuffer = function(v) {
buf = v;
};
this.getOutputBufferPosition = function() {
return p;
};
this.setOutputBufferPosition = function(v) {
p = v;
};
}
function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {
buf[p++] = min_code_size;
var cur_subblock = p++;
var clear_code = 1 << min_code_size;
var code_mask = clear_code - 1;
var eoi_code = clear_code + 1;
var next_code = eoi_code + 1;
var cur_code_size = min_code_size + 1;
var cur_shift = 0;
var cur = 0;
function emit_bytes_to_buffer(bit_block_size) {
while (cur_shift >= bit_block_size) {
buf[p++] = cur & 255;
cur >>= 8;
cur_shift -= 8;
if (p === cur_subblock + 256) {
buf[cur_subblock] = 255;
cur_subblock = p++;
}
}
}
function emit_code(c) {
cur |= c << cur_shift;
cur_shift += cur_code_size;
emit_bytes_to_buffer(8);
}
var ib_code = index_stream[0] & code_mask;
var code_table = {};
emit_code(clear_code);
for (var i = 1, il = index_stream.length;i < il; ++i) {
var k = index_stream[i] & code_mask;
var cur_key = ib_code << 8 | k;
var cur_code = code_table[cur_key];
if (cur_code === undefined) {
cur |= ib_code << cur_shift;
cur_shift += cur_code_size;
while (cur_shift >= 8) {
buf[p++] = cur & 255;
cur >>= 8;
cur_shift -= 8;
if (p === cur_subblock + 256) {
buf[cur_subblock] = 255;
cur_subblock = p++;
}
}
if (next_code === 4096) {
emit_code(clear_code);
next_code = eoi_code + 1;
cur_code_size = min_code_size + 1;
code_table = {};
} else {
if (next_code >= 1 << cur_code_size)
++cur_code_size;
code_table[cur_key] = next_code++;
}
ib_code = k;
} else {
ib_code = cur_code;
}
}
emit_code(ib_code);
emit_code(eoi_code);
emit_bytes_to_buffer(1);
if (cur_subblock + 1 === p) {
buf[cur_subblock] = 0;
} else {
buf[cur_subblock] = p - cur_subblock - 1;
buf[p++] = 0;
}
return p;
}
function GifReader(buf) {
var p = 0;
if (buf[p++] !== 71 || buf[p++] !== 73 || buf[p++] !== 70 || buf[p++] !== 56 || (buf[p++] + 1 & 253) !== 56 || buf[p++] !== 97) {
throw new Error("Invalid GIF 87a/89a header.");
}
var width = buf[p++] | buf[p++] << 8;
var height = buf[p++] | buf[p++] << 8;
var pf0 = buf[p++];
var global_palette_flag = pf0 >> 7;
var num_global_colors_pow2 = pf0 & 7;
var num_global_colors = 1 << num_global_colors_pow2 + 1;
var background = buf[p++];
buf[p++];
var global_palette_offset = null;
var global_palette_size = null;
if (global_palette_flag) {
global_palette_offset = p;
global_palette_size = num_global_colors;
p += num_global_colors * 3;
}
var no_eof = true;
var frames = [];
var delay = 0;
var transparent_index = null;
var disposal = 0;
var loop_count = null;
this.width = width;
this.height = height;
while (no_eof && p < buf.length) {
switch (buf[p++]) {
case 33:
switch (buf[p++]) {
case 255:
if (buf[p] !== 11 || buf[p + 1] == 78 && buf[p + 2] == 69 && buf[p + 3] == 84 && buf[p + 4] == 83 && buf[p + 5] == 67 && buf[p + 6] == 65 && buf[p + 7] == 80 && buf[p + 8] == 69 && buf[p + 9] == 50 && buf[p + 10] == 46 && buf[p + 11] == 48 && buf[p + 12] == 3 && buf[p + 13] == 1 && buf[p + 16] == 0) {
p += 14;
loop_count = buf[p++] | buf[p++] << 8;
p++;
} else {
p += 12;
while (true) {
var block_size = buf[p++];
if (!(block_size >= 0))
throw Error("Invalid block size");
if (block_size === 0)
break;
p += block_size;
}
}
break;
case 249:
if (buf[p++] !== 4 || buf[p + 4] !== 0)
throw new Error("Invalid graphics extension block.");
var pf1 = buf[p++];
delay = buf[p++] | buf[p++] << 8;
transparent_index = buf[p++];
if ((pf1 & 1) === 0)
transparent_index = null;
disposal = pf1 >> 2 & 7;
p++;
break;
case 254:
while (true) {
var block_size = buf[p++];
if (!(block_size >= 0))
throw Error("Invalid block size");
if (block_size === 0)
break;
p += block_size;
}
break;
default:
throw new Error("Unknown graphic control label: 0x" + buf[p - 1].toString(16));
}
break;
case 44:
var x = buf[p++] | buf[p++] << 8;
var y = buf[p++] | buf[p++] << 8;
var w = buf[p++] | buf[p++] << 8;
var h = buf[p++] | buf[p++] << 8;
var pf2 = buf[p++];
var local_palette_flag = pf2 >> 7;
var interlace_flag = pf2 >> 6 & 1;
var num_local_colors_pow2 = pf2 & 7;
var num_local_colors = 1 << num_local_colors_pow2 + 1;
var palette_offset = global_palette_offset;
var palette_size = global_palette_size;
var has_local_palette = false;
if (local_palette_flag) {
var has_local_palette = true;
palette_offset = p;
palette_size = num_local_colors;
p += num_local_colors * 3;
}
var data_offset = p;
p++;
while (true) {
var block_size = buf[p++];
if (!(block_size >= 0))
throw Error("Invalid block size");
if (block_size === 0)
break;
p += block_size;
}
frames.push({
x,
y,
width: w,
height: h,
has_local_palette,
palette_offset,
palette_size,
data_offset,
data_length: p - data_offset,
transparent_index,
interlaced: !!interlace_flag,
delay,
disposal
});
break;
case 59:
no_eof = false;
break;
default:
throw new Error("Unknown gif block: 0x" + buf[p - 1].toString(16));
break;
}
}
this.numFrames = function() {
return frames.length;
};
this.loopCount = function() {
return loop_count;
};
this.frameInfo = function(frame_num) {
if (frame_num < 0 || frame_num >= frames.length)
throw new Error("Frame index out of range.");
return frames[frame_num];
};
this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {
var frame = this.frameInfo(frame_num);
var num_pixels = frame.width * frame.height;
var index_stream = new Uint8Array(num_pixels);
GifReaderLZWOutputIndexStream(buf, frame.data_offset, index_stream, num_pixels);
var palette_offset2 = frame.palette_offset;
var trans = frame.transparent_index;
if (trans === null)
trans = 256;
var framewidth = frame.width;
var framestride = width - framewidth;
var xleft = framewidth;
var opbeg = (frame.y * width + frame.x) * 4;
var opend = ((frame.y + frame.height) * width + frame.x) * 4;
var op = opbeg;
var scanstride = framestride * 4;
if (frame.interlaced === true) {
scanstride += width * 4 * 7;
}
var interlaceskip = 8;
for (var i = 0, il = index_stream.length;i < il; ++i) {
var index = index_stream[i];
if (xleft === 0) {
op += scanstride;
xleft = framewidth;
if (op >= opend) {
scanstride = framestride * 4 + width * 4 * (interlaceskip - 1);
op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
interlaceskip >>= 1;
}
}
if (index === trans) {
op += 4;
} else {
var r = buf[palette_offset2 + index * 3];
var g = buf[palette_offset2 + index * 3 + 1];
var b = buf[palette_offset2 + index * 3 + 2];
pixels[op++] = b;
pixels[op++] = g;
pixels[op++] = r;
pixels[op++] = 255;
}
--xleft;
}
};
this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {
var frame = this.frameInfo(frame_num);
var num_pixels = frame.width * frame.height;
var index_stream = new Uint8Array(num_pixels);
GifReaderLZWOutputIndexStream(buf, frame.data_offset, index_stream, num_pixels);
var palette_offset2 = frame.palette_offset;
var trans = frame.transparent_index;
if (trans === null)
trans = 256;
var framewidth = frame.width;
var framestride = width - framewidth;
var xleft = framewidth;
var opbeg = (frame.y * width + frame.x) * 4;
var opend = ((frame.y + frame.height) * width + frame.x) * 4;
var op = opbeg;
var scanstride = framestride * 4;
if (frame.interlaced === true) {
scanstride += width * 4 * 7;
}
var interlaceskip = 8;
for (var i = 0, il = index_stream.length;i < il; ++i) {
var index = index_stream[i];
if (xleft === 0) {
op += scanstride;
xleft = framewidth;
if (op >= opend) {
scanstride = framestride * 4 + width * 4 * (interlaceskip - 1);
op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
interlaceskip >>= 1;
}
}
if (index === trans) {
op += 4;
} else {
var r = buf[palette_offset2 + index * 3];
var g = buf[palette_offset2 + index * 3 + 1];
var b = buf[palette_offset2 + index * 3 + 2];
pixels[op++] = r;
pixels[op++] = g;
pixels[op++] = b;
pixels[op++] = 255;
}
--xleft;
}
};
}
function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {
var min_code_size = code_stream[p++];
var clear_code = 1 << min_code_size;
var eoi_code = clear_code + 1;
var next_code = eoi_code + 1;
var cur_code_size = min_code_size + 1;
var code_mask = (1 << cur_code_size) - 1;
var cur_shift = 0;
var cur = 0;
var op = 0;
var subblock_size = code_stream[p++];
var code_table = new Int32Array(4096);
var prev_code = null;
while (true) {
while (cur_shift < 16) {
if (subblock_size === 0)
break;
cur |= code_stream[p++] << cur_shift;
cur_shift += 8;
if (subblock_size === 1) {
subblock_size = code_stream[p++];
} else {
--subblock_size;
}
}
if (cur_shift < cur_code_size)
break;
var code = cur & code_mask;
cur >>= cur_code_size;
cur_shift -= cur_code_size;
if (code === clear_code) {
next_code = eoi_code + 1;
cur_code_size = min_code_size + 1;
code_mask = (1 << cur_code_size) - 1;
prev_code = null;
continue;
} else if (code === eoi_code) {
break;
}
var chase_code = code < next_code ? code : prev_code;
var chase_length = 0;
var chase = chase_code;
while (chase > clear_code) {
chase = code_table[chase] >> 8;
++chase_length;
}
var k = chase;
var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
if (op_end > output_length) {
console.log("Warning, gif stream longer than expected.");
return;
}
output[op++] = k;
op += chase_length;
var b = op;
if (chase_code !== code)
output[op++] = k;
chase = chase_code;
while (chase_length--) {
chase = code_table[chase];
output[--b] = chase & 255;
chase >>= 8;
}
if (prev_code !== null && next_code < 4096) {
code_table[next_code++] = prev_code << 8 | k;
if (next_code >= code_mask + 1 && cur_code_size < 12) {
++cur_code_size;
code_mask = code_mask << 1 | 1;
}
}
prev_code = code;
}
if (op !== output_length) {
console.log("Warning, gif stream shorter than expected.");
}
return output;
}
try {
exports.GifWriter = GifWriter;
exports.GifReader = GifReader;
} catch (e) {}
});
// ../../node_modules/.bun/gifwrap@0.10.1/node_modules/gifwrap/src/bitmapimage.js
var require_bitmapimage = __commonJS((exports, module) => {
class BitmapImage {
constructor(...args) {
if (args.length === 0) {
throw new Error("constructor requires parameters");
}
const firstArg = args[0];
if (firstArg !== null && typeof firstArg === "object") {
if (firstArg instanceof BitmapImage) {
const sourceBitmap = firstArg.bitmap;
this.bitmap = {
width: sourceBitmap.width,
height: sourceBitmap.height,
data: new Buffer(sourceBitmap.width * sourceBitmap.height * 4)
};
sourceBitmap.data.copy(this.bitmap.data);
} else if (firstArg.width && firstArg.height && firstArg.data) {
this.bitmap = firstArg;
} else {
throw new Error("unrecognized constructor parameters");
}
} else if (typeof firstArg === "number" && typeof args[1] === "number") {
const width = firstArg;
const height = args[1];
const thirdArg = args[2];
this.bitmap = { width, height };
if (Buffer.isBuffer(thirdArg)) {
this.bitmap.data = thirdArg;
} else {
this.bitmap.data = new Buffer(width * height * 4);
if (typeof thirdArg === "number") {
this.fillRGBA(thirdArg);
}
}
} else {
throw new Error("unrecognized constructor parameters");
}
}
blit(toImage, toX, toY, fromX, fromY, fromWidth, fromHeight) {
if (fromX + fromWidth > this.bitmap.width) {
throw new Error("copy exceeds width of source bitmap");
}
if (toX + fromWidth > toImage.bitmap.width) {
throw new Error("copy exceeds width of target bitmap");
}
if (fromY + fromHeight > this.bitmap.height) {
throw new Error("copy exceeds height of source bitmap");
}
if (toY + fromHeight > toImage.bitmap.height) {
throw new Erro("copy exceeds height of target bitmap");
}
const sourceBuf = this.bitmap.data;
const targetBuf = toImage.bitmap.data;
const sourceByteWidth = this.bitmap.width * 4;
const targetByteWidth = toImage.bitmap.width * 4;
const copyByteWidth = fromWidth * 4;
let si = fromY * sourceByteWidth + fromX * 4;
let ti = toY * targetByteWidth + toX * 4;
while (--fromHeight >= 0) {
sourceBuf.copy(targetBuf, ti, si, si + copyByteWidth);
si += sourceByteWidth;
ti += targetByteWidth;
}
return this;
}
fillRGBA(rgba) {
const buf = this.bitmap.data;
const bufByteWidth = this.bitmap.height * 4;
let bi = 0;
while (bi < bufByteWidth) {
buf.writeUInt32BE(rgba, bi);
bi += 4;
}
while (bi < buf.length) {
buf.copy(buf, bi, 0, bufByteWidth);
bi += bufByteWidth;
}
return this;
}
getRGBA(x, y) {
const bi = (y * this.bitmap.width + x) * 4;
return this.bitmap.data.readUInt32BE(bi);
}
getRGBASet() {
const rgbaSet = new Set;
const buf = this.bitmap.data;
for (let bi = 0;bi < buf.length; bi += 4) {
rgbaSet.add(buf.readUInt32BE(bi, true));
}
return rgbaSet;
}
greyscale() {
const buf = this.bitmap.data;
this.scan(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => {
const grey = Math.round(0.299 * buf[idx] + 0.587 * buf[idx + 1] + 0.114 * buf[idx + 2]);
buf[idx] = grey;
buf[idx + 1] = grey;
buf[idx + 2] = grey;
});
return this;
}
reframe(xOffset, yOffset, width, height, fillRGBA) {
const cropX = xOffset < 0 ? 0 : xOffset;
const cropY = yOffset < 0 ? 0 : yOffset;
const cropWidth = width + cropX > this.bitmap.width ? this.bitmap.width - cropX : width;
const cropHeight = height + cropY > this.bitmap.height ? this.bitmap.height - cropY : height;
const newX = xOffset < 0 ? -xOffset : 0;
const newY = yOffset < 0 ? -yOffset : 0;
let image2;
if (fillRGBA === undefined) {
if (cropX !== xOffset || cropY != yOffset || cropWidth !== width || cropHeight !== height) {
throw new GifError(`fillRGBA required for this reframing`);
}
image2 = new BitmapImage(width, height);
} else {
image2 = new BitmapImage(width, height, fillRGBA);
}
this.blit(image2, newX, newY, cropX, cropY, cropWidth, cropHeight);
this.bitmap = image2.bitmap;
return this;
}
scale(factor) {
if (factor === 1) {
return;
}
if (!Number.isInteger(factor) || factor < 1) {
throw new Error("the scale must be an integer >= 1");
}
const sourceWidth = this.bitmap.width;
const sourceHeight = this.bitmap.height;
const destByteWidth = sourceWidth * factor * 4;
const sourceBuf = this.bitmap.data;
const destBuf = new Buffer(sourceHeight * destByteWidth * factor);
let sourceIndex = 0;
let priorDestRowIndex;
let destIndex = 0;
for (let y = 0;y < sourceHeight; ++y) {
priorDestRowIndex = destIndex;
for (let x = 0;x < sourceWidth; ++x) {
const color = sourceBuf.readUInt32BE(sourceIndex, true);
for (let cx = 0;cx < factor; ++cx) {
destBuf.writeUInt32BE(color, destIndex);
destIndex += 4;
}
sourceIndex += 4;
}
for (let cy = 1;cy < factor; ++cy) {
destBuf.copy(destBuf, destIndex, priorDestRowIndex, destIndex);
destIndex += destByteWidth;
priorDestRowIndex += destByteWidth;
}
}
this.bitmap = {
width: sourceWidth * factor,
height: sourceHeight * factor,
data: destBuf
};
return this;
}
scanAllCoords(scanHandler) {
const width = this.bitmap.width;
const bufferLength = this.bitmap.data.length;
let x = 0;
let y = 0;
for (let bi = 0;bi < bufferLength; bi += 4) {
scanHandler(x, y, bi);
if (++x === width) {
x = 0;
++y;
}
}
}
scanAllIndexes(scanHandler) {
const bufferLength = this.bitmap.data.length;
for (let bi = 0;bi < bufferLength; bi += 4) {
scanHandler(bi);
}
}
}
module.exports = BitmapImage;
});
// ../../node_modules/.bun/gifwrap@0.10.1/node_modules/gifwrap/src/gif.js
var require_gif = __commonJS((exports) => {
class Gif {
constructor(buffer, frames, spec) {
this.width = spec.width;
this.height = spec.height;
this.loops = spec.loops;
this.usesTransparency = spec.usesTransparency;
this.colorScope = spec.colorScope;
this.frames = frames;
this.buffer = buffer;
}
}
Gif.GlobalColorsPreferred = 0;
Gif.GlobalColorsOnly = 1;
Gif.LocalColorsOnly = 2;
class GifError2 extends Error {
constructor(messageOrError) {
super(messageOrError);
if (messageOrError instanceof Error) {
this.stack = "Gif" + messageOrError.stack;
}
}
}
exports.Gif = Gif;
exports.GifError = GifError2;
});
// ../../node_modules/.bun/image-q@4.0.0/node_modules/image-q/dist/cjs/image-q.cjs
var require_image_q = __commonJS((exports, module) => {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => (key in obj) ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export2 = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __reExport = (target, module2, copyDefault, desc) => {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
for (let key of __getOwnPropNames(module2))
if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
__defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
}
return target;
};
var __toCommonJS = /* @__PURE__ */ ((cache) => {
return (module2, temp) => {
return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
};
})(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap : 0);
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var src_exports = {};
__export2(src_exports, {
applyPalette: () => applyPalette,
applyPaletteSync: () => applyPaletteSync,
buildPalette: () => buildPalette,
buildPaletteSync: () => buildPaletteSync,
constants: () => constants_exports,
conversion: () => conversion_exports,
distance: () => distance_exports,
image: () => image_exports,
palette: () => palette_exports,
quality: () => quality_exports,
utils: () => utils_exports
});
var constants_exports = {};
__export2(constants_exports, {
bt709: () => bt709_exports
});
var bt709_exports = {};
__export2(bt709_exports, {
Y: () => Y,
x: () => x,
y: () => y
});
var Y = /* @__PURE__ */ ((Y2) => {
Y2[Y2["RED"] = 0.2126] = "RED";
Y2[Y2["GREEN"] = 0.7152] = "GREEN";
Y2[Y2["BLUE"] = 0.0722] = "BLUE";
Y2[Y2["WHITE"] = 1] = "WHITE";
return Y2;
})(Y || {});
var x = /* @__PURE__ */ ((x2) => {
x2[x2["RED"] = 0.64] = "RED";
x2[x2["GREEN"] = 0.3] = "GREEN";
x2[x2["BLUE"] = 0.15] = "BLUE";
x2[x2["WHITE"] = 0.3127] = "WHITE";
return x2;
})(x || {});
var y = /* @__PURE__ */ ((y2) => {
y2[y2["RED"] = 0.33] = "RED";
y2[y2["GREEN"] = 0.6] = "GREEN";
y2[y2["BLUE"] = 0.06] = "BLUE";
y2[y2["WHITE"] = 0.329] = "WHITE";
return y2;
})(y || {});
var conversion_exports = {};
__export2(conversion_exports, {
lab2rgb: () => lab2rgb,
lab2xyz: () => lab2xyz,
rgb2hsl: () => rgb2hsl,
rgb2lab: () => rgb2lab,
rgb2xyz: () => rgb2xyz,
xyz2lab: () => xyz2lab,
xyz2rgb: () => xyz2rgb
});
function correctGamma(n) {
return n > 0.04045 ? ((n + 0.055) / 1.055) ** 2.4 : n / 12.92;
}
function rgb2xyz(r, g, b) {
r = correctGamma(r / 255);
g = correctGamma(g / 255);
b = correctGamma(b / 255);
return {
x: r * 0.4124 + g * 0.3576 + b * 0.1805,
y: r * 0.2126 + g * 0.7152 + b * 0.0722,
z: r * 0.0193 + g * 0.1192 + b * 0.9505
};
}
var arithmetic_exports = {};
__export2(arithmetic_exports, {
degrees2radians: () => degrees2radians,
inRange0to255: () => inRange0to255,
inRange0to255Rounded: () => inRange0to255Rounded,
intInRange: () => intInRange,
max3: () => max3,
min3: () => min3,
stableSort: () => stableSort
});
function degrees2radians(n) {
return n * (Math.PI / 180);
}
function max3(a, b, c) {
let m = a;
if (m < b)
m = b;
if (m < c)
m = c;
return m;
}
function min3(a, b, c) {
let m = a;
if (m > b)
m = b;
if (m > c)
m = c;
return m;
}
function intInRange(value, low, high) {
if (value > high)
value = high;
if (value < low)
value = low;
return value | 0;
}
function inRange0to255Rounded(n) {
n = Math.round(n);
if (n > 255)
n = 255;
else if (n < 0)
n = 0;
return n;
}
function inRange0to255(n) {
if (n > 255)
n = 255;
else if (n < 0)
n = 0;
return n;
}
function stableSort(arrayToSort, callback) {
const type = typeof arrayToSort[0];
let sorted;
if (type === "number" || type === "string") {
const ord = /* @__PURE__ */ Object.create(null);
for (let i = 0, l = arrayToSort.length;i < l; i++) {
const val = arrayToSort[i];
if (ord[val] || ord[val] === 0)
continue;
ord[val] = i;
}
sorted = arrayToSort.sort((a, b) => callback(a, b) || ord[a] - ord[b]);
} else {
const ord2 = arrayToSort.slice(0);
sorted = arrayToSort.sort((a, b) => callback(a, b) || ord2.indexOf(a) - ord2.indexOf(b));
}
return sorted;
}
function rgb2hsl(r, g, b) {
const min = min3(r, g, b);
const max = max3(r, g, b);
const delta = max - min;
const l = (min + max) / 510;
let s = 0;
if (l > 0 && l < 1)
s = delta / (l < 0.5 ? max + min : 510 - max - min);
let h = 0;
if (delta > 0) {
if (max === r) {
h = (g - b) / delta;
} else if (max === g) {
h = 2 + (b - r) / delta;
} else {
h = 4 + (r - g) / delta;
}
h *= 60;
if (h < 0)
h += 360;
}
return { h, s, l };
}
var refX = 0.95047;
var refY = 1;
var refZ = 1.08883;
function pivot(n) {
return n > 0.008856 ? n ** (1 / 3) : 7.787 * n + 16 / 116;
}
function xyz2lab(x2, y2, z) {
x2 = pivot(x2 / refX);
y2 = pivot(y2 / refY);
z = pivot(z / refZ);
if (116 * y2 - 16 < 0)
throw new Error("xxx");
return {
L: Math.max(0, 116 * y2 - 16),
a: 500 * (x2 - y2),
b: 200 * (y2 - z)
};
}
function rgb2lab(r, g, b) {
const xyz = rgb2xyz(r, g, b);
return xyz2lab(xyz.x, xyz.y, xyz.z);
}
var refX2 = 0.95047;
var refY2 = 1;
var refZ2 = 1.08883;
function pivot2(n) {
return n > 0.206893034 ? n ** 3 : (n - 16 / 116) / 7.787;
}
function lab2xyz(L, a, b) {
const y2 = (L + 16) / 116;
const x2 = a / 500 + y2;
const z = y2 - b / 200;
return {
x: refX2 * pivot2(x2),
y: refY2 * pivot2(y2),
z: refZ2 * pivot2(z)
};
}
function correctGamma2(n) {
return n > 0.0031308 ? 1.055 * n ** (1 / 2.4) - 0.055 : 12.92 * n;
}
function xyz2rgb(x2, y2, z) {
const r = correctGamma2(x2 * 3.2406 + y2 * -1.5372 + z * -0.4986);
const g = correctGamma2(x2 * -0.9689 + y2 * 1.8758 + z * 0.0415);
const b = correctGamma2(x2 * 0.0557 + y2 * -0.204 + z * 1.057);
return {
r: inRange0to255Rounded(r * 255),
g: inRange0to255Rounded(g * 255),
b: inRange0to255Rounded(b * 255)
};
}
function lab2rgb(L, a, b) {
const xyz = lab2xyz(L, a, b);
return xyz2rgb(xyz.x, xyz.y, xyz.z);
}
var distance_exports = {};
__export2(distance_exports, {
AbstractDistanceCalculator: () => AbstractDistanceCalculator,
AbstractEuclidean: () => AbstractEuclidean,
AbstractManhattan: () => AbstractManhattan,
CIE94GraphicArts: () => CIE94GraphicArts,
CIE94Textiles: () => CIE94Textiles,
CIEDE2000: () => CIEDE2000,
CMetric: () => CMetric,
Euclidean: () => Euclidean,
EuclideanBT709: () => EuclideanBT709,
EuclideanBT709NoAlpha: () => EuclideanBT709NoAlpha,
Manhattan: () => Manhattan,
ManhattanBT709: () => ManhattanBT709,
ManhattanNommyde: () => ManhattanNommyde,
PNGQuant: () => PNGQuant
});
var AbstractDistanceCalculator = class {
constructor() {
__publicField(this, "_maxDistance");
__publicField(this, "_whitePoint");
this._setDefaults();
this.setWhitePoint(255, 255, 255, 255);
}
setWhitePoint(r, g, b, a) {
this._whitePoint = {
r: r > 0 ? 255 / r : 0,
g: g > 0 ? 255 / g : 0,
b: b > 0 ? 255 / b : 0,
a: a > 0 ? 255 / a : 0
};
this._maxDistance = this.calculateRaw(r, g, b, a, 0, 0, 0, 0);
}
calculateNormalized(colorA, colorB) {
return this.calculateRaw(colorA.r, colorA.g, colorA.b, colorA.a, colorB.r, colorB.g, colorB.b, colorB.a) / this._maxDistance;
}
};
var AbstractCIE94 = class extends AbstractDistanceCalculator {
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
const lab1 = rgb2lab(inRange0to255(r1 * this._whitePoint.r), inRange0to255(g1 * this._whitePoint.g), inRange0to255(b1 * this._whitePoint.b));
const lab2 = rgb2lab(inRange0to255(r2 * this._whitePoint.r), inRange0to255(g2 * this._whitePoint.g), inRange0to255(b2 * this._whitePoint.b));
const dL = lab1.L - lab2.L;
const dA = lab1.a - lab2.a;
const dB = lab1.b - lab2.b;
const c1 = Math.sqrt(lab1.a * lab1.a + lab1.b * lab1.b);
const c2 = Math.sqrt(lab2.a * lab2.a + lab2.b * lab2.b);
const dC = c1 - c2;
let deltaH = dA * dA + dB * dB - dC * dC;
deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH);
const dAlpha = (a2 - a1) * this._whitePoint.a * this._kA;
return Math.sqrt((dL / this._Kl) ** 2 + (dC / (1 + this._K1 * c1)) ** 2 + (deltaH / (1 + this._K2 * c1)) ** 2 + dAlpha ** 2);
}
};
var CIE94Textiles = class extends AbstractCIE94 {
_setDefaults() {
this._Kl = 2;
this._K1 = 0.048;
this._K2 = 0.014;
this._kA = 0.25 * 50 / 255;
}
};
var CIE94GraphicArts = class extends AbstractCIE94 {
_setDefaults() {
this._Kl = 1;
this._K1 = 0.045;
this._K2 = 0.015;
this._kA = 0.25 * 100 / 255;
}
};
var _CIEDE2000 = class extends AbstractDistanceCalculator {
_setDefaults() {}
static _calculatehp(b, ap) {
const hp = Math.atan2(b, ap);
if (hp >= 0)
return hp;
return hp + _CIEDE2000._deg360InRad;
}
static _calculateRT(ahp, aCp) {
const aCp_to_7 = aCp ** 7;
const R_C = 2 * Math.sqrt(aCp_to_7 / (aCp_to_7 + _CIEDE2000._pow25to7));
const delta_theta = _CIEDE2000._deg30InRad * Math.exp(-(((ahp - _CIEDE2000._deg275InRad) / _CIEDE2000._deg25InRad) ** 2));
return -Math.sin(2 * delta_theta) * R_C;
}
static _calculateT(ahp) {
return 1 - 0.17 * Math.cos(ahp - _CIEDE2000._deg30InRad) + 0.24 * Math.cos(ahp * 2) + 0.32 * Math.cos(ahp * 3 + _CIEDE2000._deg6InRad) - 0.2 * Math.cos(ahp * 4 - _CIEDE2000._deg63InRad);
}
static _calculate_ahp(C1pC2p, h_bar, h1p, h2p) {
const hpSum = h1p + h2p;
if (C1pC2p === 0)
return hpSum;
if (h_bar <= _CIEDE2000._deg180InRad)
return hpSum / 2;
if (hpSum < _CIEDE2000._deg360InRad) {
return (hpSum + _CIEDE2000._deg360InRad) / 2;
}
return (hpSum - _CIEDE2000._deg360InRad) / 2;
}
static _calculate_dHp(C1pC2p, h_bar, h2p, h1p) {
let dhp;
if (C1pC2p === 0) {
dhp = 0;
} else if (h_bar <= _CIEDE2000._deg180InRad) {
dhp = h2p - h1p;
} else if (h2p <= h1p) {
dhp = h2p - h1p + _CIEDE2000._deg360InRad;
} else {
dhp = h2p - h1p - _CIEDE2000._deg360InRad;
}
return 2 * Math.sqrt(C1pC2p) * Math.sin(dhp / 2);
}
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
const lab1 = rgb2lab(inRange0to255(r1 * this._whitePoint.r), inRange0to255(g1 * this._whitePoint.g), inRange0to255(b1 * this._whitePoint.b));
const lab2 = rgb2lab(inRange0to255(r2 * this._whitePoint.r), inRange0to255(g2 * this._whitePoint.g), inRange0to255(b2 * this._whitePoint.b));
const dA = (a2 - a1) * this._whitePoint.a * _CIEDE2000._kA;
const dE2 = this.calculateRawInLab(lab1, lab2);
return Math.sqrt(dE2 + dA * dA);
}
calculateRawInLab(Lab1, Lab2) {
const L1 = Lab1.L;
const a1 = Lab1.a;
const b1 = Lab1.b;
const L2 = Lab2.L;
const a2 = Lab2.a;
const b2 = Lab2.b;
const C1 = Math.sqrt(a1 * a1 + b1 * b1);
const C2 = Math.sqrt(a2 * a2 + b2 * b2);
const pow_a_C1_C2_to_7 = ((C1 + C2) / 2) ** 7;
const G = 0.5 * (1 - Math.sqrt(pow_a_C1_C2_to_7 / (pow_a_C1_C2_to_7 + _CIEDE2000._pow25to7)));
const a1p = (1 + G) * a1;
const a2p = (1 + G) * a2;
const C1p = Math.sqrt(a1p * a1p + b1 * b1);
const C2p = Math.sqrt(a2p * a2p + b2 * b2);
const C1pC2p = C1p * C2p;
const h1p = _CIEDE2000._calculatehp(b1, a1p);
const h2p = _CIEDE2000._calculatehp(b2, a2p);
const h_bar = Math.abs(h1p - h2p);
const dLp = L2 - L1;
const dCp = C2p - C1p;
const dHp = _CIEDE2000._calculate_dHp(C1pC2p, h_bar, h2p, h1p);
const ahp = _CIEDE2000._calculate_ahp(C1pC2p, h_bar, h1p, h2p);
const T = _CIEDE2000._calculateT(ahp);
const aCp = (C1p + C2p) / 2;
const aLp_minus_50_square = ((L1 + L2) / 2 - 50) ** 2;
const S_L = 1 + 0.015 * aLp_minus_50_square / Math.sqrt(20 + aLp_minus_50_square);
const S_C = 1 + 0.045 * aCp;
const S_H = 1 + 0.015 * T * aCp;
const R_T = _CIEDE2000._calculateRT(ahp, aCp);
const dLpSL = dLp / S_L;
const dCpSC = dCp / S_C;
const dHpSH = dHp / S_H;
return dLpSL ** 2 + dCpSC ** 2 + dHpSH ** 2 + R_T * dCpSC * dHpSH;
}
};
var CIEDE2000 = _CIEDE2000;
__publicField(CIEDE2000, "_kA", 0.25 * 100 / 255);
__publicField(CIEDE2000, "_pow25to7", 25 ** 7);
__publicField(CIEDE2000, "_deg360InRad", degrees2radians(360));
__publicField(CIEDE2000, "_deg180InRad", degrees2radians(180));
__publicField(CIEDE2000, "_deg30InRad", degrees2radians(30));
__publicField(CIEDE2000, "_deg6InRad", degrees2radians(6));
__publicField(CIEDE2000, "_deg63InRad", degrees2radians(63));
__publicField(CIEDE2000, "_deg275InRad", degrees2radians(275));
__publicField(CIEDE2000, "_deg25InRad", degrees2radians(25));
var CMetric = class extends AbstractDistanceCalculator {
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
const rmean = (r1 + r2) / 2 * this._whitePoint.r;
const r = (r1 - r2) * this._whitePoint.r;
const g = (g1 - g2) * this._whitePoint.g;
const b = (b1 - b2) * this._whitePoint.b;
const dE = ((512 + rmean) * r * r >> 8) + 4 * g * g + ((767 - rmean) * b * b >> 8);
const dA = (a2 - a1) * this._whitePoint.a;
return Math.sqrt(dE + dA * dA);
}
_setDefaults() {}
};
var AbstractEuclidean = class extends AbstractDistanceCalculator {
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
const dR = r2 - r1;
const dG = g2 - g1;
const dB = b2 - b1;
const dA = a2 - a1;
return Math.sqrt(this._kR * dR * dR + this._kG * dG * dG + this._kB * dB * dB + this._kA * dA * dA);
}
};
var Euclidean = class extends AbstractEuclidean {
_setDefaults() {
this._kR = 1;
this._kG = 1;
this._kB = 1;
this._kA = 1;
}
};
var EuclideanBT709 = class extends AbstractEuclidean {
_setDefaults() {
this._kR = 0.2126;
this._kG = 0.7152;
this._kB = 0.0722;
this._kA = 1;
}
};
var EuclideanBT709NoAlpha = class extends AbstractEuclidean {
_setDefaults() {
this._kR = 0.2126;
this._kG = 0.7152;
this._kB = 0.0722;
this._kA = 0;
}
};
var AbstractManhattan = class extends AbstractDistanceCalculator {
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
let dR = r2 - r1;
let dG = g2 - g1;
let dB = b2 - b1;
let dA = a2 - a1;
if (dR < 0)
dR = 0 - dR;
if (dG < 0)
dG = 0 - dG;
if (dB < 0)
dB = 0 - dB;
if (dA < 0)
dA = 0 - dA;
return this._kR * dR + this._kG * dG + this._kB * dB + this._kA * dA;
}
};
var Manhattan = class extends AbstractManhattan {
_setDefaults() {
this._kR = 1;
this._kG = 1;
this._kB = 1;
this._kA = 1;
}
};
var ManhattanNommyde = class extends AbstractManhattan {
_setDefaults() {
this._kR = 0.4984;
this._kG = 0.8625;
this._kB = 0.2979;
this._kA = 1;
}
};
var ManhattanBT709 = class extends AbstractManhattan {
_setDefaults() {
this._kR = 0.2126;
this._kG = 0.7152;
this._kB = 0.0722;
this._kA = 1;
}
};
var PNGQuant = class extends AbstractDistanceCalculator {
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
const alphas = (a2 - a1) * this._whitePoint.a;
return this._colordifferenceCh(r1 * this._whitePoint.r, r2 * this._whitePoint.r, alphas) + this._colordifferenceCh(g1 * this._whitePoint.g, g2 * this._whitePoint.g, alphas) + this._colordifferenceCh(b1 * this._whitePoint.b, b2 * this._whitePoint.b, alphas);
}
_colordifferenceCh(x2, y2, alphas) {
const black = x2 - y2;
const white = black + alphas;
return black * black + white * white;
}
_setDefaults() {}
};
var palette_exports = {};
__export2(palette_exports, {
AbstractPaletteQuantizer: () => AbstractPaletteQuantizer,
ColorHistogram: () => ColorHistogram,
NeuQuant: () => NeuQuant,
NeuQuantFloat: () => NeuQuantFloat,
RGBQuant: () => RGBQuant,
WuColorCube: () => WuColorCube,
WuQuant: () => WuQuant
});
var AbstractPaletteQuantizer = class {
quantizeSync() {
for (const value of this.quantize()) {
if (value.palette) {
return value.palette;
}
}
throw new Error("unreachable");
}
};
var Point = class {
constructor() {
__publicField(this, "r");
__publicField(this, "g");
__publicField(this, "b");
__publicField(this, "a");
__publicField(this, "uint32");
__publicField(this, "rgba");
this.uint32 = -1 >>> 0;
this.r = this.g = this.b = this.a = 0;
this.rgba = new Array(4);
this.rgba[0] = 0;
this.rgba[1] = 0;
this.rgba[2] = 0;
this.rgba[3] = 0;
}
static createByQuadruplet(quadruplet) {
const point = new Point;
point.r = quadruplet[0] | 0;
point.g = quadruplet[1] | 0;
point.b = quadruplet[2] | 0;
point.a = quadruplet[3] | 0;
point._loadUINT32();
point._loadQuadruplet();
return point;
}
static createByRGBA(red, green, blue, alpha) {
const point = new Point;
point.r = red | 0;
point.g = green | 0;
point.b = blue | 0;
point.a = alpha | 0;
point._loadUINT32();
point._loadQuadruplet();
return point;
}
static createByUint32(uint32) {
const point = new Point;
point.uint32 = uint32 >>> 0;
point._loadRGBA();
point._loadQuadruplet();
return point;
}
from(point) {
this.r = point.r;
this.g = point.g;
this.b = point.b;
this.a = point.a;
this.uint32 = point.uint32;
this.rgba[0] = point.r;
this.rgba[1] = point.g;
this.rgba[2] = point.b;
this.rgba[3] = point.a;
}
getLuminosity(useAlphaChannel) {
let r = this.r;
let g = this.g;
let b = this.b;
if (useAlphaChannel) {
r = Math.min(255, 255 - this.a + this.a * r / 255);
g = Math.min(255, 255 - this.a + this.a * g / 255);
b = Math.min(255, 255 - this.a + this.a * b / 255);
}
return r * 0.2126 + g * 0.7152 + b * 0.0722;
}
_loadUINT32() {
this.uint32 = (this.a << 24 | this.b << 16 | this.g << 8 | this.r) >>> 0;
}
_loadRGBA() {
this.r = this.uint32 & 255;
this.g = this.uint32 >>> 8 & 255;
this.b = this.uint32 >>> 16 & 255;
this.a = this.uint32 >>> 24 & 255;
}
_loadQuadruplet() {
this.rgba[0] = this.r;
this.rgba[1] = this.g;
this.rgba[2] = this.b;
this.rgba[3] = this.a;
}
};
var PointContainer = class {
constructor() {
__publicField(this, "_pointArray");
__publicField(this, "_width");
__publicField(this, "_height");
this._width = 0;
this._height = 0;
this._pointArray = [];
}
getWidth() {
return this._width;
}
getHeight() {
return this._height;
}
setWidth(width) {
this._width = width;
}
setHeight(height) {
this._height = height;
}
getPointArray() {
return this._pointArray;
}
clone() {
const clone3 = new PointContainer;
clone3._width = this._width;
clone3._height = this._height;
for (let i = 0, l = this._pointArray.length;i < l; i++) {
clone3._pointArray[i] = Point.createByUint32(this._pointArray[i].uint32 | 0);
}
return clone3;
}
toUint32Array() {
const l = this._pointArray.length;
const uint32Array = new Uint32Array(l);
for (let i = 0;i < l; i++) {
uint32Array[i] = this._pointArray[i].uint32;
}
return uint32Array;
}
toUint8Array() {
return new Uint8Array(this.toUint32Array().buffer);
}
static fromHTMLImageElement(img) {
const width = img.naturalWidth;
const height = img.naturalHeight;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height, 0, 0, width, height);
return PointContainer.fromHTMLCanvasElement(canvas);
}
static fromHTMLCanvasElement(canvas) {
const width = canvas.width;
const height = canvas.height;
const ctx = canvas.getContext("2d");
const imgData = ctx.getImageData(0, 0, width, height);
return PointContainer.fromImageData(imgData);
}
static fromImageData(imageData) {
const width = imageData.width;
const height = imageData.height;
return PointContainer.fromUint8Array(imageData.data, width, height);
}
static fromUint8Array(uint8Array, width, height) {
switch (Object.prototype.toString.call(uint8Array)) {
case "[object Uint8ClampedArray]":
case "[object Uint8Array]":
break;
default:
uint8Array = new Uint8Array(uint8Array);
}
const uint32Array = new Uint32Array(uint8Array.buffer);
return PointContainer.fromUint32Array(uint32Array, width, height);
}
static fromUint32Array(uint32Array, width, height) {
const container = new PointContainer;
container._width = width;
container._height = height;
for (let i = 0, l = uint32Array.length;i < l; i++) {
container._pointArray[i] = Point.createByUint32(uint32Array[i] | 0);
}
return container;
}
static fromBuffer(buffer, width, height) {
const uint32Array = new Uint32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Uint32Array.BYTES_PER_ELEMENT);
return PointContainer.fromUint32Array(uint32Array, width, height);
}
};
var hueGroups = 10;
function hueGroup(hue, segmentsNumber) {
const maxHue = 360;
const seg = maxHue / segmentsNumber;
const half = seg / 2;
for (let i = 1, mid = seg - half;i < segmentsNumber; i++, mid += seg) {
if (hue >= mid && hue < mid + seg)
return i;
}
return 0;
}
var Palette = class {
constructor() {
__publicField(this, "_pointContainer");
__publicField(this, "_pointArray", []);
__publicField(this, "_i32idx", {});
this._pointContainer = new PointContainer;
this._pointContainer.setHeight(1);
this._pointArray = this._pointContainer.getPointArray();
}
add(color) {
this._pointArray.push(color);
this._pointContainer.setWidth(this._pointArray.length);
}
has(color) {
for (let i = this._pointArray.length - 1;i >= 0; i--) {
if (color.uint32 === this._pointArray[i].uint32)
return true;
}
return false;
}
getNearestColor(colorDistanceCalculator, color) {
return this._pointArray[this._getNearestIndex(colorDistanceCalculator, color) | 0];
}
getPointContainer() {
return this._pointContainer;
}
_nearestPointFromCache(key) {
return typeof this._i32idx[key] === "number" ? this._i32idx[key] : -1;
}
_getNearestIndex(colorDistanceCalculator, point) {
let idx = this._nearestPointFromCache("" + point.uint32);
if (idx >= 0)
return idx;
let minimalDistance = Number.MAX_VALUE;
idx = 0;
for (let i = 0, l = this._pointArray.length;i < l; i++) {
const p = this._pointArray[i];
const distance2 = colorDistanceCalculator.calculateRaw(point.r, point.g, point.b, point.a, p.r, p.g, p.b, p.a);
if (distance2 < minimalDistance) {
minimalDistance = distance2;
idx = i;
}
}
this._i32idx[point.uint32] = idx;
return idx;
}
sort() {
this._i32idx = {};
this._pointArray.sort((a, b) => {
const hslA = rgb2hsl(a.r, a.g, a.b);
const hslB = rgb2hsl(b.r, b.g, b.b);
const hueA = a.r === a.g && a.g === a.b ? 0 : 1 + hueGroup(hslA.h, hueGroups);
const hueB = b.r === b.g && b.g === b.b ? 0 : 1 + hueGroup(hslB.h, hueGroups);
const hueDiff = hueB - hueA;
if (hueDiff)
return -hueDiff;
const lA = a.getLuminosity(true);
const lB = b.getLuminosity(true);
if (lB - lA !== 0)
return lB - lA;
const satDiff = (hslB.s * 100 | 0) - (hslA.s * 100 | 0);
if (satDiff)
return -satDiff;
return 0;
});
}
};
var utils_exports = {};
__export2(utils_exports, {
HueStatistics: () => HueStatistics,
Palette: () => Palette,
Point: () => Point,
PointContainer: () => PointContainer,
ProgressTracker: () => ProgressTracker,
arithmetic: () => arithmetic_exports
});
var HueGroup = class {
constructor() {
__publicField(this, "num", 0);
__publicField(this, "cols", []);
}
};
var HueStatistics = class {
constructor(numGroups, minCols) {
__publicField(this, "_numGroups");
__publicField(this, "_minCols");
__publicField(this, "_stats");
__publicField(this, "_groupsFull");
this._numGroups = numGroups;
this._minCols = minCols;
this._stats = [];
for (let i = 0;i <= numGroups; i++) {
this._stats[i] = new HueGroup;
}
this._groupsFull = 0;
}
check(i32) {
if (this._groupsFull === this._numGroups + 1) {
this.check = () => {};
}
const r = i32 & 255;
const g = i32 >>> 8 & 255;
const b = i32 >>> 16 & 255;
const hg = r === g && g === b ? 0 : 1 + hueGroup(rgb2hsl(r, g, b).h, this._numGroups);
const gr = this._stats[hg];
const min = this._minCols;
gr.num++;
if (gr.num > min) {
return;
}
if (gr.num === min) {
this._groupsFull++;
}
if (gr.num <= min) {
this._stats[hg].cols.push(i32);
}
}
injectIntoDictionary(histG) {
for (let i = 0;i <= this._numGroups; i++) {
if (this._stats[i].num <= this._minCols) {
this._stats[i].cols.forEach((col) => {
if (!histG[col]) {
histG[col] = 1;
} else {
histG[col]++;
}
});
}
}
}
injectIntoArray(histG) {
for (let i = 0;i <= this._numGroups; i++) {
if (this._stats[i].num <= this._minCols) {
this._stats[i].cols.forEach((col) => {
if (histG.indexOf(col) === -1) {
histG.push(col);
}
});
}
}
}
};
var _ProgressTracker = class {
constructor(valueRange, progressRange) {
__publicField(this, "progress");
__publicField(this, "_step");
__publicField(this, "_range");
__publicField(this, "_last");
__publicField(this, "_progressRange");
this._range = valueRange;
this._progressRange = progressRange;
this._step = Math.max(1, this._range / (_ProgressTracker.steps + 1) | 0);
this._last = -this._step;
this.progress = 0;
}
shouldNotify(current) {
if (current - this._last >= this._step) {
this._last = current;
this.progress = Math.min(this._progressRange * this._last / this._range, this._progressRange);
return true;
}
return false;
}
};
var ProgressTracker = _ProgressTracker;
__publicField(ProgressTracker, "steps", 100);
var networkBiasShift = 3;
var Neuron = class {
constructor(defaultValue) {
__publicField(this, "r");
__publicField(this, "g");
__publicField(this, "b");
__publicField(this, "a");
this.r = this.g = this.b = this.a = defaultValue;
}
toPoint() {
return Point.createByRGBA(this.r >> networkBiasShift, this.g >> networkBiasShift, this.b >> networkBiasShift, this.a >> networkBiasShift);
}
subtract(r, g, b, a) {
this.r -= r | 0;
this.g -= g | 0;
this.b -= b | 0;
this.a -= a | 0;
}
};
var _NeuQuant = class extends AbstractPaletteQuantizer {
constructor(colorDistanceCalculator, colors = 256) {
super();
__publicField(this, "_pointArray");
__publicField(this, "_networkSize");
__publicField(this, "_network");
__publicField(this, "_sampleFactor");
__publicField(this, "_radPower");
__publicField(this, "_freq");
__publicField(this, "_bias");
__publicField(this, "_distance");
this._distance = colorDistanceCalculator;
this._pointArray = [];
this._sampleFactor = 1;
this._networkSize = colors;
this._distance.setWhitePoint(255 << networkBiasShift, 255 << networkBiasShift, 255 << networkBiasShift, 255 << networkBiasShift);
}
sample(pointContainer) {
this._pointArray = this._pointArray.concat(pointContainer.getPointArray());
}
*quantize() {
this._init();
yield* this._learn();
yield {
palette: this._buildPalette(),
progress: 100
};
}
_init() {
this._freq = [];
this._bias = [];
this._radPower = [];
this._network = [];
for (let i = 0;i < this._networkSize; i++) {
this._network[i] = new Neuron((i << networkBiasShift + 8) / this._networkSize | 0);
this._freq[i] = _NeuQuant._initialBias / this._networkSize | 0;
this._bias[i] = 0;
}
}
*_learn() {
let sampleFactor = this._sampleFactor;
const pointsNumber = this._pointArray.length;
if (pointsNumber < _NeuQuant._minpicturebytes)
sampleFactor = 1;
const alphadec = 30 + (sampleFactor - 1) / 3 | 0;
const pointsToSample = pointsNumber / sampleFactor | 0;
let delta = pointsToSample / _NeuQuant._nCycles | 0;
let alpha = _NeuQuant._initAlpha;
let radius = (this._networkSize >> 3) * _NeuQuant._radiusBias;
let rad = radius >> _NeuQuant._radiusBiasShift;
if (rad <= 1)
rad = 0;
for (let i = 0;i < rad; i++) {
this._radPower[i] = alpha * ((rad * rad - i * i) * _NeuQuant._radBias / (rad * rad)) >>> 0;
}
let step;
if (pointsNumber < _NeuQuant._minpicturebytes) {
step = 1;
} else if (pointsNumber % _NeuQuant._prime1 !== 0) {
step = _NeuQuant._prime1;
} else if (pointsNumber % _NeuQuant._prime2 !== 0) {
step = _NeuQuant._prime2;
} else if (pointsNumber % _NeuQuant._prime3 !== 0) {
step = _NeuQuant._prime3;
} else {
step = _NeuQuant._prime4;
}
const tracker = new ProgressTracker(pointsToSample, 99);
for (let i = 0, pointIndex = 0;i < pointsToSample; ) {
if (tracker.shouldNotify(i)) {
yield {
progress: tracker.progress
};
}
const point = this._pointArray[pointIndex];
const b = point.b << networkBiasShift;
const g = point.g << networkBiasShift;
const r = point.r << networkBiasShift;
const a = point.a << networkBiasShift;
const neuronIndex = this._contest(b, g, r, a);
this._alterSingle(alpha, neuronIndex, b, g, r, a);
if (rad !== 0)
this._alterNeighbour(rad, neuronIndex, b, g, r, a);
pointIndex += step;
if (pointIndex >= pointsNumber)
pointIndex -= pointsNumber;
i++;
if (delta === 0)
delta = 1;
if (i % delta === 0) {
alpha -= alpha / alphadec | 0;
radius -= radius / _NeuQuant._radiusDecrease | 0;
rad = radius >> _NeuQuant._radiusBiasShift;
if (rad <= 1)
rad = 0;
for (let j = 0;j < rad; j++) {
this._radPower[j] = alpha * ((rad * rad - j * j) * _NeuQuant._radBias / (rad * rad)) >>> 0;
}
}
}
}
_buildPalette() {
const palette2 = new Palette;
this._network.forEach((neuron) => {
palette2.add(neuron.toPoint());
});
palette2.sort();
return palette2;
}
_alterNeighbour(rad, i, b, g, r, al) {
let lo = i - rad;
if (lo < -1)
lo = -1;
let hi = i + rad;
if (hi > this._networkSize)
hi = this._networkSize;
let j = i + 1;
let k = i - 1;
let m = 1;
while (j < hi || k > lo) {
const a = this._radPower[m++] / _NeuQuant._alphaRadBias;
if (j < hi) {
const p = this._network[j++];
p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));
}
if (k > lo) {
const p = this._network[k--];
p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));
}
}
}
_alterSingle(alpha, i, b, g, r, a) {
alpha /= _NeuQuant._initAlpha;
const n = this._network[i];
n.subtract(alpha * (n.r - r), alpha * (n.g - g), alpha * (n.b - b), alpha * (n.a - a));
}
_contest(b, g, r, a) {
const multiplier = 255 * 4 << networkBiasShift;
let bestd = ~(1 << 31);
let bestbiasd = bestd;
let bestpos = -1;
let bestbiaspos = bestpos;
for (let i = 0;i < this._networkSize; i++) {
const n = this._network[i];
const dist = this._distance.calculateNormalized(n, { r, g, b, a }) * multiplier | 0;
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
const biasdist = dist - (this._bias[i] >> _NeuQuant._initialBiasShift - networkBiasShift);
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
const betafreq = this._freq[i] >> _NeuQuant._betaShift;
this._freq[i] -= betafreq;
this._bias[i] += betafreq << _NeuQuant._gammaShift;
}
this._freq[bestpos] += _NeuQuant._beta;
this._bias[bestpos] -= _NeuQuant._betaGamma;
return bestbiaspos;
}
};
var NeuQuant = _NeuQuant;
__publicField(NeuQuant, "_prime1", 499);
__publicField(NeuQuant, "_prime2", 491);
__publicField(NeuQuant, "_prime3", 487);
__publicField(NeuQuant, "_prime4", 503);
__publicField(NeuQuant, "_minpicturebytes", _NeuQuant._prime4);
__publicField(NeuQuant, "_nCycles", 100);
__publicField(NeuQuant, "_initialBiasShift", 16);
__publicField(NeuQuant, "_initialBias", 1 << _NeuQuant._initialBiasShift);
__publicField(NeuQuant, "_gammaShift", 10);
__publicField(NeuQuant, "_betaShift", 10);
__publicField(NeuQuant, "_beta", _NeuQuant._initialBias >> _NeuQuant._betaShift);
__publicField(NeuQuant, "_betaGamma", _NeuQuant._initialBias << _NeuQuant._gammaShift - _NeuQuant._betaShift);
__publicField(NeuQuant, "_radiusBiasShift", 6);
__publicField(NeuQuant, "_radiusBias", 1 << _NeuQuant._radiusBiasShift);
__publicField(NeuQuant, "_radiusDecrease", 30);
__publicField(NeuQuant, "_alphaBiasShift", 10);
__publicField(NeuQuant, "_initAlpha", 1 << _NeuQuant._alphaBiasShift);
__publicField(NeuQuant, "_radBiasShift", 8);
__publicField(NeuQuant, "_radBias", 1 << _NeuQuant._radBiasShift);
__publicField(NeuQuant, "_alphaRadBiasShift", _NeuQuant._alphaBiasShift + _NeuQuant._radBiasShift);
__publicField(NeuQuant, "_alphaRadBias", 1 << _NeuQuant._alphaRadBiasShift);
var networkBiasShift2 = 3;
var NeuronFloat = class {
constructor(defaultValue) {
__publicField(this, "r");
__publicField(this, "g");
__publicField(this, "b");
__publicField(this, "a");
this.r = this.g = this.b = this.a = defaultValue;
}
toPoint() {
return Point.createByRGBA(this.r >> networkBiasShift2, this.g >> networkBiasShift2, this.b >> networkBiasShift2, this.a >> networkBiasShift2);
}
subtract(r, g, b, a) {
this.r -= r;
this.g -= g;
this.b -= b;
this.a -= a;
}
};
var _NeuQuantFloat = class extends AbstractPaletteQuantizer {
constructor(colorDistanceCalculator, colors = 256) {
super();
__publicField(this, "_pointArray");
__publicField(this, "_networkSize");
__publicField(this, "_network");
__publicField(this, "_sampleFactor");
__publicField(this, "_radPower");
__publicField(this, "_freq");
__publicField(this, "_bias");
__publicField(this, "_distance");
this._distance = colorDistanceCalculator;
this._pointArray = [];
this._sampleFactor = 1;
this._networkSize = colors;
this._distance.setWhitePoint(255 << networkBiasShift2, 255 << networkBiasShift2, 255 << networkBiasShift2, 255 << networkBiasShift2);
}
sample(pointContainer) {
this._pointArray = this._pointArray.concat(pointContainer.getPointArray());
}
*quantize() {
this._init();
yield* this._learn();
yield {
palette: this._buildPalette(),
progress: 100
};
}
_init() {
this._freq = [];
this._bias = [];
this._radPower = [];
this._network = [];
for (let i = 0;i < this._networkSize; i++) {
this._network[i] = new NeuronFloat((i << networkBiasShift2 + 8) / this._networkSize);
this._freq[i] = _NeuQuantFloat._initialBias / this._networkSize;
this._bias[i] = 0;
}
}
*_learn() {
let sampleFactor = this._sampleFactor;
const pointsNumber = this._pointArray.length;
if (pointsNumber < _NeuQuantFloat._minpicturebytes)
sampleFactor = 1;
const alphadec = 30 + (sampleFactor - 1) / 3;
const pointsToSample = pointsNumber / sampleFactor;
let delta = pointsToSample / _NeuQuantFloat._nCycles | 0;
let alpha = _NeuQuantFloat._initAlpha;
let radius = (this._networkSize >> 3) * _NeuQuantFloat._radiusBias;
let rad = radius >> _NeuQuantFloat._radiusBiasShift;
if (rad <= 1)
rad = 0;
for (let i = 0;i < rad; i++) {
this._radPower[i] = alpha * ((rad * rad - i * i) * _NeuQuantFloat._radBias / (rad * rad));
}
let step;
if (pointsNumber < _NeuQuantFloat._minpicturebytes) {
step = 1;
} else if (pointsNumber % _NeuQuantFloat._prime1 !== 0) {
step = _NeuQuantFloat._prime1;
} else if (pointsNumber % _NeuQuantFloat._prime2 !== 0) {
step = _NeuQuantFloat._prime2;
} else if (pointsNumber % _NeuQuantFloat._prime3 !== 0) {
step = _NeuQuantFloat._prime3;
} else {
step = _NeuQuantFloat._prime4;
}
const tracker = new ProgressTracker(pointsToSample, 99);
for (let i = 0, pointIndex = 0;i < pointsToSample; ) {
if (tracker.shouldNotify(i)) {
yield {
progress: tracker.progress
};
}
const point = this._pointArray[pointIndex];
const b = point.b << networkBiasShift2;
const g = point.g << networkBiasShift2;
const r = point.r << networkBiasShift2;
const a = point.a << networkBiasShift2;
const neuronIndex = this._contest(b, g, r, a);
this._alterSingle(alpha, neuronIndex, b, g, r, a);
if (rad !== 0)
this._alterNeighbour(rad, neuronIndex, b, g, r, a);
pointIndex += step;
if (pointIndex >= pointsNumber)
pointIndex -= pointsNumber;
i++;
if (delta === 0)
delta = 1;
if (i % delta === 0) {
alpha -= alpha / alphadec;
radius -= radius / _NeuQuantFloat._radiusDecrease;
rad = radius >> _NeuQuantFloat._radiusBiasShift;
if (rad <= 1)
rad = 0;
for (let j = 0;j < rad; j++) {
this._radPower[j] = alpha * ((rad * rad - j * j) * _NeuQuantFloat._radBias / (rad * rad));
}
}
}
}
_buildPalette() {
const palette2 = new Palette;
this._network.forEach((neuron) => {
palette2.add(neuron.toPoint());
});
palette2.sort();
return palette2;
}
_alterNeighbour(rad, i, b, g, r, al) {
let lo = i - rad;
if (lo < -1)
lo = -1;
let hi = i + rad;
if (hi > this._networkSize)
hi = this._networkSize;
let j = i + 1;
let k = i - 1;
let m = 1;
while (j < hi || k > lo) {
const a = this._radPower[m++] / _NeuQuantFloat._alphaRadBias;
if (j < hi) {
const p = this._network[j++];
p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));
}
if (k > lo) {
const p = this._network[k--];
p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));
}
}
}
_alterSingle(alpha, i, b, g, r, a) {
alpha /= _NeuQuantFloat._initAlpha;
const n = this._network[i];
n.subtract(alpha * (n.r - r), alpha * (n.g - g), alpha * (n.b - b), alpha * (n.a - a));
}
_contest(b, g, r, al) {
const multiplier = 255 * 4 << networkBiasShift2;
let bestd = ~(1 << 31);
let bestbiasd = bestd;
let bestpos = -1;
let bestbiaspos = bestpos;
for (let i = 0;i < this._networkSize; i++) {
const n = this._network[i];
const dist = this._distance.calculateNormalized(n, { r, g, b, a: al }) * multiplier;
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
const biasdist = dist - (this._bias[i] >> _NeuQuantFloat._initialBiasShift - networkBiasShift2);
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
const betafreq = this._freq[i] >> _NeuQuantFloat._betaShift;
this._freq[i] -= betafreq;
this._bias[i] += betafreq << _NeuQuantFloat._gammaShift;
}
this._freq[bestpos] += _NeuQuantFloat._beta;
this._bias[bestpos] -= _NeuQuantFloat._betaGamma;
return bestbiaspos;
}
};
var NeuQuantFloat = _NeuQuantFloat;
__publicField(NeuQuantFloat, "_prime1", 499);
__publicField(NeuQuantFloat, "_prime2", 491);
__publicField(NeuQuantFloat, "_prime3", 487);
__publicField(NeuQuantFloat, "_prime4", 503);
__publicField(NeuQuantFloat, "_minpicturebytes", _NeuQuantFloat._prime4);
__publicField(NeuQuantFloat, "_nCycles", 100);
__publicField(NeuQuantFloat, "_initialBiasShift", 16);
__publicField(NeuQuantFloat, "_initialBias", 1 << _NeuQuantFloat._initialBiasShift);
__publicField(NeuQuantFloat, "_gammaShift", 10);
__publicField(NeuQuantFloat, "_betaShift", 10);
__publicField(NeuQuantFloat, "_beta", _NeuQuantFloat._initialBias >> _NeuQuantFloat._betaShift);
__publicField(NeuQuantFloat, "_betaGamma", _NeuQuantFloat._initialBias << _NeuQuantFloat._gammaShift - _NeuQuantFloat._betaShift);
__publicField(NeuQuantFloat, "_radiusBiasShift", 6);
__publicField(NeuQuantFloat, "_radiusBias", 1 << _NeuQuantFloat._radiusBiasShift);
__publicField(NeuQuantFloat, "_radiusDecrease", 30);
__publicField(NeuQuantFloat, "_alphaBiasShift", 10);
__publicField(NeuQuantFloat, "_initAlpha", 1 << _NeuQuantFloat._alphaBiasShift);
__publicField(NeuQuantFloat, "_radBiasShift", 8);
__publicField(NeuQuantFloat, "_radBias", 1 << _NeuQuantFloat._radBiasShift);
__publicField(NeuQuantFloat, "_alphaRadBiasShift", _NeuQuantFloat._alphaBiasShift + _NeuQuantFloat._radBiasShift);
__publicField(NeuQuantFloat, "_alphaRadBias", 1 << _NeuQuantFloat._alphaRadBiasShift);
var _ColorHistogram = class {
constructor(method, colors) {
__publicField(this, "_method");
__publicField(this, "_hueStats");
__publicField(this, "_histogram");
__publicField(this, "_initColors");
__publicField(this, "_minHueCols");
this._method = method;
this._minHueCols = colors << 2;
this._initColors = colors << 2;
this._hueStats = new HueStatistics(_ColorHistogram._hueGroups, this._minHueCols);
this._histogram = /* @__PURE__ */ Object.create(null);
}
sample(pointContainer) {
switch (this._method) {
case 1:
this._colorStats1D(pointContainer);
break;
case 2:
this._colorStats2D(pointContainer);
break;
}
}
getImportanceSortedColorsIDXI32() {
const sorted = stableSort(Object.keys(this._histogram), (a, b) => this._histogram[b] - this._histogram[a]);
if (sorted.length === 0) {
return [];
}
let idxi32;
switch (this._method) {
case 1:
const initialColorsLimit = Math.min(sorted.length, this._initColors);
const last = sorted[initialColorsLimit - 1];
const freq = this._histogram[last];
idxi32 = sorted.slice(0, initialColorsLimit);
let pos = initialColorsLimit;
const len = sorted.length;
while (pos < len && this._histogram[sorted[pos]] === freq) {
idxi32.push(sorted[pos++]);
}
this._hueStats.injectIntoArray(idxi32);
break;
case 2:
idxi32 = sorted;
break;
default:
throw new Error("Incorrect method");
}
return idxi32.map((v) => +v);
}
_colorStats1D(pointContainer) {
const histG = this._histogram;
const pointArray = pointContainer.getPointArray();
const len = pointArray.length;
for (let i = 0;i < len; i++) {
const col = pointArray[i].uint32;
this._hueStats.check(col);
if (col in histG) {
histG[col]++;
} else {
histG[col] = 1;
}
}
}
_colorStats2D(pointContainer) {
const width = pointContainer.getWidth();
const height = pointContainer.getHeight();
const pointArray = pointContainer.getPointArray();
const boxW = _ColorHistogram._boxSize[0];
const boxH = _ColorHistogram._boxSize[1];
const area = boxW * boxH;
const boxes = this._makeBoxes(width, height, boxW, boxH);
const histG = this._histogram;
boxes.forEach((box) => {
let effc = Math.round(box.w * box.h / area) * _ColorHistogram._boxPixels;
if (effc < 2)
effc = 2;
const histL = {};
this._iterateBox(box, width, (i) => {
const col = pointArray[i].uint32;
this._hueStats.check(col);
if (col in histG) {
histG[col]++;
} else if (col in histL) {
if (++histL[col] >= effc) {
histG[col] = histL[col];
}
} else {
histL[col] = 1;
}
});
});
this._hueStats.injectIntoDictionary(histG);
}
_iterateBox(bbox, wid, fn) {
const b = bbox;
const i0 = b.y * wid + b.x;
const i1 = (b.y + b.h - 1) * wid + (b.x + b.w - 1);
const incr = wid - b.w + 1;
let cnt = 0;
let i = i0;
do {
fn.call(this, i);
i += ++cnt % b.w === 0 ? incr : 1;
} while (i <= i1);
}
_makeBoxes(width, height, stepX, stepY) {
const wrem = width % stepX;
const hrem = height % stepY;
const xend = width - wrem;
const yend = height - hrem;
const boxesArray = [];
for (let y2 = 0;y2 < height; y2 += stepY) {
for (let x2 = 0;x2 < width; x2 += stepX) {
boxesArray.push({
x: x2,
y: y2,
w: x2 === xend ? wrem : stepX,
h: y2 === yend ? hrem : stepY
});
}
}
return boxesArray;
}
};
var ColorHistogram = _ColorHistogram;
__publicField(ColorHistogram, "_boxSize", [64, 64]);
__publicField(ColorHistogram, "_boxPixels", 2);
__publicField(ColorHistogram, "_hueGroups", 10);
var RemovedColor = class {
constructor(index, color, distance2) {
__publicField(this, "index");
__publicField(this, "color");
__publicField(this, "distance");
this.index = index;
this.color = color;
this.distance = distance2;
}
};
var RGBQuant = class extends AbstractPaletteQuantizer {
constructor(colorDistanceCalculator, colors = 256, method = 2) {
super();
__publicField(this, "_colors");
__publicField(this, "_initialDistance");
__publicField(this, "_distanceIncrement");
__publicField(this, "_histogram");
__publicField(this, "_distance");
this._distance = colorDistanceCalculator;
this._colors = colors;
this._histogram = new ColorHistogram(method, colors);
this._initialDistance = 0.01;
this._distanceIncrement = 0.005;
}
sample(image2) {
this._histogram.sample(image2);
}
*quantize() {
const idxi32 = this._histogram.getImportanceSortedColorsIDXI32();
if (idxi32.length === 0) {
throw new Error("No colors in image");
}
yield* this._buildPalette(idxi32);
}
*_buildPalette(idxi32) {
const palette2 = new Palette;
const colorArray = palette2.getPointContainer().getPointArray();
const usageArray = new Array(idxi32.length);
for (let i = 0;i < idxi32.length; i++) {
colorArray.push(Point.createByUint32(idxi32[i]));
usageArray[i] = 1;
}
const len = colorArray.length;
const memDist = [];
let palLen = len;
let thold = this._initialDistance;
const tracker = new ProgressTracker(palLen - this._colors, 99);
while (palLen > this._colors) {
memDist.length = 0;
for (let i = 0;i < len; i++) {
if (tracker.shouldNotify(len - palLen)) {
yield {
progress: tracker.progress
};
}
if (usageArray[i] === 0)
continue;
const pxi = colorArray[i];
for (let j = i + 1;j < len; j++) {
if (usageArray[j] === 0)
continue;
const pxj = colorArray[j];
const dist = this._distance.calculateNormalized(pxi, pxj);
if (dist < thold) {
memDist.push(new RemovedColor(j, pxj, dist));
usageArray[j] = 0;
palLen--;
}
}
}
thold += palLen > this._colors * 3 ? this._initialDistance : this._distanceIncrement;
}
if (palLen < this._colors) {
stableSort(memDist, (a, b) => b.distance - a.distance);
let k = 0;
while (palLen < this._colors && k < memDist.length) {
const removedColor = memDist[k];
usageArray[removedColor.index] = 1;
palLen++;
k++;
}
}
let colors = colorArray.length;
for (let colorIndex = colors - 1;colorIndex >= 0; colorIndex--) {
if (usageArray[colorIndex] === 0) {
if (colorIndex !== colors - 1) {
colorArray[colorIndex] = colorArray[colors - 1];
}
--colors;
}
}
colorArray.length = colors;
palette2.sort();
yield {
palette: palette2,
progress: 100
};
}
};
function createArray1D(dimension1) {
const a = [];
for (let k = 0;k < dimension1; k++) {
a[k] = 0;
}
return a;
}
function createArray4D(dimension1, dimension2, dimension3, dimension4) {
const a = new Array(dimension1);
for (let i = 0;i < dimension1; i++) {
a[i] = new Array(dimension2);
for (let j = 0;j < dimension2; j++) {
a[i][j] = new Array(dimension3);
for (let k = 0;k < dimension3; k++) {
a[i][j][k] = new Array(dimension4);
for (let l = 0;l < dimension4; l++) {
a[i][j][k][l] = 0;
}
}
}
}
return a;
}
function createArray3D(dimension1, dimension2, dimension3) {
const a = new Array(dimension1);
for (let i = 0;i < dimension1; i++) {
a[i] = new Array(dimension2);
for (let j = 0;j < dimension2; j++) {
a[i][j] = new Array(dimension3);
for (let k = 0;k < dimension3; k++) {
a[i][j][k] = 0;
}
}
}
return a;
}
function fillArray3D(a, dimension1, dimension2, dimension3, value) {
for (let i = 0;i < dimension1; i++) {
a[i] = [];
for (let j = 0;j < dimension2; j++) {
a[i][j] = [];
for (let k = 0;k < dimension3; k++) {
a[i][j][k] = value;
}
}
}
}
function fillArray1D(a, dimension1, value) {
for (let i = 0;i < dimension1; i++) {
a[i] = value;
}
}
var WuColorCube = class {
constructor() {
__publicField(this, "redMinimum");
__publicField(this, "redMaximum");
__publicField(this, "greenMinimum");
__publicField(this, "greenMaximum");
__publicField(this, "blueMinimum");
__publicField(this, "blueMaximum");
__publicField(this, "volume");
__publicField(this, "alphaMinimum");
__publicField(this, "alphaMaximum");
}
};
var _WuQuant = class extends AbstractPaletteQuantizer {
constructor(colorDistanceCalculator, colors = 256, significantBitsPerChannel = 5) {
super();
__publicField(this, "_reds");
__publicField(this, "_greens");
__publicField(this, "_blues");
__publicField(this, "_alphas");
__publicField(this, "_sums");
__publicField(this, "_weights");
__publicField(this, "_momentsRed");
__publicField(this, "_momentsGreen");
__publicField(this, "_momentsBlue");
__publicField(this, "_momentsAlpha");
__publicField(this, "_moments");
__publicField(this, "_table");
__publicField(this, "_pixels");
__publicField(this, "_cubes");
__publicField(this, "_colors");
__publicField(this, "_significantBitsPerChannel");
__publicField(this, "_maxSideIndex");
__publicField(this, "_alphaMaxSideIndex");
__publicField(this, "_sideSize");
__publicField(this, "_alphaSideSize");
__publicField(this, "_distance");
this._distance = colorDistanceCalculator;
this._setQuality(significantBitsPerChannel);
this._initialize(colors);
}
sample(image2) {
const pointArray = image2.getPointArray();
for (let i = 0, l = pointArray.length;i < l; i++) {
this._addColor(pointArray[i]);
}
this._pixels = this._pixels.concat(pointArray);
}
*quantize() {
yield* this._preparePalette();
const palette2 = new Palette;
for (let paletteIndex = 0;paletteIndex < this._colors; paletteIndex++) {
if (this._sums[paletteIndex] > 0) {
const sum = this._sums[paletteIndex];
const r = this._reds[paletteIndex] / sum;
const g = this._greens[paletteIndex] / sum;
const b = this._blues[paletteIndex] / sum;
const a = this._alphas[paletteIndex] / sum;
const color = Point.createByRGBA(r | 0, g | 0, b | 0, a | 0);
palette2.add(color);
}
}
palette2.sort();
yield {
palette: palette2,
progress: 100
};
}
*_preparePalette() {
yield* this._calculateMoments();
let next = 0;
const volumeVariance = createArray1D(this._colors);
for (let cubeIndex = 1;cubeIndex < this._colors; ++cubeIndex) {
if (this._cut(this._cubes[next], this._cubes[cubeIndex])) {
volumeVariance[next] = this._cubes[next].volume > 1 ? this._calculateVariance(this._cubes[next]) : 0;
volumeVariance[cubeIndex] = this._cubes[cubeIndex].volume > 1 ? this._calculateVariance(this._cubes[cubeIndex]) : 0;
} else {
volumeVariance[next] = 0;
cubeIndex--;
}
next = 0;
let temp = volumeVariance[0];
for (let index = 1;index <= cubeIndex; ++index) {
if (volumeVariance[index] > temp) {
temp = volumeVariance[index];
next = index;
}
}
if (temp <= 0) {
this._colors = cubeIndex + 1;
break;
}
}
const lookupRed = [];
const lookupGreen = [];
const lookupBlue = [];
const lookupAlpha = [];
for (let k = 0;k < this._colors; ++k) {
const weight = _WuQuant._volume(this._cubes[k], this._weights);
if (weight > 0) {
lookupRed[k] = _WuQuant._volume(this._cubes[k], this._momentsRed) / weight | 0;
lookupGreen[k] = _WuQuant._volume(this._cubes[k], this._momentsGreen) / weight | 0;
lookupBlue[k] = _WuQuant._volume(this._cubes[k], this._momentsBlue) / weight | 0;
lookupAlpha[k] = _WuQuant._volume(this._cubes[k], this._momentsAlpha) / weight | 0;
} else {
lookupRed[k] = 0;
lookupGreen[k] = 0;
lookupBlue[k] = 0;
lookupAlpha[k] = 0;
}
}
this._reds = createArray1D(this._colors + 1);
this._greens = createArray1D(this._colors + 1);
this._blues = createArray1D(this._colors + 1);
this._alphas = createArray1D(this._colors + 1);
this._sums = createArray1D(this._colors + 1);
for (let index = 0, l = this._pixels.length;index < l; index++) {
const color = this._pixels[index];
const match = -1;
let bestMatch = match;
let bestDistance = Number.MAX_VALUE;
for (let lookup = 0;lookup < this._colors; lookup++) {
const foundRed = lookupRed[lookup];
const foundGreen = lookupGreen[lookup];
const foundBlue = lookupBlue[lookup];
const foundAlpha = lookupAlpha[lookup];
const distance2 = this._distance.calculateRaw(foundRed, foundGreen, foundBlue, foundAlpha, color.r, color.g, color.b, color.a);
if (distance2 < bestDistance) {
bestDistance = distance2;
bestMatch = lookup;
}
}
this._reds[bestMatch] += color.r;
this._greens[bestMatch] += color.g;
this._blues[bestMatch] += color.b;
this._alphas[bestMatch] += color.a;
this._sums[bestMatch]++;
}
}
_addColor(color) {
const bitsToRemove = 8 - this._significantBitsPerChannel;
const indexRed = (color.r >> bitsToRemove) + 1;
const indexGreen = (color.g >> bitsToRemove) + 1;
const indexBlue = (color.b >> bitsToRemove) + 1;
const indexAlpha = (color.a >> bitsToRemove) + 1;
this._weights[indexAlpha][indexRed][indexGreen][indexBlue]++;
this._momentsRed[indexAlpha][indexRed][indexGreen][indexBlue] += color.r;
this._momentsGreen[indexAlpha][indexRed][indexGreen][indexBlue] += color.g;
this._momentsBlue[indexAlpha][indexRed][indexGreen][indexBlue] += color.b;
this._momentsAlpha[indexAlpha][indexRed][indexGreen][indexBlue] += color.a;
this._moments[indexAlpha][indexRed][indexGreen][indexBlue] += this._table[color.r] + this._table[color.g] + this._table[color.b] + this._table[color.a];
}
*_calculateMoments() {
const area = [];
const areaRed = [];
const areaGreen = [];
const areaBlue = [];
const areaAlpha = [];
const area2 = [];
const xarea = createArray3D(this._sideSize, this._sideSize, this._sideSize);
const xareaRed = createArray3D(this._sideSize, this._sideSize, this._sideSize);
const xareaGreen = createArray3D(this._sideSize, this._sideSize, this._sideSize);
const xareaBlue = createArray3D(this._sideSize, this._sideSize, this._sideSize);
const xareaAlpha = createArray3D(this._sideSize, this._sideSize, this._sideSize);
const xarea2 = createArray3D(this._sideSize, this._sideSize, this._sideSize);
let trackerProgress = 0;
const tracker = new ProgressTracker(this._alphaMaxSideIndex * this._maxSideIndex, 99);
for (let alphaIndex = 1;alphaIndex <= this._alphaMaxSideIndex; ++alphaIndex) {
fillArray3D(xarea, this._sideSize, this._sideSize, this._sideSize, 0);
fillArray3D(xareaRed, this._sideSize, this._sideSize, this._sideSize, 0);
fillArray3D(xareaGreen, this._sideSize, this._sideSize, this._sideSize, 0);
fillArray3D(xareaBlue, this._sideSize, this._sideSize, this._sideSize, 0);
fillArray3D(xareaAlpha, this._sideSize, this._sideSize, this._sideSize, 0);
fillArray3D(xarea2, this._sideSize, this._sideSize, this._sideSize, 0);
for (let redIndex = 1;redIndex <= this._maxSideIndex; ++redIndex, ++trackerProgress) {
if (tracker.shouldNotify(trackerProgress)) {
yield {
progress: tracker.progress
};
}
fillArray1D(area, this._sideSize, 0);
fillArray1D(areaRed, this._sideSize, 0);
fillArray1D(areaGreen, this._sideSize, 0);
fillArray1D(areaBlue, this._sideSize, 0);
fillArray1D(areaAlpha, this._sideSize, 0);
fillArray1D(area2, this._sideSize, 0);
for (let greenIndex = 1;greenIndex <= this._maxSideIndex; ++greenIndex) {
let line = 0;
let lineRed = 0;
let lineGreen = 0;
let lineBlue = 0;
let lineAlpha = 0;
let line2 = 0;
for (let blueIndex = 1;blueIndex <= this._maxSideIndex; ++blueIndex) {
line += this._weights[alphaIndex][redIndex][greenIndex][blueIndex];
lineRed += this._momentsRed[alphaIndex][redIndex][greenIndex][blueIndex];
lineGreen += this._momentsGreen[alphaIndex][redIndex][greenIndex][blueIndex];
lineBlue += this._momentsBlue[alphaIndex][redIndex][greenIndex][blueIndex];
lineAlpha += this._momentsAlpha[alphaIndex][redIndex][greenIndex][blueIndex];
line2 += this._moments[alphaIndex][redIndex][greenIndex][blueIndex];
area[blueIndex] += line;
areaRed[blueIndex] += lineRed;
areaGreen[blueIndex] += lineGreen;
areaBlue[blueIndex] += lineBlue;
areaAlpha[blueIndex] += lineAlpha;
area2[blueIndex] += line2;
xarea[redIndex][greenIndex][blueIndex] = xarea[redIndex - 1][greenIndex][blueIndex] + area[blueIndex];
xareaRed[redIndex][greenIndex][blueIndex] = xareaRed[redIndex - 1][greenIndex][blueIndex] + areaRed[blueIndex];
xareaGreen[redIndex][greenIndex][blueIndex] = xareaGreen[redIndex - 1][greenIndex][blueIndex] + areaGreen[blueIndex];
xareaBlue[redIndex][greenIndex][blueIndex] = xareaBlue[redIndex - 1][greenIndex][blueIndex] + areaBlue[blueIndex];
xareaAlpha[redIndex][greenIndex][blueIndex] = xareaAlpha[redIndex - 1][greenIndex][blueIndex] + areaAlpha[blueIndex];
xarea2[redIndex][greenIndex][blueIndex] = xarea2[redIndex - 1][greenIndex][blueIndex] + area2[blueIndex];
this._weights[alphaIndex][redIndex][greenIndex][blueIndex] = this._weights[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xarea[redIndex][greenIndex][blueIndex];
this._momentsRed[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsRed[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaRed[redIndex][greenIndex][blueIndex];
this._momentsGreen[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsGreen[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaGreen[redIndex][greenIndex][blueIndex];
this._momentsBlue[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsBlue[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaBlue[redIndex][greenIndex][blueIndex];
this._momentsAlpha[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsAlpha[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaAlpha[redIndex][greenIndex][blueIndex];
this._moments[alphaIndex][redIndex][greenIndex][blueIndex] = this._moments[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xarea2[redIndex][greenIndex][blueIndex];
}
}
}
}
}
static _volumeFloat(cube, moment) {
return moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
}
static _volume(cube, moment) {
return _WuQuant._volumeFloat(cube, moment) | 0;
}
static _top(cube, direction, position, moment) {
let result;
switch (direction) {
case _WuQuant._alpha:
result = moment[position][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] - moment[position][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] - moment[position][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] + moment[position][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (moment[position][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] - moment[position][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] - moment[position][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[position][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
break;
case _WuQuant._red:
result = moment[cube.alphaMaximum][position][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMaximum][position][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMinimum][position][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMinimum][position][cube.greenMinimum][cube.blueMaximum] - (moment[cube.alphaMaximum][position][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMaximum][position][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMinimum][position][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][position][cube.greenMinimum][cube.blueMinimum]);
break;
case _WuQuant._green:
result = moment[cube.alphaMaximum][cube.redMaximum][position][cube.blueMaximum] - moment[cube.alphaMaximum][cube.redMinimum][position][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMaximum][position][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][position][cube.blueMaximum] - (moment[cube.alphaMaximum][cube.redMaximum][position][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMinimum][position][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMaximum][position][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][position][cube.blueMinimum]);
break;
case _WuQuant._blue:
result = moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][position] - moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][position] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][position] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][position] - (moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][position] - moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][position] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][position] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][position]);
break;
default:
throw new Error("impossible");
}
return result | 0;
}
static _bottom(cube, direction, moment) {
switch (direction) {
case _WuQuant._alpha:
return -moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (-moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
case _WuQuant._red:
return -moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (-moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
case _WuQuant._green:
return -moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (-moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
case _WuQuant._blue:
return -moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] - (-moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
default:
return 0;
}
}
_calculateVariance(cube) {
const volumeRed = _WuQuant._volume(cube, this._momentsRed);
const volumeGreen = _WuQuant._volume(cube, this._momentsGreen);
const volumeBlue = _WuQuant._volume(cube, this._momentsBlue);
const volumeAlpha = _WuQuant._volume(cube, this._momentsAlpha);
const volumeMoment = _WuQuant._volumeFloat(cube, this._moments);
const volumeWeight = _WuQuant._volume(cube, this._weights);
const distance2 = volumeRed * volumeRed + volumeGreen * volumeGreen + volumeBlue * volumeBlue + volumeAlpha * volumeAlpha;
return volumeMoment - distance2 / volumeWeight;
}
_maximize(cube, direction, first, last, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight) {
const bottomRed = _WuQuant._bottom(cube, direction, this._momentsRed) | 0;
const bottomGreen = _WuQuant._bottom(cube, direction, this._momentsGreen) | 0;
const bottomBlue = _WuQuant._bottom(cube, direction, this._momentsBlue) | 0;
const bottomAlpha = _WuQuant._bottom(cube, direction, this._momentsAlpha) | 0;
const bottomWeight = _WuQuant._bottom(cube, direction, this._weights) | 0;
let result = 0;
let cutPosition = -1;
for (let position = first;position < last; ++position) {
let halfRed = bottomRed + _WuQuant._top(cube, direction, position, this._momentsRed);
let halfGreen = bottomGreen + _WuQuant._top(cube, direction, position, this._momentsGreen);
let halfBlue = bottomBlue + _WuQuant._top(cube, direction, position, this._momentsBlue);
let halfAlpha = bottomAlpha + _WuQuant._top(cube, direction, position, this._momentsAlpha);
let halfWeight = bottomWeight + _WuQuant._top(cube, direction, position, this._weights);
if (halfWeight !== 0) {
let halfDistance = halfRed * halfRed + halfGreen * halfGreen + halfBlue * halfBlue + halfAlpha * halfAlpha;
let temp = halfDistance / halfWeight;
halfRed = wholeRed - halfRed;
halfGreen = wholeGreen - halfGreen;
halfBlue = wholeBlue - halfBlue;
halfAlpha = wholeAlpha - halfAlpha;
halfWeight = wholeWeight - halfWeight;
if (halfWeight !== 0) {
halfDistance = halfRed * halfRed + halfGreen * halfGreen + halfBlue * halfBlue + halfAlpha * halfAlpha;
temp += halfDistance / halfWeight;
if (temp > result) {
result = temp;
cutPosition = position;
}
}
}
}
return { max: result, position: cutPosition };
}
_cut(first, second) {
let direction;
const wholeRed = _WuQuant._volume(first, this._momentsRed);
const wholeGreen = _WuQuant._volume(first, this._momentsGreen);
const wholeBlue = _WuQuant._volume(first, this._momentsBlue);
const wholeAlpha = _WuQuant._volume(first, this._momentsAlpha);
const wholeWeight = _WuQuant._volume(first, this._weights);
const red = this._maximize(first, _WuQuant._red, first.redMinimum + 1, first.redMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);
const green = this._maximize(first, _WuQuant._green, first.greenMinimum + 1, first.greenMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);
const blue = this._maximize(first, _WuQuant._blue, first.blueMinimum + 1, first.blueMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);
const alpha = this._maximize(first, _WuQuant._alpha, first.alphaMinimum + 1, first.alphaMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);
if (alpha.max >= red.max && alpha.max >= green.max && alpha.max >= blue.max) {
direction = _WuQuant._alpha;
if (alpha.position < 0)
return false;
} else if (red.max >= alpha.max && red.max >= green.max && red.max >= blue.max) {
direction = _WuQuant._red;
} else if (green.max >= alpha.max && green.max >= red.max && green.max >= blue.max) {
direction = _WuQuant._green;
} else {
direction = _WuQuant._blue;
}
second.redMaximum = first.redMaximum;
second.greenMaximum = first.greenMaximum;
second.blueMaximum = first.blueMaximum;
second.alphaMaximum = first.alphaMaximum;
switch (direction) {
case _WuQuant._red:
second.redMinimum = first.redMaximum = red.position;
second.greenMinimum = first.greenMinimum;
second.blueMinimum = first.blueMinimum;
second.alphaMinimum = first.alphaMinimum;
break;
case _WuQuant._green:
second.greenMinimum = first.greenMaximum = green.position;
second.redMinimum = first.redMinimum;
second.blueMinimum = first.blueMinimum;
second.alphaMinimum = first.alphaMinimum;
break;
case _WuQuant._blue:
second.blueMinimum = first.blueMaximum = blue.position;
second.redMinimum = first.redMinimum;
second.greenMinimum = first.greenMinimum;
second.alphaMinimum = first.alphaMinimum;
break;
case _WuQuant._alpha:
second.alphaMinimum = first.alphaMaximum = alpha.position;
second.blueMinimum = first.blueMinimum;
second.redMinimum = first.redMinimum;
second.greenMinimum = first.greenMinimum;
break;
}
first.volume = (first.redMaximum - first.redMinimum) * (first.greenMaximum - first.greenMinimum) * (first.blueMaximum - first.blueMinimum) * (first.alphaMaximum - first.alphaMinimum);
second.volume = (second.redMaximum - second.redMinimum) * (second.greenMaximum - second.greenMinimum) * (second.blueMaximum - second.blueMinimum) * (second.alphaMaximum - second.alphaMinimum);
return true;
}
_initialize(colors) {
this._colors = colors;
this._cubes = [];
for (let cubeIndex = 0;cubeIndex < colors; cubeIndex++) {
this._cubes[cubeIndex] = new WuColorCube;
}
this._cubes[0].redMinimum = 0;
this._cubes[0].greenMinimum = 0;
this._cubes[0].blueMinimum = 0;
this._cubes[0].alphaMinimum = 0;
this._cubes[0].redMaximum = this._maxSideIndex;
this._cubes[0].greenMaximum = this._maxSideIndex;
this._cubes[0].blueMaximum = this._maxSideIndex;
this._cubes[0].alphaMaximum = this._alphaMaxSideIndex;
this._weights = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._momentsRed = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._momentsGreen = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._momentsBlue = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._momentsAlpha = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._moments = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._table = [];
for (let tableIndex = 0;tableIndex < 256; ++tableIndex) {
this._table[tableIndex] = tableIndex * tableIndex;
}
this._pixels = [];
}
_setQuality(significantBitsPerChannel = 5) {
this._significantBitsPerChannel = significantBitsPerChannel;
this._maxSideIndex = 1 << this._significantBitsPerChannel;
this._alphaMaxSideIndex = this._maxSideIndex;
this._sideSize = this._maxSideIndex + 1;
this._alphaSideSize = this._alphaMaxSideIndex + 1;
}
};
var WuQuant = _WuQuant;
__publicField(WuQuant, "_alpha", 3);
__publicField(WuQuant, "_red", 2);
__publicField(WuQuant, "_green", 1);
__publicField(WuQuant, "_blue", 0);
var image_exports = {};
__export2(image_exports, {
AbstractImageQuantizer: () => AbstractImageQuantizer,
ErrorDiffusionArray: () => ErrorDiffusionArray,
ErrorDiffusionArrayKernel: () => ErrorDiffusionArrayKernel,
ErrorDiffusionRiemersma: () => ErrorDiffusionRiemersma,
NearestColor: () => NearestColor
});
var AbstractImageQuantizer = class {
quantizeSync(pointContainer, palette2) {
for (const value of this.quantize(pointContainer, palette2)) {
if (value.pointContainer) {
return value.pointContainer;
}
}
throw new Error("unreachable");
}
};
var NearestColor = class extends AbstractImageQuantizer {
constructor(colorDistanceCalculator) {
super();
__publicField(this, "_distance");
this._distance = colorDistanceCalculator;
}
*quantize(pointContainer, palette2) {
const pointArray = pointContainer.getPointArray();
const width = pointContainer.getWidth();
const height = pointContainer.getHeight();
const tracker = new ProgressTracker(height, 99);
for (let y2 = 0;y2 < height; y2++) {
if (tracker.shouldNotify(y2)) {
yield {
progress: tracker.progress
};
}
for (let x2 = 0, idx = y2 * width;x2 < width; x2++, idx++) {
const point = pointArray[idx];
point.from(palette2.getNearestColor(this._distance, point));
}
}
yield {
pointContainer,
progress: 100
};
}
};
var ErrorDiffusionArrayKernel = /* @__PURE__ */ ((ErrorDiffusionArrayKernel2) => {
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["FloydSteinberg"] = 0] = "FloydSteinberg";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["FalseFloydSteinberg"] = 1] = "FalseFloydSteinberg";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["Stucki"] = 2] = "Stucki";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["Atkinson"] = 3] = "Atkinson";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["Jarvis"] = 4] = "Jarvis";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["Burkes"] = 5] = "Burkes";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["Sierra"] = 6] = "Sierra";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["TwoSierra"] = 7] = "TwoSierra";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["SierraLite"] = 8] = "SierraLite";
return ErrorDiffusionArrayKernel2;
})(ErrorDiffusionArrayKernel || {});
var ErrorDiffusionArray = class extends AbstractImageQuantizer {
constructor(colorDistanceCalculator, kernel, serpentine = true, minimumColorDistanceToDither = 0, calculateErrorLikeGIMP = false) {
super();
__publicField(this, "_minColorDistance");
__publicField(this, "_serpentine");
__publicField(this, "_kernel");
__publicField(this, "_calculateErrorLikeGIMP");
__publicField(this, "_distance");
this._setKernel(kernel);
this._distance = colorDistanceCalculator;
this._minColorDistance = minimumColorDistanceToDither;
this._serpentine = serpentine;
this._calculateErrorLikeGIMP = calculateErrorLikeGIMP;
}
*quantize(pointContainer, palette2) {
const pointArray = pointContainer.getPointArray();
const originalPoint = new Point;
const width = pointContainer.getWidth();
const height = pointContainer.getHeight();
const errorLines = [];
let dir = 1;
let maxErrorLines = 1;
for (const kernel of this._kernel) {
const kernelErrorLines = kernel[2] + 1;
if (maxErrorLines < kernelErrorLines)
maxErrorLines = kernelErrorLines;
}
for (let i = 0;i < maxErrorLines; i++) {
this._fillErrorLine(errorLines[i] = [], width);
}
const tracker = new ProgressTracker(height, 99);
for (let y2 = 0;y2 < height; y2++) {
if (tracker.shouldNotify(y2)) {
yield {
progress: tracker.progress
};
}
if (this._serpentine)
dir *= -1;
const lni = y2 * width;
const xStart = dir === 1 ? 0 : width - 1;
const xEnd = dir === 1 ? width : -1;
this._fillErrorLine(errorLines[0], width);
errorLines.push(errorLines.shift());
const errorLine = errorLines[0];
for (let x2 = xStart, idx = lni + xStart;x2 !== xEnd; x2 += dir, idx += dir) {
const point = pointArray[idx];
const error = errorLine[x2];
originalPoint.from(point);
const correctedPoint = Point.createByRGBA(inRange0to255Rounded(point.r + error[0]), inRange0to255Rounded(point.g + error[1]), inRange0to255Rounded(point.b + error[2]), inRange0to255Rounded(point.a + error[3]));
const palettePoint = palette2.getNearestColor(this._distance, correctedPoint);
point.from(palettePoint);
if (this._minColorDistance) {
const dist = this._distance.calculateNormalized(originalPoint, palettePoint);
if (dist < this._minColorDistance)
continue;
}
let er;
let eg;
let eb;
let ea;
if (this._calculateErrorLikeGIMP) {
er = correctedPoint.r - palettePoint.r;
eg = correctedPoint.g - palettePoint.g;
eb = correctedPoint.b - palettePoint.b;
ea = correctedPoint.a - palettePoint.a;
} else {
er = originalPoint.r - palettePoint.r;
eg = originalPoint.g - palettePoint.g;
eb = originalPoint.b - palettePoint.b;
ea = originalPoint.a - palettePoint.a;
}
const dStart = dir === 1 ? 0 : this._kernel.length - 1;
const dEnd = dir === 1 ? this._kernel.length : -1;
for (let i = dStart;i !== dEnd; i += dir) {
const x1 = this._kernel[i][1] * dir;
const y1 = this._kernel[i][2];
if (x1 + x2 >= 0 && x1 + x2 < width && y1 + y2 >= 0 && y1 + y2 < height) {
const d = this._kernel[i][0];
const e = errorLines[y1][x1 + x2];
e[0] += er * d;
e[1] += eg * d;
e[2] += eb * d;
e[3] += ea * d;
}
}
}
}
yield {
pointContainer,
progress: 100
};
}
_fillErrorLine(errorLine, width) {
if (errorLine.length > width) {
errorLine.length = width;
}
const l = errorLine.length;
for (let i = 0;i < l; i++) {
const error = errorLine[i];
error[0] = error[1] = error[2] = error[3] = 0;
}
for (let i = l;i < width; i++) {
errorLine[i] = [0, 0, 0, 0];
}
}
_setKernel(kernel) {
switch (kernel) {
case 0:
this._kernel = [
[7 / 16, 1, 0],
[3 / 16, -1, 1],
[5 / 16, 0, 1],
[1 / 16, 1, 1]
];
break;
case 1:
this._kernel = [
[3 / 8, 1, 0],
[3 / 8, 0, 1],
[2 / 8, 1, 1]
];
break;
case 2:
this._kernel = [
[8 / 42, 1, 0],
[4 / 42, 2, 0],
[2 / 42, -2, 1],
[4 / 42, -1, 1],
[8 / 42, 0, 1],
[4 / 42, 1, 1],
[2 / 42, 2, 1],
[1 / 42, -2, 2],
[2 / 42, -1, 2],
[4 / 42, 0, 2],
[2 / 42, 1, 2],
[1 / 42, 2, 2]
];
break;
case 3:
this._kernel = [
[1 / 8, 1, 0],
[1 / 8, 2, 0],
[1 / 8, -1, 1],
[1 / 8, 0, 1],
[1 / 8, 1, 1],
[1 / 8, 0, 2]
];
break;
case 4:
this._kernel = [
[7 / 48, 1, 0],
[5 / 48, 2, 0],
[3 / 48, -2, 1],
[5 / 48, -1, 1],
[7 / 48, 0, 1],
[5 / 48, 1, 1],
[3 / 48, 2, 1],
[1 / 48, -2, 2],
[3 / 48, -1, 2],
[5 / 48, 0, 2],
[3 / 48, 1, 2],
[1 / 48, 2, 2]
];
break;
case 5:
this._kernel = [
[8 / 32, 1, 0],
[4 / 32, 2, 0],
[2 / 32, -2, 1],
[4 / 32, -1, 1],
[8 / 32, 0, 1],
[4 / 32, 1, 1],
[2 / 32, 2, 1]
];
break;
case 6:
this._kernel = [
[5 / 32, 1, 0],
[3 / 32, 2, 0],
[2 / 32, -2, 1],
[4 / 32, -1, 1],
[5 / 32, 0, 1],
[4 / 32, 1, 1],
[2 / 32, 2, 1],
[2 / 32, -1, 2],
[3 / 32, 0, 2],
[2 / 32, 1, 2]
];
break;
case 7:
this._kernel = [
[4 / 16, 1, 0],
[3 / 16, 2, 0],
[1 / 16, -2, 1],
[2 / 16, -1, 1],
[3 / 16, 0, 1],
[2 / 16, 1, 1],
[1 / 16, 2, 1]
];
break;
case 8:
this._kernel = [
[2 / 4, 1, 0],
[1 / 4, -1, 1],
[1 / 4, 0, 1]
];
break;
default:
throw new Error(`ErrorDiffusionArray: unknown kernel = ${kernel}`);
}
}
};
function* hilbertCurve(width, height, callback) {
const maxBound = Math.max(width, height);
const level = Math.floor(Math.log(maxBound) / Math.log(2) + 1);
const tracker = new ProgressTracker(width * height, 99);
const data = {
width,
height,
level,
callback,
tracker,
index: 0,
x: 0,
y: 0
};
yield* walkHilbert(data, 1);
visit(data, 0);
}
function* walkHilbert(data, direction) {
if (data.level < 1)
return;
if (data.tracker.shouldNotify(data.index)) {
yield { progress: data.tracker.progress };
}
data.level--;
switch (direction) {
case 2:
yield* walkHilbert(data, 1);
visit(data, 3);
yield* walkHilbert(data, 2);
visit(data, 4);
yield* walkHilbert(data, 2);
visit(data, 2);
yield* walkHilbert(data, 4);
break;
case 3:
yield* walkHilbert(data, 4);
visit(data, 2);
yield* walkHilbert(data, 3);
visit(data, 1);
yield* walkHilbert(data, 3);
visit(data, 3);
yield* walkHilbert(data, 1);
break;
case 1:
yield* walkHilbert(data, 2);
visit(data, 4);
yield* walkHilbert(data, 1);
visit(data, 3);
yield* walkHilbert(data, 1);
visit(data, 1);
yield* walkHilbert(data, 3);
break;
case 4:
yield* walkHilbert(data, 3);
visit(data, 1);
yield* walkHilbert(data, 4);
visit(data, 2);
yield* walkHilbert(data, 4);
visit(data, 4);
yield* walkHilbert(data, 2);
break;
default:
break;
}
data.level++;
}
function visit(data, direction) {
if (data.x >= 0 && data.x < data.width && data.y >= 0 && data.y < data.height) {
data.callback(data.x, data.y);
data.index++;
}
switch (direction) {
case 2:
data.x--;
break;
case 3:
data.x++;
break;
case 1:
data.y--;
break;
case 4:
data.y++;
break;
}
}
var ErrorDiffusionRiemersma = class extends AbstractImageQuantizer {
constructor(colorDistanceCalculator, errorQueueSize = 16, errorPropagation = 1) {
super();
__publicField(this, "_distance");
__publicField(this, "_weights");
__publicField(this, "_errorQueueSize");
this._distance = colorDistanceCalculator;
this._errorQueueSize = errorQueueSize;
this._weights = ErrorDiffusionRiemersma._createWeights(errorPropagation, errorQueueSize);
}
*quantize(pointContainer, palette2) {
const pointArray = pointContainer.getPointArray();
const width = pointContainer.getWidth();
const height = pointContainer.getHeight();
const errorQueue = [];
let head = 0;
for (let i = 0;i < this._errorQueueSize; i++) {
errorQueue[i] = { r: 0, g: 0, b: 0, a: 0 };
}
yield* hilbertCurve(width, height, (x2, y2) => {
const p = pointArray[x2 + y2 * width];
let { r, g, b, a } = p;
for (let i = 0;i < this._errorQueueSize; i++) {
const weight = this._weights[i];
const e = errorQueue[(i + head) % this._errorQueueSize];
r += e.r * weight;
g += e.g * weight;
b += e.b * weight;
a += e.a * weight;
}
const correctedPoint = Point.createByRGBA(inRange0to255Rounded(r), inRange0to255Rounded(g), inRange0to255Rounded(b), inRange0to255Rounded(a));
const quantizedPoint = palette2.getNearestColor(this._distance, correctedPoint);
head = (head + 1) % this._errorQueueSize;
const tail = (head + this._errorQueueSize - 1) % this._errorQueueSize;
errorQueue[tail].r = p.r - quantizedPoint.r;
errorQueue[tail].g = p.g - quantizedPoint.g;
errorQueue[tail].b = p.b - quantizedPoint.b;
errorQueue[tail].a = p.a - quantizedPoint.a;
p.from(quantizedPoint);
});
yield {
pointContainer,
progress: 100
};
}
static _createWeights(errorPropagation, errorQueueSize) {
const weights = [];
const multiplier = Math.exp(Math.log(errorQueueSize) / (errorQueueSize - 1));
for (let i = 0, next = 1;i < errorQueueSize; i++) {
weights[i] = (next + 0.5 | 0) / errorQueueSize * errorPropagation;
next *= multiplier;
}
return weights;
}
};
var quality_exports = {};
__export2(quality_exports, {
ssim: () => ssim
});
var K1 = 0.01;
var K2 = 0.03;
function ssim(image1, image2) {
if (image1.getHeight() !== image2.getHeight() || image1.getWidth() !== image2.getWidth()) {
throw new Error("Images have different sizes!");
}
const bitsPerComponent = 8;
const L = (1 << bitsPerComponent) - 1;
const c1 = (K1 * L) ** 2;
const c2 = (K2 * L) ** 2;
let numWindows = 0;
let mssim = 0;
iterate(image1, image2, (lumaValues1, lumaValues2, averageLumaValue1, averageLumaValue2) => {
let sigxy = 0;
let sigsqx = 0;
let sigsqy = 0;
for (let i = 0;i < lumaValues1.length; i++) {
sigsqx += (lumaValues1[i] - averageLumaValue1) ** 2;
sigsqy += (lumaValues2[i] - averageLumaValue2) ** 2;
sigxy += (lumaValues1[i] - averageLumaValue1) * (lumaValues2[i] - averageLumaValue2);
}
const numPixelsInWin = lumaValues1.length - 1;
sigsqx /= numPixelsInWin;
sigsqy /= numPixelsInWin;
sigxy /= numPixelsInWin;
const numerator = (2 * averageLumaValue1 * averageLumaValue2 + c1) * (2 * sigxy + c2);
const denominator = (averageLumaValue1 ** 2 + averageLumaValue2 ** 2 + c1) * (sigsqx + sigsqy + c2);
const ssim2 = numerator / denominator;
mssim += ssim2;
numWindows++;
});
return mssim / numWindows;
}
function iterate(image1, image2, callback) {
const windowSize = 8;
const width = image1.getWidth();
const height = image1.getHeight();
for (let y2 = 0;y2 < height; y2 += windowSize) {
for (let x2 = 0;x2 < width; x2 += windowSize) {
const windowWidth = Math.min(windowSize, width - x2);
const windowHeight = Math.min(windowSize, height - y2);
const lumaValues1 = calculateLumaValuesForWindow(image1, x2, y2, windowWidth, windowHeight);
const lumaValues2 = calculateLumaValuesForWindow(image2, x2, y2, windowWidth, windowHeight);
const averageLuma1 = calculateAverageLuma(lumaValues1);
const averageLuma2 = calculateAverageLuma(lumaValues2);
callback(lumaValues1, lumaValues2, averageLuma1, averageLuma2);
}
}
}
function calculateLumaValuesForWindow(image2, x2, y2, width, height) {
const pointArray = image2.getPointArray();
const lumaValues = [];
let counter = 0;
for (let j = y2;j < y2 + height; j++) {
const offset = j * image2.getWidth();
for (let i = x2;i < x2 + width; i++) {
const point = pointArray[offset + i];
lumaValues[counter] = point.r * 0.2126 + point.g * 0.7152 + point.b * 0.0722;
counter++;
}
}
return lumaValues;
}
function calculateAverageLuma(lumaValues) {
let sumLuma = 0;
for (const luma of lumaValues) {
sumLuma += luma;
}
return sumLuma / lumaValues.length;
}
var setImmediateImpl = typeof setImmediate === "function" ? setImmediate : typeof process !== "undefined" && typeof (process == null ? undefined : process.nextTick) === "function" ? (callback) => process.nextTick(callback) : (callback) => setTimeout(callback, 0);
function buildPaletteSync(images, {
colorDistanceFormula,
paletteQuantization,
colors
} = {}) {
const distanceCalculator = colorDistanceFormulaToColorDistance(colorDistanceFormula);
const paletteQuantizer = paletteQuantizationToPaletteQuantizer(distanceCalculator, paletteQuantization, colors);
images.forEach((image2) => paletteQuantizer.sample(image2));
return paletteQuantizer.quantizeSync();
}
async function buildPalette(images, {
colorDistanceFormula,
paletteQuantization,
colors,
onProgress
} = {}) {
return new Promise((resolve2, reject2) => {
const distanceCalculator = colorDistanceFormulaToColorDistance(colorDistanceFormula);
const paletteQuantizer = paletteQuantizationToPaletteQuantizer(distanceCalculator, paletteQuantization, colors);
images.forEach((image2) => paletteQuantizer.sample(image2));
let palette2;
const iterator = paletteQuantizer.quantize();
const next = () => {
try {
const result = iterator.next();
if (result.done) {
resolve2(palette2);
} else {
if (result.value.palette)
palette2 = result.value.palette;
if (onProgress)
onProgress(result.value.progress);
setImmediateImpl(next);
}
} catch (error) {
reject2(error);
}
};
setImmediateImpl(next);
});
}
function applyPaletteSync(image2, palette2, { colorDistanceFormula, imageQuantization } = {}) {
const distanceCalculator = colorDistanceFormulaToColorDistance(colorDistanceFormula);
const imageQuantizer = imageQuantizationToImageQuantizer(distanceCalculator, imageQuantization);
return imageQuantizer.quantizeSync(image2, palette2);
}
async function applyPalette(image2, palette2, {
colorDistanceFormula,
imageQuantization,
onProgress
} = {}) {
return new Promise((resolve2, reject2) => {
const distanceCalculator = colorDistanceFormulaToColorDistance(colorDistanceFormula);
const imageQuantizer = imageQuantizationToImageQuantizer(distanceCalculator, imageQuantization);
let outPointContainer;
const iterator = imageQuantizer.quantize(image2, palette2);
const next = () => {
try {
const result = iterator.next();
if (result.done) {
resolve2(outPointContainer);
} else {
if (result.value.pointContainer) {
outPointContainer = result.value.pointContainer;
}
if (onProgress)
onProgress(result.value.progress);
setImmediateImpl(next);
}
} catch (error) {
reject2(error);
}
};
setImmediateImpl(next);
});
}
function colorDistanceFormulaToColorDistance(colorDistanceFormula = "euclidean-bt709") {
switch (colorDistanceFormula) {
case "cie94-graphic-arts":
return new CIE94GraphicArts;
case "cie94-textiles":
return new CIE94Textiles;
case "ciede2000":
return new CIEDE2000;
case "color-metric":
return new CMetric;
case "euclidean":
return new Euclidean;
case "euclidean-bt709":
return new EuclideanBT709;
case "euclidean-bt709-noalpha":
return new EuclideanBT709NoAlpha;
case "manhattan":
return new Manhattan;
case "manhattan-bt709":
return new ManhattanBT709;
case "manhattan-nommyde":
return new ManhattanNommyde;
case "pngquant":
return new PNGQuant;
default:
throw new Error(`Unknown colorDistanceFormula ${colorDistanceFormula}`);
}
}
function imageQuantizationToImageQuantizer(distanceCalculator, imageQuantization = "floyd-steinberg") {
switch (imageQuantization) {
case "nearest":
return new NearestColor(distanceCalculator);
case "riemersma":
return new ErrorDiffusionRiemersma(distanceCalculator);
case "floyd-steinberg":
return new ErrorDiffusionArray(distanceCalculator, 0);
case "false-floyd-steinberg":
return new ErrorDiffusionArray(distanceCalculator, 1);
case "stucki":
return new ErrorDiffusionArray(distanceCalculator, 2);
case "atkinson":
return new ErrorDiffusionArray(distanceCalculator, 3);
case "jarvis":
return new ErrorDiffusionArray(distanceCalculator, 4);
case "burkes":
return new ErrorDiffusionArray(distanceCalculator, 5);
case "sierra":
return new ErrorDiffusionArray(distanceCalculator, 6);
case "two-sierra":
return new ErrorDiffusionArray(distanceCalculator, 7);
case "sierra-lite":
return new ErrorDiffusionArray(distanceCalculator, 8);
default:
throw new Error(`Unknown imageQuantization ${imageQuantization}`);
}
}
function paletteQuantizationToPaletteQuantizer(distanceCalculator, paletteQuantization = "wuquant", colors = 256) {
switch (paletteQuantization) {
case "neuquant":
return new NeuQuant(distanceCalculator, colors);
case "rgbquant":
return new RGBQuant(distanceCalculator, colors);
case "wuquant":
return new WuQuant(distanceCalculator, colors);
case "neuquant-float":
return new NeuQuantFloat(distanceCalculator, colors);
default:
throw new Error(`Unknown paletteQuantization ${paletteQuantization}`);
}
}
module.exports = __toCommonJS(src_exports);
});
// ../../node_modules/.bun/gifwrap@0.10.1/node_modules/gifwrap/src/gifframe.js
var require_gifframe = __commonJS((exports) => {
var BitmapImage = require_bitmapimage();
var { GifError: GifError2 } = require_gif();
class GifFrame extends BitmapImage {
constructor(...args) {
super(...args);
if (args[0] instanceof GifFrame) {
const source = args[0];
this.xOffset = source.xOffset;
this.yOffset = source.yOffset;
this.disposalMethod = source.disposalMethod;
this.delayCentisecs = source.delayCentisecs;
this.interlaced = source.interlaced;
} else {
const lastArg = args[args.length - 1];
let options = {};
if (typeof lastArg === "object" && !(lastArg instanceof BitmapImage)) {
options = lastArg;
}
this.xOffset = options.xOffset || 0;
this.yOffset = options.yOffset || 0;
this.disposalMethod = options.disposalMethod !== undefined ? options.disposalMethod : GifFrame.DisposeToBackgroundColor;
this.delayCentisecs = options.delayCentisecs || 8;
this.interlaced = options.interlaced || false;
}
}
getPalette() {
const colorSet = new Set;
const buf = this.bitmap.data;
let i = 0;
let usesTransparency = false;
while (i < buf.length) {
if (buf[i + 3] === 0) {
usesTransparency = true;
} else {
const color = buf.readUInt32BE(i, true) >> 8 & 16777215;
colorSet.add(color);
}
i += 4;
}
const colors = new Array(colorSet.size);
const iter = colorSet.values();
for (i = 0;i < colors.length; ++i) {
colors[i] = iter.next().value;
}
colors.sort((a, b) => a - b);
let indexCount = colors.length;
if (usesTransparency) {
++indexCount;
}
return { colors, usesTransparency, indexCount };
}
}
GifFrame.DisposeToAnything = 0;
GifFrame.DisposeNothing = 1;
GifFrame.DisposeToBackgroundColor = 2;
GifFrame.DisposeToPrevious = 3;
exports.GifFrame = GifFrame;
});
// ../../node_modules/.bun/gifwrap@0.10.1/node_modules/gifwrap/src/gifutil.js
var require_gifutil = __commonJS((exports) => {
var fs = __require("fs");
var ImageQ = require_image_q();
var BitmapImage = require_bitmapimage();
var { GifFrame } = require_gifframe();
var { GifError: GifError2 } = require_gif();
var { GifCodec } = require_gifcodec();
var INVALID_SUFFIXES = [".jpg", ".jpeg", ".png", ".bmp"];
var defaultCodec = new GifCodec;
exports.cloneFrames = function(frames) {
let clones = [];
frames.forEach((frame) => {
clones.push(new GifFrame(frame));
});
return clones;
};
exports.getColorInfo = function(frames, maxGlobalIndex) {
let usesTransparency = false;
const palettes = [];
for (let i = 0;i < frames.length; ++i) {
let palette2 = frames[i].getPalette();
if (palette2.usesTransparency) {
usesTransparency = true;
}
if (palette2.indexCount > 256) {
throw new GifError2(`Frame ${i} uses more than 256 color indexes`);
}
palettes.push(palette2);
}
if (maxGlobalIndex === 0) {
return { usesTransparency, palettes };
}
const globalColorSet = new Set;
palettes.forEach((palette2) => {
palette2.colors.forEach((color) => {
globalColorSet.add(color);
});
});
let indexCount = globalColorSet.size;
if (usesTransparency) {
++indexCount;
}
if (maxGlobalIndex && indexCount > maxGlobalIndex) {
return { usesTransparency, palettes };
}
const colors = new Array(globalColorSet.size);
const iter = globalColorSet.values();
for (let i = 0;i < colors.length; ++i) {
colors[i] = iter.next().value;
}
colors.sort((a, b) => a - b);
return { colors, indexCount, usesTransparency, palettes };
};
exports.copyAsJimp = function(jimp, bitmapImageToCopy) {
return exports.shareAsJimp(jimp, new BitmapImage(bitmapImageToCopy));
};
exports.getMaxDimensions = function(frames) {
let maxWidth = 0, maxHeight = 0;
frames.forEach((frame) => {
const width = frame.xOffset + frame.bitmap.width;
if (width > maxWidth) {
maxWidth = width;
}
const height = frame.yOffset + frame.bitmap.height;
if (height > maxHeight) {
maxHeight = height;
}
});
return { maxWidth, maxHeight };
};
exports.quantizeDekker = function(imageOrImages, maxColorIndexes, dither) {
maxColorIndexes = maxColorIndexes || 256;
_quantize(imageOrImages, "NeuQuantFloat", maxColorIndexes, 0, dither);
};
exports.quantizeSorokin = function(imageOrImages, maxColorIndexes, histogram, dither) {
maxColorIndexes = maxColorIndexes || 256;
histogram = histogram || "min-pop";
let histogramID;
switch (histogram) {
case "min-pop":
histogramID = 2;
break;
case "top-pop":
histogramID = 1;
break;
default:
throw new Error(`Invalid quantizeSorokin histogram '${histogram}'`);
}
_quantize(imageOrImages, "RGBQuant", maxColorIndexes, histogramID, dither);
};
exports.quantizeWu = function(imageOrImages, maxColorIndexes, significantBits, dither) {
maxColorIndexes = maxColorIndexes || 256;
significantBits = significantBits || 5;
if (significantBits < 1 || significantBits > 8) {
throw new Error("Invalid quantization quality");
}
_quantize(imageOrImages, "WuQuant", maxColorIndexes, significantBits, dither);
};
exports.read = function(source, decoder) {
decoder = decoder || defaultCodec;
if (Buffer.isBuffer(source)) {
return decoder.decodeGif(source);
}
return _readBinary(source).then((buffer) => {
return decoder.decodeGif(buffer);
});
};
exports.shareAsJimp = function(jimp, bitmapImageToShare) {
const jimpImage = new jimp(bitmapImageToShare.bitmap.width, bitmapImageToShare.bitmap.height, 0);
jimpImage.bitmap.data = bitmapImageToShare.bitmap.data;
return jimpImage;
};
exports.write = function(path, frames, spec, encoder) {
encoder = encoder || defaultCodec;
const matches = path.match(/\.[a-zA-Z]+$/);
if (matches !== null && INVALID_SUFFIXES.includes(matches[0].toLowerCase())) {
throw new Error(`GIF '${path}' has an unexpected suffix`);
}
return encoder.encodeGif(frames, spec).then((gif) => {
return _writeBinary(path, gif.buffer).then(() => {
return gif;
});
});
};
function _quantize(imageOrImages, method, maxColorIndexes, modifier, dither) {
const images = Array.isArray(imageOrImages) ? imageOrImages : [imageOrImages];
const ditherAlgs = [
"FloydSteinberg",
"FalseFloydSteinberg",
"Stucki",
"Atkinson",
"Jarvis",
"Burkes",
"Sierra",
"TwoSierra",
"SierraLite"
];
if (dither) {
if (ditherAlgs.indexOf(dither.ditherAlgorithm) < 0) {
throw new Error(`Invalid ditherAlgorithm '${dither.ditherAlgorithm}'`);
}
if (dither.serpentine === undefined) {
dither.serpentine = true;
}
if (dither.minimumColorDistanceToDither === undefined) {
dither.minimumColorDistanceToDither = 0;
}
if (dither.calculateErrorLikeGIMP === undefined) {
dither.calculateErrorLikeGIMP = false;
}
}
const distCalculator = new ImageQ.distance.Euclidean;
const quantizer = new ImageQ.palette[method](distCalculator, maxColorIndexes, modifier);
let imageMaker;
if (dither) {
imageMaker = new ImageQ.image.ErrorDiffusionArray(distCalculator, ImageQ.image.ErrorDiffusionArrayKernel[dither.ditherAlgorithm], dither.serpentine, dither.minimumColorDistanceToDither, dither.calculateErrorLikeGIMP);
} else {
imageMaker = new ImageQ.image.NearestColor(distCalculator);
}
const inputContainers = [];
images.forEach((image2) => {
const imageBuf = image2.bitmap.data;
const inputBuf = new ArrayBuffer(imageBuf.length);
const inputArray = new Uint32Array(inputBuf);
for (let bi = 0, ai = 0;bi < imageBuf.length; bi += 4, ++ai) {
inputArray[ai] = imageBuf.readUInt32LE(bi, true);
}
const inputContainer = ImageQ.utils.PointContainer.fromUint32Array(inputArray, image2.bitmap.width, image2.bitmap.height);
quantizer.sample(inputContainer);
inputContainers.push(inputContainer);
});
const limitedPalette = quantizer.quantizeSync();
for (let i = 0;i < images.length; ++i) {
const imageBuf = images[i].bitmap.data;
const outputContainer = imageMaker.quantizeSync(inputContainers[i], limitedPalette);
const outputArray = outputContainer.toUint32Array();
for (let bi = 0, ai = 0;bi < imageBuf.length; bi += 4, ++ai) {
imageBuf.writeUInt32LE(outputArray[ai], bi);
}
}
}
function _readBinary(path) {
return new Promise((resolve2, reject2) => {
fs.readFile(path, (err, buffer) => {
if (err) {
return reject2(err);
}
return resolve2(buffer);
});
});
}
function _writeBinary(path, buffer) {
return new Promise((resolve2, reject2) => {
fs.writeFile(path, buffer, (err) => {
if (err) {
return reject2(err);
}
return resolve2();
});
});
}
});
// ../../node_modules/.bun/gifwrap@0.10.1/node_modules/gifwrap/src/gifcodec.js
var require_gifcodec = __commonJS((exports) => {
var Omggif = require_omggif();
var { Gif, GifError: GifError2 } = require_gif();
function GifUtil() {
const data = require_gifutil();
GifUtil = function() {
return data;
};
return data;
}
var { GifFrame } = require_gifframe();
var PER_GIF_OVERHEAD = 200;
var PER_FRAME_OVERHEAD = 100;
class GifCodec {
constructor(options = {}) {
this._transparentRGB = null;
if (typeof options.transparentRGB === "number" && options.transparentRGB !== 0) {
this._transparentRGBA = options.transparentRGB * 256;
}
this._testInitialBufferSize = 0;
}
decodeGif(buffer) {
try {
let reader;
try {
reader = new Omggif.GifReader(buffer);
} catch (err) {
throw new GifError2(err);
}
const frameCount = reader.numFrames();
const frames = [];
const spec = {
width: reader.width,
height: reader.height,
loops: reader.loopCount()
};
spec.usesTransparency = false;
for (let i = 0;i < frameCount; ++i) {
const frameInfo = this._decodeFrame(reader, i, spec.usesTransparency);
frames.push(frameInfo.frame);
if (frameInfo.usesTransparency) {
spec.usesTransparency = true;
}
}
return Promise.resolve(new Gif(buffer, frames, spec));
} catch (err) {
return Promise.reject(err);
}
}
encodeGif(frames, spec = {}) {
try {
if (frames === null || frames.length === 0) {
throw new GifError2("there are no frames");
}
const dims = GifUtil().getMaxDimensions(frames);
spec = Object.assign({}, spec);
spec.width = dims.maxWidth;
spec.height = dims.maxHeight;
if (spec.loops === undefined) {
spec.loops = 0;
}
spec.colorScope = spec.colorScope || Gif.GlobalColorsPreferred;
return Promise.resolve(this._encodeGif(frames, spec));
} catch (err) {
return Promise.reject(err);
}
}
_decodeFrame(reader, frameIndex, alreadyUsedTransparency) {
let info, buffer;
try {
info = reader.frameInfo(frameIndex);
buffer = new Buffer(reader.width * reader.height * 4);
reader.decodeAndBlitFrameRGBA(frameIndex, buffer);
if (info.width !== reader.width || info.height !== reader.height) {
if (info.y) {
buffer = buffer.slice(info.y * reader.width * 4);
}
if (reader.width > info.width) {
for (let ii = 0;ii < info.height; ++ii) {
buffer.copy(buffer, ii * info.width * 4, (info.x + ii * reader.width) * 4, (info.x + ii * reader.width) * 4 + info.width * 4);
}
}
buffer = buffer.slice(0, info.width * info.height * 4);
}
} catch (err) {
throw new GifError2(err);
}
let usesTransparency = false;
if (this._transparentRGBA === null) {
if (!alreadyUsedTransparency) {
for (let i = 3;i < buffer.length; i += 4) {
if (buffer[i] === 0) {
usesTransparency = true;
i = buffer.length;
}
}
}
} else {
for (let i = 3;i < buffer.length; i += 4) {
if (buffer[i] === 0) {
buffer.writeUInt32BE(this._transparentRGBA, i - 3);
usesTransparency = true;
}
}
}
const frame = new GifFrame(info.width, info.height, buffer, {
xOffset: info.x,
yOffset: info.y,
disposalMethod: info.disposal,
interlaced: info.interlaced,
delayCentisecs: info.delay
});
return { frame, usesTransparency };
}
_encodeGif(frames, spec) {
let colorInfo;
if (spec.colorScope === Gif.LocalColorsOnly) {
colorInfo = GifUtil().getColorInfo(frames, 0);
} else {
colorInfo = GifUtil().getColorInfo(frames, 256);
if (!colorInfo.colors) {
if (spec.colorScope === Gif.GlobalColorsOnly) {
throw new GifError2("Too many color indexes for global color table");
}
spec.colorScope = Gif.LocalColorsOnly;
}
}
spec.usesTransparency = colorInfo.usesTransparency;
const localPalettes = colorInfo.palettes;
if (spec.colorScope === Gif.LocalColorsOnly) {
const localSizeEst = 2000;
return _encodeLocal(frames, spec, localSizeEst, localPalettes);
}
const globalSizeEst = 2000;
return _encodeGlobal(frames, spec, globalSizeEst, colorInfo);
}
_getSizeEstimateGlobal(globalPalette, frames) {
if (this._testInitialBufferSize > 0) {
return this._testInitialBufferSize;
}
let sizeEst = PER_GIF_OVERHEAD + 3 * 256;
const pixelBitWidth = _getPixelBitWidth(globalPalette);
frames.forEach((frame) => {
sizeEst += _getFrameSizeEst(frame, pixelBitWidth);
});
return sizeEst;
}
_getSizeEstimateLocal(palettes, frames) {
if (this._testInitialBufferSize > 0) {
return this._testInitialBufferSize;
}
let sizeEst = PER_GIF_OVERHEAD;
for (let i = 0;i < frames.length; ++i) {
const palette2 = palettes[i];
const pixelBitWidth = _getPixelBitWidth(palette2);
sizeEst += _getFrameSizeEst(frames[i], pixelBitWidth);
}
return sizeEst;
}
}
exports.GifCodec = GifCodec;
function _colorLookupLinear(colors, color) {
const index = colors.indexOf(color);
return index === -1 ? null : index;
}
function _colorLookupBinary(colors, color) {
var lo = 0, hi = colors.length - 1, mid;
while (lo <= hi) {
mid = Math.floor((lo + hi) / 2);
if (colors[mid] > color)
hi = mid - 1;
else if (colors[mid] < color)
lo = mid + 1;
else
return mid;
}
return null;
}
function _encodeGlobal(frames, spec, bufferSizeEst, globalPalette) {
const extendedGlobalPalette = {
colors: globalPalette.colors.slice(),
usesTransparency: globalPalette.usesTransparency
};
_extendPaletteToPowerOf2(extendedGlobalPalette);
const options = {
palette: extendedGlobalPalette.colors,
loop: spec.loops
};
let buffer = new Buffer(bufferSizeEst);
let gifWriter;
try {
gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height, options);
} catch (err) {
throw new GifError2(err);
}
for (let i = 0;i < frames.length; ++i) {
buffer = _writeFrame(gifWriter, i, frames[i], globalPalette, false);
}
return new Gif(buffer.slice(0, gifWriter.end()), frames, spec);
}
function _encodeLocal(frames, spec, bufferSizeEst, localPalettes) {
const options = {
loop: spec.loops
};
let buffer = new Buffer(bufferSizeEst);
let gifWriter;
try {
gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height, options);
} catch (err) {
throw new GifError2(err);
}
for (let i = 0;i < frames.length; ++i) {
buffer = _writeFrame(gifWriter, i, frames[i], localPalettes[i], true);
}
return new Gif(buffer.slice(0, gifWriter.end()), frames, spec);
}
function _extendPaletteToPowerOf2(palette2) {
const colors = palette2.colors;
if (palette2.usesTransparency) {
colors.push(0);
}
const colorCount = colors.length;
let powerOf2 = 2;
while (colorCount > powerOf2) {
powerOf2 <<= 1;
}
colors.length = powerOf2;
colors.fill(0, colorCount);
}
function _getFrameSizeEst(frame, pixelBitWidth) {
let byteLength = frame.bitmap.width * frame.bitmap.height;
byteLength = Math.ceil(byteLength * pixelBitWidth / 8);
byteLength += Math.ceil(byteLength / 255);
return PER_FRAME_OVERHEAD + byteLength + 3 * 256;
}
function _getIndexedImage(frameIndex, frame, palette2) {
const colors = palette2.colors;
const colorToIndexFunc = colors.length <= 8 ? _colorLookupLinear : _colorLookupBinary;
const colorBuffer = frame.bitmap.data;
const indexBuffer = new Buffer(colorBuffer.length / 4);
let transparentIndex = colors.length;
let i = 0, j = 0;
while (i < colorBuffer.length) {
if (colorBuffer[i + 3] !== 0) {
const color = colorBuffer.readUInt32BE(i, true) >> 8 & 16777215;
indexBuffer[j] = colorToIndexFunc(colors, color);
} else {
indexBuffer[j] = transparentIndex;
}
i += 4;
++j;
}
if (palette2.usesTransparency) {
if (transparentIndex === 256) {
throw new GifError2(`Frame ${frameIndex} already has 256 colors` + `and so can't use transparency`);
}
} else {
transparentIndex = null;
}
return { buffer: indexBuffer, transparentIndex };
}
function _getPixelBitWidth(palette2) {
let indexCount = palette2.indexCount;
let pixelBitWidth = 0;
--indexCount;
while (indexCount) {
++pixelBitWidth;
indexCount >>= 1;
}
return pixelBitWidth > 0 ? pixelBitWidth : 1;
}
function _writeFrame(gifWriter, frameIndex, frame, palette2, isLocalPalette) {
if (frame.interlaced) {
throw new GifError2("writing interlaced GIFs is not supported");
}
const frameInfo = _getIndexedImage(frameIndex, frame, palette2);
const options = {
delay: frame.delayCentisecs,
disposal: frame.disposalMethod,
transparent: frameInfo.transparentIndex
};
if (isLocalPalette) {
_extendPaletteToPowerOf2(palette2);
options.palette = palette2.colors;
}
try {
let buffer = gifWriter.getOutputBuffer();
let startOfFrame = gifWriter.getOutputBufferPosition();
let endOfFrame;
let tryAgain = true;
while (tryAgain) {
endOfFrame = gifWriter.addFrame(frame.xOffset, frame.yOffset, frame.bitmap.width, frame.bitmap.height, frameInfo.buffer, options);
tryAgain = false;
if (endOfFrame >= buffer.length - 1) {
const biggerBuffer = new Buffer(buffer.length * 1.5);
buffer.copy(biggerBuffer);
gifWriter.setOutputBuffer(biggerBuffer);
gifWriter.setOutputBufferPosition(startOfFrame);
buffer = biggerBuffer;
tryAgain = true;
}
}
return buffer;
} catch (err) {
throw new GifError2(err);
}
}
});
// ../../node_modules/.bun/gifwrap@0.10.1/node_modules/gifwrap/src/index.js
var require_src = __commonJS((exports, module) => {
var BitmapImage = require_bitmapimage();
var { Gif, GifError: GifError2 } = require_gif();
var { GifCodec } = require_gifcodec();
var { GifFrame } = require_gifframe();
var GifUtil = require_gifutil();
module.exports = {
BitmapImage,
Gif,
GifCodec,
GifFrame,
GifUtil,
GifError: GifError2
};
});
// ../../node_modules/.bun/jpeg-js@0.4.4/node_modules/jpeg-js/lib/encoder.js
var require_encoder = __commonJS((exports, module) => {
var btoa = btoa || function(buf) {
return Buffer.from(buf).toString("base64");
};
function JPEGEncoder(quality2) {
var self2 = this;
var fround = Math.round;
var ffloor = Math.floor;
var YTable = new Array(64);
var UVTable = new Array(64);
var fdtbl_Y = new Array(64);
var fdtbl_UV = new Array(64);
var YDC_HT;
var UVDC_HT;
var YAC_HT;
var UVAC_HT;
var bitcode = new Array(65535);
var category = new Array(65535);
var outputfDCTQuant = new Array(64);
var DU = new Array(64);
var byteout = [];
var bytenew = 0;
var bytepos = 7;
var YDU = new Array(64);
var UDU = new Array(64);
var VDU = new Array(64);
var clt = new Array(256);
var RGB_YUV_TABLE = new Array(2048);
var currentQuality;
var ZigZag = [
0,
1,
5,
6,
14,
15,
27,
28,
2,
4,
7,
13,
16,
26,
29,
42,
3,
8,
12,
17,
25,
30,
41,
43,
9,
11,
18,
24,
31,
40,
44,
53,
10,
19,
23,
32,
39,
45,
52,
54,
20,
22,
33,
38,
46,
51,
55,
60,
21,
34,
37,
47,
50,
56,
59,
61,
35,
36,
48,
49,
57,
58,
62,
63
];
var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125];
var std_ac_luminance_values = [
1,
2,
3,
0,
4,
17,
5,
18,
33,
49,
65,
6,
19,
81,
97,
7,
34,
113,
20,
50,
129,
145,
161,
8,
35,
66,
177,
193,
21,
82,
209,
240,
36,
51,
98,
114,
130,
9,
10,
22,
23,
24,
25,
26,
37,
38,
39,
40,
41,
42,
52,
53,
54,
55,
56,
57,
58,
67,
68,
69,
70,
71,
72,
73,
74,
83,
84,
85,
86,
87,
88,
89,
90,
99,
100,
101,
102,
103,
104,
105,
106,
115,
116,
117,
118,
119,
120,
121,
122,
131,
132,
133,
134,
135,
136,
137,
138,
146,
147,
148,
149,
150,
151,
152,
153,
154,
162,
163,
164,
165,
166,
167,
168,
169,
170,
178,
179,
180,
181,
182,
183,
184,
185,
186,
194,
195,
196,
197,
198,
199,
200,
201,
202,
210,
211,
212,
213,
214,
215,
216,
217,
218,
225,
226,
227,
228,
229,
230,
231,
232,
233,
234,
241,
242,
243,
244,
245,
246,
247,
248,
249,
250
];
var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119];
var std_ac_chrominance_values = [
0,
1,
2,
3,
17,
4,
5,
33,
49,
6,
18,
65,
81,
7,
97,
113,
19,
34,
50,
129,
8,
20,
66,
145,
161,
177,
193,
9,
35,
51,
82,
240,
21,
98,
114,
209,
10,
22,
36,
52,
225,
37,
241,
23,
24,
25,
26,
38,
39,
40,
41,
42,
53,
54,
55,
56,
57,
58,
67,
68,
69,
70,
71,
72,
73,
74,
83,
84,
85,
86,
87,
88,
89,
90,
99,
100,
101,
102,
103,
104,
105,
106,
115,
116,
117,
118,
119,
120,
121,
122,
130,
131,
132,
133,
134,
135,
136,
137,
138,
146,
147,
148,
149,
150,
151,
152,
153,
154,
162,
163,
164,
165,
166,
167,
168,
169,
170,
178,
179,
180,
181,
182,
183,
184,
185,
186,
194,
195,
196,
197,
198,
199,
200,
201,
202,
210,
211,
212,
213,
214,
215,
216,
217,
218,
226,
227,
228,
229,
230,
231,
232,
233,
234,
242,
243,
244,
245,
246,
247,
248,
249,
250
];
function initQuantTables(sf) {
var YQT = [
16,
11,
10,
16,
24,
40,
51,
61,
12,
12,
14,
19,
26,
58,
60,
55,
14,
13,
16,
24,
40,
57,
69,
56,
14,
17,
22,
29,
51,
87,
80,
62,
18,
22,
37,
56,
68,
109,
103,
77,
24,
35,
55,
64,
81,
104,
113,
92,
49,
64,
78,
87,
103,
121,
120,
101,
72,
92,
95,
98,
112,
100,
103,
99
];
for (var i = 0;i < 64; i++) {
var t = ffloor((YQT[i] * sf + 50) / 100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
var UVQT = [
17,
18,
24,
47,
99,
99,
99,
99,
18,
21,
26,
66,
99,
99,
99,
99,
24,
26,
56,
99,
99,
99,
99,
99,
47,
66,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99
];
for (var j = 0;j < 64; j++) {
var u = ffloor((UVQT[j] * sf + 50) / 100);
if (u < 1) {
u = 1;
} else if (u > 255) {
u = 255;
}
UVTable[ZigZag[j]] = u;
}
var aasf = [
1,
1.387039845,
1.306562965,
1.175875602,
1,
0.785694958,
0.5411961,
0.275899379
];
var k = 0;
for (var row = 0;row < 8; row++) {
for (var col = 0;col < 8; col++) {
fdtbl_Y[k] = 1 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8);
fdtbl_UV[k] = 1 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8);
k++;
}
}
}
function computeHuffmanTbl(nrcodes, std_table) {
var codevalue = 0;
var pos_in_table = 0;
var HT = new Array;
for (var k = 1;k <= 16; k++) {
for (var j = 1;j <= nrcodes[k]; j++) {
HT[std_table[pos_in_table]] = [];
HT[std_table[pos_in_table]][0] = codevalue;
HT[std_table[pos_in_table]][1] = k;
pos_in_table++;
codevalue++;
}
codevalue *= 2;
}
return HT;
}
function initHuffmanTbl() {
YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values);
UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values);
YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values);
UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values);
}
function initCategoryNumber() {
var nrlower = 1;
var nrupper = 2;
for (var cat = 1;cat <= 15; cat++) {
for (var nr = nrlower;nr < nrupper; nr++) {
category[32767 + nr] = cat;
bitcode[32767 + nr] = [];
bitcode[32767 + nr][1] = cat;
bitcode[32767 + nr][0] = nr;
}
for (var nrneg = -(nrupper - 1);nrneg <= -nrlower; nrneg++) {
category[32767 + nrneg] = cat;
bitcode[32767 + nrneg] = [];
bitcode[32767 + nrneg][1] = cat;
bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg;
}
nrlower <<= 1;
nrupper <<= 1;
}
}
function initRGBYUVTable() {
for (var i = 0;i < 256; i++) {
RGB_YUV_TABLE[i] = 19595 * i;
RGB_YUV_TABLE[i + 256 >> 0] = 38470 * i;
RGB_YUV_TABLE[i + 512 >> 0] = 7471 * i + 32768;
RGB_YUV_TABLE[i + 768 >> 0] = -11059 * i;
RGB_YUV_TABLE[i + 1024 >> 0] = -21709 * i;
RGB_YUV_TABLE[i + 1280 >> 0] = 32768 * i + 8421375;
RGB_YUV_TABLE[i + 1536 >> 0] = -27439 * i;
RGB_YUV_TABLE[i + 1792 >> 0] = -5329 * i;
}
}
function writeBits(bs) {
var value = bs[0];
var posval = bs[1] - 1;
while (posval >= 0) {
if (value & 1 << posval) {
bytenew |= 1 << bytepos;
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew == 255) {
writeByte(255);
writeByte(0);
} else {
writeByte(bytenew);
}
bytepos = 7;
bytenew = 0;
}
}
}
function writeByte(value) {
byteout.push(value);
}
function writeWord(value) {
writeByte(value >> 8 & 255);
writeByte(value & 255);
}
function fDCTQuant(data, fdtbl) {
var d0, d1, d2, d3, d4, d5, d6, d7;
var dataOff = 0;
var i;
var I8 = 8;
var I64 = 64;
for (i = 0;i < I8; ++i) {
d0 = data[dataOff];
d1 = data[dataOff + 1];
d2 = data[dataOff + 2];
d3 = data[dataOff + 3];
d4 = data[dataOff + 4];
d5 = data[dataOff + 5];
d6 = data[dataOff + 6];
d7 = data[dataOff + 7];
var tmp0 = d0 + d7;
var tmp7 = d0 - d7;
var tmp1 = d1 + d6;
var tmp6 = d1 - d6;
var tmp2 = d2 + d5;
var tmp5 = d2 - d5;
var tmp3 = d3 + d4;
var tmp4 = d3 - d4;
var tmp10 = tmp0 + tmp3;
var tmp13 = tmp0 - tmp3;
var tmp11 = tmp1 + tmp2;
var tmp12 = tmp1 - tmp2;
data[dataOff] = tmp10 + tmp11;
data[dataOff + 4] = tmp10 - tmp11;
var z1 = (tmp12 + tmp13) * 0.707106781;
data[dataOff + 2] = tmp13 + z1;
data[dataOff + 6] = tmp13 - z1;
tmp10 = tmp4 + tmp5;
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
var z5 = (tmp10 - tmp12) * 0.382683433;
var z2 = 0.5411961 * tmp10 + z5;
var z4 = 1.306562965 * tmp12 + z5;
var z3 = tmp11 * 0.707106781;
var z11 = tmp7 + z3;
var z13 = tmp7 - z3;
data[dataOff + 5] = z13 + z2;
data[dataOff + 3] = z13 - z2;
data[dataOff + 1] = z11 + z4;
data[dataOff + 7] = z11 - z4;
dataOff += 8;
}
dataOff = 0;
for (i = 0;i < I8; ++i) {
d0 = data[dataOff];
d1 = data[dataOff + 8];
d2 = data[dataOff + 16];
d3 = data[dataOff + 24];
d4 = data[dataOff + 32];
d5 = data[dataOff + 40];
d6 = data[dataOff + 48];
d7 = data[dataOff + 56];
var tmp0p2 = d0 + d7;
var tmp7p2 = d0 - d7;
var tmp1p2 = d1 + d6;
var tmp6p2 = d1 - d6;
var tmp2p2 = d2 + d5;
var tmp5p2 = d2 - d5;
var tmp3p2 = d3 + d4;
var tmp4p2 = d3 - d4;
var tmp10p2 = tmp0p2 + tmp3p2;
var tmp13p2 = tmp0p2 - tmp3p2;
var tmp11p2 = tmp1p2 + tmp2p2;
var tmp12p2 = tmp1p2 - tmp2p2;
data[dataOff] = tmp10p2 + tmp11p2;
data[dataOff + 32] = tmp10p2 - tmp11p2;
var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781;
data[dataOff + 16] = tmp13p2 + z1p2;
data[dataOff + 48] = tmp13p2 - z1p2;
tmp10p2 = tmp4p2 + tmp5p2;
tmp11p2 = tmp5p2 + tmp6p2;
tmp12p2 = tmp6p2 + tmp7p2;
var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433;
var z2p2 = 0.5411961 * tmp10p2 + z5p2;
var z4p2 = 1.306562965 * tmp12p2 + z5p2;
var z3p2 = tmp11p2 * 0.707106781;
var z11p2 = tmp7p2 + z3p2;
var z13p2 = tmp7p2 - z3p2;
data[dataOff + 40] = z13p2 + z2p2;
data[dataOff + 24] = z13p2 - z2p2;
data[dataOff + 8] = z11p2 + z4p2;
data[dataOff + 56] = z11p2 - z4p2;
dataOff++;
}
var fDCTQuant2;
for (i = 0;i < I64; ++i) {
fDCTQuant2 = data[i] * fdtbl[i];
outputfDCTQuant[i] = fDCTQuant2 > 0 ? fDCTQuant2 + 0.5 | 0 : fDCTQuant2 - 0.5 | 0;
}
return outputfDCTQuant;
}
function writeAPP0() {
writeWord(65504);
writeWord(16);
writeByte(74);
writeByte(70);
writeByte(73);
writeByte(70);
writeByte(0);
writeByte(1);
writeByte(1);
writeByte(0);
writeWord(1);
writeWord(1);
writeByte(0);
writeByte(0);
}
function writeAPP1(exifBuffer) {
if (!exifBuffer)
return;
writeWord(65505);
if (exifBuffer[0] === 69 && exifBuffer[1] === 120 && exifBuffer[2] === 105 && exifBuffer[3] === 102) {
writeWord(exifBuffer.length + 2);
} else {
writeWord(exifBuffer.length + 5 + 2);
writeByte(69);
writeByte(120);
writeByte(105);
writeByte(102);
writeByte(0);
}
for (var i = 0;i < exifBuffer.length; i++) {
writeByte(exifBuffer[i]);
}
}
function writeSOF0(width, height) {
writeWord(65472);
writeWord(17);
writeByte(8);
writeWord(height);
writeWord(width);
writeByte(3);
writeByte(1);
writeByte(17);
writeByte(0);
writeByte(2);
writeByte(17);
writeByte(1);
writeByte(3);
writeByte(17);
writeByte(1);
}
function writeDQT() {
writeWord(65499);
writeWord(132);
writeByte(0);
for (var i = 0;i < 64; i++) {
writeByte(YTable[i]);
}
writeByte(1);
for (var j = 0;j < 64; j++) {
writeByte(UVTable[j]);
}
}
function writeDHT() {
writeWord(65476);
writeWord(418);
writeByte(0);
for (var i = 0;i < 16; i++) {
writeByte(std_dc_luminance_nrcodes[i + 1]);
}
for (var j = 0;j <= 11; j++) {
writeByte(std_dc_luminance_values[j]);
}
writeByte(16);
for (var k = 0;k < 16; k++) {
writeByte(std_ac_luminance_nrcodes[k + 1]);
}
for (var l = 0;l <= 161; l++) {
writeByte(std_ac_luminance_values[l]);
}
writeByte(1);
for (var m = 0;m < 16; m++) {
writeByte(std_dc_chrominance_nrcodes[m + 1]);
}
for (var n = 0;n <= 11; n++) {
writeByte(std_dc_chrominance_values[n]);
}
writeByte(17);
for (var o = 0;o < 16; o++) {
writeByte(std_ac_chrominance_nrcodes[o + 1]);
}
for (var p = 0;p <= 161; p++) {
writeByte(std_ac_chrominance_values[p]);
}
}
function writeCOM(comments) {
if (typeof comments === "undefined" || comments.constructor !== Array)
return;
comments.forEach((e) => {
if (typeof e !== "string")
return;
writeWord(65534);
var l = e.length;
writeWord(l + 2);
var i;
for (i = 0;i < l; i++)
writeByte(e.charCodeAt(i));
});
}
function writeSOS() {
writeWord(65498);
writeWord(12);
writeByte(3);
writeByte(1);
writeByte(0);
writeByte(2);
writeByte(17);
writeByte(3);
writeByte(17);
writeByte(0);
writeByte(63);
writeByte(0);
}
function processDU(CDU, fdtbl, DC, HTDC, HTAC) {
var EOB = HTAC[0];
var M16zeroes = HTAC[240];
var pos;
var I16 = 16;
var I63 = 63;
var I64 = 64;
var DU_DCT = fDCTQuant(CDU, fdtbl);
for (var j = 0;j < I64; ++j) {
DU[ZigZag[j]] = DU_DCT[j];
}
var Diff = DU[0] - DC;
DC = DU[0];
if (Diff == 0) {
writeBits(HTDC[0]);
} else {
pos = 32767 + Diff;
writeBits(HTDC[category[pos]]);
writeBits(bitcode[pos]);
}
var end0pos = 63;
for (;end0pos > 0 && DU[end0pos] == 0; end0pos--) {}
if (end0pos == 0) {
writeBits(EOB);
return DC;
}
var i = 1;
var lng;
while (i <= end0pos) {
var startpos = i;
for (;DU[i] == 0 && i <= end0pos; ++i) {}
var nrzeroes = i - startpos;
if (nrzeroes >= I16) {
lng = nrzeroes >> 4;
for (var nrmarker = 1;nrmarker <= lng; ++nrmarker)
writeBits(M16zeroes);
nrzeroes = nrzeroes & 15;
}
pos = 32767 + DU[i];
writeBits(HTAC[(nrzeroes << 4) + category[pos]]);
writeBits(bitcode[pos]);
i++;
}
if (end0pos != I63) {
writeBits(EOB);
}
return DC;
}
function initCharLookupTable() {
var sfcc = String.fromCharCode;
for (var i = 0;i < 256; i++) {
clt[i] = sfcc(i);
}
}
this.encode = function(image2, quality3) {
var time_start = new Date().getTime();
if (quality3)
setQuality(quality3);
byteout = new Array;
bytenew = 0;
bytepos = 7;
writeWord(65496);
writeAPP0();
writeCOM(image2.comments);
writeAPP1(image2.exifBuffer);
writeDQT();
writeSOF0(image2.width, image2.height);
writeDHT();
writeSOS();
var DCY = 0;
var DCU = 0;
var DCV = 0;
bytenew = 0;
bytepos = 7;
this.encode.displayName = "_encode_";
var imageData = image2.data;
var width = image2.width;
var height = image2.height;
var quadWidth = width * 4;
var tripleWidth = width * 3;
var x, y = 0;
var r, g, b;
var start, p, col, row, pos;
while (y < height) {
x = 0;
while (x < quadWidth) {
start = quadWidth * y + x;
p = start;
col = -1;
row = 0;
for (pos = 0;pos < 64; pos++) {
row = pos >> 3;
col = (pos & 7) * 4;
p = start + row * quadWidth + col;
if (y + row >= height) {
p -= quadWidth * (y + 1 + row - height);
}
if (x + col >= quadWidth) {
p -= x + col - quadWidth + 4;
}
r = imageData[p++];
g = imageData[p++];
b = imageData[p++];
YDU[pos] = (RGB_YUV_TABLE[r] + RGB_YUV_TABLE[g + 256 >> 0] + RGB_YUV_TABLE[b + 512 >> 0] >> 16) - 128;
UDU[pos] = (RGB_YUV_TABLE[r + 768 >> 0] + RGB_YUV_TABLE[g + 1024 >> 0] + RGB_YUV_TABLE[b + 1280 >> 0] >> 16) - 128;
VDU[pos] = (RGB_YUV_TABLE[r + 1280 >> 0] + RGB_YUV_TABLE[g + 1536 >> 0] + RGB_YUV_TABLE[b + 1792 >> 0] >> 16) - 128;
}
DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
x += 32;
}
y += 8;
}
if (bytepos >= 0) {
var fillbits = [];
fillbits[1] = bytepos + 1;
fillbits[0] = (1 << bytepos + 1) - 1;
writeBits(fillbits);
}
writeWord(65497);
if (typeof module === "undefined")
return new Uint8Array(byteout);
return Buffer.from(byteout);
var jpegDataUri = "data:image/jpeg;base64," + btoa(byteout.join(""));
byteout = [];
var duration = new Date().getTime() - time_start;
return jpegDataUri;
};
function setQuality(quality3) {
if (quality3 <= 0) {
quality3 = 1;
}
if (quality3 > 100) {
quality3 = 100;
}
if (currentQuality == quality3)
return;
var sf = 0;
if (quality3 < 50) {
sf = Math.floor(5000 / quality3);
} else {
sf = Math.floor(200 - quality3 * 2);
}
initQuantTables(sf);
currentQuality = quality3;
}
function init() {
var time_start = new Date().getTime();
if (!quality2)
quality2 = 50;
initCharLookupTable();
initHuffmanTbl();
initCategoryNumber();
initRGBYUVTable();
setQuality(quality2);
var duration = new Date().getTime() - time_start;
}
init();
}
if (typeof module !== "undefined") {
module.exports = encode3;
} else if (typeof window !== "undefined") {
window["jpeg-js"] = window["jpeg-js"] || {};
window["jpeg-js"].encode = encode3;
}
function encode3(imgData, qu) {
if (typeof qu === "undefined")
qu = 50;
var encoder = new JPEGEncoder(qu);
var data = encoder.encode(imgData, qu);
return {
data,
width: imgData.width,
height: imgData.height
};
}
});
// ../../node_modules/.bun/jpeg-js@0.4.4/node_modules/jpeg-js/lib/decoder.js
var require_decoder = __commonJS((exports, module) => {
var JpegImage = function jpegImage() {
var dctZigZag = new Int32Array([
0,
1,
8,
16,
9,
2,
3,
10,
17,
24,
32,
25,
18,
11,
4,
5,
12,
19,
26,
33,
40,
48,
41,
34,
27,
20,
13,
6,
7,
14,
21,
28,
35,
42,
49,
56,
57,
50,
43,
36,
29,
22,
15,
23,
30,
37,
44,
51,
58,
59,
52,
45,
38,
31,
39,
46,
53,
60,
61,
54,
47,
55,
62,
63
]);
var dctCos1 = 4017;
var dctSin1 = 799;
var dctCos3 = 3406;
var dctSin3 = 2276;
var dctCos6 = 1567;
var dctSin6 = 3784;
var dctSqrt2 = 5793;
var dctSqrt1d2 = 2896;
function constructor() {}
function buildHuffmanTable(codeLengths, values) {
var k = 0, code = [], i, j, length = 16;
while (length > 0 && !codeLengths[length - 1])
length--;
code.push({ children: [], index: 0 });
var p = code[0], q;
for (i = 0;i < length; i++) {
for (j = 0;j < codeLengths[i]; j++) {
p = code.pop();
p.children[p.index] = values[k];
while (p.index > 0) {
if (code.length === 0)
throw new Error("Could not recreate Huffman Table");
p = code.pop();
}
p.index++;
code.push(p);
while (code.length <= i) {
code.push(q = { children: [], index: 0 });
p.children[p.index] = q.children;
p = q;
}
k++;
}
if (i + 1 < length) {
code.push(q = { children: [], index: 0 });
p.children[p.index] = q.children;
p = q;
}
}
return code[0].children;
}
function decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive, opts) {
var precision = frame.precision;
var samplesPerLine = frame.samplesPerLine;
var scanLines = frame.scanLines;
var mcusPerLine = frame.mcusPerLine;
var progressive = frame.progressive;
var { maxH, maxV } = frame;
var startOffset = offset, bitsData = 0, bitsCount = 0;
function readBit() {
if (bitsCount > 0) {
bitsCount--;
return bitsData >> bitsCount & 1;
}
bitsData = data[offset++];
if (bitsData == 255) {
var nextByte = data[offset++];
if (nextByte) {
throw new Error("unexpected marker: " + (bitsData << 8 | nextByte).toString(16));
}
}
bitsCount = 7;
return bitsData >>> 7;
}
function decodeHuffman(tree) {
var node = tree, bit;
while ((bit = readBit()) !== null) {
node = node[bit];
if (typeof node === "number")
return node;
if (typeof node !== "object")
throw new Error("invalid huffman sequence");
}
return null;
}
function receive(length) {
var n2 = 0;
while (length > 0) {
var bit = readBit();
if (bit === null)
return;
n2 = n2 << 1 | bit;
length--;
}
return n2;
}
function receiveAndExtend(length) {
var n2 = receive(length);
if (n2 >= 1 << length - 1)
return n2;
return n2 + (-1 << length) + 1;
}
function decodeBaseline(component2, zz) {
var t = decodeHuffman(component2.huffmanTableDC);
var diff = t === 0 ? 0 : receiveAndExtend(t);
zz[0] = component2.pred += diff;
var k2 = 1;
while (k2 < 64) {
var rs = decodeHuffman(component2.huffmanTableAC);
var s = rs & 15, r = rs >> 4;
if (s === 0) {
if (r < 15)
break;
k2 += 16;
continue;
}
k2 += r;
var z = dctZigZag[k2];
zz[z] = receiveAndExtend(s);
k2++;
}
}
function decodeDCFirst(component2, zz) {
var t = decodeHuffman(component2.huffmanTableDC);
var diff = t === 0 ? 0 : receiveAndExtend(t) << successive;
zz[0] = component2.pred += diff;
}
function decodeDCSuccessive(component2, zz) {
zz[0] |= readBit() << successive;
}
var eobrun = 0;
function decodeACFirst(component2, zz) {
if (eobrun > 0) {
eobrun--;
return;
}
var k2 = spectralStart, e = spectralEnd;
while (k2 <= e) {
var rs = decodeHuffman(component2.huffmanTableAC);
var s = rs & 15, r = rs >> 4;
if (s === 0) {
if (r < 15) {
eobrun = receive(r) + (1 << r) - 1;
break;
}
k2 += 16;
continue;
}
k2 += r;
var z = dctZigZag[k2];
zz[z] = receiveAndExtend(s) * (1 << successive);
k2++;
}
}
var successiveACState = 0, successiveACNextValue;
function decodeACSuccessive(component2, zz) {
var k2 = spectralStart, e = spectralEnd, r = 0;
while (k2 <= e) {
var z = dctZigZag[k2];
var direction = zz[z] < 0 ? -1 : 1;
switch (successiveACState) {
case 0:
var rs = decodeHuffman(component2.huffmanTableAC);
var s = rs & 15, r = rs >> 4;
if (s === 0) {
if (r < 15) {
eobrun = receive(r) + (1 << r);
successiveACState = 4;
} else {
r = 16;
successiveACState = 1;
}
} else {
if (s !== 1)
throw new Error("invalid ACn encoding");
successiveACNextValue = receiveAndExtend(s);
successiveACState = r ? 2 : 3;
}
continue;
case 1:
case 2:
if (zz[z])
zz[z] += (readBit() << successive) * direction;
else {
r--;
if (r === 0)
successiveACState = successiveACState == 2 ? 3 : 0;
}
break;
case 3:
if (zz[z])
zz[z] += (readBit() << successive) * direction;
else {
zz[z] = successiveACNextValue << successive;
successiveACState = 0;
}
break;
case 4:
if (zz[z])
zz[z] += (readBit() << successive) * direction;
break;
}
k2++;
}
if (successiveACState === 4) {
eobrun--;
if (eobrun === 0)
successiveACState = 0;
}
}
function decodeMcu(component2, decode4, mcu2, row, col) {
var mcuRow = mcu2 / mcusPerLine | 0;
var mcuCol = mcu2 % mcusPerLine;
var blockRow = mcuRow * component2.v + row;
var blockCol = mcuCol * component2.h + col;
if (component2.blocks[blockRow] === undefined && opts.tolerantDecoding)
return;
decode4(component2, component2.blocks[blockRow][blockCol]);
}
function decodeBlock(component2, decode4, mcu2) {
var blockRow = mcu2 / component2.blocksPerLine | 0;
var blockCol = mcu2 % component2.blocksPerLine;
if (component2.blocks[blockRow] === undefined && opts.tolerantDecoding)
return;
decode4(component2, component2.blocks[blockRow][blockCol]);
}
var componentsLength = components.length;
var component, i, j, k, n;
var decodeFn;
if (progressive) {
if (spectralStart === 0)
decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
else
decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
} else {
decodeFn = decodeBaseline;
}
var mcu = 0, marker;
var mcuExpected;
if (componentsLength == 1) {
mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
} else {
mcuExpected = mcusPerLine * frame.mcusPerColumn;
}
if (!resetInterval)
resetInterval = mcuExpected;
var h, v;
while (mcu < mcuExpected) {
for (i = 0;i < componentsLength; i++)
components[i].pred = 0;
eobrun = 0;
if (componentsLength == 1) {
component = components[0];
for (n = 0;n < resetInterval; n++) {
decodeBlock(component, decodeFn, mcu);
mcu++;
}
} else {
for (n = 0;n < resetInterval; n++) {
for (i = 0;i < componentsLength; i++) {
component = components[i];
h = component.h;
v = component.v;
for (j = 0;j < v; j++) {
for (k = 0;k < h; k++) {
decodeMcu(component, decodeFn, mcu, j, k);
}
}
}
mcu++;
if (mcu === mcuExpected)
break;
}
}
if (mcu === mcuExpected) {
do {
if (data[offset] === 255) {
if (data[offset + 1] !== 0) {
break;
}
}
offset += 1;
} while (offset < data.length - 2);
}
bitsCount = 0;
marker = data[offset] << 8 | data[offset + 1];
if (marker < 65280) {
throw new Error("marker was not found");
}
if (marker >= 65488 && marker <= 65495) {
offset += 2;
} else
break;
}
return offset - startOffset;
}
function buildComponentData(frame, component) {
var lines = [];
var blocksPerLine = component.blocksPerLine;
var blocksPerColumn = component.blocksPerColumn;
var samplesPerLine = blocksPerLine << 3;
var R = new Int32Array(64), r = new Uint8Array(64);
function quantizeAndInverse(zz, dataOut, dataIn) {
var qt = component.quantizationTable;
var v0, v1, v2, v3, v4, v5, v6, v7, t;
var p = dataIn;
var i2;
for (i2 = 0;i2 < 64; i2++)
p[i2] = zz[i2] * qt[i2];
for (i2 = 0;i2 < 8; ++i2) {
var row = 8 * i2;
if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && p[7 + row] == 0) {
t = dctSqrt2 * p[0 + row] + 512 >> 10;
p[0 + row] = t;
p[1 + row] = t;
p[2 + row] = t;
p[3 + row] = t;
p[4 + row] = t;
p[5 + row] = t;
p[6 + row] = t;
p[7 + row] = t;
continue;
}
v0 = dctSqrt2 * p[0 + row] + 128 >> 8;
v1 = dctSqrt2 * p[4 + row] + 128 >> 8;
v2 = p[2 + row];
v3 = p[6 + row];
v4 = dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128 >> 8;
v7 = dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128 >> 8;
v5 = p[3 + row] << 4;
v6 = p[5 + row] << 4;
t = v0 - v1 + 1 >> 1;
v0 = v0 + v1 + 1 >> 1;
v1 = t;
t = v2 * dctSin6 + v3 * dctCos6 + 128 >> 8;
v2 = v2 * dctCos6 - v3 * dctSin6 + 128 >> 8;
v3 = t;
t = v4 - v6 + 1 >> 1;
v4 = v4 + v6 + 1 >> 1;
v6 = t;
t = v7 + v5 + 1 >> 1;
v5 = v7 - v5 + 1 >> 1;
v7 = t;
t = v0 - v3 + 1 >> 1;
v0 = v0 + v3 + 1 >> 1;
v3 = t;
t = v1 - v2 + 1 >> 1;
v1 = v1 + v2 + 1 >> 1;
v2 = t;
t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12;
v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12;
v7 = t;
t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12;
v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12;
v6 = t;
p[0 + row] = v0 + v7;
p[7 + row] = v0 - v7;
p[1 + row] = v1 + v6;
p[6 + row] = v1 - v6;
p[2 + row] = v2 + v5;
p[5 + row] = v2 - v5;
p[3 + row] = v3 + v4;
p[4 + row] = v3 - v4;
}
for (i2 = 0;i2 < 8; ++i2) {
var col = i2;
if (p[1 * 8 + col] == 0 && p[2 * 8 + col] == 0 && p[3 * 8 + col] == 0 && p[4 * 8 + col] == 0 && p[5 * 8 + col] == 0 && p[6 * 8 + col] == 0 && p[7 * 8 + col] == 0) {
t = dctSqrt2 * dataIn[i2 + 0] + 8192 >> 14;
p[0 * 8 + col] = t;
p[1 * 8 + col] = t;
p[2 * 8 + col] = t;
p[3 * 8 + col] = t;
p[4 * 8 + col] = t;
p[5 * 8 + col] = t;
p[6 * 8 + col] = t;
p[7 * 8 + col] = t;
continue;
}
v0 = dctSqrt2 * p[0 * 8 + col] + 2048 >> 12;
v1 = dctSqrt2 * p[4 * 8 + col] + 2048 >> 12;
v2 = p[2 * 8 + col];
v3 = p[6 * 8 + col];
v4 = dctSqrt1d2 * (p[1 * 8 + col] - p[7 * 8 + col]) + 2048 >> 12;
v7 = dctSqrt1d2 * (p[1 * 8 + col] + p[7 * 8 + col]) + 2048 >> 12;
v5 = p[3 * 8 + col];
v6 = p[5 * 8 + col];
t = v0 - v1 + 1 >> 1;
v0 = v0 + v1 + 1 >> 1;
v1 = t;
t = v2 * dctSin6 + v3 * dctCos6 + 2048 >> 12;
v2 = v2 * dctCos6 - v3 * dctSin6 + 2048 >> 12;
v3 = t;
t = v4 - v6 + 1 >> 1;
v4 = v4 + v6 + 1 >> 1;
v6 = t;
t = v7 + v5 + 1 >> 1;
v5 = v7 - v5 + 1 >> 1;
v7 = t;
t = v0 - v3 + 1 >> 1;
v0 = v0 + v3 + 1 >> 1;
v3 = t;
t = v1 - v2 + 1 >> 1;
v1 = v1 + v2 + 1 >> 1;
v2 = t;
t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12;
v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12;
v7 = t;
t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12;
v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12;
v6 = t;
p[0 * 8 + col] = v0 + v7;
p[7 * 8 + col] = v0 - v7;
p[1 * 8 + col] = v1 + v6;
p[6 * 8 + col] = v1 - v6;
p[2 * 8 + col] = v2 + v5;
p[5 * 8 + col] = v2 - v5;
p[3 * 8 + col] = v3 + v4;
p[4 * 8 + col] = v3 - v4;
}
for (i2 = 0;i2 < 64; ++i2) {
var sample2 = 128 + (p[i2] + 8 >> 4);
dataOut[i2] = sample2 < 0 ? 0 : sample2 > 255 ? 255 : sample2;
}
}
requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);
var i, j;
for (var blockRow = 0;blockRow < blocksPerColumn; blockRow++) {
var scanLine = blockRow << 3;
for (i = 0;i < 8; i++)
lines.push(new Uint8Array(samplesPerLine));
for (var blockCol = 0;blockCol < blocksPerLine; blockCol++) {
quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);
var offset = 0, sample = blockCol << 3;
for (j = 0;j < 8; j++) {
var line = lines[scanLine + j];
for (i = 0;i < 8; i++)
line[sample + i] = r[offset++];
}
}
}
return lines;
}
function clampTo8bit(a) {
return a < 0 ? 0 : a > 255 ? 255 : a;
}
constructor.prototype = {
load: function load(path) {
var xhr = new XMLHttpRequest;
xhr.open("GET", path, true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
this.parse(data);
if (this.onload)
this.onload();
}.bind(this);
xhr.send(null);
},
parse: function parse(data) {
var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000;
var offset = 0, length = data.length;
function readUint16() {
var value = data[offset] << 8 | data[offset + 1];
offset += 2;
return value;
}
function readDataBlock() {
var length2 = readUint16();
var array = data.subarray(offset, offset + length2 - 2);
offset += array.length;
return array;
}
function prepareComponents(frame2) {
var maxH2 = 1, maxV2 = 1;
var component2, componentId2;
for (componentId2 in frame2.components) {
if (frame2.components.hasOwnProperty(componentId2)) {
component2 = frame2.components[componentId2];
if (maxH2 < component2.h)
maxH2 = component2.h;
if (maxV2 < component2.v)
maxV2 = component2.v;
}
}
var mcusPerLine = Math.ceil(frame2.samplesPerLine / 8 / maxH2);
var mcusPerColumn = Math.ceil(frame2.scanLines / 8 / maxV2);
for (componentId2 in frame2.components) {
if (frame2.components.hasOwnProperty(componentId2)) {
component2 = frame2.components[componentId2];
var blocksPerLine = Math.ceil(Math.ceil(frame2.samplesPerLine / 8) * component2.h / maxH2);
var blocksPerColumn = Math.ceil(Math.ceil(frame2.scanLines / 8) * component2.v / maxV2);
var blocksPerLineForMcu = mcusPerLine * component2.h;
var blocksPerColumnForMcu = mcusPerColumn * component2.v;
var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;
var blocks = [];
requestMemoryAllocation(blocksToAllocate * 256);
for (var i2 = 0;i2 < blocksPerColumnForMcu; i2++) {
var row = [];
for (var j2 = 0;j2 < blocksPerLineForMcu; j2++)
row.push(new Int32Array(64));
blocks.push(row);
}
component2.blocksPerLine = blocksPerLine;
component2.blocksPerColumn = blocksPerColumn;
component2.blocks = blocks;
}
}
frame2.maxH = maxH2;
frame2.maxV = maxV2;
frame2.mcusPerLine = mcusPerLine;
frame2.mcusPerColumn = mcusPerColumn;
}
var jfif = null;
var adobe = null;
var pixels = null;
var frame, resetInterval;
var quantizationTables = [], frames = [];
var huffmanTablesAC = [], huffmanTablesDC = [];
var fileMarker = readUint16();
var malformedDataOffset = -1;
this.comments = [];
if (fileMarker != 65496) {
throw new Error("SOI not found");
}
fileMarker = readUint16();
while (fileMarker != 65497) {
var i, j, l;
switch (fileMarker) {
case 65280:
break;
case 65504:
case 65505:
case 65506:
case 65507:
case 65508:
case 65509:
case 65510:
case 65511:
case 65512:
case 65513:
case 65514:
case 65515:
case 65516:
case 65517:
case 65518:
case 65519:
case 65534:
var appData = readDataBlock();
if (fileMarker === 65534) {
var comment = String.fromCharCode.apply(null, appData);
this.comments.push(comment);
}
if (fileMarker === 65504) {
if (appData[0] === 74 && appData[1] === 70 && appData[2] === 73 && appData[3] === 70 && appData[4] === 0) {
jfif = {
version: { major: appData[5], minor: appData[6] },
densityUnits: appData[7],
xDensity: appData[8] << 8 | appData[9],
yDensity: appData[10] << 8 | appData[11],
thumbWidth: appData[12],
thumbHeight: appData[13],
thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
};
}
}
if (fileMarker === 65505) {
if (appData[0] === 69 && appData[1] === 120 && appData[2] === 105 && appData[3] === 102 && appData[4] === 0) {
this.exifBuffer = appData.subarray(5, appData.length);
}
}
if (fileMarker === 65518) {
if (appData[0] === 65 && appData[1] === 100 && appData[2] === 111 && appData[3] === 98 && appData[4] === 101 && appData[5] === 0) {
adobe = {
version: appData[6],
flags0: appData[7] << 8 | appData[8],
flags1: appData[9] << 8 | appData[10],
transformCode: appData[11]
};
}
}
break;
case 65499:
var quantizationTablesLength = readUint16();
var quantizationTablesEnd = quantizationTablesLength + offset - 2;
while (offset < quantizationTablesEnd) {
var quantizationTableSpec = data[offset++];
requestMemoryAllocation(64 * 4);
var tableData = new Int32Array(64);
if (quantizationTableSpec >> 4 === 0) {
for (j = 0;j < 64; j++) {
var z = dctZigZag[j];
tableData[z] = data[offset++];
}
} else if (quantizationTableSpec >> 4 === 1) {
for (j = 0;j < 64; j++) {
var z = dctZigZag[j];
tableData[z] = readUint16();
}
} else
throw new Error("DQT: invalid table spec");
quantizationTables[quantizationTableSpec & 15] = tableData;
}
break;
case 65472:
case 65473:
case 65474:
readUint16();
frame = {};
frame.extended = fileMarker === 65473;
frame.progressive = fileMarker === 65474;
frame.precision = data[offset++];
frame.scanLines = readUint16();
frame.samplesPerLine = readUint16();
frame.components = {};
frame.componentsOrder = [];
var pixelsInFrame = frame.scanLines * frame.samplesPerLine;
if (pixelsInFrame > maxResolutionInPixels) {
var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);
throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);
}
var componentsCount = data[offset++], componentId;
var maxH = 0, maxV = 0;
for (i = 0;i < componentsCount; i++) {
componentId = data[offset];
var h = data[offset + 1] >> 4;
var v = data[offset + 1] & 15;
var qId = data[offset + 2];
if (h <= 0 || v <= 0) {
throw new Error("Invalid sampling factor, expected values above 0");
}
frame.componentsOrder.push(componentId);
frame.components[componentId] = {
h,
v,
quantizationIdx: qId
};
offset += 3;
}
prepareComponents(frame);
frames.push(frame);
break;
case 65476:
var huffmanLength = readUint16();
for (i = 2;i < huffmanLength; ) {
var huffmanTableSpec = data[offset++];
var codeLengths = new Uint8Array(16);
var codeLengthSum = 0;
for (j = 0;j < 16; j++, offset++) {
codeLengthSum += codeLengths[j] = data[offset];
}
requestMemoryAllocation(16 + codeLengthSum);
var huffmanValues = new Uint8Array(codeLengthSum);
for (j = 0;j < codeLengthSum; j++, offset++)
huffmanValues[j] = data[offset];
i += 17 + codeLengthSum;
(huffmanTableSpec >> 4 === 0 ? huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues);
}
break;
case 65501:
readUint16();
resetInterval = readUint16();
break;
case 65500:
readUint16();
readUint16();
break;
case 65498:
var scanLength = readUint16();
var selectorsCount = data[offset++];
var components = [], component;
for (i = 0;i < selectorsCount; i++) {
component = frame.components[data[offset++]];
var tableSpec = data[offset++];
component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
components.push(component);
}
var spectralStart = data[offset++];
var spectralEnd = data[offset++];
var successiveApproximation = data[offset++];
var processed = decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successiveApproximation >> 4, successiveApproximation & 15, this.opts);
offset += processed;
break;
case 65535:
if (data[offset] !== 255) {
offset--;
}
break;
default:
if (data[offset - 3] == 255 && data[offset - 2] >= 192 && data[offset - 2] <= 254) {
offset -= 3;
break;
} else if (fileMarker === 224 || fileMarker == 225) {
if (malformedDataOffset !== -1) {
throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);
}
malformedDataOffset = offset - 1;
const nextOffset = readUint16();
if (data[offset + nextOffset - 2] === 255) {
offset += nextOffset - 2;
break;
}
}
throw new Error("unknown JPEG marker " + fileMarker.toString(16));
}
fileMarker = readUint16();
}
if (frames.length != 1)
throw new Error("only single frame JPEGs supported");
for (var i = 0;i < frames.length; i++) {
var cp = frames[i].components;
for (var j in cp) {
cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
delete cp[j].quantizationIdx;
}
}
this.width = frame.samplesPerLine;
this.height = frame.scanLines;
this.jfif = jfif;
this.adobe = adobe;
this.components = [];
for (var i = 0;i < frame.componentsOrder.length; i++) {
var component = frame.components[frame.componentsOrder[i]];
this.components.push({
lines: buildComponentData(frame, component),
scaleX: component.h / frame.maxH,
scaleY: component.v / frame.maxV
});
}
},
getData: function getData(width, height) {
var scaleX = this.width / width, scaleY = this.height / height;
var component1, component2, component3, component4;
var component1Line, component2Line, component3Line, component4Line;
var x, y;
var offset = 0;
var Y, Cb, Cr, K, C, M, Ye, R, G, B;
var colorTransform;
var dataLength = width * height * this.components.length;
requestMemoryAllocation(dataLength);
var data = new Uint8Array(dataLength);
switch (this.components.length) {
case 1:
component1 = this.components[0];
for (y = 0;y < height; y++) {
component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
for (x = 0;x < width; x++) {
Y = component1Line[0 | x * component1.scaleX * scaleX];
data[offset++] = Y;
}
}
break;
case 2:
component1 = this.components[0];
component2 = this.components[1];
for (y = 0;y < height; y++) {
component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
for (x = 0;x < width; x++) {
Y = component1Line[0 | x * component1.scaleX * scaleX];
data[offset++] = Y;
Y = component2Line[0 | x * component2.scaleX * scaleX];
data[offset++] = Y;
}
}
break;
case 3:
colorTransform = true;
if (this.adobe && this.adobe.transformCode)
colorTransform = true;
else if (typeof this.opts.colorTransform !== "undefined")
colorTransform = !!this.opts.colorTransform;
component1 = this.components[0];
component2 = this.components[1];
component3 = this.components[2];
for (y = 0;y < height; y++) {
component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
component3Line = component3.lines[0 | y * component3.scaleY * scaleY];
for (x = 0;x < width; x++) {
if (!colorTransform) {
R = component1Line[0 | x * component1.scaleX * scaleX];
G = component2Line[0 | x * component2.scaleX * scaleX];
B = component3Line[0 | x * component3.scaleX * scaleX];
} else {
Y = component1Line[0 | x * component1.scaleX * scaleX];
Cb = component2Line[0 | x * component2.scaleX * scaleX];
Cr = component3Line[0 | x * component3.scaleX * scaleX];
R = clampTo8bit(Y + 1.402 * (Cr - 128));
G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
B = clampTo8bit(Y + 1.772 * (Cb - 128));
}
data[offset++] = R;
data[offset++] = G;
data[offset++] = B;
}
}
break;
case 4:
if (!this.adobe)
throw new Error("Unsupported color mode (4 components)");
colorTransform = false;
if (this.adobe && this.adobe.transformCode)
colorTransform = true;
else if (typeof this.opts.colorTransform !== "undefined")
colorTransform = !!this.opts.colorTransform;
component1 = this.components[0];
component2 = this.components[1];
component3 = this.components[2];
component4 = this.components[3];
for (y = 0;y < height; y++) {
component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
component3Line = component3.lines[0 | y * component3.scaleY * scaleY];
component4Line = component4.lines[0 | y * component4.scaleY * scaleY];
for (x = 0;x < width; x++) {
if (!colorTransform) {
C = component1Line[0 | x * component1.scaleX * scaleX];
M = component2Line[0 | x * component2.scaleX * scaleX];
Ye = component3Line[0 | x * component3.scaleX * scaleX];
K = component4Line[0 | x * component4.scaleX * scaleX];
} else {
Y = component1Line[0 | x * component1.scaleX * scaleX];
Cb = component2Line[0 | x * component2.scaleX * scaleX];
Cr = component3Line[0 | x * component3.scaleX * scaleX];
K = component4Line[0 | x * component4.scaleX * scaleX];
C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));
M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));
}
data[offset++] = 255 - C;
data[offset++] = 255 - M;
data[offset++] = 255 - Ye;
data[offset++] = 255 - K;
}
}
break;
default:
throw new Error("Unsupported color mode");
}
return data;
},
copyToImageData: function copyToImageData(imageData, formatAsRGBA) {
var { width, height } = imageData;
var imageDataArray = imageData.data;
var data = this.getData(width, height);
var i = 0, j = 0, x, y;
var Y, K, C, M, R, G, B;
switch (this.components.length) {
case 1:
for (y = 0;y < height; y++) {
for (x = 0;x < width; x++) {
Y = data[i++];
imageDataArray[j++] = Y;
imageDataArray[j++] = Y;
imageDataArray[j++] = Y;
if (formatAsRGBA) {
imageDataArray[j++] = 255;
}
}
}
break;
case 3:
for (y = 0;y < height; y++) {
for (x = 0;x < width; x++) {
R = data[i++];
G = data[i++];
B = data[i++];
imageDataArray[j++] = R;
imageDataArray[j++] = G;
imageDataArray[j++] = B;
if (formatAsRGBA) {
imageDataArray[j++] = 255;
}
}
}
break;
case 4:
for (y = 0;y < height; y++) {
for (x = 0;x < width; x++) {
C = data[i++];
M = data[i++];
Y = data[i++];
K = data[i++];
R = 255 - clampTo8bit(C * (1 - K / 255) + K);
G = 255 - clampTo8bit(M * (1 - K / 255) + K);
B = 255 - clampTo8bit(Y * (1 - K / 255) + K);
imageDataArray[j++] = R;
imageDataArray[j++] = G;
imageDataArray[j++] = B;
if (formatAsRGBA) {
imageDataArray[j++] = 255;
}
}
}
break;
default:
throw new Error("Unsupported color mode");
}
}
};
var totalBytesAllocated = 0;
var maxMemoryUsageBytes = 0;
function requestMemoryAllocation(increaseAmount = 0) {
var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;
if (totalMemoryImpactBytes > maxMemoryUsageBytes) {
var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);
throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`);
}
totalBytesAllocated = totalMemoryImpactBytes;
}
constructor.resetMaxMemoryUsage = function(maxMemoryUsageBytes_) {
totalBytesAllocated = 0;
maxMemoryUsageBytes = maxMemoryUsageBytes_;
};
constructor.getBytesAllocated = function() {
return totalBytesAllocated;
};
constructor.requestMemoryAllocation = requestMemoryAllocation;
return constructor;
}();
if (typeof module !== "undefined") {
module.exports = decode3;
} else if (typeof window !== "undefined") {
window["jpeg-js"] = window["jpeg-js"] || {};
window["jpeg-js"].decode = decode3;
}
function decode3(jpegData, userOpts = {}) {
var defaultOpts = {
colorTransform: undefined,
useTArray: false,
formatAsRGBA: true,
tolerantDecoding: true,
maxResolutionInMP: 100,
maxMemoryUsageInMB: 512
};
var opts = { ...defaultOpts, ...userOpts };
var arr = new Uint8Array(jpegData);
var decoder = new JpegImage;
decoder.opts = opts;
JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024);
decoder.parse(arr);
var channels = opts.formatAsRGBA ? 4 : 3;
var bytesNeeded = decoder.width * decoder.height * channels;
try {
JpegImage.requestMemoryAllocation(bytesNeeded);
var image2 = {
width: decoder.width,
height: decoder.height,
exifBuffer: decoder.exifBuffer,
data: opts.useTArray ? new Uint8Array(bytesNeeded) : Buffer.alloc(bytesNeeded)
};
if (decoder.comments.length > 0) {
image2["comments"] = decoder.comments;
}
} catch (err) {
if (err instanceof RangeError) {
throw new Error("Could not allocate enough memory for the image. " + "Required: " + bytesNeeded);
}
if (err instanceof ReferenceError) {
if (err.message === "Buffer is not defined") {
throw new Error("Buffer is not globally defined in this environment. " + "Consider setting useTArray to true");
}
}
throw err;
}
decoder.copyToImageData(image2, opts.formatAsRGBA);
return image2;
}
});
// ../../node_modules/.bun/jpeg-js@0.4.4/node_modules/jpeg-js/index.js
var require_jpeg_js = __commonJS((exports, module) => {
var encode3 = require_encoder();
var decode3 = require_decoder();
module.exports = {
encode: encode3,
decode: decode3
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/chunkstream.js
var require_chunkstream = __commonJS((exports, module) => {
var util = __require("util");
var Stream = __require("stream");
var ChunkStream = module.exports = function() {
Stream.call(this);
this._buffers = [];
this._buffered = 0;
this._reads = [];
this._paused = false;
this._encoding = "utf8";
this.writable = true;
};
util.inherits(ChunkStream, Stream);
ChunkStream.prototype.read = function(length, callback) {
this._reads.push({
length: Math.abs(length),
allowLess: length < 0,
func: callback
});
process.nextTick(function() {
this._process();
if (this._paused && this._reads && this._reads.length > 0) {
this._paused = false;
this.emit("drain");
}
}.bind(this));
};
ChunkStream.prototype.write = function(data, encoding) {
if (!this.writable) {
this.emit("error", new Error("Stream not writable"));
return false;
}
let dataBuffer;
if (Buffer.isBuffer(data)) {
dataBuffer = data;
} else {
dataBuffer = Buffer.from(data, encoding || this._encoding);
}
this._buffers.push(dataBuffer);
this._buffered += dataBuffer.length;
this._process();
if (this._reads && this._reads.length === 0) {
this._paused = true;
}
return this.writable && !this._paused;
};
ChunkStream.prototype.end = function(data, encoding) {
if (data) {
this.write(data, encoding);
}
this.writable = false;
if (!this._buffers) {
return;
}
if (this._buffers.length === 0) {
this._end();
} else {
this._buffers.push(null);
this._process();
}
};
ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
ChunkStream.prototype._end = function() {
if (this._reads.length > 0) {
this.emit("error", new Error("Unexpected end of input"));
}
this.destroy();
};
ChunkStream.prototype.destroy = function() {
if (!this._buffers) {
return;
}
this.writable = false;
this._reads = null;
this._buffers = null;
this.emit("close");
};
ChunkStream.prototype._processReadAllowingLess = function(read) {
this._reads.shift();
let smallerBuf = this._buffers[0];
if (smallerBuf.length > read.length) {
this._buffered -= read.length;
this._buffers[0] = smallerBuf.slice(read.length);
read.func.call(this, smallerBuf.slice(0, read.length));
} else {
this._buffered -= smallerBuf.length;
this._buffers.shift();
read.func.call(this, smallerBuf);
}
};
ChunkStream.prototype._processRead = function(read) {
this._reads.shift();
let pos = 0;
let count = 0;
let data = Buffer.alloc(read.length);
while (pos < read.length) {
let buf = this._buffers[count++];
let len = Math.min(buf.length, read.length - pos);
buf.copy(data, pos, 0, len);
pos += len;
if (len !== buf.length) {
this._buffers[--count] = buf.slice(len);
}
}
if (count > 0) {
this._buffers.splice(0, count);
}
this._buffered -= read.length;
read.func.call(this, data);
};
ChunkStream.prototype._process = function() {
try {
while (this._buffered > 0 && this._reads && this._reads.length > 0) {
let read = this._reads[0];
if (read.allowLess) {
this._processReadAllowingLess(read);
} else if (this._buffered >= read.length) {
this._processRead(read);
} else {
break;
}
}
if (this._buffers && !this.writable) {
this._end();
}
} catch (ex) {
this.emit("error", ex);
}
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/interlace.js
var require_interlace = __commonJS((exports) => {
var imagePasses = [
{
x: [0],
y: [0]
},
{
x: [4],
y: [0]
},
{
x: [0, 4],
y: [4]
},
{
x: [2, 6],
y: [0, 4]
},
{
x: [0, 2, 4, 6],
y: [2, 6]
},
{
x: [1, 3, 5, 7],
y: [0, 2, 4, 6]
},
{
x: [0, 1, 2, 3, 4, 5, 6, 7],
y: [1, 3, 5, 7]
}
];
exports.getImagePasses = function(width, height) {
let images = [];
let xLeftOver = width % 8;
let yLeftOver = height % 8;
let xRepeats = (width - xLeftOver) / 8;
let yRepeats = (height - yLeftOver) / 8;
for (let i = 0;i < imagePasses.length; i++) {
let pass = imagePasses[i];
let passWidth = xRepeats * pass.x.length;
let passHeight = yRepeats * pass.y.length;
for (let j = 0;j < pass.x.length; j++) {
if (pass.x[j] < xLeftOver) {
passWidth++;
} else {
break;
}
}
for (let j = 0;j < pass.y.length; j++) {
if (pass.y[j] < yLeftOver) {
passHeight++;
} else {
break;
}
}
if (passWidth > 0 && passHeight > 0) {
images.push({ width: passWidth, height: passHeight, index: i });
}
}
return images;
};
exports.getInterlaceIterator = function(width) {
return function(x, y, pass) {
let outerXLeftOver = x % imagePasses[pass].x.length;
let outerX = (x - outerXLeftOver) / imagePasses[pass].x.length * 8 + imagePasses[pass].x[outerXLeftOver];
let outerYLeftOver = y % imagePasses[pass].y.length;
let outerY = (y - outerYLeftOver) / imagePasses[pass].y.length * 8 + imagePasses[pass].y[outerYLeftOver];
return outerX * 4 + outerY * width * 4;
};
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/paeth-predictor.js
var require_paeth_predictor = __commonJS((exports, module) => {
module.exports = function paethPredictor(left, above, upLeft) {
let paeth = left + above - upLeft;
let pLeft = Math.abs(paeth - left);
let pAbove = Math.abs(paeth - above);
let pUpLeft = Math.abs(paeth - upLeft);
if (pLeft <= pAbove && pLeft <= pUpLeft) {
return left;
}
if (pAbove <= pUpLeft) {
return above;
}
return upLeft;
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/filter-parse.js
var require_filter_parse = __commonJS((exports, module) => {
var interlaceUtils = require_interlace();
var paethPredictor = require_paeth_predictor();
function getByteWidth(width, bpp, depth) {
let byteWidth = width * bpp;
if (depth !== 8) {
byteWidth = Math.ceil(byteWidth / (8 / depth));
}
return byteWidth;
}
var Filter = module.exports = function(bitmapInfo, dependencies) {
let width = bitmapInfo.width;
let height = bitmapInfo.height;
let interlace = bitmapInfo.interlace;
let bpp = bitmapInfo.bpp;
let depth = bitmapInfo.depth;
this.read = dependencies.read;
this.write = dependencies.write;
this.complete = dependencies.complete;
this._imageIndex = 0;
this._images = [];
if (interlace) {
let passes = interlaceUtils.getImagePasses(width, height);
for (let i = 0;i < passes.length; i++) {
this._images.push({
byteWidth: getByteWidth(passes[i].width, bpp, depth),
height: passes[i].height,
lineIndex: 0
});
}
} else {
this._images.push({
byteWidth: getByteWidth(width, bpp, depth),
height,
lineIndex: 0
});
}
if (depth === 8) {
this._xComparison = bpp;
} else if (depth === 16) {
this._xComparison = bpp * 2;
} else {
this._xComparison = 1;
}
};
Filter.prototype.start = function() {
this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this));
};
Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
let xComparison = this._xComparison;
let xBiggerThan = xComparison - 1;
for (let x = 0;x < byteWidth; x++) {
let rawByte = rawData[1 + x];
let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
unfilteredLine[x] = rawByte + f1Left;
}
};
Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
let lastLine = this._lastLine;
for (let x = 0;x < byteWidth; x++) {
let rawByte = rawData[1 + x];
let f2Up = lastLine ? lastLine[x] : 0;
unfilteredLine[x] = rawByte + f2Up;
}
};
Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
let xComparison = this._xComparison;
let xBiggerThan = xComparison - 1;
let lastLine = this._lastLine;
for (let x = 0;x < byteWidth; x++) {
let rawByte = rawData[1 + x];
let f3Up = lastLine ? lastLine[x] : 0;
let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
let f3Add = Math.floor((f3Left + f3Up) / 2);
unfilteredLine[x] = rawByte + f3Add;
}
};
Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
let xComparison = this._xComparison;
let xBiggerThan = xComparison - 1;
let lastLine = this._lastLine;
for (let x = 0;x < byteWidth; x++) {
let rawByte = rawData[1 + x];
let f4Up = lastLine ? lastLine[x] : 0;
let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
unfilteredLine[x] = rawByte + f4Add;
}
};
Filter.prototype._reverseFilterLine = function(rawData) {
let filter = rawData[0];
let unfilteredLine;
let currentImage = this._images[this._imageIndex];
let byteWidth = currentImage.byteWidth;
if (filter === 0) {
unfilteredLine = rawData.slice(1, byteWidth + 1);
} else {
unfilteredLine = Buffer.alloc(byteWidth);
switch (filter) {
case 1:
this._unFilterType1(rawData, unfilteredLine, byteWidth);
break;
case 2:
this._unFilterType2(rawData, unfilteredLine, byteWidth);
break;
case 3:
this._unFilterType3(rawData, unfilteredLine, byteWidth);
break;
case 4:
this._unFilterType4(rawData, unfilteredLine, byteWidth);
break;
default:
throw new Error("Unrecognised filter type - " + filter);
}
}
this.write(unfilteredLine);
currentImage.lineIndex++;
if (currentImage.lineIndex >= currentImage.height) {
this._lastLine = null;
this._imageIndex++;
currentImage = this._images[this._imageIndex];
} else {
this._lastLine = unfilteredLine;
}
if (currentImage) {
this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
} else {
this._lastLine = null;
this.complete();
}
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/filter-parse-async.js
var require_filter_parse_async = __commonJS((exports, module) => {
var util = __require("util");
var ChunkStream = require_chunkstream();
var Filter = require_filter_parse();
var FilterAsync = module.exports = function(bitmapInfo) {
ChunkStream.call(this);
let buffers = [];
let that = this;
this._filter = new Filter(bitmapInfo, {
read: this.read.bind(this),
write: function(buffer) {
buffers.push(buffer);
},
complete: function() {
that.emit("complete", Buffer.concat(buffers));
}
});
this._filter.start();
};
util.inherits(FilterAsync, ChunkStream);
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/constants.js
var require_constants = __commonJS((exports, module) => {
module.exports = {
PNG_SIGNATURE: [137, 80, 78, 71, 13, 10, 26, 10],
TYPE_IHDR: 1229472850,
TYPE_IEND: 1229278788,
TYPE_IDAT: 1229209940,
TYPE_PLTE: 1347179589,
TYPE_tRNS: 1951551059,
TYPE_gAMA: 1732332865,
COLORTYPE_GRAYSCALE: 0,
COLORTYPE_PALETTE: 1,
COLORTYPE_COLOR: 2,
COLORTYPE_ALPHA: 4,
COLORTYPE_PALETTE_COLOR: 3,
COLORTYPE_COLOR_ALPHA: 6,
COLORTYPE_TO_BPP_MAP: {
0: 1,
2: 3,
3: 1,
4: 2,
6: 4
},
GAMMA_DIVISION: 1e5
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/crc.js
var require_crc = __commonJS((exports, module) => {
var crcTable = [];
(function() {
for (let i = 0;i < 256; i++) {
let currentCrc = i;
for (let j = 0;j < 8; j++) {
if (currentCrc & 1) {
currentCrc = 3988292384 ^ currentCrc >>> 1;
} else {
currentCrc = currentCrc >>> 1;
}
}
crcTable[i] = currentCrc;
}
})();
var CrcCalculator = module.exports = function() {
this._crc = -1;
};
CrcCalculator.prototype.write = function(data) {
for (let i = 0;i < data.length; i++) {
this._crc = crcTable[(this._crc ^ data[i]) & 255] ^ this._crc >>> 8;
}
return true;
};
CrcCalculator.prototype.crc32 = function() {
return this._crc ^ -1;
};
CrcCalculator.crc32 = function(buf) {
let crc = -1;
for (let i = 0;i < buf.length; i++) {
crc = crcTable[(crc ^ buf[i]) & 255] ^ crc >>> 8;
}
return crc ^ -1;
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/parser.js
var require_parser = __commonJS((exports, module) => {
var constants2 = require_constants();
var CrcCalculator = require_crc();
var Parser = module.exports = function(options, dependencies) {
this._options = options;
options.checkCRC = options.checkCRC !== false;
this._hasIHDR = false;
this._hasIEND = false;
this._emittedHeadersFinished = false;
this._palette = [];
this._colorType = 0;
this._chunks = {};
this._chunks[constants2.TYPE_IHDR] = this._handleIHDR.bind(this);
this._chunks[constants2.TYPE_IEND] = this._handleIEND.bind(this);
this._chunks[constants2.TYPE_IDAT] = this._handleIDAT.bind(this);
this._chunks[constants2.TYPE_PLTE] = this._handlePLTE.bind(this);
this._chunks[constants2.TYPE_tRNS] = this._handleTRNS.bind(this);
this._chunks[constants2.TYPE_gAMA] = this._handleGAMA.bind(this);
this.read = dependencies.read;
this.error = dependencies.error;
this.metadata = dependencies.metadata;
this.gamma = dependencies.gamma;
this.transColor = dependencies.transColor;
this.palette = dependencies.palette;
this.parsed = dependencies.parsed;
this.inflateData = dependencies.inflateData;
this.finished = dependencies.finished;
this.simpleTransparency = dependencies.simpleTransparency;
this.headersFinished = dependencies.headersFinished || function() {};
};
Parser.prototype.start = function() {
this.read(constants2.PNG_SIGNATURE.length, this._parseSignature.bind(this));
};
Parser.prototype._parseSignature = function(data) {
let signature = constants2.PNG_SIGNATURE;
for (let i = 0;i < signature.length; i++) {
if (data[i] !== signature[i]) {
this.error(new Error("Invalid file signature"));
return;
}
}
this.read(8, this._parseChunkBegin.bind(this));
};
Parser.prototype._parseChunkBegin = function(data) {
let length = data.readUInt32BE(0);
let type = data.readUInt32BE(4);
let name = "";
for (let i = 4;i < 8; i++) {
name += String.fromCharCode(data[i]);
}
let ancillary = Boolean(data[4] & 32);
if (!this._hasIHDR && type !== constants2.TYPE_IHDR) {
this.error(new Error("Expected IHDR on beggining"));
return;
}
this._crc = new CrcCalculator;
this._crc.write(Buffer.from(name));
if (this._chunks[type]) {
return this._chunks[type](length);
}
if (!ancillary) {
this.error(new Error("Unsupported critical chunk type " + name));
return;
}
this.read(length + 4, this._skipChunk.bind(this));
};
Parser.prototype._skipChunk = function() {
this.read(8, this._parseChunkBegin.bind(this));
};
Parser.prototype._handleChunkEnd = function() {
this.read(4, this._parseChunkEnd.bind(this));
};
Parser.prototype._parseChunkEnd = function(data) {
let fileCrc = data.readInt32BE(0);
let calcCrc = this._crc.crc32();
if (this._options.checkCRC && calcCrc !== fileCrc) {
this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc));
return;
}
if (!this._hasIEND) {
this.read(8, this._parseChunkBegin.bind(this));
}
};
Parser.prototype._handleIHDR = function(length) {
this.read(length, this._parseIHDR.bind(this));
};
Parser.prototype._parseIHDR = function(data) {
this._crc.write(data);
let width = data.readUInt32BE(0);
let height = data.readUInt32BE(4);
let depth = data[8];
let colorType = data[9];
let compr = data[10];
let filter = data[11];
let interlace = data[12];
if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
this.error(new Error("Unsupported bit depth " + depth));
return;
}
if (!(colorType in constants2.COLORTYPE_TO_BPP_MAP)) {
this.error(new Error("Unsupported color type"));
return;
}
if (compr !== 0) {
this.error(new Error("Unsupported compression method"));
return;
}
if (filter !== 0) {
this.error(new Error("Unsupported filter method"));
return;
}
if (interlace !== 0 && interlace !== 1) {
this.error(new Error("Unsupported interlace method"));
return;
}
this._colorType = colorType;
let bpp = constants2.COLORTYPE_TO_BPP_MAP[this._colorType];
this._hasIHDR = true;
this.metadata({
width,
height,
depth,
interlace: Boolean(interlace),
palette: Boolean(colorType & constants2.COLORTYPE_PALETTE),
color: Boolean(colorType & constants2.COLORTYPE_COLOR),
alpha: Boolean(colorType & constants2.COLORTYPE_ALPHA),
bpp,
colorType
});
this._handleChunkEnd();
};
Parser.prototype._handlePLTE = function(length) {
this.read(length, this._parsePLTE.bind(this));
};
Parser.prototype._parsePLTE = function(data) {
this._crc.write(data);
let entries = Math.floor(data.length / 3);
for (let i = 0;i < entries; i++) {
this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 255]);
}
this.palette(this._palette);
this._handleChunkEnd();
};
Parser.prototype._handleTRNS = function(length) {
this.simpleTransparency();
this.read(length, this._parseTRNS.bind(this));
};
Parser.prototype._parseTRNS = function(data) {
this._crc.write(data);
if (this._colorType === constants2.COLORTYPE_PALETTE_COLOR) {
if (this._palette.length === 0) {
this.error(new Error("Transparency chunk must be after palette"));
return;
}
if (data.length > this._palette.length) {
this.error(new Error("More transparent colors than palette size"));
return;
}
for (let i = 0;i < data.length; i++) {
this._palette[i][3] = data[i];
}
this.palette(this._palette);
}
if (this._colorType === constants2.COLORTYPE_GRAYSCALE) {
this.transColor([data.readUInt16BE(0)]);
}
if (this._colorType === constants2.COLORTYPE_COLOR) {
this.transColor([
data.readUInt16BE(0),
data.readUInt16BE(2),
data.readUInt16BE(4)
]);
}
this._handleChunkEnd();
};
Parser.prototype._handleGAMA = function(length) {
this.read(length, this._parseGAMA.bind(this));
};
Parser.prototype._parseGAMA = function(data) {
this._crc.write(data);
this.gamma(data.readUInt32BE(0) / constants2.GAMMA_DIVISION);
this._handleChunkEnd();
};
Parser.prototype._handleIDAT = function(length) {
if (!this._emittedHeadersFinished) {
this._emittedHeadersFinished = true;
this.headersFinished();
}
this.read(-length, this._parseIDAT.bind(this, length));
};
Parser.prototype._parseIDAT = function(length, data) {
this._crc.write(data);
if (this._colorType === constants2.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
throw new Error("Expected palette not found");
}
this.inflateData(data);
let leftOverLength = length - data.length;
if (leftOverLength > 0) {
this._handleIDAT(leftOverLength);
} else {
this._handleChunkEnd();
}
};
Parser.prototype._handleIEND = function(length) {
this.read(length, this._parseIEND.bind(this));
};
Parser.prototype._parseIEND = function(data) {
this._crc.write(data);
this._hasIEND = true;
this._handleChunkEnd();
if (this.finished) {
this.finished();
}
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/bitmapper.js
var require_bitmapper = __commonJS((exports) => {
var interlaceUtils = require_interlace();
var pixelBppMapper = [
function() {},
function(pxData, data, pxPos, rawPos) {
if (rawPos === data.length) {
throw new Error("Ran out of data");
}
let pixel = data[rawPos];
pxData[pxPos] = pixel;
pxData[pxPos + 1] = pixel;
pxData[pxPos + 2] = pixel;
pxData[pxPos + 3] = 255;
},
function(pxData, data, pxPos, rawPos) {
if (rawPos + 1 >= data.length) {
throw new Error("Ran out of data");
}
let pixel = data[rawPos];
pxData[pxPos] = pixel;
pxData[pxPos + 1] = pixel;
pxData[pxPos + 2] = pixel;
pxData[pxPos + 3] = data[rawPos + 1];
},
function(pxData, data, pxPos, rawPos) {
if (rawPos + 2 >= data.length) {
throw new Error("Ran out of data");
}
pxData[pxPos] = data[rawPos];
pxData[pxPos + 1] = data[rawPos + 1];
pxData[pxPos + 2] = data[rawPos + 2];
pxData[pxPos + 3] = 255;
},
function(pxData, data, pxPos, rawPos) {
if (rawPos + 3 >= data.length) {
throw new Error("Ran out of data");
}
pxData[pxPos] = data[rawPos];
pxData[pxPos + 1] = data[rawPos + 1];
pxData[pxPos + 2] = data[rawPos + 2];
pxData[pxPos + 3] = data[rawPos + 3];
}
];
var pixelBppCustomMapper = [
function() {},
function(pxData, pixelData, pxPos, maxBit) {
let pixel = pixelData[0];
pxData[pxPos] = pixel;
pxData[pxPos + 1] = pixel;
pxData[pxPos + 2] = pixel;
pxData[pxPos + 3] = maxBit;
},
function(pxData, pixelData, pxPos) {
let pixel = pixelData[0];
pxData[pxPos] = pixel;
pxData[pxPos + 1] = pixel;
pxData[pxPos + 2] = pixel;
pxData[pxPos + 3] = pixelData[1];
},
function(pxData, pixelData, pxPos, maxBit) {
pxData[pxPos] = pixelData[0];
pxData[pxPos + 1] = pixelData[1];
pxData[pxPos + 2] = pixelData[2];
pxData[pxPos + 3] = maxBit;
},
function(pxData, pixelData, pxPos) {
pxData[pxPos] = pixelData[0];
pxData[pxPos + 1] = pixelData[1];
pxData[pxPos + 2] = pixelData[2];
pxData[pxPos + 3] = pixelData[3];
}
];
function bitRetriever(data, depth) {
let leftOver = [];
let i = 0;
function split() {
if (i === data.length) {
throw new Error("Ran out of data");
}
let byte = data[i];
i++;
let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
switch (depth) {
default:
throw new Error("unrecognised depth");
case 16:
byte2 = data[i];
i++;
leftOver.push((byte << 8) + byte2);
break;
case 4:
byte2 = byte & 15;
byte1 = byte >> 4;
leftOver.push(byte1, byte2);
break;
case 2:
byte4 = byte & 3;
byte3 = byte >> 2 & 3;
byte2 = byte >> 4 & 3;
byte1 = byte >> 6 & 3;
leftOver.push(byte1, byte2, byte3, byte4);
break;
case 1:
byte8 = byte & 1;
byte7 = byte >> 1 & 1;
byte6 = byte >> 2 & 1;
byte5 = byte >> 3 & 1;
byte4 = byte >> 4 & 1;
byte3 = byte >> 5 & 1;
byte2 = byte >> 6 & 1;
byte1 = byte >> 7 & 1;
leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
break;
}
}
return {
get: function(count) {
while (leftOver.length < count) {
split();
}
let returner = leftOver.slice(0, count);
leftOver = leftOver.slice(count);
return returner;
},
resetAfterLine: function() {
leftOver.length = 0;
},
end: function() {
if (i !== data.length) {
throw new Error("extra data found");
}
}
};
}
function mapImage8Bit(image2, pxData, getPxPos, bpp, data, rawPos) {
let imageWidth = image2.width;
let imageHeight = image2.height;
let imagePass = image2.index;
for (let y = 0;y < imageHeight; y++) {
for (let x = 0;x < imageWidth; x++) {
let pxPos = getPxPos(x, y, imagePass);
pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
rawPos += bpp;
}
}
return rawPos;
}
function mapImageCustomBit(image2, pxData, getPxPos, bpp, bits, maxBit) {
let imageWidth = image2.width;
let imageHeight = image2.height;
let imagePass = image2.index;
for (let y = 0;y < imageHeight; y++) {
for (let x = 0;x < imageWidth; x++) {
let pixelData = bits.get(bpp);
let pxPos = getPxPos(x, y, imagePass);
pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
}
bits.resetAfterLine();
}
}
exports.dataToBitMap = function(data, bitmapInfo) {
let width = bitmapInfo.width;
let height = bitmapInfo.height;
let depth = bitmapInfo.depth;
let bpp = bitmapInfo.bpp;
let interlace = bitmapInfo.interlace;
let bits;
if (depth !== 8) {
bits = bitRetriever(data, depth);
}
let pxData;
if (depth <= 8) {
pxData = Buffer.alloc(width * height * 4);
} else {
pxData = new Uint16Array(width * height * 4);
}
let maxBit = Math.pow(2, depth) - 1;
let rawPos = 0;
let images;
let getPxPos;
if (interlace) {
images = interlaceUtils.getImagePasses(width, height);
getPxPos = interlaceUtils.getInterlaceIterator(width, height);
} else {
let nonInterlacedPxPos = 0;
getPxPos = function() {
let returner = nonInterlacedPxPos;
nonInterlacedPxPos += 4;
return returner;
};
images = [{ width, height }];
}
for (let imageIndex = 0;imageIndex < images.length; imageIndex++) {
if (depth === 8) {
rawPos = mapImage8Bit(images[imageIndex], pxData, getPxPos, bpp, data, rawPos);
} else {
mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit);
}
}
if (depth === 8) {
if (rawPos !== data.length) {
throw new Error("extra data found");
}
} else {
bits.end();
}
return pxData;
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/format-normaliser.js
var require_format_normaliser = __commonJS((exports, module) => {
function dePalette(indata, outdata, width, height, palette2) {
let pxPos = 0;
for (let y = 0;y < height; y++) {
for (let x = 0;x < width; x++) {
let color = palette2[indata[pxPos]];
if (!color) {
throw new Error("index " + indata[pxPos] + " not in palette");
}
for (let i = 0;i < 4; i++) {
outdata[pxPos + i] = color[i];
}
pxPos += 4;
}
}
}
function replaceTransparentColor(indata, outdata, width, height, transColor) {
let pxPos = 0;
for (let y = 0;y < height; y++) {
for (let x = 0;x < width; x++) {
let makeTrans = false;
if (transColor.length === 1) {
if (transColor[0] === indata[pxPos]) {
makeTrans = true;
}
} else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
makeTrans = true;
}
if (makeTrans) {
for (let i = 0;i < 4; i++) {
outdata[pxPos + i] = 0;
}
}
pxPos += 4;
}
}
}
function scaleDepth(indata, outdata, width, height, depth) {
let maxOutSample = 255;
let maxInSample = Math.pow(2, depth) - 1;
let pxPos = 0;
for (let y = 0;y < height; y++) {
for (let x = 0;x < width; x++) {
for (let i = 0;i < 4; i++) {
outdata[pxPos + i] = Math.floor(indata[pxPos + i] * maxOutSample / maxInSample + 0.5);
}
pxPos += 4;
}
}
}
module.exports = function(indata, imageData, skipRescale = false) {
let depth = imageData.depth;
let width = imageData.width;
let height = imageData.height;
let colorType = imageData.colorType;
let transColor = imageData.transColor;
let palette2 = imageData.palette;
let outdata = indata;
if (colorType === 3) {
dePalette(indata, outdata, width, height, palette2);
} else {
if (transColor) {
replaceTransparentColor(indata, outdata, width, height, transColor);
}
if (depth !== 8 && !skipRescale) {
if (depth === 16) {
outdata = Buffer.alloc(width * height * 4);
}
scaleDepth(indata, outdata, width, height, depth);
}
}
return outdata;
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/parser-async.js
var require_parser_async = __commonJS((exports, module) => {
var util = __require("util");
var zlib = __require("zlib");
var ChunkStream = require_chunkstream();
var FilterAsync = require_filter_parse_async();
var Parser = require_parser();
var bitmapper = require_bitmapper();
var formatNormaliser = require_format_normaliser();
var ParserAsync = module.exports = function(options) {
ChunkStream.call(this);
this._parser = new Parser(options, {
read: this.read.bind(this),
error: this._handleError.bind(this),
metadata: this._handleMetaData.bind(this),
gamma: this.emit.bind(this, "gamma"),
palette: this._handlePalette.bind(this),
transColor: this._handleTransColor.bind(this),
finished: this._finished.bind(this),
inflateData: this._inflateData.bind(this),
simpleTransparency: this._simpleTransparency.bind(this),
headersFinished: this._headersFinished.bind(this)
});
this._options = options;
this.writable = true;
this._parser.start();
};
util.inherits(ParserAsync, ChunkStream);
ParserAsync.prototype._handleError = function(err) {
this.emit("error", err);
this.writable = false;
this.destroy();
if (this._inflate && this._inflate.destroy) {
this._inflate.destroy();
}
if (this._filter) {
this._filter.destroy();
this._filter.on("error", function() {});
}
this.errord = true;
};
ParserAsync.prototype._inflateData = function(data) {
if (!this._inflate) {
if (this._bitmapInfo.interlace) {
this._inflate = zlib.createInflate();
this._inflate.on("error", this.emit.bind(this, "error"));
this._filter.on("complete", this._complete.bind(this));
this._inflate.pipe(this._filter);
} else {
let rowSize = (this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7 >> 3) + 1;
let imageSize = rowSize * this._bitmapInfo.height;
let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
this._inflate = zlib.createInflate({ chunkSize });
let leftToInflate = imageSize;
let emitError = this.emit.bind(this, "error");
this._inflate.on("error", function(err) {
if (!leftToInflate) {
return;
}
emitError(err);
});
this._filter.on("complete", this._complete.bind(this));
let filterWrite = this._filter.write.bind(this._filter);
this._inflate.on("data", function(chunk) {
if (!leftToInflate) {
return;
}
if (chunk.length > leftToInflate) {
chunk = chunk.slice(0, leftToInflate);
}
leftToInflate -= chunk.length;
filterWrite(chunk);
});
this._inflate.on("end", this._filter.end.bind(this._filter));
}
}
this._inflate.write(data);
};
ParserAsync.prototype._handleMetaData = function(metaData) {
this._metaData = metaData;
this._bitmapInfo = Object.create(metaData);
this._filter = new FilterAsync(this._bitmapInfo);
};
ParserAsync.prototype._handleTransColor = function(transColor) {
this._bitmapInfo.transColor = transColor;
};
ParserAsync.prototype._handlePalette = function(palette2) {
this._bitmapInfo.palette = palette2;
};
ParserAsync.prototype._simpleTransparency = function() {
this._metaData.alpha = true;
};
ParserAsync.prototype._headersFinished = function() {
this.emit("metadata", this._metaData);
};
ParserAsync.prototype._finished = function() {
if (this.errord) {
return;
}
if (!this._inflate) {
this.emit("error", "No Inflate block");
} else {
this._inflate.end();
}
};
ParserAsync.prototype._complete = function(filteredData) {
if (this.errord) {
return;
}
let normalisedBitmapData;
try {
let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo, this._options.skipRescale);
bitmapData = null;
} catch (ex) {
this._handleError(ex);
return;
}
this.emit("parsed", normalisedBitmapData);
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/bitpacker.js
var require_bitpacker = __commonJS((exports, module) => {
var constants2 = require_constants();
module.exports = function(dataIn, width, height, options) {
let outHasAlpha = [constants2.COLORTYPE_COLOR_ALPHA, constants2.COLORTYPE_ALPHA].indexOf(options.colorType) !== -1;
if (options.colorType === options.inputColorType) {
let bigEndian = function() {
let buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true);
return new Int16Array(buffer)[0] !== 256;
}();
if (options.bitDepth === 8 || options.bitDepth === 16 && bigEndian) {
return dataIn;
}
}
let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
let maxValue = 255;
let inBpp = constants2.COLORTYPE_TO_BPP_MAP[options.inputColorType];
if (inBpp === 4 && !options.inputHasAlpha) {
inBpp = 3;
}
let outBpp = constants2.COLORTYPE_TO_BPP_MAP[options.colorType];
if (options.bitDepth === 16) {
maxValue = 65535;
outBpp *= 2;
}
let outData = Buffer.alloc(width * height * outBpp);
let inIndex = 0;
let outIndex = 0;
let bgColor = options.bgColor || {};
if (bgColor.red === undefined) {
bgColor.red = maxValue;
}
if (bgColor.green === undefined) {
bgColor.green = maxValue;
}
if (bgColor.blue === undefined) {
bgColor.blue = maxValue;
}
function getRGBA() {
let red;
let green;
let blue;
let alpha = maxValue;
switch (options.inputColorType) {
case constants2.COLORTYPE_COLOR_ALPHA:
alpha = data[inIndex + 3];
red = data[inIndex];
green = data[inIndex + 1];
blue = data[inIndex + 2];
break;
case constants2.COLORTYPE_COLOR:
red = data[inIndex];
green = data[inIndex + 1];
blue = data[inIndex + 2];
break;
case constants2.COLORTYPE_ALPHA:
alpha = data[inIndex + 1];
red = data[inIndex];
green = red;
blue = red;
break;
case constants2.COLORTYPE_GRAYSCALE:
red = data[inIndex];
green = red;
blue = red;
break;
default:
throw new Error("input color type:" + options.inputColorType + " is not supported at present");
}
if (options.inputHasAlpha) {
if (!outHasAlpha) {
alpha /= maxValue;
red = Math.min(Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), maxValue);
green = Math.min(Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), maxValue);
blue = Math.min(Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), maxValue);
}
}
return { red, green, blue, alpha };
}
for (let y = 0;y < height; y++) {
for (let x = 0;x < width; x++) {
let rgba = getRGBA(data, inIndex);
switch (options.colorType) {
case constants2.COLORTYPE_COLOR_ALPHA:
case constants2.COLORTYPE_COLOR:
if (options.bitDepth === 8) {
outData[outIndex] = rgba.red;
outData[outIndex + 1] = rgba.green;
outData[outIndex + 2] = rgba.blue;
if (outHasAlpha) {
outData[outIndex + 3] = rgba.alpha;
}
} else {
outData.writeUInt16BE(rgba.red, outIndex);
outData.writeUInt16BE(rgba.green, outIndex + 2);
outData.writeUInt16BE(rgba.blue, outIndex + 4);
if (outHasAlpha) {
outData.writeUInt16BE(rgba.alpha, outIndex + 6);
}
}
break;
case constants2.COLORTYPE_ALPHA:
case constants2.COLORTYPE_GRAYSCALE: {
let grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
if (options.bitDepth === 8) {
outData[outIndex] = grayscale;
if (outHasAlpha) {
outData[outIndex + 1] = rgba.alpha;
}
} else {
outData.writeUInt16BE(grayscale, outIndex);
if (outHasAlpha) {
outData.writeUInt16BE(rgba.alpha, outIndex + 2);
}
}
break;
}
default:
throw new Error("unrecognised color Type " + options.colorType);
}
inIndex += inBpp;
outIndex += outBpp;
}
}
return outData;
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/filter-pack.js
var require_filter_pack = __commonJS((exports, module) => {
var paethPredictor = require_paeth_predictor();
function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
for (let x = 0;x < byteWidth; x++) {
rawData[rawPos + x] = pxData[pxPos + x];
}
}
function filterSumNone(pxData, pxPos, byteWidth) {
let sum = 0;
let length = pxPos + byteWidth;
for (let i = pxPos;i < length; i++) {
sum += Math.abs(pxData[i]);
}
return sum;
}
function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
for (let x = 0;x < byteWidth; x++) {
let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
let val = pxData[pxPos + x] - left;
rawData[rawPos + x] = val;
}
}
function filterSumSub(pxData, pxPos, byteWidth, bpp) {
let sum = 0;
for (let x = 0;x < byteWidth; x++) {
let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
let val = pxData[pxPos + x] - left;
sum += Math.abs(val);
}
return sum;
}
function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
for (let x = 0;x < byteWidth; x++) {
let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
let val = pxData[pxPos + x] - up;
rawData[rawPos + x] = val;
}
}
function filterSumUp(pxData, pxPos, byteWidth) {
let sum = 0;
let length = pxPos + byteWidth;
for (let x = pxPos;x < length; x++) {
let up = pxPos > 0 ? pxData[x - byteWidth] : 0;
let val = pxData[x] - up;
sum += Math.abs(val);
}
return sum;
}
function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
for (let x = 0;x < byteWidth; x++) {
let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
let val = pxData[pxPos + x] - (left + up >> 1);
rawData[rawPos + x] = val;
}
}
function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
let sum = 0;
for (let x = 0;x < byteWidth; x++) {
let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
let val = pxData[pxPos + x] - (left + up >> 1);
sum += Math.abs(val);
}
return sum;
}
function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
for (let x = 0;x < byteWidth; x++) {
let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
rawData[rawPos + x] = val;
}
}
function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
let sum = 0;
for (let x = 0;x < byteWidth; x++) {
let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
sum += Math.abs(val);
}
return sum;
}
var filters = {
0: filterNone,
1: filterSub,
2: filterUp,
3: filterAvg,
4: filterPaeth
};
var filterSums = {
0: filterSumNone,
1: filterSumSub,
2: filterSumUp,
3: filterSumAvg,
4: filterSumPaeth
};
module.exports = function(pxData, width, height, options, bpp) {
let filterTypes;
if (!("filterType" in options) || options.filterType === -1) {
filterTypes = [0, 1, 2, 3, 4];
} else if (typeof options.filterType === "number") {
filterTypes = [options.filterType];
} else {
throw new Error("unrecognised filter types");
}
if (options.bitDepth === 16) {
bpp *= 2;
}
let byteWidth = width * bpp;
let rawPos = 0;
let pxPos = 0;
let rawData = Buffer.alloc((byteWidth + 1) * height);
let sel = filterTypes[0];
for (let y = 0;y < height; y++) {
if (filterTypes.length > 1) {
let min = Infinity;
for (let i = 0;i < filterTypes.length; i++) {
let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
if (sum < min) {
sel = filterTypes[i];
min = sum;
}
}
}
rawData[rawPos] = sel;
rawPos++;
filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
rawPos += byteWidth;
pxPos += byteWidth;
}
return rawData;
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/packer.js
var require_packer = __commonJS((exports, module) => {
var constants2 = require_constants();
var CrcStream = require_crc();
var bitPacker = require_bitpacker();
var filter = require_filter_pack();
var zlib = __require("zlib");
var Packer = module.exports = function(options) {
this._options = options;
options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9;
options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3;
options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
options.deflateFactory = options.deflateFactory || zlib.createDeflate;
options.bitDepth = options.bitDepth || 8;
options.colorType = typeof options.colorType === "number" ? options.colorType : constants2.COLORTYPE_COLOR_ALPHA;
options.inputColorType = typeof options.inputColorType === "number" ? options.inputColorType : constants2.COLORTYPE_COLOR_ALPHA;
if ([
constants2.COLORTYPE_GRAYSCALE,
constants2.COLORTYPE_COLOR,
constants2.COLORTYPE_COLOR_ALPHA,
constants2.COLORTYPE_ALPHA
].indexOf(options.colorType) === -1) {
throw new Error("option color type:" + options.colorType + " is not supported at present");
}
if ([
constants2.COLORTYPE_GRAYSCALE,
constants2.COLORTYPE_COLOR,
constants2.COLORTYPE_COLOR_ALPHA,
constants2.COLORTYPE_ALPHA
].indexOf(options.inputColorType) === -1) {
throw new Error("option input color type:" + options.inputColorType + " is not supported at present");
}
if (options.bitDepth !== 8 && options.bitDepth !== 16) {
throw new Error("option bit depth:" + options.bitDepth + " is not supported at present");
}
};
Packer.prototype.getDeflateOptions = function() {
return {
chunkSize: this._options.deflateChunkSize,
level: this._options.deflateLevel,
strategy: this._options.deflateStrategy
};
};
Packer.prototype.createDeflate = function() {
return this._options.deflateFactory(this.getDeflateOptions());
};
Packer.prototype.filterData = function(data, width, height) {
let packedData = bitPacker(data, width, height, this._options);
let bpp = constants2.COLORTYPE_TO_BPP_MAP[this._options.colorType];
let filteredData = filter(packedData, width, height, this._options, bpp);
return filteredData;
};
Packer.prototype._packChunk = function(type, data) {
let len = data ? data.length : 0;
let buf = Buffer.alloc(len + 12);
buf.writeUInt32BE(len, 0);
buf.writeUInt32BE(type, 4);
if (data) {
data.copy(buf, 8);
}
buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
return buf;
};
Packer.prototype.packGAMA = function(gamma) {
let buf = Buffer.alloc(4);
buf.writeUInt32BE(Math.floor(gamma * constants2.GAMMA_DIVISION), 0);
return this._packChunk(constants2.TYPE_gAMA, buf);
};
Packer.prototype.packIHDR = function(width, height) {
let buf = Buffer.alloc(13);
buf.writeUInt32BE(width, 0);
buf.writeUInt32BE(height, 4);
buf[8] = this._options.bitDepth;
buf[9] = this._options.colorType;
buf[10] = 0;
buf[11] = 0;
buf[12] = 0;
return this._packChunk(constants2.TYPE_IHDR, buf);
};
Packer.prototype.packIDAT = function(data) {
return this._packChunk(constants2.TYPE_IDAT, data);
};
Packer.prototype.packIEND = function() {
return this._packChunk(constants2.TYPE_IEND, null);
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/packer-async.js
var require_packer_async = __commonJS((exports, module) => {
var util = __require("util");
var Stream = __require("stream");
var constants2 = require_constants();
var Packer = require_packer();
var PackerAsync = module.exports = function(opt) {
Stream.call(this);
let options = opt || {};
this._packer = new Packer(options);
this._deflate = this._packer.createDeflate();
this.readable = true;
};
util.inherits(PackerAsync, Stream);
PackerAsync.prototype.pack = function(data, width, height, gamma) {
this.emit("data", Buffer.from(constants2.PNG_SIGNATURE));
this.emit("data", this._packer.packIHDR(width, height));
if (gamma) {
this.emit("data", this._packer.packGAMA(gamma));
}
let filteredData = this._packer.filterData(data, width, height);
this._deflate.on("error", this.emit.bind(this, "error"));
this._deflate.on("data", function(compressedData) {
this.emit("data", this._packer.packIDAT(compressedData));
}.bind(this));
this._deflate.on("end", function() {
this.emit("data", this._packer.packIEND());
this.emit("end");
}.bind(this));
this._deflate.end(filteredData);
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/sync-inflate.js
var require_sync_inflate = __commonJS((exports, module) => {
var assert = __require("assert").ok;
var zlib = __require("zlib");
var util = __require("util");
var kMaxLength = __require("buffer").kMaxLength;
function Inflate(opts) {
if (!(this instanceof Inflate)) {
return new Inflate(opts);
}
if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
opts.chunkSize = zlib.Z_MIN_CHUNK;
}
zlib.Inflate.call(this, opts);
this._offset = this._offset === undefined ? this._outOffset : this._offset;
this._buffer = this._buffer || this._outBuffer;
if (opts && opts.maxLength != null) {
this._maxLength = opts.maxLength;
}
}
function createInflate(opts) {
return new Inflate(opts);
}
function _close(engine, callback) {
if (callback) {
process.nextTick(callback);
}
if (!engine._handle) {
return;
}
engine._handle.close();
engine._handle = null;
}
Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
if (typeof asyncCb === "function") {
return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
}
let self2 = this;
let availInBefore = chunk && chunk.length;
let availOutBefore = this._chunkSize - this._offset;
let leftToInflate = this._maxLength;
let inOff = 0;
let buffers = [];
let nread = 0;
let error;
this.on("error", function(err) {
error = err;
});
function handleChunk(availInAfter, availOutAfter) {
if (self2._hadError) {
return;
}
let have = availOutBefore - availOutAfter;
assert(have >= 0, "have should not go down");
if (have > 0) {
let out = self2._buffer.slice(self2._offset, self2._offset + have);
self2._offset += have;
if (out.length > leftToInflate) {
out = out.slice(0, leftToInflate);
}
buffers.push(out);
nread += out.length;
leftToInflate -= out.length;
if (leftToInflate === 0) {
return false;
}
}
if (availOutAfter === 0 || self2._offset >= self2._chunkSize) {
availOutBefore = self2._chunkSize;
self2._offset = 0;
self2._buffer = Buffer.allocUnsafe(self2._chunkSize);
}
if (availOutAfter === 0) {
inOff += availInBefore - availInAfter;
availInBefore = availInAfter;
return true;
}
return false;
}
assert(this._handle, "zlib binding closed");
let res;
do {
res = this._handle.writeSync(flushFlag, chunk, inOff, availInBefore, this._buffer, this._offset, availOutBefore);
res = res || this._writeState;
} while (!this._hadError && handleChunk(res[0], res[1]));
if (this._hadError) {
throw error;
}
if (nread >= kMaxLength) {
_close(this);
throw new RangeError("Cannot create final Buffer. It would be larger than 0x" + kMaxLength.toString(16) + " bytes");
}
let buf = Buffer.concat(buffers, nread);
_close(this);
return buf;
};
util.inherits(Inflate, zlib.Inflate);
function zlibBufferSync(engine, buffer) {
if (typeof buffer === "string") {
buffer = Buffer.from(buffer);
}
if (!(buffer instanceof Buffer)) {
throw new TypeError("Not a string or buffer");
}
let flushFlag = engine._finishFlushFlag;
if (flushFlag == null) {
flushFlag = zlib.Z_FINISH;
}
return engine._processChunk(buffer, flushFlag);
}
function inflateSync(buffer, opts) {
return zlibBufferSync(new Inflate(opts), buffer);
}
module.exports = exports = inflateSync;
exports.Inflate = Inflate;
exports.createInflate = createInflate;
exports.inflateSync = inflateSync;
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/sync-reader.js
var require_sync_reader = __commonJS((exports, module) => {
var SyncReader = module.exports = function(buffer) {
this._buffer = buffer;
this._reads = [];
};
SyncReader.prototype.read = function(length, callback) {
this._reads.push({
length: Math.abs(length),
allowLess: length < 0,
func: callback
});
};
SyncReader.prototype.process = function() {
while (this._reads.length > 0 && this._buffer.length) {
let read = this._reads[0];
if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
this._reads.shift();
let buf = this._buffer;
this._buffer = buf.slice(read.length);
read.func.call(this, buf.slice(0, read.length));
} else {
break;
}
}
if (this._reads.length > 0) {
throw new Error("There are some read requests waitng on finished stream");
}
if (this._buffer.length > 0) {
throw new Error("unrecognised content at end of stream");
}
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/filter-parse-sync.js
var require_filter_parse_sync = __commonJS((exports) => {
var SyncReader = require_sync_reader();
var Filter = require_filter_parse();
exports.process = function(inBuffer, bitmapInfo) {
let outBuffers = [];
let reader = new SyncReader(inBuffer);
let filter = new Filter(bitmapInfo, {
read: reader.read.bind(reader),
write: function(bufferPart) {
outBuffers.push(bufferPart);
},
complete: function() {}
});
filter.start();
reader.process();
return Buffer.concat(outBuffers);
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/parser-sync.js
var require_parser_sync = __commonJS((exports, module) => {
var hasSyncZlib = true;
var zlib = __require("zlib");
var inflateSync = require_sync_inflate();
if (!zlib.deflateSync) {
hasSyncZlib = false;
}
var SyncReader = require_sync_reader();
var FilterSync = require_filter_parse_sync();
var Parser = require_parser();
var bitmapper = require_bitmapper();
var formatNormaliser = require_format_normaliser();
module.exports = function(buffer, options) {
if (!hasSyncZlib) {
throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");
}
let err;
function handleError(_err_) {
err = _err_;
}
let metaData;
function handleMetaData(_metaData_) {
metaData = _metaData_;
}
function handleTransColor(transColor) {
metaData.transColor = transColor;
}
function handlePalette(palette2) {
metaData.palette = palette2;
}
function handleSimpleTransparency() {
metaData.alpha = true;
}
let gamma;
function handleGamma(_gamma_) {
gamma = _gamma_;
}
let inflateDataList = [];
function handleInflateData(inflatedData2) {
inflateDataList.push(inflatedData2);
}
let reader = new SyncReader(buffer);
let parser = new Parser(options, {
read: reader.read.bind(reader),
error: handleError,
metadata: handleMetaData,
gamma: handleGamma,
palette: handlePalette,
transColor: handleTransColor,
inflateData: handleInflateData,
simpleTransparency: handleSimpleTransparency
});
parser.start();
reader.process();
if (err) {
throw err;
}
let inflateData = Buffer.concat(inflateDataList);
inflateDataList.length = 0;
let inflatedData;
if (metaData.interlace) {
inflatedData = zlib.inflateSync(inflateData);
} else {
let rowSize = (metaData.width * metaData.bpp * metaData.depth + 7 >> 3) + 1;
let imageSize = rowSize * metaData.height;
inflatedData = inflateSync(inflateData, {
chunkSize: imageSize,
maxLength: imageSize
});
}
inflateData = null;
if (!inflatedData || !inflatedData.length) {
throw new Error("bad png - invalid inflate data response");
}
let unfilteredData = FilterSync.process(inflatedData, metaData);
inflateData = null;
let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
unfilteredData = null;
let normalisedBitmapData = formatNormaliser(bitmapData, metaData, options.skipRescale);
metaData.data = normalisedBitmapData;
metaData.gamma = gamma || 0;
return metaData;
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/packer-sync.js
var require_packer_sync = __commonJS((exports, module) => {
var hasSyncZlib = true;
var zlib = __require("zlib");
if (!zlib.deflateSync) {
hasSyncZlib = false;
}
var constants2 = require_constants();
var Packer = require_packer();
module.exports = function(metaData, opt) {
if (!hasSyncZlib) {
throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");
}
let options = opt || {};
let packer = new Packer(options);
let chunks = [];
chunks.push(Buffer.from(constants2.PNG_SIGNATURE));
chunks.push(packer.packIHDR(metaData.width, metaData.height));
if (metaData.gamma) {
chunks.push(packer.packGAMA(metaData.gamma));
}
let filteredData = packer.filterData(metaData.data, metaData.width, metaData.height);
let compressedData = zlib.deflateSync(filteredData, packer.getDeflateOptions());
filteredData = null;
if (!compressedData || !compressedData.length) {
throw new Error("bad png - invalid compressed data response");
}
chunks.push(packer.packIDAT(compressedData));
chunks.push(packer.packIEND());
return Buffer.concat(chunks);
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/png-sync.js
var require_png_sync = __commonJS((exports) => {
var parse = require_parser_sync();
var pack = require_packer_sync();
exports.read = function(buffer, options) {
return parse(buffer, options || {});
};
exports.write = function(png, options) {
return pack(png, options);
};
});
// ../../node_modules/.bun/pngjs@7.0.0/node_modules/pngjs/lib/png.js
var require_png = __commonJS((exports) => {
var util = __require("util");
var Stream = __require("stream");
var Parser = require_parser_async();
var Packer = require_packer_async();
var PNGSync = require_png_sync();
var PNG = exports.PNG = function(options) {
Stream.call(this);
options = options || {};
this.width = options.width | 0;
this.height = options.height | 0;
this.data = this.width > 0 && this.height > 0 ? Buffer.alloc(4 * this.width * this.height) : null;
if (options.fill && this.data) {
this.data.fill(0);
}
this.gamma = 0;
this.readable = this.writable = true;
this._parser = new Parser(options);
this._parser.on("error", this.emit.bind(this, "error"));
this._parser.on("close", this._handleClose.bind(this));
this._parser.on("metadata", this._metadata.bind(this));
this._parser.on("gamma", this._gamma.bind(this));
this._parser.on("parsed", function(data) {
this.data = data;
this.emit("parsed", data);
}.bind(this));
this._packer = new Packer(options);
this._packer.on("data", this.emit.bind(this, "data"));
this._packer.on("end", this.emit.bind(this, "end"));
this._parser.on("close", this._handleClose.bind(this));
this._packer.on("error", this.emit.bind(this, "error"));
};
util.inherits(PNG, Stream);
PNG.sync = PNGSync;
PNG.prototype.pack = function() {
if (!this.data || !this.data.length) {
this.emit("error", "No data provided");
return this;
}
process.nextTick(function() {
this._packer.pack(this.data, this.width, this.height, this.gamma);
}.bind(this));
return this;
};
PNG.prototype.parse = function(data, callback) {
if (callback) {
let onParsed, onError;
onParsed = function(parsedData) {
this.removeListener("error", onError);
this.data = parsedData;
callback(null, this);
}.bind(this);
onError = function(err) {
this.removeListener("parsed", onParsed);
callback(err, null);
}.bind(this);
this.once("parsed", onParsed);
this.once("error", onError);
}
this.end(data);
return this;
};
PNG.prototype.write = function(data) {
this._parser.write(data);
return true;
};
PNG.prototype.end = function(data) {
this._parser.end(data);
};
PNG.prototype._metadata = function(metadata) {
this.width = metadata.width;
this.height = metadata.height;
this.emit("metadata", metadata);
};
PNG.prototype._gamma = function(gamma) {
this.gamma = gamma;
};
PNG.prototype._handleClose = function() {
if (!this._parser.writable && !this._packer.readable) {
this.emit("close");
}
};
PNG.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) {
srcX |= 0;
srcY |= 0;
width |= 0;
height |= 0;
deltaX |= 0;
deltaY |= 0;
if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
throw new Error("bitblt reading outside image");
}
if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
throw new Error("bitblt writing outside image");
}
for (let y = 0;y < height; y++) {
src.data.copy(dst.data, (deltaY + y) * dst.width + deltaX << 2, (srcY + y) * src.width + srcX << 2, (srcY + y) * src.width + srcX + width << 2);
}
};
PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) {
PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
return this;
};
PNG.adjustGamma = function(src) {
if (src.gamma) {
for (let y = 0;y < src.height; y++) {
for (let x = 0;x < src.width; x++) {
let idx = src.width * y + x << 2;
for (let i = 0;i < 3; i++) {
let sample = src.data[idx + i] / 255;
sample = Math.pow(sample, 1 / 2.2 / src.gamma);
src.data[idx + i] = Math.round(sample * 255);
}
}
}
src.gamma = 0;
}
};
PNG.prototype.adjustGamma = function() {
PNG.adjustGamma(this);
};
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/utils/common.js
var require_common = __commonJS((exports) => {
var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined";
function _has(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
exports.assign = function(obj) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) {
continue;
}
if (typeof source !== "object") {
throw new TypeError(source + "must be non-object");
}
for (var p in source) {
if (_has(source, p)) {
obj[p] = source[p];
}
}
}
return obj;
};
exports.shrinkBuf = function(buf, size) {
if (buf.length === size) {
return buf;
}
if (buf.subarray) {
return buf.subarray(0, size);
}
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function(dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
return;
}
for (var i = 0;i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
len = 0;
for (i = 0, l = chunks.length;i < l; i++) {
len += chunks[i].length;
}
result = new Uint8Array(len);
pos = 0;
for (i = 0, l = chunks.length;i < l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function(dest, src, src_offs, len, dest_offs) {
for (var i = 0;i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
exports.setTyped = function(on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/trees.js
var require_trees = __commonJS((exports) => {
var utils2 = require_common();
var Z_FIXED = 4;
var Z_BINARY = 0;
var Z_TEXT = 1;
var Z_UNKNOWN = 2;
function zero(buf) {
var len = buf.length;
while (--len >= 0) {
buf[len] = 0;
}
}
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var LENGTH_CODES = 29;
var LITERALS = 256;
var L_CODES = LITERALS + 1 + LENGTH_CODES;
var D_CODES = 30;
var BL_CODES = 19;
var HEAP_SIZE = 2 * L_CODES + 1;
var MAX_BITS = 15;
var Buf_size = 16;
var MAX_BL_BITS = 7;
var END_BLOCK = 256;
var REP_3_6 = 16;
var REPZ_3_10 = 17;
var REPZ_11_138 = 18;
var extra_lbits = [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];
var extra_dbits = [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];
var extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];
var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
var DIST_CODE_LEN = 512;
var static_ltree = new Array((L_CODES + 2) * 2);
zero(static_ltree);
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
zero(_length_code);
var base_length = new Array(LENGTH_CODES);
zero(base_length);
var base_dist = new Array(D_CODES);
zero(base_dist);
function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree;
this.extra_bits = extra_bits;
this.extra_base = extra_base;
this.elems = elems;
this.max_length = max_length;
this.has_stree = static_tree && static_tree.length;
}
var static_l_desc;
var static_d_desc;
var static_bl_desc;
function TreeDesc(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree;
this.max_code = 0;
this.stat_desc = stat_desc;
}
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
function put_short(s, w) {
s.pending_buf[s.pending++] = w & 255;
s.pending_buf[s.pending++] = w >>> 8 & 255;
}
function send_bits(s, value, length) {
if (s.bi_valid > Buf_size - length) {
s.bi_buf |= value << s.bi_valid & 65535;
put_short(s, s.bi_buf);
s.bi_buf = value >> Buf_size - s.bi_valid;
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= value << s.bi_valid & 65535;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c * 2], tree[c * 2 + 1]);
}
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 255;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
function gen_bitlen(s, desc) {
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h;
var n, m;
var bits;
var xbits;
var f;
var overflow = 0;
for (bits = 0;bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
tree[s.heap[s.heap_max] * 2 + 1] = 0;
for (h = s.heap_max + 1;h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n * 2 + 1] = bits;
if (n > max_code) {
continue;
}
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n - base];
}
f = tree[n * 2];
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n * 2 + 1] + xbits);
}
}
if (overflow === 0) {
return;
}
do {
bits = max_length - 1;
while (s.bl_count[bits] === 0) {
bits--;
}
s.bl_count[bits]--;
s.bl_count[bits + 1] += 2;
s.bl_count[max_length]--;
overflow -= 2;
} while (overflow > 0);
for (bits = max_length;bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) {
continue;
}
if (tree[m * 2 + 1] !== bits) {
s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
tree[m * 2 + 1] = bits;
}
n--;
}
}
}
function gen_codes(tree, max_code, bl_count) {
var next_code = new Array(MAX_BITS + 1);
var code = 0;
var bits;
var n;
for (bits = 1;bits <= MAX_BITS; bits++) {
next_code[bits] = code = code + bl_count[bits - 1] << 1;
}
for (n = 0;n <= max_code; n++) {
var len = tree[n * 2 + 1];
if (len === 0) {
continue;
}
tree[n * 2] = bi_reverse(next_code[len]++, len);
}
}
function tr_static_init() {
var n;
var bits;
var length;
var code;
var dist;
var bl_count = new Array(MAX_BITS + 1);
length = 0;
for (code = 0;code < LENGTH_CODES - 1; code++) {
base_length[code] = length;
for (n = 0;n < 1 << extra_lbits[code]; n++) {
_length_code[length++] = code;
}
}
_length_code[length - 1] = code;
dist = 0;
for (code = 0;code < 16; code++) {
base_dist[code] = dist;
for (n = 0;n < 1 << extra_dbits[code]; n++) {
_dist_code[dist++] = code;
}
}
dist >>= 7;
for (;code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0;n < 1 << extra_dbits[code] - 7; n++) {
_dist_code[256 + dist++] = code;
}
}
for (bits = 0;bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n * 2 + 1] = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n * 2 + 1] = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n * 2 + 1] = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n * 2 + 1] = 8;
n++;
bl_count[8]++;
}
gen_codes(static_ltree, L_CODES + 1, bl_count);
for (n = 0;n < D_CODES; n++) {
static_dtree[n * 2 + 1] = 5;
static_dtree[n * 2] = bi_reverse(n, 5);
}
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
}
function init_block(s) {
var n;
for (n = 0;n < L_CODES; n++) {
s.dyn_ltree[n * 2] = 0;
}
for (n = 0;n < D_CODES; n++) {
s.dyn_dtree[n * 2] = 0;
}
for (n = 0;n < BL_CODES; n++) {
s.bl_tree[n * 2] = 0;
}
s.dyn_ltree[END_BLOCK * 2] = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
function bi_windup(s) {
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
function copy_block(s, buf, len, header) {
bi_windup(s);
if (header) {
put_short(s, len);
put_short(s, ~len);
}
utils2.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
function smaller(tree, n, m, depth) {
var _n2 = n * 2;
var _m2 = m * 2;
return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n] <= depth[m];
}
function pqdownheap(s, tree, k) {
var v = s.heap[k];
var j = k << 1;
while (j <= s.heap_len) {
if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
j++;
}
if (smaller(tree, v, s.heap[j], s.depth)) {
break;
}
s.heap[k] = s.heap[j];
k = j;
j <<= 1;
}
s.heap[k] = v;
}
function compress_block(s, ltree, dtree) {
var dist;
var lc;
var lx = 0;
var code;
var extra;
if (s.last_lit !== 0) {
do {
dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree);
} else {
code = _length_code[lc];
send_code(s, code + LITERALS + 1, ltree);
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra);
}
dist--;
code = d_code(dist);
send_code(s, code, dtree);
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra);
}
}
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
function build_tree(s, desc) {
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m;
var max_code = -1;
var node;
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0;n < elems; n++) {
if (tree[n * 2] !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n * 2 + 1] = 0;
}
}
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
tree[node * 2] = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node * 2 + 1];
}
}
desc.max_code = max_code;
for (n = s.heap_len >> 1;n >= 1; n--) {
pqdownheap(s, tree, n);
}
node = elems;
do {
n = s.heap[1];
s.heap[1] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1);
m = s.heap[1];
s.heap[--s.heap_max] = n;
s.heap[--s.heap_max] = m;
tree[node * 2] = tree[n * 2] + tree[m * 2];
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n * 2 + 1] = tree[m * 2 + 1] = node;
s.heap[1] = node++;
pqdownheap(s, tree, 1);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1];
gen_bitlen(s, desc);
gen_codes(tree, max_code, s.bl_count);
}
function scan_tree(s, tree, max_code) {
var n;
var prevlen = -1;
var curlen;
var nextlen = tree[0 * 2 + 1];
var count = 0;
var max_count = 7;
var min_count = 4;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code + 1) * 2 + 1] = 65535;
for (n = 0;n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1];
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2] += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) {
s.bl_tree[curlen * 2]++;
}
s.bl_tree[REP_3_6 * 2]++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10 * 2]++;
} else {
s.bl_tree[REPZ_11_138 * 2]++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
function send_tree(s, tree, max_code) {
var n;
var prevlen = -1;
var curlen;
var nextlen = tree[0 * 2 + 1];
var count = 0;
var max_count = 7;
var min_count = 4;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0;n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1];
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do {
send_code(s, curlen, s.bl_tree);
} while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count - 3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count - 3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count - 11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
function build_bl_tree(s) {
var max_blindex;
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
build_tree(s, s.bl_desc);
for (max_blindex = BL_CODES - 1;max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) {
break;
}
}
s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
return max_blindex;
}
function send_all_trees(s, lcodes, dcodes, blcodes) {
var rank;
send_bits(s, lcodes - 257, 5);
send_bits(s, dcodes - 1, 5);
send_bits(s, blcodes - 4, 4);
for (rank = 0;rank < blcodes; rank++) {
send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], 3);
}
send_tree(s, s.dyn_ltree, lcodes - 1);
send_tree(s, s.dyn_dtree, dcodes - 1);
}
function detect_data_type(s) {
var black_mask = 4093624447;
var n;
for (n = 0;n <= 31; n++, black_mask >>>= 1) {
if (black_mask & 1 && s.dyn_ltree[n * 2] !== 0) {
return Z_BINARY;
}
}
if (s.dyn_ltree[9 * 2] !== 0 || s.dyn_ltree[10 * 2] !== 0 || s.dyn_ltree[13 * 2] !== 0) {
return Z_TEXT;
}
for (n = 32;n < LITERALS; n++) {
if (s.dyn_ltree[n * 2] !== 0) {
return Z_TEXT;
}
}
return Z_BINARY;
}
var static_init_done = false;
function _tr_init(s) {
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
init_block(s);
}
function _tr_stored_block(s, buf, stored_len, last) {
send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);
copy_block(s, buf, stored_len, true);
}
function _tr_align(s) {
send_bits(s, STATIC_TREES << 1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
function _tr_flush_block(s, buf, stored_len, last) {
var opt_lenb, static_lenb;
var max_blindex = 0;
if (s.level > 0) {
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
build_tree(s, s.l_desc);
build_tree(s, s.d_desc);
max_blindex = build_bl_tree(s);
opt_lenb = s.opt_len + 3 + 7 >>> 3;
static_lenb = s.static_len + 3 + 7 >>> 3;
if (static_lenb <= opt_lenb) {
opt_lenb = static_lenb;
}
} else {
opt_lenb = static_lenb = stored_len + 5;
}
if (stored_len + 4 <= opt_lenb && buf !== -1) {
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
init_block(s);
if (last) {
bi_windup(s);
}
}
function _tr_tally(s, dist, lc) {
s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 255;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 255;
s.pending_buf[s.l_buf + s.last_lit] = lc & 255;
s.last_lit++;
if (dist === 0) {
s.dyn_ltree[lc * 2]++;
} else {
s.matches++;
dist--;
s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++;
s.dyn_dtree[d_code(dist) * 2]++;
}
return s.last_lit === s.lit_bufsize - 1;
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/adler32.js
var require_adler32 = __commonJS((exports, module) => {
function adler32(adler, buf, len, pos) {
var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n = 0;
while (len !== 0) {
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = s1 + buf[pos++] | 0;
s2 = s2 + s1 | 0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return s1 | s2 << 16 | 0;
}
module.exports = adler32;
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/crc32.js
var require_crc32 = __commonJS((exports, module) => {
function makeTable() {
var c, table = [];
for (var n = 0;n < 256; n++) {
c = n;
for (var k = 0;k < 8; k++) {
c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
}
table[n] = c;
}
return table;
}
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable, end = pos + len;
crc ^= -1;
for (var i = pos;i < end; i++) {
crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255];
}
return crc ^ -1;
}
module.exports = crc32;
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/messages.js
var require_messages = __commonJS((exports, module) => {
module.exports = {
2: "need dictionary",
1: "stream end",
0: "",
"-1": "file error",
"-2": "stream error",
"-3": "data error",
"-4": "insufficient memory",
"-5": "buffer error",
"-6": "incompatible version"
};
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/deflate.js
var require_deflate = __commonJS((exports) => {
var utils2 = require_common();
var trees = require_trees();
var adler32 = require_adler32();
var crc32 = require_crc32();
var msg = require_messages();
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_BUF_ERROR = -5;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
var Z_UNKNOWN = 2;
var Z_DEFLATED = 8;
var MAX_MEM_LEVEL = 9;
var MAX_WBITS = 15;
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
var LITERALS = 256;
var L_CODES = LITERALS + 1 + LENGTH_CODES;
var D_CODES = 30;
var BL_CODES = 19;
var HEAP_SIZE = 2 * L_CODES + 1;
var MAX_BITS = 15;
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1;
var PRESET_DICT = 32;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1;
var BS_BLOCK_DONE = 2;
var BS_FINISH_STARTED = 3;
var BS_FINISH_DONE = 4;
var OS_CODE = 3;
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return (f << 1) - (f > 4 ? 9 : 0);
}
function zero(buf) {
var len = buf.length;
while (--len >= 0) {
buf[len] = 0;
}
}
function flush_pending(strm) {
var s = strm.state;
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) {
return;
}
utils2.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only(s, last) {
trees._tr_flush_block(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
function putShortMSB(s, b) {
s.pending_buf[s.pending++] = b >>> 8 & 255;
s.pending_buf[s.pending++] = b & 255;
}
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) {
len = size;
}
if (len === 0) {
return 0;
}
strm.avail_in -= len;
utils2.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
} else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length;
var scan2 = s.strstart;
var match;
var len;
var best_len = s.prev_length;
var nice_match = s.nice_match;
var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0;
var _win = s.window;
var wmask = s.w_mask;
var prev = s.prev;
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan2 + best_len - 1];
var scan_end = _win[scan2 + best_len];
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
if (nice_match > s.lookahead) {
nice_match = s.lookahead;
}
do {
match = cur_match;
if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan2] || _win[++match] !== _win[scan2 + 1]) {
continue;
}
scan2 += 2;
match++;
do {} while (_win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && scan2 < strend);
len = MAX_MATCH - (strend - scan2);
scan2 = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan2 + best_len - 1];
scan_end = _win[scan2 + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
do {
more = s.window_size - s.lookahead - s.strstart;
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils2.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
s.block_start -= _w_size;
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = m >= _w_size ? m - _w_size : 0;
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = m >= _w_size ? m - _w_size : 0;
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + 1]) & s.hash_mask;
while (s.insert) {
s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
}
function deflate_stored(s, flush) {
var max_block_size = 65535;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
for (;; ) {
if (s.lookahead <= 1) {
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
}
s.strstart += s.lookahead;
s.lookahead = 0;
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) {
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
}
s.insert = 0;
if (flush === Z_FINISH) {
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
return BS_NEED_MORE;
}
function deflate_fast(s, flush) {
var hash_head;
var bflush;
for (;; ) {
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
}
hash_head = 0;
if (s.lookahead >= MIN_MATCH) {
s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
}
if (hash_head !== 0 && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) {
s.match_length = longest_match(s, hash_head);
}
if (s.match_length >= MIN_MATCH) {
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
if (s.match_length <= s.max_lazy_match && s.lookahead >= MIN_MATCH) {
s.match_length--;
do {
s.strstart++;
s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
} while (--s.match_length !== 0);
s.strstart++;
} else {
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + 1]) & s.hash_mask;
}
} else {
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
}
s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
if (flush === Z_FINISH) {
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
return BS_FINISH_DONE;
}
if (s.last_lit) {
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
return BS_BLOCK_DONE;
}
function deflate_slow(s, flush) {
var hash_head;
var bflush;
var max_insert;
for (;; ) {
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
}
hash_head = 0;
if (s.lookahead >= MIN_MATCH) {
s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
}
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH - 1;
if (hash_head !== 0 && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) {
s.match_length = longest_match(s, hash_head);
if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096)) {
s.match_length = MIN_MATCH - 1;
}
}
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
s.lookahead -= s.prev_length - 1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH - 1;
s.strstart++;
if (bflush) {
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
} else if (s.match_available) {
bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
if (bflush) {
flush_block_only(s, false);
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
if (s.match_available) {
bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
if (flush === Z_FINISH) {
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
return BS_FINISH_DONE;
}
if (s.last_lit) {
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
return BS_BLOCK_DONE;
}
function deflate_rle(s, flush) {
var bflush;
var prev;
var scan2, strend;
var _win = s.window;
for (;; ) {
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
}
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan2 = s.strstart - 1;
prev = _win[scan2];
if (prev === _win[++scan2] && prev === _win[++scan2] && prev === _win[++scan2]) {
strend = s.strstart + MAX_MATCH;
do {} while (prev === _win[++scan2] && prev === _win[++scan2] && prev === _win[++scan2] && prev === _win[++scan2] && prev === _win[++scan2] && prev === _win[++scan2] && prev === _win[++scan2] && prev === _win[++scan2] && scan2 < strend);
s.match_length = MAX_MATCH - (strend - scan2);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
}
if (s.match_length >= MIN_MATCH) {
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
}
s.insert = 0;
if (flush === Z_FINISH) {
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
return BS_FINISH_DONE;
}
if (s.last_lit) {
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
return BS_BLOCK_DONE;
}
function deflate_huff(s, flush) {
var bflush;
for (;; ) {
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break;
}
}
s.match_length = 0;
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
}
s.insert = 0;
if (flush === Z_FINISH) {
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
return BS_FINISH_DONE;
}
if (s.last_lit) {
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
}
return BS_BLOCK_DONE;
}
function Config(good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
}
var configuration_table;
configuration_table = [
new Config(0, 0, 0, 0, deflate_stored),
new Config(4, 4, 8, 4, deflate_fast),
new Config(4, 5, 16, 8, deflate_fast),
new Config(4, 6, 32, 32, deflate_fast),
new Config(4, 4, 16, 16, deflate_slow),
new Config(8, 16, 32, 32, deflate_slow),
new Config(8, 16, 128, 128, deflate_slow),
new Config(8, 32, 128, 256, deflate_slow),
new Config(32, 128, 258, 1024, deflate_slow),
new Config(32, 258, 258, 4096, deflate_slow)
];
function lm_init(s) {
s.window_size = 2 * s.w_size;
zero(s.head);
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null;
this.status = 0;
this.pending_buf = null;
this.pending_buf_size = 0;
this.pending_out = 0;
this.pending = 0;
this.wrap = 0;
this.gzhead = null;
this.gzindex = 0;
this.method = Z_DEFLATED;
this.last_flush = -1;
this.w_size = 0;
this.w_bits = 0;
this.w_mask = 0;
this.window = null;
this.window_size = 0;
this.prev = null;
this.head = null;
this.ins_h = 0;
this.hash_size = 0;
this.hash_bits = 0;
this.hash_mask = 0;
this.hash_shift = 0;
this.block_start = 0;
this.match_length = 0;
this.prev_match = 0;
this.match_available = 0;
this.strstart = 0;
this.match_start = 0;
this.lookahead = 0;
this.prev_length = 0;
this.max_chain_length = 0;
this.max_lazy_match = 0;
this.level = 0;
this.strategy = 0;
this.good_match = 0;
this.nice_match = 0;
this.dyn_ltree = new utils2.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils2.Buf16((2 * D_CODES + 1) * 2);
this.bl_tree = new utils2.Buf16((2 * BL_CODES + 1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null;
this.d_desc = null;
this.bl_desc = null;
this.bl_count = new utils2.Buf16(MAX_BITS + 1);
this.heap = new utils2.Buf16(2 * L_CODES + 1);
zero(this.heap);
this.heap_len = 0;
this.heap_max = 0;
this.depth = new utils2.Buf16(2 * L_CODES + 1);
zero(this.depth);
this.l_buf = 0;
this.lit_bufsize = 0;
this.last_lit = 0;
this.d_buf = 0;
this.opt_len = 0;
this.static_len = 0;
this.matches = 0;
this.insert = 0;
this.bi_buf = 0;
this.bi_valid = 0;
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
}
s.status = s.wrap ? INIT_STATE : BUSY_STATE;
strm.adler = s.wrap === 2 ? 0 : 1;
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) {
return Z_STREAM_ERROR;
}
if (strm.state.wrap !== 2) {
return Z_STREAM_ERROR;
}
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) {
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
} else if (windowBits > 15) {
wrap = 2;
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
var s = new DeflateState;
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils2.Buf8(s.w_size * 2);
s.head = new utils2.Buf16(s.hash_size);
s.prev = new utils2.Buf16(s.w_size);
s.lit_bufsize = 1 << memLevel + 6;
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils2.Buf8(s.pending_buf_size);
s.d_buf = 1 * s.lit_bufsize;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val;
if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush !== Z_FINISH) {
return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm;
old_flush = s.last_flush;
s.last_flush = flush;
if (s.status === INIT_STATE) {
if (s.wrap === 2) {
strm.adler = 0;
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) {
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0);
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
} else {
put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16));
put_byte(s, s.gzhead.time & 255);
put_byte(s, s.gzhead.time >> 8 & 255);
put_byte(s, s.gzhead.time >> 16 & 255);
put_byte(s, s.gzhead.time >> 24 & 255);
put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0);
put_byte(s, s.gzhead.os & 255);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 255);
put_byte(s, s.gzhead.extra.length >> 8 & 255);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
} else {
var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= level_flags << 6;
if (s.strstart !== 0) {
header |= PRESET_DICT;
}
header += 31 - header % 31;
s.status = BUSY_STATE;
putShortMSB(s, header);
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 65535);
}
strm.adler = 1;
}
}
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra) {
beg = s.pending;
while (s.gzindex < (s.gzhead.extra.length & 65535)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 255);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
} else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name) {
beg = s.pending;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 255;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
} else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment) {
beg = s.pending;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 255;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
} else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 255);
put_byte(s, strm.adler >> 8 & 255);
strm.adler = 0;
s.status = BUSY_STATE;
}
} else {
s.status = BUSY_STATE;
}
}
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1;
return Z_OK;
}
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH && s.status !== FINISH_STATE) {
var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush);
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
}
return Z_OK;
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
} else if (flush !== Z_BLOCK) {
trees._tr_stored_block(s, 0, 0, false);
if (flush === Z_FULL_FLUSH) {
zero(s.head);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1;
return Z_OK;
}
}
}
if (flush !== Z_FINISH) {
return Z_OK;
}
if (s.wrap <= 0) {
return Z_STREAM_END;
}
if (s.wrap === 2) {
put_byte(s, strm.adler & 255);
put_byte(s, strm.adler >> 8 & 255);
put_byte(s, strm.adler >> 16 & 255);
put_byte(s, strm.adler >> 24 & 255);
put_byte(s, strm.total_in & 255);
put_byte(s, strm.total_in >> 8 & 255);
put_byte(s, strm.total_in >> 16 & 255);
put_byte(s, strm.total_in >> 24 & 255);
} else {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 65535);
}
flush_pending(strm);
if (s.wrap > 0) {
s.wrap = -s.wrap;
}
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm || !strm.state) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
function deflateSetDictionary(strm, dictionary) {
var dictLength = dictionary.length;
var s;
var str, n;
var wrap;
var avail;
var next;
var input;
var tmpDict;
if (!strm || !strm.state) {
return Z_STREAM_ERROR;
}
s = strm.state;
wrap = s.wrap;
if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) {
return Z_STREAM_ERROR;
}
if (wrap === 1) {
strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
}
s.wrap = 0;
if (dictLength >= s.w_size) {
if (wrap === 0) {
zero(s.head);
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
tmpDict = new utils2.Buf8(s.w_size);
utils2.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
dictionary = tmpDict;
dictLength = s.w_size;
}
avail = strm.avail_in;
next = strm.next_in;
input = strm.input;
strm.avail_in = dictLength;
strm.next_in = 0;
strm.input = dictionary;
fill_window(s);
while (s.lookahead >= MIN_MATCH) {
str = s.strstart;
n = s.lookahead - (MIN_MATCH - 1);
do {
s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
} while (--n);
s.strstart = str;
s.lookahead = MIN_MATCH - 1;
fill_window(s);
}
s.strstart += s.lookahead;
s.block_start = s.strstart;
s.insert = s.lookahead;
s.lookahead = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
strm.next_in = next;
strm.input = input;
strm.avail_in = avail;
s.wrap = wrap;
return Z_OK;
}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateInfo = "pako deflate (from Nodeca project)";
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/utils/strings.js
var require_strings = __commonJS((exports) => {
var utils2 = require_common();
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try {
String.fromCharCode.apply(null, [0]);
} catch (__) {
STR_APPLY_OK = false;
}
try {
String.fromCharCode.apply(null, new Uint8Array(1));
} catch (__) {
STR_APPLY_UIA_OK = false;
}
var _utf8len = new utils2.Buf8(256);
for (q = 0;q < 256; q++) {
_utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
}
var q;
_utf8len[254] = _utf8len[254] = 1;
exports.string2buf = function(str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
for (m_pos = 0;m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 64512) === 55296 && m_pos + 1 < str_len) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 64512) === 56320) {
c = 65536 + (c - 55296 << 10) + (c2 - 56320);
m_pos++;
}
}
buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4;
}
buf = new utils2.Buf8(buf_len);
for (i = 0, m_pos = 0;i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 64512) === 55296 && m_pos + 1 < str_len) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 64512) === 56320) {
c = 65536 + (c - 55296 << 10) + (c2 - 56320);
m_pos++;
}
}
if (c < 128) {
buf[i++] = c;
} else if (c < 2048) {
buf[i++] = 192 | c >>> 6;
buf[i++] = 128 | c & 63;
} else if (c < 65536) {
buf[i++] = 224 | c >>> 12;
buf[i++] = 128 | c >>> 6 & 63;
buf[i++] = 128 | c & 63;
} else {
buf[i++] = 240 | c >>> 18;
buf[i++] = 128 | c >>> 12 & 63;
buf[i++] = 128 | c >>> 6 & 63;
buf[i++] = 128 | c & 63;
}
}
return buf;
};
function buf2binstring(buf, len) {
if (len < 65534) {
if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {
return String.fromCharCode.apply(null, utils2.shrinkBuf(buf, len));
}
}
var result = "";
for (var i = 0;i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
exports.binstring2buf = function(str) {
var buf = new utils2.Buf8(str.length);
for (var i = 0, len = buf.length;i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
exports.buf2string = function(buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
var utf16buf = new Array(len * 2);
for (out = 0, i = 0;i < len; ) {
c = buf[i++];
if (c < 128) {
utf16buf[out++] = c;
continue;
}
c_len = _utf8len[c];
if (c_len > 4) {
utf16buf[out++] = 65533;
i += c_len - 1;
continue;
}
c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7;
while (c_len > 1 && i < len) {
c = c << 6 | buf[i++] & 63;
c_len--;
}
if (c_len > 1) {
utf16buf[out++] = 65533;
continue;
}
if (c < 65536) {
utf16buf[out++] = c;
} else {
c -= 65536;
utf16buf[out++] = 55296 | c >> 10 & 1023;
utf16buf[out++] = 56320 | c & 1023;
}
}
return buf2binstring(utf16buf, out);
};
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) {
max = buf.length;
}
pos = max - 1;
while (pos >= 0 && (buf[pos] & 192) === 128) {
pos--;
}
if (pos < 0) {
return max;
}
if (pos === 0) {
return max;
}
return pos + _utf8len[buf[pos]] > max ? pos : max;
};
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/zstream.js
var require_zstream = __commonJS((exports, module) => {
function ZStream() {
this.input = null;
this.next_in = 0;
this.avail_in = 0;
this.total_in = 0;
this.output = null;
this.next_out = 0;
this.avail_out = 0;
this.total_out = 0;
this.msg = "";
this.state = null;
this.data_type = 2;
this.adler = 0;
}
module.exports = ZStream;
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/deflate.js
var require_deflate2 = __commonJS((exports) => {
var zlib_deflate = require_deflate();
var utils2 = require_common();
var strings = require_strings();
var msg = require_messages();
var ZStream = require_zstream();
var toString2 = Object.prototype.toString;
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
function Deflate(options) {
if (!(this instanceof Deflate))
return new Deflate(options);
this.options = utils2.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ""
}, options || {});
var opt = this.options;
if (opt.raw && opt.windowBits > 0) {
opt.windowBits = -opt.windowBits;
} else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) {
opt.windowBits += 16;
}
this.err = 0;
this.msg = "";
this.ended = false;
this.chunks = [];
this.strm = new ZStream;
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
if (opt.dictionary) {
var dict;
if (typeof opt.dictionary === "string") {
dict = strings.string2buf(opt.dictionary);
} else if (toString2.call(opt.dictionary) === "[object ArrayBuffer]") {
dict = new Uint8Array(opt.dictionary);
} else {
dict = opt.dictionary;
}
status = zlib_deflate.deflateSetDictionary(this.strm, dict);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
this._dict_set = true;
}
}
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) {
return false;
}
_mode = mode === ~~mode ? mode : mode === true ? Z_FINISH : Z_NO_FLUSH;
if (typeof data === "string") {
strm.input = strings.string2buf(data);
} else if (toString2.call(data) === "[object ArrayBuffer]") {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils2.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode);
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH)) {
if (this.options.to === "string") {
this.onData(strings.buf2binstring(utils2.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils2.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
Deflate.prototype.onEnd = function(status) {
if (status === Z_OK) {
if (this.options.to === "string") {
this.result = this.chunks.join("");
} else {
this.result = utils2.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
if (deflator.err) {
throw deflator.msg || msg[deflator.err];
}
return deflator.result;
}
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inffast.js
var require_inffast = __commonJS((exports, module) => {
var BAD = 30;
var TYPE = 12;
module.exports = function inflate_fast(strm, start) {
var state;
var _in;
var last;
var _out;
var beg;
var end;
var dmax;
var wsize;
var whave;
var wnext;
var s_window;
var hold;
var bits;
var lcode;
var dcode;
var lmask;
var dmask;
var here;
var op;
var len;
var dist;
var from;
var from_source;
var input, output;
state = strm.state;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
dmax = state.dmax;
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;; ) {
op = here >>> 24;
hold >>>= op;
bits -= op;
op = here >>> 16 & 255;
if (op === 0) {
output[_out++] = here & 65535;
} else if (op & 16) {
len = here & 65535;
op &= 15;
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & (1 << op) - 1;
hold >>>= op;
bits -= op;
}
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;; ) {
op = here >>> 24;
hold >>>= op;
bits -= op;
op = here >>> 16 & 255;
if (op & 16) {
dist = here & 65535;
op &= 15;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & (1 << op) - 1;
if (dist > dmax) {
strm.msg = "invalid distance too far back";
state.mode = BAD;
break top;
}
hold >>>= op;
bits -= op;
op = _out - beg;
if (dist > op) {
op = dist - op;
if (op > whave) {
if (state.sane) {
strm.msg = "invalid distance too far back";
state.mode = BAD;
break top;
}
}
from = 0;
from_source = s_window;
if (wnext === 0) {
from += wsize - op;
if (op < len) {
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist;
from_source = output;
}
} else if (wnext < op) {
from += wsize + wnext - op;
op -= wnext;
if (op < len) {
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) {
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist;
from_source = output;
}
}
} else {
from += wnext - op;
if (op < len) {
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist;
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
} else {
from = _out - dist;
do {
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
} else if ((op & 64) === 0) {
here = dcode[(here & 65535) + (hold & (1 << op) - 1)];
continue dodist;
} else {
strm.msg = "invalid distance code";
state.mode = BAD;
break top;
}
break;
}
} else if ((op & 64) === 0) {
here = lcode[(here & 65535) + (hold & (1 << op) - 1)];
continue dolen;
} else if (op & 32) {
state.mode = TYPE;
break top;
} else {
strm.msg = "invalid literal/length code";
state.mode = BAD;
break top;
}
break;
}
} while (_in < last && _out < end);
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);
strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);
state.hold = hold;
state.bits = bits;
return;
};
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inftrees.js
var require_inftrees = __commonJS((exports, module) => {
var utils2 = require_common();
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [
3,
4,
5,
6,
7,
8,
9,
10,
11,
13,
15,
17,
19,
23,
27,
31,
35,
43,
51,
59,
67,
83,
99,
115,
131,
163,
195,
227,
258,
0,
0
];
var lext = [
16,
16,
16,
16,
16,
16,
16,
16,
17,
17,
17,
17,
18,
18,
18,
18,
19,
19,
19,
19,
20,
20,
20,
20,
21,
21,
21,
21,
16,
72,
78
];
var dbase = [
1,
2,
3,
4,
5,
7,
9,
13,
17,
25,
33,
49,
65,
97,
129,
193,
257,
385,
513,
769,
1025,
1537,
2049,
3073,
4097,
6145,
8193,
12289,
16385,
24577,
0,
0
];
var dext = [
16,
16,
16,
16,
17,
17,
18,
18,
19,
19,
20,
20,
21,
21,
22,
22,
23,
23,
24,
24,
25,
25,
26,
26,
27,
27,
28,
28,
29,
29,
64,
64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
var bits = opts.bits;
var len = 0;
var sym = 0;
var min = 0, max = 0;
var root = 0;
var curr = 0;
var drop = 0;
var left = 0;
var used = 0;
var huff = 0;
var incr;
var fill;
var low;
var mask;
var next;
var base = null;
var base_index = 0;
var end;
var count = new utils2.Buf16(MAXBITS + 1);
var offs = new utils2.Buf16(MAXBITS + 1);
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
for (len = 0;len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0;sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
root = bits;
for (max = MAXBITS;max >= 1; max--) {
if (count[max] !== 0) {
break;
}
}
if (root > max) {
root = max;
}
if (max === 0) {
table[table_index++] = 1 << 24 | 64 << 16 | 0;
table[table_index++] = 1 << 24 | 64 << 16 | 0;
opts.bits = 1;
return 0;
}
for (min = 1;min < max; min++) {
if (count[min] !== 0) {
break;
}
}
if (root < min) {
root = min;
}
left = 1;
for (len = 1;len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
}
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1;
}
offs[1] = 0;
for (len = 1;len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
for (sym = 0;sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
if (type === CODES) {
base = extra = work;
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else {
base = dbase;
extra = dext;
end = -1;
}
huff = 0;
sym = 0;
len = min;
next = table_index;
curr = root;
drop = 0;
low = -1;
used = 1 << root;
mask = used - 1;
if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) {
return 1;
}
for (;; ) {
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
} else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
} else {
here_op = 32 + 64;
here_val = 0;
}
incr = 1 << len - drop;
fill = 1 << curr;
min = fill;
do {
fill -= incr;
table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0;
} while (fill !== 0);
incr = 1 << len - 1;
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
sym++;
if (--count[len] === 0) {
if (len === max) {
break;
}
len = lens[lens_index + work[sym]];
}
if (len > root && (huff & mask) !== low) {
if (drop === 0) {
drop = root;
}
next += min;
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) {
break;
}
curr++;
left <<= 1;
}
used += 1 << curr;
if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) {
return 1;
}
low = huff & mask;
table[low] = root << 24 | curr << 16 | next - table_index | 0;
}
}
if (huff !== 0) {
table[next + huff] = len - drop << 24 | 64 << 16 | 0;
}
opts.bits = root;
return 0;
};
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inflate.js
var require_inflate = __commonJS((exports) => {
var utils2 = require_common();
var adler32 = require_adler32();
var crc32 = require_crc32();
var inflate_fast = require_inffast();
var inflate_table = require_inftrees();
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
var Z_DEFLATED = 8;
var HEAD = 1;
var FLAGS = 2;
var TIME = 3;
var OS = 4;
var EXLEN = 5;
var EXTRA = 6;
var NAME = 7;
var COMMENT = 8;
var HCRC = 9;
var DICTID = 10;
var DICT = 11;
var TYPE = 12;
var TYPEDO = 13;
var STORED = 14;
var COPY_ = 15;
var COPY = 16;
var TABLE = 17;
var LENLENS = 18;
var CODELENS = 19;
var LEN_ = 20;
var LEN = 21;
var LENEXT = 22;
var DIST = 23;
var DISTEXT = 24;
var MATCH = 25;
var LIT = 26;
var CHECK = 27;
var LENGTH = 28;
var DONE = 29;
var BAD = 30;
var MEM = 31;
var SYNC = 32;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
var MAX_WBITS = 15;
var DEF_WBITS = MAX_WBITS;
function zswap32(q) {
return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24);
}
function InflateState() {
this.mode = 0;
this.last = false;
this.wrap = 0;
this.havedict = false;
this.flags = 0;
this.dmax = 0;
this.check = 0;
this.total = 0;
this.head = null;
this.wbits = 0;
this.wsize = 0;
this.whave = 0;
this.wnext = 0;
this.window = null;
this.hold = 0;
this.bits = 0;
this.length = 0;
this.offset = 0;
this.extra = 0;
this.lencode = null;
this.distcode = null;
this.lenbits = 0;
this.distbits = 0;
this.ncode = 0;
this.nlen = 0;
this.ndist = 0;
this.have = 0;
this.next = null;
this.lens = new utils2.Buf16(320);
this.work = new utils2.Buf16(288);
this.lendyn = null;
this.distdyn = null;
this.sane = 0;
this.back = 0;
this.was = 0;
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) {
return Z_STREAM_ERROR;
}
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = "";
if (state.wrap) {
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null;
state.hold = 0;
state.bits = 0;
state.lencode = state.lendyn = new utils2.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils2.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) {
return Z_STREAM_ERROR;
}
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
if (!strm || !strm.state) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
} else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) {
return Z_STREAM_ERROR;
}
state = new InflateState;
strm.state = state;
state.window = null;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
var virgin = true;
var lenfix;
var distfix;
function fixedtables(state) {
if (virgin) {
var sym;
lenfix = new utils2.Buf32(512);
distfix = new utils2.Buf32(32);
sym = 0;
while (sym < 144) {
state.lens[sym++] = 8;
}
while (sym < 256) {
state.lens[sym++] = 9;
}
while (sym < 280) {
state.lens[sym++] = 7;
}
while (sym < 288) {
state.lens[sym++] = 8;
}
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
sym = 0;
while (sym < 32) {
state.lens[sym++] = 5;
}
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils2.Buf8(state.wsize);
}
if (copy >= state.wsize) {
utils2.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
} else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
utils2.arraySet(state.window, src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
utils2.arraySet(state.window, src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
} else {
state.wnext += dist;
if (state.wnext === state.wsize) {
state.wnext = 0;
}
if (state.whave < state.wsize) {
state.whave += dist;
}
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output;
var next;
var put;
var have, left;
var hold;
var bits;
var _in, _out;
var copy;
var from;
var from_source;
var here = 0;
var here_bits, here_op, here_val;
var last_bits, last_op, last_val;
var len;
var ret;
var hbuf = new utils2.Buf8(4);
var opts;
var n;
var order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) {
state.mode = TYPEDO;
}
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
_in = have;
_out = left;
ret = Z_OK;
inf_leave:
for (;; ) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
while (bits < 16) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
if (state.wrap & 2 && hold === 35615) {
state.check = 0;
hbuf[0] = hold & 255;
hbuf[1] = hold >>> 8 & 255;
state.check = crc32(state.check, hbuf, 2, 0);
hold = 0;
bits = 0;
state.mode = FLAGS;
break;
}
state.flags = 0;
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || (((hold & 255) << 8) + (hold >> 8)) % 31) {
strm.msg = "incorrect header check";
state.mode = BAD;
break;
}
if ((hold & 15) !== Z_DEFLATED) {
strm.msg = "unknown compression method";
state.mode = BAD;
break;
}
hold >>>= 4;
bits -= 4;
len = (hold & 15) + 8;
if (state.wbits === 0) {
state.wbits = len;
} else if (len > state.wbits) {
strm.msg = "invalid window size";
state.mode = BAD;
break;
}
state.dmax = 1 << len;
strm.adler = state.check = 1;
state.mode = hold & 512 ? DICTID : TYPE;
hold = 0;
bits = 0;
break;
case FLAGS:
while (bits < 16) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
state.flags = hold;
if ((state.flags & 255) !== Z_DEFLATED) {
strm.msg = "unknown compression method";
state.mode = BAD;
break;
}
if (state.flags & 57344) {
strm.msg = "unknown header flags set";
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = hold >> 8 & 1;
}
if (state.flags & 512) {
hbuf[0] = hold & 255;
hbuf[1] = hold >>> 8 & 255;
state.check = crc32(state.check, hbuf, 2, 0);
}
hold = 0;
bits = 0;
state.mode = TIME;
case TIME:
while (bits < 32) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
if (state.head) {
state.head.time = hold;
}
if (state.flags & 512) {
hbuf[0] = hold & 255;
hbuf[1] = hold >>> 8 & 255;
hbuf[2] = hold >>> 16 & 255;
hbuf[3] = hold >>> 24 & 255;
state.check = crc32(state.check, hbuf, 4, 0);
}
hold = 0;
bits = 0;
state.mode = OS;
case OS:
while (bits < 16) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
if (state.head) {
state.head.xflags = hold & 255;
state.head.os = hold >> 8;
}
if (state.flags & 512) {
hbuf[0] = hold & 255;
hbuf[1] = hold >>> 8 & 255;
state.check = crc32(state.check, hbuf, 2, 0);
}
hold = 0;
bits = 0;
state.mode = EXLEN;
case EXLEN:
if (state.flags & 1024) {
while (bits < 16) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 512) {
hbuf[0] = hold & 255;
hbuf[1] = hold >>> 8 & 255;
state.check = crc32(state.check, hbuf, 2, 0);
}
hold = 0;
bits = 0;
} else if (state.head) {
state.head.extra = null;
}
state.mode = EXTRA;
case EXTRA:
if (state.flags & 1024) {
copy = state.length;
if (copy > have) {
copy = have;
}
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
state.head.extra = new Array(state.head.extra_len);
}
utils2.arraySet(state.head.extra, input, next, copy, len);
}
if (state.flags & 512) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) {
break inf_leave;
}
}
state.length = 0;
state.mode = NAME;
case NAME:
if (state.flags & 2048) {
if (have === 0) {
break inf_leave;
}
copy = 0;
do {
len = input[next + copy++];
if (state.head && len && state.length < 65536) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 512) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) {
break inf_leave;
}
} else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
case COMMENT:
if (state.flags & 4096) {
if (have === 0) {
break inf_leave;
}
copy = 0;
do {
len = input[next + copy++];
if (state.head && len && state.length < 65536) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 512) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) {
break inf_leave;
}
} else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
case HCRC:
if (state.flags & 512) {
while (bits < 16) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
if (hold !== (state.check & 65535)) {
strm.msg = "header crc mismatch";
state.mode = BAD;
break;
}
hold = 0;
bits = 0;
}
if (state.head) {
state.head.hcrc = state.flags >> 9 & 1;
state.head.done = true;
}
strm.adler = state.check = 0;
state.mode = TYPE;
break;
case DICTID:
while (bits < 32) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
strm.adler = state.check = zswap32(hold);
hold = 0;
bits = 0;
state.mode = DICT;
case DICT:
if (state.havedict === 0) {
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
return Z_NEED_DICT;
}
strm.adler = state.check = 1;
state.mode = TYPE;
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) {
break inf_leave;
}
case TYPEDO:
if (state.last) {
hold >>>= bits & 7;
bits -= bits & 7;
state.mode = CHECK;
break;
}
while (bits < 3) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
state.last = hold & 1;
hold >>>= 1;
bits -= 1;
switch (hold & 3) {
case 0:
state.mode = STORED;
break;
case 1:
fixedtables(state);
state.mode = LEN_;
if (flush === Z_TREES) {
hold >>>= 2;
bits -= 2;
break inf_leave;
}
break;
case 2:
state.mode = TABLE;
break;
case 3:
strm.msg = "invalid block type";
state.mode = BAD;
}
hold >>>= 2;
bits -= 2;
break;
case STORED:
hold >>>= bits & 7;
bits -= bits & 7;
while (bits < 32) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
if ((hold & 65535) !== (hold >>> 16 ^ 65535)) {
strm.msg = "invalid stored block lengths";
state.mode = BAD;
break;
}
state.length = hold & 65535;
hold = 0;
bits = 0;
state.mode = COPY_;
if (flush === Z_TREES) {
break inf_leave;
}
case COPY_:
state.mode = COPY;
case COPY:
copy = state.length;
if (copy) {
if (copy > have) {
copy = have;
}
if (copy > left) {
copy = left;
}
if (copy === 0) {
break inf_leave;
}
utils2.arraySet(output, input, next, copy, put);
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
state.mode = TYPE;
break;
case TABLE:
while (bits < 14) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
state.nlen = (hold & 31) + 257;
hold >>>= 5;
bits -= 5;
state.ndist = (hold & 31) + 1;
hold >>>= 5;
bits -= 5;
state.ncode = (hold & 15) + 4;
hold >>>= 4;
bits -= 4;
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = "too many length or distance symbols";
state.mode = BAD;
break;
}
state.have = 0;
state.mode = LENLENS;
case LENLENS:
while (state.have < state.ncode) {
while (bits < 3) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
state.lens[order[state.have++]] = hold & 7;
hold >>>= 3;
bits -= 3;
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
state.lencode = state.lendyn;
state.lenbits = 7;
opts = { bits: state.lenbits };
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = "invalid code lengths set";
state.mode = BAD;
break;
}
state.have = 0;
state.mode = CODELENS;
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;; ) {
here = state.lencode[hold & (1 << state.lenbits) - 1];
here_bits = here >>> 24;
here_op = here >>> 16 & 255;
here_val = here & 65535;
if (here_bits <= bits) {
break;
}
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
if (here_val < 16) {
hold >>>= here_bits;
bits -= here_bits;
state.lens[state.have++] = here_val;
} else {
if (here_val === 16) {
n = here_bits + 2;
while (bits < n) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
hold >>>= here_bits;
bits -= here_bits;
if (state.have === 0) {
strm.msg = "invalid bit length repeat";
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 3);
hold >>>= 2;
bits -= 2;
} else if (here_val === 17) {
n = here_bits + 3;
while (bits < n) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
hold >>>= here_bits;
bits -= here_bits;
len = 0;
copy = 3 + (hold & 7);
hold >>>= 3;
bits -= 3;
} else {
n = here_bits + 7;
while (bits < n) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
hold >>>= here_bits;
bits -= here_bits;
len = 0;
copy = 11 + (hold & 127);
hold >>>= 7;
bits -= 7;
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = "invalid bit length repeat";
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
if (state.mode === BAD) {
break;
}
if (state.lens[256] === 0) {
strm.msg = "invalid code -- missing end-of-block";
state.mode = BAD;
break;
}
state.lenbits = 9;
opts = { bits: state.lenbits };
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = "invalid literal/lengths set";
state.mode = BAD;
break;
}
state.distbits = 6;
state.distcode = state.distdyn;
opts = { bits: state.distbits };
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
state.distbits = opts.bits;
if (ret) {
strm.msg = "invalid distances set";
state.mode = BAD;
break;
}
state.mode = LEN_;
if (flush === Z_TREES) {
break inf_leave;
}
case LEN_:
state.mode = LEN;
case LEN:
if (have >= 6 && left >= 258) {
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
inflate_fast(strm, _out);
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;; ) {
here = state.lencode[hold & (1 << state.lenbits) - 1];
here_bits = here >>> 24;
here_op = here >>> 16 & 255;
here_val = here & 65535;
if (here_bits <= bits) {
break;
}
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
if (here_op && (here_op & 240) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;; ) {
here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)];
here_bits = here >>> 24;
here_op = here >>> 16 & 255;
here_val = here & 65535;
if (last_bits + here_bits <= bits) {
break;
}
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
hold >>>= last_bits;
bits -= last_bits;
state.back += last_bits;
}
hold >>>= here_bits;
bits -= here_bits;
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
state.mode = LIT;
break;
}
if (here_op & 32) {
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = "invalid literal/length code";
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
case LENEXT:
if (state.extra) {
n = state.extra;
while (bits < n) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
state.length += hold & (1 << state.extra) - 1;
hold >>>= state.extra;
bits -= state.extra;
state.back += state.extra;
}
state.was = state.length;
state.mode = DIST;
case DIST:
for (;; ) {
here = state.distcode[hold & (1 << state.distbits) - 1];
here_bits = here >>> 24;
here_op = here >>> 16 & 255;
here_val = here & 65535;
if (here_bits <= bits) {
break;
}
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
if ((here_op & 240) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;; ) {
here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)];
here_bits = here >>> 24;
here_op = here >>> 16 & 255;
here_val = here & 65535;
if (last_bits + here_bits <= bits) {
break;
}
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
hold >>>= last_bits;
bits -= last_bits;
state.back += last_bits;
}
hold >>>= here_bits;
bits -= here_bits;
state.back += here_bits;
if (here_op & 64) {
strm.msg = "invalid distance code";
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = here_op & 15;
state.mode = DISTEXT;
case DISTEXT:
if (state.extra) {
n = state.extra;
while (bits < n) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
state.offset += hold & (1 << state.extra) - 1;
hold >>>= state.extra;
bits -= state.extra;
state.back += state.extra;
}
if (state.offset > state.dmax) {
strm.msg = "invalid distance too far back";
state.mode = BAD;
break;
}
state.mode = MATCH;
case MATCH:
if (left === 0) {
break inf_leave;
}
copy = _out - left;
if (state.offset > copy) {
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = "invalid distance too far back";
state.mode = BAD;
break;
}
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
} else {
from = state.wnext - copy;
}
if (copy > state.length) {
copy = state.length;
}
from_source = state.window;
} else {
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) {
copy = left;
}
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) {
state.mode = LEN;
}
break;
case LIT:
if (left === 0) {
break inf_leave;
}
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
while (bits < 32) {
if (have === 0) {
break inf_leave;
}
have--;
hold |= input[next++] << bits;
bits += 8;
}
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check = state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out);
}
_out = left;
if ((state.flags ? hold : zswap32(hold)) !== state.check) {
strm.msg = "incorrect data check";
state.mode = BAD;
break;
}
hold = 0;
bits = 0;
}
state.mode = LENGTH;
case LENGTH:
if (state.wrap && state.flags) {
while (bits < 32) {
if (have === 0) {
break inf_leave;
}
have--;
hold += input[next++] << bits;
bits += 8;
}
if (hold !== (state.total & 4294967295)) {
strm.msg = "incorrect length check";
state.mode = BAD;
break;
}
hold = 0;
bits = 0;
}
state.mode = DONE;
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
default:
return Z_STREAM_ERROR;
}
}
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH)) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out);
}
strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
if (!strm || !strm.state) {
return Z_STREAM_ERROR;
}
state = strm.state;
if ((state.wrap & 2) === 0) {
return Z_STREAM_ERROR;
}
state.head = head;
head.done = false;
return Z_OK;
}
function inflateSetDictionary(strm, dictionary) {
var dictLength = dictionary.length;
var state;
var dictid;
var ret;
if (!strm || !strm.state) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.wrap !== 0 && state.mode !== DICT) {
return Z_STREAM_ERROR;
}
if (state.mode === DICT) {
dictid = 1;
dictid = adler32(dictid, dictionary, dictLength, 0);
if (dictid !== state.check) {
return Z_DATA_ERROR;
}
}
ret = updatewindow(strm, dictionary, dictLength, dictLength);
if (ret) {
state.mode = MEM;
return Z_MEM_ERROR;
}
state.havedict = 1;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateInfo = "pako inflate (from Nodeca project)";
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/constants.js
var require_constants2 = __commonJS((exports, module) => {
module.exports = {
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
Z_BUF_ERROR: -5,
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
Z_BINARY: 0,
Z_TEXT: 1,
Z_UNKNOWN: 2,
Z_DEFLATED: 8
};
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/gzheader.js
var require_gzheader = __commonJS((exports, module) => {
function GZheader() {
this.text = 0;
this.time = 0;
this.xflags = 0;
this.os = 0;
this.extra = null;
this.extra_len = 0;
this.name = "";
this.comment = "";
this.hcrc = 0;
this.done = false;
}
module.exports = GZheader;
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/inflate.js
var require_inflate2 = __commonJS((exports) => {
var zlib_inflate = require_inflate();
var utils2 = require_common();
var strings = require_strings();
var c = require_constants2();
var msg = require_messages();
var ZStream = require_zstream();
var GZheader = require_gzheader();
var toString2 = Object.prototype.toString;
function Inflate(options) {
if (!(this instanceof Inflate))
return new Inflate(options);
this.options = utils2.assign({
chunkSize: 16384,
windowBits: 0,
to: ""
}, options || {});
var opt = this.options;
if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) {
opt.windowBits = -15;
}
}
if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) {
opt.windowBits += 32;
}
if (opt.windowBits > 15 && opt.windowBits < 48) {
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0;
this.msg = "";
this.ended = false;
this.chunks = [];
this.strm = new ZStream;
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(this.strm, opt.windowBits);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new GZheader;
zlib_inflate.inflateGetHeader(this.strm, this.header);
if (opt.dictionary) {
if (typeof opt.dictionary === "string") {
opt.dictionary = strings.string2buf(opt.dictionary);
} else if (toString2.call(opt.dictionary) === "[object ArrayBuffer]") {
opt.dictionary = new Uint8Array(opt.dictionary);
}
if (opt.raw) {
status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
}
}
}
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var dictionary = this.options.dictionary;
var status, _mode;
var next_out_utf8, tail, utf8str;
var allowBufError = false;
if (this.ended) {
return false;
}
_mode = mode === ~~mode ? mode : mode === true ? c.Z_FINISH : c.Z_NO_FLUSH;
if (typeof data === "string") {
strm.input = strings.binstring2buf(data);
} else if (toString2.call(data) === "[object ArrayBuffer]") {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils2.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);
if (status === c.Z_NEED_DICT && dictionary) {
status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
}
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) {
if (this.options.to === "string") {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) {
utils2.arraySet(strm.output, strm.output, next_out_utf8, tail, 0);
}
this.onData(utf8str);
} else {
this.onData(utils2.shrinkBuf(strm.output, strm.next_out));
}
}
}
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
Inflate.prototype.onEnd = function(status) {
if (status === c.Z_OK) {
if (this.options.to === "string") {
this.result = this.chunks.join("");
} else {
this.result = utils2.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
if (inflator.err) {
throw inflator.msg || msg[inflator.err];
}
return inflator.result;
}
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
});
// ../../node_modules/.bun/pako@1.0.11/node_modules/pako/index.js
var require_pako = __commonJS((exports, module) => {
var assign = require_common().assign;
var deflate = require_deflate2();
var inflate = require_inflate2();
var constants3 = require_constants2();
var pako = {};
assign(pako, deflate, inflate, constants3);
module.exports = pako;
});
// ../../node_modules/.bun/utif2@4.1.0/node_modules/utif2/UTIF.js
var require_UTIF = __commonJS((exports, module) => {
(function() {
var UTIF = {};
if (typeof module == "object") {
module.exports = UTIF;
} else {
self.UTIF = UTIF;
}
var pako = require_pako();
function log() {
if (typeof process == "undefined" || true)
console.log.apply(console, arguments);
}
(function(UTIF2, pako2) {
(function() {
var W = function a1() {
function W2(p) {
this.message = "JPEG error: " + p;
}
W2.prototype = new Error;
W2.prototype.name = "JpegError";
W2.constructor = W2;
return W2;
}(), ak = function ag() {
var p = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]), t = 4017, ac = 799, ah = 3406, ao = 2276, ar = 1567, ai = 3784, s = 5793, ad = 2896;
function ak2(Q) {
if (Q == null)
Q = {};
if (Q.w == null)
Q.w = -1;
this.V = Q.n;
this.N = Q.w;
}
function a5(Q, h) {
var f = 0, G = [], n, E, a = 16, F;
while (a > 0 && !Q[a - 1]) {
a--;
}
G.push({ children: [], index: 0 });
var C = G[0];
for (n = 0;n < a; n++) {
for (E = 0;E < Q[n]; E++) {
C = G.pop();
C.children[C.index] = h[f];
while (C.index > 0) {
C = G.pop();
}
C.index++;
G.push(C);
while (G.length <= n) {
G.push(F = { children: [], index: 0 });
C.children[C.index] = F.children;
C = F;
}
f++;
}
if (n + 1 < a) {
G.push(F = { children: [], index: 0 });
C.children[C.index] = F.children;
C = F;
}
}
return G[0].children;
}
function a2(Q, h, f) {
return 64 * ((Q.P + 1) * h + f);
}
function a7(Q, h, f, G, n, E, a, C, F, d) {
if (d == null)
d = false;
var { m: T, Z: U } = f, z = h, J = 0, V = 0, r = 0, D = 0, a8, q = 0, X, O, _, N, e, K, x = 0, k, g, R, c;
function Y() {
if (V > 0) {
V--;
return J >> V & 1;
}
J = Q[h++];
if (J === 255) {
var I = Q[h++];
if (I) {
if (I === 220 && d) {
h += 2;
var l = Z(Q, h);
h += 2;
if (l > 0 && l !== f.s) {
throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data", l);
}
} else if (I === 217) {
if (d) {
var M = q * 8;
if (M > 0 && M < f.s / 10) {
throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, " + "possibly caused by incorrect `scanLines` parameter", M);
}
}
throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data");
}
throw new W("unexpected marker");
}
}
V = 7;
return J >>> 7;
}
function u(I) {
var l = I;
while (true) {
l = l[Y()];
switch (typeof l) {
case "number":
return l;
case "object":
continue;
}
throw new W("invalid huffman sequence");
}
}
function m(I) {
var e2 = 0;
while (I > 0) {
e2 = e2 << 1 | Y();
I--;
}
return e2;
}
function j(I) {
if (I === 1) {
return Y() === 1 ? 1 : -1;
}
var e2 = m(I);
if (e2 >= 1 << I - 1) {
return e2;
}
return e2 + (-1 << I) + 1;
}
function v(X2, I) {
var l = u(X2.J), M = l === 0 ? 0 : j(l), N2 = 1;
X2.D[I] = X2.Q += M;
while (N2 < 64) {
var S = u(X2.i), i = S & 15, A = S >> 4;
if (i === 0) {
if (A < 15) {
break;
}
N2 += 16;
continue;
}
N2 += A;
var o = p[N2];
X2.D[I + o] = j(i);
N2++;
}
}
function $(X2, I) {
var l = u(X2.J), M = l === 0 ? 0 : j(l) << F;
X2.D[I] = X2.Q += M;
}
function b(X2, I) {
X2.D[I] |= Y() << F;
}
function P(X2, I) {
if (r > 0) {
r--;
return;
}
var N2 = E, l = a;
while (N2 <= l) {
var M = u(X2.i), S = M & 15, i = M >> 4;
if (S === 0) {
if (i < 15) {
r = m(i) + (1 << i) - 1;
break;
}
N2 += 16;
continue;
}
N2 += i;
var A = p[N2];
X2.D[I + A] = j(S) * (1 << F);
N2++;
}
}
function a4(X2, I) {
var N2 = E, l = a, M = 0, S, i;
while (N2 <= l) {
var A = I + p[N2], o = X2.D[A] < 0 ? -1 : 1;
switch (D) {
case 0:
i = u(X2.i);
S = i & 15;
M = i >> 4;
if (S === 0) {
if (M < 15) {
r = m(M) + (1 << M);
D = 4;
} else {
M = 16;
D = 1;
}
} else {
if (S !== 1) {
throw new W("invalid ACn encoding");
}
a8 = j(S);
D = M ? 2 : 3;
}
continue;
case 1:
case 2:
if (X2.D[A]) {
X2.D[A] += o * (Y() << F);
} else {
M--;
if (M === 0) {
D = D === 2 ? 3 : 0;
}
}
break;
case 3:
if (X2.D[A]) {
X2.D[A] += o * (Y() << F);
} else {
X2.D[A] = a8 << F;
D = 0;
}
break;
case 4:
if (X2.D[A]) {
X2.D[A] += o * (Y() << F);
}
break;
}
N2++;
}
if (D === 4) {
r--;
if (r === 0) {
D = 0;
}
}
}
function H(X2, I, x2, l, M) {
var S = x2 / T | 0, i = x2 % T;
q = S * X2.A + l;
var A = i * X2.h + M, o = a2(X2, q, A);
I(X2, o);
}
function w(X2, I, x2) {
q = x2 / X2.P | 0;
var l = x2 % X2.P, M = a2(X2, q, l);
I(X2, M);
}
var y = G.length;
if (U) {
if (E === 0) {
K = C === 0 ? $ : b;
} else {
K = C === 0 ? P : a4;
}
} else {
K = v;
}
if (y === 1) {
g = G[0].P * G[0].c;
} else {
g = T * f.R;
}
while (x <= g) {
var L = n ? Math.min(g - x, n) : g;
if (L > 0) {
for (O = 0;O < y; O++) {
G[O].Q = 0;
}
r = 0;
if (y === 1) {
X = G[0];
for (e = 0;e < L; e++) {
w(X, K, x);
x++;
}
} else {
for (e = 0;e < L; e++) {
for (O = 0;O < y; O++) {
X = G[O];
R = X.h;
c = X.A;
for (_ = 0;_ < c; _++) {
for (N = 0;N < R; N++) {
H(X, K, x, _, N);
}
}
}
x++;
}
}
}
V = 0;
k = an(Q, h);
if (!k) {
break;
}
if (k.u) {
var a6 = L > 0 ? "unexpected" : "excessive";
h = k.offset;
}
if (k.M >= 65488 && k.M <= 65495) {
h += 2;
} else {
break;
}
}
return h - z;
}
function al(Q, h, f) {
var { $: G, D: n } = Q, E, a, C, F, d, T, U, z, J, V, Y, u, m, j, v, $, b;
if (!G) {
throw new W("missing required Quantization Table.");
}
for (var r = 0;r < 64; r += 8) {
J = n[h + r];
V = n[h + r + 1];
Y = n[h + r + 2];
u = n[h + r + 3];
m = n[h + r + 4];
j = n[h + r + 5];
v = n[h + r + 6];
$ = n[h + r + 7];
J *= G[r];
if ((V | Y | u | m | j | v | $) === 0) {
b = s * J + 512 >> 10;
f[r] = b;
f[r + 1] = b;
f[r + 2] = b;
f[r + 3] = b;
f[r + 4] = b;
f[r + 5] = b;
f[r + 6] = b;
f[r + 7] = b;
continue;
}
V *= G[r + 1];
Y *= G[r + 2];
u *= G[r + 3];
m *= G[r + 4];
j *= G[r + 5];
v *= G[r + 6];
$ *= G[r + 7];
E = s * J + 128 >> 8;
a = s * m + 128 >> 8;
C = Y;
F = v;
d = ad * (V - $) + 128 >> 8;
z = ad * (V + $) + 128 >> 8;
T = u << 4;
U = j << 4;
E = E + a + 1 >> 1;
a = E - a;
b = C * ai + F * ar + 128 >> 8;
C = C * ar - F * ai + 128 >> 8;
F = b;
d = d + U + 1 >> 1;
U = d - U;
z = z + T + 1 >> 1;
T = z - T;
E = E + F + 1 >> 1;
F = E - F;
a = a + C + 1 >> 1;
C = a - C;
b = d * ao + z * ah + 2048 >> 12;
d = d * ah - z * ao + 2048 >> 12;
z = b;
b = T * ac + U * t + 2048 >> 12;
T = T * t - U * ac + 2048 >> 12;
U = b;
f[r] = E + z;
f[r + 7] = E - z;
f[r + 1] = a + U;
f[r + 6] = a - U;
f[r + 2] = C + T;
f[r + 5] = C - T;
f[r + 3] = F + d;
f[r + 4] = F - d;
}
for (var P = 0;P < 8; ++P) {
J = f[P];
V = f[P + 8];
Y = f[P + 16];
u = f[P + 24];
m = f[P + 32];
j = f[P + 40];
v = f[P + 48];
$ = f[P + 56];
if ((V | Y | u | m | j | v | $) === 0) {
b = s * J + 8192 >> 14;
if (b < -2040) {
b = 0;
} else if (b >= 2024) {
b = 255;
} else {
b = b + 2056 >> 4;
}
n[h + P] = b;
n[h + P + 8] = b;
n[h + P + 16] = b;
n[h + P + 24] = b;
n[h + P + 32] = b;
n[h + P + 40] = b;
n[h + P + 48] = b;
n[h + P + 56] = b;
continue;
}
E = s * J + 2048 >> 12;
a = s * m + 2048 >> 12;
C = Y;
F = v;
d = ad * (V - $) + 2048 >> 12;
z = ad * (V + $) + 2048 >> 12;
T = u;
U = j;
E = (E + a + 1 >> 1) + 4112;
a = E - a;
b = C * ai + F * ar + 2048 >> 12;
C = C * ar - F * ai + 2048 >> 12;
F = b;
d = d + U + 1 >> 1;
U = d - U;
z = z + T + 1 >> 1;
T = z - T;
E = E + F + 1 >> 1;
F = E - F;
a = a + C + 1 >> 1;
C = a - C;
b = d * ao + z * ah + 2048 >> 12;
d = d * ah - z * ao + 2048 >> 12;
z = b;
b = T * ac + U * t + 2048 >> 12;
T = T * t - U * ac + 2048 >> 12;
U = b;
J = E + z;
$ = E - z;
V = a + U;
v = a - U;
Y = C + T;
j = C - T;
u = F + d;
m = F - d;
if (J < 16) {
J = 0;
} else if (J >= 4080) {
J = 255;
} else {
J >>= 4;
}
if (V < 16) {
V = 0;
} else if (V >= 4080) {
V = 255;
} else {
V >>= 4;
}
if (Y < 16) {
Y = 0;
} else if (Y >= 4080) {
Y = 255;
} else {
Y >>= 4;
}
if (u < 16) {
u = 0;
} else if (u >= 4080) {
u = 255;
} else {
u >>= 4;
}
if (m < 16) {
m = 0;
} else if (m >= 4080) {
m = 255;
} else {
m >>= 4;
}
if (j < 16) {
j = 0;
} else if (j >= 4080) {
j = 255;
} else {
j >>= 4;
}
if (v < 16) {
v = 0;
} else if (v >= 4080) {
v = 255;
} else {
v >>= 4;
}
if ($ < 16) {
$ = 0;
} else if ($ >= 4080) {
$ = 255;
} else {
$ >>= 4;
}
n[h + P] = J;
n[h + P + 8] = V;
n[h + P + 16] = Y;
n[h + P + 24] = u;
n[h + P + 32] = m;
n[h + P + 40] = j;
n[h + P + 48] = v;
n[h + P + 56] = $;
}
}
function a0(Q, h) {
var { P: f, c: G } = h, n = new Int16Array(64);
for (var E = 0;E < G; E++) {
for (var a = 0;a < f; a++) {
var C = a2(h, E, a);
al(h, C, n);
}
}
return h.D;
}
function an(Q, h, f) {
if (f == null)
f = h;
var G = Q.length - 1, n = f < h ? f : h;
if (h >= G) {
return null;
}
var E = Z(Q, h);
if (E >= 65472 && E <= 65534) {
return { u: null, M: E, offset: h };
}
var a = Z(Q, n);
while (!(a >= 65472 && a <= 65534)) {
if (++n >= G) {
return null;
}
a = Z(Q, n);
}
return { u: E.toString(16), M: a, offset: n };
}
ak2.prototype = { parse(Q, h) {
if (h == null)
h = {};
var f = h.F, E = 0, a = null, C = null, F, d, T = 0;
function G() {
var o = Z(Q, E);
E += 2;
var B = E + o - 2, V2 = an(Q, B, E);
if (V2 && V2.u) {
B = V2.offset;
}
var ab = Q.subarray(E, B);
E += ab.length;
return ab;
}
function n(F2) {
var o = Math.ceil(F2.o / 8 / F2.X), B = Math.ceil(F2.s / 8 / F2.B);
for (var Y2 = 0;Y2 < F2.W.length; Y2++) {
R = F2.W[Y2];
var ab = Math.ceil(Math.ceil(F2.o / 8) * R.h / F2.X), af = Math.ceil(Math.ceil(F2.s / 8) * R.A / F2.B), ap = o * R.h, aq = B * R.A, ae = 64 * aq * (ap + 1);
R.D = new Int16Array(ae);
R.P = ab;
R.c = af;
}
F2.m = o;
F2.R = B;
}
var U = [], z = [], J = [], V = Z(Q, E);
E += 2;
if (V !== 65496) {
throw new W("SOI not found");
}
V = Z(Q, E);
E += 2;
markerLoop:
while (V !== 65497) {
var Y, u, m;
switch (V) {
case 65504:
case 65505:
case 65506:
case 65507:
case 65508:
case 65509:
case 65510:
case 65511:
case 65512:
case 65513:
case 65514:
case 65515:
case 65516:
case 65517:
case 65518:
case 65519:
case 65534:
var j = G();
if (V === 65504) {
if (j[0] === 74 && j[1] === 70 && j[2] === 73 && j[3] === 70 && j[4] === 0) {
a = { version: { d: j[5], T: j[6] }, K: j[7], j: j[8] << 8 | j[9], H: j[10] << 8 | j[11], S: j[12], I: j[13], C: j.subarray(14, 14 + 3 * j[12] * j[13]) };
}
}
if (V === 65518) {
if (j[0] === 65 && j[1] === 100 && j[2] === 111 && j[3] === 98 && j[4] === 101) {
C = { version: j[5] << 8 | j[6], k: j[7] << 8 | j[8], q: j[9] << 8 | j[10], a: j[11] };
}
}
break;
case 65499:
var v = Z(Q, E), b;
E += 2;
var $ = v + E - 2;
while (E < $) {
var r = Q[E++], P = new Uint16Array(64);
if (r >> 4 === 0) {
for (u = 0;u < 64; u++) {
b = p[u];
P[b] = Q[E++];
}
} else if (r >> 4 === 1) {
for (u = 0;u < 64; u++) {
b = p[u];
P[b] = Z(Q, E);
E += 2;
}
} else {
throw new W("DQT - invalid table spec");
}
U[r & 15] = P;
}
break;
case 65472:
case 65473:
case 65474:
if (F) {
throw new W("Only single frame JPEGs supported");
}
E += 2;
F = {};
F.G = V === 65473;
F.Z = V === 65474;
F.precision = Q[E++];
var D = Z(Q, E), a4, q = 0, H = 0;
E += 2;
F.s = f || D;
F.o = Z(Q, E);
E += 2;
F.W = [];
F._ = {};
var a8 = Q[E++];
for (Y = 0;Y < a8; Y++) {
a4 = Q[E];
var w = Q[E + 1] >> 4, y = Q[E + 1] & 15;
if (q < w) {
q = w;
}
if (H < y) {
H = y;
}
var X = Q[E + 2];
m = F.W.push({ h: w, A: y, L: X, $: null });
F._[a4] = m - 1;
E += 3;
}
F.X = q;
F.B = H;
n(F);
break;
case 65476:
var O = Z(Q, E);
E += 2;
for (Y = 2;Y < O; ) {
var _ = Q[E++], N = new Uint8Array(16), e = 0;
for (u = 0;u < 16; u++, E++) {
e += N[u] = Q[E];
}
var K = new Uint8Array(e);
for (u = 0;u < e; u++, E++) {
K[u] = Q[E];
}
Y += 17 + e;
(_ >> 4 === 0 ? J : z)[_ & 15] = a5(N, K);
}
break;
case 65501:
E += 2;
d = Z(Q, E);
E += 2;
break;
case 65498:
var x = ++T === 1 && !f, R;
E += 2;
var k = Q[E++], g = [];
for (Y = 0;Y < k; Y++) {
var c = Q[E++], L = F._[c];
R = F.W[L];
R.index = c;
var a6 = Q[E++];
R.J = J[a6 >> 4];
R.i = z[a6 & 15];
g.push(R);
}
var I = Q[E++], l = Q[E++], M = Q[E++];
try {
var S = a7(Q, E, F, g, d, I, l, M >> 4, M & 15, x);
E += S;
} catch (ex) {
if (ex instanceof DNLMarkerError) {
return this.parse(Q, { F: ex.s });
} else if (ex instanceof EOIMarkerError) {
break markerLoop;
}
throw ex;
}
break;
case 65500:
E += 4;
break;
case 65535:
if (Q[E] !== 255) {
E--;
}
break;
default:
var i = an(Q, E - 2, E - 3);
if (i && i.u) {
E = i.offset;
break;
}
if (E >= Q.length - 1) {
break markerLoop;
}
throw new W("JpegImage.parse - unknown marker: " + V.toString(16));
}
V = Z(Q, E);
E += 2;
}
this.width = F.o;
this.height = F.s;
this.g = a;
this.b = C;
this.W = [];
for (Y = 0;Y < F.W.length; Y++) {
R = F.W[Y];
var A = U[R.L];
if (A) {
R.$ = A;
}
this.W.push({ index: R.index, e: a0(F, R), l: R.h / F.X, t: R.A / F.B, P: R.P, c: R.c });
}
this.p = this.W.length;
return;
}, Y(Q, h, f) {
if (f == null)
f = false;
var G = this.width / Q, n = this.height / h, E, a, C, F, d, T, U, z, J, V, Y = 0, u, m = this.W.length, j = Q * h * m, v = new Uint8ClampedArray(j), $ = new Uint32Array(Q), b = 4294967288, r;
for (U = 0;U < m; U++) {
E = this.W[U];
a = E.l * G;
C = E.t * n;
Y = U;
u = E.e;
F = E.P + 1 << 3;
if (a !== r) {
for (d = 0;d < Q; d++) {
z = 0 | d * a;
$[d] = (z & b) << 3 | z & 7;
}
r = a;
}
for (T = 0;T < h; T++) {
z = 0 | T * C;
V = F * (z & b) | (z & 7) << 3;
for (d = 0;d < Q; d++) {
v[Y] = u[V + $[d]];
Y += m;
}
}
}
var P = this.V;
if (!f && m === 4 && !P) {
P = new Int32Array([-256, 255, -256, 255, -256, 255, -256, 255]);
}
if (P) {
for (U = 0;U < j; ) {
for (z = 0, J = 0;z < m; z++, U++, J += 2) {
v[U] = (v[U] * P[J] >> 8) + P[J + 1];
}
}
}
return v;
}, get f() {
if (this.b) {
return !!this.b.a;
}
if (this.p === 3) {
if (this.N === 0) {
return false;
} else if (this.W[0].index === 82 && this.W[1].index === 71 && this.W[2].index === 66) {
return false;
}
return true;
}
if (this.N === 1) {
return true;
}
return false;
}, z: function aj(Q) {
var h, f, G;
for (var n = 0, E = Q.length;n < E; n += 3) {
h = Q[n];
f = Q[n + 1];
G = Q[n + 2];
Q[n] = h - 179.456 + 1.402 * G;
Q[n + 1] = h + 135.459 - 0.344 * f - 0.714 * G;
Q[n + 2] = h - 226.816 + 1.772 * f;
}
return Q;
}, O: function aa(Q) {
var h, f, G, n, E = 0;
for (var a = 0, C = Q.length;a < C; a += 4) {
h = Q[a];
f = Q[a + 1];
G = Q[a + 2];
n = Q[a + 3];
Q[E++] = -122.67195406894 + f * (-0.0000660635669420364 * f + 0.000437130475926232 * G - 0.000054080610064599 * h + 0.00048449797120281 * n - 0.154362151871126) + G * (-0.000957964378445773 * G + 0.000817076911346625 * h - 0.00477271405408747 * n + 1.53380253221734) + h * (0.000961250184130688 * h - 0.00266257332283933 * n + 0.48357088451265) + n * (-0.000336197177618394 * n + 0.484791561490776);
Q[E++] = 107.268039397724 + f * (0.0000219927104525741 * f - 0.000640992018297945 * G + 0.000659397001245577 * h + 0.000426105652938837 * n - 0.176491792462875) + G * (-0.000778269941513683 * G + 0.00130872261408275 * h + 0.000770482631801132 * n - 0.151051492775562) + h * (0.00126935368114843 * h - 0.00265090189010898 * n + 0.25802910206845) + n * (-0.000318913117588328 * n - 0.213742400323665);
Q[E++] = -20.810012546947 + f * (-0.000570115196973677 * f - 0.0000263409051004589 * G + 0.0020741088115012 * h - 0.00288260236853442 * n + 0.814272968359295) + G * (-0.0000153496057440975 * G - 0.000132689043961446 * h + 0.000560833691242812 * n - 0.195152027534049) + h * (0.00174418132927582 * h - 0.00255243321439347 * n + 0.116935020465145) + n * (-0.000343531996510555 * n + 0.24165260232407);
}
return Q.subarray(0, E);
}, r: function a3(Q) {
var h, f, G;
for (var n = 0, E = Q.length;n < E; n += 4) {
h = Q[n];
f = Q[n + 1];
G = Q[n + 2];
Q[n] = 434.456 - h - 1.402 * G;
Q[n + 1] = 119.541 - h + 0.344 * f + 0.714 * G;
Q[n + 2] = 481.816 - h - 1.772 * f;
}
return Q;
}, U: function as(Q) {
var h, f, G, n, E = 0;
for (var a = 0, C = Q.length;a < C; a += 4) {
h = Q[a];
f = Q[a + 1];
G = Q[a + 2];
n = Q[a + 3];
Q[E++] = 255 + h * (-0.00006747147073602441 * h + 0.0008379262121013727 * f + 0.0002894718188643294 * G + 0.003264231057537806 * n - 1.1185611867203937) + f * (0.000026374107616089405 * f - 0.00008626949158638572 * G - 0.0002748769067499491 * n - 0.02155688794978967) + G * (-0.00003878099212869363 * G - 0.0003267808279485286 * n + 0.0686742238595345) - n * (0.0003361971776183937 * n + 0.7430659151342254);
Q[E++] = 255 + h * (0.00013596372813588848 * h + 0.000924537132573585 * f + 0.00010567359618683593 * G + 0.0004791864687436512 * n - 0.3109689587515875) + f * (-0.00023545346108370344 * f + 0.0002702845253534714 * G + 0.0020200308977307156 * n - 0.7488052167015494) + G * (0.00006834815998235662 * G + 0.00015168452363460973 * n - 0.09751927774728933) - n * (0.0003189131175883281 * n + 0.7364883807733168);
Q[E++] = 255 + h * (0.000013598650411385307 * h + 0.00012423956175490851 * f + 0.0004751985097583589 * G - 0.0000036729317476630422 * n - 0.05562186980264034) + f * (0.00016141380598724676 * f + 0.0009692239130725186 * G + 0.0007782692450036253 * n - 0.44015232367526463) + G * (0.0000005068882914068769 * G + 0.0017778369011375071 * n - 0.7591454649749609) - n * (0.0003435319965105553 * n + 0.7063770186160144);
}
return Q.subarray(0, E);
}, getData: function(Q) {
var { width: h, height: f, forceRGB: G, isSourcePDF: n } = Q;
if (this.p > 4) {
throw new W("Unsupported color mode");
}
var E = this.Y(h, f, n);
if (this.p === 1 && G) {
var a = E.length, C = new Uint8ClampedArray(a * 3), F = 0;
for (var d = 0;d < a; d++) {
var T = E[d];
C[F++] = T;
C[F++] = T;
C[F++] = T;
}
return C;
} else if (this.p === 3 && this.f) {
return this.z(E);
} else if (this.p === 4) {
if (this.f) {
if (G) {
return this.O(E);
}
return this.r(E);
} else if (G) {
return this.U(E);
}
}
return E;
} };
return ak2;
}();
function a9(p, t) {
return p[t] << 24 >> 24;
}
function Z(p, t) {
return p[t] << 8 | p[t + 1];
}
function am(p, t) {
return (p[t] << 24 | p[t + 1] << 16 | p[t + 2] << 8 | p[t + 3]) >>> 0;
}
UTIF2.JpegDecoder = ak;
})();
UTIF2.encodeImage = function(rgba, w, h, metadata) {
var idf = {
t256: [w],
t257: [h],
t258: [8, 8, 8, 8],
t259: [1],
t262: [2],
t273: [1000],
t277: [4],
t278: [h],
t279: [w * h * 4],
t282: [[72, 1]],
t283: [[72, 1]],
t284: [1],
t286: [[0, 1]],
t287: [[0, 1]],
t296: [1],
t305: ["Photopea (UTIF.js)"],
t338: [1]
};
if (metadata)
for (var i in metadata)
idf[i] = metadata[i];
var prfx = new Uint8Array(UTIF2.encode([idf]));
var img = new Uint8Array(rgba);
var data = new Uint8Array(1000 + w * h * 4);
for (var i = 0;i < prfx.length; i++)
data[i] = prfx[i];
for (var i = 0;i < img.length; i++)
data[1000 + i] = img[i];
return data.buffer;
};
UTIF2.encode = function(ifds) {
var LE = false;
var data = new Uint8Array(20000), offset = 4, bin = LE ? UTIF2._binLE : UTIF2._binBE;
data[0] = data[1] = LE ? 73 : 77;
bin.writeUshort(data, 2, 42);
var ifdo = 8;
bin.writeUint(data, offset, ifdo);
offset += 4;
for (var i = 0;i < ifds.length; i++) {
var noffs = UTIF2._writeIFD(bin, UTIF2._types.basic, data, ifdo, ifds[i]);
ifdo = noffs[1];
if (i < ifds.length - 1) {
if ((ifdo & 3) != 0)
ifdo += 4 - (ifdo & 3);
bin.writeUint(data, noffs[0], ifdo);
}
}
return data.slice(0, ifdo).buffer;
};
UTIF2.decode = function(buff, prm) {
if (prm == null)
prm = { parseMN: true, debug: false };
var data = new Uint8Array(buff), offset = 0;
var id = UTIF2._binBE.readASCII(data, offset, 2);
offset += 2;
var bin = id == "II" ? UTIF2._binLE : UTIF2._binBE;
var num = bin.readUshort(data, offset);
offset += 2;
var ifdo = bin.readUint(data, offset);
offset += 4;
var ifds = [];
while (true) {
var cnt = bin.readUshort(data, ifdo), typ = bin.readUshort(data, ifdo + 4);
if (cnt != 0) {
if (typ < 1 || 13 < typ) {
log("error in TIFF");
break;
}
}
UTIF2._readIFD(bin, data, ifdo, ifds, 0, prm);
ifdo = bin.readUint(data, ifdo + 2 + cnt * 12);
if (ifdo == 0)
break;
}
return ifds;
};
UTIF2.decodeImage = function(buff, img, ifds) {
if (img.data)
return;
var data = new Uint8Array(buff);
var id = UTIF2._binBE.readASCII(data, 0, 2);
if (img["t256"] == null)
return;
img.isLE = id == "II";
img.width = img["t256"][0];
img.height = img["t257"][0];
var cmpr = img["t259"] ? img["t259"][0] : 1;
var fo = img["t266"] ? img["t266"][0] : 1;
if (img["t284"] && img["t284"][0] == 2)
log("PlanarConfiguration 2 should not be used!");
if (cmpr == 7 && img["t258"] && img["t258"].length > 3)
img["t258"] = img["t258"].slice(0, 3);
var spp = img["t277"] ? img["t277"][0] : 1;
var bps = img["t258"] ? img["t258"][0] : 1;
var bipp = bps * spp;
if (cmpr == 1 && img["t279"] != null && img["t278"] && img["t262"][0] == 32803) {
bipp = Math.round(img["t279"][0] * 8 / (img.width * img["t278"][0]));
}
if (img["t50885"] && img["t50885"][0] == 4)
bipp = img["t258"][0] * 3;
var bipl = Math.ceil(img.width * bipp / 8) * 8;
var soff = img["t273"];
if (soff == null || img["t322"])
soff = img["t324"];
var bcnt = img["t279"];
if (cmpr == 1 && soff.length == 1)
bcnt = [img.height * (bipl >>> 3)];
if (bcnt == null || img["t322"])
bcnt = img["t325"];
var bytes = new Uint8Array(img.height * (bipl >>> 3)), bilen = 0;
if (img["t322"] != null) {
var tw = img["t322"][0], th = img["t323"][0];
var tx = Math.floor((img.width + tw - 1) / tw);
var ty = Math.floor((img.height + th - 1) / th);
var tbuff = new Uint8Array(Math.ceil(tw * th * bipp / 8) | 0);
console.log("====", tx, ty);
for (var y = 0;y < ty; y++)
for (var x = 0;x < tx; x++) {
var i = y * tx + x;
tbuff.fill(0);
UTIF2.decode._decompress(img, ifds, data, soff[i], bcnt[i], cmpr, tbuff, 0, fo, tw, th);
if (cmpr == 6)
bytes = tbuff;
else
UTIF2._copyTile(tbuff, Math.ceil(tw * bipp / 8) | 0, th, bytes, Math.ceil(img.width * bipp / 8) | 0, img.height, Math.ceil(x * tw * bipp / 8) | 0, y * th);
}
bilen = bytes.length * 8;
} else {
if (soff == null)
return;
var rps = img["t278"] ? img["t278"][0] : img.height;
rps = Math.min(rps, img.height);
for (var i = 0;i < soff.length; i++) {
UTIF2.decode._decompress(img, ifds, data, soff[i], bcnt[i], cmpr, bytes, Math.ceil(bilen / 8) | 0, fo, img.width, rps);
bilen += bipl * rps;
}
bilen = Math.min(bilen, bytes.length * 8);
}
img.data = new Uint8Array(bytes.buffer, 0, Math.ceil(bilen / 8) | 0);
};
UTIF2.decode._decompress = function(img, ifds, data, off, len, cmpr, tgt, toff, fo, w, h) {
if (img["t271"] && img["t271"][0] == "Panasonic" && img["t45"] && img["t45"][0] == 6)
cmpr = 34316;
if (false) {} else if (cmpr == 1)
for (var j = 0;j < len; j++)
tgt[toff + j] = data[off + j];
else if (cmpr == 2)
UTIF2.decode._decodeG2(data, off, len, tgt, toff, w, fo);
else if (cmpr == 3)
UTIF2.decode._decodeG3(data, off, len, tgt, toff, w, fo, img["t292"] ? (img["t292"][0] & 1) == 1 : false);
else if (cmpr == 4)
UTIF2.decode._decodeG4(data, off, len, tgt, toff, w, fo);
else if (cmpr == 5)
UTIF2.decode._decodeLZW(data, off, len, tgt, toff, 8);
else if (cmpr == 6)
UTIF2.decode._decodeOldJPEG(img, data, off, len, tgt, toff);
else if (cmpr == 7 || cmpr == 34892)
UTIF2.decode._decodeNewJPEG(img, data, off, len, tgt, toff);
else if (cmpr == 8 || cmpr == 32946) {
var src = new Uint8Array(data.buffer, off + 2, len - 6);
var bin = pako2["inflateRaw"](src);
if (toff + bin.length <= tgt.length)
tgt.set(bin, toff);
} else if (cmpr == 9)
UTIF2.decode._decodeVC5(data, off, len, tgt, toff, img["t33422"]);
else if (cmpr == 32767)
UTIF2.decode._decodeARW(img, data, off, len, tgt, toff);
else if (cmpr == 32773)
UTIF2.decode._decodePackBits(data, off, len, tgt, toff);
else if (cmpr == 32809)
UTIF2.decode._decodeThunder(data, off, len, tgt, toff);
else if (cmpr == 34316)
UTIF2.decode._decodePanasonic(img, data, off, len, tgt, toff);
else if (cmpr == 34713)
UTIF2.decode._decodeNikon(img, ifds, data, off, len, tgt, toff);
else if (cmpr == 34676)
UTIF2.decode._decodeLogLuv32(img, data, off, len, tgt, toff);
else
log("Unknown compression", cmpr);
var bps = img["t258"] ? Math.min(32, img["t258"][0]) : 1;
var noc = img["t277"] ? img["t277"][0] : 1, bpp = bps * noc >>> 3, bpl = Math.ceil(bps * noc * w / 8);
if (bps == 16 && !img.isLE && img["t33422"] == null)
for (var y = 0;y < h; y++) {
var roff = toff + y * bpl;
for (var x = 1;x < bpl; x += 2) {
var t = tgt[roff + x];
tgt[roff + x] = tgt[roff + x - 1];
tgt[roff + x - 1] = t;
}
}
if (img["t317"] && img["t317"][0] == 2) {
for (var y = 0;y < h; y++) {
var ntoff = toff + y * bpl;
if (bps == 16)
for (var j = bpp;j < bpl; j += 2) {
var nv = (tgt[ntoff + j + 1] << 8 | tgt[ntoff + j]) + (tgt[ntoff + j - bpp + 1] << 8 | tgt[ntoff + j - bpp]);
tgt[ntoff + j] = nv & 255;
tgt[ntoff + j + 1] = nv >>> 8 & 255;
}
else if (noc == 3)
for (var j = 3;j < bpl; j += 3) {
tgt[ntoff + j] = tgt[ntoff + j] + tgt[ntoff + j - 3] & 255;
tgt[ntoff + j + 1] = tgt[ntoff + j + 1] + tgt[ntoff + j - 2] & 255;
tgt[ntoff + j + 2] = tgt[ntoff + j + 2] + tgt[ntoff + j - 1] & 255;
}
else
for (var j = bpp;j < bpl; j++)
tgt[ntoff + j] = tgt[ntoff + j] + tgt[ntoff + j - bpp] & 255;
}
}
};
UTIF2.decode._decodePanasonic = function(img, data, off, len, tgt, toff) {
var img_buffer = data.buffer;
var rawWidth = img["t2"][0];
var rawHeight = img["t3"][0];
var bitsPerSample = img["t10"][0];
var RW2_Format = img["t45"][0];
var bidx = 0;
var imageIndex = 0;
var vpos = 0;
var byte = 0;
var arr_a, arr_b;
var bytes = RW2_Format == 6 ? new Uint32Array(18) : new Uint8Array(16);
var i, j, sh, pred = [0, 0], nonz = [0, 0], isOdd, idx = 0, pixel_base;
var row, col, crow;
var buffer = new Uint8Array(16384);
var result = new Uint16Array(tgt.buffer);
function getDataRaw(bits) {
if (vpos == 0) {
var arr_a2 = new Uint8Array(img_buffer, off + imageIndex + 8184, 16384 - 8184);
var arr_b2 = new Uint8Array(img_buffer, off + imageIndex, 8184);
buffer.set(arr_a2);
buffer.set(arr_b2, arr_a2.length);
imageIndex += 16384;
}
if (RW2_Format == 5) {
for (i = 0;i < 16; i++) {
bytes[i] = buffer[vpos++];
vpos &= 16383;
}
} else {
vpos = vpos - bits & 131071;
byte = vpos >> 3 ^ 16368;
return (buffer[byte] | buffer[byte + 1] << 8) >> (vpos & 7) & ~(-1 << bits);
}
}
function getBufferDataRW6(i2) {
return buffer[vpos + 15 - i2];
}
function readPageRW6() {
bytes[0] = getBufferDataRW6(0) << 6 | getBufferDataRW6(1) >> 2;
bytes[1] = ((getBufferDataRW6(1) & 3) << 12 | getBufferDataRW6(2) << 4 | getBufferDataRW6(3) >> 4) & 16383;
bytes[2] = getBufferDataRW6(3) >> 2 & 3;
bytes[3] = (getBufferDataRW6(3) & 3) << 8 | getBufferDataRW6(4);
bytes[4] = getBufferDataRW6(5) << 2 | getBufferDataRW6(6) >> 6;
bytes[5] = (getBufferDataRW6(6) & 63) << 4 | getBufferDataRW6(7) >> 4;
bytes[6] = getBufferDataRW6(7) >> 2 & 3;
bytes[7] = (getBufferDataRW6(7) & 3) << 8 | getBufferDataRW6(8);
bytes[8] = getBufferDataRW6(9) << 2 & 1020 | getBufferDataRW6(10) >> 6;
bytes[9] = (getBufferDataRW6(10) << 4 | getBufferDataRW6(11) >> 4) & 1023;
bytes[10] = getBufferDataRW6(11) >> 2 & 3;
bytes[11] = (getBufferDataRW6(11) & 3) << 8 | getBufferDataRW6(12);
bytes[12] = (getBufferDataRW6(13) << 2 & 1020 | getBufferDataRW6(14) >> 6) & 1023;
bytes[13] = (getBufferDataRW6(14) << 4 | getBufferDataRW6(15) >> 4) & 1023;
vpos += 16;
byte = 0;
}
function readPageRw6_bps12() {
bytes[0] = getBufferDataRW6(0) << 4 | getBufferDataRW6(1) >> 4;
bytes[1] = ((getBufferDataRW6(1) & 15) << 8 | getBufferDataRW6(2)) & 4095;
bytes[2] = getBufferDataRW6(3) >> 6 & 3;
bytes[3] = (getBufferDataRW6(3) & 63) << 2 | getBufferDataRW6(4) >> 6;
bytes[4] = (getBufferDataRW6(4) & 63) << 2 | getBufferDataRW6(5) >> 6;
bytes[5] = (getBufferDataRW6(5) & 63) << 2 | getBufferDataRW6(6) >> 6;
bytes[6] = getBufferDataRW6(6) >> 4 & 3;
bytes[7] = (getBufferDataRW6(6) & 15) << 4 | getBufferDataRW6(7) >> 4;
bytes[8] = (getBufferDataRW6(7) & 15) << 4 | getBufferDataRW6(8) >> 4;
bytes[9] = (getBufferDataRW6(8) & 15) << 4 | getBufferDataRW6(9) >> 4;
bytes[10] = getBufferDataRW6(9) >> 2 & 3;
bytes[11] = (getBufferDataRW6(9) & 3) << 6 | getBufferDataRW6(10) >> 2;
bytes[12] = (getBufferDataRW6(10) & 3) << 6 | getBufferDataRW6(11) >> 2;
bytes[13] = (getBufferDataRW6(11) & 3) << 6 | getBufferDataRW6(12) >> 2;
bytes[14] = getBufferDataRW6(12) & 3;
bytes[15] = getBufferDataRW6(13);
bytes[16] = getBufferDataRW6(14);
bytes[17] = getBufferDataRW6(15);
vpos += 16;
byte = 0;
}
function resetPredNonzeros() {
pred[0] = 0;
pred[1] = 0;
nonz[0] = 0;
nonz[1] = 0;
}
if (RW2_Format == 7) {
throw RW2_Format;
} else if (RW2_Format == 6) {
var is12bit = bitsPerSample == 12, readPageRw6Fn = is12bit ? readPageRw6_bps12 : readPageRW6, pixelsPerBlock = is12bit ? 14 : 11, pixelbase0 = is12bit ? 128 : 512, pixelbase_compare = is12bit ? 2048 : 8192, spix_compare = is12bit ? 16383 : 65535, pixel_mask = is12bit ? 4095 : 16383, blocksperrow = rawWidth / pixelsPerBlock, rowbytes = blocksperrow * 16, bufferSize = is12bit ? 18 : 14;
for (row = 0;row < rawHeight - 15; row += 16) {
var rowstoread = Math.min(16, rawHeight - row);
var readlen = rowbytes * rowstoread;
buffer = new Uint8Array(img_buffer, off + bidx, readlen);
vpos = 0;
bidx += readlen;
for (crow = 0, col = 0;crow < rowstoread; crow++, col = 0) {
idx = (row + crow) * rawWidth;
for (var rblock = 0;rblock < blocksperrow; rblock++) {
readPageRw6Fn();
resetPredNonzeros();
sh = 0;
pixel_base = 0;
for (i = 0;i < pixelsPerBlock; i++) {
isOdd = i & 1;
if (i % 3 == 2) {
var base = byte < bufferSize ? bytes[byte++] : 0;
if (base == 3)
base = 4;
pixel_base = pixelbase0 << base;
sh = 1 << base;
}
var epixel = byte < bufferSize ? bytes[byte++] : 0;
if (pred[isOdd]) {
epixel *= sh;
if (pixel_base < pixelbase_compare && nonz[isOdd] > pixel_base)
epixel += nonz[isOdd] - pixel_base;
nonz[isOdd] = epixel;
} else {
pred[isOdd] = epixel;
if (epixel)
nonz[isOdd] = epixel;
else
epixel = nonz[isOdd];
}
result[idx + col++] = epixel - 15 <= spix_compare ? epixel - 15 & spix_compare : epixel + 2147483633 >> 31 & pixel_mask;
}
}
}
}
} else if (RW2_Format == 5) {
var blockSize = bitsPerSample == 12 ? 10 : 9;
for (row = 0;row < rawHeight; row++) {
for (col = 0;col < rawWidth; col += blockSize) {
getDataRaw(0);
if (bitsPerSample == 12) {
result[idx++] = ((bytes[1] & 15) << 8) + bytes[0];
result[idx++] = 16 * bytes[2] + (bytes[1] >> 4);
result[idx++] = ((bytes[4] & 15) << 8) + bytes[3];
result[idx++] = 16 * bytes[5] + (bytes[4] >> 4);
result[idx++] = ((bytes[7] & 15) << 8) + bytes[6];
result[idx++] = 16 * bytes[8] + (bytes[7] >> 4);
result[idx++] = ((bytes[10] & 15) << 8) + bytes[9];
result[idx++] = 16 * bytes[11] + (bytes[10] >> 4);
result[idx++] = ((bytes[13] & 15) << 8) + bytes[12];
result[idx++] = 16 * bytes[14] + (bytes[13] >> 4);
} else if (bitsPerSample == 14) {
result[idx++] = bytes[0] + ((bytes[1] & 63) << 8);
result[idx++] = (bytes[1] >> 6) + 4 * bytes[2] + ((bytes[3] & 15) << 10);
result[idx++] = (bytes[3] >> 4) + 16 * bytes[4] + ((bytes[5] & 3) << 12);
result[idx++] = ((bytes[5] & 252) >> 2) + (bytes[6] << 6);
result[idx++] = bytes[7] + ((bytes[8] & 63) << 8);
result[idx++] = (bytes[8] >> 6) + 4 * bytes[9] + ((bytes[10] & 15) << 10);
result[idx++] = (bytes[10] >> 4) + 16 * bytes[11] + ((bytes[12] & 3) << 12);
result[idx++] = ((bytes[12] & 252) >> 2) + (bytes[13] << 6);
result[idx++] = bytes[14] + ((bytes[15] & 63) << 8);
}
}
}
} else if (RW2_Format == 4) {
for (row = 0;row < rawHeight; row++) {
for (col = 0;col < rawWidth; col++) {
i = col % 14;
isOdd = i & 1;
if (i == 0)
resetPredNonzeros();
if (i % 3 == 2)
sh = 4 >> 3 - getDataRaw(2);
if (nonz[isOdd]) {
j = getDataRaw(8);
if (j != 0) {
pred[isOdd] -= 128 << sh;
if (pred[isOdd] < 0 || sh == 4)
pred[isOdd] &= ~(-1 << sh);
pred[isOdd] += j << sh;
}
} else {
nonz[isOdd] = getDataRaw(8);
if (nonz[isOdd] || i > 11)
pred[isOdd] = nonz[isOdd] << 4 | getDataRaw(4);
}
result[idx++] = pred[col & 1];
}
}
} else
throw RW2_Format;
};
UTIF2.decode._decodeVC5 = function() {
var x = [1, 0, 1, 0, 2, 2, 1, 1, 3, 7, 1, 2, 5, 25, 1, 3, 6, 48, 1, 4, 6, 54, 1, 5, 7, 111, 1, 8, 7, 99, 1, 6, 7, 105, 12, 0, 7, 107, 1, 7, 8, 209, 20, 0, 8, 212, 1, 9, 8, 220, 1, 10, 9, 393, 1, 11, 9, 394, 32, 0, 9, 416, 1, 12, 9, 427, 1, 13, 10, 887, 1, 18, 10, 784, 1, 14, 10, 790, 1, 15, 10, 835, 60, 0, 10, 852, 1, 16, 10, 885, 1, 17, 11, 1571, 1, 19, 11, 1668, 1, 20, 11, 1669, 100, 0, 11, 1707, 1, 21, 11, 1772, 1, 22, 12, 3547, 1, 29, 12, 3164, 1, 24, 12, 3166, 1, 25, 12, 3140, 1, 23, 12, 3413, 1, 26, 12, 3537, 1, 27, 12, 3539, 1, 28, 13, 7093, 1, 35, 13, 6283, 1, 30, 13, 6331, 1, 31, 13, 6335, 180, 0, 13, 6824, 1, 32, 13, 7072, 1, 33, 13, 7077, 320, 0, 13, 7076, 1, 34, 14, 12565, 1, 36, 14, 12661, 1, 37, 14, 12669, 1, 38, 14, 13651, 1, 39, 14, 14184, 1, 40, 15, 28295, 1, 46, 15, 28371, 1, 47, 15, 25320, 1, 42, 15, 25336, 1, 43, 15, 25128, 1, 41, 15, 27300, 1, 44, 15, 28293, 1, 45, 16, 50259, 1, 48, 16, 50643, 1, 49, 16, 50675, 1, 50, 16, 56740, 1, 53, 16, 56584, 1, 51, 16, 56588, 1, 52, 17, 113483, 1, 61, 17, 113482, 1, 60, 17, 101285, 1, 55, 17, 101349, 1, 56, 17, 109205, 1, 57, 17, 109207, 1, 58, 17, 100516, 1, 54, 17, 113171, 1, 59, 18, 202568, 1, 62, 18, 202696, 1, 63, 18, 218408, 1, 64, 18, 218412, 1, 65, 18, 226340, 1, 66, 18, 226356, 1, 67, 18, 226358, 1, 68, 19, 402068, 1, 69, 19, 405138, 1, 70, 19, 405394, 1, 71, 19, 436818, 1, 72, 19, 436826, 1, 73, 19, 452714, 1, 75, 19, 452718, 1, 76, 19, 452682, 1, 74, 20, 804138, 1, 77, 20, 810279, 1, 78, 20, 810790, 1, 79, 20, 873638, 1, 80, 20, 873654, 1, 81, 20, 905366, 1, 82, 20, 905430, 1, 83, 20, 905438, 1, 84, 21, 1608278, 1, 85, 21, 1620557, 1, 86, 21, 1621582, 1, 87, 21, 1621583, 1, 88, 21, 1747310, 1, 89, 21, 1810734, 1, 90, 21, 1810735, 1, 91, 21, 1810863, 1, 92, 21, 1810879, 1, 93, 22, 3621725, 1, 99, 22, 3621757, 1, 100, 22, 3241112, 1, 94, 22, 3494556, 1, 95, 22, 3494557, 1, 96, 22, 3494622, 1, 97, 22, 3494623, 1, 98, 23, 6482227, 1, 102, 23, 6433117, 1, 101, 23, 6989117, 1, 103, 23, 6989119, 1, 105, 23, 6989118, 1, 104, 23, 7243449, 1, 106, 23, 7243512, 1, 107, 24, 13978233, 1, 111, 24, 12964453, 1, 109, 24, 12866232, 1, 108, 24, 14486897, 1, 113, 24, 13978232, 1, 110, 24, 14486896, 1, 112, 24, 14487026, 1, 114, 24, 14487027, 1, 115, 25, 25732598, 1, 225, 25, 25732597, 1, 189, 25, 25732596, 1, 188, 25, 25732595, 1, 203, 25, 25732594, 1, 202, 25, 25732593, 1, 197, 25, 25732592, 1, 207, 25, 25732591, 1, 169, 25, 25732590, 1, 223, 25, 25732589, 1, 159, 25, 25732522, 1, 235, 25, 25732579, 1, 152, 25, 25732575, 1, 192, 25, 25732489, 1, 179, 25, 25732573, 1, 201, 25, 25732472, 1, 172, 25, 25732576, 1, 149, 25, 25732488, 1, 178, 25, 25732566, 1, 120, 25, 25732571, 1, 219, 25, 25732577, 1, 150, 25, 25732487, 1, 127, 25, 25732506, 1, 211, 25, 25732548, 1, 125, 25, 25732588, 1, 158, 25, 25732486, 1, 247, 25, 25732467, 1, 238, 25, 25732508, 1, 163, 25, 25732552, 1, 228, 25, 25732603, 1, 183, 25, 25732513, 1, 217, 25, 25732587, 1, 168, 25, 25732520, 1, 122, 25, 25732484, 1, 128, 25, 25732562, 1, 249, 25, 25732505, 1, 187, 25, 25732504, 1, 186, 25, 25732483, 1, 136, 25, 25928905, 1, 181, 25, 25732560, 1, 255, 25, 25732500, 1, 230, 25, 25732482, 1, 135, 25, 25732555, 1, 233, 25, 25732568, 1, 222, 25, 25732583, 1, 145, 25, 25732481, 1, 134, 25, 25732586, 1, 167, 25, 25732521, 1, 248, 25, 25732518, 1, 209, 25, 25732480, 1, 243, 25, 25732512, 1, 216, 25, 25732509, 1, 164, 25, 25732547, 1, 140, 25, 25732479, 1, 157, 25, 25732544, 1, 239, 25, 25732574, 1, 191, 25, 25732564, 1, 251, 25, 25732478, 1, 156, 25, 25732546, 1, 139, 25, 25732498, 1, 242, 25, 25732557, 1, 133, 25, 25732477, 1, 162, 25, 25732515, 1, 213, 25, 25732584, 1, 165, 25, 25732514, 1, 212, 25, 25732476, 1, 227, 25, 25732494, 1, 198, 25, 25732531, 1, 236, 25, 25732530, 1, 234, 25, 25732529, 1, 117, 25, 25732528, 1, 215, 25, 25732527, 1, 124, 25, 25732526, 1, 123, 25, 25732525, 1, 254, 25, 25732524, 1, 253, 25, 25732523, 1, 148, 25, 25732570, 1, 218, 25, 25732580, 1, 146, 25, 25732581, 1, 147, 25, 25732569, 1, 224, 25, 25732533, 1, 143, 25, 25732540, 1, 184, 25, 25732541, 1, 185, 25, 25732585, 1, 166, 25, 25732556, 1, 132, 25, 25732485, 1, 129, 25, 25732563, 1, 250, 25, 25732578, 1, 151, 25, 25732501, 1, 119, 25, 25732502, 1, 193, 25, 25732536, 1, 176, 25, 25732496, 1, 245, 25, 25732553, 1, 229, 25, 25732516, 1, 206, 25, 25732582, 1, 144, 25, 25732517, 1, 208, 25, 25732558, 1, 137, 25, 25732543, 1, 241, 25, 25732466, 1, 237, 25, 25732507, 1, 190, 25, 25732542, 1, 240, 25, 25732551, 1, 131, 25, 25732554, 1, 232, 25, 25732565, 1, 252, 25, 25732475, 1, 171, 25, 25732493, 1, 205, 25, 25732492, 1, 204, 25, 25732491, 1, 118, 25, 25732490, 1, 214, 25, 25928904, 1, 180, 25, 25732549, 1, 126, 25, 25732602, 1, 182, 25, 25732539, 1, 175, 25, 25732545, 1, 141, 25, 25732559, 1, 138, 25, 25732537, 1, 177, 25, 25732534, 1, 153, 25, 25732503, 1, 194, 25, 25732606, 1, 160, 25, 25732567, 1, 121, 25, 25732538, 1, 174, 25, 25732497, 1, 246, 25, 25732550, 1, 130, 25, 25732572, 1, 200, 25, 25732474, 1, 170, 25, 25732511, 1, 221, 25, 25732601, 1, 196, 25, 25732532, 1, 142, 25, 25732519, 1, 210, 25, 25732495, 1, 199, 25, 25732605, 1, 155, 25, 25732535, 1, 154, 25, 25732499, 1, 244, 25, 25732510, 1, 220, 25, 25732600, 1, 195, 25, 25732607, 1, 161, 25, 25732604, 1, 231, 25, 25732473, 1, 173, 25, 25732599, 1, 226, 26, 51465122, 1, 116, 26, 51465123, 0, 1], o, C, k, P = [3, 3, 3, 3, 2, 2, 2, 1, 1, 1], V = 24576, ar = 16384, H = 8192, az = ar | H;
function d(t) {
var E = t[1], h = t[0][E >>> 3] >>> 7 - (E & 7) & 1;
t[1]++;
return h;
}
function ag(t, E) {
if (o == null) {
o = {};
for (var h = 0;h < x.length; h += 4)
o[x[h + 1]] = x.slice(h, h + 4);
}
var L = d(t), g = o[L];
while (g == null) {
L = L << 1 | d(t);
g = o[L];
}
var n = g[3];
if (n != 0)
n = d(t) == 0 ? n : -n;
E[0] = g[2];
E[1] = n;
}
function m(t, E) {
for (var h = 0;h < E; h++) {
if ((t & 1) == 1)
t++;
t = t >>> 1;
}
return t;
}
function A(t, E) {
return t >> E;
}
function O(t, E, h, L, g, n) {
E[h] = A(A(11 * t[g] - 4 * t[g + n] + t[g + n + n] + 4, 3) + t[L], 1);
E[h + n] = A(A(5 * t[g] + 4 * t[g + n] - t[g + n + n] + 4, 3) - t[L], 1);
}
function J(t, E, h, L, g, n) {
var W = t[g - n] - t[g + n], j = t[g], $ = t[L];
E[h] = A(A(W + 4, 3) + j + $, 1);
E[h + n] = A(A(-W + 4, 3) + j - $, 1);
}
function y(t, E, h, L, g, n) {
E[h] = A(A(5 * t[g] + 4 * t[g - n] - t[g - n - n] + 4, 3) + t[L], 1);
E[h + n] = A(A(11 * t[g] - 4 * t[g - n] + t[g - n - n] + 4, 3) - t[L], 1);
}
function q(t) {
t = t < 0 ? 0 : t > 4095 ? 4095 : t;
t = k[t] >>> 2;
return t;
}
function av(t, E, h, L, g, n) {
L = new Uint16Array(L.buffer);
var W = Date.now(), j = UTIF2._binBE, $ = E + h, r, u, X, I, ax, a3, R, ai, aa, ap, ah, ae, aD, al, i, aE, T, B;
E += 4;
var a5 = n[0] == 1;
while (E < $) {
var S = j.readShort(t, E), s = j.readUshort(t, E + 2);
E += 4;
if (S == 12)
r = s;
else if (S == 20)
u = s;
else if (S == 21)
X = s;
else if (S == 48)
I = s;
else if (S == 53)
ax = s;
else if (S == 35)
a3 = s;
else if (S == 62)
R = s;
else if (S == 101)
ai = s;
else if (S == 109)
aa = s;
else if (S == 84)
ap = s;
else if (S == 106)
ah = s;
else if (S == 107)
ae = s;
else if (S == 108)
aD = s;
else if (S == 102)
al = s;
else if (S == 104)
i = s;
else if (S == 105)
aE = s;
else {
var F = S < 0 ? -S : S, D = F & 65280, _ = 0;
if (F & az) {
if (F & H) {
_ = s & 65535;
_ += (F & 255) << 16;
} else {
_ = s & 65535;
}
}
if ((F & V) == V) {
if (T == null) {
T = [];
for (var M = 0;M < 4; M++)
T[M] = new Int16Array((u >>> 1) * (X >>> 1));
B = new Int16Array((u >>> 1) * (X >>> 1));
C = new Int16Array(1024);
for (var M = 0;M < 1024; M++) {
var aG = M - 512, p = Math.abs(aG), r = Math.floor(768 * p * p * p / (255 * 255 * 255)) + p;
C[M] = Math.sign(aG) * r;
}
k = new Uint16Array(4096);
var aA = (1 << 16) - 1;
for (var M = 0;M < 4096; M++) {
var at = M, a1 = aA * (Math.pow(113, at / 4095) - 1) / 112;
k[M] = Math.min(a1, aA);
}
}
var w = T[R], v = m(u, 1 + P[I]), N = m(X, 1 + P[I]);
if (I == 0) {
for (var b = 0;b < N; b++)
for (var G = 0;G < v; G++) {
var c = E + (b * v + G) * 2;
w[b * (u >>> 1) + G] = t[c] << 8 | t[c + 1];
}
} else {
var a7 = [t, E * 8], a4 = [], ay = 0, aw = v * N, f = [0, 0], Q = 0, s = 0;
while (ay < aw) {
ag(a7, f);
Q = f[0];
s = f[1];
while (Q > 0) {
a4[ay++] = s;
Q--;
}
}
var l = (I - 1) % 3, aF = l != 1 ? v : 0, a2 = l != 0 ? N : 0;
for (var b = 0;b < N; b++) {
var af = (b + a2) * (u >>> 1) + aF, au = b * v;
for (var G = 0;G < v; G++)
w[af + G] = C[a4[au + G] + 512] * ax;
}
if (l == 2) {
var i = u >>> 1, an = v * 2, a9 = N * 2;
for (var b = 0;b < N; b++) {
for (var G = 0;G < an; G++) {
var M = b * 2 * i + G, a = b * i + G, e = N * i + a;
if (b == 0)
O(w, B, M, e, a, i);
else if (b == N - 1)
y(w, B, M, e, a, i);
else
J(w, B, M, e, a, i);
}
}
var Z = w;
w = B;
B = Z;
for (var b = 0;b < a9; b++) {
for (var G = 0;G < v; G++) {
var M = b * i + 2 * G, a = b * i + G, e = v + a;
if (G == 0)
O(w, B, M, e, a, 1);
else if (G == v - 1)
y(w, B, M, e, a, 1);
else
J(w, B, M, e, a, 1);
}
}
var Z = w;
w = B;
B = Z;
var aC = [], aB = 2 - ~~((I - 1) / 3);
for (var K = 0;K < 3; K++)
aC[K] = aa >> 14 - K * 2 & 3;
var a6 = aC[aB];
if (a6 != 0)
for (var b = 0;b < a9; b++)
for (var G = 0;G < an; G++) {
var M = b * i + G;
w[M] = w[M] << a6;
}
}
}
if (I == 9 && R == 3) {
var a8 = T[0], ab = T[1], aq = T[2], as = T[3];
for (var b = 0;b < X; b += 2)
for (var G = 0;G < u; G += 2) {
var U = b * u + G, c = (b >>> 1) * (u >>> 1) + (G >>> 1), z = a8[c], ao = ab[c] - 2048, ak = aq[c] - 2048, ad = as[c] - 2048, aj = (ao << 1) + z, a0 = (ak << 1) + z, aH = z + ad, am = z - ad;
if (a5) {
L[U] = q(aH);
L[U + 1] = q(a0);
L[U + u] = q(aj);
L[U + u + 1] = q(am);
} else {
L[U] = q(aj);
L[U + 1] = q(aH);
L[U + u] = q(am);
L[U + u + 1] = q(a0);
}
}
}
E += _ * 4;
} else if (F == 16388) {
E += _ * 4;
} else if (D == 8192 || D == 8448 || D == 9216) {} else
throw F.toString(16);
}
}
console.log(Date.now() - W);
}
return av;
}();
UTIF2.decode._decodeLogLuv32 = function(img, data, off, len, tgt, toff) {
var w = img.width, qw = w * 4;
var io = 0, out = new Uint8Array(qw);
while (io < len) {
var oo = 0;
while (oo < qw) {
var c = data[off + io];
io++;
if (c < 128) {
for (var j = 0;j < c; j++)
out[oo + j] = data[off + io + j];
oo += c;
io += c;
} else {
c = c - 126;
for (var j = 0;j < c; j++)
out[oo + j] = data[off + io];
oo += c;
io++;
}
}
for (var x = 0;x < w; x++) {
tgt[toff + 0] = out[x];
tgt[toff + 1] = out[x + w];
tgt[toff + 2] = out[x + w * 2];
tgt[toff + 4] = out[x + w * 3];
toff += 6;
}
}
};
UTIF2.decode._ljpeg_diff = function(data, prm, huff) {
var getbithuff = UTIF2.decode._getbithuff;
var len, diff;
len = getbithuff(data, prm, huff[0], huff);
diff = getbithuff(data, prm, len, 0);
if ((diff & 1 << len - 1) == 0)
diff -= (1 << len) - 1;
return diff;
};
UTIF2.decode._decodeARW = function(img, inp, off, src_length, tgt, toff) {
var raw_width = img["t256"][0], height = img["t257"][0], tiff_bps = img["t258"][0];
var bin = img.isLE ? UTIF2._binLE : UTIF2._binBE;
var arw2 = raw_width * height == src_length || raw_width * height * 1.5 == src_length;
if (!arw2) {
height += 8;
var prm = [off, 0, 0, 0];
var huff = new Uint16Array(32770);
var tab = [
3857,
3856,
3599,
3342,
3085,
2828,
2571,
2314,
2057,
1800,
1543,
1286,
1029,
772,
771,
768,
514,
513
];
var i, c, n, col, row, sum = 0;
var ljpeg_diff = UTIF2.decode._ljpeg_diff;
huff[0] = 15;
for (n = i = 0;i < 18; i++) {
var lim = 32768 >>> (tab[i] >>> 8);
for (var c = 0;c < lim; c++)
huff[++n] = tab[i];
}
for (col = raw_width;col--; )
for (row = 0;row < height + 1; row += 2) {
if (row == height)
row = 1;
sum += ljpeg_diff(inp, prm, huff);
if (row < height) {
var clr = sum & 4095;
UTIF2.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps);
}
}
return;
}
if (raw_width * height * 1.5 == src_length) {
for (var i = 0;i < src_length; i += 3) {
var b0 = inp[off + i + 0], b1 = inp[off + i + 1], b2 = inp[off + i + 2];
tgt[toff + i] = b1 << 4 | b0 >>> 4;
tgt[toff + i + 1] = b0 << 4 | b2 >>> 4;
tgt[toff + i + 2] = b2 << 4 | b1 >>> 4;
}
return;
}
var pix = new Uint16Array(16);
var row, col, val, max, min, imax, imin, sh, bit, i, dp;
var data = new Uint8Array(raw_width + 1);
for (row = 0;row < height; row++) {
for (var j = 0;j < raw_width; j++)
data[j] = inp[off++];
for (dp = 0, col = 0;col < raw_width - 30; dp += 16) {
max = 2047 & (val = bin.readUint(data, dp));
min = 2047 & val >>> 11;
imax = 15 & val >>> 22;
imin = 15 & val >>> 26;
for (sh = 0;sh < 4 && 128 << sh <= max - min; sh++)
;
for (bit = 30, i = 0;i < 16; i++)
if (i == imax)
pix[i] = max;
else if (i == imin)
pix[i] = min;
else {
pix[i] = ((bin.readUshort(data, dp + (bit >> 3)) >>> (bit & 7) & 127) << sh) + min;
if (pix[i] > 2047)
pix[i] = 2047;
bit += 7;
}
for (i = 0;i < 16; i++, col += 2) {
var clr = pix[i] << 1;
UTIF2.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps);
}
col -= col & 1 ? 1 : 31;
}
}
};
UTIF2.decode._decodeNikon = function(img, imgs, data, off, src_length, tgt, toff) {
var nikon_tree = [
[
0,
0,
1,
5,
1,
1,
1,
1,
1,
1,
2,
0,
0,
0,
0,
0,
0,
5,
4,
3,
6,
2,
7,
1,
0,
8,
9,
11,
10,
12
],
[
0,
0,
1,
5,
1,
1,
1,
1,
1,
1,
2,
0,
0,
0,
0,
0,
0,
57,
90,
56,
39,
22,
5,
4,
3,
2,
1,
0,
11,
12,
12
],
[
0,
0,
1,
4,
2,
3,
1,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
5,
4,
6,
3,
7,
2,
8,
1,
9,
0,
10,
11,
12
],
[
0,
0,
1,
4,
3,
1,
1,
1,
1,
1,
2,
0,
0,
0,
0,
0,
0,
5,
6,
4,
7,
8,
3,
9,
2,
1,
0,
10,
11,
12,
13,
14
],
[
0,
0,
1,
5,
1,
1,
1,
1,
1,
1,
1,
2,
0,
0,
0,
0,
0,
8,
92,
75,
58,
41,
7,
6,
5,
4,
3,
2,
1,
0,
13,
14
],
[
0,
0,
1,
4,
2,
2,
3,
1,
2,
0,
0,
0,
0,
0,
0,
0,
0,
7,
6,
8,
5,
9,
4,
10,
3,
11,
12,
2,
0,
1,
13,
14
]
];
var raw_width = img["t256"][0], height = img["t257"][0], tiff_bps = img["t258"][0];
var tree = 0, split = 0;
var make_decoder = UTIF2.decode._make_decoder;
var getbithuff = UTIF2.decode._getbithuff;
var mn = imgs[0].exifIFD.makerNote, md = mn["t150"] ? mn["t150"] : mn["t140"], mdo = 0;
var ver0 = md[mdo++], ver1 = md[mdo++];
if (ver0 == 73 || ver1 == 88)
mdo += 2110;
if (ver0 == 70)
tree = 2;
if (tiff_bps == 14)
tree += 3;
var vpred = [[0, 0], [0, 0]], bin = img.isLE ? UTIF2._binLE : UTIF2._binBE;
for (var i = 0;i < 2; i++)
for (var j = 0;j < 2; j++) {
vpred[i][j] = bin.readShort(md, mdo);
mdo += 2;
}
var max = 1 << tiff_bps & 32767, step = 0;
var csize = bin.readShort(md, mdo);
mdo += 2;
if (csize > 1)
step = Math.floor(max / (csize - 1));
if (ver0 == 68 && ver1 == 32 && step > 0)
split = bin.readShort(md, 562);
var i;
var row, col;
var len, shl, diff;
var min_v = 0;
var hpred = [0, 0];
var huff = make_decoder(nikon_tree[tree]);
var prm = [off, 0, 0, 0];
for (min_v = row = 0;row < height; row++) {
if (split && row == split) {
huff = make_decoder(nikon_tree[tree + 1]);
}
for (col = 0;col < raw_width; col++) {
i = getbithuff(data, prm, huff[0], huff);
len = i & 15;
shl = i >>> 4;
diff = (getbithuff(data, prm, len - shl, 0) << 1) + 1 << shl >>> 1;
if ((diff & 1 << len - 1) == 0)
diff -= (1 << len) - (shl == 0 ? 1 : 0);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
var clr = Math.min(Math.max(hpred[col & 1], 0), (1 << tiff_bps) - 1);
var bti = (row * raw_width + col) * tiff_bps;
UTIF2.decode._putsF(tgt, bti, clr << 16 - tiff_bps);
}
}
};
UTIF2.decode._putsF = function(dt, pos, val) {
val = val << 8 - (pos & 7);
var o = pos >>> 3;
dt[o] |= val >>> 16;
dt[o + 1] |= val >>> 8;
dt[o + 2] |= val;
};
UTIF2.decode._getbithuff = function(data, prm, nbits, huff) {
var zero_after_ff = 0;
var get_byte = UTIF2.decode._get_byte;
var c;
var off = prm[0], bitbuf = prm[1], vbits = prm[2], reset = prm[3];
if (nbits == 0 || vbits < 0)
return 0;
while (!reset && vbits < nbits && (c = data[off++]) != -1 && !(reset = zero_after_ff && c == 255 && data[off++])) {
bitbuf = (bitbuf << 8) + c;
vbits += 8;
}
c = bitbuf << 32 - vbits >>> 32 - nbits;
if (huff) {
vbits -= huff[c + 1] >>> 8;
c = huff[c + 1] & 255;
} else
vbits -= nbits;
if (vbits < 0)
throw "e";
prm[0] = off;
prm[1] = bitbuf;
prm[2] = vbits;
prm[3] = reset;
return c;
};
UTIF2.decode._make_decoder = function(source) {
var max, len, h, i, j;
var huff = [];
for (max = 16;max != 0 && !source[max]; max--)
;
var si = 17;
huff[0] = max;
for (h = len = 1;len <= max; len++)
for (i = 0;i < source[len]; i++, ++si)
for (j = 0;j < 1 << max - len; j++)
if (h <= 1 << max)
huff[h++] = len << 8 | source[si];
return huff;
};
UTIF2.decode._decodeNewJPEG = function(img, data, off, len, tgt, toff) {
len = Math.min(len, data.length - off);
var tables = img["t347"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len);
if (tables) {
var SOI = 216, EOI2 = 217, boff = 0;
for (var i = 0;i < tlen - 1; i++) {
if (tables[i] == 255 && tables[i + 1] == EOI2)
break;
buff[boff++] = tables[i];
}
var byte1 = data[off], byte2 = data[off + 1];
if (byte1 != 255 || byte2 != SOI) {
buff[boff++] = byte1;
buff[boff++] = byte2;
}
for (var i = 2;i < len; i++)
buff[boff++] = data[off + i];
} else
for (var i = 0;i < len; i++)
buff[i] = data[off + i];
if (img["t262"][0] == 32803 || img["t259"][0] == 7 && img["t262"][0] == 34892) {
var bps = img["t258"][0];
var out = UTIF2.LosslessJpegDecode(buff), olen = out.length;
if (false) {} else if (bps == 16) {
if (img.isLE)
for (var i = 0;i < olen; i++) {
tgt[toff + (i << 1)] = out[i] & 255;
tgt[toff + (i << 1) + 1] = out[i] >>> 8;
}
else
for (var i = 0;i < olen; i++) {
tgt[toff + (i << 1)] = out[i] >>> 8;
tgt[toff + (i << 1) + 1] = out[i] & 255;
}
} else if (bps == 14 || bps == 12 || bps == 10) {
var rst = 16 - bps;
for (var i = 0;i < olen; i++)
UTIF2.decode._putsF(tgt, i * bps, out[i] << rst);
} else if (bps == 8) {
for (var i = 0;i < olen; i++)
tgt[toff + i] = out[i];
} else
throw new Error("unsupported bit depth " + bps);
} else {
var parser = new UTIF2.JpegDecoder;
parser.parse(buff);
var decoded = parser.getData({ width: parser.width, height: parser.height, forceRGB: true, isSourcePDF: false });
for (var i = 0;i < decoded.length; i++)
tgt[toff + i] = decoded[i];
}
if (img["t262"][0] == 6)
img["t262"][0] = 2;
};
UTIF2.decode._decodeOldJPEGInit = function(img, data, off, len) {
var SOI = 216, EOI2 = 217, DQT = 219, DHT = 196, DRI = 221, SOF0 = 192, SOS2 = 218;
var joff = 0, soff = 0, tables, sosMarker2, isTiled = false, i, j, k;
var jpgIchgFmt = img["t513"], jifoff = jpgIchgFmt ? jpgIchgFmt[0] : 0;
var jpgIchgFmtLen = img["t514"], jiflen = jpgIchgFmtLen ? jpgIchgFmtLen[0] : 0;
var soffTag = img["t324"] || img["t273"] || jpgIchgFmt;
var ycbcrss = img["t530"], ssx = 0, ssy = 0;
var spp = img["t277"] ? img["t277"][0] : 1;
var jpgresint = img["t515"];
if (soffTag) {
soff = soffTag[0];
isTiled = soffTag.length > 1;
}
if (!isTiled) {
if (data[off] == 255 && data[off + 1] == SOI)
return { jpegOffset: off };
if (jpgIchgFmt != null) {
if (data[off + jifoff] == 255 && data[off + jifoff + 1] == SOI)
joff = off + jifoff;
else
log("JPEGInterchangeFormat does not point to SOI");
if (jpgIchgFmtLen == null)
log("JPEGInterchangeFormatLength field is missing");
else if (jifoff >= soff || jifoff + jiflen <= soff)
log("JPEGInterchangeFormatLength field value is invalid");
if (joff != null)
return { jpegOffset: joff };
}
}
if (ycbcrss != null) {
ssx = ycbcrss[0];
ssy = ycbcrss[1];
}
if (jpgIchgFmt != null) {
if (jpgIchgFmtLen != null)
if (jiflen >= 2 && jifoff + jiflen <= soff) {
if (data[off + jifoff + jiflen - 2] == 255 && data[off + jifoff + jiflen - 1] == SOI)
tables = new Uint8Array(jiflen - 2);
else
tables = new Uint8Array(jiflen);
for (i = 0;i < tables.length; i++)
tables[i] = data[off + jifoff + i];
log("Incorrect JPEG interchange format: using JPEGInterchangeFormat offset to derive tables");
} else
log("JPEGInterchangeFormat+JPEGInterchangeFormatLength > offset to first strip or tile");
}
if (tables == null) {
var ooff = 0, out = [];
out[ooff++] = 255;
out[ooff++] = SOI;
var qtables = img["t519"];
if (qtables == null)
throw new Error("JPEGQTables tag is missing");
for (i = 0;i < qtables.length; i++) {
out[ooff++] = 255;
out[ooff++] = DQT;
out[ooff++] = 0;
out[ooff++] = 67;
out[ooff++] = i;
for (j = 0;j < 64; j++)
out[ooff++] = data[off + qtables[i] + j];
}
for (k = 0;k < 2; k++) {
var htables = img[k == 0 ? "t520" : "t521"];
if (htables == null)
throw new Error((k == 0 ? "JPEGDCTables" : "JPEGACTables") + " tag is missing");
for (i = 0;i < htables.length; i++) {
out[ooff++] = 255;
out[ooff++] = DHT;
var nc = 19;
for (j = 0;j < 16; j++)
nc += data[off + htables[i] + j];
out[ooff++] = nc >>> 8;
out[ooff++] = nc & 255;
out[ooff++] = i | k << 4;
for (j = 0;j < 16; j++)
out[ooff++] = data[off + htables[i] + j];
for (j = 0;j < nc; j++)
out[ooff++] = data[off + htables[i] + 16 + j];
}
}
out[ooff++] = 255;
out[ooff++] = SOF0;
out[ooff++] = 0;
out[ooff++] = 8 + 3 * spp;
out[ooff++] = 8;
out[ooff++] = img.height >>> 8 & 255;
out[ooff++] = img.height & 255;
out[ooff++] = img.width >>> 8 & 255;
out[ooff++] = img.width & 255;
out[ooff++] = spp;
if (spp == 1) {
out[ooff++] = 1;
out[ooff++] = 17;
out[ooff++] = 0;
} else
for (i = 0;i < 3; i++) {
out[ooff++] = i + 1;
out[ooff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15;
out[ooff++] = i;
}
if (jpgresint != null && jpgresint[0] != 0) {
out[ooff++] = 255;
out[ooff++] = DRI;
out[ooff++] = 0;
out[ooff++] = 4;
out[ooff++] = jpgresint[0] >>> 8 & 255;
out[ooff++] = jpgresint[0] & 255;
}
tables = new Uint8Array(out);
}
var sofpos = -1;
i = 0;
while (i < tables.length - 1) {
if (tables[i] == 255 && tables[i + 1] == SOF0) {
sofpos = i;
break;
}
i++;
}
if (sofpos == -1) {
var tmptab = new Uint8Array(tables.length + 10 + 3 * spp);
tmptab.set(tables);
var tmpoff = tables.length;
sofpos = tables.length;
tables = tmptab;
tables[tmpoff++] = 255;
tables[tmpoff++] = SOF0;
tables[tmpoff++] = 0;
tables[tmpoff++] = 8 + 3 * spp;
tables[tmpoff++] = 8;
tables[tmpoff++] = img.height >>> 8 & 255;
tables[tmpoff++] = img.height & 255;
tables[tmpoff++] = img.width >>> 8 & 255;
tables[tmpoff++] = img.width & 255;
tables[tmpoff++] = spp;
if (spp == 1) {
tables[tmpoff++] = 1;
tables[tmpoff++] = 17;
tables[tmpoff++] = 0;
} else
for (i = 0;i < 3; i++) {
tables[tmpoff++] = i + 1;
tables[tmpoff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15;
tables[tmpoff++] = i;
}
}
if (data[soff] == 255 && data[soff + 1] == SOS2) {
var soslen = data[soff + 2] << 8 | data[soff + 3];
sosMarker2 = new Uint8Array(soslen + 2);
sosMarker2[0] = data[soff];
sosMarker2[1] = data[soff + 1];
sosMarker2[2] = data[soff + 2];
sosMarker2[3] = data[soff + 3];
for (i = 0;i < soslen - 2; i++)
sosMarker2[i + 4] = data[soff + i + 4];
} else {
sosMarker2 = new Uint8Array(2 + 6 + 2 * spp);
var sosoff = 0;
sosMarker2[sosoff++] = 255;
sosMarker2[sosoff++] = SOS2;
sosMarker2[sosoff++] = 0;
sosMarker2[sosoff++] = 6 + 2 * spp;
sosMarker2[sosoff++] = spp;
if (spp == 1) {
sosMarker2[sosoff++] = 1;
sosMarker2[sosoff++] = 0;
} else
for (i = 0;i < 3; i++) {
sosMarker2[sosoff++] = i + 1;
sosMarker2[sosoff++] = i << 4 | i;
}
sosMarker2[sosoff++] = 0;
sosMarker2[sosoff++] = 63;
sosMarker2[sosoff++] = 0;
}
return { jpegOffset: off, tables, sosMarker: sosMarker2, sofPosition: sofpos };
};
UTIF2.decode._decodeOldJPEG = function(img, data, off, len, tgt, toff) {
var i, dlen, tlen, buff, buffoff;
var jpegData = UTIF2.decode._decodeOldJPEGInit(img, data, off, len);
if (jpegData.jpegOffset != null) {
dlen = off + len - jpegData.jpegOffset;
buff = new Uint8Array(dlen);
for (i = 0;i < dlen; i++)
buff[i] = data[jpegData.jpegOffset + i];
} else {
tlen = jpegData.tables.length;
buff = new Uint8Array(tlen + jpegData.sosMarker.length + len + 2);
buff.set(jpegData.tables);
buffoff = tlen;
buff[jpegData.sofPosition + 5] = img.height >>> 8 & 255;
buff[jpegData.sofPosition + 6] = img.height & 255;
buff[jpegData.sofPosition + 7] = img.width >>> 8 & 255;
buff[jpegData.sofPosition + 8] = img.width & 255;
if (data[off] != 255 || data[off + 1] != SOS) {
buff.set(jpegData.sosMarker, buffoff);
buffoff += sosMarker.length;
}
for (i = 0;i < len; i++)
buff[buffoff++] = data[off + i];
buff[buffoff++] = 255;
buff[buffoff++] = EOI;
}
var parser = new UTIF2.JpegDecoder;
parser.parse(buff);
var decoded = parser.getData({ width: parser.width, height: parser.height, forceRGB: true, isSourcePDF: false });
for (var i = 0;i < decoded.length; i++)
tgt[toff + i] = decoded[i];
if (img["t262"] && img["t262"][0] == 6)
img["t262"][0] = 2;
};
UTIF2.decode._decodePackBits = function(data, off, len, tgt, toff) {
var sa = new Int8Array(data.buffer), ta = new Int8Array(tgt.buffer), lim = off + len;
while (off < lim) {
var n = sa[off];
off++;
if (n >= 0 && n < 128)
for (var i = 0;i < n + 1; i++) {
ta[toff] = sa[off];
toff++;
off++;
}
if (n >= -127 && n < 0) {
for (var i = 0;i < -n + 1; i++) {
ta[toff] = sa[off];
toff++;
}
off++;
}
}
return toff;
};
UTIF2.decode._decodeThunder = function(data, off, len, tgt, toff) {
var d2 = [0, 1, 0, -1], d3 = [0, 1, 2, 3, 0, -3, -2, -1];
var lim = off + len, qoff = toff * 2, px = 0;
while (off < lim) {
var b = data[off], msk = b >>> 6, n = b & 63;
off++;
if (msk == 3) {
px = n & 15;
tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1);
qoff++;
}
if (msk == 0)
for (var i = 0;i < n; i++) {
tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1);
qoff++;
}
if (msk == 2)
for (var i = 0;i < 2; i++) {
var d = n >>> 3 * (1 - i) & 7;
if (d != 4) {
px += d3[d];
tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1);
qoff++;
}
}
if (msk == 1)
for (var i = 0;i < 3; i++) {
var d = n >>> 2 * (2 - i) & 3;
if (d != 2) {
px += d2[d];
tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1);
qoff++;
}
}
}
};
UTIF2.decode._dmap = { "1": 0, "011": 1, "000011": 2, "0000011": 3, "010": -1, "000010": -2, "0000010": -3 };
UTIF2.decode._lens = function() {
var addKeys = function(lens, arr, i0, inc) {
for (var i = 0;i < arr.length; i++)
lens[arr[i]] = i0 + i * inc;
};
var termW = "00110101,000111,0111,1000,1011,1100,1110,1111,10011,10100,00111,01000,001000,000011,110100,110101," + "101010,101011,0100111,0001100,0001000,0010111,0000011,0000100,0101000,0101011,0010011,0100100,0011000,00000010,00000011,00011010," + "00011011,00010010,00010011,00010100,00010101,00010110,00010111,00101000,00101001,00101010,00101011,00101100,00101101,00000100,00000101,00001010," + "00001011,01010010,01010011,01010100,01010101,00100100,00100101,01011000,01011001,01011010,01011011,01001010,01001011,00110010,00110011,00110100";
var termB = "0000110111,010,11,10,011,0011,0010,00011,000101,000100,0000100,0000101,0000111,00000100,00000111,000011000," + "0000010111,0000011000,0000001000,00001100111,00001101000,00001101100,00000110111,00000101000,00000010111,00000011000,000011001010,000011001011,000011001100,000011001101,000001101000,000001101001," + "000001101010,000001101011,000011010010,000011010011,000011010100,000011010101,000011010110,000011010111,000001101100,000001101101,000011011010,000011011011,000001010100,000001010101,000001010110,000001010111," + "000001100100,000001100101,000001010010,000001010011,000000100100,000000110111,000000111000,000000100111,000000101000,000001011000,000001011001,000000101011,000000101100,000001011010,000001100110,000001100111";
var makeW = "11011,10010,010111,0110111,00110110,00110111,01100100,01100101,01101000,01100111,011001100,011001101,011010010,011010011,011010100,011010101,011010110," + "011010111,011011000,011011001,011011010,011011011,010011000,010011001,010011010,011000,010011011";
var makeB = "0000001111,000011001000,000011001001,000001011011,000000110011,000000110100,000000110101,0000001101100,0000001101101,0000001001010,0000001001011,0000001001100," + "0000001001101,0000001110010,0000001110011,0000001110100,0000001110101,0000001110110,0000001110111,0000001010010,0000001010011,0000001010100,0000001010101,0000001011010," + "0000001011011,0000001100100,0000001100101";
var makeA = "00000001000,00000001100,00000001101,000000010010,000000010011,000000010100,000000010101,000000010110,000000010111,000000011100,000000011101,000000011110,000000011111";
termW = termW.split(",");
termB = termB.split(",");
makeW = makeW.split(",");
makeB = makeB.split(",");
makeA = makeA.split(",");
var lensW = {}, lensB = {};
addKeys(lensW, termW, 0, 1);
addKeys(lensW, makeW, 64, 64);
addKeys(lensW, makeA, 1792, 64);
addKeys(lensB, termB, 0, 1);
addKeys(lensB, makeB, 64, 64);
addKeys(lensB, makeA, 1792, 64);
return [lensW, lensB];
}();
UTIF2.decode._decodeG4 = function(data, off, slen, tgt, toff, w, fo) {
var U = UTIF2.decode, boff = off << 3, len = 0, wrd = "";
var line = [], pline = [];
for (var i = 0;i < w; i++)
pline.push(0);
pline = U._makeDiff(pline);
var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b2 = 0, clr = 0;
var y = 0, mode = "", toRead = 0;
var bipl = Math.ceil(w / 8) * 8;
while (boff >>> 3 < off + slen) {
b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b2 = U._findDiff(pline, b1, clr);
var bit = 0;
if (fo == 1)
bit = data[boff >>> 3] >>> 7 - (boff & 7) & 1;
if (fo == 2)
bit = data[boff >>> 3] >>> (boff & 7) & 1;
boff++;
wrd += bit;
if (mode == "H") {
if (U._lens[clr][wrd] != null) {
var dl = U._lens[clr][wrd];
wrd = "";
len += dl;
if (dl < 64) {
U._addNtimes(line, len, clr);
a0 += len;
clr = 1 - clr;
len = 0;
toRead--;
if (toRead == 0)
mode = "";
}
}
} else {
if (wrd == "0001") {
wrd = "";
U._addNtimes(line, b2 - a0, clr);
a0 = b2;
}
if (wrd == "001") {
wrd = "";
mode = "H";
toRead = 2;
}
if (U._dmap[wrd] != null) {
a1 = b1 + U._dmap[wrd];
U._addNtimes(line, a1 - a0, clr);
a0 = a1;
wrd = "";
clr = 1 - clr;
}
}
if (line.length == w && mode == "") {
U._writeBits(line, tgt, toff * 8 + y * bipl);
clr = 0;
y++;
a0 = 0;
pline = U._makeDiff(line);
line = [];
}
}
};
UTIF2.decode._findDiff = function(line, x, clr) {
for (var i = 0;i < line.length; i += 2)
if (line[i] >= x && line[i + 1] == clr)
return line[i];
};
UTIF2.decode._makeDiff = function(line) {
var out = [];
if (line[0] == 1)
out.push(0, 1);
for (var i = 1;i < line.length; i++)
if (line[i - 1] != line[i])
out.push(i, line[i]);
out.push(line.length, 0, line.length, 1);
return out;
};
UTIF2.decode._decodeG2 = function(data, off, slen, tgt, toff, w, fo) {
var U = UTIF2.decode, boff = off << 3, len = 0, wrd = "";
var line = [];
var clr = 0;
var y = 0;
var bipl = Math.ceil(w / 8) * 8;
while (boff >>> 3 < off + slen) {
var bit = 0;
if (fo == 1)
bit = data[boff >>> 3] >>> 7 - (boff & 7) & 1;
if (fo == 2)
bit = data[boff >>> 3] >>> (boff & 7) & 1;
boff++;
wrd += bit;
len = U._lens[clr][wrd];
if (len != null) {
U._addNtimes(line, len, clr);
wrd = "";
if (len < 64)
clr = 1 - clr;
if (line.length == w) {
U._writeBits(line, tgt, toff * 8 + y * bipl);
line = [];
y++;
clr = 0;
if ((boff & 7) != 0)
boff += 8 - (boff & 7);
if (len >= 64)
boff += 8;
}
}
}
};
UTIF2.decode._decodeG3 = function(data, off, slen, tgt, toff, w, fo, twoDim) {
var U = UTIF2.decode, boff = off << 3, len = 0, wrd = "";
var line = [], pline = [];
for (var i = 0;i < w; i++)
line.push(0);
var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b2 = 0, clr = 0;
var y = -1, mode = "", toRead = 0, is1D = true;
var bipl = Math.ceil(w / 8) * 8;
while (boff >>> 3 < off + slen) {
b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b2 = U._findDiff(pline, b1, clr);
var bit = 0;
if (fo == 1)
bit = data[boff >>> 3] >>> 7 - (boff & 7) & 1;
if (fo == 2)
bit = data[boff >>> 3] >>> (boff & 7) & 1;
boff++;
wrd += bit;
if (is1D) {
if (U._lens[clr][wrd] != null) {
var dl = U._lens[clr][wrd];
wrd = "";
len += dl;
if (dl < 64) {
U._addNtimes(line, len, clr);
clr = 1 - clr;
len = 0;
}
}
} else {
if (mode == "H") {
if (U._lens[clr][wrd] != null) {
var dl = U._lens[clr][wrd];
wrd = "";
len += dl;
if (dl < 64) {
U._addNtimes(line, len, clr);
a0 += len;
clr = 1 - clr;
len = 0;
toRead--;
if (toRead == 0)
mode = "";
}
}
} else {
if (wrd == "0001") {
wrd = "";
U._addNtimes(line, b2 - a0, clr);
a0 = b2;
}
if (wrd == "001") {
wrd = "";
mode = "H";
toRead = 2;
}
if (U._dmap[wrd] != null) {
a1 = b1 + U._dmap[wrd];
U._addNtimes(line, a1 - a0, clr);
a0 = a1;
wrd = "";
clr = 1 - clr;
}
}
}
if (wrd.endsWith("000000000001")) {
if (y >= 0)
U._writeBits(line, tgt, toff * 8 + y * bipl);
if (twoDim) {
if (fo == 1)
is1D = (data[boff >>> 3] >>> 7 - (boff & 7) & 1) == 1;
if (fo == 2)
is1D = (data[boff >>> 3] >>> (boff & 7) & 1) == 1;
boff++;
}
wrd = "";
clr = 0;
y++;
a0 = 0;
pline = U._makeDiff(line);
line = [];
}
}
if (line.length == w)
U._writeBits(line, tgt, toff * 8 + y * bipl);
};
UTIF2.decode._addNtimes = function(arr, n, val) {
for (var i = 0;i < n; i++)
arr.push(val);
};
UTIF2.decode._writeBits = function(bits, tgt, boff) {
for (var i = 0;i < bits.length; i++)
tgt[boff + i >>> 3] |= bits[i] << 7 - (boff + i & 7);
};
UTIF2.decode._decodeLZW = UTIF2.decode._decodeLZW = function() {
var e, U, Z, u, K = 0, V = 0, g = 0, N = 0, O = function() {
var S = e >>> 3, A = U[S] << 16 | U[S + 1] << 8 | U[S + 2], j = A >>> 24 - (e & 7) - V & (1 << V) - 1;
e += V;
return j;
}, h = new Uint32Array(4096 * 4), w = 0, m = function(S) {
if (S == w)
return;
w = S;
g = 1 << S;
N = g + 1;
for (var A = 0;A < N + 1; A++) {
h[4 * A] = h[4 * A + 3] = A;
h[4 * A + 1] = 65535;
h[4 * A + 2] = 1;
}
}, i = function(S) {
V = S + 1;
K = N + 1;
}, D = function(S) {
var A = S << 2, j = h[A + 2], a = u + j - 1;
while (A != 65535) {
Z[a--] = h[A];
A = h[A + 1];
}
u += j;
}, L = function(S, A) {
var j = K << 2, a = S << 2;
h[j] = h[(A << 2) + 3];
h[j + 1] = a;
h[j + 2] = h[a + 2] + 1;
h[j + 3] = h[a + 3];
K++;
if (K + 1 == 1 << V && V != 12)
V++;
}, T = function(S, A, j, a, n, q) {
e = A << 3;
U = S;
Z = a;
u = n;
var B = A + j << 3, _ = 0, t = 0;
m(q);
i(q);
while (e < B && (_ = O()) != N) {
if (_ == g) {
i(q);
_ = O();
if (_ == N)
break;
D(_);
} else {
if (_ < K) {
D(_);
L(t, _);
} else {
L(t, t);
D(K - 1);
}
}
t = _;
}
return u;
};
return T;
}();
UTIF2.tags = {};
UTIF2._types = function() {
var main = new Array(250);
main.fill(0);
main = main.concat([0, 0, 0, 0, 4, 3, 3, 3, 3, 3, 0, 0, 3, 0, 0, 0, 3, 0, 0, 2, 2, 2, 2, 4, 3, 0, 0, 3, 4, 4, 3, 3, 5, 5, 3, 2, 5, 5, 0, 0, 0, 0, 4, 4, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 5, 5, 3, 0, 3, 3, 4, 4, 4, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
var rest = { 33432: 2, 33434: 5, 33437: 5, 34665: 4, 34850: 3, 34853: 4, 34855: 3, 34864: 3, 34866: 4, 36864: 7, 36867: 2, 36868: 2, 37121: 7, 37377: 10, 37378: 5, 37380: 10, 37381: 5, 37383: 3, 37384: 3, 37385: 3, 37386: 5, 37510: 7, 37520: 2, 37521: 2, 37522: 2, 40960: 7, 40961: 3, 40962: 4, 40963: 4, 40965: 4, 41486: 5, 41487: 5, 41488: 3, 41985: 3, 41986: 3, 41987: 3, 41988: 5, 41989: 3, 41990: 3, 41993: 3, 41994: 3, 41995: 7, 41996: 3, 42032: 2, 42033: 2, 42034: 5, 42036: 2, 42037: 2, 59932: 7 };
return {
basic: {
main,
rest
},
gps: {
main: [1, 2, 5, 2, 5, 1, 5, 5, 0, 9],
rest: { 18: 2, 29: 2 }
}
};
}();
UTIF2._readIFD = function(bin, data, offset, ifds, depth, prm) {
var cnt = bin.readUshort(data, offset);
offset += 2;
var ifd = {};
if (prm.debug)
log(" ".repeat(depth), ifds.length - 1, ">>>----------------");
for (var i = 0;i < cnt; i++) {
var tag = bin.readUshort(data, offset);
offset += 2;
var type = bin.readUshort(data, offset);
offset += 2;
var num = bin.readUint(data, offset);
offset += 4;
var voff = bin.readUint(data, offset);
offset += 4;
var arr = [];
if (type == 1 || type == 7) {
var no = num < 5 ? offset - 4 : voff;
if (no + num > data.buffer.byteLength)
num = data.buffer.byteLength - no;
arr = new Uint8Array(data.buffer, no, num);
}
if (type == 2) {
var o0 = num < 5 ? offset - 4 : voff, c = data[o0], len = Math.max(0, Math.min(num - 1, data.length - o0));
if (c < 128 || len == 0)
arr.push(bin.readASCII(data, o0, len));
else
arr = new Uint8Array(data.buffer, o0, len);
}
if (type == 3) {
for (var j = 0;j < num; j++)
arr.push(bin.readUshort(data, (num < 3 ? offset - 4 : voff) + 2 * j));
}
if (type == 4 || type == 13) {
for (var j = 0;j < num; j++)
arr.push(bin.readUint(data, (num < 2 ? offset - 4 : voff) + 4 * j));
}
if (type == 5 || type == 10) {
var ri = type == 5 ? bin.readUint : bin.readInt;
for (var j = 0;j < num; j++)
arr.push([ri(data, voff + j * 8), ri(data, voff + j * 8 + 4)]);
}
if (type == 8) {
for (var j = 0;j < num; j++)
arr.push(bin.readShort(data, (num < 3 ? offset - 4 : voff) + 2 * j));
}
if (type == 9) {
for (var j = 0;j < num; j++)
arr.push(bin.readInt(data, (num < 2 ? offset - 4 : voff) + 4 * j));
}
if (type == 11) {
for (var j = 0;j < num; j++)
arr.push(bin.readFloat(data, voff + j * 4));
}
if (type == 12) {
for (var j = 0;j < num; j++)
arr.push(bin.readDouble(data, voff + j * 8));
}
if (num != 0 && arr.length == 0) {
log(tag, "unknown TIFF tag type: ", type, "num:", num);
if (i == 0)
return;
continue;
}
if (prm.debug)
log(" ".repeat(depth), tag, type, UTIF2.tags[tag], arr);
ifd["t" + tag] = arr;
if (tag == 330 && ifd["t272"] && ifd["t272"][0] == "DSLR-A100") {} else if (tag == 330 || tag == 34665 || tag == 34853 || tag == 50740 && bin.readUshort(data, bin.readUint(arr, 0)) < 300 || tag == 61440) {
var oarr = tag == 50740 ? [bin.readUint(arr, 0)] : arr;
var subfd = [];
for (var j = 0;j < oarr.length; j++)
UTIF2._readIFD(bin, data, oarr[j], subfd, depth + 1, prm);
if (tag == 330)
ifd.subIFD = subfd;
if (tag == 34665)
ifd.exifIFD = subfd[0];
if (tag == 34853)
ifd.gpsiIFD = subfd[0];
if (tag == 50740)
ifd.dngPrvt = subfd[0];
if (tag == 61440)
ifd.fujiIFD = subfd[0];
}
if (tag == 37500 && prm.parseMN) {
var mn = arr;
if (bin.readASCII(mn, 0, 5) == "Nikon")
ifd.makerNote = UTIF2["decode"](mn.slice(10).buffer)[0];
else if (bin.readASCII(mn, 0, 5) == "OLYMP" || bin.readASCII(mn, 0, 9) == "OM SYSTEM") {
var inds = [8208, 8224, 8240, 8256, 8272];
var subsub = [];
UTIF2._readIFD(bin, mn, mn[1] == 77 ? 16 : mn[5] == 85 ? 12 : 8, subsub, depth + 1, prm);
var obj = ifd.makerNote = subsub.pop();
for (var j = 0;j < inds.length; j++) {
var k = "t" + inds[j];
if (obj[k] == null)
continue;
UTIF2._readIFD(bin, mn, obj[k][0], subsub, depth + 1, prm);
obj[k] = subsub.pop();
}
if (obj["t12288"]) {
UTIF2._readIFD(bin, obj["t12288"], 0, subsub, depth + 1, prm);
obj["t12288"] = subsub.pop();
}
} else if (bin.readUshort(data, voff) < 300 && bin.readUshort(data, voff + 4) <= 12) {
var subsub = [];
UTIF2._readIFD(bin, data, voff, subsub, depth + 1, prm);
ifd.makerNote = subsub[0];
}
}
}
ifds.push(ifd);
if (prm.debug)
log(" ".repeat(depth), "<<<---------------");
return offset;
};
UTIF2._writeIFD = function(bin, types2, data, offset, ifd) {
var keys = Object.keys(ifd), knum = keys.length;
if (ifd["exifIFD"])
knum--;
if (ifd["gpsiIFD"])
knum--;
bin.writeUshort(data, offset, knum);
offset += 2;
var eoff = offset + knum * 12 + 4;
for (var ki = 0;ki < keys.length; ki++) {
var key = keys[ki];
if (key == "t34665" || key == "t34853")
continue;
if (key == "exifIFD")
key = "t34665";
if (key == "gpsiIFD")
key = "t34853";
var tag = parseInt(key.slice(1)), type = types2.main[tag];
if (type == null)
type = types2.rest[tag];
if (type == null || type == 0)
throw new Error("unknown type of tag: " + tag);
var val = ifd[key];
if (tag == 34665) {
var outp = UTIF2._writeIFD(bin, types2, data, eoff, ifd["exifIFD"]);
val = [eoff];
eoff = outp[1];
}
if (tag == 34853) {
var outp = UTIF2._writeIFD(bin, UTIF2._types.gps, data, eoff, ifd["gpsiIFD"]);
val = [eoff];
eoff = outp[1];
}
if (type == 2)
val = val[0] + "\x00";
var num = val.length;
bin.writeUshort(data, offset, tag);
offset += 2;
bin.writeUshort(data, offset, type);
offset += 2;
bin.writeUint(data, offset, num);
offset += 4;
var dlen = [-1, 1, 1, 2, 4, 8, 0, 1, 0, 4, 8, 0, 8][type] * num;
var toff = offset;
if (dlen > 4) {
bin.writeUint(data, offset, eoff);
toff = eoff;
}
if (type == 1 || type == 7) {
for (var i = 0;i < num; i++)
data[toff + i] = val[i];
} else if (type == 2) {
bin.writeASCII(data, toff, val);
} else if (type == 3) {
for (var i = 0;i < num; i++)
bin.writeUshort(data, toff + 2 * i, val[i]);
} else if (type == 4) {
for (var i = 0;i < num; i++)
bin.writeUint(data, toff + 4 * i, val[i]);
} else if (type == 5 || type == 10) {
var wr = type == 5 ? bin.writeUint : bin.writeInt;
for (var i = 0;i < num; i++) {
var v = val[i], nu = v[0], de = v[1];
if (nu == null)
throw "e";
wr(data, toff + 8 * i, nu);
wr(data, toff + 8 * i + 4, de);
}
} else if (type == 9) {
for (var i = 0;i < num; i++)
bin.writeInt(data, toff + 4 * i, val[i]);
} else if (type == 12) {
for (var i = 0;i < num; i++)
bin.writeDouble(data, toff + 8 * i, val[i]);
} else
throw type;
if (dlen > 4) {
dlen += dlen & 1;
eoff += dlen;
}
offset += 4;
}
return [offset, eoff];
};
UTIF2.toRGBA8 = function(out, scl) {
function gamma(x2) {
return x2 < 0.0031308 ? 12.92 * x2 : 1.055 * Math.pow(x2, 1 / 2.4) - 0.055;
}
var { width: w, height: h } = out, area = w * h, qarea = area * 4, data = out.data;
var img = new Uint8Array(area * 4);
var intp = out["t262"] ? out["t262"][0] : 2, bps = out["t258"] ? Math.min(32, out["t258"][0]) : 1;
if (out["t262"] == null && bps == 1)
intp = 0;
var smpls = out["t277"] ? out["t277"][0] : out["t258"] ? out["t258"].length : [1, 1, 3, 1, 1, 4, 3][intp];
var sfmt = out["t339"] ? out["t339"][0] : null;
if (intp == 1 && bps == 32 && sfmt != 3)
throw "e";
var bpl = Math.ceil(smpls * bps * w / 8);
if (false) {} else if (intp == 0) {
scl = 1 / 256;
for (var y = 0;y < h; y++) {
var off = y * bpl, io = y * w;
if (bps == 1)
for (var i = 0;i < w; i++) {
var qi = io + i << 2, px = data[off + (i >> 3)] >> 7 - (i & 7) & 1;
img[qi] = img[qi + 1] = img[qi + 2] = (1 - px) * 255;
img[qi + 3] = 255;
}
if (bps == 4)
for (var i = 0;i < w; i++) {
var qi = io + i << 2, px = data[off + (i >> 1)] >> 4 - 4 * (i & 1) & 15;
img[qi] = img[qi + 1] = img[qi + 2] = (15 - px) * 17;
img[qi + 3] = 255;
}
if (bps == 8)
for (var i = 0;i < w; i++) {
var qi = io + i << 2, px = data[off + i];
img[qi] = img[qi + 1] = img[qi + 2] = 255 - px;
img[qi + 3] = 255;
}
if (bps == 16)
for (var i = 0;i < w; i++) {
var qi = io + i << 2, o = off + 2 * i, px = data[o + 1] << 8 | data[o];
img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, 255 - ~~(px * scl));
img[qi + 3] = 255;
}
}
} else if (intp == 1) {
if (scl == null)
scl = 1 / 256;
var f32 = (data.length & 3) == 0 ? new Float32Array(data.buffer) : null;
for (var y = 0;y < h; y++) {
var off = y * bpl, io = y * w;
if (bps == 1)
for (var i = 0;i < w; i++) {
var qi = io + i << 2, px = data[off + (i >> 3)] >> 7 - (i & 7) & 1;
img[qi] = img[qi + 1] = img[qi + 2] = px * 255;
img[qi + 3] = 255;
}
if (bps == 2)
for (var i = 0;i < w; i++) {
var qi = io + i << 2, px = data[off + (i >> 2)] >> 6 - 2 * (i & 3) & 3;
img[qi] = img[qi + 1] = img[qi + 2] = px * 85;
img[qi + 3] = 255;
}
if (bps == 8)
for (var i = 0;i < w; i++) {
var qi = io + i << 2, px = data[off + i * smpls];
img[qi] = img[qi + 1] = img[qi + 2] = px;
img[qi + 3] = 255;
}
if (bps == 16)
for (var i = 0;i < w; i++) {
var qi = io + i << 2, o = off + 2 * i, px = data[o + 1] << 8 | data[o];
img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, ~~(px * scl));
img[qi + 3] = 255;
}
if (bps == 32)
for (var i = 0;i < w; i++) {
var qi = io + i << 2, o = (off >>> 2) + i, px = f32[o];
img[qi] = img[qi + 1] = img[qi + 2] = ~~(0.5 + 255 * px);
img[qi + 3] = 255;
}
}
} else if (intp == 2) {
if (bps == 8) {
if (smpls == 1)
for (var i = 0;i < area; i++) {
img[4 * i] = img[4 * i + 1] = img[4 * i + 2] = data[i];
img[4 * i + 3] = 255;
}
if (smpls == 3)
for (var i = 0;i < area; i++) {
var qi = i << 2, ti = i * 3;
img[qi] = data[ti];
img[qi + 1] = data[ti + 1];
img[qi + 2] = data[ti + 2];
img[qi + 3] = 255;
}
if (smpls >= 4)
for (var i = 0;i < area; i++) {
var qi = i << 2, ti = i * smpls;
img[qi] = data[ti];
img[qi + 1] = data[ti + 1];
img[qi + 2] = data[ti + 2];
img[qi + 3] = data[ti + 3];
}
} else if (bps == 16) {
if (smpls == 4)
for (var i = 0;i < area; i++) {
var qi = i << 2, ti = i * 8 + 1;
img[qi] = data[ti];
img[qi + 1] = data[ti + 2];
img[qi + 2] = data[ti + 4];
img[qi + 3] = data[ti + 6];
}
if (smpls == 3)
for (var i = 0;i < area; i++) {
var qi = i << 2, ti = i * 6 + 1;
img[qi] = data[ti];
img[qi + 1] = data[ti + 2];
img[qi + 2] = data[ti + 4];
img[qi + 3] = 255;
}
} else if (bps == 32) {
var ndt = new Float32Array(data.buffer);
var min = 0;
for (var i = 0;i < ndt.length; i++)
min = Math.min(min, ndt[i]);
if (min < 0)
for (var i = 0;i < data.length; i += 4) {
var t = data[i];
data[i] = data[i + 3];
data[i + 3] = t;
t = data[i + 1];
data[i + 1] = data[i + 2];
data[i + 2] = t;
}
var pmap = [];
for (var i = 0;i < 65536; i++)
pmap.push(gamma(i / 65535));
for (var i = 0;i < ndt.length; i++) {
var cv = Math.max(0, Math.min(1, ndt[i]));
ndt[i] = pmap[~~(0.5 + cv * 65535)];
}
if (smpls == 3)
for (var i = 0;i < area; i++) {
var qi = i << 2, ti = i * 3;
img[qi] = ~~(0.5 + ndt[ti] * 255);
img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255);
img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255);
img[qi + 3] = 255;
}
else if (smpls == 4)
for (var i = 0;i < area; i++) {
var qi = i << 2, ti = i * 4;
img[qi] = ~~(0.5 + ndt[ti] * 255);
img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255);
img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255);
img[qi + 3] = ~~(0.5 + ndt[ti + 3] * 255);
}
else
throw smpls;
} else
throw bps;
} else if (intp == 3) {
var map = out["t320"];
var cn = 1 << bps;
var nexta = bps == 8 && smpls > 1 && out["t338"] && out["t338"][0] != 0;
for (var y = 0;y < h; y++)
for (var x = 0;x < w; x++) {
var i = y * w + x;
var qi = i << 2, mi = 0;
var dof = y * bpl;
if (false) {} else if (bps == 1)
mi = data[dof + (x >>> 3)] >>> 7 - (x & 7) & 1;
else if (bps == 2)
mi = data[dof + (x >>> 2)] >>> 6 - 2 * (x & 3) & 3;
else if (bps == 4)
mi = data[dof + (x >>> 1)] >>> 4 - 4 * (x & 1) & 15;
else if (bps == 8)
mi = data[dof + x * smpls];
else
throw bps;
img[qi] = map[mi] >> 8;
img[qi + 1] = map[cn + mi] >> 8;
img[qi + 2] = map[cn + cn + mi] >> 8;
img[qi + 3] = nexta ? data[dof + x * smpls + 1] : 255;
}
} else if (intp == 5) {
var gotAlpha = smpls > 4 ? 1 : 0;
for (var i = 0;i < area; i++) {
var qi = i << 2, si = i * smpls;
if (window.UDOC) {
var C = data[si], M = data[si + 1], Y = data[si + 2], K = data[si + 3];
var c = UDOC.C.cmykToRgb([C * (1 / 255), M * (1 / 255), Y * (1 / 255), K * (1 / 255)]);
img[qi] = ~~(0.5 + 255 * c[0]);
img[qi + 1] = ~~(0.5 + 255 * c[1]);
img[qi + 2] = ~~(0.5 + 255 * c[2]);
} else {
var C = 255 - data[si], M = 255 - data[si + 1], Y = 255 - data[si + 2], K = (255 - data[si + 3]) * (1 / 255);
img[qi] = ~~(C * K + 0.5);
img[qi + 1] = ~~(M * K + 0.5);
img[qi + 2] = ~~(Y * K + 0.5);
}
img[qi + 3] = 255 * (1 - gotAlpha) + data[si + 4] * gotAlpha;
}
} else if (intp == 6 && out["t278"]) {
var rps = out["t278"][0];
for (var y = 0;y < h; y += rps) {
var i = y * w, len = rps * w;
for (var j = 0;j < len; j++) {
var qi = 4 * (i + j), si = 3 * i + 4 * (j >>> 1);
var Y = data[si + (j & 1)], Cb = data[si + 2] - 128, Cr = data[si + 3] - 128;
var r = Y + ((Cr >> 2) + (Cr >> 3) + (Cr >> 5));
var g = Y - ((Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ((Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5));
var b = Y + (Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6));
img[qi] = Math.max(0, Math.min(255, r));
img[qi + 1] = Math.max(0, Math.min(255, g));
img[qi + 2] = Math.max(0, Math.min(255, b));
img[qi + 3] = 255;
}
}
} else if (intp == 32845) {
for (var y = 0;y < h; y++)
for (var x = 0;x < w; x++) {
var si = (y * w + x) * 6, qi = (y * w + x) * 4;
var L = data[si + 1] << 8 | data[si];
var L = Math.pow(2, (L + 0.5) / 256 - 64);
var u = (data[si + 3] + 0.5) / 410;
var v = (data[si + 5] + 0.5) / 410;
var sX = 9 * u / (6 * u - 16 * v + 12);
var sY = 4 * v / (6 * u - 16 * v + 12);
var bY = L;
var X = sX * bY / sY, Y = bY, Z = (1 - sX - sY) * bY / sY;
var r = 2.69 * X - 1.276 * Y - 0.414 * Z;
var g = -1.022 * X + 1.978 * Y + 0.044 * Z;
var b = 0.061 * X - 0.224 * Y + 1.163 * Z;
img[qi] = gamma(Math.min(r, 1)) * 255;
img[qi + 1] = gamma(Math.min(g, 1)) * 255;
img[qi + 2] = gamma(Math.min(b, 1)) * 255;
img[qi + 3] = 255;
}
} else
log("Unknown Photometric interpretation: " + intp);
return img;
};
UTIF2.replaceIMG = function(imgs) {
if (imgs == null)
imgs = document.getElementsByTagName("img");
var sufs = ["tif", "tiff", "dng", "cr2", "nef"];
for (var i = 0;i < imgs.length; i++) {
var img = imgs[i], src = img.getAttribute("src");
if (src == null)
continue;
var suff = src.split(".").pop().toLowerCase();
if (sufs.indexOf(suff) == -1)
continue;
var xhr = new XMLHttpRequest;
UTIF2._xhrs.push(xhr);
UTIF2._imgs.push(img);
xhr.open("GET", src);
xhr.responseType = "arraybuffer";
xhr.onload = UTIF2._imgLoaded;
xhr.send();
}
};
UTIF2._xhrs = [];
UTIF2._imgs = [];
UTIF2._imgLoaded = function(e) {
var ind = UTIF2._xhrs.indexOf(e.target), img = UTIF2._imgs[ind];
UTIF2._xhrs.splice(ind, 1);
UTIF2._imgs.splice(ind, 1);
img.setAttribute("src", UTIF2.bufferToURI(e.target.response));
};
UTIF2.bufferToURI = function(buff) {
var ifds = UTIF2.decode(buff);
var vsns = ifds, ma = 0, page = vsns[0];
if (ifds[0].subIFD)
vsns = vsns.concat(ifds[0].subIFD);
for (var i = 0;i < vsns.length; i++) {
var img = vsns[i];
if (img["t258"] == null || img["t258"].length < 3)
continue;
var ar = img["t256"] * img["t257"];
if (ar > ma) {
ma = ar;
page = img;
}
}
UTIF2.decodeImage(buff, page, ifds);
var rgba = UTIF2.toRGBA8(page), w = page.width, h = page.height;
var cnv = document.createElement("canvas");
cnv.width = w;
cnv.height = h;
var ctx = cnv.getContext("2d");
var imgd = new ImageData(new Uint8ClampedArray(rgba.buffer), w, h);
ctx.putImageData(imgd, 0, 0);
return cnv.toDataURL();
};
UTIF2._binBE = {
nextZero: function(data, o) {
while (data[o] != 0)
o++;
return o;
},
readUshort: function(buff, p) {
return buff[p] << 8 | buff[p + 1];
},
readShort: function(buff, p) {
var a = UTIF2._binBE.ui8;
a[0] = buff[p + 1];
a[1] = buff[p + 0];
return UTIF2._binBE.i16[0];
},
readInt: function(buff, p) {
var a = UTIF2._binBE.ui8;
a[0] = buff[p + 3];
a[1] = buff[p + 2];
a[2] = buff[p + 1];
a[3] = buff[p + 0];
return UTIF2._binBE.i32[0];
},
readUint: function(buff, p) {
var a = UTIF2._binBE.ui8;
a[0] = buff[p + 3];
a[1] = buff[p + 2];
a[2] = buff[p + 1];
a[3] = buff[p + 0];
return UTIF2._binBE.ui32[0];
},
readASCII: function(buff, p, l) {
var s = "";
for (var i = 0;i < l; i++)
s += String.fromCharCode(buff[p + i]);
return s;
},
readFloat: function(buff, p) {
var a = UTIF2._binBE.ui8;
for (var i = 0;i < 4; i++)
a[i] = buff[p + 3 - i];
return UTIF2._binBE.fl32[0];
},
readDouble: function(buff, p) {
var a = UTIF2._binBE.ui8;
for (var i = 0;i < 8; i++)
a[i] = buff[p + 7 - i];
return UTIF2._binBE.fl64[0];
},
writeUshort: function(buff, p, n) {
buff[p] = n >> 8 & 255;
buff[p + 1] = n & 255;
},
writeInt: function(buff, p, n) {
var a = UTIF2._binBE.ui8;
UTIF2._binBE.i32[0] = n;
buff[p + 3] = a[0];
buff[p + 2] = a[1];
buff[p + 1] = a[2];
buff[p + 0] = a[3];
},
writeUint: function(buff, p, n) {
buff[p] = n >> 24 & 255;
buff[p + 1] = n >> 16 & 255;
buff[p + 2] = n >> 8 & 255;
buff[p + 3] = n >> 0 & 255;
},
writeASCII: function(buff, p, s) {
for (var i = 0;i < s.length; i++)
buff[p + i] = s.charCodeAt(i);
},
writeDouble: function(buff, p, n) {
UTIF2._binBE.fl64[0] = n;
for (var i = 0;i < 8; i++)
buff[p + i] = UTIF2._binBE.ui8[7 - i];
}
};
UTIF2._binBE.ui8 = new Uint8Array(8);
UTIF2._binBE.i16 = new Int16Array(UTIF2._binBE.ui8.buffer);
UTIF2._binBE.i32 = new Int32Array(UTIF2._binBE.ui8.buffer);
UTIF2._binBE.ui32 = new Uint32Array(UTIF2._binBE.ui8.buffer);
UTIF2._binBE.fl32 = new Float32Array(UTIF2._binBE.ui8.buffer);
UTIF2._binBE.fl64 = new Float64Array(UTIF2._binBE.ui8.buffer);
UTIF2._binLE = {
nextZero: UTIF2._binBE.nextZero,
readUshort: function(buff, p) {
return buff[p + 1] << 8 | buff[p];
},
readShort: function(buff, p) {
var a = UTIF2._binBE.ui8;
a[0] = buff[p + 0];
a[1] = buff[p + 1];
return UTIF2._binBE.i16[0];
},
readInt: function(buff, p) {
var a = UTIF2._binBE.ui8;
a[0] = buff[p + 0];
a[1] = buff[p + 1];
a[2] = buff[p + 2];
a[3] = buff[p + 3];
return UTIF2._binBE.i32[0];
},
readUint: function(buff, p) {
var a = UTIF2._binBE.ui8;
a[0] = buff[p + 0];
a[1] = buff[p + 1];
a[2] = buff[p + 2];
a[3] = buff[p + 3];
return UTIF2._binBE.ui32[0];
},
readASCII: UTIF2._binBE.readASCII,
readFloat: function(buff, p) {
var a = UTIF2._binBE.ui8;
for (var i = 0;i < 4; i++)
a[i] = buff[p + i];
return UTIF2._binBE.fl32[0];
},
readDouble: function(buff, p) {
var a = UTIF2._binBE.ui8;
for (var i = 0;i < 8; i++)
a[i] = buff[p + i];
return UTIF2._binBE.fl64[0];
},
writeUshort: function(buff, p, n) {
buff[p] = n & 255;
buff[p + 1] = n >> 8 & 255;
},
writeInt: function(buff, p, n) {
var a = UTIF2._binBE.ui8;
UTIF2._binBE.i32[0] = n;
buff[p + 0] = a[0];
buff[p + 1] = a[1];
buff[p + 2] = a[2];
buff[p + 3] = a[3];
},
writeUint: function(buff, p, n) {
buff[p] = n >>> 0 & 255;
buff[p + 1] = n >>> 8 & 255;
buff[p + 2] = n >>> 16 & 255;
buff[p + 3] = n >>> 24 & 255;
},
writeASCII: UTIF2._binBE.writeASCII
};
UTIF2._copyTile = function(tb, tw, th, b, w, h, xoff, yoff) {
var xlim = Math.min(tw, w - xoff);
var ylim = Math.min(th, h - yoff);
for (var y = 0;y < ylim; y++) {
var tof = (yoff + y) * w + xoff;
var sof = y * tw;
for (var x = 0;x < xlim; x++)
b[tof + x] = tb[sof + x];
}
};
UTIF2.LosslessJpegDecode = function() {
var b, O;
function l() {
return b[O++];
}
function m() {
return b[O++] << 8 | b[O++];
}
function a0(h) {
var V = l(), I = [0, 0, 0, 255], f = [], G = 8;
for (var w = 0;w < 16; w++)
f[w] = l();
for (var w = 0;w < 16; w++) {
for (var x = 0;x < f[w]; x++) {
var T = z(I, 0, w + 1, 1);
I[T + 3] = l();
}
}
var E = new Uint8Array(1 << G);
h[V] = [new Uint8Array(I), E];
for (var w = 0;w < 1 << G; w++) {
var s = G, _ = w, Y = 0, F = 0;
while (I[Y + 3] == 255 && s != 0) {
F = _ >> --s & 1;
Y = I[Y + F];
}
E[w] = Y;
}
}
function z(h, V, I, f) {
if (h[V + 3] != 255)
return 0;
if (I == 0)
return V;
for (var w = 0;w < 2; w++) {
if (h[V + w] == 0) {
h[V + w] = h.length;
h.push(0, 0, f, 255);
}
var x = z(h, h[V + w], I - 1, f + 1);
if (x != 0)
return x;
}
return 0;
}
function i(h) {
var { b: V, f: I } = h;
while (V < 25 && h.a < h.d) {
var f = h.data[h.a++];
if (f == 255 && !h.c)
h.a++;
I = I << 8 | f;
V += 8;
}
if (V < 0)
throw "e";
h.b = V;
h.f = I;
}
function H(h, V) {
if (V.b < h)
i(V);
return V.f >> (V.b -= h) & 65535 >> 16 - h;
}
function g(h, V) {
var I = h[0], f = 0, w = 255, x = 0;
if (V.b < 16)
i(V);
var T = V.f >> V.b - 8 & 255;
f = h[1][T];
w = I[f + 3];
V.b -= I[f + 2];
while (w == 255) {
x = V.f >> --V.b & 1;
f = I[f + x];
w = I[f + 3];
}
return w;
}
function P(h, V) {
if (h < 32768 >> 16 - V)
h += -(1 << V) + 1;
return h;
}
function a2(h, V) {
var I = g(h, V);
if (I == 0)
return 0;
if (I == 16)
return -32768;
var f = H(I, V);
return P(f, I);
}
function X(h, V, I, f, w, x) {
var T = 0;
for (var G = 0;G < x; G++) {
var s = G * V;
for (var _ = 0;_ < V; _ += w) {
T++;
for (var Y = 0;Y < w; Y++)
h[s + _ + Y] = a2(f[Y], I);
}
if (I.e != 0 && T % I.e == 0 && G != 0) {
var { a: F, data: t } = I;
while (t[F] != 255 || !(208 <= t[F + 1] && t[F + 1] <= 215))
F--;
I.a = F + 2;
I.f = 0;
I.b = 0;
}
}
}
function o(h, V) {
return P(H(h, V), h);
}
function a1(h, V, I, f, w) {
var x = b.length - O;
for (var T = 0;T < x; T += 4) {
var G = b[O + T];
b[O + T] = b[O + T + 3];
b[O + T + 3] = G;
var G = b[O + T + 1];
b[O + T + 1] = b[O + T + 2];
b[O + T + 2] = G;
}
for (var E = 0;E < w; E++) {
var s = 32768, _ = 32768;
for (var Y = 0;Y < V; Y += 2) {
var F = g(f, I), t = g(f, I);
if (F != 0)
s += o(F, I);
if (t != 0)
_ += o(t, I);
h[E * V + Y] = s & 65535;
h[E * V + Y + 1] = _ & 65535;
}
}
}
function C(h) {
b = h;
O = 0;
if (m() != 65496)
throw "e";
var V = [], I = 0, f = 0, w = 0, x = [], T = [], G = [], E = 0, s = 0, _ = 0;
while (true) {
var Y = m();
if (Y == 65535) {
O--;
continue;
}
var F = m();
if (Y == 65475) {
f = l();
s = m();
_ = m();
E = l();
for (var t = 0;t < E; t++) {
var a = l(), J = l(), r = l();
if (r != 0)
throw "e";
V[a] = [t, J >> 4, J & 15];
}
} else if (Y == 65476) {
var a3 = O + F - 2;
while (O < a3)
a0(T);
} else if (Y == 65498) {
O++;
for (var t = 0;t < E; t++) {
var a5 = l(), v = V[a5];
G[v[0]] = T[l() >>> 4];
x[v[0]] = v.slice(1);
}
I = l();
O += 2;
break;
} else if (Y == 65501) {
w = m();
} else {
O += F - 2;
}
}
var a4 = f > 8 ? Uint16Array : Uint8Array, $ = new a4(s * _ * E), M = { b: 0, f: 0, c: I == 8, a: O, data: b, d: b.length, e: w };
if (M.c)
a1($, _ * E, M, G[0], s);
else {
var c = [], p = 0, D = 0;
for (var t = 0;t < E; t++) {
var N = x[t], S = N[0], K = N[1];
if (S > p)
p = S;
if (K > D)
D = K;
c.push(S * K);
}
if (p != 1 || D != 1) {
if (E != 3 || c[1] != 1 || c[2] != 1)
throw "e";
if (p != 2 || D != 1 && D != 2)
throw "e";
var u = [], Z = 0;
for (var t = 0;t < E; t++) {
for (var R = 0;R < c[t]; R++)
u.push(G[t]);
Z += c[t];
}
var B = _ / p, e = s / D, d = B * e;
X($, B * Z, M, u, Z, e);
j($, I, B, e, Z - 2, Z, Z, f);
var A = new Uint16Array(d * c[0]);
if (p == 2 && D == 2) {
for (var t = 0;t < d; t++) {
A[4 * t] = $[6 * t];
A[4 * t + 1] = $[6 * t + 1];
A[4 * t + 2] = $[6 * t + 2];
A[4 * t + 3] = $[6 * t + 3];
}
j(A, I, B * 4, e, 0, 1, 1, f);
for (var t = 0;t < d; t++) {
$[6 * t] = A[4 * t];
$[6 * t + 1] = A[4 * t + 1];
$[6 * t + 2] = A[4 * t + 2];
$[6 * t + 3] = A[4 * t + 3];
}
}
if (p == 2 && D == 1) {
for (var t = 0;t < d; t++) {
A[2 * t] = $[4 * t];
A[2 * t + 1] = $[4 * t + 1];
}
j(A, I, B * 2, e, 0, 1, 1, f);
for (var t = 0;t < d; t++) {
$[4 * t] = A[2 * t];
$[4 * t + 1] = A[2 * t + 1];
}
}
var n = $.slice(0);
for (var K = 0;K < s; K++) {
if (D == 2)
for (var S = 0;S < _; S++) {
var q = (K * _ + S) * E, k = ((K >>> 1) * B + (S >>> 1)) * Z, y = (K & 1) * 2 + (S & 1);
$[q] = n[k + y];
$[q + 1] = n[k + 4];
$[q + 2] = n[k + 5];
}
else
for (var S = 0;S < _; S++) {
var q = (K * _ + S) * E, k = (K * B + (S >>> 1)) * Z, y = S & 1;
$[q] = n[k + y];
$[q + 1] = n[k + 2];
$[q + 2] = n[k + 3];
}
}
} else {
X($, _ * E, M, G, E, s);
if (w == 0)
j($, I, _, s, 0, E, E, f);
else {
var U = Math.floor(w / _);
for (var K = 0;K < s; K += U) {
var L = $.slice(K * _ * E, (K + U) * _ * E);
j(L, I, _, U, 0, E, E, f);
$.set(L, K * _ * E);
}
}
}
}
return $;
}
function j(h, V, I, f, w, x, G, E) {
var s = I * G;
for (var _ = w;_ < x; _++)
h[_] += 1 << E - 1;
for (var Y = G;Y < s; Y += G)
for (var _ = w;_ < x; _++)
h[Y + _] += h[Y + _ - G];
for (var F = 1;F < f; F++) {
var t = F * s;
for (var _ = w;_ < x; _++)
h[t + _] += h[t + _ - s];
for (var Y = G;Y < s; Y += G) {
for (var _ = w;_ < x; _++) {
var a = t + Y + _, J = a - s, r = h[a - G], Q = 0;
if (V == 0)
Q = 0;
else if (V == 1)
Q = r;
else if (V == 2)
Q = h[J];
else if (V == 3)
Q = h[J - G];
else if (V == 4)
Q = r + (h[J] - h[J - G]);
else if (V == 5)
Q = r + (h[J] - h[J - G] >>> 1);
else if (V == 6)
Q = h[J] + (r - h[J - G] >>> 1);
else if (V == 7)
Q = r + h[J] >>> 1;
else
throw V;
h[a] += Q;
}
}
}
}
return C;
}();
(function() {
var G = 0, F = 1, i = 2, b = 3, J = 4, N = 5, E = 6, s = 7, c = 8, T = 9, a3 = 10, f = 11, q = 12, M = 13, m = 14, x = 15, L = 16, $ = 17, p = 18;
function a5(t) {
var Z = UTIF2._binBE.readUshort, u = { b: Z(t, 0), i: t[2], C: t[3], u: t[4], q: Z(t, 5), k: Z(t, 7), e: Z(t, 9), l: Z(t, 11), s: t[13], d: Z(t, 14) };
if (u.b != 18771 || u.i > 1 || u.q < 6 || u.q % 6 || u.e < 768 || u.e % 24 || u.l != 768 || u.k < u.l || u.k % u.l || u.k - u.e >= u.l || u.s > 16 || u.s != u.k / u.l || u.s != Math.ceil(u.e / u.l) || u.d != u.q / 6 || u.u != 12 && u.u != 14 && u.u != 16 || u.C != 16 && u.C != 0) {
throw "Invalid data";
}
if (u.i == 0) {
throw "Not implemented. We need this file!";
}
u.h = u.C == 16;
u.m = (u.h ? u.l * 2 / 3 : u.l >>> 1) | 0;
u.A = u.m + 2;
u.f = 64;
u.g = (1 << u.u) - 1;
u.n = 4 * u.u;
return u;
}
function a7(t, Z) {
var u = new Array(Z.s), e = 4 * Z.s, Q = 16 + e;
if (e & 12)
Q += 16 - (e & 12);
for (var V = 0, O = 16;V < Z.s; O += 4) {
var o = UTIF2._binBE.readUint(t, O);
u[V] = t.slice(Q, Q + o);
u[V].j = 0;
u[V].a = 0;
Q += o;
V++;
}
if (Q != t.length)
throw "Invalid data";
return u;
}
function a6(t, Z) {
for (var u = -Z[4], e = 0;u <= Z[4]; e++, u++) {
t[e] = u <= -Z[3] ? -4 : u <= -Z[2] ? -3 : u <= -Z[1] ? -2 : u < -Z[0] ? -1 : u <= Z[0] ? 0 : u < Z[1] ? 1 : u < Z[2] ? 2 : u < Z[3] ? 3 : 4;
}
}
function a1(t, Z, u) {
var e = [Z, 3 * Z + 18, 5 * Z + 67, 7 * Z + 276, u];
t.o = Z;
t.w = (e[4] + 2 * Z) / (2 * Z + 1) + 1 | 0;
t.v = Math.ceil(Math.log2(t.w));
t.t = 9;
a6(t.c, e);
}
function a2(t) {
var Z = { c: new Int8Array(2 << t.u) };
a1(Z, 0, t.g);
return Z;
}
function D(t) {
var Z = [[], [], []], u = Math.max(2, t.w + 32 >>> 6);
for (var e = 0;e < 3; e++) {
for (var Q = 0;Q < 41; Q++) {
Z[e][Q] = [u, 1];
}
}
return Z;
}
function a4(t) {
for (var Z = -1, u = 0;!u; Z++) {
u = t[t.j] >>> 7 - t.a & 1;
t.a++;
t.a &= 7;
if (!t.a)
t.j++;
}
return Z;
}
function K(t, Z) {
var u = 0, e = 8 - t.a, Q = t.j, V = t.a;
if (Z) {
if (Z >= e) {
do {
u <<= e;
Z -= e;
u |= t[t.j] & (1 << e) - 1;
t.j++;
e = 8;
} while (Z >= 8);
}
if (Z) {
u <<= Z;
e -= Z;
u |= t[t.j] >>> e & (1 << Z) - 1;
}
t.a = 8 - e;
}
return u;
}
function a0(t, Z) {
var u = 0;
if (Z < t) {
while (u <= 14 && Z << ++u < t)
;
}
return u;
}
function r(t, Z, u, e, Q, V, O, o) {
if (o == null)
o = 0;
var X = V + 1, k = X % 2, j = 0, I = 0, a = 0, l, R, w = e[Q], S = e[Q - 1], H = e[Q - 2][X], g = S[X - 1], Y = S[X], P = S[X + 1], A = w[X - 1], v = w[X + 1], y = Math.abs, d, C, n, h;
if (k) {
d = y(P - Y);
C = y(H - Y);
n = y(g - Y);
}
if (k) {
h = d > n && C < d ? H + g : d < n && C < n ? H + P : P + g;
h = h + 2 * Y >>> 2;
if (o) {
w[X] = h;
return;
}
l = Z.t * Z.c[t.g + Y - H] + Z.c[t.g + g - Y];
} else {
h = Y > g && Y > P || Y < g && Y < P ? v + A + 2 * Y >>> 2 : A + v >>> 1;
l = Z.t * Z.c[t.g + Y - g] + Z.c[t.g + g - A];
}
R = y(l);
var W = a4(u);
if (W < t.n - Z.v - 1) {
var z = a0(O[R][0], O[R][1]);
a = K(u, z) + (W << z);
} else {
a = K(u, Z.v) + 1;
}
a = a & 1 ? -1 - (a >>> 1) : a >>> 1;
O[R][0] += y(a);
if (O[R][1] == t.f) {
O[R][0] >>>= 1;
O[R][1] >>>= 1;
}
O[R][1]++;
h = l < 0 ? h - a : h + a;
if (t.i) {
if (h < 0)
h += Z.w;
else if (h > t.g)
h -= Z.w;
}
w[X] = h >= 0 ? Math.min(h, t.g) : 0;
}
function U(t, Z, u) {
var e = t[0].length;
for (var Q = Z;Q <= u; Q++) {
t[Q][0] = t[Q - 1][1];
t[Q][e - 1] = t[Q - 1][e - 2];
}
}
function B(t) {
U(t, s, q);
U(t, i, J);
U(t, x, $);
}
function _(t, Z, u, e, Q, V, O, o, X, k, j, I, a) {
var l = 0, R = 1, w = Q < M && Q > J;
while (R < t.m) {
if (l < t.m) {
r(t, Z, u, e, Q, l, O[X], t.h && (w && k || !w && (j || (l & I) == a)));
r(t, Z, u, e, V, l, O[X], t.h && (!w && k || w && (j || (l & I) == a)));
l += 2;
}
if (l > 8) {
r(t, Z, u, e, Q, R, o[X]);
r(t, Z, u, e, V, R, o[X]);
R += 2;
}
}
B(e);
}
function a8(t, Z, u, e, Q, V) {
_(t, Z, u, e, i, s, Q, V, 0, 0, 1, 0, 8);
_(t, Z, u, e, c, x, Q, V, 1, 0, 1, 0, 8);
_(t, Z, u, e, b, T, Q, V, 2, 1, 0, 3, 0);
_(t, Z, u, e, a3, L, Q, V, 0, 0, 0, 3, 2);
_(t, Z, u, e, J, f, Q, V, 1, 0, 0, 3, 2);
_(t, Z, u, e, q, $, Q, V, 2, 1, 0, 3, 0);
}
function a9(t, Z, u, e, Q, V) {
var O = V.length, o = t.l;
if (Q + 1 == t.s)
o = t.e - Q * t.l;
var X = 6 * t.e * e + Q * t.l;
for (var k = 0;k < 6; k++) {
for (var j = 0;j < o; j++) {
var I = V[k % O][j % O], a;
if (I == 0) {
a = i + (k >>> 1);
} else if (I == 2) {
a = x + (k >>> 1);
} else {
a = s + k;
}
var l = t.h ? (j * 2 / 3 & 2147483646 | j % 3 & 1) + (j % 3 >>> 1) : j >>> 1;
Z[X + j] = u[a][l + 1];
}
X += t.e;
}
}
UTIF2._decompressRAF = function(t, Z) {
var u = a5(t), e = a7(t, u), Q = a2(u), V = new Int16Array(u.e * u.q);
if (Z == null) {
Z = u.h ? [[1, 1, 0, 1, 1, 2], [1, 1, 2, 1, 1, 0], [2, 0, 1, 0, 2, 1], [1, 1, 2, 1, 1, 0], [1, 1, 0, 1, 1, 2], [0, 2, 1, 2, 0, 1]] : [[0, 1], [3, 2]];
}
var O = [[G, b], [F, J], [N, f], [E, q], [M, L], [m, $]], o = [];
for (var X = 0;X < p; X++) {
o[X] = new Uint16Array(u.A);
}
for (var k = 0;k < u.s; k++) {
var j = D(Q), I = D(Q);
for (var X = 0;X < p; X++) {
for (var a = 0;a < u.A; a++) {
o[X][a] = 0;
}
}
for (var l = 0;l < u.d; l++) {
a8(u, Q, e[k], o, j, I);
for (var X = 0;X < 6; X++) {
for (var a = 0;a < u.A; a++) {
o[O[X][0]][a] = o[O[X][1]][a];
}
}
a9(u, V, o, l, k, Z);
for (var X = i;X < p; X++) {
if ([N, E, M, m].indexOf(X) == -1) {
for (var a = 0;a < u.A; a++) {
o[X][a] = 0;
}
}
}
B(o);
}
}
return V;
};
})();
})(UTIF, pako);
})();
});
// ../../node_modules/.bun/ieee754@1.2.1/node_modules/ieee754/index.js
var require_ieee754 = __commonJS((exports) => {
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? nBytes - 1 : 0;
var d = isLE ? -1 : 1;
var s = buffer[offset + i];
i += d;
e = s & (1 << -nBits) - 1;
s >>= -nBits;
nBits += eLen;
for (;nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for (;nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : (s ? -1 : 1) * Infinity;
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
var i = isLE ? 0 : nBytes - 1;
var d = isLE ? 1 : -1;
var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (;mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {}
e = e << mLen | m;
eLen += mLen;
for (;eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128;
};
});
// ../../node_modules/.bun/token-types@4.2.1/node_modules/token-types/lib/index.js
var require_lib = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnsiStringType = exports.StringType = exports.BufferType = exports.Uint8ArrayType = exports.IgnoreType = exports.Float80_LE = exports.Float80_BE = exports.Float64_LE = exports.Float64_BE = exports.Float32_LE = exports.Float32_BE = exports.Float16_LE = exports.Float16_BE = exports.INT64_BE = exports.UINT64_BE = exports.INT64_LE = exports.UINT64_LE = exports.INT32_LE = exports.INT32_BE = exports.INT24_BE = exports.INT24_LE = exports.INT16_LE = exports.INT16_BE = exports.INT8 = exports.UINT32_BE = exports.UINT32_LE = exports.UINT24_BE = exports.UINT24_LE = exports.UINT16_BE = exports.UINT16_LE = exports.UINT8 = undefined;
var ieee754 = require_ieee754();
function dv(array) {
return new DataView(array.buffer, array.byteOffset);
}
exports.UINT8 = {
len: 1,
get(array, offset) {
return dv(array).getUint8(offset);
},
put(array, offset, value) {
dv(array).setUint8(offset, value);
return offset + 1;
}
};
exports.UINT16_LE = {
len: 2,
get(array, offset) {
return dv(array).getUint16(offset, true);
},
put(array, offset, value) {
dv(array).setUint16(offset, value, true);
return offset + 2;
}
};
exports.UINT16_BE = {
len: 2,
get(array, offset) {
return dv(array).getUint16(offset);
},
put(array, offset, value) {
dv(array).setUint16(offset, value);
return offset + 2;
}
};
exports.UINT24_LE = {
len: 3,
get(array, offset) {
const dataView = dv(array);
return dataView.getUint8(offset) + (dataView.getUint16(offset + 1, true) << 8);
},
put(array, offset, value) {
const dataView = dv(array);
dataView.setUint8(offset, value & 255);
dataView.setUint16(offset + 1, value >> 8, true);
return offset + 3;
}
};
exports.UINT24_BE = {
len: 3,
get(array, offset) {
const dataView = dv(array);
return (dataView.getUint16(offset) << 8) + dataView.getUint8(offset + 2);
},
put(array, offset, value) {
const dataView = dv(array);
dataView.setUint16(offset, value >> 8);
dataView.setUint8(offset + 2, value & 255);
return offset + 3;
}
};
exports.UINT32_LE = {
len: 4,
get(array, offset) {
return dv(array).getUint32(offset, true);
},
put(array, offset, value) {
dv(array).setUint32(offset, value, true);
return offset + 4;
}
};
exports.UINT32_BE = {
len: 4,
get(array, offset) {
return dv(array).getUint32(offset);
},
put(array, offset, value) {
dv(array).setUint32(offset, value);
return offset + 4;
}
};
exports.INT8 = {
len: 1,
get(array, offset) {
return dv(array).getInt8(offset);
},
put(array, offset, value) {
dv(array).setInt8(offset, value);
return offset + 1;
}
};
exports.INT16_BE = {
len: 2,
get(array, offset) {
return dv(array).getInt16(offset);
},
put(array, offset, value) {
dv(array).setInt16(offset, value);
return offset + 2;
}
};
exports.INT16_LE = {
len: 2,
get(array, offset) {
return dv(array).getInt16(offset, true);
},
put(array, offset, value) {
dv(array).setInt16(offset, value, true);
return offset + 2;
}
};
exports.INT24_LE = {
len: 3,
get(array, offset) {
const unsigned = exports.UINT24_LE.get(array, offset);
return unsigned > 8388607 ? unsigned - 16777216 : unsigned;
},
put(array, offset, value) {
const dataView = dv(array);
dataView.setUint8(offset, value & 255);
dataView.setUint16(offset + 1, value >> 8, true);
return offset + 3;
}
};
exports.INT24_BE = {
len: 3,
get(array, offset) {
const unsigned = exports.UINT24_BE.get(array, offset);
return unsigned > 8388607 ? unsigned - 16777216 : unsigned;
},
put(array, offset, value) {
const dataView = dv(array);
dataView.setUint16(offset, value >> 8);
dataView.setUint8(offset + 2, value & 255);
return offset + 3;
}
};
exports.INT32_BE = {
len: 4,
get(array, offset) {
return dv(array).getInt32(offset);
},
put(array, offset, value) {
dv(array).setInt32(offset, value);
return offset + 4;
}
};
exports.INT32_LE = {
len: 4,
get(array, offset) {
return dv(array).getInt32(offset, true);
},
put(array, offset, value) {
dv(array).setInt32(offset, value, true);
return offset + 4;
}
};
exports.UINT64_LE = {
len: 8,
get(array, offset) {
return dv(array).getBigUint64(offset, true);
},
put(array, offset, value) {
dv(array).setBigUint64(offset, value, true);
return offset + 8;
}
};
exports.INT64_LE = {
len: 8,
get(array, offset) {
return dv(array).getBigInt64(offset, true);
},
put(array, offset, value) {
dv(array).setBigInt64(offset, value, true);
return offset + 8;
}
};
exports.UINT64_BE = {
len: 8,
get(array, offset) {
return dv(array).getBigUint64(offset);
},
put(array, offset, value) {
dv(array).setBigUint64(offset, value);
return offset + 8;
}
};
exports.INT64_BE = {
len: 8,
get(array, offset) {
return dv(array).getBigInt64(offset);
},
put(array, offset, value) {
dv(array).setBigInt64(offset, value);
return offset + 8;
}
};
exports.Float16_BE = {
len: 2,
get(dataView, offset) {
return ieee754.read(dataView, offset, false, 10, this.len);
},
put(dataView, offset, value) {
ieee754.write(dataView, value, offset, false, 10, this.len);
return offset + this.len;
}
};
exports.Float16_LE = {
len: 2,
get(array, offset) {
return ieee754.read(array, offset, true, 10, this.len);
},
put(array, offset, value) {
ieee754.write(array, value, offset, true, 10, this.len);
return offset + this.len;
}
};
exports.Float32_BE = {
len: 4,
get(array, offset) {
return dv(array).getFloat32(offset);
},
put(array, offset, value) {
dv(array).setFloat32(offset, value);
return offset + 4;
}
};
exports.Float32_LE = {
len: 4,
get(array, offset) {
return dv(array).getFloat32(offset, true);
},
put(array, offset, value) {
dv(array).setFloat32(offset, value, true);
return offset + 4;
}
};
exports.Float64_BE = {
len: 8,
get(array, offset) {
return dv(array).getFloat64(offset);
},
put(array, offset, value) {
dv(array).setFloat64(offset, value);
return offset + 8;
}
};
exports.Float64_LE = {
len: 8,
get(array, offset) {
return dv(array).getFloat64(offset, true);
},
put(array, offset, value) {
dv(array).setFloat64(offset, value, true);
return offset + 8;
}
};
exports.Float80_BE = {
len: 10,
get(array, offset) {
return ieee754.read(array, offset, false, 63, this.len);
},
put(array, offset, value) {
ieee754.write(array, value, offset, false, 63, this.len);
return offset + this.len;
}
};
exports.Float80_LE = {
len: 10,
get(array, offset) {
return ieee754.read(array, offset, true, 63, this.len);
},
put(array, offset, value) {
ieee754.write(array, value, offset, true, 63, this.len);
return offset + this.len;
}
};
class IgnoreType {
constructor(len) {
this.len = len;
}
get(array, off) {}
}
exports.IgnoreType = IgnoreType;
class Uint8ArrayType {
constructor(len) {
this.len = len;
}
get(array, offset) {
return array.subarray(offset, offset + this.len);
}
}
exports.Uint8ArrayType = Uint8ArrayType;
class BufferType {
constructor(len) {
this.len = len;
}
get(uint8Array, off) {
return Buffer.from(uint8Array.subarray(off, off + this.len));
}
}
exports.BufferType = BufferType;
class StringType {
constructor(len, encoding) {
this.len = len;
this.encoding = encoding;
}
get(uint8Array, offset) {
return Buffer.from(uint8Array).toString(this.encoding, offset, offset + this.len);
}
}
exports.StringType = StringType;
class AnsiStringType {
constructor(len) {
this.len = len;
}
static decode(buffer, offset, until) {
let str = "";
for (let i = offset;i < until; ++i) {
str += AnsiStringType.codePointToString(AnsiStringType.singleByteDecoder(buffer[i]));
}
return str;
}
static inRange(a, min, max) {
return min <= a && a <= max;
}
static codePointToString(cp) {
if (cp <= 65535) {
return String.fromCharCode(cp);
} else {
cp -= 65536;
return String.fromCharCode((cp >> 10) + 55296, (cp & 1023) + 56320);
}
}
static singleByteDecoder(bite) {
if (AnsiStringType.inRange(bite, 0, 127)) {
return bite;
}
const codePoint = AnsiStringType.windows1252[bite - 128];
if (codePoint === null) {
throw Error("invaliding encoding");
}
return codePoint;
}
get(buffer, offset = 0) {
return AnsiStringType.decode(buffer, offset, offset + this.len);
}
}
exports.AnsiStringType = AnsiStringType;
AnsiStringType.windows1252 = [
8364,
129,
8218,
402,
8222,
8230,
8224,
8225,
710,
8240,
352,
8249,
338,
141,
381,
143,
144,
8216,
8217,
8220,
8221,
8226,
8211,
8212,
732,
8482,
353,
8250,
339,
157,
382,
376,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
174,
175,
176,
177,
178,
179,
180,
181,
182,
183,
184,
185,
186,
187,
188,
189,
190,
191,
192,
193,
194,
195,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
210,
211,
212,
213,
214,
215,
216,
217,
218,
219,
220,
221,
222,
223,
224,
225,
226,
227,
228,
229,
230,
231,
232,
233,
234,
235,
236,
237,
238,
239,
240,
241,
242,
243,
244,
245,
246,
247,
248,
249,
250,
251,
252,
253,
254,
255
];
});
// ../../node_modules/.bun/peek-readable@4.1.0/node_modules/peek-readable/lib/EndOfFileStream.js
var require_EndOfFileStream = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.EndOfStreamError = exports.defaultMessages = undefined;
exports.defaultMessages = "End-Of-Stream";
class EndOfStreamError extends Error {
constructor() {
super(exports.defaultMessages);
}
}
exports.EndOfStreamError = EndOfStreamError;
});
// ../../node_modules/.bun/peek-readable@4.1.0/node_modules/peek-readable/lib/Deferred.js
var require_Deferred = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Deferred = undefined;
class Deferred {
constructor() {
this.resolve = () => null;
this.reject = () => null;
this.promise = new Promise((resolve2, reject2) => {
this.reject = reject2;
this.resolve = resolve2;
});
}
}
exports.Deferred = Deferred;
});
// ../../node_modules/.bun/peek-readable@4.1.0/node_modules/peek-readable/lib/StreamReader.js
var require_StreamReader = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.StreamReader = exports.EndOfStreamError = undefined;
var EndOfFileStream_1 = require_EndOfFileStream();
var Deferred_1 = require_Deferred();
var EndOfFileStream_2 = require_EndOfFileStream();
Object.defineProperty(exports, "EndOfStreamError", { enumerable: true, get: function() {
return EndOfFileStream_2.EndOfStreamError;
} });
var maxStreamReadSize = 1 * 1024 * 1024;
class StreamReader {
constructor(s) {
this.s = s;
this.deferred = null;
this.endOfStream = false;
this.peekQueue = [];
if (!s.read || !s.once) {
throw new Error("Expected an instance of stream.Readable");
}
this.s.once("end", () => this.reject(new EndOfFileStream_1.EndOfStreamError));
this.s.once("error", (err) => this.reject(err));
this.s.once("close", () => this.reject(new Error("Stream closed")));
}
async peek(uint8Array, offset, length) {
const bytesRead = await this.read(uint8Array, offset, length);
this.peekQueue.push(uint8Array.subarray(offset, offset + bytesRead));
return bytesRead;
}
async read(buffer, offset, length) {
if (length === 0) {
return 0;
}
if (this.peekQueue.length === 0 && this.endOfStream) {
throw new EndOfFileStream_1.EndOfStreamError;
}
let remaining = length;
let bytesRead = 0;
while (this.peekQueue.length > 0 && remaining > 0) {
const peekData = this.peekQueue.pop();
if (!peekData)
throw new Error("peekData should be defined");
const lenCopy = Math.min(peekData.length, remaining);
buffer.set(peekData.subarray(0, lenCopy), offset + bytesRead);
bytesRead += lenCopy;
remaining -= lenCopy;
if (lenCopy < peekData.length) {
this.peekQueue.push(peekData.subarray(lenCopy));
}
}
while (remaining > 0 && !this.endOfStream) {
const reqLen = Math.min(remaining, maxStreamReadSize);
const chunkLen = await this.readFromStream(buffer, offset + bytesRead, reqLen);
bytesRead += chunkLen;
if (chunkLen < reqLen)
break;
remaining -= chunkLen;
}
return bytesRead;
}
async readFromStream(buffer, offset, length) {
const readBuffer = this.s.read(length);
if (readBuffer) {
buffer.set(readBuffer, offset);
return readBuffer.length;
} else {
const request = {
buffer,
offset,
length,
deferred: new Deferred_1.Deferred
};
this.deferred = request.deferred;
this.s.once("readable", () => {
this.readDeferred(request);
});
return request.deferred.promise;
}
}
readDeferred(request) {
const readBuffer = this.s.read(request.length);
if (readBuffer) {
request.buffer.set(readBuffer, request.offset);
request.deferred.resolve(readBuffer.length);
this.deferred = null;
} else {
this.s.once("readable", () => {
this.readDeferred(request);
});
}
}
reject(err) {
this.endOfStream = true;
if (this.deferred) {
this.deferred.reject(err);
this.deferred = null;
}
}
}
exports.StreamReader = StreamReader;
});
// ../../node_modules/.bun/peek-readable@4.1.0/node_modules/peek-readable/lib/index.js
var require_lib2 = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.StreamReader = exports.EndOfStreamError = undefined;
var EndOfFileStream_1 = require_EndOfFileStream();
Object.defineProperty(exports, "EndOfStreamError", { enumerable: true, get: function() {
return EndOfFileStream_1.EndOfStreamError;
} });
var StreamReader_1 = require_StreamReader();
Object.defineProperty(exports, "StreamReader", { enumerable: true, get: function() {
return StreamReader_1.StreamReader;
} });
});
// ../../node_modules/.bun/strtok3@6.3.0/node_modules/strtok3/lib/AbstractTokenizer.js
var require_AbstractTokenizer = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbstractTokenizer = undefined;
var peek_readable_1 = require_lib2();
class AbstractTokenizer {
constructor(fileInfo) {
this.position = 0;
this.numBuffer = new Uint8Array(8);
this.fileInfo = fileInfo ? fileInfo : {};
}
async readToken(token, position = this.position) {
const uint8Array = Buffer.alloc(token.len);
const len = await this.readBuffer(uint8Array, { position });
if (len < token.len)
throw new peek_readable_1.EndOfStreamError;
return token.get(uint8Array, 0);
}
async peekToken(token, position = this.position) {
const uint8Array = Buffer.alloc(token.len);
const len = await this.peekBuffer(uint8Array, { position });
if (len < token.len)
throw new peek_readable_1.EndOfStreamError;
return token.get(uint8Array, 0);
}
async readNumber(token) {
const len = await this.readBuffer(this.numBuffer, { length: token.len });
if (len < token.len)
throw new peek_readable_1.EndOfStreamError;
return token.get(this.numBuffer, 0);
}
async peekNumber(token) {
const len = await this.peekBuffer(this.numBuffer, { length: token.len });
if (len < token.len)
throw new peek_readable_1.EndOfStreamError;
return token.get(this.numBuffer, 0);
}
async ignore(length) {
if (this.fileInfo.size !== undefined) {
const bytesLeft = this.fileInfo.size - this.position;
if (length > bytesLeft) {
this.position += bytesLeft;
return bytesLeft;
}
}
this.position += length;
return length;
}
async close() {}
normalizeOptions(uint8Array, options) {
if (options && options.position !== undefined && options.position < this.position) {
throw new Error("`options.position` must be equal or greater than `tokenizer.position`");
}
if (options) {
return {
mayBeLess: options.mayBeLess === true,
offset: options.offset ? options.offset : 0,
length: options.length ? options.length : uint8Array.length - (options.offset ? options.offset : 0),
position: options.position ? options.position : this.position
};
}
return {
mayBeLess: false,
offset: 0,
length: uint8Array.length,
position: this.position
};
}
}
exports.AbstractTokenizer = AbstractTokenizer;
});
// ../../node_modules/.bun/strtok3@6.3.0/node_modules/strtok3/lib/ReadStreamTokenizer.js
var require_ReadStreamTokenizer = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReadStreamTokenizer = undefined;
var AbstractTokenizer_1 = require_AbstractTokenizer();
var peek_readable_1 = require_lib2();
var maxBufferSize = 256000;
class ReadStreamTokenizer extends AbstractTokenizer_1.AbstractTokenizer {
constructor(stream2, fileInfo) {
super(fileInfo);
this.streamReader = new peek_readable_1.StreamReader(stream2);
}
async getFileInfo() {
return this.fileInfo;
}
async readBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
const skipBytes = normOptions.position - this.position;
if (skipBytes > 0) {
await this.ignore(skipBytes);
return this.readBuffer(uint8Array, options);
} else if (skipBytes < 0) {
throw new Error("`options.position` must be equal or greater than `tokenizer.position`");
}
if (normOptions.length === 0) {
return 0;
}
const bytesRead = await this.streamReader.read(uint8Array, normOptions.offset, normOptions.length);
this.position += bytesRead;
if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) {
throw new peek_readable_1.EndOfStreamError;
}
return bytesRead;
}
async peekBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
let bytesRead = 0;
if (normOptions.position) {
const skipBytes = normOptions.position - this.position;
if (skipBytes > 0) {
const skipBuffer = new Uint8Array(normOptions.length + skipBytes);
bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess });
uint8Array.set(skipBuffer.subarray(skipBytes), normOptions.offset);
return bytesRead - skipBytes;
} else if (skipBytes < 0) {
throw new Error("Cannot peek from a negative offset in a stream");
}
}
if (normOptions.length > 0) {
try {
bytesRead = await this.streamReader.peek(uint8Array, normOptions.offset, normOptions.length);
} catch (err) {
if (options && options.mayBeLess && err instanceof peek_readable_1.EndOfStreamError) {
return 0;
}
throw err;
}
if (!normOptions.mayBeLess && bytesRead < normOptions.length) {
throw new peek_readable_1.EndOfStreamError;
}
}
return bytesRead;
}
async ignore(length) {
const bufSize = Math.min(maxBufferSize, length);
const buf = new Uint8Array(bufSize);
let totBytesRead = 0;
while (totBytesRead < length) {
const remaining = length - totBytesRead;
const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) });
if (bytesRead < 0) {
return bytesRead;
}
totBytesRead += bytesRead;
}
return totBytesRead;
}
}
exports.ReadStreamTokenizer = ReadStreamTokenizer;
});
// ../../node_modules/.bun/strtok3@6.3.0/node_modules/strtok3/lib/BufferTokenizer.js
var require_BufferTokenizer = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.BufferTokenizer = undefined;
var peek_readable_1 = require_lib2();
var AbstractTokenizer_1 = require_AbstractTokenizer();
class BufferTokenizer extends AbstractTokenizer_1.AbstractTokenizer {
constructor(uint8Array, fileInfo) {
super(fileInfo);
this.uint8Array = uint8Array;
this.fileInfo.size = this.fileInfo.size ? this.fileInfo.size : uint8Array.length;
}
async readBuffer(uint8Array, options) {
if (options && options.position) {
if (options.position < this.position) {
throw new Error("`options.position` must be equal or greater than `tokenizer.position`");
}
this.position = options.position;
}
const bytesRead = await this.peekBuffer(uint8Array, options);
this.position += bytesRead;
return bytesRead;
}
async peekBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length);
if (!normOptions.mayBeLess && bytes2read < normOptions.length) {
throw new peek_readable_1.EndOfStreamError;
} else {
uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read), normOptions.offset);
return bytes2read;
}
}
async close() {}
}
exports.BufferTokenizer = BufferTokenizer;
});
// ../../node_modules/.bun/strtok3@6.3.0/node_modules/strtok3/lib/core.js
var require_core = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromBuffer = exports.fromStream = exports.EndOfStreamError = undefined;
var ReadStreamTokenizer_1 = require_ReadStreamTokenizer();
var BufferTokenizer_1 = require_BufferTokenizer();
var peek_readable_1 = require_lib2();
Object.defineProperty(exports, "EndOfStreamError", { enumerable: true, get: function() {
return peek_readable_1.EndOfStreamError;
} });
function fromStream(stream2, fileInfo) {
fileInfo = fileInfo ? fileInfo : {};
return new ReadStreamTokenizer_1.ReadStreamTokenizer(stream2, fileInfo);
}
exports.fromStream = fromStream;
function fromBuffer(uint8Array, fileInfo) {
return new BufferTokenizer_1.BufferTokenizer(uint8Array, fileInfo);
}
exports.fromBuffer = fromBuffer;
});
// ../../node_modules/.bun/file-type@16.5.4/node_modules/file-type/util.js
var require_util = __commonJS((exports) => {
exports.stringToBytes = (string) => [...string].map((character) => character.charCodeAt(0));
exports.tarHeaderChecksumMatches = (buffer, offset = 0) => {
const readSum = parseInt(buffer.toString("utf8", 148, 154).replace(/\0.*$/, "").trim(), 8);
if (isNaN(readSum)) {
return false;
}
let sum = 8 * 32;
for (let i = offset;i < offset + 148; i++) {
sum += buffer[i];
}
for (let i = offset + 156;i < offset + 512; i++) {
sum += buffer[i];
}
return readSum === sum;
};
exports.uint32SyncSafeToken = {
get: (buffer, offset) => {
return buffer[offset + 3] & 127 | buffer[offset + 2] << 7 | buffer[offset + 1] << 14 | buffer[offset] << 21;
},
len: 4
};
});
// ../../node_modules/.bun/file-type@16.5.4/node_modules/file-type/supported.js
var require_supported = __commonJS((exports, module) => {
module.exports = {
extensions: [
"jpg",
"png",
"apng",
"gif",
"webp",
"flif",
"xcf",
"cr2",
"cr3",
"orf",
"arw",
"dng",
"nef",
"rw2",
"raf",
"tif",
"bmp",
"icns",
"jxr",
"psd",
"indd",
"zip",
"tar",
"rar",
"gz",
"bz2",
"7z",
"dmg",
"mp4",
"mid",
"mkv",
"webm",
"mov",
"avi",
"mpg",
"mp2",
"mp3",
"m4a",
"oga",
"ogg",
"ogv",
"opus",
"flac",
"wav",
"spx",
"amr",
"pdf",
"epub",
"exe",
"swf",
"rtf",
"wasm",
"woff",
"woff2",
"eot",
"ttf",
"otf",
"ico",
"flv",
"ps",
"xz",
"sqlite",
"nes",
"crx",
"xpi",
"cab",
"deb",
"ar",
"rpm",
"Z",
"lz",
"cfb",
"mxf",
"mts",
"blend",
"bpg",
"docx",
"pptx",
"xlsx",
"3gp",
"3g2",
"jp2",
"jpm",
"jpx",
"mj2",
"aif",
"qcp",
"odt",
"ods",
"odp",
"xml",
"mobi",
"heic",
"cur",
"ktx",
"ape",
"wv",
"dcm",
"ics",
"glb",
"pcap",
"dsf",
"lnk",
"alias",
"voc",
"ac3",
"m4v",
"m4p",
"m4b",
"f4v",
"f4p",
"f4b",
"f4a",
"mie",
"asf",
"ogm",
"ogx",
"mpc",
"arrow",
"shp",
"aac",
"mp1",
"it",
"s3m",
"xm",
"ai",
"skp",
"avif",
"eps",
"lzh",
"pgp",
"asar",
"stl",
"chm",
"3mf",
"zst",
"jxl",
"vcf"
],
mimeTypes: [
"image/jpeg",
"image/png",
"image/gif",
"image/webp",
"image/flif",
"image/x-xcf",
"image/x-canon-cr2",
"image/x-canon-cr3",
"image/tiff",
"image/bmp",
"image/vnd.ms-photo",
"image/vnd.adobe.photoshop",
"application/x-indesign",
"application/epub+zip",
"application/x-xpinstall",
"application/vnd.oasis.opendocument.text",
"application/vnd.oasis.opendocument.spreadsheet",
"application/vnd.oasis.opendocument.presentation",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/zip",
"application/x-tar",
"application/x-rar-compressed",
"application/gzip",
"application/x-bzip2",
"application/x-7z-compressed",
"application/x-apple-diskimage",
"application/x-apache-arrow",
"video/mp4",
"audio/midi",
"video/x-matroska",
"video/webm",
"video/quicktime",
"video/vnd.avi",
"audio/vnd.wave",
"audio/qcelp",
"audio/x-ms-asf",
"video/x-ms-asf",
"application/vnd.ms-asf",
"video/mpeg",
"video/3gpp",
"audio/mpeg",
"audio/mp4",
"audio/opus",
"video/ogg",
"audio/ogg",
"application/ogg",
"audio/x-flac",
"audio/ape",
"audio/wavpack",
"audio/amr",
"application/pdf",
"application/x-msdownload",
"application/x-shockwave-flash",
"application/rtf",
"application/wasm",
"font/woff",
"font/woff2",
"application/vnd.ms-fontobject",
"font/ttf",
"font/otf",
"image/x-icon",
"video/x-flv",
"application/postscript",
"application/eps",
"application/x-xz",
"application/x-sqlite3",
"application/x-nintendo-nes-rom",
"application/x-google-chrome-extension",
"application/vnd.ms-cab-compressed",
"application/x-deb",
"application/x-unix-archive",
"application/x-rpm",
"application/x-compress",
"application/x-lzip",
"application/x-cfb",
"application/x-mie",
"application/mxf",
"video/mp2t",
"application/x-blender",
"image/bpg",
"image/jp2",
"image/jpx",
"image/jpm",
"image/mj2",
"audio/aiff",
"application/xml",
"application/x-mobipocket-ebook",
"image/heif",
"image/heif-sequence",
"image/heic",
"image/heic-sequence",
"image/icns",
"image/ktx",
"application/dicom",
"audio/x-musepack",
"text/calendar",
"text/vcard",
"model/gltf-binary",
"application/vnd.tcpdump.pcap",
"audio/x-dsf",
"application/x.ms.shortcut",
"application/x.apple.alias",
"audio/x-voc",
"audio/vnd.dolby.dd-raw",
"audio/x-m4a",
"image/apng",
"image/x-olympus-orf",
"image/x-sony-arw",
"image/x-adobe-dng",
"image/x-nikon-nef",
"image/x-panasonic-rw2",
"image/x-fujifilm-raf",
"video/x-m4v",
"video/3gpp2",
"application/x-esri-shape",
"audio/aac",
"audio/x-it",
"audio/x-s3m",
"audio/x-xm",
"video/MP1S",
"video/MP2P",
"application/vnd.sketchup.skp",
"image/avif",
"application/x-lzh-compressed",
"application/pgp-encrypted",
"application/x-asar",
"model/stl",
"application/vnd.ms-htmlhelp",
"model/3mf",
"image/jxl",
"application/zstd"
]
};
});
// ../../node_modules/.bun/file-type@16.5.4/node_modules/file-type/core.js
var require_core2 = __commonJS((exports, module) => {
var Token = require_lib();
var strtok3 = require_core();
var {
stringToBytes,
tarHeaderChecksumMatches,
uint32SyncSafeToken
} = require_util();
var supported = require_supported();
var minimumBytes = 4100;
async function fromStream(stream3) {
const tokenizer = await strtok3.fromStream(stream3);
try {
return await fromTokenizer(tokenizer);
} finally {
await tokenizer.close();
}
}
async function fromBuffer(input) {
if (!(input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer.isBuffer(input))) {
throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`Buffer\` or \`ArrayBuffer\`, got \`${typeof input}\``);
}
const buffer = input instanceof Buffer ? input : Buffer.from(input);
if (!(buffer && buffer.length > 1)) {
return;
}
const tokenizer = strtok3.fromBuffer(buffer);
return fromTokenizer(tokenizer);
}
function _check(buffer, headers, options) {
options = {
offset: 0,
...options
};
for (const [index, header] of headers.entries()) {
if (options.mask) {
if (header !== (options.mask[index] & buffer[index + options.offset])) {
return false;
}
} else if (header !== buffer[index + options.offset]) {
return false;
}
}
return true;
}
async function fromTokenizer(tokenizer) {
try {
return _fromTokenizer(tokenizer);
} catch (error) {
if (!(error instanceof strtok3.EndOfStreamError)) {
throw error;
}
}
}
async function _fromTokenizer(tokenizer) {
let buffer = Buffer.alloc(minimumBytes);
const bytesRead = 12;
const check = (header, options) => _check(buffer, header, options);
const checkString = (header, options) => check(stringToBytes(header), options);
if (!tokenizer.fileInfo.size) {
tokenizer.fileInfo.size = Number.MAX_SAFE_INTEGER;
}
await tokenizer.peekBuffer(buffer, { length: bytesRead, mayBeLess: true });
if (check([66, 77])) {
return {
ext: "bmp",
mime: "image/bmp"
};
}
if (check([11, 119])) {
return {
ext: "ac3",
mime: "audio/vnd.dolby.dd-raw"
};
}
if (check([120, 1])) {
return {
ext: "dmg",
mime: "application/x-apple-diskimage"
};
}
if (check([77, 90])) {
return {
ext: "exe",
mime: "application/x-msdownload"
};
}
if (check([37, 33])) {
await tokenizer.peekBuffer(buffer, { length: 24, mayBeLess: true });
if (checkString("PS-Adobe-", { offset: 2 }) && checkString(" EPSF-", { offset: 14 })) {
return {
ext: "eps",
mime: "application/eps"
};
}
return {
ext: "ps",
mime: "application/postscript"
};
}
if (check([31, 160]) || check([31, 157])) {
return {
ext: "Z",
mime: "application/x-compress"
};
}
if (check([255, 216, 255])) {
return {
ext: "jpg",
mime: "image/jpeg"
};
}
if (check([73, 73, 188])) {
return {
ext: "jxr",
mime: "image/vnd.ms-photo"
};
}
if (check([31, 139, 8])) {
return {
ext: "gz",
mime: "application/gzip"
};
}
if (check([66, 90, 104])) {
return {
ext: "bz2",
mime: "application/x-bzip2"
};
}
if (checkString("ID3")) {
await tokenizer.ignore(6);
const id3HeaderLen = await tokenizer.readToken(uint32SyncSafeToken);
if (tokenizer.position + id3HeaderLen > tokenizer.fileInfo.size) {
return {
ext: "mp3",
mime: "audio/mpeg"
};
}
await tokenizer.ignore(id3HeaderLen);
return fromTokenizer(tokenizer);
}
if (checkString("MP+")) {
return {
ext: "mpc",
mime: "audio/x-musepack"
};
}
if ((buffer[0] === 67 || buffer[0] === 70) && check([87, 83], { offset: 1 })) {
return {
ext: "swf",
mime: "application/x-shockwave-flash"
};
}
if (check([71, 73, 70])) {
return {
ext: "gif",
mime: "image/gif"
};
}
if (checkString("FLIF")) {
return {
ext: "flif",
mime: "image/flif"
};
}
if (checkString("8BPS")) {
return {
ext: "psd",
mime: "image/vnd.adobe.photoshop"
};
}
if (checkString("WEBP", { offset: 8 })) {
return {
ext: "webp",
mime: "image/webp"
};
}
if (checkString("MPCK")) {
return {
ext: "mpc",
mime: "audio/x-musepack"
};
}
if (checkString("FORM")) {
return {
ext: "aif",
mime: "audio/aiff"
};
}
if (checkString("icns", { offset: 0 })) {
return {
ext: "icns",
mime: "image/icns"
};
}
if (check([80, 75, 3, 4])) {
try {
while (tokenizer.position + 30 < tokenizer.fileInfo.size) {
await tokenizer.readBuffer(buffer, { length: 30 });
const zipHeader = {
compressedSize: buffer.readUInt32LE(18),
uncompressedSize: buffer.readUInt32LE(22),
filenameLength: buffer.readUInt16LE(26),
extraFieldLength: buffer.readUInt16LE(28)
};
zipHeader.filename = await tokenizer.readToken(new Token.StringType(zipHeader.filenameLength, "utf-8"));
await tokenizer.ignore(zipHeader.extraFieldLength);
if (zipHeader.filename === "META-INF/mozilla.rsa") {
return {
ext: "xpi",
mime: "application/x-xpinstall"
};
}
if (zipHeader.filename.endsWith(".rels") || zipHeader.filename.endsWith(".xml")) {
const type = zipHeader.filename.split("/")[0];
switch (type) {
case "_rels":
break;
case "word":
return {
ext: "docx",
mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
};
case "ppt":
return {
ext: "pptx",
mime: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
};
case "xl":
return {
ext: "xlsx",
mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
};
default:
break;
}
}
if (zipHeader.filename.startsWith("xl/")) {
return {
ext: "xlsx",
mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
};
}
if (zipHeader.filename.startsWith("3D/") && zipHeader.filename.endsWith(".model")) {
return {
ext: "3mf",
mime: "model/3mf"
};
}
if (zipHeader.filename === "mimetype" && zipHeader.compressedSize === zipHeader.uncompressedSize) {
const mimeType = await tokenizer.readToken(new Token.StringType(zipHeader.compressedSize, "utf-8"));
switch (mimeType) {
case "application/epub+zip":
return {
ext: "epub",
mime: "application/epub+zip"
};
case "application/vnd.oasis.opendocument.text":
return {
ext: "odt",
mime: "application/vnd.oasis.opendocument.text"
};
case "application/vnd.oasis.opendocument.spreadsheet":
return {
ext: "ods",
mime: "application/vnd.oasis.opendocument.spreadsheet"
};
case "application/vnd.oasis.opendocument.presentation":
return {
ext: "odp",
mime: "application/vnd.oasis.opendocument.presentation"
};
default:
}
}
if (zipHeader.compressedSize === 0) {
let nextHeaderIndex = -1;
while (nextHeaderIndex < 0 && tokenizer.position < tokenizer.fileInfo.size) {
await tokenizer.peekBuffer(buffer, { mayBeLess: true });
nextHeaderIndex = buffer.indexOf("504B0304", 0, "hex");
await tokenizer.ignore(nextHeaderIndex >= 0 ? nextHeaderIndex : buffer.length);
}
} else {
await tokenizer.ignore(zipHeader.compressedSize);
}
}
} catch (error) {
if (!(error instanceof strtok3.EndOfStreamError)) {
throw error;
}
}
return {
ext: "zip",
mime: "application/zip"
};
}
if (checkString("OggS")) {
await tokenizer.ignore(28);
const type = Buffer.alloc(8);
await tokenizer.readBuffer(type);
if (_check(type, [79, 112, 117, 115, 72, 101, 97, 100])) {
return {
ext: "opus",
mime: "audio/opus"
};
}
if (_check(type, [128, 116, 104, 101, 111, 114, 97])) {
return {
ext: "ogv",
mime: "video/ogg"
};
}
if (_check(type, [1, 118, 105, 100, 101, 111, 0])) {
return {
ext: "ogm",
mime: "video/ogg"
};
}
if (_check(type, [127, 70, 76, 65, 67])) {
return {
ext: "oga",
mime: "audio/ogg"
};
}
if (_check(type, [83, 112, 101, 101, 120, 32, 32])) {
return {
ext: "spx",
mime: "audio/ogg"
};
}
if (_check(type, [1, 118, 111, 114, 98, 105, 115])) {
return {
ext: "ogg",
mime: "audio/ogg"
};
}
return {
ext: "ogx",
mime: "application/ogg"
};
}
if (check([80, 75]) && (buffer[2] === 3 || buffer[2] === 5 || buffer[2] === 7) && (buffer[3] === 4 || buffer[3] === 6 || buffer[3] === 8)) {
return {
ext: "zip",
mime: "application/zip"
};
}
if (checkString("ftyp", { offset: 4 }) && (buffer[8] & 96) !== 0) {
const brandMajor = buffer.toString("binary", 8, 12).replace("\x00", " ").trim();
switch (brandMajor) {
case "avif":
return { ext: "avif", mime: "image/avif" };
case "mif1":
return { ext: "heic", mime: "image/heif" };
case "msf1":
return { ext: "heic", mime: "image/heif-sequence" };
case "heic":
case "heix":
return { ext: "heic", mime: "image/heic" };
case "hevc":
case "hevx":
return { ext: "heic", mime: "image/heic-sequence" };
case "qt":
return { ext: "mov", mime: "video/quicktime" };
case "M4V":
case "M4VH":
case "M4VP":
return { ext: "m4v", mime: "video/x-m4v" };
case "M4P":
return { ext: "m4p", mime: "video/mp4" };
case "M4B":
return { ext: "m4b", mime: "audio/mp4" };
case "M4A":
return { ext: "m4a", mime: "audio/x-m4a" };
case "F4V":
return { ext: "f4v", mime: "video/mp4" };
case "F4P":
return { ext: "f4p", mime: "video/mp4" };
case "F4A":
return { ext: "f4a", mime: "audio/mp4" };
case "F4B":
return { ext: "f4b", mime: "audio/mp4" };
case "crx":
return { ext: "cr3", mime: "image/x-canon-cr3" };
default:
if (brandMajor.startsWith("3g")) {
if (brandMajor.startsWith("3g2")) {
return { ext: "3g2", mime: "video/3gpp2" };
}
return { ext: "3gp", mime: "video/3gpp" };
}
return { ext: "mp4", mime: "video/mp4" };
}
}
if (checkString("MThd")) {
return {
ext: "mid",
mime: "audio/midi"
};
}
if (checkString("wOFF") && (check([0, 1, 0, 0], { offset: 4 }) || checkString("OTTO", { offset: 4 }))) {
return {
ext: "woff",
mime: "font/woff"
};
}
if (checkString("wOF2") && (check([0, 1, 0, 0], { offset: 4 }) || checkString("OTTO", { offset: 4 }))) {
return {
ext: "woff2",
mime: "font/woff2"
};
}
if (check([212, 195, 178, 161]) || check([161, 178, 195, 212])) {
return {
ext: "pcap",
mime: "application/vnd.tcpdump.pcap"
};
}
if (checkString("DSD ")) {
return {
ext: "dsf",
mime: "audio/x-dsf"
};
}
if (checkString("LZIP")) {
return {
ext: "lz",
mime: "application/x-lzip"
};
}
if (checkString("fLaC")) {
return {
ext: "flac",
mime: "audio/x-flac"
};
}
if (check([66, 80, 71, 251])) {
return {
ext: "bpg",
mime: "image/bpg"
};
}
if (checkString("wvpk")) {
return {
ext: "wv",
mime: "audio/wavpack"
};
}
if (checkString("%PDF")) {
await tokenizer.ignore(1350);
const maxBufferSize = 10 * 1024 * 1024;
const buffer2 = Buffer.alloc(Math.min(maxBufferSize, tokenizer.fileInfo.size));
await tokenizer.readBuffer(buffer2, { mayBeLess: true });
if (buffer2.includes(Buffer.from("AIPrivateData"))) {
return {
ext: "ai",
mime: "application/postscript"
};
}
return {
ext: "pdf",
mime: "application/pdf"
};
}
if (check([0, 97, 115, 109])) {
return {
ext: "wasm",
mime: "application/wasm"
};
}
if (check([73, 73, 42, 0])) {
if (checkString("CR", { offset: 8 })) {
return {
ext: "cr2",
mime: "image/x-canon-cr2"
};
}
if (check([28, 0, 254, 0], { offset: 8 }) || check([31, 0, 11, 0], { offset: 8 })) {
return {
ext: "nef",
mime: "image/x-nikon-nef"
};
}
if (check([8, 0, 0, 0], { offset: 4 }) && (check([45, 0, 254, 0], { offset: 8 }) || check([39, 0, 254, 0], { offset: 8 }))) {
return {
ext: "dng",
mime: "image/x-adobe-dng"
};
}
buffer = Buffer.alloc(24);
await tokenizer.peekBuffer(buffer);
if ((check([16, 251, 134, 1], { offset: 4 }) || check([8, 0, 0, 0], { offset: 4 })) && check([0, 254, 0, 4, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 1], { offset: 9 })) {
return {
ext: "arw",
mime: "image/x-sony-arw"
};
}
return {
ext: "tif",
mime: "image/tiff"
};
}
if (check([77, 77, 0, 42])) {
return {
ext: "tif",
mime: "image/tiff"
};
}
if (checkString("MAC ")) {
return {
ext: "ape",
mime: "audio/ape"
};
}
if (check([26, 69, 223, 163])) {
async function readField() {
const msb = await tokenizer.peekNumber(Token.UINT8);
let mask = 128;
let ic = 0;
while ((msb & mask) === 0 && mask !== 0) {
++ic;
mask >>= 1;
}
const id = Buffer.alloc(ic + 1);
await tokenizer.readBuffer(id);
return id;
}
async function readElement() {
const id = await readField();
const lenField = await readField();
lenField[0] ^= 128 >> lenField.length - 1;
const nrLen = Math.min(6, lenField.length);
return {
id: id.readUIntBE(0, id.length),
len: lenField.readUIntBE(lenField.length - nrLen, nrLen)
};
}
async function readChildren(level, children) {
while (children > 0) {
const e = await readElement();
if (e.id === 17026) {
return tokenizer.readToken(new Token.StringType(e.len, "utf-8"));
}
await tokenizer.ignore(e.len);
--children;
}
}
const re = await readElement();
const docType = await readChildren(1, re.len);
switch (docType) {
case "webm":
return {
ext: "webm",
mime: "video/webm"
};
case "matroska":
return {
ext: "mkv",
mime: "video/x-matroska"
};
default:
return;
}
}
if (check([82, 73, 70, 70])) {
if (check([65, 86, 73], { offset: 8 })) {
return {
ext: "avi",
mime: "video/vnd.avi"
};
}
if (check([87, 65, 86, 69], { offset: 8 })) {
return {
ext: "wav",
mime: "audio/vnd.wave"
};
}
if (check([81, 76, 67, 77], { offset: 8 })) {
return {
ext: "qcp",
mime: "audio/qcelp"
};
}
}
if (checkString("SQLi")) {
return {
ext: "sqlite",
mime: "application/x-sqlite3"
};
}
if (check([78, 69, 83, 26])) {
return {
ext: "nes",
mime: "application/x-nintendo-nes-rom"
};
}
if (checkString("Cr24")) {
return {
ext: "crx",
mime: "application/x-google-chrome-extension"
};
}
if (checkString("MSCF") || checkString("ISc(")) {
return {
ext: "cab",
mime: "application/vnd.ms-cab-compressed"
};
}
if (check([237, 171, 238, 219])) {
return {
ext: "rpm",
mime: "application/x-rpm"
};
}
if (check([197, 208, 211, 198])) {
return {
ext: "eps",
mime: "application/eps"
};
}
if (check([40, 181, 47, 253])) {
return {
ext: "zst",
mime: "application/zstd"
};
}
if (check([79, 84, 84, 79, 0])) {
return {
ext: "otf",
mime: "font/otf"
};
}
if (checkString("#!AMR")) {
return {
ext: "amr",
mime: "audio/amr"
};
}
if (checkString("{\\rtf")) {
return {
ext: "rtf",
mime: "application/rtf"
};
}
if (check([70, 76, 86, 1])) {
return {
ext: "flv",
mime: "video/x-flv"
};
}
if (checkString("IMPM")) {
return {
ext: "it",
mime: "audio/x-it"
};
}
if (checkString("-lh0-", { offset: 2 }) || checkString("-lh1-", { offset: 2 }) || checkString("-lh2-", { offset: 2 }) || checkString("-lh3-", { offset: 2 }) || checkString("-lh4-", { offset: 2 }) || checkString("-lh5-", { offset: 2 }) || checkString("-lh6-", { offset: 2 }) || checkString("-lh7-", { offset: 2 }) || checkString("-lzs-", { offset: 2 }) || checkString("-lz4-", { offset: 2 }) || checkString("-lz5-", { offset: 2 }) || checkString("-lhd-", { offset: 2 })) {
return {
ext: "lzh",
mime: "application/x-lzh-compressed"
};
}
if (check([0, 0, 1, 186])) {
if (check([33], { offset: 4, mask: [241] })) {
return {
ext: "mpg",
mime: "video/MP1S"
};
}
if (check([68], { offset: 4, mask: [196] })) {
return {
ext: "mpg",
mime: "video/MP2P"
};
}
}
if (checkString("ITSF")) {
return {
ext: "chm",
mime: "application/vnd.ms-htmlhelp"
};
}
if (check([253, 55, 122, 88, 90, 0])) {
return {
ext: "xz",
mime: "application/x-xz"
};
}
if (checkString("<?xml ")) {
return {
ext: "xml",
mime: "application/xml"
};
}
if (check([55, 122, 188, 175, 39, 28])) {
return {
ext: "7z",
mime: "application/x-7z-compressed"
};
}
if (check([82, 97, 114, 33, 26, 7]) && (buffer[6] === 0 || buffer[6] === 1)) {
return {
ext: "rar",
mime: "application/x-rar-compressed"
};
}
if (checkString("solid ")) {
return {
ext: "stl",
mime: "model/stl"
};
}
if (checkString("BLENDER")) {
return {
ext: "blend",
mime: "application/x-blender"
};
}
if (checkString("!<arch>")) {
await tokenizer.ignore(8);
const str = await tokenizer.readToken(new Token.StringType(13, "ascii"));
if (str === "debian-binary") {
return {
ext: "deb",
mime: "application/x-deb"
};
}
return {
ext: "ar",
mime: "application/x-unix-archive"
};
}
if (check([137, 80, 78, 71, 13, 10, 26, 10])) {
await tokenizer.ignore(8);
async function readChunkHeader() {
return {
length: await tokenizer.readToken(Token.INT32_BE),
type: await tokenizer.readToken(new Token.StringType(4, "binary"))
};
}
do {
const chunk = await readChunkHeader();
if (chunk.length < 0) {
return;
}
switch (chunk.type) {
case "IDAT":
return {
ext: "png",
mime: "image/png"
};
case "acTL":
return {
ext: "apng",
mime: "image/apng"
};
default:
await tokenizer.ignore(chunk.length + 4);
}
} while (tokenizer.position + 8 < tokenizer.fileInfo.size);
return {
ext: "png",
mime: "image/png"
};
}
if (check([65, 82, 82, 79, 87, 49, 0, 0])) {
return {
ext: "arrow",
mime: "application/x-apache-arrow"
};
}
if (check([103, 108, 84, 70, 2, 0, 0, 0])) {
return {
ext: "glb",
mime: "model/gltf-binary"
};
}
if (check([102, 114, 101, 101], { offset: 4 }) || check([109, 100, 97, 116], { offset: 4 }) || check([109, 111, 111, 118], { offset: 4 }) || check([119, 105, 100, 101], { offset: 4 })) {
return {
ext: "mov",
mime: "video/quicktime"
};
}
if (check([73, 73, 82, 79, 8, 0, 0, 0, 24])) {
return {
ext: "orf",
mime: "image/x-olympus-orf"
};
}
if (checkString("gimp xcf ")) {
return {
ext: "xcf",
mime: "image/x-xcf"
};
}
if (check([73, 73, 85, 0, 24, 0, 0, 0, 136, 231, 116, 216])) {
return {
ext: "rw2",
mime: "image/x-panasonic-rw2"
};
}
if (check([48, 38, 178, 117, 142, 102, 207, 17, 166, 217])) {
async function readHeader() {
const guid = Buffer.alloc(16);
await tokenizer.readBuffer(guid);
return {
id: guid,
size: Number(await tokenizer.readToken(Token.UINT64_LE))
};
}
await tokenizer.ignore(30);
while (tokenizer.position + 24 < tokenizer.fileInfo.size) {
const header = await readHeader();
let payload = header.size - 24;
if (_check(header.id, [145, 7, 220, 183, 183, 169, 207, 17, 142, 230, 0, 192, 12, 32, 83, 101])) {
const typeId = Buffer.alloc(16);
payload -= await tokenizer.readBuffer(typeId);
if (_check(typeId, [64, 158, 105, 248, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) {
return {
ext: "asf",
mime: "audio/x-ms-asf"
};
}
if (_check(typeId, [192, 239, 25, 188, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) {
return {
ext: "asf",
mime: "video/x-ms-asf"
};
}
break;
}
await tokenizer.ignore(payload);
}
return {
ext: "asf",
mime: "application/vnd.ms-asf"
};
}
if (check([171, 75, 84, 88, 32, 49, 49, 187, 13, 10, 26, 10])) {
return {
ext: "ktx",
mime: "image/ktx"
};
}
if ((check([126, 16, 4]) || check([126, 24, 4])) && check([48, 77, 73, 69], { offset: 4 })) {
return {
ext: "mie",
mime: "application/x-mie"
};
}
if (check([39, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], { offset: 2 })) {
return {
ext: "shp",
mime: "application/x-esri-shape"
};
}
if (check([0, 0, 0, 12, 106, 80, 32, 32, 13, 10, 135, 10])) {
await tokenizer.ignore(20);
const type = await tokenizer.readToken(new Token.StringType(4, "ascii"));
switch (type) {
case "jp2 ":
return {
ext: "jp2",
mime: "image/jp2"
};
case "jpx ":
return {
ext: "jpx",
mime: "image/jpx"
};
case "jpm ":
return {
ext: "jpm",
mime: "image/jpm"
};
case "mjp2":
return {
ext: "mj2",
mime: "image/mj2"
};
default:
return;
}
}
if (check([255, 10]) || check([0, 0, 0, 12, 74, 88, 76, 32, 13, 10, 135, 10])) {
return {
ext: "jxl",
mime: "image/jxl"
};
}
if (check([0, 0, 1, 186]) || check([0, 0, 1, 179])) {
return {
ext: "mpg",
mime: "video/mpeg"
};
}
if (check([0, 1, 0, 0, 0])) {
return {
ext: "ttf",
mime: "font/ttf"
};
}
if (check([0, 0, 1, 0])) {
return {
ext: "ico",
mime: "image/x-icon"
};
}
if (check([0, 0, 2, 0])) {
return {
ext: "cur",
mime: "image/x-icon"
};
}
if (check([208, 207, 17, 224, 161, 177, 26, 225])) {
return {
ext: "cfb",
mime: "application/x-cfb"
};
}
await tokenizer.peekBuffer(buffer, { length: Math.min(256, tokenizer.fileInfo.size), mayBeLess: true });
if (checkString("BEGIN:")) {
if (checkString("VCARD", { offset: 6 })) {
return {
ext: "vcf",
mime: "text/vcard"
};
}
if (checkString("VCALENDAR", { offset: 6 })) {
return {
ext: "ics",
mime: "text/calendar"
};
}
}
if (checkString("FUJIFILMCCD-RAW")) {
return {
ext: "raf",
mime: "image/x-fujifilm-raf"
};
}
if (checkString("Extended Module:")) {
return {
ext: "xm",
mime: "audio/x-xm"
};
}
if (checkString("Creative Voice File")) {
return {
ext: "voc",
mime: "audio/x-voc"
};
}
if (check([4, 0, 0, 0]) && buffer.length >= 16) {
const jsonSize = buffer.readUInt32LE(12);
if (jsonSize > 12 && buffer.length >= jsonSize + 16) {
try {
const header = buffer.slice(16, jsonSize + 16).toString();
const json = JSON.parse(header);
if (json.files) {
return {
ext: "asar",
mime: "application/x-asar"
};
}
} catch (_) {}
}
}
if (check([6, 14, 43, 52, 2, 5, 1, 1, 13, 1, 2, 1, 1, 2])) {
return {
ext: "mxf",
mime: "application/mxf"
};
}
if (checkString("SCRM", { offset: 44 })) {
return {
ext: "s3m",
mime: "audio/x-s3m"
};
}
if (check([71], { offset: 4 }) && (check([71], { offset: 192 }) || check([71], { offset: 196 }))) {
return {
ext: "mts",
mime: "video/mp2t"
};
}
if (check([66, 79, 79, 75, 77, 79, 66, 73], { offset: 60 })) {
return {
ext: "mobi",
mime: "application/x-mobipocket-ebook"
};
}
if (check([68, 73, 67, 77], { offset: 128 })) {
return {
ext: "dcm",
mime: "application/dicom"
};
}
if (check([76, 0, 0, 0, 1, 20, 2, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 70])) {
return {
ext: "lnk",
mime: "application/x.ms.shortcut"
};
}
if (check([98, 111, 111, 107, 0, 0, 0, 0, 109, 97, 114, 107, 0, 0, 0, 0])) {
return {
ext: "alias",
mime: "application/x.apple.alias"
};
}
if (check([76, 80], { offset: 34 }) && (check([0, 0, 1], { offset: 8 }) || check([1, 0, 2], { offset: 8 }) || check([2, 0, 2], { offset: 8 }))) {
return {
ext: "eot",
mime: "application/vnd.ms-fontobject"
};
}
if (check([6, 6, 237, 245, 216, 29, 70, 229, 189, 49, 239, 231, 254, 116, 183, 29])) {
return {
ext: "indd",
mime: "application/x-indesign"
};
}
await tokenizer.peekBuffer(buffer, { length: Math.min(512, tokenizer.fileInfo.size), mayBeLess: true });
if (tarHeaderChecksumMatches(buffer)) {
return {
ext: "tar",
mime: "application/x-tar"
};
}
if (check([255, 254, 255, 14, 83, 0, 107, 0, 101, 0, 116, 0, 99, 0, 104, 0, 85, 0, 112, 0, 32, 0, 77, 0, 111, 0, 100, 0, 101, 0, 108, 0])) {
return {
ext: "skp",
mime: "application/vnd.sketchup.skp"
};
}
if (checkString("-----BEGIN PGP MESSAGE-----")) {
return {
ext: "pgp",
mime: "application/pgp-encrypted"
};
}
if (buffer.length >= 2 && check([255, 224], { offset: 0, mask: [255, 224] })) {
if (check([16], { offset: 1, mask: [22] })) {
if (check([8], { offset: 1, mask: [8] })) {
return {
ext: "aac",
mime: "audio/aac"
};
}
return {
ext: "aac",
mime: "audio/aac"
};
}
if (check([2], { offset: 1, mask: [6] })) {
return {
ext: "mp3",
mime: "audio/mpeg"
};
}
if (check([4], { offset: 1, mask: [6] })) {
return {
ext: "mp2",
mime: "audio/mpeg"
};
}
if (check([6], { offset: 1, mask: [6] })) {
return {
ext: "mp1",
mime: "audio/mpeg"
};
}
}
}
var stream2 = (readableStream) => new Promise((resolve, reject) => {
const stream = eval("require")("stream");
readableStream.on("error", reject);
readableStream.once("readable", async () => {
const pass = new stream.PassThrough;
let outputStream;
if (stream.pipeline) {
outputStream = stream.pipeline(readableStream, pass, () => {});
} else {
outputStream = readableStream.pipe(pass);
}
const chunk = readableStream.read(minimumBytes) || readableStream.read() || Buffer.alloc(0);
try {
const fileType2 = await fromBuffer(chunk);
pass.fileType = fileType2;
} catch (error) {
reject(error);
}
resolve(outputStream);
});
});
var fileType = {
fromStream,
fromTokenizer,
fromBuffer,
stream: stream2
};
Object.defineProperty(fileType, "extensions", {
get() {
return new Set(supported.extensions);
}
});
Object.defineProperty(fileType, "mimeTypes", {
get() {
return new Set(supported.mimeTypes);
}
});
module.exports = fileType;
});
// ../../node_modules/.bun/mime@3.0.0/node_modules/mime/Mime.js
var require_Mime = __commonJS((exports, module) => {
function Mime() {
this._types = Object.create(null);
this._extensions = Object.create(null);
for (let i = 0;i < arguments.length; i++) {
this.define(arguments[i]);
}
this.define = this.define.bind(this);
this.getType = this.getType.bind(this);
this.getExtension = this.getExtension.bind(this);
}
Mime.prototype.define = function(typeMap, force) {
for (let type in typeMap) {
let extensions = typeMap[type].map(function(t) {
return t.toLowerCase();
});
type = type.toLowerCase();
for (let i = 0;i < extensions.length; i++) {
const ext = extensions[i];
if (ext[0] === "*") {
continue;
}
if (!force && ext in this._types) {
throw new Error('Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type + '".');
}
this._types[ext] = type;
}
if (force || !this._extensions[type]) {
const ext = extensions[0];
this._extensions[type] = ext[0] !== "*" ? ext : ext.substr(1);
}
}
};
Mime.prototype.getType = function(path) {
path = String(path);
let last = path.replace(/^.*[/\\]/, "").toLowerCase();
let ext = last.replace(/^.*\./, "").toLowerCase();
let hasPath = last.length < path.length;
let hasDot = ext.length < last.length - 1;
return (hasDot || !hasPath) && this._types[ext] || null;
};
Mime.prototype.getExtension = function(type) {
type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
return type && this._extensions[type.toLowerCase()] || null;
};
module.exports = Mime;
});
// ../../node_modules/.bun/mime@3.0.0/node_modules/mime/types/standard.js
var require_standard = __commonJS((exports, module) => {
module.exports = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomdeleted+xml": ["atomdeleted"], "application/atomsvc+xml": ["atomsvc"], "application/atsc-dwd+xml": ["dwd"], "application/atsc-held+xml": ["held"], "application/atsc-rsat+xml": ["rsat"], "application/bdoc": ["bdoc"], "application/calendar+xml": ["xcs"], "application/ccxml+xml": ["ccxml"], "application/cdfx+xml": ["cdfx"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["es", "ecma"], "application/emma+xml": ["emma"], "application/emotionml+xml": ["emotionml"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/express": ["exp"], "application/fdt+xml": ["fdt"], "application/font-tdpfr": ["pfr"], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hjson": ["hjson"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/its+xml": ["its"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lgr+xml": ["lgr"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mmt-aei+xml": ["maei"], "application/mmt-usd+xml": ["musd"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/n-quads": ["nq"], "application/n-triples": ["nt"], "application/node": ["cjs"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/p2p-overlay+xml": ["relo"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/provenance+xml": ["provx"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf", "owl"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/route-apd+xml": ["rapd"], "application/route-s-tsid+xml": ["sls"], "application/route-usd+xml": ["rusd"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/senml+xml": ["senmlx"], "application/sensml+xml": ["sensmlx"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/sieve": ["siv", "sieve"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/swid+xml": ["swidtag"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/toml": ["toml"], "application/trig": ["trig"], "application/ttml+xml": ["ttml"], "application/ubjson": ["ubj"], "application/urc-ressheet+xml": ["rsheet"], "application/urc-targetdesc+xml": ["td"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/xaml+xml": ["xaml"], "application/xcap-att+xml": ["xav"], "application/xcap-caps+xml": ["xca"], "application/xcap-diff+xml": ["xdf"], "application/xcap-el+xml": ["xel"], "application/xcap-ns+xml": ["xns"], "application/xenc+xml": ["xenc"], "application/xhtml+xml": ["xhtml", "xht"], "application/xliff+xml": ["xlf"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["*xsl", "xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": ["*3gpp"], "audio/adpcm": ["adp"], "audio/amr": ["amr"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mobile-xmf": ["mxmf"], "audio/mp3": ["*mp3"], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx", "opus"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/wav": ["wav"], "audio/wave": ["*wav"], "audio/webm": ["weba"], "audio/xm": ["xm"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/aces": ["exr"], "image/apng": ["apng"], "image/avif": ["avif"], "image/bmp": ["bmp"], "image/cgm": ["cgm"], "image/dicom-rle": ["drle"], "image/emf": ["emf"], "image/fits": ["fits"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/heic": ["heic"], "image/heic-sequence": ["heics"], "image/heif": ["heif"], "image/heif-sequence": ["heifs"], "image/hej2k": ["hej2"], "image/hsj2": ["hsj2"], "image/ief": ["ief"], "image/jls": ["jls"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jph": ["jph"], "image/jphc": ["jhc"], "image/jpm": ["jpm"], "image/jpx": ["jpx", "jpf"], "image/jxr": ["jxr"], "image/jxra": ["jxra"], "image/jxrs": ["jxrs"], "image/jxs": ["jxs"], "image/jxsc": ["jxsc"], "image/jxsi": ["jxsi"], "image/jxss": ["jxss"], "image/ktx": ["ktx"], "image/ktx2": ["ktx2"], "image/png": ["png"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/t38": ["t38"], "image/tiff": ["tif", "tiff"], "image/tiff-fx": ["tfx"], "image/webp": ["webp"], "image/wmf": ["wmf"], "message/disposition-notification": ["disposition-notification"], "message/global": ["u8msg"], "message/global-delivery-status": ["u8dsn"], "message/global-disposition-notification": ["u8mdn"], "message/global-headers": ["u8hdr"], "message/rfc822": ["eml", "mime"], "model/3mf": ["3mf"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/mesh": ["msh", "mesh", "silo"], "model/mtl": ["mtl"], "model/obj": ["obj"], "model/step+xml": ["stpx"], "model/step+zip": ["stpz"], "model/step-xml+zip": ["stpxz"], "model/stl": ["stl"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["*x3db", "x3dbz"], "model/x3d+fastinfoset": ["x3db"], "model/x3d+vrml": ["*x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "model/x3d-vrml": ["x3dv"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["markdown", "md"], "text/mathml": ["mml"], "text/mdx": ["mdx"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/richtext": ["rtx"], "text/rtf": ["*rtf"], "text/sgml": ["sgml", "sgm"], "text/shex": ["shex"], "text/slim": ["slim", "slm"], "text/spdx": ["spdx"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vtt": ["vtt"], "text/xml": ["*xml"], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/iso.segment": ["m4s"], "video/jpeg": ["jpgv"], "video/jpm": ["*jpm", "jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/webm": ["webm"] };
});
// ../../node_modules/.bun/mime@3.0.0/node_modules/mime/lite.js
var require_lite = __commonJS((exports, module) => {
var Mime = require_Mime();
module.exports = new Mime(require_standard());
});
// ../../node_modules/.bun/exif-parser@0.1.12/node_modules/exif-parser/lib/jpeg.js
var require_jpeg = __commonJS((exports, module) => {
module.exports = {
parseSections: function(stream2, iterator) {
var len, markerType;
stream2.setBigEndian(true);
while (stream2.remainingLength() > 0 && markerType !== 218) {
if (stream2.nextUInt8() !== 255) {
throw new Error("Invalid JPEG section offset");
}
markerType = stream2.nextUInt8();
if (markerType >= 208 && markerType <= 217 || markerType === 218) {
len = 0;
} else {
len = stream2.nextUInt16() - 2;
}
iterator(markerType, stream2.branch(0, len));
stream2.skip(len);
}
},
getSizeFromSOFSection: function(stream2) {
stream2.skip(1);
return {
height: stream2.nextUInt16(),
width: stream2.nextUInt16()
};
},
getSectionName: function(markerType) {
var name, index;
switch (markerType) {
case 216:
name = "SOI";
break;
case 196:
name = "DHT";
break;
case 219:
name = "DQT";
break;
case 221:
name = "DRI";
break;
case 218:
name = "SOS";
break;
case 254:
name = "COM";
break;
case 217:
name = "EOI";
break;
default:
if (markerType >= 224 && markerType <= 239) {
name = "APP";
index = markerType - 224;
} else if (markerType >= 192 && markerType <= 207 && markerType !== 196 && markerType !== 200 && markerType !== 204) {
name = "SOF";
index = markerType - 192;
} else if (markerType >= 208 && markerType <= 215) {
name = "RST";
index = markerType - 208;
}
break;
}
var nameStruct = {
name
};
if (typeof index === "number") {
nameStruct.index = index;
}
return nameStruct;
}
};
});
// ../../node_modules/.bun/exif-parser@0.1.12/node_modules/exif-parser/lib/exif.js
var require_exif = __commonJS((exports, module) => {
function readExifValue(format, stream2) {
switch (format) {
case 1:
return stream2.nextUInt8();
case 3:
return stream2.nextUInt16();
case 4:
return stream2.nextUInt32();
case 5:
return [stream2.nextUInt32(), stream2.nextUInt32()];
case 6:
return stream2.nextInt8();
case 8:
return stream2.nextUInt16();
case 9:
return stream2.nextUInt32();
case 10:
return [stream2.nextInt32(), stream2.nextInt32()];
case 11:
return stream2.nextFloat();
case 12:
return stream2.nextDouble();
default:
throw new Error("Invalid format while decoding: " + format);
}
}
function getBytesPerComponent(format) {
switch (format) {
case 1:
case 2:
case 6:
case 7:
return 1;
case 3:
case 8:
return 2;
case 4:
case 9:
case 11:
return 4;
case 5:
case 10:
case 12:
return 8;
default:
return 0;
}
}
function readExifTag(tiffMarker, stream2) {
var tagType = stream2.nextUInt16(), format = stream2.nextUInt16(), bytesPerComponent = getBytesPerComponent(format), components = stream2.nextUInt32(), valueBytes = bytesPerComponent * components, values, value, c;
if (valueBytes > 4) {
stream2 = tiffMarker.openWithOffset(stream2.nextUInt32());
}
if (format === 2) {
values = stream2.nextString(components);
var lastNull = values.indexOf("\x00");
if (lastNull !== -1) {
values = values.substr(0, lastNull);
}
} else if (format === 7) {
values = stream2.nextBuffer(components);
} else if (format !== 0) {
values = [];
for (c = 0;c < components; ++c) {
values.push(readExifValue(format, stream2));
}
}
if (valueBytes < 4) {
stream2.skip(4 - valueBytes);
}
return [tagType, values, format];
}
function readIFDSection(tiffMarker, stream2, iterator) {
var numberOfEntries = stream2.nextUInt16(), tag, i;
for (i = 0;i < numberOfEntries; ++i) {
tag = readExifTag(tiffMarker, stream2);
iterator(tag[0], tag[1], tag[2]);
}
}
function readHeader(stream2) {
var exifHeader = stream2.nextString(6);
if (exifHeader !== "Exif\x00\x00") {
throw new Error("Invalid EXIF header");
}
var tiffMarker = stream2.mark();
var tiffHeader = stream2.nextUInt16();
if (tiffHeader === 18761) {
stream2.setBigEndian(false);
} else if (tiffHeader === 19789) {
stream2.setBigEndian(true);
} else {
throw new Error("Invalid TIFF header");
}
if (stream2.nextUInt16() !== 42) {
throw new Error("Invalid TIFF data");
}
return tiffMarker;
}
module.exports = {
IFD0: 1,
IFD1: 2,
GPSIFD: 3,
SubIFD: 4,
InteropIFD: 5,
parseTags: function(stream2, iterator) {
var tiffMarker;
try {
tiffMarker = readHeader(stream2);
} catch (e) {
return false;
}
var subIfdOffset, gpsOffset, interopOffset;
var ifd0Stream = tiffMarker.openWithOffset(stream2.nextUInt32()), IFD0 = this.IFD0;
readIFDSection(tiffMarker, ifd0Stream, function(tagType, value, format) {
switch (tagType) {
case 34853:
gpsOffset = value[0];
break;
case 34665:
subIfdOffset = value[0];
break;
default:
iterator(IFD0, tagType, value, format);
break;
}
});
var ifd1Offset = ifd0Stream.nextUInt32();
if (ifd1Offset !== 0) {
var ifd1Stream = tiffMarker.openWithOffset(ifd1Offset);
readIFDSection(tiffMarker, ifd1Stream, iterator.bind(null, this.IFD1));
}
if (gpsOffset) {
var gpsStream = tiffMarker.openWithOffset(gpsOffset);
readIFDSection(tiffMarker, gpsStream, iterator.bind(null, this.GPSIFD));
}
if (subIfdOffset) {
var subIfdStream = tiffMarker.openWithOffset(subIfdOffset), InteropIFD = this.InteropIFD;
readIFDSection(tiffMarker, subIfdStream, function(tagType, value, format) {
if (tagType === 40965) {
interopOffset = value[0];
} else {
iterator(InteropIFD, tagType, value, format);
}
});
}
if (interopOffset) {
var interopStream = tiffMarker.openWithOffset(interopOffset);
readIFDSection(tiffMarker, interopStream, iterator.bind(null, this.InteropIFD));
}
return true;
}
};
});
// ../../node_modules/.bun/exif-parser@0.1.12/node_modules/exif-parser/lib/date.js
var require_date = __commonJS((exports, module) => {
function parseNumber(s) {
return parseInt(s, 10);
}
var hours = 3600;
var minutes = 60;
function parseDateTimeParts(dateParts, timeParts) {
dateParts = dateParts.map(parseNumber);
timeParts = timeParts.map(parseNumber);
var year = dateParts[0];
var month = dateParts[1] - 1;
var day = dateParts[2];
var hours2 = timeParts[0];
var minutes2 = timeParts[1];
var seconds = timeParts[2];
var date = Date.UTC(year, month, day, hours2, minutes2, seconds, 0);
var timestamp = date / 1000;
return timestamp;
}
function parseDateWithTimezoneFormat(dateTimeStr) {
var dateParts = dateTimeStr.substr(0, 10).split("-");
var timeParts = dateTimeStr.substr(11, 8).split(":");
var timezoneStr = dateTimeStr.substr(19, 6);
var timezoneParts = timezoneStr.split(":").map(parseNumber);
var timezoneOffset = timezoneParts[0] * hours + timezoneParts[1] * minutes;
var timestamp = parseDateTimeParts(dateParts, timeParts);
timestamp -= timezoneOffset;
if (typeof timestamp === "number" && !isNaN(timestamp)) {
return timestamp;
}
}
function parseDateWithSpecFormat(dateTimeStr) {
var parts = dateTimeStr.split(" "), dateParts = parts[0].split(":"), timeParts = parts[1].split(":");
var timestamp = parseDateTimeParts(dateParts, timeParts);
if (typeof timestamp === "number" && !isNaN(timestamp)) {
return timestamp;
}
}
function parseExifDate(dateTimeStr) {
var isSpecFormat = dateTimeStr.length === 19 && dateTimeStr.charAt(4) === ":";
var isTimezoneFormat = dateTimeStr.length === 25 && dateTimeStr.charAt(10) === "T";
var timestamp;
if (isTimezoneFormat) {
return parseDateWithTimezoneFormat(dateTimeStr);
} else if (isSpecFormat) {
return parseDateWithSpecFormat(dateTimeStr);
}
}
module.exports = {
parseDateWithSpecFormat,
parseDateWithTimezoneFormat,
parseExifDate
};
});
// ../../node_modules/.bun/exif-parser@0.1.12/node_modules/exif-parser/lib/simplify.js
var require_simplify = __commonJS((exports, module) => {
var exif = require_exif();
var date = require_date();
var degreeTags = [
{
section: exif.GPSIFD,
type: 2,
name: "GPSLatitude",
refType: 1,
refName: "GPSLatitudeRef",
posVal: "N"
},
{
section: exif.GPSIFD,
type: 4,
name: "GPSLongitude",
refType: 3,
refName: "GPSLongitudeRef",
posVal: "E"
}
];
var dateTags = [
{
section: exif.SubIFD,
type: 306,
name: "ModifyDate"
},
{
section: exif.SubIFD,
type: 36867,
name: "DateTimeOriginal"
},
{
section: exif.SubIFD,
type: 36868,
name: "CreateDate"
},
{
section: exif.SubIFD,
type: 306,
name: "ModifyDate"
}
];
module.exports = {
castDegreeValues: function(getTagValue, setTagValue) {
degreeTags.forEach(function(t) {
var degreeVal = getTagValue(t);
if (degreeVal) {
var degreeRef = getTagValue({ section: t.section, type: t.refType, name: t.refName });
var degreeNumRef = degreeRef === t.posVal ? 1 : -1;
var degree = (degreeVal[0] + degreeVal[1] / 60 + degreeVal[2] / 3600) * degreeNumRef;
setTagValue(t, degree);
}
});
},
castDateValues: function(getTagValue, setTagValue) {
dateTags.forEach(function(t) {
var dateStrVal = getTagValue(t);
if (dateStrVal) {
var timestamp = date.parseExifDate(dateStrVal);
if (typeof timestamp !== "undefined") {
setTagValue(t, timestamp);
}
}
});
},
simplifyValue: function(values, format) {
if (Array.isArray(values)) {
values = values.map(function(value) {
if (format === 10 || format === 5) {
return value[0] / value[1];
}
return value;
});
if (values.length === 1) {
values = values[0];
}
}
return values;
}
};
});
// ../../node_modules/.bun/exif-parser@0.1.12/node_modules/exif-parser/lib/exif-tags.js
var require_exif_tags = __commonJS((exports, module) => {
module.exports = {
exif: {
1: "InteropIndex",
2: "InteropVersion",
11: "ProcessingSoftware",
254: "SubfileType",
255: "OldSubfileType",
256: "ImageWidth",
257: "ImageHeight",
258: "BitsPerSample",
259: "Compression",
262: "PhotometricInterpretation",
263: "Thresholding",
264: "CellWidth",
265: "CellLength",
266: "FillOrder",
269: "DocumentName",
270: "ImageDescription",
271: "Make",
272: "Model",
273: "StripOffsets",
274: "Orientation",
277: "SamplesPerPixel",
278: "RowsPerStrip",
279: "StripByteCounts",
280: "MinSampleValue",
281: "MaxSampleValue",
282: "XResolution",
283: "YResolution",
284: "PlanarConfiguration",
285: "PageName",
286: "XPosition",
287: "YPosition",
288: "FreeOffsets",
289: "FreeByteCounts",
290: "GrayResponseUnit",
291: "GrayResponseCurve",
292: "T4Options",
293: "T6Options",
296: "ResolutionUnit",
297: "PageNumber",
300: "ColorResponseUnit",
301: "TransferFunction",
305: "Software",
306: "ModifyDate",
315: "Artist",
316: "HostComputer",
317: "Predictor",
318: "WhitePoint",
319: "PrimaryChromaticities",
320: "ColorMap",
321: "HalftoneHints",
322: "TileWidth",
323: "TileLength",
324: "TileOffsets",
325: "TileByteCounts",
326: "BadFaxLines",
327: "CleanFaxData",
328: "ConsecutiveBadFaxLines",
330: "SubIFD",
332: "InkSet",
333: "InkNames",
334: "NumberofInks",
336: "DotRange",
337: "TargetPrinter",
338: "ExtraSamples",
339: "SampleFormat",
340: "SMinSampleValue",
341: "SMaxSampleValue",
342: "TransferRange",
343: "ClipPath",
344: "XClipPathUnits",
345: "YClipPathUnits",
346: "Indexed",
347: "JPEGTables",
351: "OPIProxy",
400: "GlobalParametersIFD",
401: "ProfileType",
402: "FaxProfile",
403: "CodingMethods",
404: "VersionYear",
405: "ModeNumber",
433: "Decode",
434: "DefaultImageColor",
435: "T82Options",
437: "JPEGTables",
512: "JPEGProc",
513: "ThumbnailOffset",
514: "ThumbnailLength",
515: "JPEGRestartInterval",
517: "JPEGLosslessPredictors",
518: "JPEGPointTransforms",
519: "JPEGQTables",
520: "JPEGDCTables",
521: "JPEGACTables",
529: "YCbCrCoefficients",
530: "YCbCrSubSampling",
531: "YCbCrPositioning",
532: "ReferenceBlackWhite",
559: "StripRowCounts",
700: "ApplicationNotes",
999: "USPTOMiscellaneous",
4096: "RelatedImageFileFormat",
4097: "RelatedImageWidth",
4098: "RelatedImageHeight",
18246: "Rating",
18247: "XP_DIP_XML",
18248: "StitchInfo",
18249: "RatingPercent",
32781: "ImageID",
32931: "WangTag1",
32932: "WangAnnotation",
32933: "WangTag3",
32934: "WangTag4",
32995: "Matteing",
32996: "DataType",
32997: "ImageDepth",
32998: "TileDepth",
33405: "Model2",
33421: "CFARepeatPatternDim",
33422: "CFAPattern2",
33423: "BatteryLevel",
33424: "KodakIFD",
33432: "Copyright",
33434: "ExposureTime",
33437: "FNumber",
33445: "MDFileTag",
33446: "MDScalePixel",
33447: "MDColorTable",
33448: "MDLabName",
33449: "MDSampleInfo",
33450: "MDPrepDate",
33451: "MDPrepTime",
33452: "MDFileUnits",
33550: "PixelScale",
33589: "AdventScale",
33590: "AdventRevision",
33628: "UIC1Tag",
33629: "UIC2Tag",
33630: "UIC3Tag",
33631: "UIC4Tag",
33723: "IPTC-NAA",
33918: "IntergraphPacketData",
33919: "IntergraphFlagRegisters",
33920: "IntergraphMatrix",
33921: "INGRReserved",
33922: "ModelTiePoint",
34016: "Site",
34017: "ColorSequence",
34018: "IT8Header",
34019: "RasterPadding",
34020: "BitsPerRunLength",
34021: "BitsPerExtendedRunLength",
34022: "ColorTable",
34023: "ImageColorIndicator",
34024: "BackgroundColorIndicator",
34025: "ImageColorValue",
34026: "BackgroundColorValue",
34027: "PixelIntensityRange",
34028: "TransparencyIndicator",
34029: "ColorCharacterization",
34030: "HCUsage",
34031: "TrapIndicator",
34032: "CMYKEquivalent",
34118: "SEMInfo",
34152: "AFCP_IPTC",
34232: "PixelMagicJBIGOptions",
34264: "ModelTransform",
34306: "WB_GRGBLevels",
34310: "LeafData",
34377: "PhotoshopSettings",
34665: "ExifOffset",
34675: "ICC_Profile",
34687: "TIFF_FXExtensions",
34688: "MultiProfiles",
34689: "SharedData",
34690: "T88Options",
34732: "ImageLayer",
34735: "GeoTiffDirectory",
34736: "GeoTiffDoubleParams",
34737: "GeoTiffAsciiParams",
34850: "ExposureProgram",
34852: "SpectralSensitivity",
34853: "GPSInfo",
34855: "ISO",
34856: "Opto-ElectricConvFactor",
34857: "Interlace",
34858: "TimeZoneOffset",
34859: "SelfTimerMode",
34864: "SensitivityType",
34865: "StandardOutputSensitivity",
34866: "RecommendedExposureIndex",
34867: "ISOSpeed",
34868: "ISOSpeedLatitudeyyy",
34869: "ISOSpeedLatitudezzz",
34908: "FaxRecvParams",
34909: "FaxSubAddress",
34910: "FaxRecvTime",
34954: "LeafSubIFD",
36864: "ExifVersion",
36867: "DateTimeOriginal",
36868: "CreateDate",
37121: "ComponentsConfiguration",
37122: "CompressedBitsPerPixel",
37377: "ShutterSpeedValue",
37378: "ApertureValue",
37379: "BrightnessValue",
37380: "ExposureCompensation",
37381: "MaxApertureValue",
37382: "SubjectDistance",
37383: "MeteringMode",
37384: "LightSource",
37385: "Flash",
37386: "FocalLength",
37387: "FlashEnergy",
37388: "SpatialFrequencyResponse",
37389: "Noise",
37390: "FocalPlaneXResolution",
37391: "FocalPlaneYResolution",
37392: "FocalPlaneResolutionUnit",
37393: "ImageNumber",
37394: "SecurityClassification",
37395: "ImageHistory",
37396: "SubjectArea",
37397: "ExposureIndex",
37398: "TIFF-EPStandardID",
37399: "SensingMethod",
37434: "CIP3DataFile",
37435: "CIP3Sheet",
37436: "CIP3Side",
37439: "StoNits",
37500: "MakerNote",
37510: "UserComment",
37520: "SubSecTime",
37521: "SubSecTimeOriginal",
37522: "SubSecTimeDigitized",
37679: "MSDocumentText",
37680: "MSPropertySetStorage",
37681: "MSDocumentTextPosition",
37724: "ImageSourceData",
40091: "XPTitle",
40092: "XPComment",
40093: "XPAuthor",
40094: "XPKeywords",
40095: "XPSubject",
40960: "FlashpixVersion",
40961: "ColorSpace",
40962: "ExifImageWidth",
40963: "ExifImageHeight",
40964: "RelatedSoundFile",
40965: "InteropOffset",
41483: "FlashEnergy",
41484: "SpatialFrequencyResponse",
41485: "Noise",
41486: "FocalPlaneXResolution",
41487: "FocalPlaneYResolution",
41488: "FocalPlaneResolutionUnit",
41489: "ImageNumber",
41490: "SecurityClassification",
41491: "ImageHistory",
41492: "SubjectLocation",
41493: "ExposureIndex",
41494: "TIFF-EPStandardID",
41495: "SensingMethod",
41728: "FileSource",
41729: "SceneType",
41730: "CFAPattern",
41985: "CustomRendered",
41986: "ExposureMode",
41987: "WhiteBalance",
41988: "DigitalZoomRatio",
41989: "FocalLengthIn35mmFormat",
41990: "SceneCaptureType",
41991: "GainControl",
41992: "Contrast",
41993: "Saturation",
41994: "Sharpness",
41995: "DeviceSettingDescription",
41996: "SubjectDistanceRange",
42016: "ImageUniqueID",
42032: "OwnerName",
42033: "SerialNumber",
42034: "LensInfo",
42035: "LensMake",
42036: "LensModel",
42037: "LensSerialNumber",
42112: "GDALMetadata",
42113: "GDALNoData",
42240: "Gamma",
44992: "ExpandSoftware",
44993: "ExpandLens",
44994: "ExpandFilm",
44995: "ExpandFilterLens",
44996: "ExpandScanner",
44997: "ExpandFlashLamp",
48129: "PixelFormat",
48130: "Transformation",
48131: "Uncompressed",
48132: "ImageType",
48256: "ImageWidth",
48257: "ImageHeight",
48258: "WidthResolution",
48259: "HeightResolution",
48320: "ImageOffset",
48321: "ImageByteCount",
48322: "AlphaOffset",
48323: "AlphaByteCount",
48324: "ImageDataDiscard",
48325: "AlphaDataDiscard",
50215: "OceScanjobDesc",
50216: "OceApplicationSelector",
50217: "OceIDNumber",
50218: "OceImageLogic",
50255: "Annotations",
50341: "PrintIM",
50560: "USPTOOriginalContentType",
50706: "DNGVersion",
50707: "DNGBackwardVersion",
50708: "UniqueCameraModel",
50709: "LocalizedCameraModel",
50710: "CFAPlaneColor",
50711: "CFALayout",
50712: "LinearizationTable",
50713: "BlackLevelRepeatDim",
50714: "BlackLevel",
50715: "BlackLevelDeltaH",
50716: "BlackLevelDeltaV",
50717: "WhiteLevel",
50718: "DefaultScale",
50719: "DefaultCropOrigin",
50720: "DefaultCropSize",
50721: "ColorMatrix1",
50722: "ColorMatrix2",
50723: "CameraCalibration1",
50724: "CameraCalibration2",
50725: "ReductionMatrix1",
50726: "ReductionMatrix2",
50727: "AnalogBalance",
50728: "AsShotNeutral",
50729: "AsShotWhiteXY",
50730: "BaselineExposure",
50731: "BaselineNoise",
50732: "BaselineSharpness",
50733: "BayerGreenSplit",
50734: "LinearResponseLimit",
50735: "CameraSerialNumber",
50736: "DNGLensInfo",
50737: "ChromaBlurRadius",
50738: "AntiAliasStrength",
50739: "ShadowScale",
50740: "DNGPrivateData",
50741: "MakerNoteSafety",
50752: "RawImageSegmentation",
50778: "CalibrationIlluminant1",
50779: "CalibrationIlluminant2",
50780: "BestQualityScale",
50781: "RawDataUniqueID",
50784: "AliasLayerMetadata",
50827: "OriginalRawFileName",
50828: "OriginalRawFileData",
50829: "ActiveArea",
50830: "MaskedAreas",
50831: "AsShotICCProfile",
50832: "AsShotPreProfileMatrix",
50833: "CurrentICCProfile",
50834: "CurrentPreProfileMatrix",
50879: "ColorimetricReference",
50898: "PanasonicTitle",
50899: "PanasonicTitle2",
50931: "CameraCalibrationSig",
50932: "ProfileCalibrationSig",
50933: "ProfileIFD",
50934: "AsShotProfileName",
50935: "NoiseReductionApplied",
50936: "ProfileName",
50937: "ProfileHueSatMapDims",
50938: "ProfileHueSatMapData1",
50939: "ProfileHueSatMapData2",
50940: "ProfileToneCurve",
50941: "ProfileEmbedPolicy",
50942: "ProfileCopyright",
50964: "ForwardMatrix1",
50965: "ForwardMatrix2",
50966: "PreviewApplicationName",
50967: "PreviewApplicationVersion",
50968: "PreviewSettingsName",
50969: "PreviewSettingsDigest",
50970: "PreviewColorSpace",
50971: "PreviewDateTime",
50972: "RawImageDigest",
50973: "OriginalRawFileDigest",
50974: "SubTileBlockSize",
50975: "RowInterleaveFactor",
50981: "ProfileLookTableDims",
50982: "ProfileLookTableData",
51008: "OpcodeList1",
51009: "OpcodeList2",
51022: "OpcodeList3",
51041: "NoiseProfile",
51043: "TimeCodes",
51044: "FrameRate",
51058: "TStop",
51081: "ReelName",
51089: "OriginalDefaultFinalSize",
51090: "OriginalBestQualitySize",
51091: "OriginalDefaultCropSize",
51105: "CameraLabel",
51107: "ProfileHueSatMapEncoding",
51108: "ProfileLookTableEncoding",
51109: "BaselineExposureOffset",
51110: "DefaultBlackRender",
51111: "NewRawImageDigest",
51112: "RawToPreviewGain",
51125: "DefaultUserCrop",
59932: "Padding",
59933: "OffsetSchema",
65000: "OwnerName",
65001: "SerialNumber",
65002: "Lens",
65024: "KDC_IFD",
65100: "RawFile",
65101: "Converter",
65102: "WhiteBalance",
65105: "Exposure",
65106: "Shadows",
65107: "Brightness",
65108: "Contrast",
65109: "Saturation",
65110: "Sharpness",
65111: "Smoothness",
65112: "MoireFilter"
},
gps: {
0: "GPSVersionID",
1: "GPSLatitudeRef",
2: "GPSLatitude",
3: "GPSLongitudeRef",
4: "GPSLongitude",
5: "GPSAltitudeRef",
6: "GPSAltitude",
7: "GPSTimeStamp",
8: "GPSSatellites",
9: "GPSStatus",
10: "GPSMeasureMode",
11: "GPSDOP",
12: "GPSSpeedRef",
13: "GPSSpeed",
14: "GPSTrackRef",
15: "GPSTrack",
16: "GPSImgDirectionRef",
17: "GPSImgDirection",
18: "GPSMapDatum",
19: "GPSDestLatitudeRef",
20: "GPSDestLatitude",
21: "GPSDestLongitudeRef",
22: "GPSDestLongitude",
23: "GPSDestBearingRef",
24: "GPSDestBearing",
25: "GPSDestDistanceRef",
26: "GPSDestDistance",
27: "GPSProcessingMethod",
28: "GPSAreaInformation",
29: "GPSDateStamp",
30: "GPSDifferential",
31: "GPSHPositioningError"
}
};
});
// ../../node_modules/.bun/exif-parser@0.1.12/node_modules/exif-parser/lib/parser.js
var require_parser2 = __commonJS((exports, module) => {
var jpeg2 = require_jpeg();
var exif = require_exif();
var simplify = require_simplify();
function ExifResult(startMarker, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset) {
this.startMarker = startMarker;
this.tags = tags;
this.imageSize = imageSize;
this.thumbnailOffset = thumbnailOffset;
this.thumbnailLength = thumbnailLength;
this.thumbnailType = thumbnailType;
this.app1Offset = app1Offset;
}
ExifResult.prototype = {
hasThumbnail: function(mime) {
if (!this.thumbnailOffset || !this.thumbnailLength) {
return false;
}
if (typeof mime !== "string") {
return true;
}
if (mime.toLowerCase().trim() === "image/jpeg") {
return this.thumbnailType === 6;
}
if (mime.toLowerCase().trim() === "image/tiff") {
return this.thumbnailType === 1;
}
return false;
},
getThumbnailOffset: function() {
return this.app1Offset + 6 + this.thumbnailOffset;
},
getThumbnailLength: function() {
return this.thumbnailLength;
},
getThumbnailBuffer: function() {
return this._getThumbnailStream().nextBuffer(this.thumbnailLength);
},
_getThumbnailStream: function() {
return this.startMarker.openWithOffset(this.getThumbnailOffset());
},
getImageSize: function() {
return this.imageSize;
},
getThumbnailSize: function() {
var stream2 = this._getThumbnailStream(), size;
jpeg2.parseSections(stream2, function(sectionType, sectionStream) {
if (jpeg2.getSectionName(sectionType).name === "SOF") {
size = jpeg2.getSizeFromSOFSection(sectionStream);
}
});
return size;
}
};
function Parser(stream2) {
this.stream = stream2;
this.flags = {
readBinaryTags: false,
resolveTagNames: true,
simplifyValues: true,
imageSize: true,
hidePointers: true,
returnTags: true
};
}
Parser.prototype = {
enableBinaryFields: function(enable) {
this.flags.readBinaryTags = !!enable;
return this;
},
enablePointers: function(enable) {
this.flags.hidePointers = !enable;
return this;
},
enableTagNames: function(enable) {
this.flags.resolveTagNames = !!enable;
return this;
},
enableImageSize: function(enable) {
this.flags.imageSize = !!enable;
return this;
},
enableReturnTags: function(enable) {
this.flags.returnTags = !!enable;
return this;
},
enableSimpleValues: function(enable) {
this.flags.simplifyValues = !!enable;
return this;
},
parse: function() {
var start = this.stream.mark(), stream2 = start.openWithOffset(0), flags = this.flags, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset, tagNames, getTagValue, setTagValue;
if (flags.resolveTagNames) {
tagNames = require_exif_tags();
}
if (flags.resolveTagNames) {
tags = {};
getTagValue = function(t) {
return tags[t.name];
};
setTagValue = function(t, value) {
tags[t.name] = value;
};
} else {
tags = [];
getTagValue = function(t) {
var i;
for (i = 0;i < tags.length; ++i) {
if (tags[i].type === t.type && tags[i].section === t.section) {
return tags.value;
}
}
};
setTagValue = function(t, value) {
var i;
for (i = 0;i < tags.length; ++i) {
if (tags[i].type === t.type && tags[i].section === t.section) {
tags.value = value;
return;
}
}
};
}
jpeg2.parseSections(stream2, function(sectionType, sectionStream) {
var validExifHeaders, sectionOffset = sectionStream.offsetFrom(start);
if (sectionType === 225) {
validExifHeaders = exif.parseTags(sectionStream, function(ifdSection, tagType, value, format) {
if (!flags.readBinaryTags && format === 7) {
return;
}
if (tagType === 513) {
thumbnailOffset = value[0];
if (flags.hidePointers) {
return;
}
} else if (tagType === 514) {
thumbnailLength = value[0];
if (flags.hidePointers) {
return;
}
} else if (tagType === 259) {
thumbnailType = value[0];
if (flags.hidePointers) {
return;
}
}
if (!flags.returnTags) {
return;
}
if (flags.simplifyValues) {
value = simplify.simplifyValue(value, format);
}
if (flags.resolveTagNames) {
var sectionTagNames = ifdSection === exif.GPSIFD ? tagNames.gps : tagNames.exif;
var name = sectionTagNames[tagType];
if (!name) {
name = tagNames.exif[tagType];
}
if (!tags.hasOwnProperty(name)) {
tags[name] = value;
}
} else {
tags.push({
section: ifdSection,
type: tagType,
value
});
}
});
if (validExifHeaders) {
app1Offset = sectionOffset;
}
} else if (flags.imageSize && jpeg2.getSectionName(sectionType).name === "SOF") {
imageSize = jpeg2.getSizeFromSOFSection(sectionStream);
}
});
if (flags.simplifyValues) {
simplify.castDegreeValues(getTagValue, setTagValue);
simplify.castDateValues(getTagValue, setTagValue);
}
return new ExifResult(start, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset);
}
};
module.exports = Parser;
});
// ../../node_modules/.bun/exif-parser@0.1.12/node_modules/exif-parser/lib/dom-bufferstream.js
var require_dom_bufferstream = __commonJS((exports, module) => {
function DOMBufferStream(arrayBuffer, offset, length, bigEndian, global, parentOffset) {
this.global = global;
offset = offset || 0;
length = length || arrayBuffer.byteLength - offset;
this.arrayBuffer = arrayBuffer.slice(offset, offset + length);
this.view = new global.DataView(this.arrayBuffer, 0, this.arrayBuffer.byteLength);
this.setBigEndian(bigEndian);
this.offset = 0;
this.parentOffset = (parentOffset || 0) + offset;
}
DOMBufferStream.prototype = {
setBigEndian: function(bigEndian) {
this.littleEndian = !bigEndian;
},
nextUInt8: function() {
var value = this.view.getUint8(this.offset);
this.offset += 1;
return value;
},
nextInt8: function() {
var value = this.view.getInt8(this.offset);
this.offset += 1;
return value;
},
nextUInt16: function() {
var value = this.view.getUint16(this.offset, this.littleEndian);
this.offset += 2;
return value;
},
nextUInt32: function() {
var value = this.view.getUint32(this.offset, this.littleEndian);
this.offset += 4;
return value;
},
nextInt16: function() {
var value = this.view.getInt16(this.offset, this.littleEndian);
this.offset += 2;
return value;
},
nextInt32: function() {
var value = this.view.getInt32(this.offset, this.littleEndian);
this.offset += 4;
return value;
},
nextFloat: function() {
var value = this.view.getFloat32(this.offset, this.littleEndian);
this.offset += 4;
return value;
},
nextDouble: function() {
var value = this.view.getFloat64(this.offset, this.littleEndian);
this.offset += 8;
return value;
},
nextBuffer: function(length) {
var value = this.arrayBuffer.slice(this.offset, this.offset + length);
this.offset += length;
return value;
},
remainingLength: function() {
return this.arrayBuffer.byteLength - this.offset;
},
nextString: function(length) {
var value = this.arrayBuffer.slice(this.offset, this.offset + length);
value = String.fromCharCode.apply(null, new this.global.Uint8Array(value));
this.offset += length;
return value;
},
mark: function() {
var self2 = this;
return {
openWithOffset: function(offset) {
offset = (offset || 0) + this.offset;
return new DOMBufferStream(self2.arrayBuffer, offset, self2.arrayBuffer.byteLength - offset, !self2.littleEndian, self2.global, self2.parentOffset);
},
offset: this.offset,
getParentOffset: function() {
return self2.parentOffset;
}
};
},
offsetFrom: function(marker) {
return this.parentOffset + this.offset - (marker.offset + marker.getParentOffset());
},
skip: function(amount) {
this.offset += amount;
},
branch: function(offset, length) {
length = typeof length === "number" ? length : this.arrayBuffer.byteLength - (this.offset + offset);
return new DOMBufferStream(this.arrayBuffer, this.offset + offset, length, !this.littleEndian, this.global, this.parentOffset);
}
};
module.exports = DOMBufferStream;
});
// ../../node_modules/.bun/exif-parser@0.1.12/node_modules/exif-parser/lib/bufferstream.js
var require_bufferstream = __commonJS((exports, module) => {
function BufferStream(buffer, offset, length, bigEndian) {
this.buffer = buffer;
this.offset = offset || 0;
length = typeof length === "number" ? length : buffer.length;
this.endPosition = this.offset + length;
this.setBigEndian(bigEndian);
}
BufferStream.prototype = {
setBigEndian: function(bigEndian) {
this.bigEndian = !!bigEndian;
},
nextUInt8: function() {
var value = this.buffer.readUInt8(this.offset);
this.offset += 1;
return value;
},
nextInt8: function() {
var value = this.buffer.readInt8(this.offset);
this.offset += 1;
return value;
},
nextUInt16: function() {
var value = this.bigEndian ? this.buffer.readUInt16BE(this.offset) : this.buffer.readUInt16LE(this.offset);
this.offset += 2;
return value;
},
nextUInt32: function() {
var value = this.bigEndian ? this.buffer.readUInt32BE(this.offset) : this.buffer.readUInt32LE(this.offset);
this.offset += 4;
return value;
},
nextInt16: function() {
var value = this.bigEndian ? this.buffer.readInt16BE(this.offset) : this.buffer.readInt16LE(this.offset);
this.offset += 2;
return value;
},
nextInt32: function() {
var value = this.bigEndian ? this.buffer.readInt32BE(this.offset) : this.buffer.readInt32LE(this.offset);
this.offset += 4;
return value;
},
nextFloat: function() {
var value = this.bigEndian ? this.buffer.readFloatBE(this.offset) : this.buffer.readFloatLE(this.offset);
this.offset += 4;
return value;
},
nextDouble: function() {
var value = this.bigEndian ? this.buffer.readDoubleBE(this.offset) : this.buffer.readDoubleLE(this.offset);
this.offset += 8;
return value;
},
nextBuffer: function(length) {
var value = this.buffer.slice(this.offset, this.offset + length);
this.offset += length;
return value;
},
remainingLength: function() {
return this.endPosition - this.offset;
},
nextString: function(length) {
var value = this.buffer.toString("utf8", this.offset, this.offset + length);
this.offset += length;
return value;
},
mark: function() {
var self2 = this;
return {
openWithOffset: function(offset) {
offset = (offset || 0) + this.offset;
return new BufferStream(self2.buffer, offset, self2.endPosition - offset, self2.bigEndian);
},
offset: this.offset
};
},
offsetFrom: function(marker) {
return this.offset - marker.offset;
},
skip: function(amount) {
this.offset += amount;
},
branch: function(offset, length) {
length = typeof length === "number" ? length : this.endPosition - (this.offset + offset);
return new BufferStream(this.buffer, this.offset + offset, length, this.bigEndian);
}
};
module.exports = BufferStream;
});
// ../../node_modules/.bun/exif-parser@0.1.12/node_modules/exif-parser/index.js
var require_exif_parser = __commonJS((exports, module) => {
var Parser = require_parser2();
function getGlobal() {
return (1, eval)("this");
}
module.exports = {
create: function(buffer, global) {
global = global || getGlobal();
if (buffer instanceof global.ArrayBuffer) {
var DOMBufferStream = require_dom_bufferstream();
return new Parser(new DOMBufferStream(buffer, 0, buffer.byteLength, true, global));
} else {
var NodeBufferStream = require_bufferstream();
return new Parser(new NodeBufferStream(buffer, 0, buffer.length, true));
}
}
};
});
// ../../node_modules/.bun/any-base@1.1.0/node_modules/any-base/src/converter.js
var require_converter = __commonJS((exports, module) => {
function Converter(srcAlphabet, dstAlphabet) {
if (!srcAlphabet || !dstAlphabet || !srcAlphabet.length || !dstAlphabet.length) {
throw new Error("Bad alphabet");
}
this.srcAlphabet = srcAlphabet;
this.dstAlphabet = dstAlphabet;
}
Converter.prototype.convert = function(number) {
var i, divide, newlen, numberMap = {}, fromBase = this.srcAlphabet.length, toBase = this.dstAlphabet.length, length = number.length, result = typeof number === "string" ? "" : [];
if (!this.isValid(number)) {
throw new Error('Number "' + number + '" contains of non-alphabetic digits (' + this.srcAlphabet + ")");
}
if (this.srcAlphabet === this.dstAlphabet) {
return number;
}
for (i = 0;i < length; i++) {
numberMap[i] = this.srcAlphabet.indexOf(number[i]);
}
do {
divide = 0;
newlen = 0;
for (i = 0;i < length; i++) {
divide = divide * fromBase + numberMap[i];
if (divide >= toBase) {
numberMap[newlen++] = parseInt(divide / toBase, 10);
divide = divide % toBase;
} else if (newlen > 0) {
numberMap[newlen++] = 0;
}
}
length = newlen;
result = this.dstAlphabet.slice(divide, divide + 1).concat(result);
} while (newlen !== 0);
return result;
};
Converter.prototype.isValid = function(number) {
var i = 0;
for (;i < number.length; ++i) {
if (this.srcAlphabet.indexOf(number[i]) === -1) {
return false;
}
}
return true;
};
module.exports = Converter;
});
// ../../node_modules/.bun/any-base@1.1.0/node_modules/any-base/index.js
var require_any_base = __commonJS((exports, module) => {
var Converter = require_converter();
function anyBase(srcAlphabet, dstAlphabet) {
var converter = new Converter(srcAlphabet, dstAlphabet);
return function(number) {
return converter.convert(number);
};
}
anyBase.BIN = "01";
anyBase.OCT = "01234567";
anyBase.DEC = "0123456789";
anyBase.HEX = "0123456789abcdef";
module.exports = anyBase;
});
// src/3d/WGPURenderer.ts
import { PerspectiveCamera, Color, NoToneMapping, LinearSRGBColorSpace } from "three";
import { WebGPURenderer } from "three/webgpu";
import { createWebGPUDevice, setupGlobals } from "bun-webgpu";
// src/3d/canvas.ts
import { GPUCanvasContextMock } from "bun-webgpu";
import { toArrayBuffer } from "bun:ffi";
// ../../node_modules/.bun/bmp-ts@1.0.9/node_modules/bmp-ts/dist/esm/header-types.js
var HeaderTypes;
(function(HeaderTypes2) {
HeaderTypes2[HeaderTypes2["BITMAP_INFO_HEADER"] = 40] = "BITMAP_INFO_HEADER";
HeaderTypes2[HeaderTypes2["BITMAP_V2_INFO_HEADER"] = 52] = "BITMAP_V2_INFO_HEADER";
HeaderTypes2[HeaderTypes2["BITMAP_V3_INFO_HEADER"] = 56] = "BITMAP_V3_INFO_HEADER";
HeaderTypes2[HeaderTypes2["BITMAP_V4_HEADER"] = 108] = "BITMAP_V4_HEADER";
HeaderTypes2[HeaderTypes2["BITMAP_V5_HEADER"] = 124] = "BITMAP_V5_HEADER";
})(HeaderTypes || (HeaderTypes = {}));
var header_types_default = HeaderTypes;
// ../../node_modules/.bun/bmp-ts@1.0.9/node_modules/bmp-ts/dist/esm/mask-color.js
function maskColor(maskRed, maskGreen, maskBlue, maskAlpha) {
const maskRedR = ~maskRed + 1 & maskRed;
const maskGreenR = ~maskGreen + 1 & maskGreen;
const maskBlueR = ~maskBlue + 1 & maskBlue;
const maskAlphaR = ~maskAlpha + 1 & maskAlpha;
const shiftedMaskRedL = maskRed / maskRedR + 1;
const shiftedMaskGreenL = maskGreen / maskGreenR + 1;
const shiftedMaskBlueL = maskBlue / maskBlueR + 1;
const shiftedMaskAlphaL = maskAlpha / maskAlphaR + 1;
return {
shiftRed: (x) => (x & maskRed) / maskRedR * 256 / shiftedMaskRedL,
shiftGreen: (x) => (x & maskGreen) / maskGreenR * 256 / shiftedMaskGreenL,
shiftBlue: (x) => (x & maskBlue) / maskBlueR * 256 / shiftedMaskBlueL,
shiftAlpha: maskAlpha !== 0 ? (x) => (x & maskAlpha) / maskAlphaR * 256 / shiftedMaskAlphaL : () => 255
};
}
// ../../node_modules/.bun/bmp-ts@1.0.9/node_modules/bmp-ts/dist/esm/types.js
var BmpCompression;
(function(BmpCompression2) {
BmpCompression2[BmpCompression2["NONE"] = 0] = "NONE";
BmpCompression2[BmpCompression2["BI_RLE8"] = 1] = "BI_RLE8";
BmpCompression2[BmpCompression2["BI_RLE4"] = 2] = "BI_RLE4";
BmpCompression2[BmpCompression2["BI_BIT_FIELDS"] = 3] = "BI_BIT_FIELDS";
BmpCompression2[BmpCompression2["BI_ALPHA_BIT_FIELDS"] = 6] = "BI_ALPHA_BIT_FIELDS";
})(BmpCompression || (BmpCompression = {}));
// ../../node_modules/.bun/bmp-ts@1.0.9/node_modules/bmp-ts/dist/esm/decoder.js
class BmpDecoder {
flag;
fileSize;
reserved1;
reserved2;
offset;
headerSize;
width;
height;
planes;
bitPP;
compression;
rawSize;
hr;
vr;
colors;
importantColors;
palette;
data;
maskRed;
maskGreen;
maskBlue;
maskAlpha;
toRGBA;
pos;
bottomUp;
buffer;
locRed;
locGreen;
locBlue;
locAlpha;
shiftRed;
shiftGreen;
shiftBlue;
shiftAlpha;
constructor(buffer, { toRGBA } = { toRGBA: false }) {
this.buffer = buffer;
this.toRGBA = !!toRGBA;
this.pos = 0;
this.bottomUp = true;
this.flag = this.buffer.toString("utf-8", 0, this.pos += 2);
if (this.flag !== "BM") {
throw new Error("Invalid BMP File");
}
this.locRed = this.toRGBA ? 0 : 3;
this.locGreen = this.toRGBA ? 1 : 2;
this.locBlue = this.toRGBA ? 2 : 1;
this.locAlpha = this.toRGBA ? 3 : 0;
this.parseHeader();
this.parseRGBA();
}
parseHeader() {
this.fileSize = this.readUInt32LE();
this.reserved1 = this.buffer.readUInt16LE(this.pos);
this.pos += 2;
this.reserved2 = this.buffer.readUInt16LE(this.pos);
this.pos += 2;
this.offset = this.readUInt32LE();
this.headerSize = this.readUInt32LE();
if (!(this.headerSize in header_types_default)) {
throw new Error(`Unsupported BMP header size ${this.headerSize}`);
}
this.width = this.readUInt32LE();
this.height = this.readUInt32LE();
this.height = this.height > 2147483647 ? this.height - 4294967296 : this.height;
this.planes = this.buffer.readUInt16LE(this.pos);
this.pos += 2;
this.bitPP = this.buffer.readUInt16LE(this.pos);
this.pos += 2;
this.compression = this.readUInt32LE();
this.rawSize = this.readUInt32LE();
this.hr = this.readUInt32LE();
this.vr = this.readUInt32LE();
this.colors = this.readUInt32LE();
this.importantColors = this.readUInt32LE();
if (this.bitPP === 32) {
this.maskAlpha = 0;
this.maskRed = 16711680;
this.maskGreen = 65280;
this.maskBlue = 255;
} else if (this.bitPP === 16) {
this.maskAlpha = 0;
this.maskRed = 31744;
this.maskGreen = 992;
this.maskBlue = 31;
}
if (this.headerSize > header_types_default.BITMAP_INFO_HEADER || this.compression === BmpCompression.BI_BIT_FIELDS || this.compression === BmpCompression.BI_ALPHA_BIT_FIELDS) {
this.maskRed = this.readUInt32LE();
this.maskGreen = this.readUInt32LE();
this.maskBlue = this.readUInt32LE();
}
if (this.headerSize > header_types_default.BITMAP_V2_INFO_HEADER || this.compression === BmpCompression.BI_ALPHA_BIT_FIELDS) {
this.maskAlpha = this.readUInt32LE();
}
if (this.headerSize > header_types_default.BITMAP_V3_INFO_HEADER) {
this.pos += header_types_default.BITMAP_V4_HEADER - header_types_default.BITMAP_V3_INFO_HEADER;
}
if (this.headerSize > header_types_default.BITMAP_V4_HEADER) {
this.pos += header_types_default.BITMAP_V5_HEADER - header_types_default.BITMAP_V4_HEADER;
}
if (this.bitPP <= 8 || this.colors > 0) {
const len = this.colors === 0 ? 1 << this.bitPP : this.colors;
this.palette = new Array(len);
for (let i = 0;i < len; i++) {
const blue = this.buffer.readUInt8(this.pos++);
const green = this.buffer.readUInt8(this.pos++);
const red = this.buffer.readUInt8(this.pos++);
const quad = this.buffer.readUInt8(this.pos++);
this.palette[i] = {
red,
green,
blue,
quad
};
}
}
if (this.height < 0) {
this.height *= -1;
this.bottomUp = false;
}
const coloShift = maskColor(this.maskRed, this.maskGreen, this.maskBlue, this.maskAlpha);
this.shiftRed = coloShift.shiftRed;
this.shiftGreen = coloShift.shiftGreen;
this.shiftBlue = coloShift.shiftBlue;
this.shiftAlpha = coloShift.shiftAlpha;
}
parseRGBA() {
this.data = Buffer.alloc(this.width * this.height * 4);
switch (this.bitPP) {
case 1:
this.bit1();
break;
case 4:
this.bit4();
break;
case 8:
this.bit8();
break;
case 16:
this.bit16();
break;
case 24:
this.bit24();
break;
default:
this.bit32();
}
}
bit1() {
const xLen = Math.ceil(this.width / 8);
const mode = xLen % 4;
const padding = mode !== 0 ? 4 - mode : 0;
let lastLine;
this.scanImage(padding, xLen, (x, line) => {
if (line !== lastLine) {
lastLine = line;
}
const b = this.buffer.readUInt8(this.pos++);
const location = line * this.width * 4 + x * 8 * 4;
for (let i = 0;i < 8; i++) {
if (x * 8 + i < this.width) {
const rgb = this.palette[b >> 7 - i & 1];
this.data[location + i * this.locAlpha] = 0;
this.data[location + i * 4 + this.locBlue] = rgb.blue;
this.data[location + i * 4 + this.locGreen] = rgb.green;
this.data[location + i * 4 + this.locRed] = rgb.red;
} else {
break;
}
}
});
}
bit4() {
if (this.compression === BmpCompression.BI_RLE4) {
this.data.fill(0);
let lowNibble = false;
let lines = this.bottomUp ? this.height - 1 : 0;
let location = 0;
while (location < this.data.length) {
const a = this.buffer.readUInt8(this.pos++);
const b = this.buffer.readUInt8(this.pos++);
if (a === 0) {
if (b === 0) {
lines += this.bottomUp ? -1 : 1;
location = lines * this.width * 4;
lowNibble = false;
continue;
}
if (b === 1) {
break;
}
if (b === 2) {
const x = this.buffer.readUInt8(this.pos++);
const y = this.buffer.readUInt8(this.pos++);
lines += this.bottomUp ? -y : y;
location += y * this.width * 4 + x * 4;
} else {
let c = this.buffer.readUInt8(this.pos++);
for (let i = 0;i < b; i++) {
location = this.setPixelData(location, lowNibble ? c & 15 : (c & 240) >> 4);
if (i & 1 && i + 1 < b) {
c = this.buffer.readUInt8(this.pos++);
}
lowNibble = !lowNibble;
}
if ((b + 1 >> 1 & 1) === 1) {
this.pos++;
}
}
} else {
for (let i = 0;i < a; i++) {
location = this.setPixelData(location, lowNibble ? b & 15 : (b & 240) >> 4);
lowNibble = !lowNibble;
}
}
}
} else {
const xLen = Math.ceil(this.width / 2);
const mode = xLen % 4;
const padding = mode !== 0 ? 4 - mode : 0;
this.scanImage(padding, xLen, (x, line) => {
const b = this.buffer.readUInt8(this.pos++);
const location = line * this.width * 4 + x * 2 * 4;
const first4 = b >> 4;
let rgb = this.palette[first4];
this.data[location] = 0;
this.data[location + 1] = rgb.blue;
this.data[location + 2] = rgb.green;
this.data[location + 3] = rgb.red;
if (x * 2 + 1 >= this.width) {
return false;
}
const last4 = b & 15;
rgb = this.palette[last4];
this.data[location + 4] = 0;
this.data[location + 4 + 1] = rgb.blue;
this.data[location + 4 + 2] = rgb.green;
this.data[location + 4 + 3] = rgb.red;
});
}
}
bit8() {
if (this.compression === BmpCompression.BI_RLE8) {
this.data.fill(0);
let lines = this.bottomUp ? this.height - 1 : 0;
let location = 0;
while (location < this.data.length) {
const a = this.buffer.readUInt8(this.pos++);
const b = this.buffer.readUInt8(this.pos++);
if (a === 0) {
if (b === 0) {
lines += this.bottomUp ? -1 : 1;
location = lines * this.width * 4;
continue;
}
if (b === 1) {
break;
}
if (b === 2) {
const x = this.buffer.readUInt8(this.pos++);
const y = this.buffer.readUInt8(this.pos++);
lines += this.bottomUp ? -y : y;
location += y * this.width * 4 + x * 4;
} else {
for (let i = 0;i < b; i++) {
const c = this.buffer.readUInt8(this.pos++);
location = this.setPixelData(location, c);
}
const shouldIncrement = b & true;
if (shouldIncrement) {
this.pos++;
}
}
} else {
for (let i = 0;i < a; i++) {
location = this.setPixelData(location, b);
}
}
}
} else {
const mode = this.width % 4;
const padding = mode !== 0 ? 4 - mode : 0;
this.scanImage(padding, this.width, (x, line) => {
const b = this.buffer.readUInt8(this.pos++);
const location = line * this.width * 4 + x * 4;
if (b < this.palette.length) {
const rgb = this.palette[b];
this.data[location] = 0;
this.data[location + 1] = rgb.blue;
this.data[location + 2] = rgb.green;
this.data[location + 3] = rgb.red;
} else {
this.data[location] = 0;
this.data[location + 1] = 255;
this.data[location + 2] = 255;
this.data[location + 3] = 255;
}
});
}
}
bit16() {
const padding = this.width % 2 * 2;
this.scanImage(padding, this.width, (x, line) => {
const loc = line * this.width * 4 + x * 4;
const px = this.buffer.readUInt16LE(this.pos);
this.pos += 2;
this.data[loc + this.locRed] = this.shiftRed(px);
this.data[loc + this.locGreen] = this.shiftGreen(px);
this.data[loc + this.locBlue] = this.shiftBlue(px);
this.data[loc + this.locAlpha] = this.shiftAlpha(px);
});
}
bit24() {
const padding = this.width % 4;
this.scanImage(padding, this.width, (x, line) => {
const loc = line * this.width * 4 + x * 4;
const blue = this.buffer.readUInt8(this.pos++);
const green = this.buffer.readUInt8(this.pos++);
const red = this.buffer.readUInt8(this.pos++);
this.data[loc + this.locRed] = red;
this.data[loc + this.locGreen] = green;
this.data[loc + this.locBlue] = blue;
this.data[loc + this.locAlpha] = 0;
});
}
bit32() {
this.scanImage(0, this.width, (x, line) => {
const loc = line * this.width * 4 + x * 4;
const px = this.readUInt32LE();
this.data[loc + this.locRed] = this.shiftRed(px);
this.data[loc + this.locGreen] = this.shiftGreen(px);
this.data[loc + this.locBlue] = this.shiftBlue(px);
this.data[loc + this.locAlpha] = this.shiftAlpha(px);
});
}
scanImage(padding = 0, width = this.width, processPixel) {
for (let y = this.height - 1;y >= 0; y--) {
const line = this.bottomUp ? y : this.height - 1 - y;
for (let x = 0;x < width; x++) {
const result = processPixel.call(this, x, line);
if (result === false) {
return;
}
}
this.pos += padding;
}
}
readUInt32LE() {
const value = this.buffer.readUInt32LE(this.pos);
this.pos += 4;
return value;
}
setPixelData(location, rgbIndex) {
const { blue, green, red } = this.palette[rgbIndex];
this.data[location + this.locAlpha] = 0;
this.data[location + 1 + this.locBlue] = blue;
this.data[location + 2 + this.locGreen] = green;
this.data[location + 3 + this.locRed] = red;
return location + 4;
}
}
// ../../node_modules/.bun/bmp-ts@1.0.9/node_modules/bmp-ts/dist/esm/encoder.js
function createInteger(numbers) {
return numbers.reduce((final, n) => final << 1 | n, 0);
}
function createColor(color) {
return color.quad << 24 | color.red << 16 | color.green << 8 | color.blue;
}
class BmpEncoder {
fileSize;
reserved1;
reserved2;
offset;
width;
flag;
height;
planes;
bitPP;
compress;
hr;
vr;
colors;
importantColors;
rawSize;
headerSize;
data;
palette;
extraBytes;
buffer;
bytesInColor;
pos;
constructor(imgData) {
this.buffer = imgData.data;
this.width = imgData.width;
this.height = imgData.height;
this.headerSize = header_types_default.BITMAP_INFO_HEADER;
this.flag = "BM";
this.bitPP = imgData.bitPP || 24;
this.offset = 54;
this.reserved1 = imgData.reserved1 || 0;
this.reserved2 = imgData.reserved2 || 0;
this.planes = 1;
this.compress = 0;
this.hr = imgData.hr || 0;
this.vr = imgData.vr || 0;
this.importantColors = imgData.importantColors || 0;
this.colors = Math.min(2 ** (this.bitPP - 1 || 1), imgData.colors || Infinity);
this.palette = imgData.palette || [];
if (this.colors && this.bitPP < 16) {
this.offset += this.colors * 4;
} else {
this.colors = 0;
}
switch (this.bitPP) {
case 32:
this.bytesInColor = 4;
break;
case 16:
this.bytesInColor = 2;
break;
case 8:
this.bytesInColor = 1;
break;
case 4:
this.bytesInColor = 1 / 2;
break;
case 1:
this.bytesInColor = 1 / 8;
break;
default:
this.bytesInColor = 3;
this.bitPP = 24;
}
const rowWidth = this.width * this.bitPP / 32;
const rowBytes = Math.ceil(rowWidth);
this.extraBytes = (rowBytes - rowWidth) * 4;
this.rawSize = this.height * rowBytes * 4 + 2;
this.fileSize = this.rawSize + this.offset;
this.data = Buffer.alloc(this.fileSize, 1);
this.pos = 0;
this.encode();
}
encode() {
this.pos = 0;
this.writeHeader();
switch (this.bitPP) {
case 32:
this.bit32();
break;
case 16:
this.bit16();
break;
case 8:
this.bit8();
break;
case 4:
this.bit4();
break;
case 1:
this.bit1();
break;
default:
this.bit24();
}
}
writeHeader() {
this.data.write(this.flag, this.pos, 2);
this.pos += 2;
this.writeUInt32LE(this.fileSize);
this.writeUInt32LE(this.reserved1 << 16 | this.reserved2);
this.writeUInt32LE(this.offset);
this.writeUInt32LE(this.headerSize);
this.writeUInt32LE(this.width);
this.writeUInt32LE(this.height);
this.data.writeUInt16LE(this.planes, this.pos);
this.pos += 2;
this.data.writeUInt16LE(this.bitPP, this.pos);
this.pos += 2;
this.writeUInt32LE(this.compress);
this.writeUInt32LE(this.rawSize);
this.writeUInt32LE(this.hr);
this.writeUInt32LE(this.vr);
this.writeUInt32LE(this.colors);
this.writeUInt32LE(this.importantColors);
}
bit1() {
if (this.palette.length && this.colors === 2) {
this.initColors(1);
} else {
this.writeUInt32LE(16777215);
this.writeUInt32LE(0);
}
this.pos += 1;
let lineArr = [];
this.writeImage((p, index, x) => {
let i = index;
i++;
const b = this.buffer[i++];
const g = this.buffer[i++];
const r = this.buffer[i++];
const brightness = r * 0.2126 + g * 0.7152 + b * 0.0722;
lineArr.push(brightness > 127 ? 0 : 1);
if ((x + 1) % 8 === 0) {
this.data[p - 1] = createInteger(lineArr);
lineArr = [];
} else if (x === this.width - 1 && lineArr.length > 0) {
this.data[p - 1] = createInteger(lineArr) << 4;
lineArr = [];
}
return i;
});
}
bit4() {
const colors = this.initColors(4);
let integerPair = [];
this.writeImage((p, index, x) => {
let i = index;
const colorInt = createColor({
quad: this.buffer[i++],
blue: this.buffer[i++],
green: this.buffer[i++],
red: this.buffer[i++]
});
const colorExists = colors.findIndex((c) => c === colorInt);
if (colorExists !== -1) {
integerPair.push(colorExists);
} else {
integerPair.push(0);
}
if ((x + 1) % 2 === 0) {
this.data[p] = integerPair[0] << 4 | integerPair[1];
integerPair = [];
}
return i;
});
}
bit8() {
const colors = this.initColors(8);
this.writeImage((p, index) => {
let i = index;
const colorInt = createColor({
quad: this.buffer[i++],
blue: this.buffer[i++],
green: this.buffer[i++],
red: this.buffer[i++]
});
const colorExists = colors.findIndex((c) => c === colorInt);
if (colorExists !== -1) {
this.data[p] = colorExists;
} else {
this.data[p] = 0;
}
return i;
});
}
bit16() {
this.writeImage((p, index) => {
let i = index + 1;
const b = this.buffer[i++] / 8;
const g = this.buffer[i++] / 8;
const r = this.buffer[i++] / 8;
const color = r << 10 | g << 5 | b;
this.data[p] = color & 255;
this.data[p + 1] = (color & 65280) >> 8;
return i;
});
}
bit24() {
this.writeImage((p, index) => {
let i = index + 1;
this.data[p] = this.buffer[i++];
this.data[p + 1] = this.buffer[i++];
this.data[p + 2] = this.buffer[i++];
return i;
});
}
bit32() {
this.writeImage((p, index) => {
let i = index;
this.data[p + 3] = this.buffer[i++];
this.data[p] = this.buffer[i++];
this.data[p + 1] = this.buffer[i++];
this.data[p + 2] = this.buffer[i++];
return i;
});
}
writeImage(writePixel) {
const rowBytes = this.extraBytes + this.width * this.bytesInColor;
let i = 0;
for (let y = 0;y < this.height; y++) {
for (let x = 0;x < this.width; x++) {
const p = Math.floor(this.pos + (this.height - 1 - y) * rowBytes + x * this.bytesInColor);
i = writePixel.call(this, p, i, x, y);
}
}
}
initColors(bit) {
const colors = [];
if (this.palette.length) {
for (let i = 0;i < this.colors; i++) {
const rootColor = createColor(this.palette[i]);
this.writeUInt32LE(rootColor);
colors.push(rootColor);
}
} else {
throw new Error(`To encode ${bit}-bit BMPs a pallette is needed. Please choose up to ${this.colors} colors. Colors must be 32-bit integers.`);
}
return colors;
}
writeUInt32LE(value) {
this.data.writeUInt32LE(value, this.pos);
this.pos += 4;
}
}
// ../../node_modules/.bun/bmp-ts@1.0.9/node_modules/bmp-ts/dist/esm/index.js
function decode(bmpData, options) {
return new BmpDecoder(bmpData, options);
}
function encode(imgData) {
return new BmpEncoder(imgData);
}
// ../../node_modules/.bun/tinycolor2@1.6.0/node_modules/tinycolor2/esm/tinycolor.js
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(obj2) {
return typeof obj2;
} : function(obj2) {
return obj2 && typeof Symbol == "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
}, _typeof(obj);
}
var trimLeft = /^\s+/;
var trimRight = /\s+$/;
function tinycolor(color, opts) {
color = color ? color : "";
opts = opts || {};
if (color instanceof tinycolor) {
return color;
}
if (!(this instanceof tinycolor)) {
return new tinycolor(color, opts);
}
var rgb = inputToRGB(color);
this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format;
this._gradientType = opts.gradientType;
if (this._r < 1)
this._r = Math.round(this._r);
if (this._g < 1)
this._g = Math.round(this._g);
if (this._b < 1)
this._b = Math.round(this._b);
this._ok = rgb.ok;
}
tinycolor.prototype = {
isDark: function isDark() {
return this.getBrightness() < 128;
},
isLight: function isLight() {
return !this.isDark();
},
isValid: function isValid() {
return this._ok;
},
getOriginalInput: function getOriginalInput() {
return this._originalInput;
},
getFormat: function getFormat() {
return this._format;
},
getAlpha: function getAlpha() {
return this._a;
},
getBrightness: function getBrightness() {
var rgb = this.toRgb();
return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
},
getLuminance: function getLuminance() {
var rgb = this.toRgb();
var RsRGB, GsRGB, BsRGB, R, G, B;
RsRGB = rgb.r / 255;
GsRGB = rgb.g / 255;
BsRGB = rgb.b / 255;
if (RsRGB <= 0.03928)
R = RsRGB / 12.92;
else
R = Math.pow((RsRGB + 0.055) / 1.055, 2.4);
if (GsRGB <= 0.03928)
G = GsRGB / 12.92;
else
G = Math.pow((GsRGB + 0.055) / 1.055, 2.4);
if (BsRGB <= 0.03928)
B = BsRGB / 12.92;
else
B = Math.pow((BsRGB + 0.055) / 1.055, 2.4);
return 0.2126 * R + 0.7152 * G + 0.0722 * B;
},
setAlpha: function setAlpha(value) {
this._a = boundAlpha(value);
this._roundA = Math.round(100 * this._a) / 100;
return this;
},
toHsv: function toHsv() {
var hsv = rgbToHsv(this._r, this._g, this._b);
return {
h: hsv.h * 360,
s: hsv.s,
v: hsv.v,
a: this._a
};
},
toHsvString: function toHsvString() {
var hsv = rgbToHsv(this._r, this._g, this._b);
var h = Math.round(hsv.h * 360), s = Math.round(hsv.s * 100), v = Math.round(hsv.v * 100);
return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")";
},
toHsl: function toHsl() {
var hsl = rgbToHsl(this._r, this._g, this._b);
return {
h: hsl.h * 360,
s: hsl.s,
l: hsl.l,
a: this._a
};
},
toHslString: function toHslString() {
var hsl = rgbToHsl(this._r, this._g, this._b);
var h = Math.round(hsl.h * 360), s = Math.round(hsl.s * 100), l = Math.round(hsl.l * 100);
return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")";
},
toHex: function toHex(allow3Char) {
return rgbToHex(this._r, this._g, this._b, allow3Char);
},
toHexString: function toHexString(allow3Char) {
return "#" + this.toHex(allow3Char);
},
toHex8: function toHex8(allow4Char) {
return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
},
toHex8String: function toHex8String(allow4Char) {
return "#" + this.toHex8(allow4Char);
},
toRgb: function toRgb() {
return {
r: Math.round(this._r),
g: Math.round(this._g),
b: Math.round(this._b),
a: this._a
};
},
toRgbString: function toRgbString() {
return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")";
},
toPercentageRgb: function toPercentageRgb() {
return {
r: Math.round(bound01(this._r, 255) * 100) + "%",
g: Math.round(bound01(this._g, 255) * 100) + "%",
b: Math.round(bound01(this._b, 255) * 100) + "%",
a: this._a
};
},
toPercentageRgbString: function toPercentageRgbString() {
return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
},
toName: function toName() {
if (this._a === 0) {
return "transparent";
}
if (this._a < 1) {
return false;
}
return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
},
toFilter: function toFilter(secondColor) {
var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a);
var secondHex8String = hex8String;
var gradientType = this._gradientType ? "GradientType = 1, " : "";
if (secondColor) {
var s = tinycolor(secondColor);
secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a);
}
return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")";
},
toString: function toString(format) {
var formatSet = !!format;
format = format || this._format;
var formattedString = false;
var hasAlpha = this._a < 1 && this._a >= 0;
var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");
if (needsAlphaFormat) {
if (format === "name" && this._a === 0) {
return this.toName();
}
return this.toRgbString();
}
if (format === "rgb") {
formattedString = this.toRgbString();
}
if (format === "prgb") {
formattedString = this.toPercentageRgbString();
}
if (format === "hex" || format === "hex6") {
formattedString = this.toHexString();
}
if (format === "hex3") {
formattedString = this.toHexString(true);
}
if (format === "hex4") {
formattedString = this.toHex8String(true);
}
if (format === "hex8") {
formattedString = this.toHex8String();
}
if (format === "name") {
formattedString = this.toName();
}
if (format === "hsl") {
formattedString = this.toHslString();
}
if (format === "hsv") {
formattedString = this.toHsvString();
}
return formattedString || this.toHexString();
},
clone: function clone() {
return tinycolor(this.toString());
},
_applyModification: function _applyModification(fn, args) {
var color = fn.apply(null, [this].concat([].slice.call(args)));
this._r = color._r;
this._g = color._g;
this._b = color._b;
this.setAlpha(color._a);
return this;
},
lighten: function lighten() {
return this._applyModification(_lighten, arguments);
},
brighten: function brighten() {
return this._applyModification(_brighten, arguments);
},
darken: function darken() {
return this._applyModification(_darken, arguments);
},
desaturate: function desaturate() {
return this._applyModification(_desaturate, arguments);
},
saturate: function saturate() {
return this._applyModification(_saturate, arguments);
},
greyscale: function greyscale() {
return this._applyModification(_greyscale, arguments);
},
spin: function spin() {
return this._applyModification(_spin, arguments);
},
_applyCombination: function _applyCombination(fn, args) {
return fn.apply(null, [this].concat([].slice.call(args)));
},
analogous: function analogous() {
return this._applyCombination(_analogous, arguments);
},
complement: function complement() {
return this._applyCombination(_complement, arguments);
},
monochromatic: function monochromatic() {
return this._applyCombination(_monochromatic, arguments);
},
splitcomplement: function splitcomplement() {
return this._applyCombination(_splitcomplement, arguments);
},
triad: function triad() {
return this._applyCombination(polyad, [3]);
},
tetrad: function tetrad() {
return this._applyCombination(polyad, [4]);
}
};
tinycolor.fromRatio = function(color, opts) {
if (_typeof(color) == "object") {
var newColor = {};
for (var i in color) {
if (color.hasOwnProperty(i)) {
if (i === "a") {
newColor[i] = color[i];
} else {
newColor[i] = convertToPercentage(color[i]);
}
}
}
color = newColor;
}
return tinycolor(color, opts);
};
function inputToRGB(color) {
var rgb = {
r: 0,
g: 0,
b: 0
};
var a = 1;
var s = null;
var v = null;
var l = null;
var ok = false;
var format = false;
if (typeof color == "string") {
color = stringInputToObject(color);
}
if (_typeof(color) == "object") {
if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
rgb = rgbToRgb(color.r, color.g, color.b);
ok = true;
format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
} else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
s = convertToPercentage(color.s);
v = convertToPercentage(color.v);
rgb = hsvToRgb(color.h, s, v);
ok = true;
format = "hsv";
} else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
s = convertToPercentage(color.s);
l = convertToPercentage(color.l);
rgb = hslToRgb(color.h, s, l);
ok = true;
format = "hsl";
}
if (color.hasOwnProperty("a")) {
a = color.a;
}
}
a = boundAlpha(a);
return {
ok,
format: color.format || format,
r: Math.min(255, Math.max(rgb.r, 0)),
g: Math.min(255, Math.max(rgb.g, 0)),
b: Math.min(255, Math.max(rgb.b, 0)),
a
};
}
function rgbToRgb(r, g, b) {
return {
r: bound01(r, 255) * 255,
g: bound01(g, 255) * 255,
b: bound01(b, 255) * 255
};
}
function rgbToHsl(r, g, b) {
r = bound01(r, 255);
g = bound01(g, 255);
b = bound01(b, 255);
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if (max == min) {
h = s = 0;
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return {
h,
s,
l
};
}
function hslToRgb(h, s, l) {
var r, g, b;
h = bound01(h, 360);
s = bound01(s, 100);
l = bound01(l, 100);
function hue2rgb(p2, q2, t) {
if (t < 0)
t += 1;
if (t > 1)
t -= 1;
if (t < 1 / 6)
return p2 + (q2 - p2) * 6 * t;
if (t < 1 / 2)
return q2;
if (t < 2 / 3)
return p2 + (q2 - p2) * (2 / 3 - t) * 6;
return p2;
}
if (s === 0) {
r = g = b = l;
} else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return {
r: r * 255,
g: g * 255,
b: b * 255
};
}
function rgbToHsv(r, g, b) {
r = bound01(r, 255);
g = bound01(g, 255);
b = bound01(b, 255);
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, v = max;
var d = max - min;
s = max === 0 ? 0 : d / max;
if (max == min) {
h = 0;
} else {
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return {
h,
s,
v
};
}
function hsvToRgb(h, s, v) {
h = bound01(h, 360) * 6;
s = bound01(s, 100);
v = bound01(v, 100);
var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod];
return {
r: r * 255,
g: g * 255,
b: b * 255
};
}
function rgbToHex(r, g, b, allow3Char) {
var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];
if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
}
return hex.join("");
}
function rgbaToHex(r, g, b, a, allow4Char) {
var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))];
if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
}
return hex.join("");
}
function rgbaToArgbHex(r, g, b, a) {
var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];
return hex.join("");
}
tinycolor.equals = function(color1, color2) {
if (!color1 || !color2)
return false;
return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
};
tinycolor.random = function() {
return tinycolor.fromRatio({
r: Math.random(),
g: Math.random(),
b: Math.random()
});
};
function _desaturate(color, amount) {
amount = amount === 0 ? 0 : amount || 10;
var hsl = tinycolor(color).toHsl();
hsl.s -= amount / 100;
hsl.s = clamp01(hsl.s);
return tinycolor(hsl);
}
function _saturate(color, amount) {
amount = amount === 0 ? 0 : amount || 10;
var hsl = tinycolor(color).toHsl();
hsl.s += amount / 100;
hsl.s = clamp01(hsl.s);
return tinycolor(hsl);
}
function _greyscale(color) {
return tinycolor(color).desaturate(100);
}
function _lighten(color, amount) {
amount = amount === 0 ? 0 : amount || 10;
var hsl = tinycolor(color).toHsl();
hsl.l += amount / 100;
hsl.l = clamp01(hsl.l);
return tinycolor(hsl);
}
function _brighten(color, amount) {
amount = amount === 0 ? 0 : amount || 10;
var rgb = tinycolor(color).toRgb();
rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100))));
rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100))));
rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100))));
return tinycolor(rgb);
}
function _darken(color, amount) {
amount = amount === 0 ? 0 : amount || 10;
var hsl = tinycolor(color).toHsl();
hsl.l -= amount / 100;
hsl.l = clamp01(hsl.l);
return tinycolor(hsl);
}
function _spin(color, amount) {
var hsl = tinycolor(color).toHsl();
var hue = (hsl.h + amount) % 360;
hsl.h = hue < 0 ? 360 + hue : hue;
return tinycolor(hsl);
}
function _complement(color) {
var hsl = tinycolor(color).toHsl();
hsl.h = (hsl.h + 180) % 360;
return tinycolor(hsl);
}
function polyad(color, number) {
if (isNaN(number) || number <= 0) {
throw new Error("Argument to polyad must be a positive number");
}
var hsl = tinycolor(color).toHsl();
var result = [tinycolor(color)];
var step = 360 / number;
for (var i = 1;i < number; i++) {
result.push(tinycolor({
h: (hsl.h + i * step) % 360,
s: hsl.s,
l: hsl.l
}));
}
return result;
}
function _splitcomplement(color) {
var hsl = tinycolor(color).toHsl();
var h = hsl.h;
return [tinycolor(color), tinycolor({
h: (h + 72) % 360,
s: hsl.s,
l: hsl.l
}), tinycolor({
h: (h + 216) % 360,
s: hsl.s,
l: hsl.l
})];
}
function _analogous(color, results, slices) {
results = results || 6;
slices = slices || 30;
var hsl = tinycolor(color).toHsl();
var part = 360 / slices;
var ret = [tinycolor(color)];
for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360;--results; ) {
hsl.h = (hsl.h + part) % 360;
ret.push(tinycolor(hsl));
}
return ret;
}
function _monochromatic(color, results) {
results = results || 6;
var hsv = tinycolor(color).toHsv();
var { h, s, v } = hsv;
var ret = [];
var modification = 1 / results;
while (results--) {
ret.push(tinycolor({
h,
s,
v
}));
v = (v + modification) % 1;
}
return ret;
}
tinycolor.mix = function(color1, color2, amount) {
amount = amount === 0 ? 0 : amount || 50;
var rgb1 = tinycolor(color1).toRgb();
var rgb2 = tinycolor(color2).toRgb();
var p = amount / 100;
var rgba = {
r: (rgb2.r - rgb1.r) * p + rgb1.r,
g: (rgb2.g - rgb1.g) * p + rgb1.g,
b: (rgb2.b - rgb1.b) * p + rgb1.b,
a: (rgb2.a - rgb1.a) * p + rgb1.a
};
return tinycolor(rgba);
};
tinycolor.readability = function(color1, color2) {
var c1 = tinycolor(color1);
var c2 = tinycolor(color2);
return (Math.max(c1.getLuminance(), c2.getLuminance()) + 0.05) / (Math.min(c1.getLuminance(), c2.getLuminance()) + 0.05);
};
tinycolor.isReadable = function(color1, color2, wcag2) {
var readability = tinycolor.readability(color1, color2);
var wcag2Parms, out;
out = false;
wcag2Parms = validateWCAG2Parms(wcag2);
switch (wcag2Parms.level + wcag2Parms.size) {
case "AAsmall":
case "AAAlarge":
out = readability >= 4.5;
break;
case "AAlarge":
out = readability >= 3;
break;
case "AAAsmall":
out = readability >= 7;
break;
}
return out;
};
tinycolor.mostReadable = function(baseColor, colorList, args) {
var bestColor = null;
var bestScore = 0;
var readability;
var includeFallbackColors, level, size;
args = args || {};
includeFallbackColors = args.includeFallbackColors;
level = args.level;
size = args.size;
for (var i = 0;i < colorList.length; i++) {
readability = tinycolor.readability(baseColor, colorList[i]);
if (readability > bestScore) {
bestScore = readability;
bestColor = tinycolor(colorList[i]);
}
}
if (tinycolor.isReadable(baseColor, bestColor, {
level,
size
}) || !includeFallbackColors) {
return bestColor;
} else {
args.includeFallbackColors = false;
return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args);
}
};
var names = tinycolor.names = {
aliceblue: "f0f8ff",
antiquewhite: "faebd7",
aqua: "0ff",
aquamarine: "7fffd4",
azure: "f0ffff",
beige: "f5f5dc",
bisque: "ffe4c4",
black: "000",
blanchedalmond: "ffebcd",
blue: "00f",
blueviolet: "8a2be2",
brown: "a52a2a",
burlywood: "deb887",
burntsienna: "ea7e5d",
cadetblue: "5f9ea0",
chartreuse: "7fff00",
chocolate: "d2691e",
coral: "ff7f50",
cornflowerblue: "6495ed",
cornsilk: "fff8dc",
crimson: "dc143c",
cyan: "0ff",
darkblue: "00008b",
darkcyan: "008b8b",
darkgoldenrod: "b8860b",
darkgray: "a9a9a9",
darkgreen: "006400",
darkgrey: "a9a9a9",
darkkhaki: "bdb76b",
darkmagenta: "8b008b",
darkolivegreen: "556b2f",
darkorange: "ff8c00",
darkorchid: "9932cc",
darkred: "8b0000",
darksalmon: "e9967a",
darkseagreen: "8fbc8f",
darkslateblue: "483d8b",
darkslategray: "2f4f4f",
darkslategrey: "2f4f4f",
darkturquoise: "00ced1",
darkviolet: "9400d3",
deeppink: "ff1493",
deepskyblue: "00bfff",
dimgray: "696969",
dimgrey: "696969",
dodgerblue: "1e90ff",
firebrick: "b22222",
floralwhite: "fffaf0",
forestgreen: "228b22",
fuchsia: "f0f",
gainsboro: "dcdcdc",
ghostwhite: "f8f8ff",
gold: "ffd700",
goldenrod: "daa520",
gray: "808080",
green: "008000",
greenyellow: "adff2f",
grey: "808080",
honeydew: "f0fff0",
hotpink: "ff69b4",
indianred: "cd5c5c",
indigo: "4b0082",
ivory: "fffff0",
khaki: "f0e68c",
lavender: "e6e6fa",
lavenderblush: "fff0f5",
lawngreen: "7cfc00",
lemonchiffon: "fffacd",
lightblue: "add8e6",
lightcoral: "f08080",
lightcyan: "e0ffff",
lightgoldenrodyellow: "fafad2",
lightgray: "d3d3d3",
lightgreen: "90ee90",
lightgrey: "d3d3d3",
lightpink: "ffb6c1",
lightsalmon: "ffa07a",
lightseagreen: "20b2aa",
lightskyblue: "87cefa",
lightslategray: "789",
lightslategrey: "789",
lightsteelblue: "b0c4de",
lightyellow: "ffffe0",
lime: "0f0",
limegreen: "32cd32",
linen: "faf0e6",
magenta: "f0f",
maroon: "800000",
mediumaquamarine: "66cdaa",
mediumblue: "0000cd",
mediumorchid: "ba55d3",
mediumpurple: "9370db",
mediumseagreen: "3cb371",
mediumslateblue: "7b68ee",
mediumspringgreen: "00fa9a",
mediumturquoise: "48d1cc",
mediumvioletred: "c71585",
midnightblue: "191970",
mintcream: "f5fffa",
mistyrose: "ffe4e1",
moccasin: "ffe4b5",
navajowhite: "ffdead",
navy: "000080",
oldlace: "fdf5e6",
olive: "808000",
olivedrab: "6b8e23",
orange: "ffa500",
orangered: "ff4500",
orchid: "da70d6",
palegoldenrod: "eee8aa",
palegreen: "98fb98",
paleturquoise: "afeeee",
palevioletred: "db7093",
papayawhip: "ffefd5",
peachpuff: "ffdab9",
peru: "cd853f",
pink: "ffc0cb",
plum: "dda0dd",
powderblue: "b0e0e6",
purple: "800080",
rebeccapurple: "663399",
red: "f00",
rosybrown: "bc8f8f",
royalblue: "4169e1",
saddlebrown: "8b4513",
salmon: "fa8072",
sandybrown: "f4a460",
seagreen: "2e8b57",
seashell: "fff5ee",
sienna: "a0522d",
silver: "c0c0c0",
skyblue: "87ceeb",
slateblue: "6a5acd",
slategray: "708090",
slategrey: "708090",
snow: "fffafa",
springgreen: "00ff7f",
steelblue: "4682b4",
tan: "d2b48c",
teal: "008080",
thistle: "d8bfd8",
tomato: "ff6347",
turquoise: "40e0d0",
violet: "ee82ee",
wheat: "f5deb3",
white: "fff",
whitesmoke: "f5f5f5",
yellow: "ff0",
yellowgreen: "9acd32"
};
var hexNames = tinycolor.hexNames = flip(names);
function flip(o) {
var flipped = {};
for (var i in o) {
if (o.hasOwnProperty(i)) {
flipped[o[i]] = i;
}
}
return flipped;
}
function boundAlpha(a) {
a = parseFloat(a);
if (isNaN(a) || a < 0 || a > 1) {
a = 1;
}
return a;
}
function bound01(n, max) {
if (isOnePointZero(n))
n = "100%";
var processPercent = isPercentage(n);
n = Math.min(max, Math.max(0, parseFloat(n)));
if (processPercent) {
n = parseInt(n * max, 10) / 100;
}
if (Math.abs(n - max) < 0.000001) {
return 1;
}
return n % max / parseFloat(max);
}
function clamp01(val) {
return Math.min(1, Math.max(0, val));
}
function parseIntFromHex(val) {
return parseInt(val, 16);
}
function isOnePointZero(n) {
return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1;
}
function isPercentage(n) {
return typeof n === "string" && n.indexOf("%") != -1;
}
function pad2(c) {
return c.length == 1 ? "0" + c : "" + c;
}
function convertToPercentage(n) {
if (n <= 1) {
n = n * 100 + "%";
}
return n;
}
function convertDecimalToHex(d) {
return Math.round(parseFloat(d) * 255).toString(16);
}
function convertHexToDecimal(h) {
return parseIntFromHex(h) / 255;
}
var matchers = function() {
var CSS_INTEGER = "[-\\+]?\\d+%?";
var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
return {
CSS_UNIT: new RegExp(CSS_UNIT),
rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
};
}();
function isValidCSSUnit(color) {
return !!matchers.CSS_UNIT.exec(color);
}
function stringInputToObject(color) {
color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase();
var named = false;
if (names[color]) {
color = names[color];
named = true;
} else if (color == "transparent") {
return {
r: 0,
g: 0,
b: 0,
a: 0,
format: "name"
};
}
var match;
if (match = matchers.rgb.exec(color)) {
return {
r: match[1],
g: match[2],
b: match[3]
};
}
if (match = matchers.rgba.exec(color)) {
return {
r: match[1],
g: match[2],
b: match[3],
a: match[4]
};
}
if (match = matchers.hsl.exec(color)) {
return {
h: match[1],
s: match[2],
l: match[3]
};
}
if (match = matchers.hsla.exec(color)) {
return {
h: match[1],
s: match[2],
l: match[3],
a: match[4]
};
}
if (match = matchers.hsv.exec(color)) {
return {
h: match[1],
s: match[2],
v: match[3]
};
}
if (match = matchers.hsva.exec(color)) {
return {
h: match[1],
s: match[2],
v: match[3],
a: match[4]
};
}
if (match = matchers.hex8.exec(color)) {
return {
r: parseIntFromHex(match[1]),
g: parseIntFromHex(match[2]),
b: parseIntFromHex(match[3]),
a: convertHexToDecimal(match[4]),
format: named ? "name" : "hex8"
};
}
if (match = matchers.hex6.exec(color)) {
return {
r: parseIntFromHex(match[1]),
g: parseIntFromHex(match[2]),
b: parseIntFromHex(match[3]),
format: named ? "name" : "hex"
};
}
if (match = matchers.hex4.exec(color)) {
return {
r: parseIntFromHex(match[1] + "" + match[1]),
g: parseIntFromHex(match[2] + "" + match[2]),
b: parseIntFromHex(match[3] + "" + match[3]),
a: convertHexToDecimal(match[4] + "" + match[4]),
format: named ? "name" : "hex8"
};
}
if (match = matchers.hex3.exec(color)) {
return {
r: parseIntFromHex(match[1] + "" + match[1]),
g: parseIntFromHex(match[2] + "" + match[2]),
b: parseIntFromHex(match[3] + "" + match[3]),
format: named ? "name" : "hex"
};
}
return false;
}
function validateWCAG2Parms(parms) {
var level, size;
parms = parms || {
level: "AA",
size: "small"
};
level = (parms.level || "AA").toUpperCase();
size = (parms.size || "small").toLowerCase();
if (level !== "AA" && level !== "AAA") {
level = "AA";
}
if (size !== "small" && size !== "large") {
size = "small";
}
return {
level,
size
};
}
// ../../node_modules/.bun/@jimp+utils@1.6.0/node_modules/@jimp/utils/dist/esm/index.js
function clone2(image2) {
const newBitmap = {
width: image2.bitmap.width,
height: image2.bitmap.height,
data: Buffer.from(image2.bitmap.data)
};
return new image2.constructor(newBitmap);
}
function scan(image2, xArg, yArg, wArg, hArg, cbArg) {
let x;
let y;
let w;
let h;
let cb;
if (typeof xArg === "function") {
cb = xArg;
x = 0;
y = 0;
w = image2.bitmap.width;
h = image2.bitmap.height;
} else {
x = xArg;
if (typeof yArg !== "number")
throw new Error("y must be a number");
y = yArg;
if (typeof wArg !== "number")
throw new Error("w must be a number");
w = wArg;
if (typeof hArg !== "number")
throw new Error("h must be a number");
h = hArg;
if (typeof cbArg !== "function")
throw new Error("cb must be a function");
cb = cbArg;
}
x = Math.round(x);
y = Math.round(y);
w = Math.round(w);
h = Math.round(h);
const bound = cb.bind(image2);
for (let _y = y;_y < y + h; _y++) {
for (let _x = x;_x < x + w; _x++) {
const idx = image2.bitmap.width * _y + _x << 2;
bound(_x, _y, idx);
}
}
return image2;
}
function* scanIterator(image2, x, y, w, h) {
x = Math.round(x);
y = Math.round(y);
w = Math.round(w);
h = Math.round(h);
for (let _y = y;_y < y + h; _y++) {
for (let _x = x;_x < x + w; _x++) {
const idx = image2.bitmap.width * _y + _x << 2;
yield { x: _x, y: _y, idx, image: image2 };
}
}
}
function intToRGBA(i) {
if (typeof i !== "number") {
throw new Error("i must be a number");
}
const rgba = {
r: 0,
g: 0,
b: 0,
a: 0
};
rgba.r = Math.floor(i / Math.pow(256, 3));
rgba.g = Math.floor((i - rgba.r * Math.pow(256, 3)) / Math.pow(256, 2));
rgba.b = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2)) / Math.pow(256, 1));
rgba.a = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2) - rgba.b * Math.pow(256, 1)) / Math.pow(256, 0));
return rgba;
}
function colorDiff(rgba1, rgba2) {
const sq = (n) => Math.pow(n, 2);
const { max } = Math;
const maxVal = 255 * 255 * 3;
const rgba1A = "a" in rgba1 ? rgba1.a : 255;
const rgba2A = "a" in rgba2 ? rgba2.a : 255;
return (max(sq(rgba1.r - rgba2.r), sq(rgba1.r - rgba2.r - rgba1A + rgba2A)) + max(sq(rgba1.g - rgba2.g), sq(rgba1.g - rgba2.g - rgba1A + rgba2A)) + max(sq(rgba1.b - rgba2.b), sq(rgba1.b - rgba2.b - rgba1A + rgba2A))) / maxVal;
}
function limit255(n) {
n = Math.max(n, 0);
n = Math.min(n, 255);
return n;
}
function cssColorToHex(cssColor) {
if (typeof cssColor === "number") {
return cssColor;
}
return parseInt(tinycolor(cssColor).toHex8(), 16);
}
// ../../node_modules/.bun/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js
function encode2(image2, options = {}) {
scan({ bitmap: image2 }, 0, 0, image2.width, image2.height, function(_, __, index) {
const red = image2.data[index + 0];
const green = image2.data[index + 1];
const blue = image2.data[index + 2];
const alpha = image2.data[index + 3];
image2.data[index + 0] = alpha;
image2.data[index + 1] = blue;
image2.data[index + 2] = green;
image2.data[index + 3] = red;
});
return encode({ ...image2, ...options }).data;
}
function decode2(data, options) {
const result = decode(data, options);
scan({ bitmap: result }, 0, 0, result.width, result.height, function(_, __, index) {
const blue = result.data[index + 1];
const green = result.data[index + 2];
const red = result.data[index + 3];
result.data[index + 0] = red;
result.data[index + 1] = green;
result.data[index + 2] = blue;
result.data[index + 3] = 255;
});
return result;
}
function msBmp() {
return {
mime: "image/x-ms-bmp",
encode: encode2,
decode: decode2
};
}
function bmp() {
return {
mime: "image/bmp",
encode: encode2,
decode: decode2
};
}
// ../../node_modules/.bun/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js
var import_omggif = __toESM(require_omggif(), 1);
var import_gifwrap = __toESM(require_src(), 1);
function gif() {
return {
mime: "image/gif",
encode: async (bitmap) => {
const gif2 = new import_gifwrap.BitmapImage(bitmap);
import_gifwrap.GifUtil.quantizeDekker(gif2, 256);
const newFrame = new import_gifwrap.GifFrame(bitmap);
const gifCodec = new import_gifwrap.GifCodec;
const newGif = await gifCodec.encodeGif([newFrame], {});
return newGif.buffer;
},
decode: (data) => {
const gifObj = new import_omggif.default.GifReader(data);
const gifData = Buffer.alloc(gifObj.width * gifObj.height * 4);
gifObj.decodeAndBlitFrameRGBA(0, gifData);
return {
data: gifData,
width: gifObj.width,
height: gifObj.height
};
}
};
}
// ../../node_modules/.bun/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js
var import_jpeg_js = __toESM(require_jpeg_js(), 1);
function jpeg() {
return {
mime: "image/jpeg",
encode: (bitmap, { quality: quality2 = 100 } = {}) => import_jpeg_js.default.encode(bitmap, quality2).data,
decode: (data, options) => import_jpeg_js.default.decode(data, options)
};
}
// ../../node_modules/.bun/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js
var import_pngjs = __toESM(require_png(), 1);
// ../../node_modules/.bun/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/constants.js
var PNGFilterType;
(function(PNGFilterType2) {
PNGFilterType2[PNGFilterType2["AUTO"] = -1] = "AUTO";
PNGFilterType2[PNGFilterType2["NONE"] = 0] = "NONE";
PNGFilterType2[PNGFilterType2["SUB"] = 1] = "SUB";
PNGFilterType2[PNGFilterType2["UP"] = 2] = "UP";
PNGFilterType2[PNGFilterType2["AVERAGE"] = 3] = "AVERAGE";
PNGFilterType2[PNGFilterType2["PATH"] = 4] = "PATH";
})(PNGFilterType || (PNGFilterType = {}));
var PNGColorType;
(function(PNGColorType2) {
PNGColorType2[PNGColorType2["GRAYSCALE"] = 0] = "GRAYSCALE";
PNGColorType2[PNGColorType2["COLOR"] = 2] = "COLOR";
PNGColorType2[PNGColorType2["GRAYSCALE_ALPHA"] = 4] = "GRAYSCALE_ALPHA";
PNGColorType2[PNGColorType2["COLOR_ALPHA"] = 6] = "COLOR_ALPHA";
})(PNGColorType || (PNGColorType = {}));
// ../../node_modules/.bun/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js
function png() {
return {
mime: "image/png",
hasAlpha: true,
encode: (bitmap, { deflateLevel = 9, deflateStrategy = 3, filterType = PNGFilterType.AUTO, colorType, inputHasAlpha = true, ...options } = {}) => {
const png2 = new import_pngjs.PNG({
width: bitmap.width,
height: bitmap.height
});
png2.data = bitmap.data;
return import_pngjs.PNG.sync.write(png2, {
...options,
deflateLevel,
deflateStrategy,
filterType,
colorType: typeof colorType !== "undefined" ? colorType : inputHasAlpha ? PNGColorType.COLOR_ALPHA : PNGColorType.COLOR,
inputHasAlpha
});
},
decode: (data, options) => {
const result = import_pngjs.PNG.sync.read(data, options);
return {
data: result.data,
width: result.width,
height: result.height
};
}
};
}
// ../../node_modules/.bun/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js
var import_utif2 = __toESM(require_UTIF(), 1);
function getDimensionValue(dimension) {
if (typeof dimension === "number") {
return dimension;
}
if (dimension instanceof Uint8Array) {
return dimension[0];
}
if (typeof dimension[0] === "string") {
return parseInt(dimension[0]);
}
return dimension[0];
}
function tiff() {
return {
mime: "image/tiff",
encode: (bitmap) => {
const tiff2 = import_utif2.default.encodeImage(bitmap.data, bitmap.width, bitmap.height);
return Buffer.from(tiff2);
},
decode: (data) => {
const ifds = import_utif2.default.decode(data);
const page = ifds[0];
if (!page) {
throw new Error("No page found in TIFF");
}
if (!page.t256) {
throw new Error("No image width found in TIFF");
}
if (!page.t257) {
throw new Error("No image height found in TIFF");
}
ifds.forEach((ifd) => {
import_utif2.default.decodeImage(data, ifd);
});
const rgba = import_utif2.default.toRGBA8(page);
return {
data: Buffer.from(rgba),
width: getDimensionValue(page.t256),
height: getDimensionValue(page.t257)
};
}
};
}
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/external.js
var exports_external = {};
__export(exports_external, {
void: () => voidType,
util: () => util,
unknown: () => unknownType,
union: () => unionType,
undefined: () => undefinedType,
tuple: () => tupleType,
transformer: () => effectsType,
symbol: () => symbolType,
string: () => stringType,
strictObject: () => strictObjectType,
setErrorMap: () => setErrorMap,
set: () => setType,
record: () => recordType,
quotelessJson: () => quotelessJson,
promise: () => promiseType,
preprocess: () => preprocessType,
pipeline: () => pipelineType,
ostring: () => ostring,
optional: () => optionalType,
onumber: () => onumber,
oboolean: () => oboolean,
objectUtil: () => objectUtil,
object: () => objectType,
number: () => numberType,
nullable: () => nullableType,
null: () => nullType,
never: () => neverType,
nativeEnum: () => nativeEnumType,
nan: () => nanType,
map: () => mapType,
makeIssue: () => makeIssue,
literal: () => literalType,
lazy: () => lazyType,
late: () => late,
isValid: () => isValid2,
isDirty: () => isDirty,
isAsync: () => isAsync,
isAborted: () => isAborted,
intersection: () => intersectionType,
instanceof: () => instanceOfType,
getParsedType: () => getParsedType,
getErrorMap: () => getErrorMap,
function: () => functionType,
enum: () => enumType,
effect: () => effectsType,
discriminatedUnion: () => discriminatedUnionType,
defaultErrorMap: () => en_default,
datetimeRegex: () => datetimeRegex,
date: () => dateType,
custom: () => custom,
coerce: () => coerce,
boolean: () => booleanType,
bigint: () => bigIntType,
array: () => arrayType,
any: () => anyType,
addIssueToContext: () => addIssueToContext,
ZodVoid: () => ZodVoid,
ZodUnknown: () => ZodUnknown,
ZodUnion: () => ZodUnion,
ZodUndefined: () => ZodUndefined,
ZodType: () => ZodType,
ZodTuple: () => ZodTuple,
ZodTransformer: () => ZodEffects,
ZodSymbol: () => ZodSymbol,
ZodString: () => ZodString,
ZodSet: () => ZodSet,
ZodSchema: () => ZodType,
ZodRecord: () => ZodRecord,
ZodReadonly: () => ZodReadonly,
ZodPromise: () => ZodPromise,
ZodPipeline: () => ZodPipeline,
ZodParsedType: () => ZodParsedType,
ZodOptional: () => ZodOptional,
ZodObject: () => ZodObject,
ZodNumber: () => ZodNumber,
ZodNullable: () => ZodNullable,
ZodNull: () => ZodNull,
ZodNever: () => ZodNever,
ZodNativeEnum: () => ZodNativeEnum,
ZodNaN: () => ZodNaN,
ZodMap: () => ZodMap,
ZodLiteral: () => ZodLiteral,
ZodLazy: () => ZodLazy,
ZodIssueCode: () => ZodIssueCode,
ZodIntersection: () => ZodIntersection,
ZodFunction: () => ZodFunction,
ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
ZodError: () => ZodError,
ZodEnum: () => ZodEnum,
ZodEffects: () => ZodEffects,
ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
ZodDefault: () => ZodDefault,
ZodDate: () => ZodDate,
ZodCatch: () => ZodCatch,
ZodBranded: () => ZodBranded,
ZodBoolean: () => ZodBoolean,
ZodBigInt: () => ZodBigInt,
ZodArray: () => ZodArray,
ZodAny: () => ZodAny,
Schema: () => ZodType,
ParseStatus: () => ParseStatus,
OK: () => OK,
NEVER: () => NEVER,
INVALID: () => INVALID,
EMPTY_PATH: () => EMPTY_PATH,
DIRTY: () => DIRTY,
BRAND: () => BRAND
});
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/util.js
var util;
(function(util2) {
util2.assertEqual = (_) => {};
function assertIs(_arg) {}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error;
}
util2.assertNever = assertNever;
util2.arrayToEnum = (items) => {
const obj = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
util2.getValidEnumValues = (obj) => {
const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return util2.objectValues(filtered);
};
util2.objectValues = (obj) => {
return util2.objectKeys(obj).map(function(e) {
return obj[e];
});
};
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
keys.push(key);
}
}
return keys;
};
util2.find = (arr, checker) => {
for (const item of arr) {
if (checker(item))
return item;
}
return;
};
util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
}
util2.joinValues = joinValues;
util2.jsonStringifyReplacer = (_, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return {
...first,
...second
};
};
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
var getParsedType = (data) => {
const t = typeof data;
switch (t) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/ZodError.js
var ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
var quotelessJson = (obj) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
class ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, actualProto);
} else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
} else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
const firstEl = sub.path[0];
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
fieldErrors[firstEl].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
}
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/locales/en.js
var errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "bigint")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
var en_default = errorMap;
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/errors.js
var overrideErrorMap = en_default;
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
var makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== undefined) {
return {
...issueData,
path: fullPath,
message: issueData.message
};
}
let errorMessage = "";
const maps = errorMaps.filter((m) => !!m).slice().reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: errorMessage
};
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === en_default ? undefined : en_default
].filter((x) => !!x)
});
ctx.common.issues.push(issue);
}
class ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid")
this.value = "dirty";
}
abort() {
if (this.value !== "aborted")
this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted")
return INVALID;
if (s.status === "dirty")
status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted")
return INVALID;
if (value.status === "aborted")
return INVALID;
if (key.status === "dirty")
status.dirty();
if (value.status === "dirty")
status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
}
var INVALID = Object.freeze({
status: "aborted"
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid2 = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/types.js
class ParseInputLazyPath {
constructor(parent, value, path, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
this._key = key;
}
get path() {
if (!this._cachedPath.length) {
if (Array.isArray(this._key)) {
this._cachedPath.push(...this._path, ...this._key);
} else {
this._cachedPath.push(...this._path, this._key);
}
}
return this._cachedPath;
}
}
var handleResult = (ctx, result) => {
if (isValid2(result)) {
return { success: true, data: result.value };
} else {
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
return {
success: false,
get error() {
if (this._error)
return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
}
};
}
};
function processCreateParams(params) {
if (!params)
return {};
const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error)) {
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
}
if (errorMap2)
return { errorMap: errorMap2, description };
const customMap = (iss, ctx) => {
const { message } = params;
if (iss.code === "invalid_enum_value") {
return { message: message ?? ctx.defaultError };
}
if (typeof ctx.data === "undefined") {
return { message: message ?? required_error ?? ctx.defaultError };
}
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
return { message: message ?? invalid_type_error ?? ctx.defaultError };
};
return { errorMap: customMap, description };
}
class ZodType {
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus,
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) {
throw new Error("Synchronous parse encountered promise.");
}
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success)
return result.data;
throw result.error;
}
safeParse(data, params) {
const ctx = {
common: {
issues: [],
async: params?.async ?? false,
contextualErrorMap: params?.errorMap
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
"~validate"(data) {
const ctx = {
common: {
issues: [],
async: !!this["~standard"].async
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
if (!this["~standard"].async) {
try {
const result = this._parseSync({ data, path: [], parent: ctx });
return isValid2(result) ? {
value: result.value
} : {
issues: ctx.common.issues
};
} catch (err) {
if (err?.message?.toLowerCase()?.includes("encountered")) {
this["~standard"].async = true;
}
ctx.common = {
issues: [],
async: true
};
}
}
return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid2(result) ? {
value: result.value
} : {
issues: ctx.common.issues
});
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params?.errorMap,
async: true
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val);
} else {
return message;
}
};
return this._refinement((val, ctx) => {
const result = check(val);
const setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then((data) => {
if (!data) {
setError();
return false;
} else {
return true;
}
});
}
if (!result) {
setError();
return false;
} else {
return true;
}
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else {
return true;
}
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def) {
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data) => this["~validate"](data)
};
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(undefined).success;
}
isNullable() {
return this.safeParse(null).success;
}
}
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let secondsRegexSource = `[0-5]\\d`;
if (args.precision) {
secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
} else if (args.precision == null) {
secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
}
const secondsQuantifier = args.precision ? "+" : "?";
return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset)
opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt))
return false;
try {
const [header] = jwt.split(".");
if (!header)
return false;
const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
const decoded = JSON.parse(atob(base64));
if (typeof decoded !== "object" || decoded === null)
return false;
if ("typ" in decoded && decoded?.typ !== "JWT")
return false;
if (!decoded.alg)
return false;
if (alg && decoded.alg !== alg)
return false;
return true;
} catch {
return false;
}
}
function isValidCidr(ip, version) {
if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
return true;
}
return false;
}
class ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
});
return INVALID;
}
const status = new ParseStatus;
let ctx = undefined;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
} else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
}
status.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "url") {
try {
new URL(input.data);
} catch {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "regex") {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "trim") {
input.data = input.data.trim();
} else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message
});
status.dirty();
}
} else if (check.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
} else if (check.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
} else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "datetime") {
const regex = datetimeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if (check.kind === "date") {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
});
status.dirty();
}
} else if (check.kind === "time") {
const regex = timeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
});
status.dirty();
}
} else if (check.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "jwt") {
if (!isValidJWT(input.data, check.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cidr") {
if (!isValidCidr(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64url") {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message)
});
}
_addCheck(check) {
return new ZodString({
...this._def,
checks: [...this._def.checks, check]
});
}
email(message) {
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
}
url(message) {
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
}
emoji(message) {
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
}
uuid(message) {
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
}
nanoid(message) {
return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
}
cuid(message) {
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
}
cuid2(message) {
return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
}
ulid(message) {
return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
}
base64(message) {
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
}
base64url(message) {
return this._addCheck({
kind: "base64url",
...errorUtil.errToObj(message)
});
}
jwt(options) {
return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
cidr(options) {
return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
}
datetime(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
}
return this._addCheck({
kind: "datetime",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
offset: options?.offset ?? false,
local: options?.local ?? false,
...errorUtil.errToObj(options?.message)
});
}
date(message) {
return this._addCheck({ kind: "date", message });
}
time(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "time",
precision: null,
message: options
});
}
return this._addCheck({
kind: "time",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
...errorUtil.errToObj(options?.message)
});
}
duration(message) {
return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options?.position,
...errorUtil.errToObj(options?.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isCIDR() {
return !!this._def.checks.find((ch) => ch.kind === "cidr");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get isBase64url() {
return !!this._def.checks.find((ch) => ch.kind === "base64url");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
}
ZodString.create = (params) => {
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / 10 ** decCount;
}
class ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) {
input.data = Number(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = undefined;
const status = new ParseStatus;
for (const check of this._def.checks) {
if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status.dirty();
}
} else if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodNumber({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new ZodNumber({
...this._def,
checks: [...this._def.checks, check]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null;
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
return true;
} else if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
}
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
class ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
try {
input.data = BigInt(input.data);
} catch {
return this._getInvalidInput(input);
}
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
return this._getInvalidInput(input);
}
let ctx = undefined;
const status = new ParseStatus;
for (const check of this._def.checks) {
if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType
});
return INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodBigInt({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new ZodBigInt({
...this._def,
checks: [...this._def.checks, check]
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
}
ZodBigInt.create = (params) => {
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
class ZodBoolean extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
class ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
});
return INVALID;
}
if (Number.isNaN(input.data.getTime())) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date
});
return INVALID;
}
const status = new ParseStatus;
let ctx = undefined;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check) {
return new ZodDate({
...this._def,
checks: [...this._def.checks, check]
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
}
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: params?.coerce || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
class ZodSymbol extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
};
class ZodUndefined extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
};
class ZodNull extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
};
class ZodAny extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
}
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
class ZodUnknown extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
}
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
class ZodNever extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
}
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
class ZodVoid extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
};
class ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : undefined,
maximum: tooBig ? def.exactLength.value : undefined,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) {
return Promise.all([...ctx.data].map((item, i) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
})).then((result2) => {
return ParseStatus.mergeArray(status, result2);
});
}
const result = [...ctx.data].map((item, i) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new ZodArray({
...this._def,
minLength: { value: minLength, message: errorUtil.toString(message) }
});
}
max(maxLength, message) {
return new ZodArray({
...this._def,
maxLength: { value: maxLength, message: errorUtil.toString(message) }
});
}
length(len, message) {
return new ZodArray({
...this._def,
exactLength: { value: len, message: errorUtil.toString(message) }
});
}
nonempty(message) {
return this.min(1, message);
}
}
ZodArray.create = (schema, params) => {
return new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
};
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: () => newShape
});
} else if (schema instanceof ZodArray) {
return new ZodArray({
...schema._def,
type: deepPartialify(schema.element)
});
} else if (schema instanceof ZodOptional) {
return ZodOptional.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodNullable) {
return ZodNullable.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodTuple) {
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
} else {
return schema;
}
}
class ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
this.nonstrict = this.passthrough;
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
this._cached = { shape, keys };
return this._cached;
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key in ctx.data) {
if (!shapeKeys.includes(key)) {
extraKeys.push(key);
}
}
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") {
for (const key of extraKeys) {
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] }
});
}
} else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip") {} else {
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
}
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
}
if (ctx.common.async) {
return Promise.resolve().then(async () => {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new ZodObject({
...this._def,
unknownKeys: "strict",
...message !== undefined ? {
errorMap: (issue, ctx) => {
const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message: errorUtil.errToObj(message).message ?? defaultError
};
return {
message: defaultError
};
}
} : {}
});
}
strip() {
return new ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
extend(augmentation) {
return new ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation
})
});
}
merge(merging) {
const merged = new ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape()
}),
typeName: ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
setKey(key, schema) {
return this.augment({ [key]: schema });
}
catchall(index) {
return new ZodObject({
...this._def,
catchall: index
});
}
pick(mask) {
const shape = {};
for (const key of util.objectKeys(mask)) {
if (mask[key] && this.shape[key]) {
shape[key] = this.shape[key];
}
}
return new ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
const shape = {};
for (const key of util.objectKeys(this.shape)) {
if (!mask[key]) {
shape[key] = this.shape[key];
}
}
return new ZodObject({
...this._def,
shape: () => shape
});
}
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
} else {
newShape[key] = fieldSchema.optional();
}
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
if (mask && !mask[key]) {
newShape[key] = this.shape[key];
} else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = newField._def.innerType;
}
newShape[key] = newField;
}
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
}
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
class ZodUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) {
if (result.result.status === "valid") {
return result.result;
}
}
for (const result of results) {
if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
}
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
if (ctx.common.async) {
return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
} else {
let dirty = undefined;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid") {
return result;
} else if (result.status === "dirty" && !dirty) {
dirty = { result, ctx: childCtx };
}
if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues2) => new ZodError(issues2));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
}
ZodUnion.create = (types2, params) => {
return new ZodUnion({
options: types2,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
};
var getDiscriminator = (type) => {
if (type instanceof ZodLazy) {
return getDiscriminator(type.schema);
} else if (type instanceof ZodEffects) {
return getDiscriminator(type.innerType());
} else if (type instanceof ZodLiteral) {
return [type.value];
} else if (type instanceof ZodEnum) {
return type.options;
} else if (type instanceof ZodNativeEnum) {
return util.objectValues(type.enum);
} else if (type instanceof ZodDefault) {
return getDiscriminator(type._def.innerType);
} else if (type instanceof ZodUndefined) {
return [undefined];
} else if (type instanceof ZodNull) {
return [null];
} else if (type instanceof ZodOptional) {
return [undefined, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodNullable) {
return [null, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodBranded) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodReadonly) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodCatch) {
return getDiscriminator(type._def.innerType);
} else {
return [];
}
};
class ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) {
return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
} else {
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
static create(discriminator, options, params) {
const optionsMap = new Map;
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) {
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
}
for (const value of discriminatorValues) {
if (optionsMap.has(value)) {
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
}
optionsMap.set(value, type);
}
}
return new ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
}
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) {
return { valid: true, data: a };
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a, ...b };
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return { valid: false };
}
newObj[key] = sharedValue.data;
}
return { valid: true, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) {
return { valid: false };
}
const newArray = [];
for (let index = 0;index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) {
return { valid: false };
}
newArray.push(sharedValue.data);
}
return { valid: true, data: newArray };
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
return { valid: true, data: a };
} else {
return { valid: false };
}
}
class ZodIntersection extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
return INVALID;
}
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
});
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
status.dirty();
}
return { status: status.value, value: merged.data };
};
if (ctx.common.async) {
return Promise.all([
this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}),
this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})
]).then(([left, right]) => handleParsed(left, right));
} else {
return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
}
}
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
};
class ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema)
return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x) => !!x);
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
} else {
return ParseStatus.mergeArray(status, items);
}
}
get items() {
return this._def.items;
}
rest(rest) {
return new ZodTuple({
...this._def,
rest
});
}
}
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params)
});
};
class ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) {
pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (ctx.common.async) {
return ParseStatus.mergeObjectAsync(status, pairs);
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) {
return new ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
}
return new ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
}
class ZodMap extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
};
});
if (ctx.common.async) {
const finalMap = new Map;
return Promise.resolve().then(async () => {
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
});
} else {
const finalMap = new Map;
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
}
}
}
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
};
class ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements2) {
const parsedSet = new Set;
for (const element of elements2) {
if (element.status === "aborted")
return INVALID;
if (element.status === "dirty")
status.dirty();
parsedSet.add(element.value);
}
return { status: status.value, value: parsedSet };
}
const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
if (ctx.common.async) {
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
} else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new ZodSet({
...this._def,
minSize: { value: minSize, message: errorUtil.toString(message) }
});
}
max(maxSize, message) {
return new ZodSet({
...this._def,
maxSize: { value: maxSize, message: errorUtil.toString(message) }
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
}
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
};
class ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function(...args) {
const error = new ZodError([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
return parsedReturns;
});
} else {
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
}
class ZodLazy extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
}
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
};
class ZodLiteral extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
}
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
};
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
class ZodEnum extends ZodType {
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) {
this._cache = new Set(this._def.values);
}
if (!this._cache.has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
extract(values, newDef = this._def) {
return ZodEnum.create(values, {
...this._def,
...newDef
});
}
exclude(values, newDef = this._def) {
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
...this._def,
...newDef
});
}
}
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) {
this._cache = new Set(util.getValidEnumValues(this._def.values));
}
if (!this._cache.has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
}
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
};
class ZodPromise extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
}
ZodPromise.create = (schema, params) => {
return new ZodPromise({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
};
class ZodEffects extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
} else {
status.dirty();
}
},
get path() {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) {
return Promise.resolve(processed).then(async (processed2) => {
if (status.value === "aborted")
return INVALID;
const result = await this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
});
} else {
if (status.value === "aborted")
return INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) {
return Promise.resolve(result);
}
if (result instanceof Promise) {
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
}
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
executeRefinement(inner.value);
return { status: status.value, value: inner.value };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
return executeRefinement(inner.value).then(() => {
return { status: status.value, value: inner.value };
});
});
}
}
if (effect.type === "transform") {
if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid2(base))
return INVALID;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) {
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
}
return { status: status.value, value: result };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
if (!isValid2(base))
return INVALID;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
status: status.value,
value: result
}));
});
}
}
util.assertNever(effect);
}
}
ZodEffects.create = (schema, effect, params) => {
return new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects({
schema,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
};
class ZodOptional extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(undefined);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
}
ZodOptional.create = (type, params) => {
return new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
};
class ZodNullable extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
}
ZodNullable.create = (type, params) => {
return new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
};
class ZodDefault extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) {
data = this._def.defaultValue();
}
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
}
ZodDefault.create = (type, params) => {
return new ZodDefault({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
...processCreateParams(params)
});
};
class ZodCatch extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx
}
});
if (isAsync(result)) {
return result.then((result2) => {
return {
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
});
} else {
return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
}
removeCatch() {
return this._def.innerType;
}
}
ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params)
});
};
class ZodNaN extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return { status: "valid", value: input.data };
}
}
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
};
var BRAND = Symbol("zod_brand");
class ZodBranded extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
}
class ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
} else {
return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
};
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else {
return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
}
static create(a, b) {
return new ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
}
class ZodReadonly extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze = (data) => {
if (isValid2(data)) {
data.value = Object.freeze(data.value);
}
return data;
};
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
}
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
};
function cleanParams(params, data) {
const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
const p2 = typeof p === "string" ? { message: p } : p;
return p2;
}
function custom(check, _params = {}, fatal) {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
const r = check(data);
if (r instanceof Promise) {
return r.then((r2) => {
if (!r2) {
const params = cleanParams(_params, data);
const _fatal = params.fatal ?? fatal ?? true;
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
}
});
}
if (!r) {
const params = cleanParams(_params, data);
const _fatal = params.fatal ?? fatal ?? true;
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
}
return;
});
return ZodAny.create();
}
var late = {
object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var coerce = {
string: (arg) => ZodString.create({ ...arg, coerce: true }),
number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
boolean: (arg) => ZodBoolean.create({
...arg,
coerce: true
}),
bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
date: (arg) => ZodDate.create({ ...arg, coerce: true })
};
var NEVER = INVALID;
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/index.js
var zod_default = exports_external;
// ../../node_modules/.bun/@jimp+types@1.6.0/node_modules/@jimp/types/dist/esm/index.js
var Edge;
(function(Edge2) {
Edge2[Edge2["EXTEND"] = 1] = "EXTEND";
Edge2[Edge2["WRAP"] = 2] = "WRAP";
Edge2[Edge2["CROP"] = 3] = "CROP";
})(Edge || (Edge = {}));
var JimpClassSchema = exports_external.object({
bitmap: exports_external.object({
data: exports_external.union([exports_external.instanceof(Buffer), exports_external.instanceof(Uint8Array)]),
width: exports_external.number(),
height: exports_external.number()
})
});
// ../../node_modules/.bun/@jimp+plugin-blit@1.6.0/node_modules/@jimp/plugin-blit/dist/esm/index.js
var BlitOptionsSchemaComplex = exports_external.object({
src: JimpClassSchema,
x: exports_external.number().optional(),
y: exports_external.number().optional(),
srcX: exports_external.number().optional(),
srcY: exports_external.number().optional(),
srcW: exports_external.number().optional(),
srcH: exports_external.number().optional()
});
var BlitOptionsSchema = exports_external.union([JimpClassSchema, BlitOptionsSchemaComplex]);
var methods = {
blit(image2, options) {
const parsed = BlitOptionsSchema.parse(options);
let {
src,
x = 0,
y = 0,
srcX = 0,
srcY = 0,
srcW = src.bitmap.width,
srcH = src.bitmap.height
} = "bitmap" in parsed ? { src: parsed } : parsed;
if (!("bitmap" in src)) {
throw new Error("The source must be a Jimp image");
}
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("x and y must be numbers");
}
x = Math.round(x);
y = Math.round(y);
srcX = Math.round(srcX);
srcY = Math.round(srcY);
srcW = Math.round(srcW);
srcH = Math.round(srcH);
const maxWidth = image2.bitmap.width;
const maxHeight = image2.bitmap.height;
scan(src, srcX, srcY, srcW, srcH, function(sx, sy, idx) {
const xOffset = x + sx - srcX;
const yOffset = y + sy - srcY;
if (xOffset >= 0 && yOffset >= 0 && maxWidth - xOffset > 0 && maxHeight - yOffset > 0) {
const dstIdx = image2.getPixelIndex(xOffset, yOffset);
const srcColor = {
r: src.bitmap.data[idx] || 0,
g: src.bitmap.data[idx + 1] || 0,
b: src.bitmap.data[idx + 2] || 0,
a: src.bitmap.data[idx + 3] || 0
};
const dst = {
r: image2.bitmap.data[dstIdx] || 0,
g: image2.bitmap.data[dstIdx + 1] || 0,
b: image2.bitmap.data[dstIdx + 2] || 0,
a: image2.bitmap.data[dstIdx + 3] || 0
};
image2.bitmap.data[dstIdx] = (srcColor.a * (srcColor.r - dst.r) - dst.r + 255 >> 8) + dst.r;
image2.bitmap.data[dstIdx + 1] = (srcColor.a * (srcColor.g - dst.g) - dst.g + 255 >> 8) + dst.g;
image2.bitmap.data[dstIdx + 2] = (srcColor.a * (srcColor.b - dst.b) - dst.b + 255 >> 8) + dst.b;
image2.bitmap.data[dstIdx + 3] = limit255(dst.a + srcColor.a);
}
});
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-blur@1.6.0/node_modules/@jimp/plugin-blur/dist/esm/blur-tables.js
var mulTable = [
1,
57,
41,
21,
203,
34,
97,
73,
227,
91,
149,
62,
105,
45,
39,
137,
241,
107,
3,
173,
39,
71,
65,
238,
219,
101,
187,
87,
81,
151,
141,
133,
249,
117,
221,
209,
197,
187,
177,
169,
5,
153,
73,
139,
133,
127,
243,
233,
223,
107,
103,
99,
191,
23,
177,
171,
165,
159,
77,
149,
9,
139,
135,
131,
253,
245,
119,
231,
224,
109,
211,
103,
25,
195,
189,
23,
45,
175,
171,
83,
81,
79,
155,
151,
147,
9,
141,
137,
67,
131,
129,
251,
123,
30,
235,
115,
113,
221,
217,
53,
13,
51,
50,
49,
193,
189,
185,
91,
179,
175,
43,
169,
83,
163,
5,
79,
155,
19,
75,
147,
145,
143,
35,
69,
17,
67,
33,
65,
255,
251,
247,
243,
239,
59,
29,
229,
113,
111,
219,
27,
213,
105,
207,
51,
201,
199,
49,
193,
191,
47,
93,
183,
181,
179,
11,
87,
43,
85,
167,
165,
163,
161,
159,
157,
155,
77,
19,
75,
37,
73,
145,
143,
141,
35,
138,
137,
135,
67,
33,
131,
129,
255,
63,
250,
247,
61,
121,
239,
237,
117,
29,
229,
227,
225,
111,
55,
109,
216,
213,
211,
209,
207,
205,
203,
201,
199,
197,
195,
193,
48,
190,
47,
93,
185,
183,
181,
179,
178,
176,
175,
173,
171,
85,
21,
167,
165,
41,
163,
161,
5,
79,
157,
78,
154,
153,
19,
75,
149,
74,
147,
73,
144,
143,
71,
141,
140,
139,
137,
17,
135,
134,
133,
66,
131,
65,
129,
1
];
var shgTable = [
0,
9,
10,
10,
14,
12,
14,
14,
16,
15,
16,
15,
16,
15,
15,
17,
18,
17,
12,
18,
16,
17,
17,
19,
19,
18,
19,
18,
18,
19,
19,
19,
20,
19,
20,
20,
20,
20,
20,
20,
15,
20,
19,
20,
20,
20,
21,
21,
21,
20,
20,
20,
21,
18,
21,
21,
21,
21,
20,
21,
17,
21,
21,
21,
22,
22,
21,
22,
22,
21,
22,
21,
19,
22,
22,
19,
20,
22,
22,
21,
21,
21,
22,
22,
22,
18,
22,
22,
21,
22,
22,
23,
22,
20,
23,
22,
22,
23,
23,
21,
19,
21,
21,
21,
23,
23,
23,
22,
23,
23,
21,
23,
22,
23,
18,
22,
23,
20,
22,
23,
23,
23,
21,
22,
20,
22,
21,
22,
24,
24,
24,
24,
24,
22,
21,
24,
23,
23,
24,
21,
24,
23,
24,
22,
24,
24,
22,
24,
24,
22,
23,
24,
24,
24,
20,
23,
22,
23,
24,
24,
24,
24,
24,
24,
24,
23,
21,
23,
22,
23,
24,
24,
24,
22,
24,
24,
24,
23,
22,
24,
24,
25,
23,
25,
25,
23,
24,
25,
25,
24,
22,
25,
25,
25,
24,
23,
24,
25,
25,
25,
25,
25,
25,
25,
25,
25,
25,
25,
25,
23,
25,
23,
24,
25,
25,
25,
25,
25,
25,
25,
25,
25,
24,
22,
25,
25,
23,
25,
25,
20,
24,
25,
24,
25,
25,
22,
24,
25,
24,
25,
24,
25,
25,
24,
25,
25,
25,
25,
22,
25,
25,
25,
24,
25,
24,
25,
18
];
// ../../node_modules/.bun/@jimp+plugin-blur@1.6.0/node_modules/@jimp/plugin-blur/dist/esm/index.js
var methods2 = {
blur(image2, r) {
if (typeof r !== "number") {
throw new Error("r must be a number");
}
if (r < 1) {
throw new Error("r must be greater than 0");
}
let rsum;
let gsum;
let bsum;
let asum;
let x;
let y;
let i;
let p;
let p1;
let p2;
let yp;
let yi;
let yw;
const wm = image2.bitmap.width - 1;
const hm = image2.bitmap.height - 1;
const rad1 = r + 1;
const mulSum = mulTable[r];
const shgSum = shgTable[r];
const red = [];
const green = [];
const blue = [];
const alpha = [];
const vmin = [];
const vmax = [];
let iterations = 2;
while (iterations-- > 0) {
yi = 0;
yw = 0;
for (y = 0;y < image2.bitmap.height; y++) {
rsum = image2.bitmap.data[yw] * rad1;
gsum = image2.bitmap.data[yw + 1] * rad1;
bsum = image2.bitmap.data[yw + 2] * rad1;
asum = image2.bitmap.data[yw + 3] * rad1;
for (i = 1;i <= r; i++) {
p = yw + ((i > wm ? wm : i) << 2);
rsum += image2.bitmap.data[p++];
gsum += image2.bitmap.data[p++];
bsum += image2.bitmap.data[p++];
asum += image2.bitmap.data[p];
}
for (x = 0;x < image2.bitmap.width; x++) {
red[yi] = rsum;
green[yi] = gsum;
blue[yi] = bsum;
alpha[yi] = asum;
if (y === 0) {
vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2;
vmax[x] = (p = x - r) > 0 ? p << 2 : 0;
}
p1 = yw + vmin[x];
p2 = yw + vmax[x];
rsum += image2.bitmap.data[p1++] - image2.bitmap.data[p2++];
gsum += image2.bitmap.data[p1++] - image2.bitmap.data[p2++];
bsum += image2.bitmap.data[p1++] - image2.bitmap.data[p2++];
asum += image2.bitmap.data[p1] - image2.bitmap.data[p2++];
yi++;
}
yw += image2.bitmap.width << 2;
}
for (x = 0;x < image2.bitmap.width; x++) {
yp = x;
rsum = red[yp] * rad1;
gsum = green[yp] * rad1;
bsum = blue[yp] * rad1;
asum = alpha[yp] * rad1;
for (i = 1;i <= r; i++) {
yp += i > hm ? 0 : image2.bitmap.width;
rsum += red[yp];
gsum += green[yp];
bsum += blue[yp];
asum += alpha[yp];
}
yi = x << 2;
for (y = 0;y < image2.bitmap.height; y++) {
image2.bitmap.data[yi] = limit255(rsum * mulSum >>> shgSum);
image2.bitmap.data[yi + 1] = limit255(gsum * mulSum >>> shgSum);
image2.bitmap.data[yi + 2] = limit255(bsum * mulSum >>> shgSum);
image2.bitmap.data[yi + 3] = limit255(asum * mulSum >>> shgSum);
if (x === 0) {
vmin[y] = ((p = y + rad1) < hm ? p : hm) * image2.bitmap.width;
vmax[y] = (p = y - r) > 0 ? p * image2.bitmap.width : 0;
}
p1 = x + vmin[y];
p2 = x + vmax[y];
rsum += red[p1] - red[p2];
gsum += green[p1] - green[p2];
bsum += blue[p1] - blue[p2];
asum += alpha[p1] - alpha[p2];
yi += image2.bitmap.width << 2;
}
}
}
return image2;
},
gaussian(image2, r) {
if (typeof r !== "number") {
throw new Error("r must be a number");
}
if (r < 1) {
throw new Error("r must be greater than 0");
}
const rs = Math.ceil(r * 2.57);
const range = rs * 2 + 1;
const rr2 = r * r * 2;
const rr2pi = rr2 * Math.PI;
const weights = [];
for (let y = 0;y < range; y++) {
const weightsRow = [];
for (let x = 0;x < range; x++) {
const dsq = (x - rs) ** 2 + (y - rs) ** 2;
weightsRow[x] = Math.exp(-dsq / rr2) / rr2pi;
}
weights.push(weightsRow);
}
for (let y = 0;y < image2.bitmap.height; y++) {
for (let x = 0;x < image2.bitmap.width; x++) {
let red = 0;
let green = 0;
let blue = 0;
let alpha = 0;
let wsum = 0;
for (let iy = 0;iy < range; iy++) {
for (let ix = 0;ix < range; ix++) {
const x1 = Math.min(image2.bitmap.width - 1, Math.max(0, ix + x - rs));
const y1 = Math.min(image2.bitmap.height - 1, Math.max(0, iy + y - rs));
const weight = weights[iy][ix];
const idx2 = y1 * image2.bitmap.width + x1 << 2;
red += image2.bitmap.data[idx2] * weight;
green += image2.bitmap.data[idx2 + 1] * weight;
blue += image2.bitmap.data[idx2 + 2] * weight;
alpha += image2.bitmap.data[idx2 + 3] * weight;
wsum += weight;
}
const idx = y * image2.bitmap.width + x << 2;
image2.bitmap.data[idx] = Math.round(red / wsum);
image2.bitmap.data[idx + 1] = Math.round(green / wsum);
image2.bitmap.data[idx + 2] = Math.round(blue / wsum);
image2.bitmap.data[idx + 3] = Math.round(alpha / wsum);
}
}
}
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-circle@1.6.0/node_modules/@jimp/plugin-circle/dist/esm/index.js
var CircleOptionsSchema = exports_external.object({
x: exports_external.number().optional(),
y: exports_external.number().optional(),
radius: exports_external.number().min(0).optional()
});
var methods3 = {
circle(image2, options = {}) {
const parsed = CircleOptionsSchema.parse(options);
const radius = parsed.radius || (image2.bitmap.width > image2.bitmap.height ? image2.bitmap.height : image2.bitmap.width) / 2;
const center = {
x: typeof parsed.x === "number" ? parsed.x : image2.bitmap.width / 2,
y: typeof parsed.y === "number" ? parsed.y : image2.bitmap.height / 2
};
image2.scan((x, y, idx) => {
const curR = Math.sqrt(Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2));
if (radius - curR <= 0) {
image2.bitmap.data[idx + 3] = 0;
} else if (radius - curR < 1) {
image2.bitmap.data[idx + 3] = 255 * (radius - curR);
}
});
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-color@1.6.0/node_modules/@jimp/plugin-color/dist/esm/index.js
var ConvolutionMatrixSchema = exports_external.array(exports_external.number()).min(1).array();
var ConvolutionComplexOptionsSchema = exports_external.object({
kernel: ConvolutionMatrixSchema,
edgeHandling: exports_external.nativeEnum(Edge).optional()
});
var ConvolutionOptionsSchema = exports_external.union([
ConvolutionMatrixSchema,
ConvolutionComplexOptionsSchema
]);
var ConvoluteComplexOptionsSchema = exports_external.object({
kernel: ConvolutionMatrixSchema,
x: exports_external.number().optional(),
y: exports_external.number().optional(),
w: exports_external.number().optional(),
h: exports_external.number().optional()
});
var ConvoluteOptionsSchema = exports_external.union([
ConvolutionMatrixSchema,
ConvoluteComplexOptionsSchema
]);
var PixelateSize = exports_external.number().min(1).max(Infinity);
var PixelateComplexOptionsSchema = exports_external.object({
size: PixelateSize,
x: exports_external.number().optional(),
y: exports_external.number().optional(),
w: exports_external.number().optional(),
h: exports_external.number().optional()
});
var PixelateOptionsSchema = exports_external.union([
PixelateSize,
PixelateComplexOptionsSchema
]);
function applyKernel(image2, kernel, x, y) {
const value = [0, 0, 0, 0];
const size = (kernel.length - 1) / 2;
for (let kx = 0;kx < kernel.length; kx += 1) {
for (let ky = 0;ky < kernel[kx].length; ky += 1) {
const idx = image2.getPixelIndex(x + kx - size, y + ky - size);
value[0] += image2.bitmap.data[idx] * kernel[kx][ky];
value[1] += image2.bitmap.data[idx + 1] * kernel[kx][ky];
value[2] += image2.bitmap.data[idx + 2] * kernel[kx][ky];
value[3] += image2.bitmap.data[idx + 3] * kernel[kx][ky];
}
}
return value;
}
function mix(clr, clr2, p = 50) {
return {
r: (clr2.r - clr.r) * (p / 100) + clr.r,
g: (clr2.g - clr.g) * (p / 100) + clr.g,
b: (clr2.b - clr.b) * (p / 100) + clr.b
};
}
var HueActionSchema = exports_external.object({
apply: exports_external.literal("hue"),
params: exports_external.tuple([exports_external.number().min(-360).max(360)])
});
var SpinActionSchema = exports_external.object({
apply: exports_external.literal("spin"),
params: exports_external.tuple([exports_external.number().min(-360).max(360)])
});
var LightenActionSchema = exports_external.object({
apply: exports_external.literal("lighten"),
params: exports_external.tuple([exports_external.number().min(0).max(100)]).optional()
});
var RGBColorSchema = exports_external.object({
r: exports_external.number().min(0).max(255),
g: exports_external.number().min(0).max(255),
b: exports_external.number().min(0).max(255)
});
var MixActionSchema = exports_external.object({
apply: exports_external.literal("mix"),
params: exports_external.union([
exports_external.tuple([RGBColorSchema]),
exports_external.tuple([RGBColorSchema, exports_external.number().min(0).max(100)])
])
});
var TintActionSchema = exports_external.object({
apply: exports_external.literal("tint"),
params: exports_external.tuple([exports_external.number().min(0).max(100)]).optional()
});
var ShadeActionSchema = exports_external.object({
apply: exports_external.literal("shade"),
params: exports_external.tuple([exports_external.number().min(0).max(100)]).optional()
});
var XorActionSchema = exports_external.object({
apply: exports_external.literal("xor"),
params: exports_external.tuple([RGBColorSchema])
});
var RedActionSchema = exports_external.object({
apply: exports_external.literal("red"),
params: exports_external.tuple([exports_external.number().min(-255).max(255)])
});
var GreenActionSchema = exports_external.object({
apply: exports_external.literal("green"),
params: exports_external.tuple([exports_external.number().min(-255).max(255)])
});
var BlueActionSchema = exports_external.object({
apply: exports_external.literal("blue"),
params: exports_external.tuple([exports_external.number().min(-255).max(255)])
});
var BrightenActionSchema = exports_external.object({
apply: exports_external.literal("brighten"),
params: exports_external.tuple([exports_external.number().min(0).max(100)]).optional()
});
var DarkenActionSchema = exports_external.object({
apply: exports_external.literal("darken"),
params: exports_external.tuple([exports_external.number().min(0).max(100)]).optional()
});
var DesaturateActionSchema = exports_external.object({
apply: exports_external.literal("desaturate"),
params: exports_external.tuple([exports_external.number().min(0).max(100)]).optional()
});
var SaturateActionSchema = exports_external.object({
apply: exports_external.literal("saturate"),
params: exports_external.tuple([exports_external.number().min(0).max(100)]).optional()
});
var GrayscaleActionSchema = exports_external.object({
apply: exports_external.literal("greyscale"),
params: exports_external.tuple([]).optional()
});
var ColorActionNameSchema = exports_external.union([
HueActionSchema,
SpinActionSchema,
LightenActionSchema,
MixActionSchema,
TintActionSchema,
ShadeActionSchema,
XorActionSchema,
RedActionSchema,
GreenActionSchema,
BlueActionSchema,
BrightenActionSchema,
DarkenActionSchema,
DesaturateActionSchema,
SaturateActionSchema,
GrayscaleActionSchema
]);
var ColorActionName = Object.freeze({
LIGHTEN: "lighten",
BRIGHTEN: "brighten",
DARKEN: "darken",
DESATURATE: "desaturate",
SATURATE: "saturate",
GREYSCALE: "greyscale",
SPIN: "spin",
HUE: "hue",
MIX: "mix",
TINT: "tint",
SHADE: "shade",
XOR: "xor",
RED: "red",
GREEN: "green",
BLUE: "blue"
});
function histogram(image2) {
const histogram2 = {
r: new Array(256).fill(0),
g: new Array(256).fill(0),
b: new Array(256).fill(0)
};
image2.scan((_, __, index) => {
histogram2.r[image2.bitmap.data[index + 0]]++;
histogram2.g[image2.bitmap.data[index + 1]]++;
histogram2.b[image2.bitmap.data[index + 2]]++;
});
return histogram2;
}
var normalizeValue = function(value, min, max) {
return (value - min) * 255 / (max - min);
};
var getBounds = function(histogramChannel) {
return [
histogramChannel.findIndex((value) => value > 0),
255 - histogramChannel.slice().reverse().findIndex((value) => value > 0)
];
};
var methods4 = {
normalize(image2) {
const h = histogram(image2);
const bounds = {
r: getBounds(h.r),
g: getBounds(h.g),
b: getBounds(h.b)
};
image2.scan((_, __, idx) => {
const r = image2.bitmap.data[idx + 0];
const g = image2.bitmap.data[idx + 1];
const b = image2.bitmap.data[idx + 2];
image2.bitmap.data[idx + 0] = normalizeValue(r, bounds.r[0], bounds.r[1]);
image2.bitmap.data[idx + 1] = normalizeValue(g, bounds.g[0], bounds.g[1]);
image2.bitmap.data[idx + 2] = normalizeValue(b, bounds.b[0], bounds.b[1]);
});
return image2;
},
invert(image2) {
image2.scan((_, __, idx) => {
image2.bitmap.data[idx] = 255 - image2.bitmap.data[idx];
image2.bitmap.data[idx + 1] = 255 - image2.bitmap.data[idx + 1];
image2.bitmap.data[idx + 2] = 255 - image2.bitmap.data[idx + 2];
});
return image2;
},
brightness(image2, val) {
if (typeof val !== "number") {
throw new Error("val must be numbers");
}
image2.scan((_, __, idx) => {
image2.bitmap.data[idx] = limit255(image2.bitmap.data[idx] * val);
image2.bitmap.data[idx + 1] = limit255(image2.bitmap.data[idx + 1] * val);
image2.bitmap.data[idx + 2] = limit255(image2.bitmap.data[idx + 2] * val);
});
return image2;
},
contrast(image2, val) {
if (typeof val !== "number") {
throw new Error("val must be numbers");
}
if (val < -1 || val > 1) {
throw new Error("val must be a number between -1 and +1");
}
const factor = (val + 1) / (1 - val);
function adjust(value) {
value = Math.floor(factor * (value - 127) + 127);
return value < 0 ? 0 : value > 255 ? 255 : value;
}
image2.scan((_, __, idx) => {
image2.bitmap.data[idx] = adjust(image2.bitmap.data[idx]);
image2.bitmap.data[idx + 1] = adjust(image2.bitmap.data[idx + 1]);
image2.bitmap.data[idx + 2] = adjust(image2.bitmap.data[idx + 2]);
});
return image2;
},
posterize(image2, n) {
if (typeof n !== "number") {
throw new Error("n must be numbers");
}
if (n < 2) {
n = 2;
}
image2.scan((_, __, idx) => {
const r = image2.bitmap.data[idx];
const g = image2.bitmap.data[idx + 1];
const b = image2.bitmap.data[idx + 2];
image2.bitmap.data[idx] = Math.floor(r / 255 * (n - 1)) / (n - 1) * 255;
image2.bitmap.data[idx + 1] = Math.floor(g / 255 * (n - 1)) / (n - 1) * 255;
image2.bitmap.data[idx + 2] = Math.floor(b / 255 * (n - 1)) / (n - 1) * 255;
});
return image2;
},
greyscale(image2) {
image2.scan((_, __, idx) => {
const grey = 0.2126 * image2.bitmap.data[idx] + 0.7152 * image2.bitmap.data[idx + 1] + 0.0722 * image2.bitmap.data[idx + 2];
image2.bitmap.data[idx] = grey;
image2.bitmap.data[idx + 1] = grey;
image2.bitmap.data[idx + 2] = grey;
});
return image2;
},
opacity(image2, f) {
if (typeof f !== "number") {
throw new Error("f must be a number");
}
if (f < 0 || f > 1) {
throw new Error("f must be a number from 0 to 1");
}
image2.scan((_, __, idx) => {
const v = image2.bitmap.data[idx + 3] * f;
image2.bitmap.data[idx + 3] = v;
});
return image2;
},
sepia(image2) {
image2.scan((_, __, idx) => {
let red = image2.bitmap.data[idx];
let green = image2.bitmap.data[idx + 1];
let blue = image2.bitmap.data[idx + 2];
red = red * 0.393 + green * 0.769 + blue * 0.189;
green = red * 0.349 + green * 0.686 + blue * 0.168;
blue = red * 0.272 + green * 0.534 + blue * 0.131;
image2.bitmap.data[idx] = red < 255 ? red : 255;
image2.bitmap.data[idx + 1] = green < 255 ? green : 255;
image2.bitmap.data[idx + 2] = blue < 255 ? blue : 255;
});
return image2;
},
fade(image2, f) {
if (typeof f !== "number") {
throw new Error("f must be a number");
}
if (f < 0 || f > 1) {
throw new Error("f must be a number from 0 to 1");
}
return this.opacity(image2, 1 - f);
},
convolution(image2, options) {
const parsed = ConvolutionOptionsSchema.parse(options);
const { kernel, edgeHandling = Edge.EXTEND } = "kernel" in parsed ? parsed : { kernel: parsed, edgeHandling: undefined };
if (!kernel[0]) {
throw new Error("kernel must be a matrix");
}
const newData = Buffer.from(image2.bitmap.data);
const kRows = kernel.length;
const kCols = kernel[0].length;
const rowEnd = Math.floor(kRows / 2);
const colEnd = Math.floor(kCols / 2);
const rowIni = -rowEnd;
const colIni = -colEnd;
let weight;
let rSum;
let gSum;
let bSum;
let ri;
let gi;
let bi;
let xi;
let yi;
let idxi;
image2.scan((x, y, idx) => {
bSum = 0;
gSum = 0;
rSum = 0;
for (let row = rowIni;row <= rowEnd; row++) {
for (let col = colIni;col <= colEnd; col++) {
xi = x + col;
yi = y + row;
weight = kernel[row + rowEnd][col + colEnd];
idxi = image2.getPixelIndex(xi, yi, edgeHandling);
if (idxi === -1) {
bi = 0;
gi = 0;
ri = 0;
} else {
ri = image2.bitmap.data[idxi + 0];
gi = image2.bitmap.data[idxi + 1];
bi = image2.bitmap.data[idxi + 2];
}
rSum += weight * ri;
gSum += weight * gi;
bSum += weight * bi;
}
}
if (rSum < 0) {
rSum = 0;
}
if (gSum < 0) {
gSum = 0;
}
if (bSum < 0) {
bSum = 0;
}
if (rSum > 255) {
rSum = 255;
}
if (gSum > 255) {
gSum = 255;
}
if (bSum > 255) {
bSum = 255;
}
newData[idx + 0] = rSum;
newData[idx + 1] = gSum;
newData[idx + 2] = bSum;
});
image2.bitmap.data = newData;
return image2;
},
opaque(image2) {
image2.scan((_, __, idx) => {
image2.bitmap.data[idx + 3] = 255;
});
return image2;
},
pixelate(image2, options) {
const parsed = PixelateOptionsSchema.parse(options);
const { size, x = 0, y = 0, w = image2.bitmap.width - x, h = image2.bitmap.height - y } = typeof parsed === "number" ? { size: parsed } : parsed;
const kernel = [
[1 / 16, 2 / 16, 1 / 16],
[2 / 16, 4 / 16, 2 / 16],
[1 / 16, 2 / 16, 1 / 16]
];
const source = clone2(image2);
scan(source, x, y, w, h, (xx, yx, idx) => {
xx = size * Math.floor(xx / size);
yx = size * Math.floor(yx / size);
const value = applyKernel(source, kernel, xx, yx);
image2.bitmap.data[idx] = value[0];
image2.bitmap.data[idx + 1] = value[1];
image2.bitmap.data[idx + 2] = value[2];
image2.bitmap.data[idx + 3] = value[3];
});
return image2;
},
convolute(image2, options) {
const parsed = ConvoluteOptionsSchema.parse(options);
const { kernel, x = 0, y = 0, w = image2.bitmap.width - x, h = image2.bitmap.height - y } = "kernel" in parsed ? parsed : { kernel: parsed };
const source = clone2(image2);
scan(source, x, y, w, h, (xx, yx, idx) => {
const value = applyKernel(source, kernel, xx, yx);
image2.bitmap.data[idx] = limit255(value[0]);
image2.bitmap.data[idx + 1] = limit255(value[1]);
image2.bitmap.data[idx + 2] = limit255(value[2]);
image2.bitmap.data[idx + 3] = limit255(value[3]);
});
return image2;
},
color(image2, actions) {
if (!actions || !Array.isArray(actions)) {
throw new Error("actions must be an array");
}
actions.forEach((action) => ColorActionNameSchema.parse(action));
actions = actions.map((action) => {
if (action.apply === "xor" || action.apply === "mix") {
action.params[0] = tinycolor(action.params[0]).toRgb();
}
return action;
});
image2.scan((_, __, idx) => {
let clr = {
r: image2.bitmap.data[idx],
g: image2.bitmap.data[idx + 1],
b: image2.bitmap.data[idx + 2]
};
const colorModifier = (i, amount) => limit255(clr[i] + amount);
actions.forEach((action) => {
if (action.apply === "mix") {
clr = mix(clr, action.params[0], action.params[1]);
} else if (action.apply === "tint") {
clr = mix(clr, { r: 255, g: 255, b: 255 }, action.params?.[0]);
} else if (action.apply === "shade") {
clr = mix(clr, { r: 0, g: 0, b: 0 }, action.params?.[0]);
} else if (action.apply === "xor") {
clr = {
r: clr.r ^ action.params[0].r,
g: clr.g ^ action.params[0].g,
b: clr.b ^ action.params[0].b
};
} else if (action.apply === "red") {
clr.r = colorModifier("r", action.params[0]);
} else if (action.apply === "green") {
clr.g = colorModifier("g", action.params[0]);
} else if (action.apply === "blue") {
clr.b = colorModifier("b", action.params[0]);
} else {
if (action.apply === "hue") {
action.apply = "spin";
}
const tnyClr = tinycolor(clr);
const fn = tnyClr[action.apply].bind(tnyClr);
if (!fn) {
throw new Error("action " + action.apply + " not supported");
}
clr = fn(...action.params || []).toRgb();
}
});
image2.bitmap.data[idx] = clr.r;
image2.bitmap.data[idx + 1] = clr.g;
image2.bitmap.data[idx + 2] = clr.b;
});
return image2;
}
};
// ../../node_modules/.bun/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js
var import_core = __toESM(require_core2(), 1);
// ../../node_modules/.bun/await-to-js@3.0.0/node_modules/await-to-js/dist/await-to-js.es5.js
function to(promise, errorExt) {
return promise.then(function(data) {
return [null, data];
}).catch(function(err) {
if (errorExt) {
Object.assign(err, errorExt);
}
return [err, undefined];
});
}
// ../../node_modules/.bun/@jimp+file-ops@1.6.0/node_modules/@jimp/file-ops/dist/esm/index.js
import { promises as fs } from "fs";
import { existsSync } from "fs";
var readFile = fs.readFile;
var writeFile = fs.writeFile;
// ../../node_modules/.bun/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js
var import_lite = __toESM(require_lite(), 1);
// ../../node_modules/.bun/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/utils/constants.js
var HorizontalAlign;
(function(HorizontalAlign2) {
HorizontalAlign2[HorizontalAlign2["LEFT"] = 1] = "LEFT";
HorizontalAlign2[HorizontalAlign2["CENTER"] = 2] = "CENTER";
HorizontalAlign2[HorizontalAlign2["RIGHT"] = 4] = "RIGHT";
})(HorizontalAlign || (HorizontalAlign = {}));
var VerticalAlign;
(function(VerticalAlign2) {
VerticalAlign2[VerticalAlign2["TOP"] = 8] = "TOP";
VerticalAlign2[VerticalAlign2["MIDDLE"] = 16] = "MIDDLE";
VerticalAlign2[VerticalAlign2["BOTTOM"] = 32] = "BOTTOM";
})(VerticalAlign || (VerticalAlign = {}));
var BlendMode;
(function(BlendMode2) {
BlendMode2["SRC_OVER"] = "srcOver";
BlendMode2["DST_OVER"] = "dstOver";
BlendMode2["MULTIPLY"] = "multiply";
BlendMode2["ADD"] = "add";
BlendMode2["SCREEN"] = "screen";
BlendMode2["OVERLAY"] = "overlay";
BlendMode2["DARKEN"] = "darken";
BlendMode2["LIGHTEN"] = "lighten";
BlendMode2["HARD_LIGHT"] = "hardLight";
BlendMode2["DIFFERENCE"] = "difference";
BlendMode2["EXCLUSION"] = "exclusion";
})(BlendMode || (BlendMode = {}));
// ../../node_modules/.bun/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/utils/composite-modes.js
var exports_composite_modes = {};
__export(exports_composite_modes, {
srcOver: () => srcOver,
screen: () => screen,
overlay: () => overlay,
names: () => names2,
multiply: () => multiply,
lighten: () => lighten2,
hardLight: () => hardLight,
exclusion: () => exclusion,
dstOver: () => dstOver,
difference: () => difference,
darken: () => darken2,
add: () => add
});
function srcOver(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const r = (src.r * src.a + dst.r * dst.a * (1 - src.a)) / a;
const g = (src.g * src.a + dst.g * dst.a * (1 - src.a)) / a;
const b = (src.b * src.a + dst.b * dst.a * (1 - src.a)) / a;
return { r, g, b, a };
}
function dstOver(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const r = (dst.r * dst.a + src.r * src.a * (1 - dst.a)) / a;
const g = (dst.g * dst.a + src.g * src.a * (1 - dst.a)) / a;
const b = (dst.b * dst.a + src.b * src.a * (1 - dst.a)) / a;
return { r, g, b, a };
}
function multiply(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const sra = src.r * src.a;
const sga = src.g * src.a;
const sba = src.b * src.a;
const dra = dst.r * dst.a;
const dga = dst.g * dst.a;
const dba = dst.b * dst.a;
const r = (sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
const g = (sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
const b = (sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
return { r, g, b, a };
}
function add(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const sra = src.r * src.a;
const sga = src.g * src.a;
const sba = src.b * src.a;
const dra = dst.r * dst.a;
const dga = dst.g * dst.a;
const dba = dst.b * dst.a;
const r = (sra + dra) / a;
const g = (sga + dga) / a;
const b = (sba + dba) / a;
return { r, g, b, a };
}
function screen(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const sra = src.r * src.a;
const sga = src.g * src.a;
const sba = src.b * src.a;
const dra = dst.r * dst.a;
const dga = dst.g * dst.a;
const dba = dst.b * dst.a;
const r = (sra * dst.a + dra * src.a - sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
const g = (sga * dst.a + dga * src.a - sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
const b = (sba * dst.a + dba * src.a - sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
return { r, g, b, a };
}
function overlay(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const sra = src.r * src.a;
const sga = src.g * src.a;
const sba = src.b * src.a;
const dra = dst.r * dst.a;
const dga = dst.g * dst.a;
const dba = dst.b * dst.a;
const r = (2 * dra <= dst.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a;
const g = (2 * dga <= dst.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a;
const b = (2 * dba <= dst.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a;
return { r, g, b, a };
}
function darken2(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const sra = src.r * src.a;
const sga = src.g * src.a;
const sba = src.b * src.a;
const dra = dst.r * dst.a;
const dga = dst.g * dst.a;
const dba = dst.b * dst.a;
const r = (Math.min(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
const g = (Math.min(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
const b = (Math.min(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
return { r, g, b, a };
}
function lighten2(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const sra = src.r * src.a;
const sga = src.g * src.a;
const sba = src.b * src.a;
const dra = dst.r * dst.a;
const dga = dst.g * dst.a;
const dba = dst.b * dst.a;
const r = (Math.max(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
const g = (Math.max(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
const b = (Math.max(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
return { r, g, b, a };
}
function hardLight(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const sra = src.r * src.a;
const sga = src.g * src.a;
const sba = src.b * src.a;
const dra = dst.r * dst.a;
const dga = dst.g * dst.a;
const dba = dst.b * dst.a;
const r = (2 * sra <= src.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a;
const g = (2 * sga <= src.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a;
const b = (2 * sba <= src.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a;
return { r, g, b, a };
}
function difference(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const sra = src.r * src.a;
const sga = src.g * src.a;
const sba = src.b * src.a;
const dra = dst.r * dst.a;
const dga = dst.g * dst.a;
const dba = dst.b * dst.a;
const r = (sra + dra - 2 * Math.min(sra * dst.a, dra * src.a)) / a;
const g = (sga + dga - 2 * Math.min(sga * dst.a, dga * src.a)) / a;
const b = (sba + dba - 2 * Math.min(sba * dst.a, dba * src.a)) / a;
return { r, g, b, a };
}
function exclusion(src, dst, ops = 1) {
src.a *= ops;
const a = dst.a + src.a - dst.a * src.a;
const sra = src.r * src.a;
const sga = src.g * src.a;
const sba = src.b * src.a;
const dra = dst.r * dst.a;
const dga = dst.g * dst.a;
const dba = dst.b * dst.a;
const r = (sra * dst.a + dra * src.a - 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
const g = (sga * dst.a + dga * src.a - 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
const b = (sba * dst.a + dba * src.a - 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
return { r, g, b, a };
}
var names2 = [
srcOver,
dstOver,
multiply,
add,
screen,
overlay,
darken2,
lighten2,
hardLight,
difference,
exclusion
];
// ../../node_modules/.bun/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/utils/composite.js
function composite(baseImage, src, x = 0, y = 0, options = {}) {
if (!(src instanceof baseImage.constructor)) {
throw new Error("The source must be a Jimp image");
}
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("x and y must be numbers");
}
const { mode = BlendMode.SRC_OVER } = options;
let { opacitySource = 1, opacityDest = 1 } = options;
if (typeof opacitySource !== "number" || opacitySource < 0 || opacitySource > 1) {
opacitySource = 1;
}
if (typeof opacityDest !== "number" || opacityDest < 0 || opacityDest > 1) {
opacityDest = 1;
}
const blendmode = exports_composite_modes[mode];
x = Math.round(x);
y = Math.round(y);
if (opacityDest !== 1) {
baseImage.scan((_, __, idx) => {
const v = baseImage.bitmap.data[idx + 3] * opacityDest;
baseImage.bitmap.data[idx + 3] = v;
});
}
src.scan((sx, sy, idx) => {
const dstIdx = baseImage.getPixelIndex(x + sx, y + sy, Edge.CROP);
if (dstIdx === -1) {
return;
}
const blended = blendmode({
r: src.bitmap.data[idx + 0] / 255,
g: src.bitmap.data[idx + 1] / 255,
b: src.bitmap.data[idx + 2] / 255,
a: src.bitmap.data[idx + 3] / 255
}, {
r: baseImage.bitmap.data[dstIdx + 0] / 255,
g: baseImage.bitmap.data[dstIdx + 1] / 255,
b: baseImage.bitmap.data[dstIdx + 2] / 255,
a: baseImage.bitmap.data[dstIdx + 3] / 255
}, opacitySource);
baseImage.bitmap.data[dstIdx + 0] = limit255(blended.r * 255);
baseImage.bitmap.data[dstIdx + 1] = limit255(blended.g * 255);
baseImage.bitmap.data[dstIdx + 2] = limit255(blended.b * 255);
baseImage.bitmap.data[dstIdx + 3] = limit255(blended.a * 255);
});
return baseImage;
}
// ../../node_modules/.bun/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/utils/image-bitmap.js
var import_exif_parser = __toESM(require_exif_parser(), 1);
function getExifOrientation(img) {
const _exif = img._exif;
return _exif && _exif.tags && _exif.tags.Orientation || 1;
}
function getExifOrientationTransformation(img) {
const w = img.bitmap.width;
const h = img.bitmap.height;
switch (getExifOrientation(img)) {
case 1:
return null;
case 2:
return function(x, y) {
return [w - x - 1, y];
};
case 3:
return function(x, y) {
return [w - x - 1, h - y - 1];
};
case 4:
return function(x, y) {
return [x, h - y - 1];
};
case 5:
return function(x, y) {
return [y, x];
};
case 6:
return function(x, y) {
return [y, h - x - 1];
};
case 7:
return function(x, y) {
return [w - y - 1, h - x - 1];
};
case 8:
return function(x, y) {
return [w - y - 1, x];
};
default:
return null;
}
}
function transformBitmap(img, width, height, transformation) {
const _data = img.bitmap.data;
const _width = img.bitmap.width;
const data = Buffer.alloc(_data.length);
for (let x = 0;x < width; x++) {
for (let y = 0;y < height; y++) {
const [_x, _y] = transformation(x, y);
const idx = width * y + x << 2;
const _idx = _width * _y + _x << 2;
const pixel = _data.readUInt32BE(_idx);
data.writeUInt32BE(pixel, idx);
}
}
img.bitmap.data = data;
img.bitmap.width = width;
img.bitmap.height = height;
img._exif.tags.Orientation = 1;
}
function exifRotate(img) {
if (getExifOrientation(img) < 2) {
return;
}
const transformation = getExifOrientationTransformation(img);
const swapDimensions = getExifOrientation(img) > 4;
const newWidth = swapDimensions ? img.bitmap.height : img.bitmap.width;
const newHeight = swapDimensions ? img.bitmap.width : img.bitmap.height;
if (transformation) {
transformBitmap(img, newWidth, newHeight, transformation);
}
}
async function attemptExifRotate(image2, buffer) {
try {
image2._exif = import_exif_parser.default.create(buffer).parse();
exifRotate(image2);
} catch {}
}
// ../../node_modules/.bun/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js
var emptyBitmap = {
data: Buffer.alloc(0),
width: 0,
height: 0
};
function bufferFromArrayBuffer(arrayBuffer) {
const buffer = Buffer.alloc(arrayBuffer.byteLength);
const view = new Uint8Array(arrayBuffer);
for (let i = 0;i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
}
function createJimp({ plugins: pluginsArg, formats: formatsArg } = {}) {
const plugins = pluginsArg || [];
const formats = (formatsArg || []).map((format) => format());
const CustomJimp = class Jimp {
bitmap = emptyBitmap;
background = 0;
formats = [];
mime;
constructor(options = emptyBitmap) {
this.formats = formats;
if ("data" in options) {
this.bitmap = options;
} else {
this.bitmap = {
data: Buffer.alloc(options.width * options.height * 4),
width: options.width,
height: options.height
};
if (options.color) {
this.background = typeof options.color === "string" ? cssColorToHex(options.color) : options.color;
for (let i = 0;i < this.bitmap.data.length; i += 4) {
this.bitmap.data.writeUInt32BE(this.background, i);
}
}
}
for (const methods5 of plugins) {
for (const key in methods5) {
this[key] = (...args) => {
const result = methods5[key]?.(this, ...args);
if (typeof result === "object" && "bitmap" in result) {
this.bitmap = result.bitmap;
return this;
}
return result;
};
}
}
}
static async read(url, options) {
if (Buffer.isBuffer(url) || url instanceof ArrayBuffer) {
return this.fromBuffer(url);
}
if (existsSync(url)) {
return this.fromBuffer(await readFile(url));
}
const [fetchErr, response] = await to(fetch(url));
if (fetchErr) {
throw new Error(`Could not load Buffer from URL: ${url}`);
}
if (!response.ok) {
throw new Error(`HTTP Status ${response.status} for url ${url}`);
}
const [arrayBufferErr, data] = await to(response.arrayBuffer());
if (arrayBufferErr) {
throw new Error(`Could not load Buffer from ${url}`);
}
const buffer = bufferFromArrayBuffer(data);
return this.fromBuffer(buffer, options);
}
static fromBitmap(bitmap) {
let data;
if (bitmap.data instanceof Buffer) {
data = Buffer.from(bitmap.data);
}
if (bitmap.data instanceof Uint8Array || bitmap.data instanceof Uint8ClampedArray) {
data = Buffer.from(bitmap.data.buffer);
}
if (Array.isArray(bitmap.data)) {
data = Buffer.concat(bitmap.data.map((hex) => Buffer.from(hex.toString(16).padStart(8, "0"), "hex")));
}
if (!data) {
throw new Error("data must be a Buffer");
}
if (typeof bitmap.height !== "number" || typeof bitmap.width !== "number") {
throw new Error("bitmap must have width and height");
}
return new CustomJimp({
height: bitmap.height,
width: bitmap.width,
data
});
}
static async fromBuffer(buffer, options) {
const actualBuffer = buffer instanceof ArrayBuffer ? bufferFromArrayBuffer(buffer) : buffer;
const mime2 = await import_core.default.fromBuffer(actualBuffer);
if (!mime2 || !mime2.mime) {
throw new Error("Could not find MIME for Buffer");
}
const format = formats.find((format2) => format2.mime === mime2.mime);
if (!format || !format.decode) {
throw new Error(`Mime type ${mime2.mime} does not support decoding`);
}
const image2 = new CustomJimp(await format.decode(actualBuffer, options?.[format.mime]));
image2.mime = mime2.mime;
attemptExifRotate(image2, actualBuffer);
return image2;
}
inspect() {
return "<Jimp " + (this.bitmap === emptyBitmap ? "pending..." : this.bitmap.width + "x" + this.bitmap.height) + ">";
}
toString() {
return "[object Jimp]";
}
get width() {
return this.bitmap.width;
}
get height() {
return this.bitmap.height;
}
async getBuffer(mime2, options) {
const format = this.formats.find((format2) => format2.mime === mime2);
if (!format || !format.encode) {
throw new Error(`Unsupported MIME type: ${mime2}`);
}
let outputImage;
if (format.hasAlpha) {
outputImage = this;
} else {
outputImage = new CustomJimp({
width: this.bitmap.width,
height: this.bitmap.height,
color: this.background
});
composite(outputImage, this);
}
return format.encode(outputImage.bitmap, options);
}
async getBase64(mime2, options) {
const data = await this.getBuffer(mime2, options);
return "data:" + mime2 + ";base64," + data.toString("base64");
}
async write(path, options) {
const mimeType = import_lite.default.getType(path);
await writeFile(path, await this.getBuffer(mimeType, options));
}
clone() {
return new CustomJimp({
...this.bitmap,
data: Buffer.from(this.bitmap.data)
});
}
getPixelIndex(x, y, edgeHandling) {
let xi;
let yi;
if (!edgeHandling) {
edgeHandling = Edge.EXTEND;
}
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("x and y must be numbers");
}
x = Math.round(x);
y = Math.round(y);
xi = x;
yi = y;
if (edgeHandling === Edge.EXTEND) {
if (x < 0)
xi = 0;
if (x >= this.bitmap.width)
xi = this.bitmap.width - 1;
if (y < 0)
yi = 0;
if (y >= this.bitmap.height)
yi = this.bitmap.height - 1;
}
if (edgeHandling === Edge.WRAP) {
if (x < 0) {
xi = this.bitmap.width + x;
}
if (x >= this.bitmap.width) {
xi = x % this.bitmap.width;
}
if (y < 0) {
yi = this.bitmap.height + y;
}
if (y >= this.bitmap.height) {
yi = y % this.bitmap.height;
}
}
let i = this.bitmap.width * yi + xi << 2;
if (xi < 0 || xi >= this.bitmap.width) {
i = -1;
}
if (yi < 0 || yi >= this.bitmap.height) {
i = -1;
}
return i;
}
getPixelColor(x, y) {
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("x and y must be numbers");
}
const idx = this.getPixelIndex(x, y);
return this.bitmap.data.readUInt32BE(idx);
}
setPixelColor(hex, x, y) {
if (typeof hex !== "number" || typeof x !== "number" || typeof y !== "number") {
throw new Error("hex, x and y must be numbers");
}
const idx = this.getPixelIndex(x, y);
this.bitmap.data.writeUInt32BE(hex, idx);
return this;
}
hasAlpha() {
const { width, height, data } = this.bitmap;
const byteLen = width * height << 2;
for (let idx = 3;idx < byteLen; idx += 4) {
if (data[idx] !== 255) {
return true;
}
}
return false;
}
composite(src, x = 0, y = 0, options = {}) {
return composite(this, src, x, y, options);
}
scan(x, y, w, h, f) {
return scan(this, x, y, w, h, f);
}
scanIterator(x = 0, y = 0, w = this.bitmap.width, h = this.bitmap.height) {
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("x and y must be numbers");
}
if (typeof w !== "number" || typeof h !== "number") {
throw new Error("w and h must be numbers");
}
return scanIterator(this, x, y, w, h);
}
};
return CustomJimp;
}
// ../../node_modules/.bun/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/constants.js
var ResizeStrategy;
(function(ResizeStrategy2) {
ResizeStrategy2["NEAREST_NEIGHBOR"] = "nearestNeighbor";
ResizeStrategy2["BILINEAR"] = "bilinearInterpolation";
ResizeStrategy2["BICUBIC"] = "bicubicInterpolation";
ResizeStrategy2["HERMITE"] = "hermiteInterpolation";
ResizeStrategy2["BEZIER"] = "bezierInterpolation";
})(ResizeStrategy || (ResizeStrategy = {}));
// ../../node_modules/.bun/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/modules/resize.js
function Resize(widthOriginal, heightOriginal, targetWidth, targetHeight, blendAlpha, interpolationPass, resizeCallback) {
this.widthOriginal = Math.abs(Math.floor(widthOriginal) || 0);
this.heightOriginal = Math.abs(Math.floor(heightOriginal) || 0);
this.targetWidth = Math.abs(Math.floor(targetWidth) || 0);
this.targetHeight = Math.abs(Math.floor(targetHeight) || 0);
this.colorChannels = blendAlpha ? 4 : 3;
this.interpolationPass = Boolean(interpolationPass);
this.resizeCallback = typeof resizeCallback === "function" ? resizeCallback : function() {};
this.targetWidthMultipliedByChannels = this.targetWidth * this.colorChannels;
this.originalWidthMultipliedByChannels = this.widthOriginal * this.colorChannels;
this.originalHeightMultipliedByChannels = this.heightOriginal * this.colorChannels;
this.widthPassResultSize = this.targetWidthMultipliedByChannels * this.heightOriginal;
this.finalResultSize = this.targetWidthMultipliedByChannels * this.targetHeight;
this.initialize();
}
Resize.prototype.initialize = function() {
if (this.widthOriginal > 0 && this.heightOriginal > 0 && this.targetWidth > 0 && this.targetHeight > 0) {
this.configurePasses();
} else {
console.log(this);
throw new Error("Invalid settings specified for the resizer.");
}
};
Resize.prototype.configurePasses = function() {
if (this.widthOriginal === this.targetWidth) {
this.resizeWidth = this.bypassResizer;
} else {
this.ratioWeightWidthPass = this.widthOriginal / this.targetWidth;
if (this.ratioWeightWidthPass < 1 && this.interpolationPass) {
this.initializeFirstPassBuffers(true);
this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthInterpolatedRGBA : this.resizeWidthInterpolatedRGB;
} else {
this.initializeFirstPassBuffers(false);
this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthRGBA : this.resizeWidthRGB;
}
}
if (this.heightOriginal === this.targetHeight) {
this.resizeHeight = this.bypassResizer;
} else {
this.ratioWeightHeightPass = this.heightOriginal / this.targetHeight;
if (this.ratioWeightHeightPass < 1 && this.interpolationPass) {
this.initializeSecondPassBuffers(true);
this.resizeHeight = this.resizeHeightInterpolated;
} else {
this.initializeSecondPassBuffers(false);
this.resizeHeight = this.colorChannels === 4 ? this.resizeHeightRGBA : this.resizeHeightRGB;
}
}
};
Resize.prototype._resizeWidthInterpolatedRGBChannels = function(buffer, fourthChannel) {
const channelsNum = fourthChannel ? 4 : 3;
const ratioWeight = this.ratioWeightWidthPass;
const outputBuffer = this.widthBuffer;
let weight = 0;
let finalOffset = 0;
let pixelOffset = 0;
let firstWeight = 0;
let secondWeight = 0;
let targetPosition;
for (targetPosition = 0;weight < 1 / 3; targetPosition += channelsNum, weight += ratioWeight) {
for (finalOffset = targetPosition, pixelOffset = 0;finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {
outputBuffer[finalOffset] = buffer[pixelOffset];
outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1];
outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2];
if (fourthChannel)
outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3];
}
}
weight -= 1 / 3;
let interpolationWidthSourceReadStop;
for (interpolationWidthSourceReadStop = this.widthOriginal - 1;weight < interpolationWidthSourceReadStop; targetPosition += channelsNum, weight += ratioWeight) {
secondWeight = weight % 1;
firstWeight = 1 - secondWeight;
for (finalOffset = targetPosition, pixelOffset = Math.floor(weight) * channelsNum;finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {
outputBuffer[finalOffset + 0] = buffer[pixelOffset + 0] * firstWeight + buffer[pixelOffset + channelsNum + 0] * secondWeight;
outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1] * firstWeight + buffer[pixelOffset + channelsNum + 1] * secondWeight;
outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2] * firstWeight + buffer[pixelOffset + channelsNum + 2] * secondWeight;
if (fourthChannel)
outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3] * firstWeight + buffer[pixelOffset + channelsNum + 3] * secondWeight;
}
}
for (interpolationWidthSourceReadStop = this.originalWidthMultipliedByChannels - channelsNum;targetPosition < this.targetWidthMultipliedByChannels; targetPosition += channelsNum) {
for (finalOffset = targetPosition, pixelOffset = interpolationWidthSourceReadStop;finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {
outputBuffer[finalOffset] = buffer[pixelOffset];
outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1];
outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2];
if (fourthChannel)
outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3];
}
}
return outputBuffer;
};
Resize.prototype._resizeWidthRGBChannels = function(buffer, fourthChannel) {
const channelsNum = fourthChannel ? 4 : 3;
const ratioWeight = this.ratioWeightWidthPass;
const ratioWeightDivisor = 1 / ratioWeight;
const nextLineOffsetOriginalWidth = this.originalWidthMultipliedByChannels - channelsNum + 1;
const nextLineOffsetTargetWidth = this.targetWidthMultipliedByChannels - channelsNum + 1;
const output = this.outputWidthWorkBench;
const outputBuffer = this.widthBuffer;
const trustworthyColorsCount = this.outputWidthWorkBenchOpaquePixelsCount;
let weight = 0;
let amountToNext = 0;
let actualPosition = 0;
let currentPosition = 0;
let line = 0;
let pixelOffset = 0;
let outputOffset = 0;
let multiplier = 1;
let r = 0;
let g = 0;
let b = 0;
let a = 0;
do {
for (line = 0;line < this.originalHeightMultipliedByChannels; ) {
output[line++] = 0;
output[line++] = 0;
output[line++] = 0;
if (fourthChannel) {
output[line++] = 0;
trustworthyColorsCount[line / channelsNum - 1] = 0;
}
}
weight = ratioWeight;
do {
amountToNext = 1 + actualPosition - currentPosition;
multiplier = Math.min(weight, amountToNext);
for (line = 0, pixelOffset = actualPosition;line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetOriginalWidth) {
r = buffer[pixelOffset];
g = buffer[++pixelOffset];
b = buffer[++pixelOffset];
a = fourthChannel ? buffer[++pixelOffset] : 255;
output[line++] += (a ? r : 0) * multiplier;
output[line++] += (a ? g : 0) * multiplier;
output[line++] += (a ? b : 0) * multiplier;
if (fourthChannel) {
output[line++] += a * multiplier;
trustworthyColorsCount[line / channelsNum - 1] += a ? multiplier : 0;
}
}
if (weight >= amountToNext) {
actualPosition += channelsNum;
currentPosition = actualPosition;
weight -= amountToNext;
} else {
currentPosition += weight;
break;
}
} while (weight > 0 && actualPosition < this.originalWidthMultipliedByChannels);
for (line = 0, pixelOffset = outputOffset;line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetTargetWidth) {
weight = fourthChannel ? trustworthyColorsCount[line / channelsNum] : 1;
multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor;
outputBuffer[pixelOffset] = output[line++] * multiplier;
outputBuffer[++pixelOffset] = output[line++] * multiplier;
outputBuffer[++pixelOffset] = output[line++] * multiplier;
if (fourthChannel)
outputBuffer[++pixelOffset] = output[line++] * ratioWeightDivisor;
}
outputOffset += channelsNum;
} while (outputOffset < this.targetWidthMultipliedByChannels);
return outputBuffer;
};
Resize.prototype._resizeHeightRGBChannels = function(buffer, fourthChannel) {
const ratioWeight = this.ratioWeightHeightPass;
const ratioWeightDivisor = 1 / ratioWeight;
const output = this.outputHeightWorkBench;
const outputBuffer = this.heightBuffer;
const trustworthyColorsCount = this.outputHeightWorkBenchOpaquePixelsCount;
let weight = 0;
let amountToNext = 0;
let actualPosition = 0;
let currentPosition = 0;
let pixelOffset = 0;
let outputOffset = 0;
let caret = 0;
let multiplier = 1;
let r = 0;
let g = 0;
let b = 0;
let a = 0;
do {
for (pixelOffset = 0;pixelOffset < this.targetWidthMultipliedByChannels; ) {
output[pixelOffset++] = 0;
output[pixelOffset++] = 0;
output[pixelOffset++] = 0;
if (fourthChannel) {
output[pixelOffset++] = 0;
trustworthyColorsCount[pixelOffset / 4 - 1] = 0;
}
}
weight = ratioWeight;
do {
amountToNext = 1 + actualPosition - currentPosition;
multiplier = Math.min(weight, amountToNext);
caret = actualPosition;
for (pixelOffset = 0;pixelOffset < this.targetWidthMultipliedByChannels; ) {
r = buffer[caret++];
g = buffer[caret++];
b = buffer[caret++];
a = fourthChannel ? buffer[caret++] : 255;
output[pixelOffset++] += (a ? r : 0) * multiplier;
output[pixelOffset++] += (a ? g : 0) * multiplier;
output[pixelOffset++] += (a ? b : 0) * multiplier;
if (fourthChannel) {
output[pixelOffset++] += a * multiplier;
trustworthyColorsCount[pixelOffset / 4 - 1] += a ? multiplier : 0;
}
}
if (weight >= amountToNext) {
actualPosition = caret;
currentPosition = actualPosition;
weight -= amountToNext;
} else {
currentPosition += weight;
break;
}
} while (weight > 0 && actualPosition < this.widthPassResultSize);
for (pixelOffset = 0;pixelOffset < this.targetWidthMultipliedByChannels; ) {
weight = fourthChannel ? trustworthyColorsCount[pixelOffset / 4] : 1;
multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor;
outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);
outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);
outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);
if (fourthChannel) {
outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor);
}
}
} while (outputOffset < this.finalResultSize);
return outputBuffer;
};
Resize.prototype.resizeWidthInterpolatedRGB = function(buffer) {
return this._resizeWidthInterpolatedRGBChannels(buffer, false);
};
Resize.prototype.resizeWidthInterpolatedRGBA = function(buffer) {
return this._resizeWidthInterpolatedRGBChannels(buffer, true);
};
Resize.prototype.resizeWidthRGB = function(buffer) {
return this._resizeWidthRGBChannels(buffer, false);
};
Resize.prototype.resizeWidthRGBA = function(buffer) {
return this._resizeWidthRGBChannels(buffer, true);
};
Resize.prototype.resizeHeightInterpolated = function(buffer) {
const ratioWeight = this.ratioWeightHeightPass;
const outputBuffer = this.heightBuffer;
let weight = 0;
let finalOffset = 0;
let pixelOffset = 0;
let pixelOffsetAccumulated = 0;
let pixelOffsetAccumulated2 = 0;
let firstWeight = 0;
let secondWeight = 0;
let interpolationHeightSourceReadStop;
for (;weight < 1 / 3; weight += ratioWeight) {
for (pixelOffset = 0;pixelOffset < this.targetWidthMultipliedByChannels; ) {
outputBuffer[finalOffset++] = Math.round(buffer[pixelOffset++]);
}
}
weight -= 1 / 3;
for (interpolationHeightSourceReadStop = this.heightOriginal - 1;weight < interpolationHeightSourceReadStop; weight += ratioWeight) {
secondWeight = weight % 1;
firstWeight = 1 - secondWeight;
pixelOffsetAccumulated = Math.floor(weight) * this.targetWidthMultipliedByChannels;
pixelOffsetAccumulated2 = pixelOffsetAccumulated + this.targetWidthMultipliedByChannels;
for (pixelOffset = 0;pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) {
outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++] * firstWeight + buffer[pixelOffsetAccumulated2++] * secondWeight);
}
}
while (finalOffset < this.finalResultSize) {
for (pixelOffset = 0, pixelOffsetAccumulated = interpolationHeightSourceReadStop * this.targetWidthMultipliedByChannels;pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) {
outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++]);
}
}
return outputBuffer;
};
Resize.prototype.resizeHeightRGB = function(buffer) {
return this._resizeHeightRGBChannels(buffer, false);
};
Resize.prototype.resizeHeightRGBA = function(buffer) {
return this._resizeHeightRGBChannels(buffer, true);
};
Resize.prototype.resize = function(buffer) {
this.resizeCallback(this.resizeHeight(this.resizeWidth(buffer)));
};
Resize.prototype.bypassResizer = function(buffer) {
return buffer;
};
Resize.prototype.initializeFirstPassBuffers = function(BILINEARAlgo) {
this.widthBuffer = this.generateFloatBuffer(this.widthPassResultSize);
if (!BILINEARAlgo) {
this.outputWidthWorkBench = this.generateFloatBuffer(this.originalHeightMultipliedByChannels);
if (this.colorChannels > 3) {
this.outputWidthWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.heightOriginal);
}
}
};
Resize.prototype.initializeSecondPassBuffers = function(BILINEARAlgo) {
this.heightBuffer = this.generateUint8Buffer(this.finalResultSize);
if (!BILINEARAlgo) {
this.outputHeightWorkBench = this.generateFloatBuffer(this.targetWidthMultipliedByChannels);
if (this.colorChannels > 3) {
this.outputHeightWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.targetWidth);
}
}
};
Resize.prototype.generateFloatBuffer = function(bufferLength) {
try {
return new Float32Array(bufferLength);
} catch (error) {
console.error(error);
return [];
}
};
Resize.prototype.generateFloat64Buffer = function(bufferLength) {
try {
return new Float64Array(bufferLength);
} catch (error) {
console.error(error);
return [];
}
};
Resize.prototype.generateUint8Buffer = function(bufferLength) {
try {
return new Uint8Array(bufferLength);
} catch (error) {
console.error(error);
return [];
}
};
var resize_default = Resize;
// ../../node_modules/.bun/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/modules/resize2.js
var operations = {
nearestNeighbor(src, dst) {
const wSrc = src.width;
const hSrc = src.height;
const wDst = dst.width;
const hDst = dst.height;
const bufSrc = src.data;
const bufDst = dst.data;
for (let i = 0;i < hDst; i++) {
for (let j = 0;j < wDst; j++) {
let posDst = (i * wDst + j) * 4;
const iSrc = Math.floor(i * hSrc / hDst);
const jSrc = Math.floor(j * wSrc / wDst);
let posSrc = (iSrc * wSrc + jSrc) * 4;
bufDst[posDst++] = bufSrc[posSrc++];
bufDst[posDst++] = bufSrc[posSrc++];
bufDst[posDst++] = bufSrc[posSrc++];
bufDst[posDst++] = bufSrc[posSrc++];
}
}
},
bilinearInterpolation(src, dst) {
const wSrc = src.width;
const hSrc = src.height;
const wDst = dst.width;
const hDst = dst.height;
const bufSrc = src.data;
const bufDst = dst.data;
const interpolate = function(k, kMin, vMin, kMax, vMax) {
if (kMin === kMax) {
return vMin;
}
return Math.round((k - kMin) * vMax + (kMax - k) * vMin);
};
const assign = function(pos, offset, x, xMin, xMax, y, yMin, yMax) {
let posMin = (yMin * wSrc + xMin) * 4 + offset;
let posMax = (yMin * wSrc + xMax) * 4 + offset;
const vMin = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]);
if (yMax === yMin) {
bufDst[pos + offset] = vMin;
} else {
posMin = (yMax * wSrc + xMin) * 4 + offset;
posMax = (yMax * wSrc + xMax) * 4 + offset;
const vMax = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]);
bufDst[pos + offset] = interpolate(y, yMin, vMin, yMax, vMax);
}
};
for (let i = 0;i < hDst; i++) {
for (let j = 0;j < wDst; j++) {
const posDst = (i * wDst + j) * 4;
const x = j * wSrc / wDst;
const xMin = Math.floor(x);
const xMax = Math.min(Math.ceil(x), wSrc - 1);
const y = i * hSrc / hDst;
const yMin = Math.floor(y);
const yMax = Math.min(Math.ceil(y), hSrc - 1);
assign(posDst, 0, x, xMin, xMax, y, yMin, yMax);
assign(posDst, 1, x, xMin, xMax, y, yMin, yMax);
assign(posDst, 2, x, xMin, xMax, y, yMin, yMax);
assign(posDst, 3, x, xMin, xMax, y, yMin, yMax);
}
}
},
_interpolate2D(src, dst, options, interpolate) {
const bufSrc = src.data;
const bufDst = dst.data;
const wSrc = src.width;
const hSrc = src.height;
const wDst = dst.width;
const hDst = dst.height;
const wM = Math.max(1, Math.floor(wSrc / wDst));
const wDst2 = wDst * wM;
const hM = Math.max(1, Math.floor(hSrc / hDst));
const hDst2 = hDst * hM;
const buf1 = Buffer.alloc(wDst2 * hSrc * 4);
for (let i = 0;i < hSrc; i++) {
for (let j = 0;j < wDst2; j++) {
const x = j * (wSrc - 1) / wDst2;
const xPos = Math.floor(x);
const t = x - xPos;
const srcPos = (i * wSrc + xPos) * 4;
const buf1Pos = (i * wDst2 + j) * 4;
for (let k = 0;k < 4; k++) {
const kPos = srcPos + k;
const x0 = xPos > 0 ? bufSrc[kPos - 4] : 2 * bufSrc[kPos] - bufSrc[kPos + 4];
const x1 = bufSrc[kPos];
const x2 = bufSrc[kPos + 4];
const x3 = xPos < wSrc - 2 ? bufSrc[kPos + 8] : 2 * bufSrc[kPos + 4] - bufSrc[kPos];
buf1[buf1Pos + k] = interpolate(x0, x1, x2, x3, t);
}
}
}
const buf2 = Buffer.alloc(wDst2 * hDst2 * 4);
for (let i = 0;i < hDst2; i++) {
for (let j = 0;j < wDst2; j++) {
const y = i * (hSrc - 1) / hDst2;
const yPos = Math.floor(y);
const t = y - yPos;
const buf1Pos = (yPos * wDst2 + j) * 4;
const buf2Pos = (i * wDst2 + j) * 4;
for (let k = 0;k < 4; k++) {
const kPos = buf1Pos + k;
const y0 = yPos > 0 ? buf1[kPos - wDst2 * 4] : 2 * buf1[kPos] - buf1[kPos + wDst2 * 4];
const y1 = buf1[kPos];
const y2 = buf1[kPos + wDst2 * 4];
const y3 = yPos < hSrc - 2 ? buf1[kPos + wDst2 * 8] : 2 * buf1[kPos + wDst2 * 4] - buf1[kPos];
buf2[buf2Pos + k] = interpolate(y0, y1, y2, y3, t);
}
}
}
const m = wM * hM;
if (m > 1) {
for (let i = 0;i < hDst; i++) {
for (let j = 0;j < wDst; j++) {
let r = 0;
let g = 0;
let b = 0;
let a = 0;
let realColors = 0;
for (let y = 0;y < hM; y++) {
const yPos = i * hM + y;
for (let x = 0;x < wM; x++) {
const xPos = j * wM + x;
const xyPos = (yPos * wDst2 + xPos) * 4;
const pixelAlpha = buf2[xyPos + 3];
if (pixelAlpha) {
r += buf2[xyPos];
g += buf2[xyPos + 1];
b += buf2[xyPos + 2];
realColors++;
}
a += pixelAlpha;
}
}
const pos = (i * wDst + j) * 4;
bufDst[pos] = realColors ? Math.round(r / realColors) : 0;
bufDst[pos + 1] = realColors ? Math.round(g / realColors) : 0;
bufDst[pos + 2] = realColors ? Math.round(b / realColors) : 0;
bufDst[pos + 3] = Math.round(a / m);
}
}
} else {
dst.data = buf2;
}
},
bicubicInterpolation(src, dst, options) {
const interpolateCubic = function(x0, x1, x2, x3, t) {
const a0 = x3 - x2 - x0 + x1;
const a1 = x0 - x1 - a0;
const a2 = x2 - x0;
const a3 = x1;
return Math.max(0, Math.min(255, a0 * (t * t * t) + a1 * (t * t) + a2 * t + a3));
};
return this._interpolate2D(src, dst, options, interpolateCubic);
},
hermiteInterpolation(src, dst, options) {
const interpolateHermite = function(x0, x1, x2, x3, t) {
const c0 = x1;
const c1 = 0.5 * (x2 - x0);
const c2 = x0 - 2.5 * x1 + 2 * x2 - 0.5 * x3;
const c3 = 0.5 * (x3 - x0) + 1.5 * (x1 - x2);
return Math.max(0, Math.min(255, Math.round(((c3 * t + c2) * t + c1) * t + c0)));
};
return this._interpolate2D(src, dst, options, interpolateHermite);
},
bezierInterpolation(src, dst, options) {
const interpolateBezier = function(x0, x1, x2, x3, t) {
const cp1 = x1 + (x2 - x0) / 4;
const cp2 = x2 - (x3 - x1) / 4;
const nt = 1 - t;
const c0 = x1 * nt * nt * nt;
const c1 = 3 * cp1 * nt * nt * t;
const c2 = 3 * cp2 * nt * t * t;
const c3 = x2 * t * t * t;
return Math.max(0, Math.min(255, Math.round(c0 + c1 + c2 + c3)));
};
return this._interpolate2D(src, dst, options, interpolateBezier);
}
};
// ../../node_modules/.bun/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js
var ResizeOptionsSchema = exports_external.union([
exports_external.object({
w: exports_external.number().min(0),
h: exports_external.number().min(0).optional(),
mode: exports_external.nativeEnum(ResizeStrategy).optional()
}),
exports_external.object({
w: exports_external.number().min(0).optional(),
h: exports_external.number().min(0),
mode: exports_external.nativeEnum(ResizeStrategy).optional()
})
]);
var ScaleToFitOptionsSchema = exports_external.object({
w: exports_external.number().min(0),
h: exports_external.number().min(0),
mode: exports_external.nativeEnum(ResizeStrategy).optional()
});
var ScaleComplexOptionsSchema = exports_external.object({
f: exports_external.number().min(0),
mode: exports_external.nativeEnum(ResizeStrategy).optional()
});
var methods5 = {
resize(image2, options) {
const { mode } = ResizeOptionsSchema.parse(options);
let w;
let h;
if (typeof options.w === "number") {
w = options.w;
h = options.h ?? image2.bitmap.height * (w / image2.bitmap.width);
} else if (typeof options.h === "number") {
h = options.h;
w = options.w ?? image2.bitmap.width * (h / image2.bitmap.height);
} else {
throw new Error("w must be a number");
}
w = Math.round(w) || 1;
h = Math.round(h) || 1;
if (mode && typeof operations[mode] === "function") {
const dst = {
data: Buffer.alloc(w * h * 4),
width: w,
height: h
};
operations[mode](image2.bitmap, dst);
image2.bitmap = dst;
} else {
const resize = new resize_default(image2.bitmap.width, image2.bitmap.height, w, h, true, true, (buffer) => {
image2.bitmap.data = Buffer.from(buffer);
image2.bitmap.width = w;
image2.bitmap.height = h;
});
resize.resize(image2.bitmap.data);
}
return image2;
},
scale(image2, options) {
const { f, mode } = typeof options === "number" ? { f: options } : ScaleComplexOptionsSchema.parse(options);
const w = image2.bitmap.width * f;
const h = image2.bitmap.height * f;
return this.resize(image2, { w, h, mode });
},
scaleToFit(image2, options) {
const { h, w, mode } = ScaleToFitOptionsSchema.parse(options);
const f = w / h > image2.bitmap.width / image2.bitmap.height ? h / image2.bitmap.height : w / image2.bitmap.width;
return this.scale(image2, { f, mode });
}
};
// ../../node_modules/.bun/@jimp+plugin-contain@1.6.0/node_modules/@jimp/plugin-contain/dist/esm/index.js
var ContainOptionsSchema = exports_external.object({
w: exports_external.number(),
h: exports_external.number(),
align: exports_external.number().optional(),
mode: exports_external.nativeEnum(ResizeStrategy).optional()
});
var methods6 = {
contain(image2, options) {
const { w, h, align = HorizontalAlign.CENTER | VerticalAlign.MIDDLE, mode } = ContainOptionsSchema.parse(options);
const hbits = align & (1 << 3) - 1;
const vbits = align >> 3;
if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) {
throw new Error("only use one flag per alignment direction");
}
const alignH = hbits >> 1;
const alignV = vbits >> 1;
const f = w / h > image2.bitmap.width / image2.bitmap.height ? h / image2.bitmap.height : w / image2.bitmap.width;
const c = methods5.scale(clone2(image2), { f, mode });
image2 = methods5.resize(image2, { w, h, mode });
image2.scan((_, __, idx) => {
image2.bitmap.data.writeUInt32BE(image2.background, idx);
});
image2 = methods.blit(image2, {
src: c,
x: (image2.bitmap.width - c.bitmap.width) / 2 * alignH,
y: (image2.bitmap.height - c.bitmap.height) / 2 * alignV
});
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-crop@1.6.0/node_modules/@jimp/plugin-crop/dist/esm/index.js
var CropOptionsSchema = exports_external.object({
x: exports_external.number(),
y: exports_external.number(),
w: exports_external.number(),
h: exports_external.number()
});
var AutocropComplexOptionsSchema = exports_external.object({
tolerance: exports_external.number().min(0).max(1).optional(),
cropOnlyFrames: exports_external.boolean().optional(),
cropSymmetric: exports_external.boolean().optional(),
leaveBorder: exports_external.number().optional(),
ignoreSides: exports_external.object({
north: exports_external.boolean().optional(),
south: exports_external.boolean().optional(),
east: exports_external.boolean().optional(),
west: exports_external.boolean().optional()
}).optional()
});
var methods7 = {
crop(image2, options) {
let { x, y, w, h } = CropOptionsSchema.parse(options);
x = Math.round(x);
y = Math.round(y);
w = Math.round(w);
h = Math.round(h);
if (x === 0 && w === image2.bitmap.width) {
const start = w * y + x << 2;
const end = start + (h * w << 2);
image2.bitmap.data = image2.bitmap.data.slice(start, end);
} else {
const bitmap = Buffer.allocUnsafe(w * h * 4);
let offset = 0;
scan(image2, x, y, w, h, function(_, __, idx) {
const data = image2.bitmap.data.readUInt32BE(idx);
bitmap.writeUInt32BE(data, offset);
offset += 4;
});
image2.bitmap.data = bitmap;
}
image2.bitmap.width = w;
image2.bitmap.height = h;
return image2;
},
autocrop(image2, options = {}) {
const { tolerance = 0.0002, cropOnlyFrames = true, cropSymmetric = false, leaveBorder = 0, ignoreSides: ignoreSidesArg } = typeof options === "number" ? { tolerance: options } : AutocropComplexOptionsSchema.parse(options);
const w = image2.bitmap.width;
const h = image2.bitmap.height;
const minPixelsPerSide = 1;
const ignoreSides = {
north: false,
south: false,
east: false,
west: false,
...ignoreSidesArg
};
let colorTarget = image2.getPixelColor(0, 0);
const rgba1 = intToRGBA(colorTarget);
let northPixelsToCrop = 0;
let eastPixelsToCrop = 0;
let southPixelsToCrop = 0;
let westPixelsToCrop = 0;
colorTarget = image2.getPixelColor(0, 0);
if (!ignoreSides.north) {
north:
for (let y = 0;y < h - minPixelsPerSide; y++) {
for (let x = 0;x < w; x++) {
const colorXY = image2.getPixelColor(x, y);
const rgba2 = intToRGBA(colorXY);
if (colorDiff(rgba1, rgba2) > tolerance) {
break north;
}
}
northPixelsToCrop++;
}
}
colorTarget = image2.getPixelColor(w, 0);
if (!ignoreSides.west) {
west:
for (let x = 0;x < w - minPixelsPerSide; x++) {
for (let y = 0 + northPixelsToCrop;y < h; y++) {
const colorXY = image2.getPixelColor(x, y);
const rgba2 = intToRGBA(colorXY);
if (colorDiff(rgba1, rgba2) > tolerance) {
break west;
}
}
westPixelsToCrop++;
}
}
colorTarget = image2.getPixelColor(0, h);
if (!ignoreSides.south) {
south:
for (let y = h - 1;y >= northPixelsToCrop + minPixelsPerSide; y--) {
for (let x = w - eastPixelsToCrop - 1;x >= 0; x--) {
const colorXY = image2.getPixelColor(x, y);
const rgba2 = intToRGBA(colorXY);
if (colorDiff(rgba1, rgba2) > tolerance) {
break south;
}
}
southPixelsToCrop++;
}
}
colorTarget = image2.getPixelColor(w, h);
if (!ignoreSides.east) {
east:
for (let x = w - 1;x >= 0 + westPixelsToCrop + minPixelsPerSide; x--) {
for (let y = h - 1;y >= 0 + northPixelsToCrop; y--) {
const colorXY = image2.getPixelColor(x, y);
const rgba2 = intToRGBA(colorXY);
if (colorDiff(rgba1, rgba2) > tolerance) {
break east;
}
}
eastPixelsToCrop++;
}
}
let doCrop = false;
westPixelsToCrop -= leaveBorder;
eastPixelsToCrop -= leaveBorder;
northPixelsToCrop -= leaveBorder;
southPixelsToCrop -= leaveBorder;
if (cropSymmetric) {
const horizontal = Math.min(eastPixelsToCrop, westPixelsToCrop);
const vertical = Math.min(northPixelsToCrop, southPixelsToCrop);
westPixelsToCrop = horizontal;
eastPixelsToCrop = horizontal;
northPixelsToCrop = vertical;
southPixelsToCrop = vertical;
}
westPixelsToCrop = westPixelsToCrop >= 0 ? westPixelsToCrop : 0;
eastPixelsToCrop = eastPixelsToCrop >= 0 ? eastPixelsToCrop : 0;
northPixelsToCrop = northPixelsToCrop >= 0 ? northPixelsToCrop : 0;
southPixelsToCrop = southPixelsToCrop >= 0 ? southPixelsToCrop : 0;
const widthOfRemainingPixels = w - (westPixelsToCrop + eastPixelsToCrop);
const heightOfRemainingPixels = h - (southPixelsToCrop + northPixelsToCrop);
if (cropOnlyFrames) {
doCrop = eastPixelsToCrop !== 0 && northPixelsToCrop !== 0 && westPixelsToCrop !== 0 && southPixelsToCrop !== 0;
} else {
doCrop = eastPixelsToCrop !== 0 || northPixelsToCrop !== 0 || westPixelsToCrop !== 0 || southPixelsToCrop !== 0;
}
if (doCrop) {
this.crop(image2, {
x: westPixelsToCrop,
y: northPixelsToCrop,
w: widthOfRemainingPixels,
h: heightOfRemainingPixels
});
}
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-cover@1.6.0/node_modules/@jimp/plugin-cover/dist/esm/index.js
var CoverOptionsSchema = exports_external.object({
w: exports_external.number(),
h: exports_external.number(),
align: exports_external.number().optional(),
mode: exports_external.nativeEnum(ResizeStrategy).optional()
});
var methods8 = {
cover(image2, options) {
const { w, h, align = HorizontalAlign.CENTER | VerticalAlign.MIDDLE, mode } = CoverOptionsSchema.parse(options);
const hbits = align & (1 << 3) - 1;
const vbits = align >> 3;
if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) {
throw new Error("only use one flag per alignment direction");
}
const alignH = hbits >> 1;
const alignV = vbits >> 1;
const f = w / h > image2.bitmap.width / image2.bitmap.height ? w / image2.bitmap.width : h / image2.bitmap.height;
image2 = methods5.scale(image2, {
f,
mode
});
image2 = methods7.crop(image2, {
x: (image2.bitmap.width - w) / 2 * alignH,
y: (image2.bitmap.height - h) / 2 * alignV,
w,
h
});
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-displace@1.6.0/node_modules/@jimp/plugin-displace/dist/esm/index.js
var DisplaceOptionsSchema = exports_external.object({
map: JimpClassSchema,
offset: exports_external.number()
});
var methods9 = {
displace(image2, options) {
const { map, offset } = DisplaceOptionsSchema.parse(options);
const source = clone2(image2);
image2.scan((x, y, idx) => {
let displacement = map.bitmap.data[idx] / 256 * offset;
displacement = Math.round(displacement);
const ids = image2.getPixelIndex(x + displacement, y);
image2.bitmap.data[ids] = source.bitmap.data[idx];
image2.bitmap.data[ids + 1] = source.bitmap.data[idx + 1];
image2.bitmap.data[ids + 2] = source.bitmap.data[idx + 2];
});
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-dither@1.6.0/node_modules/@jimp/plugin-dither/dist/esm/index.js
var methods10 = {
dither(image2) {
const rgb565Matrix = [
1,
9,
3,
11,
13,
5,
15,
7,
4,
12,
2,
10,
16,
8,
14,
6
];
image2.scan((x, y, idx) => {
const thresholdId = ((y & 3) << 2) + x % 4;
const dither = rgb565Matrix[thresholdId];
image2.bitmap.data[idx] = Math.min(image2.bitmap.data[idx] + dither, 255);
image2.bitmap.data[idx + 1] = Math.min(image2.bitmap.data[idx + 1] + dither, 255);
image2.bitmap.data[idx + 2] = Math.min(image2.bitmap.data[idx + 2] + dither, 255);
});
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-fisheye@1.6.0/node_modules/@jimp/plugin-fisheye/dist/esm/index.js
var FisheyeOptionsSchema = exports_external.object({
radius: exports_external.number().min(0).optional()
});
var methods11 = {
fisheye(image2, options = {}) {
const { radius = 2.5 } = FisheyeOptionsSchema.parse(options);
const source = clone2(image2);
const { width, height } = source.bitmap;
source.scan((x, y) => {
const hx = x / width;
const hy = y / height;
const rActual = Math.sqrt(Math.pow(hx - 0.5, 2) + Math.pow(hy - 0.5, 2));
const rn = 2 * Math.pow(rActual, radius);
const cosA = (hx - 0.5) / rActual;
const sinA = (hy - 0.5) / rActual;
const newX = Math.round((rn * cosA + 0.5) * width);
const newY = Math.round((rn * sinA + 0.5) * height);
const color = source.getPixelColor(newX, newY);
image2.setPixelColor(color, x, y);
});
image2.setPixelColor(source.getPixelColor(width / 2, height / 2), width / 2, height / 2);
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-flip@1.6.0/node_modules/@jimp/plugin-flip/dist/esm/index.js
var FlipOptionsSchema = exports_external.object({
horizontal: exports_external.boolean().optional(),
vertical: exports_external.boolean().optional()
});
var methods12 = {
flip(image2, options) {
const { horizontal, vertical } = FlipOptionsSchema.parse(options);
const bitmap = Buffer.alloc(image2.bitmap.data.length);
image2.scan((x, y, idx) => {
const _x = horizontal ? image2.bitmap.width - 1 - x : x;
const _y = vertical ? image2.bitmap.height - 1 - y : y;
const _idx = image2.bitmap.width * _y + _x << 2;
const data = image2.bitmap.data.readUInt32BE(idx);
bitmap.writeUInt32BE(data, _idx);
});
image2.bitmap.data = Buffer.from(bitmap);
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-hash@1.6.0/node_modules/@jimp/plugin-hash/dist/esm/index.js
var import_any_base = __toESM(require_any_base(), 1);
// ../../node_modules/.bun/@jimp+plugin-hash@1.6.0/node_modules/@jimp/plugin-hash/dist/esm/phash.js
class ImagePHash {
size;
smallerSize;
constructor(size, smallerSize) {
this.size = size || 32;
this.smallerSize = smallerSize || 8;
initCoefficients(this.size);
}
distance(s1, s2) {
let counter = 0;
for (let k = 0;k < s1.length; k++) {
if (s1[k] !== s2[k]) {
counter++;
}
}
return counter / s1.length;
}
getHash(img) {
img = methods5.resize(clone2(img), { w: this.size, h: this.size });
img = methods4.greyscale(img);
const vals = [];
for (let x = 0;x < img.bitmap.width; x++) {
const row = [];
for (let y = 0;y < img.bitmap.height; y++) {
row[y] = intToRGBA2(img.getPixelColor(x, y)).b;
}
vals[x] = row;
}
const dctVals = applyDCT(vals, this.size);
let total = 0;
for (let x = 0;x < this.smallerSize; x++) {
for (let y = 0;y < this.smallerSize; y++) {
total += dctVals[x][y];
}
}
const avg = total / (this.smallerSize * this.smallerSize);
let hash = "";
for (let x = 0;x < this.smallerSize; x++) {
for (let y = 0;y < this.smallerSize; y++) {
hash += dctVals[x][y] > avg ? "1" : "0";
}
}
return hash;
}
}
function intToRGBA2(i) {
const a = i & 255;
i >>>= 8;
const b = i & 255;
i >>>= 8;
const g = i & 255;
i >>>= 8;
const r = i & 255;
return { r, g, b, a };
}
var c = [];
function initCoefficients(size) {
for (let i = 1;i < size; i++) {
c[i] = 1;
}
c[0] = 1 / Math.sqrt(2);
}
function applyDCT(f, size) {
const N = size;
const F = [];
for (let u = 0;u < N; u++) {
const row = [];
for (let v = 0;v < N; v++) {
let sum = 0;
for (let i = 0;i < N; i++) {
for (let j = 0;j < N; j++) {
sum += Math.cos((2 * i + 1) / (2 * N) * u * Math.PI) * Math.cos((2 * j + 1) / (2 * N) * v * Math.PI) * f[i][j];
}
}
sum *= c[u] * c[v] / 4;
row[v] = sum;
F[u] = row;
}
}
return F;
}
var phash_default = ImagePHash;
// ../../node_modules/.bun/@jimp+plugin-hash@1.6.0/node_modules/@jimp/plugin-hash/dist/esm/index.js
var alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_";
var maxHashLength = [NaN, NaN];
for (let i = 2;i < 65; i++) {
const maxHash = import_any_base.default(import_any_base.default.BIN, alphabet.slice(0, i))(new Array(64 + 1).join("1"));
maxHashLength.push(maxHash.length);
}
var methods13 = {
pHash(image2) {
const pHash = new phash_default;
return pHash.getHash(image2);
},
hash(image2, base = 64) {
if (base < 2 || base > 64) {
throw new Error("base must be a number between 2 and 64");
}
const subAlphabet = alphabet.slice(0, base);
const pHash = this.pHash(image2);
const maxLength = maxHashLength[base];
return import_any_base.default(import_any_base.default.BIN, subAlphabet)(pHash).padStart(maxLength, "0");
},
distanceFromHash(image2, compareHash) {
const pHash = new phash_default;
const currentHash = pHash.getHash(image2);
return pHash.distance(currentHash, compareHash);
}
};
// ../../node_modules/.bun/@jimp+plugin-mask@1.6.0/node_modules/@jimp/plugin-mask/dist/esm/index.js
var MaskOptionsObjectSchema = exports_external.object({
src: JimpClassSchema,
x: exports_external.number().optional(),
y: exports_external.number().optional()
});
var MaskOptionsSchema = exports_external.union([JimpClassSchema, MaskOptionsObjectSchema]);
var methods14 = {
mask(image2, options) {
MaskOptionsSchema.parse(options);
let src;
let x;
let y;
if ("bitmap" in options) {
src = options;
x = 0;
y = 0;
} else {
src = options.src;
x = options.x ?? 0;
y = options.y ?? 0;
}
x = Math.round(x);
y = Math.round(y);
const w = image2.bitmap.width;
const h = image2.bitmap.height;
src.scan(function(sx, sy, idx) {
const destX = x + sx;
const destY = y + sy;
if (destX >= 0 && destY >= 0 && destX < w && destY < h) {
const dstIdx = image2.getPixelIndex(destX, destY);
const { data } = src.bitmap;
const avg = (data[idx + 0] + data[idx + 1] + data[idx + 2]) / 3;
image2.bitmap.data[dstIdx + 3] *= avg / 255;
}
});
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-print@1.6.0/node_modules/@jimp/plugin-print/dist/esm/measure-text.js
function measureText(font, text) {
let x = 0;
for (let i = 0;i < text.length; i++) {
const char = text[i];
const fontChar = font.chars[char];
if (fontChar) {
const fontKerning = font.kernings[char];
const nextChar = text[i + 1];
const kerning = fontKerning && nextChar && fontKerning[nextChar] ? fontKerning[nextChar] || 0 : 0;
x += (fontChar.xadvance || 0) + kerning;
}
}
return x;
}
function splitLines(font, text, maxWidth) {
const words = text.replace(/[\r\n]+/g, `
`).split(" ");
const lines = [];
let currentLine = [];
let longestLine = 0;
words.forEach((word) => {
const wordWidth = measureText(font, word + (words.length > 1 ? " " : ""));
if (wordWidth > maxWidth) {
const characterIterator = word[Symbol.iterator]();
let current = "";
for (const char of characterIterator) {
const nextLine = [...currentLine, current + char].join(" ");
const length2 = measureText(font, nextLine);
if (length2 < maxWidth) {
current += char;
} else if (length2 > maxWidth) {
lines.push([...currentLine, current]);
currentLine = [];
current = char;
} else {
lines.push([...currentLine, current + char]);
currentLine = [];
current = "";
}
}
return;
}
const line = [...currentLine, word].join(" ");
const length = measureText(font, line);
if (length <= maxWidth && !word.includes(`
`)) {
if (length > longestLine) {
longestLine = length;
}
currentLine.push(word);
} else {
lines.push(currentLine);
currentLine = [word.replace(`
`, "")];
}
});
lines.push(currentLine);
return {
lines,
longestLine
};
}
function measureTextHeight(font, text, maxWidth) {
const { lines } = splitLines(font, text, maxWidth);
return lines.length * font.common.lineHeight;
}
// ../../node_modules/.bun/@jimp+plugin-print@1.6.0/node_modules/@jimp/plugin-print/dist/esm/index.js
var PrintOptionsSchema = exports_external.object({
x: exports_external.number(),
y: exports_external.number(),
text: exports_external.union([
exports_external.union([exports_external.string(), exports_external.number()]),
exports_external.object({
text: exports_external.union([exports_external.string(), exports_external.number()]),
alignmentX: exports_external.nativeEnum(HorizontalAlign).optional(),
alignmentY: exports_external.nativeEnum(VerticalAlign).optional()
})
]),
maxWidth: exports_external.number().optional(),
maxHeight: exports_external.number().optional(),
cb: exports_external.function(exports_external.tuple([exports_external.object({ x: exports_external.number(), y: exports_external.number() })])).optional()
});
function xOffsetBasedOnAlignment(font, line, maxWidth, alignment) {
if (alignment === HorizontalAlign.LEFT) {
return 0;
}
if (alignment === HorizontalAlign.CENTER) {
return (maxWidth - measureText(font, line)) / 2;
}
return maxWidth - measureText(font, line);
}
function drawCharacter(image2, font, x, y, char) {
if (char.width > 0 && char.height > 0) {
const characterPage = font.pages[char.page];
if (characterPage) {
image2 = methods.blit(image2, {
src: characterPage,
x: x + char.xoffset,
y: y + char.yoffset,
srcX: char.x,
srcY: char.y,
srcW: char.width,
srcH: char.height
});
}
}
return image2;
}
function printText(image2, font, x, y, text, defaultCharWidth) {
for (let i = 0;i < text.length; i++) {
const stringChar = text[i];
let char;
if (font.chars[stringChar]) {
char = stringChar;
} else if (/\s/.test(stringChar)) {
char = "";
} else {
char = "?";
}
const fontChar = font.chars[char] || { xadvance: undefined };
const fontKerning = font.kernings[char];
if (fontChar) {
drawCharacter(image2, font, x, y, fontChar);
}
const nextChar = text[i + 1];
const kerning = fontKerning && nextChar && fontKerning[nextChar] ? fontKerning[nextChar] || 0 : 0;
x += kerning + (fontChar.xadvance || defaultCharWidth);
}
}
var methods15 = {
print(image2, { font, ...options }) {
let {
x,
y,
text,
maxWidth = Infinity,
maxHeight = Infinity,
cb = () => {}
} = PrintOptionsSchema.parse(options);
let alignmentX;
let alignmentY;
if (typeof text === "object" && text.text !== null && text.text !== undefined) {
alignmentX = text.alignmentX || HorizontalAlign.LEFT;
alignmentY = text.alignmentY || VerticalAlign.TOP;
({ text } = text);
} else {
alignmentX = HorizontalAlign.LEFT;
alignmentY = VerticalAlign.TOP;
text = text.toString();
}
if (typeof text === "number") {
text = text.toString();
}
if (maxHeight !== Infinity && alignmentY === VerticalAlign.BOTTOM) {
y += maxHeight - measureTextHeight(font, text, maxWidth);
} else if (maxHeight !== Infinity && alignmentY === VerticalAlign.MIDDLE) {
y += maxHeight / 2 - measureTextHeight(font, text, maxWidth) / 2;
}
const defaultCharWidth = Object.entries(font.chars).find((c2) => c2[1].xadvance)?.[1].xadvance;
if (typeof defaultCharWidth !== "number") {
throw new Error("Could not find default character width");
}
const { lines, longestLine } = splitLines(font, text, maxWidth);
lines.forEach((line) => {
const lineString = line.join(" ");
const alignmentWidth = xOffsetBasedOnAlignment(font, lineString, maxWidth, alignmentX);
printText(image2, font, x + alignmentWidth, y, lineString, defaultCharWidth);
y += font.common.lineHeight;
});
cb.bind(image2)({ x: x + longestLine, y });
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-rotate@1.6.0/node_modules/@jimp/plugin-rotate/dist/esm/index.js
var RotateOptionsSchema = exports_external.union([
exports_external.number(),
exports_external.object({
deg: exports_external.number(),
mode: exports_external.union([exports_external.boolean(), exports_external.nativeEnum(ResizeStrategy)]).optional()
})
]);
function createIdxTranslationFunction(w) {
return function(x, y) {
return y * w + x << 2;
};
}
function matrixRotate(image2, deg) {
if (Math.abs(deg) % 90 !== 0) {
throw new Error("Unsupported matrix rotation degree");
}
const w = image2.bitmap.width;
const h = image2.bitmap.height;
let angle;
switch (deg) {
case 90:
case -270:
angle = 90;
break;
case 180:
case -180:
angle = 180;
break;
case 270:
case -90:
angle = -90;
break;
default:
throw new Error("Unsupported matrix rotation degree");
}
const nW = angle === 180 ? w : h;
const nH = angle === 180 ? h : w;
const dstBuffer = Buffer.alloc(image2.bitmap.data.length);
const srcIdxFunction = createIdxTranslationFunction(w);
const dstIdxFunction = createIdxTranslationFunction(nW);
for (let x = 0;x < w; x++) {
for (let y = 0;y < h; y++) {
const srcIdx = srcIdxFunction(x, y);
const pixelRGBA = image2.bitmap.data.readUInt32BE(srcIdx);
let dstIdx;
switch (angle) {
case 90:
dstIdx = dstIdxFunction(y, w - x - 1);
break;
case -90:
dstIdx = dstIdxFunction(h - y - 1, x);
break;
case 180:
dstIdx = dstIdxFunction(w - x - 1, h - y - 1);
break;
default:
throw new Error("Unsupported matrix rotation angle");
}
dstBuffer.writeUInt32BE(pixelRGBA, dstIdx);
}
}
image2.bitmap.data = dstBuffer;
image2.bitmap.width = nW;
image2.bitmap.height = nH;
}
function createTranslationFunction(deltaX, deltaY) {
return function(x, y) {
return {
x: x + deltaX,
y: y + deltaY
};
};
}
function advancedRotate(image2, deg, mode) {
const rad = deg * Math.PI / 180;
const cosine = Math.cos(rad);
const sine = Math.sin(rad);
let w = image2.bitmap.width;
let h = image2.bitmap.height;
if (mode === true || typeof mode === "string") {
w = Math.ceil(Math.abs(image2.bitmap.width * cosine) + Math.abs(image2.bitmap.height * sine)) + 1;
h = Math.ceil(Math.abs(image2.bitmap.width * sine) + Math.abs(image2.bitmap.height * cosine)) + 1;
if (w % 2 !== 0) {
w++;
}
if (h % 2 !== 0) {
h++;
}
const c2 = clone2(image2);
image2.scan((_, __, idx) => {
image2.bitmap.data.writeUInt32BE(image2.background, idx);
});
const max = Math.max(w, h, image2.bitmap.width, image2.bitmap.height);
image2 = methods5.resize(image2, {
h: max,
w: max,
mode: mode === true ? undefined : mode
});
image2 = composite(image2, c2, image2.bitmap.width / 2 - c2.bitmap.width / 2, image2.bitmap.height / 2 - c2.bitmap.height / 2);
}
const bW = image2.bitmap.width;
const bH = image2.bitmap.height;
const dstBuffer = Buffer.alloc(image2.bitmap.data.length);
const translate2Cartesian = createTranslationFunction(-(bW / 2), -(bH / 2));
const translate2Screen = createTranslationFunction(bW / 2 + 0.5, bH / 2 + 0.5);
for (let y = 1;y <= bH; y++) {
for (let x = 1;x <= bW; x++) {
const cartesian = translate2Cartesian(x, y);
const source = translate2Screen(cosine * cartesian.x - sine * cartesian.y, cosine * cartesian.y + sine * cartesian.x);
const dstIdx = bW * (y - 1) + x - 1 << 2;
if (source.x >= 0 && source.x < bW && source.y >= 0 && source.y < bH) {
const srcIdx = (bW * (source.y | 0) + source.x | 0) << 2;
const pixelRGBA = image2.bitmap.data.readUInt32BE(srcIdx);
dstBuffer.writeUInt32BE(pixelRGBA, dstIdx);
} else {
dstBuffer.writeUInt32BE(image2.background, dstIdx);
}
}
}
image2.bitmap.data = dstBuffer;
if (mode === true || typeof mode === "string") {
const x = Math.max(bW / 2 - w / 2, 0);
const y = Math.max(bH / 2 - h / 2, 0);
image2 = methods7.crop(image2, { x, y, w, h });
}
}
var methods16 = {
rotate(image2, options) {
const parsed = RotateOptionsSchema.parse(options);
const actualOptions = typeof parsed === "number" ? { deg: parsed } : parsed;
const { mode = true } = actualOptions;
let { deg } = actualOptions;
deg %= 360;
if (deg % 360 === 0) {
return image2;
}
const matrixRotateAllowed = deg % 90 === 0 && (mode || image2.bitmap.width === image2.bitmap.height || deg % 180 === 0);
if (matrixRotateAllowed) {
matrixRotate(image2, deg);
} else {
advancedRotate(image2, deg, mode);
}
return image2;
}
};
// ../../node_modules/.bun/@jimp+plugin-threshold@1.6.0/node_modules/@jimp/plugin-threshold/dist/esm/index.js
var ThresholdOptionsSchema = exports_external.object({
max: exports_external.number().min(0).max(255),
replace: exports_external.number().min(0).max(255).optional(),
autoGreyscale: exports_external.boolean().optional()
});
var methods17 = {
threshold(image2, options) {
let {
max,
replace = 255,
autoGreyscale = true
} = ThresholdOptionsSchema.parse(options);
max = limit255(max);
replace = limit255(replace);
if (autoGreyscale) {
methods4.greyscale(image2);
}
image2.scan((_, __, idx) => {
const grey = image2.bitmap.data[idx] < max ? image2.bitmap.data[idx] : replace;
image2.bitmap.data[idx] = grey;
image2.bitmap.data[idx + 1] = grey;
image2.bitmap.data[idx + 2] = grey;
});
return image2;
}
};
// ../../node_modules/.bun/image-q@4.0.0/node_modules/image-q/dist/esm/image-q.mjs
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => (key in obj) ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __export2 = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var constants_exports = {};
__export2(constants_exports, {
bt709: () => bt709_exports
});
var bt709_exports = {};
__export2(bt709_exports, {
Y: () => Y,
x: () => x,
y: () => y
});
var Y = /* @__PURE__ */ ((Y2) => {
Y2[Y2["RED"] = 0.2126] = "RED";
Y2[Y2["GREEN"] = 0.7152] = "GREEN";
Y2[Y2["BLUE"] = 0.0722] = "BLUE";
Y2[Y2["WHITE"] = 1] = "WHITE";
return Y2;
})(Y || {});
var x = /* @__PURE__ */ ((x2) => {
x2[x2["RED"] = 0.64] = "RED";
x2[x2["GREEN"] = 0.3] = "GREEN";
x2[x2["BLUE"] = 0.15] = "BLUE";
x2[x2["WHITE"] = 0.3127] = "WHITE";
return x2;
})(x || {});
var y = /* @__PURE__ */ ((y2) => {
y2[y2["RED"] = 0.33] = "RED";
y2[y2["GREEN"] = 0.6] = "GREEN";
y2[y2["BLUE"] = 0.06] = "BLUE";
y2[y2["WHITE"] = 0.329] = "WHITE";
return y2;
})(y || {});
var conversion_exports = {};
__export2(conversion_exports, {
lab2rgb: () => lab2rgb,
lab2xyz: () => lab2xyz,
rgb2hsl: () => rgb2hsl,
rgb2lab: () => rgb2lab,
rgb2xyz: () => rgb2xyz,
xyz2lab: () => xyz2lab,
xyz2rgb: () => xyz2rgb
});
function correctGamma(n) {
return n > 0.04045 ? ((n + 0.055) / 1.055) ** 2.4 : n / 12.92;
}
function rgb2xyz(r, g, b) {
r = correctGamma(r / 255);
g = correctGamma(g / 255);
b = correctGamma(b / 255);
return {
x: r * 0.4124 + g * 0.3576 + b * 0.1805,
y: r * 0.2126 + g * 0.7152 + b * 0.0722,
z: r * 0.0193 + g * 0.1192 + b * 0.9505
};
}
var arithmetic_exports = {};
__export2(arithmetic_exports, {
degrees2radians: () => degrees2radians,
inRange0to255: () => inRange0to255,
inRange0to255Rounded: () => inRange0to255Rounded,
intInRange: () => intInRange,
max3: () => max3,
min3: () => min3,
stableSort: () => stableSort
});
function degrees2radians(n) {
return n * (Math.PI / 180);
}
function max3(a, b, c2) {
let m = a;
if (m < b)
m = b;
if (m < c2)
m = c2;
return m;
}
function min3(a, b, c2) {
let m = a;
if (m > b)
m = b;
if (m > c2)
m = c2;
return m;
}
function intInRange(value, low, high) {
if (value > high)
value = high;
if (value < low)
value = low;
return value | 0;
}
function inRange0to255Rounded(n) {
n = Math.round(n);
if (n > 255)
n = 255;
else if (n < 0)
n = 0;
return n;
}
function inRange0to255(n) {
if (n > 255)
n = 255;
else if (n < 0)
n = 0;
return n;
}
function stableSort(arrayToSort, callback) {
const type = typeof arrayToSort[0];
let sorted;
if (type === "number" || type === "string") {
const ord = /* @__PURE__ */ Object.create(null);
for (let i = 0, l = arrayToSort.length;i < l; i++) {
const val = arrayToSort[i];
if (ord[val] || ord[val] === 0)
continue;
ord[val] = i;
}
sorted = arrayToSort.sort((a, b) => callback(a, b) || ord[a] - ord[b]);
} else {
const ord2 = arrayToSort.slice(0);
sorted = arrayToSort.sort((a, b) => callback(a, b) || ord2.indexOf(a) - ord2.indexOf(b));
}
return sorted;
}
function rgb2hsl(r, g, b) {
const min = min3(r, g, b);
const max = max3(r, g, b);
const delta = max - min;
const l = (min + max) / 510;
let s = 0;
if (l > 0 && l < 1)
s = delta / (l < 0.5 ? max + min : 510 - max - min);
let h = 0;
if (delta > 0) {
if (max === r) {
h = (g - b) / delta;
} else if (max === g) {
h = 2 + (b - r) / delta;
} else {
h = 4 + (r - g) / delta;
}
h *= 60;
if (h < 0)
h += 360;
}
return { h, s, l };
}
var refX = 0.95047;
var refY = 1;
var refZ = 1.08883;
function pivot(n) {
return n > 0.008856 ? n ** (1 / 3) : 7.787 * n + 16 / 116;
}
function xyz2lab(x2, y2, z) {
x2 = pivot(x2 / refX);
y2 = pivot(y2 / refY);
z = pivot(z / refZ);
if (116 * y2 - 16 < 0)
throw new Error("xxx");
return {
L: Math.max(0, 116 * y2 - 16),
a: 500 * (x2 - y2),
b: 200 * (y2 - z)
};
}
function rgb2lab(r, g, b) {
const xyz = rgb2xyz(r, g, b);
return xyz2lab(xyz.x, xyz.y, xyz.z);
}
var refX2 = 0.95047;
var refY2 = 1;
var refZ2 = 1.08883;
function pivot2(n) {
return n > 0.206893034 ? n ** 3 : (n - 16 / 116) / 7.787;
}
function lab2xyz(L, a, b) {
const y2 = (L + 16) / 116;
const x2 = a / 500 + y2;
const z = y2 - b / 200;
return {
x: refX2 * pivot2(x2),
y: refY2 * pivot2(y2),
z: refZ2 * pivot2(z)
};
}
function correctGamma2(n) {
return n > 0.0031308 ? 1.055 * n ** (1 / 2.4) - 0.055 : 12.92 * n;
}
function xyz2rgb(x2, y2, z) {
const r = correctGamma2(x2 * 3.2406 + y2 * -1.5372 + z * -0.4986);
const g = correctGamma2(x2 * -0.9689 + y2 * 1.8758 + z * 0.0415);
const b = correctGamma2(x2 * 0.0557 + y2 * -0.204 + z * 1.057);
return {
r: inRange0to255Rounded(r * 255),
g: inRange0to255Rounded(g * 255),
b: inRange0to255Rounded(b * 255)
};
}
function lab2rgb(L, a, b) {
const xyz = lab2xyz(L, a, b);
return xyz2rgb(xyz.x, xyz.y, xyz.z);
}
var distance_exports = {};
__export2(distance_exports, {
AbstractDistanceCalculator: () => AbstractDistanceCalculator,
AbstractEuclidean: () => AbstractEuclidean,
AbstractManhattan: () => AbstractManhattan,
CIE94GraphicArts: () => CIE94GraphicArts,
CIE94Textiles: () => CIE94Textiles,
CIEDE2000: () => CIEDE2000,
CMetric: () => CMetric,
Euclidean: () => Euclidean,
EuclideanBT709: () => EuclideanBT709,
EuclideanBT709NoAlpha: () => EuclideanBT709NoAlpha,
Manhattan: () => Manhattan,
ManhattanBT709: () => ManhattanBT709,
ManhattanNommyde: () => ManhattanNommyde,
PNGQuant: () => PNGQuant
});
var AbstractDistanceCalculator = class {
constructor() {
__publicField(this, "_maxDistance");
__publicField(this, "_whitePoint");
this._setDefaults();
this.setWhitePoint(255, 255, 255, 255);
}
setWhitePoint(r, g, b, a) {
this._whitePoint = {
r: r > 0 ? 255 / r : 0,
g: g > 0 ? 255 / g : 0,
b: b > 0 ? 255 / b : 0,
a: a > 0 ? 255 / a : 0
};
this._maxDistance = this.calculateRaw(r, g, b, a, 0, 0, 0, 0);
}
calculateNormalized(colorA, colorB) {
return this.calculateRaw(colorA.r, colorA.g, colorA.b, colorA.a, colorB.r, colorB.g, colorB.b, colorB.a) / this._maxDistance;
}
};
var AbstractCIE94 = class extends AbstractDistanceCalculator {
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
const lab1 = rgb2lab(inRange0to255(r1 * this._whitePoint.r), inRange0to255(g1 * this._whitePoint.g), inRange0to255(b1 * this._whitePoint.b));
const lab2 = rgb2lab(inRange0to255(r2 * this._whitePoint.r), inRange0to255(g2 * this._whitePoint.g), inRange0to255(b2 * this._whitePoint.b));
const dL = lab1.L - lab2.L;
const dA = lab1.a - lab2.a;
const dB = lab1.b - lab2.b;
const c1 = Math.sqrt(lab1.a * lab1.a + lab1.b * lab1.b);
const c2 = Math.sqrt(lab2.a * lab2.a + lab2.b * lab2.b);
const dC = c1 - c2;
let deltaH = dA * dA + dB * dB - dC * dC;
deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH);
const dAlpha = (a2 - a1) * this._whitePoint.a * this._kA;
return Math.sqrt((dL / this._Kl) ** 2 + (dC / (1 + this._K1 * c1)) ** 2 + (deltaH / (1 + this._K2 * c1)) ** 2 + dAlpha ** 2);
}
};
var CIE94Textiles = class extends AbstractCIE94 {
_setDefaults() {
this._Kl = 2;
this._K1 = 0.048;
this._K2 = 0.014;
this._kA = 0.25 * 50 / 255;
}
};
var CIE94GraphicArts = class extends AbstractCIE94 {
_setDefaults() {
this._Kl = 1;
this._K1 = 0.045;
this._K2 = 0.015;
this._kA = 0.25 * 100 / 255;
}
};
var _CIEDE2000 = class extends AbstractDistanceCalculator {
_setDefaults() {}
static _calculatehp(b, ap) {
const hp = Math.atan2(b, ap);
if (hp >= 0)
return hp;
return hp + _CIEDE2000._deg360InRad;
}
static _calculateRT(ahp, aCp) {
const aCp_to_7 = aCp ** 7;
const R_C = 2 * Math.sqrt(aCp_to_7 / (aCp_to_7 + _CIEDE2000._pow25to7));
const delta_theta = _CIEDE2000._deg30InRad * Math.exp(-(((ahp - _CIEDE2000._deg275InRad) / _CIEDE2000._deg25InRad) ** 2));
return -Math.sin(2 * delta_theta) * R_C;
}
static _calculateT(ahp) {
return 1 - 0.17 * Math.cos(ahp - _CIEDE2000._deg30InRad) + 0.24 * Math.cos(ahp * 2) + 0.32 * Math.cos(ahp * 3 + _CIEDE2000._deg6InRad) - 0.2 * Math.cos(ahp * 4 - _CIEDE2000._deg63InRad);
}
static _calculate_ahp(C1pC2p, h_bar, h1p, h2p) {
const hpSum = h1p + h2p;
if (C1pC2p === 0)
return hpSum;
if (h_bar <= _CIEDE2000._deg180InRad)
return hpSum / 2;
if (hpSum < _CIEDE2000._deg360InRad) {
return (hpSum + _CIEDE2000._deg360InRad) / 2;
}
return (hpSum - _CIEDE2000._deg360InRad) / 2;
}
static _calculate_dHp(C1pC2p, h_bar, h2p, h1p) {
let dhp;
if (C1pC2p === 0) {
dhp = 0;
} else if (h_bar <= _CIEDE2000._deg180InRad) {
dhp = h2p - h1p;
} else if (h2p <= h1p) {
dhp = h2p - h1p + _CIEDE2000._deg360InRad;
} else {
dhp = h2p - h1p - _CIEDE2000._deg360InRad;
}
return 2 * Math.sqrt(C1pC2p) * Math.sin(dhp / 2);
}
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
const lab1 = rgb2lab(inRange0to255(r1 * this._whitePoint.r), inRange0to255(g1 * this._whitePoint.g), inRange0to255(b1 * this._whitePoint.b));
const lab2 = rgb2lab(inRange0to255(r2 * this._whitePoint.r), inRange0to255(g2 * this._whitePoint.g), inRange0to255(b2 * this._whitePoint.b));
const dA = (a2 - a1) * this._whitePoint.a * _CIEDE2000._kA;
const dE2 = this.calculateRawInLab(lab1, lab2);
return Math.sqrt(dE2 + dA * dA);
}
calculateRawInLab(Lab1, Lab2) {
const L1 = Lab1.L;
const a1 = Lab1.a;
const b1 = Lab1.b;
const L2 = Lab2.L;
const a2 = Lab2.a;
const b2 = Lab2.b;
const C1 = Math.sqrt(a1 * a1 + b1 * b1);
const C2 = Math.sqrt(a2 * a2 + b2 * b2);
const pow_a_C1_C2_to_7 = ((C1 + C2) / 2) ** 7;
const G = 0.5 * (1 - Math.sqrt(pow_a_C1_C2_to_7 / (pow_a_C1_C2_to_7 + _CIEDE2000._pow25to7)));
const a1p = (1 + G) * a1;
const a2p = (1 + G) * a2;
const C1p = Math.sqrt(a1p * a1p + b1 * b1);
const C2p = Math.sqrt(a2p * a2p + b2 * b2);
const C1pC2p = C1p * C2p;
const h1p = _CIEDE2000._calculatehp(b1, a1p);
const h2p = _CIEDE2000._calculatehp(b2, a2p);
const h_bar = Math.abs(h1p - h2p);
const dLp = L2 - L1;
const dCp = C2p - C1p;
const dHp = _CIEDE2000._calculate_dHp(C1pC2p, h_bar, h2p, h1p);
const ahp = _CIEDE2000._calculate_ahp(C1pC2p, h_bar, h1p, h2p);
const T = _CIEDE2000._calculateT(ahp);
const aCp = (C1p + C2p) / 2;
const aLp_minus_50_square = ((L1 + L2) / 2 - 50) ** 2;
const S_L = 1 + 0.015 * aLp_minus_50_square / Math.sqrt(20 + aLp_minus_50_square);
const S_C = 1 + 0.045 * aCp;
const S_H = 1 + 0.015 * T * aCp;
const R_T = _CIEDE2000._calculateRT(ahp, aCp);
const dLpSL = dLp / S_L;
const dCpSC = dCp / S_C;
const dHpSH = dHp / S_H;
return dLpSL ** 2 + dCpSC ** 2 + dHpSH ** 2 + R_T * dCpSC * dHpSH;
}
};
var CIEDE2000 = _CIEDE2000;
__publicField(CIEDE2000, "_kA", 0.25 * 100 / 255);
__publicField(CIEDE2000, "_pow25to7", 25 ** 7);
__publicField(CIEDE2000, "_deg360InRad", degrees2radians(360));
__publicField(CIEDE2000, "_deg180InRad", degrees2radians(180));
__publicField(CIEDE2000, "_deg30InRad", degrees2radians(30));
__publicField(CIEDE2000, "_deg6InRad", degrees2radians(6));
__publicField(CIEDE2000, "_deg63InRad", degrees2radians(63));
__publicField(CIEDE2000, "_deg275InRad", degrees2radians(275));
__publicField(CIEDE2000, "_deg25InRad", degrees2radians(25));
var CMetric = class extends AbstractDistanceCalculator {
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
const rmean = (r1 + r2) / 2 * this._whitePoint.r;
const r = (r1 - r2) * this._whitePoint.r;
const g = (g1 - g2) * this._whitePoint.g;
const b = (b1 - b2) * this._whitePoint.b;
const dE = ((512 + rmean) * r * r >> 8) + 4 * g * g + ((767 - rmean) * b * b >> 8);
const dA = (a2 - a1) * this._whitePoint.a;
return Math.sqrt(dE + dA * dA);
}
_setDefaults() {}
};
var AbstractEuclidean = class extends AbstractDistanceCalculator {
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
const dR = r2 - r1;
const dG = g2 - g1;
const dB = b2 - b1;
const dA = a2 - a1;
return Math.sqrt(this._kR * dR * dR + this._kG * dG * dG + this._kB * dB * dB + this._kA * dA * dA);
}
};
var Euclidean = class extends AbstractEuclidean {
_setDefaults() {
this._kR = 1;
this._kG = 1;
this._kB = 1;
this._kA = 1;
}
};
var EuclideanBT709 = class extends AbstractEuclidean {
_setDefaults() {
this._kR = 0.2126;
this._kG = 0.7152;
this._kB = 0.0722;
this._kA = 1;
}
};
var EuclideanBT709NoAlpha = class extends AbstractEuclidean {
_setDefaults() {
this._kR = 0.2126;
this._kG = 0.7152;
this._kB = 0.0722;
this._kA = 0;
}
};
var AbstractManhattan = class extends AbstractDistanceCalculator {
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
let dR = r2 - r1;
let dG = g2 - g1;
let dB = b2 - b1;
let dA = a2 - a1;
if (dR < 0)
dR = 0 - dR;
if (dG < 0)
dG = 0 - dG;
if (dB < 0)
dB = 0 - dB;
if (dA < 0)
dA = 0 - dA;
return this._kR * dR + this._kG * dG + this._kB * dB + this._kA * dA;
}
};
var Manhattan = class extends AbstractManhattan {
_setDefaults() {
this._kR = 1;
this._kG = 1;
this._kB = 1;
this._kA = 1;
}
};
var ManhattanNommyde = class extends AbstractManhattan {
_setDefaults() {
this._kR = 0.4984;
this._kG = 0.8625;
this._kB = 0.2979;
this._kA = 1;
}
};
var ManhattanBT709 = class extends AbstractManhattan {
_setDefaults() {
this._kR = 0.2126;
this._kG = 0.7152;
this._kB = 0.0722;
this._kA = 1;
}
};
var PNGQuant = class extends AbstractDistanceCalculator {
calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {
const alphas = (a2 - a1) * this._whitePoint.a;
return this._colordifferenceCh(r1 * this._whitePoint.r, r2 * this._whitePoint.r, alphas) + this._colordifferenceCh(g1 * this._whitePoint.g, g2 * this._whitePoint.g, alphas) + this._colordifferenceCh(b1 * this._whitePoint.b, b2 * this._whitePoint.b, alphas);
}
_colordifferenceCh(x2, y2, alphas) {
const black = x2 - y2;
const white = black + alphas;
return black * black + white * white;
}
_setDefaults() {}
};
var palette_exports = {};
__export2(palette_exports, {
AbstractPaletteQuantizer: () => AbstractPaletteQuantizer,
ColorHistogram: () => ColorHistogram,
NeuQuant: () => NeuQuant,
NeuQuantFloat: () => NeuQuantFloat,
RGBQuant: () => RGBQuant,
WuColorCube: () => WuColorCube,
WuQuant: () => WuQuant
});
var AbstractPaletteQuantizer = class {
quantizeSync() {
for (const value of this.quantize()) {
if (value.palette) {
return value.palette;
}
}
throw new Error("unreachable");
}
};
var Point = class {
constructor() {
__publicField(this, "r");
__publicField(this, "g");
__publicField(this, "b");
__publicField(this, "a");
__publicField(this, "uint32");
__publicField(this, "rgba");
this.uint32 = -1 >>> 0;
this.r = this.g = this.b = this.a = 0;
this.rgba = new Array(4);
this.rgba[0] = 0;
this.rgba[1] = 0;
this.rgba[2] = 0;
this.rgba[3] = 0;
}
static createByQuadruplet(quadruplet) {
const point = new Point;
point.r = quadruplet[0] | 0;
point.g = quadruplet[1] | 0;
point.b = quadruplet[2] | 0;
point.a = quadruplet[3] | 0;
point._loadUINT32();
point._loadQuadruplet();
return point;
}
static createByRGBA(red, green, blue, alpha) {
const point = new Point;
point.r = red | 0;
point.g = green | 0;
point.b = blue | 0;
point.a = alpha | 0;
point._loadUINT32();
point._loadQuadruplet();
return point;
}
static createByUint32(uint32) {
const point = new Point;
point.uint32 = uint32 >>> 0;
point._loadRGBA();
point._loadQuadruplet();
return point;
}
from(point) {
this.r = point.r;
this.g = point.g;
this.b = point.b;
this.a = point.a;
this.uint32 = point.uint32;
this.rgba[0] = point.r;
this.rgba[1] = point.g;
this.rgba[2] = point.b;
this.rgba[3] = point.a;
}
getLuminosity(useAlphaChannel) {
let r = this.r;
let g = this.g;
let b = this.b;
if (useAlphaChannel) {
r = Math.min(255, 255 - this.a + this.a * r / 255);
g = Math.min(255, 255 - this.a + this.a * g / 255);
b = Math.min(255, 255 - this.a + this.a * b / 255);
}
return r * 0.2126 + g * 0.7152 + b * 0.0722;
}
_loadUINT32() {
this.uint32 = (this.a << 24 | this.b << 16 | this.g << 8 | this.r) >>> 0;
}
_loadRGBA() {
this.r = this.uint32 & 255;
this.g = this.uint32 >>> 8 & 255;
this.b = this.uint32 >>> 16 & 255;
this.a = this.uint32 >>> 24 & 255;
}
_loadQuadruplet() {
this.rgba[0] = this.r;
this.rgba[1] = this.g;
this.rgba[2] = this.b;
this.rgba[3] = this.a;
}
};
var PointContainer = class {
constructor() {
__publicField(this, "_pointArray");
__publicField(this, "_width");
__publicField(this, "_height");
this._width = 0;
this._height = 0;
this._pointArray = [];
}
getWidth() {
return this._width;
}
getHeight() {
return this._height;
}
setWidth(width) {
this._width = width;
}
setHeight(height) {
this._height = height;
}
getPointArray() {
return this._pointArray;
}
clone() {
const clone3 = new PointContainer;
clone3._width = this._width;
clone3._height = this._height;
for (let i = 0, l = this._pointArray.length;i < l; i++) {
clone3._pointArray[i] = Point.createByUint32(this._pointArray[i].uint32 | 0);
}
return clone3;
}
toUint32Array() {
const l = this._pointArray.length;
const uint32Array = new Uint32Array(l);
for (let i = 0;i < l; i++) {
uint32Array[i] = this._pointArray[i].uint32;
}
return uint32Array;
}
toUint8Array() {
return new Uint8Array(this.toUint32Array().buffer);
}
static fromHTMLImageElement(img) {
const width = img.naturalWidth;
const height = img.naturalHeight;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height, 0, 0, width, height);
return PointContainer.fromHTMLCanvasElement(canvas);
}
static fromHTMLCanvasElement(canvas) {
const width = canvas.width;
const height = canvas.height;
const ctx = canvas.getContext("2d");
const imgData = ctx.getImageData(0, 0, width, height);
return PointContainer.fromImageData(imgData);
}
static fromImageData(imageData) {
const width = imageData.width;
const height = imageData.height;
return PointContainer.fromUint8Array(imageData.data, width, height);
}
static fromUint8Array(uint8Array, width, height) {
switch (Object.prototype.toString.call(uint8Array)) {
case "[object Uint8ClampedArray]":
case "[object Uint8Array]":
break;
default:
uint8Array = new Uint8Array(uint8Array);
}
const uint32Array = new Uint32Array(uint8Array.buffer);
return PointContainer.fromUint32Array(uint32Array, width, height);
}
static fromUint32Array(uint32Array, width, height) {
const container = new PointContainer;
container._width = width;
container._height = height;
for (let i = 0, l = uint32Array.length;i < l; i++) {
container._pointArray[i] = Point.createByUint32(uint32Array[i] | 0);
}
return container;
}
static fromBuffer(buffer, width, height) {
const uint32Array = new Uint32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Uint32Array.BYTES_PER_ELEMENT);
return PointContainer.fromUint32Array(uint32Array, width, height);
}
};
var hueGroups = 10;
function hueGroup(hue, segmentsNumber) {
const maxHue = 360;
const seg = maxHue / segmentsNumber;
const half = seg / 2;
for (let i = 1, mid = seg - half;i < segmentsNumber; i++, mid += seg) {
if (hue >= mid && hue < mid + seg)
return i;
}
return 0;
}
var Palette = class {
constructor() {
__publicField(this, "_pointContainer");
__publicField(this, "_pointArray", []);
__publicField(this, "_i32idx", {});
this._pointContainer = new PointContainer;
this._pointContainer.setHeight(1);
this._pointArray = this._pointContainer.getPointArray();
}
add(color) {
this._pointArray.push(color);
this._pointContainer.setWidth(this._pointArray.length);
}
has(color) {
for (let i = this._pointArray.length - 1;i >= 0; i--) {
if (color.uint32 === this._pointArray[i].uint32)
return true;
}
return false;
}
getNearestColor(colorDistanceCalculator, color) {
return this._pointArray[this._getNearestIndex(colorDistanceCalculator, color) | 0];
}
getPointContainer() {
return this._pointContainer;
}
_nearestPointFromCache(key) {
return typeof this._i32idx[key] === "number" ? this._i32idx[key] : -1;
}
_getNearestIndex(colorDistanceCalculator, point) {
let idx = this._nearestPointFromCache("" + point.uint32);
if (idx >= 0)
return idx;
let minimalDistance = Number.MAX_VALUE;
idx = 0;
for (let i = 0, l = this._pointArray.length;i < l; i++) {
const p = this._pointArray[i];
const distance2 = colorDistanceCalculator.calculateRaw(point.r, point.g, point.b, point.a, p.r, p.g, p.b, p.a);
if (distance2 < minimalDistance) {
minimalDistance = distance2;
idx = i;
}
}
this._i32idx[point.uint32] = idx;
return idx;
}
sort() {
this._i32idx = {};
this._pointArray.sort((a, b) => {
const hslA = rgb2hsl(a.r, a.g, a.b);
const hslB = rgb2hsl(b.r, b.g, b.b);
const hueA = a.r === a.g && a.g === a.b ? 0 : 1 + hueGroup(hslA.h, hueGroups);
const hueB = b.r === b.g && b.g === b.b ? 0 : 1 + hueGroup(hslB.h, hueGroups);
const hueDiff = hueB - hueA;
if (hueDiff)
return -hueDiff;
const lA = a.getLuminosity(true);
const lB = b.getLuminosity(true);
if (lB - lA !== 0)
return lB - lA;
const satDiff = (hslB.s * 100 | 0) - (hslA.s * 100 | 0);
if (satDiff)
return -satDiff;
return 0;
});
}
};
var utils_exports = {};
__export2(utils_exports, {
HueStatistics: () => HueStatistics,
Palette: () => Palette,
Point: () => Point,
PointContainer: () => PointContainer,
ProgressTracker: () => ProgressTracker,
arithmetic: () => arithmetic_exports
});
var HueGroup = class {
constructor() {
__publicField(this, "num", 0);
__publicField(this, "cols", []);
}
};
var HueStatistics = class {
constructor(numGroups, minCols) {
__publicField(this, "_numGroups");
__publicField(this, "_minCols");
__publicField(this, "_stats");
__publicField(this, "_groupsFull");
this._numGroups = numGroups;
this._minCols = minCols;
this._stats = [];
for (let i = 0;i <= numGroups; i++) {
this._stats[i] = new HueGroup;
}
this._groupsFull = 0;
}
check(i32) {
if (this._groupsFull === this._numGroups + 1) {
this.check = () => {};
}
const r = i32 & 255;
const g = i32 >>> 8 & 255;
const b = i32 >>> 16 & 255;
const hg = r === g && g === b ? 0 : 1 + hueGroup(rgb2hsl(r, g, b).h, this._numGroups);
const gr = this._stats[hg];
const min = this._minCols;
gr.num++;
if (gr.num > min) {
return;
}
if (gr.num === min) {
this._groupsFull++;
}
if (gr.num <= min) {
this._stats[hg].cols.push(i32);
}
}
injectIntoDictionary(histG) {
for (let i = 0;i <= this._numGroups; i++) {
if (this._stats[i].num <= this._minCols) {
this._stats[i].cols.forEach((col) => {
if (!histG[col]) {
histG[col] = 1;
} else {
histG[col]++;
}
});
}
}
}
injectIntoArray(histG) {
for (let i = 0;i <= this._numGroups; i++) {
if (this._stats[i].num <= this._minCols) {
this._stats[i].cols.forEach((col) => {
if (histG.indexOf(col) === -1) {
histG.push(col);
}
});
}
}
}
};
var _ProgressTracker = class {
constructor(valueRange, progressRange) {
__publicField(this, "progress");
__publicField(this, "_step");
__publicField(this, "_range");
__publicField(this, "_last");
__publicField(this, "_progressRange");
this._range = valueRange;
this._progressRange = progressRange;
this._step = Math.max(1, this._range / (_ProgressTracker.steps + 1) | 0);
this._last = -this._step;
this.progress = 0;
}
shouldNotify(current) {
if (current - this._last >= this._step) {
this._last = current;
this.progress = Math.min(this._progressRange * this._last / this._range, this._progressRange);
return true;
}
return false;
}
};
var ProgressTracker = _ProgressTracker;
__publicField(ProgressTracker, "steps", 100);
var networkBiasShift = 3;
var Neuron = class {
constructor(defaultValue) {
__publicField(this, "r");
__publicField(this, "g");
__publicField(this, "b");
__publicField(this, "a");
this.r = this.g = this.b = this.a = defaultValue;
}
toPoint() {
return Point.createByRGBA(this.r >> networkBiasShift, this.g >> networkBiasShift, this.b >> networkBiasShift, this.a >> networkBiasShift);
}
subtract(r, g, b, a) {
this.r -= r | 0;
this.g -= g | 0;
this.b -= b | 0;
this.a -= a | 0;
}
};
var _NeuQuant = class extends AbstractPaletteQuantizer {
constructor(colorDistanceCalculator, colors = 256) {
super();
__publicField(this, "_pointArray");
__publicField(this, "_networkSize");
__publicField(this, "_network");
__publicField(this, "_sampleFactor");
__publicField(this, "_radPower");
__publicField(this, "_freq");
__publicField(this, "_bias");
__publicField(this, "_distance");
this._distance = colorDistanceCalculator;
this._pointArray = [];
this._sampleFactor = 1;
this._networkSize = colors;
this._distance.setWhitePoint(255 << networkBiasShift, 255 << networkBiasShift, 255 << networkBiasShift, 255 << networkBiasShift);
}
sample(pointContainer) {
this._pointArray = this._pointArray.concat(pointContainer.getPointArray());
}
*quantize() {
this._init();
yield* this._learn();
yield {
palette: this._buildPalette(),
progress: 100
};
}
_init() {
this._freq = [];
this._bias = [];
this._radPower = [];
this._network = [];
for (let i = 0;i < this._networkSize; i++) {
this._network[i] = new Neuron((i << networkBiasShift + 8) / this._networkSize | 0);
this._freq[i] = _NeuQuant._initialBias / this._networkSize | 0;
this._bias[i] = 0;
}
}
*_learn() {
let sampleFactor = this._sampleFactor;
const pointsNumber = this._pointArray.length;
if (pointsNumber < _NeuQuant._minpicturebytes)
sampleFactor = 1;
const alphadec = 30 + (sampleFactor - 1) / 3 | 0;
const pointsToSample = pointsNumber / sampleFactor | 0;
let delta = pointsToSample / _NeuQuant._nCycles | 0;
let alpha = _NeuQuant._initAlpha;
let radius = (this._networkSize >> 3) * _NeuQuant._radiusBias;
let rad = radius >> _NeuQuant._radiusBiasShift;
if (rad <= 1)
rad = 0;
for (let i = 0;i < rad; i++) {
this._radPower[i] = alpha * ((rad * rad - i * i) * _NeuQuant._radBias / (rad * rad)) >>> 0;
}
let step;
if (pointsNumber < _NeuQuant._minpicturebytes) {
step = 1;
} else if (pointsNumber % _NeuQuant._prime1 !== 0) {
step = _NeuQuant._prime1;
} else if (pointsNumber % _NeuQuant._prime2 !== 0) {
step = _NeuQuant._prime2;
} else if (pointsNumber % _NeuQuant._prime3 !== 0) {
step = _NeuQuant._prime3;
} else {
step = _NeuQuant._prime4;
}
const tracker = new ProgressTracker(pointsToSample, 99);
for (let i = 0, pointIndex = 0;i < pointsToSample; ) {
if (tracker.shouldNotify(i)) {
yield {
progress: tracker.progress
};
}
const point = this._pointArray[pointIndex];
const b = point.b << networkBiasShift;
const g = point.g << networkBiasShift;
const r = point.r << networkBiasShift;
const a = point.a << networkBiasShift;
const neuronIndex = this._contest(b, g, r, a);
this._alterSingle(alpha, neuronIndex, b, g, r, a);
if (rad !== 0)
this._alterNeighbour(rad, neuronIndex, b, g, r, a);
pointIndex += step;
if (pointIndex >= pointsNumber)
pointIndex -= pointsNumber;
i++;
if (delta === 0)
delta = 1;
if (i % delta === 0) {
alpha -= alpha / alphadec | 0;
radius -= radius / _NeuQuant._radiusDecrease | 0;
rad = radius >> _NeuQuant._radiusBiasShift;
if (rad <= 1)
rad = 0;
for (let j = 0;j < rad; j++) {
this._radPower[j] = alpha * ((rad * rad - j * j) * _NeuQuant._radBias / (rad * rad)) >>> 0;
}
}
}
}
_buildPalette() {
const palette2 = new Palette;
this._network.forEach((neuron) => {
palette2.add(neuron.toPoint());
});
palette2.sort();
return palette2;
}
_alterNeighbour(rad, i, b, g, r, al) {
let lo = i - rad;
if (lo < -1)
lo = -1;
let hi = i + rad;
if (hi > this._networkSize)
hi = this._networkSize;
let j = i + 1;
let k = i - 1;
let m = 1;
while (j < hi || k > lo) {
const a = this._radPower[m++] / _NeuQuant._alphaRadBias;
if (j < hi) {
const p = this._network[j++];
p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));
}
if (k > lo) {
const p = this._network[k--];
p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));
}
}
}
_alterSingle(alpha, i, b, g, r, a) {
alpha /= _NeuQuant._initAlpha;
const n = this._network[i];
n.subtract(alpha * (n.r - r), alpha * (n.g - g), alpha * (n.b - b), alpha * (n.a - a));
}
_contest(b, g, r, a) {
const multiplier = 255 * 4 << networkBiasShift;
let bestd = ~(1 << 31);
let bestbiasd = bestd;
let bestpos = -1;
let bestbiaspos = bestpos;
for (let i = 0;i < this._networkSize; i++) {
const n = this._network[i];
const dist = this._distance.calculateNormalized(n, { r, g, b, a }) * multiplier | 0;
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
const biasdist = dist - (this._bias[i] >> _NeuQuant._initialBiasShift - networkBiasShift);
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
const betafreq = this._freq[i] >> _NeuQuant._betaShift;
this._freq[i] -= betafreq;
this._bias[i] += betafreq << _NeuQuant._gammaShift;
}
this._freq[bestpos] += _NeuQuant._beta;
this._bias[bestpos] -= _NeuQuant._betaGamma;
return bestbiaspos;
}
};
var NeuQuant = _NeuQuant;
__publicField(NeuQuant, "_prime1", 499);
__publicField(NeuQuant, "_prime2", 491);
__publicField(NeuQuant, "_prime3", 487);
__publicField(NeuQuant, "_prime4", 503);
__publicField(NeuQuant, "_minpicturebytes", _NeuQuant._prime4);
__publicField(NeuQuant, "_nCycles", 100);
__publicField(NeuQuant, "_initialBiasShift", 16);
__publicField(NeuQuant, "_initialBias", 1 << _NeuQuant._initialBiasShift);
__publicField(NeuQuant, "_gammaShift", 10);
__publicField(NeuQuant, "_betaShift", 10);
__publicField(NeuQuant, "_beta", _NeuQuant._initialBias >> _NeuQuant._betaShift);
__publicField(NeuQuant, "_betaGamma", _NeuQuant._initialBias << _NeuQuant._gammaShift - _NeuQuant._betaShift);
__publicField(NeuQuant, "_radiusBiasShift", 6);
__publicField(NeuQuant, "_radiusBias", 1 << _NeuQuant._radiusBiasShift);
__publicField(NeuQuant, "_radiusDecrease", 30);
__publicField(NeuQuant, "_alphaBiasShift", 10);
__publicField(NeuQuant, "_initAlpha", 1 << _NeuQuant._alphaBiasShift);
__publicField(NeuQuant, "_radBiasShift", 8);
__publicField(NeuQuant, "_radBias", 1 << _NeuQuant._radBiasShift);
__publicField(NeuQuant, "_alphaRadBiasShift", _NeuQuant._alphaBiasShift + _NeuQuant._radBiasShift);
__publicField(NeuQuant, "_alphaRadBias", 1 << _NeuQuant._alphaRadBiasShift);
var networkBiasShift2 = 3;
var NeuronFloat = class {
constructor(defaultValue) {
__publicField(this, "r");
__publicField(this, "g");
__publicField(this, "b");
__publicField(this, "a");
this.r = this.g = this.b = this.a = defaultValue;
}
toPoint() {
return Point.createByRGBA(this.r >> networkBiasShift2, this.g >> networkBiasShift2, this.b >> networkBiasShift2, this.a >> networkBiasShift2);
}
subtract(r, g, b, a) {
this.r -= r;
this.g -= g;
this.b -= b;
this.a -= a;
}
};
var _NeuQuantFloat = class extends AbstractPaletteQuantizer {
constructor(colorDistanceCalculator, colors = 256) {
super();
__publicField(this, "_pointArray");
__publicField(this, "_networkSize");
__publicField(this, "_network");
__publicField(this, "_sampleFactor");
__publicField(this, "_radPower");
__publicField(this, "_freq");
__publicField(this, "_bias");
__publicField(this, "_distance");
this._distance = colorDistanceCalculator;
this._pointArray = [];
this._sampleFactor = 1;
this._networkSize = colors;
this._distance.setWhitePoint(255 << networkBiasShift2, 255 << networkBiasShift2, 255 << networkBiasShift2, 255 << networkBiasShift2);
}
sample(pointContainer) {
this._pointArray = this._pointArray.concat(pointContainer.getPointArray());
}
*quantize() {
this._init();
yield* this._learn();
yield {
palette: this._buildPalette(),
progress: 100
};
}
_init() {
this._freq = [];
this._bias = [];
this._radPower = [];
this._network = [];
for (let i = 0;i < this._networkSize; i++) {
this._network[i] = new NeuronFloat((i << networkBiasShift2 + 8) / this._networkSize);
this._freq[i] = _NeuQuantFloat._initialBias / this._networkSize;
this._bias[i] = 0;
}
}
*_learn() {
let sampleFactor = this._sampleFactor;
const pointsNumber = this._pointArray.length;
if (pointsNumber < _NeuQuantFloat._minpicturebytes)
sampleFactor = 1;
const alphadec = 30 + (sampleFactor - 1) / 3;
const pointsToSample = pointsNumber / sampleFactor;
let delta = pointsToSample / _NeuQuantFloat._nCycles | 0;
let alpha = _NeuQuantFloat._initAlpha;
let radius = (this._networkSize >> 3) * _NeuQuantFloat._radiusBias;
let rad = radius >> _NeuQuantFloat._radiusBiasShift;
if (rad <= 1)
rad = 0;
for (let i = 0;i < rad; i++) {
this._radPower[i] = alpha * ((rad * rad - i * i) * _NeuQuantFloat._radBias / (rad * rad));
}
let step;
if (pointsNumber < _NeuQuantFloat._minpicturebytes) {
step = 1;
} else if (pointsNumber % _NeuQuantFloat._prime1 !== 0) {
step = _NeuQuantFloat._prime1;
} else if (pointsNumber % _NeuQuantFloat._prime2 !== 0) {
step = _NeuQuantFloat._prime2;
} else if (pointsNumber % _NeuQuantFloat._prime3 !== 0) {
step = _NeuQuantFloat._prime3;
} else {
step = _NeuQuantFloat._prime4;
}
const tracker = new ProgressTracker(pointsToSample, 99);
for (let i = 0, pointIndex = 0;i < pointsToSample; ) {
if (tracker.shouldNotify(i)) {
yield {
progress: tracker.progress
};
}
const point = this._pointArray[pointIndex];
const b = point.b << networkBiasShift2;
const g = point.g << networkBiasShift2;
const r = point.r << networkBiasShift2;
const a = point.a << networkBiasShift2;
const neuronIndex = this._contest(b, g, r, a);
this._alterSingle(alpha, neuronIndex, b, g, r, a);
if (rad !== 0)
this._alterNeighbour(rad, neuronIndex, b, g, r, a);
pointIndex += step;
if (pointIndex >= pointsNumber)
pointIndex -= pointsNumber;
i++;
if (delta === 0)
delta = 1;
if (i % delta === 0) {
alpha -= alpha / alphadec;
radius -= radius / _NeuQuantFloat._radiusDecrease;
rad = radius >> _NeuQuantFloat._radiusBiasShift;
if (rad <= 1)
rad = 0;
for (let j = 0;j < rad; j++) {
this._radPower[j] = alpha * ((rad * rad - j * j) * _NeuQuantFloat._radBias / (rad * rad));
}
}
}
}
_buildPalette() {
const palette2 = new Palette;
this._network.forEach((neuron) => {
palette2.add(neuron.toPoint());
});
palette2.sort();
return palette2;
}
_alterNeighbour(rad, i, b, g, r, al) {
let lo = i - rad;
if (lo < -1)
lo = -1;
let hi = i + rad;
if (hi > this._networkSize)
hi = this._networkSize;
let j = i + 1;
let k = i - 1;
let m = 1;
while (j < hi || k > lo) {
const a = this._radPower[m++] / _NeuQuantFloat._alphaRadBias;
if (j < hi) {
const p = this._network[j++];
p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));
}
if (k > lo) {
const p = this._network[k--];
p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));
}
}
}
_alterSingle(alpha, i, b, g, r, a) {
alpha /= _NeuQuantFloat._initAlpha;
const n = this._network[i];
n.subtract(alpha * (n.r - r), alpha * (n.g - g), alpha * (n.b - b), alpha * (n.a - a));
}
_contest(b, g, r, al) {
const multiplier = 255 * 4 << networkBiasShift2;
let bestd = ~(1 << 31);
let bestbiasd = bestd;
let bestpos = -1;
let bestbiaspos = bestpos;
for (let i = 0;i < this._networkSize; i++) {
const n = this._network[i];
const dist = this._distance.calculateNormalized(n, { r, g, b, a: al }) * multiplier;
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
const biasdist = dist - (this._bias[i] >> _NeuQuantFloat._initialBiasShift - networkBiasShift2);
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
const betafreq = this._freq[i] >> _NeuQuantFloat._betaShift;
this._freq[i] -= betafreq;
this._bias[i] += betafreq << _NeuQuantFloat._gammaShift;
}
this._freq[bestpos] += _NeuQuantFloat._beta;
this._bias[bestpos] -= _NeuQuantFloat._betaGamma;
return bestbiaspos;
}
};
var NeuQuantFloat = _NeuQuantFloat;
__publicField(NeuQuantFloat, "_prime1", 499);
__publicField(NeuQuantFloat, "_prime2", 491);
__publicField(NeuQuantFloat, "_prime3", 487);
__publicField(NeuQuantFloat, "_prime4", 503);
__publicField(NeuQuantFloat, "_minpicturebytes", _NeuQuantFloat._prime4);
__publicField(NeuQuantFloat, "_nCycles", 100);
__publicField(NeuQuantFloat, "_initialBiasShift", 16);
__publicField(NeuQuantFloat, "_initialBias", 1 << _NeuQuantFloat._initialBiasShift);
__publicField(NeuQuantFloat, "_gammaShift", 10);
__publicField(NeuQuantFloat, "_betaShift", 10);
__publicField(NeuQuantFloat, "_beta", _NeuQuantFloat._initialBias >> _NeuQuantFloat._betaShift);
__publicField(NeuQuantFloat, "_betaGamma", _NeuQuantFloat._initialBias << _NeuQuantFloat._gammaShift - _NeuQuantFloat._betaShift);
__publicField(NeuQuantFloat, "_radiusBiasShift", 6);
__publicField(NeuQuantFloat, "_radiusBias", 1 << _NeuQuantFloat._radiusBiasShift);
__publicField(NeuQuantFloat, "_radiusDecrease", 30);
__publicField(NeuQuantFloat, "_alphaBiasShift", 10);
__publicField(NeuQuantFloat, "_initAlpha", 1 << _NeuQuantFloat._alphaBiasShift);
__publicField(NeuQuantFloat, "_radBiasShift", 8);
__publicField(NeuQuantFloat, "_radBias", 1 << _NeuQuantFloat._radBiasShift);
__publicField(NeuQuantFloat, "_alphaRadBiasShift", _NeuQuantFloat._alphaBiasShift + _NeuQuantFloat._radBiasShift);
__publicField(NeuQuantFloat, "_alphaRadBias", 1 << _NeuQuantFloat._alphaRadBiasShift);
var _ColorHistogram = class {
constructor(method, colors) {
__publicField(this, "_method");
__publicField(this, "_hueStats");
__publicField(this, "_histogram");
__publicField(this, "_initColors");
__publicField(this, "_minHueCols");
this._method = method;
this._minHueCols = colors << 2;
this._initColors = colors << 2;
this._hueStats = new HueStatistics(_ColorHistogram._hueGroups, this._minHueCols);
this._histogram = /* @__PURE__ */ Object.create(null);
}
sample(pointContainer) {
switch (this._method) {
case 1:
this._colorStats1D(pointContainer);
break;
case 2:
this._colorStats2D(pointContainer);
break;
}
}
getImportanceSortedColorsIDXI32() {
const sorted = stableSort(Object.keys(this._histogram), (a, b) => this._histogram[b] - this._histogram[a]);
if (sorted.length === 0) {
return [];
}
let idxi32;
switch (this._method) {
case 1:
const initialColorsLimit = Math.min(sorted.length, this._initColors);
const last = sorted[initialColorsLimit - 1];
const freq = this._histogram[last];
idxi32 = sorted.slice(0, initialColorsLimit);
let pos = initialColorsLimit;
const len = sorted.length;
while (pos < len && this._histogram[sorted[pos]] === freq) {
idxi32.push(sorted[pos++]);
}
this._hueStats.injectIntoArray(idxi32);
break;
case 2:
idxi32 = sorted;
break;
default:
throw new Error("Incorrect method");
}
return idxi32.map((v) => +v);
}
_colorStats1D(pointContainer) {
const histG = this._histogram;
const pointArray = pointContainer.getPointArray();
const len = pointArray.length;
for (let i = 0;i < len; i++) {
const col = pointArray[i].uint32;
this._hueStats.check(col);
if (col in histG) {
histG[col]++;
} else {
histG[col] = 1;
}
}
}
_colorStats2D(pointContainer) {
const width = pointContainer.getWidth();
const height = pointContainer.getHeight();
const pointArray = pointContainer.getPointArray();
const boxW = _ColorHistogram._boxSize[0];
const boxH = _ColorHistogram._boxSize[1];
const area = boxW * boxH;
const boxes = this._makeBoxes(width, height, boxW, boxH);
const histG = this._histogram;
boxes.forEach((box) => {
let effc = Math.round(box.w * box.h / area) * _ColorHistogram._boxPixels;
if (effc < 2)
effc = 2;
const histL = {};
this._iterateBox(box, width, (i) => {
const col = pointArray[i].uint32;
this._hueStats.check(col);
if (col in histG) {
histG[col]++;
} else if (col in histL) {
if (++histL[col] >= effc) {
histG[col] = histL[col];
}
} else {
histL[col] = 1;
}
});
});
this._hueStats.injectIntoDictionary(histG);
}
_iterateBox(bbox, wid, fn) {
const b = bbox;
const i0 = b.y * wid + b.x;
const i1 = (b.y + b.h - 1) * wid + (b.x + b.w - 1);
const incr = wid - b.w + 1;
let cnt = 0;
let i = i0;
do {
fn.call(this, i);
i += ++cnt % b.w === 0 ? incr : 1;
} while (i <= i1);
}
_makeBoxes(width, height, stepX, stepY) {
const wrem = width % stepX;
const hrem = height % stepY;
const xend = width - wrem;
const yend = height - hrem;
const boxesArray = [];
for (let y2 = 0;y2 < height; y2 += stepY) {
for (let x2 = 0;x2 < width; x2 += stepX) {
boxesArray.push({
x: x2,
y: y2,
w: x2 === xend ? wrem : stepX,
h: y2 === yend ? hrem : stepY
});
}
}
return boxesArray;
}
};
var ColorHistogram = _ColorHistogram;
__publicField(ColorHistogram, "_boxSize", [64, 64]);
__publicField(ColorHistogram, "_boxPixels", 2);
__publicField(ColorHistogram, "_hueGroups", 10);
var RemovedColor = class {
constructor(index, color, distance2) {
__publicField(this, "index");
__publicField(this, "color");
__publicField(this, "distance");
this.index = index;
this.color = color;
this.distance = distance2;
}
};
var RGBQuant = class extends AbstractPaletteQuantizer {
constructor(colorDistanceCalculator, colors = 256, method = 2) {
super();
__publicField(this, "_colors");
__publicField(this, "_initialDistance");
__publicField(this, "_distanceIncrement");
__publicField(this, "_histogram");
__publicField(this, "_distance");
this._distance = colorDistanceCalculator;
this._colors = colors;
this._histogram = new ColorHistogram(method, colors);
this._initialDistance = 0.01;
this._distanceIncrement = 0.005;
}
sample(image2) {
this._histogram.sample(image2);
}
*quantize() {
const idxi32 = this._histogram.getImportanceSortedColorsIDXI32();
if (idxi32.length === 0) {
throw new Error("No colors in image");
}
yield* this._buildPalette(idxi32);
}
*_buildPalette(idxi32) {
const palette2 = new Palette;
const colorArray = palette2.getPointContainer().getPointArray();
const usageArray = new Array(idxi32.length);
for (let i = 0;i < idxi32.length; i++) {
colorArray.push(Point.createByUint32(idxi32[i]));
usageArray[i] = 1;
}
const len = colorArray.length;
const memDist = [];
let palLen = len;
let thold = this._initialDistance;
const tracker = new ProgressTracker(palLen - this._colors, 99);
while (palLen > this._colors) {
memDist.length = 0;
for (let i = 0;i < len; i++) {
if (tracker.shouldNotify(len - palLen)) {
yield {
progress: tracker.progress
};
}
if (usageArray[i] === 0)
continue;
const pxi = colorArray[i];
for (let j = i + 1;j < len; j++) {
if (usageArray[j] === 0)
continue;
const pxj = colorArray[j];
const dist = this._distance.calculateNormalized(pxi, pxj);
if (dist < thold) {
memDist.push(new RemovedColor(j, pxj, dist));
usageArray[j] = 0;
palLen--;
}
}
}
thold += palLen > this._colors * 3 ? this._initialDistance : this._distanceIncrement;
}
if (palLen < this._colors) {
stableSort(memDist, (a, b) => b.distance - a.distance);
let k = 0;
while (palLen < this._colors && k < memDist.length) {
const removedColor = memDist[k];
usageArray[removedColor.index] = 1;
palLen++;
k++;
}
}
let colors = colorArray.length;
for (let colorIndex = colors - 1;colorIndex >= 0; colorIndex--) {
if (usageArray[colorIndex] === 0) {
if (colorIndex !== colors - 1) {
colorArray[colorIndex] = colorArray[colors - 1];
}
--colors;
}
}
colorArray.length = colors;
palette2.sort();
yield {
palette: palette2,
progress: 100
};
}
};
function createArray1D(dimension1) {
const a = [];
for (let k = 0;k < dimension1; k++) {
a[k] = 0;
}
return a;
}
function createArray4D(dimension1, dimension2, dimension3, dimension4) {
const a = new Array(dimension1);
for (let i = 0;i < dimension1; i++) {
a[i] = new Array(dimension2);
for (let j = 0;j < dimension2; j++) {
a[i][j] = new Array(dimension3);
for (let k = 0;k < dimension3; k++) {
a[i][j][k] = new Array(dimension4);
for (let l = 0;l < dimension4; l++) {
a[i][j][k][l] = 0;
}
}
}
}
return a;
}
function createArray3D(dimension1, dimension2, dimension3) {
const a = new Array(dimension1);
for (let i = 0;i < dimension1; i++) {
a[i] = new Array(dimension2);
for (let j = 0;j < dimension2; j++) {
a[i][j] = new Array(dimension3);
for (let k = 0;k < dimension3; k++) {
a[i][j][k] = 0;
}
}
}
return a;
}
function fillArray3D(a, dimension1, dimension2, dimension3, value) {
for (let i = 0;i < dimension1; i++) {
a[i] = [];
for (let j = 0;j < dimension2; j++) {
a[i][j] = [];
for (let k = 0;k < dimension3; k++) {
a[i][j][k] = value;
}
}
}
}
function fillArray1D(a, dimension1, value) {
for (let i = 0;i < dimension1; i++) {
a[i] = value;
}
}
var WuColorCube = class {
constructor() {
__publicField(this, "redMinimum");
__publicField(this, "redMaximum");
__publicField(this, "greenMinimum");
__publicField(this, "greenMaximum");
__publicField(this, "blueMinimum");
__publicField(this, "blueMaximum");
__publicField(this, "volume");
__publicField(this, "alphaMinimum");
__publicField(this, "alphaMaximum");
}
};
var _WuQuant = class extends AbstractPaletteQuantizer {
constructor(colorDistanceCalculator, colors = 256, significantBitsPerChannel = 5) {
super();
__publicField(this, "_reds");
__publicField(this, "_greens");
__publicField(this, "_blues");
__publicField(this, "_alphas");
__publicField(this, "_sums");
__publicField(this, "_weights");
__publicField(this, "_momentsRed");
__publicField(this, "_momentsGreen");
__publicField(this, "_momentsBlue");
__publicField(this, "_momentsAlpha");
__publicField(this, "_moments");
__publicField(this, "_table");
__publicField(this, "_pixels");
__publicField(this, "_cubes");
__publicField(this, "_colors");
__publicField(this, "_significantBitsPerChannel");
__publicField(this, "_maxSideIndex");
__publicField(this, "_alphaMaxSideIndex");
__publicField(this, "_sideSize");
__publicField(this, "_alphaSideSize");
__publicField(this, "_distance");
this._distance = colorDistanceCalculator;
this._setQuality(significantBitsPerChannel);
this._initialize(colors);
}
sample(image2) {
const pointArray = image2.getPointArray();
for (let i = 0, l = pointArray.length;i < l; i++) {
this._addColor(pointArray[i]);
}
this._pixels = this._pixels.concat(pointArray);
}
*quantize() {
yield* this._preparePalette();
const palette2 = new Palette;
for (let paletteIndex = 0;paletteIndex < this._colors; paletteIndex++) {
if (this._sums[paletteIndex] > 0) {
const sum = this._sums[paletteIndex];
const r = this._reds[paletteIndex] / sum;
const g = this._greens[paletteIndex] / sum;
const b = this._blues[paletteIndex] / sum;
const a = this._alphas[paletteIndex] / sum;
const color = Point.createByRGBA(r | 0, g | 0, b | 0, a | 0);
palette2.add(color);
}
}
palette2.sort();
yield {
palette: palette2,
progress: 100
};
}
*_preparePalette() {
yield* this._calculateMoments();
let next = 0;
const volumeVariance = createArray1D(this._colors);
for (let cubeIndex = 1;cubeIndex < this._colors; ++cubeIndex) {
if (this._cut(this._cubes[next], this._cubes[cubeIndex])) {
volumeVariance[next] = this._cubes[next].volume > 1 ? this._calculateVariance(this._cubes[next]) : 0;
volumeVariance[cubeIndex] = this._cubes[cubeIndex].volume > 1 ? this._calculateVariance(this._cubes[cubeIndex]) : 0;
} else {
volumeVariance[next] = 0;
cubeIndex--;
}
next = 0;
let temp = volumeVariance[0];
for (let index = 1;index <= cubeIndex; ++index) {
if (volumeVariance[index] > temp) {
temp = volumeVariance[index];
next = index;
}
}
if (temp <= 0) {
this._colors = cubeIndex + 1;
break;
}
}
const lookupRed = [];
const lookupGreen = [];
const lookupBlue = [];
const lookupAlpha = [];
for (let k = 0;k < this._colors; ++k) {
const weight = _WuQuant._volume(this._cubes[k], this._weights);
if (weight > 0) {
lookupRed[k] = _WuQuant._volume(this._cubes[k], this._momentsRed) / weight | 0;
lookupGreen[k] = _WuQuant._volume(this._cubes[k], this._momentsGreen) / weight | 0;
lookupBlue[k] = _WuQuant._volume(this._cubes[k], this._momentsBlue) / weight | 0;
lookupAlpha[k] = _WuQuant._volume(this._cubes[k], this._momentsAlpha) / weight | 0;
} else {
lookupRed[k] = 0;
lookupGreen[k] = 0;
lookupBlue[k] = 0;
lookupAlpha[k] = 0;
}
}
this._reds = createArray1D(this._colors + 1);
this._greens = createArray1D(this._colors + 1);
this._blues = createArray1D(this._colors + 1);
this._alphas = createArray1D(this._colors + 1);
this._sums = createArray1D(this._colors + 1);
for (let index = 0, l = this._pixels.length;index < l; index++) {
const color = this._pixels[index];
const match = -1;
let bestMatch = match;
let bestDistance = Number.MAX_VALUE;
for (let lookup = 0;lookup < this._colors; lookup++) {
const foundRed = lookupRed[lookup];
const foundGreen = lookupGreen[lookup];
const foundBlue = lookupBlue[lookup];
const foundAlpha = lookupAlpha[lookup];
const distance2 = this._distance.calculateRaw(foundRed, foundGreen, foundBlue, foundAlpha, color.r, color.g, color.b, color.a);
if (distance2 < bestDistance) {
bestDistance = distance2;
bestMatch = lookup;
}
}
this._reds[bestMatch] += color.r;
this._greens[bestMatch] += color.g;
this._blues[bestMatch] += color.b;
this._alphas[bestMatch] += color.a;
this._sums[bestMatch]++;
}
}
_addColor(color) {
const bitsToRemove = 8 - this._significantBitsPerChannel;
const indexRed = (color.r >> bitsToRemove) + 1;
const indexGreen = (color.g >> bitsToRemove) + 1;
const indexBlue = (color.b >> bitsToRemove) + 1;
const indexAlpha = (color.a >> bitsToRemove) + 1;
this._weights[indexAlpha][indexRed][indexGreen][indexBlue]++;
this._momentsRed[indexAlpha][indexRed][indexGreen][indexBlue] += color.r;
this._momentsGreen[indexAlpha][indexRed][indexGreen][indexBlue] += color.g;
this._momentsBlue[indexAlpha][indexRed][indexGreen][indexBlue] += color.b;
this._momentsAlpha[indexAlpha][indexRed][indexGreen][indexBlue] += color.a;
this._moments[indexAlpha][indexRed][indexGreen][indexBlue] += this._table[color.r] + this._table[color.g] + this._table[color.b] + this._table[color.a];
}
*_calculateMoments() {
const area = [];
const areaRed = [];
const areaGreen = [];
const areaBlue = [];
const areaAlpha = [];
const area2 = [];
const xarea = createArray3D(this._sideSize, this._sideSize, this._sideSize);
const xareaRed = createArray3D(this._sideSize, this._sideSize, this._sideSize);
const xareaGreen = createArray3D(this._sideSize, this._sideSize, this._sideSize);
const xareaBlue = createArray3D(this._sideSize, this._sideSize, this._sideSize);
const xareaAlpha = createArray3D(this._sideSize, this._sideSize, this._sideSize);
const xarea2 = createArray3D(this._sideSize, this._sideSize, this._sideSize);
let trackerProgress = 0;
const tracker = new ProgressTracker(this._alphaMaxSideIndex * this._maxSideIndex, 99);
for (let alphaIndex = 1;alphaIndex <= this._alphaMaxSideIndex; ++alphaIndex) {
fillArray3D(xarea, this._sideSize, this._sideSize, this._sideSize, 0);
fillArray3D(xareaRed, this._sideSize, this._sideSize, this._sideSize, 0);
fillArray3D(xareaGreen, this._sideSize, this._sideSize, this._sideSize, 0);
fillArray3D(xareaBlue, this._sideSize, this._sideSize, this._sideSize, 0);
fillArray3D(xareaAlpha, this._sideSize, this._sideSize, this._sideSize, 0);
fillArray3D(xarea2, this._sideSize, this._sideSize, this._sideSize, 0);
for (let redIndex = 1;redIndex <= this._maxSideIndex; ++redIndex, ++trackerProgress) {
if (tracker.shouldNotify(trackerProgress)) {
yield {
progress: tracker.progress
};
}
fillArray1D(area, this._sideSize, 0);
fillArray1D(areaRed, this._sideSize, 0);
fillArray1D(areaGreen, this._sideSize, 0);
fillArray1D(areaBlue, this._sideSize, 0);
fillArray1D(areaAlpha, this._sideSize, 0);
fillArray1D(area2, this._sideSize, 0);
for (let greenIndex = 1;greenIndex <= this._maxSideIndex; ++greenIndex) {
let line = 0;
let lineRed = 0;
let lineGreen = 0;
let lineBlue = 0;
let lineAlpha = 0;
let line2 = 0;
for (let blueIndex = 1;blueIndex <= this._maxSideIndex; ++blueIndex) {
line += this._weights[alphaIndex][redIndex][greenIndex][blueIndex];
lineRed += this._momentsRed[alphaIndex][redIndex][greenIndex][blueIndex];
lineGreen += this._momentsGreen[alphaIndex][redIndex][greenIndex][blueIndex];
lineBlue += this._momentsBlue[alphaIndex][redIndex][greenIndex][blueIndex];
lineAlpha += this._momentsAlpha[alphaIndex][redIndex][greenIndex][blueIndex];
line2 += this._moments[alphaIndex][redIndex][greenIndex][blueIndex];
area[blueIndex] += line;
areaRed[blueIndex] += lineRed;
areaGreen[blueIndex] += lineGreen;
areaBlue[blueIndex] += lineBlue;
areaAlpha[blueIndex] += lineAlpha;
area2[blueIndex] += line2;
xarea[redIndex][greenIndex][blueIndex] = xarea[redIndex - 1][greenIndex][blueIndex] + area[blueIndex];
xareaRed[redIndex][greenIndex][blueIndex] = xareaRed[redIndex - 1][greenIndex][blueIndex] + areaRed[blueIndex];
xareaGreen[redIndex][greenIndex][blueIndex] = xareaGreen[redIndex - 1][greenIndex][blueIndex] + areaGreen[blueIndex];
xareaBlue[redIndex][greenIndex][blueIndex] = xareaBlue[redIndex - 1][greenIndex][blueIndex] + areaBlue[blueIndex];
xareaAlpha[redIndex][greenIndex][blueIndex] = xareaAlpha[redIndex - 1][greenIndex][blueIndex] + areaAlpha[blueIndex];
xarea2[redIndex][greenIndex][blueIndex] = xarea2[redIndex - 1][greenIndex][blueIndex] + area2[blueIndex];
this._weights[alphaIndex][redIndex][greenIndex][blueIndex] = this._weights[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xarea[redIndex][greenIndex][blueIndex];
this._momentsRed[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsRed[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaRed[redIndex][greenIndex][blueIndex];
this._momentsGreen[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsGreen[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaGreen[redIndex][greenIndex][blueIndex];
this._momentsBlue[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsBlue[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaBlue[redIndex][greenIndex][blueIndex];
this._momentsAlpha[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsAlpha[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaAlpha[redIndex][greenIndex][blueIndex];
this._moments[alphaIndex][redIndex][greenIndex][blueIndex] = this._moments[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xarea2[redIndex][greenIndex][blueIndex];
}
}
}
}
}
static _volumeFloat(cube, moment) {
return moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
}
static _volume(cube, moment) {
return _WuQuant._volumeFloat(cube, moment) | 0;
}
static _top(cube, direction, position, moment) {
let result;
switch (direction) {
case _WuQuant._alpha:
result = moment[position][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] - moment[position][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] - moment[position][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] + moment[position][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (moment[position][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] - moment[position][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] - moment[position][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[position][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
break;
case _WuQuant._red:
result = moment[cube.alphaMaximum][position][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMaximum][position][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMinimum][position][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMinimum][position][cube.greenMinimum][cube.blueMaximum] - (moment[cube.alphaMaximum][position][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMaximum][position][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMinimum][position][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][position][cube.greenMinimum][cube.blueMinimum]);
break;
case _WuQuant._green:
result = moment[cube.alphaMaximum][cube.redMaximum][position][cube.blueMaximum] - moment[cube.alphaMaximum][cube.redMinimum][position][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMaximum][position][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][position][cube.blueMaximum] - (moment[cube.alphaMaximum][cube.redMaximum][position][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMinimum][position][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMaximum][position][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][position][cube.blueMinimum]);
break;
case _WuQuant._blue:
result = moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][position] - moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][position] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][position] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][position] - (moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][position] - moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][position] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][position] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][position]);
break;
default:
throw new Error("impossible");
}
return result | 0;
}
static _bottom(cube, direction, moment) {
switch (direction) {
case _WuQuant._alpha:
return -moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (-moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
case _WuQuant._red:
return -moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (-moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
case _WuQuant._green:
return -moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (-moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
case _WuQuant._blue:
return -moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] - (-moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);
default:
return 0;
}
}
_calculateVariance(cube) {
const volumeRed = _WuQuant._volume(cube, this._momentsRed);
const volumeGreen = _WuQuant._volume(cube, this._momentsGreen);
const volumeBlue = _WuQuant._volume(cube, this._momentsBlue);
const volumeAlpha = _WuQuant._volume(cube, this._momentsAlpha);
const volumeMoment = _WuQuant._volumeFloat(cube, this._moments);
const volumeWeight = _WuQuant._volume(cube, this._weights);
const distance2 = volumeRed * volumeRed + volumeGreen * volumeGreen + volumeBlue * volumeBlue + volumeAlpha * volumeAlpha;
return volumeMoment - distance2 / volumeWeight;
}
_maximize(cube, direction, first, last, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight) {
const bottomRed = _WuQuant._bottom(cube, direction, this._momentsRed) | 0;
const bottomGreen = _WuQuant._bottom(cube, direction, this._momentsGreen) | 0;
const bottomBlue = _WuQuant._bottom(cube, direction, this._momentsBlue) | 0;
const bottomAlpha = _WuQuant._bottom(cube, direction, this._momentsAlpha) | 0;
const bottomWeight = _WuQuant._bottom(cube, direction, this._weights) | 0;
let result = 0;
let cutPosition = -1;
for (let position = first;position < last; ++position) {
let halfRed = bottomRed + _WuQuant._top(cube, direction, position, this._momentsRed);
let halfGreen = bottomGreen + _WuQuant._top(cube, direction, position, this._momentsGreen);
let halfBlue = bottomBlue + _WuQuant._top(cube, direction, position, this._momentsBlue);
let halfAlpha = bottomAlpha + _WuQuant._top(cube, direction, position, this._momentsAlpha);
let halfWeight = bottomWeight + _WuQuant._top(cube, direction, position, this._weights);
if (halfWeight !== 0) {
let halfDistance = halfRed * halfRed + halfGreen * halfGreen + halfBlue * halfBlue + halfAlpha * halfAlpha;
let temp = halfDistance / halfWeight;
halfRed = wholeRed - halfRed;
halfGreen = wholeGreen - halfGreen;
halfBlue = wholeBlue - halfBlue;
halfAlpha = wholeAlpha - halfAlpha;
halfWeight = wholeWeight - halfWeight;
if (halfWeight !== 0) {
halfDistance = halfRed * halfRed + halfGreen * halfGreen + halfBlue * halfBlue + halfAlpha * halfAlpha;
temp += halfDistance / halfWeight;
if (temp > result) {
result = temp;
cutPosition = position;
}
}
}
}
return { max: result, position: cutPosition };
}
_cut(first, second) {
let direction;
const wholeRed = _WuQuant._volume(first, this._momentsRed);
const wholeGreen = _WuQuant._volume(first, this._momentsGreen);
const wholeBlue = _WuQuant._volume(first, this._momentsBlue);
const wholeAlpha = _WuQuant._volume(first, this._momentsAlpha);
const wholeWeight = _WuQuant._volume(first, this._weights);
const red = this._maximize(first, _WuQuant._red, first.redMinimum + 1, first.redMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);
const green = this._maximize(first, _WuQuant._green, first.greenMinimum + 1, first.greenMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);
const blue = this._maximize(first, _WuQuant._blue, first.blueMinimum + 1, first.blueMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);
const alpha = this._maximize(first, _WuQuant._alpha, first.alphaMinimum + 1, first.alphaMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);
if (alpha.max >= red.max && alpha.max >= green.max && alpha.max >= blue.max) {
direction = _WuQuant._alpha;
if (alpha.position < 0)
return false;
} else if (red.max >= alpha.max && red.max >= green.max && red.max >= blue.max) {
direction = _WuQuant._red;
} else if (green.max >= alpha.max && green.max >= red.max && green.max >= blue.max) {
direction = _WuQuant._green;
} else {
direction = _WuQuant._blue;
}
second.redMaximum = first.redMaximum;
second.greenMaximum = first.greenMaximum;
second.blueMaximum = first.blueMaximum;
second.alphaMaximum = first.alphaMaximum;
switch (direction) {
case _WuQuant._red:
second.redMinimum = first.redMaximum = red.position;
second.greenMinimum = first.greenMinimum;
second.blueMinimum = first.blueMinimum;
second.alphaMinimum = first.alphaMinimum;
break;
case _WuQuant._green:
second.greenMinimum = first.greenMaximum = green.position;
second.redMinimum = first.redMinimum;
second.blueMinimum = first.blueMinimum;
second.alphaMinimum = first.alphaMinimum;
break;
case _WuQuant._blue:
second.blueMinimum = first.blueMaximum = blue.position;
second.redMinimum = first.redMinimum;
second.greenMinimum = first.greenMinimum;
second.alphaMinimum = first.alphaMinimum;
break;
case _WuQuant._alpha:
second.alphaMinimum = first.alphaMaximum = alpha.position;
second.blueMinimum = first.blueMinimum;
second.redMinimum = first.redMinimum;
second.greenMinimum = first.greenMinimum;
break;
}
first.volume = (first.redMaximum - first.redMinimum) * (first.greenMaximum - first.greenMinimum) * (first.blueMaximum - first.blueMinimum) * (first.alphaMaximum - first.alphaMinimum);
second.volume = (second.redMaximum - second.redMinimum) * (second.greenMaximum - second.greenMinimum) * (second.blueMaximum - second.blueMinimum) * (second.alphaMaximum - second.alphaMinimum);
return true;
}
_initialize(colors) {
this._colors = colors;
this._cubes = [];
for (let cubeIndex = 0;cubeIndex < colors; cubeIndex++) {
this._cubes[cubeIndex] = new WuColorCube;
}
this._cubes[0].redMinimum = 0;
this._cubes[0].greenMinimum = 0;
this._cubes[0].blueMinimum = 0;
this._cubes[0].alphaMinimum = 0;
this._cubes[0].redMaximum = this._maxSideIndex;
this._cubes[0].greenMaximum = this._maxSideIndex;
this._cubes[0].blueMaximum = this._maxSideIndex;
this._cubes[0].alphaMaximum = this._alphaMaxSideIndex;
this._weights = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._momentsRed = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._momentsGreen = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._momentsBlue = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._momentsAlpha = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._moments = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);
this._table = [];
for (let tableIndex = 0;tableIndex < 256; ++tableIndex) {
this._table[tableIndex] = tableIndex * tableIndex;
}
this._pixels = [];
}
_setQuality(significantBitsPerChannel = 5) {
this._significantBitsPerChannel = significantBitsPerChannel;
this._maxSideIndex = 1 << this._significantBitsPerChannel;
this._alphaMaxSideIndex = this._maxSideIndex;
this._sideSize = this._maxSideIndex + 1;
this._alphaSideSize = this._alphaMaxSideIndex + 1;
}
};
var WuQuant = _WuQuant;
__publicField(WuQuant, "_alpha", 3);
__publicField(WuQuant, "_red", 2);
__publicField(WuQuant, "_green", 1);
__publicField(WuQuant, "_blue", 0);
var image_exports = {};
__export2(image_exports, {
AbstractImageQuantizer: () => AbstractImageQuantizer,
ErrorDiffusionArray: () => ErrorDiffusionArray,
ErrorDiffusionArrayKernel: () => ErrorDiffusionArrayKernel,
ErrorDiffusionRiemersma: () => ErrorDiffusionRiemersma,
NearestColor: () => NearestColor
});
var AbstractImageQuantizer = class {
quantizeSync(pointContainer, palette2) {
for (const value of this.quantize(pointContainer, palette2)) {
if (value.pointContainer) {
return value.pointContainer;
}
}
throw new Error("unreachable");
}
};
var NearestColor = class extends AbstractImageQuantizer {
constructor(colorDistanceCalculator) {
super();
__publicField(this, "_distance");
this._distance = colorDistanceCalculator;
}
*quantize(pointContainer, palette2) {
const pointArray = pointContainer.getPointArray();
const width = pointContainer.getWidth();
const height = pointContainer.getHeight();
const tracker = new ProgressTracker(height, 99);
for (let y2 = 0;y2 < height; y2++) {
if (tracker.shouldNotify(y2)) {
yield {
progress: tracker.progress
};
}
for (let x2 = 0, idx = y2 * width;x2 < width; x2++, idx++) {
const point = pointArray[idx];
point.from(palette2.getNearestColor(this._distance, point));
}
}
yield {
pointContainer,
progress: 100
};
}
};
var ErrorDiffusionArrayKernel = /* @__PURE__ */ ((ErrorDiffusionArrayKernel2) => {
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["FloydSteinberg"] = 0] = "FloydSteinberg";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["FalseFloydSteinberg"] = 1] = "FalseFloydSteinberg";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["Stucki"] = 2] = "Stucki";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["Atkinson"] = 3] = "Atkinson";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["Jarvis"] = 4] = "Jarvis";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["Burkes"] = 5] = "Burkes";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["Sierra"] = 6] = "Sierra";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["TwoSierra"] = 7] = "TwoSierra";
ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2["SierraLite"] = 8] = "SierraLite";
return ErrorDiffusionArrayKernel2;
})(ErrorDiffusionArrayKernel || {});
var ErrorDiffusionArray = class extends AbstractImageQuantizer {
constructor(colorDistanceCalculator, kernel, serpentine = true, minimumColorDistanceToDither = 0, calculateErrorLikeGIMP = false) {
super();
__publicField(this, "_minColorDistance");
__publicField(this, "_serpentine");
__publicField(this, "_kernel");
__publicField(this, "_calculateErrorLikeGIMP");
__publicField(this, "_distance");
this._setKernel(kernel);
this._distance = colorDistanceCalculator;
this._minColorDistance = minimumColorDistanceToDither;
this._serpentine = serpentine;
this._calculateErrorLikeGIMP = calculateErrorLikeGIMP;
}
*quantize(pointContainer, palette2) {
const pointArray = pointContainer.getPointArray();
const originalPoint = new Point;
const width = pointContainer.getWidth();
const height = pointContainer.getHeight();
const errorLines = [];
let dir = 1;
let maxErrorLines = 1;
for (const kernel of this._kernel) {
const kernelErrorLines = kernel[2] + 1;
if (maxErrorLines < kernelErrorLines)
maxErrorLines = kernelErrorLines;
}
for (let i = 0;i < maxErrorLines; i++) {
this._fillErrorLine(errorLines[i] = [], width);
}
const tracker = new ProgressTracker(height, 99);
for (let y2 = 0;y2 < height; y2++) {
if (tracker.shouldNotify(y2)) {
yield {
progress: tracker.progress
};
}
if (this._serpentine)
dir *= -1;
const lni = y2 * width;
const xStart = dir === 1 ? 0 : width - 1;
const xEnd = dir === 1 ? width : -1;
this._fillErrorLine(errorLines[0], width);
errorLines.push(errorLines.shift());
const errorLine = errorLines[0];
for (let x2 = xStart, idx = lni + xStart;x2 !== xEnd; x2 += dir, idx += dir) {
const point = pointArray[idx];
const error = errorLine[x2];
originalPoint.from(point);
const correctedPoint = Point.createByRGBA(inRange0to255Rounded(point.r + error[0]), inRange0to255Rounded(point.g + error[1]), inRange0to255Rounded(point.b + error[2]), inRange0to255Rounded(point.a + error[3]));
const palettePoint = palette2.getNearestColor(this._distance, correctedPoint);
point.from(palettePoint);
if (this._minColorDistance) {
const dist = this._distance.calculateNormalized(originalPoint, palettePoint);
if (dist < this._minColorDistance)
continue;
}
let er;
let eg;
let eb;
let ea;
if (this._calculateErrorLikeGIMP) {
er = correctedPoint.r - palettePoint.r;
eg = correctedPoint.g - palettePoint.g;
eb = correctedPoint.b - palettePoint.b;
ea = correctedPoint.a - palettePoint.a;
} else {
er = originalPoint.r - palettePoint.r;
eg = originalPoint.g - palettePoint.g;
eb = originalPoint.b - palettePoint.b;
ea = originalPoint.a - palettePoint.a;
}
const dStart = dir === 1 ? 0 : this._kernel.length - 1;
const dEnd = dir === 1 ? this._kernel.length : -1;
for (let i = dStart;i !== dEnd; i += dir) {
const x1 = this._kernel[i][1] * dir;
const y1 = this._kernel[i][2];
if (x1 + x2 >= 0 && x1 + x2 < width && y1 + y2 >= 0 && y1 + y2 < height) {
const d = this._kernel[i][0];
const e = errorLines[y1][x1 + x2];
e[0] += er * d;
e[1] += eg * d;
e[2] += eb * d;
e[3] += ea * d;
}
}
}
}
yield {
pointContainer,
progress: 100
};
}
_fillErrorLine(errorLine, width) {
if (errorLine.length > width) {
errorLine.length = width;
}
const l = errorLine.length;
for (let i = 0;i < l; i++) {
const error = errorLine[i];
error[0] = error[1] = error[2] = error[3] = 0;
}
for (let i = l;i < width; i++) {
errorLine[i] = [0, 0, 0, 0];
}
}
_setKernel(kernel) {
switch (kernel) {
case 0:
this._kernel = [
[7 / 16, 1, 0],
[3 / 16, -1, 1],
[5 / 16, 0, 1],
[1 / 16, 1, 1]
];
break;
case 1:
this._kernel = [
[3 / 8, 1, 0],
[3 / 8, 0, 1],
[2 / 8, 1, 1]
];
break;
case 2:
this._kernel = [
[8 / 42, 1, 0],
[4 / 42, 2, 0],
[2 / 42, -2, 1],
[4 / 42, -1, 1],
[8 / 42, 0, 1],
[4 / 42, 1, 1],
[2 / 42, 2, 1],
[1 / 42, -2, 2],
[2 / 42, -1, 2],
[4 / 42, 0, 2],
[2 / 42, 1, 2],
[1 / 42, 2, 2]
];
break;
case 3:
this._kernel = [
[1 / 8, 1, 0],
[1 / 8, 2, 0],
[1 / 8, -1, 1],
[1 / 8, 0, 1],
[1 / 8, 1, 1],
[1 / 8, 0, 2]
];
break;
case 4:
this._kernel = [
[7 / 48, 1, 0],
[5 / 48, 2, 0],
[3 / 48, -2, 1],
[5 / 48, -1, 1],
[7 / 48, 0, 1],
[5 / 48, 1, 1],
[3 / 48, 2, 1],
[1 / 48, -2, 2],
[3 / 48, -1, 2],
[5 / 48, 0, 2],
[3 / 48, 1, 2],
[1 / 48, 2, 2]
];
break;
case 5:
this._kernel = [
[8 / 32, 1, 0],
[4 / 32, 2, 0],
[2 / 32, -2, 1],
[4 / 32, -1, 1],
[8 / 32, 0, 1],
[4 / 32, 1, 1],
[2 / 32, 2, 1]
];
break;
case 6:
this._kernel = [
[5 / 32, 1, 0],
[3 / 32, 2, 0],
[2 / 32, -2, 1],
[4 / 32, -1, 1],
[5 / 32, 0, 1],
[4 / 32, 1, 1],
[2 / 32, 2, 1],
[2 / 32, -1, 2],
[3 / 32, 0, 2],
[2 / 32, 1, 2]
];
break;
case 7:
this._kernel = [
[4 / 16, 1, 0],
[3 / 16, 2, 0],
[1 / 16, -2, 1],
[2 / 16, -1, 1],
[3 / 16, 0, 1],
[2 / 16, 1, 1],
[1 / 16, 2, 1]
];
break;
case 8:
this._kernel = [
[2 / 4, 1, 0],
[1 / 4, -1, 1],
[1 / 4, 0, 1]
];
break;
default:
throw new Error(`ErrorDiffusionArray: unknown kernel = ${kernel}`);
}
}
};
function* hilbertCurve(width, height, callback) {
const maxBound = Math.max(width, height);
const level = Math.floor(Math.log(maxBound) / Math.log(2) + 1);
const tracker = new ProgressTracker(width * height, 99);
const data = {
width,
height,
level,
callback,
tracker,
index: 0,
x: 0,
y: 0
};
yield* walkHilbert(data, 1);
visit(data, 0);
}
function* walkHilbert(data, direction) {
if (data.level < 1)
return;
if (data.tracker.shouldNotify(data.index)) {
yield { progress: data.tracker.progress };
}
data.level--;
switch (direction) {
case 2:
yield* walkHilbert(data, 1);
visit(data, 3);
yield* walkHilbert(data, 2);
visit(data, 4);
yield* walkHilbert(data, 2);
visit(data, 2);
yield* walkHilbert(data, 4);
break;
case 3:
yield* walkHilbert(data, 4);
visit(data, 2);
yield* walkHilbert(data, 3);
visit(data, 1);
yield* walkHilbert(data, 3);
visit(data, 3);
yield* walkHilbert(data, 1);
break;
case 1:
yield* walkHilbert(data, 2);
visit(data, 4);
yield* walkHilbert(data, 1);
visit(data, 3);
yield* walkHilbert(data, 1);
visit(data, 1);
yield* walkHilbert(data, 3);
break;
case 4:
yield* walkHilbert(data, 3);
visit(data, 1);
yield* walkHilbert(data, 4);
visit(data, 2);
yield* walkHilbert(data, 4);
visit(data, 4);
yield* walkHilbert(data, 2);
break;
default:
break;
}
data.level++;
}
function visit(data, direction) {
if (data.x >= 0 && data.x < data.width && data.y >= 0 && data.y < data.height) {
data.callback(data.x, data.y);
data.index++;
}
switch (direction) {
case 2:
data.x--;
break;
case 3:
data.x++;
break;
case 1:
data.y--;
break;
case 4:
data.y++;
break;
}
}
var ErrorDiffusionRiemersma = class extends AbstractImageQuantizer {
constructor(colorDistanceCalculator, errorQueueSize = 16, errorPropagation = 1) {
super();
__publicField(this, "_distance");
__publicField(this, "_weights");
__publicField(this, "_errorQueueSize");
this._distance = colorDistanceCalculator;
this._errorQueueSize = errorQueueSize;
this._weights = ErrorDiffusionRiemersma._createWeights(errorPropagation, errorQueueSize);
}
*quantize(pointContainer, palette2) {
const pointArray = pointContainer.getPointArray();
const width = pointContainer.getWidth();
const height = pointContainer.getHeight();
const errorQueue = [];
let head = 0;
for (let i = 0;i < this._errorQueueSize; i++) {
errorQueue[i] = { r: 0, g: 0, b: 0, a: 0 };
}
yield* hilbertCurve(width, height, (x2, y2) => {
const p = pointArray[x2 + y2 * width];
let { r, g, b, a } = p;
for (let i = 0;i < this._errorQueueSize; i++) {
const weight = this._weights[i];
const e = errorQueue[(i + head) % this._errorQueueSize];
r += e.r * weight;
g += e.g * weight;
b += e.b * weight;
a += e.a * weight;
}
const correctedPoint = Point.createByRGBA(inRange0to255Rounded(r), inRange0to255Rounded(g), inRange0to255Rounded(b), inRange0to255Rounded(a));
const quantizedPoint = palette2.getNearestColor(this._distance, correctedPoint);
head = (head + 1) % this._errorQueueSize;
const tail = (head + this._errorQueueSize - 1) % this._errorQueueSize;
errorQueue[tail].r = p.r - quantizedPoint.r;
errorQueue[tail].g = p.g - quantizedPoint.g;
errorQueue[tail].b = p.b - quantizedPoint.b;
errorQueue[tail].a = p.a - quantizedPoint.a;
p.from(quantizedPoint);
});
yield {
pointContainer,
progress: 100
};
}
static _createWeights(errorPropagation, errorQueueSize) {
const weights = [];
const multiplier = Math.exp(Math.log(errorQueueSize) / (errorQueueSize - 1));
for (let i = 0, next = 1;i < errorQueueSize; i++) {
weights[i] = (next + 0.5 | 0) / errorQueueSize * errorPropagation;
next *= multiplier;
}
return weights;
}
};
var quality_exports = {};
__export2(quality_exports, {
ssim: () => ssim
});
var K1 = 0.01;
var K2 = 0.03;
function ssim(image1, image2) {
if (image1.getHeight() !== image2.getHeight() || image1.getWidth() !== image2.getWidth()) {
throw new Error("Images have different sizes!");
}
const bitsPerComponent = 8;
const L = (1 << bitsPerComponent) - 1;
const c1 = (K1 * L) ** 2;
const c2 = (K2 * L) ** 2;
let numWindows = 0;
let mssim = 0;
iterate(image1, image2, (lumaValues1, lumaValues2, averageLumaValue1, averageLumaValue2) => {
let sigxy = 0;
let sigsqx = 0;
let sigsqy = 0;
for (let i = 0;i < lumaValues1.length; i++) {
sigsqx += (lumaValues1[i] - averageLumaValue1) ** 2;
sigsqy += (lumaValues2[i] - averageLumaValue2) ** 2;
sigxy += (lumaValues1[i] - averageLumaValue1) * (lumaValues2[i] - averageLumaValue2);
}
const numPixelsInWin = lumaValues1.length - 1;
sigsqx /= numPixelsInWin;
sigsqy /= numPixelsInWin;
sigxy /= numPixelsInWin;
const numerator = (2 * averageLumaValue1 * averageLumaValue2 + c1) * (2 * sigxy + c2);
const denominator = (averageLumaValue1 ** 2 + averageLumaValue2 ** 2 + c1) * (sigsqx + sigsqy + c2);
const ssim2 = numerator / denominator;
mssim += ssim2;
numWindows++;
});
return mssim / numWindows;
}
function iterate(image1, image2, callback) {
const windowSize = 8;
const width = image1.getWidth();
const height = image1.getHeight();
for (let y2 = 0;y2 < height; y2 += windowSize) {
for (let x2 = 0;x2 < width; x2 += windowSize) {
const windowWidth = Math.min(windowSize, width - x2);
const windowHeight = Math.min(windowSize, height - y2);
const lumaValues1 = calculateLumaValuesForWindow(image1, x2, y2, windowWidth, windowHeight);
const lumaValues2 = calculateLumaValuesForWindow(image2, x2, y2, windowWidth, windowHeight);
const averageLuma1 = calculateAverageLuma(lumaValues1);
const averageLuma2 = calculateAverageLuma(lumaValues2);
callback(lumaValues1, lumaValues2, averageLuma1, averageLuma2);
}
}
}
function calculateLumaValuesForWindow(image2, x2, y2, width, height) {
const pointArray = image2.getPointArray();
const lumaValues = [];
let counter = 0;
for (let j = y2;j < y2 + height; j++) {
const offset = j * image2.getWidth();
for (let i = x2;i < x2 + width; i++) {
const point = pointArray[offset + i];
lumaValues[counter] = point.r * 0.2126 + point.g * 0.7152 + point.b * 0.0722;
counter++;
}
}
return lumaValues;
}
function calculateAverageLuma(lumaValues) {
let sumLuma = 0;
for (const luma of lumaValues) {
sumLuma += luma;
}
return sumLuma / lumaValues.length;
}
var setImmediateImpl = typeof setImmediate === "function" ? setImmediate : typeof process !== "undefined" && typeof (process == null ? undefined : process.nextTick) === "function" ? (callback) => process.nextTick(callback) : (callback) => setTimeout(callback, 0);
function buildPaletteSync(images, {
colorDistanceFormula,
paletteQuantization,
colors
} = {}) {
const distanceCalculator = colorDistanceFormulaToColorDistance(colorDistanceFormula);
const paletteQuantizer = paletteQuantizationToPaletteQuantizer(distanceCalculator, paletteQuantization, colors);
images.forEach((image2) => paletteQuantizer.sample(image2));
return paletteQuantizer.quantizeSync();
}
function applyPaletteSync(image2, palette2, { colorDistanceFormula, imageQuantization } = {}) {
const distanceCalculator = colorDistanceFormulaToColorDistance(colorDistanceFormula);
const imageQuantizer = imageQuantizationToImageQuantizer(distanceCalculator, imageQuantization);
return imageQuantizer.quantizeSync(image2, palette2);
}
function colorDistanceFormulaToColorDistance(colorDistanceFormula = "euclidean-bt709") {
switch (colorDistanceFormula) {
case "cie94-graphic-arts":
return new CIE94GraphicArts;
case "cie94-textiles":
return new CIE94Textiles;
case "ciede2000":
return new CIEDE2000;
case "color-metric":
return new CMetric;
case "euclidean":
return new Euclidean;
case "euclidean-bt709":
return new EuclideanBT709;
case "euclidean-bt709-noalpha":
return new EuclideanBT709NoAlpha;
case "manhattan":
return new Manhattan;
case "manhattan-bt709":
return new ManhattanBT709;
case "manhattan-nommyde":
return new ManhattanNommyde;
case "pngquant":
return new PNGQuant;
default:
throw new Error(`Unknown colorDistanceFormula ${colorDistanceFormula}`);
}
}
function imageQuantizationToImageQuantizer(distanceCalculator, imageQuantization = "floyd-steinberg") {
switch (imageQuantization) {
case "nearest":
return new NearestColor(distanceCalculator);
case "riemersma":
return new ErrorDiffusionRiemersma(distanceCalculator);
case "floyd-steinberg":
return new ErrorDiffusionArray(distanceCalculator, 0);
case "false-floyd-steinberg":
return new ErrorDiffusionArray(distanceCalculator, 1);
case "stucki":
return new ErrorDiffusionArray(distanceCalculator, 2);
case "atkinson":
return new ErrorDiffusionArray(distanceCalculator, 3);
case "jarvis":
return new ErrorDiffusionArray(distanceCalculator, 4);
case "burkes":
return new ErrorDiffusionArray(distanceCalculator, 5);
case "sierra":
return new ErrorDiffusionArray(distanceCalculator, 6);
case "two-sierra":
return new ErrorDiffusionArray(distanceCalculator, 7);
case "sierra-lite":
return new ErrorDiffusionArray(distanceCalculator, 8);
default:
throw new Error(`Unknown imageQuantization ${imageQuantization}`);
}
}
function paletteQuantizationToPaletteQuantizer(distanceCalculator, paletteQuantization = "wuquant", colors = 256) {
switch (paletteQuantization) {
case "neuquant":
return new NeuQuant(distanceCalculator, colors);
case "rgbquant":
return new RGBQuant(distanceCalculator, colors);
case "wuquant":
return new WuQuant(distanceCalculator, colors);
case "neuquant-float":
return new NeuQuantFloat(distanceCalculator, colors);
default:
throw new Error(`Unknown paletteQuantization ${paletteQuantization}`);
}
}
// ../../node_modules/.bun/@jimp+plugin-quantize@1.6.0/node_modules/@jimp/plugin-quantize/dist/esm/index.js
var QuantizeOptionsSchema = zod_default.object({
colors: zod_default.number().optional(),
colorDistanceFormula: zod_default.union([
zod_default.literal("cie94-textiles"),
zod_default.literal("cie94-graphic-arts"),
zod_default.literal("ciede2000"),
zod_default.literal("color-metric"),
zod_default.literal("euclidean"),
zod_default.literal("euclidean-bt709-noalpha"),
zod_default.literal("euclidean-bt709"),
zod_default.literal("manhattan"),
zod_default.literal("manhattan-bt709"),
zod_default.literal("manhattan-nommyde"),
zod_default.literal("pngquant")
]).optional(),
paletteQuantization: zod_default.union([
zod_default.literal("neuquant"),
zod_default.literal("neuquant-float"),
zod_default.literal("rgbquant"),
zod_default.literal("wuquant")
]).optional(),
imageQuantization: zod_default.union([
zod_default.literal("nearest"),
zod_default.literal("riemersma"),
zod_default.literal("floyd-steinberg"),
zod_default.literal("false-floyd-steinberg"),
zod_default.literal("stucki"),
zod_default.literal("atkinson"),
zod_default.literal("jarvis"),
zod_default.literal("burkes"),
zod_default.literal("sierra"),
zod_default.literal("two-sierra"),
zod_default.literal("sierra-lite")
]).optional()
});
var methods18 = {
quantize(image2, options) {
const { colors, colorDistanceFormula, paletteQuantization, imageQuantization } = QuantizeOptionsSchema.parse(options);
const inPointContainer = utils_exports.PointContainer.fromUint8Array(image2.bitmap.data, image2.bitmap.width, image2.bitmap.height);
const palette2 = buildPaletteSync([inPointContainer], {
colors,
colorDistanceFormula,
paletteQuantization
});
const outPointContainer = applyPaletteSync(inPointContainer, palette2, {
colorDistanceFormula,
imageQuantization
});
image2.bitmap.data = Buffer.from(outPointContainer.toUint8Array());
return image2;
}
};
// ../../node_modules/.bun/jimp@1.6.0/node_modules/jimp/dist/esm/index.js
var defaultPlugins = [
methods,
methods2,
methods3,
methods4,
methods6,
methods8,
methods7,
methods9,
methods10,
methods11,
methods12,
methods13,
methods14,
methods15,
methods5,
methods16,
methods17,
methods18
];
var defaultFormats = [bmp, msBmp, gif, jpeg, png, tiff];
var JimpMime = {
bmp: bmp().mime,
gif: gif().mime,
jpeg: jpeg().mime,
png: png().mime,
tiff: tiff().mime
};
var Jimp = createJimp({
formats: defaultFormats,
plugins: defaultPlugins
});
// src/3d/shaders/supersampling.wgsl
var supersampling_default = `struct CellResult {
bg: vec4<f32>, // Background RGBA (16 bytes)
fg: vec4<f32>, // Foreground RGBA (16 bytes)
char: u32, // Unicode character code (4 bytes)
_padding1: u32, // Padding (4 bytes)
_padding2: u32, // Extra padding (4 bytes)
_padding3: u32, // Extra padding (4 bytes) - total now 48 bytes (16-byte aligned)
};
struct CellBuffer {
cells: array<CellResult>
};
struct SuperSamplingParams {
width: u32, // Canvas width in pixels
height: u32, // Canvas height in pixels
sampleAlgo: u32, // 0 = standard 2x2, 1 = pre-squeezed horizontal blend
_padding: u32, // Padding for 16-byte alignment
};
@group(0) @binding(0) var inputTexture: texture_2d<f32>;
@group(0) @binding(1) var<storage, read_write> output: CellBuffer;
@group(0) @binding(2) var<uniform> params: SuperSamplingParams;
// Quadrant character lookup table (same as Zig implementation)
const quadrantChars = array<u32, 16>(
32u, // ' ' - 0000
0x2597u, // \u2597 - 0001 BR
0x2596u, // \u2596 - 0010 BL
0x2584u, // \u2584 - 0011 Lower Half Block
0x259Du, // \u259D - 0100 TR
0x2590u, // \u2590 - 0101 Right Half Block
0x259Eu, // \u259E - 0110 TR+BL
0x259Fu, // \u259F - 0111 TR+BL+BR
0x2598u, // \u2598 - 1000 TL
0x259Au, // \u259A - 1001 TL+BR
0x258Cu, // \u258C - 1010 Left Half Block
0x2599u, // \u2599 - 1011 TL+BL+BR
0x2580u, // \u2580 - 1100 Upper Half Block
0x259Cu, // \u259C - 1101 TL+TR+BR
0x259Bu, // \u259B - 1110 TL+TR+BL
0x2588u // \u2588 - 1111 Full Block
);
const inv_255: f32 = 1.0 / 255.0;
fn getPixelColor(pixelX: u32, pixelY: u32) -> vec4<f32> {
if (pixelX >= params.width || pixelY >= params.height) {
return vec4<f32>(0.0, 0.0, 0.0, 1.0); // Black for out-of-bounds
}
// textureLoad automatically handles format conversion to RGBA
return textureLoad(inputTexture, vec2<i32>(i32(pixelX), i32(pixelY)), 0);
}
fn colorDistance(a: vec4<f32>, b: vec4<f32>) -> f32 {
let diff = a.rgb - b.rgb;
return dot(diff, diff);
}
fn luminance(color: vec4<f32>) -> f32 {
return 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;
}
fn closestColorIndex(pixel: vec4<f32>, candA: vec4<f32>, candB: vec4<f32>) -> u32 {
return select(1u, 0u, colorDistance(pixel, candA) <= colorDistance(pixel, candB));
}
fn averageColor(pixels: array<vec4<f32>, 4>) -> vec4<f32> {
return (pixels[0] + pixels[1] + pixels[2] + pixels[3]) * 0.25;
}
fn blendColors(color1: vec4<f32>, color2: vec4<f32>) -> vec4<f32> {
let a1 = color1.a;
let a2 = color2.a;
if (a1 == 0.0 && a2 == 0.0) {
return vec4<f32>(0.0, 0.0, 0.0, 0.0);
}
let outAlpha = a1 + a2 - a1 * a2;
if (outAlpha == 0.0) {
return vec4<f32>(0.0, 0.0, 0.0, 0.0);
}
let rgb = (color1.rgb * a1 + color2.rgb * a2 * (1.0 - a1)) / outAlpha;
return vec4<f32>(rgb, outAlpha);
}
fn averageColorsWithAlpha(pixels: array<vec4<f32>, 4>) -> vec4<f32> {
let blend1 = blendColors(pixels[0], pixels[1]);
let blend2 = blendColors(pixels[2], pixels[3]);
return blendColors(blend1, blend2);
}
fn renderQuadrantBlock(pixels: array<vec4<f32>, 4>) -> CellResult {
var maxDist: f32 = colorDistance(pixels[0], pixels[1]);
var pIdxA: u32 = 0u;
var pIdxB: u32 = 1u;
for (var i: u32 = 0u; i < 4u; i++) {
for (var j: u32 = i + 1u; j < 4u; j++) {
let dist = colorDistance(pixels[i], pixels[j]);
if (dist > maxDist) {
pIdxA = i;
pIdxB = j;
maxDist = dist;
}
}
}
let pCandA = pixels[pIdxA];
let pCandB = pixels[pIdxB];
var chosenDarkColor: vec4<f32>;
var chosenLightColor: vec4<f32>;
if (luminance(pCandA) <= luminance(pCandB)) {
chosenDarkColor = pCandA;
chosenLightColor = pCandB;
} else {
chosenDarkColor = pCandB;
chosenLightColor = pCandA;
}
var quadrantBits: u32 = 0u;
let bitValues = array<u32, 4>(8u, 4u, 2u, 1u); // TL, TR, BL, BR
for (var i: u32 = 0u; i < 4u; i++) {
if (closestColorIndex(pixels[i], chosenDarkColor, chosenLightColor) == 0u) {
quadrantBits |= bitValues[i];
}
}
// Construct result
var result: CellResult;
if (quadrantBits == 0u) { // All light
result.char = 32u; // Space character
result.fg = chosenDarkColor;
result.bg = averageColorsWithAlpha(pixels);
} else if (quadrantBits == 15u) { // All dark
result.char = quadrantChars[15]; // Full block
result.fg = averageColorsWithAlpha(pixels);
result.bg = chosenLightColor;
} else { // Mixed pattern
result.char = quadrantChars[quadrantBits];
result.fg = chosenDarkColor;
result.bg = chosenLightColor;
}
result._padding1 = 0u;
result._padding2 = 0u;
result._padding3 = 0u;
return result;
}
@compute @workgroup_size(\${WORKGROUP_SIZE}, \${WORKGROUP_SIZE}, 1)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let cellX = id.x;
let cellY = id.y;
let bufferWidthCells = (params.width + 1u) / 2u;
let bufferHeightCells = (params.height + 1u) / 2u;
if (cellX >= bufferWidthCells || cellY >= bufferHeightCells) {
return;
}
let renderX = cellX * 2u;
let renderY = cellY * 2u;
var pixelsRgba: array<vec4<f32>, 4>;
if (params.sampleAlgo == 1u) {
let topColor = getPixelColor(renderX, renderY);
let topColor2 = getPixelColor(renderX + 1u, renderY);
let blendedTop = blendColors(topColor, topColor2);
let bottomColor = getPixelColor(renderX, renderY + 1u);
let bottomColor2 = getPixelColor(renderX + 1u, renderY + 1u);
let blendedBottom = blendColors(bottomColor, bottomColor2);
pixelsRgba[0] = blendedTop; // TL
pixelsRgba[1] = blendedTop; // TR
pixelsRgba[2] = blendedBottom; // BL
pixelsRgba[3] = blendedBottom; // BR
} else {
pixelsRgba[0] = getPixelColor(renderX, renderY); // TL
pixelsRgba[1] = getPixelColor(renderX + 1u, renderY); // TR
pixelsRgba[2] = getPixelColor(renderX, renderY + 1u); // BL
pixelsRgba[3] = getPixelColor(renderX + 1u, renderY + 1u); // BR
}
let cellResult = renderQuadrantBlock(pixelsRgba);
let outputIndex = cellY * bufferWidthCells + cellX;
output.cells[outputIndex] = cellResult;
}`;
// src/3d/canvas.ts
var WORKGROUP_SIZE = 4;
var SUPERSAMPLING_COMPUTE_SHADER = supersampling_default.replace(/\${WORKGROUP_SIZE}/g, WORKGROUP_SIZE.toString());
var SuperSampleAlgorithm;
((SuperSampleAlgorithm2) => {
SuperSampleAlgorithm2[SuperSampleAlgorithm2["STANDARD"] = 0] = "STANDARD";
SuperSampleAlgorithm2[SuperSampleAlgorithm2["PRE_SQUEEZED"] = 1] = "PRE_SQUEEZED";
})(SuperSampleAlgorithm ||= {});
class CLICanvas {
device;
readbackBuffer = null;
width;
height;
gpuCanvasContext;
superSampleDrawTimeMs = 0;
mapAsyncTimeMs = 0;
superSample = "gpu" /* GPU */;
computePipeline = null;
computeBindGroupLayout = null;
computeOutputBuffer = null;
computeParamsBuffer = null;
computeReadbackBuffer = null;
updateScheduled = false;
screenshotGPUBuffer = null;
superSampleAlgorithm = 0 /* STANDARD */;
destroyed = false;
constructor(device, width, height, superSample, sampleAlgo = 0 /* STANDARD */) {
this.device = device;
this.width = width;
this.height = height;
this.superSample = superSample;
this.gpuCanvasContext = new GPUCanvasContextMock(this, width, height);
this.superSampleAlgorithm = sampleAlgo;
}
destroy() {
this.destroyed = true;
}
setSuperSampleAlgorithm(superSampleAlgorithm) {
this.superSampleAlgorithm = superSampleAlgorithm;
this.scheduleUpdateComputeBuffers();
}
getSuperSampleAlgorithm() {
return this.superSampleAlgorithm;
}
getContext(type, attrs) {
if (type === "webgpu") {
this.updateReadbackBuffer(this.width, this.height);
this.updateComputeBuffers(this.width, this.height);
return this.gpuCanvasContext;
}
throw new Error(`getContext not implemented: ${type}`);
}
setSize(width, height) {
this.width = width;
this.height = height;
this.gpuCanvasContext.setSize(width, height);
this.updateReadbackBuffer(width, height);
this.scheduleUpdateComputeBuffers();
}
addEventListener(event, listener, options) {
console.error("addEventListener mockCanvas", event, listener, options);
}
removeEventListener(event, listener, options) {
console.error("removeEventListener mockCanvas", event, listener, options);
}
dispatchEvent(event) {
console.error("dispatchEvent mockCanvas", event);
}
setSuperSample(superSample) {
this.superSample = superSample;
}
async saveToFile(filePath) {
const bytesPerPixel = 4;
const unalignedBytesPerRow = this.width * bytesPerPixel;
const alignedBytesPerRow = Math.ceil(unalignedBytesPerRow / 256) * 256;
const textureBufferSize = alignedBytesPerRow * this.height;
if (!this.screenshotGPUBuffer || this.screenshotGPUBuffer.size !== textureBufferSize) {
if (this.screenshotGPUBuffer) {
this.screenshotGPUBuffer.destroy();
}
this.screenshotGPUBuffer = this.device.createBuffer({
label: "Screenshot GPU Buffer",
size: textureBufferSize,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST
});
}
const texture = this.gpuCanvasContext.getCurrentTexture();
const commandEncoder = this.device.createCommandEncoder({ label: "Screenshot Command Encoder" });
commandEncoder.copyTextureToBuffer({ texture }, { buffer: this.screenshotGPUBuffer, bytesPerRow: alignedBytesPerRow, rowsPerImage: this.height }, { width: this.width, height: this.height });
const commandBuffer = commandEncoder.finish();
this.device.queue.submit([commandBuffer]);
await this.screenshotGPUBuffer.mapAsync(GPUMapMode.READ);
const resultBuffer = this.screenshotGPUBuffer.getMappedRange();
const pixelData = new Uint8Array(resultBuffer);
const contextFormat = texture.format;
const isBGRA = contextFormat === "bgra8unorm";
const imageData = new Uint8Array(this.width * this.height * 4);
for (let y2 = 0;y2 < this.height; y2++) {
const srcOffset = y2 * alignedBytesPerRow;
const dstOffset = y2 * this.width * 4;
if (isBGRA) {
for (let x2 = 0;x2 < this.width; x2++) {
const srcPixelOffset = srcOffset + x2 * 4;
const dstPixelOffset = dstOffset + x2 * 4;
imageData[dstPixelOffset] = pixelData[srcPixelOffset + 2];
imageData[dstPixelOffset + 1] = pixelData[srcPixelOffset + 1];
imageData[dstPixelOffset + 2] = pixelData[srcPixelOffset];
imageData[dstPixelOffset + 3] = pixelData[srcPixelOffset + 3];
}
} else {
imageData.set(pixelData.subarray(srcOffset, srcOffset + this.width * 4), dstOffset);
}
}
const image2 = new Jimp({
data: Buffer.from(imageData),
width: this.width,
height: this.height
});
await image2.write(filePath);
this.screenshotGPUBuffer.unmap();
}
async initComputePipeline() {
if (this.computePipeline)
return;
const shaderModule = this.device.createShaderModule({
label: "SuperSampling Compute Shader",
code: SUPERSAMPLING_COMPUTE_SHADER
});
this.computeBindGroupLayout = this.device.createBindGroupLayout({
label: "SuperSampling Bind Group Layout",
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
texture: { sampleType: "float", viewDimension: "2d" }
},
{
binding: 1,
visibility: GPUShaderStage.COMPUTE,
buffer: { type: "storage" }
},
{
binding: 2,
visibility: GPUShaderStage.COMPUTE,
buffer: { type: "uniform" }
}
]
});
const pipelineLayout = this.device.createPipelineLayout({
label: "SuperSampling Pipeline Layout",
bindGroupLayouts: [this.computeBindGroupLayout]
});
this.computePipeline = this.device.createComputePipeline({
label: "SuperSampling Compute Pipeline",
layout: pipelineLayout,
compute: {
module: shaderModule,
entryPoint: "main"
}
});
this.computeParamsBuffer = this.device.createBuffer({
label: "SuperSampling Params Buffer",
size: 16,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});
this.updateComputeParams();
}
updateComputeParams() {
if (!this.computeParamsBuffer || this.superSample === "none" /* NONE */)
return;
const paramsData = new ArrayBuffer(16);
const uint32View = new Uint32Array(paramsData);
uint32View[0] = this.width;
uint32View[1] = this.height;
uint32View[2] = this.superSampleAlgorithm;
this.device.queue.writeBuffer(this.computeParamsBuffer, 0, paramsData);
}
scheduleUpdateComputeBuffers() {
this.updateScheduled = true;
}
updateComputeBuffers(width, height) {
if (this.superSample === "none" /* NONE */)
return;
this.updateComputeParams();
const cellBytesSize = 48;
const terminalWidthCells = Math.floor((width + 1) / 2);
const terminalHeightCells = Math.floor((height + 1) / 2);
const outputBufferSize = terminalWidthCells * terminalHeightCells * cellBytesSize;
const oldOutputBuffer = this.computeOutputBuffer;
const oldReadbackBuffer = this.computeReadbackBuffer;
if (oldOutputBuffer) {
oldOutputBuffer.destroy();
}
if (oldReadbackBuffer) {
oldReadbackBuffer.destroy();
}
this.computeOutputBuffer = this.device.createBuffer({
label: "SuperSampling Output Buffer",
size: outputBufferSize,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC
});
this.computeReadbackBuffer = this.device.createBuffer({
label: "SuperSampling Readback Buffer",
size: outputBufferSize,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST
});
}
async runComputeShaderSuperSampling(texture, buffer) {
if (this.destroyed) {
return;
}
if (this.updateScheduled) {
this.updateScheduled = false;
await this.device.queue.onSubmittedWorkDone();
this.updateComputeBuffers(this.width, this.height);
}
await this.initComputePipeline();
if (!this.computePipeline || !this.computeBindGroupLayout || !this.computeOutputBuffer || !this.computeParamsBuffer) {
throw new Error("Compute pipeline not initialized");
}
const mapAsyncStart = performance.now();
const textureView = texture.createView({
label: "SuperSampling Input Texture View"
});
const bindGroup = this.device.createBindGroup({
label: "SuperSampling Bind Group",
layout: this.computeBindGroupLayout,
entries: [
{ binding: 0, resource: textureView },
{ binding: 1, resource: { buffer: this.computeOutputBuffer } },
{ binding: 2, resource: { buffer: this.computeParamsBuffer } }
]
});
const commandEncoder = this.device.createCommandEncoder({ label: "SuperSampling Command Encoder" });
const computePass = commandEncoder.beginComputePass({ label: "SuperSampling Compute Pass" });
computePass.setPipeline(this.computePipeline);
computePass.setBindGroup(0, bindGroup);
const terminalWidthCells = Math.floor((this.width + 1) / 2);
const terminalHeightCells = Math.floor((this.height + 1) / 2);
const dispatchX = Math.ceil(terminalWidthCells / WORKGROUP_SIZE);
const dispatchY = Math.ceil(terminalHeightCells / WORKGROUP_SIZE);
computePass.dispatchWorkgroups(dispatchX, dispatchY, 1);
computePass.end();
commandEncoder.copyBufferToBuffer(this.computeOutputBuffer, 0, this.computeReadbackBuffer, 0, this.computeOutputBuffer.size);
const commandBuffer = commandEncoder.finish();
this.device.queue.submit([commandBuffer]);
await this.computeReadbackBuffer.mapAsync(GPUMapMode.READ);
if (this.destroyed) {
this.computeReadbackBuffer.unmap();
return;
}
const resultsPtr = this.computeReadbackBuffer.getMappedRangePtr();
const size = this.computeReadbackBuffer.size;
this.mapAsyncTimeMs = performance.now() - mapAsyncStart;
const ssStart = performance.now();
buffer.drawPackedBuffer(resultsPtr, size, 0, 0, terminalWidthCells, terminalHeightCells);
this.superSampleDrawTimeMs = performance.now() - ssStart;
this.computeReadbackBuffer.unmap();
}
updateReadbackBuffer(renderWidth, renderHeight) {
if (this.readbackBuffer) {
this.readbackBuffer.destroy();
}
const bytesPerPixel = 4;
const unalignedBytesPerRow = renderWidth * bytesPerPixel;
const alignedBytesPerRow = Math.ceil(unalignedBytesPerRow / 256) * 256;
const textureBufferSize = alignedBytesPerRow * renderHeight;
this.readbackBuffer = this.device.createBuffer({
label: "Readback Buffer",
size: textureBufferSize,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST
});
}
async readPixelsIntoBuffer(buffer) {
if (this.destroyed) {
return;
}
const texture = this.gpuCanvasContext.getCurrentTexture();
this.gpuCanvasContext.switchTextures();
if (this.superSample === "gpu" /* GPU */) {
await this.runComputeShaderSuperSampling(texture, buffer);
return;
}
const textureBuffer = this.readbackBuffer;
if (!textureBuffer) {
throw new Error("Readback buffer not found");
}
try {
const bytesPerPixel = 4;
const unalignedBytesPerRow = this.width * bytesPerPixel;
const alignedBytesPerRow = Math.ceil(unalignedBytesPerRow / 256) * 256;
const contextFormat = texture.format;
const commandEncoder = this.device.createCommandEncoder({ label: "Readback Command Encoder" });
commandEncoder.copyTextureToBuffer({ texture }, { buffer: textureBuffer, bytesPerRow: alignedBytesPerRow, rowsPerImage: this.height }, {
width: this.width,
height: this.height
});
const commandBuffer = commandEncoder.finish();
this.device.queue.submit([commandBuffer]);
const mapStart = performance.now();
await textureBuffer.mapAsync(GPUMapMode.READ, 0, textureBuffer.size);
this.mapAsyncTimeMs = performance.now() - mapStart;
if (this.destroyed) {
textureBuffer.unmap();
return;
}
const mappedRangePtr = textureBuffer.getMappedRangePtr(0, textureBuffer.size);
const bufPtr = mappedRangePtr;
if (this.superSample === "cpu" /* CPU */) {
const format = contextFormat === "bgra8unorm" ? "bgra8unorm" : "rgba8unorm";
const ssStart = performance.now();
buffer.drawSuperSampleBuffer(0, 0, bufPtr, textureBuffer.size, format, alignedBytesPerRow);
this.superSampleDrawTimeMs = performance.now() - ssStart;
} else {
this.superSampleDrawTimeMs = 0;
const pixelData = new Uint8Array(toArrayBuffer(bufPtr, 0, textureBuffer.size));
const isBGRA = contextFormat === "bgra8unorm";
const backgroundColor = RGBA.fromValues(0, 0, 0, 1);
for (let y2 = 0;y2 < this.height; y2++) {
for (let x2 = 0;x2 < this.width; x2++) {
const pixelIndexInPaddedRow = y2 * alignedBytesPerRow + x2 * bytesPerPixel;
if (pixelIndexInPaddedRow + 3 >= pixelData.length)
continue;
let rByte, gByte, bByte;
if (isBGRA) {
bByte = pixelData[pixelIndexInPaddedRow];
gByte = pixelData[pixelIndexInPaddedRow + 1];
rByte = pixelData[pixelIndexInPaddedRow + 2];
} else {
rByte = pixelData[pixelIndexInPaddedRow];
gByte = pixelData[pixelIndexInPaddedRow + 1];
bByte = pixelData[pixelIndexInPaddedRow + 2];
}
const r = rByte / 255;
const g = gByte / 255;
const b = bByte / 255;
const cellColor = RGBA.fromValues(r, g, b, 1);
buffer.setCellWithAlphaBlending(x2, y2, "\u2588", cellColor, backgroundColor);
}
}
}
} finally {
textureBuffer.unmap();
}
}
}
// src/3d/WGPURenderer.ts
var SuperSampleType;
((SuperSampleType2) => {
SuperSampleType2["NONE"] = "none";
SuperSampleType2["GPU"] = "gpu";
SuperSampleType2["CPU"] = "cpu";
})(SuperSampleType ||= {});
class ThreeCliRenderer {
cliRenderer;
outputWidth;
outputHeight;
renderWidth;
renderHeight;
superSample;
backgroundColor = RGBA.fromValues(0, 0, 0, 1);
alpha = false;
threeRenderer;
canvas;
device = null;
activeCamera;
_aspectRatio = null;
doRenderStats = false;
resizeHandler;
debugToggleHandler;
destroyHandler;
renderTimeMs = 0;
readbackTimeMs = 0;
totalDrawTimeMs = 0;
renderMethod = () => Promise.resolve();
get aspectRatio() {
if (this._aspectRatio)
return this._aspectRatio;
if (this.cliRenderer.resolution) {
const pixelAspectRatio = this.cliRenderer.resolution.width / this.cliRenderer.resolution.height;
return pixelAspectRatio;
}
const terminalWidth = process.stdout.columns;
const terminalHeight = process.stdout.rows;
return terminalWidth / (terminalHeight * 2);
}
constructor(cliRenderer, options) {
this.cliRenderer = cliRenderer;
this.outputWidth = options.width;
this.outputHeight = options.height;
this.superSample = options.superSample ?? "gpu" /* GPU */;
this.renderWidth = this.outputWidth * (this.superSample !== "none" /* NONE */ ? 2 : 1);
this.renderHeight = this.outputHeight * (this.superSample !== "none" /* NONE */ ? 2 : 1);
this.backgroundColor = options.backgroundColor ?? RGBA.fromValues(0, 0, 0, 1);
this.alpha = options.alpha ?? false;
if (process.env.CELL_ASPECT_RATIO) {
this._aspectRatio = parseFloat(process.env.CELL_ASPECT_RATIO);
}
const fov = options.focalLength ? 2 * Math.atan(this.outputHeight / (2 * options.focalLength)) * (180 / Math.PI) : 1;
this.activeCamera = new PerspectiveCamera(fov, this.aspectRatio, 0.1, 1000);
this.activeCamera.position.set(0, 0, 3);
this.activeCamera.up.set(0, 1, 0);
this.activeCamera.lookAt(0, 0, 0);
this.activeCamera.updateMatrixWorld();
this.resizeHandler = (width, height) => {
this.setSize(width, height, true);
};
this.debugToggleHandler = (enabled) => {
this.doRenderStats = enabled;
};
this.destroyHandler = () => {
this.destroy();
};
if (options.autoResize !== false) {
this.cliRenderer.on("resize", this.resizeHandler);
}
this.cliRenderer.on("debugOverlay:toggle" /* DEBUG_OVERLAY_TOGGLE */, this.debugToggleHandler);
this.cliRenderer.on("destroy" /* DESTROY */, this.destroyHandler);
setupGlobals({ libPath: options.libPath });
}
toggleDebugStats() {
this.doRenderStats = !this.doRenderStats;
}
async init() {
this.device = await createWebGPUDevice();
this.canvas = new CLICanvas(this.device, this.renderWidth, this.renderHeight, this.superSample);
try {
this.threeRenderer = new WebGPURenderer({
canvas: this.canvas,
device: this.device,
alpha: this.alpha
});
this.setBackgroundColor(this.backgroundColor);
this.threeRenderer.toneMapping = NoToneMapping;
this.threeRenderer.outputColorSpace = LinearSRGBColorSpace;
this.threeRenderer.setSize(this.renderWidth, this.renderHeight, false);
} catch (error) {
console.error("Error creating THREE.WebGPURenderer:", error);
throw error;
}
await this.threeRenderer.init().then(() => {
this.renderMethod = this.doDrawScene.bind(this);
});
}
getSuperSampleAlgorithm() {
return this.canvas.getSuperSampleAlgorithm();
}
setSuperSampleAlgorithm(superSampleAlgorithm) {
this.canvas.setSuperSampleAlgorithm(superSampleAlgorithm);
}
saveToFile(filePath) {
return this.canvas.saveToFile(filePath);
}
setActiveCamera(camera) {
this.activeCamera = camera;
}
getActiveCamera() {
return this.activeCamera;
}
setBackgroundColor(color) {
this.backgroundColor = color;
const clearColor = new Color(this.backgroundColor.r, this.backgroundColor.g, this.backgroundColor.b);
const clearAlpha = this.alpha ? this.backgroundColor.a : 1;
this.threeRenderer.setClearColor(clearColor, clearAlpha);
}
setSize(width, height, forceUpdate = false) {
if (!forceUpdate && this.outputWidth === width && this.outputHeight === height)
return;
this.outputWidth = width;
this.outputHeight = height;
this.renderWidth = this.outputWidth * (this.superSample !== "none" /* NONE */ ? 2 : 1);
this.renderHeight = this.outputHeight * (this.superSample !== "none" /* NONE */ ? 2 : 1);
this.canvas?.setSize(this.renderWidth, this.renderHeight);
this.threeRenderer?.setSize(this.renderWidth, this.renderHeight, false);
this.threeRenderer?.setViewport(0, 0, this.renderWidth, this.renderHeight);
if (this.activeCamera instanceof PerspectiveCamera) {
this.activeCamera.aspect = this.aspectRatio;
}
this.activeCamera.updateProjectionMatrix();
}
async drawScene(root, buffer, deltaTime) {
await this.renderMethod(root, this.activeCamera, buffer, deltaTime);
if (this.doRenderStats) {
this.renderStats(buffer);
}
}
rendering = false;
destroyed = false;
async doDrawScene(root, camera, buffer, deltaTime) {
if (this.rendering) {
console.warn("ThreeCliRenderer.drawScene was called concurrently, which is not supported.");
return;
}
if (this.destroyed) {
return;
}
try {
this.rendering = true;
const totalStart = performance.now();
const renderStart = performance.now();
await this.threeRenderer.render(root, camera);
this.renderTimeMs = performance.now() - renderStart;
const readbackStart = performance.now();
await this.canvas.readPixelsIntoBuffer(buffer);
this.readbackTimeMs = performance.now() - readbackStart;
this.totalDrawTimeMs = performance.now() - totalStart;
} finally {
this.rendering = false;
}
}
toggleSuperSampling() {
if (this.superSample === "none" /* NONE */) {
this.superSample = "cpu" /* CPU */;
} else if (this.superSample === "cpu" /* CPU */) {
this.superSample = "gpu" /* GPU */;
} else {
this.superSample = "none" /* NONE */;
}
this.canvas.setSuperSample(this.superSample);
this.setSize(this.outputWidth, this.outputHeight, true);
}
renderStats(buffer) {
const stats = [
`WebGPU Renderer Stats:`,
` Render: ${this.renderTimeMs.toFixed(2)}ms`,
` Readback: ${this.readbackTimeMs.toFixed(2)}ms`,
` \u251C MapAsync: ${this.canvas.mapAsyncTimeMs.toFixed(2)}ms`,
` \u2514 SS Draw: ${this.canvas.superSampleDrawTimeMs.toFixed(2)}ms`,
` Total Draw: ${this.totalDrawTimeMs.toFixed(2)}ms`,
` SuperSample: ${this.superSample}`,
` SuperSample Algorithm: ${this.getSuperSampleAlgorithm()}`
];
const startY = 4;
const startX = 2;
const fg = RGBA.fromValues(0.9, 0.9, 0.9, 1);
const bg = RGBA.fromValues(0.1, 0.1, 0.1, 1);
stats.forEach((line, index) => {
buffer.drawText(line, startX + 1, startY + index, fg, bg);
});
}
destroy() {
this.destroyed = true;
this.cliRenderer.off("resize", this.resizeHandler);
this.cliRenderer.off("debugOverlay:toggle" /* DEBUG_OVERLAY_TOGGLE */, this.debugToggleHandler);
if (this.canvas) {
this.canvas.destroy();
}
if (this.threeRenderer) {
this.threeRenderer.dispose();
this.threeRenderer = undefined;
}
this.canvas = undefined;
this.device = null;
this.renderMethod = () => Promise.resolve();
}
}
// src/3d/ThreeRenderable.ts
import { PerspectiveCamera as PerspectiveCamera2 } from "three";
class ThreeRenderable extends Renderable {
engine;
scene;
autoAspect;
initPromise = null;
initFailed = false;
drawInFlight = false;
frameCallback = null;
frameCallbackRegistered = false;
cliRenderer;
clearColor;
constructor(ctx, options) {
const { scene = null, camera, renderer, autoAspect = true, ...renderableOptions } = options;
super(ctx, { ...renderableOptions, buffered: true, live: options.live ?? true });
const cliRenderer = ctx;
if (typeof cliRenderer.setFrameCallback !== "function" || typeof cliRenderer.removeFrameCallback !== "function") {
throw new Error("ThreeRenderable requires a CliRenderer context");
}
this.cliRenderer = cliRenderer;
this.scene = scene;
this.autoAspect = autoAspect;
this.clearColor = renderer?.backgroundColor ?? RGBA.fromValues(0, 0, 0, 1);
const { width, height } = this.getRenderSize();
this.engine = new ThreeCliRenderer(cliRenderer, {
width,
height,
autoResize: false,
...renderer
});
if (camera) {
this.engine.setActiveCamera(camera);
}
this.updateCameraAspect(width, height);
this.registerFrameCallback();
}
get aspectRatio() {
return this.getAspectRatio(this.width, this.height);
}
get renderer() {
return this.engine;
}
getScene() {
return this.scene;
}
setScene(scene) {
this.scene = scene;
this.requestRender();
}
getActiveCamera() {
return this.engine.getActiveCamera();
}
setActiveCamera(camera) {
this.engine.setActiveCamera(camera);
this.updateCameraAspect(this.width, this.height);
this.requestRender();
}
setAutoAspect(autoAspect) {
if (this.autoAspect === autoAspect)
return;
this.autoAspect = autoAspect;
if (autoAspect) {
this.updateCameraAspect(this.width, this.height);
}
}
onResize(width, height) {
if (width > 0 && height > 0) {
this.engine.setSize(width, height, true);
this.updateCameraAspect(width, height);
}
super.onResize(width, height);
}
renderSelf(buffer, deltaTime) {
if (!this.visible || this.isDestroyed)
return;
if (this.frameCallbackRegistered)
return;
if (this.buffered && !this.frameBuffer)
return;
this.renderToBuffer(buffer, deltaTime / 1000);
}
destroySelf() {
if (this.frameCallback && this.frameCallbackRegistered) {
this.cliRenderer.removeFrameCallback(this.frameCallback);
this.frameCallbackRegistered = false;
this.frameCallback = null;
}
this.engine.destroy();
super.destroySelf();
}
registerFrameCallback() {
if (this.frameCallbackRegistered)
return;
this.frameCallback = async (deltaTime) => {
if (this.isDestroyed || !this.visible || !this.parent)
return;
if (!this.scene || !this.frameBuffer)
return;
await this.renderToBuffer(this.frameBuffer, deltaTime / 1000);
};
this.cliRenderer.setFrameCallback(this.frameCallback);
this.frameCallbackRegistered = true;
}
async renderToBuffer(buffer, deltaTime) {
if (!this.scene || this.isDestroyed || this.drawInFlight)
return;
this.drawInFlight = true;
try {
const initialized = await this.ensureInitialized();
if (!initialized || !this.scene)
return;
if (buffer === this.frameBuffer) {
buffer.clear(this.clearColor);
}
await this.engine.drawScene(this.scene, buffer, deltaTime);
} finally {
this.drawInFlight = false;
}
}
async ensureInitialized() {
if (this.initFailed)
return false;
if (!this.initPromise) {
this.initPromise = this.engine.init().then(() => true).catch((error) => {
this.initFailed = true;
console.error("ThreeRenderable init failed:", error);
return false;
});
}
return this.initPromise;
}
updateCameraAspect(width, height) {
if (!this.autoAspect || width <= 0 || height <= 0)
return;
const camera = this.engine.getActiveCamera();
if (camera instanceof PerspectiveCamera2) {
camera.aspect = this.getAspectRatio(width, height);
camera.updateProjectionMatrix();
}
}
getAspectRatio(width, height) {
if (width <= 0 || height <= 0)
return 1;
const resolution = this.cliRenderer.resolution;
if (resolution && this.cliRenderer.terminalWidth > 0 && this.cliRenderer.terminalHeight > 0) {
const cellWidth = resolution.width / this.cliRenderer.terminalWidth;
const cellHeight = resolution.height / this.cliRenderer.terminalHeight;
if (cellHeight > 0) {
return width * cellWidth / (height * cellHeight);
}
}
return width / (height * 2);
}
getRenderSize() {
return {
width: Math.max(1, this.width),
height: Math.max(1, this.height)
};
}
}
// src/3d/TextureUtils.ts
import { Color as Color2, DataTexture, NearestFilter, ClampToEdgeWrapping, RGBAFormat, UnsignedByteType } from "three";
class TextureUtils {
static async loadTextureFromFile(path) {
try {
const buffer = await Bun.file(path).arrayBuffer();
const image2 = await Jimp.read(buffer);
image2.flip({ horizontal: false, vertical: true });
const texture = new DataTexture(image2.bitmap.data, image2.bitmap.width, image2.bitmap.height, RGBAFormat, UnsignedByteType);
texture.needsUpdate = true;
texture.format = RGBAFormat;
texture.magFilter = NearestFilter;
texture.minFilter = NearestFilter;
texture.wrapS = ClampToEdgeWrapping;
texture.wrapT = ClampToEdgeWrapping;
texture.flipY = false;
return texture;
} catch (error) {
console.error(`Failed to load texture from ${path}:`, error);
return null;
}
}
static async fromFile(path) {
return this.loadTextureFromFile(path);
}
static createCheckerboard(size = 256, color1 = new Color2(1, 1, 1), color2 = new Color2(0, 0, 0), checkSize = 32) {
const data = new Uint8ClampedArray(size * size * 4);
for (let y2 = 0;y2 < size; y2++) {
for (let x2 = 0;x2 < size; x2++) {
const isEvenX = Math.floor(x2 / checkSize) % 2 === 0;
const isEvenY = Math.floor(y2 / checkSize) % 2 === 0;
const color = isEvenX && isEvenY || !isEvenX && !isEvenY ? color1 : color2;
const index = (y2 * size + x2) * 4;
data[index] = Math.floor(color.r * 255);
data[index + 1] = Math.floor(color.g * 255);
data[index + 2] = Math.floor(color.b * 255);
data[index + 3] = 255;
}
}
const imageData = { data, width: size, height: size };
const texture = new DataTexture(data, size, size, RGBAFormat, UnsignedByteType);
texture.needsUpdate = true;
texture.format = RGBAFormat;
texture.magFilter = NearestFilter;
texture.minFilter = NearestFilter;
texture.wrapS = ClampToEdgeWrapping;
texture.wrapT = ClampToEdgeWrapping;
texture.flipY = false;
return texture;
}
static createGradient(size = 256, startColor = new Color2(1, 0, 0), endColor = new Color2(0, 0, 1), direction = "vertical") {
const data = new Uint8ClampedArray(size * size * 4);
for (let y2 = 0;y2 < size; y2++) {
for (let x2 = 0;x2 < size; x2++) {
let t = 0;
if (direction === "horizontal") {
t = x2 / (size - 1);
} else if (direction === "vertical") {
t = y2 / (size - 1);
} else if (direction === "radial") {
const dx = x2 - size / 2;
const dy = y2 - size / 2;
t = Math.min(1, Math.sqrt(dx * dx + dy * dy) / (size / 2));
}
const r = startColor.r * (1 - t) + endColor.r * t;
const g = startColor.g * (1 - t) + endColor.g * t;
const b = startColor.b * (1 - t) + endColor.b * t;
const index = (y2 * size + x2) * 4;
data[index] = Math.floor(r * 255);
data[index + 1] = Math.floor(g * 255);
data[index + 2] = Math.floor(b * 255);
data[index + 3] = 255;
}
}
const imageData = { data, width: size, height: size };
const texture = new DataTexture(data, size, size, RGBAFormat, UnsignedByteType);
texture.needsUpdate = true;
texture.format = RGBAFormat;
texture.magFilter = NearestFilter;
texture.minFilter = NearestFilter;
texture.wrapS = ClampToEdgeWrapping;
texture.wrapT = ClampToEdgeWrapping;
texture.flipY = false;
return texture;
}
static createNoise(size = 256, scale = 1, octaves = 1, color1 = new Color2(1, 1, 1), color2 = new Color2(0, 0, 0)) {
const data = new Uint8ClampedArray(size * size * 4);
for (let y2 = 0;y2 < size; y2++) {
for (let x2 = 0;x2 < size; x2++) {
let noise = 0;
let amplitude = 1;
let frequency = 1;
for (let o = 0;o < octaves; o++) {
const nx = x2 * frequency * scale / size;
const ny = y2 * frequency * scale / size;
const sampleX = Math.sin(nx * 12.9898) * 43758.5453;
const sampleY = Math.cos(ny * 78.233) * 43758.5453;
const sample = Math.sin(sampleX + sampleY) * 0.5 + 0.5;
noise += sample * amplitude;
amplitude *= 0.5;
frequency *= 2;
}
noise = Math.min(1, Math.max(0, noise));
const r = color1.r * noise + color2.r * (1 - noise);
const g = color1.g * noise + color2.g * (1 - noise);
const b = color1.b * noise + color2.b * (1 - noise);
const index = (y2 * size + x2) * 4;
data[index] = Math.floor(r * 255);
data[index + 1] = Math.floor(g * 255);
data[index + 2] = Math.floor(b * 255);
data[index + 3] = 255;
}
}
const imageData = { data, width: size, height: size };
const texture = new DataTexture(data, size, size, RGBAFormat, UnsignedByteType);
texture.needsUpdate = true;
texture.format = RGBAFormat;
texture.magFilter = NearestFilter;
texture.minFilter = NearestFilter;
texture.wrapS = ClampToEdgeWrapping;
texture.wrapT = ClampToEdgeWrapping;
texture.flipY = false;
return texture;
}
}
// src/3d/SpriteUtils.ts
import { Sprite, SpriteMaterial } from "three";
class SheetSprite extends Sprite {
_frameIndex = 0;
_numFrames = 0;
constructor(material, numFrames) {
super(material);
this._numFrames = numFrames;
this.setIndex(0);
}
setIndex = (index) => {
this._frameIndex = index;
this.material.map?.repeat.set(1 / this._numFrames, 1);
this.material.map?.offset.set(this._frameIndex / this._numFrames, 0);
};
}
class SpriteUtils {
static async fromFile(path, {
materialParameters = {
alphaTest: 0.1,
depthWrite: true
}
} = {}) {
const texture = await TextureUtils.fromFile(path);
if (!texture) {
throw new Error(`Failed to load sprite texture from ${path}`);
}
const spriteMaterial = new SpriteMaterial({ map: texture, ...materialParameters });
const sprite = new Sprite(spriteMaterial);
const textureAspectRatio = texture.image.width / texture.image.height;
sprite.updateMatrix = function() {
this.matrix.compose(this.position, this.quaternion, this.scale.clone().setX(this.scale.x * textureAspectRatio));
};
return sprite;
}
static async sheetFromFile(path, numFrames) {
const spriteTexture = await TextureUtils.fromFile(path);
if (!spriteTexture) {
console.error("Failed to load sprite texture, exiting.");
process.exit(1);
}
const spriteMaterial = new SpriteMaterial({ map: spriteTexture });
const sprite = new SheetSprite(spriteMaterial, numFrames);
const singleFrameWidth = spriteTexture.image.width / numFrames;
const singleFrameHeight = spriteTexture.image.height;
const frameAspectRatio = singleFrameWidth / singleFrameHeight;
sprite.updateMatrix = function() {
this.matrix.compose(this.position, this.quaternion, this.scale.clone().setX(this.scale.x * frameAspectRatio));
};
return sprite;
}
}
// src/3d/animation/SpriteAnimator.ts
import * as THREE from "three";
import { uniform, texture as tslTexture, uv, float, vec2, bufferAttribute, mix as mix2 } from "three/tsl";
import { MeshBasicNodeMaterial } from "three/webgpu";
var HIDDEN_MATRIX = new THREE.Matrix4().scale(new THREE.Vector3(0, 0, 0));
var DEFAULT_FRAME_DURATION = 100;
var DEFAULT_INITIAL_FRAME = 0;
var DEFAULT_SCALE = 1;
var DEFAULT_FLIP_X = false;
var DEFAULT_FLIP_Y = false;
class Animation {
name;
state;
resource;
instanceIndex;
instanceManager;
frameAttribute;
flipAttribute;
currentLocalFrame;
timeAccumulator;
isPlaying;
_isActive = false;
constructor(name, state, resource, instanceIndex, instanceManager, frameAttribute, flipAttribute) {
this.name = name;
this.state = state;
this.resource = resource;
this.instanceIndex = instanceIndex;
this.instanceManager = instanceManager;
this.frameAttribute = frameAttribute;
this.flipAttribute = flipAttribute;
this.currentLocalFrame = state.initialFrame;
this.timeAccumulator = 0;
this.isPlaying = true;
this.instanceManager.mesh.setMatrixAt(this.instanceIndex, HIDDEN_MATRIX);
const absoluteFrame = this.state.animFrameOffset + this.currentLocalFrame;
this.frameAttribute.setX(this.instanceIndex, absoluteFrame);
this.flipAttribute.setXY(this.instanceIndex, this.state.flipX ? 1 : 0, this.state.flipY ? 1 : 0);
}
activate(worldTransform) {
this._isActive = true;
this.isPlaying = true;
this.currentLocalFrame = this.state.initialFrame;
this.timeAccumulator = 0;
this.updateVisuals(worldTransform);
const absoluteFrame = this.state.animFrameOffset + this.currentLocalFrame;
this.frameAttribute.setX(this.instanceIndex, absoluteFrame);
this.frameAttribute.needsUpdate = true;
this.flipAttribute.setXY(this.instanceIndex, this.state.flipX ? 1 : 0, this.state.flipY ? 1 : 0);
this.flipAttribute.needsUpdate = true;
}
deactivate() {
this._isActive = false;
this.isPlaying = false;
this.instanceManager.mesh.setMatrixAt(this.instanceIndex, HIDDEN_MATRIX);
}
updateVisuals(worldTransform) {
if (!this._isActive)
return;
this.instanceManager.mesh.setMatrixAt(this.instanceIndex, worldTransform);
}
updateTime(deltaTimeMs) {
if (!this.isPlaying || !this._isActive)
return false;
this.timeAccumulator += deltaTimeMs;
let needsFrameAttributeUpdate = false;
if (this.timeAccumulator >= this.state.frameDuration) {
const framesToAdvance = Math.floor(this.timeAccumulator / this.state.frameDuration);
this.timeAccumulator %= this.state.frameDuration;
const oldLocalFrame = this.currentLocalFrame;
let nextLocalFrame = this.currentLocalFrame + framesToAdvance;
if (nextLocalFrame >= this.state.animNumFrames) {
if (this.state.loop) {
this.currentLocalFrame = nextLocalFrame % this.state.animNumFrames;
} else {
this.currentLocalFrame = this.state.animNumFrames - 1;
this.isPlaying = false;
}
} else {
this.currentLocalFrame = nextLocalFrame;
}
if (this.currentLocalFrame !== oldLocalFrame || !this.isPlaying) {
const absoluteFrame = this.state.animFrameOffset + this.currentLocalFrame;
this.frameAttribute.setX(this.instanceIndex, absoluteFrame);
this.frameAttribute.needsUpdate = true;
needsFrameAttributeUpdate = true;
}
}
return needsFrameAttributeUpdate;
}
play() {
if (!this._isActive)
return;
this.isPlaying = true;
}
stop() {
this.isPlaying = false;
}
goToFrame(localFrame) {
if (!this._isActive)
return;
const targetLocalFrame = Math.max(0, Math.min(localFrame, this.state.animNumFrames - 1));
if (this.currentLocalFrame !== targetLocalFrame) {
this.currentLocalFrame = targetLocalFrame;
this.timeAccumulator = 0;
const absoluteFrame = this.state.animFrameOffset + this.currentLocalFrame;
this.frameAttribute.setX(this.instanceIndex, absoluteFrame);
this.frameAttribute.needsUpdate = true;
}
}
setFrameDuration(newFrameDuration) {
if (newFrameDuration > 0) {
this.state = { ...this.state, frameDuration: newFrameDuration };
}
}
getResource() {
return this.resource;
}
releaseInstanceSlot() {
this.instanceManager.releaseInstanceSlot(this.instanceIndex);
}
}
class TiledSprite {
id;
animator;
_animations;
_currentAnimation;
_transformObject;
_reusableMatrix;
_reusableAnimGeomScale;
_isVisibleState = true;
originalDefinition;
constructor(id, userSpriteDefinition, animator, animationInstanceParams) {
this.id = id;
this.originalDefinition = userSpriteDefinition;
this.animator = animator;
this._transformObject = new THREE.Object3D;
this._reusableMatrix = new THREE.Matrix4;
this._reusableAnimGeomScale = new THREE.Vector3;
const initialScale = userSpriteDefinition.scale ?? DEFAULT_SCALE;
this._transformObject.scale.set(initialScale, initialScale, initialScale);
this._animations = new Map;
for (const params of animationInstanceParams) {
const anim = new Animation(params.name, params.state, params.resource, params.index, params.instanceManager, params.frameAttribute, params.flipAttribute);
this._animations.set(params.name, anim);
}
const initialAnim = this._animations.get(userSpriteDefinition.initialAnimation);
if (!initialAnim) {
throw new Error(`[TiledSprite] Initial animation "${userSpriteDefinition.initialAnimation}" not found for sprite "${this.id}".`);
}
this._currentAnimation = initialAnim;
const initialWorldMatrix = this._calculateAnimationWorldMatrix(this._currentAnimation.state);
this._currentAnimation.activate(initialWorldMatrix);
this._isVisibleState = true;
}
_calculateAnimationWorldMatrix(animState) {
const matrix = this._reusableMatrix;
const animGeomScale = this._reusableAnimGeomScale;
const worldHeight = this._transformObject.scale.y;
const frameAspectRatio = animState.sheetTilesetWidth / animState.sheetNumFrames / animState.sheetTilesetHeight;
const worldWidth = worldHeight * frameAspectRatio;
animGeomScale.set(worldWidth, worldHeight, this._transformObject.scale.z);
matrix.compose(this._transformObject.position, this._transformObject.quaternion, animGeomScale);
return matrix;
}
get currentAnimation() {
return this._currentAnimation;
}
updateCurrentAnimationVisuals() {
if (this._isVisibleState) {
const currentAnim = this.currentAnimation;
if (currentAnim) {
const finalMatrix = this._calculateAnimationWorldMatrix(currentAnim.state);
currentAnim.updateVisuals(finalMatrix);
}
}
}
setPosition(position) {
this._transformObject.position.copy(position);
this.updateCurrentAnimationVisuals();
}
setRotation(rotation) {
this._transformObject.quaternion.copy(rotation);
this.updateCurrentAnimationVisuals();
}
setScale(scale) {
this._transformObject.scale.copy(scale);
this.updateCurrentAnimationVisuals();
}
getScale() {
return this._transformObject.scale.clone();
}
setTransform(position, rotation, newScale) {
this._transformObject.position.copy(position);
this._transformObject.quaternion.copy(rotation);
this._transformObject.scale.copy(newScale);
this.updateCurrentAnimationVisuals();
}
play() {
this.currentAnimation.play();
}
stop() {
this.currentAnimation.stop();
}
goToFrame(frame) {
this.currentAnimation.goToFrame(frame);
}
setFrameDuration(newFrameDuration) {
this.currentAnimation.setFrameDuration(newFrameDuration);
}
isPlaying() {
return this.currentAnimation.isPlaying;
}
async setAnimation(animationName) {
const newAnim = this._animations.get(animationName);
if (!newAnim) {
throw new Error(`[TiledSprite] Animation "${animationName}" not found for sprite "${this.id}".`);
}
const switchingToSameAnimation = this._currentAnimation.name === animationName;
const oldAnim = this._currentAnimation;
if (!switchingToSameAnimation || !this._isVisibleState) {
oldAnim?.deactivate();
}
this._currentAnimation = newAnim;
if (this._isVisibleState) {
const finalMatrix = this._calculateAnimationWorldMatrix(newAnim.state);
newAnim.activate(finalMatrix);
} else {
newAnim.deactivate();
}
}
update(deltaTime) {
if (this.visible) {
this.currentAnimation.updateTime(deltaTime);
}
}
destroy() {
this._animations.forEach((anim) => {
anim.deactivate();
anim.releaseInstanceSlot();
});
this._animations.clear();
this._isVisibleState = false;
}
getCurrentAnimationName() {
return this._currentAnimation.name;
}
getWorldTransform() {
return this._calculateAnimationWorldMatrix(this._currentAnimation.state);
}
getWorldPlaneSize() {
const animState = this._currentAnimation.state;
const worldHeight = this._transformObject.scale.y;
const frameActualWidthPx = animState.sheetTilesetWidth / animState.sheetNumFrames;
const frameAspectRatio = frameActualWidthPx / animState.sheetTilesetHeight;
const worldWidth = worldHeight * frameAspectRatio;
return new THREE.Vector2(worldWidth, worldHeight);
}
get visible() {
return this._isVisibleState;
}
set visible(value) {
if (this._isVisibleState === value) {
return;
}
this._isVisibleState = value;
if (value) {
const finalMatrix = this._calculateAnimationWorldMatrix(this._currentAnimation.state);
this._currentAnimation.activate(finalMatrix);
} else {
this._currentAnimation.deactivate();
}
}
get definition() {
return this.originalDefinition;
}
get currentTransform() {
return {
position: this._transformObject.position.clone(),
quaternion: this._transformObject.quaternion.clone(),
scale: this._transformObject.scale.clone()
};
}
}
class SpriteAnimator {
scene;
instances = new Map;
_idCounter = 0;
instanceManagers = new Map;
constructor(scene) {
this.scene = scene;
}
createSpriteAnimationMaterial(resource, frameAttribute, flipAttribute, materialFactory) {
const texture = resource.texture;
const sheetProps = resource.sheetProperties;
const uvTileWidth = 1 / sheetProps.sheetNumFrames;
const uvTileHeight = 1;
const uvTileSize = new THREE.Vector2(uvTileWidth, uvTileHeight);
const tileSizeUniform = uniform(uvTileSize);
const epsilon = float(0.000001);
const baseUV = uv();
const oneFloat = float(1);
const a_frameIndex = bufferAttribute(frameAttribute);
const a_flip = bufferAttribute(flipAttribute);
const calculatedTileCoordX = a_frameIndex.mul(tileSizeUniform.x);
const calculatedTileCoord = vec2(calculatedTileCoordX, float(0));
const flippedX = mix2(baseUV.x, oneFloat.sub(baseUV.x), a_flip.x);
const flippedY = mix2(baseUV.y, oneFloat.sub(baseUV.y), a_flip.y);
const finalLocalUV = vec2(flippedX, flippedY);
const mapNode = tslTexture(texture);
const finalUV = finalLocalUV.mul(tileSizeUniform).min(tileSizeUniform.sub(epsilon)).add(calculatedTileCoord);
const sampledColor = mapNode.sample(finalUV);
const material = materialFactory();
material.colorNode = sampledColor;
return material;
}
getOrCreateInstanceManager(resource, maxInstances, renderOrder, depthWrite, materialFactory) {
const key = `${resource.sheetProperties.imagePath}_${maxInstances}_${renderOrder}_${depthWrite}`;
let manager = this.instanceManagers.get(key);
if (!manager) {
const geometry = new THREE.PlaneGeometry(1, 1);
const frameArray = new Float32Array(maxInstances);
const frameAttribute = new THREE.InstancedBufferAttribute(frameArray, 1);
frameAttribute.setUsage(THREE.DynamicDrawUsage);
const flipArray = new Float32Array(maxInstances * 2);
const flipAttribute = new THREE.InstancedBufferAttribute(flipArray, 2);
flipAttribute.setUsage(THREE.DynamicDrawUsage);
const material = this.createSpriteAnimationMaterial(resource, frameAttribute, flipAttribute, materialFactory);
geometry.setAttribute("a_frameIndexInstanced", frameAttribute);
geometry.setAttribute("a_flipInstanced", flipAttribute);
for (let i = 0;i < maxInstances; i++) {
flipAttribute.setXY(i, 0, 0);
}
flipAttribute.needsUpdate = true;
const instanceManager = resource.createInstanceManager(geometry, material, {
maxInstances,
renderOrder,
depthWrite,
name: `SpriteAnimator_${key}`
});
const uvTileWidth = 1 / resource.sheetProperties.sheetNumFrames;
const uvTileSize = new THREE.Vector2(uvTileWidth, 1);
manager = {
instanceManager,
frameAttribute,
flipAttribute,
uvTileSize
};
this.instanceManagers.set(key, manager);
}
return manager;
}
async createSprite(userSpriteDefinition, materialFactory) {
const id = userSpriteDefinition.id ?? `sprite_${this._idCounter++}`;
const animationInstanceParams = [];
const resolvedMaterialFactory = materialFactory ?? (() => new MeshBasicNodeMaterial({
transparent: true,
alphaTest: 0.1,
depthWrite: true
}));
const resourceManagers = new Map;
for (const animName in userSpriteDefinition.animations) {
const animDef = userSpriteDefinition.animations[animName];
const resource = animDef.resource;
let managerInfo = resourceManagers.get(resource);
if (!managerInfo) {
const maxInstances = userSpriteDefinition.maxInstances ?? 1024;
const renderOrder = userSpriteDefinition.renderOrder ?? 0;
const depthWrite = userSpriteDefinition.depthWrite ?? true;
managerInfo = this.getOrCreateInstanceManager(resource, maxInstances, renderOrder, depthWrite, resolvedMaterialFactory);
resourceManagers.set(resource, managerInfo);
}
const instanceIndex = managerInfo.instanceManager.acquireInstanceSlot();
const resolvedState = {
imagePath: resource.sheetProperties.imagePath,
sheetTilesetWidth: resource.sheetProperties.sheetTilesetWidth,
sheetTilesetHeight: resource.sheetProperties.sheetTilesetHeight,
sheetNumFrames: resource.sheetProperties.sheetNumFrames,
animNumFrames: animDef.animNumFrames ?? resource.sheetProperties.sheetNumFrames,
animFrameOffset: animDef.animFrameOffset ?? 0,
frameDuration: animDef.frameDuration ?? DEFAULT_FRAME_DURATION,
loop: animDef.loop ?? true,
initialFrame: animDef.initialFrame ?? DEFAULT_INITIAL_FRAME,
flipX: animDef.flipX ?? DEFAULT_FLIP_X,
flipY: animDef.flipY ?? DEFAULT_FLIP_Y,
texture: resource.texture
};
animationInstanceParams.push({
name: animName,
state: resolvedState,
resource,
index: instanceIndex,
instanceManager: managerInfo.instanceManager,
frameAttribute: managerInfo.frameAttribute,
flipAttribute: managerInfo.flipAttribute
});
}
if (!userSpriteDefinition.initialAnimation || !userSpriteDefinition.animations[userSpriteDefinition.initialAnimation]) {
let found = false;
for (const p of animationInstanceParams)
if (p.name === userSpriteDefinition.initialAnimation)
found = true;
if (!found) {
for (const params of animationInstanceParams) {
params.instanceManager.releaseInstanceSlot(params.index);
}
throw new Error(`[SpriteAnimator] initialAnimation "${userSpriteDefinition.initialAnimation}" not found or invalid for sprite "${id}".`);
}
}
const tiledSprite = new TiledSprite(id, userSpriteDefinition, this, animationInstanceParams);
this.instances.set(id, tiledSprite);
return tiledSprite;
}
update(deltaTime) {
for (const sprite of this.instances.values()) {
sprite.update(deltaTime);
}
}
removeSprite(id) {
const sprite = this.instances.get(id);
if (sprite) {
sprite.destroy();
this.instances.delete(id);
}
}
removeAllSprites() {
const ids = Array.from(this.instances.keys());
for (const id of ids) {
this.removeSprite(id);
}
}
}
// src/3d/animation/ExplodingSpriteEffect.ts
import * as THREE2 from "three";
import {
uniform as uniform2,
attribute,
texture as tslTexture2,
uv as uv2,
float as float2,
vec2 as vec22,
vec3,
vec4,
step,
max,
sin,
cos,
positionLocal,
mat3
} from "three/tsl";
import { MeshBasicNodeMaterial as MeshBasicNodeMaterial2 } from "three/webgpu";
var DEFAULT_EXPLOSION_PARAMETERS = {
numRows: 5,
numCols: 5,
durationMs: 2000,
strength: 5,
strengthVariation: 0.5,
gravity: 9.8,
gravityScale: 0.15,
fadeOut: true,
angularVelocityMin: new THREE2.Vector3(-Math.PI, -Math.PI, -Math.PI),
angularVelocityMax: new THREE2.Vector3(Math.PI, Math.PI, Math.PI),
initialVelocityYBoost: 1,
zVariationStrength: 0.3,
materialFactory: () => new MeshBasicNodeMaterial2({
transparent: true,
alphaTest: 0.01,
side: THREE2.DoubleSide,
depthWrite: true
})
};
class ExplodingSpriteEffect {
static baseMaterialCache = new Map;
scene;
resource;
frameUvOffset;
frameUvSize;
spriteWorldTransform;
params;
instancedMesh;
material;
numParticles;
uniformRefs;
isActive = true;
timeElapsedMs = 0;
constructor(scene, resource, frameUvOffset, frameUvSize, spriteWorldTransform, userParams) {
this.scene = scene;
this.resource = resource;
this.frameUvOffset = frameUvOffset;
this.frameUvSize = frameUvSize;
this.spriteWorldTransform = spriteWorldTransform;
this.params = { ...DEFAULT_EXPLOSION_PARAMETERS, ...userParams };
this.numParticles = this.params.numRows * this.params.numCols;
const materialFactory = userParams?.materialFactory ?? DEFAULT_EXPLOSION_PARAMETERS.materialFactory;
this._createGPUParticles(materialFactory);
}
_createGPUParticles(materialFactory) {
if (this.numParticles === 0)
return;
const particleUnitWidth = 1 / this.params.numCols;
const particleUnitHeight = 1 / this.params.numRows;
const poolKey = `${this.params.numRows}x${this.params.numCols}`;
this._createGPUMaterial(materialFactory);
this.instancedMesh = this.resource.meshPool.acquireMesh(poolKey, {
geometry: () => {
const geometry = new THREE2.PlaneGeometry(particleUnitWidth, particleUnitHeight);
geometry.setAttribute("a_particleData", new THREE2.InstancedBufferAttribute(new Float32Array(this.numParticles * 4), 4));
geometry.setAttribute("a_velocity", new THREE2.InstancedBufferAttribute(new Float32Array(this.numParticles * 4), 4));
geometry.setAttribute("a_angularVel", new THREE2.InstancedBufferAttribute(new Float32Array(this.numParticles * 4), 4));
geometry.setAttribute("a_uvOffset", new THREE2.InstancedBufferAttribute(new Float32Array(this.numParticles * 4), 4));
return geometry;
},
material: this.material,
maxInstances: this.numParticles,
name: `ExplodingSprite_${poolKey}`
});
const particleData = this.instancedMesh.geometry.getAttribute("a_particleData").array;
const velocityData = this.instancedMesh.geometry.getAttribute("a_velocity").array;
const angularVelData = this.instancedMesh.geometry.getAttribute("a_angularVel").array;
const uvOffsetData = this.instancedMesh.geometry.getAttribute("a_uvOffset").array;
const spriteWorldCenter = new THREE2.Vector3().setFromMatrixPosition(this.spriteWorldTransform);
let particleIndex = 0;
for (let r = 0;r < this.params.numRows; r++) {
for (let c2 = 0;c2 < this.params.numCols; c2++) {
const localParticlePosX = (c2 + 0.5) * particleUnitWidth - 0.5;
const localParticlePosY = (r + 0.5) * particleUnitHeight - 0.5;
const initialLocalPosition = new THREE2.Vector3(localParticlePosX, localParticlePosY, 0);
const worldPosition = initialLocalPosition.clone().applyMatrix4(this.spriteWorldTransform);
let velocityDir = worldPosition.clone().sub(spriteWorldCenter);
if (velocityDir.lengthSq() < 0.0001) {
velocityDir.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5);
}
velocityDir.normalize();
const strengthVariationRange = this.params.strengthVariation;
const minStrengthFactor = 1 - strengthVariationRange * 0.5;
const maxStrengthFactor = 1 + strengthVariationRange * 0.5;
const strengthFactor = minStrengthFactor + Math.random() * (maxStrengthFactor - minStrengthFactor);
const strength = this.params.strength * strengthFactor * 0.1;
const velocity = velocityDir.multiplyScalar(strength);
if (Math.abs(this.spriteWorldTransform.elements[10]) < 0.1 && Math.abs(this.spriteWorldTransform.elements[11]) < 0.1) {
velocity.z += (Math.random() - 0.5) * strength * this.params.zVariationStrength;
}
velocity.y += this.params.strength * this.params.initialVelocityYBoost * Math.random();
const angularVelocity = new THREE2.Vector3(THREE2.MathUtils.randFloat(this.params.angularVelocityMin.x, this.params.angularVelocityMax.x), THREE2.MathUtils.randFloat(this.params.angularVelocityMin.y, this.params.angularVelocityMax.y), THREE2.MathUtils.randFloat(this.params.angularVelocityMin.z, this.params.angularVelocityMax.z));
const lifeVariation = 0.8 + Math.random() * 0.4;
const randomSeed = Math.random();
const u0 = this.frameUvOffset.x + c2 / this.params.numCols * this.frameUvSize.x;
const v0 = this.frameUvOffset.y + r / this.params.numRows * this.frameUvSize.y;
const uSize = this.frameUvSize.x / this.params.numCols;
const vSize = this.frameUvSize.y / this.params.numRows;
const baseIndex = particleIndex * 4;
particleData[baseIndex] = localParticlePosX;
particleData[baseIndex + 1] = localParticlePosY;
particleData[baseIndex + 2] = randomSeed;
particleData[baseIndex + 3] = lifeVariation;
velocityData[baseIndex] = velocity.x;
velocityData[baseIndex + 1] = velocity.y;
velocityData[baseIndex + 2] = velocity.z;
velocityData[baseIndex + 3] = 0;
angularVelData[baseIndex] = angularVelocity.x;
angularVelData[baseIndex + 1] = angularVelocity.y;
angularVelData[baseIndex + 2] = angularVelocity.z;
angularVelData[baseIndex + 3] = 0;
uvOffsetData[baseIndex] = u0;
uvOffsetData[baseIndex + 1] = v0;
uvOffsetData[baseIndex + 2] = uSize;
uvOffsetData[baseIndex + 3] = vSize;
particleIndex++;
}
}
this.instancedMesh.onBeforeRender = () => {
this.uniformRefs.time.value = this.timeElapsedMs / 1000;
};
this.timeElapsedMs = 0;
this.instancedMesh.geometry.getAttribute("a_particleData").needsUpdate = true;
this.instancedMesh.geometry.getAttribute("a_velocity").needsUpdate = true;
this.instancedMesh.geometry.getAttribute("a_angularVel").needsUpdate = true;
this.instancedMesh.geometry.getAttribute("a_uvOffset").needsUpdate = true;
this.instancedMesh.frustumCulled = false;
for (let i = 0;i < this.numParticles; i++) {
this.instancedMesh.setMatrixAt(i, this.spriteWorldTransform);
}
this.instancedMesh.instanceMatrix.needsUpdate = true;
this.scene.add(this.instancedMesh);
}
_createGPUMaterial(materialFactory) {
const key = `${this.resource.texture.uuid}_${this.params.numRows}x${this.params.numCols}_${this.params.fadeOut ? 1 : 0}`;
let template = ExplodingSpriteEffect.baseMaterialCache.get(key);
if (!template) {
template = ExplodingSpriteEffect._buildTemplateMaterial(this.resource.texture, this.params, materialFactory);
ExplodingSpriteEffect.baseMaterialCache.set(key, template);
}
this.material = template;
this.uniformRefs = template.userData.uniformRefs;
}
static _buildTemplateMaterial(texture, params, materialFactory) {
const timeUniformNode = uniform2(0);
timeUniformNode.name = "timeUniform";
const durationUniformNode = uniform2(params.durationMs / 1000);
durationUniformNode.name = "durationUniform";
const gravityUniformNode = uniform2(params.gravity * params.gravityScale);
gravityUniformNode.name = "gravityUniform";
const a_particleData = attribute("a_particleData", "vec4");
const a_velocity = attribute("a_velocity", "vec4");
const a_angularVel = attribute("a_angularVel", "vec4");
const a_uvOffset = attribute("a_uvOffset", "vec4");
const localPos = vec22(a_particleData.x, a_particleData.y);
const lifeVariation = a_particleData.w;
const initialVelocity = vec3(a_velocity.x, a_velocity.y, a_velocity.z);
const angularVelocity = vec3(a_angularVel.x, a_angularVel.y, a_angularVel.z);
const uvOffset = vec22(a_uvOffset.x, a_uvOffset.y);
const uvSize = vec22(a_uvOffset.z, a_uvOffset.w);
const particleLifetime = durationUniformNode.mul(lifeVariation);
const normalizedTime = timeUniformNode.div(particleLifetime);
const isAlive = step(normalizedTime, float2(1));
const deltaTime = timeUniformNode;
const gravity = vec3(float2(0), gravityUniformNode.negate(), float2(0));
const velocityContribution = initialVelocity.mul(deltaTime);
const gravityContribution = gravity.mul(deltaTime).mul(deltaTime).mul(float2(0.5));
const positionOffset = velocityContribution.add(gravityContribution);
const rotationAmount = angularVelocity.mul(deltaTime);
const cosX = cos(rotationAmount.x);
const sinX = sin(rotationAmount.x);
const cosY = cos(rotationAmount.y);
const sinY = sin(rotationAmount.y);
const cosZ = cos(rotationAmount.z);
const sinZ = sin(rotationAmount.z);
const rotationMatrix = mat3(cosY.mul(cosZ), cosY.mul(sinZ).negate(), sinY, sinX.mul(sinY).mul(cosZ).add(cosX.mul(sinZ)), sinX.mul(sinY).mul(sinZ).negate().add(cosX.mul(cosZ)), sinX.mul(cosY).negate(), cosX.mul(sinY).mul(cosZ).negate().add(sinX.mul(sinZ)), cosX.mul(sinY).mul(sinZ).add(sinX.mul(cosZ)), cosX.mul(cosY));
const rotatedVertexPosition = rotationMatrix.mul(positionLocal);
const finalOffset = vec3(localPos.x, localPos.y, float2(0)).add(positionOffset);
let opacity = float2(1);
if (params.fadeOut) {
const fadeStart = float2(0.7);
const fadeProgress = max(float2(0), normalizedTime.sub(fadeStart).div(float2(1).sub(fadeStart)));
opacity = float2(1).sub(fadeProgress);
}
opacity = opacity.mul(isAlive);
const baseUV = uv2();
const finalUV = baseUV.mul(uvSize).add(uvOffset);
const mapNode = tslTexture2(texture);
const sampledColor = mapNode.sample(finalUV);
const material = materialFactory();
const finalColor = vec4(sampledColor.rgb, sampledColor.a.mul(opacity));
material.colorNode = finalColor;
material.positionNode = rotatedVertexPosition.add(finalOffset);
material.userData.uniformRefs = {
time: timeUniformNode,
duration: durationUniformNode,
gravity: gravityUniformNode
};
return material;
}
update(deltaTimeMs) {
if (!this.isActive)
return;
this.timeElapsedMs += deltaTimeMs;
if (this.timeElapsedMs >= this.params.durationMs) {
this.dispose();
}
}
dispose() {
if (!this.isActive)
return;
this.isActive = false;
if (this.instancedMesh) {
this.scene.remove(this.instancedMesh);
const poolKey = `${this.params.numRows}x${this.params.numCols}`;
this.resource.meshPool.releaseMesh(poolKey, this.instancedMesh);
}
}
}
class ExplosionManager {
scene;
activeExplosions = [];
constructor(scene) {
this.scene = scene;
}
fillPool(resource, count, params = {}) {
const effectParams = { ...DEFAULT_EXPLOSION_PARAMETERS, ...params };
const poolKey = `${effectParams.numRows}x${effectParams.numCols}`;
const particleUnitWidth = 1 / effectParams.numCols;
const particleUnitHeight = 1 / effectParams.numRows;
const numParticles = effectParams.numRows * effectParams.numCols;
const materialFactory = params.materialFactory ?? DEFAULT_EXPLOSION_PARAMETERS.materialFactory;
const material = ExplodingSpriteEffect._buildTemplateMaterial(resource.texture, effectParams, materialFactory);
resource.meshPool.fill(poolKey, {
geometry: () => {
const geometry = new THREE2.PlaneGeometry(particleUnitWidth, particleUnitHeight);
const particleData = new Float32Array(numParticles * 4);
const velocityData = new Float32Array(numParticles * 4);
const angularVelData = new Float32Array(numParticles * 4);
const uvOffsetData = new Float32Array(numParticles * 4);
const particleDataAttribute = new THREE2.InstancedBufferAttribute(particleData, 4);
const velocityAttribute = new THREE2.InstancedBufferAttribute(velocityData, 4);
const angularVelAttribute = new THREE2.InstancedBufferAttribute(angularVelData, 4);
const uvOffsetAttribute = new THREE2.InstancedBufferAttribute(uvOffsetData, 4);
geometry.setAttribute("a_particleData", particleDataAttribute);
geometry.setAttribute("a_velocity", velocityAttribute);
geometry.setAttribute("a_angularVel", angularVelAttribute);
geometry.setAttribute("a_uvOffset", uvOffsetAttribute);
particleDataAttribute.needsUpdate = true;
velocityAttribute.needsUpdate = true;
angularVelAttribute.needsUpdate = true;
uvOffsetAttribute.needsUpdate = true;
return geometry;
},
material,
maxInstances: numParticles,
name: `ExplodingSprite_${poolKey}`
}, count);
}
_createEffectCreationData(sprite) {
const animState = sprite.currentAnimation.state;
const resource = sprite.currentAnimation.getResource();
const currentAbsoluteFrame = animState.animFrameOffset + sprite.currentAnimation.currentLocalFrame;
const frameUOffset = currentAbsoluteFrame * resource.uvTileSize.x;
return {
resource,
frameUvOffset: new THREE2.Vector2(frameUOffset, 0),
frameUvSize: resource.uvTileSize.clone(),
spriteWorldTransform: sprite.getWorldTransform()
};
}
createExplosionForSprite(spriteToExplode, userParams) {
const effectCreationData = this._createEffectCreationData(spriteToExplode);
const definition = spriteToExplode.definition;
const transform = spriteToExplode.currentTransform;
let spriteRecreationData = {
definition,
currentTransform: transform
};
spriteToExplode.destroy();
const effect = new ExplodingSpriteEffect(this.scene, effectCreationData.resource, effectCreationData.frameUvOffset, effectCreationData.frameUvSize, effectCreationData.spriteWorldTransform, userParams);
this.activeExplosions.push(effect);
const handle = {
effect,
recreationData: spriteRecreationData,
hasBeenRestored: false,
restoreSprite: async (spriteAnimator) => {
if (handle.hasBeenRestored) {
return null;
}
handle.effect.dispose();
const newSprite = await spriteAnimator.createSprite(handle.recreationData.definition);
const currentSpriteTransform = handle.recreationData.currentTransform;
newSprite.setTransform(currentSpriteTransform.position, currentSpriteTransform.quaternion, currentSpriteTransform.scale);
handle.hasBeenRestored = true;
return newSprite;
}
};
return handle;
}
update(deltaTimeMs) {
for (let i = this.activeExplosions.length - 1;i >= 0; i--) {
const explosion = this.activeExplosions[i];
explosion.update(deltaTimeMs);
if (!explosion.isActive) {
this.activeExplosions.splice(i, 1);
}
}
}
disposeAll() {
this.activeExplosions.forEach((exp) => exp.dispose());
this.activeExplosions = [];
}
}
// src/3d/animation/SpriteParticleGenerator.ts
import * as THREE3 from "three";
import {
uniform as uniform3,
texture as tslTexture3,
uv as uv3,
float as float3,
vec2 as vec23,
vec3 as vec32,
vec4 as vec42,
bufferAttribute as bufferAttribute2,
step as step2,
max as max2,
sin as sin2,
cos as cos2,
positionLocal as positionLocal2,
mat3 as mat32,
mix as mix3,
floor
} from "three/tsl";
import { MeshBasicNodeMaterial as MeshBasicNodeMaterial3 } from "three/webgpu";
class SpriteParticleGenerator {
scene;
baseConfig;
autoSpawnConfig = null;
_currentOriginIndex = 0;
instanceManager = null;
material = null;
texture = null;
particleDataAttribute = null;
velocityAttribute = null;
angularVelAttribute = null;
scaleDataAttribute = null;
timeUniform;
gravityUniform;
animationUniform;
sheetNumFramesUniform;
particleSlots = [];
currentTime = 0;
maxParticles;
isInitialized = false;
constructor(scene, initialBaseConfig) {
this.scene = scene;
this.baseConfig = { ...initialBaseConfig };
this.maxParticles = this.baseConfig.maxParticles;
if (!this.baseConfig.resource) {
throw new Error("[SpriteParticleGenerator] resource is mandatory in initialBaseConfig.");
}
this.timeUniform = uniform3(0);
this.gravityUniform = uniform3(this.baseConfig.gravity || new THREE3.Vector3(0, -9.8, 0));
this.animationUniform = uniform3(new THREE3.Vector4);
this.sheetNumFramesUniform = uniform3(1);
}
async _ensureInitialized() {
if (this.isInitialized)
return;
await this._initializeGPUParticleSystem();
this.isInitialized = true;
}
async _initializeGPUParticleSystem() {
const resource = this.baseConfig.resource;
this.texture = resource.texture;
const frameDuration = (this.baseConfig.frameDuration ?? 100) / 1000;
const animNumFrames = this.baseConfig.animNumFrames ?? resource.sheetProperties.sheetNumFrames;
const loop = this.baseConfig.loop ?? true ? 1 : 0;
const animFrameOffset = this.baseConfig.animFrameOffset ?? 0;
this.animationUniform.value.set(frameDuration, animNumFrames, loop, animFrameOffset);
this.sheetNumFramesUniform.value = resource.sheetProperties.sheetNumFrames;
const particleData = new Float32Array(this.maxParticles * 4);
const velocityData = new Float32Array(this.maxParticles * 4);
const angularVelData = new Float32Array(this.maxParticles * 4);
const scaleData = new Float32Array(this.maxParticles * 4);
this.particleDataAttribute = new THREE3.InstancedBufferAttribute(particleData, 4);
this.velocityAttribute = new THREE3.InstancedBufferAttribute(velocityData, 4);
this.angularVelAttribute = new THREE3.InstancedBufferAttribute(angularVelData, 4);
this.scaleDataAttribute = new THREE3.InstancedBufferAttribute(scaleData, 4);
this.particleDataAttribute.setUsage(THREE3.DynamicDrawUsage);
this.velocityAttribute.setUsage(THREE3.DynamicDrawUsage);
this.angularVelAttribute.setUsage(THREE3.DynamicDrawUsage);
this.scaleDataAttribute.setUsage(THREE3.DynamicDrawUsage);
for (let i = 0;i < this.maxParticles; i++) {
this.particleSlots.push({ isActive: false, spawnTime: 0, lifespan: 0 });
particleData[i * 4 + 3] = -1;
}
const frameAspectRatio = this.texture.image.width / resource.sheetProperties.sheetNumFrames / this.texture.image.height;
const scale = this.baseConfig.scale ?? 1;
const geometry = new THREE3.PlaneGeometry(scale * frameAspectRatio, scale);
geometry.setAttribute("a_particleData", this.particleDataAttribute);
geometry.setAttribute("a_velocity", this.velocityAttribute);
geometry.setAttribute("a_angularVel", this.angularVelAttribute);
geometry.setAttribute("a_scaleData", this.scaleDataAttribute);
const materialFactory = this.baseConfig.materialFactory ?? (() => new MeshBasicNodeMaterial3({
transparent: true,
alphaTest: 0.01,
side: THREE3.DoubleSide,
depthWrite: this.baseConfig.depthWrite ?? false
}));
const material = this._createGPUMaterial(materialFactory);
this.instanceManager = resource.createInstanceManager(geometry, material, {
maxInstances: this.maxParticles,
renderOrder: this.baseConfig.renderOrder ?? 0,
depthWrite: this.baseConfig.depthWrite ?? true,
name: `SpriteParticleGenerator_${resource.sheetProperties.imagePath.replace(/[^a-zA-Z0-9_]/g, "_")}`,
matrix: new THREE3.Matrix4
});
}
_createGPUMaterial(materialFactory) {
const a_particleData = bufferAttribute2(this.particleDataAttribute);
const a_velocity = bufferAttribute2(this.velocityAttribute);
const a_angularVel = bufferAttribute2(this.angularVelAttribute);
const a_scaleData = bufferAttribute2(this.scaleDataAttribute);
const origin = vec32(a_particleData.x, a_particleData.y, a_particleData.z);
const spawnTime = a_particleData.w;
const initialVelocity = vec32(a_velocity.x, a_velocity.y, a_velocity.z);
const gravityFactor = a_velocity.w;
const angularVelocity = vec32(a_angularVel.x, a_angularVel.y, a_angularVel.z);
const lifespan = a_angularVel.w;
const initialScale = a_scaleData.x;
const scaleMin = a_scaleData.y;
const scaleMax = a_scaleData.z;
const randomSeed = a_scaleData.w;
const age = this.timeUniform.sub(spawnTime);
const normalizedAge = age.div(lifespan);
const isAlive = step2(float3(0), spawnTime).mul(step2(normalizedAge, float3(1)));
const gravity = this.gravityUniform.mul(gravityFactor);
const velocityContribution = initialVelocity.mul(age);
const gravityContribution = gravity.mul(age).mul(age).mul(float3(0.5));
const currentPosition = origin.add(velocityContribution).add(gravityContribution);
const rotationAmount = angularVelocity.mul(age);
const cosX = cos2(rotationAmount.x);
const sinX = sin2(rotationAmount.x);
const cosY = cos2(rotationAmount.y);
const sinY = sin2(rotationAmount.y);
const cosZ = cos2(rotationAmount.z);
const sinZ = sin2(rotationAmount.z);
const rotationMatrix = mat32(cosY.mul(cosZ), cosY.mul(sinZ).negate(), sinY, sinX.mul(sinY).mul(cosZ).add(cosX.mul(sinZ)), sinX.mul(sinY).mul(sinZ).negate().add(cosX.mul(cosZ)), sinX.mul(cosY).negate(), cosX.mul(sinY).mul(cosZ).negate().add(sinX.mul(sinZ)), cosX.mul(sinY).mul(sinZ).add(sinX.mul(cosZ)), cosX.mul(cosY));
const rotatedVertexPosition = rotationMatrix.mul(positionLocal2);
let currentScale = initialScale;
if (this.baseConfig.scaleOverLifeMinMax) {
const scaleMultiplier = mix3(scaleMin, scaleMax, normalizedAge);
currentScale = initialScale.mul(scaleMultiplier);
}
const scaledPosition = rotatedVertexPosition.mul(currentScale);
const finalPosition = scaledPosition.add(currentPosition);
let opacity = float3(1);
if (this.baseConfig.fadeOut) {
const fadeStart = float3(0.7);
const fadeProgress = max2(float3(0), normalizedAge.sub(fadeStart).div(float3(1).sub(fadeStart)));
opacity = float3(1).sub(fadeProgress);
}
opacity = opacity.mul(isAlive);
const frameDuration = this.animationUniform.x;
const animNumFrames = this.animationUniform.y;
const loopFlag = this.animationUniform.z;
const animFrameOffset = this.animationUniform.w;
const frameFloat = age.div(frameDuration);
const rawFrameIndex = floor(frameFloat);
const maxFrame = animNumFrames.sub(float3(1));
const clampedFrame = max2(float3(0), rawFrameIndex).min(maxFrame);
const loopedFrame = rawFrameIndex.mod(animNumFrames);
const finalLocalFrame = mix3(clampedFrame, loopedFrame, loopFlag);
const frameIndex = animFrameOffset.add(finalLocalFrame);
const uvTileWidth = float3(1).div(this.sheetNumFramesUniform);
const uvOffset = vec23(frameIndex.mul(uvTileWidth), float3(0));
const uvSize = vec23(uvTileWidth, float3(1));
const baseUV = uv3();
const finalUV = baseUV.mul(uvSize).add(uvOffset);
const mapNode = tslTexture3(this.texture);
const sampledColor = mapNode.sample(finalUV);
this.material = materialFactory();
const finalColor = vec42(sampledColor.rgb, sampledColor.a.mul(opacity));
this.material.colorNode = finalColor;
this.material.positionNode = finalPosition;
return this.material;
}
_resolveCurrentOrigin(originsArray) {
const currentOrigin = originsArray[this._currentOriginIndex];
this._currentOriginIndex = (this._currentOriginIndex + 1) % originsArray.length;
return currentOrigin;
}
getActiveParticleCount() {
return this.particleSlots.filter((slot) => slot.isActive).length;
}
_resolveSpawnRadius(spawnRadius) {
return typeof spawnRadius === "number" ? new THREE3.Vector3(spawnRadius, spawnRadius, spawnRadius) : spawnRadius;
}
_spawnParticle(effectiveParams, spawnRadiusVec) {
if (!this.instanceManager?.hasFreeIndices)
return;
const index = this.instanceManager.acquireInstanceSlot();
const particleOrigin = this._resolveCurrentOrigin(effectiveParams.origins);
const spawnOffset = new THREE3.Vector3((Math.random() - 0.5) * 2 * spawnRadiusVec.x, (Math.random() - 0.5) * 2 * spawnRadiusVec.y, (Math.random() - 0.5) * 2 * spawnRadiusVec.z);
const initialPosition = new THREE3.Vector3().copy(particleOrigin).add(spawnOffset);
const velocity = new THREE3.Vector3(THREE3.MathUtils.randFloat(effectiveParams.initialVelocityMin.x, effectiveParams.initialVelocityMax.x), THREE3.MathUtils.randFloat(effectiveParams.initialVelocityMin.y, effectiveParams.initialVelocityMax.y), THREE3.MathUtils.randFloat(effectiveParams.initialVelocityMin.z, effectiveParams.initialVelocityMax.z));
const angularVelocity = new THREE3.Vector3(THREE3.MathUtils.randFloat(effectiveParams.angularVelocityMin.x, effectiveParams.angularVelocityMax.x), THREE3.MathUtils.randFloat(effectiveParams.angularVelocityMin.y, effectiveParams.angularVelocityMax.y), THREE3.MathUtils.randFloat(effectiveParams.angularVelocityMin.z, effectiveParams.angularVelocityMax.z));
const lifespan = THREE3.MathUtils.randFloat(effectiveParams.lifetimeMsMin, effectiveParams.lifetimeMsMax) / 1000;
let gravityFactor = 1;
if (effectiveParams.randomGravityFactorMinMax) {
gravityFactor = THREE3.MathUtils.randFloat(effectiveParams.randomGravityFactorMinMax.x, effectiveParams.randomGravityFactorMinMax.y);
}
const initialScale = effectiveParams.scale ?? 1;
let scaleMin = initialScale;
let scaleMax = initialScale;
if (effectiveParams.scaleOverLifeMinMax) {
scaleMin = initialScale * effectiveParams.scaleOverLifeMinMax.x;
scaleMax = initialScale * effectiveParams.scaleOverLifeMinMax.y;
}
this.particleDataAttribute.setXYZW(index, initialPosition.x, initialPosition.y, initialPosition.z, this.currentTime);
this.velocityAttribute.setXYZW(index, velocity.x, velocity.y, velocity.z, gravityFactor);
this.angularVelAttribute.setXYZW(index, angularVelocity.x, angularVelocity.y, angularVelocity.z, lifespan);
this.scaleDataAttribute.setXYZW(index, initialScale, scaleMin, scaleMax, Math.random());
this.particleSlots[index] = {
isActive: true,
spawnTime: this.currentTime,
lifespan
};
this.particleDataAttribute.needsUpdate = true;
this.velocityAttribute.needsUpdate = true;
this.angularVelAttribute.needsUpdate = true;
this.scaleDataAttribute.needsUpdate = true;
}
async spawnParticles(count, overrides = {}) {
await this._ensureInitialized();
if (count <= 0)
return;
const finalParams = {
...this.baseConfig,
...overrides
};
const spawnRadiusVec = this._resolveSpawnRadius(finalParams.spawnRadius);
for (let i = 0;i < count; i++) {
this._spawnParticle(finalParams, spawnRadiusVec);
}
}
setAutoSpawn(ratePerSecond, autoSpawnParamOverrides = {}) {
if (ratePerSecond <= 0) {
this.stopAutoSpawn();
return;
}
const originalOverridesToStore = Object.keys(autoSpawnParamOverrides).length > 0 ? { ...autoSpawnParamOverrides } : undefined;
this.autoSpawnConfig = {
resolvedParams: { ...this.baseConfig, ...autoSpawnParamOverrides },
originalOverrides: originalOverridesToStore,
ratePerSecond,
accumulator: 0
};
}
hasAutoSpawn() {
return this.autoSpawnConfig !== null;
}
stopAutoSpawn() {
this.autoSpawnConfig = null;
}
async update(deltaTimeMs) {
await this._ensureInitialized();
this.currentTime += deltaTimeMs / 1000;
this.timeUniform.value = this.currentTime;
if (this.autoSpawnConfig) {
this.autoSpawnConfig.accumulator += deltaTimeMs;
const particlesToSpawnThisFrame = Math.floor(this.autoSpawnConfig.accumulator * (this.autoSpawnConfig.ratePerSecond / 1000));
if (particlesToSpawnThisFrame > 0) {
const spawnRadiusVec = this._resolveSpawnRadius(this.autoSpawnConfig.resolvedParams.spawnRadius);
for (let i = 0;i < particlesToSpawnThisFrame; i++) {
this._spawnParticle(this.autoSpawnConfig.resolvedParams, spawnRadiusVec);
}
this.autoSpawnConfig.accumulator -= particlesToSpawnThisFrame * 1000 / this.autoSpawnConfig.ratePerSecond;
}
}
for (let i = 0;i < this.particleSlots.length; i++) {
const slot = this.particleSlots[i];
if (slot.isActive && this.currentTime - slot.spawnTime >= slot.lifespan) {
slot.isActive = false;
this.particleDataAttribute.setW(i, -1);
this.instanceManager.releaseInstanceSlot(i);
this.particleDataAttribute.needsUpdate = true;
}
}
}
dispose() {
if (this.instanceManager) {
this.instanceManager.dispose();
this.material?.dispose();
}
this.stopAutoSpawn();
}
}
// src/3d/animation/PhysicsExplodingSpriteEffect.ts
import * as THREE4 from "three";
import { texture as tslTexture4, uv as uv4, vec2 as vec24, attribute as attribute2 } from "three/tsl";
import { MeshBasicNodeMaterial as MeshBasicNodeMaterial4 } from "three/webgpu";
var DEFAULT_PHYSICS_EXPLOSION_PARAMETERS = {
numRows: 5,
numCols: 5,
durationMs: 3000,
explosionForce: 25,
forceVariation: 0.4,
torqueStrength: 15,
gravityScale: 1,
fadeOut: true,
linearDamping: 0.8,
angularDamping: 0.5,
restitution: 0.3,
friction: 0.7,
density: 1,
materialFactory: () => new MeshBasicNodeMaterial4({
transparent: true,
alphaTest: 0.01,
depthWrite: false
})
};
class PhysicsExplodingSpriteEffect {
static materialCache = new Map;
scene;
physicsWorld;
resource;
frameUvOffset;
frameUvSize;
spriteWorldTransform;
params;
particles = [];
numParticles;
instancedMesh;
material;
uvOffsetAttribute;
isActive = true;
timeElapsedMs = 0;
particleIdCounter = 0;
constructor(scene, physicsWorld, resource, frameUvOffset, frameUvSize, spriteWorldTransform, userParams) {
this.scene = scene;
this.physicsWorld = physicsWorld;
this.resource = resource;
this.frameUvOffset = frameUvOffset;
this.frameUvSize = frameUvSize;
this.spriteWorldTransform = spriteWorldTransform;
this.params = { ...DEFAULT_PHYSICS_EXPLOSION_PARAMETERS, ...userParams };
this.numParticles = this.params.numRows * this.params.numCols;
const materialFactory = userParams?.materialFactory ?? DEFAULT_PHYSICS_EXPLOSION_PARAMETERS.materialFactory;
this._createPhysicsParticles(materialFactory);
}
_createPhysicsParticles(materialFactory) {
if (this.numParticles === 0)
return;
const particleUnitWidth = 1 / this.params.numCols;
const particleUnitHeight = 1 / this.params.numRows;
const spriteWorldCenter = new THREE4.Vector3().setFromMatrixPosition(this.spriteWorldTransform);
const spriteScale = new THREE4.Vector3().setFromMatrixScale(this.spriteWorldTransform);
const avgScale = (spriteScale.x + spriteScale.y) * 0.5;
const uvOffsetData = new Float32Array(this.numParticles * 4);
let particleIndex = 0;
for (let r = 0;r < this.params.numRows; r++) {
for (let c2 = 0;c2 < this.params.numCols; c2++) {
const localParticlePosX = (c2 + 0.5) * particleUnitWidth - 0.5;
const localParticlePosY = (r + 0.5) * particleUnitHeight - 0.5;
const initialLocalPosition = new THREE4.Vector3(localParticlePosX, localParticlePosY, 0);
const worldPosition = initialLocalPosition.clone().applyMatrix4(this.spriteWorldTransform);
const rigidBodyDesc = {
translation: { x: worldPosition.x, y: worldPosition.y },
linearDamping: this.params.linearDamping,
angularDamping: this.params.angularDamping
};
const rigidBody = this.physicsWorld.createRigidBody(rigidBodyDesc);
const particlePhysicsWidth = particleUnitWidth * avgScale * 0.8;
const particlePhysicsHeight = particleUnitHeight * avgScale * 0.8;
const colliderDesc = {
width: particlePhysicsWidth,
height: particlePhysicsHeight,
restitution: this.params.restitution,
friction: this.params.friction,
density: this.params.density
};
this.physicsWorld.createCollider(colliderDesc, rigidBody);
let explosionDir = worldPosition.clone().sub(spriteWorldCenter);
if (explosionDir.lengthSq() < 0.0001) {
explosionDir.set(Math.random() - 0.5, Math.random() - 0.5, 0);
}
explosionDir.normalize();
const forceVariationRange = this.params.forceVariation;
const minForceFactor = 1 - forceVariationRange * 0.5;
const maxForceFactor = 1 + forceVariationRange * 0.5;
const forceFactor = minForceFactor + Math.random() * (maxForceFactor - minForceFactor);
const explosionForce = this.params.explosionForce * forceFactor;
const forceVector = {
x: explosionDir.x * explosionForce,
y: explosionDir.y * explosionForce + explosionForce * 0.3
};
rigidBody.applyImpulse(forceVector);
const torque = (Math.random() - 0.5) * this.params.torqueStrength;
rigidBody.applyTorqueImpulse(torque);
const u0 = this.frameUvOffset.x + c2 / this.params.numCols * this.frameUvSize.x;
const v0 = this.frameUvOffset.y + r / this.params.numRows * this.frameUvSize.y;
const uSize = this.frameUvSize.x / this.params.numCols;
const vSize = this.frameUvSize.y / this.params.numRows;
const baseIndex = particleIndex * 4;
uvOffsetData[baseIndex] = u0;
uvOffsetData[baseIndex + 1] = v0;
uvOffsetData[baseIndex + 2] = uSize;
uvOffsetData[baseIndex + 3] = vSize;
const particleId = `explosion_particle_${this.particleIdCounter++}`;
const lifeVariation = 0.8 + Math.random() * 0.4;
const particle = {
rigidBody,
instanceIndex: particleIndex,
uvOffset: new THREE4.Vector2(u0, v0),
uvSize: new THREE4.Vector2(uSize, vSize),
initialOpacity: 1,
lifeVariation,
id: particleId
};
this.particles.push(particle);
particleIndex++;
}
}
this.uvOffsetAttribute = new THREE4.InstancedBufferAttribute(uvOffsetData, 4);
this.material = PhysicsExplodingSpriteEffect.getSharedMaterial(this.resource.texture, materialFactory);
const poolKey = `${this.params.numRows}x${this.params.numCols}`;
this.instancedMesh = this.resource.meshPool.acquireMesh(poolKey, {
geometry: () => new THREE4.PlaneGeometry(particleUnitWidth, particleUnitHeight),
material: this.material,
maxInstances: this.numParticles,
name: `PhysicsExplodingSprite_${poolKey}`
});
this.instancedMesh.geometry.setAttribute("a_uvOffset", this.uvOffsetAttribute);
this.instancedMesh.frustumCulled = false;
for (let i = 0;i < this.numParticles; i++) {
this.instancedMesh.setMatrixAt(i, this.spriteWorldTransform);
}
this.instancedMesh.instanceMatrix.needsUpdate = true;
this.scene.add(this.instancedMesh);
}
static getSharedMaterial(texture, materialFactory) {
const key = texture.uuid;
const cached = PhysicsExplodingSpriteEffect.materialCache.get(key);
if (cached)
return cached;
const a_uvOffset = attribute2("a_uvOffset", "vec4");
const uvOffset = vec24(a_uvOffset.x, a_uvOffset.y);
const uvSize = vec24(a_uvOffset.z, a_uvOffset.w);
const baseUV = uv4();
const finalUV = baseUV.mul(uvSize).add(uvOffset);
const mapNode = tslTexture4(texture);
const sampledColor = mapNode.sample(finalUV);
const material = materialFactory();
material.colorNode = sampledColor;
PhysicsExplodingSpriteEffect.materialCache.set(key, material);
return material;
}
update(deltaTimeMs) {
if (!this.isActive)
return;
this.timeElapsedMs += deltaTimeMs;
const tempMatrix = new THREE4.Matrix4;
const tempScale = new THREE4.Vector3;
this.spriteWorldTransform.decompose(new THREE4.Vector3, new THREE4.Quaternion, tempScale);
const axis = new THREE4.Vector3(0, 0, 1);
for (const particle of this.particles) {
const position = particle.rigidBody.getTranslation();
const rotation = particle.rigidBody.getRotation();
const quaternion = new THREE4.Quaternion().setFromAxisAngle(axis, rotation);
tempMatrix.compose(new THREE4.Vector3(position.x, position.y, 0), quaternion, tempScale);
this.instancedMesh.setMatrixAt(particle.instanceIndex, tempMatrix);
}
this.instancedMesh.instanceMatrix.needsUpdate = true;
if (this.timeElapsedMs >= this.params.durationMs) {
this.dispose();
}
}
dispose() {
if (!this.isActive)
return;
this.isActive = false;
if (this.instancedMesh) {
this.scene.remove(this.instancedMesh);
const poolKey = `${this.params.numRows}x${this.params.numCols}`;
this.resource.meshPool.releaseMesh(poolKey, this.instancedMesh);
}
for (const particle of this.particles) {
this.physicsWorld.removeRigidBody(particle.rigidBody);
}
this.particles = [];
}
}
class PhysicsExplosionManager {
scene;
physicsWorld;
activeExplosions = [];
constructor(scene, physicsWorld) {
this.scene = scene;
this.physicsWorld = physicsWorld;
}
fillPool(resource, count, params = {}) {
const effectParams = { ...DEFAULT_PHYSICS_EXPLOSION_PARAMETERS, ...params };
const poolKey = `${effectParams.numRows}x${effectParams.numCols}`;
const particleUnitWidth = 1 / effectParams.numCols;
const particleUnitHeight = 1 / effectParams.numRows;
const numParticles = effectParams.numRows * effectParams.numCols;
const materialFactory = params.materialFactory ?? DEFAULT_PHYSICS_EXPLOSION_PARAMETERS.materialFactory;
const material = PhysicsExplodingSpriteEffect.getSharedMaterial(resource.texture, materialFactory);
const geometry = new THREE4.PlaneGeometry(particleUnitWidth, particleUnitHeight);
resource.meshPool.fill(poolKey, {
geometry: () => geometry,
material,
maxInstances: numParticles,
name: `PhysicsExplodingSprite_${poolKey}`
}, count);
}
_createEffectCreationData(sprite) {
const animState = sprite.currentAnimation.state;
const resource = sprite.currentAnimation.getResource();
const currentAbsoluteFrame = animState.animFrameOffset + sprite.currentAnimation.currentLocalFrame;
const frameUOffset = currentAbsoluteFrame * resource.uvTileSize.x;
return {
resource,
frameUvOffset: new THREE4.Vector2(frameUOffset, 0),
frameUvSize: resource.uvTileSize.clone(),
spriteWorldTransform: sprite.getWorldTransform()
};
}
async createExplosionForSprite(spriteToExplode, userParams) {
const effectCreationData = this._createEffectCreationData(spriteToExplode);
const definition = spriteToExplode.definition;
const transform = spriteToExplode.currentTransform;
const spriteRecreationData = {
definition,
currentTransform: transform
};
spriteToExplode.destroy();
const effect = new PhysicsExplodingSpriteEffect(this.scene, this.physicsWorld, effectCreationData.resource, effectCreationData.frameUvOffset, effectCreationData.frameUvSize, effectCreationData.spriteWorldTransform, userParams);
this.activeExplosions.push(effect);
const handle = {
effect,
recreationData: spriteRecreationData,
hasBeenRestored: false,
restoreSprite: async (spriteAnimator) => {
if (handle.hasBeenRestored) {
return null;
}
handle.effect.dispose();
const newSprite = await spriteAnimator.createSprite(handle.recreationData.definition);
const currentSpriteTransform = handle.recreationData.currentTransform;
newSprite.setTransform(currentSpriteTransform.position, currentSpriteTransform.quaternion, currentSpriteTransform.scale);
handle.hasBeenRestored = true;
return newSprite;
}
};
return handle;
}
update(deltaTimeMs) {
for (let i = this.activeExplosions.length - 1;i >= 0; i--) {
const explosion = this.activeExplosions[i];
explosion.update(deltaTimeMs);
if (!explosion.isActive) {
this.activeExplosions.splice(i, 1);
}
}
}
disposeAll() {
this.activeExplosions.forEach((exp) => exp.dispose());
this.activeExplosions = [];
}
}
// src/3d/physics/RapierPhysicsAdapter.ts
import RAPIER from "@dimforge/rapier2d-simd-compat";
class RapierRigidBody {
rapierBody;
constructor(rapierBody) {
this.rapierBody = rapierBody;
}
applyImpulse(force) {
this.rapierBody.applyImpulse(force, true);
}
applyTorqueImpulse(torque) {
this.rapierBody.applyTorqueImpulse(torque, true);
}
getTranslation() {
const pos = this.rapierBody.translation();
return { x: pos.x, y: pos.y };
}
getRotation() {
return this.rapierBody.rotation();
}
get nativeBody() {
return this.rapierBody;
}
}
class RapierPhysicsWorld {
rapierWorld;
constructor(rapierWorld) {
this.rapierWorld = rapierWorld;
}
createRigidBody(desc) {
const rigidBodyDesc = RAPIER.RigidBodyDesc.dynamic().setTranslation(desc.translation.x, desc.translation.y).setLinearDamping(desc.linearDamping).setAngularDamping(desc.angularDamping);
const rapierBody = this.rapierWorld.createRigidBody(rigidBodyDesc);
return new RapierRigidBody(rapierBody);
}
createCollider(colliderDesc, rigidBody) {
const rapierColliderDesc = RAPIER.ColliderDesc.cuboid(colliderDesc.width * 0.5, colliderDesc.height * 0.5).setRestitution(colliderDesc.restitution).setFriction(colliderDesc.friction).setDensity(colliderDesc.density);
const rapierRigidBody = rigidBody.nativeBody;
this.rapierWorld.createCollider(rapierColliderDesc, rapierRigidBody);
}
removeRigidBody(rigidBody) {
const rapierRigidBody = rigidBody.nativeBody;
this.rapierWorld.removeRigidBody(rapierRigidBody);
}
static createFromRapierWorld(rapierWorld) {
return new RapierPhysicsWorld(rapierWorld);
}
}
// src/3d/physics/PlanckPhysicsAdapter.ts
import * as planck from "planck";
class PlanckRigidBody {
planckBody;
constructor(planckBody) {
this.planckBody = planckBody;
}
applyImpulse(force) {
this.planckBody.applyLinearImpulse(planck.Vec2(force.x, force.y), this.planckBody.getWorldCenter());
}
applyTorqueImpulse(torque) {
this.planckBody.applyAngularImpulse(torque);
}
getTranslation() {
const pos = this.planckBody.getPosition();
return { x: pos.x, y: pos.y };
}
getRotation() {
return this.planckBody.getAngle();
}
get nativeBody() {
return this.planckBody;
}
}
class PlanckPhysicsWorld {
planckWorld;
constructor(planckWorld) {
this.planckWorld = planckWorld;
}
createRigidBody(desc) {
const bodyDef = {
type: "dynamic",
position: planck.Vec2(desc.translation.x, desc.translation.y),
linearDamping: desc.linearDamping,
angularDamping: desc.angularDamping
};
const planckBody = this.planckWorld.createBody(bodyDef);
return new PlanckRigidBody(planckBody);
}
createCollider(colliderDesc, rigidBody) {
const shape = planck.Box(colliderDesc.width * 0.5, colliderDesc.height * 0.5);
const fixtureDef = {
shape,
density: colliderDesc.density,
friction: colliderDesc.friction,
restitution: colliderDesc.restitution
};
const planckRigidBody = rigidBody.nativeBody;
planckRigidBody.createFixture(fixtureDef);
}
removeRigidBody(rigidBody) {
const planckRigidBody = rigidBody.nativeBody;
this.planckWorld.destroyBody(planckRigidBody);
}
static createFromPlanckWorld(planckWorld) {
return new PlanckPhysicsWorld(planckWorld);
}
}
// src/3d/SpriteResourceManager.ts
import * as THREE5 from "three";
var HIDDEN_MATRIX2 = new THREE5.Matrix4().scale(new THREE5.Vector3(0, 0, 0));
class MeshPool {
pools = new Map;
acquireMesh(poolId, options) {
const poolArray = this.pools.get(poolId) ?? [];
this.pools.set(poolId, poolArray);
if (poolArray.length > 0) {
const mesh2 = poolArray.pop();
mesh2.material = options.material;
mesh2.count = options.maxInstances;
return mesh2;
}
const mesh = new THREE5.InstancedMesh(options.geometry(), options.material, options.maxInstances);
if (options.name) {
mesh.name = options.name;
}
return mesh;
}
releaseMesh(poolId, mesh) {
const poolArray = this.pools.get(poolId) ?? [];
poolArray.push(mesh);
this.pools.set(poolId, poolArray);
}
fill(poolId, options, count) {
const poolArray = this.pools.get(poolId) ?? [];
this.pools.set(poolId, poolArray);
for (let i = 0;i < count; i++) {
const mesh = new THREE5.InstancedMesh(options.geometry(), options.material, options.maxInstances);
if (options.name) {
mesh.name = `${options.name}_${i}`;
}
poolArray.push(mesh);
}
}
clearPool(poolId) {
const poolArray = this.pools.get(poolId);
if (poolArray) {
poolArray.forEach((mesh) => {
mesh.geometry.dispose();
if (Array.isArray(mesh.material)) {
mesh.material.forEach((mat) => mat.dispose());
} else {
mesh.material.dispose();
}
});
poolArray.length = 0;
}
}
clearAllPools() {
for (const poolId of this.pools.keys()) {
this.clearPool(poolId);
}
this.pools.clear();
}
}
class InstanceManager {
scene;
instancedMesh;
material;
maxInstances;
_freeIndices = [];
instanceCount = 0;
_matrix;
constructor(scene, geometry, material, options) {
this.scene = scene;
this.material = material;
this.maxInstances = options.maxInstances;
this._matrix = options.matrix ?? HIDDEN_MATRIX2;
this.instancedMesh = new THREE5.InstancedMesh(geometry, material, this.maxInstances);
this.instancedMesh.renderOrder = options.renderOrder ?? 0;
this.instancedMesh.frustumCulled = options.frustumCulled ?? false;
this.instancedMesh.instanceMatrix.setUsage(THREE5.DynamicDrawUsage);
if (options.name) {
this.instancedMesh.name = options.name;
}
for (let i = 0;i < this.maxInstances; i++) {
this._freeIndices.push(i);
this.instancedMesh.setMatrixAt(i, this._matrix);
}
this.instancedMesh.instanceMatrix.needsUpdate = true;
this.scene.add(this.instancedMesh);
}
acquireInstanceSlot() {
if (this._freeIndices.length === 0) {
throw new Error(`[InstanceManager] Max instances (${this.maxInstances}) reached. Cannot acquire slot.`);
}
const instanceIndex = this._freeIndices.pop();
this.instanceCount++;
return instanceIndex;
}
releaseInstanceSlot(instanceIndex) {
if (instanceIndex >= 0 && instanceIndex < this.maxInstances) {
this.instancedMesh.setMatrixAt(instanceIndex, this._matrix);
this.instancedMesh.instanceMatrix.needsUpdate = true;
if (!this._freeIndices.includes(instanceIndex)) {
this._freeIndices.push(instanceIndex);
this._freeIndices.sort((a, b) => a - b);
this.instanceCount--;
}
} else {
console.warn(`[InstanceManager] Attempted to release invalid instanceIndex ${instanceIndex}`);
}
}
getInstanceCount() {
return this.instanceCount;
}
getMaxInstances() {
return this.maxInstances;
}
get hasFreeIndices() {
return this._freeIndices.length > 0;
}
get mesh() {
return this.instancedMesh;
}
dispose() {
this.scene.remove(this.instancedMesh);
this.instancedMesh.geometry.dispose();
if (Array.isArray(this.material)) {
this.material.forEach((mat) => mat.dispose());
} else {
this.material.dispose();
}
}
}
class SpriteResource {
_texture;
_sheetProperties;
scene;
_meshPool;
constructor(texture, sheetProperties, scene) {
this._texture = texture;
this._sheetProperties = sheetProperties;
this.scene = scene;
this._meshPool = new MeshPool;
}
get texture() {
return this._texture;
}
get sheetProperties() {
return this._sheetProperties;
}
get meshPool() {
return this._meshPool;
}
createInstanceManager(geometry, material, options) {
const managerOptions = {
...options,
name: options.name ?? `InstancedSprites_${this._sheetProperties.imagePath.replace(/[^a-zA-Z0-9_]/g, "_")}`
};
return new InstanceManager(this.scene, geometry, material, managerOptions);
}
get uvTileSize() {
const uvTileWidth = 1 / this._sheetProperties.sheetNumFrames;
const uvTileHeight = 1;
return new THREE5.Vector2(uvTileWidth, uvTileHeight);
}
dispose() {
this._meshPool.clearAllPools();
}
}
class SpriteResourceManager {
resources = new Map;
textureCache = new Map;
scene;
constructor(scene) {
this.scene = scene;
}
getResourceKey(sheetProps) {
return sheetProps.imagePath;
}
async getOrCreateResource(texture, sheetProps) {
const resourceKey = this.getResourceKey(sheetProps);
let resource = this.resources.get(resourceKey);
if (!resource) {
resource = new SpriteResource(texture, sheetProps, this.scene);
this.resources.set(resourceKey, resource);
}
return resource;
}
async createResource(config) {
let texture = this.textureCache.get(config.imagePath);
if (!texture) {
const loadedTexture = await TextureUtils.fromFile(config.imagePath);
if (!loadedTexture) {
throw new Error(`[SpriteResourceManager] Failed to load texture for ${config.imagePath}`);
}
loadedTexture.needsUpdate = true;
texture = loadedTexture;
this.textureCache.set(config.imagePath, texture);
}
const sheetProps = {
imagePath: config.imagePath,
sheetTilesetWidth: texture.image.width,
sheetTilesetHeight: texture.image.height,
sheetNumFrames: config.sheetNumFrames
};
return await this.getOrCreateResource(texture, sheetProps);
}
clearCache() {
this.resources.clear();
this.textureCache.clear();
}
}
// src/3d.ts
import * as THREE6 from "three";
export {
TiledSprite,
ThreeRenderable,
ThreeCliRenderer,
TextureUtils,
THREE6 as THREE,
SuperSampleType,
SuperSampleAlgorithm,
SpriteUtils,
SpriteResourceManager,
SpriteResource,
SpriteParticleGenerator,
SpriteAnimator,
SheetSprite,
RapierRigidBody,
RapierPhysicsWorld,
PlanckRigidBody,
PlanckPhysicsWorld,
PhysicsExplosionManager,
PhysicsExplodingSpriteEffect,
MeshPool,
InstanceManager,
ExplosionManager,
ExplodingSpriteEffect,
DEFAULT_PHYSICS_EXPLOSION_PARAMETERS,
DEFAULT_EXPLOSION_PARAMETERS,
CLICanvas
};
//# debugId=A658FFDC4E7D1D3B64756E2164756E21
//# sourceMappingURL=3d.js.map