@kiloscribe/inscription-sdk
Version:
SDK for inscribing files on Hedera
12,388 lines • 371 kB
JavaScript
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value2) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value2 }) : obj[key] = value2;
var __publicField = (obj, key, value2) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value2);
import { Client, PrivateKey, TransferTransaction } from "@hashgraph/sdk";
import { detectKeyTypeFromString, HederaMirrorNode } from "@hashgraphonline/standards-sdk";
var buffer = {};
var base64Js = {};
base64Js.byteLength = byteLength$1;
base64Js.toByteArray = toByteArray;
base64Js.fromByteArray = fromByteArray;
var lookup$2 = [];
var revLookup = [];
var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (var i$1 = 0, len = code.length; i$1 < len; ++i$1) {
lookup$2[i$1] = code[i$1];
revLookup[code.charCodeAt(i$1)] = i$1;
}
revLookup["-".charCodeAt(0)] = 62;
revLookup["_".charCodeAt(0)] = 63;
function getLens(b64) {
var len = b64.length;
if (len % 4 > 0) {
throw new Error("Invalid string. Length must be a multiple of 4");
}
var validLen = b64.indexOf("=");
if (validLen === -1) validLen = len;
var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
return [validLen, placeHoldersLen];
}
function byteLength$1(b64) {
var lens = getLens(b64);
var validLen = lens[0];
var placeHoldersLen = lens[1];
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function _byteLength(b64, validLen, placeHoldersLen) {
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function toByteArray(b64) {
var tmp;
var lens = getLens(b64);
var validLen = lens[0];
var placeHoldersLen = lens[1];
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
var curByte = 0;
var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
var i;
for (i = 0; i < len; i += 4) {
tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
arr[curByte++] = tmp >> 16 & 255;
arr[curByte++] = tmp >> 8 & 255;
arr[curByte++] = tmp & 255;
}
if (placeHoldersLen === 2) {
tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
arr[curByte++] = tmp & 255;
}
if (placeHoldersLen === 1) {
tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
arr[curByte++] = tmp >> 8 & 255;
arr[curByte++] = tmp & 255;
}
return arr;
}
function tripletToBase64(num) {
return lookup$2[num >> 18 & 63] + lookup$2[num >> 12 & 63] + lookup$2[num >> 6 & 63] + lookup$2[num & 63];
}
function encodeChunk(uint8, start, end) {
var tmp;
var output = [];
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255);
output.push(tripletToBase64(tmp));
}
return output.join("");
}
function fromByteArray(uint8) {
var tmp;
var len = uint8.length;
var extraBytes = len % 3;
var parts2 = [];
var maxChunkLength = 16383;
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts2.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
}
if (extraBytes === 1) {
tmp = uint8[len - 1];
parts2.push(
lookup$2[tmp >> 2] + lookup$2[tmp << 4 & 63] + "=="
);
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
parts2.push(
lookup$2[tmp >> 10] + lookup$2[tmp >> 4 & 63] + lookup$2[tmp << 2 & 63] + "="
);
}
return parts2.join("");
}
var ieee754$1 = {};
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
ieee754$1.read = function(buffer2, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? nBytes - 1 : 0;
var d = isLE ? -1 : 1;
var s = buffer2[offset + i];
i += d;
e = s & (1 << -nBits) - 1;
s >>= -nBits;
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer2[offset + i], i += d, nBits -= 8) {
}
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer2[offset + i], i += d, nBits -= 8) {
}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : (s ? -1 : 1) * Infinity;
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
ieee754$1.write = function(buffer2, value2, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
var i = isLE ? 0 : nBytes - 1;
var d = isLE ? 1 : -1;
var s = value2 < 0 || value2 === 0 && 1 / value2 < 0 ? 1 : 0;
value2 = Math.abs(value2);
if (isNaN(value2) || value2 === Infinity) {
m = isNaN(value2) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value2) / Math.LN2);
if (value2 * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value2 += rt / c;
} else {
value2 += rt * Math.pow(2, 1 - eBias);
}
if (value2 * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value2 * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value2 * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer2[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
}
e = e << mLen | m;
eLen += mLen;
for (; eLen > 0; buffer2[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
}
buffer2[offset + i - d] |= s * 128;
};
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
(function(exports) {
const base64 = base64Js;
const ieee754$1$1 = ieee754$1;
const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
exports.Buffer = Buffer3;
exports.SlowBuffer = SlowBuffer;
exports.INSPECT_MAX_BYTES = 50;
const K_MAX_LENGTH = 2147483647;
exports.kMaxLength = K_MAX_LENGTH;
const { Uint8Array: GlobalUint8Array, ArrayBuffer: GlobalArrayBuffer, SharedArrayBuffer: GlobalSharedArrayBuffer } = globalThis;
Buffer3.TYPED_ARRAY_SUPPORT = typedArraySupport();
if (!Buffer3.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
console.error(
"This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
);
}
function typedArraySupport() {
try {
const arr = new GlobalUint8Array(1);
const proto = { foo: function() {
return 42;
} };
Object.setPrototypeOf(proto, GlobalUint8Array.prototype);
Object.setPrototypeOf(arr, proto);
return arr.foo() === 42;
} catch (e) {
return false;
}
}
Object.defineProperty(Buffer3.prototype, "parent", {
enumerable: true,
get: function() {
if (!Buffer3.isBuffer(this)) return void 0;
return this.buffer;
}
});
Object.defineProperty(Buffer3.prototype, "offset", {
enumerable: true,
get: function() {
if (!Buffer3.isBuffer(this)) return void 0;
return this.byteOffset;
}
});
function createBuffer(length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"');
}
const buf = new GlobalUint8Array(length);
Object.setPrototypeOf(buf, Buffer3.prototype);
return buf;
}
function Buffer3(arg, encodingOrOffset, length) {
if (typeof arg === "number") {
if (typeof encodingOrOffset === "string") {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
);
}
return allocUnsafe(arg);
}
return from(arg, encodingOrOffset, length);
}
Buffer3.poolSize = 8192;
function from(value2, encodingOrOffset, length) {
if (typeof value2 === "string") {
return fromString(value2, encodingOrOffset);
}
if (GlobalArrayBuffer.isView(value2)) {
return fromArrayView(value2);
}
if (value2 == null) {
throw new TypeError(
"The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value2
);
}
if (isInstance(value2, GlobalArrayBuffer) || value2 && isInstance(value2.buffer, GlobalArrayBuffer)) {
return fromArrayBuffer(value2, encodingOrOffset, length);
}
if (typeof GlobalSharedArrayBuffer !== "undefined" && (isInstance(value2, GlobalSharedArrayBuffer) || value2 && isInstance(value2.buffer, GlobalSharedArrayBuffer))) {
return fromArrayBuffer(value2, encodingOrOffset, length);
}
if (typeof value2 === "number") {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
);
}
const valueOf = value2.valueOf && value2.valueOf();
if (valueOf != null && valueOf !== value2) {
return Buffer3.from(valueOf, encodingOrOffset, length);
}
const b = fromObject(value2);
if (b) return b;
if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value2[Symbol.toPrimitive] === "function") {
return Buffer3.from(value2[Symbol.toPrimitive]("string"), encodingOrOffset, length);
}
throw new TypeError(
"The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value2
);
}
Buffer3.from = function(value2, encodingOrOffset, length) {
return from(value2, encodingOrOffset, length);
};
Object.setPrototypeOf(Buffer3.prototype, GlobalUint8Array.prototype);
Object.setPrototypeOf(Buffer3, GlobalUint8Array);
function assertSize(size) {
if (typeof size !== "number") {
throw new TypeError('"size" argument must be of type number');
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"');
}
}
function alloc(size, fill, encoding) {
assertSize(size);
if (size <= 0) {
return createBuffer(size);
}
if (fill !== void 0) {
return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
}
return createBuffer(size);
}
Buffer3.alloc = function(size, fill, encoding) {
return alloc(size, fill, encoding);
};
function allocUnsafe(size) {
assertSize(size);
return createBuffer(size < 0 ? 0 : checked(size) | 0);
}
Buffer3.allocUnsafe = function(size) {
return allocUnsafe(size);
};
Buffer3.allocUnsafeSlow = function(size) {
return allocUnsafe(size);
};
function fromString(string, encoding) {
if (typeof encoding !== "string" || encoding === "") {
encoding = "utf8";
}
if (!Buffer3.isEncoding(encoding)) {
throw new TypeError("Unknown encoding: " + encoding);
}
const length = byteLength2(string, encoding) | 0;
let buf = createBuffer(length);
const actual = buf.write(string, encoding);
if (actual !== length) {
buf = buf.slice(0, actual);
}
return buf;
}
function fromArrayLike(array) {
const length = array.length < 0 ? 0 : checked(array.length) | 0;
const buf = createBuffer(length);
for (let i = 0; i < length; i += 1) {
buf[i] = array[i] & 255;
}
return buf;
}
function fromArrayView(arrayView) {
if (isInstance(arrayView, GlobalUint8Array)) {
const copy = new GlobalUint8Array(arrayView);
return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
}
return fromArrayLike(arrayView);
}
function fromArrayBuffer(array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds');
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds');
}
let buf;
if (byteOffset === void 0 && length === void 0) {
buf = new GlobalUint8Array(array);
} else if (length === void 0) {
buf = new GlobalUint8Array(array, byteOffset);
} else {
buf = new GlobalUint8Array(array, byteOffset, length);
}
Object.setPrototypeOf(buf, Buffer3.prototype);
return buf;
}
function fromObject(obj) {
if (Buffer3.isBuffer(obj)) {
const len = checked(obj.length) | 0;
const buf = createBuffer(len);
if (buf.length === 0) {
return buf;
}
obj.copy(buf, 0, 0, len);
return buf;
}
if (obj.length !== void 0) {
if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
return createBuffer(0);
}
return fromArrayLike(obj);
}
if (obj.type === "Buffer" && Array.isArray(obj.data)) {
return fromArrayLike(obj.data);
}
}
function checked(length) {
if (length >= K_MAX_LENGTH) {
throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
}
return length | 0;
}
function SlowBuffer(length) {
if (+length != length) {
length = 0;
}
return Buffer3.alloc(+length);
}
Buffer3.isBuffer = function isBuffer2(b) {
return b != null && b._isBuffer === true && b !== Buffer3.prototype;
};
Buffer3.compare = function compare(a, b) {
if (isInstance(a, GlobalUint8Array)) a = Buffer3.from(a, a.offset, a.byteLength);
if (isInstance(b, GlobalUint8Array)) b = Buffer3.from(b, b.offset, b.byteLength);
if (!Buffer3.isBuffer(a) || !Buffer3.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
);
}
if (a === b) return 0;
let x = a.length;
let y = b.length;
for (let i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
Buffer3.isEncoding = function isEncoding(encoding) {
switch (String(encoding).toLowerCase()) {
case "hex":
case "utf8":
case "utf-8":
case "ascii":
case "latin1":
case "binary":
case "base64":
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return true;
default:
return false;
}
};
Buffer3.concat = function concat(list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers');
}
if (list.length === 0) {
return Buffer3.alloc(0);
}
let i;
if (length === void 0) {
length = 0;
for (i = 0; i < list.length; ++i) {
length += list[i].length;
}
}
const buffer2 = Buffer3.allocUnsafe(length);
let pos = 0;
for (i = 0; i < list.length; ++i) {
let buf = list[i];
if (isInstance(buf, GlobalUint8Array)) {
if (pos + buf.length > buffer2.length) {
if (!Buffer3.isBuffer(buf)) buf = Buffer3.from(buf);
buf.copy(buffer2, pos);
} else {
GlobalUint8Array.prototype.set.call(
buffer2,
buf,
pos
);
}
} else if (!Buffer3.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers');
} else {
buf.copy(buffer2, pos);
}
pos += buf.length;
}
return buffer2;
};
function byteLength2(string, encoding) {
if (Buffer3.isBuffer(string)) {
return string.length;
}
if (GlobalArrayBuffer.isView(string) || isInstance(string, GlobalArrayBuffer)) {
return string.byteLength;
}
if (typeof string !== "string") {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
);
}
const len = string.length;
const mustMatch = arguments.length > 2 && arguments[2] === true;
if (!mustMatch && len === 0) return 0;
let loweredCase = false;
for (; ; ) {
switch (encoding) {
case "ascii":
case "latin1":
case "binary":
return len;
case "utf8":
case "utf-8":
return utf8ToBytes(string).length;
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return len * 2;
case "hex":
return len >>> 1;
case "base64":
return base64ToBytes(string).length;
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length;
}
encoding = ("" + encoding).toLowerCase();
loweredCase = true;
}
}
}
Buffer3.byteLength = byteLength2;
function slowToString(encoding, start, end) {
let loweredCase = false;
if (start === void 0 || start < 0) {
start = 0;
}
if (start > this.length) {
return "";
}
if (end === void 0 || end > this.length) {
end = this.length;
}
if (end <= 0) {
return "";
}
end >>>= 0;
start >>>= 0;
if (end <= start) {
return "";
}
if (!encoding) encoding = "utf8";
while (true) {
switch (encoding) {
case "hex":
return hexSlice(this, start, end);
case "utf8":
case "utf-8":
return utf8Slice(this, start, end);
case "ascii":
return asciiSlice(this, start, end);
case "latin1":
case "binary":
return latin1Slice(this, start, end);
case "base64":
return base64Slice(this, start, end);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return utf16leSlice(this, start, end);
default:
if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
encoding = (encoding + "").toLowerCase();
loweredCase = true;
}
}
}
Buffer3.prototype._isBuffer = true;
function swap(b, n, m) {
const i = b[n];
b[n] = b[m];
b[m] = i;
}
Buffer3.prototype.swap16 = function swap16() {
const len = this.length;
if (len % 2 !== 0) {
throw new RangeError("Buffer size must be a multiple of 16-bits");
}
for (let i = 0; i < len; i += 2) {
swap(this, i, i + 1);
}
return this;
};
Buffer3.prototype.swap32 = function swap32() {
const len = this.length;
if (len % 4 !== 0) {
throw new RangeError("Buffer size must be a multiple of 32-bits");
}
for (let i = 0; i < len; i += 4) {
swap(this, i, i + 3);
swap(this, i + 1, i + 2);
}
return this;
};
Buffer3.prototype.swap64 = function swap64() {
const len = this.length;
if (len % 8 !== 0) {
throw new RangeError("Buffer size must be a multiple of 64-bits");
}
for (let i = 0; i < len; i += 8) {
swap(this, i, i + 7);
swap(this, i + 1, i + 6);
swap(this, i + 2, i + 5);
swap(this, i + 3, i + 4);
}
return this;
};
Buffer3.prototype.toString = function toString3() {
const length = this.length;
if (length === 0) return "";
if (arguments.length === 0) return utf8Slice(this, 0, length);
return slowToString.apply(this, arguments);
};
Buffer3.prototype.toLocaleString = Buffer3.prototype.toString;
Buffer3.prototype.equals = function equals(b) {
if (!Buffer3.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
if (this === b) return true;
return Buffer3.compare(this, b) === 0;
};
Buffer3.prototype.inspect = function inspect() {
let str = "";
const max2 = exports.INSPECT_MAX_BYTES;
str = this.toString("hex", 0, max2).replace(/(.{2})/g, "$1 ").trim();
if (this.length > max2) str += " ... ";
return "<Buffer " + str + ">";
};
if (customInspectSymbol) {
Buffer3.prototype[customInspectSymbol] = Buffer3.prototype.inspect;
}
Buffer3.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
if (isInstance(target, GlobalUint8Array)) {
target = Buffer3.from(target, target.offset, target.byteLength);
}
if (!Buffer3.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
);
}
if (start === void 0) {
start = 0;
}
if (end === void 0) {
end = target ? target.length : 0;
}
if (thisStart === void 0) {
thisStart = 0;
}
if (thisEnd === void 0) {
thisEnd = this.length;
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError("out of range index");
}
if (thisStart >= thisEnd && start >= end) {
return 0;
}
if (thisStart >= thisEnd) {
return -1;
}
if (start >= end) {
return 1;
}
start >>>= 0;
end >>>= 0;
thisStart >>>= 0;
thisEnd >>>= 0;
if (this === target) return 0;
let x = thisEnd - thisStart;
let y = end - start;
const len = Math.min(x, y);
const thisCopy = this.slice(thisStart, thisEnd);
const targetCopy = target.slice(start, end);
for (let i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i];
y = targetCopy[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) {
if (buffer2.length === 0) return -1;
if (typeof byteOffset === "string") {
encoding = byteOffset;
byteOffset = 0;
} else if (byteOffset > 2147483647) {
byteOffset = 2147483647;
} else if (byteOffset < -2147483648) {
byteOffset = -2147483648;
}
byteOffset = +byteOffset;
if (numberIsNaN(byteOffset)) {
byteOffset = dir ? 0 : buffer2.length - 1;
}
if (byteOffset < 0) byteOffset = buffer2.length + byteOffset;
if (byteOffset >= buffer2.length) {
if (dir) return -1;
else byteOffset = buffer2.length - 1;
} else if (byteOffset < 0) {
if (dir) byteOffset = 0;
else return -1;
}
if (typeof val === "string") {
val = Buffer3.from(val, encoding);
}
if (Buffer3.isBuffer(val)) {
if (val.length === 0) {
return -1;
}
return arrayIndexOf(buffer2, val, byteOffset, encoding, dir);
} else if (typeof val === "number") {
val = val & 255;
if (typeof GlobalUint8Array.prototype.indexOf === "function") {
if (dir) {
return GlobalUint8Array.prototype.indexOf.call(buffer2, val, byteOffset);
} else {
return GlobalUint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset);
}
}
return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir);
}
throw new TypeError("val must be string, number or Buffer");
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
let indexSize = 1;
let arrLength = arr.length;
let valLength = val.length;
if (encoding !== void 0) {
encoding = String(encoding).toLowerCase();
if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
if (arr.length < 2 || val.length < 2) {
return -1;
}
indexSize = 2;
arrLength /= 2;
valLength /= 2;
byteOffset /= 2;
}
}
function read(buf, i2) {
if (indexSize === 1) {
return buf[i2];
} else {
return buf.readUInt16BE(i2 * indexSize);
}
}
let i;
if (dir) {
let foundIndex = -1;
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i;
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
} else {
if (foundIndex !== -1) i -= i - foundIndex;
foundIndex = -1;
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
for (i = byteOffset; i >= 0; i--) {
let found = true;
for (let j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false;
break;
}
}
if (found) return i;
}
}
return -1;
}
Buffer3.prototype.includes = function includes(val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1;
};
Buffer3.prototype.indexOf = function indexOf2(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer3.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
function hexWrite(buf, string, offset, length) {
offset = Number(offset) || 0;
const remaining = buf.length - offset;
if (!length) {
length = remaining;
} else {
length = Number(length);
if (length > remaining) {
length = remaining;
}
}
const strLen = string.length;
if (length > strLen / 2) {
length = strLen / 2;
}
let i;
for (i = 0; i < length; ++i) {
const parsed = parseInt(string.substr(i * 2, 2), 16);
if (numberIsNaN(parsed)) return i;
buf[offset + i] = parsed;
}
return i;
}
function utf8Write(buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function base64Write(buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
Buffer3.prototype.write = function write(string, offset, length, encoding) {
if (offset === void 0) {
encoding = "utf8";
length = this.length;
offset = 0;
} else if (length === void 0 && typeof offset === "string") {
encoding = offset;
length = this.length;
offset = 0;
} else if (isFinite(offset)) {
offset = offset >>> 0;
if (isFinite(length)) {
length = length >>> 0;
if (encoding === void 0) encoding = "utf8";
} else {
encoding = length;
length = void 0;
}
} else {
throw new Error(
"Buffer.write(string, encoding, offset[, length]) is no longer supported"
);
}
const remaining = this.length - offset;
if (length === void 0 || length > remaining) length = remaining;
if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
throw new RangeError("Attempt to write outside buffer bounds");
}
if (!encoding) encoding = "utf8";
let loweredCase = false;
for (; ; ) {
switch (encoding) {
case "hex":
return hexWrite(this, string, offset, length);
case "utf8":
case "utf-8":
return utf8Write(this, string, offset, length);
case "ascii":
case "latin1":
case "binary":
return asciiWrite(this, string, offset, length);
case "base64":
return base64Write(this, string, offset, length);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return ucs2Write(this, string, offset, length);
default:
if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
encoding = ("" + encoding).toLowerCase();
loweredCase = true;
}
}
};
Buffer3.prototype.toJSON = function toJSON2() {
return {
type: "Buffer",
data: Array.prototype.slice.call(this._arr || this, 0)
};
};
function base64Slice(buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf);
} else {
return base64.fromByteArray(buf.slice(start, end));
}
}
function utf8Slice(buf, start, end) {
end = Math.min(buf.length, end);
const res = [];
let i = start;
while (i < end) {
const firstByte = buf[i];
let codePoint = null;
let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
if (i + bytesPerSequence <= end) {
let secondByte, thirdByte, fourthByte, tempCodePoint;
switch (bytesPerSequence) {
case 1:
if (firstByte < 128) {
codePoint = firstByte;
}
break;
case 2:
secondByte = buf[i + 1];
if ((secondByte & 192) === 128) {
tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
if (tempCodePoint > 127) {
codePoint = tempCodePoint;
}
}
break;
case 3:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
codePoint = tempCodePoint;
}
}
break;
case 4:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
fourthByte = buf[i + 3];
if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
codePoint = tempCodePoint;
}
}
}
}
if (codePoint === null) {
codePoint = 65533;
bytesPerSequence = 1;
} else if (codePoint > 65535) {
codePoint -= 65536;
res.push(codePoint >>> 10 & 1023 | 55296);
codePoint = 56320 | codePoint & 1023;
}
res.push(codePoint);
i += bytesPerSequence;
}
return decodeCodePointsArray(res);
}
const MAX_ARGUMENTS_LENGTH = 4096;
function decodeCodePointsArray(codePoints) {
const len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints);
}
let res = "";
let i = 0;
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
);
}
return res;
}
function asciiSlice(buf, start, end) {
let ret = "";
end = Math.min(buf.length, end);
for (let i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 127);
}
return ret;
}
function latin1Slice(buf, start, end) {
let ret = "";
end = Math.min(buf.length, end);
for (let i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i]);
}
return ret;
}
function hexSlice(buf, start, end) {
const len = buf.length;
if (!start || start < 0) start = 0;
if (!end || end < 0 || end > len) end = len;
let out = "";
for (let i = start; i < end; ++i) {
out += hexSliceLookupTable[buf[i]];
}
return out;
}
function utf16leSlice(buf, start, end) {
const bytes = buf.slice(start, end);
let res = "";
for (let i = 0; i < bytes.length - 1; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
}
return res;
}
Buffer3.prototype.slice = function slice(start, end) {
const len = this.length;
start = ~~start;
end = end === void 0 ? len : ~~end;
if (start < 0) {
start += len;
if (start < 0) start = 0;
} else if (start > len) {
start = len;
}
if (end < 0) {
end += len;
if (end < 0) end = 0;
} else if (end > len) {
end = len;
}
if (end < start) end = start;
const newBuf = this.subarray(start, end);
Object.setPrototypeOf(newBuf, Buffer3.prototype);
return newBuf;
};
function checkOffset(offset, ext, length) {
if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
}
Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = function readUIntLE(offset, byteLength3, noAssert) {
offset = offset >>> 0;
byteLength3 = byteLength3 >>> 0;
if (!noAssert) checkOffset(offset, byteLength3, this.length);
let val = this[offset];
let mul = 1;
let i = 0;
while (++i < byteLength3 && (mul *= 256)) {
val += this[offset + i] * mul;
}
return val;
};
Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = function readUIntBE(offset, byteLength3, noAssert) {
offset = offset >>> 0;
byteLength3 = byteLength3 >>> 0;
if (!noAssert) {
checkOffset(offset, byteLength3, this.length);
}
let val = this[offset + --byteLength3];
let mul = 1;
while (byteLength3 > 0 && (mul *= 256)) {
val += this[offset + --byteLength3] * mul;
}
return val;
};
Buffer3.prototype.readUint8 = Buffer3.prototype.readUInt8 = function readUInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
return this[offset];
};
Buffer3.prototype.readUint16LE = Buffer3.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] | this[offset + 1] << 8;
};
Buffer3.prototype.readUint16BE = Buffer3.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] << 8 | this[offset + 1];
};
Buffer3.prototype.readUint32LE = Buffer3.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
};
Buffer3.prototype.readUint32BE = Buffer3.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
};
Buffer3.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
offset = offset >>> 0;
validateNumber(offset, "offset");
const first = this[offset];
const last = this[offset + 7];
if (first === void 0 || last === void 0) {
boundsError(offset, this.length - 8);
}
const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
return BigInt(lo) + (BigInt(hi) << BigInt(32));
});
Buffer3.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
offset = offset >>> 0;
validateNumber(offset, "offset");
const first = this[offset];
const last = this[offset + 7];
if (first === void 0 || last === void 0) {
boundsError(offset, this.length - 8);
}
const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
return (BigInt(hi) << BigInt(32)) + BigInt(lo);
});
Buffer3.prototype.readIntLE = function readIntLE(offset, byteLength3, noAssert) {
offset = offset >>> 0;
byteLength3 = byteLength3 >>> 0;
if (!noAssert) checkOffset(offset, byteLength3, this.length);
let val = this[offset];
let mul = 1;
let i = 0;
while (++i < byteLength3 && (mul *= 256)) {
val += this[offset + i] * mul;
}
mul *= 128;
if (val >= mul) val -= Math.pow(2, 8 * byteLength3);
return val;
};
Buffer3.prototype.readIntBE = function readIntBE(offset, byteLength3, noAssert) {
offset = offset >>> 0;
byteLength3 = byteLength3 >>> 0;
if (!noAssert) checkOffset(offset, byteLength3, this.length);
let i = byteLength3;
let mul = 1;
let val = this[offset + --i];
while (i > 0 && (mul *= 256)) {
val += this[offset + --i] * mul;
}
mul *= 128;
if (val >= mul) val -= Math.pow(2, 8 * byteLength3);
return val;
};
Buffer3.prototype.readInt8 = function readInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
if (!(this[offset] & 128)) return this[offset];
return (255 - this[offset] + 1) * -1;
};
Buffer3.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
const val = this[offset] | this[offset + 1] << 8;
return val & 32768 ? val | 4294901760 : val;
};
Buffer3.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
const val = this[offset + 1] | this[offset] << 8;
return val & 32768 ? val | 4294901760 : val;
};
Buffer3.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
};
Buffer3.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
};
Buffer3.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
offset = offset >>> 0;
validateNumber(offset, "offset");
const first = this[offset];
const last = this[offset + 7];
if (first === void 0 || last === void 0) {
boundsError(offset, this.length - 8);
}
const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
});
Buffer3.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
offset = offset >>> 0;
validateNumber(offset, "offset");
const first = this[offset];
const last = this[offset + 7];
if (first === void 0 || last === void 0) {
boundsError(offset, this.length - 8);
}
const val = (first << 24) + // Overflow
this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
});
Buffer3.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754$1$1.read(this, offset, true, 23, 4);
};
Buffer3.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754$1$1.read(this, offset, false, 23, 4);
};
Buffer3.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754$1$1.read(this, offset, true, 52, 8);
};
Buffer3.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754$1$1.read(this, offset, false, 52, 8);
};
function checkInt(buf, value2, offset, ext, max2, min) {
if (!Buffer3.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
if (value2 > max2 || value2 < min) throw new RangeError('"value" argument is out of bounds');
if (offset + ext > buf.length) throw new RangeError("Index out of range");
}
Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = function writeUIntLE(value2, offset, byteLength3, noAssert) {
value2 = +value2;
offset = offset >>> 0;
byteLength3 = byteLength3 >>> 0;
if (!noAssert) {
const maxBytes = Math.pow(2, 8 * byteLength3) - 1;
checkInt(this, value2, offset, byteLength3, maxBytes, 0);
}
let mul = 1;
let i = 0;
this[offset] = value2 & 255;
while (++i < byteLength3 && (mul *= 256)) {
this[offset + i] = value2 / mul & 255;
}
return offset + byteLength3;
};
Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = function writeUIntBE(value2, offset, byteLength3, noAssert) {
value2 = +value2;
offset = offset >>> 0;
byteLength3 = byteLength3 >>> 0;
if (!noAssert) {
const maxBytes = Math.pow(2, 8 * byteLength3) - 1;
checkInt(this, value2, offset, byteLength3, maxBytes, 0);
}
let i = byteLength3 - 1;
let mul = 1;
this[offset + i] = value2 & 255;
while (--i >= 0 && (mul *= 256)) {
this[offset + i] = value2 / mul & 255;
}
return offset + byteLength3;
};
Buffer3.prototype.writeUint8 = Buffer3.prototype.writeUInt8 = function writeUInt8(value2, offset, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value2, offset, 1, 255, 0);
this[offset] = value2 & 255;
return offset + 1;
};
Buffer3.prototype.writeUint16LE = Buffer3.prototype.writeUInt16LE = function writeUInt16LE(value2, offset, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value2, offset, 2, 65535, 0);
this[offset] = value2 & 255;
this[offset + 1] = value2 >>> 8;
return offset + 2;
};
Buffer3.prototype.writeUint16BE = Buffer3.prototype.writeUInt16BE = function writeUInt16BE(value2, offset, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value2, offset, 2, 65535, 0);
this[offset] = value2 >>> 8;
this[offset + 1] = value2 & 255;
return offset + 2;
};
Buffer3.prototype.writeUint32LE = Buffer3.prototype.writeUInt32LE = function writeUInt32LE(value2, offset, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value2, offset, 4, 4294967295, 0);
this[offset + 3] = value2 >>> 24;
this[offset + 2] = value2 >>> 16;
this[offset + 1] = value2 >>> 8;
this[offset] = value2 & 255;
return offset + 4;
};
Buffer3.prototype.writeUint32BE = Buffer3.prototype.writeUInt32BE = function writeUInt32BE(value2, offset, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value2, offset, 4, 4294967295, 0);
this[offset] = value2 >>> 24;
this[offset + 1] = value2 >>> 16;
this[offset + 2] = value2 >>> 8;
this[offset + 3] = value2 & 255;
return offset + 4;
};
function wrtBigUInt64LE(buf, value2, offset, min, max2) {
checkIntBI(value2, min, max2, buf, offset, 7);
let lo = Number(value2 & BigInt(4294967295));
buf[offset++] = lo;
lo = lo >> 8;
buf[offset++] = lo;
lo = lo >> 8;
buf[offset++] = lo;
lo = lo >> 8;
buf[offset++] = lo;
let hi = Number(value2 >> BigInt(32) & BigInt(4294967295));
buf[offset++] = hi;
hi = hi >> 8;
buf[offset++] = hi;
hi = hi >> 8;
buf[offset++] = hi;
hi = hi >> 8;
buf[offset++] = hi;
return offset;
}
function wrtBigUInt64BE(buf, value2, offset, min, max2) {
checkIntBI(value2, min, max2, buf, offset, 7);
let lo = Number(value2 & BigInt(4294967295));
buf[offset + 7] = lo;
lo = lo >> 8;
buf[offset + 6] = lo;
lo = lo >> 8;
buf[offset + 5] = lo;
lo = lo >> 8;
buf[offset + 4] = lo;
let hi = Number(value2 >> BigInt(32) & BigInt(4294967295));
buf[offset + 3] = hi;
hi = hi >> 8;
buf[offset + 2] = hi;
hi = hi >> 8;
buf[offset + 1] = hi;
hi = hi >> 8;
buf[offset] = hi;
return offset + 8;
}
Buffer3.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value2, offset = 0) {
return wrtBigUInt64LE(this, value2, offset, BigInt(0), BigInt("0xffffffffffffffff"));
});
Buffer3.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value2, offset = 0) {
return wrtBigUInt64BE(this, value2, offset, BigInt(0), BigInt("0xffffffffffffffff"));
});
Buffer3.prototype.writeIntLE = function writeIntLE(value2, offset, byteLength3, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) {
const limit = Math.pow(2, 8 * byteLength3 - 1);
checkInt(this, value2, offset, byteLength3, limit - 1, -limit);
}
let i = 0;
let mul = 1;
let sub = 0;
this[offset] = value2 & 255;
while (++i < byteLength3 && (mul *= 256)) {
if (value2 < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1;
}
this[offset + i] = (value2 / mul >> 0) - sub & 255;
}
return offset + byteLength3;
};
Buffer3.prototype.writeIntBE = function writeIntBE(value2, offset, byteLength3, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) {
const limit = Math.pow(2, 8 * byteLength3 - 1);
checkInt(this, value2, offset, byteLength3, limit - 1, -limit);
}
let i = byteLength3 - 1;
let mul = 1;
let sub = 0;
this[offset + i] = value2 & 255;
while (--i >= 0 && (mul *= 256)) {
if (value2 < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1;
}
this[offset + i] = (value2 / mul >> 0) - sub & 255;
}
return offset + byteLength3;
};
Buffer3.prototype.writeInt8 = function writeInt8(value2, offset, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value2, offset, 1, 127, -128);
if (value2 < 0) value2 = 255 + value2 + 1;
this[offset] = value2 & 255;
return offset + 1;
};
Buffer3.prototype.writeInt16LE = function writeInt16LE(value2, offset, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value2, offset, 2, 32767, -32768);
this[offset] = value2 & 255;
this[offset + 1] = value2 >>> 8;
return offset + 2;
};
Buffer3.prototype.writeInt16BE = function writeInt16BE(value2, offset, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value2, offset, 2, 32767, -32768);
this[offset] = value2 >>> 8;
this[offset + 1] = value2 & 255;
return offset + 2;
};
Buffer3.prototype.writeInt32LE = function writeInt32LE(value2, offset, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value2, offset, 4, 2147483647, -2147483648);
this[offset] = value2 & 255;
this[offset + 1] = value2 >>> 8;
this[offset + 2] = value2 >>> 16;
this[offset + 3] = value2 >>> 24;
return offset + 4;
};
Buffer3.prototype.writeInt32BE = function writeInt32BE(value2, offset, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value2, offset, 4, 2147483647, -2147483648);
if (value2 < 0) value2 = 4294967295 + value2 + 1;
this[offset] = value2 >>> 24;
this[offset + 1] = value2 >>> 16;
this[offset + 2] = value2 >>> 8;
this[offset + 3] = value2 & 255;
return offset + 4;
};
Buffer3.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value2, offset = 0) {
return wrtBigUInt64LE(this, value2, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
});
Buffer3.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value2, offset = 0) {
return wrtBigUInt64BE(this, value2, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
});
function checkIEEE754(buf, value2, offset, ext, max2, min) {
if (offset + ext > buf.length) throw new RangeError("Index out of range");
if (offset < 0) throw new RangeError("Index out of range");
}
function writeFloat(buf, value2, offset, littleEndian, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(buf, value2, offset, 4);
}
ieee754$1$1.write(buf, value2, offset, littleEndian, 23, 4);
return offset + 4;
}
Buffer3.prototype.writeFloatLE = function writeFloatLE(value2, offset, noAssert) {
return writeFloat(this, value2, offset, true, noAssert);
};
Buffer3.prototype.writeFloatBE = function writeFloatBE(value2, offset, noAssert) {
return writeFloat(this, value2, offset, false, noAssert);
};
function writeDouble(buf, value2, offset, littleEndian, noAssert) {
value2 = +value2;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(buf, value2, offset, 8);
}
ieee754$1$1.write(buf, value2, offset, littleEndian, 52, 8);
return offset + 8;
}
Buffer3.prototype.writeDoubleLE = function writeDoubleLE(value2, offset, noAssert) {
return writeDouble(this, value2, offset, true, noAssert);
};
Buffer3.prototype.writeDoubleBE = function writeDoubleBE(value2, offset, noAssert) {
return writeDouble(this, value2, offset, false, noAssert);
};
Buffer3.prototype.copy = function copy(target, targetStart, start, end) {
if (!Buffer3.isBuffer(target)) throw new TypeError("argument should be a Buffer");
if (!start) start = 0;
if (!end && end !== 0) end = this.length;
if (targetStart >= target.length) targetStart = target.length;
if (!targetStart) targetStart = 0;
if (end > 0 && end < start) end = start;
if (end === start) return 0;
if (target.length === 0 || this.length === 0) return 0;
if (targetStart < 0) {
throw new RangeError("targetStart out of bounds");
}
if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
if (end < 0) throw new RangeError("sourceEnd out of bounds");
if (end > this.length) end = this.length;
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start;
}
const len = end - start;
if (this === target && typeof GlobalUint8Array.prototype.copyWithin === "function") {
this.copyWithin(targetStart, start, end);
} else {
GlobalUint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
);
}
return len;
};
Buffer3.prototype.fill = function fill(val, start, end, encoding) {
if (typeof val === "string") {
if (typeof start === "string") {
encoding = start;
start = 0;
end = this.length;
} else if (typeof end === "string") {
encoding = end;
end = this.length;
}
if (encoding !== void 0 && typeof encoding !== "string") {
throw new TypeError("encoding must be a string");
}
if (typeof encoding === "string" && !Buffer3.isEncoding(encoding)) {
throw new TypeError("Unknown encoding: " + encoding);
}
if (val.length === 1) {
const code2 = val.charCodeAt(0);
if (encoding === "utf8" && code2 < 128 || encoding === "latin1") {
val = code2;
}
}
} else if (typeof val === "number") {
val = val & 255;
} else if (typeof val === "boolean") {
val = Number(val);
}
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError("Out of range index");
}
if (end <= start) {
return this;
}
start = start >>> 0;
end = end === void 0 ? this.length : end >>> 0;
if (!val) val = 0;
let i;
if (typeof val === "number") {
for (i = start; i < end; ++i) {
this[i] = val;
}
} else {
const bytes = Buffer3.isBuffer(val) ? val : Buffer3.from(val, encoding);
const len = bytes.length;
if (len === 0) {
throw new TypeError('The value "' + val + '" is invalid for argument "value"');
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len];
}
}
return this;
};
const errors = {};
function E(sym, getMessage, Base) {
errors[sym] = class NodeError extends Base {
constructor() {
super();
Object.defineProperty(this, "message", {
value: getMessage.apply(this, arguments),
writable: true,
configurable: true
});
this.name = `${this.name} [${sym}]`;
this.stack;
delete this.name;
}
get code() {
return sym;
}
set code(value2) {
Object.defineProperty(this, "code", {
configurable: true,
enumerable: true,
value: value2,
writable: true
});
}
toString() {
return `${this.name} [${sym}]: ${this.message}`;
}
};
}
E(
"ERR_BUFFER_OUT_OF_BOUNDS",
function(name) {
if (name) {
return `${name} is outside of buffer bounds`;
}
return "Attempt to access memory outside buffer bounds";
},
RangeError
);
E(
"ERR_INVALID_ARG_TYPE",
function(name, actual) {
return `The "${name}" argument must be of type number. Received type ${typeof actual}`;
},
TypeError
);
E(
"ERR_OUT_OF_RANGE",
function(str, range, input) {
let msg = `The value of "${str}" is out of range.`;
let received = input;
if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
received = addNumericalSeparator(String(input));
} else if (typeof input === "bigint") {
received = String(input);
if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
received = addNumericalSeparator(received);
}
received += "n";
}
msg += ` It must be ${range}. Received ${received}`;
return msg;
},
RangeError
);
function addNumericalSeparator(val) {
let res = "";
let i = val.length;
const start = val[0] === "-" ? 1 : 0;
for (; i >= start + 4; i -= 3) {
res = `_${val.slice(i - 3, i)}${res}`;
}
return `${val.slice(0, i)}${res}`;
}
function checkBounds(buf, offset, byteLength3) {
validateNumber(offset, "offset");
if (buf[offset] === void 0 || buf[offset + byteLength3] === void 0) {
boundsError(offset, buf.length - (byteLength3 + 1));
}
}
function checkIntBI(value2, min, max2, buf, offset, byteLength3) {
if (value2 > max2 || value2 < min) {
const n = typeof min === "bigint" ? "n" : "";
let range;
{
if (min === 0 || min === BigInt(0)) {
range = `>= 0${n} and < 2${n} ** ${(byteLength3 + 1) * 8}${n}`;
} else {
range = `>= -(2${n} ** ${(byteLength3 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength3 + 1) * 8 - 1}${n}`;
}
}
throw new errors.ERR_OUT_OF_RANGE("value", range, value2);
}
checkBounds(buf, offset, byteLength3);
}
function validateNumber(value2, name) {
if (typeof value2 !== "number") {
throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value2);
}
}
function boundsError(value2, length, type) {
if (Math.floor(value2) !== value2) {
validateNumber(value2, type);
throw new errors.ERR_OUT_OF_RANGE("offset", "an integer", value2);
}
if (length < 0) {
throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
}
throw new errors.ERR_OUT_OF_RANGE(
"offset",
`>= ${0} and <= ${length}`,
value2
);
}
const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
function base64clean(str) {
str = str.split("=")[0];
str = str.trim().replace(INVALID_BASE64_RE, "");
if (str.length < 2) return "";
while (str.length % 4 !== 0) {
str = str + "=";
}
return str;
}
function utf8ToBytes(string, units) {
units = units || Infinity;
let codePoint;
const length = string.length;
let leadSurrogate = null;
const bytes = [];
for (let i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i);
if (codePoint > 55295 && codePoint < 57344) {
if (!leadSurrogate) {
if (codePoint > 56319) {
if ((units -= 3) > -1) bytes.push(239, 191, 189);
continue;
} else if (i + 1 === length) {
if ((units -= 3) > -1) bytes.push(239, 191, 189);
continue;
}
leadSurrogate = codePoint;
continue;
}
if (codePoint < 56320) {
if ((units -= 3) > -1) bytes.push(239, 191, 189);
leadSurrogate = codePoint;
continue;
}
codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
} else if (leadSurrogate) {
if ((units -= 3) > -1) bytes.push(239, 191, 189);
}
leadSurrogate = null;
if (codePoint < 128) {
if ((units -= 1) < 0) break;
bytes.push(codePoint);
} else if (codePoint < 2048) {
if ((units -= 2) < 0) break;
bytes.push(
codePoint >> 6 | 192,
codePoint & 63 | 128
);
} else if (codePoint < 65536) {
if ((units -= 3) < 0) break;
bytes.push(
codePoint >> 12 | 224,
codePoint >> 6 & 63 | 128,
codePoint & 63 | 128
);
} else if (codePoint < 1114112) {
if ((units -= 4) < 0) break;
bytes.push(
codePoint >> 18 | 240,
codePoint >> 12 & 63 | 128,
codePoint >> 6 & 63 | 128,
codePoint & 63 | 128
);
} else {
throw new Error("Invalid code point");
}
}
return bytes;
}
function asciiToBytes(str) {
const byteArray = [];
for (let i = 0; i < str.length; ++i) {
byteArray.push(str.charCodeAt(i) & 255);
}
return byteArray;
}
function utf16leToBytes(str, units) {
let c, hi, lo;
const byteArray = [];
for (let i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break;
c = str.charCodeAt(i);
hi = c >> 8;
lo = c % 256;
byteArray.push(lo);
byteArray.push(hi);
}
return byteArray;
}
function base64ToBytes(str) {
return base64.toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset, length) {
let i;
for (i = 0; i < length; ++i) {
if (i + offset >= dst.length || i >= src.length) break;
dst[i + offset] = src[i];
}
return i;
}
function isInstance(obj, type) {
return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
}
function numberIsNaN(obj) {
return obj !== obj;
}
const hexSliceLookupTable = function() {
const alphabet = "0123456789abcdef";
const table = new Array(256);
for (let i = 0; i < 16; ++i) {
const i16 = i * 16;
for (let j = 0; j < 16; ++j) {
table[i16 + j] = alphabet[i] + alphabet[j];
}
}
return table;
}();
function defineBigIntMethod(fn) {
return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
}
function BufferBigIntNotDefined() {
throw new Error("BigInt not supported");
}
})(buffer);
const Buffer2 = buffer.Buffer;
const Buffer$1 = buffer.Buffer;
const global = globalThis || void 0 || self;
function getDefaultExportFromCjs$1(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var browser$1 = { exports: {} };
var process = browser$1.exports = {};
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error("setTimeout has not been defined");
}
function defaultClearTimeout() {
throw new Error("clearTimeout has not been defined");
}
(function() {
try {
if (typeof setTimeout === "function") {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === "function") {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
})();
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
return setTimeout(fun, 0);
}
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
return cachedSetTimeout.call(null, fun, 0);
} catch (e2) {
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
return clearTimeout(marker);
}
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
return cachedClearTimeout(marker);
} catch (e) {
try {
return cachedClearTimeout.call(null, marker);
} catch (e2) {
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function(fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function() {
this.fun.apply(null, this.array);
};
process.title = "browser";
process.browser = true;
process.env = {};
process.argv = [];
process.version = "";
process.versions = {};
function noop$1() {
}
process.on = noop$1;
process.addListener = noop$1;
process.once = noop$1;
process.off = noop$1;
process.removeListener = noop$1;
process.removeAllListeners = noop$1;
process.emit = noop$1;
process.prependListener = noop$1;
process.prependOnceListener = noop$1;
process.listeners = function(name) {
return [];
};
process.binding = function(name) {
throw new Error("process.binding is not supported");
};
process.cwd = function() {
return "/";
};
process.chdir = function(dir) {
throw new Error("process.chdir is not supported");
};
process.umask = function() {
return 0;
};
var browserExports$1 = browser$1.exports;
const process$1 = /* @__PURE__ */ getDefaultExportFromCjs$1(browserExports$1);
function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
}
const { toString: toString$1 } = Object.prototype;
const { getPrototypeOf } = Object;
const { iterator, toStringTag } = Symbol;
const kindOf = /* @__PURE__ */ ((cache2) => (thing) => {
const str = toString$1.call(thing);
return cache2[str] || (cache2[str] = str.slice(8, -1).toLowerCase());
})(/* @__PURE__ */ Object.create(null));
const kindOfTest = (type) => {
type = type.toLowerCase();
return (thing) => kindOf(thing) === type;
};
const typeOfTest = (type) => (thing) => typeof thing === type;
const { isArray } = Array;
const isUndefined = typeOfTest("undefined");
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
const isArrayBuffer = kindOfTest("ArrayBuffer");
function isArrayBufferView(val) {
let result;
if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
result = ArrayBuffer.isView(val);
} else {
result = val && val.buffer && isArrayBuffer(val.buffer);
}
return result;
}
const isString = typeOfTest("string");
const isFunction = typeOfTest("function");
const isNumber = typeOfTest("number");
const isObject$1 = (thing) => thing !== null && typeof thing === "object";
const isBoolean = (thing) => thing === true || thing === false;
const isPlainObject = (val) => {
if (kindOf(val) !== "object") {
return false;
}
const prototype2 = getPrototypeOf(val);
return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
};
const isEmptyObject = (val) => {
if (!isObject$1(val) || isBuffer(val)) {
return false;
}
try {
return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
} catch (e) {
return false;
}
};
const isDate = kindOfTest("Date");
const isFile = kindOfTest("File");
const isBlob = kindOfTest("Blob");
const isFileList = kindOfTest("FileList");
const isStream = (val) => isObject$1(val) && isFunction(val.pipe);
const isFormData = (thing) => {
let kind;
return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]"));
};
const isURLSearchParams = kindOfTest("URLSearchParams");
const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
const trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
function forEach(obj, fn, { allOwnKeys = false } = {}) {
if (obj === null || typeof obj === "undefined") {
return;
}
let i;
let l;
if (typeof obj !== "object") {
obj = [obj];
}
if (isArray(obj)) {
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
if (isBuffer(obj)) {
return;
}
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
function findKey(obj, key) {
if (isBuffer(obj)) {
return null;
}
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
const _global = (() => {
if (typeof globalThis !== "undefined") return globalThis;
return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
})();
const isContextDefined = (context) => !isUndefined(context) && context !== _global;
function merge() {
const { caseless } = isContextDefined(this) && this || {};
const result = {};
const assignValue = (val, key) => {
const targetKey = caseless && findKey(result, key) || key;
if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
result[targetKey] = merge(result[targetKey], val);
} else if (isPlainObject(val)) {
result[targetKey] = merge({}, val);
} else if (isArray(val)) {
result[targetKey] = val.slice();
} else {
result[targetKey] = val;
}
};
for (let i = 0, l = arguments.length; i < l; i++) {
arguments[i] && forEach(arguments[i], assignValue);
}
return result;
}
const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
forEach(b, (val, key) => {
if (thisArg && isFunction(val)) {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
}, { allOwnKeys });
return a;
};
const stripBOM = (content) => {
if (content.charCodeAt(0) === 65279) {
content = content.slice(1);
}
return content;
};
const inherits = (constructor, superConstructor, props, descriptors2) => {
constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
constructor.prototype.constructor = constructor;
Object.defineProperty(constructor, "super", {
value: superConstructor.prototype
});
props && Object.assign(constructor.prototype, props);
};
const toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
const endsWith = (str, searchString, position) => {
str = String(str);
if (position === void 0 || position > str.length) {
position = str.length;
}
position -= searchString.length;
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
const toArray$1 = (thing) => {
if (!thing) return null;
if (isArray(thing)) return thing;
let i = thing.length;
if (!isNumber(i)) return null;
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
const isTypedArray = /* @__PURE__ */ ((TypedArray) => {
return (thing) => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
const forEachEntry = (obj, fn) => {
const generator = obj && obj[iterator];
const _iterator = generator.call(obj);
let result;
while ((result = _iterator.next()) && !result.done) {
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
};
const matchAll = (regExp, str) => {
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
const isHTMLForm = kindOfTest("HTMLFormElement");
const toCamelCase = (str) => {
return str.toLowerCase().replace(
/[-_\s]([a-z\d])(\w*)/g,
function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
}
);
};
const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
const isRegExp = kindOfTest("RegExp");
const reduceDescriptors = (obj, reducer) => {
const descriptors2 = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors2, (descriptor, name) => {
let ret;
if ((ret = reducer(descriptor, name, obj)) !== false) {
reducedDescriptors[name] = ret || descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
const freezeMethods = (obj) => {
reduceDescriptors(obj, (descriptor, name) => {
if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
return false;
}
const value2 = obj[name];
if (!isFunction(value2)) return;
descriptor.enumerable = false;
if ("writable" in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error("Can not rewrite read-only method '" + name + "'");
};
}
});
};
const toObjectSet = (arrayOrString, delimiter) => {
const obj = {};
const define = (arr) => {
arr.forEach((value2) => {
obj[value2] = true;
});
};
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
};
const noop = () => {
};
const toFiniteNumber = (value2, defaultValue) => {
return value2 != null && Number.isFinite(value2 = +value2) ? value2 : defaultValue;
};
function isSpecCompliantForm(thing) {
return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
}
const toJSONObject = (obj) => {
const stack = new Array(10);
const visit = (source, i) => {
if (isObject$1(source)) {
if (stack.indexOf(source) >= 0) {
return;
}
if (isBuffer(source)) {
return source;
}
if (!("toJSON" in source)) {
stack[i] = source;
const target = isArray(source) ? [] : {};
forEach(source, (value2, key) => {
const reducedValue = visit(value2, i + 1);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
stack[i] = void 0;
return target;
}
}
return source;
};
return visit(obj, 0);
};
const isAsyncFn = kindOfTest("AsyncFunction");
const isThenable = (thing) => thing && (isObject$1(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
if (setImmediateSupported) {
return setImmediate;
}
return postMessageSupported ? ((token, callbacks) => {
_global.addEventListener("message", ({ source, data }) => {
if (source === _global && data === token) {
callbacks.length && callbacks.shift()();
}
}, false);
return (cb) => {
callbacks.push(cb);
_global.postMessage(token, "*");
};
})(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
})(
typeof setImmediate === "function",
isFunction(_global.postMessage)
);
const asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process$1 !== "undefined" && process$1.nextTick || _setImmediate;
const isIterable = (thing) => thing != null && isFunction(thing[iterator]);
const utils$1 = {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject: isObject$1,
isPlainObject,
isEmptyObject,
isReadableStream,
isRequest,
isResponse,
isHeaders,
isUndefined,
isDate,
isFile,
isBlob,
isRegExp,
isFunction,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray: toArray$1,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty,
// an alias to avoid ESLint no-prototype-builtins detection
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber,
findKey,
global: _global,
isContextDefined,
isSpecCompliantForm,
toJSONObject,
isAsyncFn,
isThenable,
setImmediate: _setImmediate,
asap,
isIterable
};
function AxiosError$1(message, code2, config, request, response) {
Error.call(this);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error().stack;
}
this.message = message;
this.name = "AxiosError";
code2 && (this.code = code2);
config && (this.config = config);
request && (this.request = request);
if (response) {
this.response = response;
this.status = response.status ? response.status : null;
}
}
utils$1.inherits(AxiosError$1, Error, {
toJSON: function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: utils$1.toJSONObject(this.config),
code: this.code,
status: this.status
};
}
});
const prototype$1 = AxiosError$1.prototype;
const descriptors = {};
[
"ERR_BAD_OPTION_VALUE",
"ERR_BAD_OPTION",
"ECONNABORTED",
"ETIMEDOUT",
"ERR_NETWORK",
"ERR_FR_TOO_MANY_REDIRECTS",
"ERR_DEPRECATED",
"ERR_BAD_RESPONSE",
"ERR_BAD_REQUEST",
"ERR_CANCELED",
"ERR_NOT_SUPPORT",
"ERR_INVALID_URL"
// eslint-disable-next-line func-names
].forEach((code2) => {
descriptors[code2] = { value: code2 };
});
Object.defineProperties(AxiosError$1, descriptors);
Object.defineProperty(prototype$1, "isAxiosError", { value: true });
AxiosError$1.from = (error, code2, config, request, response, customProps) => {
const axiosError = Object.create(prototype$1);
utils$1.toFlatObject(error, axiosError, function filter2(obj) {
return obj !== Error.prototype;
}, (prop) => {
return prop !== "isAxiosError";
});
AxiosError$1.call(axiosError, error.message, code2, config, request, response);
axiosError.cause = error;
axiosError.name = error.name;
customProps && Object.assign(axiosError, customProps);
return axiosError;
};
const httpAdapter = null;
function isVisitable(thing) {
return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
}
function removeBrackets(key) {
return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key;
}
function renderKey(path, key, dots) {
if (!path) return key;
return path.concat(key).map(function each(token, i) {
token = removeBrackets(token);
return !dots && i ? "[" + token + "]" : token;
}).join(dots ? "." : "");
}
function isFlatArray(arr) {
return utils$1.isArray(arr) && !arr.some(isVisitable);
}
const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
function toFormData$1(obj, formData, options) {
if (!utils$1.isObject(obj)) {
throw new TypeError("target must be an object");
}
formData = formData || new FormData();
options = utils$1.toFlatObject(options, {
metaTokens: true,
dots: false,
indexes: false
}, false, function defined(option, source) {
return !utils$1.isUndefined(source[option]);
});
const metaTokens = options.metaTokens;
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
if (!utils$1.isFunction(visitor)) {
throw new TypeError("visitor must be a function");
}
function convertValue(value2) {
if (value2 === null) return "";
if (utils$1.isDate(value2)) {
return value2.toISOString();
}
if (utils$1.isBoolean(value2)) {
return value2.toString();
}
if (!useBlob && utils$1.isBlob(value2)) {
throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");
}
if (utils$1.isArrayBuffer(value2) || utils$1.isTypedArray(value2)) {
return useBlob && typeof Blob === "function" ? new Blob([value2]) : Buffer2.from(value2);
}
return value2;
}
function defaultVisitor(value2, key, path) {
let arr = value2;
if (value2 && !path && typeof value2 === "object") {
if (utils$1.endsWith(key, "{}")) {
key = metaTokens ? key : key.slice(0, -2);
value2 = JSON.stringify(value2);
} else if (utils$1.isArray(value2) && isFlatArray(value2) || (utils$1.isFileList(value2) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value2))) {
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils$1.isUndefined(el) || el === null) && formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]",
convertValue(el)
);
});
return false;
}
}
if (isVisitable(value2)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value2));
return false;
}
const stack = [];
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable
});
function build(value2, path) {
if (utils$1.isUndefined(value2)) return;
if (stack.indexOf(value2) !== -1) {
throw Error("Circular reference detected in " + path.join("."));
}
stack.push(value2);
utils$1.forEach(value2, function each(el, key) {
const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
formData,
el,
utils$1.isString(key) ? key.trim() : key,
path,
exposedHelpers
);
if (result === true) {
build(el, path ? path.concat(key) : [key]);
}
});
stack.pop();
}
if (!utils$1.isObject(obj)) {
throw new TypeError("data must be an object");
}
build(obj);
return formData;
}
function encode$2(str) {
const charMap = {
"!": "%21",
"'": "%27",
"(": "%28",
")": "%29",
"~": "%7E",
"%20": "+",
"%00": "\0"
};
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
return charMap[match];
});
}
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData$1(params, this, options);
}
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value2) {
this._pairs.push([name, value2]);
};
prototype.toString = function toString(encoder) {
const _encode = encoder ? function(value2) {
return encoder.call(this, value2, encode$2);
} : encode$2;
return this._pairs.map(function each(pair) {
return _encode(pair[0]) + "=" + _encode(pair[1]);
}, "").join("&");
};
function encode$1(val) {
return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
}
function buildURL(url2, params, options) {
if (!params) {
return url2;
}
const _encode = options && options.encode || encode$1;
if (utils$1.isFunction(options)) {
options = {
serialize: options
};
}
const serializeFn = options && options.serialize;
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, options);
} else {
serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url2.indexOf("#");
if (hashmarkIndex !== -1) {
url2 = url2.slice(0, hashmarkIndex);
}
url2 += (url2.indexOf("?") === -1 ? "?" : "&") + serializedParams;
}
return url2;
}
class InterceptorManager {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
utils$1.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}
const transitionalDefaults = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
};
const URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams;
const FormData$1 = typeof FormData !== "undefined" ? FormData : null;
const Blob$1 = typeof Blob !== "undefined" ? Blob : null;
const platform$1 = {
isBrowser: true,
classes: {
URLSearchParams: URLSearchParams$1,
FormData: FormData$1,
Blob: Blob$1
},
protocols: ["http", "https", "file", "blob", "url", "data"]
};
const hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
const _navigator = typeof navigator === "object" && navigator || void 0;
const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
const hasStandardBrowserWebWorkerEnv = (() => {
return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
})();
const origin = hasBrowserEnv && window.location.href || "http://localhost";
const utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
hasBrowserEnv,
hasStandardBrowserEnv,
hasStandardBrowserWebWorkerEnv,
navigator: _navigator,
origin
}, Symbol.toStringTag, { value: "Module" }));
const platform = {
...utils,
...platform$1
};
function toURLEncodedForm(data, options) {
return toFormData$1(data, new platform.classes.URLSearchParams(), {
visitor: function(value2, key, path, helpers) {
if (platform.isNode && utils$1.isBuffer(value2)) {
this.append(key, value2.toString("base64"));
return false;
}
return helpers.defaultVisitor.apply(this, arguments);
},
...options
});
}
function parsePropPath(name) {
return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
return match[0] === "[]" ? "" : match[1] || match[0];
});
}
function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
function formDataToJSON(formData) {
function buildPath(path, value2, target, index) {
let name = path[index++];
if (name === "__proto__") return true;
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils$1.isArray(target) ? target.length : name;
if (isLast) {
if (utils$1.hasOwnProp(target, name)) {
target[name] = [target[name], value2];
} else {
target[name] = value2;
}
return !isNumericKey;
}
if (!target[name] || !utils$1.isObject(target[name])) {
target[name] = [];
}
const result = buildPath(path, value2, target[name], index);
if (result && utils$1.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
const obj = {};
utils$1.forEachEntry(formData, (name, value2) => {
buildPath(parsePropPath(name), value2, obj, 0);
});
return obj;
}
return null;
}
function stringifySafely(rawValue, parser2, encoder) {
if (utils$1.isString(rawValue)) {
try {
(parser2 || JSON.parse)(rawValue);
return utils$1.trim(rawValue);
} catch (e) {
if (e.name !== "SyntaxError") {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
const defaults = {
transitional: transitionalDefaults,
adapter: ["xhr", "http", "fetch"],
transformRequest: [function transformRequest(data, headers) {
const contentType = headers.getContentType() || "";
const hasJSONContentType = contentType.indexOf("application/json") > -1;
const isObjectPayload = utils$1.isObject(data);
if (isObjectPayload && utils$1.isHTMLForm(data)) {
data = new FormData(data);
}
const isFormData2 = utils$1.isFormData(data);
if (isFormData2) {
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
}
if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
return data;
}
if (utils$1.isArrayBufferView(data)) {
return data.buffer;
}
if (utils$1.isURLSearchParams(data)) {
headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
return data.toString();
}
let isFileList2;
if (isObjectPayload) {
if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
return toURLEncodedForm(data, this.formSerializer).toString();
}
if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
const _FormData = this.env && this.env.FormData;
return toFormData$1(
isFileList2 ? { "files[]": data } : data,
_FormData && new _FormData(),
this.formSerializer
);
}
}
if (isObjectPayload || hasJSONContentType) {
headers.setContentType("application/json", false);
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
const transitional2 = this.transitional || defaults.transitional;
const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
const JSONRequested = this.responseType === "json";
if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
return data;
}
if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data);
} catch (e) {
if (strictJSONParsing) {
if (e.name === "SyntaxError") {
throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: "XSRF-TOKEN",
xsrfHeaderName: "X-XSRF-TOKEN",
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: platform.classes.FormData,
Blob: platform.classes.Blob
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
"Accept": "application/json, text/plain, */*",
"Content-Type": void 0
}
}
};
utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
defaults.headers[method] = {};
});
const ignoreDuplicateOf = utils$1.toObjectSet([
"age",
"authorization",
"content-length",
"content-type",
"etag",
"expires",
"from",
"host",
"if-modified-since",
"if-unmodified-since",
"last-modified",
"location",
"max-forwards",
"proxy-authorization",
"referer",
"retry-after",
"user-agent"
]);
const parseHeaders = (rawHeaders) => {
const parsed = {};
let key;
let val;
let i;
rawHeaders && rawHeaders.split("\n").forEach(function parser2(line) {
i = line.indexOf(":");
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || parsed[key] && ignoreDuplicateOf[key]) {
return;
}
if (key === "set-cookie") {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
}
});
return parsed;
};
const $internals = Symbol("internals");
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value2) {
if (value2 === false || value2 == null) {
return value2;
}
return utils$1.isArray(value2) ? value2.map(normalizeValue) : String(value2);
}
function parseTokens(str) {
const tokens = /* @__PURE__ */ Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while (match = tokensRE.exec(str)) {
tokens[match[1]] = match[2];
}
return tokens;
}
const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
function matchHeaderValue(context, value2, header, filter2, isHeaderNameFilter) {
if (utils$1.isFunction(filter2)) {
return filter2.call(this, value2, header);
}
if (isHeaderNameFilter) {
value2 = header;
}
if (!utils$1.isString(value2)) return;
if (utils$1.isString(filter2)) {
return value2.indexOf(filter2) !== -1;
}
if (utils$1.isRegExp(filter2)) {
return filter2.test(value2);
}
}
function formatHeader(header) {
return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils$1.toCamelCase(" " + header);
["get", "set", "has"].forEach((methodName) => {
Object.defineProperty(obj, methodName + accessorName, {
value: function(arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true
});
});
}
let AxiosHeaders$1 = class AxiosHeaders {
constructor(headers) {
headers && this.set(headers);
}
set(header, valueOrRewrite, rewrite) {
const self2 = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
throw new Error("header name must be a non-empty string");
}
const key = utils$1.findKey(self2, lHeader);
if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
self2[key || _header] = normalizeValue(_value);
}
}
const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite);
} else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
let obj = {}, dest, key;
for (const entry of header) {
if (!utils$1.isArray(entry)) {
throw TypeError("Object iterator must return a key-value pair");
}
obj[key = entry[0]] = (dest = obj[key]) ? utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
}
setHeaders(obj, valueOrRewrite);
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
get(header, parser2) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
if (key) {
const value2 = this[key];
if (!parser2) {
return value2;
}
if (parser2 === true) {
return parseTokens(value2);
}
if (utils$1.isFunction(parser2)) {
return parser2.call(this, value2, key);
}
if (utils$1.isRegExp(parser2)) {
return parser2.exec(value2);
}
throw new TypeError("parser must be boolean|regexp|function");
}
}
}
has(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
}
return false;
}
delete(header, matcher) {
const self2 = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = utils$1.findKey(self2, _header);
if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
delete self2[key];
deleted = true;
}
}
}
if (utils$1.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;
while (i--) {
const key = keys[i];
if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
normalize(format) {
const self2 = this;
const headers = {};
utils$1.forEach(this, (value2, header) => {
const key = utils$1.findKey(headers, header);
if (key) {
self2[key] = normalizeValue(value2);
delete self2[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self2[header];
}
self2[normalized] = normalizeValue(value2);
headers[normalized] = true;
});
return this;
}
concat(...targets) {
return this.constructor.concat(this, ...targets);
}
toJSON(asStrings) {
const obj = /* @__PURE__ */ Object.create(null);
utils$1.forEach(this, (value2, header) => {
value2 != null && value2 !== false && (obj[header] = asStrings && utils$1.isArray(value2) ? value2.join(", ") : value2);
});
return obj;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON()).map(([header, value2]) => header + ": " + value2).join("\n");
}
getSetCookie() {
return this.get("set-cookie") || [];
}
get [Symbol.toStringTag]() {
return "AxiosHeaders";
}
static from(thing) {
return thing instanceof this ? thing : new this(thing);
}
static concat(first, ...targets) {
const computed = new this(first);
targets.forEach((target) => computed.set(target));
return computed;
}
static accessor(header) {
const internals = this[$internals] = this[$internals] = {
accessors: {}
};
const accessors = internals.accessors;
const prototype2 = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype2, _header);
accessors[lHeader] = true;
}
}
utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
};
AxiosHeaders$1.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({ value: value2 }, key) => {
let mapped = key[0].toUpperCase() + key.slice(1);
return {
get: () => value2,
set(headerValue) {
this[mapped] = headerValue;
}
};
});
utils$1.freezeMethods(AxiosHeaders$1);
function transformData(fns, response) {
const config = this || defaults;
const context = response || config;
const headers = AxiosHeaders$1.from(context.headers);
let data = context.data;
utils$1.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : void 0);
});
headers.normalize();
return data;
}
function isCancel$1(value2) {
return !!(value2 && value2.__CANCEL__);
}
function CanceledError$1(message, config, request) {
AxiosError$1.call(this, message == null ? "canceled" : message, AxiosError$1.ERR_CANCELED, config, request);
this.name = "CanceledError";
}
utils$1.inherits(CanceledError$1, AxiosError$1, {
__CANCEL__: true
});
function settle(resolve, reject, response) {
const validateStatus2 = response.config.validateStatus;
if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
resolve(response);
} else {
reject(new AxiosError$1(
"Request failed with status code " + response.status,
[AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
response.config,
response.request,
response
));
}
}
function parseProtocol(url2) {
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url2);
return match && match[1] || "";
}
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== void 0 ? min : 1e3;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
};
}
function throttle(fn, freq) {
let timestamp = 0;
let threshold = 1e3 / freq;
let lastArgs;
let timer;
const invoke = (args, now = Date.now()) => {
timestamp = now;
lastArgs = null;
if (timer) {
clearTimeout(timer);
timer = null;
}
fn(...args);
};
const throttled = (...args) => {
const now = Date.now();
const passed = now - timestamp;
if (passed >= threshold) {
invoke(args, now);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
timer = null;
invoke(lastArgs);
}, threshold - passed);
}
}
};
const flush = () => lastArgs && invoke(lastArgs);
return [throttled, flush];
}
const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return throttle((e) => {
const loaded = e.loaded;
const total = e.lengthComputable ? e.total : void 0;
const progressBytes = loaded - bytesNotified;
const rate = _speedometer(progressBytes);
const inRange = loaded <= total;
bytesNotified = loaded;
const data = {
loaded,
total,
progress: total ? loaded / total : void 0,
bytes: progressBytes,
rate: rate ? rate : void 0,
estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
event: e,
lengthComputable: total != null,
[isDownloadStream ? "download" : "upload"]: true
};
listener(data);
}, freq);
};
const progressEventDecorator = (total, throttled) => {
const lengthComputable = total != null;
return [(loaded) => throttled[0]({
lengthComputable,
total,
loaded
}), throttled[1]];
};
const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url2) => {
url2 = new URL(url2, platform.origin);
return origin2.protocol === url2.protocol && origin2.host === url2.host && (isMSIE || origin2.port === url2.port);
})(
new URL(platform.origin),
platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
) : () => true;
const cookies = platform.hasStandardBrowserEnv ? (
// Standard browser envs support document.cookie
{
write(name, value2, expires, path, domain, secure) {
const cookie = [name + "=" + encodeURIComponent(value2)];
utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
utils$1.isString(path) && cookie.push("path=" + path);
utils$1.isString(domain) && cookie.push("domain=" + domain);
secure === true && cookie.push("secure");
document.cookie = cookie.join("; ");
},
read(name) {
const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
return match ? decodeURIComponent(match[3]) : null;
},
remove(name) {
this.write(name, "", Date.now() - 864e5);
}
}
) : (
// Non-standard browser env (web workers, react-native) lack needed support.
{
write() {
},
read() {
return null;
},
remove() {
}
}
);
function isAbsoluteURL(url2) {
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url2);
}
function combineURLs(baseURL, relativeURL) {
return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
}
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
let isRelativeUrl = !isAbsoluteURL(requestedURL);
if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
function mergeConfig$1(config1, config2) {
config2 = config2 || {};
const config = {};
function getMergedValue(target, source, prop, caseless) {
if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
return utils$1.merge.call({ caseless }, target, source);
} else if (utils$1.isPlainObject(source)) {
return utils$1.merge({}, source);
} else if (utils$1.isArray(source)) {
return source.slice();
}
return source;
}
function mergeDeepProperties(a, b, prop, caseless) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(a, b, prop, caseless);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(void 0, a, prop, caseless);
}
}
function valueFromConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(void 0, b);
}
}
function defaultToConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(void 0, b);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(void 0, a);
}
}
function mergeDirectKeys(a, b, prop) {
if (prop in config2) {
return getMergedValue(a, b);
} else if (prop in config1) {
return getMergedValue(void 0, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
};
utils$1.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
const merge2 = mergeMap[prop] || mergeDeepProperties;
const configValue = merge2(config1[prop], config2[prop], prop);
utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue);
});
return config;
}
const resolveConfig = (config) => {
const newConfig = mergeConfig$1({}, config);
let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
newConfig.headers = headers = AxiosHeaders$1.from(headers);
newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
if (auth) {
headers.set(
"Authorization",
"Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : ""))
);
}
let contentType;
if (utils$1.isFormData(data)) {
if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
headers.setContentType(void 0);
} else if ((contentType = headers.getContentType()) !== false) {
const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : [];
headers.setContentType([type || "multipart/form-data", ...tokens].join("; "));
}
}
if (platform.hasStandardBrowserEnv) {
withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) {
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
};
const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
const xhrAdapter = isXHRAdapterSupported && function(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
const _config = resolveConfig(config);
let requestData = _config.data;
const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
let { responseType, onUploadProgress, onDownloadProgress } = _config;
let onCanceled;
let uploadThrottled, downloadThrottled;
let flushUpload, flushDownload;
function done() {
flushUpload && flushUpload();
flushDownload && flushDownload();
_config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
_config.signal && _config.signal.removeEventListener("abort", onCanceled);
}
let request = new XMLHttpRequest();
request.open(_config.method.toUpperCase(), _config.url, true);
request.timeout = _config.timeout;
function onloadend() {
if (!request) {
return;
}
const responseHeaders = AxiosHeaders$1.from(
"getAllResponseHeaders" in request && request.getAllResponseHeaders()
);
const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request
};
settle(function _resolve(value2) {
resolve(value2);
done();
}, function _reject(err2) {
reject(err2);
done();
}, response);
request = null;
}
if ("onloadend" in request) {
request.onloadend = onloadend;
} else {
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
return;
}
setTimeout(onloadend);
};
}
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError$1("Request aborted", AxiosError$1.ECONNABORTED, config, request));
request = null;
};
request.onerror = function handleError() {
reject(new AxiosError$1("Network Error", AxiosError$1.ERR_NETWORK, config, request));
request = null;
};
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
const transitional2 = _config.transitional || transitionalDefaults;
if (_config.timeoutErrorMessage) {
timeoutErrorMessage = _config.timeoutErrorMessage;
}
reject(new AxiosError$1(
timeoutErrorMessage,
transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
config,
request
));
request = null;
};
requestData === void 0 && requestHeaders.setContentType(null);
if ("setRequestHeader" in request) {
utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
if (!utils$1.isUndefined(_config.withCredentials)) {
request.withCredentials = !!_config.withCredentials;
}
if (responseType && responseType !== "json") {
request.responseType = _config.responseType;
}
if (onDownloadProgress) {
[downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
request.addEventListener("progress", downloadThrottled);
}
if (onUploadProgress && request.upload) {
[uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
request.upload.addEventListener("progress", uploadThrottled);
request.upload.addEventListener("loadend", flushUpload);
}
if (_config.cancelToken || _config.signal) {
onCanceled = (cancel) => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel);
request.abort();
request = null;
};
_config.cancelToken && _config.cancelToken.subscribe(onCanceled);
if (_config.signal) {
_config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
}
}
const protocol2 = parseProtocol(_config.url);
if (protocol2 && platform.protocols.indexOf(protocol2) === -1) {
reject(new AxiosError$1("Unsupported protocol " + protocol2 + ":", AxiosError$1.ERR_BAD_REQUEST, config));
return;
}
request.send(requestData || null);
});
};
const composeSignals = (signals, timeout) => {
const { length } = signals = signals ? signals.filter(Boolean) : [];
if (timeout || length) {
let controller = new AbortController();
let aborted;
const onabort = function(reason) {
if (!aborted) {
aborted = true;
unsubscribe();
const err2 = reason instanceof Error ? reason : this.reason;
controller.abort(err2 instanceof AxiosError$1 ? err2 : new CanceledError$1(err2 instanceof Error ? err2.message : err2));
}
};
let timer = timeout && setTimeout(() => {
timer = null;
onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT));
}, timeout);
const unsubscribe = () => {
if (signals) {
timer && clearTimeout(timer);
timer = null;
signals.forEach((signal2) => {
signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
});
signals = null;
}
};
signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
const { signal } = controller;
signal.unsubscribe = () => utils$1.asap(unsubscribe);
return signal;
}
};
const streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
if (len < chunkSize) {
yield chunk;
return;
}
let pos = 0;
let end;
while (pos < len) {
end = pos + chunkSize;
yield chunk.slice(pos, end);
pos = end;
}
};
const readBytes = async function* (iterable, chunkSize) {
for await (const chunk of readStream(iterable)) {
yield* streamChunk(chunk, chunkSize);
}
};
const readStream = async function* (stream) {
if (stream[Symbol.asyncIterator]) {
yield* stream;
return;
}
const reader = stream.getReader();
try {
for (; ; ) {
const { done, value: value2 } = await reader.read();
if (done) {
break;
}
yield value2;
}
} finally {
await reader.cancel();
}
};
const trackStream = (stream, chunkSize, onProgress, onFinish) => {
const iterator2 = readBytes(stream, chunkSize);
let bytes = 0;
let done;
let _onFinish = (e) => {
if (!done) {
done = true;
onFinish && onFinish(e);
}
};
return new ReadableStream({
async pull(controller) {
try {
const { done: done2, value: value2 } = await iterator2.next();
if (done2) {
_onFinish();
controller.close();
return;
}
let len = value2.byteLength;
if (onProgress) {
let loadedBytes = bytes += len;
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value2));
} catch (err2) {
_onFinish(err2);
throw err2;
}
},
cancel(reason) {
_onFinish(reason);
return iterator2.return();
}
}, {
highWaterMark: 2
});
};
const isFetchSupported = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function";
const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === "function";
const encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Response(str).arrayBuffer()));
const test = (fn, ...args) => {
try {
return !!fn(...args);
} catch (e) {
return false;
}
};
const supportsRequestStream = isReadableStreamSupported && test(() => {
let duplexAccessed = false;
const hasContentType = new Request(platform.origin, {
body: new ReadableStream(),
method: "POST",
get duplex() {
duplexAccessed = true;
return "half";
}
}).headers.has("Content-Type");
return duplexAccessed && !hasContentType;
});
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const supportsResponseStream = isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response("").body));
const resolvers = {
stream: supportsResponseStream && ((res) => res.body)
};
isFetchSupported && ((res) => {
["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
!resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res2) => res2[type]() : (_, config) => {
throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config);
});
});
})(new Response());
const getBodyLength = async (body) => {
if (body == null) {
return 0;
}
if (utils$1.isBlob(body)) {
return body.size;
}
if (utils$1.isSpecCompliantForm(body)) {
const _request = new Request(platform.origin, {
method: "POST",
body
});
return (await _request.arrayBuffer()).byteLength;
}
if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
return body.byteLength;
}
if (utils$1.isURLSearchParams(body)) {
body = body + "";
}
if (utils$1.isString(body)) {
return (await encodeText(body)).byteLength;
}
};
const resolveBodyLength = async (headers, body) => {
const length = utils$1.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
};
const fetchAdapter = isFetchSupported && (async (config) => {
let {
url: url2,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = "same-origin",
fetchOptions
} = resolveConfig(config);
responseType = responseType ? (responseType + "").toLowerCase() : "text";
let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
let request;
const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
composedSignal.unsubscribe();
});
let requestContentLength;
try {
if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
let _request = new Request(url2, {
method: "POST",
body: data,
duplex: "half"
});
let contentTypeHeader;
if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
headers.setContentType(contentTypeHeader);
}
if (_request.body) {
const [onProgress, flush] = progressEventDecorator(
requestContentLength,
progressEventReducer(asyncDecorator(onUploadProgress))
);
data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
}
}
if (!utils$1.isString(withCredentials)) {
withCredentials = withCredentials ? "include" : "omit";
}
const isCredentialsSupported = "credentials" in Request.prototype;
request = new Request(url2, {
...fetchOptions,
signal: composedSignal,
method: method.toUpperCase(),
headers: headers.normalize().toJSON(),
body: data,
duplex: "half",
credentials: isCredentialsSupported ? withCredentials : void 0
});
let response = await fetch(request, fetchOptions);
const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
const options = {};
["status", "statusText", "headers"].forEach((prop) => {
options[prop] = response[prop];
});
const responseContentLength = utils$1.toFiniteNumber(response.headers.get("content-length"));
const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
responseContentLength,
progressEventReducer(asyncDecorator(onDownloadProgress), true)
) || [];
response = new Response(
trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
flush && flush();
unsubscribe && unsubscribe();
}),
options
);
}
responseType = responseType || "text";
let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || "text"](response, config);
!isStreamResponse && unsubscribe && unsubscribe();
return await new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders$1.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request
});
});
} catch (err2) {
unsubscribe && unsubscribe();
if (err2 && err2.name === "TypeError" && /Load failed|fetch/i.test(err2.message)) {
throw Object.assign(
new AxiosError$1("Network Error", AxiosError$1.ERR_NETWORK, config, request),
{
cause: err2.cause || err2
}
);
}
throw AxiosError$1.from(err2, err2 && err2.code, config, request);
}
});
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter,
fetch: fetchAdapter
};
utils$1.forEach(knownAdapters, (fn, value2) => {
if (fn) {
try {
Object.defineProperty(fn, "name", { value: value2 });
} catch (e) {
}
Object.defineProperty(fn, "adapterName", { value: value2 });
}
});
const renderReason = (reason) => `- ${reason}`;
const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
const adapters = {
getAdapter: (adapters2) => {
adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2];
const { length } = adapters2;
let nameOrAdapter;
let adapter;
const rejectedReasons = {};
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters2[i];
let id;
adapter = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter === void 0) {
throw new AxiosError$1(`Unknown adapter '${id}'`);
}
}
if (adapter) {
break;
}
rejectedReasons[id || "#" + i] = adapter;
}
if (!adapter) {
const reasons = Object.entries(rejectedReasons).map(
([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
);
let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
throw new AxiosError$1(
`There is no suitable adapter to dispatch the request ` + s,
"ERR_NOT_SUPPORT"
);
}
return adapter;
},
adapters: knownAdapters
};
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError$1(null, config);
}
}
function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders$1.from(config.headers);
config.data = transformData.call(
config,
config.transformRequest
);
if (["post", "put", "patch"].indexOf(config.method) !== -1) {
config.headers.setContentType("application/x-www-form-urlencoded", false);
}
const adapter = adapters.getAdapter(config.adapter || defaults.adapter);
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
response.data = transformData.call(
config,
config.transformResponse,
response
);
response.headers = AxiosHeaders$1.from(response.headers);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel$1(reason)) {
throwIfCancellationRequested(config);
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
config.transformResponse,
reason.response
);
reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
}
}
return Promise.reject(reason);
});
}
const VERSION$1 = "1.11.0";
const validators$1 = {};
["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
validators$1[type] = function validator2(thing) {
return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type;
};
});
const deprecatedWarnings = {};
validators$1.transitional = function transitional(validator2, version, message) {
function formatMessage(opt, desc) {
return "[Axios v" + VERSION$1 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
}
return (value2, opt, opts) => {
if (validator2 === false) {
throw new AxiosError$1(
formatMessage(opt, " has been removed" + (version ? " in " + version : "")),
AxiosError$1.ERR_DEPRECATED
);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
console.warn(
formatMessage(
opt,
" has been deprecated since v" + version + " and will be removed in the near future"
)
);
}
return validator2 ? validator2(value2, opt, opts) : true;
};
};
validators$1.spelling = function spelling(correctSpelling) {
return (value2, opt) => {
console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
return true;
};
};
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== "object") {
throw new AxiosError$1("options must be an object", AxiosError$1.ERR_BAD_OPTION_VALUE);
}
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
const opt = keys[i];
const validator2 = schema[opt];
if (validator2) {
const value2 = options[opt];
const result = value2 === void 0 || validator2(value2, opt, options);
if (result !== true) {
throw new AxiosError$1("option " + opt + " must be " + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError$1("Unknown option " + opt, AxiosError$1.ERR_BAD_OPTION);
}
}
}
const validator = {
assertOptions,
validators: validators$1
};
const validators = validator.validators;
let Axios$1 = class Axios {
constructor(instanceConfig) {
this.defaults = instanceConfig || {};
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
async request(configOrUrl, config) {
try {
return await this._request(configOrUrl, config);
} catch (err2) {
if (err2 instanceof Error) {
let dummy = {};
Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
try {
if (!err2.stack) {
err2.stack = stack;
} else if (stack && !String(err2.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
err2.stack += "\n" + stack;
}
} catch (e) {
}
}
throw err2;
}
}
_request(configOrUrl, config) {
if (typeof configOrUrl === "string") {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig$1(this.defaults, config);
const { transitional: transitional2, paramsSerializer, headers } = config;
if (transitional2 !== void 0) {
validator.assertOptions(transitional2, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
}, false);
}
if (paramsSerializer != null) {
if (utils$1.isFunction(paramsSerializer)) {
config.paramsSerializer = {
serialize: paramsSerializer
};
} else {
validator.assertOptions(paramsSerializer, {
encode: validators.function,
serialize: validators.function
}, true);
}
}
if (config.allowAbsoluteUrls !== void 0) ;
else if (this.defaults.allowAbsoluteUrls !== void 0) {
config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
} else {
config.allowAbsoluteUrls = true;
}
validator.assertOptions(config, {
baseUrl: validators.spelling("baseURL"),
withXsrfToken: validators.spelling("withXSRFToken")
}, true);
config.method = (config.method || this.defaults.method || "get").toLowerCase();
let contextHeaders = headers && utils$1.merge(
headers.common,
headers[config.method]
);
headers && utils$1.forEach(
["delete", "get", "head", "post", "put", "patch", "common"],
(method) => {
delete headers[method];
}
);
config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), void 0];
chain.unshift(...requestInterceptorChain);
chain.push(...responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
i = 0;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
getUri(config) {
config = mergeConfig$1(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
};
utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
Axios$1.prototype[method] = function(url2, config) {
return this.request(mergeConfig$1(config || {}, {
method,
url: url2,
data: (config || {}).data
}));
};
});
utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
function generateHTTPMethod(isForm) {
return function httpMethod(url2, data, config) {
return this.request(mergeConfig$1(config || {}, {
method,
headers: isForm ? {
"Content-Type": "multipart/form-data"
} : {},
url: url2,
data
}));
};
}
Axios$1.prototype[method] = generateHTTPMethod();
Axios$1.prototype[method + "Form"] = generateHTTPMethod(true);
});
let CancelToken$1 = class CancelToken {
constructor(executor) {
if (typeof executor !== "function") {
throw new TypeError("executor must be a function.");
}
let resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
this.promise.then((cancel) => {
if (!token._listeners) return;
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
this.promise.then = (onfulfilled) => {
let _resolve;
const promise = new Promise((resolve) => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
return;
}
token.reason = new CanceledError$1(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
toAbortSignal() {
const controller = new AbortController();
const abort = (err2) => {
controller.abort(err2);
};
this.subscribe(abort);
controller.signal.unsubscribe = () => this.unsubscribe(abort);
return controller.signal;
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel
};
}
};
function spread$1(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
}
function isAxiosError$1(payload) {
return utils$1.isObject(payload) && payload.isAxiosError === true;
}
const HttpStatusCode$1 = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511
};
Object.entries(HttpStatusCode$1).forEach(([key, value2]) => {
HttpStatusCode$1[value2] = key;
});
function createInstance(defaultConfig) {
const context = new Axios$1(defaultConfig);
const instance = bind(Axios$1.prototype.request, context);
utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true });
utils$1.extend(instance, context, null, { allOwnKeys: true });
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
};
return instance;
}
const axios = createInstance(defaults);
axios.Axios = Axios$1;
axios.CanceledError = CanceledError$1;
axios.CancelToken = CancelToken$1;
axios.isCancel = isCancel$1;
axios.VERSION = VERSION$1;
axios.toFormData = toFormData$1;
axios.AxiosError = AxiosError$1;
axios.Cancel = axios.CanceledError;
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread$1;
axios.isAxiosError = isAxiosError$1;
axios.mergeConfig = mergeConfig$1;
axios.AxiosHeaders = AxiosHeaders$1;
axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode$1;
axios.default = axios;
const {
Axios: Axios2,
AxiosError,
CanceledError,
isCancel,
CancelToken: CancelToken2,
VERSION,
all: all2,
Cancel,
isAxiosError,
spread,
toFormData,
AxiosHeaders: AxiosHeaders2,
HttpStatusCode,
formToJSON,
getAdapter,
mergeConfig
} = axios;
const _Logger = class _Logger {
constructor() {
__publicField(this, "isProduction");
this.isProduction = process$1.env.NODE_ENV === "production";
}
static getInstance() {
if (!_Logger.instance) {
_Logger.instance = new _Logger();
}
return _Logger.instance;
}
debug(message, ...args) {
if (!this.isProduction) {
console.debug(message, ...args);
}
}
info(message, ...args) {
if (!this.isProduction) {
console.info(message, ...args);
}
}
warn(message, ...args) {
console.warn(message, ...args);
}
error(message, ...args) {
console.error(message, ...args);
}
};
__publicField(_Logger, "instance");
let Logger = _Logger;
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
class Auth {
constructor(config) {
__publicField(this, "accountId");
__publicField(this, "privateKey");
__publicField(this, "baseUrl");
__publicField(this, "network");
this.accountId = config.accountId;
if (typeof config.privateKey === "string") {
const keyDetection = detectKeyTypeFromString(config.privateKey);
this.privateKey = keyDetection.privateKey;
} else {
this.privateKey = config.privateKey;
}
this.network = config.network || "mainnet";
this.baseUrl = config.baseUrl || "https://kiloscribe.com";
}
async authenticate() {
var _a2, _b2, _c;
const requestSignatureResponse = await axios.get(
`${this.baseUrl}/api/auth/request-signature`,
{
headers: {
"x-session": this.accountId
}
}
);
if (!((_a2 = requestSignatureResponse.data) == null ? void 0 : _a2.message)) {
throw new Error("Failed to get signature message");
}
const message = requestSignatureResponse.data.message;
const signature = await this.signMessage(message);
const authResponse = await axios.post(
`${this.baseUrl}/api/auth/authenticate`,
{
authData: {
id: this.accountId,
signature,
data: message,
network: this.network
},
include: "apiKey"
}
);
if (!((_c = (_b2 = authResponse.data) == null ? void 0 : _b2.user) == null ? void 0 : _c.sessionToken)) {
throw new Error("Authentication failed");
}
return {
apiKey: authResponse.data.apiKey
};
}
async signMessage(message) {
const messageBytes = new TextEncoder().encode(message);
const signatureBytes = await this.privateKey.sign(messageBytes);
return Buffer$1.from(signatureBytes).toString("hex");
}
}
class ClientAuth {
constructor(config) {
__publicField(this, "accountId");
__publicField(this, "signer");
__publicField(this, "baseUrl");
__publicField(this, "network");
__publicField(this, "logger");
this.accountId = config.accountId;
this.signer = config.signer;
this.network = config.network || "mainnet";
this.baseUrl = config.baseUrl || "https://kiloscribe.com";
this.logger = config.logger;
}
async authenticate() {
var _a2, _b2, _c;
const requestSignatureResponse = await axios.get(
`${this.baseUrl}/api/auth/request-signature`,
{
headers: {
"x-session": this.accountId
}
}
);
if (!((_a2 = requestSignatureResponse.data) == null ? void 0 : _a2.message)) {
throw new Error("Failed to get signature message");
}
const message = requestSignatureResponse.data.message;
const signature = await this.signMessage(JSON.stringify(message));
const authResponse = await axios.post(
`${this.baseUrl}/api/auth/authenticate`,
{
authData: {
id: this.accountId,
signature,
data: message,
network: this.network
},
include: "apiKey"
}
);
if (!((_c = (_b2 = authResponse.data) == null ? void 0 : _b2.user) == null ? void 0 : _c.sessionToken)) {
throw new Error("Authentication failed");
}
return {
apiKey: authResponse.data.apiKey
};
}
async signMessage(message) {
try {
const messageBytes = new TextEncoder().encode(message);
this.logger.debug(`signing message`);
const signatureBytes = await this.signer.sign([messageBytes], {
encoding: "utf-8"
});
return Buffer$1.from(signatureBytes == null ? void 0 : signatureBytes[0].signature).toString("hex");
} catch (e) {
this.logger.error(`Failed to sign message`, e);
throw new Error("Failed to sign message");
}
}
}
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var ieee754 = {};
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
var hasRequiredIeee754;
function requireIeee754() {
if (hasRequiredIeee754) return ieee754;
hasRequiredIeee754 = 1;
ieee754.read = function(buffer2, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? nBytes - 1 : 0;
var d = isLE ? -1 : 1;
var s = buffer2[offset + i];
i += d;
e = s & (1 << -nBits) - 1;
s >>= -nBits;
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer2[offset + i], i += d, nBits -= 8) {
}
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer2[offset + i], i += d, nBits -= 8) {
}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : (s ? -1 : 1) * Infinity;
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
ieee754.write = function(buffer2, value2, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
var i = isLE ? 0 : nBytes - 1;
var d = isLE ? 1 : -1;
var s = value2 < 0 || value2 === 0 && 1 / value2 < 0 ? 1 : 0;
value2 = Math.abs(value2);
if (isNaN(value2) || value2 === Infinity) {
m = isNaN(value2) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value2) / Math.LN2);
if (value2 * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value2 += rt / c;
} else {
value2 += rt * Math.pow(2, 1 - eBias);
}
if (value2 * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value2 * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value2 * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer2[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
}
e = e << mLen | m;
eLen += mLen;
for (; eLen > 0; buffer2[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
}
buffer2[offset + i - d] |= s * 128;
};
return ieee754;
}
requireIeee754();
function dv(array) {
return new DataView(array.buffer, array.byteOffset);
}
const UINT8 = {
len: 1,
get(array, offset) {
return dv(array).getUint8(offset);
},
put(array, offset, value2) {
dv(array).setUint8(offset, value2);
return offset + 1;
}
};
const UINT16_LE = {
len: 2,
get(array, offset) {
return dv(array).getUint16(offset, true);
},
put(array, offset, value2) {
dv(array).setUint16(offset, value2, true);
return offset + 2;
}
};
const UINT16_BE = {
len: 2,
get(array, offset) {
return dv(array).getUint16(offset);
},
put(array, offset, value2) {
dv(array).setUint16(offset, value2);
return offset + 2;
}
};
const UINT32_LE = {
len: 4,
get(array, offset) {
return dv(array).getUint32(offset, true);
},
put(array, offset, value2) {
dv(array).setUint32(offset, value2, true);
return offset + 4;
}
};
const UINT32_BE = {
len: 4,
get(array, offset) {
return dv(array).getUint32(offset);
},
put(array, offset, value2) {
dv(array).setUint32(offset, value2);
return offset + 4;
}
};
const INT32_BE = {
len: 4,
get(array, offset) {
return dv(array).getInt32(offset);
},
put(array, offset, value2) {
dv(array).setInt32(offset, value2);
return offset + 4;
}
};
const UINT64_LE = {
len: 8,
get(array, offset) {
return dv(array).getBigUint64(offset, true);
},
put(array, offset, value2) {
dv(array).setBigUint64(offset, value2, true);
return offset + 8;
}
};
class StringType {
constructor(len, encoding) {
this.len = len;
if (encoding && encoding.toLowerCase() === "windows-1252") {
this.decoder = StringType.decodeWindows1252;
} else {
const textDecoder = new TextDecoder(encoding);
this.decoder = (bytes) => textDecoder.decode(bytes);
}
}
get(data, offset = 0) {
const bytes = data.subarray(offset, offset + this.len);
return this.decoder(bytes);
}
static decodeWindows1252(bytes) {
let result = "";
for (let i = 0; i < bytes.length; i++) {
const byte = bytes[i];
result += byte < 128 || byte >= 160 ? String.fromCharCode(byte) : StringType.win1252Map[byte - 128];
}
return result;
}
}
StringType.win1252Map = "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";
const defaultMessages = "End-Of-Stream";
class EndOfStreamError extends Error {
constructor() {
super(defaultMessages);
this.name = "EndOfStreamError";
}
}
class AbortError extends Error {
constructor(message = "The operation was aborted") {
super(message);
this.name = "AbortError";
}
}
class AbstractStreamReader {
constructor() {
this.endOfStream = false;
this.interrupted = false;
this.peekQueue = [];
}
async peek(uint8Array, mayBeLess = false) {
const bytesRead = await this.read(uint8Array, mayBeLess);
this.peekQueue.push(uint8Array.subarray(0, bytesRead));
return bytesRead;
}
async read(buffer2, mayBeLess = false) {
if (buffer2.length === 0) {
return 0;
}
let bytesRead = this.readFromPeekBuffer(buffer2);
if (!this.endOfStream) {
bytesRead += await this.readRemainderFromStream(buffer2.subarray(bytesRead), mayBeLess);
}
if (bytesRead === 0 && !mayBeLess) {
throw new EndOfStreamError();
}
return bytesRead;
}
/**
* Read chunk from stream
* @param buffer - Target Uint8Array (or Buffer) to store data read from stream in
* @returns Number of bytes read
*/
readFromPeekBuffer(buffer2) {
let remaining = buffer2.length;
let bytesRead = 0;
while (this.peekQueue.length > 0 && remaining > 0) {
const peekData = this.peekQueue.pop();
if (!peekData)
throw new Error("peekData should be defined");
const lenCopy = Math.min(peekData.length, remaining);
buffer2.set(peekData.subarray(0, lenCopy), bytesRead);
bytesRead += lenCopy;
remaining -= lenCopy;
if (lenCopy < peekData.length) {
this.peekQueue.push(peekData.subarray(lenCopy));
}
}
return bytesRead;
}
async readRemainderFromStream(buffer2, mayBeLess) {
let bytesRead = 0;
while (bytesRead < buffer2.length && !this.endOfStream) {
if (this.interrupted) {
throw new AbortError();
}
const chunkLen = await this.readFromStream(buffer2.subarray(bytesRead), mayBeLess);
if (chunkLen === 0)
break;
bytesRead += chunkLen;
}
if (!mayBeLess && bytesRead < buffer2.length) {
throw new EndOfStreamError();
}
return bytesRead;
}
}
class WebStreamReader extends AbstractStreamReader {
constructor(reader) {
super();
this.reader = reader;
}
async abort() {
return this.close();
}
async close() {
this.reader.releaseLock();
}
}
class WebStreamByobReader extends WebStreamReader {
/**
* Read from stream
* @param buffer - Target Uint8Array (or Buffer) to store data read from stream in
* @param mayBeLess - If true, may fill the buffer partially
* @protected Bytes read
*/
async readFromStream(buffer2, mayBeLess) {
if (buffer2.length === 0)
return 0;
const result = await this.reader.read(new Uint8Array(buffer2.length), { min: mayBeLess ? void 0 : buffer2.length });
if (result.done) {
this.endOfStream = result.done;
}
if (result.value) {
buffer2.set(result.value);
return result.value.length;
}
return 0;
}
}
class WebStreamDefaultReader extends AbstractStreamReader {
constructor(reader) {
super();
this.reader = reader;
this.buffer = null;
}
/**
* Copy chunk to target, and store the remainder in this.buffer
*/
writeChunk(target, chunk) {
const written = Math.min(chunk.length, target.length);
target.set(chunk.subarray(0, written));
if (written < chunk.length) {
this.buffer = chunk.subarray(written);
} else {
this.buffer = null;
}
return written;
}
/**
* Read from stream
* @param buffer - Target Uint8Array (or Buffer) to store data read from stream in
* @param mayBeLess - If true, may fill the buffer partially
* @protected Bytes read
*/
async readFromStream(buffer2, mayBeLess) {
if (buffer2.length === 0)
return 0;
let totalBytesRead = 0;
if (this.buffer) {
totalBytesRead += this.writeChunk(buffer2, this.buffer);
}
while (totalBytesRead < buffer2.length && !this.endOfStream) {
const result = await this.reader.read();
if (result.done) {
this.endOfStream = true;
break;
}
if (result.value) {
totalBytesRead += this.writeChunk(buffer2.subarray(totalBytesRead), result.value);
}
}
if (!mayBeLess && totalBytesRead === 0 && this.endOfStream) {
throw new EndOfStreamError();
}
return totalBytesRead;
}
abort() {
this.interrupted = true;
return this.reader.cancel();
}
async close() {
await this.abort();
this.reader.releaseLock();
}
}
function makeWebStreamReader(stream) {
try {
const reader = stream.getReader({ mode: "byob" });
if (reader instanceof ReadableStreamDefaultReader) {
return new WebStreamDefaultReader(reader);
}
return new WebStreamByobReader(reader);
} catch (error) {
if (error instanceof TypeError) {
return new WebStreamDefaultReader(stream.getReader());
}
throw error;
}
}
class AbstractTokenizer {
/**
* Constructor
* @param options Tokenizer options
* @protected
*/
constructor(options) {
this.numBuffer = new Uint8Array(8);
this.position = 0;
this.onClose = options == null ? void 0 : options.onClose;
if (options == null ? void 0 : options.abortSignal) {
options.abortSignal.addEventListener("abort", () => {
this.abort();
});
}
}
/**
* Read a token from the tokenizer-stream
* @param token - The token to read
* @param position - If provided, the desired position in the tokenizer-stream
* @returns Promise with token data
*/
async readToken(token, position = this.position) {
const uint8Array = new Uint8Array(token.len);
const len = await this.readBuffer(uint8Array, { position });
if (len < token.len)
throw new EndOfStreamError();
return token.get(uint8Array, 0);
}
/**
* Peek a token from the tokenizer-stream.
* @param token - Token to peek from the tokenizer-stream.
* @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position.
* @returns Promise with token data
*/
async peekToken(token, position = this.position) {
const uint8Array = new Uint8Array(token.len);
const len = await this.peekBuffer(uint8Array, { position });
if (len < token.len)
throw new EndOfStreamError();
return token.get(uint8Array, 0);
}
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
async readNumber(token) {
const len = await this.readBuffer(this.numBuffer, { length: token.len });
if (len < token.len)
throw new EndOfStreamError();
return token.get(this.numBuffer, 0);
}
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
async peekNumber(token) {
const len = await this.peekBuffer(this.numBuffer, { length: token.len });
if (len < token.len)
throw new EndOfStreamError();
return token.get(this.numBuffer, 0);
}
/**
* Ignore number of bytes, advances the pointer in under tokenizer-stream.
* @param length - Number of bytes to ignore
* @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available
*/
async ignore(length) {
if (this.fileInfo.size !== void 0) {
const bytesLeft = this.fileInfo.size - this.position;
if (length > bytesLeft) {
this.position += bytesLeft;
return bytesLeft;
}
}
this.position += length;
return length;
}
async close() {
var _a2;
await this.abort();
await ((_a2 = this.onClose) == null ? void 0 : _a2.call(this));
}
normalizeOptions(uint8Array, options) {
if (!this.supportsRandomAccess() && options && options.position !== void 0 && options.position < this.position) {
throw new Error("`options.position` must be equal or greater than `tokenizer.position`");
}
return {
...{
mayBeLess: false,
offset: 0,
length: uint8Array.length,
position: this.position
},
...options
};
}
abort() {
return Promise.resolve();
}
}
const maxBufferSize = 256e3;
class ReadStreamTokenizer extends AbstractTokenizer {
/**
* Constructor
* @param streamReader stream-reader to read from
* @param options Tokenizer options
*/
constructor(streamReader, options) {
super(options);
this.streamReader = streamReader;
this.fileInfo = (options == null ? void 0 : options.fileInfo) ?? {};
}
/**
* Read buffer from tokenizer
* @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream
* @param options - Read behaviour options
* @returns Promise with number of bytes read
*/
async readBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
const skipBytes = normOptions.position - this.position;
if (skipBytes > 0) {
await this.ignore(skipBytes);
return this.readBuffer(uint8Array, options);
}
if (skipBytes < 0) {
throw new Error("`options.position` must be equal or greater than `tokenizer.position`");
}
if (normOptions.length === 0) {
return 0;
}
const bytesRead = await this.streamReader.read(uint8Array.subarray(0, normOptions.length), normOptions.mayBeLess);
this.position += bytesRead;
if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) {
throw new EndOfStreamError();
}
return bytesRead;
}
/**
* Peek (read ahead) buffer from tokenizer
* @param uint8Array - Uint8Array (or Buffer) to write data to
* @param options - Read behaviour options
* @returns Promise with number of bytes peeked
*/
async peekBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
let bytesRead = 0;
if (normOptions.position) {
const skipBytes = normOptions.position - this.position;
if (skipBytes > 0) {
const skipBuffer = new Uint8Array(normOptions.length + skipBytes);
bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess });
uint8Array.set(skipBuffer.subarray(skipBytes));
return bytesRead - skipBytes;
}
if (skipBytes < 0) {
throw new Error("Cannot peek from a negative offset in a stream");
}
}
if (normOptions.length > 0) {
try {
bytesRead = await this.streamReader.peek(uint8Array.subarray(0, normOptions.length), normOptions.mayBeLess);
} catch (err2) {
if ((options == null ? void 0 : options.mayBeLess) && err2 instanceof EndOfStreamError) {
return 0;
}
throw err2;
}
if (!normOptions.mayBeLess && bytesRead < normOptions.length) {
throw new EndOfStreamError();
}
}
return bytesRead;
}
async ignore(length) {
const bufSize = Math.min(maxBufferSize, length);
const buf = new Uint8Array(bufSize);
let totBytesRead = 0;
while (totBytesRead < length) {
const remaining = length - totBytesRead;
const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) });
if (bytesRead < 0) {
return bytesRead;
}
totBytesRead += bytesRead;
}
return totBytesRead;
}
abort() {
return this.streamReader.abort();
}
async close() {
return this.streamReader.close();
}
supportsRandomAccess() {
return false;
}
}
class BufferTokenizer extends AbstractTokenizer {
/**
* Construct BufferTokenizer
* @param uint8Array - Uint8Array to tokenize
* @param options Tokenizer options
*/
constructor(uint8Array, options) {
super(options);
this.uint8Array = uint8Array;
this.fileInfo = { ...(options == null ? void 0 : options.fileInfo) ?? {}, ...{ size: uint8Array.length } };
}
/**
* Read buffer from tokenizer
* @param uint8Array - Uint8Array to tokenize
* @param options - Read behaviour options
* @returns {Promise<number>}
*/
async readBuffer(uint8Array, options) {
if (options == null ? void 0 : options.position) {
this.position = options.position;
}
const bytesRead = await this.peekBuffer(uint8Array, options);
this.position += bytesRead;
return bytesRead;
}
/**
* Peek (read ahead) buffer from tokenizer
* @param uint8Array
* @param options - Read behaviour options
* @returns {Promise<number>}
*/
async peekBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length);
if (!normOptions.mayBeLess && bytes2read < normOptions.length) {
throw new EndOfStreamError();
}
uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read));
return bytes2read;
}
close() {
return super.close();
}
supportsRandomAccess() {
return true;
}
setPosition(position) {
this.position = position;
}
}
function fromWebStream(webStream, options) {
const webStreamReader = makeWebStreamReader(webStream);
const _options = options ?? {};
const chainedClose = _options.onClose;
_options.onClose = async () => {
await webStreamReader.close();
if (chainedClose) {
return chainedClose();
}
};
return new ReadStreamTokenizer(webStreamReader, _options);
}
function fromBuffer(uint8Array, options) {
return new BufferTokenizer(uint8Array, options);
}
var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;
var fleb = new u8([
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
2,
2,
2,
2,
3,
3,
3,
3,
4,
4,
4,
4,
5,
5,
5,
5,
0,
/* unused */
0,
0,
/* impossible */
0
]);
var fdeb = new u8([
0,
0,
0,
0,
1,
1,
2,
2,
3,
3,
4,
4,
5,
5,
6,
6,
7,
7,
8,
8,
9,
9,
10,
10,
11,
11,
12,
12,
13,
13,
/* unused */
0,
0
]);
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
var freb = function(eb, start) {
var b = new u16(31);
for (var i = 0; i < 31; ++i) {
b[i] = start += 1 << eb[i - 1];
}
var r = new i32(b[30]);
for (var i = 1; i < 30; ++i) {
for (var j = b[i]; j < b[i + 1]; ++j) {
r[j] = j - b[i] << 5 | i;
}
}
return { b, r };
};
var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0), fd = _b.b;
var rev = new u16(32768);
for (var i = 0; i < 32768; ++i) {
var x = (i & 43690) >> 1 | (i & 21845) << 1;
x = (x & 52428) >> 2 | (x & 13107) << 2;
x = (x & 61680) >> 4 | (x & 3855) << 4;
rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
}
var hMap = function(cd, mb, r) {
var s = cd.length;
var i = 0;
var l = new u16(mb);
for (; i < s; ++i) {
if (cd[i])
++l[cd[i] - 1];
}
var le = new u16(mb);
for (i = 1; i < mb; ++i) {
le[i] = le[i - 1] + l[i - 1] << 1;
}
var co;
if (r) {
co = new u16(1 << mb);
var rvb = 15 - mb;
for (i = 0; i < s; ++i) {
if (cd[i]) {
var sv = i << 4 | cd[i];
var r_1 = mb - cd[i];
var v = le[cd[i] - 1]++ << r_1;
for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
co[rev[v] >> rvb] = sv;
}
}
}
} else {
co = new u16(s);
for (i = 0; i < s; ++i) {
if (cd[i]) {
co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
}
}
}
return co;
};
var flt = new u8(288);
for (var i = 0; i < 144; ++i)
flt[i] = 8;
for (var i = 144; i < 256; ++i)
flt[i] = 9;
for (var i = 256; i < 280; ++i)
flt[i] = 7;
for (var i = 280; i < 288; ++i)
flt[i] = 8;
var fdt = new u8(32);
for (var i = 0; i < 32; ++i)
fdt[i] = 5;
var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
var max = function(a) {
var m = a[0];
for (var i = 1; i < a.length; ++i) {
if (a[i] > m)
m = a[i];
}
return m;
};
var bits = function(d, p, m) {
var o = p / 8 | 0;
return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
};
var bits16 = function(d, p) {
var o = p / 8 | 0;
return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
};
var shft = function(p) {
return (p + 7) / 8 | 0;
};
var slc = function(v, s, e) {
if (e == null || e > v.length)
e = v.length;
return new u8(v.subarray(s, e));
};
var ec = [
"unexpected EOF",
"invalid block type",
"invalid length/literal",
"invalid distance",
"stream finished",
"no stream handler",
,
"no callback",
"invalid UTF-8 data",
"extra field too long",
"date not in range 1980-2099",
"filename too long",
"stream finishing",
"invalid zip data"
// determined by unknown compression method
];
var err = function(ind, msg, nt) {
var e = new Error(msg || ec[ind]);
e.code = ind;
if (Error.captureStackTrace)
Error.captureStackTrace(e, err);
if (!nt)
throw e;
return e;
};
var inflt = function(dat, st, buf, dict) {
var sl = dat.length, dl = 0;
if (!sl || st.f && !st.l)
return buf || new u8(0);
var noBuf = !buf;
var resize = noBuf || st.i != 2;
var noSt = st.i;
if (noBuf)
buf = new u8(sl * 3);
var cbuf = function(l2) {
var bl = buf.length;
if (l2 > bl) {
var nbuf = new u8(Math.max(bl * 2, l2));
nbuf.set(buf);
buf = nbuf;
}
};
var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
var tbts = sl * 8;
do {
if (!lm) {
final = bits(dat, pos, 1);
var type = bits(dat, pos + 1, 3);
pos += 3;
if (!type) {
var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
if (t > sl) {
if (noSt)
err(0);
break;
}
if (resize)
cbuf(bt + l);
buf.set(dat.subarray(s, t), bt);
st.b = bt += l, st.p = pos = t * 8, st.f = final;
continue;
} else if (type == 1)
lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
else if (type == 2) {
var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
var tl = hLit + bits(dat, pos + 5, 31) + 1;
pos += 14;
var ldt = new u8(tl);
var clt = new u8(19);
for (var i = 0; i < hcLen; ++i) {
clt[clim[i]] = bits(dat, pos + i * 3, 7);
}
pos += hcLen * 3;
var clb = max(clt), clbmsk = (1 << clb) - 1;
var clm = hMap(clt, clb, 1);
for (var i = 0; i < tl; ) {
var r = clm[bits(dat, pos, clbmsk)];
pos += r & 15;
var s = r >> 4;
if (s < 16) {
ldt[i++] = s;
} else {
var c = 0, n = 0;
if (s == 16)
n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
else if (s == 17)
n = 3 + bits(dat, pos, 7), pos += 3;
else if (s == 18)
n = 11 + bits(dat, pos, 127), pos += 7;
while (n--)
ldt[i++] = c;
}
}
var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
lbt = max(lt);
dbt = max(dt);
lm = hMap(lt, lbt, 1);
dm = hMap(dt, dbt, 1);
} else
err(1);
if (pos > tbts) {
if (noSt)
err(0);
break;
}
}
if (resize)
cbuf(bt + 131072);
var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
var lpos = pos;
for (; ; lpos = pos) {
var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
pos += c & 15;
if (pos > tbts) {
if (noSt)
err(0);
break;
}
if (!c)
err(2);
if (sym < 256)
buf[bt++] = sym;
else if (sym == 256) {
lpos = pos, lm = null;
break;
} else {
var add = sym - 254;
if (sym > 264) {
var i = sym - 257, b = fleb[i];
add = bits(dat, pos, (1 << b) - 1) + fl[i];
pos += b;
}
var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
if (!d)
err(3);
pos += d & 15;
var dt = fd[dsym];
if (dsym > 3) {
var b = fdeb[dsym];
dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
}
if (pos > tbts) {
if (noSt)
err(0);
break;
}
if (resize)
cbuf(bt + 131072);
var end = bt + add;
if (bt < dt) {
var shift = dl - dt, dend = Math.min(dt, end);
if (shift + bt < 0)
err(3);
for (; bt < dend; ++bt)
buf[bt] = dict[shift + bt];
}
for (; bt < end; ++bt)
buf[bt] = buf[bt - dt];
}
}
st.l = lm, st.p = lpos, st.b = bt, st.f = final;
if (lm)
final = 1, st.m = lbt, st.d = dm, st.n = dbt;
} while (!final);
return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
};
var et = /* @__PURE__ */ new u8(0);
var gzs = function(d) {
if (d[0] != 31 || d[1] != 139 || d[2] != 8)
err(6, "invalid gzip data");
var flg = d[3];
var st = 10;
if (flg & 4)
st += (d[10] | d[11] << 8) + 2;
for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
;
return st + (flg & 2);
};
var gzl = function(d) {
var l = d.length;
return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
};
var zls = function(d, dict) {
if ((d[0] & 15) != 8 || d[0] >> 4 > 7 || (d[0] << 8 | d[1]) % 31)
err(6, "invalid zlib data");
if ((d[1] >> 5 & 1) == 1)
err(6, "invalid zlib data: " + (d[1] & 32 ? "need" : "unexpected") + " dictionary");
return (d[1] >> 3 & 4) + 2;
};
function inflateSync(data, opts) {
return inflt(data, { i: 2 }, opts, opts);
}
function gunzipSync(data, opts) {
var st = gzs(data);
if (st + 8 > data.length)
err(6, "invalid gzip data");
return inflt(data.subarray(st, -8), { i: 2 }, new u8(gzl(data)), opts);
}
function unzlibSync(data, opts) {
return inflt(data.subarray(zls(data), -4), { i: 2 }, opts, opts);
}
function decompressSync(data, opts) {
return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzipSync(data, opts) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflateSync(data, opts) : unzlibSync(data, opts);
}
var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
var tds = 0;
try {
td.decode(et, { stream: true });
tds = 1;
} catch (e) {
}
var browser = { exports: {} };
var ms;
var hasRequiredMs;
function requireMs() {
if (hasRequiredMs) return ms;
hasRequiredMs = 1;
var s = 1e3;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
ms = function(val, options) {
options = options || {};
var type = typeof val;
if (type === "string" && val.length > 0) {
return parse2(val);
} else if (type === "number" && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
);
};
function parse2(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n * y;
case "weeks":
case "week":
case "w":
return n * w;
case "days":
case "day":
case "d":
return n * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n;
default:
return void 0;
}
}
function fmtShort(ms2) {
var msAbs = Math.abs(ms2);
if (msAbs >= d) {
return Math.round(ms2 / d) + "d";
}
if (msAbs >= h) {
return Math.round(ms2 / h) + "h";
}
if (msAbs >= m) {
return Math.round(ms2 / m) + "m";
}
if (msAbs >= s) {
return Math.round(ms2 / s) + "s";
}
return ms2 + "ms";
}
function fmtLong(ms2) {
var msAbs = Math.abs(ms2);
if (msAbs >= d) {
return plural(ms2, msAbs, d, "day");
}
if (msAbs >= h) {
return plural(ms2, msAbs, h, "hour");
}
if (msAbs >= m) {
return plural(ms2, msAbs, m, "minute");
}
if (msAbs >= s) {
return plural(ms2, msAbs, s, "second");
}
return ms2 + " ms";
}
function plural(ms2, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : "");
}
return ms;
}
var common;
var hasRequiredCommon;
function requireCommon() {
if (hasRequiredCommon) return common;
hasRequiredCommon = 1;
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = requireMs();
createDebug.destroy = destroy;
Object.keys(env).forEach((key) => {
createDebug[key] = env[key];
});
createDebug.names = [];
createDebug.skips = [];
createDebug.formatters = {};
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0;
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug2(...args) {
if (!debug2.enabled) {
return;
}
const self2 = debug2;
const curr = Number(/* @__PURE__ */ new Date());
const ms2 = curr - (prevTime || curr);
self2.diff = ms2;
self2.prev = prevTime;
self2.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== "string") {
args.unshift("%O");
}
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
if (match === "%%") {
return "%";
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === "function") {
const val = args[index];
match = formatter.call(self2, val);
args.splice(index, 1);
index--;
}
return match;
});
createDebug.formatArgs.call(self2, args);
const logFn = self2.log || createDebug.log;
logFn.apply(self2, args);
}
debug2.namespace = namespace;
debug2.useColors = createDebug.useColors();
debug2.color = createDebug.selectColor(namespace);
debug2.extend = extend2;
debug2.destroy = createDebug.destroy;
Object.defineProperty(debug2, "enabled", {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: (v) => {
enableOverride = v;
}
});
if (typeof createDebug.init === "function") {
createDebug.init(debug2);
}
return debug2;
}
function extend2(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
for (const ns of split) {
if (ns[0] === "-") {
createDebug.skips.push(ns.slice(1));
} else {
createDebug.names.push(ns);
}
}
}
function matchesTemplate(search, template) {
let searchIndex = 0;
let templateIndex = 0;
let starIndex = -1;
let matchIndex = 0;
while (searchIndex < search.length) {
if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
if (template[templateIndex] === "*") {
starIndex = templateIndex;
matchIndex = searchIndex;
templateIndex++;
} else {
searchIndex++;
templateIndex++;
}
} else if (starIndex !== -1) {
templateIndex = starIndex + 1;
matchIndex++;
searchIndex = matchIndex;
} else {
return false;
}
}
while (templateIndex < template.length && template[templateIndex] === "*") {
templateIndex++;
}
return templateIndex === template.length;
}
function disable() {
const namespaces = [
...createDebug.names,
...createDebug.skips.map((namespace) => "-" + namespace)
].join(",");
createDebug.enable("");
return namespaces;
}
function enabled(name) {
for (const skip of createDebug.skips) {
if (matchesTemplate(name, skip)) {
return false;
}
}
for (const ns of createDebug.names) {
if (matchesTemplate(name, ns)) {
return true;
}
}
return false;
}
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
function destroy() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
createDebug.enable(createDebug.load());
return createDebug;
}
common = setup;
return common;
}
var hasRequiredBrowser;
function requireBrowser() {
if (hasRequiredBrowser) return browser.exports;
hasRequiredBrowser = 1;
(function(module, exports) {
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = /* @__PURE__ */ (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
};
})();
exports.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
function useColors() {
if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
return true;
}
if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
let m;
return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
function formatArgs(args) {
args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match) => {
if (match === "%%") {
return;
}
index++;
if (match === "%c") {
lastC = index;
}
});
args.splice(lastC, 0, c);
}
exports.log = console.debug || console.log || (() => {
});
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem("debug", namespaces);
} else {
exports.storage.removeItem("debug");
}
} catch (error) {
}
}
function load() {
let r;
try {
r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
} catch (error) {
}
if (!r && typeof process$1 !== "undefined" && "env" in process$1) {
r = process$1.env.DEBUG;
}
return r;
}
function localstorage() {
try {
return localStorage;
} catch (error) {
}
}
module.exports = requireCommon()(exports);
const { formatters } = module.exports;
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error) {
return "[UnexpectedJSONParseError]: " + error.message;
}
};
})(browser, browser.exports);
return browser.exports;
}
var browserExports = requireBrowser();
const initDebug = /* @__PURE__ */ getDefaultExportFromCjs(browserExports);
const Signature = {
LocalFileHeader: 67324752,
DataDescriptor: 134695760,
CentralFileHeader: 33639248,
EndOfCentralDirectory: 101010256
};
const DataDescriptor = {
get(array) {
UINT16_LE.get(array, 6);
return {
signature: UINT32_LE.get(array, 0),
compressedSize: UINT32_LE.get(array, 8),
uncompressedSize: UINT32_LE.get(array, 12)
};
},
len: 16
};
const LocalFileHeaderToken = {
get(array) {
const flags = UINT16_LE.get(array, 6);
return {
signature: UINT32_LE.get(array, 0),
minVersion: UINT16_LE.get(array, 4),
dataDescriptor: !!(flags & 8),
compressedMethod: UINT16_LE.get(array, 8),
compressedSize: UINT32_LE.get(array, 18),
uncompressedSize: UINT32_LE.get(array, 22),
filenameLength: UINT16_LE.get(array, 26),
extraFieldLength: UINT16_LE.get(array, 28),
filename: null
};
},
len: 30
};
const EndOfCentralDirectoryRecordToken = {
get(array) {
return {
signature: UINT32_LE.get(array, 0),
nrOfThisDisk: UINT16_LE.get(array, 4),
nrOfThisDiskWithTheStart: UINT16_LE.get(array, 6),
nrOfEntriesOnThisDisk: UINT16_LE.get(array, 8),
nrOfEntriesOfSize: UINT16_LE.get(array, 10),
sizeOfCd: UINT32_LE.get(array, 12),
offsetOfStartOfCd: UINT32_LE.get(array, 16),
zipFileCommentLength: UINT16_LE.get(array, 20)
};
},
len: 22
};
const FileHeader = {
get(array) {
const flags = UINT16_LE.get(array, 8);
return {
signature: UINT32_LE.get(array, 0),
minVersion: UINT16_LE.get(array, 6),
dataDescriptor: !!(flags & 8),
compressedMethod: UINT16_LE.get(array, 10),
compressedSize: UINT32_LE.get(array, 20),
uncompressedSize: UINT32_LE.get(array, 24),
filenameLength: UINT16_LE.get(array, 28),
extraFieldLength: UINT16_LE.get(array, 30),
fileCommentLength: UINT16_LE.get(array, 32),
relativeOffsetOfLocalHeader: UINT32_LE.get(array, 42),
filename: null
};
},
len: 46
};
function signatureToArray(signature) {
const signatureBytes = new Uint8Array(UINT32_LE.len);
UINT32_LE.put(signatureBytes, 0, signature);
return signatureBytes;
}
const debug = initDebug("tokenizer:inflate");
const syncBufferSize = 256 * 1024;
const ddSignatureArray = signatureToArray(Signature.DataDescriptor);
const eocdSignatureBytes = signatureToArray(Signature.EndOfCentralDirectory);
class ZipHandler {
constructor(tokenizer) {
this.tokenizer = tokenizer;
this.syncBuffer = new Uint8Array(syncBufferSize);
}
async isZip() {
return await this.peekSignature() === Signature.LocalFileHeader;
}
peekSignature() {
return this.tokenizer.peekToken(UINT32_LE);
}
async findEndOfCentralDirectoryLocator() {
const randomReadTokenizer = this.tokenizer;
const chunkLength = Math.min(16 * 1024, randomReadTokenizer.fileInfo.size);
const buffer2 = this.syncBuffer.subarray(0, chunkLength);
await this.tokenizer.readBuffer(buffer2, { position: randomReadTokenizer.fileInfo.size - chunkLength });
for (let i = buffer2.length - 4; i >= 0; i--) {
if (buffer2[i] === eocdSignatureBytes[0] && buffer2[i + 1] === eocdSignatureBytes[1] && buffer2[i + 2] === eocdSignatureBytes[2] && buffer2[i + 3] === eocdSignatureBytes[3]) {
return randomReadTokenizer.fileInfo.size - chunkLength + i;
}
}
return -1;
}
async readCentralDirectory() {
if (!this.tokenizer.supportsRandomAccess()) {
debug("Cannot reading central-directory without random-read support");
return;
}
debug("Reading central-directory...");
const pos = this.tokenizer.position;
const offset = await this.findEndOfCentralDirectoryLocator();
if (offset > 0) {
debug("Central-directory 32-bit signature found");
const eocdHeader = await this.tokenizer.readToken(EndOfCentralDirectoryRecordToken, offset);
const files = [];
this.tokenizer.setPosition(eocdHeader.offsetOfStartOfCd);
for (let n = 0; n < eocdHeader.nrOfEntriesOfSize; ++n) {
const entry = await this.tokenizer.readToken(FileHeader);
if (entry.signature !== Signature.CentralFileHeader) {
throw new Error("Expected Central-File-Header signature");
}
entry.filename = await this.tokenizer.readToken(new StringType(entry.filenameLength, "utf-8"));
await this.tokenizer.ignore(entry.extraFieldLength);
await this.tokenizer.ignore(entry.fileCommentLength);
files.push(entry);
debug(`Add central-directory file-entry: n=${n + 1}/${files.length}: filename=${files[n].filename}`);
}
this.tokenizer.setPosition(pos);
return files;
}
this.tokenizer.setPosition(pos);
}
async unzip(fileCb) {
const entries = await this.readCentralDirectory();
if (entries) {
return this.iterateOverCentralDirectory(entries, fileCb);
}
let stop = false;
do {
const zipHeader = await this.readLocalFileHeader();
if (!zipHeader)
break;
const next = fileCb(zipHeader);
stop = !!next.stop;
let fileData = void 0;
await this.tokenizer.ignore(zipHeader.extraFieldLength);
if (zipHeader.dataDescriptor && zipHeader.compressedSize === 0) {
const chunks = [];
let len = syncBufferSize;
debug("Compressed-file-size unknown, scanning for next data-descriptor-signature....");
let nextHeaderIndex = -1;
while (nextHeaderIndex < 0 && len === syncBufferSize) {
len = await this.tokenizer.peekBuffer(this.syncBuffer, { mayBeLess: true });
nextHeaderIndex = indexOf(this.syncBuffer.subarray(0, len), ddSignatureArray);
const size = nextHeaderIndex >= 0 ? nextHeaderIndex : len;
if (next.handler) {
const data = new Uint8Array(size);
await this.tokenizer.readBuffer(data);
chunks.push(data);
} else {
await this.tokenizer.ignore(size);
}
}
debug(`Found data-descriptor-signature at pos=${this.tokenizer.position}`);
if (next.handler) {
await this.inflate(zipHeader, mergeArrays(chunks), next.handler);
}
} else {
if (next.handler) {
debug(`Reading compressed-file-data: ${zipHeader.compressedSize} bytes`);
fileData = new Uint8Array(zipHeader.compressedSize);
await this.tokenizer.readBuffer(fileData);
await this.inflate(zipHeader, fileData, next.handler);
} else {
debug(`Ignoring compressed-file-data: ${zipHeader.compressedSize} bytes`);
await this.tokenizer.ignore(zipHeader.compressedSize);
}
}
debug(`Reading data-descriptor at pos=${this.tokenizer.position}`);
if (zipHeader.dataDescriptor) {
const dataDescriptor = await this.tokenizer.readToken(DataDescriptor);
if (dataDescriptor.signature !== 134695760) {
throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position - DataDescriptor.len}`);
}
}
} while (!stop);
}
async iterateOverCentralDirectory(entries, fileCb) {
for (const fileHeader of entries) {
const next = fileCb(fileHeader);
if (next.handler) {
this.tokenizer.setPosition(fileHeader.relativeOffsetOfLocalHeader);
const zipHeader = await this.readLocalFileHeader();
if (zipHeader) {
await this.tokenizer.ignore(zipHeader.extraFieldLength);
const fileData = new Uint8Array(fileHeader.compressedSize);
await this.tokenizer.readBuffer(fileData);
await this.inflate(zipHeader, fileData, next.handler);
}
}
if (next.stop)
break;
}
}
inflate(zipHeader, fileData, cb) {
if (zipHeader.compressedMethod === 0) {
return cb(fileData);
}
debug(`Decompress filename=${zipHeader.filename}, compressed-size=${fileData.length}`);
const uncompressedData = decompressSync(fileData);
return cb(uncompressedData);
}
async readLocalFileHeader() {
const signature = await this.tokenizer.peekToken(UINT32_LE);
if (signature === Signature.LocalFileHeader) {
const header = await this.tokenizer.readToken(LocalFileHeaderToken);
header.filename = await this.tokenizer.readToken(new StringType(header.filenameLength, "utf-8"));
return header;
}
if (signature === Signature.CentralFileHeader) {
return false;
}
if (signature === 3759263696) {
throw new Error("Encrypted ZIP");
}
throw new Error("Unexpected signature");
}
}
function indexOf(buffer2, portion) {
const bufferLength = buffer2.length;
const portionLength = portion.length;
if (portionLength > bufferLength)
return -1;
for (let i = 0; i <= bufferLength - portionLength; i++) {
let found = true;
for (let j = 0; j < portionLength; j++) {
if (buffer2[i + j] !== portion[j]) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
function mergeArrays(chunks) {
const totalLength2 = chunks.reduce((acc, curr) => acc + curr.length, 0);
const mergedArray = new Uint8Array(totalLength2);
let offset = 0;
for (const chunk of chunks) {
mergedArray.set(chunk, offset);
offset += chunk.length;
}
return mergedArray;
}
({
utf8: new globalThis.TextDecoder("utf8")
});
new globalThis.TextEncoder();
Array.from({ length: 256 }, (_, index) => index.toString(16).padStart(2, "0"));
function getUintBE(view) {
const { byteLength: byteLength2 } = view;
if (byteLength2 === 6) {
return view.getUint16(0) * 2 ** 32 + view.getUint32(2);
}
if (byteLength2 === 5) {
return view.getUint8(0) * 2 ** 32 + view.getUint32(1);
}
if (byteLength2 === 4) {
return view.getUint32(0);
}
if (byteLength2 === 3) {
return view.getUint8(0) * 2 ** 16 + view.getUint16(1);
}
if (byteLength2 === 2) {
return view.getUint16(0);
}
if (byteLength2 === 1) {
return view.getUint8(0);
}
}
function stringToBytes(string) {
return [...string].map((character) => character.charCodeAt(0));
}
function tarHeaderChecksumMatches(arrayBuffer, offset = 0) {
const readSum = Number.parseInt(new StringType(6).get(arrayBuffer, 148).replace(/\0.*$/, "").trim(), 8);
if (Number.isNaN(readSum)) {
return false;
}
let sum = 8 * 32;
for (let index = offset; index < offset + 148; index++) {
sum += arrayBuffer[index];
}
for (let index = offset + 156; index < offset + 512; index++) {
sum += arrayBuffer[index];
}
return readSum === sum;
}
const uint32SyncSafeToken = {
get: (buffer2, offset) => buffer2[offset + 3] & 127 | buffer2[offset + 2] << 7 | buffer2[offset + 1] << 14 | buffer2[offset] << 21,
len: 4
};
const extensions = [
"jpg",
"png",
"apng",
"gif",
"webp",
"flif",
"xcf",
"cr2",
"cr3",
"orf",
"arw",
"dng",
"nef",
"rw2",
"raf",
"tif",
"bmp",
"icns",
"jxr",
"psd",
"indd",
"zip",
"tar",
"rar",
"gz",
"bz2",
"7z",
"dmg",
"mp4",
"mid",
"mkv",
"webm",
"mov",
"avi",
"mpg",
"mp2",
"mp3",
"m4a",
"oga",
"ogg",
"ogv",
"opus",
"flac",
"wav",
"spx",
"amr",
"pdf",
"epub",
"elf",
"macho",
"exe",
"swf",
"rtf",
"wasm",
"woff",
"woff2",
"eot",
"ttf",
"otf",
"ttc",
"ico",
"flv",
"ps",
"xz",
"sqlite",
"nes",
"crx",
"xpi",
"cab",
"deb",
"ar",
"rpm",
"Z",
"lz",
"cfb",
"mxf",
"mts",
"blend",
"bpg",
"docx",
"pptx",
"xlsx",
"3gp",
"3g2",
"j2c",
"jp2",
"jpm",
"jpx",
"mj2",
"aif",
"qcp",
"odt",
"ods",
"odp",
"xml",
"mobi",
"heic",
"cur",
"ktx",
"ape",
"wv",
"dcm",
"ics",
"glb",
"pcap",
"dsf",
"lnk",
"alias",
"voc",
"ac3",
"m4v",
"m4p",
"m4b",
"f4v",
"f4p",
"f4b",
"f4a",
"mie",
"asf",
"ogm",
"ogx",
"mpc",
"arrow",
"shp",
"aac",
"mp1",
"it",
"s3m",
"xm",
"skp",
"avif",
"eps",
"lzh",
"pgp",
"asar",
"stl",
"chm",
"3mf",
"zst",
"jxl",
"vcf",
"jls",
"pst",
"dwg",
"parquet",
"class",
"arj",
"cpio",
"ace",
"avro",
"icc",
"fbx",
"vsdx",
"vtt",
"apk",
"drc",
"lz4",
"potx",
"xltx",
"dotx",
"xltm",
"ott",
"ots",
"otp",
"odg",
"otg",
"xlsm",
"docm",
"dotm",
"potm",
"pptm",
"jar",
"rm",
"ppsm",
"ppsx"
];
const mimeTypes = [
"image/jpeg",
"image/png",
"image/gif",
"image/webp",
"image/flif",
"image/x-xcf",
"image/x-canon-cr2",
"image/x-canon-cr3",
"image/tiff",
"image/bmp",
"image/vnd.ms-photo",
"image/vnd.adobe.photoshop",
"application/x-indesign",
"application/epub+zip",
"application/x-xpinstall",
"application/vnd.ms-powerpoint.slideshow.macroenabled.12",
"application/vnd.oasis.opendocument.text",
"application/vnd.oasis.opendocument.spreadsheet",
"application/vnd.oasis.opendocument.presentation",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.openxmlformats-officedocument.presentationml.slideshow",
"application/zip",
"application/x-tar",
"application/x-rar-compressed",
"application/gzip",
"application/x-bzip2",
"application/x-7z-compressed",
"application/x-apple-diskimage",
"application/vnd.apache.arrow.file",
"video/mp4",
"audio/midi",
"video/matroska",
"video/webm",
"video/quicktime",
"video/vnd.avi",
"audio/wav",
"audio/qcelp",
"audio/x-ms-asf",
"video/x-ms-asf",
"application/vnd.ms-asf",
"video/mpeg",
"video/3gpp",
"audio/mpeg",
"audio/mp4",
// RFC 4337
"video/ogg",
"audio/ogg",
"audio/ogg; codecs=opus",
"application/ogg",
"audio/flac",
"audio/ape",
"audio/wavpack",
"audio/amr",
"application/pdf",
"application/x-elf",
"application/x-mach-binary",
"application/x-msdownload",
"application/x-shockwave-flash",
"application/rtf",
"application/wasm",
"font/woff",
"font/woff2",
"application/vnd.ms-fontobject",
"font/ttf",
"font/otf",
"font/collection",
"image/x-icon",
"video/x-flv",
"application/postscript",
"application/eps",
"application/x-xz",
"application/x-sqlite3",
"application/x-nintendo-nes-rom",
"application/x-google-chrome-extension",
"application/vnd.ms-cab-compressed",
"application/x-deb",
"application/x-unix-archive",
"application/x-rpm",
"application/x-compress",
"application/x-lzip",
"application/x-cfb",
"application/x-mie",
"application/mxf",
"video/mp2t",
"application/x-blender",
"image/bpg",
"image/j2c",
"image/jp2",
"image/jpx",
"image/jpm",
"image/mj2",
"audio/aiff",
"application/xml",
"application/x-mobipocket-ebook",
"image/heif",
"image/heif-sequence",
"image/heic",
"image/heic-sequence",
"image/icns",
"image/ktx",
"application/dicom",
"audio/x-musepack",
"text/calendar",
"text/vcard",
"text/vtt",
"model/gltf-binary",
"application/vnd.tcpdump.pcap",
"audio/x-dsf",
// Non-standard
"application/x.ms.shortcut",
// Invented by us
"application/x.apple.alias",
// Invented by us
"audio/x-voc",
"audio/vnd.dolby.dd-raw",
"audio/x-m4a",
"image/apng",
"image/x-olympus-orf",
"image/x-sony-arw",
"image/x-adobe-dng",
"image/x-nikon-nef",
"image/x-panasonic-rw2",
"image/x-fujifilm-raf",
"video/x-m4v",
"video/3gpp2",
"application/x-esri-shape",
"audio/aac",
"audio/x-it",
"audio/x-s3m",
"audio/x-xm",
"video/MP1S",
"video/MP2P",
"application/vnd.sketchup.skp",
"image/avif",
"application/x-lzh-compressed",
"application/pgp-encrypted",
"application/x-asar",
"model/stl",
"application/vnd.ms-htmlhelp",
"model/3mf",
"image/jxl",
"application/zstd",
"image/jls",
"application/vnd.ms-outlook",
"image/vnd.dwg",
"application/vnd.apache.parquet",
"application/java-vm",
"application/x-arj",
"application/x-cpio",
"application/x-ace-compressed",
"application/avro",
"application/vnd.iccprofile",
"application/x.autodesk.fbx",
// Invented by us
"application/vnd.visio",
"application/vnd.android.package-archive",
"application/vnd.google.draco",
// Invented by us
"application/x-lz4",
// Invented by us
"application/vnd.openxmlformats-officedocument.presentationml.template",
"application/vnd.openxmlformats-officedocument.spreadsheetml.template",
"application/vnd.openxmlformats-officedocument.wordprocessingml.template",
"application/vnd.ms-excel.template.macroenabled.12",
"application/vnd.oasis.opendocument.text-template",
"application/vnd.oasis.opendocument.spreadsheet-template",
"application/vnd.oasis.opendocument.presentation-template",
"application/vnd.oasis.opendocument.graphics",
"application/vnd.oasis.opendocument.graphics-template",
"application/vnd.ms-excel.sheet.macroenabled.12",
"application/vnd.ms-word.document.macroenabled.12",
"application/vnd.ms-word.template.macroenabled.12",
"application/vnd.ms-powerpoint.template.macroenabled.12",
"application/vnd.ms-powerpoint.presentation.macroenabled.12",
"application/java-archive",
"application/vnd.rn-realmedia"
];
const reasonableDetectionSizeInBytes = 4100;
async function fileTypeFromBuffer(input, options) {
return new FileTypeParser(options).fromBuffer(input);
}
function getFileTypeFromMimeType(mimeType) {
mimeType = mimeType.toLowerCase();
switch (mimeType) {
case "application/epub+zip":
return {
ext: "epub",
mime: mimeType
};
case "application/vnd.oasis.opendocument.text":
return {
ext: "odt",
mime: mimeType
};
case "application/vnd.oasis.opendocument.text-template":
return {
ext: "ott",
mime: mimeType
};
case "application/vnd.oasis.opendocument.spreadsheet":
return {
ext: "ods",
mime: mimeType
};
case "application/vnd.oasis.opendocument.spreadsheet-template":
return {
ext: "ots",
mime: mimeType
};
case "application/vnd.oasis.opendocument.presentation":
return {
ext: "odp",
mime: mimeType
};
case "application/vnd.oasis.opendocument.presentation-template":
return {
ext: "otp",
mime: mimeType
};
case "application/vnd.oasis.opendocument.graphics":
return {
ext: "odg",
mime: mimeType
};
case "application/vnd.oasis.opendocument.graphics-template":
return {
ext: "otg",
mime: mimeType
};
case "application/vnd.openxmlformats-officedocument.presentationml.slideshow":
return {
ext: "ppsx",
mime: mimeType
};
case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
return {
ext: "xlsx",
mime: mimeType
};
case "application/vnd.ms-excel.sheet.macroenabled":
return {
ext: "xlsm",
mime: "application/vnd.ms-excel.sheet.macroenabled.12"
};
case "application/vnd.openxmlformats-officedocument.spreadsheetml.template":
return {
ext: "xltx",
mime: mimeType
};
case "application/vnd.ms-excel.template.macroenabled":
return {
ext: "xltm",
mime: "application/vnd.ms-excel.template.macroenabled.12"
};
case "application/vnd.ms-powerpoint.slideshow.macroenabled":
return {
ext: "ppsm",
mime: "application/vnd.ms-powerpoint.slideshow.macroenabled.12"
};
case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
return {
ext: "docx",
mime: mimeType
};
case "application/vnd.ms-word.document.macroenabled":
return {
ext: "docm",
mime: "application/vnd.ms-word.document.macroenabled.12"
};
case "application/vnd.openxmlformats-officedocument.wordprocessingml.template":
return {
ext: "dotx",
mime: mimeType
};
case "application/vnd.ms-word.template.macroenabledtemplate":
return {
ext: "dotm",
mime: "application/vnd.ms-word.template.macroenabled.12"
};
case "application/vnd.openxmlformats-officedocument.presentationml.template":
return {
ext: "potx",
mime: mimeType
};
case "application/vnd.ms-powerpoint.template.macroenabled":
return {
ext: "potm",
mime: "application/vnd.ms-powerpoint.template.macroenabled.12"
};
case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
return {
ext: "pptx",
mime: mimeType
};
case "application/vnd.ms-powerpoint.presentation.macroenabled":
return {
ext: "pptm",
mime: "application/vnd.ms-powerpoint.presentation.macroenabled.12"
};
case "application/vnd.ms-visio.drawing":
return {
ext: "vsdx",
mime: "application/vnd.visio"
};
case "application/vnd.ms-package.3dmanufacturing-3dmodel+xml":
return {
ext: "3mf",
mime: "model/3mf"
};
}
}
function _check(buffer2, headers, options) {
options = {
offset: 0,
...options
};
for (const [index, header] of headers.entries()) {
if (options.mask) {
if (header !== (options.mask[index] & buffer2[index + options.offset])) {
return false;
}
} else if (header !== buffer2[index + options.offset]) {
return false;
}
}
return true;
}
class FileTypeParser {
constructor(options) {
// Detections with a high degree of certainty in identifying the correct file type
__publicField(this, "detectConfident", async (tokenizer) => {
this.buffer = new Uint8Array(reasonableDetectionSizeInBytes);
if (tokenizer.fileInfo.size === void 0) {
tokenizer.fileInfo.size = Number.MAX_SAFE_INTEGER;
}
this.tokenizer = tokenizer;
await tokenizer.peekBuffer(this.buffer, { length: 12, mayBeLess: true });
if (this.check([66, 77])) {
return {
ext: "bmp",
mime: "image/bmp"
};
}
if (this.check([11, 119])) {
return {
ext: "ac3",
mime: "audio/vnd.dolby.dd-raw"
};
}
if (this.check([120, 1])) {
return {
ext: "dmg",
mime: "application/x-apple-diskimage"
};
}
if (this.check([77, 90])) {
return {
ext: "exe",
mime: "application/x-msdownload"
};
}
if (this.check([37, 33])) {
await tokenizer.peekBuffer(this.buffer, { length: 24, mayBeLess: true });
if (this.checkString("PS-Adobe-", { offset: 2 }) && this.checkString(" EPSF-", { offset: 14 })) {
return {
ext: "eps",
mime: "application/eps"
};
}
return {
ext: "ps",
mime: "application/postscript"
};
}
if (this.check([31, 160]) || this.check([31, 157])) {
return {
ext: "Z",
mime: "application/x-compress"
};
}
if (this.check([199, 113])) {
return {
ext: "cpio",
mime: "application/x-cpio"
};
}
if (this.check([96, 234])) {
return {
ext: "arj",
mime: "application/x-arj"
};
}
if (this.check([239, 187, 191])) {
this.tokenizer.ignore(3);
return this.detectConfident(tokenizer);
}
if (this.check([71, 73, 70])) {
return {
ext: "gif",
mime: "image/gif"
};
}
if (this.check([73, 73, 188])) {
return {
ext: "jxr",
mime: "image/vnd.ms-photo"
};
}
if (this.check([31, 139, 8])) {
return {
ext: "gz",
mime: "application/gzip"
};
}
if (this.check([66, 90, 104])) {
return {
ext: "bz2",
mime: "application/x-bzip2"
};
}
if (this.checkString("ID3")) {
await tokenizer.ignore(6);
const id3HeaderLength = await tokenizer.readToken(uint32SyncSafeToken);
if (tokenizer.position + id3HeaderLength > tokenizer.fileInfo.size) {
return {
ext: "mp3",
mime: "audio/mpeg"
};
}
await tokenizer.ignore(id3HeaderLength);
return this.fromTokenizer(tokenizer);
}
if (this.checkString("MP+")) {
return {
ext: "mpc",
mime: "audio/x-musepack"
};
}
if ((this.buffer[0] === 67 || this.buffer[0] === 70) && this.check([87, 83], { offset: 1 })) {
return {
ext: "swf",
mime: "application/x-shockwave-flash"
};
}
if (this.check([255, 216, 255])) {
if (this.check([247], { offset: 3 })) {
return {
ext: "jls",
mime: "image/jls"
};
}
return {
ext: "jpg",
mime: "image/jpeg"
};
}
if (this.check([79, 98, 106, 1])) {
return {
ext: "avro",
mime: "application/avro"
};
}
if (this.checkString("FLIF")) {
return {
ext: "flif",
mime: "image/flif"
};
}
if (this.checkString("8BPS")) {
return {
ext: "psd",
mime: "image/vnd.adobe.photoshop"
};
}
if (this.checkString("MPCK")) {
return {
ext: "mpc",
mime: "audio/x-musepack"
};
}
if (this.checkString("FORM")) {
return {
ext: "aif",
mime: "audio/aiff"
};
}
if (this.checkString("icns", { offset: 0 })) {
return {
ext: "icns",
mime: "image/icns"
};
}
if (this.check([80, 75, 3, 4])) {
let fileType;
await new ZipHandler(tokenizer).unzip((zipHeader) => {
switch (zipHeader.filename) {
case "META-INF/mozilla.rsa":
fileType = {
ext: "xpi",
mime: "application/x-xpinstall"
};
return {
stop: true
};
case "META-INF/MANIFEST.MF":
fileType = {
ext: "jar",
mime: "application/java-archive"
};
return {
stop: true
};
case "mimetype":
return {
async handler(fileData) {
const mimeType = new TextDecoder("utf-8").decode(fileData).trim();
fileType = getFileTypeFromMimeType(mimeType);
},
stop: true
};
case "[Content_Types].xml":
return {
async handler(fileData) {
let xmlContent = new TextDecoder("utf-8").decode(fileData);
const endPos = xmlContent.indexOf('.main+xml"');
if (endPos === -1) {
const mimeType = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml";
if (xmlContent.includes(`ContentType="${mimeType}"`)) {
fileType = getFileTypeFromMimeType(mimeType);
}
} else {
xmlContent = xmlContent.slice(0, Math.max(0, endPos));
const firstPos = xmlContent.lastIndexOf('"');
const mimeType = xmlContent.slice(Math.max(0, firstPos + 1));
fileType = getFileTypeFromMimeType(mimeType);
}
},
stop: true
};
default:
if (/classes\d*\.dex/.test(zipHeader.filename)) {
fileType = {
ext: "apk",
mime: "application/vnd.android.package-archive"
};
return { stop: true };
}
return {};
}
});
return fileType ?? {
ext: "zip",
mime: "application/zip"
};
}
if (this.checkString("OggS")) {
await tokenizer.ignore(28);
const type = new Uint8Array(8);
await tokenizer.readBuffer(type);
if (_check(type, [79, 112, 117, 115, 72, 101, 97, 100])) {
return {
ext: "opus",
mime: "audio/ogg; codecs=opus"
};
}
if (_check(type, [128, 116, 104, 101, 111, 114, 97])) {
return {
ext: "ogv",
mime: "video/ogg"
};
}
if (_check(type, [1, 118, 105, 100, 101, 111, 0])) {
return {
ext: "ogm",
mime: "video/ogg"
};
}
if (_check(type, [127, 70, 76, 65, 67])) {
return {
ext: "oga",
mime: "audio/ogg"
};
}
if (_check(type, [83, 112, 101, 101, 120, 32, 32])) {
return {
ext: "spx",
mime: "audio/ogg"
};
}
if (_check(type, [1, 118, 111, 114, 98, 105, 115])) {
return {
ext: "ogg",
mime: "audio/ogg"
};
}
return {
ext: "ogx",
mime: "application/ogg"
};
}
if (this.check([80, 75]) && (this.buffer[2] === 3 || this.buffer[2] === 5 || this.buffer[2] === 7) && (this.buffer[3] === 4 || this.buffer[3] === 6 || this.buffer[3] === 8)) {
return {
ext: "zip",
mime: "application/zip"
};
}
if (this.checkString("MThd")) {
return {
ext: "mid",
mime: "audio/midi"
};
}
if (this.checkString("wOFF") && (this.check([0, 1, 0, 0], { offset: 4 }) || this.checkString("OTTO", { offset: 4 }))) {
return {
ext: "woff",
mime: "font/woff"
};
}
if (this.checkString("wOF2") && (this.check([0, 1, 0, 0], { offset: 4 }) || this.checkString("OTTO", { offset: 4 }))) {
return {
ext: "woff2",
mime: "font/woff2"
};
}
if (this.check([212, 195, 178, 161]) || this.check([161, 178, 195, 212])) {
return {
ext: "pcap",
mime: "application/vnd.tcpdump.pcap"
};
}
if (this.checkString("DSD ")) {
return {
ext: "dsf",
mime: "audio/x-dsf"
// Non-standard
};
}
if (this.checkString("LZIP")) {
return {
ext: "lz",
mime: "application/x-lzip"
};
}
if (this.checkString("fLaC")) {
return {
ext: "flac",
mime: "audio/flac"
};
}
if (this.check([66, 80, 71, 251])) {
return {
ext: "bpg",
mime: "image/bpg"
};
}
if (this.checkString("wvpk")) {
return {
ext: "wv",
mime: "audio/wavpack"
};
}
if (this.checkString("%PDF")) {
return {
ext: "pdf",
mime: "application/pdf"
};
}
if (this.check([0, 97, 115, 109])) {
return {
ext: "wasm",
mime: "application/wasm"
};
}
if (this.check([73, 73])) {
const fileType = await this.readTiffHeader(false);
if (fileType) {
return fileType;
}
}
if (this.check([77, 77])) {
const fileType = await this.readTiffHeader(true);
if (fileType) {
return fileType;
}
}
if (this.checkString("MAC ")) {
return {
ext: "ape",
mime: "audio/ape"
};
}
if (this.check([26, 69, 223, 163])) {
async function readField() {
const msb = await tokenizer.peekNumber(UINT8);
let mask = 128;
let ic = 0;
while ((msb & mask) === 0 && mask !== 0) {
++ic;
mask >>= 1;
}
const id = new Uint8Array(ic + 1);
await tokenizer.readBuffer(id);
return id;
}
async function readElement() {
const idField = await readField();
const lengthField = await readField();
lengthField[0] ^= 128 >> lengthField.length - 1;
const nrLength = Math.min(6, lengthField.length);
const idView = new DataView(idField.buffer);
const lengthView = new DataView(lengthField.buffer, lengthField.length - nrLength, nrLength);
return {
id: getUintBE(idView),
len: getUintBE(lengthView)
};
}
async function readChildren(children) {
while (children > 0) {
const element = await readElement();
if (element.id === 17026) {
const rawValue = await tokenizer.readToken(new StringType(element.len));
return rawValue.replaceAll(/\00.*$/g, "");
}
await tokenizer.ignore(element.len);
--children;
}
}
const re2 = await readElement();
const documentType = await readChildren(re2.len);
switch (documentType) {
case "webm":
return {
ext: "webm",
mime: "video/webm"
};
case "matroska":
return {
ext: "mkv",
mime: "video/matroska"
};
default:
return;
}
}
if (this.checkString("SQLi")) {
return {
ext: "sqlite",
mime: "application/x-sqlite3"
};
}
if (this.check([78, 69, 83, 26])) {
return {
ext: "nes",
mime: "application/x-nintendo-nes-rom"
};
}
if (this.checkString("Cr24")) {
return {
ext: "crx",
mime: "application/x-google-chrome-extension"
};
}
if (this.checkString("MSCF") || this.checkString("ISc(")) {
return {
ext: "cab",
mime: "application/vnd.ms-cab-compressed"
};
}
if (this.check([237, 171, 238, 219])) {
return {
ext: "rpm",
mime: "application/x-rpm"
};
}
if (this.check([197, 208, 211, 198])) {
return {
ext: "eps",
mime: "application/eps"
};
}
if (this.check([40, 181, 47, 253])) {
return {
ext: "zst",
mime: "application/zstd"
};
}
if (this.check([127, 69, 76, 70])) {
return {
ext: "elf",
mime: "application/x-elf"
};
}
if (this.check([33, 66, 68, 78])) {
return {
ext: "pst",
mime: "application/vnd.ms-outlook"
};
}
if (this.checkString("PAR1") || this.checkString("PARE")) {
return {
ext: "parquet",
mime: "application/vnd.apache.parquet"
};
}
if (this.checkString("ttcf")) {
return {
ext: "ttc",
mime: "font/collection"
};
}
if (this.check([207, 250, 237, 254])) {
return {
ext: "macho",
mime: "application/x-mach-binary"
};
}
if (this.check([4, 34, 77, 24])) {
return {
ext: "lz4",
mime: "application/x-lz4"
// Invented by us
};
}
if (this.check([79, 84, 84, 79, 0])) {
return {
ext: "otf",
mime: "font/otf"
};
}
if (this.checkString("#!AMR")) {
return {
ext: "amr",
mime: "audio/amr"
};
}
if (this.checkString("{\\rtf")) {
return {
ext: "rtf",
mime: "application/rtf"
};
}
if (this.check([70, 76, 86, 1])) {
return {
ext: "flv",
mime: "video/x-flv"
};
}
if (this.checkString("IMPM")) {
return {
ext: "it",
mime: "audio/x-it"
};
}
if (this.checkString("-lh0-", { offset: 2 }) || this.checkString("-lh1-", { offset: 2 }) || this.checkString("-lh2-", { offset: 2 }) || this.checkString("-lh3-", { offset: 2 }) || this.checkString("-lh4-", { offset: 2 }) || this.checkString("-lh5-", { offset: 2 }) || this.checkString("-lh6-", { offset: 2 }) || this.checkString("-lh7-", { offset: 2 }) || this.checkString("-lzs-", { offset: 2 }) || this.checkString("-lz4-", { offset: 2 }) || this.checkString("-lz5-", { offset: 2 }) || this.checkString("-lhd-", { offset: 2 })) {
return {
ext: "lzh",
mime: "application/x-lzh-compressed"
};
}
if (this.check([0, 0, 1, 186])) {
if (this.check([33], { offset: 4, mask: [241] })) {
return {
ext: "mpg",
// May also be .ps, .mpeg
mime: "video/MP1S"
};
}
if (this.check([68], { offset: 4, mask: [196] })) {
return {
ext: "mpg",
// May also be .mpg, .m2p, .vob or .sub
mime: "video/MP2P"
};
}
}
if (this.checkString("ITSF")) {
return {
ext: "chm",
mime: "application/vnd.ms-htmlhelp"
};
}
if (this.check([202, 254, 186, 190])) {
return {
ext: "class",
mime: "application/java-vm"
};
}
if (this.checkString(".RMF")) {
return {
ext: "rm",
mime: "application/vnd.rn-realmedia"
};
}
if (this.checkString("DRACO")) {
return {
ext: "drc",
mime: "application/vnd.google.draco"
// Invented by us
};
}
if (this.check([253, 55, 122, 88, 90, 0])) {
return {
ext: "xz",
mime: "application/x-xz"
};
}
if (this.checkString("<?xml ")) {
return {
ext: "xml",
mime: "application/xml"
};
}
if (this.check([55, 122, 188, 175, 39, 28])) {
return {
ext: "7z",
mime: "application/x-7z-compressed"
};
}
if (this.check([82, 97, 114, 33, 26, 7]) && (this.buffer[6] === 0 || this.buffer[6] === 1)) {
return {
ext: "rar",
mime: "application/x-rar-compressed"
};
}
if (this.checkString("solid ")) {
return {
ext: "stl",
mime: "model/stl"
};
}
if (this.checkString("AC")) {
const version = new StringType(4, "latin1").get(this.buffer, 2);
if (version.match("^d*") && version >= 1e3 && version <= 1050) {
return {
ext: "dwg",
mime: "image/vnd.dwg"
};
}
}
if (this.checkString("070707")) {
return {
ext: "cpio",
mime: "application/x-cpio"
};
}
if (this.checkString("BLENDER")) {
return {
ext: "blend",
mime: "application/x-blender"
};
}
if (this.checkString("!<arch>")) {
await tokenizer.ignore(8);
const string = await tokenizer.readToken(new StringType(13, "ascii"));
if (string === "debian-binary") {
return {
ext: "deb",
mime: "application/x-deb"
};
}
return {
ext: "ar",
mime: "application/x-unix-archive"
};
}
if (this.checkString("WEBVTT") && // One of LF, CR, tab, space, or end of file must follow "WEBVTT" per the spec (see `fixture/fixture-vtt-*.vtt` for examples). Note that `\0` is technically the null character (there is no such thing as an EOF character). However, checking for `\0` gives us the same result as checking for the end of the stream.
["\n", "\r", " ", " ", "\0"].some((char7) => this.checkString(char7, { offset: 6 }))) {
return {
ext: "vtt",
mime: "text/vtt"
};
}
if (this.check([137, 80, 78, 71, 13, 10, 26, 10])) {
await tokenizer.ignore(8);
async function readChunkHeader() {
return {
length: await tokenizer.readToken(INT32_BE),
type: await tokenizer.readToken(new StringType(4, "latin1"))
};
}
do {
const chunk = await readChunkHeader();
if (chunk.length < 0) {
return;
}
switch (chunk.type) {
case "IDAT":
return {
ext: "png",
mime: "image/png"
};
case "acTL":
return {
ext: "apng",
mime: "image/apng"
};
default:
await tokenizer.ignore(chunk.length + 4);
}
} while (tokenizer.position + 8 < tokenizer.fileInfo.size);
return {
ext: "png",
mime: "image/png"
};
}
if (this.check([65, 82, 82, 79, 87, 49, 0, 0])) {
return {
ext: "arrow",
mime: "application/vnd.apache.arrow.file"
};
}
if (this.check([103, 108, 84, 70, 2, 0, 0, 0])) {
return {
ext: "glb",
mime: "model/gltf-binary"
};
}
if (this.check([102, 114, 101, 101], { offset: 4 }) || this.check([109, 100, 97, 116], { offset: 4 }) || this.check([109, 111, 111, 118], { offset: 4 }) || this.check([119, 105, 100, 101], { offset: 4 })) {
return {
ext: "mov",
mime: "video/quicktime"
};
}
if (this.check([73, 73, 82, 79, 8, 0, 0, 0, 24])) {
return {
ext: "orf",
mime: "image/x-olympus-orf"
};
}
if (this.checkString("gimp xcf ")) {
return {
ext: "xcf",
mime: "image/x-xcf"
};
}
if (this.checkString("ftyp", { offset: 4 }) && (this.buffer[8] & 96) !== 0) {
const brandMajor = new StringType(4, "latin1").get(this.buffer, 8).replace("\0", " ").trim();
switch (brandMajor) {
case "avif":
case "avis":
return { ext: "avif", mime: "image/avif" };
case "mif1":
return { ext: "heic", mime: "image/heif" };
case "msf1":
return { ext: "heic", mime: "image/heif-sequence" };
case "heic":
case "heix":
return { ext: "heic", mime: "image/heic" };
case "hevc":
case "hevx":
return { ext: "heic", mime: "image/heic-sequence" };
case "qt":
return { ext: "mov", mime: "video/quicktime" };
case "M4V":
case "M4VH":
case "M4VP":
return { ext: "m4v", mime: "video/x-m4v" };
case "M4P":
return { ext: "m4p", mime: "video/mp4" };
case "M4B":
return { ext: "m4b", mime: "audio/mp4" };
case "M4A":
return { ext: "m4a", mime: "audio/x-m4a" };
case "F4V":
return { ext: "f4v", mime: "video/mp4" };
case "F4P":
return { ext: "f4p", mime: "video/mp4" };
case "F4A":
return { ext: "f4a", mime: "audio/mp4" };
case "F4B":
return { ext: "f4b", mime: "audio/mp4" };
case "crx":
return { ext: "cr3", mime: "image/x-canon-cr3" };
default:
if (brandMajor.startsWith("3g")) {
if (brandMajor.startsWith("3g2")) {
return { ext: "3g2", mime: "video/3gpp2" };
}
return { ext: "3gp", mime: "video/3gpp" };
}
return { ext: "mp4", mime: "video/mp4" };
}
}
if (this.check([82, 73, 70, 70])) {
if (this.checkString("WEBP", { offset: 8 })) {
return {
ext: "webp",
mime: "image/webp"
};
}
if (this.check([65, 86, 73], { offset: 8 })) {
return {
ext: "avi",
mime: "video/vnd.avi"
};
}
if (this.check([87, 65, 86, 69], { offset: 8 })) {
return {
ext: "wav",
mime: "audio/wav"
};
}
if (this.check([81, 76, 67, 77], { offset: 8 })) {
return {
ext: "qcp",
mime: "audio/qcelp"
};
}
}
if (this.check([73, 73, 85, 0, 24, 0, 0, 0, 136, 231, 116, 216])) {
return {
ext: "rw2",
mime: "image/x-panasonic-rw2"
};
}
if (this.check([48, 38, 178, 117, 142, 102, 207, 17, 166, 217])) {
async function readHeader() {
const guid = new Uint8Array(16);
await tokenizer.readBuffer(guid);
return {
id: guid,
size: Number(await tokenizer.readToken(UINT64_LE))
};
}
await tokenizer.ignore(30);
while (tokenizer.position + 24 < tokenizer.fileInfo.size) {
const header = await readHeader();
let payload = header.size - 24;
if (_check(header.id, [145, 7, 220, 183, 183, 169, 207, 17, 142, 230, 0, 192, 12, 32, 83, 101])) {
const typeId = new Uint8Array(16);
payload -= await tokenizer.readBuffer(typeId);
if (_check(typeId, [64, 158, 105, 248, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) {
return {
ext: "asf",
mime: "audio/x-ms-asf"
};
}
if (_check(typeId, [192, 239, 25, 188, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) {
return {
ext: "asf",
mime: "video/x-ms-asf"
};
}
break;
}
await tokenizer.ignore(payload);
}
return {
ext: "asf",
mime: "application/vnd.ms-asf"
};
}
if (this.check([171, 75, 84, 88, 32, 49, 49, 187, 13, 10, 26, 10])) {
return {
ext: "ktx",
mime: "image/ktx"
};
}
if ((this.check([126, 16, 4]) || this.check([126, 24, 4])) && this.check([48, 77, 73, 69], { offset: 4 })) {
return {
ext: "mie",
mime: "application/x-mie"
};
}
if (this.check([39, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], { offset: 2 })) {
return {
ext: "shp",
mime: "application/x-esri-shape"
};
}
if (this.check([255, 79, 255, 81])) {
return {
ext: "j2c",
mime: "image/j2c"
};
}
if (this.check([0, 0, 0, 12, 106, 80, 32, 32, 13, 10, 135, 10])) {
await tokenizer.ignore(20);
const type = await tokenizer.readToken(new StringType(4, "ascii"));
switch (type) {
case "jp2 ":
return {
ext: "jp2",
mime: "image/jp2"
};
case "jpx ":
return {
ext: "jpx",
mime: "image/jpx"
};
case "jpm ":
return {
ext: "jpm",
mime: "image/jpm"
};
case "mjp2":
return {
ext: "mj2",
mime: "image/mj2"
};
default:
return;
}
}
if (this.check([255, 10]) || this.check([0, 0, 0, 12, 74, 88, 76, 32, 13, 10, 135, 10])) {
return {
ext: "jxl",
mime: "image/jxl"
};
}
if (this.check([254, 255])) {
if (this.check([0, 60, 0, 63, 0, 120, 0, 109, 0, 108], { offset: 2 })) {
return {
ext: "xml",
mime: "application/xml"
};
}
return void 0;
}
if (this.check([208, 207, 17, 224, 161, 177, 26, 225])) {
return {
ext: "cfb",
mime: "application/x-cfb"
};
}
await tokenizer.peekBuffer(this.buffer, { length: Math.min(256, tokenizer.fileInfo.size), mayBeLess: true });
if (this.check([97, 99, 115, 112], { offset: 36 })) {
return {
ext: "icc",
mime: "application/vnd.iccprofile"
};
}
if (this.checkString("**ACE", { offset: 7 }) && this.checkString("**", { offset: 12 })) {
return {
ext: "ace",
mime: "application/x-ace-compressed"
};
}
if (this.checkString("BEGIN:")) {
if (this.checkString("VCARD", { offset: 6 })) {
return {
ext: "vcf",
mime: "text/vcard"
};
}
if (this.checkString("VCALENDAR", { offset: 6 })) {
return {
ext: "ics",
mime: "text/calendar"
};
}
}
if (this.checkString("FUJIFILMCCD-RAW")) {
return {
ext: "raf",
mime: "image/x-fujifilm-raf"
};
}
if (this.checkString("Extended Module:")) {
return {
ext: "xm",
mime: "audio/x-xm"
};
}
if (this.checkString("Creative Voice File")) {
return {
ext: "voc",
mime: "audio/x-voc"
};
}
if (this.check([4, 0, 0, 0]) && this.buffer.length >= 16) {
const jsonSize = new DataView(this.buffer.buffer).getUint32(12, true);
if (jsonSize > 12 && this.buffer.length >= jsonSize + 16) {
try {
const header = new TextDecoder().decode(this.buffer.subarray(16, jsonSize + 16));
const json = JSON.parse(header);
if (json.files) {
return {
ext: "asar",
mime: "application/x-asar"
};
}
} catch {
}
}
}
if (this.check([6, 14, 43, 52, 2, 5, 1, 1, 13, 1, 2, 1, 1, 2])) {
return {
ext: "mxf",
mime: "application/mxf"
};
}
if (this.checkString("SCRM", { offset: 44 })) {
return {
ext: "s3m",
mime: "audio/x-s3m"
};
}
if (this.check([71]) && this.check([71], { offset: 188 })) {
return {
ext: "mts",
mime: "video/mp2t"
};
}
if (this.check([71], { offset: 4 }) && this.check([71], { offset: 196 })) {
return {
ext: "mts",
mime: "video/mp2t"
};
}
if (this.check([66, 79, 79, 75, 77, 79, 66, 73], { offset: 60 })) {
return {
ext: "mobi",
mime: "application/x-mobipocket-ebook"
};
}
if (this.check([68, 73, 67, 77], { offset: 128 })) {
return {
ext: "dcm",
mime: "application/dicom"
};
}
if (this.check([76, 0, 0, 0, 1, 20, 2, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 70])) {
return {
ext: "lnk",
mime: "application/x.ms.shortcut"
// Invented by us
};
}
if (this.check([98, 111, 111, 107, 0, 0, 0, 0, 109, 97, 114, 107, 0, 0, 0, 0])) {
return {
ext: "alias",
mime: "application/x.apple.alias"
// Invented by us
};
}
if (this.checkString("Kaydara FBX Binary \0")) {
return {
ext: "fbx",
mime: "application/x.autodesk.fbx"
// Invented by us
};
}
if (this.check([76, 80], { offset: 34 }) && (this.check([0, 0, 1], { offset: 8 }) || this.check([1, 0, 2], { offset: 8 }) || this.check([2, 0, 2], { offset: 8 }))) {
return {
ext: "eot",
mime: "application/vnd.ms-fontobject"
};
}
if (this.check([6, 6, 237, 245, 216, 29, 70, 229, 189, 49, 239, 231, 254, 116, 183, 29])) {
return {
ext: "indd",
mime: "application/x-indesign"
};
}
await tokenizer.peekBuffer(this.buffer, { length: Math.min(512, tokenizer.fileInfo.size), mayBeLess: true });
if (this.checkString("ustar", { offset: 257 }) && (this.checkString("\0", { offset: 262 }) || this.checkString(" ", { offset: 262 })) || this.check([0, 0, 0, 0, 0, 0], { offset: 257 }) && tarHeaderChecksumMatches(this.buffer)) {
return {
ext: "tar",
mime: "application/x-tar"
};
}
if (this.check([255, 254])) {
if (this.check([60, 0, 63, 0, 120, 0, 109, 0, 108, 0], { offset: 2 })) {
return {
ext: "xml",
mime: "application/xml"
};
}
if (this.check([255, 14, 83, 0, 107, 0, 101, 0, 116, 0, 99, 0, 104, 0, 85, 0, 112, 0, 32, 0, 77, 0, 111, 0, 100, 0, 101, 0, 108, 0], { offset: 2 })) {
return {
ext: "skp",
mime: "application/vnd.sketchup.skp"
};
}
return void 0;
}
if (this.checkString("-----BEGIN PGP MESSAGE-----")) {
return {
ext: "pgp",
mime: "application/pgp-encrypted"
};
}
});
// Detections with limited supporting data, resulting in a higher likelihood of false positives
__publicField(this, "detectImprecise", async (tokenizer) => {
this.buffer = new Uint8Array(reasonableDetectionSizeInBytes);
await tokenizer.peekBuffer(this.buffer, { length: Math.min(8, tokenizer.fileInfo.size), mayBeLess: true });
if (this.check([0, 0, 1, 186]) || this.check([0, 0, 1, 179])) {
return {
ext: "mpg",
mime: "video/mpeg"
};
}
if (this.check([0, 1, 0, 0, 0])) {
return {
ext: "ttf",
mime: "font/ttf"
};
}
if (this.check([0, 0, 1, 0])) {
return {
ext: "ico",
mime: "image/x-icon"
};
}
if (this.check([0, 0, 2, 0])) {
return {
ext: "cur",
mime: "image/x-icon"
};
}
await tokenizer.peekBuffer(this.buffer, { length: Math.min(2 + this.options.mpegOffsetTolerance, tokenizer.fileInfo.size), mayBeLess: true });
if (this.buffer.length >= 2 + this.options.mpegOffsetTolerance) {
for (let depth = 0; depth <= this.options.mpegOffsetTolerance; ++depth) {
const type = this.scanMpeg(depth);
if (type) {
return type;
}
}
}
});
this.options = {
mpegOffsetTolerance: 0,
...options
};
this.detectors = [
...(options == null ? void 0 : options.customDetectors) ?? [],
{ id: "core", detect: this.detectConfident },
{ id: "core.imprecise", detect: this.detectImprecise }
];
this.tokenizerOptions = {
abortSignal: options == null ? void 0 : options.signal
};
}
async fromTokenizer(tokenizer) {
const initialPosition = tokenizer.position;
for (const detector of this.detectors) {
const fileType = await detector.detect(tokenizer);
if (fileType) {
return fileType;
}
if (initialPosition !== tokenizer.position) {
return void 0;
}
}
}
async fromBuffer(input) {
if (!(input instanceof Uint8Array || input instanceof ArrayBuffer)) {
throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof input}\``);
}
const buffer2 = input instanceof Uint8Array ? input : new Uint8Array(input);
if (!((buffer2 == null ? void 0 : buffer2.length) > 1)) {
return;
}
return this.fromTokenizer(fromBuffer(buffer2, this.tokenizerOptions));
}
async fromBlob(blob) {
return this.fromStream(blob.stream());
}
async fromStream(stream) {
const tokenizer = await fromWebStream(stream, this.tokenizerOptions);
try {
return await this.fromTokenizer(tokenizer);
} finally {
await tokenizer.close();
}
}
async toDetectionStream(stream, options) {
const { sampleSize = reasonableDetectionSizeInBytes } = options;
let detectedFileType;
let firstChunk;
const reader = stream.getReader({ mode: "byob" });
try {
const { value: chunk, done } = await reader.read(new Uint8Array(sampleSize));
firstChunk = chunk;
if (!done && chunk) {
try {
detectedFileType = await this.fromBuffer(chunk.subarray(0, sampleSize));
} catch (error) {
if (!(error instanceof EndOfStreamError)) {
throw error;
}
detectedFileType = void 0;
}
}
firstChunk = chunk;
} finally {
reader.releaseLock();
}
const transformStream = new TransformStream({
async start(controller) {
controller.enqueue(firstChunk);
},
transform(chunk, controller) {
controller.enqueue(chunk);
}
});
const newStream = stream.pipeThrough(transformStream);
newStream.fileType = detectedFileType;
return newStream;
}
check(header, options) {
return _check(this.buffer, header, options);
}
checkString(header, options) {
return this.check(stringToBytes(header), options);
}
async readTiffTag(bigEndian) {
const tagId = await this.tokenizer.readToken(bigEndian ? UINT16_BE : UINT16_LE);
this.tokenizer.ignore(10);
switch (tagId) {
case 50341:
return {
ext: "arw",
mime: "image/x-sony-arw"
};
case 50706:
return {
ext: "dng",
mime: "image/x-adobe-dng"
};
}
}
async readTiffIFD(bigEndian) {
const numberOfTags = await this.tokenizer.readToken(bigEndian ? UINT16_BE : UINT16_LE);
for (let n = 0; n < numberOfTags; ++n) {
const fileType = await this.readTiffTag(bigEndian);
if (fileType) {
return fileType;
}
}
}
async readTiffHeader(bigEndian) {
const version = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 2);
const ifdOffset = (bigEndian ? UINT32_BE : UINT32_LE).get(this.buffer, 4);
if (version === 42) {
if (ifdOffset >= 6) {
if (this.checkString("CR", { offset: 8 })) {
return {
ext: "cr2",
mime: "image/x-canon-cr2"
};
}
if (ifdOffset >= 8) {
const someId1 = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 8);
const someId2 = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 10);
if (someId1 === 28 && someId2 === 254 || someId1 === 31 && someId2 === 11) {
return {
ext: "nef",
mime: "image/x-nikon-nef"
};
}
}
}
await this.tokenizer.ignore(ifdOffset);
const fileType = await this.readTiffIFD(bigEndian);
return fileType ?? {
ext: "tif",
mime: "image/tiff"
};
}
if (version === 43) {
return {
ext: "tif",
mime: "image/tiff"
};
}
}
/**
Scan check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE).
@param offset - Offset to scan for sync-preamble.
@returns {{ext: string, mime: string}}
*/
scanMpeg(offset) {
if (this.check([255, 224], { offset, mask: [255, 224] })) {
if (this.check([16], { offset: offset + 1, mask: [22] })) {
if (this.check([8], { offset: offset + 1, mask: [8] })) {
return {
ext: "aac",
mime: "audio/aac"
};
}
return {
ext: "aac",
mime: "audio/aac"
};
}
if (this.check([2], { offset: offset + 1, mask: [6] })) {
return {
ext: "mp3",
mime: "audio/mpeg"
};
}
if (this.check([4], { offset: offset + 1, mask: [6] })) {
return {
ext: "mp2",
mime: "audio/mpeg"
};
}
if (this.check([6], { offset: offset + 1, mask: [6] })) {
return {
ext: "mp1",
mime: "audio/mpeg"
};
}
}
}
}
new Set(extensions);
new Set(mimeTypes);
const PACKET_TYPES = /* @__PURE__ */ Object.create(null);
PACKET_TYPES["open"] = "0";
PACKET_TYPES["close"] = "1";
PACKET_TYPES["ping"] = "2";
PACKET_TYPES["pong"] = "3";
PACKET_TYPES["message"] = "4";
PACKET_TYPES["upgrade"] = "5";
PACKET_TYPES["noop"] = "6";
const PACKET_TYPES_REVERSE = /* @__PURE__ */ Object.create(null);
Object.keys(PACKET_TYPES).forEach((key) => {
PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
});
const ERROR_PACKET = { type: "error", data: "parser error" };
const withNativeBlob$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
const withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
const isView$1 = (obj) => {
return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
};
const encodePacket = ({ type, data }, supportsBinary, callback) => {
if (withNativeBlob$1 && data instanceof Blob) {
if (supportsBinary) {
return callback(data);
} else {
return encodeBlobAsBase64(data, callback);
}
} else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(data))) {
if (supportsBinary) {
return callback(data);
} else {
return encodeBlobAsBase64(new Blob([data]), callback);
}
}
return callback(PACKET_TYPES[type] + (data || ""));
};
const encodeBlobAsBase64 = (data, callback) => {
const fileReader = new FileReader();
fileReader.onload = function() {
const content = fileReader.result.split(",")[1];
callback("b" + (content || ""));
};
return fileReader.readAsDataURL(data);
};
function toArray(data) {
if (data instanceof Uint8Array) {
return data;
} else if (data instanceof ArrayBuffer) {
return new Uint8Array(data);
} else {
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
}
}
let TEXT_ENCODER;
function encodePacketToBinary(packet, callback) {
if (withNativeBlob$1 && packet.data instanceof Blob) {
return packet.data.arrayBuffer().then(toArray).then(callback);
} else if (withNativeArrayBuffer$2 && (packet.data instanceof ArrayBuffer || isView$1(packet.data))) {
return callback(toArray(packet.data));
}
encodePacket(packet, false, (encoded) => {
if (!TEXT_ENCODER) {
TEXT_ENCODER = new TextEncoder();
}
callback(TEXT_ENCODER.encode(encoded));
});
}
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const lookup$1 = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
for (let i = 0; i < chars.length; i++) {
lookup$1[chars.charCodeAt(i)] = i;
}
const decode$1 = (base64) => {
let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup$1[base64.charCodeAt(i)];
encoded2 = lookup$1[base64.charCodeAt(i + 1)];
encoded3 = lookup$1[base64.charCodeAt(i + 2)];
encoded4 = lookup$1[base64.charCodeAt(i + 3)];
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return arraybuffer;
};
const withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
const decodePacket = (encodedPacket, binaryType) => {
if (typeof encodedPacket !== "string") {
return {
type: "message",
data: mapBinary(encodedPacket, binaryType)
};
}
const type = encodedPacket.charAt(0);
if (type === "b") {
return {
type: "message",
data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
};
}
const packetType = PACKET_TYPES_REVERSE[type];
if (!packetType) {
return ERROR_PACKET;
}
return encodedPacket.length > 1 ? {
type: PACKET_TYPES_REVERSE[type],
data: encodedPacket.substring(1)
} : {
type: PACKET_TYPES_REVERSE[type]
};
};
const decodeBase64Packet = (data, binaryType) => {
if (withNativeArrayBuffer$1) {
const decoded = decode$1(data);
return mapBinary(decoded, binaryType);
} else {
return { base64: true, data };
}
};
const mapBinary = (data, binaryType) => {
switch (binaryType) {
case "blob":
if (data instanceof Blob) {
return data;
} else {
return new Blob([data]);
}
case "arraybuffer":
default:
if (data instanceof ArrayBuffer) {
return data;
} else {
return data.buffer;
}
}
};
const SEPARATOR = String.fromCharCode(30);
const encodePayload = (packets, callback) => {
const length = packets.length;
const encodedPackets = new Array(length);
let count = 0;
packets.forEach((packet, i) => {
encodePacket(packet, false, (encodedPacket) => {
encodedPackets[i] = encodedPacket;
if (++count === length) {
callback(encodedPackets.join(SEPARATOR));
}
});
});
};
const decodePayload = (encodedPayload, binaryType) => {
const encodedPackets = encodedPayload.split(SEPARATOR);
const packets = [];
for (let i = 0; i < encodedPackets.length; i++) {
const decodedPacket = decodePacket(encodedPackets[i], binaryType);
packets.push(decodedPacket);
if (decodedPacket.type === "error") {
break;
}
}
return packets;
};
function createPacketEncoderStream() {
return new TransformStream({
transform(packet, controller) {
encodePacketToBinary(packet, (encodedPacket) => {
const payloadLength = encodedPacket.length;
let header;
if (payloadLength < 126) {
header = new Uint8Array(1);
new DataView(header.buffer).setUint8(0, payloadLength);
} else if (payloadLength < 65536) {
header = new Uint8Array(3);
const view = new DataView(header.buffer);
view.setUint8(0, 126);
view.setUint16(1, payloadLength);
} else {
header = new Uint8Array(9);
const view = new DataView(header.buffer);
view.setUint8(0, 127);
view.setBigUint64(1, BigInt(payloadLength));
}
if (packet.data && typeof packet.data !== "string") {
header[0] |= 128;
}
controller.enqueue(header);
controller.enqueue(encodedPacket);
});
}
});
}
let TEXT_DECODER;
function totalLength(chunks) {
return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
}
function concatChunks(chunks, size) {
if (chunks[0].length === size) {
return chunks.shift();
}
const buffer2 = new Uint8Array(size);
let j = 0;
for (let i = 0; i < size; i++) {
buffer2[i] = chunks[0][j++];
if (j === chunks[0].length) {
chunks.shift();
j = 0;
}
}
if (chunks.length && j < chunks[0].length) {
chunks[0] = chunks[0].slice(j);
}
return buffer2;
}
function createPacketDecoderStream(maxPayload, binaryType) {
if (!TEXT_DECODER) {
TEXT_DECODER = new TextDecoder();
}
const chunks = [];
let state = 0;
let expectedLength = -1;
let isBinary2 = false;
return new TransformStream({
transform(chunk, controller) {
chunks.push(chunk);
while (true) {
if (state === 0) {
if (totalLength(chunks) < 1) {
break;
}
const header = concatChunks(chunks, 1);
isBinary2 = (header[0] & 128) === 128;
expectedLength = header[0] & 127;
if (expectedLength < 126) {
state = 3;
} else if (expectedLength === 126) {
state = 1;
} else {
state = 2;
}
} else if (state === 1) {
if (totalLength(chunks) < 2) {
break;
}
const headerArray = concatChunks(chunks, 2);
expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
state = 3;
} else if (state === 2) {
if (totalLength(chunks) < 8) {
break;
}
const headerArray = concatChunks(chunks, 8);
const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
const n = view.getUint32(0);
if (n > Math.pow(2, 53 - 32) - 1) {
controller.enqueue(ERROR_PACKET);
break;
}
expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
state = 3;
} else {
if (totalLength(chunks) < expectedLength) {
break;
}
const data = concatChunks(chunks, expectedLength);
controller.enqueue(decodePacket(isBinary2 ? data : TEXT_DECODER.decode(data), binaryType));
state = 0;
}
if (expectedLength === 0 || expectedLength > maxPayload) {
controller.enqueue(ERROR_PACKET);
break;
}
}
}
});
}
const protocol$1 = 4;
function Emitter(obj) {
if (obj) return mixin(obj);
}
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) {
this._callbacks = this._callbacks || {};
(this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
return this;
};
Emitter.prototype.once = function(event, fn) {
function on2() {
this.off(event, on2);
fn.apply(this, arguments);
}
on2.fn = fn;
this.on(event, on2);
return this;
};
Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) {
this._callbacks = this._callbacks || {};
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
var callbacks = this._callbacks["$" + event];
if (!callbacks) return this;
if (1 == arguments.length) {
delete this._callbacks["$" + event];
return this;
}
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
if (callbacks.length === 0) {
delete this._callbacks["$" + event];
}
return this;
};
Emitter.prototype.emit = function(event) {
this._callbacks = this._callbacks || {};
var args = new Array(arguments.length - 1), callbacks = this._callbacks["$" + event];
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
Emitter.prototype.emitReserved = Emitter.prototype.emit;
Emitter.prototype.listeners = function(event) {
this._callbacks = this._callbacks || {};
return this._callbacks["$" + event] || [];
};
Emitter.prototype.hasListeners = function(event) {
return !!this.listeners(event).length;
};
const nextTick = (() => {
const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
if (isPromiseAvailable) {
return (cb) => Promise.resolve().then(cb);
} else {
return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
}
})();
const globalThisShim = (() => {
if (typeof self !== "undefined") {
return self;
} else if (typeof window !== "undefined") {
return window;
} else {
return Function("return this")();
}
})();
const defaultBinaryType = "arraybuffer";
function createCookieJar() {
}
function pick(obj, ...attr) {
return attr.reduce((acc, k) => {
if (obj.hasOwnProperty(k)) {
acc[k] = obj[k];
}
return acc;
}, {});
}
const NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
const NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
function installTimerFunctions(obj, opts) {
if (opts.useNativeTimers) {
obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
} else {
obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
}
}
const BASE64_OVERHEAD = 1.33;
function byteLength(obj) {
if (typeof obj === "string") {
return utf8Length(obj);
}
return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
}
function utf8Length(str) {
let c = 0, length = 0;
for (let i = 0, l = str.length; i < l; i++) {
c = str.charCodeAt(i);
if (c < 128) {
length += 1;
} else if (c < 2048) {
length += 2;
} else if (c < 55296 || c >= 57344) {
length += 3;
} else {
i++;
length += 4;
}
}
return length;
}
function randomString() {
return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
}
function encode(obj) {
let str = "";
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
if (str.length)
str += "&";
str += encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]);
}
}
return str;
}
function decode(qs) {
let qry = {};
let pairs = qs.split("&");
for (let i = 0, l = pairs.length; i < l; i++) {
let pair = pairs[i].split("=");
qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return qry;
}
class TransportError extends Error {
constructor(reason, description, context) {
super(reason);
this.description = description;
this.context = context;
this.type = "TransportError";
}
}
class Transport extends Emitter {
/**
* Transport abstract constructor.
*
* @param {Object} opts - options
* @protected
*/
constructor(opts) {
super();
this.writable = false;
installTimerFunctions(this, opts);
this.opts = opts;
this.query = opts.query;
this.socket = opts.socket;
this.supportsBinary = !opts.forceBase64;
}
/**
* Emits an error.
*
* @param {String} reason
* @param description
* @param context - the error context
* @return {Transport} for chaining
* @protected
*/
onError(reason, description, context) {
super.emitReserved("error", new TransportError(reason, description, context));
return this;
}
/**
* Opens the transport.
*/
open() {
this.readyState = "opening";
this.doOpen();
return this;
}
/**
* Closes the transport.
*/
close() {
if (this.readyState === "opening" || this.readyState === "open") {
this.doClose();
this.onClose();
}
return this;
}
/**
* Sends multiple packets.
*
* @param {Array} packets
*/
send(packets) {
if (this.readyState === "open") {
this.write(packets);
}
}
/**
* Called upon open
*
* @protected
*/
onOpen() {
this.readyState = "open";
this.writable = true;
super.emitReserved("open");
}
/**
* Called with data.
*
* @param {String} data
* @protected
*/
onData(data) {
const packet = decodePacket(data, this.socket.binaryType);
this.onPacket(packet);
}
/**
* Called with a decoded packet.
*
* @protected
*/
onPacket(packet) {
super.emitReserved("packet", packet);
}
/**
* Called upon close.
*
* @protected
*/
onClose(details) {
this.readyState = "closed";
super.emitReserved("close", details);
}
/**
* Pauses the transport, in order not to lose packets during an upgrade.
*
* @param onPause
*/
pause(onPause) {
}
createUri(schema, query = {}) {
return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
}
_hostname() {
const hostname = this.opts.hostname;
return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
}
_port() {
if (this.opts.port && (this.opts.secure && Number(this.opts.port !== 443) || !this.opts.secure && Number(this.opts.port) !== 80)) {
return ":" + this.opts.port;
} else {
return "";
}
}
_query(query) {
const encodedQuery = encode(query);
return encodedQuery.length ? "?" + encodedQuery : "";
}
}
class Polling extends Transport {
constructor() {
super(...arguments);
this._polling = false;
}
get name() {
return "polling";
}
/**
* Opens the socket (triggers polling). We write a PING message to determine
* when the transport is open.
*
* @protected
*/
doOpen() {
this._poll();
}
/**
* Pauses polling.
*
* @param {Function} onPause - callback upon buffers are flushed and transport is paused
* @package
*/
pause(onPause) {
this.readyState = "pausing";
const pause = () => {
this.readyState = "paused";
onPause();
};
if (this._polling || !this.writable) {
let total = 0;
if (this._polling) {
total++;
this.once("pollComplete", function() {
--total || pause();
});
}
if (!this.writable) {
total++;
this.once("drain", function() {
--total || pause();
});
}
} else {
pause();
}
}
/**
* Starts polling cycle.
*
* @private
*/
_poll() {
this._polling = true;
this.doPoll();
this.emitReserved("poll");
}
/**
* Overloads onData to detect payloads.
*
* @protected
*/
onData(data) {
const callback = (packet) => {
if ("opening" === this.readyState && packet.type === "open") {
this.onOpen();
}
if ("close" === packet.type) {
this.onClose({ description: "transport closed by the server" });
return false;
}
this.onPacket(packet);
};
decodePayload(data, this.socket.binaryType).forEach(callback);
if ("closed" !== this.readyState) {
this._polling = false;
this.emitReserved("pollComplete");
if ("open" === this.readyState) {
this._poll();
}
}
}
/**
* For polling, send a close packet.
*
* @protected
*/
doClose() {
const close = () => {
this.write([{ type: "close" }]);
};
if ("open" === this.readyState) {
close();
} else {
this.once("open", close);
}
}
/**
* Writes a packets payload.
*
* @param {Array} packets - data packets
* @protected
*/
write(packets) {
this.writable = false;
encodePayload(packets, (data) => {
this.doWrite(data, () => {
this.writable = true;
this.emitReserved("drain");
});
});
}
/**
* Generates uri for connection.
*
* @private
*/
uri() {
const schema = this.opts.secure ? "https" : "http";
const query = this.query || {};
if (false !== this.opts.timestampRequests) {
query[this.opts.timestampParam] = randomString();
}
if (!this.supportsBinary && !query.sid) {
query.b64 = 1;
}
return this.createUri(schema, query);
}
}
let value = false;
try {
value = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
} catch (err2) {
}
const hasCORS = value;
function empty() {
}
class BaseXHR extends Polling {
/**
* XHR Polling constructor.
*
* @param {Object} opts
* @package
*/
constructor(opts) {
super(opts);
if (typeof location !== "undefined") {
const isSSL = "https:" === location.protocol;
let port = location.port;
if (!port) {
port = isSSL ? "443" : "80";
}
this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
}
}
/**
* Sends data.
*
* @param {String} data to send.
* @param {Function} called upon flush.
* @private
*/
doWrite(data, fn) {
const req = this.request({
method: "POST",
data
});
req.on("success", fn);
req.on("error", (xhrStatus, context) => {
this.onError("xhr post error", xhrStatus, context);
});
}
/**
* Starts a poll cycle.
*
* @private
*/
doPoll() {
const req = this.request();
req.on("data", this.onData.bind(this));
req.on("error", (xhrStatus, context) => {
this.onError("xhr poll error", xhrStatus, context);
});
this.pollXhr = req;
}
}
let Request$1 = class Request2 extends Emitter {
/**
* Request constructor
*
* @param {Object} options
* @package
*/
constructor(createRequest, uri, opts) {
super();
this.createRequest = createRequest;
installTimerFunctions(this, opts);
this._opts = opts;
this._method = opts.method || "GET";
this._uri = uri;
this._data = void 0 !== opts.data ? opts.data : null;
this._create();
}
/**
* Creates the XHR object and sends the request.
*
* @private
*/
_create() {
var _a2;
const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
opts.xdomain = !!this._opts.xd;
const xhr = this._xhr = this.createRequest(opts);
try {
xhr.open(this._method, this._uri, true);
try {
if (this._opts.extraHeaders) {
xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
for (let i in this._opts.extraHeaders) {
if (this._opts.extraHeaders.hasOwnProperty(i)) {
xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
}
}
}
} catch (e) {
}
if ("POST" === this._method) {
try {
xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
} catch (e) {
}
}
try {
xhr.setRequestHeader("Accept", "*/*");
} catch (e) {
}
(_a2 = this._opts.cookieJar) === null || _a2 === void 0 ? void 0 : _a2.addCookies(xhr);
if ("withCredentials" in xhr) {
xhr.withCredentials = this._opts.withCredentials;
}
if (this._opts.requestTimeout) {
xhr.timeout = this._opts.requestTimeout;
}
xhr.onreadystatechange = () => {
var _a3;
if (xhr.readyState === 3) {
(_a3 = this._opts.cookieJar) === null || _a3 === void 0 ? void 0 : _a3.parseCookies(
// @ts-ignore
xhr.getResponseHeader("set-cookie")
);
}
if (4 !== xhr.readyState)
return;
if (200 === xhr.status || 1223 === xhr.status) {
this._onLoad();
} else {
this.setTimeoutFn(() => {
this._onError(typeof xhr.status === "number" ? xhr.status : 0);
}, 0);
}
};
xhr.send(this._data);
} catch (e) {
this.setTimeoutFn(() => {
this._onError(e);
}, 0);
return;
}
if (typeof document !== "undefined") {
this._index = Request2.requestsCount++;
Request2.requests[this._index] = this;
}
}
/**
* Called upon error.
*
* @private
*/
_onError(err2) {
this.emitReserved("error", err2, this._xhr);
this._cleanup(true);
}
/**
* Cleans up house.
*
* @private
*/
_cleanup(fromError) {
if ("undefined" === typeof this._xhr || null === this._xhr) {
return;
}
this._xhr.onreadystatechange = empty;
if (fromError) {
try {
this._xhr.abort();
} catch (e) {
}
}
if (typeof document !== "undefined") {
delete Request2.requests[this._index];
}
this._xhr = null;
}
/**
* Called upon load.
*
* @private
*/
_onLoad() {
const data = this._xhr.responseText;
if (data !== null) {
this.emitReserved("data", data);
this.emitReserved("success");
this._cleanup();
}
}
/**
* Aborts the request.
*
* @package
*/
abort() {
this._cleanup();
}
};
Request$1.requestsCount = 0;
Request$1.requests = {};
if (typeof document !== "undefined") {
if (typeof attachEvent === "function") {
attachEvent("onunload", unloadHandler);
} else if (typeof addEventListener === "function") {
const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
addEventListener(terminationEvent, unloadHandler, false);
}
}
function unloadHandler() {
for (let i in Request$1.requests) {
if (Request$1.requests.hasOwnProperty(i)) {
Request$1.requests[i].abort();
}
}
}
const hasXHR2 = function() {
const xhr = newRequest({
xdomain: false
});
return xhr && xhr.responseType !== null;
}();
class XHR extends BaseXHR {
constructor(opts) {
super(opts);
const forceBase64 = opts && opts.forceBase64;
this.supportsBinary = hasXHR2 && !forceBase64;
}
request(opts = {}) {
Object.assign(opts, { xd: this.xd }, this.opts);
return new Request$1(newRequest, this.uri(), opts);
}
}
function newRequest(opts) {
const xdomain = opts.xdomain;
try {
if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
return new XMLHttpRequest();
}
} catch (e) {
}
if (!xdomain) {
try {
return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
const isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
class BaseWS extends Transport {
get name() {
return "websocket";
}
doOpen() {
const uri = this.uri();
const protocols = this.opts.protocols;
const opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
if (this.opts.extraHeaders) {
opts.headers = this.opts.extraHeaders;
}
try {
this.ws = this.createSocket(uri, protocols, opts);
} catch (err2) {
return this.emitReserved("error", err2);
}
this.ws.binaryType = this.socket.binaryType;
this.addEventListeners();
}
/**
* Adds event listeners to the socket
*
* @private
*/
addEventListeners() {
this.ws.onopen = () => {
if (this.opts.autoUnref) {
this.ws._socket.unref();
}
this.onOpen();
};
this.ws.onclose = (closeEvent) => this.onClose({
description: "websocket connection closed",
context: closeEvent
});
this.ws.onmessage = (ev) => this.onData(ev.data);
this.ws.onerror = (e) => this.onError("websocket error", e);
}
write(packets) {
this.writable = false;
for (let i = 0; i < packets.length; i++) {
const packet = packets[i];
const lastPacket = i === packets.length - 1;
encodePacket(packet, this.supportsBinary, (data) => {
try {
this.doWrite(packet, data);
} catch (e) {
}
if (lastPacket) {
nextTick(() => {
this.writable = true;
this.emitReserved("drain");
}, this.setTimeoutFn);
}
});
}
}
doClose() {
if (typeof this.ws !== "undefined") {
this.ws.onerror = () => {
};
this.ws.close();
this.ws = null;
}
}
/**
* Generates uri for connection.
*
* @private
*/
uri() {
const schema = this.opts.secure ? "wss" : "ws";
const query = this.query || {};
if (this.opts.timestampRequests) {
query[this.opts.timestampParam] = randomString();
}
if (!this.supportsBinary) {
query.b64 = 1;
}
return this.createUri(schema, query);
}
}
const WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
class WS extends BaseWS {
createSocket(uri, protocols, opts) {
return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
}
doWrite(_packet, data) {
this.ws.send(data);
}
}
class WT extends Transport {
get name() {
return "webtransport";
}
doOpen() {
try {
this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
} catch (err2) {
return this.emitReserved("error", err2);
}
this._transport.closed.then(() => {
this.onClose();
}).catch((err2) => {
this.onError("webtransport error", err2);
});
this._transport.ready.then(() => {
this._transport.createBidirectionalStream().then((stream) => {
const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
const reader = stream.readable.pipeThrough(decoderStream).getReader();
const encoderStream = createPacketEncoderStream();
encoderStream.readable.pipeTo(stream.writable);
this._writer = encoderStream.writable.getWriter();
const read = () => {
reader.read().then(({ done, value: value2 }) => {
if (done) {
return;
}
this.onPacket(value2);
read();
}).catch((err2) => {
});
};
read();
const packet = { type: "open" };
if (this.query.sid) {
packet.data = `{"sid":"${this.query.sid}"}`;
}
this._writer.write(packet).then(() => this.onOpen());
});
});
}
write(packets) {
this.writable = false;
for (let i = 0; i < packets.length; i++) {
const packet = packets[i];
const lastPacket = i === packets.length - 1;
this._writer.write(packet).then(() => {
if (lastPacket) {
nextTick(() => {
this.writable = true;
this.emitReserved("drain");
}, this.setTimeoutFn);
}
});
}
}
doClose() {
var _a2;
(_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.close();
}
}
const transports = {
websocket: WS,
webtransport: WT,
polling: XHR
};
const re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
const parts = [
"source",
"protocol",
"authority",
"userInfo",
"user",
"password",
"host",
"port",
"relative",
"path",
"directory",
"file",
"query",
"anchor"
];
function parse(str) {
if (str.length > 8e3) {
throw "URI too long";
}
const src = str, b = str.indexOf("["), e = str.indexOf("]");
if (b != -1 && e != -1) {
str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ";") + str.substring(e, str.length);
}
let m = re.exec(str || ""), uri = {}, i = 14;
while (i--) {
uri[parts[i]] = m[i] || "";
}
if (b != -1 && e != -1) {
uri.source = src;
uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ":");
uri.authority = uri.authority.replace("[", "").replace("]", "").replace(/;/g, ":");
uri.ipv6uri = true;
}
uri.pathNames = pathNames(uri, uri["path"]);
uri.queryKey = queryKey(uri, uri["query"]);
return uri;
}
function pathNames(obj, path) {
const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
if (path.slice(0, 1) == "/" || path.length === 0) {
names.splice(0, 1);
}
if (path.slice(-1) == "/") {
names.splice(names.length - 1, 1);
}
return names;
}
function queryKey(uri, query) {
const data = {};
query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function($0, $1, $2) {
if ($1) {
data[$1] = $2;
}
});
return data;
}
const withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
const OFFLINE_EVENT_LISTENERS = [];
if (withEventListeners) {
addEventListener("offline", () => {
OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
}, false);
}
class SocketWithoutUpgrade extends Emitter {
/**
* Socket constructor.
*
* @param {String|Object} uri - uri or options
* @param {Object} opts - options
*/
constructor(uri, opts) {
super();
this.binaryType = defaultBinaryType;
this.writeBuffer = [];
this._prevBufferLen = 0;
this._pingInterval = -1;
this._pingTimeout = -1;
this._maxPayload = -1;
this._pingTimeoutTime = Infinity;
if (uri && "object" === typeof uri) {
opts = uri;
uri = null;
}
if (uri) {
const parsedUri = parse(uri);
opts.hostname = parsedUri.host;
opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
opts.port = parsedUri.port;
if (parsedUri.query)
opts.query = parsedUri.query;
} else if (opts.host) {
opts.hostname = parse(opts.host).host;
}
installTimerFunctions(this, opts);
this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
if (opts.hostname && !opts.port) {
opts.port = this.secure ? "443" : "80";
}
this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : this.secure ? "443" : "80");
this.transports = [];
this._transportsByName = {};
opts.transports.forEach((t) => {
const transportName = t.prototype.name;
this.transports.push(transportName);
this._transportsByName[transportName] = t;
});
this.opts = Object.assign({
path: "/engine.io",
agent: false,
withCredentials: false,
upgrade: true,
timestampParam: "t",
rememberUpgrade: false,
addTrailingSlash: true,
rejectUnauthorized: true,
perMessageDeflate: {
threshold: 1024
},
transportOptions: {},
closeOnBeforeunload: false
}, opts);
this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : "");
if (typeof this.opts.query === "string") {
this.opts.query = decode(this.opts.query);
}
if (withEventListeners) {
if (this.opts.closeOnBeforeunload) {
this._beforeunloadEventListener = () => {
if (this.transport) {
this.transport.removeAllListeners();
this.transport.close();
}
};
addEventListener("beforeunload", this._beforeunloadEventListener, false);
}
if (this.hostname !== "localhost") {
this._offlineEventListener = () => {
this._onClose("transport close", {
description: "network connection lost"
});
};
OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
}
}
if (this.opts.withCredentials) {
this._cookieJar = createCookieJar();
}
this._open();
}
/**
* Creates transport of the given type.
*
* @param {String} name - transport name
* @return {Transport}
* @private
*/
createTransport(name) {
const query = Object.assign({}, this.opts.query);
query.EIO = protocol$1;
query.transport = name;
if (this.id)
query.sid = this.id;
const opts = Object.assign({}, this.opts, {
query,
socket: this,
hostname: this.hostname,
secure: this.secure,
port: this.port
}, this.opts.transportOptions[name]);
return new this._transportsByName[name](opts);
}
/**
* Initializes transport to use and starts probe.
*
* @private
*/
_open() {
if (this.transports.length === 0) {
this.setTimeoutFn(() => {
this.emitReserved("error", "No transports available");
}, 0);
return;
}
const transportName = this.opts.rememberUpgrade && SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
this.readyState = "opening";
const transport = this.createTransport(transportName);
transport.open();
this.setTransport(transport);
}
/**
* Sets the current transport. Disables the existing one (if any).
*
* @private
*/
setTransport(transport) {
if (this.transport) {
this.transport.removeAllListeners();
}
this.transport = transport;
transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", (reason) => this._onClose("transport close", reason));
}
/**
* Called when connection is deemed open.
*
* @private
*/
onOpen() {
this.readyState = "open";
SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
this.emitReserved("open");
this.flush();
}
/**
* Handles a packet.
*
* @private
*/
_onPacket(packet) {
if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
this.emitReserved("packet", packet);
this.emitReserved("heartbeat");
switch (packet.type) {
case "open":
this.onHandshake(JSON.parse(packet.data));
break;
case "ping":
this._sendPacket("pong");
this.emitReserved("ping");
this.emitReserved("pong");
this._resetPingTimeout();
break;
case "error":
const err2 = new Error("server error");
err2.code = packet.data;
this._onError(err2);
break;
case "message":
this.emitReserved("data", packet.data);
this.emitReserved("message", packet.data);
break;
}
}
}
/**
* Called upon handshake completion.
*
* @param {Object} data - handshake obj
* @private
*/
onHandshake(data) {
this.emitReserved("handshake", data);
this.id = data.sid;
this.transport.query.sid = data.sid;
this._pingInterval = data.pingInterval;
this._pingTimeout = data.pingTimeout;
this._maxPayload = data.maxPayload;
this.onOpen();
if ("closed" === this.readyState)
return;
this._resetPingTimeout();
}
/**
* Sets and resets ping timeout timer based on server pings.
*
* @private
*/
_resetPingTimeout() {
this.clearTimeoutFn(this._pingTimeoutTimer);
const delay = this._pingInterval + this._pingTimeout;
this._pingTimeoutTime = Date.now() + delay;
this._pingTimeoutTimer = this.setTimeoutFn(() => {
this._onClose("ping timeout");
}, delay);
if (this.opts.autoUnref) {
this._pingTimeoutTimer.unref();
}
}
/**
* Called on `drain` event
*
* @private
*/
_onDrain() {
this.writeBuffer.splice(0, this._prevBufferLen);
this._prevBufferLen = 0;
if (0 === this.writeBuffer.length) {
this.emitReserved("drain");
} else {
this.flush();
}
}
/**
* Flush write buffers.
*
* @private
*/
flush() {
if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
const packets = this._getWritablePackets();
this.transport.send(packets);
this._prevBufferLen = packets.length;
this.emitReserved("flush");
}
}
/**
* Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
* long-polling)
*
* @private
*/
_getWritablePackets() {
const shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
if (!shouldCheckPayloadSize) {
return this.writeBuffer;
}
let payloadSize = 1;
for (let i = 0; i < this.writeBuffer.length; i++) {
const data = this.writeBuffer[i].data;
if (data) {
payloadSize += byteLength(data);
}
if (i > 0 && payloadSize > this._maxPayload) {
return this.writeBuffer.slice(0, i);
}
payloadSize += 2;
}
return this.writeBuffer;
}
/**
* Checks whether the heartbeat timer has expired but the socket has not yet been notified.
*
* Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
* `write()` method then the message would not be buffered by the Socket.IO client.
*
* @return {boolean}
* @private
*/
/* private */
_hasPingExpired() {
if (!this._pingTimeoutTime)
return true;
const hasExpired = Date.now() > this._pingTimeoutTime;
if (hasExpired) {
this._pingTimeoutTime = 0;
nextTick(() => {
this._onClose("ping timeout");
}, this.setTimeoutFn);
}
return hasExpired;
}
/**
* Sends a message.
*
* @param {String} msg - message.
* @param {Object} options.
* @param {Function} fn - callback function.
* @return {Socket} for chaining.
*/
write(msg, options, fn) {
this._sendPacket("message", msg, options, fn);
return this;
}
/**
* Sends a message. Alias of {@link Socket#write}.
*
* @param {String} msg - message.
* @param {Object} options.
* @param {Function} fn - callback function.
* @return {Socket} for chaining.
*/
send(msg, options, fn) {
this._sendPacket("message", msg, options, fn);
return this;
}
/**
* Sends a packet.
*
* @param {String} type: packet type.
* @param {String} data.
* @param {Object} options.
* @param {Function} fn - callback function.
* @private
*/
_sendPacket(type, data, options, fn) {
if ("function" === typeof data) {
fn = data;
data = void 0;
}
if ("function" === typeof options) {
fn = options;
options = null;
}
if ("closing" === this.readyState || "closed" === this.readyState) {
return;
}
options = options || {};
options.compress = false !== options.compress;
const packet = {
type,
data,
options
};
this.emitReserved("packetCreate", packet);
this.writeBuffer.push(packet);
if (fn)
this.once("flush", fn);
this.flush();
}
/**
* Closes the connection.
*/
close() {
const close = () => {
this._onClose("forced close");
this.transport.close();
};
const cleanupAndClose = () => {
this.off("upgrade", cleanupAndClose);
this.off("upgradeError", cleanupAndClose);
close();
};
const waitForUpgrade = () => {
this.once("upgrade", cleanupAndClose);
this.once("upgradeError", cleanupAndClose);
};
if ("opening" === this.readyState || "open" === this.readyState) {
this.readyState = "closing";
if (this.writeBuffer.length) {
this.once("drain", () => {
if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
});
} else if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
}
return this;
}
/**
* Called upon transport error
*
* @private
*/
_onError(err2) {
SocketWithoutUpgrade.priorWebsocketSuccess = false;
if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
this.transports.shift();
return this._open();
}
this.emitReserved("error", err2);
this._onClose("transport error", err2);
}
/**
* Called upon transport close.
*
* @private
*/
_onClose(reason, description) {
if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
this.clearTimeoutFn(this._pingTimeoutTimer);
this.transport.removeAllListeners("close");
this.transport.close();
this.transport.removeAllListeners();
if (withEventListeners) {
if (this._beforeunloadEventListener) {
removeEventListener("beforeunload", this._beforeunloadEventListener, false);
}
if (this._offlineEventListener) {
const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
if (i !== -1) {
OFFLINE_EVENT_LISTENERS.splice(i, 1);
}
}
}
this.readyState = "closed";
this.id = null;
this.emitReserved("close", reason, description);
this.writeBuffer = [];
this._prevBufferLen = 0;
}
}
}
SocketWithoutUpgrade.protocol = protocol$1;
class SocketWithUpgrade extends SocketWithoutUpgrade {
constructor() {
super(...arguments);
this._upgrades = [];
}
onOpen() {
super.onOpen();
if ("open" === this.readyState && this.opts.upgrade) {
for (let i = 0; i < this._upgrades.length; i++) {
this._probe(this._upgrades[i]);
}
}
}
/**
* Probes a transport.
*
* @param {String} name - transport name
* @private
*/
_probe(name) {
let transport = this.createTransport(name);
let failed = false;
SocketWithoutUpgrade.priorWebsocketSuccess = false;
const onTransportOpen = () => {
if (failed)
return;
transport.send([{ type: "ping", data: "probe" }]);
transport.once("packet", (msg) => {
if (failed)
return;
if ("pong" === msg.type && "probe" === msg.data) {
this.upgrading = true;
this.emitReserved("upgrading", transport);
if (!transport)
return;
SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
this.transport.pause(() => {
if (failed)
return;
if ("closed" === this.readyState)
return;
cleanup();
this.setTransport(transport);
transport.send([{ type: "upgrade" }]);
this.emitReserved("upgrade", transport);
transport = null;
this.upgrading = false;
this.flush();
});
} else {
const err2 = new Error("probe error");
err2.transport = transport.name;
this.emitReserved("upgradeError", err2);
}
});
};
function freezeTransport() {
if (failed)
return;
failed = true;
cleanup();
transport.close();
transport = null;
}
const onerror = (err2) => {
const error = new Error("probe error: " + err2);
error.transport = transport.name;
freezeTransport();
this.emitReserved("upgradeError", error);
};
function onTransportClose() {
onerror("transport closed");
}
function onclose() {
onerror("socket closed");
}
function onupgrade(to) {
if (transport && to.name !== transport.name) {
freezeTransport();
}
}
const cleanup = () => {
transport.removeListener("open", onTransportOpen);
transport.removeListener("error", onerror);
transport.removeListener("close", onTransportClose);
this.off("close", onclose);
this.off("upgrading", onupgrade);
};
transport.once("open", onTransportOpen);
transport.once("error", onerror);
transport.once("close", onTransportClose);
this.once("close", onclose);
this.once("upgrading", onupgrade);
if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
this.setTimeoutFn(() => {
if (!failed) {
transport.open();
}
}, 200);
} else {
transport.open();
}
}
onHandshake(data) {
this._upgrades = this._filterUpgrades(data.upgrades);
super.onHandshake(data);
}
/**
* Filters upgrades, returning only those matching client transports.
*
* @param {Array} upgrades - server upgrades
* @private
*/
_filterUpgrades(upgrades) {
const filteredUpgrades = [];
for (let i = 0; i < upgrades.length; i++) {
if (~this.transports.indexOf(upgrades[i]))
filteredUpgrades.push(upgrades[i]);
}
return filteredUpgrades;
}
}
let Socket$1 = class Socket extends SocketWithUpgrade {
constructor(uri, opts = {}) {
const o = typeof uri === "object" ? uri : opts;
if (!o.transports || o.transports && typeof o.transports[0] === "string") {
o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map((transportName) => transports[transportName]).filter((t) => !!t);
}
super(uri, o);
}
};
function url(uri, path = "", loc) {
let obj = uri;
loc = loc || typeof location !== "undefined" && location;
if (null == uri)
uri = loc.protocol + "//" + loc.host;
if (typeof uri === "string") {
if ("/" === uri.charAt(0)) {
if ("/" === uri.charAt(1)) {
uri = loc.protocol + uri;
} else {
uri = loc.host + uri;
}
}
if (!/^(https?|wss?):\/\//.test(uri)) {
if ("undefined" !== typeof loc) {
uri = loc.protocol + "//" + uri;
} else {
uri = "https://" + uri;
}
}
obj = parse(uri);
}
if (!obj.port) {
if (/^(http|ws)$/.test(obj.protocol)) {
obj.port = "80";
} else if (/^(http|ws)s$/.test(obj.protocol)) {
obj.port = "443";
}
}
obj.path = obj.path || "/";
const ipv6 = obj.host.indexOf(":") !== -1;
const host = ipv6 ? "[" + obj.host + "]" : obj.host;
obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
return obj;
}
const withNativeArrayBuffer = typeof ArrayBuffer === "function";
const isView = (obj) => {
return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
};
const toString2 = Object.prototype.toString;
const withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString2.call(Blob) === "[object BlobConstructor]";
const withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString2.call(File) === "[object FileConstructor]";
function isBinary(obj) {
return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
}
function hasBinary(obj, toJSON2) {
if (!obj || typeof obj !== "object") {
return false;
}
if (Array.isArray(obj)) {
for (let i = 0, l = obj.length; i < l; i++) {
if (hasBinary(obj[i])) {
return true;
}
}
return false;
}
if (isBinary(obj)) {
return true;
}
if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
return hasBinary(obj.toJSON(), true);
}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
return true;
}
}
return false;
}
function deconstructPacket(packet) {
const buffers = [];
const packetData = packet.data;
const pack = packet;
pack.data = _deconstructPacket(packetData, buffers);
pack.attachments = buffers.length;
return { packet: pack, buffers };
}
function _deconstructPacket(data, buffers) {
if (!data)
return data;
if (isBinary(data)) {
const placeholder = { _placeholder: true, num: buffers.length };
buffers.push(data);
return placeholder;
} else if (Array.isArray(data)) {
const newData = new Array(data.length);
for (let i = 0; i < data.length; i++) {
newData[i] = _deconstructPacket(data[i], buffers);
}
return newData;
} else if (typeof data === "object" && !(data instanceof Date)) {
const newData = {};
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
newData[key] = _deconstructPacket(data[key], buffers);
}
}
return newData;
}
return data;
}
function reconstructPacket(packet, buffers) {
packet.data = _reconstructPacket(packet.data, buffers);
delete packet.attachments;
return packet;
}
function _reconstructPacket(data, buffers) {
if (!data)
return data;
if (data && data._placeholder === true) {
const isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
if (isIndexValid) {
return buffers[data.num];
} else {
throw new Error("illegal attachments");
}
} else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
data[i] = _reconstructPacket(data[i], buffers);
}
} else if (typeof data === "object") {
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
data[key] = _reconstructPacket(data[key], buffers);
}
}
}
return data;
}
const RESERVED_EVENTS$1 = [
"connect",
"connect_error",
"disconnect",
"disconnecting",
"newListener",
"removeListener"
// used by the Node.js EventEmitter
];
const protocol = 5;
var PacketType;
(function(PacketType2) {
PacketType2[PacketType2["CONNECT"] = 0] = "CONNECT";
PacketType2[PacketType2["DISCONNECT"] = 1] = "DISCONNECT";
PacketType2[PacketType2["EVENT"] = 2] = "EVENT";
PacketType2[PacketType2["ACK"] = 3] = "ACK";
PacketType2[PacketType2["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
PacketType2[PacketType2["BINARY_EVENT"] = 5] = "BINARY_EVENT";
PacketType2[PacketType2["BINARY_ACK"] = 6] = "BINARY_ACK";
})(PacketType || (PacketType = {}));
class Encoder {
/**
* Encoder constructor
*
* @param {function} replacer - custom replacer to pass down to JSON.parse
*/
constructor(replacer) {
this.replacer = replacer;
}
/**
* Encode a packet as a single string if non-binary, or as a
* buffer sequence, depending on packet type.
*
* @param {Object} obj - packet object
*/
encode(obj) {
if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
if (hasBinary(obj)) {
return this.encodeAsBinary({
type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
nsp: obj.nsp,
data: obj.data,
id: obj.id
});
}
}
return [this.encodeAsString(obj)];
}
/**
* Encode packet as string.
*/
encodeAsString(obj) {
let str = "" + obj.type;
if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
str += obj.attachments + "-";
}
if (obj.nsp && "/" !== obj.nsp) {
str += obj.nsp + ",";
}
if (null != obj.id) {
str += obj.id;
}
if (null != obj.data) {
str += JSON.stringify(obj.data, this.replacer);
}
return str;
}
/**
* Encode packet as 'buffer sequence' by removing blobs, and
* deconstructing packet into object with placeholders and
* a list of buffers.
*/
encodeAsBinary(obj) {
const deconstruction = deconstructPacket(obj);
const pack = this.encodeAsString(deconstruction.packet);
const buffers = deconstruction.buffers;
buffers.unshift(pack);
return buffers;
}
}
function isObject(value2) {
return Object.prototype.toString.call(value2) === "[object Object]";
}
class Decoder extends Emitter {
/**
* Decoder constructor
*
* @param {function} reviver - custom reviver to pass down to JSON.stringify
*/
constructor(reviver) {
super();
this.reviver = reviver;
}
/**
* Decodes an encoded packet string into packet JSON.
*
* @param {String} obj - encoded packet
*/
add(obj) {
let packet;
if (typeof obj === "string") {
if (this.reconstructor) {
throw new Error("got plaintext data when reconstructing a packet");
}
packet = this.decodeString(obj);
const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
this.reconstructor = new BinaryReconstructor(packet);
if (packet.attachments === 0) {
super.emitReserved("decoded", packet);
}
} else {
super.emitReserved("decoded", packet);
}
} else if (isBinary(obj) || obj.base64) {
if (!this.reconstructor) {
throw new Error("got binary data when not reconstructing a packet");
} else {
packet = this.reconstructor.takeBinaryData(obj);
if (packet) {
this.reconstructor = null;
super.emitReserved("decoded", packet);
}
}
} else {
throw new Error("Unknown type: " + obj);
}
}
/**
* Decode a packet String (JSON data)
*
* @param {String} str
* @return {Object} packet
*/
decodeString(str) {
let i = 0;
const p = {
type: Number(str.charAt(0))
};
if (PacketType[p.type] === void 0) {
throw new Error("unknown packet type " + p.type);
}
if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
const start = i + 1;
while (str.charAt(++i) !== "-" && i != str.length) {
}
const buf = str.substring(start, i);
if (buf != Number(buf) || str.charAt(i) !== "-") {
throw new Error("Illegal attachments");
}
p.attachments = Number(buf);
}
if ("/" === str.charAt(i + 1)) {
const start = i + 1;
while (++i) {
const c = str.charAt(i);
if ("," === c)
break;
if (i === str.length)
break;
}
p.nsp = str.substring(start, i);
} else {
p.nsp = "/";
}
const next = str.charAt(i + 1);
if ("" !== next && Number(next) == next) {
const start = i + 1;
while (++i) {
const c = str.charAt(i);
if (null == c || Number(c) != c) {
--i;
break;
}
if (i === str.length)
break;
}
p.id = Number(str.substring(start, i + 1));
}
if (str.charAt(++i)) {
const payload = this.tryParse(str.substr(i));
if (Decoder.isPayloadValid(p.type, payload)) {
p.data = payload;
} else {
throw new Error("invalid payload");
}
}
return p;
}
tryParse(str) {
try {
return JSON.parse(str, this.reviver);
} catch (e) {
return false;
}
}
static isPayloadValid(type, payload) {
switch (type) {
case PacketType.CONNECT:
return isObject(payload);
case PacketType.DISCONNECT:
return payload === void 0;
case PacketType.CONNECT_ERROR:
return typeof payload === "string" || isObject(payload);
case PacketType.EVENT:
case PacketType.BINARY_EVENT:
return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
case PacketType.ACK:
case PacketType.BINARY_ACK:
return Array.isArray(payload);
}
}
/**
* Deallocates a parser's resources
*/
destroy() {
if (this.reconstructor) {
this.reconstructor.finishedReconstruction();
this.reconstructor = null;
}
}
}
class BinaryReconstructor {
constructor(packet) {
this.packet = packet;
this.buffers = [];
this.reconPack = packet;
}
/**
* Method to be called when binary data received from connection
* after a BINARY_EVENT packet.
*
* @param {Buffer | ArrayBuffer} binData - the raw binary data received
* @return {null | Object} returns null if more binary data is expected or
* a reconstructed packet object if all buffers have been received.
*/
takeBinaryData(binData) {
this.buffers.push(binData);
if (this.buffers.length === this.reconPack.attachments) {
const packet = reconstructPacket(this.reconPack, this.buffers);
this.finishedReconstruction();
return packet;
}
return null;
}
/**
* Cleans up binary packet reconstruction variables.
*/
finishedReconstruction() {
this.reconPack = null;
this.buffers = [];
}
}
const parser = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
Decoder,
Encoder,
get PacketType() {
return PacketType;
},
protocol
}, Symbol.toStringTag, { value: "Module" }));
function on(obj, ev, fn) {
obj.on(ev, fn);
return function subDestroy() {
obj.off(ev, fn);
};
}
const RESERVED_EVENTS = Object.freeze({
connect: 1,
connect_error: 1,
disconnect: 1,
disconnecting: 1,
// EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
newListener: 1,
removeListener: 1
});
class Socket2 extends Emitter {
/**
* `Socket` constructor.
*/
constructor(io, nsp, opts) {
super();
this.connected = false;
this.recovered = false;
this.receiveBuffer = [];
this.sendBuffer = [];
this._queue = [];
this._queueSeq = 0;
this.ids = 0;
this.acks = {};
this.flags = {};
this.io = io;
this.nsp = nsp;
if (opts && opts.auth) {
this.auth = opts.auth;
}
this._opts = Object.assign({}, opts);
if (this.io._autoConnect)
this.open();
}
/**
* Whether the socket is currently disconnected
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log(socket.disconnected); // false
* });
*
* socket.on("disconnect", () => {
* console.log(socket.disconnected); // true
* });
*/
get disconnected() {
return !this.connected;
}
/**
* Subscribe to open, close and packet events
*
* @private
*/
subEvents() {
if (this.subs)
return;
const io = this.io;
this.subs = [
on(io, "open", this.onopen.bind(this)),
on(io, "packet", this.onpacket.bind(this)),
on(io, "error", this.onerror.bind(this)),
on(io, "close", this.onclose.bind(this))
];
}
/**
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
*
* @example
* const socket = io();
*
* console.log(socket.active); // true
*
* socket.on("disconnect", (reason) => {
* if (reason === "io server disconnect") {
* // the disconnection was initiated by the server, you need to manually reconnect
* console.log(socket.active); // false
* }
* // else the socket will automatically try to reconnect
* console.log(socket.active); // true
* });
*/
get active() {
return !!this.subs;
}
/**
* "Opens" the socket.
*
* @example
* const socket = io({
* autoConnect: false
* });
*
* socket.connect();
*/
connect() {
if (this.connected)
return this;
this.subEvents();
if (!this.io["_reconnecting"])
this.io.open();
if ("open" === this.io._readyState)
this.onopen();
return this;
}
/**
* Alias for {@link connect()}.
*/
open() {
return this.connect();
}
/**
* Sends a `message` event.
*
* This method mimics the WebSocket.send() method.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
*
* @example
* socket.send("hello");
*
* // this is equivalent to
* socket.emit("message", "hello");
*
* @return self
*/
send(...args) {
args.unshift("message");
this.emit.apply(this, args);
return this;
}
/**
* Override `emit`.
* If the event is in `events`, it's emitted normally.
*
* @example
* socket.emit("hello", "world");
*
* // all serializable datastructures are supported (no need to call JSON.stringify)
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
*
* // with an acknowledgement from the server
* socket.emit("hello", "world", (val) => {
* // ...
* });
*
* @return self
*/
emit(ev, ...args) {
var _a2, _b2, _c;
if (RESERVED_EVENTS.hasOwnProperty(ev)) {
throw new Error('"' + ev.toString() + '" is a reserved event name');
}
args.unshift(ev);
if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
this._addToQueue(args);
return this;
}
const packet = {
type: PacketType.EVENT,
data: args
};
packet.options = {};
packet.options.compress = this.flags.compress !== false;
if ("function" === typeof args[args.length - 1]) {
const id = this.ids++;
const ack = args.pop();
this._registerAckCallback(id, ack);
packet.id = id;
}
const isTransportWritable = (_b2 = (_a2 = this.io.engine) === null || _a2 === void 0 ? void 0 : _a2.transport) === null || _b2 === void 0 ? void 0 : _b2.writable;
const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
const discardPacket = this.flags.volatile && !isTransportWritable;
if (discardPacket) ;
else if (isConnected) {
this.notifyOutgoingListeners(packet);
this.packet(packet);
} else {
this.sendBuffer.push(packet);
}
this.flags = {};
return this;
}
/**
* @private
*/
_registerAckCallback(id, ack) {
var _a2;
const timeout = (_a2 = this.flags.timeout) !== null && _a2 !== void 0 ? _a2 : this._opts.ackTimeout;
if (timeout === void 0) {
this.acks[id] = ack;
return;
}
const timer = this.io.setTimeoutFn(() => {
delete this.acks[id];
for (let i = 0; i < this.sendBuffer.length; i++) {
if (this.sendBuffer[i].id === id) {
this.sendBuffer.splice(i, 1);
}
}
ack.call(this, new Error("operation has timed out"));
}, timeout);
const fn = (...args) => {
this.io.clearTimeoutFn(timer);
ack.apply(this, args);
};
fn.withError = true;
this.acks[id] = fn;
}
/**
* Emits an event and waits for an acknowledgement
*
* @example
* // without timeout
* const response = await socket.emitWithAck("hello", "world");
*
* // with a specific timeout
* try {
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
* } catch (err) {
* // the server did not acknowledge the event in the given delay
* }
*
* @return a Promise that will be fulfilled when the server acknowledges the event
*/
emitWithAck(ev, ...args) {
return new Promise((resolve, reject) => {
const fn = (arg1, arg2) => {
return arg1 ? reject(arg1) : resolve(arg2);
};
fn.withError = true;
args.push(fn);
this.emit(ev, ...args);
});
}
/**
* Add the packet to the queue.
* @param args
* @private
*/
_addToQueue(args) {
let ack;
if (typeof args[args.length - 1] === "function") {
ack = args.pop();
}
const packet = {
id: this._queueSeq++,
tryCount: 0,
pending: false,
args,
flags: Object.assign({ fromQueue: true }, this.flags)
};
args.push((err2, ...responseArgs) => {
if (packet !== this._queue[0]) {
return;
}
const hasError = err2 !== null;
if (hasError) {
if (packet.tryCount > this._opts.retries) {
this._queue.shift();
if (ack) {
ack(err2);
}
}
} else {
this._queue.shift();
if (ack) {
ack(null, ...responseArgs);
}
}
packet.pending = false;
return this._drainQueue();
});
this._queue.push(packet);
this._drainQueue();
}
/**
* Send the first packet of the queue, and wait for an acknowledgement from the server.
* @param force - whether to resend a packet that has not been acknowledged yet
*
* @private
*/
_drainQueue(force = false) {
if (!this.connected || this._queue.length === 0) {
return;
}
const packet = this._queue[0];
if (packet.pending && !force) {
return;
}
packet.pending = true;
packet.tryCount++;
this.flags = packet.flags;
this.emit.apply(this, packet.args);
}
/**
* Sends a packet.
*
* @param packet
* @private
*/
packet(packet) {
packet.nsp = this.nsp;
this.io._packet(packet);
}
/**
* Called upon engine `open`.
*
* @private
*/
onopen() {
if (typeof this.auth == "function") {
this.auth((data) => {
this._sendConnectPacket(data);
});
} else {
this._sendConnectPacket(this.auth);
}
}
/**
* Sends a CONNECT packet to initiate the Socket.IO session.
*
* @param data
* @private
*/
_sendConnectPacket(data) {
this.packet({
type: PacketType.CONNECT,
data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data) : data
});
}
/**
* Called upon engine or manager `error`.
*
* @param err
* @private
*/
onerror(err2) {
if (!this.connected) {
this.emitReserved("connect_error", err2);
}
}
/**
* Called upon engine `close`.
*
* @param reason
* @param description
* @private
*/
onclose(reason, description) {
this.connected = false;
delete this.id;
this.emitReserved("disconnect", reason, description);
this._clearAcks();
}
/**
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
* the server.
*
* @private
*/
_clearAcks() {
Object.keys(this.acks).forEach((id) => {
const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
if (!isBuffered) {
const ack = this.acks[id];
delete this.acks[id];
if (ack.withError) {
ack.call(this, new Error("socket has been disconnected"));
}
}
});
}
/**
* Called with socket packet.
*
* @param packet
* @private
*/
onpacket(packet) {
const sameNamespace = packet.nsp === this.nsp;
if (!sameNamespace)
return;
switch (packet.type) {
case PacketType.CONNECT:
if (packet.data && packet.data.sid) {
this.onconnect(packet.data.sid, packet.data.pid);
} else {
this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
}
break;
case PacketType.EVENT:
case PacketType.BINARY_EVENT:
this.onevent(packet);
break;
case PacketType.ACK:
case PacketType.BINARY_ACK:
this.onack(packet);
break;
case PacketType.DISCONNECT:
this.ondisconnect();
break;
case PacketType.CONNECT_ERROR:
this.destroy();
const err2 = new Error(packet.data.message);
err2.data = packet.data.data;
this.emitReserved("connect_error", err2);
break;
}
}
/**
* Called upon a server event.
*
* @param packet
* @private
*/
onevent(packet) {
const args = packet.data || [];
if (null != packet.id) {
args.push(this.ack(packet.id));
}
if (this.connected) {
this.emitEvent(args);
} else {
this.receiveBuffer.push(Object.freeze(args));
}
}
emitEvent(args) {
if (this._anyListeners && this._anyListeners.length) {
const listeners = this._anyListeners.slice();
for (const listener of listeners) {
listener.apply(this, args);
}
}
super.emit.apply(this, args);
if (this._pid && args.length && typeof args[args.length - 1] === "string") {
this._lastOffset = args[args.length - 1];
}
}
/**
* Produces an ack callback to emit with an event.
*
* @private
*/
ack(id) {
const self2 = this;
let sent = false;
return function(...args) {
if (sent)
return;
sent = true;
self2.packet({
type: PacketType.ACK,
id,
data: args
});
};
}
/**
* Called upon a server acknowledgement.
*
* @param packet
* @private
*/
onack(packet) {
const ack = this.acks[packet.id];
if (typeof ack !== "function") {
return;
}
delete this.acks[packet.id];
if (ack.withError) {
packet.data.unshift(null);
}
ack.apply(this, packet.data);
}
/**
* Called upon server connect.
*
* @private
*/
onconnect(id, pid) {
this.id = id;
this.recovered = pid && this._pid === pid;
this._pid = pid;
this.connected = true;
this.emitBuffered();
this.emitReserved("connect");
this._drainQueue(true);
}
/**
* Emit buffered events (received and emitted).
*
* @private
*/
emitBuffered() {
this.receiveBuffer.forEach((args) => this.emitEvent(args));
this.receiveBuffer = [];
this.sendBuffer.forEach((packet) => {
this.notifyOutgoingListeners(packet);
this.packet(packet);
});
this.sendBuffer = [];
}
/**
* Called upon server disconnect.
*
* @private
*/
ondisconnect() {
this.destroy();
this.onclose("io server disconnect");
}
/**
* Called upon forced client/server side disconnections,
* this method ensures the manager stops tracking us and
* that reconnections don't get triggered for this.
*
* @private
*/
destroy() {
if (this.subs) {
this.subs.forEach((subDestroy) => subDestroy());
this.subs = void 0;
}
this.io["_destroy"](this);
}
/**
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
*
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
*
* @example
* const socket = io();
*
* socket.on("disconnect", (reason) => {
* // console.log(reason); prints "io client disconnect"
* });
*
* socket.disconnect();
*
* @return self
*/
disconnect() {
if (this.connected) {
this.packet({ type: PacketType.DISCONNECT });
}
this.destroy();
if (this.connected) {
this.onclose("io client disconnect");
}
return this;
}
/**
* Alias for {@link disconnect()}.
*
* @return self
*/
close() {
return this.disconnect();
}
/**
* Sets the compress flag.
*
* @example
* socket.compress(false).emit("hello");
*
* @param compress - if `true`, compresses the sending data
* @return self
*/
compress(compress) {
this.flags.compress = compress;
return this;
}
/**
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
* ready to send messages.
*
* @example
* socket.volatile.emit("hello"); // the server may or may not receive it
*
* @returns self
*/
get volatile() {
this.flags.volatile = true;
return this;
}
/**
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
* given number of milliseconds have elapsed without an acknowledgement from the server:
*
* @example
* socket.timeout(5000).emit("my-event", (err) => {
* if (err) {
* // the server did not acknowledge the event in the given delay
* }
* });
*
* @returns self
*/
timeout(timeout) {
this.flags.timeout = timeout;
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* @example
* socket.onAny((event, ...args) => {
* console.log(`got ${event}`);
* });
*
* @param listener
*/
onAny(listener) {
this._anyListeners = this._anyListeners || [];
this._anyListeners.push(listener);
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* @example
* socket.prependAny((event, ...args) => {
* console.log(`got event ${event}`);
* });
*
* @param listener
*/
prependAny(listener) {
this._anyListeners = this._anyListeners || [];
this._anyListeners.unshift(listener);
return this;
}
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(`got event ${event}`);
* }
*
* socket.onAny(catchAllListener);
*
* // remove a specific listener
* socket.offAny(catchAllListener);
*
* // or remove all listeners
* socket.offAny();
*
* @param listener
*/
offAny(listener) {
if (!this._anyListeners) {
return this;
}
if (listener) {
const listeners = this._anyListeners;
for (let i = 0; i < listeners.length; i++) {
if (listener === listeners[i]) {
listeners.splice(i, 1);
return this;
}
}
} else {
this._anyListeners = [];
}
return this;
}
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*/
listenersAny() {
return this._anyListeners || [];
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.onAnyOutgoing((event, ...args) => {
* console.log(`sent event ${event}`);
* });
*
* @param listener
*/
onAnyOutgoing(listener) {
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
this._anyOutgoingListeners.push(listener);
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.prependAnyOutgoing((event, ...args) => {
* console.log(`sent event ${event}`);
* });
*
* @param listener
*/
prependAnyOutgoing(listener) {
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
this._anyOutgoingListeners.unshift(listener);
return this;
}
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(`sent event ${event}`);
* }
*
* socket.onAnyOutgoing(catchAllListener);
*
* // remove a specific listener
* socket.offAnyOutgoing(catchAllListener);
*
* // or remove all listeners
* socket.offAnyOutgoing();
*
* @param [listener] - the catch-all listener (optional)
*/
offAnyOutgoing(listener) {
if (!this._anyOutgoingListeners) {
return this;
}
if (listener) {
const listeners = this._anyOutgoingListeners;
for (let i = 0; i < listeners.length; i++) {
if (listener === listeners[i]) {
listeners.splice(i, 1);
return this;
}
}
} else {
this._anyOutgoingListeners = [];
}
return this;
}
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*/
listenersAnyOutgoing() {
return this._anyOutgoingListeners || [];
}
/**
* Notify the listeners for each packet sent
*
* @param packet
*
* @private
*/
notifyOutgoingListeners(packet) {
if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
const listeners = this._anyOutgoingListeners.slice();
for (const listener of listeners) {
listener.apply(this, packet.data);
}
}
}
}
function Backoff(opts) {
opts = opts || {};
this.ms = opts.min || 100;
this.max = opts.max || 1e4;
this.factor = opts.factor || 2;
this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
this.attempts = 0;
}
Backoff.prototype.duration = function() {
var ms2 = this.ms * Math.pow(this.factor, this.attempts++);
if (this.jitter) {
var rand = Math.random();
var deviation = Math.floor(rand * this.jitter * ms2);
ms2 = (Math.floor(rand * 10) & 1) == 0 ? ms2 - deviation : ms2 + deviation;
}
return Math.min(ms2, this.max) | 0;
};
Backoff.prototype.reset = function() {
this.attempts = 0;
};
Backoff.prototype.setMin = function(min) {
this.ms = min;
};
Backoff.prototype.setMax = function(max2) {
this.max = max2;
};
Backoff.prototype.setJitter = function(jitter) {
this.jitter = jitter;
};
class Manager extends Emitter {
constructor(uri, opts) {
var _a2;
super();
this.nsps = {};
this.subs = [];
if (uri && "object" === typeof uri) {
opts = uri;
uri = void 0;
}
opts = opts || {};
opts.path = opts.path || "/socket.io";
this.opts = opts;
installTimerFunctions(this, opts);
this.reconnection(opts.reconnection !== false);
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
this.reconnectionDelay(opts.reconnectionDelay || 1e3);
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5e3);
this.randomizationFactor((_a2 = opts.randomizationFactor) !== null && _a2 !== void 0 ? _a2 : 0.5);
this.backoff = new Backoff({
min: this.reconnectionDelay(),
max: this.reconnectionDelayMax(),
jitter: this.randomizationFactor()
});
this.timeout(null == opts.timeout ? 2e4 : opts.timeout);
this._readyState = "closed";
this.uri = uri;
const _parser = opts.parser || parser;
this.encoder = new _parser.Encoder();
this.decoder = new _parser.Decoder();
this._autoConnect = opts.autoConnect !== false;
if (this._autoConnect)
this.open();
}
reconnection(v) {
if (!arguments.length)
return this._reconnection;
this._reconnection = !!v;
if (!v) {
this.skipReconnect = true;
}
return this;
}
reconnectionAttempts(v) {
if (v === void 0)
return this._reconnectionAttempts;
this._reconnectionAttempts = v;
return this;
}
reconnectionDelay(v) {
var _a2;
if (v === void 0)
return this._reconnectionDelay;
this._reconnectionDelay = v;
(_a2 = this.backoff) === null || _a2 === void 0 ? void 0 : _a2.setMin(v);
return this;
}
randomizationFactor(v) {
var _a2;
if (v === void 0)
return this._randomizationFactor;
this._randomizationFactor = v;
(_a2 = this.backoff) === null || _a2 === void 0 ? void 0 : _a2.setJitter(v);
return this;
}
reconnectionDelayMax(v) {
var _a2;
if (v === void 0)
return this._reconnectionDelayMax;
this._reconnectionDelayMax = v;
(_a2 = this.backoff) === null || _a2 === void 0 ? void 0 : _a2.setMax(v);
return this;
}
timeout(v) {
if (!arguments.length)
return this._timeout;
this._timeout = v;
return this;
}
/**
* Starts trying to reconnect if reconnection is enabled and we have not
* started reconnecting yet
*
* @private
*/
maybeReconnectOnOpen() {
if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
this.reconnect();
}
}
/**
* Sets the current transport `socket`.
*
* @param {Function} fn - optional, callback
* @return self
* @public
*/
open(fn) {
if (~this._readyState.indexOf("open"))
return this;
this.engine = new Socket$1(this.uri, this.opts);
const socket = this.engine;
const self2 = this;
this._readyState = "opening";
this.skipReconnect = false;
const openSubDestroy = on(socket, "open", function() {
self2.onopen();
fn && fn();
});
const onError = (err2) => {
this.cleanup();
this._readyState = "closed";
this.emitReserved("error", err2);
if (fn) {
fn(err2);
} else {
this.maybeReconnectOnOpen();
}
};
const errorSub = on(socket, "error", onError);
if (false !== this._timeout) {
const timeout = this._timeout;
const timer = this.setTimeoutFn(() => {
openSubDestroy();
onError(new Error("timeout"));
socket.close();
}, timeout);
if (this.opts.autoUnref) {
timer.unref();
}
this.subs.push(() => {
this.clearTimeoutFn(timer);
});
}
this.subs.push(openSubDestroy);
this.subs.push(errorSub);
return this;
}
/**
* Alias for open()
*
* @return self
* @public
*/
connect(fn) {
return this.open(fn);
}
/**
* Called upon transport open.
*
* @private
*/
onopen() {
this.cleanup();
this._readyState = "open";
this.emitReserved("open");
const socket = this.engine;
this.subs.push(
on(socket, "ping", this.onping.bind(this)),
on(socket, "data", this.ondata.bind(this)),
on(socket, "error", this.onerror.bind(this)),
on(socket, "close", this.onclose.bind(this)),
// @ts-ignore
on(this.decoder, "decoded", this.ondecoded.bind(this))
);
}
/**
* Called upon a ping.
*
* @private
*/
onping() {
this.emitReserved("ping");
}
/**
* Called with data.
*
* @private
*/
ondata(data) {
try {
this.decoder.add(data);
} catch (e) {
this.onclose("parse error", e);
}
}
/**
* Called when parser fully decodes a packet.
*
* @private
*/
ondecoded(packet) {
nextTick(() => {
this.emitReserved("packet", packet);
}, this.setTimeoutFn);
}
/**
* Called upon socket error.
*
* @private
*/
onerror(err2) {
this.emitReserved("error", err2);
}
/**
* Creates a new socket for the given `nsp`.
*
* @return {Socket}
* @public
*/
socket(nsp, opts) {
let socket = this.nsps[nsp];
if (!socket) {
socket = new Socket2(this, nsp, opts);
this.nsps[nsp] = socket;
} else if (this._autoConnect && !socket.active) {
socket.connect();
}
return socket;
}
/**
* Called upon a socket close.
*
* @param socket
* @private
*/
_destroy(socket) {
const nsps = Object.keys(this.nsps);
for (const nsp of nsps) {
const socket2 = this.nsps[nsp];
if (socket2.active) {
return;
}
}
this._close();
}
/**
* Writes a packet.
*
* @param packet
* @private
*/
_packet(packet) {
const encodedPackets = this.encoder.encode(packet);
for (let i = 0; i < encodedPackets.length; i++) {
this.engine.write(encodedPackets[i], packet.options);
}
}
/**
* Clean up transport subscriptions and packet buffer.
*
* @private
*/
cleanup() {
this.subs.forEach((subDestroy) => subDestroy());
this.subs.length = 0;
this.decoder.destroy();
}
/**
* Close the current socket.
*
* @private
*/
_close() {
this.skipReconnect = true;
this._reconnecting = false;
this.onclose("forced close");
}
/**
* Alias for close()
*
* @private
*/
disconnect() {
return this._close();
}
/**
* Called when:
*
* - the low-level engine is closed
* - the parser encountered a badly formatted packet
* - all sockets are disconnected
*
* @private
*/
onclose(reason, description) {
var _a2;
this.cleanup();
(_a2 = this.engine) === null || _a2 === void 0 ? void 0 : _a2.close();
this.backoff.reset();
this._readyState = "closed";
this.emitReserved("close", reason, description);
if (this._reconnection && !this.skipReconnect) {
this.reconnect();
}
}
/**
* Attempt a reconnection.
*
* @private
*/
reconnect() {
if (this._reconnecting || this.skipReconnect)
return this;
const self2 = this;
if (this.backoff.attempts >= this._reconnectionAttempts) {
this.backoff.reset();
this.emitReserved("reconnect_failed");
this._reconnecting = false;
} else {
const delay = this.backoff.duration();
this._reconnecting = true;
const timer = this.setTimeoutFn(() => {
if (self2.skipReconnect)
return;
this.emitReserved("reconnect_attempt", self2.backoff.attempts);
if (self2.skipReconnect)
return;
self2.open((err2) => {
if (err2) {
self2._reconnecting = false;
self2.reconnect();
this.emitReserved("reconnect_error", err2);
} else {
self2.onreconnect();
}
});
}, delay);
if (this.opts.autoUnref) {
timer.unref();
}
this.subs.push(() => {
this.clearTimeoutFn(timer);
});
}
}
/**
* Called upon successful reconnect.
*
* @private
*/
onreconnect() {
const attempt = this.backoff.attempts;
this._reconnecting = false;
this.backoff.reset();
this.emitReserved("reconnect", attempt);
}
}
const cache = {};
function lookup(uri, opts) {
if (typeof uri === "object") {
opts = uri;
uri = void 0;
}
opts = opts || {};
const parsed = url(uri, opts.path || "/socket.io");
const source = parsed.source;
const id = parsed.id;
const path = parsed.path;
const sameNamespace = cache[id] && path in cache[id]["nsps"];
const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
let io;
if (newConnection) {
io = new Manager(source, opts);
} else {
if (!cache[id]) {
cache[id] = new Manager(source, opts);
}
io = cache[id];
}
if (parsed.query && !opts.query) {
opts.query = parsed.queryKey;
}
return io.socket(parsed.path, opts);
}
Object.assign(lookup, {
Manager,
Socket: Socket2,
io: lookup,
connect: lookup
});
const _InscriptionSDK = class _InscriptionSDK {
constructor(config) {
__publicField(this, "client");
__publicField(this, "config");
__publicField(this, "logger", Logger.getInstance());
__publicField(this, "socket", null);
__publicField(this, "socketConnected", false);
__publicField(this, "connectionMode", "auto");
__publicField(this, "wsBaseUrl", null);
this.config = config;
if (!config.apiKey) {
throw new ValidationError("API key is required");
}
if (!config.network) {
throw new ValidationError("Network is required");
}
const headers = {
"x-api-key": config.apiKey,
"Content-Type": "application/json"
};
this.client = axios.create({
baseURL: "https://v2-api.tier.bot/api",
headers
});
this.logger = Logger.getInstance();
if (config.wsBaseUrl) {
this.wsBaseUrl = config.wsBaseUrl;
}
this.connectionMode = config.connectionMode || "websocket";
if (!this.wsBaseUrl && this.connectionMode !== "http") {
this.fetchWebSocketServers().catch(
(err2) => this.logger.warn("Failed to fetch WebSocket servers:", err2)
);
}
}
async getFileMetadata(url2) {
try {
const response = await axios.get(url2);
const mimeType = response.headers["content-type"] || "";
return {
size: parseInt(response.headers["content-length"] || "0", 10),
mimeType
};
} catch (error) {
this.logger.error("Error fetching file metadata:", error);
throw new ValidationError("Unable to fetch file metadata");
}
}
/**
* Gets the MIME type for a file based on its extension.
* @param fileName - The name of the file.
* @returns The MIME type of the file.
* @throws ValidationError if the file has no extension.
*/
getMimeType(fileName) {
const extension = fileName.toLowerCase().split(".").pop();
if (!extension) {
throw new ValidationError("File must have an extension");
}
const mimeType = _InscriptionSDK.VALID_MIME_TYPES[extension];
if (!mimeType) {
throw new ValidationError(`Unsupported file type: ${extension}`);
}
return mimeType;
}
/**
* Validates the request object.
* @param request - The request object to validate.
* @throws ValidationError if the request is invalid.
*/
validateRequest(request) {
this.logger.debug("Validating request:", request);
if (!request.holderId || request.holderId.trim() === "") {
this.logger.warn("holderId is missing or empty");
throw new ValidationError("holderId is required");
}
if (!_InscriptionSDK.VALID_MODES.includes(request.mode)) {
throw new ValidationError(
`Invalid mode: ${request.mode}. Must be one of: ${_InscriptionSDK.VALID_MODES.join(", ")}`
);
}
if (request.mode === "hashinal") {
if (!request.jsonFileURL && !request.metadataObject) {
throw new ValidationError(
"Hashinal mode requires either jsonFileURL or metadataObject"
);
}
}
if (request.onlyJSONCollection && request.mode !== "hashinal-collection") {
throw new ValidationError(
"onlyJSONCollection can only be used with hashinal-collection mode"
);
}
this.validateFileInput(request.file);
}
/**
* Normalizes the MIME type to a standard format.
* @param mimeType - The MIME type to normalize.
* @returns The normalized MIME type.
*/
normalizeMimeType(mimeType) {
if (mimeType === "image/vnd.microsoft.icon") {
this.logger.debug(
"Normalizing MIME type from image/vnd.microsoft.icon to image/x-icon"
);
return "image/x-icon";
}
return mimeType;
}
validateMimeType(mimeType) {
const validMimeTypes = Object.values(_InscriptionSDK.VALID_MIME_TYPES);
if (validMimeTypes.includes(mimeType)) {
return true;
}
if (mimeType === "image/vnd.microsoft.icon") {
this.logger.debug(
"Accepting alternative MIME type for ICO: image/vnd.microsoft.icon"
);
return true;
}
return false;
}
validateFileInput(file) {
if (file.type === "base64") {
if (!file.base64) {
throw new ValidationError("Base64 data is required");
}
const base64Data = file.base64.replace(/^data:.*?;base64,/, "");
const size = Math.ceil(base64Data.length * 0.75);
if (size > _InscriptionSDK.MAX_BASE64_SIZE) {
throw new ValidationError(
`File size exceeds maximum limit of ${_InscriptionSDK.MAX_BASE64_SIZE / 1024 / 1024}MB`
);
}
const mimeType = file.mimeType || this.getMimeType(file.fileName);
if (!this.validateMimeType(mimeType)) {
throw new ValidationError(
"File must have one of the supported MIME types"
);
}
if (file.mimeType === "image/vnd.microsoft.icon") {
file.mimeType = this.normalizeMimeType(file.mimeType);
}
} else if (file.type === "url") {
if (!file.url) {
throw new ValidationError("URL is required");
}
}
}
async detectMimeTypeFromBase64(base64Data) {
if (base64Data.startsWith("data:")) {
const matches = base64Data.match(/^data:([^;]+);base64,/);
if (matches && matches.length > 1) {
return matches[1];
}
}
try {
const sanitizedBase64 = base64Data.replace(/\s/g, "");
const buffer2 = Buffer2.from(sanitizedBase64, "base64");
const typeResult = await fileTypeFromBuffer(buffer2);
return (typeResult == null ? void 0 : typeResult.mime) || "application/octet-stream";
} catch (err2) {
this.logger.warn("Failed to detect MIME type from buffer");
return "application/octet-stream";
}
}
/**
* Starts an inscription and returns the transaction bytes.
* @param request - The request object containing the file to inscribe and the client configuration
* @returns The transaction bytes of the started inscription
* @throws ValidationError if the request is invalid
* @throws Error if the inscription fails
*/
async startInscription(request) {
var _a2, _b2;
try {
this.validateRequest(request);
let mimeType = request.file.mimeType;
if (request.file.type === "url") {
const fileMetadata = await this.getFileMetadata(request.file.url);
mimeType = fileMetadata.mimeType || mimeType;
if (fileMetadata.size > _InscriptionSDK.MAX_URL_FILE_SIZE) {
throw new ValidationError(
`File size exceeds maximum URL file limit of ${_InscriptionSDK.MAX_URL_FILE_SIZE / 1024 / 1024}MB`
);
}
} else if (request.file.type === "base64") {
mimeType = await this.detectMimeTypeFromBase64(request.file.base64);
}
if (mimeType === "image/vnd.microsoft.icon") {
mimeType = this.normalizeMimeType(mimeType);
}
if (request.jsonFileURL) {
const jsonMetadata = await this.getFileMetadata(request.jsonFileURL);
if (jsonMetadata.mimeType !== "application/json") {
throw new ValidationError(
"JSON file must be of type application/json"
);
}
}
const requestBody = {
holderId: request.holderId,
mode: request.mode,
network: this.config.network,
onlyJSONCollection: request.onlyJSONCollection ? 1 : 0,
creator: request.creator,
description: request.description,
fileStandard: request.fileStandard,
metadataObject: request.metadataObject,
jsonFileURL: request.jsonFileURL
};
let response;
if (request.file.type === "url") {
response = await this.client.post("/inscriptions/start-inscription", {
...requestBody,
fileURL: request.file.url
});
} else {
response = await this.client.post("/inscriptions/start-inscription", {
...requestBody,
fileBase64: request.file.base64,
fileName: request.file.fileName,
fileMimeType: mimeType || this.getMimeType(request.file.fileName)
});
}
return response.data;
} catch (error) {
if (error instanceof ValidationError) {
throw error;
}
if (axios.isAxiosError(error)) {
throw new Error(
((_b2 = (_a2 = error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b2.message) || "Failed to start inscription"
);
}
throw error;
}
}
/**
* Executes a transaction with the provided transaction bytes,
* typically called after inscribing a file through `startInscription`.
* @param transactionBytes - The bytes of the transaction to execute.
* @param clientConfig - The configuration for the Hedera client.
* @returns The transaction receipt.
* @throws ValidationError if the transaction bytes are invalid.
* @throws Error if the execution fails.
*/
async executeTransaction(transactionBytes, clientConfig) {
var _a2, _b2;
try {
const client = clientConfig.network === "mainnet" ? Client.forMainnet() : Client.forTestnet();
const mirrorNode = new HederaMirrorNode(clientConfig.network);
const account = await mirrorNode.requestAccount(clientConfig.accountId);
const type = (_a2 = account == null ? void 0 : account.key) == null ? void 0 : _a2._type;
const keyIsString = typeof clientConfig.privateKey === "string";
let privateKey;
if (type && keyIsString) {
privateKey = ((_b2 = type == null ? void 0 : type.toLowerCase()) == null ? void 0 : _b2.includes("ecdsa")) ? PrivateKey.fromStringECDSA(clientConfig.privateKey) : PrivateKey.fromStringED25519(clientConfig.privateKey);
} else if (!type && keyIsString) {
const keyType = keyIsString ? detectKeyTypeFromString(clientConfig.privateKey) : void 0;
privateKey = (keyType == null ? void 0 : keyType.detectedType) === "ed25519" ? PrivateKey.fromStringED25519(clientConfig.privateKey) : PrivateKey.fromStringECDSA(clientConfig.privateKey);
} else {
privateKey = clientConfig.privateKey;
}
client.setOperator(clientConfig.accountId, privateKey);
const transaction = TransferTransaction.fromBytes(
Buffer2.from(transactionBytes, "base64")
);
const signedTransaction = await transaction.sign(privateKey);
const executeTx = await signedTransaction.execute(client);
const receipt = await executeTx.getReceipt(client);
const status = receipt.status.toString();
if (status !== "SUCCESS") {
throw new Error(`Transaction failed with status: ${status}`);
}
return executeTx.transactionId.toString();
} catch (error) {
throw new Error(
`Failed to execute transaction: ${error instanceof Error ? error.message : "Unknown error"}`
);
}
}
/**
* Executes a transaction with the provided transaction bytes using a Signer,
* typically called after inscribing a file through `startInscription`.
* @param transactionBytes - The bytes of the transaction to execute.
* @param clientConfig - The configuration for the Hedera client.
* @returns The transaction receipt.
* @throws ValidationError if the transaction bytes are invalid.
* @throws Error if the execution fails.
*/
async executeTransactionWithSigner(transactionBytes, signer) {
try {
const transaction = TransferTransaction.fromBytes(
Buffer2.from(transactionBytes, "base64")
);
const executeTx = await transaction.executeWithSigner(signer);
const receipt = await executeTx.getReceiptWithSigner(signer);
const status = receipt.status.toString();
if (status !== "SUCCESS") {
throw new Error(`Transaction failed with status: ${status}`);
}
return executeTx.transactionId.toString();
} catch (error) {
throw new Error(
`Failed to execute transaction: ${error instanceof Error ? error.message : "Unknown error"}`
);
}
}
/**
* Inscribes a file and executes the transaction. Note that base64 files are limited to 2MB, while URL files are limited to 100MB.
* @param request - The request object containing the file to inscribe and the client configuration
* @param clientConfig - The configuration for the Hedera network and account
* @returns The transaction ID of the executed transaction
* @throws ValidationError if the request is invalid
* @throws Error if the transaction execution fails
*/
async inscribeAndExecute(request, clientConfig, progressCallback, options) {
const waitForCompletion = (options == null ? void 0 : options.waitForCompletion) ?? true;
const maxWaitTime = (options == null ? void 0 : options.maxWaitTime) ?? 12e4;
const checkInterval = (options == null ? void 0 : options.checkInterval) ?? 2e3;
this.logger.debug("inscribeAndExecute called", {
hasProgressCallback: !!progressCallback,
connectionMode: this.connectionMode,
wsBaseUrl: this.wsBaseUrl
});
if (this.connectionMode !== "http") {
const useWebSocket = this.connectionMode === "websocket" || this.connectionMode === "auto" && await this.detectBestConnection();
if (useWebSocket) {
try {
const wsResult = await this.inscribeViaWebSocket(
request,
clientConfig,
progressCallback
);
return wsResult;
} catch (error) {
this.logger.error(
"WebSocket inscription failed, falling back to HTTP:",
error
);
throw error;
}
} else {
this.logger.info(
`Not using WebSocket: useWebSocket=${useWebSocket}, wsBaseUrl=${this.wsBaseUrl}`
);
}
} else {
this.logger.info(
`Not using WebSocket: hasCallback=${!!progressCallback}, connectionMode=${this.connectionMode}`
);
}
const inscriptionResponse = await this.startInscription(request);
if (!inscriptionResponse.transactionBytes) {
this.logger.error(
"No transaction bytes returned from inscription request",
inscriptionResponse
);
throw new Error("No transaction bytes returned from inscription request");
}
this.logger.info("executing transaction");
const transactionId = await this.executeTransaction(
inscriptionResponse.transactionBytes,
clientConfig
);
const result = {
jobId: inscriptionResponse.tx_id,
transactionId
};
if (waitForCompletion) {
if (progressCallback) {
progressCallback({
stage: "confirming",
message: "Transaction executed, waiting for inscription to complete",
progressPercent: 5
});
}
const maxAttempts = Math.floor(maxWaitTime / checkInterval);
const finalResult = await this.waitForInscription(
transactionId,
maxAttempts,
checkInterval,
true,
progressCallback
);
return {
...result,
topicId: finalResult.topic_id,
status: finalResult.status,
completed: finalResult.completed
};
}
return result;
}
async fetchWebSocketServers() {
try {
const response = await this.client.get("/inscriptions/websocket-servers");
const { servers, recommended } = response.data;
if (recommended) {
this.wsBaseUrl = recommended;
} else if (servers && servers.length > 0) {
const activeServers = servers.filter((s) => s.status === "active");
if (activeServers.length > 0) {
const selectedServer = activeServers[0];
this.wsBaseUrl = selectedServer.url;
}
}
} catch (error) {
this.logger.debug(
"Could not fetch WebSocket servers, will use HTTP only"
);
}
}
async detectBestConnection() {
if (!this.wsBaseUrl) return false;
try {
const testSocket = lookup(this.wsBaseUrl, {
auth: { apiKey: this.config.apiKey },
transports: ["websocket"],
timeout: 3e3
});
return new Promise((resolve) => {
const timeout = setTimeout(() => {
testSocket.disconnect();
resolve(false);
}, 3e3);
testSocket.on("connect", () => {
clearTimeout(timeout);
testSocket.disconnect();
resolve(true);
});
testSocket.on("connect_error", () => {
clearTimeout(timeout);
testSocket.disconnect();
resolve(false);
});
});
} catch (e) {
return false;
}
}
async inscribeViaWebSocket(request, clientConfig, progressCallback) {
if (!this.wsBaseUrl) {
const response = await this.client.get("/inscriptions/websocket-servers");
const recommended = response.data.recommended;
if (!recommended) {
throw new Error("No WebSocket servers available");
}
this.wsBaseUrl = recommended;
}
await this.connectWebSocket();
return new Promise((resolve, reject) => {
if (!this.socket) {
return reject(new Error("WebSocket not connected"));
}
let jobId;
let transactionId;
let topicId;
let timeoutHandle;
const cleanup = () => {
var _a2, _b2, _c;
if (timeoutHandle) clearTimeout(timeoutHandle);
(_a2 = this.socket) == null ? void 0 : _a2.off("inscription-progress", progressHandler);
(_b2 = this.socket) == null ? void 0 : _b2.off("inscription-complete", completeHandler);
(_c = this.socket) == null ? void 0 : _c.off("inscription-error", errorHandler);
};
const TIMEOUT_MS = 6e4;
timeoutHandle = setTimeout(() => {
this.logger.error(
`WebSocket inscription timeout after ${TIMEOUT_MS / 1e3} seconds`,
{
jobId,
transactionId,
lastTopicId: topicId
}
);
cleanup();
resolve({
jobId,
transactionId,
topicId,
topic_id: topicId,
status: "timeout",
completed: false
});
}, TIMEOUT_MS);
const completeHandler = (data) => {
cleanup();
resolve({
jobId,
transactionId,
topicId: data.topicId || data.topic_id,
topic_id: data.topicId || data.topic_id,
status: "completed",
completed: true
});
};
const errorHandler = (data) => {
cleanup();
reject(new Error(data.error || "Inscription failed"));
};
const progressHandler = (data) => {
this.logger.debug("Progress event received:", {
jobId: data.jobId,
status: data.status,
progress: data.progress,
topicId: data.topicId || data.topic_id,
topic_id: data.topicId || data.topic_id
});
if (data.topicId || data.topic_id) {
topicId = data.topicId || data.topic_id;
}
if (progressCallback) {
progressCallback({
stage: data.status === "completed" ? "completed" : "confirming",
message: `Processing inscription: ${data.status}`,
progressPercent: data.progress || 0,
details: data
});
}
if (data.status === "completed" || data.progress === 100) {
this.logger.info("Inscription completed via progress handler", {
status: data.status,
progress: data.progress,
topicId: data.topicId || data.topic_id || topicId,
topic_id: data.topicId || data.topic_id || topicId
});
cleanup();
resolve({
jobId,
transactionId,
topicId: data.topicId || data.topic_id || topicId,
topic_id: data.topicId || data.topic_id || topicId,
status: "completed",
completed: true
});
}
};
this.socket.on("inscription-progress", progressHandler);
this.socket.on("inscription-complete", completeHandler);
this.socket.on("inscription-error", errorHandler);
this.socket.emit(
"start-inscription",
{
...request,
network: this.config.network
},
async (response) => {
if (!response.success) {
cleanup();
return reject(new Error(response.error || "Inscription failed"));
}
try {
if (!response.transactionBytes) {
throw new Error(
"No transaction bytes returned from WebSocket inscription"
);
}
transactionId = await this.executeTransaction(
response.transactionBytes,
clientConfig
);
jobId = response.jobId || response.tx_id;
if (!jobId) {
throw new Error("No job ID returned from WebSocket inscription");
}
if (progressCallback) {
progressCallback({
stage: "confirming",
message: "Transaction executed, inscribing to HCS...",
progressPercent: 5
});
}
this.logger.info(
"Transaction executed, waiting for inscription completion...",
{
jobId,
transactionId
}
);
} catch (error) {
cleanup();
reject(error);
}
}
);
});
}
async connectWebSocket() {
if (this.socketConnected && this.socket) return;
if (!this.wsBaseUrl) {
throw new Error("WebSocket URL not configured");
}
return new Promise((resolve, reject) => {
this.socket = lookup(this.wsBaseUrl, {
auth: { apiKey: this.config.apiKey },
transports: ["websocket", "polling"]
});
const timeout = setTimeout(() => {
reject(new Error("WebSocket connection timeout"));
}, 1e4);
this.socket.on("connect", () => {
clearTimeout(timeout);
this.socketConnected = true;
this.logger.info("WebSocket connected");
resolve();
});
this.socket.on("connect_error", (error) => {
clearTimeout(timeout);
this.socketConnected = false;
reject(new Error(`WebSocket connection failed: ${error.message}`));
});
this.socket.on("disconnect", () => {
this.socketConnected = false;
this.logger.info("WebSocket disconnected");
});
});
}
/**
* Disconnects the WebSocket connection if active
*/
disconnect() {
if (this.socket) {
this.socket.disconnect();
this.socket = null;
this.socketConnected = false;
}
}
/**
* Inscribes a file and executes the transaction. Note that base64 files are limited to 2MB, while URL files are limited to 100MB.
* @param request - The request object containing the file to inscribe and the client configuration
* @param clientConfig - The configuration for the Hedera network and account
* @returns The transaction ID of the executed transaction
* @throws ValidationError if the request is invalid
* @throws Error if the transaction execution fails
*/
async inscribe(request, signer) {
const inscriptionResponse = await this.startInscription(request);
if (!inscriptionResponse.transactionBytes) {
this.logger.error(
"No transaction bytes returned from inscription request",
inscriptionResponse
);
throw new Error("No transaction bytes returned from inscription request");
}
this.logger.info("executing transaction");
const transactionId = await this.executeTransactionWithSigner(
inscriptionResponse.transactionBytes,
signer
);
return {
jobId: inscriptionResponse.tx_id,
transactionId
};
}
async retryWithBackoff(operation, maxRetries = 3, baseDelay = 1e3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
if (attempt === maxRetries - 1) {
throw error;
}
const delay = baseDelay * Math.pow(2, attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
this.logger.debug(
`Retry attempt ${attempt + 1}/${maxRetries} after ${delay}ms delay`
);
}
}
throw new Error("Retry operation failed");
}
/**
* Retrieves an inscription by its transaction id. Call this function on an interval
* so you can retrieve the status. Store the transaction id in your database if you
* need to reference it later on
* @param txId - The ID of the inscription to retrieve
* @returns The retrieved inscription
* @throws ValidationError if the ID is invalid
* @throws Error if the retrieval fails
*/
async retrieveInscription(txId) {
if (!txId) {
throw new ValidationError("Transaction ID is required");
}
try {
const formattedTransactionId = txId.includes("@") ? `${txId.split("@")[0]}-${txId.split("@")[1].replace(/\./g, "-")}` : txId;
return await this.retryWithBackoff(async () => {
const response = await this.client.get(
`/inscriptions/retrieve-inscription?id=${formattedTransactionId}`
);
const result = response.data;
const isCompleted = result.completed || result.status.toLowerCase() === "completed";
return { ...result, completed: isCompleted, jobId: result.id };
});
} catch (error) {
this.logger.error("Failed to retrieve inscription:", error);
throw error;
}
}
/**
* Fetch inscription numbers with optional filtering and sorting
* @param params Query parameters for filtering and sorting inscriptions
* @returns Array of inscription details
*/
async getInscriptionNumbers(params = {}) {
try {
const response = await this.client.get("/inscriptions/numbers", {
params
});
return response.data;
} catch (error) {
this.logger.error("Failed to fetch inscription numbers:", error);
throw error;
}
}
/**
* Authenticates the SDK with the provided configuration
* @param config - The configuration for authentication
* @returns The authentication result
*/
static async authenticate(config) {
const auth = new Auth(config);
return auth.authenticate();
}
/**
* Creates an instance of the InscriptionSDK with authentication.
* Useful for cases where you don't have an API key but need to authenticate from server-side
* with a private key.
* @param config - The configuration for authentication
* @returns An instance of the InscriptionSDK
*/
static async createWithAuth(config) {
const auth = config.type === "client" ? new ClientAuth({
...config,
logger: Logger.getInstance()
}) : new Auth(config);
const { apiKey } = await auth.authenticate();
return new _InscriptionSDK({
apiKey,
network: config.network || "mainnet",
wsBaseUrl: config.wsBaseUrl,
connectionMode: config.connectionMode || "websocket"
});
}
async waitForInscription(txId, maxAttempts = 30, intervalMs = 4e3, checkCompletion = false, progressCallback) {
var _a2;
let attempts = 0;
let highestPercentSoFar = 0;
const reportProgress = (stage, message, percent, details) => {
if (progressCallback) {
try {
highestPercentSoFar = Math.max(highestPercentSoFar, percent);
progressCallback({
stage,
message,
progressPercent: highestPercentSoFar,
details: {
...details,
txId,
currentAttempt: attempts,
maxAttempts
}
});
} catch (err2) {
this.logger.warn(`Error in progress callback: ${err2}`);
}
}
};
reportProgress("confirming", "Starting inscription verification", 0);
while (attempts < maxAttempts) {
reportProgress(
"confirming",
`Verifying inscription status (attempt ${attempts + 1}/${maxAttempts})`,
5,
{ attempt: attempts + 1 }
);
const result = await this.retrieveInscription(txId);
if (result.error) {
reportProgress("verifying", `Error: ${result.error}`, 100, {
error: result.error
});
throw new Error(result.error);
}
let progressPercent = 5;
const isCompleted = result.completed || result.status.toLowerCase() === "completed";
if (result.messages !== void 0 && result.maxMessages !== void 0 && result.maxMessages > 0) {
progressPercent = Math.min(
95,
5 + result.messages / result.maxMessages * 90
);
if (isCompleted) {
progressPercent = 100;
}
} else if (result.status === "processing") {
progressPercent = 10;
} else if (isCompleted) {
progressPercent = 100;
}
reportProgress(
isCompleted ? "completed" : "confirming",
isCompleted ? "Inscription completed successfully" : `Processing inscription (${result.status})`,
progressPercent,
{
status: result.status,
messagesProcessed: result.messages,
maxMessages: result.maxMessages,
messageCount: result.messages,
completed: isCompleted,
confirmedMessages: result.confirmedMessages,
result
}
);
const isHashinal = result.mode === "hashinal";
const isHashinalCollection = result.mode === "hashinal-collection";
const isDynamic = ((_a2 = result.fileStandard) == null ? void 0 : _a2.toString()) === "6";
if (isHashinalCollection && isCompleted) {
if (!checkCompletion || isCompleted) {
reportProgress(
"completed",
"Inscription verification complete",
100,
{ result }
);
return result;
}
}
if (isHashinal && result.topic_id && result.jsonTopicId) {
if (!checkCompletion || isCompleted) {
reportProgress(
"completed",
"Inscription verification complete",
100,
{ result }
);
return result;
}
}
if (!isHashinal && !isDynamic && result.topic_id) {
if (!checkCompletion || isCompleted) {
reportProgress(
"completed",
"Inscription verification complete",
100,
{ result }
);
return result;
}
}
if (isDynamic && result.topic_id && result.jsonTopicId && result.registryTopicId) {
if (!checkCompletion || isCompleted) {
reportProgress(
"completed",
"Inscription verification complete",
100,
{ result }
);
return result;
}
}
await new Promise((resolve) => setTimeout(resolve, intervalMs));
attempts++;
}
reportProgress(
"verifying",
`Inscription ${txId} did not complete within ${maxAttempts} attempts`,
100,
{ timedOut: true }
);
throw new Error(
`Inscription ${txId} did not complete within ${maxAttempts} attempts`
);
}
/**
* Fetch inscriptions owned by a specific holder
* @param params Query parameters for retrieving holder's inscriptions
* @returns Array of inscription details owned by the holder
*/
async getHolderInscriptions(params) {
var _a2, _b2;
if (!params.holderId) {
throw new ValidationError("Holder ID is required");
}
try {
const queryParams = {
holderId: params.holderId
};
if (params.includeCollections) {
queryParams.includeCollections = "1";
}
const response = await this.client.get(
"/inscriptions/holder-inscriptions",
{
params: queryParams
}
);
return response.data;
} catch (error) {
this.logger.error("Failed to fetch holder inscriptions:", error);
if (axios.isAxiosError(error)) {
throw new Error(
((_b2 = (_a2 = error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b2.message) || "Failed to fetch holder inscriptions"
);
}
throw error;
}
}
};
__publicField(_InscriptionSDK, "VALID_MODES", [
"file",
"upload",
"hashinal",
"hashinal-collection"
]);
__publicField(_InscriptionSDK, "MAX_BASE64_SIZE", 2 * 1024 * 1024);
__publicField(_InscriptionSDK, "MAX_URL_FILE_SIZE", 100 * 1024 * 1024);
__publicField(_InscriptionSDK, "VALID_MIME_TYPES", {
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
gif: "image/gif",
ico: "image/x-icon",
heic: "image/heic",
heif: "image/heif",
bmp: "image/bmp",
webp: "image/webp",
tiff: "image/tiff",
tif: "image/tiff",
svg: "image/svg+xml",
mp4: "video/mp4",
webm: "video/webm",
mp3: "audio/mpeg",
pdf: "application/pdf",
doc: "application/msword",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
xls: "application/vnd.ms-excel",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
ppt: "application/vnd.ms-powerpoint",
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
html: "text/html",
htm: "text/html",
css: "text/css",
php: "application/x-httpd-php",
java: "text/x-java-source",
js: "application/javascript",
mjs: "application/javascript",
csv: "text/csv",
json: "application/json",
txt: "text/plain",
glb: "model/gltf-binary",
wav: "audio/wav",
ogg: "audio/ogg",
oga: "audio/ogg",
flac: "audio/flac",
aac: "audio/aac",
m4a: "audio/mp4",
avi: "video/x-msvideo",
mov: "video/quicktime",
mkv: "video/x-matroska",
m4v: "video/mp4",
mpg: "video/mpeg",
mpeg: "video/mpeg",
ts: "application/typescript",
zip: "application/zip",
rar: "application/vnd.rar",
tar: "application/x-tar",
gz: "application/gzip",
"7z": "application/x-7z-compressed",
xml: "application/xml",
yaml: "application/yaml",
yml: "application/yaml",
md: "text/markdown",
markdown: "text/markdown",
rtf: "application/rtf",
gltf: "model/gltf+json",
usdz: "model/vnd.usdz+zip",
obj: "model/obj",
stl: "model/stl",
fbx: "application/octet-stream",
ttf: "font/ttf",
otf: "font/otf",
woff: "font/woff",
woff2: "font/woff2",
eot: "application/vnd.ms-fontobject",
psd: "application/vnd.adobe.photoshop",
ai: "application/postscript",
eps: "application/postscript",
ps: "application/postscript",
sqlite: "application/x-sqlite3",
db: "application/x-sqlite3",
apk: "application/vnd.android.package-archive",
ics: "text/calendar",
vcf: "text/vcard",
py: "text/x-python",
rb: "text/x-ruby",
go: "text/x-go",
rs: "text/x-rust",
typescript: "application/typescript",
jsx: "text/jsx",
tsx: "text/tsx",
sql: "application/sql",
toml: "application/toml",
avif: "image/avif",
jxl: "image/jxl",
weba: "audio/webm",
wasm: "application/wasm"
});
let InscriptionSDK = _InscriptionSDK;
export {
Auth,
ClientAuth,
InscriptionSDK,
ValidationError
};
//# sourceMappingURL=inscription-sdk.es.js.map