UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

32,779 lines • 1.01 MB
import { i as __require, o as __toESM, r as __exportAll, t as __commonJSMin } from "./chunk-DORXReHP.js";
import z$1, { z } from "zod";
import { existsSync, promises } from "fs";
import path from "path";
import fileType from "file-type/core.js";
//#region node_modules/bmp-ts/dist/esm/header-types.js
var HeaderTypes;
(function(HeaderTypes) {
	HeaderTypes[HeaderTypes["BITMAP_INFO_HEADER"] = 40] = "BITMAP_INFO_HEADER";
	HeaderTypes[HeaderTypes["BITMAP_V2_INFO_HEADER"] = 52] = "BITMAP_V2_INFO_HEADER";
	HeaderTypes[HeaderTypes["BITMAP_V3_INFO_HEADER"] = 56] = "BITMAP_V3_INFO_HEADER";
	HeaderTypes[HeaderTypes["BITMAP_V4_HEADER"] = 108] = "BITMAP_V4_HEADER";
	HeaderTypes[HeaderTypes["BITMAP_V5_HEADER"] = 124] = "BITMAP_V5_HEADER";
})(HeaderTypes || (HeaderTypes = {}));
var header_types_default = HeaderTypes;
//#endregion
//#region 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
	};
}
//#endregion
//#region node_modules/bmp-ts/dist/esm/types.js
var BmpCompression;
(function(BmpCompression) {
	BmpCompression[BmpCompression["NONE"] = 0] = "NONE";
	BmpCompression[BmpCompression["BI_RLE8"] = 1] = "BI_RLE8";
	BmpCompression[BmpCompression["BI_RLE4"] = 2] = "BI_RLE4";
	BmpCompression[BmpCompression["BI_BIT_FIELDS"] = 3] = "BI_BIT_FIELDS";
	BmpCompression[BmpCompression["BI_ALPHA_BIT_FIELDS"] = 6] = "BI_ALPHA_BIT_FIELDS";
})(BmpCompression || (BmpCompression = {}));
//#endregion
//#region node_modules/bmp-ts/dist/esm/decoder.js
var BmpDecoder = class {
	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);
						}
						if (b & true) 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++) if (processPixel.call(this, x, line) === 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;
	}
};
//#endregion
//#region 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;
}
var BmpEncoder = class {
	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 brightness = this.buffer[i++] * .2126 + g * .7152 + b * .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 color = this.buffer[i++] / 8 << 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;
	}
};
//#endregion
//#region node_modules/bmp-ts/dist/esm/index.js
function decode$1(bmpData, options) {
	return new BmpDecoder(bmpData, options);
}
function encode$1(imgData) {
	return new BmpEncoder(imgData);
}
//#endregion
//#region node_modules/tinycolor2/esm/tinycolor.js
function _typeof(obj) {
	"@babel/helpers - typeof";
	return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
		return typeof obj;
	} : function(obj) {
		return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
	}, _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) / 1e3;
	},
	getLuminance: function getLuminance() {
		var rgb = this.toRgb();
		var RsRGB = rgb.r / 255, GsRGB = rgb.g / 255, BsRGB = rgb.b / 255, R, G, B;
		if (RsRGB <= .03928) R = RsRGB / 12.92;
		else R = Math.pow((RsRGB + .055) / 1.055, 2.4);
		if (GsRGB <= .03928) G = GsRGB / 12.92;
		else G = Math.pow((GsRGB + .055) / 1.055, 2.4);
		if (BsRGB <= .03928) B = BsRGB / 12.92;
		else B = Math.pow((BsRGB + .055) / 1.055, 2.4);
		return .2126 * R + .7152 * G + .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;
		if (!formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name")) {
			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 > .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(p, q, t) {
		if (t < 0) t += 1;
		if (t > 1) t -= 1;
		if (t < 1 / 6) return p + (q - p) * 6 * t;
		if (t < 1 / 2) return q;
		if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
		return p;
	}
	if (s === 0) r = g = b = l;
	else {
		var q = l < .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) {
	return [
		pad2(convertDecimalToHex(a)),
		pad2(Math.round(r).toString(16)),
		pad2(Math.round(g).toString(16)),
		pad2(Math.round(b).toString(16))
	].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 = hsv.h, s = hsv.s, v = hsv.v;
	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;
	return tinycolor({
		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
	});
};
tinycolor.readability = function(color1, color2) {
	var c1 = tinycolor(color1);
	var c2 = tinycolor(color2);
	return (Math.max(c1.getLuminance(), c2.getLuminance()) + .05) / (Math.min(c1.getLuminance(), c2.getLuminance()) + .05);
};
tinycolor.isReadable = function(color1, color2, wcag2) {
	var readability = tinycolor.readability(color1, color2);
	var wcag2Parms, 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$1 = 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$1);
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) < 1e-6) 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_UNIT = "(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)";
	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$1[color]) {
		color = names$1[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
	};
}
//#endregion
//#region node_modules/@jimp/utils/dist/esm/index.js
function clone(image) {
	const newBitmap = {
		width: image.bitmap.width,
		height: image.bitmap.height,
		data: Buffer.from(image.bitmap.data)
	};
	return new image.constructor(newBitmap);
}
function scan(image, 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 = image.bitmap.width;
		h = image.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(image);
	for (let _y = y; _y < y + h; _y++) for (let _x = x; _x < x + w; _x++) {
		const idx = image.bitmap.width * _y + _x << 2;
		bound(_x, _y, idx);
	}
	return image;
}
function* scanIterator(image, 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 = image.bitmap.width * _y + _x << 2;
		yield {
			x: _x,
			y: _y,
			idx,
			image
		};
	}
}
/**
* A helper method that converts RGBA values to a single integer value
* @param i A single integer value representing an RGBA colour (e.g. 0xFF0000FF for red)
* @returns An object with the properties r, g, b and a representing RGBA values
* @example
* ```ts
* import { intToRGBA } from "@jimp/utils";
*
* intToRGBA(0xFF0000FF); // { r: 255, g: 0, b: 0, a:255 }
* ```
*/
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;
}
/**
* A static helper method that converts RGBA values to a single integer value
* @param r the red value (0-255)
* @param g the green value (0-255)
* @param b the blue value (0-255)
* @param a the alpha value (0-255)
* @example
* ```ts
* import { rgbaToInt } from "@jimp/utils";
*
* rgbaToInt(255, 0, 0, 255); // 0xFF0000FF
* ```
*/
function rgbaToInt(r, g, b, a) {
	if (typeof r !== "number" || typeof g !== "number" || typeof b !== "number" || typeof a !== "number") throw new Error("r, g, b and a must be numbers");
	if (r < 0 || r > 255) throw new Error("r must be between 0 and 255");
	if (g < 0 || g > 255) throw new Error("g must be between 0 and 255");
	if (b < 0 || b > 255) throw new Error("b must be between 0 and 255");
	if (a < 0 || a > 255) throw new Error("a must be between 0 and 255");
	let i = r & 255;
	i <<= 8;
	i |= g & 255;
	i <<= 8;
	i |= b & 255;
	i <<= 8;
	i |= a & 255;
	i >>>= 0;
	return i;
}
/**
* Compute color difference
* 0 means no difference, 1 means maximum difference.
* Both parameters must be an color object `{ r:val, g:val, b:val, a:val }`
* Where `a` is optional and `val` is an integer between 0 and 255.
* @param rgba1 first color to compare.
* @param rgba2 second color to compare.
* @returns float between 0 and 1.
* @example
* ```ts
* import { colorDiff } from "@jimp/utils";
*
* colorDiff(
*  { r: 255, g: 0, b: 0, a: 0 },
*  { r: 0, g: 255, b: 0, a: 0 },
* ); // 0.5
*
* colorDiff(
*  { r: 0, g: 0, b: 0, },
*  { r: 255, g: 255, b: 255, }
* ); // 0.7
* ```
*/
function colorDiff(rgba1, rgba2) {
	const sq = (n) => Math.pow(n, 2);
	const { max } = Math;
	const maxVal = 65025 * 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;
}
/**
* Limits a number to between 0 or 255
* @example
* ```ts
* import { limit255 } from "@jimp/utils";
*
* limit255(256); // 255
* limit255(-1); // 0
* ```
*/
function limit255(n) {
	n = Math.max(n, 0);
	n = Math.min(n, 255);
	return n;
}
/**
* Converts a css color (Hex, 8-digit (RGBA) Hex, RGB, RGBA, HSL, HSLA, HSV, HSVA, Named) to a hex number
* @returns A hex number representing a color
* @example
* ```ts
* import { cssColorToHex } from "@jimp/utils";
*
* cssColorToHex("rgba(255, 0, 0, 0.5)"); // "ff000080"
* ```
*/
function cssColorToHex(cssColor) {
	if (typeof cssColor === "number") return cssColor;
	return parseInt(tinycolor(cssColor).toHex8(), 16);
}
//#endregion
//#region node_modules/@jimp/js-bmp/dist/esm/index.js
function encode(image, options = {}) {
	scan({ bitmap: image }, 0, 0, image.width, image.height, function(_, __, index) {
		const red = image.data[index + 0];
		const green = image.data[index + 1];
		const blue = image.data[index + 2];
		const alpha = image.data[index + 3];
		image.data[index + 0] = alpha;
		image.data[index + 1] = blue;
		image.data[index + 2] = green;
		image.data[index + 3] = red;
	});
	return encode$1({
		...image,
		...options
	}).data;
}
function decode(data, options) {
	const result = decode$1(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,
		decode
	};
}
function bmp() {
	return {
		mime: "image/bmp",
		encode,
		decode
	};
}
//#endregion
//#region node_modules/omggif/omggif.js
var require_omggif = /* @__PURE__ */ __commonJSMin(((exports) => {
	function GifWriter(buf, width, height, gopts) {
		var p = 0;
		var gopts = gopts === void 0 ? {} : gopts;
		var loop_count = gopts.loop === void 0 ? null : gopts.loop;
		var global_palette = gopts.palette === void 0 ? null : gopts.palette;
		if (width <= 0 || height <= 0 || width > 65535 || height > 65535) throw new Error("Width/Height invalid.");
		function check_palette_and_num_colors(palette) {
			var num_colors = palette.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 !== void 0) {
				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 === void 0 ? {} : 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 palette = opts.palette;
			if (palette === void 0 || palette === null) {
				using_local_palette = false;
				palette = global_palette;
			}
			if (palette === void 0 || palette === null) throw new Error("Must supply either a local or global palette.");
			var num_colors = check_palette_and_num_colors(palette);
			var min_code_size = 0;
			while (num_colors >>= 1) ++min_code_size;
			num_colors = 1 << min_code_size;
			var delay = opts.delay === void 0 ? 0 : opts.delay;
			var disposal = opts.disposal === void 0 ? 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 !== void 0 && 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 i = 0, il = palette.length; i < il; ++i) {
				var rgb = palette[i];
				buf[p++] = rgb >> 16 & 255;
				buf[p++] = rgb >> 8 & 255;
				buf[p++] = rgb & 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 === void 0) {
				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 = 1 << (pf0 & 7) + 1;
		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 = 1 << (pf2 & 7) + 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));
		}
		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_offset = 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_offset + index * 3];
					var g = buf[palette_offset + index * 3 + 1];
					var b = buf[palette_offset + 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_offset = 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_offset + index * 3];
					var g = buf[palette_offset + index * 3 + 1];
					var b = buf[palette_offset + 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;
			if (op + chase_length + (chase_code !== code ? 1 : 0) > 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) {}
}));
//#endregion
//#region node_modules/gifwrap/src/bitmapimage.js
var require_bitmapimage = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = class BitmapImage {
		/**
		* BitmapImage is a class that hold an RGBA (red, green, blue, alpha) representation of an image. It's shape is borrowed from the Jimp package to make it easy to transfer GIF image frames into Jimp and Jimp images into GIF image frames. Each instance has a `bitmap` property having the following properties:
		* 
		* Property | Description
		* --- | ---
		* bitmap.width | width of image in pixels
		* bitmap.height | height of image in pixels
		* bitmap.data | a Buffer whose every four bytes represents a pixel, each sequential byte of a pixel corresponding to the red, green, blue, and alpha values of the pixel
		*
		* Its constructor supports the following signatures:
		*
		* * new BitmapImage(bitmap: { width: number, height: number, data: Buffer })
		* * new BitmapImage(bitmapImage: BitmapImage)
		* * new BitmapImage(width: number, height: number, buffer: Buffer)
		* * new BitmapImage(width: number, height: number, backgroundRGBA?: number)
		* 
		* When a `BitmapImage` is provided, the constructed `BitmapImage` is a deep clone of the provided one, so that each image's pixel data can subsequently be modified without affecting each other.
		*
		* `backgroundRGBA` is an optional parameter representing a pixel as a single number. In hex, the number is as follows: 0xRRGGBBAA, where RR is the red byte, GG the green byte, BB, the blue byte, and AA the alpha value. An AA of 0x00 is considered transparent, and all non-zero AA values are treated as opaque.
		*/
		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");
		}
		/**
		* Copy a square portion of this image into another image. 
		* 
		* @param {BitmapImage} toImage Image into which to copy the square
		* @param {number} toX x-coord in toImage of upper-left corner of receiving square
		* @param {number} toY y-coord in toImage of upper-left corner of receiving square
		* @param {number} fromX x-coord in this image of upper-left corner of source square
		* @param {number} fromY y-coord in this image of upper-left corner of source square
		* @return {BitmapImage} The present image to allow for chaining.
		*/
		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;
		}
		/**
		* Fills the image with a single color.
		* 
		* @param {number} rgba Color with which to fill image, expressed as a singlenumber in the form 0xRRGGBBAA, where AA is 0x00 for transparent and any other value for opaque.
		* @return {BitmapImage} The present image to allow for chaining.
		*/
		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;
		}
		/**
		* Gets the RGBA number of the pixel at the given coordinate in the form 0xRRGGBBAA, where AA is the alpha value, with alpha 0x00 encoding to transparency in GIFs.
		* 
		* @param {number} x x-coord of pixel
		* @param {number} y y-coord of pixel
		* @return {number} RGBA of pixel in 0xRRGGBBAA form
		*/
		getRGBA(x, y) {
			const bi = (y * this.bitmap.width + x) * 4;
			return this.bitmap.data.readUInt32BE(bi);
		}
		/**
		* Gets a set of all RGBA colors found within the image.
		* 
		* @return {Set} Set of all RGBA colors that the image contains.
		*/
		getRGBASet() {
			const rgbaSet = /* @__PURE__ */ new Set();
			const buf = this.bitmap.data;
			for (let bi = 0; bi < buf.length; bi += 4) rgbaSet.add(buf.readUInt32BE(bi, true));
			return rgbaSet;
		}
		/**
		* Converts the image to greyscale using inferred Adobe metrics.
		* 
		* @return {BitmapImage} The present image to allow for chaining.
		*/
		greyscale() {
			const buf = this.bitmap.data;
			this.scan(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => {
				const grey = Math.round(.299 * buf[idx] + .587 * buf[idx + 1] + .114 * buf[idx + 2]);
				buf[idx] = grey;
				buf[idx + 1] = grey;
				buf[idx + 2] = grey;
			});
			return this;
		}
		/**
		* Reframes the image as if placing a frame around the original image and replacing the original image with the newly framed image. When the new frame is strictly within the boundaries of the original image, this method crops the image. When any of the new boundaries exceed those of the original image, the `fillRGBA` must be provided to indicate the color with which to fill the extra space added to the image.
		* 
		* @param {number} xOffset The x-coord offset of the upper-left pixel of the desired image relative to the present image.
		* @param {number} yOffset The y-coord offset of the upper-left pixel of the desired image relative to the present image.
		* @param {number} width The width of the new image after reframing
		* @param {number} height The height of the new image after reframing
		* @param {number} fillRGBA The color with which to fill space added to the image as a result of the reframing, in 0xRRGGBBAA format, where AA is 0x00 to indicate transparent and a non-zero value to indicate opaque. This parameter is only required when the reframing exceeds the original boundaries (i.e. does not simply perform a crop).
		* @return {BitmapImage} The present image to allow for chaining.
		*/
		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 image;
			if (fillRGBA === void 0) {
				if (cropX !== xOffset || cropY != yOffset || cropWidth !== width || cropHeight !== height) throw new GifError(`fillRGBA required for this reframing`);
				image = new BitmapImage(width, height);
			} else image = new BitmapImage(width, height, fillRGBA);
			this.blit(image, newX, newY, cropX, cropY, cropWidth, cropHeight);
			this.bitmap = image.bitmap;
			return this;
		}
		/**
		* Scales the image size up by an integer factor. Each pixel of the original image becomes a square of the same color in the new image having a size of `factor` x `factor` pixels.
		* 
		* @param {number} factor The factor by which to scale up the image. Must be an integer >= 1.
		* @return {BitmapImage} The present image to allow for chaining.
		*/
		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;
		}
		/**
		* Scans all coordinates of the image, handing each in turn to the provided handler function.
		*
		* @param {function} scanHandler A function(x: number, y: number, bi: number) to be called for each pixel of the image with that pixel's x-coord, y-coord, and index into the `data` buffer. The function accesses the pixel at this coordinate by accessing the `this.data` at index `bi`.
		* @see scanAllIndexes
		*/
		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;
				}
			}
		}
		/**
		* Scans all pixels of the image, handing the index of each in turn to the provided handler function. Runs a bit faster than `scanAllCoords()`, should the handler not need pixel coordinates.
		*
		* @param {function} scanHandler A function(bi: number) to be called for each pixel of the image with that pixel's index into the `data` buffer. The pixels is found at index 'bi' within `this.data`.
		* @see scanAllCoords
		*/
		scanAllIndexes(scanHandler) {
			const bufferLength = this.bitmap.data.length;
			for (let bi = 0; bi < bufferLength; bi += 4) scanHandler(bi);
		}
	};
}));
//#endregion
//#region node_modules/gifwrap/src/gif.js
var require_gif = /* @__PURE__ */ __commonJSMin(((exports) => {
	/** @class Gif */
	var Gif = class {
		/**
		* Gif is a class representing an encoded GIF. It is intended to be a read-only representation of a byte-encoded GIF. Only encoders and decoders should be creating instances of this class.
		* 
		* Property | Description
		* --- | ---
		* width | width of the GIF at its widest
		* height | height of the GIF at its highest
		* loops | the number of times the GIF should loop before stopping; 0 => loop indefinitely
		* usesTransparency | boolean indicating whether at least one frame contains at least one transparent pixel
		* colorScope | the scope of the color tables as encoded within the GIF; either Gif.GlobalColorsOnly (== 1) or Gif.LocalColorsOnly (== 2).
		* frames | a array of GifFrame instances, one for each frame of the GIF
		* buffer | a Buffer holding the encoding's byte data
		* 
		* Its constructor should only ever be called by the GIF encoder or decoder.
		*
		* @param {Buffer} buffer A Buffer containing the encoded bytes
		* @param {GifFrame[]} frames Array of frames found in the encoding
		* @param {object} spec Properties of the encoding as listed above
		*/
		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 GifError */
	var GifError = class extends Error {
		/**
		* GifError is a class representing a GIF-related error
		* 
		* @param {string|Error} messageOrError
		*/
		constructor(messageOrError) {
			super(messageOrError);
			if (messageOrError instanceof Error) this.stack = "Gif" + messageOrError.stack;
		}
	};
	exports.Gif = Gif;
	exports.GifError = GifError;
}));
//#endregion
//#region node_modules/image-q/dist/cjs/image-q.cjs
var require_image_q = /* @__PURE__ */ __commonJSMin(((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 __export = (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 = {};
	__export(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 = {};
	__export(constants_exports, { bt709: () => bt709_exports });
	var bt709_exports = {};
	__export(bt709_exports, {
		Y: () => Y,
		x: () => x,
		y: () => y
	});
	var Y = /* @__PURE__ */ ((Y2) => {
		Y2[Y2["RED"] = .2126] = "RED";
		Y2[Y2["GREEN"] = .7152] = "GREEN";
		Y2[Y2["BLUE"] = .0722] = "BLUE";
		Y2[Y2["WHITE"] = 1] = "WHITE";
		return Y2;
	})(Y || {});
	var x = /* @__PURE__ */ ((x2) => {
		x2[x2["RED"] = .64] = "RED";
		x2[x2["GREEN"] = .3] = "GREEN";
		x2[x2["BLUE"] = .15] = "BLUE";
		x2[x2["WHITE"] = .3127] = "WHITE";
		return x2;
	})(x || {});
	var y = /* @__PURE__ */ ((y2) => {
		y2[y2["RED"] = .33] = "RED";
		y2[y2["GREEN"] = .6] = "GREEN";
		y2[y2["BLUE"] = .06] = "BLUE";
		y2[y2["WHITE"] = .329] = "WHITE";
		return y2;
	})(y || {});
	var conversion_exports = {};
	__export(conversion_exports, {
		lab2rgb: () => lab2rgb,
		lab2xyz: () => lab2xyz,
		rgb2hsl: () => rgb2hsl,
		rgb2lab: () => rgb2lab,
		rgb2xyz: () => rgb2xyz,
		xyz2lab: () => xyz2lab,
		xyz2rgb: () => xyz2rgb
	});
	function correctGamma(n) {
		return n > .04045 ? ((n + .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 * .4124 + g * .3576 + b * .1805,
			y: r * .2126 + g * .7152 + b * .0722,
			z: r * .0193 + g * .1192 + b * .9505
		};
	}
	var arithmetic_exports = {};
	__export(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 < .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 = .95047;
	var refY = 1;
	var refZ = 1.08883;
	function pivot(n) {
		return n > .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 = .95047;
	var refY2 = 1;
	var refZ2 = 1.08883;
	function pivot2(n) {
		return n > .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 > .0031308 ? 1.055 * n ** (1 / 2.4) - .055 : 12.92 * n;
	}
	function xyz2rgb(x2, y2, z) {
		const r = correctGamma2(x2 * 3.2406 + y2 * -1.5372 + z * -.4986);
		const g = correctGamma2(x2 * -.9689 + y2 * 1.8758 + z * .0415);
		const b = correctGamma2(x2 * .0557 + y2 * -.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 = {};
	__export(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 dC = c1 - Math.sqrt(lab2.a * lab2.a + lab2.b * lab2.b);
			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 = .048;
			this._K2 = .014;
			this._kA = .25 * 50 / 255;
		}
	};
	var CIE94GraphicArts = class extends AbstractCIE94 {
		_setDefaults() {
			this._Kl = 1;
			this._K1 = .045;
			this._K2 = .015;
			this._kA = .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 - .17 * Math.cos(ahp - _CIEDE2000._deg30InRad) + .24 * Math.cos(ahp * 2) + .32 * Math.cos(ahp * 3 + _CIEDE2000._deg6InRad) - .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 pow_a_C1_C2_to_7 = ((Math.sqrt(a1 * a1 + b1 * b1) + Math.sqrt(a2 * a2 + b2 * b2)) / 2) ** 7;
			const G = .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 + .015 * aLp_minus_50_square / Math.sqrt(20 + aLp_minus_50_square);
			const S_C = 1 + .045 * aCp;
			const S_H = 1 + .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", .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 = .2126;
			this._kG = .7152;
			this._kB = .0722;
			this._kA = 1;
		}
	};
	var EuclideanBT709NoAlpha = class extends AbstractEuclidean {
		_setDefaults() {
			this._kR = .2126;
			this._kG = .7152;
			this._kB = .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 = .4984;
			this._kG = .8625;
			this._kB = .2979;
			this._kA = 1;
		}
	};
	var ManhattanBT709 = class extends AbstractManhattan {
		_setDefaults() {
			this._kR = .2126;
			this._kG = .7152;
			this._kB = .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 = {};
	__export(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 * .2126 + g * .7152 + b * .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 clone = new PointContainer();
			clone._width = this._width;
			clone._height = this._height;
			for (let i = 0, l = this._pointArray.length; i < l; i++) clone._pointArray[i] = Point.createByUint32(this._pointArray[i].uint32 | 0);
			return clone;
		}
		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;
			canvas.getContext("2d").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 imgData = canvas.getContext("2d").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 seg = 360 / 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 distance = colorDistanceCalculator.calculateRaw(point.r, point.g, point.b, point.a, p.r, p.g, p.b, p.a);
				if (distance < minimalDistance) {
					minimalDistance = distance;
					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 hueDiff = (b.r === b.g && b.g === b.b ? 0 : 1 + hueGroup(hslB.h, hueGroups)) - 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 = {};
	__export(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 palette = new Palette();
			this._network.forEach((neuron) => {
				palette.add(neuron.toPoint());
			});
			palette.sort();
			return palette;
		}
		_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 = 1020 << networkBiasShift;
			let bestd = 2147483647;
			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 palette = new Palette();
			this._network.forEach((neuron) => {
				palette.add(neuron.toPoint());
			});
			palette.sort();
			return palette;
		}
		_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 = 1020 << networkBiasShift2;
			let bestd = 2147483647;
			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, distance) {
			__publicField(this, "index");
			__publicField(this, "color");
			__publicField(this, "distance");
			this.index = index;
			this.color = color;
			this.distance = distance;
		}
	};
	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 = .01;
			this._distanceIncrement = .005;
		}
		sample(image) {
			this._histogram.sample(image);
		}
		*quantize() {
			const idxi32 = this._histogram.getImportanceSortedColorsIDXI32();
			if (idxi32.length === 0) throw new Error("No colors in image");
			yield* this._buildPalette(idxi32);
		}
		*_buildPalette(idxi32) {
			const palette = new Palette();
			const colorArray = palette.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;
			palette.sort();
			yield {
				palette,
				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(image) {
			const pointArray = image.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 palette = 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);
				palette.add(color);
			}
			palette.sort();
			yield {
				palette,
				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];
				let bestMatch = -1;
				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 distance = this._distance.calculateRaw(foundRed, foundGreen, foundBlue, foundAlpha, color.r, color.g, color.b, color.a);
					if (distance < bestDistance) {
						bestDistance = distance;
						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);
			return volumeMoment - (volumeRed * volumeRed + volumeGreen * volumeGreen + volumeBlue * volumeBlue + volumeAlpha * volumeAlpha) / 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 = {};
	__export(image_exports, {
		AbstractImageQuantizer: () => AbstractImageQuantizer,
		ErrorDiffusionArray: () => ErrorDiffusionArray,
		ErrorDiffusionArrayKernel: () => ErrorDiffusionArrayKernel,
		ErrorDiffusionRiemersma: () => ErrorDiffusionRiemersma,
		NearestColor: () => NearestColor
	});
	var AbstractImageQuantizer = class {
		quantizeSync(pointContainer, palette) {
			for (const value of this.quantize(pointContainer, palette)) 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, palette) {
			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(palette.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, palette) {
			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 = palette.getNearestColor(this._distance, correctedPoint);
					point.from(palettePoint);
					if (this._minColorDistance) {
						if (this._distance.calculateNormalized(originalPoint, palettePoint) < 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 data = {
			width,
			height,
			level: Math.floor(Math.log(maxBound) / Math.log(2) + 1),
			callback,
			tracker: new ProgressTracker(width * height, 99),
			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, palette) {
			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 = palette.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 + .5 | 0) / errorQueueSize * errorPropagation;
				next *= multiplier;
			}
			return weights;
		}
	};
	var quality_exports = {};
	__export(quality_exports, { ssim: () => ssim });
	var K1 = .01;
	var K2 = .03;
	function ssim(image1, image2) {
		if (image1.getHeight() !== image2.getHeight() || image1.getWidth() !== image2.getWidth()) throw new Error("Images have different sizes!");
		const L = 255;
		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 ssim2 = (2 * averageLumaValue1 * averageLumaValue2 + c1) * (2 * sigxy + c2) / ((averageLumaValue1 ** 2 + averageLumaValue2 ** 2 + c1) * (sigsqx + sigsqy + c2));
			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);
			callback(lumaValues1, lumaValues2, calculateAverageLuma(lumaValues1), calculateAverageLuma(lumaValues2));
		}
	}
	function calculateLumaValuesForWindow(image, x2, y2, width, height) {
		const pointArray = image.getPointArray();
		const lumaValues = [];
		let counter = 0;
		for (let j = y2; j < y2 + height; j++) {
			const offset = j * image.getWidth();
			for (let i = x2; i < x2 + width; i++) {
				const point = pointArray[offset + i];
				lumaValues[counter] = point.r * .2126 + point.g * .7152 + point.b * .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 ? void 0 : process.nextTick) === "function" ? (callback) => process.nextTick(callback) : (callback) => setTimeout(callback, 0);
	function buildPaletteSync(images, { colorDistanceFormula, paletteQuantization, colors } = {}) {
		const paletteQuantizer = paletteQuantizationToPaletteQuantizer(colorDistanceFormulaToColorDistance(colorDistanceFormula), paletteQuantization, colors);
		images.forEach((image) => paletteQuantizer.sample(image));
		return paletteQuantizer.quantizeSync();
	}
	async function buildPalette(images, { colorDistanceFormula, paletteQuantization, colors, onProgress } = {}) {
		return new Promise((resolve, reject) => {
			const paletteQuantizer = paletteQuantizationToPaletteQuantizer(colorDistanceFormulaToColorDistance(colorDistanceFormula), paletteQuantization, colors);
			images.forEach((image) => paletteQuantizer.sample(image));
			let palette;
			const iterator = paletteQuantizer.quantize();
			const next = () => {
				try {
					const result = iterator.next();
					if (result.done) resolve(palette);
					else {
						if (result.value.palette) palette = result.value.palette;
						if (onProgress) onProgress(result.value.progress);
						setImmediateImpl(next);
					}
				} catch (error) {
					reject(error);
				}
			};
			setImmediateImpl(next);
		});
	}
	function applyPaletteSync(image, palette, { colorDistanceFormula, imageQuantization } = {}) {
		return imageQuantizationToImageQuantizer(colorDistanceFormulaToColorDistance(colorDistanceFormula), imageQuantization).quantizeSync(image, palette);
	}
	async function applyPalette(image, palette, { colorDistanceFormula, imageQuantization, onProgress } = {}) {
		return new Promise((resolve, reject) => {
			const imageQuantizer = imageQuantizationToImageQuantizer(colorDistanceFormulaToColorDistance(colorDistanceFormula), imageQuantization);
			let outPointContainer;
			const iterator = imageQuantizer.quantize(image, palette);
			const next = () => {
				try {
					const result = iterator.next();
					if (result.done) resolve(outPointContainer);
					else {
						if (result.value.pointContainer) outPointContainer = result.value.pointContainer;
						if (onProgress) onProgress(result.value.progress);
						setImmediateImpl(next);
					}
				} catch (error) {
					reject(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);
}));
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* cie94.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* ciede2000.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* cmetric.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* common.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* constants.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* ditherErrorDiffusionArray.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* euclidean.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* helper.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* hueStatistics.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* iq.ts - Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* lab2rgb.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* lab2xyz.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* manhattanNeuQuant.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* nearestColor.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* palette.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* pngQuant.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* point.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* pointContainer.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* rgb2hsl.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* rgb2lab.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* rgb2xyz.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* ssim.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* wuQuant.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* xyz2lab.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* xyz2rgb.ts - part of Image Quantization Library
*/
/**
* @preserve
* MIT License
*
* Copyright 2015-2018 Igor Bezkrovnyi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* riemersma.ts - part of Image Quantization Library
*/
/**
* @preserve TypeScript port:
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* colorHistogram.ts - part of Image Quantization Library
*/
/**
* @preserve TypeScript port:
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* neuquant.ts - part of Image Quantization Library
*/
/**
* @preserve TypeScript port:
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* rgbquant.ts - part of Image Quantization Library
*/
//#endregion
//#region node_modules/gifwrap/src/gifframe.js
var require_gifframe = /* @__PURE__ */ __commonJSMin(((exports) => {
	const BitmapImage = require_bitmapimage();
	const { GifError } = require_gif();
	/** @class GifFrame */
	var GifFrame = class GifFrame extends BitmapImage {
		/**
		* GifFrame is a class representing an image frame of a GIF. GIFs contain one or more instances of GifFrame.
		* 
		* Property | Description
		* --- | ---
		* xOffset | x-coord of position within GIF at which to render the image (defaults to 0)
		* yOffset | y-coord of position within GIF at which to render the image (defaults to 0)
		* disposalMethod | GIF disposal method; only relevant when the frames aren't all the same size (defaults to 2, disposing to background color)
		* delayCentisecs | duration of the frame in hundreths of a second
		* interlaced | boolean indicating whether the frame renders interlaced
		* 
		* Its constructor supports the following signatures:
		* 
		* * new GifFrame(bitmap: {width: number, height: number, data: Buffer}, options?)
		* * new GifFrame(bitmapImage: BitmapImage, options?)
		* * new GifFrame(width: number, height: number, buffer: Buffer, options?)
		* * new GifFrame(width: number, height: number, backgroundRGBA?: number, options?)
		* * new GifFrame(frame: GifFrame)
		* 
		* See the base class BitmapImage for a discussion of all parameters but `options` and `frame`. `options` is an optional argument providing initial values for the above-listed GifFrame properties. Each property within option is itself optional.
		* 
		* Provide a `frame` to the constructor to create a clone of the provided frame. The new frame includes a copy of the provided frame's pixel data so that each can subsequently be modified without affecting each other.
		*/
		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 !== void 0 ? options.disposalMethod : GifFrame.DisposeToBackgroundColor;
				this.delayCentisecs = options.delayCentisecs || 8;
				this.interlaced = options.interlaced || false;
			}
		}
		/**
		* Get a summary of the colors found within the frame. The return value is an object of the following form:
		* 
		* Property | Description
		* --- | ---
		* colors | An array of all the opaque colors found within the frame. Each color is given as an RGB number of the form 0xRRGGBB. The array is sorted by increasing number. Will be an empty array when the image is completely transparent.
		* usesTransparency | boolean indicating whether there are any transparent pixels within the frame. A pixel is considered transparent if its alpha value is 0x00.
		* indexCount | The number of color indexes required to represent this palette of colors. It is equal to the number of opaque colors plus one if the image includes transparency.
		* 
		* @return {object} An object representing a color palette as described above.
		*/
		getPalette() {
			const colorSet = /* @__PURE__ */ 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;
}));
//#endregion
//#region node_modules/gifwrap/src/gifutil.js
var require_gifutil = /* @__PURE__ */ __commonJSMin(((exports) => {
	/** @namespace GifUtil */
	const fs$1 = __require("fs");
	const ImageQ = require_image_q();
	const BitmapImage = require_bitmapimage();
	const { GifFrame } = require_gifframe();
	const { GifError } = require_gif();
	const { GifCodec } = require_gifcodec();
	const INVALID_SUFFIXES = [
		".jpg",
		".jpeg",
		".png",
		".bmp"
	];
	const defaultCodec = new GifCodec();
	/**
	* cloneFrames() clones provided frames. It's a utility method for cloning an entire array of frames at once.
	* 
	* @function cloneFrames
	* @memberof GifUtil
	* @param {GifFrame[]} frames An array of GifFrame instances to clone
	* @return {GifFrame[]} An array of GifFrame clones of the provided frames.
	*/
	exports.cloneFrames = function(frames) {
		let clones = [];
		frames.forEach((frame) => {
			clones.push(new GifFrame(frame));
		});
		return clones;
	};
	/**
	* getColorInfo() gets information about the colors used in the provided frames. The method is able to return an array of all colors found across all frames.
	* 
	* `maxGlobalIndex` controls whether the computation short-circuits to avoid doing work that the caller doesn't need. The method only returns `colors` and `indexCount` for the colors across all frames when the number of indexes required to store the colors and transparency in a GIF (which is the value of `indexCount`) is less than or equal to `maxGlobalIndex`. Such short-circuiting is useful when the caller just needs to determine whether any frame includes transparency.
	* 
	* @function getColorInfo
	* @memberof GifUtil
	* @param {GifFrame[]} frames Frames to examine for color and transparency.
	* @param {number} maxGlobalIndex Maximum number of color indexes (including one for transparency) allowed among the returned compilation of colors. `colors` and `indexCount` are not returned if the number of color indexes required to accommodate  all frames exceeds this number. Returns `colors` and `indexCount` by default.
	* @returns {object} Object containing at least `palettes` and `usesTransparency`. `palettes` is an array of all the palettes returned by GifFrame#getPalette(). `usesTransparency` indicates whether at least one frame uses transparency. If `maxGlobalIndex` is not exceeded, the object also contains `colors`, an array of all colors (RGB) found across all palettes, sorted by increasing value, and `indexCount` indicating the number of indexes required to store the colors and the transparency in a GIF.
	* @throws {GifError} When any frame requires more than 256 color indexes.
	*/
	exports.getColorInfo = function(frames, maxGlobalIndex) {
		let usesTransparency = false;
		const palettes = [];
		for (let i = 0; i < frames.length; ++i) {
			let palette = frames[i].getPalette();
			if (palette.usesTransparency) usesTransparency = true;
			if (palette.indexCount > 256) throw new GifError(`Frame ${i} uses more than 256 color indexes`);
			palettes.push(palette);
		}
		if (maxGlobalIndex === 0) return {
			usesTransparency,
			palettes
		};
		const globalColorSet = /* @__PURE__ */ new Set();
		palettes.forEach((palette) => {
			palette.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
		};
	};
	/**
	* copyAsJimp() returns a Jimp that contains a copy of the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the Jimp does not affect the provided bitmap image. This method serves as a macro for simplifying working with Jimp.
	*
	* @function copyAsJimp
	* @memberof GifUtil
	* @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp.
	* @param {bitmapImageToCopy} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp.
	* @return {object} An new instance of Jimp containing a copy of the image in bitmapImageToCopy.
	*/
	exports.copyAsJimp = function(jimp, bitmapImageToCopy) {
		return exports.shareAsJimp(jimp, new BitmapImage(bitmapImageToCopy));
	};
	/**
	* getMaxDimensions() returns the pixel width and height required to accommodate all of the provided frames, according to the offsets and dimensions of each frame.
	* 
	* @function getMaxDimensions
	* @memberof GifUtil
	* @param {GifFrame[]} frames Frames to measure for their aggregate maximum dimensions.
	* @return {object} An object of the form {maxWidth, maxHeight} indicating the maximum width and height required to accommodate all frames.
	*/
	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
		};
	};
	/**
	* Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Anthony Dekker.
	* 
	* The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.
	* 
	* The method may increase the number of colors if there are fewer than the provided maximum.
	* 
	* @function quantizeDekker
	* @memberof GifUtil
	* @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.
	* @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.
	* @param {object} dither (optional) An object configuring the dithering to apply. The properties are as followings, imported from the [`image-q` package](https://github.com/ibezkrovnyi/image-quantization) without explanation: { `ditherAlgorithm`: One of 'FloydSteinberg', 'FalseFloydSteinberg', 'Stucki', 'Atkinson', 'Jarvis', 'Burkes', 'Sierra', 'TwoSierra', 'SierraLite'; `minimumColorDistanceToDither`: (optional) A number defaulting to 0; `serpentine`: (optional) A boolean defaulting to true; `calculateErrorLikeGIMP`: (optional) A boolean defaulting to false. }
	*/
	exports.quantizeDekker = function(imageOrImages, maxColorIndexes, dither) {
		maxColorIndexes = maxColorIndexes || 256;
		_quantize(imageOrImages, "NeuQuantFloat", maxColorIndexes, 0, dither);
	};
	/**
	* Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Leon Sorokin. This quantization method differs from the other two by likely never increasing the number of colors, should there be fewer than the provided maximum.
	* 
	* The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.
	* 
	* @function quantizeSorokin
	* @memberof GifUtil
	* @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.
	* @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.
	* @param {string} histogram (optional) Histogram method: 'top-pop' for global top-population, 'min-pop' for minimum-population threshhold within subregions. Defaults to 'min-pop'.
	* @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`.
	*/
	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);
	};
	/**
	* Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Xiaolin Wu.
	* 
	* The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.
	* 
	* The method may increase the number of colors if there are fewer than the provided maximum.
	* 
	* @function quantizeWu
	* @memberof GifUtil
	* @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.
	* @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.
	* @param {number} significantBits (optional) This is the number of significant high bits in each RGB color channel. Takes integer values from 1 through 8. Higher values correspond to higher quality. Defaults to 5.
	* @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`.
	*/
	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);
	};
	/**
	* read() decodes an encoded GIF, whether provided as a filename or as a byte buffer.
	* 
	* @function read
	* @memberof GifUtil
	* @param {string|Buffer} source Source to decode. When a string, it's the GIF filename to load and parse. When a Buffer, it's an encoded GIF to parse.
	* @param {object} decoder An optional GIF decoder object implementing the `decode` method of class GifCodec. When provided, the method decodes the GIF using this decoder. When not provided, the method uses GifCodec.
	* @return {Promise} A Promise that resolves to an instance of the Gif class, representing the decoded GIF.
	*/
	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);
		});
	};
	/**
	* shareAsJimp() returns a Jimp that shares a bitmap with the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the image in either the Jimp or the BitmapImage affects the other objects. This method serves as a macro for simplifying working with Jimp.
	*
	* @function shareAsJimp
	* @memberof GifUtil
	* @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp.
	* @param {bitmapImageToShare} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp.
	* @return {object} An new instance of Jimp that shares the image in bitmapImageToShare.
	*/
	exports.shareAsJimp = function(jimp, bitmapImageToShare) {
		const jimpImage = new jimp(bitmapImageToShare.bitmap.width, bitmapImageToShare.bitmap.height, 0);
		jimpImage.bitmap.data = bitmapImageToShare.bitmap.data;
		return jimpImage;
	};
	/**
	* write() encodes a GIF and saves it as a file.
	* 
	* @function write
	* @memberof GifUtil
	* @param {string} path Filename to write GIF out as. Will overwrite an existing file.
	* @param {GifFrame[]} frames Array of frames to be written into GIF.
	* @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely, and `colorScope` defaults to Gif.GlobalColorsPreferred.
	* @param {object} encoder An optional GIF encoder object implementing the `encode` method of class GifCodec. When provided, the method encodes the GIF using this encoder. When not provided, the method uses GifCodec.
	* @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.
	*/
	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 === void 0) dither.serpentine = true;
			if (dither.minimumColorDistanceToDither === void 0) dither.minimumColorDistanceToDither = 0;
			if (dither.calculateErrorLikeGIMP === void 0) 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((image) => {
			const imageBuf = image.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, image.bitmap.width, image.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 outputArray = imageMaker.quantizeSync(inputContainers[i], limitedPalette).toUint32Array();
			for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) imageBuf.writeUInt32LE(outputArray[ai], bi);
		}
	}
	function _readBinary(path) {
		return new Promise((resolve, reject) => {
			fs$1.readFile(path, (err, buffer) => {
				if (err) return reject(err);
				return resolve(buffer);
			});
		});
	}
	function _writeBinary(path, buffer) {
		return new Promise((resolve, reject) => {
			fs$1.writeFile(path, buffer, (err) => {
				if (err) return reject(err);
				return resolve();
			});
		});
	}
}));
//#endregion
//#region node_modules/gifwrap/src/gifcodec.js
var require_gifcodec = /* @__PURE__ */ __commonJSMin(((exports) => {
	const Omggif = require_omggif();
	const { Gif, GifError } = require_gif();
	function GifUtil() {
		const data = require_gifutil();
		GifUtil = function() {
			return data;
		};
		return data;
	}
	const { GifFrame } = require_gifframe();
	const PER_GIF_OVERHEAD = 200;
	const PER_FRAME_OVERHEAD = 100;
	/** @class GifCodec */
	var GifCodec = class {
		/**
		* GifCodec is a class that both encodes and decodes GIFs. It implements both the `encode()` method expected of an encoder and the `decode()` method expected of a decoder, and it wraps the `omggif` GIF encoder/decoder package. GifCodec serves as this library's default encoder and decoder, but it's possible to wrap other GIF encoders and decoders for use by `gifwrap` as well. GifCodec will not encode GIFs with interlacing.
		* 
		* Instances of this class are stateless and can be shared across multiple encodings and decodings.
		* 
		* Its constructor takes one option argument:
		* 
		* @param {object} options Optionally takes an objection whose only possible property is `transparentRGB`. Images are internally represented in RGBA format, where A is the alpha value of a pixel. When `transparentRGB` is provided, this RGB value (excluding alpha) is assigned to transparent pixels, which are also given alpha value 0x00. (All opaque pixels are given alpha value 0xFF). The RGB color of transparent pixels shouldn't matter for most applications. Defaults to 0x000000.
		*/
		constructor(options = {}) {
			this._transparentRGB = null;
			if (typeof options.transparentRGB === "number" && options.transparentRGB !== 0) this._transparentRGBA = options.transparentRGB * 256;
			this._testInitialBufferSize = 0;
		}
		/**
		* Decodes a GIF from a Buffer to yield an instance of Gif. Transparent pixels of the GIF are given alpha values of 0x00, and opaque pixels are given alpha values of 0xFF. The RGB values of transparent pixels default to 0x000000 but can be overridden by the constructor's `transparentRGB` option.
		* 
		* @param {Buffer} buffer Bytes of an encoded GIF to decode.
		* @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.
		* @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs.
		*/
		decodeGif(buffer) {
			try {
				let reader;
				try {
					reader = new Omggif.GifReader(buffer);
				} catch (err) {
					throw new GifError(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);
			}
		}
		/**
		* Encodes a GIF from provided frames. Each pixel having an alpha value of 0x00 renders as transparent within the encoding, while all pixels of non-zero alpha value render as opaque.
		* 
		* @param {GifFrame[]} frames Array of frames to encode
		* @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely. Set `loop` to null to disable looping, playing only once. `colorScope` defaults to Gif.GlobalColorsPreferred.
		* @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.
		* @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs.
		*/
		encodeGif(frames, spec = {}) {
			try {
				if (frames === null || frames.length === 0) throw new GifError("there are no frames");
				const dims = GifUtil().getMaxDimensions(frames);
				spec = Object.assign({}, spec);
				spec.width = dims.maxWidth;
				spec.height = dims.maxHeight;
				if (spec.loops === void 0) 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 GifError(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;
			}
			return {
				frame: new GifFrame(info.width, info.height, buffer, {
					xOffset: info.x,
					yOffset: info.y,
					disposalMethod: info.disposal,
					interlaced: info.interlaced,
					delayCentisecs: info.delay
				}),
				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 GifError("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) return _encodeLocal(frames, spec, 2e3, localPalettes);
			return _encodeGlobal(frames, spec, 2e3, 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 palette = palettes[i];
				const pixelBitWidth = _getPixelBitWidth(palette);
				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 GifError(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 GifError(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(palette) {
		const colors = palette.colors;
		if (palette.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, palette) {
		const colors = palette.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) indexBuffer[j] = colorToIndexFunc(colors, colorBuffer.readUInt32BE(i, true) >> 8 & 16777215);
			else indexBuffer[j] = transparentIndex;
			i += 4;
			++j;
		}
		if (palette.usesTransparency) {
			if (transparentIndex === 256) throw new GifError(`Frame ${frameIndex} already has 256 colorsand so can't use transparency`);
		} else transparentIndex = null;
		return {
			buffer: indexBuffer,
			transparentIndex
		};
	}
	function _getPixelBitWidth(palette) {
		let indexCount = palette.indexCount;
		let pixelBitWidth = 0;
		--indexCount;
		while (indexCount) {
			++pixelBitWidth;
			indexCount >>= 1;
		}
		return pixelBitWidth > 0 ? pixelBitWidth : 1;
	}
	function _writeFrame(gifWriter, frameIndex, frame, palette, isLocalPalette) {
		if (frame.interlaced) throw new GifError("writing interlaced GIFs is not supported");
		const frameInfo = _getIndexedImage(frameIndex, frame, palette);
		const options = {
			delay: frame.delayCentisecs,
			disposal: frame.disposalMethod,
			transparent: frameInfo.transparentIndex
		};
		if (isLocalPalette) {
			_extendPaletteToPowerOf2(palette);
			options.palette = palette.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 GifError(err);
		}
	}
}));
//#endregion
//#region node_modules/gifwrap/src/index.js
var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const BitmapImage = require_bitmapimage();
	const { Gif, GifError } = require_gif();
	const { GifCodec } = require_gifcodec();
	const { GifFrame } = require_gifframe();
	module.exports = {
		BitmapImage,
		Gif,
		GifCodec,
		GifFrame,
		GifUtil: require_gifutil(),
		GifError
	};
}));
//#endregion
//#region node_modules/@jimp/js-gif/dist/esm/index.js
var import_omggif = /* @__PURE__ */ __toESM(require_omggif(), 1);
var import_src = require_src();
function gif() {
	return {
		mime: "image/gif",
		encode: async (bitmap) => {
			const gif = new import_src.BitmapImage(bitmap);
			import_src.GifUtil.quantizeDekker(gif, 256);
			const newFrame = new import_src.GifFrame(bitmap);
			return (await new import_src.GifCodec().encodeGif([newFrame], {})).buffer;
		},
		decode: (data) => {
			const gifObj = new import_omggif.GifReader(data);
			const gifData = Buffer.alloc(gifObj.width * gifObj.height * 4);
			gifObj.decodeAndBlitFrameRGBA(0, gifData);
			return {
				data: gifData,
				width: gifObj.width,
				height: gifObj.height
			};
		}
	};
}
//#endregion
//#region node_modules/jpeg-js/lib/encoder.js
var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	function JPEGEncoder(quality) {
		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,
				.785694958,
				.5411961,
				.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) * .707106781;
				data[dataOff + 2] = tmp13 + z1;
				data[dataOff + 6] = tmp13 - z1;
				tmp10 = tmp4 + tmp5;
				tmp11 = tmp5 + tmp6;
				tmp12 = tmp6 + tmp7;
				var z5 = (tmp10 - tmp12) * .382683433;
				var z2 = .5411961 * tmp10 + z5;
				var z4 = 1.306562965 * tmp12 + z5;
				var z3 = tmp11 * .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) * .707106781;
				data[dataOff + 16] = tmp13p2 + z1p2;
				data[dataOff + 48] = tmp13p2 - z1p2;
				tmp10p2 = tmp4p2 + tmp5p2;
				tmp11p2 = tmp5p2 + tmp6p2;
				tmp12p2 = tmp6p2 + tmp7p2;
				var z5p2 = (tmp10p2 - tmp12p2) * .382683433;
				var z2p2 = .5411961 * tmp10p2 + z5p2;
				var z4p2 = 1.306562965 * tmp12p2 + z5p2;
				var z3p2 = tmp11p2 * .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 fDCTQuant;
			for (i = 0; i < I64; ++i) {
				fDCTQuant = data[i] * fdtbl[i];
				outputfDCTQuant[i] = fDCTQuant > 0 ? fDCTQuant + .5 | 0 : fDCTQuant - .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(image, quality) {
			(/* @__PURE__ */ new Date()).getTime();
			if (quality) setQuality(quality);
			byteout = new Array();
			bytenew = 0;
			bytepos = 7;
			writeWord(65496);
			writeAPP0();
			writeCOM(image.comments);
			writeAPP1(image.exifBuffer);
			writeDQT();
			writeSOF0(image.width, image.height);
			writeDHT();
			writeSOS();
			var DCY = 0;
			var DCU = 0;
			var DCV = 0;
			bytenew = 0;
			bytepos = 7;
			this.encode.displayName = "_encode_";
			var imageData = image.data;
			var width = image.width;
			var height = image.height;
			var quadWidth = width * 4;
			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);
		};
		function setQuality(quality) {
			if (quality <= 0) quality = 1;
			if (quality > 100) quality = 100;
			if (currentQuality == quality) return;
			var sf = 0;
			if (quality < 50) sf = Math.floor(5e3 / quality);
			else sf = Math.floor(200 - quality * 2);
			initQuantTables(sf);
			currentQuality = quality;
		}
		function init() {
			var time_start = (/* @__PURE__ */ new Date()).getTime();
			if (!quality) quality = 50;
			initCharLookupTable();
			initHuffmanTbl();
			initCategoryNumber();
			initRGBYUVTable();
			setQuality(quality);
			(/* @__PURE__ */ new Date()).getTime() - time_start;
		}
		init();
	}
	if (typeof module !== "undefined") module.exports = encode;
	else if (typeof window !== "undefined") {
		window["jpeg-js"] = window["jpeg-js"] || {};
		window["jpeg-js"].encode = encode;
	}
	function encode(imgData, qu) {
		if (typeof qu === "undefined") qu = 50;
		return {
			data: new JPEGEncoder(qu).encode(imgData, qu),
			width: imgData.width,
			height: imgData.height
		};
	}
}));
//#endregion
//#region node_modules/jpeg-js/lib/decoder.js
var require_decoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var JpegImage = (function jpegImage() {
		"use strict";
		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) {
			frame.precision;
			frame.samplesPerLine;
			frame.scanLines;
			var mcusPerLine = frame.mcusPerLine;
			var progressive = frame.progressive;
			frame.maxH;
			frame.maxV;
			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 n = 0;
				while (length > 0) {
					var bit = readBit();
					if (bit === null) return;
					n = n << 1 | bit;
					length--;
				}
				return n;
			}
			function receiveAndExtend(length) {
				var n = receive(length);
				if (n >= 1 << length - 1) return n;
				return n + (-1 << length) + 1;
			}
			function decodeBaseline(component, zz) {
				var t = decodeHuffman(component.huffmanTableDC);
				var diff = t === 0 ? 0 : receiveAndExtend(t);
				zz[0] = component.pred += diff;
				var k = 1;
				while (k < 64) {
					var rs = decodeHuffman(component.huffmanTableAC);
					var s = rs & 15, r = rs >> 4;
					if (s === 0) {
						if (r < 15) break;
						k += 16;
						continue;
					}
					k += r;
					var z = dctZigZag[k];
					zz[z] = receiveAndExtend(s);
					k++;
				}
			}
			function decodeDCFirst(component, zz) {
				var t = decodeHuffman(component.huffmanTableDC);
				var diff = t === 0 ? 0 : receiveAndExtend(t) << successive;
				zz[0] = component.pred += diff;
			}
			function decodeDCSuccessive(component, zz) {
				zz[0] |= readBit() << successive;
			}
			var eobrun = 0;
			function decodeACFirst(component, zz) {
				if (eobrun > 0) {
					eobrun--;
					return;
				}
				var k = spectralStart, e = spectralEnd;
				while (k <= e) {
					var rs = decodeHuffman(component.huffmanTableAC);
					var s = rs & 15, r = rs >> 4;
					if (s === 0) {
						if (r < 15) {
							eobrun = receive(r) + (1 << r) - 1;
							break;
						}
						k += 16;
						continue;
					}
					k += r;
					var z = dctZigZag[k];
					zz[z] = receiveAndExtend(s) * (1 << successive);
					k++;
				}
			}
			var successiveACState = 0, successiveACNextValue;
			function decodeACSuccessive(component, zz) {
				var k = spectralStart, e = spectralEnd, r = 0;
				while (k <= e) {
					var z = dctZigZag[k];
					var direction = zz[z] < 0 ? -1 : 1;
					switch (successiveACState) {
						case 0:
							var rs = decodeHuffman(component.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;
					}
					k++;
				}
				if (successiveACState === 4) {
					eobrun--;
					if (eobrun === 0) successiveACState = 0;
				}
			}
			function decodeMcu(component, decode, mcu, row, col) {
				var mcuRow = mcu / mcusPerLine | 0;
				var mcuCol = mcu % mcusPerLine;
				var blockRow = mcuRow * component.v + row;
				var blockCol = mcuCol * component.h + col;
				if (component.blocks[blockRow] === void 0 && opts.tolerantDecoding) return;
				decode(component, component.blocks[blockRow][blockCol]);
			}
			function decodeBlock(component, decode, mcu) {
				var blockRow = mcu / component.blocksPerLine | 0;
				var blockCol = mcu % component.blocksPerLine;
				if (component.blocks[blockRow] === void 0 && opts.tolerantDecoding) return;
				decode(component, component.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 i;
				for (i = 0; i < 64; i++) p[i] = zz[i] * qt[i];
				for (i = 0; i < 8; ++i) {
					var row = 8 * i;
					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 (i = 0; i < 8; ++i) {
					var col = i;
					if (p[8 + col] == 0 && p[16 + col] == 0 && p[24 + col] == 0 && p[32 + col] == 0 && p[40 + col] == 0 && p[48 + col] == 0 && p[56 + col] == 0) {
						t = dctSqrt2 * dataIn[i + 0] + 8192 >> 14;
						p[0 + col] = t;
						p[8 + col] = t;
						p[16 + col] = t;
						p[24 + col] = t;
						p[32 + col] = t;
						p[40 + col] = t;
						p[48 + col] = t;
						p[56 + col] = t;
						continue;
					}
					v0 = dctSqrt2 * p[0 + col] + 2048 >> 12;
					v1 = dctSqrt2 * p[32 + col] + 2048 >> 12;
					v2 = p[16 + col];
					v3 = p[48 + col];
					v4 = dctSqrt1d2 * (p[8 + col] - p[56 + col]) + 2048 >> 12;
					v7 = dctSqrt1d2 * (p[8 + col] + p[56 + col]) + 2048 >> 12;
					v5 = p[24 + col];
					v6 = p[40 + 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 + col] = v0 + v7;
					p[56 + col] = v0 - v7;
					p[8 + col] = v1 + v6;
					p[48 + col] = v1 - v6;
					p[16 + col] = v2 + v5;
					p[40 + col] = v2 - v5;
					p[24 + col] = v3 + v4;
					p[32 + col] = v3 - v4;
				}
				for (i = 0; i < 64; ++i) {
					var sample = 128 + (p[i] + 8 >> 4);
					dataOut[i] = sample < 0 ? 0 : sample > 255 ? 255 : sample;
				}
			}
			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 * 1e3 * 1e3, offset = 0;
				data.length;
				function readUint16() {
					var value = data[offset] << 8 | data[offset + 1];
					offset += 2;
					return value;
				}
				function readDataBlock() {
					var length = readUint16();
					var array = data.subarray(offset, offset + length - 2);
					offset += array.length;
					return array;
				}
				function prepareComponents(frame) {
					var maxH = 1, maxV = 1;
					var component, componentId;
					for (componentId in frame.components) if (frame.components.hasOwnProperty(componentId)) {
						component = frame.components[componentId];
						if (maxH < component.h) maxH = component.h;
						if (maxV < component.v) maxV = component.v;
					}
					var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
					var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
					for (componentId in frame.components) if (frame.components.hasOwnProperty(componentId)) {
						component = frame.components[componentId];
						var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
						var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
						var blocksPerLineForMcu = mcusPerLine * component.h;
						var blocksPerColumnForMcu = mcusPerColumn * component.v;
						var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;
						var blocks = [];
						requestMemoryAllocation(blocksToAllocate * 256);
						for (var i = 0; i < blocksPerColumnForMcu; i++) {
							var row = [];
							for (var j = 0; j < blocksPerLineForMcu; j++) row.push(new Int32Array(64));
							blocks.push(row);
						}
						component.blocksPerLine = blocksPerLine;
						component.blocksPerColumn = blocksPerColumn;
						component.blocks = blocks;
					}
					frame.maxH = maxH;
					frame.maxV = maxV;
					frame.mcusPerLine = mcusPerLine;
					frame.mcusPerColumn = mcusPerColumn;
				}
				var jfif = null;
				var adobe = 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;
					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 quantizationTablesEnd = readUint16() + offset - 2;
							while (offset < quantizationTablesEnd) {
								var quantizationTableSpec = data[offset++];
								requestMemoryAllocation(256);
								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;
							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:
							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 - .3441363 * (Cb - 128) - .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 - .3441363 * (Cb - 128) - .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 = imageData.width, height = imageData.height;
				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 = decode;
	else if (typeof window !== "undefined") {
		window["jpeg-js"] = window["jpeg-js"] || {};
		window["jpeg-js"].decode = decode;
	}
	function decode(jpegData, userOpts = {}) {
		var opts = {
			colorTransform: void 0,
			useTArray: false,
			formatAsRGBA: true,
			tolerantDecoding: true,
			maxResolutionInMP: 100,
			maxMemoryUsageInMB: 512,
			...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 image = {
				width: decoder.width,
				height: decoder.height,
				exifBuffer: decoder.exifBuffer,
				data: opts.useTArray ? new Uint8Array(bytesNeeded) : Buffer.alloc(bytesNeeded)
			};
			if (decoder.comments.length > 0) image["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(image, opts.formatAsRGBA);
		return image;
	}
}));
//#endregion
//#region node_modules/@jimp/js-jpeg/dist/esm/index.js
var import_jpeg_js = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = {
		encode: require_encoder(),
		decode: require_decoder()
	};
})))(), 1);
function jpeg() {
	return {
		mime: "image/jpeg",
		encode: (bitmap, { quality = 100 } = {}) => import_jpeg_js.default.encode(bitmap, quality).data,
		decode: (data, options) => import_jpeg_js.default.decode(data, options)
	};
}
//#endregion
//#region node_modules/pngjs/lib/chunkstream.js
var require_chunkstream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let util$5 = __require("util");
	let Stream$2 = __require("stream");
	let ChunkStream = module.exports = function() {
		Stream$2.call(this);
		this._buffers = [];
		this._buffered = 0;
		this._reads = [];
		this._paused = false;
		this._encoding = "utf8";
		this.writable = true;
	};
	util$5.inherits(ChunkStream, Stream$2);
	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", /* @__PURE__ */ 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", /* @__PURE__ */ 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);
		}
	};
}));
//#endregion
//#region node_modules/pngjs/lib/interlace.js
var require_interlace = /* @__PURE__ */ __commonJSMin(((exports) => {
	let 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;
		};
	};
}));
//#endregion
//#region node_modules/pngjs/lib/paeth-predictor.js
var require_paeth_predictor = /* @__PURE__ */ __commonJSMin(((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;
	};
}));
//#endregion
//#region node_modules/pngjs/lib/filter-parse.js
var require_filter_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let interlaceUtils = require_interlace();
	let paethPredictor = require_paeth_predictor();
	function getByteWidth(width, bpp, depth) {
		let byteWidth = width * bpp;
		if (depth !== 8) byteWidth = Math.ceil(byteWidth / (8 / depth));
		return byteWidth;
	}
	let 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++) unfilteredLine[x] = rawData[1 + x] + (x > xBiggerThan ? unfilteredLine[x - xComparison] : 0);
	};
	Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
		let lastLine = this._lastLine;
		for (let x = 0; x < byteWidth; x++) unfilteredLine[x] = rawData[1 + x] + (lastLine ? lastLine[x] : 0);
	};
	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;
			unfilteredLine[x] = rawByte + Math.floor((f3Left + f3Up) / 2);
		}
	};
	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;
			unfilteredLine[x] = rawByte + paethPredictor(x > xBiggerThan ? unfilteredLine[x - xComparison] : 0, f4Up, x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0);
		}
	};
	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();
		}
	};
}));
//#endregion
//#region node_modules/pngjs/lib/filter-parse-async.js
var require_filter_parse_async = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let util$4 = __require("util");
	let ChunkStream = require_chunkstream();
	let Filter = require_filter_parse();
	let 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$4.inherits(FilterAsync, ChunkStream);
}));
//#endregion
//#region node_modules/pngjs/lib/constants.js
var require_constants$1 = /* @__PURE__ */ __commonJSMin(((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
	};
}));
//#endregion
//#region node_modules/pngjs/lib/crc.js
var require_crc = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let 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;
		}
	})();
	let 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;
	};
}));
//#endregion
//#region node_modules/pngjs/lib/parser.js
var require_parser$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let constants = require_constants$1();
	let CrcCalculator = require_crc();
	let 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[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
		this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
		this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
		this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
		this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
		this._chunks[constants.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(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this));
	};
	Parser.prototype._parseSignature = function(data) {
		let signature = constants.PNG_SIGNATURE;
		for (let i = 0; i < signature.length; i++) if (data[i] !== signature[i]) {
			this.error(/* @__PURE__ */ 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 !== constants.TYPE_IHDR) {
			this.error(/* @__PURE__ */ 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(/* @__PURE__ */ 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(/* @__PURE__ */ 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(/* @__PURE__ */ new Error("Unsupported bit depth " + depth));
			return;
		}
		if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
			this.error(/* @__PURE__ */ new Error("Unsupported color type"));
			return;
		}
		if (compr !== 0) {
			this.error(/* @__PURE__ */ new Error("Unsupported compression method"));
			return;
		}
		if (filter !== 0) {
			this.error(/* @__PURE__ */ new Error("Unsupported filter method"));
			return;
		}
		if (interlace !== 0 && interlace !== 1) {
			this.error(/* @__PURE__ */ new Error("Unsupported interlace method"));
			return;
		}
		this._colorType = colorType;
		let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
		this._hasIHDR = true;
		this.metadata({
			width,
			height,
			depth,
			interlace: Boolean(interlace),
			palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
			color: Boolean(colorType & constants.COLORTYPE_COLOR),
			alpha: Boolean(colorType & constants.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 === constants.COLORTYPE_PALETTE_COLOR) {
			if (this._palette.length === 0) {
				this.error(/* @__PURE__ */ new Error("Transparency chunk must be after palette"));
				return;
			}
			if (data.length > this._palette.length) {
				this.error(/* @__PURE__ */ 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 === constants.COLORTYPE_GRAYSCALE) this.transColor([data.readUInt16BE(0)]);
		if (this._colorType === constants.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) / constants.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 === constants.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();
	};
}));
//#endregion
//#region node_modules/pngjs/lib/bitmapper.js
var require_bitmapper = /* @__PURE__ */ __commonJSMin(((exports) => {
	let interlaceUtils = require_interlace();
	let 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];
		}
	];
	let 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(image, pxData, getPxPos, bpp, data, rawPos) {
		let imageWidth = image.width;
		let imageHeight = image.height;
		let imagePass = image.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(image, pxData, getPxPos, bpp, bits, maxBit) {
		let imageWidth = image.width;
		let imageHeight = image.height;
		let imagePass = image.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;
	};
}));
//#endregion
//#region node_modules/pngjs/lib/format-normaliser.js
var require_format_normaliser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	function dePalette(indata, outdata, width, height, palette) {
		let pxPos = 0;
		for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
			let color = palette[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 + .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 palette = imageData.palette;
		let outdata = indata;
		if (colorType === 3) dePalette(indata, outdata, width, height, palette);
		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;
	};
}));
//#endregion
//#region node_modules/pngjs/lib/parser-async.js
var require_parser_async = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let util$3 = __require("util");
	let zlib$4 = __require("zlib");
	let ChunkStream = require_chunkstream();
	let FilterAsync = require_filter_parse_async();
	let Parser = require_parser$2();
	let bitmapper = require_bitmapper();
	let formatNormaliser = require_format_normaliser();
	let 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$3.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$4.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 imageSize = ((this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7 >> 3) + 1) * this._bitmapInfo.height;
			let chunkSize = Math.max(imageSize, zlib$4.Z_MIN_CHUNK);
			this._inflate = zlib$4.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(palette) {
		this._bitmapInfo.palette = palette;
	};
	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);
	};
}));
//#endregion
//#region node_modules/pngjs/lib/bitpacker.js
var require_bitpacker = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let constants = require_constants$1();
	module.exports = function(dataIn, width, height, options) {
		let outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(options.colorType) !== -1;
		if (options.colorType === options.inputColorType) {
			let bigEndian = (function() {
				let buffer = /* @__PURE__ */ 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 = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
		if (inBpp === 4 && !options.inputHasAlpha) inBpp = 3;
		let outBpp = constants.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 === void 0) bgColor.red = maxValue;
		if (bgColor.green === void 0) bgColor.green = maxValue;
		if (bgColor.blue === void 0) bgColor.blue = maxValue;
		function getRGBA() {
			let red;
			let green;
			let blue;
			let alpha = maxValue;
			switch (options.inputColorType) {
				case constants.COLORTYPE_COLOR_ALPHA:
					alpha = data[inIndex + 3];
					red = data[inIndex];
					green = data[inIndex + 1];
					blue = data[inIndex + 2];
					break;
				case constants.COLORTYPE_COLOR:
					red = data[inIndex];
					green = data[inIndex + 1];
					blue = data[inIndex + 2];
					break;
				case constants.COLORTYPE_ALPHA:
					alpha = data[inIndex + 1];
					red = data[inIndex];
					green = red;
					blue = red;
					break;
				case constants.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 constants.COLORTYPE_COLOR_ALPHA:
				case constants.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 constants.COLORTYPE_ALPHA:
				case constants.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;
	};
}));
//#endregion
//#region node_modules/pngjs/lib/filter-pack.js
var require_filter_pack = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let 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;
	}
	let filters = {
		0: filterNone,
		1: filterSub,
		2: filterUp,
		3: filterAvg,
		4: filterPaeth
	};
	let 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;
	};
}));
//#endregion
//#region node_modules/pngjs/lib/packer.js
var require_packer = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let constants = require_constants$1();
	let CrcStream = require_crc();
	let bitPacker = require_bitpacker();
	let filter = require_filter_pack();
	let zlib$3 = __require("zlib");
	let 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$3.createDeflate;
		options.bitDepth = options.bitDepth || 8;
		options.colorType = typeof options.colorType === "number" ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
		options.inputColorType = typeof options.inputColorType === "number" ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
		if ([
			constants.COLORTYPE_GRAYSCALE,
			constants.COLORTYPE_COLOR,
			constants.COLORTYPE_COLOR_ALPHA,
			constants.COLORTYPE_ALPHA
		].indexOf(options.colorType) === -1) throw new Error("option color type:" + options.colorType + " is not supported at present");
		if ([
			constants.COLORTYPE_GRAYSCALE,
			constants.COLORTYPE_COLOR,
			constants.COLORTYPE_COLOR_ALPHA,
			constants.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 = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
		return filter(packedData, width, height, this._options, bpp);
	};
	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 * constants.GAMMA_DIVISION), 0);
		return this._packChunk(constants.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(constants.TYPE_IHDR, buf);
	};
	Packer.prototype.packIDAT = function(data) {
		return this._packChunk(constants.TYPE_IDAT, data);
	};
	Packer.prototype.packIEND = function() {
		return this._packChunk(constants.TYPE_IEND, null);
	};
}));
//#endregion
//#region node_modules/pngjs/lib/packer-async.js
var require_packer_async = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let util$2 = __require("util");
	let Stream$1 = __require("stream");
	let constants = require_constants$1();
	let Packer = require_packer();
	let PackerAsync = module.exports = function(opt) {
		Stream$1.call(this);
		this._packer = new Packer(opt || {});
		this._deflate = this._packer.createDeflate();
		this.readable = true;
	};
	util$2.inherits(PackerAsync, Stream$1);
	PackerAsync.prototype.pack = function(data, width, height, gamma) {
		this.emit("data", Buffer.from(constants.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);
	};
}));
//#endregion
//#region node_modules/pngjs/lib/sync-inflate.js
var require_sync_inflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let assert = __require("assert").ok;
	let zlib$2 = __require("zlib");
	let util$1 = __require("util");
	let kMaxLength = __require("buffer").kMaxLength;
	function Inflate(opts) {
		if (!(this instanceof Inflate)) return new Inflate(opts);
		if (opts && opts.chunkSize < zlib$2.Z_MIN_CHUNK) opts.chunkSize = zlib$2.Z_MIN_CHUNK;
		zlib$2.Inflate.call(this, opts);
		this._offset = this._offset === void 0 ? 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$2.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
		let self = 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 (self._hadError) return;
			let have = availOutBefore - availOutAfter;
			assert(have >= 0, "have should not go down");
			if (have > 0) {
				let out = self._buffer.slice(self._offset, self._offset + have);
				self._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 || self._offset >= self._chunkSize) {
				availOutBefore = self._chunkSize;
				self._offset = 0;
				self._buffer = Buffer.allocUnsafe(self._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$1.inherits(Inflate, zlib$2.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$2.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;
}));
//#endregion
//#region node_modules/pngjs/lib/sync-reader.js
var require_sync_reader = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let 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");
	};
}));
//#endregion
//#region node_modules/pngjs/lib/filter-parse-sync.js
var require_filter_parse_sync = /* @__PURE__ */ __commonJSMin(((exports) => {
	let SyncReader = require_sync_reader();
	let Filter = require_filter_parse();
	exports.process = function(inBuffer, bitmapInfo) {
		let outBuffers = [];
		let reader = new SyncReader(inBuffer);
		new Filter(bitmapInfo, {
			read: reader.read.bind(reader),
			write: function(bufferPart) {
				outBuffers.push(bufferPart);
			},
			complete: function() {}
		}).start();
		reader.process();
		return Buffer.concat(outBuffers);
	};
}));
//#endregion
//#region node_modules/pngjs/lib/parser-sync.js
var require_parser_sync = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let hasSyncZlib = true;
	let zlib$1 = __require("zlib");
	let inflateSync = require_sync_inflate();
	if (!zlib$1.deflateSync) hasSyncZlib = false;
	let SyncReader = require_sync_reader();
	let FilterSync = require_filter_parse_sync();
	let Parser = require_parser$2();
	let bitmapper = require_bitmapper();
	let 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(palette) {
			metaData.palette = palette;
		}
		function handleSimpleTransparency() {
			metaData.alpha = true;
		}
		let gamma;
		function handleGamma(_gamma_) {
			gamma = _gamma_;
		}
		let inflateDataList = [];
		function handleInflateData(inflatedData) {
			inflateDataList.push(inflatedData);
		}
		let reader = new SyncReader(buffer);
		new Parser(options, {
			read: reader.read.bind(reader),
			error: handleError,
			metadata: handleMetaData,
			gamma: handleGamma,
			palette: handlePalette,
			transColor: handleTransColor,
			inflateData: handleInflateData,
			simpleTransparency: handleSimpleTransparency
		}).start();
		reader.process();
		if (err) throw err;
		let inflateData = Buffer.concat(inflateDataList);
		inflateDataList.length = 0;
		let inflatedData;
		if (metaData.interlace) inflatedData = zlib$1.inflateSync(inflateData);
		else {
			let imageSize = ((metaData.width * metaData.bpp * metaData.depth + 7 >> 3) + 1) * 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;
	};
}));
//#endregion
//#region node_modules/pngjs/lib/packer-sync.js
var require_packer_sync = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	let hasSyncZlib = true;
	let zlib = __require("zlib");
	if (!zlib.deflateSync) hasSyncZlib = false;
	let constants = require_constants$1();
	let 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 packer = new Packer(opt || {});
		let chunks = [];
		chunks.push(Buffer.from(constants.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);
	};
}));
//#endregion
//#region node_modules/pngjs/lib/png-sync.js
var require_png_sync = /* @__PURE__ */ __commonJSMin(((exports) => {
	let parse = require_parser_sync();
	let pack = require_packer_sync();
	exports.read = function(buffer, options) {
		return parse(buffer, options || {});
	};
	exports.write = function(png, options) {
		return pack(png, options);
	};
}));
//#endregion
//#region node_modules/@jimp/js-png/dist/esm/constants.js
var import_png = (/* @__PURE__ */ __commonJSMin(((exports) => {
	let util = __require("util");
	let Stream = __require("stream");
	let Parser = require_parser_async();
	let Packer = require_packer_async();
	let PNGSync = require_png_sync();
	let 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);
	};
})))();
/**
* Filter method is a single-byte integer that indicates the preprocessing method applied to the image data before compression.
*/
var PNGFilterType;
(function(PNGFilterType) {
	PNGFilterType[PNGFilterType["AUTO"] = -1] = "AUTO";
	/** scanline is transmitted unmodified */
	PNGFilterType[PNGFilterType["NONE"] = 0] = "NONE";
	/** filter transmits the difference between each byte and the value of the corresponding byte of the prior pixel */
	PNGFilterType[PNGFilterType["SUB"] = 1] = "SUB";
	/** The Up() filter is just like the Sub() filter except that the pixel immediately above the current pixel, rather than just to its left, is used as the predictor. */
	PNGFilterType[PNGFilterType["UP"] = 2] = "UP";
	/** uses the average of the two neighboring pixels (left and above) to predict the value of a pixel */
	PNGFilterType[PNGFilterType["AVERAGE"] = 3] = "AVERAGE";
	/** computes a simple linear function of the three neighboring pixels (left, above, upper left), then chooses as predictor the neighboring pixel closest to the computed value. */
	PNGFilterType[PNGFilterType["PATH"] = 4] = "PATH";
})(PNGFilterType || (PNGFilterType = {}));
/**
* Color type is a single-byte integer that describes the interpretation of the image data.
* Color type codes represent sums of the following values:
*
* 1 (palette used), 2 (color used), and 4 (alpha channel used).
*/
var PNGColorType;
(function(PNGColorType) {
	PNGColorType[PNGColorType["GRAYSCALE"] = 0] = "GRAYSCALE";
	PNGColorType[PNGColorType["COLOR"] = 2] = "COLOR";
	PNGColorType[PNGColorType["GRAYSCALE_ALPHA"] = 4] = "GRAYSCALE_ALPHA";
	PNGColorType[PNGColorType["COLOR_ALPHA"] = 6] = "COLOR_ALPHA";
})(PNGColorType || (PNGColorType = {}));
//#endregion
//#region 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 png = new import_png.PNG({
				width: bitmap.width,
				height: bitmap.height
			});
			png.data = bitmap.data;
			return import_png.PNG.sync.write(png, {
				...options,
				deflateLevel,
				deflateStrategy,
				filterType,
				colorType: typeof colorType !== "undefined" ? colorType : inputHasAlpha ? PNGColorType.COLOR_ALPHA : PNGColorType.COLOR,
				inputHasAlpha
			});
		},
		decode: (data, options) => {
			const result = import_png.PNG.sync.read(data, options);
			return {
				data: result.data,
				width: result.width,
				height: result.height
			};
		}
	};
}
//#endregion
//#region node_modules/pako/lib/utils/common.js
var require_common = /* @__PURE__ */ __commonJSMin(((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 = 0, pos, chunk, result;
			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);
}));
//#endregion
//#region node_modules/pako/lib/zlib/trees.js
var require_trees = /* @__PURE__ */ __commonJSMin(((exports) => {
	var utils = 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);
		}
		utils.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 {
			/*** pqremove ***/
			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[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[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[18] !== 0 || s.dyn_ltree[20] !== 0 || s.dyn_ltree[26] !== 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;
}));
//#endregion
//#region node_modules/pako/lib/zlib/adler32.js
var require_adler32 = /* @__PURE__ */ __commonJSMin(((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 > 2e3 ? 2e3 : 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;
}));
//#endregion
//#region node_modules/pako/lib/zlib/crc32.js
var require_crc32 = /* @__PURE__ */ __commonJSMin(((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;
}));
//#endregion
//#region node_modules/pako/lib/zlib/messages.js
var require_messages = /* @__PURE__ */ __commonJSMin(((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"
	};
}));
//#endregion
//#region node_modules/pako/lib/zlib/deflate.js
var require_deflate$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	var utils = 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 L_CODES = 286;
	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;
		utils.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;
		utils.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 scan = 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[scan + best_len - 1];
		var scan_end = _win[scan + 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[scan] || _win[++match] !== _win[scan + 1]) continue;
			scan += 2;
			match++;
			do			;
while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend);
			len = MAX_MATCH - (strend - scan);
			scan = strend - MAX_MATCH;
			if (len > best_len) {
				s.match_start = cur_match;
				best_len = len;
				if (len >= nice_match) break;
				scan_end1 = _win[scan + best_len - 1];
				scan_end = _win[scan + 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)) {
				utils.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(s, 0); ***/
				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(s, 0); ***/
				flush_block_only(s, false);
				if (s.strm.avail_out === 0) return BS_NEED_MORE;
			}
		}
		s.insert = 0;
		if (flush === Z_FINISH) {
			/*** FLUSH_BLOCK(s, 1); ***/
			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(s, 0); ***/
			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) {
				/*** INSERT_STRING(s, s.strstart, hash_head); ***/
				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) {
				/*** _tr_tally_dist(s, s.strstart - s.match_start,
				s.match_length - MIN_MATCH, bflush); ***/
				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++;
						/*** INSERT_STRING(s, s.strstart, hash_head); ***/
						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 {
				/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
				bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
				s.lookahead--;
				s.strstart++;
			}
			if (bflush) {
				/*** FLUSH_BLOCK(s, 0); ***/
				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(s, 1); ***/
			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(s, 0); ***/
			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) {
				/*** INSERT_STRING(s, s.strstart, hash_head); ***/
				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;
				/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
				s.prev_length - MIN_MATCH, bflush);***/
				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) {
						/*** INSERT_STRING(s, s.strstart, hash_head); ***/
						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(s, 0); ***/
					flush_block_only(s, false);
					if (s.strm.avail_out === 0) return BS_NEED_MORE;
				}
			} else if (s.match_available) {
				/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
				bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
				if (bflush)
 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
				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) {
			/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
			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(s, 1); ***/
			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(s, 0); ***/
			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 scan, 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) {
				scan = s.strstart - 1;
				prev = _win[scan];
				if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
					strend = s.strstart + MAX_MATCH;
					do					;
while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend);
					s.match_length = MAX_MATCH - (strend - scan);
					if (s.match_length > s.lookahead) s.match_length = s.lookahead;
				}
			}
			if (s.match_length >= MIN_MATCH) {
				/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
				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 {
				/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
				bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
				s.lookahead--;
				s.strstart++;
			}
			if (bflush) {
				/*** FLUSH_BLOCK(s, 0); ***/
				flush_block_only(s, false);
				if (s.strm.avail_out === 0) return BS_NEED_MORE;
			}
		}
		s.insert = 0;
		if (flush === Z_FINISH) {
			/*** FLUSH_BLOCK(s, 1); ***/
			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(s, 0); ***/
			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;
			/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
			bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
			s.lookahead--;
			s.strstart++;
			if (bflush) {
				/*** FLUSH_BLOCK(s, 0); ***/
				flush_block_only(s, false);
				if (s.strm.avail_out === 0) return BS_NEED_MORE;
			}
		}
		s.insert = 0;
		if (flush === Z_FINISH) {
			/*** FLUSH_BLOCK(s, 1); ***/
			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(s, 0); ***/
			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 = [
		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;
		/*** CLEAR_HASH(s); ***/
		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 utils.Buf16(HEAP_SIZE * 2);
		this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
		this.bl_tree = new utils.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 utils.Buf16(MAX_BITS + 1);
		this.heap = new utils.Buf16(2 * L_CODES + 1);
		zero(this.heap);
		this.heap_len = 0;
		this.heap_max = 0;
		this.depth = new utils.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 utils.Buf8(s.w_size * 2);
		s.head = new utils.Buf16(s.hash_size);
		s.prev = new utils.Buf16(s.w_size);
		s.lit_bufsize = 1 << memLevel + 6;
		s.pending_buf_size = s.lit_bufsize * 4;
		s.pending_buf = new utils.Buf8(s.pending_buf_size);
		s.d_buf = 1 * s.lit_bufsize;
		s.l_buf = 3 * 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) {
						/*** CLEAR_HASH(s); ***/ 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) {
				/*** CLEAR_HASH(s); ***/
				zero(s.head);
				s.strstart = 0;
				s.block_start = 0;
				s.insert = 0;
			}
			tmpDict = new utils.Buf8(s.w_size);
			utils.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)";
}));
//#endregion
//#region node_modules/pako/lib/utils/strings.js
var require_strings = /* @__PURE__ */ __commonJSMin(((exports) => {
	var utils = 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 utils.Buf8(256);
	for (var q = 0; q < 256; q++) _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
	_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 utils.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, utils.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 utils.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;
	};
}));
//#endregion
//#region node_modules/pako/lib/zlib/zstream.js
var require_zstream = /* @__PURE__ */ __commonJSMin(((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;
}));
//#endregion
//#region node_modules/pako/lib/deflate.js
var require_deflate = /* @__PURE__ */ __commonJSMin(((exports) => {
	var zlib_deflate = require_deflate$1();
	var utils = require_common();
	var strings = require_strings();
	var msg = require_messages();
	var ZStream = require_zstream();
	var toString = 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;
	/**
	* class Deflate
	*
	* Generic JS-style wrapper for zlib calls. If you don't need
	* streaming behaviour - use more simple functions: [[deflate]],
	* [[deflateRaw]] and [[gzip]].
	**/
	/**
	* Deflate.result -> Uint8Array|Array
	*
	* Compressed result, generated by default [[Deflate#onData]]
	* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
	* (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
	* push a chunk with explicit flush (call [[Deflate#push]] with
	* `Z_SYNC_FLUSH` param).
	**/
	/**
	* Deflate.err -> Number
	*
	* Error code after deflate finished. 0 (Z_OK) on success.
	* You will not need it in real life, because deflate errors
	* are possible only on wrong options or bad `onData` / `onEnd`
	* custom handlers.
	**/
	/**
	* Deflate.msg -> String
	*
	* Error message, if [[Deflate.err]] != 0
	**/
	/**
	* new Deflate(options)
	* - options (Object): zlib deflate options.
	*
	* Creates new deflator instance with specified params. Throws exception
	* on bad params. Supported options:
	*
	* - `level`
	* - `windowBits`
	* - `memLevel`
	* - `strategy`
	* - `dictionary`
	*
	* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
	* for more information on these.
	*
	* Additional options, for internal needs:
	*
	* - `chunkSize` - size of generated data chunks (16K by default)
	* - `raw` (Boolean) - do raw deflate
	* - `gzip` (Boolean) - create gzip wrapper
	* - `to` (String) - if equal to 'string', then result will be "binary string"
	*    (each char code [0..255])
	* - `header` (Object) - custom header for gzip
	*   - `text` (Boolean) - true if compressed data believed to be text
	*   - `time` (Number) - modification time, unix timestamp
	*   - `os` (Number) - operation system code
	*   - `extra` (Array) - array of bytes with extra data (max 65536)
	*   - `name` (String) - file name (binary string)
	*   - `comment` (String) - comment (binary string)
	*   - `hcrc` (Boolean) - true if header crc should be added
	*
	* ##### Example:
	*
	* ```javascript
	* var pako = require('pako')
	*   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
	*   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
	*
	* var deflate = new pako.Deflate({ level: 3});
	*
	* deflate.push(chunk1, false);
	* deflate.push(chunk2, true);  // true -> last chunk
	*
	* if (deflate.err) { throw new Error(deflate.err); }
	*
	* console.log(deflate.result);
	* ```
	**/
	function Deflate(options) {
		if (!(this instanceof Deflate)) return new Deflate(options);
		this.options = utils.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 (toString.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#push(data[, mode]) -> Boolean
	* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
	*   converted to utf8 byte sequence.
	* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
	*   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
	*
	* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
	* new compressed chunks. Returns `true` on success. The last data block must have
	* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
	* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
	* can use mode Z_SYNC_FLUSH, keeping the compression context.
	*
	* On fail call [[Deflate#onEnd]] with error code and return false.
	*
	* We strongly recommend to use `Uint8Array` on input for best speed (output
	* array format is detected automatically). Also, don't skip last param and always
	* use the same type in your code (boolean or number). That will improve JS speed.
	*
	* For regular `Array`-s make sure all elements are [0..255].
	*
	* ##### Example
	*
	* ```javascript
	* push(chunk, false); // push one of data chunks
	* ...
	* push(chunk, true);  // push last chunk
	* ```
	**/
	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 (toString.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 utils.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(utils.shrinkBuf(strm.output, strm.next_out)));
			else this.onData(utils.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#onData(chunk) -> Void
	* - chunk (Uint8Array|Array|String): output data. Type of array depends
	*   on js engine support. When string output requested, each chunk
	*   will be string.
	*
	* By default, stores data blocks in `chunks[]` property and glue
	* those in `onEnd`. Override this handler, if you need another behaviour.
	**/
	Deflate.prototype.onData = function(chunk) {
		this.chunks.push(chunk);
	};
	/**
	* Deflate#onEnd(status) -> Void
	* - status (Number): deflate status. 0 (Z_OK) on success,
	*   other if not.
	*
	* Called once after you tell deflate that the input stream is
	* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
	* or if an error happened. By default - join collected chunks,
	* free memory and fill `results` / `err` properties.
	**/
	Deflate.prototype.onEnd = function(status) {
		if (status === Z_OK) if (this.options.to === "string") this.result = this.chunks.join("");
		else this.result = utils.flattenChunks(this.chunks);
		this.chunks = [];
		this.err = status;
		this.msg = this.strm.msg;
	};
	/**
	* deflate(data[, options]) -> Uint8Array|Array|String
	* - data (Uint8Array|Array|String): input data to compress.
	* - options (Object): zlib deflate options.
	*
	* Compress `data` with deflate algorithm and `options`.
	*
	* Supported options are:
	*
	* - level
	* - windowBits
	* - memLevel
	* - strategy
	* - dictionary
	*
	* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
	* for more information on these.
	*
	* Sugar (options):
	*
	* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
	*   negative windowBits implicitly.
	* - `to` (String) - if equal to 'string', then result will be "binary string"
	*    (each char code [0..255])
	*
	* ##### Example:
	*
	* ```javascript
	* var pako = require('pako')
	*   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
	*
	* console.log(pako.deflate(data));
	* ```
	**/
	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;
	}
	/**
	* deflateRaw(data[, options]) -> Uint8Array|Array|String
	* - data (Uint8Array|Array|String): input data to compress.
	* - options (Object): zlib deflate options.
	*
	* The same as [[deflate]], but creates raw data, without wrapper
	* (header and adler32 crc).
	**/
	function deflateRaw(input, options) {
		options = options || {};
		options.raw = true;
		return deflate(input, options);
	}
	/**
	* gzip(data[, options]) -> Uint8Array|Array|String
	* - data (Uint8Array|Array|String): input data to compress.
	* - options (Object): zlib deflate options.
	*
	* The same as [[deflate]], but create gzip wrapper instead of
	* deflate one.
	**/
	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;
}));
//#endregion
//#region node_modules/pako/lib/zlib/inffast.js
var require_inffast = /* @__PURE__ */ __commonJSMin(((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;
	};
}));
//#endregion
//#region node_modules/pako/lib/zlib/inftrees.js
var require_inftrees = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var utils = 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 utils.Buf16(MAXBITS + 1);
		var offs = new utils.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++] = 20971520;
			table[table_index++] = 20971520;
			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 = 96;
				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 | 4194304;
		opts.bits = root;
		return 0;
	};
}));
//#endregion
//#region node_modules/pako/lib/zlib/inflate.js
var require_inflate$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	var utils = 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 DEF_WBITS = 15;
	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 utils.Buf16(320);
		this.work = new utils.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 utils.Buf32(ENOUGH_LENS);
		state.distcode = state.distdyn = new utils.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, distfix;
	function fixedtables(state) {
		if (virgin) {
			var sym;
			lenfix = new utils.Buf32(512);
			distfix = new utils.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 utils.Buf8(state.wsize);
		}
		if (copy >= state.wsize) {
			utils.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;
			utils.arraySet(state.window, src, end - copy, dist, state.wnext);
			copy -= dist;
			if (copy) {
				utils.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 utils.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);
							utils.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;
					utils.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)";
}));
//#endregion
//#region node_modules/pako/lib/zlib/constants.js
var require_constants = /* @__PURE__ */ __commonJSMin(((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
	};
}));
//#endregion
//#region node_modules/pako/lib/zlib/gzheader.js
var require_gzheader = /* @__PURE__ */ __commonJSMin(((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;
}));
//#endregion
//#region node_modules/pako/lib/inflate.js
var require_inflate = /* @__PURE__ */ __commonJSMin(((exports) => {
	var zlib_inflate = require_inflate$1();
	var utils = require_common();
	var strings = require_strings();
	var c = require_constants();
	var msg = require_messages();
	var ZStream = require_zstream();
	var GZheader = require_gzheader();
	var toString = Object.prototype.toString;
	/**
	* class Inflate
	*
	* Generic JS-style wrapper for zlib calls. If you don't need
	* streaming behaviour - use more simple functions: [[inflate]]
	* and [[inflateRaw]].
	**/
	/**
	* Inflate.result -> Uint8Array|Array|String
	*
	* Uncompressed result, generated by default [[Inflate#onData]]
	* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
	* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
	* push a chunk with explicit flush (call [[Inflate#push]] with
	* `Z_SYNC_FLUSH` param).
	**/
	/**
	* Inflate.err -> Number
	*
	* Error code after inflate finished. 0 (Z_OK) on success.
	* Should be checked if broken data possible.
	**/
	/**
	* Inflate.msg -> String
	*
	* Error message, if [[Inflate.err]] != 0
	**/
	/**
	* new Inflate(options)
	* - options (Object): zlib inflate options.
	*
	* Creates new inflator instance with specified params. Throws exception
	* on bad params. Supported options:
	*
	* - `windowBits`
	* - `dictionary`
	*
	* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
	* for more information on these.
	*
	* Additional options, for internal needs:
	*
	* - `chunkSize` - size of generated data chunks (16K by default)
	* - `raw` (Boolean) - do raw inflate
	* - `to` (String) - if equal to 'string', then result will be converted
	*   from utf8 to utf16 (javascript) string. When string output requested,
	*   chunk length can differ from `chunkSize`, depending on content.
	*
	* By default, when no options set, autodetect deflate/gzip data format via
	* wrapper header.
	*
	* ##### Example:
	*
	* ```javascript
	* var pako = require('pako')
	*   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
	*   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
	*
	* var inflate = new pako.Inflate({ level: 3});
	*
	* inflate.push(chunk1, false);
	* inflate.push(chunk2, true);  // true -> last chunk
	*
	* if (inflate.err) { throw new Error(inflate.err); }
	*
	* console.log(inflate.result);
	* ```
	**/
	function Inflate(options) {
		if (!(this instanceof Inflate)) return new Inflate(options);
		this.options = utils.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 (toString.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#push(data[, mode]) -> Boolean
	* - data (Uint8Array|Array|ArrayBuffer|String): input data
	* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
	*   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
	*
	* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
	* new output chunks. Returns `true` on success. The last data block must have
	* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
	* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
	* can use mode Z_SYNC_FLUSH, keeping the decompression context.
	*
	* On fail call [[Inflate#onEnd]] with error code and return false.
	*
	* We strongly recommend to use `Uint8Array` on input for best speed (output
	* format is detected automatically). Also, don't skip last param and always
	* use the same type in your code (boolean or number). That will improve JS speed.
	*
	* For regular `Array`-s make sure all elements are [0..255].
	*
	* ##### Example
	*
	* ```javascript
	* push(chunk, false); // push one of data chunks
	* ...
	* push(chunk, true);  // push last chunk
	* ```
	**/
	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 (toString.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 utils.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) utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0);
					this.onData(utf8str);
				} else this.onData(utils.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#onData(chunk) -> Void
	* - chunk (Uint8Array|Array|String): output data. Type of array depends
	*   on js engine support. When string output requested, each chunk
	*   will be string.
	*
	* By default, stores data blocks in `chunks[]` property and glue
	* those in `onEnd`. Override this handler, if you need another behaviour.
	**/
	Inflate.prototype.onData = function(chunk) {
		this.chunks.push(chunk);
	};
	/**
	* Inflate#onEnd(status) -> Void
	* - status (Number): inflate status. 0 (Z_OK) on success,
	*   other if not.
	*
	* Called either after you tell inflate that the input stream is
	* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
	* or if an error happened. By default - join collected chunks,
	* free memory and fill `results` / `err` properties.
	**/
	Inflate.prototype.onEnd = function(status) {
		if (status === c.Z_OK) if (this.options.to === "string") this.result = this.chunks.join("");
		else this.result = utils.flattenChunks(this.chunks);
		this.chunks = [];
		this.err = status;
		this.msg = this.strm.msg;
	};
	/**
	* inflate(data[, options]) -> Uint8Array|Array|String
	* - data (Uint8Array|Array|String): input data to decompress.
	* - options (Object): zlib inflate options.
	*
	* Decompress `data` with inflate/ungzip and `options`. Autodetect
	* format via wrapper header by default. That's why we don't provide
	* separate `ungzip` method.
	*
	* Supported options are:
	*
	* - windowBits
	*
	* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
	* for more information.
	*
	* Sugar (options):
	*
	* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
	*   negative windowBits implicitly.
	* - `to` (String) - if equal to 'string', then result will be converted
	*   from utf8 to utf16 (javascript) string. When string output requested,
	*   chunk length can differ from `chunkSize`, depending on content.
	*
	*
	* ##### Example:
	*
	* ```javascript
	* var pako = require('pako')
	*   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
	*   , output;
	*
	* try {
	*   output = pako.inflate(input);
	* } catch (err)
	*   console.log(err);
	* }
	* ```
	**/
	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;
	}
	/**
	* inflateRaw(data[, options]) -> Uint8Array|Array|String
	* - data (Uint8Array|Array|String): input data to decompress.
	* - options (Object): zlib inflate options.
	*
	* The same as [[inflate]], but creates raw data, without wrapper
	* (header and adler32 crc).
	**/
	function inflateRaw(input, options) {
		options = options || {};
		options.raw = true;
		return inflate(input, options);
	}
	/**
	* ungzip(data[, options]) -> Uint8Array|Array|String
	* - data (Uint8Array|Array|String): input data to decompress.
	* - options (Object): zlib inflate options.
	*
	* Just shortcut to [[inflate]], because it autodetects format
	* by header.content. Done for convenience.
	**/
	exports.Inflate = Inflate;
	exports.inflate = inflate;
	exports.inflateRaw = inflateRaw;
	exports.ungzip = inflate;
}));
//#endregion
//#region node_modules/pako/index.js
var require_pako = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var assign = require_common().assign;
	var deflate = require_deflate();
	var inflate = require_inflate();
	var constants = require_constants();
	var pako = {};
	assign(pako, deflate, inflate, constants);
	module.exports = pako;
}));
//#endregion
//#region node_modules/@jimp/js-tiff/dist/esm/index.js
var import_UTIF = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var UTIF = {};
		if (typeof module == "object") module.exports = UTIF;
		else self.UTIF = UTIF;
		var pako = typeof __require === "function" ? require_pako() : self.pako;
		function log() {
			if (typeof process == "undefined" || false) console.log.apply(console, arguments);
		}
		(function(UTIF, pako) {
			(function() {
				"use strict";
				var W = function a1() {
					function W(p) {
						this.message = "JPEG error: " + p;
					}
					W.prototype = /* @__PURE__ */ new Error();
					W.prototype.name = "JpegError";
					W.constructor = W;
					return W;
				}(), 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 ak(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 = !1;
						var T = f.m, U = f.Z, 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 (!0) {
								l = l[Y()];
								switch (typeof l) {
									case "number": return l;
									case "object": continue;
								}
								throw new W("invalid huffman sequence");
							}
						}
						function m(I) {
							var e = 0;
							while (I > 0) {
								e = e << 1 | Y();
								I--;
							}
							return e;
						}
						function j(I) {
							if (I === 1) return Y() === 1 ? 1 : -1;
							var e = m(I);
							if (e >= 1 << I - 1) return e;
							return e + (-1 << I) + 1;
						}
						function v(X, I) {
							var l = u(X.J), M = l === 0 ? 0 : j(l), N = 1;
							X.D[I] = X.Q += M;
							while (N < 64) {
								var S = u(X.i), i = S & 15, A = S >> 4;
								if (i === 0) {
									if (A < 15) break;
									N += 16;
									continue;
								}
								N += A;
								var o = p[N];
								X.D[I + o] = j(i);
								N++;
							}
						}
						function $(X, I) {
							var l = u(X.J), M = l === 0 ? 0 : j(l) << F;
							X.D[I] = X.Q += M;
						}
						function b(X, I) {
							X.D[I] |= Y() << F;
						}
						function P(X, I) {
							if (r > 0) {
								r--;
								return;
							}
							var N = E, l = a;
							while (N <= l) {
								var M = u(X.i), S = M & 15, i = M >> 4;
								if (S === 0) {
									if (i < 15) {
										r = m(i) + (1 << i) - 1;
										break;
									}
									N += 16;
									continue;
								}
								N += i;
								var A = p[N];
								X.D[I + A] = j(S) * (1 << F);
								N++;
							}
						}
						function a4(X, I) {
							var N = E, l = a, M = 0, S, i;
							while (N <= l) {
								var A = I + p[N], o = X.D[A] < 0 ? -1 : 1;
								switch (D) {
									case 0:
										i = u(X.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 (X.D[A]) X.D[A] += o * (Y() << F);
										else {
											M--;
											if (M === 0) D = D === 2 ? 3 : 0;
										}
										break;
									case 3:
										if (X.D[A]) X.D[A] += o * (Y() << F);
										else {
											X.D[A] = a8 << F;
											D = 0;
										}
										break;
									case 4:
										if (X.D[A]) X.D[A] += o * (Y() << F);
										break;
								}
								N++;
							}
							if (D === 4) {
								r--;
								if (r === 0) D = 0;
							}
						}
						function H(X, I, x, l, M) {
							var S = x / T | 0, i = x % T;
							q = S * X.A + l;
							var A = i * X.h + M;
							I(X, a2(X, q, A));
						}
						function w(X, I, x) {
							q = x / X.P | 0;
							var l = x % X.P;
							I(X, a2(X, q, l));
						}
						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) h = k.offset;
							if (k.M >= 65488 && k.M <= 65495) h += 2;
							else break;
						}
						return h - z;
					}
					function al(Q, h, f) {
						var G = Q.$, n = Q.D, 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 f = h.P, G = h.c, n = new Int16Array(64);
						for (var E = 0; E < G; E++) for (var a = 0; a < f; a++) al(h, a2(h, E, a), 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
						};
					}
					ak.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, V = an(Q, B, E);
								if (V && V.u) B = V.offset;
								var ab = Q.subarray(E, B);
								E += ab.length;
								return ab;
							}
							function n(F) {
								var o = Math.ceil(F.o / 8 / F.X), B = Math.ceil(F.s / 8 / F.B);
								for (var Y = 0; Y < F.W.length; Y++) {
									R = F.W[Y];
									var ab = Math.ceil(Math.ceil(F.o / 8) * R.h / F.X), af = Math.ceil(Math.ceil(F.s / 8) * R.A / F.B), ap = o * R.h, ae = 64 * (B * R.A) * (ap + 1);
									R.D = new Int16Array(ae);
									R.P = ab;
									R.c = af;
								}
								F.m = o;
								F.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;
						},
						Y(Q, h, f) {
							if (f == null) f = !1;
							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 !1;
								else if (this.W[0].index === 82 && this.W[1].index === 71 && this.W[2].index === 66) return !1;
								return !0;
							}
							if (this.N === 1) return !0;
							return !1;
						},
						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 - .344 * f - .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 * (-660635669420364e-19 * f + .000437130475926232 * G - 54080610064599e-18 * h + .00048449797120281 * n - .154362151871126) + G * (-.000957964378445773 * G + .000817076911346625 * h - .00477271405408747 * n + 1.53380253221734) + h * (.000961250184130688 * h - .00266257332283933 * n + .48357088451265) + n * (-.000336197177618394 * n + .484791561490776);
								Q[E++] = 107.268039397724 + f * (219927104525741e-19 * f - .000640992018297945 * G + .000659397001245577 * h + .000426105652938837 * n - .176491792462875) + G * (-.000778269941513683 * G + .00130872261408275 * h + .000770482631801132 * n - .151051492775562) + h * (.00126935368114843 * h - .00265090189010898 * n + .25802910206845) + n * (-.000318913117588328 * n - .213742400323665);
								Q[E++] = -20.810012546947 + f * (-.000570115196973677 * f - 263409051004589e-19 * G + .0020741088115012 * h - .00288260236853442 * n + .814272968359295) + G * (-153496057440975e-19 * G - .000132689043961446 * h + .000560833691242812 * n - .195152027534049) + h * (.00174418132927582 * h - .00255243321439347 * n + .116935020465145) + n * (-.000343531996510555 * n + .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 + .344 * f + .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 * (-6747147073602441e-20 * h + .0008379262121013727 * f + .0002894718188643294 * G + .003264231057537806 * n - 1.1185611867203937) + f * (26374107616089405e-21 * f - 8626949158638572e-20 * G - .0002748769067499491 * n - .02155688794978967) + G * (-3878099212869363e-20 * G - .0003267808279485286 * n + .0686742238595345) - n * (.0003361971776183937 * n + .7430659151342254);
								Q[E++] = 255 + h * (.00013596372813588848 * h + .000924537132573585 * f + .00010567359618683593 * G + .0004791864687436512 * n - .3109689587515875) + f * (-.00023545346108370344 * f + .0002702845253534714 * G + .0020200308977307156 * n - .7488052167015494) + G * (6834815998235662e-20 * G + .00015168452363460973 * n - .09751927774728933) - n * (.0003189131175883281 * n + .7364883807733168);
								Q[E++] = 255 + h * (13598650411385307e-21 * h + .00012423956175490851 * f + .0004751985097583589 * G - 36729317476630422e-22 * n - .05562186980264034) + f * (.00016141380598724676 * f + .0009692239130725186 * G + .0007782692450036253 * n - .44015232367526463) + G * (5.068882914068769e-7 * G + .0017778369011375071 * n - .7591454649749609) - n * (.0003435319965105553 * n + .7063770186160144);
							}
							return Q.subarray(0, E);
						},
						getData: function(Q) {
							var h = Q.width, f = Q.height, G = Q.forceRGB, n = Q.isSourcePDF;
							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 ak;
				}();
				function Z(p, t) {
					return p[t] << 8 | p[t + 1];
				}
				UTIF.JpegDecoder = ak;
			})();
			UTIF.encodeImage = function(rgba, w, h, metadata) {
				var idf = {
					"t256": [w],
					"t257": [h],
					"t258": [
						8,
						8,
						8,
						8
					],
					"t259": [1],
					"t262": [2],
					"t273": [1e3],
					"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(UTIF.encode([idf]));
				var img = new Uint8Array(rgba);
				var data = new Uint8Array(1e3 + w * h * 4);
				for (var i = 0; i < prfx.length; i++) data[i] = prfx[i];
				for (var i = 0; i < img.length; i++) data[1e3 + i] = img[i];
				return data.buffer;
			};
			UTIF.encode = function(ifds) {
				var LE = false;
				var data = new Uint8Array(2e4), offset = 4, bin = LE ? UTIF._binLE : UTIF._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 = UTIF._writeIFD(bin, UTIF._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;
			};
			UTIF.decode = function(buff, prm) {
				if (prm == null) prm = {
					parseMN: true,
					debug: false
				};
				var data = new Uint8Array(buff), offset = 0;
				var id = UTIF._binBE.readASCII(data, offset, 2);
				offset += 2;
				var bin = id == "II" ? UTIF._binLE : UTIF._binBE;
				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;
						}
					}
					UTIF._readIFD(bin, data, ifdo, ifds, 0, prm);
					ifdo = bin.readUint(data, ifdo + 2 + cnt * 12);
					if (ifdo == 0) break;
				}
				return ifds;
			};
			UTIF.decodeImage = function(buff, img, ifds) {
				if (img.data) return;
				var data = new Uint8Array(buff);
				var id = UTIF._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 bipp = (img["t258"] ? img["t258"][0] : 1) * 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);
						UTIF.decode._decompress(img, ifds, data, soff[i], bcnt[i], cmpr, tbuff, 0, fo, tw, th);
						if (cmpr == 6) bytes = tbuff;
						else UTIF._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++) {
						UTIF.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);
			};
			UTIF.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 (cmpr == 1) for (var j = 0; j < len; j++) tgt[toff + j] = data[off + j];
				else if (cmpr == 2) UTIF.decode._decodeG2(data, off, len, tgt, toff, w, fo);
				else if (cmpr == 3) UTIF.decode._decodeG3(data, off, len, tgt, toff, w, fo, img["t292"] ? (img["t292"][0] & 1) == 1 : false);
				else if (cmpr == 4) UTIF.decode._decodeG4(data, off, len, tgt, toff, w, fo);
				else if (cmpr == 5) UTIF.decode._decodeLZW(data, off, len, tgt, toff, 8);
				else if (cmpr == 6) UTIF.decode._decodeOldJPEG(img, data, off, len, tgt, toff);
				else if (cmpr == 7 || cmpr == 34892) UTIF.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 = pako["inflateRaw"](src);
					if (toff + bin.length <= tgt.length) tgt.set(bin, toff);
				} else if (cmpr == 9) UTIF.decode._decodeVC5(data, off, len, tgt, toff, img["t33422"]);
				else if (cmpr == 32767) UTIF.decode._decodeARW(img, data, off, len, tgt, toff);
				else if (cmpr == 32773) UTIF.decode._decodePackBits(data, off, len, tgt, toff);
				else if (cmpr == 32809) UTIF.decode._decodeThunder(data, off, len, tgt, toff);
				else if (cmpr == 34316) UTIF.decode._decodePanasonic(img, data, off, len, tgt, toff);
				else if (cmpr == 34713) UTIF.decode._decodeNikon(img, ifds, data, off, len, tgt, toff);
				else if (cmpr == 34676) UTIF.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;
				}
			};
			UTIF.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 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_a = new Uint8Array(img_buffer, off + imageIndex + 8184, 8200);
						var arr_b = new Uint8Array(img_buffer, off + imageIndex, 8184);
						buffer.set(arr_a);
						buffer.set(arr_b, arr_a.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(i) {
					return buffer[vpos + 15 - i];
				}
				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;
			};
			UTIF.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 = UTIF._binBE, $ = E + h, r, u, X, I, ax, R, aa, i, 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);
						else if (S == 62) R = s;
						else if (S == 101);
						else if (S == 109) aa = s;
						else if (S == 84);
						else if (S == 106);
						else if (S == 107);
						else if (S == 108);
						else if (S == 102);
						else if (S == 104) i = s;
						else if (S == 105);
						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 / (65025 * 255)) + p;
										C[M] = Math.sign(aG) * r;
									}
									k = new Uint16Array(4096);
									var aA = 65535;
									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;
			}();
			UTIF.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;
					}
				}
			};
			UTIF.decode._ljpeg_diff = function(data, prm, huff) {
				var getbithuff = UTIF.decode._getbithuff;
				var 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;
			};
			UTIF.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 ? UTIF._binLE : UTIF._binBE;
				if (!(raw_width * height == src_length || raw_width * height * 1.5 == src_length)) {
					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 = UTIF.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;
							UTIF.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;
							UTIF.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps);
						}
						col -= col & 1 ? 1 : 31;
					}
				}
			};
			UTIF.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 = UTIF.decode._make_decoder;
				var getbithuff = UTIF.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 ? UTIF._binLE : UTIF._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 hpred = [0, 0];
				var huff = make_decoder(nikon_tree[tree]);
				var prm = [
					off,
					0,
					0,
					0
				];
				for (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;
						UTIF.decode._putsF(tgt, bti, clr << 16 - tiff_bps);
					}
				}
			};
			UTIF.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;
			};
			UTIF.decode._getbithuff = function(data, prm, nbits, huff) {
				var zero_after_ff = 0;
				UTIF.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;
			};
			UTIF.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;
			};
			UTIF.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, EOI = 217, boff = 0;
					for (var i = 0; i < tlen - 1; i++) {
						if (tables[i] == 255 && tables[i + 1] == EOI) 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 = UTIF.LosslessJpegDecode(buff), olen = out.length;
					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++) UTIF.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 UTIF.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;
			};
			UTIF.decode._decodeOldJPEGInit = function(img, data, off, len) {
				var SOI = 216, DQT = 219, DHT = 196, DRI = 221, SOF0 = 192, SOS = 218;
				var joff = 0, soff = 0, tables, sosMarker, 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] == SOS) {
					var soslen = data[soff + 2] << 8 | data[soff + 3];
					sosMarker = new Uint8Array(soslen + 2);
					sosMarker[0] = data[soff];
					sosMarker[1] = data[soff + 1];
					sosMarker[2] = data[soff + 2];
					sosMarker[3] = data[soff + 3];
					for (i = 0; i < soslen - 2; i++) sosMarker[i + 4] = data[soff + i + 4];
				} else {
					sosMarker = new Uint8Array(8 + 2 * spp);
					var sosoff = 0;
					sosMarker[sosoff++] = 255;
					sosMarker[sosoff++] = SOS;
					sosMarker[sosoff++] = 0;
					sosMarker[sosoff++] = 6 + 2 * spp;
					sosMarker[sosoff++] = spp;
					if (spp == 1) {
						sosMarker[sosoff++] = 1;
						sosMarker[sosoff++] = 0;
					} else for (i = 0; i < 3; i++) {
						sosMarker[sosoff++] = i + 1;
						sosMarker[sosoff++] = i << 4 | i;
					}
					sosMarker[sosoff++] = 0;
					sosMarker[sosoff++] = 63;
					sosMarker[sosoff++] = 0;
				}
				return {
					jpegOffset: off,
					tables,
					sosMarker,
					sofPosition: sofpos
				};
			};
			UTIF.decode._decodeOldJPEG = function(img, data, off, len, tgt, toff) {
				var i, dlen, tlen, buff, buffoff;
				var jpegData = UTIF.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 UTIF.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;
			};
			UTIF.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;
			};
			UTIF.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++;
						}
					}
				}
			};
			UTIF.decode._dmap = {
				"1": 0,
				"011": 1,
				"000011": 2,
				"0000011": 3,
				"010": -1,
				"000010": -2,
				"0000010": -3
			};
			UTIF.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];
			})();
			UTIF.decode._decodeG4 = function(data, off, slen, tgt, toff, w, fo) {
				var U = UTIF.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, 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 = [];
					}
				}
			};
			UTIF.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];
			};
			UTIF.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;
			};
			UTIF.decode._decodeG2 = function(data, off, slen, tgt, toff, w, fo) {
				var U = UTIF.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;
						}
					}
				}
			};
			UTIF.decode._decodeG3 = function(data, off, slen, tgt, toff, w, fo, twoDim) {
				var U = UTIF.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, 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);
			};
			UTIF.decode._addNtimes = function(arr, n, val) {
				for (var i = 0; i < n; i++) arr.push(val);
			};
			UTIF.decode._writeBits = function(bits, tgt, boff) {
				for (var i = 0; i < bits.length; i++) tgt[boff + i >>> 3] |= bits[i] << 7 - (boff + i & 7);
			};
			UTIF.decode._decodeLZW = UTIF.decode._decodeLZW = function() {
				var e, U, Z, u, K = 0, V = 0, g = 0, N = 0, O = function() {
					var S = e >>> 3, j = (U[S] << 16 | U[S + 1] << 8 | U[S + 2]) >>> 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;
			}();
			UTIF.tags = {};
			UTIF._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
				]);
				return {
					basic: {
						main,
						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
						}
					},
					gps: {
						main: [
							1,
							2,
							5,
							2,
							5,
							1,
							5,
							5,
							0,
							9
						],
						rest: {
							18: 2,
							29: 2
						}
					}
				};
			}();
			UTIF._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, UTIF.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++) UTIF._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 = UTIF["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 = [];
							UTIF._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;
								UTIF._readIFD(bin, mn, obj[k][0], subsub, depth + 1, prm);
								obj[k] = subsub.pop();
							}
							if (obj["t12288"]) {
								UTIF._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 = [];
							UTIF._readIFD(bin, data, voff, subsub, depth + 1, prm);
							ifd.makerNote = subsub[0];
						}
					}
				}
				ifds.push(ifd);
				if (prm.debug) log("   ".repeat(depth), "<<<---------------");
				return offset;
			};
			UTIF._writeIFD = function(bin, types, 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 = types.main[tag];
					if (type == null) type = types.rest[tag];
					if (type == null || type == 0) throw new Error("unknown type of tag: " + tag);
					var val = ifd[key];
					if (tag == 34665) {
						var outp = UTIF._writeIFD(bin, types, data, eoff, ifd["exifIFD"]);
						val = [eoff];
						eoff = outp[1];
					}
					if (tag == 34853) {
						var outp = UTIF._writeIFD(bin, UTIF._types.gps, data, eoff, ifd["gpsiIFD"]);
						val = [eoff];
						eoff = outp[1];
					}
					if (type == 2) val = val[0] + "\0";
					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];
			};
			UTIF.toRGBA8 = function(out, scl) {
				function gamma(x) {
					return x < .0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - .055;
				}
				var w = out.width, h = out.height, area = w * h;
				area * 4;
				var 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 (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] = ~~(.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++) ndt[i] = pmap[~~(.5 + Math.max(0, Math.min(1, ndt[i])) * 65535)];
					if (smpls == 3) for (var i = 0; i < area; i++) {
						var qi = i << 2, ti = i * 3;
						img[qi] = ~~(.5 + ndt[ti] * 255);
						img[qi + 1] = ~~(.5 + ndt[ti + 1] * 255);
						img[qi + 2] = ~~(.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] = ~~(.5 + ndt[ti] * 255);
						img[qi + 1] = ~~(.5 + ndt[ti + 1] * 255);
						img[qi + 2] = ~~(.5 + ndt[ti + 2] * 255);
						img[qi + 3] = ~~(.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 (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] = ~~(.5 + 255 * c[0]);
							img[qi + 1] = ~~(.5 + 255 * c[1]);
							img[qi + 2] = ~~(.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 + .5);
							img[qi + 1] = ~~(M * K + .5);
							img[qi + 2] = ~~(Y * K + .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 + .5) / 256 - 64);
					var u = (data[si + 3] + .5) / 410;
					var v = (data[si + 5] + .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 - .414 * Z;
					var g = -1.022 * X + 1.978 * Y + .044 * Z;
					var b = .061 * X - .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;
			};
			UTIF.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();
					UTIF._xhrs.push(xhr);
					UTIF._imgs.push(img);
					xhr.open("GET", src);
					xhr.responseType = "arraybuffer";
					xhr.onload = UTIF._imgLoaded;
					xhr.send();
				}
			};
			UTIF._xhrs = [];
			UTIF._imgs = [];
			UTIF._imgLoaded = function(e) {
				var ind = UTIF._xhrs.indexOf(e.target), img = UTIF._imgs[ind];
				UTIF._xhrs.splice(ind, 1);
				UTIF._imgs.splice(ind, 1);
				img.setAttribute("src", UTIF.bufferToURI(e.target.response));
			};
			UTIF.bufferToURI = function(buff) {
				var ifds = UTIF.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;
					}
				}
				UTIF.decodeImage(buff, page, ifds);
				var rgba = UTIF.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();
			};
			UTIF._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 = UTIF._binBE.ui8;
					a[0] = buff[p + 1];
					a[1] = buff[p + 0];
					return UTIF._binBE.i16[0];
				},
				readInt: function(buff, p) {
					var a = UTIF._binBE.ui8;
					a[0] = buff[p + 3];
					a[1] = buff[p + 2];
					a[2] = buff[p + 1];
					a[3] = buff[p + 0];
					return UTIF._binBE.i32[0];
				},
				readUint: function(buff, p) {
					var a = UTIF._binBE.ui8;
					a[0] = buff[p + 3];
					a[1] = buff[p + 2];
					a[2] = buff[p + 1];
					a[3] = buff[p + 0];
					return UTIF._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 = UTIF._binBE.ui8;
					for (var i = 0; i < 4; i++) a[i] = buff[p + 3 - i];
					return UTIF._binBE.fl32[0];
				},
				readDouble: function(buff, p) {
					var a = UTIF._binBE.ui8;
					for (var i = 0; i < 8; i++) a[i] = buff[p + 7 - i];
					return UTIF._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 = UTIF._binBE.ui8;
					UTIF._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) {
					UTIF._binBE.fl64[0] = n;
					for (var i = 0; i < 8; i++) buff[p + i] = UTIF._binBE.ui8[7 - i];
				}
			};
			UTIF._binBE.ui8 = new Uint8Array(8);
			UTIF._binBE.i16 = new Int16Array(UTIF._binBE.ui8.buffer);
			UTIF._binBE.i32 = new Int32Array(UTIF._binBE.ui8.buffer);
			UTIF._binBE.ui32 = new Uint32Array(UTIF._binBE.ui8.buffer);
			UTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer);
			UTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer);
			UTIF._binLE = {
				nextZero: UTIF._binBE.nextZero,
				readUshort: function(buff, p) {
					return buff[p + 1] << 8 | buff[p];
				},
				readShort: function(buff, p) {
					var a = UTIF._binBE.ui8;
					a[0] = buff[p + 0];
					a[1] = buff[p + 1];
					return UTIF._binBE.i16[0];
				},
				readInt: function(buff, p) {
					var a = UTIF._binBE.ui8;
					a[0] = buff[p + 0];
					a[1] = buff[p + 1];
					a[2] = buff[p + 2];
					a[3] = buff[p + 3];
					return UTIF._binBE.i32[0];
				},
				readUint: function(buff, p) {
					var a = UTIF._binBE.ui8;
					a[0] = buff[p + 0];
					a[1] = buff[p + 1];
					a[2] = buff[p + 2];
					a[3] = buff[p + 3];
					return UTIF._binBE.ui32[0];
				},
				readASCII: UTIF._binBE.readASCII,
				readFloat: function(buff, p) {
					var a = UTIF._binBE.ui8;
					for (var i = 0; i < 4; i++) a[i] = buff[p + i];
					return UTIF._binBE.fl32[0];
				},
				readDouble: function(buff, p) {
					var a = UTIF._binBE.ui8;
					for (var i = 0; i < 8; i++) a[i] = buff[p + i];
					return UTIF._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 = UTIF._binBE.ui8;
					UTIF._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: UTIF._binBE.writeASCII
			};
			UTIF._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];
				}
			};
			UTIF.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 V = h.b, I = h.f;
					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;
					return P(H(I, V), 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 F = I.a, t = I.data;
							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 (!0) {
						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();
								if (l() != 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 v = V[l()];
								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 $ = new (f > 8 ? Uint16Array : Uint8Array)(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 = UTIF._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 = UTIF._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;
					t.j;
					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, 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;
					}
				}
				UTIF._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);
	})();
})))(), 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 tiff = import_UTIF.default.encodeImage(bitmap.data, bitmap.width, bitmap.height);
			return Buffer.from(tiff);
		},
		decode: (data) => {
			const ifds = import_UTIF.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_UTIF.default.decodeImage(data, ifd);
			});
			const rgba = import_UTIF.default.toRGBA8(page);
			return {
				data: Buffer.from(rgba),
				width: getDimensionValue(page.t256),
				height: getDimensionValue(page.t257)
			};
		}
	};
}
//#endregion
//#region node_modules/@jimp/types/dist/esm/index.js
var Edge;
(function(Edge) {
	Edge[Edge["EXTEND"] = 1] = "EXTEND";
	Edge[Edge["WRAP"] = 2] = "WRAP";
	Edge[Edge["CROP"] = 3] = "CROP";
})(Edge || (Edge = {}));
const JimpClassSchema = z.object({ bitmap: z.object({
	data: z.union([z.instanceof(Buffer), z.instanceof(Uint8Array)]),
	width: z.number(),
	height: z.number()
}) });
//#endregion
//#region node_modules/@jimp/plugin-blit/dist/esm/index.js
const BlitOptionsSchemaComplex = z.object({
	src: JimpClassSchema,
	x: z.number().optional(),
	y: z.number().optional(),
	srcX: z.number().optional(),
	srcY: z.number().optional(),
	srcW: z.number().optional(),
	srcH: z.number().optional()
});
const BlitOptionsSchema = z.union([JimpClassSchema, BlitOptionsSchemaComplex]);
const methods$17 = { blit(image, 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 = image.bitmap.width;
	const maxHeight = image.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 = image.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: image.bitmap.data[dstIdx] || 0,
				g: image.bitmap.data[dstIdx + 1] || 0,
				b: image.bitmap.data[dstIdx + 2] || 0,
				a: image.bitmap.data[dstIdx + 3] || 0
			};
			image.bitmap.data[dstIdx] = (srcColor.a * (srcColor.r - dst.r) - dst.r + 255 >> 8) + dst.r;
			image.bitmap.data[dstIdx + 1] = (srcColor.a * (srcColor.g - dst.g) - dst.g + 255 >> 8) + dst.g;
			image.bitmap.data[dstIdx + 2] = (srcColor.a * (srcColor.b - dst.b) - dst.b + 255 >> 8) + dst.b;
			image.bitmap.data[dstIdx + 3] = limit255(dst.a + srcColor.a);
		}
	});
	return image;
} };
//#endregion
//#region node_modules/@jimp/plugin-blur/dist/esm/blur-tables.js
const 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
];
const 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
];
//#endregion
//#region node_modules/@jimp/plugin-blur/dist/esm/index.js
const methods$16 = {
	blur(image, 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 = image.bitmap.width - 1;
		const hm = image.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 < image.bitmap.height; y++) {
				rsum = image.bitmap.data[yw] * rad1;
				gsum = image.bitmap.data[yw + 1] * rad1;
				bsum = image.bitmap.data[yw + 2] * rad1;
				asum = image.bitmap.data[yw + 3] * rad1;
				for (i = 1; i <= r; i++) {
					p = yw + ((i > wm ? wm : i) << 2);
					rsum += image.bitmap.data[p++];
					gsum += image.bitmap.data[p++];
					bsum += image.bitmap.data[p++];
					asum += image.bitmap.data[p];
				}
				for (x = 0; x < image.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 += image.bitmap.data[p1++] - image.bitmap.data[p2++];
					gsum += image.bitmap.data[p1++] - image.bitmap.data[p2++];
					bsum += image.bitmap.data[p1++] - image.bitmap.data[p2++];
					asum += image.bitmap.data[p1] - image.bitmap.data[p2++];
					yi++;
				}
				yw += image.bitmap.width << 2;
			}
			for (x = 0; x < image.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 : image.bitmap.width;
					rsum += red[yp];
					gsum += green[yp];
					bsum += blue[yp];
					asum += alpha[yp];
				}
				yi = x << 2;
				for (y = 0; y < image.bitmap.height; y++) {
					image.bitmap.data[yi] = limit255(rsum * mulSum >>> shgSum);
					image.bitmap.data[yi + 1] = limit255(gsum * mulSum >>> shgSum);
					image.bitmap.data[yi + 2] = limit255(bsum * mulSum >>> shgSum);
					image.bitmap.data[yi + 3] = limit255(asum * mulSum >>> shgSum);
					if (x === 0) {
						vmin[y] = ((p = y + rad1) < hm ? p : hm) * image.bitmap.width;
						vmax[y] = (p = y - r) > 0 ? p * image.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 += image.bitmap.width << 2;
				}
			}
		}
		return image;
	},
	gaussian(image, 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 < image.bitmap.height; y++) for (let x = 0; x < image.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(image.bitmap.width - 1, Math.max(0, ix + x - rs));
					const y1 = Math.min(image.bitmap.height - 1, Math.max(0, iy + y - rs));
					const weight = weights[iy][ix];
					const idx = y1 * image.bitmap.width + x1 << 2;
					red += image.bitmap.data[idx] * weight;
					green += image.bitmap.data[idx + 1] * weight;
					blue += image.bitmap.data[idx + 2] * weight;
					alpha += image.bitmap.data[idx + 3] * weight;
					wsum += weight;
				}
				const idx = y * image.bitmap.width + x << 2;
				image.bitmap.data[idx] = Math.round(red / wsum);
				image.bitmap.data[idx + 1] = Math.round(green / wsum);
				image.bitmap.data[idx + 2] = Math.round(blue / wsum);
				image.bitmap.data[idx + 3] = Math.round(alpha / wsum);
			}
		}
		return image;
	}
};
//#endregion
//#region node_modules/@jimp/plugin-circle/dist/esm/index.js
const CircleOptionsSchema = z.object({
	x: z.number().optional(),
	y: z.number().optional(),
	radius: z.number().min(0).optional()
});
const methods$15 = { circle(image, options = {}) {
	const parsed = CircleOptionsSchema.parse(options);
	const radius = parsed.radius || (image.bitmap.width > image.bitmap.height ? image.bitmap.height : image.bitmap.width) / 2;
	const center = {
		x: typeof parsed.x === "number" ? parsed.x : image.bitmap.width / 2,
		y: typeof parsed.y === "number" ? parsed.y : image.bitmap.height / 2
	};
	image.scan((x, y, idx) => {
		const curR = Math.sqrt(Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2));
		if (radius - curR <= 0) image.bitmap.data[idx + 3] = 0;
		else if (radius - curR < 1) image.bitmap.data[idx + 3] = 255 * (radius - curR);
	});
	return image;
} };
//#endregion
//#region node_modules/@jimp/plugin-color/dist/esm/index.js
const ConvolutionMatrixSchema = z.array(z.number()).min(1).array();
const ConvolutionComplexOptionsSchema = z.object({
	kernel: ConvolutionMatrixSchema,
	edgeHandling: z.nativeEnum(Edge).optional()
});
const ConvolutionOptionsSchema = z.union([ConvolutionMatrixSchema, ConvolutionComplexOptionsSchema]);
const ConvoluteComplexOptionsSchema = z.object({
	kernel: ConvolutionMatrixSchema,
	x: z.number().optional(),
	y: z.number().optional(),
	w: z.number().optional(),
	h: z.number().optional()
});
const ConvoluteOptionsSchema = z.union([ConvolutionMatrixSchema, ConvoluteComplexOptionsSchema]);
const PixelateSize = z.number().min(1).max(Infinity);
const PixelateComplexOptionsSchema = z.object({
	size: PixelateSize,
	x: z.number().optional(),
	y: z.number().optional(),
	w: z.number().optional(),
	h: z.number().optional()
});
const PixelateOptionsSchema = z.union([PixelateSize, PixelateComplexOptionsSchema]);
function applyKernel(image, 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 = image.getPixelIndex(x + kx - size, y + ky - size);
		value[0] += image.bitmap.data[idx] * kernel[kx][ky];
		value[1] += image.bitmap.data[idx + 1] * kernel[kx][ky];
		value[2] += image.bitmap.data[idx + 2] * kernel[kx][ky];
		value[3] += image.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
	};
}
const HueActionSchema = z.object({
	apply: z.literal("hue"),
	params: z.tuple([z.number().min(-360).max(360)])
});
const SpinActionSchema = z.object({
	apply: z.literal("spin"),
	params: z.tuple([z.number().min(-360).max(360)])
});
const LightenActionSchema = z.object({
	apply: z.literal("lighten"),
	params: z.tuple([z.number().min(0).max(100)]).optional()
});
const RGBColorSchema = z.object({
	r: z.number().min(0).max(255),
	g: z.number().min(0).max(255),
	b: z.number().min(0).max(255)
});
const MixActionSchema = z.object({
	apply: z.literal("mix"),
	params: z.union([z.tuple([RGBColorSchema]), z.tuple([RGBColorSchema, z.number().min(0).max(100)])])
});
const TintActionSchema = z.object({
	apply: z.literal("tint"),
	params: z.tuple([z.number().min(0).max(100)]).optional()
});
const ShadeActionSchema = z.object({
	apply: z.literal("shade"),
	params: z.tuple([z.number().min(0).max(100)]).optional()
});
const XorActionSchema = z.object({
	apply: z.literal("xor"),
	params: z.tuple([RGBColorSchema])
});
const RedActionSchema = z.object({
	apply: z.literal("red"),
	params: z.tuple([z.number().min(-255).max(255)])
});
const GreenActionSchema = z.object({
	apply: z.literal("green"),
	params: z.tuple([z.number().min(-255).max(255)])
});
const BlueActionSchema = z.object({
	apply: z.literal("blue"),
	params: z.tuple([z.number().min(-255).max(255)])
});
const BrightenActionSchema = z.object({
	apply: z.literal("brighten"),
	params: z.tuple([z.number().min(0).max(100)]).optional()
});
const DarkenActionSchema = z.object({
	apply: z.literal("darken"),
	params: z.tuple([z.number().min(0).max(100)]).optional()
});
const DesaturateActionSchema = z.object({
	apply: z.literal("desaturate"),
	params: z.tuple([z.number().min(0).max(100)]).optional()
});
const SaturateActionSchema = z.object({
	apply: z.literal("saturate"),
	params: z.tuple([z.number().min(0).max(100)]).optional()
});
const GrayscaleActionSchema = z.object({
	apply: z.literal("greyscale"),
	params: z.tuple([]).optional()
});
const ColorActionNameSchema = z.union([
	HueActionSchema,
	SpinActionSchema,
	LightenActionSchema,
	MixActionSchema,
	TintActionSchema,
	ShadeActionSchema,
	XorActionSchema,
	RedActionSchema,
	GreenActionSchema,
	BlueActionSchema,
	BrightenActionSchema,
	DarkenActionSchema,
	DesaturateActionSchema,
	SaturateActionSchema,
	GrayscaleActionSchema
]);
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"
});
/**
* Get an image's histogram
* @return An object with an array of color occurrence counts for each channel (r,g,b)
*/
function histogram(image) {
	const histogram = {
		r: new Array(256).fill(0),
		g: new Array(256).fill(0),
		b: new Array(256).fill(0)
	};
	image.scan((_, __, index) => {
		histogram.r[image.bitmap.data[index + 0]]++;
		histogram.g[image.bitmap.data[index + 1]]++;
		histogram.b[image.bitmap.data[index + 2]]++;
	});
	return histogram;
}
/**
* Normalize values
* @param  value Pixel channel value.
* @param  min   Minimum value for channel
* @param  max   Maximum value for channel
*/
const normalizeValue = function(value, min, max) {
	return (value - min) * 255 / (max - min);
};
const getBounds = function(histogramChannel) {
	return [histogramChannel.findIndex((value) => value > 0), 255 - histogramChannel.slice().reverse().findIndex((value) => value > 0)];
};
const methods$14 = {
	normalize(image) {
		const h = histogram(image);
		const bounds = {
			r: getBounds(h.r),
			g: getBounds(h.g),
			b: getBounds(h.b)
		};
		image.scan((_, __, idx) => {
			const r = image.bitmap.data[idx + 0];
			const g = image.bitmap.data[idx + 1];
			const b = image.bitmap.data[idx + 2];
			image.bitmap.data[idx + 0] = normalizeValue(r, bounds.r[0], bounds.r[1]);
			image.bitmap.data[idx + 1] = normalizeValue(g, bounds.g[0], bounds.g[1]);
			image.bitmap.data[idx + 2] = normalizeValue(b, bounds.b[0], bounds.b[1]);
		});
		return image;
	},
	invert(image) {
		image.scan((_, __, idx) => {
			image.bitmap.data[idx] = 255 - image.bitmap.data[idx];
			image.bitmap.data[idx + 1] = 255 - image.bitmap.data[idx + 1];
			image.bitmap.data[idx + 2] = 255 - image.bitmap.data[idx + 2];
		});
		return image;
	},
	brightness(image, val) {
		if (typeof val !== "number") throw new Error("val must be numbers");
		image.scan((_, __, idx) => {
			image.bitmap.data[idx] = limit255(image.bitmap.data[idx] * val);
			image.bitmap.data[idx + 1] = limit255(image.bitmap.data[idx + 1] * val);
			image.bitmap.data[idx + 2] = limit255(image.bitmap.data[idx + 2] * val);
		});
		return image;
	},
	contrast(image, 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;
		}
		image.scan((_, __, idx) => {
			image.bitmap.data[idx] = adjust(image.bitmap.data[idx]);
			image.bitmap.data[idx + 1] = adjust(image.bitmap.data[idx + 1]);
			image.bitmap.data[idx + 2] = adjust(image.bitmap.data[idx + 2]);
		});
		return image;
	},
	posterize(image, n) {
		if (typeof n !== "number") throw new Error("n must be numbers");
		if (n < 2) n = 2;
		image.scan((_, __, idx) => {
			const r = image.bitmap.data[idx];
			const g = image.bitmap.data[idx + 1];
			const b = image.bitmap.data[idx + 2];
			image.bitmap.data[idx] = Math.floor(r / 255 * (n - 1)) / (n - 1) * 255;
			image.bitmap.data[idx + 1] = Math.floor(g / 255 * (n - 1)) / (n - 1) * 255;
			image.bitmap.data[idx + 2] = Math.floor(b / 255 * (n - 1)) / (n - 1) * 255;
		});
		return image;
	},
	greyscale(image) {
		image.scan((_, __, idx) => {
			const grey = .2126 * image.bitmap.data[idx] + .7152 * image.bitmap.data[idx + 1] + .0722 * image.bitmap.data[idx + 2];
			image.bitmap.data[idx] = grey;
			image.bitmap.data[idx + 1] = grey;
			image.bitmap.data[idx + 2] = grey;
		});
		return image;
	},
	opacity(image, 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");
		image.scan((_, __, idx) => {
			const v = image.bitmap.data[idx + 3] * f;
			image.bitmap.data[idx + 3] = v;
		});
		return image;
	},
	sepia(image) {
		image.scan((_, __, idx) => {
			let red = image.bitmap.data[idx];
			let green = image.bitmap.data[idx + 1];
			let blue = image.bitmap.data[idx + 2];
			red = red * .393 + green * .769 + blue * .189;
			green = red * .349 + green * .686 + blue * .168;
			blue = red * .272 + green * .534 + blue * .131;
			image.bitmap.data[idx] = red < 255 ? red : 255;
			image.bitmap.data[idx + 1] = green < 255 ? green : 255;
			image.bitmap.data[idx + 2] = blue < 255 ? blue : 255;
		});
		return image;
	},
	fade(image, 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(image, 1 - f);
	},
	convolution(image, options) {
		const parsed = ConvolutionOptionsSchema.parse(options);
		const { kernel, edgeHandling = Edge.EXTEND } = "kernel" in parsed ? parsed : {
			kernel: parsed,
			edgeHandling: void 0
		};
		if (!kernel[0]) throw new Error("kernel must be a matrix");
		const newData = Buffer.from(image.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;
		image.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 = image.getPixelIndex(xi, yi, edgeHandling);
				if (idxi === -1) {
					bi = 0;
					gi = 0;
					ri = 0;
				} else {
					ri = image.bitmap.data[idxi + 0];
					gi = image.bitmap.data[idxi + 1];
					bi = image.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;
		});
		image.bitmap.data = newData;
		return image;
	},
	opaque(image) {
		image.scan((_, __, idx) => {
			image.bitmap.data[idx + 3] = 255;
		});
		return image;
	},
	pixelate(image, options) {
		const parsed = PixelateOptionsSchema.parse(options);
		const { size, x = 0, y = 0, w = image.bitmap.width - x, h = image.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 = clone(image);
		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);
			image.bitmap.data[idx] = value[0];
			image.bitmap.data[idx + 1] = value[1];
			image.bitmap.data[idx + 2] = value[2];
			image.bitmap.data[idx + 3] = value[3];
		});
		return image;
	},
	convolute(image, options) {
		const parsed = ConvoluteOptionsSchema.parse(options);
		const { kernel, x = 0, y = 0, w = image.bitmap.width - x, h = image.bitmap.height - y } = "kernel" in parsed ? parsed : { kernel: parsed };
		const source = clone(image);
		scan(source, x, y, w, h, (xx, yx, idx) => {
			const value = applyKernel(source, kernel, xx, yx);
			image.bitmap.data[idx] = limit255(value[0]);
			image.bitmap.data[idx + 1] = limit255(value[1]);
			image.bitmap.data[idx + 2] = limit255(value[2]);
			image.bitmap.data[idx + 3] = limit255(value[3]);
		});
		return image;
	},
	color(image, 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;
		});
		image.scan((_, __, idx) => {
			let clr = {
				r: image.bitmap.data[idx],
				g: image.bitmap.data[idx + 1],
				b: image.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();
				}
			});
			image.bitmap.data[idx] = clr.r;
			image.bitmap.data[idx + 1] = clr.g;
			image.bitmap.data[idx + 2] = clr.b;
		});
		return image;
	}
};
//#endregion
//#region node_modules/@jimp/file-ops/dist/esm/index.js
var import_await_to_js_umd = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function(global, factory) {
		typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : factory(global.awaitToJs = {});
	})(exports, (function(exports$1) {
		"use strict";
		/**
		* @param { Promise } promise
		* @param { Object= } errorExt - Additional Information you can pass to the err object
		* @return { Promise }
		*/
		function to(promise, errorExt) {
			return promise.then(function(data) {
				return [null, data];
			}).catch(function(err) {
				if (errorExt) Object.assign(err, errorExt);
				return [err, void 0];
			});
		}
		exports$1.to = to;
		exports$1["default"] = to;
		Object.defineProperty(exports$1, "__esModule", { value: true });
	}));
})))();
const readFile = promises.readFile;
const writeFile = promises.writeFile;
//#endregion
//#region node_modules/mime/Mime.js
var require_Mime = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* @param typeMap [Object] Map of MIME type -> Array[extensions]
	* @param ...
	*/
	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);
	}
	/**
	* Define mimetype -> extension mappings.  Each key is a mime-type that maps
	* to an array of extensions associated with the type.  The first extension is
	* used as the default extension for the type.
	*
	* e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
	*
	* If a type declares an extension that has already been defined, an error will
	* be thrown.  To suppress this error and force the extension to be associated
	* with the new type, pass `force`=true.  Alternatively, you may prefix the
	* extension with "*" to map the type to extension, without mapping the
	* extension to the type.
	*
	* e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
	*
	*
	* @param map (Object) type definitions
	* @param force (Boolean) if true, force overriding of existing definitions
	*/
	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);
			}
		}
	};
	/**
	* Lookup a mime type based on extension
	*/
	Mime.prototype.getType = function(path) {
		path = String(path);
		let last = path.replace(/^.*[/\\]/, "").toLowerCase();
		let ext = last.replace(/^.*\./, "").toLowerCase();
		let hasPath = last.length < path.length;
		return (ext.length < last.length - 1 || !hasPath) && this._types[ext] || null;
	};
	/**
	* Return file extension associated with a mime type
	*/
	Mime.prototype.getExtension = function(type) {
		type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
		return type && this._extensions[type.toLowerCase()] || null;
	};
	module.exports = Mime;
}));
//#endregion
//#region node_modules/mime/types/standard.js
var require_standard = /* @__PURE__ */ __commonJSMin(((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"]
	};
}));
//#endregion
//#region node_modules/@jimp/core/dist/esm/utils/constants.js
var import_lite = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = new (require_Mime())(require_standard());
})))(), 1);
var HorizontalAlign;
(function(HorizontalAlign) {
	HorizontalAlign[HorizontalAlign["LEFT"] = 1] = "LEFT";
	HorizontalAlign[HorizontalAlign["CENTER"] = 2] = "CENTER";
	HorizontalAlign[HorizontalAlign["RIGHT"] = 4] = "RIGHT";
})(HorizontalAlign || (HorizontalAlign = {}));
var VerticalAlign;
(function(VerticalAlign) {
	VerticalAlign[VerticalAlign["TOP"] = 8] = "TOP";
	VerticalAlign[VerticalAlign["MIDDLE"] = 16] = "MIDDLE";
	VerticalAlign[VerticalAlign["BOTTOM"] = 32] = "BOTTOM";
})(VerticalAlign || (VerticalAlign = {}));
/**
* How to blend two images together
*/
var BlendMode;
(function(BlendMode) {
	/**
	* Composite the source image over the destination image.
	* This is the default value. It represents the most intuitive case, where shapes are painted on top of what is below, with transparent areas showing the destination layer.
	*/
	BlendMode["SRC_OVER"] = "srcOver";
	/** Composite the source image under the destination image. */
	BlendMode["DST_OVER"] = "dstOver";
	/**
	* Multiply the color components of the source and destination images.
	* This can only result in the same or darker colors (multiplying by white, 1.0, results in no change; multiplying by black, 0.0, results in black).
	* When compositing two opaque images, this has similar effect to overlapping two transparencies on a projector.
	*
	* This mode is useful for coloring shadows.
	*/
	BlendMode["MULTIPLY"] = "multiply";
	/**
	* The Add mode adds the color information of the base layers and the blending layer.
	* In digital terms, adding color increases the brightness.
	*/
	BlendMode["ADD"] = "add";
	/**
	* Multiply the inverse of the components of the source and destination images, and inverse the result.
	* Inverting the components means that a fully saturated channel (opaque white) is treated as the value 0.0, and values normally treated as 0.0 (black, transparent) are treated as 1.0.
	* This is essentially the same as modulate blend mode, but with the values of the colors inverted before the multiplication and the result being inverted back before rendering.
	* This can only result in the same or lighter colors (multiplying by black, 1.0, results in no change; multiplying by white, 0.0, results in white). Similarly, in the alpha channel, it can only result in more opaque colors.
	* This has similar effect to two projectors displaying their images on the same screen simultaneously.
	*/
	BlendMode["SCREEN"] = "screen";
	/**
	* Multiply the components of the source and destination images after adjusting them to favor the destination.
	* Specifically, if the destination value is smaller, this multiplies it with the source value, whereas is the source value is smaller, it multiplies the inverse of the source value with the inverse of the destination value, then inverts the result.
	* Inverting the components means that a fully saturated channel (opaque white) is treated as the value 0.0, and values normally treated as 0.0 (black, transparent) are treated as 1.0.
	*
	* The Overlay mode behaves like Screen mode in bright areas, and like Multiply mode in darker areas.
	* With this mode, the bright areas will look brighter and the dark areas will look darker.
	*/
	BlendMode["OVERLAY"] = "overlay";
	/**
	* Composite the source and destination image by choosing the lowest value from each color channel.
	* The opacity of the output image is computed in the same way as for srcOver.
	*/
	BlendMode["DARKEN"] = "darken";
	/**
	* Composite the source and destination image by choosing the highest value from each color channel.
	* The opacity of the output image is computed in the same way as for srcOver.
	*/
	BlendMode["LIGHTEN"] = "lighten";
	/**
	* Multiply the components of the source and destination images after adjusting them to favor the source.
	* Specifically, if the source value is smaller, this multiplies it with the destination value, whereas is the destination value is smaller, it multiplies the inverse of the destination value with the inverse of the source value, then inverts the result.
	* Inverting the components means that a fully saturated channel (opaque white) is treated as the value 0.0, and values normally treated as 0.0 (black, transparent) are treated as 1.0.
	*
	* The effect of the Hard light mode depends on the density of the superimposed color. Using bright colors on the blending layer will create a brighter effect like the Screen modes, while dark colors will create darker colors like the Multiply mode.
	*/
	BlendMode["HARD_LIGHT"] = "hardLight";
	/**
	* Subtract the smaller value from the bigger value for each channel.
	* Compositing black has no effect; compositing white inverts the colors of the other image.
	* The opacity of the output image is computed in the same way as for srcOver.
	* The effect is similar to exclusion but harsher.
	*/
	BlendMode["DIFFERENCE"] = "difference";
	/**
	* Subtract double the product of the two images from the sum of the two images.
	* Compositing black has no effect; compositing white inverts the colors of the other image.
	* The opacity of the output image is computed in the same way as for srcOver.
	* The effect is similar to difference but softer.
	*/
	BlendMode["EXCLUSION"] = "exclusion";
})(BlendMode || (BlendMode = {}));
//#endregion
//#region node_modules/@jimp/core/dist/esm/utils/composite-modes.js
var composite_modes_exports = /* @__PURE__ */ __exportAll({
	add: () => add,
	darken: () => darken,
	difference: () => difference,
	dstOver: () => dstOver,
	exclusion: () => exclusion,
	hardLight: () => hardLight,
	lighten: () => lighten,
	multiply: () => multiply,
	names: () => names,
	overlay: () => overlay,
	screen: () => screen,
	srcOver: () => srcOver
});
function srcOver(src, dst, ops = 1) {
	src.a *= ops;
	const a = dst.a + src.a - dst.a * src.a;
	return {
		r: (src.r * src.a + dst.r * dst.a * (1 - src.a)) / a,
		g: (src.g * src.a + dst.g * dst.a * (1 - src.a)) / a,
		b: (src.b * src.a + dst.b * dst.a * (1 - src.a)) / a,
		a
	};
}
function dstOver(src, dst, ops = 1) {
	src.a *= ops;
	const a = dst.a + src.a - dst.a * src.a;
	return {
		r: (dst.r * dst.a + src.r * src.a * (1 - dst.a)) / a,
		g: (dst.g * dst.a + src.g * src.a * (1 - dst.a)) / a,
		b: (dst.b * dst.a + src.b * src.a * (1 - dst.a)) / a,
		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;
	return {
		r: (sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a,
		g: (sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a,
		b: (sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a,
		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;
	return {
		r: (sra + dra) / a,
		g: (sga + dga) / a,
		b: (sba + dba) / a,
		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;
	return {
		r: (sra * dst.a + dra * src.a - sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a,
		g: (sga * dst.a + dga * src.a - sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a,
		b: (sba * dst.a + dba * src.a - sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a,
		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;
	return {
		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,
		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,
		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,
		a
	};
}
function darken(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;
	return {
		r: (Math.min(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a,
		g: (Math.min(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a,
		b: (Math.min(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a,
		a
	};
}
function lighten(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;
	return {
		r: (Math.max(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a,
		g: (Math.max(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a,
		b: (Math.max(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a,
		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;
	return {
		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,
		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,
		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,
		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;
	return {
		r: (sra + dra - 2 * Math.min(sra * dst.a, dra * src.a)) / a,
		g: (sga + dga - 2 * Math.min(sga * dst.a, dga * src.a)) / a,
		b: (sba + dba - 2 * Math.min(sba * dst.a, dba * src.a)) / a,
		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;
	return {
		r: (sra * dst.a + dra * src.a - 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a,
		g: (sga * dst.a + dga * src.a - 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a,
		b: (sba * dst.a + dba * src.a - 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a,
		a
	};
}
const names = [
	srcOver,
	dstOver,
	multiply,
	add,
	screen,
	overlay,
	darken,
	lighten,
	hardLight,
	difference,
	exclusion
];
//#endregion
//#region 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 = composite_modes_exports[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;
}
//#endregion
//#region node_modules/exif-parser/lib/jpeg.js
var require_jpeg = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = {
		parseSections: function(stream, iterator) {
			var len, markerType;
			stream.setBigEndian(true);
			while (stream.remainingLength() > 0 && markerType !== 218) {
				if (stream.nextUInt8() !== 255) throw new Error("Invalid JPEG section offset");
				markerType = stream.nextUInt8();
				if (markerType >= 208 && markerType <= 217 || markerType === 218) len = 0;
				else len = stream.nextUInt16() - 2;
				iterator(markerType, stream.branch(0, len));
				stream.skip(len);
			}
		},
		getSizeFromSOFSection: function(stream) {
			stream.skip(1);
			return {
				height: stream.nextUInt16(),
				width: stream.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;
		}
	};
}));
//#endregion
//#region node_modules/exif-parser/lib/exif.js
var require_exif = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	function readExifValue(format, stream) {
		switch (format) {
			case 1: return stream.nextUInt8();
			case 3: return stream.nextUInt16();
			case 4: return stream.nextUInt32();
			case 5: return [stream.nextUInt32(), stream.nextUInt32()];
			case 6: return stream.nextInt8();
			case 8: return stream.nextUInt16();
			case 9: return stream.nextUInt32();
			case 10: return [stream.nextInt32(), stream.nextInt32()];
			case 11: return stream.nextFloat();
			case 12: return stream.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, stream) {
		var tagType = stream.nextUInt16(), format = stream.nextUInt16(), bytesPerComponent = getBytesPerComponent(format), components = stream.nextUInt32(), valueBytes = bytesPerComponent * components, values, c;
		if (valueBytes > 4) stream = tiffMarker.openWithOffset(stream.nextUInt32());
		if (format === 2) {
			values = stream.nextString(components);
			var lastNull = values.indexOf("\0");
			if (lastNull !== -1) values = values.substr(0, lastNull);
		} else if (format === 7) values = stream.nextBuffer(components);
		else if (format !== 0) {
			values = [];
			for (c = 0; c < components; ++c) values.push(readExifValue(format, stream));
		}
		if (valueBytes < 4) stream.skip(4 - valueBytes);
		return [
			tagType,
			values,
			format
		];
	}
	function readIFDSection(tiffMarker, stream, iterator) {
		var numberOfEntries = stream.nextUInt16(), tag, i;
		for (i = 0; i < numberOfEntries; ++i) {
			tag = readExifTag(tiffMarker, stream);
			iterator(tag[0], tag[1], tag[2]);
		}
	}
	function readHeader(stream) {
		if (stream.nextString(6) !== "Exif\0\0") throw new Error("Invalid EXIF header");
		var tiffMarker = stream.mark();
		var tiffHeader = stream.nextUInt16();
		if (tiffHeader === 18761) stream.setBigEndian(false);
		else if (tiffHeader === 19789) stream.setBigEndian(true);
		else throw new Error("Invalid TIFF header");
		if (stream.nextUInt16() !== 42) throw new Error("Invalid TIFF data");
		return tiffMarker;
	}
	module.exports = {
		IFD0: 1,
		IFD1: 2,
		GPSIFD: 3,
		SubIFD: 4,
		InteropIFD: 5,
		parseTags: function(stream, iterator) {
			var tiffMarker;
			try {
				tiffMarker = readHeader(stream);
			} catch (e) {
				return false;
			}
			var subIfdOffset, gpsOffset, interopOffset;
			var ifd0Stream = tiffMarker.openWithOffset(stream.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;
		}
	};
}));
//#endregion
//#region node_modules/exif-parser/lib/date.js
var require_date = /* @__PURE__ */ __commonJSMin(((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 hours = timeParts[0];
		var minutes = timeParts[1];
		var seconds = timeParts[2];
		return Date.UTC(year, month, day, hours, minutes, seconds, 0) / 1e3;
	}
	function parseDateWithTimezoneFormat(dateTimeStr) {
		var dateParts = dateTimeStr.substr(0, 10).split("-");
		var timeParts = dateTimeStr.substr(11, 8).split(":");
		var timezoneParts = dateTimeStr.substr(19, 6).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(" ");
		var timestamp = parseDateTimeParts(parts[0].split(":"), parts[1].split(":"));
		if (typeof timestamp === "number" && !isNaN(timestamp)) return timestamp;
	}
	function parseExifDate(dateTimeStr) {
		var isSpecFormat = dateTimeStr.length === 19 && dateTimeStr.charAt(4) === ":";
		if (dateTimeStr.length === 25 && dateTimeStr.charAt(10) === "T") return parseDateWithTimezoneFormat(dateTimeStr);
		else if (isSpecFormat) return parseDateWithSpecFormat(dateTimeStr);
	}
	module.exports = {
		parseDateWithSpecFormat,
		parseDateWithTimezoneFormat,
		parseExifDate
	};
}));
//#endregion
//#region node_modules/exif-parser/lib/simplify.js
var require_simplify = /* @__PURE__ */ __commonJSMin(((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 degreeNumRef = getTagValue({
						section: t.section,
						type: t.refType,
						name: t.refName
					}) === t.posVal ? 1 : -1;
					setTagValue(t, (degreeVal[0] + degreeVal[1] / 60 + degreeVal[2] / 3600) * degreeNumRef);
				}
			});
		},
		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;
		}
	};
}));
//#endregion
//#region node_modules/exif-parser/lib/exif-tags.js
var require_exif_tags = /* @__PURE__ */ __commonJSMin(((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",
			65e3: "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"
		}
	};
}));
//#endregion
//#region node_modules/exif-parser/lib/parser.js
var require_parser$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var jpeg = require_jpeg(), exif = require_exif(), 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 stream = this._getThumbnailStream(), size;
			jpeg.parseSections(stream, function(sectionType, sectionStream) {
				if (jpeg.getSectionName(sectionType).name === "SOF") size = jpeg.getSizeFromSOFSection(sectionStream);
			});
			return size;
		}
	};
	function Parser(stream) {
		this.stream = stream;
		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(), stream = 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;
					}
				};
			}
			jpeg.parseSections(stream, 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 name = (ifdSection === exif.GPSIFD ? tagNames.gps : tagNames.exif)[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 && jpeg.getSectionName(sectionType).name === "SOF") imageSize = jpeg.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;
}));
//#endregion
//#region node_modules/exif-parser/lib/dom-bufferstream.js
var require_dom_bufferstream = /* @__PURE__ */ __commonJSMin(((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 self = this;
			return {
				openWithOffset: function(offset) {
					offset = (offset || 0) + this.offset;
					return new DOMBufferStream(self.arrayBuffer, offset, self.arrayBuffer.byteLength - offset, !self.littleEndian, self.global, self.parentOffset);
				},
				offset: this.offset,
				getParentOffset: function() {
					return self.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;
}));
//#endregion
//#region node_modules/exif-parser/lib/bufferstream.js
var require_bufferstream = /* @__PURE__ */ __commonJSMin(((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 self = this;
			return {
				openWithOffset: function(offset) {
					offset = (offset || 0) + this.offset;
					return new BufferStream(self.buffer, offset, self.endPosition - offset, self.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;
}));
//#endregion
//#region node_modules/@jimp/core/dist/esm/utils/image-bitmap.js
var import_exif_parser = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
	var Parser = require_parser$1();
	function getGlobal() {
		return (0, eval)("this");
	}
	module.exports = { create: function(buffer, global) {
		global = global || getGlobal();
		if (buffer instanceof global.ArrayBuffer) return new Parser(new (require_dom_bufferstream())(buffer, 0, buffer.byteLength, true, global));
		else return new Parser(new (require_bufferstream())(buffer, 0, buffer.length, true));
	} };
})))(), 1);
/**
* Obtains image orientation from EXIF metadata.
*
* @param img a Jimp image object
* @returns a number 1-8 representing EXIF orientation,
*          in particular 1 if orientation tag is missing
*/
function getExifOrientation(img) {
	const _exif = img._exif;
	return _exif && _exif.tags && _exif.tags.Orientation || 1;
}
/**
* Returns a function which translates EXIF-rotated coordinates into
* non-rotated ones.
*
* Transformation reference: http://sylvana.net/jpegcrop/exif_orientation.html.
*
* @param img a Jimp image object
* @returns transformation function for transformBitmap().
*/
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;
	}
}
/**
* Transforms bitmap in place (moves pixels around) according to given
* transformation function.
*
* @param img a Jimp image object, which bitmap is supposed to
*        be transformed
* @param width bitmap width after the transformation
* @param height bitmap height after the transformation
* @param transformation transformation function which defines pixel
*        mapping between new and source bitmap. It takes a pair of coordinates
*        in the target, and returns a respective pair of coordinates in
*        the source bitmap, i.e. has following form:
*        `function(new_x, new_y) { return [src_x, src_y] }`.
*/
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;
}
/**
* Automagically rotates an image based on its EXIF data (if present).
* @param img  a Jimp image object
*/
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(image, buffer) {
	try {
		image._exif = import_exif_parser.default.create(buffer).parse();
		exifRotate(image);
	} catch {}
}
//#endregion
//#region node_modules/@jimp/core/dist/esm/index.js
const emptyBitmap = {
	data: Buffer.alloc(0),
	width: 0,
	height: 0
};
/**
* Prepare a Buffer object from the arrayBuffer.
*/
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;
}
/**
* Create a Jimp class that support the given image formats and methods
*/
function createJimp({ plugins: pluginsArg, formats: formatsArg } = {}) {
	const plugins = pluginsArg || [];
	const formats = (formatsArg || []).map((format) => format());
	const CustomJimp = class Jimp {
		/**
		* The bitmap data of the image
		*/
		bitmap = emptyBitmap;
		/**  Default color to use for new pixels */
		background = 0;
		/** Formats that can be used with Jimp */
		formats = [];
		/** The original MIME type of the image */
		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 methods of plugins) for (const key in methods) this[key] = (...args) => {
				const result = methods[key]?.(this, ...args);
				if (typeof result === "object" && "bitmap" in result) {
					this.bitmap = result.bitmap;
					return this;
				}
				return result;
			};
		}
		/**
		* Create a Jimp instance from a URL, a file path, or a Buffer
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* // Read from a file path
		* const image = await Jimp.read("test/image.png");
		*
		* // Read from a URL
		* const image = await Jimp.read("https://upload.wikimedia.org/wikipedia/commons/0/01/Bot-Test.jpg");
		* ```
		*/
		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 (0, import_await_to_js_umd.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 (0, import_await_to_js_umd.to)(response.arrayBuffer());
			if (arrayBufferErr) throw new Error(`Could not load Buffer from ${url}`);
			const buffer = bufferFromArrayBuffer(data);
			return this.fromBuffer(buffer, options);
		}
		/**
		* Create a Jimp instance from a bitmap.
		* The difference between this and just using the constructor is that this will
		* convert raw image data into the bitmap format that Jimp uses.
		*
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = Jimp.fromBitmap({
		*   data: Buffer.from([
		*     0xffffffff, 0xffffffff, 0xffffffff,
		*     0xffffffff, 0xffffffff, 0xffffffff,
		*     0xffffffff, 0xffffffff, 0xffffffff,
		*   ]),
		*   width: 3,
		*   height: 3,
		* });
		* ```
		*/
		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
			});
		}
		/**
		* Parse a bitmap with the loaded image types.
		*
		* @param buffer Raw image data
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const buffer = await fs.readFile("test/image.png");
		* const image = await Jimp.fromBuffer(buffer);
		* ```
		*/
		static async fromBuffer(buffer, options) {
			const actualBuffer = buffer instanceof ArrayBuffer ? bufferFromArrayBuffer(buffer) : buffer;
			const mime = await fileType.fromBuffer(actualBuffer);
			if (!mime || !mime.mime) throw new Error("Could not find MIME for Buffer");
			const format = formats.find((format) => format.mime === mime.mime);
			if (!format || !format.decode) throw new Error(`Mime type ${mime.mime} does not support decoding`);
			const image = new CustomJimp(await format.decode(actualBuffer, options?.[format.mime]));
			image.mime = mime.mime;
			attemptExifRotate(image, actualBuffer);
			return image;
		}
		/**
		* Nicely format Jimp object when sent to the console e.g. console.log(image)
		* @returns Pretty printed jimp object
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = await Jimp.read("test/image.png");
		*
		* console.log(image);
		* ```
		*/
		inspect() {
			return "<Jimp " + (this.bitmap === emptyBitmap ? "pending..." : this.bitmap.width + "x" + this.bitmap.height) + ">";
		}
		/**
		* Nicely format Jimp object when converted to a string
		* @returns pretty printed
		*/
		toString() {
			return "[object Jimp]";
		}
		/** Get the width of the image */
		get width() {
			return this.bitmap.width;
		}
		/** Get the height of the image */
		get height() {
			return this.bitmap.height;
		}
		/**
		* Converts the Jimp instance to an image buffer
		* @param mime The mime type to export to
		* @param options The options to use when exporting
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		* import { promises as fs } from "fs";
		*
		* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
		*
		* await image.write("test/output.jpeg", {
		*   quality: 50,
		* });
		* ```
		*/
		async getBuffer(mime, options) {
			const format = this.formats.find((format) => format.mime === mime);
			if (!format || !format.encode) throw new Error(`Unsupported MIME type: ${mime}`);
			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);
		}
		/**
		* Converts the image to a base 64 string
		*
		* @param mime The mime type to export to
		* @param options The options to use when exporting
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = Jimp.fromBuffer(Buffer.from([
		*   0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
		*   0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
		*   0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
		* ]));
		*
		* const base64 = image.getBase64("image/jpeg", {
		*   quality: 50,
		* });
		* ```
		*/
		async getBase64(mime, options) {
			const data = await this.getBuffer(mime, options);
			return "data:" + mime + ";base64," + data.toString("base64");
		}
		/**
		* Write the image to a file
		* @param path the path to write the image to
		* @param options the options to use when writing the image
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = Jimp.fromBuffer(Buffer.from([
		*   0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
		*   0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
		*   0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
		* ]));
		*
		* await image.write("test/output.png");
		* ```
		*/
		async write(path, options) {
			const mimeType = import_lite.default.getType(path);
			await writeFile(path, await this.getBuffer(mimeType, options));
		}
		/**
		* Clone the image into a new Jimp instance.
		* @param this
		* @returns A new Jimp instance
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
		*
		* const clone = image.clone();
		* ```
		*/
		clone() {
			return new CustomJimp({
				...this.bitmap,
				data: Buffer.from(this.bitmap.data)
			});
		}
		/**
		* Returns the offset of a pixel in the bitmap buffer
		* @param x the x coordinate
		* @param y the y coordinate
		* @param edgeHandling (optional) define how to sum pixels from outside the border
		* @returns the index of the pixel or -1 if not found
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
		*
		* image.getPixelIndex(1, 1); // 2
		* ```
		*/
		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;
		}
		/**
		* Returns the hex color value of a pixel
		* @param x the x coordinate
		* @param y the y coordinate
		* @returns the color of the pixel
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
		*
		* image.getPixelColor(1, 1); // 0xffffffff
		* ```
		*/
		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);
		}
		/**
		* Sets the hex colour value of a pixel
		*
		* @param hex color to set
		* @param x the x coordinate
		* @param y the y coordinate
		*
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
		*
		* image.setPixelColor(0xff0000ff, 0, 0);
		* ```
		*/
		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;
		}
		/**
		* Determine if the image contains opaque pixels.
		*
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = new Jimp({ width: 3, height: 3, color: 0xffffffaa });
		* const image2 = new Jimp({ width: 3, height: 3, color: 0xff0000ff });
		*
		* image.hasAlpha(); // false
		* image2.hasAlpha(); // true
		* ```
		*/
		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;
		}
		/**
		* Composites a source image over to this image respecting alpha channels
		* @param src the source Jimp instance
		* @param x the x position to blit the image
		* @param y the y position to blit the image
		* @param options determine what mode to use
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = new Jimp({ width: 10, height: 10, color: 0xffffffff });
		* const image2 = new Jimp({ width: 3, height: 3, color: 0xff0000ff });
		*
		* image.composite(image2, 3, 3);
		* ```
		*/
		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);
		}
		/**
		* Iterate scan through a region of the bitmap
		* @param x the x coordinate to begin the scan at
		* @param y the y coordinate to begin the scan at
		* @param w the width of the scan region
		* @param h the height of the scan region
		* @example
		* ```ts
		* import { Jimp } from "jimp";
		*
		* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
		*
		* for (const { x, y, idx, image } of j.scanIterator()) {
		*   // do something with the pixel
		* }
		* ```
		*/
		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;
}
//#endregion
//#region node_modules/@jimp/plugin-resize/dist/esm/constants.js
/**
* What resizing algorithm to use.
*/
var ResizeStrategy;
(function(ResizeStrategy) {
	/**
	* Nearest Neighbor resizing is a method used in image processing that assigns the value of the nearest pixel to the output pixel when resizing an image.
	* While fast, it can lead to lower quality outputs with noticeable pixelation, especially at larger scaling factors.
	*/
	ResizeStrategy["NEAREST_NEIGHBOR"] = "nearestNeighbor";
	/**
	* Bilinear resizing is an image scaling method that uses the weighted average of the four nearest pixel values, providing smoother gradients than nearest neighbor resizing.
	* It's computationally more intense than nearest neighbor but results in images of higher quality and fewer artifacts.
	*/
	ResizeStrategy["BILINEAR"] = "bilinearInterpolation";
	/**
	* Bicubic resizing is an image interpolation method that uses the values of the nearest 16 pixels in the input image to calculate the output pixel value, providing even more smoothness and sharpness than bilinear resizing.
	* Although it's computationally more expensive than bilinear and nearest neighbor, it produces higher quality images, making it ideal for photographic image scaling.
	*/
	ResizeStrategy["BICUBIC"] = "bicubicInterpolation";
	/**
	* Hermite resizing is an image resizing method that uses Hermite interpolation, a mathematical formula, to determine the values of output pixels based on a weighted average of the surrounding pixels.
	* Although slower than some simpler techniques like bilinear or nearest neighbor, Hermite resizing can produce higher quality visuals and detailed renderings with less blurring.
	*/
	ResizeStrategy["HERMITE"] = "hermiteInterpolation";
	ResizeStrategy["BEZIER"] = "bezierInterpolation";
})(ResizeStrategy || (ResizeStrategy = {}));
//#endregion
//#region 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 [];
	}
};
//#endregion
//#region node_modules/@jimp/plugin-resize/dist/esm/modules/resize2.js
/**
* Copyright (c) 2015 Guyon Roche
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
const 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 = .5 * (x2 - x0);
			const c2 = x0 - 2.5 * x1 + 2 * x2 - .5 * x3;
			const c3 = .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);
	}
};
//#endregion
//#region node_modules/@jimp/plugin-resize/dist/esm/index.js
const ResizeOptionsSchema = z.union([z.object({
	w: z.number().min(0),
	h: z.number().min(0).optional(),
	mode: z.nativeEnum(ResizeStrategy).optional()
}), z.object({
	w: z.number().min(0).optional(),
	h: z.number().min(0),
	mode: z.nativeEnum(ResizeStrategy).optional()
})]);
const ScaleToFitOptionsSchema = z.object({
	w: z.number().min(0),
	h: z.number().min(0),
	mode: z.nativeEnum(ResizeStrategy).optional()
});
const ScaleComplexOptionsSchema = z.object({
	f: z.number().min(0),
	mode: z.nativeEnum(ResizeStrategy).optional()
});
const methods$13 = {
	resize(image, options) {
		const { mode } = ResizeOptionsSchema.parse(options);
		let w;
		let h;
		if (typeof options.w === "number") {
			w = options.w;
			h = options.h ?? image.bitmap.height * (w / image.bitmap.width);
		} else if (typeof options.h === "number") {
			h = options.h;
			w = options.w ?? image.bitmap.width * (h / image.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](image.bitmap, dst);
			image.bitmap = dst;
		} else new Resize(image.bitmap.width, image.bitmap.height, w, h, true, true, (buffer) => {
			image.bitmap.data = Buffer.from(buffer);
			image.bitmap.width = w;
			image.bitmap.height = h;
		}).resize(image.bitmap.data);
		return image;
	},
	scale(image, options) {
		const { f, mode } = typeof options === "number" ? { f: options } : ScaleComplexOptionsSchema.parse(options);
		const w = image.bitmap.width * f;
		const h = image.bitmap.height * f;
		return this.resize(image, {
			w,
			h,
			mode
		});
	},
	scaleToFit(image, options) {
		const { h, w, mode } = ScaleToFitOptionsSchema.parse(options);
		const f = w / h > image.bitmap.width / image.bitmap.height ? h / image.bitmap.height : w / image.bitmap.width;
		return this.scale(image, {
			f,
			mode
		});
	}
};
//#endregion
//#region node_modules/@jimp/plugin-contain/dist/esm/index.js
const ContainOptionsSchema = z.object({
	w: z.number(),
	h: z.number(),
	align: z.number().optional(),
	mode: z.nativeEnum(ResizeStrategy).optional()
});
const methods$12 = { contain(image, options) {
	const { w, h, align = HorizontalAlign.CENTER | VerticalAlign.MIDDLE, mode } = ContainOptionsSchema.parse(options);
	const hbits = align & 7;
	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 > image.bitmap.width / image.bitmap.height ? h / image.bitmap.height : w / image.bitmap.width;
	const c = methods$13.scale(clone(image), {
		f,
		mode
	});
	image = methods$13.resize(image, {
		w,
		h,
		mode
	});
	image.scan((_, __, idx) => {
		image.bitmap.data.writeUInt32BE(image.background, idx);
	});
	image = methods$17.blit(image, {
		src: c,
		x: (image.bitmap.width - c.bitmap.width) / 2 * alignH,
		y: (image.bitmap.height - c.bitmap.height) / 2 * alignV
	});
	return image;
} };
//#endregion
//#region node_modules/@jimp/plugin-crop/dist/esm/index.js
const CropOptionsSchema = z.object({
	x: z.number(),
	y: z.number(),
	w: z.number(),
	h: z.number()
});
const AutocropComplexOptionsSchema = z.object({
	tolerance: z.number().min(0).max(1).optional(),
	cropOnlyFrames: z.boolean().optional(),
	cropSymmetric: z.boolean().optional(),
	leaveBorder: z.number().optional(),
	ignoreSides: z.object({
		north: z.boolean().optional(),
		south: z.boolean().optional(),
		east: z.boolean().optional(),
		west: z.boolean().optional()
	}).optional()
});
const methods$11 = {
	crop(image, 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 === image.bitmap.width) {
			const start = w * y + x << 2;
			const end = start + (h * w << 2);
			image.bitmap.data = image.bitmap.data.slice(start, end);
		} else {
			const bitmap = Buffer.allocUnsafe(w * h * 4);
			let offset = 0;
			scan(image, x, y, w, h, function(_, __, idx) {
				const data = image.bitmap.data.readUInt32BE(idx);
				bitmap.writeUInt32BE(data, offset);
				offset += 4;
			});
			image.bitmap.data = bitmap;
		}
		image.bitmap.width = w;
		image.bitmap.height = h;
		return image;
	},
	autocrop(image, options = {}) {
		const { tolerance = 2e-4, cropOnlyFrames = true, cropSymmetric = false, leaveBorder = 0, ignoreSides: ignoreSidesArg } = typeof options === "number" ? { tolerance: options } : AutocropComplexOptionsSchema.parse(options);
		const w = image.bitmap.width;
		const h = image.bitmap.height;
		const minPixelsPerSide = 1;
		const ignoreSides = {
			north: false,
			south: false,
			east: false,
			west: false,
			...ignoreSidesArg
		};
		/**
		* All borders must be of the same color as the top left pixel, to be cropped.
		* It should be possible to crop borders each with a different color,
		* but since there are many ways for corners to intersect, it would
		* introduce unnecessary complexity to the algorithm.
		*/
		let colorTarget = image.getPixelColor(0, 0);
		const rgba1 = intToRGBA(colorTarget);
		let northPixelsToCrop = 0;
		let eastPixelsToCrop = 0;
		let southPixelsToCrop = 0;
		let westPixelsToCrop = 0;
		colorTarget = image.getPixelColor(0, 0);
		if (!ignoreSides.north) north: for (let y = 0; y < h - minPixelsPerSide; y++) {
			for (let x = 0; x < w; x++) if (colorDiff(rgba1, intToRGBA(image.getPixelColor(x, y))) > tolerance) break north;
			northPixelsToCrop++;
		}
		colorTarget = image.getPixelColor(w, 0);
		if (!ignoreSides.west) west: for (let x = 0; x < w - minPixelsPerSide; x++) {
			for (let y = 0 + northPixelsToCrop; y < h; y++) if (colorDiff(rgba1, intToRGBA(image.getPixelColor(x, y))) > tolerance) break west;
			westPixelsToCrop++;
		}
		colorTarget = image.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--) if (colorDiff(rgba1, intToRGBA(image.getPixelColor(x, y))) > tolerance) break south;
			southPixelsToCrop++;
		}
		colorTarget = image.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--) if (colorDiff(rgba1, intToRGBA(image.getPixelColor(x, y))) > 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(image, {
			x: westPixelsToCrop,
			y: northPixelsToCrop,
			w: widthOfRemainingPixels,
			h: heightOfRemainingPixels
		});
		return image;
	}
};
//#endregion
//#region node_modules/@jimp/plugin-cover/dist/esm/index.js
const CoverOptionsSchema = z.object({
	w: z.number(),
	h: z.number(),
	align: z.number().optional(),
	mode: z.nativeEnum(ResizeStrategy).optional()
});
const methods$10 = { cover(image, options) {
	const { w, h, align = HorizontalAlign.CENTER | VerticalAlign.MIDDLE, mode } = CoverOptionsSchema.parse(options);
	const hbits = align & 7;
	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 > image.bitmap.width / image.bitmap.height ? w / image.bitmap.width : h / image.bitmap.height;
	image = methods$13.scale(image, {
		f,
		mode
	});
	image = methods$11.crop(image, {
		x: (image.bitmap.width - w) / 2 * alignH,
		y: (image.bitmap.height - h) / 2 * alignV,
		w,
		h
	});
	return image;
} };
//#endregion
//#region node_modules/@jimp/plugin-displace/dist/esm/index.js
const DisplaceOptionsSchema = z.object({
	map: JimpClassSchema,
	offset: z.number()
});
const methods$9 = { displace(image, options) {
	const { map, offset } = DisplaceOptionsSchema.parse(options);
	const source = clone(image);
	image.scan((x, y, idx) => {
		let displacement = map.bitmap.data[idx] / 256 * offset;
		displacement = Math.round(displacement);
		const ids = image.getPixelIndex(x + displacement, y);
		image.bitmap.data[ids] = source.bitmap.data[idx];
		image.bitmap.data[ids + 1] = source.bitmap.data[idx + 1];
		image.bitmap.data[ids + 2] = source.bitmap.data[idx + 2];
	});
	return image;
} };
//#endregion
//#region node_modules/@jimp/plugin-dither/dist/esm/index.js
const methods$8 = { dither(image) {
	const rgb565Matrix = [
		1,
		9,
		3,
		11,
		13,
		5,
		15,
		7,
		4,
		12,
		2,
		10,
		16,
		8,
		14,
		6
	];
	image.scan((x, y, idx) => {
		const dither = rgb565Matrix[((y & 3) << 2) + x % 4];
		image.bitmap.data[idx] = Math.min(image.bitmap.data[idx] + dither, 255);
		image.bitmap.data[idx + 1] = Math.min(image.bitmap.data[idx + 1] + dither, 255);
		image.bitmap.data[idx + 2] = Math.min(image.bitmap.data[idx + 2] + dither, 255);
	});
	return image;
} };
//#endregion
//#region node_modules/@jimp/plugin-fisheye/dist/esm/index.js
const FisheyeOptionsSchema = z.object({ radius: z.number().min(0).optional() });
const methods$7 = { fisheye(image, options = {}) {
	const { radius = 2.5 } = FisheyeOptionsSchema.parse(options);
	const source = clone(image);
	const { width, height } = source.bitmap;
	source.scan((x, y) => {
		const hx = x / width;
		const hy = y / height;
		const rActual = Math.sqrt(Math.pow(hx - .5, 2) + Math.pow(hy - .5, 2));
		const rn = 2 * Math.pow(rActual, radius);
		const cosA = (hx - .5) / rActual;
		const sinA = (hy - .5) / rActual;
		const newX = Math.round((rn * cosA + .5) * width);
		const newY = Math.round((rn * sinA + .5) * height);
		const color = source.getPixelColor(newX, newY);
		image.setPixelColor(color, x, y);
	});
	image.setPixelColor(source.getPixelColor(width / 2, height / 2), width / 2, height / 2);
	return image;
} };
//#endregion
//#region node_modules/@jimp/plugin-flip/dist/esm/index.js
const FlipOptionsSchema = z.object({
	horizontal: z.boolean().optional(),
	vertical: z.boolean().optional()
});
const methods$6 = { flip(image, options) {
	const { horizontal, vertical } = FlipOptionsSchema.parse(options);
	const bitmap = Buffer.alloc(image.bitmap.data.length);
	image.scan((x, y, idx) => {
		const _x = horizontal ? image.bitmap.width - 1 - x : x;
		const _y = vertical ? image.bitmap.height - 1 - y : y;
		const _idx = image.bitmap.width * _y + _x << 2;
		const data = image.bitmap.data.readUInt32BE(idx);
		bitmap.writeUInt32BE(data, _idx);
	});
	image.bitmap.data = Buffer.from(bitmap);
	return image;
} };
//#endregion
//#region node_modules/any-base/src/converter.js
var require_converter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Converter
	*
	* @param {string|Array} srcAlphabet
	* @param {string|Array} dstAlphabet
	* @constructor
	*/
	function Converter(srcAlphabet, dstAlphabet) {
		if (!srcAlphabet || !dstAlphabet || !srcAlphabet.length || !dstAlphabet.length) throw new Error("Bad alphabet");
		this.srcAlphabet = srcAlphabet;
		this.dstAlphabet = dstAlphabet;
	}
	/**
	* Convert number from source alphabet to destination alphabet
	*
	* @param {string|Array} number - number represented as a string or array of points
	*
	* @returns {string|Array}
	*/
	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;
	};
	/**
	* Valid number with source alphabet
	*
	* @param {number} number
	*
	* @returns {boolean}
	*/
	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;
}));
//#endregion
//#region node_modules/@jimp/plugin-hash/dist/esm/phash.js
var import_any_base = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
	var Converter = require_converter();
	/**
	* Function get source and destination alphabet and return convert function
	*
	* @param {string|Array} srcAlphabet
	* @param {string|Array} dstAlphabet
	*
	* @returns {function(number|Array)}
	*/
	function anyBase(srcAlphabet, dstAlphabet) {
		var converter = new Converter(srcAlphabet, dstAlphabet);
		/**
		* Convert function
		*
		* @param {string|Array} number
		*
		* @return {string|Array} number
		*/
		return function(number) {
			return converter.convert(number);
		};
	}
	anyBase.BIN = "01";
	anyBase.OCT = "01234567";
	anyBase.DEC = "0123456789";
	anyBase.HEX = "0123456789abcdef";
	module.exports = anyBase;
})))(), 1);
var ImagePHash = class {
	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;
	}
	/**
	* Returns a 'binary string' (like. 001010111011100010) which is easy to do a hamming distance on.
	*/
	getHash(img) {
		img = methods$13.resize(clone(img), {
			w: this.size,
			h: this.size
		});
		img = methods$14.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] = intToRGBA$1(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;
	}
};
/**
Convert a 32-bit integer color value to an RGBA object.
*/
function intToRGBA$1(i) {
	const a = i & 255;
	i >>>= 8;
	const b = i & 255;
	i >>>= 8;
	const g = i & 255;
	i >>>= 8;
	return {
		r: i & 255,
		g,
		b,
		a
	};
}
const 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;
}
//#endregion
//#region node_modules/@jimp/plugin-hash/dist/esm/index.js
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_";
const maxHashLength = [NaN, NaN];
for (let i = 2; i < 65; i++) {
	const maxHash = (0, import_any_base.default)(import_any_base.default.BIN, alphabet.slice(0, i))(new Array(65).join("1"));
	maxHashLength.push(maxHash.length);
}
const methods$5 = {
	pHash(image) {
		return new ImagePHash().getHash(image);
	},
	hash(image, 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(image);
		const maxLength = maxHashLength[base];
		return (0, import_any_base.default)(import_any_base.default.BIN, subAlphabet)(pHash).padStart(maxLength, "0");
	},
	distanceFromHash(image, compareHash) {
		const pHash = new ImagePHash();
		const currentHash = pHash.getHash(image);
		return pHash.distance(currentHash, compareHash);
	}
};
/**
* Calculates the hamming distance of two images based on their perceptual hash
* @param img1 A Jimp image to compare
* @param img2 A Jimp image to compare
* @returns A number ranging from 0 to 1, 0 means they are believed to be identical
* @example
* ```ts
* import { Jimp, distance } from "jimp";
*
* const image1 = await Jimp.read("test/image.png");
* const image2 = await Jimp.read("test/image.png");
*
* distance(image1, image2); // 0.5
* ```
*/
function distance(img1, img2) {
	const phash = new ImagePHash();
	const hash1 = phash.getHash(img1);
	const hash2 = phash.getHash(img2);
	return phash.distance(hash1, hash2);
}
/**
* Calculates the hamming distance of two images based on their perceptual hash
* @param hash1 A pHash
* @param hash2 A pHash
* @returns A number ranging from 0 to 1, 0 means they are believed to be identical
* @example
* ```ts
* import { Jimp, compareHashes } from "jimp";
*
* const image1 = await Jimp.read("test/image.png");
* const image2 = await Jimp.read("test/image.png");
*
* compareHashes(image1.pHash(), image2.pHash()); // 0.5
* ```
*/
function compareHashes(hash1, hash2) {
	return new ImagePHash().distance(hash1, hash2);
}
//#endregion
//#region node_modules/@jimp/plugin-mask/dist/esm/index.js
const MaskOptionsObjectSchema = z.object({
	src: JimpClassSchema,
	x: z.number().optional(),
	y: z.number().optional()
});
const MaskOptionsSchema = z.union([JimpClassSchema, MaskOptionsObjectSchema]);
const methods$4 = { mask(image, 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 = image.bitmap.width;
	const h = image.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 = image.getPixelIndex(destX, destY);
			const { data } = src.bitmap;
			const avg = (data[idx + 0] + data[idx + 1] + data[idx + 2]) / 3;
			image.bitmap.data[dstIdx + 3] *= avg / 255;
		}
	});
	return image;
} };
//#endregion
//#region 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, " \n").split(" ");
	const lines = [];
	let currentLine = [];
	let longestLine = 0;
	words.forEach((word) => {
		if (measureText(font, word + (words.length > 1 ? " " : "")) > maxWidth) {
			const characterIterator = word[Symbol.iterator]();
			let current = "";
			for (const char of characterIterator) {
				const length = measureText(font, [...currentLine, current + char].join(" "));
				if (length < maxWidth) current += char;
				else if (length > maxWidth) {
					lines.push([...currentLine, current]);
					currentLine = [];
					current = char;
				} else {
					lines.push([...currentLine, current + char]);
					currentLine = [];
					current = "";
				}
			}
			return;
		}
		const length = measureText(font, [...currentLine, word].join(" "));
		if (length <= maxWidth && !word.includes("\n")) {
			if (length > longestLine) longestLine = length;
			currentLine.push(word);
		} else {
			lines.push(currentLine);
			currentLine = [word.replace("\n", "")];
		}
	});
	lines.push(currentLine);
	return {
		lines,
		longestLine
	};
}
function measureTextHeight(font, text, maxWidth) {
	const { lines } = splitLines(font, text, maxWidth);
	return lines.length * font.common.lineHeight;
}
//#endregion
//#region node_modules/@jimp/plugin-print/dist/esm/index.js
const PrintOptionsSchema = z.object({
	x: z.number(),
	y: z.number(),
	text: z.union([z.union([z.string(), z.number()]), z.object({
		text: z.union([z.string(), z.number()]),
		alignmentX: z.nativeEnum(HorizontalAlign).optional(),
		alignmentY: z.nativeEnum(VerticalAlign).optional()
	})]),
	maxWidth: z.number().optional(),
	maxHeight: z.number().optional(),
	cb: z.function(z.tuple([z.object({
		x: z.number(),
		y: z.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(image, font, x, y, char) {
	if (char.width > 0 && char.height > 0) {
		const characterPage = font.pages[char.page];
		if (characterPage) image = methods$17.blit(image, {
			src: characterPage,
			x: x + char.xoffset,
			y: y + char.yoffset,
			srcX: char.x,
			srcY: char.y,
			srcW: char.width,
			srcH: char.height
		});
	}
	return image;
}
function printText(image, 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: void 0 };
		const fontKerning = font.kernings[char];
		if (fontChar) drawCharacter(image, font, x, y, fontChar);
		const nextChar = text[i + 1];
		const kerning = fontKerning && nextChar && fontKerning[nextChar] ? fontKerning[nextChar] || 0 : 0;
		x += kerning + (fontChar.xadvance || defaultCharWidth);
	}
}
const methods$3 = { print(image, { 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 !== void 0) {
		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((c) => c[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(" ");
		printText(image, font, x + xOffsetBasedOnAlignment(font, lineString, maxWidth, alignmentX), y, lineString, defaultCharWidth);
		y += font.common.lineHeight;
	});
	cb.bind(image)({
		x: x + longestLine,
		y
	});
	return image;
} };
//#endregion
//#region node_modules/@jimp/plugin-rotate/dist/esm/index.js
const RotateOptionsSchema = z.union([z.number(), z.object({
	deg: z.number(),
	mode: z.union([z.boolean(), z.nativeEnum(ResizeStrategy)]).optional()
})]);
/** function to translate the x, y coordinate to the index of the pixel in the buffer */
function createIdxTranslationFunction(w) {
	return function(x, y) {
		return y * w + x << 2;
	};
}
/**
* Rotates an image counter-clockwise by multiple of 90 degrees. NB: 'this' must be a Jimp object.
*
* This function is based on matrix rotation. Check this to get an initial idea how it works: https://stackoverflow.com/a/8664879/10561909
*
* @param deg the number of degrees to rotate the image by, it should be a multiple of 90
*/
function matrixRotate(image, deg) {
	if (Math.abs(deg) % 90 !== 0) throw new Error("Unsupported matrix rotation degree");
	const w = image.bitmap.width;
	const h = image.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(image.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 = image.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);
	}
	image.bitmap.data = dstBuffer;
	image.bitmap.width = nW;
	image.bitmap.height = nH;
}
function createTranslationFunction(deltaX, deltaY) {
	return function(x, y) {
		return {
			x: x + deltaX,
			y: y + deltaY
		};
	};
}
/**
* Rotates an image counter-clockwise by an arbitrary number of degrees. NB: 'this' must be a Jimp object.
* @param {number} deg the number of degrees to rotate the image by
*/
function advancedRotate(image, deg, mode) {
	const rad = deg * Math.PI / 180;
	const cosine = Math.cos(rad);
	const sine = Math.sin(rad);
	let w = image.bitmap.width;
	let h = image.bitmap.height;
	if (mode === true || typeof mode === "string") {
		w = Math.ceil(Math.abs(image.bitmap.width * cosine) + Math.abs(image.bitmap.height * sine)) + 1;
		h = Math.ceil(Math.abs(image.bitmap.width * sine) + Math.abs(image.bitmap.height * cosine)) + 1;
		if (w % 2 !== 0) w++;
		if (h % 2 !== 0) h++;
		const c = clone(image);
		image.scan((_, __, idx) => {
			image.bitmap.data.writeUInt32BE(image.background, idx);
		});
		const max = Math.max(w, h, image.bitmap.width, image.bitmap.height);
		image = methods$13.resize(image, {
			h: max,
			w: max,
			mode: mode === true ? void 0 : mode
		});
		image = composite(image, c, image.bitmap.width / 2 - c.bitmap.width / 2, image.bitmap.height / 2 - c.bitmap.height / 2);
	}
	const bW = image.bitmap.width;
	const bH = image.bitmap.height;
	const dstBuffer = Buffer.alloc(image.bitmap.data.length);
	const translate2Cartesian = createTranslationFunction(-(bW / 2), -(bH / 2));
	const translate2Screen = createTranslationFunction(bW / 2 + .5, bH / 2 + .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 = image.bitmap.data.readUInt32BE(srcIdx);
			dstBuffer.writeUInt32BE(pixelRGBA, dstIdx);
		} else dstBuffer.writeUInt32BE(image.background, dstIdx);
	}
	image.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);
		image = methods$11.crop(image, {
			x,
			y,
			w,
			h
		});
	}
}
const methods$2 = { rotate(image, 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 image;
	if (deg % 90 === 0 && (mode || image.bitmap.width === image.bitmap.height || deg % 180 === 0)) matrixRotate(image, deg);
	else advancedRotate(image, deg, mode);
	return image;
} };
//#endregion
//#region node_modules/@jimp/plugin-threshold/dist/esm/index.js
const ThresholdOptionsSchema = z.object({
	max: z.number().min(0).max(255),
	replace: z.number().min(0).max(255).optional(),
	autoGreyscale: z.boolean().optional()
});
const methods$1 = { threshold(image, options) {
	let { max, replace = 255, autoGreyscale = true } = ThresholdOptionsSchema.parse(options);
	max = limit255(max);
	replace = limit255(replace);
	if (autoGreyscale) methods$14.greyscale(image);
	image.scan((_, __, idx) => {
		const grey = image.bitmap.data[idx] < max ? image.bitmap.data[idx] : replace;
		image.bitmap.data[idx] = grey;
		image.bitmap.data[idx + 1] = grey;
		image.bitmap.data[idx + 2] = grey;
	});
	return image;
} };
//#endregion
//#region 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 __export = (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;
};
__export({}, { bt709: () => bt709_exports });
var bt709_exports = {};
__export(bt709_exports, {
	Y: () => Y,
	x: () => x,
	y: () => y
});
var Y = /* @__PURE__ */ ((Y2) => {
	Y2[Y2["RED"] = .2126] = "RED";
	Y2[Y2["GREEN"] = .7152] = "GREEN";
	Y2[Y2["BLUE"] = .0722] = "BLUE";
	Y2[Y2["WHITE"] = 1] = "WHITE";
	return Y2;
})(Y || {});
var x = /* @__PURE__ */ ((x2) => {
	x2[x2["RED"] = .64] = "RED";
	x2[x2["GREEN"] = .3] = "GREEN";
	x2[x2["BLUE"] = .15] = "BLUE";
	x2[x2["WHITE"] = .3127] = "WHITE";
	return x2;
})(x || {});
var y = /* @__PURE__ */ ((y2) => {
	y2[y2["RED"] = .33] = "RED";
	y2[y2["GREEN"] = .6] = "GREEN";
	y2[y2["BLUE"] = .06] = "BLUE";
	y2[y2["WHITE"] = .329] = "WHITE";
	return y2;
})(y || {});
__export({}, {
	lab2rgb: () => lab2rgb,
	lab2xyz: () => lab2xyz,
	rgb2hsl: () => rgb2hsl,
	rgb2lab: () => rgb2lab,
	rgb2xyz: () => rgb2xyz,
	xyz2lab: () => xyz2lab,
	xyz2rgb: () => xyz2rgb
});
function correctGamma(n) {
	return n > .04045 ? ((n + .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 * .4124 + g * .3576 + b * .1805,
		y: r * .2126 + g * .7152 + b * .0722,
		z: r * .0193 + g * .1192 + b * .9505
	};
}
var arithmetic_exports = {};
__export(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 < .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 = .95047;
var refY = 1;
var refZ = 1.08883;
function pivot(n) {
	return n > .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 = .95047;
var refY2 = 1;
var refZ2 = 1.08883;
function pivot2(n) {
	return n > .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 > .0031308 ? 1.055 * n ** (1 / 2.4) - .055 : 12.92 * n;
}
function xyz2rgb(x2, y2, z) {
	const r = correctGamma2(x2 * 3.2406 + y2 * -1.5372 + z * -.4986);
	const g = correctGamma2(x2 * -.9689 + y2 * 1.8758 + z * .0415);
	const b = correctGamma2(x2 * .0557 + y2 * -.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);
}
__export({}, {
	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 dC = c1 - Math.sqrt(lab2.a * lab2.a + lab2.b * lab2.b);
		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 = .048;
		this._K2 = .014;
		this._kA = .25 * 50 / 255;
	}
};
var CIE94GraphicArts = class extends AbstractCIE94 {
	_setDefaults() {
		this._Kl = 1;
		this._K1 = .045;
		this._K2 = .015;
		this._kA = .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 - .17 * Math.cos(ahp - _CIEDE2000._deg30InRad) + .24 * Math.cos(ahp * 2) + .32 * Math.cos(ahp * 3 + _CIEDE2000._deg6InRad) - .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 pow_a_C1_C2_to_7 = ((Math.sqrt(a1 * a1 + b1 * b1) + Math.sqrt(a2 * a2 + b2 * b2)) / 2) ** 7;
		const G = .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 + .015 * aLp_minus_50_square / Math.sqrt(20 + aLp_minus_50_square);
		const S_C = 1 + .045 * aCp;
		const S_H = 1 + .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", .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 = .2126;
		this._kG = .7152;
		this._kB = .0722;
		this._kA = 1;
	}
};
var EuclideanBT709NoAlpha = class extends AbstractEuclidean {
	_setDefaults() {
		this._kR = .2126;
		this._kG = .7152;
		this._kB = .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 = .4984;
		this._kG = .8625;
		this._kB = .2979;
		this._kA = 1;
	}
};
var ManhattanBT709 = class extends AbstractManhattan {
	_setDefaults() {
		this._kR = .2126;
		this._kG = .7152;
		this._kB = .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() {}
};
__export({}, {
	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 * .2126 + g * .7152 + b * .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 clone = new PointContainer();
		clone._width = this._width;
		clone._height = this._height;
		for (let i = 0, l = this._pointArray.length; i < l; i++) clone._pointArray[i] = Point.createByUint32(this._pointArray[i].uint32 | 0);
		return clone;
	}
	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;
		canvas.getContext("2d").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 imgData = canvas.getContext("2d").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 seg = 360 / 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 distance = colorDistanceCalculator.calculateRaw(point.r, point.g, point.b, point.a, p.r, p.g, p.b, p.a);
			if (distance < minimalDistance) {
				minimalDistance = distance;
				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 hueDiff = (b.r === b.g && b.g === b.b ? 0 : 1 + hueGroup(hslB.h, hueGroups)) - 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 = {};
__export(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 palette = new Palette();
		this._network.forEach((neuron) => {
			palette.add(neuron.toPoint());
		});
		palette.sort();
		return palette;
	}
	_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 = 1020 << networkBiasShift;
		let bestd = 2147483647;
		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 palette = new Palette();
		this._network.forEach((neuron) => {
			palette.add(neuron.toPoint());
		});
		palette.sort();
		return palette;
	}
	_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 = 1020 << networkBiasShift2;
		let bestd = 2147483647;
		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, distance) {
		__publicField(this, "index");
		__publicField(this, "color");
		__publicField(this, "distance");
		this.index = index;
		this.color = color;
		this.distance = distance;
	}
};
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 = .01;
		this._distanceIncrement = .005;
	}
	sample(image) {
		this._histogram.sample(image);
	}
	*quantize() {
		const idxi32 = this._histogram.getImportanceSortedColorsIDXI32();
		if (idxi32.length === 0) throw new Error("No colors in image");
		yield* this._buildPalette(idxi32);
	}
	*_buildPalette(idxi32) {
		const palette = new Palette();
		const colorArray = palette.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;
		palette.sort();
		yield {
			palette,
			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(image) {
		const pointArray = image.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 palette = 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);
			palette.add(color);
		}
		palette.sort();
		yield {
			palette,
			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];
			let bestMatch = -1;
			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 distance = this._distance.calculateRaw(foundRed, foundGreen, foundBlue, foundAlpha, color.r, color.g, color.b, color.a);
				if (distance < bestDistance) {
					bestDistance = distance;
					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);
		return volumeMoment - (volumeRed * volumeRed + volumeGreen * volumeGreen + volumeBlue * volumeBlue + volumeAlpha * volumeAlpha) / 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);
__export({}, {
	AbstractImageQuantizer: () => AbstractImageQuantizer,
	ErrorDiffusionArray: () => ErrorDiffusionArray,
	ErrorDiffusionArrayKernel: () => ErrorDiffusionArrayKernel,
	ErrorDiffusionRiemersma: () => ErrorDiffusionRiemersma,
	NearestColor: () => NearestColor
});
var AbstractImageQuantizer = class {
	quantizeSync(pointContainer, palette) {
		for (const value of this.quantize(pointContainer, palette)) 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, palette) {
		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(palette.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, palette) {
		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 = palette.getNearestColor(this._distance, correctedPoint);
				point.from(palettePoint);
				if (this._minColorDistance) {
					if (this._distance.calculateNormalized(originalPoint, palettePoint) < 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 data = {
		width,
		height,
		level: Math.floor(Math.log(maxBound) / Math.log(2) + 1),
		callback,
		tracker: new ProgressTracker(width * height, 99),
		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, palette) {
		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 = palette.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 + .5 | 0) / errorQueueSize * errorPropagation;
			next *= multiplier;
		}
		return weights;
	}
};
__export({}, { ssim: () => ssim });
var K1 = .01;
var K2 = .03;
function ssim(image1, image2) {
	if (image1.getHeight() !== image2.getHeight() || image1.getWidth() !== image2.getWidth()) throw new Error("Images have different sizes!");
	const L = 255;
	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 ssim2 = (2 * averageLumaValue1 * averageLumaValue2 + c1) * (2 * sigxy + c2) / ((averageLumaValue1 ** 2 + averageLumaValue2 ** 2 + c1) * (sigsqx + sigsqy + c2));
		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);
		callback(lumaValues1, lumaValues2, calculateAverageLuma(lumaValues1), calculateAverageLuma(lumaValues2));
	}
}
function calculateLumaValuesForWindow(image, x2, y2, width, height) {
	const pointArray = image.getPointArray();
	const lumaValues = [];
	let counter = 0;
	for (let j = y2; j < y2 + height; j++) {
		const offset = j * image.getWidth();
		for (let i = x2; i < x2 + width; i++) {
			const point = pointArray[offset + i];
			lumaValues[counter] = point.r * .2126 + point.g * .7152 + point.b * .0722;
			counter++;
		}
	}
	return lumaValues;
}
function calculateAverageLuma(lumaValues) {
	let sumLuma = 0;
	for (const luma of lumaValues) sumLuma += luma;
	return sumLuma / lumaValues.length;
}
typeof setImmediate === "function" ? setImmediate : typeof process !== "undefined" && (process == null || process.nextTick);
function buildPaletteSync(images, { colorDistanceFormula, paletteQuantization, colors } = {}) {
	const paletteQuantizer = paletteQuantizationToPaletteQuantizer(colorDistanceFormulaToColorDistance(colorDistanceFormula), paletteQuantization, colors);
	images.forEach((image) => paletteQuantizer.sample(image));
	return paletteQuantizer.quantizeSync();
}
function applyPaletteSync(image, palette, { colorDistanceFormula, imageQuantization } = {}) {
	return imageQuantizationToImageQuantizer(colorDistanceFormulaToColorDistance(colorDistanceFormula), imageQuantization).quantizeSync(image, palette);
}
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}`);
	}
}
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* cie94.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* ciede2000.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* cmetric.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* common.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* constants.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* ditherErrorDiffusionArray.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* euclidean.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* helper.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* hueStatistics.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* iq.ts - Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* lab2rgb.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* lab2xyz.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* manhattanNeuQuant.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* nearestColor.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* palette.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* pngQuant.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* point.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* pointContainer.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* rgb2hsl.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* rgb2lab.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* rgb2xyz.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* ssim.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* wuQuant.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* xyz2lab.ts - part of Image Quantization Library
*/
/**
* @preserve
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* xyz2rgb.ts - part of Image Quantization Library
*/
/**
* @preserve
* MIT License
*
* Copyright 2015-2018 Igor Bezkrovnyi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* riemersma.ts - part of Image Quantization Library
*/
/**
* @preserve TypeScript port:
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* colorHistogram.ts - part of Image Quantization Library
*/
/**
* @preserve TypeScript port:
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* neuquant.ts - part of Image Quantization Library
*/
/**
* @preserve TypeScript port:
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* rgbquant.ts - part of Image Quantization Library
*/
//#endregion
//#region node_modules/@jimp/plugin-quantize/dist/esm/index.js
const QuantizeOptionsSchema = z$1.object({
	colors: z$1.number().optional(),
	colorDistanceFormula: z$1.union([
		z$1.literal("cie94-textiles"),
		z$1.literal("cie94-graphic-arts"),
		z$1.literal("ciede2000"),
		z$1.literal("color-metric"),
		z$1.literal("euclidean"),
		z$1.literal("euclidean-bt709-noalpha"),
		z$1.literal("euclidean-bt709"),
		z$1.literal("manhattan"),
		z$1.literal("manhattan-bt709"),
		z$1.literal("manhattan-nommyde"),
		z$1.literal("pngquant")
	]).optional(),
	paletteQuantization: z$1.union([
		z$1.literal("neuquant"),
		z$1.literal("neuquant-float"),
		z$1.literal("rgbquant"),
		z$1.literal("wuquant")
	]).optional(),
	imageQuantization: z$1.union([
		z$1.literal("nearest"),
		z$1.literal("riemersma"),
		z$1.literal("floyd-steinberg"),
		z$1.literal("false-floyd-steinberg"),
		z$1.literal("stucki"),
		z$1.literal("atkinson"),
		z$1.literal("jarvis"),
		z$1.literal("burkes"),
		z$1.literal("sierra"),
		z$1.literal("two-sierra"),
		z$1.literal("sierra-lite")
	]).optional()
});
const methods = { quantize(image, options) {
	const { colors, colorDistanceFormula, paletteQuantization, imageQuantization } = QuantizeOptionsSchema.parse(options);
	const inPointContainer = utils_exports.PointContainer.fromUint8Array(image.bitmap.data, image.bitmap.width, image.bitmap.height);
	const outPointContainer = applyPaletteSync(inPointContainer, buildPaletteSync([inPointContainer], {
		colors,
		colorDistanceFormula,
		paletteQuantization
	}), {
		colorDistanceFormula,
		imageQuantization
	});
	image.bitmap.data = Buffer.from(outPointContainer.toUint8Array());
	return image;
} };
//#endregion
//#region node_modules/parse-bmfont-ascii/index.js
var require_parse_bmfont_ascii = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = function parseBMFontAscii(data) {
		if (!data) throw new Error("no data provided");
		data = data.toString().trim();
		var output = {
			pages: [],
			chars: [],
			kernings: []
		};
		var lines = data.split(/\r\n?|\n/g);
		if (lines.length === 0) throw new Error("no data in BMFont file");
		for (var i = 0; i < lines.length; i++) {
			var lineData = splitLine(lines[i], i);
			if (!lineData) continue;
			if (lineData.key === "page") {
				if (typeof lineData.data.id !== "number") throw new Error("malformed file at line " + i + " -- needs page id=N");
				if (typeof lineData.data.file !== "string") throw new Error("malformed file at line " + i + " -- needs page file=\"path\"");
				output.pages[lineData.data.id] = lineData.data.file;
			} else if (lineData.key === "chars" || lineData.key === "kernings") {} else if (lineData.key === "char") output.chars.push(lineData.data);
			else if (lineData.key === "kerning") output.kernings.push(lineData.data);
			else output[lineData.key] = lineData.data;
		}
		return output;
	};
	function splitLine(line, idx) {
		line = line.replace(/\t+/g, " ").trim();
		if (!line) return null;
		var space = line.indexOf(" ");
		if (space === -1) throw new Error("no named row at line " + idx);
		var key = line.substring(0, space);
		line = line.substring(space + 1);
		line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, "");
		line = line.split("=");
		line = line.map(function(str) {
			return str.trim().match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g);
		});
		var data = [];
		for (var i = 0; i < line.length; i++) {
			var dt = line[i];
			if (i === 0) data.push({
				key: dt[0],
				data: ""
			});
			else if (i === line.length - 1) data[data.length - 1].data = parseData(dt[0]);
			else {
				data[data.length - 1].data = parseData(dt[0]);
				data.push({
					key: dt[1],
					data: ""
				});
			}
		}
		var out = {
			key,
			data: {}
		};
		data.forEach(function(v) {
			out.data[v.key] = v.data;
		});
		return out;
	}
	function parseData(data) {
		if (!data || data.length === 0) return "";
		if (data.indexOf("\"") === 0 || data.indexOf("'") === 0) return data.substring(1, data.length - 1);
		if (data.indexOf(",") !== -1) return parseIntList(data);
		return parseInt(data, 10);
	}
	function parseIntList(data) {
		return data.split(",").map(function(val) {
			return parseInt(val, 10);
		});
	}
}));
//#endregion
//#region node_modules/xml2js/lib/defaults.js
var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => {
	(function() {
		exports.defaults = {
			"0.1": {
				explicitCharkey: false,
				trim: true,
				normalize: true,
				normalizeTags: false,
				attrkey: "@",
				charkey: "#",
				explicitArray: false,
				ignoreAttrs: false,
				mergeAttrs: false,
				explicitRoot: false,
				validator: null,
				xmlns: false,
				explicitChildren: false,
				childkey: "@@",
				charsAsChildren: false,
				includeWhiteChars: false,
				async: false,
				strict: true,
				attrNameProcessors: null,
				attrValueProcessors: null,
				tagNameProcessors: null,
				valueProcessors: null,
				emptyTag: ""
			},
			"0.2": {
				explicitCharkey: false,
				trim: false,
				normalize: false,
				normalizeTags: false,
				attrkey: "$",
				charkey: "_",
				explicitArray: true,
				ignoreAttrs: false,
				mergeAttrs: false,
				explicitRoot: true,
				validator: null,
				xmlns: false,
				explicitChildren: false,
				preserveChildrenOrder: false,
				childkey: "$$",
				charsAsChildren: false,
				includeWhiteChars: false,
				async: false,
				strict: true,
				attrNameProcessors: null,
				attrValueProcessors: null,
				tagNameProcessors: null,
				valueProcessors: null,
				rootName: "root",
				xmldec: {
					"version": "1.0",
					"encoding": "UTF-8",
					"standalone": true
				},
				doctype: null,
				renderOpts: {
					"pretty": true,
					"indent": "  ",
					"newline": "\n"
				},
				headless: false,
				chunkSize: 1e4,
				emptyTag: "",
				cdata: false
			}
		};
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/Utility.js
var require_Utility = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var assign, getValue, isArray, isEmpty, isFunction, isObject, isPlainObject, slice = [].slice, hasProp = {}.hasOwnProperty;
		assign = function() {
			var i, key, len, source, sources, target = arguments[0];
			sources = 2 <= arguments.length ? slice.call(arguments, 1) : [];
			if (isFunction(Object.assign)) Object.assign.apply(null, arguments);
			else for (i = 0, len = sources.length; i < len; i++) {
				source = sources[i];
				if (source != null) for (key in source) {
					if (!hasProp.call(source, key)) continue;
					target[key] = source[key];
				}
			}
			return target;
		};
		isFunction = function(val) {
			return !!val && Object.prototype.toString.call(val) === "[object Function]";
		};
		isObject = function(val) {
			var ref;
			return !!val && ((ref = typeof val) === "function" || ref === "object");
		};
		isArray = function(val) {
			if (isFunction(Array.isArray)) return Array.isArray(val);
			else return Object.prototype.toString.call(val) === "[object Array]";
		};
		isEmpty = function(val) {
			var key;
			if (isArray(val)) return !val.length;
			else {
				for (key in val) {
					if (!hasProp.call(val, key)) continue;
					return false;
				}
				return true;
			}
		};
		isPlainObject = function(val) {
			var ctor, proto;
			return isObject(val) && (proto = Object.getPrototypeOf(val)) && (ctor = proto.constructor) && typeof ctor === "function" && ctor instanceof ctor && Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object);
		};
		getValue = function(obj) {
			if (isFunction(obj.valueOf)) return obj.valueOf();
			else return obj;
		};
		module.exports.assign = assign;
		module.exports.isFunction = isFunction;
		module.exports.isObject = isObject;
		module.exports.isArray = isArray;
		module.exports.isEmpty = isEmpty;
		module.exports.isPlainObject = isPlainObject;
		module.exports.getValue = getValue;
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDOMImplementation.js
var require_XMLDOMImplementation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		module.exports = (function() {
			function XMLDOMImplementation() {}
			XMLDOMImplementation.prototype.hasFeature = function(feature, version) {
				return true;
			};
			XMLDOMImplementation.prototype.createDocumentType = function(qualifiedName, publicId, systemId) {
				throw new Error("This DOM method is not implemented.");
			};
			XMLDOMImplementation.prototype.createDocument = function(namespaceURI, qualifiedName, doctype) {
				throw new Error("This DOM method is not implemented.");
			};
			XMLDOMImplementation.prototype.createHTMLDocument = function(title) {
				throw new Error("This DOM method is not implemented.");
			};
			XMLDOMImplementation.prototype.getFeature = function(feature, version) {
				throw new Error("This DOM method is not implemented.");
			};
			return XMLDOMImplementation;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js
var require_XMLDOMErrorHandler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		module.exports = (function() {
			function XMLDOMErrorHandler() {}
			XMLDOMErrorHandler.prototype.handleError = function(error) {
				throw new Error(error);
			};
			return XMLDOMErrorHandler;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDOMStringList.js
var require_XMLDOMStringList = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		module.exports = (function() {
			function XMLDOMStringList(arr) {
				this.arr = arr || [];
			}
			Object.defineProperty(XMLDOMStringList.prototype, "length", { get: function() {
				return this.arr.length;
			} });
			XMLDOMStringList.prototype.item = function(index) {
				return this.arr[index] || null;
			};
			XMLDOMStringList.prototype.contains = function(str) {
				return this.arr.indexOf(str) !== -1;
			};
			return XMLDOMStringList;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDOMConfiguration.js
var require_XMLDOMConfiguration = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var XMLDOMErrorHandler = require_XMLDOMErrorHandler(), XMLDOMStringList = require_XMLDOMStringList();
		module.exports = (function() {
			function XMLDOMConfiguration() {
				this.defaultParams = {
					"canonical-form": false,
					"cdata-sections": false,
					"comments": false,
					"datatype-normalization": false,
					"element-content-whitespace": true,
					"entities": true,
					"error-handler": new XMLDOMErrorHandler(),
					"infoset": true,
					"validate-if-schema": false,
					"namespaces": true,
					"namespace-declarations": true,
					"normalize-characters": false,
					"schema-location": "",
					"schema-type": "",
					"split-cdata-sections": true,
					"validate": false,
					"well-formed": true
				};
				this.params = Object.create(this.defaultParams);
			}
			Object.defineProperty(XMLDOMConfiguration.prototype, "parameterNames", { get: function() {
				return new XMLDOMStringList(Object.keys(this.defaultParams));
			} });
			XMLDOMConfiguration.prototype.getParameter = function(name) {
				if (this.params.hasOwnProperty(name)) return this.params[name];
				else return null;
			};
			XMLDOMConfiguration.prototype.canSetParameter = function(name, value) {
				return true;
			};
			XMLDOMConfiguration.prototype.setParameter = function(name, value) {
				if (value != null) return this.params[name] = value;
				else return delete this.params[name];
			};
			return XMLDOMConfiguration;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/NodeType.js
var require_NodeType = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		module.exports = {
			Element: 1,
			Attribute: 2,
			Text: 3,
			CData: 4,
			EntityReference: 5,
			EntityDeclaration: 6,
			ProcessingInstruction: 7,
			Comment: 8,
			Document: 9,
			DocType: 10,
			DocumentFragment: 11,
			NotationDeclaration: 12,
			Declaration: 201,
			Raw: 202,
			AttributeDeclaration: 203,
			ElementDeclaration: 204,
			Dummy: 205
		};
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLAttribute.js
var require_XMLAttribute = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType = require_NodeType();
		require_XMLNode();
		module.exports = (function() {
			function XMLAttribute(parent, name, value) {
				this.parent = parent;
				if (this.parent) {
					this.options = this.parent.options;
					this.stringify = this.parent.stringify;
				}
				if (name == null) throw new Error("Missing attribute name. " + this.debugInfo(name));
				this.name = this.stringify.name(name);
				this.value = this.stringify.attValue(value);
				this.type = NodeType.Attribute;
				this.isId = false;
				this.schemaTypeInfo = null;
			}
			Object.defineProperty(XMLAttribute.prototype, "nodeType", { get: function() {
				return this.type;
			} });
			Object.defineProperty(XMLAttribute.prototype, "ownerElement", { get: function() {
				return this.parent;
			} });
			Object.defineProperty(XMLAttribute.prototype, "textContent", {
				get: function() {
					return this.value;
				},
				set: function(value) {
					return this.value = value || "";
				}
			});
			Object.defineProperty(XMLAttribute.prototype, "namespaceURI", { get: function() {
				return "";
			} });
			Object.defineProperty(XMLAttribute.prototype, "prefix", { get: function() {
				return "";
			} });
			Object.defineProperty(XMLAttribute.prototype, "localName", { get: function() {
				return this.name;
			} });
			Object.defineProperty(XMLAttribute.prototype, "specified", { get: function() {
				return true;
			} });
			XMLAttribute.prototype.clone = function() {
				return Object.create(this);
			};
			XMLAttribute.prototype.toString = function(options) {
				return this.options.writer.attribute(this, this.options.writer.filterOptions(options));
			};
			XMLAttribute.prototype.debugInfo = function(name) {
				name = name || this.name;
				if (name == null) return "parent: <" + this.parent.name + ">";
				else return "attribute: {" + name + "}, parent: <" + this.parent.name + ">";
			};
			XMLAttribute.prototype.isEqualNode = function(node) {
				if (node.namespaceURI !== this.namespaceURI) return false;
				if (node.prefix !== this.prefix) return false;
				if (node.localName !== this.localName) return false;
				if (node.value !== this.value) return false;
				return true;
			};
			return XMLAttribute;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLNamedNodeMap.js
var require_XMLNamedNodeMap = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		module.exports = (function() {
			function XMLNamedNodeMap(nodes) {
				this.nodes = nodes;
			}
			Object.defineProperty(XMLNamedNodeMap.prototype, "length", { get: function() {
				return Object.keys(this.nodes).length || 0;
			} });
			XMLNamedNodeMap.prototype.clone = function() {
				return this.nodes = null;
			};
			XMLNamedNodeMap.prototype.getNamedItem = function(name) {
				return this.nodes[name];
			};
			XMLNamedNodeMap.prototype.setNamedItem = function(node) {
				var oldNode = this.nodes[node.nodeName];
				this.nodes[node.nodeName] = node;
				return oldNode || null;
			};
			XMLNamedNodeMap.prototype.removeNamedItem = function(name) {
				var oldNode = this.nodes[name];
				delete this.nodes[name];
				return oldNode || null;
			};
			XMLNamedNodeMap.prototype.item = function(index) {
				return this.nodes[Object.keys(this.nodes)[index]] || null;
			};
			XMLNamedNodeMap.prototype.getNamedItemNS = function(namespaceURI, localName) {
				throw new Error("This DOM method is not implemented.");
			};
			XMLNamedNodeMap.prototype.setNamedItemNS = function(node) {
				throw new Error("This DOM method is not implemented.");
			};
			XMLNamedNodeMap.prototype.removeNamedItemNS = function(namespaceURI, localName) {
				throw new Error("This DOM method is not implemented.");
			};
			return XMLNamedNodeMap;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLElement.js
var require_XMLElement = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLAttribute, XMLNamedNodeMap, XMLNode, getValue, isFunction, isObject, ref, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		ref = require_Utility(), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue;
		XMLNode = require_XMLNode();
		NodeType = require_NodeType();
		XMLAttribute = require_XMLAttribute();
		XMLNamedNodeMap = require_XMLNamedNodeMap();
		module.exports = (function(superClass) {
			extend(XMLElement, superClass);
			function XMLElement(parent, name, attributes) {
				var child, j, len, ref1;
				XMLElement.__super__.constructor.call(this, parent);
				if (name == null) throw new Error("Missing element name. " + this.debugInfo());
				this.name = this.stringify.name(name);
				this.type = NodeType.Element;
				this.attribs = {};
				this.schemaTypeInfo = null;
				if (attributes != null) this.attribute(attributes);
				if (parent.type === NodeType.Document) {
					this.isRoot = true;
					this.documentObject = parent;
					parent.rootObject = this;
					if (parent.children) {
						ref1 = parent.children;
						for (j = 0, len = ref1.length; j < len; j++) {
							child = ref1[j];
							if (child.type === NodeType.DocType) {
								child.name = this.name;
								break;
							}
						}
					}
				}
			}
			Object.defineProperty(XMLElement.prototype, "tagName", { get: function() {
				return this.name;
			} });
			Object.defineProperty(XMLElement.prototype, "namespaceURI", { get: function() {
				return "";
			} });
			Object.defineProperty(XMLElement.prototype, "prefix", { get: function() {
				return "";
			} });
			Object.defineProperty(XMLElement.prototype, "localName", { get: function() {
				return this.name;
			} });
			Object.defineProperty(XMLElement.prototype, "id", { get: function() {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			} });
			Object.defineProperty(XMLElement.prototype, "className", { get: function() {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			} });
			Object.defineProperty(XMLElement.prototype, "classList", { get: function() {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			} });
			Object.defineProperty(XMLElement.prototype, "attributes", { get: function() {
				if (!this.attributeMap || !this.attributeMap.nodes) this.attributeMap = new XMLNamedNodeMap(this.attribs);
				return this.attributeMap;
			} });
			XMLElement.prototype.clone = function() {
				var att, attName, clonedSelf = Object.create(this), ref1;
				if (clonedSelf.isRoot) clonedSelf.documentObject = null;
				clonedSelf.attribs = {};
				ref1 = this.attribs;
				for (attName in ref1) {
					if (!hasProp.call(ref1, attName)) continue;
					att = ref1[attName];
					clonedSelf.attribs[attName] = att.clone();
				}
				clonedSelf.children = [];
				this.children.forEach(function(child) {
					var clonedChild = child.clone();
					clonedChild.parent = clonedSelf;
					return clonedSelf.children.push(clonedChild);
				});
				return clonedSelf;
			};
			XMLElement.prototype.attribute = function(name, value) {
				var attName, attValue;
				if (name != null) name = getValue(name);
				if (isObject(name)) for (attName in name) {
					if (!hasProp.call(name, attName)) continue;
					attValue = name[attName];
					this.attribute(attName, attValue);
				}
				else {
					if (isFunction(value)) value = value.apply();
					if (this.options.keepNullAttributes && value == null) this.attribs[name] = new XMLAttribute(this, name, "");
					else if (value != null) this.attribs[name] = new XMLAttribute(this, name, value);
				}
				return this;
			};
			XMLElement.prototype.removeAttribute = function(name) {
				var attName, j, len;
				if (name == null) throw new Error("Missing attribute name. " + this.debugInfo());
				name = getValue(name);
				if (Array.isArray(name)) for (j = 0, len = name.length; j < len; j++) {
					attName = name[j];
					delete this.attribs[attName];
				}
				else delete this.attribs[name];
				return this;
			};
			XMLElement.prototype.toString = function(options) {
				return this.options.writer.element(this, this.options.writer.filterOptions(options));
			};
			XMLElement.prototype.att = function(name, value) {
				return this.attribute(name, value);
			};
			XMLElement.prototype.a = function(name, value) {
				return this.attribute(name, value);
			};
			XMLElement.prototype.getAttribute = function(name) {
				if (this.attribs.hasOwnProperty(name)) return this.attribs[name].value;
				else return null;
			};
			XMLElement.prototype.setAttribute = function(name, value) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.getAttributeNode = function(name) {
				if (this.attribs.hasOwnProperty(name)) return this.attribs[name];
				else return null;
			};
			XMLElement.prototype.setAttributeNode = function(newAttr) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.removeAttributeNode = function(oldAttr) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.getElementsByTagName = function(name) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.getAttributeNS = function(namespaceURI, localName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.setAttributeNS = function(namespaceURI, qualifiedName, value) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.removeAttributeNS = function(namespaceURI, localName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.getAttributeNodeNS = function(namespaceURI, localName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.setAttributeNodeNS = function(newAttr) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.hasAttribute = function(name) {
				return this.attribs.hasOwnProperty(name);
			};
			XMLElement.prototype.hasAttributeNS = function(namespaceURI, localName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.setIdAttribute = function(name, isId) {
				if (this.attribs.hasOwnProperty(name)) return this.attribs[name].isId;
				else return isId;
			};
			XMLElement.prototype.setIdAttributeNS = function(namespaceURI, localName, isId) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.setIdAttributeNode = function(idAttr, isId) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.getElementsByTagName = function(tagname) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.getElementsByClassName = function(classNames) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLElement.prototype.isEqualNode = function(node) {
				var i, j, ref1;
				if (!XMLElement.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) return false;
				if (node.namespaceURI !== this.namespaceURI) return false;
				if (node.prefix !== this.prefix) return false;
				if (node.localName !== this.localName) return false;
				if (node.attribs.length !== this.attribs.length) return false;
				for (i = j = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; i = 0 <= ref1 ? ++j : --j) if (!this.attribs[i].isEqualNode(node.attribs[i])) return false;
				return true;
			};
			return XMLElement;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLCharacterData.js
var require_XMLCharacterData = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var XMLNode, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		XMLNode = require_XMLNode();
		module.exports = (function(superClass) {
			extend(XMLCharacterData, superClass);
			function XMLCharacterData(parent) {
				XMLCharacterData.__super__.constructor.call(this, parent);
				this.value = "";
			}
			Object.defineProperty(XMLCharacterData.prototype, "data", {
				get: function() {
					return this.value;
				},
				set: function(value) {
					return this.value = value || "";
				}
			});
			Object.defineProperty(XMLCharacterData.prototype, "length", { get: function() {
				return this.value.length;
			} });
			Object.defineProperty(XMLCharacterData.prototype, "textContent", {
				get: function() {
					return this.value;
				},
				set: function(value) {
					return this.value = value || "";
				}
			});
			XMLCharacterData.prototype.clone = function() {
				return Object.create(this);
			};
			XMLCharacterData.prototype.substringData = function(offset, count) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLCharacterData.prototype.appendData = function(arg) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLCharacterData.prototype.insertData = function(offset, arg) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLCharacterData.prototype.deleteData = function(offset, count) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLCharacterData.prototype.replaceData = function(offset, count, arg) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLCharacterData.prototype.isEqualNode = function(node) {
				if (!XMLCharacterData.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) return false;
				if (node.data !== this.data) return false;
				return true;
			};
			return XMLCharacterData;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLCData.js
var require_XMLCData = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLCharacterData, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		NodeType = require_NodeType();
		XMLCharacterData = require_XMLCharacterData();
		module.exports = (function(superClass) {
			extend(XMLCData, superClass);
			function XMLCData(parent, text) {
				XMLCData.__super__.constructor.call(this, parent);
				if (text == null) throw new Error("Missing CDATA text. " + this.debugInfo());
				this.name = "#cdata-section";
				this.type = NodeType.CData;
				this.value = this.stringify.cdata(text);
			}
			XMLCData.prototype.clone = function() {
				return Object.create(this);
			};
			XMLCData.prototype.toString = function(options) {
				return this.options.writer.cdata(this, this.options.writer.filterOptions(options));
			};
			return XMLCData;
		})(XMLCharacterData);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLComment.js
var require_XMLComment = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLCharacterData, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		NodeType = require_NodeType();
		XMLCharacterData = require_XMLCharacterData();
		module.exports = (function(superClass) {
			extend(XMLComment, superClass);
			function XMLComment(parent, text) {
				XMLComment.__super__.constructor.call(this, parent);
				if (text == null) throw new Error("Missing comment text. " + this.debugInfo());
				this.name = "#comment";
				this.type = NodeType.Comment;
				this.value = this.stringify.comment(text);
			}
			XMLComment.prototype.clone = function() {
				return Object.create(this);
			};
			XMLComment.prototype.toString = function(options) {
				return this.options.writer.comment(this, this.options.writer.filterOptions(options));
			};
			return XMLComment;
		})(XMLCharacterData);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDeclaration.js
var require_XMLDeclaration = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLNode, isObject, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		isObject = require_Utility().isObject;
		XMLNode = require_XMLNode();
		NodeType = require_NodeType();
		module.exports = (function(superClass) {
			extend(XMLDeclaration, superClass);
			function XMLDeclaration(parent, version, encoding, standalone) {
				var ref;
				XMLDeclaration.__super__.constructor.call(this, parent);
				if (isObject(version)) ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
				if (!version) version = "1.0";
				this.type = NodeType.Declaration;
				this.version = this.stringify.xmlVersion(version);
				if (encoding != null) this.encoding = this.stringify.xmlEncoding(encoding);
				if (standalone != null) this.standalone = this.stringify.xmlStandalone(standalone);
			}
			XMLDeclaration.prototype.toString = function(options) {
				return this.options.writer.declaration(this, this.options.writer.filterOptions(options));
			};
			return XMLDeclaration;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDTDAttList.js
var require_XMLDTDAttList = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLNode, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		XMLNode = require_XMLNode();
		NodeType = require_NodeType();
		module.exports = (function(superClass) {
			extend(XMLDTDAttList, superClass);
			function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {
				XMLDTDAttList.__super__.constructor.call(this, parent);
				if (elementName == null) throw new Error("Missing DTD element name. " + this.debugInfo());
				if (attributeName == null) throw new Error("Missing DTD attribute name. " + this.debugInfo(elementName));
				if (!attributeType) throw new Error("Missing DTD attribute type. " + this.debugInfo(elementName));
				if (!defaultValueType) throw new Error("Missing DTD attribute default. " + this.debugInfo(elementName));
				if (defaultValueType.indexOf("#") !== 0) defaultValueType = "#" + defaultValueType;
				if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. " + this.debugInfo(elementName));
				if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) throw new Error("Default value only applies to #FIXED or #DEFAULT. " + this.debugInfo(elementName));
				this.elementName = this.stringify.name(elementName);
				this.type = NodeType.AttributeDeclaration;
				this.attributeName = this.stringify.name(attributeName);
				this.attributeType = this.stringify.dtdAttType(attributeType);
				if (defaultValue) this.defaultValue = this.stringify.dtdAttDefault(defaultValue);
				this.defaultValueType = defaultValueType;
			}
			XMLDTDAttList.prototype.toString = function(options) {
				return this.options.writer.dtdAttList(this, this.options.writer.filterOptions(options));
			};
			return XMLDTDAttList;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDTDEntity.js
var require_XMLDTDEntity = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLNode, isObject, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		isObject = require_Utility().isObject;
		XMLNode = require_XMLNode();
		NodeType = require_NodeType();
		module.exports = (function(superClass) {
			extend(XMLDTDEntity, superClass);
			function XMLDTDEntity(parent, pe, name, value) {
				XMLDTDEntity.__super__.constructor.call(this, parent);
				if (name == null) throw new Error("Missing DTD entity name. " + this.debugInfo(name));
				if (value == null) throw new Error("Missing DTD entity value. " + this.debugInfo(name));
				this.pe = !!pe;
				this.name = this.stringify.name(name);
				this.type = NodeType.EntityDeclaration;
				if (!isObject(value)) {
					this.value = this.stringify.dtdEntityValue(value);
					this.internal = true;
				} else {
					if (!value.pubID && !value.sysID) throw new Error("Public and/or system identifiers are required for an external entity. " + this.debugInfo(name));
					if (value.pubID && !value.sysID) throw new Error("System identifier is required for a public external entity. " + this.debugInfo(name));
					this.internal = false;
					if (value.pubID != null) this.pubID = this.stringify.dtdPubID(value.pubID);
					if (value.sysID != null) this.sysID = this.stringify.dtdSysID(value.sysID);
					if (value.nData != null) this.nData = this.stringify.dtdNData(value.nData);
					if (this.pe && this.nData) throw new Error("Notation declaration is not allowed in a parameter entity. " + this.debugInfo(name));
				}
			}
			Object.defineProperty(XMLDTDEntity.prototype, "publicId", { get: function() {
				return this.pubID;
			} });
			Object.defineProperty(XMLDTDEntity.prototype, "systemId", { get: function() {
				return this.sysID;
			} });
			Object.defineProperty(XMLDTDEntity.prototype, "notationName", { get: function() {
				return this.nData || null;
			} });
			Object.defineProperty(XMLDTDEntity.prototype, "inputEncoding", { get: function() {
				return null;
			} });
			Object.defineProperty(XMLDTDEntity.prototype, "xmlEncoding", { get: function() {
				return null;
			} });
			Object.defineProperty(XMLDTDEntity.prototype, "xmlVersion", { get: function() {
				return null;
			} });
			XMLDTDEntity.prototype.toString = function(options) {
				return this.options.writer.dtdEntity(this, this.options.writer.filterOptions(options));
			};
			return XMLDTDEntity;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDTDElement.js
var require_XMLDTDElement = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLNode, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		XMLNode = require_XMLNode();
		NodeType = require_NodeType();
		module.exports = (function(superClass) {
			extend(XMLDTDElement, superClass);
			function XMLDTDElement(parent, name, value) {
				XMLDTDElement.__super__.constructor.call(this, parent);
				if (name == null) throw new Error("Missing DTD element name. " + this.debugInfo());
				if (!value) value = "(#PCDATA)";
				if (Array.isArray(value)) value = "(" + value.join(",") + ")";
				this.name = this.stringify.name(name);
				this.type = NodeType.ElementDeclaration;
				this.value = this.stringify.dtdElementValue(value);
			}
			XMLDTDElement.prototype.toString = function(options) {
				return this.options.writer.dtdElement(this, this.options.writer.filterOptions(options));
			};
			return XMLDTDElement;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDTDNotation.js
var require_XMLDTDNotation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLNode, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		XMLNode = require_XMLNode();
		NodeType = require_NodeType();
		module.exports = (function(superClass) {
			extend(XMLDTDNotation, superClass);
			function XMLDTDNotation(parent, name, value) {
				XMLDTDNotation.__super__.constructor.call(this, parent);
				if (name == null) throw new Error("Missing DTD notation name. " + this.debugInfo(name));
				if (!value.pubID && !value.sysID) throw new Error("Public or system identifiers are required for an external entity. " + this.debugInfo(name));
				this.name = this.stringify.name(name);
				this.type = NodeType.NotationDeclaration;
				if (value.pubID != null) this.pubID = this.stringify.dtdPubID(value.pubID);
				if (value.sysID != null) this.sysID = this.stringify.dtdSysID(value.sysID);
			}
			Object.defineProperty(XMLDTDNotation.prototype, "publicId", { get: function() {
				return this.pubID;
			} });
			Object.defineProperty(XMLDTDNotation.prototype, "systemId", { get: function() {
				return this.sysID;
			} });
			XMLDTDNotation.prototype.toString = function(options) {
				return this.options.writer.dtdNotation(this, this.options.writer.filterOptions(options));
			};
			return XMLDTDNotation;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDocType.js
var require_XMLDocType = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLNamedNodeMap, XMLNode, isObject, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		isObject = require_Utility().isObject;
		XMLNode = require_XMLNode();
		NodeType = require_NodeType();
		XMLDTDAttList = require_XMLDTDAttList();
		XMLDTDEntity = require_XMLDTDEntity();
		XMLDTDElement = require_XMLDTDElement();
		XMLDTDNotation = require_XMLDTDNotation();
		XMLNamedNodeMap = require_XMLNamedNodeMap();
		module.exports = (function(superClass) {
			extend(XMLDocType, superClass);
			function XMLDocType(parent, pubID, sysID) {
				var child, i, len, ref, ref1, ref2;
				XMLDocType.__super__.constructor.call(this, parent);
				this.type = NodeType.DocType;
				if (parent.children) {
					ref = parent.children;
					for (i = 0, len = ref.length; i < len; i++) {
						child = ref[i];
						if (child.type === NodeType.Element) {
							this.name = child.name;
							break;
						}
					}
				}
				this.documentObject = parent;
				if (isObject(pubID)) ref1 = pubID, pubID = ref1.pubID, sysID = ref1.sysID;
				if (sysID == null) ref2 = [pubID, sysID], sysID = ref2[0], pubID = ref2[1];
				if (pubID != null) this.pubID = this.stringify.dtdPubID(pubID);
				if (sysID != null) this.sysID = this.stringify.dtdSysID(sysID);
			}
			Object.defineProperty(XMLDocType.prototype, "entities", { get: function() {
				var child, i, len, nodes = {}, ref = this.children;
				for (i = 0, len = ref.length; i < len; i++) {
					child = ref[i];
					if (child.type === NodeType.EntityDeclaration && !child.pe) nodes[child.name] = child;
				}
				return new XMLNamedNodeMap(nodes);
			} });
			Object.defineProperty(XMLDocType.prototype, "notations", { get: function() {
				var child, i, len, nodes = {}, ref = this.children;
				for (i = 0, len = ref.length; i < len; i++) {
					child = ref[i];
					if (child.type === NodeType.NotationDeclaration) nodes[child.name] = child;
				}
				return new XMLNamedNodeMap(nodes);
			} });
			Object.defineProperty(XMLDocType.prototype, "publicId", { get: function() {
				return this.pubID;
			} });
			Object.defineProperty(XMLDocType.prototype, "systemId", { get: function() {
				return this.sysID;
			} });
			Object.defineProperty(XMLDocType.prototype, "internalSubset", { get: function() {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			} });
			XMLDocType.prototype.element = function(name, value) {
				var child = new XMLDTDElement(this, name, value);
				this.children.push(child);
				return this;
			};
			XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
				var child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
				this.children.push(child);
				return this;
			};
			XMLDocType.prototype.entity = function(name, value) {
				var child = new XMLDTDEntity(this, false, name, value);
				this.children.push(child);
				return this;
			};
			XMLDocType.prototype.pEntity = function(name, value) {
				var child = new XMLDTDEntity(this, true, name, value);
				this.children.push(child);
				return this;
			};
			XMLDocType.prototype.notation = function(name, value) {
				var child = new XMLDTDNotation(this, name, value);
				this.children.push(child);
				return this;
			};
			XMLDocType.prototype.toString = function(options) {
				return this.options.writer.docType(this, this.options.writer.filterOptions(options));
			};
			XMLDocType.prototype.ele = function(name, value) {
				return this.element(name, value);
			};
			XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
				return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);
			};
			XMLDocType.prototype.ent = function(name, value) {
				return this.entity(name, value);
			};
			XMLDocType.prototype.pent = function(name, value) {
				return this.pEntity(name, value);
			};
			XMLDocType.prototype.not = function(name, value) {
				return this.notation(name, value);
			};
			XMLDocType.prototype.up = function() {
				return this.root() || this.documentObject;
			};
			XMLDocType.prototype.isEqualNode = function(node) {
				if (!XMLDocType.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) return false;
				if (node.name !== this.name) return false;
				if (node.publicId !== this.publicId) return false;
				if (node.systemId !== this.systemId) return false;
				return true;
			};
			return XMLDocType;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLRaw.js
var require_XMLRaw = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLNode, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		NodeType = require_NodeType();
		XMLNode = require_XMLNode();
		module.exports = (function(superClass) {
			extend(XMLRaw, superClass);
			function XMLRaw(parent, text) {
				XMLRaw.__super__.constructor.call(this, parent);
				if (text == null) throw new Error("Missing raw text. " + this.debugInfo());
				this.type = NodeType.Raw;
				this.value = this.stringify.raw(text);
			}
			XMLRaw.prototype.clone = function() {
				return Object.create(this);
			};
			XMLRaw.prototype.toString = function(options) {
				return this.options.writer.raw(this, this.options.writer.filterOptions(options));
			};
			return XMLRaw;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLText.js
var require_XMLText = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLCharacterData, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		NodeType = require_NodeType();
		XMLCharacterData = require_XMLCharacterData();
		module.exports = (function(superClass) {
			extend(XMLText, superClass);
			function XMLText(parent, text) {
				XMLText.__super__.constructor.call(this, parent);
				if (text == null) throw new Error("Missing element text. " + this.debugInfo());
				this.name = "#text";
				this.type = NodeType.Text;
				this.value = this.stringify.text(text);
			}
			Object.defineProperty(XMLText.prototype, "isElementContentWhitespace", { get: function() {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			} });
			Object.defineProperty(XMLText.prototype, "wholeText", { get: function() {
				var next, prev, str = "";
				prev = this.previousSibling;
				while (prev) {
					str = prev.data + str;
					prev = prev.previousSibling;
				}
				str += this.data;
				next = this.nextSibling;
				while (next) {
					str = str + next.data;
					next = next.nextSibling;
				}
				return str;
			} });
			XMLText.prototype.clone = function() {
				return Object.create(this);
			};
			XMLText.prototype.toString = function(options) {
				return this.options.writer.text(this, this.options.writer.filterOptions(options));
			};
			XMLText.prototype.splitText = function(offset) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLText.prototype.replaceWholeText = function(content) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			return XMLText;
		})(XMLCharacterData);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLProcessingInstruction.js
var require_XMLProcessingInstruction = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLCharacterData, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		NodeType = require_NodeType();
		XMLCharacterData = require_XMLCharacterData();
		module.exports = (function(superClass) {
			extend(XMLProcessingInstruction, superClass);
			function XMLProcessingInstruction(parent, target, value) {
				XMLProcessingInstruction.__super__.constructor.call(this, parent);
				if (target == null) throw new Error("Missing instruction target. " + this.debugInfo());
				this.type = NodeType.ProcessingInstruction;
				this.target = this.stringify.insTarget(target);
				this.name = this.target;
				if (value) this.value = this.stringify.insValue(value);
			}
			XMLProcessingInstruction.prototype.clone = function() {
				return Object.create(this);
			};
			XMLProcessingInstruction.prototype.toString = function(options) {
				return this.options.writer.processingInstruction(this, this.options.writer.filterOptions(options));
			};
			XMLProcessingInstruction.prototype.isEqualNode = function(node) {
				if (!XMLProcessingInstruction.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) return false;
				if (node.target !== this.target) return false;
				return true;
			};
			return XMLProcessingInstruction;
		})(XMLCharacterData);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDummy.js
var require_XMLDummy = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLNode, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		XMLNode = require_XMLNode();
		NodeType = require_NodeType();
		module.exports = (function(superClass) {
			extend(XMLDummy, superClass);
			function XMLDummy(parent) {
				XMLDummy.__super__.constructor.call(this, parent);
				this.type = NodeType.Dummy;
			}
			XMLDummy.prototype.clone = function() {
				return Object.create(this);
			};
			XMLDummy.prototype.toString = function(options) {
				return "";
			};
			return XMLDummy;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLNodeList.js
var require_XMLNodeList = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		module.exports = (function() {
			function XMLNodeList(nodes) {
				this.nodes = nodes;
			}
			Object.defineProperty(XMLNodeList.prototype, "length", { get: function() {
				return this.nodes.length || 0;
			} });
			XMLNodeList.prototype.clone = function() {
				return this.nodes = null;
			};
			XMLNodeList.prototype.item = function(index) {
				return this.nodes[index] || null;
			};
			return XMLNodeList;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/DocumentPosition.js
var require_DocumentPosition = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		module.exports = {
			Disconnected: 1,
			Preceding: 2,
			Following: 4,
			Contains: 8,
			ContainedBy: 16,
			ImplementationSpecific: 32
		};
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLNode.js
var require_XMLNode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var DocumentPosition, NodeType, XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLDummy, XMLElement, XMLNodeList, XMLProcessingInstruction, XMLRaw, XMLText, getValue, isEmpty, isFunction, isObject, ref1, hasProp = {}.hasOwnProperty;
		ref1 = require_Utility(), isObject = ref1.isObject, isFunction = ref1.isFunction, isEmpty = ref1.isEmpty, getValue = ref1.getValue;
		XMLElement = null;
		XMLCData = null;
		XMLComment = null;
		XMLDeclaration = null;
		XMLDocType = null;
		XMLRaw = null;
		XMLText = null;
		XMLProcessingInstruction = null;
		XMLDummy = null;
		NodeType = null;
		XMLNodeList = null;
		DocumentPosition = null;
		module.exports = (function() {
			function XMLNode(parent1) {
				this.parent = parent1;
				if (this.parent) {
					this.options = this.parent.options;
					this.stringify = this.parent.stringify;
				}
				this.value = null;
				this.children = [];
				this.baseURI = null;
				if (!XMLElement) {
					XMLElement = require_XMLElement();
					XMLCData = require_XMLCData();
					XMLComment = require_XMLComment();
					XMLDeclaration = require_XMLDeclaration();
					XMLDocType = require_XMLDocType();
					XMLRaw = require_XMLRaw();
					XMLText = require_XMLText();
					XMLProcessingInstruction = require_XMLProcessingInstruction();
					XMLDummy = require_XMLDummy();
					NodeType = require_NodeType();
					XMLNodeList = require_XMLNodeList();
					require_XMLNamedNodeMap();
					DocumentPosition = require_DocumentPosition();
				}
			}
			Object.defineProperty(XMLNode.prototype, "nodeName", { get: function() {
				return this.name;
			} });
			Object.defineProperty(XMLNode.prototype, "nodeType", { get: function() {
				return this.type;
			} });
			Object.defineProperty(XMLNode.prototype, "nodeValue", { get: function() {
				return this.value;
			} });
			Object.defineProperty(XMLNode.prototype, "parentNode", { get: function() {
				return this.parent;
			} });
			Object.defineProperty(XMLNode.prototype, "childNodes", { get: function() {
				if (!this.childNodeList || !this.childNodeList.nodes) this.childNodeList = new XMLNodeList(this.children);
				return this.childNodeList;
			} });
			Object.defineProperty(XMLNode.prototype, "firstChild", { get: function() {
				return this.children[0] || null;
			} });
			Object.defineProperty(XMLNode.prototype, "lastChild", { get: function() {
				return this.children[this.children.length - 1] || null;
			} });
			Object.defineProperty(XMLNode.prototype, "previousSibling", { get: function() {
				var i = this.parent.children.indexOf(this);
				return this.parent.children[i - 1] || null;
			} });
			Object.defineProperty(XMLNode.prototype, "nextSibling", { get: function() {
				var i = this.parent.children.indexOf(this);
				return this.parent.children[i + 1] || null;
			} });
			Object.defineProperty(XMLNode.prototype, "ownerDocument", { get: function() {
				return this.document() || null;
			} });
			Object.defineProperty(XMLNode.prototype, "textContent", {
				get: function() {
					var child, j, len, ref2, str;
					if (this.nodeType === NodeType.Element || this.nodeType === NodeType.DocumentFragment) {
						str = "";
						ref2 = this.children;
						for (j = 0, len = ref2.length; j < len; j++) {
							child = ref2[j];
							if (child.textContent) str += child.textContent;
						}
						return str;
					} else return null;
				},
				set: function(value) {
					throw new Error("This DOM method is not implemented." + this.debugInfo());
				}
			});
			XMLNode.prototype.setParent = function(parent) {
				var child, j, len, ref2, results;
				this.parent = parent;
				if (parent) {
					this.options = parent.options;
					this.stringify = parent.stringify;
				}
				ref2 = this.children;
				results = [];
				for (j = 0, len = ref2.length; j < len; j++) {
					child = ref2[j];
					results.push(child.setParent(this));
				}
				return results;
			};
			XMLNode.prototype.element = function(name, attributes, text) {
				var childNode, item, j, k, key, lastChild = null, len, len1, ref2, ref3, val;
				if (attributes === null && text == null) ref2 = [{}, null], attributes = ref2[0], text = ref2[1];
				if (attributes == null) attributes = {};
				attributes = getValue(attributes);
				if (!isObject(attributes)) ref3 = [attributes, text], text = ref3[0], attributes = ref3[1];
				if (name != null) name = getValue(name);
				if (Array.isArray(name)) for (j = 0, len = name.length; j < len; j++) {
					item = name[j];
					lastChild = this.element(item);
				}
				else if (isFunction(name)) lastChild = this.element(name.apply());
				else if (isObject(name)) for (key in name) {
					if (!hasProp.call(name, key)) continue;
					val = name[key];
					if (isFunction(val)) val = val.apply();
					if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);
					else if (!this.options.separateArrayItems && Array.isArray(val) && isEmpty(val)) lastChild = this.dummy();
					else if (isObject(val) && isEmpty(val)) lastChild = this.element(key);
					else if (!this.options.keepNullNodes && val == null) lastChild = this.dummy();
					else if (!this.options.separateArrayItems && Array.isArray(val)) for (k = 0, len1 = val.length; k < len1; k++) {
						item = val[k];
						childNode = {};
						childNode[key] = item;
						lastChild = this.element(childNode);
					}
					else if (isObject(val)) if (!this.options.ignoreDecorators && this.stringify.convertTextKey && key.indexOf(this.stringify.convertTextKey) === 0) lastChild = this.element(val);
					else {
						lastChild = this.element(key);
						lastChild.element(val);
					}
					else lastChild = this.element(key, val);
				}
				else if (!this.options.keepNullNodes && text === null) lastChild = this.dummy();
				else if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) lastChild = this.text(text);
				else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) lastChild = this.cdata(text);
				else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) lastChild = this.comment(text);
				else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) lastChild = this.raw(text);
				else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text);
				else lastChild = this.node(name, attributes, text);
				if (lastChild == null) throw new Error("Could not create any elements with: " + name + ". " + this.debugInfo());
				return lastChild;
			};
			XMLNode.prototype.insertBefore = function(name, attributes, text) {
				var child, i, newChild, refChild, removed;
				if (name != null ? name.type : void 0) {
					newChild = name;
					refChild = attributes;
					newChild.setParent(this);
					if (refChild) {
						i = children.indexOf(refChild);
						removed = children.splice(i);
						children.push(newChild);
						Array.prototype.push.apply(children, removed);
					} else children.push(newChild);
					return newChild;
				} else {
					if (this.isRoot) throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
					i = this.parent.children.indexOf(this);
					removed = this.parent.children.splice(i);
					child = this.parent.element(name, attributes, text);
					Array.prototype.push.apply(this.parent.children, removed);
					return child;
				}
			};
			XMLNode.prototype.insertAfter = function(name, attributes, text) {
				var child, i, removed;
				if (this.isRoot) throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
				i = this.parent.children.indexOf(this);
				removed = this.parent.children.splice(i + 1);
				child = this.parent.element(name, attributes, text);
				Array.prototype.push.apply(this.parent.children, removed);
				return child;
			};
			XMLNode.prototype.remove = function() {
				var i;
				if (this.isRoot) throw new Error("Cannot remove the root element. " + this.debugInfo());
				i = this.parent.children.indexOf(this);
				[].splice.apply(this.parent.children, [i, i - i + 1].concat([]));
				return this.parent;
			};
			XMLNode.prototype.node = function(name, attributes, text) {
				var child, ref2;
				if (name != null) name = getValue(name);
				attributes || (attributes = {});
				attributes = getValue(attributes);
				if (!isObject(attributes)) ref2 = [attributes, text], text = ref2[0], attributes = ref2[1];
				child = new XMLElement(this, name, attributes);
				if (text != null) child.text(text);
				this.children.push(child);
				return child;
			};
			XMLNode.prototype.text = function(value) {
				var child;
				if (isObject(value)) this.element(value);
				child = new XMLText(this, value);
				this.children.push(child);
				return this;
			};
			XMLNode.prototype.cdata = function(value) {
				var child = new XMLCData(this, value);
				this.children.push(child);
				return this;
			};
			XMLNode.prototype.comment = function(value) {
				var child = new XMLComment(this, value);
				this.children.push(child);
				return this;
			};
			XMLNode.prototype.commentBefore = function(value) {
				var i = this.parent.children.indexOf(this), removed = this.parent.children.splice(i);
				this.parent.comment(value);
				Array.prototype.push.apply(this.parent.children, removed);
				return this;
			};
			XMLNode.prototype.commentAfter = function(value) {
				var i = this.parent.children.indexOf(this), removed = this.parent.children.splice(i + 1);
				this.parent.comment(value);
				Array.prototype.push.apply(this.parent.children, removed);
				return this;
			};
			XMLNode.prototype.raw = function(value) {
				var child = new XMLRaw(this, value);
				this.children.push(child);
				return this;
			};
			XMLNode.prototype.dummy = function() {
				return new XMLDummy(this);
			};
			XMLNode.prototype.instruction = function(target, value) {
				var insTarget, insValue, instruction, j, len;
				if (target != null) target = getValue(target);
				if (value != null) value = getValue(value);
				if (Array.isArray(target)) for (j = 0, len = target.length; j < len; j++) {
					insTarget = target[j];
					this.instruction(insTarget);
				}
				else if (isObject(target)) for (insTarget in target) {
					if (!hasProp.call(target, insTarget)) continue;
					insValue = target[insTarget];
					this.instruction(insTarget, insValue);
				}
				else {
					if (isFunction(value)) value = value.apply();
					instruction = new XMLProcessingInstruction(this, target, value);
					this.children.push(instruction);
				}
				return this;
			};
			XMLNode.prototype.instructionBefore = function(target, value) {
				var i = this.parent.children.indexOf(this), removed = this.parent.children.splice(i);
				this.parent.instruction(target, value);
				Array.prototype.push.apply(this.parent.children, removed);
				return this;
			};
			XMLNode.prototype.instructionAfter = function(target, value) {
				var i = this.parent.children.indexOf(this), removed = this.parent.children.splice(i + 1);
				this.parent.instruction(target, value);
				Array.prototype.push.apply(this.parent.children, removed);
				return this;
			};
			XMLNode.prototype.declaration = function(version, encoding, standalone) {
				var doc = this.document(), xmldec = new XMLDeclaration(doc, version, encoding, standalone);
				if (doc.children.length === 0) doc.children.unshift(xmldec);
				else if (doc.children[0].type === NodeType.Declaration) doc.children[0] = xmldec;
				else doc.children.unshift(xmldec);
				return doc.root() || doc;
			};
			XMLNode.prototype.dtd = function(pubID, sysID) {
				var child, doc = this.document(), doctype = new XMLDocType(doc, pubID, sysID), i, j, k, len, len1, ref2 = doc.children, ref3;
				for (i = j = 0, len = ref2.length; j < len; i = ++j) {
					child = ref2[i];
					if (child.type === NodeType.DocType) {
						doc.children[i] = doctype;
						return doctype;
					}
				}
				ref3 = doc.children;
				for (i = k = 0, len1 = ref3.length; k < len1; i = ++k) {
					child = ref3[i];
					if (child.isRoot) {
						doc.children.splice(i, 0, doctype);
						return doctype;
					}
				}
				doc.children.push(doctype);
				return doctype;
			};
			XMLNode.prototype.up = function() {
				if (this.isRoot) throw new Error("The root node has no parent. Use doc() if you need to get the document object.");
				return this.parent;
			};
			XMLNode.prototype.root = function() {
				var node = this;
				while (node) if (node.type === NodeType.Document) return node.rootObject;
				else if (node.isRoot) return node;
				else node = node.parent;
			};
			XMLNode.prototype.document = function() {
				var node = this;
				while (node) if (node.type === NodeType.Document) return node;
				else node = node.parent;
			};
			XMLNode.prototype.end = function(options) {
				return this.document().end(options);
			};
			XMLNode.prototype.prev = function() {
				var i = this.parent.children.indexOf(this);
				if (i < 1) throw new Error("Already at the first node. " + this.debugInfo());
				return this.parent.children[i - 1];
			};
			XMLNode.prototype.next = function() {
				var i = this.parent.children.indexOf(this);
				if (i === -1 || i === this.parent.children.length - 1) throw new Error("Already at the last node. " + this.debugInfo());
				return this.parent.children[i + 1];
			};
			XMLNode.prototype.importDocument = function(doc) {
				var clonedRoot = doc.root().clone();
				clonedRoot.parent = this;
				clonedRoot.isRoot = false;
				this.children.push(clonedRoot);
				return this;
			};
			XMLNode.prototype.debugInfo = function(name) {
				var ref2, ref3;
				name = name || this.name;
				if (name == null && !((ref2 = this.parent) != null ? ref2.name : void 0)) return "";
				else if (name == null) return "parent: <" + this.parent.name + ">";
				else if (!((ref3 = this.parent) != null ? ref3.name : void 0)) return "node: <" + name + ">";
				else return "node: <" + name + ">, parent: <" + this.parent.name + ">";
			};
			XMLNode.prototype.ele = function(name, attributes, text) {
				return this.element(name, attributes, text);
			};
			XMLNode.prototype.nod = function(name, attributes, text) {
				return this.node(name, attributes, text);
			};
			XMLNode.prototype.txt = function(value) {
				return this.text(value);
			};
			XMLNode.prototype.dat = function(value) {
				return this.cdata(value);
			};
			XMLNode.prototype.com = function(value) {
				return this.comment(value);
			};
			XMLNode.prototype.ins = function(target, value) {
				return this.instruction(target, value);
			};
			XMLNode.prototype.doc = function() {
				return this.document();
			};
			XMLNode.prototype.dec = function(version, encoding, standalone) {
				return this.declaration(version, encoding, standalone);
			};
			XMLNode.prototype.e = function(name, attributes, text) {
				return this.element(name, attributes, text);
			};
			XMLNode.prototype.n = function(name, attributes, text) {
				return this.node(name, attributes, text);
			};
			XMLNode.prototype.t = function(value) {
				return this.text(value);
			};
			XMLNode.prototype.d = function(value) {
				return this.cdata(value);
			};
			XMLNode.prototype.c = function(value) {
				return this.comment(value);
			};
			XMLNode.prototype.r = function(value) {
				return this.raw(value);
			};
			XMLNode.prototype.i = function(target, value) {
				return this.instruction(target, value);
			};
			XMLNode.prototype.u = function() {
				return this.up();
			};
			XMLNode.prototype.importXMLBuilder = function(doc) {
				return this.importDocument(doc);
			};
			XMLNode.prototype.replaceChild = function(newChild, oldChild) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.removeChild = function(oldChild) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.appendChild = function(newChild) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.hasChildNodes = function() {
				return this.children.length !== 0;
			};
			XMLNode.prototype.cloneNode = function(deep) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.normalize = function() {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.isSupported = function(feature, version) {
				return true;
			};
			XMLNode.prototype.hasAttributes = function() {
				return this.attribs.length !== 0;
			};
			XMLNode.prototype.compareDocumentPosition = function(other) {
				var ref = this, res;
				if (ref === other) return 0;
				else if (this.document() !== other.document()) {
					res = DocumentPosition.Disconnected | DocumentPosition.ImplementationSpecific;
					if (Math.random() < .5) res |= DocumentPosition.Preceding;
					else res |= DocumentPosition.Following;
					return res;
				} else if (ref.isAncestor(other)) return DocumentPosition.Contains | DocumentPosition.Preceding;
				else if (ref.isDescendant(other)) return DocumentPosition.Contains | DocumentPosition.Following;
				else if (ref.isPreceding(other)) return DocumentPosition.Preceding;
				else return DocumentPosition.Following;
			};
			XMLNode.prototype.isSameNode = function(other) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.lookupPrefix = function(namespaceURI) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.isDefaultNamespace = function(namespaceURI) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.lookupNamespaceURI = function(prefix) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.isEqualNode = function(node) {
				var i, j, ref2;
				if (node.nodeType !== this.nodeType) return false;
				if (node.children.length !== this.children.length) return false;
				for (i = j = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j <= ref2 : j >= ref2; i = 0 <= ref2 ? ++j : --j) if (!this.children[i].isEqualNode(node.children[i])) return false;
				return true;
			};
			XMLNode.prototype.getFeature = function(feature, version) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.setUserData = function(key, data, handler) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.getUserData = function(key) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLNode.prototype.contains = function(other) {
				if (!other) return false;
				return other === this || this.isDescendant(other);
			};
			XMLNode.prototype.isDescendant = function(node) {
				var child, isDescendantChild, j, len, ref2 = this.children;
				for (j = 0, len = ref2.length; j < len; j++) {
					child = ref2[j];
					if (node === child) return true;
					isDescendantChild = child.isDescendant(node);
					if (isDescendantChild) return true;
				}
				return false;
			};
			XMLNode.prototype.isAncestor = function(node) {
				return node.isDescendant(this);
			};
			XMLNode.prototype.isPreceding = function(node) {
				var nodePos = this.treePosition(node), thisPos = this.treePosition(this);
				if (nodePos === -1 || thisPos === -1) return false;
				else return nodePos < thisPos;
			};
			XMLNode.prototype.isFollowing = function(node) {
				var nodePos = this.treePosition(node), thisPos = this.treePosition(this);
				if (nodePos === -1 || thisPos === -1) return false;
				else return nodePos > thisPos;
			};
			XMLNode.prototype.treePosition = function(node) {
				var found, pos = 0;
				found = false;
				this.foreachTreeNode(this.document(), function(childNode) {
					pos++;
					if (!found && childNode === node) return found = true;
				});
				if (found) return pos;
				else return -1;
			};
			XMLNode.prototype.foreachTreeNode = function(node, func) {
				var child, j, len, ref2, res;
				node || (node = this.document());
				ref2 = node.children;
				for (j = 0, len = ref2.length; j < len; j++) {
					child = ref2[j];
					if (res = func(child)) return res;
					else {
						res = this.foreachTreeNode(child, func);
						if (res) return res;
					}
				}
			};
			return XMLNode;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLStringifier.js
var require_XMLStringifier = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var bind = function(fn, me) {
			return function() {
				return fn.apply(me, arguments);
			};
		}, hasProp = {}.hasOwnProperty;
		module.exports = (function() {
			function XMLStringifier(options) {
				this.assertLegalName = bind(this.assertLegalName, this);
				this.assertLegalChar = bind(this.assertLegalChar, this);
				var key, ref, value;
				options || (options = {});
				this.options = options;
				if (!this.options.version) this.options.version = "1.0";
				ref = options.stringify || {};
				for (key in ref) {
					if (!hasProp.call(ref, key)) continue;
					value = ref[key];
					this[key] = value;
				}
			}
			XMLStringifier.prototype.name = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalName("" + val || "");
			};
			XMLStringifier.prototype.text = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalChar(this.textEscape("" + val || ""));
			};
			XMLStringifier.prototype.cdata = function(val) {
				if (this.options.noValidation) return val;
				val = "" + val || "";
				val = val.replace("]]>", "]]]]><![CDATA[>");
				return this.assertLegalChar(val);
			};
			XMLStringifier.prototype.comment = function(val) {
				if (this.options.noValidation) return val;
				val = "" + val || "";
				if (val.match(/--/)) throw new Error("Comment text cannot contain double-hypen: " + val);
				return this.assertLegalChar(val);
			};
			XMLStringifier.prototype.raw = function(val) {
				if (this.options.noValidation) return val;
				return "" + val || "";
			};
			XMLStringifier.prototype.attValue = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalChar(this.attEscape(val = "" + val || ""));
			};
			XMLStringifier.prototype.insTarget = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalChar("" + val || "");
			};
			XMLStringifier.prototype.insValue = function(val) {
				if (this.options.noValidation) return val;
				val = "" + val || "";
				if (val.match(/\?>/)) throw new Error("Invalid processing instruction value: " + val);
				return this.assertLegalChar(val);
			};
			XMLStringifier.prototype.xmlVersion = function(val) {
				if (this.options.noValidation) return val;
				val = "" + val || "";
				if (!val.match(/1\.[0-9]+/)) throw new Error("Invalid version number: " + val);
				return val;
			};
			XMLStringifier.prototype.xmlEncoding = function(val) {
				if (this.options.noValidation) return val;
				val = "" + val || "";
				if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) throw new Error("Invalid encoding: " + val);
				return this.assertLegalChar(val);
			};
			XMLStringifier.prototype.xmlStandalone = function(val) {
				if (this.options.noValidation) return val;
				if (val) return "yes";
				else return "no";
			};
			XMLStringifier.prototype.dtdPubID = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalChar("" + val || "");
			};
			XMLStringifier.prototype.dtdSysID = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalChar("" + val || "");
			};
			XMLStringifier.prototype.dtdElementValue = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalChar("" + val || "");
			};
			XMLStringifier.prototype.dtdAttType = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalChar("" + val || "");
			};
			XMLStringifier.prototype.dtdAttDefault = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalChar("" + val || "");
			};
			XMLStringifier.prototype.dtdEntityValue = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalChar("" + val || "");
			};
			XMLStringifier.prototype.dtdNData = function(val) {
				if (this.options.noValidation) return val;
				return this.assertLegalChar("" + val || "");
			};
			XMLStringifier.prototype.convertAttKey = "@";
			XMLStringifier.prototype.convertPIKey = "?";
			XMLStringifier.prototype.convertTextKey = "#text";
			XMLStringifier.prototype.convertCDataKey = "#cdata";
			XMLStringifier.prototype.convertCommentKey = "#comment";
			XMLStringifier.prototype.convertRawKey = "#raw";
			XMLStringifier.prototype.assertLegalChar = function(str) {
				var regex, res;
				if (this.options.noValidation) return str;
				regex = "";
				if (this.options.version === "1.0") {
					regex = /[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
					if (res = str.match(regex)) throw new Error("Invalid character in string: " + str + " at index " + res.index);
				} else if (this.options.version === "1.1") {
					regex = /[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
					if (res = str.match(regex)) throw new Error("Invalid character in string: " + str + " at index " + res.index);
				}
				return str;
			};
			XMLStringifier.prototype.assertLegalName = function(str) {
				var regex;
				if (this.options.noValidation) return str;
				this.assertLegalChar(str);
				regex = /^([:A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])([\x2D\.0-:A-Z_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*$/;
				if (!str.match(regex)) throw new Error("Invalid character in name");
				return str;
			};
			XMLStringifier.prototype.textEscape = function(str) {
				var ampregex;
				if (this.options.noValidation) return str;
				ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
				return str.replace(ampregex, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r/g, "&#xD;");
			};
			XMLStringifier.prototype.attEscape = function(str) {
				var ampregex;
				if (this.options.noValidation) return str;
				ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
				return str.replace(ampregex, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;").replace(/\t/g, "&#x9;").replace(/\n/g, "&#xA;").replace(/\r/g, "&#xD;");
			};
			return XMLStringifier;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/WriterState.js
var require_WriterState = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		module.exports = {
			None: 0,
			OpenTag: 1,
			InsideTag: 2,
			CloseTag: 3
		};
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLWriterBase.js
var require_XMLWriterBase = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, WriterState, assign, hasProp = {}.hasOwnProperty;
		assign = require_Utility().assign;
		NodeType = require_NodeType();
		require_XMLDeclaration();
		require_XMLDocType();
		require_XMLCData();
		require_XMLComment();
		require_XMLElement();
		require_XMLRaw();
		require_XMLText();
		require_XMLProcessingInstruction();
		require_XMLDummy();
		require_XMLDTDAttList();
		require_XMLDTDElement();
		require_XMLDTDEntity();
		require_XMLDTDNotation();
		WriterState = require_WriterState();
		module.exports = (function() {
			function XMLWriterBase(options) {
				var key, ref, value;
				options || (options = {});
				this.options = options;
				ref = options.writer || {};
				for (key in ref) {
					if (!hasProp.call(ref, key)) continue;
					value = ref[key];
					this["_" + key] = this[key];
					this[key] = value;
				}
			}
			XMLWriterBase.prototype.filterOptions = function(options) {
				var filteredOptions, ref, ref1, ref2, ref3, ref4, ref5, ref6;
				options || (options = {});
				options = assign({}, this.options, options);
				filteredOptions = { writer: this };
				filteredOptions.pretty = options.pretty || false;
				filteredOptions.allowEmpty = options.allowEmpty || false;
				filteredOptions.indent = (ref = options.indent) != null ? ref : "  ";
				filteredOptions.newline = (ref1 = options.newline) != null ? ref1 : "\n";
				filteredOptions.offset = (ref2 = options.offset) != null ? ref2 : 0;
				filteredOptions.dontPrettyTextNodes = (ref3 = (ref4 = options.dontPrettyTextNodes) != null ? ref4 : options.dontprettytextnodes) != null ? ref3 : 0;
				filteredOptions.spaceBeforeSlash = (ref5 = (ref6 = options.spaceBeforeSlash) != null ? ref6 : options.spacebeforeslash) != null ? ref5 : "";
				if (filteredOptions.spaceBeforeSlash === true) filteredOptions.spaceBeforeSlash = " ";
				filteredOptions.suppressPrettyCount = 0;
				filteredOptions.user = {};
				filteredOptions.state = WriterState.None;
				return filteredOptions;
			};
			XMLWriterBase.prototype.indent = function(node, options, level) {
				var indentLevel;
				if (!options.pretty || options.suppressPrettyCount) return "";
				else if (options.pretty) {
					indentLevel = (level || 0) + options.offset + 1;
					if (indentLevel > 0) return new Array(indentLevel).join(options.indent);
				}
				return "";
			};
			XMLWriterBase.prototype.endline = function(node, options, level) {
				if (!options.pretty || options.suppressPrettyCount) return "";
				else return options.newline;
			};
			XMLWriterBase.prototype.attribute = function(att, options, level) {
				var r;
				this.openAttribute(att, options, level);
				r = " " + att.name + "=\"" + att.value + "\"";
				this.closeAttribute(att, options, level);
				return r;
			};
			XMLWriterBase.prototype.cdata = function(node, options, level) {
				var r;
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level) + "<![CDATA[";
				options.state = WriterState.InsideTag;
				r += node.value;
				options.state = WriterState.CloseTag;
				r += "]]>" + this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.comment = function(node, options, level) {
				var r;
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level) + "<!-- ";
				options.state = WriterState.InsideTag;
				r += node.value;
				options.state = WriterState.CloseTag;
				r += " -->" + this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.declaration = function(node, options, level) {
				var r;
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level) + "<?xml";
				options.state = WriterState.InsideTag;
				r += " version=\"" + node.version + "\"";
				if (node.encoding != null) r += " encoding=\"" + node.encoding + "\"";
				if (node.standalone != null) r += " standalone=\"" + node.standalone + "\"";
				options.state = WriterState.CloseTag;
				r += options.spaceBeforeSlash + "?>";
				r += this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.docType = function(node, options, level) {
				var child, i, len, r, ref;
				level || (level = 0);
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level);
				r += "<!DOCTYPE " + node.root().name;
				if (node.pubID && node.sysID) r += " PUBLIC \"" + node.pubID + "\" \"" + node.sysID + "\"";
				else if (node.sysID) r += " SYSTEM \"" + node.sysID + "\"";
				if (node.children.length > 0) {
					r += " [";
					r += this.endline(node, options, level);
					options.state = WriterState.InsideTag;
					ref = node.children;
					for (i = 0, len = ref.length; i < len; i++) {
						child = ref[i];
						r += this.writeChildNode(child, options, level + 1);
					}
					options.state = WriterState.CloseTag;
					r += "]";
				}
				options.state = WriterState.CloseTag;
				r += options.spaceBeforeSlash + ">";
				r += this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.element = function(node, options, level) {
				var att, child, childNodeCount, firstChildNode, i, j, len, len1, name, prettySuppressed, r, ref, ref1, ref2;
				level || (level = 0);
				prettySuppressed = false;
				r = "";
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r += this.indent(node, options, level) + "<" + node.name;
				ref = node.attribs;
				for (name in ref) {
					if (!hasProp.call(ref, name)) continue;
					att = ref[name];
					r += this.attribute(att, options, level);
				}
				childNodeCount = node.children.length;
				firstChildNode = childNodeCount === 0 ? null : node.children[0];
				if (childNodeCount === 0 || node.children.every(function(e) {
					return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === "";
				})) if (options.allowEmpty) {
					r += ">";
					options.state = WriterState.CloseTag;
					r += "</" + node.name + ">" + this.endline(node, options, level);
				} else {
					options.state = WriterState.CloseTag;
					r += options.spaceBeforeSlash + "/>" + this.endline(node, options, level);
				}
				else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && firstChildNode.value != null) {
					r += ">";
					options.state = WriterState.InsideTag;
					options.suppressPrettyCount++;
					prettySuppressed = true;
					r += this.writeChildNode(firstChildNode, options, level + 1);
					options.suppressPrettyCount--;
					prettySuppressed = false;
					options.state = WriterState.CloseTag;
					r += "</" + node.name + ">" + this.endline(node, options, level);
				} else {
					if (options.dontPrettyTextNodes) {
						ref1 = node.children;
						for (i = 0, len = ref1.length; i < len; i++) {
							child = ref1[i];
							if ((child.type === NodeType.Text || child.type === NodeType.Raw) && child.value != null) {
								options.suppressPrettyCount++;
								prettySuppressed = true;
								break;
							}
						}
					}
					r += ">" + this.endline(node, options, level);
					options.state = WriterState.InsideTag;
					ref2 = node.children;
					for (j = 0, len1 = ref2.length; j < len1; j++) {
						child = ref2[j];
						r += this.writeChildNode(child, options, level + 1);
					}
					options.state = WriterState.CloseTag;
					r += this.indent(node, options, level) + "</" + node.name + ">";
					if (prettySuppressed) options.suppressPrettyCount--;
					r += this.endline(node, options, level);
					options.state = WriterState.None;
				}
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.writeChildNode = function(node, options, level) {
				switch (node.type) {
					case NodeType.CData: return this.cdata(node, options, level);
					case NodeType.Comment: return this.comment(node, options, level);
					case NodeType.Element: return this.element(node, options, level);
					case NodeType.Raw: return this.raw(node, options, level);
					case NodeType.Text: return this.text(node, options, level);
					case NodeType.ProcessingInstruction: return this.processingInstruction(node, options, level);
					case NodeType.Dummy: return "";
					case NodeType.Declaration: return this.declaration(node, options, level);
					case NodeType.DocType: return this.docType(node, options, level);
					case NodeType.AttributeDeclaration: return this.dtdAttList(node, options, level);
					case NodeType.ElementDeclaration: return this.dtdElement(node, options, level);
					case NodeType.EntityDeclaration: return this.dtdEntity(node, options, level);
					case NodeType.NotationDeclaration: return this.dtdNotation(node, options, level);
					default: throw new Error("Unknown XML node type: " + node.constructor.name);
				}
			};
			XMLWriterBase.prototype.processingInstruction = function(node, options, level) {
				var r;
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level) + "<?";
				options.state = WriterState.InsideTag;
				r += node.target;
				if (node.value) r += " " + node.value;
				options.state = WriterState.CloseTag;
				r += options.spaceBeforeSlash + "?>";
				r += this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.raw = function(node, options, level) {
				var r;
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level);
				options.state = WriterState.InsideTag;
				r += node.value;
				options.state = WriterState.CloseTag;
				r += this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.text = function(node, options, level) {
				var r;
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level);
				options.state = WriterState.InsideTag;
				r += node.value;
				options.state = WriterState.CloseTag;
				r += this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.dtdAttList = function(node, options, level) {
				var r;
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level) + "<!ATTLIST";
				options.state = WriterState.InsideTag;
				r += " " + node.elementName + " " + node.attributeName + " " + node.attributeType;
				if (node.defaultValueType !== "#DEFAULT") r += " " + node.defaultValueType;
				if (node.defaultValue) r += " \"" + node.defaultValue + "\"";
				options.state = WriterState.CloseTag;
				r += options.spaceBeforeSlash + ">" + this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.dtdElement = function(node, options, level) {
				var r;
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level) + "<!ELEMENT";
				options.state = WriterState.InsideTag;
				r += " " + node.name + " " + node.value;
				options.state = WriterState.CloseTag;
				r += options.spaceBeforeSlash + ">" + this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.dtdEntity = function(node, options, level) {
				var r;
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level) + "<!ENTITY";
				options.state = WriterState.InsideTag;
				if (node.pe) r += " %";
				r += " " + node.name;
				if (node.value) r += " \"" + node.value + "\"";
				else {
					if (node.pubID && node.sysID) r += " PUBLIC \"" + node.pubID + "\" \"" + node.sysID + "\"";
					else if (node.sysID) r += " SYSTEM \"" + node.sysID + "\"";
					if (node.nData) r += " NDATA " + node.nData;
				}
				options.state = WriterState.CloseTag;
				r += options.spaceBeforeSlash + ">" + this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.dtdNotation = function(node, options, level) {
				var r;
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				r = this.indent(node, options, level) + "<!NOTATION";
				options.state = WriterState.InsideTag;
				r += " " + node.name;
				if (node.pubID && node.sysID) r += " PUBLIC \"" + node.pubID + "\" \"" + node.sysID + "\"";
				else if (node.pubID) r += " PUBLIC \"" + node.pubID + "\"";
				else if (node.sysID) r += " SYSTEM \"" + node.sysID + "\"";
				options.state = WriterState.CloseTag;
				r += options.spaceBeforeSlash + ">" + this.endline(node, options, level);
				options.state = WriterState.None;
				this.closeNode(node, options, level);
				return r;
			};
			XMLWriterBase.prototype.openNode = function(node, options, level) {};
			XMLWriterBase.prototype.closeNode = function(node, options, level) {};
			XMLWriterBase.prototype.openAttribute = function(att, options, level) {};
			XMLWriterBase.prototype.closeAttribute = function(att, options, level) {};
			return XMLWriterBase;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLStringWriter.js
var require_XMLStringWriter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var XMLWriterBase, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		XMLWriterBase = require_XMLWriterBase();
		module.exports = (function(superClass) {
			extend(XMLStringWriter, superClass);
			function XMLStringWriter(options) {
				XMLStringWriter.__super__.constructor.call(this, options);
			}
			XMLStringWriter.prototype.document = function(doc, options) {
				var child, i, len, r, ref;
				options = this.filterOptions(options);
				r = "";
				ref = doc.children;
				for (i = 0, len = ref.length; i < len; i++) {
					child = ref[i];
					r += this.writeChildNode(child, options, 0);
				}
				if (options.pretty && r.slice(-options.newline.length) === options.newline) r = r.slice(0, -options.newline.length);
				return r;
			};
			return XMLStringWriter;
		})(XMLWriterBase);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDocument.js
var require_XMLDocument = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, XMLDOMConfiguration, XMLDOMImplementation, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		isPlainObject = require_Utility().isPlainObject;
		XMLDOMImplementation = require_XMLDOMImplementation();
		XMLDOMConfiguration = require_XMLDOMConfiguration();
		XMLNode = require_XMLNode();
		NodeType = require_NodeType();
		XMLStringifier = require_XMLStringifier();
		XMLStringWriter = require_XMLStringWriter();
		module.exports = (function(superClass) {
			extend(XMLDocument, superClass);
			function XMLDocument(options) {
				XMLDocument.__super__.constructor.call(this, null);
				this.name = "#document";
				this.type = NodeType.Document;
				this.documentURI = null;
				this.domConfig = new XMLDOMConfiguration();
				options || (options = {});
				if (!options.writer) options.writer = new XMLStringWriter();
				this.options = options;
				this.stringify = new XMLStringifier(options);
			}
			Object.defineProperty(XMLDocument.prototype, "implementation", { value: new XMLDOMImplementation() });
			Object.defineProperty(XMLDocument.prototype, "doctype", { get: function() {
				var child, i, len, ref = this.children;
				for (i = 0, len = ref.length; i < len; i++) {
					child = ref[i];
					if (child.type === NodeType.DocType) return child;
				}
				return null;
			} });
			Object.defineProperty(XMLDocument.prototype, "documentElement", { get: function() {
				return this.rootObject || null;
			} });
			Object.defineProperty(XMLDocument.prototype, "inputEncoding", { get: function() {
				return null;
			} });
			Object.defineProperty(XMLDocument.prototype, "strictErrorChecking", { get: function() {
				return false;
			} });
			Object.defineProperty(XMLDocument.prototype, "xmlEncoding", { get: function() {
				if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) return this.children[0].encoding;
				else return null;
			} });
			Object.defineProperty(XMLDocument.prototype, "xmlStandalone", { get: function() {
				if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) return this.children[0].standalone === "yes";
				else return false;
			} });
			Object.defineProperty(XMLDocument.prototype, "xmlVersion", { get: function() {
				if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) return this.children[0].version;
				else return "1.0";
			} });
			Object.defineProperty(XMLDocument.prototype, "URL", { get: function() {
				return this.documentURI;
			} });
			Object.defineProperty(XMLDocument.prototype, "origin", { get: function() {
				return null;
			} });
			Object.defineProperty(XMLDocument.prototype, "compatMode", { get: function() {
				return null;
			} });
			Object.defineProperty(XMLDocument.prototype, "characterSet", { get: function() {
				return null;
			} });
			Object.defineProperty(XMLDocument.prototype, "contentType", { get: function() {
				return null;
			} });
			XMLDocument.prototype.end = function(writer) {
				var writerOptions = {};
				if (!writer) writer = this.options.writer;
				else if (isPlainObject(writer)) {
					writerOptions = writer;
					writer = this.options.writer;
				}
				return writer.document(this, writer.filterOptions(writerOptions));
			};
			XMLDocument.prototype.toString = function(options) {
				return this.options.writer.document(this, this.options.writer.filterOptions(options));
			};
			XMLDocument.prototype.createElement = function(tagName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createDocumentFragment = function() {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createTextNode = function(data) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createComment = function(data) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createCDATASection = function(data) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createProcessingInstruction = function(target, data) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createAttribute = function(name) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createEntityReference = function(name) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.getElementsByTagName = function(tagname) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.importNode = function(importedNode, deep) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createElementNS = function(namespaceURI, qualifiedName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createAttributeNS = function(namespaceURI, qualifiedName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.getElementsByTagNameNS = function(namespaceURI, localName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.getElementById = function(elementId) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.adoptNode = function(source) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.normalizeDocument = function() {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.renameNode = function(node, namespaceURI, qualifiedName) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.getElementsByClassName = function(classNames) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createEvent = function(eventInterface) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createRange = function() {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createNodeIterator = function(root, whatToShow, filter) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			XMLDocument.prototype.createTreeWalker = function(root, whatToShow, filter) {
				throw new Error("This DOM method is not implemented." + this.debugInfo());
			};
			return XMLDocument;
		})(XMLNode);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLDocumentCB.js
var require_XMLDocumentCB = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, WriterState, XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocument, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue, isFunction, isObject, isPlainObject, ref, hasProp = {}.hasOwnProperty;
		ref = require_Utility(), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject, getValue = ref.getValue;
		NodeType = require_NodeType();
		XMLDocument = require_XMLDocument();
		XMLElement = require_XMLElement();
		XMLCData = require_XMLCData();
		XMLComment = require_XMLComment();
		XMLRaw = require_XMLRaw();
		XMLText = require_XMLText();
		XMLProcessingInstruction = require_XMLProcessingInstruction();
		XMLDeclaration = require_XMLDeclaration();
		XMLDocType = require_XMLDocType();
		XMLDTDAttList = require_XMLDTDAttList();
		XMLDTDEntity = require_XMLDTDEntity();
		XMLDTDElement = require_XMLDTDElement();
		XMLDTDNotation = require_XMLDTDNotation();
		XMLAttribute = require_XMLAttribute();
		XMLStringifier = require_XMLStringifier();
		XMLStringWriter = require_XMLStringWriter();
		WriterState = require_WriterState();
		module.exports = (function() {
			function XMLDocumentCB(options, onData, onEnd) {
				var writerOptions;
				this.name = "?xml";
				this.type = NodeType.Document;
				options || (options = {});
				writerOptions = {};
				if (!options.writer) options.writer = new XMLStringWriter();
				else if (isPlainObject(options.writer)) {
					writerOptions = options.writer;
					options.writer = new XMLStringWriter();
				}
				this.options = options;
				this.writer = options.writer;
				this.writerOptions = this.writer.filterOptions(writerOptions);
				this.stringify = new XMLStringifier(options);
				this.onDataCallback = onData || function() {};
				this.onEndCallback = onEnd || function() {};
				this.currentNode = null;
				this.currentLevel = -1;
				this.openTags = {};
				this.documentStarted = false;
				this.documentCompleted = false;
				this.root = null;
			}
			XMLDocumentCB.prototype.createChildNode = function(node) {
				var att, attName, attributes, child, i, len, ref1, ref2;
				switch (node.type) {
					case NodeType.CData:
						this.cdata(node.value);
						break;
					case NodeType.Comment:
						this.comment(node.value);
						break;
					case NodeType.Element:
						attributes = {};
						ref1 = node.attribs;
						for (attName in ref1) {
							if (!hasProp.call(ref1, attName)) continue;
							att = ref1[attName];
							attributes[attName] = att.value;
						}
						this.node(node.name, attributes);
						break;
					case NodeType.Dummy:
						this.dummy();
						break;
					case NodeType.Raw:
						this.raw(node.value);
						break;
					case NodeType.Text:
						this.text(node.value);
						break;
					case NodeType.ProcessingInstruction:
						this.instruction(node.target, node.value);
						break;
					default: throw new Error("This XML node type is not supported in a JS object: " + node.constructor.name);
				}
				ref2 = node.children;
				for (i = 0, len = ref2.length; i < len; i++) {
					child = ref2[i];
					this.createChildNode(child);
					if (child.type === NodeType.Element) this.up();
				}
				return this;
			};
			XMLDocumentCB.prototype.dummy = function() {
				return this;
			};
			XMLDocumentCB.prototype.node = function(name, attributes, text) {
				var ref1;
				if (name == null) throw new Error("Missing node name.");
				if (this.root && this.currentLevel === -1) throw new Error("Document can only have one root node. " + this.debugInfo(name));
				this.openCurrent();
				name = getValue(name);
				if (attributes == null) attributes = {};
				attributes = getValue(attributes);
				if (!isObject(attributes)) ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
				this.currentNode = new XMLElement(this, name, attributes);
				this.currentNode.children = false;
				this.currentLevel++;
				this.openTags[this.currentLevel] = this.currentNode;
				if (text != null) this.text(text);
				return this;
			};
			XMLDocumentCB.prototype.element = function(name, attributes, text) {
				var child, i, len, oldValidationFlag, ref1, root;
				if (this.currentNode && this.currentNode.type === NodeType.DocType) this.dtdElement.apply(this, arguments);
				else if (Array.isArray(name) || isObject(name) || isFunction(name)) {
					oldValidationFlag = this.options.noValidation;
					this.options.noValidation = true;
					root = new XMLDocument(this.options).element("TEMP_ROOT");
					root.element(name);
					this.options.noValidation = oldValidationFlag;
					ref1 = root.children;
					for (i = 0, len = ref1.length; i < len; i++) {
						child = ref1[i];
						this.createChildNode(child);
						if (child.type === NodeType.Element) this.up();
					}
				} else this.node(name, attributes, text);
				return this;
			};
			XMLDocumentCB.prototype.attribute = function(name, value) {
				var attName, attValue;
				if (!this.currentNode || this.currentNode.children) throw new Error("att() can only be used immediately after an ele() call in callback mode. " + this.debugInfo(name));
				if (name != null) name = getValue(name);
				if (isObject(name)) for (attName in name) {
					if (!hasProp.call(name, attName)) continue;
					attValue = name[attName];
					this.attribute(attName, attValue);
				}
				else {
					if (isFunction(value)) value = value.apply();
					if (this.options.keepNullAttributes && value == null) this.currentNode.attribs[name] = new XMLAttribute(this, name, "");
					else if (value != null) this.currentNode.attribs[name] = new XMLAttribute(this, name, value);
				}
				return this;
			};
			XMLDocumentCB.prototype.text = function(value) {
				var node;
				this.openCurrent();
				node = new XMLText(this, value);
				this.onData(this.writer.text(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				return this;
			};
			XMLDocumentCB.prototype.cdata = function(value) {
				var node;
				this.openCurrent();
				node = new XMLCData(this, value);
				this.onData(this.writer.cdata(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				return this;
			};
			XMLDocumentCB.prototype.comment = function(value) {
				var node;
				this.openCurrent();
				node = new XMLComment(this, value);
				this.onData(this.writer.comment(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				return this;
			};
			XMLDocumentCB.prototype.raw = function(value) {
				var node;
				this.openCurrent();
				node = new XMLRaw(this, value);
				this.onData(this.writer.raw(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				return this;
			};
			XMLDocumentCB.prototype.instruction = function(target, value) {
				var i, insTarget, insValue, len, node;
				this.openCurrent();
				if (target != null) target = getValue(target);
				if (value != null) value = getValue(value);
				if (Array.isArray(target)) for (i = 0, len = target.length; i < len; i++) {
					insTarget = target[i];
					this.instruction(insTarget);
				}
				else if (isObject(target)) for (insTarget in target) {
					if (!hasProp.call(target, insTarget)) continue;
					insValue = target[insTarget];
					this.instruction(insTarget, insValue);
				}
				else {
					if (isFunction(value)) value = value.apply();
					node = new XMLProcessingInstruction(this, target, value);
					this.onData(this.writer.processingInstruction(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				}
				return this;
			};
			XMLDocumentCB.prototype.declaration = function(version, encoding, standalone) {
				var node;
				this.openCurrent();
				if (this.documentStarted) throw new Error("declaration() must be the first node.");
				node = new XMLDeclaration(this, version, encoding, standalone);
				this.onData(this.writer.declaration(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				return this;
			};
			XMLDocumentCB.prototype.doctype = function(root, pubID, sysID) {
				this.openCurrent();
				if (root == null) throw new Error("Missing root node name.");
				if (this.root) throw new Error("dtd() must come before the root node.");
				this.currentNode = new XMLDocType(this, pubID, sysID);
				this.currentNode.rootNodeName = root;
				this.currentNode.children = false;
				this.currentLevel++;
				this.openTags[this.currentLevel] = this.currentNode;
				return this;
			};
			XMLDocumentCB.prototype.dtdElement = function(name, value) {
				var node;
				this.openCurrent();
				node = new XMLDTDElement(this, name, value);
				this.onData(this.writer.dtdElement(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				return this;
			};
			XMLDocumentCB.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
				var node;
				this.openCurrent();
				node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
				this.onData(this.writer.dtdAttList(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				return this;
			};
			XMLDocumentCB.prototype.entity = function(name, value) {
				var node;
				this.openCurrent();
				node = new XMLDTDEntity(this, false, name, value);
				this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				return this;
			};
			XMLDocumentCB.prototype.pEntity = function(name, value) {
				var node;
				this.openCurrent();
				node = new XMLDTDEntity(this, true, name, value);
				this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				return this;
			};
			XMLDocumentCB.prototype.notation = function(name, value) {
				var node;
				this.openCurrent();
				node = new XMLDTDNotation(this, name, value);
				this.onData(this.writer.dtdNotation(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
				return this;
			};
			XMLDocumentCB.prototype.up = function() {
				if (this.currentLevel < 0) throw new Error("The document node has no parent.");
				if (this.currentNode) {
					if (this.currentNode.children) this.closeNode(this.currentNode);
					else this.openNode(this.currentNode);
					this.currentNode = null;
				} else this.closeNode(this.openTags[this.currentLevel]);
				delete this.openTags[this.currentLevel];
				this.currentLevel--;
				return this;
			};
			XMLDocumentCB.prototype.end = function() {
				while (this.currentLevel >= 0) this.up();
				return this.onEnd();
			};
			XMLDocumentCB.prototype.openCurrent = function() {
				if (this.currentNode) {
					this.currentNode.children = true;
					return this.openNode(this.currentNode);
				}
			};
			XMLDocumentCB.prototype.openNode = function(node) {
				var att, chunk, name, ref1;
				if (!node.isOpen) {
					if (!this.root && this.currentLevel === 0 && node.type === NodeType.Element) this.root = node;
					chunk = "";
					if (node.type === NodeType.Element) {
						this.writerOptions.state = WriterState.OpenTag;
						chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + "<" + node.name;
						ref1 = node.attribs;
						for (name in ref1) {
							if (!hasProp.call(ref1, name)) continue;
							att = ref1[name];
							chunk += this.writer.attribute(att, this.writerOptions, this.currentLevel);
						}
						chunk += (node.children ? ">" : "/>") + this.writer.endline(node, this.writerOptions, this.currentLevel);
						this.writerOptions.state = WriterState.InsideTag;
					} else {
						this.writerOptions.state = WriterState.OpenTag;
						chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + "<!DOCTYPE " + node.rootNodeName;
						if (node.pubID && node.sysID) chunk += " PUBLIC \"" + node.pubID + "\" \"" + node.sysID + "\"";
						else if (node.sysID) chunk += " SYSTEM \"" + node.sysID + "\"";
						if (node.children) {
							chunk += " [";
							this.writerOptions.state = WriterState.InsideTag;
						} else {
							this.writerOptions.state = WriterState.CloseTag;
							chunk += ">";
						}
						chunk += this.writer.endline(node, this.writerOptions, this.currentLevel);
					}
					this.onData(chunk, this.currentLevel);
					return node.isOpen = true;
				}
			};
			XMLDocumentCB.prototype.closeNode = function(node) {
				var chunk;
				if (!node.isClosed) {
					chunk = "";
					this.writerOptions.state = WriterState.CloseTag;
					if (node.type === NodeType.Element) chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + "</" + node.name + ">" + this.writer.endline(node, this.writerOptions, this.currentLevel);
					else chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + "]>" + this.writer.endline(node, this.writerOptions, this.currentLevel);
					this.writerOptions.state = WriterState.None;
					this.onData(chunk, this.currentLevel);
					return node.isClosed = true;
				}
			};
			XMLDocumentCB.prototype.onData = function(chunk, level) {
				this.documentStarted = true;
				return this.onDataCallback(chunk, level + 1);
			};
			XMLDocumentCB.prototype.onEnd = function() {
				this.documentCompleted = true;
				return this.onEndCallback();
			};
			XMLDocumentCB.prototype.debugInfo = function(name) {
				if (name == null) return "";
				else return "node: <" + name + ">";
			};
			XMLDocumentCB.prototype.ele = function() {
				return this.element.apply(this, arguments);
			};
			XMLDocumentCB.prototype.nod = function(name, attributes, text) {
				return this.node(name, attributes, text);
			};
			XMLDocumentCB.prototype.txt = function(value) {
				return this.text(value);
			};
			XMLDocumentCB.prototype.dat = function(value) {
				return this.cdata(value);
			};
			XMLDocumentCB.prototype.com = function(value) {
				return this.comment(value);
			};
			XMLDocumentCB.prototype.ins = function(target, value) {
				return this.instruction(target, value);
			};
			XMLDocumentCB.prototype.dec = function(version, encoding, standalone) {
				return this.declaration(version, encoding, standalone);
			};
			XMLDocumentCB.prototype.dtd = function(root, pubID, sysID) {
				return this.doctype(root, pubID, sysID);
			};
			XMLDocumentCB.prototype.e = function(name, attributes, text) {
				return this.element(name, attributes, text);
			};
			XMLDocumentCB.prototype.n = function(name, attributes, text) {
				return this.node(name, attributes, text);
			};
			XMLDocumentCB.prototype.t = function(value) {
				return this.text(value);
			};
			XMLDocumentCB.prototype.d = function(value) {
				return this.cdata(value);
			};
			XMLDocumentCB.prototype.c = function(value) {
				return this.comment(value);
			};
			XMLDocumentCB.prototype.r = function(value) {
				return this.raw(value);
			};
			XMLDocumentCB.prototype.i = function(target, value) {
				return this.instruction(target, value);
			};
			XMLDocumentCB.prototype.att = function() {
				if (this.currentNode && this.currentNode.type === NodeType.DocType) return this.attList.apply(this, arguments);
				else return this.attribute.apply(this, arguments);
			};
			XMLDocumentCB.prototype.a = function() {
				if (this.currentNode && this.currentNode.type === NodeType.DocType) return this.attList.apply(this, arguments);
				else return this.attribute.apply(this, arguments);
			};
			XMLDocumentCB.prototype.ent = function(name, value) {
				return this.entity(name, value);
			};
			XMLDocumentCB.prototype.pent = function(name, value) {
				return this.pEntity(name, value);
			};
			XMLDocumentCB.prototype.not = function(name, value) {
				return this.notation(name, value);
			};
			return XMLDocumentCB;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/XMLStreamWriter.js
var require_XMLStreamWriter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, WriterState, XMLWriterBase, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		NodeType = require_NodeType();
		XMLWriterBase = require_XMLWriterBase();
		WriterState = require_WriterState();
		module.exports = (function(superClass) {
			extend(XMLStreamWriter, superClass);
			function XMLStreamWriter(stream, options) {
				this.stream = stream;
				XMLStreamWriter.__super__.constructor.call(this, options);
			}
			XMLStreamWriter.prototype.endline = function(node, options, level) {
				if (node.isLastRootNode && options.state === WriterState.CloseTag) return "";
				else return XMLStreamWriter.__super__.endline.call(this, node, options, level);
			};
			XMLStreamWriter.prototype.document = function(doc, options) {
				var child, i, j, k, len, len1, ref = doc.children, ref1, results;
				for (i = j = 0, len = ref.length; j < len; i = ++j) {
					child = ref[i];
					child.isLastRootNode = i === doc.children.length - 1;
				}
				options = this.filterOptions(options);
				ref1 = doc.children;
				results = [];
				for (k = 0, len1 = ref1.length; k < len1; k++) {
					child = ref1[k];
					results.push(this.writeChildNode(child, options, 0));
				}
				return results;
			};
			XMLStreamWriter.prototype.attribute = function(att, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.attribute.call(this, att, options, level));
			};
			XMLStreamWriter.prototype.cdata = function(node, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.cdata.call(this, node, options, level));
			};
			XMLStreamWriter.prototype.comment = function(node, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.comment.call(this, node, options, level));
			};
			XMLStreamWriter.prototype.declaration = function(node, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.declaration.call(this, node, options, level));
			};
			XMLStreamWriter.prototype.docType = function(node, options, level) {
				var child, j, len, ref;
				level || (level = 0);
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				this.stream.write(this.indent(node, options, level));
				this.stream.write("<!DOCTYPE " + node.root().name);
				if (node.pubID && node.sysID) this.stream.write(" PUBLIC \"" + node.pubID + "\" \"" + node.sysID + "\"");
				else if (node.sysID) this.stream.write(" SYSTEM \"" + node.sysID + "\"");
				if (node.children.length > 0) {
					this.stream.write(" [");
					this.stream.write(this.endline(node, options, level));
					options.state = WriterState.InsideTag;
					ref = node.children;
					for (j = 0, len = ref.length; j < len; j++) {
						child = ref[j];
						this.writeChildNode(child, options, level + 1);
					}
					options.state = WriterState.CloseTag;
					this.stream.write("]");
				}
				options.state = WriterState.CloseTag;
				this.stream.write(options.spaceBeforeSlash + ">");
				this.stream.write(this.endline(node, options, level));
				options.state = WriterState.None;
				return this.closeNode(node, options, level);
			};
			XMLStreamWriter.prototype.element = function(node, options, level) {
				var att, child, childNodeCount, firstChildNode, j, len, name, ref, ref1;
				level || (level = 0);
				this.openNode(node, options, level);
				options.state = WriterState.OpenTag;
				this.stream.write(this.indent(node, options, level) + "<" + node.name);
				ref = node.attribs;
				for (name in ref) {
					if (!hasProp.call(ref, name)) continue;
					att = ref[name];
					this.attribute(att, options, level);
				}
				childNodeCount = node.children.length;
				firstChildNode = childNodeCount === 0 ? null : node.children[0];
				if (childNodeCount === 0 || node.children.every(function(e) {
					return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === "";
				})) if (options.allowEmpty) {
					this.stream.write(">");
					options.state = WriterState.CloseTag;
					this.stream.write("</" + node.name + ">");
				} else {
					options.state = WriterState.CloseTag;
					this.stream.write(options.spaceBeforeSlash + "/>");
				}
				else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && firstChildNode.value != null) {
					this.stream.write(">");
					options.state = WriterState.InsideTag;
					options.suppressPrettyCount++;
					this.writeChildNode(firstChildNode, options, level + 1);
					options.suppressPrettyCount--;
					options.state = WriterState.CloseTag;
					this.stream.write("</" + node.name + ">");
				} else {
					this.stream.write(">" + this.endline(node, options, level));
					options.state = WriterState.InsideTag;
					ref1 = node.children;
					for (j = 0, len = ref1.length; j < len; j++) {
						child = ref1[j];
						this.writeChildNode(child, options, level + 1);
					}
					options.state = WriterState.CloseTag;
					this.stream.write(this.indent(node, options, level) + "</" + node.name + ">");
				}
				this.stream.write(this.endline(node, options, level));
				options.state = WriterState.None;
				return this.closeNode(node, options, level);
			};
			XMLStreamWriter.prototype.processingInstruction = function(node, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.processingInstruction.call(this, node, options, level));
			};
			XMLStreamWriter.prototype.raw = function(node, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.raw.call(this, node, options, level));
			};
			XMLStreamWriter.prototype.text = function(node, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.text.call(this, node, options, level));
			};
			XMLStreamWriter.prototype.dtdAttList = function(node, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.dtdAttList.call(this, node, options, level));
			};
			XMLStreamWriter.prototype.dtdElement = function(node, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.dtdElement.call(this, node, options, level));
			};
			XMLStreamWriter.prototype.dtdEntity = function(node, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.dtdEntity.call(this, node, options, level));
			};
			XMLStreamWriter.prototype.dtdNotation = function(node, options, level) {
				return this.stream.write(XMLStreamWriter.__super__.dtdNotation.call(this, node, options, level));
			};
			return XMLStreamWriter;
		})(XMLWriterBase);
	}).call(exports);
}));
//#endregion
//#region node_modules/xmlbuilder/lib/index.js
var require_lib$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		var NodeType, WriterState, XMLDOMImplementation, XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref = require_Utility();
		assign = ref.assign, isFunction = ref.isFunction;
		XMLDOMImplementation = require_XMLDOMImplementation();
		XMLDocument = require_XMLDocument();
		XMLDocumentCB = require_XMLDocumentCB();
		XMLStringWriter = require_XMLStringWriter();
		XMLStreamWriter = require_XMLStreamWriter();
		NodeType = require_NodeType();
		WriterState = require_WriterState();
		module.exports.create = function(name, xmldec, doctype, options) {
			var doc, root;
			if (name == null) throw new Error("Root element needs a name.");
			options = assign({}, xmldec, doctype, options);
			doc = new XMLDocument(options);
			root = doc.element(name);
			if (!options.headless) {
				doc.declaration(options);
				if (options.pubID != null || options.sysID != null) doc.dtd(options);
			}
			return root;
		};
		module.exports.begin = function(options, onData, onEnd) {
			var ref1;
			if (isFunction(options)) {
				ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1];
				options = {};
			}
			if (onData) return new XMLDocumentCB(options, onData, onEnd);
			else return new XMLDocument(options);
		};
		module.exports.stringWriter = function(options) {
			return new XMLStringWriter(options);
		};
		module.exports.streamWriter = function(stream, options) {
			return new XMLStreamWriter(stream, options);
		};
		module.exports.implementation = new XMLDOMImplementation();
		module.exports.nodeType = NodeType;
		module.exports.writerState = WriterState;
	}).call(exports);
}));
//#endregion
//#region node_modules/xml2js/lib/builder.js
var require_builder = /* @__PURE__ */ __commonJSMin(((exports) => {
	(function() {
		"use strict";
		var builder, defaults, escapeCDATA, requiresCDATA, wrapCDATA, hasProp = {}.hasOwnProperty;
		builder = require_lib$1();
		defaults = require_defaults().defaults;
		requiresCDATA = function(entry) {
			return typeof entry === "string" && (entry.indexOf("&") >= 0 || entry.indexOf(">") >= 0 || entry.indexOf("<") >= 0);
		};
		wrapCDATA = function(entry) {
			return "<![CDATA[" + escapeCDATA(entry) + "]]>";
		};
		escapeCDATA = function(entry) {
			return entry.replace("]]>", "]]]]><![CDATA[>");
		};
		exports.Builder = (function() {
			function Builder(opts) {
				var key, ref, value;
				this.options = {};
				ref = defaults["0.2"];
				for (key in ref) {
					if (!hasProp.call(ref, key)) continue;
					value = ref[key];
					this.options[key] = value;
				}
				for (key in opts) {
					if (!hasProp.call(opts, key)) continue;
					value = opts[key];
					this.options[key] = value;
				}
			}
			Builder.prototype.buildObject = function(rootObj) {
				var attrkey = this.options.attrkey, charkey = this.options.charkey, render, rootElement, rootName;
				if (Object.keys(rootObj).length === 1 && this.options.rootName === defaults["0.2"].rootName) {
					rootName = Object.keys(rootObj)[0];
					rootObj = rootObj[rootName];
				} else rootName = this.options.rootName;
				render = (function(_this) {
					return function(element, obj) {
						var attr, child, entry, index, key, value;
						if (typeof obj !== "object") if (_this.options.cdata && requiresCDATA(obj)) element.raw(wrapCDATA(obj));
						else element.txt(obj);
						else if (Array.isArray(obj)) for (index in obj) {
							if (!hasProp.call(obj, index)) continue;
							child = obj[index];
							for (key in child) {
								entry = child[key];
								element = render(element.ele(key), entry).up();
							}
						}
						else for (key in obj) {
							if (!hasProp.call(obj, key)) continue;
							child = obj[key];
							if (key === attrkey) {
								if (typeof child === "object") for (attr in child) {
									value = child[attr];
									element = element.att(attr, value);
								}
							} else if (key === charkey) if (_this.options.cdata && requiresCDATA(child)) element = element.raw(wrapCDATA(child));
							else element = element.txt(child);
							else if (Array.isArray(child)) for (index in child) {
								if (!hasProp.call(child, index)) continue;
								entry = child[index];
								if (typeof entry === "string") if (_this.options.cdata && requiresCDATA(entry)) element = element.ele(key).raw(wrapCDATA(entry)).up();
								else element = element.ele(key, entry).up();
								else element = render(element.ele(key), entry).up();
							}
							else if (typeof child === "object") element = render(element.ele(key), child).up();
							else if (typeof child === "string" && _this.options.cdata && requiresCDATA(child)) element = element.ele(key).raw(wrapCDATA(child)).up();
							else {
								if (child == null) child = "";
								element = element.ele(key, child.toString()).up();
							}
						}
						return element;
					};
				})(this);
				rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, {
					headless: this.options.headless,
					allowSurrogateChars: this.options.allowSurrogateChars
				});
				return render(rootElement, rootObj).end(this.options.renderOpts);
			};
			return Builder;
		})();
	}).call(exports);
}));
//#endregion
//#region node_modules/sax/lib/sax.js
var require_sax = /* @__PURE__ */ __commonJSMin(((exports) => {
	(function(sax) {
		sax.parser = function(strict, opt) {
			return new SAXParser(strict, opt);
		};
		sax.SAXParser = SAXParser;
		sax.SAXStream = SAXStream;
		sax.createStream = createStream;
		sax.MAX_BUFFER_LENGTH = 64 * 1024;
		var buffers = [
			"comment",
			"sgmlDecl",
			"textNode",
			"tagName",
			"doctype",
			"procInstName",
			"procInstBody",
			"entity",
			"attribName",
			"attribValue",
			"cdata",
			"script"
		];
		sax.EVENTS = [
			"text",
			"processinginstruction",
			"sgmldeclaration",
			"doctype",
			"comment",
			"opentagstart",
			"attribute",
			"opentag",
			"closetag",
			"opencdata",
			"cdata",
			"closecdata",
			"error",
			"end",
			"ready",
			"script",
			"opennamespace",
			"closenamespace"
		];
		function SAXParser(strict, opt) {
			if (!(this instanceof SAXParser)) return new SAXParser(strict, opt);
			var parser = this;
			clearBuffers(parser);
			parser.q = parser.c = "";
			parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH;
			parser.encoding = null;
			parser.opt = opt || {};
			parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags;
			parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase";
			parser.opt.maxEntityCount = parser.opt.maxEntityCount || 512;
			parser.opt.maxEntityDepth = parser.opt.maxEntityDepth || 4;
			parser.entityCount = parser.entityDepth = 0;
			parser.tags = [];
			parser.closed = parser.closedRoot = parser.sawRoot = false;
			parser.tag = parser.error = null;
			parser.strict = !!strict;
			parser.noscript = !!(strict || parser.opt.noscript);
			parser.state = S.BEGIN;
			parser.strictEntities = parser.opt.strictEntities;
			parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES);
			parser.attribList = [];
			if (parser.opt.xmlns) parser.ns = Object.create(rootNS);
			if (parser.opt.unquotedAttributeValues === void 0) parser.opt.unquotedAttributeValues = !strict;
			parser.trackPosition = parser.opt.position !== false;
			if (parser.trackPosition) parser.position = parser.line = parser.column = 0;
			emit(parser, "onready");
		}
		if (!Object.create) Object.create = function(o) {
			function F() {}
			F.prototype = o;
			return new F();
		};
		if (!Object.keys) Object.keys = function(o) {
			var a = [];
			for (var i in o) if (o.hasOwnProperty(i)) a.push(i);
			return a;
		};
		function checkBufferLength(parser) {
			var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10);
			var maxActual = 0;
			for (var i = 0, l = buffers.length; i < l; i++) {
				var len = parser[buffers[i]].length;
				if (len > maxAllowed) switch (buffers[i]) {
					case "textNode":
						closeText(parser);
						break;
					case "cdata":
						emitNode(parser, "oncdata", parser.cdata);
						parser.cdata = "";
						break;
					case "script":
						emitNode(parser, "onscript", parser.script);
						parser.script = "";
						break;
					default: error(parser, "Max buffer length exceeded: " + buffers[i]);
				}
				maxActual = Math.max(maxActual, len);
			}
			parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH - maxActual + parser.position;
		}
		function clearBuffers(parser) {
			for (var i = 0, l = buffers.length; i < l; i++) parser[buffers[i]] = "";
		}
		function flushBuffers(parser) {
			closeText(parser);
			if (parser.cdata !== "") {
				emitNode(parser, "oncdata", parser.cdata);
				parser.cdata = "";
			}
			if (parser.script !== "") {
				emitNode(parser, "onscript", parser.script);
				parser.script = "";
			}
		}
		SAXParser.prototype = {
			end: function() {
				end(this);
			},
			write,
			resume: function() {
				this.error = null;
				return this;
			},
			close: function() {
				return this.write(null);
			},
			flush: function() {
				flushBuffers(this);
			}
		};
		var Stream;
		try {
			Stream = __require("stream").Stream;
		} catch (ex) {
			Stream = function() {};
		}
		if (!Stream) Stream = function() {};
		var streamWraps = sax.EVENTS.filter(function(ev) {
			return ev !== "error" && ev !== "end";
		});
		function createStream(strict, opt) {
			return new SAXStream(strict, opt);
		}
		function determineBufferEncoding(data, isEnd) {
			if (data.length >= 2) {
				if (data[0] === 255 && data[1] === 254) return "utf-16le";
				if (data[0] === 254 && data[1] === 255) return "utf-16be";
			}
			if (data.length >= 3 && data[0] === 239 && data[1] === 187 && data[2] === 191) return "utf8";
			if (data.length >= 4) {
				if (data[0] === 60 && data[1] === 0 && data[2] === 63 && data[3] === 0) return "utf-16le";
				if (data[0] === 0 && data[1] === 60 && data[2] === 0 && data[3] === 63) return "utf-16be";
				return "utf8";
			}
			return isEnd ? "utf8" : null;
		}
		function SAXStream(strict, opt) {
			if (!(this instanceof SAXStream)) return new SAXStream(strict, opt);
			Stream.apply(this);
			this._parser = new SAXParser(strict, opt);
			this.writable = true;
			this.readable = true;
			var me = this;
			this._parser.onend = function() {
				me.emit("end");
			};
			this._parser.onerror = function(er) {
				me.emit("error", er);
				me._parser.error = null;
			};
			this._decoder = null;
			this._decoderBuffer = null;
			streamWraps.forEach(function(ev) {
				Object.defineProperty(me, "on" + ev, {
					get: function() {
						return me._parser["on" + ev];
					},
					set: function(h) {
						if (!h) {
							me.removeAllListeners(ev);
							me._parser["on" + ev] = h;
							return h;
						}
						me.on(ev, h);
					},
					enumerable: true,
					configurable: false
				});
			});
		}
		SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } });
		SAXStream.prototype._decodeBuffer = function(data, isEnd) {
			if (this._decoderBuffer) {
				data = Buffer.concat([this._decoderBuffer, data]);
				this._decoderBuffer = null;
			}
			if (!this._decoder) {
				var encoding = determineBufferEncoding(data, isEnd);
				if (!encoding) {
					this._decoderBuffer = data;
					return "";
				}
				this._parser.encoding = encoding;
				this._decoder = new TextDecoder(encoding);
			}
			return this._decoder.decode(data, { stream: !isEnd });
		};
		SAXStream.prototype.write = function(data) {
			if (typeof Buffer === "function" && typeof Buffer.isBuffer === "function" && Buffer.isBuffer(data)) data = this._decodeBuffer(data, false);
			else if (this._decoderBuffer) {
				var remaining = this._decodeBuffer(Buffer.alloc(0), true);
				if (remaining) {
					this._parser.write(remaining);
					this.emit("data", remaining);
				}
			}
			this._parser.write(data.toString());
			this.emit("data", data);
			return true;
		};
		SAXStream.prototype.end = function(chunk) {
			if (chunk && chunk.length) this.write(chunk);
			if (this._decoderBuffer) {
				var finalChunk = this._decodeBuffer(Buffer.alloc(0), true);
				if (finalChunk) {
					this._parser.write(finalChunk);
					this.emit("data", finalChunk);
				}
			} else if (this._decoder) {
				var remaining = this._decoder.decode();
				if (remaining) {
					this._parser.write(remaining);
					this.emit("data", remaining);
				}
			}
			this._parser.end();
			return true;
		};
		SAXStream.prototype.on = function(ev, handler) {
			var me = this;
			if (!me._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) me._parser["on" + ev] = function() {
				var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments);
				args.splice(0, 0, ev);
				me.emit.apply(me, args);
			};
			return Stream.prototype.on.call(me, ev, handler);
		};
		var CDATA = "[CDATA[";
		var DOCTYPE = "DOCTYPE";
		var XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace";
		var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
		var rootNS = {
			xml: XML_NAMESPACE,
			xmlns: XMLNS_NAMESPACE
		};
		var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
		var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;
		var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
		var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;
		function isWhitespace(c) {
			return c === " " || c === "\n" || c === "\r" || c === "	";
		}
		function isQuote(c) {
			return c === "\"" || c === "'";
		}
		function isAttribEnd(c) {
			return c === ">" || isWhitespace(c);
		}
		function isMatch(regex, c) {
			return regex.test(c);
		}
		function notMatch(regex, c) {
			return !isMatch(regex, c);
		}
		var S = 0;
		sax.STATE = {
			BEGIN: S++,
			BEGIN_WHITESPACE: S++,
			TEXT: S++,
			TEXT_ENTITY: S++,
			OPEN_WAKA: S++,
			SGML_DECL: S++,
			SGML_DECL_QUOTED: S++,
			DOCTYPE: S++,
			DOCTYPE_QUOTED: S++,
			DOCTYPE_DTD: S++,
			DOCTYPE_DTD_QUOTED: S++,
			COMMENT_STARTING: S++,
			COMMENT: S++,
			COMMENT_ENDING: S++,
			COMMENT_ENDED: S++,
			CDATA: S++,
			CDATA_ENDING: S++,
			CDATA_ENDING_2: S++,
			PROC_INST: S++,
			PROC_INST_BODY: S++,
			PROC_INST_ENDING: S++,
			OPEN_TAG: S++,
			OPEN_TAG_SLASH: S++,
			ATTRIB: S++,
			ATTRIB_NAME: S++,
			ATTRIB_NAME_SAW_WHITE: S++,
			ATTRIB_VALUE: S++,
			ATTRIB_VALUE_QUOTED: S++,
			ATTRIB_VALUE_CLOSED: S++,
			ATTRIB_VALUE_UNQUOTED: S++,
			ATTRIB_VALUE_ENTITY_Q: S++,
			ATTRIB_VALUE_ENTITY_U: S++,
			CLOSE_TAG: S++,
			CLOSE_TAG_SAW_WHITE: S++,
			SCRIPT: S++,
			SCRIPT_ENDING: S++
		};
		sax.XML_ENTITIES = {
			amp: "&",
			gt: ">",
			lt: "<",
			quot: "\"",
			apos: "'"
		};
		sax.ENTITIES = {
			amp: "&",
			gt: ">",
			lt: "<",
			quot: "\"",
			apos: "'",
			AElig: 198,
			Aacute: 193,
			Acirc: 194,
			Agrave: 192,
			Aring: 197,
			Atilde: 195,
			Auml: 196,
			Ccedil: 199,
			ETH: 208,
			Eacute: 201,
			Ecirc: 202,
			Egrave: 200,
			Euml: 203,
			Iacute: 205,
			Icirc: 206,
			Igrave: 204,
			Iuml: 207,
			Ntilde: 209,
			Oacute: 211,
			Ocirc: 212,
			Ograve: 210,
			Oslash: 216,
			Otilde: 213,
			Ouml: 214,
			THORN: 222,
			Uacute: 218,
			Ucirc: 219,
			Ugrave: 217,
			Uuml: 220,
			Yacute: 221,
			aacute: 225,
			acirc: 226,
			aelig: 230,
			agrave: 224,
			aring: 229,
			atilde: 227,
			auml: 228,
			ccedil: 231,
			eacute: 233,
			ecirc: 234,
			egrave: 232,
			eth: 240,
			euml: 235,
			iacute: 237,
			icirc: 238,
			igrave: 236,
			iuml: 239,
			ntilde: 241,
			oacute: 243,
			ocirc: 244,
			ograve: 242,
			oslash: 248,
			otilde: 245,
			ouml: 246,
			szlig: 223,
			thorn: 254,
			uacute: 250,
			ucirc: 251,
			ugrave: 249,
			uuml: 252,
			yacute: 253,
			yuml: 255,
			copy: 169,
			reg: 174,
			nbsp: 160,
			iexcl: 161,
			cent: 162,
			pound: 163,
			curren: 164,
			yen: 165,
			brvbar: 166,
			sect: 167,
			uml: 168,
			ordf: 170,
			laquo: 171,
			not: 172,
			shy: 173,
			macr: 175,
			deg: 176,
			plusmn: 177,
			sup1: 185,
			sup2: 178,
			sup3: 179,
			acute: 180,
			micro: 181,
			para: 182,
			middot: 183,
			cedil: 184,
			ordm: 186,
			raquo: 187,
			frac14: 188,
			frac12: 189,
			frac34: 190,
			iquest: 191,
			times: 215,
			divide: 247,
			OElig: 338,
			oelig: 339,
			Scaron: 352,
			scaron: 353,
			Yuml: 376,
			fnof: 402,
			circ: 710,
			tilde: 732,
			Alpha: 913,
			Beta: 914,
			Gamma: 915,
			Delta: 916,
			Epsilon: 917,
			Zeta: 918,
			Eta: 919,
			Theta: 920,
			Iota: 921,
			Kappa: 922,
			Lambda: 923,
			Mu: 924,
			Nu: 925,
			Xi: 926,
			Omicron: 927,
			Pi: 928,
			Rho: 929,
			Sigma: 931,
			Tau: 932,
			Upsilon: 933,
			Phi: 934,
			Chi: 935,
			Psi: 936,
			Omega: 937,
			alpha: 945,
			beta: 946,
			gamma: 947,
			delta: 948,
			epsilon: 949,
			zeta: 950,
			eta: 951,
			theta: 952,
			iota: 953,
			kappa: 954,
			lambda: 955,
			mu: 956,
			nu: 957,
			xi: 958,
			omicron: 959,
			pi: 960,
			rho: 961,
			sigmaf: 962,
			sigma: 963,
			tau: 964,
			upsilon: 965,
			phi: 966,
			chi: 967,
			psi: 968,
			omega: 969,
			thetasym: 977,
			upsih: 978,
			piv: 982,
			ensp: 8194,
			emsp: 8195,
			thinsp: 8201,
			zwnj: 8204,
			zwj: 8205,
			lrm: 8206,
			rlm: 8207,
			ndash: 8211,
			mdash: 8212,
			lsquo: 8216,
			rsquo: 8217,
			sbquo: 8218,
			ldquo: 8220,
			rdquo: 8221,
			bdquo: 8222,
			dagger: 8224,
			Dagger: 8225,
			bull: 8226,
			hellip: 8230,
			permil: 8240,
			prime: 8242,
			Prime: 8243,
			lsaquo: 8249,
			rsaquo: 8250,
			oline: 8254,
			frasl: 8260,
			euro: 8364,
			image: 8465,
			weierp: 8472,
			real: 8476,
			trade: 8482,
			alefsym: 8501,
			larr: 8592,
			uarr: 8593,
			rarr: 8594,
			darr: 8595,
			harr: 8596,
			crarr: 8629,
			lArr: 8656,
			uArr: 8657,
			rArr: 8658,
			dArr: 8659,
			hArr: 8660,
			forall: 8704,
			part: 8706,
			exist: 8707,
			empty: 8709,
			nabla: 8711,
			isin: 8712,
			notin: 8713,
			ni: 8715,
			prod: 8719,
			sum: 8721,
			minus: 8722,
			lowast: 8727,
			radic: 8730,
			prop: 8733,
			infin: 8734,
			ang: 8736,
			and: 8743,
			or: 8744,
			cap: 8745,
			cup: 8746,
			int: 8747,
			there4: 8756,
			sim: 8764,
			cong: 8773,
			asymp: 8776,
			ne: 8800,
			equiv: 8801,
			le: 8804,
			ge: 8805,
			sub: 8834,
			sup: 8835,
			nsub: 8836,
			sube: 8838,
			supe: 8839,
			oplus: 8853,
			otimes: 8855,
			perp: 8869,
			sdot: 8901,
			lceil: 8968,
			rceil: 8969,
			lfloor: 8970,
			rfloor: 8971,
			lang: 9001,
			rang: 9002,
			loz: 9674,
			spades: 9824,
			clubs: 9827,
			hearts: 9829,
			diams: 9830
		};
		Object.keys(sax.ENTITIES).forEach(function(key) {
			var e = sax.ENTITIES[key];
			var s = typeof e === "number" ? String.fromCharCode(e) : e;
			sax.ENTITIES[key] = s;
		});
		for (var s in sax.STATE) sax.STATE[sax.STATE[s]] = s;
		S = sax.STATE;
		function emit(parser, event, data) {
			parser[event] && parser[event](data);
		}
		function getDeclaredEncoding(body) {
			var match = body && body.match(/(?:^|\s)encoding\s*=\s*(['"])([^'"]+)\1/i);
			return match ? match[2] : null;
		}
		function normalizeEncodingName(encoding) {
			if (!encoding) return null;
			return encoding.toLowerCase().replace(/[^a-z0-9]/g, "");
		}
		function encodingsMatch(detectedEncoding, declaredEncoding) {
			const detected = normalizeEncodingName(detectedEncoding);
			const declared = normalizeEncodingName(declaredEncoding);
			if (!detected || !declared) return true;
			if (declared === "utf16") return detected === "utf16le" || detected === "utf16be";
			return detected === declared;
		}
		function validateXmlDeclarationEncoding(parser, data) {
			if (!parser.strict || !parser.encoding || !data || data.name !== "xml") return;
			var declaredEncoding = getDeclaredEncoding(data.body);
			if (declaredEncoding && !encodingsMatch(parser.encoding, declaredEncoding)) strictFail(parser, "XML declaration encoding " + declaredEncoding + " does not match detected stream encoding " + parser.encoding.toUpperCase());
		}
		function emitNode(parser, nodeType, data) {
			if (parser.textNode) closeText(parser);
			emit(parser, nodeType, data);
		}
		function closeText(parser) {
			parser.textNode = textopts(parser.opt, parser.textNode);
			if (parser.textNode) emit(parser, "ontext", parser.textNode);
			parser.textNode = "";
		}
		function textopts(opt, text) {
			if (opt.trim) text = text.trim();
			if (opt.normalize) text = text.replace(/\s+/g, " ");
			return text;
		}
		function error(parser, er) {
			closeText(parser);
			if (parser.trackPosition) er += "\nLine: " + parser.line + "\nColumn: " + parser.column + "\nChar: " + parser.c;
			er = new Error(er);
			parser.error = er;
			emit(parser, "onerror", er);
			return parser;
		}
		function end(parser) {
			if (parser.sawRoot && !parser.closedRoot) strictFail(parser, "Unclosed root tag");
			if (parser.state !== S.BEGIN && parser.state !== S.BEGIN_WHITESPACE && parser.state !== S.TEXT) error(parser, "Unexpected end");
			closeText(parser);
			parser.c = "";
			parser.closed = true;
			emit(parser, "onend");
			SAXParser.call(parser, parser.strict, parser.opt);
			return parser;
		}
		function strictFail(parser, message) {
			if (typeof parser !== "object" || !(parser instanceof SAXParser)) throw new Error("bad call to strictFail");
			if (parser.strict) error(parser, message);
		}
		function newTag(parser) {
			if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase]();
			var parent = parser.tags[parser.tags.length - 1] || parser;
			var tag = parser.tag = {
				name: parser.tagName,
				attributes: {}
			};
			if (parser.opt.xmlns) tag.ns = parent.ns;
			parser.attribList.length = 0;
			emitNode(parser, "onopentagstart", tag);
		}
		function qname(name, attribute) {
			var qualName = name.indexOf(":") < 0 ? ["", name] : name.split(":");
			var prefix = qualName[0];
			var local = qualName[1];
			if (attribute && name === "xmlns") {
				prefix = "xmlns";
				local = "";
			}
			return {
				prefix,
				local
			};
		}
		function attrib(parser) {
			if (!parser.strict) parser.attribName = parser.attribName[parser.looseCase]();
			if (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) {
				parser.attribName = parser.attribValue = "";
				return;
			}
			if (parser.opt.xmlns) {
				var qn = qname(parser.attribName, true);
				var prefix = qn.prefix;
				var local = qn.local;
				if (prefix === "xmlns") if (local === "xml" && parser.attribValue !== XML_NAMESPACE) strictFail(parser, "xml: prefix must be bound to " + XML_NAMESPACE + "\nActual: " + parser.attribValue);
				else if (local === "xmlns" && parser.attribValue !== XMLNS_NAMESPACE) strictFail(parser, "xmlns: prefix must be bound to " + XMLNS_NAMESPACE + "\nActual: " + parser.attribValue);
				else {
					var tag = parser.tag;
					var parent = parser.tags[parser.tags.length - 1] || parser;
					if (tag.ns === parent.ns) tag.ns = Object.create(parent.ns);
					tag.ns[local] = parser.attribValue;
				}
				parser.attribList.push([parser.attribName, parser.attribValue]);
			} else {
				parser.tag.attributes[parser.attribName] = parser.attribValue;
				emitNode(parser, "onattribute", {
					name: parser.attribName,
					value: parser.attribValue
				});
			}
			parser.attribName = parser.attribValue = "";
		}
		function openTag(parser, selfClosing) {
			if (parser.opt.xmlns) {
				var tag = parser.tag;
				var qn = qname(parser.tagName);
				tag.prefix = qn.prefix;
				tag.local = qn.local;
				tag.uri = tag.ns[qn.prefix] || "";
				if (tag.prefix && !tag.uri) {
					strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(parser.tagName));
					tag.uri = qn.prefix;
				}
				var parent = parser.tags[parser.tags.length - 1] || parser;
				if (tag.ns && parent.ns !== tag.ns) Object.keys(tag.ns).forEach(function(p) {
					emitNode(parser, "onopennamespace", {
						prefix: p,
						uri: tag.ns[p]
					});
				});
				for (var i = 0, l = parser.attribList.length; i < l; i++) {
					var nv = parser.attribList[i];
					var name = nv[0];
					var value = nv[1];
					var qualName = qname(name, true);
					var prefix = qualName.prefix;
					var local = qualName.local;
					var uri = prefix === "" ? "" : tag.ns[prefix] || "";
					var a = {
						name,
						value,
						prefix,
						local,
						uri
					};
					if (prefix && prefix !== "xmlns" && !uri) {
						strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(prefix));
						a.uri = prefix;
					}
					parser.tag.attributes[name] = a;
					emitNode(parser, "onattribute", a);
				}
				parser.attribList.length = 0;
			}
			parser.tag.isSelfClosing = !!selfClosing;
			parser.sawRoot = true;
			parser.tags.push(parser.tag);
			emitNode(parser, "onopentag", parser.tag);
			if (!selfClosing) {
				if (!parser.noscript && parser.tagName.toLowerCase() === "script") parser.state = S.SCRIPT;
				else parser.state = S.TEXT;
				parser.tag = null;
				parser.tagName = "";
			}
			parser.attribName = parser.attribValue = "";
			parser.attribList.length = 0;
		}
		function closeTag(parser) {
			if (!parser.tagName) {
				strictFail(parser, "Weird empty close tag.");
				parser.textNode += "</>";
				parser.state = S.TEXT;
				return;
			}
			if (parser.script) {
				if (parser.tagName !== "script") {
					parser.script += "</" + parser.tagName + ">";
					parser.tagName = "";
					parser.state = S.SCRIPT;
					return;
				}
				emitNode(parser, "onscript", parser.script);
				parser.script = "";
			}
			var t = parser.tags.length;
			var tagName = parser.tagName;
			if (!parser.strict) tagName = tagName[parser.looseCase]();
			var closeTo = tagName;
			while (t--) if (parser.tags[t].name !== closeTo) strictFail(parser, "Unexpected close tag");
			else break;
			if (t < 0) {
				strictFail(parser, "Unmatched closing tag: " + parser.tagName);
				parser.textNode += "</" + parser.tagName + ">";
				parser.state = S.TEXT;
				return;
			}
			parser.tagName = tagName;
			var s = parser.tags.length;
			while (s-- > t) {
				var tag = parser.tag = parser.tags.pop();
				parser.tagName = parser.tag.name;
				emitNode(parser, "onclosetag", parser.tagName);
				var x = {};
				for (var i in tag.ns) x[i] = tag.ns[i];
				var parent = parser.tags[parser.tags.length - 1] || parser;
				if (parser.opt.xmlns && tag.ns !== parent.ns) Object.keys(tag.ns).forEach(function(p) {
					var n = tag.ns[p];
					emitNode(parser, "onclosenamespace", {
						prefix: p,
						uri: n
					});
				});
			}
			if (t === 0) parser.closedRoot = true;
			parser.tagName = parser.attribValue = parser.attribName = "";
			parser.attribList.length = 0;
			parser.state = S.TEXT;
		}
		function parseEntity(parser) {
			var entity = parser.entity;
			var entityLC = entity.toLowerCase();
			var num;
			var numStr = "";
			if (parser.ENTITIES[entity]) return parser.ENTITIES[entity];
			if (parser.ENTITIES[entityLC]) return parser.ENTITIES[entityLC];
			entity = entityLC;
			if (entity.charAt(0) === "#") if (entity.charAt(1) === "x") {
				entity = entity.slice(2);
				num = parseInt(entity, 16);
				numStr = num.toString(16);
			} else {
				entity = entity.slice(1);
				num = parseInt(entity, 10);
				numStr = num.toString(10);
			}
			entity = entity.replace(/^0+/, "");
			if (isNaN(num) || numStr.toLowerCase() !== entity || num < 0 || num > 1114111) {
				strictFail(parser, "Invalid character entity");
				return "&" + parser.entity + ";";
			}
			return String.fromCodePoint(num);
		}
		function beginWhiteSpace(parser, c) {
			if (c === "<") {
				parser.state = S.OPEN_WAKA;
				parser.startTagPosition = parser.position;
			} else if (!isWhitespace(c)) {
				strictFail(parser, "Non-whitespace before first tag.");
				parser.textNode = c;
				parser.state = S.TEXT;
			}
		}
		function charAt(chunk, i) {
			var result = "";
			if (i < chunk.length) result = chunk.charAt(i);
			return result;
		}
		function write(chunk) {
			var parser = this;
			if (this.error) throw this.error;
			if (parser.closed) return error(parser, "Cannot write after close. Assign an onready handler.");
			if (chunk === null) return end(parser);
			if (typeof chunk === "object") chunk = chunk.toString();
			var i = 0;
			var c = "";
			while (true) {
				c = charAt(chunk, i++);
				parser.c = c;
				if (!c) break;
				if (parser.trackPosition) {
					parser.position++;
					if (c === "\n") {
						parser.line++;
						parser.column = 0;
					} else parser.column++;
				}
				switch (parser.state) {
					case S.BEGIN:
						parser.state = S.BEGIN_WHITESPACE;
						if (c === "") continue;
						beginWhiteSpace(parser, c);
						continue;
					case S.BEGIN_WHITESPACE:
						beginWhiteSpace(parser, c);
						continue;
					case S.TEXT:
						if (parser.sawRoot && !parser.closedRoot) {
							var starti = i - 1;
							while (c && c !== "<" && c !== "&") {
								c = charAt(chunk, i++);
								if (c && parser.trackPosition) {
									parser.position++;
									if (c === "\n") {
										parser.line++;
										parser.column = 0;
									} else parser.column++;
								}
							}
							parser.textNode += chunk.substring(starti, i - 1);
						}
						if (c === "<" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {
							parser.state = S.OPEN_WAKA;
							parser.startTagPosition = parser.position;
						} else {
							if (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) strictFail(parser, "Text data outside of root node.");
							if (c === "&") parser.state = S.TEXT_ENTITY;
							else parser.textNode += c;
						}
						continue;
					case S.SCRIPT:
						if (c === "<") parser.state = S.SCRIPT_ENDING;
						else parser.script += c;
						continue;
					case S.SCRIPT_ENDING:
						if (c === "/") parser.state = S.CLOSE_TAG;
						else {
							parser.script += "<" + c;
							parser.state = S.SCRIPT;
						}
						continue;
					case S.OPEN_WAKA:
						if (c === "!") {
							parser.state = S.SGML_DECL;
							parser.sgmlDecl = "";
						} else if (isWhitespace(c)) {} else if (isMatch(nameStart, c)) {
							parser.state = S.OPEN_TAG;
							parser.tagName = c;
						} else if (c === "/") {
							parser.state = S.CLOSE_TAG;
							parser.tagName = "";
						} else if (c === "?") {
							parser.state = S.PROC_INST;
							parser.procInstName = parser.procInstBody = "";
						} else {
							strictFail(parser, "Unencoded <");
							if (parser.startTagPosition + 1 < parser.position) {
								var pad = parser.position - parser.startTagPosition;
								c = new Array(pad).join(" ") + c;
							}
							parser.textNode += "<" + c;
							parser.state = S.TEXT;
						}
						continue;
					case S.SGML_DECL:
						if (parser.sgmlDecl + c === "--") {
							parser.state = S.COMMENT;
							parser.comment = "";
							parser.sgmlDecl = "";
							continue;
						}
						if (parser.doctype && parser.doctype !== true && parser.sgmlDecl) {
							parser.state = S.DOCTYPE_DTD;
							parser.doctype += "<!" + parser.sgmlDecl + c;
							parser.sgmlDecl = "";
						} else if ((parser.sgmlDecl + c).toUpperCase() === CDATA) {
							emitNode(parser, "onopencdata");
							parser.state = S.CDATA;
							parser.sgmlDecl = "";
							parser.cdata = "";
						} else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {
							parser.state = S.DOCTYPE;
							if (parser.doctype || parser.sawRoot) strictFail(parser, "Inappropriately located doctype declaration");
							parser.doctype = "";
							parser.sgmlDecl = "";
						} else if (c === ">") {
							emitNode(parser, "onsgmldeclaration", parser.sgmlDecl);
							parser.sgmlDecl = "";
							parser.state = S.TEXT;
						} else if (isQuote(c)) {
							parser.state = S.SGML_DECL_QUOTED;
							parser.sgmlDecl += c;
						} else parser.sgmlDecl += c;
						continue;
					case S.SGML_DECL_QUOTED:
						if (c === parser.q) {
							parser.state = S.SGML_DECL;
							parser.q = "";
						}
						parser.sgmlDecl += c;
						continue;
					case S.DOCTYPE:
						if (c === ">") {
							parser.state = S.TEXT;
							emitNode(parser, "ondoctype", parser.doctype);
							parser.doctype = true;
						} else {
							parser.doctype += c;
							if (c === "[") parser.state = S.DOCTYPE_DTD;
							else if (isQuote(c)) {
								parser.state = S.DOCTYPE_QUOTED;
								parser.q = c;
							}
						}
						continue;
					case S.DOCTYPE_QUOTED:
						parser.doctype += c;
						if (c === parser.q) {
							parser.q = "";
							parser.state = S.DOCTYPE;
						}
						continue;
					case S.DOCTYPE_DTD:
						if (c === "]") {
							parser.doctype += c;
							parser.state = S.DOCTYPE;
						} else if (c === "<") {
							parser.state = S.OPEN_WAKA;
							parser.startTagPosition = parser.position;
						} else if (isQuote(c)) {
							parser.doctype += c;
							parser.state = S.DOCTYPE_DTD_QUOTED;
							parser.q = c;
						} else parser.doctype += c;
						continue;
					case S.DOCTYPE_DTD_QUOTED:
						parser.doctype += c;
						if (c === parser.q) {
							parser.state = S.DOCTYPE_DTD;
							parser.q = "";
						}
						continue;
					case S.COMMENT:
						if (c === "-") parser.state = S.COMMENT_ENDING;
						else parser.comment += c;
						continue;
					case S.COMMENT_ENDING:
						if (c === "-") {
							parser.state = S.COMMENT_ENDED;
							parser.comment = textopts(parser.opt, parser.comment);
							if (parser.comment) emitNode(parser, "oncomment", parser.comment);
							parser.comment = "";
						} else {
							parser.comment += "-" + c;
							parser.state = S.COMMENT;
						}
						continue;
					case S.COMMENT_ENDED:
						if (c !== ">") {
							strictFail(parser, "Malformed comment");
							parser.comment += "--" + c;
							parser.state = S.COMMENT;
						} else if (parser.doctype && parser.doctype !== true) parser.state = S.DOCTYPE_DTD;
						else parser.state = S.TEXT;
						continue;
					case S.CDATA:
						var starti = i - 1;
						while (c && c !== "]") {
							c = charAt(chunk, i++);
							if (c && parser.trackPosition) {
								parser.position++;
								if (c === "\n") {
									parser.line++;
									parser.column = 0;
								} else parser.column++;
							}
						}
						parser.cdata += chunk.substring(starti, i - 1);
						if (c === "]") parser.state = S.CDATA_ENDING;
						continue;
					case S.CDATA_ENDING:
						if (c === "]") parser.state = S.CDATA_ENDING_2;
						else {
							parser.cdata += "]" + c;
							parser.state = S.CDATA;
						}
						continue;
					case S.CDATA_ENDING_2:
						if (c === ">") {
							if (parser.cdata) emitNode(parser, "oncdata", parser.cdata);
							emitNode(parser, "onclosecdata");
							parser.cdata = "";
							parser.state = S.TEXT;
						} else if (c === "]") parser.cdata += "]";
						else {
							parser.cdata += "]]" + c;
							parser.state = S.CDATA;
						}
						continue;
					case S.PROC_INST:
						if (c === "?") parser.state = S.PROC_INST_ENDING;
						else if (isWhitespace(c)) parser.state = S.PROC_INST_BODY;
						else parser.procInstName += c;
						continue;
					case S.PROC_INST_BODY:
						if (!parser.procInstBody && isWhitespace(c)) continue;
						else if (c === "?") parser.state = S.PROC_INST_ENDING;
						else parser.procInstBody += c;
						continue;
					case S.PROC_INST_ENDING:
						if (c === ">") {
							const procInstEndData = {
								name: parser.procInstName,
								body: parser.procInstBody
							};
							validateXmlDeclarationEncoding(parser, procInstEndData);
							emitNode(parser, "onprocessinginstruction", procInstEndData);
							parser.procInstName = parser.procInstBody = "";
							parser.state = S.TEXT;
						} else {
							parser.procInstBody += "?" + c;
							parser.state = S.PROC_INST_BODY;
						}
						continue;
					case S.OPEN_TAG:
						if (isMatch(nameBody, c)) parser.tagName += c;
						else {
							newTag(parser);
							if (c === ">") openTag(parser);
							else if (c === "/") parser.state = S.OPEN_TAG_SLASH;
							else {
								if (!isWhitespace(c)) strictFail(parser, "Invalid character in tag name");
								parser.state = S.ATTRIB;
							}
						}
						continue;
					case S.OPEN_TAG_SLASH:
						if (c === ">") {
							openTag(parser, true);
							closeTag(parser);
						} else {
							strictFail(parser, "Forward-slash in opening tag not followed by >");
							parser.state = S.ATTRIB;
						}
						continue;
					case S.ATTRIB:
						if (isWhitespace(c)) continue;
						else if (c === ">") openTag(parser);
						else if (c === "/") parser.state = S.OPEN_TAG_SLASH;
						else if (isMatch(nameStart, c)) {
							parser.attribName = c;
							parser.attribValue = "";
							parser.state = S.ATTRIB_NAME;
						} else strictFail(parser, "Invalid attribute name");
						continue;
					case S.ATTRIB_NAME:
						if (c === "=") parser.state = S.ATTRIB_VALUE;
						else if (c === ">") {
							strictFail(parser, "Attribute without value");
							parser.attribValue = parser.attribName;
							attrib(parser);
							openTag(parser);
						} else if (isWhitespace(c)) parser.state = S.ATTRIB_NAME_SAW_WHITE;
						else if (isMatch(nameBody, c)) parser.attribName += c;
						else strictFail(parser, "Invalid attribute name");
						continue;
					case S.ATTRIB_NAME_SAW_WHITE:
						if (c === "=") parser.state = S.ATTRIB_VALUE;
						else if (isWhitespace(c)) continue;
						else {
							strictFail(parser, "Attribute without value");
							parser.tag.attributes[parser.attribName] = "";
							parser.attribValue = "";
							emitNode(parser, "onattribute", {
								name: parser.attribName,
								value: ""
							});
							parser.attribName = "";
							if (c === ">") openTag(parser);
							else if (isMatch(nameStart, c)) {
								parser.attribName = c;
								parser.state = S.ATTRIB_NAME;
							} else {
								strictFail(parser, "Invalid attribute name");
								parser.state = S.ATTRIB;
							}
						}
						continue;
					case S.ATTRIB_VALUE:
						if (isWhitespace(c)) continue;
						else if (isQuote(c)) {
							parser.q = c;
							parser.state = S.ATTRIB_VALUE_QUOTED;
						} else {
							if (!parser.opt.unquotedAttributeValues) error(parser, "Unquoted attribute value");
							parser.state = S.ATTRIB_VALUE_UNQUOTED;
							parser.attribValue = c;
						}
						continue;
					case S.ATTRIB_VALUE_QUOTED:
						if (c !== parser.q) {
							if (c === "&") parser.state = S.ATTRIB_VALUE_ENTITY_Q;
							else parser.attribValue += c;
							continue;
						}
						attrib(parser);
						parser.q = "";
						parser.state = S.ATTRIB_VALUE_CLOSED;
						continue;
					case S.ATTRIB_VALUE_CLOSED:
						if (isWhitespace(c)) parser.state = S.ATTRIB;
						else if (c === ">") openTag(parser);
						else if (c === "/") parser.state = S.OPEN_TAG_SLASH;
						else if (isMatch(nameStart, c)) {
							strictFail(parser, "No whitespace between attributes");
							parser.attribName = c;
							parser.attribValue = "";
							parser.state = S.ATTRIB_NAME;
						} else strictFail(parser, "Invalid attribute name");
						continue;
					case S.ATTRIB_VALUE_UNQUOTED:
						if (!isAttribEnd(c)) {
							if (c === "&") parser.state = S.ATTRIB_VALUE_ENTITY_U;
							else parser.attribValue += c;
							continue;
						}
						attrib(parser);
						if (c === ">") openTag(parser);
						else parser.state = S.ATTRIB;
						continue;
					case S.CLOSE_TAG:
						if (!parser.tagName) if (isWhitespace(c)) continue;
						else if (notMatch(nameStart, c)) if (parser.script) {
							parser.script += "</" + c;
							parser.state = S.SCRIPT;
						} else strictFail(parser, "Invalid tagname in closing tag.");
						else parser.tagName = c;
						else if (c === ">") closeTag(parser);
						else if (isMatch(nameBody, c)) parser.tagName += c;
						else if (parser.script) {
							parser.script += "</" + parser.tagName + c;
							parser.tagName = "";
							parser.state = S.SCRIPT;
						} else {
							if (!isWhitespace(c)) strictFail(parser, "Invalid tagname in closing tag");
							parser.state = S.CLOSE_TAG_SAW_WHITE;
						}
						continue;
					case S.CLOSE_TAG_SAW_WHITE:
						if (isWhitespace(c)) continue;
						if (c === ">") closeTag(parser);
						else strictFail(parser, "Invalid characters in closing tag");
						continue;
					case S.TEXT_ENTITY:
					case S.ATTRIB_VALUE_ENTITY_Q:
					case S.ATTRIB_VALUE_ENTITY_U:
						var returnState;
						var buffer;
						switch (parser.state) {
							case S.TEXT_ENTITY:
								returnState = S.TEXT;
								buffer = "textNode";
								break;
							case S.ATTRIB_VALUE_ENTITY_Q:
								returnState = S.ATTRIB_VALUE_QUOTED;
								buffer = "attribValue";
								break;
							case S.ATTRIB_VALUE_ENTITY_U:
								returnState = S.ATTRIB_VALUE_UNQUOTED;
								buffer = "attribValue";
								break;
						}
						if (c === ";") {
							var parsedEntity = parseEntity(parser);
							if (parser.opt.unparsedEntities && !Object.values(sax.XML_ENTITIES).includes(parsedEntity)) {
								if ((parser.entityCount += 1) > parser.opt.maxEntityCount) error(parser, "Parsed entity count exceeds max entity count");
								if ((parser.entityDepth += 1) > parser.opt.maxEntityDepth) error(parser, "Parsed entity depth exceeds max entity depth");
								parser.entity = "";
								parser.state = returnState;
								parser.write(parsedEntity);
								parser.entityDepth -= 1;
							} else {
								parser[buffer] += parsedEntity;
								parser.entity = "";
								parser.state = returnState;
							}
						} else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) parser.entity += c;
						else {
							strictFail(parser, "Invalid character in entity name");
							parser[buffer] += "&" + parser.entity + c;
							parser.entity = "";
							parser.state = returnState;
						}
						continue;
					default: throw new Error(parser, "Unknown state: " + parser.state);
				}
			}
			if (parser.position >= parser.bufferCheckPosition) checkBufferLength(parser);
			return parser;
		}
		/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */
		/* istanbul ignore next */
		if (!String.fromCodePoint) (function() {
			var stringFromCharCode = String.fromCharCode;
			var floor = Math.floor;
			var fromCodePoint = function() {
				var MAX_SIZE = 16384;
				var codeUnits = [];
				var highSurrogate;
				var lowSurrogate;
				var index = -1;
				var length = arguments.length;
				if (!length) return "";
				var result = "";
				while (++index < length) {
					var codePoint = Number(arguments[index]);
					if (!isFinite(codePoint) || codePoint < 0 || codePoint > 1114111 || floor(codePoint) !== codePoint) throw RangeError("Invalid code point: " + codePoint);
					if (codePoint <= 65535) codeUnits.push(codePoint);
					else {
						codePoint -= 65536;
						highSurrogate = (codePoint >> 10) + 55296;
						lowSurrogate = codePoint % 1024 + 56320;
						codeUnits.push(highSurrogate, lowSurrogate);
					}
					if (index + 1 === length || codeUnits.length > MAX_SIZE) {
						result += stringFromCharCode.apply(null, codeUnits);
						codeUnits.length = 0;
					}
				}
				return result;
			};
			/* istanbul ignore next */
			if (Object.defineProperty) Object.defineProperty(String, "fromCodePoint", {
				value: fromCodePoint,
				configurable: true,
				writable: true
			});
			else String.fromCodePoint = fromCodePoint;
		})();
	})(typeof exports === "undefined" ? exports.sax = {} : exports);
}));
//#endregion
//#region node_modules/xml2js/lib/bom.js
var require_bom = /* @__PURE__ */ __commonJSMin(((exports) => {
	(function() {
		"use strict";
		exports.stripBOM = function(str) {
			if (str[0] === "") return str.substring(1);
			else return str;
		};
	}).call(exports);
}));
//#endregion
//#region node_modules/xml2js/lib/processors.js
var require_processors = /* @__PURE__ */ __commonJSMin(((exports) => {
	(function() {
		"use strict";
		var prefixMatch = /* @__PURE__ */ new RegExp(/(?!xmlns)^.*:/);
		exports.normalize = function(str) {
			return str.toLowerCase();
		};
		exports.firstCharLowerCase = function(str) {
			return str.charAt(0).toLowerCase() + str.slice(1);
		};
		exports.stripPrefix = function(str) {
			return str.replace(prefixMatch, "");
		};
		exports.parseNumbers = function(str) {
			if (!isNaN(str)) str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str);
			return str;
		};
		exports.parseBooleans = function(str) {
			if (/^(?:true|false)$/i.test(str)) str = str.toLowerCase() === "true";
			return str;
		};
	}).call(exports);
}));
//#endregion
//#region node_modules/xml2js/lib/parser.js
var require_parser = /* @__PURE__ */ __commonJSMin(((exports) => {
	(function() {
		"use strict";
		var bom, defaults, events, isEmpty, processItem, processors, sax, setImmediate, bind = function(fn, me) {
			return function() {
				return fn.apply(me, arguments);
			};
		}, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		sax = require_sax();
		events = __require("events");
		bom = require_bom();
		processors = require_processors();
		setImmediate = __require("timers").setImmediate;
		defaults = require_defaults().defaults;
		isEmpty = function(thing) {
			return typeof thing === "object" && thing != null && Object.keys(thing).length === 0;
		};
		processItem = function(processors, item, key) {
			var i, len, process;
			for (i = 0, len = processors.length; i < len; i++) {
				process = processors[i];
				item = process(item, key);
			}
			return item;
		};
		exports.Parser = (function(superClass) {
			extend(Parser, superClass);
			function Parser(opts) {
				this.parseStringPromise = bind(this.parseStringPromise, this);
				this.parseString = bind(this.parseString, this);
				this.reset = bind(this.reset, this);
				this.assignOrPush = bind(this.assignOrPush, this);
				this.processAsync = bind(this.processAsync, this);
				var key, ref, value;
				if (!(this instanceof exports.Parser)) return new exports.Parser(opts);
				this.options = {};
				ref = defaults["0.2"];
				for (key in ref) {
					if (!hasProp.call(ref, key)) continue;
					value = ref[key];
					this.options[key] = value;
				}
				for (key in opts) {
					if (!hasProp.call(opts, key)) continue;
					value = opts[key];
					this.options[key] = value;
				}
				if (this.options.xmlns) this.options.xmlnskey = this.options.attrkey + "ns";
				if (this.options.normalizeTags) {
					if (!this.options.tagNameProcessors) this.options.tagNameProcessors = [];
					this.options.tagNameProcessors.unshift(processors.normalize);
				}
				this.reset();
			}
			Parser.prototype.processAsync = function() {
				var chunk, err;
				try {
					if (this.remaining.length <= this.options.chunkSize) {
						chunk = this.remaining;
						this.remaining = "";
						this.saxParser = this.saxParser.write(chunk);
						return this.saxParser.close();
					} else {
						chunk = this.remaining.substr(0, this.options.chunkSize);
						this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length);
						this.saxParser = this.saxParser.write(chunk);
						return setImmediate(this.processAsync);
					}
				} catch (error1) {
					err = error1;
					if (!this.saxParser.errThrown) {
						this.saxParser.errThrown = true;
						return this.emit(err);
					}
				}
			};
			Parser.prototype.assignOrPush = function(obj, key, newValue) {
				if (!(key in obj)) if (!this.options.explicitArray) return obj[key] = newValue;
				else return obj[key] = [newValue];
				else {
					if (!(obj[key] instanceof Array)) obj[key] = [obj[key]];
					return obj[key].push(newValue);
				}
			};
			Parser.prototype.reset = function() {
				var attrkey, charkey, ontext, stack;
				this.removeAllListeners();
				this.saxParser = sax.parser(this.options.strict, {
					trim: false,
					normalize: false,
					xmlns: this.options.xmlns
				});
				this.saxParser.errThrown = false;
				this.saxParser.onerror = (function(_this) {
					return function(error) {
						_this.saxParser.resume();
						if (!_this.saxParser.errThrown) {
							_this.saxParser.errThrown = true;
							return _this.emit("error", error);
						}
					};
				})(this);
				this.saxParser.onend = (function(_this) {
					return function() {
						if (!_this.saxParser.ended) {
							_this.saxParser.ended = true;
							return _this.emit("end", _this.resultObject);
						}
					};
				})(this);
				this.saxParser.ended = false;
				this.EXPLICIT_CHARKEY = this.options.explicitCharkey;
				this.resultObject = null;
				stack = [];
				attrkey = this.options.attrkey;
				charkey = this.options.charkey;
				this.saxParser.onopentag = (function(_this) {
					return function(node) {
						var key, newValue, obj = Object.create(null), processedKey, ref;
						obj[charkey] = "";
						if (!_this.options.ignoreAttrs) {
							ref = node.attributes;
							for (key in ref) {
								if (!hasProp.call(ref, key)) continue;
								if (!(attrkey in obj) && !_this.options.mergeAttrs) obj[attrkey] = Object.create(null);
								newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key];
								processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key;
								if (_this.options.mergeAttrs) _this.assignOrPush(obj, processedKey, newValue);
								else obj[attrkey][processedKey] = newValue;
							}
						}
						obj["#name"] = _this.options.tagNameProcessors ? processItem(_this.options.tagNameProcessors, node.name) : node.name;
						if (_this.options.xmlns) obj[_this.options.xmlnskey] = {
							uri: node.uri,
							local: node.local
						};
						return stack.push(obj);
					};
				})(this);
				this.saxParser.onclosetag = (function(_this) {
					return function() {
						var cdata, emptyStr, key, node, nodeName, obj = stack.pop(), objClone, old, s, xpath;
						nodeName = obj["#name"];
						if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) delete obj["#name"];
						if (obj.cdata === true) {
							cdata = obj.cdata;
							delete obj.cdata;
						}
						s = stack[stack.length - 1];
						if (obj[charkey].match(/^\s*$/) && !cdata) {
							emptyStr = obj[charkey];
							delete obj[charkey];
						} else {
							if (_this.options.trim) obj[charkey] = obj[charkey].trim();
							if (_this.options.normalize) obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim();
							obj[charkey] = _this.options.valueProcessors ? processItem(_this.options.valueProcessors, obj[charkey], nodeName) : obj[charkey];
							if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) obj = obj[charkey];
						}
						if (isEmpty(obj)) if (typeof _this.options.emptyTag === "function") obj = _this.options.emptyTag();
						else obj = _this.options.emptyTag !== "" ? _this.options.emptyTag : emptyStr;
						if (_this.options.validator != null) {
							xpath = "/" + (function() {
								var i, len, results = [];
								for (i = 0, len = stack.length; i < len; i++) {
									node = stack[i];
									results.push(node["#name"]);
								}
								return results;
							})().concat(nodeName).join("/");
							(function() {
								var err;
								try {
									return obj = _this.options.validator(xpath, s && s[nodeName], obj);
								} catch (error1) {
									err = error1;
									return _this.emit("error", err);
								}
							})();
						}
						if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === "object") {
							if (!_this.options.preserveChildrenOrder) {
								node = Object.create(null);
								if (_this.options.attrkey in obj) {
									node[_this.options.attrkey] = obj[_this.options.attrkey];
									delete obj[_this.options.attrkey];
								}
								if (!_this.options.charsAsChildren && _this.options.charkey in obj) {
									node[_this.options.charkey] = obj[_this.options.charkey];
									delete obj[_this.options.charkey];
								}
								if (Object.getOwnPropertyNames(obj).length > 0) node[_this.options.childkey] = obj;
								obj = node;
							} else if (s) {
								s[_this.options.childkey] = s[_this.options.childkey] || [];
								objClone = Object.create(null);
								for (key in obj) {
									if (!hasProp.call(obj, key)) continue;
									objClone[key] = obj[key];
								}
								s[_this.options.childkey].push(objClone);
								delete obj["#name"];
								if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) obj = obj[charkey];
							}
						}
						if (stack.length > 0) return _this.assignOrPush(s, nodeName, obj);
						else {
							if (_this.options.explicitRoot) {
								old = obj;
								obj = Object.create(null);
								obj[nodeName] = old;
							}
							_this.resultObject = obj;
							_this.saxParser.ended = true;
							return _this.emit("end", _this.resultObject);
						}
					};
				})(this);
				ontext = (function(_this) {
					return function(text) {
						var charChild, s = stack[stack.length - 1];
						if (s) {
							s[charkey] += text;
							if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && (_this.options.includeWhiteChars || text.replace(/\\n/g, "").trim() !== "")) {
								s[_this.options.childkey] = s[_this.options.childkey] || [];
								charChild = { "#name": "__text__" };
								charChild[charkey] = text;
								if (_this.options.normalize) charChild[charkey] = charChild[charkey].replace(/\s{2,}/g, " ").trim();
								s[_this.options.childkey].push(charChild);
							}
							return s;
						}
					};
				})(this);
				this.saxParser.ontext = ontext;
				return this.saxParser.oncdata = (function(_this) {
					return function(text) {
						var s = ontext(text);
						if (s) return s.cdata = true;
					};
				})(this);
			};
			Parser.prototype.parseString = function(str, cb) {
				var err;
				if (cb != null && typeof cb === "function") {
					this.on("end", function(result) {
						this.reset();
						return cb(null, result);
					});
					this.on("error", function(err) {
						this.reset();
						return cb(err);
					});
				}
				try {
					str = str.toString();
					if (str.trim() === "") {
						this.emit("end", null);
						return true;
					}
					str = bom.stripBOM(str);
					if (this.options.async) {
						this.remaining = str;
						setImmediate(this.processAsync);
						return this.saxParser;
					}
					return this.saxParser.write(str).close();
				} catch (error1) {
					err = error1;
					if (!(this.saxParser.errThrown || this.saxParser.ended)) {
						this.emit("error", err);
						return this.saxParser.errThrown = true;
					} else if (this.saxParser.ended) throw err;
				}
			};
			Parser.prototype.parseStringPromise = function(str) {
				return new Promise((function(_this) {
					return function(resolve, reject) {
						return _this.parseString(str, function(err, value) {
							if (err) return reject(err);
							else return resolve(value);
						});
					};
				})(this));
			};
			return Parser;
		})(events);
		exports.parseString = function(str, a, b) {
			var cb, options, parser;
			if (b != null) {
				if (typeof b === "function") cb = b;
				if (typeof a === "object") options = a;
			} else {
				if (typeof a === "function") cb = a;
				options = {};
			}
			parser = new exports.Parser(options);
			return parser.parseString(str, cb);
		};
		exports.parseStringPromise = function(str, a) {
			var options, parser;
			if (typeof a === "object") options = a;
			parser = new exports.Parser(options);
			return parser.parseStringPromise(str);
		};
	}).call(exports);
}));
//#endregion
//#region node_modules/xml2js/lib/xml2js.js
var require_xml2js = /* @__PURE__ */ __commonJSMin(((exports) => {
	(function() {
		"use strict";
		var builder, defaults, parser, processors, extend = function(child, parent) {
			for (var key in parent) if (hasProp.call(parent, key)) child[key] = parent[key];
			function ctor() {
				this.constructor = child;
			}
			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		}, hasProp = {}.hasOwnProperty;
		defaults = require_defaults();
		builder = require_builder();
		parser = require_parser();
		processors = require_processors();
		exports.defaults = defaults.defaults;
		exports.processors = processors;
		exports.ValidationError = (function(superClass) {
			extend(ValidationError, superClass);
			function ValidationError(message) {
				this.message = message;
			}
			return ValidationError;
		})(Error);
		exports.Builder = builder.Builder;
		exports.Parser = parser.Parser;
		exports.parseString = parser.parseString;
		exports.parseStringPromise = parser.parseStringPromise;
	}).call(exports);
}));
//#endregion
//#region node_modules/parse-bmfont-xml/lib/parse-attribs.js
var require_parse_attribs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var GLYPH_DESIGNER_ERROR = "chasrset";
	module.exports = function parseAttributes(obj) {
		obj = Object.assign({}, obj);
		if (GLYPH_DESIGNER_ERROR in obj) {
			obj["charset"] = obj[GLYPH_DESIGNER_ERROR];
			delete obj[GLYPH_DESIGNER_ERROR];
		}
		for (var k in obj) if (k === "face" || k === "charset") continue;
		else if (k === "padding" || k === "spacing") obj[k] = parseIntList(obj[k]);
		else obj[k] = parseInt(obj[k], 10);
		return obj;
	};
	function parseIntList(data) {
		return data.split(",").map(function(val) {
			return parseInt(val, 10);
		});
	}
}));
//#endregion
//#region node_modules/parse-bmfont-xml/lib/index.js
var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var xml2js = require_xml2js();
	var parseAttributes = require_parse_attribs();
	module.exports = function parseBMFontXML(data) {
		data = data.toString().trim();
		var output = {
			pages: [],
			chars: [],
			kernings: []
		};
		xml2js.parseString(data, function(err, result) {
			if (err) throw err;
			if (!result.font) throw "XML bitmap font doesn't have <font> root";
			result = result.font;
			output.common = parseAttributes(result.common[0].$);
			output.info = parseAttributes(result.info[0].$);
			for (var i = 0; i < result.pages.length; i++) {
				var p = result.pages[i].page[0].$;
				if (typeof p.id === "undefined") throw new Error("malformed file -- needs page id=N");
				if (typeof p.file !== "string") throw new Error("malformed file -- needs page file=\"path\"");
				output.pages[parseInt(p.id, 10)] = p.file;
			}
			if (result.chars) {
				var chrArray = result.chars[0]["char"] || [];
				for (var i = 0; i < chrArray.length; i++) output.chars.push(parseAttributes(chrArray[i].$));
			}
			if (result.kernings) {
				var kernArray = result.kernings[0]["kerning"] || [];
				for (var i = 0; i < kernArray.length; i++) output.kernings.push(parseAttributes(kernArray[i].$));
			}
		});
		return output;
	};
}));
//#endregion
//#region node_modules/parse-bmfont-binary/index.js
var require_parse_bmfont_binary = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var HEADER = [
		66,
		77,
		70
	];
	module.exports = function readBMFontBinary(buf) {
		if (buf.length < 6) throw new Error("invalid buffer length for BMFont");
		if (!HEADER.every(function(byte, i) {
			return buf.readUInt8(i) === byte;
		})) throw new Error("BMFont missing BMF byte header");
		var i = 3;
		if (buf.readUInt8(i++) > 3) throw new Error("Only supports BMFont Binary v3 (BMFont App v1.10)");
		var target = {
			kernings: [],
			chars: []
		};
		for (var b = 0; b < 5; b++) i += readBlock(target, buf, i);
		return target;
	};
	function readBlock(target, buf, i) {
		if (i > buf.length - 1) return 0;
		var blockID = buf.readUInt8(i++);
		var blockSize = buf.readInt32LE(i);
		i += 4;
		switch (blockID) {
			case 1:
				target.info = readInfo(buf, i);
				break;
			case 2:
				target.common = readCommon(buf, i);
				break;
			case 3:
				target.pages = readPages(buf, i, blockSize);
				break;
			case 4:
				target.chars = readChars(buf, i, blockSize);
				break;
			case 5:
				target.kernings = readKernings(buf, i, blockSize);
				break;
		}
		return 5 + blockSize;
	}
	function readInfo(buf, i) {
		var info = {};
		info.size = buf.readInt16LE(i);
		var bitField = buf.readUInt8(i + 2);
		info.smooth = bitField >> 7 & 1;
		info.unicode = bitField >> 6 & 1;
		info.italic = bitField >> 5 & 1;
		info.bold = bitField >> 4 & 1;
		if (bitField >> 3 & 1) info.fixedHeight = 1;
		info.charset = buf.readUInt8(i + 3) || "";
		info.stretchH = buf.readUInt16LE(i + 4);
		info.aa = buf.readUInt8(i + 6);
		info.padding = [
			buf.readInt8(i + 7),
			buf.readInt8(i + 8),
			buf.readInt8(i + 9),
			buf.readInt8(i + 10)
		];
		info.spacing = [buf.readInt8(i + 11), buf.readInt8(i + 12)];
		info.outline = buf.readUInt8(i + 13);
		info.face = readStringNT(buf, i + 14);
		return info;
	}
	function readCommon(buf, i) {
		var common = {};
		common.lineHeight = buf.readUInt16LE(i);
		common.base = buf.readUInt16LE(i + 2);
		common.scaleW = buf.readUInt16LE(i + 4);
		common.scaleH = buf.readUInt16LE(i + 6);
		common.pages = buf.readUInt16LE(i + 8);
		buf.readUInt8(i + 10);
		common.packed = 0;
		common.alphaChnl = buf.readUInt8(i + 11);
		common.redChnl = buf.readUInt8(i + 12);
		common.greenChnl = buf.readUInt8(i + 13);
		common.blueChnl = buf.readUInt8(i + 14);
		return common;
	}
	function readPages(buf, i, size) {
		var pages = [];
		var text = readNameNT(buf, i);
		var len = text.length + 1;
		var count = size / len;
		for (var c = 0; c < count; c++) {
			pages[c] = buf.slice(i, i + text.length).toString("utf8");
			i += len;
		}
		return pages;
	}
	function readChars(buf, i, blockSize) {
		var chars = [];
		var count = blockSize / 20;
		for (var c = 0; c < count; c++) {
			var char = {};
			var off = c * 20;
			char.id = buf.readUInt32LE(i + 0 + off);
			char.x = buf.readUInt16LE(i + 4 + off);
			char.y = buf.readUInt16LE(i + 6 + off);
			char.width = buf.readUInt16LE(i + 8 + off);
			char.height = buf.readUInt16LE(i + 10 + off);
			char.xoffset = buf.readInt16LE(i + 12 + off);
			char.yoffset = buf.readInt16LE(i + 14 + off);
			char.xadvance = buf.readInt16LE(i + 16 + off);
			char.page = buf.readUInt8(i + 18 + off);
			char.chnl = buf.readUInt8(i + 19 + off);
			chars[c] = char;
		}
		return chars;
	}
	function readKernings(buf, i, blockSize) {
		var kernings = [];
		var count = blockSize / 10;
		for (var c = 0; c < count; c++) {
			var kern = {};
			var off = c * 10;
			kern.first = buf.readUInt32LE(i + 0 + off);
			kern.second = buf.readUInt32LE(i + 4 + off);
			kern.amount = buf.readInt16LE(i + 8 + off);
			kernings[c] = kern;
		}
		return kernings;
	}
	function readNameNT(buf, offset) {
		var pos = offset;
		for (; pos < buf.length; pos++) if (buf[pos] === 0) break;
		return buf.slice(offset, pos);
	}
	function readStringNT(buf, offset) {
		return readNameNT(buf, offset).toString("utf8");
	}
}));
//#endregion
//#region node_modules/simple-xml-to-json/lib/simpleXmlToJson.min.js
var require_simpleXmlToJson_min = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	function e(e) {
		return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
	}
	const t = (e) => {
		if (!e) return null;
		const r = {};
		switch (e.type) {
			case "ELEMENT": {
				let a = {};
				const u = s(e.value.attributes), c = t(e.value.children);
				if (u && (a = Object.assign(a, u)), c) {
					const t = n(e.value.children);
					a = Object.assign(a, t);
				}
				r[e.value.type] = a;
				break;
			}
			case "ATTRIBUTE": {
				const t = e.value;
				r[t.name] = t.value;
				break;
			}
			case "CONTENT": return { content: e.value };
		}
		return r;
	}, n = (e) => e && Array.isArray(e) && 0 !== e.length ? r(e) ? { content: e[0].value } : { children: e.map(t) } : null, r = (e) => e && Array.isArray(e) && 1 === e.length && "CONTENT" === e[0].type, s = (e) => {
		if (e && Array.isArray(e)) return e.map(t).reduce(((e, t) => Object.assign(e, t)), {});
		return null;
	};
	var a = { convert: (e) => t(e.value.children[0]) };
	var u = { Token: (e, t) => ({
		type: e,
		value: t
	}) };
	const { Token: c } = u, l = c("EOF"), o = (e) => " " === e || "\n" === e || "\r" === e || "	" === e, E = (e) => e.replace(/'/g, "'");
	const { createLexer: i } = { createLexer: function(e) {
		let t = null, n = ((e) => {
			let t = 0;
			for (; t < e.length && o(e[t]);) t++;
			return ((e, t) => {
				if (e.startsWith("<?xml", t)) {
					const n = e.length;
					for (; t < n;) if ("?" !== e[t]) t++;
					else {
						if (">" === e[t + 1]) return t + 2;
						t++;
					}
				}
				return t;
			})(e, t);
		})(e), r = [];
		const s = () => e[n], a = () => t !== l && n < e.length, u = (e) => "\"" === e || "'" === e, T = () => {
			for (; a() && o(e[n]);) n++;
		}, i = (t) => {
			if (a()) {
				if ("<" === e[n]) {
					let t = "<";
					return n++, a() && "/" === e[n] ? (n++, t = "</") : a() && "!" === e[n] && "-" === e[n + 1] && "-" === e[n + 2] && (n++, n++, n++, t = "<!--"), t;
				}
				if ("/" === s()) {
					let e = "/";
					return n++, a() && ">" === s() && (n++, e = "/>"), e;
				}
				if ("=" === e[n] || ">" === e[n]) {
					const t = e[n];
					return n++, t;
				}
			}
			return p(!!t);
		}, p = (t) => {
			const r = t ? /[^>=<]/u : /[a-zA-Z0-9_:-]/;
			let s = n;
			for (; a() && e[n].match(r);) n++;
			return E(e.substring(s, n));
		}, N = () => {
			const o = n;
			T();
			const f = n - o;
			if (a()) if (t && "OPEN_BRACKET" === t.type) {
				T();
				const e = i(!1);
				t = c("ELEMENT_TYPE", e), r.push(e);
			} else if (t && "ASSIGN" === t.type) {
				a() && u(s()) && n++;
				const r = e[n - 1];
				let l = n;
				for (; a() && s() !== r;) n++;
				const o = E(e.substring(l, n));
				n++, t = c("ATTRIB_VALUE", o);
			} else {
				T();
				let u = i(!0);
				switch (u) {
					case "=":
						t = "ATTRIB_NAME" === t.type ? c("ASSIGN") : c("CONTENT", u);
						break;
					case "</": {
						const s = n;
						for (; ">" !== e[n];) n++;
						t = c("CLOSE_ELEMENT", e.substring(s, n)), n++, r.pop();
						break;
					}
					case "/>":
						t = c("CLOSE_ELEMENT", r.pop());
						break;
					case "<!--": {
						const t = [
							"!",
							"-",
							"-"
						];
						for (; a() && (">" !== t[2] || "-" !== t[1] || "-" !== t[0]);) t.shift(), t.push(e[n]), n++;
						return N();
					}
					case ">":
						t = c("CLOSE_BRACKET");
						break;
					case "<":
						t = c("OPEN_BRACKET");
						break;
					default:
						if (u && u.length > 0) {
							if ("CLOSE_BRACKET" === t.type) {
								let e = "";
								"<" !== s() && (e = p(!0)), t = c("CONTENT", u + e);
							} else if ("ATTRIB_NAME" !== t.type && "CONTENT" !== t.type) "CLOSE_ELEMENT" === t.type ? (u = " ".repeat(f) + u, t = c("CONTENT", u)) : t = c("ATTRIB_NAME", u);
							else t = c("CONTENT", " ".repeat(f) + u);
							break;
						}
						{
							const t = "Unknown Syntax : \"" + e[n] + "\"";
							throw new Error(t);
						}
				}
			}
			else t = l;
			return t;
		};
		return {
			peek: s,
			next: N,
			hasNext: a
		};
	} }, { Token: p } = u, [N, f, h, O] = [
		"ROOT",
		"ELEMENT",
		"ATTRIBUTE",
		"CONTENT"
	], y = (e, t) => ({
		type: e,
		value: t
	}), v = (e) => y(O, e), C = (e, t, n) => y(f, {
		type: e,
		attributes: t,
		children: n
	}), A = (e, t) => y(h, {
		name: e,
		value: t
	}), L = (e, t) => {
		const n = [];
		for (; e.hasNext();) {
			const r = e.next();
			switch (r.type) {
				case "OPEN_BRACKET": {
					const t = e.next(), [r, s] = _(e);
					let a = [];
					"CLOSE_ELEMENT" !== s.type && (a = L(e, t)), a && a.length > 0 && "CONTENT" === a[0].type && (a = b(a)), n.push(C(t.value, r, a));
					break;
				}
				case "CLOSE_ELEMENT":
					if (r.value === t.value) return n;
					break;
				case "CONTENT":
					n.push(v(r.value));
					break;
				case "EOF": return n;
				default: throw new Error(`Unknown Lexem type: ${r.type} "${r.value}, scoping element: ${t.value}"`);
			}
		}
		return n;
	}, _ = (e) => {
		const t = [];
		let n = e.peek();
		if (!e.hasNext() || n && "CLOSE_BRACKET" === n.type || n && "CLOSE_ELEMENT" === n.type) return [t, n];
		for (n = e.next(); e.hasNext() && n && "CLOSE_BRACKET" !== n.type && "CLOSE_ELEMENT" !== n.type;) {
			const r = n;
			"content" === r.value && (r.value = "@content"), e.next();
			const s = e.next(), a = A(r.value, s.value);
			t.push(a), n = e.next();
		}
		return [t, n];
	};
	function b(e) {
		let t = [], n = "";
		return e.forEach(((e) => {
			"CONTENT" === e.type ? n += e.value : (n.length && (t.push(v(n)), n = ""), t.push(e));
		})), n.length && t.push(v(n)), t;
	}
	var x = {
		AttribNode: A,
		ContentNode: v,
		ElementNode: C,
		Node: y,
		transpile: function(e, t) {
			const n = ((e) => y(N, { children: L(e, p(N, "ROOT")) }))(i(e));
			return t ? t.convert(n) : n;
		}
	};
	const k = a, { transpile: d } = x;
	module.exports = e({
		convertXML: function(e, t) {
			return d(e, t || k);
		},
		createAST: function(e) {
			return d(e);
		}
	});
}));
//#endregion
//#region node_modules/@jimp/plugin-print/dist/esm/load-bitmap-font.js
var import_parse_bmfont_ascii = /* @__PURE__ */ __toESM(require_parse_bmfont_ascii(), 1);
var import_lib = /* @__PURE__ */ __toESM(require_lib(), 1);
var import_parse_bmfont_binary = /* @__PURE__ */ __toESM(require_parse_bmfont_binary(), 1);
const { convertXML } = (/* @__PURE__ */ __toESM(require_simpleXmlToJson_min(), 1)).default;
const isWebWorker = typeof self !== "undefined" && self.document === void 0;
const CharacterJimp = createJimp({ formats: [png] });
const HEADER = Buffer.from([
	66,
	77,
	70,
	3
]);
function isBinary(buf) {
	if (typeof buf === "string") return buf.substring(0, 3) === "BMF";
	const startOfHeader = buf.slice(0, 4);
	return buf.length > 4 && startOfHeader[0] === HEADER[0] && startOfHeader[1] === HEADER[1] && startOfHeader[2] === HEADER[2];
}
function parseFont(file, data) {
	if (isBinary(data)) {
		if (typeof data === "string") data = Buffer.from(data, "binary");
		return (0, import_parse_bmfont_binary.default)(data);
	}
	data = data.toString().trim();
	if (/.json$/.test(file) || data.charAt(0) === "{") return JSON.parse(data);
	if (/.xml$/.test(file) || data.charAt(0) === "<") return (0, import_lib.default)(data);
	return (0, import_parse_bmfont_ascii.default)(data);
}
function parseNumbersInObject(obj) {
	for (const key in obj) {
		try {
			obj[key] = parseInt(obj[key], 10);
		} catch {}
		if (typeof obj[key] === "object") parseNumbersInObject(obj[key]);
	}
	return obj;
}
/**
*
* @param bufferOrUrl A URL to a file or a buffer
* @returns
*/
async function loadBitmapFontData(bufferOrUrl) {
	if (isWebWorker && typeof bufferOrUrl === "string") {
		const font = convertXML(await (await fetch(bufferOrUrl)).text()).font.children.reduce((acc, i) => ({
			...acc,
			...i
		}), {});
		const pages = [];
		const chars = [];
		const kernings = [];
		for (let i = 0; i < font.pages.children.length; i++) {
			const p = font.pages.children[i].page;
			const id = parseInt(p.id, 10);
			pages[id] = parseNumbersInObject(p.file);
		}
		for (let i = 0; i < font.chars.children.length; i++) chars.push(parseNumbersInObject(font.chars.children[i].char));
		for (let i = 0; i < font.kernings.children.length; i++) kernings.push(parseNumbersInObject(font.kernings.children[i].kerning));
		return {
			info: font.info,
			common: font.common,
			pages,
			chars,
			kernings
		};
	} else if (typeof bufferOrUrl === "string") return parseFont(bufferOrUrl, await (await fetch(bufferOrUrl)).text());
	else return parseFont("", bufferOrUrl);
}
async function processBitmapFont(file, font) {
	const chars = {};
	const kernings = {};
	for (let i = 0; i < font.chars.length; i++) {
		const char = font.chars[i];
		chars[String.fromCharCode(char.id)] = char;
	}
	for (let i = 0; i < font.kernings.length; i++) {
		const firstString = String.fromCharCode(font.kernings[i].first);
		kernings[firstString] = kernings[firstString] || {};
		kernings[firstString][String.fromCharCode(font.kernings[i].second)] = font.kernings[i].amount;
	}
	return {
		...font,
		chars,
		kernings,
		pages: await Promise.all(font.pages.map(async (page) => CharacterJimp.read(path.join(path.dirname(file), page))))
	};
}
//#endregion
//#region node_modules/@jimp/plugin-print/dist/esm/load-font.js
/**
* Loads a Bitmap Font from a file.
* @param file A path or URL to a font file
* @returns A collection of Jimp images that can be used to print text
* @example
* ```ts
* import { Jimp, loadFont } from "jimp";
* import { SANS_10_BLACK } from "jimp/fonts";
*
* const font = await loadFont(SANS_10_BLACK);
* const image = new Jimp({ width: 200, height: 100, color: 0xffffffff });
*
* image.print(font, 10, 10, "Hello world!");
* ```
*/
async function loadFont(file) {
	let fileOrBuffer = file;
	if (typeof window === "undefined" && !isWebWorker) {
		const { existsSync, promises: fs } = await import("fs");
		if (existsSync(file)) fileOrBuffer = await fs.readFile(file);
	}
	return processBitmapFont(file, await loadBitmapFontData(fileOrBuffer));
}
//#endregion
//#region node_modules/@jimp/diff/dist/esm/index.js
var import_pixelmatch = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = pixelmatch;
	const defaultOptions = {
		threshold: .1,
		includeAA: false,
		alpha: .1,
		aaColor: [
			255,
			255,
			0
		],
		diffColor: [
			255,
			0,
			0
		],
		diffColorAlt: null,
		diffMask: false
	};
	function pixelmatch(img1, img2, output, width, height, options) {
		if (!isPixelData(img1) || !isPixelData(img2) || output && !isPixelData(output)) throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");
		if (img1.length !== img2.length || output && output.length !== img1.length) throw new Error("Image sizes do not match.");
		if (img1.length !== width * height * 4) throw new Error("Image data size does not match width/height.");
		options = Object.assign({}, defaultOptions, options);
		const len = width * height;
		const a32 = new Uint32Array(img1.buffer, img1.byteOffset, len);
		const b32 = new Uint32Array(img2.buffer, img2.byteOffset, len);
		let identical = true;
		for (let i = 0; i < len; i++) if (a32[i] !== b32[i]) {
			identical = false;
			break;
		}
		if (identical) {
			if (output && !options.diffMask) for (let i = 0; i < len; i++) drawGrayPixel(img1, 4 * i, options.alpha, output);
			return 0;
		}
		const maxDelta = 35215 * options.threshold * options.threshold;
		let diff = 0;
		for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
			const pos = (y * width + x) * 4;
			const delta = colorDelta(img1, img2, pos, pos);
			if (Math.abs(delta) > maxDelta) if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) || antialiased(img2, x, y, width, height, img1))) {
				if (output && !options.diffMask) drawPixel(output, pos, ...options.aaColor);
			} else {
				if (output) drawPixel(output, pos, ...delta < 0 && options.diffColorAlt || options.diffColor);
				diff++;
			}
			else if (output) {
				if (!options.diffMask) drawGrayPixel(img1, pos, options.alpha, output);
			}
		}
		return diff;
	}
	function isPixelData(arr) {
		return ArrayBuffer.isView(arr) && arr.constructor.BYTES_PER_ELEMENT === 1;
	}
	function antialiased(img, x1, y1, width, height, img2) {
		const x0 = Math.max(x1 - 1, 0);
		const y0 = Math.max(y1 - 1, 0);
		const x2 = Math.min(x1 + 1, width - 1);
		const y2 = Math.min(y1 + 1, height - 1);
		const pos = (y1 * width + x1) * 4;
		let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0;
		let min = 0;
		let max = 0;
		let minX, minY, maxX, maxY;
		for (let x = x0; x <= x2; x++) for (let y = y0; y <= y2; y++) {
			if (x === x1 && y === y1) continue;
			const delta = colorDelta(img, img, pos, (y * width + x) * 4, true);
			if (delta === 0) {
				zeroes++;
				if (zeroes > 2) return false;
			} else if (delta < min) {
				min = delta;
				minX = x;
				minY = y;
			} else if (delta > max) {
				max = delta;
				maxX = x;
				maxY = y;
			}
		}
		if (min === 0 || max === 0) return false;
		return hasManySiblings(img, minX, minY, width, height) && hasManySiblings(img2, minX, minY, width, height) || hasManySiblings(img, maxX, maxY, width, height) && hasManySiblings(img2, maxX, maxY, width, height);
	}
	function hasManySiblings(img, x1, y1, width, height) {
		const x0 = Math.max(x1 - 1, 0);
		const y0 = Math.max(y1 - 1, 0);
		const x2 = Math.min(x1 + 1, width - 1);
		const y2 = Math.min(y1 + 1, height - 1);
		const pos = (y1 * width + x1) * 4;
		let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0;
		for (let x = x0; x <= x2; x++) for (let y = y0; y <= y2; y++) {
			if (x === x1 && y === y1) continue;
			const pos2 = (y * width + x) * 4;
			if (img[pos] === img[pos2] && img[pos + 1] === img[pos2 + 1] && img[pos + 2] === img[pos2 + 2] && img[pos + 3] === img[pos2 + 3]) zeroes++;
			if (zeroes > 2) return true;
		}
		return false;
	}
	function colorDelta(img1, img2, k, m, yOnly) {
		let r1 = img1[k + 0];
		let g1 = img1[k + 1];
		let b1 = img1[k + 2];
		let a1 = img1[k + 3];
		let r2 = img2[m + 0];
		let g2 = img2[m + 1];
		let b2 = img2[m + 2];
		let a2 = img2[m + 3];
		if (a1 === a2 && r1 === r2 && g1 === g2 && b1 === b2) return 0;
		if (a1 < 255) {
			a1 /= 255;
			r1 = blend(r1, a1);
			g1 = blend(g1, a1);
			b1 = blend(b1, a1);
		}
		if (a2 < 255) {
			a2 /= 255;
			r2 = blend(r2, a2);
			g2 = blend(g2, a2);
			b2 = blend(b2, a2);
		}
		const y1 = rgb2y(r1, g1, b1);
		const y2 = rgb2y(r2, g2, b2);
		const y = y1 - y2;
		if (yOnly) return y;
		const i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2);
		const q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2);
		const delta = .5053 * y * y + .299 * i * i + .1957 * q * q;
		return y1 > y2 ? -delta : delta;
	}
	function rgb2y(r, g, b) {
		return r * .29889531 + g * .58662247 + b * .11448223;
	}
	function rgb2i(r, g, b) {
		return r * .59597799 - g * .2741761 - b * .32180189;
	}
	function rgb2q(r, g, b) {
		return r * .21147017 - g * .52261711 + b * .31114694;
	}
	function blend(c, a) {
		return 255 + (c - 255) * a;
	}
	function drawPixel(output, pos, r, g, b) {
		output[pos + 0] = r;
		output[pos + 1] = g;
		output[pos + 2] = b;
		output[pos + 3] = 255;
	}
	function drawGrayPixel(img, i, alpha, output) {
		const r = img[i + 0];
		const g = img[i + 1];
		const b = img[i + 2];
		const val = blend(rgb2y(r, g, b), alpha * img[i + 3] / 255);
		drawPixel(output, i, val, val, val);
	}
})))(), 1);
/**
* Diffs two images and returns
* @param img1 A Jimp image to compare
* @param img2 A Jimp image to compare
* @param threshold A number, 0 to 1, the smaller the value the more sensitive the comparison (default: 0.1)
* @returns An object with the following properties:
* - percent: The proportion of different pixels (0-1), where 0 means the two images are pixel identical
* - image: A Jimp image showing differences
* @example
* ```ts
* import { Jimp, diff } from "jimp";
*
* const image1 = await Jimp.read("test/image.png");
* const image2 = await Jimp.read("test/image.png");
*
* const diff = diff(image1, image2);
*
* diff.percent; // 0.5
* diff.image; // a Jimp image showing differences
* ```
*/
function diff(img1, img2, threshold = .1) {
	let bmp1 = img1.bitmap;
	let bmp2 = img2.bitmap;
	if (bmp1.width !== bmp2.width || bmp1.height !== bmp2.height) if (bmp1.width * bmp1.height > bmp2.width * bmp2.height) bmp1 = methods$13.resize(clone(img1), {
		w: bmp2.width,
		h: bmp2.height
	}).bitmap;
	else bmp2 = methods$13.resize(clone(img2), {
		w: bmp1.width,
		h: bmp1.height
	}).bitmap;
	if (typeof threshold !== "number" || threshold < 0 || threshold > 1) throw new Error("threshold must be a number between 0 and 1");
	const diff = new img1.constructor({
		width: bmp1.width,
		height: bmp1.height,
		color: 4294967295
	});
	return {
		percent: (0, import_pixelmatch.default)(bmp1.data, bmp2.data, diff.bitmap.data, diff.bitmap.width, diff.bitmap.height, { threshold }) / (diff.bitmap.width * diff.bitmap.height),
		image: diff
	};
}
//#endregion
//#region node_modules/jimp/dist/esm/index.js
/**
* @module jimp
*/
const defaultPlugins = [
	methods$17,
	methods$16,
	methods$15,
	methods$14,
	methods$12,
	methods$10,
	methods$11,
	methods$9,
	methods$8,
	methods$7,
	methods$6,
	methods$5,
	methods$4,
	methods$3,
	methods$13,
	methods$2,
	methods$1,
	methods
];
const defaultFormats = [
	bmp,
	msBmp,
	gif,
	jpeg,
	png,
	tiff
];
/** Convenience object for getting the MIME types of the default formats */
const JimpMime = {
	bmp: bmp().mime,
	gif: gif().mime,
	jpeg: jpeg().mime,
	png: png().mime,
	tiff: tiff().mime
};
/**
* @class
*
* A `Jimp` class enables you to:class
*
* - Read an image into a "bit map" (a collection of pixels)
* - Modify the bit map through methods that change the pixels
* - Write the bit map back to an image buffer
*
* @example
*
* #### Basic
*
* You can use the Jimp class to make empty images.
* This is useful for when you want to create an image that composed of other images on top of a background.
*
* ```ts
* import { Jimp } from "jimp";
*
* const image = new Jimp({ width: 256, height: 256, color: 0xffffffff });
* const image2 = new Jimp({ width: 100, height: 100, color: 0xff0000ff });
*
* image.composite(image2, 50, 50);
* ```
*
* #### Node
*
* You can use jimp in Node.js.
* For example you can read an image from a file and resize it and
* then write it back to a file.
*
* ```ts
* import { Jimp } from "jimp";
* import { promises as fs } from "fs";
*
* const image = await Jimp.read("test/image.png");
*
* image.resize(256, 100);
* image.greyscale();
*
* await image.write('test/output.png');
* ```
*
* #### Browser
*
* You can use jimp in the browser by reading files from URLs
*
* ```ts
* import { Jimp } from "jimp";
*
* const image = await Jimp.read("https://upload.wikimedia.org/wikipedia/commons/0/01/Bot-Test.jpg");
*
* image.resize(256, 100);
* image.greyscale();
*
* const output = await image.getBuffer("test/image.png");
*
* const canvas = document.createElement("canvas");
*
* canvas.width = image.bitmap.width;
* canvas.height = image.bitmap.height;
*
* const ctx = canvas.getContext("2d");
* ctx.putImageData(image.bitmap, 0, 0);
*
* document.body.appendChild(canvas);
* ```
*/
const Jimp = createJimp({
	formats: defaultFormats,
	plugins: defaultPlugins
});
//#endregion
export { BlendMode, BmpCompression, HorizontalAlign, Jimp, JimpMime, PNGColorType, PNGFilterType, ResizeStrategy, VerticalAlign, colorDiff, compareHashes, cssColorToHex, defaultFormats, defaultPlugins, diff, distance, intToRGBA, limit255, loadFont, measureText, measureTextHeight, rgbaToInt };