diff --git a/.gitignore b/.gitignore index c4abefd7..d0e0cde4 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,3 @@ bz2.wasm /src/public/data/players /src/public/data/src - -LoginThread.js -worker.js diff --git a/src/public/225/GO-DOWNLOAD-rs2launch b/src/public/225/GO-DOWNLOAD-rs2launch new file mode 100644 index 00000000..e69de29b diff --git a/src/public/225/archives/config b/src/public/225/archives/config new file mode 100644 index 00000000..0850a437 Binary files /dev/null and b/src/public/225/archives/config differ diff --git a/src/public/225/archives/crc b/src/public/225/archives/crc new file mode 100644 index 00000000..567b4944 Binary files /dev/null and b/src/public/225/archives/crc differ diff --git a/src/public/225/archives/interface b/src/public/225/archives/interface new file mode 100644 index 00000000..c19ec0a6 Binary files /dev/null and b/src/public/225/archives/interface differ diff --git a/src/public/225/archives/media b/src/public/225/archives/media new file mode 100644 index 00000000..e88e2f73 Binary files /dev/null and b/src/public/225/archives/media differ diff --git a/src/public/225/archives/models b/src/public/225/archives/models new file mode 100644 index 00000000..4e0962e6 Binary files /dev/null and b/src/public/225/archives/models differ diff --git a/src/public/225/archives/sounds b/src/public/225/archives/sounds new file mode 100644 index 00000000..451e6978 Binary files /dev/null and b/src/public/225/archives/sounds differ diff --git a/src/public/225/archives/textures b/src/public/225/archives/textures new file mode 100644 index 00000000..7012cb72 Binary files /dev/null and b/src/public/225/archives/textures differ diff --git a/src/public/225/archives/title b/src/public/225/archives/title new file mode 100644 index 00000000..09c440b0 Binary files /dev/null and b/src/public/225/archives/title differ diff --git a/src/public/225/archives/wordenc b/src/public/225/archives/wordenc new file mode 100644 index 00000000..85b8129d Binary files /dev/null and b/src/public/225/archives/wordenc differ diff --git a/src/public/225/runescape.jar b/src/public/225/runescape.jar new file mode 100644 index 00000000..cb5e74bf Binary files /dev/null and b/src/public/225/runescape.jar differ diff --git a/src/public/SCC1_Florestan.sf2 b/src/public/SCC1_Florestan.sf2 new file mode 100644 index 00000000..74f5e7dd Binary files /dev/null and b/src/public/SCC1_Florestan.sf2 differ diff --git a/src/public/app.js b/src/public/app.js deleted file mode 100644 index 75e791dd..00000000 --- a/src/public/app.js +++ /dev/null @@ -1,23382 +0,0 @@ -var __require = (x => - typeof require !== 'undefined' - ? require - : typeof Proxy !== 'undefined' - ? new Proxy(x, { - get: (a, b) => (typeof require !== 'undefined' ? require : a)[b] - }) - : x)(function (x) { - if (typeof require !== 'undefined') return require.apply(this, arguments); - throw Error('Dynamic require of "' + x + '" is not supported'); -}); - -// node_modules/kleur/index.mjs -var run = function (arr, str) { - let i = 0, - tmp, - beg = '', - end = ''; - for (; i < arr.length; i++) { - tmp = arr[i]; - beg += tmp.open; - end += tmp.close; - if (!!~str.indexOf(tmp.close)) { - str = str.replace(tmp.rgx, tmp.close + tmp.open); - } - } - return beg + str + end; -}; -var chain = function (has, keys) { - let ctx = {has, keys}; - ctx.reset = $.reset.bind(ctx); - ctx.bold = $.bold.bind(ctx); - ctx.dim = $.dim.bind(ctx); - ctx.italic = $.italic.bind(ctx); - ctx.underline = $.underline.bind(ctx); - ctx.inverse = $.inverse.bind(ctx); - ctx.hidden = $.hidden.bind(ctx); - ctx.strikethrough = $.strikethrough.bind(ctx); - ctx.black = $.black.bind(ctx); - ctx.red = $.red.bind(ctx); - ctx.green = $.green.bind(ctx); - ctx.yellow = $.yellow.bind(ctx); - ctx.blue = $.blue.bind(ctx); - ctx.magenta = $.magenta.bind(ctx); - ctx.cyan = $.cyan.bind(ctx); - ctx.white = $.white.bind(ctx); - ctx.gray = $.gray.bind(ctx); - ctx.grey = $.grey.bind(ctx); - ctx.bgBlack = $.bgBlack.bind(ctx); - ctx.bgRed = $.bgRed.bind(ctx); - ctx.bgGreen = $.bgGreen.bind(ctx); - ctx.bgYellow = $.bgYellow.bind(ctx); - ctx.bgBlue = $.bgBlue.bind(ctx); - ctx.bgMagenta = $.bgMagenta.bind(ctx); - ctx.bgCyan = $.bgCyan.bind(ctx); - ctx.bgWhite = $.bgWhite.bind(ctx); - return ctx; -}; -var init = function (open, close) { - let blk = { - open: `\x1B[${open}m`, - close: `\x1B[${close}m`, - rgx: new RegExp(`\\x1b\\[${close}m`, 'g') - }; - return function (txt) { - if (this !== undefined && this.has !== undefined) { - !!~this.has.indexOf(open) || (this.has.push(open), this.keys.push(blk)); - return txt === undefined ? this : $.enabled ? run(this.keys, txt + '') : txt + ''; - } - return txt === undefined ? chain([open], [blk]) : $.enabled ? run([blk], txt + '') : txt + ''; - }; -}; -var FORCE_COLOR; -var NODE_DISABLE_COLORS; -var NO_COLOR; -var TERM; -var isTTY = true; -if (typeof process !== 'undefined') { - ({FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM} = process.env || {}); - isTTY = process.stdout && process.stdout.isTTY; -} -var $ = { - enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && ((FORCE_COLOR != null && FORCE_COLOR !== '0') || isTTY), - reset: init(0, 0), - bold: init(1, 22), - dim: init(2, 22), - italic: init(3, 23), - underline: init(4, 24), - inverse: init(7, 27), - hidden: init(8, 28), - strikethrough: init(9, 29), - black: init(30, 39), - red: init(31, 39), - green: init(32, 39), - yellow: init(33, 39), - blue: init(34, 39), - magenta: init(35, 39), - cyan: init(36, 39), - white: init(37, 39), - gray: init(90, 39), - grey: init(90, 39), - bgBlack: init(40, 49), - bgRed: init(41, 49), - bgGreen: init(42, 49), - bgYellow: init(43, 49), - bgBlue: init(44, 49), - bgMagenta: init(45, 49), - bgCyan: init(46, 49), - bgWhite: init(47, 49) -}; -var kleur_default = $; - -// src/jagex2/jstring/JString.ts -function toBase37(string) { - string = string.trim(); - let l = 0n; - for (let i = 0; i < string.length && i < 12; i++) { - const c = string.charCodeAt(i); - l *= 37n; - if (c >= 65 && c <= 90) { - l += BigInt(c + 1 - 65); - } else if (c >= 97 && c <= 122) { - l += BigInt(c + 1 - 97); - } else if (c >= 48 && c <= 57) { - l += BigInt(c + 27 - 48); - } - } - return l; -} -function fromBase37(value) { - if (value < 0n || value >= 6582952005840035281n) { - return 'invalid_name'; - } - if (value % 37n === 0n) { - return 'invalid_name'; - } - let len = 0; - const chars = Array(12); - while (value !== 0n) { - const l1 = value; - value /= 37n; - chars[11 - len++] = BASE37_LOOKUP[Number(l1 - value * 37n)]; - } - return chars.slice(12 - len).join(''); -} -function toTitleCase(str) { - return str.replace(/\w\S*/g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()); -} -function toSafeName(name) { - return fromBase37(toBase37(name)); -} -function toDisplayName(name) { - return toTitleCase(toSafeName(name).replaceAll('_', ' ')); -} -var BASE37_LOOKUP = ['_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; - -// src/jagex2/datastruct/Linkable.ts -class Linkable { - key; - next; - prev; - constructor() { - this.key = 0n; - this.next = this; - this.prev = this; - } - unlink() { - if (!this.prev || !this.next) { - return; - } - this.prev.next = this.next; - this.next.prev = this.prev; - this.next = null; - this.prev = null; - } -} - -// src/jagex2/datastruct/LinkList.ts -class LinkList { - sentinel; - cursor = null; - constructor() { - const head = new Linkable(); - head.next = head; - head.prev = head; - this.sentinel = head; - } - addTail(node) { - if (node.prev) { - node.unlink(); - } - node.prev = this.sentinel.prev; - node.next = this.sentinel; - if (node.prev) { - node.prev.next = node; - } - node.next.prev = node; - } - addHead(node) { - if (node.prev) { - node.unlink(); - } - node.prev = this.sentinel; - node.next = this.sentinel.next; - node.prev.next = node; - if (node.next) { - node.next.prev = node; - } - } - removeHead() { - const node = this.sentinel.next; - if (node === this.sentinel) { - return null; - } - node?.unlink(); - return node; - } - head() { - const node = this.sentinel.next; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.next || null; - return node; - } - tail() { - const node = this.sentinel.prev; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.prev || null; - return node; - } - next() { - const node = this.cursor; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.next || null; - return node; - } - prev() { - const node = this.cursor; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.prev || null; - return node; - } - clear() { - while (true) { - const node = this.sentinel.next; - if (node === this.sentinel) { - return; - } - node?.unlink(); - } - } -} - -// src/jagex2/datastruct/Hashable.ts -class Hashable extends Linkable { - nextHashable; - prevHashable; - constructor() { - super(); - this.nextHashable = this; - this.prevHashable = this; - } - uncache() { - if (!this.prevHashable || !this.nextHashable) { - return; - } - this.prevHashable.nextHashable = this.nextHashable; - this.nextHashable.prevHashable = this.prevHashable; - this.nextHashable = null; - this.prevHashable = null; - } -} - -// src/jagex2/io/Packet.ts -class Packet extends Hashable { - static crctable = new Int32Array(256); - static bitmask = new Uint32Array(33); - static crc32b = 3988292384; - static { - for (let i = 0; i < 32; i++) { - this.bitmask[i] = (1 << i) - 1; - } - this.bitmask[32] = 4294967295; - for (let b = 0; b < 256; b++) { - let remainder = b; - for (let bit = 0; bit < 8; bit++) { - if ((remainder & 1) == 1) { - remainder = (remainder >>> 1) ^ this.crc32b; - } else { - remainder >>>= 1; - } - } - this.crctable[b] = remainder; - } - } - static getcrc(src, offset, length) { - let crc = 4294967295; - for (let i = offset; i < length; i++) { - crc = (crc >>> 8) ^ this.crctable[(crc ^ src[i]) & 255]; - } - return ~crc; - } - static checkcrc(src, offset, length, expected = 0) { - const checksum = Packet.getcrc(src, offset, length); - return checksum == expected; - } - static alloc(type) { - let packet = null; - if (type === 0 && this.cacheMinCount > 0) { - packet = this.cacheMin.removeHead(); - this.cacheMinCount--; - } else if (type === 1 && this.cacheMidCount > 0) { - packet = this.cacheMid.removeHead(); - this.cacheMidCount--; - } else if (type === 2 && this.cacheMaxCount > 0) { - packet = this.cacheMax.removeHead(); - this.cacheMaxCount--; - } else if (type === 3 && this.cacheBigCount > 0) { - packet = this.cacheBig.removeHead(); - this.cacheBigCount--; - } else if (type === 4 && this.cacheHugeCount > 0) { - packet = this.cacheHuge.removeHead(); - this.cacheHugeCount--; - } else if (type === 5 && this.cacheUnimaginableCount > 0) { - packet = this.cacheUnimaginable.removeHead(); - this.cacheUnimaginableCount--; - } - if (packet !== null) { - packet.pos = 0; - packet.bitPos = 0; - return packet; - } - if (type === 0) { - return new Packet(new Uint8Array(100)); - } else if (type === 1) { - return new Packet(new Uint8Array(5000)); - } else if (type === 2) { - return new Packet(new Uint8Array(30000)); - } else if (type === 3) { - return new Packet(new Uint8Array(1e5)); - } else if (type === 4) { - return new Packet(new Uint8Array(500000)); - } else if (type === 5) { - return new Packet(new Uint8Array(2000000)); - } else { - return new Packet(new Uint8Array(type)); - } - } - static async load(path, seekToEnd = false) { - const packet = new Packet(new Uint8Array(await (await fetch(path)).arrayBuffer())); - if (seekToEnd) { - packet.pos = packet.data.length; - } - return packet; - } - static cacheMinCount = 0; - static cacheMidCount = 0; - static cacheMaxCount = 0; - static cacheBigCount = 0; - static cacheHugeCount = 0; - static cacheUnimaginableCount = 0; - static cacheMin = new LinkList(); - static cacheMid = new LinkList(); - static cacheMax = new LinkList(); - static cacheBig = new LinkList(); - static cacheHuge = new LinkList(); - static cacheUnimaginable = new LinkList(); - data; - #view; - pos; - bitPos; - constructor(src) { - super(); - this.data = src; - this.#view = new DataView(this.data.buffer); - this.pos = 0; - this.bitPos = 0; - } - get available() { - return this.data.length - this.pos; - } - get length() { - return this.data.length; - } - release() { - this.pos = 0; - this.bitPos = 0; - if (this.data.length === 100 && Packet.cacheMinCount < 1000) { - Packet.cacheMin.addTail(this); - Packet.cacheMinCount++; - } else if (this.data.length === 5000 && Packet.cacheMidCount < 250) { - Packet.cacheMid.addTail(this); - Packet.cacheMidCount++; - } else if (this.data.length === 30000 && Packet.cacheMaxCount < 50) { - Packet.cacheMax.addTail(this); - Packet.cacheMaxCount++; - } else if (this.data.length === 1e5 && Packet.cacheBigCount < 10) { - Packet.cacheBig.addTail(this); - Packet.cacheBigCount++; - } else if (this.data.length === 500000 && Packet.cacheHugeCount < 5) { - Packet.cacheHuge.addTail(this); - Packet.cacheHugeCount++; - } else if (this.data.length === 2000000 && Packet.cacheUnimaginableCount < 2) { - Packet.cacheUnimaginable.addTail(this); - Packet.cacheUnimaginableCount++; - } - } - p1(value) { - this.#view.setUint8(this.pos++, value); - } - p2(value) { - this.#view.setUint16(this.pos, value); - this.pos += 2; - } - ip2(value) { - this.#view.setUint16(this.pos, value, true); - this.pos += 2; - } - p3(value) { - this.#view.setUint8(this.pos++, value >> 16); - this.#view.setUint16(this.pos, value); - this.pos += 2; - } - p4(value) { - this.#view.setInt32(this.pos, value); - this.pos += 4; - } - ip4(value) { - this.#view.setInt32(this.pos, value, true); - this.pos += 4; - } - p8(value) { - this.#view.setBigInt64(this.pos, value); - this.pos += 8; - } - pbool(value) { - this.p1(value ? 1 : 0); - } - pjstr(str, terminator = 10) { - const length = str.length; - for (let i = 0; i < length; i++) { - this.#view.setUint8(this.pos++, str.charCodeAt(i)); - } - this.#view.setUint8(this.pos++, terminator); - } - pdata(src, offset, length) { - this.data.set(src.subarray(offset, offset + length), this.pos); - this.pos += length - offset; - } - psize4(size) { - this.#view.setUint32(this.pos - size - 4, size); - } - psize2(size) { - this.#view.setUint16(this.pos - size - 2, size); - } - psize1(size) { - this.#view.setUint8(this.pos - size - 1, size); - } - psmarts(value) { - if (value < 64 && value >= 64) { - this.p1(value + 64); - } else if (value < 16384 && value >= -16384) { - this.p2(value + 49152); - } else { - throw new Error('Error psmarts out of range: ' + value); - } - } - psmart(value) { - if (value >= 0 && value < 128) { - this.p1(value); - } else if (value >= 0 && value < 32768) { - this.p2(value + 32768); - } else { - throw new Error('Error psmart out of range: ' + value); - } - } - g1() { - return this.#view.getUint8(this.pos++); - } - g1b() { - return this.#view.getInt8(this.pos++); - } - g2() { - this.pos += 2; - return this.#view.getUint16(this.pos - 2); - } - g2s() { - this.pos += 2; - return this.#view.getInt16(this.pos - 2); - } - ig2() { - this.pos += 2; - return this.#view.getUint16(this.pos - 2, true); - } - g3() { - const result = (this.#view.getUint8(this.pos++) << 16) | this.#view.getUint16(this.pos); - this.pos += 2; - return result; - } - g4() { - this.pos += 4; - return this.#view.getInt32(this.pos - 4); - } - ig4() { - this.pos += 4; - return this.#view.getInt32(this.pos - 4, true); - } - g8() { - this.pos += 8; - return this.#view.getBigInt64(this.pos - 8); - } - gbool() { - return this.g1() === 1; - } - gjstr(terminator = 10) { - const length = this.data.length; - let str = ''; - let b; - while ((b = this.#view.getUint8(this.pos++)) !== terminator && this.pos < length) { - str += String.fromCharCode(b); - } - return str; - } - gdata(dest, offset, length) { - dest.set(this.data.subarray(this.pos, this.pos + length), offset); - this.pos += length; - } - gsmarts() { - return this.#view.getUint8(this.pos) < 128 ? this.g1() - 64 : this.g2() - 49152; - } - gsmart() { - return this.#view.getUint8(this.pos) < 128 ? this.g1() : this.g2() - 32768; - } - bits() { - this.bitPos = this.pos << 3; - } - bytes() { - this.pos = (this.bitPos + 7) >>> 3; - } - gBit(n) { - let bytePos = this.bitPos >>> 3; - let remaining = 8 - (this.bitPos & 7); - let value = 0; - this.bitPos += n; - for (; n > remaining; remaining = 8) { - value += (this.#view.getUint8(bytePos++) & Packet.bitmask[remaining]) << (n - remaining); - n -= remaining; - } - if (n == remaining) { - value += this.#view.getUint8(bytePos) & Packet.bitmask[remaining]; - } else { - value += (this.#view.getUint8(bytePos) >>> (remaining - n)) & Packet.bitmask[n]; - } - return value; - } - pBit(n, value) { - const pos = this.bitPos; - this.bitPos += n; - let bytePos = pos >>> 3; - let remaining = 8 - (pos & 7); - const view = this.#view; - for (; n > remaining; remaining = 8) { - const shift2 = (1 << remaining) - 1; - const byte2 = view.getUint8(bytePos); - view.setUint8(bytePos++, (byte2 & ~shift2) | ((value >>> (n - remaining)) & shift2)); - n -= remaining; - } - const r = remaining - n; - const shift = (1 << n) - 1; - const byte = view.getUint8(bytePos); - view.setUint8(bytePos, (byte & (~shift << r)) | ((value & shift) << r)); - } -} - -// src/lostcity/cache/config/ConfigType.ts -class ConfigType { - id; - debugname = null; - constructor(id) { - this.id = id; - } - decodeType(dat) { - while (dat.available > 0) { - const code = dat.g1(); - if (code === 0) { - break; - } - this.decode(code, dat); - } - } -} - -// src/lostcity/cache/config/CategoryType.ts -class CategoryType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - CategoryType.configNames = new Map(); - CategoryType.configs = []; - if (!(await fetch(`${dir}/server/category.dat`)).ok) { - console.log('Warning: No category.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/category.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new CategoryType(id); - config.decodeType(dat); - CategoryType.configs[id] = config; - if (config.debugname) { - CategoryType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return CategoryType.configs[id]; - } - static getId(name) { - return CategoryType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - decode(code, dat) { - this.debugname = dat.gjstr(); - } - toString() { - return this.debugname ?? `category_${this.id}`; - } -} - -// src/lostcity/cache/config/ScriptVarType.ts -class ScriptVarType { - static INT = 105; - static AUTOINT = 255; - static STRING = 115; - static ENUM = 103; - static OBJ = 111; - static LOC = 108; - static COMPONENT = 73; - static NAMEDOBJ = 79; - static STRUCT = 74; - static BOOLEAN = 49; - static COORD = 99; - static CATEGORY = 121; - static SPOTANIM = 116; - static NPC = 110; - static INV = 118; - static SYNTH = 80; - static SEQ = 65; - static STAT = 83; - static VARP = 86; - static PLAYER_UID = 112; - static NPC_UID = 78; - static INTERFACE = 97; - static NPC_STAT = 254; - static IDKIT = 75; - static getType(type) { - switch (type) { - case ScriptVarType.INT: - return 'int'; - case ScriptVarType.STRING: - return 'string'; - case ScriptVarType.ENUM: - return 'enum'; - case ScriptVarType.OBJ: - return 'obj'; - case ScriptVarType.LOC: - return 'loc'; - case ScriptVarType.COMPONENT: - return 'component'; - case ScriptVarType.NAMEDOBJ: - return 'namedobj'; - case ScriptVarType.STRUCT: - return 'struct'; - case ScriptVarType.BOOLEAN: - return 'boolean'; - case ScriptVarType.COORD: - return 'coord'; - case ScriptVarType.CATEGORY: - return 'category'; - case ScriptVarType.SPOTANIM: - return 'spotanim'; - case ScriptVarType.NPC: - return 'npc'; - case ScriptVarType.INV: - return 'inv'; - case ScriptVarType.SYNTH: - return 'synth'; - case ScriptVarType.SEQ: - return 'seq'; - case ScriptVarType.STAT: - return 'stat'; - case ScriptVarType.AUTOINT: - return 'autoint'; - case ScriptVarType.VARP: - return 'varp'; - case ScriptVarType.PLAYER_UID: - return 'player_uid'; - case ScriptVarType.NPC_UID: - return 'npc_uid'; - case ScriptVarType.INTERFACE: - return 'interface'; - case ScriptVarType.NPC_STAT: - return 'npc_stat'; - case ScriptVarType.IDKIT: - return 'idkit'; - default: - return 'unknown'; - } - } - static getTypeChar(type) { - let char = 'i'; - switch (type) { - case 'int': - char = 'i'; - break; - case 'autoint': - char = '\xFF'; - break; - case 'string': - char = 's'; - break; - case 'enum': - char = 'g'; - break; - case 'obj': - char = 'o'; - break; - case 'loc': - char = 'l'; - break; - case 'component': - char = 'I'; - break; - case 'namedobj': - char = 'O'; - break; - case 'struct': - char = 'J'; - break; - case 'boolean': - char = '1'; - break; - case 'coord': - char = 'c'; - break; - case 'category': - char = 'y'; - break; - case 'spotanim': - char = 't'; - break; - case 'npc': - char = 'n'; - break; - case 'inv': - char = 'v'; - break; - case 'synth': - char = 'P'; - break; - case 'seq': - char = 'A'; - break; - case 'stat': - char = 'S'; - break; - case 'varp': - char = 'V'; - break; - case 'player_uid': - char = 'p'; - break; - case 'npc_uid': - char = 'N'; - break; - case 'interface': - char = 'a'; - break; - case 'npc_stat': - char = '\xFE'; - break; - case 'idkit': - char = 'K'; - break; - default: - return null; - } - return char.charCodeAt(0); - } - static getDefault(type) { - if (type === ScriptVarType.STRING) { - return ''; - } else if (type === ScriptVarType.BOOLEAN) { - return 0; - } else { - return -1; - } - } -} - -// src/lostcity/cache/config/DbTableType.ts -class DbTableType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - DbTableType.configNames = new Map(); - DbTableType.configs = []; - if (!(await fetch(`${dir}/server/dbtable.dat`)).ok) { - console.log('Warning: No dbtable.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/dbtable.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new DbTableType(id); - config.decodeType(dat); - DbTableType.configs[id] = config; - if (config.debugname) { - DbTableType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return DbTableType.configs[id]; - } - static getId(name) { - return DbTableType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - types = []; - defaultValues = []; - columnNames = []; - decode(code, dat) { - if (code === 1) { - this.types = new Array(dat.g1()); - for (let setting = dat.g1(); setting != 255; setting = dat.g1()) { - const column = setting & 127; - const hasDefault = (setting & 128) !== 0; - const columnTypes = new Array(dat.g1()); - for (let i = 0; i < columnTypes.length; i++) { - columnTypes[i] = dat.g1(); - } - this.types[column] = columnTypes; - if (hasDefault) { - if (!this.defaultValues) { - this.defaultValues = new Array(this.types.length); - } - this.defaultValues[column] = this.decodeValues(dat, column); - } - } - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else if (code === 251) { - this.columnNames = new Array(dat.g1()); - for (let i = 0; i < this.columnNames.length; i++) { - this.columnNames[i] = dat.gjstr(); - } - } else { - throw new Error(`Unrecognized dbtable config code: ${code}`); - } - } - getDefault(column) { - if (!this.defaultValues[column]) { - const defaults = []; - for (let i = 0; i < this.types[column].length; i++) { - defaults[i] = ScriptVarType.getDefault(this.types[column][i]); - } - return defaults; - } - return this.defaultValues[column]; - } - decodeValues(dat, column) { - const types = this.types[column]; - const fieldCount = dat.g1(); - const values = new Array(fieldCount * types.length); - for (let fieldId = 0; fieldId < fieldCount; fieldId++) { - for (let typeId = 0; typeId < types.length; typeId++) { - const type = types[typeId]; - const index = typeId + fieldId * types.length; - if (type === ScriptVarType.STRING) { - values[index] = dat.gjstr(); - } else { - values[index] = dat.g4(); - } - } - } - return values; - } -} - -// src/lostcity/cache/config/DbRowType.ts -class DbRowType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - DbRowType.configNames = new Map(); - DbRowType.configs = []; - if (!(await fetch(`${dir}/server/dbrow.dat`)).ok) { - console.log('Warning: No dbrow.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/dbrow.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new DbRowType(id); - config.decodeType(dat); - DbRowType.configs[id] = config; - if (config.debugname) { - DbRowType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return DbRowType.configs[id]; - } - static getId(name) { - return DbRowType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - static getInTable(tableId) { - return DbRowType.configs.filter(config => config.tableId === tableId); - } - tableId = 0; - types = []; - columnValues = []; - decode(code, dat) { - if (code === 3) { - const numColumns = dat.g1(); - this.types = new Array(numColumns); - this.columnValues = new Array(numColumns); - for (let columnId = dat.g1(); columnId != 255; columnId = dat.g1()) { - const columnTypes = new Array(dat.g1()); - for (let i = 0; i < columnTypes.length; i++) { - columnTypes[i] = dat.g1(); - } - this.types[columnId] = columnTypes; - this.columnValues[columnId] = this.decodeValues(dat, columnId); - } - } else if (code === 4) { - this.tableId = dat.g2(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized dbtable config code: ${code}`); - } - } - getValue(column, listIndex) { - const value = this.columnValues[column].slice(listIndex * this.types[column].length, (listIndex + 1) * this.types[column].length); - if (!value.length) { - return DbTableType.get(this.tableId).getDefault(column); - } - return value; - } - decodeValues(dat, column) { - const types = this.types[column]; - const fieldCount = dat.g1(); - const values = new Array(fieldCount * types.length); - for (let fieldId = 0; fieldId < fieldCount; fieldId++) { - for (let typeId = 0; typeId < types.length; typeId++) { - const type = types[typeId]; - const index = typeId + fieldId * types.length; - if (type === ScriptVarType.STRING) { - values[index] = dat.gjstr(); - } else { - values[index] = dat.g4(); - } - } - } - return values; - } -} - -// src/lostcity/cache/config/EnumType.ts -class EnumType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - EnumType.configNames = new Map(); - EnumType.configs = []; - if (!(await fetch(`${dir}/server/enum.dat`)).ok) { - console.log('Warning: No enum.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/enum.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new EnumType(id); - config.decodeType(dat); - EnumType.configs[id] = config; - if (config.debugname) { - EnumType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return EnumType.configs[id]; - } - static getId(name) { - return EnumType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - inputtype = ScriptVarType.INT; - outputtype = ScriptVarType.INT; - defaultInt = 0; - defaultString = 'null'; - values = new Map(); - decode(code, dat) { - if (code === 1) { - this.inputtype = dat.g1(); - } else if (code === 2) { - this.outputtype = dat.g1(); - } else if (code === 3) { - this.defaultString = dat.gjstr(); - } else if (code === 4) { - this.defaultInt = dat.g4(); - } else if (code === 5) { - const count = dat.g2(); - for (let i = 0; i < count; i++) { - this.values.set(dat.g4(), dat.gjstr()); - } - } else if (code === 6) { - const count = dat.g2(); - for (let i = 0; i < count; i++) { - this.values.set(dat.g4(), dat.g4()); - } - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized enum config code: ${code}`); - } - } -} - -// src/3rdparty/bz2.js -async function instantiate(module, imports = {}) { - const adaptedImports = { - env: Object.assign(Object.create(globalThis), imports.env || {}, { - abort(message, fileName, lineNumber, columnNumber) { - message = __liftString(message >>> 0); - fileName = __liftString(fileName >>> 0); - lineNumber = lineNumber >>> 0; - columnNumber = columnNumber >>> 0; - (() => { - throw Error(`${message} in ${fileName}:${lineNumber}:${columnNumber}`); - })(); - } - }) - }; - const {exports} = await WebAssembly.instantiate(module, adaptedImports); - const memory = exports.memory || imports.env.memory; - const adaptedExports = Object.setPrototypeOf( - { - read(length, stream, avail_in, next_in) { - stream = __lowerStaticArray(__setU8, 6, 0, stream, Int8Array) || __notnull(); - return __liftStaticArray(__getI8, 0, exports.read(length, stream, avail_in, next_in) >>> 0); - } - }, - exports - ); - function __liftString(pointer) { - if (!pointer) return null; - const end = (pointer + new Uint32Array(memory.buffer)[(pointer - 4) >>> 2]) >>> 1, - memoryU16 = new Uint16Array(memory.buffer); - let start = pointer >>> 1, - string = ''; - while (end - start > 1024) string += String.fromCharCode(...memoryU16.subarray(start, (start += 1024))); - return string + String.fromCharCode(...memoryU16.subarray(start, end)); - } - function __liftStaticArray(liftElement, align, pointer) { - if (!pointer) return null; - const length = __getU32(pointer - 4) >>> align, - values = new Array(length); - for (let i = 0; i < length; ++i) values[i] = liftElement(pointer + ((i << align) >>> 0)); - return values; - } - function __lowerStaticArray(lowerElement, id, align, values, typedConstructor) { - if (values == null) return 0; - const length = values.length, - buffer = exports.__pin(exports.__new(length << align, id)) >>> 0; - if (typedConstructor) { - new typedConstructor(memory.buffer, buffer, length).set(values); - } else { - for (let i = 0; i < length; i++) lowerElement(buffer + ((i << align) >>> 0), values[i]); - } - exports.__unpin(buffer); - return buffer; - } - function __notnull() { - throw TypeError('value must not be null'); - } - let __dataview = new DataView(memory.buffer); - function __setU8(pointer, value) { - try { - __dataview.setUint8(pointer, value, true); - } catch { - __dataview = new DataView(memory.buffer); - __dataview.setUint8(pointer, value, true); - } - } - function __getI8(pointer) { - try { - return __dataview.getInt8(pointer, true); - } catch { - __dataview = new DataView(memory.buffer); - return __dataview.getInt8(pointer, true); - } - } - function __getU32(pointer) { - try { - return __dataview.getUint32(pointer, true); - } catch { - __dataview = new DataView(memory.buffer); - return __dataview.getUint32(pointer, true); - } - } - return adaptedExports; -} - -// src/3rdparty/bzip.ts -class Bzip { - static bz2 = null; - static load = async bytes => { - this.bz2 = await instantiate(new WebAssembly.Module(bytes), {env: undefined}); - }; - static read = (length, stream, avail_in, next_in) => { - if (!this.bz2) { - throw new Error('bz2 not found!!'); - } - return Int8Array.from(this.bz2.read(length, stream, avail_in, next_in)); - }; -} - -// src/jagex2/io/Jagfile.ts -function genHash(name) { - let hash = 0; - name = name.toUpperCase(); - for (let i = 0; i < name.length; i++) { - hash = (hash * 61 + name.charCodeAt(i) - 32) | 0; - } - return hash; -} - -class Jagfile { - data = null; - fileCount = 0; - fileHash = []; - fileName = []; - fileUnpackedSize = []; - filePackedSize = []; - filePos = []; - unpacked = false; - fileQueue = []; - fileWrite = []; - static async load(path) { - return new Jagfile(await Packet.load(path)); - } - constructor(src) { - if (!src) { - return; - } - const unpackedSize = src.g3(); - const packedSize = src.g3(); - if (unpackedSize === packedSize) { - this.data = new Uint8Array(src.data); - this.unpacked = false; - } else { - this.data = new Uint8Array(Bzip.read(unpackedSize, src.data, packedSize, 6)); - src = new Packet(this.data); - this.unpacked = true; - } - this.fileCount = src.g2(); - let pos = src.pos + this.fileCount * 10; - for (let i = 0; i < this.fileCount; i++) { - this.fileHash[i] = src.g4(); - const hashMatch = KNOWN_HASHES.findIndex(x => x === this.fileHash[i]); - if (hashMatch !== -1) { - this.fileName[i] = KNOWN_NAMES[hashMatch]; - } - this.fileUnpackedSize[i] = src.g3(); - this.filePackedSize[i] = src.g3(); - this.filePos[i] = pos; - pos += this.filePackedSize[i]; - } - } - get(index) { - if (index < 0 || index >= this.fileCount) { - return null; - } - if (this.data === null) { - throw new Error('Jagfile data is not loaded'); - } - const src = this.data.subarray(this.filePos[index], this.filePos[index] + this.filePackedSize[index]); - if (this.unpacked) { - return new Packet(src); - } else { - return new Packet(Uint8Array.from(Bzip.read(this.fileUnpackedSize[index], this.data, this.filePackedSize[index], this.filePos[index]))); - } - } - read(name) { - const hash = genHash(name); - for (let i = 0; i < this.fileCount; i++) { - if (this.fileHash[i] === hash) { - return this.get(i); - } - } - return null; - } - write(name, data) { - const hash = genHash(name); - this.fileQueue.push({hash, name, write: true, data: data.data.subarray(0, data.pos)}); - } - delete(name) { - const hash = genHash(name); - this.fileQueue.push({hash, name, delete: true}); - } - rename(oldName, newName) { - const oldHash = genHash(oldName); - const newHash = genHash(newName); - this.fileQueue.push({ - hash: oldHash, - name: oldName, - rename: true, - newName, - newHash - }); - } - save(path, doNotCompressWhole = false) { - let buf = Packet.alloc(5); - for (let i = 0; i < this.fileQueue.length; i++) { - const queued = this.fileQueue[i]; - let index = this.fileHash.findIndex(x => x === queued.hash); - if (queued.write) { - if (index === -1) { - index = this.fileCount++; - this.fileHash[index] = queued.hash; - this.fileName[index] = queued.name; - } - if (!queued.data) { - throw new Error('Cannot write without data'); - } - this.fileUnpackedSize[index] = queued.data.length; - this.filePackedSize[index] = queued.data.length; - this.filePos[index] = -1; - this.fileWrite[index] = queued.data; - } - if (queued.delete && index !== -1) { - this.fileHash.splice(index, 1); - this.fileName.splice(index, 1); - this.fileUnpackedSize.splice(index, 1); - this.filePackedSize.splice(index, 1); - this.filePos.splice(index, 1); - this.fileCount--; - } - if (queued.rename && index !== -1) { - if (!queued.newHash) { - throw new Error('Cannot rename without newHash'); - } - if (!queued.newName) { - throw new Error('Cannot rename without newName'); - } - this.fileHash[index] = queued.newHash; - this.fileName[index] = queued.newName; - } - this.fileQueue.splice(i, 1); - i--; - } - let compressWhole = this.fileCount === 1; - if (doNotCompressWhole && compressWhole) { - compressWhole = false; - } - buf.p2(this.fileCount); - for (let i = 0; i < this.fileCount; i++) { - buf.p4(this.fileHash[i]); - buf.p3(this.fileUnpackedSize[i]); - if (this.fileWrite[i] && !compressWhole) { - this.fileWrite[i] = BZip2.compress(this.fileWrite[i], false, true); - this.filePackedSize[i] = this.fileWrite[i].length; - } - buf.p3(this.filePackedSize[i]); - } - for (let i = 0; i < this.fileCount; i++) { - const data = this.fileWrite[i]; - buf.pdata(data, 0, data.length); - } - const jag = Packet.alloc(5); - jag.p3(buf.pos); - if (compressWhole) { - buf = new Packet(BZip2.compress(buf.data, false, true)); - } - if (compressWhole) { - jag.p3(buf.data.length); - jag.pdata(buf.data, 0, buf.data.length); - } else { - jag.p3(buf.pos); - jag.pdata(buf.data, 0, buf.pos); - } - jag.save(path); - buf.release(); - jag.release(); - } - deconstruct(name) { - const dat = this.read(name + '.dat'); - const idx = this.read(name + '.idx'); - if (dat === null || idx === null) { - throw new Error('Failed to read dat or idx'); - } - const count = idx.g2(); - const sizes = new Array(count); - const offsets = new Array(count); - let offset = 2; - for (let i = 0; i < count; i++) { - sizes[i] = idx.g2(); - offsets[i] = offset; - offset += sizes[i]; - } - const checksums = new Array(count); - for (let i = 0; i < count; i++) { - dat.pos = offsets[i]; - checksums[i] = Packet.getcrc(dat.data, offset, sizes[i]); - } - return {count, sizes, offsets, checksums}; - } -} -var KNOWN_NAMES = [ - 'index.dat', - 'logo.dat', - 'p11.dat', - 'p12.dat', - 'b12.dat', - 'q8.dat', - 'runes.dat', - 'title.dat', - 'titlebox.dat', - 'titlebutton.dat', - 'p11_full.dat', - 'p12_full.dat', - 'b12_full.dat', - 'q8_full.dat', - 'flo.dat', - 'flo.idx', - 'idk.dat', - 'idk.idx', - 'loc.dat', - 'loc.idx', - 'npc.dat', - 'npc.idx', - 'obj.dat', - 'obj.idx', - 'seq.dat', - 'seq.idx', - 'spotanim.dat', - 'spotanim.idx', - 'varp.dat', - 'varp.idx', - 'varbit.dat', - 'varbit.idx', - 'mesanim.dat', - 'mesanim.idx', - 'mes.dat', - 'mes.idx', - 'param.dat', - 'param.idx', - 'hunt.dat', - 'hunt.idx', - 'data', - 'backbase1.dat', - 'backbase2.dat', - 'backhmid1.dat', - 'backhmid2.dat', - 'backleft1.dat', - 'backleft2.dat', - 'backright1.dat', - 'backright2.dat', - 'backtop1.dat', - 'backtop2.dat', - 'backvmid1.dat', - 'backvmid2.dat', - 'backvmid3.dat', - 'chatback.dat', - 'combatboxes.dat', - 'combaticons.dat', - 'combaticons2.dat', - 'combaticons3.dat', - 'compass.dat', - 'cross.dat', - 'gnomeball_buttons.dat', - 'headicons.dat', - 'hitmarks.dat', - 'invback.dat', - 'leftarrow.dat', - 'magicoff.dat', - 'magicoff2.dat', - 'magicon.dat', - 'magicon2.dat', - 'mapback.dat', - 'mapdots.dat', - 'mapflag.dat', - 'mapfunction.dat', - 'mapscene.dat', - 'miscgraphics.dat', - 'miscgraphics2.dat', - 'miscgraphics3.dat', - 'prayerglow.dat', - 'prayeroff.dat', - 'prayeron.dat', - 'redstone1.dat', - 'redstone2.dat', - 'redstone3.dat', - 'rightarrow.dat', - 'scrollbar.dat', - 'sideicons.dat', - 'staticons.dat', - 'staticons2.dat', - 'steelborder.dat', - 'steelborder2.dat', - 'sworddecor.dat', - 'tradebacking.dat', - 'wornicons.dat', - 'mapmarker.dat', - 'mod_icons.dat', - 'mapedge.dat', - 'blackmark.dat', - 'button_brown.dat', - 'button_brown_big.dat', - 'button_red.dat', - 'chest.dat', - 'coins.dat', - 'headicons_hint.dat', - 'headicons_pk.dat', - 'headicons_prayer.dat', - 'key.dat', - 'keys.dat', - 'leftarrow_small.dat', - 'letter.dat', - 'number_button.dat', - 'overlay_duel.dat', - 'overlay_multiway.dat', - 'pen.dat', - 'rightarrow_small.dat', - 'startgame.dat', - 'tex_brown.dat', - 'tex_red.dat', - 'titlescroll.dat', - 'base_head.dat', - 'base_label.dat', - 'base_type.dat', - 'frame_del.dat', - 'frame_head.dat', - 'frame_tran1.dat', - 'frame_tran2.dat', - 'ob_axis.dat', - 'ob_face1.dat', - 'ob_face2.dat', - 'ob_face3.dat', - 'ob_face4.dat', - 'ob_face5.dat', - 'ob_head.dat', - 'ob_point1.dat', - 'ob_point2.dat', - 'ob_point3.dat', - 'ob_point4.dat', - 'ob_point5.dat', - 'ob_vertex1.dat', - 'ob_vertex2.dat', - 'anim_crc', - 'anim_index', - 'anim_version', - 'map_crc', - 'map_index', - 'map_version', - 'midi_crc', - 'midi_index', - 'midi_version', - 'model_crc', - 'model_index', - 'model_version', - '0.dat', - '1.dat', - '2.dat', - '3.dat', - '4.dat', - '5.dat', - '6.dat', - '7.dat', - '8.dat', - '9.dat', - '10.dat', - '11.dat', - '12.dat', - '13.dat', - '14.dat', - '15.dat', - '16.dat', - '17.dat', - '18.dat', - '19.dat', - '20.dat', - '21.dat', - '22.dat', - '23.dat', - '24.dat', - '25.dat', - '26.dat', - '27.dat', - '28.dat', - '29.dat', - '30.dat', - '31.dat', - '32.dat', - '33.dat', - '34.dat', - '35.dat', - '36.dat', - '37.dat', - '38.dat', - '39.dat', - '40.dat', - '41.dat', - '42.dat', - '43.dat', - '44.dat', - '45.dat', - '46.dat', - '47.dat', - '48.dat', - '49.dat', - 'badenc.txt', - 'domainenc.txt', - 'fragmentsenc.txt', - 'tldlist.txt', - 'sounds.dat', - 'labels.dat', - 'floorcol.dat', - 'underlay.dat', - 'overlay.dat', - 'size.dat' -]; -var KNOWN_HASHES = []; -for (let i = 0; i < KNOWN_NAMES.length; i++) { - KNOWN_HASHES[i] = genHash(KNOWN_NAMES[i]); -} - -// src/lostcity/cache/config/FontType.ts -class FontType { - static CHAR_LOOKUP = []; - static instances = []; - static { - const charset = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!"\xA3$%^&*()-_=+[{]};:'@#~,<.>/?\\| `; - for (let i = 0; i < 256; i++) { - let c = charset.indexOf(String.fromCharCode(i)); - if (c == -1) { - c = 74; - } - FontType.CHAR_LOOKUP[i] = c; - } - } - static async load(dir) { - const title = await Jagfile.load(`${dir}/client/title`); - FontType.instances[0] = new FontType(title, 'p11'); - FontType.instances[1] = new FontType(title, 'p12'); - FontType.instances[2] = new FontType(title, 'b12'); - FontType.instances[3] = new FontType(title, 'q8'); - } - static get(id) { - return FontType.instances[id]; - } - static get count() { - return this.instances.length; - } - charMask = new Array(94); - charMaskWidth = new Uint8Array(94); - charMaskHeight = new Uint8Array(94); - charOffsetX = new Uint8Array(94); - charOffsetY = new Uint8Array(94); - charAdvance = new Uint8Array(95); - drawWidth = new Uint8Array(256); - height = 0; - constructor(title, font) { - const dat = title.read(`${font}.dat`); - const idx = title.read('index.dat'); - if (!dat || !idx) { - return; - } - idx.pos = dat.g2() + 4; - const off = idx.g1(); - if (off > 0) { - idx.pos += (off - 1) * 3; - } - for (let i = 0; i < 94; i++) { - this.charOffsetX[i] = idx.g1(); - this.charOffsetY[i] = idx.g1(); - const w = (this.charMaskWidth[i] = idx.g2()); - const h = (this.charMaskHeight[i] = idx.g2()); - const type = idx.g1(); - const len = w * h; - this.charMask[i] = new Uint8Array(len); - if (type == 0) { - for (let j = 0; j < len; j++) { - this.charMask[i][j] = dat.g1(); - } - } else if (type == 1) { - for (let x = 0; x < w; x++) { - for (let y = 0; y < h; y++) { - this.charMask[i][x + y * w] = dat.g1(); - } - } - } - if (h > this.height) { - this.height = h; - } - this.charOffsetX[i] = 1; - this.charAdvance[i] = w + 2; - let space = 0; - for (let y = Math.floor(h / 7); y < h; y++) { - space += this.charMask[i][y * w]; - } - if (space <= Math.floor(h / 7)) { - this.charAdvance[i]--; - this.charOffsetX[i] = 0; - } - space = 0; - for (let y = Math.floor(h / 7); y < h; y++) { - space += this.charMask[i][w + y * w - 1]; - } - if (space <= Math.floor(h / 7)) { - this.charAdvance[i]--; - } - } - this.charAdvance[94] = this.charAdvance[8]; - for (let c = 0; c < 256; c++) { - this.drawWidth[c] = this.charAdvance[FontType.CHAR_LOOKUP[c]]; - } - } - stringWidth(str) { - if (str == null) { - return 0; - } - let size = 0; - for (let c = 0; c < str.length; c++) { - if (str.charAt(c) == '@' && c + 4 < str.length && str.charAt(c + 4) == '@') { - c += 4; - } else { - size += this.drawWidth[str.charCodeAt(c)]; - } - } - return size; - } - split(str, maxWidth) { - if (str.length === 0) { - return [str]; - } - const lines = []; - while (str.length > 0) { - const width = this.stringWidth(str); - if (width <= maxWidth && str.indexOf('|') === -1) { - lines.push(str); - break; - } - let splitIndex = str.length; - for (let i = 0; i < str.length; i++) { - if (str[i] === ' ') { - const w = this.stringWidth(str.substring(0, i)); - if (w > maxWidth) { - break; - } - splitIndex = i; - } else if (str[i] === '|') { - splitIndex = i; - break; - } - } - lines.push(str.substring(0, splitIndex)); - str = str.substring(splitIndex + 1); - } - return lines; - } -} - -// src/lostcity/entity/hunt/HuntCheckNotTooStrong.ts -var HuntCheckNotTooStrong; -(HuntCheckNotTooStrong2 => { - HuntCheckNotTooStrong2[(HuntCheckNotTooStrong2['OFF'] = 0)] = 'OFF'; - HuntCheckNotTooStrong2[(HuntCheckNotTooStrong2['OUTSIDE_WILDERNESS'] = 1)] = 'OUTSIDE_WILDERNESS'; -})((HuntCheckNotTooStrong ||= {})); -var HuntCheckNotTooStrong_default = HuntCheckNotTooStrong; - -// src/lostcity/entity/hunt/HuntModeType.ts -var HuntModeType; -(HuntModeType2 => { - HuntModeType2[(HuntModeType2['OFF'] = 0)] = 'OFF'; - HuntModeType2[(HuntModeType2['PLAYER'] = 1)] = 'PLAYER'; - HuntModeType2[(HuntModeType2['NPC'] = 2)] = 'NPC'; - HuntModeType2[(HuntModeType2['OBJ'] = 3)] = 'OBJ'; - HuntModeType2[(HuntModeType2['SCENERY'] = 4)] = 'SCENERY'; -})((HuntModeType ||= {})); -var HuntModeType_default = HuntModeType; - -// src/lostcity/entity/hunt/HuntNobodyNear.ts -var HuntNobodyNear; -(HuntNobodyNear2 => { - HuntNobodyNear2[(HuntNobodyNear2['KEEPHUNTING'] = 0)] = 'KEEPHUNTING'; - HuntNobodyNear2[(HuntNobodyNear2['PAUSEHUNT'] = 1)] = 'PAUSEHUNT'; -})((HuntNobodyNear ||= {})); -var HuntNobodyNear_default = HuntNobodyNear; - -// src/lostcity/entity/hunt/HuntVis.ts -var HuntVis; -(HuntVis2 => { - HuntVis2[(HuntVis2['OFF'] = 0)] = 'OFF'; - HuntVis2[(HuntVis2['LINEOFSIGHT'] = 1)] = 'LINEOFSIGHT'; - HuntVis2[(HuntVis2['LINEOFWALK'] = 2)] = 'LINEOFWALK'; -})((HuntVis ||= {})); -var HuntVis_default = HuntVis; - -// src/lostcity/entity/NpcMode.ts -var NpcMode; -(NpcMode2 => { - NpcMode2[(NpcMode2['NULL'] = -1)] = 'NULL'; - NpcMode2[(NpcMode2['NONE'] = 0)] = 'NONE'; - NpcMode2[(NpcMode2['WANDER'] = 1)] = 'WANDER'; - NpcMode2[(NpcMode2['PATROL'] = 2)] = 'PATROL'; - NpcMode2[(NpcMode2['PLAYERESCAPE'] = 3)] = 'PLAYERESCAPE'; - NpcMode2[(NpcMode2['PLAYERFOLLOW'] = 4)] = 'PLAYERFOLLOW'; - NpcMode2[(NpcMode2['PLAYERFACE'] = 5)] = 'PLAYERFACE'; - NpcMode2[(NpcMode2['PLAYERFACECLOSE'] = 6)] = 'PLAYERFACECLOSE'; - NpcMode2[(NpcMode2['OPPLAYER1'] = 7)] = 'OPPLAYER1'; - NpcMode2[(NpcMode2['OPPLAYER2'] = 8)] = 'OPPLAYER2'; - NpcMode2[(NpcMode2['OPPLAYER3'] = 9)] = 'OPPLAYER3'; - NpcMode2[(NpcMode2['OPPLAYER4'] = 10)] = 'OPPLAYER4'; - NpcMode2[(NpcMode2['OPPLAYER5'] = 11)] = 'OPPLAYER5'; - NpcMode2[(NpcMode2['APPLAYER1'] = 12)] = 'APPLAYER1'; - NpcMode2[(NpcMode2['APPLAYER2'] = 13)] = 'APPLAYER2'; - NpcMode2[(NpcMode2['APPLAYER3'] = 14)] = 'APPLAYER3'; - NpcMode2[(NpcMode2['APPLAYER4'] = 15)] = 'APPLAYER4'; - NpcMode2[(NpcMode2['APPLAYER5'] = 16)] = 'APPLAYER5'; - NpcMode2[(NpcMode2['OPLOC1'] = 17)] = 'OPLOC1'; - NpcMode2[(NpcMode2['OPLOC2'] = 18)] = 'OPLOC2'; - NpcMode2[(NpcMode2['OPLOC3'] = 19)] = 'OPLOC3'; - NpcMode2[(NpcMode2['OPLOC4'] = 20)] = 'OPLOC4'; - NpcMode2[(NpcMode2['OPLOC5'] = 21)] = 'OPLOC5'; - NpcMode2[(NpcMode2['APLOC1'] = 22)] = 'APLOC1'; - NpcMode2[(NpcMode2['APLOC2'] = 23)] = 'APLOC2'; - NpcMode2[(NpcMode2['APLOC3'] = 24)] = 'APLOC3'; - NpcMode2[(NpcMode2['APLOC4'] = 25)] = 'APLOC4'; - NpcMode2[(NpcMode2['APLOC5'] = 26)] = 'APLOC5'; - NpcMode2[(NpcMode2['OPOBJ1'] = 27)] = 'OPOBJ1'; - NpcMode2[(NpcMode2['OPOBJ2'] = 28)] = 'OPOBJ2'; - NpcMode2[(NpcMode2['OPOBJ3'] = 29)] = 'OPOBJ3'; - NpcMode2[(NpcMode2['OPOBJ4'] = 30)] = 'OPOBJ4'; - NpcMode2[(NpcMode2['OPOBJ5'] = 31)] = 'OPOBJ5'; - NpcMode2[(NpcMode2['APOBJ1'] = 32)] = 'APOBJ1'; - NpcMode2[(NpcMode2['APOBJ2'] = 33)] = 'APOBJ2'; - NpcMode2[(NpcMode2['APOBJ3'] = 34)] = 'APOBJ3'; - NpcMode2[(NpcMode2['APOBJ4'] = 35)] = 'APOBJ4'; - NpcMode2[(NpcMode2['APOBJ5'] = 36)] = 'APOBJ5'; - NpcMode2[(NpcMode2['OPNPC1'] = 37)] = 'OPNPC1'; - NpcMode2[(NpcMode2['OPNPC2'] = 38)] = 'OPNPC2'; - NpcMode2[(NpcMode2['OPNPC3'] = 39)] = 'OPNPC3'; - NpcMode2[(NpcMode2['OPNPC4'] = 40)] = 'OPNPC4'; - NpcMode2[(NpcMode2['OPNPC5'] = 41)] = 'OPNPC5'; - NpcMode2[(NpcMode2['APNPC1'] = 42)] = 'APNPC1'; - NpcMode2[(NpcMode2['APNPC2'] = 43)] = 'APNPC2'; - NpcMode2[(NpcMode2['APNPC3'] = 44)] = 'APNPC3'; - NpcMode2[(NpcMode2['APNPC4'] = 45)] = 'APNPC4'; - NpcMode2[(NpcMode2['APNPC5'] = 46)] = 'APNPC5'; - NpcMode2[(NpcMode2['QUEUE1'] = 47)] = 'QUEUE1'; - NpcMode2[(NpcMode2['QUEUE2'] = 48)] = 'QUEUE2'; - NpcMode2[(NpcMode2['QUEUE3'] = 49)] = 'QUEUE3'; - NpcMode2[(NpcMode2['QUEUE4'] = 50)] = 'QUEUE4'; - NpcMode2[(NpcMode2['QUEUE5'] = 51)] = 'QUEUE5'; - NpcMode2[(NpcMode2['QUEUE6'] = 52)] = 'QUEUE6'; - NpcMode2[(NpcMode2['QUEUE7'] = 53)] = 'QUEUE7'; - NpcMode2[(NpcMode2['QUEUE8'] = 54)] = 'QUEUE8'; - NpcMode2[(NpcMode2['QUEUE9'] = 55)] = 'QUEUE9'; - NpcMode2[(NpcMode2['QUEUE10'] = 56)] = 'QUEUE10'; - NpcMode2[(NpcMode2['QUEUE11'] = 57)] = 'QUEUE11'; - NpcMode2[(NpcMode2['QUEUE12'] = 58)] = 'QUEUE12'; - NpcMode2[(NpcMode2['QUEUE13'] = 59)] = 'QUEUE13'; - NpcMode2[(NpcMode2['QUEUE14'] = 60)] = 'QUEUE14'; - NpcMode2[(NpcMode2['QUEUE15'] = 61)] = 'QUEUE15'; - NpcMode2[(NpcMode2['QUEUE16'] = 62)] = 'QUEUE16'; - NpcMode2[(NpcMode2['QUEUE17'] = 63)] = 'QUEUE17'; - NpcMode2[(NpcMode2['QUEUE18'] = 64)] = 'QUEUE18'; - NpcMode2[(NpcMode2['QUEUE19'] = 65)] = 'QUEUE19'; - NpcMode2[(NpcMode2['QUEUE20'] = 66)] = 'QUEUE20'; -})((NpcMode ||= {})); -var NpcMode_default = NpcMode; - -// src/lostcity/cache/config/HuntType.ts -class HuntType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - HuntType.configNames = new Map(); - HuntType.configs = []; - if (!(await fetch(`${dir}/server/hunt.dat`)).ok) { - console.log('Warning: No hunt.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/hunt.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new HuntType(id); - config.decodeType(dat); - HuntType.configs[id] = config; - if (config.debugname) { - HuntType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return HuntType.configs[id]; - } - static getId(name) { - return HuntType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - type = HuntModeType_default.OFF; - checkVis = HuntVis_default.OFF; - checkNotTooStrong = HuntCheckNotTooStrong_default.OFF; - checkNotBusy = false; - findKeepHunting = false; - findNewMode = NpcMode_default.NONE; - nobodyNear = HuntNobodyNear_default.PAUSEHUNT; - checkNotCombat = -1; - checkNotCombatSelf = -1; - checkAfk = true; - rate = 1; - checkCategory = -1; - checkNpc = -1; - checkObj = -1; - checkLoc = -1; - checkInv = -1; - checkObjParam = -1; - checkInvMinQuantity = -1; - checkInvMaxQuantity = -1; - decode(code, dat) { - if (code === 1) { - this.type = dat.g1(); - } else if (code == 2) { - this.checkVis = dat.g1(); - } else if (code == 3) { - this.checkNotTooStrong = dat.g1(); - } else if (code == 4) { - this.checkNotBusy = true; - } else if (code == 5) { - this.findKeepHunting = true; - } else if (code == 6) { - this.findNewMode = dat.g1(); - } else if (code == 7) { - this.nobodyNear = dat.g1(); - } else if (code === 8) { - this.checkNotCombat = dat.g2(); - } else if (code === 9) { - this.checkNotCombatSelf = dat.g2(); - } else if (code === 10) { - this.checkAfk = false; - } else if (code === 11) { - this.rate = dat.g2(); - } else if (code === 12) { - this.checkCategory = dat.g2(); - } else if (code === 13) { - this.checkNpc = dat.g2(); - } else if (code === 14) { - this.checkObj = dat.g2(); - } else if (code === 15) { - this.checkLoc = dat.g2(); - } else if (code === 16) { - this.checkInv = dat.g2(); - this.checkObj = dat.g2(); - this.checkInvMinQuantity = dat.g4(); - this.checkInvMaxQuantity = dat.g4(); - } else if (code === 17) { - this.checkInv = dat.g2(); - this.checkObjParam = dat.g2(); - this.checkInvMinQuantity = dat.g4(); - this.checkInvMaxQuantity = dat.g4(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized hunt config code: ${code}`); - } - } -} - -// src/lostcity/cache/config/IdkType.ts -class IdkType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - IdkType.configNames = new Map(); - IdkType.configs = []; - if (!(await fetch(`${dir}/server/idk.dat`)).ok) { - console.log('Warning: No idk.dat found.'); - return; - } - const server = await Packet.load(`${dir}/server/idk.dat`); - const count = server.g2(); - const jag = await Jagfile.load(`${dir}/client/config`); - const client = jag.read('idk.dat'); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new IdkType(id); - config.decodeType(server); - config.decodeType(client); - IdkType.configs[id] = config; - if (config.debugname) { - IdkType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return IdkType.configs[id]; - } - static getId(name) { - return IdkType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - type = -1; - models = null; - heads = new Uint16Array(5).fill(-1); - recol_s = new Uint16Array(6).fill(0); - recol_d = new Uint16Array(6).fill(0); - disable = false; - decode(code, dat) { - if (code === 1) { - this.type = dat.g1(); - } else if (code === 2) { - const count = dat.g1(); - this.models = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.models[i] = dat.g2(); - } - } else if (code === 3) { - this.disable = true; - } else if (code >= 40 && code < 50) { - this.recol_s[code - 40] = dat.g2(); - } else if (code >= 50 && code < 60) { - this.recol_d[code - 50] = dat.g2(); - } else if (code >= 60 && code < 70) { - this.heads[code - 60] = dat.g2(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized idk config code: ${code}`); - } - } -} - -// src/lostcity/cache/config/Component.ts -class Component { - static TYPE_LAYER = 0; - static TYPE_UNUSED = 1; - static TYPE_INVENTORY = 2; - static TYPE_RECT = 3; - static TYPE_TEXT = 4; - static TYPE_SPRITE = 5; - static TYPE_MODEL = 6; - static TYPE_INVENTORY_TEXT = 7; - static NO_BUTTON = 0; - static BUTTON = 1; - static TARGET_BUTTON = 2; - static CLOSE_BUTTON = 3; - static TOGGLE_BUTTON = 4; - static SELECT_BUTTON = 5; - static PAUSE_BUTTON = 6; - static componentNames = new Map(); - static components = []; - static async load(dir) { - this.componentNames = new Map(); - this.components = []; - if (!(await fetch(`${dir}/server/interface.dat`)).ok) { - console.log('Warning: No interface.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/interface.dat`); - dat.g2(); - let rootLayer = -1; - while (dat.available > 0) { - let id = dat.g2(); - if (id === 65535) { - rootLayer = dat.g2(); - id = dat.g2(); - } - const com = new Component(); - com.id = id; - com.rootLayer = rootLayer; - com.comName = dat.gjstr(); - com.overlay = dat.gbool(); - com.type = dat.g1(); - com.buttonType = dat.g1(); - com.clientCode = dat.g2(); - com.width = dat.g2(); - com.height = dat.g2(); - com.overLayer = dat.g1(); - if (com.overLayer == 0) { - com.overLayer = -1; - } else { - com.overLayer = ((com.overLayer - 1) << 8) + dat.g1(); - } - const comparatorCount = dat.g1(); - if (comparatorCount > 0) { - com.scriptComparator = new Uint8Array(comparatorCount).fill(0); - com.scriptOperand = new Uint16Array(comparatorCount).fill(0); - for (let i = 0; i < comparatorCount; i++) { - com.scriptComparator[i] = dat.g1(); - com.scriptOperand[i] = dat.g2(); - } - } - const scriptCount = dat.g1(); - if (scriptCount > 0) { - com.scripts = new Array(scriptCount).fill(null); - for (let i = 0; i < scriptCount; i++) { - const opcodeCount = dat.g2(); - com.scripts[i] = new Uint16Array(opcodeCount).fill(0); - for (let j = 0; j < opcodeCount; j++) { - com.scripts[i][j] = dat.g2(); - } - } - } - switch (com.type) { - case Component.TYPE_LAYER: { - com.scroll = dat.g2(); - com.hide = dat.gbool(); - const childCount = dat.g1(); - com.childId = new Uint16Array(childCount).fill(0); - com.childX = new Uint16Array(childCount).fill(0); - com.childY = new Uint16Array(childCount).fill(0); - for (let i = 0; i < childCount; i++) { - com.childId[i] = dat.g2(); - com.childX[i] = dat.g2s(); - com.childY[i] = dat.g2s(); - } - break; - } - case Component.TYPE_UNUSED: - dat.pos += 10; - break; - case Component.TYPE_INVENTORY: { - com.draggable = dat.gbool(); - com.interactable = dat.gbool(); - com.usable = dat.gbool(); - com.marginX = dat.g1(); - com.marginY = dat.g1(); - com.inventorySlotOffsetX = new Uint16Array(20).fill(0); - com.inventorySlotOffsetY = new Uint16Array(20).fill(0); - com.inventorySlotGraphic = new Array(20).fill(null); - for (let i = 0; i < 20; i++) { - if (dat.gbool()) { - com.inventorySlotOffsetX[i] = dat.g2s(); - com.inventorySlotOffsetY[i] = dat.g2s(); - com.inventorySlotGraphic[i] = dat.gjstr(); - } - } - com.inventoryOptions = new Array(5).fill(null); - for (let i = 0; i < 5; i++) { - com.inventoryOptions[i] = dat.gjstr(); - } - com.actionVerb = dat.gjstr(); - com.action = dat.gjstr(); - com.actionTarget = dat.g2(); - break; - } - case Component.TYPE_RECT: - com.fill = dat.gbool(); - com.colour = dat.g4(); - com.activeColour = dat.g4(); - com.overColour = dat.g4(); - break; - case Component.TYPE_TEXT: - com.center = dat.gbool(); - com.font = dat.g1(); - com.shadowed = dat.gbool(); - com.text = dat.gjstr(); - com.activeText = dat.gjstr(); - com.colour = dat.g4(); - com.activeColour = dat.g4(); - com.overColour = dat.g4(); - break; - case Component.TYPE_SPRITE: - com.graphic = dat.gjstr(); - com.activeGraphic = dat.gjstr(); - break; - case Component.TYPE_MODEL: { - com.model = dat.g1(); - if (com.model != 0) { - com.model = ((com.model - 1) << 8) + dat.g1(); - } - com.activeModel = dat.g1(); - if (com.activeModel != 0) { - com.activeModel = ((com.activeModel - 1) << 8) + dat.g1(); - } - com.anim = dat.g1(); - if (com.anim == 0) { - com.anim = -1; - } else { - com.anim = ((com.anim - 1) << 8) + dat.g1(); - } - com.activeAnim = dat.g1(); - if (com.activeAnim == 0) { - com.activeAnim = -1; - } else { - com.activeAnim = ((com.activeAnim - 1) << 8) + dat.g1(); - } - com.zoom = dat.g2(); - com.xan = dat.g2(); - com.yan = dat.g2(); - break; - } - case Component.TYPE_INVENTORY_TEXT: { - com.center = dat.gbool(); - com.font = dat.g1(); - com.shadowed = dat.gbool(); - com.colour = dat.g4(); - com.marginX = dat.g2s(); - com.marginY = dat.g2s(); - com.interactable = dat.gbool(); - com.inventoryOptions = new Array(5).fill(null); - for (let i = 0; i < 5; i++) { - com.inventoryOptions[i] = dat.gjstr(); - } - break; - } - } - switch (com.buttonType) { - case Component.NO_BUTTON: - break; - case Component.TARGET_BUTTON: - com.actionVerb = dat.gjstr(); - com.action = dat.gjstr(); - com.actionTarget = dat.g2(); - break; - case Component.BUTTON: - case Component.TOGGLE_BUTTON: - case Component.SELECT_BUTTON: - case Component.PAUSE_BUTTON: - com.option = dat.gjstr(); - break; - } - Component.components[id] = com; - if (com.comName) { - Component.componentNames.set(com.comName, id); - } - } - } - static get(id) { - return Component.components[id]; - } - static getId(name) { - return Component.componentNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - id = -1; - rootLayer = -1; - comName = null; - overlay = false; - type = -1; - buttonType = -1; - clientCode = 0; - width = 0; - height = 0; - overLayer = -1; - scriptComparator = null; - scriptOperand = null; - scripts = null; - scroll = 0; - hide = false; - draggable = false; - interactable = false; - usable = false; - marginX = 0; - marginY = 0; - inventorySlotOffsetX = null; - inventorySlotOffsetY = null; - inventorySlotGraphic = null; - inventoryOptions = null; - fill = false; - center = false; - font = 0; - shadowed = false; - text = null; - activeText = null; - colour = 0; - activeColour = 0; - overColour = 0; - graphic = null; - activeGraphic = null; - model = -1; - activeModel = -1; - anim = -1; - activeAnim = -1; - zoom = 0; - xan = 0; - yan = 0; - actionVerb = null; - action = null; - actionTarget = -1; - option = null; - childId = null; - childX = null; - childY = null; -} - -// src/lostcity/cache/config/InvType.ts -class InvType extends ConfigType { - static configNames = new Map(); - static configs = []; - static SCOPE_TEMP = 0; - static SCOPE_PERM = 1; - static SCOPE_SHARED = 2; - static INV = -1; - static WORN = -1; - static async load(dir) { - InvType.configNames = new Map(); - InvType.configs = []; - if (!(await fetch(`${dir}/server/inv.dat`)).ok) { - console.log('Warning: No inv.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/inv.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new InvType(id); - config.decodeType(dat); - InvType.configs[id] = config; - if (config.debugname) { - InvType.configNames.set(config.debugname, id); - } - } - InvType.INV = InvType.getId('inv'); - InvType.WORN = InvType.getId('worn'); - } - static get(id) { - return InvType.configs[id]; - } - static getId(name) { - return InvType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - scope = 0; - size = 1; - stackall = false; - restock = false; - allstock = false; - stockobj = null; - stockcount = null; - stockrate = null; - protect = true; - runweight = false; - dummyinv = false; - decode(code, dat) { - if (code === 1) { - this.scope = dat.g1(); - } else if (code === 2) { - this.size = dat.g2(); - } else if (code === 3) { - this.stackall = true; - } else if (code === 4) { - const count = dat.g1(); - this.stockobj = new Uint16Array(count); - this.stockcount = new Uint16Array(count); - this.stockrate = new Int32Array(count); - for (let j = 0; j < count; j++) { - this.stockobj[j] = dat.g2(); - this.stockcount[j] = dat.g2(); - this.stockrate[j] = dat.g4(); - } - } else if (code === 5) { - this.restock = true; - } else if (code === 6) { - this.allstock = true; - } else if (code === 7) { - this.protect = false; - } else if (code === 8) { - this.runweight = true; - } else if (code === 9) { - this.dummyinv = true; - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized inv config code: ${code}`); - } - } -} - -// src/lostcity/cache/config/ParamHelper.ts -var ParamHelper = { - getStringParam: function (id, holder, defaultValue) { - const value = holder.params?.get(id); - if (typeof value !== 'string') { - return defaultValue ?? 'null'; - } - return value; - }, - getIntParam: function (id, holder, defaultValue) { - const value = holder.params?.get(id); - if (typeof value !== 'number') { - return defaultValue; - } - return value; - }, - decodeParams: function (dat) { - const count = dat.g1(); - const params = new Map(); - for (let i = 0; i < count; i++) { - const key = dat.g3(); - const isString = dat.gbool(); - if (isString) { - params.set(key, dat.gjstr()); - } else { - params.set(key, dat.g4()); - } - } - return params; - } -}; - -// src/lostcity/cache/config/LocType.ts -class LocType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - LocType.configNames = new Map(); - LocType.configs = []; - if (!(await fetch(`${dir}/server/loc.dat`)).ok) { - console.log('Warning: No loc.dat found.'); - return; - } - const server = await Packet.load(`${dir}/server/loc.dat`); - const count = server.g2(); - const jag = await Jagfile.load(`${dir}/client/config`); - const client = jag.read('loc.dat'); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new LocType(id); - config.active = -1; - config.decodeType(server); - config.decodeType(client); - if (config.active === -1 && config.shapes) { - config.active = config.shapes.length > 0 && config.shapes[0] === 10 ? 1 : 0; - if (config.op && config.op.length > 0) { - config.active = 1; - } - } - LocType.configs[id] = config; - if (config.debugname) { - LocType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return LocType.configs[id]; - } - static getId(name) { - return LocType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === undefined || id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - models = null; - shapes = null; - name = null; - desc = null; - recol_s = null; - recol_d = null; - width = 1; - length = 1; - blockwalk = true; - blockrange = true; - active = 0; - hillskew = false; - sharelight = false; - occlude = false; - anim = -1; - hasalpha = false; - wallwidth = 16; - ambient = 0; - contrast = 0; - op = null; - mapfunction = -1; - mapscene = -1; - mirror = false; - shadow = true; - resizex = 128; - resizey = 128; - resizez = 128; - forceapproach = 0; - xoff = 0; - yoff = 0; - zoff = 0; - forcedecor = false; - category = -1; - params = new Map(); - decode(code, dat) { - if (code === 1) { - const count = dat.g1(); - this.models = new Uint16Array(count); - this.shapes = new Uint8Array(count); - for (let i = 0; i < count; i++) { - this.models[i] = dat.g2(); - this.shapes[i] = dat.g1(); - } - } else if (code === 2) { - this.name = dat.gjstr(); - } else if (code === 3) { - this.desc = dat.gjstr(); - } else if (code === 14) { - this.width = dat.g1(); - } else if (code === 15) { - this.length = dat.g1(); - } else if (code === 17) { - this.blockwalk = false; - } else if (code === 18) { - this.blockrange = false; - } else if (code === 19) { - this.active = dat.g1(); - } else if (code === 21) { - this.hillskew = true; - } else if (code === 22) { - this.sharelight = true; - } else if (code === 23) { - this.occlude = true; - } else if (code === 24) { - this.anim = dat.g2(); - if (this.anim == 65535) { - this.anim = -1; - } - } else if (code === 25) { - this.hasalpha = true; - } else if (code === 28) { - this.wallwidth = dat.g1(); - } else if (code === 29) { - this.ambient = dat.g1b(); - } else if (code === 39) { - this.contrast = dat.g1b(); - } else if (code >= 30 && code < 35) { - if (!this.op) { - this.op = new Array(5).fill(null); - } - this.op[code - 30] = dat.gjstr(); - if (this.op[code - 30] === 'hidden') { - this.op[code - 30] = null; - } - } else if (code === 40) { - const count = dat.g1(); - this.recol_s = new Uint16Array(count); - this.recol_d = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.recol_s[i] = dat.g2(); - this.recol_d[i] = dat.g2(); - } - } else if (code === 60) { - this.mapfunction = dat.g2(); - } else if (code === 62) { - this.mirror = true; - } else if (code === 64) { - this.shadow = false; - } else if (code === 65) { - this.resizex = dat.g2(); - } else if (code === 66) { - this.resizey = dat.g2(); - } else if (code === 67) { - this.resizez = dat.g2(); - } else if (code === 68) { - this.mapscene = dat.g2(); - } else if (code === 69) { - this.forceapproach = dat.g1(); - } else if (code === 70) { - this.xoff = dat.g2s(); - } else if (code === 71) { - this.yoff = dat.g2s(); - } else if (code === 72) { - this.zoff = dat.g2s(); - } else if (code === 73) { - this.forcedecor = true; - } else if (code === 200) { - this.category = dat.g2(); - } else if (code === 249) { - this.params = ParamHelper.decodeParams(dat); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized loc config code: ${code}`); - } - } -} - -// src/lostcity/cache/config/MesanimType.ts -class MesanimType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - MesanimType.configNames = new Map(); - MesanimType.configs = []; - if (!(await fetch(`${dir}/server/mesanim.dat`)).ok) { - console.log('Warning: No mesanim.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/mesanim.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new MesanimType(id); - config.decodeType(dat); - MesanimType.configs[id] = config; - if (config.debugname) { - MesanimType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return MesanimType.configs[id]; - } - static getId(name) { - return MesanimType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - len = new Array(4).fill(-1); - decode(code, dat) { - if (code >= 1 && code < 5) { - this.len[code - 1] = dat.g2(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized mesanim config code: ${code}`); - } - } -} - -// src/lostcity/entity/BlockWalk.ts -var BlockWalk; -(BlockWalk2 => { - BlockWalk2[(BlockWalk2['NONE'] = 0)] = 'NONE'; - BlockWalk2[(BlockWalk2['NPC'] = 1)] = 'NPC'; - BlockWalk2[(BlockWalk2['ALL'] = 2)] = 'ALL'; -})((BlockWalk ||= {})); -var BlockWalk_default = BlockWalk; - -// src/lostcity/entity/MoveRestrict.ts -var MoveRestrict; -(MoveRestrict2 => { - MoveRestrict2[(MoveRestrict2['NORMAL'] = 0)] = 'NORMAL'; - MoveRestrict2[(MoveRestrict2['BLOCKED'] = 1)] = 'BLOCKED'; - MoveRestrict2[(MoveRestrict2['BLOCKED_NORMAL'] = 2)] = 'BLOCKED_NORMAL'; - MoveRestrict2[(MoveRestrict2['INDOORS'] = 3)] = 'INDOORS'; - MoveRestrict2[(MoveRestrict2['OUTDOORS'] = 4)] = 'OUTDOORS'; - MoveRestrict2[(MoveRestrict2['NOMOVE'] = 5)] = 'NOMOVE'; - MoveRestrict2[(MoveRestrict2['PASSTHRU'] = 6)] = 'PASSTHRU'; -})((MoveRestrict ||= {})); -var MoveRestrict_default = MoveRestrict; - -// src/lostcity/entity/NpcStat.ts -var NpcStat; -(NpcStat2 => { - NpcStat2[(NpcStat2['ATTACK'] = 0)] = 'ATTACK'; - NpcStat2[(NpcStat2['DEFENCE'] = 1)] = 'DEFENCE'; - NpcStat2[(NpcStat2['STRENGTH'] = 2)] = 'STRENGTH'; - NpcStat2[(NpcStat2['HITPOINTS'] = 3)] = 'HITPOINTS'; - NpcStat2[(NpcStat2['RANGED'] = 4)] = 'RANGED'; - NpcStat2[(NpcStat2['MAGIC'] = 5)] = 'MAGIC'; -})((NpcStat ||= {})); -var NpcStat_default = NpcStat; - -// src/lostcity/cache/config/NpcType.ts -class NpcType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - NpcType.configNames = new Map(); - NpcType.configs = []; - if (!(await fetch(`${dir}/server/npc.dat`)).ok) { - console.log('Warning: No npc.dat found.'); - return; - } - const server = await Packet.load(`${dir}/server/npc.dat`); - const count = server.g2(); - const jag = await Jagfile.load(`${dir}/client/config`); - const client = jag.read('npc.dat'); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new NpcType(id); - config.decodeType(server); - config.decodeType(client); - NpcType.configs[id] = config; - if (config.debugname) { - NpcType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return NpcType.configs[id]; - } - static getId(name) { - return NpcType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - name = null; - desc = null; - size = 1; - models = null; - heads = null; - hasanim = false; - readyanim = -1; - walkanim = -1; - walkanim_b = -1; - walkanim_r = -1; - walkanim_l = -1; - hasalpha = false; - recol_s = null; - recol_d = null; - op = null; - resizex = -1; - resizey = -1; - resizez = -1; - minimap = true; - vislevel = -1; - resizeh = 128; - resizev = 128; - category = -1; - wanderrange = 5; - maxrange = 10; - huntrange = 5; - timer = -1; - respawnrate = 100; - stats = [1, 1, 1, 1, 1, 1]; - moverestrict = MoveRestrict_default.NORMAL; - attackrange = 7; - huntmode = -1; - defaultmode = NpcMode_default.WANDER; - members = false; - blockwalk = BlockWalk_default.NPC; - params = new Map(); - patrolCoord = []; - patrolDelay = []; - givechase = true; - decode(code, dat) { - if (code === 1) { - const count = dat.g1(); - this.models = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.models[i] = dat.g2(); - } - } else if (code === 2) { - this.name = dat.gjstr(); - } else if (code === 3) { - this.desc = dat.gjstr(); - } else if (code === 12) { - this.size = dat.g1(); - } else if (code === 13) { - this.readyanim = dat.g2(); - } else if (code === 14) { - this.walkanim = dat.g2(); - } else if (code === 16) { - this.hasanim = true; - } else if (code === 17) { - this.walkanim = dat.g2(); - this.walkanim_b = dat.g2(); - this.walkanim_r = dat.g2(); - this.walkanim_l = dat.g2(); - } else if (code === 18) { - this.category = dat.g2(); - } else if (code >= 30 && code < 40) { - if (!this.op) { - this.op = new Array(5).fill(null); - } - this.op[code - 30] = dat.gjstr(); - if (this.op[code - 30] === 'hidden') { - this.op[code - 30] = null; - } - } else if (code === 40) { - const count = dat.g1(); - this.recol_s = new Uint16Array(count); - this.recol_d = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.recol_s[i] = dat.g2(); - this.recol_d[i] = dat.g2(); - } - } else if (code === 60) { - const count = dat.g1(); - this.heads = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.heads[i] = dat.g2(); - } - } else if (code === 74) { - this.stats[NpcStat_default.ATTACK] = dat.g2(); - } else if (code === 75) { - this.stats[NpcStat_default.DEFENCE] = dat.g2(); - } else if (code === 76) { - this.stats[NpcStat_default.STRENGTH] = dat.g2(); - } else if (code === 77) { - this.stats[NpcStat_default.HITPOINTS] = dat.g2(); - } else if (code === 78) { - this.stats[NpcStat_default.RANGED] = dat.g2(); - } else if (code === 79) { - this.stats[NpcStat_default.MAGIC] = dat.g2(); - } else if (code === 90) { - this.resizex = dat.g2(); - } else if (code === 91) { - this.resizey = dat.g2(); - } else if (code === 92) { - this.resizez = dat.g2(); - } else if (code === 93) { - this.minimap = false; - } else if (code === 95) { - this.vislevel = dat.g2(); - } else if (code === 97) { - this.resizeh = dat.g2(); - } else if (code === 98) { - this.resizev = dat.g2(); - } else if (code === 200) { - this.wanderrange = dat.g1(); - } else if (code === 201) { - this.maxrange = dat.g1(); - } else if (code === 202) { - this.huntrange = dat.g1(); - } else if (code === 203) { - this.timer = dat.g2(); - } else if (code === 204) { - this.respawnrate = dat.g2(); - } else if (code === 206) { - this.moverestrict = dat.g1(); - } else if (code == 207) { - this.attackrange = dat.g1(); - } else if (code === 208) { - this.blockwalk = dat.g1(); - } else if (code === 209) { - this.huntmode = dat.g1(); - } else if (code === 210) { - this.defaultmode = dat.g1(); - } else if (code === 211) { - this.members = true; - } else if (code === 212) { - const count = dat.g1(); - this.patrolCoord = new Array(count); - this.patrolDelay = new Array(count); - for (let j = 0; j < count; j++) { - this.patrolCoord[j] = dat.g4(); - this.patrolDelay[j] = dat.g1(); - } - } else if (code === 213) { - this.givechase = false; - } else if (code === 249) { - this.params = ParamHelper.decodeParams(dat); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - console.error('Unrecognized npc config code: ' + code); - console.error('Try `npm run build` and report an issue if this still happens.'); - process.exit(1); - } - } -} - -// src/lostcity/cache/config/ParamType.ts -class ParamType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - ParamType.configNames = new Map(); - ParamType.configs = []; - if (!(await fetch(`${dir}/server/param.dat`)).ok) { - console.log('Warning: No param.dat found.'); - } - const dat = await Packet.load(`${dir}/server/param.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new ParamType(id); - config.decodeType(dat); - ParamType.configs[id] = config; - if (config.debugname) { - ParamType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return ParamType.configs[id]; - } - static getId(name) { - return ParamType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - type = ScriptVarType.INT; - defaultInt = -1; - defaultString = null; - autodisable = true; - decode(code, dat) { - if (code === 1) { - this.type = dat.g1(); - } else if (code === 2) { - this.defaultInt = dat.g4(); - } else if (code === 4) { - this.autodisable = false; - } else if (code === 5) { - this.defaultString = dat.gjstr(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized param config code: ${code}`); - } - } - getType() { - switch (this.type) { - case ScriptVarType.INT: - return 'int'; - case ScriptVarType.STRING: - return 'string'; - case ScriptVarType.ENUM: - return 'enum'; - case ScriptVarType.OBJ: - return 'obj'; - case ScriptVarType.LOC: - return 'loc'; - case ScriptVarType.COMPONENT: - return 'component'; - case ScriptVarType.NAMEDOBJ: - return 'namedobj'; - case ScriptVarType.STRUCT: - return 'struct'; - case ScriptVarType.BOOLEAN: - return 'boolean'; - case ScriptVarType.COORD: - return 'coord'; - case ScriptVarType.CATEGORY: - return 'category'; - case ScriptVarType.SPOTANIM: - return 'spotanim'; - case ScriptVarType.NPC: - return 'npc'; - case ScriptVarType.INV: - return 'inv'; - case ScriptVarType.SYNTH: - return 'synth'; - case ScriptVarType.SEQ: - return 'seq'; - case ScriptVarType.STAT: - return 'stat'; - case ScriptVarType.INTERFACE: - return 'interface'; - default: - return 'unknown'; - } - } - isString() { - return this.type === ScriptVarType.STRING; - } - get default() { - return this.isString() ? this.defaultString : this.defaultInt; - } -} - -// src/lostcity/cache/config/ObjType.ts -class ObjType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir, members) { - ObjType.configNames = new Map(); - ObjType.configs = []; - if (!(await fetch(`${dir}/server/obj.dat`)).ok) { - console.log('Warning: No obj.dat found.'); - return; - } - const server = await Packet.load(`${dir}/server/obj.dat`); - const count = server.g2(); - const jag = await Jagfile.load(`${dir}/client/config`); - const client = jag.read('obj.dat'); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new ObjType(id); - config.decodeType(server); - config.decodeType(client); - ObjType.configs[id] = config; - if (config.debugname) { - ObjType.configNames.set(config.debugname, id); - } - } - for (let id = 0; id < count; id++) { - const config = ObjType.configs[id]; - if (config.certtemplate != -1) { - config.toCertificate(); - } - if (!members && config.members) { - config.tradeable = false; - config.op = null; - config.iop = null; - config.params.forEach((_, key) => { - if (ParamType.get(key)?.autodisable) { - config.params.delete(key); - } - }); - } - } - } - static get(id) { - return ObjType.configs[id]; - } - static getId(name) { - return ObjType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - static getWearPosId(name) { - switch (name) { - case 'hat': - return 0; - case 'back': - return 1; - case 'front': - return 2; - case 'righthand': - return 3; - case 'torso': - return 4; - case 'lefthand': - return 5; - case 'arms': - return 6; - case 'legs': - return 7; - case 'head': - return 8; - case 'hands': - return 9; - case 'feet': - return 10; - case 'jaw': - return 11; - case 'ring': - return 12; - case 'quiver': - return 13; - default: - return -1; - } - } - model = 0; - name = null; - desc = null; - recol_s = null; - recol_d = null; - zoom2d = 2000; - xan2d = 0; - yan2d = 0; - zan2d = 0; - xof2d = 0; - yof2d = 0; - code9 = false; - code10 = -1; - stackable = false; - cost = 1; - members = false; - op = null; - iop = null; - manwear = -1; - manwear2 = -1; - manwearOffsetY = 0; - womanwear = -1; - womanwear2 = -1; - womanwearOffsetY = 0; - manwear3 = -1; - womanwear3 = -1; - manhead = -1; - manhead2 = -1; - womanhead = -1; - womanhead2 = -1; - countobj = null; - countco = null; - certlink = -1; - certtemplate = -1; - wearpos = -1; - wearpos2 = -1; - wearpos3 = -1; - weight = 0; - category = -1; - dummyitem = 0; - tradeable = false; - respawnrate = 100; - params = new Map(); - decode(code, dat) { - if (code === 1) { - this.model = dat.g2(); - } else if (code === 2) { - this.name = dat.gjstr(); - } else if (code === 3) { - this.desc = dat.gjstr(); - } else if (code === 4) { - this.zoom2d = dat.g2(); - } else if (code === 5) { - this.xan2d = dat.g2(); - } else if (code === 6) { - this.yan2d = dat.g2(); - } else if (code === 7) { - this.xof2d = dat.g2s(); - } else if (code === 8) { - this.yof2d = dat.g2s(); - } else if (code === 9) { - this.code9 = true; - } else if (code === 10) { - this.code10 = dat.g2(); - } else if (code === 11) { - this.stackable = true; - } else if (code === 12) { - this.cost = dat.g4(); - } else if (code === 13) { - this.wearpos = dat.g1(); - } else if (code === 14) { - this.wearpos2 = dat.g1(); - } else if (code === 16) { - this.members = true; - } else if (code === 23) { - this.manwear = dat.g2(); - this.manwearOffsetY = dat.g1b(); - } else if (code === 24) { - this.manwear2 = dat.g2(); - } else if (code === 25) { - this.womanwear = dat.g2(); - this.womanwearOffsetY = dat.g1b(); - } else if (code === 26) { - this.womanwear2 = dat.g2(); - } else if (code === 27) { - this.wearpos3 = dat.g1(); - } else if (code >= 30 && code < 35) { - if (!this.op) { - this.op = new Array(5).fill(null); - } - this.op[code - 30] = dat.gjstr(); - } else if (code >= 35 && code < 40) { - if (!this.iop) { - this.iop = new Array(5).fill(null); - } - this.iop[code - 35] = dat.gjstr(); - } else if (code === 40) { - const count = dat.g1(); - this.recol_s = new Uint16Array(count); - this.recol_d = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.recol_s[i] = dat.g2(); - this.recol_d[i] = dat.g2(); - } - } else if (code === 75) { - this.weight = dat.g2s(); - } else if (code === 78) { - this.manwear3 = dat.g2(); - } else if (code === 79) { - this.womanwear3 = dat.g2(); - } else if (code === 90) { - this.manhead = dat.g2(); - } else if (code === 91) { - this.womanhead = dat.g2(); - } else if (code === 92) { - this.manhead2 = dat.g2(); - } else if (code === 93) { - this.womanhead2 = dat.g2(); - } else if (code === 94) { - this.category = dat.g2(); - } else if (code === 95) { - this.zan2d = dat.g2(); - } else if (code === 96) { - this.dummyitem = dat.g1(); - } else if (code === 97) { - this.certlink = dat.g2(); - } else if (code === 98) { - this.certtemplate = dat.g2(); - } else if (code >= 100 && code < 110) { - if (!this.countobj || !this.countco) { - this.countobj = new Uint16Array(10); - this.countco = new Uint16Array(10); - } - this.countobj[code - 100] = dat.g2(); - this.countco[code - 100] = dat.g2(); - } else if (code === 200) { - this.tradeable = true; - } else if (code === 201) { - this.respawnrate = dat.g2(); - } else if (code === 249) { - this.params = ParamHelper.decodeParams(dat); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized obj config code: ${code}`); - } - } - toCertificate() { - const template = ObjType.get(this.certtemplate); - this.model = template.model; - this.zoom2d = template.zoom2d; - this.xan2d = template.xan2d; - this.yan2d = template.yan2d; - this.zan2d = template.zan2d; - this.xof2d = template.xof2d; - this.yof2d = template.yof2d; - this.recol_s = template.recol_s; - this.recol_d = template.recol_d; - const link = ObjType.get(this.certlink); - this.name = link.name; - this.members = link.members; - this.cost = link.cost; - this.tradeable = link.tradeable; - let article = 'a'; - const c = (link.name || '').toLowerCase().charAt(0); - if (c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u') { - article = 'an'; - } - this.desc = `Swap this note at any bank for ${article} ${link.name}.`; - this.stackable = true; - } -} - -// src/lostcity/cache/config/SeqFrame.ts -class SeqFrame { - static instances = []; - static async load(dir) { - SeqFrame.instances = []; - const frame_del = await Packet.load(`${dir}/server/frame_del.dat`); - for (let i = 0; i < frame_del.data.length; i++) { - const frame = new SeqFrame(); - frame.delay = frame_del.g1(); - SeqFrame.instances[i] = frame; - } - } - delay = 0; -} - -// src/lostcity/cache/config/SeqType.ts -class SeqType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - SeqType.configNames = new Map(); - SeqType.configs = []; - if (!(await fetch(`${dir}/server/seq.dat`)).ok) { - console.log('Warning: No seq.dat found.'); - return; - } - const server = await Packet.load(`${dir}/server/seq.dat`); - const count = server.g2(); - const jag = await Jagfile.load(`${dir}/client/config`); - const client = jag.read('seq.dat'); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new SeqType(id); - config.decodeType(server); - config.decodeType(client); - SeqType.configs[id] = config; - if (config.debugname) { - SeqType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return SeqType.configs[id]; - } - static getId(name) { - return SeqType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return SeqType.configs.length; - } - frames = null; - iframes = null; - delay = null; - replayoff = -1; - walkmerge = null; - stretches = false; - priority = 5; - mainhand = -1; - offhand = -1; - replaycount = 99; - duration = 0; - decode(code, dat) { - if (code === 1) { - const count = dat.g1(); - this.frames = new Int32Array(count); - this.iframes = new Int32Array(count); - this.delay = new Int32Array(count); - for (let i = 0; i < count; i++) { - this.frames[i] = dat.g2(); - this.iframes[i] = dat.g2(); - if (this.iframes[i] === 65535) { - this.iframes[i] = -1; - } - this.delay[i] = dat.g2(); - if (this.delay[i] === 0) { - this.delay[i] = SeqFrame.instances[this.frames[i]].delay; - } - if (this.delay[i] === 0) { - this.delay[i] = 1; - } - this.duration += this.delay[i]; - } - } else if (code === 2) { - this.replayoff = dat.g2(); - } else if (code === 3) { - const count = dat.g1(); - this.walkmerge = new Int32Array(count + 1); - for (let i = 0; i < count; i++) { - this.walkmerge[i] = dat.g1(); - } - this.walkmerge[count] = 9999999; - } else if (code === 4) { - this.stretches = true; - } else if (code === 5) { - this.priority = dat.g1(); - } else if (code === 6) { - this.mainhand = dat.g2(); - } else if (code === 7) { - this.offhand = dat.g2(); - } else if (code === 8) { - this.replaycount = dat.g1(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized seq config code: ${code}`); - } - } -} - -// src/lostcity/cache/config/StructType.ts -class StructType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - StructType.configNames = new Map(); - StructType.configs = []; - if (!(await fetch(`${dir}/server/struct.dat`)).ok) { - console.log('Warning: No struct.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/struct.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new StructType(id); - config.decodeType(dat); - StructType.configs[id] = config; - if (config.debugname) { - StructType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return StructType.configs[id]; - } - static getId(name) { - return StructType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - params = null; - decode(code, dat) { - if (code === 249) { - this.params = ParamHelper.decodeParams(dat); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized struct config code: ${code}`); - } - } -} - -// src/lostcity/cache/config/VarNpcType.ts -class VarNpcType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - VarNpcType.configNames = new Map(); - VarNpcType.configs = []; - if (!(await fetch(`${dir}/server/varn.dat`)).ok) { - console.log('Warning: No varn.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/varn.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new VarNpcType(id); - config.decodeType(dat); - VarNpcType.configs[id] = config; - if (config.debugname) { - VarNpcType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return VarNpcType.configs[id]; - } - static getId(name) { - return VarNpcType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - type = ScriptVarType.INT; - decode(code, dat) { - if (code === 1) { - this.type = dat.g1(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - console.error(`Unrecognized varn config code: ${code}`); - } - } -} - -// src/lostcity/cache/config/VarPlayerType.ts -class VarPlayerType extends ConfigType { - static configNames = new Map(); - static configs = []; - static SCOPE_TEMP = 0; - static SCOPE_PERM = 1; - static PLAYER_RUN = -1; - static TEMP_RUN = -1; - static LASTCOMBAT = -1; - static async load(dir) { - VarPlayerType.configNames = new Map(); - VarPlayerType.configs = []; - if (!(await fetch(`${dir}/server/varp.dat`)).ok) { - console.log('Warning: No varp.dat found.'); - } - const server = await Packet.load(`${dir}/server/varp.dat`); - const count = server.g2(); - const jag = await Jagfile.load(`${dir}/client/config`); - const client = jag.read('varp.dat'); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new VarPlayerType(id); - config.decodeType(server); - config.decodeType(client); - VarPlayerType.configs[id] = config; - if (config.debugname) { - VarPlayerType.configNames.set(config.debugname, id); - } - } - VarPlayerType.PLAYER_RUN = VarPlayerType.getId('player_run'); - VarPlayerType.TEMP_RUN = VarPlayerType.getId('temp_run'); - VarPlayerType.LASTCOMBAT = VarPlayerType.getId('lastcombat'); - } - static get(id) { - return VarPlayerType.configs[id]; - } - static getId(name) { - return VarPlayerType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - clientcode = 0; - scope = VarPlayerType.SCOPE_TEMP; - type = ScriptVarType.INT; - protect = true; - transmit = false; - decode(code, dat) { - if (code === 1) { - this.scope = dat.g1(); - } else if (code === 2) { - this.type = dat.g1(); - } else if (code === 4) { - this.protect = false; - } else if (code === 5) { - this.clientcode = dat.g2(); - } else if (code === 6) { - this.transmit = true; - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - console.error(`Unrecognized varp config code: ${code}`); - } - } -} - -// src/lostcity/cache/config/VarSharedType.ts -class VarSharedType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - VarSharedType.configNames = new Map(); - VarSharedType.configs = []; - if (!(await fetch(`${dir}/server/vars.dat`)).ok) { - console.log('Warning: No vars.dat found.'); - return; - } - const dat = await Packet.load(`${dir}/server/vars.dat`); - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new VarSharedType(id); - config.decodeType(dat); - VarSharedType.configs[id] = config; - if (config.debugname) { - VarSharedType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return VarSharedType.configs[id]; - } - static getId(name) { - return VarSharedType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - type = ScriptVarType.INT; - decode(code, dat) { - switch (code) { - case 1: - this.type = dat.g1(); - break; - case 250: - this.debugname = dat.gjstr(); - break; - default: - console.error(`Unrecognized vars config code: ${code}`); - break; - } - } -} - -// src/lostcity/cache/wordenc/WordEncFragments.ts -class WordEncFragments { - fragments = []; - filter(chars) { - for (let currentIndex = 0; currentIndex < chars.length; ) { - const numberIndex = this.indexOfNumber(chars, currentIndex); - if (numberIndex === -1) { - return; - } - let isSymbolOrNotLowercaseAlpha = false; - for (let index = currentIndex; index >= 0 && index < numberIndex && !isSymbolOrNotLowercaseAlpha; index++) { - if (!WordEnc2.isSymbol(chars[index]) && !WordEnc2.isNotLowercaseAlpha(chars[index])) { - isSymbolOrNotLowercaseAlpha = true; - } - } - let startIndex = 0; - if (isSymbolOrNotLowercaseAlpha) { - startIndex = 0; - } - if (startIndex === 0) { - startIndex = 1; - currentIndex = numberIndex; - } - let value = 0; - for (let index = numberIndex; index < chars.length && index < currentIndex; index++) { - value = value * 10 + chars[index].charCodeAt(0) - 48; - } - if (value <= 255 && currentIndex - numberIndex <= 8) { - startIndex++; - } else { - startIndex = 0; - } - if (startIndex === 4) { - WordEnc2.maskChars(numberIndex, currentIndex, chars); - startIndex = 0; - } - currentIndex = this.indexOfNonNumber(currentIndex, chars); - } - } - isBadFragment(chars) { - if (WordEnc2.isNumericalChars(chars)) { - return true; - } - const value = this.getInteger(chars); - const fragments = this.fragments; - const fragmentsLength = fragments.length; - if (value === fragments[0] || value === fragments[fragmentsLength - 1]) { - return true; - } - let start = 0; - let end = fragmentsLength - 1; - while (start <= end) { - const mid = ((start + end) / 2) | 0; - if (value === fragments[mid]) { - return true; - } else if (value < fragments[mid]) { - end = mid - 1; - } else { - start = mid + 1; - } - } - return false; - } - getInteger(chars) { - if (chars.length > 6) { - return 0; - } - let value = 0; - for (let index = 0; index < chars.length; index++) { - const char = chars[chars.length - index - 1]; - if (WordEnc2.isLowercaseAlpha(char)) { - value = value * 38 + char.charCodeAt(0) + 1 - 'a'.charCodeAt(0); - } else if (char == "'") { - value = value * 38 + 27; - } else if (WordEnc2.isNumerical(char)) { - value = value * 38 + char.charCodeAt(0) + 28 - '0'.charCodeAt(0); - } else if (char != '\0') { - return 0; - } - } - return value; - } - indexOfNumber(chars, offset) { - for (let index = offset; index < chars.length && index >= 0; index++) { - if (WordEnc2.isNumerical(chars[index])) { - return index; - } - } - return -1; - } - indexOfNonNumber(offset, chars) { - for (let index = offset; index < chars.length && index >= 0; index++) { - if (!WordEnc2.isNumerical(chars[index])) { - return index; - } - } - return chars.length; - } -} - -// src/lostcity/cache/wordenc/WordEncBadWords.ts -class WordEncBadWords { - wordEncFragments; - bads = []; - badCombinations = []; - constructor(wordEncFragments) { - this.wordEncFragments = wordEncFragments; - } - filter(chars) { - for (let comboIndex = 0; comboIndex < 2; comboIndex++) { - for (let index = this.bads.length - 1; index >= 0; index--) { - this.filterBadCombinations(this.badCombinations[index], chars, this.bads[index]); - } - } - } - filterBadCombinations(combos, chars, bads) { - if (bads.length > chars.length) { - return; - } - for (let startIndex = 0; startIndex <= chars.length - bads.length; startIndex++) { - let currentIndex = startIndex; - const {currentIndex: updatedCurrentIndex, badIndex, hasSymbol, hasNumber, hasDigit} = this.processBadCharacters(chars, bads, currentIndex); - currentIndex = updatedCurrentIndex; - let currentChar = chars[currentIndex]; - let nextChar = currentIndex + 1 < chars.length ? chars[currentIndex + 1] : '\0'; - if (!(badIndex >= bads.length && (!hasNumber || !hasDigit))) { - continue; - } - let shouldFilter = true; - let localIndex; - if (hasSymbol) { - let isBeforeSymbol = false; - let isAfterSymbol = false; - if (startIndex - 1 < 0 || (WordEnc2.isSymbol(chars[startIndex - 1]) && chars[startIndex - 1] != "'")) { - isBeforeSymbol = true; - } - if (currentIndex >= chars.length || (WordEnc2.isSymbol(chars[currentIndex]) && chars[currentIndex] != "'")) { - isAfterSymbol = true; - } - if (!isBeforeSymbol || !isAfterSymbol) { - let isSubstringValid = false; - localIndex = startIndex - 2; - if (isBeforeSymbol) { - localIndex = startIndex; - } - while (!isSubstringValid && localIndex < currentIndex) { - if (localIndex >= 0 && (!WordEnc2.isSymbol(chars[localIndex]) || chars[localIndex] == "'")) { - const localSubString = []; - let localSubStringIndex; - for ( - localSubStringIndex = 0; - localSubStringIndex < 3 && localIndex + localSubStringIndex < chars.length && (!WordEnc2.isSymbol(chars[localIndex + localSubStringIndex]) || chars[localIndex + localSubStringIndex] == "'"); - localSubStringIndex++ - ) { - localSubString[localSubStringIndex] = chars[localIndex + localSubStringIndex]; - } - let isSubStringValidCondition = true; - if (localSubStringIndex == 0) { - isSubStringValidCondition = false; - } - if (localSubStringIndex < 3 && localIndex - 1 >= 0 && (!WordEnc2.isSymbol(chars[localIndex - 1]) || chars[localIndex - 1] == "'")) { - isSubStringValidCondition = false; - } - if (isSubStringValidCondition && !this.wordEncFragments.isBadFragment(localSubString)) { - isSubstringValid = true; - } - } - localIndex++; - } - if (!isSubstringValid) { - shouldFilter = false; - } - } - } else { - currentChar = ' '; - if (startIndex - 1 >= 0) { - currentChar = chars[startIndex - 1]; - } - nextChar = ' '; - if (currentIndex < chars.length) { - nextChar = chars[currentIndex]; - } - const current = this.getIndex(currentChar); - const next = this.getIndex(nextChar); - if (combos != null && this.comboMatches(current, combos, next)) { - shouldFilter = false; - } - } - if (!shouldFilter) { - continue; - } - let numeralCount = 0; - let alphaCount = 0; - for (let index = startIndex; index < currentIndex; index++) { - if (WordEnc2.isNumerical(chars[index])) { - numeralCount++; - } else if (WordEnc2.isAlpha(chars[index])) { - alphaCount++; - } - } - if (numeralCount <= alphaCount) { - WordEnc2.maskChars(startIndex, currentIndex, chars); - } - } - } - processBadCharacters(chars, bads, startIndex) { - let index = startIndex; - let badIndex = 0; - let count = 0; - let hasSymbol = false; - let hasNumber = false; - let hasDigit = false; - for (; index < chars.length && !(hasNumber && hasDigit); ) { - if (index >= chars.length || (hasNumber && hasDigit)) { - break; - } - const currentChar = chars[index]; - const nextChar = index + 1 < chars.length ? chars[index + 1] : '\0'; - let currentLength; - if (badIndex < bads.length && (currentLength = this.getEmulatedBadCharLen(nextChar, String.fromCharCode(bads[badIndex]), currentChar)) > 0) { - if (currentLength === 1 && WordEnc2.isNumerical(currentChar)) { - hasNumber = true; - } - if (currentLength === 2 && (WordEnc2.isNumerical(currentChar) || WordEnc2.isNumerical(nextChar))) { - hasNumber = true; - } - index += currentLength; - badIndex++; - } else { - if (badIndex === 0) { - break; - } - let previousLength; - if ((previousLength = this.getEmulatedBadCharLen(nextChar, String.fromCharCode(bads[badIndex - 1]), currentChar)) > 0) { - index += previousLength; - } else { - if (badIndex >= bads.length || !WordEnc2.isNotLowercaseAlpha(currentChar)) { - break; - } - if (WordEnc2.isSymbol(currentChar) && currentChar !== "'") { - hasSymbol = true; - } - if (WordEnc2.isNumerical(currentChar)) { - hasDigit = true; - } - index++; - count++; - if ((((count * 100) / (index - startIndex)) | 0) > 90) { - break; - } - } - } - } - return { - currentIndex: index, - badIndex, - hasSymbol, - hasNumber, - hasDigit - }; - } - getEmulatedBadCharLen(nextChar, badChar, currentChar) { - if (badChar == currentChar) { - return 1; - } - if (badChar >= 'a' && badChar <= 'm') { - if (badChar == 'a') { - if (currentChar != '4' && currentChar != '@' && currentChar != '^') { - if (currentChar == '/' && nextChar == '\\') { - return 2; - } - return 0; - } - return 1; - } - if (badChar == 'b') { - if (currentChar != '6' && currentChar != '8') { - if (currentChar == '1' && nextChar == '3') { - return 2; - } - return 0; - } - return 1; - } - if (badChar == 'c') { - if (currentChar != '(' && currentChar != '<' && currentChar != '{' && currentChar != '[') { - return 0; - } - return 1; - } - if (badChar == 'd') { - if (currentChar == '[' && nextChar == ')') { - return 2; - } - return 0; - } - if (badChar == 'e') { - if (currentChar != '3' && currentChar != '\u20AC') { - return 0; - } - return 1; - } - if (badChar == 'f') { - if (currentChar == 'p' && nextChar == 'h') { - return 2; - } - if (currentChar == '\xA3') { - return 1; - } - return 0; - } - if (badChar == 'g') { - if (currentChar != '9' && currentChar != '6') { - return 0; - } - return 1; - } - if (badChar == 'h') { - if (currentChar == '#') { - return 1; - } - return 0; - } - if (badChar == 'i') { - if (currentChar != 'y' && currentChar != 'l' && currentChar != 'j' && currentChar != '1' && currentChar != '!' && currentChar != ':' && currentChar != ';' && currentChar != '|') { - return 0; - } - return 1; - } - if (badChar == 'j') { - return 0; - } - if (badChar == 'k') { - return 0; - } - if (badChar == 'l') { - if (currentChar != '1' && currentChar != '|' && currentChar != 'i') { - return 0; - } - return 1; - } - if (badChar == 'm') { - return 0; - } - } - if (badChar >= 'n' && badChar <= 'z') { - if (badChar == 'n') { - return 0; - } - if (badChar == 'o') { - if (currentChar != '0' && currentChar != '*') { - if ((currentChar != '(' || nextChar != ')') && (currentChar != '[' || nextChar != ']') && (currentChar != '{' || nextChar != '}') && (currentChar != '<' || nextChar != '>')) { - return 0; - } - return 2; - } - return 1; - } - if (badChar == 'p') { - return 0; - } - if (badChar == 'q') { - return 0; - } - if (badChar == 'r') { - return 0; - } - if (badChar == 's') { - if (currentChar != '5' && currentChar != 'z' && currentChar != '$' && currentChar != '2') { - return 0; - } - return 1; - } - if (badChar == 't') { - if (currentChar != '7' && currentChar != '+') { - return 0; - } - return 1; - } - if (badChar == 'u') { - if (currentChar == 'v') { - return 1; - } - if ((currentChar != '\\' || nextChar != '/') && (currentChar != '\\' || nextChar != '|') && (currentChar != '|' || nextChar != '/')) { - return 0; - } - return 2; - } - if (badChar == 'v') { - if ((currentChar != '\\' || nextChar != '/') && (currentChar != '\\' || nextChar != '|') && (currentChar != '|' || nextChar != '/')) { - return 0; - } - return 2; - } - if (badChar == 'w') { - if (currentChar == 'v' && nextChar == 'v') { - return 2; - } - return 0; - } - if (badChar == 'x') { - if ((currentChar != ')' || nextChar != '(') && (currentChar != '}' || nextChar != '{') && (currentChar != ']' || nextChar != '[') && (currentChar != '>' || nextChar != '<')) { - return 0; - } - return 2; - } - if (badChar == 'y') { - return 0; - } - if (badChar == 'z') { - return 0; - } - } - if (badChar >= '0' && badChar <= '9') { - if (badChar == '0') { - if (currentChar == 'o' || currentChar == 'O') { - return 1; - } else if ((currentChar != '(' || nextChar != ')') && (currentChar != '{' || nextChar != '}') && (currentChar != '[' || nextChar != ']')) { - return 0; - } else { - return 2; - } - } else if (badChar == '1') { - return currentChar == 'l' ? 1 : 0; - } else { - return 0; - } - } else if (badChar == ',') { - return currentChar == '.' ? 1 : 0; - } else if (badChar == '.') { - return currentChar == ',' ? 1 : 0; - } else if (badChar == '!') { - return currentChar == 'i' ? 1 : 0; - } - return 0; - } - comboMatches(currentIndex, combos, nextIndex) { - let start = 0; - let end = combos.length - 1; - while (start <= end) { - const mid = ((start + end) / 2) | 0; - if (combos[mid][0] === currentIndex && combos[mid][1] === nextIndex) { - return true; - } else if (currentIndex < combos[mid][0] || (currentIndex === combos[mid][0] && nextIndex < combos[mid][1])) { - end = mid - 1; - } else { - start = mid + 1; - } - } - return false; - } - getIndex(char) { - if (WordEnc2.isLowercaseAlpha(char)) { - return char.charCodeAt(0) + 1 - 'a'.charCodeAt(0); - } else if (char == "'") { - return 28; - } else if (WordEnc2.isNumerical(char)) { - return char.charCodeAt(0) + 29 - '0'.charCodeAt(0); - } - return 27; - } -} - -// src/lostcity/cache/wordenc/WordEncDomains.ts -class WordEncDomains { - wordEncBadWords; - domains = []; - constructor(wordEncBadWords) { - this.wordEncBadWords = wordEncBadWords; - } - filter(chars) { - const ampersat = [...chars]; - const period = [...chars]; - this.wordEncBadWords.filterBadCombinations(null, ampersat, WordEnc2.AMPERSAT); - this.wordEncBadWords.filterBadCombinations(null, period, WordEnc2.PERIOD); - for (let index = this.domains.length - 1; index >= 0; index--) { - this.filterDomain(period, ampersat, this.domains[index], chars); - } - } - getEmulatedDomainCharLen(nextChar, domainChar, currentChar) { - if (domainChar == currentChar) { - return 1; - } else if (domainChar == 'o' && currentChar == '0') { - return 1; - } else if (domainChar == 'o' && currentChar == '(' && nextChar == ')') { - return 2; - } else if (domainChar == 'c' && (currentChar == '(' || currentChar == '<' || currentChar == '[')) { - return 1; - } else if (domainChar == 'e' && currentChar == '\u20AC') { - return 1; - } else if (domainChar == 's' && currentChar == '$') { - return 1; - } else if (domainChar == 'l' && currentChar == 'i') { - return 1; - } - return 0; - } - filterDomain(period, ampersat, domain, chars) { - const domainLength = domain.length; - const charsLength = chars.length; - for (let index = 0; index <= charsLength - domainLength; index++) { - const {matched, currentIndex} = this.findMatchingDomain(index, domain, chars); - if (!matched) { - continue; - } - const ampersatStatus = WordEnc2.prefixSymbolStatus(index, chars, 3, ampersat, ['@']); - const periodStatus = WordEnc2.suffixSymbolStatus(currentIndex - 1, chars, 3, period, ['.', ',']); - const shouldFilter = ampersatStatus > 2 || periodStatus > 2; - if (!shouldFilter) { - continue; - } - WordEnc2.maskChars(index, currentIndex, chars); - } - } - findMatchingDomain(startIndex, domain, chars) { - const domainLength = domain.length; - let currentIndex = startIndex; - let domainIndex = 0; - while (currentIndex < chars.length && domainIndex < domainLength) { - const currentChar = chars[currentIndex]; - const nextChar = currentIndex + 1 < chars.length ? chars[currentIndex + 1] : '\0'; - const currentLength = this.getEmulatedDomainCharLen(nextChar, String.fromCharCode(domain[domainIndex]), currentChar); - if (currentLength > 0) { - currentIndex += currentLength; - domainIndex++; - } else { - if (domainIndex === 0) break; - const previousLength = this.getEmulatedDomainCharLen(nextChar, String.fromCharCode(domain[domainIndex - 1]), currentChar); - if (previousLength > 0) { - currentIndex += previousLength; - if (domainIndex === 1) startIndex++; - } else { - if (domainIndex >= domainLength || !WordEnc2.isSymbol(currentChar)) break; - currentIndex++; - } - } - } - return {matched: domainIndex >= domainLength, currentIndex}; - } -} - -// src/lostcity/cache/wordenc/WordEncTlds.ts -class WordEncTlds { - wordEncBadWords; - wordEncDomains; - tlds = []; - tldTypes = []; - constructor(wordEncBadWords, wordEncDomains) { - this.wordEncBadWords = wordEncBadWords; - this.wordEncDomains = wordEncDomains; - } - filter(chars) { - const period = [...chars]; - const slash = [...chars]; - this.wordEncBadWords.filterBadCombinations(null, period, WordEnc2.PERIOD); - this.wordEncBadWords.filterBadCombinations(null, slash, WordEnc2.SLASH); - for (let index = 0; index < this.tlds.length; index++) { - this.filterTld(slash, this.tldTypes[index], chars, this.tlds[index], period); - } - } - filterTld(slash, tldType, chars, tld, period) { - if (tld.length > chars.length) { - return; - } - for (let index = 0; index <= chars.length - tld.length; index++) { - const {currentIndex, tldIndex} = this.processTlds(chars, tld, index); - if (tldIndex < tld.length) { - continue; - } - let shouldFilter = false; - const periodFilterStatus = WordEnc2.prefixSymbolStatus(index, chars, 3, period, [',', '.']); - const slashFilterStatus = WordEnc2.suffixSymbolStatus(currentIndex - 1, chars, 5, slash, ['\\', '/']); - if (tldType == 1 && periodFilterStatus > 0 && slashFilterStatus > 0) { - shouldFilter = true; - } - if (tldType == 2 && ((periodFilterStatus > 2 && slashFilterStatus > 0) || (periodFilterStatus > 0 && slashFilterStatus > 2))) { - shouldFilter = true; - } - if (tldType == 3 && periodFilterStatus > 0 && slashFilterStatus > 2) { - shouldFilter = true; - } - if (!shouldFilter) { - continue; - } - let startFilterIndex = index; - let endFilterIndex = currentIndex - 1; - let foundPeriod = false; - let periodIndex; - if (periodFilterStatus > 2) { - if (periodFilterStatus == 4) { - foundPeriod = false; - for (periodIndex = index - 1; periodIndex >= 0; periodIndex--) { - if (foundPeriod) { - if (period[periodIndex] != '*') { - break; - } - startFilterIndex = periodIndex; - } else if (period[periodIndex] == '*') { - startFilterIndex = periodIndex; - foundPeriod = true; - } - } - } - foundPeriod = false; - for (periodIndex = startFilterIndex - 1; periodIndex >= 0; periodIndex--) { - if (foundPeriod) { - if (WordEnc2.isSymbol(chars[periodIndex])) { - break; - } - startFilterIndex = periodIndex; - } else if (!WordEnc2.isSymbol(chars[periodIndex])) { - foundPeriod = true; - startFilterIndex = periodIndex; - } - } - } - if (slashFilterStatus > 2) { - if (slashFilterStatus == 4) { - foundPeriod = false; - for (periodIndex = endFilterIndex + 1; periodIndex < chars.length; periodIndex++) { - if (foundPeriod) { - if (slash[periodIndex] != '*') { - break; - } - endFilterIndex = periodIndex; - } else if (slash[periodIndex] == '*') { - endFilterIndex = periodIndex; - foundPeriod = true; - } - } - } - foundPeriod = false; - for (periodIndex = endFilterIndex + 1; periodIndex < chars.length; periodIndex++) { - if (foundPeriod) { - if (WordEnc2.isSymbol(chars[periodIndex])) { - break; - } - endFilterIndex = periodIndex; - } else if (!WordEnc2.isSymbol(chars[periodIndex])) { - foundPeriod = true; - endFilterIndex = periodIndex; - } - } - } - WordEnc2.maskChars(startFilterIndex, endFilterIndex + 1, chars); - } - } - processTlds(chars, tld, currentIndex) { - let tldIndex = 0; - while (currentIndex < chars.length && tldIndex < tld.length) { - const currentChar = chars[currentIndex]; - const nextChar = currentIndex + 1 < chars.length ? chars[currentIndex + 1] : '\0'; - let currentLength; - if ((currentLength = this.wordEncDomains.getEmulatedDomainCharLen(nextChar, String.fromCharCode(tld[tldIndex]), currentChar)) > 0) { - currentIndex += currentLength; - tldIndex++; - } else { - if (tldIndex === 0) { - break; - } - let previousLength; - if ((previousLength = this.wordEncDomains.getEmulatedDomainCharLen(nextChar, String.fromCharCode(tld[tldIndex - 1]), currentChar)) > 0) { - currentIndex += previousLength; - } else { - if (!WordEnc2.isSymbol(currentChar)) { - break; - } - currentIndex++; - } - } - } - return {currentIndex, tldIndex}; - } -} - -// src/lostcity/cache/wordenc/WordEnc.ts -class WordEnc2 { - static PERIOD = new Uint16Array( - ['d', 'o', 't'] - .join('') - .split('') - .map(char => char.charCodeAt(0)) - ); - static AMPERSAT = new Uint16Array( - ['(', 'a', ')'] - .join('') - .split('') - .map(char => char.charCodeAt(0)) - ); - static SLASH = new Uint16Array( - ['s', 'l', 'a', 's', 'h'] - .join('') - .split('') - .map(char => char.charCodeAt(0)) - ); - static wordEncFragments = new WordEncFragments(); - static wordEncBadWords = new WordEncBadWords(this.wordEncFragments); - static wordEncDomains = new WordEncDomains(this.wordEncBadWords); - static wordEncTlds = new WordEncTlds(this.wordEncBadWords, this.wordEncDomains); - static whitelist = ['cook', "cook's", 'cooks', 'seeks', 'sheet']; - static async load(dir) { - if (!(await fetch(`${dir}/client/wordenc`)).ok) { - console.log('Warning: No wordenc found.'); - return; - } - const wordenc = await Jagfile.load(`${dir}/client/wordenc`); - const fragmentsenc = wordenc.read('fragmentsenc.txt'); - if (!fragmentsenc) { - console.log('Warning: No fragmentsenc found.'); - return; - } - const badenc = wordenc.read('badenc.txt'); - if (!badenc) { - console.log('Warning: No badenc found.'); - return; - } - const domainenc = wordenc.read('domainenc.txt'); - if (!domainenc) { - console.log('Warning: No domainenc found.'); - return; - } - const tldlist = wordenc.read('tldlist.txt'); - if (!tldlist) { - console.log('Warning: No tldlist found.'); - return; - } - this.decodeBadEnc(badenc); - this.decodeDomainEnc(domainenc); - this.decodeFragmentsEnc(fragmentsenc); - this.decodeTldList(tldlist); - } - static filter(input) { - const characters = [...input]; - this.format(characters); - const trimmed = characters.join('').trim(); - const lowercase = trimmed.toLowerCase(); - const filtered = [...lowercase]; - this.wordEncTlds.filter(filtered); - this.wordEncBadWords.filter(filtered); - this.wordEncDomains.filter(filtered); - this.wordEncFragments.filter(filtered); - for (let index = 0; index < this.whitelist.length; index++) { - let offset = -1; - while ((offset = lowercase.indexOf(this.whitelist[index], offset + 1)) !== -1) { - const whitelisted = [...this.whitelist[index]]; - for (let charIndex = 0; charIndex < whitelisted.length; charIndex++) { - filtered[charIndex + offset] = whitelisted[charIndex]; - } - } - } - this.replaceUppercases(filtered, [...trimmed]); - this.formatUppercases(filtered); - return filtered.join('').trim(); - } - static isSymbol(char) { - return !this.isAlpha(char) && !this.isNumerical(char); - } - static isNotLowercaseAlpha(char) { - return this.isLowercaseAlpha(char) ? char == 'v' || char == 'x' || char == 'j' || char == 'q' || char == 'z' : true; - } - static isAlpha(char) { - return this.isLowercaseAlpha(char) || this.isUppercaseAlpha(char); - } - static isNumerical(char) { - return char >= '0' && char <= '9'; - } - static isLowercaseAlpha(char) { - return char >= 'a' && char <= 'z'; - } - static isUppercaseAlpha(char) { - return char >= 'A' && char <= 'Z'; - } - static isNumericalChars(chars) { - for (let index = 0; index < chars.length; index++) { - if (!this.isNumerical(chars[index]) && chars[index] !== '\0') { - return false; - } - } - return true; - } - static maskChars(offset, length, chars) { - for (let index = offset; index < length; index++) { - chars[index] = '*'; - } - } - static maskedCountBackwards(chars, offset) { - let count = 0; - for (let index = offset - 1; index >= 0 && WordEnc2.isSymbol(chars[index]); index--) { - if (chars[index] === '*') { - count++; - } - } - return count; - } - static maskedCountForwards(chars, offset) { - let count = 0; - for (let index = offset + 1; index < chars.length && this.isSymbol(chars[index]); index++) { - if (chars[index] === '*') { - count++; - } - } - return count; - } - static maskedCharsStatus(chars, filtered, offset, length, prefix) { - const count = prefix ? this.maskedCountBackwards(filtered, offset) : this.maskedCountForwards(filtered, offset); - if (count >= length) { - return 4; - } else if (this.isSymbol(prefix ? chars[offset - 1] : chars[offset + 1])) { - return 1; - } - return 0; - } - static prefixSymbolStatus(offset, chars, length, symbolChars, symbols) { - if (offset === 0) { - return 2; - } - for (let index = offset - 1; index >= 0 && WordEnc2.isSymbol(chars[index]); index--) { - if (symbols.includes(chars[index])) { - return 3; - } - } - return WordEnc2.maskedCharsStatus(chars, symbolChars, offset, length, true); - } - static suffixSymbolStatus(offset, chars, length, symbolChars, symbols) { - if (offset + 1 === chars.length) { - return 2; - } - for (let index = offset + 1; index < chars.length && WordEnc2.isSymbol(chars[index]); index++) { - if (symbols.includes(chars[index])) { - return 3; - } - } - return WordEnc2.maskedCharsStatus(chars, symbolChars, offset, length, false); - } - static decodeTldList(packet) { - const count = packet.g4(); - for (let index = 0; index < count; index++) { - this.wordEncTlds.tldTypes[index] = packet.g1(); - this.wordEncTlds.tlds[index] = new Uint16Array(packet.g1()).map(() => packet.g1()); - } - } - static decodeBadEnc(packet) { - const count = packet.g4(); - for (let index = 0; index < count; index++) { - this.wordEncBadWords.bads[index] = new Uint16Array(packet.g1()).map(() => packet.g1()); - const combos = new Array(packet.g1()).fill([]).map(() => [packet.g1b(), packet.g1b()]); - if (combos.length > 0) { - this.wordEncBadWords.badCombinations[index] = combos; - } - } - } - static decodeDomainEnc(packet) { - const count = packet.g4(); - for (let index = 0; index < count; index++) { - this.wordEncDomains.domains[index] = new Uint16Array(packet.g1()).map(() => packet.g1()); - } - } - static decodeFragmentsEnc(packet) { - const count = packet.g4(); - for (let index = 0; index < count; index++) { - this.wordEncFragments.fragments[index] = packet.g2(); - } - } - static format(chars) { - let pos = 0; - for (let index = 0; index < chars.length; index++) { - if (this.isCharacterAllowed(chars[index])) { - chars[pos] = chars[index]; - } else { - chars[pos] = ' '; - } - if (pos === 0 || chars[pos] !== ' ' || chars[pos - 1] !== ' ') { - pos++; - } - } - for (let index = pos; index < chars.length; index++) { - chars[index] = ' '; - } - } - static isCharacterAllowed(char) { - return (char >= ' ' && char <= '\x7F') || char == ' ' || char == '\n' || char == '\t' || char == '\xA3' || char == '\u20AC'; - } - static replaceUppercases(chars, comparison) { - for (let index = 0; index < comparison.length; index++) { - if (chars[index] !== '*' && this.isUppercaseAlpha(comparison[index])) { - chars[index] = comparison[index]; - } - } - } - static formatUppercases(chars) { - let flagged = true; - for (let index = 0; index < chars.length; index++) { - const char = chars[index]; - if (!this.isAlpha(char)) { - flagged = true; - } else if (flagged) { - if (this.isLowercaseAlpha(char)) { - flagged = false; - } - } else if (this.isUppercaseAlpha(char)) { - chars[index] = String.fromCharCode(char.charCodeAt(0) + 'a'.charCodeAt(0) - 65); - } - } - } -} - -// src/lostcity/cache/config/SpotanimType.ts -class SpotanimType extends ConfigType { - static configNames = new Map(); - static configs = []; - static async load(dir) { - SpotanimType.configNames = new Map(); - SpotanimType.configs = []; - if (!(await fetch(`${dir}/server/spotanim.dat`)).ok) { - console.log('Warning: No spotanim.dat found.'); - return; - } - const server = await Packet.load(`${dir}/server/spotanim.dat`); - const count = server.g2(); - const jag = await Jagfile.load(`${dir}/client/config`); - const client = jag.read('spotanim.dat'); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new SpotanimType(id); - config.decodeType(server); - config.decodeType(client); - SpotanimType.configs[id] = config; - if (config.debugname) { - SpotanimType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return SpotanimType.configs[id]; - } - static getId(name) { - return SpotanimType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - model = 0; - anim = -1; - hasalpha = false; - recol_s = new Uint16Array(6); - recol_d = new Uint16Array(6); - resizeh = 128; - resizev = 128; - orientation = 0; - ambient = 0; - contrast = 0; - decode(code, dat) { - if (code === 1) { - this.model = dat.g2(); - } else if (code === 2) { - this.anim = dat.g2(); - } else if (code === 3) { - this.hasalpha = true; - } else if (code === 4) { - this.resizeh = dat.g2(); - } else if (code === 5) { - this.resizev = dat.g2(); - } else if (code === 6) { - this.orientation = dat.g2(); - } else if (code === 7) { - this.ambient = dat.g1(); - } else if (code === 8) { - this.contrast = dat.g1(); - } else if (code >= 40 && code < 50) { - this.recol_s[code - 40] = dat.g2(); - } else if (code >= 50 && code < 60) { - this.recol_d[code - 50] = dat.g2(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized spotanim config code: ${code}`); - } - } -} - -// src/lostcity/engine/script/ScriptPointer.ts -function checkedHandler(pointer, handler) { - return function (state) { - if (typeof pointer === 'number') { - state.pointerCheck(pointer); - } else { - state.pointerCheck(pointer[state.intOperand]); - } - handler(state); - }; -} -var ScriptPointer; -(ScriptPointer2 => { - ScriptPointer2[(ScriptPointer2['ActivePlayer'] = 0)] = 'ActivePlayer'; - ScriptPointer2[(ScriptPointer2['ActivePlayer2'] = 1)] = 'ActivePlayer2'; - ScriptPointer2[(ScriptPointer2['ProtectedActivePlayer'] = 2)] = 'ProtectedActivePlayer'; - ScriptPointer2[(ScriptPointer2['ProtectedActivePlayer2'] = 3)] = 'ProtectedActivePlayer2'; - ScriptPointer2[(ScriptPointer2['ActiveNpc'] = 4)] = 'ActiveNpc'; - ScriptPointer2[(ScriptPointer2['ActiveNpc2'] = 5)] = 'ActiveNpc2'; - ScriptPointer2[(ScriptPointer2['ActiveLoc'] = 6)] = 'ActiveLoc'; - ScriptPointer2[(ScriptPointer2['ActiveLoc2'] = 7)] = 'ActiveLoc2'; - ScriptPointer2[(ScriptPointer2['ActiveObj'] = 8)] = 'ActiveObj'; - ScriptPointer2[(ScriptPointer2['ActiveObj2'] = 9)] = 'ActiveObj2'; - ScriptPointer2[(ScriptPointer2['_LAST'] = 10)] = '_LAST'; -})((ScriptPointer ||= {})); -var ActiveNpc = [4 /* ActiveNpc */, 5 /* ActiveNpc2 */]; -var ActiveLoc = [6 /* ActiveLoc */, 7 /* ActiveLoc2 */]; -var ActiveObj = [8 /* ActiveObj */, 9 /* ActiveObj2 */]; -var ActivePlayer = [0 /* ActivePlayer */, 1 /* ActivePlayer2 */]; -var ProtectedActivePlayer = [2 /* ProtectedActivePlayer */, 3 /* ProtectedActivePlayer2 */]; -var ScriptPointer_default = ScriptPointer; - -// node:path -var L = Object.create; -var b = Object.defineProperty; -var z = Object.getOwnPropertyDescriptor; -var D = Object.getOwnPropertyNames; -var T = Object.getPrototypeOf; -var R = Object.prototype.hasOwnProperty; -var _ = (f, e) => () => (e || f((e = {exports: {}}).exports, e), e.exports); -var E = (f, e) => { - for (var r in e) b(f, r, {get: e[r], enumerable: true}); -}; -var C = (f, e, r, l) => { - if ((e && typeof e == 'object') || typeof e == 'function') for (let i of D(e)) !R.call(f, i) && i !== r && b(f, i, {get: () => e[i], enumerable: !(l = z(e, i)) || l.enumerable}); - return f; -}; -var A = (f, e, r) => (C(f, e, 'default'), r && C(r, e, 'default')); -var y = (f, e, r) => ((r = f != null ? L(T(f)) : {}), C(e || !f || !f.__esModule ? b(r, 'default', {value: f, enumerable: true}) : r, f)); -var h = _((F, S) => { - function c(f) { - if (typeof f != 'string') throw new TypeError('Path must be a string. Received ' + JSON.stringify(f)); - } - function w(f, e) { - for (var r = '', l = 0, i = -1, s = 0, n, t = 0; t <= f.length; ++t) { - if (t < f.length) n = f.charCodeAt(t); - else { - if (n === 47) break; - n = 47; - } - if (n === 47) { - if (!(i === t - 1 || s === 1)) - if (i !== t - 1 && s === 2) { - if (r.length < 2 || l !== 2 || r.charCodeAt(r.length - 1) !== 46 || r.charCodeAt(r.length - 2) !== 46) { - if (r.length > 2) { - var a = r.lastIndexOf('/'); - if (a !== r.length - 1) { - a === -1 ? ((r = ''), (l = 0)) : ((r = r.slice(0, a)), (l = r.length - 1 - r.lastIndexOf('/'))), (i = t), (s = 0); - continue; - } - } else if (r.length === 2 || r.length === 1) { - (r = ''), (l = 0), (i = t), (s = 0); - continue; - } - } - e && (r.length > 0 ? (r += '/..') : (r = '..'), (l = 2)); - } else r.length > 0 ? (r += '/' + f.slice(i + 1, t)) : (r = f.slice(i + 1, t)), (l = t - i - 1); - (i = t), (s = 0); - } else n === 46 && s !== -1 ? ++s : (s = -1); - } - return r; - } - function J(f, e) { - var r = e.dir || e.root, - l = e.base || (e.name || '') + (e.ext || ''); - return r ? (r === e.root ? r + l : r + f + l) : l; - } - var g = { - resolve: function () { - for (var e = '', r = false, l, i = arguments.length - 1; i >= -1 && !r; i--) { - var s; - i >= 0 ? (s = arguments[i]) : (l === undefined && (l = process.cwd()), (s = l)), c(s), s.length !== 0 && ((e = s + '/' + e), (r = s.charCodeAt(0) === 47)); - } - return (e = w(e, !r)), r ? (e.length > 0 ? '/' + e : '/') : e.length > 0 ? e : '.'; - }, - normalize: function (e) { - if ((c(e), e.length === 0)) return '.'; - var r = e.charCodeAt(0) === 47, - l = e.charCodeAt(e.length - 1) === 47; - return (e = w(e, !r)), e.length === 0 && !r && (e = '.'), e.length > 0 && l && (e += '/'), r ? '/' + e : e; - }, - isAbsolute: function (e) { - return c(e), e.length > 0 && e.charCodeAt(0) === 47; - }, - join: function () { - if (arguments.length === 0) return '.'; - for (var e, r = 0; r < arguments.length; ++r) { - var l = arguments[r]; - c(l), l.length > 0 && (e === undefined ? (e = l) : (e += '/' + l)); - } - return e === undefined ? '.' : g.normalize(e); - }, - relative: function (e, r) { - if ((c(e), c(r), e === r || ((e = g.resolve(e)), (r = g.resolve(r)), e === r))) return ''; - for (var l = 1; l < e.length && e.charCodeAt(l) === 47; ++l); - for (var i = e.length, s = i - l, n = 1; n < r.length && r.charCodeAt(n) === 47; ++n); - for (var t = r.length, a = t - n, v = s < a ? s : a, u = -1, o = 0; o <= v; ++o) { - if (o === v) { - if (a > v) { - if (r.charCodeAt(n + o) === 47) return r.slice(n + o + 1); - if (o === 0) return r.slice(n + o); - } else s > v && (e.charCodeAt(l + o) === 47 ? (u = o) : o === 0 && (u = 0)); - break; - } - var k = e.charCodeAt(l + o), - P = r.charCodeAt(n + o); - if (k !== P) break; - k === 47 && (u = o); - } - var d = ''; - for (o = l + u + 1; o <= i; ++o) (o === i || e.charCodeAt(o) === 47) && (d.length === 0 ? (d += '..') : (d += '/..')); - return d.length > 0 ? d + r.slice(n + u) : ((n += u), r.charCodeAt(n) === 47 && ++n, r.slice(n)); - }, - _makeLong: function (e) { - return e; - }, - dirname: function (e) { - if ((c(e), e.length === 0)) return '.'; - for (var r = e.charCodeAt(0), l = r === 47, i = -1, s = true, n = e.length - 1; n >= 1; --n) - if (((r = e.charCodeAt(n)), r === 47)) { - if (!s) { - i = n; - break; - } - } else s = false; - return i === -1 ? (l ? '/' : '.') : l && i === 1 ? '//' : e.slice(0, i); - }, - basename: function (e, r) { - if (r !== undefined && typeof r != 'string') throw new TypeError('"ext" argument must be a string'); - c(e); - var l = 0, - i = -1, - s = true, - n; - if (r !== undefined && r.length > 0 && r.length <= e.length) { - if (r.length === e.length && r === e) return ''; - var t = r.length - 1, - a = -1; - for (n = e.length - 1; n >= 0; --n) { - var v = e.charCodeAt(n); - if (v === 47) { - if (!s) { - l = n + 1; - break; - } - } else a === -1 && ((s = false), (a = n + 1)), t >= 0 && (v === r.charCodeAt(t) ? --t === -1 && (i = n) : ((t = -1), (i = a))); - } - return l === i ? (i = a) : i === -1 && (i = e.length), e.slice(l, i); - } else { - for (n = e.length - 1; n >= 0; --n) - if (e.charCodeAt(n) === 47) { - if (!s) { - l = n + 1; - break; - } - } else i === -1 && ((s = false), (i = n + 1)); - return i === -1 ? '' : e.slice(l, i); - } - }, - extname: function (e) { - c(e); - for (var r = -1, l = 0, i = -1, s = true, n = 0, t = e.length - 1; t >= 0; --t) { - var a = e.charCodeAt(t); - if (a === 47) { - if (!s) { - l = t + 1; - break; - } - continue; - } - i === -1 && ((s = false), (i = t + 1)), a === 46 ? (r === -1 ? (r = t) : n !== 1 && (n = 1)) : r !== -1 && (n = -1); - } - return r === -1 || i === -1 || n === 0 || (n === 1 && r === i - 1 && r === l + 1) ? '' : e.slice(r, i); - }, - format: function (e) { - if (e === null || typeof e != 'object') throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof e); - return J('/', e); - }, - parse: function (e) { - c(e); - var r = {root: '', dir: '', base: '', ext: '', name: ''}; - if (e.length === 0) return r; - var l = e.charCodeAt(0), - i = l === 47, - s; - i ? ((r.root = '/'), (s = 1)) : (s = 0); - for (var n = -1, t = 0, a = -1, v = true, u = e.length - 1, o = 0; u >= s; --u) { - if (((l = e.charCodeAt(u)), l === 47)) { - if (!v) { - t = u + 1; - break; - } - continue; - } - a === -1 && ((v = false), (a = u + 1)), l === 46 ? (n === -1 ? (n = u) : o !== 1 && (o = 1)) : n !== -1 && (o = -1); - } - return ( - n === -1 || a === -1 || o === 0 || (o === 1 && n === a - 1 && n === t + 1) - ? a !== -1 && (t === 0 && i ? (r.base = r.name = e.slice(1, a)) : (r.base = r.name = e.slice(t, a))) - : (t === 0 && i ? ((r.name = e.slice(1, n)), (r.base = e.slice(1, a))) : ((r.name = e.slice(t, n)), (r.base = e.slice(t, a))), (r.ext = e.slice(n, a))), - t > 0 ? (r.dir = e.slice(0, t - 1)) : i && (r.dir = '/'), - r - ); - }, - sep: '/', - delimiter: ':', - win32: null, - posix: null - }; - g.posix = g; - S.exports = g; -}); -var m = {}; -E(m, {default: () => q}); -A(m, y(h())); -var q = y(h()); - -// src/lostcity/engine/script/ScriptOpcode.ts -var ScriptOpcode; -(ScriptOpcode2 => { - ScriptOpcode2[(ScriptOpcode2['PUSH_CONSTANT_INT'] = 0)] = 'PUSH_CONSTANT_INT'; - ScriptOpcode2[(ScriptOpcode2['PUSH_VARP'] = 1)] = 'PUSH_VARP'; - ScriptOpcode2[(ScriptOpcode2['POP_VARP'] = 2)] = 'POP_VARP'; - ScriptOpcode2[(ScriptOpcode2['PUSH_CONSTANT_STRING'] = 3)] = 'PUSH_CONSTANT_STRING'; - ScriptOpcode2[(ScriptOpcode2['PUSH_VARN'] = 4)] = 'PUSH_VARN'; - ScriptOpcode2[(ScriptOpcode2['POP_VARN'] = 5)] = 'POP_VARN'; - ScriptOpcode2[(ScriptOpcode2['BRANCH'] = 6)] = 'BRANCH'; - ScriptOpcode2[(ScriptOpcode2['BRANCH_NOT'] = 7)] = 'BRANCH_NOT'; - ScriptOpcode2[(ScriptOpcode2['BRANCH_EQUALS'] = 8)] = 'BRANCH_EQUALS'; - ScriptOpcode2[(ScriptOpcode2['BRANCH_LESS_THAN'] = 9)] = 'BRANCH_LESS_THAN'; - ScriptOpcode2[(ScriptOpcode2['BRANCH_GREATER_THAN'] = 10)] = 'BRANCH_GREATER_THAN'; - ScriptOpcode2[(ScriptOpcode2['PUSH_VARS'] = 11)] = 'PUSH_VARS'; - ScriptOpcode2[(ScriptOpcode2['POP_VARS'] = 12)] = 'POP_VARS'; - ScriptOpcode2[(ScriptOpcode2['RETURN'] = 21)] = 'RETURN'; - ScriptOpcode2[(ScriptOpcode2['GOSUB'] = 22)] = 'GOSUB'; - ScriptOpcode2[(ScriptOpcode2['JUMP'] = 23)] = 'JUMP'; - ScriptOpcode2[(ScriptOpcode2['SWITCH'] = 24)] = 'SWITCH'; - ScriptOpcode2[(ScriptOpcode2['BRANCH_LESS_THAN_OR_EQUALS'] = 31)] = 'BRANCH_LESS_THAN_OR_EQUALS'; - ScriptOpcode2[(ScriptOpcode2['BRANCH_GREATER_THAN_OR_EQUALS'] = 32)] = 'BRANCH_GREATER_THAN_OR_EQUALS'; - ScriptOpcode2[(ScriptOpcode2['PUSH_INT_LOCAL'] = 33)] = 'PUSH_INT_LOCAL'; - ScriptOpcode2[(ScriptOpcode2['POP_INT_LOCAL'] = 34)] = 'POP_INT_LOCAL'; - ScriptOpcode2[(ScriptOpcode2['PUSH_STRING_LOCAL'] = 35)] = 'PUSH_STRING_LOCAL'; - ScriptOpcode2[(ScriptOpcode2['POP_STRING_LOCAL'] = 36)] = 'POP_STRING_LOCAL'; - ScriptOpcode2[(ScriptOpcode2['JOIN_STRING'] = 37)] = 'JOIN_STRING'; - ScriptOpcode2[(ScriptOpcode2['POP_INT_DISCARD'] = 38)] = 'POP_INT_DISCARD'; - ScriptOpcode2[(ScriptOpcode2['POP_STRING_DISCARD'] = 39)] = 'POP_STRING_DISCARD'; - ScriptOpcode2[(ScriptOpcode2['GOSUB_WITH_PARAMS'] = 40)] = 'GOSUB_WITH_PARAMS'; - ScriptOpcode2[(ScriptOpcode2['JUMP_WITH_PARAMS'] = 41)] = 'JUMP_WITH_PARAMS'; - ScriptOpcode2[(ScriptOpcode2['DEFINE_ARRAY'] = 44)] = 'DEFINE_ARRAY'; - ScriptOpcode2[(ScriptOpcode2['PUSH_ARRAY_INT'] = 45)] = 'PUSH_ARRAY_INT'; - ScriptOpcode2[(ScriptOpcode2['POP_ARRAY_INT'] = 46)] = 'POP_ARRAY_INT'; - ScriptOpcode2[(ScriptOpcode2['COORDX'] = 1000)] = 'COORDX'; - ScriptOpcode2[(ScriptOpcode2['COORDY'] = 1001)] = 'COORDY'; - ScriptOpcode2[(ScriptOpcode2['COORDZ'] = 1002)] = 'COORDZ'; - ScriptOpcode2[(ScriptOpcode2['DISTANCE'] = 1003)] = 'DISTANCE'; - ScriptOpcode2[(ScriptOpcode2['HUNTALL'] = 1004)] = 'HUNTALL'; - ScriptOpcode2[(ScriptOpcode2['HUNTNEXT'] = 1005)] = 'HUNTNEXT'; - ScriptOpcode2[(ScriptOpcode2['INZONE'] = 1006)] = 'INZONE'; - ScriptOpcode2[(ScriptOpcode2['LINEOFSIGHT'] = 1007)] = 'LINEOFSIGHT'; - ScriptOpcode2[(ScriptOpcode2['LINEOFWALK'] = 1008)] = 'LINEOFWALK'; - ScriptOpcode2[(ScriptOpcode2['MAP_BLOCKED'] = 1009)] = 'MAP_BLOCKED'; - ScriptOpcode2[(ScriptOpcode2['MAP_INDOORS'] = 1010)] = 'MAP_INDOORS'; - ScriptOpcode2[(ScriptOpcode2['MAP_CLOCK'] = 1011)] = 'MAP_CLOCK'; - ScriptOpcode2[(ScriptOpcode2['MAP_LOCADDUNSAFE'] = 1012)] = 'MAP_LOCADDUNSAFE'; - ScriptOpcode2[(ScriptOpcode2['MAP_MEMBERS'] = 1013)] = 'MAP_MEMBERS'; - ScriptOpcode2[(ScriptOpcode2['MAP_PLAYERCOUNT'] = 1014)] = 'MAP_PLAYERCOUNT'; - ScriptOpcode2[(ScriptOpcode2['MOVECOORD'] = 1015)] = 'MOVECOORD'; - ScriptOpcode2[(ScriptOpcode2['PLAYERCOUNT'] = 1016)] = 'PLAYERCOUNT'; - ScriptOpcode2[(ScriptOpcode2['PROJANIM_MAP'] = 1017)] = 'PROJANIM_MAP'; - ScriptOpcode2[(ScriptOpcode2['PROJANIM_NPC'] = 1018)] = 'PROJANIM_NPC'; - ScriptOpcode2[(ScriptOpcode2['PROJANIM_PL'] = 1019)] = 'PROJANIM_PL'; - ScriptOpcode2[(ScriptOpcode2['SEQLENGTH'] = 1020)] = 'SEQLENGTH'; - ScriptOpcode2[(ScriptOpcode2['SPLIT_GET'] = 1021)] = 'SPLIT_GET'; - ScriptOpcode2[(ScriptOpcode2['SPLIT_GETANIM'] = 1022)] = 'SPLIT_GETANIM'; - ScriptOpcode2[(ScriptOpcode2['SPLIT_INIT'] = 1023)] = 'SPLIT_INIT'; - ScriptOpcode2[(ScriptOpcode2['SPLIT_LINECOUNT'] = 1024)] = 'SPLIT_LINECOUNT'; - ScriptOpcode2[(ScriptOpcode2['SPLIT_PAGECOUNT'] = 1025)] = 'SPLIT_PAGECOUNT'; - ScriptOpcode2[(ScriptOpcode2['SPOTANIM_MAP'] = 1026)] = 'SPOTANIM_MAP'; - ScriptOpcode2[(ScriptOpcode2['STAT_RANDOM'] = 1027)] = 'STAT_RANDOM'; - ScriptOpcode2[(ScriptOpcode2['STRUCT_PARAM'] = 1028)] = 'STRUCT_PARAM'; - ScriptOpcode2[(ScriptOpcode2['WORLD_DELAY'] = 1029)] = 'WORLD_DELAY'; - ScriptOpcode2[(ScriptOpcode2['NPCCOUNT'] = 1030)] = 'NPCCOUNT'; - ScriptOpcode2[(ScriptOpcode2['ZONECOUNT'] = 1031)] = 'ZONECOUNT'; - ScriptOpcode2[(ScriptOpcode2['LOCCOUNT'] = 1032)] = 'LOCCOUNT'; - ScriptOpcode2[(ScriptOpcode2['OBJCOUNT'] = 1033)] = 'OBJCOUNT'; - ScriptOpcode2[(ScriptOpcode2['ALLOWDESIGN'] = 2000)] = 'ALLOWDESIGN'; - ScriptOpcode2[(ScriptOpcode2['ANIM'] = 2001)] = 'ANIM'; - ScriptOpcode2[(ScriptOpcode2['BAS_READYANIM'] = 2002)] = 'BAS_READYANIM'; - ScriptOpcode2[(ScriptOpcode2['BAS_RUNNING'] = 2003)] = 'BAS_RUNNING'; - ScriptOpcode2[(ScriptOpcode2['BAS_TURNONSPOT'] = 2004)] = 'BAS_TURNONSPOT'; - ScriptOpcode2[(ScriptOpcode2['BAS_WALK_B'] = 2005)] = 'BAS_WALK_B'; - ScriptOpcode2[(ScriptOpcode2['BAS_WALK_F'] = 2006)] = 'BAS_WALK_F'; - ScriptOpcode2[(ScriptOpcode2['BAS_WALK_L'] = 2007)] = 'BAS_WALK_L'; - ScriptOpcode2[(ScriptOpcode2['BAS_WALK_R'] = 2008)] = 'BAS_WALK_R'; - ScriptOpcode2[(ScriptOpcode2['BUFFER_FULL'] = 2009)] = 'BUFFER_FULL'; - ScriptOpcode2[(ScriptOpcode2['BUILDAPPEARANCE'] = 2010)] = 'BUILDAPPEARANCE'; - ScriptOpcode2[(ScriptOpcode2['BUSY'] = 2011)] = 'BUSY'; - ScriptOpcode2[(ScriptOpcode2['CAM_LOOKAT'] = 2012)] = 'CAM_LOOKAT'; - ScriptOpcode2[(ScriptOpcode2['CAM_MOVETO'] = 2013)] = 'CAM_MOVETO'; - ScriptOpcode2[(ScriptOpcode2['CAM_RESET'] = 2014)] = 'CAM_RESET'; - ScriptOpcode2[(ScriptOpcode2['CAM_SHAKE'] = 2015)] = 'CAM_SHAKE'; - ScriptOpcode2[(ScriptOpcode2['CLEARQUEUE'] = 2016)] = 'CLEARQUEUE'; - ScriptOpcode2[(ScriptOpcode2['CLEARSOFTTIMER'] = 2017)] = 'CLEARSOFTTIMER'; - ScriptOpcode2[(ScriptOpcode2['CLEARTIMER'] = 2018)] = 'CLEARTIMER'; - ScriptOpcode2[(ScriptOpcode2['COORD'] = 2019)] = 'COORD'; - ScriptOpcode2[(ScriptOpcode2['DAMAGE'] = 2020)] = 'DAMAGE'; - ScriptOpcode2[(ScriptOpcode2['DISPLAYNAME'] = 2021)] = 'DISPLAYNAME'; - ScriptOpcode2[(ScriptOpcode2['FACESQUARE'] = 2022)] = 'FACESQUARE'; - ScriptOpcode2[(ScriptOpcode2['FINDUID'] = 2023)] = 'FINDUID'; - ScriptOpcode2[(ScriptOpcode2['GENDER'] = 2024)] = 'GENDER'; - ScriptOpcode2[(ScriptOpcode2['GETQUEUE'] = 2025)] = 'GETQUEUE'; - ScriptOpcode2[(ScriptOpcode2['GIVEXP'] = 2026)] = 'GIVEXP'; - ScriptOpcode2[(ScriptOpcode2['HEADICONS_GET'] = 2027)] = 'HEADICONS_GET'; - ScriptOpcode2[(ScriptOpcode2['HEADICONS_SET'] = 2028)] = 'HEADICONS_SET'; - ScriptOpcode2[(ScriptOpcode2['HEALENERGY'] = 2029)] = 'HEALENERGY'; - ScriptOpcode2[(ScriptOpcode2['HINT_COORD'] = 2030)] = 'HINT_COORD'; - ScriptOpcode2[(ScriptOpcode2['HINT_NPC'] = 2031)] = 'HINT_NPC'; - ScriptOpcode2[(ScriptOpcode2['HINT_PLAYER'] = 2032)] = 'HINT_PLAYER'; - ScriptOpcode2[(ScriptOpcode2['HINT_STOP'] = 2033)] = 'HINT_STOP'; - ScriptOpcode2[(ScriptOpcode2['IF_CLOSE'] = 2034)] = 'IF_CLOSE'; - ScriptOpcode2[(ScriptOpcode2['IF_CLOSESTICKY'] = 2035)] = 'IF_CLOSESTICKY'; - ScriptOpcode2[(ScriptOpcode2['IF_MULTIZONE'] = 2036)] = 'IF_MULTIZONE'; - ScriptOpcode2[(ScriptOpcode2['IF_OPENCHAT'] = 2037)] = 'IF_OPENCHAT'; - ScriptOpcode2[(ScriptOpcode2['IF_OPENCHATSTICKY'] = 2038)] = 'IF_OPENCHATSTICKY'; - ScriptOpcode2[(ScriptOpcode2['IF_OPENMAINMODAL'] = 2039)] = 'IF_OPENMAINMODAL'; - ScriptOpcode2[(ScriptOpcode2['IF_OPENMAINMODALSIDEOVERLAY'] = 2040)] = 'IF_OPENMAINMODALSIDEOVERLAY'; - ScriptOpcode2[(ScriptOpcode2['IF_OPENSIDEOVERLAY'] = 2041)] = 'IF_OPENSIDEOVERLAY'; - ScriptOpcode2[(ScriptOpcode2['IF_SETANIM'] = 2042)] = 'IF_SETANIM'; - ScriptOpcode2[(ScriptOpcode2['IF_SETCOLOUR'] = 2043)] = 'IF_SETCOLOUR'; - ScriptOpcode2[(ScriptOpcode2['IF_SETHIDE'] = 2044)] = 'IF_SETHIDE'; - ScriptOpcode2[(ScriptOpcode2['IF_SETMODEL'] = 2045)] = 'IF_SETMODEL'; - ScriptOpcode2[(ScriptOpcode2['IF_SETRECOL'] = 2046)] = 'IF_SETRECOL'; - ScriptOpcode2[(ScriptOpcode2['IF_SETNPCHEAD'] = 2047)] = 'IF_SETNPCHEAD'; - ScriptOpcode2[(ScriptOpcode2['IF_SETOBJECT'] = 2048)] = 'IF_SETOBJECT'; - ScriptOpcode2[(ScriptOpcode2['IF_SETPLAYERHEAD'] = 2049)] = 'IF_SETPLAYERHEAD'; - ScriptOpcode2[(ScriptOpcode2['IF_SETPOSITION'] = 2050)] = 'IF_SETPOSITION'; - ScriptOpcode2[(ScriptOpcode2['IF_SETRESUMEBUTTONS'] = 2051)] = 'IF_SETRESUMEBUTTONS'; - ScriptOpcode2[(ScriptOpcode2['IF_SETTAB'] = 2052)] = 'IF_SETTAB'; - ScriptOpcode2[(ScriptOpcode2['IF_SETTABACTIVE'] = 2053)] = 'IF_SETTABACTIVE'; - ScriptOpcode2[(ScriptOpcode2['IF_SETTABFLASH'] = 2054)] = 'IF_SETTABFLASH'; - ScriptOpcode2[(ScriptOpcode2['IF_SETTEXT'] = 2055)] = 'IF_SETTEXT'; - ScriptOpcode2[(ScriptOpcode2['LAST_LOGIN_INFO'] = 2056)] = 'LAST_LOGIN_INFO'; - ScriptOpcode2[(ScriptOpcode2['LAST_COM'] = 2057)] = 'LAST_COM'; - ScriptOpcode2[(ScriptOpcode2['LAST_INT'] = 2058)] = 'LAST_INT'; - ScriptOpcode2[(ScriptOpcode2['LAST_ITEM'] = 2059)] = 'LAST_ITEM'; - ScriptOpcode2[(ScriptOpcode2['LAST_SLOT'] = 2060)] = 'LAST_SLOT'; - ScriptOpcode2[(ScriptOpcode2['LAST_TARGETSLOT'] = 2061)] = 'LAST_TARGETSLOT'; - ScriptOpcode2[(ScriptOpcode2['LAST_USEITEM'] = 2062)] = 'LAST_USEITEM'; - ScriptOpcode2[(ScriptOpcode2['LAST_USESLOT'] = 2063)] = 'LAST_USESLOT'; - ScriptOpcode2[(ScriptOpcode2['LONGQUEUE'] = 2064)] = 'LONGQUEUE'; - ScriptOpcode2[(ScriptOpcode2['MES'] = 2065)] = 'MES'; - ScriptOpcode2[(ScriptOpcode2['MIDI_JINGLE'] = 2066)] = 'MIDI_JINGLE'; - ScriptOpcode2[(ScriptOpcode2['MIDI_SONG'] = 2067)] = 'MIDI_SONG'; - ScriptOpcode2[(ScriptOpcode2['NAME'] = 2068)] = 'NAME'; - ScriptOpcode2[(ScriptOpcode2['P_APRANGE'] = 2069)] = 'P_APRANGE'; - ScriptOpcode2[(ScriptOpcode2['P_ARRIVEDELAY'] = 2070)] = 'P_ARRIVEDELAY'; - ScriptOpcode2[(ScriptOpcode2['P_COUNTDIALOG'] = 2071)] = 'P_COUNTDIALOG'; - ScriptOpcode2[(ScriptOpcode2['P_DELAY'] = 2072)] = 'P_DELAY'; - ScriptOpcode2[(ScriptOpcode2['P_EXACTMOVE'] = 2073)] = 'P_EXACTMOVE'; - ScriptOpcode2[(ScriptOpcode2['P_FINDUID'] = 2074)] = 'P_FINDUID'; - ScriptOpcode2[(ScriptOpcode2['P_LOCMERGE'] = 2075)] = 'P_LOCMERGE'; - ScriptOpcode2[(ScriptOpcode2['P_LOGOUT'] = 2076)] = 'P_LOGOUT'; - ScriptOpcode2[(ScriptOpcode2['P_OPHELD'] = 2077)] = 'P_OPHELD'; - ScriptOpcode2[(ScriptOpcode2['P_OPLOC'] = 2078)] = 'P_OPLOC'; - ScriptOpcode2[(ScriptOpcode2['P_OPNPC'] = 2079)] = 'P_OPNPC'; - ScriptOpcode2[(ScriptOpcode2['P_OPNPCT'] = 2080)] = 'P_OPNPCT'; - ScriptOpcode2[(ScriptOpcode2['P_OPOBJ'] = 2081)] = 'P_OPOBJ'; - ScriptOpcode2[(ScriptOpcode2['P_OPPLAYER'] = 2082)] = 'P_OPPLAYER'; - ScriptOpcode2[(ScriptOpcode2['P_OPPLAYERT'] = 2083)] = 'P_OPPLAYERT'; - ScriptOpcode2[(ScriptOpcode2['P_PAUSEBUTTON'] = 2084)] = 'P_PAUSEBUTTON'; - ScriptOpcode2[(ScriptOpcode2['P_STOPACTION'] = 2085)] = 'P_STOPACTION'; - ScriptOpcode2[(ScriptOpcode2['P_TELEJUMP'] = 2086)] = 'P_TELEJUMP'; - ScriptOpcode2[(ScriptOpcode2['P_TELEPORT'] = 2087)] = 'P_TELEPORT'; - ScriptOpcode2[(ScriptOpcode2['P_WALK'] = 2088)] = 'P_WALK'; - ScriptOpcode2[(ScriptOpcode2['PLAYER_FINDALLZONE'] = 2089)] = 'PLAYER_FINDALLZONE'; - ScriptOpcode2[(ScriptOpcode2['PLAYER_FINDNEXT'] = 2090)] = 'PLAYER_FINDNEXT'; - ScriptOpcode2[(ScriptOpcode2['QUEUE'] = 2091)] = 'QUEUE'; - ScriptOpcode2[(ScriptOpcode2['SAY'] = 2092)] = 'SAY'; - ScriptOpcode2[(ScriptOpcode2['WALKTRIGGER'] = 2093)] = 'WALKTRIGGER'; - ScriptOpcode2[(ScriptOpcode2['SETTIMER'] = 2094)] = 'SETTIMER'; - ScriptOpcode2[(ScriptOpcode2['SOFTTIMER'] = 2095)] = 'SOFTTIMER'; - ScriptOpcode2[(ScriptOpcode2['SOUND_SYNTH'] = 2096)] = 'SOUND_SYNTH'; - ScriptOpcode2[(ScriptOpcode2['SPOTANIM_PL'] = 2097)] = 'SPOTANIM_PL'; - ScriptOpcode2[(ScriptOpcode2['STAFFMODLEVEL'] = 2098)] = 'STAFFMODLEVEL'; - ScriptOpcode2[(ScriptOpcode2['STAT'] = 2099)] = 'STAT'; - ScriptOpcode2[(ScriptOpcode2['STAT_ADD'] = 2100)] = 'STAT_ADD'; - ScriptOpcode2[(ScriptOpcode2['STAT_BASE'] = 2101)] = 'STAT_BASE'; - ScriptOpcode2[(ScriptOpcode2['STAT_HEAL'] = 2102)] = 'STAT_HEAL'; - ScriptOpcode2[(ScriptOpcode2['STAT_SUB'] = 2103)] = 'STAT_SUB'; - ScriptOpcode2[(ScriptOpcode2['STRONGQUEUE'] = 2104)] = 'STRONGQUEUE'; - ScriptOpcode2[(ScriptOpcode2['UID'] = 2105)] = 'UID'; - ScriptOpcode2[(ScriptOpcode2['WEAKQUEUE'] = 2106)] = 'WEAKQUEUE'; - ScriptOpcode2[(ScriptOpcode2['IF_OPENMAINOVERLAY'] = 2107)] = 'IF_OPENMAINOVERLAY'; - ScriptOpcode2[(ScriptOpcode2['AFK_EVENT'] = 2108)] = 'AFK_EVENT'; - ScriptOpcode2[(ScriptOpcode2['LOWMEMORY'] = 2109)] = 'LOWMEMORY'; - ScriptOpcode2[(ScriptOpcode2['SETIDKIT'] = 2110)] = 'SETIDKIT'; - ScriptOpcode2[(ScriptOpcode2['P_CLEARPENDINGACTION'] = 2111)] = 'P_CLEARPENDINGACTION'; - ScriptOpcode2[(ScriptOpcode2['GETWALKTRIGGER'] = 2112)] = 'GETWALKTRIGGER'; - ScriptOpcode2[(ScriptOpcode2['BUSY2'] = 2113)] = 'BUSY2'; - ScriptOpcode2[(ScriptOpcode2['FINDHERO'] = 2114)] = 'FINDHERO'; - ScriptOpcode2[(ScriptOpcode2['BOTH_HEROPOINTS'] = 2115)] = 'BOTH_HEROPOINTS'; - ScriptOpcode2[(ScriptOpcode2['SETGENDER'] = 2116)] = 'SETGENDER'; - ScriptOpcode2[(ScriptOpcode2['SETSKINCOLOUR'] = 2117)] = 'SETSKINCOLOUR'; - ScriptOpcode2[(ScriptOpcode2['P_ANIMPROTECT'] = 2118)] = 'P_ANIMPROTECT'; - ScriptOpcode2[(ScriptOpcode2['NPC_ADD'] = 2500)] = 'NPC_ADD'; - ScriptOpcode2[(ScriptOpcode2['NPC_ANIM'] = 2501)] = 'NPC_ANIM'; - ScriptOpcode2[(ScriptOpcode2['NPC_BASESTAT'] = 2502)] = 'NPC_BASESTAT'; - ScriptOpcode2[(ScriptOpcode2['NPC_CATEGORY'] = 2503)] = 'NPC_CATEGORY'; - ScriptOpcode2[(ScriptOpcode2['NPC_CHANGETYPE'] = 2504)] = 'NPC_CHANGETYPE'; - ScriptOpcode2[(ScriptOpcode2['NPC_COORD'] = 2505)] = 'NPC_COORD'; - ScriptOpcode2[(ScriptOpcode2['NPC_DAMAGE'] = 2506)] = 'NPC_DAMAGE'; - ScriptOpcode2[(ScriptOpcode2['NPC_DEL'] = 2507)] = 'NPC_DEL'; - ScriptOpcode2[(ScriptOpcode2['NPC_DELAY'] = 2508)] = 'NPC_DELAY'; - ScriptOpcode2[(ScriptOpcode2['NPC_FACESQUARE'] = 2509)] = 'NPC_FACESQUARE'; - ScriptOpcode2[(ScriptOpcode2['NPC_FIND'] = 2510)] = 'NPC_FIND'; - ScriptOpcode2[(ScriptOpcode2['NPC_FINDALLANY'] = 2511)] = 'NPC_FINDALLANY'; - ScriptOpcode2[(ScriptOpcode2['NPC_FINDEXACT'] = 2512)] = 'NPC_FINDEXACT'; - ScriptOpcode2[(ScriptOpcode2['NPC_FINDHERO'] = 2513)] = 'NPC_FINDHERO'; - ScriptOpcode2[(ScriptOpcode2['NPC_FINDALLZONE'] = 2514)] = 'NPC_FINDALLZONE'; - ScriptOpcode2[(ScriptOpcode2['NPC_FINDNEXT'] = 2515)] = 'NPC_FINDNEXT'; - ScriptOpcode2[(ScriptOpcode2['NPC_FINDUID'] = 2516)] = 'NPC_FINDUID'; - ScriptOpcode2[(ScriptOpcode2['NPC_GETMODE'] = 2517)] = 'NPC_GETMODE'; - ScriptOpcode2[(ScriptOpcode2['NPC_HEROPOINTS'] = 2518)] = 'NPC_HEROPOINTS'; - ScriptOpcode2[(ScriptOpcode2['NPC_NAME'] = 2519)] = 'NPC_NAME'; - ScriptOpcode2[(ScriptOpcode2['NPC_PARAM'] = 2520)] = 'NPC_PARAM'; - ScriptOpcode2[(ScriptOpcode2['NPC_QUEUE'] = 2521)] = 'NPC_QUEUE'; - ScriptOpcode2[(ScriptOpcode2['NPC_RANGE'] = 2522)] = 'NPC_RANGE'; - ScriptOpcode2[(ScriptOpcode2['NPC_SAY'] = 2523)] = 'NPC_SAY'; - ScriptOpcode2[(ScriptOpcode2['NPC_HUNTALL'] = 2524)] = 'NPC_HUNTALL'; - ScriptOpcode2[(ScriptOpcode2['NPC_HUNTNEXT'] = 2525)] = 'NPC_HUNTNEXT'; - ScriptOpcode2[(ScriptOpcode2['NPC_SETHUNT'] = 2526)] = 'NPC_SETHUNT'; - ScriptOpcode2[(ScriptOpcode2['NPC_SETHUNTMODE'] = 2527)] = 'NPC_SETHUNTMODE'; - ScriptOpcode2[(ScriptOpcode2['NPC_SETMODE'] = 2528)] = 'NPC_SETMODE'; - ScriptOpcode2[(ScriptOpcode2['NPC_WALKTRIGGER'] = 2529)] = 'NPC_WALKTRIGGER'; - ScriptOpcode2[(ScriptOpcode2['NPC_SETTIMER'] = 2530)] = 'NPC_SETTIMER'; - ScriptOpcode2[(ScriptOpcode2['NPC_STAT'] = 2531)] = 'NPC_STAT'; - ScriptOpcode2[(ScriptOpcode2['NPC_STATADD'] = 2532)] = 'NPC_STATADD'; - ScriptOpcode2[(ScriptOpcode2['NPC_STATHEAL'] = 2533)] = 'NPC_STATHEAL'; - ScriptOpcode2[(ScriptOpcode2['NPC_STATSUB'] = 2534)] = 'NPC_STATSUB'; - ScriptOpcode2[(ScriptOpcode2['NPC_TELE'] = 2535)] = 'NPC_TELE'; - ScriptOpcode2[(ScriptOpcode2['NPC_TYPE'] = 2536)] = 'NPC_TYPE'; - ScriptOpcode2[(ScriptOpcode2['NPC_UID'] = 2537)] = 'NPC_UID'; - ScriptOpcode2[(ScriptOpcode2['SPOTANIM_NPC'] = 2538)] = 'SPOTANIM_NPC'; - ScriptOpcode2[(ScriptOpcode2['NPC_WALK'] = 2539)] = 'NPC_WALK'; - ScriptOpcode2[(ScriptOpcode2['NPC_ATTACKRANGE'] = 2540)] = 'NPC_ATTACKRANGE'; - ScriptOpcode2[(ScriptOpcode2['LOC_ADD'] = 3000)] = 'LOC_ADD'; - ScriptOpcode2[(ScriptOpcode2['LOC_ANGLE'] = 3001)] = 'LOC_ANGLE'; - ScriptOpcode2[(ScriptOpcode2['LOC_ANIM'] = 3002)] = 'LOC_ANIM'; - ScriptOpcode2[(ScriptOpcode2['LOC_CATEGORY'] = 3003)] = 'LOC_CATEGORY'; - ScriptOpcode2[(ScriptOpcode2['LOC_CHANGE'] = 3004)] = 'LOC_CHANGE'; - ScriptOpcode2[(ScriptOpcode2['LOC_COORD'] = 3005)] = 'LOC_COORD'; - ScriptOpcode2[(ScriptOpcode2['LOC_DEL'] = 3006)] = 'LOC_DEL'; - ScriptOpcode2[(ScriptOpcode2['LOC_FIND'] = 3007)] = 'LOC_FIND'; - ScriptOpcode2[(ScriptOpcode2['LOC_FINDALLZONE'] = 3008)] = 'LOC_FINDALLZONE'; - ScriptOpcode2[(ScriptOpcode2['LOC_FINDNEXT'] = 3009)] = 'LOC_FINDNEXT'; - ScriptOpcode2[(ScriptOpcode2['LOC_NAME'] = 3010)] = 'LOC_NAME'; - ScriptOpcode2[(ScriptOpcode2['LOC_PARAM'] = 3011)] = 'LOC_PARAM'; - ScriptOpcode2[(ScriptOpcode2['LOC_SHAPE'] = 3012)] = 'LOC_SHAPE'; - ScriptOpcode2[(ScriptOpcode2['LOC_TYPE'] = 3013)] = 'LOC_TYPE'; - ScriptOpcode2[(ScriptOpcode2['OBJ_ADD'] = 3500)] = 'OBJ_ADD'; - ScriptOpcode2[(ScriptOpcode2['OBJ_ADDALL'] = 3501)] = 'OBJ_ADDALL'; - ScriptOpcode2[(ScriptOpcode2['OBJ_COORD'] = 3502)] = 'OBJ_COORD'; - ScriptOpcode2[(ScriptOpcode2['OBJ_COUNT'] = 3503)] = 'OBJ_COUNT'; - ScriptOpcode2[(ScriptOpcode2['OBJ_DEL'] = 3504)] = 'OBJ_DEL'; - ScriptOpcode2[(ScriptOpcode2['OBJ_NAME'] = 3505)] = 'OBJ_NAME'; - ScriptOpcode2[(ScriptOpcode2['OBJ_PARAM'] = 3506)] = 'OBJ_PARAM'; - ScriptOpcode2[(ScriptOpcode2['OBJ_TAKEITEM'] = 3507)] = 'OBJ_TAKEITEM'; - ScriptOpcode2[(ScriptOpcode2['OBJ_TYPE'] = 3508)] = 'OBJ_TYPE'; - ScriptOpcode2[(ScriptOpcode2['NC_CATEGORY'] = 4000)] = 'NC_CATEGORY'; - ScriptOpcode2[(ScriptOpcode2['NC_DEBUGNAME'] = 4001)] = 'NC_DEBUGNAME'; - ScriptOpcode2[(ScriptOpcode2['NC_DESC'] = 4002)] = 'NC_DESC'; - ScriptOpcode2[(ScriptOpcode2['NC_NAME'] = 4003)] = 'NC_NAME'; - ScriptOpcode2[(ScriptOpcode2['NC_OP'] = 4004)] = 'NC_OP'; - ScriptOpcode2[(ScriptOpcode2['NC_PARAM'] = 4005)] = 'NC_PARAM'; - ScriptOpcode2[(ScriptOpcode2['LC_CATEGORY'] = 4100)] = 'LC_CATEGORY'; - ScriptOpcode2[(ScriptOpcode2['LC_DEBUGNAME'] = 4101)] = 'LC_DEBUGNAME'; - ScriptOpcode2[(ScriptOpcode2['LC_DESC'] = 4102)] = 'LC_DESC'; - ScriptOpcode2[(ScriptOpcode2['LC_NAME'] = 4103)] = 'LC_NAME'; - ScriptOpcode2[(ScriptOpcode2['LC_OP'] = 4104)] = 'LC_OP'; - ScriptOpcode2[(ScriptOpcode2['LC_PARAM'] = 4105)] = 'LC_PARAM'; - ScriptOpcode2[(ScriptOpcode2['LC_WIDTH'] = 4106)] = 'LC_WIDTH'; - ScriptOpcode2[(ScriptOpcode2['LC_LENGTH'] = 4107)] = 'LC_LENGTH'; - ScriptOpcode2[(ScriptOpcode2['OC_CATEGORY'] = 4200)] = 'OC_CATEGORY'; - ScriptOpcode2[(ScriptOpcode2['OC_CERT'] = 4201)] = 'OC_CERT'; - ScriptOpcode2[(ScriptOpcode2['OC_COST'] = 4202)] = 'OC_COST'; - ScriptOpcode2[(ScriptOpcode2['OC_DEBUGNAME'] = 4203)] = 'OC_DEBUGNAME'; - ScriptOpcode2[(ScriptOpcode2['OC_DESC'] = 4204)] = 'OC_DESC'; - ScriptOpcode2[(ScriptOpcode2['OC_IOP'] = 4205)] = 'OC_IOP'; - ScriptOpcode2[(ScriptOpcode2['OC_MEMBERS'] = 4206)] = 'OC_MEMBERS'; - ScriptOpcode2[(ScriptOpcode2['OC_NAME'] = 4207)] = 'OC_NAME'; - ScriptOpcode2[(ScriptOpcode2['OC_OP'] = 4208)] = 'OC_OP'; - ScriptOpcode2[(ScriptOpcode2['OC_PARAM'] = 4209)] = 'OC_PARAM'; - ScriptOpcode2[(ScriptOpcode2['OC_STACKABLE'] = 4210)] = 'OC_STACKABLE'; - ScriptOpcode2[(ScriptOpcode2['OC_TRADEABLE'] = 4211)] = 'OC_TRADEABLE'; - ScriptOpcode2[(ScriptOpcode2['OC_UNCERT'] = 4212)] = 'OC_UNCERT'; - ScriptOpcode2[(ScriptOpcode2['OC_WEARPOS2'] = 4213)] = 'OC_WEARPOS2'; - ScriptOpcode2[(ScriptOpcode2['OC_WEARPOS3'] = 4214)] = 'OC_WEARPOS3'; - ScriptOpcode2[(ScriptOpcode2['OC_WEARPOS'] = 4215)] = 'OC_WEARPOS'; - ScriptOpcode2[(ScriptOpcode2['OC_WEIGHT'] = 4216)] = 'OC_WEIGHT'; - ScriptOpcode2[(ScriptOpcode2['INV_ALLSTOCK'] = 4300)] = 'INV_ALLSTOCK'; - ScriptOpcode2[(ScriptOpcode2['INV_SIZE'] = 4301)] = 'INV_SIZE'; - ScriptOpcode2[(ScriptOpcode2['INV_STOCKBASE'] = 4302)] = 'INV_STOCKBASE'; - ScriptOpcode2[(ScriptOpcode2['INV_ADD'] = 4303)] = 'INV_ADD'; - ScriptOpcode2[(ScriptOpcode2['INV_CHANGESLOT'] = 4304)] = 'INV_CHANGESLOT'; - ScriptOpcode2[(ScriptOpcode2['INV_CLEAR'] = 4305)] = 'INV_CLEAR'; - ScriptOpcode2[(ScriptOpcode2['INV_DEL'] = 4306)] = 'INV_DEL'; - ScriptOpcode2[(ScriptOpcode2['INV_DELSLOT'] = 4307)] = 'INV_DELSLOT'; - ScriptOpcode2[(ScriptOpcode2['INV_DROPITEM'] = 4308)] = 'INV_DROPITEM'; - ScriptOpcode2[(ScriptOpcode2['INV_DROPSLOT'] = 4309)] = 'INV_DROPSLOT'; - ScriptOpcode2[(ScriptOpcode2['INV_FREESPACE'] = 4310)] = 'INV_FREESPACE'; - ScriptOpcode2[(ScriptOpcode2['INV_GETNUM'] = 4311)] = 'INV_GETNUM'; - ScriptOpcode2[(ScriptOpcode2['INV_GETOBJ'] = 4312)] = 'INV_GETOBJ'; - ScriptOpcode2[(ScriptOpcode2['INV_ITEMSPACE'] = 4313)] = 'INV_ITEMSPACE'; - ScriptOpcode2[(ScriptOpcode2['INV_ITEMSPACE2'] = 4314)] = 'INV_ITEMSPACE2'; - ScriptOpcode2[(ScriptOpcode2['INV_MOVEFROMSLOT'] = 4315)] = 'INV_MOVEFROMSLOT'; - ScriptOpcode2[(ScriptOpcode2['INV_MOVETOSLOT'] = 4316)] = 'INV_MOVETOSLOT'; - ScriptOpcode2[(ScriptOpcode2['BOTH_MOVEINV'] = 4317)] = 'BOTH_MOVEINV'; - ScriptOpcode2[(ScriptOpcode2['INV_MOVEITEM'] = 4318)] = 'INV_MOVEITEM'; - ScriptOpcode2[(ScriptOpcode2['INV_MOVEITEM_CERT'] = 4319)] = 'INV_MOVEITEM_CERT'; - ScriptOpcode2[(ScriptOpcode2['INV_MOVEITEM_UNCERT'] = 4320)] = 'INV_MOVEITEM_UNCERT'; - ScriptOpcode2[(ScriptOpcode2['INV_SETSLOT'] = 4321)] = 'INV_SETSLOT'; - ScriptOpcode2[(ScriptOpcode2['INV_TOTAL'] = 4322)] = 'INV_TOTAL'; - ScriptOpcode2[(ScriptOpcode2['INV_TOTALCAT'] = 4323)] = 'INV_TOTALCAT'; - ScriptOpcode2[(ScriptOpcode2['INV_TRANSMIT'] = 4324)] = 'INV_TRANSMIT'; - ScriptOpcode2[(ScriptOpcode2['INVOTHER_TRANSMIT'] = 4325)] = 'INVOTHER_TRANSMIT'; - ScriptOpcode2[(ScriptOpcode2['INV_STOPTRANSMIT'] = 4326)] = 'INV_STOPTRANSMIT'; - ScriptOpcode2[(ScriptOpcode2['BOTH_DROPSLOT'] = 4327)] = 'BOTH_DROPSLOT'; - ScriptOpcode2[(ScriptOpcode2['INV_DROPALL'] = 4328)] = 'INV_DROPALL'; - ScriptOpcode2[(ScriptOpcode2['INV_TOTALPARAM'] = 4329)] = 'INV_TOTALPARAM'; - ScriptOpcode2[(ScriptOpcode2['INV_TOTALPARAM_STACK'] = 4330)] = 'INV_TOTALPARAM_STACK'; - ScriptOpcode2[(ScriptOpcode2['ENUM'] = 4400)] = 'ENUM'; - ScriptOpcode2[(ScriptOpcode2['ENUM_GETOUTPUTCOUNT'] = 4401)] = 'ENUM_GETOUTPUTCOUNT'; - ScriptOpcode2[(ScriptOpcode2['APPEND_NUM'] = 4500)] = 'APPEND_NUM'; - ScriptOpcode2[(ScriptOpcode2['APPEND'] = 4501)] = 'APPEND'; - ScriptOpcode2[(ScriptOpcode2['APPEND_SIGNNUM'] = 4502)] = 'APPEND_SIGNNUM'; - ScriptOpcode2[(ScriptOpcode2['LOWERCASE'] = 4503)] = 'LOWERCASE'; - ScriptOpcode2[(ScriptOpcode2['TEXT_GENDER'] = 4504)] = 'TEXT_GENDER'; - ScriptOpcode2[(ScriptOpcode2['TOSTRING'] = 4505)] = 'TOSTRING'; - ScriptOpcode2[(ScriptOpcode2['COMPARE'] = 4506)] = 'COMPARE'; - ScriptOpcode2[(ScriptOpcode2['TEXT_SWITCH'] = 4507)] = 'TEXT_SWITCH'; - ScriptOpcode2[(ScriptOpcode2['APPEND_CHAR'] = 4508)] = 'APPEND_CHAR'; - ScriptOpcode2[(ScriptOpcode2['STRING_LENGTH'] = 4509)] = 'STRING_LENGTH'; - ScriptOpcode2[(ScriptOpcode2['SUBSTRING'] = 4510)] = 'SUBSTRING'; - ScriptOpcode2[(ScriptOpcode2['STRING_INDEXOF_CHAR'] = 4511)] = 'STRING_INDEXOF_CHAR'; - ScriptOpcode2[(ScriptOpcode2['STRING_INDEXOF_STRING'] = 4512)] = 'STRING_INDEXOF_STRING'; - ScriptOpcode2[(ScriptOpcode2['ADD'] = 4600)] = 'ADD'; - ScriptOpcode2[(ScriptOpcode2['SUB'] = 4601)] = 'SUB'; - ScriptOpcode2[(ScriptOpcode2['MULTIPLY'] = 4602)] = 'MULTIPLY'; - ScriptOpcode2[(ScriptOpcode2['DIVIDE'] = 4603)] = 'DIVIDE'; - ScriptOpcode2[(ScriptOpcode2['RANDOM'] = 4604)] = 'RANDOM'; - ScriptOpcode2[(ScriptOpcode2['RANDOMINC'] = 4605)] = 'RANDOMINC'; - ScriptOpcode2[(ScriptOpcode2['INTERPOLATE'] = 4606)] = 'INTERPOLATE'; - ScriptOpcode2[(ScriptOpcode2['ADDPERCENT'] = 4607)] = 'ADDPERCENT'; - ScriptOpcode2[(ScriptOpcode2['SETBIT'] = 4608)] = 'SETBIT'; - ScriptOpcode2[(ScriptOpcode2['CLEARBIT'] = 4609)] = 'CLEARBIT'; - ScriptOpcode2[(ScriptOpcode2['TESTBIT'] = 4610)] = 'TESTBIT'; - ScriptOpcode2[(ScriptOpcode2['MODULO'] = 4611)] = 'MODULO'; - ScriptOpcode2[(ScriptOpcode2['POW'] = 4612)] = 'POW'; - ScriptOpcode2[(ScriptOpcode2['INVPOW'] = 4613)] = 'INVPOW'; - ScriptOpcode2[(ScriptOpcode2['AND'] = 4614)] = 'AND'; - ScriptOpcode2[(ScriptOpcode2['OR'] = 4615)] = 'OR'; - ScriptOpcode2[(ScriptOpcode2['MIN'] = 4616)] = 'MIN'; - ScriptOpcode2[(ScriptOpcode2['MAX'] = 4617)] = 'MAX'; - ScriptOpcode2[(ScriptOpcode2['SCALE'] = 4618)] = 'SCALE'; - ScriptOpcode2[(ScriptOpcode2['BITCOUNT'] = 4619)] = 'BITCOUNT'; - ScriptOpcode2[(ScriptOpcode2['TOGGLEBIT'] = 4620)] = 'TOGGLEBIT'; - ScriptOpcode2[(ScriptOpcode2['SETBIT_RANGE'] = 4621)] = 'SETBIT_RANGE'; - ScriptOpcode2[(ScriptOpcode2['CLEARBIT_RANGE'] = 4622)] = 'CLEARBIT_RANGE'; - ScriptOpcode2[(ScriptOpcode2['GETBIT_RANGE'] = 4623)] = 'GETBIT_RANGE'; - ScriptOpcode2[(ScriptOpcode2['SETBIT_RANGE_TOINT'] = 4624)] = 'SETBIT_RANGE_TOINT'; - ScriptOpcode2[(ScriptOpcode2['SIN_DEG'] = 4625)] = 'SIN_DEG'; - ScriptOpcode2[(ScriptOpcode2['COS_DEG'] = 4626)] = 'COS_DEG'; - ScriptOpcode2[(ScriptOpcode2['ATAN2_DEG'] = 4627)] = 'ATAN2_DEG'; - ScriptOpcode2[(ScriptOpcode2['ABS'] = 4628)] = 'ABS'; - ScriptOpcode2[(ScriptOpcode2['DB_FIND_WITH_COUNT'] = 7500)] = 'DB_FIND_WITH_COUNT'; - ScriptOpcode2[(ScriptOpcode2['DB_FINDNEXT'] = 7501)] = 'DB_FINDNEXT'; - ScriptOpcode2[(ScriptOpcode2['DB_GETFIELD'] = 7502)] = 'DB_GETFIELD'; - ScriptOpcode2[(ScriptOpcode2['DB_GETFIELDCOUNT'] = 7503)] = 'DB_GETFIELDCOUNT'; - ScriptOpcode2[(ScriptOpcode2['DB_LISTALL_WITH_COUNT'] = 7504)] = 'DB_LISTALL_WITH_COUNT'; - ScriptOpcode2[(ScriptOpcode2['DB_GETROWTABLE'] = 7505)] = 'DB_GETROWTABLE'; - ScriptOpcode2[(ScriptOpcode2['DB_FINDBYINDEX'] = 7506)] = 'DB_FINDBYINDEX'; - ScriptOpcode2[(ScriptOpcode2['DB_FIND_REFINE_WITH_COUNT'] = 7507)] = 'DB_FIND_REFINE_WITH_COUNT'; - ScriptOpcode2[(ScriptOpcode2['DB_FIND'] = 7508)] = 'DB_FIND'; - ScriptOpcode2[(ScriptOpcode2['DB_FIND_REFINE'] = 7509)] = 'DB_FIND_REFINE'; - ScriptOpcode2[(ScriptOpcode2['DB_LISTALL'] = 7510)] = 'DB_LISTALL'; - ScriptOpcode2[(ScriptOpcode2['ERROR'] = 1e4)] = 'ERROR'; - ScriptOpcode2[(ScriptOpcode2['MAP_LOCALDEV'] = 10001)] = 'MAP_LOCALDEV'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTCLOCK'] = 10002)] = 'MAP_LASTCLOCK'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTWORLD'] = 10003)] = 'MAP_LASTWORLD'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTCLIENTIN'] = 10004)] = 'MAP_LASTCLIENTIN'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTNPC'] = 10005)] = 'MAP_LASTNPC'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTPLAYER'] = 10006)] = 'MAP_LASTPLAYER'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTLOGOUT'] = 10007)] = 'MAP_LASTLOGOUT'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTLOGIN'] = 10008)] = 'MAP_LASTLOGIN'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTZONE'] = 10009)] = 'MAP_LASTZONE'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTCLIENTOUT'] = 10010)] = 'MAP_LASTCLIENTOUT'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTCLEANUP'] = 10011)] = 'MAP_LASTCLEANUP'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTBANDWIDTHIN'] = 10012)] = 'MAP_LASTBANDWIDTHIN'; - ScriptOpcode2[(ScriptOpcode2['MAP_LASTBANDWIDTHOUT'] = 10013)] = 'MAP_LASTBANDWIDTHOUT'; -})((ScriptOpcode ||= {})); -var ScriptOpcode_default = ScriptOpcode; - -// src/lostcity/engine/script/Script.ts -class Script { - info = { - scriptName: '', - sourceFilePath: '', - lookupKey: -1, - parameterTypes: [], - pcs: [], - lines: [] - }; - id; - intLocalCount = 0; - stringLocalCount = 0; - intArgCount = 0; - stringArgCount = 0; - switchTables = []; - opcodes = []; - intOperands = []; - stringOperands = []; - static isLargeOperand(opcode) { - if (opcode > 100) { - return false; - } - switch (opcode) { - case ScriptOpcode_default.RETURN: - case ScriptOpcode_default.POP_INT_DISCARD: - case ScriptOpcode_default.POP_STRING_DISCARD: - case ScriptOpcode_default.GOSUB: - case ScriptOpcode_default.JUMP: - return false; - } - return true; - } - static decode(id, stream) { - const length = stream.data.length; - if (length < 16) { - throw new Error('Invalid script file (minimum length)'); - } - stream.pos = length - 2; - const trailerLen = stream.g2(); - const trailerPos = length - trailerLen - 12 - 2; - if (trailerPos < 0 || trailerPos >= length) { - throw new Error('Invalid script file (bad trailer pos)'); - } - stream.pos = trailerPos; - const script = new Script(id); - const _instructions = stream.g4(); - script.intLocalCount = stream.g2(); - script.stringLocalCount = stream.g2(); - script.intArgCount = stream.g2(); - script.stringArgCount = stream.g2(); - const switches = stream.g1(); - for (let i = 0; i < switches; i++) { - const count = stream.g2(); - const table = []; - for (let j = 0; j < count; j++) { - const key = stream.g4(); - const offset = stream.g4(); - table[key] = offset; - } - script.switchTables[i] = table; - } - stream.pos = 0; - script.info.scriptName = stream.gjstr(0); - script.info.sourceFilePath = stream.gjstr(0); - script.info.lookupKey = stream.g4(); - const parameterTypeCount = stream.g1(); - for (let i = 0; i < parameterTypeCount; i++) { - script.info.parameterTypes.push(stream.g1()); - } - const lineNumberTableLength = stream.g2(); - for (let i = 0; i < lineNumberTableLength; i++) { - script.info.pcs.push(stream.g4()); - script.info.lines.push(stream.g4()); - } - let instr = 0; - while (trailerPos > stream.pos) { - const opcode = stream.g2(); - if (opcode === ScriptOpcode_default.PUSH_CONSTANT_STRING) { - script.stringOperands[instr] = stream.gjstr(0); - } else if (Script.isLargeOperand(opcode)) { - script.intOperands[instr] = stream.g4(); - } else { - script.intOperands[instr] = stream.g1(); - } - script.opcodes[instr++] = opcode; - } - return script; - } - constructor(id) { - this.id = id; - } - get name() { - return this.info.scriptName; - } - get fileName() { - return q.basename(this.info.sourceFilePath); - } - lineNumber(pc) { - for (let i = 0; i < this.info.pcs.length; i++) { - if (this.info.pcs[i] > pc) { - return this.info.lines[i - 1]; - } - } - return this.info.lines[this.info.lines.length - 1]; - } -} - -// src/lostcity/engine/script/ScriptProvider.ts -class ScriptProvider { - static COMPILER_VERSION = 18; - static scripts = []; - static scriptLookup = new Map(); - static scriptNames = new Map(); - static async load(dir) { - const dat = await Packet.load(`${dir}/server/script.dat`); - const idx = await Packet.load(`${dir}/server/script.idx`); - if (!dat.data.length || !idx.data.length) { - console.log('\nFatal: No script.dat or script.idx found. Please run the server:build script.'); - process.exit(1); - } - const entries = dat.g2(); - idx.pos += 2; - const version = dat.g4(); - if (version !== ScriptProvider.COMPILER_VERSION) { - console.error('\nFatal: Scripts were compiled with an older RuneScript compiler. Please update it, try `npm run build` and then restart the server.'); - process.exit(1); - } - const scripts = new Array(entries); - const scriptNames = new Map(); - const scriptLookup = new Map(); - let loaded = 0; - for (let id = 0; id < entries; id++) { - const size = idx.g2(); - if (size === 0) { - continue; - } - try { - const data = new Uint8Array(size); - dat.gdata(data, 0, data.length); - const script = Script.decode(id, new Packet(data)); - scripts[id] = script; - scriptNames.set(script.name, id); - if (script.info.lookupKey !== 4294967295) { - scriptLookup.set(script.info.lookupKey, script); - } - loaded++; - } catch (err) { - console.error(err); - console.error(`Warning: Failed to load script ${id}, something may have been partially written`); - return -1; - } - } - ScriptProvider.scripts = scripts; - ScriptProvider.scriptNames = scriptNames; - ScriptProvider.scriptLookup = scriptLookup; - return loaded; - } - static get(id) { - return this.scripts[id]; - } - static getByName(name) { - const id = ScriptProvider.scriptNames.get(name); - if (id === undefined) { - return; - } - return ScriptProvider.scripts[id]; - } - static getByTrigger(trigger, type = -1, category = -1) { - let script = ScriptProvider.scriptLookup.get(trigger | (2 << 8) | (type << 10)); - if (script) { - return script; - } - script = ScriptProvider.scriptLookup.get(trigger | (1 << 8) | (category << 10)); - if (script) { - return script; - } - return ScriptProvider.scriptLookup.get(trigger); - } - static getByTriggerSpecific(trigger, type = -1, category = -1) { - if (type !== -1) { - return ScriptProvider.scriptLookup.get(trigger | (2 << 8) | (type << 10)); - } else if (category !== -1) { - return ScriptProvider.scriptLookup.get(trigger | (1 << 8) | (category << 10)); - } - return ScriptProvider.scriptLookup.get(trigger); - } -} - -// src/lostcity/util/Numbers.ts -function toInt32(num) { - return num | 0; -} -function bitcount(num) { - num = num - ((num >> 1) & 1431655765); - num = (num & 858993459) + ((num >> 2) & 858993459); - return (((num + (num >> 4)) & 252645135) * 16843009) >> 24; -} -function setBitRange(num, startBit, endBit) { - const mask = MASK[endBit - startBit + 1]; - return num | (mask << startBit); -} -function clearBitRange(num, startBit, endBit) { - const mask = MASK[endBit - startBit + 1]; - return num & ~(mask << startBit); -} -var initMaskArray = function () { - const data = [0]; - let incrementor = 2; - for (let i = 1; i < 33; ++i) { - data[i] = toInt32(incrementor - 1); - incrementor += incrementor; - } - return data; -}; -var MASK = initMaskArray(); - -// src/lostcity/engine/script/ScriptState.ts -class ScriptState { - static ABORTED = -1; - static RUNNING = 0; - static FINISHED = 1; - static SUSPENDED = 2; - static PAUSEBUTTON = 3; - static COUNTDIALOG = 4; - static NPC_SUSPENDED = 5; - static WORLD_SUSPENDED = 6; - script; - trigger; - execution = ScriptState.RUNNING; - executionHistory = []; - pc = -1; - opcount = 0; - frames = []; - fp = 0; - debugFrames = []; - debugFp = 0; - intStack = []; - isp = 0; - stringStack = []; - ssp = 0; - intLocals = []; - stringLocals = []; - pointers = 0; - self = null; - _activePlayer = null; - _activePlayer2 = null; - _activeNpc = null; - _activeNpc2 = null; - _activeLoc = null; - _activeLoc2 = null; - _activeObj = null; - _activeObj2 = null; - splitPages = []; - splitMesanim = -1; - dbTable = null; - dbColumn = -1; - dbRow = -1; - dbRowQuery = []; - huntIterator = null; - npcIterator = null; - locIterator = null; - lastInt = 0; - constructor(script, args = []) { - this.script = script; - this.trigger = script.info.lookupKey & 255; - if (args) { - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - if (typeof arg === 'number') { - this.intLocals.push(arg); - } else { - this.stringLocals.push(arg); - } - } - } - } - pointerSet(...pointers) { - this.pointers = 0; - for (let i = 0; i < pointers.length; i++) { - this.pointers |= 1 << pointers[i]; - } - } - pointerAdd(pointer) { - this.pointers |= 1 << pointer; - } - pointerRemove(pointer) { - this.pointers &= ~(1 << pointer); - } - pointerGet(pointer) { - return (this.pointers & (1 << pointer)) != 0; - } - pointerCheck(...pointers) { - for (let i = 0; i < pointers.length; i++) { - const flag = 1 << pointers[i]; - if ((this.pointers & flag) != flag) { - throw new Error(`Required pointer: ${ScriptState.pointerPrint(flag)}, current: ${ScriptState.pointerPrint(this.pointers)}`); - } - } - } - static pointerPrint(flags) { - let text = ''; - for (let i = 0; i < ScriptPointer_default._LAST; i++) { - if ((flags & (1 << i)) != 0) { - text += `${ScriptPointer_default[i]}, `; - } - } - return text.substring(0, text.lastIndexOf(',')); - } - get activePlayer() { - const player = this.intOperand === 0 ? this._activePlayer : this._activePlayer2; - if (player === null) { - throw new Error('Attempt to access null active_player'); - } - return player; - } - set activePlayer(player) { - if (this.intOperand === 0) { - this._activePlayer = player; - } else { - this._activePlayer2 = player; - } - } - get activeNpc() { - const npc = this.intOperand === 0 ? this._activeNpc : this._activeNpc2; - if (npc === null) { - throw new Error('Attempt to access null active_npc'); - } - return npc; - } - set activeNpc(npc) { - if (this.intOperand === 0) { - this._activeNpc = npc; - } else { - this._activeNpc2 = npc; - } - } - get activeLoc() { - const loc = this.intOperand === 0 ? this._activeLoc : this._activeLoc2; - if (loc === null) { - throw new Error('Attempt to access null active_loc'); - } - return loc; - } - set activeLoc(loc) { - if (this.intOperand === 0) { - this._activeLoc = loc; - } else { - this._activeLoc2 = loc; - } - } - get activeObj() { - const obj = this.intOperand === 0 ? this._activeObj : this._activeObj2; - if (obj === null) { - throw new Error('Attempt to access null active_obj'); - } - return obj; - } - set activeObj(obj) { - if (this.intOperand === 0) { - this._activeObj = obj; - } else { - this._activeObj2 = obj; - } - } - get intOperand() { - return this.script.intOperands[this.pc]; - } - get stringOperand() { - return this.script.stringOperands[this.pc]; - } - popInt() { - const value = this.intStack[--this.isp]; - if (!value) { - return 0; - } - return toInt32(value); - } - popInts(amount) { - const ints = Array(amount); - for (let i = amount - 1; i >= 0; i--) { - ints[i] = this.popInt(); - } - return ints; - } - pushInt(value) { - this.intStack[this.isp++] = toInt32(value); - } - popString() { - return this.stringStack[--this.ssp] ?? ''; - } - popStrings(amount) { - const strings = Array(amount); - for (let i = amount - 1; i >= 0; i--) { - strings[i] = this.popString(); - } - return strings; - } - pushString(value) { - this.stringStack[this.ssp++] = value; - } - reset() { - this.pc = -1; - this.frames = []; - this.fp = 0; - this.intStack = []; - this.isp = 0; - this.stringStack = []; - this.ssp = 0; - this.intLocals = []; - this.stringLocals = []; - this.pointers = 0; - } -} - -// src/lostcity/engine/Inventory.ts -class InventoryTransaction { - requested = 0; - completed = 0; - items = []; - constructor(requested, completed = 0, items = []) { - this.requested = requested; - this.completed = completed; - this.items = items; - } - getLeftOver() { - return this.requested - this.completed; - } - hasSucceeded() { - return this.completed == this.requested; - } - hasFailed() { - return !this.hasSucceeded(); - } - revert(from) { - for (let i = 0; i < this.items.length; i++) { - const item = this.items[i].item; - from.remove(item.id, item.count, this.items[i].slot); - } - } -} - -class Inventory { - static STACK_LIMIT = 2147483647; - static NORMAL_STACK = 0; - static ALWAYS_STACK = 1; - static NEVER_STACK = 2; - static fromType(inv) { - if (inv === -1) { - throw new Error('Invalid inventory type'); - } - const type = InvType.get(inv); - let stackType = Inventory.NORMAL_STACK; - if (type.stackall) { - stackType = Inventory.ALWAYS_STACK; - } - const container = new Inventory(type.size, stackType); - container.type = inv; - if (type.stockobj && type.stockcount && type.stockobj.length) { - for (let i = 0; i < type.stockobj.length; i++) { - container.set(i, { - id: type.stockobj[i], - count: type.stockcount[i] - }); - } - } - return container; - } - stackType = Inventory.NORMAL_STACK; - capacity = 0; - items = []; - update = false; - type = -1; - constructor(capacity, stackType = Inventory.NORMAL_STACK) { - this.capacity = capacity; - this.stackType = stackType; - for (let i = 0; i < capacity; i++) { - this.items.push(null); - } - } - contains(id) { - return this.items.some(item => item && item.id == id); - } - hasAt(slot, id) { - const item = this.items[slot]; - return item && item.id == id; - } - get nextFreeSlot() { - return this.items.indexOf(null, 0); - } - get freeSlotCount() { - return this.items.filter(item => item == null).length; - } - get occupiedSlotCount() { - return this.items.filter(item => item != null).length; - } - get isFull() { - return this.occupiedSlotCount == this.capacity; - } - get isEmpty() { - return this.occupiedSlotCount == 0; - } - get hasAny() { - return this.items.some(item => item != null); - } - get hasSpace() { - return this.nextFreeSlot != -1; - } - get itemsFiltered() { - return this.items.filter(item => item != null); - } - getItemCount(id) { - let count = 0; - for (let i = 0; i < this.capacity; i++) { - const item = this.items[i]; - if (item && item.id == id) { - count += item.count; - } - } - return Math.min(Inventory.STACK_LIMIT, count); - } - getItemIndex(id) { - return this.items.findIndex(item => item && item.id == id); - } - removeAll() { - this.items.fill(null, 0, this.capacity); - this.update = true; - } - add(id, count = 1, beginSlot = -1, assureFullInsertion = true, forceNoStack = false, dryRun = false) { - const type = ObjType.get(id); - const stockObj = InvType.get(this.type).stockobj?.includes(id) === true; - const stack = !forceNoStack && this.stackType != Inventory.NEVER_STACK && (type.stackable || this.stackType == Inventory.ALWAYS_STACK); - let previousCount = 0; - if (stack) { - previousCount = this.getItemCount(id); - } - if (previousCount == Inventory.STACK_LIMIT) { - return new InventoryTransaction(count, 0, []); - } - const freeSlotCount = this.freeSlotCount; - if (freeSlotCount == 0 && (!stack || (stack && previousCount == 0 && !stockObj))) { - return new InventoryTransaction(count, 0, []); - } - if (assureFullInsertion) { - if (stack && previousCount > Inventory.STACK_LIMIT - count) { - return new InventoryTransaction(count, 0, []); - } - if (!stack && count > freeSlotCount) { - return new InventoryTransaction(count, 0, []); - } - } else { - if (stack && previousCount == Inventory.STACK_LIMIT) { - return new InventoryTransaction(count, 0, []); - } else if (!stack && freeSlotCount == 0) { - return new InventoryTransaction(count, 0, []); - } - } - let completed = 0; - const added = []; - if (!stack) { - const startSlot = Math.max(0, beginSlot); - for (let i = startSlot; i < this.capacity; i++) { - if (this.items[i] != null) { - continue; - } - const add = {id, count: 1}; - if (!dryRun) { - this.set(i, add); - } - added.push({slot: i, item: add}); - if (++completed >= count) { - break; - } - } - } else { - let stackIndex = this.getItemIndex(id); - if (stackIndex == -1) { - if (beginSlot == -1) { - stackIndex = this.nextFreeSlot; - } else { - stackIndex = this.items.indexOf(null, beginSlot); - } - if (stackIndex == -1) { - return new InventoryTransaction(count, completed, []); - } - } - const stackCount = this.get(stackIndex)?.count ?? 0; - const total = Math.min(Inventory.STACK_LIMIT, stackCount + count); - const add = {id, count: total}; - if (!dryRun) { - this.set(stackIndex, add); - } - added.push({slot: stackIndex, item: add}); - completed = total - stackCount; - } - return new InventoryTransaction(count, completed, added); - } - remove(id, count = 1, beginSlot = -1, assureFullRemoval = false) { - const hasCount = this.getItemCount(id); - const stockObj = InvType.get(this.type).stockobj?.includes(id) === true; - if (assureFullRemoval && hasCount < count) { - return new InventoryTransaction(count, 0, []); - } else if (!assureFullRemoval && hasCount < 1) { - return new InventoryTransaction(count, 0, []); - } - let totalRemoved = 0; - const removed = []; - let skippedIndices = null; - if (beginSlot != -1) { - skippedIndices = []; - for (let i = 0; i < beginSlot; i++) { - skippedIndices.push(i); - } - } - let index = 0; - if (beginSlot != -1) { - index = beginSlot; - } - for (let i = index; i < this.capacity; i++) { - const curItem = this.items[i]; - if (!curItem || curItem.id != id) { - continue; - } - const removeCount = Math.min(curItem.count, count - totalRemoved); - totalRemoved += removeCount; - curItem.count -= removeCount; - if (curItem.count == 0 && !stockObj) { - const removedItem = this.items[i]; - this.items[i] = null; - if (removedItem) { - removed.push({slot: i, item: removedItem}); - } - } - if (totalRemoved >= count) { - break; - } - } - if (skippedIndices != null && totalRemoved < count) { - for (let i = 0; i < skippedIndices.length; i++) { - const curItem = this.items[i]; - if (!curItem || curItem.id != id) { - continue; - } - const removeCount = Math.min(curItem.count, count - totalRemoved); - totalRemoved += removeCount; - curItem.count -= removeCount; - if (curItem.count == 0 && !stockObj) { - const removedItem = this.items[i]; - this.items[i] = null; - if (removedItem) { - removed.push({slot: i, item: removedItem}); - } - } - if (totalRemoved >= count) { - break; - } - } - } - if (totalRemoved > 0) { - this.update = true; - } - return new InventoryTransaction(count, totalRemoved, removed); - } - delete(slot) { - this.items[slot] = null; - this.update = true; - } - swap(from, to) { - const temp = this.items[from]; - this.set(from, this.items[to]); - this.set(to, temp); - } - shift() { - this.items = this.items.sort((a, b2) => { - if (a === null || b2 === null) { - return +(a === null) - +(b2 === null); - } else { - return +(a > b2) || -(a < b2); - } - }); - this.update = true; - } - get(slot) { - return this.items[slot]; - } - set(slot, item) { - this.items[slot] = item; - this.update = true; - } - validSlot(slot) { - return slot >= 0 && slot < this.capacity; - } - transfer(to, item, fromSlot = -1, toSlot = -1, note = false, unnote = false) { - if (item.count <= 0) { - return null; - } - const count = Math.min(item.count, this.getItemCount(item.id)); - const objType = ObjType.get(item.id); - let finalItem = {id: item.id, count}; - if (note && objType.certlink !== -1 && objType.certtemplate === -1) { - finalItem = {id: objType.certlink, count}; - } else if (unnote && objType.certlink !== -1 && objType.certtemplate >= 0) { - finalItem = {id: objType.certlink, count}; - } - const add = to.add(finalItem.id, finalItem.count, toSlot, false); - if (add.completed == 0) { - return null; - } - const remove = this.remove(item.id, add.completed, fromSlot, false); - if (remove.completed == 0) { - return null; - } - return remove; - } -} - -// node_modules/@2004scape/rsmod-pathfinder/dist/rsmod-pathfinder.js -async function instantiate2(module, imports = {}) { - const adaptedImports = { - env: Object.assign(Object.create(globalThis), imports.env || {}, { - abort(message, fileName, lineNumber, columnNumber) { - message = __liftString(message >>> 0); - fileName = __liftString(fileName >>> 0); - lineNumber = lineNumber >>> 0; - columnNumber = columnNumber >>> 0; - (() => { - throw Error(`${message} in ${fileName}:${lineNumber}:${columnNumber}`); - })(); - }, - seed() { - return (() => { - return Date.now() * Math.random(); - })(); - } - }) - }; - const {exports} = await WebAssembly.instantiate(module, adaptedImports); - const memory = exports.memory || imports.env.memory; - const adaptedExports = Object.setPrototypeOf( - { - findPath(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, shape, moveNear, blockAccessFlags, maxWaypoints, collision) { - moveNear = moveNear ? 1 : 0; - exports.__setArgumentsLength(arguments.length); - return __liftStaticArray(__getI32, 2, exports.findPath(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, shape, moveNear, blockAccessFlags, maxWaypoints, collision) >>> 0); - }, - findNaivePath(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags, collision) { - exports.__setArgumentsLength(arguments.length); - return __liftStaticArray(__getI32, 2, exports.findNaivePath(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags, collision) >>> 0); - }, - changeFloor(x, z2, level, add) { - add = add ? 1 : 0; - exports.changeFloor(x, z2, level, add); - }, - changeLoc(x, z2, level, width, length, blockrange, breakroutefinding, add) { - blockrange = blockrange ? 1 : 0; - breakroutefinding = breakroutefinding ? 1 : 0; - add = add ? 1 : 0; - exports.changeLoc(x, z2, level, width, length, blockrange, breakroutefinding, add); - }, - changeNpc(x, z2, level, size, add) { - add = add ? 1 : 0; - exports.changeNpc(x, z2, level, size, add); - }, - changePlayer(x, z2, level, size, add) { - add = add ? 1 : 0; - exports.changePlayer(x, z2, level, size, add); - }, - changeRoof(x, z2, level, add) { - add = add ? 1 : 0; - exports.changeRoof(x, z2, level, add); - }, - changeWall(x, z2, level, angle, shape, blockrange, breakroutefinding, add) { - blockrange = blockrange ? 1 : 0; - breakroutefinding = breakroutefinding ? 1 : 0; - add = add ? 1 : 0; - exports.changeWall(x, z2, level, angle, shape, blockrange, breakroutefinding, add); - }, - allocateIfAbsent(absoluteX, absoluteZ, level) { - return __liftStaticArray(__getI32, 2, exports.allocateIfAbsent(absoluteX, absoluteZ, level) >>> 0); - }, - isZoneAllocated(absoluteX, absoluteZ, level) { - return exports.isZoneAllocated(absoluteX, absoluteZ, level) != 0; - }, - isFlagged(x, z2, level, masks) { - return exports.isFlagged(x, z2, level, masks) != 0; - }, - canTravel(level, x, z2, offsetX, offsetZ, size, extraFlag, collision) { - exports.__setArgumentsLength(arguments.length); - return exports.canTravel(level, x, z2, offsetX, offsetZ, size, extraFlag, collision) != 0; - }, - hasLineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { - exports.__setArgumentsLength(arguments.length); - return exports.hasLineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) != 0; - }, - hasLineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { - exports.__setArgumentsLength(arguments.length); - return exports.hasLineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) != 0; - }, - lineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { - exports.__setArgumentsLength(arguments.length); - return __liftStaticArray(__getI32, 2, exports.lineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) >>> 0); - }, - lineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { - exports.__setArgumentsLength(arguments.length); - return __liftStaticArray(__getI32, 2, exports.lineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) >>> 0); - }, - reached(level, srcX, srcZ, destX, destZ, destWidth, destHeight, srcSize, angle, shape, blockAccessFlags) { - exports.__setArgumentsLength(arguments.length); - return exports.reached(level, srcX, srcZ, destX, destZ, destWidth, destHeight, srcSize, angle, shape, blockAccessFlags) != 0; - }, - __collides(srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight) { - return exports.__collides(srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight) != 0; - }, - __reachRectangle1(level, srcX, srcZ, destX, destZ, destWidth, destHeight, blockAccessFlags) { - return exports.__reachRectangle1(level, srcX, srcZ, destX, destZ, destWidth, destHeight, blockAccessFlags) != 0; - }, - __reachRectangleN(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags) { - return exports.__reachRectangleN(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags) != 0; - }, - __reachRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) { - return exports.__reachRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) != 0; - }, - __reachExclusiveRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) { - return exports.__reachExclusiveRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) != 0; - }, - CollisionFlag: (values => ( - (values[(values.NULL = exports['CollisionFlag.NULL'].valueOf())] = 'NULL'), - (values[(values.OPEN = exports['CollisionFlag.OPEN'].valueOf())] = 'OPEN'), - (values[(values.WALL_NORTH_WEST = exports['CollisionFlag.WALL_NORTH_WEST'].valueOf())] = 'WALL_NORTH_WEST'), - (values[(values.WALL_NORTH = exports['CollisionFlag.WALL_NORTH'].valueOf())] = 'WALL_NORTH'), - (values[(values.WALL_NORTH_EAST = exports['CollisionFlag.WALL_NORTH_EAST'].valueOf())] = 'WALL_NORTH_EAST'), - (values[(values.WALL_EAST = exports['CollisionFlag.WALL_EAST'].valueOf())] = 'WALL_EAST'), - (values[(values.WALL_SOUTH_EAST = exports['CollisionFlag.WALL_SOUTH_EAST'].valueOf())] = 'WALL_SOUTH_EAST'), - (values[(values.WALL_SOUTH = exports['CollisionFlag.WALL_SOUTH'].valueOf())] = 'WALL_SOUTH'), - (values[(values.WALL_SOUTH_WEST = exports['CollisionFlag.WALL_SOUTH_WEST'].valueOf())] = 'WALL_SOUTH_WEST'), - (values[(values.WALL_WEST = exports['CollisionFlag.WALL_WEST'].valueOf())] = 'WALL_WEST'), - (values[(values.LOC = exports['CollisionFlag.LOC'].valueOf())] = 'LOC'), - (values[(values.WALL_NORTH_WEST_PROJ_BLOCKER = exports['CollisionFlag.WALL_NORTH_WEST_PROJ_BLOCKER'].valueOf())] = 'WALL_NORTH_WEST_PROJ_BLOCKER'), - (values[(values.WALL_NORTH_PROJ_BLOCKER = exports['CollisionFlag.WALL_NORTH_PROJ_BLOCKER'].valueOf())] = 'WALL_NORTH_PROJ_BLOCKER'), - (values[(values.WALL_NORTH_EAST_PROJ_BLOCKER = exports['CollisionFlag.WALL_NORTH_EAST_PROJ_BLOCKER'].valueOf())] = 'WALL_NORTH_EAST_PROJ_BLOCKER'), - (values[(values.WALL_EAST_PROJ_BLOCKER = exports['CollisionFlag.WALL_EAST_PROJ_BLOCKER'].valueOf())] = 'WALL_EAST_PROJ_BLOCKER'), - (values[(values.WALL_SOUTH_EAST_PROJ_BLOCKER = exports['CollisionFlag.WALL_SOUTH_EAST_PROJ_BLOCKER'].valueOf())] = 'WALL_SOUTH_EAST_PROJ_BLOCKER'), - (values[(values.WALL_SOUTH_PROJ_BLOCKER = exports['CollisionFlag.WALL_SOUTH_PROJ_BLOCKER'].valueOf())] = 'WALL_SOUTH_PROJ_BLOCKER'), - (values[(values.WALL_SOUTH_WEST_PROJ_BLOCKER = exports['CollisionFlag.WALL_SOUTH_WEST_PROJ_BLOCKER'].valueOf())] = 'WALL_SOUTH_WEST_PROJ_BLOCKER'), - (values[(values.WALL_WEST_PROJ_BLOCKER = exports['CollisionFlag.WALL_WEST_PROJ_BLOCKER'].valueOf())] = 'WALL_WEST_PROJ_BLOCKER'), - (values[(values.LOC_PROJ_BLOCKER = exports['CollisionFlag.LOC_PROJ_BLOCKER'].valueOf())] = 'LOC_PROJ_BLOCKER'), - (values[(values.FLOOR_DECORATION = exports['CollisionFlag.FLOOR_DECORATION'].valueOf())] = 'FLOOR_DECORATION'), - (values[(values.NPC = exports['CollisionFlag.NPC'].valueOf())] = 'NPC'), - (values[(values.PLAYER = exports['CollisionFlag.PLAYER'].valueOf())] = 'PLAYER'), - (values[(values.FLOOR = exports['CollisionFlag.FLOOR'].valueOf())] = 'FLOOR'), - (values[(values.WALL_NORTH_WEST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_NORTH_WEST_ROUTE_BLOCKER'].valueOf())] = 'WALL_NORTH_WEST_ROUTE_BLOCKER'), - (values[(values.WALL_NORTH_ROUTE_BLOCKER = exports['CollisionFlag.WALL_NORTH_ROUTE_BLOCKER'].valueOf())] = 'WALL_NORTH_ROUTE_BLOCKER'), - (values[(values.WALL_NORTH_EAST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_NORTH_EAST_ROUTE_BLOCKER'].valueOf())] = 'WALL_NORTH_EAST_ROUTE_BLOCKER'), - (values[(values.WALL_EAST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_EAST_ROUTE_BLOCKER'].valueOf())] = 'WALL_EAST_ROUTE_BLOCKER'), - (values[(values.WALL_SOUTH_EAST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_SOUTH_EAST_ROUTE_BLOCKER'].valueOf())] = 'WALL_SOUTH_EAST_ROUTE_BLOCKER'), - (values[(values.WALL_SOUTH_ROUTE_BLOCKER = exports['CollisionFlag.WALL_SOUTH_ROUTE_BLOCKER'].valueOf())] = 'WALL_SOUTH_ROUTE_BLOCKER'), - (values[(values.WALL_SOUTH_WEST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_SOUTH_WEST_ROUTE_BLOCKER'].valueOf())] = 'WALL_SOUTH_WEST_ROUTE_BLOCKER'), - (values[(values.WALL_WEST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_WEST_ROUTE_BLOCKER'].valueOf())] = 'WALL_WEST_ROUTE_BLOCKER'), - (values[(values.LOC_ROUTE_BLOCKER = exports['CollisionFlag.LOC_ROUTE_BLOCKER'].valueOf())] = 'LOC_ROUTE_BLOCKER'), - (values[(values.ROOF = exports['CollisionFlag.ROOF'].valueOf())] = 'ROOF'), - (values[(values.FLOOR_BLOCKED = exports['CollisionFlag.FLOOR_BLOCKED'].valueOf())] = 'FLOOR_BLOCKED'), - (values[(values.WALK_BLOCKED = exports['CollisionFlag.WALK_BLOCKED'].valueOf())] = 'WALK_BLOCKED'), - (values[(values.BLOCK_WEST = exports['CollisionFlag.BLOCK_WEST'].valueOf())] = 'BLOCK_WEST'), - (values[(values.BLOCK_EAST = exports['CollisionFlag.BLOCK_EAST'].valueOf())] = 'BLOCK_EAST'), - (values[(values.BLOCK_SOUTH = exports['CollisionFlag.BLOCK_SOUTH'].valueOf())] = 'BLOCK_SOUTH'), - (values[(values.BLOCK_NORTH = exports['CollisionFlag.BLOCK_NORTH'].valueOf())] = 'BLOCK_NORTH'), - (values[(values.BLOCK_SOUTH_WEST = exports['CollisionFlag.BLOCK_SOUTH_WEST'].valueOf())] = 'BLOCK_SOUTH_WEST'), - (values[(values.BLOCK_SOUTH_EAST = exports['CollisionFlag.BLOCK_SOUTH_EAST'].valueOf())] = 'BLOCK_SOUTH_EAST'), - (values[(values.BLOCK_NORTH_WEST = exports['CollisionFlag.BLOCK_NORTH_WEST'].valueOf())] = 'BLOCK_NORTH_WEST'), - (values[(values.BLOCK_NORTH_EAST = exports['CollisionFlag.BLOCK_NORTH_EAST'].valueOf())] = 'BLOCK_NORTH_EAST'), - (values[(values.BLOCK_NORTH_AND_SOUTH_EAST = exports['CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST'].valueOf())] = 'BLOCK_NORTH_AND_SOUTH_EAST'), - (values[(values.BLOCK_NORTH_AND_SOUTH_WEST = exports['CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST'].valueOf())] = 'BLOCK_NORTH_AND_SOUTH_WEST'), - (values[(values.BLOCK_NORTH_EAST_AND_WEST = exports['CollisionFlag.BLOCK_NORTH_EAST_AND_WEST'].valueOf())] = 'BLOCK_NORTH_EAST_AND_WEST'), - (values[(values.BLOCK_SOUTH_EAST_AND_WEST = exports['CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST'].valueOf())] = 'BLOCK_SOUTH_EAST_AND_WEST'), - (values[(values.BLOCK_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_WEST_ROUTE_BLOCKER'), - (values[(values.BLOCK_EAST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_EAST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_EAST_ROUTE_BLOCKER'), - (values[(values.BLOCK_SOUTH_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_SOUTH_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_SOUTH_ROUTE_BLOCKER'), - (values[(values.BLOCK_NORTH_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_ROUTE_BLOCKER'), - (values[(values.BLOCK_SOUTH_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_SOUTH_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_SOUTH_WEST_ROUTE_BLOCKER'), - (values[(values.BLOCK_SOUTH_EAST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_SOUTH_EAST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_SOUTH_EAST_ROUTE_BLOCKER'), - (values[(values.BLOCK_NORTH_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_WEST_ROUTE_BLOCKER'), - (values[(values.BLOCK_NORTH_EAST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_EAST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_EAST_ROUTE_BLOCKER'), - (values[(values.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER'), - (values[(values.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER'), - (values[(values.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER'), - (values[(values.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER'), - values - ))({}), - LocShape: (values => ( - (values[(values.WALL_STRAIGHT = exports['LocShape.WALL_STRAIGHT'].valueOf())] = 'WALL_STRAIGHT'), - (values[(values.WALL_DIAGONAL_CORNER = exports['LocShape.WALL_DIAGONAL_CORNER'].valueOf())] = 'WALL_DIAGONAL_CORNER'), - (values[(values.WALL_L = exports['LocShape.WALL_L'].valueOf())] = 'WALL_L'), - (values[(values.WALL_SQUARE_CORNER = exports['LocShape.WALL_SQUARE_CORNER'].valueOf())] = 'WALL_SQUARE_CORNER'), - (values[(values.WALLDECOR_STRAIGHT_NOOFFSET = exports['LocShape.WALLDECOR_STRAIGHT_NOOFFSET'].valueOf())] = 'WALLDECOR_STRAIGHT_NOOFFSET'), - (values[(values.WALLDECOR_STRAIGHT_OFFSET = exports['LocShape.WALLDECOR_STRAIGHT_OFFSET'].valueOf())] = 'WALLDECOR_STRAIGHT_OFFSET'), - (values[(values.WALLDECOR_DIAGONAL_OFFSET = exports['LocShape.WALLDECOR_DIAGONAL_OFFSET'].valueOf())] = 'WALLDECOR_DIAGONAL_OFFSET'), - (values[(values.WALLDECOR_DIAGONAL_NOOFFSET = exports['LocShape.WALLDECOR_DIAGONAL_NOOFFSET'].valueOf())] = 'WALLDECOR_DIAGONAL_NOOFFSET'), - (values[(values.WALLDECOR_DIAGONAL_BOTH = exports['LocShape.WALLDECOR_DIAGONAL_BOTH'].valueOf())] = 'WALLDECOR_DIAGONAL_BOTH'), - (values[(values.WALL_DIAGONAL = exports['LocShape.WALL_DIAGONAL'].valueOf())] = 'WALL_DIAGONAL'), - (values[(values.CENTREPIECE_STRAIGHT = exports['LocShape.CENTREPIECE_STRAIGHT'].valueOf())] = 'CENTREPIECE_STRAIGHT'), - (values[(values.CENTREPIECE_DIAGONAL = exports['LocShape.CENTREPIECE_DIAGONAL'].valueOf())] = 'CENTREPIECE_DIAGONAL'), - (values[(values.ROOF_STRAIGHT = exports['LocShape.ROOF_STRAIGHT'].valueOf())] = 'ROOF_STRAIGHT'), - (values[(values.ROOF_DIAGONAL_WITH_ROOFEDGE = exports['LocShape.ROOF_DIAGONAL_WITH_ROOFEDGE'].valueOf())] = 'ROOF_DIAGONAL_WITH_ROOFEDGE'), - (values[(values.ROOF_DIAGONAL = exports['LocShape.ROOF_DIAGONAL'].valueOf())] = 'ROOF_DIAGONAL'), - (values[(values.ROOF_L_CONCAVE = exports['LocShape.ROOF_L_CONCAVE'].valueOf())] = 'ROOF_L_CONCAVE'), - (values[(values.ROOF_L_CONVEX = exports['LocShape.ROOF_L_CONVEX'].valueOf())] = 'ROOF_L_CONVEX'), - (values[(values.ROOF_FLAT = exports['LocShape.ROOF_FLAT'].valueOf())] = 'ROOF_FLAT'), - (values[(values.ROOFEDGE_STRAIGHT = exports['LocShape.ROOFEDGE_STRAIGHT'].valueOf())] = 'ROOFEDGE_STRAIGHT'), - (values[(values.ROOFEDGE_DIAGONAL_CORNER = exports['LocShape.ROOFEDGE_DIAGONAL_CORNER'].valueOf())] = 'ROOFEDGE_DIAGONAL_CORNER'), - (values[(values.ROOFEDGE_L = exports['LocShape.ROOFEDGE_L'].valueOf())] = 'ROOFEDGE_L'), - (values[(values.ROOFEDGE_SQUARE_CORNER = exports['LocShape.ROOFEDGE_SQUARE_CORNER'].valueOf())] = 'ROOFEDGE_SQUARE_CORNER'), - (values[(values.GROUND_DECOR = exports['LocShape.GROUND_DECOR'].valueOf())] = 'GROUND_DECOR'), - values - ))({}), - LocAngle: (values => ( - (values[(values.WEST = exports['LocAngle.WEST'].valueOf())] = 'WEST'), - (values[(values.NORTH = exports['LocAngle.NORTH'].valueOf())] = 'NORTH'), - (values[(values.EAST = exports['LocAngle.EAST'].valueOf())] = 'EAST'), - (values[(values.SOUTH = exports['LocAngle.SOUTH'].valueOf())] = 'SOUTH'), - values - ))({}), - CollisionType: (values => ( - (values[(values.NORMAL = exports['CollisionType.NORMAL'].valueOf())] = 'NORMAL'), - (values[(values.BLOCKED = exports['CollisionType.BLOCKED'].valueOf())] = 'BLOCKED'), - (values[(values.INDOORS = exports['CollisionType.INDOORS'].valueOf())] = 'INDOORS'), - (values[(values.OUTDOORS = exports['CollisionType.OUTDOORS'].valueOf())] = 'OUTDOORS'), - (values[(values.LINE_OF_SIGHT = exports['CollisionType.LINE_OF_SIGHT'].valueOf())] = 'LINE_OF_SIGHT'), - values - ))({}), - LocLayer: (values => ( - (values[(values.WALL = exports['LocLayer.WALL'].valueOf())] = 'WALL'), - (values[(values.WALL_DECOR = exports['LocLayer.WALL_DECOR'].valueOf())] = 'WALL_DECOR'), - (values[(values.GROUND = exports['LocLayer.GROUND'].valueOf())] = 'GROUND'), - (values[(values.GROUND_DECOR = exports['LocLayer.GROUND_DECOR'].valueOf())] = 'GROUND_DECOR'), - values - ))({}), - BlockAccessFlag: (values => ( - (values[(values.BLOCK_NORTH = exports['BlockAccessFlag.BLOCK_NORTH'].valueOf())] = 'BLOCK_NORTH'), - (values[(values.BLOCK_EAST = exports['BlockAccessFlag.BLOCK_EAST'].valueOf())] = 'BLOCK_EAST'), - (values[(values.BLOCK_SOUTH = exports['BlockAccessFlag.BLOCK_SOUTH'].valueOf())] = 'BLOCK_SOUTH'), - (values[(values.BLOCK_WEST = exports['BlockAccessFlag.BLOCK_WEST'].valueOf())] = 'BLOCK_WEST'), - values - ))({}) - }, - exports - ); - function __liftString(pointer) { - if (!pointer) return null; - const end = (pointer + new Uint32Array(memory.buffer)[(pointer - 4) >>> 2]) >>> 1, - memoryU16 = new Uint16Array(memory.buffer); - let start = pointer >>> 1, - string = ''; - while (end - start > 1024) string += String.fromCharCode(...memoryU16.subarray(start, (start += 1024))); - return string + String.fromCharCode(...memoryU16.subarray(start, end)); - } - function __liftStaticArray(liftElement, align, pointer) { - if (!pointer) return null; - const length = __getU32(pointer - 4) >>> align, - values = new Array(length); - for (let i = 0; i < length; ++i) values[i] = liftElement(pointer + ((i << align) >>> 0)); - return values; - } - let __dataview = new DataView(memory.buffer); - function __getI32(pointer) { - try { - return __dataview.getInt32(pointer, true); - } catch { - __dataview = new DataView(memory.buffer); - return __dataview.getInt32(pointer, true); - } - } - function __getU32(pointer) { - try { - return __dataview.getUint32(pointer, true); - } catch { - __dataview = new DataView(memory.buffer); - return __dataview.getUint32(pointer, true); - } - } - return adaptedExports; -} -var { - memory, - findPath, - findNaivePath, - changeFloor, - changeLoc, - changeNpc, - changePlayer, - changeRoof, - changeWall, - allocateIfAbsent, - deallocateIfPresent, - isZoneAllocated, - isFlagged, - canTravel, - hasLineOfSight, - hasLineOfWalk, - lineOfSight, - lineOfWalk, - reached, - locShapeLayer, - __get, - __set, - __add, - __remove, - __rotate, - __rotateFlags, - __collides, - __reachRectangle1, - __reachRectangleN, - __alteredRotation, - __reachRectangle, - __reachExclusiveRectangle, - CollisionFlag, - LocShape, - LocAngle, - CollisionType, - LocLayer, - BlockAccessFlag -} = await (async url => - instantiate2( - await (async () => { - try { - return await globalThis.WebAssembly.compileStreaming(globalThis.fetch(url)); - } catch { - return globalThis.WebAssembly.compile(await (await import('node:fs/promises')).readFile(url)); - } - })(), - {} - ))(new URL('rsmod-pathfinder.wasm', import.meta.url)); - -// src/lostcity/entity/Position.ts -var Direction = { - NORTH_WEST: 0, - NORTH: 1, - NORTH_EAST: 2, - WEST: 3, - EAST: 4, - SOUTH_WEST: 5, - SOUTH: 6, - SOUTH_EAST: 7 -}; -var Position = { - zone: pos => pos >> 3, - zoneCenter: pos => Position.zone(pos) - 6, - zoneOrigin: pos => Position.zoneCenter(pos) << 3, - mapsquare: pos => pos >> 6, - local: pos => pos - (Position.zoneCenter(pos) << 3), - localOrigin: pos => pos - (Position.mapsquare(pos) << 6), - zoneUpdate: pos => pos - ((pos >> 3) << 3), - face: (srcX, srcZ, dstX, dstZ) => { - if (srcX == dstX) { - if (srcZ > dstZ) { - return Direction.SOUTH; - } else if (srcZ < dstZ) { - return Direction.NORTH; - } - } else if (srcX > dstX) { - if (srcZ > dstZ) { - return Direction.SOUTH_WEST; - } else if (srcZ < dstZ) { - return Direction.NORTH_WEST; - } else { - return Direction.WEST; - } - } else { - if (srcZ > dstZ) { - return Direction.SOUTH_EAST; - } else if (srcZ < dstZ) { - return Direction.NORTH_EAST; - } else { - return Direction.EAST; - } - } - return -1; - }, - moveX: (pos, dir) => { - return pos + Position.deltaX(dir); - }, - moveZ: (pos, dir) => { - return pos + Position.deltaZ(dir); - }, - distanceTo(pos, other) { - const p1 = Position.closest(pos, other); - const p2 = Position.closest(other, pos); - return Math.max(Math.abs(p1.x - p2.x), Math.abs(p1.z - p2.z)); - }, - closest(pos, other) { - const occupiedX = pos.x + pos.width - 1; - const occupiedZ = pos.z + pos.length - 1; - return { - x: other.x <= pos.x ? pos.x : other.x >= occupiedX ? occupiedX : other.x, - z: other.z <= pos.z ? pos.z : other.z >= occupiedZ ? occupiedZ : other.z - }; - }, - distanceToSW(pos, other) { - const deltaX = Math.abs(pos.x - other.x); - const deltaZ = Math.abs(pos.z - other.z); - return Math.max(deltaX, deltaZ); - }, - isWithinDistanceSW(pos, other, distance) { - const dx = Math.abs(pos.x - other.x); - const dz = Math.abs(pos.z - other.z); - return dz < distance && dx < distance; - }, - deltaX(dir) { - switch (dir) { - case Direction.SOUTH_EAST: - case Direction.NORTH_EAST: - case Direction.EAST: - return 1; - case Direction.SOUTH_WEST: - case Direction.NORTH_WEST: - case Direction.WEST: - return -1; - } - return 0; - }, - deltaZ(dir) { - switch (dir) { - case Direction.NORTH_WEST: - case Direction.NORTH_EAST: - case Direction.NORTH: - return 1; - case Direction.SOUTH_WEST: - case Direction.SOUTH_EAST: - case Direction.SOUTH: - return -1; - } - return 0; - }, - unpackCoord(coord) { - const level = (coord >> 28) & 3; - const x = (coord >> 14) & 16383; - const z2 = coord & 16383; - return {level, x, z: z2}; - }, - packCoord(level, x, z2) { - return (z2 & 16383) | ((x & 16383) << 14) | ((level & 3) << 28); - }, - packZoneCoord(x, z2) { - return ((x & 7) << 4) | (z2 & 7); - }, - intersects(srcX, srcZ, srcWidth, srcHeight, destX, destZ, destWidth, destHeight) { - const srcHorizontal = srcX + srcWidth; - const srcVertical = srcZ + srcHeight; - const destHorizontal = destX + destWidth; - const destVertical = destZ + destHeight; - return !(destX >= srcHorizontal || destHorizontal <= srcX || destZ >= srcVertical || destVertical <= srcZ); - }, - formatString(level, x, z2, separator = '_') { - const mx = x >> 6; - const mz = z2 >> 6; - const lx = x & 63; - const lz = z2 & 63; - return level + separator + mx + separator + mz + separator + lx + separator + lz; - } -}; - -// src/lostcity/entity/HitType.ts -var HitType; -(HitType2 => { - HitType2[(HitType2['BLOCK'] = 0)] = 'BLOCK'; - HitType2[(HitType2['DAMAGE'] = 1)] = 'DAMAGE'; - HitType2[(HitType2['POISON'] = 2)] = 'POISON'; -})((HitType ||= {})); -var HitType_default = HitType; - -// src/lostcity/entity/PlayerStat.ts -var PlayerStat; -(PlayerStat2 => { - PlayerStat2[(PlayerStat2['ATTACK'] = 0)] = 'ATTACK'; - PlayerStat2[(PlayerStat2['DEFENCE'] = 1)] = 'DEFENCE'; - PlayerStat2[(PlayerStat2['STRENGTH'] = 2)] = 'STRENGTH'; - PlayerStat2[(PlayerStat2['HITPOINTS'] = 3)] = 'HITPOINTS'; - PlayerStat2[(PlayerStat2['RANGED'] = 4)] = 'RANGED'; - PlayerStat2[(PlayerStat2['PRAYER'] = 5)] = 'PRAYER'; - PlayerStat2[(PlayerStat2['MAGIC'] = 6)] = 'MAGIC'; - PlayerStat2[(PlayerStat2['COOKING'] = 7)] = 'COOKING'; - PlayerStat2[(PlayerStat2['WOODCUTTING'] = 8)] = 'WOODCUTTING'; - PlayerStat2[(PlayerStat2['FLETCHING'] = 9)] = 'FLETCHING'; - PlayerStat2[(PlayerStat2['FISHING'] = 10)] = 'FISHING'; - PlayerStat2[(PlayerStat2['FIREMAKING'] = 11)] = 'FIREMAKING'; - PlayerStat2[(PlayerStat2['CRAFTING'] = 12)] = 'CRAFTING'; - PlayerStat2[(PlayerStat2['SMITHING'] = 13)] = 'SMITHING'; - PlayerStat2[(PlayerStat2['MINING'] = 14)] = 'MINING'; - PlayerStat2[(PlayerStat2['HERBLORE'] = 15)] = 'HERBLORE'; - PlayerStat2[(PlayerStat2['AGILITY'] = 16)] = 'AGILITY'; - PlayerStat2[(PlayerStat2['THIEVING'] = 17)] = 'THIEVING'; - PlayerStat2[(PlayerStat2['STAT18'] = 18)] = 'STAT18'; - PlayerStat2[(PlayerStat2['STAT19'] = 19)] = 'STAT19'; - PlayerStat2[(PlayerStat2['RUNECRAFT'] = 20)] = 'RUNECRAFT'; -})((PlayerStat ||= {})); -var PlayerStat_default = PlayerStat; - -// src/lostcity/engine/script/ScriptValidators.ts -function check(input, validator) { - return validator.validate(input); -} - -class ScriptInputNumberNotNullValidator { - validate(input) { - if (input !== -1) return input; - throw Error('An input number was null(-1).'); - } -} - -class ScriptInputStringNotNullValidator { - validate(input) { - if (input.length > 0) return input; - throw Error('An input string was null(-1).'); - } -} - -class ScriptInputConfigTypeValidator { - type; - count; - name; - constructor(type, count, name) { - this.type = type; - this.count = count; - this.name = name; - } - validate(input) { - if (this.count(input)) return this.type(input); - throw new Error(`An input for a ${this.name} type was not valid to use. Input was ${input}.`); - } -} - -class ScriptInputRangeValidator { - min; - max; - name; - constructor(min, max, name) { - this.min = min; - this.max = max; - this.name = name; - } - validate(input) { - if (input >= this.min && input <= this.max) { - return input; - } - throw new Error(`An input for a ${this.name} was out of range. Range should be: ${this.min} to ${this.max}. Input was ${input}.`); - } -} - -class ScriptInputCoordValidator extends ScriptInputRangeValidator { - validate(input) { - if (input >= this.min && input <= this.max) { - return Position.unpackCoord(input); - } - throw new Error(`An input for a ${this.name} was out of range. Range should be: ${this.min} to ${this.max}. Input was ${input}.`); - } -} -var NumberNotNull = new ScriptInputNumberNotNullValidator(); -var StringNotNull = new ScriptInputStringNotNullValidator(); -var LocTypeValid = new ScriptInputConfigTypeValidator(LocType.get, input => input >= 0 && input < LocType.count, 'Loc'); -var LocAngleValid = new ScriptInputRangeValidator(LocAngle.WEST, LocAngle.SOUTH, 'LocAngle'); -var LocShapeValid = new ScriptInputRangeValidator(LocShape.WALL_STRAIGHT, LocShape.GROUND_DECOR, 'LocShape'); -var DurationValid = new ScriptInputRangeValidator(1, 2147483647, 'Duration'); -var CoordValid = new ScriptInputCoordValidator(0, 2147483647, 'Coord'); -var ParamTypeValid = new ScriptInputConfigTypeValidator(ParamType.get, input => input >= 0 && input < ParamType.count, 'Param'); -var NpcTypeValid = new ScriptInputConfigTypeValidator(NpcType.get, input => input >= 0 && input < NpcType.count, 'Npc'); -var NpcStatValid = new ScriptInputRangeValidator(NpcStat_default.ATTACK, NpcStat_default.MAGIC, 'NpcStat'); -var PlayerStatValid = new ScriptInputRangeValidator(PlayerStat_default.ATTACK, PlayerStat_default.RUNECRAFT, 'PlayerStat'); -var QueueValid = new ScriptInputRangeValidator(0, 19, 'AIQueue'); -var HuntTypeValid = new ScriptInputConfigTypeValidator(HuntType.get, input => input >= 0 && input < HuntType.count, 'Hunt'); -var NpcModeValid = new ScriptInputRangeValidator(NpcMode_default.NULL, NpcMode_default.APNPC5, 'NpcMode'); -var HitTypeValid = new ScriptInputRangeValidator(HitType_default.BLOCK, HitType_default.POISON, 'Hit'); -var SpotAnimTypeValid = new ScriptInputConfigTypeValidator(SpotanimType.get, input => input >= 0 && input < SpotanimType.count, 'Spotanim'); -var EnumTypeValid = new ScriptInputConfigTypeValidator(EnumType.get, input => input >= 0 && input < EnumType.count, 'Enum'); -var ObjTypeValid = new ScriptInputConfigTypeValidator(ObjType.get, input => input >= 0 && input < ObjType.count, 'Obj'); -var ObjStackValid = new ScriptInputRangeValidator(1, Inventory.STACK_LIMIT, 'ObjStack'); -var InvTypeValid = new ScriptInputConfigTypeValidator(InvType.get, input => input >= 0 && input < InvType.count, 'Inv'); -var CategoryTypeValid = new ScriptInputConfigTypeValidator(CategoryType.get, input => input >= 0 && input < CategoryType.count, 'Cat'); -var IDKTypeValid = new ScriptInputConfigTypeValidator(IdkType.get, input => input >= 0 && input < IdkType.count, 'Idk'); -var HuntVisValid = new ScriptInputRangeValidator(HuntVis_default.OFF, HuntVis_default.LINEOFWALK, 'HuntVis'); -var SeqTypeValid = new ScriptInputConfigTypeValidator(SeqType.get, input => input >= 0 && input < SeqType.count, 'Seq'); -var VarPlayerValid = new ScriptInputConfigTypeValidator(VarPlayerType.get, input => input >= 0 && input < VarPlayerType.count, 'Varp'); -var VarNpcValid = new ScriptInputConfigTypeValidator(VarNpcType.get, input => input >= 0 && input < VarNpcType.count, 'Varn'); -var VarSharedValid = new ScriptInputConfigTypeValidator(VarSharedType.get, input => input >= 0 && input < VarSharedType.count, 'Vars'); -var FontTypeValid = new ScriptInputConfigTypeValidator(FontType.get, input => input >= 0 && input < FontType.count, 'Font'); -var MesanimValid = new ScriptInputConfigTypeValidator(MesanimType.get, input => input >= 0 && input < MesanimType.count, 'Mesanim'); -var StructTypeValid = new ScriptInputConfigTypeValidator(StructType.get, input => input >= 0 && input < StructType.count, 'Struct'); -var DbRowTypeValid = new ScriptInputConfigTypeValidator(DbRowType.get, input => input >= 0 && input < DbRowType.count, 'Dbrow'); -var DbTableTypeValid = new ScriptInputConfigTypeValidator(DbTableType.get, input => input >= 0 && input < DbTableType.count, 'Dbtable'); -var GenderValid = new ScriptInputRangeValidator(0, 1, 'Gender'); -var SkinColourValid = new ScriptInputRangeValidator(0, 7, 'SkinColour'); - -// src/lostcity/engine/script/handlers/CoreOps.ts -var gosub = function (state, id) { - if (state.fp >= 50) { - throw new Error('stack overflow'); - } - state.frames[state.fp++] = { - script: state.script, - pc: state.pc, - intLocals: state.intLocals, - stringLocals: state.stringLocals - }; - const script = ScriptProvider.get(id); - if (!script) { - throw new Error(`unable to find proc ${script}`); - } - setupNewScript(state, script); -}; -var jump = function (state, id) { - const label = ScriptProvider.get(id); - if (!label) { - throw new Error(`unable to find label ${id}`); - } - state.debugFrames[state.debugFp++] = { - script: state.script, - pc: state.pc - }; - setupNewScript(state, label); - state.fp = 0; - state.frames = []; -}; -var setupNewScript = function (state, script) { - state.script = script; - state.pc = -1; - state.intLocals = state.popInts(script.intArgCount); - state.stringLocals = state.popStrings(script.stringArgCount); -}; -var CoreOps = { - [ScriptOpcode_default.PUSH_CONSTANT_INT]: state => { - state.pushInt(state.intOperand); - }, - [ScriptOpcode_default.PUSH_CONSTANT_STRING]: state => { - state.pushString(state.stringOperand); - }, - [ScriptOpcode_default.PUSH_VARP]: state => { - const secondary = (state.intOperand >> 16) & 1; - if (secondary && !state._activePlayer2) { - throw new Error('No secondary active_player.'); - } else if (!secondary && !state._activePlayer) { - throw new Error('No active_player.'); - } - const varpType = check(state.intOperand & 65535, VarPlayerValid); - if (varpType.type === ScriptVarType.STRING) { - state.pushString(secondary ? state._activePlayer2.getVar(varpType.id) : state._activePlayer.getVar(varpType.id)); - } else { - state.pushInt(secondary ? state._activePlayer2.getVar(varpType.id) : state._activePlayer.getVar(varpType.id)); - } - }, - [ScriptOpcode_default.POP_VARP]: state => { - const secondary = (state.intOperand >> 16) & 1; - if (secondary && !state._activePlayer2) { - throw new Error('No secondary active_player.'); - } else if (!secondary && !state._activePlayer) { - throw new Error('No active_player.'); - } - const varpType = check(state.intOperand & 65535, VarPlayerValid); - if (!state.pointerGet(ProtectedActivePlayer[secondary]) && varpType.protect) { - throw new Error(`%${varpType.debugname} requires protected access`); - } - if (varpType.type === ScriptVarType.STRING) { - const value = state.popString(); - if (secondary) { - state._activePlayer2.setVar(varpType.id, value); - } else { - state._activePlayer.setVar(varpType.id, value); - } - } else { - const value = state.popInt(); - if (secondary) { - state._activePlayer2.setVar(varpType.id, value); - } else { - state._activePlayer.setVar(varpType.id, value); - } - } - }, - [ScriptOpcode_default.PUSH_VARN]: state => { - const secondary = (state.intOperand >> 16) & 1; - if (secondary && !state._activeNpc2) { - throw new Error('No secondary active_npc.'); - } else if (!secondary && !state._activeNpc) { - throw new Error('No active_npc.'); - } - const varnType = check(state.intOperand & 65535, VarNpcValid); - if (varnType.type === ScriptVarType.STRING) { - state.pushString(secondary ? state._activeNpc2.getVar(varnType.id) : state._activeNpc.getVar(varnType.id)); - } else { - state.pushInt(secondary ? state._activeNpc2.getVar(varnType.id) : state._activeNpc.getVar(varnType.id)); - } - }, - [ScriptOpcode_default.POP_VARN]: state => { - const secondary = (state.intOperand >> 16) & 1; - if (secondary && !state._activeNpc2) { - throw new Error('No secondary active_npc.'); - } else if (!secondary && !state._activeNpc) { - throw new Error('No active_npc.'); - } - const varnType = check(state.intOperand & 65535, VarNpcValid); - if (varnType.type === ScriptVarType.STRING) { - const value = state.popInt(); - if (secondary) { - state._activeNpc2.setVar(varnType.id, value); - } else { - state._activeNpc.setVar(varnType.id, value); - } - } else { - const value = state.popInt(); - if (secondary) { - state._activeNpc2.setVar(varnType.id, value); - } else { - state._activeNpc.setVar(varnType.id, value); - } - } - }, - [ScriptOpcode_default.PUSH_INT_LOCAL]: state => { - state.pushInt(state.intLocals[state.intOperand]); - }, - [ScriptOpcode_default.POP_INT_LOCAL]: state => { - state.intLocals[state.intOperand] = state.popInt(); - }, - [ScriptOpcode_default.PUSH_STRING_LOCAL]: state => { - state.pushString(state.stringLocals[state.intOperand]); - }, - [ScriptOpcode_default.POP_STRING_LOCAL]: state => { - state.stringLocals[state.intOperand] = state.popString(); - }, - [ScriptOpcode_default.BRANCH]: state => { - state.pc += state.intOperand; - }, - [ScriptOpcode_default.BRANCH_NOT]: state => { - const b2 = state.popInt(); - const a = state.popInt(); - if (a !== b2) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.BRANCH_EQUALS]: state => { - const b2 = state.popInt(); - const a = state.popInt(); - if (a === b2) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.BRANCH_LESS_THAN]: state => { - const b2 = state.popInt(); - const a = state.popInt(); - if (a < b2) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.BRANCH_GREATER_THAN]: state => { - const b2 = state.popInt(); - const a = state.popInt(); - if (a > b2) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.BRANCH_LESS_THAN_OR_EQUALS]: state => { - const b2 = state.popInt(); - const a = state.popInt(); - if (a <= b2) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.BRANCH_GREATER_THAN_OR_EQUALS]: state => { - const b2 = state.popInt(); - const a = state.popInt(); - if (a >= b2) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.POP_INT_DISCARD]: state => { - state.isp--; - }, - [ScriptOpcode_default.POP_STRING_DISCARD]: state => { - state.ssp--; - }, - [ScriptOpcode_default.RETURN]: state => { - if (state.fp === 0) { - state.execution = ScriptState.FINISHED; - return; - } - const frame = state.frames[--state.fp]; - state.pc = frame.pc; - state.script = frame.script; - state.intLocals = frame.intLocals; - state.stringLocals = frame.stringLocals; - }, - [ScriptOpcode_default.JOIN_STRING]: state => { - const count = state.intOperand; - const strings = []; - for (let i = 0; i < count; i++) { - strings.push(state.popString()); - } - state.pushString(strings.reverse().join('')); - }, - [ScriptOpcode_default.GOSUB]: state => { - gosub(state, state.popInt()); - }, - [ScriptOpcode_default.GOSUB_WITH_PARAMS]: state => { - gosub(state, state.intOperand); - }, - [ScriptOpcode_default.JUMP]: state => { - jump(state, state.popInt()); - }, - [ScriptOpcode_default.JUMP_WITH_PARAMS]: state => { - jump(state, state.intOperand); - }, - [ScriptOpcode_default.DEFINE_ARRAY]: state => { - throw new Error('unimplemented'); - }, - [ScriptOpcode_default.PUSH_ARRAY_INT]: state => { - throw new Error('unimplemented'); - }, - [ScriptOpcode_default.POP_ARRAY_INT]: state => { - throw new Error('unimplemented'); - }, - [ScriptOpcode_default.SWITCH]: state => { - const key = state.popInt(); - const table = state.script.switchTables[state.intOperand]; - if (table === undefined) { - return; - } - const result = table[key]; - if (result) { - state.pc += result; - } - }, - [ScriptOpcode_default.PUSH_VARS]: state => { - const varsType = check(state.intOperand & 65535, VarSharedValid); - if (varsType.type === ScriptVarType.STRING) { - state.pushString(World_default.varsString[varsType.id] ?? ''); - } else { - state.pushInt(World_default.vars[varsType.id]); - } - }, - [ScriptOpcode_default.POP_VARS]: state => { - const varsType = check(state.intOperand & 65535, VarSharedValid); - if (varsType.type === ScriptVarType.STRING) { - World_default.varsString[varsType.id] = state.popString(); - } else { - World_default.vars[varsType.id] = state.popInt(); - } - } -}; -var CoreOps_default = CoreOps; - -// src/lostcity/engine/script/handlers/DbOps.ts -var DebugOps = { - [ScriptOpcode_default.DB_FIND_WITH_COUNT]: state => { - throw new Error('unimplemented'); - }, - [ScriptOpcode_default.DB_FINDNEXT]: state => { - if (!state.dbTable) { - throw new Error('No table selected'); - } - if (state.dbRow + 1 >= state.dbRowQuery.length) { - state.pushInt(-1); - return; - } - state.dbRow++; - state.pushInt(check(state.dbRowQuery[state.dbRow], DbRowTypeValid).id); - }, - [ScriptOpcode_default.DB_GETFIELD]: state => { - const [row, tableColumnPacked, listIndex] = state.popInts(3); - const table = (tableColumnPacked >> 12) & 65535; - const column = (tableColumnPacked >> 4) & 127; - const tuple = tableColumnPacked & 63; - const rowType = check(row, DbRowTypeValid); - const tableType = check(table, DbTableTypeValid); - let values; - if (rowType.tableId !== table) { - values = tableType.getDefault(column); - } else { - values = rowType.getValue(column, listIndex); - } - const valueTypes = tableType.types[column]; - for (let i = 0; i < values.length; i++) { - if (valueTypes[i] === ScriptVarType.STRING) { - state.pushString(values[i]); - } else { - state.pushInt(values[i]); - } - } - }, - [ScriptOpcode_default.DB_GETFIELDCOUNT]: state => { - const [row, tableColumnPacked] = state.popInts(2); - const table = (tableColumnPacked >> 12) & 65535; - const column = (tableColumnPacked >> 4) & 127; - const tuple = tableColumnPacked & 63; - const rowType = check(row, DbRowTypeValid); - const tableType = check(table, DbTableTypeValid); - if (rowType.tableId !== table) { - state.pushInt(0); - return; - } - state.pushInt(rowType.columnValues[column].length / tableType.types[column].length); - }, - [ScriptOpcode_default.DB_LISTALL_WITH_COUNT]: state => { - throw new Error('unimplemented'); - }, - [ScriptOpcode_default.DB_GETROWTABLE]: state => { - state.pushInt(check(state.popInt(), DbRowTypeValid).tableId); - }, - [ScriptOpcode_default.DB_FINDBYINDEX]: state => { - throw new Error('unimplemented'); - }, - [ScriptOpcode_default.DB_FIND_REFINE_WITH_COUNT]: state => { - throw new Error('unimplemented'); - }, - [ScriptOpcode_default.DB_FIND]: state => { - const isString = state.popInt() == 2; - const query = isString ? state.popString() : state.popInt(); - const tableColumnPacked = state.popInt(); - const table = (tableColumnPacked >> 12) & 65535; - const column = (tableColumnPacked >> 4) & 127; - const tuple = tableColumnPacked & 63; - state.dbTable = check(table, DbTableTypeValid); - state.dbRow = -1; - state.dbRowQuery = []; - const rows = DbRowType.getInTable(table); - for (let i = 0; i < rows.length; i++) { - const row = rows[i]; - if (row.columnValues[column].includes(query)) { - state.dbRowQuery.push(row.id); - } - } - state.pushInt(state.dbRowQuery.length); - }, - [ScriptOpcode_default.DB_FIND_REFINE]: state => { - const isString = state.popInt() == 2; - const query = isString ? state.popString() : state.popInt(); - const tableColumnPacked = state.popInt(); - const table = (tableColumnPacked >> 12) & 65535; - const column = (tableColumnPacked >> 4) & 127; - const tuple = tableColumnPacked & 63; - const found = []; - const rows = DbRowType.getInTable(table); - for (let i = 0; i < rows.length; i++) { - const row = rows[i]; - if (row.columnValues[column].includes(query)) { - found.push(row.id); - } - } - const prevQuery = state.dbRowQuery; - state.dbRow = -1; - state.dbRowQuery = []; - for (let i = 0; i < prevQuery.length; i++) { - if (found.includes(prevQuery[i])) { - state.dbRowQuery.push(prevQuery[i]); - } - } - state.pushInt(state.dbRowQuery.length); - }, - [ScriptOpcode_default.DB_LISTALL]: state => { - throw new Error('unimplemented'); - } -}; -var DbOps_default = DebugOps; - -// src/lostcity/util/Environment.ts -var Environment_default = { - PUBLIC_IP: 'localhost', - WEB_PORT: 80, - GAME_PORT: 43594, - LOGIN_HOST: 'localhost', - LOGIN_PORT: 43500, - LOGIN_KEY: '', - FRIEND_HOST: 'localhost', - FRIEND_PORT: 43501, - FRIEND_KEY: '', - WORLD_ID: 0, - LOCAL_DEV: true, - MEMBERS_WORLD: true, - XP_MULTIPLIER: 1, - SHUTDOWN_TIMER: 50, - HTTPS_ENABLED: false, - ADDRESS_SHOWPORT: true, - CLIRUNNER: false, - CI_MODE: false, - SKIP_CORS: false, - DB_HOST: '', - DB_USER: '', - DB_PASS: '', - DB_NAME: '', - ADMIN_IP: 'localhost', - SKIP_CRC: false, - JAVA_PATH: 'java', - DATA_SRC_DIR: 'data/src', - VALIDATE_PACK: true, - STRICT_FOLDERS: true, - BUILD_ON_STARTUP: true, - UPDATE_ON_STARTUP: true, - JMODS: ['pazaz'], - CLIENT_PATHFINDER: true, - NO_SOCKET_TIMEOUT: false, - PROFILE_SCRIPTS: false -}; - -// src/lostcity/engine/script/handlers/DebugOps.ts -var DebugOps2 = { - [ScriptOpcode_default.ERROR]: state => { - throw new Error(state.popString()); - }, - [ScriptOpcode_default.MAP_LOCALDEV]: state => { - state.pushInt(Environment_default.LOCAL_DEV ? 1 : 0); - } -}; -var DebugOps_default = DebugOps2; - -// src/lostcity/engine/script/handlers/EnumOps.ts -var EnumOps = { - [ScriptOpcode_default.ENUM]: state => { - const [inputType, outputType, enumId, key] = state.popInts(4); - const enumType = check(enumId, EnumTypeValid); - if (enumType.inputtype !== inputType || enumType.outputtype !== outputType) { - throw new Error(`Type validation error: ${enumType.debugname} key: ${key}. Expected input: ${inputType} got: ${enumType.inputtype}. Expected output: ${outputType} got: ${enumType.outputtype}`); - } - const value = enumType.values.get(key); - if (typeof value === 'string') { - state.pushString(value ?? enumType.defaultString); - } else { - state.pushInt(value ?? enumType.defaultInt); - } - }, - [ScriptOpcode_default.ENUM_GETOUTPUTCOUNT]: state => { - state.pushInt(check(state.popInt(), EnumTypeValid).values.size); - } -}; -var EnumOps_default = EnumOps; - -// src/lostcity/entity/EntityLifeCycle.ts -var EntityLifeCycle; -(EntityLifeCycle2 => { - EntityLifeCycle2[(EntityLifeCycle2['FOREVER'] = 0)] = 'FOREVER'; - EntityLifeCycle2[(EntityLifeCycle2['RESPAWN'] = 1)] = 'RESPAWN'; - EntityLifeCycle2[(EntityLifeCycle2['DESPAWN'] = 2)] = 'DESPAWN'; -})((EntityLifeCycle ||= {})); -var EntityLifeCycle_default = EntityLifeCycle; - -// src/lostcity/entity/Entity.ts -class Entity { - level; - x; - z; - width; - length; - lifecycle; - lifecycleTick = -1; - lastLifecycleTick = -1; - constructor(level, x, z2, width, length, lifecycle) { - this.level = level; - this.x = x; - this.z = z2; - this.width = width; - this.length = length; - this.lifecycle = lifecycle; - } - updateLifeCycle(tick) { - return this.lifecycleTick === tick && this.lifecycle !== EntityLifeCycle_default.FOREVER; - } - checkLifeCycle(tick) { - if (this.lifecycle === EntityLifeCycle_default.FOREVER) { - return true; - } - if (this.lifecycle === EntityLifeCycle_default.RESPAWN) { - return this.lifecycleTick < tick; - } - if (this.lifecycle === EntityLifeCycle_default.DESPAWN) { - return this.lifecycleTick > tick; - } - return false; - } - setLifeCycle(tick) { - this.lifecycleTick = tick; - this.lastLifecycleTick = World_default.currentTick; - } -} - -// src/lostcity/entity/NonPathingEntity.ts -class NonPathingEntity extends Entity { - resetEntity(respawn) {} -} - -// src/lostcity/entity/Obj.ts -class Obj extends NonPathingEntity { - type; - count; - receiverId = -1; - reveal = -1; - constructor(level, x, z2, lifecycle, type, count) { - super(level, x, z2, 1, 1, lifecycle); - this.type = type; - this.count = count; - } -} - -// src/lostcity/engine/script/handlers/InvOps.ts -var InvOps = { - [ScriptOpcode_default.INV_ALLSTOCK]: state => { - const invType = check(state.popInt(), InvTypeValid); - state.pushInt(invType.allstock ? 1 : 0); - }, - [ScriptOpcode_default.INV_SIZE]: state => { - const invType = check(state.popInt(), InvTypeValid); - state.pushInt(invType.size); - }, - [ScriptOpcode_default.INV_STOCKBASE]: state => { - const [inv, obj] = state.popInts(2); - const invType = check(inv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - if (!invType.stockobj || !invType.stockcount) { - state.pushInt(-1); - return; - } - const index = invType.stockobj.indexOf(objType.id); - state.pushInt(index >= 0 ? invType.stockcount[index] : -1); - }, - [ScriptOpcode_default.INV_ADD]: checkedHandler(ActivePlayer, state => { - const [inv, objId, count] = state.popInts(3); - const invType = check(inv, InvTypeValid); - const objType = check(objId, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${invType.debugname}`); - } - if (!invType.dummyinv && objType.dummyitem !== 0) { - throw new Error(`dummyitem in non-dummyinv: ${objType.debugname} -> ${invType.debugname}`); - } - const player = state.activePlayer; - const overflow = count - player.invAdd(invType.id, objType.id, count); - if (overflow > 0) { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, objType.id, overflow), player.pid, 200); - } - }), - [ScriptOpcode_default.INV_CHANGESLOT]: checkedHandler(ActivePlayer, state => { - const [inv, find, replace, replaceCount] = state.popInts(4); - throw new Error('unimplemented'); - }), - [ScriptOpcode_default.INV_CLEAR]: checkedHandler(ActivePlayer, state => { - const invType = check(state.popInt(), InvTypeValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${invType.debugname}`); - } - state.activePlayer.invClear(invType.id); - }), - [ScriptOpcode_default.INV_DEL]: checkedHandler(ActivePlayer, state => { - const [inv, obj, count] = state.popInts(3); - const invType = check(inv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${invType.debugname}`); - } - state.activePlayer.invDel(invType.id, objType.id, count); - }), - [ScriptOpcode_default.INV_DELSLOT]: checkedHandler(ActivePlayer, state => { - const [inv, slot] = state.popInts(2); - const invType = check(inv, InvTypeValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${invType.debugname}`); - } - const obj = state.activePlayer.invGetSlot(invType.id, slot); - if (!obj) { - return; - } - state.activePlayer.invDelSlot(invType.id, slot); - }), - [ScriptOpcode_default.INV_DROPITEM]: checkedHandler(ActivePlayer, state => { - const [inv, coord, obj, count, duration] = state.popInts(5); - const invType = check(inv, InvTypeValid); - const position = check(coord, CoordValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - check(duration, DurationValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${invType.debugname}`); - } - const player = state.activePlayer; - const completed = player.invDel(invType.id, objType.id, count); - if (completed == 0) { - return; - } - player.playerLog('Dropped item from', invType.debugname, objType.debugname); - const floorObj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objType.id, completed); - World_default.addObj(floorObj, player.pid, duration); - state.activeObj = floorObj; - state.pointerAdd(ActiveObj[state.intOperand]); - }), - [ScriptOpcode_default.INV_DROPSLOT]: checkedHandler(ActivePlayer, state => { - const [inv, coord, slot, duration] = state.popInts(4); - const invType = check(inv, InvTypeValid); - check(duration, DurationValid); - const position = check(coord, CoordValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${invType.debugname}`); - } - const obj = state.activePlayer.invGetSlot(invType.id, slot); - if (!obj) { - throw new Error('$slot is empty'); - } - const player = state.activePlayer; - const completed = player.invDel(invType.id, obj.id, obj.count, slot); - if (completed === 0) { - return; - } - const objType = ObjType.get(obj.id); - player.playerLog('Dropped item from', invType.debugname, objType.debugname); - const floorObj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, obj.id, completed); - World_default.addObj(floorObj, player.pid, duration); - state.activeObj = floorObj; - state.pointerAdd(ActiveObj[state.intOperand]); - }), - [ScriptOpcode_default.INV_FREESPACE]: checkedHandler(ActivePlayer, state => { - const invType = check(state.popInt(), InvTypeValid); - state.pushInt(state.activePlayer.invFreeSpace(invType.id)); - }), - [ScriptOpcode_default.INV_GETNUM]: checkedHandler(ActivePlayer, state => { - const [inv, slot] = state.popInts(2); - const invType = check(inv, InvTypeValid); - state.pushInt(state.activePlayer.invGetSlot(invType.id, slot)?.count ?? 0); - }), - [ScriptOpcode_default.INV_GETOBJ]: checkedHandler(ActivePlayer, state => { - const [inv, slot] = state.popInts(2); - const invType = check(inv, InvTypeValid); - state.pushInt(state.activePlayer.invGetSlot(invType.id, slot)?.id ?? -1); - }), - [ScriptOpcode_default.INV_ITEMSPACE]: checkedHandler(ActivePlayer, state => { - const [inv, obj, count, size] = state.popInts(4); - const invType = check(inv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - if (size < 0 || size > invType.size) { - throw new Error(`\$count is out of range: ${count}`); - } - state.pushInt(state.activePlayer.invItemSpace(invType.id, objType.id, count, size) === 0 ? 1 : 0); - }), - [ScriptOpcode_default.INV_ITEMSPACE2]: checkedHandler(ActivePlayer, state => { - const [inv, obj, count, size] = state.popInts(4); - const invType = check(inv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - state.pushInt(state.activePlayer.invItemSpace(invType.id, objType.id, count, size)); - }), - [ScriptOpcode_default.INV_MOVEFROMSLOT]: checkedHandler(ActivePlayer, state => { - const [fromInv, toInv, fromSlot] = state.popInts(3); - const fromInvType = check(fromInv, InvTypeValid); - const toInvType = check(toInv, InvTypeValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${toInvType.debugname}`); - } - const player = state.activePlayer; - const {overflow, fromObj} = player.invMoveFromSlot(fromInvType.id, toInvType.id, fromSlot); - if (overflow > 0) { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, fromObj, overflow), player.pid, 200); - } - }), - [ScriptOpcode_default.INV_MOVETOSLOT]: checkedHandler(ActivePlayer, state => { - const [fromInv, toInv, fromSlot, toSlot] = state.popInts(4); - const fromInvType = check(fromInv, InvTypeValid); - const toInvType = check(toInv, InvTypeValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${toInvType.debugname}`); - } - state.activePlayer.invMoveToSlot(fromInvType.id, toInvType.id, fromSlot, toSlot); - }), - [ScriptOpcode_default.BOTH_MOVEINV]: checkedHandler(ActivePlayer, state => { - const [from, to] = state.popInts(2); - const fromInvType = check(from, InvTypeValid); - const toInvType = check(to, InvTypeValid); - const secondary = state.intOperand == 1; - const fromPlayer = secondary ? state._activePlayer2 : state._activePlayer; - const toPlayer = secondary ? state._activePlayer : state._activePlayer2; - if (!fromPlayer || !toPlayer) { - throw new Error('player is null'); - } - if (!state.pointerGet(ProtectedActivePlayer[secondary ? 1 : 0]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$from_inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[secondary ? 0 : 1]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$to_inv requires protected access: ${toInvType.debugname}`); - } - const fromInv = fromPlayer.getInventory(from); - const toInv = toPlayer.getInventory(to); - if (!fromInv || !toInv) { - throw new Error('inv is null'); - } - for (let slot = 0; slot < fromInv.capacity; slot++) { - const obj = fromInv.get(slot); - if (!obj) { - continue; - } - fromInv.delete(slot); - toInv.add(obj.id, obj.count); - fromPlayer.playerLog('Gave ' + ObjType.get(obj.id).name + ' x' + obj.count + ' during trade with ' + toPlayer.username); - toPlayer.playerLog('Received ' + ObjType.get(obj.id).name + ' x' + obj.count + ' during trade with ' + fromPlayer.username); - } - }), - [ScriptOpcode_default.INV_MOVEITEM]: checkedHandler(ActivePlayer, state => { - const [fromInv, toInv, obj, count] = state.popInts(4); - const fromInvType = check(fromInv, InvTypeValid); - const toInvType = check(toInv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${toInvType.debugname}`); - } - const player = state.activePlayer; - const completed = player.invDel(fromInvType.id, objType.id, count); - if (completed == 0) { - return; - } - const overflow = count - player.invAdd(toInvType.id, objType.id, completed); - if (overflow > 0) { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, objType.id, overflow), player.pid, 200); - } - }), - [ScriptOpcode_default.INV_MOVEITEM_CERT]: checkedHandler(ActivePlayer, state => { - const [fromInv, toInv, obj, count] = state.popInts(4); - const fromInvType = check(fromInv, InvTypeValid); - const toInvType = check(toInv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${toInvType.debugname}`); - } - const player = state.activePlayer; - const completed = player.invDel(fromInvType.id, objType.id, count); - if (completed == 0) { - return; - } - let finalObj = objType.id; - if (objType.certtemplate === -1 && objType.certlink >= 0) { - finalObj = objType.certlink; - } - const overflow = count - player.invAdd(toInvType.id, finalObj, completed); - if (overflow > 0) { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, finalObj, overflow), player.pid, 200); - } - }), - [ScriptOpcode_default.INV_MOVEITEM_UNCERT]: checkedHandler(ActivePlayer, state => { - const [fromInv, toInv, obj, count] = state.popInts(4); - const fromInvType = check(fromInv, InvTypeValid); - const toInvType = check(toInv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${toInvType.debugname}`); - } - const player = state.activePlayer; - const completed = player.invDel(fromInvType.id, objType.id, count); - if (completed == 0) { - return; - } - if (objType.certtemplate >= 0 && objType.certlink >= 0) { - player.invAdd(toInvType.id, objType.certlink, completed); - } else { - player.invAdd(toInvType.id, objType.id, completed); - } - }), - [ScriptOpcode_default.INV_SETSLOT]: checkedHandler(ActivePlayer, state => { - const [inv, slot, objId, count] = state.popInts(4); - const invType = check(inv, InvTypeValid); - const objType = check(objId, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${invType.debugname}`); - } - if (!invType.dummyinv && objType.dummyitem !== 0) { - throw new Error(`dummyitem in non-dummyinv: ${objType.debugname} -> ${invType.debugname}`); - } - state.activePlayer.invSet(invType.id, objType.id, count, slot); - }), - [ScriptOpcode_default.INV_TOTAL]: checkedHandler(ActivePlayer, state => { - const [inv, obj] = state.popInts(2); - const invType = check(inv, InvTypeValid); - if (obj === -1) { - state.pushInt(0); - return; - } - state.pushInt(state.activePlayer.invTotal(invType.id, obj)); - }), - [ScriptOpcode_default.INV_TOTALCAT]: checkedHandler(ActivePlayer, state => { - const [inv, category] = state.popInts(2); - const invType = check(inv, InvTypeValid); - const catType = check(category, CategoryTypeValid); - state.pushInt(state.activePlayer.invTotalCat(invType.id, catType.id)); - }), - [ScriptOpcode_default.INV_TRANSMIT]: checkedHandler(ActivePlayer, state => { - const [inv, com] = state.popInts(2); - const invType = check(inv, InvTypeValid); - check(com, NumberNotNull); - state.activePlayer.invListenOnCom(invType.id, com, state.activePlayer.uid); - }), - [ScriptOpcode_default.INVOTHER_TRANSMIT]: checkedHandler(ActivePlayer, state => { - const [uid, inv, com] = state.popInts(3); - check(uid, NumberNotNull); - const invType = check(inv, InvTypeValid); - check(com, NumberNotNull); - state.activePlayer.invListenOnCom(invType.id, com, uid); - }), - [ScriptOpcode_default.INV_STOPTRANSMIT]: checkedHandler(ActivePlayer, state => { - const com = check(state.popInt(), NumberNotNull); - state.activePlayer.invStopListenOnCom(com); - }), - [ScriptOpcode_default.BOTH_DROPSLOT]: checkedHandler(ActivePlayer, state => { - const [inv, coord, slot, duration] = state.popInts(4); - const invType = check(inv, InvTypeValid); - check(duration, DurationValid); - const position = check(coord, CoordValid); - const secondary = state.intOperand == 1; - const fromPlayer = secondary ? state._activePlayer2 : state._activePlayer; - const toPlayer = secondary ? state._activePlayer : state._activePlayer2; - if (!fromPlayer || !toPlayer) { - throw new Error('player is null'); - } - if (!state.pointerGet(ProtectedActivePlayer[secondary ? 1 : 0]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`inv requires protected access: ${invType.debugname}`); - } - const obj = fromPlayer.invGetSlot(invType.id, slot); - if (!obj) { - throw new Error('$slot is empty'); - } - const completed = fromPlayer.invDel(invType.id, obj.id, obj.count, slot); - if (completed === 0) { - return; - } - const objType = ObjType.get(obj.id); - fromPlayer.playerLog('Dropped item from', invType.debugname, objType.debugname); - if (!objType.tradeable) { - return; - } - World_default.addObj(new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, obj.id, completed), toPlayer.pid, duration); - }), - [ScriptOpcode_default.INV_DROPALL]: checkedHandler(ActivePlayer, state => { - const [inv, coord, duration] = state.popInts(3); - const invType = check(inv, InvTypeValid); - check(duration, DurationValid); - const position = check(coord, CoordValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`\$inv requires protected access: ${invType.debugname}`); - } - const inventory = state.activePlayer.getInventory(invType.id); - if (!inventory) { - return; - } - for (let slot = 0; slot < inventory.capacity; slot++) { - const obj = inventory.get(slot); - if (!obj) { - continue; - } - inventory.delete(slot); - const objType = ObjType.get(obj.id); - if (!objType.tradeable) { - continue; - } - World_default.addObj(new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, obj.id, obj.count), -1, duration); - } - }), - [ScriptOpcode_default.INV_TOTALPARAM]: checkedHandler(ActivePlayer, state => { - const [inv, param] = state.popInts(2); - state.pushInt(state.activePlayer.invTotalParam(inv, param)); - }), - [ScriptOpcode_default.INV_TOTALPARAM_STACK]: checkedHandler(ActivePlayer, state => { - const [inv, param] = state.popInts(2); - state.pushInt(state.activePlayer.invTotalParamStack(inv, param)); - }) -}; -var InvOps_default = InvOps; - -// src/lostcity/entity/NpcIteratorType.ts -var NpcIteratorType; -(NpcIteratorType2 => { - NpcIteratorType2[(NpcIteratorType2['ZONE'] = 0)] = 'ZONE'; - NpcIteratorType2[(NpcIteratorType2['DISTANCE'] = 1)] = 'DISTANCE'; -})((NpcIteratorType ||= {})); -var NpcIteratorType_default = NpcIteratorType; - -// src/lostcity/engine/script/ScriptIterators.ts -class ScriptIterator { - iterator; - tick; - constructor(tick) { - this.iterator = this.generator(); - this.tick = tick; - } - [Symbol.iterator]() { - return this.iterator; - } - next() { - return this.iterator.next(); - } -} - -class HuntIterator extends ScriptIterator { - x; - z; - level; - minX; - maxX; - minZ; - maxZ; - distance; - checkVis; - checkType; - checkCategory; - type; - constructor(tick, level, x, z2, distance, checkVis, checkType, checkCategory, type) { - super(tick); - const centerX = Position.zone(x); - const centerZ = Position.zone(z2); - const radius = (1 + distance / 8) | 0; - this.x = x; - this.z = z2; - this.level = level; - this.maxX = centerX + radius; - this.minX = centerX - radius; - this.maxZ = centerZ + radius; - this.minZ = centerZ - radius; - this.distance = distance; - this.checkVis = checkVis; - this.checkType = checkType; - this.checkCategory = checkCategory; - this.type = type; - } - *generator() { - for (let x = this.maxX; x >= this.minX; x--) { - const zoneX = x << 3; - for (let z2 = this.maxZ; z2 >= this.minZ; z2--) { - const zoneZ = z2 << 3; - if (this.type === HuntModeType_default.PLAYER) { - for (const player of World_default.getZone(zoneX, zoneZ, this.level).getAllPlayersSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error('[HuntIterator] tried to use an old iterator. Create a new iterator instead.'); - } - if (Position.distanceToSW({x: this.x, z: this.z}, player) > this.distance) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, player.x, player.z, 1, 1, 1, 1)) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, player.x, player.z, 1, 1, 1, 1)) { - continue; - } - yield player; - } - } else if (this.type === HuntModeType_default.NPC) { - for (const npc of World_default.getZone(zoneX, zoneZ, this.level).getAllNpcsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error('[HuntIterator] tried to use an old iterator. Create a new iterator instead.'); - } - if (this.checkType !== -1 && npc.type !== this.checkType) { - continue; - } - const npcType = NpcType.get(npc.type); - if (this.checkCategory !== -1 && npcType.category !== this.checkCategory) { - continue; - } - if (!npcType.op) { - continue; - } - if (!npcType.op[1]) { - continue; - } - if (Position.distanceToSW({x: this.x, z: this.z}, npc) > this.distance) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { - continue; - } - yield npc; - } - } else if (this.type === HuntModeType_default.OBJ) { - for (const obj of World_default.getZone(zoneX, zoneZ, this.level).getAllObjsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error('[HuntIterator] tried to use an old iterator. Create a new iterator instead.'); - } - if (this.checkType !== -1 && obj.type !== this.checkType) { - continue; - } - const objType = ObjType.get(obj.type); - if (this.checkCategory !== -1 && objType.category !== this.checkCategory) { - continue; - } - if (Position.distanceToSW({x: this.x, z: this.z}, obj) > this.distance) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, obj.x, obj.z, 1, 1, 1, 1)) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, obj.x, obj.z, 1, 1, 1, 1)) { - continue; - } - yield obj; - } - } else if (this.type === HuntModeType_default.SCENERY) { - for (const loc of World_default.getZone(zoneX, zoneZ, this.level).getAllLocsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error('[HuntIterator] tried to use an old iterator. Create a new iterator instead.'); - } - if (this.checkType !== -1 && loc.type !== this.checkType) { - continue; - } - const locType = LocType.get(loc.type); - if (this.checkCategory !== -1 && locType.category !== this.checkCategory) { - continue; - } - if (Position.distanceToSW({x: this.x, z: this.z}, loc) > this.distance) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, loc.x, loc.z, 1, 1, 1, 1)) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, loc.x, loc.z, 1, 1, 1, 1)) { - continue; - } - yield loc; - } - } - } - } - } -} - -class NpcIterator extends ScriptIterator { - level; - x; - z; - minX; - maxX; - minZ; - maxZ; - distance; - checkVis; - type; - constructor(tick, level, x, z2, distance, checkVis, type) { - super(tick); - const centerX = Position.zone(x); - const centerZ = Position.zone(z2); - const radius = (1 + distance / 8) | 0; - this.x = x; - this.z = z2; - this.level = level; - this.maxX = centerX + radius; - this.minX = centerX - radius; - this.maxZ = centerZ + radius; - this.minZ = centerZ - radius; - this.distance = distance; - this.checkVis = checkVis; - this.type = type; - } - *generator() { - if (this.type === NpcIteratorType_default.ZONE) { - for (const npc of World_default.getZone(this.x, this.z, this.level).getAllNpcsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error('[NpcIterator] tried to use an old iterator. Create a new iterator instead.'); - } - yield npc; - } - } else if (this.type === NpcIteratorType_default.DISTANCE) { - for (let x = this.maxX; x >= this.minX; x--) { - const zoneX = x << 3; - for (let z2 = this.maxZ; z2 >= this.minZ; z2--) { - const zoneZ = z2 << 3; - for (const npc of World_default.getZone(zoneX, zoneZ, this.level).getAllNpcsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error('[NpcIterator] tried to use an old iterator. Create a new iterator instead.'); - } - if (Position.distanceToSW({x: this.x, z: this.z}, npc) > this.distance) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { - continue; - } - yield npc; - } - } - } - } - } -} - -class LocIterator extends ScriptIterator { - level; - x; - z; - constructor(tick, level, x, z2) { - super(tick); - this.level = level; - this.x = x; - this.z = z2; - } - *generator() { - for (const loc of World_default.getZone(this.x, this.z, this.level).getAllLocsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error('[LocIterator] tried to use an old iterator. Create a new iterator instead.'); - } - yield loc; - } - } -} - -// src/lostcity/entity/Loc.ts -class Loc extends NonPathingEntity { - info; - constructor(level, x, z2, width, length, lifecycle, type, shape, angle) { - super(level, x, z2, width, length, lifecycle); - this.info = (type & 16383) | ((shape & 31) << 14) | ((angle & 3) << 19); - } - get type() { - return this.info & 16383; - } - get shape() { - return (this.info >> 14) & 31; - } - get angle() { - return (this.info >> 19) & 3; - } -} - -// src/lostcity/engine/script/handlers/LocOps.ts -var LocOps = { - [ScriptOpcode_default.LOC_ADD]: state => { - const [coord, type, angle, shape, duration] = state.popInts(5); - const position = check(coord, CoordValid); - const locType = check(type, LocTypeValid); - const locAngle = check(angle, LocAngleValid); - const locShape = check(shape, LocShapeValid); - check(duration, DurationValid); - const created = new Loc(position.level, position.x, position.z, locType.width, locType.length, EntityLifeCycle_default.DESPAWN, locType.id, locShape, locAngle); - const locs = World_default.getZone(position.x, position.z, position.level).getLocsUnsafe(Position.packZoneCoord(position.x, position.z)); - for (const loc of locs) { - if (loc !== created && loc.angle === locAngle && loc.shape === locShape) { - World_default.removeLoc(loc, duration); - break; - } - } - World_default.addLoc(created, duration); - state.activeLoc = created; - state.pointerAdd(ActiveLoc[state.intOperand]); - }, - [ScriptOpcode_default.LOC_ANGLE]: checkedHandler(ActiveLoc, state => { - state.pushInt(check(state.activeLoc.angle, LocAngleValid)); - }), - [ScriptOpcode_default.LOC_ANIM]: checkedHandler(ActiveLoc, state => { - const seqType = check(state.popInt(), SeqTypeValid); - World_default.animLoc(state.activeLoc, seqType.id); - }), - [ScriptOpcode_default.LOC_CATEGORY]: checkedHandler(ActiveLoc, state => { - state.pushInt(check(state.activeLoc.type, LocTypeValid).category); - }), - [ScriptOpcode_default.LOC_CHANGE]: checkedHandler(ActiveLoc, state => { - const [id, duration] = state.popInts(2); - const locType = check(id, LocTypeValid); - check(duration, DurationValid); - World_default.removeLoc(state.activeLoc, duration); - const {level, x, z: z2, angle, shape} = state.activeLoc; - const locs = World_default.getZone(x, z2, level).getLocsUnsafe(Position.packZoneCoord(x, z2)); - let found = null; - for (const loc of locs) { - if (loc.type === locType.id && loc.angle === angle && loc.shape === shape && loc.lifecycle === EntityLifeCycle_default.RESPAWN) { - found = loc; - World_default.addLoc(loc, 0); - break; - } - } - if (!found) { - found = new Loc(level, x, z2, locType.width, locType.length, EntityLifeCycle_default.DESPAWN, locType.id, shape, angle); - World_default.addLoc(found, duration); - } - state.activeLoc = found; - state.pointerAdd(ActiveLoc[state.intOperand]); - }), - [ScriptOpcode_default.LOC_COORD]: checkedHandler(ActiveLoc, state => { - const position = state.activeLoc; - state.pushInt(Position.packCoord(position.level, position.x, position.z)); - }), - [ScriptOpcode_default.LOC_DEL]: checkedHandler(ActiveLoc, state => { - const duration = check(state.popInt(), DurationValid); - const {level, x, z: z2, angle, shape} = state.activeLoc; - const locs = World_default.getZone(x, z2, level).getLocsUnsafe(Position.packZoneCoord(x, z2)); - for (const loc of locs) { - if (loc !== state.activeLoc && loc.angle === angle && loc.shape === shape) { - World_default.removeLoc(loc, duration); - break; - } - } - World_default.removeLoc(state.activeLoc, duration); - }), - [ScriptOpcode_default.LOC_FIND]: state => { - const [coord, locId] = state.popInts(2); - const locType = check(locId, LocTypeValid); - const position = check(coord, CoordValid); - const loc = World_default.getLoc(position.x, position.z, position.level, locType.id); - if (!loc) { - state.pushInt(0); - return; - } - state.activeLoc = loc; - state.pointerAdd(ActiveLoc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.LOC_FINDALLZONE]: state => { - const position = check(state.popInt(), CoordValid); - state.locIterator = new LocIterator(World_default.currentTick, position.level, position.x, position.z); - if (state._activeLoc) { - state._activeLoc2 = state._activeLoc; - state.pointerAdd(ScriptPointer_default.ActiveLoc2); - } - }, - [ScriptOpcode_default.LOC_FINDNEXT]: state => { - const result = state.locIterator?.next(); - if (!result || result.done) { - state.pushInt(0); - return; - } - state.activeLoc = result.value; - state.pointerAdd(ActiveLoc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.LOC_PARAM]: checkedHandler(ActiveLoc, state => { - const paramType = check(state.popInt(), ParamTypeValid); - const locType = check(state.activeLoc.type, LocTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, locType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, locType, paramType.defaultInt)); - } - }), - [ScriptOpcode_default.LOC_TYPE]: checkedHandler(ActiveLoc, state => { - state.pushInt(check(state.activeLoc.type, LocTypeValid).id); - }), - [ScriptOpcode_default.LOC_NAME]: checkedHandler(ActiveLoc, state => { - state.pushString(check(state.activeLoc.type, LocTypeValid).name ?? 'null'); - }), - [ScriptOpcode_default.LOC_SHAPE]: checkedHandler(ActiveLoc, state => { - state.pushInt(check(state.activeLoc.shape, LocShapeValid)); - }) -}; -var LocOps_default = LocOps; - -// src/lostcity/engine/script/handlers/LocConfigOps.ts -var LocConfigOps = { - [ScriptOpcode_default.LC_NAME]: state => { - const locType = check(state.popInt(), LocTypeValid); - state.pushString(locType.name ?? locType.debugname ?? 'null'); - }, - [ScriptOpcode_default.LC_PARAM]: state => { - const [locId, paramId] = state.popInts(2); - const locType = check(locId, LocTypeValid); - const paramType = check(paramId, ParamTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, locType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, locType, paramType.defaultInt)); - } - }, - [ScriptOpcode_default.LC_CATEGORY]: state => { - state.pushInt(check(state.popInt(), LocTypeValid).category); - }, - [ScriptOpcode_default.LC_DESC]: state => { - state.pushString(check(state.popInt(), LocTypeValid).desc ?? 'null'); - }, - [ScriptOpcode_default.LC_DEBUGNAME]: state => { - state.pushString(check(state.popInt(), LocTypeValid).debugname ?? 'null'); - }, - [ScriptOpcode_default.LC_WIDTH]: state => { - state.pushInt(check(state.popInt(), LocTypeValid).width); - }, - [ScriptOpcode_default.LC_LENGTH]: state => { - state.pushInt(check(state.popInt(), LocTypeValid).length); - } -}; -var LocConfigOps_default = LocConfigOps; - -// src/lostcity/engine/script/ServerTriggerType.ts -var ServerTriggerType; -(ServerTriggerType2 => { - ServerTriggerType2[(ServerTriggerType2['PROC'] = 0)] = 'PROC'; - ServerTriggerType2[(ServerTriggerType2['LABEL'] = 1)] = 'LABEL'; - ServerTriggerType2[(ServerTriggerType2['DEBUGPROC'] = 2)] = 'DEBUGPROC'; - ServerTriggerType2[(ServerTriggerType2['APNPC1'] = 3)] = 'APNPC1'; - ServerTriggerType2[(ServerTriggerType2['APNPC2'] = 4)] = 'APNPC2'; - ServerTriggerType2[(ServerTriggerType2['APNPC3'] = 5)] = 'APNPC3'; - ServerTriggerType2[(ServerTriggerType2['APNPC4'] = 6)] = 'APNPC4'; - ServerTriggerType2[(ServerTriggerType2['APNPC5'] = 7)] = 'APNPC5'; - ServerTriggerType2[(ServerTriggerType2['APNPCU'] = 8)] = 'APNPCU'; - ServerTriggerType2[(ServerTriggerType2['APNPCT'] = 9)] = 'APNPCT'; - ServerTriggerType2[(ServerTriggerType2['OPNPC1'] = 10)] = 'OPNPC1'; - ServerTriggerType2[(ServerTriggerType2['OPNPC2'] = 11)] = 'OPNPC2'; - ServerTriggerType2[(ServerTriggerType2['OPNPC3'] = 12)] = 'OPNPC3'; - ServerTriggerType2[(ServerTriggerType2['OPNPC4'] = 13)] = 'OPNPC4'; - ServerTriggerType2[(ServerTriggerType2['OPNPC5'] = 14)] = 'OPNPC5'; - ServerTriggerType2[(ServerTriggerType2['OPNPCU'] = 15)] = 'OPNPCU'; - ServerTriggerType2[(ServerTriggerType2['OPNPCT'] = 16)] = 'OPNPCT'; - ServerTriggerType2[(ServerTriggerType2['AI_APNPC1'] = 17)] = 'AI_APNPC1'; - ServerTriggerType2[(ServerTriggerType2['AI_APNPC2'] = 18)] = 'AI_APNPC2'; - ServerTriggerType2[(ServerTriggerType2['AI_APNPC3'] = 19)] = 'AI_APNPC3'; - ServerTriggerType2[(ServerTriggerType2['AI_APNPC4'] = 20)] = 'AI_APNPC4'; - ServerTriggerType2[(ServerTriggerType2['AI_APNPC5'] = 21)] = 'AI_APNPC5'; - ServerTriggerType2[(ServerTriggerType2['AI_OPNPC1'] = 24)] = 'AI_OPNPC1'; - ServerTriggerType2[(ServerTriggerType2['AI_OPNPC2'] = 25)] = 'AI_OPNPC2'; - ServerTriggerType2[(ServerTriggerType2['AI_OPNPC3'] = 26)] = 'AI_OPNPC3'; - ServerTriggerType2[(ServerTriggerType2['AI_OPNPC4'] = 27)] = 'AI_OPNPC4'; - ServerTriggerType2[(ServerTriggerType2['AI_OPNPC5'] = 28)] = 'AI_OPNPC5'; - ServerTriggerType2[(ServerTriggerType2['APOBJ1'] = 31)] = 'APOBJ1'; - ServerTriggerType2[(ServerTriggerType2['APOBJ2'] = 32)] = 'APOBJ2'; - ServerTriggerType2[(ServerTriggerType2['APOBJ3'] = 33)] = 'APOBJ3'; - ServerTriggerType2[(ServerTriggerType2['APOBJ4'] = 34)] = 'APOBJ4'; - ServerTriggerType2[(ServerTriggerType2['APOBJ5'] = 35)] = 'APOBJ5'; - ServerTriggerType2[(ServerTriggerType2['APOBJU'] = 36)] = 'APOBJU'; - ServerTriggerType2[(ServerTriggerType2['APOBJT'] = 37)] = 'APOBJT'; - ServerTriggerType2[(ServerTriggerType2['OPOBJ1'] = 38)] = 'OPOBJ1'; - ServerTriggerType2[(ServerTriggerType2['OPOBJ2'] = 39)] = 'OPOBJ2'; - ServerTriggerType2[(ServerTriggerType2['OPOBJ3'] = 40)] = 'OPOBJ3'; - ServerTriggerType2[(ServerTriggerType2['OPOBJ4'] = 41)] = 'OPOBJ4'; - ServerTriggerType2[(ServerTriggerType2['OPOBJ5'] = 42)] = 'OPOBJ5'; - ServerTriggerType2[(ServerTriggerType2['OPOBJU'] = 43)] = 'OPOBJU'; - ServerTriggerType2[(ServerTriggerType2['OPOBJT'] = 44)] = 'OPOBJT'; - ServerTriggerType2[(ServerTriggerType2['AI_APOBJ1'] = 45)] = 'AI_APOBJ1'; - ServerTriggerType2[(ServerTriggerType2['AI_APOBJ2'] = 46)] = 'AI_APOBJ2'; - ServerTriggerType2[(ServerTriggerType2['AI_APOBJ3'] = 47)] = 'AI_APOBJ3'; - ServerTriggerType2[(ServerTriggerType2['AI_APOBJ4'] = 48)] = 'AI_APOBJ4'; - ServerTriggerType2[(ServerTriggerType2['AI_APOBJ5'] = 49)] = 'AI_APOBJ5'; - ServerTriggerType2[(ServerTriggerType2['AI_OPOBJ1'] = 52)] = 'AI_OPOBJ1'; - ServerTriggerType2[(ServerTriggerType2['AI_OPOBJ2'] = 53)] = 'AI_OPOBJ2'; - ServerTriggerType2[(ServerTriggerType2['AI_OPOBJ3'] = 54)] = 'AI_OPOBJ3'; - ServerTriggerType2[(ServerTriggerType2['AI_OPOBJ4'] = 55)] = 'AI_OPOBJ4'; - ServerTriggerType2[(ServerTriggerType2['AI_OPOBJ5'] = 56)] = 'AI_OPOBJ5'; - ServerTriggerType2[(ServerTriggerType2['APLOC1'] = 59)] = 'APLOC1'; - ServerTriggerType2[(ServerTriggerType2['APLOC2'] = 60)] = 'APLOC2'; - ServerTriggerType2[(ServerTriggerType2['APLOC3'] = 61)] = 'APLOC3'; - ServerTriggerType2[(ServerTriggerType2['APLOC4'] = 62)] = 'APLOC4'; - ServerTriggerType2[(ServerTriggerType2['APLOC5'] = 63)] = 'APLOC5'; - ServerTriggerType2[(ServerTriggerType2['APLOCU'] = 64)] = 'APLOCU'; - ServerTriggerType2[(ServerTriggerType2['APLOCT'] = 65)] = 'APLOCT'; - ServerTriggerType2[(ServerTriggerType2['OPLOC1'] = 66)] = 'OPLOC1'; - ServerTriggerType2[(ServerTriggerType2['OPLOC2'] = 67)] = 'OPLOC2'; - ServerTriggerType2[(ServerTriggerType2['OPLOC3'] = 68)] = 'OPLOC3'; - ServerTriggerType2[(ServerTriggerType2['OPLOC4'] = 69)] = 'OPLOC4'; - ServerTriggerType2[(ServerTriggerType2['OPLOC5'] = 70)] = 'OPLOC5'; - ServerTriggerType2[(ServerTriggerType2['OPLOCU'] = 71)] = 'OPLOCU'; - ServerTriggerType2[(ServerTriggerType2['OPLOCT'] = 72)] = 'OPLOCT'; - ServerTriggerType2[(ServerTriggerType2['AI_APLOC1'] = 73)] = 'AI_APLOC1'; - ServerTriggerType2[(ServerTriggerType2['AI_APLOC2'] = 74)] = 'AI_APLOC2'; - ServerTriggerType2[(ServerTriggerType2['AI_APLOC3'] = 75)] = 'AI_APLOC3'; - ServerTriggerType2[(ServerTriggerType2['AI_APLOC4'] = 76)] = 'AI_APLOC4'; - ServerTriggerType2[(ServerTriggerType2['AI_APLOC5'] = 77)] = 'AI_APLOC5'; - ServerTriggerType2[(ServerTriggerType2['AI_OPLOC1'] = 80)] = 'AI_OPLOC1'; - ServerTriggerType2[(ServerTriggerType2['AI_OPLOC2'] = 81)] = 'AI_OPLOC2'; - ServerTriggerType2[(ServerTriggerType2['AI_OPLOC3'] = 82)] = 'AI_OPLOC3'; - ServerTriggerType2[(ServerTriggerType2['AI_OPLOC4'] = 83)] = 'AI_OPLOC4'; - ServerTriggerType2[(ServerTriggerType2['AI_OPLOC5'] = 84)] = 'AI_OPLOC5'; - ServerTriggerType2[(ServerTriggerType2['APPLAYER1'] = 87)] = 'APPLAYER1'; - ServerTriggerType2[(ServerTriggerType2['APPLAYER2'] = 88)] = 'APPLAYER2'; - ServerTriggerType2[(ServerTriggerType2['APPLAYER3'] = 89)] = 'APPLAYER3'; - ServerTriggerType2[(ServerTriggerType2['APPLAYER4'] = 90)] = 'APPLAYER4'; - ServerTriggerType2[(ServerTriggerType2['APPLAYER5'] = 91)] = 'APPLAYER5'; - ServerTriggerType2[(ServerTriggerType2['APPLAYERU'] = 92)] = 'APPLAYERU'; - ServerTriggerType2[(ServerTriggerType2['APPLAYERT'] = 93)] = 'APPLAYERT'; - ServerTriggerType2[(ServerTriggerType2['OPPLAYER1'] = 94)] = 'OPPLAYER1'; - ServerTriggerType2[(ServerTriggerType2['OPPLAYER2'] = 95)] = 'OPPLAYER2'; - ServerTriggerType2[(ServerTriggerType2['OPPLAYER3'] = 96)] = 'OPPLAYER3'; - ServerTriggerType2[(ServerTriggerType2['OPPLAYER4'] = 97)] = 'OPPLAYER4'; - ServerTriggerType2[(ServerTriggerType2['OPPLAYER5'] = 98)] = 'OPPLAYER5'; - ServerTriggerType2[(ServerTriggerType2['OPPLAYERU'] = 99)] = 'OPPLAYERU'; - ServerTriggerType2[(ServerTriggerType2['OPPLAYERT'] = 100)] = 'OPPLAYERT'; - ServerTriggerType2[(ServerTriggerType2['AI_APPLAYER1'] = 101)] = 'AI_APPLAYER1'; - ServerTriggerType2[(ServerTriggerType2['AI_APPLAYER2'] = 102)] = 'AI_APPLAYER2'; - ServerTriggerType2[(ServerTriggerType2['AI_APPLAYER3'] = 103)] = 'AI_APPLAYER3'; - ServerTriggerType2[(ServerTriggerType2['AI_APPLAYER4'] = 104)] = 'AI_APPLAYER4'; - ServerTriggerType2[(ServerTriggerType2['AI_APPLAYER5'] = 105)] = 'AI_APPLAYER5'; - ServerTriggerType2[(ServerTriggerType2['AI_OPPLAYER1'] = 108)] = 'AI_OPPLAYER1'; - ServerTriggerType2[(ServerTriggerType2['AI_OPPLAYER2'] = 109)] = 'AI_OPPLAYER2'; - ServerTriggerType2[(ServerTriggerType2['AI_OPPLAYER3'] = 110)] = 'AI_OPPLAYER3'; - ServerTriggerType2[(ServerTriggerType2['AI_OPPLAYER4'] = 111)] = 'AI_OPPLAYER4'; - ServerTriggerType2[(ServerTriggerType2['AI_OPPLAYER5'] = 112)] = 'AI_OPPLAYER5'; - ServerTriggerType2[(ServerTriggerType2['QUEUE'] = 116)] = 'QUEUE'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE1'] = 117)] = 'AI_QUEUE1'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE2'] = 118)] = 'AI_QUEUE2'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE3'] = 119)] = 'AI_QUEUE3'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE4'] = 120)] = 'AI_QUEUE4'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE5'] = 121)] = 'AI_QUEUE5'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE6'] = 122)] = 'AI_QUEUE6'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE7'] = 123)] = 'AI_QUEUE7'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE8'] = 124)] = 'AI_QUEUE8'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE9'] = 125)] = 'AI_QUEUE9'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE10'] = 126)] = 'AI_QUEUE10'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE11'] = 127)] = 'AI_QUEUE11'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE12'] = 128)] = 'AI_QUEUE12'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE13'] = 129)] = 'AI_QUEUE13'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE14'] = 130)] = 'AI_QUEUE14'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE15'] = 131)] = 'AI_QUEUE15'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE16'] = 132)] = 'AI_QUEUE16'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE17'] = 133)] = 'AI_QUEUE17'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE18'] = 134)] = 'AI_QUEUE18'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE19'] = 135)] = 'AI_QUEUE19'; - ServerTriggerType2[(ServerTriggerType2['AI_QUEUE20'] = 136)] = 'AI_QUEUE20'; - ServerTriggerType2[(ServerTriggerType2['SOFTTIMER'] = 137)] = 'SOFTTIMER'; - ServerTriggerType2[(ServerTriggerType2['TIMER'] = 138)] = 'TIMER'; - ServerTriggerType2[(ServerTriggerType2['AI_TIMER'] = 139)] = 'AI_TIMER'; - ServerTriggerType2[(ServerTriggerType2['OPHELD1'] = 140)] = 'OPHELD1'; - ServerTriggerType2[(ServerTriggerType2['OPHELD2'] = 141)] = 'OPHELD2'; - ServerTriggerType2[(ServerTriggerType2['OPHELD3'] = 142)] = 'OPHELD3'; - ServerTriggerType2[(ServerTriggerType2['OPHELD4'] = 143)] = 'OPHELD4'; - ServerTriggerType2[(ServerTriggerType2['OPHELD5'] = 144)] = 'OPHELD5'; - ServerTriggerType2[(ServerTriggerType2['OPHELDU'] = 145)] = 'OPHELDU'; - ServerTriggerType2[(ServerTriggerType2['OPHELDT'] = 146)] = 'OPHELDT'; - ServerTriggerType2[(ServerTriggerType2['IF_BUTTON'] = 147)] = 'IF_BUTTON'; - ServerTriggerType2[(ServerTriggerType2['INV_BUTTON1'] = 148)] = 'INV_BUTTON1'; - ServerTriggerType2[(ServerTriggerType2['INV_BUTTON2'] = 149)] = 'INV_BUTTON2'; - ServerTriggerType2[(ServerTriggerType2['INV_BUTTON3'] = 150)] = 'INV_BUTTON3'; - ServerTriggerType2[(ServerTriggerType2['INV_BUTTON4'] = 151)] = 'INV_BUTTON4'; - ServerTriggerType2[(ServerTriggerType2['INV_BUTTON5'] = 152)] = 'INV_BUTTON5'; - ServerTriggerType2[(ServerTriggerType2['INV_BUTTOND'] = 153)] = 'INV_BUTTOND'; - ServerTriggerType2[(ServerTriggerType2['IF_CLOSE'] = 154)] = 'IF_CLOSE'; - ServerTriggerType2[(ServerTriggerType2['LOGIN'] = 155)] = 'LOGIN'; - ServerTriggerType2[(ServerTriggerType2['LOGOUT'] = 156)] = 'LOGOUT'; - ServerTriggerType2[(ServerTriggerType2['TUTORIAL_CLICKSIDE'] = 157)] = 'TUTORIAL_CLICKSIDE'; - ServerTriggerType2[(ServerTriggerType2['MOVE'] = 158)] = 'MOVE'; - ServerTriggerType2[(ServerTriggerType2['WALKTRIGGER'] = 159)] = 'WALKTRIGGER'; - ServerTriggerType2[(ServerTriggerType2['AI_WALKTRIGGER'] = 160)] = 'AI_WALKTRIGGER'; - ServerTriggerType2[(ServerTriggerType2['LEVELUP'] = 161)] = 'LEVELUP'; -})((ServerTriggerType ||= {})); -(ServerTriggerType => { - function toString(trigger) { - return ServerTriggerType[trigger].toLowerCase(); - } - ServerTriggerType.toString = toString; -})((ServerTriggerType ||= {})); -var ServerTriggerType_default = ServerTriggerType; - -// src/lostcity/entity/Interaction.ts -var Interaction; -(Interaction2 => { - Interaction2[(Interaction2['SCRIPT'] = 0)] = 'SCRIPT'; - Interaction2[(Interaction2['ENGINE'] = 1)] = 'ENGINE'; -})((Interaction ||= {})); -var Interaction_default = Interaction; - -// src/lostcity/engine/script/handlers/NpcOps.ts -var NpcOps = { - [ScriptOpcode_default.NPC_FINDUID]: state => { - const npcUid = state.popInt(); - const slot = npcUid & 65535; - const expectedType = (npcUid >> 16) & 65535; - const npc = World_default.getNpc(slot); - if (!npc || npc.type !== expectedType) { - state.pushInt(0); - return; - } - state.activeNpc = npc; - state.pointerAdd(ActiveNpc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.NPC_ADD]: state => { - const [coord, id, duration] = state.popInts(3); - const position = check(coord, CoordValid); - const npcType = check(id, NpcTypeValid); - check(duration, DurationValid); - const npc = new Npc2(position.level, position.x, position.z, npcType.size, npcType.size, EntityLifeCycle_default.DESPAWN, World_default.getNextNid(), npcType.id, npcType.moverestrict, npcType.blockwalk); - World_default.addNpc(npc, duration); - state.activeNpc = npc; - state.pointerAdd(ActiveNpc[state.intOperand]); - }, - [ScriptOpcode_default.NPC_ANIM]: checkedHandler(ActiveNpc, state => { - const delay = check(state.popInt(), NumberNotNull); - const seq = state.popInt(); - state.activeNpc.playAnimation(seq, delay); - }), - [ScriptOpcode_default.NPC_BASESTAT]: checkedHandler(ActiveNpc, state => { - const stat = check(state.popInt(), NpcStatValid); - state.pushInt(state.activeNpc.baseLevels[stat]); - }), - [ScriptOpcode_default.NPC_CATEGORY]: checkedHandler(ActiveNpc, state => { - state.pushInt(check(state.activeNpc.type, NpcTypeValid).category); - }), - [ScriptOpcode_default.NPC_COORD]: checkedHandler(ActiveNpc, state => { - const position = state.activeNpc; - state.pushInt(Position.packCoord(position.level, position.x, position.z)); - }), - [ScriptOpcode_default.NPC_DEL]: checkedHandler(ActiveNpc, state => { - if (Environment_default.CLIRUNNER) { - return; - } - World_default.removeNpc(state.activeNpc, check(state.activeNpc.type, NpcTypeValid).respawnrate); - }), - [ScriptOpcode_default.NPC_DELAY]: checkedHandler(ActiveNpc, state => { - if (Environment_default.CLIRUNNER) { - return; - } - state.activeNpc.delay = state.popInt() + 1; - state.execution = ScriptState.NPC_SUSPENDED; - }), - [ScriptOpcode_default.NPC_FACESQUARE]: checkedHandler(ActiveNpc, state => { - const position = check(state.popInt(), CoordValid); - state.activeNpc.faceSquare(position.x, position.z); - }), - [ScriptOpcode_default.NPC_FINDEXACT]: state => { - const [coord, id] = state.popInts(2); - const position = check(coord, CoordValid); - const npcType = check(id, NpcTypeValid); - state.npcIterator = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, 0, 0, NpcIteratorType_default.ZONE); - for (const npc of state.npcIterator) { - if (npc.type === npcType.id && npc.x === position.x && npc.level === position.level && npc.z === position.z) { - state.activeNpc = npc; - state.pointerAdd(ActiveNpc[state.intOperand]); - state.pushInt(1); - return; - } - } - state.pushInt(0); - return; - }, - [ScriptOpcode_default.NPC_FINDHERO]: checkedHandler(ActiveNpc, state => { - const uid = state.activeNpc.findHero(); - if (uid === -1) { - state.pushInt(0); - return; - } - const player = World_default.getPlayerByUid(uid); - if (!player) { - state.pushInt(0); - return; - } - state.activePlayer = player; - state.pointerAdd(ScriptPointer_default.ActivePlayer); - state.pushInt(1); - }), - [ScriptOpcode_default.NPC_PARAM]: checkedHandler(ActiveNpc, state => { - const paramType = check(state.popInt(), ParamTypeValid); - const npcType = check(state.activeNpc.type, NpcTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, npcType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, npcType, paramType.defaultInt)); - } - }), - [ScriptOpcode_default.NPC_QUEUE]: checkedHandler(ActiveNpc, state => { - const delay = check(state.popInt(), NumberNotNull); - const arg = state.popInt(); - const queueId = check(state.popInt(), QueueValid); - const npcType = check(state.activeNpc.type, NpcTypeValid); - const script = ScriptProvider.getByTrigger(ServerTriggerType_default.AI_QUEUE1 + queueId - 1, npcType.id, npcType.category); - if (script) { - state.activeNpc.enqueueScript(script, delay, arg); - } - }), - [ScriptOpcode_default.NPC_RANGE]: checkedHandler(ActiveNpc, state => { - const position = check(state.popInt(), CoordValid); - const npc = state.activeNpc; - if (position.level !== npc.level) { - state.pushInt(-1); - } else { - state.pushInt( - Position.distanceTo(npc, { - x: position.x, - z: position.z, - width: 1, - length: 1 - }) - ); - } - }), - [ScriptOpcode_default.NPC_SAY]: checkedHandler(ActiveNpc, state => { - state.activeNpc.say(state.popString()); - }), - [ScriptOpcode_default.NPC_SETHUNT]: checkedHandler(ActiveNpc, state => { - state.activeNpc.huntrange = check(state.popInt(), NumberNotNull); - }), - [ScriptOpcode_default.NPC_SETHUNTMODE]: checkedHandler(ActiveNpc, state => { - state.activeNpc.huntMode = check(state.popInt(), HuntTypeValid).id; - }), - [ScriptOpcode_default.NPC_SETMODE]: checkedHandler(ActiveNpc, state => { - const mode = check(state.popInt(), NpcModeValid); - state.activeNpc.clearWaypoints(); - if (mode === NpcMode_default.NULL || mode === NpcMode_default.NONE || mode === NpcMode_default.WANDER || mode === NpcMode_default.PATROL) { - state.activeNpc.clearInteraction(); - state.activeNpc.targetOp = mode; - return; - } - state.activeNpc.targetOp = mode; - let target; - if (mode >= NpcMode_default.OPNPC1) { - target = state._activeNpc2; - } else if (mode >= NpcMode_default.OPOBJ1) { - target = state._activeObj; - } else if (mode >= NpcMode_default.OPLOC1) { - target = state._activeLoc; - } else { - target = state._activePlayer; - } - if (target) { - if (target instanceof Npc2 || target instanceof Obj || target instanceof Loc) { - state.activeNpc.setInteraction(Interaction_default.SCRIPT, target, mode, {type: target.type, com: -1}); - } else { - state.activeNpc.setInteraction(Interaction_default.SCRIPT, target, mode); - } - } else { - state.activeNpc.noMode(); - } - }), - [ScriptOpcode_default.NPC_STAT]: checkedHandler(ActiveNpc, state => { - const stat = check(state.popInt(), NpcStatValid); - state.pushInt(state.activeNpc.levels[stat]); - }), - [ScriptOpcode_default.NPC_STATHEAL]: checkedHandler(ActiveNpc, state => { - const [stat, constant, percent] = state.popInts(3); - check(stat, NpcStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const npc = state.activeNpc; - const base = npc.baseLevels[stat]; - const current = npc.levels[stat]; - const healed = current + (constant + (current * percent) / 100); - npc.levels[stat] = Math.min(healed, base); - if (stat === 0 && npc.levels[stat] === npc.baseLevels[stat]) { - npc.resetHeroPoints(); - } - }), - [ScriptOpcode_default.NPC_TYPE]: checkedHandler(ActiveNpc, state => { - state.pushInt(check(state.activeNpc.type, NpcTypeValid).id); - }), - [ScriptOpcode_default.NPC_DAMAGE]: checkedHandler(ActiveNpc, state => { - const amount = check(state.popInt(), NumberNotNull); - const type = check(state.popInt(), HitTypeValid); - state.activeNpc.applyDamage(amount, type); - }), - [ScriptOpcode_default.NPC_NAME]: checkedHandler(ActiveNpc, state => { - state.pushString(check(state.activeNpc.type, NpcTypeValid).name ?? 'null'); - }), - [ScriptOpcode_default.NPC_UID]: checkedHandler(ActiveNpc, state => { - state.pushInt(state.activeNpc.uid); - }), - [ScriptOpcode_default.NPC_SETTIMER]: checkedHandler(ActiveNpc, state => { - state.activeNpc.setTimer(check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.SPOTANIM_NPC]: checkedHandler(ActiveNpc, state => { - const delay = check(state.popInt(), NumberNotNull); - const height = check(state.popInt(), NumberNotNull); - const spotanimType = check(state.popInt(), SpotAnimTypeValid); - state.activeNpc.spotanim(spotanimType.id, height, delay); - }), - [ScriptOpcode_default.NPC_FIND]: state => { - const [coord, npc, distance, checkVis] = state.popInts(4); - const position = check(coord, CoordValid); - const npcType = check(npc, NpcTypeValid); - check(distance, NumberNotNull); - const huntvis = check(checkVis, HuntVisValid); - let closestNpc; - let closestDistance = distance; - const npcs = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, NpcIteratorType_default.DISTANCE); - for (const npc2 of npcs) { - if (npc2 && npc2.type === npcType.id) { - const npcDistance = Position.distanceToSW(position, npc2); - if (npcDistance <= closestDistance) { - closestNpc = npc2; - closestDistance = npcDistance; - } - } - } - if (!closestNpc) { - state.pushInt(0); - return; - } - state.activeNpc = closestNpc; - state.pointerAdd(ActiveNpc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.NPC_FINDALLANY]: state => { - const [coord, distance, checkVis] = state.popInts(3); - const position = check(coord, CoordValid); - check(distance, NumberNotNull); - const huntvis = check(checkVis, HuntVisValid); - state.npcIterator = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, NpcIteratorType_default.DISTANCE); - if (state._activeNpc) { - state._activeNpc2 = state._activeNpc; - state.pointerAdd(ScriptPointer_default.ActiveNpc2); - } - }, - [ScriptOpcode_default.NPC_FINDALLZONE]: state => { - const position = check(state.popInt(), CoordValid); - state.npcIterator = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, 0, 0, NpcIteratorType_default.ZONE); - if (state._activeNpc) { - state._activeNpc2 = state._activeNpc; - state.pointerAdd(ScriptPointer_default.ActiveNpc2); - } - }, - [ScriptOpcode_default.NPC_FINDNEXT]: state => { - const result = state.npcIterator?.next(); - if (!result || result.done) { - state.pushInt(0); - return; - } - state.activeNpc = result.value; - state.pointerAdd(ActiveNpc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.NPC_TELE]: checkedHandler(ActiveNpc, state => { - const position = check(state.popInt(), CoordValid); - state.activeNpc.teleport(position.x, position.z, position.level); - }), - [ScriptOpcode_default.NPC_WALK]: checkedHandler(ActiveNpc, state => { - const position = check(state.popInt(), CoordValid); - state.activeNpc.queueWaypoint(position.x, position.z); - }), - [ScriptOpcode_default.NPC_CHANGETYPE]: checkedHandler(ActiveNpc, state => { - state.activeNpc.changeType(check(state.popInt(), NpcTypeValid).id); - }), - [ScriptOpcode_default.NPC_GETMODE]: checkedHandler(ActiveNpc, state => { - state.pushInt(state.activeNpc.targetOp); - }), - [ScriptOpcode_default.NPC_HEROPOINTS]: checkedHandler([ScriptPointer_default.ActivePlayer, ...ActiveNpc], state => { - state.activeNpc.addHero(state.activePlayer.uid, check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.NPC_WALKTRIGGER]: checkedHandler(ActiveNpc, state => { - const [queueId, arg] = state.popInts(2); - check(queueId, QueueValid); - state.activeNpc.walktrigger = queueId - 1; - state.activeNpc.walktriggerArg = arg; - }), - [ScriptOpcode_default.NPC_STATADD]: checkedHandler(ActiveNpc, state => { - const [stat, constant, percent] = state.popInts(3); - check(stat, NpcStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const npc = state.activeNpc; - const current = npc.levels[stat]; - const added = current + (constant + (current * percent) / 100); - npc.levels[stat] = Math.min(added, 255); - if (stat === 0 && npc.levels[stat] >= npc.baseLevels[stat]) { - npc.resetHeroPoints(); - } - }), - [ScriptOpcode_default.NPC_STATSUB]: checkedHandler(ActiveNpc, state => { - const [stat, constant, percent] = state.popInts(3); - check(stat, NpcStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const npc = state.activeNpc; - const current = npc.levels[stat]; - const subbed = current - (constant + (current * percent) / 100); - npc.levels[stat] = Math.max(subbed, 0); - }), - [ScriptOpcode_default.NPC_ATTACKRANGE]: checkedHandler(ActiveNpc, state => { - state.pushInt(check(state.activeNpc.type, NpcTypeValid).attackrange); - }) -}; -var NpcOps_default = NpcOps; - -// src/lostcity/engine/script/handlers/NpcConfigOps.ts -var NpcConfigOps = { - [ScriptOpcode_default.NC_NAME]: state => { - const npcType = check(state.popInt(), NpcTypeValid); - state.pushString(npcType.name ?? npcType.debugname ?? 'null'); - }, - [ScriptOpcode_default.NC_PARAM]: state => { - const [npcId, paramId] = state.popInts(2); - const npcType = check(npcId, NpcTypeValid); - const paramType = check(paramId, ParamTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramId, npcType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramId, npcType, paramType.defaultInt)); - } - }, - [ScriptOpcode_default.NC_CATEGORY]: state => { - state.pushInt(check(state.popInt(), NpcTypeValid).category); - }, - [ScriptOpcode_default.NC_DESC]: state => { - state.pushString(check(state.popInt(), NpcTypeValid).desc ?? 'null'); - }, - [ScriptOpcode_default.NC_DEBUGNAME]: state => { - state.pushString(check(state.popInt(), NpcTypeValid).debugname ?? 'null'); - }, - [ScriptOpcode_default.NC_OP]: state => { - const [npcId, op] = state.popInts(2); - const npcType = check(npcId, NpcTypeValid); - check(op, NumberNotNull); - if (!npcType.op) { - state.pushString(''); - return; - } - state.pushString(npcType.op[op - 1] ?? ''); - } -}; -var NpcConfigOps_default = NpcConfigOps; - -// src/jagex2/Trig.ts -class Trig { - static _sin = new Int32Array(16384); - static _cos = new Int32Array(16384); - static { - const size = 0.0003834951969714103; - for (let index = 0; index < 16384; index++) { - this._sin[index] = (Math.sin(index * size) * 16384) | 0; - this._cos[index] = (Math.cos(index * size) * 16384) | 0; - } - } - static radians(x) { - return ((x & 16383) / 16384) * 6.283185307179586; - } - static atan2(y2, x) { - return (Math.round(Math.atan2(y2, x) * 2607.5945876176133) & 16383) | 0; - } - static sin(x) { - return this._sin[x & 16383]; - } - static cos(x) { - return this._cos[x & 16383]; - } -} - -// src/lostcity/engine/script/handlers/NumberOps.ts -var NumberOps = { - [ScriptOpcode_default.ADD]: state => { - const b2 = state.popInt(); - const a = state.popInt(); - state.pushInt(a + b2); - }, - [ScriptOpcode_default.SUB]: state => { - const b2 = state.popInt(); - const a = state.popInt(); - state.pushInt(a - b2); - }, - [ScriptOpcode_default.MULTIPLY]: state => { - const b2 = state.popInt(); - const a = state.popInt(); - state.pushInt(a * b2); - }, - [ScriptOpcode_default.DIVIDE]: state => { - const b2 = state.popInt(); - const a = state.popInt(); - state.pushInt(a / b2); - }, - [ScriptOpcode_default.RANDOM]: state => { - const a = state.popInt(); - state.pushInt(Math.random() * a); - }, - [ScriptOpcode_default.RANDOMINC]: state => { - const a = state.popInt(); - state.pushInt(Math.random() * (a + 1)); - }, - [ScriptOpcode_default.INTERPOLATE]: state => { - const [y0, y1, x0, x1, x] = state.popInts(5); - const lerp = Math.floor((y1 - y0) / (x1 - x0)) * (x - x0) + y0; - state.pushInt(lerp); - }, - [ScriptOpcode_default.ADDPERCENT]: state => { - const [num, percent] = state.popInts(2); - state.pushInt(((num * percent) / 100 + num) | 0); - }, - [ScriptOpcode_default.SETBIT]: state => { - const [value, bit] = state.popInts(2); - state.pushInt(value | (1 << bit)); - }, - [ScriptOpcode_default.CLEARBIT]: state => { - const [value, bit] = state.popInts(2); - state.pushInt(value & ~(1 << bit)); - }, - [ScriptOpcode_default.TESTBIT]: state => { - const [value, bit] = state.popInts(2); - state.pushInt(value & (1 << bit) ? 1 : 0); - }, - [ScriptOpcode_default.MODULO]: state => { - const [n1, n2] = state.popInts(2); - state.pushInt(n1 % n2); - }, - [ScriptOpcode_default.POW]: state => { - const [base, exponent] = state.popInts(2); - state.pushInt(Math.pow(base, exponent)); - }, - [ScriptOpcode_default.INVPOW]: state => { - const [n1, n2] = state.popInts(2); - if (n1 === 0 || n2 === 0) { - state.pushInt(0); - } else { - switch (n2) { - case 1: - state.pushInt(n1); - return; - case 2: - state.pushInt(Math.sqrt(n1)); - return; - case 3: - state.pushInt(Math.cbrt(n1)); - return; - case 4: - state.pushInt(Math.sqrt(Math.sqrt(n1))); - return; - default: - state.pushInt(Math.pow(n1, 1 / n2)); - return; - } - } - }, - [ScriptOpcode_default.AND]: state => { - const [n1, n2] = state.popInts(2); - state.pushInt(n1 & n2); - }, - [ScriptOpcode_default.OR]: state => { - const [n1, n2] = state.popInts(2); - state.pushInt(n1 | n2); - }, - [ScriptOpcode_default.MIN]: state => { - const [a, b2] = state.popInts(2); - state.pushInt(Math.min(a, b2)); - }, - [ScriptOpcode_default.MAX]: state => { - const [a, b2] = state.popInts(2); - state.pushInt(Math.max(a, b2)); - }, - [ScriptOpcode_default.SCALE]: state => { - const [a, b2, c] = state.popInts(3); - state.pushInt((a * c) / b2); - }, - [ScriptOpcode_default.BITCOUNT]: state => { - state.pushInt(bitcount(state.popInt())); - }, - [ScriptOpcode_default.TOGGLEBIT]: state => { - const [value, bit] = state.popInts(2); - state.pushInt(value ^ (1 << bit)); - }, - [ScriptOpcode_default.SETBIT_RANGE]: state => { - const [num, startBit, endBit] = state.popInts(3); - state.pushInt(setBitRange(num, startBit, endBit)); - }, - [ScriptOpcode_default.CLEARBIT_RANGE]: state => { - const [num, startBit, endBit] = state.popInts(3); - state.pushInt(clearBitRange(num, startBit, endBit)); - }, - [ScriptOpcode_default.GETBIT_RANGE]: state => { - const [num, startBit, endBit] = state.popInts(3); - const a = 31 - endBit; - state.pushInt((num << a) >>> (startBit + a)); - }, - [ScriptOpcode_default.SETBIT_RANGE_TOINT]: state => { - const [num, value, startBit, endBit] = state.popInts(4); - const clearedBitRange = clearBitRange(num, startBit, endBit); - const maxValue = MASK[endBit - startBit + 1]; - let assignValue = value; - if (value > maxValue) { - assignValue = maxValue; - } - state.pushInt(clearedBitRange | (assignValue << startBit)); - }, - [ScriptOpcode_default.SIN_DEG]: state => { - state.pushInt(Trig.sin(state.popInt())); - }, - [ScriptOpcode_default.COS_DEG]: state => { - state.pushInt(Trig.cos(state.popInt())); - }, - [ScriptOpcode_default.ATAN2_DEG]: state => { - state.pushInt(Trig.atan2(state.popInt(), state.popInt())); - }, - [ScriptOpcode_default.ABS]: state => { - state.pushInt(Math.abs(state.popInt())); - } -}; -var NumberOps_default = NumberOps; - -// src/lostcity/engine/script/handlers/ObjOps.ts -var ObjOps = { - [ScriptOpcode_default.OBJ_ADD]: state => { - const [coord, objId, count, duration] = state.popInts(4); - if (objId === -1 || count === -1) { - return; - } - const objType = check(objId, ObjTypeValid); - check(duration, DurationValid); - const position = check(coord, CoordValid); - check(count, ObjStackValid); - if (objType.dummyitem !== 0) { - throw new Error(`attempted to add dummy item: ${objType.debugname}`); - } - const obj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objId, count); - World_default.addObj(obj, state.activePlayer.pid, duration); - state.activeObj = obj; - state.pointerAdd(ActiveObj[state.intOperand]); - if (Environment_default.CLIRUNNER) { - state.activePlayer.invAdd(InvType.getByName('bank').id, objId, count); - } - }, - [ScriptOpcode_default.OBJ_ADDALL]: state => { - const [coord, objId, count, duration] = state.popInts(4); - if (objId === -1 || count === -1) { - return; - } - const objType = check(objId, ObjTypeValid); - check(duration, DurationValid); - const position = check(coord, CoordValid); - check(count, ObjStackValid); - if (objType.dummyitem !== 0) { - throw new Error(`attempted to add dummy item: ${objType.debugname}`); - } - const obj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objId, count); - World_default.addObj(obj, -1, duration); - state.activeObj = obj; - state.pointerAdd(ActiveObj[state.intOperand]); - }, - [ScriptOpcode_default.OBJ_PARAM]: state => { - const paramType = check(state.popInt(), ParamTypeValid); - const objType = check(state.activeObj.type, ObjTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, objType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, objType, paramType.defaultInt)); - } - }, - [ScriptOpcode_default.OBJ_NAME]: state => { - const objType = check(state.activeObj.type, ObjTypeValid); - state.pushString(objType.name ?? objType.debugname ?? 'null'); - }, - [ScriptOpcode_default.OBJ_DEL]: state => { - const duration = ObjType.get(state.activeObj.type).respawnrate; - if (state.pointerGet(ActivePlayer[state.intOperand])) { - World_default.removeObj(state.activeObj, duration); - } else { - World_default.removeObj(state.activeObj, duration); - } - }, - [ScriptOpcode_default.OBJ_COUNT]: state => { - state.pushInt(check(state.activeObj.count, ObjStackValid)); - }, - [ScriptOpcode_default.OBJ_TYPE]: state => { - state.pushInt(check(state.activeObj.type, ObjTypeValid).id); - }, - [ScriptOpcode_default.OBJ_TAKEITEM]: state => { - const invType = check(state.popInt(), InvTypeValid); - const obj = state.activeObj; - const objType = ObjType.get(obj.type); - const zone = World_default.getZone(obj.x, obj.z, obj.level); - for (const o of zone.getObjsSafe(Position.packZoneCoord(obj.x, obj.z))) { - if (o.type !== obj.type || o.count !== obj.count) { - continue; - } - if (o.receiverId !== -1 && o.receiverId !== state.activePlayer.pid) { - continue; - } - state.activePlayer.playerLog('Picked up item', objType.debugname); - state.activePlayer.invAdd(invType.id, obj.type, obj.count); - if (obj.lifecycle === EntityLifeCycle_default.RESPAWN) { - World_default.removeObj(obj, objType.respawnrate); - break; - } else if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - World_default.removeObj(obj, 0); - break; - } - } - }, - [ScriptOpcode_default.OBJ_COORD]: state => { - const position = state.activeObj; - state.pushInt(Position.packCoord(position.level, position.x, position.z)); - } -}; -var ObjOps_default = ObjOps; - -// src/lostcity/engine/script/handlers/ObjConfigOps.ts -var ObjConfigOps = { - [ScriptOpcode_default.OC_NAME]: state => { - const objType = check(state.popInt(), ObjTypeValid); - state.pushString(objType.name ?? objType.debugname ?? 'null'); - }, - [ScriptOpcode_default.OC_PARAM]: state => { - const [objId, paramId] = state.popInts(2); - const objType = check(objId, ObjTypeValid); - const paramType = check(paramId, ParamTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, objType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, objType, paramType.defaultInt)); - } - }, - [ScriptOpcode_default.OC_CATEGORY]: state => { - state.pushInt(check(state.popInt(), ObjTypeValid).category); - }, - [ScriptOpcode_default.OC_DESC]: state => { - state.pushString(check(state.popInt(), ObjTypeValid).desc ?? 'null'); - }, - [ScriptOpcode_default.OC_MEMBERS]: state => { - state.pushInt(check(state.popInt(), ObjTypeValid).members ? 1 : 0); - }, - [ScriptOpcode_default.OC_WEIGHT]: state => { - state.pushInt(check(state.popInt(), ObjTypeValid).weight); - }, - [ScriptOpcode_default.OC_WEARPOS]: state => { - state.pushInt(check(state.popInt(), ObjTypeValid).wearpos); - }, - [ScriptOpcode_default.OC_WEARPOS2]: state => { - state.pushInt(check(state.popInt(), ObjTypeValid).wearpos2); - }, - [ScriptOpcode_default.OC_WEARPOS3]: state => { - state.pushInt(check(state.popInt(), ObjTypeValid).wearpos3); - }, - [ScriptOpcode_default.OC_COST]: state => { - state.pushInt(check(state.popInt(), ObjTypeValid).cost); - }, - [ScriptOpcode_default.OC_TRADEABLE]: state => { - state.pushInt(check(state.popInt(), ObjTypeValid).tradeable ? 1 : 0); - }, - [ScriptOpcode_default.OC_DEBUGNAME]: state => { - state.pushString(check(state.popInt(), ObjTypeValid).debugname ?? 'null'); - }, - [ScriptOpcode_default.OC_CERT]: state => { - const objType = check(state.popInt(), ObjTypeValid); - if (objType.certtemplate == -1 && objType.certlink >= 0) { - state.pushInt(objType.certlink); - } else { - state.pushInt(objType.id); - } - }, - [ScriptOpcode_default.OC_UNCERT]: state => { - const objType = check(state.popInt(), ObjTypeValid); - if (objType.certtemplate >= 0 && objType.certlink >= 0) { - state.pushInt(objType.certlink); - } else { - state.pushInt(objType.id); - } - }, - [ScriptOpcode_default.OC_STACKABLE]: state => { - state.pushInt(check(state.popInt(), ObjTypeValid).stackable ? 1 : 0); - } -}; -var ObjConfigOps_default = ObjConfigOps; - -// src/lostcity/entity/EntityQueueRequest.ts -class EntityQueueRequest extends Linkable { - type; - script; - args; - delay; - lastInt = 0; - constructor(type, script, args, delay) { - super(); - this.type = type; - this.script = script; - this.args = args; - this.delay = delay; - } -} - -class EntityQueueState extends Linkable { - script; - delay; - constructor(script, delay) { - super(); - this.script = script; - this.delay = delay; - } -} - -// src/lostcity/network/225/outgoing/prot/ServerProt.ts -class ServerProt { - id; - length; - static all = []; - static byId = []; - static IF_OPENCHATMODAL = new ServerProt(14, 2); - static IF_OPENMAINSIDEMODAL = new ServerProt(28, 4); - static IF_CLOSE = new ServerProt(129, 0); - static IF_OPENSIDEOVERLAY = new ServerProt(167, 3); - static IF_OPENMAINMODAL = new ServerProt(168, 2); - static IF_OPENSIDEMODAL = new ServerProt(195, 2); - static IF_SETCOLOUR = new ServerProt(2, 4); - static IF_SETHIDE = new ServerProt(26, 3); - static IF_SETOBJECT = new ServerProt(46, 6); - static IF_SHOWSIDE = new ServerProt(84, 1); - static IF_SETMODEL = new ServerProt(87, 4); - static IF_SETRECOL = new ServerProt(103, 6); - static IF_SETANIM = new ServerProt(146, 4); - static IF_SETPLAYERHEAD = new ServerProt(197, 2); - static IF_SETTEXT = new ServerProt(201, -2); - static IF_SETNPCHEAD = new ServerProt(204, 4); - static IF_SETPOSITION = new ServerProt(209, 6); - static TUTORIAL_FLASHSIDE = new ServerProt(126, 1); - static TUTORIAL_OPENCHAT = new ServerProt(185, 2); - static UPDATE_INV_STOP_TRANSMIT = new ServerProt(15, 2); - static UPDATE_INV_FULL = new ServerProt(98, -2); - static UPDATE_INV_PARTIAL = new ServerProt(213, -2); - static CAM_LOOKAT = new ServerProt(74, 6); - static CAM_SHAKE = new ServerProt(13, 4); - static CAM_MOVETO = new ServerProt(3, 6); - static CAM_RESET = new ServerProt(239, 0); - static NPC_INFO = new ServerProt(1, -2); - static PLAYER_INFO = new ServerProt(184, -2); - static FINISH_TRACKING = new ServerProt(133, 0); - static ENABLE_TRACKING = new ServerProt(226, 0); - static MESSAGE_GAME = new ServerProt(4, -1); - static UPDATE_IGNORELIST = new ServerProt(21, -2); - static CHAT_FILTER_SETTINGS = new ServerProt(32, 3); - static MESSAGE_PRIVATE = new ServerProt(41, -1); - static UPDATE_FRIENDLIST = new ServerProt(152, 9); - static UNSET_MAP_FLAG = new ServerProt(19, 0); - static UPDATE_RUNWEIGHT = new ServerProt(22, 2); - static HINT_ARROW = new ServerProt(25, 6); - static UPDATE_REBOOT_TIMER = new ServerProt(43, 2); - static UPDATE_STAT = new ServerProt(44, 6); - static UPDATE_RUNENERGY = new ServerProt(68, 1); - static RESET_ANIMS = new ServerProt(136, 0); - static UPDATE_UID192 = new ServerProt(139, 2); - static LAST_LOGIN_INFO = new ServerProt(140, 9); - static LOGOUT = new ServerProt(142, 0); - static P_COUNTDIALOG = new ServerProt(243, 0); - static SET_MULTIWAY = new ServerProt(254, 1); - static DATA_LOC_DONE = new ServerProt(20, 2); - static DATA_LAND_DONE = new ServerProt(80, 2); - static DATA_LAND = new ServerProt(132, -2); - static DATA_LOC = new ServerProt(220, -2); - static REBUILD_NORMAL = new ServerProt(237, -2); - static VARP_SMALL = new ServerProt(150, 3); - static VARP_LARGE = new ServerProt(175, 6); - static RESET_CLIENT_VARCACHE = new ServerProt(193, 0); - static SYNTH_SOUND = new ServerProt(12, 5); - static MIDI_SONG = new ServerProt(54, -1); - static MIDI_JINGLE = new ServerProt(212, -2); - static UPDATE_ZONE_PARTIAL_FOLLOWS = new ServerProt(7, 2); - static UPDATE_ZONE_FULL_FOLLOWS = new ServerProt(135, 2); - static UPDATE_ZONE_PARTIAL_ENCLOSED = new ServerProt(162, -2); - constructor(id, length) { - this.id = id; - this.length = length; - ServerProt.all.push(this); - ServerProt.byId[id] = this; - } -} - -// src/lostcity/entity/MoveSpeed.ts -var MoveSpeed; -(MoveSpeed2 => { - MoveSpeed2[(MoveSpeed2['STATIONARY'] = 0)] = 'STATIONARY'; - MoveSpeed2[(MoveSpeed2['CRAWL'] = 1)] = 'CRAWL'; - MoveSpeed2[(MoveSpeed2['WALK'] = 2)] = 'WALK'; - MoveSpeed2[(MoveSpeed2['RUN'] = 3)] = 'RUN'; - MoveSpeed2[(MoveSpeed2['INSTANT'] = 4)] = 'INSTANT'; -})((MoveSpeed ||= {})); -var MoveSpeed_default = MoveSpeed; - -// src/lostcity/entity/MoveStrategy.ts -var MoveStrategy; -(MoveStrategy2 => { - MoveStrategy2[(MoveStrategy2['SMART'] = 0)] = 'SMART'; - MoveStrategy2[(MoveStrategy2['NAIVE'] = 1)] = 'NAIVE'; - MoveStrategy2[(MoveStrategy2['FLY'] = 2)] = 'FLY'; -})((MoveStrategy ||= {})); -var MoveStrategy_default = MoveStrategy; - -// src/lostcity/entity/PathingEntity.ts -class PathingEntity extends Entity { - moveRestrict; - blockWalk; - moveStrategy; - coordmask; - entitymask; - moveSpeed = MoveSpeed_default.INSTANT; - walkDir = -1; - runDir = -1; - waypointIndex = -1; - waypoints = new Int32Array(25); - lastX = -1; - lastZ = -1; - tele = false; - jump = false; - lastStepX = -1; - lastStepZ = -1; - stepsTaken = 0; - lastInt = -1; - lastCrawl = false; - walktrigger = -1; - walktriggerArg = 0; - orientation = Direction.SOUTH; - interacted = false; - repathed = false; - target = null; - targetOp = -1; - targetSubject = {type: -1, com: -1}; - targetX = -1; - targetZ = -1; - apRange = 10; - apRangeCalled = false; - alreadyFacedCoord = false; - alreadyFacedEntity = false; - mask = 0; - exactStartX = -1; - exactStartZ = -1; - exactEndX = -1; - exactEndZ = -1; - exactMoveStart = -1; - exactMoveEnd = -1; - exactMoveDirection = -1; - faceX = -1; - faceZ = -1; - faceEntity = -1; - damageTaken = -1; - damageType = -1; - animId = -1; - animDelay = -1; - chat = null; - graphicId = -1; - graphicHeight = -1; - graphicDelay = -1; - constructor(level, x, z2, width, length, lifecycle, moveRestrict, blockWalk, moveStrategy, coordmask, entitymask) { - super(level, x, z2, width, length, lifecycle); - this.moveRestrict = moveRestrict; - this.blockWalk = blockWalk; - this.moveStrategy = moveStrategy; - this.coordmask = coordmask; - this.entitymask = entitymask; - this.lastStepX = x - 1; - this.lastStepZ = z2; - } - processMovement() { - if (!this.hasWaypoints() || this.moveSpeed === MoveSpeed_default.STATIONARY || this.moveSpeed === MoveSpeed_default.INSTANT) { - return false; - } - if (this.moveSpeed === MoveSpeed_default.CRAWL) { - this.lastCrawl = !this.lastCrawl; - if (this.lastCrawl && this.walkDir === -1) { - this.walkDir = this.validateAndAdvanceStep(); - } - return true; - } - if (this.walkDir === -1) { - this.walkDir = this.validateAndAdvanceStep(); - if (this.moveSpeed === MoveSpeed_default.RUN && this.walkDir !== -1 && this.runDir === -1) { - this.runDir = this.validateAndAdvanceStep(); - } - } - return true; - } - refreshZonePresence(previousX, previousZ, previousLevel) { - if (this.x != previousX || this.z !== previousZ || this.level !== previousLevel) { - switch (this.blockWalk) { - case BlockWalk_default.NPC: - World_default.gameMap.changeNpcCollision(this.width, previousX, previousZ, previousLevel, false); - World_default.gameMap.changeNpcCollision(this.width, this.x, this.z, this.level, true); - break; - case BlockWalk_default.ALL: - World_default.gameMap.changeNpcCollision(this.width, previousX, previousZ, previousLevel, false); - World_default.gameMap.changeNpcCollision(this.width, this.x, this.z, this.level, true); - World_default.gameMap.changePlayerCollision(this.width, previousX, previousZ, previousLevel, false); - World_default.gameMap.changePlayerCollision(this.width, this.x, this.z, this.level, true); - break; - } - this.lastStepX = previousX; - this.lastStepZ = previousZ; - } - if (Position.zone(previousX) !== Position.zone(this.x) || Position.zone(previousZ) !== Position.zone(this.z) || previousLevel != this.level) { - World_default.getZone(previousX, previousZ, previousLevel).leave(this); - World_default.getZone(this.x, this.z, this.level).enter(this); - } - } - validateAndAdvanceStep() { - const dir = this.takeStep(); - if (dir === null) { - return -1; - } - if (dir === -1) { - this.waypointIndex--; - if (this.waypointIndex != -1) { - return this.validateAndAdvanceStep(); - } - return -1; - } - const previousX = this.x; - const previousZ = this.z; - this.x = Position.moveX(this.x, dir); - this.z = Position.moveZ(this.z, dir); - this.orientation = dir; - this.stepsTaken++; - this.refreshZonePresence(previousX, previousZ, this.level); - return dir; - } - queueWaypoint(x, z2) { - this.waypoints[0] = Position.packCoord(0, x, z2); - this.waypointIndex = 0; - } - queueWaypoints(waypoints) { - let index = -1; - for (let input = waypoints.length - 1, output = 0; input >= 0 && output < this.waypoints.length; input--, output++) { - this.waypoints[output] = waypoints[input]; - index++; - } - this.waypointIndex = index; - } - clearWaypoints() { - this.waypointIndex = -1; - } - teleJump(x, z2, level) { - this.teleport(x, z2, level); - this.jump = true; - } - teleport(x, z2, level) { - if (isNaN(level)) { - level = 0; - } - level = Math.max(0, Math.min(level, 3)); - const previousX = this.x; - const previousZ = this.z; - const previousLevel = this.level; - this.x = x; - this.z = z2; - this.level = level; - this.refreshZonePresence(previousX, previousZ, previousLevel); - this.lastStepX = this.x - 1; - this.lastStepZ = this.z; - this.moveSpeed = MoveSpeed_default.INSTANT; - if (previousLevel != level) { - this.jump = true; - } - } - validateDistanceWalked() { - const distanceCheck = - Position.distanceTo(this, { - x: this.lastX, - z: this.lastZ, - width: this.width, - length: this.length - }) > 2; - if (distanceCheck) { - this.jump = true; - } - } - convertMovementDir() { - let walkDir = this.walkDir; - let runDir = this.runDir; - let tele = this.moveSpeed === MoveSpeed_default.INSTANT; - const distanceMoved = Position.distanceTo(this, { - x: this.lastX, - z: this.lastZ, - width: this.width, - length: this.length - }); - if (tele && !this.jump && distanceMoved <= 2) { - if (distanceMoved === 2) { - const firstX = ((this.x + this.lastX) / 2) | 0; - const firstZ = ((this.z + this.lastZ) / 2) | 0; - walkDir = Position.face(this.lastX, this.lastZ, firstX, firstZ); - runDir = Position.face(firstX, firstZ, this.x, this.z); - } else { - walkDir = Position.face(this.lastX, this.lastZ, this.x, this.z); - runDir = -1; - } - tele = false; - } - this.walkDir = walkDir; - this.runDir = runDir; - this.tele = tele; - } - hasWaypoints() { - return this.waypointIndex !== -1; - } - isLastOrNoWaypoint() { - return this.waypointIndex <= 0; - } - inOperableDistance(target) { - if (target.level !== this.level) { - return false; - } - if (target instanceof PathingEntity) { - return reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, target.orientation, -2); - } else if (target instanceof Loc) { - const forceapproach = LocType.get(target.type).forceapproach; - return reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, target.angle, target.shape, forceapproach); - } - const reachedAdjacent = reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, 0, -2); - if (isFlagged(target.x, target.z, target.level, CollisionFlag.WALK_BLOCKED)) { - return reachedAdjacent; - } - if (!this.hasWaypoints() && reachedAdjacent) { - return true; - } - return reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, 0, -1); - } - inApproachDistance(range, target) { - if (target.level !== this.level) { - return false; - } - if (target instanceof PathingEntity && Position.intersects(this.x, this.z, this.width, this.length, target.x, target.z, target.width, target.length)) { - return false; - } - return Position.distanceTo(this, target) <= range && hasLineOfSight(this.level, this.x, this.z, target.x, target.z, this.width, this.length, target.width, target.length, CollisionFlag.PLAYER); - } - pathToMoveClick(input, needsfinding) { - if (this.moveStrategy === MoveStrategy_default.SMART) { - if (needsfinding) { - const {x, z: z2} = Position.unpackCoord(input[0]); - this.queueWaypoints(findPath(this.level, this.x, this.z, x, z2)); - } else { - this.queueWaypoints(input); - } - } else { - const {x, z: z2} = Position.unpackCoord(input[input.length - 1]); - this.queueWaypoint(x, z2); - } - } - pathToPathingTarget() { - if (!this.target || !(this.target instanceof PathingEntity)) { - return; - } - if (!this.isLastOrNoWaypoint()) { - return; - } - if (this.targetOp === ServerTriggerType_default.APPLAYER3 || this.targetOp === ServerTriggerType_default.OPPLAYER3) { - this.queueWaypoint(this.target.lastStepX, this.target.lastStepZ); - return; - } - this.pathToTarget(); - } - pathToTarget() { - if (!this.target) { - return; - } - this.targetX = this.target.x; - this.targetZ = this.target.z; - if (this.moveStrategy === MoveStrategy_default.SMART) { - if (this.target instanceof PathingEntity) { - this.queueWaypoints(findPath(this.level, this.x, this.z, this.target.x, this.target.z, this.width, this.target.width, this.target.length, this.target.orientation, -2)); - } else if (this.target instanceof Loc) { - const forceapproach = LocType.get(this.target.type).forceapproach; - this.queueWaypoints(findPath(this.level, this.x, this.z, this.target.x, this.target.z, this.width, this.target.width, this.target.length, this.target.angle, this.target.shape, true, forceapproach)); - } else { - this.queueWaypoints(findPath(this.level, this.x, this.z, this.target.x, this.target.z)); - } - } else if (this.moveStrategy === MoveStrategy_default.NAIVE) { - const collisionStrategy = this.getCollisionStrategy(); - if (collisionStrategy === null) { - return; - } - const extraFlag = this.blockWalkFlag(); - if (extraFlag === CollisionFlag.NULL) { - return; - } - if (this.target instanceof PathingEntity) { - this.queueWaypoints(findNaivePath(this.level, this.x, this.z, this.target.x, this.target.z, this.width, this.length, this.target.width, this.target.length, extraFlag, collisionStrategy)); - } else { - this.queueWaypoint(this.target.x, this.target.z); - } - } else { - const collisionStrategy = this.getCollisionStrategy(); - if (collisionStrategy === null) { - return; - } - const extraFlag = this.blockWalkFlag(); - if (extraFlag === CollisionFlag.NULL) { - return; - } - this.queueWaypoint(this.target.x, this.target.z); - } - } - setInteraction(interaction, target, op, subject) { - this.target = target; - this.targetOp = op; - this.targetSubject = subject ?? {type: -1, com: -1}; - this.targetX = target.x; - this.targetZ = target.z; - this.apRange = 10; - this.apRangeCalled = false; - if (target instanceof Player2) { - const pid = target.pid + 32768; - if (this.faceEntity !== pid) { - this.faceEntity = pid; - this.mask |= this.entitymask; - } - } else if (target instanceof Npc2) { - const nid = target.nid; - if (this.faceEntity !== nid) { - this.faceEntity = nid; - this.mask |= this.entitymask; - } - } else { - const faceX = target.x * 2 + target.width; - const faceZ = target.z * 2 + target.length; - if (this.faceX !== faceX || this.faceZ !== faceZ) { - this.faceX = faceX; - this.faceZ = faceZ; - this.mask |= this.coordmask; - } - } - if (interaction === Interaction_default.SCRIPT) { - this.pathToTarget(); - } - } - clearInteraction() { - this.target = null; - this.targetOp = -1; - this.targetSubject = {type: -1, com: -1}; - this.targetX = -1; - this.targetZ = -1; - this.apRange = 10; - this.apRangeCalled = false; - this.alreadyFacedCoord = true; - this.alreadyFacedEntity = true; - } - getCollisionStrategy() { - if (this.moveRestrict === MoveRestrict_default.NORMAL) { - return CollisionType.NORMAL; - } else if (this.moveRestrict === MoveRestrict_default.BLOCKED) { - return CollisionType.BLOCKED; - } else if (this.moveRestrict === MoveRestrict_default.BLOCKED_NORMAL) { - return CollisionType.LINE_OF_SIGHT; - } else if (this.moveRestrict === MoveRestrict_default.INDOORS) { - return CollisionType.INDOORS; - } else if (this.moveRestrict === MoveRestrict_default.OUTDOORS) { - return CollisionType.OUTDOORS; - } else if (this.moveRestrict === MoveRestrict_default.NOMOVE) { - return null; - } else if (this.moveRestrict === MoveRestrict_default.PASSTHRU) { - return CollisionType.NORMAL; - } - return null; - } - resetPathingEntity() { - this.moveSpeed = this.defaultMoveSpeed(); - this.walkDir = -1; - this.runDir = -1; - this.jump = false; - this.tele = false; - this.lastX = this.x; - this.lastZ = this.z; - this.stepsTaken = 0; - this.interacted = false; - this.apRangeCalled = false; - this.mask = 0; - this.exactStartX = -1; - this.exactStartZ = -1; - this.exactEndX = -1; - this.exactEndZ = -1; - this.exactMoveStart = -1; - this.exactMoveEnd = -1; - this.exactMoveDirection = -1; - this.animId = -1; - this.animDelay = -1; - this.animId = -1; - this.animDelay = -1; - this.chat = null; - this.damageTaken = -1; - this.damageType = -1; - this.graphicId = -1; - this.graphicHeight = -1; - this.graphicDelay = -1; - if (this.faceX !== -1) { - this.orientation = Position.face(this.x, this.z, this.faceX, this.faceZ); - } else if (this.target) { - this.orientation = Position.face(this.x, this.z, this.target.x, this.target.z); - } - if (this.alreadyFacedCoord && this.faceX !== -1 && !this.hasWaypoints()) { - this.faceX = -1; - this.faceZ = -1; - this.alreadyFacedCoord = false; - } else if (this.alreadyFacedEntity && !this.target && this.faceEntity !== -1) { - this.mask |= this.entitymask; - this.faceEntity = -1; - this.alreadyFacedEntity = false; - } - } - takeStep() { - if (this.waypointIndex === -1) { - return null; - } - const srcX = this.x; - const srcZ = this.z; - const {x, z: z2} = Position.unpackCoord(this.waypoints[this.waypointIndex]); - const dir = Position.face(srcX, srcZ, x, z2); - const dx = Position.deltaX(dir); - const dz = Position.deltaZ(dir); - if (dx == 0 && dz == 0) { - return -1; - } - const collisionStrategy = this.getCollisionStrategy(); - if (collisionStrategy === null) { - return -1; - } - const extraFlag = this.blockWalkFlag(); - if (extraFlag === CollisionFlag.NULL) { - return -1; - } - if (this.moveStrategy === MoveStrategy_default.FLY) { - return dir; - } - if (canTravel(this.level, this.x, this.z, dx, dz, this.width, extraFlag, collisionStrategy)) { - return dir; - } - if (dx != 0 && canTravel(this.level, this.x, this.z, dx, 0, this.width, extraFlag, collisionStrategy)) { - return Position.face(srcX, srcZ, x, srcZ); - } - if (dz != 0 && canTravel(this.level, this.x, this.z, 0, dz, this.width, extraFlag, collisionStrategy)) { - return Position.face(srcX, srcZ, srcX, z2); - } - return null; - } -} - -// src/jagex2/datastruct/Stack.ts -class Stack { - sentinel; - cursor = null; - constructor() { - const head = new Hashable(); - head.nextHashable = head; - head.prevHashable = head; - this.sentinel = head; - } - push(node) { - if (node.prevHashable) { - node.uncache(); - } - node.prevHashable = this.sentinel.prevHashable; - node.nextHashable = this.sentinel; - if (node.prevHashable) { - node.prevHashable.nextHashable = node; - } - node.nextHashable.prevHashable = node; - } - pop() { - const node = this.sentinel.nextHashable; - if (node === this.sentinel) { - return null; - } - node?.uncache(); - return node; - } - head() { - const node = this.sentinel.nextHashable; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.nextHashable || null; - return node; - } - next() { - const node = this.cursor; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.nextHashable || null; - return node; - } -} - -// src/lostcity/server/PreloadedPacks.ts -async function preloadClient() { - const allMaps = [ - 'l29_75', - 'l30_75', - 'l31_75', - 'l32_70', - 'l32_71', - 'l32_72', - 'l32_73', - 'l32_74', - 'l32_75', - 'l33_70', - 'l33_71', - 'l33_72', - 'l33_73', - 'l33_74', - 'l33_75', - 'l33_76', - 'l34_70', - 'l34_71', - 'l34_72', - 'l34_73', - 'l34_74', - 'l34_75', - 'l34_76', - 'l35_20', - 'l35_75', - 'l35_76', - 'l36_146', - 'l36_147', - 'l36_148', - 'l36_149', - 'l36_150', - 'l36_153', - 'l36_154', - 'l36_52', - 'l36_53', - 'l36_54', - 'l36_72', - 'l36_73', - 'l36_74', - 'l36_75', - 'l36_76', - 'l37_146', - 'l37_147', - 'l37_148', - 'l37_149', - 'l37_150', - 'l37_151', - 'l37_152', - 'l37_153', - 'l37_154', - 'l37_48', - 'l37_49', - 'l37_50', - 'l37_51', - 'l37_52', - 'l37_53', - 'l37_54', - 'l37_55', - 'l37_72', - 'l37_73', - 'l37_74', - 'l37_75', - 'l38_146', - 'l38_147', - 'l38_148', - 'l38_149', - 'l38_150', - 'l38_151', - 'l38_152', - 'l38_153', - 'l38_154', - 'l38_155', - 'l38_45', - 'l38_46', - 'l38_47', - 'l38_48', - 'l38_49', - 'l38_50', - 'l38_51', - 'l38_52', - 'l38_53', - 'l38_54', - 'l38_55', - 'l38_72', - 'l38_73', - 'l38_74', - 'l39_147', - 'l39_148', - 'l39_149', - 'l39_150', - 'l39_151', - 'l39_152', - 'l39_153', - 'l39_154', - 'l39_155', - 'l39_45', - 'l39_46', - 'l39_47', - 'l39_48', - 'l39_49', - 'l39_50', - 'l39_51', - 'l39_52', - 'l39_53', - 'l39_54', - 'l39_55', - 'l39_72', - 'l39_73', - 'l39_74', - 'l39_75', - 'l39_76', - 'l40_147', - 'l40_148', - 'l40_149', - 'l40_150', - 'l40_151', - 'l40_152', - 'l40_153', - 'l40_154', - 'l40_45', - 'l40_46', - 'l40_47', - 'l40_48', - 'l40_49', - 'l40_50', - 'l40_51', - 'l40_52', - 'l40_53', - 'l40_54', - 'l40_55', - 'l40_72', - 'l40_73', - 'l40_74', - 'l40_75', - 'l40_76', - 'l41_146', - 'l41_149', - 'l41_151', - 'l41_152', - 'l41_153', - 'l41_154', - 'l41_45', - 'l41_46', - 'l41_47', - 'l41_48', - 'l41_49', - 'l41_50', - 'l41_51', - 'l41_52', - 'l41_53', - 'l41_54', - 'l41_55', - 'l41_56', - 'l41_72', - 'l41_73', - 'l41_74', - 'l41_75', - 'l42_144', - 'l42_145', - 'l42_146', - 'l42_151', - 'l42_152', - 'l42_153', - 'l42_49', - 'l42_50', - 'l42_51', - 'l42_52', - 'l42_53', - 'l42_54', - 'l42_55', - 'l42_56', - 'l42_72', - 'l42_73', - 'l42_74', - 'l42_75', - 'l43_144', - 'l43_145', - 'l43_146', - 'l43_153', - 'l43_154', - 'l43_45', - 'l43_46', - 'l43_47', - 'l43_48', - 'l43_49', - 'l43_50', - 'l43_51', - 'l43_52', - 'l43_53', - 'l43_54', - 'l43_55', - 'l43_56', - 'l43_72', - 'l43_73', - 'l43_74', - 'l43_75', - 'l44_144', - 'l44_145', - 'l44_146', - 'l44_148', - 'l44_149', - 'l44_150', - 'l44_151', - 'l44_152', - 'l44_153', - 'l44_154', - 'l44_155', - 'l44_45', - 'l44_46', - 'l44_47', - 'l44_48', - 'l44_49', - 'l44_50', - 'l44_51', - 'l44_52', - 'l44_53', - 'l44_54', - 'l44_55', - 'l44_72', - 'l44_73', - 'l44_74', - 'l44_75', - 'l45_145', - 'l45_146', - 'l45_148', - 'l45_150', - 'l45_151', - 'l45_152', - 'l45_153', - 'l45_154', - 'l45_155', - 'l45_45', - 'l45_46', - 'l45_47', - 'l45_48', - 'l45_49', - 'l45_50', - 'l45_51', - 'l45_52', - 'l45_53', - 'l45_54', - 'l45_55', - 'l45_56', - 'l45_57', - 'l45_58', - 'l45_59', - 'l45_60', - 'l45_61', - 'l45_62', - 'l45_73', - 'l45_74', - 'l45_75', - 'l45_76', - 'l46_149', - 'l46_150', - 'l46_152', - 'l46_153', - 'l46_154', - 'l46_161', - 'l46_45', - 'l46_46', - 'l46_47', - 'l46_48', - 'l46_49', - 'l46_50', - 'l46_51', - 'l46_52', - 'l46_53', - 'l46_54', - 'l46_55', - 'l46_56', - 'l46_57', - 'l46_58', - 'l46_59', - 'l46_60', - 'l46_61', - 'l46_62', - 'l46_75', - 'l47_148', - 'l47_149', - 'l47_150', - 'l47_152', - 'l47_153', - 'l47_160', - 'l47_161', - 'l47_47', - 'l47_48', - 'l47_49', - 'l47_50', - 'l47_51', - 'l47_52', - 'l47_53', - 'l47_54', - 'l47_55', - 'l47_56', - 'l47_57', - 'l47_58', - 'l47_59', - 'l47_60', - 'l47_61', - 'l47_62', - 'l47_75', - 'l48_148', - 'l48_149', - 'l48_152', - 'l48_153', - 'l48_154', - 'l48_155', - 'l48_156', - 'l48_47', - 'l48_48', - 'l48_49', - 'l48_50', - 'l48_51', - 'l48_52', - 'l48_53', - 'l48_54', - 'l48_55', - 'l48_56', - 'l48_57', - 'l48_58', - 'l48_59', - 'l48_60', - 'l48_61', - 'l48_62', - 'l49_148', - 'l49_149', - 'l49_153', - 'l49_154', - 'l49_155', - 'l49_156', - 'l49_46', - 'l49_47', - 'l49_48', - 'l49_49', - 'l49_50', - 'l49_51', - 'l49_52', - 'l49_53', - 'l49_54', - 'l49_55', - 'l49_56', - 'l49_57', - 'l49_58', - 'l49_59', - 'l49_60', - 'l49_61', - 'l49_62', - 'l50_149', - 'l50_150', - 'l50_152', - 'l50_153', - 'l50_154', - 'l50_46', - 'l50_47', - 'l50_48', - 'l50_49', - 'l50_50', - 'l50_51', - 'l50_52', - 'l50_53', - 'l50_54', - 'l50_55', - 'l50_56', - 'l50_57', - 'l50_58', - 'l50_59', - 'l50_60', - 'l50_61', - 'l50_62', - 'l51_147', - 'l51_154', - 'l51_46', - 'l51_47', - 'l51_48', - 'l51_49', - 'l51_50', - 'l51_51', - 'l51_52', - 'l51_53', - 'l51_54', - 'l51_55', - 'l51_56', - 'l51_57', - 'l51_58', - 'l51_59', - 'l51_60', - 'l51_61', - 'l51_62', - 'l52_152', - 'l52_153', - 'l52_154', - 'l52_46', - 'l52_47', - 'l52_48', - 'l52_49', - 'l52_50', - 'l52_51', - 'l52_52', - 'l52_53', - 'l52_54', - 'l52_55', - 'l52_56', - 'l52_57', - 'l52_58', - 'l52_59', - 'l52_60', - 'l52_61', - 'l52_62', - 'l53_49', - 'l53_50', - 'l53_51', - 'l53_52', - 'l53_53', - 'm29_75', - 'm30_75', - 'm31_75', - 'm32_70', - 'm32_71', - 'm32_72', - 'm32_73', - 'm32_74', - 'm32_75', - 'm33_70', - 'm33_71', - 'm33_72', - 'm33_73', - 'm33_74', - 'm33_75', - 'm33_76', - 'm34_70', - 'm34_71', - 'm34_72', - 'm34_73', - 'm34_74', - 'm34_75', - 'm34_76', - 'm35_20', - 'm35_75', - 'm35_76', - 'm36_146', - 'm36_147', - 'm36_148', - 'm36_149', - 'm36_150', - 'm36_153', - 'm36_154', - 'm36_52', - 'm36_53', - 'm36_54', - 'm36_72', - 'm36_73', - 'm36_74', - 'm36_75', - 'm36_76', - 'm37_146', - 'm37_147', - 'm37_148', - 'm37_149', - 'm37_150', - 'm37_151', - 'm37_152', - 'm37_153', - 'm37_154', - 'm37_48', - 'm37_49', - 'm37_50', - 'm37_51', - 'm37_52', - 'm37_53', - 'm37_54', - 'm37_55', - 'm37_72', - 'm37_73', - 'm37_74', - 'm37_75', - 'm38_146', - 'm38_147', - 'm38_148', - 'm38_149', - 'm38_150', - 'm38_151', - 'm38_152', - 'm38_153', - 'm38_154', - 'm38_155', - 'm38_45', - 'm38_46', - 'm38_47', - 'm38_48', - 'm38_49', - 'm38_50', - 'm38_51', - 'm38_52', - 'm38_53', - 'm38_54', - 'm38_55', - 'm38_72', - 'm38_73', - 'm38_74', - 'm39_147', - 'm39_148', - 'm39_149', - 'm39_150', - 'm39_151', - 'm39_152', - 'm39_153', - 'm39_154', - 'm39_155', - 'm39_45', - 'm39_46', - 'm39_47', - 'm39_48', - 'm39_49', - 'm39_50', - 'm39_51', - 'm39_52', - 'm39_53', - 'm39_54', - 'm39_55', - 'm39_72', - 'm39_73', - 'm39_74', - 'm39_75', - 'm39_76', - 'm40_147', - 'm40_148', - 'm40_149', - 'm40_150', - 'm40_151', - 'm40_152', - 'm40_153', - 'm40_154', - 'm40_45', - 'm40_46', - 'm40_47', - 'm40_48', - 'm40_49', - 'm40_50', - 'm40_51', - 'm40_52', - 'm40_53', - 'm40_54', - 'm40_55', - 'm40_72', - 'm40_73', - 'm40_74', - 'm40_75', - 'm40_76', - 'm41_146', - 'm41_149', - 'm41_151', - 'm41_152', - 'm41_153', - 'm41_154', - 'm41_45', - 'm41_46', - 'm41_47', - 'm41_48', - 'm41_49', - 'm41_50', - 'm41_51', - 'm41_52', - 'm41_53', - 'm41_54', - 'm41_55', - 'm41_56', - 'm41_72', - 'm41_73', - 'm41_74', - 'm41_75', - 'm42_144', - 'm42_145', - 'm42_146', - 'm42_151', - 'm42_152', - 'm42_153', - 'm42_49', - 'm42_50', - 'm42_51', - 'm42_52', - 'm42_53', - 'm42_54', - 'm42_55', - 'm42_56', - 'm42_72', - 'm42_73', - 'm42_74', - 'm42_75', - 'm43_144', - 'm43_145', - 'm43_146', - 'm43_153', - 'm43_154', - 'm43_45', - 'm43_46', - 'm43_47', - 'm43_48', - 'm43_49', - 'm43_50', - 'm43_51', - 'm43_52', - 'm43_53', - 'm43_54', - 'm43_55', - 'm43_56', - 'm43_72', - 'm43_73', - 'm43_74', - 'm43_75', - 'm44_144', - 'm44_145', - 'm44_146', - 'm44_148', - 'm44_149', - 'm44_150', - 'm44_151', - 'm44_152', - 'm44_153', - 'm44_154', - 'm44_155', - 'm44_45', - 'm44_46', - 'm44_47', - 'm44_48', - 'm44_49', - 'm44_50', - 'm44_51', - 'm44_52', - 'm44_53', - 'm44_54', - 'm44_55', - 'm44_72', - 'm44_73', - 'm44_74', - 'm44_75', - 'm45_145', - 'm45_146', - 'm45_148', - 'm45_150', - 'm45_151', - 'm45_152', - 'm45_153', - 'm45_154', - 'm45_155', - 'm45_45', - 'm45_46', - 'm45_47', - 'm45_48', - 'm45_49', - 'm45_50', - 'm45_51', - 'm45_52', - 'm45_53', - 'm45_54', - 'm45_55', - 'm45_56', - 'm45_57', - 'm45_58', - 'm45_59', - 'm45_60', - 'm45_61', - 'm45_62', - 'm45_73', - 'm45_74', - 'm45_75', - 'm45_76', - 'm46_149', - 'm46_150', - 'm46_152', - 'm46_153', - 'm46_154', - 'm46_161', - 'm46_45', - 'm46_46', - 'm46_47', - 'm46_48', - 'm46_49', - 'm46_50', - 'm46_51', - 'm46_52', - 'm46_53', - 'm46_54', - 'm46_55', - 'm46_56', - 'm46_57', - 'm46_58', - 'm46_59', - 'm46_60', - 'm46_61', - 'm46_62', - 'm46_75', - 'm47_148', - 'm47_149', - 'm47_150', - 'm47_152', - 'm47_153', - 'm47_160', - 'm47_161', - 'm47_47', - 'm47_48', - 'm47_49', - 'm47_50', - 'm47_51', - 'm47_52', - 'm47_53', - 'm47_54', - 'm47_55', - 'm47_56', - 'm47_57', - 'm47_58', - 'm47_59', - 'm47_60', - 'm47_61', - 'm47_62', - 'm47_75', - 'm48_148', - 'm48_149', - 'm48_152', - 'm48_153', - 'm48_154', - 'm48_155', - 'm48_156', - 'm48_47', - 'm48_48', - 'm48_49', - 'm48_50', - 'm48_51', - 'm48_52', - 'm48_53', - 'm48_54', - 'm48_55', - 'm48_56', - 'm48_57', - 'm48_58', - 'm48_59', - 'm48_60', - 'm48_61', - 'm48_62', - 'm49_148', - 'm49_149', - 'm49_153', - 'm49_154', - 'm49_155', - 'm49_156', - 'm49_46', - 'm49_47', - 'm49_48', - 'm49_49', - 'm49_50', - 'm49_51', - 'm49_52', - 'm49_53', - 'm49_54', - 'm49_55', - 'm49_56', - 'm49_57', - 'm49_58', - 'm49_59', - 'm49_60', - 'm49_61', - 'm49_62', - 'm50_149', - 'm50_150', - 'm50_152', - 'm50_153', - 'm50_154', - 'm50_46', - 'm50_47', - 'm50_48', - 'm50_49', - 'm50_50', - 'm50_51', - 'm50_52', - 'm50_53', - 'm50_54', - 'm50_55', - 'm50_56', - 'm50_57', - 'm50_58', - 'm50_59', - 'm50_60', - 'm50_61', - 'm50_62', - 'm51_147', - 'm51_154', - 'm51_46', - 'm51_47', - 'm51_48', - 'm51_49', - 'm51_50', - 'm51_51', - 'm51_52', - 'm51_53', - 'm51_54', - 'm51_55', - 'm51_56', - 'm51_57', - 'm51_58', - 'm51_59', - 'm51_60', - 'm51_61', - 'm51_62', - 'm52_152', - 'm52_153', - 'm52_154', - 'm52_46', - 'm52_47', - 'm52_48', - 'm52_49', - 'm52_50', - 'm52_51', - 'm52_52', - 'm52_53', - 'm52_54', - 'm52_55', - 'm52_56', - 'm52_57', - 'm52_58', - 'm52_59', - 'm52_60', - 'm52_61', - 'm52_62', - 'm53_49', - 'm53_50', - 'm53_51', - 'm53_52', - 'm53_53', - 'n29_75', - 'n30_75', - 'n31_75', - 'n32_70', - 'n32_71', - 'n32_72', - 'n32_73', - 'n32_74', - 'n32_75', - 'n33_70', - 'n33_71', - 'n33_72', - 'n33_73', - 'n33_74', - 'n33_75', - 'n33_76', - 'n34_70', - 'n34_71', - 'n34_72', - 'n34_73', - 'n34_74', - 'n34_75', - 'n34_76', - 'n35_20', - 'n35_75', - 'n35_76', - 'n36_146', - 'n36_147', - 'n36_148', - 'n36_149', - 'n36_150', - 'n36_153', - 'n36_154', - 'n36_52', - 'n36_53', - 'n36_54', - 'n36_72', - 'n36_73', - 'n36_74', - 'n36_75', - 'n36_76', - 'n37_146', - 'n37_147', - 'n37_148', - 'n37_149', - 'n37_150', - 'n37_151', - 'n37_152', - 'n37_153', - 'n37_154', - 'n37_48', - 'n37_49', - 'n37_50', - 'n37_51', - 'n37_52', - 'n37_53', - 'n37_54', - 'n37_55', - 'n37_72', - 'n37_73', - 'n37_74', - 'n37_75', - 'n38_146', - 'n38_147', - 'n38_148', - 'n38_149', - 'n38_150', - 'n38_151', - 'n38_152', - 'n38_153', - 'n38_154', - 'n38_155', - 'n38_45', - 'n38_46', - 'n38_47', - 'n38_48', - 'n38_49', - 'n38_50', - 'n38_51', - 'n38_52', - 'n38_53', - 'n38_54', - 'n38_55', - 'n38_72', - 'n38_73', - 'n38_74', - 'n39_147', - 'n39_148', - 'n39_149', - 'n39_150', - 'n39_151', - 'n39_152', - 'n39_153', - 'n39_154', - 'n39_155', - 'n39_45', - 'n39_46', - 'n39_47', - 'n39_48', - 'n39_49', - 'n39_50', - 'n39_51', - 'n39_52', - 'n39_53', - 'n39_54', - 'n39_55', - 'n39_72', - 'n39_73', - 'n39_74', - 'n39_75', - 'n39_76', - 'n40_147', - 'n40_148', - 'n40_149', - 'n40_150', - 'n40_151', - 'n40_152', - 'n40_153', - 'n40_154', - 'n40_45', - 'n40_46', - 'n40_47', - 'n40_48', - 'n40_49', - 'n40_50', - 'n40_51', - 'n40_52', - 'n40_53', - 'n40_54', - 'n40_55', - 'n40_72', - 'n40_73', - 'n40_74', - 'n40_75', - 'n40_76', - 'n41_146', - 'n41_149', - 'n41_151', - 'n41_152', - 'n41_153', - 'n41_154', - 'n41_45', - 'n41_46', - 'n41_47', - 'n41_48', - 'n41_49', - 'n41_50', - 'n41_51', - 'n41_52', - 'n41_53', - 'n41_54', - 'n41_55', - 'n41_56', - 'n41_72', - 'n41_73', - 'n41_74', - 'n41_75', - 'n42_144', - 'n42_145', - 'n42_146', - 'n42_151', - 'n42_152', - 'n42_153', - 'n42_49', - 'n42_50', - 'n42_51', - 'n42_52', - 'n42_53', - 'n42_54', - 'n42_55', - 'n42_56', - 'n42_72', - 'n42_73', - 'n42_74', - 'n42_75', - 'n43_144', - 'n43_145', - 'n43_146', - 'n43_153', - 'n43_154', - 'n43_45', - 'n43_46', - 'n43_47', - 'n43_48', - 'n43_49', - 'n43_50', - 'n43_51', - 'n43_52', - 'n43_53', - 'n43_54', - 'n43_55', - 'n43_56', - 'n43_72', - 'n43_73', - 'n43_74', - 'n43_75', - 'n44_144', - 'n44_145', - 'n44_146', - 'n44_148', - 'n44_149', - 'n44_150', - 'n44_151', - 'n44_152', - 'n44_153', - 'n44_154', - 'n44_155', - 'n44_45', - 'n44_46', - 'n44_47', - 'n44_48', - 'n44_49', - 'n44_50', - 'n44_51', - 'n44_52', - 'n44_53', - 'n44_54', - 'n44_55', - 'n44_72', - 'n44_73', - 'n44_74', - 'n44_75', - 'n45_145', - 'n45_146', - 'n45_148', - 'n45_150', - 'n45_151', - 'n45_152', - 'n45_153', - 'n45_154', - 'n45_155', - 'n45_45', - 'n45_46', - 'n45_47', - 'n45_48', - 'n45_49', - 'n45_50', - 'n45_51', - 'n45_52', - 'n45_53', - 'n45_54', - 'n45_55', - 'n45_56', - 'n45_57', - 'n45_58', - 'n45_59', - 'n45_60', - 'n45_61', - 'n45_62', - 'n45_73', - 'n45_74', - 'n45_75', - 'n45_76', - 'n46_149', - 'n46_150', - 'n46_152', - 'n46_153', - 'n46_154', - 'n46_161', - 'n46_45', - 'n46_46', - 'n46_47', - 'n46_48', - 'n46_49', - 'n46_50', - 'n46_51', - 'n46_52', - 'n46_53', - 'n46_54', - 'n46_55', - 'n46_56', - 'n46_57', - 'n46_58', - 'n46_59', - 'n46_60', - 'n46_61', - 'n46_62', - 'n46_75', - 'n47_148', - 'n47_149', - 'n47_150', - 'n47_152', - 'n47_153', - 'n47_160', - 'n47_161', - 'n47_47', - 'n47_48', - 'n47_49', - 'n47_50', - 'n47_51', - 'n47_52', - 'n47_53', - 'n47_54', - 'n47_55', - 'n47_56', - 'n47_57', - 'n47_58', - 'n47_59', - 'n47_60', - 'n47_61', - 'n47_62', - 'n47_75', - 'n48_148', - 'n48_149', - 'n48_152', - 'n48_153', - 'n48_154', - 'n48_155', - 'n48_156', - 'n48_47', - 'n48_48', - 'n48_49', - 'n48_50', - 'n48_51', - 'n48_52', - 'n48_53', - 'n48_54', - 'n48_55', - 'n48_56', - 'n48_57', - 'n48_58', - 'n48_59', - 'n48_60', - 'n48_61', - 'n48_62', - 'n49_148', - 'n49_149', - 'n49_153', - 'n49_154', - 'n49_155', - 'n49_156', - 'n49_46', - 'n49_47', - 'n49_48', - 'n49_49', - 'n49_50', - 'n49_51', - 'n49_52', - 'n49_53', - 'n49_54', - 'n49_55', - 'n49_56', - 'n49_57', - 'n49_58', - 'n49_59', - 'n49_60', - 'n49_61', - 'n49_62', - 'n50_149', - 'n50_150', - 'n50_152', - 'n50_153', - 'n50_154', - 'n50_46', - 'n50_47', - 'n50_48', - 'n50_49', - 'n50_50', - 'n50_51', - 'n50_52', - 'n50_53', - 'n50_54', - 'n50_55', - 'n50_56', - 'n50_57', - 'n50_58', - 'n50_59', - 'n50_60', - 'n50_61', - 'n50_62', - 'n51_147', - 'n51_154', - 'n51_46', - 'n51_47', - 'n51_48', - 'n51_49', - 'n51_50', - 'n51_51', - 'n51_52', - 'n51_53', - 'n51_54', - 'n51_55', - 'n51_56', - 'n51_57', - 'n51_58', - 'n51_59', - 'n51_60', - 'n51_61', - 'n51_62', - 'n52_152', - 'n52_153', - 'n52_154', - 'n52_46', - 'n52_47', - 'n52_48', - 'n52_49', - 'n52_50', - 'n52_51', - 'n52_52', - 'n52_53', - 'n52_54', - 'n52_55', - 'n52_56', - 'n52_57', - 'n52_58', - 'n52_59', - 'n52_60', - 'n52_61', - 'n52_62', - 'n53_49', - 'n53_50', - 'n53_51', - 'n53_52', - 'n53_53', - 'o29_75', - 'o30_75', - 'o31_75', - 'o32_70', - 'o32_71', - 'o32_72', - 'o32_73', - 'o32_74', - 'o32_75', - 'o33_70', - 'o33_71', - 'o33_72', - 'o33_73', - 'o33_74', - 'o33_75', - 'o33_76', - 'o34_70', - 'o34_71', - 'o34_72', - 'o34_73', - 'o34_74', - 'o34_75', - 'o34_76', - 'o35_20', - 'o35_75', - 'o35_76', - 'o36_146', - 'o36_147', - 'o36_148', - 'o36_149', - 'o36_150', - 'o36_153', - 'o36_154', - 'o36_52', - 'o36_53', - 'o36_54', - 'o36_72', - 'o36_73', - 'o36_74', - 'o36_75', - 'o36_76', - 'o37_146', - 'o37_147', - 'o37_148', - 'o37_149', - 'o37_150', - 'o37_151', - 'o37_152', - 'o37_153', - 'o37_154', - 'o37_48', - 'o37_49', - 'o37_50', - 'o37_51', - 'o37_52', - 'o37_53', - 'o37_54', - 'o37_55', - 'o37_72', - 'o37_73', - 'o37_74', - 'o37_75', - 'o38_146', - 'o38_147', - 'o38_148', - 'o38_149', - 'o38_150', - 'o38_151', - 'o38_152', - 'o38_153', - 'o38_154', - 'o38_155', - 'o38_45', - 'o38_46', - 'o38_47', - 'o38_48', - 'o38_49', - 'o38_50', - 'o38_51', - 'o38_52', - 'o38_53', - 'o38_54', - 'o38_55', - 'o38_72', - 'o38_73', - 'o38_74', - 'o39_147', - 'o39_148', - 'o39_149', - 'o39_150', - 'o39_151', - 'o39_152', - 'o39_153', - 'o39_154', - 'o39_155', - 'o39_45', - 'o39_46', - 'o39_47', - 'o39_48', - 'o39_49', - 'o39_50', - 'o39_51', - 'o39_52', - 'o39_53', - 'o39_54', - 'o39_55', - 'o39_72', - 'o39_73', - 'o39_74', - 'o39_75', - 'o39_76', - 'o40_147', - 'o40_148', - 'o40_149', - 'o40_150', - 'o40_151', - 'o40_152', - 'o40_153', - 'o40_154', - 'o40_45', - 'o40_46', - 'o40_47', - 'o40_48', - 'o40_49', - 'o40_50', - 'o40_51', - 'o40_52', - 'o40_53', - 'o40_54', - 'o40_55', - 'o40_72', - 'o40_73', - 'o40_74', - 'o40_75', - 'o40_76', - 'o41_146', - 'o41_149', - 'o41_151', - 'o41_152', - 'o41_153', - 'o41_154', - 'o41_45', - 'o41_46', - 'o41_47', - 'o41_48', - 'o41_49', - 'o41_50', - 'o41_51', - 'o41_52', - 'o41_53', - 'o41_54', - 'o41_55', - 'o41_56', - 'o41_72', - 'o41_73', - 'o41_74', - 'o41_75', - 'o42_144', - 'o42_145', - 'o42_146', - 'o42_151', - 'o42_152', - 'o42_153', - 'o42_49', - 'o42_50', - 'o42_51', - 'o42_52', - 'o42_53', - 'o42_54', - 'o42_55', - 'o42_56', - 'o42_72', - 'o42_73', - 'o42_74', - 'o42_75', - 'o43_144', - 'o43_145', - 'o43_146', - 'o43_153', - 'o43_154', - 'o43_45', - 'o43_46', - 'o43_47', - 'o43_48', - 'o43_49', - 'o43_50', - 'o43_51', - 'o43_52', - 'o43_53', - 'o43_54', - 'o43_55', - 'o43_56', - 'o43_72', - 'o43_73', - 'o43_74', - 'o43_75', - 'o44_144', - 'o44_145', - 'o44_146', - 'o44_148', - 'o44_149', - 'o44_150', - 'o44_151', - 'o44_152', - 'o44_153', - 'o44_154', - 'o44_155', - 'o44_45', - 'o44_46', - 'o44_47', - 'o44_48', - 'o44_49', - 'o44_50', - 'o44_51', - 'o44_52', - 'o44_53', - 'o44_54', - 'o44_55', - 'o44_72', - 'o44_73', - 'o44_74', - 'o44_75', - 'o45_145', - 'o45_146', - 'o45_148', - 'o45_150', - 'o45_151', - 'o45_152', - 'o45_153', - 'o45_154', - 'o45_155', - 'o45_45', - 'o45_46', - 'o45_47', - 'o45_48', - 'o45_49', - 'o45_50', - 'o45_51', - 'o45_52', - 'o45_53', - 'o45_54', - 'o45_55', - 'o45_56', - 'o45_57', - 'o45_58', - 'o45_59', - 'o45_60', - 'o45_61', - 'o45_62', - 'o45_73', - 'o45_74', - 'o45_75', - 'o45_76', - 'o46_149', - 'o46_150', - 'o46_152', - 'o46_153', - 'o46_154', - 'o46_161', - 'o46_45', - 'o46_46', - 'o46_47', - 'o46_48', - 'o46_49', - 'o46_50', - 'o46_51', - 'o46_52', - 'o46_53', - 'o46_54', - 'o46_55', - 'o46_56', - 'o46_57', - 'o46_58', - 'o46_59', - 'o46_60', - 'o46_61', - 'o46_62', - 'o46_75', - 'o47_148', - 'o47_149', - 'o47_150', - 'o47_152', - 'o47_153', - 'o47_160', - 'o47_161', - 'o47_47', - 'o47_48', - 'o47_49', - 'o47_50', - 'o47_51', - 'o47_52', - 'o47_53', - 'o47_54', - 'o47_55', - 'o47_56', - 'o47_57', - 'o47_58', - 'o47_59', - 'o47_60', - 'o47_61', - 'o47_62', - 'o47_75', - 'o48_148', - 'o48_149', - 'o48_152', - 'o48_153', - 'o48_154', - 'o48_155', - 'o48_156', - 'o48_47', - 'o48_48', - 'o48_49', - 'o48_50', - 'o48_51', - 'o48_52', - 'o48_53', - 'o48_54', - 'o48_55', - 'o48_56', - 'o48_57', - 'o48_58', - 'o48_59', - 'o48_60', - 'o48_61', - 'o48_62', - 'o49_148', - 'o49_149', - 'o49_153', - 'o49_154', - 'o49_155', - 'o49_156', - 'o49_46', - 'o49_47', - 'o49_48', - 'o49_49', - 'o49_50', - 'o49_51', - 'o49_52', - 'o49_53', - 'o49_54', - 'o49_55', - 'o49_56', - 'o49_57', - 'o49_58', - 'o49_59', - 'o49_60', - 'o49_61', - 'o49_62', - 'o50_149', - 'o50_150', - 'o50_152', - 'o50_153', - 'o50_154', - 'o50_46', - 'o50_47', - 'o50_48', - 'o50_49', - 'o50_50', - 'o50_51', - 'o50_52', - 'o50_53', - 'o50_54', - 'o50_55', - 'o50_56', - 'o50_57', - 'o50_58', - 'o50_59', - 'o50_60', - 'o50_61', - 'o50_62', - 'o51_147', - 'o51_154', - 'o51_46', - 'o51_47', - 'o51_48', - 'o51_49', - 'o51_50', - 'o51_51', - 'o51_52', - 'o51_53', - 'o51_54', - 'o51_55', - 'o51_56', - 'o51_57', - 'o51_58', - 'o51_59', - 'o51_60', - 'o51_61', - 'o51_62', - 'o52_152', - 'o52_153', - 'o52_154', - 'o52_46', - 'o52_47', - 'o52_48', - 'o52_49', - 'o52_50', - 'o52_51', - 'o52_52', - 'o52_53', - 'o52_54', - 'o52_55', - 'o52_56', - 'o52_57', - 'o52_58', - 'o52_59', - 'o52_60', - 'o52_61', - 'o52_62', - 'o53_49', - 'o53_50', - 'o53_51', - 'o53_52', - 'o53_53' - ]; - for (let i = 0; i < allMaps.length; i++) { - const name = allMaps[i]; - const map = new Uint8Array(await (await fetch(`data/pack/client/maps/${name}`)).arrayBuffer()); - const crc = Packet.getcrc(map, 0, map.length); - PRELOADED.set(name, map); - PRELOADED_CRC.set(name, crc); - } - const allSongs = [ - 'adventure.mid', - 'al_kharid.mid', - 'alone.mid', - 'ambience_2.mid', - 'ambience_3.mid', - 'ambience_4.mid', - 'ambient_jungle.mid', - 'arabian.mid', - 'arabian2.mid', - 'arabian3.mid', - 'arabique.mid', - 'army_of_darkness.mid', - 'arrival.mid', - 'attack1.mid', - 'attack2.mid', - 'attack3.mid', - 'attack4.mid', - 'attack5.mid', - 'attack6.mid', - 'attention.mid', - 'autumn_voyage.mid', - 'background2.mid', - 'ballad_of_enchantment.mid', - 'baroque.mid', - 'beyond.mid', - 'big_chords.mid', - 'book_of_spells.mid', - 'camelot.mid', - 'cave_background1.mid', - 'cavern.mid', - 'cellar_song1.mid', - 'chain_of_command.mid', - 'chompy_hunt.mid', - 'close_quarters.mid', - 'crystal_cave.mid', - 'crystal_sword.mid', - 'cursed.mid', - 'dangerous.mid', - 'dark2.mid', - 'deep_wildy.mid', - 'desert_voyage.mid', - 'doorways.mid', - 'dream1.mid', - 'duel_arena.mid', - 'dunjun.mid', - 'egypt.mid', - 'emotion.mid', - 'emperor.mid', - 'escape.mid', - 'expanse.mid', - 'expecting.mid', - 'expedition.mid', - 'fade_test.mid', - 'faerie.mid', - 'fanfare.mid', - 'fanfare2.mid', - 'fanfare3.mid', - 'fishing.mid', - 'flute_salad.mid', - 'forbidden.mid', - 'forever.mid', - 'game_intro_1.mid', - 'gaol.mid', - 'garden.mid', - 'gnome.mid', - 'gnome_king.mid', - 'gnome_theme.mid', - 'gnome_village.mid', - 'gnome_village2.mid', - 'gnomeball.mid', - 'greatness.mid', - 'grumpy.mid', - 'harmony.mid', - 'harmony2.mid', - 'heart_and_mind.mid', - 'high_seas.mid', - 'horizon.mid', - 'iban.mid', - 'ice_melody.mid', - 'in_the_manor.mid', - 'inspiration.mid', - 'intrepid.mid', - 'jolly-r.mid', - 'jungle_island.mid', - 'jungly1.mid', - 'jungly2.mid', - 'jungly3.mid', - 'knightly.mid', - 'landlubber.mid', - 'lasting.mid', - 'legion.mid', - 'lightness.mid', - 'lightwalk.mid', - 'lonesome.mid', - 'long_ago.mid', - 'long_way_home.mid', - 'lullaby.mid', - 'mage_arena.mid', - 'magic_dance.mid', - 'magical_journey.mid', - 'march2.mid', - 'medieval.mid', - 'mellow.mid', - 'miles_away.mid', - 'miracle_dance.mid', - 'monarch_waltz.mid', - 'moody.mid', - 'neverland.mid', - 'newbie_melody.mid', - 'nightfall.mid', - 'nomad.mid', - 'null.mid', - 'organ_music_1.mid', - 'organ_music_2.mid', - 'oriental.mid', - 'overture.mid', - 'parade.mid', - 'quest.mid', - 'regal2.mid', - 'reggae.mid', - 'reggae2.mid', - 'riverside.mid', - 'royale.mid', - 'rune_essence.mid', - 'sad_meadow.mid', - 'scape_cave.mid', - 'scape_main.mid', - 'scape_sad1.mid', - 'scape_soft.mid', - 'scape_wild1.mid', - 'sea_shanty.mid', - 'sea_shanty2.mid', - 'serenade.mid', - 'serene.mid', - 'shine.mid', - 'shining.mid', - 'silence.mid', - 'soundscape.mid', - 'spirit.mid', - 'splendour.mid', - 'spooky2.mid', - 'spooky_jungle.mid', - 'starlight.mid', - 'start.mid', - 'still_night.mid', - 'talking_forest.mid', - 'the_desert.mid', - 'the_shadow.mid', - 'the_tower.mid', - 'theme.mid', - 'tomorrow.mid', - 'trawler.mid', - 'trawler_minor.mid', - 'tree_spirits.mid', - 'tribal.mid', - 'tribal2.mid', - 'tribal_background.mid', - 'trinity.mid', - 'troubled.mid', - 'undercurrent.mid', - 'underground.mid', - 'understanding.mid', - 'unknown_land.mid', - 'upass1.mid', - 'upcoming.mid', - 'venture.mid', - 'venture2.mid', - 'vision.mid', - 'voodoo_cult.mid', - 'voyage.mid', - 'wander.mid', - 'waterfall.mid', - 'wilderness2.mid', - 'wilderness3.mid', - 'wilderness4.mid', - 'witching.mid', - 'wolf_mountain.mid', - 'wonder.mid', - 'wonderous.mid', - 'workshop.mid', - 'yesteryear.mid', - 'zealot.mid' - ]; - for (let i = 0; i < allSongs.length; i++) { - const name = allSongs[i]; - const song = new Uint8Array(await (await fetch(`data/pack/client/songs/${name}`)).arrayBuffer()); - const crc = Packet.getcrc(song, 0, song.length); - PRELOADED.set(name, song); - PRELOADED_CRC.set(name, crc); - } - const allJingles = [ - 'advance agility.mid', - 'advance attack.mid', - 'advance attack2.mid', - 'advance cooking.mid', - 'advance cooking2.mid', - 'advance crafting.mid', - 'advance crafting2.mid', - 'advance defense.mid', - 'advance defense2.mid', - 'advance firemarking.mid', - 'advance firemarking2.mid', - 'advance fishing.mid', - 'advance fishing2.mid', - 'advance fletching.mid', - 'advance fletching2.mid', - 'advance herblaw.mid', - 'advance herblaw2.mid', - 'advance hitpoints.mid', - 'advance hitpoints2.mid', - 'advance magic.mid', - 'advance magic2.mid', - 'advance mining.mid', - 'advance mining2.mid', - 'advance prayer.mid', - 'advance prayer2.mid', - 'advance ranged.mid', - 'advance ranged2.mid', - 'advance runecraft.mid', - 'advance runecraft2.mid', - 'advance smithing.mid', - 'advance smithing2.mid', - 'advance strength.mid', - 'advance strength2.mid', - 'advance thieving.mid', - 'advance thieving2.mid', - 'advance woodcutting.mid', - 'advance woodcutting2.mid', - 'death.mid', - 'death2.mid', - 'dice lose.mid', - 'dice win.mid', - 'duel start.mid', - 'duel win2.mid', - 'quest complete 1.mid', - 'quest complete 2.mid', - 'quest complete 3.mid', - 'sailing journey.mid', - 'treasure hunt win.mid' - ]; - for (let i = 0; i < allJingles.length; i++) { - const name = allJingles[i]; - const jingle = new Uint8Array(await (await fetch(`data/pack/client/jingles/${name}`)).arrayBuffer()).subarray(4); - const crc = Packet.getcrc(jingle, 0, jingle.length); - PRELOADED.set(name, jingle); - PRELOADED_CRC.set(name, crc); - } -} -var PRELOADED = new Map(); -var PRELOADED_CRC = new Map(); - -// src/lostcity/network/outgoing/OutgoingMessage.ts -class OutgoingMessage extends Hashable {} - -// src/lostcity/network/outgoing/prot/ServerProtPriority.ts -class ServerProtPriority { - static LOW = new ServerProtPriority(); - static HIGH = new ServerProtPriority(); -} - -// src/lostcity/network/outgoing/model/IfClose.ts -class IfClose extends OutgoingMessage { - priority = ServerProtPriority.LOW; -} - -// src/lostcity/network/outgoing/model/UpdateUid192.ts -class UpdateUid192 extends OutgoingMessage { - uid; - priority = ServerProtPriority.HIGH; - constructor(uid) { - super(); - this.uid = uid; - } -} - -// src/lostcity/network/outgoing/model/ResetAnims.ts -class ResetAnims extends OutgoingMessage { - priority = ServerProtPriority.HIGH; -} - -// src/lostcity/network/outgoing/model/ResetClientVarCache.ts -class ResetClientVarCache extends OutgoingMessage { - priority = ServerProtPriority.HIGH; -} - -// src/lostcity/network/outgoing/model/TutorialOpenChat.ts -class TutorialOpenChat extends OutgoingMessage { - component; - priority = ServerProtPriority.LOW; - constructor(component) { - super(); - this.component = component; - } -} - -// src/lostcity/network/outgoing/model/UpdateInvStopTransmit.ts -class UpdateInvStopTransmit extends OutgoingMessage { - component; - priority = ServerProtPriority.HIGH; - constructor(component) { - super(); - this.component = component; - } -} - -// src/lostcity/network/outgoing/model/VarpSmall.ts -class VarpSmall extends OutgoingMessage { - varp; - value; - priority = ServerProtPriority.HIGH; - constructor(varp, value) { - super(); - this.varp = varp; - this.value = value; - } -} - -// src/lostcity/network/outgoing/model/VarpLarge.ts -class VarpLarge extends OutgoingMessage { - varp; - value; - priority = ServerProtPriority.HIGH; - constructor(varp, value) { - super(); - this.varp = varp; - this.value = value; - } -} - -// src/lostcity/network/outgoing/model/MidiSong.ts -class MidiSong extends OutgoingMessage { - name; - crc; - length; - priority = ServerProtPriority.LOW; - constructor(name, crc, length) { - super(); - this.name = name; - this.crc = crc; - this.length = length; - } -} - -// src/lostcity/network/outgoing/model/MidiJingle.ts -class MidiJingle extends OutgoingMessage { - delay; - data; - priority = ServerProtPriority.LOW; - constructor(delay, data) { - super(); - this.delay = delay; - this.data = data; - } -} - -// src/lostcity/network/outgoing/model/IfOpenSideOverlay.ts -class IfOpenSideOverlay extends OutgoingMessage { - component; - tab; - priority = ServerProtPriority.LOW; - constructor(component, tab) { - super(); - this.component = component; - this.tab = tab; - } -} - -// src/lostcity/network/outgoing/model/UnsetMapFlag.ts -class UnsetMapFlag extends OutgoingMessage { - priority = ServerProtPriority.HIGH; -} - -// src/lostcity/network/outgoing/model/HintArrow.ts -class HintArrow extends OutgoingMessage { - type; - nid; - pid; - x; - z2; - y2; - priority = ServerProtPriority.LOW; - constructor(type, nid, pid, x, z2, y2) { - super(); - this.type = type; - this.nid = nid; - this.pid = pid; - this.x = x; - this.z = z2; - this.y = y2; - } -} - -// src/lostcity/network/outgoing/model/LastLoginInfo.ts -class LastLoginInfo extends OutgoingMessage { - lastLoginIp; - daysSinceLogin; - daysSinceRecoveryChange; - unreadMessageCount; - priority = ServerProtPriority.LOW; - constructor(lastLoginIp, daysSinceLogin, daysSinceRecoveryChange, unreadMessageCount) { - super(); - this.lastLoginIp = lastLoginIp; - this.daysSinceLogin = daysSinceLogin; - this.daysSinceRecoveryChange = daysSinceRecoveryChange; - this.unreadMessageCount = unreadMessageCount; - } -} - -// src/lostcity/network/outgoing/model/MessageGame.ts -class MessageGame extends OutgoingMessage { - msg; - priority = ServerProtPriority.HIGH; - constructor(msg) { - super(); - this.msg = msg; - } -} - -// src/lostcity/engine/zone/ZoneEventType.ts -var ZoneEventType; -(ZoneEventType2 => { - ZoneEventType2[(ZoneEventType2['ENCLOSED'] = 0)] = 'ENCLOSED'; - ZoneEventType2[(ZoneEventType2['FOLLOWS'] = 1)] = 'FOLLOWS'; -})((ZoneEventType ||= {})); -var ZoneEventType_default = ZoneEventType; - -// src/lostcity/network/outgoing/model/UpdateZonePartialEnclosed.ts -class UpdateZonePartialEnclosed extends OutgoingMessage { - zoneX; - zoneZ; - originX; - originZ; - data; - priority = ServerProtPriority.HIGH; - constructor(zoneX, zoneZ, originX, originZ, data) { - super(); - this.zoneX = zoneX; - this.zoneZ = zoneZ; - this.originX = originX; - this.originZ = originZ; - this.data = data; - } -} - -// src/lostcity/network/outgoing/model/UpdateZoneFullFollows.ts -class UpdateZoneFullFollows extends OutgoingMessage { - zoneX; - zoneZ; - originX; - originZ; - priority = ServerProtPriority.HIGH; - constructor(zoneX, zoneZ, originX, originZ) { - super(); - this.zoneX = zoneX; - this.zoneZ = zoneZ; - this.originX = originX; - this.originZ = originZ; - } -} - -// src/lostcity/network/outgoing/model/UpdateZonePartialFollows.ts -class UpdateZonePartialFollows extends OutgoingMessage { - zoneX; - zoneZ; - originX; - originZ; - priority = ServerProtPriority.HIGH; - constructor(zoneX, zoneZ, originX, originZ) { - super(); - this.zoneX = zoneX; - this.zoneZ = zoneZ; - this.originX = originX; - this.originZ = originZ; - } -} - -// src/lostcity/network/outgoing/ZoneMessage.ts -class ZoneMessage extends OutgoingMessage { - coord; - priority = ServerProtPriority.HIGH; - constructor(coord) { - super(); - this.coord = coord; - } -} - -// src/lostcity/network/outgoing/model/ObjAdd.ts -class ObjAdd extends ZoneMessage { - coord; - obj; - count; - constructor(coord, obj, count) { - super(coord); - this.coord = coord; - this.obj = obj; - this.count = count; - } -} - -// src/lostcity/network/outgoing/model/LocAddChange.ts -class LocAddChange extends ZoneMessage { - coord; - loc; - shape; - angle; - constructor(coord, loc, shape, angle) { - super(coord); - this.coord = coord; - this.loc = loc; - this.shape = shape; - this.angle = angle; - } -} - -// src/lostcity/network/outgoing/model/LocDel.ts -class LocDel extends ZoneMessage { - coord; - shape; - angle; - constructor(coord, shape, angle) { - super(coord); - this.coord = coord; - this.shape = shape; - this.angle = angle; - } -} - -// src/lostcity/network/outgoing/model/MapProjAnim.ts -class MapProjAnim extends ZoneMessage { - srcX; - srcZ; - dstX; - dstZ; - target; - spotanim; - srcHeight; - dstHeight; - startDelay; - endDelay; - peak; - arc; - constructor(srcX, srcZ, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) { - super(Position.packZoneCoord(srcX, srcZ)); - this.srcX = srcX; - this.srcZ = srcZ; - this.dstX = dstX; - this.dstZ = dstZ; - this.target = target; - this.spotanim = spotanim; - this.srcHeight = srcHeight; - this.dstHeight = dstHeight; - this.startDelay = startDelay; - this.endDelay = endDelay; - this.peak = peak; - this.arc = arc; - } -} - -// src/lostcity/network/outgoing/model/MapAnim.ts -class MapAnim extends ZoneMessage { - coord; - spotanim; - height; - delay; - constructor(coord, spotanim, height, delay) { - super(coord); - this.coord = coord; - this.spotanim = spotanim; - this.height = height; - this.delay = delay; - } -} - -// src/lostcity/network/outgoing/model/ObjDel.ts -class ObjDel extends ZoneMessage { - coord; - obj; - constructor(coord, obj) { - super(coord); - this.coord = coord; - this.obj = obj; - } -} - -// src/lostcity/network/outgoing/model/ObjCount.ts -class ObjCount extends ZoneMessage { - coord; - obj; - oldCount; - newCount; - constructor(coord, obj, oldCount, newCount) { - super(coord); - this.coord = coord; - this.obj = obj; - this.oldCount = oldCount; - this.newCount = newCount; - } -} - -// src/lostcity/network/outgoing/model/ObjReveal.ts -class ObjReveal extends ZoneMessage { - coord; - obj; - count; - receiverId; - constructor(coord, obj, count, receiverId) { - super(coord); - this.coord = coord; - this.obj = obj; - this.count = count; - this.receiverId = receiverId; - } -} - -// src/lostcity/network/outgoing/model/LocAnim.ts -class LocAnim extends ZoneMessage { - coord; - shape; - angle; - seq; - constructor(coord, shape, angle, seq) { - super(coord); - this.coord = coord; - this.shape = shape; - this.angle = angle; - this.seq = seq; - } -} - -// src/lostcity/network/outgoing/model/LocMerge.ts -class LocMerge extends ZoneMessage { - srcX; - srcZ; - shape; - angle; - locId; - startCycle; - endCycle; - pid; - east; - south; - west; - north; - constructor(srcX, srcZ, shape, angle, locId, startCycle, endCycle, pid, east, south, west, north) { - super(Position.packZoneCoord(srcX, srcZ)); - this.srcX = srcX; - this.srcZ = srcZ; - this.shape = shape; - this.angle = angle; - this.locId = locId; - this.startCycle = startCycle; - this.endCycle = endCycle; - this.pid = pid; - this.east = east; - this.south = south; - this.west = west; - this.north = north; - } -} - -// src/lostcity/network/outgoing/codec/MessageEncoder.ts -class MessageEncoder { - test(_2) { - return this.prot.length; - } -} - -// src/lostcity/network/225/outgoing/codec/IfOpenChatModalEncoder.ts -class IfOpenChatModalEncoder extends MessageEncoder { - prot = ServerProt.IF_OPENCHATMODAL; - encode(buf, message) { - buf.p2(message.component); - } -} - -// src/lostcity/network/outgoing/model/IfOpenChatModal.ts -class IfOpenChatModal extends OutgoingMessage { - component; - priority = ServerProtPriority.LOW; - constructor(component) { - super(); - this.component = component; - } -} - -// src/lostcity/network/outgoing/model/PlayerInfo.ts -class PlayerInfo extends OutgoingMessage { - buildArea; - level; - x; - z2; - originX; - originZ; - uid; - mask; - tele; - jump2; - walkDir; - runDir; - priority = ServerProtPriority.HIGH; - accumulator = 0; - constructor(buildArea, level, x, z2, originX, originZ, uid, mask, tele, jump2, walkDir, runDir) { - super(); - this.buildArea = buildArea; - this.level = level; - this.x = x; - this.z = z2; - this.originX = originX; - this.originZ = originZ; - this.uid = uid; - this.mask = mask; - this.tele = tele; - this.jump = jump2; - this.walkDir = walkDir; - this.runDir = runDir; - } -} - -// src/lostcity/network/225/outgoing/codec/PlayerInfoEncoder.ts -class PlayerInfoEncoder extends MessageEncoder { - static BITS_NEW = 11 + 5 + 5 + 1 + 1 + 11; - static BITS_RUN = 2 + 3 + 3 + 1 + 1; - static BITS_WALK = 2 + 3 + 1 + 1; - static BITS_EXTENDED = 2 + 1; - static BYTES_LIMIT = 4997; - prot = ServerProt.PLAYER_INFO; - encode(buf, message) { - const buildArea = message.buildArea; - buildArea.resize(); - this.writeLocalPlayer(buf, message); - this.writePlayers(buf, message); - this.writeNewPlayers(buf, message); - const extended = buildArea.extendedInfo; - if (extended.size > 0) { - for (const info of extended) { - const other = World_default.getPlayerByUid(info.id); - if (!other) { - continue; - } - this.writeUpdate(other, message, buf, info.id === message.uid, info.added); - } - } - buildArea.reset(); - } - test(_2) { - return PlayerInfoEncoder.BYTES_LIMIT; - } - writeLocalPlayer(bitBlock, message) { - const {buildArea, uid, level, x, z: z2, mask, tele, jump: jump2, walkDir, runDir} = message; - const player = World_default.getPlayerByUid(uid); - if (!player) { - return; - } - bitBlock.bits(); - bitBlock.pBit(1, tele || walkDir !== -1 || runDir !== -1 || mask > 0 ? 1 : 0); - if (tele) { - bitBlock.pBit(2, 3); - bitBlock.pBit(2, level); - bitBlock.pBit(7, Position.local(x)); - bitBlock.pBit(7, Position.local(z2)); - bitBlock.pBit(1, jump2 ? 1 : 0); - bitBlock.pBit(1, mask > 0 ? 1 : 0); - } else if (runDir !== -1) { - bitBlock.pBit(2, 2); - bitBlock.pBit(3, walkDir); - bitBlock.pBit(3, runDir); - bitBlock.pBit(1, mask > 0 ? 1 : 0); - } else if (walkDir !== -1) { - bitBlock.pBit(2, 1); - bitBlock.pBit(3, walkDir); - bitBlock.pBit(1, mask > 0 ? 1 : 0); - } else if (mask > 0) { - bitBlock.pBit(2, 0); - } - if (mask > 0) { - buildArea.extendedInfo.add({id: uid, added: false}); - message.accumulator += this.calculateUpdateSize(player, message, true, true); - } - } - writePlayers(bitBlock, message) { - const buildArea = message.buildArea; - bitBlock.pBit(8, buildArea.players.size); - for (const uid of buildArea.players) { - const other = World_default.getPlayerByUid(uid); - if (!other || other.tele || other.level !== message.level || !Position.isWithinDistanceSW(message, other, buildArea.viewDistance) || !other.checkLifeCycle(World_default.currentTick)) { - bitBlock.pBit(1, 1); - bitBlock.pBit(2, 3); - buildArea.players.delete(uid); - continue; - } - let extendedInfo = other.mask > 0; - const {walkDir, runDir} = other; - let bits = 0; - if (runDir !== -1) { - bits = PlayerInfoEncoder.BITS_RUN; - } else if (walkDir !== -1) { - bits = PlayerInfoEncoder.BITS_WALK; - } else if (extendedInfo) { - bits = PlayerInfoEncoder.BITS_EXTENDED; - } - const updateSize = extendedInfo ? this.calculateUpdateSize(other, message, false, false) : 0; - if (((bitBlock.bitPos + bits + 7 + 24) >>> 3) + bitBlock.pos + (message.accumulator += updateSize) > this.test(message)) { - extendedInfo = false; - } - bitBlock.pBit(1, walkDir !== -1 || runDir !== -1 || extendedInfo ? 1 : 0); - if (runDir !== -1) { - bitBlock.pBit(2, 2); - bitBlock.pBit(3, walkDir); - bitBlock.pBit(3, runDir); - bitBlock.pBit(1, extendedInfo ? 1 : 0); - } else if (walkDir !== -1) { - bitBlock.pBit(2, 1); - bitBlock.pBit(3, walkDir); - bitBlock.pBit(1, extendedInfo ? 1 : 0); - } else if (extendedInfo) { - bitBlock.pBit(2, 0); - } - if (extendedInfo) { - buildArea.extendedInfo.add({id: uid, added: false}); - } - } - } - writeNewPlayers(bitBlock, message) { - const buildArea = message.buildArea; - for (const other of buildArea.getNearbyPlayers(message.uid, message.x, message.z, message.originX, message.originZ)) { - const extendedInfo = !buildArea.hasAppearance(other.pid, other.appearanceHashCode); - const updateSize = extendedInfo ? this.calculateUpdateSize(other, message, false, true) : 0; - if (((bitBlock.bitPos + PlayerInfoEncoder.BITS_NEW + 7 + 24) >>> 3) + bitBlock.pos + (message.accumulator += updateSize) > this.test(message)) { - break; - } - bitBlock.pBit(11, other.pid); - bitBlock.pBit(5, other.x - message.x); - bitBlock.pBit(5, other.z - message.z); - bitBlock.pBit(1, other.jump ? 1 : 0); - bitBlock.pBit(1, extendedInfo ? 1 : 0); - if (extendedInfo) { - buildArea.extendedInfo.add({id: other.uid, added: true}); - } - buildArea.players.add(other.uid); - } - if (buildArea.extendedInfo.size > 0) { - bitBlock.pBit(11, 2047); - } - bitBlock.bytes(); - } - writeUpdate(player, message, out, self2 = false, newlyObserved = false) { - let mask = player.mask; - if (newlyObserved) { - mask |= Player2.APPEARANCE; - } - if (newlyObserved && (player.orientation !== -1 || player.faceX !== -1 || player.faceZ !== -1)) { - mask |= Player2.FACE_COORD; - } - if (newlyObserved && player.faceEntity !== -1) { - mask |= Player2.FACE_ENTITY; - } - if (mask > 255) { - mask |= Player2.BIG_UPDATE; - } - if (self2 && mask & Player2.CHAT) { - mask &= ~Player2.CHAT; - } - if (message.buildArea.hasAppearance(player.pid, player.appearanceHashCode)) { - mask &= ~Player2.APPEARANCE; - } - out.p1(mask & 255); - if (mask & Player2.BIG_UPDATE) { - out.p1(mask >> 8); - } - if (mask & Player2.APPEARANCE) { - out.p1(player.appearance.length); - out.pdata(player.appearance, 0, player.appearance.length); - message.buildArea.saveAppearance(player.pid, player.appearanceHashCode); - } - if (mask & Player2.ANIM) { - out.p2(player.animId); - out.p1(player.animDelay); - } - if (mask & Player2.FACE_ENTITY) { - if (player.faceEntity !== -1) { - player.alreadyFacedEntity = true; - } - out.p2(player.faceEntity); - } - if (mask & Player2.SAY) { - out.pjstr(player.chat ?? ''); - } - if (mask & Player2.DAMAGE) { - out.p1(player.damageTaken); - out.p1(player.damageType); - out.p1(player.levels[PlayerStat_default.HITPOINTS]); - out.p1(player.baseLevels[PlayerStat_default.HITPOINTS]); - } - if (mask & Player2.FACE_COORD) { - if (player.faceX !== -1) { - player.alreadyFacedCoord = true; - } - if (newlyObserved && player.faceX !== -1) { - out.p2(player.faceX); - out.p2(player.faceZ); - } else if (newlyObserved && player.orientation !== -1) { - const faceX = Position.moveX(player.x, player.orientation); - const faceZ = Position.moveZ(player.z, player.orientation); - out.p2(faceX * 2 + 1); - out.p2(faceZ * 2 + 1); - } else { - out.p2(player.faceX); - out.p2(player.faceZ); - } - } - if (mask & Player2.CHAT) { - out.p1(player.messageColor); - out.p1(player.messageEffect); - out.p1(player.messageType); - out.p1(player.message.length); - out.pdata(player.message, 0, player.message.length); - } - if (mask & Player2.SPOTANIM) { - out.p2(player.graphicId); - out.p2(player.graphicHeight); - out.p2(player.graphicDelay); - } - if (mask & Player2.EXACT_MOVE) { - out.p1(player.exactStartX - Position.zoneOrigin(message.originX)); - out.p1(player.exactStartZ - Position.zoneOrigin(message.originZ)); - out.p1(player.exactEndX - Position.zoneOrigin(message.originX)); - out.p1(player.exactEndZ - Position.zoneOrigin(message.originZ)); - out.p2(player.exactMoveStart); - out.p2(player.exactMoveEnd); - out.p1(player.exactMoveDirection); - } - } - calculateUpdateSize(player, message, self2 = false, newlyObserved = false) { - let length = 0; - let mask = player.mask; - if (newlyObserved) { - mask |= Player2.APPEARANCE; - } - if (newlyObserved && (player.orientation !== -1 || player.faceX !== -1 || player.faceZ !== -1)) { - mask |= Player2.FACE_COORD; - } - if (newlyObserved && player.faceEntity !== -1) { - mask |= Player2.FACE_ENTITY; - } - if (mask > 255) { - mask |= Player2.BIG_UPDATE; - } - if (self2 && mask & Player2.CHAT) { - mask &= ~Player2.CHAT; - } - if (message.buildArea.hasAppearance(player.pid, player.appearanceHashCode)) { - mask &= ~Player2.APPEARANCE; - } - length += 1; - if (mask & Player2.BIG_UPDATE) { - length += 1; - } - if (mask & Player2.APPEARANCE) { - length += 1; - length += player.appearance?.length ?? 0; - } - if (mask & Player2.ANIM) { - length += 3; - } - if (mask & Player2.FACE_ENTITY) { - length += 2; - } - if (mask & Player2.SAY) { - length += (player.chat?.length ?? 0) + 1; - } - if (mask & Player2.DAMAGE) { - length += 4; - } - if (mask & Player2.FACE_COORD) { - length += 4; - } - if (mask & Player2.CHAT) { - length += 4; - length += player.message?.length ?? 0; - } - if (mask & Player2.SPOTANIM) { - length += 6; - } - if (mask & Player2.EXACT_MOVE) { - length += 9; - } - return length; - } -} - -// src/lostcity/network/outgoing/model/RebuildNormal.ts -class RebuildNormal extends OutgoingMessage { - zoneX; - zoneZ; - priority = ServerProtPriority.HIGH; - constructor(zoneX, zoneZ) { - super(); - this.zoneX = zoneX; - this.zoneZ = zoneZ; - } - get mapsquares() { - const minX = this.zoneX - 6; - const maxX = this.zoneX + 6; - const minZ = this.zoneZ - 6; - const maxZ = this.zoneZ + 6; - const result = new Set(); - for (let x = minX; x <= maxX; x++) { - const mx = Position.mapsquare(x << 3); - for (let z2 = minZ; z2 <= maxZ; z2++) { - const mz = Position.mapsquare(z2 << 3); - result.add((mx << 8) | mz); - } - } - return result; - } -} - -// src/lostcity/network/225/outgoing/codec/RebuildNormalEncoder.ts -class RebuildNormalEncoder extends MessageEncoder { - prot = ServerProt.REBUILD_NORMAL; - encode(buf, message) { - buf.p2(message.zoneX); - buf.p2(message.zoneZ); - for (const packed of message.mapsquares) { - const x = packed >> 8; - const z2 = packed & 255; - buf.p1(x); - buf.p1(z2); - buf.p4(PRELOADED_CRC.get(`m${x}_${z2}`) ?? 0); - buf.p4(PRELOADED_CRC.get(`l${x}_${z2}`) ?? 0); - } - } - test(message) { - return 2 + 2 + message.mapsquares.size * (1 + 1 + 4 + 4); - } -} - -// src/lostcity/network/outgoing/model/DataLand.ts -class DataLand extends OutgoingMessage { - x; - z2; - offset; - length; - data; - priority = ServerProtPriority.HIGH; - constructor(x, z2, offset, length, data) { - super(); - this.x = x; - this.z = z2; - this.offset = offset; - this.length = length; - this.data = data; - } -} - -// src/lostcity/network/225/outgoing/codec/DataLandEncoder.ts -class DataLandEncoder extends MessageEncoder { - prot = ServerProt.DATA_LAND; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - buf.p2(message.offset); - buf.p2(message.length); - buf.pdata(message.data, 0, message.data.length); - } - test(message) { - return 1 + 1 + 2 + 2 + message.data.length; - } -} - -// src/lostcity/network/outgoing/model/DataLandDone.ts -class DataLandDone extends OutgoingMessage { - x; - z2; - priority = ServerProtPriority.HIGH; - constructor(x, z2) { - super(); - this.x = x; - this.z = z2; - } -} - -// src/lostcity/network/225/outgoing/codec/DataLandDoneEncoder.ts -class DataLandDoneEncoder extends MessageEncoder { - prot = ServerProt.DATA_LAND_DONE; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - } -} - -// src/lostcity/network/outgoing/model/DataLoc.ts -class DataLoc extends OutgoingMessage { - x; - z2; - offset; - length; - data; - priority = ServerProtPriority.HIGH; - constructor(x, z2, offset, length, data) { - super(); - this.x = x; - this.z = z2; - this.offset = offset; - this.length = length; - this.data = data; - } -} - -// src/lostcity/network/225/outgoing/codec/DataLocEncoder.ts -class DataLocEncoder extends MessageEncoder { - prot = ServerProt.DATA_LOC; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - buf.p2(message.offset); - buf.p2(message.length); - buf.pdata(message.data, 0, message.data.length); - } - test(message) { - return 1 + 1 + 2 + 2 + message.data.length; - } -} - -// src/lostcity/network/outgoing/model/DataLocDone.ts -class DataLocDone extends OutgoingMessage { - x; - z2; - priority = ServerProtPriority.HIGH; - constructor(x, z2) { - super(); - this.x = x; - this.z = z2; - } -} - -// src/lostcity/network/225/outgoing/codec/DataLocDoneEncoder.ts -class DataLocDoneEncoder extends MessageEncoder { - prot = ServerProt.DATA_LOC_DONE; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - } -} - -// src/lostcity/network/outgoing/model/CamLookAt.ts -class CamLookAt extends OutgoingMessage { - x; - z2; - height; - speed; - multiplier; - priority = ServerProtPriority.LOW; - constructor(x, z2, height, speed, multiplier) { - super(); - this.x = x; - this.z = z2; - this.height = height; - this.speed = speed; - this.multiplier = multiplier; - } -} - -// src/lostcity/network/225/outgoing/codec/CamLookAtEncoder.ts -class CamLookAtEncoder extends MessageEncoder { - prot = ServerProt.CAM_LOOKAT; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - buf.p2(message.height); - buf.p1(message.speed); - buf.p1(message.multiplier); - } -} - -// src/lostcity/network/outgoing/model/CamMoveTo.ts -class CamMoveTo extends OutgoingMessage { - x; - z2; - height; - speed; - multiplier; - priority = ServerProtPriority.LOW; - constructor(x, z2, height, speed, multiplier) { - super(); - this.x = x; - this.z = z2; - this.height = height; - this.speed = speed; - this.multiplier = multiplier; - } -} - -// src/lostcity/network/225/outgoing/codec/CamMoveToEncoder.ts -class CamMoveToEncoder extends MessageEncoder { - prot = ServerProt.CAM_MOVETO; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - buf.p2(message.height); - buf.p1(message.speed); - buf.p1(message.multiplier); - } -} - -// src/lostcity/network/outgoing/model/CamReset.ts -class CamReset extends OutgoingMessage { - priority = ServerProtPriority.LOW; -} - -// src/lostcity/network/225/outgoing/codec/CamResetEncoder.ts -class CamResetEncoder extends MessageEncoder { - prot = ServerProt.CAM_RESET; - encode(_2, __) {} -} - -// src/lostcity/network/outgoing/model/CamShake.ts -class CamShake extends OutgoingMessage { - type; - jitter; - amplitude; - frequency; - priority = ServerProtPriority.LOW; - constructor(type, jitter, amplitude, frequency) { - super(); - this.type = type; - this.jitter = jitter; - this.amplitude = amplitude; - this.frequency = frequency; - } -} - -// src/lostcity/network/225/outgoing/codec/CamShakeEncoder.ts -class CamShakeEncoder extends MessageEncoder { - prot = ServerProt.CAM_SHAKE; - encode(buf, message) { - buf.p1(message.type); - buf.p1(message.jitter); - buf.p1(message.amplitude); - buf.p1(message.frequency); - } -} - -// src/lostcity/network/outgoing/model/ChatFilterSettings.ts -class ChatFilterSettings extends OutgoingMessage { - publicChat; - privateChat; - tradeDuel; - priority = ServerProtPriority.HIGH; - constructor(publicChat, privateChat, tradeDuel) { - super(); - this.publicChat = publicChat; - this.privateChat = privateChat; - this.tradeDuel = tradeDuel; - } -} - -// src/lostcity/network/225/outgoing/codec/ChatFilterSettingsEncoder.ts -class ChatFilterSettingsEncoder extends MessageEncoder { - prot = ServerProt.CHAT_FILTER_SETTINGS; - encode(buf, message) { - buf.p1(message.publicChat); - buf.p1(message.privateChat); - buf.p1(message.tradeDuel); - } -} - -// src/lostcity/network/outgoing/model/EnableTracking.ts -class EnableTracking extends OutgoingMessage { - priority = ServerProtPriority.LOW; -} - -// src/lostcity/network/225/outgoing/codec/EnableTrackingEncoder.ts -class EnableTrackingEncoder extends MessageEncoder { - prot = ServerProt.ENABLE_TRACKING; - encode(_2, __) {} -} - -// src/lostcity/network/outgoing/model/FinishTracking.ts -class FinishTracking extends OutgoingMessage { - priority = ServerProtPriority.LOW; -} - -// src/lostcity/network/225/outgoing/codec/FinishTrackingEncoder.ts -class FinishTrackingEncoder extends MessageEncoder { - prot = ServerProt.FINISH_TRACKING; - encode(_2, __) {} -} - -// src/lostcity/network/225/outgoing/codec/HintArrowEncoder.ts -class HintArrowEncoder extends MessageEncoder { - prot = ServerProt.HINT_ARROW; - encode(buf, message) { - const {type, nid, pid, x, z: z2, y: y2} = message; - if (type === 1) { - buf.p1(type); - buf.p2(nid); - buf.p2(0); - buf.p1(0); - } else if (type >= 2 && type <= 6) { - buf.p1(type); - buf.p2(x); - buf.p2(z2); - buf.p1(y2); - } else if (type === 10) { - buf.p1(type); - buf.p2(pid); - buf.p2(0); - buf.p1(0); - } else if (type === -1) { - buf.p1(-1); - buf.p2(0); - buf.p2(0); - buf.p1(0); - } - } -} - -// src/lostcity/network/225/outgoing/codec/IfCloseEncoder.ts -class IfCloseEncoder extends MessageEncoder { - prot = ServerProt.IF_CLOSE; - encode(_2, __) {} -} - -// src/lostcity/network/outgoing/model/IfOpenMainModal.ts -class IfOpenMainModal extends OutgoingMessage { - component; - priority = ServerProtPriority.LOW; - constructor(component) { - super(); - this.component = component; - } -} - -// src/lostcity/network/225/outgoing/codec/IfOpenMainModalEncoder.ts -class IfOpenMainModalEncoder extends MessageEncoder { - prot = ServerProt.IF_OPENMAINMODAL; - encode(buf, message) { - buf.p2(message.component); - } -} - -// src/lostcity/network/outgoing/model/IfOpenMainSideModal.ts -class IfOpenMainSideModal extends OutgoingMessage { - main; - side; - priority = ServerProtPriority.LOW; - constructor(main, side) { - super(); - this.main = main; - this.side = side; - } -} - -// src/lostcity/network/225/outgoing/codec/IfOpenMainSideModalEncoder.ts -class IfOpenMainSideModalEncoder extends MessageEncoder { - prot = ServerProt.IF_OPENMAINSIDEMODAL; - encode(buf, message) { - buf.p2(message.main); - buf.p2(message.side); - } -} - -// src/lostcity/network/outgoing/model/IfOpenSideModal.ts -class IfOpenSideModal extends OutgoingMessage { - component; - priority = ServerProtPriority.LOW; - constructor(component) { - super(); - this.component = component; - } -} - -// src/lostcity/network/225/outgoing/codec/IfOpenSideModalEncoder.ts -class IfOpenSideModalEncoder extends MessageEncoder { - prot = ServerProt.IF_OPENSIDEMODAL; - encode(buf, message) { - buf.p2(message.component); - } -} - -// src/lostcity/network/225/outgoing/codec/IfOpenSideOverlayEncoder.ts -class IfOpenSideOverlayEncoder extends MessageEncoder { - prot = ServerProt.IF_OPENSIDEOVERLAY; - encode(buf, message) { - buf.p2(message.component); - buf.p1(message.tab); - } -} - -// src/lostcity/network/outgoing/model/IfSetAnim.ts -class IfSetAnim extends OutgoingMessage { - component; - seq; - priority = ServerProtPriority.LOW; - constructor(component, seq) { - super(); - this.component = component; - this.seq = seq; - } -} - -// src/lostcity/network/225/outgoing/codec/IfSetAnimEncoder.ts -class IfSetAnimEncoder extends MessageEncoder { - prot = ServerProt.IF_SETANIM; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.seq); - } -} - -// src/lostcity/network/outgoing/model/IfSetColour.ts -class IfSetColour extends OutgoingMessage { - component; - colour; - priority = ServerProtPriority.LOW; - constructor(component, colour) { - super(); - this.component = component; - this.colour = colour; - } -} - -// src/lostcity/network/225/outgoing/codec/IfSetColourEncoder.ts -class IfSetColourEncoder extends MessageEncoder { - prot = ServerProt.IF_SETCOLOUR; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.colour); - } -} - -// src/lostcity/network/outgoing/model/IfSetHide.ts -class IfSetHide extends OutgoingMessage { - component; - hidden; - priority = ServerProtPriority.LOW; - constructor(component, hidden) { - super(); - this.component = component; - this.hidden = hidden; - } -} - -// src/lostcity/network/225/outgoing/codec/IfSetHideEncoder.ts -class IfSetHideEncoder extends MessageEncoder { - prot = ServerProt.IF_SETHIDE; - encode(buf, message) { - buf.p2(message.component); - buf.pbool(message.hidden); - } -} - -// src/lostcity/network/outgoing/model/IfSetModel.ts -class IfSetModel extends OutgoingMessage { - component; - model; - priority = ServerProtPriority.LOW; - constructor(component, model) { - super(); - this.component = component; - this.model = model; - } -} - -// src/lostcity/network/225/outgoing/codec/IfSetModelEncoder.ts -class IfSetModelEncoder extends MessageEncoder { - prot = ServerProt.IF_SETMODEL; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.model); - } -} - -// src/lostcity/network/outgoing/model/IfSetNpcHead.ts -class IfSetNpcHead extends OutgoingMessage { - component; - npc; - priority = ServerProtPriority.LOW; - constructor(component, npc) { - super(); - this.component = component; - this.npc = npc; - } -} - -// src/lostcity/network/225/outgoing/codec/IfSetNpcHeadEncoder.ts -class IfSetNpcHeadEncoder extends MessageEncoder { - prot = ServerProt.IF_SETNPCHEAD; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.npc); - } -} - -// src/lostcity/network/outgoing/model/IfSetObject.ts -class IfSetObject extends OutgoingMessage { - component; - obj; - scale; - priority = ServerProtPriority.LOW; - constructor(component, obj, scale) { - super(); - this.component = component; - this.obj = obj; - this.scale = scale; - } -} - -// src/lostcity/network/225/outgoing/codec/IfSetObjectEncoder.ts -class IfSetObjectEncoder extends MessageEncoder { - prot = ServerProt.IF_SETOBJECT; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.obj); - buf.p2(message.scale); - } -} - -// src/lostcity/network/outgoing/model/IfSetPlayerHead.ts -class IfSetPlayerHead extends OutgoingMessage { - component; - priority = ServerProtPriority.LOW; - constructor(component) { - super(); - this.component = component; - } -} - -// src/lostcity/network/225/outgoing/codec/IfSetPlayerHeadEncoder.ts -class IfSetPlayerHeadEncoder extends MessageEncoder { - prot = ServerProt.IF_SETPLAYERHEAD; - encode(buf, message) { - buf.p2(message.component); - } -} - -// src/lostcity/network/outgoing/model/IfSetPosition.ts -class IfSetPosition extends OutgoingMessage { - component; - x; - y2; - priority = ServerProtPriority.LOW; - constructor(component, x, y2) { - super(); - this.component = component; - this.x = x; - this.y = y2; - } -} - -// src/lostcity/network/225/outgoing/codec/IfSetPositionEncoder.ts -class IfSetPositionEncoder extends MessageEncoder { - prot = ServerProt.IF_SETPOSITION; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.x); - buf.p2(message.y); - } -} - -// src/lostcity/network/outgoing/model/IfSetRecol.ts -class IfSetRecol extends OutgoingMessage { - component; - src; - dst; - priority = ServerProtPriority.LOW; - constructor(component, src, dst) { - super(); - this.component = component; - this.src = src; - this.dst = dst; - } -} - -// src/lostcity/network/225/outgoing/codec/IfSetRecolEncoder.ts -class IfSetRecolEncoder extends MessageEncoder { - prot = ServerProt.IF_SETRECOL; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.src); - buf.p2(message.dst); - } -} - -// src/lostcity/network/outgoing/model/IfSetText.ts -class IfSetText extends OutgoingMessage { - component; - text; - priority = ServerProtPriority.LOW; - constructor(component, text) { - super(); - this.component = component; - this.text = text; - } -} - -// src/lostcity/network/225/outgoing/codec/IfSetTextEncoder.ts -class IfSetTextEncoder extends MessageEncoder { - prot = ServerProt.IF_SETTEXT; - encode(buf, message) { - buf.p2(message.component); - buf.pjstr(message.text); - } - test(message) { - return 2 + 1 + message.text.length; - } -} - -// src/lostcity/network/outgoing/model/IfShowSide.ts -class IfShowSide extends OutgoingMessage { - tab; - priority = ServerProtPriority.LOW; - constructor(tab) { - super(); - this.tab = tab; - } -} - -// src/lostcity/network/225/outgoing/codec/IfShowSideEncoder.ts -class IfShowSideEncoder extends MessageEncoder { - prot = ServerProt.IF_SHOWSIDE; - encode(buf, message) { - buf.p1(message.tab); - } -} - -// src/lostcity/network/225/outgoing/codec/LastLoginInfoEncoder.ts -class LastLoginInfoEncoder extends MessageEncoder { - prot = ServerProt.LAST_LOGIN_INFO; - encode(buf, message) { - buf.p4(message.lastLoginIp); - buf.p2(message.daysSinceLogin); - buf.p1(message.daysSinceRecoveryChange); - buf.p2(message.unreadMessageCount); - } -} - -// src/lostcity/network/225/outgoing/prot/ZoneProt.ts -class ZoneProt extends ServerProt { - static LOC_MERGE = new ZoneProt(23, 14); - static LOC_ANIM = new ZoneProt(42, 4); - static OBJ_DEL = new ZoneProt(49, 3); - static OBJ_REVEAL = new ZoneProt(50, 7); - static LOC_ADD_CHANGE = new ZoneProt(59, 4); - static MAP_PROJANIM = new ZoneProt(69, 15); - static LOC_DEL = new ZoneProt(76, 2); - static OBJ_COUNT = new ZoneProt(151, 7); - static MAP_ANIM = new ZoneProt(191, 6); - static OBJ_ADD = new ZoneProt(223, 5); -} - -// src/lostcity/network/outgoing/codec/ZoneMessageEncoder.ts -class ZoneMessageEncoder extends MessageEncoder { - enclose(message) { - const buf = new Packet(new Uint8Array(1 + this.prot.length)); - buf.p1(this.prot.id); - this.encode(buf, message); - return buf.data; - } -} - -// src/lostcity/network/225/outgoing/codec/LocAddChangeEncoder.ts -class LocAddChangeEncoder extends ZoneMessageEncoder { - prot = ZoneProt.LOC_ADD_CHANGE; - encode(buf, message) { - buf.p1(message.coord); - buf.p1((message.shape << 2) | (message.angle & 3)); - buf.p2(message.loc); - } -} - -// src/lostcity/network/225/outgoing/codec/LocAnimEncoder.ts -class LocAnimEncoder extends ZoneMessageEncoder { - prot = ZoneProt.LOC_ANIM; - encode(buf, message) { - buf.p1(message.coord); - buf.p1((message.shape << 2) | (message.angle & 3)); - buf.p2(message.seq); - } -} - -// src/lostcity/network/225/outgoing/codec/LocDelEncoder.ts -class LocDelEncoder extends ZoneMessageEncoder { - prot = ZoneProt.LOC_DEL; - encode(buf, message) { - buf.p1(message.coord); - buf.p1((message.shape << 2) | (message.angle & 3)); - } -} - -// src/lostcity/network/225/outgoing/codec/LocMergeEncoder.ts -class LocMergeEncoder extends ZoneMessageEncoder { - prot = ZoneProt.LOC_MERGE; - encode(buf, message) { - buf.p1(message.coord); - buf.p1((message.shape << 2) | (message.angle & 3)); - buf.p2(message.locId); - buf.p2(message.startCycle); - buf.p2(message.endCycle); - buf.p2(message.pid); - buf.p1(message.east - message.srcX); - buf.p1(message.south - message.srcZ); - buf.p1(message.west - message.srcX); - buf.p1(message.north - message.srcZ); - } -} - -// src/lostcity/network/outgoing/model/Logout.ts -class Logout extends OutgoingMessage { - priority = ServerProtPriority.HIGH; -} - -// src/lostcity/network/225/outgoing/codec/LogoutEncoder.ts -class LogoutEncoder extends MessageEncoder { - prot = ServerProt.LOGOUT; - encode(_2, __) {} -} - -// src/lostcity/network/225/outgoing/codec/MapAnimEncoder.ts -class MapAnimEncoder extends ZoneMessageEncoder { - prot = ZoneProt.MAP_ANIM; - encode(buf, message) { - buf.p1(message.coord); - buf.p2(message.spotanim); - buf.p1(message.height); - buf.p2(message.delay); - } -} - -// src/lostcity/network/225/outgoing/codec/MapProjAnimEncoder.ts -class MapProjAnimEncoder extends ZoneMessageEncoder { - prot = ZoneProt.MAP_PROJANIM; - encode(buf, message) { - buf.p1(message.coord); - buf.p1(message.dstX - message.srcX); - buf.p1(message.dstZ - message.srcZ); - buf.p2(message.target); - buf.p2(message.spotanim); - buf.p1(message.srcHeight); - buf.p1(message.dstHeight); - buf.p2(message.startDelay); - buf.p2(message.endDelay); - buf.p1(message.peak); - buf.p1(message.arc); - } -} - -// src/lostcity/network/225/outgoing/codec/MessageGameEncoder.ts -class MessageGameEncoder extends MessageEncoder { - prot = ServerProt.MESSAGE_GAME; - encode(buf, message) { - buf.pjstr(message.msg); - } - test(message) { - return 1 + message.msg.length; - } -} - -// src/jagex2/wordenc/WordPack.ts -class WordPack { - static CHAR_LOOKUP = [ - ' ', - 'e', - 't', - 'a', - 'o', - 'i', - 'h', - 'n', - 's', - 'r', - 'd', - 'l', - 'u', - 'm', - 'w', - 'c', - 'y', - 'f', - 'g', - 'p', - 'b', - 'v', - 'k', - 'x', - 'j', - 'q', - 'z', - '0', - '1', - '2', - '3', - '4', - '5', - '6', - '7', - '8', - '9', - ' ', - '!', - '?', - '.', - ',', - ':', - ';', - '(', - ')', - '-', - '&', - '*', - '\\', - "'", - '@', - '#', - '+', - '=', - '\xA3', - '$', - '%', - '"', - '[', - ']' - ]; - static unpack(packet, length) { - const charBuffer = []; - let pos = 0; - let carry = -1; - let nibble; - for (let i = 0; i < length && pos < 80; i++) { - const data = packet.g1(); - nibble = (data >> 4) & 15; - if (carry !== -1) { - charBuffer[pos++] = this.CHAR_LOOKUP[(carry << 4) + nibble - 195]; - carry = -1; - } else if (nibble < 13) { - charBuffer[pos++] = this.CHAR_LOOKUP[nibble]; - } else { - carry = nibble; - } - nibble = data & 15; - if (carry != -1) { - charBuffer[pos++] = this.CHAR_LOOKUP[(carry << 4) + nibble - 195]; - carry = -1; - } else if (nibble < 13) { - charBuffer[pos++] = this.CHAR_LOOKUP[nibble]; - } else { - carry = nibble; - } - } - return this.toSentenceCase(charBuffer.slice(0, pos).join('')); - } - static pack(packet, input) { - if (input.length > 80) { - input = input.substring(0, 80); - } - input = input.toLowerCase(); - let carry = -1; - for (let i = 0; i < input.length; i++) { - const char = input.charAt(i); - let index = 0; - for (let j = 0; j < this.CHAR_LOOKUP.length; j++) { - if (char === this.CHAR_LOOKUP[j]) { - index = j; - break; - } - } - if (index > 12) { - index += 195; - } - if (carry == -1) { - if (index < 13) { - carry = index; - } else { - packet.p1(index); - } - } else if (index < 13) { - packet.p1((carry << 4) + index); - carry = -1; - } else { - packet.p1((carry << 4) + (index >> 4)); - carry = index & 15; - } - } - if (carry != -1) { - packet.p1(carry << 4); - } - } - static toSentenceCase(input) { - const chars = [...input.toLowerCase()]; - let punctuation = true; - for (let index = 0; index < chars.length; index++) { - const char = chars[index]; - if (punctuation && char >= 'a' && char <= 'z') { - chars[index] = char.toUpperCase(); - punctuation = false; - } - if (char === '.' || char === '!') { - punctuation = true; - } - } - return chars.join(''); - } -} - -// src/lostcity/network/225/outgoing/codec/MessagePrivateEncoder.ts -class MessagePrivateEncoder extends MessageEncoder { - prot = ServerProt.MESSAGE_PRIVATE; - encode(buf, message) { - buf.p8(message.from); - buf.p4(message.messageId); - buf.p1(message.staffModLevel); - WordPack.pack(buf, WordEnc2.filter(message.msg)); - } - test(message) { - return 8 + 4 + 1 + 1 + message.msg.length; - } -} - -// src/lostcity/network/outgoing/model/MessagePrivate.ts -class MessagePrivate extends OutgoingMessage { - from; - messageId; - staffModLevel; - msg; - priority = ServerProtPriority.HIGH; - constructor(from, messageId, staffModLevel, msg) { - super(); - this.from = from; - this.messageId = messageId; - this.staffModLevel = staffModLevel; - this.msg = msg; - } -} - -// src/lostcity/network/225/outgoing/codec/MidiJingleEncoder.ts -class MidiJingleEncoder extends MessageEncoder { - prot = ServerProt.MIDI_JINGLE; - encode(buf, message) { - buf.p2(message.delay); - buf.p4(message.data.length); - buf.pdata(message.data, 0, message.data.length); - } - test(message) { - return 2 + 4 + message.data.length; - } -} - -// src/lostcity/network/225/outgoing/codec/MidiSongEncoder.ts -class MidiSongEncoder extends MessageEncoder { - prot = ServerProt.MIDI_SONG; - encode(buf, message) { - buf.pjstr(message.name); - buf.p4(message.crc); - buf.p4(message.length); - } - test(message) { - return 1 + message.name.length + 4 + 4; - } -} - -// src/lostcity/network/225/outgoing/codec/ObjAddEncoder.ts -class ObjAddEncoder extends ZoneMessageEncoder { - prot = ZoneProt.OBJ_ADD; - encode(buf, message) { - buf.p1(message.coord); - buf.p2(message.obj); - buf.p2(Math.min(message.count, 65535)); - } -} - -// src/lostcity/network/225/outgoing/codec/ObjCountEncoder.ts -class ObjCountEncoder extends ZoneMessageEncoder { - prot = ZoneProt.OBJ_COUNT; - encode(buf, message) { - buf.p1(message.coord); - buf.p2(message.obj); - buf.p2(Math.min(message.oldCount, 65535)); - buf.p2(Math.min(message.newCount, 65535)); - } -} - -// src/lostcity/network/225/outgoing/codec/ObjDelEncoder.ts -class ObjDelEncoder extends ZoneMessageEncoder { - prot = ZoneProt.OBJ_DEL; - encode(buf, message) { - buf.p1(message.coord); - buf.p2(message.obj); - } -} - -// src/lostcity/network/225/outgoing/codec/ObjRevealEncoder.ts -class ObjRevealEncoder extends ZoneMessageEncoder { - prot = ZoneProt.OBJ_REVEAL; - encode(buf, message) { - buf.p1(message.coord); - buf.p2(message.obj); - buf.p2(Math.min(message.count, 65535)); - buf.p2(message.receiverId); - } -} - -// src/lostcity/network/outgoing/model/PCountDialog.ts -class PCountDialog extends OutgoingMessage { - priority = ServerProtPriority.LOW; -} - -// src/lostcity/network/225/outgoing/codec/PCountDialogEncoder.ts -class PCountDialogEncoder extends MessageEncoder { - prot = ServerProt.P_COUNTDIALOG; - encode(_2, __) {} -} - -// src/lostcity/network/225/outgoing/codec/ResetAnimsEncoder.ts -class ResetAnimsEncoder extends MessageEncoder { - prot = ServerProt.RESET_ANIMS; - encode(_2, __) {} -} - -// src/lostcity/network/225/outgoing/codec/ResetClientVarCacheEncoder.ts -class ResetClientVarCacheEncoder extends MessageEncoder { - prot = ServerProt.RESET_CLIENT_VARCACHE; - encode(_2, __) {} -} - -// src/lostcity/network/outgoing/model/SetMultiway.ts -class SetMultiway extends OutgoingMessage { - hidden; - priority = ServerProtPriority.LOW; - constructor(hidden) { - super(); - this.hidden = hidden; - } -} - -// src/lostcity/network/225/outgoing/codec/SetMultiwayEncoder.ts -class SetMultiwayEncoder extends MessageEncoder { - prot = ServerProt.SET_MULTIWAY; - encode(buf, message) { - buf.pbool(message.hidden); - } -} - -// src/lostcity/network/outgoing/model/SynthSound.ts -class SynthSound extends OutgoingMessage { - synth; - loops; - delay; - priority = ServerProtPriority.LOW; - constructor(synth, loops, delay) { - super(); - this.synth = synth; - this.loops = loops; - this.delay = delay; - } -} - -// src/lostcity/network/225/outgoing/codec/SynthSoundEncoder.ts -class SynthSoundEncoder extends MessageEncoder { - prot = ServerProt.SYNTH_SOUND; - encode(buf, message) { - buf.p2(message.synth); - buf.p1(message.loops); - buf.p2(message.delay); - } -} - -// src/lostcity/network/outgoing/model/TutorialFlashSide.ts -class TutorialFlashSide extends OutgoingMessage { - tab; - priority = ServerProtPriority.LOW; - constructor(tab) { - super(); - this.tab = tab; - } -} - -// src/lostcity/network/225/outgoing/codec/TutorialFlashSideEncoder.ts -class TutorialFlashSideEncoder extends MessageEncoder { - prot = ServerProt.TUTORIAL_FLASHSIDE; - encode(buf, message) { - buf.p1(message.tab); - } -} - -// src/lostcity/network/225/outgoing/codec/TutorialOpenChatEncoder.ts -class TutorialOpenChatEncoder extends MessageEncoder { - prot = ServerProt.TUTORIAL_OPENCHAT; - encode(buf, message) { - buf.p2(message.component); - } -} - -// src/lostcity/network/225/outgoing/codec/UnsetMapFlagEncoder.ts -class UnsetMapFlagEncoder extends MessageEncoder { - prot = ServerProt.UNSET_MAP_FLAG; - encode(_2, __) {} -} - -// src/lostcity/network/outgoing/model/UpdateFriendList.ts -class UpdateFriendList extends OutgoingMessage { - name; - nodeId; - priority = ServerProtPriority.LOW; - constructor(name, nodeId) { - super(); - this.name = name; - this.nodeId = nodeId; - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateFriendListEncoder.ts -class UpdateFriendListEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_FRIENDLIST; - encode(buf, message) { - buf.p8(message.name); - buf.p1(message.nodeId); - } -} - -// src/lostcity/network/outgoing/model/UpdateIgnoreList.ts -class UpdateIgnoreList extends OutgoingMessage { - names; - priority = ServerProtPriority.LOW; - constructor(names) { - super(); - this.names = names; - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateIgnoreListEncoder.ts -class UpdateIgnoreListEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_IGNORELIST; - encode(buf, message) { - for (const name of message.names) { - buf.p8(name); - } - } - test(message) { - return 8 * message.names.length; - } -} - -// src/lostcity/network/outgoing/model/UpdateInvFull.ts -class UpdateInvFull extends OutgoingMessage { - component; - inv; - priority = ServerProtPriority.HIGH; - constructor(component, inv) { - super(); - this.component = component; - this.inv = inv; - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateInvFullEncoder.ts -class UpdateInvFullEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_INV_FULL; - encode(buf, message) { - const {component, inv} = message; - const comType = Component.get(component); - const size = Math.min(inv.capacity, comType.width * comType.height); - buf.p2(component); - buf.p1(size); - for (let slot = 0; slot < size; slot++) { - const obj = inv.get(slot); - if (obj) { - buf.p2(obj.id + 1); - if (obj.count >= 255) { - buf.p1(255); - buf.p4(obj.count); - } else { - buf.p1(obj.count); - } - } else { - buf.p2(0); - buf.p1(0); - } - } - } - test(message) { - const {component, inv} = message; - const comType = Component.get(component); - const size = Math.min(inv.capacity, comType.width * comType.height); - let length = 0; - length += 3; - for (let slot = 0; slot < size; slot++) { - const obj = inv.get(slot); - if (obj) { - length += 2; - if (obj.count >= 255) { - length += 5; - } else { - length += 1; - } - } else { - length += 3; - } - } - return length; - } -} - -// src/lostcity/network/outgoing/model/UpdateInvPartial.ts -class UpdateInvPartial extends OutgoingMessage { - component; - inv; - priority = ServerProtPriority.HIGH; - slots; - constructor(component, inv, ...slots) { - super(); - this.component = component; - this.inv = inv; - this.slots = slots; - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateInvPartialEncoder.ts -class UpdateInvPartialEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_INV_PARTIAL; - encode(buf, message) { - const {component, inv} = message; - buf.p2(component); - for (const slot of message.slots) { - const obj = inv.get(slot); - buf.p1(slot); - if (obj) { - buf.p2(obj.id + 1); - if (obj.count >= 255) { - buf.p1(255); - buf.p4(obj.count); - } else { - buf.p1(obj.count); - } - } else { - buf.p2(0); - buf.p1(0); - } - } - } - test(message) { - const {inv} = message; - let length = 0; - length += 2; - for (const slot of message.slots) { - const obj = inv.get(slot); - length += 1; - if (obj) { - length += 2; - if (obj.count >= 255) { - length += 5; - } else { - length += 1; - } - } else { - length += 3; - } - } - return length; - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateInvStopTransmitEncoder.ts -class UpdateInvStopTransmitEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_INV_STOP_TRANSMIT; - encode(buf, message) { - buf.p2(message.component); - } -} - -// src/lostcity/network/outgoing/model/UpdateRunEnergy.ts -class UpdateRunEnergy extends OutgoingMessage { - energy; - priority = ServerProtPriority.LOW; - constructor(energy) { - super(); - this.energy = energy; - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateRunEnergyEncoder.ts -class UpdateRunEnergyEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_RUNENERGY; - encode(buf, message) { - buf.p1((message.energy / 100) | 0); - } -} - -// src/lostcity/network/outgoing/model/UpdateRunWeight.ts -class UpdateRunWeight extends OutgoingMessage { - kg; - priority = ServerProtPriority.LOW; - constructor(kg) { - super(); - this.kg = kg; - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateRunWeightEncoder.ts -class UpdateRunWeightEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_RUNWEIGHT; - encode(buf, message) { - buf.p2(message.kg); - } -} - -// src/lostcity/network/outgoing/model/UpdateStat.ts -class UpdateStat extends OutgoingMessage { - stat; - exp; - level; - priority = ServerProtPriority.LOW; - constructor(stat, exp, level) { - super(); - this.stat = stat; - this.exp = exp; - this.level = level; - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateStatEncoder.ts -class UpdateStatEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_STAT; - encode(buf, message) { - buf.p1(message.stat); - buf.p4((message.exp / 10) | 0); - buf.p1(message.level); - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateUid192Encoder.ts -class UpdateUid192Encoder extends MessageEncoder { - prot = ServerProt.UPDATE_UID192; - encode(buf, message) { - buf.p2(message.uid); - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateZoneFullFollowsEncoder.ts -class UpdateZoneFullFollowsEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_ZONE_FULL_FOLLOWS; - encode(buf, message) { - buf.p1((message.zoneX << 3) - Position.zoneOrigin(message.originX)); - buf.p1((message.zoneZ << 3) - Position.zoneOrigin(message.originZ)); - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateZonePartialFollowsEncoder.ts -class UpdateZonePartialFollowsEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_ZONE_PARTIAL_FOLLOWS; - encode(buf, message) { - buf.p1((message.zoneX << 3) - Position.zoneOrigin(message.originX)); - buf.p1((message.zoneZ << 3) - Position.zoneOrigin(message.originZ)); - } -} - -// src/lostcity/network/225/outgoing/codec/UpdateZonePartialEnclosedEncoder.ts -class UpdateZonePartialEnclosedEncoder extends MessageEncoder { - prot = ServerProt.UPDATE_ZONE_PARTIAL_ENCLOSED; - encode(buf, message) { - buf.p1((message.zoneX << 3) - Position.zoneOrigin(message.originX)); - buf.p1((message.zoneZ << 3) - Position.zoneOrigin(message.originZ)); - buf.pdata(message.data, 0, message.data.length); - } - test(message) { - return 1 + 1 + message.data.length; - } -} - -// src/lostcity/network/225/outgoing/codec/VarpLargeEncoder.ts -class VarpLargeEncoder extends MessageEncoder { - prot = ServerProt.VARP_LARGE; - encode(buf, message) { - buf.p2(message.varp); - buf.p4(message.value); - } -} - -// src/lostcity/network/225/outgoing/codec/VarpSmallEncoder.ts -class VarpSmallEncoder extends MessageEncoder { - prot = ServerProt.VARP_SMALL; - encode(buf, message) { - buf.p2(message.varp); - buf.p1(message.value); - } -} - -// src/lostcity/network/outgoing/model/NpcInfo.ts -class NpcInfo extends OutgoingMessage { - buildArea; - level; - x; - z2; - originX; - originZ; - priority = ServerProtPriority.HIGH; - accumulator = 0; - constructor(buildArea, level, x, z2, originX, originZ) { - super(); - this.buildArea = buildArea; - this.level = level; - this.x = x; - this.z = z2; - this.originX = originX; - this.originZ = originZ; - } -} - -// src/lostcity/network/225/outgoing/codec/NpcInfoEncoder.ts -class NpcInfoEncoder extends MessageEncoder { - static BITS_NEW = 13 + 11 + 5 + 5 + 1; - static BITS_RUN = 2 + 3 + 3 + 1 + 1; - static BITS_WALK = 2 + 3 + 1 + 1; - static BITS_EXTENDED = 2 + 1; - static BYTES_LIMIT = 4997; - prot = ServerProt.NPC_INFO; - encode(buf, message) { - const buildArea = message.buildArea; - this.writeNpcs(buf, message); - this.writeNewNpcs(buf, message); - const extended = buildArea.extendedInfo; - if (extended.size > 0) { - for (const info of extended) { - const npc = World_default.getNpc(info.id); - if (!npc) { - continue; - } - this.writeUpdate(npc, buf, info.added); - } - } - buildArea.reset(); - } - test(_2) { - return NpcInfoEncoder.BYTES_LIMIT; - } - writeNpcs(bitBlock, message) { - const buildArea = message.buildArea; - bitBlock.bits(); - bitBlock.pBit(8, buildArea.npcs.size); - for (const nid of buildArea.npcs) { - const npc = World_default.getNpc(nid); - if (!npc || npc.tele || npc.level !== message.level || !Position.isWithinDistanceSW(message, npc, 16) || !npc.checkLifeCycle(World_default.currentTick)) { - bitBlock.pBit(1, 1); - bitBlock.pBit(2, 3); - buildArea.npcs.delete(nid); - continue; - } - let extendedInfo = npc.mask > 0; - const {walkDir, runDir} = npc; - let bits = 0; - if (runDir !== -1) { - bits = NpcInfoEncoder.BITS_RUN; - } else if (walkDir !== -1) { - bits = NpcInfoEncoder.BITS_WALK; - } else if (extendedInfo) { - bits = NpcInfoEncoder.BITS_EXTENDED; - } - const updateSize = extendedInfo ? this.calculateUpdateSize(npc, false) : 0; - if (((bitBlock.bitPos + bits + 7 + 24) >>> 3) + bitBlock.pos + (message.accumulator += updateSize) > this.test(message)) { - extendedInfo = false; - } - bitBlock.pBit(1, runDir !== -1 || walkDir !== -1 || extendedInfo ? 1 : 0); - if (runDir !== -1) { - bitBlock.pBit(2, 2); - bitBlock.pBit(3, walkDir); - bitBlock.pBit(3, runDir); - bitBlock.pBit(1, extendedInfo ? 1 : 0); - } else if (walkDir !== -1) { - bitBlock.pBit(2, 1); - bitBlock.pBit(3, walkDir); - bitBlock.pBit(1, extendedInfo ? 1 : 0); - } else if (extendedInfo) { - bitBlock.pBit(2, 0); - } - if (extendedInfo) { - buildArea.extendedInfo.add({id: nid, added: false}); - } - } - } - writeNewNpcs(bitBlock, message) { - const buildArea = message.buildArea; - for (const npc of buildArea.getNearbyNpcs(message.x, message.z, message.originX, message.originZ)) { - const extendedInfo = npc.mask > 0 || npc.orientation !== -1 || npc.faceX !== -1 || npc.faceZ !== -1 || npc.faceEntity !== -1; - const updateSize = extendedInfo ? this.calculateUpdateSize(npc, true) : 0; - if (((bitBlock.bitPos + NpcInfoEncoder.BITS_NEW + 7 + 24) >>> 3) + bitBlock.pos + (message.accumulator += updateSize) > this.test(message)) { - break; - } - bitBlock.pBit(13, npc.nid); - bitBlock.pBit(11, npc.type); - bitBlock.pBit(5, npc.x - message.x); - bitBlock.pBit(5, npc.z - message.z); - bitBlock.pBit(1, extendedInfo ? 1 : 0); - buildArea.npcs.add(npc.nid); - if (extendedInfo) { - buildArea.extendedInfo.add({id: npc.nid, added: true}); - } - } - if (buildArea.extendedInfo.size > 0) { - bitBlock.pBit(13, 8191); - } - bitBlock.bytes(); - } - writeUpdate(npc, out, newlyObserved) { - let mask = npc.mask; - if (newlyObserved && (npc.orientation !== -1 || npc.faceX !== -1 || npc.faceZ != -1)) { - mask |= Npc2.FACE_COORD; - } - if (newlyObserved && npc.faceEntity !== -1) { - mask |= Npc2.FACE_ENTITY; - } - out.p1(mask); - if (mask & Npc2.ANIM) { - out.p2(npc.animId); - out.p1(npc.animDelay); - } - if (mask & Npc2.FACE_ENTITY) { - if (npc.faceEntity !== -1) { - npc.alreadyFacedEntity = true; - } - out.p2(npc.faceEntity); - } - if (mask & Npc2.SAY) { - out.pjstr(npc.chat ?? ''); - } - if (mask & Npc2.DAMAGE) { - out.p1(npc.damageTaken); - out.p1(npc.damageType); - out.p1(npc.levels[NpcStat_default.HITPOINTS]); - out.p1(npc.baseLevels[NpcStat_default.HITPOINTS]); - } - if (mask & Npc2.CHANGE_TYPE) { - out.p2(npc.type); - } - if (mask & Npc2.SPOTANIM) { - out.p2(npc.graphicId); - out.p2(npc.graphicHeight); - out.p2(npc.graphicDelay); - } - if (mask & Npc2.FACE_COORD) { - if (npc.faceX !== -1) { - npc.alreadyFacedCoord = true; - } - if (newlyObserved && npc.faceX != -1) { - out.p2(npc.faceX); - out.p2(npc.faceZ); - } else if (newlyObserved && npc.orientation != -1) { - const faceX = Position.moveX(npc.x, npc.orientation); - const faceZ = Position.moveZ(npc.z, npc.orientation); - out.p2(faceX * 2 + 1); - out.p2(faceZ * 2 + 1); - } else { - out.p2(npc.faceX); - out.p2(npc.faceZ); - } - } - } - calculateUpdateSize(npc, newlyObserved) { - let length = 0; - let mask = npc.mask; - if (newlyObserved && (npc.orientation !== -1 || npc.faceX !== -1 || npc.faceZ != -1)) { - mask |= Npc2.FACE_COORD; - } - if (newlyObserved && npc.faceEntity !== -1) { - mask |= Npc2.FACE_ENTITY; - } - length += 1; - if (mask & Npc2.ANIM) { - length += 3; - } - if (mask & Npc2.FACE_ENTITY) { - length += 2; - } - if (mask & Npc2.SAY) { - length += (npc.chat?.length ?? 0) + 1; - } - if (mask & Npc2.DAMAGE) { - length += 4; - } - if (mask & Npc2.CHANGE_TYPE) { - length += 2; - } - if (mask & Npc2.SPOTANIM) { - length += 6; - } - if (mask & Npc2.FACE_COORD) { - length += 4; - } - return length; - } -} - -// src/lostcity/network/225/outgoing/prot/ServerProtRepository.ts -class ServerProtRepository { - encoders = new Map(); - bind(message, encoder) { - if (this.encoders.has(message)) { - throw new Error(`[ServerProtRepository] Already defines a ${message.name}.`); - } - this.encoders.set(message, encoder); - } - constructor() { - this.bind(CamLookAt, new CamLookAtEncoder()); - this.bind(CamMoveTo, new CamMoveToEncoder()); - this.bind(CamReset, new CamResetEncoder()); - this.bind(CamShake, new CamShakeEncoder()); - this.bind(ChatFilterSettings, new ChatFilterSettingsEncoder()); - this.bind(DataLand, new DataLandEncoder()); - this.bind(DataLandDone, new DataLandDoneEncoder()); - this.bind(DataLoc, new DataLocEncoder()); - this.bind(DataLocDone, new DataLocDoneEncoder()); - this.bind(EnableTracking, new EnableTrackingEncoder()); - this.bind(FinishTracking, new FinishTrackingEncoder()); - this.bind(HintArrow, new HintArrowEncoder()); - this.bind(IfClose, new IfCloseEncoder()); - this.bind(IfOpenChatModal, new IfOpenChatModalEncoder()); - this.bind(IfOpenMainModal, new IfOpenMainModalEncoder()); - this.bind(IfOpenMainSideModal, new IfOpenMainSideModalEncoder()); - this.bind(IfOpenSideModal, new IfOpenSideModalEncoder()); - this.bind(IfOpenSideOverlay, new IfOpenSideOverlayEncoder()); - this.bind(IfSetAnim, new IfSetAnimEncoder()); - this.bind(IfSetColour, new IfSetColourEncoder()); - this.bind(IfSetHide, new IfSetHideEncoder()); - this.bind(IfSetModel, new IfSetModelEncoder()); - this.bind(IfSetNpcHead, new IfSetNpcHeadEncoder()); - this.bind(IfSetObject, new IfSetObjectEncoder()); - this.bind(IfSetPlayerHead, new IfSetPlayerHeadEncoder()); - this.bind(IfSetPosition, new IfSetPositionEncoder()); - this.bind(IfSetRecol, new IfSetRecolEncoder()); - this.bind(IfSetText, new IfSetTextEncoder()); - this.bind(IfShowSide, new IfShowSideEncoder()); - this.bind(LastLoginInfo, new LastLoginInfoEncoder()); - this.bind(LocAddChange, new LocAddChangeEncoder()); - this.bind(LocAnim, new LocAnimEncoder()); - this.bind(LocDel, new LocDelEncoder()); - this.bind(LocMerge, new LocMergeEncoder()); - this.bind(Logout, new LogoutEncoder()); - this.bind(MapAnim, new MapAnimEncoder()); - this.bind(MapProjAnim, new MapProjAnimEncoder()); - this.bind(MessageGame, new MessageGameEncoder()); - this.bind(MessagePrivate, new MessagePrivateEncoder()); - this.bind(MidiJingle, new MidiJingleEncoder()); - this.bind(MidiSong, new MidiSongEncoder()); - this.bind(NpcInfo, new NpcInfoEncoder()); - this.bind(ObjAdd, new ObjAddEncoder()); - this.bind(ObjCount, new ObjCountEncoder()); - this.bind(ObjDel, new ObjDelEncoder()); - this.bind(ObjReveal, new ObjRevealEncoder()); - this.bind(PCountDialog, new PCountDialogEncoder()); - this.bind(PlayerInfo, new PlayerInfoEncoder()); - this.bind(RebuildNormal, new RebuildNormalEncoder()); - this.bind(ResetAnims, new ResetAnimsEncoder()); - this.bind(ResetClientVarCache, new ResetClientVarCacheEncoder()); - this.bind(SetMultiway, new SetMultiwayEncoder()); - this.bind(SynthSound, new SynthSoundEncoder()); - this.bind(TutorialFlashSide, new TutorialFlashSideEncoder()); - this.bind(TutorialOpenChat, new TutorialOpenChatEncoder()); - this.bind(UnsetMapFlag, new UnsetMapFlagEncoder()); - this.bind(UpdateFriendList, new UpdateFriendListEncoder()); - this.bind(UpdateIgnoreList, new UpdateIgnoreListEncoder()); - this.bind(UpdateInvFull, new UpdateInvFullEncoder()); - this.bind(UpdateInvPartial, new UpdateInvPartialEncoder()); - this.bind(UpdateInvStopTransmit, new UpdateInvStopTransmitEncoder()); - this.bind(UpdateRunEnergy, new UpdateRunEnergyEncoder()); - this.bind(UpdateRunWeight, new UpdateRunWeightEncoder()); - this.bind(UpdateStat, new UpdateStatEncoder()); - this.bind(UpdateUid192, new UpdateUid192Encoder()); - this.bind(UpdateZoneFullFollows, new UpdateZoneFullFollowsEncoder()); - this.bind(UpdateZonePartialEnclosed, new UpdateZonePartialEnclosedEncoder()); - this.bind(UpdateZonePartialFollows, new UpdateZonePartialFollowsEncoder()); - this.bind(VarpLarge, new VarpLargeEncoder()); - this.bind(VarpSmall, new VarpSmallEncoder()); - } - getEncoder(message) { - return this.encoders.get(message.constructor); - } - getZoneEncoder(message) { - return this.encoders.get(message.constructor); - } -} -var ServerProtRepository_default = new ServerProtRepository(); - -// src/lostcity/engine/zone/Zone.ts -class Zone { - index; - x; - z; - level; - players = new Set(); - npcs = new Set(); - locs = []; - objs = []; - events = new Set(); - shared = null; - totalLocs = 0; - totalObjs = 0; - constructor(index) { - this.index = index; - const coord = ZoneMap2.unpackIndex(index); - this.x = coord.x >> 3; - this.z = coord.z >> 3; - this.level = coord.level; - } - enter(entity) { - if (entity instanceof Player2) { - this.players.add(entity.uid); - World_default.getZoneGrid(this.level).flag(this.x, this.z); - } else if (entity instanceof Npc2) { - this.npcs.add(entity.nid); - } - } - leave(entity) { - if (entity instanceof Player2) { - this.players.delete(entity.uid); - if (this.players.size === 0) { - World_default.getZoneGrid(this.level).unflag(this.x, this.z); - } - } else if (entity instanceof Npc2) { - this.npcs.delete(entity.nid); - } - } - tick(tick) { - let updated; - do { - updated = false; - for (const obj of this.getAllObjsUnsafe()) { - if (!obj.updateLifeCycle(tick) || obj.lastLifecycleTick === tick) { - continue; - } - if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - if (obj.receiverId !== -1) { - World_default.revealObj(obj); - } else { - World_default.removeObj(obj, 0); - updated = true; - } - } else if (obj.lifecycle === EntityLifeCycle_default.RESPAWN) { - World_default.addObj(obj, -1, 0); - updated = true; - } - } - for (const loc of this.getAllLocsUnsafe()) { - if (!loc.updateLifeCycle(tick) || loc.lastLifecycleTick === tick) { - continue; - } - if (loc.lifecycle === EntityLifeCycle_default.DESPAWN) { - World_default.removeLoc(loc, 0); - updated = true; - } else if (loc.lifecycle === EntityLifeCycle_default.RESPAWN) { - World_default.addLoc(loc, 0); - updated = true; - } - } - } while (updated); - } - computeShared() { - this.shared = null; - let length = 0; - const enclosed = []; - for (const event of this.events.values()) { - if (event.type !== ZoneEventType_default.ENCLOSED) { - continue; - } - const encoder = ServerProtRepository_default.getZoneEncoder(event.message); - if (typeof encoder === 'undefined') { - continue; - } - const bytes = encoder.enclose(event.message); - enclosed.push(bytes); - length += bytes.length; - } - if (enclosed.length === 0 || length === 0) { - return; - } - const shared = new Uint8Array(length); - let ptr = 0; - for (const bytes of enclosed) { - shared.set(bytes, ptr); - ptr += bytes.length; - } - this.shared = shared; - } - writeFullFollows(player) { - player.write(new UpdateZoneFullFollows(this.x, this.z, player.originX, player.originZ)); - for (const obj of this.getAllObjsUnsafe(true)) { - if (obj.receiverId !== -1 && obj.receiverId !== player.pid) { - continue; - } - player.write(new UpdateZonePartialFollows(this.x, this.z, player.originX, player.originZ)); - if (obj.lifecycle === EntityLifeCycle_default.DESPAWN && obj.checkLifeCycle(World_default.currentTick)) { - player.write(new ObjAdd(Position.packZoneCoord(obj.x, obj.z), obj.type, obj.count)); - } else if (obj.lifecycle === EntityLifeCycle_default.RESPAWN && obj.checkLifeCycle(World_default.currentTick)) { - player.write(new ObjAdd(Position.packZoneCoord(obj.x, obj.z), obj.type, obj.count)); - } - } - for (const loc of this.getAllLocsUnsafe(true)) { - if (loc.lifecycle === EntityLifeCycle_default.DESPAWN && loc.checkLifeCycle(World_default.currentTick)) { - player.write(new LocAddChange(Position.packZoneCoord(loc.x, loc.z), loc.type, loc.shape, loc.angle)); - } else if (loc.lifecycle === EntityLifeCycle_default.RESPAWN && !loc.checkLifeCycle(World_default.currentTick)) { - player.write(new LocDel(Position.packZoneCoord(loc.x, loc.z), loc.shape, loc.angle)); - } - } - } - writePartialEncloses(player) { - if (!this.shared) { - return; - } - player.write(new UpdateZonePartialEnclosed(this.x, this.z, player.originX, player.originZ, this.shared)); - } - writePartialFollows(player) { - if (this.events.size === 0) { - return; - } - player.write(new UpdateZonePartialFollows(this.x, this.z, player.originX, player.originZ)); - for (const event of this.events) { - if (event.type !== ZoneEventType_default.FOLLOWS) { - continue; - } - if (event.receiverId !== -1 && event.receiverId !== player.pid) { - continue; - } - player.write(event.message); - } - } - reset() { - this.events.clear(); - } - addStaticLoc(loc) { - const coord = Position.packZoneCoord(loc.x, loc.z); - const locs = this.locs[coord]; - if (!locs) { - this.locs[coord] = []; - } - this.locs[coord]?.push(loc); - this.totalLocs++; - this.sortLocs(coord); - } - addStaticObj(obj) { - const coord = Position.packZoneCoord(obj.x, obj.z); - const objs = this.objs[coord]; - if (!objs) { - this.objs[coord] = []; - } - this.objs[coord]?.push(obj); - this.totalObjs++; - this.sortObjs(coord); - } - addLoc(loc) { - const coord = Position.packZoneCoord(loc.x, loc.z); - if (loc.lifecycle === EntityLifeCycle_default.DESPAWN) { - const locs = this.locs[coord]; - if (!locs) { - this.locs[coord] = []; - } - this.locs[coord]?.push(loc); - this.totalLocs++; - } - this.sortLocs(coord); - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId: -1, - message: new LocAddChange(coord, loc.type, loc.shape, loc.angle) - }); - } - removeLoc(loc) { - const coord = Position.packZoneCoord(loc.x, loc.z); - if (loc.lifecycle === EntityLifeCycle_default.DESPAWN) { - const locs = this.locs[coord]; - if (locs) { - for (let index = 0; index < locs.length; index++) { - if (loc === locs[index]) { - locs.splice(index, 1); - this.totalLocs--; - break; - } - } - } - } - this.sortLocs(coord); - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId: -1, - message: new LocDel(coord, loc.shape, loc.angle) - }); - } - getLoc(x, z2, type) { - for (const loc of this.getLocsSafe(Position.packZoneCoord(x, z2))) { - if (loc.type === type) { - return loc; - } - } - return null; - } - mergeLoc(loc, player, startCycle, endCycle, south, east, north, west) { - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId: -1, - message: new LocMerge(loc.x, loc.z, loc.shape, loc.angle, loc.type, startCycle, endCycle, player.pid, east, south, west, north) - }); - } - animLoc(loc, seq) { - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId: -1, - message: new LocAnim(Position.packZoneCoord(loc.x, loc.z), loc.shape, loc.angle, seq) - }); - } - addObj(obj, receiverId) { - const coord = Position.packZoneCoord(obj.x, obj.z); - if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - const objs = this.objs[coord]; - if (!objs) { - this.objs[coord] = []; - } - this.objs[coord]?.push(obj); - this.totalObjs++; - } - this.sortObjs(coord); - if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.events.add({ - type: ZoneEventType_default.FOLLOWS, - receiverId, - message: new ObjAdd(coord, obj.type, obj.count) - }); - } else if (obj.lifecycle === EntityLifeCycle_default.RESPAWN) { - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId, - message: new ObjAdd(coord, obj.type, obj.count) - }); - } - } - revealObj(obj, receiverId) { - const coord = Position.packZoneCoord(obj.x, obj.z); - obj.receiverId = -1; - obj.reveal = -1; - this.sortObjs(coord); - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId: -1, - message: new ObjReveal(coord, obj.type, obj.count, receiverId) - }); - } - changeObj(obj, receiverId, oldCount, newCount) { - const coord = Position.packZoneCoord(obj.x, obj.z); - obj.count = newCount; - this.sortObjs(coord); - this.events.add({ - type: ZoneEventType_default.FOLLOWS, - receiverId, - message: new ObjCount(coord, obj.type, oldCount, newCount) - }); - } - removeObj(obj) { - const coord = Position.packZoneCoord(obj.x, obj.z); - if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - const objs = this.objs[coord]; - if (objs) { - for (let index = 0; index < objs.length; index++) { - if (obj === objs[index]) { - objs.splice(index, 1); - this.totalObjs--; - break; - } - } - } - } - this.sortObjs(coord); - if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.events.add({ - type: ZoneEventType_default.FOLLOWS, - receiverId: -1, - message: new ObjDel(coord, obj.type) - }); - } else if (obj.lifecycle === EntityLifeCycle_default.RESPAWN) { - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId: -1, - message: new ObjDel(coord, obj.type) - }); - } - } - animMap(x, z2, spotanim, height, delay) { - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId: -1, - message: new MapAnim(Position.packZoneCoord(x, z2), spotanim, height, delay) - }); - } - mapProjAnim(x, z2, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) { - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId: -1, - message: new MapProjAnim(x, z2, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) - }); - } - getObj(x, z2, type, receiverId) { - for (const obj of this.getObjsSafe(Position.packZoneCoord(x, z2))) { - if ((obj.receiverId !== -1 && obj.receiverId !== receiverId) || obj.type !== type) { - continue; - } - return obj; - } - return null; - } - *getAllPlayersSafe() { - for (const uid of this.players) { - const player = World_default.getPlayerByUid(uid); - if (player && player.checkLifeCycle(World_default.currentTick)) { - yield player; - } - } - } - *getAllNpcsSafe() { - for (const nid of this.npcs) { - const npc = World_default.getNpc(nid); - if (npc && npc.checkLifeCycle(World_default.currentTick)) { - yield npc; - } - } - } - *getAllObjsSafe() { - for (let index = 0; index < this.objs.length; index++) { - const objs = this.objs[index]; - if (objs) { - for (let i = 0; i < objs.length; i++) { - const obj = objs[i]; - if (obj.checkLifeCycle(World_default.currentTick)) { - yield obj; - } - } - } - } - } - *getObjsSafe(coord) { - const objs = this.objs[coord]; - if (objs) { - for (let i = 0; i < objs.length; i++) { - const obj = objs[i]; - if (obj.checkLifeCycle(World_default.currentTick)) { - yield obj; - } - } - } - } - *getObjsUnsafe(coord) { - const objs = this.objs[coord]; - if (objs) { - for (let i = 0; i < objs.length; i++) { - yield objs[i]; - } - } - } - *getAllObjsUnsafe(reverse = false) { - for (let index = 0; index < this.objs.length; index++) { - const objs = this.objs[index]; - if (objs) { - if (reverse) { - for (let i = objs.length - 1; i >= 0; i--) { - yield objs[i]; - } - } else { - for (let i = 0; i < objs.length; i++) { - yield objs[i]; - } - } - } - } - } - *getAllLocsSafe() { - for (let index = 0; index < this.locs.length; index++) { - const locs = this.locs[index]; - if (locs) { - for (let i = 0; i < locs.length; i++) { - const loc = locs[i]; - if (loc.checkLifeCycle(World_default.currentTick)) { - yield loc; - } - } - } - } - } - *getLocsSafe(coord) { - const locs = this.locs[coord]; - if (locs) { - for (let i = 0; i < locs.length; i++) { - const loc = locs[i]; - if (loc.checkLifeCycle(World_default.currentTick)) { - yield loc; - } - } - } - } - *getLocsUnsafe(coord) { - const locs = this.locs[coord]; - if (locs) { - for (let i = 0; i < locs.length; i++) { - yield locs[i]; - } - } - } - *getAllLocsUnsafe(reverse = false) { - for (let index = 0; index < this.locs.length; index++) { - const locs = this.locs[index]; - if (locs) { - if (reverse) { - for (let i = locs.length - 1; i >= 0; i--) { - yield locs[i]; - } - } else { - for (let i = 0; i < locs.length; i++) { - yield locs[i]; - } - } - } - } - } - sortObjs(coord) { - const objs = this.objs[coord]; - if (!objs) { - return; - } - let topCost = -99999999; - let topObj = null; - for (const obj of objs) { - const type = ObjType.get(obj.type); - let cost = type.cost; - if (type.stackable) { - cost *= obj.count + 1; - } - cost += obj.lifecycle; - if (cost > topCost) { - topCost = cost; - topObj = obj; - } - } - if (!topObj) { - return; - } - if (objs[0] !== topObj) { - objs.splice(objs.indexOf(topObj), 1); - objs.unshift(topObj); - } - } - sortLocs(coord) { - const locs = this.locs[coord]; - if (!locs) { - return; - } - let topCost = -99999999; - let topLoc = null; - for (const loc of locs) { - const cost = loc.lifecycle; - if (cost > topCost) { - topCost = cost; - topLoc = loc; - } - } - if (!topLoc) { - return; - } - if (locs[0] !== topLoc) { - locs.splice(locs.indexOf(topLoc), 1); - locs.unshift(topLoc); - } - } -} - -// src/lostcity/engine/zone/ZoneGrid.ts -class ZoneGrid { - static GRID_SIZE = 2048; - static INT_BITS = 5; - static INT_BITS_FLAG = (1 << this.INT_BITS) - 1; - static DEFAULT_GRID_SIZE = this.GRID_SIZE * (this.GRID_SIZE >> this.INT_BITS); - grid; - constructor(size = ZoneGrid.DEFAULT_GRID_SIZE) { - this.grid = new Int32Array(size); - } - index(zoneX, zoneY) { - return (zoneX << ZoneGrid.INT_BITS) | (zoneY >>> ZoneGrid.INT_BITS); - } - flag(zoneX, zoneY) { - this.grid[this.index(zoneX, zoneY)] |= 1 << (zoneY & ZoneGrid.INT_BITS_FLAG); - } - unflag(zoneX, zoneY) { - this.grid[this.index(zoneX, zoneY)] &= ~(1 << (zoneY & ZoneGrid.INT_BITS_FLAG)); - } - isFlagged(zoneX, zoneY, radius) { - const minX = Math.max(0, zoneX - radius); - const maxX = Math.min(ZoneGrid.GRID_SIZE - 1, zoneX + radius); - const minY = Math.max(0, zoneY - radius); - const maxY = Math.min(ZoneGrid.GRID_SIZE - 1, zoneY + radius); - const bits = ZoneGrid.INT_BITS_FLAG; - const startY = minY & ~bits; - const endY = (maxY >>> ZoneGrid.INT_BITS) << ZoneGrid.INT_BITS; - for (let x = minX; x <= maxX; x++) { - for (let y2 = startY; y2 <= endY; y2 += 32) { - const index = this.index(x, y2); - const line = this.grid[index]; - let trailingTrimmed = line; - if (y2 + bits > maxY) { - trailingTrimmed = line & ((1 << (maxY - y2 + 1)) - 1); - } - let leadingTrimmed = trailingTrimmed; - if (y2 < minY) { - leadingTrimmed = trailingTrimmed >>> (minY - y2); - } - if (leadingTrimmed !== 0) { - return true; - } - } - } - return false; - } -} - -// src/lostcity/engine/zone/ZoneMap.ts -class ZoneMap2 { - static zoneIndex(x, z2, level) { - return ((x >> 3) & 2047) | (((z2 >> 3) & 2047) << 11) | ((level & 3) << 22); - } - static unpackIndex(index) { - const x = (index & 2047) << 3; - const z2 = ((index >> 11) & 2047) << 3; - const level = index >> 22; - return {x, z: z2, level}; - } - zones; - grids; - constructor() { - this.zones = new Map(); - this.grids = new Map(); - } - zone(x, z2, level) { - const zoneIndex = ZoneMap2.zoneIndex(x, z2, level); - let zone = this.zones.get(zoneIndex); - if (typeof zone == 'undefined') { - zone = new Zone(zoneIndex); - this.zones.set(zoneIndex, zone); - } - return zone; - } - zoneByIndex(index) { - let zone = this.zones.get(index); - if (typeof zone == 'undefined') { - zone = new Zone(index); - this.zones.set(index, zone); - } - return zone; - } - grid(level) { - let grid = this.grids.get(level); - if (typeof grid == 'undefined') { - grid = new ZoneGrid(); - this.grids.set(level, grid); - } - return grid; - } - zoneCount() { - return this.zones.size; - } - locCount() { - let total = 0; - for (const zone of this.zones.values()) { - total += zone.totalLocs; - } - return total; - } - objCount() { - let total = 0; - for (const zone of this.zones.values()) { - total += zone.totalObjs; - } - return total; - } -} - -// src/lostcity/entity/BuildArea.ts -class BuildArea { - static INTERVAL = 10; - static PREFERRED_PLAYERS = 250; - static PREFERRED_NPCS = 255; - static PREFERRED_VIEW_DISTANCE = 16; - npcs; - players; - loadedZones; - activeZones; - extendedInfo; - appearances; - forceViewDistance = false; - viewDistance = BuildArea.PREFERRED_VIEW_DISTANCE; - lastResize = 0; - constructor() { - this.npcs = new Set(); - this.players = new Set(); - this.loadedZones = new Set(); - this.activeZones = new Set(); - this.extendedInfo = new Set(); - this.appearances = new Map(); - } - resize() { - if (this.forceViewDistance) { - return; - } - if (this.players.size >= BuildArea.PREFERRED_PLAYERS) { - if (this.viewDistance > 1) { - this.viewDistance--; - } - this.lastResize = 0; - return; - } - if (++this.lastResize >= BuildArea.INTERVAL) { - if (this.viewDistance < BuildArea.PREFERRED_VIEW_DISTANCE) { - this.viewDistance++; - } else { - this.lastResize = 0; - } - } - } - reset() { - this.extendedInfo.clear(); - } - *getNearbyPlayers(uid, x, z2, originX, originZ) { - players: for (const zoneIndex of this.proximitySort(x, z2, this.activeZones)) { - for (const other of this.getNearby(World_default.getZoneIndex(zoneIndex).getAllPlayersSafe(), x, z2, originX, originZ, this.viewDistance)) { - if (this.players.size >= BuildArea.PREFERRED_PLAYERS) { - break players; - } - if (this.players.has(other.uid)) { - continue; - } - if (other.uid === uid) { - continue; - } - yield other; - } - } - } - *getNearbyNpcs(x, z2, originX, originZ) { - npcs: for (const zoneIndex of this.proximitySort(x, z2, this.activeZones)) { - for (const npc of this.getNearby(World_default.getZoneIndex(zoneIndex).getAllNpcsSafe(), x, z2, originX, originZ, 16)) { - if (this.npcs.size >= BuildArea.PREFERRED_NPCS) { - break npcs; - } - if (this.npcs.has(npc.nid)) { - continue; - } - yield npc; - } - } - } - hasAppearance(pid, hashCode) { - const appearance = this.appearances.get(pid); - if (typeof appearance === 'undefined') { - return false; - } - return appearance === hashCode; - } - saveAppearance(pid, hashCode) { - this.appearances.set(pid, hashCode); - } - *getNearby(entities, x, z2, originX, originZ, distance) { - const absLeftX = originX - 48; - const absRightX = originX + 48; - const absTopZ = originZ + 48; - const absBottomZ = originZ - 48; - for (const entity of entities) { - if (entity.x <= absLeftX || entity.x >= absRightX || entity.z >= absTopZ || entity.z <= absBottomZ) { - continue; - } - if (!Position.isWithinDistanceSW({x, z: z2}, entity, distance)) { - continue; - } - yield entity; - } - } - proximitySort(zoneX, zoneZ, zones) { - return Array.from(zones.values()) - .map(zoneIndex => this.zoneToDistance(zoneIndex, zoneX, zoneZ)) - .sort((a, b2) => a.distance - b2.distance) - .map(({zoneIndex}) => zoneIndex); - } - zoneToDistance(zoneIndex, zoneX, zoneZ) { - const pos = ZoneMap2.unpackIndex(zoneIndex); - const distance = Math.abs(pos.x - zoneX) + Math.abs(pos.z - zoneZ); - return {zoneIndex, distance}; - } -} - -// src/lostcity/entity/Player.ts -function getLevelByExp(exp) { - for (let i = 98; i >= 0; i--) { - if (exp >= levelExperience[i]) { - return Math.min(i + 2, 99); - } - } - return 1; -} -function getExpByLevel(level) { - return levelExperience[level - 2]; -} -var levelExperience = new Int32Array(99); -var acc = 0; -for (let i = 0; i < 99; i++) { - const level = i + 1; - const delta = Math.floor(level + Math.pow(2, level / 7) * 300); - acc += delta; - levelExperience[i] = Math.floor(acc / 4) * 10; -} - -class Player2 extends PathingEntity { - static APPEARANCE = 1; - static ANIM = 2; - static FACE_ENTITY = 4; - static SAY = 8; - static DAMAGE = 16; - static FACE_COORD = 32; - static CHAT = 64; - static BIG_UPDATE = 128; - static SPOTANIM = 256; - static EXACT_MOVE = 512; - static SKILLS = [ - 'attack', - 'defence', - 'strength', - 'hitpoints', - 'ranged', - 'prayer', - 'magic', - 'cooking', - 'woodcutting', - 'fletching', - 'fishing', - 'firemaking', - 'crafting', - 'smithing', - 'mining', - 'herblore', - 'agility', - 'thieving', - 'stat18', - 'stat19', - 'runecraft' - ]; - static DESIGN_BODY_COLORS = [ - [6798, 107, 10283, 16, 4797, 7744, 5799, 4634, 33697, 22433, 2983, 54193], - [8741, 12, 64030, 43162, 7735, 8404, 1701, 38430, 24094, 10153, 56621, 4783, 1341, 16578, 35003, 25239], - [25238, 8742, 12, 64030, 43162, 7735, 8404, 1701, 38430, 24094, 10153, 56621, 4783, 1341, 16578, 35003], - [4626, 11146, 6439, 12, 4758, 10270], - [4550, 4537, 5681, 5673, 5790, 6806, 8076, 4574] - ]; - save() {} - username; - username37; - displayName; - body; - colors; - gender; - runenergy = 1e4; - lastRunEnergy = -1; - runweight; - playtime; - stats = new Int32Array(21); - levels = new Uint8Array(21); - vars; - varsString; - invs = new Map(); - pid = -1; - uid = -1; - lowMemory = false; - combatLevel = 3; - headicons = 0; - appearance = null; - appearanceHashCode = 0n; - baseLevels = new Uint8Array(21); - lastStats = new Int32Array(21); - lastLevels = new Uint8Array(21); - originX = -1; - originZ = -1; - buildArea = new BuildArea(); - lastMovement = 0; - basReadyAnim = -1; - basTurnOnSpot = -1; - basWalkForward = -1; - basWalkBackward = -1; - basWalkLeft = -1; - basWalkRight = -1; - basRunning = -1; - animProtect = 0; - logoutRequested = false; - invListeners = []; - allowDesign = false; - afkEventReady = false; - interactWalkTrigger = false; - highPriorityOut = new Stack(); - lowPriorityOut = new Stack(); - lastResponse = -1; - messageColor = null; - messageEffect = null; - messageType = null; - message = null; - delay = 0; - queue = new LinkList(); - weakQueue = new LinkList(); - engineQueue = new LinkList(); - cameraPackets = new LinkList(); - timers = new Map(); - modalState = 0; - modalTop = -1; - lastModalTop = -1; - modalBottom = -1; - lastModalBottom = -1; - modalSidebar = -1; - lastModalSidebar = -1; - refreshModalClose = false; - refreshModal = false; - modalSticky = -1; - overlaySide = new Array(14).fill(-1); - receivedFirstClose = false; - protect = false; - activeScript = null; - resumeButtons = []; - lastItem = -1; - lastSlot = -1; - lastUseItem = -1; - lastUseSlot = -1; - lastTargetSlot = -1; - lastCom = -1; - staffModLevel = 0; - heroPoints = new Array(16); - afkZones = new Int32Array(2); - lastAfkZone = 0; - constructor(username, username37) { - super(0, 3094, 3106, 1, 1, EntityLifeCycle_default.FOREVER, MoveRestrict_default.NORMAL, BlockWalk_default.NPC, MoveStrategy_default.SMART, Player2.FACE_COORD, Player2.FACE_ENTITY); - this.username = username; - this.username37 = username37; - this.displayName = toDisplayName(username); - this.vars = new Int32Array(VarPlayerType.count); - this.varsString = new Array(VarPlayerType.count); - this.body = [0, 10, 18, 26, 33, 36, 42]; - this.colors = [0, 0, 0, 0, 0]; - this.gender = 0; - this.runenergy = 1e4; - this.runweight = 0; - this.playtime = 0; - this.lastStats.fill(-1); - this.lastLevels.fill(-1); - } - resetHeroPoints() { - this.heroPoints = new Array(16); - this.heroPoints.fill({uid: -1, points: 0}); - } - addHero(uid, points) { - const index = this.heroPoints.findIndex(hero => hero && hero.uid === uid); - if (index !== -1) { - this.heroPoints[index].points += points; - return; - } - const emptyIndex = this.heroPoints.findIndex(hero => hero && hero.uid === -1); - if (emptyIndex !== -1) { - this.heroPoints[emptyIndex] = {uid, points}; - return; - } - } - findHero() { - this.heroPoints.sort((a, b2) => { - return b2.points - a.points; - }); - return this.heroPoints[0]?.uid ?? -1; - } - resetEntity(respawn) { - if (respawn) { - } - super.resetPathingEntity(); - this.repathed = false; - this.protect = false; - this.messageColor = null; - this.messageEffect = null; - this.messageType = null; - this.message = null; - } - onLogin() { - this.playerLog('Logging in'); - this.write(new IfClose()); - this.write(new UpdateUid192(this.pid)); - this.unsetMapFlag(); - this.write(new ResetAnims()); - this.resetHeroPoints(); - this.write(new ResetClientVarCache()); - for (let varp = 0; varp < this.vars.length; varp++) { - const type = VarPlayerType.get(varp); - const value = this.vars[varp]; - if (type.transmit) { - this.writeVarp(varp, value); - } - } - const loginTrigger = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.LOGIN, -1, -1); - if (loginTrigger) { - this.executeScript(ScriptRunner2.init(loginTrigger, this), true); - } - const moveTrigger = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.MOVE, -1, -1); - if (moveTrigger) { - const script = ScriptRunner2.init(moveTrigger, this); - this.runScript(script, true); - } - this.lastStepX = this.x - 1; - this.lastStepZ = this.z; - } - calculateRunWeight() { - this.runweight = 0; - const invs = this.invs.values(); - for (let i = 0; i < this.invs.size; i++) { - const inv = invs.next().value; - if (!inv) { - continue; - } - const invType = InvType.get(inv.type); - if (!invType || !invType.runweight) { - continue; - } - for (let slot = 0; slot < inv.capacity; slot++) { - const item = inv.get(slot); - if (!item) { - continue; - } - const type = ObjType.get(item.id); - if (!type || type.stackable) { - continue; - } - this.runweight += type.weight * item.count; - } - } - } - playerLog(message, ...args) {} - processEngineQueue() { - for (let request = this.engineQueue.head(); request !== null; request = this.engineQueue.next()) { - const delay = request.delay--; - if (this.canAccess() && delay <= 0) { - const script = ScriptRunner2.init(request.script, this, null, request.args); - this.executeScript(script, true); - request.unlink(); - } - } - } - updateMovement(repathAllowed = true) { - if (this.containsModalInterface()) { - this.recoverEnergy(false); - return false; - } - if (repathAllowed && this.target instanceof PathingEntity && !this.interacted && this.walktrigger === -1) { - this.pathToPathingTarget(); - } - if (this.hasWaypoints() && this.walktrigger !== -1 && !this.protect && !this.delayed()) { - const trigger = ScriptProvider.get(this.walktrigger); - this.walktrigger = -1; - if (trigger) { - const script = ScriptRunner2.init(trigger, this); - this.runScript(script, true); - } - } - if (this.runenergy < 100) { - this.setVar(VarPlayerType.PLAYER_RUN, 0); - this.setVar(VarPlayerType.TEMP_RUN, 0); - } - if (this.moveSpeed !== MoveSpeed_default.INSTANT) { - this.moveSpeed = this.defaultMoveSpeed(); - if (this.basRunning === -1) { - this.moveSpeed = MoveSpeed_default.WALK; - } else if (this.getVar(VarPlayerType.TEMP_RUN)) { - this.moveSpeed = MoveSpeed_default.RUN; - } - } - if (!super.processMovement()) { - this.setVar(VarPlayerType.TEMP_RUN, 0); - } - const moved = this.lastX !== this.x || this.lastZ !== this.z; - if (moved) { - const trigger = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.MOVE, -1, -1); - if (trigger) { - this.runScript(ScriptRunner2.init(trigger, this), true); - } - } - this.drainEnergy(moved); - this.recoverEnergy(moved); - if (this.runenergy === 0) { - this.setVar(VarPlayerType.PLAYER_RUN, 0); - this.setVar(VarPlayerType.TEMP_RUN, 0); - } - return moved; - } - drainEnergy(moved) { - if (!moved || this.stepsTaken === 0) { - return; - } - if (!this.delayed() && this.moveSpeed === MoveSpeed_default.RUN && this.stepsTaken > 1) { - const weightKg = Math.floor(this.runweight / 1000); - const clampWeight = Math.min(Math.max(weightKg, 0), 64); - const loss = (67 + (67 * clampWeight) / 64) | 0; - this.runenergy = Math.max(this.runenergy - loss, 0); - } - } - recoverEnergy(moved) { - if (!this.delayed() && (!moved || this.moveSpeed !== MoveSpeed_default.RUN) && this.runenergy < 1e4) { - const recovered = ((this.baseLevels[PlayerStat_default.AGILITY] / 9) | 0) + 8; - this.runenergy = Math.min(this.runenergy + recovered, 1e4); - } - } - blockWalkFlag() { - return CollisionFlag.PLAYER; - } - defaultMoveSpeed() { - return this.getVar(VarPlayerType.PLAYER_RUN) ? MoveSpeed_default.RUN : MoveSpeed_default.WALK; - } - closeSticky() { - if (this.modalSticky !== -1) { - const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalSticky); - if (closeTrigger) { - this.enqueueScript(closeTrigger, 1 /* ENGINE */); - } - this.modalSticky = -1; - this.write(new TutorialOpenChat(-1)); - } - } - closeModal() { - if (!this.receivedFirstClose) { - this.receivedFirstClose = true; - return; - } - this.weakQueue.clear(); - if (!this.delayed()) { - this.protect = false; - } - if (this.modalState === 0) { - return; - } - if (this.modalTop !== -1) { - const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalTop); - if (closeTrigger) { - this.enqueueScript(closeTrigger, 1 /* ENGINE */); - } - this.modalTop = -1; - } - if (this.modalBottom !== -1) { - const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalBottom); - if (closeTrigger) { - this.enqueueScript(closeTrigger, 1 /* ENGINE */); - } - this.modalBottom = -1; - } - if (this.modalSidebar !== -1) { - const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalSidebar); - if (closeTrigger) { - this.enqueueScript(closeTrigger, 1 /* ENGINE */); - } - this.modalSidebar = -1; - } - this.modalState = 0; - this.refreshModalClose = true; - } - delayed() { - return this.delay > 0; - } - containsModalInterface() { - return (this.modalState & 1) === 1 || (this.modalState & 2) === 2 || (this.modalState & 16) === 16; - } - busy() { - return this.delayed() || this.containsModalInterface(); - } - canAccess() { - return !this.protect && !this.busy(); - } - enqueueScript(script, type = 0 /* NORMAL */, delay = 0, args = []) { - const request = new EntityQueueRequest(type, script, args, delay); - if (type === 1 /* ENGINE */) { - request.delay = 0; - this.engineQueue.addTail(request); - } else if (type === 2 /* WEAK */) { - this.weakQueue.addTail(request); - } else { - this.queue.addTail(request); - } - } - processQueues() { - let hasStrong = false; - for (let request = this.queue.head(); request !== null; request = this.queue.next()) { - if (request.type === 3 /* STRONG */) { - hasStrong = true; - break; - } - } - if (hasStrong) { - this.closeModal(); - } - this.processQueue(); - this.processWeakQueue(); - } - processQueue() { - for (let request = this.queue.head(); request !== null; request = this.queue.next()) { - if (request.type === 3 /* STRONG */) { - this.closeModal(); - } - const delay = request.delay--; - if (this.canAccess() && delay <= 0) { - const script = ScriptRunner2.init(request.script, this, null, request.args); - this.executeScript(script, true); - request.unlink(); - } - } - } - processWeakQueue() { - for (let request = this.weakQueue.head(); request !== null; request = this.weakQueue.next()) { - const delay = request.delay--; - if (this.canAccess() && delay <= 0) { - const script = ScriptRunner2.init(request.script, this, null, request.args); - this.executeScript(script, true); - request.unlink(); - } - } - } - setTimer(type, script, args = [], interval) { - const timerId = script.id; - const timer = { - type, - script, - args, - interval, - clock: interval - }; - this.timers.set(timerId, timer); - } - clearTimer(timerId) { - this.timers.delete(timerId); - } - processTimers(type) { - for (const timer of this.timers.values()) { - if (type !== timer.type) { - continue; - } - if (--timer.clock <= 0 && (timer.type === 1 /* SOFT */ || this.canAccess())) { - timer.clock = timer.interval; - const script = ScriptRunner2.init(timer.script, this, null, timer.args); - this.runScript(script, timer.type === 0 /* NORMAL */); - } - } - } - stopAction() { - this.clearPendingAction(); - this.unsetMapFlag(); - } - clearPendingAction() { - this.clearInteraction(); - this.closeModal(); - } - hasInteraction() { - return this.target !== null; - } - getOpTrigger() { - if (!this.target) { - return null; - } - let typeId = -1; - let categoryId = -1; - if (this.target instanceof Npc2 || this.target instanceof Loc || this.target instanceof Obj) { - const type = this.target instanceof Npc2 ? NpcType.get(this.target.type) : this.target instanceof Loc ? LocType.get(this.target.type) : ObjType.get(this.target.type); - typeId = type.id; - categoryId = type.category; - } - if (this.targetSubject.type !== -1) { - typeId = this.targetSubject.type; - } - if (this.targetSubject.com !== -1) { - typeId = this.targetSubject.com; - } - return ScriptProvider.getByTrigger(this.targetOp + 7, typeId, categoryId) ?? null; - } - getApTrigger() { - if (!this.target) { - return null; - } - let typeId = -1; - let categoryId = -1; - if (this.target instanceof Npc2 || this.target instanceof Loc || this.target instanceof Obj) { - const type = this.target instanceof Npc2 ? NpcType.get(this.target.type) : this.target instanceof Loc ? LocType.get(this.target.type) : ObjType.get(this.target.type); - typeId = type.id; - categoryId = type.category; - } - if (this.targetSubject.type !== -1) { - typeId = this.targetSubject.type; - } - if (this.targetSubject.com !== -1) { - typeId = this.targetSubject.com; - } - return ScriptProvider.getByTrigger(this.targetOp, typeId, categoryId) ?? null; - } - processInteraction() { - if (this.target === null || !this.canAccess()) { - this.updateMovement(); - return; - } - if (this.target.level !== this.level) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.target instanceof Npc2 && (World_default.getNpc(this.target.nid) === null || this.target.delayed())) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.target instanceof Npc2 && this.targetSubject.type !== -1 && World_default.getNpcByUid((this.targetSubject.type << 16) | this.target.nid) === null) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.target instanceof Obj && World_default.getObj(this.target.x, this.target.z, this.level, this.target.type, this.pid) === null) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.target instanceof Loc && World_default.getLoc(this.target.x, this.target.z, this.level, this.target.type) === null) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.target instanceof Player2 && World_default.getPlayerByUid(this.target.uid) === null) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.targetOp === ServerTriggerType_default.APPLAYER3 || this.targetOp === ServerTriggerType_default.OPPLAYER3) { - const moved2 = this.updateMovement(false); - if (moved2) { - this.alreadyFacedEntity = false; - this.alreadyFacedCoord = false; - this.lastMovement = World_default.currentTick + 1; - } - return; - } - const opTrigger = this.getOpTrigger(); - const apTrigger = this.getApTrigger(); - if (opTrigger && this.target instanceof PathingEntity && this.inOperableDistance(this.target)) { - const target = this.target; - this.target = null; - this.executeScript(ScriptRunner2.init(opTrigger, this, target), true); - if (this.target === null) { - this.unsetMapFlag(); - } - this.interacted = true; - this.clearWaypoints(); - } else if (apTrigger && this.inApproachDistance(this.apRange, this.target)) { - const target = this.target; - this.target = null; - this.executeScript(ScriptRunner2.init(apTrigger, this, target), true); - if (this.apRangeCalled) { - this.target = target; - } else { - this.clearWaypoints(); - this.interacted = true; - } - if (this.target === null) { - this.unsetMapFlag(); - } - } else if (this.target instanceof PathingEntity && this.inOperableDistance(this.target)) { - if (Environment_default.LOCAL_DEV && !opTrigger && !apTrigger) { - let debugname = '_'; - if (this.target instanceof Npc2) { - if ((this.targetSubject.com !== -1 && this.targetOp === ServerTriggerType_default.APNPCT) || this.targetOp === ServerTriggerType_default.OPNPCT) { - debugname = Component.get(this.targetSubject.com)?.comName ?? this.targetSubject.toString(); - } else { - debugname = NpcType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } - } else if (this.target instanceof Loc) { - debugname = LocType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } else if (this.target instanceof Obj) { - debugname = ObjType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } else if ( - (this.targetSubject.com !== -1 && this.targetOp === ServerTriggerType_default.APNPCT) || - this.targetOp === ServerTriggerType_default.APPLAYERT || - this.targetOp === ServerTriggerType_default.APLOCT || - this.targetOp === ServerTriggerType_default.APOBJT - ) { - debugname = Component.get(this.targetSubject.com)?.comName ?? this.targetSubject.toString(); - } else if (this.targetSubject.type !== -1) { - debugname = ObjType.get(this.targetSubject.type)?.debugname ?? this.targetSubject.toString(); - } - this.messageGame(`No trigger for [${ServerTriggerType_default[this.targetOp + 7].toLowerCase()},${debugname}]`); - } - this.target = null; - this.messageGame('Nothing interesting happens.'); - this.interacted = true; - this.clearWaypoints(); - } - const moved = this.updateMovement(); - if (moved) { - this.alreadyFacedEntity = false; - this.alreadyFacedCoord = false; - this.lastMovement = World_default.currentTick + 1; - } - if (this.target && (!this.interacted || this.apRangeCalled)) { - this.interacted = false; - if (opTrigger && (this.target instanceof PathingEntity || !moved) && this.inOperableDistance(this.target)) { - const target = this.target; - this.target = null; - this.executeScript(ScriptRunner2.init(opTrigger, this, target), true); - if (this.target === null) { - this.unsetMapFlag(); - } - this.interacted = true; - this.clearWaypoints(); - } else if (apTrigger && this.inApproachDistance(this.apRange, this.target)) { - this.apRangeCalled = false; - const target = this.target; - this.target = null; - this.executeScript(ScriptRunner2.init(apTrigger, this, target), true); - if (this.apRangeCalled) { - this.target = target; - } else { - this.clearWaypoints(); - this.interacted = true; - } - if (this.target === null) { - this.unsetMapFlag(); - } - } else if ((this.target instanceof PathingEntity || !moved) && this.inOperableDistance(this.target)) { - if (Environment_default.LOCAL_DEV && !opTrigger && !apTrigger) { - let debugname = '_'; - if (this.target instanceof Npc2) { - debugname = NpcType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } else if (this.target instanceof Loc) { - debugname = LocType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } else if (this.target instanceof Obj) { - debugname = ObjType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } else if ( - (this.targetSubject.com !== -1 && this.targetOp === ServerTriggerType_default.APNPCT) || - this.targetOp === ServerTriggerType_default.APPLAYERT || - this.targetOp === ServerTriggerType_default.APLOCT || - this.targetOp === ServerTriggerType_default.APOBJT - ) { - debugname = Component.get(this.targetSubject.com)?.comName ?? this.targetSubject.toString(); - } else if (this.targetSubject.type !== -1) { - debugname = ObjType.get(this.targetSubject.type)?.debugname ?? this.targetSubject.toString(); - } - this.messageGame(`No trigger for [${ServerTriggerType_default[this.targetOp + 7].toLowerCase()},${debugname}]`); - } - this.target = null; - this.messageGame('Nothing interesting happens.'); - this.interacted = true; - this.clearWaypoints(); - } - } - if (!this.interactWalkTrigger && this.walktrigger !== -1 && !this.protect && !this.delayed()) { - const trigger = ScriptProvider.get(this.walktrigger); - this.walktrigger = -1; - if (trigger) { - const script = ScriptRunner2.init(trigger, this); - this.interactWalkTrigger = true; - this.unsetMapFlag(); - this.runScript(script, true); - } - } - if (!this.interacted && !this.hasWaypoints() && !moved) { - this.messageGame("I can't reach that!"); - this.clearInteraction(); - } - if (this.interacted && !this.apRangeCalled && this.target === null) { - this.clearInteraction(); - } - } - getAppearanceInSlot(slot) { - let part = -1; - if (slot === 8) { - part = this.body[0]; - } else if (slot === 11) { - part = this.body[1]; - } else if (slot === 4) { - part = this.body[2]; - } else if (slot === 6) { - part = this.body[3]; - } else if (slot === 9) { - part = this.body[4]; - } else if (slot === 7) { - part = this.body[5]; - } else if (slot === 10) { - part = this.body[6]; - } - if (part === -1) { - return 0; - } else { - return 256 + part; - } - } - getCombatLevel() { - const base = 0.25 * (this.baseLevels[PlayerStat_default.DEFENCE] + this.baseLevels[PlayerStat_default.HITPOINTS] + Math.floor(this.baseLevels[PlayerStat_default.PRAYER] / 2)); - const melee = 0.325 * (this.baseLevels[PlayerStat_default.ATTACK] + this.baseLevels[PlayerStat_default.STRENGTH]); - const range = 0.325 * (Math.floor(this.baseLevels[PlayerStat_default.RANGED] / 2) + this.baseLevels[PlayerStat_default.RANGED]); - const magic = 0.325 * (Math.floor(this.baseLevels[PlayerStat_default.MAGIC] / 2) + this.baseLevels[PlayerStat_default.MAGIC]); - return Math.floor(base + Math.max(melee, range, magic)); - } - generateAppearance(inv) { - const stream = Packet.alloc(0); - stream.p1(this.gender); - stream.p1(this.headicons); - const skippedSlots = []; - let worn = this.getInventory(inv); - if (!worn) { - worn = new Inventory(0); - } - for (let i = 0; i < worn.capacity; i++) { - const equip = worn.get(i); - if (!equip) { - continue; - } - const config = ObjType.get(equip.id); - if (config.wearpos2 !== -1) { - if (skippedSlots.indexOf(config.wearpos2) === -1) { - skippedSlots.push(config.wearpos2); - } - } - if (config.wearpos3 !== -1) { - if (skippedSlots.indexOf(config.wearpos3) === -1) { - skippedSlots.push(config.wearpos3); - } - } - } - const parts = []; - for (let slot = 0; slot < 12; slot++) { - if (skippedSlots.indexOf(slot) !== -1) { - stream.p1(0); - parts[slot] = 0n; - continue; - } - const equip = worn.get(slot); - if (!equip) { - const appearanceValue = this.getAppearanceInSlot(slot); - if (appearanceValue < 1) { - stream.p1(0); - parts[slot] = 0n; - } else { - stream.p2(appearanceValue); - parts[slot] = BigInt(appearanceValue); - } - } else { - stream.p2(512 + equip.id); - parts[slot] = BigInt(512 + equip.id); - } - } - for (let i = 0; i < this.colors.length; i++) { - stream.p1(this.colors[i]); - } - stream.p2(this.basReadyAnim); - stream.p2(this.basTurnOnSpot); - stream.p2(this.basWalkForward); - stream.p2(this.basWalkBackward); - stream.p2(this.basWalkLeft); - stream.p2(this.basWalkRight); - stream.p2(this.basRunning); - stream.p8(this.username37); - stream.p1(this.combatLevel); - this.mask |= Player2.APPEARANCE; - this.appearance = new Uint8Array(stream.pos); - stream.pos = 0; - stream.gdata(this.appearance, 0, this.appearance.length); - stream.release(); - this.appearanceHashCode = 0n; - for (let part = 0; part < 12; part++) { - this.appearanceHashCode <<= 0x4n; - if (parts[part] >= 256) { - this.appearanceHashCode += parts[part] - 256n; - } - } - if (parts[0] >= 256) { - this.appearanceHashCode += (parts[0] - 256n) >> 4n; - } - if (parts[1] >= 256) { - this.appearanceHashCode += (parts[1] - 256n) >> 8n; - } - for (let part = 0; part < 5; part++) { - this.appearanceHashCode <<= 0x3n; - this.appearanceHashCode += BigInt(this.colors[part]); - } - this.appearanceHashCode <<= 0x1n; - this.appearanceHashCode += BigInt(this.gender); - } - getInventoryFromListener(listener) { - if (listener.source === -1) { - return World_default.getInventory(listener.type); - } else { - const player = World_default.getPlayerByUid(listener.source); - if (!player) { - return null; - } - return player.getInventory(listener.type); - } - } - getInventory(inv) { - if (inv === -1) { - return null; - } - const invType = InvType.get(inv); - let container = null; - if (!invType) { - return null; - } - if (invType.scope === InvType.SCOPE_SHARED) { - container = World_default.getInventory(inv); - } else { - container = this.invs.get(inv); - if (!container) { - container = Inventory.fromType(inv); - this.invs.set(inv, container); - } - } - return container; - } - invListenOnCom(inv, com, source) { - if (inv === -1) { - return; - } - const index = this.invListeners.findIndex(l => l.type === inv && l.com === com); - if (index !== -1) { - return; - } - const invType = InvType.get(inv); - if (invType.scope === InvType.SCOPE_SHARED) { - source = -1; - } - this.invListeners.push({type: inv, com, source, firstSeen: true}); - } - invStopListenOnCom(com) { - const index = this.invListeners.findIndex(l => l.com === com); - if (index === -1) { - return; - } - this.invListeners.splice(index, 1); - this.write(new UpdateInvStopTransmit(com)); - } - invGetSlot(inv, slot) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invGetSlot: Invalid inventory type: ' + inv); - } - if (!container.validSlot(slot)) { - throw new Error('invGetSlot: Invalid slot: ' + slot); - } - return container.get(slot); - } - invClear(inv) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invClear: Invalid inventory type: ' + inv); - } - container.removeAll(); - } - invAdd(inv, obj, count, assureFullInsertion = true) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invAdd: Invalid inventory type: ' + inv); - } - const transaction = container.add(obj, count, -1, assureFullInsertion); - return transaction.completed; - } - invSet(inv, obj, count, slot) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invSet: Invalid inventory type: ' + inv); - } - if (!container.validSlot(slot)) { - throw new Error('invSet: Invalid slot: ' + slot); - } - container.set(slot, {id: obj, count}); - } - invDel(inv, obj, count, beginSlot = -1) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invDel: Invalid inventory type: ' + inv); - } - if (beginSlot < -1 || beginSlot >= this.invSize(inv)) { - throw new Error('invDel: Invalid beginSlot: ' + beginSlot); - } - const transaction = container.remove(obj, count, beginSlot); - return transaction.completed; - } - invDelSlot(inv, slot) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invDelSlot: Invalid inventory type: ' + inv); - } - if (!container.validSlot(slot)) { - throw new Error('invDelSlot: Invalid slot: ' + slot); - } - container.delete(slot); - } - invSize(inv) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invSize: Invalid inventory type: ' + inv); - } - return container.capacity; - } - invTotal(inv, obj) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invTotal: Invalid inventory type: ' + inv); - } - return container.getItemCount(obj); - } - invFreeSpace(inv) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invFreeSpace: Invalid inventory type: ' + inv); - } - return container.freeSlotCount; - } - invItemSpace(inv, obj, count, size) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invItemSpace: Invalid inventory type: ' + inv); - } - const objType = ObjType.get(obj); - let uncert = obj; - if (objType.certtemplate >= 0 && objType.certlink >= 0) { - uncert = objType.certlink; - } - if (objType.stackable || uncert != obj || container.stackType == Inventory.ALWAYS_STACK) { - const stockObj = InvType.get(inv).stockobj?.includes(obj) === true; - if (this.invTotal(inv, obj) == 0 && this.invFreeSpace(inv) == 0 && !stockObj) { - return count; - } - return Math.max(0, count - (Inventory.STACK_LIMIT - this.invTotal(inv, obj))); - } - return Math.max(0, count - (this.invFreeSpace(inv) - (this.invSize(inv) - size))); - } - invMoveToSlot(fromInv, toInv, fromSlot, toSlot) { - const from = this.getInventory(fromInv); - if (!from) { - throw new Error('invMoveToSlot: Invalid inventory type: ' + fromInv); - } - if (!from.validSlot(fromSlot)) { - throw new Error('invMoveToSlot: Invalid from slot: ' + fromSlot); - } - const to = this.getInventory(toInv); - if (!to) { - throw new Error('invMoveToSlot: Invalid inventory type: ' + toInv); - } - if (!to.validSlot(toSlot)) { - throw new Error('invMoveToSlot: Invalid to slot: ' + toSlot); - } - const fromObj = this.invGetSlot(fromInv, fromSlot); - if (!fromObj) { - throw new Error(`invMoveToSlot: Invalid from obj was null. This means the obj does not exist at this slot: ${fromSlot}`); - } - const toObj = this.invGetSlot(toInv, toSlot); - this.invSet(toInv, fromObj.id, fromObj.count, toSlot); - if (toObj) { - this.invSet(fromInv, toObj.id, toObj.count, fromSlot); - } else { - this.invDelSlot(fromInv, fromSlot); - } - } - invMoveFromSlot(fromInv, toInv, fromSlot) { - const from = this.getInventory(fromInv); - if (!from) { - throw new Error('invMoveFromSlot: Invalid inventory type: ' + fromInv); - } - const to = this.getInventory(toInv); - if (!to) { - throw new Error('invMoveFromSlot: Invalid inventory type: ' + toInv); - } - if (!from.validSlot(fromSlot)) { - throw new Error('invMoveFromSlot: Invalid from slot: ' + fromSlot); - } - const fromObj = this.invGetSlot(fromInv, fromSlot); - if (!fromObj) { - throw new Error(`invMoveFromSlot: Invalid from obj was null. This means the obj does not exist at this slot: ${fromSlot}`); - } - return { - overflow: fromObj.count - this.invAdd(toInv, fromObj.id, fromObj.count), - fromObj: fromObj.id - }; - } - invTotalCat(inv, category) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invTotalCat: Invalid inventory type: ' + inv); - } - return container.itemsFiltered.filter(obj => ObjType.get(obj.id).category == category).reduce((count, obj) => count + obj.count, 0); - } - _invTotalParam(inv, param, stack) { - const container = this.getInventory(inv); - if (!container) { - throw new Error('invTotalParam: Invalid inventory type: ' + inv); - } - const paramType = ParamType.get(param); - let total = 0; - for (let slot = 0; slot < container.capacity; slot++) { - const item = container.items[slot]; - if (!item || item.id < 0 || item.id >= ObjType.count) { - continue; - } - const obj = ObjType.get(item.id); - const value = ParamHelper.getIntParam(paramType.id, obj, paramType.defaultInt); - if (stack) { - total += item.count * value; - } else { - total += value; - } - } - return total; - } - invTotalParam(inv, param) { - return this._invTotalParam(inv, param, false); - } - invTotalParamStack(inv, param) { - return this._invTotalParam(inv, param, true); - } - getVar(id) { - const varp = VarPlayerType.get(id); - return varp.type === ScriptVarType.STRING ? this.varsString[varp.id] : this.vars[varp.id]; - } - setVar(id, value) { - const varp = VarPlayerType.get(id); - if (varp.type === ScriptVarType.STRING && typeof value === 'string') { - this.varsString[varp.id] = value; - } else if (typeof value === 'number') { - this.vars[varp.id] = value; - if (varp.transmit) { - this.writeVarp(id, value); - } - } - } - writeVarp(id, value) { - if (value >= -128 && value <= 127) { - this.write(new VarpSmall(id, value)); - } else { - this.write(new VarpLarge(id, value)); - } - } - addXp(stat, xp) { - if (xp < 0) { - throw new Error(`Invalid xp parameter for addXp call: Stat was: ${stat}, Exp was: ${xp}`); - } - if (xp == 0) { - return; - } - const multi = Number(Environment_default.XP_MULTIPLIER) || 1; - this.stats[stat] += xp * multi; - if (this.stats[stat] > 2000000000) { - this.stats[stat] = 2000000000; - } - const before = this.baseLevels[stat]; - if (this.levels[stat] === this.baseLevels[stat]) { - this.levels[stat] = getLevelByExp(this.stats[stat]); - } - this.baseLevels[stat] = getLevelByExp(this.stats[stat]); - if (this.baseLevels[stat] > before) { - if (this.levels[stat] < before) { - this.levels[stat] += 1; - } - const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.LEVELUP, stat, -1); - if (script) { - this.enqueueScript(script, 1 /* ENGINE */); - } - } - if (this.combatLevel != this.getCombatLevel()) { - this.combatLevel = this.getCombatLevel(); - this.generateAppearance(InvType.WORN); - } - } - setLevel(stat, level) { - level = Math.min(99, Math.max(1, level)); - this.baseLevels[stat] = level; - this.levels[stat] = level; - this.stats[stat] = getExpByLevel(level); - if (this.getCombatLevel() != this.combatLevel) { - this.combatLevel = this.getCombatLevel(); - this.generateAppearance(InvType.WORN); - } - } - playAnimation(anim, delay) { - if (anim >= SeqType.count || this.animProtect) { - return; - } - if (anim == -1 || this.animId == -1 || SeqType.get(anim).priority > SeqType.get(this.animId).priority || SeqType.get(this.animId).priority === 0) { - this.animId = anim; - this.animDelay = delay; - this.mask |= Player2.ANIM; - } - } - spotanim(spotanim, height, delay) { - this.graphicId = spotanim; - this.graphicHeight = height; - this.graphicDelay = delay; - this.mask |= Player2.SPOTANIM; - } - applyDamage(damage, type) { - this.damageTaken = damage; - this.damageType = type; - const current = this.levels[PlayerStat_default.HITPOINTS]; - if (current - damage <= 0) { - this.levels[PlayerStat_default.HITPOINTS] = 0; - this.damageTaken = current; - } else { - this.levels[PlayerStat_default.HITPOINTS] = current - damage; - } - this.mask |= Player2.DAMAGE; - } - say(message) { - this.chat = message; - this.mask |= Player2.SAY; - } - faceSquare(x, z2) { - this.faceX = x * 2 + 1; - this.faceZ = z2 * 2 + 1; - this.orientation = Position.face(this.x, this.z, x, z2); - this.mask |= Player2.FACE_COORD; - } - playSong(name) { - name = name.toLowerCase().replaceAll(' ', '_'); - if (!name) { - return; - } - const song = PRELOADED.get(name + '.mid'); - const crc = PRELOADED_CRC.get(name + '.mid'); - if (song && crc) { - const length = song.length; - this.write(new MidiSong(name, crc, length)); - } - } - playJingle(delay, name) { - name = name.toLowerCase().replaceAll('_', ' '); - if (!name) { - return; - } - const jingle = PRELOADED.get(name + '.mid'); - if (jingle) { - this.write(new MidiJingle(delay, jingle)); - } - } - openMainModal(com) { - if (this.modalState & 4) { - this.write(new IfClose()); - this.modalState &= ~4; - this.modalSidebar = -1; - } - this.modalState |= 1; - this.modalTop = com; - this.refreshModal = true; - } - openChat(com) { - this.modalState |= 2; - this.modalBottom = com; - this.refreshModal = true; - } - openSideOverlay(com) { - this.modalState |= 4; - this.modalSidebar = com; - this.refreshModal = true; - } - openChatSticky(com) { - this.write(new TutorialOpenChat(com)); - this.modalState |= 8; - this.modalSticky = com; - } - openMainModalSideOverlay(top, side) { - this.modalState |= 1; - this.modalTop = top; - this.modalState |= 4; - this.modalSidebar = side; - this.refreshModal = true; - } - exactMove(startX, startZ, endX, endZ, startCycle, endCycle, direction) { - this.exactStartX = startX; - this.exactStartZ = startZ; - this.exactEndX = endX; - this.exactEndZ = endZ; - this.exactMoveStart = startCycle; - this.exactMoveEnd = endCycle; - this.exactMoveDirection = direction; - this.mask |= Player2.EXACT_MOVE; - this.x = endX; - this.z = endZ; - this.lastStepX = this.x - 1; - this.lastStepZ = this.z; - } - setTab(com, tab) { - this.overlaySide[tab] = com; - this.write(new IfOpenSideOverlay(com, tab)); - } - isComponentVisible(com) { - return this.modalTop === com.rootLayer || this.modalBottom === com.rootLayer || this.modalSidebar === com.rootLayer || this.overlaySide.findIndex(l => l === com.rootLayer) !== -1 || this.modalSticky === com.rootLayer; - } - updateAfkZones() { - this.lastAfkZone = Math.min(1000, this.lastAfkZone + 1); - if (this.withinAfkZone()) { - return; - } - const coord = Position.packCoord(0, this.x - 10, this.z - 10); - if (this.moveSpeed === MoveSpeed_default.INSTANT && this.jump) { - this.afkZones[1] = coord; - } else { - this.afkZones[1] = this.afkZones[0]; - } - this.afkZones[0] = coord; - this.lastAfkZone = 0; - } - zonesAfk() { - return this.lastAfkZone === 1000; - } - withinAfkZone() { - const size = 21; - for (let index = 0; index < this.afkZones.length; index++) { - const coord = Position.unpackCoord(this.afkZones[index]); - if (Position.intersects(this.x, this.z, this.width, this.length, coord.x, coord.z, size, size)) { - return true; - } - } - return false; - } - isInWilderness() { - if (this.x >= 2944 && this.x < 3392 && this.z >= 3520 && this.z < 6400) { - return true; - } else if (this.x >= 2944 && this.x < 3392 && this.z >= 9920 && this.z < 12800) { - return true; - } else { - return false; - } - } - runScript(script, protect = false, force = false) { - if (!force && protect && (this.protect || this.delayed())) { - return -1; - } - if (protect) { - script.pointerAdd(ScriptPointer_default.ProtectedActivePlayer); - this.protect = true; - } - const state = ScriptRunner2.execute(script); - if (protect) { - this.protect = false; - } - if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer) && script._activePlayer) { - script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer); - script._activePlayer.protect = false; - } - if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer2) && script._activePlayer2) { - script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer2); - script._activePlayer2.protect = false; - } - return state; - } - executeScript(script, protect = false, force = false) { - const state = this.runScript(script, protect, force); - if (state === -1) { - return; - } - if (state !== ScriptState.FINISHED && state !== ScriptState.ABORTED) { - if (state === ScriptState.WORLD_SUSPENDED) { - World_default.enqueueScript(script, script.popInt()); - } else if (state === ScriptState.NPC_SUSPENDED) { - script.activeNpc.activeScript = script; - } else { - script.activePlayer.activeScript = script; - script.activePlayer.protect = protect; - } - } else if (script === this.activeScript) { - this.activeScript = null; - if ((this.modalState & 1) == 0) { - this.closeModal(); - } - } - } - wrappedMessageGame(mes) { - const font = FontType.get(1); - const lines = font.split(mes, 456); - for (const line of lines) { - this.messageGame(line); - } - } - write(message) { - if (message.priority === ServerProtPriority.HIGH) { - this.highPriorityOut.push(message); - } else { - this.lowPriorityOut.push(message); - } - } - unsetMapFlag() { - this.clearWaypoints(); - this.write(new UnsetMapFlag()); - } - hintNpc(nid) { - this.write(new HintArrow(1, nid, 0, 0, 0, 0)); - } - hintTile(offset, x, z2, height) { - this.write(new HintArrow(offset, 0, 0, x, z2, height)); - } - hintPlayer(pid) { - this.write(new HintArrow(10, 0, pid, 0, 0, 0)); - } - stopHint() { - this.write(new HintArrow(-1, 0, 0, 0, 0, 0)); - } - lastLoginInfo(lastLoginIp, daysSinceLogin, daysSinceRecoveryChange, unreadMessageCount) { - this.write(new LastLoginInfo(lastLoginIp, daysSinceLogin, daysSinceRecoveryChange, unreadMessageCount)); - this.modalState |= 16; - } - logout() {} - terminate() {} - messageGame(msg) { - this.write(new MessageGame(msg)); - } -} - -// src/lostcity/network/225/incoming/prot/ClientProt.ts -class ClientProt { - index; - id; - length; - static all = []; - static byId = []; - static REBUILD_GETMAPS = new ClientProt(4, 150, -1); - static NO_TIMEOUT = new ClientProt(6, 108, 0); - static IDLE_TIMER = new ClientProt(30, 70, 0); - static EVENT_TRACKING = new ClientProt(34, 81, -2); - static EVENT_CAMERA_POSITION = new ClientProt(35, 189, 6); - static ANTICHEAT_OPLOGIC1 = new ClientProt(60, 7, 4); - static ANTICHEAT_OPLOGIC2 = new ClientProt(61, 88, 4); - static ANTICHEAT_OPLOGIC3 = new ClientProt(62, 30, 3); - static ANTICHEAT_OPLOGIC4 = new ClientProt(63, 176, 2); - static ANTICHEAT_OPLOGIC5 = new ClientProt(64, 220, 0); - static ANTICHEAT_OPLOGIC6 = new ClientProt(65, 66, 4); - static ANTICHEAT_OPLOGIC7 = new ClientProt(66, 17, 4); - static ANTICHEAT_OPLOGIC8 = new ClientProt(67, 2, 2); - static ANTICHEAT_OPLOGIC9 = new ClientProt(68, 238, 1); - static ANTICHEAT_CYCLELOGIC1 = new ClientProt(70, 233, 1); - static ANTICHEAT_CYCLELOGIC2 = new ClientProt(71, 146, -1); - static ANTICHEAT_CYCLELOGIC3 = new ClientProt(74, 215, 3); - static ANTICHEAT_CYCLELOGIC4 = new ClientProt(72, 236, 4); - static ANTICHEAT_CYCLELOGIC5 = new ClientProt(75, 85, 0); - static ANTICHEAT_CYCLELOGIC6 = new ClientProt(73, 219, -1); - static OPOBJ1 = new ClientProt(80, 140, 6); - static OPOBJ2 = new ClientProt(81, 40, 6); - static OPOBJ3 = new ClientProt(82, 200, 6); - static OPOBJ4 = new ClientProt(83, 178, 6); - static OPOBJ5 = new ClientProt(84, 247, 6); - static OPOBJT = new ClientProt(88, 138, 8); - static OPOBJU = new ClientProt(89, 239, 12); - static OPNPC1 = new ClientProt(100, 194, 2); - static OPNPC2 = new ClientProt(101, 8, 2); - static OPNPC3 = new ClientProt(102, 27, 2); - static OPNPC4 = new ClientProt(103, 113, 2); - static OPNPC5 = new ClientProt(104, 100, 2); - static OPNPCT = new ClientProt(108, 134, 4); - static OPNPCU = new ClientProt(109, 202, 8); - static OPLOC1 = new ClientProt(120, 245, 6); - static OPLOC2 = new ClientProt(121, 172, 6); - static OPLOC3 = new ClientProt(122, 96, 6); - static OPLOC4 = new ClientProt(123, 97, 6); - static OPLOC5 = new ClientProt(124, 116, 6); - static OPLOCT = new ClientProt(128, 9, 8); - static OPLOCU = new ClientProt(129, 75, 12); - static OPPLAYER1 = new ClientProt(140, 164, 2); - static OPPLAYER2 = new ClientProt(141, 53, 2); - static OPPLAYER3 = new ClientProt(142, 185, 2); - static OPPLAYER4 = new ClientProt(143, 206, 2); - static OPPLAYERT = new ClientProt(148, 177, 4); - static OPPLAYERU = new ClientProt(149, 248, 8); - static OPHELD1 = new ClientProt(160, 195, 6); - static OPHELD2 = new ClientProt(161, 71, 6); - static OPHELD3 = new ClientProt(162, 133, 6); - static OPHELD4 = new ClientProt(163, 157, 6); - static OPHELD5 = new ClientProt(164, 211, 6); - static OPHELDT = new ClientProt(168, 48, 8); - static OPHELDU = new ClientProt(169, 130, 12); - static INV_BUTTON1 = new ClientProt(190, 31, 6); - static INV_BUTTON2 = new ClientProt(191, 59, 6); - static INV_BUTTON3 = new ClientProt(192, 212, 6); - static INV_BUTTON4 = new ClientProt(193, 38, 6); - static INV_BUTTON5 = new ClientProt(194, 6, 6); - static IF_BUTTON = new ClientProt(200, 155, 2); - static RESUME_PAUSEBUTTON = new ClientProt(201, 235, 2); - static CLOSE_MODAL = new ClientProt(202, 231, 0); - static RESUME_P_COUNTDIALOG = new ClientProt(203, 237, 4); - static TUTORIAL_CLICKSIDE = new ClientProt(204, 175, 1); - static MOVE_OPCLICK = new ClientProt(242, 93, -1); - static BUG_REPORT = new ClientProt(243, 190, 10); - static MOVE_MINIMAPCLICK = new ClientProt(244, 165, -1); - static INV_BUTTOND = new ClientProt(245, 159, 6); - static IGNORELIST_DEL = new ClientProt(246, 171, 8); - static IGNORELIST_ADD = new ClientProt(247, 79, 8); - static IF_PLAYERDESIGN = new ClientProt(248, 52, 13); - static CHAT_SETMODE = new ClientProt(249, 244, 3); - static MESSAGE_PRIVATE = new ClientProt(250, 148, -1); - static FRIENDLIST_DEL = new ClientProt(251, 11, 8); - static FRIENDLIST_ADD = new ClientProt(252, 118, 8); - static CLIENT_CHEAT = new ClientProt(253, 4, -1); - static MESSAGE_PUBLIC = new ClientProt(254, 158, -1); - static MOVE_GAMECLICK = new ClientProt(255, 181, -1); - constructor(index, id, length) { - this.index = index; - this.id = id; - this.length = length; - ClientProt.all[index] = this; - ClientProt.byId[id] = this; - } -} - -// src/lostcity/network/incoming/codec/MessageDecoder.ts -class MessageDecoder {} - -// src/lostcity/network/incoming/IncomingMessage.ts -class IncomingMessage {} - -// src/lostcity/network/incoming/prot/ClientProtCategory.ts -class ClientProtCategory { - id; - limit; - static CLIENT_EVENT = new ClientProtCategory(0, 20); - static USER_EVENT = new ClientProtCategory(1, 5); - constructor(id, limit) { - this.id = id; - this.limit = limit; - } -} - -// src/lostcity/network/incoming/model/ClientCheat.ts -class ClientCheat extends IncomingMessage { - input; - category = ClientProtCategory.USER_EVENT; - constructor(input) { - super(); - this.input = input; - } -} - -// src/lostcity/network/225/incoming/codec/ClientCheatDecoder.ts -class ClientCheatDecoder extends MessageDecoder { - prot = ClientProt.CLIENT_CHEAT; - decode(buf) { - const input = buf.gjstr(); - return new ClientCheat(input); - } -} - -// src/lostcity/network/incoming/model/CloseModal.ts -class CloseModal extends IncomingMessage { - category = ClientProtCategory.USER_EVENT; -} - -// src/lostcity/network/225/incoming/codec/CloseModalDecoder.ts -class CloseModalDecoder extends MessageDecoder { - prot = ClientProt.CLOSE_MODAL; - decode() { - return new CloseModal(); - } -} - -// src/lostcity/network/incoming/model/IdleTimer.ts -class IdleTimer extends IncomingMessage { - category = ClientProtCategory.CLIENT_EVENT; -} - -// src/lostcity/network/225/incoming/codec/IdleTimerDecoder.ts -class IdleTimerDecoder extends MessageDecoder { - prot = ClientProt.IDLE_TIMER; - decode() { - return new IdleTimer(); - } -} - -// src/lostcity/network/incoming/model/IfButton.ts -class IfButton extends IncomingMessage { - component; - category = ClientProtCategory.USER_EVENT; - constructor(component) { - super(); - this.component = component; - } -} - -// src/lostcity/network/225/incoming/codec/IfButtonDecoder.ts -class IfButtonDecoder extends MessageDecoder { - prot = ClientProt.IF_BUTTON; - decode(buf) { - const component = buf.g2(); - return new IfButton(component); - } -} - -// src/lostcity/network/incoming/model/IfPlayerDesign.ts -class IfPlayerDesign extends IncomingMessage { - gender; - idkit; - color; - category = ClientProtCategory.USER_EVENT; - constructor(gender, idkit, color) { - super(); - this.gender = gender; - this.idkit = idkit; - this.color = color; - } -} - -// src/lostcity/network/225/incoming/codec/IfPlayerDesignDecoder.ts -class IfPlayerDesignDecoder extends MessageDecoder { - prot = ClientProt.IF_PLAYERDESIGN; - decode(buf) { - const gender = buf.g1(); - const idkit = []; - for (let i = 0; i < 7; i++) { - idkit[i] = buf.g1(); - if (idkit[i] === 255) { - idkit[i] = -1; - } - } - const color = []; - for (let i = 0; i < 5; i++) { - color[i] = buf.g1(); - } - return new IfPlayerDesign(gender, idkit, color); - } -} - -// src/lostcity/network/incoming/model/InvButton.ts -class InvButton extends IncomingMessage { - op; - obj; - slot; - component; - category = ClientProtCategory.USER_EVENT; - constructor(op, obj, slot, component) { - super(); - this.op = op; - this.obj = obj; - this.slot = slot; - this.component = component; - } -} - -// src/lostcity/network/225/incoming/codec/InvButtonDecoder.ts -class InvButtonDecoder extends MessageDecoder { - prot; - op; - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const obj = buf.g2(); - const slot = buf.g2(); - const component = buf.g2(); - return new InvButton(this.op, obj, slot, component); - } -} - -// src/lostcity/network/incoming/model/InvButtonD.ts -class InvButtonD extends IncomingMessage { - component; - slot; - targetSlot; - category = ClientProtCategory.USER_EVENT; - constructor(component, slot, targetSlot) { - super(); - this.component = component; - this.slot = slot; - this.targetSlot = targetSlot; - } -} - -// src/lostcity/network/225/incoming/codec/InvButtonDDecoder.ts -class InvButtonDDecoder extends MessageDecoder { - prot = ClientProt.INV_BUTTOND; - decode(buf) { - const component = buf.g2(); - const slot = buf.g2(); - const targetSlot = buf.g2(); - return new InvButtonD(component, slot, targetSlot); - } -} - -// src/lostcity/network/incoming/model/MessagePrivate.ts -class MessagePrivate3 extends IncomingMessage { - username; - input; - category = ClientProtCategory.USER_EVENT; - constructor(username, input) { - super(); - this.username = username; - this.input = input; - } -} - -// src/lostcity/network/225/incoming/codec/MessagePrivateDecoder.ts -class MessagePrivateDecoder extends MessageDecoder { - prot = ClientProt.MESSAGE_PRIVATE; - decode(buf) { - const username = buf.g8(); - const input = WordPack.unpack(buf, buf.length - 8); - return new MessagePrivate3(username, input); - } -} - -// src/lostcity/network/incoming/model/MessagePublic.ts -class MessagePublic extends IncomingMessage { - input; - color; - effect; - category = ClientProtCategory.USER_EVENT; - constructor(input, color, effect) { - super(); - this.input = input; - this.color = color; - this.effect = effect; - } -} - -// src/lostcity/network/225/incoming/codec/MessagePublicDecoder.ts -class MessagePublicDecoder extends MessageDecoder { - prot = ClientProt.MESSAGE_PUBLIC; - decode(buf) { - const color = buf.g1(); - const effect = buf.g1(); - const input = WordPack.unpack(buf, buf.length - 2); - return new MessagePublic(input, color, effect); - } -} - -// src/lostcity/network/incoming/model/OpHeld.ts -class OpHeld extends IncomingMessage { - op; - obj; - slot; - component; - category = ClientProtCategory.USER_EVENT; - constructor(op, obj, slot, component) { - super(); - this.op = op; - this.obj = obj; - this.slot = slot; - this.component = component; - } -} - -// src/lostcity/network/225/incoming/codec/OpHeldDecoder.ts -class OpHeldDecoder extends MessageDecoder { - prot; - op; - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const obj = buf.g2(); - const slot = buf.g2(); - const component = buf.g2(); - return new OpHeld(this.op, obj, slot, component); - } -} - -// src/lostcity/network/incoming/model/OpHeldT.ts -class OpHeldT extends IncomingMessage { - obj; - slot; - component; - spellComponent; - category = ClientProtCategory.USER_EVENT; - constructor(obj, slot, component, spellComponent) { - super(); - this.obj = obj; - this.slot = slot; - this.component = component; - this.spellComponent = spellComponent; - } -} - -// src/lostcity/network/225/incoming/codec/OpHeldTDecoder.ts -class OpHeldTDecoder extends MessageDecoder { - prot = ClientProt.OPHELDT; - decode(buf) { - const obj = buf.g2(); - const slot = buf.g2(); - const component = buf.g2(); - const spellComponent = buf.g2(); - return new OpHeldT(obj, slot, component, spellComponent); - } -} - -// src/lostcity/network/incoming/model/OpHeldU.ts -class OpHeldU extends IncomingMessage { - obj; - slot; - component; - useObj; - useSlot; - useComponent; - category = ClientProtCategory.USER_EVENT; - constructor(obj, slot, component, useObj, useSlot, useComponent) { - super(); - this.obj = obj; - this.slot = slot; - this.component = component; - this.useObj = useObj; - this.useSlot = useSlot; - this.useComponent = useComponent; - } -} - -// src/lostcity/network/225/incoming/codec/OpHeldUDecoder.ts -class OpHeldUDecoder extends MessageDecoder { - prot = ClientProt.OPHELDU; - decode(buf) { - const obj = buf.g2(); - const slot = buf.g2(); - const component = buf.g2(); - const useObj = buf.g2(); - const useSlot = buf.g2(); - const useComponent = buf.g2(); - return new OpHeldU(obj, slot, component, useObj, useSlot, useComponent); - } -} - -// src/lostcity/network/incoming/model/OpLoc.ts -class OpLoc extends IncomingMessage { - op; - x; - z2; - loc; - category = ClientProtCategory.USER_EVENT; - constructor(op, x, z2, loc) { - super(); - this.op = op; - this.x = x; - this.z = z2; - this.loc = loc; - } -} - -// src/lostcity/network/225/incoming/codec/OpLocDecoder.ts -class OpLocDecoder extends MessageDecoder { - prot; - op; - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const x = buf.g2(); - const z2 = buf.g2(); - const loc = buf.g2(); - return new OpLoc(this.op, x, z2, loc); - } -} - -// src/lostcity/network/incoming/model/OpLocT.ts -class OpLocT extends IncomingMessage { - x; - z2; - loc; - spellComponent; - category = ClientProtCategory.USER_EVENT; - constructor(x, z2, loc, spellComponent) { - super(); - this.x = x; - this.z = z2; - this.loc = loc; - this.spellComponent = spellComponent; - } -} - -// src/lostcity/network/225/incoming/codec/OpLocTDecoder.ts -class OpLocTDecoder extends MessageDecoder { - prot = ClientProt.OPLOCT; - decode(buf) { - const x = buf.g2(); - const z2 = buf.g2(); - const loc = buf.g2(); - const spellComponent = buf.g2(); - return new OpLocT(x, z2, loc, spellComponent); - } -} - -// src/lostcity/network/incoming/model/OpLocU.ts -class OpLocU extends IncomingMessage { - x; - z2; - loc; - useObj; - useSlot; - useComponent; - category = ClientProtCategory.USER_EVENT; - constructor(x, z2, loc, useObj, useSlot, useComponent) { - super(); - this.x = x; - this.z = z2; - this.loc = loc; - this.useObj = useObj; - this.useSlot = useSlot; - this.useComponent = useComponent; - } -} - -// src/lostcity/network/225/incoming/codec/OpLocUDecoder.ts -class OpLocUDecoder extends MessageDecoder { - prot = ClientProt.OPLOCU; - decode(buf) { - const x = buf.g2(); - const z2 = buf.g2(); - const loc = buf.g2(); - const useObj = buf.g2(); - const useSlot = buf.g2(); - const useComponent = buf.g2(); - return new OpLocU(x, z2, loc, useObj, useSlot, useComponent); - } -} - -// src/lostcity/network/incoming/model/OpNpc.ts -class OpNpc extends IncomingMessage { - op; - nid; - category = ClientProtCategory.USER_EVENT; - constructor(op, nid) { - super(); - this.op = op; - this.nid = nid; - } -} - -// src/lostcity/network/225/incoming/codec/OpNpcDecoder.ts -class OpNpcDecoder extends MessageDecoder { - prot; - op; - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const nid = buf.g2(); - return new OpNpc(this.op, nid); - } -} - -// src/lostcity/network/incoming/model/OpNpcT.ts -class OpNpcT extends IncomingMessage { - nid; - spellComponent; - category = ClientProtCategory.USER_EVENT; - constructor(nid, spellComponent) { - super(); - this.nid = nid; - this.spellComponent = spellComponent; - } -} - -// src/lostcity/network/225/incoming/codec/OpNpcTDecoder.ts -class OpNpcTDecoder extends MessageDecoder { - prot = ClientProt.OPNPCT; - decode(buf) { - const nid = buf.g2(); - const spellComponent = buf.g2(); - return new OpNpcT(nid, spellComponent); - } -} - -// src/lostcity/network/incoming/model/OpNpcU.ts -class OpNpcU extends IncomingMessage { - nid; - useObj; - useSlot; - useComponent; - category = ClientProtCategory.USER_EVENT; - constructor(nid, useObj, useSlot, useComponent) { - super(); - this.nid = nid; - this.useObj = useObj; - this.useSlot = useSlot; - this.useComponent = useComponent; - } -} - -// src/lostcity/network/225/incoming/codec/OpNpcUDecoder.ts -class OpNpcUDecoder extends MessageDecoder { - prot = ClientProt.OPNPCU; - decode(buf) { - const nid = buf.g2(); - const useObj = buf.g2(); - const useSlot = buf.g2(); - const useComponent = buf.g2(); - return new OpNpcU(nid, useObj, useSlot, useComponent); - } -} - -// src/lostcity/network/incoming/model/OpObj.ts -class OpObj extends IncomingMessage { - op; - x; - z2; - obj; - category = ClientProtCategory.USER_EVENT; - constructor(op, x, z2, obj) { - super(); - this.op = op; - this.x = x; - this.z = z2; - this.obj = obj; - } -} - -// src/lostcity/network/225/incoming/codec/OpObjDecoder.ts -class OpObjDecoder extends MessageDecoder { - prot; - op; - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const x = buf.g2(); - const z2 = buf.g2(); - const obj = buf.g2(); - return new OpObj(this.op, x, z2, obj); - } -} - -// src/lostcity/network/incoming/model/OpObjT.ts -class OpObjT extends IncomingMessage { - x; - z2; - obj; - spellComponent; - category = ClientProtCategory.USER_EVENT; - constructor(x, z2, obj, spellComponent) { - super(); - this.x = x; - this.z = z2; - this.obj = obj; - this.spellComponent = spellComponent; - } -} - -// src/lostcity/network/225/incoming/codec/OpObjTDecoder.ts -class OpObjTDecoder extends MessageDecoder { - prot = ClientProt.OPOBJT; - decode(buf) { - const x = buf.g2(); - const z2 = buf.g2(); - const obj = buf.g2(); - const spellComponent = buf.g2(); - return new OpObjT(x, z2, obj, spellComponent); - } -} - -// src/lostcity/network/incoming/model/OpObjU.ts -class OpObjU extends IncomingMessage { - x; - z2; - obj; - useObj; - useSlot; - useComponent; - category = ClientProtCategory.USER_EVENT; - constructor(x, z2, obj, useObj, useSlot, useComponent) { - super(); - this.x = x; - this.z = z2; - this.obj = obj; - this.useObj = useObj; - this.useSlot = useSlot; - this.useComponent = useComponent; - } -} - -// src/lostcity/network/225/incoming/codec/OpObjUDecoder.ts -class OpObjUDecoder extends MessageDecoder { - prot = ClientProt.OPOBJU; - decode(buf) { - const x = buf.g2(); - const z2 = buf.g2(); - const obj = buf.g2(); - const useObj = buf.g2(); - const useSlot = buf.g2(); - const useComponent = buf.g2(); - return new OpObjU(x, z2, obj, useObj, useSlot, useComponent); - } -} - -// src/lostcity/network/incoming/model/OpPlayer.ts -class OpPlayer extends IncomingMessage { - op; - pid; - category = ClientProtCategory.USER_EVENT; - constructor(op, pid) { - super(); - this.op = op; - this.pid = pid; - } -} - -// src/lostcity/network/225/incoming/codec/OpPlayerDecoder.ts -class OpPlayerDecoder extends MessageDecoder { - prot; - op; - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const pid = buf.g2(); - return new OpPlayer(this.op, pid); - } -} - -// src/lostcity/network/incoming/model/OpPlayerT.ts -class OpPlayerT extends IncomingMessage { - pid; - spellComponent; - category = ClientProtCategory.USER_EVENT; - constructor(pid, spellComponent) { - super(); - this.pid = pid; - this.spellComponent = spellComponent; - } -} - -// src/lostcity/network/225/incoming/codec/OpPlayerTDecoder.ts -class OpPlayerTDecoder extends MessageDecoder { - prot = ClientProt.OPPLAYERT; - decode(buf) { - const pid = buf.g2(); - const spellComponent = buf.g2(); - return new OpPlayerT(pid, spellComponent); - } -} - -// src/lostcity/network/incoming/model/OpPlayerU.ts -class OpPlayerU extends IncomingMessage { - pid; - useObj; - useSlot; - useComponent; - category = ClientProtCategory.USER_EVENT; - constructor(pid, useObj, useSlot, useComponent) { - super(); - this.pid = pid; - this.useObj = useObj; - this.useSlot = useSlot; - this.useComponent = useComponent; - } -} - -// src/lostcity/network/225/incoming/codec/OpPlayerUDecoder.ts -class OpPlayerUDecoder extends MessageDecoder { - prot = ClientProt.OPPLAYERU; - decode(buf) { - const pid = buf.g2(); - const useObj = buf.g2(); - const useSlot = buf.g2(); - const useComponent = buf.g2(); - return new OpPlayerU(pid, useObj, useSlot, useComponent); - } -} - -// src/lostcity/network/incoming/model/RebuildGetMaps.ts -class RebuildGetMaps extends IncomingMessage { - maps; - category = ClientProtCategory.USER_EVENT; - constructor(maps) { - super(); - this.maps = maps; - } -} - -// src/lostcity/network/225/incoming/codec/RebuildGetMapsDecoder.ts -class RebuildGetMapsDecoder extends MessageDecoder { - prot = ClientProt.REBUILD_GETMAPS; - decode(buf) { - const maps = []; - const count = buf.length / 3; - for (let i = 0; i < count; i++) { - const type = buf.g1(); - const x = buf.g1(); - const z2 = buf.g1(); - maps.push({type, x, z: z2}); - } - return new RebuildGetMaps(maps); - } -} - -// src/lostcity/network/incoming/model/ResumePauseButton.ts -class ResumePauseButton extends IncomingMessage { - category = ClientProtCategory.USER_EVENT; -} - -// src/lostcity/network/225/incoming/codec/ResumePauseButtonDecoder.ts -class ResumePauseButtonDecoder extends MessageDecoder { - prot = ClientProt.RESUME_PAUSEBUTTON; - decode() { - return new ResumePauseButton(); - } -} - -// src/lostcity/network/incoming/model/ResumePCountDialog.ts -class ResumePCountDialog extends IncomingMessage { - input; - category = ClientProtCategory.USER_EVENT; - constructor(input) { - super(); - this.input = input; - } -} - -// src/lostcity/network/225/incoming/codec/ResumePCountDialogDecoder.ts -class ResumePCountDialogDecoder extends MessageDecoder { - prot = ClientProt.RESUME_P_COUNTDIALOG; - decode(buf) { - const input = buf.g4(); - return new ResumePCountDialog(input); - } -} - -// src/lostcity/network/incoming/model/TutorialClickSide.ts -class TutorialClickSide extends IncomingMessage { - tab; - category = ClientProtCategory.USER_EVENT; - constructor(tab) { - super(); - this.tab = tab; - } -} - -// src/lostcity/network/225/incoming/codec/TutorialClickSideDecoder.ts -class TutorialClickSideDecoder extends MessageDecoder { - prot = ClientProt.TUTORIAL_CLICKSIDE; - decode(buf) { - const tab = buf.g1(); - return new TutorialClickSide(tab); - } -} - -// src/lostcity/network/incoming/handler/MessageHandler.ts -class MessageHandler {} - -// src/lostcity/network/225/incoming/handler/InvButtonHandler.ts -class InvButtonHandler extends MessageHandler { - handle(message, player) { - const {op, obj: item, slot, component: comId} = message; - const com = Component.get(comId); - if (typeof com === 'undefined' || !com.inventoryOptions || !com.inventoryOptions.length || !player.isComponentVisible(com)) { - return false; - } - if (!com.inventoryOptions[op - 1]) { - return false; - } - const listener = player.invListeners.find(l => l.com === comId); - if (!listener) { - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - return false; - } - if (player.delayed()) { - return false; - } - player.lastItem = item; - player.lastSlot = slot; - let trigger; - if (op === 1) { - trigger = ServerTriggerType_default.INV_BUTTON1; - } else if (op === 2) { - trigger = ServerTriggerType_default.INV_BUTTON2; - } else if (op === 3) { - trigger = ServerTriggerType_default.INV_BUTTON3; - } else if (op === 4) { - trigger = ServerTriggerType_default.INV_BUTTON4; - } else { - trigger = ServerTriggerType_default.INV_BUTTON5; - } - const script = ScriptProvider.getByTrigger(trigger, comId, -1); - if (script) { - const root = Component.get(com.rootLayer); - player.executeScript(ScriptRunner2.init(script, player), root.overlay == false); - } else { - if (Environment_default.LOCAL_DEV) { - player.messageGame(`No trigger for [${ServerTriggerType_default.toString(trigger)},${com.comName}]`); - } - } - return true; - } -} - -// src/lostcity/server/ClientSocket.ts -class ClientSocket { - state = -1; - remoteAddress; - totalBytesRead = 0; - totalBytesWritten = 0; - uniqueId = crypto.randomUUID(); - encryptor = null; - decryptor = null; - in = new Uint8Array(5000); - inOffset = 0; - inCount = new Uint8Array(256); - out = new Packet(new Uint8Array(5000)); - player = null; - constructor(remoteAddress = '0', state = -1) { - this.remoteAddress = remoteAddress; - this.state = state; - } - send(data) { - this.totalBytesWritten += data.length; - self.postMessage(data); - } - close() { - setTimeout(() => { - self.close(); - }, 100); - } - terminate() { - self.close(); - } - reset() { - this.inOffset = 0; - this.inCount.fill(0); - } - writeImmediate(data) { - this.send(data); - } - flush() { - const out = this.out; - if (out.pos === 0) { - return; - } - this.send(out.data.subarray(0, out.pos)); - out.pos = 0; - } -} - -// src/lostcity/server/NullClientSocket.ts -class NullClientSocket extends ClientSocket { - constructor() { - super(null, ''); - } - isTCP() { - return this.type === ClientSocket.TCP; - } - isWebSocket() { - return this.type === ClientSocket.WEBSOCKET; - } - send(data) { - if (!this.socket) { - return; - } - } - close() { - if (!this.socket) { - return; - } - } - terminate() { - if (!this.socket) { - return; - } - } - reset() { - this.inOffset = 0; - this.inCount.fill(0); - } -} - -// src/lostcity/util/TryParse.ts -function tryParseInt(value, defaultValue) { - if (typeof value === 'number') { - return value; - } - if (typeof value !== 'string' && typeof value !== 'number') { - return defaultValue; - } - const intValue = parseInt(value); - if (!isNaN(intValue)) { - return intValue; - } - return defaultValue; -} - -// src/lostcity/network/225/incoming/handler/ClientCheatHandler.ts -class ClientCheatHandler extends MessageHandler { - handle(message, player) { - if (message.input.length > 80) { - return false; - } - const {input: cheat} = message; - const args = cheat.toLowerCase().split(' '); - const cmd = args.shift(); - if (cmd === undefined || cmd.length <= 0) { - return false; - } - player.playerLog('Cheat ran', cheat); - if (cmd === 'advancestat') { - if (args.length < 1) { - return false; - } - const stat = Player2.SKILLS.indexOf(args[0]); - const level = Math.min(99, Math.max(1, tryParseInt(args[1], 1))); - if (stat === -1) { - return false; - } - player.setLevel(stat, player.baseLevels[stat] + level); - } else if (cmd === 'getcoord') { - player.messageGame(Position.formatString(player.level, player.x, player.z, '_')); - } else if (cmd === 'getvar') { - if (args.length < 1) { - return false; - } - const varp = VarPlayerType.getId(args[0]); - if (varp === -1) { - return false; - } - const value = player.getVar(varp); - player.messageGame('get ' + args[0] + ': ' + value); - } else if (cmd === 'give') { - if (args.length < 1) { - return false; - } - const obj = ObjType.getId(args[0]); - const count = Math.max(1, Math.min(tryParseInt(args[1], 1), 2147483647)); - if (obj === -1) { - return false; - } - player.invAdd(InvType.INV, obj, count, false); - } else if (cmd === 'givecrap') { - } else if (cmd === 'givemany') { - } else if (cmd === 'setstat') { - if (args.length < 2) { - return false; - } - const stat = Player2.SKILLS.indexOf(args[0]); - if (stat === -1) { - return false; - } - player.setLevel(stat, parseInt(args[1])); - } else if (cmd === 'setvar') { - if (args.length < 2) { - return false; - } - const varp = VarPlayerType.getId(args[0]); - const value = Math.max(-2147483648, Math.min(tryParseInt(args[1], 0), 2147483647)); - if (varp === -1) { - return false; - } - player.setVar(varp, value); - player.messageGame('set ' + args[0] + ': to ' + value); - } else if (cmd === 'tele') { - if (args.length < 1) { - return false; - } - if (args[0] === 'up') { - player.teleJump(player.x, player.z, player.level + 1); - player.messageGame('::tele ' + Position.formatString(player.level, player.x, player.z, ',')); - } else if (args[0] === 'down') { - player.teleJump(player.x, player.z, player.level - 1); - player.messageGame('::tele ' + Position.formatString(player.level, player.x, player.z, ',')); - } else if (args[0].indexOf(',') === -1) { - player.teleJump(tryParseInt(args[0], 3200), tryParseInt(args[1], 3200), tryParseInt(args[2], player.level)); - } else { - const coord = args[0].split(','); - if (coord.length !== 5) { - return false; - } - const level = tryParseInt(coord[0], 0); - const mx = tryParseInt(coord[1], 50); - const mz = tryParseInt(coord[2], 50); - const lx = tryParseInt(coord[3], 0); - const lz = tryParseInt(coord[4], 0); - if (level < 0 || level > 3 || mx < 0 || mx > 255 || mz < 0 || mz > 255 || lx < 0 || lx > 63 || lz < 0 || lz > 63) { - return false; - } - player.teleJump((mx << 6) + lx, (mz << 6) + lz, level); - } - } else if (cmd === 'reload' && Environment_default.LOCAL_DEV) { - World_default.reload(); - const count = ScriptProvider.load('data/pack'); - player.messageGame(`Reloaded ${count} scripts.`); - } else if (cmd === 'rebuild' && Environment_default.LOCAL_DEV) { - World_default.devThread.postMessage({ - type: 'pack' - }); - } else if (cmd === 'setxp') { - if (args.length < 2) { - player.messageGame('Usage: ::setxp '); - return false; - } - const stat = Player2.SKILLS.indexOf(args[0]); - if (stat === -1) { - player.messageGame(`Unknown stat ${args[0]}`); - return false; - } - const exp = parseInt(args[1]) * 10; - player.stats[stat] = exp; - } else if (cmd === 'minlevel') { - for (let i = 0; i < Player2.SKILLS.length; i++) { - if (i === PlayerStat_default.HITPOINTS) { - player.setLevel(i, 10); - } else { - player.setLevel(i, 1); - } - } - } else if (cmd === 'serverdrop') { - player.terminate(); - } else if (cmd === 'random') { - player.afkEventReady = true; - } else if (cmd === 'bench' && player.staffModLevel >= 3) { - const start = Date.now(); - for (let index = 0; index < 1e5; index++) { - findPath(player.level, player.x, player.z, player.x, player.z + 10); - } - const end = Date.now(); - console.log(`took = ${end - start} ms`); - } else if (cmd === 'bots' && player.staffModLevel >= 3) { - player.messageGame('Adding bots'); - for (let i = 0; i < 2000; i++) { - const bot = new NetworkPlayer2(`bot${i}`, toBase37(`bot${i}`), new NullClientSocket()); - bot.onLogin(); - World_default.addPlayer(bot); - } - } else if (cmd === 'teleall' && player.staffModLevel >= 3) { - player.messageGame('Teleporting all players'); - for (const player2 of World_default.players) { - player2.closeModal(); - do { - const x = Math.floor(Math.random() * 64) + 3200; - const z2 = Math.floor(Math.random() * 64) + 3200; - player2.teleport(x + Math.floor(Math.random() * 64) - 32, z2 + Math.floor(Math.random() * 64) - 32, 0); - } while (isFlagged(player2.x, player2.z, player2.level, CollisionFlag.WALK_BLOCKED)); - } - } else if (cmd === 'moveall' && player.staffModLevel >= 3) { - player.messageGame('Moving all players'); - console.time('moveall'); - for (const player2 of World_default.players) { - player2.closeModal(); - player2.queueWaypoints(findPath(player2.level, player2.x, player2.z, ((player2.x >>> 6) << 6) + 32, ((player2.z >>> 6) << 6) + 32)); - } - console.timeEnd('moveall'); - } else if (cmd === 'speed' && player.staffModLevel >= 3) { - if (args.length < 1) { - player.messageGame('Usage: ::speed '); - return false; - } - const speed = tryParseInt(args.shift(), 20); - if (speed < 20) { - player.messageGame('::speed input was too low.'); - return false; - } - player.messageGame(`World speed was changed to ${speed}ms`); - World_default.tickRate = speed; - } else if (cmd === 'fly' && player.staffModLevel >= 3) { - if (player.moveStrategy === MoveStrategy_default.FLY) { - player.moveStrategy = MoveStrategy_default.SMART; - } else { - player.moveStrategy = MoveStrategy_default.FLY; - } - player.messageGame(`Fly is on? ${player.moveStrategy === MoveStrategy_default.FLY}`); - } else if (cmd === 'naive' && player.staffModLevel >= 3) { - if (player.moveStrategy === MoveStrategy_default.NAIVE) { - player.moveStrategy = MoveStrategy_default.SMART; - } else { - player.moveStrategy = MoveStrategy_default.NAIVE; - } - player.messageGame(`Naive is on? ${player.moveStrategy === MoveStrategy_default.NAIVE}`); - } - const script = ScriptProvider.getByName(`[debugproc,${cmd}]`); - if (!script) { - return false; - } - const params = new Array(script.info.parameterTypes.length).fill(-1); - for (let i = 0; i < script.info.parameterTypes.length; i++) { - const type = script.info.parameterTypes[i]; - try { - switch (type) { - case ScriptVarType.STRING: { - const value = args.shift(); - params[i] = value ?? ''; - break; - } - case ScriptVarType.INT: { - const value = args.shift(); - params[i] = parseInt(value ?? '0', 10) | 0; - break; - } - case ScriptVarType.OBJ: - case ScriptVarType.NAMEDOBJ: { - const name = args.shift(); - params[i] = ObjType.getId(name ?? ''); - break; - } - case ScriptVarType.NPC: { - const name = args.shift(); - params[i] = NpcType.getId(name ?? ''); - break; - } - case ScriptVarType.LOC: { - const name = args.shift(); - params[i] = LocType.getId(name ?? ''); - break; - } - case ScriptVarType.SEQ: { - const name = args.shift(); - params[i] = SeqType.getId(name ?? ''); - break; - } - case ScriptVarType.STAT: { - const name = args.shift(); - params[i] = Player2.SKILLS.indexOf(name ?? ''); - break; - } - case ScriptVarType.INV: { - const name = args.shift(); - params[i] = InvType.getId(name ?? ''); - break; - } - case ScriptVarType.COORD: { - const args2 = cheat.split('_'); - const level = parseInt(args2[0].slice(6)); - const mx = parseInt(args2[1]); - const mz = parseInt(args2[2]); - const lx = parseInt(args2[3]); - const lz = parseInt(args2[4]); - params[i] = Position.packCoord(level, (mx << 6) + lx, (mz << 6) + lz); - break; - } - case ScriptVarType.INTERFACE: { - const name = args.shift(); - params[i] = Component.getId(name ?? ''); - break; - } - case ScriptVarType.SPOTANIM: { - const name = args.shift(); - params[i] = SpotanimType.getId(name ?? ''); - break; - } - case ScriptVarType.IDKIT: { - const name = args.shift(); - params[i] = IdkType.getId(name ?? ''); - break; - } - } - } catch (err) { - return false; - } - } - player.executeScript(ScriptRunner2.init(script, player, null, params), false); - return true; - } -} - -// src/lostcity/network/225/incoming/handler/CloseModalHandler.ts -class CloseModalHandler extends MessageHandler { - handle(_message, player) { - player.closeModal(); - return true; - } -} - -// src/lostcity/network/225/incoming/handler/IdleTimerHandler.ts -class IdleTimerHandler extends MessageHandler { - handle(_message, player) { - if (!Environment_default.LOCAL_DEV) { - player.logout(); - player.logoutRequested = true; - } - return true; - } -} - -// src/lostcity/network/225/incoming/handler/IfButtonHandler.ts -class IfButtonHandler extends MessageHandler { - handle(message, player) { - const {component: comId} = message; - const com = Component.get(comId); - if (typeof com === 'undefined' || !player.isComponentVisible(com)) { - return false; - } - player.lastCom = comId; - if (player.resumeButtons.indexOf(player.lastCom) !== -1) { - if (player.activeScript) { - player.executeScript(player.activeScript, true); - } - } else { - const root = Component.get(com.rootLayer); - const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.IF_BUTTON, comId, -1); - if (script) { - player.executeScript(ScriptRunner2.init(script, player), root.overlay == false); - } else { - if (Environment_default.LOCAL_DEV) { - player.messageGame(`No trigger for [if_button,${com.comName}]`); - } - } - } - return true; - } -} - -// src/lostcity/network/225/incoming/handler/IfPlayerDesignHandler.ts -class IfPlayerDesignHandler extends MessageHandler { - handle(message, player) { - const {gender, idkit, color} = message; - if (!player.allowDesign) { - return false; - } - if (gender > 1) { - return false; - } - let pass = true; - for (let i = 0; i < 7; i++) { - let type = i; - if (gender === 1) { - type += 7; - } - if (type == 8 && idkit[i] === -1) { - continue; - } - const idk = IdkType.get(idkit[i]); - if (!idk || idk.disable || idk.type != type) { - pass = false; - break; - } - } - if (!pass) { - return false; - } - for (let i = 0; i < 5; i++) { - if (color[i] >= Player2.DESIGN_BODY_COLORS[i].length) { - pass = false; - break; - } - } - if (!pass) { - return false; - } - player.gender = gender; - player.body = idkit; - player.colors = color; - player.generateAppearance(InvType.WORN); - return true; - } -} - -// src/lostcity/network/225/incoming/handler/InvButtonDHandler.ts -class InvButtonDHandler extends MessageHandler { - handle(message, player) { - const {component: comId, slot, targetSlot} = message; - const com = Component.get(comId); - if (typeof com === 'undefined' || !player.isComponentVisible(com)) { - return false; - } - const listener = player.invListeners.find(l => l.com === comId); - if (!listener) { - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.get(slot) || !inv.validSlot(targetSlot)) { - return false; - } - if (player.delayed()) { - player.write(new UpdateInvPartial(comId, inv, slot, targetSlot)); - return false; - } - player.lastSlot = slot; - player.lastTargetSlot = targetSlot; - const dragTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.INV_BUTTOND, comId); - if (dragTrigger) { - const root = Component.get(com.rootLayer); - player.executeScript(ScriptRunner2.init(dragTrigger, player), root.overlay == false); - } else { - if (Environment_default.LOCAL_DEV) { - player.messageGame(`No trigger for [inv_buttond,${com.comName}]`); - } - } - return true; - } -} - -// src/lostcity/network/225/incoming/handler/MessagePrivateHandler.ts -class MessagePrivateHandler extends MessageHandler { - handle(message, player) { - return true; - } -} - -// src/lostcity/network/225/incoming/handler/MessagePublicHandler.ts -class MessagePublicHandler extends MessageHandler { - handle(message, player) { - const {color, effect, input} = message; - if (color < 0 || color > 11 || effect < 0 || effect > 2 || input.length > 100) { - return false; - } - player.messageColor = color; - player.messageEffect = effect; - player.messageType = 0; - const out = Packet.alloc(0); - WordPack.pack(out, WordEnc2.filter(input)); - player.message = new Uint8Array(out.pos); - out.pos = 0; - out.gdata(player.message, 0, player.message.length); - out.release(); - player.mask |= Player2.CHAT; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpHeldHandler.ts -class OpHeldHandler extends MessageHandler { - handle(message, player) { - const {obj: item, slot, component: comId} = message; - const com = Component.get(comId); - if (typeof com === 'undefined' || !player.isComponentVisible(com)) { - return false; - } - const type = ObjType.get(item); - if (message.op !== 5 && ((type.iop && !type.iop[message.op - 1]) || !type.iop)) { - return false; - } - const listener = player.invListeners.find(l => l.com === comId); - if (!listener) { - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - return false; - } - if (player.delayed()) { - return false; - } - player.lastItem = item; - player.lastSlot = slot; - player.clearInteraction(); - player.closeModal(); - let trigger; - if (message.op === 1) { - trigger = ServerTriggerType_default.OPHELD1; - } else if (message.op === 2) { - trigger = ServerTriggerType_default.OPHELD2; - } else if (message.op === 3) { - trigger = ServerTriggerType_default.OPHELD3; - } else if (message.op === 4) { - trigger = ServerTriggerType_default.OPHELD4; - } else { - trigger = ServerTriggerType_default.OPHELD5; - } - const script = ScriptProvider.getByTrigger(trigger, type.id, type.category); - if (script) { - player.executeScript(ScriptRunner2.init(script, player), true); - } else { - if (Environment_default.LOCAL_DEV) { - player.messageGame(`No trigger for [${ServerTriggerType_default.toString(trigger)},${type.debugname}]`); - } - } - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpHeldTHandler.ts -class OpHeldTHandler extends MessageHandler { - handle(message, player) { - const {obj: item, slot, component: comId, spellComponent: spellComId} = message; - const com = Component.get(comId); - if (typeof com === 'undefined' || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const spellCom = Component.get(comId); - if (typeof spellCom === 'undefined' || !player.isComponentVisible(spellCom)) { - player.unsetMapFlag(); - return false; - } - const listener = player.invListeners.find(l => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - player.lastItem = item; - player.lastSlot = slot; - player.clearInteraction(); - player.closeModal(); - const script = ScriptProvider.getByTrigger(ServerTriggerType_default.OPHELDT, spellComId, -1); - if (script) { - player.executeScript(ScriptRunner2.init(script, player), true); - } else { - if (Environment_default.LOCAL_DEV) { - player.messageGame(`No trigger for [opheldt,${spellCom.comName}]`); - } - player.messageGame('Nothing interesting happens.'); - } - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpHeldUHandler.ts -class OpHeldUHandler extends MessageHandler { - handle(message, player) { - const {obj: item, slot, component: comId, useObj: useItem, useSlot, useComponent: useComId} = message; - const com = Component.get(comId); - if (typeof com === 'undefined' || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const useCom = Component.get(comId); - if (typeof useCom === 'undefined' || !player.isComponentVisible(useCom)) { - player.unsetMapFlag(); - return false; - } - { - const listener = player.invListeners.find(l => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - } - { - const listener = player.invListeners.find(l => l.com === useComId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(useSlot) || !inv.hasAt(useSlot, useItem)) { - player.unsetMapFlag(); - return false; - } - } - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - player.lastItem = item; - player.lastSlot = slot; - player.lastUseItem = useItem; - player.lastUseSlot = useSlot; - const objType = ObjType.get(player.lastItem); - const useObjType = ObjType.get(player.lastUseItem); - if ((objType.members || useObjType.members) && !World_default.members) { - player.messageGame("To use this item please login to a members' server."); - player.unsetMapFlag(); - return false; - } - let script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, objType.id, -1); - if (!script) { - script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, useObjType.id, -1); - [player.lastItem, player.lastUseItem] = [player.lastUseItem, player.lastItem]; - [player.lastSlot, player.lastUseSlot] = [player.lastUseSlot, player.lastSlot]; - } - const objCategory = objType.category !== -1 ? CategoryType.get(objType.category) : null; - if (!script && objCategory) { - script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, -1, objCategory.id); - } - const useObjCategory = useObjType.category !== -1 ? CategoryType.get(useObjType.category) : null; - if (!script && useObjCategory) { - script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, -1, useObjCategory.id); - [player.lastItem, player.lastUseItem] = [player.lastUseItem, player.lastItem]; - [player.lastSlot, player.lastUseSlot] = [player.lastUseSlot, player.lastSlot]; - } - player.clearInteraction(); - player.closeModal(); - if (script) { - player.executeScript(ScriptRunner2.init(script, player), true); - } else { - if (Environment_default.LOCAL_DEV) { - player.messageGame(`No trigger for [opheldu,${objType.debugname}]`); - } - player.messageGame('Nothing interesting happens.'); - } - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpLocHandler.ts -class OpLocHandler extends MessageHandler { - handle(message, player) { - const {x, z: z2, loc: locId} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { - return false; - } - const loc = World_default.getLoc(x, z2, player.level, locId); - if (!loc) { - player.unsetMapFlag(); - return false; - } - const locType = LocType.get(loc.type); - if (!locType.op || !locType.op[message.op - 1]) { - player.unsetMapFlag(); - return false; - } - let mode; - if (message.op === 1) { - mode = ServerTriggerType_default.APLOC1; - } else if (message.op === 2) { - mode = ServerTriggerType_default.APLOC2; - } else if (message.op === 3) { - mode = ServerTriggerType_default.APLOC3; - } else if (message.op === 4) { - mode = ServerTriggerType_default.APLOC4; - } else { - mode = ServerTriggerType_default.APLOC5; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, loc, mode); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpLocTHandler.ts -class OpLocTHandler extends MessageHandler { - handle(message, player) { - const {x, z: z2, loc: locId, spellComponent: spellComId} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const spellCom = Component.get(spellComId); - if (typeof spellCom === 'undefined' || !player.isComponentVisible(spellCom)) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { - player.unsetMapFlag(); - return false; - } - const loc = World_default.getLoc(x, z2, player.level, locId); - if (!loc) { - player.unsetMapFlag(); - return false; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, loc, ServerTriggerType_default.APLOCT, {type: loc.type, com: spellComId}); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpLocUHandler.ts -class OpLocUHandler extends MessageHandler { - handle(message, player) { - const {x, z: z2, loc: locId, useObj: item, useSlot: slot, useComponent: comId} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const com = Component.get(comId); - if (typeof com === 'undefined' || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { - player.unsetMapFlag(); - return false; - } - const listener = player.invListeners.find(l => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - const loc = World_default.getLoc(x, z2, player.level, locId); - if (!loc) { - player.unsetMapFlag(); - return false; - } - if (ObjType.get(item).members && !World_default.members) { - player.messageGame("To use this item please login to a members' server."); - player.unsetMapFlag(); - return false; - } - player.lastUseItem = item; - player.lastUseSlot = slot; - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, loc, ServerTriggerType_default.APLOCU); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpNpcHandler.ts -class OpNpcHandler extends MessageHandler { - handle(message, player) { - const {nid} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const npc = World_default.getNpc(nid); - if (!npc || npc.delayed()) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.npcs.has(npc.nid)) { - player.unsetMapFlag(); - return false; - } - const npcType = NpcType.get(npc.type); - if (!npcType.op || !npcType.op[message.op - 1]) { - player.unsetMapFlag(); - return false; - } - let mode; - if (message.op === 1) { - mode = ServerTriggerType_default.APNPC1; - } else if (message.op === 2) { - mode = ServerTriggerType_default.APNPC2; - } else if (message.op === 3) { - mode = ServerTriggerType_default.APNPC3; - } else if (message.op === 4) { - mode = ServerTriggerType_default.APNPC4; - } else { - mode = ServerTriggerType_default.APNPC5; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, npc, mode, {type: npc.type, com: -1}); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpNpcTHandler.ts -class OpNpcTHandler extends MessageHandler { - handle(message, player) { - const {nid, spellComponent: spellComId} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const spellCom = Component.get(spellComId); - if (typeof spellCom === 'undefined' || !player.isComponentVisible(spellCom)) { - player.unsetMapFlag(); - return false; - } - const npc = World_default.getNpc(nid); - if (!npc || npc.delayed()) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.npcs.has(npc.nid)) { - player.unsetMapFlag(); - return false; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, npc, ServerTriggerType_default.APNPCT, {type: npc.type, com: spellComId}); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpNpcUHandler.ts -class OpNpcUHandler extends MessageHandler { - handle(message, player) { - const {nid, useObj: item, useSlot: slot, useComponent: comId} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const com = Component.get(comId); - if (typeof com === 'undefined' || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const listener = player.invListeners.find(l => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - const npc = World_default.getNpc(nid); - if (!npc || npc.delayed()) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.npcs.has(npc.nid)) { - player.unsetMapFlag(); - return false; - } - if (ObjType.get(item).members && !World_default.members) { - player.messageGame("To use this item please login to a members' server."); - player.unsetMapFlag(); - return false; - } - player.lastUseItem = item; - player.lastUseSlot = slot; - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, npc, ServerTriggerType_default.APNPCU, {type: npc.type, com: -1}); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpObjHandler.ts -class OpObjHandler extends MessageHandler { - handle(message, player) { - const {x, z: z2, obj: objId} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { - player.unsetMapFlag(); - return false; - } - const obj = World_default.getObj(x, z2, player.level, objId, player.pid); - if (!obj) { - player.unsetMapFlag(); - return false; - } - const objType = ObjType.get(obj.type); - if ((message.op === 1 && ((objType.op && !objType.op[0]) || !objType.op)) || (message.op === 4 && ((objType.op && !objType.op[3]) || !objType.op))) { - player.unsetMapFlag(); - return false; - } - let mode; - if (message.op === 1) { - mode = ServerTriggerType_default.APOBJ1; - } else if (message.op === 2) { - mode = ServerTriggerType_default.APOBJ2; - } else if (message.op === 3) { - mode = ServerTriggerType_default.APOBJ3; - } else if (message.op === 4) { - mode = ServerTriggerType_default.APOBJ4; - } else { - mode = ServerTriggerType_default.APOBJ5; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, obj, mode); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpObjTHandler.ts -class OpObjTHandler extends MessageHandler { - handle(message, player) { - const {x, z: z2, obj: objId, spellComponent: spellComId} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const spellCom = Component.get(spellComId); - if (typeof spellCom === 'undefined' || !player.isComponentVisible(spellCom)) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { - player.unsetMapFlag(); - return false; - } - const obj = World_default.getObj(x, z2, player.level, objId, player.pid); - if (!obj) { - player.unsetMapFlag(); - return false; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, obj, ServerTriggerType_default.APOBJT, {type: obj.type, com: spellComId}); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpObjUHandler.ts -class OpObjUHandler extends MessageHandler { - handle(message, player) { - const {x, z: z2, obj: objId, useObj: item, useSlot: slot, useComponent: comId} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const com = Component.get(comId); - if (typeof com === 'undefined' || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { - player.unsetMapFlag(); - return false; - } - const listener = player.invListeners.find(l => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - const obj = World_default.getObj(x, z2, player.level, objId, player.pid); - if (!obj) { - player.unsetMapFlag(); - return false; - } - if (ObjType.get(item).members && !World_default.members) { - player.messageGame("To use this item please login to a members' server."); - player.unsetMapFlag(); - return false; - } - player.lastUseItem = item; - player.lastUseSlot = slot; - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, obj, ServerTriggerType_default.APOBJU); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpPlayerHandler.ts -class OpPlayerHandler extends MessageHandler { - handle(message, player) { - const {pid} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const other = World_default.getPlayer(pid); - if (!other) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.players.has(other.uid)) { - player.unsetMapFlag(); - return false; - } - let mode; - if (message.op === 1) { - mode = ServerTriggerType_default.APPLAYER1; - } else if (message.op === 2) { - mode = ServerTriggerType_default.APPLAYER2; - } else if (message.op === 3) { - mode = ServerTriggerType_default.APPLAYER3; - } else { - mode = ServerTriggerType_default.APPLAYER4; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, other, mode); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpPlayerTHandler.ts -class OpPlayerTHandler extends MessageHandler { - handle(message, player) { - const {pid, spellComponent: spellComId} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const spellCom = Component.get(spellComId); - if (typeof spellCom === 'undefined' || !player.isComponentVisible(spellCom)) { - player.unsetMapFlag(); - return false; - } - const other = World_default.getPlayer(pid); - if (!other) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.players.has(other.uid)) { - player.unsetMapFlag(); - return false; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, other, ServerTriggerType_default.APPLAYERT, {type: -1, com: spellComId}); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/OpPlayerUHandler.ts -class OpPlayerUHandler extends MessageHandler { - handle(message, player) { - const {pid, useObj: item, useSlot: slot, useComponent: comId} = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const com = Component.get(comId); - if (typeof com === 'undefined' || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const listener = player.invListeners.find(l => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - const other = World_default.getPlayer(pid); - if (!other) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.players.has(other.uid)) { - player.unsetMapFlag(); - return false; - } - if (ObjType.get(item).members && !World_default.members) { - player.messageGame("To use this item please login to a members' server."); - player.unsetMapFlag(); - return false; - } - player.lastUseSlot = slot; - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, other, ServerTriggerType_default.APPLAYERU, {type: item, com: -1}); - player.opcalled = true; - return true; - } -} - -// src/lostcity/network/225/incoming/handler/RebuildGetMapsHandler.ts -class RebuildGetMapsHandler extends MessageHandler { - handle(message, player) { - const {maps: requested} = message; - for (let i = 0; i < requested.length; i++) { - const {type, x, z: z2} = requested[i]; - const CHUNK_SIZE = 1000 - 1 - 2 - 1 - 1 - 2 - 2; - if (type == 0) { - const land = PRELOADED.get(`m${x}_${z2}`); - if (!land) { - continue; - } - for (let off = 0; off < land.length; off += CHUNK_SIZE) { - player.write(new DataLand(x, z2, off, land.length, land.subarray(off, off + CHUNK_SIZE))); - } - player.write(new DataLandDone(x, z2)); - } else if (type == 1) { - const loc = PRELOADED.get(`l${x}_${z2}`); - if (!loc) { - continue; - } - for (let off = 0; off < loc.length; off += CHUNK_SIZE) { - player.write(new DataLoc(x, z2, off, loc.length, loc.subarray(off, off + CHUNK_SIZE))); - } - player.write(new DataLocDone(x, z2)); - } - } - return true; - } -} - -// src/lostcity/network/225/incoming/handler/ResumePauseButtonHandler.ts -class ResumePauseButtonHandler extends MessageHandler { - handle(_message, player) { - if (!player.activeScript || player.activeScript.execution !== ScriptState.PAUSEBUTTON) { - return false; - } - player.executeScript(player.activeScript, true); - return true; - } -} - -// src/lostcity/network/225/incoming/handler/ResumePCountDialogHandler.ts -class ResumePCountDialogHandler extends MessageHandler { - handle(message, player) { - const {input} = message; - if (!player.activeScript || player.activeScript.execution !== ScriptState.COUNTDIALOG) { - return false; - } - player.activeScript.lastInt = input; - player.executeScript(player.activeScript, true); - return true; - } -} - -// src/lostcity/network/225/incoming/handler/TutorialClickSideHandler.ts -class TutorialClickSideHandler extends MessageHandler { - handle(message, player) { - const {tab} = message; - if (tab < 0 || tab > 13) { - return false; - } - const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.TUTORIAL_CLICKSIDE, -1, -1); - if (script) { - player.executeScript(ScriptRunner2.init(script, player), true); - } - return true; - } -} - -// src/lostcity/network/incoming/model/MoveClick.ts -class MoveClick extends IncomingMessage { - path; - ctrlHeld; - opClick; - category = ClientProtCategory.USER_EVENT; - constructor(path, ctrlHeld, opClick) { - super(); - this.path = path; - this.ctrlHeld = ctrlHeld; - this.opClick = opClick; - } -} - -// src/lostcity/network/225/incoming/codec/MoveClickDecoder.ts -class MoveClickDecoder extends MessageDecoder { - prot; - constructor(prot) { - super(); - this.prot = prot; - } - decode(buf) { - const ctrlHeld = buf.g1(); - const startX = buf.g2(); - const startZ = buf.g2(); - const offset = this.prot === ClientProt.MOVE_MINIMAPCLICK ? 14 : 0; - const waypoints = (buf.available - offset) >> 1; - const path = [{x: startX, z: startZ}]; - for (let index = 1; index <= waypoints && index < 25; index++) { - path.push({ - x: startX + buf.g1b(), - z: startZ + buf.g1b() - }); - } - return new MoveClick(path, ctrlHeld, this.prot === ClientProt.MOVE_OPCLICK); - } -} - -// src/lostcity/network/225/incoming/handler/MoveClickHandler.ts -class MoveClickHandler extends MessageHandler { - handle(message, player) { - const start = message.path[0]; - if (player.delayed() || message.ctrlHeld < 0 || message.ctrlHeld > 1 || Position.distanceToSW(player, {x: start.x, z: start.z}) > 104) { - player.unsetMapFlag(); - player.userPath = []; - return false; - } - if (Environment_default.CLIENT_PATHFINDER) { - player.userPath = []; - for (let i = 0; i < message.path.length; i++) { - player.userPath[i] = Position.packCoord(player.level, message.path[i].x, message.path[i].z); - } - } else { - const dest = message.path[message.path.length - 1]; - player.userPath = [Position.packCoord(player.level, dest.x, dest.z)]; - } - player.interactWalkTrigger = false; - if (!message.opClick) { - player.clearInteraction(); - player.closeModal(); - } - if (player.runenergy < 100) { - player.setVar(VarPlayerType.TEMP_RUN, 0); - } else { - player.setVar(VarPlayerType.TEMP_RUN, message.ctrlHeld); - } - return true; - } -} - -// src/lostcity/network/225/incoming/prot/ClientProtRepository.ts -class ClientProtRepository { - decoders = new Map(); - handlers = new Map(); - bind(decoder, handler) { - if (this.decoders.has(decoder.prot.id)) { - throw new Error(`[ClientProtRepository] Already defines a ${decoder.prot.id}.`); - } - this.decoders.set(decoder.prot.id, decoder); - if (handler) { - this.handlers.set(decoder.prot.id, handler); - } - } - constructor() { - this.bind(new ClientCheatDecoder(), new ClientCheatHandler()); - this.bind(new CloseModalDecoder(), new CloseModalHandler()); - this.bind(new IdleTimerDecoder(), new IdleTimerHandler()); - this.bind(new IfButtonDecoder(), new IfButtonHandler()); - this.bind(new IfPlayerDesignDecoder(), new IfPlayerDesignHandler()); - this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON1, 1), new InvButtonHandler()); - this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON2, 2), new InvButtonHandler()); - this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON3, 3), new InvButtonHandler()); - this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON4, 4), new InvButtonHandler()); - this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON5, 5), new InvButtonHandler()); - this.bind(new InvButtonDDecoder(), new InvButtonDHandler()); - this.bind(new MessagePrivateDecoder(), new MessagePrivateHandler()); - this.bind(new MessagePublicDecoder(), new MessagePublicHandler()); - this.bind(new MoveClickDecoder(ClientProt.MOVE_GAMECLICK), new MoveClickHandler()); - this.bind(new MoveClickDecoder(ClientProt.MOVE_OPCLICK), new MoveClickHandler()); - this.bind(new MoveClickDecoder(ClientProt.MOVE_MINIMAPCLICK), new MoveClickHandler()); - this.bind(new OpHeldDecoder(ClientProt.OPHELD1, 1), new OpHeldHandler()); - this.bind(new OpHeldDecoder(ClientProt.OPHELD2, 2), new OpHeldHandler()); - this.bind(new OpHeldDecoder(ClientProt.OPHELD3, 3), new OpHeldHandler()); - this.bind(new OpHeldDecoder(ClientProt.OPHELD4, 4), new OpHeldHandler()); - this.bind(new OpHeldDecoder(ClientProt.OPHELD5, 5), new OpHeldHandler()); - this.bind(new OpHeldTDecoder(), new OpHeldTHandler()); - this.bind(new OpHeldUDecoder(), new OpHeldUHandler()); - this.bind(new OpLocDecoder(ClientProt.OPLOC1, 1), new OpLocHandler()); - this.bind(new OpLocDecoder(ClientProt.OPLOC2, 2), new OpLocHandler()); - this.bind(new OpLocDecoder(ClientProt.OPLOC3, 3), new OpLocHandler()); - this.bind(new OpLocDecoder(ClientProt.OPLOC4, 4), new OpLocHandler()); - this.bind(new OpLocDecoder(ClientProt.OPLOC5, 5), new OpLocHandler()); - this.bind(new OpLocTDecoder(), new OpLocTHandler()); - this.bind(new OpLocUDecoder(), new OpLocUHandler()); - this.bind(new OpNpcDecoder(ClientProt.OPNPC1, 1), new OpNpcHandler()); - this.bind(new OpNpcDecoder(ClientProt.OPNPC2, 2), new OpNpcHandler()); - this.bind(new OpNpcDecoder(ClientProt.OPNPC3, 3), new OpNpcHandler()); - this.bind(new OpNpcDecoder(ClientProt.OPNPC4, 4), new OpNpcHandler()); - this.bind(new OpNpcDecoder(ClientProt.OPNPC5, 5), new OpNpcHandler()); - this.bind(new OpNpcTDecoder(), new OpNpcTHandler()); - this.bind(new OpNpcUDecoder(), new OpNpcUHandler()); - this.bind(new OpObjDecoder(ClientProt.OPOBJ1, 1), new OpObjHandler()); - this.bind(new OpObjDecoder(ClientProt.OPOBJ2, 2), new OpObjHandler()); - this.bind(new OpObjDecoder(ClientProt.OPOBJ3, 3), new OpObjHandler()); - this.bind(new OpObjDecoder(ClientProt.OPOBJ4, 4), new OpObjHandler()); - this.bind(new OpObjDecoder(ClientProt.OPOBJ5, 5), new OpObjHandler()); - this.bind(new OpObjTDecoder(), new OpObjTHandler()); - this.bind(new OpObjUDecoder(), new OpObjUHandler()); - this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER1, 1), new OpPlayerHandler()); - this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER2, 2), new OpPlayerHandler()); - this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER3, 3), new OpPlayerHandler()); - this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER4, 4), new OpPlayerHandler()); - this.bind(new OpPlayerTDecoder(), new OpPlayerTHandler()); - this.bind(new OpPlayerUDecoder(), new OpPlayerUHandler()); - this.bind(new RebuildGetMapsDecoder(), new RebuildGetMapsHandler()); - this.bind(new ResumePauseButtonDecoder(), new ResumePauseButtonHandler()); - this.bind(new ResumePCountDialogDecoder(), new ResumePCountDialogHandler()); - this.bind(new TutorialClickSideDecoder(), new TutorialClickSideHandler()); - } - getDecoder(prot) { - return this.decoders.get(prot.id); - } - getHandler(prot) { - return this.handlers.get(prot.id); - } -} -var ClientProtRepository_default = new ClientProtRepository(); - -// src/lostcity/entity/NetworkPlayer.ts -function isNetworkPlayer(player) { - return player.client !== null && player.client !== undefined; -} - -class NetworkPlayer2 extends Player2 { - client = null; - userPath = []; - opcalled = false; - constructor(username, username37, client) { - super(username, username37); - this.client = client; - this.client.player = this; - } - decodeIn() { - if (this.client === null || this.client.inOffset < 1) { - return; - } - let offset = 0; - this.lastResponse = World_default.currentTick; - this.userPath = []; - this.opcalled = false; - World_default.lastCycleBandwidth[0] += this.client.inOffset; - while (this.client.inOffset > offset) { - const packetType = ClientProt.byId[this.client.in[offset++]]; - let length = packetType.length; - if (length == -1) { - length = this.client.in[offset++]; - } else if (length == -2) { - length = (this.client.in[offset++] << 8) | this.client.in[offset++]; - } - const data = new Packet(this.client.in.slice(offset, offset + length)); - offset += length; - const decoder = ClientProtRepository_default.getDecoder(packetType); - if (decoder) { - const message = decoder.decode(data); - const handler = ClientProtRepository_default.getHandler(packetType); - if (handler) { - handler.handle(message, this); - } - } - } - this.client?.reset(); - } - encodeOut() { - if (!this.client) { - return; - } - if (this.modalTop !== this.lastModalTop || this.modalBottom !== this.lastModalBottom || this.modalSidebar !== this.lastModalSidebar || this.refreshModalClose) { - if (this.refreshModalClose) { - this.write(new IfClose()); - } - this.refreshModalClose = false; - this.lastModalTop = this.modalTop; - this.lastModalBottom = this.modalBottom; - this.lastModalSidebar = this.modalSidebar; - } - if (this.refreshModal) { - if ((this.modalState & 1) === 1 && (this.modalState & 4) === 4) { - this.write(new IfOpenMainSideModal(this.modalTop, this.modalSidebar)); - } else if ((this.modalState & 1) === 1) { - this.write(new IfOpenMainModal(this.modalTop)); - } else if ((this.modalState & 2) === 2) { - this.write(new IfOpenChatModal(this.modalBottom)); - } else if ((this.modalState & 4) === 4) { - this.write(new IfOpenSideModal(this.modalSidebar)); - } - this.refreshModal = false; - } - for (let message = this.highPriorityOut.head(); message; message = this.highPriorityOut.next()) { - this.writeInner(message); - message.uncache(); - } - for (let message = this.lowPriorityOut.head(); message; message = this.lowPriorityOut.next()) { - this.writeInner(message); - message.uncache(); - } - this.client.flush(); - } - writeInner(message) { - const client = this.client; - if (!client) { - return; - } - const encoder = ServerProtRepository_default.getEncoder(message); - if (!encoder) { - return; - } - const prot = encoder.prot; - const buf = client.out; - const test = (1 + prot.length === -1 ? 1 : prot.length === -2 ? 2 : 0) + encoder.test(message); - if (buf.pos + test >= buf.length) { - client.flush(); - } - const pos = buf.pos; - buf.p1(prot.id); - if (prot.length === -1) { - buf.pos += 1; - } else if (prot.length === -2) { - buf.pos += 2; - } - const start = buf.pos; - encoder.encode(buf, message); - if (prot.length === -1) { - buf.psize1(buf.pos - start); - } else if (prot.length === -2) { - buf.psize2(buf.pos - start); - } - if (client.encryptor) { - buf.data[pos] = (buf.data[pos] + client.encryptor.nextInt()) & 255; - } - World_default.lastCycleBandwidth[1] += buf.pos - pos; - } - logout() { - this.writeInner(new Logout()); - this.client?.flush(); - } - terminate() { - this.client?.terminate(); - this.client = null; - } - playerLog(message, ...args) {} - updateMap() { - const loadedZones = this.buildArea.loadedZones; - const activeZones = this.buildArea.activeZones; - const reloadLeftX = (Position.zone(this.originX) - 4) << 3; - const reloadRightX = (Position.zone(this.originX) + 5) << 3; - const reloadTopZ = (Position.zone(this.originZ) + 5) << 3; - const reloadBottomZ = (Position.zone(this.originZ) - 4) << 3; - if (this.x < reloadLeftX || this.z < reloadBottomZ || this.x > reloadRightX - 1 || this.z > reloadTopZ - 1 || (this.tele && (Position.zone(this.x) !== Position.zone(this.originX) || Position.zone(this.z) !== Position.zone(this.originZ)))) { - this.write(new RebuildNormal(Position.zone(this.x), Position.zone(this.z))); - this.originX = this.x; - this.originZ = this.z; - loadedZones.clear(); - } - for (let info = this.cameraPackets.head(); info !== null; info = this.cameraPackets.next()) { - const localX = info.camX - Position.zoneOrigin(this.originX); - const localZ = info.camZ - Position.zoneOrigin(this.originZ); - if (info.type === ServerProt.CAM_MOVETO) { - this.write(new CamMoveTo(localX, localZ, info.height, info.rotationSpeed, info.rotationMultiplier)); - } else if (info.type === ServerProt.CAM_LOOKAT) { - this.write(new CamLookAt(localX, localZ, info.height, info.rotationSpeed, info.rotationMultiplier)); - } - info.unlink(); - } - if (this.moveSpeed === MoveSpeed_default.INSTANT && this.jump) { - loadedZones.clear(); - } - activeZones.clear(); - const centerX = Position.zone(this.x); - const centerZ = Position.zone(this.z); - const leftX = Position.zone(this.originX) - 6; - const rightX = Position.zone(this.originX) + 6; - const topZ = Position.zone(this.originZ) + 6; - const bottomZ = Position.zone(this.originZ) - 6; - for (let x = centerX - 3; x <= centerX + 3; x++) { - for (let z2 = centerZ - 3; z2 <= centerZ + 3; z2++) { - if (x < leftX || x > rightX || z2 > topZ || z2 < bottomZ) { - continue; - } - activeZones.add(ZoneMap2.zoneIndex(x << 3, z2 << 3, this.level)); - } - } - } - updatePlayers() { - this.write(new PlayerInfo(this.buildArea, this.level, this.x, this.z, this.originX, this.originZ, this.uid, this.mask, this.tele, this.jump, this.walkDir, this.runDir)); - } - updateNpcs() { - this.write(new NpcInfo(this.buildArea, this.level, this.x, this.z, this.originX, this.originZ)); - } - updateZones() { - const loadedZones = this.buildArea.loadedZones; - const activeZones = this.buildArea.activeZones; - for (const zoneIndex of loadedZones) { - if (!activeZones.has(zoneIndex)) { - loadedZones.delete(zoneIndex); - } - } - for (const zoneIndex of activeZones) { - const zone = World_default.getZoneIndex(zoneIndex); - if (!loadedZones.has(zone.index)) { - zone.writeFullFollows(this); - } else { - zone.writePartialEncloses(this); - zone.writePartialFollows(this); - } - loadedZones.add(zone.index); - } - } - updateStats() { - for (let i = 0; i < this.stats.length; i++) { - if (this.stats[i] !== this.lastStats[i] || this.levels[i] !== this.lastLevels[i]) { - this.write(new UpdateStat(i, this.stats[i], this.levels[i])); - this.lastStats[i] = this.stats[i]; - this.lastLevels[i] = this.levels[i]; - } - } - if (Math.floor(this.runenergy) / 100 !== Math.floor(this.lastRunEnergy) / 100) { - this.write(new UpdateRunEnergy(this.runenergy)); - this.lastRunEnergy = this.runenergy; - } - } - updateInvs() { - let runWeightChanged = false; - let firstSeen = false; - for (let i = 0; i < this.invListeners.length; i++) { - const listener = this.invListeners[i]; - if (!listener) { - continue; - } - if (listener.source === -1) { - const inv = World_default.getInventory(listener.type); - if (!inv) { - continue; - } - if (inv.update || listener.firstSeen) { - this.write(new UpdateInvFull(listener.com, inv)); - listener.firstSeen = false; - } - } else { - const player = World_default.getPlayerByUid(listener.source); - if (!player) { - continue; - } - const inv = player.getInventory(listener.type); - if (!inv) { - continue; - } - if (inv.update || listener.firstSeen) { - this.write(new UpdateInvFull(listener.com, inv)); - if (listener.firstSeen) { - firstSeen = true; - } - listener.firstSeen = false; - const invType = InvType.get(listener.type); - if (invType.runweight) { - runWeightChanged = true; - } - } - } - } - if (runWeightChanged) { - const current = this.runweight; - this.calculateRunWeight(); - runWeightChanged = current !== this.runweight; - } - if (runWeightChanged || firstSeen) { - this.write(new UpdateRunWeight(Math.ceil(this.runweight / 1000))); - } - } -} - -// src/lostcity/entity/CameraInfo.ts -class CameraInfo extends Linkable { - type; - camX; - camZ; - height; - rotationSpeed; - rotationMultiplier; - constructor(type, camX, camZ, height, rotationSpeed, rotationMultiplier) { - super(); - this.type = type; - this.camX = camX; - this.camZ = camZ; - this.height = height; - this.rotationSpeed = rotationSpeed; - this.rotationMultiplier = rotationMultiplier; - } -} - -// src/lostcity/util/ColorConversion.ts -class ColorConversion { - static hsl24to16(hue, saturation, lightness) { - if (lightness > 243) { - saturation >>= 4; - } else if (lightness > 217) { - saturation >>= 3; - } else if (lightness > 192) { - saturation >>= 2; - } else if (lightness > 179) { - saturation >>= 1; - } - return (((hue & 255) >> 2) << 10) + ((saturation >> 5) << 7) + (lightness >> 1); - } - static rgb15to24(rgb) { - const r = (rgb >> 10) & 31; - const g = (rgb >> 5) & 31; - const b2 = rgb & 31; - return ((r << 3) << 16) + ((g << 3) << 8) + (b2 << 3); - } - static rgb15toHsl16(rgb) { - const r = (rgb >> 10) & 31; - const g = (rgb >> 5) & 31; - const b2 = rgb & 31; - const red = r / 31; - const green = g / 31; - const blue = b2 / 31; - return ColorConversion.rgbToHsl(red, green, blue); - } - static rgb24to15(rgb) { - const r = (rgb >> 16) & 255; - const g = (rgb >> 8) & 255; - const b2 = rgb & 255; - return ((r >> 3) << 10) + ((g >> 3) << 5) + (b2 >> 3); - } - static rgb24toHsl16(rgb) { - const r = (rgb >> 16) & 255; - const g = (rgb >> 8) & 255; - const b2 = rgb & 255; - const red = r / 256; - const green = g / 256; - const blue = b2 / 256; - return ColorConversion.rgbToHsl(red, green, blue); - } - static rgbToHsl(red, green, blue) { - let min = red; - if (green < min) { - min = green; - } - if (blue < min) { - min = blue; - } - let max = red; - if (green > max) { - max = green; - } - if (blue > max) { - max = blue; - } - let hNorm = 0; - let sNorm = 0; - const lNorm = (min + max) / 2; - if (min !== max) { - if (lNorm < 0.5) { - sNorm = (max - min) / (max + min); - } else if (lNorm >= 0.5) { - sNorm = (max - min) / (2 - max - min); - } - if (red === max) { - hNorm = (green - blue) / (max - min); - } else if (green === max) { - hNorm = (blue - red) / (max - min) + 2; - } else if (blue === max) { - hNorm = (red - green) / (max - min) + 4; - } - } - hNorm /= 6; - const hue = (hNorm * 256) | 0; - let saturation = (sNorm * 256) | 0; - let lightness = (lNorm * 256) | 0; - if (saturation < 0) { - saturation = 0; - } else if (saturation > 255) { - saturation = 255; - } - if (lightness < 0) { - lightness = 0; - } else if (lightness > 255) { - lightness = 255; - } - return ColorConversion.hsl24to16(hue, saturation, lightness); - } - static RGB15_HSL16 = new Int32Array(32768); - static { - for (let rgb = 0; rgb < 32768; rgb++) { - ColorConversion.RGB15_HSL16[rgb] = ColorConversion.rgb15toHsl16(rgb); - } - } - static reverseHsl(hsl) { - const possible = []; - for (let rgb = 0; rgb < 32768; rgb++) { - if (ColorConversion.RGB15_HSL16[rgb] === hsl) { - possible.push(rgb); - } - } - return possible; - } -} - -// src/lostcity/engine/script/handlers/PlayerOps.ts -var popScriptArgs = function (state) { - const types = state.popString(); - const count = types.length; - const args = []; - for (let i = count - 1; i >= 0; i--) { - const type = types.charAt(i); - if (type === 's') { - args[i] = state.popString(); - } else { - args[i] = state.popInt(); - } - } - return args; -}; -var PlayerOps = { - [ScriptOpcode_default.FINDUID]: state => { - const uid = state.popInt(); - const player = World_default.getPlayerByUid(uid); - if (!player) { - state.pushInt(0); - return; - } - state.activePlayer = player; - state.pointerAdd(ActivePlayer[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.P_FINDUID]: state => { - const uid = state.popInt() >>> 0; - const player = World_default.getPlayerByUid(uid); - if (state.pointerGet(ProtectedActivePlayer[state.intOperand]) && state.activePlayer.uid === uid) { - state.pushInt(1); - return; - } - if (!player || !player.canAccess()) { - state.pushInt(0); - return; - } - state.activePlayer = player; - state.pointerAdd(ActivePlayer[state.intOperand]); - state.pointerAdd(ProtectedActivePlayer[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.STRONGQUEUE]: checkedHandler(ActivePlayer, state => { - const args = popScriptArgs(state); - const delay = check(state.popInt(), NumberNotNull); - const scriptId = state.popInt(); - const script = ScriptProvider.get(scriptId); - if (!script) { - throw new Error(`Unable to find queue script: ${scriptId}`); - } - state.activePlayer.enqueueScript(script, 3 /* STRONG */, delay, args); - }), - [ScriptOpcode_default.WEAKQUEUE]: checkedHandler(ActivePlayer, state => { - const args = popScriptArgs(state); - const delay = check(state.popInt(), NumberNotNull); - const scriptId = state.popInt(); - const script = ScriptProvider.get(scriptId); - if (!script) { - throw new Error(`Unable to find queue script: ${scriptId}`); - } - state.activePlayer.enqueueScript(script, 2 /* WEAK */, delay, args); - }), - [ScriptOpcode_default.QUEUE]: checkedHandler(ActivePlayer, state => { - const args = popScriptArgs(state); - const delay = check(state.popInt(), NumberNotNull); - const scriptId = state.popInt(); - const script = ScriptProvider.get(scriptId); - if (!script) { - throw new Error(`Unable to find queue script: ${scriptId}`); - } - state.activePlayer.enqueueScript(script, 0 /* NORMAL */, delay, args); - }), - [ScriptOpcode_default.ANIM]: checkedHandler(ActivePlayer, state => { - const delay = state.popInt(); - const seq = state.popInt(); - state.activePlayer.playAnimation(seq, delay); - }), - [ScriptOpcode_default.BUFFER_FULL]: checkedHandler(ActivePlayer, state => { - throw new Error('unimplemented'); - }), - [ScriptOpcode_default.BUILDAPPEARANCE]: checkedHandler(ActivePlayer, state => { - state.activePlayer.generateAppearance(check(state.popInt(), InvTypeValid).id); - }), - [ScriptOpcode_default.CAM_LOOKAT]: checkedHandler(ActivePlayer, state => { - const [coord, height, rotationSpeed, rotationMultiplier] = state.popInts(4); - const pos = check(coord, CoordValid); - state.activePlayer.cameraPackets.addTail(new CameraInfo(ServerProt.CAM_LOOKAT, pos.x, pos.z, height, rotationSpeed, rotationMultiplier)); - }), - [ScriptOpcode_default.CAM_MOVETO]: checkedHandler(ActivePlayer, state => { - const [coord, height, rotationSpeed, rotationMultiplier] = state.popInts(4); - const pos = check(coord, CoordValid); - state.activePlayer.cameraPackets.addTail(new CameraInfo(ServerProt.CAM_MOVETO, pos.x, pos.z, height, rotationSpeed, rotationMultiplier)); - }), - [ScriptOpcode_default.CAM_SHAKE]: checkedHandler(ActivePlayer, state => { - const [type, jitter, amplitude, frequency] = state.popInts(4); - state.activePlayer.write(new CamShake(type, jitter, amplitude, frequency)); - }), - [ScriptOpcode_default.CAM_RESET]: checkedHandler(ActivePlayer, state => { - state.activePlayer.write(new CamReset()); - }), - [ScriptOpcode_default.COORD]: checkedHandler(ActivePlayer, state => { - const position = state.activePlayer; - state.pushInt(Position.packCoord(position.level, position.x, position.z)); - }), - [ScriptOpcode_default.DISPLAYNAME]: checkedHandler(ActivePlayer, state => { - state.pushString(state.activePlayer.displayName); - }), - [ScriptOpcode_default.FACESQUARE]: checkedHandler(ActivePlayer, state => { - const pos = check(state.popInt(), CoordValid); - state.activePlayer.faceSquare(pos.x, pos.z); - }), - [ScriptOpcode_default.IF_CLOSE]: checkedHandler(ActivePlayer, state => { - state.activePlayer.closeModal(); - }), - [ScriptOpcode_default.LAST_COM]: state => { - state.pushInt(state.activePlayer.lastCom); - }, - [ScriptOpcode_default.LAST_INT]: state => { - state.pushInt(state.lastInt); - }, - [ScriptOpcode_default.LAST_ITEM]: state => { - const allowedTriggers = [ - ServerTriggerType_default.OPHELD1, - ServerTriggerType_default.OPHELD2, - ServerTriggerType_default.OPHELD3, - ServerTriggerType_default.OPHELD4, - ServerTriggerType_default.OPHELD5, - ServerTriggerType_default.OPHELDU, - ServerTriggerType_default.OPHELDT, - ServerTriggerType_default.INV_BUTTON1, - ServerTriggerType_default.INV_BUTTON2, - ServerTriggerType_default.INV_BUTTON3, - ServerTriggerType_default.INV_BUTTON4, - ServerTriggerType_default.INV_BUTTON5 - ]; - if (!allowedTriggers.includes(state.trigger)) { - throw new Error('is not safe to use in this trigger'); - } - state.pushInt(state.activePlayer.lastItem); - }, - [ScriptOpcode_default.LAST_SLOT]: state => { - const allowedTriggers = [ - ServerTriggerType_default.OPHELD1, - ServerTriggerType_default.OPHELD2, - ServerTriggerType_default.OPHELD3, - ServerTriggerType_default.OPHELD4, - ServerTriggerType_default.OPHELD5, - ServerTriggerType_default.OPHELDU, - ServerTriggerType_default.OPHELDT, - ServerTriggerType_default.INV_BUTTON1, - ServerTriggerType_default.INV_BUTTON2, - ServerTriggerType_default.INV_BUTTON3, - ServerTriggerType_default.INV_BUTTON4, - ServerTriggerType_default.INV_BUTTON5, - ServerTriggerType_default.INV_BUTTOND - ]; - if (!allowedTriggers.includes(state.trigger)) { - throw new Error('is not safe to use in this trigger'); - } - state.pushInt(state.activePlayer.lastSlot); - }, - [ScriptOpcode_default.LAST_USEITEM]: state => { - const allowedTriggers = [ - ServerTriggerType_default.OPHELDU, - ServerTriggerType_default.APOBJU, - ServerTriggerType_default.APLOCU, - ServerTriggerType_default.APNPCU, - ServerTriggerType_default.APPLAYERU, - ServerTriggerType_default.OPOBJU, - ServerTriggerType_default.OPLOCU, - ServerTriggerType_default.OPNPCU, - ServerTriggerType_default.OPPLAYERU - ]; - if (!allowedTriggers.includes(state.trigger)) { - throw new Error('is not safe to use in this trigger'); - } - state.pushInt(state.activePlayer.lastUseItem); - }, - [ScriptOpcode_default.LAST_USESLOT]: state => { - const allowedTriggers = [ - ServerTriggerType_default.OPHELDU, - ServerTriggerType_default.APOBJU, - ServerTriggerType_default.APLOCU, - ServerTriggerType_default.APNPCU, - ServerTriggerType_default.APPLAYERU, - ServerTriggerType_default.OPOBJU, - ServerTriggerType_default.OPLOCU, - ServerTriggerType_default.OPNPCU, - ServerTriggerType_default.OPPLAYERU - ]; - if (!allowedTriggers.includes(state.trigger)) { - throw new Error('is not safe to use in this trigger'); - } - state.pushInt(state.activePlayer.lastUseSlot); - }, - [ScriptOpcode_default.MES]: checkedHandler(ActivePlayer, state => { - const message = state.popString(); - if (Environment_default.CLIRUNNER) { - console.log(message); - } - state.activePlayer.messageGame(message); - }), - [ScriptOpcode_default.NAME]: checkedHandler(ActivePlayer, state => { - state.pushString(state.activePlayer.username); - }), - [ScriptOpcode_default.P_APRANGE]: checkedHandler(ProtectedActivePlayer, state => { - state.activePlayer.apRange = check(state.popInt(), NumberNotNull); - state.activePlayer.apRangeCalled = true; - }), - [ScriptOpcode_default.P_ARRIVEDELAY]: checkedHandler(ProtectedActivePlayer, state => { - if (state.activePlayer.lastMovement < World_default.currentTick) { - return; - } - state.activePlayer.delay = 1; - state.execution = ScriptState.SUSPENDED; - }), - [ScriptOpcode_default.P_COUNTDIALOG]: checkedHandler(ProtectedActivePlayer, state => { - state.activePlayer.write(new PCountDialog()); - state.execution = ScriptState.COUNTDIALOG; - }), - [ScriptOpcode_default.P_DELAY]: checkedHandler(ProtectedActivePlayer, state => { - state.activePlayer.delay = check(state.popInt(), NumberNotNull) + 1; - state.execution = ScriptState.SUSPENDED; - }), - [ScriptOpcode_default.P_OPHELD]: checkedHandler(ProtectedActivePlayer, state => { - throw new Error('unimplemented'); - }), - [ScriptOpcode_default.P_OPLOC]: checkedHandler(ProtectedActivePlayer, state => { - const type = check(state.popInt(), NumberNotNull) - 1; - if (type < 0 || type >= 5) { - throw new Error(`Invalid oploc: ${type + 1}`); - } - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeLoc, ServerTriggerType_default.APLOC1 + type); - }), - [ScriptOpcode_default.P_OPNPC]: checkedHandler(ProtectedActivePlayer, state => { - const type = check(state.popInt(), NumberNotNull) - 1; - if (type < 0 || type >= 5) { - throw new Error(`Invalid opnpc: ${type + 1}`); - } - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeNpc, ServerTriggerType_default.APNPC1 + type, {type: state.activeNpc.type, com: -1}); - }), - [ScriptOpcode_default.P_OPNPCT]: checkedHandler(ProtectedActivePlayer, state => { - const spellId = check(state.popInt(), NumberNotNull); - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeNpc, ServerTriggerType_default.APNPCT, {type: state.activeNpc.type, com: spellId}); - }), - [ScriptOpcode_default.P_PAUSEBUTTON]: checkedHandler(ProtectedActivePlayer, state => { - state.execution = ScriptState.PAUSEBUTTON; - }), - [ScriptOpcode_default.P_STOPACTION]: checkedHandler(ProtectedActivePlayer, state => { - state.activePlayer.stopAction(); - }), - [ScriptOpcode_default.P_CLEARPENDINGACTION]: checkedHandler(ProtectedActivePlayer, state => { - state.activePlayer.clearPendingAction(); - }), - [ScriptOpcode_default.P_TELEJUMP]: checkedHandler(ProtectedActivePlayer, state => { - const position = check(state.popInt(), CoordValid); - state.activePlayer.teleJump(position.x, position.z, position.level); - }), - [ScriptOpcode_default.P_TELEPORT]: checkedHandler(ProtectedActivePlayer, state => { - const position = check(state.popInt(), CoordValid); - state.activePlayer.teleport(position.x, position.z, position.level); - }), - [ScriptOpcode_default.P_WALK]: checkedHandler(ProtectedActivePlayer, state => { - const pos = check(state.popInt(), CoordValid); - const player = state.activePlayer; - player.queueWaypoints(findPath(player.level, player.x, player.z, pos.x, pos.z, player.width, player.width, player.length, player.orientation)); - player.updateMovement(false); - }), - [ScriptOpcode_default.SAY]: checkedHandler(ActivePlayer, state => { - state.activePlayer.say(state.popString()); - }), - [ScriptOpcode_default.SOUND_SYNTH]: checkedHandler(ActivePlayer, state => { - const [synth, loops, delay] = state.popInts(3); - state.activePlayer.write(new SynthSound(synth, loops, delay)); - }), - [ScriptOpcode_default.STAFFMODLEVEL]: checkedHandler(ActivePlayer, state => { - state.pushInt(state.activePlayer.staffModLevel); - }), - [ScriptOpcode_default.STAT]: checkedHandler(ActivePlayer, state => { - const stat = check(state.popInt(), PlayerStatValid); - state.pushInt(state.activePlayer.levels[stat]); - }), - [ScriptOpcode_default.STAT_BASE]: checkedHandler(ActivePlayer, state => { - const stat = check(state.popInt(), PlayerStatValid); - state.pushInt(state.activePlayer.baseLevels[stat]); - }), - [ScriptOpcode_default.STAT_ADD]: checkedHandler(ActivePlayer, state => { - const [stat, constant, percent] = state.popInts(3); - check(stat, PlayerStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const player = state.activePlayer; - const current = player.levels[stat]; - const added = current + (constant + (current * percent) / 100); - player.levels[stat] = Math.min(added, 255); - if (stat === 3 && player.levels[3] >= player.baseLevels[3]) { - player.resetHeroPoints(); - } - }), - [ScriptOpcode_default.STAT_SUB]: checkedHandler(ActivePlayer, state => { - const [stat, constant, percent] = state.popInts(3); - check(stat, PlayerStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const player = state.activePlayer; - const current = player.levels[stat]; - const subbed = current - (constant + (current * percent) / 100); - player.levels[stat] = Math.max(subbed, 0); - }), - [ScriptOpcode_default.SPOTANIM_PL]: checkedHandler(ActivePlayer, state => { - const delay = check(state.popInt(), NumberNotNull); - const height = state.popInt(); - const spotanimType = check(state.popInt(), SpotAnimTypeValid); - state.activePlayer.spotanim(spotanimType.id, height, delay); - }), - [ScriptOpcode_default.STAT_HEAL]: checkedHandler(ActivePlayer, state => { - const [stat, constant, percent] = state.popInts(3); - check(stat, PlayerStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const player = state.activePlayer; - const base = player.baseLevels[stat]; - const current = player.levels[stat]; - const healed = current + (constant + (current * percent) / 100); - player.levels[stat] = Math.max(Math.min(healed, base), current); - if (stat === 3 && player.levels[3] >= player.baseLevels[3]) { - player.resetHeroPoints(); - } - }), - [ScriptOpcode_default.UID]: checkedHandler(ActivePlayer, state => { - state.pushInt(state.activePlayer.uid); - }), - [ScriptOpcode_default.P_LOGOUT]: checkedHandler(ProtectedActivePlayer, state => { - state.activePlayer.logoutRequested = true; - }), - [ScriptOpcode_default.IF_SETCOLOUR]: checkedHandler(ActivePlayer, state => { - const [com, colour] = state.popInts(2); - check(com, NumberNotNull); - check(colour, NumberNotNull); - state.activePlayer.write(new IfSetColour(com, ColorConversion.rgb24to15(colour))); - }), - [ScriptOpcode_default.IF_OPENCHAT]: checkedHandler(ActivePlayer, state => { - state.activePlayer.openChat(check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.IF_OPENMAINMODALSIDEOVERLAY]: checkedHandler(ActivePlayer, state => { - const [main, side] = state.popInts(2); - check(main, NumberNotNull); - check(side, NumberNotNull); - state.activePlayer.openMainModalSideOverlay(main, side); - }), - [ScriptOpcode_default.IF_SETHIDE]: checkedHandler(ActivePlayer, state => { - const [com, hide] = state.popInts(2); - check(com, NumberNotNull); - check(hide, NumberNotNull); - state.activePlayer.write(new IfSetHide(com, hide === 1)); - }), - [ScriptOpcode_default.IF_SETOBJECT]: checkedHandler(ActivePlayer, state => { - const [com, obj, scale] = state.popInts(3); - check(com, NumberNotNull); - check(obj, ObjTypeValid); - check(scale, NumberNotNull); - state.activePlayer.write(new IfSetObject(com, obj, scale)); - }), - [ScriptOpcode_default.IF_SETTABACTIVE]: checkedHandler(ActivePlayer, state => { - state.activePlayer.write(new IfShowSide(check(state.popInt(), NumberNotNull))); - }), - [ScriptOpcode_default.IF_SETMODEL]: checkedHandler(ActivePlayer, state => { - const [com, model] = state.popInts(2); - check(com, NumberNotNull); - check(model, NumberNotNull); - state.activePlayer.write(new IfSetModel(com, model)); - }), - [ScriptOpcode_default.IF_SETRECOL]: checkedHandler(ActivePlayer, state => { - const [com, src, dest] = state.popInts(3); - check(com, NumberNotNull); - state.activePlayer.write(new IfSetRecol(com, src, dest)); - }), - [ScriptOpcode_default.IF_SETTABFLASH]: checkedHandler(ActivePlayer, state => { - state.activePlayer.write(new TutorialFlashSide(check(state.popInt(), NumberNotNull))); - }), - [ScriptOpcode_default.IF_SETANIM]: checkedHandler(ActivePlayer, state => { - const [com, seq] = state.popInts(2); - check(com, NumberNotNull); - if (seq === -1) { - return; - } - state.activePlayer.write(new IfSetAnim(com, seq)); - }), - [ScriptOpcode_default.IF_SETTAB]: checkedHandler(ActivePlayer, state => { - const [com, tab] = state.popInts(2); - check(tab, NumberNotNull); - state.activePlayer.setTab(com, tab); - }), - [ScriptOpcode_default.IF_OPENMAINMODAL]: checkedHandler(ActivePlayer, state => { - state.activePlayer.openMainModal(check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.IF_OPENCHATSTICKY]: checkedHandler(ActivePlayer, state => { - state.activePlayer.openChatSticky(check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.IF_OPENSIDEOVERLAY]: checkedHandler(ActivePlayer, state => { - state.activePlayer.openSideOverlay(check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.IF_SETPLAYERHEAD]: checkedHandler(ActivePlayer, state => { - state.activePlayer.write(new IfSetPlayerHead(check(state.popInt(), NumberNotNull))); - }), - [ScriptOpcode_default.IF_SETTEXT]: checkedHandler(ActivePlayer, state => { - const text = state.popString(); - const com = check(state.popInt(), NumberNotNull); - state.activePlayer.write(new IfSetText(com, text)); - }), - [ScriptOpcode_default.IF_SETNPCHEAD]: checkedHandler(ActivePlayer, state => { - const [com, npc] = state.popInts(2); - check(com, NumberNotNull); - check(npc, NpcTypeValid); - state.activePlayer.write(new IfSetNpcHead(com, npc)); - }), - [ScriptOpcode_default.IF_SETPOSITION]: checkedHandler(ActivePlayer, state => { - const [com, x, y2] = state.popInts(3); - check(com, NumberNotNull); - state.activePlayer.write(new IfSetPosition(com, x, y2)); - }), - [ScriptOpcode_default.IF_MULTIZONE]: checkedHandler(ActivePlayer, state => { - state.activePlayer.write(new SetMultiway(check(state.popInt(), NumberNotNull) === 1)); - }), - [ScriptOpcode_default.GIVEXP]: checkedHandler(ProtectedActivePlayer, state => { - const [stat, xp] = state.popInts(2); - check(stat, NumberNotNull); - check(xp, NumberNotNull); - state.activePlayer.addXp(stat, xp); - }), - [ScriptOpcode_default.DAMAGE]: state => { - const amount = check(state.popInt(), NumberNotNull); - const type = check(state.popInt(), HitTypeValid); - const uid = check(state.popInt(), NumberNotNull); - const player = World_default.getPlayerByUid(uid); - if (!player) { - return; - } - player.applyDamage(amount, type); - }, - [ScriptOpcode_default.IF_SETRESUMEBUTTONS]: checkedHandler(ActivePlayer, state => { - const [button1, button2, button3, button4, button5] = state.popInts(5); - state.activePlayer.resumeButtons = [button1, button2, button3, button4, button5]; - }), - [ScriptOpcode_default.TEXT_GENDER]: checkedHandler(ActivePlayer, state => { - const [male, female] = state.popStrings(2); - if (state.activePlayer.gender == 0) { - state.pushString(male); - } else { - state.pushString(female); - } - }), - [ScriptOpcode_default.MIDI_SONG]: state => { - state.activePlayer.playSong(check(state.popString(), StringNotNull)); - }, - [ScriptOpcode_default.MIDI_JINGLE]: state => { - const delay = check(state.popInt(), NumberNotNull); - const name = check(state.popString(), StringNotNull); - state.activePlayer.playJingle(delay, name); - }, - [ScriptOpcode_default.SOFTTIMER]: checkedHandler(ActivePlayer, state => { - const args = popScriptArgs(state); - const interval = state.popInt(); - const timerId = state.popInt(); - const script = ScriptProvider.get(timerId); - if (!script) { - throw new Error(`Unable to find timer script: ${timerId}`); - } - state.activePlayer.setTimer(1 /* SOFT */, script, args, interval); - }), - [ScriptOpcode_default.CLEARSOFTTIMER]: checkedHandler(ActivePlayer, state => { - state.activePlayer.clearTimer(state.popInt()); - }), - [ScriptOpcode_default.SETTIMER]: checkedHandler(ActivePlayer, state => { - const args = popScriptArgs(state); - const interval = state.popInt(); - const timerId = state.popInt(); - const script = ScriptProvider.get(timerId); - if (!script) { - throw new Error(`Unable to find timer script: ${timerId}`); - } - state.activePlayer.setTimer(0 /* NORMAL */, script, args, interval); - }), - [ScriptOpcode_default.CLEARTIMER]: checkedHandler(ActivePlayer, state => { - state.activePlayer.clearTimer(state.popInt()); - }), - [ScriptOpcode_default.HINT_COORD]: state => { - const [offset, coord, height] = state.popInts(3); - const position = check(coord, CoordValid); - state.activePlayer.hintTile(offset, position.x, position.z, height); - }, - [ScriptOpcode_default.HINT_STOP]: state => { - state.activePlayer.stopHint(); - }, - [ScriptOpcode_default.IF_CLOSESTICKY]: state => { - state.activePlayer.closeSticky(); - }, - [ScriptOpcode_default.P_EXACTMOVE]: checkedHandler(ProtectedActivePlayer, state => { - const [start, end, startCycle, endCycle, direction] = state.popInts(5); - const startPos = check(start, CoordValid); - const endPos = check(end, CoordValid); - state.activePlayer.unsetMapFlag(); - state.activePlayer.exactMove(startPos.x, startPos.z, endPos.x, endPos.z, startCycle, endCycle, direction); - }), - [ScriptOpcode_default.BUSY]: state => { - state.pushInt(state.activePlayer.busy() ? 1 : 0); - }, - [ScriptOpcode_default.BUSY2]: state => { - state.pushInt(state.activePlayer.hasInteraction() || state.activePlayer.hasWaypoints() ? 1 : 0); - }, - [ScriptOpcode_default.GETQUEUE]: state => { - const scriptId = state.popInt(); - let count = 0; - for (let request = state.activePlayer.queue.head(); request !== null; request = state.activePlayer.queue.next()) { - if (request.script.id === scriptId) { - count++; - } - } - for (let request = state.activePlayer.weakQueue.head(); request !== null; request = state.activePlayer.weakQueue.next()) { - if (request.script.id === scriptId) { - count++; - } - } - state.pushInt(count); - }, - [ScriptOpcode_default.P_LOCMERGE]: checkedHandler(ProtectedActivePlayer, state => { - const [startCycle, endCycle, southEast, northWest] = state.popInts(4); - const se = check(southEast, CoordValid); - const nw = check(northWest, CoordValid); - World_default.mergeLoc(state.activeLoc, state.activePlayer, startCycle, endCycle, se.z, se.x, nw.z, nw.x); - }), - [ScriptOpcode_default.LAST_LOGIN_INFO]: state => { - const player = state.activePlayer; - if (!isNetworkPlayer(player) || player.client === null) { - return; - } - const client = player.client; - const remoteAddress = client.remoteAddress; - if (remoteAddress == null) { - return; - } - const lastLoginIp = new Uint32Array(new Uint8Array(remoteAddress.split('.').map(x => parseInt(x))).reverse().buffer)[0]; - player.lastLoginInfo(lastLoginIp, 0, 201, 0); - }, - [ScriptOpcode_default.BAS_READYANIM]: state => { - state.activePlayer.basReadyAnim = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_TURNONSPOT]: state => { - state.activePlayer.basTurnOnSpot = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_WALK_F]: state => { - state.activePlayer.basWalkForward = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_WALK_B]: state => { - state.activePlayer.basWalkBackward = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_WALK_L]: state => { - state.activePlayer.basWalkLeft = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_WALK_R]: state => { - state.activePlayer.basWalkRight = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_RUNNING]: state => { - const seq = state.popInt(); - if (seq === -1) { - state.activePlayer.basRunning = -1; - return; - } - state.activePlayer.basRunning = check(seq, SeqTypeValid).id; - }, - [ScriptOpcode_default.GENDER]: state => { - state.pushInt(state.activePlayer.gender); - }, - [ScriptOpcode_default.HINT_NPC]: state => { - state.activePlayer.hintNpc(check(state.popInt(), NumberNotNull)); - }, - [ScriptOpcode_default.HINT_PLAYER]: state => { - state.activePlayer.hintPlayer(check(state.popInt(), NumberNotNull)); - }, - [ScriptOpcode_default.HEADICONS_GET]: state => { - state.pushInt(state.activePlayer.headicons); - }, - [ScriptOpcode_default.HEADICONS_SET]: state => { - state.activePlayer.headicons = check(state.popInt(), NumberNotNull); - }, - [ScriptOpcode_default.P_OPOBJ]: checkedHandler(ProtectedActivePlayer, state => { - const type = check(state.popInt(), NumberNotNull) - 1; - if (type < 0 || type >= 5) { - throw new Error(`Invalid opobj: ${type + 1}`); - } - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeObj, ServerTriggerType_default.APOBJ1 + type); - }), - [ScriptOpcode_default.P_OPPLAYER]: checkedHandler(ProtectedActivePlayer, state => { - const type = check(state.popInt(), NumberNotNull) - 1; - if (type < 0 || type >= 5) { - throw new Error(`Invalid opplayer: ${type + 1}`); - } - const target = state._activePlayer2; - if (!target) { - return; - } - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, target, ServerTriggerType_default.APPLAYER1 + type); - }), - [ScriptOpcode_default.ALLOWDESIGN]: state => { - state.activePlayer.allowDesign = check(state.popInt(), NumberNotNull) === 1; - }, - [ScriptOpcode_default.LAST_TARGETSLOT]: state => { - const allowedTriggers = [ServerTriggerType_default.INV_BUTTOND]; - if (!allowedTriggers.includes(state.trigger)) { - throw new Error('is not safe to use in this trigger'); - } - state.pushInt(state.activePlayer.lastTargetSlot); - }, - [ScriptOpcode_default.WALKTRIGGER]: state => { - state.activePlayer.walktrigger = state.popInt(); - }, - [ScriptOpcode_default.GETWALKTRIGGER]: state => { - state.pushInt(state.activePlayer.walktrigger); - }, - [ScriptOpcode_default.CLEARQUEUE]: state => { - const scriptId = state.popInt(); - for (let request = state.activePlayer.queue.head(); request !== null; request = state.activePlayer.queue.next()) { - if (request.script.id === scriptId) { - request.unlink(); - } - } - for (let request = state.activePlayer.weakQueue.head(); request !== null; request = state.activePlayer.weakQueue.next()) { - if (request.script.id === scriptId) { - request.unlink(); - } - } - }, - [ScriptOpcode_default.HEALENERGY]: state => { - const amount = check(state.popInt(), NumberNotNull); - const player = state.activePlayer; - player.runenergy = Math.min(Math.max(player.runenergy + amount, 0), 1e4); - }, - [ScriptOpcode_default.AFK_EVENT]: state => { - state.pushInt(state.activePlayer.afkEventReady ? 1 : 0); - state.activePlayer.afkEventReady = false; - }, - [ScriptOpcode_default.LOWMEMORY]: state => { - state.pushInt(state.activePlayer.lowMemory ? 1 : 0); - }, - [ScriptOpcode_default.SETIDKIT]: state => { - const [idkit, color] = state.popInts(2); - const idkType = check(idkit, IDKTypeValid); - let slot = idkType.type; - if (state.activePlayer.gender === 1) { - slot -= 7; - } - state.activePlayer.body[slot] = idkType.id; - let type = idkType.type; - if (state.activePlayer.gender === 1) { - type -= 7; - } - let colorSlot = -1; - if (type === 0 || type === 1) { - colorSlot = 0; - } else if (type === 2 || type === 3) { - colorSlot = 1; - } else if (type === 4) { - } else if (type === 5) { - colorSlot = 2; - } else if (type === 6) { - colorSlot = 3; - } - if (colorSlot !== -1) { - state.activePlayer.colors[colorSlot] = color; - } - }, - [ScriptOpcode_default.SETGENDER]: state => { - const gender = check(state.popInt(), GenderValid); - for (let i = 0; i < 7; i++) { - state.activePlayer.body[i] = -1; - for (let j = 0; j < IdkType.count; j++) { - if (!IdkType.get(j).disable && IdkType.get(j).type == i + (gender === 0 ? 0 : 7)) { - state.activePlayer.body[i] = j; - break; - } - } - } - state.activePlayer.gender = gender; - }, - [ScriptOpcode_default.SETSKINCOLOUR]: state => { - const skin = check(state.popInt(), SkinColourValid); - state.activePlayer.colors[4] = skin; - }, - [ScriptOpcode_default.P_OPPLAYERT]: checkedHandler(ProtectedActivePlayer, state => { - const spellId = check(state.popInt(), NumberNotNull); - const target = state._activePlayer2; - if (!target) { - return; - } - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, target, ServerTriggerType_default.APPLAYERT, {type: -1, com: spellId}); - }), - [ScriptOpcode_default.FINDHERO]: checkedHandler(ActivePlayer, state => { - const uid = state.activePlayer.findHero(); - if (uid === -1) { - state.pushInt(0); - return; - } - const player = World_default.getPlayerByUid(uid); - if (!player) { - state.pushInt(0); - return; - } - state._activePlayer2 = player; - state.pointerAdd(ScriptPointer_default.ActivePlayer2); - state.pushInt(1); - }), - [ScriptOpcode_default.BOTH_HEROPOINTS]: checkedHandler(ActivePlayer, state => { - const damage = check(state.popInt(), NumberNotNull); - const secondary = state.intOperand === 1; - const fromPlayer = secondary ? state._activePlayer2 : state._activePlayer; - const toPlayer = secondary ? state._activePlayer : state._activePlayer2; - if (!fromPlayer || !toPlayer) { - throw new Error('player is null'); - } - toPlayer.addHero(fromPlayer.uid, damage); - }), - [ScriptOpcode_default.P_ANIMPROTECT]: checkedHandler(ProtectedActivePlayer, state => { - state.activePlayer.animProtect = check(state.popInt(), NumberNotNull); - }) -}; -var PlayerOps_default = PlayerOps; - -// src/lostcity/engine/script/handlers/ServerOps.ts -var ServerOps = { - [ScriptOpcode_default.MAP_CLOCK]: state => { - state.pushInt(World_default.currentTick); - }, - [ScriptOpcode_default.MAP_MEMBERS]: state => { - state.pushInt(World_default.members ? 1 : 0); - }, - [ScriptOpcode_default.MAP_PLAYERCOUNT]: state => { - const [c1, c2] = state.popInts(2); - const from = check(c1, CoordValid); - const to = check(c2, CoordValid); - let count = 0; - for (let x = Math.floor(from.x / 8); x <= Math.ceil(to.x / 8); x++) { - for (let z2 = Math.floor(from.z / 8); z2 <= Math.ceil(to.z / 8); z2++) { - for (const player of World_default.getZone(x << 3, z2 << 3, from.level).getAllPlayersSafe()) { - if (player.x >= from.x && player.x <= to.x && player.z >= from.z && player.z <= to.z) { - count++; - } - } - } - } - state.pushInt(count); - }, - [ScriptOpcode_default.HUNTALL]: state => { - const [coord, distance, checkVis] = state.popInts(3); - const position = check(coord, CoordValid); - check(distance, NumberNotNull); - const huntvis = check(checkVis, HuntVisValid); - state.huntIterator = new HuntIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, -1, -1, HuntModeType_default.PLAYER); - }, - [ScriptOpcode_default.HUNTNEXT]: state => { - const result = state.huntIterator?.next(); - if (!result || result.done) { - state.pushInt(0); - return; - } - if (!(result.value instanceof Player2)) { - throw new Error('[ServerOps] huntnext command must result instance of Player.'); - } - state.activePlayer = result.value; - state.pointerAdd(ActivePlayer[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.NPC_HUNTALL]: state => { - const [coord, distance, checkVis] = state.popInts(3); - const position = check(coord, CoordValid); - check(distance, NumberNotNull); - const huntvis = check(checkVis, HuntVisValid); - state.huntIterator = new HuntIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, -1, -1, HuntModeType_default.NPC); - }, - [ScriptOpcode_default.NPC_HUNTNEXT]: state => { - const result = state.huntIterator?.next(); - if (!result || result.done) { - state.pushInt(0); - return; - } - if (!(result.value instanceof Npc2)) { - throw new Error('[ServerOps] npc_huntnext command must result instance of Npc.'); - } - state.activeNpc = result.value; - state.pointerAdd(ActiveNpc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.INZONE]: state => { - const [c1, c2, c3] = state.popInts(3); - const from = check(c1, CoordValid); - const to = check(c2, CoordValid); - const pos = check(c3, CoordValid); - if (pos.x < from.x || pos.x > to.x) { - state.pushInt(0); - } else if (pos.level < from.level || pos.level > to.level) { - state.pushInt(0); - } else if (pos.z < from.z || pos.z > to.z) { - state.pushInt(0); - } else { - state.pushInt(1); - } - }, - [ScriptOpcode_default.LINEOFWALK]: state => { - const [c1, c2] = state.popInts(2); - const from = check(c1, CoordValid); - const to = check(c2, CoordValid); - if (from.level !== to.level) { - state.pushInt(0); - return; - } - state.pushInt(hasLineOfWalk(from.level, from.x, from.z, to.x, to.z, 1, 1, 1, 1) ? 1 : 0); - }, - [ScriptOpcode_default.STAT_RANDOM]: state => { - const [level, low, high] = state.popInts(3); - const value = Math.floor((low * (99 - level)) / 98) + Math.floor((high * (level - 1)) / 98) + 1; - const chance = Math.floor(Math.random() * 256); - state.pushInt(value > chance ? 1 : 0); - }, - [ScriptOpcode_default.SPOTANIM_MAP]: state => { - const [spotanim, coord, height, delay] = state.popInts(4); - const position = check(coord, CoordValid); - const spotanimType = check(spotanim, SpotAnimTypeValid); - World_default.animMap(position.level, position.x, position.z, spotanimType.id, height, delay); - }, - [ScriptOpcode_default.DISTANCE]: state => { - const [c1, c2] = state.popInts(2); - const from = check(c1, CoordValid); - const to = check(c2, CoordValid); - state.pushInt(Position.distanceToSW(from, to)); - }, - [ScriptOpcode_default.MOVECOORD]: state => { - const [coord, x, y2, z2] = state.popInts(4); - const position = check(coord, CoordValid); - state.pushInt(Position.packCoord(position.level + y2, position.x + x, position.z + z2)); - }, - [ScriptOpcode_default.SEQLENGTH]: state => { - state.pushInt(check(state.popInt(), SeqTypeValid).duration); - }, - [ScriptOpcode_default.SPLIT_INIT]: state => { - const [maxWidth, linesPerPage, fontId] = state.popInts(3); - let text = state.popString(); - const font = check(fontId, FontTypeValid); - if (text.startsWith('') !== -1) { - const mesanim = text.substring(3, text.indexOf('>')); - state.splitMesanim = MesanimType.getId(mesanim); - text = text.substring(text.indexOf('>') + 1); - } else { - state.splitMesanim = -1; - } - state.splitPages = []; - const lines = font.split(text, maxWidth); - while (lines.length > 0) { - state.splitPages.push(lines.splice(0, linesPerPage)); - } - }, - [ScriptOpcode_default.SPLIT_GET]: state => { - const [page, line] = state.popInts(2); - state.pushString(state.splitPages[page][line]); - }, - [ScriptOpcode_default.SPLIT_PAGECOUNT]: state => { - state.pushInt(state.splitPages.length); - }, - [ScriptOpcode_default.SPLIT_LINECOUNT]: state => { - const page = state.popInt(); - state.pushInt(state.splitPages[page].length); - }, - [ScriptOpcode_default.SPLIT_GETANIM]: state => { - const page = state.popInt(); - if (state.splitMesanim === -1) { - state.pushInt(-1); - return; - } - state.pushInt(check(state.splitMesanim, MesanimValid).len[state.splitPages[page].length - 1]); - }, - [ScriptOpcode_default.STRUCT_PARAM]: state => { - const [structId, paramId] = state.popInts(2); - const paramType = check(paramId, ParamTypeValid); - const structType = check(structId, StructTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, structType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, structType, paramType.defaultInt)); - } - }, - [ScriptOpcode_default.COORDX]: state => { - state.pushInt(check(state.popInt(), CoordValid).x); - }, - [ScriptOpcode_default.COORDY]: state => { - state.pushInt(check(state.popInt(), CoordValid).level); - }, - [ScriptOpcode_default.COORDZ]: state => { - state.pushInt(check(state.popInt(), CoordValid).z); - }, - [ScriptOpcode_default.PLAYERCOUNT]: state => { - state.pushInt(World_default.getTotalPlayers()); - }, - [ScriptOpcode_default.MAP_BLOCKED]: state => { - const position = check(state.popInt(), CoordValid); - state.pushInt(isFlagged(position.x, position.z, position.level, CollisionFlag.WALK_BLOCKED) ? 1 : 0); - }, - [ScriptOpcode_default.MAP_INDOORS]: state => { - const position = check(state.popInt(), CoordValid); - state.pushInt(isFlagged(position.x, position.z, position.level, CollisionFlag.ROOF) ? 1 : 0); - }, - [ScriptOpcode_default.LINEOFSIGHT]: state => { - const [c1, c2] = state.popInts(2); - const from = check(c1, CoordValid); - const to = check(c2, CoordValid); - if (from.level !== to.level) { - state.pushInt(0); - return; - } - state.pushInt(hasLineOfSight(from.level, from.x, from.z, to.x, to.z, 1, 1, 1, 1) ? 1 : 0); - }, - [ScriptOpcode_default.WORLD_DELAY]: state => { - state.execution = ScriptState.WORLD_SUSPENDED; - }, - [ScriptOpcode_default.PROJANIM_PL]: state => { - const [srcCoord, uid, spotanim, srcHeight, dstHeight, delay, duration, peak, arc] = state.popInts(9); - const srcPos = check(srcCoord, CoordValid); - const spotanimType = check(spotanim, SpotAnimTypeValid); - const player = World_default.getPlayerByUid(uid); - if (!player) { - throw new Error(`attempted to use invalid player uid: ${uid}`); - } - World_default.mapProjAnim(srcPos.level, srcPos.x, srcPos.z, player.x, player.z, -player.pid - 1, spotanimType.id, srcHeight + 100, dstHeight + 100, delay, duration, peak, arc); - }, - [ScriptOpcode_default.PROJANIM_NPC]: state => { - const [srcCoord, npcUid, spotanim, srcHeight, dstHeight, delay, duration, peak, arc] = state.popInts(9); - const srcPos = check(srcCoord, CoordValid); - const spotanimType = check(spotanim, SpotAnimTypeValid); - const slot = npcUid & 65535; - const expectedType = (npcUid >> 16) & 65535; - const npc = World_default.getNpc(slot); - if (!npc) { - throw new Error(`attempted to use invalid npc uid: ${npcUid}`); - } - World_default.mapProjAnim(srcPos.level, srcPos.x, srcPos.z, npc.x, npc.z, npc.nid + 1, spotanimType.id, srcHeight + 100, dstHeight + 100, delay, duration, peak, arc); - }, - [ScriptOpcode_default.PROJANIM_MAP]: state => { - const [srcCoord, dstCoord, spotanim, srcHeight, dstHeight, delay, duration, peak, arc] = state.popInts(9); - const spotanimType = check(spotanim, SpotAnimTypeValid); - const srcPos = check(srcCoord, CoordValid); - const dstPos = check(dstCoord, CoordValid); - World_default.mapProjAnim(srcPos.level, srcPos.x, srcPos.z, dstPos.x, dstPos.z, 0, spotanimType.id, srcHeight + 100, dstHeight, delay, duration, peak, arc); - }, - [ScriptOpcode_default.MAP_LOCADDUNSAFE]: state => { - const pos = check(state.popInt(), CoordValid); - for (const loc of World_default.getZone(pos.x, pos.z, pos.level).getAllLocsUnsafe()) { - const type = check(loc.type, LocTypeValid); - if (type.active !== 1) { - continue; - } - const layer = locShapeLayer(loc.shape); - if (!loc.checkLifeCycle(World_default.currentTick) && layer === LocLayer.WALL) { - continue; - } - if (layer === LocLayer.WALL) { - if (loc.x === pos.x && loc.z === pos.z) { - state.pushInt(1); - return; - } - } else if (layer === LocLayer.GROUND) { - const width = loc.angle === LocAngle.NORTH || loc.angle === LocAngle.SOUTH ? loc.length : loc.width; - const length = loc.angle === LocAngle.NORTH || loc.angle === LocAngle.SOUTH ? loc.width : loc.length; - for (let index = 0; index < width * length; index++) { - const deltaX = loc.x + (index % width); - const deltaZ = loc.z + ((index / width) | 0); - if (deltaX === pos.x && deltaZ === pos.z) { - state.pushInt(1); - return; - } - } - } else if (layer === LocLayer.GROUND_DECOR) { - if (loc.x === pos.x && loc.z === pos.z) { - state.pushInt(1); - return; - } - } - } - state.pushInt(0); - }, - [ScriptOpcode_default.NPCCOUNT]: state => { - state.pushInt(World_default.getTotalNpcs()); - }, - [ScriptOpcode_default.MAP_LASTCLOCK]: state => { - state.pushInt(World_default.lastCycleStats[0]); - }, - [ScriptOpcode_default.MAP_LASTWORLD]: state => { - state.pushInt(World_default.lastCycleStats[1]); - }, - [ScriptOpcode_default.MAP_LASTCLIENTIN]: state => { - state.pushInt(World_default.lastCycleStats[2]); - }, - [ScriptOpcode_default.MAP_LASTNPC]: state => { - state.pushInt(World_default.lastCycleStats[3]); - }, - [ScriptOpcode_default.MAP_LASTPLAYER]: state => { - state.pushInt(World_default.lastCycleStats[4]); - }, - [ScriptOpcode_default.MAP_LASTLOGOUT]: state => { - state.pushInt(World_default.lastCycleStats[5]); - }, - [ScriptOpcode_default.MAP_LASTLOGIN]: state => { - state.pushInt(World_default.lastCycleStats[6]); - }, - [ScriptOpcode_default.MAP_LASTZONE]: state => { - state.pushInt(World_default.lastCycleStats[7]); - }, - [ScriptOpcode_default.MAP_LASTCLIENTOUT]: state => { - state.pushInt(World_default.lastCycleStats[8]); - }, - [ScriptOpcode_default.MAP_LASTCLEANUP]: state => { - state.pushInt(World_default.lastCycleStats[9]); - }, - [ScriptOpcode_default.MAP_LASTBANDWIDTHIN]: state => { - state.pushInt(World_default.lastCycleBandwidth[0]); - }, - [ScriptOpcode_default.MAP_LASTBANDWIDTHOUT]: state => { - state.pushInt(World_default.lastCycleBandwidth[1]); - }, - [ScriptOpcode_default.ZONECOUNT]: state => { - state.pushInt(World_default.zoneMap.zoneCount()); - }, - [ScriptOpcode_default.LOCCOUNT]: state => { - state.pushInt(World_default.zoneMap.locCount()); - }, - [ScriptOpcode_default.OBJCOUNT]: state => { - state.pushInt(World_default.zoneMap.objCount()); - } -}; -var ServerOps_default = ServerOps; - -// src/lostcity/engine/script/handlers/StringOps.ts -var javaStringCompare = function (a, b2) { - const len1 = a.length; - const len2 = b2.length; - const lim = Math.min(len1, len2); - let k = 0; - while (k < lim) { - const c1 = a.charCodeAt(k); - const c2 = b2.charCodeAt(k); - if (c1 != c2) { - return c1 - c2; - } - k++; - } - return len1 - len2; -}; -var StringOps = { - [ScriptOpcode_default.APPEND_NUM]: state => { - const text = state.popString(); - const num = state.popInt(); - state.pushString(text + num); - }, - [ScriptOpcode_default.APPEND]: state => { - const [t1, t2] = state.popStrings(2); - state.pushString(t1 + t2); - }, - [ScriptOpcode_default.APPEND_SIGNNUM]: state => { - const text = state.popString(); - const num = state.popInt(); - if (num >= 0) { - state.pushString(`${text}+${num}`); - } else { - state.pushString(text + num); - } - }, - [ScriptOpcode_default.LOWERCASE]: state => { - state.pushString(state.popString().toLowerCase()); - }, - [ScriptOpcode_default.TOSTRING]: state => { - state.pushString(state.popInt().toString()); - }, - [ScriptOpcode_default.COMPARE]: state => { - const [s1, s2] = state.popStrings(2); - state.pushInt(javaStringCompare(s1, s2)); - }, - [ScriptOpcode_default.TEXT_SWITCH]: state => { - const value = state.popInt(); - const [s1, s2] = state.popStrings(2); - state.pushString(value === 1 ? s1 : s2); - }, - [ScriptOpcode_default.APPEND_CHAR]: state => { - const text = state.popString(); - const char = state.popInt(); - state.pushString(text + String.fromCharCode(char)); - }, - [ScriptOpcode_default.STRING_LENGTH]: state => { - state.pushInt(state.popString().length); - }, - [ScriptOpcode_default.SUBSTRING]: state => { - const text = state.popString(); - const [start, end] = state.popInts(2); - state.pushString(text.substring(start, end)); - }, - [ScriptOpcode_default.STRING_INDEXOF_CHAR]: state => { - const text = state.popString(); - const find = String.fromCharCode(state.popInt()); - state.pushInt(text.indexOf(find)); - }, - [ScriptOpcode_default.STRING_INDEXOF_STRING]: state => { - const text = state.popString(); - const find = state.popString(); - state.pushInt(text.indexOf(find)); - } -}; -var StringOps_default = StringOps; - -// src/lostcity/engine/script/ScriptRunner.ts -class ScriptRunner2 { - static HANDLERS = { - ...CoreOps_default, - ...ServerOps_default, - ...PlayerOps_default, - ...NpcOps_default, - ...LocOps_default, - ...ObjOps_default, - ...NpcConfigOps_default, - ...LocConfigOps_default, - ...ObjConfigOps_default, - ...InvOps_default, - ...EnumOps_default, - ...StringOps_default, - ...NumberOps_default, - ...DbOps_default, - ...DebugOps_default - }; - static init(script, self2 = null, target = null, args = []) { - const state = new ScriptState(script, args); - state.self = self2; - if (self2 instanceof Player2) { - state._activePlayer = self2; - state.pointerAdd(ScriptPointer_default.ActivePlayer); - } else if (self2 instanceof Npc2) { - state._activeNpc = self2; - state.pointerAdd(ScriptPointer_default.ActiveNpc); - } else if (self2 instanceof Loc) { - state._activeLoc = self2; - state.pointerAdd(ScriptPointer_default.ActiveLoc); - } else if (self2 instanceof Obj) { - state._activeObj = self2; - state.pointerAdd(ScriptPointer_default.ActiveObj); - } - if (target instanceof Player2) { - if (self2 instanceof Player2) { - state._activePlayer2 = target; - state.pointerAdd(ScriptPointer_default.ActivePlayer2); - } else { - state._activePlayer = target; - state.pointerAdd(ScriptPointer_default.ActivePlayer); - } - } else if (target instanceof Npc2) { - if (self2 instanceof Npc2) { - state._activeNpc2 = target; - state.pointerAdd(ScriptPointer_default.ActiveNpc2); - } else { - state._activeNpc = target; - state.pointerAdd(ScriptPointer_default.ActiveNpc); - } - } else if (target instanceof Loc) { - if (self2 instanceof Loc) { - state._activeLoc2 = target; - state.pointerAdd(ScriptPointer_default.ActiveLoc2); - } else { - state._activeLoc = target; - state.pointerAdd(ScriptPointer_default.ActiveLoc); - } - } else if (target instanceof Obj) { - if (self2 instanceof Obj) { - state._activeObj2 = target; - state.pointerAdd(ScriptPointer_default.ActiveObj2); - } else { - state._activeObj = target; - state.pointerAdd(ScriptPointer_default.ActiveObj); - } - } - return state; - } - static execute(state, reset = false, benchmark = false) { - if (!state || !state.script || !state.script.info) { - return ScriptState.ABORTED; - } - try { - if (reset) { - state.reset(); - } - if (state.execution !== ScriptState.RUNNING) { - state.executionHistory.push(state.execution); - } - state.execution = ScriptState.RUNNING; - const start = performance.now() * 1000; - while (state.execution === ScriptState.RUNNING) { - if (state.pc >= state.script.opcodes.length || state.pc < -1) { - throw new Error('Invalid program counter: ' + state.pc + ', max expected: ' + state.script.opcodes.length); - } - if (!benchmark && state.opcount > 500000) { - throw new Error('Too many instructions'); - } - state.opcount++; - ScriptRunner2.executeInner(state, state.script.opcodes[++state.pc]); - } - const time = (performance.now() * 1000 - start) | 0; - if (Environment_default.PROFILE_SCRIPTS && time > 1000) { - const message = `Warning [cpu time]: Script: ${state.script.info.scriptName}, time: ${time}us`; - if (state.self instanceof Player2) { - state.self.wrappedMessageGame(message); - } else { - console.warn(message); - } - } - } catch (err) { - if (state.pc >= 0 && state.pc < state.script.opcodes.length) { - const opcode = state.script.opcodes[state.pc]; - let secondary = state.intOperand; - if (opcode === ScriptOpcode_default.POP_VARP || opcode === ScriptOpcode_default.POP_VARN || opcode === ScriptOpcode_default.PUSH_VARP || opcode === ScriptOpcode_default.PUSH_VARN) { - secondary = (state.intOperand >> 16) & 1; - } else if (opcode <= ScriptOpcode_default.POP_ARRAY_INT) { - secondary = 0; - } - err.message = ScriptOpcode_default[opcode].toLowerCase() + ' ' + err.message; - if (secondary) { - err.message = '.' + err.message; - } - } - if (state.self instanceof Player2) { - state.self.wrappedMessageGame(`script error: ${err.message}`); - state.self.wrappedMessageGame(`file: ${q.basename(state.script.info.sourceFilePath)}`); - state.self.wrappedMessageGame(''); - state.self.wrappedMessageGame('stack backtrace:'); - state.self.wrappedMessageGame(` 1: ${state.script.name} - ${state.script.fileName}:${state.script.lineNumber(state.pc)}`); - let trace2 = 1; - for (let i = state.fp; i > 0; i--) { - const frame = state.frames[i]; - if (frame) { - trace2++; - state.self.wrappedMessageGame(` ${trace2}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); - } - } - for (let i = state.debugFp; i >= 0; i--) { - const frame = state.debugFrames[i]; - if (frame) { - trace2++; - state.self.wrappedMessageGame(` ${trace2}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); - } - } - } - console.error(`script error: ${err.message}`); - console.error(`file: ${q.basename(state.script.info.sourceFilePath)}`); - console.error(''); - console.error('stack backtrace:'); - console.error(` 1: ${state.script.name} - ${state.script.fileName}:${state.script.lineNumber(state.pc)}`); - let trace = 1; - for (let i = state.fp; i > 0; i--) { - const frame = state.frames[i]; - if (frame) { - trace++; - console.error(` ${trace}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); - } - } - for (let i = state.debugFp; i >= 0; i--) { - const frame = state.debugFrames[i]; - if (frame) { - trace++; - console.error(` ${trace}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); - } - } - state.execution = ScriptState.ABORTED; - } - return state.execution; - } - static executeInner(state, opcode) { - const handler = ScriptRunner2.HANDLERS[opcode]; - if (!handler) { - throw new Error(`Unknown opcode ${opcode}`); - } - handler(state); - } -} - -// src/lostcity/entity/Npc.ts -class Npc2 extends PathingEntity { - static ANIM = 2; - static FACE_ENTITY = 4; - static SAY = 8; - static DAMAGE = 16; - static CHANGE_TYPE = 32; - static SPOTANIM = 64; - static FACE_COORD = 128; - nid; - type; - uid; - origType; - startX; - startZ; - levels = new Uint8Array(6); - baseLevels = new Uint8Array(6); - vars; - varsString; - activeScript = null; - delay = 0; - queue = new LinkList(); - timerInterval = 0; - timerClock = 0; - huntMode = -1; - nextHuntTick = -1; - huntrange = 5; - nextPatrolTick = -1; - nextPatrolPoint = 0; - delayedPatrol = false; - heroPoints = new Array(16); - constructor(level, x, z2, width, length, lifecycle, nid, type, moveRestrict, blockWalk) { - super(level, x, z2, width, length, lifecycle, moveRestrict, blockWalk, MoveStrategy_default.NAIVE, Npc2.FACE_COORD, Npc2.FACE_ENTITY); - this.nid = nid; - this.type = type; - this.uid = (type << 16) | nid; - this.startX = this.x; - this.startZ = this.z; - this.origType = type; - const npcType = NpcType.get(type); - for (let index = 0; index < npcType.stats.length; index++) { - const level2 = npcType.stats[index]; - this.levels[index] = level2; - this.baseLevels[index] = level2; - } - if (npcType.timer !== -1) { - this.setTimer(npcType.timer); - } - this.vars = new Int32Array(VarNpcType.count); - this.varsString = new Array(VarNpcType.count); - this.targetOp = npcType.defaultmode; - this.huntMode = npcType.huntmode; - this.huntrange = npcType.huntrange; - } - resetHeroPoints() { - this.heroPoints = new Array(16); - this.heroPoints.fill({uid: -1, points: 0}); - } - addHero(uid, points) { - const index = this.heroPoints.findIndex(hero => hero && hero.uid === uid); - if (index !== -1) { - this.heroPoints[index].points += points; - return; - } - const emptyIndex = this.heroPoints.findIndex(hero => hero && hero.uid === -1); - if (emptyIndex !== -1) { - this.heroPoints[emptyIndex] = {uid, points}; - return; - } - } - findHero() { - this.heroPoints.sort((a, b2) => { - return b2.points - a.points; - }); - return this.heroPoints[0]?.uid ?? -1; - } - getVar(id) { - const varn = VarNpcType.get(id); - return varn.type === ScriptVarType.STRING ? this.varsString[varn.id] : this.vars[varn.id]; - } - setVar(id, value) { - const varn = VarNpcType.get(id); - if (varn.type === ScriptVarType.STRING && typeof value === 'string') { - this.varsString[varn.id] = value; - } else if (typeof value === 'number') { - this.vars[varn.id] = value; - } - } - resetEntity(respawn) { - if (respawn) { - this.type = this.origType; - this.uid = (this.type << 16) | this.nid; - this.orientation = Direction.SOUTH; - for (let index = 0; index < this.baseLevels.length; index++) { - this.levels[index] = this.baseLevels[index]; - } - this.resetHeroPoints(); - this.defaultMode(); - const npcType = NpcType.get(this.type); - this.huntrange = npcType.huntrange; - } - super.resetPathingEntity(); - } - updateMovement(repathAllowed = true) { - const type = NpcType.get(this.type); - if (type.moverestrict === MoveRestrict_default.NOMOVE) { - return false; - } - if (this.target && this.targetOp !== NpcMode_default.PLAYERFOLLOW) { - const distanceToEscape = Position.distanceTo(this, { - x: this.startX, - z: this.startZ, - width: this.width, - length: this.length - }); - const targetDistanceFromStart = Position.distanceTo(this.target, { - x: this.startX, - z: this.startZ, - width: this.target.width, - length: this.target.length - }); - if (targetDistanceFromStart > type.maxrange && distanceToEscape > type.maxrange) { - return false; - } - } - if (repathAllowed && this.target instanceof PathingEntity && !this.interacted && this.walktrigger === -1) { - this.pathToPathingTarget(); - } - if (this.walktrigger !== -1) { - const type2 = NpcType.get(this.type); - const script = ScriptProvider.getByTrigger(ServerTriggerType_default.AI_QUEUE1 + this.walktrigger, type2.id, type2.category); - this.walktrigger = -1; - if (script) { - const state = ScriptRunner2.init(script, this, null, [this.walktriggerArg]); - ScriptRunner2.execute(state); - } - } - if (this.moveSpeed !== MoveSpeed_default.INSTANT) { - this.moveSpeed = this.defaultMoveSpeed(); - } - return super.processMovement(); - } - blockWalkFlag() { - if (this.moveRestrict === MoveRestrict_default.NORMAL) { - return CollisionFlag.NPC; - } else if (this.moveRestrict === MoveRestrict_default.BLOCKED) { - return CollisionFlag.OPEN; - } else if (this.moveRestrict === MoveRestrict_default.BLOCKED_NORMAL) { - return CollisionFlag.NPC; - } else if (this.moveRestrict === MoveRestrict_default.INDOORS) { - return CollisionFlag.NPC; - } else if (this.moveRestrict === MoveRestrict_default.OUTDOORS) { - return CollisionFlag.NPC; - } else if (this.moveRestrict === MoveRestrict_default.NOMOVE) { - return CollisionFlag.NULL; - } else if (this.moveRestrict === MoveRestrict_default.PASSTHRU) { - return CollisionFlag.OPEN; - } - return CollisionFlag.NULL; - } - defaultMoveSpeed() { - return MoveSpeed_default.WALK; - } - delayed() { - return this.delay > 0; - } - setTimer(interval) { - this.timerInterval = interval; - } - executeScript(script) { - if (!script) { - return; - } - const state = ScriptRunner2.execute(script); - if (state !== ScriptState.FINISHED && state !== ScriptState.ABORTED) { - if (state === ScriptState.WORLD_SUSPENDED) { - World_default.enqueueScript(script, script.popInt()); - } else if (state === ScriptState.NPC_SUSPENDED) { - script.activeNpc.activeScript = script; - } else { - script.activePlayer.activeScript = script; - } - } else if (script === this.activeScript) { - this.activeScript = null; - } - if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer) && script._activePlayer) { - script._activePlayer.protect = false; - script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer); - } - if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer2) && script._activePlayer2) { - script._activePlayer2.protect = false; - script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer2); - } - } - processTimers() { - if (this.timerInterval !== 0 && ++this.timerClock >= this.timerInterval) { - this.timerClock = 0; - const type = NpcType.get(this.type); - const script = ScriptProvider.getByTrigger(ServerTriggerType_default.AI_TIMER, type.id, type.category); - if (script) { - this.executeScript(ScriptRunner2.init(script, this)); - } - } - } - processQueue() { - for (let request = this.queue.head(); request !== null; request = this.queue.next()) { - if (!this.delayed()) { - request.delay--; - } - if (!this.delayed() && request.delay <= 0) { - const state = ScriptRunner2.init(request.script, this, null, request.args); - state.lastInt = request.lastInt; - this.executeScript(state); - request.unlink(); - } - } - } - enqueueScript(script, delay = 0, arg = 0) { - const request = new EntityQueueRequest(0 /* NORMAL */, script, [], delay); - request.lastInt = arg; - this.queue.addTail(request); - } - randomWalk(range) { - const dx = Math.round(Math.random() * (range * 2) - range); - const dz = Math.round(Math.random() * (range * 2) - range); - const destX = this.startX + dx; - const destZ = this.startZ + dz; - if (destX !== this.x || destZ !== this.z) { - this.queueWaypoint(destX, destZ); - } - } - processNpcModes() { - if (this.targetOp === NpcMode_default.NULL) { - this.defaultMode(); - } else if (this.targetOp === NpcMode_default.NONE) { - this.noMode(); - } else if (this.targetOp === NpcMode_default.WANDER) { - this.wanderMode(); - } else if (this.targetOp === NpcMode_default.PATROL) { - this.patrolMode(); - } else if (this.targetOp === NpcMode_default.PLAYERESCAPE) { - this.playerEscapeMode(); - } else if (this.targetOp === NpcMode_default.PLAYERFOLLOW) { - this.playerFollowMode(); - } else if (this.targetOp === NpcMode_default.PLAYERFACE) { - this.playerFaceMode(); - } else if (this.targetOp === NpcMode_default.PLAYERFACECLOSE) { - this.playerFaceCloseMode(); - } else { - this.aiMode(); - } - } - noMode() { - this.clearInteraction(); - this.updateMovement(false); - this.targetOp = NpcMode_default.NONE; - this.faceEntity = -1; - this.mask |= Npc2.FACE_ENTITY; - } - defaultMode() { - this.clearInteraction(); - this.updateMovement(false); - const type = NpcType.get(this.type); - this.targetOp = type.defaultmode; - this.faceEntity = -1; - this.mask |= Npc2.FACE_ENTITY; - } - wanderMode() { - const type = NpcType.get(this.type); - if (type.moverestrict !== MoveRestrict_default.NOMOVE && Math.random() < 0.125) { - this.randomWalk(type.wanderrange); - } - this.updateMovement(false); - } - patrolMode() { - const type = NpcType.get(this.type); - const patrolPoints = type.patrolCoord; - const patrolDelay = type.patrolDelay[this.nextPatrolPoint]; - let dest = Position.unpackCoord(patrolPoints[this.nextPatrolPoint]); - this.updateMovement(false); - if (!this.hasWaypoints() && !this.target) { - this.queueWaypoint(dest.x, dest.z); - } - if (!(this.x === dest.x && this.z === dest.z) && World_default.currentTick >= this.nextPatrolTick) { - this.teleport(dest.x, dest.z, dest.level); - } - if (this.x === dest.x && this.z === dest.z && !this.delayedPatrol) { - this.nextPatrolTick = World_default.currentTick + patrolDelay; - this.delayedPatrol = true; - } - if (this.nextPatrolTick > World_default.currentTick) { - return; - } - this.nextPatrolPoint = (this.nextPatrolPoint + 1) % patrolPoints.length; - this.nextPatrolTick = World_default.currentTick + 30; - this.delayedPatrol = false; - dest = Position.unpackCoord(patrolPoints[this.nextPatrolPoint]); - this.queueWaypoint(dest.x, dest.z); - } - playerEscapeMode() { - if (!this.target) { - this.defaultMode(); - return; - } - if (!(this.target instanceof Player2)) { - throw new Error('[Npc] Target must be a Player for playerescape mode.'); - } - if (World_default.getPlayerByUid(this.target.uid) === null) { - this.defaultMode(); - return; - } - if (Position.distanceToSW(this, this.target) > 25) { - this.defaultMode(); - return; - } - let direction; - let flags; - if (this.target.x >= this.x && this.target.z >= this.z) { - direction = Direction.SOUTH_WEST; - flags = CollisionFlag.WALL_SOUTH | CollisionFlag.WALL_WEST; - } else if (this.target.x >= this.x && this.target.z < this.z) { - direction = Direction.NORTH_WEST; - flags = CollisionFlag.WALL_NORTH | CollisionFlag.WALL_WEST; - } else if (this.target.x < this.x && this.target.z >= this.z) { - direction = Direction.SOUTH_EAST; - flags = CollisionFlag.WALL_SOUTH | CollisionFlag.WALL_EAST; - } else { - direction = Direction.NORTH_EAST; - flags = CollisionFlag.WALL_NORTH | CollisionFlag.WALL_EAST; - } - const mx = Position.moveX(this.x, direction); - const mz = Position.moveZ(this.z, direction); - if (isFlagged(mx, mz, this.level, flags)) { - this.defaultMode(); - return; - } - const position = {x: mx, z: mz, level: this.level}; - if ( - Position.distanceToSW(position, { - x: this.startX, - z: this.startZ - }) < NpcType.get(this.type).maxrange - ) { - this.queueWaypoint(position.x, position.z); - this.updateMovement(false); - return; - } - if (direction === Direction.NORTH_EAST || direction === Direction.NORTH_WEST) { - this.queueWaypoint(this.x, position.z); - } else { - this.queueWaypoint(position.x, this.z); - } - this.updateMovement(false); - } - playerFollowMode() { - if (!this.target) { - this.defaultMode(); - return; - } - if (!(this.target instanceof Player2)) { - throw new Error('[Npc] Target must be a Player for playerfollow mode.'); - } - if (World_default.getPlayerByUid(this.target.uid) === null) { - this.defaultMode(); - return; - } - if (this.level !== this.target.level) { - this.defaultMode(); - return; - } - this.pathToTarget(); - this.updateMovement(); - } - playerFaceMode() { - if (!this.target) { - this.defaultMode(); - return; - } - if (!(this.target instanceof Player2)) { - throw new Error('[Npc] Target must be a Player for playerface mode.'); - } - if (World_default.getPlayerByUid(this.target.uid) === null) { - this.defaultMode(); - return; - } - if (this.level !== this.target.level) { - this.defaultMode(); - return; - } - const type = NpcType.get(this.type); - if (Position.distanceTo(this, this.target) > type.maxrange) { - this.defaultMode(); - return; - } - this.updateMovement(false); - } - playerFaceCloseMode() { - if (!this.target) { - this.defaultMode(); - return; - } - if (!(this.target instanceof Player2)) { - throw new Error('[Npc] Target must be a Player for playerfaceclose mode.'); - } - if (World_default.getPlayerByUid(this.target.uid) == null) { - this.defaultMode(); - return; - } - if (this.level !== this.target.level) { - this.defaultMode(); - return; - } - if (Position.distanceTo(this, this.target) > 1) { - this.defaultMode(); - return; - } - this.updateMovement(false); - } - aiMode() { - if (this.delayed() || !this.target) { - this.defaultMode(); - return; - } - if (this.target.level !== this.level) { - this.defaultMode(); - return; - } - if (this.target instanceof Npc2 && (World_default.getNpc(this.target.nid) === null || this.target.delayed())) { - this.defaultMode(); - return; - } - if (this.target instanceof Npc2 && this.targetSubject.type !== -1 && World_default.getNpcByUid((this.targetSubject.type << 16) | this.target.nid) === null) { - this.defaultMode(); - return; - } - if (this.target instanceof Obj && World_default.getObj(this.target.x, this.target.z, this.level, this.target.type, -1) === null) { - this.defaultMode(); - return; - } - if (this.target instanceof Loc && World_default.getLoc(this.target.x, this.target.z, this.level, this.target.type) === null) { - this.defaultMode(); - return; - } - if (this.target instanceof Player2 && World_default.getPlayerByUid(this.target.uid) === null) { - this.defaultMode(); - return; - } - const type = NpcType.get(this.type); - if (Position.distanceTo(this, this.target) > type.attackrange) { - this.defaultMode(); - return; - } - const apTrigger = - (this.targetOp >= NpcMode_default.APNPC1 && this.targetOp <= NpcMode_default.APNPC5) || - (this.targetOp >= NpcMode_default.APPLAYER1 && this.targetOp <= NpcMode_default.APPLAYER5) || - (this.targetOp >= NpcMode_default.APLOC1 && this.targetOp <= NpcMode_default.APLOC5) || - (this.targetOp >= NpcMode_default.APOBJ1 && this.targetOp <= NpcMode_default.APOBJ5); - const opTrigger = !apTrigger; - const script = this.getTrigger(); - if (script && opTrigger && this.inOperableDistance(this.target) && this.target instanceof PathingEntity) { - this.executeScript(ScriptRunner2.init(script, this, this.target)); - this.interacted = true; - this.clearWaypoints(); - } else if (script && apTrigger && this.inApproachDistance(type.attackrange, this.target)) { - this.executeScript(ScriptRunner2.init(script, this, this.target)); - this.interacted = true; - this.clearWaypoints(); - } else if (this.inOperableDistance(this.target) && this.target instanceof PathingEntity) { - this.target = null; - this.interacted = true; - this.clearWaypoints(); - } - const moved = this.updateMovement(); - if (moved) { - this.alreadyFacedEntity = false; - this.alreadyFacedCoord = false; - } - if (this.target && !this.interacted) { - this.interacted = false; - if (script && opTrigger && this.inOperableDistance(this.target) && (this.target instanceof PathingEntity || !moved)) { - this.executeScript(ScriptRunner2.init(script, this, this.target)); - this.interacted = true; - this.clearWaypoints(); - } else if (script && apTrigger && this.inApproachDistance(type.attackrange, this.target)) { - this.executeScript(ScriptRunner2.init(script, this, this.target)); - this.interacted = true; - this.clearWaypoints(); - } else if (this.inOperableDistance(this.target) && (this.target instanceof PathingEntity || !moved)) { - this.target = null; - this.interacted = true; - this.clearWaypoints(); - } - } - } - getTrigger() { - const trigger = this.getTriggerForMode(this.targetOp); - if (trigger) { - return ScriptProvider.getByTrigger(trigger, this.type, -1) ?? null; - } - return null; - } - getTriggerForMode(mode) { - if (mode === NpcMode_default.OPPLAYER1) { - return ServerTriggerType_default.AI_OPPLAYER1; - } else if (mode === NpcMode_default.OPPLAYER2) { - return ServerTriggerType_default.AI_OPPLAYER2; - } else if (mode === NpcMode_default.OPPLAYER3) { - return ServerTriggerType_default.AI_OPPLAYER3; - } else if (mode === NpcMode_default.OPPLAYER4) { - return ServerTriggerType_default.AI_OPPLAYER4; - } else if (mode === NpcMode_default.OPPLAYER5) { - return ServerTriggerType_default.AI_OPPLAYER5; - } else if (mode === NpcMode_default.APPLAYER1) { - return ServerTriggerType_default.AI_APPLAYER1; - } else if (mode === NpcMode_default.APPLAYER2) { - return ServerTriggerType_default.AI_APPLAYER2; - } else if (mode === NpcMode_default.APPLAYER3) { - return ServerTriggerType_default.AI_APPLAYER3; - } else if (mode === NpcMode_default.APPLAYER4) { - return ServerTriggerType_default.AI_APPLAYER4; - } else if (mode === NpcMode_default.APPLAYER5) { - return ServerTriggerType_default.AI_APPLAYER5; - } else if (mode === NpcMode_default.OPLOC1) { - return ServerTriggerType_default.AI_OPLOC1; - } else if (mode === NpcMode_default.OPLOC2) { - return ServerTriggerType_default.AI_OPLOC2; - } else if (mode === NpcMode_default.OPLOC3) { - return ServerTriggerType_default.AI_OPLOC3; - } else if (mode === NpcMode_default.OPLOC4) { - return ServerTriggerType_default.AI_OPLOC4; - } else if (mode === NpcMode_default.OPLOC5) { - return ServerTriggerType_default.AI_OPLOC5; - } else if (mode === NpcMode_default.APLOC1) { - return ServerTriggerType_default.AI_APLOC1; - } else if (mode === NpcMode_default.APLOC2) { - return ServerTriggerType_default.AI_APLOC2; - } else if (mode === NpcMode_default.APLOC3) { - return ServerTriggerType_default.AI_APLOC3; - } else if (mode === NpcMode_default.APLOC4) { - return ServerTriggerType_default.AI_APLOC4; - } else if (mode === NpcMode_default.APLOC5) { - return ServerTriggerType_default.AI_APLOC5; - } else if (mode === NpcMode_default.OPOBJ1) { - return ServerTriggerType_default.AI_OPOBJ1; - } else if (mode === NpcMode_default.OPOBJ2) { - return ServerTriggerType_default.AI_OPOBJ2; - } else if (mode === NpcMode_default.OPOBJ3) { - return ServerTriggerType_default.AI_OPOBJ3; - } else if (mode === NpcMode_default.OPOBJ4) { - return ServerTriggerType_default.AI_OPOBJ4; - } else if (mode === NpcMode_default.OPOBJ5) { - return ServerTriggerType_default.AI_OPOBJ5; - } else if (mode === NpcMode_default.APOBJ1) { - return ServerTriggerType_default.AI_APOBJ1; - } else if (mode === NpcMode_default.APOBJ2) { - return ServerTriggerType_default.AI_APOBJ2; - } else if (mode === NpcMode_default.APOBJ3) { - return ServerTriggerType_default.AI_APOBJ3; - } else if (mode === NpcMode_default.APOBJ4) { - return ServerTriggerType_default.AI_APOBJ4; - } else if (mode === NpcMode_default.APOBJ5) { - return ServerTriggerType_default.AI_APOBJ5; - } else if (mode === NpcMode_default.OPNPC1) { - return ServerTriggerType_default.AI_OPNPC1; - } else if (mode === NpcMode_default.OPNPC2) { - return ServerTriggerType_default.AI_OPNPC2; - } else if (mode === NpcMode_default.OPNPC3) { - return ServerTriggerType_default.AI_OPNPC3; - } else if (mode === NpcMode_default.OPNPC4) { - return ServerTriggerType_default.AI_OPNPC4; - } else if (mode === NpcMode_default.OPNPC5) { - return ServerTriggerType_default.AI_OPNPC5; - } else if (mode === NpcMode_default.APNPC1) { - return ServerTriggerType_default.AI_APNPC1; - } else if (mode === NpcMode_default.APNPC2) { - return ServerTriggerType_default.AI_APNPC2; - } else if (mode === NpcMode_default.APNPC3) { - return ServerTriggerType_default.AI_APNPC3; - } else if (mode === NpcMode_default.APNPC4) { - return ServerTriggerType_default.AI_APNPC4; - } else if (mode === NpcMode_default.APNPC5) { - return ServerTriggerType_default.AI_APNPC5; - } else if (mode === NpcMode_default.QUEUE1) { - return ServerTriggerType_default.AI_QUEUE1; - } else if (mode === NpcMode_default.QUEUE2) { - return ServerTriggerType_default.AI_QUEUE2; - } else if (mode === NpcMode_default.QUEUE3) { - return ServerTriggerType_default.AI_QUEUE3; - } else if (mode === NpcMode_default.QUEUE4) { - return ServerTriggerType_default.AI_QUEUE4; - } else if (mode === NpcMode_default.QUEUE5) { - return ServerTriggerType_default.AI_QUEUE5; - } else if (mode === NpcMode_default.QUEUE6) { - return ServerTriggerType_default.AI_QUEUE6; - } else if (mode === NpcMode_default.QUEUE7) { - return ServerTriggerType_default.AI_QUEUE7; - } else if (mode === NpcMode_default.QUEUE8) { - return ServerTriggerType_default.AI_QUEUE8; - } else if (mode === NpcMode_default.QUEUE9) { - return ServerTriggerType_default.AI_QUEUE9; - } else if (mode === NpcMode_default.QUEUE10) { - return ServerTriggerType_default.AI_QUEUE10; - } else if (mode === NpcMode_default.QUEUE11) { - return ServerTriggerType_default.AI_QUEUE11; - } else if (mode === NpcMode_default.QUEUE12) { - return ServerTriggerType_default.AI_QUEUE12; - } else if (mode === NpcMode_default.QUEUE13) { - return ServerTriggerType_default.AI_QUEUE13; - } else if (mode === NpcMode_default.QUEUE14) { - return ServerTriggerType_default.AI_QUEUE14; - } else if (mode === NpcMode_default.QUEUE15) { - return ServerTriggerType_default.AI_QUEUE15; - } else if (mode === NpcMode_default.QUEUE16) { - return ServerTriggerType_default.AI_QUEUE16; - } else if (mode === NpcMode_default.QUEUE17) { - return ServerTriggerType_default.AI_QUEUE17; - } else if (mode === NpcMode_default.QUEUE18) { - return ServerTriggerType_default.AI_QUEUE18; - } else if (mode === NpcMode_default.QUEUE19) { - return ServerTriggerType_default.AI_QUEUE19; - } else if (mode === NpcMode_default.QUEUE20) { - return ServerTriggerType_default.AI_QUEUE20; - } - return null; - } - huntAll() { - if (this.nextHuntTick > World_default.currentTick) { - return; - } - const hunt = HuntType.get(this.huntMode); - if (hunt.type === HuntModeType_default.OFF) { - return; - } - if (hunt.nobodyNear === HuntNobodyNear_default.PAUSEHUNT && !World_default.getZoneGrid(this.level).isFlagged(Position.zone(this.x), Position.zone(this.z), 5)) { - return; - } - if (!hunt.findKeepHunting && this.target !== null) { - return; - } - let hunted; - if (hunt.type === HuntModeType_default.PLAYER) { - hunted = this.huntPlayers(hunt); - } else if (hunt.type === HuntModeType_default.NPC) { - hunted = this.huntNpcs(hunt); - } else if (hunt.type === HuntModeType_default.OBJ) { - hunted = this.huntObjs(hunt); - } else { - hunted = this.huntLocs(hunt); - } - if (hunted.length > 0) { - const entity = hunted[Math.floor(Math.random() * hunted.length)]; - this.setInteraction(Interaction_default.SCRIPT, entity, hunt.findNewMode); - } - this.nextHuntTick = World_default.currentTick + hunt.rate; - } - huntPlayers(hunt) { - const type = NpcType.get(this.type); - const players = []; - const hunted = new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, -1, -1, HuntModeType_default.PLAYER); - for (const player of hunted) { - if (!(player instanceof Player2)) { - throw new Error('[Npc] huntAll must be of type Player here.'); - } - if (hunt.checkAfk && player.zonesAfk()) { - continue; - } - if (hunt.checkNotTooStrong === HuntCheckNotTooStrong_default.OUTSIDE_WILDERNESS && !player.isInWilderness() && player.combatLevel > type.vislevel * 2) { - continue; - } - if (hunt.checkNotCombat !== -1 && player.getVar(hunt.checkNotCombat) + 8 > World_default.currentTick) { - continue; - } else if (hunt.checkNotCombatSelf !== -1 && this.getVar(hunt.checkNotCombatSelf) >= World_default.currentTick) { - continue; - } - if (hunt.checkInv !== -1) { - let quantity = 0; - if (hunt.checkObj !== -1) { - quantity = player.invTotal(hunt.checkInv, hunt.checkObj); - } else if (hunt.checkObjParam !== -1) { - quantity = player.invTotalParam(hunt.checkInv, hunt.checkObjParam); - } - if (quantity < hunt.checkInvMinQuantity || quantity > hunt.checkInvMaxQuantity) { - continue; - } - } - if (hunt.checkNotBusy && player.busy()) { - continue; - } - players.push(player); - } - return players; - } - huntNpcs(hunt) { - return Array.from(new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, hunt.checkNpc, hunt.checkCategory, HuntModeType_default.NPC)); - } - huntObjs(hunt) { - return Array.from(new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, hunt.checkObj, hunt.checkCategory, HuntModeType_default.OBJ)); - } - huntLocs(hunt) { - return Array.from(new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, hunt.checkLoc, hunt.checkCategory, HuntModeType_default.SCENERY)); - } - playAnimation(seq, delay) { - this.animId = seq; - this.animDelay = delay; - this.mask |= Npc2.ANIM; - } - spotanim(spotanim, height, delay) { - this.graphicId = spotanim; - this.graphicHeight = height; - this.graphicDelay = delay; - this.mask |= Npc2.SPOTANIM; - } - applyDamage(damage, type) { - this.damageTaken = damage; - this.damageType = type; - const current = this.levels[NpcStat_default.HITPOINTS]; - if (current - damage <= 0) { - this.levels[NpcStat_default.HITPOINTS] = 0; - this.damageTaken = current; - } else { - this.levels[NpcStat_default.HITPOINTS] = current - damage; - } - this.mask |= Npc2.DAMAGE; - } - say(text) { - if (!text) { - return; - } - this.chat = text; - this.mask |= Npc2.SAY; - } - faceSquare(x, z2) { - this.faceX = x * 2 + 1; - this.faceZ = z2 * 2 + 1; - this.orientation = Position.face(this.x, this.z, x, z2); - this.mask |= Npc2.FACE_COORD; - } - changeType(type) { - this.type = type; - this.mask |= Npc2.CHANGE_TYPE; - this.uid = (type << 16) | this.nid; - } -} - -// src/lostcity/engine/GameMap.ts -class GameMap { - async init(zoneMap) { - console.time('Loading game map'); - const path = 'data/pack/server/maps/'; - const maps = [ - 'm29_75', - 'm30_75', - 'm31_75', - 'm32_70', - 'm32_71', - 'm32_72', - 'm32_73', - 'm32_74', - 'm32_75', - 'm33_70', - 'm33_71', - 'm33_72', - 'm33_73', - 'm33_74', - 'm33_75', - 'm33_76', - 'm34_70', - 'm34_71', - 'm34_72', - 'm34_73', - 'm34_74', - 'm34_75', - 'm34_76', - 'm35_20', - 'm35_75', - 'm35_76', - 'm36_146', - 'm36_147', - 'm36_148', - 'm36_149', - 'm36_150', - 'm36_153', - 'm36_154', - 'm36_52', - 'm36_53', - 'm36_54', - 'm36_72', - 'm36_73', - 'm36_74', - 'm36_75', - 'm36_76', - 'm37_146', - 'm37_147', - 'm37_148', - 'm37_149', - 'm37_150', - 'm37_151', - 'm37_152', - 'm37_153', - 'm37_154', - 'm37_48', - 'm37_49', - 'm37_50', - 'm37_51', - 'm37_52', - 'm37_53', - 'm37_54', - 'm37_55', - 'm37_72', - 'm37_73', - 'm37_74', - 'm37_75', - 'm38_146', - 'm38_147', - 'm38_148', - 'm38_149', - 'm38_150', - 'm38_151', - 'm38_152', - 'm38_153', - 'm38_154', - 'm38_155', - 'm38_45', - 'm38_46', - 'm38_47', - 'm38_48', - 'm38_49', - 'm38_50', - 'm38_51', - 'm38_52', - 'm38_53', - 'm38_54', - 'm38_55', - 'm38_72', - 'm38_73', - 'm38_74', - 'm39_147', - 'm39_148', - 'm39_149', - 'm39_150', - 'm39_151', - 'm39_152', - 'm39_153', - 'm39_154', - 'm39_155', - 'm39_45', - 'm39_46', - 'm39_47', - 'm39_48', - 'm39_49', - 'm39_50', - 'm39_51', - 'm39_52', - 'm39_53', - 'm39_54', - 'm39_55', - 'm39_72', - 'm39_73', - 'm39_74', - 'm39_75', - 'm39_76', - 'm40_147', - 'm40_148', - 'm40_149', - 'm40_150', - 'm40_151', - 'm40_152', - 'm40_153', - 'm40_154', - 'm40_45', - 'm40_46', - 'm40_47', - 'm40_48', - 'm40_49', - 'm40_50', - 'm40_51', - 'm40_52', - 'm40_53', - 'm40_54', - 'm40_55', - 'm40_72', - 'm40_73', - 'm40_74', - 'm40_75', - 'm40_76', - 'm41_146', - 'm41_149', - 'm41_151', - 'm41_152', - 'm41_153', - 'm41_154', - 'm41_45', - 'm41_46', - 'm41_47', - 'm41_48', - 'm41_49', - 'm41_50', - 'm41_51', - 'm41_52', - 'm41_53', - 'm41_54', - 'm41_55', - 'm41_56', - 'm41_72', - 'm41_73', - 'm41_74', - 'm41_75', - 'm42_144', - 'm42_145', - 'm42_146', - 'm42_151', - 'm42_152', - 'm42_153', - 'm42_49', - 'm42_50', - 'm42_51', - 'm42_52', - 'm42_53', - 'm42_54', - 'm42_55', - 'm42_56', - 'm42_72', - 'm42_73', - 'm42_74', - 'm42_75', - 'm43_144', - 'm43_145', - 'm43_146', - 'm43_153', - 'm43_154', - 'm43_45', - 'm43_46', - 'm43_47', - 'm43_48', - 'm43_49', - 'm43_50', - 'm43_51', - 'm43_52', - 'm43_53', - 'm43_54', - 'm43_55', - 'm43_56', - 'm43_72', - 'm43_73', - 'm43_74', - 'm43_75', - 'm44_144', - 'm44_145', - 'm44_146', - 'm44_148', - 'm44_149', - 'm44_150', - 'm44_151', - 'm44_152', - 'm44_153', - 'm44_154', - 'm44_155', - 'm44_45', - 'm44_46', - 'm44_47', - 'm44_48', - 'm44_49', - 'm44_50', - 'm44_51', - 'm44_52', - 'm44_53', - 'm44_54', - 'm44_55', - 'm44_72', - 'm44_73', - 'm44_74', - 'm44_75', - 'm45_145', - 'm45_146', - 'm45_148', - 'm45_150', - 'm45_151', - 'm45_152', - 'm45_153', - 'm45_154', - 'm45_155', - 'm45_45', - 'm45_46', - 'm45_47', - 'm45_48', - 'm45_49', - 'm45_50', - 'm45_51', - 'm45_52', - 'm45_53', - 'm45_54', - 'm45_55', - 'm45_56', - 'm45_57', - 'm45_58', - 'm45_59', - 'm45_60', - 'm45_61', - 'm45_62', - 'm45_73', - 'm45_74', - 'm45_75', - 'm45_76', - 'm46_149', - 'm46_150', - 'm46_152', - 'm46_153', - 'm46_154', - 'm46_161', - 'm46_45', - 'm46_46', - 'm46_47', - 'm46_48', - 'm46_49', - 'm46_50', - 'm46_51', - 'm46_52', - 'm46_53', - 'm46_54', - 'm46_55', - 'm46_56', - 'm46_57', - 'm46_58', - 'm46_59', - 'm46_60', - 'm46_61', - 'm46_62', - 'm46_75', - 'm47_148', - 'm47_149', - 'm47_150', - 'm47_152', - 'm47_153', - 'm47_160', - 'm47_161', - 'm47_47', - 'm47_48', - 'm47_49', - 'm47_50', - 'm47_51', - 'm47_52', - 'm47_53', - 'm47_54', - 'm47_55', - 'm47_56', - 'm47_57', - 'm47_58', - 'm47_59', - 'm47_60', - 'm47_61', - 'm47_62', - 'm47_75', - 'm48_148', - 'm48_149', - 'm48_152', - 'm48_153', - 'm48_154', - 'm48_155', - 'm48_156', - 'm48_47', - 'm48_48', - 'm48_49', - 'm48_50', - 'm48_51', - 'm48_52', - 'm48_53', - 'm48_54', - 'm48_55', - 'm48_56', - 'm48_57', - 'm48_58', - 'm48_59', - 'm48_60', - 'm48_61', - 'm48_62', - 'm49_148', - 'm49_149', - 'm49_153', - 'm49_154', - 'm49_155', - 'm49_156', - 'm49_46', - 'm49_47', - 'm49_48', - 'm49_49', - 'm49_50', - 'm49_51', - 'm49_52', - 'm49_53', - 'm49_54', - 'm49_55', - 'm49_56', - 'm49_57', - 'm49_58', - 'm49_59', - 'm49_60', - 'm49_61', - 'm49_62', - 'm50_149', - 'm50_150', - 'm50_152', - 'm50_153', - 'm50_154', - 'm50_46', - 'm50_47', - 'm50_48', - 'm50_49', - 'm50_50', - 'm50_51', - 'm50_52', - 'm50_53', - 'm50_54', - 'm50_55', - 'm50_56', - 'm50_57', - 'm50_58', - 'm50_59', - 'm50_60', - 'm50_61', - 'm50_62', - 'm51_147', - 'm51_154', - 'm51_46', - 'm51_47', - 'm51_48', - 'm51_49', - 'm51_50', - 'm51_51', - 'm51_52', - 'm51_53', - 'm51_54', - 'm51_55', - 'm51_56', - 'm51_57', - 'm51_58', - 'm51_59', - 'm51_60', - 'm51_61', - 'm51_62', - 'm52_152', - 'm52_153', - 'm52_154', - 'm52_46', - 'm52_47', - 'm52_48', - 'm52_49', - 'm52_50', - 'm52_51', - 'm52_52', - 'm52_53', - 'm52_54', - 'm52_55', - 'm52_56', - 'm52_57', - 'm52_58', - 'm52_59', - 'm52_60', - 'm52_61', - 'm52_62', - 'm53_49', - 'm53_50', - 'm53_51', - 'm53_52', - 'm53_53' - ]; - for (let index = 0; index < maps.length; index++) { - const [mx, mz] = maps[index].substring(1).split('_').map(Number); - const mapsquareX = mx << 6; - const mapsquareZ = mz << 6; - this.decodeNpcs(await Packet.load(`${path}n${mx}_${mz}`), mapsquareX, mapsquareZ); - this.decodeObjs(await Packet.load(`${path}o${mx}_${mz}`), mapsquareX, mapsquareZ, zoneMap); - const lands = new Int8Array(4 * 64 * 64); - this.decodeLands(lands, await Packet.load(`${path}m${mx}_${mz}`), mapsquareX, mapsquareZ); - this.decodeLocs(lands, await Packet.load(`${path}l${mx}_${mz}`), mapsquareX, mapsquareZ, zoneMap); - } - console.timeEnd('Loading game map'); - } - changeLandCollision(x, z2, level, add) { - changeFloor(x, z2, level, add); - } - changeLocCollision(shape, angle, blockrange, length, width, active, x, z2, level, add) { - const locLayer = locShapeLayer(shape); - if (locLayer === LocLayer.WALL) { - changeWall(x, z2, level, angle, shape, blockrange, false, add); - } else if (locLayer === LocLayer.GROUND) { - if (angle === LocAngle.NORTH || angle === LocAngle.SOUTH) { - changeLoc(x, z2, level, length, width, blockrange, false, add); - } else { - changeLoc(x, z2, level, width, length, blockrange, false, add); - } - } else if (locLayer === LocLayer.GROUND_DECOR) { - if (active === 1) { - changeFloor(x, z2, level, add); - } - } - } - changeNpcCollision(size, x, z2, level, add) { - changeNpc(x, z2, level, size, add); - } - changePlayerCollision(size, x, z2, level, add) { - changePlayer(x, z2, level, size, add); - } - changeRoofCollision(x, z2, level, add) { - changeRoof(x, z2, level, add); - } - decodeNpcs(packet, mapsquareX, mapsquareZ) { - while (packet.available > 0) { - const {x, z: z2, level} = this.unpackCoord(packet.g2()); - const absoluteX = mapsquareX + x; - const absoluteZ = mapsquareZ + z2; - const count = packet.g1(); - for (let index = 0; index < count; index++) { - const npcType = NpcType.get(packet.g2()); - const size = npcType.size; - const npc = new Npc2(level, absoluteX, absoluteZ, size, size, EntityLifeCycle_default.RESPAWN, World_default.getNextNid(), npcType.id, npcType.moverestrict, npcType.blockwalk); - if (npcType.members && World_default.members) { - World_default.addNpc(npc, -1); - } else if (!npcType.members) { - World_default.addNpc(npc, -1); - } - } - } - } - decodeObjs(packet, mapsquareX, mapsquareZ, zoneMap) { - while (packet.available > 0) { - const {x, z: z2, level} = this.unpackCoord(packet.g2()); - const absoluteX = mapsquareX + x; - const absoluteZ = mapsquareZ + z2; - const count = packet.g1(); - for (let j = 0; j < count; j++) { - const objType = ObjType.get(packet.g2()); - const obj = new Obj(level, absoluteX, absoluteZ, EntityLifeCycle_default.RESPAWN, objType.id, packet.g1()); - if (objType.members && World_default.members) { - zoneMap.zone(obj.x, obj.z, obj.level).addStaticObj(obj); - } else if (!objType.members) { - zoneMap.zone(obj.x, obj.z, obj.level).addStaticObj(obj); - } - } - } - } - decodeLands(lands, packet, mapsquareX, mapsquareZ) { - for (let level = 0; level < 4; level++) { - for (let x = 0; x < 64; x++) { - for (let z2 = 0; z2 < 64; z2++) { - while (true) { - const opcode = packet.g1(); - if (opcode === 0) { - break; - } else if (opcode === 1) { - packet.g1(); - break; - } - if (opcode <= 49) { - packet.g1b(); - } else if (opcode <= 81) { - lands[this.packCoord(x, z2, level)] = opcode - 49; - } - } - } - } - } - this.applyLandCollision(mapsquareX, mapsquareZ, lands); - } - applyLandCollision(mapsquareX, mapsquareZ, lands) { - for (let level = 0; level < 4; level++) { - for (let x = 0; x < 64; x++) { - const absoluteX = x + mapsquareX; - for (let z2 = 0; z2 < 64; z2++) { - const absoluteZ = z2 + mapsquareZ; - if (x % 7 === 0 && z2 % 7 === 0) { - allocateIfAbsent(absoluteX, absoluteZ, level); - } - const land = lands[this.packCoord(x, z2, level)]; - if ((land & 4) !== 0) { - this.changeRoofCollision(absoluteX, absoluteZ, level, true); - } - if ((land & 1) !== 1) { - continue; - } - const bridged = (level === 1 ? land & 2 : lands[this.packCoord(x, z2, 1)] & 2) === 2; - const actualLevel = bridged ? level - 1 : level; - if (actualLevel < 0) { - continue; - } - this.changeLandCollision(absoluteX, absoluteZ, actualLevel, true); - } - } - } - } - decodeLocs(lands, packet, mapsquareX, mapsquareZ, zoneMap) { - let locId = -1; - let locIdOffset = packet.gsmart(); - while (locIdOffset !== 0) { - locId += locIdOffset; - let coord = 0; - let coordOffset = packet.gsmart(); - while (coordOffset !== 0) { - const {x, z: z2, level} = this.unpackCoord((coord += coordOffset - 1)); - const info = packet.g1(); - coordOffset = packet.gsmart(); - const bridged = (level === 1 ? lands[coord] & 2 : lands[this.packCoord(x, z2, 1)] & 2) === 2; - const actualLevel = bridged ? level - 1 : level; - if (actualLevel < 0) { - continue; - } - const type = LocType.get(locId); - const width = type.width; - const length = type.length; - const shape = info >> 2; - const angle = info & 3; - const absoluteX = x + mapsquareX; - const absoluteZ = z2 + mapsquareZ; - zoneMap.zone(absoluteX, absoluteZ, actualLevel).addStaticLoc(new Loc(actualLevel, absoluteX, absoluteZ, width, length, EntityLifeCycle_default.RESPAWN, locId, shape, angle)); - if (type.blockwalk) { - this.changeLocCollision(shape, angle, type.blockrange, length, width, type.active, absoluteX, absoluteZ, actualLevel, true); - } - } - locIdOffset = packet.gsmart(); - } - } - packCoord(x, z2, level) { - return (z2 & 63) | ((x & 63) << 6) | ((level & 3) << 12); - } - unpackCoord(packed) { - const z2 = packed & 63; - const x = (packed >> 6) & 63; - const level = (packed >> 12) & 3; - return {x, z: z2, level}; - } -} - -// src/jagex2/io/Isaac.ts -class Isaac { - count = 0; - rsl = new Int32Array(256); - mem = new Int32Array(256); - a = 0; - b = 0; - c = 0; - constructor(seed = [0, 0, 0, 0]) { - for (let i = 0; i < seed.length; i++) { - this.rsl[i] = seed[i]; - } - this.init(); - } - init() { - let a = 2654435769, - b2 = 2654435769, - c = 2654435769, - d = 2654435769, - e = 2654435769, - f = 2654435769, - g = 2654435769, - h2 = 2654435769; - for (let i = 0; i < 4; i++) { - a ^= b2 << 11; - d += a; - b2 += c; - b2 ^= c >>> 2; - e += b2; - c += d; - c ^= d << 8; - f += c; - d += e; - d ^= e >>> 16; - g += d; - e += f; - e ^= f << 10; - h2 += e; - f += g; - f ^= g >>> 4; - a += f; - g += h2; - g ^= h2 << 8; - b2 += g; - h2 += a; - h2 ^= a >>> 9; - c += h2; - a += b2; - } - for (let i = 0; i < 256; i += 8) { - a += this.rsl[i]; - b2 += this.rsl[i + 1]; - c += this.rsl[i + 2]; - d += this.rsl[i + 3]; - e += this.rsl[i + 4]; - f += this.rsl[i + 5]; - g += this.rsl[i + 6]; - h2 += this.rsl[i + 7]; - a ^= b2 << 11; - d += a; - b2 += c; - b2 ^= c >>> 2; - e += b2; - c += d; - c ^= d << 8; - f += c; - d += e; - d ^= e >>> 16; - g += d; - e += f; - e ^= f << 10; - h2 += e; - f += g; - f ^= g >>> 4; - a += f; - g += h2; - g ^= h2 << 8; - b2 += g; - h2 += a; - h2 ^= a >>> 9; - c += h2; - a += b2; - this.mem[i] = a; - this.mem[i + 1] = b2; - this.mem[i + 2] = c; - this.mem[i + 3] = d; - this.mem[i + 4] = e; - this.mem[i + 5] = f; - this.mem[i + 6] = g; - this.mem[i + 7] = h2; - } - for (let i = 0; i < 256; i += 8) { - a += this.mem[i]; - b2 += this.mem[i + 1]; - c += this.mem[i + 2]; - d += this.mem[i + 3]; - e += this.mem[i + 4]; - f += this.mem[i + 5]; - g += this.mem[i + 6]; - h2 += this.mem[i + 7]; - a ^= b2 << 11; - d += a; - b2 += c; - b2 ^= c >>> 2; - e += b2; - c += d; - c ^= d << 8; - f += c; - d += e; - d ^= e >>> 16; - g += d; - e += f; - e ^= f << 10; - h2 += e; - f += g; - f ^= g >>> 4; - a += f; - g += h2; - g ^= h2 << 8; - b2 += g; - h2 += a; - h2 ^= a >>> 9; - c += h2; - a += b2; - this.mem[i] = a; - this.mem[i + 1] = b2; - this.mem[i + 2] = c; - this.mem[i + 3] = d; - this.mem[i + 4] = e; - this.mem[i + 5] = f; - this.mem[i + 6] = g; - this.mem[i + 7] = h2; - } - this.isaac(); - this.count = 256; - } - isaac() { - this.c++; - this.b += this.c; - for (let i = 0; i < 256; i++) { - const x = this.mem[i]; - switch (i & 3) { - case 0: - this.a ^= this.a << 13; - break; - case 1: - this.a ^= this.a >>> 6; - break; - case 2: - this.a ^= this.a << 2; - break; - case 3: - this.a ^= this.a >>> 16; - break; - } - this.a += this.mem[(i + 128) & 255]; - let y2; - this.mem[i] = y2 = this.mem[(x >>> 2) & 255] + this.a + this.b; - this.rsl[i] = this.b = this.mem[((y2 >>> 8) >>> 2) & 255] + x; - } - } - nextInt() { - if (this.count-- === 0) { - this.isaac(); - this.count = 255; - } - return this.rsl[this.count]; - } -} - -// src/lostcity/entity/PlayerLoading.ts -class PlayerLoading { - static loadFromFile(name) { - const name37 = toBase37(name); - const safeName = fromBase37(name37); - let save; - if (fs.existsSync(`data/players/${safeName}.sav`)) { - save = Packet.load(`data/players/${safeName}.sav`); - } else { - save = new Packet(new Uint8Array()); - } - return PlayerLoading.load(name, save, null); - } - static load(name, sav, client) { - const name37 = toBase37(name); - const safeName = fromBase37(name37); - const player = client ? new NetworkPlayer2(safeName, name37, client) : new Player2(safeName, name37); - if (sav.data.length < 2) { - for (let i = 0; i < 21; i++) { - player.stats[i] = 0; - player.baseLevels[i] = 1; - player.levels[i] = 1; - } - player.stats[PlayerStat_default.HITPOINTS] = getExpByLevel(10); - player.baseLevels[PlayerStat_default.HITPOINTS] = 10; - player.levels[PlayerStat_default.HITPOINTS] = 10; - return player; - } - if (sav.g2() !== 8196) { - throw new Error('Invalid player save'); - } - const version = sav.g2(); - if (version > 3) { - throw new Error('Unsupported player save format'); - } - sav.pos = sav.data.length - 4; - const crc = sav.g4(); - if (crc != Packet.getcrc(sav.data, 0, sav.data.length - 4)) { - throw new Error('Player save corrupted'); - } - sav.pos = 4; - player.x = sav.g2(); - player.z = sav.g2(); - player.level = sav.g1(); - for (let i = 0; i < 7; i++) { - player.body[i] = sav.g1(); - if (player.body[i] === 255) { - player.body[i] = -1; - } - } - for (let i = 0; i < 5; i++) { - player.colors[i] = sav.g1(); - } - player.gender = sav.g1(); - player.runenergy = sav.g2(); - if (version >= 2) { - player.playtime = sav.g4(); - } else { - player.playtime = sav.g2(); - } - for (let i = 0; i < 21; i++) { - player.stats[i] = sav.g4(); - player.baseLevels[i] = getLevelByExp(player.stats[i]); - player.levels[i] = sav.g1(); - } - const varpCount = sav.g2(); - for (let i = 0; i < varpCount; i++) { - player.vars[i] = sav.g4(); - } - const invCount = sav.g1(); - for (let i = 0; i < invCount; i++) { - const type = sav.g2(); - const inv = player.getInventory(type); - if (inv) { - for (let j = 0; j < inv.capacity; j++) { - const id = sav.g2(); - if (id === 0) { - continue; - } - let count = sav.g1(); - if (count === 255) { - count = sav.g4(); - } - inv.set(j, { - id: id - 1, - count - }); - } - } - } - if (version >= 3) { - const afkZones = sav.g1(); - for (let index = 0; index < afkZones; index++) { - player.afkZones[index] = sav.g4(); - } - player.lastAfkZone = sav.g2(); - } - player.combatLevel = player.getCombatLevel(); - player.lastResponse = World_default.currentTick; - if (Environment_default.LOCAL_DEV) { - player.staffModLevel = 3; - } else if (Environment_default.JMODS.find(name2 => name2 === safeName) !== undefined) { - player.staffModLevel = 2; - } - return player; - } -} - -// src/lostcity/util/WorkerFactory.ts -function createWorker(fileEmbed) { - const blob = new Blob([fileEmbed], {type: 'application/javascript'}); - const blobUrl = URL.createObjectURL(blob); - return new Worker(blobUrl, {type: 'module'}); -} - -// src/lostcity/server/NetworkStream.ts -class NetworkStream { - queue = []; - available = 0; - buffer = null; - offset = 0; - waiting = 0; - received(buf) { - this.queue.push(buf); - this.available += buf.length; - } - clear() { - this.queue = []; - this.available = 0; - this.buffer = null; - this.offset = 0; - } - async readByte(socket) { - if (socket === null) { - return 0; - } - if (this.available < 1) { - await new Promise(res => setTimeout(res, 10)); - return this.readByte(socket); - } - if (this.buffer === null) { - this.buffer = this.queue.shift() ?? null; - this.offset = 0; - } - const value = this.buffer?.[this.offset] ?? 0; - this.offset++; - this.available--; - if (this.buffer && this.offset === this.buffer.length) { - this.buffer = null; - } - return value; - } - async readBytes(socket, destination, offset, length, full = true) { - if (socket === null) { - return 0; - } - if (this.available < length) { - if (full) { - await new Promise(res => setTimeout(res, 10)); - return this.readBytes(socket, destination, offset, length); - } else { - length = this.available; - } - } - destination.pos = offset; - for (let i = 0; i < length; i++) { - if (this.buffer === null) { - this.buffer = this.queue.shift() ?? null; - this.offset = 0; - } - destination.data[offset + i] = this.buffer?.[this.offset] ?? 0; - this.offset++; - this.available--; - if (this.buffer && this.offset === this.buffer.length) { - this.buffer = null; - } - } - return length; - } -} - -// src/lostcity/server/LoginServer.ts -class LoginResponse { - static SUCCESSFUL = Uint8Array.from([2]); - static INVALID_USER_OR_PASS = Uint8Array.from([3]); - static ACCOUNT_DISABLED = Uint8Array.from([4]); - static LOGGED_IN = Uint8Array.from([5]); - static SERVER_UPDATED = Uint8Array.from([6]); - static WORLD_FULL = Uint8Array.from([7]); - static LOGIN_SERVER_OFFLINE = Uint8Array.from([8]); - static LOGIN_LIMIT_EXCEEDED = Uint8Array.from([9]); - static UNABLE_TO_CONNECT = Uint8Array.from([10]); - static LOGIN_REJECTED = Uint8Array.from([11]); - static NEED_MEMBERS_ACCOUNT = Uint8Array.from([12]); - static COULD_NOT_COMPLETE = Uint8Array.from([13]); - static SERVER_UPDATING = Uint8Array.from([14]); - static RECONNECTING = Uint8Array.from([15]); - static LOGIN_ATTEMPTS_EXCEEDED = Uint8Array.from([16]); - static STANDING_IN_MEMBERS = Uint8Array.from([17]); - static STAFF_MOD_LEVEL = Uint8Array.from([18]); -} -class LoginClient { - socket = null; - stream = new NetworkStream(); - async connect() { - if (this.socket) { - return; - } - return new Promise(res => { - this.socket = net.createConnection({ - port: Environment_default.LOGIN_PORT, - host: Environment_default.LOGIN_HOST - }); - this.socket.setNoDelay(true); - this.socket.setTimeout(1000); - this.socket.on('data', async buf => { - this.stream.received(buf); - }); - this.socket.once('close', () => { - this.disconnect(); - res(); - }); - this.socket.once('error', () => { - this.disconnect(); - res(); - }); - this.socket.once('connect', () => { - res(); - }); - }); - } - disconnect() { - if (this.socket === null) { - return; - } - this.socket.destroy(); - this.socket = null; - this.stream.clear(); - } - async write(socket, opcode, data = null, full = true) { - if (socket === null) { - return; - } - const packet = new Packet(new Uint8Array(1 + 2 + (data !== null ? data?.length : 0))); - packet.p1(opcode); - if (data !== null) { - packet.p2(data.length); - packet.pdata(data, 0, data.length); - } else { - packet.p2(0); - } - const done = socket.write(packet.data); - if (!done && full) { - await new Promise(res => { - const interval = setInterval(() => { - if (socket === null || socket.closed) { - clearInterval(interval); - res(); - } - }, 100); - socket.once('drain', () => { - clearInterval(interval); - res(); - }); - }); - } - } - async load(username37, password, uid) { - await this.connect(); - if (this.socket === null) { - return {reply: -1, data: null}; - } - const request = new Packet(new Uint8Array(2 + 8 + password.length + 1 + 4)); - request.p2(Environment_default.WORLD_ID); - request.p8(username37); - request.pjstr(password); - request.p4(uid); - await this.write(this.socket, 1, request.data); - const reply = await this.stream.readByte(this.socket); - if (reply !== 1) { - this.disconnect(); - return {reply, data: null}; - } - const data = new Packet(new Uint8Array(2)); - await this.stream.readBytes(this.socket, data, 0, 2); - const length = data.g2(); - const data2 = new Packet(new Uint8Array(length)); - await this.stream.readBytes(this.socket, data2, 0, length); - this.disconnect(); - return {reply, data: data2}; - } - async save(username37, save) { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2 + 8 + 2 + save.length)); - request.p2(Environment_default.WORLD_ID); - request.p8(username37); - request.p2(save.length); - request.pdata(save, 0, save.length); - await this.write(this.socket, 2, request.data); - const reply = await this.stream.readByte(this.socket); - this.disconnect(); - return reply; - } - async reset() { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2)); - request.p2(Environment_default.WORLD_ID); - await this.write(this.socket, 3, request.data); - this.disconnect(); - } - async count(world) { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2)); - request.p2(world); - await this.write(this.socket, 4, request.data); - const reply = new Packet(new Uint8Array(2)); - await this.stream.readBytes(this.socket, reply, 0, 2); - const count = reply.g2(); - this.disconnect(); - return count; - } - async heartbeat(players) { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2 + 2 + players.length * 8)); - request.p2(Environment_default.WORLD_ID); - request.p2(players.length); - for (const player of players) { - request.p8(player); - } - await this.write(this.socket, 5, request.data); - this.disconnect(); - } -} - -// src/lostcity/server/CrcTable.ts -async function makeCrc(path) { - if (!(await fetch(path)).ok) { - return; - } - const packet = await Packet.load(path); - const crc = Packet.getcrc(packet.data, 0, packet.data.length); - CrcTable.push(crc); - CrcBuffer.p4(crc); -} -function makeCrcs() { - CrcTable = []; - CrcBuffer.pos = 0; - CrcBuffer.p4(0); - makeCrc('data/pack/client/title'); - makeCrc('data/pack/client/config'); - makeCrc('data/pack/client/interface'); - makeCrc('data/pack/client/media'); - makeCrc('data/pack/client/models'); - makeCrc('data/pack/client/textures'); - makeCrc('data/pack/client/wordenc'); - makeCrc('data/pack/client/sounds'); - CrcBuffer32 = Packet.getcrc(CrcBuffer.data, 0, CrcBuffer.data.length); -} -var CrcBuffer = new Packet(new Uint8Array(4 * 9)); -var CrcTable = []; -var CrcBuffer32 = 0; -if ((await fetch('data/pack/client/')).ok) { - makeCrcs(); -} - -// src/lostcity/server/LoginThreadWorker.ts -var LoginThreadWorker = ` -// src/jagex2/datastruct/Linkable.ts -class Linkable { - key; - next; - prev; - constructor() { - this.key = 0n; - this.next = this; - this.prev = this; - } - unlink() { - if (!this.prev || !this.next) { - return; - } - this.prev.next = this.next; - this.next.prev = this.prev; - this.next = null; - this.prev = null; - } -} - -// src/jagex2/datastruct/LinkList.ts -class LinkList { - sentinel; - cursor = null; - constructor() { - const head = new Linkable; - head.next = head; - head.prev = head; - this.sentinel = head; - } - addTail(node) { - if (node.prev) { - node.unlink(); - } - node.prev = this.sentinel.prev; - node.next = this.sentinel; - if (node.prev) { - node.prev.next = node; - } - node.next.prev = node; - } - addHead(node) { - if (node.prev) { - node.unlink(); - } - node.prev = this.sentinel; - node.next = this.sentinel.next; - node.prev.next = node; - if (node.next) { - node.next.prev = node; - } - } - removeHead() { - const node = this.sentinel.next; - if (node === this.sentinel) { - return null; - } - node?.unlink(); - return node; - } - head() { - const node = this.sentinel.next; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.next || null; - return node; - } - tail() { - const node = this.sentinel.prev; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.prev || null; - return node; - } - next() { - const node = this.cursor; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.next || null; - return node; - } - prev() { - const node = this.cursor; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.prev || null; - return node; - } - clear() { - while (true) { - const node = this.sentinel.next; - if (node === this.sentinel) { - return; - } - node?.unlink(); - } - } -} - -// src/jagex2/datastruct/Hashable.ts -class Hashable extends Linkable { - nextHashable; - prevHashable; - constructor() { - super(); - this.nextHashable = this; - this.prevHashable = this; - } - uncache() { - if (!this.prevHashable || !this.nextHashable) { - return; - } - this.prevHashable.nextHashable = this.nextHashable; - this.nextHashable.prevHashable = this.prevHashable; - this.nextHashable = null; - this.prevHashable = null; - } -} - -// src/jagex2/io/Packet.ts -class Packet extends Hashable { - static crctable = new Int32Array(256); - static bitmask = new Uint32Array(33); - static crc32b = 3988292384; - static { - for (let i = 0;i < 32; i++) { - this.bitmask[i] = (1 << i) - 1; - } - this.bitmask[32] = 4294967295; - for (let b = 0;b < 256; b++) { - let remainder = b; - for (let bit = 0;bit < 8; bit++) { - if ((remainder & 1) == 1) { - remainder = remainder >>> 1 ^ this.crc32b; - } else { - remainder >>>= 1; - } - } - this.crctable[b] = remainder; - } - } - static getcrc(src, offset, length) { - let crc = 4294967295; - for (let i = offset;i < length; i++) { - crc = crc >>> 8 ^ this.crctable[(crc ^ src[i]) & 255]; - } - return ~crc; - } - static checkcrc(src, offset, length, expected = 0) { - const checksum = Packet.getcrc(src, offset, length); - return checksum == expected; - } - static alloc(type) { - let packet = null; - if (type === 0 && this.cacheMinCount > 0) { - packet = this.cacheMin.removeHead(); - this.cacheMinCount--; - } else if (type === 1 && this.cacheMidCount > 0) { - packet = this.cacheMid.removeHead(); - this.cacheMidCount--; - } else if (type === 2 && this.cacheMaxCount > 0) { - packet = this.cacheMax.removeHead(); - this.cacheMaxCount--; - } else if (type === 3 && this.cacheBigCount > 0) { - packet = this.cacheBig.removeHead(); - this.cacheBigCount--; - } else if (type === 4 && this.cacheHugeCount > 0) { - packet = this.cacheHuge.removeHead(); - this.cacheHugeCount--; - } else if (type === 5 && this.cacheUnimaginableCount > 0) { - packet = this.cacheUnimaginable.removeHead(); - this.cacheUnimaginableCount--; - } - if (packet !== null) { - packet.pos = 0; - packet.bitPos = 0; - return packet; - } - if (type === 0) { - return new Packet(new Uint8Array(100)); - } else if (type === 1) { - return new Packet(new Uint8Array(5000)); - } else if (type === 2) { - return new Packet(new Uint8Array(30000)); - } else if (type === 3) { - return new Packet(new Uint8Array(1e5)); - } else if (type === 4) { - return new Packet(new Uint8Array(500000)); - } else if (type === 5) { - return new Packet(new Uint8Array(2000000)); - } else { - return new Packet(new Uint8Array(type)); - } - } - static async load(path, seekToEnd = false) { - const packet = new Packet(new Uint8Array(await (await fetch(path)).arrayBuffer())); - if (seekToEnd) { - packet.pos = packet.data.length; - } - return packet; - } - static cacheMinCount = 0; - static cacheMidCount = 0; - static cacheMaxCount = 0; - static cacheBigCount = 0; - static cacheHugeCount = 0; - static cacheUnimaginableCount = 0; - static cacheMin = new LinkList; - static cacheMid = new LinkList; - static cacheMax = new LinkList; - static cacheBig = new LinkList; - static cacheHuge = new LinkList; - static cacheUnimaginable = new LinkList; - data; - #view; - pos; - bitPos; - constructor(src) { - super(); - this.data = src; - this.#view = new DataView(this.data.buffer); - this.pos = 0; - this.bitPos = 0; - } - get available() { - return this.data.length - this.pos; - } - get length() { - return this.data.length; - } - release() { - this.pos = 0; - this.bitPos = 0; - if (this.data.length === 100 && Packet.cacheMinCount < 1000) { - Packet.cacheMin.addTail(this); - Packet.cacheMinCount++; - } else if (this.data.length === 5000 && Packet.cacheMidCount < 250) { - Packet.cacheMid.addTail(this); - Packet.cacheMidCount++; - } else if (this.data.length === 30000 && Packet.cacheMaxCount < 50) { - Packet.cacheMax.addTail(this); - Packet.cacheMaxCount++; - } else if (this.data.length === 1e5 && Packet.cacheBigCount < 10) { - Packet.cacheBig.addTail(this); - Packet.cacheBigCount++; - } else if (this.data.length === 500000 && Packet.cacheHugeCount < 5) { - Packet.cacheHuge.addTail(this); - Packet.cacheHugeCount++; - } else if (this.data.length === 2000000 && Packet.cacheUnimaginableCount < 2) { - Packet.cacheUnimaginable.addTail(this); - Packet.cacheUnimaginableCount++; - } - } - p1(value) { - this.#view.setUint8(this.pos++, value); - } - p2(value) { - this.#view.setUint16(this.pos, value); - this.pos += 2; - } - ip2(value) { - this.#view.setUint16(this.pos, value, true); - this.pos += 2; - } - p3(value) { - this.#view.setUint8(this.pos++, value >> 16); - this.#view.setUint16(this.pos, value); - this.pos += 2; - } - p4(value) { - this.#view.setInt32(this.pos, value); - this.pos += 4; - } - ip4(value) { - this.#view.setInt32(this.pos, value, true); - this.pos += 4; - } - p8(value) { - this.#view.setBigInt64(this.pos, value); - this.pos += 8; - } - pbool(value) { - this.p1(value ? 1 : 0); - } - pjstr(str, terminator = 10) { - const length = str.length; - for (let i = 0;i < length; i++) { - this.#view.setUint8(this.pos++, str.charCodeAt(i)); - } - this.#view.setUint8(this.pos++, terminator); - } - pdata(src, offset, length) { - this.data.set(src.subarray(offset, offset + length), this.pos); - this.pos += length - offset; - } - psize4(size) { - this.#view.setUint32(this.pos - size - 4, size); - } - psize2(size) { - this.#view.setUint16(this.pos - size - 2, size); - } - psize1(size) { - this.#view.setUint8(this.pos - size - 1, size); - } - psmarts(value) { - if (value < 64 && value >= 64) { - this.p1(value + 64); - } else if (value < 16384 && value >= -16384) { - this.p2(value + 49152); - } else { - throw new Error("Error psmarts out of range: " + value); - } - } - psmart(value) { - if (value >= 0 && value < 128) { - this.p1(value); - } else if (value >= 0 && value < 32768) { - this.p2(value + 32768); - } else { - throw new Error("Error psmart out of range: " + value); - } - } - g1() { - return this.#view.getUint8(this.pos++); - } - g1b() { - return this.#view.getInt8(this.pos++); - } - g2() { - this.pos += 2; - return this.#view.getUint16(this.pos - 2); - } - g2s() { - this.pos += 2; - return this.#view.getInt16(this.pos - 2); - } - ig2() { - this.pos += 2; - return this.#view.getUint16(this.pos - 2, true); - } - g3() { - const result = this.#view.getUint8(this.pos++) << 16 | this.#view.getUint16(this.pos); - this.pos += 2; - return result; - } - g4() { - this.pos += 4; - return this.#view.getInt32(this.pos - 4); - } - ig4() { - this.pos += 4; - return this.#view.getInt32(this.pos - 4, true); - } - g8() { - this.pos += 8; - return this.#view.getBigInt64(this.pos - 8); - } - gbool() { - return this.g1() === 1; - } - gjstr(terminator = 10) { - const length = this.data.length; - let str = ""; - let b; - while ((b = this.#view.getUint8(this.pos++)) !== terminator && this.pos < length) { - str += String.fromCharCode(b); - } - return str; - } - gdata(dest, offset, length) { - dest.set(this.data.subarray(this.pos, this.pos + length), offset); - this.pos += length; - } - gsmarts() { - return this.#view.getUint8(this.pos) < 128 ? this.g1() - 64 : this.g2() - 49152; - } - gsmart() { - return this.#view.getUint8(this.pos) < 128 ? this.g1() : this.g2() - 32768; - } - bits() { - this.bitPos = this.pos << 3; - } - bytes() { - this.pos = this.bitPos + 7 >>> 3; - } - gBit(n) { - let bytePos = this.bitPos >>> 3; - let remaining = 8 - (this.bitPos & 7); - let value = 0; - this.bitPos += n; - for (;n > remaining; remaining = 8) { - value += (this.#view.getUint8(bytePos++) & Packet.bitmask[remaining]) << n - remaining; - n -= remaining; - } - if (n == remaining) { - value += this.#view.getUint8(bytePos) & Packet.bitmask[remaining]; - } else { - value += this.#view.getUint8(bytePos) >>> remaining - n & Packet.bitmask[n]; - } - return value; - } - pBit(n, value) { - const pos = this.bitPos; - this.bitPos += n; - let bytePos = pos >>> 3; - let remaining = 8 - (pos & 7); - const view = this.#view; - for (;n > remaining; remaining = 8) { - const shift2 = (1 << remaining) - 1; - const byte2 = view.getUint8(bytePos); - view.setUint8(bytePos++, byte2 & ~shift2 | value >>> n - remaining & shift2); - n -= remaining; - } - const r = remaining - n; - const shift = (1 << n) - 1; - const byte = view.getUint8(bytePos); - view.setUint8(bytePos, byte & ~shift << r | (value & shift) << r); - } -} - -// src/jagex2/jstring/JString.ts -function toBase37(string) { - string = string.trim(); - let l = 0n; - for (let i = 0;i < string.length && i < 12; i++) { - const c = string.charCodeAt(i); - l *= 37n; - if (c >= 65 && c <= 90) { - l += BigInt(c + 1 - 65); - } else if (c >= 97 && c <= 122) { - l += BigInt(c + 1 - 97); - } else if (c >= 48 && c <= 57) { - l += BigInt(c + 27 - 48); - } - } - return l; -} -function fromBase37(value) { - if (value < 0n || value >= 6582952005840035281n) { - return "invalid_name"; - } - if (value % 37n === 0n) { - return "invalid_name"; - } - let len = 0; - const chars = Array(12); - while (value !== 0n) { - const l1 = value; - value /= 37n; - chars[11 - len++] = BASE37_LOOKUP[Number(l1 - value * 37n)]; - } - return chars.slice(12 - len).join(""); -} -function toSafeName(name) { - return fromBase37(toBase37(name)); -} -var BASE37_LOOKUP = [ - "_", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9" -]; - -// src/lostcity/server/NetworkStream.ts -class NetworkStream { - queue = []; - available = 0; - buffer = null; - offset = 0; - waiting = 0; - received(buf) { - this.queue.push(buf); - this.available += buf.length; - } - clear() { - this.queue = []; - this.available = 0; - this.buffer = null; - this.offset = 0; - } - async readByte(socket) { - if (socket === null) { - return 0; - } - if (this.available < 1) { - await new Promise((res) => setTimeout(res, 10)); - return this.readByte(socket); - } - if (this.buffer === null) { - this.buffer = this.queue.shift() ?? null; - this.offset = 0; - } - const value = this.buffer?.[this.offset] ?? 0; - this.offset++; - this.available--; - if (this.buffer && this.offset === this.buffer.length) { - this.buffer = null; - } - return value; - } - async readBytes(socket, destination, offset, length, full = true) { - if (socket === null) { - return 0; - } - if (this.available < length) { - if (full) { - await new Promise((res) => setTimeout(res, 10)); - return this.readBytes(socket, destination, offset, length); - } else { - length = this.available; - } - } - destination.pos = offset; - for (let i = 0;i < length; i++) { - if (this.buffer === null) { - this.buffer = this.queue.shift() ?? null; - this.offset = 0; - } - destination.data[offset + i] = this.buffer?.[this.offset] ?? 0; - this.offset++; - this.available--; - if (this.buffer && this.offset === this.buffer.length) { - this.buffer = null; - } - } - return length; - } -} - -// src/lostcity/util/Environment.ts -var Environment_default = { - PUBLIC_IP: "localhost", - WEB_PORT: 80, - GAME_PORT: 43594, - LOGIN_HOST: "localhost", - LOGIN_PORT: 43500, - LOGIN_KEY: "", - FRIEND_HOST: "localhost", - FRIEND_PORT: 43501, - FRIEND_KEY: "", - WORLD_ID: 0, - LOCAL_DEV: true, - MEMBERS_WORLD: true, - XP_MULTIPLIER: 1, - SHUTDOWN_TIMER: 50, - HTTPS_ENABLED: false, - ADDRESS_SHOWPORT: true, - CLIRUNNER: false, - CI_MODE: false, - SKIP_CORS: false, - DB_HOST: "", - DB_USER: "", - DB_PASS: "", - DB_NAME: "", - ADMIN_IP: "localhost", - SKIP_CRC: false, - JAVA_PATH: "java", - DATA_SRC_DIR: "data/src", - VALIDATE_PACK: true, - STRICT_FOLDERS: true, - BUILD_ON_STARTUP: true, - UPDATE_ON_STARTUP: true, - JMODS: ["pazaz"], - CLIENT_PATHFINDER: true, - NO_SOCKET_TIMEOUT: false, - PROFILE_SCRIPTS: false -}; - -// src/lostcity/server/LoginServer.ts -class LoginResponse { - static SUCCESSFUL = Uint8Array.from([2]); - static INVALID_USER_OR_PASS = Uint8Array.from([3]); - static ACCOUNT_DISABLED = Uint8Array.from([4]); - static LOGGED_IN = Uint8Array.from([5]); - static SERVER_UPDATED = Uint8Array.from([6]); - static WORLD_FULL = Uint8Array.from([7]); - static LOGIN_SERVER_OFFLINE = Uint8Array.from([8]); - static LOGIN_LIMIT_EXCEEDED = Uint8Array.from([9]); - static UNABLE_TO_CONNECT = Uint8Array.from([10]); - static LOGIN_REJECTED = Uint8Array.from([11]); - static NEED_MEMBERS_ACCOUNT = Uint8Array.from([12]); - static COULD_NOT_COMPLETE = Uint8Array.from([13]); - static SERVER_UPDATING = Uint8Array.from([14]); - static RECONNECTING = Uint8Array.from([15]); - static LOGIN_ATTEMPTS_EXCEEDED = Uint8Array.from([16]); - static STANDING_IN_MEMBERS = Uint8Array.from([17]); - static STAFF_MOD_LEVEL = Uint8Array.from([18]); -} -class LoginClient { - socket = null; - stream = new NetworkStream; - async connect() { - if (this.socket) { - return; - } - return new Promise((res) => { - this.socket = net.createConnection({ - port: Environment_default.LOGIN_PORT, - host: Environment_default.LOGIN_HOST - }); - this.socket.setNoDelay(true); - this.socket.setTimeout(1000); - this.socket.on("data", async (buf) => { - this.stream.received(buf); - }); - this.socket.once("close", () => { - this.disconnect(); - res(); - }); - this.socket.once("error", () => { - this.disconnect(); - res(); - }); - this.socket.once("connect", () => { - res(); - }); - }); - } - disconnect() { - if (this.socket === null) { - return; - } - this.socket.destroy(); - this.socket = null; - this.stream.clear(); - } - async write(socket, opcode, data = null, full = true) { - if (socket === null) { - return; - } - const packet = new Packet(new Uint8Array(1 + 2 + (data !== null ? data?.length : 0))); - packet.p1(opcode); - if (data !== null) { - packet.p2(data.length); - packet.pdata(data, 0, data.length); - } else { - packet.p2(0); - } - const done = socket.write(packet.data); - if (!done && full) { - await new Promise((res) => { - const interval = setInterval(() => { - if (socket === null || socket.closed) { - clearInterval(interval); - res(); - } - }, 100); - socket.once("drain", () => { - clearInterval(interval); - res(); - }); - }); - } - } - async load(username37, password, uid) { - await this.connect(); - if (this.socket === null) { - return { reply: -1, data: null }; - } - const request = new Packet(new Uint8Array(2 + 8 + password.length + 1 + 4)); - request.p2(Environment_default.WORLD_ID); - request.p8(username37); - request.pjstr(password); - request.p4(uid); - await this.write(this.socket, 1, request.data); - const reply = await this.stream.readByte(this.socket); - if (reply !== 1) { - this.disconnect(); - return { reply, data: null }; - } - const data = new Packet(new Uint8Array(2)); - await this.stream.readBytes(this.socket, data, 0, 2); - const length = data.g2(); - const data2 = new Packet(new Uint8Array(length)); - await this.stream.readBytes(this.socket, data2, 0, length); - this.disconnect(); - return { reply, data: data2 }; - } - async save(username37, save) { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2 + 8 + 2 + save.length)); - request.p2(Environment_default.WORLD_ID); - request.p8(username37); - request.p2(save.length); - request.pdata(save, 0, save.length); - await this.write(this.socket, 2, request.data); - const reply = await this.stream.readByte(this.socket); - this.disconnect(); - return reply; - } - async reset() { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2)); - request.p2(Environment_default.WORLD_ID); - await this.write(this.socket, 3, request.data); - this.disconnect(); - } - async count(world) { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2)); - request.p2(world); - await this.write(this.socket, 4, request.data); - const reply = new Packet(new Uint8Array(2)); - await this.stream.readBytes(this.socket, reply, 0, 2); - const count = reply.g2(); - this.disconnect(); - return count; - } - async heartbeat(players) { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2 + 2 + players.length * 8)); - request.p2(Environment_default.WORLD_ID); - request.p2(players.length); - for (const player of players) { - request.p8(player); - } - await this.write(this.socket, 5, request.data); - this.disconnect(); - } -} - -// src/lostcity/server/LoginThread.ts -self.onmessage = async (msg) => { - try { - switch (msg.data.type) { - case "reset": { - break; - } - case "heartbeat": { - break; - } - case "loginreq": { - const { opcode, data, socket } = msg.data; - const stream = new Packet(data); - const revision = stream.g1(); - if (revision !== 225) { - self.postMessage({ - type: "loginreply", - status: LoginResponse.SERVER_UPDATED, - socket - }); - return; - } - const info = stream.g1(); - const crcs = new Uint8Array(9 * 4); - stream.gdata(crcs, 0, crcs.length); - const enc = new Uint8Array(stream.g1()); - stream.gdata(enc, 0, enc.length); - stream.pos = 0; - stream.pdata(enc, 0, enc.length); - stream.pos = 0; - if (stream.g1() !== 10) { - self.postMessage({ - type: "loginreply", - status: LoginResponse.LOGIN_REJECTED, - socket - }); - return; - } - const seed = []; - for (let i = 0;i < 4; i++) { - seed[i] = stream.g4(); - } - const uid = stream.g4(); - const username = stream.gjstr(); - const password = stream.gjstr(); - if (username.length < 1 || username.length > 12) { - self.postMessage({ - type: "loginreply", - status: LoginResponse.INVALID_USER_OR_PASS, - socket - }); - return; - } - const save = new Uint8Array; - self.postMessage({ - type: "loginreply", - status: LoginResponse.SUCCESSFUL, - socket, - info, - seed, - username: toSafeName(username), - save - }); - break; - } - case "logout": { - const { username, save } = msg.data; - if (Environment_default.LOGIN_KEY) { - const login = new LoginClient; - const reply = await login.save(toBase37(username), save); - if (reply === 0) { - self.postMessage({ - type: "logoutreply", - username - }); - } - } else { - self.postMessage({ - type: "logoutreply", - username - }); - } - break; - } - default: - console.error("Unknown message type: " + msg.data.type); - break; - } - } catch (err) { - console.error(err); - } -}; -`; - -// src/lostcity/engine/Login.ts -class Login { - loginThread = createWorker(LoginThreadWorker); - loginRequests = new Map(); - logoutRequests = new Set(); - constructor() { - this.loginThread.onmessage = msg => { - try { - this.onMessage(msg); - } catch (err) { - console.error('Login Thread:', err); - } - }; - } - async readIn(socket, data) { - const opcode = data.g1(); - if (opcode === 16) { - const length = data.g1(); - if (data.available < length) { - socket.terminate(); - return; - } - const post = new Uint8Array(length); - data.gdata(post, 0, post.length); - data.pos -= post.length; - const revision = data.g1(); - if (revision !== 225) { - socket.writeImmediate(LoginResponse.SERVER_UPDATED); - return; - } - data.pos += 1; - const crcs = new Uint8Array(9 * 4); - data.gdata(crcs, 0, crcs.length); - if (!Packet.checkcrc(crcs, 0, crcs.length, CrcBuffer32)) { - socket.writeImmediate(LoginResponse.SERVER_UPDATED); - return; - } - this.loginThread.postMessage({ - type: 'loginreq', - opcode, - data: post, - socket: socket.uniqueId - }); - this.loginRequests.set(socket.uniqueId, socket); - } else { - socket.terminate(); - } - } - logout(player) { - if (this.logoutRequests.has(player.username37)) { - return; - } - this.loginThread.postMessage({ - type: 'logout', - username: player.username - }); - } - onMessage(msg) { - switch (msg.data.type) { - case 'loginreply': { - const {status, socket} = msg.data; - const client = this.loginRequests.get(socket); - if (!client) { - return; - } - this.loginRequests.delete(socket); - if (status[0] !== 2) { - client.writeImmediate(status); - client.close(); - return; - } - const {info, seed, username, save} = msg.data; - if (World_default.getTotalPlayers() >= 2000) { - client.writeImmediate(LoginResponse.WORLD_FULL); - client.close(); - return; - } - if (World_default.shutdownTick > -1 && World_default.currentTick - World_default.shutdownTick > 0) { - client.writeImmediate(LoginResponse.SERVER_UPDATING); - client.close(); - return; - } - if (Environment_default.LOCAL_DEV) { - for (const player2 of World_default.players) { - if (player2.username === username) { - client.writeImmediate(LoginResponse.LOGGED_IN); - client.close(); - return; - } - } - } - client.decryptor = new Isaac(seed); - for (let i = 0; i < 4; i++) { - seed[i] += 50; - } - client.encryptor = new Isaac(seed); - const player = PlayerLoading.load(username, new Packet(save), client); - player.lowMemory = (info & 1) !== 0; - World_default.addPlayer(player); - break; - } - case 'logoutreply': { - const {username} = msg.data; - const player = World_default.getPlayerByUsername(username); - if (player) { - World_default.getZone(player.x, player.z, player.level).leave(player); - World_default.players.remove(player.pid); - player.pid = -1; - player.terminate(); - this.logoutRequests.delete(player.username37); - } - break; - } - default: - throw new Error('Unknown message type: ' + msg.data.type); - } - } -} -var Login_default = new Login(); - -// src/lostcity/entity/EntityList.ts -class EntityList { - entities; - free; - indexPadding; - ids; - lastUsedIndex = 0; - constructor(size, indexPadding) { - this.entities = new Array(size).fill(null); - this.ids = new Int32Array(size).fill(-1); - this.free = new Set(Array.from({length: size}, (_2, index) => index)); - this.indexPadding = indexPadding; - } - next(_2 = false, start = this.lastUsedIndex + 1) { - const length = this.ids.length; - for (let index = start; index < length; index++) { - if (this.ids[index] === -1) { - return index; - } - } - for (let index = this.indexPadding; index < start; index++) { - if (this.ids[index] === -1) { - return index; - } - } - throw new Error('[EntityList] cannot find next id'); - } - *[Symbol.iterator]() { - for (const index of this.ids) { - if (index === -1) { - continue; - } - const entity = this.entities[index]; - if (!entity) { - continue; - } - yield entity; - } - } - get count() { - let count = 0; - for (const _2 of this[Symbol.iterator]()) { - count++; - } - return count; - } - get(id) { - const index = this.ids[id]; - return index !== -1 ? this.entities[index] : null; - } - set(id, entity) { - if (!this.free.size) { - throw new Error('[EntityList] cannot find available entities slot.'); - } - const index = this.free.values().next().value; - this.free.delete(index); - this.ids[id] = index; - this.entities[index] = entity; - this.lastUsedIndex = id; - } - remove(id) { - const index = this.ids[id]; - if (index !== -1) { - this.entities[index] = null; - this.ids[id] = -1; - this.free.add(index); - } - } - reset() { - this.entities.fill(null); - this.ids.fill(-1); - this.free.clear(); - for (let i = 0; i < this.ids.length; i++) { - this.free.add(i); - } - } -} - -class NpcList extends EntityList { - constructor(size) { - super(size, 0); - } -} - -class PlayerList extends EntityList { - constructor(size) { - super(size, 1); - } - next(priority = false, start = this.lastUsedIndex + 1) { - if (priority) { - const init2 = start === 0 ? 1 : 0; - for (let i = init2; i < 100; i++) { - const index = start + i; - const id = this.ids[index]; - if (id === -1) { - return index; - } - } - } - return super.next(); - } -} - -// src/lostcity/network/outgoing/model/UpdateRebootTimer.ts -class UpdateRebootTimer extends OutgoingMessage { - ticks; - priority = ServerProtPriority.LOW; - constructor(ticks) { - super(); - this.ticks = ticks; - } -} - -// src/lostcity/engine/World.ts -class World35 { - id = Environment_default.WORLD_ID; - members = Environment_default.MEMBERS_WORLD; - currentTick = 0; - tickRate = 600; - shutdownTick = -1; - allLastModified = 0; - datLastModified = new Map(); - lastCycleStats = []; - lastCycleBandwidth = [0, 0]; - gameMap = new GameMap(); - zoneMap = new ZoneMap2(); - invs = []; - vars = new Int32Array(); - varsString = []; - newPlayers = []; - players = new PlayerList(2048); - npcs = new NpcList(8192); - zonesTracking = new Map(); - queue = new LinkList(); - shouldReload(type, client = false) { - return true; - } - async reload() { - let transmitted = false; - if (this.shouldReload('varp', true)) { - VarPlayerType.load('data/pack'); - transmitted = true; - } - if (this.shouldReload('param')) { - ParamType.load('data/pack'); - } - if (this.shouldReload('obj', true)) { - ObjType.load('data/pack', this.members); - transmitted = true; - } - if (this.shouldReload('loc', true)) { - LocType.load('data/pack'); - transmitted = true; - } - if (this.shouldReload('npc', true)) { - NpcType.load('data/pack'); - transmitted = true; - } - if (this.shouldReload('idk', true)) { - IdkType.load('data/pack'); - transmitted = true; - } - if (this.shouldReload('frame_del')) { - SeqFrame.load('data/pack'); - } - if (this.shouldReload('seq', true)) { - SeqType.load('data/pack'); - transmitted = true; - } - if (this.shouldReload('spotanim', true)) { - SpotanimType.load('data/pack'); - transmitted = true; - } - if (this.shouldReload('category')) { - CategoryType.load('data/pack'); - } - if (this.shouldReload('enum')) { - EnumType.load('data/pack'); - } - if (this.shouldReload('struct')) { - StructType.load('data/pack'); - } - if (this.shouldReload('inv')) { - InvType.load('data/pack'); - for (let i = 0; i < InvType.count; i++) { - const inv = InvType.get(i); - if (inv && inv.scope === InvType.SCOPE_SHARED) { - this.invs[i] = Inventory.fromType(i); - } - } - } - if (this.shouldReload('mesanim')) { - MesanimType.load('data/pack'); - } - if (this.shouldReload('dbtable')) { - DbTableType.load('data/pack'); - } - if (this.shouldReload('dbrow')) { - DbRowType.load('data/pack'); - } - if (this.shouldReload('hunt')) { - HuntType.load('data/pack'); - } - if (this.shouldReload('varn')) { - VarNpcType.load('data/pack'); - } - if (this.shouldReload('vars')) { - VarSharedType.load('data/pack'); - if (this.vars.length !== VarSharedType.count) { - const old = this.vars; - this.vars = new Int32Array(VarSharedType.count); - for (let i = 0; i < VarSharedType.count && i < old.length; i++) { - this.vars[i] = old[i]; - } - const oldString = this.varsString; - this.varsString = new Array(VarSharedType.count); - for (let i = 0; i < VarSharedType.count && i < old.length; i++) { - this.varsString[i] = oldString[i]; - } - } - } - if (this.shouldReload('interface')) { - Component.load('data/pack'); - transmitted = true; - } - if (this.shouldReload('script')) { - const count = await ScriptProvider.load('data/pack'); - if (count === -1) { - this.broadcastMes('There was an issue while reloading scripts.'); - } else { - this.broadcastMes(`Reloaded ${count} scripts.`); - } - } - makeCrcs(); - preloadClient(); - } - broadcastMes(message) { - for (const player of this.players) { - player.messageGame(message); - } - } - async start(skipMaps = false, startCycle = true) { - console.log('Starting world...'); - await Bzip.load(await (await fetch('bz2.wasm')).arrayBuffer()); - await FontType.load('data/pack'); - await WordEnc2.load('data/pack'); - await this.reload(); - if (!skipMaps) { - await this.gameMap.init(this.zoneMap); - } - Login_default.loginThread.postMessage({ - type: 'reset' - }); - if (Environment_default.WEB_PORT === 80) { - console.log(kleur_default.green().bold('World ready') + kleur_default.white().bold(': http://' + Environment_default.PUBLIC_IP)); - } else { - console.log(kleur_default.green().bold('World ready') + kleur_default.white().bold(': http://' + Environment_default.PUBLIC_IP + ':' + Environment_default.WEB_PORT)); - } - if (startCycle) { - await this.cycle(); - } - } - rebootTimer(duration) { - this.shutdownTick = this.currentTick + duration; - for (const player of this.players) { - player.write(new UpdateRebootTimer(this.shutdownTick - this.currentTick)); - } - } - async cycle(continueCycle = true) { - const start = Date.now(); - let worldProcessing = Date.now(); - for (let request = this.queue.head(); request !== null; request = this.queue.next()) { - const delay = request.delay--; - if (delay > 0) { - continue; - } - const script = request.script; - try { - const state = ScriptRunner2.execute(script); - request.unlink(); - if (state === ScriptState.SUSPENDED) { - script.activePlayer.activeScript = script; - } else if (state === ScriptState.NPC_SUSPENDED) { - script.activeNpc.activeScript = script; - } else if (state === ScriptState.WORLD_SUSPENDED) { - this.enqueueScript(script, script.popInt()); - } - } catch (err) { - console.error(err); - } - } - if (this.currentTick % 500 === 0) { - for (const player of this.players) { - player.afkEventReady = Math.random() < (player.zonesAfk() ? 0.1666 : 0.0833); - } - } - for (const npc of this.npcs) { - if (!npc.updateLifeCycle(this.currentTick)) { - continue; - } - if (npc.lifecycle === EntityLifeCycle_default.RESPAWN) { - this.addNpc(npc, -1); - } else if (npc.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.removeNpc(npc, -1); - } - } - for (const npc of this.npcs) { - if (!npc.checkLifeCycle(this.currentTick) || npc.delayed()) { - continue; - } - if (npc.huntMode !== -1) { - npc.huntAll(); - } - } - worldProcessing = Date.now() - worldProcessing; - this.lastCycleBandwidth[0] = 0; - let clientInput = Date.now(); - for (const player of this.players) { - if (!isNetworkPlayer(player)) { - continue; - } - try { - player.decodeIn(); - } catch (err) { - console.error(err); - await this.removePlayer(player); - } - } - clientInput = Date.now() - clientInput; - for (const player of this.players) { - if (!isNetworkPlayer(player)) { - continue; - } - if (player.userPath.length > 0 || player.opcalled) { - if (player.delayed()) { - player.unsetMapFlag(); - continue; - } - if ((!player.target || player.target instanceof Loc || player.target instanceof Obj) && player.faceEntity !== -1) { - player.faceEntity = -1; - player.mask |= Player2.FACE_ENTITY; - } - if (player.opcalled && (player.userPath.length === 0 || !Environment_default.CLIENT_PATHFINDER)) { - player.pathToTarget(); - continue; - } - player.pathToMoveClick(player.userPath, !Environment_default.CLIENT_PATHFINDER); - } - if (player.target instanceof Player2 && (player.targetOp === ServerTriggerType_default.APPLAYER3 || player.targetOp === ServerTriggerType_default.OPPLAYER3)) { - if (Position.distanceToSW(player, player.target) <= 25) { - player.pathToPathingTarget(); - } else { - player.clearWaypoints(); - } - } - } - let npcProcessing = Date.now(); - for (const npc of this.npcs) { - if (!npc.checkLifeCycle(this.currentTick)) { - continue; - } - try { - if (npc.delayed()) { - npc.delay--; - } - if (npc.delayed()) { - continue; - } - if (npc.activeScript) { - npc.executeScript(npc.activeScript); - } - if (!npc.checkLifeCycle(this.currentTick)) { - continue; - } - npc.processTimers(); - npc.processQueue(); - npc.processNpcModes(); - npc.validateDistanceWalked(); - } catch (err) { - console.error(err); - this.removeNpc(npc, -1); - } - } - npcProcessing = Date.now() - npcProcessing; - let playerProcessing = Date.now(); - for (const player of this.players) { - try { - player.playtime++; - if (player.delayed()) { - player.delay--; - } - if (player.activeScript && !player.delayed() && player.activeScript.execution === ScriptState.SUSPENDED) { - player.executeScript(player.activeScript, true); - } - player.processQueues(); - player.processTimers(0 /* NORMAL */); - player.processTimers(1 /* SOFT */); - player.processEngineQueue(); - player.processInteraction(); - if ((player.mask & Player2.EXACT_MOVE) == 0) { - player.validateDistanceWalked(); - } - if (this.shutdownTick < this.currentTick) { - if (!Environment_default.NO_SOCKET_TIMEOUT && this.currentTick - player.lastResponse >= 75) { - player.logoutRequested = true; - } - } - if (player.logoutRequested) { - player.closeModal(); - } - } catch (err) { - console.error(err); - await this.removePlayer(player); - } - } - playerProcessing = Date.now() - playerProcessing; - let playerLogout = Date.now(); - for (const player of this.players) { - if (!Environment_default.NO_SOCKET_TIMEOUT && this.currentTick - player.lastResponse >= 100) { - player.queue.clear(); - player.weakQueue.clear(); - player.engineQueue.clear(); - player.clearInteraction(); - player.closeModal(); - player.unsetMapFlag(); - player.logoutRequested = true; - player.setVar(VarPlayerType.LASTCOMBAT, 0); - } - if (!player.logoutRequested) { - continue; - } - if (player.queue.head() === null) { - const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.LOGOUT, -1, -1); - if (!script) { - console.error('LOGOUT TRIGGER IS BROKEN!'); - continue; - } - const state = ScriptRunner2.init(script, player); - state.pointerAdd(ScriptPointer_default.ProtectedActivePlayer); - ScriptRunner2.execute(state); - const result = state.popInt(); - if (result === 0) { - player.logoutRequested = false; - } - if (player.logoutRequested) { - await this.removePlayer(player); - } - } else { - player.messageGame('[DEBUG]: Waiting for queue to empty before logging out.'); - } - } - playerLogout = Date.now() - playerLogout; - let playerLogin = Date.now(); - for (let i = 0; i < this.newPlayers.length; i++) { - const player = this.newPlayers[i]; - this.newPlayers.splice(i--, 1); - let pid; - try { - pid = this.getNextPid(isNetworkPlayer(player) ? player.client : null); - } catch (e) { - if (player instanceof NetworkPlayer2 && player.client) { - player.client.send(LoginResponse.WORLD_FULL); - player.client.close(); - } - continue; - } - this.players.set(pid, player); - player.pid = pid; - player.uid = ((Number(player.username37 & 0x1fffffn) << 11) | player.pid) >>> 0; - player.tele = true; - this.getZone(player.x, player.z, player.level).enter(player); - if (!Environment_default.CLIRUNNER) { - player.onLogin(); - } - if (this.shutdownTick > -1) { - player.write(new UpdateRebootTimer(this.shutdownTick - this.currentTick)); - } - if (player instanceof NetworkPlayer2 && player.client) { - player.client.state = 1; - if (player.staffModLevel >= 2) { - player.client.send(LoginResponse.STAFF_MOD_LEVEL); - } else { - player.client.send(LoginResponse.SUCCESSFUL); - } - } - } - playerLogin = Date.now() - playerLogin; - let zoneProcessing = Date.now(); - for (const zone of Array.from(this.zonesTracking.get(this.currentTick) ?? [])) { - zone.tick(this.currentTick); - } - this.computeSharedEvents(); - zoneProcessing = Date.now() - zoneProcessing; - for (const player of this.players) { - player.convertMovementDir(); - } - for (const npc of this.npcs) { - npc.convertMovementDir(); - } - this.lastCycleBandwidth[1] = 0; - let clientOutput = Date.now(); - for (const player of this.players) { - if (!isNetworkPlayer(player)) { - continue; - } - try { - player.updateMap(); - player.updatePlayers(); - player.updateNpcs(); - player.updateZones(); - player.updateInvs(); - player.updateStats(); - player.updateAfkZones(); - player.encodeOut(); - } catch (err) { - console.error(err); - await this.removePlayer(player); - } - } - clientOutput = Date.now() - clientOutput; - let cleanup = Date.now(); - for (const zone of Array.from(this.zonesTracking.get(this.currentTick) ?? [])) { - zone.reset(); - } - this.zonesTracking.delete(this.currentTick); - for (const player of this.players) { - player.resetEntity(false); - for (const inv of player.invs.values()) { - if (!inv) { - continue; - } - inv.update = false; - } - } - for (const npc of this.npcs) { - if (!npc.checkLifeCycle(this.currentTick)) { - continue; - } - npc.resetEntity(false); - } - for (let i = 0; i < this.invs.length; i++) { - const inv = this.invs[i]; - if (!inv) { - continue; - } - inv.update = false; - const invType = InvType.get(inv.type); - if (!invType.restock || !invType.stockcount || !invType.stockrate) { - continue; - } - for (let index = 0; index < inv.items.length; index++) { - const item = inv.items[index]; - if (!item) { - continue; - } - if (item.count < invType.stockcount[index] && this.currentTick % invType.stockrate[index] === 0) { - inv.add(item?.id, 1, index, true, false, false); - inv.update = true; - continue; - } - if (item.count > invType.stockcount[index] && this.currentTick % invType.stockrate[index] === 0) { - inv.remove(item?.id, 1, index, true); - inv.update = true; - continue; - } - if (invType.allstock && !invType.stockcount[index] && this.currentTick % 100 === 0) { - inv.remove(item?.id, 1, index, true); - inv.update = true; - } - } - } - cleanup = Date.now() - cleanup; - if (this.currentTick % 100 === 0) { - const players = []; - for (const player of this.players) { - players.push(player.username37); - } - Login_default.loginThread.postMessage({ - type: 'heartbeat', - players - }); - } - if (this.shutdownTick > -1 && this.currentTick >= this.shutdownTick) { - const duration = this.currentTick - this.shutdownTick; - const online = this.getTotalPlayers(); - if (online) { - for (const player of this.players) { - player.logoutRequested = true; - if (isNetworkPlayer(player)) { - player.logout(); - if (player.client && duration > 2) { - player.client.close(); - } - } - } - this.npcs.reset(); - if (duration > 2) { - if (this.tickRate > 1) { - this.tickRate = 1; - } - if (duration > 24000) { - for (const player of this.players) { - await this.removePlayer(player); - } - this.tickRate = 600; - } - } - } else { - process.exit(0); - } - } - if (this.currentTick % 1500 === 0 && this.currentTick > 0) { - } - const end = Date.now(); - this.currentTick++; - this.lastCycleStats = [end - start, worldProcessing, clientInput, npcProcessing, playerProcessing, playerLogout, playerLogin, zoneProcessing, clientOutput, cleanup]; - if (continueCycle) { - const nextTick = this.tickRate - (end - start); - setTimeout(this.cycle.bind(this), nextTick); - } - } - enqueueScript(script, delay = 0) { - this.queue.addTail(new EntityQueueState(script, delay + 1)); - } - getInventory(inv) { - if (inv === -1) { - return null; - } - let container = this.invs.find(x => x && x.type == inv); - if (!container) { - container = Inventory.fromType(inv); - this.invs.push(container); - } - return container; - } - getZone(x, z2, level) { - return this.zoneMap.zone(x, z2, level); - } - getZoneIndex(zoneIndex) { - return this.zoneMap.zoneByIndex(zoneIndex); - } - getZoneGrid(level) { - return this.zoneMap.grid(level); - } - computeSharedEvents() { - const zones = new Set(); - for (const player of this.players) { - if (!isNetworkPlayer(player)) { - continue; - } - for (const zone of player.buildArea.loadedZones) { - zones.add(zone); - } - } - for (const zoneIndex of zones) { - this.getZoneIndex(zoneIndex).computeShared(); - } - } - addNpc(npc, duration) { - this.npcs.set(npc.nid, npc); - npc.x = npc.startX; - npc.z = npc.startZ; - const zone = this.getZone(npc.x, npc.z, npc.level); - zone.enter(npc); - switch (npc.blockWalk) { - case BlockWalk_default.NPC: - this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, true); - break; - case BlockWalk_default.ALL: - this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, true); - this.gameMap.changePlayerCollision(npc.width, npc.x, npc.z, npc.level, true); - break; - } - npc.resetEntity(true); - npc.playAnimation(-1, 0); - npc.setLifeCycle(this.currentTick + duration); - } - removeNpc(npc, duration) { - const zone = this.getZone(npc.x, npc.z, npc.level); - zone.leave(npc); - switch (npc.blockWalk) { - case BlockWalk_default.NPC: - this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, false); - break; - case BlockWalk_default.ALL: - this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, false); - this.gameMap.changePlayerCollision(npc.width, npc.x, npc.z, npc.level, false); - break; - } - if (npc.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.npcs.remove(npc.nid); - } else if (npc.lifecycle === EntityLifeCycle_default.RESPAWN) { - npc.setLifeCycle(this.currentTick + duration); - } - } - getLoc(x, z2, level, locId) { - return this.getZone(x, z2, level).getLoc(x, z2, locId); - } - getObj(x, z2, level, objId, receiverId) { - return this.getZone(x, z2, level).getObj(x, z2, objId, receiverId); - } - trackZone(tick, zone) { - let zones; - const active = this.zonesTracking.get(tick); - if (!active) { - zones = new Set(); - } else { - zones = active; - } - zones.add(zone); - this.zonesTracking.set(tick, zones); - } - addLoc(loc, duration) { - const type = LocType.get(loc.type); - if (type.blockwalk) { - this.gameMap.changeLocCollision(loc.shape, loc.angle, type.blockrange, type.length, type.width, type.active, loc.x, loc.z, loc.level, true); - } - const zone = this.getZone(loc.x, loc.z, loc.level); - zone.addLoc(loc); - loc.setLifeCycle(this.currentTick + duration); - this.trackZone(this.currentTick + duration, zone); - this.trackZone(this.currentTick, zone); - } - mergeLoc(loc, player, startCycle, endCycle, south, east, north, west) { - const zone = this.getZone(loc.x, loc.z, loc.level); - zone.mergeLoc(loc, player, startCycle, endCycle, south, east, north, west); - this.trackZone(this.currentTick, zone); - } - animLoc(loc, seq) { - const zone = this.getZone(loc.x, loc.z, loc.level); - zone.animLoc(loc, seq); - this.trackZone(this.currentTick, zone); - } - removeLoc(loc, duration) { - const type = LocType.get(loc.type); - if (type.blockwalk) { - this.gameMap.changeLocCollision(loc.shape, loc.angle, type.blockrange, type.length, type.width, type.active, loc.x, loc.z, loc.level, false); - } - const zone = this.getZone(loc.x, loc.z, loc.level); - zone.removeLoc(loc); - loc.setLifeCycle(this.currentTick + duration); - this.trackZone(this.currentTick + duration, zone); - this.trackZone(this.currentTick, zone); - } - addObj(obj, receiverId, duration) { - const objType = ObjType.get(obj.type); - const existing = this.getObj(obj.x, obj.z, obj.level, obj.type, receiverId); - if (existing && existing.lifecycle === EntityLifeCycle_default.DESPAWN && obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - const nextCount = obj.count + existing.count; - if (objType.stackable && nextCount <= Inventory.STACK_LIMIT) { - this.changeObj(existing, receiverId, nextCount); - return; - } - } - const zone = this.getZone(obj.x, obj.z, obj.level); - zone.addObj(obj, receiverId); - if (receiverId !== -1 && objType.tradeable) { - obj.setLifeCycle(this.currentTick + 100); - this.trackZone(this.currentTick + 100, zone); - this.trackZone(this.currentTick, zone); - obj.receiverId = receiverId; - obj.reveal = duration; - } else { - obj.setLifeCycle(this.currentTick + duration); - this.trackZone(this.currentTick + duration, zone); - this.trackZone(this.currentTick, zone); - } - } - revealObj(obj) { - const duration = obj.reveal; - const zone = this.getZone(obj.x, obj.z, obj.level); - zone.revealObj(obj, obj.receiverId); - obj.setLifeCycle(this.currentTick + duration); - this.trackZone(this.currentTick + duration, zone); - this.trackZone(this.currentTick, zone); - } - changeObj(obj, receiverId, newCount) { - const zone = this.getZone(obj.x, obj.z, obj.level); - zone.changeObj(obj, receiverId, obj.count, newCount); - this.trackZone(this.currentTick, zone); - } - removeObj(obj, duration) { - const zone = this.getZone(obj.x, obj.z, obj.level); - zone.removeObj(obj); - obj.setLifeCycle(this.currentTick + duration); - this.trackZone(this.currentTick + duration, zone); - this.trackZone(this.currentTick, zone); - } - animMap(level, x, z2, spotanim, height, delay) { - const zone = this.getZone(x, z2, level); - zone.animMap(x, z2, spotanim, height, delay); - this.trackZone(this.currentTick, zone); - } - mapProjAnim(level, x, z2, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) { - const zone = this.getZone(x, z2, level); - zone.mapProjAnim(x, z2, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc); - this.trackZone(this.currentTick, zone); - } - async readIn(socket, stream) { - while (stream.available > 0) { - const start = stream.pos; - let opcode = stream.g1(); - if (socket.decryptor) { - opcode = (opcode - socket.decryptor.nextInt()) & 255; - stream.data[start] = opcode; - } - if (typeof ClientProt.byId[opcode] === 'undefined') { - socket.state = -1; - socket.close(); - return; - } - let length = ClientProt.byId[opcode].length; - if (length === -1) { - length = stream.g1(); - } else if (length === -2) { - length = stream.g2(); - } - if (stream.available < length) { - break; - } - stream.pos += length; - socket.inCount[opcode]++; - if (socket.inCount[opcode] > 5) { - continue; - } - const data = new Uint8Array(stream.pos - start); - const pos = stream.pos; - stream.pos = start; - stream.gdata(data, 0, data.length); - stream.pos = pos; - socket.in.set(data, socket.inOffset); - socket.inOffset += stream.pos - start; - } - } - addPlayer(player) { - this.newPlayers.push(player); - } - async removePlayer(player) { - if (player.pid === -1) { - return; - } - player.playerLog('Logging out'); - if (isNetworkPlayer(player)) { - player.logout(); - player.client.close(); - player.client = null; - } - Login_default.logout(player); - } - getPlayer(pid) { - return this.players.get(pid); - } - getPlayerByUid(uid) { - const pid = uid & 2047; - const name37 = (uid >> 11) & 2097151; - const player = this.getPlayer(pid); - if (!player) { - return null; - } - if (Number(player.username37 & 0x1fffffn) !== name37) { - return null; - } - return player; - } - getPlayerByUsername(username) { - const username37 = toBase37(username); - for (const player of this.players) { - if (player.username37 === username37) { - return player; - } - } - for (const player of this.newPlayers) { - if (player.username37 === username37) { - return player; - } - } - return; - } - getTotalPlayers() { - return this.players.count; - } - getTotalNpcs() { - return this.npcs.count; - } - getNpc(nid) { - return this.npcs.get(nid); - } - getNpcByUid(uid) { - const slot = uid & 65535; - const type = (uid >> 16) & 65535; - const npc = this.getNpc(slot); - if (!npc || npc.type !== type) { - return null; - } - return npc; - } - getNextNid() { - return this.npcs.next(); - } - getNextPid(client = null) { - if (client) { - const ip = client.remoteAddress; - const octets = ip.split('.'); - const start = (parseInt(octets[3]) % 20) * 100; - return this.players.next(true, start); - } - return this.players.next(); - } -} -var World_default = new World35(); - -// src/lostcity/server/WorkerServer.ts -class WorkerServer { - socket = new ClientSocket(); - constructor() {} - start() { - const seed = new Packet(new Uint8Array(4 + 4)); - seed.p4(Math.floor(Math.random() * 4294967295)); - seed.p4(Math.floor(Math.random() * 4294967295)); - this.socket.send(seed.data); - self.onmessage = async e => { - const packet = new Packet(new Uint8Array(e.data)); - switch (e.type) { - case 'message': - try { - if (this.socket.state === 1) { - await World_default.readIn(this.socket, packet); - } else { - await Login_default.readIn(this.socket, packet); - } - } catch (err) { - this.socket.close(); - } - break; - default: - console.log('default', e.type); - break; - } - }; - } -} - -// src/lostcity/app.ts -await World_default.start(); -var workerServer = new WorkerServer(); -workerServer.start(); diff --git a/src/public/favicon.ico b/src/public/favicon.ico new file mode 100644 index 00000000..a42ac98e Binary files /dev/null and b/src/public/favicon.ico differ diff --git a/src/public/rsmod-pathfinder.wasm b/src/public/rsmod-pathfinder.wasm new file mode 100644 index 00000000..35878f33 Binary files /dev/null and b/src/public/rsmod-pathfinder.wasm differ diff --git a/src/public/worker.js b/src/public/worker.js new file mode 100644 index 00000000..db89bb39 --- /dev/null +++ b/src/public/worker.js @@ -0,0 +1,66347 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getProtoOf = Object.getPrototypeOf; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __toESM = (mod, isNodeMode, target) => { + target = mod != null ? __create(__getProtoOf(mod)) : {}; + const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, 'default', {value: mod, enumerable: true}) : target; + for (let key of __getOwnPropNames(mod)) + if (!__hasOwnProp.call(to, key)) + __defProp(to, key, { + get: () => mod[key], + enumerable: true + }); + return to; +}; +var __toCommonJS = from => { + const moduleCache = (__toCommonJS.moduleCache ??= new WeakMap()); + var cached = moduleCache.get(from); + if (cached) return cached; + var to = __defProp({}, '__esModule', {value: true}); + var desc = {enumerable: false}; + if ((from && typeof from === 'object') || typeof from === 'function') { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key)) + __defProp(to, key, { + get: () => from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + moduleCache.set(from, to); + return to; +}; +var __commonJS = (cb, mod) => () => (mod || cb((mod = {exports: {}}).exports, mod), mod.exports); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { + get: all[name], + enumerable: true, + configurable: true, + set: newValue => (all[name] = () => newValue) + }); +}; +var __esm = (fn, res) => () => (fn && (res = fn((fn = 0))), res); +var __require = (x => + typeof require !== 'undefined' + ? require + : typeof Proxy !== 'undefined' + ? new Proxy(x, { + get: (a, b) => (typeof require !== 'undefined' ? require : a)[b] + }) + : x)(function (x) { + if (typeof require !== 'undefined') return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); + +// node:path +var exports_path = {}; +__export(exports_path, { + default: () => q +}); +var L, b, z, D, T, R, _, E, C, A, y, h, m, q; +var init_path = __esm(() => { + L = Object.create; + b = Object.defineProperty; + z = Object.getOwnPropertyDescriptor; + D = Object.getOwnPropertyNames; + T = Object.getPrototypeOf; + R = Object.prototype.hasOwnProperty; + _ = (f, e) => () => (e || f((e = {exports: {}}).exports, e), e.exports); + E = (f, e) => { + for (var r in e) b(f, r, {get: e[r], enumerable: true}); + }; + C = (f, e, r, l) => { + if ((e && typeof e == 'object') || typeof e == 'function') for (let i of D(e)) !R.call(f, i) && i !== r && b(f, i, {get: () => e[i], enumerable: !(l = z(e, i)) || l.enumerable}); + return f; + }; + A = (f, e, r) => (C(f, e, 'default'), r && C(r, e, 'default')); + y = (f, e, r) => ((r = f != null ? L(T(f)) : {}), C(e || !f || !f.__esModule ? b(r, 'default', {value: f, enumerable: true}) : r, f)); + h = _((F, S) => { + function c(f) { + if (typeof f != 'string') throw new TypeError('Path must be a string. Received ' + JSON.stringify(f)); + } + function w(f, e) { + for (var r = '', l = 0, i = -1, s = 0, n, t = 0; t <= f.length; ++t) { + if (t < f.length) n = f.charCodeAt(t); + else { + if (n === 47) break; + n = 47; + } + if (n === 47) { + if (!(i === t - 1 || s === 1)) + if (i !== t - 1 && s === 2) { + if (r.length < 2 || l !== 2 || r.charCodeAt(r.length - 1) !== 46 || r.charCodeAt(r.length - 2) !== 46) { + if (r.length > 2) { + var a = r.lastIndexOf('/'); + if (a !== r.length - 1) { + a === -1 ? ((r = ''), (l = 0)) : ((r = r.slice(0, a)), (l = r.length - 1 - r.lastIndexOf('/'))), (i = t), (s = 0); + continue; + } + } else if (r.length === 2 || r.length === 1) { + (r = ''), (l = 0), (i = t), (s = 0); + continue; + } + } + e && (r.length > 0 ? (r += '/..') : (r = '..'), (l = 2)); + } else r.length > 0 ? (r += '/' + f.slice(i + 1, t)) : (r = f.slice(i + 1, t)), (l = t - i - 1); + (i = t), (s = 0); + } else n === 46 && s !== -1 ? ++s : (s = -1); + } + return r; + } + function J(f, e) { + var r = e.dir || e.root, + l = e.base || (e.name || '') + (e.ext || ''); + return r ? (r === e.root ? r + l : r + f + l) : l; + } + var g = { + resolve: function () { + for (var e = '', r = false, l, i = arguments.length - 1; i >= -1 && !r; i--) { + var s; + i >= 0 ? (s = arguments[i]) : (l === undefined && (l = process.cwd()), (s = l)), c(s), s.length !== 0 && ((e = s + '/' + e), (r = s.charCodeAt(0) === 47)); + } + return (e = w(e, !r)), r ? (e.length > 0 ? '/' + e : '/') : e.length > 0 ? e : '.'; + }, + normalize: function (e) { + if ((c(e), e.length === 0)) return '.'; + var r = e.charCodeAt(0) === 47, + l = e.charCodeAt(e.length - 1) === 47; + return (e = w(e, !r)), e.length === 0 && !r && (e = '.'), e.length > 0 && l && (e += '/'), r ? '/' + e : e; + }, + isAbsolute: function (e) { + return c(e), e.length > 0 && e.charCodeAt(0) === 47; + }, + join: function () { + if (arguments.length === 0) return '.'; + for (var e, r = 0; r < arguments.length; ++r) { + var l = arguments[r]; + c(l), l.length > 0 && (e === undefined ? (e = l) : (e += '/' + l)); + } + return e === undefined ? '.' : g.normalize(e); + }, + relative: function (e, r) { + if ((c(e), c(r), e === r || ((e = g.resolve(e)), (r = g.resolve(r)), e === r))) return ''; + for (var l = 1; l < e.length && e.charCodeAt(l) === 47; ++l); + for (var i = e.length, s = i - l, n = 1; n < r.length && r.charCodeAt(n) === 47; ++n); + for (var t = r.length, a = t - n, v = s < a ? s : a, u = -1, o = 0; o <= v; ++o) { + if (o === v) { + if (a > v) { + if (r.charCodeAt(n + o) === 47) return r.slice(n + o + 1); + if (o === 0) return r.slice(n + o); + } else s > v && (e.charCodeAt(l + o) === 47 ? (u = o) : o === 0 && (u = 0)); + break; + } + var k = e.charCodeAt(l + o), + P = r.charCodeAt(n + o); + if (k !== P) break; + k === 47 && (u = o); + } + var d = ''; + for (o = l + u + 1; o <= i; ++o) (o === i || e.charCodeAt(o) === 47) && (d.length === 0 ? (d += '..') : (d += '/..')); + return d.length > 0 ? d + r.slice(n + u) : ((n += u), r.charCodeAt(n) === 47 && ++n, r.slice(n)); + }, + _makeLong: function (e) { + return e; + }, + dirname: function (e) { + if ((c(e), e.length === 0)) return '.'; + for (var r = e.charCodeAt(0), l = r === 47, i = -1, s = true, n = e.length - 1; n >= 1; --n) + if (((r = e.charCodeAt(n)), r === 47)) { + if (!s) { + i = n; + break; + } + } else s = false; + return i === -1 ? (l ? '/' : '.') : l && i === 1 ? '//' : e.slice(0, i); + }, + basename: function (e, r) { + if (r !== undefined && typeof r != 'string') throw new TypeError('"ext" argument must be a string'); + c(e); + var l = 0, + i = -1, + s = true, + n; + if (r !== undefined && r.length > 0 && r.length <= e.length) { + if (r.length === e.length && r === e) return ''; + var t = r.length - 1, + a = -1; + for (n = e.length - 1; n >= 0; --n) { + var v = e.charCodeAt(n); + if (v === 47) { + if (!s) { + l = n + 1; + break; + } + } else a === -1 && ((s = false), (a = n + 1)), t >= 0 && (v === r.charCodeAt(t) ? --t === -1 && (i = n) : ((t = -1), (i = a))); + } + return l === i ? (i = a) : i === -1 && (i = e.length), e.slice(l, i); + } else { + for (n = e.length - 1; n >= 0; --n) + if (e.charCodeAt(n) === 47) { + if (!s) { + l = n + 1; + break; + } + } else i === -1 && ((s = false), (i = n + 1)); + return i === -1 ? '' : e.slice(l, i); + } + }, + extname: function (e) { + c(e); + for (var r = -1, l = 0, i = -1, s = true, n = 0, t = e.length - 1; t >= 0; --t) { + var a = e.charCodeAt(t); + if (a === 47) { + if (!s) { + l = t + 1; + break; + } + continue; + } + i === -1 && ((s = false), (i = t + 1)), a === 46 ? (r === -1 ? (r = t) : n !== 1 && (n = 1)) : r !== -1 && (n = -1); + } + return r === -1 || i === -1 || n === 0 || (n === 1 && r === i - 1 && r === l + 1) ? '' : e.slice(r, i); + }, + format: function (e) { + if (e === null || typeof e != 'object') throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof e); + return J('/', e); + }, + parse: function (e) { + c(e); + var r = {root: '', dir: '', base: '', ext: '', name: ''}; + if (e.length === 0) return r; + var l = e.charCodeAt(0), + i = l === 47, + s; + i ? ((r.root = '/'), (s = 1)) : (s = 0); + for (var n = -1, t = 0, a = -1, v = true, u = e.length - 1, o = 0; u >= s; --u) { + if (((l = e.charCodeAt(u)), l === 47)) { + if (!v) { + t = u + 1; + break; + } + continue; + } + a === -1 && ((v = false), (a = u + 1)), l === 46 ? (n === -1 ? (n = u) : o !== 1 && (o = 1)) : n !== -1 && (o = -1); + } + return ( + n === -1 || a === -1 || o === 0 || (o === 1 && n === a - 1 && n === t + 1) + ? a !== -1 && (t === 0 && i ? (r.base = r.name = e.slice(1, a)) : (r.base = r.name = e.slice(t, a))) + : (t === 0 && i ? ((r.name = e.slice(1, n)), (r.base = e.slice(1, a))) : ((r.name = e.slice(t, n)), (r.base = e.slice(t, a))), (r.ext = e.slice(n, a))), + t > 0 ? (r.dir = e.slice(0, t - 1)) : i && (r.dir = '/'), + r + ); + }, + sep: '/', + delimiter: ':', + win32: null, + posix: null + }; + g.posix = g; + S.exports = g; + }); + m = {}; + E(m, {default: () => q}); + A(m, y(h())); + q = y(h()); +}); + +// node_modules/node-forge/lib/forge.js +var require_forge = __commonJS((exports, module) => { + module.exports = { + options: { + usePureJavaScript: false + } + }; +}); + +// node_modules/node-forge/lib/baseN.js +var require_baseN = __commonJS((exports, module) => { + var _encodeWithByteBuffer = function (input, alphabet) { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for (i = 0; i < input.length(); ++i) { + for (var j = 0, carry = input.at(i); j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + while (carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + var output = ''; + for (i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { + output += first; + } + for (i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + return output; + }; + var api = {}; + module.exports = api; + var _reverseAlphabets = {}; + api.encode = function (input, alphabet, maxline) { + if (typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + if (maxline !== undefined && typeof maxline !== 'number') { + throw new TypeError('"maxline" must be a number.'); + } + var output = ''; + if (!(input instanceof Uint8Array)) { + output = _encodeWithByteBuffer(input, alphabet); + } else { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for (i = 0; i < input.length; ++i) { + for (var j = 0, carry = input[i]; j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + while (carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + for (i = 0; input[i] === 0 && i < input.length - 1; ++i) { + output += first; + } + for (i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + } + if (maxline) { + var regex = new RegExp('.{1,' + maxline + '}', 'g'); + output = output.match(regex).join('\r\n'); + } + return output; + }; + api.decode = function (input, alphabet) { + if (typeof input !== 'string') { + throw new TypeError('"input" must be a string.'); + } + if (typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + var table = _reverseAlphabets[alphabet]; + if (!table) { + table = _reverseAlphabets[alphabet] = []; + for (var i = 0; i < alphabet.length; ++i) { + table[alphabet.charCodeAt(i)] = i; + } + } + input = input.replace(/\s/g, ''); + var base = alphabet.length; + var first = alphabet.charAt(0); + var bytes = [0]; + for (var i = 0; i < input.length; i++) { + var value = table[input.charCodeAt(i)]; + if (value === undefined) { + return; + } + for (var j = 0, carry = value; j < bytes.length; ++j) { + carry += bytes[j] * base; + bytes[j] = carry & 255; + carry >>= 8; + } + while (carry > 0) { + bytes.push(carry & 255); + carry >>= 8; + } + } + for (var k = 0; input[k] === first && k < input.length - 1; ++k) { + bytes.push(0); + } + if (typeof Buffer !== 'undefined') { + return Buffer.from(bytes.reverse()); + } + return new Uint8Array(bytes.reverse()); + }; +}); + +// node_modules/node-forge/lib/util.js +var require_util = __commonJS((exports, module) => { + var _checkBitsParam = function (n) { + if (!(n === 8 || n === 16 || n === 24 || n === 32)) { + throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); + } + }; + var ByteStringBuffer = function (b2) { + this.data = ''; + this.read = 0; + if (typeof b2 === 'string') { + this.data = b2; + } else if (util.isArrayBuffer(b2) || util.isArrayBufferView(b2)) { + if (typeof Buffer !== 'undefined' && b2 instanceof Buffer) { + this.data = b2.toString('binary'); + } else { + var arr = new Uint8Array(b2); + try { + this.data = String.fromCharCode.apply(null, arr); + } catch (e) { + for (var i = 0; i < arr.length; ++i) { + this.putByte(arr[i]); + } + } + } + } else if (b2 instanceof ByteStringBuffer || (typeof b2 === 'object' && typeof b2.data === 'string' && typeof b2.read === 'number')) { + this.data = b2.data; + this.read = b2.read; + } + this._constructedStringLength = 0; + }; + var DataBuffer = function (b2, options) { + options = options || {}; + this.read = options.readOffset || 0; + this.growSize = options.growSize || 1024; + var isArrayBuffer = util.isArrayBuffer(b2); + var isArrayBufferView = util.isArrayBufferView(b2); + if (isArrayBuffer || isArrayBufferView) { + if (isArrayBuffer) { + this.data = new DataView(b2); + } else { + this.data = new DataView(b2.buffer, b2.byteOffset, b2.byteLength); + } + this.write = 'writeOffset' in options ? options.writeOffset : this.data.byteLength; + return; + } + this.data = new DataView(new ArrayBuffer(0)); + this.write = 0; + if (b2 !== null && b2 !== undefined) { + this.putBytes(b2); + } + if ('writeOffset' in options) { + this.write = options.writeOffset; + } + }; + var forge = require_forge(); + var baseN = require_baseN(); + var util = (module.exports = forge.util = forge.util || {}); + (function () { + if (typeof process !== 'undefined' && process.nextTick && false) { + } + if (typeof setImmediate === 'function') { + util.setImmediate = function () { + return setImmediate.apply(undefined, arguments); + }; + util.nextTick = function (callback) { + return setImmediate(callback); + }; + return; + } + util.setImmediate = function (callback) { + setTimeout(callback, 0); + }; + if (typeof window !== 'undefined' && typeof window.postMessage === 'function') { + let handler2 = function (event) { + if (event.source === window && event.data === msg) { + event.stopPropagation(); + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function (callback) { + callback(); + }); + } + }; + var handler = handler2; + var msg = 'forge.setImmediate'; + var callbacks = []; + util.setImmediate = function (callback) { + callbacks.push(callback); + if (callbacks.length === 1) { + window.postMessage(msg, '*'); + } + }; + window.addEventListener('message', handler2, true); + } + if (typeof MutationObserver !== 'undefined') { + var now = Date.now(); + var attr = true; + var div = document.createElement('div'); + var callbacks = []; + new MutationObserver(function () { + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function (callback) { + callback(); + }); + }).observe(div, {attributes: true}); + var oldSetImmediate = util.setImmediate; + util.setImmediate = function (callback) { + if (Date.now() - now > 15) { + now = Date.now(); + oldSetImmediate(callback); + } else { + callbacks.push(callback); + if (callbacks.length === 1) { + div.setAttribute('a', (attr = !attr)); + } + } + }; + } + util.nextTick = util.setImmediate; + })(); + util.isNodejs = typeof process !== 'undefined' && process.versions && process.versions.node; + util.globalScope = (function () { + if (util.isNodejs) { + return global; + } + return typeof self === 'undefined' ? window : self; + })(); + util.isArray = + Array.isArray || + function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + util.isArrayBuffer = function (x) { + return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; + }; + util.isArrayBufferView = function (x) { + return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined; + }; + util.ByteBuffer = ByteStringBuffer; + util.ByteStringBuffer = ByteStringBuffer; + var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; + util.ByteStringBuffer.prototype._optimizeConstructedString = function (x) { + this._constructedStringLength += x; + if (this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { + this.data.substr(0, 1); + this._constructedStringLength = 0; + } + }; + util.ByteStringBuffer.prototype.length = function () { + return this.data.length - this.read; + }; + util.ByteStringBuffer.prototype.isEmpty = function () { + return this.length() <= 0; + }; + util.ByteStringBuffer.prototype.putByte = function (b2) { + return this.putBytes(String.fromCharCode(b2)); + }; + util.ByteStringBuffer.prototype.fillWithByte = function (b2, n) { + b2 = String.fromCharCode(b2); + var d = this.data; + while (n > 0) { + if (n & 1) { + d += b2; + } + n >>>= 1; + if (n > 0) { + b2 += b2; + } + } + this.data = d; + this._optimizeConstructedString(n); + return this; + }; + util.ByteStringBuffer.prototype.putBytes = function (bytes) { + this.data += bytes; + this._optimizeConstructedString(bytes.length); + return this; + }; + util.ByteStringBuffer.prototype.putString = function (str) { + return this.putBytes(util.encodeUtf8(str)); + }; + util.ByteStringBuffer.prototype.putInt16 = function (i) { + return this.putBytes(String.fromCharCode((i >> 8) & 255) + String.fromCharCode(i & 255)); + }; + util.ByteStringBuffer.prototype.putInt24 = function (i) { + return this.putBytes(String.fromCharCode((i >> 16) & 255) + String.fromCharCode((i >> 8) & 255) + String.fromCharCode(i & 255)); + }; + util.ByteStringBuffer.prototype.putInt32 = function (i) { + return this.putBytes(String.fromCharCode((i >> 24) & 255) + String.fromCharCode((i >> 16) & 255) + String.fromCharCode((i >> 8) & 255) + String.fromCharCode(i & 255)); + }; + util.ByteStringBuffer.prototype.putInt16Le = function (i) { + return this.putBytes(String.fromCharCode(i & 255) + String.fromCharCode((i >> 8) & 255)); + }; + util.ByteStringBuffer.prototype.putInt24Le = function (i) { + return this.putBytes(String.fromCharCode(i & 255) + String.fromCharCode((i >> 8) & 255) + String.fromCharCode((i >> 16) & 255)); + }; + util.ByteStringBuffer.prototype.putInt32Le = function (i) { + return this.putBytes(String.fromCharCode(i & 255) + String.fromCharCode((i >> 8) & 255) + String.fromCharCode((i >> 16) & 255) + String.fromCharCode((i >> 24) & 255)); + }; + util.ByteStringBuffer.prototype.putInt = function (i, n) { + _checkBitsParam(n); + var bytes = ''; + do { + n -= 8; + bytes += String.fromCharCode((i >> n) & 255); + } while (n > 0); + return this.putBytes(bytes); + }; + util.ByteStringBuffer.prototype.putSignedInt = function (i, n) { + if (i < 0) { + i += 2 << (n - 1); + } + return this.putInt(i, n); + }; + util.ByteStringBuffer.prototype.putBuffer = function (buffer) { + return this.putBytes(buffer.getBytes()); + }; + util.ByteStringBuffer.prototype.getByte = function () { + return this.data.charCodeAt(this.read++); + }; + util.ByteStringBuffer.prototype.getInt16 = function () { + var rval = (this.data.charCodeAt(this.read) << 8) ^ this.data.charCodeAt(this.read + 1); + this.read += 2; + return rval; + }; + util.ByteStringBuffer.prototype.getInt24 = function () { + var rval = (this.data.charCodeAt(this.read) << 16) ^ (this.data.charCodeAt(this.read + 1) << 8) ^ this.data.charCodeAt(this.read + 2); + this.read += 3; + return rval; + }; + util.ByteStringBuffer.prototype.getInt32 = function () { + var rval = (this.data.charCodeAt(this.read) << 24) ^ (this.data.charCodeAt(this.read + 1) << 16) ^ (this.data.charCodeAt(this.read + 2) << 8) ^ this.data.charCodeAt(this.read + 3); + this.read += 4; + return rval; + }; + util.ByteStringBuffer.prototype.getInt16Le = function () { + var rval = this.data.charCodeAt(this.read) ^ (this.data.charCodeAt(this.read + 1) << 8); + this.read += 2; + return rval; + }; + util.ByteStringBuffer.prototype.getInt24Le = function () { + var rval = this.data.charCodeAt(this.read) ^ (this.data.charCodeAt(this.read + 1) << 8) ^ (this.data.charCodeAt(this.read + 2) << 16); + this.read += 3; + return rval; + }; + util.ByteStringBuffer.prototype.getInt32Le = function () { + var rval = this.data.charCodeAt(this.read) ^ (this.data.charCodeAt(this.read + 1) << 8) ^ (this.data.charCodeAt(this.read + 2) << 16) ^ (this.data.charCodeAt(this.read + 3) << 24); + this.read += 4; + return rval; + }; + util.ByteStringBuffer.prototype.getInt = function (n) { + _checkBitsParam(n); + var rval = 0; + do { + rval = (rval << 8) + this.data.charCodeAt(this.read++); + n -= 8; + } while (n > 0); + return rval; + }; + util.ByteStringBuffer.prototype.getSignedInt = function (n) { + var x = this.getInt(n); + var max = 2 << (n - 2); + if (x >= max) { + x -= max << 1; + } + return x; + }; + util.ByteStringBuffer.prototype.getBytes = function (count) { + var rval; + if (count) { + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if (count === 0) { + rval = ''; + } else { + rval = this.read === 0 ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; + }; + util.ByteStringBuffer.prototype.bytes = function (count) { + return typeof count === 'undefined' ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); + }; + util.ByteStringBuffer.prototype.at = function (i) { + return this.data.charCodeAt(this.read + i); + }; + util.ByteStringBuffer.prototype.setAt = function (i, b2) { + this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b2) + this.data.substr(this.read + i + 1); + return this; + }; + util.ByteStringBuffer.prototype.last = function () { + return this.data.charCodeAt(this.data.length - 1); + }; + util.ByteStringBuffer.prototype.copy = function () { + var c = util.createBuffer(this.data); + c.read = this.read; + return c; + }; + util.ByteStringBuffer.prototype.compact = function () { + if (this.read > 0) { + this.data = this.data.slice(this.read); + this.read = 0; + } + return this; + }; + util.ByteStringBuffer.prototype.clear = function () { + this.data = ''; + this.read = 0; + return this; + }; + util.ByteStringBuffer.prototype.truncate = function (count) { + var len = Math.max(0, this.length() - count); + this.data = this.data.substr(this.read, len); + this.read = 0; + return this; + }; + util.ByteStringBuffer.prototype.toHex = function () { + var rval = ''; + for (var i = this.read; i < this.data.length; ++i) { + var b2 = this.data.charCodeAt(i); + if (b2 < 16) { + rval += '0'; + } + rval += b2.toString(16); + } + return rval; + }; + util.ByteStringBuffer.prototype.toString = function () { + return util.decodeUtf8(this.bytes()); + }; + util.DataBuffer = DataBuffer; + util.DataBuffer.prototype.length = function () { + return this.write - this.read; + }; + util.DataBuffer.prototype.isEmpty = function () { + return this.length() <= 0; + }; + util.DataBuffer.prototype.accommodate = function (amount, growSize) { + if (this.length() >= amount) { + return this; + } + growSize = Math.max(growSize || this.growSize, amount); + var src = new Uint8Array(this.data.buffer, this.data.byteOffset, this.data.byteLength); + var dst = new Uint8Array(this.length() + growSize); + dst.set(src); + this.data = new DataView(dst.buffer); + return this; + }; + util.DataBuffer.prototype.putByte = function (b2) { + this.accommodate(1); + this.data.setUint8(this.write++, b2); + return this; + }; + util.DataBuffer.prototype.fillWithByte = function (b2, n) { + this.accommodate(n); + for (var i = 0; i < n; ++i) { + this.data.setUint8(b2); + } + return this; + }; + util.DataBuffer.prototype.putBytes = function (bytes, encoding) { + if (util.isArrayBufferView(bytes)) { + var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var len = src.byteLength - src.byteOffset; + this.accommodate(len); + var dst = new Uint8Array(this.data.buffer, this.write); + dst.set(src); + this.write += len; + return this; + } + if (util.isArrayBuffer(bytes)) { + var src = new Uint8Array(bytes); + this.accommodate(src.byteLength); + var dst = new Uint8Array(this.data.buffer); + dst.set(src, this.write); + this.write += src.byteLength; + return this; + } + if (bytes instanceof util.DataBuffer || (typeof bytes === 'object' && typeof bytes.read === 'number' && typeof bytes.write === 'number' && util.isArrayBufferView(bytes.data))) { + var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); + this.accommodate(src.byteLength); + var dst = new Uint8Array(bytes.data.byteLength, this.write); + dst.set(src); + this.write += src.byteLength; + return this; + } + if (bytes instanceof util.ByteStringBuffer) { + bytes = bytes.data; + encoding = 'binary'; + } + encoding = encoding || 'binary'; + if (typeof bytes === 'string') { + var view; + if (encoding === 'hex') { + this.accommodate(Math.ceil(bytes.length / 2)); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.hex.decode(bytes, view, this.write); + return this; + } + if (encoding === 'base64') { + this.accommodate(Math.ceil(bytes.length / 4) * 3); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.base64.decode(bytes, view, this.write); + return this; + } + if (encoding === 'utf8') { + bytes = util.encodeUtf8(bytes); + encoding = 'binary'; + } + if (encoding === 'binary' || encoding === 'raw') { + this.accommodate(bytes.length); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.raw.decode(view); + return this; + } + if (encoding === 'utf16') { + this.accommodate(bytes.length * 2); + view = new Uint16Array(this.data.buffer, this.write); + this.write += util.text.utf16.encode(view); + return this; + } + throw new Error('Invalid encoding: ' + encoding); + } + throw Error('Invalid parameter: ' + bytes); + }; + util.DataBuffer.prototype.putBuffer = function (buffer) { + this.putBytes(buffer); + buffer.clear(); + return this; + }; + util.DataBuffer.prototype.putString = function (str) { + return this.putBytes(str, 'utf16'); + }; + util.DataBuffer.prototype.putInt16 = function (i) { + this.accommodate(2); + this.data.setInt16(this.write, i); + this.write += 2; + return this; + }; + util.DataBuffer.prototype.putInt24 = function (i) { + this.accommodate(3); + this.data.setInt16(this.write, (i >> 8) & 65535); + this.data.setInt8(this.write, (i >> 16) & 255); + this.write += 3; + return this; + }; + util.DataBuffer.prototype.putInt32 = function (i) { + this.accommodate(4); + this.data.setInt32(this.write, i); + this.write += 4; + return this; + }; + util.DataBuffer.prototype.putInt16Le = function (i) { + this.accommodate(2); + this.data.setInt16(this.write, i, true); + this.write += 2; + return this; + }; + util.DataBuffer.prototype.putInt24Le = function (i) { + this.accommodate(3); + this.data.setInt8(this.write, (i >> 16) & 255); + this.data.setInt16(this.write, (i >> 8) & 65535, true); + this.write += 3; + return this; + }; + util.DataBuffer.prototype.putInt32Le = function (i) { + this.accommodate(4); + this.data.setInt32(this.write, i, true); + this.write += 4; + return this; + }; + util.DataBuffer.prototype.putInt = function (i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + do { + n -= 8; + this.data.setInt8(this.write++, (i >> n) & 255); + } while (n > 0); + return this; + }; + util.DataBuffer.prototype.putSignedInt = function (i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + if (i < 0) { + i += 2 << (n - 1); + } + return this.putInt(i, n); + }; + util.DataBuffer.prototype.getByte = function () { + return this.data.getInt8(this.read++); + }; + util.DataBuffer.prototype.getInt16 = function () { + var rval = this.data.getInt16(this.read); + this.read += 2; + return rval; + }; + util.DataBuffer.prototype.getInt24 = function () { + var rval = (this.data.getInt16(this.read) << 8) ^ this.data.getInt8(this.read + 2); + this.read += 3; + return rval; + }; + util.DataBuffer.prototype.getInt32 = function () { + var rval = this.data.getInt32(this.read); + this.read += 4; + return rval; + }; + util.DataBuffer.prototype.getInt16Le = function () { + var rval = this.data.getInt16(this.read, true); + this.read += 2; + return rval; + }; + util.DataBuffer.prototype.getInt24Le = function () { + var rval = this.data.getInt8(this.read) ^ (this.data.getInt16(this.read + 1, true) << 8); + this.read += 3; + return rval; + }; + util.DataBuffer.prototype.getInt32Le = function () { + var rval = this.data.getInt32(this.read, true); + this.read += 4; + return rval; + }; + util.DataBuffer.prototype.getInt = function (n) { + _checkBitsParam(n); + var rval = 0; + do { + rval = (rval << 8) + this.data.getInt8(this.read++); + n -= 8; + } while (n > 0); + return rval; + }; + util.DataBuffer.prototype.getSignedInt = function (n) { + var x = this.getInt(n); + var max = 2 << (n - 2); + if (x >= max) { + x -= max << 1; + } + return x; + }; + util.DataBuffer.prototype.getBytes = function (count) { + var rval; + if (count) { + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if (count === 0) { + rval = ''; + } else { + rval = this.read === 0 ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; + }; + util.DataBuffer.prototype.bytes = function (count) { + return typeof count === 'undefined' ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); + }; + util.DataBuffer.prototype.at = function (i) { + return this.data.getUint8(this.read + i); + }; + util.DataBuffer.prototype.setAt = function (i, b2) { + this.data.setUint8(i, b2); + return this; + }; + util.DataBuffer.prototype.last = function () { + return this.data.getUint8(this.write - 1); + }; + util.DataBuffer.prototype.copy = function () { + return new util.DataBuffer(this); + }; + util.DataBuffer.prototype.compact = function () { + if (this.read > 0) { + var src = new Uint8Array(this.data.buffer, this.read); + var dst = new Uint8Array(src.byteLength); + dst.set(src); + this.data = new DataView(dst); + this.write -= this.read; + this.read = 0; + } + return this; + }; + util.DataBuffer.prototype.clear = function () { + this.data = new DataView(new ArrayBuffer(0)); + this.read = this.write = 0; + return this; + }; + util.DataBuffer.prototype.truncate = function (count) { + this.write = Math.max(0, this.length() - count); + this.read = Math.min(this.read, this.write); + return this; + }; + util.DataBuffer.prototype.toHex = function () { + var rval = ''; + for (var i = this.read; i < this.data.byteLength; ++i) { + var b2 = this.data.getUint8(i); + if (b2 < 16) { + rval += '0'; + } + rval += b2.toString(16); + } + return rval; + }; + util.DataBuffer.prototype.toString = function (encoding) { + var view = new Uint8Array(this.data, this.read, this.length()); + encoding = encoding || 'utf8'; + if (encoding === 'binary' || encoding === 'raw') { + return util.binary.raw.encode(view); + } + if (encoding === 'hex') { + return util.binary.hex.encode(view); + } + if (encoding === 'base64') { + return util.binary.base64.encode(view); + } + if (encoding === 'utf8') { + return util.text.utf8.decode(view); + } + if (encoding === 'utf16') { + return util.text.utf16.decode(view); + } + throw new Error('Invalid encoding: ' + encoding); + }; + util.createBuffer = function (input, encoding) { + encoding = encoding || 'raw'; + if (input !== undefined && encoding === 'utf8') { + input = util.encodeUtf8(input); + } + return new util.ByteBuffer(input); + }; + util.fillString = function (c, n) { + var s = ''; + while (n > 0) { + if (n & 1) { + s += c; + } + n >>>= 1; + if (n > 0) { + c += c; + } + } + return s; + }; + util.xorBytes = function (s1, s2, n) { + var s3 = ''; + var b2 = ''; + var t = ''; + var i = 0; + var c = 0; + for (; n > 0; --n, ++i) { + b2 = s1.charCodeAt(i) ^ s2.charCodeAt(i); + if (c >= 10) { + s3 += t; + t = ''; + c = 0; + } + t += String.fromCharCode(b2); + ++c; + } + s3 += t; + return s3; + }; + util.hexToBytes = function (hex) { + var rval = ''; + var i = 0; + if (hex.length & true) { + i = 1; + rval += String.fromCharCode(parseInt(hex[0], 16)); + } + for (; i < hex.length; i += 2) { + rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + } + return rval; + }; + util.bytesToHex = function (bytes) { + return util.createBuffer(bytes).toHex(); + }; + util.int32ToBytes = function (i) { + return String.fromCharCode((i >> 24) & 255) + String.fromCharCode((i >> 16) & 255) + String.fromCharCode((i >> 8) & 255) + String.fromCharCode(i & 255); + }; + var _base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + var _base64Idx = [ + 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 64, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 + ]; + var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + util.encode64 = function (input, maxline) { + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while (i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if (isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + } + if (maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); + } + } + output += line; + return output; + }; + util.decode64 = function (input) { + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + var output = ''; + var enc1, enc2, enc3, enc4; + var i = 0; + while (i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); + if (enc3 !== 64) { + output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); + if (enc4 !== 64) { + output += String.fromCharCode(((enc3 & 3) << 6) | enc4); + } + } + } + return output; + }; + util.encodeUtf8 = function (str) { + return unescape(encodeURIComponent(str)); + }; + util.decodeUtf8 = function (str) { + return decodeURIComponent(escape(str)); + }; + util.binary = { + raw: {}, + hex: {}, + base64: {}, + base58: {}, + baseN: { + encode: baseN.encode, + decode: baseN.decode + } + }; + util.binary.raw.encode = function (bytes) { + return String.fromCharCode.apply(null, bytes); + }; + util.binary.raw.decode = function (str, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for (var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? j - offset : out; + }; + util.binary.hex.encode = util.bytesToHex; + util.binary.hex.decode = function (hex, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(Math.ceil(hex.length / 2)); + } + offset = offset || 0; + var i = 0, + j = offset; + if (hex.length & 1) { + i = 1; + out[j++] = parseInt(hex[0], 16); + } + for (; i < hex.length; i += 2) { + out[j++] = parseInt(hex.substr(i, 2), 16); + } + return output ? j - offset : out; + }; + util.binary.base64.encode = function (input, maxline) { + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while (i < input.byteLength) { + chr1 = input[i++]; + chr2 = input[i++]; + chr3 = input[i++]; + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if (isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + } + if (maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); + } + } + output += line; + return output; + }; + util.binary.base64.decode = function (input, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(Math.ceil(input.length / 4) * 3); + } + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + offset = offset || 0; + var enc1, enc2, enc3, enc4; + var i = 0, + j = offset; + while (i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + out[j++] = (enc1 << 2) | (enc2 >> 4); + if (enc3 !== 64) { + out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); + if (enc4 !== 64) { + out[j++] = ((enc3 & 3) << 6) | enc4; + } + } + } + return output ? j - offset : out.subarray(0, j); + }; + util.binary.base58.encode = function (input, maxline) { + return util.binary.baseN.encode(input, _base58, maxline); + }; + util.binary.base58.decode = function (input, maxline) { + return util.binary.baseN.decode(input, _base58, maxline); + }; + util.text = { + utf8: {}, + utf16: {} + }; + util.text.utf8.encode = function (str, output, offset) { + str = util.encodeUtf8(str); + var out = output; + if (!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for (var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? j - offset : out; + }; + util.text.utf8.decode = function (bytes) { + return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); + }; + util.text.utf16.encode = function (str, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(str.length * 2); + } + var view = new Uint16Array(out.buffer); + offset = offset || 0; + var j = offset; + var k = offset; + for (var i = 0; i < str.length; ++i) { + view[k++] = str.charCodeAt(i); + j += 2; + } + return output ? j - offset : out; + }; + util.text.utf16.decode = function (bytes) { + return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); + }; + util.deflate = function (api, bytes, raw) { + bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); + if (raw) { + var start = 2; + var flg = bytes.charCodeAt(1); + if (flg & 32) { + start = 6; + } + bytes = bytes.substring(start, bytes.length - 4); + } + return bytes; + }; + util.inflate = function (api, bytes, raw) { + var rval = api.inflate(util.encode64(bytes)).rval; + return rval === null ? null : util.decode64(rval); + }; + var _setStorageObject = function (api, id, obj) { + if (!api) { + throw new Error('WebStorage not available.'); + } + var rval; + if (obj === null) { + rval = api.removeItem(id); + } else { + obj = util.encode64(JSON.stringify(obj)); + rval = api.setItem(id, obj); + } + if (typeof rval !== 'undefined' && rval.rval !== true) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } + }; + var _getStorageObject = function (api, id) { + if (!api) { + throw new Error('WebStorage not available.'); + } + var rval = api.getItem(id); + if (api.init) { + if (rval.rval === null) { + if (rval.error) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } + rval = null; + } else { + rval = rval.rval; + } + } + if (rval !== null) { + rval = JSON.parse(util.decode64(rval)); + } + return rval; + }; + var _setItem = function (api, id, key, data) { + var obj = _getStorageObject(api, id); + if (obj === null) { + obj = {}; + } + obj[key] = data; + _setStorageObject(api, id, obj); + }; + var _getItem = function (api, id, key) { + var rval = _getStorageObject(api, id); + if (rval !== null) { + rval = key in rval ? rval[key] : null; + } + return rval; + }; + var _removeItem = function (api, id, key) { + var obj = _getStorageObject(api, id); + if (obj !== null && key in obj) { + delete obj[key]; + var empty = true; + for (var prop in obj) { + empty = false; + break; + } + if (empty) { + obj = null; + } + _setStorageObject(api, id, obj); + } + }; + var _clearItems = function (api, id) { + _setStorageObject(api, id, null); + }; + var _callStorageFunction = function (func, args, location) { + var rval = null; + if (typeof location === 'undefined') { + location = ['web', 'flash']; + } + var type; + var done = false; + var exception = null; + for (var idx in location) { + type = location[idx]; + try { + if (type === 'flash' || type === 'both') { + if (args[0] === null) { + throw new Error('Flash local storage not available.'); + } + rval = func.apply(this, args); + done = type === 'flash'; + } + if (type === 'web' || type === 'both') { + args[0] = localStorage; + rval = func.apply(this, args); + done = true; + } + } catch (ex) { + exception = ex; + } + if (done) { + break; + } + } + if (!done) { + throw exception; + } + return rval; + }; + util.setItem = function (api, id, key, data, location) { + _callStorageFunction(_setItem, arguments, location); + }; + util.getItem = function (api, id, key, location) { + return _callStorageFunction(_getItem, arguments, location); + }; + util.removeItem = function (api, id, key, location) { + _callStorageFunction(_removeItem, arguments, location); + }; + util.clearItems = function (api, id, location) { + _callStorageFunction(_clearItems, arguments, location); + }; + util.isEmpty = function (obj) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + return false; + } + } + return true; + }; + util.format = function (format) { + var re = /%./g; + var match; + var part; + var argi = 0; + var parts = []; + var last = 0; + while ((match = re.exec(format))) { + part = format.substring(last, re.lastIndex - 2); + if (part.length > 0) { + parts.push(part); + } + last = re.lastIndex; + var code = match[0][1]; + switch (code) { + case 's': + case 'o': + if (argi < arguments.length) { + parts.push(arguments[argi++ + 1]); + } else { + parts.push(''); + } + break; + case '%': + parts.push('%'); + break; + default: + parts.push('<%' + code + '?>'); + } + } + parts.push(format.substring(last)); + return parts.join(''); + }; + util.formatNumber = function (number, decimals, dec_point, thousands_sep) { + var n = number, + c = isNaN((decimals = Math.abs(decimals))) ? 2 : decimals; + var d = dec_point === undefined ? ',' : dec_point; + var t = thousands_sep === undefined ? '.' : thousands_sep, + s = n < 0 ? '-' : ''; + var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; + var j = i.length > 3 ? i.length % 3 : 0; + return ( + s + + (j ? i.substr(0, j) + t : '') + + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + + (c + ? d + + Math.abs(n - i) + .toFixed(c) + .slice(2) + : '') + ); + }; + util.formatSize = function (size) { + if (size >= 1073741824) { + size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; + } else if (size >= 1048576) { + size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; + } else if (size >= 1024) { + size = util.formatNumber(size / 1024, 0) + ' KiB'; + } else { + size = util.formatNumber(size, 0) + ' bytes'; + } + return size; + }; + util.bytesFromIP = function (ip) { + if (ip.indexOf('.') !== -1) { + return util.bytesFromIPv4(ip); + } + if (ip.indexOf(':') !== -1) { + return util.bytesFromIPv6(ip); + } + return null; + }; + util.bytesFromIPv4 = function (ip) { + ip = ip.split('.'); + if (ip.length !== 4) { + return null; + } + var b2 = util.createBuffer(); + for (var i = 0; i < ip.length; ++i) { + var num = parseInt(ip[i], 10); + if (isNaN(num)) { + return null; + } + b2.putByte(num); + } + return b2.getBytes(); + }; + util.bytesFromIPv6 = function (ip) { + var blanks = 0; + ip = ip.split(':').filter(function (e) { + if (e.length === 0) ++blanks; + return true; + }); + var zeros = (8 - ip.length + blanks) * 2; + var b2 = util.createBuffer(); + for (var i = 0; i < 8; ++i) { + if (!ip[i] || ip[i].length === 0) { + b2.fillWithByte(0, zeros); + zeros = 0; + continue; + } + var bytes = util.hexToBytes(ip[i]); + if (bytes.length < 2) { + b2.putByte(0); + } + b2.putBytes(bytes); + } + return b2.getBytes(); + }; + util.bytesToIP = function (bytes) { + if (bytes.length === 4) { + return util.bytesToIPv4(bytes); + } + if (bytes.length === 16) { + return util.bytesToIPv6(bytes); + } + return null; + }; + util.bytesToIPv4 = function (bytes) { + if (bytes.length !== 4) { + return null; + } + var ip = []; + for (var i = 0; i < bytes.length; ++i) { + ip.push(bytes.charCodeAt(i)); + } + return ip.join('.'); + }; + util.bytesToIPv6 = function (bytes) { + if (bytes.length !== 16) { + return null; + } + var ip = []; + var zeroGroups = []; + var zeroMaxGroup = 0; + for (var i = 0; i < bytes.length; i += 2) { + var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); + while (hex[0] === '0' && hex !== '0') { + hex = hex.substr(1); + } + if (hex === '0') { + var last = zeroGroups[zeroGroups.length - 1]; + var idx = ip.length; + if (!last || idx !== last.end + 1) { + zeroGroups.push({start: idx, end: idx}); + } else { + last.end = idx; + if (last.end - last.start > zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start) { + zeroMaxGroup = zeroGroups.length - 1; + } + } + } + ip.push(hex); + } + if (zeroGroups.length > 0) { + var group = zeroGroups[zeroMaxGroup]; + if (group.end - group.start > 0) { + ip.splice(group.start, group.end - group.start + 1, ''); + if (group.start === 0) { + ip.unshift(''); + } + if (group.end === 7) { + ip.push(''); + } + } + } + return ip.join(':'); + }; + util.estimateCores = function (options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + if ('cores' in util && !options.update) { + return callback(null, util.cores); + } + if (typeof navigator !== 'undefined' && 'hardwareConcurrency' in navigator && navigator.hardwareConcurrency > 0) { + util.cores = navigator.hardwareConcurrency; + return callback(null, util.cores); + } + if (typeof Worker === 'undefined') { + util.cores = 1; + return callback(null, util.cores); + } + if (typeof Blob === 'undefined') { + util.cores = 2; + return callback(null, util.cores); + } + var blobUrl = URL.createObjectURL( + new Blob( + [ + '(', + function () { + self.addEventListener('message', function (e) { + var st = Date.now(); + var et = st + 4; + while (Date.now() < et); + self.postMessage({st, et}); + }); + }.toString(), + ')()' + ], + {type: 'application/javascript'} + ) + ); + sample([], 5, 16); + function sample(max, samples, numWorkers) { + if (samples === 0) { + var avg = Math.floor( + max.reduce(function (avg2, x) { + return avg2 + x; + }, 0) / max.length + ); + util.cores = Math.max(1, avg); + URL.revokeObjectURL(blobUrl); + return callback(null, util.cores); + } + map(numWorkers, function (err, results) { + max.push(reduce(numWorkers, results)); + sample(max, samples - 1, numWorkers); + }); + } + function map(numWorkers, callback2) { + var workers = []; + var results = []; + for (var i = 0; i < numWorkers; ++i) { + var worker = new Worker(blobUrl); + worker.addEventListener('message', function (e) { + results.push(e.data); + if (results.length === numWorkers) { + for (var i2 = 0; i2 < numWorkers; ++i2) { + workers[i2].terminate(); + } + callback2(null, results); + } + }); + workers.push(worker); + } + for (var i = 0; i < numWorkers; ++i) { + workers[i].postMessage(i); + } + } + function reduce(numWorkers, results) { + var overlaps = []; + for (var n = 0; n < numWorkers; ++n) { + var r1 = results[n]; + var overlap = (overlaps[n] = []); + for (var i = 0; i < numWorkers; ++i) { + if (n === i) { + continue; + } + var r2 = results[i]; + if ((r1.st > r2.st && r1.st < r2.et) || (r2.st > r1.st && r2.st < r1.et)) { + overlap.push(i); + } + } + } + return overlaps.reduce(function (max, overlap2) { + return Math.max(max, overlap2.length); + }, 0); + } + }; +}); + +// node_modules/node-forge/lib/cipher.js +var require_cipher = __commonJS((exports, module) => { + var forge = require_forge(); + require_util(); + module.exports = forge.cipher = forge.cipher || {}; + forge.cipher.algorithms = forge.cipher.algorithms || {}; + forge.cipher.createCipher = function (algorithm, key) { + var api = algorithm; + if (typeof api === 'string') { + api = forge.cipher.getAlgorithm(api); + if (api) { + api = api(); + } + } + if (!api) { + throw new Error('Unsupported algorithm: ' + algorithm); + } + return new forge.cipher.BlockCipher({ + algorithm: api, + key, + decrypt: false + }); + }; + forge.cipher.createDecipher = function (algorithm, key) { + var api = algorithm; + if (typeof api === 'string') { + api = forge.cipher.getAlgorithm(api); + if (api) { + api = api(); + } + } + if (!api) { + throw new Error('Unsupported algorithm: ' + algorithm); + } + return new forge.cipher.BlockCipher({ + algorithm: api, + key, + decrypt: true + }); + }; + forge.cipher.registerAlgorithm = function (name, algorithm) { + name = name.toUpperCase(); + forge.cipher.algorithms[name] = algorithm; + }; + forge.cipher.getAlgorithm = function (name) { + name = name.toUpperCase(); + if (name in forge.cipher.algorithms) { + return forge.cipher.algorithms[name]; + } + return null; + }; + var BlockCipher = (forge.cipher.BlockCipher = function (options) { + this.algorithm = options.algorithm; + this.mode = this.algorithm.mode; + this.blockSize = this.mode.blockSize; + this._finish = false; + this._input = null; + this.output = null; + this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; + this._decrypt = options.decrypt; + this.algorithm.initialize(options); + }); + BlockCipher.prototype.start = function (options) { + options = options || {}; + var opts = {}; + for (var key in options) { + opts[key] = options[key]; + } + opts.decrypt = this._decrypt; + this._finish = false; + this._input = forge.util.createBuffer(); + this.output = options.output || forge.util.createBuffer(); + this.mode.start(opts); + }; + BlockCipher.prototype.update = function (input) { + if (input) { + this._input.putBuffer(input); + } + while (!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) {} + this._input.compact(); + }; + BlockCipher.prototype.finish = function (pad) { + if (pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) { + this.mode.pad = function (input) { + return pad(this.blockSize, input, false); + }; + this.mode.unpad = function (output) { + return pad(this.blockSize, output, true); + }; + } + var options = {}; + options.decrypt = this._decrypt; + options.overflow = this._input.length() % this.blockSize; + if (!this._decrypt && this.mode.pad) { + if (!this.mode.pad(this._input, options)) { + return false; + } + } + this._finish = true; + this.update(); + if (this._decrypt && this.mode.unpad) { + if (!this.mode.unpad(this.output, options)) { + return false; + } + } + if (this.mode.afterFinish) { + if (!this.mode.afterFinish(this.output, options)) { + return false; + } + } + return true; + }; +}); + +// node_modules/node-forge/lib/cipherModes.js +var require_cipherModes = __commonJS((exports, module) => { + var transformIV = function (iv, blockSize) { + if (typeof iv === 'string') { + iv = forge.util.createBuffer(iv); + } + if (forge.util.isArray(iv) && iv.length > 4) { + var tmp = iv; + iv = forge.util.createBuffer(); + for (var i = 0; i < tmp.length; ++i) { + iv.putByte(tmp[i]); + } + } + if (iv.length() < blockSize) { + throw new Error('Invalid IV length; got ' + iv.length() + ' bytes and expected ' + blockSize + ' bytes.'); + } + if (!forge.util.isArray(iv)) { + var ints = []; + var blocks = blockSize / 4; + for (var i = 0; i < blocks; ++i) { + ints.push(iv.getInt32()); + } + iv = ints; + } + return iv; + }; + var inc32 = function (block) { + block[block.length - 1] = (block[block.length - 1] + 1) & 4294967295; + }; + var from64To32 = function (num) { + return [(num / 4294967296) | 0, num & 4294967295]; + }; + var forge = require_forge(); + require_util(); + forge.cipher = forge.cipher || {}; + var modes = (module.exports = forge.cipher.modes = forge.cipher.modes || {}); + modes.ecb = function (options) { + options = options || {}; + this.name = 'ECB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + }; + modes.ecb.prototype.start = function (options) {}; + modes.ecb.prototype.encrypt = function (input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + this.cipher.encrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } + }; + modes.ecb.prototype.decrypt = function (input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + this.cipher.decrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } + }; + modes.ecb.prototype.pad = function (input, options) { + var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); + input.fillWithByte(padding, padding); + return true; + }; + modes.ecb.prototype.unpad = function (output, options) { + if (options.overflow > 0) { + return false; + } + var len = output.length(); + var count = output.at(len - 1); + if (count > this.blockSize << 2) { + return false; + } + output.truncate(count); + return true; + }; + modes.cbc = function (options) { + options = options || {}; + this.name = 'CBC'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + }; + modes.cbc.prototype.start = function (options) { + if (options.iv === null) { + if (!this._prev) { + throw new Error('Invalid IV parameter.'); + } + this._iv = this._prev.slice(0); + } else if (!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } else { + this._iv = transformIV(options.iv, this.blockSize); + this._prev = this._iv.slice(0); + } + }; + modes.cbc.prototype.encrypt = function (input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._prev[i] ^ input.getInt32(); + } + this.cipher.encrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } + this._prev = this._outBlock; + }; + modes.cbc.prototype.decrypt = function (input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + this.cipher.decrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._prev[i] ^ this._outBlock[i]); + } + this._prev = this._inBlock.slice(0); + }; + modes.cbc.prototype.pad = function (input, options) { + var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); + input.fillWithByte(padding, padding); + return true; + }; + modes.cbc.prototype.unpad = function (output, options) { + if (options.overflow > 0) { + return false; + } + var len = output.length(); + var count = output.at(len - 1); + if (count > this.blockSize << 2) { + return false; + } + output.truncate(count); + return true; + }; + modes.cfb = function (options) { + options = options || {}; + this.name = 'CFB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + }; + modes.cfb.prototype.start = function (options) { + if (!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; + }; + modes.cfb.prototype.encrypt = function (input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; + output.putInt32(this._inBlock[i]); + } + return; + } + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; + this._partialOutput.putInt32(this._partialBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; + } else { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes(partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes(inputLength - this._partialBytes)); + this._partialBytes = 0; + }; + modes.cfb.prototype.decrypt = function (input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + output.putInt32(this._inBlock[i] ^ this._outBlock[i]); + } + return; + } + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32(); + this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; + } else { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes(partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes(inputLength - this._partialBytes)); + this._partialBytes = 0; + }; + modes.ofb = function (options) { + options = options || {}; + this.name = 'OFB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + }; + modes.ofb.prototype.start = function (options) { + if (!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; + }; + modes.ofb.prototype.encrypt = function (input, output, finish) { + var inputLength = input.length(); + if (input.length() === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + this._inBlock[i] = this._outBlock[i]; + } + return; + } + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; + } else { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._outBlock[i]; + } + } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes(partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes(inputLength - this._partialBytes)); + this._partialBytes = 0; + }; + modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; + modes.ctr = function (options) { + options = options || {}; + this.name = 'CTR'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + }; + modes.ctr.prototype.start = function (options) { + if (!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; + }; + modes.ctr.prototype.encrypt = function (input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + } + } else { + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; + } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes(partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes(inputLength - this._partialBytes)); + this._partialBytes = 0; + } + inc32(this._inBlock); + }; + modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; + modes.gcm = function (options) { + options = options || {}; + this.name = 'GCM'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + this._R = 3774873600; + }; + modes.gcm.prototype.start = function (options) { + if (!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + var iv = forge.util.createBuffer(options.iv); + this._cipherLength = 0; + var additionalData; + if ('additionalData' in options) { + additionalData = forge.util.createBuffer(options.additionalData); + } else { + additionalData = forge.util.createBuffer(); + } + if ('tagLength' in options) { + this._tagLength = options.tagLength; + } else { + this._tagLength = 128; + } + this._tag = null; + if (options.decrypt) { + this._tag = forge.util.createBuffer(options.tag).getBytes(); + if (this._tag.length !== this._tagLength / 8) { + throw new Error('Authentication tag does not match tag length.'); + } + } + this._hashBlock = new Array(this._ints); + this.tag = null; + this._hashSubkey = new Array(this._ints); + this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); + this.componentBits = 4; + this._m = this.generateHashTable(this._hashSubkey, this.componentBits); + var ivLength = iv.length(); + if (ivLength === 12) { + this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; + } else { + this._j0 = [0, 0, 0, 0]; + while (iv.length() > 0) { + this._j0 = this.ghash(this._hashSubkey, this._j0, [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]); + } + this._j0 = this.ghash(this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8))); + } + this._inBlock = this._j0.slice(0); + inc32(this._inBlock); + this._partialBytes = 0; + additionalData = forge.util.createBuffer(additionalData); + this._aDataLength = from64To32(additionalData.length() * 8); + var overflow = additionalData.length() % this.blockSize; + if (overflow) { + additionalData.fillWithByte(0, this.blockSize - overflow); + } + this._s = [0, 0, 0, 0]; + while (additionalData.length() > 0) { + this._s = this.ghash(this._hashSubkey, this._s, [additionalData.getInt32(), additionalData.getInt32(), additionalData.getInt32(), additionalData.getInt32()]); + } + }; + modes.gcm.prototype.encrypt = function (input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + output.putInt32((this._outBlock[i] ^= input.getInt32())); + } + this._cipherLength += this.blockSize; + } else { + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + if (partialBytes <= 0 || finish) { + if (finish) { + var overflow = inputLength % this.blockSize; + this._cipherLength += overflow; + this._partialOutput.truncate(this.blockSize - overflow); + } else { + this._cipherLength += this.blockSize; + } + for (var i = 0; i < this._ints; ++i) { + this._outBlock[i] = this._partialOutput.getInt32(); + } + this._partialOutput.read -= this.blockSize; + } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + input.read -= this.blockSize; + output.putBytes(this._partialOutput.getBytes(partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes(inputLength - this._partialBytes)); + this._partialBytes = 0; + } + this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); + inc32(this._inBlock); + }; + modes.gcm.prototype.decrypt = function (input, output, finish) { + var inputLength = input.length(); + if (inputLength < this.blockSize && !(finish && inputLength > 0)) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + inc32(this._inBlock); + this._hashBlock[0] = input.getInt32(); + this._hashBlock[1] = input.getInt32(); + this._hashBlock[2] = input.getInt32(); + this._hashBlock[3] = input.getInt32(); + this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); + } + if (inputLength < this.blockSize) { + this._cipherLength += inputLength % this.blockSize; + } else { + this._cipherLength += this.blockSize; + } + }; + modes.gcm.prototype.afterFinish = function (output, options) { + var rval = true; + if (options.decrypt && options.overflow) { + output.truncate(this.blockSize - options.overflow); + } + this.tag = forge.util.createBuffer(); + var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); + this._s = this.ghash(this._hashSubkey, this._s, lengths); + var tag = []; + this.cipher.encrypt(this._j0, tag); + for (var i = 0; i < this._ints; ++i) { + this.tag.putInt32(this._s[i] ^ tag[i]); + } + this.tag.truncate(this.tag.length() % (this._tagLength / 8)); + if (options.decrypt && this.tag.bytes() !== this._tag) { + rval = false; + } + return rval; + }; + modes.gcm.prototype.multiply = function (x, y2) { + var z_i = [0, 0, 0, 0]; + var v_i = y2.slice(0); + for (var i = 0; i < 128; ++i) { + var x_i = x[(i / 32) | 0] & (1 << (31 - (i % 32))); + if (x_i) { + z_i[0] ^= v_i[0]; + z_i[1] ^= v_i[1]; + z_i[2] ^= v_i[2]; + z_i[3] ^= v_i[3]; + } + this.pow(v_i, v_i); + } + return z_i; + }; + modes.gcm.prototype.pow = function (x, out) { + var lsb = x[3] & 1; + for (var i = 3; i > 0; --i) { + out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31); + } + out[0] = x[0] >>> 1; + if (lsb) { + out[0] ^= this._R; + } + }; + modes.gcm.prototype.tableMultiply = function (x) { + var z2 = [0, 0, 0, 0]; + for (var i = 0; i < 32; ++i) { + var idx = (i / 8) | 0; + var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 15; + var ah = this._m[i][x_i]; + z2[0] ^= ah[0]; + z2[1] ^= ah[1]; + z2[2] ^= ah[2]; + z2[3] ^= ah[3]; + } + return z2; + }; + modes.gcm.prototype.ghash = function (h2, y2, x) { + y2[0] ^= x[0]; + y2[1] ^= x[1]; + y2[2] ^= x[2]; + y2[3] ^= x[3]; + return this.tableMultiply(y2); + }; + modes.gcm.prototype.generateHashTable = function (h2, bits) { + var multiplier = 8 / bits; + var perInt = 4 * multiplier; + var size = 16 * multiplier; + var m2 = new Array(size); + for (var i = 0; i < size; ++i) { + var tmp = [0, 0, 0, 0]; + var idx = (i / perInt) | 0; + var shft = (perInt - 1 - (i % perInt)) * bits; + tmp[idx] = (1 << (bits - 1)) << shft; + m2[i] = this.generateSubHashTable(this.multiply(tmp, h2), bits); + } + return m2; + }; + modes.gcm.prototype.generateSubHashTable = function (mid, bits) { + var size = 1 << bits; + var half = size >>> 1; + var m2 = new Array(size); + m2[half] = mid.slice(0); + var i = half >>> 1; + while (i > 0) { + this.pow(m2[2 * i], (m2[i] = [])); + i >>= 1; + } + i = 2; + while (i < half) { + for (var j = 1; j < i; ++j) { + var m_i = m2[i]; + var m_j = m2[j]; + m2[i + j] = [m_i[0] ^ m_j[0], m_i[1] ^ m_j[1], m_i[2] ^ m_j[2], m_i[3] ^ m_j[3]]; + } + i *= 2; + } + m2[0] = [0, 0, 0, 0]; + for (i = half + 1; i < size; ++i) { + var c = m2[i ^ half]; + m2[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; + } + return m2; + }; +}); + +// node_modules/node-forge/lib/aes.js +var require_aes = __commonJS((exports, module) => { + var registerAlgorithm = function (name, mode) { + var factory = function () { + return new forge.aes.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); + }; + var initialize = function () { + init2 = true; + rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]; + var xtime = new Array(256); + for (var i = 0; i < 128; ++i) { + xtime[i] = i << 1; + xtime[i + 128] = ((i + 128) << 1) ^ 283; + } + sbox = new Array(256); + isbox = new Array(256); + mix = new Array(4); + imix = new Array(4); + for (var i = 0; i < 4; ++i) { + mix[i] = new Array(256); + imix[i] = new Array(256); + } + var e = 0, + ei = 0, + e2, + e4, + e8, + sx, + sx2, + me, + ime; + for (var i = 0; i < 256; ++i) { + sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4); + sx = (sx >> 8) ^ (sx & 255) ^ 99; + sbox[e] = sx; + isbox[sx] = e; + sx2 = xtime[sx]; + e2 = xtime[e]; + e4 = xtime[e2]; + e8 = xtime[e4]; + me = (sx2 << 24) ^ (sx << 16) ^ (sx << 8) ^ (sx ^ sx2); + ime = ((e2 ^ e4 ^ e8) << 24) ^ ((e ^ e8) << 16) ^ ((e ^ e4 ^ e8) << 8) ^ (e ^ e2 ^ e8); + for (var n = 0; n < 4; ++n) { + mix[n][e] = me; + imix[n][sx] = ime; + me = (me << 24) | (me >>> 8); + ime = (ime << 24) | (ime >>> 8); + } + if (e === 0) { + e = ei = 1; + } else { + e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; + ei ^= xtime[xtime[ei]]; + } + } + }; + var _expandKey = function (key, decrypt) { + var w = key.slice(0); + var temp, + iNk = 1; + var Nk = w.length; + var Nr1 = Nk + 6 + 1; + var end = Nb * Nr1; + for (var i = Nk; i < end; ++i) { + temp = w[i - 1]; + if (i % Nk === 0) { + temp = (sbox[(temp >>> 16) & 255] << 24) ^ (sbox[(temp >>> 8) & 255] << 16) ^ (sbox[temp & 255] << 8) ^ sbox[temp >>> 24] ^ (rcon[iNk] << 24); + iNk++; + } else if (Nk > 6 && i % Nk === 4) { + temp = (sbox[temp >>> 24] << 24) ^ (sbox[(temp >>> 16) & 255] << 16) ^ (sbox[(temp >>> 8) & 255] << 8) ^ sbox[temp & 255]; + } + w[i] = w[i - Nk] ^ temp; + } + if (decrypt) { + var tmp; + var m0 = imix[0]; + var m1 = imix[1]; + var m2 = imix[2]; + var m3 = imix[3]; + var wnew = w.slice(0); + end = w.length; + for (var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { + if (i === 0 || i === end - Nb) { + wnew[i] = w[wi]; + wnew[i + 1] = w[wi + 3]; + wnew[i + 2] = w[wi + 2]; + wnew[i + 3] = w[wi + 1]; + } else { + for (var n = 0; n < Nb; ++n) { + tmp = w[wi + n]; + wnew[i + (3 & -n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[(tmp >>> 16) & 255]] ^ m2[sbox[(tmp >>> 8) & 255]] ^ m3[sbox[tmp & 255]]; + } + } + } + w = wnew; + } + return w; + }; + var _updateBlock = function (w, input, output, decrypt) { + var Nr = w.length / 4 - 1; + var m0, m1, m2, m3, sub; + if (decrypt) { + m0 = imix[0]; + m1 = imix[1]; + m2 = imix[2]; + m3 = imix[3]; + sub = isbox; + } else { + m0 = mix[0]; + m1 = mix[1]; + m2 = mix[2]; + m3 = mix[3]; + sub = sbox; + } + var a, b2, c, d, a2, b22, c2; + a = input[0] ^ w[0]; + b2 = input[decrypt ? 3 : 1] ^ w[1]; + c = input[2] ^ w[2]; + d = input[decrypt ? 1 : 3] ^ w[3]; + var i = 3; + for (var round = 1; round < Nr; ++round) { + a2 = m0[a >>> 24] ^ m1[(b2 >>> 16) & 255] ^ m2[(c >>> 8) & 255] ^ m3[d & 255] ^ w[++i]; + b22 = m0[b2 >>> 24] ^ m1[(c >>> 16) & 255] ^ m2[(d >>> 8) & 255] ^ m3[a & 255] ^ w[++i]; + c2 = m0[c >>> 24] ^ m1[(d >>> 16) & 255] ^ m2[(a >>> 8) & 255] ^ m3[b2 & 255] ^ w[++i]; + d = m0[d >>> 24] ^ m1[(a >>> 16) & 255] ^ m2[(b2 >>> 8) & 255] ^ m3[c & 255] ^ w[++i]; + a = a2; + b2 = b22; + c = c2; + } + output[0] = (sub[a >>> 24] << 24) ^ (sub[(b2 >>> 16) & 255] << 16) ^ (sub[(c >>> 8) & 255] << 8) ^ sub[d & 255] ^ w[++i]; + output[decrypt ? 3 : 1] = (sub[b2 >>> 24] << 24) ^ (sub[(c >>> 16) & 255] << 16) ^ (sub[(d >>> 8) & 255] << 8) ^ sub[a & 255] ^ w[++i]; + output[2] = (sub[c >>> 24] << 24) ^ (sub[(d >>> 16) & 255] << 16) ^ (sub[(a >>> 8) & 255] << 8) ^ sub[b2 & 255] ^ w[++i]; + output[decrypt ? 1 : 3] = (sub[d >>> 24] << 24) ^ (sub[(a >>> 16) & 255] << 16) ^ (sub[(b2 >>> 8) & 255] << 8) ^ sub[c & 255] ^ w[++i]; + }; + var _createCipher = function (options) { + options = options || {}; + var mode = (options.mode || 'CBC').toUpperCase(); + var algorithm = 'AES-' + mode; + var cipher; + if (options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + var start = cipher.start; + cipher.start = function (iv, options2) { + var output = null; + if (options2 instanceof forge.util.ByteBuffer) { + output = options2; + options2 = {}; + } + options2 = options2 || {}; + options2.output = output; + options2.iv = iv; + start.call(cipher, options2); + }; + return cipher; + }; + var forge = require_forge(); + require_cipher(); + require_cipherModes(); + require_util(); + module.exports = forge.aes = forge.aes || {}; + forge.aes.startEncrypting = function (key, iv, output, mode) { + var cipher = _createCipher({ + key, + output, + decrypt: false, + mode + }); + cipher.start(iv); + return cipher; + }; + forge.aes.createEncryptionCipher = function (key, mode) { + return _createCipher({ + key, + output: null, + decrypt: false, + mode + }); + }; + forge.aes.startDecrypting = function (key, iv, output, mode) { + var cipher = _createCipher({ + key, + output, + decrypt: true, + mode + }); + cipher.start(iv); + return cipher; + }; + forge.aes.createDecryptionCipher = function (key, mode) { + return _createCipher({ + key, + output: null, + decrypt: true, + mode + }); + }; + forge.aes.Algorithm = function (name, mode) { + if (!init2) { + initialize(); + } + var self2 = this; + self2.name = name; + self2.mode = new mode({ + blockSize: 16, + cipher: { + encrypt: function (inBlock, outBlock) { + return _updateBlock(self2._w, inBlock, outBlock, false); + }, + decrypt: function (inBlock, outBlock) { + return _updateBlock(self2._w, inBlock, outBlock, true); + } + } + }); + self2._init = false; + }; + forge.aes.Algorithm.prototype.initialize = function (options) { + if (this._init) { + return; + } + var key = options.key; + var tmp; + if (typeof key === 'string' && (key.length === 16 || key.length === 24 || key.length === 32)) { + key = forge.util.createBuffer(key); + } else if (forge.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) { + tmp = key; + key = forge.util.createBuffer(); + for (var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + if (!forge.util.isArray(key)) { + tmp = key; + key = []; + var len = tmp.length(); + if (len === 16 || len === 24 || len === 32) { + len = len >>> 2; + for (var i = 0; i < len; ++i) { + key.push(tmp.getInt32()); + } + } + } + if (!forge.util.isArray(key) || !(key.length === 4 || key.length === 6 || key.length === 8)) { + throw new Error('Invalid key parameter.'); + } + var mode = this.mode.name; + var encryptOp = ['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1; + this._w = _expandKey(key, options.decrypt && !encryptOp); + this._init = true; + }; + forge.aes._expandKey = function (key, decrypt) { + if (!init2) { + initialize(); + } + return _expandKey(key, decrypt); + }; + forge.aes._updateBlock = _updateBlock; + registerAlgorithm('AES-ECB', forge.cipher.modes.ecb); + registerAlgorithm('AES-CBC', forge.cipher.modes.cbc); + registerAlgorithm('AES-CFB', forge.cipher.modes.cfb); + registerAlgorithm('AES-OFB', forge.cipher.modes.ofb); + registerAlgorithm('AES-CTR', forge.cipher.modes.ctr); + registerAlgorithm('AES-GCM', forge.cipher.modes.gcm); + var init2 = false; + var Nb = 4; + var sbox; + var isbox; + var rcon; + var mix; + var imix; +}); + +// node_modules/node-forge/lib/oids.js +var require_oids = __commonJS((exports, module) => { + var _IN = function (id, name) { + oids[id] = name; + oids[name] = id; + }; + var _I_ = function (id, name) { + oids[id] = name; + }; + var forge = require_forge(); + forge.pki = forge.pki || {}; + var oids = (module.exports = forge.pki.oids = forge.oids = forge.oids || {}); + _IN('1.2.840.113549.1.1.1', 'rsaEncryption'); + _IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption'); + _IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption'); + _IN('1.2.840.113549.1.1.7', 'RSAES-OAEP'); + _IN('1.2.840.113549.1.1.8', 'mgf1'); + _IN('1.2.840.113549.1.1.9', 'pSpecified'); + _IN('1.2.840.113549.1.1.10', 'RSASSA-PSS'); + _IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption'); + _IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption'); + _IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption'); + _IN('1.3.101.112', 'EdDSA25519'); + _IN('1.2.840.10040.4.3', 'dsa-with-sha1'); + _IN('1.3.14.3.2.7', 'desCBC'); + _IN('1.3.14.3.2.26', 'sha1'); + _IN('1.3.14.3.2.29', 'sha1WithRSASignature'); + _IN('2.16.840.1.101.3.4.2.1', 'sha256'); + _IN('2.16.840.1.101.3.4.2.2', 'sha384'); + _IN('2.16.840.1.101.3.4.2.3', 'sha512'); + _IN('2.16.840.1.101.3.4.2.4', 'sha224'); + _IN('2.16.840.1.101.3.4.2.5', 'sha512-224'); + _IN('2.16.840.1.101.3.4.2.6', 'sha512-256'); + _IN('1.2.840.113549.2.2', 'md2'); + _IN('1.2.840.113549.2.5', 'md5'); + _IN('1.2.840.113549.1.7.1', 'data'); + _IN('1.2.840.113549.1.7.2', 'signedData'); + _IN('1.2.840.113549.1.7.3', 'envelopedData'); + _IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData'); + _IN('1.2.840.113549.1.7.5', 'digestedData'); + _IN('1.2.840.113549.1.7.6', 'encryptedData'); + _IN('1.2.840.113549.1.9.1', 'emailAddress'); + _IN('1.2.840.113549.1.9.2', 'unstructuredName'); + _IN('1.2.840.113549.1.9.3', 'contentType'); + _IN('1.2.840.113549.1.9.4', 'messageDigest'); + _IN('1.2.840.113549.1.9.5', 'signingTime'); + _IN('1.2.840.113549.1.9.6', 'counterSignature'); + _IN('1.2.840.113549.1.9.7', 'challengePassword'); + _IN('1.2.840.113549.1.9.8', 'unstructuredAddress'); + _IN('1.2.840.113549.1.9.14', 'extensionRequest'); + _IN('1.2.840.113549.1.9.20', 'friendlyName'); + _IN('1.2.840.113549.1.9.21', 'localKeyId'); + _IN('1.2.840.113549.1.9.22.1', 'x509Certificate'); + _IN('1.2.840.113549.1.12.10.1.1', 'keyBag'); + _IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag'); + _IN('1.2.840.113549.1.12.10.1.3', 'certBag'); + _IN('1.2.840.113549.1.12.10.1.4', 'crlBag'); + _IN('1.2.840.113549.1.12.10.1.5', 'secretBag'); + _IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag'); + _IN('1.2.840.113549.1.5.13', 'pkcs5PBES2'); + _IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2'); + _IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4'); + _IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4'); + _IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC'); + _IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC'); + _IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC'); + _IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC'); + _IN('1.2.840.113549.2.7', 'hmacWithSHA1'); + _IN('1.2.840.113549.2.8', 'hmacWithSHA224'); + _IN('1.2.840.113549.2.9', 'hmacWithSHA256'); + _IN('1.2.840.113549.2.10', 'hmacWithSHA384'); + _IN('1.2.840.113549.2.11', 'hmacWithSHA512'); + _IN('1.2.840.113549.3.7', 'des-EDE3-CBC'); + _IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC'); + _IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC'); + _IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC'); + _IN('2.5.4.3', 'commonName'); + _IN('2.5.4.4', 'surname'); + _IN('2.5.4.5', 'serialNumber'); + _IN('2.5.4.6', 'countryName'); + _IN('2.5.4.7', 'localityName'); + _IN('2.5.4.8', 'stateOrProvinceName'); + _IN('2.5.4.9', 'streetAddress'); + _IN('2.5.4.10', 'organizationName'); + _IN('2.5.4.11', 'organizationalUnitName'); + _IN('2.5.4.12', 'title'); + _IN('2.5.4.13', 'description'); + _IN('2.5.4.15', 'businessCategory'); + _IN('2.5.4.17', 'postalCode'); + _IN('2.5.4.42', 'givenName'); + _IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName'); + _IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName'); + _IN('2.16.840.1.113730.1.1', 'nsCertType'); + _IN('2.16.840.1.113730.1.13', 'nsComment'); + _I_('2.5.29.1', 'authorityKeyIdentifier'); + _I_('2.5.29.2', 'keyAttributes'); + _I_('2.5.29.3', 'certificatePolicies'); + _I_('2.5.29.4', 'keyUsageRestriction'); + _I_('2.5.29.5', 'policyMapping'); + _I_('2.5.29.6', 'subtreesConstraint'); + _I_('2.5.29.7', 'subjectAltName'); + _I_('2.5.29.8', 'issuerAltName'); + _I_('2.5.29.9', 'subjectDirectoryAttributes'); + _I_('2.5.29.10', 'basicConstraints'); + _I_('2.5.29.11', 'nameConstraints'); + _I_('2.5.29.12', 'policyConstraints'); + _I_('2.5.29.13', 'basicConstraints'); + _IN('2.5.29.14', 'subjectKeyIdentifier'); + _IN('2.5.29.15', 'keyUsage'); + _I_('2.5.29.16', 'privateKeyUsagePeriod'); + _IN('2.5.29.17', 'subjectAltName'); + _IN('2.5.29.18', 'issuerAltName'); + _IN('2.5.29.19', 'basicConstraints'); + _I_('2.5.29.20', 'cRLNumber'); + _I_('2.5.29.21', 'cRLReason'); + _I_('2.5.29.22', 'expirationDate'); + _I_('2.5.29.23', 'instructionCode'); + _I_('2.5.29.24', 'invalidityDate'); + _I_('2.5.29.25', 'cRLDistributionPoints'); + _I_('2.5.29.26', 'issuingDistributionPoint'); + _I_('2.5.29.27', 'deltaCRLIndicator'); + _I_('2.5.29.28', 'issuingDistributionPoint'); + _I_('2.5.29.29', 'certificateIssuer'); + _I_('2.5.29.30', 'nameConstraints'); + _IN('2.5.29.31', 'cRLDistributionPoints'); + _IN('2.5.29.32', 'certificatePolicies'); + _I_('2.5.29.33', 'policyMappings'); + _I_('2.5.29.34', 'policyConstraints'); + _IN('2.5.29.35', 'authorityKeyIdentifier'); + _I_('2.5.29.36', 'policyConstraints'); + _IN('2.5.29.37', 'extKeyUsage'); + _I_('2.5.29.46', 'freshestCRL'); + _I_('2.5.29.54', 'inhibitAnyPolicy'); + _IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList'); + _IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess'); + _IN('1.3.6.1.5.5.7.3.1', 'serverAuth'); + _IN('1.3.6.1.5.5.7.3.2', 'clientAuth'); + _IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); + _IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); + _IN('1.3.6.1.5.5.7.3.8', 'timeStamping'); +}); + +// node_modules/node-forge/lib/asn1.js +var require_asn1 = __commonJS((exports, module) => { + var _checkBufferLength = function (bytes, remaining, n) { + if (n > remaining) { + var error = new Error('Too few bytes to parse DER.'); + error.available = bytes.length(); + error.remaining = remaining; + error.requested = n; + throw error; + } + }; + var _fromDer = function (bytes, remaining, depth, options) { + var start; + _checkBufferLength(bytes, remaining, 2); + var b1 = bytes.getByte(); + remaining--; + var tagClass = b1 & 192; + var type = b1 & 31; + start = bytes.length(); + var length = _getValueLength(bytes, remaining); + remaining -= start - bytes.length(); + if (length !== undefined && length > remaining) { + if (options.strict) { + var error = new Error('Too few bytes to read ASN.1 value.'); + error.available = bytes.length(); + error.remaining = remaining; + error.requested = length; + throw error; + } + length = remaining; + } + var value; + var bitStringContents; + var constructed = (b1 & 32) === 32; + if (constructed) { + value = []; + if (length === undefined) { + for (;;) { + _checkBufferLength(bytes, remaining, 2); + if (bytes.bytes(2) === String.fromCharCode(0, 0)) { + bytes.getBytes(2); + remaining -= 2; + break; + } + start = bytes.length(); + value.push(_fromDer(bytes, remaining, depth + 1, options)); + remaining -= start - bytes.length(); + } + } else { + while (length > 0) { + start = bytes.length(); + value.push(_fromDer(bytes, length, depth + 1, options)); + remaining -= start - bytes.length(); + length -= start - bytes.length(); + } + } + } + if (value === undefined && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING) { + bitStringContents = bytes.bytes(length); + } + if (value === undefined && options.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING && length > 1) { + var savedRead = bytes.read; + var savedRemaining = remaining; + var unused = 0; + if (type === asn1.Type.BITSTRING) { + _checkBufferLength(bytes, remaining, 1); + unused = bytes.getByte(); + remaining--; + } + if (unused === 0) { + try { + start = bytes.length(); + var subOptions = { + strict: true, + decodeBitStrings: true + }; + var composed = _fromDer(bytes, remaining, depth + 1, subOptions); + var used = start - bytes.length(); + remaining -= used; + if (type == asn1.Type.BITSTRING) { + used++; + } + var tc = composed.tagClass; + if (used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { + value = [composed]; + } + } catch (ex) {} + } + if (value === undefined) { + bytes.read = savedRead; + remaining = savedRemaining; + } + } + if (value === undefined) { + if (length === undefined) { + if (options.strict) { + throw new Error('Non-constructed ASN.1 object of indefinite length.'); + } + length = remaining; + } + if (type === asn1.Type.BMPSTRING) { + value = ''; + for (; length > 0; length -= 2) { + _checkBufferLength(bytes, remaining, 2); + value += String.fromCharCode(bytes.getInt16()); + remaining -= 2; + } + } else { + value = bytes.getBytes(length); + remaining -= length; + } + } + var asn1Options = + bitStringContents === undefined + ? null + : { + bitStringContents + }; + return asn1.create(tagClass, type, constructed, value, asn1Options); + }; + var forge = require_forge(); + require_util(); + require_oids(); + var asn1 = (module.exports = forge.asn1 = forge.asn1 || {}); + asn1.Class = { + UNIVERSAL: 0, + APPLICATION: 64, + CONTEXT_SPECIFIC: 128, + PRIVATE: 192 + }; + asn1.Type = { + NONE: 0, + BOOLEAN: 1, + INTEGER: 2, + BITSTRING: 3, + OCTETSTRING: 4, + NULL: 5, + OID: 6, + ODESC: 7, + EXTERNAL: 8, + REAL: 9, + ENUMERATED: 10, + EMBEDDED: 11, + UTF8: 12, + ROID: 13, + SEQUENCE: 16, + SET: 17, + PRINTABLESTRING: 19, + IA5STRING: 22, + UTCTIME: 23, + GENERALIZEDTIME: 24, + BMPSTRING: 30 + }; + asn1.create = function (tagClass, type, constructed, value, options) { + if (forge.util.isArray(value)) { + var tmp = []; + for (var i = 0; i < value.length; ++i) { + if (value[i] !== undefined) { + tmp.push(value[i]); + } + } + value = tmp; + } + var obj = { + tagClass, + type, + constructed, + composed: constructed || forge.util.isArray(value), + value + }; + if (options && 'bitStringContents' in options) { + obj.bitStringContents = options.bitStringContents; + obj.original = asn1.copy(obj); + } + return obj; + }; + asn1.copy = function (obj, options) { + var copy; + if (forge.util.isArray(obj)) { + copy = []; + for (var i = 0; i < obj.length; ++i) { + copy.push(asn1.copy(obj[i], options)); + } + return copy; + } + if (typeof obj === 'string') { + return obj; + } + copy = { + tagClass: obj.tagClass, + type: obj.type, + constructed: obj.constructed, + composed: obj.composed, + value: asn1.copy(obj.value, options) + }; + if (options && !options.excludeBitStringContents) { + copy.bitStringContents = obj.bitStringContents; + } + return copy; + }; + asn1.equals = function (obj1, obj2, options) { + if (forge.util.isArray(obj1)) { + if (!forge.util.isArray(obj2)) { + return false; + } + if (obj1.length !== obj2.length) { + return false; + } + for (var i = 0; i < obj1.length; ++i) { + if (!asn1.equals(obj1[i], obj2[i])) { + return false; + } + } + return true; + } + if (typeof obj1 !== typeof obj2) { + return false; + } + if (typeof obj1 === 'string') { + return obj1 === obj2; + } + var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value); + if (options && options.includeBitStringContents) { + equal = equal && obj1.bitStringContents === obj2.bitStringContents; + } + return equal; + }; + asn1.getBerValueLength = function (b2) { + var b22 = b2.getByte(); + if (b22 === 128) { + return; + } + var length; + var longForm = b22 & 128; + if (!longForm) { + length = b22; + } else { + length = b2.getInt((b22 & 127) << 3); + } + return length; + }; + var _getValueLength = function (bytes, remaining) { + var b2 = bytes.getByte(); + remaining--; + if (b2 === 128) { + return; + } + var length; + var longForm = b2 & 128; + if (!longForm) { + length = b2; + } else { + var longFormBytes = b2 & 127; + _checkBufferLength(bytes, remaining, longFormBytes); + length = bytes.getInt(longFormBytes << 3); + } + if (length < 0) { + throw new Error('Negative length: ' + length); + } + return length; + }; + asn1.fromDer = function (bytes, options) { + if (options === undefined) { + options = { + strict: true, + parseAllBytes: true, + decodeBitStrings: true + }; + } + if (typeof options === 'boolean') { + options = { + strict: options, + parseAllBytes: true, + decodeBitStrings: true + }; + } + if (!('strict' in options)) { + options.strict = true; + } + if (!('parseAllBytes' in options)) { + options.parseAllBytes = true; + } + if (!('decodeBitStrings' in options)) { + options.decodeBitStrings = true; + } + if (typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + var byteCount = bytes.length(); + var value = _fromDer(bytes, bytes.length(), 0, options); + if (options.parseAllBytes && bytes.length() !== 0) { + var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.'); + error.byteCount = byteCount; + error.remaining = bytes.length(); + throw error; + } + return value; + }; + asn1.toDer = function (obj) { + var bytes = forge.util.createBuffer(); + var b1 = obj.tagClass | obj.type; + var value = forge.util.createBuffer(); + var useBitStringContents = false; + if ('bitStringContents' in obj) { + useBitStringContents = true; + if (obj.original) { + useBitStringContents = asn1.equals(obj, obj.original); + } + } + if (useBitStringContents) { + value.putBytes(obj.bitStringContents); + } else if (obj.composed) { + if (obj.constructed) { + b1 |= 32; + } else { + value.putByte(0); + } + for (var i = 0; i < obj.value.length; ++i) { + if (obj.value[i] !== undefined) { + value.putBuffer(asn1.toDer(obj.value[i])); + } + } + } else { + if (obj.type === asn1.Type.BMPSTRING) { + for (var i = 0; i < obj.value.length; ++i) { + value.putInt16(obj.value.charCodeAt(i)); + } + } else { + if (obj.type === asn1.Type.INTEGER && obj.value.length > 1 && ((obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 128) === 0) || (obj.value.charCodeAt(0) === 255 && (obj.value.charCodeAt(1) & 128) === 128))) { + value.putBytes(obj.value.substr(1)); + } else { + value.putBytes(obj.value); + } + } + } + bytes.putByte(b1); + if (value.length() <= 127) { + bytes.putByte(value.length() & 127); + } else { + var len = value.length(); + var lenBytes = ''; + do { + lenBytes += String.fromCharCode(len & 255); + len = len >>> 8; + } while (len > 0); + bytes.putByte(lenBytes.length | 128); + for (var i = lenBytes.length - 1; i >= 0; --i) { + bytes.putByte(lenBytes.charCodeAt(i)); + } + } + bytes.putBuffer(value); + return bytes; + }; + asn1.oidToDer = function (oid) { + var values = oid.split('.'); + var bytes = forge.util.createBuffer(); + bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); + var last, valueBytes, value, b2; + for (var i = 2; i < values.length; ++i) { + last = true; + valueBytes = []; + value = parseInt(values[i], 10); + do { + b2 = value & 127; + value = value >>> 7; + if (!last) { + b2 |= 128; + } + valueBytes.push(b2); + last = false; + } while (value > 0); + for (var n = valueBytes.length - 1; n >= 0; --n) { + bytes.putByte(valueBytes[n]); + } + } + return bytes; + }; + asn1.derToOid = function (bytes) { + var oid; + if (typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + var b2 = bytes.getByte(); + oid = Math.floor(b2 / 40) + '.' + (b2 % 40); + var value = 0; + while (bytes.length() > 0) { + b2 = bytes.getByte(); + value = value << 7; + if (b2 & 128) { + value += b2 & 127; + } else { + oid += '.' + (value + b2); + value = 0; + } + } + return oid; + }; + asn1.utcTimeToDate = function (utc) { + var date = new Date(); + var year = parseInt(utc.substr(0, 2), 10); + year = year >= 50 ? 1900 + year : 2000 + year; + var MM = parseInt(utc.substr(2, 2), 10) - 1; + var DD = parseInt(utc.substr(4, 2), 10); + var hh = parseInt(utc.substr(6, 2), 10); + var mm = parseInt(utc.substr(8, 2), 10); + var ss = 0; + if (utc.length > 11) { + var c = utc.charAt(10); + var end = 10; + if (c !== '+' && c !== '-') { + ss = parseInt(utc.substr(10, 2), 10); + end += 2; + } + } + date.setUTCFullYear(year, MM, DD); + date.setUTCHours(hh, mm, ss, 0); + if (end) { + c = utc.charAt(end); + if (c === '+' || c === '-') { + var hhoffset = parseInt(utc.substr(end + 1, 2), 10); + var mmoffset = parseInt(utc.substr(end + 4, 2), 10); + var offset = hhoffset * 60 + mmoffset; + offset *= 60000; + if (c === '+') { + date.setTime(+date - offset); + } else { + date.setTime(+date + offset); + } + } + } + return date; + }; + asn1.generalizedTimeToDate = function (gentime) { + var date = new Date(); + var YYYY = parseInt(gentime.substr(0, 4), 10); + var MM = parseInt(gentime.substr(4, 2), 10) - 1; + var DD = parseInt(gentime.substr(6, 2), 10); + var hh = parseInt(gentime.substr(8, 2), 10); + var mm = parseInt(gentime.substr(10, 2), 10); + var ss = parseInt(gentime.substr(12, 2), 10); + var fff = 0; + var offset = 0; + var isUTC = false; + if (gentime.charAt(gentime.length - 1) === 'Z') { + isUTC = true; + } + var end = gentime.length - 5, + c = gentime.charAt(end); + if (c === '+' || c === '-') { + var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); + var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); + offset = hhoffset * 60 + mmoffset; + offset *= 60000; + if (c === '+') { + offset *= -1; + } + isUTC = true; + } + if (gentime.charAt(14) === '.') { + fff = parseFloat(gentime.substr(14), 10) * 1000; + } + if (isUTC) { + date.setUTCFullYear(YYYY, MM, DD); + date.setUTCHours(hh, mm, ss, fff); + date.setTime(+date + offset); + } else { + date.setFullYear(YYYY, MM, DD); + date.setHours(hh, mm, ss, fff); + } + return date; + }; + asn1.dateToUtcTime = function (date) { + if (typeof date === 'string') { + return date; + } + var rval = ''; + var format = []; + format.push(('' + date.getUTCFullYear()).substr(2)); + format.push('' + (date.getUTCMonth() + 1)); + format.push('' + date.getUTCDate()); + format.push('' + date.getUTCHours()); + format.push('' + date.getUTCMinutes()); + format.push('' + date.getUTCSeconds()); + for (var i = 0; i < format.length; ++i) { + if (format[i].length < 2) { + rval += '0'; + } + rval += format[i]; + } + rval += 'Z'; + return rval; + }; + asn1.dateToGeneralizedTime = function (date) { + if (typeof date === 'string') { + return date; + } + var rval = ''; + var format = []; + format.push('' + date.getUTCFullYear()); + format.push('' + (date.getUTCMonth() + 1)); + format.push('' + date.getUTCDate()); + format.push('' + date.getUTCHours()); + format.push('' + date.getUTCMinutes()); + format.push('' + date.getUTCSeconds()); + for (var i = 0; i < format.length; ++i) { + if (format[i].length < 2) { + rval += '0'; + } + rval += format[i]; + } + rval += 'Z'; + return rval; + }; + asn1.integerToDer = function (x) { + var rval = forge.util.createBuffer(); + if (x >= -128 && x < 128) { + return rval.putSignedInt(x, 8); + } + if (x >= -32768 && x < 32768) { + return rval.putSignedInt(x, 16); + } + if (x >= -8388608 && x < 8388608) { + return rval.putSignedInt(x, 24); + } + if (x >= -2147483648 && x < 2147483648) { + return rval.putSignedInt(x, 32); + } + var error = new Error('Integer too large; max is 32-bits.'); + error.integer = x; + throw error; + }; + asn1.derToInteger = function (bytes) { + if (typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + var n = bytes.length() * 8; + if (n > 32) { + throw new Error('Integer too large; max is 32-bits.'); + } + return bytes.getSignedInt(n); + }; + asn1.validate = function (obj, v, capture, errors) { + var rval = false; + if ((obj.tagClass === v.tagClass || typeof v.tagClass === 'undefined') && (obj.type === v.type || typeof v.type === 'undefined')) { + if (obj.constructed === v.constructed || typeof v.constructed === 'undefined') { + rval = true; + if (v.value && forge.util.isArray(v.value)) { + var j = 0; + for (var i = 0; rval && i < v.value.length; ++i) { + rval = v.value[i].optional || false; + if (obj.value[j]) { + rval = asn1.validate(obj.value[j], v.value[i], capture, errors); + if (rval) { + ++j; + } else if (v.value[i].optional) { + rval = true; + } + } + if (!rval && errors) { + errors.push('[' + v.name + '] ' + 'Tag class "' + v.tagClass + '", type "' + v.type + '" expected value length "' + v.value.length + '", got "' + obj.value.length + '"'); + } + } + } + if (rval && capture) { + if (v.capture) { + capture[v.capture] = obj.value; + } + if (v.captureAsn1) { + capture[v.captureAsn1] = obj; + } + if (v.captureBitStringContents && 'bitStringContents' in obj) { + capture[v.captureBitStringContents] = obj.bitStringContents; + } + if (v.captureBitStringValue && 'bitStringContents' in obj) { + var value; + if (obj.bitStringContents.length < 2) { + capture[v.captureBitStringValue] = ''; + } else { + var unused = obj.bitStringContents.charCodeAt(0); + if (unused !== 0) { + throw new Error('captureBitStringValue only supported for zero unused bits'); + } + capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); + } + } + } + } else if (errors) { + errors.push('[' + v.name + '] ' + 'Expected constructed "' + v.constructed + '", got "' + obj.constructed + '"'); + } + } else if (errors) { + if (obj.tagClass !== v.tagClass) { + errors.push('[' + v.name + '] ' + 'Expected tag class "' + v.tagClass + '", got "' + obj.tagClass + '"'); + } + if (obj.type !== v.type) { + errors.push('[' + v.name + '] ' + 'Expected type "' + v.type + '", got "' + obj.type + '"'); + } + } + return rval; + }; + var _nonLatinRegex = /[^\\u0000-\\u00ff]/; + asn1.prettyPrint = function (obj, level, indentation) { + var rval = ''; + level = level || 0; + indentation = indentation || 2; + if (level > 0) { + rval += '\n'; + } + var indent = ''; + for (var i = 0; i < level * indentation; ++i) { + indent += ' '; + } + rval += indent + 'Tag: '; + switch (obj.tagClass) { + case asn1.Class.UNIVERSAL: + rval += 'Universal:'; + break; + case asn1.Class.APPLICATION: + rval += 'Application:'; + break; + case asn1.Class.CONTEXT_SPECIFIC: + rval += 'Context-Specific:'; + break; + case asn1.Class.PRIVATE: + rval += 'Private:'; + break; + } + if (obj.tagClass === asn1.Class.UNIVERSAL) { + rval += obj.type; + switch (obj.type) { + case asn1.Type.NONE: + rval += ' (None)'; + break; + case asn1.Type.BOOLEAN: + rval += ' (Boolean)'; + break; + case asn1.Type.INTEGER: + rval += ' (Integer)'; + break; + case asn1.Type.BITSTRING: + rval += ' (Bit string)'; + break; + case asn1.Type.OCTETSTRING: + rval += ' (Octet string)'; + break; + case asn1.Type.NULL: + rval += ' (Null)'; + break; + case asn1.Type.OID: + rval += ' (Object Identifier)'; + break; + case asn1.Type.ODESC: + rval += ' (Object Descriptor)'; + break; + case asn1.Type.EXTERNAL: + rval += ' (External or Instance of)'; + break; + case asn1.Type.REAL: + rval += ' (Real)'; + break; + case asn1.Type.ENUMERATED: + rval += ' (Enumerated)'; + break; + case asn1.Type.EMBEDDED: + rval += ' (Embedded PDV)'; + break; + case asn1.Type.UTF8: + rval += ' (UTF8)'; + break; + case asn1.Type.ROID: + rval += ' (Relative Object Identifier)'; + break; + case asn1.Type.SEQUENCE: + rval += ' (Sequence)'; + break; + case asn1.Type.SET: + rval += ' (Set)'; + break; + case asn1.Type.PRINTABLESTRING: + rval += ' (Printable String)'; + break; + case asn1.Type.IA5String: + rval += ' (IA5String (ASCII))'; + break; + case asn1.Type.UTCTIME: + rval += ' (UTC time)'; + break; + case asn1.Type.GENERALIZEDTIME: + rval += ' (Generalized time)'; + break; + case asn1.Type.BMPSTRING: + rval += ' (BMP String)'; + break; + } + } else { + rval += obj.type; + } + rval += '\n'; + rval += indent + 'Constructed: ' + obj.constructed + '\n'; + if (obj.composed) { + var subvalues = 0; + var sub = ''; + for (var i = 0; i < obj.value.length; ++i) { + if (obj.value[i] !== undefined) { + subvalues += 1; + sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); + if (i + 1 < obj.value.length) { + sub += ','; + } + } + } + rval += indent + 'Sub values: ' + subvalues + sub; + } else { + rval += indent + 'Value: '; + if (obj.type === asn1.Type.OID) { + var oid = asn1.derToOid(obj.value); + rval += oid; + if (forge.pki && forge.pki.oids) { + if (oid in forge.pki.oids) { + rval += ' (' + forge.pki.oids[oid] + ') '; + } + } + } + if (obj.type === asn1.Type.INTEGER) { + try { + rval += asn1.derToInteger(obj.value); + } catch (ex) { + rval += '0x' + forge.util.bytesToHex(obj.value); + } + } else if (obj.type === asn1.Type.BITSTRING) { + if (obj.value.length > 1) { + rval += '0x' + forge.util.bytesToHex(obj.value.slice(1)); + } else { + rval += '(none)'; + } + if (obj.value.length > 0) { + var unused = obj.value.charCodeAt(0); + if (unused == 1) { + rval += ' (1 unused bit shown)'; + } else if (unused > 1) { + rval += ' (' + unused + ' unused bits shown)'; + } + } + } else if (obj.type === asn1.Type.OCTETSTRING) { + if (!_nonLatinRegex.test(obj.value)) { + rval += '(' + obj.value + ') '; + } + rval += '0x' + forge.util.bytesToHex(obj.value); + } else if (obj.type === asn1.Type.UTF8) { + try { + rval += forge.util.decodeUtf8(obj.value); + } catch (e) { + if (e.message === 'URI malformed') { + rval += '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)'; + } else { + throw e; + } + } + } else if (obj.type === asn1.Type.PRINTABLESTRING || obj.type === asn1.Type.IA5String) { + rval += obj.value; + } else if (_nonLatinRegex.test(obj.value)) { + rval += '0x' + forge.util.bytesToHex(obj.value); + } else if (obj.value.length === 0) { + rval += '[null]'; + } else { + rval += obj.value; + } + } + return rval; + }; +}); + +// node_modules/node-forge/lib/md.js +var require_md = __commonJS((exports, module) => { + var forge = require_forge(); + module.exports = forge.md = forge.md || {}; + forge.md.algorithms = forge.md.algorithms || {}; +}); + +// node_modules/node-forge/lib/hmac.js +var require_hmac = __commonJS((exports, module) => { + var forge = require_forge(); + require_md(); + require_util(); + var hmac = (module.exports = forge.hmac = forge.hmac || {}); + hmac.create = function () { + var _key = null; + var _md = null; + var _ipadding = null; + var _opadding = null; + var ctx = {}; + ctx.start = function (md, key) { + if (md !== null) { + if (typeof md === 'string') { + md = md.toLowerCase(); + if (md in forge.md.algorithms) { + _md = forge.md.algorithms[md].create(); + } else { + throw new Error('Unknown hash algorithm "' + md + '"'); + } + } else { + _md = md; + } + } + if (key === null) { + key = _key; + } else { + if (typeof key === 'string') { + key = forge.util.createBuffer(key); + } else if (forge.util.isArray(key)) { + var tmp = key; + key = forge.util.createBuffer(); + for (var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + var keylen = key.length(); + if (keylen > _md.blockLength) { + _md.start(); + _md.update(key.bytes()); + key = _md.digest(); + } + _ipadding = forge.util.createBuffer(); + _opadding = forge.util.createBuffer(); + keylen = key.length(); + for (var i = 0; i < keylen; ++i) { + var tmp = key.at(i); + _ipadding.putByte(54 ^ tmp); + _opadding.putByte(92 ^ tmp); + } + if (keylen < _md.blockLength) { + var tmp = _md.blockLength - keylen; + for (var i = 0; i < tmp; ++i) { + _ipadding.putByte(54); + _opadding.putByte(92); + } + } + _key = key; + _ipadding = _ipadding.bytes(); + _opadding = _opadding.bytes(); + } + _md.start(); + _md.update(_ipadding); + }; + ctx.update = function (bytes) { + _md.update(bytes); + }; + ctx.getMac = function () { + var inner = _md.digest().bytes(); + _md.start(); + _md.update(_opadding); + _md.update(inner); + return _md.digest(); + }; + ctx.digest = ctx.getMac; + return ctx; + }; +}); + +// node_modules/node-forge/lib/md5.js +var require_md5 = __commonJS((exports, module) => { + var _init = function () { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 64); + _g = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9]; + _r = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]; + _k = new Array(64); + for (var i = 0; i < 64; ++i) { + _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296); + } + _initialized = true; + }; + var _update = function (s, w, bytes) { + var t, a, b2, c, d, f, r, i; + var len = bytes.length(); + while (len >= 64) { + a = s.h0; + b2 = s.h1; + c = s.h2; + d = s.h3; + for (i = 0; i < 16; ++i) { + w[i] = bytes.getInt32Le(); + f = d ^ (b2 & (c ^ d)); + t = a + f + _k[i] + w[i]; + r = _r[i]; + a = d; + d = c; + c = b2; + b2 += (t << r) | (t >>> (32 - r)); + } + for (; i < 32; ++i) { + f = c ^ (d & (b2 ^ c)); + t = a + f + _k[i] + w[_g[i]]; + r = _r[i]; + a = d; + d = c; + c = b2; + b2 += (t << r) | (t >>> (32 - r)); + } + for (; i < 48; ++i) { + f = b2 ^ c ^ d; + t = a + f + _k[i] + w[_g[i]]; + r = _r[i]; + a = d; + d = c; + c = b2; + b2 += (t << r) | (t >>> (32 - r)); + } + for (; i < 64; ++i) { + f = c ^ (b2 | ~d); + t = a + f + _k[i] + w[_g[i]]; + r = _r[i]; + a = d; + d = c; + c = b2; + b2 += (t << r) | (t >>> (32 - r)); + } + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b2) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + len -= 64; + } + }; + var forge = require_forge(); + require_md(); + require_util(); + var md5 = (module.exports = forge.md5 = forge.md5 || {}); + forge.md.md5 = forge.md.algorithms.md5 = md5; + md5.create = function () { + if (!_initialized) { + _init(); + } + var _state = null; + var _input = forge.util.createBuffer(); + var _w = new Array(16); + var md = { + algorithm: 'md5', + blockLength: 64, + digestLength: 16, + messageLength: 0, + fullMessageLength: null, + messageLengthSize: 8 + }; + md.start = function () { + md.messageLength = 0; + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 1732584193, + h1: 4023233417, + h2: 2562383102, + h3: 271733878 + }; + return md; + }; + md.start(); + md.update = function (msg, encoding) { + if (encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + var len = msg.length; + md.messageLength += len; + len = [(len / 4294967296) >>> 0, len >>> 0]; + for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 4294967296) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = (len[1] / 4294967296) >>> 0; + } + _input.putBytes(msg); + _update(_state, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + return md; + }; + md.digest = function () { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + var bits, + carry = 0; + for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { + bits = md.fullMessageLength[i] * 8 + carry; + carry = (bits / 4294967296) >>> 0; + finalBlock.putInt32Le(bits >>> 0); + } + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32Le(s2.h0); + rval.putInt32Le(s2.h1); + rval.putInt32Le(s2.h2); + rval.putInt32Le(s2.h3); + return rval; + }; + return md; + }; + var _padding = null; + var _g = null; + var _r = null; + var _k = null; + var _initialized = false; +}); + +// node_modules/node-forge/lib/pem.js +var require_pem = __commonJS((exports, module) => { + var foldHeader = function (header) { + var rval = header.name + ': '; + var values = []; + var insertSpace = function (match, $1) { + return ' ' + $1; + }; + for (var i = 0; i < header.values.length; ++i) { + values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); + } + rval += values.join(',') + '\r\n'; + var length = 0; + var candidate = -1; + for (var i = 0; i < rval.length; ++i, ++length) { + if (length > 65 && candidate !== -1) { + var insert = rval[candidate]; + if (insert === ',') { + ++candidate; + rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate); + } else { + rval = rval.substr(0, candidate) + '\r\n' + insert + rval.substr(candidate + 1); + } + length = i - candidate - 1; + candidate = -1; + ++i; + } else if (rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') { + candidate = i; + } + } + return rval; + }; + var ltrim = function (str) { + return str.replace(/^\s+/, ''); + }; + var forge = require_forge(); + require_util(); + var pem = (module.exports = forge.pem = forge.pem || {}); + pem.encode = function (msg, options) { + options = options || {}; + var rval = '-----BEGIN ' + msg.type + '-----\r\n'; + var header; + if (msg.procType) { + header = { + name: 'Proc-Type', + values: [String(msg.procType.version), msg.procType.type] + }; + rval += foldHeader(header); + } + if (msg.contentDomain) { + header = {name: 'Content-Domain', values: [msg.contentDomain]}; + rval += foldHeader(header); + } + if (msg.dekInfo) { + header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]}; + if (msg.dekInfo.parameters) { + header.values.push(msg.dekInfo.parameters); + } + rval += foldHeader(header); + } + if (msg.headers) { + for (var i = 0; i < msg.headers.length; ++i) { + rval += foldHeader(msg.headers[i]); + } + } + if (msg.procType) { + rval += '\r\n'; + } + rval += forge.util.encode64(msg.body, options.maxline || 64) + '\r\n'; + rval += '-----END ' + msg.type + '-----\r\n'; + return rval; + }; + pem.decode = function (str) { + var rval = []; + var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; + var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; + var rCRLF = /\r?\n/; + var match; + while (true) { + match = rMessage.exec(str); + if (!match) { + break; + } + var type = match[1]; + if (type === 'NEW CERTIFICATE REQUEST') { + type = 'CERTIFICATE REQUEST'; + } + var msg = { + type, + procType: null, + contentDomain: null, + dekInfo: null, + headers: [], + body: forge.util.decode64(match[3]) + }; + rval.push(msg); + if (!match[2]) { + continue; + } + var lines = match[2].split(rCRLF); + var li = 0; + while (match && li < lines.length) { + var line = lines[li].replace(/\s+$/, ''); + for (var nl = li + 1; nl < lines.length; ++nl) { + var next = lines[nl]; + if (!/\s/.test(next[0])) { + break; + } + line += next; + li = nl; + } + match = line.match(rHeader); + if (match) { + var header = {name: match[1], values: []}; + var values = match[2].split(','); + for (var vi = 0; vi < values.length; ++vi) { + header.values.push(ltrim(values[vi])); + } + if (!msg.procType) { + if (header.name !== 'Proc-Type') { + throw new Error('Invalid PEM formatted message. The first ' + 'encapsulated header must be "Proc-Type".'); + } else if (header.values.length !== 2) { + throw new Error('Invalid PEM formatted message. The "Proc-Type" ' + 'header must have two subfields.'); + } + msg.procType = {version: values[0], type: values[1]}; + } else if (!msg.contentDomain && header.name === 'Content-Domain') { + msg.contentDomain = values[0] || ''; + } else if (!msg.dekInfo && header.name === 'DEK-Info') { + if (header.values.length === 0) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + 'header must have at least one subfield.'); + } + msg.dekInfo = {algorithm: values[0], parameters: values[1] || null}; + } else { + msg.headers.push(header); + } + } + ++li; + } + if (msg.procType === 'ENCRYPTED' && !msg.dekInfo) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + 'header must be present if "Proc-Type" is "ENCRYPTED".'); + } + } + if (rval.length === 0) { + throw new Error('Invalid PEM formatted message.'); + } + return rval; + }; +}); + +// node_modules/node-forge/lib/des.js +var require_des = __commonJS((exports, module) => { + var registerAlgorithm = function (name, mode) { + var factory = function () { + return new forge.des.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); + }; + var _createKeys = function (key) { + var pc2bytes0 = [0, 4, 536870912, 536870916, 65536, 65540, 536936448, 536936452, 512, 516, 536871424, 536871428, 66048, 66052, 536936960, 536936964], + pc2bytes1 = [0, 1, 1048576, 1048577, 67108864, 67108865, 68157440, 68157441, 256, 257, 1048832, 1048833, 67109120, 67109121, 68157696, 68157697], + pc2bytes2 = [0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272, 0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272], + pc2bytes3 = [0, 2097152, 134217728, 136314880, 8192, 2105344, 134225920, 136323072, 131072, 2228224, 134348800, 136445952, 139264, 2236416, 134356992, 136454144], + pc2bytes4 = [0, 262144, 16, 262160, 0, 262144, 16, 262160, 4096, 266240, 4112, 266256, 4096, 266240, 4112, 266256], + pc2bytes5 = [0, 1024, 32, 1056, 0, 1024, 32, 1056, 33554432, 33555456, 33554464, 33555488, 33554432, 33555456, 33554464, 33555488], + pc2bytes6 = [0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746, 0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746], + pc2bytes7 = [0, 65536, 2048, 67584, 536870912, 536936448, 536872960, 536938496, 131072, 196608, 133120, 198656, 537001984, 537067520, 537004032, 537069568], + pc2bytes8 = [0, 262144, 0, 262144, 2, 262146, 2, 262146, 33554432, 33816576, 33554432, 33816576, 33554434, 33816578, 33554434, 33816578], + pc2bytes9 = [0, 268435456, 8, 268435464, 0, 268435456, 8, 268435464, 1024, 268436480, 1032, 268436488, 1024, 268436480, 1032, 268436488], + pc2bytes10 = [0, 32, 0, 32, 1048576, 1048608, 1048576, 1048608, 8192, 8224, 8192, 8224, 1056768, 1056800, 1056768, 1056800], + pc2bytes11 = [0, 16777216, 512, 16777728, 2097152, 18874368, 2097664, 18874880, 67108864, 83886080, 67109376, 83886592, 69206016, 85983232, 69206528, 85983744], + pc2bytes12 = [0, 4096, 134217728, 134221824, 524288, 528384, 134742016, 134746112, 16, 4112, 134217744, 134221840, 524304, 528400, 134742032, 134746128], + pc2bytes13 = [0, 4, 256, 260, 0, 4, 256, 260, 1, 5, 257, 261, 1, 5, 257, 261]; + var iterations = key.length() > 8 ? 3 : 1; + var keys = []; + var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + var n = 0, + tmp; + for (var j = 0; j < iterations; j++) { + var left = key.getInt32(); + var right = key.getInt32(); + tmp = ((left >>> 4) ^ right) & 252645135; + right ^= tmp; + left ^= tmp << 4; + tmp = ((right >>> -16) ^ left) & 65535; + left ^= tmp; + right ^= tmp << -16; + tmp = ((left >>> 2) ^ right) & 858993459; + right ^= tmp; + left ^= tmp << 2; + tmp = ((right >>> -16) ^ left) & 65535; + left ^= tmp; + right ^= tmp << -16; + tmp = ((left >>> 1) ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + tmp = ((right >>> 8) ^ left) & 16711935; + left ^= tmp; + right ^= tmp << 8; + tmp = ((left >>> 1) ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + tmp = (left << 8) | ((right >>> 20) & 240); + left = (right << 24) | ((right << 8) & 16711680) | ((right >>> 8) & 65280) | ((right >>> 24) & 240); + right = tmp; + for (var i = 0; i < shifts.length; ++i) { + if (shifts[i]) { + left = (left << 2) | (left >>> 26); + right = (right << 2) | (right >>> 26); + } else { + left = (left << 1) | (left >>> 27); + right = (right << 1) | (right >>> 27); + } + left &= -15; + right &= -15; + var lefttmp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 15] | pc2bytes2[(left >>> 20) & 15] | pc2bytes3[(left >>> 16) & 15] | pc2bytes4[(left >>> 12) & 15] | pc2bytes5[(left >>> 8) & 15] | pc2bytes6[(left >>> 4) & 15]; + var righttmp = + pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 15] | pc2bytes9[(right >>> 20) & 15] | pc2bytes10[(right >>> 16) & 15] | pc2bytes11[(right >>> 12) & 15] | pc2bytes12[(right >>> 8) & 15] | pc2bytes13[(right >>> 4) & 15]; + tmp = ((righttmp >>> 16) ^ lefttmp) & 65535; + keys[n++] = lefttmp ^ tmp; + keys[n++] = righttmp ^ (tmp << 16); + } + } + return keys; + }; + var _updateBlock = function (keys, input, output, decrypt) { + var iterations = keys.length === 32 ? 3 : 9; + var looping; + if (iterations === 3) { + looping = decrypt ? [30, -2, -2] : [0, 32, 2]; + } else { + looping = decrypt ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2]; + } + var tmp; + var left = input[0]; + var right = input[1]; + tmp = ((left >>> 4) ^ right) & 252645135; + right ^= tmp; + left ^= tmp << 4; + tmp = ((left >>> 16) ^ right) & 65535; + right ^= tmp; + left ^= tmp << 16; + tmp = ((right >>> 2) ^ left) & 858993459; + left ^= tmp; + right ^= tmp << 2; + tmp = ((right >>> 8) ^ left) & 16711935; + left ^= tmp; + right ^= tmp << 8; + tmp = ((left >>> 1) ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + left = (left << 1) | (left >>> 31); + right = (right << 1) | (right >>> 31); + for (var j = 0; j < iterations; j += 3) { + var endloop = looping[j + 1]; + var loopinc = looping[j + 2]; + for (var i = looping[j]; i != endloop; i += loopinc) { + var right1 = right ^ keys[i]; + var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; + tmp = left; + left = right; + right = + tmp ^ + (spfunction2[(right1 >>> 24) & 63] | + spfunction4[(right1 >>> 16) & 63] | + spfunction6[(right1 >>> 8) & 63] | + spfunction8[right1 & 63] | + spfunction1[(right2 >>> 24) & 63] | + spfunction3[(right2 >>> 16) & 63] | + spfunction5[(right2 >>> 8) & 63] | + spfunction7[right2 & 63]); + } + tmp = left; + left = right; + right = tmp; + } + left = (left >>> 1) | (left << 31); + right = (right >>> 1) | (right << 31); + tmp = ((left >>> 1) ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + tmp = ((right >>> 8) ^ left) & 16711935; + left ^= tmp; + right ^= tmp << 8; + tmp = ((right >>> 2) ^ left) & 858993459; + left ^= tmp; + right ^= tmp << 2; + tmp = ((left >>> 16) ^ right) & 65535; + right ^= tmp; + left ^= tmp << 16; + tmp = ((left >>> 4) ^ right) & 252645135; + right ^= tmp; + left ^= tmp << 4; + output[0] = left; + output[1] = right; + }; + var _createCipher = function (options) { + options = options || {}; + var mode = (options.mode || 'CBC').toUpperCase(); + var algorithm = 'DES-' + mode; + var cipher; + if (options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + var start = cipher.start; + cipher.start = function (iv, options2) { + var output = null; + if (options2 instanceof forge.util.ByteBuffer) { + output = options2; + options2 = {}; + } + options2 = options2 || {}; + options2.output = output; + options2.iv = iv; + start.call(cipher, options2); + }; + return cipher; + }; + var forge = require_forge(); + require_cipher(); + require_cipherModes(); + require_util(); + module.exports = forge.des = forge.des || {}; + forge.des.startEncrypting = function (key, iv, output, mode) { + var cipher = _createCipher({ + key, + output, + decrypt: false, + mode: mode || (iv === null ? 'ECB' : 'CBC') + }); + cipher.start(iv); + return cipher; + }; + forge.des.createEncryptionCipher = function (key, mode) { + return _createCipher({ + key, + output: null, + decrypt: false, + mode + }); + }; + forge.des.startDecrypting = function (key, iv, output, mode) { + var cipher = _createCipher({ + key, + output, + decrypt: true, + mode: mode || (iv === null ? 'ECB' : 'CBC') + }); + cipher.start(iv); + return cipher; + }; + forge.des.createDecryptionCipher = function (key, mode) { + return _createCipher({ + key, + output: null, + decrypt: true, + mode + }); + }; + forge.des.Algorithm = function (name, mode) { + var self2 = this; + self2.name = name; + self2.mode = new mode({ + blockSize: 8, + cipher: { + encrypt: function (inBlock, outBlock) { + return _updateBlock(self2._keys, inBlock, outBlock, false); + }, + decrypt: function (inBlock, outBlock) { + return _updateBlock(self2._keys, inBlock, outBlock, true); + } + } + }); + self2._init = false; + }; + forge.des.Algorithm.prototype.initialize = function (options) { + if (this._init) { + return; + } + var key = forge.util.createBuffer(options.key); + if (this.name.indexOf('3DES') === 0) { + if (key.length() !== 24) { + throw new Error('Invalid Triple-DES key size: ' + key.length() * 8); + } + } + this._keys = _createKeys(key); + this._init = true; + }; + registerAlgorithm('DES-ECB', forge.cipher.modes.ecb); + registerAlgorithm('DES-CBC', forge.cipher.modes.cbc); + registerAlgorithm('DES-CFB', forge.cipher.modes.cfb); + registerAlgorithm('DES-OFB', forge.cipher.modes.ofb); + registerAlgorithm('DES-CTR', forge.cipher.modes.ctr); + registerAlgorithm('3DES-ECB', forge.cipher.modes.ecb); + registerAlgorithm('3DES-CBC', forge.cipher.modes.cbc); + registerAlgorithm('3DES-CFB', forge.cipher.modes.cfb); + registerAlgorithm('3DES-OFB', forge.cipher.modes.ofb); + registerAlgorithm('3DES-CTR', forge.cipher.modes.ctr); + var spfunction1 = [ + 16843776, 0, 65536, 16843780, 16842756, 66564, 4, 65536, 1024, 16843776, 16843780, 1024, 16778244, 16842756, 16777216, 4, 1028, 16778240, 16778240, 66560, 66560, 16842752, 16842752, 16778244, 65540, 16777220, 16777220, 65540, 0, 1028, 66564, + 16777216, 65536, 16843780, 4, 16842752, 16843776, 16777216, 16777216, 1024, 16842756, 65536, 66560, 16777220, 1024, 4, 16778244, 66564, 16843780, 65540, 16842752, 16778244, 16777220, 1028, 66564, 16843776, 1028, 16778240, 16778240, 0, 65540, + 66560, 0, 16842756 + ]; + var spfunction2 = [ + -2146402272, -2147450880, 32768, 1081376, 1048576, 32, -2146435040, -2147450848, -2147483616, -2146402272, -2146402304, -2147483648, -2147450880, 1048576, 32, -2146435040, 1081344, 1048608, -2147450848, 0, -2147483648, 32768, 1081376, + -2146435072, 1048608, -2147483616, 0, 1081344, 32800, -2146402304, -2146435072, 32800, 0, 1081376, -2146435040, 1048576, -2147450848, -2146435072, -2146402304, 32768, -2146435072, -2147450880, 32, -2146402272, 1081376, 32, 32768, -2147483648, + 32800, -2146402304, 1048576, -2147483616, 1048608, -2147450848, -2147483616, 1048608, 1081344, 0, -2147450880, 32800, -2147483648, -2146435040, -2146402272, 1081344 + ]; + var spfunction3 = [ + 520, 134349312, 0, 134348808, 134218240, 0, 131592, 134218240, 131080, 134217736, 134217736, 131072, 134349320, 131080, 134348800, 520, 134217728, 8, 134349312, 512, 131584, 134348800, 134348808, 131592, 134218248, 131584, 131072, 134218248, + 8, 134349320, 512, 134217728, 134349312, 134217728, 131080, 520, 131072, 134349312, 134218240, 0, 512, 131080, 134349320, 134218240, 134217736, 512, 0, 134348808, 134218248, 131072, 134217728, 134349320, 8, 131592, 131584, 134217736, + 134348800, 134218248, 520, 134348800, 131592, 8, 134348808, 131584 + ]; + var spfunction4 = [ + 8396801, 8321, 8321, 128, 8396928, 8388737, 8388609, 8193, 0, 8396800, 8396800, 8396929, 129, 0, 8388736, 8388609, 1, 8192, 8388608, 8396801, 128, 8388608, 8193, 8320, 8388737, 1, 8320, 8388736, 8192, 8396928, 8396929, 129, 8388736, 8388609, + 8396800, 8396929, 129, 0, 0, 8396800, 8320, 8388736, 8388737, 1, 8396801, 8321, 8321, 128, 8396929, 129, 1, 8192, 8388609, 8193, 8396928, 8388737, 8193, 8320, 8388608, 8396801, 128, 8388608, 8192, 8396928 + ]; + var spfunction5 = [ + 256, 34078976, 34078720, 1107296512, 524288, 256, 1073741824, 34078720, 1074266368, 524288, 33554688, 1074266368, 1107296512, 1107820544, 524544, 1073741824, 33554432, 1074266112, 1074266112, 0, 1073742080, 1107820800, 1107820800, 33554688, + 1107820544, 1073742080, 0, 1107296256, 34078976, 33554432, 1107296256, 524544, 524288, 1107296512, 256, 33554432, 1073741824, 34078720, 1107296512, 1074266368, 33554688, 1073741824, 1107820544, 34078976, 1074266368, 256, 33554432, 1107820544, + 1107820800, 524544, 1107296256, 1107820800, 34078720, 0, 1074266112, 1107296256, 524544, 33554688, 1073742080, 524288, 0, 1074266112, 34078976, 1073742080 + ]; + var spfunction6 = [ + 536870928, 541065216, 16384, 541081616, 541065216, 16, 541081616, 4194304, 536887296, 4210704, 4194304, 536870928, 4194320, 536887296, 536870912, 16400, 0, 4194320, 536887312, 16384, 4210688, 536887312, 16, 541065232, 541065232, 0, 4210704, + 541081600, 16400, 4210688, 541081600, 536870912, 536887296, 16, 541065232, 4210688, 541081616, 4194304, 16400, 536870928, 4194304, 536887296, 536870912, 16400, 536870928, 541081616, 4210688, 541065216, 4210704, 541081600, 0, 541065232, 16, + 16384, 541065216, 4210704, 16384, 4194320, 536887312, 0, 541081600, 536870912, 4194320, 536887312 + ]; + var spfunction7 = [ + 2097152, 69206018, 67110914, 0, 2048, 67110914, 2099202, 69208064, 69208066, 2097152, 0, 67108866, 2, 67108864, 69206018, 2050, 67110912, 2099202, 2097154, 67110912, 67108866, 69206016, 69208064, 2097154, 69206016, 2048, 2050, 69208066, + 2099200, 2, 67108864, 2099200, 67108864, 2099200, 2097152, 67110914, 67110914, 69206018, 69206018, 2, 2097154, 67108864, 67110912, 2097152, 69208064, 2050, 2099202, 69208064, 2050, 67108866, 69208066, 69206016, 2099200, 0, 2, 69208066, 0, + 2099202, 69206016, 2048, 67108866, 67110912, 2048, 2097154 + ]; + var spfunction8 = [ + 268439616, 4096, 262144, 268701760, 268435456, 268439616, 64, 268435456, 262208, 268697600, 268701760, 266240, 268701696, 266304, 4096, 64, 268697600, 268435520, 268439552, 4160, 266240, 262208, 268697664, 268701696, 4160, 0, 0, 268697664, + 268435520, 268439552, 266304, 262144, 266304, 262144, 268701696, 4096, 64, 268697664, 4096, 266304, 268439552, 64, 268435520, 268697600, 268697664, 268435456, 262144, 268439616, 0, 268701760, 262208, 268435520, 268697600, 268439552, + 268439616, 0, 268701760, 266240, 266240, 4160, 4160, 262208, 268435456, 268701696 + ]; +}); + +// node:crypto +var exports_crypto = {}; +__export(exports_crypto, { + webcrypto: () => cw, + timingSafeEqual: () => x0, + scryptSync: () => Id, + scrypt: () => Td, + randomUUID: () => lw, + getRandomValues: () => uw, + getCurves: () => dw, + default: () => Wq, + DEFAULT_ENCODING: () => Ga +}); +var dw, + pw, + Xa, + vw, + bw, + mw, + gw, + R0, + T2, + Ja, + Ya, + ot, + rn, + ur, + Nd, + Dd, + Ut, + Te, + on, + Ie, + ki, + W0, + $f, + pc, + Z0, + sn, + V0, + G0, + J0, + hn, + co, + Jf, + po, + Qf, + vo, + Pc, + Oc, + th, + ph, + Qc, + np, + ap, + bh, + Ao, + Bo, + pn, + _p, + Ep, + gh, + qp, + yh, + Op, + ko, + Tt, + Gr, + No, + Jt, + pa, + Rh, + pr, + Y_, + Oi, + Fi, + Ui, + k1, + yn, + Vo, + Go, + Z1, + Xo, + Fh, + ba, + Jh, + Dv, + Qr, + fu, + ou, + os, + eb, + cu, + lb, + bu, + vf, + S7, + db, + yi, + bf, + wb, + mu, + wu, + Mu, + Eb, + _u, + xu, + Eu, + Au, + Ub, + Iu, + Tu, + ar, + vs, + ku, + Yb, + Qb, + em, + im, + nm, + yf, + om, + um, + dm, + pm, + bm, + Pu, + Ou, + Fu, + ws, + Aa, + Em, + Wu, + ju, + Ba, + Dm, + Fm, + Es, + Hm, + Vm, + ji, + Yu, + Ym, + Xm, + As, + tl, + ol, + rg, + ag, + hg, + hl, + pg, + dl, + kn, + cl, + bl, + Ln, + Ds, + Lg, + Dg, + yl, + Il, + Yg, + t2, + i2, + Ws, + Ks, + s2, + ri, + Nl, + or, + Oa, + b2, + y2, + _2, + Pl, + Cr, + Tf, + Cl, + N2, + Fl, + F2, + Wl, + Z2, + V2, + Q2, + ty, + e0, + ny, + t0, + uy, + dy, + vy, + yy, + xy, + Ey, + Iy, + o0, + td, + h0, + u0, + Kf, + d0, + c0, + nd, + Hy, + od, + hd, + Jy, + dd, + r3, + n3, + o3, + cd, + d3, + p3, + v3, + m3, + Ha, + bd, + _3, + A3, + k3, + N3, + P3, + _d, + xd, + w0, + Ed, + j3, + Y3, + X3, + ow, + qd, + Xt, + zq, + Ga, + uw, + lw, + Hq, + x0, + Id, + Td, + cw, + Wq; +var init_crypto = __esm(() => { + dw = function () { + return Hq; + }; + pw = Object.create; + Xa = Object.defineProperty; + vw = Object.getOwnPropertyDescriptor; + bw = Object.getOwnPropertyNames; + mw = Object.getPrototypeOf; + gw = Object.prototype.hasOwnProperty; + R0 = (t, e) => () => (t && (e = t((t = 0))), e); + T2 = (t, e) => () => (e || t((e = {exports: {}}).exports, e), e.exports); + Ja = (t, e) => { + for (var r in e) Xa(t, r, {get: e[r], enumerable: true}); + }; + Ya = (t, e, r, o) => { + if ((e && typeof e == 'object') || typeof e == 'function') for (let f of bw(e)) !gw.call(t, f) && f !== r && Xa(t, f, {get: () => e[f], enumerable: !(o = vw(e, f)) || o.enumerable}); + return t; + }; + ot = (t, e, r) => (Ya(t, e, 'default'), r && Ya(r, e, 'default')); + rn = (t, e, r) => ((r = t != null ? pw(mw(t)) : {}), Ya(e || !t || !t.__esModule ? Xa(r, 'default', {value: t, enumerable: true}) : r, t)); + ur = t => Ya(Xa({}, '__esModule', {value: true}), t); + Nd = T2(Qa => { + Qa.byteLength = ww; + Qa.toByteArray = _w; + Qa.fromByteArray = Ew; + var jr = [], + lr = [], + yw = typeof Uint8Array < 'u' ? Uint8Array : Array, + B0 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (nn = 0, kd = B0.length; nn < kd; ++nn) (jr[nn] = B0[nn]), (lr[B0.charCodeAt(nn)] = nn); + var nn, kd; + lr['-'.charCodeAt(0)] = 62; + lr['_'.charCodeAt(0)] = 63; + function Ld(t) { + var e = t.length; + if (e % 4 > 0) throw new Error('Invalid string. Length must be a multiple of 4'); + var r = t.indexOf('='); + r === -1 && (r = e); + var o = r === e ? 0 : 4 - (r % 4); + return [r, o]; + } + function ww(t) { + var e = Ld(t), + r = e[0], + o = e[1]; + return ((r + o) * 3) / 4 - o; + } + function Mw(t, e, r) { + return ((e + r) * 3) / 4 - r; + } + function _w(t) { + var e, + r = Ld(t), + o = r[0], + f = r[1], + p = new yw(Mw(t, o, f)), + m2 = 0, + y2 = f > 0 ? o - 4 : o, + M; + for (M = 0; M < y2; M += 4) (e = (lr[t.charCodeAt(M)] << 18) | (lr[t.charCodeAt(M + 1)] << 12) | (lr[t.charCodeAt(M + 2)] << 6) | lr[t.charCodeAt(M + 3)]), (p[m2++] = (e >> 16) & 255), (p[m2++] = (e >> 8) & 255), (p[m2++] = e & 255); + return ( + f === 2 && ((e = (lr[t.charCodeAt(M)] << 2) | (lr[t.charCodeAt(M + 1)] >> 4)), (p[m2++] = e & 255)), + f === 1 && ((e = (lr[t.charCodeAt(M)] << 10) | (lr[t.charCodeAt(M + 1)] << 4) | (lr[t.charCodeAt(M + 2)] >> 2)), (p[m2++] = (e >> 8) & 255), (p[m2++] = e & 255)), + p + ); + } + function xw(t) { + return jr[(t >> 18) & 63] + jr[(t >> 12) & 63] + jr[(t >> 6) & 63] + jr[t & 63]; + } + function Sw(t, e, r) { + for (var o, f = [], p = e; p < r; p += 3) (o = ((t[p] << 16) & 16711680) + ((t[p + 1] << 8) & 65280) + (t[p + 2] & 255)), f.push(xw(o)); + return f.join(''); + } + function Ew(t) { + for (var e, r = t.length, o = r % 3, f = [], p = 16383, m2 = 0, y2 = r - o; m2 < y2; m2 += p) f.push(Sw(t, m2, m2 + p > y2 ? y2 : m2 + p)); + return o === 1 ? ((e = t[r - 1]), f.push(jr[e >> 2] + jr[(e << 4) & 63] + '==')) : o === 2 && ((e = (t[r - 2] << 8) + t[r - 1]), f.push(jr[e >> 10] + jr[(e >> 4) & 63] + jr[(e << 2) & 63] + '=')), f.join(''); + } + }); + Dd = T2(q0 => { + q0.read = function (t, e, r, o, f) { + var p, + m2, + y2 = f * 8 - o - 1, + M = (1 << y2) - 1, + x = M >> 1, + S = -7, + E2 = r ? f - 1 : 0, + B = r ? -1 : 1, + q2 = t[e + E2]; + for (E2 += B, p = q2 & ((1 << -S) - 1), q2 >>= -S, S += y2; S > 0; p = p * 256 + t[e + E2], E2 += B, S -= 8); + for (m2 = p & ((1 << -S) - 1), p >>= -S, S += o; S > 0; m2 = m2 * 256 + t[e + E2], E2 += B, S -= 8); + if (p === 0) p = 1 - x; + else { + if (p === M) return m2 ? NaN : (q2 ? -1 : 1) * (1 / 0); + (m2 = m2 + Math.pow(2, o)), (p = p - x); + } + return (q2 ? -1 : 1) * m2 * Math.pow(2, p - o); + }; + q0.write = function (t, e, r, o, f, p) { + var m2, + y2, + M, + x = p * 8 - f - 1, + S = (1 << x) - 1, + E2 = S >> 1, + B = f === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, + q2 = o ? 0 : p - 1, + L2 = o ? 1 : -1, + ge = e < 0 || (e === 0 && 1 / e < 0) ? 1 : 0; + for ( + e = Math.abs(e), + isNaN(e) || e === 1 / 0 + ? ((y2 = isNaN(e) ? 1 : 0), (m2 = S)) + : ((m2 = Math.floor(Math.log(e) / Math.LN2)), + e * (M = Math.pow(2, -m2)) < 1 && (m2--, (M *= 2)), + m2 + E2 >= 1 ? (e += B / M) : (e += B * Math.pow(2, 1 - E2)), + e * M >= 2 && (m2++, (M /= 2)), + m2 + E2 >= S ? ((y2 = 0), (m2 = S)) : m2 + E2 >= 1 ? ((y2 = (e * M - 1) * Math.pow(2, f)), (m2 = m2 + E2)) : ((y2 = e * Math.pow(2, E2 - 1) * Math.pow(2, f)), (m2 = 0))); + f >= 8; + t[r + q2] = y2 & 255, q2 += L2, y2 /= 256, f -= 8 + ); + for (m2 = (m2 << f) | y2, x += f; x > 0; t[r + q2] = m2 & 255, q2 += L2, m2 /= 256, x -= 8); + t[r + q2 - L2] |= ge * 128; + }; + }); + Ut = T2(Xn => { + var I0 = Nd(), + Gn = Dd(), + Pd = typeof Symbol == 'function' && typeof Symbol.for == 'function' ? Symbol.for('nodejs.util.inspect.custom') : null; + Xn.Buffer = me; + Xn.SlowBuffer = Tw; + Xn.INSPECT_MAX_BYTES = 50; + var eo = 2147483647; + Xn.kMaxLength = eo; + me.TYPED_ARRAY_SUPPORT = Aw(); + !me.TYPED_ARRAY_SUPPORT && + typeof console < 'u' && + 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 Aw() { + try { + let t = new Uint8Array(1), + e = { + foo: function () { + return 42; + } + }; + return Object.setPrototypeOf(e, Uint8Array.prototype), Object.setPrototypeOf(t, e), t.foo() === 42; + } catch { + return false; + } + } + Object.defineProperty(me.prototype, 'parent', { + enumerable: true, + get: function () { + if (!!me.isBuffer(this)) return this.buffer; + } + }); + Object.defineProperty(me.prototype, 'offset', { + enumerable: true, + get: function () { + if (!!me.isBuffer(this)) return this.byteOffset; + } + }); + function li(t) { + if (t > eo) throw new RangeError('The value "' + t + '" is invalid for option "size"'); + let e = new Uint8Array(t); + return Object.setPrototypeOf(e, me.prototype), e; + } + function me(t, e, r) { + if (typeof t == 'number') { + if (typeof e == 'string') throw new TypeError('The "string" argument must be of type string. Received type number'); + return N0(t); + } + return Ud(t, e, r); + } + me.poolSize = 8192; + function Ud(t, e, r) { + if (typeof t == 'string') return Bw(t, e); + if (ArrayBuffer.isView(t)) return qw(t); + if (t == null) throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof t); + if (Zr(t, ArrayBuffer) || (t && Zr(t.buffer, ArrayBuffer)) || (typeof SharedArrayBuffer < 'u' && (Zr(t, SharedArrayBuffer) || (t && Zr(t.buffer, SharedArrayBuffer))))) return k0(t, e, r); + if (typeof t == 'number') throw new TypeError('The "value" argument must not be of type number. Received type number'); + let o = t.valueOf && t.valueOf(); + if (o != null && o !== t) return me.from(o, e, r); + let f = Iw(t); + if (f) return f; + if (typeof Symbol < 'u' && Symbol.toPrimitive != null && typeof t[Symbol.toPrimitive] == 'function') return me.from(t[Symbol.toPrimitive]('string'), e, r); + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof t); + } + me.from = function (t, e, r) { + return Ud(t, e, r); + }; + Object.setPrototypeOf(me.prototype, Uint8Array.prototype); + Object.setPrototypeOf(me, Uint8Array); + function zd(t) { + if (typeof t != 'number') throw new TypeError('"size" argument must be of type number'); + if (t < 0) throw new RangeError('The value "' + t + '" is invalid for option "size"'); + } + function Rw(t, e, r) { + return zd(t), t <= 0 ? li(t) : e !== undefined ? (typeof r == 'string' ? li(t).fill(e, r) : li(t).fill(e)) : li(t); + } + me.alloc = function (t, e, r) { + return Rw(t, e, r); + }; + function N0(t) { + return zd(t), li(t < 0 ? 0 : D0(t) | 0); + } + me.allocUnsafe = function (t) { + return N0(t); + }; + me.allocUnsafeSlow = function (t) { + return N0(t); + }; + function Bw(t, e) { + if (((typeof e != 'string' || e === '') && (e = 'utf8'), !me.isEncoding(e))) throw new TypeError('Unknown encoding: ' + e); + let r = Hd(t, e) | 0, + o = li(r), + f = o.write(t, e); + return f !== r && (o = o.slice(0, f)), o; + } + function T0(t) { + let e = t.length < 0 ? 0 : D0(t.length) | 0, + r = li(e); + for (let o = 0; o < e; o += 1) r[o] = t[o] & 255; + return r; + } + function qw(t) { + if (Zr(t, Uint8Array)) { + let e = new Uint8Array(t); + return k0(e.buffer, e.byteOffset, e.byteLength); + } + return T0(t); + } + function k0(t, e, r) { + if (e < 0 || t.byteLength < e) throw new RangeError('"offset" is outside of buffer bounds'); + if (t.byteLength < e + (r || 0)) throw new RangeError('"length" is outside of buffer bounds'); + let o; + return e === undefined && r === undefined ? (o = new Uint8Array(t)) : r === undefined ? (o = new Uint8Array(t, e)) : (o = new Uint8Array(t, e, r)), Object.setPrototypeOf(o, me.prototype), o; + } + function Iw(t) { + if (me.isBuffer(t)) { + let e = D0(t.length) | 0, + r = li(e); + return r.length === 0 || t.copy(r, 0, 0, e), r; + } + if (t.length !== undefined) return typeof t.length != 'number' || C0(t.length) ? li(0) : T0(t); + if (t.type === 'Buffer' && Array.isArray(t.data)) return T0(t.data); + } + function D0(t) { + if (t >= eo) throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' + eo.toString(16) + ' bytes'); + return t | 0; + } + function Tw(t) { + return +t != t && (t = 0), me.alloc(+t); + } + me.isBuffer = function (e) { + return e != null && e._isBuffer === true && e !== me.prototype; + }; + me.compare = function (e, r) { + if ((Zr(e, Uint8Array) && (e = me.from(e, e.offset, e.byteLength)), Zr(r, Uint8Array) && (r = me.from(r, r.offset, r.byteLength)), !me.isBuffer(e) || !me.isBuffer(r))) + throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); + if (e === r) return 0; + let o = e.length, + f = r.length; + for (let p = 0, m2 = Math.min(o, f); p < m2; ++p) + if (e[p] !== r[p]) { + (o = e[p]), (f = r[p]); + break; + } + return o < f ? -1 : f < o ? 1 : 0; + }; + me.isEncoding = function (e) { + switch (String(e).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; + } + }; + me.concat = function (e, r) { + if (!Array.isArray(e)) throw new TypeError('"list" argument must be an Array of Buffers'); + if (e.length === 0) return me.alloc(0); + let o; + if (r === undefined) for (r = 0, o = 0; o < e.length; ++o) r += e[o].length; + let f = me.allocUnsafe(r), + p = 0; + for (o = 0; o < e.length; ++o) { + let m2 = e[o]; + if (Zr(m2, Uint8Array)) p + m2.length > f.length ? (me.isBuffer(m2) || (m2 = me.from(m2)), m2.copy(f, p)) : Uint8Array.prototype.set.call(f, m2, p); + else if (me.isBuffer(m2)) m2.copy(f, p); + else throw new TypeError('"list" argument must be an Array of Buffers'); + p += m2.length; + } + return f; + }; + function Hd(t, e) { + if (me.isBuffer(t)) return t.length; + if (ArrayBuffer.isView(t) || Zr(t, ArrayBuffer)) return t.byteLength; + if (typeof t != 'string') throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof t); + let r = t.length, + o = arguments.length > 2 && arguments[2] === true; + if (!o && r === 0) return 0; + let f = false; + for (;;) + switch (e) { + case 'ascii': + case 'latin1': + case 'binary': + return r; + case 'utf8': + case 'utf-8': + return L0(t).length; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return r * 2; + case 'hex': + return r >>> 1; + case 'base64': + return Xd(t).length; + default: + if (f) return o ? -1 : L0(t).length; + (e = ('' + e).toLowerCase()), (f = true); + } + } + me.byteLength = Hd; + function kw(t, e, r) { + let o = false; + if (((e === undefined || e < 0) && (e = 0), e > this.length || ((r === undefined || r > this.length) && (r = this.length), r <= 0) || ((r >>>= 0), (e >>>= 0), r <= e))) return ''; + for (t || (t = 'utf8'); ; ) + switch (t) { + case 'hex': + return Hw(this, e, r); + case 'utf8': + case 'utf-8': + return Kd(this, e, r); + case 'ascii': + return Uw(this, e, r); + case 'latin1': + case 'binary': + return zw(this, e, r); + case 'base64': + return Ow(this, e, r); + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return Ww(this, e, r); + default: + if (o) throw new TypeError('Unknown encoding: ' + t); + (t = (t + '').toLowerCase()), (o = true); + } + } + me.prototype._isBuffer = true; + function fn(t, e, r) { + let o = t[e]; + (t[e] = t[r]), (t[r] = o); + } + me.prototype.swap16 = function () { + let e = this.length; + if (e % 2 !== 0) throw new RangeError('Buffer size must be a multiple of 16-bits'); + for (let r = 0; r < e; r += 2) fn(this, r, r + 1); + return this; + }; + me.prototype.swap32 = function () { + let e = this.length; + if (e % 4 !== 0) throw new RangeError('Buffer size must be a multiple of 32-bits'); + for (let r = 0; r < e; r += 4) fn(this, r, r + 3), fn(this, r + 1, r + 2); + return this; + }; + me.prototype.swap64 = function () { + let e = this.length; + if (e % 8 !== 0) throw new RangeError('Buffer size must be a multiple of 64-bits'); + for (let r = 0; r < e; r += 8) fn(this, r, r + 7), fn(this, r + 1, r + 6), fn(this, r + 2, r + 5), fn(this, r + 3, r + 4); + return this; + }; + me.prototype.toString = function () { + let e = this.length; + return e === 0 ? '' : arguments.length === 0 ? Kd(this, 0, e) : kw.apply(this, arguments); + }; + me.prototype.toLocaleString = me.prototype.toString; + me.prototype.equals = function (e) { + if (!me.isBuffer(e)) throw new TypeError('Argument must be a Buffer'); + return this === e ? true : me.compare(this, e) === 0; + }; + me.prototype.inspect = function () { + let e = '', + r = Xn.INSPECT_MAX_BYTES; + return ( + (e = this.toString('hex', 0, r) + .replace(/(.{2})/g, '$1 ') + .trim()), + this.length > r && (e += ' ... '), + '' + ); + }; + Pd && (me.prototype[Pd] = me.prototype.inspect); + me.prototype.compare = function (e, r, o, f, p) { + if ((Zr(e, Uint8Array) && (e = me.from(e, e.offset, e.byteLength)), !me.isBuffer(e))) throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof e); + if ((r === undefined && (r = 0), o === undefined && (o = e ? e.length : 0), f === undefined && (f = 0), p === undefined && (p = this.length), r < 0 || o > e.length || f < 0 || p > this.length)) throw new RangeError('out of range index'); + if (f >= p && r >= o) return 0; + if (f >= p) return -1; + if (r >= o) return 1; + if (((r >>>= 0), (o >>>= 0), (f >>>= 0), (p >>>= 0), this === e)) return 0; + let m2 = p - f, + y2 = o - r, + M = Math.min(m2, y2), + x = this.slice(f, p), + S = e.slice(r, o); + for (let E2 = 0; E2 < M; ++E2) + if (x[E2] !== S[E2]) { + (m2 = x[E2]), (y2 = S[E2]); + break; + } + return m2 < y2 ? -1 : y2 < m2 ? 1 : 0; + }; + function Wd(t, e, r, o, f) { + if (t.length === 0) return -1; + if ((typeof r == 'string' ? ((o = r), (r = 0)) : r > 2147483647 ? (r = 2147483647) : r < -2147483648 && (r = -2147483648), (r = +r), C0(r) && (r = f ? 0 : t.length - 1), r < 0 && (r = t.length + r), r >= t.length)) { + if (f) return -1; + r = t.length - 1; + } else if (r < 0) + if (f) r = 0; + else return -1; + if ((typeof e == 'string' && (e = me.from(e, o)), me.isBuffer(e))) return e.length === 0 ? -1 : Cd(t, e, r, o, f); + if (typeof e == 'number') return (e = e & 255), typeof Uint8Array.prototype.indexOf == 'function' ? (f ? Uint8Array.prototype.indexOf.call(t, e, r) : Uint8Array.prototype.lastIndexOf.call(t, e, r)) : Cd(t, [e], r, o, f); + throw new TypeError('val must be string, number or Buffer'); + } + function Cd(t, e, r, o, f) { + let p = 1, + m2 = t.length, + y2 = e.length; + if (o !== undefined && ((o = String(o).toLowerCase()), o === 'ucs2' || o === 'ucs-2' || o === 'utf16le' || o === 'utf-16le')) { + if (t.length < 2 || e.length < 2) return -1; + (p = 2), (m2 /= 2), (y2 /= 2), (r /= 2); + } + function M(S, E2) { + return p === 1 ? S[E2] : S.readUInt16BE(E2 * p); + } + let x; + if (f) { + let S = -1; + for (x = r; x < m2; x++) + if (M(t, x) === M(e, S === -1 ? 0 : x - S)) { + if ((S === -1 && (S = x), x - S + 1 === y2)) return S * p; + } else S !== -1 && (x -= x - S), (S = -1); + } else + for (r + y2 > m2 && (r = m2 - y2), x = r; x >= 0; x--) { + let S = true; + for (let E2 = 0; E2 < y2; E2++) + if (M(t, x + E2) !== M(e, E2)) { + S = false; + break; + } + if (S) return x; + } + return -1; + } + me.prototype.includes = function (e, r, o) { + return this.indexOf(e, r, o) !== -1; + }; + me.prototype.indexOf = function (e, r, o) { + return Wd(this, e, r, o, true); + }; + me.prototype.lastIndexOf = function (e, r, o) { + return Wd(this, e, r, o, false); + }; + function Lw(t, e, r, o) { + r = Number(r) || 0; + let f = t.length - r; + o ? ((o = Number(o)), o > f && (o = f)) : (o = f); + let p = e.length; + o > p / 2 && (o = p / 2); + let m2; + for (m2 = 0; m2 < o; ++m2) { + let y2 = parseInt(e.substr(m2 * 2, 2), 16); + if (C0(y2)) return m2; + t[r + m2] = y2; + } + return m2; + } + function Nw(t, e, r, o) { + return to(L0(e, t.length - r), t, r, o); + } + function Dw(t, e, r, o) { + return to(Vw(e), t, r, o); + } + function Pw(t, e, r, o) { + return to(Xd(e), t, r, o); + } + function Cw(t, e, r, o) { + return to($w(e, t.length - r), t, r, o); + } + me.prototype.write = function (e, r, o, f) { + if (r === undefined) (f = 'utf8'), (o = this.length), (r = 0); + else if (o === undefined && typeof r == 'string') (f = r), (o = this.length), (r = 0); + else if (isFinite(r)) (r = r >>> 0), isFinite(o) ? ((o = o >>> 0), f === undefined && (f = 'utf8')) : ((f = o), (o = undefined)); + else throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); + let p = this.length - r; + if (((o === undefined || o > p) && (o = p), (e.length > 0 && (o < 0 || r < 0)) || r > this.length)) throw new RangeError('Attempt to write outside buffer bounds'); + f || (f = 'utf8'); + let m2 = false; + for (;;) + switch (f) { + case 'hex': + return Lw(this, e, r, o); + case 'utf8': + case 'utf-8': + return Nw(this, e, r, o); + case 'ascii': + case 'latin1': + case 'binary': + return Dw(this, e, r, o); + case 'base64': + return Pw(this, e, r, o); + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return Cw(this, e, r, o); + default: + if (m2) throw new TypeError('Unknown encoding: ' + f); + (f = ('' + f).toLowerCase()), (m2 = true); + } + }; + me.prototype.toJSON = function () { + return {type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0)}; + }; + function Ow(t, e, r) { + return e === 0 && r === t.length ? I0.fromByteArray(t) : I0.fromByteArray(t.slice(e, r)); + } + function Kd(t, e, r) { + r = Math.min(t.length, r); + let o = [], + f = e; + for (; f < r; ) { + let p = t[f], + m2 = null, + y2 = p > 239 ? 4 : p > 223 ? 3 : p > 191 ? 2 : 1; + if (f + y2 <= r) { + let M, x, S, E2; + switch (y2) { + case 1: + p < 128 && (m2 = p); + break; + case 2: + (M = t[f + 1]), (M & 192) === 128 && ((E2 = ((p & 31) << 6) | (M & 63)), E2 > 127 && (m2 = E2)); + break; + case 3: + (M = t[f + 1]), (x = t[f + 2]), (M & 192) === 128 && (x & 192) === 128 && ((E2 = ((p & 15) << 12) | ((M & 63) << 6) | (x & 63)), E2 > 2047 && (E2 < 55296 || E2 > 57343) && (m2 = E2)); + break; + case 4: + (M = t[f + 1]), + (x = t[f + 2]), + (S = t[f + 3]), + (M & 192) === 128 && (x & 192) === 128 && (S & 192) === 128 && ((E2 = ((p & 15) << 18) | ((M & 63) << 12) | ((x & 63) << 6) | (S & 63)), E2 > 65535 && E2 < 1114112 && (m2 = E2)); + } + } + m2 === null ? ((m2 = 65533), (y2 = 1)) : m2 > 65535 && ((m2 -= 65536), o.push(((m2 >>> 10) & 1023) | 55296), (m2 = 56320 | (m2 & 1023))), o.push(m2), (f += y2); + } + return Fw(o); + } + var Od = 4096; + function Fw(t) { + let e = t.length; + if (e <= Od) return String.fromCharCode.apply(String, t); + let r = '', + o = 0; + for (; o < e; ) r += String.fromCharCode.apply(String, t.slice(o, (o += Od))); + return r; + } + function Uw(t, e, r) { + let o = ''; + r = Math.min(t.length, r); + for (let f = e; f < r; ++f) o += String.fromCharCode(t[f] & 127); + return o; + } + function zw(t, e, r) { + let o = ''; + r = Math.min(t.length, r); + for (let f = e; f < r; ++f) o += String.fromCharCode(t[f]); + return o; + } + function Hw(t, e, r) { + let o = t.length; + (!e || e < 0) && (e = 0), (!r || r < 0 || r > o) && (r = o); + let f = ''; + for (let p = e; p < r; ++p) f += Gw[t[p]]; + return f; + } + function Ww(t, e, r) { + let o = t.slice(e, r), + f = ''; + for (let p = 0; p < o.length - 1; p += 2) f += String.fromCharCode(o[p] + o[p + 1] * 256); + return f; + } + me.prototype.slice = function (e, r) { + let o = this.length; + (e = ~~e), (r = r === undefined ? o : ~~r), e < 0 ? ((e += o), e < 0 && (e = 0)) : e > o && (e = o), r < 0 ? ((r += o), r < 0 && (r = 0)) : r > o && (r = o), r < e && (r = e); + let f = this.subarray(e, r); + return Object.setPrototypeOf(f, me.prototype), f; + }; + function Dt(t, e, r) { + if (t % 1 !== 0 || t < 0) throw new RangeError('offset is not uint'); + if (t + e > r) throw new RangeError('Trying to access beyond buffer length'); + } + me.prototype.readUintLE = me.prototype.readUIntLE = function (e, r, o) { + (e = e >>> 0), (r = r >>> 0), o || Dt(e, r, this.length); + let f = this[e], + p = 1, + m2 = 0; + for (; ++m2 < r && (p *= 256); ) f += this[e + m2] * p; + return f; + }; + me.prototype.readUintBE = me.prototype.readUIntBE = function (e, r, o) { + (e = e >>> 0), (r = r >>> 0), o || Dt(e, r, this.length); + let f = this[e + --r], + p = 1; + for (; r > 0 && (p *= 256); ) f += this[e + --r] * p; + return f; + }; + me.prototype.readUint8 = me.prototype.readUInt8 = function (e, r) { + return (e = e >>> 0), r || Dt(e, 1, this.length), this[e]; + }; + me.prototype.readUint16LE = me.prototype.readUInt16LE = function (e, r) { + return (e = e >>> 0), r || Dt(e, 2, this.length), this[e] | (this[e + 1] << 8); + }; + me.prototype.readUint16BE = me.prototype.readUInt16BE = function (e, r) { + return (e = e >>> 0), r || Dt(e, 2, this.length), (this[e] << 8) | this[e + 1]; + }; + me.prototype.readUint32LE = me.prototype.readUInt32LE = function (e, r) { + return (e = e >>> 0), r || Dt(e, 4, this.length), (this[e] | (this[e + 1] << 8) | (this[e + 2] << 16)) + this[e + 3] * 16777216; + }; + me.prototype.readUint32BE = me.prototype.readUInt32BE = function (e, r) { + return (e = e >>> 0), r || Dt(e, 4, this.length), this[e] * 16777216 + ((this[e + 1] << 16) | (this[e + 2] << 8) | this[e + 3]); + }; + me.prototype.readBigUInt64LE = Ti(function (e) { + (e = e >>> 0), Yn(e, 'offset'); + let r = this[e], + o = this[e + 7]; + (r === undefined || o === undefined) && Vf(e, this.length - 8); + let f = r + this[++e] * 2 ** 8 + this[++e] * 2 ** 16 + this[++e] * 2 ** 24, + p = this[++e] + this[++e] * 2 ** 8 + this[++e] * 2 ** 16 + o * 2 ** 24; + return BigInt(f) + (BigInt(p) << BigInt(32)); + }); + me.prototype.readBigUInt64BE = Ti(function (e) { + (e = e >>> 0), Yn(e, 'offset'); + let r = this[e], + o = this[e + 7]; + (r === undefined || o === undefined) && Vf(e, this.length - 8); + let f = r * 2 ** 24 + this[++e] * 2 ** 16 + this[++e] * 2 ** 8 + this[++e], + p = this[++e] * 2 ** 24 + this[++e] * 2 ** 16 + this[++e] * 2 ** 8 + o; + return (BigInt(f) << BigInt(32)) + BigInt(p); + }); + me.prototype.readIntLE = function (e, r, o) { + (e = e >>> 0), (r = r >>> 0), o || Dt(e, r, this.length); + let f = this[e], + p = 1, + m2 = 0; + for (; ++m2 < r && (p *= 256); ) f += this[e + m2] * p; + return (p *= 128), f >= p && (f -= Math.pow(2, 8 * r)), f; + }; + me.prototype.readIntBE = function (e, r, o) { + (e = e >>> 0), (r = r >>> 0), o || Dt(e, r, this.length); + let f = r, + p = 1, + m2 = this[e + --f]; + for (; f > 0 && (p *= 256); ) m2 += this[e + --f] * p; + return (p *= 128), m2 >= p && (m2 -= Math.pow(2, 8 * r)), m2; + }; + me.prototype.readInt8 = function (e, r) { + return (e = e >>> 0), r || Dt(e, 1, this.length), this[e] & 128 ? (255 - this[e] + 1) * -1 : this[e]; + }; + me.prototype.readInt16LE = function (e, r) { + (e = e >>> 0), r || Dt(e, 2, this.length); + let o = this[e] | (this[e + 1] << 8); + return o & 32768 ? o | 4294901760 : o; + }; + me.prototype.readInt16BE = function (e, r) { + (e = e >>> 0), r || Dt(e, 2, this.length); + let o = this[e + 1] | (this[e] << 8); + return o & 32768 ? o | 4294901760 : o; + }; + me.prototype.readInt32LE = function (e, r) { + return (e = e >>> 0), r || Dt(e, 4, this.length), this[e] | (this[e + 1] << 8) | (this[e + 2] << 16) | (this[e + 3] << 24); + }; + me.prototype.readInt32BE = function (e, r) { + return (e = e >>> 0), r || Dt(e, 4, this.length), (this[e] << 24) | (this[e + 1] << 16) | (this[e + 2] << 8) | this[e + 3]; + }; + me.prototype.readBigInt64LE = Ti(function (e) { + (e = e >>> 0), Yn(e, 'offset'); + let r = this[e], + o = this[e + 7]; + (r === undefined || o === undefined) && Vf(e, this.length - 8); + let f = this[e + 4] + this[e + 5] * 2 ** 8 + this[e + 6] * 2 ** 16 + (o << 24); + return (BigInt(f) << BigInt(32)) + BigInt(r + this[++e] * 2 ** 8 + this[++e] * 2 ** 16 + this[++e] * 2 ** 24); + }); + me.prototype.readBigInt64BE = Ti(function (e) { + (e = e >>> 0), Yn(e, 'offset'); + let r = this[e], + o = this[e + 7]; + (r === undefined || o === undefined) && Vf(e, this.length - 8); + let f = (r << 24) + this[++e] * 2 ** 16 + this[++e] * 2 ** 8 + this[++e]; + return (BigInt(f) << BigInt(32)) + BigInt(this[++e] * 2 ** 24 + this[++e] * 2 ** 16 + this[++e] * 2 ** 8 + o); + }); + me.prototype.readFloatLE = function (e, r) { + return (e = e >>> 0), r || Dt(e, 4, this.length), Gn.read(this, e, true, 23, 4); + }; + me.prototype.readFloatBE = function (e, r) { + return (e = e >>> 0), r || Dt(e, 4, this.length), Gn.read(this, e, false, 23, 4); + }; + me.prototype.readDoubleLE = function (e, r) { + return (e = e >>> 0), r || Dt(e, 8, this.length), Gn.read(this, e, true, 52, 8); + }; + me.prototype.readDoubleBE = function (e, r) { + return (e = e >>> 0), r || Dt(e, 8, this.length), Gn.read(this, e, false, 52, 8); + }; + function er(t, e, r, o, f, p) { + if (!me.isBuffer(t)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (e > f || e < p) throw new RangeError('"value" argument is out of bounds'); + if (r + o > t.length) throw new RangeError('Index out of range'); + } + me.prototype.writeUintLE = me.prototype.writeUIntLE = function (e, r, o, f) { + if (((e = +e), (r = r >>> 0), (o = o >>> 0), !f)) { + let y2 = Math.pow(2, 8 * o) - 1; + er(this, e, r, o, y2, 0); + } + let p = 1, + m2 = 0; + for (this[r] = e & 255; ++m2 < o && (p *= 256); ) this[r + m2] = (e / p) & 255; + return r + o; + }; + me.prototype.writeUintBE = me.prototype.writeUIntBE = function (e, r, o, f) { + if (((e = +e), (r = r >>> 0), (o = o >>> 0), !f)) { + let y2 = Math.pow(2, 8 * o) - 1; + er(this, e, r, o, y2, 0); + } + let p = o - 1, + m2 = 1; + for (this[r + p] = e & 255; --p >= 0 && (m2 *= 256); ) this[r + p] = (e / m2) & 255; + return r + o; + }; + me.prototype.writeUint8 = me.prototype.writeUInt8 = function (e, r, o) { + return (e = +e), (r = r >>> 0), o || er(this, e, r, 1, 255, 0), (this[r] = e & 255), r + 1; + }; + me.prototype.writeUint16LE = me.prototype.writeUInt16LE = function (e, r, o) { + return (e = +e), (r = r >>> 0), o || er(this, e, r, 2, 65535, 0), (this[r] = e & 255), (this[r + 1] = e >>> 8), r + 2; + }; + me.prototype.writeUint16BE = me.prototype.writeUInt16BE = function (e, r, o) { + return (e = +e), (r = r >>> 0), o || er(this, e, r, 2, 65535, 0), (this[r] = e >>> 8), (this[r + 1] = e & 255), r + 2; + }; + me.prototype.writeUint32LE = me.prototype.writeUInt32LE = function (e, r, o) { + return (e = +e), (r = r >>> 0), o || er(this, e, r, 4, 4294967295, 0), (this[r + 3] = e >>> 24), (this[r + 2] = e >>> 16), (this[r + 1] = e >>> 8), (this[r] = e & 255), r + 4; + }; + me.prototype.writeUint32BE = me.prototype.writeUInt32BE = function (e, r, o) { + return (e = +e), (r = r >>> 0), o || er(this, e, r, 4, 4294967295, 0), (this[r] = e >>> 24), (this[r + 1] = e >>> 16), (this[r + 2] = e >>> 8), (this[r + 3] = e & 255), r + 4; + }; + function jd(t, e, r, o, f) { + Yd(e, o, f, t, r, 7); + let p = Number(e & BigInt(4294967295)); + (t[r++] = p), (p = p >> 8), (t[r++] = p), (p = p >> 8), (t[r++] = p), (p = p >> 8), (t[r++] = p); + let m2 = Number((e >> BigInt(32)) & BigInt(4294967295)); + return (t[r++] = m2), (m2 = m2 >> 8), (t[r++] = m2), (m2 = m2 >> 8), (t[r++] = m2), (m2 = m2 >> 8), (t[r++] = m2), r; + } + function Zd(t, e, r, o, f) { + Yd(e, o, f, t, r, 7); + let p = Number(e & BigInt(4294967295)); + (t[r + 7] = p), (p = p >> 8), (t[r + 6] = p), (p = p >> 8), (t[r + 5] = p), (p = p >> 8), (t[r + 4] = p); + let m2 = Number((e >> BigInt(32)) & BigInt(4294967295)); + return (t[r + 3] = m2), (m2 = m2 >> 8), (t[r + 2] = m2), (m2 = m2 >> 8), (t[r + 1] = m2), (m2 = m2 >> 8), (t[r] = m2), r + 8; + } + me.prototype.writeBigUInt64LE = Ti(function (e, r = 0) { + return jd(this, e, r, BigInt(0), BigInt('0xffffffffffffffff')); + }); + me.prototype.writeBigUInt64BE = Ti(function (e, r = 0) { + return Zd(this, e, r, BigInt(0), BigInt('0xffffffffffffffff')); + }); + me.prototype.writeIntLE = function (e, r, o, f) { + if (((e = +e), (r = r >>> 0), !f)) { + let M = Math.pow(2, 8 * o - 1); + er(this, e, r, o, M - 1, -M); + } + let p = 0, + m2 = 1, + y2 = 0; + for (this[r] = e & 255; ++p < o && (m2 *= 256); ) e < 0 && y2 === 0 && this[r + p - 1] !== 0 && (y2 = 1), (this[r + p] = (((e / m2) >> 0) - y2) & 255); + return r + o; + }; + me.prototype.writeIntBE = function (e, r, o, f) { + if (((e = +e), (r = r >>> 0), !f)) { + let M = Math.pow(2, 8 * o - 1); + er(this, e, r, o, M - 1, -M); + } + let p = o - 1, + m2 = 1, + y2 = 0; + for (this[r + p] = e & 255; --p >= 0 && (m2 *= 256); ) e < 0 && y2 === 0 && this[r + p + 1] !== 0 && (y2 = 1), (this[r + p] = (((e / m2) >> 0) - y2) & 255); + return r + o; + }; + me.prototype.writeInt8 = function (e, r, o) { + return (e = +e), (r = r >>> 0), o || er(this, e, r, 1, 127, -128), e < 0 && (e = 255 + e + 1), (this[r] = e & 255), r + 1; + }; + me.prototype.writeInt16LE = function (e, r, o) { + return (e = +e), (r = r >>> 0), o || er(this, e, r, 2, 32767, -32768), (this[r] = e & 255), (this[r + 1] = e >>> 8), r + 2; + }; + me.prototype.writeInt16BE = function (e, r, o) { + return (e = +e), (r = r >>> 0), o || er(this, e, r, 2, 32767, -32768), (this[r] = e >>> 8), (this[r + 1] = e & 255), r + 2; + }; + me.prototype.writeInt32LE = function (e, r, o) { + return (e = +e), (r = r >>> 0), o || er(this, e, r, 4, 2147483647, -2147483648), (this[r] = e & 255), (this[r + 1] = e >>> 8), (this[r + 2] = e >>> 16), (this[r + 3] = e >>> 24), r + 4; + }; + me.prototype.writeInt32BE = function (e, r, o) { + return (e = +e), (r = r >>> 0), o || er(this, e, r, 4, 2147483647, -2147483648), e < 0 && (e = 4294967295 + e + 1), (this[r] = e >>> 24), (this[r + 1] = e >>> 16), (this[r + 2] = e >>> 8), (this[r + 3] = e & 255), r + 4; + }; + me.prototype.writeBigInt64LE = Ti(function (e, r = 0) { + return jd(this, e, r, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')); + }); + me.prototype.writeBigInt64BE = Ti(function (e, r = 0) { + return Zd(this, e, r, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')); + }); + function Vd(t, e, r, o, f, p) { + if (r + o > t.length) throw new RangeError('Index out of range'); + if (r < 0) throw new RangeError('Index out of range'); + } + function $d(t, e, r, o, f) { + return (e = +e), (r = r >>> 0), f || Vd(t, e, r, 4, 340282346638528860000000000000000000000, -340282346638528860000000000000000000000), Gn.write(t, e, r, o, 23, 4), r + 4; + } + me.prototype.writeFloatLE = function (e, r, o) { + return $d(this, e, r, true, o); + }; + me.prototype.writeFloatBE = function (e, r, o) { + return $d(this, e, r, false, o); + }; + function Gd(t, e, r, o, f) { + return ( + (e = +e), + (r = r >>> 0), + f || + Vd( + t, + e, + r, + 8, + 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, + -179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + ), + Gn.write(t, e, r, o, 52, 8), + r + 8 + ); + } + me.prototype.writeDoubleLE = function (e, r, o) { + return Gd(this, e, r, true, o); + }; + me.prototype.writeDoubleBE = function (e, r, o) { + return Gd(this, e, r, false, o); + }; + me.prototype.copy = function (e, r, o, f) { + if (!me.isBuffer(e)) throw new TypeError('argument should be a Buffer'); + if ((o || (o = 0), !f && f !== 0 && (f = this.length), r >= e.length && (r = e.length), r || (r = 0), f > 0 && f < o && (f = o), f === o || e.length === 0 || this.length === 0)) return 0; + if (r < 0) throw new RangeError('targetStart out of bounds'); + if (o < 0 || o >= this.length) throw new RangeError('Index out of range'); + if (f < 0) throw new RangeError('sourceEnd out of bounds'); + f > this.length && (f = this.length), e.length - r < f - o && (f = e.length - r + o); + let p = f - o; + return this === e && typeof Uint8Array.prototype.copyWithin == 'function' ? this.copyWithin(r, o, f) : Uint8Array.prototype.set.call(e, this.subarray(o, f), r), p; + }; + me.prototype.fill = function (e, r, o, f) { + if (typeof e == 'string') { + if ((typeof r == 'string' ? ((f = r), (r = 0), (o = this.length)) : typeof o == 'string' && ((f = o), (o = this.length)), f !== undefined && typeof f != 'string')) throw new TypeError('encoding must be a string'); + if (typeof f == 'string' && !me.isEncoding(f)) throw new TypeError('Unknown encoding: ' + f); + if (e.length === 1) { + let m2 = e.charCodeAt(0); + ((f === 'utf8' && m2 < 128) || f === 'latin1') && (e = m2); + } + } else typeof e == 'number' ? (e = e & 255) : typeof e == 'boolean' && (e = Number(e)); + if (r < 0 || this.length < r || this.length < o) throw new RangeError('Out of range index'); + if (o <= r) return this; + (r = r >>> 0), (o = o === undefined ? this.length : o >>> 0), e || (e = 0); + let p; + if (typeof e == 'number') for (p = r; p < o; ++p) this[p] = e; + else { + let m2 = me.isBuffer(e) ? e : me.from(e, f), + y2 = m2.length; + if (y2 === 0) throw new TypeError('The value "' + e + '" is invalid for argument "value"'); + for (p = 0; p < o - r; ++p) this[p + r] = m2[p % y2]; + } + return this; + }; + var $n = {}; + function P0(t, e, r) { + $n[t] = class extends r { + constructor() { + super(), Object.defineProperty(this, 'message', {value: e.apply(this, arguments), writable: true, configurable: true}), (this.name = `${this.name} [${t}]`), this.stack, delete this.name; + } + get code() { + return t; + } + set code(f) { + Object.defineProperty(this, 'code', {configurable: true, enumerable: true, value: f, writable: true}); + } + toString() { + return `${this.name} [${t}]: ${this.message}`; + } + }; + } + P0( + 'ERR_BUFFER_OUT_OF_BOUNDS', + function (t) { + return t ? `${t} is outside of buffer bounds` : 'Attempt to access memory outside buffer bounds'; + }, + RangeError + ); + P0( + 'ERR_INVALID_ARG_TYPE', + function (t, e) { + return `The "${t}" argument must be of type number. Received type ${typeof e}`; + }, + TypeError + ); + P0( + 'ERR_OUT_OF_RANGE', + function (t, e, r) { + let o = `The value of "${t}" is out of range.`, + f = r; + return ( + Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? (f = Fd(String(r))) : typeof r == 'bigint' && ((f = String(r)), (r > BigInt(2) ** BigInt(32) || r < -(BigInt(2) ** BigInt(32))) && (f = Fd(f)), (f += 'n')), + (o += ` It must be ${e}. Received ${f}`), + o + ); + }, + RangeError + ); + function Fd(t) { + let e = '', + r = t.length, + o = t[0] === '-' ? 1 : 0; + for (; r >= o + 4; r -= 3) e = `_${t.slice(r - 3, r)}${e}`; + return `${t.slice(0, r)}${e}`; + } + function Kw(t, e, r) { + Yn(e, 'offset'), (t[e] === undefined || t[e + r] === undefined) && Vf(e, t.length - (r + 1)); + } + function Yd(t, e, r, o, f, p) { + if (t > r || t < e) { + let m2 = typeof e == 'bigint' ? 'n' : '', + y2; + throw ( + (p > 3 ? (e === 0 || e === BigInt(0) ? (y2 = `>= 0${m2} and < 2${m2} ** ${(p + 1) * 8}${m2}`) : (y2 = `>= -(2${m2} ** ${(p + 1) * 8 - 1}${m2}) and < 2 ** ${(p + 1) * 8 - 1}${m2}`)) : (y2 = `>= ${e}${m2} and <= ${r}${m2}`), + new $n.ERR_OUT_OF_RANGE('value', y2, t)) + ); + } + Kw(o, f, p); + } + function Yn(t, e) { + if (typeof t != 'number') throw new $n.ERR_INVALID_ARG_TYPE(e, 'number', t); + } + function Vf(t, e, r) { + throw Math.floor(t) !== t ? (Yn(t, r), new $n.ERR_OUT_OF_RANGE(r || 'offset', 'an integer', t)) : e < 0 ? new $n.ERR_BUFFER_OUT_OF_BOUNDS() : new $n.ERR_OUT_OF_RANGE(r || 'offset', `>= ${r ? 1 : 0} and <= ${e}`, t); + } + var jw = /[^+/0-9A-Za-z-_]/g; + function Zw(t) { + if (((t = t.split('=')[0]), (t = t.trim().replace(jw, '')), t.length < 2)) return ''; + for (; t.length % 4 !== 0; ) t = t + '='; + return t; + } + function L0(t, e) { + e = e || 1 / 0; + let r, + o = t.length, + f = null, + p = []; + for (let m2 = 0; m2 < o; ++m2) { + if (((r = t.charCodeAt(m2)), r > 55295 && r < 57344)) { + if (!f) { + if (r > 56319) { + (e -= 3) > -1 && p.push(239, 191, 189); + continue; + } else if (m2 + 1 === o) { + (e -= 3) > -1 && p.push(239, 191, 189); + continue; + } + f = r; + continue; + } + if (r < 56320) { + (e -= 3) > -1 && p.push(239, 191, 189), (f = r); + continue; + } + r = (((f - 55296) << 10) | (r - 56320)) + 65536; + } else f && (e -= 3) > -1 && p.push(239, 191, 189); + if (((f = null), r < 128)) { + if ((e -= 1) < 0) break; + p.push(r); + } else if (r < 2048) { + if ((e -= 2) < 0) break; + p.push((r >> 6) | 192, (r & 63) | 128); + } else if (r < 65536) { + if ((e -= 3) < 0) break; + p.push((r >> 12) | 224, ((r >> 6) & 63) | 128, (r & 63) | 128); + } else if (r < 1114112) { + if ((e -= 4) < 0) break; + p.push((r >> 18) | 240, ((r >> 12) & 63) | 128, ((r >> 6) & 63) | 128, (r & 63) | 128); + } else throw new Error('Invalid code point'); + } + return p; + } + function Vw(t) { + let e = []; + for (let r = 0; r < t.length; ++r) e.push(t.charCodeAt(r) & 255); + return e; + } + function $w(t, e) { + let r, + o, + f, + p = []; + for (let m2 = 0; m2 < t.length && !((e -= 2) < 0); ++m2) (r = t.charCodeAt(m2)), (o = r >> 8), (f = r % 256), p.push(f), p.push(o); + return p; + } + function Xd(t) { + return I0.toByteArray(Zw(t)); + } + function to(t, e, r, o) { + let f; + for (f = 0; f < o && !(f + r >= e.length || f >= t.length); ++f) e[f + r] = t[f]; + return f; + } + function Zr(t, e) { + return t instanceof e || (t != null && t.constructor != null && t.constructor.name != null && t.constructor.name === e.name); + } + function C0(t) { + return t !== t; + } + var Gw = (function () { + let t = '0123456789abcdef', + e = new Array(256); + for (let r = 0; r < 16; ++r) { + let o = r * 16; + for (let f = 0; f < 16; ++f) e[o + f] = t[r] + t[f]; + } + return e; + })(); + function Ti(t) { + return typeof BigInt > 'u' ? Yw : t; + } + function Yw() { + throw new Error('BigInt not supported'); + } + }); + Te = T2((O0, Qd) => { + var ro = Ut(), + Vr = ro.Buffer; + function Jd(t, e) { + for (var r in t) e[r] = t[r]; + } + Vr.from && Vr.alloc && Vr.allocUnsafe && Vr.allocUnsafeSlow ? (Qd.exports = ro) : (Jd(ro, O0), (O0.Buffer = an)); + function an(t, e, r) { + return Vr(t, e, r); + } + an.prototype = Object.create(Vr.prototype); + Jd(Vr, an); + an.from = function (t, e, r) { + if (typeof t == 'number') throw new TypeError('Argument must not be a number'); + return Vr(t, e, r); + }; + an.alloc = function (t, e, r) { + if (typeof t != 'number') throw new TypeError('Argument must be a number'); + var o = Vr(t); + return e !== undefined ? (typeof r == 'string' ? o.fill(e, r) : o.fill(e)) : o.fill(0), o; + }; + an.allocUnsafe = function (t) { + if (typeof t != 'number') throw new TypeError('Argument must be a number'); + return Vr(t); + }; + an.allocUnsafeSlow = function (t) { + if (typeof t != 'number') throw new TypeError('Argument must be a number'); + return ro.SlowBuffer(t); + }; + }); + on = T2((Gq, U0) => { + var F0 = 65536, + Xw = 4294967295; + function Jw() { + throw new Error(`Secure random number generation is not supported by this browser. +Use Chrome, Firefox or Internet Explorer 11`); + } + var Qw = Te().Buffer, + io = global.crypto || global.msCrypto; + io && io.getRandomValues ? (U0.exports = e6) : (U0.exports = Jw); + function e6(t, e) { + if (t > Xw) throw new RangeError('requested too many random bytes'); + var r = Qw.allocUnsafe(t); + if (t > 0) + if (t > F0) for (var o = 0; o < t; o += F0) io.getRandomValues(r.slice(o, o + F0)); + else io.getRandomValues(r); + return typeof e == 'function' + ? process.nextTick(function () { + e(null, r); + }) + : r; + } + }); + Ie = T2((Yq, z0) => { + typeof Object.create == 'function' + ? (z0.exports = function (e, r) { + r && ((e.super_ = r), (e.prototype = Object.create(r.prototype, {constructor: {value: e, enumerable: false, writable: true, configurable: true}}))); + }) + : (z0.exports = function (e, r) { + if (r) { + e.super_ = r; + var o = function () {}; + (o.prototype = r.prototype), (e.prototype = new o()), (e.prototype.constructor = e); + } + }); + }); + ki = T2((Xq, H0) => { + var Jn = typeof Reflect == 'object' ? Reflect : null, + ec = + Jn && typeof Jn.apply == 'function' + ? Jn.apply + : function (e, r, o) { + return Function.prototype.apply.call(e, r, o); + }, + no; + Jn && typeof Jn.ownKeys == 'function' + ? (no = Jn.ownKeys) + : Object.getOwnPropertySymbols + ? (no = function (e) { + return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e)); + }) + : (no = function (e) { + return Object.getOwnPropertyNames(e); + }); + function t6(t) { + console && console.warn && console.warn(t); + } + var rc = + Number.isNaN || + function (e) { + return e !== e; + }; + function Fe() { + Fe.init.call(this); + } + H0.exports = Fe; + H0.exports.once = f6; + Fe.EventEmitter = Fe; + Fe.prototype._events = undefined; + Fe.prototype._eventsCount = 0; + Fe.prototype._maxListeners = undefined; + var tc = 10; + function fo(t) { + if (typeof t != 'function') throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof t); + } + Object.defineProperty(Fe, 'defaultMaxListeners', { + enumerable: true, + get: function () { + return tc; + }, + set: function (t) { + if (typeof t != 'number' || t < 0 || rc(t)) throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + t + '.'); + tc = t; + } + }); + Fe.init = function () { + (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) && ((this._events = Object.create(null)), (this._eventsCount = 0)), (this._maxListeners = this._maxListeners || undefined); + }; + Fe.prototype.setMaxListeners = function (e) { + if (typeof e != 'number' || e < 0 || rc(e)) throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + e + '.'); + return (this._maxListeners = e), this; + }; + function ic(t) { + return t._maxListeners === undefined ? Fe.defaultMaxListeners : t._maxListeners; + } + Fe.prototype.getMaxListeners = function () { + return ic(this); + }; + Fe.prototype.emit = function (e) { + for (var r = [], o = 1; o < arguments.length; o++) r.push(arguments[o]); + var f = e === 'error', + p = this._events; + if (p !== undefined) f = f && p.error === undefined; + else if (!f) return false; + if (f) { + var m2; + if ((r.length > 0 && (m2 = r[0]), m2 instanceof Error)) throw m2; + var y2 = new Error('Unhandled error.' + (m2 ? ' (' + m2.message + ')' : '')); + throw ((y2.context = m2), y2); + } + var M = p[e]; + if (M === undefined) return false; + if (typeof M == 'function') ec(M, this, r); + else for (var x = M.length, S = sc(M, x), o = 0; o < x; ++o) ec(S[o], this, r); + return true; + }; + function nc(t, e, r, o) { + var f, p, m2; + if ( + (fo(r), + (p = t._events), + p === undefined ? ((p = t._events = Object.create(null)), (t._eventsCount = 0)) : (p.newListener !== undefined && (t.emit('newListener', e, r.listener ? r.listener : r), (p = t._events)), (m2 = p[e])), + m2 === undefined) + ) + (m2 = p[e] = r), ++t._eventsCount; + else if ((typeof m2 == 'function' ? (m2 = p[e] = o ? [r, m2] : [m2, r]) : o ? m2.unshift(r) : m2.push(r), (f = ic(t)), f > 0 && m2.length > f && !m2.warned)) { + m2.warned = true; + var y2 = new Error('Possible EventEmitter memory leak detected. ' + m2.length + ' ' + String(e) + ' listeners added. Use emitter.setMaxListeners() to increase limit'); + (y2.name = 'MaxListenersExceededWarning'), (y2.emitter = t), (y2.type = e), (y2.count = m2.length), t6(y2); + } + return t; + } + Fe.prototype.addListener = function (e, r) { + return nc(this, e, r, false); + }; + Fe.prototype.on = Fe.prototype.addListener; + Fe.prototype.prependListener = function (e, r) { + return nc(this, e, r, true); + }; + function r6() { + if (!this.fired) return this.target.removeListener(this.type, this.wrapFn), (this.fired = true), arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments); + } + function fc(t, e, r) { + var o = {fired: false, wrapFn: undefined, target: t, type: e, listener: r}, + f = r6.bind(o); + return (f.listener = r), (o.wrapFn = f), f; + } + Fe.prototype.once = function (e, r) { + return fo(r), this.on(e, fc(this, e, r)), this; + }; + Fe.prototype.prependOnceListener = function (e, r) { + return fo(r), this.prependListener(e, fc(this, e, r)), this; + }; + Fe.prototype.removeListener = function (e, r) { + var o, f, p, m2, y2; + if ((fo(r), (f = this._events), f === undefined)) return this; + if (((o = f[e]), o === undefined)) return this; + if (o === r || o.listener === r) --this._eventsCount === 0 ? (this._events = Object.create(null)) : (delete f[e], f.removeListener && this.emit('removeListener', e, o.listener || r)); + else if (typeof o != 'function') { + for (p = -1, m2 = o.length - 1; m2 >= 0; m2--) + if (o[m2] === r || o[m2].listener === r) { + (y2 = o[m2].listener), (p = m2); + break; + } + if (p < 0) return this; + p === 0 ? o.shift() : i6(o, p), o.length === 1 && (f[e] = o[0]), f.removeListener !== undefined && this.emit('removeListener', e, y2 || r); + } + return this; + }; + Fe.prototype.off = Fe.prototype.removeListener; + Fe.prototype.removeAllListeners = function (e) { + var r, o, f; + if (((o = this._events), o === undefined)) return this; + if (o.removeListener === undefined) + return arguments.length === 0 ? ((this._events = Object.create(null)), (this._eventsCount = 0)) : o[e] !== undefined && (--this._eventsCount === 0 ? (this._events = Object.create(null)) : delete o[e]), this; + if (arguments.length === 0) { + var p = Object.keys(o), + m2; + for (f = 0; f < p.length; ++f) (m2 = p[f]), m2 !== 'removeListener' && this.removeAllListeners(m2); + return this.removeAllListeners('removeListener'), (this._events = Object.create(null)), (this._eventsCount = 0), this; + } + if (((r = o[e]), typeof r == 'function')) this.removeListener(e, r); + else if (r !== undefined) for (f = r.length - 1; f >= 0; f--) this.removeListener(e, r[f]); + return this; + }; + function ac(t, e, r) { + var o = t._events; + if (o === undefined) return []; + var f = o[e]; + return f === undefined ? [] : typeof f == 'function' ? (r ? [f.listener || f] : [f]) : r ? n6(f) : sc(f, f.length); + } + Fe.prototype.listeners = function (e) { + return ac(this, e, true); + }; + Fe.prototype.rawListeners = function (e) { + return ac(this, e, false); + }; + Fe.listenerCount = function (t, e) { + return typeof t.listenerCount == 'function' ? t.listenerCount(e) : oc.call(t, e); + }; + Fe.prototype.listenerCount = oc; + function oc(t) { + var e = this._events; + if (e !== undefined) { + var r = e[t]; + if (typeof r == 'function') return 1; + if (r !== undefined) return r.length; + } + return 0; + } + Fe.prototype.eventNames = function () { + return this._eventsCount > 0 ? no(this._events) : []; + }; + function sc(t, e) { + for (var r = new Array(e), o = 0; o < e; ++o) r[o] = t[o]; + return r; + } + function i6(t, e) { + for (; e + 1 < t.length; e++) t[e] = t[e + 1]; + t.pop(); + } + function n6(t) { + for (var e = new Array(t.length), r = 0; r < e.length; ++r) e[r] = t[r].listener || t[r]; + return e; + } + function f6(t, e) { + return new Promise(function (r, o) { + function f(m2) { + t.removeListener(e, p), o(m2); + } + function p() { + typeof t.removeListener == 'function' && t.removeListener('error', f), r([].slice.call(arguments)); + } + hc(t, e, p, {once: true}), e !== 'error' && a6(t, f, {once: true}); + }); + } + function a6(t, e, r) { + typeof t.on == 'function' && hc(t, 'error', e, r); + } + function hc(t, e, r, o) { + if (typeof t.on == 'function') o.once ? t.once(e, r) : t.on(e, r); + else if (typeof t.addEventListener == 'function') + t.addEventListener(e, function f(p) { + o.once && t.removeEventListener(e, f), r(p); + }); + else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof t); + } + }); + W0 = T2((Jq, uc) => { + uc.exports = ki().EventEmitter; + }); + $f = T2(() => {}); + pc = T2((tI, cc) => { + function lc(t, e) { + var r = Object.keys(t); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(t); + e && + (o = o.filter(function (f) { + return Object.getOwnPropertyDescriptor(t, f).enumerable; + })), + r.push.apply(r, o); + } + return r; + } + function o6(t) { + for (var e = 1; e < arguments.length; e++) { + var r = arguments[e] != null ? arguments[e] : {}; + e % 2 + ? lc(Object(r), true).forEach(function (o) { + s6(t, o, r[o]); + }) + : Object.getOwnPropertyDescriptors + ? Object.defineProperties(t, Object.getOwnPropertyDescriptors(r)) + : lc(Object(r)).forEach(function (o) { + Object.defineProperty(t, o, Object.getOwnPropertyDescriptor(r, o)); + }); + } + return t; + } + function s6(t, e, r) { + return e in t ? Object.defineProperty(t, e, {value: r, enumerable: true, configurable: true, writable: true}) : (t[e] = r), t; + } + function h6(t, e) { + if (!(t instanceof e)) throw new TypeError('Cannot call a class as a function'); + } + function dc(t, e) { + for (var r = 0; r < e.length; r++) { + var o = e[r]; + (o.enumerable = o.enumerable || false), (o.configurable = true), 'value' in o && (o.writable = true), Object.defineProperty(t, o.key, o); + } + } + function u6(t, e, r) { + return e && dc(t.prototype, e), r && dc(t, r), t; + } + var l6 = Ut(), + ao = l6.Buffer, + d6 = $f(), + K0 = d6.inspect, + c6 = (K0 && K0.custom) || 'inspect'; + function p6(t, e, r) { + ao.prototype.copy.call(t, e, r); + } + cc.exports = (function () { + function t() { + h6(this, t), (this.head = null), (this.tail = null), (this.length = 0); + } + return ( + u6(t, [ + { + key: 'push', + value: function (r) { + var o = {data: r, next: null}; + this.length > 0 ? (this.tail.next = o) : (this.head = o), (this.tail = o), ++this.length; + } + }, + { + key: 'unshift', + value: function (r) { + var o = {data: r, next: this.head}; + this.length === 0 && (this.tail = o), (this.head = o), ++this.length; + } + }, + { + key: 'shift', + value: function () { + if (this.length !== 0) { + var r = this.head.data; + return this.length === 1 ? (this.head = this.tail = null) : (this.head = this.head.next), --this.length, r; + } + } + }, + { + key: 'clear', + value: function () { + (this.head = this.tail = null), (this.length = 0); + } + }, + { + key: 'join', + value: function (r) { + if (this.length === 0) return ''; + for (var o = this.head, f = '' + o.data; (o = o.next); ) f += r + o.data; + return f; + } + }, + { + key: 'concat', + value: function (r) { + if (this.length === 0) return ao.alloc(0); + for (var o = ao.allocUnsafe(r >>> 0), f = this.head, p = 0; f; ) p6(f.data, o, p), (p += f.data.length), (f = f.next); + return o; + } + }, + { + key: 'consume', + value: function (r, o) { + var f; + return r < this.head.data.length ? ((f = this.head.data.slice(0, r)), (this.head.data = this.head.data.slice(r))) : r === this.head.data.length ? (f = this.shift()) : (f = o ? this._getString(r) : this._getBuffer(r)), f; + } + }, + { + key: 'first', + value: function () { + return this.head.data; + } + }, + { + key: '_getString', + value: function (r) { + var o = this.head, + f = 1, + p = o.data; + for (r -= p.length; (o = o.next); ) { + var m2 = o.data, + y2 = r > m2.length ? m2.length : r; + if ((y2 === m2.length ? (p += m2) : (p += m2.slice(0, r)), (r -= y2), r === 0)) { + y2 === m2.length ? (++f, o.next ? (this.head = o.next) : (this.head = this.tail = null)) : ((this.head = o), (o.data = m2.slice(y2))); + break; + } + ++f; + } + return (this.length -= f), p; + } + }, + { + key: '_getBuffer', + value: function (r) { + var o = ao.allocUnsafe(r), + f = this.head, + p = 1; + for (f.data.copy(o), r -= f.data.length; (f = f.next); ) { + var m2 = f.data, + y2 = r > m2.length ? m2.length : r; + if ((m2.copy(o, o.length - r, 0, y2), (r -= y2), r === 0)) { + y2 === m2.length ? (++p, f.next ? (this.head = f.next) : (this.head = this.tail = null)) : ((this.head = f), (f.data = m2.slice(y2))); + break; + } + ++p; + } + return (this.length -= p), o; + } + }, + { + key: c6, + value: function (r, o) { + return K0(this, o6({}, o, {depth: 0, customInspect: false})); + } + } + ]), + t + ); + })(); + }); + Z0 = T2((rI, bc) => { + function v6(t, e) { + var r = this, + o = this._readableState && this._readableState.destroyed, + f = this._writableState && this._writableState.destroyed; + return o || f + ? (e ? e(t) : t && (this._writableState ? this._writableState.errorEmitted || ((this._writableState.errorEmitted = true), process.nextTick(j0, this, t)) : process.nextTick(j0, this, t)), this) + : (this._readableState && (this._readableState.destroyed = true), + this._writableState && (this._writableState.destroyed = true), + this._destroy(t || null, function (p) { + !e && p + ? r._writableState + ? r._writableState.errorEmitted + ? process.nextTick(oo, r) + : ((r._writableState.errorEmitted = true), process.nextTick(vc, r, p)) + : process.nextTick(vc, r, p) + : e + ? (process.nextTick(oo, r), e(p)) + : process.nextTick(oo, r); + }), + this); + } + function vc(t, e) { + j0(t, e), oo(t); + } + function oo(t) { + (t._writableState && !t._writableState.emitClose) || (t._readableState && !t._readableState.emitClose) || t.emit('close'); + } + function b6() { + this._readableState && ((this._readableState.destroyed = false), (this._readableState.reading = false), (this._readableState.ended = false), (this._readableState.endEmitted = false)), + this._writableState && + ((this._writableState.destroyed = false), + (this._writableState.ended = false), + (this._writableState.ending = false), + (this._writableState.finalCalled = false), + (this._writableState.prefinished = false), + (this._writableState.finished = false), + (this._writableState.errorEmitted = false)); + } + function j0(t, e) { + t.emit('error', e); + } + function m6(t, e) { + var {_readableState: r, _writableState: o} = t; + (r && r.autoDestroy) || (o && o.autoDestroy) ? t.destroy(e) : t.emit('error', e); + } + bc.exports = {destroy: v6, undestroy: b6, errorOrDestroy: m6}; + }); + sn = T2((iI, yc) => { + function g6(t, e) { + (t.prototype = Object.create(e.prototype)), (t.prototype.constructor = t), (t.__proto__ = e); + } + var gc = {}; + function dr(t, e, r) { + r || (r = Error); + function o(p, m2, y2) { + return typeof e == 'string' ? e : e(p, m2, y2); + } + var f = (function (p) { + g6(m2, p); + function m2(y2, M, x) { + return p.call(this, o(y2, M, x)) || this; + } + return m2; + })(r); + (f.prototype.name = r.name), (f.prototype.code = t), (gc[t] = f); + } + function mc(t, e) { + if (Array.isArray(t)) { + var r = t.length; + return ( + (t = t.map(function (o) { + return String(o); + })), + r > 2 ? 'one of '.concat(e, ' ').concat(t.slice(0, r - 1).join(', '), ', or ') + t[r - 1] : r === 2 ? 'one of '.concat(e, ' ').concat(t[0], ' or ').concat(t[1]) : 'of '.concat(e, ' ').concat(t[0]) + ); + } else return 'of '.concat(e, ' ').concat(String(t)); + } + function y6(t, e, r) { + return t.substr(!r || r < 0 ? 0 : +r, e.length) === e; + } + function w6(t, e, r) { + return (r === undefined || r > t.length) && (r = t.length), t.substring(r - e.length, r) === e; + } + function M6(t, e, r) { + return typeof r != 'number' && (r = 0), r + e.length > t.length ? false : t.indexOf(e, r) !== -1; + } + dr( + 'ERR_INVALID_OPT_VALUE', + function (t, e) { + return 'The value "' + e + '" is invalid for option "' + t + '"'; + }, + TypeError + ); + dr( + 'ERR_INVALID_ARG_TYPE', + function (t, e, r) { + var o; + typeof e == 'string' && y6(e, 'not ') ? ((o = 'must not be'), (e = e.replace(/^not /, ''))) : (o = 'must be'); + var f; + if (w6(t, ' argument')) f = 'The '.concat(t, ' ').concat(o, ' ').concat(mc(e, 'type')); + else { + var p = M6(t, '.') ? 'property' : 'argument'; + f = 'The "'.concat(t, '" ').concat(p, ' ').concat(o, ' ').concat(mc(e, 'type')); + } + return (f += '. Received type '.concat(typeof r)), f; + }, + TypeError + ); + dr('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + dr('ERR_METHOD_NOT_IMPLEMENTED', function (t) { + return 'The ' + t + ' method is not implemented'; + }); + dr('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + dr('ERR_STREAM_DESTROYED', function (t) { + return 'Cannot call ' + t + ' after a stream was destroyed'; + }); + dr('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); + dr('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); + dr('ERR_STREAM_WRITE_AFTER_END', 'write after end'); + dr('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); + dr( + 'ERR_UNKNOWN_ENCODING', + function (t) { + return 'Unknown encoding: ' + t; + }, + TypeError + ); + dr('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + yc.exports.codes = gc; + }); + V0 = T2((nI, wc) => { + var _6 = sn().codes.ERR_INVALID_OPT_VALUE; + function x6(t, e, r) { + return t.highWaterMark != null ? t.highWaterMark : e ? t[r] : null; + } + function S6(t, e, r, o) { + var f = x6(e, o, r); + if (f != null) { + if (!(isFinite(f) && Math.floor(f) === f) || f < 0) { + var p = o ? r : 'highWaterMark'; + throw new _6(p, f); + } + return Math.floor(f); + } + return t.objectMode ? 16 : 16 * 1024; + } + wc.exports = {getHighWaterMark: S6}; + }); + G0 = T2((fI, Mc) => { + Mc.exports = E6; + function E6(t, e) { + if ($0('noDeprecation')) return t; + var r = false; + function o() { + if (!r) { + if ($0('throwDeprecation')) throw new Error(e); + $0('traceDeprecation') ? console.trace(e) : console.warn(e), (r = true); + } + return t.apply(this, arguments); + } + return o; + } + function $0(t) { + try { + if (!global.localStorage) return false; + } catch { + return false; + } + var e = global.localStorage[t]; + return e == null ? false : String(e).toLowerCase() === 'true'; + } + }); + J0 = T2((aI, Rc) => { + Rc.exports = ht; + function xc(t) { + var e = this; + (this.next = null), + (this.entry = null), + (this.finish = function () { + J6(e, t); + }); + } + var Qn; + ht.WritableState = Yf; + var A6 = {deprecate: G0()}, + Sc = W0(), + ho = Ut().Buffer, + R6 = global.Uint8Array || function () {}; + function B6(t) { + return ho.from(t); + } + function q6(t) { + return ho.isBuffer(t) || t instanceof R6; + } + var X0 = Z0(), + I6 = V0(), + T6 = I6.getHighWaterMark, + Li = sn().codes, + k6 = Li.ERR_INVALID_ARG_TYPE, + L6 = Li.ERR_METHOD_NOT_IMPLEMENTED, + N6 = Li.ERR_MULTIPLE_CALLBACK, + D6 = Li.ERR_STREAM_CANNOT_PIPE, + P6 = Li.ERR_STREAM_DESTROYED, + C6 = Li.ERR_STREAM_NULL_VALUES, + O6 = Li.ERR_STREAM_WRITE_AFTER_END, + F6 = Li.ERR_UNKNOWN_ENCODING, + ef = X0.errorOrDestroy; + Ie()(ht, Sc); + function U6() {} + function Yf(t, e, r) { + (Qn = Qn || hn()), + (t = t || {}), + typeof r != 'boolean' && (r = e instanceof Qn), + (this.objectMode = !!t.objectMode), + r && (this.objectMode = this.objectMode || !!t.writableObjectMode), + (this.highWaterMark = T6(this, t, 'writableHighWaterMark', r)), + (this.finalCalled = false), + (this.needDrain = false), + (this.ending = false), + (this.ended = false), + (this.finished = false), + (this.destroyed = false); + var o = t.decodeStrings === false; + (this.decodeStrings = !o), + (this.defaultEncoding = t.defaultEncoding || 'utf8'), + (this.length = 0), + (this.writing = false), + (this.corked = 0), + (this.sync = true), + (this.bufferProcessing = false), + (this.onwrite = function (f) { + V6(e, f); + }), + (this.writecb = null), + (this.writelen = 0), + (this.bufferedRequest = null), + (this.lastBufferedRequest = null), + (this.pendingcb = 0), + (this.prefinished = false), + (this.errorEmitted = false), + (this.emitClose = t.emitClose !== false), + (this.autoDestroy = !!t.autoDestroy), + (this.bufferedRequestCount = 0), + (this.corkedRequestsFree = new xc(this)); + } + Yf.prototype.getBuffer = function () { + for (var e = this.bufferedRequest, r = []; e; ) r.push(e), (e = e.next); + return r; + }; + (function () { + try { + Object.defineProperty(Yf.prototype, 'buffer', { + get: A6.deprecate( + function () { + return this.getBuffer(); + }, + '_writableState.buffer is deprecated. Use _writableState.getBuffer instead.', + 'DEP0003' + ) + }); + } catch {} + })(); + var so; + typeof Symbol == 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] == 'function' + ? ((so = Function.prototype[Symbol.hasInstance]), + Object.defineProperty(ht, Symbol.hasInstance, { + value: function (e) { + return so.call(this, e) ? true : this !== ht ? false : e && e._writableState instanceof Yf; + } + })) + : (so = function (e) { + return e instanceof this; + }); + function ht(t) { + Qn = Qn || hn(); + var e = this instanceof Qn; + if (!e && !so.call(ht, this)) return new ht(t); + (this._writableState = new Yf(t, this, e)), + (this.writable = true), + t && + (typeof t.write == 'function' && (this._write = t.write), + typeof t.writev == 'function' && (this._writev = t.writev), + typeof t.destroy == 'function' && (this._destroy = t.destroy), + typeof t.final == 'function' && (this._final = t.final)), + Sc.call(this); + } + ht.prototype.pipe = function () { + ef(this, new D6()); + }; + function z6(t, e) { + var r = new O6(); + ef(t, r), process.nextTick(e, r); + } + function H6(t, e, r, o) { + var f; + return r === null ? (f = new C6()) : typeof r != 'string' && !e.objectMode && (f = new k6('chunk', ['string', 'Buffer'], r)), f ? (ef(t, f), process.nextTick(o, f), false) : true; + } + ht.prototype.write = function (t, e, r) { + var o = this._writableState, + f = false, + p = !o.objectMode && q6(t); + return ( + p && !ho.isBuffer(t) && (t = B6(t)), + typeof e == 'function' && ((r = e), (e = null)), + p ? (e = 'buffer') : e || (e = o.defaultEncoding), + typeof r != 'function' && (r = U6), + o.ending ? z6(this, r) : (p || H6(this, o, t, r)) && (o.pendingcb++, (f = K6(this, o, p, t, e, r))), + f + ); + }; + ht.prototype.cork = function () { + this._writableState.corked++; + }; + ht.prototype.uncork = function () { + var t = this._writableState; + t.corked && (t.corked--, !t.writing && !t.corked && !t.bufferProcessing && t.bufferedRequest && Ec(this, t)); + }; + ht.prototype.setDefaultEncoding = function (e) { + if ((typeof e == 'string' && (e = e.toLowerCase()), !(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((e + '').toLowerCase()) > -1))) throw new F6(e); + return (this._writableState.defaultEncoding = e), this; + }; + Object.defineProperty(ht.prototype, 'writableBuffer', { + enumerable: false, + get: function () { + return this._writableState && this._writableState.getBuffer(); + } + }); + function W6(t, e, r) { + return !t.objectMode && t.decodeStrings !== false && typeof e == 'string' && (e = ho.from(e, r)), e; + } + Object.defineProperty(ht.prototype, 'writableHighWaterMark', { + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } + }); + function K6(t, e, r, o, f, p) { + if (!r) { + var m2 = W6(e, o, f); + o !== m2 && ((r = true), (f = 'buffer'), (o = m2)); + } + var y2 = e.objectMode ? 1 : o.length; + e.length += y2; + var M = e.length < e.highWaterMark; + if ((M || (e.needDrain = true), e.writing || e.corked)) { + var x = e.lastBufferedRequest; + (e.lastBufferedRequest = {chunk: o, encoding: f, isBuf: r, callback: p, next: null}), x ? (x.next = e.lastBufferedRequest) : (e.bufferedRequest = e.lastBufferedRequest), (e.bufferedRequestCount += 1); + } else Y0(t, e, false, y2, o, f, p); + return M; + } + function Y0(t, e, r, o, f, p, m2) { + (e.writelen = o), (e.writecb = m2), (e.writing = true), (e.sync = true), e.destroyed ? e.onwrite(new P6('write')) : r ? t._writev(f, e.onwrite) : t._write(f, p, e.onwrite), (e.sync = false); + } + function j6(t, e, r, o, f) { + --e.pendingcb, r ? (process.nextTick(f, o), process.nextTick(Gf, t, e), (t._writableState.errorEmitted = true), ef(t, o)) : (f(o), (t._writableState.errorEmitted = true), ef(t, o), Gf(t, e)); + } + function Z6(t) { + (t.writing = false), (t.writecb = null), (t.length -= t.writelen), (t.writelen = 0); + } + function V6(t, e) { + var r = t._writableState, + o = r.sync, + f = r.writecb; + if (typeof f != 'function') throw new N6(); + if ((Z6(r), e)) j6(t, r, o, e, f); + else { + var p = Ac(r) || t.destroyed; + !p && !r.corked && !r.bufferProcessing && r.bufferedRequest && Ec(t, r), o ? process.nextTick(_c, t, r, p, f) : _c(t, r, p, f); + } + } + function _c(t, e, r, o) { + r || $6(t, e), e.pendingcb--, o(), Gf(t, e); + } + function $6(t, e) { + e.length === 0 && e.needDrain && ((e.needDrain = false), t.emit('drain')); + } + function Ec(t, e) { + e.bufferProcessing = true; + var r = e.bufferedRequest; + if (t._writev && r && r.next) { + var o = e.bufferedRequestCount, + f = new Array(o), + p = e.corkedRequestsFree; + p.entry = r; + for (var m2 = 0, y2 = true; r; ) (f[m2] = r), r.isBuf || (y2 = false), (r = r.next), (m2 += 1); + (f.allBuffers = y2), + Y0(t, e, true, e.length, f, '', p.finish), + e.pendingcb++, + (e.lastBufferedRequest = null), + p.next ? ((e.corkedRequestsFree = p.next), (p.next = null)) : (e.corkedRequestsFree = new xc(e)), + (e.bufferedRequestCount = 0); + } else { + for (; r; ) { + var {chunk: M, encoding: x, callback: S} = r, + E2 = e.objectMode ? 1 : M.length; + if ((Y0(t, e, false, E2, M, x, S), (r = r.next), e.bufferedRequestCount--, e.writing)) break; + } + r === null && (e.lastBufferedRequest = null); + } + (e.bufferedRequest = r), (e.bufferProcessing = false); + } + ht.prototype._write = function (t, e, r) { + r(new L6('_write()')); + }; + ht.prototype._writev = null; + ht.prototype.end = function (t, e, r) { + var o = this._writableState; + return typeof t == 'function' ? ((r = t), (t = null), (e = null)) : typeof e == 'function' && ((r = e), (e = null)), t != null && this.write(t, e), o.corked && ((o.corked = 1), this.uncork()), o.ending || X6(this, o, r), this; + }; + Object.defineProperty(ht.prototype, 'writableLength', { + enumerable: false, + get: function () { + return this._writableState.length; + } + }); + function Ac(t) { + return t.ending && t.length === 0 && t.bufferedRequest === null && !t.finished && !t.writing; + } + function G6(t, e) { + t._final(function (r) { + e.pendingcb--, r && ef(t, r), (e.prefinished = true), t.emit('prefinish'), Gf(t, e); + }); + } + function Y6(t, e) { + !e.prefinished && !e.finalCalled && (typeof t._final == 'function' && !e.destroyed ? (e.pendingcb++, (e.finalCalled = true), process.nextTick(G6, t, e)) : ((e.prefinished = true), t.emit('prefinish'))); + } + function Gf(t, e) { + var r = Ac(e); + if (r && (Y6(t, e), e.pendingcb === 0 && ((e.finished = true), t.emit('finish'), e.autoDestroy))) { + var o = t._readableState; + (!o || (o.autoDestroy && o.endEmitted)) && t.destroy(); + } + return r; + } + function X6(t, e, r) { + (e.ending = true), Gf(t, e), r && (e.finished ? process.nextTick(r) : t.once('finish', r)), (e.ended = true), (t.writable = false); + } + function J6(t, e, r) { + var o = t.entry; + for (t.entry = null; o; ) { + var f = o.callback; + e.pendingcb--, f(r), (o = o.next); + } + e.corkedRequestsFree.next = t; + } + Object.defineProperty(ht.prototype, 'destroyed', { + enumerable: false, + get: function () { + return this._writableState === undefined ? false : this._writableState.destroyed; + }, + set: function (e) { + !this._writableState || (this._writableState.destroyed = e); + } + }); + ht.prototype.destroy = X0.destroy; + ht.prototype._undestroy = X0.undestroy; + ht.prototype._destroy = function (t, e) { + e(t); + }; + }); + hn = T2((oI, qc) => { + var Q6 = + Object.keys || + function (t) { + var e = []; + for (var r in t) e.push(r); + return e; + }; + qc.exports = $r; + var Bc = th(), + eh = J0(); + Ie()($r, Bc); + for (Q0 = Q6(eh.prototype), uo = 0; uo < Q0.length; uo++) (lo = Q0[uo]), $r.prototype[lo] || ($r.prototype[lo] = eh.prototype[lo]); + var Q0, lo, uo; + function $r(t) { + if (!(this instanceof $r)) return new $r(t); + Bc.call(this, t), + eh.call(this, t), + (this.allowHalfOpen = true), + t && (t.readable === false && (this.readable = false), t.writable === false && (this.writable = false), t.allowHalfOpen === false && ((this.allowHalfOpen = false), this.once('end', eM))); + } + Object.defineProperty($r.prototype, 'writableHighWaterMark', { + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty($r.prototype, 'writableBuffer', { + enumerable: false, + get: function () { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty($r.prototype, 'writableLength', { + enumerable: false, + get: function () { + return this._writableState.length; + } + }); + function eM() { + this._writableState.ended || process.nextTick(tM, this); + } + function tM(t) { + t.end(); + } + Object.defineProperty($r.prototype, 'destroyed', { + enumerable: false, + get: function () { + return this._readableState === undefined || this._writableState === undefined ? false : this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (e) { + this._readableState === undefined || this._writableState === undefined || ((this._readableState.destroyed = e), (this._writableState.destroyed = e)); + } + }); + }); + co = T2(Tc => { + var ih = Te().Buffer, + Ic = + ih.isEncoding || + function (t) { + switch (((t = '' + t), t && t.toLowerCase())) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + case 'raw': + return true; + default: + return false; + } + }; + function rM(t) { + if (!t) return 'utf8'; + for (var e; ; ) + switch (t) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return t; + default: + if (e) return; + (t = ('' + t).toLowerCase()), (e = true); + } + } + function iM(t) { + var e = rM(t); + if (typeof e != 'string' && (ih.isEncoding === Ic || !Ic(t))) throw new Error('Unknown encoding: ' + t); + return e || t; + } + Tc.StringDecoder = Xf; + function Xf(t) { + this.encoding = iM(t); + var e; + switch (this.encoding) { + case 'utf16le': + (this.text = hM), (this.end = uM), (e = 4); + break; + case 'utf8': + (this.fillLast = aM), (e = 4); + break; + case 'base64': + (this.text = lM), (this.end = dM), (e = 3); + break; + default: + (this.write = cM), (this.end = pM); + return; + } + (this.lastNeed = 0), (this.lastTotal = 0), (this.lastChar = ih.allocUnsafe(e)); + } + Xf.prototype.write = function (t) { + if (t.length === 0) return ''; + var e, r; + if (this.lastNeed) { + if (((e = this.fillLast(t)), e === undefined)) return ''; + (r = this.lastNeed), (this.lastNeed = 0); + } else r = 0; + return r < t.length ? (e ? e + this.text(t, r) : this.text(t, r)) : e || ''; + }; + Xf.prototype.end = sM; + Xf.prototype.text = oM; + Xf.prototype.fillLast = function (t) { + if (this.lastNeed <= t.length) return t.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal); + t.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, t.length), (this.lastNeed -= t.length); + }; + function rh(t) { + return t <= 127 ? 0 : t >> 5 === 6 ? 2 : t >> 4 === 14 ? 3 : t >> 3 === 30 ? 4 : t >> 6 === 2 ? -1 : -2; + } + function nM(t, e, r) { + var o = e.length - 1; + if (o < r) return 0; + var f = rh(e[o]); + return f >= 0 + ? (f > 0 && (t.lastNeed = f - 1), f) + : --o < r || f === -2 + ? 0 + : ((f = rh(e[o])), f >= 0 ? (f > 0 && (t.lastNeed = f - 2), f) : --o < r || f === -2 ? 0 : ((f = rh(e[o])), f >= 0 ? (f > 0 && (f === 2 ? (f = 0) : (t.lastNeed = f - 3)), f) : 0)); + } + function fM(t, e, r) { + if ((e[0] & 192) !== 128) return (t.lastNeed = 0), '\uFFFD'; + if (t.lastNeed > 1 && e.length > 1) { + if ((e[1] & 192) !== 128) return (t.lastNeed = 1), '\uFFFD'; + if (t.lastNeed > 2 && e.length > 2 && (e[2] & 192) !== 128) return (t.lastNeed = 2), '\uFFFD'; + } + } + function aM(t) { + var e = this.lastTotal - this.lastNeed, + r = fM(this, t, e); + if (r !== undefined) return r; + if (this.lastNeed <= t.length) return t.copy(this.lastChar, e, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal); + t.copy(this.lastChar, e, 0, t.length), (this.lastNeed -= t.length); + } + function oM(t, e) { + var r = nM(this, t, e); + if (!this.lastNeed) return t.toString('utf8', e); + this.lastTotal = r; + var o = t.length - (r - this.lastNeed); + return t.copy(this.lastChar, 0, o), t.toString('utf8', e, o); + } + function sM(t) { + var e = t && t.length ? this.write(t) : ''; + return this.lastNeed ? e + '\uFFFD' : e; + } + function hM(t, e) { + if ((t.length - e) % 2 === 0) { + var r = t.toString('utf16le', e); + if (r) { + var o = r.charCodeAt(r.length - 1); + if (o >= 55296 && o <= 56319) return (this.lastNeed = 2), (this.lastTotal = 4), (this.lastChar[0] = t[t.length - 2]), (this.lastChar[1] = t[t.length - 1]), r.slice(0, -1); + } + return r; + } + return (this.lastNeed = 1), (this.lastTotal = 2), (this.lastChar[0] = t[t.length - 1]), t.toString('utf16le', e, t.length - 1); + } + function uM(t) { + var e = t && t.length ? this.write(t) : ''; + if (this.lastNeed) { + var r = this.lastTotal - this.lastNeed; + return e + this.lastChar.toString('utf16le', 0, r); + } + return e; + } + function lM(t, e) { + var r = (t.length - e) % 3; + return r === 0 + ? t.toString('base64', e) + : ((this.lastNeed = 3 - r), (this.lastTotal = 3), r === 1 ? (this.lastChar[0] = t[t.length - 1]) : ((this.lastChar[0] = t[t.length - 2]), (this.lastChar[1] = t[t.length - 1])), t.toString('base64', e, t.length - r)); + } + function dM(t) { + var e = t && t.length ? this.write(t) : ''; + return this.lastNeed ? e + this.lastChar.toString('base64', 0, 3 - this.lastNeed) : e; + } + function cM(t) { + return t.toString(this.encoding); + } + function pM(t) { + return t && t.length ? this.write(t) : ''; + } + }); + Jf = {}; + Ja(Jf, {StringDecoder: () => po.StringDecoder, default: () => po.StringDecoder}); + Qf = R0(() => { + po = rn(co()); + }); + vo = T2((hI, Nc) => { + var kc = sn().codes.ERR_STREAM_PREMATURE_CLOSE; + function vM(t) { + var e = false; + return function () { + if (!e) { + e = true; + for (var r = arguments.length, o = new Array(r), f = 0; f < r; f++) o[f] = arguments[f]; + t.apply(this, o); + } + }; + } + function bM() {} + function mM(t) { + return t.setHeader && typeof t.abort == 'function'; + } + function Lc(t, e, r) { + if (typeof e == 'function') return Lc(t, null, e); + e || (e = {}), (r = vM(r || bM)); + var o = e.readable || (e.readable !== false && t.readable), + f = e.writable || (e.writable !== false && t.writable), + p = function () { + t.writable || y2(); + }, + m2 = t._writableState && t._writableState.finished, + y2 = function () { + (f = false), (m2 = true), o || r.call(t); + }, + M = t._readableState && t._readableState.endEmitted, + x = function () { + (o = false), (M = true), f || r.call(t); + }, + S = function (L2) { + r.call(t, L2); + }, + E2 = function () { + var L2; + if (o && !M) return (!t._readableState || !t._readableState.ended) && (L2 = new kc()), r.call(t, L2); + if (f && !m2) return (!t._writableState || !t._writableState.ended) && (L2 = new kc()), r.call(t, L2); + }, + B = function () { + t.req.on('finish', y2); + }; + return ( + mM(t) ? (t.on('complete', y2), t.on('abort', E2), t.req ? B() : t.on('request', B)) : f && !t._writableState && (t.on('end', p), t.on('close', p)), + t.on('end', x), + t.on('finish', y2), + e.error !== false && t.on('error', S), + t.on('close', E2), + function () { + t.removeListener('complete', y2), + t.removeListener('abort', E2), + t.removeListener('request', B), + t.req && t.req.removeListener('finish', y2), + t.removeListener('end', p), + t.removeListener('close', p), + t.removeListener('finish', y2), + t.removeListener('end', x), + t.removeListener('error', S), + t.removeListener('close', E2); + } + ); + } + Nc.exports = Lc; + }); + Pc = T2((uI, Dc) => { + var bo; + function Ni(t, e, r) { + return e in t ? Object.defineProperty(t, e, {value: r, enumerable: true, configurable: true, writable: true}) : (t[e] = r), t; + } + var gM = vo(), + Di = Symbol('lastResolve'), + un = Symbol('lastReject'), + ea = Symbol('error'), + mo = Symbol('ended'), + ln = Symbol('lastPromise'), + nh = Symbol('handlePromise'), + dn = Symbol('stream'); + function Pi(t, e) { + return {value: t, done: e}; + } + function yM(t) { + var e = t[Di]; + if (e !== null) { + var r = t[dn].read(); + r !== null && ((t[ln] = null), (t[Di] = null), (t[un] = null), e(Pi(r, false))); + } + } + function wM(t) { + process.nextTick(yM, t); + } + function MM(t, e) { + return function (r, o) { + t.then(function () { + if (e[mo]) { + r(Pi(undefined, true)); + return; + } + e[nh](r, o); + }, o); + }; + } + var _M = Object.getPrototypeOf(function () {}), + xM = Object.setPrototypeOf( + ((bo = { + get stream() { + return this[dn]; + }, + next: function () { + var e = this, + r = this[ea]; + if (r !== null) return Promise.reject(r); + if (this[mo]) return Promise.resolve(Pi(undefined, true)); + if (this[dn].destroyed) + return new Promise(function (m2, y2) { + process.nextTick(function () { + e[ea] ? y2(e[ea]) : m2(Pi(undefined, true)); + }); + }); + var o = this[ln], + f; + if (o) f = new Promise(MM(o, this)); + else { + var p = this[dn].read(); + if (p !== null) return Promise.resolve(Pi(p, false)); + f = new Promise(this[nh]); + } + return (this[ln] = f), f; + } + }), + Ni(bo, Symbol.asyncIterator, function () { + return this; + }), + Ni(bo, 'return', function () { + var e = this; + return new Promise(function (r, o) { + e[dn].destroy(null, function (f) { + if (f) { + o(f); + return; + } + r(Pi(undefined, true)); + }); + }); + }), + bo), + _M + ), + SM = function (e) { + var r, + o = Object.create( + xM, + ((r = {}), + Ni(r, dn, {value: e, writable: true}), + Ni(r, Di, {value: null, writable: true}), + Ni(r, un, {value: null, writable: true}), + Ni(r, ea, {value: null, writable: true}), + Ni(r, mo, {value: e._readableState.endEmitted, writable: true}), + Ni(r, nh, { + value: function (p, m2) { + var y2 = o[dn].read(); + y2 ? ((o[ln] = null), (o[Di] = null), (o[un] = null), p(Pi(y2, false))) : ((o[Di] = p), (o[un] = m2)); + }, + writable: true + }), + r) + ); + return ( + (o[ln] = null), + gM(e, function (f) { + if (f && f.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var p = o[un]; + p !== null && ((o[ln] = null), (o[Di] = null), (o[un] = null), p(f)), (o[ea] = f); + return; + } + var m2 = o[Di]; + m2 !== null && ((o[ln] = null), (o[Di] = null), (o[un] = null), m2(Pi(undefined, true))), (o[mo] = true); + }), + e.on('readable', wM.bind(null, o)), + o + ); + }; + Dc.exports = SM; + }); + Oc = T2((lI, Cc) => { + Cc.exports = function () { + throw new Error('Readable.from is not available in the browser'); + }; + }); + th = T2((cI, $c) => { + $c.exports = Ce; + var tf; + Ce.ReadableState = Hc; + var dI = ki().EventEmitter, + zc = function (e, r) { + return e.listeners(r).length; + }, + ra = W0(), + go = Ut().Buffer, + EM = global.Uint8Array || function () {}; + function AM(t) { + return go.from(t); + } + function RM(t) { + return go.isBuffer(t) || t instanceof EM; + } + var fh = $f(), + Ne; + fh && fh.debuglog ? (Ne = fh.debuglog('stream')) : (Ne = function () {}); + var BM = pc(), + dh = Z0(), + qM = V0(), + IM = qM.getHighWaterMark, + yo = sn().codes, + TM = yo.ERR_INVALID_ARG_TYPE, + kM = yo.ERR_STREAM_PUSH_AFTER_EOF, + LM = yo.ERR_METHOD_NOT_IMPLEMENTED, + NM = yo.ERR_STREAM_UNSHIFT_AFTER_END_EVENT, + rf, + ah, + oh; + Ie()(Ce, ra); + var ta = dh.errorOrDestroy, + sh = ['error', 'close', 'destroy', 'pause', 'resume']; + function DM(t, e, r) { + if (typeof t.prependListener == 'function') return t.prependListener(e, r); + !t._events || !t._events[e] ? t.on(e, r) : Array.isArray(t._events[e]) ? t._events[e].unshift(r) : (t._events[e] = [r, t._events[e]]); + } + function Hc(t, e, r) { + (tf = tf || hn()), + (t = t || {}), + typeof r != 'boolean' && (r = e instanceof tf), + (this.objectMode = !!t.objectMode), + r && (this.objectMode = this.objectMode || !!t.readableObjectMode), + (this.highWaterMark = IM(this, t, 'readableHighWaterMark', r)), + (this.buffer = new BM()), + (this.length = 0), + (this.pipes = null), + (this.pipesCount = 0), + (this.flowing = null), + (this.ended = false), + (this.endEmitted = false), + (this.reading = false), + (this.sync = true), + (this.needReadable = false), + (this.emittedReadable = false), + (this.readableListening = false), + (this.resumeScheduled = false), + (this.paused = true), + (this.emitClose = t.emitClose !== false), + (this.autoDestroy = !!t.autoDestroy), + (this.destroyed = false), + (this.defaultEncoding = t.defaultEncoding || 'utf8'), + (this.awaitDrain = 0), + (this.readingMore = false), + (this.decoder = null), + (this.encoding = null), + t.encoding && (rf || (rf = (Qf(), ur(Jf)).StringDecoder), (this.decoder = new rf(t.encoding)), (this.encoding = t.encoding)); + } + function Ce(t) { + if (((tf = tf || hn()), !(this instanceof Ce))) return new Ce(t); + var e = this instanceof tf; + (this._readableState = new Hc(t, this, e)), (this.readable = true), t && (typeof t.read == 'function' && (this._read = t.read), typeof t.destroy == 'function' && (this._destroy = t.destroy)), ra.call(this); + } + Object.defineProperty(Ce.prototype, 'destroyed', { + enumerable: false, + get: function () { + return this._readableState === undefined ? false : this._readableState.destroyed; + }, + set: function (e) { + !this._readableState || (this._readableState.destroyed = e); + } + }); + Ce.prototype.destroy = dh.destroy; + Ce.prototype._undestroy = dh.undestroy; + Ce.prototype._destroy = function (t, e) { + e(t); + }; + Ce.prototype.push = function (t, e) { + var r = this._readableState, + o; + return r.objectMode ? (o = true) : typeof t == 'string' && ((e = e || r.defaultEncoding), e !== r.encoding && ((t = go.from(t, e)), (e = '')), (o = true)), Wc(this, t, e, false, o); + }; + Ce.prototype.unshift = function (t) { + return Wc(this, t, null, true, false); + }; + function Wc(t, e, r, o, f) { + Ne('readableAddChunk', e); + var p = t._readableState; + if (e === null) (p.reading = false), OM(t, p); + else { + var m2; + if ((f || (m2 = PM(p, e)), m2)) ta(t, m2); + else if (p.objectMode || (e && e.length > 0)) + if ((typeof e != 'string' && !p.objectMode && Object.getPrototypeOf(e) !== go.prototype && (e = AM(e)), o)) p.endEmitted ? ta(t, new NM()) : hh(t, p, e, true); + else if (p.ended) ta(t, new kM()); + else { + if (p.destroyed) return false; + (p.reading = false), p.decoder && !r ? ((e = p.decoder.write(e)), p.objectMode || e.length !== 0 ? hh(t, p, e, false) : lh(t, p)) : hh(t, p, e, false); + } + else o || ((p.reading = false), lh(t, p)); + } + return !p.ended && (p.length < p.highWaterMark || p.length === 0); + } + function hh(t, e, r, o) { + e.flowing && e.length === 0 && !e.sync ? ((e.awaitDrain = 0), t.emit('data', r)) : ((e.length += e.objectMode ? 1 : r.length), o ? e.buffer.unshift(r) : e.buffer.push(r), e.needReadable && wo(t)), lh(t, e); + } + function PM(t, e) { + var r; + return !RM(e) && typeof e != 'string' && e !== undefined && !t.objectMode && (r = new TM('chunk', ['string', 'Buffer', 'Uint8Array'], e)), r; + } + Ce.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + Ce.prototype.setEncoding = function (t) { + rf || (rf = (Qf(), ur(Jf)).StringDecoder); + var e = new rf(t); + (this._readableState.decoder = e), (this._readableState.encoding = this._readableState.decoder.encoding); + for (var r = this._readableState.buffer.head, o = ''; r !== null; ) (o += e.write(r.data)), (r = r.next); + return this._readableState.buffer.clear(), o !== '' && this._readableState.buffer.push(o), (this._readableState.length = o.length), this; + }; + var Fc = 1073741824; + function CM(t) { + return t >= Fc ? (t = Fc) : (t--, (t |= t >>> 1), (t |= t >>> 2), (t |= t >>> 4), (t |= t >>> 8), (t |= t >>> 16), t++), t; + } + function Uc(t, e) { + return t <= 0 || (e.length === 0 && e.ended) + ? 0 + : e.objectMode + ? 1 + : t !== t + ? e.flowing && e.length + ? e.buffer.head.data.length + : e.length + : (t > e.highWaterMark && (e.highWaterMark = CM(t)), t <= e.length ? t : e.ended ? e.length : ((e.needReadable = true), 0)); + } + Ce.prototype.read = function (t) { + Ne('read', t), (t = parseInt(t, 10)); + var e = this._readableState, + r = t; + if ((t !== 0 && (e.emittedReadable = false), t === 0 && e.needReadable && ((e.highWaterMark !== 0 ? e.length >= e.highWaterMark : e.length > 0) || e.ended))) + return Ne('read: emitReadable', e.length, e.ended), e.length === 0 && e.ended ? uh(this) : wo(this), null; + if (((t = Uc(t, e)), t === 0 && e.ended)) return e.length === 0 && uh(this), null; + var o = e.needReadable; + Ne('need readable', o), + (e.length === 0 || e.length - t < e.highWaterMark) && ((o = true), Ne('length less than watermark', o)), + e.ended || e.reading + ? ((o = false), Ne('reading or ended', o)) + : o && (Ne('do read'), (e.reading = true), (e.sync = true), e.length === 0 && (e.needReadable = true), this._read(e.highWaterMark), (e.sync = false), e.reading || (t = Uc(r, e))); + var f; + return ( + t > 0 ? (f = Zc(t, e)) : (f = null), + f === null ? ((e.needReadable = e.length <= e.highWaterMark), (t = 0)) : ((e.length -= t), (e.awaitDrain = 0)), + e.length === 0 && (e.ended || (e.needReadable = true), r !== t && e.ended && uh(this)), + f !== null && this.emit('data', f), + f + ); + }; + function OM(t, e) { + if ((Ne('onEofChunk'), !e.ended)) { + if (e.decoder) { + var r = e.decoder.end(); + r && r.length && (e.buffer.push(r), (e.length += e.objectMode ? 1 : r.length)); + } + (e.ended = true), e.sync ? wo(t) : ((e.needReadable = false), e.emittedReadable || ((e.emittedReadable = true), Kc(t))); + } + } + function wo(t) { + var e = t._readableState; + Ne('emitReadable', e.needReadable, e.emittedReadable), (e.needReadable = false), e.emittedReadable || (Ne('emitReadable', e.flowing), (e.emittedReadable = true), process.nextTick(Kc, t)); + } + function Kc(t) { + var e = t._readableState; + Ne('emitReadable_', e.destroyed, e.length, e.ended), !e.destroyed && (e.length || e.ended) && (t.emit('readable'), (e.emittedReadable = false)), (e.needReadable = !e.flowing && !e.ended && e.length <= e.highWaterMark), ch(t); + } + function lh(t, e) { + e.readingMore || ((e.readingMore = true), process.nextTick(FM, t, e)); + } + function FM(t, e) { + for (; !e.reading && !e.ended && (e.length < e.highWaterMark || (e.flowing && e.length === 0)); ) { + var r = e.length; + if ((Ne('maybeReadMore read 0'), t.read(0), r === e.length)) break; + } + e.readingMore = false; + } + Ce.prototype._read = function (t) { + ta(this, new LM('_read()')); + }; + Ce.prototype.pipe = function (t, e) { + var r = this, + o = this._readableState; + switch (o.pipesCount) { + case 0: + o.pipes = t; + break; + case 1: + o.pipes = [o.pipes, t]; + break; + default: + o.pipes.push(t); + break; + } + (o.pipesCount += 1), Ne('pipe count=%d opts=%j', o.pipesCount, e); + var f = (!e || e.end !== false) && t !== process.stdout && t !== process.stderr, + p = f ? y2 : ge; + o.endEmitted ? process.nextTick(p) : r.once('end', p), t.on('unpipe', m2); + function m2(_e, N) { + Ne('onunpipe'), _e === r && N && N.hasUnpiped === false && ((N.hasUnpiped = true), S()); + } + function y2() { + Ne('onend'), t.end(); + } + var M = UM(r); + t.on('drain', M); + var x = false; + function S() { + Ne('cleanup'), + t.removeListener('close', q2), + t.removeListener('finish', L2), + t.removeListener('drain', M), + t.removeListener('error', B), + t.removeListener('unpipe', m2), + r.removeListener('end', y2), + r.removeListener('end', ge), + r.removeListener('data', E2), + (x = true), + o.awaitDrain && (!t._writableState || t._writableState.needDrain) && M(); + } + r.on('data', E2); + function E2(_e) { + Ne('ondata'); + var N = t.write(_e); + Ne('dest.write', N), N === false && (((o.pipesCount === 1 && o.pipes === t) || (o.pipesCount > 1 && Vc(o.pipes, t) !== -1)) && !x && (Ne('false write response, pause', o.awaitDrain), o.awaitDrain++), r.pause()); + } + function B(_e) { + Ne('onerror', _e), ge(), t.removeListener('error', B), zc(t, 'error') === 0 && ta(t, _e); + } + DM(t, 'error', B); + function q2() { + t.removeListener('finish', L2), ge(); + } + t.once('close', q2); + function L2() { + Ne('onfinish'), t.removeListener('close', q2), ge(); + } + t.once('finish', L2); + function ge() { + Ne('unpipe'), r.unpipe(t); + } + return t.emit('pipe', r), o.flowing || (Ne('pipe resume'), r.resume()), t; + }; + function UM(t) { + return function () { + var r = t._readableState; + Ne('pipeOnDrain', r.awaitDrain), r.awaitDrain && r.awaitDrain--, r.awaitDrain === 0 && zc(t, 'data') && ((r.flowing = true), ch(t)); + }; + } + Ce.prototype.unpipe = function (t) { + var e = this._readableState, + r = {hasUnpiped: false}; + if (e.pipesCount === 0) return this; + if (e.pipesCount === 1) return t && t !== e.pipes ? this : (t || (t = e.pipes), (e.pipes = null), (e.pipesCount = 0), (e.flowing = false), t && t.emit('unpipe', this, r), this); + if (!t) { + var {pipes: o, pipesCount: f} = e; + (e.pipes = null), (e.pipesCount = 0), (e.flowing = false); + for (var p = 0; p < f; p++) o[p].emit('unpipe', this, {hasUnpiped: false}); + return this; + } + var m2 = Vc(e.pipes, t); + return m2 === -1 ? this : (e.pipes.splice(m2, 1), (e.pipesCount -= 1), e.pipesCount === 1 && (e.pipes = e.pipes[0]), t.emit('unpipe', this, r), this); + }; + Ce.prototype.on = function (t, e) { + var r = ra.prototype.on.call(this, t, e), + o = this._readableState; + return ( + t === 'data' + ? ((o.readableListening = this.listenerCount('readable') > 0), o.flowing !== false && this.resume()) + : t === 'readable' && + !o.endEmitted && + !o.readableListening && + ((o.readableListening = o.needReadable = true), (o.flowing = false), (o.emittedReadable = false), Ne('on readable', o.length, o.reading), o.length ? wo(this) : o.reading || process.nextTick(zM, this)), + r + ); + }; + Ce.prototype.addListener = Ce.prototype.on; + Ce.prototype.removeListener = function (t, e) { + var r = ra.prototype.removeListener.call(this, t, e); + return t === 'readable' && process.nextTick(jc, this), r; + }; + Ce.prototype.removeAllListeners = function (t) { + var e = ra.prototype.removeAllListeners.apply(this, arguments); + return (t === 'readable' || t === undefined) && process.nextTick(jc, this), e; + }; + function jc(t) { + var e = t._readableState; + (e.readableListening = t.listenerCount('readable') > 0), e.resumeScheduled && !e.paused ? (e.flowing = true) : t.listenerCount('data') > 0 && t.resume(); + } + function zM(t) { + Ne('readable nexttick read 0'), t.read(0); + } + Ce.prototype.resume = function () { + var t = this._readableState; + return t.flowing || (Ne('resume'), (t.flowing = !t.readableListening), HM(this, t)), (t.paused = false), this; + }; + function HM(t, e) { + e.resumeScheduled || ((e.resumeScheduled = true), process.nextTick(WM, t, e)); + } + function WM(t, e) { + Ne('resume', e.reading), e.reading || t.read(0), (e.resumeScheduled = false), t.emit('resume'), ch(t), e.flowing && !e.reading && t.read(0); + } + Ce.prototype.pause = function () { + return Ne('call pause flowing=%j', this._readableState.flowing), this._readableState.flowing !== false && (Ne('pause'), (this._readableState.flowing = false), this.emit('pause')), (this._readableState.paused = true), this; + }; + function ch(t) { + var e = t._readableState; + for (Ne('flow', e.flowing); e.flowing && t.read() !== null; ); + } + Ce.prototype.wrap = function (t) { + var e = this, + r = this._readableState, + o = false; + t.on('end', function () { + if ((Ne('wrapped end'), r.decoder && !r.ended)) { + var m2 = r.decoder.end(); + m2 && m2.length && e.push(m2); + } + e.push(null); + }), + t.on('data', function (m2) { + if ((Ne('wrapped data'), r.decoder && (m2 = r.decoder.write(m2)), !(r.objectMode && m2 == null) && !(!r.objectMode && (!m2 || !m2.length)))) { + var y2 = e.push(m2); + y2 || ((o = true), t.pause()); + } + }); + for (var f in t) + this[f] === undefined && + typeof t[f] == 'function' && + (this[f] = (function (y2) { + return function () { + return t[y2].apply(t, arguments); + }; + })(f)); + for (var p = 0; p < sh.length; p++) t.on(sh[p], this.emit.bind(this, sh[p])); + return ( + (this._read = function (m2) { + Ne('wrapped _read', m2), o && ((o = false), t.resume()); + }), + this + ); + }; + typeof Symbol == 'function' && + (Ce.prototype[Symbol.asyncIterator] = function () { + return ah === undefined && (ah = Pc()), ah(this); + }); + Object.defineProperty(Ce.prototype, 'readableHighWaterMark', { + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Ce.prototype, 'readableBuffer', { + enumerable: false, + get: function () { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Ce.prototype, 'readableFlowing', { + enumerable: false, + get: function () { + return this._readableState.flowing; + }, + set: function (e) { + this._readableState && (this._readableState.flowing = e); + } + }); + Ce._fromList = Zc; + Object.defineProperty(Ce.prototype, 'readableLength', { + enumerable: false, + get: function () { + return this._readableState.length; + } + }); + function Zc(t, e) { + if (e.length === 0) return null; + var r; + return ( + e.objectMode + ? (r = e.buffer.shift()) + : !t || t >= e.length + ? (e.decoder ? (r = e.buffer.join('')) : e.buffer.length === 1 ? (r = e.buffer.first()) : (r = e.buffer.concat(e.length)), e.buffer.clear()) + : (r = e.buffer.consume(t, e.decoder)), + r + ); + } + function uh(t) { + var e = t._readableState; + Ne('endReadable', e.endEmitted), e.endEmitted || ((e.ended = true), process.nextTick(KM, e, t)); + } + function KM(t, e) { + if ((Ne('endReadableNT', t.endEmitted, t.length), !t.endEmitted && t.length === 0 && ((t.endEmitted = true), (e.readable = false), e.emit('end'), t.autoDestroy))) { + var r = e._writableState; + (!r || (r.autoDestroy && r.finished)) && e.destroy(); + } + } + typeof Symbol == 'function' && + (Ce.from = function (t, e) { + return oh === undefined && (oh = Oc()), oh(Ce, t, e); + }); + function Vc(t, e) { + for (var r = 0, o = t.length; r < o; r++) if (t[r] === e) return r; + return -1; + } + }); + ph = T2((pI, Yc) => { + Yc.exports = di; + var Mo = sn().codes, + jM = Mo.ERR_METHOD_NOT_IMPLEMENTED, + ZM = Mo.ERR_MULTIPLE_CALLBACK, + VM = Mo.ERR_TRANSFORM_ALREADY_TRANSFORMING, + $M = Mo.ERR_TRANSFORM_WITH_LENGTH_0, + _o = hn(); + Ie()(di, _o); + function GM(t, e) { + var r = this._transformState; + r.transforming = false; + var o = r.writecb; + if (o === null) return this.emit('error', new ZM()); + (r.writechunk = null), (r.writecb = null), e != null && this.push(e), o(t); + var f = this._readableState; + (f.reading = false), (f.needReadable || f.length < f.highWaterMark) && this._read(f.highWaterMark); + } + function di(t) { + if (!(this instanceof di)) return new di(t); + _o.call(this, t), + (this._transformState = {afterTransform: GM.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null}), + (this._readableState.needReadable = true), + (this._readableState.sync = false), + t && (typeof t.transform == 'function' && (this._transform = t.transform), typeof t.flush == 'function' && (this._flush = t.flush)), + this.on('prefinish', YM); + } + function YM() { + var t = this; + typeof this._flush == 'function' && !this._readableState.destroyed + ? this._flush(function (e, r) { + Gc(t, e, r); + }) + : Gc(this, null, null); + } + di.prototype.push = function (t, e) { + return (this._transformState.needTransform = false), _o.prototype.push.call(this, t, e); + }; + di.prototype._transform = function (t, e, r) { + r(new jM('_transform()')); + }; + di.prototype._write = function (t, e, r) { + var o = this._transformState; + if (((o.writecb = r), (o.writechunk = t), (o.writeencoding = e), !o.transforming)) { + var f = this._readableState; + (o.needTransform || f.needReadable || f.length < f.highWaterMark) && this._read(f.highWaterMark); + } + }; + di.prototype._read = function (t) { + var e = this._transformState; + e.writechunk !== null && !e.transforming ? ((e.transforming = true), this._transform(e.writechunk, e.writeencoding, e.afterTransform)) : (e.needTransform = true); + }; + di.prototype._destroy = function (t, e) { + _o.prototype._destroy.call(this, t, function (r) { + e(r); + }); + }; + function Gc(t, e, r) { + if (e) return t.emit('error', e); + if ((r != null && t.push(r), t._writableState.length)) throw new $M(); + if (t._transformState.transforming) throw new VM(); + return t.push(null); + } + }); + Qc = T2((vI, Jc) => { + Jc.exports = ia; + var Xc = ph(); + Ie()(ia, Xc); + function ia(t) { + if (!(this instanceof ia)) return new ia(t); + Xc.call(this, t); + } + ia.prototype._transform = function (t, e, r) { + r(null, t); + }; + }); + np = T2((bI, ip) => { + var vh; + function XM(t) { + var e = false; + return function () { + e || ((e = true), t.apply(undefined, arguments)); + }; + } + var rp = sn().codes, + JM = rp.ERR_MISSING_ARGS, + QM = rp.ERR_STREAM_DESTROYED; + function ep(t) { + if (t) throw t; + } + function e4(t) { + return t.setHeader && typeof t.abort == 'function'; + } + function t4(t, e, r, o) { + o = XM(o); + var f = false; + t.on('close', function () { + f = true; + }), + vh === undefined && (vh = vo()), + vh(t, {readable: e, writable: r}, function (m2) { + if (m2) return o(m2); + (f = true), o(); + }); + var p = false; + return function (m2) { + if (!f && !p) { + if (((p = true), e4(t))) return t.abort(); + if (typeof t.destroy == 'function') return t.destroy(); + o(m2 || new QM('pipe')); + } + }; + } + function tp(t) { + t(); + } + function r4(t, e) { + return t.pipe(e); + } + function i4(t) { + return !t.length || typeof t[t.length - 1] != 'function' ? ep : t.pop(); + } + function n4() { + for (var t = arguments.length, e = new Array(t), r = 0; r < t; r++) e[r] = arguments[r]; + var o = i4(e); + if ((Array.isArray(e[0]) && (e = e[0]), e.length < 2)) throw new JM('streams'); + var f, + p = e.map(function (m2, y2) { + var M = y2 < e.length - 1, + x = y2 > 0; + return t4(m2, M, x, function (S) { + f || (f = S), S && p.forEach(tp), !M && (p.forEach(tp), o(f)); + }); + }); + return e.reduce(r4); + } + ip.exports = n4; + }); + ap = T2((cr, fp) => { + cr = fp.exports = th(); + cr.Stream = cr; + cr.Readable = cr; + cr.Writable = J0(); + cr.Duplex = hn(); + cr.Transform = ph(); + cr.PassThrough = Qc(); + cr.finished = vo(); + cr.pipeline = np(); + }); + bh = T2((mI, sp) => { + var xo = Te().Buffer, + op = ap().Transform, + f4 = Ie(); + function a4(t, e) { + if (!xo.isBuffer(t) && typeof t != 'string') throw new TypeError(e + ' must be a string or a buffer'); + } + function Ci(t) { + op.call(this), (this._block = xo.allocUnsafe(t)), (this._blockSize = t), (this._blockOffset = 0), (this._length = [0, 0, 0, 0]), (this._finalized = false); + } + f4(Ci, op); + Ci.prototype._transform = function (t, e, r) { + var o = null; + try { + this.update(t, e); + } catch (f) { + o = f; + } + r(o); + }; + Ci.prototype._flush = function (t) { + var e = null; + try { + this.push(this.digest()); + } catch (r) { + e = r; + } + t(e); + }; + Ci.prototype.update = function (t, e) { + if ((a4(t, 'Data'), this._finalized)) throw new Error('Digest already called'); + xo.isBuffer(t) || (t = xo.from(t, e)); + for (var r = this._block, o = 0; this._blockOffset + t.length - o >= this._blockSize; ) { + for (var f = this._blockOffset; f < this._blockSize; ) r[f++] = t[o++]; + this._update(), (this._blockOffset = 0); + } + for (; o < t.length; ) r[this._blockOffset++] = t[o++]; + for (var p = 0, m2 = t.length * 8; m2 > 0; ++p) (this._length[p] += m2), (m2 = (this._length[p] / 4294967296) | 0), m2 > 0 && (this._length[p] -= 4294967296 * m2); + return this; + }; + Ci.prototype._update = function () { + throw new Error('_update is not implemented'); + }; + Ci.prototype.digest = function (t) { + if (this._finalized) throw new Error('Digest already called'); + this._finalized = true; + var e = this._digest(); + t !== undefined && (e = e.toString(t)), this._block.fill(0), (this._blockOffset = 0); + for (var r = 0; r < 4; ++r) this._length[r] = 0; + return e; + }; + Ci.prototype._digest = function () { + throw new Error('_digest is not implemented'); + }; + sp.exports = Ci; + }); + Ao = T2((gI, up) => { + var o4 = Ie(), + hp = bh(), + s4 = Te().Buffer, + h4 = new Array(16); + function So() { + hp.call(this, 64), (this._a = 1732584193), (this._b = 4023233417), (this._c = 2562383102), (this._d = 271733878); + } + o4(So, hp); + So.prototype._update = function () { + for (var t = h4, e = 0; e < 16; ++e) t[e] = this._block.readInt32LE(e * 4); + var r = this._a, + o = this._b, + f = this._c, + p = this._d; + (r = jt(r, o, f, p, t[0], 3614090360, 7)), + (p = jt(p, r, o, f, t[1], 3905402710, 12)), + (f = jt(f, p, r, o, t[2], 606105819, 17)), + (o = jt(o, f, p, r, t[3], 3250441966, 22)), + (r = jt(r, o, f, p, t[4], 4118548399, 7)), + (p = jt(p, r, o, f, t[5], 1200080426, 12)), + (f = jt(f, p, r, o, t[6], 2821735955, 17)), + (o = jt(o, f, p, r, t[7], 4249261313, 22)), + (r = jt(r, o, f, p, t[8], 1770035416, 7)), + (p = jt(p, r, o, f, t[9], 2336552879, 12)), + (f = jt(f, p, r, o, t[10], 4294925233, 17)), + (o = jt(o, f, p, r, t[11], 2304563134, 22)), + (r = jt(r, o, f, p, t[12], 1804603682, 7)), + (p = jt(p, r, o, f, t[13], 4254626195, 12)), + (f = jt(f, p, r, o, t[14], 2792965006, 17)), + (o = jt(o, f, p, r, t[15], 1236535329, 22)), + (r = Zt(r, o, f, p, t[1], 4129170786, 5)), + (p = Zt(p, r, o, f, t[6], 3225465664, 9)), + (f = Zt(f, p, r, o, t[11], 643717713, 14)), + (o = Zt(o, f, p, r, t[0], 3921069994, 20)), + (r = Zt(r, o, f, p, t[5], 3593408605, 5)), + (p = Zt(p, r, o, f, t[10], 38016083, 9)), + (f = Zt(f, p, r, o, t[15], 3634488961, 14)), + (o = Zt(o, f, p, r, t[4], 3889429448, 20)), + (r = Zt(r, o, f, p, t[9], 568446438, 5)), + (p = Zt(p, r, o, f, t[14], 3275163606, 9)), + (f = Zt(f, p, r, o, t[3], 4107603335, 14)), + (o = Zt(o, f, p, r, t[8], 1163531501, 20)), + (r = Zt(r, o, f, p, t[13], 2850285829, 5)), + (p = Zt(p, r, o, f, t[2], 4243563512, 9)), + (f = Zt(f, p, r, o, t[7], 1735328473, 14)), + (o = Zt(o, f, p, r, t[12], 2368359562, 20)), + (r = Vt(r, o, f, p, t[5], 4294588738, 4)), + (p = Vt(p, r, o, f, t[8], 2272392833, 11)), + (f = Vt(f, p, r, o, t[11], 1839030562, 16)), + (o = Vt(o, f, p, r, t[14], 4259657740, 23)), + (r = Vt(r, o, f, p, t[1], 2763975236, 4)), + (p = Vt(p, r, o, f, t[4], 1272893353, 11)), + (f = Vt(f, p, r, o, t[7], 4139469664, 16)), + (o = Vt(o, f, p, r, t[10], 3200236656, 23)), + (r = Vt(r, o, f, p, t[13], 681279174, 4)), + (p = Vt(p, r, o, f, t[0], 3936430074, 11)), + (f = Vt(f, p, r, o, t[3], 3572445317, 16)), + (o = Vt(o, f, p, r, t[6], 76029189, 23)), + (r = Vt(r, o, f, p, t[9], 3654602809, 4)), + (p = Vt(p, r, o, f, t[12], 3873151461, 11)), + (f = Vt(f, p, r, o, t[15], 530742520, 16)), + (o = Vt(o, f, p, r, t[2], 3299628645, 23)), + (r = $t(r, o, f, p, t[0], 4096336452, 6)), + (p = $t(p, r, o, f, t[7], 1126891415, 10)), + (f = $t(f, p, r, o, t[14], 2878612391, 15)), + (o = $t(o, f, p, r, t[5], 4237533241, 21)), + (r = $t(r, o, f, p, t[12], 1700485571, 6)), + (p = $t(p, r, o, f, t[3], 2399980690, 10)), + (f = $t(f, p, r, o, t[10], 4293915773, 15)), + (o = $t(o, f, p, r, t[1], 2240044497, 21)), + (r = $t(r, o, f, p, t[8], 1873313359, 6)), + (p = $t(p, r, o, f, t[15], 4264355552, 10)), + (f = $t(f, p, r, o, t[6], 2734768916, 15)), + (o = $t(o, f, p, r, t[13], 1309151649, 21)), + (r = $t(r, o, f, p, t[4], 4149444226, 6)), + (p = $t(p, r, o, f, t[11], 3174756917, 10)), + (f = $t(f, p, r, o, t[2], 718787259, 15)), + (o = $t(o, f, p, r, t[9], 3951481745, 21)), + (this._a = (this._a + r) | 0), + (this._b = (this._b + o) | 0), + (this._c = (this._c + f) | 0), + (this._d = (this._d + p) | 0); + }; + So.prototype._digest = function () { + (this._block[this._blockOffset++] = 128), + this._blockOffset > 56 && (this._block.fill(0, this._blockOffset, 64), this._update(), (this._blockOffset = 0)), + this._block.fill(0, this._blockOffset, 56), + this._block.writeUInt32LE(this._length[0], 56), + this._block.writeUInt32LE(this._length[1], 60), + this._update(); + var t = s4.allocUnsafe(16); + return t.writeInt32LE(this._a, 0), t.writeInt32LE(this._b, 4), t.writeInt32LE(this._c, 8), t.writeInt32LE(this._d, 12), t; + }; + function Eo(t, e) { + return (t << e) | (t >>> (32 - e)); + } + function jt(t, e, r, o, f, p, m2) { + return (Eo((t + ((e & r) | (~e & o)) + f + p) | 0, m2) + e) | 0; + } + function Zt(t, e, r, o, f, p, m2) { + return (Eo((t + ((e & o) | (r & ~o)) + f + p) | 0, m2) + e) | 0; + } + function Vt(t, e, r, o, f, p, m2) { + return (Eo((t + (e ^ r ^ o) + f + p) | 0, m2) + e) | 0; + } + function $t(t, e, r, o, f, p, m2) { + return (Eo((t + (r ^ (e | ~o)) + f + p) | 0, m2) + e) | 0; + } + up.exports = So; + }); + Bo = T2((yI, mp) => { + var mh = Ut().Buffer, + u4 = Ie(), + bp = bh(), + l4 = new Array(16), + na = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, + 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 + ], + fa = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, + 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 + ], + aa = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, + 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 + ], + oa = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, + 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 + ], + sa = [0, 1518500249, 1859775393, 2400959708, 2840853838], + ha = [1352829926, 1548603684, 1836072691, 2053994217, 0]; + function Ro() { + bp.call(this, 64), (this._a = 1732584193), (this._b = 4023233417), (this._c = 2562383102), (this._d = 271733878), (this._e = 3285377520); + } + u4(Ro, bp); + Ro.prototype._update = function () { + for (var t = l4, e = 0; e < 16; ++e) t[e] = this._block.readInt32LE(e * 4); + for (var r = this._a | 0, o = this._b | 0, f = this._c | 0, p = this._d | 0, m2 = this._e | 0, y2 = this._a | 0, M = this._b | 0, x = this._c | 0, S = this._d | 0, E2 = this._e | 0, B = 0; B < 80; B += 1) { + var q2, L2; + B < 16 + ? ((q2 = lp(r, o, f, p, m2, t[na[B]], sa[0], aa[B])), (L2 = vp(y2, M, x, S, E2, t[fa[B]], ha[0], oa[B]))) + : B < 32 + ? ((q2 = dp(r, o, f, p, m2, t[na[B]], sa[1], aa[B])), (L2 = pp(y2, M, x, S, E2, t[fa[B]], ha[1], oa[B]))) + : B < 48 + ? ((q2 = cp(r, o, f, p, m2, t[na[B]], sa[2], aa[B])), (L2 = cp(y2, M, x, S, E2, t[fa[B]], ha[2], oa[B]))) + : B < 64 + ? ((q2 = pp(r, o, f, p, m2, t[na[B]], sa[3], aa[B])), (L2 = dp(y2, M, x, S, E2, t[fa[B]], ha[3], oa[B]))) + : ((q2 = vp(r, o, f, p, m2, t[na[B]], sa[4], aa[B])), (L2 = lp(y2, M, x, S, E2, t[fa[B]], ha[4], oa[B]))), + (r = m2), + (m2 = p), + (p = cn(f, 10)), + (f = o), + (o = q2), + (y2 = E2), + (E2 = S), + (S = cn(x, 10)), + (x = M), + (M = L2); + } + var ge = (this._b + f + S) | 0; + (this._b = (this._c + p + E2) | 0), (this._c = (this._d + m2 + y2) | 0), (this._d = (this._e + r + M) | 0), (this._e = (this._a + o + x) | 0), (this._a = ge); + }; + Ro.prototype._digest = function () { + (this._block[this._blockOffset++] = 128), + this._blockOffset > 56 && (this._block.fill(0, this._blockOffset, 64), this._update(), (this._blockOffset = 0)), + this._block.fill(0, this._blockOffset, 56), + this._block.writeUInt32LE(this._length[0], 56), + this._block.writeUInt32LE(this._length[1], 60), + this._update(); + var t = mh.alloc ? mh.alloc(20) : new mh(20); + return t.writeInt32LE(this._a, 0), t.writeInt32LE(this._b, 4), t.writeInt32LE(this._c, 8), t.writeInt32LE(this._d, 12), t.writeInt32LE(this._e, 16), t; + }; + function cn(t, e) { + return (t << e) | (t >>> (32 - e)); + } + function lp(t, e, r, o, f, p, m2, y2) { + return (cn((t + (e ^ r ^ o) + p + m2) | 0, y2) + f) | 0; + } + function dp(t, e, r, o, f, p, m2, y2) { + return (cn((t + ((e & r) | (~e & o)) + p + m2) | 0, y2) + f) | 0; + } + function cp(t, e, r, o, f, p, m2, y2) { + return (cn((t + ((e | ~r) ^ o) + p + m2) | 0, y2) + f) | 0; + } + function pp(t, e, r, o, f, p, m2, y2) { + return (cn((t + ((e & o) | (r & ~o)) + p + m2) | 0, y2) + f) | 0; + } + function vp(t, e, r, o, f, p, m2, y2) { + return (cn((t + (e ^ (r | ~o)) + p + m2) | 0, y2) + f) | 0; + } + mp.exports = Ro; + }); + pn = T2((wI, yp) => { + var gp = Te().Buffer; + function qo(t, e) { + (this._block = gp.alloc(t)), (this._finalSize = e), (this._blockSize = t), (this._len = 0); + } + qo.prototype.update = function (t, e) { + typeof t == 'string' && ((e = e || 'utf8'), (t = gp.from(t, e))); + for (var r = this._block, o = this._blockSize, f = t.length, p = this._len, m2 = 0; m2 < f; ) { + for (var y2 = p % o, M = Math.min(f - m2, o - y2), x = 0; x < M; x++) r[y2 + x] = t[m2 + x]; + (p += M), (m2 += M), p % o === 0 && this._update(r); + } + return (this._len += f), this; + }; + qo.prototype.digest = function (t) { + var e = this._len % this._blockSize; + (this._block[e] = 128), this._block.fill(0, e + 1), e >= this._finalSize && (this._update(this._block), this._block.fill(0)); + var r = this._len * 8; + if (r <= 4294967295) this._block.writeUInt32BE(r, this._blockSize - 4); + else { + var o = (r & 4294967295) >>> 0, + f = (r - o) / 4294967296; + this._block.writeUInt32BE(f, this._blockSize - 8), this._block.writeUInt32BE(o, this._blockSize - 4); + } + this._update(this._block); + var p = this._hash(); + return t ? p.toString(t) : p; + }; + qo.prototype._update = function () { + throw new Error('_update must be implemented by subclass'); + }; + yp.exports = qo; + }); + _p = T2((MI, Mp) => { + var d4 = Ie(), + wp = pn(), + c4 = Te().Buffer, + p4 = [1518500249, 1859775393, -1894007588, -899497514], + v4 = new Array(80); + function ua() { + this.init(), (this._w = v4), wp.call(this, 64, 56); + } + d4(ua, wp); + ua.prototype.init = function () { + return (this._a = 1732584193), (this._b = 4023233417), (this._c = 2562383102), (this._d = 271733878), (this._e = 3285377520), this; + }; + function b4(t) { + return (t << 5) | (t >>> 27); + } + function m4(t) { + return (t << 30) | (t >>> 2); + } + function g4(t, e, r, o) { + return t === 0 ? (e & r) | (~e & o) : t === 2 ? (e & r) | (e & o) | (r & o) : e ^ r ^ o; + } + ua.prototype._update = function (t) { + for (var e = this._w, r = this._a | 0, o = this._b | 0, f = this._c | 0, p = this._d | 0, m2 = this._e | 0, y2 = 0; y2 < 16; ++y2) e[y2] = t.readInt32BE(y2 * 4); + for (; y2 < 80; ++y2) e[y2] = e[y2 - 3] ^ e[y2 - 8] ^ e[y2 - 14] ^ e[y2 - 16]; + for (var M = 0; M < 80; ++M) { + var x = ~~(M / 20), + S = (b4(r) + g4(x, o, f, p) + m2 + e[M] + p4[x]) | 0; + (m2 = p), (p = f), (f = m4(o)), (o = r), (r = S); + } + (this._a = (r + this._a) | 0), (this._b = (o + this._b) | 0), (this._c = (f + this._c) | 0), (this._d = (p + this._d) | 0), (this._e = (m2 + this._e) | 0); + }; + ua.prototype._hash = function () { + var t = c4.allocUnsafe(20); + return t.writeInt32BE(this._a | 0, 0), t.writeInt32BE(this._b | 0, 4), t.writeInt32BE(this._c | 0, 8), t.writeInt32BE(this._d | 0, 12), t.writeInt32BE(this._e | 0, 16), t; + }; + Mp.exports = ua; + }); + Ep = T2((_I, Sp) => { + var y4 = Ie(), + xp = pn(), + w4 = Te().Buffer, + M4 = [1518500249, 1859775393, -1894007588, -899497514], + _4 = new Array(80); + function la() { + this.init(), (this._w = _4), xp.call(this, 64, 56); + } + y4(la, xp); + la.prototype.init = function () { + return (this._a = 1732584193), (this._b = 4023233417), (this._c = 2562383102), (this._d = 271733878), (this._e = 3285377520), this; + }; + function x4(t) { + return (t << 1) | (t >>> 31); + } + function S4(t) { + return (t << 5) | (t >>> 27); + } + function E4(t) { + return (t << 30) | (t >>> 2); + } + function A4(t, e, r, o) { + return t === 0 ? (e & r) | (~e & o) : t === 2 ? (e & r) | (e & o) | (r & o) : e ^ r ^ o; + } + la.prototype._update = function (t) { + for (var e = this._w, r = this._a | 0, o = this._b | 0, f = this._c | 0, p = this._d | 0, m2 = this._e | 0, y2 = 0; y2 < 16; ++y2) e[y2] = t.readInt32BE(y2 * 4); + for (; y2 < 80; ++y2) e[y2] = x4(e[y2 - 3] ^ e[y2 - 8] ^ e[y2 - 14] ^ e[y2 - 16]); + for (var M = 0; M < 80; ++M) { + var x = ~~(M / 20), + S = (S4(r) + A4(x, o, f, p) + m2 + e[M] + M4[x]) | 0; + (m2 = p), (p = f), (f = E4(o)), (o = r), (r = S); + } + (this._a = (r + this._a) | 0), (this._b = (o + this._b) | 0), (this._c = (f + this._c) | 0), (this._d = (p + this._d) | 0), (this._e = (m2 + this._e) | 0); + }; + la.prototype._hash = function () { + var t = w4.allocUnsafe(20); + return t.writeInt32BE(this._a | 0, 0), t.writeInt32BE(this._b | 0, 4), t.writeInt32BE(this._c | 0, 8), t.writeInt32BE(this._d | 0, 12), t.writeInt32BE(this._e | 0, 16), t; + }; + Sp.exports = la; + }); + gh = T2((xI, Rp) => { + var R4 = Ie(), + Ap = pn(), + B4 = Te().Buffer, + q4 = [ + 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, + 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, + 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, + 2428436474, 2756734187, 3204031479, 3329325298 + ], + I4 = new Array(64); + function da() { + this.init(), (this._w = I4), Ap.call(this, 64, 56); + } + R4(da, Ap); + da.prototype.init = function () { + return (this._a = 1779033703), (this._b = 3144134277), (this._c = 1013904242), (this._d = 2773480762), (this._e = 1359893119), (this._f = 2600822924), (this._g = 528734635), (this._h = 1541459225), this; + }; + function T4(t, e, r) { + return r ^ (t & (e ^ r)); + } + function k4(t, e, r) { + return (t & e) | (r & (t | e)); + } + function L4(t) { + return ((t >>> 2) | (t << 30)) ^ ((t >>> 13) | (t << 19)) ^ ((t >>> 22) | (t << 10)); + } + function N4(t) { + return ((t >>> 6) | (t << 26)) ^ ((t >>> 11) | (t << 21)) ^ ((t >>> 25) | (t << 7)); + } + function D4(t) { + return ((t >>> 7) | (t << 25)) ^ ((t >>> 18) | (t << 14)) ^ (t >>> 3); + } + function P4(t) { + return ((t >>> 17) | (t << 15)) ^ ((t >>> 19) | (t << 13)) ^ (t >>> 10); + } + da.prototype._update = function (t) { + for (var e = this._w, r = this._a | 0, o = this._b | 0, f = this._c | 0, p = this._d | 0, m2 = this._e | 0, y2 = this._f | 0, M = this._g | 0, x = this._h | 0, S = 0; S < 16; ++S) e[S] = t.readInt32BE(S * 4); + for (; S < 64; ++S) e[S] = (P4(e[S - 2]) + e[S - 7] + D4(e[S - 15]) + e[S - 16]) | 0; + for (var E2 = 0; E2 < 64; ++E2) { + var B = (x + N4(m2) + T4(m2, y2, M) + q4[E2] + e[E2]) | 0, + q2 = (L4(r) + k4(r, o, f)) | 0; + (x = M), (M = y2), (y2 = m2), (m2 = (p + B) | 0), (p = f), (f = o), (o = r), (r = (B + q2) | 0); + } + (this._a = (r + this._a) | 0), + (this._b = (o + this._b) | 0), + (this._c = (f + this._c) | 0), + (this._d = (p + this._d) | 0), + (this._e = (m2 + this._e) | 0), + (this._f = (y2 + this._f) | 0), + (this._g = (M + this._g) | 0), + (this._h = (x + this._h) | 0); + }; + da.prototype._hash = function () { + var t = B4.allocUnsafe(32); + return t.writeInt32BE(this._a, 0), t.writeInt32BE(this._b, 4), t.writeInt32BE(this._c, 8), t.writeInt32BE(this._d, 12), t.writeInt32BE(this._e, 16), t.writeInt32BE(this._f, 20), t.writeInt32BE(this._g, 24), t.writeInt32BE(this._h, 28), t; + }; + Rp.exports = da; + }); + qp = T2((SI, Bp) => { + var C4 = Ie(), + O4 = gh(), + F4 = pn(), + U4 = Te().Buffer, + z4 = new Array(64); + function Io() { + this.init(), (this._w = z4), F4.call(this, 64, 56); + } + C4(Io, O4); + Io.prototype.init = function () { + return (this._a = 3238371032), (this._b = 914150663), (this._c = 812702999), (this._d = 4144912697), (this._e = 4290775857), (this._f = 1750603025), (this._g = 1694076839), (this._h = 3204075428), this; + }; + Io.prototype._hash = function () { + var t = U4.allocUnsafe(28); + return t.writeInt32BE(this._a, 0), t.writeInt32BE(this._b, 4), t.writeInt32BE(this._c, 8), t.writeInt32BE(this._d, 12), t.writeInt32BE(this._e, 16), t.writeInt32BE(this._f, 20), t.writeInt32BE(this._g, 24), t; + }; + Bp.exports = Io; + }); + yh = T2((EI, Pp) => { + var H4 = Ie(), + Dp = pn(), + W4 = Te().Buffer, + Ip = [ + 1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, + 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, + 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, + 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, + 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, + 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, + 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, + 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, + 1607167915, 987167468, 1816402316, 1246189591 + ], + K4 = new Array(160); + function ca() { + this.init(), (this._w = K4), Dp.call(this, 128, 112); + } + H4(ca, Dp); + ca.prototype.init = function () { + return ( + (this._ah = 1779033703), + (this._bh = 3144134277), + (this._ch = 1013904242), + (this._dh = 2773480762), + (this._eh = 1359893119), + (this._fh = 2600822924), + (this._gh = 528734635), + (this._hh = 1541459225), + (this._al = 4089235720), + (this._bl = 2227873595), + (this._cl = 4271175723), + (this._dl = 1595750129), + (this._el = 2917565137), + (this._fl = 725511199), + (this._gl = 4215389547), + (this._hl = 327033209), + this + ); + }; + function Tp(t, e, r) { + return r ^ (t & (e ^ r)); + } + function kp(t, e, r) { + return (t & e) | (r & (t | e)); + } + function Lp(t, e) { + return ((t >>> 28) | (e << 4)) ^ ((e >>> 2) | (t << 30)) ^ ((e >>> 7) | (t << 25)); + } + function Np(t, e) { + return ((t >>> 14) | (e << 18)) ^ ((t >>> 18) | (e << 14)) ^ ((e >>> 9) | (t << 23)); + } + function j4(t, e) { + return ((t >>> 1) | (e << 31)) ^ ((t >>> 8) | (e << 24)) ^ (t >>> 7); + } + function Z4(t, e) { + return ((t >>> 1) | (e << 31)) ^ ((t >>> 8) | (e << 24)) ^ ((t >>> 7) | (e << 25)); + } + function V4(t, e) { + return ((t >>> 19) | (e << 13)) ^ ((e >>> 29) | (t << 3)) ^ (t >>> 6); + } + function $4(t, e) { + return ((t >>> 19) | (e << 13)) ^ ((e >>> 29) | (t << 3)) ^ ((t >>> 6) | (e << 26)); + } + function Pt(t, e) { + return t >>> 0 < e >>> 0 ? 1 : 0; + } + ca.prototype._update = function (t) { + for ( + var e = this._w, + r = this._ah | 0, + o = this._bh | 0, + f = this._ch | 0, + p = this._dh | 0, + m2 = this._eh | 0, + y2 = this._fh | 0, + M = this._gh | 0, + x = this._hh | 0, + S = this._al | 0, + E2 = this._bl | 0, + B = this._cl | 0, + q2 = this._dl | 0, + L2 = this._el | 0, + ge = this._fl | 0, + _e = this._gl | 0, + N = this._hl | 0, + we = 0; + we < 32; + we += 2 + ) + (e[we] = t.readInt32BE(we * 4)), (e[we + 1] = t.readInt32BE(we * 4 + 4)); + for (; we < 160; we += 2) { + var ye = e[we - 30], + xe = e[we - 15 * 2 + 1], + Re = j4(ye, xe), + Ee = Z4(xe, ye); + (ye = e[we - 2 * 2]), (xe = e[we - 2 * 2 + 1]); + var Ae = V4(ye, xe), + P = $4(xe, ye), + Se = e[we - 7 * 2], + v = e[we - 7 * 2 + 1], + i = e[we - 16 * 2], + a = e[we - 16 * 2 + 1], + h2 = (Ee + v) | 0, + s = (Re + Se + Pt(h2, Ee)) | 0; + (h2 = (h2 + P) | 0), (s = (s + Ae + Pt(h2, P)) | 0), (h2 = (h2 + a) | 0), (s = (s + i + Pt(h2, a)) | 0), (e[we] = s), (e[we + 1] = h2); + } + for (var u = 0; u < 160; u += 2) { + (s = e[u]), (h2 = e[u + 1]); + var c = kp(r, o, f), + b2 = kp(S, E2, B), + l = Lp(r, S), + n = Lp(S, r), + d = Np(m2, L2), + w = Np(L2, m2), + g = Ip[u], + _2 = Ip[u + 1], + A2 = Tp(m2, y2, M), + R2 = Tp(L2, ge, _e), + I = (N + w) | 0, + Me = (x + d + Pt(I, N)) | 0; + (I = (I + R2) | 0), (Me = (Me + A2 + Pt(I, R2)) | 0), (I = (I + _2) | 0), (Me = (Me + g + Pt(I, _2)) | 0), (I = (I + h2) | 0), (Me = (Me + s + Pt(I, h2)) | 0); + var k = (n + b2) | 0, + D2 = (l + c + Pt(k, n)) | 0; + (x = M), (N = _e), (M = y2), (_e = ge), (y2 = m2), (ge = L2), (L2 = (q2 + I) | 0), (m2 = (p + Me + Pt(L2, q2)) | 0), (p = f), (q2 = B), (f = o), (B = E2), (o = r), (E2 = S), (S = (I + k) | 0), (r = (Me + D2 + Pt(S, I)) | 0); + } + (this._al = (this._al + S) | 0), + (this._bl = (this._bl + E2) | 0), + (this._cl = (this._cl + B) | 0), + (this._dl = (this._dl + q2) | 0), + (this._el = (this._el + L2) | 0), + (this._fl = (this._fl + ge) | 0), + (this._gl = (this._gl + _e) | 0), + (this._hl = (this._hl + N) | 0), + (this._ah = (this._ah + r + Pt(this._al, S)) | 0), + (this._bh = (this._bh + o + Pt(this._bl, E2)) | 0), + (this._ch = (this._ch + f + Pt(this._cl, B)) | 0), + (this._dh = (this._dh + p + Pt(this._dl, q2)) | 0), + (this._eh = (this._eh + m2 + Pt(this._el, L2)) | 0), + (this._fh = (this._fh + y2 + Pt(this._fl, ge)) | 0), + (this._gh = (this._gh + M + Pt(this._gl, _e)) | 0), + (this._hh = (this._hh + x + Pt(this._hl, N)) | 0); + }; + ca.prototype._hash = function () { + var t = W4.allocUnsafe(64); + function e(r, o, f) { + t.writeInt32BE(r, f), t.writeInt32BE(o, f + 4); + } + return e(this._ah, this._al, 0), e(this._bh, this._bl, 8), e(this._ch, this._cl, 16), e(this._dh, this._dl, 24), e(this._eh, this._el, 32), e(this._fh, this._fl, 40), e(this._gh, this._gl, 48), e(this._hh, this._hl, 56), t; + }; + Pp.exports = ca; + }); + Op = T2((AI, Cp) => { + var G4 = Ie(), + Y4 = yh(), + X4 = pn(), + J4 = Te().Buffer, + Q4 = new Array(160); + function To() { + this.init(), (this._w = Q4), X4.call(this, 128, 112); + } + G4(To, Y4); + To.prototype.init = function () { + return ( + (this._ah = 3418070365), + (this._bh = 1654270250), + (this._ch = 2438529370), + (this._dh = 355462360), + (this._eh = 1731405415), + (this._fh = 2394180231), + (this._gh = 3675008525), + (this._hh = 1203062813), + (this._al = 3238371032), + (this._bl = 914150663), + (this._cl = 812702999), + (this._dl = 4144912697), + (this._el = 4290775857), + (this._fl = 1750603025), + (this._gl = 1694076839), + (this._hl = 3204075428), + this + ); + }; + To.prototype._hash = function () { + var t = J4.allocUnsafe(48); + function e(r, o, f) { + t.writeInt32BE(r, f), t.writeInt32BE(o, f + 4); + } + return e(this._ah, this._al, 0), e(this._bh, this._bl, 8), e(this._ch, this._cl, 16), e(this._dh, this._dl, 24), e(this._eh, this._el, 32), e(this._fh, this._fl, 40), t; + }; + Cp.exports = To; + }); + ko = T2((ci, Fp) => { + var ci = (Fp.exports = function (e) { + e = e.toLowerCase(); + var r = ci[e]; + if (!r) throw new Error(e + ' is not supported (we accept pull requests)'); + return new r(); + }); + ci.sha = _p(); + ci.sha1 = Ep(); + ci.sha224 = qp(); + ci.sha256 = gh(); + ci.sha384 = Op(); + ci.sha512 = yh(); + }); + Tt = T2((RI, Up) => { + Up.exports = { + ArrayIsArray(t) { + return Array.isArray(t); + }, + ArrayPrototypeIncludes(t, e) { + return t.includes(e); + }, + ArrayPrototypeIndexOf(t, e) { + return t.indexOf(e); + }, + ArrayPrototypeJoin(t, e) { + return t.join(e); + }, + ArrayPrototypeMap(t, e) { + return t.map(e); + }, + ArrayPrototypePop(t, e) { + return t.pop(e); + }, + ArrayPrototypePush(t, e) { + return t.push(e); + }, + ArrayPrototypeSlice(t, e, r) { + return t.slice(e, r); + }, + Error, + FunctionPrototypeCall(t, e, ...r) { + return t.call(e, ...r); + }, + FunctionPrototypeSymbolHasInstance(t, e) { + return Function.prototype[Symbol.hasInstance].call(t, e); + }, + MathFloor: Math.floor, + Number, + NumberIsInteger: Number.isInteger, + NumberIsNaN: Number.isNaN, + NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, + NumberParseInt: Number.parseInt, + ObjectDefineProperties(t, e) { + return Object.defineProperties(t, e); + }, + ObjectDefineProperty(t, e, r) { + return Object.defineProperty(t, e, r); + }, + ObjectGetOwnPropertyDescriptor(t, e) { + return Object.getOwnPropertyDescriptor(t, e); + }, + ObjectKeys(t) { + return Object.keys(t); + }, + ObjectSetPrototypeOf(t, e) { + return Object.setPrototypeOf(t, e); + }, + Promise, + PromisePrototypeCatch(t, e) { + return t.catch(e); + }, + PromisePrototypeThen(t, e, r) { + return t.then(e, r); + }, + PromiseReject(t) { + return Promise.reject(t); + }, + ReflectApply: Reflect.apply, + RegExpPrototypeTest(t, e) { + return t.test(e); + }, + SafeSet: Set, + String, + StringPrototypeSlice(t, e, r) { + return t.slice(e, r); + }, + StringPrototypeToLowerCase(t) { + return t.toLowerCase(); + }, + StringPrototypeToUpperCase(t) { + return t.toUpperCase(); + }, + StringPrototypeTrim(t) { + return t.trim(); + }, + Symbol, + SymbolAsyncIterator: Symbol.asyncIterator, + SymbolHasInstance: Symbol.hasInstance, + SymbolIterator: Symbol.iterator, + TypedArrayPrototypeSet(t, e, r) { + return t.set(e, r); + }, + Uint8Array + }; + }); + Gr = T2((BI, Mh) => { + var e_ = Ut(), + t_ = Object.getPrototypeOf(async function () {}).constructor, + zp = globalThis.Blob || e_.Blob, + r_ = + typeof zp < 'u' + ? function (e) { + return e instanceof zp; + } + : function (e) { + return false; + }, + wh = class extends Error { + constructor(e) { + if (!Array.isArray(e)) throw new TypeError(`Expected input to be an Array, got ${typeof e}`); + let r = ''; + for (let o = 0; o < e.length; o++) + r += ` ${e[o].stack} +`; + super(r), (this.name = 'AggregateError'), (this.errors = e); + } + }; + Mh.exports = { + AggregateError: wh, + kEmptyObject: Object.freeze({}), + once(t) { + let e = false; + return function (...r) { + e || ((e = true), t.apply(this, r)); + }; + }, + createDeferredPromise: function () { + let t, e; + return { + promise: new Promise((o, f) => { + (t = o), (e = f); + }), + resolve: t, + reject: e + }; + }, + promisify(t) { + return new Promise((e, r) => { + t((o, ...f) => (o ? r(o) : e(...f))); + }); + }, + debuglog() { + return function () {}; + }, + format(t, ...e) { + return t.replace(/%([sdifj])/g, function (...[r, o]) { + let f = e.shift(); + return o === 'f' ? f.toFixed(6) : o === 'j' ? JSON.stringify(f) : o === 's' && typeof f == 'object' ? `${f.constructor !== Object ? f.constructor.name : ''} {}`.trim() : f.toString(); + }); + }, + inspect(t) { + switch (typeof t) { + case 'string': + if (t.includes("'")) + if (t.includes('"')) { + if (!t.includes('`') && !t.includes('${')) return `\`${t}\``; + } else return `"${t}"`; + return `'${t}'`; + case 'number': + return isNaN(t) ? 'NaN' : Object.is(t, -0) ? String(t) : t; + case 'bigint': + return `${String(t)}n`; + case 'boolean': + case 'undefined': + return String(t); + case 'object': + return '{}'; + } + }, + types: { + isAsyncFunction(t) { + return t instanceof t_; + }, + isArrayBufferView(t) { + return ArrayBuffer.isView(t); + } + }, + isBlob: r_ + }; + Mh.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom'); + }); + No = T2((qI, Lo) => { + var {AbortController: Hp, AbortSignal: i_} = typeof self < 'u' ? self : typeof window < 'u' ? window : undefined; + Lo.exports = Hp; + Lo.exports.AbortSignal = i_; + Lo.exports.default = Hp; + }); + Jt = T2((II, jp) => { + var {format: n_, inspect: Do, AggregateError: f_} = Gr(), + a_ = globalThis.AggregateError || f_, + o_ = Symbol('kIsNodeError'), + s_ = ['string', 'function', 'number', 'object', 'Function', 'Object', 'boolean', 'bigint', 'symbol'], + h_ = /^([A-Z][a-z0-9]*)+$/, + u_ = '__node_internal_', + Po = {}; + function vn(t, e) { + if (!t) throw new Po.ERR_INTERNAL_ASSERTION(e); + } + function Wp(t) { + let e = '', + r = t.length, + o = t[0] === '-' ? 1 : 0; + for (; r >= o + 4; r -= 3) e = `_${t.slice(r - 3, r)}${e}`; + return `${t.slice(0, r)}${e}`; + } + function l_(t, e, r) { + if (typeof e == 'function') return vn(e.length <= r.length, `Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`), e(...r); + let o = (e.match(/%[dfijoOs]/g) || []).length; + return vn(o === r.length, `Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${o}).`), r.length === 0 ? e : n_(e, ...r); + } + function zt(t, e, r) { + r || (r = Error); + + class o extends r { + constructor(...p) { + super(l_(t, e, p)); + } + toString() { + return `${this.name} [${t}]: ${this.message}`; + } + } + Object.defineProperties(o.prototype, { + name: {value: r.name, writable: true, enumerable: false, configurable: true}, + toString: { + value() { + return `${this.name} [${t}]: ${this.message}`; + }, + writable: true, + enumerable: false, + configurable: true + } + }), + (o.prototype.code = t), + (o.prototype[o_] = true), + (Po[t] = o); + } + function Kp(t) { + let e = u_ + t.name; + return Object.defineProperty(t, 'name', {value: e}), t; + } + function d_(t, e) { + if (t && e && t !== e) { + if (Array.isArray(e.errors)) return e.errors.push(t), e; + let r = new a_([e, t], e.message); + return (r.code = e.code), r; + } + return t || e; + } + var _h = class extends Error { + constructor(e = 'The operation was aborted', r = undefined) { + if (r !== undefined && typeof r != 'object') throw new Po.ERR_INVALID_ARG_TYPE('options', 'Object', r); + super(e, r), (this.code = 'ABORT_ERR'), (this.name = 'AbortError'); + } + }; + zt('ERR_ASSERTION', '%s', Error); + zt( + 'ERR_INVALID_ARG_TYPE', + (t, e, r) => { + vn(typeof t == 'string', "'name' must be a string"), Array.isArray(e) || (e = [e]); + let o = 'The '; + t.endsWith(' argument') ? (o += `${t} `) : (o += `"${t}" ${t.includes('.') ? 'property' : 'argument'} `), (o += 'must be '); + let f = [], + p = [], + m2 = []; + for (let M of e) + vn(typeof M == 'string', 'All expected entries have to be of type string'), s_.includes(M) ? f.push(M.toLowerCase()) : h_.test(M) ? p.push(M) : (vn(M !== 'object', 'The value "object" should be written as "Object"'), m2.push(M)); + if (p.length > 0) { + let M = f.indexOf('object'); + M !== -1 && (f.splice(f, M, 1), p.push('Object')); + } + if (f.length > 0) { + switch (f.length) { + case 1: + o += `of type ${f[0]}`; + break; + case 2: + o += `one of type ${f[0]} or ${f[1]}`; + break; + default: { + let M = f.pop(); + o += `one of type ${f.join(', ')}, or ${M}`; + } + } + (p.length > 0 || m2.length > 0) && (o += ' or '); + } + if (p.length > 0) { + switch (p.length) { + case 1: + o += `an instance of ${p[0]}`; + break; + case 2: + o += `an instance of ${p[0]} or ${p[1]}`; + break; + default: { + let M = p.pop(); + o += `an instance of ${p.join(', ')}, or ${M}`; + } + } + m2.length > 0 && (o += ' or '); + } + switch (m2.length) { + case 0: + break; + case 1: + m2[0].toLowerCase() !== m2[0] && (o += 'an '), (o += `${m2[0]}`); + break; + case 2: + o += `one of ${m2[0]} or ${m2[1]}`; + break; + default: { + let M = m2.pop(); + o += `one of ${m2.join(', ')}, or ${M}`; + } + } + if (r == null) o += `. Received ${r}`; + else if (typeof r == 'function' && r.name) o += `. Received function ${r.name}`; + else if (typeof r == 'object') { + var y2; + (y2 = r.constructor) !== null && y2 !== undefined && y2.name ? (o += `. Received an instance of ${r.constructor.name}`) : (o += `. Received ${Do(r, {depth: -1})}`); + } else { + let M = Do(r, {colors: false}); + M.length > 25 && (M = `${M.slice(0, 25)}...`), (o += `. Received type ${typeof r} (${M})`); + } + return o; + }, + TypeError + ); + zt( + 'ERR_INVALID_ARG_VALUE', + (t, e, r = 'is invalid') => { + let o = Do(e); + return o.length > 128 && (o = o.slice(0, 128) + '...'), `The ${t.includes('.') ? 'property' : 'argument'} '${t}' ${r}. Received ${o}`; + }, + TypeError + ); + zt( + 'ERR_INVALID_RETURN_VALUE', + (t, e, r) => { + var o; + let f = r != null && (o = r.constructor) !== null && o !== undefined && o.name ? `instance of ${r.constructor.name}` : `type ${typeof r}`; + return `Expected ${t} to be returned from the "${e}" function but got ${f}.`; + }, + TypeError + ); + zt( + 'ERR_MISSING_ARGS', + (...t) => { + vn(t.length > 0, 'At least one arg needs to be specified'); + let e, + r = t.length; + switch (((t = (Array.isArray(t) ? t : [t]).map(o => `"${o}"`).join(' or ')), r)) { + case 1: + e += `The ${t[0]} argument`; + break; + case 2: + e += `The ${t[0]} and ${t[1]} arguments`; + break; + default: + { + let o = t.pop(); + e += `The ${t.join(', ')}, and ${o} arguments`; + } + break; + } + return `${e} must be specified`; + }, + TypeError + ); + zt( + 'ERR_OUT_OF_RANGE', + (t, e, r) => { + vn(e, 'Missing "range" argument'); + let o; + return ( + Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? (o = Wp(String(r))) : typeof r == 'bigint' ? ((o = String(r)), (r > 2n ** 32n || r < -(2n ** 32n)) && (o = Wp(o)), (o += 'n')) : (o = Do(r)), + `The value of "${t}" is out of range. It must be ${e}. Received ${o}` + ); + }, + RangeError + ); + zt('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error); + zt('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error); + zt('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error); + zt('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error); + zt('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error); + zt('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); + zt('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error); + zt('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error); + zt('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error); + zt('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error); + zt('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError); + jp.exports = {AbortError: _h, aggregateTwoErrors: Kp(d_), hideStackFrames: Kp, codes: Po}; + }); + pa = T2((TI, Qp) => { + var { + ArrayIsArray: $p, + ArrayPrototypeIncludes: Gp, + ArrayPrototypeJoin: Yp, + ArrayPrototypeMap: c_, + NumberIsInteger: Sh, + NumberIsNaN: p_, + NumberMAX_SAFE_INTEGER: v_, + NumberMIN_SAFE_INTEGER: b_, + NumberParseInt: m_, + ObjectPrototypeHasOwnProperty: g_, + RegExpPrototypeExec: y_, + String: w_, + StringPrototypeToUpperCase: M_, + StringPrototypeTrim: __ + } = Tt(), + { + hideStackFrames: Ir, + codes: {ERR_SOCKET_BAD_PORT: x_, ERR_INVALID_ARG_TYPE: tr, ERR_INVALID_ARG_VALUE: Co, ERR_OUT_OF_RANGE: bn, ERR_UNKNOWN_SIGNAL: Zp} + } = Jt(), + {normalizeEncoding: S_} = Gr(), + {isAsyncFunction: E_, isArrayBufferView: A_} = Gr().types, + Vp = {}; + function R_(t) { + return t === (t | 0); + } + function B_(t) { + return t === t >>> 0; + } + var q_ = /^[0-7]+$/, + I_ = 'must be a 32-bit unsigned integer or an octal string'; + function T_(t, e, r) { + if ((typeof t > 'u' && (t = r), typeof t == 'string')) { + if (y_(q_, t) === null) throw new Co(e, t, I_); + t = m_(t, 8); + } + return Xp(t, e), t; + } + var k_ = Ir((t, e, r = b_, o = v_) => { + if (typeof t != 'number') throw new tr(e, 'number', t); + if (!Sh(t)) throw new bn(e, 'an integer', t); + if (t < r || t > o) throw new bn(e, `>= ${r} && <= ${o}`, t); + }), + L_ = Ir((t, e, r = -2147483648, o = 2147483647) => { + if (typeof t != 'number') throw new tr(e, 'number', t); + if (!Sh(t)) throw new bn(e, 'an integer', t); + if (t < r || t > o) throw new bn(e, `>= ${r} && <= ${o}`, t); + }), + Xp = Ir((t, e, r = false) => { + if (typeof t != 'number') throw new tr(e, 'number', t); + if (!Sh(t)) throw new bn(e, 'an integer', t); + let o = r ? 1 : 0, + f = 4294967295; + if (t < o || t > f) throw new bn(e, `>= ${o} && <= ${f}`, t); + }); + function Jp(t, e) { + if (typeof t != 'string') throw new tr(e, 'string', t); + } + function N_(t, e, r = undefined, o) { + if (typeof t != 'number') throw new tr(e, 'number', t); + if ((r != null && t < r) || (o != null && t > o) || ((r != null || o != null) && p_(t))) throw new bn(e, `${r != null ? `>= ${r}` : ''}${r != null && o != null ? ' && ' : ''}${o != null ? `<= ${o}` : ''}`, t); + } + var D_ = Ir((t, e, r) => { + if (!Gp(r, t)) { + let o = Yp( + c_(r, p => (typeof p == 'string' ? `'${p}'` : w_(p))), + ', ' + ), + f = 'must be one of: ' + o; + throw new Co(e, t, f); + } + }); + function P_(t, e) { + if (typeof t != 'boolean') throw new tr(e, 'boolean', t); + } + function xh(t, e, r) { + return t == null || !g_(t, e) ? r : t[e]; + } + var C_ = Ir((t, e, r = null) => { + let o = xh(r, 'allowArray', false), + f = xh(r, 'allowFunction', false); + if ((!xh(r, 'nullable', false) && t === null) || (!o && $p(t)) || (typeof t != 'object' && (!f || typeof t != 'function'))) throw new tr(e, 'Object', t); + }), + O_ = Ir((t, e, r = 0) => { + if (!$p(t)) throw new tr(e, 'Array', t); + if (t.length < r) { + let o = `must be longer than ${r}`; + throw new Co(e, t, o); + } + }); + function F_(t, e = 'signal') { + if ((Jp(t, e), Vp[t] === undefined)) throw Vp[M_(t)] !== undefined ? new Zp(t + ' (signals must use all capital letters)') : new Zp(t); + } + var U_ = Ir((t, e = 'buffer') => { + if (!A_(t)) throw new tr(e, ['Buffer', 'TypedArray', 'DataView'], t); + }); + function z_(t, e) { + let r = S_(e), + o = t.length; + if (r === 'hex' && o % 2 !== 0) throw new Co('encoding', e, `is invalid for data of length ${o}`); + } + function H_(t, e = 'Port', r = true) { + if ((typeof t != 'number' && typeof t != 'string') || (typeof t == 'string' && __(t).length === 0) || +t !== +t >>> 0 || t > 65535 || (t === 0 && !r)) throw new x_(e, t, r); + return t | 0; + } + var W_ = Ir((t, e) => { + if (t !== undefined && (t === null || typeof t != 'object' || !('aborted' in t))) throw new tr(e, 'AbortSignal', t); + }), + K_ = Ir((t, e) => { + if (typeof t != 'function') throw new tr(e, 'Function', t); + }), + j_ = Ir((t, e) => { + if (typeof t != 'function' || E_(t)) throw new tr(e, 'Function', t); + }), + Z_ = Ir((t, e) => { + if (t !== undefined) throw new tr(e, 'undefined', t); + }); + function V_(t, e, r) { + if (!Gp(r, t)) throw new tr(e, `('${Yp(r, '|')}')`, t); + } + Qp.exports = { + isInt32: R_, + isUint32: B_, + parseFileMode: T_, + validateArray: O_, + validateBoolean: P_, + validateBuffer: U_, + validateEncoding: z_, + validateFunction: K_, + validateInt32: L_, + validateInteger: k_, + validateNumber: N_, + validateObject: C_, + validateOneOf: D_, + validatePlainFunction: j_, + validatePort: H_, + validateSignalName: F_, + validateString: Jp, + validateUint32: Xp, + validateUndefined: Z_, + validateUnion: V_, + validateAbortSignal: W_ + }; + }); + Rh = T2((kI, i1) => { + var dt = (i1.exports = {}), + Yr, + Xr; + function Eh() { + throw new Error('setTimeout has not been defined'); + } + function Ah() { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + typeof setTimeout == 'function' ? (Yr = setTimeout) : (Yr = Eh); + } catch { + Yr = Eh; + } + try { + typeof clearTimeout == 'function' ? (Xr = clearTimeout) : (Xr = Ah); + } catch { + Xr = Ah; + } + })(); + function e1(t) { + if (Yr === setTimeout) return setTimeout(t, 0); + if ((Yr === Eh || !Yr) && setTimeout) return (Yr = setTimeout), setTimeout(t, 0); + try { + return Yr(t, 0); + } catch { + try { + return Yr.call(null, t, 0); + } catch { + return Yr.call(this, t, 0); + } + } + } + function $_(t) { + if (Xr === clearTimeout) return clearTimeout(t); + if ((Xr === Ah || !Xr) && clearTimeout) return (Xr = clearTimeout), clearTimeout(t); + try { + return Xr(t); + } catch { + try { + return Xr.call(null, t); + } catch { + return Xr.call(this, t); + } + } + } + var pi = [], + nf = false, + mn, + Oo = -1; + function G_() { + !nf || !mn || ((nf = false), mn.length ? (pi = mn.concat(pi)) : (Oo = -1), pi.length && t1()); + } + function t1() { + if (!nf) { + var t = e1(G_); + nf = true; + for (var e = pi.length; e; ) { + for (mn = pi, pi = []; ++Oo < e; ) mn && mn[Oo].run(); + (Oo = -1), (e = pi.length); + } + (mn = null), (nf = false), $_(t); + } + } + dt.nextTick = function (t) { + var e = new Array(arguments.length - 1); + if (arguments.length > 1) for (var r = 1; r < arguments.length; r++) e[r - 1] = arguments[r]; + pi.push(new r1(t, e)), pi.length === 1 && !nf && e1(t1); + }; + function r1(t, e) { + (this.fun = t), (this.array = e); + } + r1.prototype.run = function () { + this.fun.apply(null, this.array); + }; + dt.title = 'browser'; + dt.browser = true; + dt.env = {}; + dt.argv = []; + dt.version = ''; + dt.versions = {}; + function vi() {} + dt.on = vi; + dt.addListener = vi; + dt.once = vi; + dt.off = vi; + dt.removeListener = vi; + dt.removeAllListeners = vi; + dt.emit = vi; + dt.prependListener = vi; + dt.prependOnceListener = vi; + dt.listeners = function (t) { + return []; + }; + dt.binding = function (t) { + throw new Error('process.binding is not supported'); + }; + dt.cwd = function () { + return '/'; + }; + dt.chdir = function (t) { + throw new Error('process.chdir is not supported'); + }; + dt.umask = function () { + return 0; + }; + }); + pr = {}; + Ja(pr, {default: () => Y_}); + Oi = R0(() => { + ot(pr, rn(Rh())); + Y_ = rn(Rh()); + }); + Fi = T2((NI, v1) => { + var {Symbol: Fo, SymbolAsyncIterator: n1, SymbolIterator: f1} = Tt(), + a1 = Fo('kDestroyed'), + o1 = Fo('kIsErrored'), + Bh = Fo('kIsReadable'), + s1 = Fo('kIsDisturbed'); + function Uo(t, e = false) { + var r; + return !!( + t && + typeof t.pipe == 'function' && + typeof t.on == 'function' && + (!e || (typeof t.pause == 'function' && typeof t.resume == 'function')) && + (!t._writableState || ((r = t._readableState) === null || r === undefined ? undefined : r.readable) !== false) && + (!t._writableState || t._readableState) + ); + } + function zo(t) { + var e; + return !!(t && typeof t.write == 'function' && typeof t.on == 'function' && (!t._readableState || ((e = t._writableState) === null || e === undefined ? undefined : e.writable) !== false)); + } + function X_(t) { + return !!(t && typeof t.pipe == 'function' && t._readableState && typeof t.on == 'function' && typeof t.write == 'function'); + } + function gn(t) { + return t && (t._readableState || t._writableState || (typeof t.write == 'function' && typeof t.on == 'function') || (typeof t.pipe == 'function' && typeof t.on == 'function')); + } + function J_(t, e) { + return t == null ? false : e === true ? typeof t[n1] == 'function' : e === false ? typeof t[f1] == 'function' : typeof t[n1] == 'function' || typeof t[f1] == 'function'; + } + function Ho(t) { + if (!gn(t)) return null; + let {_writableState: e, _readableState: r} = t, + o = e || r; + return !!(t.destroyed || t[a1] || (o != null && o.destroyed)); + } + function h1(t) { + if (!zo(t)) return null; + if (t.writableEnded === true) return true; + let e = t._writableState; + return e != null && e.errored ? false : typeof e?.ended != 'boolean' ? null : e.ended; + } + function Q_(t, e) { + if (!zo(t)) return null; + if (t.writableFinished === true) return true; + let r = t._writableState; + return r != null && r.errored ? false : typeof r?.finished != 'boolean' ? null : !!(r.finished || (e === false && r.ended === true && r.length === 0)); + } + function e8(t) { + if (!Uo(t)) return null; + if (t.readableEnded === true) return true; + let e = t._readableState; + return !e || e.errored ? false : typeof e?.ended != 'boolean' ? null : e.ended; + } + function u1(t, e) { + if (!Uo(t)) return null; + let r = t._readableState; + return r != null && r.errored ? false : typeof r?.endEmitted != 'boolean' ? null : !!(r.endEmitted || (e === false && r.ended === true && r.length === 0)); + } + function l1(t) { + return t && t[Bh] != null ? t[Bh] : typeof t?.readable != 'boolean' ? null : Ho(t) ? false : Uo(t) && t.readable && !u1(t); + } + function d1(t) { + return typeof t?.writable != 'boolean' ? null : Ho(t) ? false : zo(t) && t.writable && !h1(t); + } + function t8(t, e) { + return gn(t) ? (Ho(t) ? true : !((e?.readable !== false && l1(t)) || (e?.writable !== false && d1(t)))) : null; + } + function r8(t) { + var e, r; + return gn(t) ? (t.writableErrored ? t.writableErrored : (e = (r = t._writableState) === null || r === undefined ? undefined : r.errored) !== null && e !== undefined ? e : null) : null; + } + function i8(t) { + var e, r; + return gn(t) ? (t.readableErrored ? t.readableErrored : (e = (r = t._readableState) === null || r === undefined ? undefined : r.errored) !== null && e !== undefined ? e : null) : null; + } + function n8(t) { + if (!gn(t)) return null; + if (typeof t.closed == 'boolean') return t.closed; + let {_writableState: e, _readableState: r} = t; + return typeof e?.closed == 'boolean' || typeof r?.closed == 'boolean' ? e?.closed || r?.closed : typeof t._closed == 'boolean' && c1(t) ? t._closed : null; + } + function c1(t) { + return typeof t._closed == 'boolean' && typeof t._defaultKeepAlive == 'boolean' && typeof t._removedConnection == 'boolean' && typeof t._removedContLen == 'boolean'; + } + function p1(t) { + return typeof t._sent100 == 'boolean' && c1(t); + } + function f8(t) { + var e; + return typeof t._consuming == 'boolean' && typeof t._dumped == 'boolean' && ((e = t.req) === null || e === undefined ? undefined : e.upgradeOrConnect) === undefined; + } + function a8(t) { + if (!gn(t)) return null; + let {_writableState: e, _readableState: r} = t, + o = e || r; + return (!o && p1(t)) || !!(o && o.autoDestroy && o.emitClose && o.closed === false); + } + function o8(t) { + var e; + return !!(t && ((e = t[s1]) !== null && e !== undefined ? e : t.readableDidRead || t.readableAborted)); + } + function s8(t) { + var e, r, o, f, p, m2, y2, M, x, S; + return !!( + t && + ((e = + (r = + (o = + (f = (p = (m2 = t[o1]) !== null && m2 !== undefined ? m2 : t.readableErrored) !== null && p !== undefined ? p : t.writableErrored) !== null && f !== undefined + ? f + : (y2 = t._readableState) === null || y2 === undefined + ? undefined + : y2.errorEmitted) !== null && o !== undefined + ? o + : (M = t._writableState) === null || M === undefined + ? undefined + : M.errorEmitted) !== null && r !== undefined + ? r + : (x = t._readableState) === null || x === undefined + ? undefined + : x.errored) !== null && e !== undefined + ? e + : (S = t._writableState) === null || S === undefined + ? undefined + : S.errored) + ); + } + v1.exports = { + kDestroyed: a1, + isDisturbed: o8, + kIsDisturbed: s1, + isErrored: s8, + kIsErrored: o1, + isReadable: l1, + kIsReadable: Bh, + isClosed: n8, + isDestroyed: Ho, + isDuplexNodeStream: X_, + isFinished: t8, + isIterable: J_, + isReadableNodeStream: Uo, + isReadableEnded: e8, + isReadableFinished: u1, + isReadableErrored: i8, + isNodeStream: gn, + isWritable: d1, + isWritableNodeStream: zo, + isWritableEnded: h1, + isWritableFinished: Q_, + isWritableErrored: r8, + isServerRequest: f8, + isServerResponse: p1, + willEmitClose: a8 + }; + }); + Ui = T2((DI, Ih) => { + var ff = (Oi(), ur(pr)), + {AbortError: h8, codes: u8} = Jt(), + {ERR_INVALID_ARG_TYPE: l8, ERR_STREAM_PREMATURE_CLOSE: b1} = u8, + {kEmptyObject: m1, once: g1} = Gr(), + {validateAbortSignal: d8, validateFunction: c8, validateObject: p8} = pa(), + {Promise: v8} = Tt(), + {isClosed: b8, isReadable: y1, isReadableNodeStream: qh, isReadableFinished: w1, isReadableErrored: m8, isWritable: M1, isWritableNodeStream: _1, isWritableFinished: x1, isWritableErrored: g8, isNodeStream: y8, willEmitClose: w8} = Fi(); + function M8(t) { + return t.setHeader && typeof t.abort == 'function'; + } + var _8 = () => {}; + function S1(t, e, r) { + var o, f; + arguments.length === 2 ? ((r = e), (e = m1)) : e == null ? (e = m1) : p8(e, 'options'), c8(r, 'callback'), d8(e.signal, 'options.signal'), (r = g1(r)); + let p = (o = e.readable) !== null && o !== undefined ? o : qh(t), + m2 = (f = e.writable) !== null && f !== undefined ? f : _1(t); + if (!y8(t)) throw new l8('stream', 'Stream', t); + let {_writableState: y2, _readableState: M} = t, + x = () => { + t.writable || B(); + }, + S = w8(t) && qh(t) === p && _1(t) === m2, + E2 = x1(t, false), + B = () => { + (E2 = true), t.destroyed && (S = false), !(S && (!t.readable || p)) && (!p || q2) && r.call(t); + }, + q2 = w1(t, false), + L2 = () => { + (q2 = true), t.destroyed && (S = false), !(S && (!t.writable || m2)) && (!m2 || E2) && r.call(t); + }, + ge = xe => { + r.call(t, xe); + }, + _e = b8(t), + N = () => { + _e = true; + let xe = g8(t) || m8(t); + if (xe && typeof xe != 'boolean') return r.call(t, xe); + if (p && !q2 && qh(t, true) && !w1(t, false)) return r.call(t, new b1()); + if (m2 && !E2 && !x1(t, false)) return r.call(t, new b1()); + r.call(t); + }, + we = () => { + t.req.on('finish', B); + }; + M8(t) ? (t.on('complete', B), S || t.on('abort', N), t.req ? we() : t.on('request', we)) : m2 && !y2 && (t.on('end', x), t.on('close', x)), + !S && typeof t.aborted == 'boolean' && t.on('aborted', N), + t.on('end', L2), + t.on('finish', B), + e.error !== false && t.on('error', ge), + t.on('close', N), + _e + ? ff.nextTick(N) + : (y2 != null && y2.errorEmitted) || (M != null && M.errorEmitted) + ? S || ff.nextTick(N) + : ((!p && (!S || y1(t)) && (E2 || M1(t) === false)) || (!m2 && (!S || M1(t)) && (q2 || y1(t) === false)) || (M && t.req && t.aborted)) && ff.nextTick(N); + let ye = () => { + (r = _8), + t.removeListener('aborted', N), + t.removeListener('complete', B), + t.removeListener('abort', N), + t.removeListener('request', we), + t.req && t.req.removeListener('finish', B), + t.removeListener('end', x), + t.removeListener('close', x), + t.removeListener('finish', B), + t.removeListener('end', L2), + t.removeListener('error', ge), + t.removeListener('close', N); + }; + if (e.signal && !_e) { + let xe = () => { + let Re = r; + ye(), Re.call(t, new h8(undefined, {cause: e.signal.reason})); + }; + if (e.signal.aborted) ff.nextTick(xe); + else { + let Re = r; + (r = g1((...Ee) => { + e.signal.removeEventListener('abort', xe), Re.apply(t, Ee); + })), + e.signal.addEventListener('abort', xe); + } + } + return ye; + } + function x8(t, e) { + return new v8((r, o) => { + S1(t, e, f => { + f ? o(f) : r(); + }); + }); + } + Ih.exports = S1; + Ih.exports.finished = x8; + }); + k1 = T2((PI, Lh) => { + var B1 = globalThis.AbortController || No().AbortController, + { + codes: {ERR_INVALID_ARG_TYPE: va, ERR_MISSING_ARGS: S8, ERR_OUT_OF_RANGE: E8}, + AbortError: Jr + } = Jt(), + {validateAbortSignal: af, validateInteger: A8, validateObject: of} = pa(), + R8 = Tt().Symbol('kWeak'), + {finished: B8} = Ui(), + {ArrayPrototypePush: q8, MathFloor: I8, Number: T8, NumberIsNaN: k8, Promise: E1, PromiseReject: A1, PromisePrototypeThen: L8, Symbol: q1} = Tt(), + Wo = q1('kEmpty'), + R1 = q1('kEof'); + function Ko(t, e) { + if (typeof t != 'function') throw new va('fn', ['Function', 'AsyncFunction'], t); + e != null && of(e, 'options'), e?.signal != null && af(e.signal, 'options.signal'); + let r = 1; + return ( + e?.concurrency != null && (r = I8(e.concurrency)), + A8(r, 'concurrency', 1), + async function* () { + var f, p; + let m2 = new B1(), + y2 = this, + M = [], + x = m2.signal, + S = {signal: x}, + E2 = () => m2.abort(); + e != null && (f = e.signal) !== null && f !== undefined && f.aborted && E2(), e == null || (p = e.signal) === null || p === undefined || p.addEventListener('abort', E2); + let B, + q2, + L2 = false; + function ge() { + L2 = true; + } + async function _e() { + try { + for await (let ye of y2) { + var N; + if (L2) return; + if (x.aborted) throw new Jr(); + try { + ye = t(ye, S); + } catch (xe) { + ye = A1(xe); + } + ye !== Wo && + (typeof ((N = ye) === null || N === undefined ? undefined : N.catch) == 'function' && ye.catch(ge), + M.push(ye), + B && (B(), (B = null)), + !L2 && + M.length && + M.length >= r && + (await new E1(xe => { + q2 = xe; + }))); + } + M.push(R1); + } catch (ye) { + let xe = A1(ye); + L8(xe, undefined, ge), M.push(xe); + } finally { + var we; + (L2 = true), B && (B(), (B = null)), e == null || (we = e.signal) === null || we === undefined || we.removeEventListener('abort', E2); + } + } + _e(); + try { + for (;;) { + for (; M.length > 0; ) { + let N = await M[0]; + if (N === R1) return; + if (x.aborted) throw new Jr(); + N !== Wo && (yield N), M.shift(), q2 && (q2(), (q2 = null)); + } + await new E1(N => { + B = N; + }); + } + } finally { + m2.abort(), (L2 = true), q2 && (q2(), (q2 = null)); + } + }.call(this) + ); + } + function N8(t = undefined) { + return ( + t != null && of(t, 'options'), + t?.signal != null && af(t.signal, 'options.signal'), + async function* () { + let r = 0; + for await (let f of this) { + var o; + if (t != null && (o = t.signal) !== null && o !== undefined && o.aborted) throw new Jr({cause: t.signal.reason}); + yield [r++, f]; + } + }.call(this) + ); + } + async function I1(t, e = undefined) { + for await (let r of kh.call(this, t, e)) return true; + return false; + } + async function D8(t, e = undefined) { + if (typeof t != 'function') throw new va('fn', ['Function', 'AsyncFunction'], t); + return !(await I1.call(this, async (...r) => !(await t(...r)), e)); + } + async function P8(t, e) { + for await (let r of kh.call(this, t, e)) return r; + } + async function C8(t, e) { + if (typeof t != 'function') throw new va('fn', ['Function', 'AsyncFunction'], t); + async function r(o, f) { + return await t(o, f), Wo; + } + for await (let o of Ko.call(this, r, e)); + } + function kh(t, e) { + if (typeof t != 'function') throw new va('fn', ['Function', 'AsyncFunction'], t); + async function r(o, f) { + return (await t(o, f)) ? o : Wo; + } + return Ko.call(this, r, e); + } + var Th = class extends S8 { + constructor() { + super('reduce'), (this.message = 'Reduce of an empty stream requires an initial value'); + } + }; + async function O8(t, e, r) { + var o; + if (typeof t != 'function') throw new va('reducer', ['Function', 'AsyncFunction'], t); + r != null && of(r, 'options'), r?.signal != null && af(r.signal, 'options.signal'); + let f = arguments.length > 1; + if (r != null && (o = r.signal) !== null && o !== undefined && o.aborted) { + let x = new Jr(undefined, {cause: r.signal.reason}); + throw (this.once('error', () => {}), await B8(this.destroy(x)), x); + } + let p = new B1(), + m2 = p.signal; + if (r != null && r.signal) { + let x = {once: true, [R8]: this}; + r.signal.addEventListener('abort', () => p.abort(), x); + } + let y2 = false; + try { + for await (let x of this) { + var M; + if (((y2 = true), r != null && (M = r.signal) !== null && M !== undefined && M.aborted)) throw new Jr(); + f ? (e = await t(e, x, {signal: m2})) : ((e = x), (f = true)); + } + if (!y2 && !f) throw new Th(); + } finally { + p.abort(); + } + return e; + } + async function F8(t) { + t != null && of(t, 'options'), t?.signal != null && af(t.signal, 'options.signal'); + let e = []; + for await (let o of this) { + var r; + if (t != null && (r = t.signal) !== null && r !== undefined && r.aborted) throw new Jr(undefined, {cause: t.signal.reason}); + q8(e, o); + } + return e; + } + function U8(t, e) { + let r = Ko.call(this, t, e); + return async function* () { + for await (let f of r) yield* f; + }.call(this); + } + function T1(t) { + if (((t = T8(t)), k8(t))) return 0; + if (t < 0) throw new E8('number', '>= 0', t); + return t; + } + function z8(t, e = undefined) { + return ( + e != null && of(e, 'options'), + e?.signal != null && af(e.signal, 'options.signal'), + (t = T1(t)), + async function* () { + var o; + if (e != null && (o = e.signal) !== null && o !== undefined && o.aborted) throw new Jr(); + for await (let p of this) { + var f; + if (e != null && (f = e.signal) !== null && f !== undefined && f.aborted) throw new Jr(); + t-- <= 0 && (yield p); + } + }.call(this) + ); + } + function H8(t, e = undefined) { + return ( + e != null && of(e, 'options'), + e?.signal != null && af(e.signal, 'options.signal'), + (t = T1(t)), + async function* () { + var o; + if (e != null && (o = e.signal) !== null && o !== undefined && o.aborted) throw new Jr(); + for await (let p of this) { + var f; + if (e != null && (f = e.signal) !== null && f !== undefined && f.aborted) throw new Jr(); + if (t-- > 0) yield p; + else return; + } + }.call(this) + ); + } + Lh.exports.streamReturningOperators = {asIndexedPairs: N8, drop: z8, filter: kh, flatMap: U8, map: Ko, take: H8}; + Lh.exports.promiseReturningOperators = {every: D8, forEach: C8, reduce: O8, toArray: F8, some: I1, find: P8}; + }); + yn = T2((CI, U1) => { + var zi = (Oi(), ur(pr)), + { + aggregateTwoErrors: W8, + codes: {ERR_MULTIPLE_CALLBACK: K8}, + AbortError: j8 + } = Jt(), + {Symbol: D1} = Tt(), + {kDestroyed: Z8, isDestroyed: V8, isFinished: $8, isServerRequest: G8} = Fi(), + P1 = D1('kDestroy'), + Nh = D1('kConstruct'); + function C1(t, e, r) { + t && (t.stack, e && !e.errored && (e.errored = t), r && !r.errored && (r.errored = t)); + } + function Y8(t, e) { + let r = this._readableState, + o = this._writableState, + f = o || r; + return (o && o.destroyed) || (r && r.destroyed) + ? (typeof e == 'function' && e(), this) + : (C1(t, o, r), + o && (o.destroyed = true), + r && (r.destroyed = true), + f.constructed + ? L1(this, t, e) + : this.once(P1, function (p) { + L1(this, W8(p, t), e); + }), + this); + } + function L1(t, e, r) { + let o = false; + function f(p) { + if (o) return; + o = true; + let {_readableState: m2, _writableState: y2} = t; + C1(p, y2, m2), y2 && (y2.closed = true), m2 && (m2.closed = true), typeof r == 'function' && r(p), p ? zi.nextTick(X8, t, p) : zi.nextTick(O1, t); + } + try { + t._destroy(e || null, f); + } catch (p) { + f(p); + } + } + function X8(t, e) { + Dh(t, e), O1(t); + } + function O1(t) { + let {_readableState: e, _writableState: r} = t; + r && (r.closeEmitted = true), e && (e.closeEmitted = true), ((r && r.emitClose) || (e && e.emitClose)) && t.emit('close'); + } + function Dh(t, e) { + let {_readableState: r, _writableState: o} = t; + (o && o.errorEmitted) || (r && r.errorEmitted) || (o && (o.errorEmitted = true), r && (r.errorEmitted = true), t.emit('error', e)); + } + function J8() { + let t = this._readableState, + e = this._writableState; + t && + ((t.constructed = true), (t.closed = false), (t.closeEmitted = false), (t.destroyed = false), (t.errored = null), (t.errorEmitted = false), (t.reading = false), (t.ended = t.readable === false), (t.endEmitted = t.readable === false)), + e && + ((e.constructed = true), + (e.destroyed = false), + (e.closed = false), + (e.closeEmitted = false), + (e.errored = null), + (e.errorEmitted = false), + (e.finalCalled = false), + (e.prefinished = false), + (e.ended = e.writable === false), + (e.ending = e.writable === false), + (e.finished = e.writable === false)); + } + function Ph(t, e, r) { + let {_readableState: o, _writableState: f} = t; + if ((f && f.destroyed) || (o && o.destroyed)) return this; + (o && o.autoDestroy) || (f && f.autoDestroy) ? t.destroy(e) : e && (e.stack, f && !f.errored && (f.errored = e), o && !o.errored && (o.errored = e), r ? zi.nextTick(Dh, t, e) : Dh(t, e)); + } + function Q8(t, e) { + if (typeof t._construct != 'function') return; + let {_readableState: r, _writableState: o} = t; + r && (r.constructed = false), o && (o.constructed = false), t.once(Nh, e), !(t.listenerCount(Nh) > 1) && zi.nextTick(e5, t); + } + function e5(t) { + let e = false; + function r(o) { + if (e) { + Ph(t, o ?? new K8()); + return; + } + e = true; + let {_readableState: f, _writableState: p} = t, + m2 = p || f; + f && (f.constructed = true), p && (p.constructed = true), m2.destroyed ? t.emit(P1, o) : o ? Ph(t, o, true) : zi.nextTick(t5, t); + } + try { + t._construct(r); + } catch (o) { + r(o); + } + } + function t5(t) { + t.emit(Nh); + } + function N1(t) { + return t && t.setHeader && typeof t.abort == 'function'; + } + function F1(t) { + t.emit('close'); + } + function r5(t, e) { + t.emit('error', e), zi.nextTick(F1, t); + } + function i5(t, e) { + !t || + V8(t) || + (!e && !$8(t) && (e = new j8()), + G8(t) ? ((t.socket = null), t.destroy(e)) : N1(t) ? t.abort() : N1(t.req) ? t.req.abort() : typeof t.destroy == 'function' ? t.destroy(e) : typeof t.close == 'function' ? t.close() : e ? zi.nextTick(r5, t, e) : zi.nextTick(F1, t), + t.destroyed || (t[Z8] = true)); + } + U1.exports = {construct: Q8, destroyer: i5, destroy: Y8, undestroy: J8, errorOrDestroy: Ph}; + }); + Vo = T2((OI, H1) => { + var {ArrayIsArray: n5, ObjectSetPrototypeOf: z1} = Tt(), + {EventEmitter: jo} = ki(); + function Zo(t) { + jo.call(this, t); + } + z1(Zo.prototype, jo.prototype); + z1(Zo, jo); + Zo.prototype.pipe = function (t, e) { + let r = this; + function o(S) { + t.writable && t.write(S) === false && r.pause && r.pause(); + } + r.on('data', o); + function f() { + r.readable && r.resume && r.resume(); + } + t.on('drain', f), !t._isStdio && (!e || e.end !== false) && (r.on('end', m2), r.on('close', y2)); + let p = false; + function m2() { + p || ((p = true), t.end()); + } + function y2() { + p || ((p = true), typeof t.destroy == 'function' && t.destroy()); + } + function M(S) { + x(), jo.listenerCount(this, 'error') === 0 && this.emit('error', S); + } + Ch(r, 'error', M), Ch(t, 'error', M); + function x() { + r.removeListener('data', o), + t.removeListener('drain', f), + r.removeListener('end', m2), + r.removeListener('close', y2), + r.removeListener('error', M), + t.removeListener('error', M), + r.removeListener('end', x), + r.removeListener('close', x), + t.removeListener('close', x); + } + return r.on('end', x), r.on('close', x), t.on('close', x), t.emit('pipe', r), t; + }; + function Ch(t, e, r) { + if (typeof t.prependListener == 'function') return t.prependListener(e, r); + !t._events || !t._events[e] ? t.on(e, r) : n5(t._events[e]) ? t._events[e].unshift(r) : (t._events[e] = [r, t._events[e]]); + } + H1.exports = {Stream: Zo, prependListener: Ch}; + }); + Go = T2((FI, $o) => { + var {AbortError: f5, codes: a5} = Jt(), + o5 = Ui(), + {ERR_INVALID_ARG_TYPE: W1} = a5, + s5 = (t, e) => { + if (typeof t != 'object' || !('aborted' in t)) throw new W1(e, 'AbortSignal', t); + }; + function h5(t) { + return !!(t && typeof t.pipe == 'function'); + } + $o.exports.addAbortSignal = function (e, r) { + if ((s5(e, 'signal'), !h5(r))) throw new W1('stream', 'stream.Stream', r); + return $o.exports.addAbortSignalNoValidate(e, r); + }; + $o.exports.addAbortSignalNoValidate = function (t, e) { + if (typeof t != 'object' || !('aborted' in t)) return e; + let r = () => { + e.destroy(new f5(undefined, {cause: t.reason})); + }; + return t.aborted ? r() : (t.addEventListener('abort', r), o5(e, () => t.removeEventListener('abort', r))), e; + }; + }); + Z1 = T2((zI, j1) => { + var {StringPrototypeSlice: K1, SymbolIterator: u5, TypedArrayPrototypeSet: Yo, Uint8Array: l5} = Tt(), + {Buffer: Oh} = Ut(), + {inspect: d5} = Gr(); + j1.exports = class { + constructor() { + (this.head = null), (this.tail = null), (this.length = 0); + } + push(e) { + let r = {data: e, next: null}; + this.length > 0 ? (this.tail.next = r) : (this.head = r), (this.tail = r), ++this.length; + } + unshift(e) { + let r = {data: e, next: this.head}; + this.length === 0 && (this.tail = r), (this.head = r), ++this.length; + } + shift() { + if (this.length === 0) return; + let e = this.head.data; + return this.length === 1 ? (this.head = this.tail = null) : (this.head = this.head.next), --this.length, e; + } + clear() { + (this.head = this.tail = null), (this.length = 0); + } + join(e) { + if (this.length === 0) return ''; + let r = this.head, + o = '' + r.data; + for (; (r = r.next) !== null; ) o += e + r.data; + return o; + } + concat(e) { + if (this.length === 0) return Oh.alloc(0); + let r = Oh.allocUnsafe(e >>> 0), + o = this.head, + f = 0; + for (; o; ) Yo(r, o.data, f), (f += o.data.length), (o = o.next); + return r; + } + consume(e, r) { + let o = this.head.data; + if (e < o.length) { + let f = o.slice(0, e); + return (this.head.data = o.slice(e)), f; + } + return e === o.length ? this.shift() : r ? this._getString(e) : this._getBuffer(e); + } + first() { + return this.head.data; + } + *[u5]() { + for (let e = this.head; e; e = e.next) yield e.data; + } + _getString(e) { + let r = '', + o = this.head, + f = 0; + do { + let p = o.data; + if (e > p.length) (r += p), (e -= p.length); + else { + e === p.length ? ((r += p), ++f, o.next ? (this.head = o.next) : (this.head = this.tail = null)) : ((r += K1(p, 0, e)), (this.head = o), (o.data = K1(p, e))); + break; + } + ++f; + } while ((o = o.next) !== null); + return (this.length -= f), r; + } + _getBuffer(e) { + let r = Oh.allocUnsafe(e), + o = e, + f = this.head, + p = 0; + do { + let m2 = f.data; + if (e > m2.length) Yo(r, m2, o - e), (e -= m2.length); + else { + e === m2.length ? (Yo(r, m2, o - e), ++p, f.next ? (this.head = f.next) : (this.head = this.tail = null)) : (Yo(r, new l5(m2.buffer, m2.byteOffset, e), o - e), (this.head = f), (f.data = m2.slice(e))); + break; + } + ++p; + } while ((f = f.next) !== null); + return (this.length -= p), r; + } + [Symbol.for('nodejs.util.inspect.custom')](e, r) { + return d5(this, {...r, depth: 0, customInspect: false}); + } + }; + }); + Xo = T2((HI, $1) => { + var {MathFloor: c5, NumberIsInteger: p5} = Tt(), + {ERR_INVALID_ARG_VALUE: v5} = Jt().codes; + function b5(t, e, r) { + return t.highWaterMark != null ? t.highWaterMark : e ? t[r] : null; + } + function V1(t) { + return t ? 16 : 16 * 1024; + } + function m5(t, e, r, o) { + let f = b5(e, o, r); + if (f != null) { + if (!p5(f) || f < 0) { + let p = o ? `options.${r}` : 'options.highWaterMark'; + throw new v5(p, f); + } + return c5(f); + } + return V1(t.objectMode); + } + $1.exports = {getHighWaterMark: m5, getDefaultHighWaterMark: V1}; + }); + Fh = T2((WI, J1) => { + var G1 = (Oi(), ur(pr)), + {PromisePrototypeThen: g5, SymbolAsyncIterator: Y1, SymbolIterator: X1} = Tt(), + {Buffer: y5} = Ut(), + {ERR_INVALID_ARG_TYPE: w5, ERR_STREAM_NULL_VALUES: M5} = Jt().codes; + function _5(t, e, r) { + let o; + if (typeof e == 'string' || e instanceof y5) + return new t({ + objectMode: true, + ...r, + read() { + this.push(e), this.push(null); + } + }); + let f; + if (e && e[Y1]) (f = true), (o = e[Y1]()); + else if (e && e[X1]) (f = false), (o = e[X1]()); + else throw new w5('iterable', ['Iterable'], e); + let p = new t({objectMode: true, highWaterMark: 1, ...r}), + m2 = false; + (p._read = function () { + m2 || ((m2 = true), M()); + }), + (p._destroy = function (x, S) { + g5( + y2(x), + () => G1.nextTick(S, x), + E2 => G1.nextTick(S, E2 || x) + ); + }); + async function y2(x) { + let S = x != null, + E2 = typeof o.throw == 'function'; + if (S && E2) { + let {value: B, done: q2} = await o.throw(x); + if ((await B, q2)) return; + } + if (typeof o.return == 'function') { + let {value: B} = await o.return(); + await B; + } + } + async function M() { + for (;;) { + try { + let {value: x, done: S} = f ? await o.next() : o.next(); + if (S) p.push(null); + else { + let E2 = x && typeof x.then == 'function' ? await x : x; + if (E2 === null) throw ((m2 = false), new M5()); + if (p.push(E2)) continue; + m2 = false; + } + } catch (x) { + p.destroy(x); + } + break; + } + } + return p; + } + J1.exports = _5; + }); + ba = T2((KI, lv) => { + var Tr = (Oi(), ur(pr)), + {ArrayPrototypeIndexOf: x5, NumberIsInteger: S5, NumberIsNaN: E5, NumberParseInt: A5, ObjectDefineProperties: tv, ObjectKeys: R5, ObjectSetPrototypeOf: rv, Promise: B5, SafeSet: q5, SymbolAsyncIterator: I5, Symbol: T5} = Tt(); + lv.exports = Le; + Le.ReadableState = jh; + var {EventEmitter: k5} = ki(), + {Stream: Hi, prependListener: L5} = Vo(), + {Buffer: Uh} = Ut(), + {addAbortSignal: N5} = Go(), + D5 = Ui(), + Pe = Gr().debuglog('stream', t => { + Pe = t; + }), + P5 = Z1(), + hf = yn(), + {getHighWaterMark: C5, getDefaultHighWaterMark: O5} = Xo(), + { + aggregateTwoErrors: Q1, + codes: {ERR_INVALID_ARG_TYPE: F5, ERR_METHOD_NOT_IMPLEMENTED: U5, ERR_OUT_OF_RANGE: z5, ERR_STREAM_PUSH_AFTER_EOF: H5, ERR_STREAM_UNSHIFT_AFTER_END_EVENT: W5} + } = Jt(), + {validateObject: K5} = pa(), + wn = T5('kPaused'), + {StringDecoder: iv} = co(), + j5 = Fh(); + rv(Le.prototype, Hi.prototype); + rv(Le, Hi); + var zh = () => {}, + {errorOrDestroy: sf} = hf; + function jh(t, e, r) { + typeof r != 'boolean' && (r = e instanceof Qr()), + (this.objectMode = !!(t && t.objectMode)), + r && (this.objectMode = this.objectMode || !!(t && t.readableObjectMode)), + (this.highWaterMark = t ? C5(this, t, 'readableHighWaterMark', r) : O5(false)), + (this.buffer = new P5()), + (this.length = 0), + (this.pipes = []), + (this.flowing = null), + (this.ended = false), + (this.endEmitted = false), + (this.reading = false), + (this.constructed = true), + (this.sync = true), + (this.needReadable = false), + (this.emittedReadable = false), + (this.readableListening = false), + (this.resumeScheduled = false), + (this[wn] = null), + (this.errorEmitted = false), + (this.emitClose = !t || t.emitClose !== false), + (this.autoDestroy = !t || t.autoDestroy !== false), + (this.destroyed = false), + (this.errored = null), + (this.closed = false), + (this.closeEmitted = false), + (this.defaultEncoding = (t && t.defaultEncoding) || 'utf8'), + (this.awaitDrainWriters = null), + (this.multiAwaitDrain = false), + (this.readingMore = false), + (this.dataEmitted = false), + (this.decoder = null), + (this.encoding = null), + t && t.encoding && ((this.decoder = new iv(t.encoding)), (this.encoding = t.encoding)); + } + function Le(t) { + if (!(this instanceof Le)) return new Le(t); + let e = this instanceof Qr(); + (this._readableState = new jh(t, this, e)), + t && (typeof t.read == 'function' && (this._read = t.read), typeof t.destroy == 'function' && (this._destroy = t.destroy), typeof t.construct == 'function' && (this._construct = t.construct), t.signal && !e && N5(t.signal, this)), + Hi.call(this, t), + hf.construct(this, () => { + this._readableState.needReadable && Jo(this, this._readableState); + }); + } + Le.prototype.destroy = hf.destroy; + Le.prototype._undestroy = hf.undestroy; + Le.prototype._destroy = function (t, e) { + e(t); + }; + Le.prototype[k5.captureRejectionSymbol] = function (t) { + this.destroy(t); + }; + Le.prototype.push = function (t, e) { + return nv(this, t, e, false); + }; + Le.prototype.unshift = function (t, e) { + return nv(this, t, e, true); + }; + function nv(t, e, r, o) { + Pe('readableAddChunk', e); + let f = t._readableState, + p; + if ( + (f.objectMode || + (typeof e == 'string' + ? ((r = r || f.defaultEncoding), f.encoding !== r && (o && f.encoding ? (e = Uh.from(e, r).toString(f.encoding)) : ((e = Uh.from(e, r)), (r = '')))) + : e instanceof Uh + ? (r = '') + : Hi._isUint8Array(e) + ? ((e = Hi._uint8ArrayToBuffer(e)), (r = '')) + : e != null && (p = new F5('chunk', ['string', 'Buffer', 'Uint8Array'], e))), + p) + ) + sf(t, p); + else if (e === null) (f.reading = false), $5(t, f); + else if (f.objectMode || (e && e.length > 0)) + if (o) + if (f.endEmitted) sf(t, new W5()); + else { + if (f.destroyed || f.errored) return false; + Hh(t, f, e, true); + } + else if (f.ended) sf(t, new H5()); + else { + if (f.destroyed || f.errored) return false; + (f.reading = false), f.decoder && !r ? ((e = f.decoder.write(e)), f.objectMode || e.length !== 0 ? Hh(t, f, e, false) : Jo(t, f)) : Hh(t, f, e, false); + } + else o || ((f.reading = false), Jo(t, f)); + return !f.ended && (f.length < f.highWaterMark || f.length === 0); + } + function Hh(t, e, r, o) { + e.flowing && e.length === 0 && !e.sync && t.listenerCount('data') > 0 + ? (e.multiAwaitDrain ? e.awaitDrainWriters.clear() : (e.awaitDrainWriters = null), (e.dataEmitted = true), t.emit('data', r)) + : ((e.length += e.objectMode ? 1 : r.length), o ? e.buffer.unshift(r) : e.buffer.push(r), e.needReadable && Qo(t)), + Jo(t, e); + } + Le.prototype.isPaused = function () { + let t = this._readableState; + return t[wn] === true || t.flowing === false; + }; + Le.prototype.setEncoding = function (t) { + let e = new iv(t); + (this._readableState.decoder = e), (this._readableState.encoding = this._readableState.decoder.encoding); + let r = this._readableState.buffer, + o = ''; + for (let f of r) o += e.write(f); + return r.clear(), o !== '' && r.push(o), (this._readableState.length = o.length), this; + }; + var Z5 = 1073741824; + function V5(t) { + if (t > Z5) throw new z5('size', '<= 1GiB', t); + return t--, (t |= t >>> 1), (t |= t >>> 2), (t |= t >>> 4), (t |= t >>> 8), (t |= t >>> 16), t++, t; + } + function ev(t, e) { + return t <= 0 || (e.length === 0 && e.ended) ? 0 : e.objectMode ? 1 : E5(t) ? (e.flowing && e.length ? e.buffer.first().length : e.length) : t <= e.length ? t : e.ended ? e.length : 0; + } + Le.prototype.read = function (t) { + Pe('read', t), t === undefined ? (t = NaN) : S5(t) || (t = A5(t, 10)); + let e = this._readableState, + r = t; + if ((t > e.highWaterMark && (e.highWaterMark = V5(t)), t !== 0 && (e.emittedReadable = false), t === 0 && e.needReadable && ((e.highWaterMark !== 0 ? e.length >= e.highWaterMark : e.length > 0) || e.ended))) + return Pe('read: emitReadable', e.length, e.ended), e.length === 0 && e.ended ? Wh(this) : Qo(this), null; + if (((t = ev(t, e)), t === 0 && e.ended)) return e.length === 0 && Wh(this), null; + let o = e.needReadable; + if ((Pe('need readable', o), (e.length === 0 || e.length - t < e.highWaterMark) && ((o = true), Pe('length less than watermark', o)), e.ended || e.reading || e.destroyed || e.errored || !e.constructed)) + (o = false), Pe('reading, ended or constructing', o); + else if (o) { + Pe('do read'), (e.reading = true), (e.sync = true), e.length === 0 && (e.needReadable = true); + try { + this._read(e.highWaterMark); + } catch (p) { + sf(this, p); + } + (e.sync = false), e.reading || (t = ev(r, e)); + } + let f; + return ( + t > 0 ? (f = hv(t, e)) : (f = null), + f === null ? ((e.needReadable = e.length <= e.highWaterMark), (t = 0)) : ((e.length -= t), e.multiAwaitDrain ? e.awaitDrainWriters.clear() : (e.awaitDrainWriters = null)), + e.length === 0 && (e.ended || (e.needReadable = true), r !== t && e.ended && Wh(this)), + f !== null && !e.errorEmitted && !e.closeEmitted && ((e.dataEmitted = true), this.emit('data', f)), + f + ); + }; + function $5(t, e) { + if ((Pe('onEofChunk'), !e.ended)) { + if (e.decoder) { + let r = e.decoder.end(); + r && r.length && (e.buffer.push(r), (e.length += e.objectMode ? 1 : r.length)); + } + (e.ended = true), e.sync ? Qo(t) : ((e.needReadable = false), (e.emittedReadable = true), fv(t)); + } + } + function Qo(t) { + let e = t._readableState; + Pe('emitReadable', e.needReadable, e.emittedReadable), (e.needReadable = false), e.emittedReadable || (Pe('emitReadable', e.flowing), (e.emittedReadable = true), Tr.nextTick(fv, t)); + } + function fv(t) { + let e = t._readableState; + Pe('emitReadable_', e.destroyed, e.length, e.ended), + !e.destroyed && !e.errored && (e.length || e.ended) && (t.emit('readable'), (e.emittedReadable = false)), + (e.needReadable = !e.flowing && !e.ended && e.length <= e.highWaterMark), + ov(t); + } + function Jo(t, e) { + !e.readingMore && e.constructed && ((e.readingMore = true), Tr.nextTick(G5, t, e)); + } + function G5(t, e) { + for (; !e.reading && !e.ended && (e.length < e.highWaterMark || (e.flowing && e.length === 0)); ) { + let r = e.length; + if ((Pe('maybeReadMore read 0'), t.read(0), r === e.length)) break; + } + e.readingMore = false; + } + Le.prototype._read = function (t) { + throw new U5('_read()'); + }; + Le.prototype.pipe = function (t, e) { + let r = this, + o = this._readableState; + o.pipes.length === 1 && (o.multiAwaitDrain || ((o.multiAwaitDrain = true), (o.awaitDrainWriters = new q5(o.awaitDrainWriters ? [o.awaitDrainWriters] : [])))), o.pipes.push(t), Pe('pipe count=%d opts=%j', o.pipes.length, e); + let p = (!e || e.end !== false) && t !== Tr.stdout && t !== Tr.stderr ? y2 : _e; + o.endEmitted ? Tr.nextTick(p) : r.once('end', p), t.on('unpipe', m2); + function m2(N, we) { + Pe('onunpipe'), N === r && we && we.hasUnpiped === false && ((we.hasUnpiped = true), S()); + } + function y2() { + Pe('onend'), t.end(); + } + let M, + x = false; + function S() { + Pe('cleanup'), + t.removeListener('close', L2), + t.removeListener('finish', ge), + M && t.removeListener('drain', M), + t.removeListener('error', q2), + t.removeListener('unpipe', m2), + r.removeListener('end', y2), + r.removeListener('end', _e), + r.removeListener('data', B), + (x = true), + M && o.awaitDrainWriters && (!t._writableState || t._writableState.needDrain) && M(); + } + function E2() { + x || + (o.pipes.length === 1 && o.pipes[0] === t + ? (Pe('false write response, pause', 0), (o.awaitDrainWriters = t), (o.multiAwaitDrain = false)) + : o.pipes.length > 1 && o.pipes.includes(t) && (Pe('false write response, pause', o.awaitDrainWriters.size), o.awaitDrainWriters.add(t)), + r.pause()), + M || ((M = Y5(r, t)), t.on('drain', M)); + } + r.on('data', B); + function B(N) { + Pe('ondata'); + let we = t.write(N); + Pe('dest.write', we), we === false && E2(); + } + function q2(N) { + if ((Pe('onerror', N), _e(), t.removeListener('error', q2), t.listenerCount('error') === 0)) { + let we = t._writableState || t._readableState; + we && !we.errorEmitted ? sf(t, N) : t.emit('error', N); + } + } + L5(t, 'error', q2); + function L2() { + t.removeListener('finish', ge), _e(); + } + t.once('close', L2); + function ge() { + Pe('onfinish'), t.removeListener('close', L2), _e(); + } + t.once('finish', ge); + function _e() { + Pe('unpipe'), r.unpipe(t); + } + return t.emit('pipe', r), t.writableNeedDrain === true ? o.flowing && E2() : o.flowing || (Pe('pipe resume'), r.resume()), t; + }; + function Y5(t, e) { + return function () { + let o = t._readableState; + o.awaitDrainWriters === e ? (Pe('pipeOnDrain', 1), (o.awaitDrainWriters = null)) : o.multiAwaitDrain && (Pe('pipeOnDrain', o.awaitDrainWriters.size), o.awaitDrainWriters.delete(e)), + (!o.awaitDrainWriters || o.awaitDrainWriters.size === 0) && t.listenerCount('data') && t.resume(); + }; + } + Le.prototype.unpipe = function (t) { + let e = this._readableState, + r = {hasUnpiped: false}; + if (e.pipes.length === 0) return this; + if (!t) { + let f = e.pipes; + (e.pipes = []), this.pause(); + for (let p = 0; p < f.length; p++) f[p].emit('unpipe', this, {hasUnpiped: false}); + return this; + } + let o = x5(e.pipes, t); + return o === -1 ? this : (e.pipes.splice(o, 1), e.pipes.length === 0 && this.pause(), t.emit('unpipe', this, r), this); + }; + Le.prototype.on = function (t, e) { + let r = Hi.prototype.on.call(this, t, e), + o = this._readableState; + return ( + t === 'data' + ? ((o.readableListening = this.listenerCount('readable') > 0), o.flowing !== false && this.resume()) + : t === 'readable' && + !o.endEmitted && + !o.readableListening && + ((o.readableListening = o.needReadable = true), (o.flowing = false), (o.emittedReadable = false), Pe('on readable', o.length, o.reading), o.length ? Qo(this) : o.reading || Tr.nextTick(X5, this)), + r + ); + }; + Le.prototype.addListener = Le.prototype.on; + Le.prototype.removeListener = function (t, e) { + let r = Hi.prototype.removeListener.call(this, t, e); + return t === 'readable' && Tr.nextTick(av, this), r; + }; + Le.prototype.off = Le.prototype.removeListener; + Le.prototype.removeAllListeners = function (t) { + let e = Hi.prototype.removeAllListeners.apply(this, arguments); + return (t === 'readable' || t === undefined) && Tr.nextTick(av, this), e; + }; + function av(t) { + let e = t._readableState; + (e.readableListening = t.listenerCount('readable') > 0), e.resumeScheduled && e[wn] === false ? (e.flowing = true) : t.listenerCount('data') > 0 ? t.resume() : e.readableListening || (e.flowing = null); + } + function X5(t) { + Pe('readable nexttick read 0'), t.read(0); + } + Le.prototype.resume = function () { + let t = this._readableState; + return t.flowing || (Pe('resume'), (t.flowing = !t.readableListening), J5(this, t)), (t[wn] = false), this; + }; + function J5(t, e) { + e.resumeScheduled || ((e.resumeScheduled = true), Tr.nextTick(Q5, t, e)); + } + function Q5(t, e) { + Pe('resume', e.reading), e.reading || t.read(0), (e.resumeScheduled = false), t.emit('resume'), ov(t), e.flowing && !e.reading && t.read(0); + } + Le.prototype.pause = function () { + return Pe('call pause flowing=%j', this._readableState.flowing), this._readableState.flowing !== false && (Pe('pause'), (this._readableState.flowing = false), this.emit('pause')), (this._readableState[wn] = true), this; + }; + function ov(t) { + let e = t._readableState; + for (Pe('flow', e.flowing); e.flowing && t.read() !== null; ); + } + Le.prototype.wrap = function (t) { + let e = false; + t.on('data', o => { + !this.push(o) && t.pause && ((e = true), t.pause()); + }), + t.on('end', () => { + this.push(null); + }), + t.on('error', o => { + sf(this, o); + }), + t.on('close', () => { + this.destroy(); + }), + t.on('destroy', () => { + this.destroy(); + }), + (this._read = () => { + e && t.resume && ((e = false), t.resume()); + }); + let r = R5(t); + for (let o = 1; o < r.length; o++) { + let f = r[o]; + this[f] === undefined && typeof t[f] == 'function' && (this[f] = t[f].bind(t)); + } + return this; + }; + Le.prototype[I5] = function () { + return sv(this); + }; + Le.prototype.iterator = function (t) { + return t !== undefined && K5(t, 'options'), sv(this, t); + }; + function sv(t, e) { + typeof t.read != 'function' && (t = Le.wrap(t, {objectMode: true})); + let r = ex(t, e); + return (r.stream = t), r; + } + async function* ex(t, e) { + let r = zh; + function o(m2) { + this === t ? (r(), (r = zh)) : (r = m2); + } + t.on('readable', o); + let f, + p = D5(t, {writable: false}, m2 => { + (f = m2 ? Q1(f, m2) : null), r(), (r = zh); + }); + try { + for (;;) { + let m2 = t.destroyed ? null : t.read(); + if (m2 !== null) yield m2; + else { + if (f) throw f; + if (f === null) return; + await new B5(o); + } + } + } catch (m2) { + throw ((f = Q1(f, m2)), f); + } finally { + (f || e?.destroyOnReturn !== false) && (f === undefined || t._readableState.autoDestroy) ? hf.destroyer(t, null) : (t.off('readable', o), p()); + } + } + tv(Le.prototype, { + readable: { + __proto__: null, + get() { + let t = this._readableState; + return !!t && t.readable !== false && !t.destroyed && !t.errorEmitted && !t.endEmitted; + }, + set(t) { + this._readableState && (this._readableState.readable = !!t); + } + }, + readableDidRead: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.dataEmitted; + } + }, + readableAborted: { + __proto__: null, + enumerable: false, + get: function () { + return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted); + } + }, + readableHighWaterMark: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } + }, + readableBuffer: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState && this._readableState.buffer; + } + }, + readableFlowing: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.flowing; + }, + set: function (t) { + this._readableState && (this._readableState.flowing = t); + } + }, + readableLength: { + __proto__: null, + enumerable: false, + get() { + return this._readableState.length; + } + }, + readableObjectMode: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.objectMode : false; + } + }, + readableEncoding: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.encoding : null; + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.errored : null; + } + }, + closed: { + __proto__: null, + get() { + return this._readableState ? this._readableState.closed : false; + } + }, + destroyed: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.destroyed : false; + }, + set(t) { + !this._readableState || (this._readableState.destroyed = t); + } + }, + readableEnded: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.endEmitted : false; + } + } + }); + tv(jh.prototype, { + pipesCount: { + __proto__: null, + get() { + return this.pipes.length; + } + }, + paused: { + __proto__: null, + get() { + return this[wn] !== false; + }, + set(t) { + this[wn] = !!t; + } + } + }); + Le._fromList = hv; + function hv(t, e) { + if (e.length === 0) return null; + let r; + return ( + e.objectMode + ? (r = e.buffer.shift()) + : !t || t >= e.length + ? (e.decoder ? (r = e.buffer.join('')) : e.buffer.length === 1 ? (r = e.buffer.first()) : (r = e.buffer.concat(e.length)), e.buffer.clear()) + : (r = e.buffer.consume(t, e.decoder)), + r + ); + } + function Wh(t) { + let e = t._readableState; + Pe('endReadable', e.endEmitted), e.endEmitted || ((e.ended = true), Tr.nextTick(tx, e, t)); + } + function tx(t, e) { + if ((Pe('endReadableNT', t.endEmitted, t.length), !t.errored && !t.closeEmitted && !t.endEmitted && t.length === 0)) { + if (((t.endEmitted = true), e.emit('end'), e.writable && e.allowHalfOpen === false)) Tr.nextTick(rx, e); + else if (t.autoDestroy) { + let r = e._writableState; + (!r || (r.autoDestroy && (r.finished || r.writable === false))) && e.destroy(); + } + } + } + function rx(t) { + t.writable && !t.writableEnded && !t.destroyed && t.end(); + } + Le.from = function (t, e) { + return j5(Le, t, e); + }; + var Kh; + function uv() { + return Kh === undefined && (Kh = {}), Kh; + } + Le.fromWeb = function (t, e) { + return uv().newStreamReadableFromReadableStream(t, e); + }; + Le.toWeb = function (t, e) { + return uv().newReadableStreamFromStreamReadable(t, e); + }; + Le.wrap = function (t, e) { + var r, o; + return new Le({ + objectMode: (r = (o = t.readableObjectMode) !== null && o !== undefined ? o : t.objectMode) !== null && r !== undefined ? r : true, + ...e, + destroy(f, p) { + hf.destroyer(t, f), p(f); + } + }).wrap(t); + }; + }); + Jh = T2((jI, xv) => { + var Mn = (Oi(), ur(pr)), + {ArrayPrototypeSlice: pv, Error: ix, FunctionPrototypeSymbolHasInstance: vv, ObjectDefineProperty: bv, ObjectDefineProperties: nx, ObjectSetPrototypeOf: mv, StringPrototypeToLowerCase: fx, Symbol: ax, SymbolHasInstance: ox} = Tt(); + xv.exports = st; + st.WritableState = ya; + var {EventEmitter: sx} = ki(), + ma = Vo().Stream, + {Buffer: es} = Ut(), + is = yn(), + {addAbortSignal: hx} = Go(), + {getHighWaterMark: ux, getDefaultHighWaterMark: lx} = Xo(), + { + ERR_INVALID_ARG_TYPE: dx, + ERR_METHOD_NOT_IMPLEMENTED: cx, + ERR_MULTIPLE_CALLBACK: gv, + ERR_STREAM_CANNOT_PIPE: px, + ERR_STREAM_DESTROYED: ga, + ERR_STREAM_ALREADY_FINISHED: vx, + ERR_STREAM_NULL_VALUES: bx, + ERR_STREAM_WRITE_AFTER_END: mx, + ERR_UNKNOWN_ENCODING: yv + } = Jt().codes, + {errorOrDestroy: uf} = is; + mv(st.prototype, ma.prototype); + mv(st, ma); + function $h() {} + var lf = ax('kOnFinished'); + function ya(t, e, r) { + typeof r != 'boolean' && (r = e instanceof Qr()), + (this.objectMode = !!(t && t.objectMode)), + r && (this.objectMode = this.objectMode || !!(t && t.writableObjectMode)), + (this.highWaterMark = t ? ux(this, t, 'writableHighWaterMark', r) : lx(false)), + (this.finalCalled = false), + (this.needDrain = false), + (this.ending = false), + (this.ended = false), + (this.finished = false), + (this.destroyed = false); + let o = !!(t && t.decodeStrings === false); + (this.decodeStrings = !o), + (this.defaultEncoding = (t && t.defaultEncoding) || 'utf8'), + (this.length = 0), + (this.writing = false), + (this.corked = 0), + (this.sync = true), + (this.bufferProcessing = false), + (this.onwrite = yx.bind(undefined, e)), + (this.writecb = null), + (this.writelen = 0), + (this.afterWriteTickInfo = null), + rs(this), + (this.pendingcb = 0), + (this.constructed = true), + (this.prefinished = false), + (this.errorEmitted = false), + (this.emitClose = !t || t.emitClose !== false), + (this.autoDestroy = !t || t.autoDestroy !== false), + (this.errored = null), + (this.closed = false), + (this.closeEmitted = false), + (this[lf] = []); + } + function rs(t) { + (t.buffered = []), (t.bufferedIndex = 0), (t.allBuffers = true), (t.allNoop = true); + } + ya.prototype.getBuffer = function () { + return pv(this.buffered, this.bufferedIndex); + }; + bv(ya.prototype, 'bufferedRequestCount', { + __proto__: null, + get() { + return this.buffered.length - this.bufferedIndex; + } + }); + function st(t) { + let e = this instanceof Qr(); + if (!e && !vv(st, this)) return new st(t); + (this._writableState = new ya(t, this, e)), + t && + (typeof t.write == 'function' && (this._write = t.write), + typeof t.writev == 'function' && (this._writev = t.writev), + typeof t.destroy == 'function' && (this._destroy = t.destroy), + typeof t.final == 'function' && (this._final = t.final), + typeof t.construct == 'function' && (this._construct = t.construct), + t.signal && hx(t.signal, this)), + ma.call(this, t), + is.construct(this, () => { + let r = this._writableState; + r.writing || Yh(this, r), Xh(this, r); + }); + } + bv(st, ox, { + __proto__: null, + value: function (t) { + return vv(this, t) ? true : this !== st ? false : t && t._writableState instanceof ya; + } + }); + st.prototype.pipe = function () { + uf(this, new px()); + }; + function wv(t, e, r, o) { + let f = t._writableState; + if (typeof r == 'function') (o = r), (r = f.defaultEncoding); + else { + if (!r) r = f.defaultEncoding; + else if (r !== 'buffer' && !es.isEncoding(r)) throw new yv(r); + typeof o != 'function' && (o = $h); + } + if (e === null) throw new bx(); + if (!f.objectMode) + if (typeof e == 'string') f.decodeStrings !== false && ((e = es.from(e, r)), (r = 'buffer')); + else if (e instanceof es) r = 'buffer'; + else if (ma._isUint8Array(e)) (e = ma._uint8ArrayToBuffer(e)), (r = 'buffer'); + else throw new dx('chunk', ['string', 'Buffer', 'Uint8Array'], e); + let p; + return f.ending ? (p = new mx()) : f.destroyed && (p = new ga('write')), p ? (Mn.nextTick(o, p), uf(t, p, true), p) : (f.pendingcb++, gx(t, f, e, r, o)); + } + st.prototype.write = function (t, e, r) { + return wv(this, t, e, r) === true; + }; + st.prototype.cork = function () { + this._writableState.corked++; + }; + st.prototype.uncork = function () { + let t = this._writableState; + t.corked && (t.corked--, t.writing || Yh(this, t)); + }; + st.prototype.setDefaultEncoding = function (e) { + if ((typeof e == 'string' && (e = fx(e)), !es.isEncoding(e))) throw new yv(e); + return (this._writableState.defaultEncoding = e), this; + }; + function gx(t, e, r, o, f) { + let p = e.objectMode ? 1 : r.length; + e.length += p; + let m2 = e.length < e.highWaterMark; + return ( + m2 || (e.needDrain = true), + e.writing || e.corked || e.errored || !e.constructed + ? (e.buffered.push({chunk: r, encoding: o, callback: f}), e.allBuffers && o !== 'buffer' && (e.allBuffers = false), e.allNoop && f !== $h && (e.allNoop = false)) + : ((e.writelen = p), (e.writecb = f), (e.writing = true), (e.sync = true), t._write(r, o, e.onwrite), (e.sync = false)), + m2 && !e.errored && !e.destroyed + ); + } + function dv(t, e, r, o, f, p, m2) { + (e.writelen = o), (e.writecb = m2), (e.writing = true), (e.sync = true), e.destroyed ? e.onwrite(new ga('write')) : r ? t._writev(f, e.onwrite) : t._write(f, p, e.onwrite), (e.sync = false); + } + function cv(t, e, r, o) { + --e.pendingcb, o(r), Gh(e), uf(t, r); + } + function yx(t, e) { + let r = t._writableState, + o = r.sync, + f = r.writecb; + if (typeof f != 'function') { + uf(t, new gv()); + return; + } + (r.writing = false), + (r.writecb = null), + (r.length -= r.writelen), + (r.writelen = 0), + e + ? (e.stack, r.errored || (r.errored = e), t._readableState && !t._readableState.errored && (t._readableState.errored = e), o ? Mn.nextTick(cv, t, r, e, f) : cv(t, r, e, f)) + : (r.buffered.length > r.bufferedIndex && Yh(t, r), + o ? (r.afterWriteTickInfo !== null && r.afterWriteTickInfo.cb === f ? r.afterWriteTickInfo.count++ : ((r.afterWriteTickInfo = {count: 1, cb: f, stream: t, state: r}), Mn.nextTick(wx, r.afterWriteTickInfo))) : Mv(t, r, 1, f)); + } + function wx({stream: t, state: e, count: r, cb: o}) { + return (e.afterWriteTickInfo = null), Mv(t, e, r, o); + } + function Mv(t, e, r, o) { + for (!e.ending && !t.destroyed && e.length === 0 && e.needDrain && ((e.needDrain = false), t.emit('drain')); r-- > 0; ) e.pendingcb--, o(); + e.destroyed && Gh(e), Xh(t, e); + } + function Gh(t) { + if (t.writing) return; + for (let f = t.bufferedIndex; f < t.buffered.length; ++f) { + var e; + let {chunk: p, callback: m2} = t.buffered[f], + y2 = t.objectMode ? 1 : p.length; + (t.length -= y2), m2((e = t.errored) !== null && e !== undefined ? e : new ga('write')); + } + let r = t[lf].splice(0); + for (let f = 0; f < r.length; f++) { + var o; + r[f]((o = t.errored) !== null && o !== undefined ? o : new ga('end')); + } + rs(t); + } + function Yh(t, e) { + if (e.corked || e.bufferProcessing || e.destroyed || !e.constructed) return; + let {buffered: r, bufferedIndex: o, objectMode: f} = e, + p = r.length - o; + if (!p) return; + let m2 = o; + if (((e.bufferProcessing = true), p > 1 && t._writev)) { + e.pendingcb -= p - 1; + let y2 = e.allNoop + ? $h + : x => { + for (let S = m2; S < r.length; ++S) r[S].callback(x); + }, + M = e.allNoop && m2 === 0 ? r : pv(r, m2); + (M.allBuffers = e.allBuffers), dv(t, e, true, e.length, M, '', y2), rs(e); + } else { + do { + let {chunk: y2, encoding: M, callback: x} = r[m2]; + r[m2++] = null; + let S = f ? 1 : y2.length; + dv(t, e, false, S, y2, M, x); + } while (m2 < r.length && !e.writing); + m2 === r.length ? rs(e) : m2 > 256 ? (r.splice(0, m2), (e.bufferedIndex = 0)) : (e.bufferedIndex = m2); + } + e.bufferProcessing = false; + } + st.prototype._write = function (t, e, r) { + if (this._writev) this._writev([{chunk: t, encoding: e}], r); + else throw new cx('_write()'); + }; + st.prototype._writev = null; + st.prototype.end = function (t, e, r) { + let o = this._writableState; + typeof t == 'function' ? ((r = t), (t = null), (e = null)) : typeof e == 'function' && ((r = e), (e = null)); + let f; + if (t != null) { + let p = wv(this, t, e); + p instanceof ix && (f = p); + } + return ( + o.corked && ((o.corked = 1), this.uncork()), + f || (!o.errored && !o.ending ? ((o.ending = true), Xh(this, o, true), (o.ended = true)) : o.finished ? (f = new vx('end')) : o.destroyed && (f = new ga('end'))), + typeof r == 'function' && (f || o.finished ? Mn.nextTick(r, f) : o[lf].push(r)), + this + ); + }; + function ts(t) { + return t.ending && !t.destroyed && t.constructed && t.length === 0 && !t.errored && t.buffered.length === 0 && !t.finished && !t.writing && !t.errorEmitted && !t.closeEmitted; + } + function Mx(t, e) { + let r = false; + function o(f) { + if (r) { + uf(t, f ?? gv()); + return; + } + if (((r = true), e.pendingcb--, f)) { + let p = e[lf].splice(0); + for (let m2 = 0; m2 < p.length; m2++) p[m2](f); + uf(t, f, e.sync); + } else ts(e) && ((e.prefinished = true), t.emit('prefinish'), e.pendingcb++, Mn.nextTick(Vh, t, e)); + } + (e.sync = true), e.pendingcb++; + try { + t._final(o); + } catch (f) { + o(f); + } + e.sync = false; + } + function _x(t, e) { + !e.prefinished && !e.finalCalled && (typeof t._final == 'function' && !e.destroyed ? ((e.finalCalled = true), Mx(t, e)) : ((e.prefinished = true), t.emit('prefinish'))); + } + function Xh(t, e, r) { + ts(e) && + (_x(t, e), + e.pendingcb === 0 && + (r + ? (e.pendingcb++, + Mn.nextTick( + (o, f) => { + ts(f) ? Vh(o, f) : f.pendingcb--; + }, + t, + e + )) + : ts(e) && (e.pendingcb++, Vh(t, e)))); + } + function Vh(t, e) { + e.pendingcb--, (e.finished = true); + let r = e[lf].splice(0); + for (let o = 0; o < r.length; o++) r[o](); + if ((t.emit('finish'), e.autoDestroy)) { + let o = t._readableState; + (!o || (o.autoDestroy && (o.endEmitted || o.readable === false))) && t.destroy(); + } + } + nx(st.prototype, { + closed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.closed : false; + } + }, + destroyed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.destroyed : false; + }, + set(t) { + this._writableState && (this._writableState.destroyed = t); + } + }, + writable: { + __proto__: null, + get() { + let t = this._writableState; + return !!t && t.writable !== false && !t.destroyed && !t.errored && !t.ending && !t.ended; + }, + set(t) { + this._writableState && (this._writableState.writable = !!t); + } + }, + writableFinished: { + __proto__: null, + get() { + return this._writableState ? this._writableState.finished : false; + } + }, + writableObjectMode: { + __proto__: null, + get() { + return this._writableState ? this._writableState.objectMode : false; + } + }, + writableBuffer: { + __proto__: null, + get() { + return this._writableState && this._writableState.getBuffer(); + } + }, + writableEnded: { + __proto__: null, + get() { + return this._writableState ? this._writableState.ending : false; + } + }, + writableNeedDrain: { + __proto__: null, + get() { + let t = this._writableState; + return t ? !t.destroyed && !t.ending && t.needDrain : false; + } + }, + writableHighWaterMark: { + __proto__: null, + get() { + return this._writableState && this._writableState.highWaterMark; + } + }, + writableCorked: { + __proto__: null, + get() { + return this._writableState ? this._writableState.corked : 0; + } + }, + writableLength: { + __proto__: null, + get() { + return this._writableState && this._writableState.length; + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._writableState ? this._writableState.errored : null; + } + }, + writableAborted: { + __proto__: null, + enumerable: false, + get: function () { + return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished); + } + } + }); + var xx = is.destroy; + st.prototype.destroy = function (t, e) { + let r = this._writableState; + return !r.destroyed && (r.bufferedIndex < r.buffered.length || r[lf].length) && Mn.nextTick(Gh, r), xx.call(this, t, e), this; + }; + st.prototype._undestroy = is.undestroy; + st.prototype._destroy = function (t, e) { + e(t); + }; + st.prototype[sx.captureRejectionSymbol] = function (t) { + this.destroy(t); + }; + var Zh; + function _v() { + return Zh === undefined && (Zh = {}), Zh; + } + st.fromWeb = function (t, e) { + return _v().newStreamWritableFromWritableStream(t, e); + }; + st.toWeb = function (t) { + return _v().newWritableStreamFromStreamWritable(t); + }; + }); + Dv = T2((ZI, Nv) => { + var Qh = (Oi(), ur(pr)), + Sx = Ut(), + {isReadable: Ex, isWritable: Ax, isIterable: Sv, isNodeStream: Rx, isReadableNodeStream: Ev, isWritableNodeStream: Av, isDuplexNodeStream: Bx} = Fi(), + Rv = Ui(), + { + AbortError: Lv, + codes: {ERR_INVALID_ARG_TYPE: qx, ERR_INVALID_RETURN_VALUE: Bv} + } = Jt(), + {destroyer: df} = yn(), + Ix = Qr(), + Tx = ba(), + {createDeferredPromise: qv} = Gr(), + Iv = Fh(), + Tv = globalThis.Blob || Sx.Blob, + kx = + typeof Tv < 'u' + ? function (e) { + return e instanceof Tv; + } + : function (e) { + return false; + }, + Lx = globalThis.AbortController || No().AbortController, + {FunctionPrototypeCall: kv} = Tt(), + _n = class extends Ix { + constructor(e) { + super(e), + e?.readable === false && ((this._readableState.readable = false), (this._readableState.ended = true), (this._readableState.endEmitted = true)), + e?.writable === false && ((this._writableState.writable = false), (this._writableState.ending = true), (this._writableState.ended = true), (this._writableState.finished = true)); + } + }; + Nv.exports = function t(e, r) { + if (Bx(e)) return e; + if (Ev(e)) return ns({readable: e}); + if (Av(e)) return ns({writable: e}); + if (Rx(e)) return ns({writable: false, readable: false}); + if (typeof e == 'function') { + let {value: f, write: p, final: m2, destroy: y2} = Nx(e); + if (Sv(f)) return Iv(_n, f, {objectMode: true, write: p, final: m2, destroy: y2}); + let M = f?.then; + if (typeof M == 'function') { + let x, + S = kv( + M, + f, + E2 => { + if (E2 != null) throw new Bv('nully', 'body', E2); + }, + E2 => { + df(x, E2); + } + ); + return (x = new _n({ + objectMode: true, + readable: false, + write: p, + final(E2) { + m2(async () => { + try { + await S, Qh.nextTick(E2, null); + } catch (B) { + Qh.nextTick(E2, B); + } + }); + }, + destroy: y2 + })); + } + throw new Bv('Iterable, AsyncIterable or AsyncFunction', r, f); + } + if (kx(e)) return t(e.arrayBuffer()); + if (Sv(e)) return Iv(_n, e, {objectMode: true, writable: false}); + if (typeof e?.writable == 'object' || typeof e?.readable == 'object') { + let f = e != null && e.readable ? (Ev(e?.readable) ? e?.readable : t(e.readable)) : undefined, + p = e != null && e.writable ? (Av(e?.writable) ? e?.writable : t(e.writable)) : undefined; + return ns({readable: f, writable: p}); + } + let o = e?.then; + if (typeof o == 'function') { + let f; + return ( + kv( + o, + e, + p => { + p != null && f.push(p), f.push(null); + }, + p => { + df(f, p); + } + ), + (f = new _n({objectMode: true, writable: false, read() {}})) + ); + } + throw new qx(r, ['Blob', 'ReadableStream', 'WritableStream', 'Stream', 'Iterable', 'AsyncIterable', 'Function', '{ readable, writable } pair', 'Promise'], e); + }; + function Nx(t) { + let {promise: e, resolve: r} = qv(), + o = new Lx(), + f = o.signal; + return { + value: t( + (async function* () { + for (;;) { + let m2 = e; + e = null; + let {chunk: y2, done: M, cb: x} = await m2; + if ((Qh.nextTick(x), M)) return; + if (f.aborted) throw new Lv(undefined, {cause: f.reason}); + ({promise: e, resolve: r} = qv()), yield y2; + } + })(), + {signal: f} + ), + write(m2, y2, M) { + let x = r; + (r = null), x({chunk: m2, done: false, cb: M}); + }, + final(m2) { + let y2 = r; + (r = null), y2({done: true, cb: m2}); + }, + destroy(m2, y2) { + o.abort(), y2(m2); + } + }; + } + function ns(t) { + let e = t.readable && typeof t.readable.read != 'function' ? Tx.wrap(t.readable) : t.readable, + r = t.writable, + o = !!Ex(e), + f = !!Ax(r), + p, + m2, + y2, + M, + x; + function S(E2) { + let B = M; + (M = null), B ? B(E2) : E2 ? x.destroy(E2) : !o && !f && x.destroy(); + } + return ( + (x = new _n({readableObjectMode: !!(e != null && e.readableObjectMode), writableObjectMode: !!(r != null && r.writableObjectMode), readable: o, writable: f})), + f && + (Rv(r, E2 => { + (f = false), E2 && df(e, E2), S(E2); + }), + (x._write = function (E2, B, q2) { + r.write(E2, B) ? q2() : (p = q2); + }), + (x._final = function (E2) { + r.end(), (m2 = E2); + }), + r.on('drain', function () { + if (p) { + let E2 = p; + (p = null), E2(); + } + }), + r.on('finish', function () { + if (m2) { + let E2 = m2; + (m2 = null), E2(); + } + })), + o && + (Rv(e, E2 => { + (o = false), E2 && df(e, E2), S(E2); + }), + e.on('readable', function () { + if (y2) { + let E2 = y2; + (y2 = null), E2(); + } + }), + e.on('end', function () { + x.push(null); + }), + (x._read = function () { + for (;;) { + let E2 = e.read(); + if (E2 === null) { + y2 = x._read; + return; + } + if (!x.push(E2)) return; + } + })), + (x._destroy = function (E2, B) { + !E2 && M !== null && (E2 = new Lv()), (y2 = null), (p = null), (m2 = null), M === null ? B(E2) : ((M = B), df(r, E2), df(e, E2)); + }), + x + ); + } + }); + Qr = T2((VI, Ov) => { + var {ObjectDefineProperties: Dx, ObjectGetOwnPropertyDescriptor: bi, ObjectKeys: Px, ObjectSetPrototypeOf: Pv} = Tt(); + Ov.exports = kr; + var ru = ba(), + vr = Jh(); + Pv(kr.prototype, ru.prototype); + Pv(kr, ru); + { + let t = Px(vr.prototype); + for (let e = 0; e < t.length; e++) { + let r = t[e]; + kr.prototype[r] || (kr.prototype[r] = vr.prototype[r]); + } + } + function kr(t) { + if (!(this instanceof kr)) return new kr(t); + ru.call(this, t), + vr.call(this, t), + t + ? ((this.allowHalfOpen = t.allowHalfOpen !== false), + t.readable === false && ((this._readableState.readable = false), (this._readableState.ended = true), (this._readableState.endEmitted = true)), + t.writable === false && ((this._writableState.writable = false), (this._writableState.ending = true), (this._writableState.ended = true), (this._writableState.finished = true))) + : (this.allowHalfOpen = true); + } + Dx(kr.prototype, { + writable: {__proto__: null, ...bi(vr.prototype, 'writable')}, + writableHighWaterMark: {__proto__: null, ...bi(vr.prototype, 'writableHighWaterMark')}, + writableObjectMode: {__proto__: null, ...bi(vr.prototype, 'writableObjectMode')}, + writableBuffer: {__proto__: null, ...bi(vr.prototype, 'writableBuffer')}, + writableLength: {__proto__: null, ...bi(vr.prototype, 'writableLength')}, + writableFinished: {__proto__: null, ...bi(vr.prototype, 'writableFinished')}, + writableCorked: {__proto__: null, ...bi(vr.prototype, 'writableCorked')}, + writableEnded: {__proto__: null, ...bi(vr.prototype, 'writableEnded')}, + writableNeedDrain: {__proto__: null, ...bi(vr.prototype, 'writableNeedDrain')}, + destroyed: { + __proto__: null, + get() { + return this._readableState === undefined || this._writableState === undefined ? false : this._readableState.destroyed && this._writableState.destroyed; + }, + set(t) { + this._readableState && this._writableState && ((this._readableState.destroyed = t), (this._writableState.destroyed = t)); + } + } + }); + var eu; + function Cv() { + return eu === undefined && (eu = {}), eu; + } + kr.fromWeb = function (t, e) { + return Cv().newStreamDuplexFromReadableWritablePair(t, e); + }; + kr.toWeb = function (t) { + return Cv().newReadableWritablePairFromDuplex(t); + }; + var tu; + kr.from = function (t) { + return tu || (tu = Dv()), tu(t, 'body'); + }; + }); + fu = T2(($I, Uv) => { + var {ObjectSetPrototypeOf: Fv, Symbol: Cx} = Tt(); + Uv.exports = mi; + var {ERR_METHOD_NOT_IMPLEMENTED: Ox} = Jt().codes, + nu = Qr(), + {getHighWaterMark: Fx} = Xo(); + Fv(mi.prototype, nu.prototype); + Fv(mi, nu); + var wa = Cx('kCallback'); + function mi(t) { + if (!(this instanceof mi)) return new mi(t); + let e = t ? Fx(this, t, 'readableHighWaterMark', true) : null; + e === 0 && (t = {...t, highWaterMark: null, readableHighWaterMark: e, writableHighWaterMark: t.writableHighWaterMark || 0}), + nu.call(this, t), + (this._readableState.sync = false), + (this[wa] = null), + t && (typeof t.transform == 'function' && (this._transform = t.transform), typeof t.flush == 'function' && (this._flush = t.flush)), + this.on('prefinish', Ux); + } + function iu(t) { + typeof this._flush == 'function' && !this.destroyed + ? this._flush((e, r) => { + if (e) { + t ? t(e) : this.destroy(e); + return; + } + r != null && this.push(r), this.push(null), t && t(); + }) + : (this.push(null), t && t()); + } + function Ux() { + this._final !== iu && iu.call(this); + } + mi.prototype._final = iu; + mi.prototype._transform = function (t, e, r) { + throw new Ox('_transform()'); + }; + mi.prototype._write = function (t, e, r) { + let o = this._readableState, + f = this._writableState, + p = o.length; + this._transform(t, e, (m2, y2) => { + if (m2) { + r(m2); + return; + } + y2 != null && this.push(y2), f.ended || p === o.length || o.length < o.highWaterMark ? r() : (this[wa] = r); + }); + }; + mi.prototype._read = function () { + if (this[wa]) { + let t = this[wa]; + (this[wa] = null), t(); + } + }; + }); + ou = T2((GI, Hv) => { + var {ObjectSetPrototypeOf: zv} = Tt(); + Hv.exports = cf; + var au = fu(); + zv(cf.prototype, au.prototype); + zv(cf, au); + function cf(t) { + if (!(this instanceof cf)) return new cf(t); + au.call(this, t); + } + cf.prototype._transform = function (t, e, r) { + r(null, t); + }; + }); + os = T2((YI, Gv) => { + var fs = (Oi(), ur(pr)), + {ArrayIsArray: zx, Promise: Hx, SymbolAsyncIterator: Wx} = Tt(), + as = Ui(), + {once: Kx} = Gr(), + jx = yn(), + Wv = Qr(), + { + aggregateTwoErrors: Zx, + codes: {ERR_INVALID_ARG_TYPE: Vv, ERR_INVALID_RETURN_VALUE: su, ERR_MISSING_ARGS: Vx, ERR_STREAM_DESTROYED: $x, ERR_STREAM_PREMATURE_CLOSE: Gx}, + AbortError: Yx + } = Jt(), + {validateFunction: Xx, validateAbortSignal: Jx} = pa(), + {isIterable: pf, isReadable: hu, isReadableNodeStream: du, isNodeStream: Kv} = Fi(), + Qx = globalThis.AbortController || No().AbortController, + uu, + lu; + function jv(t, e, r) { + let o = false; + t.on('close', () => { + o = true; + }); + let f = as(t, {readable: e, writable: r}, p => { + o = !p; + }); + return { + destroy: p => { + o || ((o = true), jx.destroyer(t, p || new $x('pipe'))); + }, + cleanup: f + }; + } + function e7(t) { + return Xx(t[t.length - 1], 'streams[stream.length - 1]'), t.pop(); + } + function t7(t) { + if (pf(t)) return t; + if (du(t)) return r7(t); + throw new Vv('val', ['Readable', 'Iterable', 'AsyncIterable'], t); + } + async function* r7(t) { + lu || (lu = ba()), yield* lu.prototype[Wx].call(t); + } + async function Zv(t, e, r, {end: o}) { + let f, + p = null, + m2 = x => { + if ((x && (f = x), p)) { + let S = p; + (p = null), S(); + } + }, + y2 = () => + new Hx((x, S) => { + f + ? S(f) + : (p = () => { + f ? S(f) : x(); + }); + }); + e.on('drain', m2); + let M = as(e, {readable: false}, m2); + try { + e.writableNeedDrain && (await y2()); + for await (let x of t) e.write(x) || (await y2()); + o && e.end(), await y2(), r(); + } catch (x) { + r(f !== x ? Zx(f, x) : x); + } finally { + M(), e.off('drain', m2); + } + } + function i7(...t) { + return $v(t, Kx(e7(t))); + } + function $v(t, e, r) { + if ((t.length === 1 && zx(t[0]) && (t = t[0]), t.length < 2)) throw new Vx('streams'); + let o = new Qx(), + f = o.signal, + p = r?.signal, + m2 = []; + Jx(p, 'options.signal'); + function y2() { + q2(new Yx()); + } + p?.addEventListener('abort', y2); + let M, + x, + S = [], + E2 = 0; + function B(N) { + q2(N, --E2 === 0); + } + function q2(N, we) { + if ((N && (!M || M.code === 'ERR_STREAM_PREMATURE_CLOSE') && (M = N), !(!M && !we))) { + for (; S.length; ) S.shift()(M); + p?.removeEventListener('abort', y2), o.abort(), we && (M || m2.forEach(ye => ye()), fs.nextTick(e, M, x)); + } + } + let L2; + for (let N = 0; N < t.length; N++) { + let we = t[N], + ye = N < t.length - 1, + xe = N > 0, + Re = ye || r?.end !== false, + Ee = N === t.length - 1; + if (Kv(we)) { + let Ae = function (P) { + P && P.name !== 'AbortError' && P.code !== 'ERR_STREAM_PREMATURE_CLOSE' && B(P); + }; + var _e = Ae; + if (Re) { + let {destroy: P, cleanup: Se} = jv(we, ye, xe); + S.push(P), hu(we) && Ee && m2.push(Se); + } + we.on('error', Ae), + hu(we) && + Ee && + m2.push(() => { + we.removeListener('error', Ae); + }); + } + if (N === 0) + if (typeof we == 'function') { + if (((L2 = we({signal: f})), !pf(L2))) throw new su('Iterable, AsyncIterable or Stream', 'source', L2); + } else pf(we) || du(we) ? (L2 = we) : (L2 = Wv.from(we)); + else if (typeof we == 'function') + if (((L2 = t7(L2)), (L2 = we(L2, {signal: f})), ye)) { + if (!pf(L2, true)) throw new su('AsyncIterable', `transform[${N - 1}]`, L2); + } else { + var ge; + uu || (uu = ou()); + let Ae = new uu({objectMode: true}), + P = (ge = L2) === null || ge === undefined ? undefined : ge.then; + if (typeof P == 'function') + E2++, + P.call( + L2, + i => { + (x = i), i != null && Ae.write(i), Re && Ae.end(), fs.nextTick(B); + }, + i => { + Ae.destroy(i), fs.nextTick(B, i); + } + ); + else if (pf(L2, true)) E2++, Zv(L2, Ae, B, {end: Re}); + else throw new su('AsyncIterable or Promise', 'destination', L2); + L2 = Ae; + let {destroy: Se, cleanup: v} = jv(L2, false, true); + S.push(Se), Ee && m2.push(v); + } + else if (Kv(we)) { + if (du(L2)) { + E2 += 2; + let Ae = n7(L2, we, B, {end: Re}); + hu(we) && Ee && m2.push(Ae); + } else if (pf(L2)) E2++, Zv(L2, we, B, {end: Re}); + else throw new Vv('val', ['Readable', 'Iterable', 'AsyncIterable'], L2); + L2 = we; + } else L2 = Wv.from(we); + } + return ((f != null && f.aborted) || (p != null && p.aborted)) && fs.nextTick(y2), L2; + } + function n7(t, e, r, {end: o}) { + let f = false; + return ( + e.on('close', () => { + f || r(new Gx()); + }), + t.pipe(e, {end: o}), + o + ? t.once('end', () => { + (f = true), e.end(); + }) + : r(), + as(t, {readable: true, writable: false}, p => { + let m2 = t._readableState; + p && p.code === 'ERR_STREAM_PREMATURE_CLOSE' && m2 && m2.ended && !m2.errored && !m2.errorEmitted ? t.once('end', r).once('error', r) : r(p); + }), + as(e, {readable: false, writable: true}, r) + ); + } + Gv.exports = {pipelineImpl: $v, pipeline: i7}; + }); + eb = T2((XI, Qv) => { + var {pipeline: f7} = os(), + ss = Qr(), + {destroyer: a7} = yn(), + {isNodeStream: o7, isReadable: Yv, isWritable: Xv} = Fi(), + { + AbortError: s7, + codes: {ERR_INVALID_ARG_VALUE: Jv, ERR_MISSING_ARGS: h7} + } = Jt(); + Qv.exports = function (...e) { + if (e.length === 0) throw new h7('streams'); + if (e.length === 1) return ss.from(e[0]); + let r = [...e]; + if ((typeof e[0] == 'function' && (e[0] = ss.from(e[0])), typeof e[e.length - 1] == 'function')) { + let q2 = e.length - 1; + e[q2] = ss.from(e[q2]); + } + for (let q2 = 0; q2 < e.length; ++q2) + if (!!o7(e[q2])) { + if (q2 < e.length - 1 && !Yv(e[q2])) throw new Jv(`streams[${q2}]`, r[q2], 'must be readable'); + if (q2 > 0 && !Xv(e[q2])) throw new Jv(`streams[${q2}]`, r[q2], 'must be writable'); + } + let o, f, p, m2, y2; + function M(q2) { + let L2 = m2; + (m2 = null), L2 ? L2(q2) : q2 ? y2.destroy(q2) : !B && !E2 && y2.destroy(); + } + let x = e[0], + S = f7(e, M), + E2 = !!Xv(x), + B = !!Yv(S); + return ( + (y2 = new ss({writableObjectMode: !!(x != null && x.writableObjectMode), readableObjectMode: !!(S != null && S.writableObjectMode), writable: E2, readable: B})), + E2 && + ((y2._write = function (q2, L2, ge) { + x.write(q2, L2) ? ge() : (o = ge); + }), + (y2._final = function (q2) { + x.end(), (f = q2); + }), + x.on('drain', function () { + if (o) { + let q2 = o; + (o = null), q2(); + } + }), + S.on('finish', function () { + if (f) { + let q2 = f; + (f = null), q2(); + } + })), + B && + (S.on('readable', function () { + if (p) { + let q2 = p; + (p = null), q2(); + } + }), + S.on('end', function () { + y2.push(null); + }), + (y2._read = function () { + for (;;) { + let q2 = S.read(); + if (q2 === null) { + p = y2._read; + return; + } + if (!y2.push(q2)) return; + } + })), + (y2._destroy = function (q2, L2) { + !q2 && m2 !== null && (q2 = new s7()), (p = null), (o = null), (f = null), m2 === null ? L2(q2) : ((m2 = L2), a7(S, q2)); + }), + y2 + ); + }; + }); + cu = T2((JI, tb) => { + var {ArrayPrototypePop: u7, Promise: l7} = Tt(), + {isIterable: d7, isNodeStream: c7} = Fi(), + {pipelineImpl: p7} = os(), + {finished: v7} = Ui(); + function b7(...t) { + return new l7((e, r) => { + let o, + f, + p = t[t.length - 1]; + if (p && typeof p == 'object' && !c7(p) && !d7(p)) { + let m2 = u7(t); + (o = m2.signal), (f = m2.end); + } + p7( + t, + (m2, y2) => { + m2 ? r(m2) : e(y2); + }, + {signal: o, end: f} + ); + }); + } + tb.exports = {finished: v7, pipeline: b7}; + }); + lb = T2((QI, ub) => { + var {Buffer: m7} = Ut(), + {ObjectDefineProperty: gi, ObjectKeys: nb, ReflectApply: fb} = Tt(), + { + promisify: {custom: ab} + } = Gr(), + {streamReturningOperators: rb, promiseReturningOperators: ib} = k1(), + { + codes: {ERR_ILLEGAL_CONSTRUCTOR: ob} + } = Jt(), + g7 = eb(), + {pipeline: sb} = os(), + {destroyer: y7} = yn(), + hb = Ui(), + pu = cu(), + vu = Fi(), + ct = (ub.exports = Vo().Stream); + ct.isDisturbed = vu.isDisturbed; + ct.isErrored = vu.isErrored; + ct.isReadable = vu.isReadable; + ct.Readable = ba(); + for (let t of nb(rb)) { + let r = function (...o) { + if (new.target) throw ob(); + return ct.Readable.from(fb(e, this, o)); + }; + M7 = r; + let e = rb[t]; + gi(r, 'name', {__proto__: null, value: e.name}), gi(r, 'length', {__proto__: null, value: e.length}), gi(ct.Readable.prototype, t, {__proto__: null, value: r, enumerable: false, configurable: true, writable: true}); + } + var M7; + for (let t of nb(ib)) { + let r = function (...f) { + if (new.target) throw ob(); + return fb(e, this, f); + }; + M7 = r; + let e = ib[t]; + gi(r, 'name', {__proto__: null, value: e.name}), gi(r, 'length', {__proto__: null, value: e.length}), gi(ct.Readable.prototype, t, {__proto__: null, value: r, enumerable: false, configurable: true, writable: true}); + } + var M7; + ct.Writable = Jh(); + ct.Duplex = Qr(); + ct.Transform = fu(); + ct.PassThrough = ou(); + ct.pipeline = sb; + var {addAbortSignal: w7} = Go(); + ct.addAbortSignal = w7; + ct.finished = hb; + ct.destroy = y7; + ct.compose = g7; + gi(ct, 'promises', { + __proto__: null, + configurable: true, + enumerable: true, + get() { + return pu; + } + }); + gi(sb, ab, { + __proto__: null, + enumerable: true, + get() { + return pu.pipeline; + } + }); + gi(hb, ab, { + __proto__: null, + enumerable: true, + get() { + return pu.finished; + } + }); + ct.Stream = ct; + ct._isUint8Array = function (e) { + return e instanceof Uint8Array; + }; + ct._uint8ArrayToBuffer = function (e) { + return m7.from(e.buffer, e.byteOffset, e.byteLength); + }; + }); + bu = T2((eT, pt) => { + var Lt = lb(), + _7 = cu(), + x7 = Lt.Readable.destroy; + pt.exports = Lt.Readable; + pt.exports._uint8ArrayToBuffer = Lt._uint8ArrayToBuffer; + pt.exports._isUint8Array = Lt._isUint8Array; + pt.exports.isDisturbed = Lt.isDisturbed; + pt.exports.isErrored = Lt.isErrored; + pt.exports.isReadable = Lt.isReadable; + pt.exports.Readable = Lt.Readable; + pt.exports.Writable = Lt.Writable; + pt.exports.Duplex = Lt.Duplex; + pt.exports.Transform = Lt.Transform; + pt.exports.PassThrough = Lt.PassThrough; + pt.exports.addAbortSignal = Lt.addAbortSignal; + pt.exports.finished = Lt.finished; + pt.exports.destroy = Lt.destroy; + pt.exports.destroy = x7; + pt.exports.pipeline = Lt.pipeline; + pt.exports.compose = Lt.compose; + Object.defineProperty(Lt, 'promises', { + configurable: true, + enumerable: true, + get() { + return _7; + } + }); + pt.exports.Stream = Lt.Stream; + pt.exports.default = pt.exports; + }); + vf = {}; + Ja(vf, {default: () => S7}); + db = R0(() => { + ot(vf, rn(bu())); + S7 = rn(bu()); + }); + yi = T2((rT, vb) => { + var cb = Te().Buffer, + pb = (db(), ur(vf)).Transform, + E7 = co().StringDecoder, + A7 = Ie(); + function Lr(t) { + pb.call(this), + (this.hashMode = typeof t == 'string'), + this.hashMode ? (this[t] = this._finalOrDigest) : (this.final = this._finalOrDigest), + this._final && ((this.__final = this._final), (this._final = null)), + (this._decoder = null), + (this._encoding = null); + } + A7(Lr, pb); + Lr.prototype.update = function (t, e, r) { + typeof t == 'string' && (t = cb.from(t, e)); + var o = this._update(t); + return this.hashMode ? this : (r && (o = this._toString(o, r)), o); + }; + Lr.prototype.setAutoPadding = function () {}; + Lr.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state'); + }; + Lr.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state'); + }; + Lr.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state'); + }; + Lr.prototype._transform = function (t, e, r) { + var o; + try { + this.hashMode ? this._update(t) : this.push(this._update(t)); + } catch (f) { + o = f; + } finally { + r(o); + } + }; + Lr.prototype._flush = function (t) { + var e; + try { + this.push(this.__final()); + } catch (r) { + e = r; + } + t(e); + }; + Lr.prototype._finalOrDigest = function (t) { + var e = this.__final() || cb.alloc(0); + return t && (e = this._toString(e, t, true)), e; + }; + Lr.prototype._toString = function (t, e, r) { + if ((this._decoder || ((this._decoder = new E7(e)), (this._encoding = e)), this._encoding !== e)) throw new Error("can't switch encodings"); + var o = this._decoder.write(t); + return r && (o += this._decoder.end()), o; + }; + vb.exports = Lr; + }); + bf = T2((iT, mb) => { + var R7 = Ie(), + B7 = Ao(), + q7 = Bo(), + I7 = ko(), + bb = yi(); + function hs(t) { + bb.call(this, 'digest'), (this._hash = t); + } + R7(hs, bb); + hs.prototype._update = function (t) { + this._hash.update(t); + }; + hs.prototype._final = function () { + return this._hash.digest(); + }; + mb.exports = function (e) { + return (e = e.toLowerCase()), e === 'md5' ? new B7() : e === 'rmd160' || e === 'ripemd160' ? new q7() : new hs(I7(e)); + }; + }); + wb = T2((nT, yb) => { + var T7 = Ie(), + xn = Te().Buffer, + gb = yi(), + k7 = xn.alloc(128), + mf = 64; + function us(t, e) { + gb.call(this, 'digest'), typeof e == 'string' && (e = xn.from(e)), (this._alg = t), (this._key = e), e.length > mf ? (e = t(e)) : e.length < mf && (e = xn.concat([e, k7], mf)); + for (var r = (this._ipad = xn.allocUnsafe(mf)), o = (this._opad = xn.allocUnsafe(mf)), f = 0; f < mf; f++) (r[f] = e[f] ^ 54), (o[f] = e[f] ^ 92); + this._hash = [r]; + } + T7(us, gb); + us.prototype._update = function (t) { + this._hash.push(t); + }; + us.prototype._final = function () { + var t = this._alg(xn.concat(this._hash)); + return this._alg(xn.concat([this._opad, t])); + }; + yb.exports = us; + }); + mu = T2((fT, Mb) => { + var L7 = Ao(); + Mb.exports = function (t) { + return new L7().update(t).digest(); + }; + }); + wu = T2((aT, xb) => { + var N7 = Ie(), + D7 = wb(), + _b = yi(), + Ma = Te().Buffer, + P7 = mu(), + gu = Bo(), + yu = ko(), + C7 = Ma.alloc(128); + function _a(t, e) { + _b.call(this, 'digest'), typeof e == 'string' && (e = Ma.from(e)); + var r = t === 'sha512' || t === 'sha384' ? 128 : 64; + if (((this._alg = t), (this._key = e), e.length > r)) { + var o = t === 'rmd160' ? new gu() : yu(t); + e = o.update(e).digest(); + } else e.length < r && (e = Ma.concat([e, C7], r)); + for (var f = (this._ipad = Ma.allocUnsafe(r)), p = (this._opad = Ma.allocUnsafe(r)), m2 = 0; m2 < r; m2++) (f[m2] = e[m2] ^ 54), (p[m2] = e[m2] ^ 92); + (this._hash = t === 'rmd160' ? new gu() : yu(t)), this._hash.update(f); + } + N7(_a, _b); + _a.prototype._update = function (t) { + this._hash.update(t); + }; + _a.prototype._final = function () { + var t = this._hash.digest(), + e = this._alg === 'rmd160' ? new gu() : yu(this._alg); + return e.update(this._opad).update(t).digest(); + }; + xb.exports = function (e, r) { + return (e = e.toLowerCase()), e === 'rmd160' || e === 'ripemd160' ? new _a('rmd160', r) : e === 'md5' ? new D7(P7, r) : new _a(e, r); + }; + }); + Mu = T2((oT, O7) => { + O7.exports = { + sha224WithRSAEncryption: {sign: 'rsa', hash: 'sha224', id: '302d300d06096086480165030402040500041c'}, + 'RSA-SHA224': {sign: 'ecdsa/rsa', hash: 'sha224', id: '302d300d06096086480165030402040500041c'}, + sha256WithRSAEncryption: {sign: 'rsa', hash: 'sha256', id: '3031300d060960864801650304020105000420'}, + 'RSA-SHA256': {sign: 'ecdsa/rsa', hash: 'sha256', id: '3031300d060960864801650304020105000420'}, + sha384WithRSAEncryption: {sign: 'rsa', hash: 'sha384', id: '3041300d060960864801650304020205000430'}, + 'RSA-SHA384': {sign: 'ecdsa/rsa', hash: 'sha384', id: '3041300d060960864801650304020205000430'}, + sha512WithRSAEncryption: {sign: 'rsa', hash: 'sha512', id: '3051300d060960864801650304020305000440'}, + 'RSA-SHA512': {sign: 'ecdsa/rsa', hash: 'sha512', id: '3051300d060960864801650304020305000440'}, + 'RSA-SHA1': {sign: 'rsa', hash: 'sha1', id: '3021300906052b0e03021a05000414'}, + 'ecdsa-with-SHA1': {sign: 'ecdsa', hash: 'sha1', id: ''}, + sha256: {sign: 'ecdsa', hash: 'sha256', id: ''}, + sha224: {sign: 'ecdsa', hash: 'sha224', id: ''}, + sha384: {sign: 'ecdsa', hash: 'sha384', id: ''}, + sha512: {sign: 'ecdsa', hash: 'sha512', id: ''}, + 'DSA-SHA': {sign: 'dsa', hash: 'sha1', id: ''}, + 'DSA-SHA1': {sign: 'dsa', hash: 'sha1', id: ''}, + DSA: {sign: 'dsa', hash: 'sha1', id: ''}, + 'DSA-WITH-SHA224': {sign: 'dsa', hash: 'sha224', id: ''}, + 'DSA-SHA224': {sign: 'dsa', hash: 'sha224', id: ''}, + 'DSA-WITH-SHA256': {sign: 'dsa', hash: 'sha256', id: ''}, + 'DSA-SHA256': {sign: 'dsa', hash: 'sha256', id: ''}, + 'DSA-WITH-SHA384': {sign: 'dsa', hash: 'sha384', id: ''}, + 'DSA-SHA384': {sign: 'dsa', hash: 'sha384', id: ''}, + 'DSA-WITH-SHA512': {sign: 'dsa', hash: 'sha512', id: ''}, + 'DSA-SHA512': {sign: 'dsa', hash: 'sha512', id: ''}, + 'DSA-RIPEMD160': {sign: 'dsa', hash: 'rmd160', id: ''}, + ripemd160WithRSA: {sign: 'rsa', hash: 'rmd160', id: '3021300906052b2403020105000414'}, + 'RSA-RIPEMD160': {sign: 'rsa', hash: 'rmd160', id: '3021300906052b2403020105000414'}, + md5WithRSAEncryption: {sign: 'rsa', hash: 'md5', id: '3020300c06082a864886f70d020505000410'}, + 'RSA-MD5': {sign: 'rsa', hash: 'md5', id: '3020300c06082a864886f70d020505000410'} + }; + }); + Eb = T2((sT, Sb) => { + Sb.exports = Mu(); + }); + _u = T2((hT, Ab) => { + var F7 = Math.pow(2, 30) - 1; + Ab.exports = function (t, e) { + if (typeof t != 'number') throw new TypeError('Iterations not a number'); + if (t < 0) throw new TypeError('Bad iterations'); + if (typeof e != 'number') throw new TypeError('Key length not a number'); + if (e < 0 || e > F7 || e !== e) throw new TypeError('Bad key length'); + }; + }); + xu = T2((uT, Bb) => { + var ls; + global.process && global.process.browser ? (ls = 'utf-8') : global.process && global.process.version ? ((Rb = parseInt(process.version.split('.')[0].slice(1), 10)), (ls = Rb >= 6 ? 'utf-8' : 'binary')) : (ls = 'utf-8'); + var Rb; + Bb.exports = ls; + }); + Eu = T2((lT, qb) => { + var Su = Te().Buffer; + qb.exports = function (t, e, r) { + if (Su.isBuffer(t)) return t; + if (typeof t == 'string') return Su.from(t, e); + if (ArrayBuffer.isView(t)) return Su.from(t.buffer); + throw new TypeError(r + ' must be a string, a Buffer, a typed array or a DataView'); + }; + }); + Au = T2((dT, Lb) => { + var U7 = mu(), + z7 = Bo(), + H7 = ko(), + Sn = Te().Buffer, + W7 = _u(), + Ib = xu(), + Tb = Eu(), + K7 = Sn.alloc(128), + ds = {md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, rmd160: 20, ripemd160: 20}; + function kb(t, e, r) { + var o = j7(t), + f = t === 'sha512' || t === 'sha384' ? 128 : 64; + e.length > f ? (e = o(e)) : e.length < f && (e = Sn.concat([e, K7], f)); + for (var p = Sn.allocUnsafe(f + ds[t]), m2 = Sn.allocUnsafe(f + ds[t]), y2 = 0; y2 < f; y2++) (p[y2] = e[y2] ^ 54), (m2[y2] = e[y2] ^ 92); + var M = Sn.allocUnsafe(f + r + 4); + p.copy(M, 0, 0, f), (this.ipad1 = M), (this.ipad2 = p), (this.opad = m2), (this.alg = t), (this.blocksize = f), (this.hash = o), (this.size = ds[t]); + } + kb.prototype.run = function (t, e) { + t.copy(e, this.blocksize); + var r = this.hash(e); + return r.copy(this.opad, this.blocksize), this.hash(this.opad); + }; + function j7(t) { + function e(o) { + return H7(t).update(o).digest(); + } + function r(o) { + return new z7().update(o).digest(); + } + return t === 'rmd160' || t === 'ripemd160' ? r : t === 'md5' ? U7 : e; + } + function Z7(t, e, r, o, f) { + W7(r, o), (t = Tb(t, Ib, 'Password')), (e = Tb(e, Ib, 'Salt')), (f = f || 'sha1'); + var p = new kb(f, t, e.length), + m2 = Sn.allocUnsafe(o), + y2 = Sn.allocUnsafe(e.length + 4); + e.copy(y2, 0, 0, e.length); + for (var M = 0, x = ds[f], S = Math.ceil(o / x), E2 = 1; E2 <= S; E2++) { + y2.writeUInt32BE(E2, e.length); + for (var B = p.run(y2, p.ipad1), q2 = B, L2 = 1; L2 < r; L2++) { + q2 = p.run(q2, p.ipad2); + for (var ge = 0; ge < x; ge++) B[ge] ^= q2[ge]; + } + B.copy(m2, M), (M += x); + } + return m2; + } + Lb.exports = Z7; + }); + Ub = T2((cT, Fb) => { + var Cb = Te().Buffer, + V7 = _u(), + Nb = xu(), + Db = Au(), + Pb = Eu(), + cs, + xa = global.crypto && global.crypto.subtle, + $7 = {sha: 'SHA-1', 'sha-1': 'SHA-1', sha1: 'SHA-1', sha256: 'SHA-256', 'sha-256': 'SHA-256', sha384: 'SHA-384', 'sha-384': 'SHA-384', 'sha-512': 'SHA-512', sha512: 'SHA-512'}, + Ru = []; + function G7(t) { + if ((global.process && !global.process.browser) || !xa || !xa.importKey || !xa.deriveBits) return Promise.resolve(false); + if (Ru[t] !== undefined) return Ru[t]; + cs = cs || Cb.alloc(8); + var e = Ob(cs, cs, 10, 128, t) + .then(function () { + return true; + }) + .catch(function () { + return false; + }); + return (Ru[t] = e), e; + } + var En; + function Bu() { + return En || (global.process && global.process.nextTick ? (En = global.process.nextTick) : global.queueMicrotask ? (En = global.queueMicrotask) : global.setImmediate ? (En = global.setImmediate) : (En = global.setTimeout), En); + } + function Ob(t, e, r, o, f) { + return xa + .importKey('raw', t, {name: 'PBKDF2'}, false, ['deriveBits']) + .then(function (p) { + return xa.deriveBits({name: 'PBKDF2', salt: e, iterations: r, hash: {name: f}}, p, o << 3); + }) + .then(function (p) { + return Cb.from(p); + }); + } + function Y7(t, e) { + t.then( + function (r) { + Bu()(function () { + e(null, r); + }); + }, + function (r) { + Bu()(function () { + e(r); + }); + } + ); + } + Fb.exports = function (t, e, r, o, f, p) { + typeof f == 'function' && ((p = f), (f = undefined)), (f = f || 'sha1'); + var m2 = $7[f.toLowerCase()]; + if (!m2 || typeof global.Promise != 'function') { + Bu()(function () { + var y2; + try { + y2 = Db(t, e, r, o, f); + } catch (M) { + return p(M); + } + p(null, y2); + }); + return; + } + if ((V7(r, o), (t = Pb(t, Nb, 'Password')), (e = Pb(e, Nb, 'Salt')), typeof p != 'function')) throw new Error('No callback provided to pbkdf2'); + Y7( + G7(m2).then(function (y2) { + return y2 ? Ob(t, e, r, o, m2) : Db(t, e, r, o, f); + }), + p + ); + }; + }); + Iu = T2(qu => { + qu.pbkdf2 = Ub(); + qu.pbkdf2Sync = Au(); + }); + Tu = T2(br => { + br.readUInt32BE = function (e, r) { + var o = (e[0 + r] << 24) | (e[1 + r] << 16) | (e[2 + r] << 8) | e[3 + r]; + return o >>> 0; + }; + br.writeUInt32BE = function (e, r, o) { + (e[0 + o] = r >>> 24), (e[1 + o] = (r >>> 16) & 255), (e[2 + o] = (r >>> 8) & 255), (e[3 + o] = r & 255); + }; + br.ip = function (e, r, o, f) { + for (var p = 0, m2 = 0, y2 = 6; y2 >= 0; y2 -= 2) { + for (var M = 0; M <= 24; M += 8) (p <<= 1), (p |= (r >>> (M + y2)) & 1); + for (var M = 0; M <= 24; M += 8) (p <<= 1), (p |= (e >>> (M + y2)) & 1); + } + for (var y2 = 6; y2 >= 0; y2 -= 2) { + for (var M = 1; M <= 25; M += 8) (m2 <<= 1), (m2 |= (r >>> (M + y2)) & 1); + for (var M = 1; M <= 25; M += 8) (m2 <<= 1), (m2 |= (e >>> (M + y2)) & 1); + } + (o[f + 0] = p >>> 0), (o[f + 1] = m2 >>> 0); + }; + br.rip = function (e, r, o, f) { + for (var p = 0, m2 = 0, y2 = 0; y2 < 4; y2++) for (var M = 24; M >= 0; M -= 8) (p <<= 1), (p |= (r >>> (M + y2)) & 1), (p <<= 1), (p |= (e >>> (M + y2)) & 1); + for (var y2 = 4; y2 < 8; y2++) for (var M = 24; M >= 0; M -= 8) (m2 <<= 1), (m2 |= (r >>> (M + y2)) & 1), (m2 <<= 1), (m2 |= (e >>> (M + y2)) & 1); + (o[f + 0] = p >>> 0), (o[f + 1] = m2 >>> 0); + }; + br.pc1 = function (e, r, o, f) { + for (var p = 0, m2 = 0, y2 = 7; y2 >= 5; y2--) { + for (var M = 0; M <= 24; M += 8) (p <<= 1), (p |= (r >> (M + y2)) & 1); + for (var M = 0; M <= 24; M += 8) (p <<= 1), (p |= (e >> (M + y2)) & 1); + } + for (var M = 0; M <= 24; M += 8) (p <<= 1), (p |= (r >> (M + y2)) & 1); + for (var y2 = 1; y2 <= 3; y2++) { + for (var M = 0; M <= 24; M += 8) (m2 <<= 1), (m2 |= (r >> (M + y2)) & 1); + for (var M = 0; M <= 24; M += 8) (m2 <<= 1), (m2 |= (e >> (M + y2)) & 1); + } + for (var M = 0; M <= 24; M += 8) (m2 <<= 1), (m2 |= (e >> (M + y2)) & 1); + (o[f + 0] = p >>> 0), (o[f + 1] = m2 >>> 0); + }; + br.r28shl = function (e, r) { + return ((e << r) & 268435455) | (e >>> (28 - r)); + }; + var ps = [14, 11, 17, 4, 27, 23, 25, 0, 13, 22, 7, 18, 5, 9, 16, 24, 2, 20, 12, 21, 1, 8, 15, 26, 15, 4, 25, 19, 9, 1, 26, 16, 5, 11, 23, 8, 12, 7, 17, 0, 22, 3, 10, 14, 6, 20, 27, 24]; + br.pc2 = function (e, r, o, f) { + for (var p = 0, m2 = 0, y2 = ps.length >>> 1, M = 0; M < y2; M++) (p <<= 1), (p |= (e >>> ps[M]) & 1); + for (var M = y2; M < ps.length; M++) (m2 <<= 1), (m2 |= (r >>> ps[M]) & 1); + (o[f + 0] = p >>> 0), (o[f + 1] = m2 >>> 0); + }; + br.expand = function (e, r, o) { + var f = 0, + p = 0; + f = ((e & 1) << 5) | (e >>> 27); + for (var m2 = 23; m2 >= 15; m2 -= 4) (f <<= 6), (f |= (e >>> m2) & 63); + for (var m2 = 11; m2 >= 3; m2 -= 4) (p |= (e >>> m2) & 63), (p <<= 6); + (p |= ((e & 31) << 1) | (e >>> 31)), (r[o + 0] = f >>> 0), (r[o + 1] = p >>> 0); + }; + var zb = [ + 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, 15, 3, 1, 13, 8, 4, + 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, + 6, 5, 10, 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, 1, 4, 2, 7, + 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, + 0, 9, 14, 8, 9, 6, 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, 9, + 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, 1, 6, 4, 11, 11, 13, 13, + 8, 12, 1, 3, 4, 7, 10, 14, 7, 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, + 2, 13, 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 + ]; + br.substitute = function (e, r) { + for (var o = 0, f = 0; f < 4; f++) { + var p = (e >>> (18 - f * 6)) & 63, + m2 = zb[f * 64 + p]; + (o <<= 4), (o |= m2); + } + for (var f = 0; f < 4; f++) { + var p = (r >>> (18 - f * 6)) & 63, + m2 = zb[4 * 64 + f * 64 + p]; + (o <<= 4), (o |= m2); + } + return o >>> 0; + }; + var Hb = [16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7]; + br.permute = function (e) { + for (var r = 0, o = 0; o < Hb.length; o++) (r <<= 1), (r |= (e >>> Hb[o]) & 1); + return r >>> 0; + }; + br.padSplit = function (e, r, o) { + for (var f = e.toString(2); f.length < r; ) f = '0' + f; + for (var p = [], m2 = 0; m2 < r; m2 += o) p.push(f.slice(m2, m2 + o)); + return p.join(' '); + }; + }); + ar = T2((bT, Kb) => { + Kb.exports = Wb; + function Wb(t, e) { + if (!t) throw new Error(e || 'Assertion failed'); + } + Wb.equal = function (e, r, o) { + if (e != r) throw new Error(o || 'Assertion failed: ' + e + ' != ' + r); + }; + }); + vs = T2((mT, jb) => { + var X7 = ar(); + function mr(t) { + (this.options = t), (this.type = this.options.type), (this.blockSize = 8), this._init(), (this.buffer = new Array(this.blockSize)), (this.bufferOff = 0); + } + jb.exports = mr; + mr.prototype._init = function () {}; + mr.prototype.update = function (e) { + return e.length === 0 ? [] : this.type === 'decrypt' ? this._updateDecrypt(e) : this._updateEncrypt(e); + }; + mr.prototype._buffer = function (e, r) { + for (var o = Math.min(this.buffer.length - this.bufferOff, e.length - r), f = 0; f < o; f++) this.buffer[this.bufferOff + f] = e[r + f]; + return (this.bufferOff += o), o; + }; + mr.prototype._flushBuffer = function (e, r) { + return this._update(this.buffer, 0, e, r), (this.bufferOff = 0), this.blockSize; + }; + mr.prototype._updateEncrypt = function (e) { + var r = 0, + o = 0, + f = ((this.bufferOff + e.length) / this.blockSize) | 0, + p = new Array(f * this.blockSize); + this.bufferOff !== 0 && ((r += this._buffer(e, r)), this.bufferOff === this.buffer.length && (o += this._flushBuffer(p, o))); + for (var m2 = e.length - ((e.length - r) % this.blockSize); r < m2; r += this.blockSize) this._update(e, r, p, o), (o += this.blockSize); + for (; r < e.length; r++, this.bufferOff++) this.buffer[this.bufferOff] = e[r]; + return p; + }; + mr.prototype._updateDecrypt = function (e) { + for (var r = 0, o = 0, f = Math.ceil((this.bufferOff + e.length) / this.blockSize) - 1, p = new Array(f * this.blockSize); f > 0; f--) (r += this._buffer(e, r)), (o += this._flushBuffer(p, o)); + return (r += this._buffer(e, r)), p; + }; + mr.prototype.final = function (e) { + var r; + e && (r = this.update(e)); + var o; + return this.type === 'encrypt' ? (o = this._finalEncrypt()) : (o = this._finalDecrypt()), r ? r.concat(o) : o; + }; + mr.prototype._pad = function (e, r) { + if (r === 0) return false; + for (; r < e.length; ) e[r++] = 0; + return true; + }; + mr.prototype._finalEncrypt = function () { + if (!this._pad(this.buffer, this.bufferOff)) return []; + var e = new Array(this.blockSize); + return this._update(this.buffer, 0, e, 0), e; + }; + mr.prototype._unpad = function (e) { + return e; + }; + mr.prototype._finalDecrypt = function () { + X7.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt'); + var e = new Array(this.blockSize); + return this._flushBuffer(e, 0), this._unpad(e); + }; + }); + ku = T2((gT, $b) => { + var Zb = ar(), + J7 = Ie(), + Nt = Tu(), + Vb = vs(); + function Q7() { + (this.tmp = new Array(2)), (this.keys = null); + } + function ei(t) { + Vb.call(this, t); + var e = new Q7(); + (this._desState = e), this.deriveKeys(e, t.key); + } + J7(ei, Vb); + $b.exports = ei; + ei.create = function (e) { + return new ei(e); + }; + var e9 = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]; + ei.prototype.deriveKeys = function (e, r) { + (e.keys = new Array(16 * 2)), Zb.equal(r.length, this.blockSize, 'Invalid key length'); + var o = Nt.readUInt32BE(r, 0), + f = Nt.readUInt32BE(r, 4); + Nt.pc1(o, f, e.tmp, 0), (o = e.tmp[0]), (f = e.tmp[1]); + for (var p = 0; p < e.keys.length; p += 2) { + var m2 = e9[p >>> 1]; + (o = Nt.r28shl(o, m2)), (f = Nt.r28shl(f, m2)), Nt.pc2(o, f, e.keys, p); + } + }; + ei.prototype._update = function (e, r, o, f) { + var p = this._desState, + m2 = Nt.readUInt32BE(e, r), + y2 = Nt.readUInt32BE(e, r + 4); + Nt.ip(m2, y2, p.tmp, 0), + (m2 = p.tmp[0]), + (y2 = p.tmp[1]), + this.type === 'encrypt' ? this._encrypt(p, m2, y2, p.tmp, 0) : this._decrypt(p, m2, y2, p.tmp, 0), + (m2 = p.tmp[0]), + (y2 = p.tmp[1]), + Nt.writeUInt32BE(o, m2, f), + Nt.writeUInt32BE(o, y2, f + 4); + }; + ei.prototype._pad = function (e, r) { + for (var o = e.length - r, f = r; f < e.length; f++) e[f] = o; + return true; + }; + ei.prototype._unpad = function (e) { + for (var r = e[e.length - 1], o = e.length - r; o < e.length; o++) Zb.equal(e[o], r); + return e.slice(0, e.length - r); + }; + ei.prototype._encrypt = function (e, r, o, f, p) { + for (var m2 = r, y2 = o, M = 0; M < e.keys.length; M += 2) { + var x = e.keys[M], + S = e.keys[M + 1]; + Nt.expand(y2, e.tmp, 0), (x ^= e.tmp[0]), (S ^= e.tmp[1]); + var E2 = Nt.substitute(x, S), + B = Nt.permute(E2), + q2 = y2; + (y2 = (m2 ^ B) >>> 0), (m2 = q2); + } + Nt.rip(y2, m2, f, p); + }; + ei.prototype._decrypt = function (e, r, o, f, p) { + for (var m2 = o, y2 = r, M = e.keys.length - 2; M >= 0; M -= 2) { + var x = e.keys[M], + S = e.keys[M + 1]; + Nt.expand(m2, e.tmp, 0), (x ^= e.tmp[0]), (S ^= e.tmp[1]); + var E2 = Nt.substitute(x, S), + B = Nt.permute(E2), + q2 = m2; + (m2 = (y2 ^ B) >>> 0), (y2 = q2); + } + Nt.rip(m2, y2, f, p); + }; + }); + Yb = T2(Gb => { + var t9 = ar(), + r9 = Ie(), + bs = {}; + function i9(t) { + t9.equal(t.length, 8, 'Invalid IV length'), (this.iv = new Array(8)); + for (var e = 0; e < this.iv.length; e++) this.iv[e] = t[e]; + } + function n9(t) { + function e(p) { + t.call(this, p), this._cbcInit(); + } + r9(e, t); + for (var r = Object.keys(bs), o = 0; o < r.length; o++) { + var f = r[o]; + e.prototype[f] = bs[f]; + } + return ( + (e.create = function (m2) { + return new e(m2); + }), + e + ); + } + Gb.instantiate = n9; + bs._cbcInit = function () { + var e = new i9(this.options.iv); + this._cbcState = e; + }; + bs._update = function (e, r, o, f) { + var p = this._cbcState, + m2 = this.constructor.super_.prototype, + y2 = p.iv; + if (this.type === 'encrypt') { + for (var M = 0; M < this.blockSize; M++) y2[M] ^= e[r + M]; + m2._update.call(this, y2, 0, o, f); + for (var M = 0; M < this.blockSize; M++) y2[M] = o[f + M]; + } else { + m2._update.call(this, e, r, o, f); + for (var M = 0; M < this.blockSize; M++) o[f + M] ^= y2[M]; + for (var M = 0; M < this.blockSize; M++) y2[M] = e[r + M]; + } + }; + }); + Qb = T2((wT, Jb) => { + var f9 = ar(), + a9 = Ie(), + Xb = vs(), + Wi = ku(); + function o9(t, e) { + f9.equal(e.length, 24, 'Invalid key length'); + var r = e.slice(0, 8), + o = e.slice(8, 16), + f = e.slice(16, 24); + t === 'encrypt' + ? (this.ciphers = [Wi.create({type: 'encrypt', key: r}), Wi.create({type: 'decrypt', key: o}), Wi.create({type: 'encrypt', key: f})]) + : (this.ciphers = [Wi.create({type: 'decrypt', key: f}), Wi.create({type: 'encrypt', key: o}), Wi.create({type: 'decrypt', key: r})]); + } + function An(t) { + Xb.call(this, t); + var e = new o9(this.type, this.options.key); + this._edeState = e; + } + a9(An, Xb); + Jb.exports = An; + An.create = function (e) { + return new An(e); + }; + An.prototype._update = function (e, r, o, f) { + var p = this._edeState; + p.ciphers[0]._update(e, r, o, f), p.ciphers[1]._update(o, f, o, f), p.ciphers[2]._update(o, f, o, f); + }; + An.prototype._pad = Wi.prototype._pad; + An.prototype._unpad = Wi.prototype._unpad; + }); + em = T2(gf => { + gf.utils = Tu(); + gf.Cipher = vs(); + gf.DES = ku(); + gf.CBC = Yb(); + gf.EDE = Qb(); + }); + im = T2((_T, rm) => { + var tm = yi(), + wi = em(), + s9 = Ie(), + Rn = Te().Buffer, + Sa = {'des-ede3-cbc': wi.CBC.instantiate(wi.EDE), 'des-ede3': wi.EDE, 'des-ede-cbc': wi.CBC.instantiate(wi.EDE), 'des-ede': wi.EDE, 'des-cbc': wi.CBC.instantiate(wi.DES), 'des-ecb': wi.DES}; + Sa.des = Sa['des-cbc']; + Sa.des3 = Sa['des-ede3-cbc']; + rm.exports = ms; + s9(ms, tm); + function ms(t) { + tm.call(this); + var e = t.mode.toLowerCase(), + r = Sa[e], + o; + t.decrypt ? (o = 'decrypt') : (o = 'encrypt'); + var f = t.key; + Rn.isBuffer(f) || (f = Rn.from(f)), (e === 'des-ede' || e === 'des-ede-cbc') && (f = Rn.concat([f, f.slice(0, 8)])); + var p = t.iv; + Rn.isBuffer(p) || (p = Rn.from(p)), (this._des = r.create({key: f, iv: p, type: o})); + } + ms.prototype._update = function (t) { + return Rn.from(this._des.update(t)); + }; + ms.prototype._final = function () { + return Rn.from(this._des.final()); + }; + }); + nm = T2(Lu => { + Lu.encrypt = function (t, e) { + return t._cipher.encryptBlock(e); + }; + Lu.decrypt = function (t, e) { + return t._cipher.decryptBlock(e); + }; + }); + yf = T2((ST, fm) => { + fm.exports = function (e, r) { + for (var o = Math.min(e.length, r.length), f = new Buffer(o), p = 0; p < o; ++p) f[p] = e[p] ^ r[p]; + return f; + }; + }); + om = T2(Nu => { + var am = yf(); + Nu.encrypt = function (t, e) { + var r = am(e, t._prev); + return (t._prev = t._cipher.encryptBlock(r)), t._prev; + }; + Nu.decrypt = function (t, e) { + var r = t._prev; + t._prev = e; + var o = t._cipher.decryptBlock(e); + return am(o, r); + }; + }); + um = T2(hm => { + var Ea = Te().Buffer, + h9 = yf(); + function sm(t, e, r) { + var o = e.length, + f = h9(e, t._cache); + return (t._cache = t._cache.slice(o)), (t._prev = Ea.concat([t._prev, r ? e : f])), f; + } + hm.encrypt = function (t, e, r) { + for (var o = Ea.allocUnsafe(0), f; e.length; ) + if ((t._cache.length === 0 && ((t._cache = t._cipher.encryptBlock(t._prev)), (t._prev = Ea.allocUnsafe(0))), t._cache.length <= e.length)) (f = t._cache.length), (o = Ea.concat([o, sm(t, e.slice(0, f), r)])), (e = e.slice(f)); + else { + o = Ea.concat([o, sm(t, e, r)]); + break; + } + return o; + }; + }); + dm = T2(lm => { + var Du = Te().Buffer; + function u9(t, e, r) { + var o = t._cipher.encryptBlock(t._prev), + f = o[0] ^ e; + return (t._prev = Du.concat([t._prev.slice(1), Du.from([r ? e : f])])), f; + } + lm.encrypt = function (t, e, r) { + for (var o = e.length, f = Du.allocUnsafe(o), p = -1; ++p < o; ) f[p] = u9(t, e[p], r); + return f; + }; + }); + pm = T2(cm => { + var gs = Te().Buffer; + function l9(t, e, r) { + for (var o, f = -1, p = 8, m2 = 0, y2, M; ++f < p; ) (o = t._cipher.encryptBlock(t._prev)), (y2 = e & (1 << (7 - f)) ? 128 : 0), (M = o[0] ^ y2), (m2 += (M & 128) >> f % 8), (t._prev = d9(t._prev, r ? y2 : M)); + return m2; + } + function d9(t, e) { + var r = t.length, + o = -1, + f = gs.allocUnsafe(t.length); + for (t = gs.concat([t, gs.from([e])]); ++o < r; ) f[o] = (t[o] << 1) | (t[o + 1] >> 7); + return f; + } + cm.encrypt = function (t, e, r) { + for (var o = e.length, f = gs.allocUnsafe(o), p = -1; ++p < o; ) f[p] = l9(t, e[p], r); + return f; + }; + }); + bm = T2(vm => { + var c9 = yf(); + function p9(t) { + return (t._prev = t._cipher.encryptBlock(t._prev)), t._prev; + } + vm.encrypt = function (t, e) { + for (; t._cache.length < e.length; ) t._cache = Buffer.concat([t._cache, p9(t)]); + var r = t._cache.slice(0, e.length); + return (t._cache = t._cache.slice(e.length)), c9(e, r); + }; + }); + Pu = T2((IT, mm) => { + function v9(t) { + for (var e = t.length, r; e--; ) + if (((r = t.readUInt8(e)), r === 255)) t.writeUInt8(0, e); + else { + r++, t.writeUInt8(r, e); + break; + } + } + mm.exports = v9; + }); + Ou = T2(ym => { + var b9 = yf(), + gm = Te().Buffer, + m9 = Pu(); + function g9(t) { + var e = t._cipher.encryptBlockRaw(t._prev); + return m9(t._prev), e; + } + var Cu = 16; + ym.encrypt = function (t, e) { + var r = Math.ceil(e.length / Cu), + o = t._cache.length; + t._cache = gm.concat([t._cache, gm.allocUnsafe(r * Cu)]); + for (var f = 0; f < r; f++) { + var p = g9(t), + m2 = o + f * Cu; + t._cache.writeUInt32BE(p[0], m2 + 0), t._cache.writeUInt32BE(p[1], m2 + 4), t._cache.writeUInt32BE(p[2], m2 + 8), t._cache.writeUInt32BE(p[3], m2 + 12); + } + var y2 = t._cache.slice(0, e.length); + return (t._cache = t._cache.slice(e.length)), b9(e, y2); + }; + }); + Fu = T2((kT, y9) => { + y9.exports = { + 'aes-128-ecb': {cipher: 'AES', key: 128, iv: 0, mode: 'ECB', type: 'block'}, + 'aes-192-ecb': {cipher: 'AES', key: 192, iv: 0, mode: 'ECB', type: 'block'}, + 'aes-256-ecb': {cipher: 'AES', key: 256, iv: 0, mode: 'ECB', type: 'block'}, + 'aes-128-cbc': {cipher: 'AES', key: 128, iv: 16, mode: 'CBC', type: 'block'}, + 'aes-192-cbc': {cipher: 'AES', key: 192, iv: 16, mode: 'CBC', type: 'block'}, + 'aes-256-cbc': {cipher: 'AES', key: 256, iv: 16, mode: 'CBC', type: 'block'}, + aes128: {cipher: 'AES', key: 128, iv: 16, mode: 'CBC', type: 'block'}, + aes192: {cipher: 'AES', key: 192, iv: 16, mode: 'CBC', type: 'block'}, + aes256: {cipher: 'AES', key: 256, iv: 16, mode: 'CBC', type: 'block'}, + 'aes-128-cfb': {cipher: 'AES', key: 128, iv: 16, mode: 'CFB', type: 'stream'}, + 'aes-192-cfb': {cipher: 'AES', key: 192, iv: 16, mode: 'CFB', type: 'stream'}, + 'aes-256-cfb': {cipher: 'AES', key: 256, iv: 16, mode: 'CFB', type: 'stream'}, + 'aes-128-cfb8': {cipher: 'AES', key: 128, iv: 16, mode: 'CFB8', type: 'stream'}, + 'aes-192-cfb8': {cipher: 'AES', key: 192, iv: 16, mode: 'CFB8', type: 'stream'}, + 'aes-256-cfb8': {cipher: 'AES', key: 256, iv: 16, mode: 'CFB8', type: 'stream'}, + 'aes-128-cfb1': {cipher: 'AES', key: 128, iv: 16, mode: 'CFB1', type: 'stream'}, + 'aes-192-cfb1': {cipher: 'AES', key: 192, iv: 16, mode: 'CFB1', type: 'stream'}, + 'aes-256-cfb1': {cipher: 'AES', key: 256, iv: 16, mode: 'CFB1', type: 'stream'}, + 'aes-128-ofb': {cipher: 'AES', key: 128, iv: 16, mode: 'OFB', type: 'stream'}, + 'aes-192-ofb': {cipher: 'AES', key: 192, iv: 16, mode: 'OFB', type: 'stream'}, + 'aes-256-ofb': {cipher: 'AES', key: 256, iv: 16, mode: 'OFB', type: 'stream'}, + 'aes-128-ctr': {cipher: 'AES', key: 128, iv: 16, mode: 'CTR', type: 'stream'}, + 'aes-192-ctr': {cipher: 'AES', key: 192, iv: 16, mode: 'CTR', type: 'stream'}, + 'aes-256-ctr': {cipher: 'AES', key: 256, iv: 16, mode: 'CTR', type: 'stream'}, + 'aes-128-gcm': {cipher: 'AES', key: 128, iv: 12, mode: 'GCM', type: 'auth'}, + 'aes-192-gcm': {cipher: 'AES', key: 192, iv: 12, mode: 'GCM', type: 'auth'}, + 'aes-256-gcm': {cipher: 'AES', key: 256, iv: 12, mode: 'GCM', type: 'auth'} + }; + }); + ws = T2((LT, wm) => { + var w9 = {ECB: nm(), CBC: om(), CFB: um(), CFB8: dm(), CFB1: pm(), OFB: bm(), CTR: Ou(), GCM: Ou()}, + ys = Fu(); + for (Uu in ys) ys[Uu].module = w9[ys[Uu].mode]; + var Uu; + wm.exports = ys; + }); + Aa = T2((NT, _m) => { + var Ms = Te().Buffer; + function Hu(t) { + Ms.isBuffer(t) || (t = Ms.from(t)); + for (var e = (t.length / 4) | 0, r = new Array(e), o = 0; o < e; o++) r[o] = t.readUInt32BE(o * 4); + return r; + } + function zu(t) { + for (var e = 0; e < t.length; t++) t[e] = 0; + } + function Mm(t, e, r, o, f) { + for (var p = r[0], m2 = r[1], y2 = r[2], M = r[3], x = t[0] ^ e[0], S = t[1] ^ e[1], E2 = t[2] ^ e[2], B = t[3] ^ e[3], q2, L2, ge, _e, N = 4, we = 1; we < f; we++) + (q2 = p[x >>> 24] ^ m2[(S >>> 16) & 255] ^ y2[(E2 >>> 8) & 255] ^ M[B & 255] ^ e[N++]), + (L2 = p[S >>> 24] ^ m2[(E2 >>> 16) & 255] ^ y2[(B >>> 8) & 255] ^ M[x & 255] ^ e[N++]), + (ge = p[E2 >>> 24] ^ m2[(B >>> 16) & 255] ^ y2[(x >>> 8) & 255] ^ M[S & 255] ^ e[N++]), + (_e = p[B >>> 24] ^ m2[(x >>> 16) & 255] ^ y2[(S >>> 8) & 255] ^ M[E2 & 255] ^ e[N++]), + (x = q2), + (S = L2), + (E2 = ge), + (B = _e); + return ( + (q2 = ((o[x >>> 24] << 24) | (o[(S >>> 16) & 255] << 16) | (o[(E2 >>> 8) & 255] << 8) | o[B & 255]) ^ e[N++]), + (L2 = ((o[S >>> 24] << 24) | (o[(E2 >>> 16) & 255] << 16) | (o[(B >>> 8) & 255] << 8) | o[x & 255]) ^ e[N++]), + (ge = ((o[E2 >>> 24] << 24) | (o[(B >>> 16) & 255] << 16) | (o[(x >>> 8) & 255] << 8) | o[S & 255]) ^ e[N++]), + (_e = ((o[B >>> 24] << 24) | (o[(x >>> 16) & 255] << 16) | (o[(S >>> 8) & 255] << 8) | o[E2 & 255]) ^ e[N++]), + (q2 = q2 >>> 0), + (L2 = L2 >>> 0), + (ge = ge >>> 0), + (_e = _e >>> 0), + [q2, L2, ge, _e] + ); + } + var M9 = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54], + kt = (function () { + for (var t = new Array(256), e = 0; e < 256; e++) e < 128 ? (t[e] = e << 1) : (t[e] = (e << 1) ^ 283); + for (var r = [], o = [], f = [[], [], [], []], p = [[], [], [], []], m2 = 0, y2 = 0, M = 0; M < 256; ++M) { + var x = y2 ^ (y2 << 1) ^ (y2 << 2) ^ (y2 << 3) ^ (y2 << 4); + (x = (x >>> 8) ^ (x & 255) ^ 99), (r[m2] = x), (o[x] = m2); + var S = t[m2], + E2 = t[S], + B = t[E2], + q2 = (t[x] * 257) ^ (x * 16843008); + (f[0][m2] = (q2 << 24) | (q2 >>> 8)), + (f[1][m2] = (q2 << 16) | (q2 >>> 16)), + (f[2][m2] = (q2 << 8) | (q2 >>> 24)), + (f[3][m2] = q2), + (q2 = (B * 16843009) ^ (E2 * 65537) ^ (S * 257) ^ (m2 * 16843008)), + (p[0][x] = (q2 << 24) | (q2 >>> 8)), + (p[1][x] = (q2 << 16) | (q2 >>> 16)), + (p[2][x] = (q2 << 8) | (q2 >>> 24)), + (p[3][x] = q2), + m2 === 0 ? (m2 = y2 = 1) : ((m2 = S ^ t[t[t[B ^ S]]]), (y2 ^= t[t[y2]])); + } + return {SBOX: r, INV_SBOX: o, SUB_MIX: f, INV_SUB_MIX: p}; + })(); + function gr(t) { + (this._key = Hu(t)), this._reset(); + } + gr.blockSize = 4 * 4; + gr.keySize = 256 / 8; + gr.prototype.blockSize = gr.blockSize; + gr.prototype.keySize = gr.keySize; + gr.prototype._reset = function () { + for (var t = this._key, e = t.length, r = e + 6, o = (r + 1) * 4, f = [], p = 0; p < e; p++) f[p] = t[p]; + for (p = e; p < o; p++) { + var m2 = f[p - 1]; + p % e === 0 + ? ((m2 = (m2 << 8) | (m2 >>> 24)), (m2 = (kt.SBOX[m2 >>> 24] << 24) | (kt.SBOX[(m2 >>> 16) & 255] << 16) | (kt.SBOX[(m2 >>> 8) & 255] << 8) | kt.SBOX[m2 & 255]), (m2 ^= M9[(p / e) | 0] << 24)) + : e > 6 && p % e === 4 && (m2 = (kt.SBOX[m2 >>> 24] << 24) | (kt.SBOX[(m2 >>> 16) & 255] << 16) | (kt.SBOX[(m2 >>> 8) & 255] << 8) | kt.SBOX[m2 & 255]), + (f[p] = f[p - e] ^ m2); + } + for (var y2 = [], M = 0; M < o; M++) { + var x = o - M, + S = f[x - (M % 4 ? 0 : 4)]; + M < 4 || x <= 4 ? (y2[M] = S) : (y2[M] = kt.INV_SUB_MIX[0][kt.SBOX[S >>> 24]] ^ kt.INV_SUB_MIX[1][kt.SBOX[(S >>> 16) & 255]] ^ kt.INV_SUB_MIX[2][kt.SBOX[(S >>> 8) & 255]] ^ kt.INV_SUB_MIX[3][kt.SBOX[S & 255]]); + } + (this._nRounds = r), (this._keySchedule = f), (this._invKeySchedule = y2); + }; + gr.prototype.encryptBlockRaw = function (t) { + return (t = Hu(t)), Mm(t, this._keySchedule, kt.SUB_MIX, kt.SBOX, this._nRounds); + }; + gr.prototype.encryptBlock = function (t) { + var e = this.encryptBlockRaw(t), + r = Ms.allocUnsafe(16); + return r.writeUInt32BE(e[0], 0), r.writeUInt32BE(e[1], 4), r.writeUInt32BE(e[2], 8), r.writeUInt32BE(e[3], 12), r; + }; + gr.prototype.decryptBlock = function (t) { + t = Hu(t); + var e = t[1]; + (t[1] = t[3]), (t[3] = e); + var r = Mm(t, this._invKeySchedule, kt.INV_SUB_MIX, kt.INV_SBOX, this._nRounds), + o = Ms.allocUnsafe(16); + return o.writeUInt32BE(r[0], 0), o.writeUInt32BE(r[3], 4), o.writeUInt32BE(r[2], 8), o.writeUInt32BE(r[1], 12), o; + }; + gr.prototype.scrub = function () { + zu(this._keySchedule), zu(this._invKeySchedule), zu(this._key); + }; + _m.exports.AES = gr; + }); + Em = T2((DT, Sm) => { + var wf = Te().Buffer, + _9 = wf.alloc(16, 0); + function x9(t) { + return [t.readUInt32BE(0), t.readUInt32BE(4), t.readUInt32BE(8), t.readUInt32BE(12)]; + } + function xm(t) { + var e = wf.allocUnsafe(16); + return e.writeUInt32BE(t[0] >>> 0, 0), e.writeUInt32BE(t[1] >>> 0, 4), e.writeUInt32BE(t[2] >>> 0, 8), e.writeUInt32BE(t[3] >>> 0, 12), e; + } + function Ra(t) { + (this.h = t), (this.state = wf.alloc(16, 0)), (this.cache = wf.allocUnsafe(0)); + } + Ra.prototype.ghash = function (t) { + for (var e = -1; ++e < t.length; ) this.state[e] ^= t[e]; + this._multiply(); + }; + Ra.prototype._multiply = function () { + for (var t = x9(this.h), e = [0, 0, 0, 0], r, o, f, p = -1; ++p < 128; ) { + for (o = (this.state[~~(p / 8)] & (1 << (7 - (p % 8)))) !== 0, o && ((e[0] ^= t[0]), (e[1] ^= t[1]), (e[2] ^= t[2]), (e[3] ^= t[3])), f = (t[3] & 1) !== 0, r = 3; r > 0; r--) t[r] = (t[r] >>> 1) | ((t[r - 1] & 1) << 31); + (t[0] = t[0] >>> 1), f && (t[0] = t[0] ^ (225 << 24)); + } + this.state = xm(e); + }; + Ra.prototype.update = function (t) { + this.cache = wf.concat([this.cache, t]); + for (var e; this.cache.length >= 16; ) (e = this.cache.slice(0, 16)), (this.cache = this.cache.slice(16)), this.ghash(e); + }; + Ra.prototype.final = function (t, e) { + return this.cache.length && this.ghash(wf.concat([this.cache, _9], 16)), this.ghash(xm([0, t, 0, e])), this.state; + }; + Sm.exports = Ra; + }); + Wu = T2((PT, Bm) => { + var S9 = Aa(), + rr = Te().Buffer, + Am = yi(), + E9 = Ie(), + Rm = Em(), + A9 = yf(), + R9 = Pu(); + function B9(t, e) { + var r = 0; + t.length !== e.length && r++; + for (var o = Math.min(t.length, e.length), f = 0; f < o; ++f) r += t[f] ^ e[f]; + return r; + } + function q9(t, e, r) { + if (e.length === 12) return (t._finID = rr.concat([e, rr.from([0, 0, 0, 1])])), rr.concat([e, rr.from([0, 0, 0, 2])]); + var o = new Rm(r), + f = e.length, + p = f % 16; + o.update(e), p && ((p = 16 - p), o.update(rr.alloc(p, 0))), o.update(rr.alloc(8, 0)); + var m2 = f * 8, + y2 = rr.alloc(8); + y2.writeUIntBE(m2, 0, 8), o.update(y2), (t._finID = o.state); + var M = rr.from(t._finID); + return R9(M), M; + } + function Bn(t, e, r, o) { + Am.call(this); + var f = rr.alloc(4, 0); + this._cipher = new S9.AES(e); + var p = this._cipher.encryptBlock(f); + (this._ghash = new Rm(p)), + (r = q9(this, r, p)), + (this._prev = rr.from(r)), + (this._cache = rr.allocUnsafe(0)), + (this._secCache = rr.allocUnsafe(0)), + (this._decrypt = o), + (this._alen = 0), + (this._len = 0), + (this._mode = t), + (this._authTag = null), + (this._called = false); + } + E9(Bn, Am); + Bn.prototype._update = function (t) { + if (!this._called && this._alen) { + var e = 16 - (this._alen % 16); + e < 16 && ((e = rr.alloc(e, 0)), this._ghash.update(e)); + } + this._called = true; + var r = this._mode.encrypt(this, t); + return this._decrypt ? this._ghash.update(t) : this._ghash.update(r), (this._len += t.length), r; + }; + Bn.prototype._final = function () { + if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data'); + var t = A9(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)); + if (this._decrypt && B9(t, this._authTag)) throw new Error('Unsupported state or unable to authenticate data'); + (this._authTag = t), this._cipher.scrub(); + }; + Bn.prototype.getAuthTag = function () { + if (this._decrypt || !rr.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state'); + return this._authTag; + }; + Bn.prototype.setAuthTag = function (e) { + if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state'); + this._authTag = e; + }; + Bn.prototype.setAAD = function (e) { + if (this._called) throw new Error('Attempting to set AAD in unsupported state'); + this._ghash.update(e), (this._alen += e.length); + }; + Bm.exports = Bn; + }); + ju = T2((CT, Im) => { + var I9 = Aa(), + Ku = Te().Buffer, + qm = yi(), + T9 = Ie(); + function _s(t, e, r, o) { + qm.call(this), (this._cipher = new I9.AES(e)), (this._prev = Ku.from(r)), (this._cache = Ku.allocUnsafe(0)), (this._secCache = Ku.allocUnsafe(0)), (this._decrypt = o), (this._mode = t); + } + T9(_s, qm); + _s.prototype._update = function (t) { + return this._mode.encrypt(this, t, this._decrypt); + }; + _s.prototype._final = function () { + this._cipher.scrub(); + }; + Im.exports = _s; + }); + Ba = T2((OT, Tm) => { + var qn = Te().Buffer, + k9 = Ao(); + function L9(t, e, r, o) { + if ((qn.isBuffer(t) || (t = qn.from(t, 'binary')), e && (qn.isBuffer(e) || (e = qn.from(e, 'binary')), e.length !== 8))) throw new RangeError('salt should be Buffer with 8 byte length'); + for (var f = r / 8, p = qn.alloc(f), m2 = qn.alloc(o || 0), y2 = qn.alloc(0); f > 0 || o > 0; ) { + var M = new k9(); + M.update(y2), M.update(t), e && M.update(e), (y2 = M.digest()); + var x = 0; + if (f > 0) { + var S = p.length - f; + (x = Math.min(f, y2.length)), y2.copy(p, S, 0, x), (f -= x); + } + if (x < y2.length && o > 0) { + var E2 = m2.length - o, + B = Math.min(o, y2.length - x); + y2.copy(m2, E2, x, x + B), (o -= B); + } + } + return y2.fill(0), {key: p, iv: m2}; + } + Tm.exports = L9; + }); + Dm = T2(Zu => { + var km = ws(), + N9 = Wu(), + Mi = Te().Buffer, + D9 = ju(), + Lm = yi(), + P9 = Aa(), + C9 = Ba(), + O9 = Ie(); + function qa(t, e, r) { + Lm.call(this), (this._cache = new xs()), (this._cipher = new P9.AES(e)), (this._prev = Mi.from(r)), (this._mode = t), (this._autopadding = true); + } + O9(qa, Lm); + qa.prototype._update = function (t) { + this._cache.add(t); + for (var e, r, o = []; (e = this._cache.get()); ) (r = this._mode.encrypt(this, e)), o.push(r); + return Mi.concat(o); + }; + var F9 = Mi.alloc(16, 16); + qa.prototype._final = function () { + var t = this._cache.flush(); + if (this._autopadding) return (t = this._mode.encrypt(this, t)), this._cipher.scrub(), t; + if (!t.equals(F9)) throw (this._cipher.scrub(), new Error('data not multiple of block length')); + }; + qa.prototype.setAutoPadding = function (t) { + return (this._autopadding = !!t), this; + }; + function xs() { + this.cache = Mi.allocUnsafe(0); + } + xs.prototype.add = function (t) { + this.cache = Mi.concat([this.cache, t]); + }; + xs.prototype.get = function () { + if (this.cache.length > 15) { + var t = this.cache.slice(0, 16); + return (this.cache = this.cache.slice(16)), t; + } + return null; + }; + xs.prototype.flush = function () { + for (var t = 16 - this.cache.length, e = Mi.allocUnsafe(t), r = -1; ++r < t; ) e.writeUInt8(t, r); + return Mi.concat([this.cache, e]); + }; + function Nm(t, e, r) { + var o = km[t.toLowerCase()]; + if (!o) throw new TypeError('invalid suite type'); + if ((typeof e == 'string' && (e = Mi.from(e)), e.length !== o.key / 8)) throw new TypeError('invalid key length ' + e.length); + if ((typeof r == 'string' && (r = Mi.from(r)), o.mode !== 'GCM' && r.length !== o.iv)) throw new TypeError('invalid iv length ' + r.length); + return o.type === 'stream' ? new D9(o.module, e, r) : o.type === 'auth' ? new N9(o.module, e, r) : new qa(o.module, e, r); + } + function U9(t, e) { + var r = km[t.toLowerCase()]; + if (!r) throw new TypeError('invalid suite type'); + var o = C9(e, false, r.key, r.iv); + return Nm(t, o.key, o.iv); + } + Zu.createCipheriv = Nm; + Zu.createCipher = U9; + }); + Fm = T2(Vu => { + var z9 = Wu(), + Mf = Te().Buffer, + Pm = ws(), + H9 = ju(), + Cm = yi(), + W9 = Aa(), + K9 = Ba(), + j9 = Ie(); + function Ia(t, e, r) { + Cm.call(this), (this._cache = new Ss()), (this._last = undefined), (this._cipher = new W9.AES(e)), (this._prev = Mf.from(r)), (this._mode = t), (this._autopadding = true); + } + j9(Ia, Cm); + Ia.prototype._update = function (t) { + this._cache.add(t); + for (var e, r, o = []; (e = this._cache.get(this._autopadding)); ) (r = this._mode.decrypt(this, e)), o.push(r); + return Mf.concat(o); + }; + Ia.prototype._final = function () { + var t = this._cache.flush(); + if (this._autopadding) return Z9(this._mode.decrypt(this, t)); + if (t) throw new Error('data not multiple of block length'); + }; + Ia.prototype.setAutoPadding = function (t) { + return (this._autopadding = !!t), this; + }; + function Ss() { + this.cache = Mf.allocUnsafe(0); + } + Ss.prototype.add = function (t) { + this.cache = Mf.concat([this.cache, t]); + }; + Ss.prototype.get = function (t) { + var e; + if (t) { + if (this.cache.length > 16) return (e = this.cache.slice(0, 16)), (this.cache = this.cache.slice(16)), e; + } else if (this.cache.length >= 16) return (e = this.cache.slice(0, 16)), (this.cache = this.cache.slice(16)), e; + return null; + }; + Ss.prototype.flush = function () { + if (this.cache.length) return this.cache; + }; + function Z9(t) { + var e = t[15]; + if (e < 1 || e > 16) throw new Error('unable to decrypt data'); + for (var r = -1; ++r < e; ) if (t[r + (16 - e)] !== e) throw new Error('unable to decrypt data'); + if (e !== 16) return t.slice(0, 16 - e); + } + function Om(t, e, r) { + var o = Pm[t.toLowerCase()]; + if (!o) throw new TypeError('invalid suite type'); + if ((typeof r == 'string' && (r = Mf.from(r)), o.mode !== 'GCM' && r.length !== o.iv)) throw new TypeError('invalid iv length ' + r.length); + if ((typeof e == 'string' && (e = Mf.from(e)), e.length !== o.key / 8)) throw new TypeError('invalid key length ' + e.length); + return o.type === 'stream' ? new H9(o.module, e, r, true) : o.type === 'auth' ? new z9(o.module, e, r, true) : new Ia(o.module, e, r); + } + function V9(t, e) { + var r = Pm[t.toLowerCase()]; + if (!r) throw new TypeError('invalid suite type'); + var o = K9(e, false, r.key, r.iv); + return Om(t, o.key, o.iv); + } + Vu.createDecipher = V9; + Vu.createDecipheriv = Om; + }); + Es = T2(Nr => { + var Um = Dm(), + zm = Fm(), + $9 = Fu(); + function G9() { + return Object.keys($9); + } + Nr.createCipher = Nr.Cipher = Um.createCipher; + Nr.createCipheriv = Nr.Cipheriv = Um.createCipheriv; + Nr.createDecipher = Nr.Decipher = zm.createDecipher; + Nr.createDecipheriv = Nr.Decipheriv = zm.createDecipheriv; + Nr.listCiphers = Nr.getCiphers = G9; + }); + Hm = T2(_i => { + _i['des-ecb'] = {key: 8, iv: 0}; + _i['des-cbc'] = _i.des = {key: 8, iv: 8}; + _i['des-ede3-cbc'] = _i.des3 = {key: 24, iv: 8}; + _i['des-ede3'] = {key: 24, iv: 0}; + _i['des-ede-cbc'] = {key: 16, iv: 8}; + _i['des-ede'] = {key: 16, iv: 0}; + }); + Vm = T2(Dr => { + var Wm = im(), + $u = Es(), + Ki = ws(), + xi = Hm(), + Km = Ba(); + function Y9(t, e) { + t = t.toLowerCase(); + var r, o; + if (Ki[t]) (r = Ki[t].key), (o = Ki[t].iv); + else if (xi[t]) (r = xi[t].key * 8), (o = xi[t].iv); + else throw new TypeError('invalid suite type'); + var f = Km(e, false, r, o); + return jm(t, f.key, f.iv); + } + function X9(t, e) { + t = t.toLowerCase(); + var r, o; + if (Ki[t]) (r = Ki[t].key), (o = Ki[t].iv); + else if (xi[t]) (r = xi[t].key * 8), (o = xi[t].iv); + else throw new TypeError('invalid suite type'); + var f = Km(e, false, r, o); + return Zm(t, f.key, f.iv); + } + function jm(t, e, r) { + if (((t = t.toLowerCase()), Ki[t])) return $u.createCipheriv(t, e, r); + if (xi[t]) return new Wm({key: e, iv: r, mode: t}); + throw new TypeError('invalid suite type'); + } + function Zm(t, e, r) { + if (((t = t.toLowerCase()), Ki[t])) return $u.createDecipheriv(t, e, r); + if (xi[t]) return new Wm({key: e, iv: r, mode: t, decrypt: true}); + throw new TypeError('invalid suite type'); + } + function J9() { + return Object.keys(xi).concat($u.getCiphers()); + } + Dr.createCipher = Dr.Cipher = Y9; + Dr.createCipheriv = Dr.Cipheriv = jm; + Dr.createDecipher = Dr.Decipher = X9; + Dr.createDecipheriv = Dr.Decipheriv = Zm; + Dr.listCiphers = Dr.getCiphers = J9; + }); + ji = T2(() => {}); + Yu = T2(($m, Gu) => { + (function (t, e) { + function r(v, i) { + if (!v) throw new Error(i || 'Assertion failed'); + } + function o(v, i) { + v.super_ = i; + var a = function () {}; + (a.prototype = i.prototype), (v.prototype = new a()), (v.prototype.constructor = v); + } + function f(v, i, a) { + if (f.isBN(v)) return v; + (this.negative = 0), (this.words = null), (this.length = 0), (this.red = null), v !== null && ((i === 'le' || i === 'be') && ((a = i), (i = 10)), this._init(v || 0, i || 10, a || 'be')); + } + typeof t == 'object' ? (t.exports = f) : (e.BN = f), (f.BN = f), (f.wordSize = 26); + var p; + try { + typeof window < 'u' && typeof window.Buffer < 'u' ? (p = window.Buffer) : (p = ji().Buffer); + } catch {} + (f.isBN = function (i) { + return i instanceof f ? true : i !== null && typeof i == 'object' && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }), + (f.max = function (i, a) { + return i.cmp(a) > 0 ? i : a; + }), + (f.min = function (i, a) { + return i.cmp(a) < 0 ? i : a; + }), + (f.prototype._init = function (i, a, h2) { + if (typeof i == 'number') return this._initNumber(i, a, h2); + if (typeof i == 'object') return this._initArray(i, a, h2); + a === 'hex' && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), (i = i.toString().replace(/\s+/g, '')); + var s = 0; + i[0] === '-' && (s++, (this.negative = 1)), s < i.length && (a === 16 ? this._parseHex(i, s, h2) : (this._parseBase(i, a, s), h2 === 'le' && this._initArray(this.toArray(), a, h2))); + }), + (f.prototype._initNumber = function (i, a, h2) { + i < 0 && ((this.negative = 1), (i = -i)), + i < 67108864 + ? ((this.words = [i & 67108863]), (this.length = 1)) + : i < 4503599627370496 + ? ((this.words = [i & 67108863, (i / 67108864) & 67108863]), (this.length = 2)) + : (r(i < 9007199254740992), (this.words = [i & 67108863, (i / 67108864) & 67108863, 1]), (this.length = 3)), + h2 === 'le' && this._initArray(this.toArray(), a, h2); + }), + (f.prototype._initArray = function (i, a, h2) { + if ((r(typeof i.length == 'number'), i.length <= 0)) return (this.words = [0]), (this.length = 1), this; + (this.length = Math.ceil(i.length / 3)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u, + c, + b2 = 0; + if (h2 === 'be') + for (s = i.length - 1, u = 0; s >= 0; s -= 3) + (c = i[s] | (i[s - 1] << 8) | (i[s - 2] << 16)), (this.words[u] |= (c << b2) & 67108863), (this.words[u + 1] = (c >>> (26 - b2)) & 67108863), (b2 += 24), b2 >= 26 && ((b2 -= 26), u++); + else if (h2 === 'le') + for (s = 0, u = 0; s < i.length; s += 3) (c = i[s] | (i[s + 1] << 8) | (i[s + 2] << 16)), (this.words[u] |= (c << b2) & 67108863), (this.words[u + 1] = (c >>> (26 - b2)) & 67108863), (b2 += 24), b2 >= 26 && ((b2 -= 26), u++); + return this.strip(); + }); + function m2(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : (a - 48) & 15; + } + function y2(v, i, a) { + var h2 = m2(v, a); + return a - 1 >= i && (h2 |= m2(v, a - 1) << 4), h2; + } + f.prototype._parseHex = function (i, a, h2) { + (this.length = Math.ceil((i.length - a) / 6)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u = 0, + c = 0, + b2; + if (h2 === 'be') for (s = i.length - 1; s >= a; s -= 2) (b2 = y2(i, a, s) << u), (this.words[c] |= b2 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b2 >>> 26)) : (u += 8); + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a; s < i.length; s += 2) (b2 = y2(i, a, s) << u), (this.words[c] |= b2 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b2 >>> 26)) : (u += 8); + } + this.strip(); + }; + function M(v, i, a, h2) { + for (var s = 0, u = Math.min(v.length, a), c = i; c < u; c++) { + var b2 = v.charCodeAt(c) - 48; + (s *= h2), b2 >= 49 ? (s += b2 - 49 + 10) : b2 >= 17 ? (s += b2 - 17 + 10) : (s += b2); + } + return s; + } + (f.prototype._parseBase = function (i, a, h2) { + (this.words = [0]), (this.length = 1); + for (var s = 0, u = 1; u <= 67108863; u *= a) s++; + s--, (u = (u / a) | 0); + for (var c = i.length - h2, b2 = c % s, l = Math.min(c, c - b2) + h2, n = 0, d = h2; d < l; d += s) (n = M(i, d, d + s, a)), this.imuln(u), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + if (b2 !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0; d < b2; d++) w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + } + this.strip(); + }), + (f.prototype.copy = function (i) { + i.words = new Array(this.length); + for (var a = 0; a < this.length; a++) i.words[a] = this.words[a]; + (i.length = this.length), (i.negative = this.negative), (i.red = this.red); + }), + (f.prototype.clone = function () { + var i = new f(null); + return this.copy(i), i; + }), + (f.prototype._expand = function (i) { + for (; this.length < i; ) this.words[this.length++] = 0; + return this; + }), + (f.prototype.strip = function () { + for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; + return this._normSign(); + }), + (f.prototype._normSign = function () { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }), + (f.prototype.inspect = function () { + return (this.red ? ''; + }); + var x = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ], + S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + E2 = [ + 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, + 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + (f.prototype.toString = function (i, a) { + (i = i || 10), (a = a | 0 || 1); + var h2; + if (i === 16 || i === 'hex') { + h2 = ''; + for (var s = 0, u = 0, c = 0; c < this.length; c++) { + var b2 = this.words[c], + l = (((b2 << s) | u) & 16777215).toString(16); + (u = (b2 >>> (24 - s)) & 16777215), u !== 0 || c !== this.length - 1 ? (h2 = x[6 - l.length] + l + h2) : (h2 = l + h2), (s += 2), s >= 26 && ((s -= 26), c--); + } + for (u !== 0 && (h2 = u.toString(16) + h2); h2.length % a !== 0; ) h2 = '0' + h2; + return this.negative !== 0 && (h2 = '-' + h2), h2; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], + d = E2[i]; + h2 = ''; + var w = this.clone(); + for (w.negative = 0; !w.isZero(); ) { + var g = w.modn(d).toString(i); + (w = w.idivn(d)), w.isZero() ? (h2 = g + h2) : (h2 = x[n - g.length] + g + h2); + } + for (this.isZero() && (h2 = '0' + h2); h2.length % a !== 0; ) h2 = '0' + h2; + return this.negative !== 0 && (h2 = '-' + h2), h2; + } + r(false, 'Base should be between 2 and 36'); + }), + (f.prototype.toNumber = function () { + var i = this.words[0]; + return ( + this.length === 2 ? (i += this.words[1] * 67108864) : this.length === 3 && this.words[2] === 1 ? (i += 4503599627370496 + this.words[1] * 67108864) : this.length > 2 && r(false, 'Number can only safely store up to 53 bits'), + this.negative !== 0 ? -i : i + ); + }), + (f.prototype.toJSON = function () { + return this.toString(16); + }), + (f.prototype.toBuffer = function (i, a) { + return r(typeof p < 'u'), this.toArrayLike(p, i, a); + }), + (f.prototype.toArray = function (i, a) { + return this.toArrayLike(Array, i, a); + }), + (f.prototype.toArrayLike = function (i, a, h2) { + var s = this.byteLength(), + u = h2 || Math.max(1, s); + r(s <= u, 'byte array longer than desired length'), r(u > 0, 'Requested array length <= 0'), this.strip(); + var c = a === 'le', + b2 = new i(u), + l, + n, + d = this.clone(); + if (c) { + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b2[n] = l); + for (; n < u; n++) b2[n] = 0; + } else { + for (n = 0; n < u - s; n++) b2[n] = 0; + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b2[u - n - 1] = l); + } + return b2; + }), + Math.clz32 + ? (f.prototype._countBits = function (i) { + return 32 - Math.clz32(i); + }) + : (f.prototype._countBits = function (i) { + var a = i, + h2 = 0; + return a >= 4096 && ((h2 += 13), (a >>>= 13)), a >= 64 && ((h2 += 7), (a >>>= 7)), a >= 8 && ((h2 += 4), (a >>>= 4)), a >= 2 && ((h2 += 2), (a >>>= 2)), h2 + a; + }), + (f.prototype._zeroBits = function (i) { + if (i === 0) return 26; + var a = i, + h2 = 0; + return (a & 8191) === 0 && ((h2 += 13), (a >>>= 13)), (a & 127) === 0 && ((h2 += 7), (a >>>= 7)), (a & 15) === 0 && ((h2 += 4), (a >>>= 4)), (a & 3) === 0 && ((h2 += 2), (a >>>= 2)), (a & 1) === 0 && h2++, h2; + }), + (f.prototype.bitLength = function () { + var i = this.words[this.length - 1], + a = this._countBits(i); + return (this.length - 1) * 26 + a; + }); + function B(v) { + for (var i = new Array(v.bitLength()), a = 0; a < i.length; a++) { + var h2 = (a / 26) | 0, + s = a % 26; + i[a] = (v.words[h2] & (1 << s)) >>> s; + } + return i; + } + (f.prototype.zeroBits = function () { + if (this.isZero()) return 0; + for (var i = 0, a = 0; a < this.length; a++) { + var h2 = this._zeroBits(this.words[a]); + if (((i += h2), h2 !== 26)) break; + } + return i; + }), + (f.prototype.byteLength = function () { + return Math.ceil(this.bitLength() / 8); + }), + (f.prototype.toTwos = function (i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }), + (f.prototype.fromTwos = function (i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }), + (f.prototype.isNeg = function () { + return this.negative !== 0; + }), + (f.prototype.neg = function () { + return this.clone().ineg(); + }), + (f.prototype.ineg = function () { + return this.isZero() || (this.negative ^= 1), this; + }), + (f.prototype.iuor = function (i) { + for (; this.length < i.length; ) this.words[this.length++] = 0; + for (var a = 0; a < i.length; a++) this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }), + (f.prototype.ior = function (i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }), + (f.prototype.or = function (i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }), + (f.prototype.uor = function (i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }), + (f.prototype.iuand = function (i) { + var a; + this.length > i.length ? (a = i) : (a = this); + for (var h2 = 0; h2 < a.length; h2++) this.words[h2] = this.words[h2] & i.words[h2]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.iand = function (i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }), + (f.prototype.and = function (i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }), + (f.prototype.uand = function (i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }), + (f.prototype.iuxor = function (i) { + var a, h2; + this.length > i.length ? ((a = this), (h2 = i)) : ((a = i), (h2 = this)); + for (var s = 0; s < h2.length; s++) this.words[s] = a.words[s] ^ h2.words[s]; + if (this !== a) for (; s < a.length; s++) this.words[s] = a.words[s]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.ixor = function (i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }), + (f.prototype.xor = function (i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }), + (f.prototype.uxor = function (i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }), + (f.prototype.inotn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = Math.ceil(i / 26) | 0, + h2 = i % 26; + this._expand(a), h2 > 0 && a--; + for (var s = 0; s < a; s++) this.words[s] = ~this.words[s] & 67108863; + return h2 > 0 && (this.words[s] = ~this.words[s] & (67108863 >> (26 - h2))), this.strip(); + }), + (f.prototype.notn = function (i) { + return this.clone().inotn(i); + }), + (f.prototype.setn = function (i, a) { + r(typeof i == 'number' && i >= 0); + var h2 = (i / 26) | 0, + s = i % 26; + return this._expand(h2 + 1), a ? (this.words[h2] = this.words[h2] | (1 << s)) : (this.words[h2] = this.words[h2] & ~(1 << s)), this.strip(); + }), + (f.prototype.iadd = function (i) { + var a; + if (this.negative !== 0 && i.negative === 0) return (this.negative = 0), (a = this.isub(i)), (this.negative ^= 1), this._normSign(); + if (this.negative === 0 && i.negative !== 0) return (i.negative = 0), (a = this.isub(i)), (i.negative = 1), a._normSign(); + var h2, s; + this.length > i.length ? ((h2 = this), (s = i)) : ((h2 = i), (s = this)); + for (var u = 0, c = 0; c < s.length; c++) (a = (h2.words[c] | 0) + (s.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + for (; u !== 0 && c < h2.length; c++) (a = (h2.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + if (((this.length = h2.length), u !== 0)) (this.words[this.length] = u), this.length++; + else if (h2 !== this) for (; c < h2.length; c++) this.words[c] = h2.words[c]; + return this; + }), + (f.prototype.add = function (i) { + var a; + return i.negative !== 0 && this.negative === 0 + ? ((i.negative = 0), (a = this.sub(i)), (i.negative ^= 1), a) + : i.negative === 0 && this.negative !== 0 + ? ((this.negative = 0), (a = i.sub(this)), (this.negative = 1), a) + : this.length > i.length + ? this.clone().iadd(i) + : i.clone().iadd(this); + }), + (f.prototype.isub = function (i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return (i.negative = 1), a._normSign(); + } else if (this.negative !== 0) return (this.negative = 0), this.iadd(i), (this.negative = 1), this._normSign(); + var h2 = this.cmp(i); + if (h2 === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; + var s, u; + h2 > 0 ? ((s = this), (u = i)) : ((s = i), (u = this)); + for (var c = 0, b2 = 0; b2 < u.length; b2++) (a = (s.words[b2] | 0) - (u.words[b2] | 0) + c), (c = a >> 26), (this.words[b2] = a & 67108863); + for (; c !== 0 && b2 < s.length; b2++) (a = (s.words[b2] | 0) + c), (c = a >> 26), (this.words[b2] = a & 67108863); + if (c === 0 && b2 < s.length && s !== this) for (; b2 < s.length; b2++) this.words[b2] = s.words[b2]; + return (this.length = Math.max(this.length, b2)), s !== this && (this.negative = 1), this.strip(); + }), + (f.prototype.sub = function (i) { + return this.clone().isub(i); + }); + function q2(v, i, a) { + a.negative = i.negative ^ v.negative; + var h2 = (v.length + i.length) | 0; + (a.length = h2), (h2 = (h2 - 1) | 0); + var s = v.words[0] | 0, + u = i.words[0] | 0, + c = s * u, + b2 = c & 67108863, + l = (c / 67108864) | 0; + a.words[0] = b2; + for (var n = 1; n < h2; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _2 = Math.max(0, n - v.length + 1); _2 <= g; _2++) { + var A2 = (n - _2) | 0; + (s = v.words[A2] | 0), (u = i.words[_2] | 0), (c = s * u + w), (d += (c / 67108864) | 0), (w = c & 67108863); + } + (a.words[n] = w | 0), (l = d | 0); + } + return l !== 0 ? (a.words[n] = l | 0) : a.length--, a.strip(); + } + var L2 = function (i, a, h2) { + var s = i.words, + u = a.words, + c = h2.words, + b2 = 0, + l, + n, + d, + w = s[0] | 0, + g = w & 8191, + _2 = w >>> 13, + A2 = s[1] | 0, + R2 = A2 & 8191, + I = A2 >>> 13, + Me = s[2] | 0, + k = Me & 8191, + D2 = Me >>> 13, + nt = s[3] | 0, + C2 = nt & 8191, + O = nt >>> 13, + vt = s[4] | 0, + F = vt & 8191, + U = vt >>> 13, + bt = s[5] | 0, + z2 = bt & 8191, + H = bt >>> 13, + mt = s[6] | 0, + W = mt & 8191, + K = mt >>> 13, + gt = s[7] | 0, + j = gt & 8191, + Z = gt >>> 13, + yt = s[8] | 0, + V = yt & 8191, + $2 = yt >>> 13, + wt = s[9] | 0, + G = wt & 8191, + Y = wt >>> 13, + Mt = u[0] | 0, + X = Mt & 8191, + J = Mt >>> 13, + _t = u[1] | 0, + Q = _t & 8191, + ee = _t >>> 13, + xt = u[2] | 0, + te = xt & 8191, + re = xt >>> 13, + St = u[3] | 0, + ie = St & 8191, + ne = St >>> 13, + Et = u[4] | 0, + fe = Et & 8191, + ae = Et >>> 13, + At = u[5] | 0, + oe = At & 8191, + se = At >>> 13, + Rt = u[6] | 0, + he = Rt & 8191, + ue = Rt >>> 13, + Bt = u[7] | 0, + le = Bt & 8191, + de = Bt >>> 13, + qt = u[8] | 0, + ce = qt & 8191, + pe = qt >>> 13, + It = u[9] | 0, + ve = It & 8191, + be = It >>> 13; + (h2.negative = i.negative ^ a.negative), (h2.length = 19), (l = Math.imul(g, X)), (n = Math.imul(g, J)), (n = (n + Math.imul(_2, X)) | 0), (d = Math.imul(_2, J)); + var ft = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (ft >>> 26)) | 0), + (ft &= 67108863), + (l = Math.imul(R2, X)), + (n = Math.imul(R2, J)), + (n = (n + Math.imul(I, X)) | 0), + (d = Math.imul(I, J)), + (l = (l + Math.imul(g, Q)) | 0), + (n = (n + Math.imul(g, ee)) | 0), + (n = (n + Math.imul(_2, Q)) | 0), + (d = (d + Math.imul(_2, ee)) | 0); + var Be = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Be >>> 26)) | 0), + (Be &= 67108863), + (l = Math.imul(k, X)), + (n = Math.imul(k, J)), + (n = (n + Math.imul(D2, X)) | 0), + (d = Math.imul(D2, J)), + (l = (l + Math.imul(R2, Q)) | 0), + (n = (n + Math.imul(R2, ee)) | 0), + (n = (n + Math.imul(I, Q)) | 0), + (d = (d + Math.imul(I, ee)) | 0), + (l = (l + Math.imul(g, te)) | 0), + (n = (n + Math.imul(g, re)) | 0), + (n = (n + Math.imul(_2, te)) | 0), + (d = (d + Math.imul(_2, re)) | 0); + var qe = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (qe >>> 26)) | 0), + (qe &= 67108863), + (l = Math.imul(C2, X)), + (n = Math.imul(C2, J)), + (n = (n + Math.imul(O, X)) | 0), + (d = Math.imul(O, J)), + (l = (l + Math.imul(k, Q)) | 0), + (n = (n + Math.imul(k, ee)) | 0), + (n = (n + Math.imul(D2, Q)) | 0), + (d = (d + Math.imul(D2, ee)) | 0), + (l = (l + Math.imul(R2, te)) | 0), + (n = (n + Math.imul(R2, re)) | 0), + (n = (n + Math.imul(I, te)) | 0), + (d = (d + Math.imul(I, re)) | 0), + (l = (l + Math.imul(g, ie)) | 0), + (n = (n + Math.imul(g, ne)) | 0), + (n = (n + Math.imul(_2, ie)) | 0), + (d = (d + Math.imul(_2, ne)) | 0); + var ze = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (ze >>> 26)) | 0), + (ze &= 67108863), + (l = Math.imul(F, X)), + (n = Math.imul(F, J)), + (n = (n + Math.imul(U, X)) | 0), + (d = Math.imul(U, J)), + (l = (l + Math.imul(C2, Q)) | 0), + (n = (n + Math.imul(C2, ee)) | 0), + (n = (n + Math.imul(O, Q)) | 0), + (d = (d + Math.imul(O, ee)) | 0), + (l = (l + Math.imul(k, te)) | 0), + (n = (n + Math.imul(k, re)) | 0), + (n = (n + Math.imul(D2, te)) | 0), + (d = (d + Math.imul(D2, re)) | 0), + (l = (l + Math.imul(R2, ie)) | 0), + (n = (n + Math.imul(R2, ne)) | 0), + (n = (n + Math.imul(I, ie)) | 0), + (d = (d + Math.imul(I, ne)) | 0), + (l = (l + Math.imul(g, fe)) | 0), + (n = (n + Math.imul(g, ae)) | 0), + (n = (n + Math.imul(_2, fe)) | 0), + (d = (d + Math.imul(_2, ae)) | 0); + var He = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (He >>> 26)) | 0), + (He &= 67108863), + (l = Math.imul(z2, X)), + (n = Math.imul(z2, J)), + (n = (n + Math.imul(H, X)) | 0), + (d = Math.imul(H, J)), + (l = (l + Math.imul(F, Q)) | 0), + (n = (n + Math.imul(F, ee)) | 0), + (n = (n + Math.imul(U, Q)) | 0), + (d = (d + Math.imul(U, ee)) | 0), + (l = (l + Math.imul(C2, te)) | 0), + (n = (n + Math.imul(C2, re)) | 0), + (n = (n + Math.imul(O, te)) | 0), + (d = (d + Math.imul(O, re)) | 0), + (l = (l + Math.imul(k, ie)) | 0), + (n = (n + Math.imul(k, ne)) | 0), + (n = (n + Math.imul(D2, ie)) | 0), + (d = (d + Math.imul(D2, ne)) | 0), + (l = (l + Math.imul(R2, fe)) | 0), + (n = (n + Math.imul(R2, ae)) | 0), + (n = (n + Math.imul(I, fe)) | 0), + (d = (d + Math.imul(I, ae)) | 0), + (l = (l + Math.imul(g, oe)) | 0), + (n = (n + Math.imul(g, se)) | 0), + (n = (n + Math.imul(_2, oe)) | 0), + (d = (d + Math.imul(_2, se)) | 0); + var We = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (We >>> 26)) | 0), + (We &= 67108863), + (l = Math.imul(W, X)), + (n = Math.imul(W, J)), + (n = (n + Math.imul(K, X)) | 0), + (d = Math.imul(K, J)), + (l = (l + Math.imul(z2, Q)) | 0), + (n = (n + Math.imul(z2, ee)) | 0), + (n = (n + Math.imul(H, Q)) | 0), + (d = (d + Math.imul(H, ee)) | 0), + (l = (l + Math.imul(F, te)) | 0), + (n = (n + Math.imul(F, re)) | 0), + (n = (n + Math.imul(U, te)) | 0), + (d = (d + Math.imul(U, re)) | 0), + (l = (l + Math.imul(C2, ie)) | 0), + (n = (n + Math.imul(C2, ne)) | 0), + (n = (n + Math.imul(O, ie)) | 0), + (d = (d + Math.imul(O, ne)) | 0), + (l = (l + Math.imul(k, fe)) | 0), + (n = (n + Math.imul(k, ae)) | 0), + (n = (n + Math.imul(D2, fe)) | 0), + (d = (d + Math.imul(D2, ae)) | 0), + (l = (l + Math.imul(R2, oe)) | 0), + (n = (n + Math.imul(R2, se)) | 0), + (n = (n + Math.imul(I, oe)) | 0), + (d = (d + Math.imul(I, se)) | 0), + (l = (l + Math.imul(g, he)) | 0), + (n = (n + Math.imul(g, ue)) | 0), + (n = (n + Math.imul(_2, he)) | 0), + (d = (d + Math.imul(_2, ue)) | 0); + var Ke = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ke >>> 26)) | 0), + (Ke &= 67108863), + (l = Math.imul(j, X)), + (n = Math.imul(j, J)), + (n = (n + Math.imul(Z, X)) | 0), + (d = Math.imul(Z, J)), + (l = (l + Math.imul(W, Q)) | 0), + (n = (n + Math.imul(W, ee)) | 0), + (n = (n + Math.imul(K, Q)) | 0), + (d = (d + Math.imul(K, ee)) | 0), + (l = (l + Math.imul(z2, te)) | 0), + (n = (n + Math.imul(z2, re)) | 0), + (n = (n + Math.imul(H, te)) | 0), + (d = (d + Math.imul(H, re)) | 0), + (l = (l + Math.imul(F, ie)) | 0), + (n = (n + Math.imul(F, ne)) | 0), + (n = (n + Math.imul(U, ie)) | 0), + (d = (d + Math.imul(U, ne)) | 0), + (l = (l + Math.imul(C2, fe)) | 0), + (n = (n + Math.imul(C2, ae)) | 0), + (n = (n + Math.imul(O, fe)) | 0), + (d = (d + Math.imul(O, ae)) | 0), + (l = (l + Math.imul(k, oe)) | 0), + (n = (n + Math.imul(k, se)) | 0), + (n = (n + Math.imul(D2, oe)) | 0), + (d = (d + Math.imul(D2, se)) | 0), + (l = (l + Math.imul(R2, he)) | 0), + (n = (n + Math.imul(R2, ue)) | 0), + (n = (n + Math.imul(I, he)) | 0), + (d = (d + Math.imul(I, ue)) | 0), + (l = (l + Math.imul(g, le)) | 0), + (n = (n + Math.imul(g, de)) | 0), + (n = (n + Math.imul(_2, le)) | 0), + (d = (d + Math.imul(_2, de)) | 0); + var je = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (je >>> 26)) | 0), + (je &= 67108863), + (l = Math.imul(V, X)), + (n = Math.imul(V, J)), + (n = (n + Math.imul($2, X)) | 0), + (d = Math.imul($2, J)), + (l = (l + Math.imul(j, Q)) | 0), + (n = (n + Math.imul(j, ee)) | 0), + (n = (n + Math.imul(Z, Q)) | 0), + (d = (d + Math.imul(Z, ee)) | 0), + (l = (l + Math.imul(W, te)) | 0), + (n = (n + Math.imul(W, re)) | 0), + (n = (n + Math.imul(K, te)) | 0), + (d = (d + Math.imul(K, re)) | 0), + (l = (l + Math.imul(z2, ie)) | 0), + (n = (n + Math.imul(z2, ne)) | 0), + (n = (n + Math.imul(H, ie)) | 0), + (d = (d + Math.imul(H, ne)) | 0), + (l = (l + Math.imul(F, fe)) | 0), + (n = (n + Math.imul(F, ae)) | 0), + (n = (n + Math.imul(U, fe)) | 0), + (d = (d + Math.imul(U, ae)) | 0), + (l = (l + Math.imul(C2, oe)) | 0), + (n = (n + Math.imul(C2, se)) | 0), + (n = (n + Math.imul(O, oe)) | 0), + (d = (d + Math.imul(O, se)) | 0), + (l = (l + Math.imul(k, he)) | 0), + (n = (n + Math.imul(k, ue)) | 0), + (n = (n + Math.imul(D2, he)) | 0), + (d = (d + Math.imul(D2, ue)) | 0), + (l = (l + Math.imul(R2, le)) | 0), + (n = (n + Math.imul(R2, de)) | 0), + (n = (n + Math.imul(I, le)) | 0), + (d = (d + Math.imul(I, de)) | 0), + (l = (l + Math.imul(g, ce)) | 0), + (n = (n + Math.imul(g, pe)) | 0), + (n = (n + Math.imul(_2, ce)) | 0), + (d = (d + Math.imul(_2, pe)) | 0); + var Ze = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ze >>> 26)) | 0), + (Ze &= 67108863), + (l = Math.imul(G, X)), + (n = Math.imul(G, J)), + (n = (n + Math.imul(Y, X)) | 0), + (d = Math.imul(Y, J)), + (l = (l + Math.imul(V, Q)) | 0), + (n = (n + Math.imul(V, ee)) | 0), + (n = (n + Math.imul($2, Q)) | 0), + (d = (d + Math.imul($2, ee)) | 0), + (l = (l + Math.imul(j, te)) | 0), + (n = (n + Math.imul(j, re)) | 0), + (n = (n + Math.imul(Z, te)) | 0), + (d = (d + Math.imul(Z, re)) | 0), + (l = (l + Math.imul(W, ie)) | 0), + (n = (n + Math.imul(W, ne)) | 0), + (n = (n + Math.imul(K, ie)) | 0), + (d = (d + Math.imul(K, ne)) | 0), + (l = (l + Math.imul(z2, fe)) | 0), + (n = (n + Math.imul(z2, ae)) | 0), + (n = (n + Math.imul(H, fe)) | 0), + (d = (d + Math.imul(H, ae)) | 0), + (l = (l + Math.imul(F, oe)) | 0), + (n = (n + Math.imul(F, se)) | 0), + (n = (n + Math.imul(U, oe)) | 0), + (d = (d + Math.imul(U, se)) | 0), + (l = (l + Math.imul(C2, he)) | 0), + (n = (n + Math.imul(C2, ue)) | 0), + (n = (n + Math.imul(O, he)) | 0), + (d = (d + Math.imul(O, ue)) | 0), + (l = (l + Math.imul(k, le)) | 0), + (n = (n + Math.imul(k, de)) | 0), + (n = (n + Math.imul(D2, le)) | 0), + (d = (d + Math.imul(D2, de)) | 0), + (l = (l + Math.imul(R2, ce)) | 0), + (n = (n + Math.imul(R2, pe)) | 0), + (n = (n + Math.imul(I, ce)) | 0), + (d = (d + Math.imul(I, pe)) | 0), + (l = (l + Math.imul(g, ve)) | 0), + (n = (n + Math.imul(g, be)) | 0), + (n = (n + Math.imul(_2, ve)) | 0), + (d = (d + Math.imul(_2, be)) | 0); + var Ve = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ve >>> 26)) | 0), + (Ve &= 67108863), + (l = Math.imul(G, Q)), + (n = Math.imul(G, ee)), + (n = (n + Math.imul(Y, Q)) | 0), + (d = Math.imul(Y, ee)), + (l = (l + Math.imul(V, te)) | 0), + (n = (n + Math.imul(V, re)) | 0), + (n = (n + Math.imul($2, te)) | 0), + (d = (d + Math.imul($2, re)) | 0), + (l = (l + Math.imul(j, ie)) | 0), + (n = (n + Math.imul(j, ne)) | 0), + (n = (n + Math.imul(Z, ie)) | 0), + (d = (d + Math.imul(Z, ne)) | 0), + (l = (l + Math.imul(W, fe)) | 0), + (n = (n + Math.imul(W, ae)) | 0), + (n = (n + Math.imul(K, fe)) | 0), + (d = (d + Math.imul(K, ae)) | 0), + (l = (l + Math.imul(z2, oe)) | 0), + (n = (n + Math.imul(z2, se)) | 0), + (n = (n + Math.imul(H, oe)) | 0), + (d = (d + Math.imul(H, se)) | 0), + (l = (l + Math.imul(F, he)) | 0), + (n = (n + Math.imul(F, ue)) | 0), + (n = (n + Math.imul(U, he)) | 0), + (d = (d + Math.imul(U, ue)) | 0), + (l = (l + Math.imul(C2, le)) | 0), + (n = (n + Math.imul(C2, de)) | 0), + (n = (n + Math.imul(O, le)) | 0), + (d = (d + Math.imul(O, de)) | 0), + (l = (l + Math.imul(k, ce)) | 0), + (n = (n + Math.imul(k, pe)) | 0), + (n = (n + Math.imul(D2, ce)) | 0), + (d = (d + Math.imul(D2, pe)) | 0), + (l = (l + Math.imul(R2, ve)) | 0), + (n = (n + Math.imul(R2, be)) | 0), + (n = (n + Math.imul(I, ve)) | 0), + (d = (d + Math.imul(I, be)) | 0); + var $e = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + ($e >>> 26)) | 0), + ($e &= 67108863), + (l = Math.imul(G, te)), + (n = Math.imul(G, re)), + (n = (n + Math.imul(Y, te)) | 0), + (d = Math.imul(Y, re)), + (l = (l + Math.imul(V, ie)) | 0), + (n = (n + Math.imul(V, ne)) | 0), + (n = (n + Math.imul($2, ie)) | 0), + (d = (d + Math.imul($2, ne)) | 0), + (l = (l + Math.imul(j, fe)) | 0), + (n = (n + Math.imul(j, ae)) | 0), + (n = (n + Math.imul(Z, fe)) | 0), + (d = (d + Math.imul(Z, ae)) | 0), + (l = (l + Math.imul(W, oe)) | 0), + (n = (n + Math.imul(W, se)) | 0), + (n = (n + Math.imul(K, oe)) | 0), + (d = (d + Math.imul(K, se)) | 0), + (l = (l + Math.imul(z2, he)) | 0), + (n = (n + Math.imul(z2, ue)) | 0), + (n = (n + Math.imul(H, he)) | 0), + (d = (d + Math.imul(H, ue)) | 0), + (l = (l + Math.imul(F, le)) | 0), + (n = (n + Math.imul(F, de)) | 0), + (n = (n + Math.imul(U, le)) | 0), + (d = (d + Math.imul(U, de)) | 0), + (l = (l + Math.imul(C2, ce)) | 0), + (n = (n + Math.imul(C2, pe)) | 0), + (n = (n + Math.imul(O, ce)) | 0), + (d = (d + Math.imul(O, pe)) | 0), + (l = (l + Math.imul(k, ve)) | 0), + (n = (n + Math.imul(k, be)) | 0), + (n = (n + Math.imul(D2, ve)) | 0), + (d = (d + Math.imul(D2, be)) | 0); + var Ge = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ge >>> 26)) | 0), + (Ge &= 67108863), + (l = Math.imul(G, ie)), + (n = Math.imul(G, ne)), + (n = (n + Math.imul(Y, ie)) | 0), + (d = Math.imul(Y, ne)), + (l = (l + Math.imul(V, fe)) | 0), + (n = (n + Math.imul(V, ae)) | 0), + (n = (n + Math.imul($2, fe)) | 0), + (d = (d + Math.imul($2, ae)) | 0), + (l = (l + Math.imul(j, oe)) | 0), + (n = (n + Math.imul(j, se)) | 0), + (n = (n + Math.imul(Z, oe)) | 0), + (d = (d + Math.imul(Z, se)) | 0), + (l = (l + Math.imul(W, he)) | 0), + (n = (n + Math.imul(W, ue)) | 0), + (n = (n + Math.imul(K, he)) | 0), + (d = (d + Math.imul(K, ue)) | 0), + (l = (l + Math.imul(z2, le)) | 0), + (n = (n + Math.imul(z2, de)) | 0), + (n = (n + Math.imul(H, le)) | 0), + (d = (d + Math.imul(H, de)) | 0), + (l = (l + Math.imul(F, ce)) | 0), + (n = (n + Math.imul(F, pe)) | 0), + (n = (n + Math.imul(U, ce)) | 0), + (d = (d + Math.imul(U, pe)) | 0), + (l = (l + Math.imul(C2, ve)) | 0), + (n = (n + Math.imul(C2, be)) | 0), + (n = (n + Math.imul(O, ve)) | 0), + (d = (d + Math.imul(O, be)) | 0); + var Ye = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ye >>> 26)) | 0), + (Ye &= 67108863), + (l = Math.imul(G, fe)), + (n = Math.imul(G, ae)), + (n = (n + Math.imul(Y, fe)) | 0), + (d = Math.imul(Y, ae)), + (l = (l + Math.imul(V, oe)) | 0), + (n = (n + Math.imul(V, se)) | 0), + (n = (n + Math.imul($2, oe)) | 0), + (d = (d + Math.imul($2, se)) | 0), + (l = (l + Math.imul(j, he)) | 0), + (n = (n + Math.imul(j, ue)) | 0), + (n = (n + Math.imul(Z, he)) | 0), + (d = (d + Math.imul(Z, ue)) | 0), + (l = (l + Math.imul(W, le)) | 0), + (n = (n + Math.imul(W, de)) | 0), + (n = (n + Math.imul(K, le)) | 0), + (d = (d + Math.imul(K, de)) | 0), + (l = (l + Math.imul(z2, ce)) | 0), + (n = (n + Math.imul(z2, pe)) | 0), + (n = (n + Math.imul(H, ce)) | 0), + (d = (d + Math.imul(H, pe)) | 0), + (l = (l + Math.imul(F, ve)) | 0), + (n = (n + Math.imul(F, be)) | 0), + (n = (n + Math.imul(U, ve)) | 0), + (d = (d + Math.imul(U, be)) | 0); + var Xe = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Xe >>> 26)) | 0), + (Xe &= 67108863), + (l = Math.imul(G, oe)), + (n = Math.imul(G, se)), + (n = (n + Math.imul(Y, oe)) | 0), + (d = Math.imul(Y, se)), + (l = (l + Math.imul(V, he)) | 0), + (n = (n + Math.imul(V, ue)) | 0), + (n = (n + Math.imul($2, he)) | 0), + (d = (d + Math.imul($2, ue)) | 0), + (l = (l + Math.imul(j, le)) | 0), + (n = (n + Math.imul(j, de)) | 0), + (n = (n + Math.imul(Z, le)) | 0), + (d = (d + Math.imul(Z, de)) | 0), + (l = (l + Math.imul(W, ce)) | 0), + (n = (n + Math.imul(W, pe)) | 0), + (n = (n + Math.imul(K, ce)) | 0), + (d = (d + Math.imul(K, pe)) | 0), + (l = (l + Math.imul(z2, ve)) | 0), + (n = (n + Math.imul(z2, be)) | 0), + (n = (n + Math.imul(H, ve)) | 0), + (d = (d + Math.imul(H, be)) | 0); + var Je = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Je >>> 26)) | 0), + (Je &= 67108863), + (l = Math.imul(G, he)), + (n = Math.imul(G, ue)), + (n = (n + Math.imul(Y, he)) | 0), + (d = Math.imul(Y, ue)), + (l = (l + Math.imul(V, le)) | 0), + (n = (n + Math.imul(V, de)) | 0), + (n = (n + Math.imul($2, le)) | 0), + (d = (d + Math.imul($2, de)) | 0), + (l = (l + Math.imul(j, ce)) | 0), + (n = (n + Math.imul(j, pe)) | 0), + (n = (n + Math.imul(Z, ce)) | 0), + (d = (d + Math.imul(Z, pe)) | 0), + (l = (l + Math.imul(W, ve)) | 0), + (n = (n + Math.imul(W, be)) | 0), + (n = (n + Math.imul(K, ve)) | 0), + (d = (d + Math.imul(K, be)) | 0); + var Qe = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Qe >>> 26)) | 0), + (Qe &= 67108863), + (l = Math.imul(G, le)), + (n = Math.imul(G, de)), + (n = (n + Math.imul(Y, le)) | 0), + (d = Math.imul(Y, de)), + (l = (l + Math.imul(V, ce)) | 0), + (n = (n + Math.imul(V, pe)) | 0), + (n = (n + Math.imul($2, ce)) | 0), + (d = (d + Math.imul($2, pe)) | 0), + (l = (l + Math.imul(j, ve)) | 0), + (n = (n + Math.imul(j, be)) | 0), + (n = (n + Math.imul(Z, ve)) | 0), + (d = (d + Math.imul(Z, be)) | 0); + var et = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (et >>> 26)) | 0), + (et &= 67108863), + (l = Math.imul(G, ce)), + (n = Math.imul(G, pe)), + (n = (n + Math.imul(Y, ce)) | 0), + (d = Math.imul(Y, pe)), + (l = (l + Math.imul(V, ve)) | 0), + (n = (n + Math.imul(V, be)) | 0), + (n = (n + Math.imul($2, ve)) | 0), + (d = (d + Math.imul($2, be)) | 0); + var tt = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (tt >>> 26)) | 0), (tt &= 67108863), (l = Math.imul(G, ve)), (n = Math.imul(G, be)), (n = (n + Math.imul(Y, ve)) | 0), (d = Math.imul(Y, be)); + var rt = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + return ( + (b2 = (((d + (n >>> 13)) | 0) + (rt >>> 26)) | 0), + (rt &= 67108863), + (c[0] = ft), + (c[1] = Be), + (c[2] = qe), + (c[3] = ze), + (c[4] = He), + (c[5] = We), + (c[6] = Ke), + (c[7] = je), + (c[8] = Ze), + (c[9] = Ve), + (c[10] = $e), + (c[11] = Ge), + (c[12] = Ye), + (c[13] = Xe), + (c[14] = Je), + (c[15] = Qe), + (c[16] = et), + (c[17] = tt), + (c[18] = rt), + b2 !== 0 && ((c[19] = b2), h2.length++), + h2 + ); + }; + Math.imul || (L2 = q2); + function ge(v, i, a) { + (a.negative = i.negative ^ v.negative), (a.length = v.length + i.length); + for (var h2 = 0, s = 0, u = 0; u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b2 = h2 & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1); n <= l; n++) { + var d = u - n, + w = v.words[d] | 0, + g = i.words[n] | 0, + _2 = w * g, + A2 = _2 & 67108863; + (c = (c + ((_2 / 67108864) | 0)) | 0), (A2 = (A2 + b2) | 0), (b2 = A2 & 67108863), (c = (c + (A2 >>> 26)) | 0), (s += c >>> 26), (c &= 67108863); + } + (a.words[u] = b2), (h2 = c), (c = s); + } + return h2 !== 0 ? (a.words[u] = h2) : a.length--, a.strip(); + } + function _e(v, i, a) { + var h2 = new N(); + return h2.mulp(v, i, a); + } + f.prototype.mulTo = function (i, a) { + var h2, + s = this.length + i.length; + return this.length === 10 && i.length === 10 ? (h2 = L2(this, i, a)) : s < 63 ? (h2 = q2(this, i, a)) : s < 1024 ? (h2 = ge(this, i, a)) : (h2 = _e(this, i, a)), h2; + }; + function N(v, i) { + (this.x = v), (this.y = i); + } + (N.prototype.makeRBT = function (i) { + for (var a = new Array(i), h2 = f.prototype._countBits(i) - 1, s = 0; s < i; s++) a[s] = this.revBin(s, h2, i); + return a; + }), + (N.prototype.revBin = function (i, a, h2) { + if (i === 0 || i === h2 - 1) return i; + for (var s = 0, u = 0; u < a; u++) (s |= (i & 1) << (a - u - 1)), (i >>= 1); + return s; + }), + (N.prototype.permute = function (i, a, h2, s, u, c) { + for (var b2 = 0; b2 < c; b2++) (s[b2] = a[i[b2]]), (u[b2] = h2[i[b2]]); + }), + (N.prototype.transform = function (i, a, h2, s, u, c) { + this.permute(c, i, a, h2, s, u); + for (var b2 = 1; b2 < u; b2 <<= 1) + for (var l = b2 << 1, n = Math.cos((2 * Math.PI) / l), d = Math.sin((2 * Math.PI) / l), w = 0; w < u; w += l) + for (var g = n, _2 = d, A2 = 0; A2 < b2; A2++) { + var R2 = h2[w + A2], + I = s[w + A2], + Me = h2[w + A2 + b2], + k = s[w + A2 + b2], + D2 = g * Me - _2 * k; + (k = g * k + _2 * Me), (Me = D2), (h2[w + A2] = R2 + Me), (s[w + A2] = I + k), (h2[w + A2 + b2] = R2 - Me), (s[w + A2 + b2] = I - k), A2 !== l && ((D2 = n * g - d * _2), (_2 = n * _2 + d * g), (g = D2)); + } + }), + (N.prototype.guessLen13b = function (i, a) { + var h2 = Math.max(a, i) | 1, + s = h2 & 1, + u = 0; + for (h2 = (h2 / 2) | 0; h2; h2 = h2 >>> 1) u++; + return 1 << (u + 1 + s); + }), + (N.prototype.conjugate = function (i, a, h2) { + if (!(h2 <= 1)) + for (var s = 0; s < h2 / 2; s++) { + var u = i[s]; + (i[s] = i[h2 - s - 1]), (i[h2 - s - 1] = u), (u = a[s]), (a[s] = -a[h2 - s - 1]), (a[h2 - s - 1] = -u); + } + }), + (N.prototype.normalize13b = function (i, a) { + for (var h2 = 0, s = 0; s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h2; + (i[s] = u & 67108863), u < 67108864 ? (h2 = 0) : (h2 = (u / 67108864) | 0); + } + return i; + }), + (N.prototype.convert13b = function (i, a, h2, s) { + for (var u = 0, c = 0; c < a; c++) (u = u + (i[c] | 0)), (h2[2 * c] = u & 8191), (u = u >>> 13), (h2[2 * c + 1] = u & 8191), (u = u >>> 13); + for (c = 2 * a; c < s; ++c) h2[c] = 0; + r(u === 0), r((u & -8192) === 0); + }), + (N.prototype.stub = function (i) { + for (var a = new Array(i), h2 = 0; h2 < i; h2++) a[h2] = 0; + return a; + }), + (N.prototype.mulp = function (i, a, h2) { + var s = 2 * this.guessLen13b(i.length, a.length), + u = this.makeRBT(s), + c = this.stub(s), + b2 = new Array(s), + l = new Array(s), + n = new Array(s), + d = new Array(s), + w = new Array(s), + g = new Array(s), + _2 = h2.words; + (_2.length = s), this.convert13b(i.words, i.length, b2, s), this.convert13b(a.words, a.length, d, s), this.transform(b2, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A2 = 0; A2 < s; A2++) { + var R2 = l[A2] * w[A2] - n[A2] * g[A2]; + (n[A2] = l[A2] * g[A2] + n[A2] * w[A2]), (l[A2] = R2); + } + return this.conjugate(l, n, s), this.transform(l, n, _2, c, s, u), this.conjugate(_2, c, s), this.normalize13b(_2, s), (h2.negative = i.negative ^ a.negative), (h2.length = i.length + a.length), h2.strip(); + }), + (f.prototype.mul = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), this.mulTo(i, a); + }), + (f.prototype.mulf = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), _e(this, i, a); + }), + (f.prototype.imul = function (i) { + return this.clone().mulTo(i, this); + }), + (f.prototype.imuln = function (i) { + r(typeof i == 'number'), r(i < 67108864); + for (var a = 0, h2 = 0; h2 < this.length; h2++) { + var s = (this.words[h2] | 0) * i, + u = (s & 67108863) + (a & 67108863); + (a >>= 26), (a += (s / 67108864) | 0), (a += u >>> 26), (this.words[h2] = u & 67108863); + } + return a !== 0 && ((this.words[h2] = a), this.length++), this; + }), + (f.prototype.muln = function (i) { + return this.clone().imuln(i); + }), + (f.prototype.sqr = function () { + return this.mul(this); + }), + (f.prototype.isqr = function () { + return this.imul(this.clone()); + }), + (f.prototype.pow = function (i) { + var a = B(i); + if (a.length === 0) return new f(1); + for (var h2 = this, s = 0; s < a.length && a[s] === 0; s++, h2 = h2.sqr()); + if (++s < a.length) for (var u = h2.sqr(); s < a.length; s++, u = u.sqr()) a[s] !== 0 && (h2 = h2.mul(u)); + return h2; + }), + (f.prototype.iushln = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26, + s = (67108863 >>> (26 - a)) << (26 - a), + u; + if (a !== 0) { + var c = 0; + for (u = 0; u < this.length; u++) { + var b2 = this.words[u] & s, + l = ((this.words[u] | 0) - b2) << a; + (this.words[u] = l | c), (c = b2 >>> (26 - a)); + } + c && ((this.words[u] = c), this.length++); + } + if (h2 !== 0) { + for (u = this.length - 1; u >= 0; u--) this.words[u + h2] = this.words[u]; + for (u = 0; u < h2; u++) this.words[u] = 0; + this.length += h2; + } + return this.strip(); + }), + (f.prototype.ishln = function (i) { + return r(this.negative === 0), this.iushln(i); + }), + (f.prototype.iushrn = function (i, a, h2) { + r(typeof i == 'number' && i >= 0); + var s; + a ? (s = (a - (a % 26)) / 26) : (s = 0); + var u = i % 26, + c = Math.min((i - u) / 26, this.length), + b2 = 67108863 ^ ((67108863 >>> u) << u), + l = h2; + if (((s -= c), (s = Math.max(0, s)), l)) { + for (var n = 0; n < c; n++) l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) for (this.length -= c, n = 0; n < this.length; n++) this.words[n] = this.words[n + c]; + else (this.words[0] = 0), (this.length = 1); + var d = 0; + for (n = this.length - 1; n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + (this.words[n] = (d << (26 - u)) | (w >>> u)), (d = w & b2); + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && ((this.words[0] = 0), (this.length = 1)), this.strip(); + }), + (f.prototype.ishrn = function (i, a, h2) { + return r(this.negative === 0), this.iushrn(i, a, h2); + }), + (f.prototype.shln = function (i) { + return this.clone().ishln(i); + }), + (f.prototype.ushln = function (i) { + return this.clone().iushln(i); + }), + (f.prototype.shrn = function (i) { + return this.clone().ishrn(i); + }), + (f.prototype.ushrn = function (i) { + return this.clone().iushrn(i); + }), + (f.prototype.testn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26, + s = 1 << a; + if (this.length <= h2) return false; + var u = this.words[h2]; + return !!(u & s); + }), + (f.prototype.imaskn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26; + if ((r(this.negative === 0, 'imaskn works only with positive numbers'), this.length <= h2)) return this; + if ((a !== 0 && h2++, (this.length = Math.min(h2, this.length)), a !== 0)) { + var s = 67108863 ^ ((67108863 >>> a) << a); + this.words[this.length - 1] &= s; + } + return this.strip(); + }), + (f.prototype.maskn = function (i) { + return this.clone().imaskn(i); + }), + (f.prototype.iaddn = function (i) { + return ( + r(typeof i == 'number'), + r(i < 67108864), + i < 0 + ? this.isubn(-i) + : this.negative !== 0 + ? this.length === 1 && (this.words[0] | 0) < i + ? ((this.words[0] = i - (this.words[0] | 0)), (this.negative = 0), this) + : ((this.negative = 0), this.isubn(i), (this.negative = 1), this) + : this._iaddn(i) + ); + }), + (f.prototype._iaddn = function (i) { + this.words[0] += i; + for (var a = 0; a < this.length && this.words[a] >= 67108864; a++) (this.words[a] -= 67108864), a === this.length - 1 ? (this.words[a + 1] = 1) : this.words[a + 1]++; + return (this.length = Math.max(this.length, a + 1)), this; + }), + (f.prototype.isubn = function (i) { + if ((r(typeof i == 'number'), r(i < 67108864), i < 0)) return this.iaddn(-i); + if (this.negative !== 0) return (this.negative = 0), this.iaddn(i), (this.negative = 1), this; + if (((this.words[0] -= i), this.length === 1 && this.words[0] < 0)) (this.words[0] = -this.words[0]), (this.negative = 1); + else for (var a = 0; a < this.length && this.words[a] < 0; a++) (this.words[a] += 67108864), (this.words[a + 1] -= 1); + return this.strip(); + }), + (f.prototype.addn = function (i) { + return this.clone().iaddn(i); + }), + (f.prototype.subn = function (i) { + return this.clone().isubn(i); + }), + (f.prototype.iabs = function () { + return (this.negative = 0), this; + }), + (f.prototype.abs = function () { + return this.clone().iabs(); + }), + (f.prototype._ishlnsubmul = function (i, a, h2) { + var s = i.length + h2, + u; + this._expand(s); + var c, + b2 = 0; + for (u = 0; u < i.length; u++) { + c = (this.words[u + h2] | 0) + b2; + var l = (i.words[u] | 0) * a; + (c -= l & 67108863), (b2 = (c >> 26) - ((l / 67108864) | 0)), (this.words[u + h2] = c & 67108863); + } + for (; u < this.length - h2; u++) (c = (this.words[u + h2] | 0) + b2), (b2 = c >> 26), (this.words[u + h2] = c & 67108863); + if (b2 === 0) return this.strip(); + for (r(b2 === -1), b2 = 0, u = 0; u < this.length; u++) (c = -(this.words[u] | 0) + b2), (b2 = c >> 26), (this.words[u] = c & 67108863); + return (this.negative = 1), this.strip(); + }), + (f.prototype._wordDiv = function (i, a) { + var h2 = this.length - i.length, + s = this.clone(), + u = i, + c = u.words[u.length - 1] | 0, + b2 = this._countBits(c); + (h2 = 26 - b2), h2 !== 0 && ((u = u.ushln(h2)), s.iushln(h2), (c = u.words[u.length - 1] | 0)); + var l = s.length - u.length, + n; + if (a !== 'mod') { + (n = new f(null)), (n.length = l + 1), (n.words = new Array(n.length)); + for (var d = 0; d < n.length; d++) n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && ((s = w), n && (n.words[l] = 1)); + for (var g = l - 1; g >= 0; g--) { + var _2 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_2 = Math.min((_2 / c) | 0, 67108863), s._ishlnsubmul(u, _2, g); s.negative !== 0; ) _2--, (s.negative = 0), s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _2); + } + return n && n.strip(), s.strip(), a !== 'div' && h2 !== 0 && s.iushrn(h2), {div: n || null, mod: s}; + }), + (f.prototype.divmod = function (i, a, h2) { + if ((r(!i.isZero()), this.isZero())) return {div: new f(0), mod: new f(0)}; + var s, u, c; + return this.negative !== 0 && i.negative === 0 + ? ((c = this.neg().divmod(i, a)), a !== 'mod' && (s = c.div.neg()), a !== 'div' && ((u = c.mod.neg()), h2 && u.negative !== 0 && u.iadd(i)), {div: s, mod: u}) + : this.negative === 0 && i.negative !== 0 + ? ((c = this.divmod(i.neg(), a)), a !== 'mod' && (s = c.div.neg()), {div: s, mod: c.mod}) + : (this.negative & i.negative) !== 0 + ? ((c = this.neg().divmod(i.neg(), a)), a !== 'div' && ((u = c.mod.neg()), h2 && u.negative !== 0 && u.isub(i)), {div: c.div, mod: u}) + : i.length > this.length || this.cmp(i) < 0 + ? {div: new f(0), mod: this} + : i.length === 1 + ? a === 'div' + ? {div: this.divn(i.words[0]), mod: null} + : a === 'mod' + ? {div: null, mod: new f(this.modn(i.words[0]))} + : {div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0]))} + : this._wordDiv(i, a); + }), + (f.prototype.div = function (i) { + return this.divmod(i, 'div', false).div; + }), + (f.prototype.mod = function (i) { + return this.divmod(i, 'mod', false).mod; + }), + (f.prototype.umod = function (i) { + return this.divmod(i, 'mod', true).mod; + }), + (f.prototype.divRound = function (i) { + var a = this.divmod(i); + if (a.mod.isZero()) return a.div; + var h2 = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, + s = i.ushrn(1), + u = i.andln(1), + c = h2.cmp(s); + return c < 0 || (u === 1 && c === 0) ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }), + (f.prototype.modn = function (i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h2 = 0, s = this.length - 1; s >= 0; s--) h2 = (a * h2 + (this.words[s] | 0)) % i; + return h2; + }), + (f.prototype.idivn = function (i) { + r(i <= 67108863); + for (var a = 0, h2 = this.length - 1; h2 >= 0; h2--) { + var s = (this.words[h2] | 0) + a * 67108864; + (this.words[h2] = (s / i) | 0), (a = s % i); + } + return this.strip(); + }), + (f.prototype.divn = function (i) { + return this.clone().idivn(i); + }), + (f.prototype.egcd = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h2 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = new f(0), b2 = new f(1), l = 0; a.isEven() && h2.isEven(); ) a.iushrn(1), h2.iushrn(1), ++l; + for (var n = h2.clone(), d = a.clone(); !a.isZero(); ) { + for (var w = 0, g = 1; (a.words[0] & g) === 0 && w < 26; ++w, g <<= 1); + if (w > 0) for (a.iushrn(w); w-- > 0; ) (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _2 = 0, A2 = 1; (h2.words[0] & A2) === 0 && _2 < 26; ++_2, A2 <<= 1); + if (_2 > 0) for (h2.iushrn(_2); _2-- > 0; ) (c.isOdd() || b2.isOdd()) && (c.iadd(n), b2.isub(d)), c.iushrn(1), b2.iushrn(1); + a.cmp(h2) >= 0 ? (a.isub(h2), s.isub(c), u.isub(b2)) : (h2.isub(a), c.isub(s), b2.isub(u)); + } + return {a: c, b: b2, gcd: h2.iushln(l)}; + }), + (f.prototype._invmp = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h2 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = h2.clone(); a.cmpn(1) > 0 && h2.cmpn(1) > 0; ) { + for (var b2 = 0, l = 1; (a.words[0] & l) === 0 && b2 < 26; ++b2, l <<= 1); + if (b2 > 0) for (a.iushrn(b2); b2-- > 0; ) s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1; (h2.words[0] & d) === 0 && n < 26; ++n, d <<= 1); + if (n > 0) for (h2.iushrn(n); n-- > 0; ) u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h2) >= 0 ? (a.isub(h2), s.isub(u)) : (h2.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? (w = s) : (w = u), w.cmpn(0) < 0 && w.iadd(i), w; + }), + (f.prototype.gcd = function (i) { + if (this.isZero()) return i.abs(); + if (i.isZero()) return this.abs(); + var a = this.clone(), + h2 = i.clone(); + (a.negative = 0), (h2.negative = 0); + for (var s = 0; a.isEven() && h2.isEven(); s++) a.iushrn(1), h2.iushrn(1); + do { + for (; a.isEven(); ) a.iushrn(1); + for (; h2.isEven(); ) h2.iushrn(1); + var u = a.cmp(h2); + if (u < 0) { + var c = a; + (a = h2), (h2 = c); + } else if (u === 0 || h2.cmpn(1) === 0) break; + a.isub(h2); + } while (true); + return h2.iushln(s); + }), + (f.prototype.invm = function (i) { + return this.egcd(i).a.umod(i); + }), + (f.prototype.isEven = function () { + return (this.words[0] & 1) === 0; + }), + (f.prototype.isOdd = function () { + return (this.words[0] & 1) === 1; + }), + (f.prototype.andln = function (i) { + return this.words[0] & i; + }), + (f.prototype.bincn = function (i) { + r(typeof i == 'number'); + var a = i % 26, + h2 = (i - a) / 26, + s = 1 << a; + if (this.length <= h2) return this._expand(h2 + 1), (this.words[h2] |= s), this; + for (var u = s, c = h2; u !== 0 && c < this.length; c++) { + var b2 = this.words[c] | 0; + (b2 += u), (u = b2 >>> 26), (b2 &= 67108863), (this.words[c] = b2); + } + return u !== 0 && ((this.words[c] = u), this.length++), this; + }), + (f.prototype.isZero = function () { + return this.length === 1 && this.words[0] === 0; + }), + (f.prototype.cmpn = function (i) { + var a = i < 0; + if (this.negative !== 0 && !a) return -1; + if (this.negative === 0 && a) return 1; + this.strip(); + var h2; + if (this.length > 1) h2 = 1; + else { + a && (i = -i), r(i <= 67108863, 'Number is too big'); + var s = this.words[0] | 0; + h2 = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h2 | 0 : h2; + }), + (f.prototype.cmp = function (i) { + if (this.negative !== 0 && i.negative === 0) return -1; + if (this.negative === 0 && i.negative !== 0) return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }), + (f.prototype.ucmp = function (i) { + if (this.length > i.length) return 1; + if (this.length < i.length) return -1; + for (var a = 0, h2 = this.length - 1; h2 >= 0; h2--) { + var s = this.words[h2] | 0, + u = i.words[h2] | 0; + if (s !== u) { + s < u ? (a = -1) : s > u && (a = 1); + break; + } + } + return a; + }), + (f.prototype.gtn = function (i) { + return this.cmpn(i) === 1; + }), + (f.prototype.gt = function (i) { + return this.cmp(i) === 1; + }), + (f.prototype.gten = function (i) { + return this.cmpn(i) >= 0; + }), + (f.prototype.gte = function (i) { + return this.cmp(i) >= 0; + }), + (f.prototype.ltn = function (i) { + return this.cmpn(i) === -1; + }), + (f.prototype.lt = function (i) { + return this.cmp(i) === -1; + }), + (f.prototype.lten = function (i) { + return this.cmpn(i) <= 0; + }), + (f.prototype.lte = function (i) { + return this.cmp(i) <= 0; + }), + (f.prototype.eqn = function (i) { + return this.cmpn(i) === 0; + }), + (f.prototype.eq = function (i) { + return this.cmp(i) === 0; + }), + (f.red = function (i) { + return new P(i); + }), + (f.prototype.toRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), r(this.negative === 0, 'red works only with positives'), i.convertTo(this)._forceRed(i); + }), + (f.prototype.fromRed = function () { + return r(this.red, 'fromRed works only with numbers in reduction context'), this.red.convertFrom(this); + }), + (f.prototype._forceRed = function (i) { + return (this.red = i), this; + }), + (f.prototype.forceRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), this._forceRed(i); + }), + (f.prototype.redAdd = function (i) { + return r(this.red, 'redAdd works only with red numbers'), this.red.add(this, i); + }), + (f.prototype.redIAdd = function (i) { + return r(this.red, 'redIAdd works only with red numbers'), this.red.iadd(this, i); + }), + (f.prototype.redSub = function (i) { + return r(this.red, 'redSub works only with red numbers'), this.red.sub(this, i); + }), + (f.prototype.redISub = function (i) { + return r(this.red, 'redISub works only with red numbers'), this.red.isub(this, i); + }), + (f.prototype.redShl = function (i) { + return r(this.red, 'redShl works only with red numbers'), this.red.shl(this, i); + }), + (f.prototype.redMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.mul(this, i); + }), + (f.prototype.redIMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.imul(this, i); + }), + (f.prototype.redSqr = function () { + return r(this.red, 'redSqr works only with red numbers'), this.red._verify1(this), this.red.sqr(this); + }), + (f.prototype.redISqr = function () { + return r(this.red, 'redISqr works only with red numbers'), this.red._verify1(this), this.red.isqr(this); + }), + (f.prototype.redSqrt = function () { + return r(this.red, 'redSqrt works only with red numbers'), this.red._verify1(this), this.red.sqrt(this); + }), + (f.prototype.redInvm = function () { + return r(this.red, 'redInvm works only with red numbers'), this.red._verify1(this), this.red.invm(this); + }), + (f.prototype.redNeg = function () { + return r(this.red, 'redNeg works only with red numbers'), this.red._verify1(this), this.red.neg(this); + }), + (f.prototype.redPow = function (i) { + return r(this.red && !i.red, 'redPow(normalNum)'), this.red._verify1(this), this.red.pow(this, i); + }); + var we = {k256: null, p224: null, p192: null, p25519: null}; + function ye(v, i) { + (this.name = v), (this.p = new f(i, 16)), (this.n = this.p.bitLength()), (this.k = new f(1).iushln(this.n).isub(this.p)), (this.tmp = this._tmp()); + } + (ye.prototype._tmp = function () { + var i = new f(null); + return (i.words = new Array(Math.ceil(this.n / 13))), i; + }), + (ye.prototype.ireduce = function (i) { + var a = i, + h2; + do this.split(a, this.tmp), (a = this.imulK(a)), (a = a.iadd(this.tmp)), (h2 = a.bitLength()); + while (h2 > this.n); + var s = h2 < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? ((a.words[0] = 0), (a.length = 1)) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }), + (ye.prototype.split = function (i, a) { + i.iushrn(this.n, 0, a); + }), + (ye.prototype.imulK = function (i) { + return i.imul(this.k); + }); + function xe() { + ye.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + o(xe, ye), + (xe.prototype.split = function (i, a) { + for (var h2 = 4194303, s = Math.min(i.length, 9), u = 0; u < s; u++) a.words[u] = i.words[u]; + if (((a.length = s), i.length <= 9)) { + (i.words[0] = 0), (i.length = 1); + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h2, u = 10; u < i.length; u++) { + var b2 = i.words[u] | 0; + (i.words[u - 10] = ((b2 & h2) << 4) | (c >>> 22)), (c = b2); + } + (c >>>= 22), (i.words[u - 10] = c), c === 0 && i.length > 10 ? (i.length -= 10) : (i.length -= 9); + }), + (xe.prototype.imulK = function (i) { + (i.words[i.length] = 0), (i.words[i.length + 1] = 0), (i.length += 2); + for (var a = 0, h2 = 0; h2 < i.length; h2++) { + var s = i.words[h2] | 0; + (a += s * 977), (i.words[h2] = a & 67108863), (a = s * 64 + ((a / 67108864) | 0)); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }); + function Re() { + ye.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + o(Re, ye); + function Ee() { + ye.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + o(Ee, ye); + function Ae() { + ye.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + o(Ae, ye), + (Ae.prototype.imulK = function (i) { + for (var a = 0, h2 = 0; h2 < i.length; h2++) { + var s = (i.words[h2] | 0) * 19 + a, + u = s & 67108863; + (s >>>= 26), (i.words[h2] = u), (a = s); + } + return a !== 0 && (i.words[i.length++] = a), i; + }), + (f._prime = function (i) { + if (we[i]) return we[i]; + var a; + if (i === 'k256') a = new xe(); + else if (i === 'p224') a = new Re(); + else if (i === 'p192') a = new Ee(); + else if (i === 'p25519') a = new Ae(); + else throw new Error('Unknown prime ' + i); + return (we[i] = a), a; + }); + function P(v) { + if (typeof v == 'string') { + var i = f._prime(v); + (this.m = i.p), (this.prime = i); + } else r(v.gtn(1), 'modulus must be greater than 1'), (this.m = v), (this.prime = null); + } + (P.prototype._verify1 = function (i) { + r(i.negative === 0, 'red works only with positives'), r(i.red, 'red works only with red numbers'); + }), + (P.prototype._verify2 = function (i, a) { + r((i.negative | a.negative) === 0, 'red works only with positives'), r(i.red && i.red === a.red, 'red works only with red numbers'); + }), + (P.prototype.imod = function (i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }), + (P.prototype.neg = function (i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }), + (P.prototype.add = function (i, a) { + this._verify2(i, a); + var h2 = i.add(a); + return h2.cmp(this.m) >= 0 && h2.isub(this.m), h2._forceRed(this); + }), + (P.prototype.iadd = function (i, a) { + this._verify2(i, a); + var h2 = i.iadd(a); + return h2.cmp(this.m) >= 0 && h2.isub(this.m), h2; + }), + (P.prototype.sub = function (i, a) { + this._verify2(i, a); + var h2 = i.sub(a); + return h2.cmpn(0) < 0 && h2.iadd(this.m), h2._forceRed(this); + }), + (P.prototype.isub = function (i, a) { + this._verify2(i, a); + var h2 = i.isub(a); + return h2.cmpn(0) < 0 && h2.iadd(this.m), h2; + }), + (P.prototype.shl = function (i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }), + (P.prototype.imul = function (i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }), + (P.prototype.mul = function (i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }), + (P.prototype.isqr = function (i) { + return this.imul(i, i.clone()); + }), + (P.prototype.sqr = function (i) { + return this.mul(i, i); + }), + (P.prototype.sqrt = function (i) { + if (i.isZero()) return i.clone(); + var a = this.m.andln(3); + if ((r(a % 2 === 1), a === 3)) { + var h2 = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h2); + } + for (var s = this.m.subn(1), u = 0; !s.isZero() && s.andln(1) === 0; ) u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), + b2 = c.redNeg(), + l = this.m.subn(1).iushrn(1), + n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this); this.pow(n, l).cmp(b2) !== 0; ) n.redIAdd(b2); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _2 = u; g.cmp(c) !== 0; ) { + for (var A2 = g, R2 = 0; A2.cmp(c) !== 0; R2++) A2 = A2.redSqr(); + r(R2 < _2); + var I = this.pow(d, new f(1).iushln(_2 - R2 - 1)); + (w = w.redMul(I)), (d = I.redSqr()), (g = g.redMul(d)), (_2 = R2); + } + return w; + }), + (P.prototype.invm = function (i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? ((a.negative = 0), this.imod(a).redNeg()) : this.imod(a); + }), + (P.prototype.pow = function (i, a) { + if (a.isZero()) return new f(1).toRed(this); + if (a.cmpn(1) === 0) return i.clone(); + var h2 = 4, + s = new Array(1 << h2); + (s[0] = new f(1).toRed(this)), (s[1] = i); + for (var u = 2; u < s.length; u++) s[u] = this.mul(s[u - 1], i); + var c = s[0], + b2 = 0, + l = 0, + n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1; u >= 0; u--) { + for (var d = a.words[u], w = n - 1; w >= 0; w--) { + var g = (d >> w) & 1; + if ((c !== s[0] && (c = this.sqr(c)), g === 0 && b2 === 0)) { + l = 0; + continue; + } + (b2 <<= 1), (b2 |= g), l++, !(l !== h2 && (u !== 0 || w !== 0)) && ((c = this.mul(c, s[b2])), (l = 0), (b2 = 0)); + } + n = 26; + } + return c; + }), + (P.prototype.convertTo = function (i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }), + (P.prototype.convertFrom = function (i) { + var a = i.clone(); + return (a.red = null), a; + }), + (f.mont = function (i) { + return new Se(i); + }); + function Se(v) { + P.call(this, v), + (this.shift = this.m.bitLength()), + this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), + (this.r = new f(1).iushln(this.shift)), + (this.r2 = this.imod(this.r.sqr())), + (this.rinv = this.r._invmp(this.m)), + (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), + (this.minv = this.minv.umod(this.r)), + (this.minv = this.r.sub(this.minv)); + } + o(Se, P), + (Se.prototype.convertTo = function (i) { + return this.imod(i.ushln(this.shift)); + }), + (Se.prototype.convertFrom = function (i) { + var a = this.imod(i.mul(this.rinv)); + return (a.red = null), a; + }), + (Se.prototype.imul = function (i, a) { + if (i.isZero() || a.isZero()) return (i.words[0] = 0), (i.length = 1), i; + var h2 = i.imul(a), + s = h2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h2.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.mul = function (i, a) { + if (i.isZero() || a.isZero()) return new f(0)._forceRed(this); + var h2 = i.mul(a), + s = h2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h2.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.invm = function (i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }); + })(typeof Gu > 'u' || Gu, $m); + }); + Ym = T2((Gm, Xu) => { + (function (t, e) { + function r(v, i) { + if (!v) throw new Error(i || 'Assertion failed'); + } + function o(v, i) { + v.super_ = i; + var a = function () {}; + (a.prototype = i.prototype), (v.prototype = new a()), (v.prototype.constructor = v); + } + function f(v, i, a) { + if (f.isBN(v)) return v; + (this.negative = 0), (this.words = null), (this.length = 0), (this.red = null), v !== null && ((i === 'le' || i === 'be') && ((a = i), (i = 10)), this._init(v || 0, i || 10, a || 'be')); + } + typeof t == 'object' ? (t.exports = f) : (e.BN = f), (f.BN = f), (f.wordSize = 26); + var p; + try { + typeof window < 'u' && typeof window.Buffer < 'u' ? (p = window.Buffer) : (p = ji().Buffer); + } catch {} + (f.isBN = function (i) { + return i instanceof f ? true : i !== null && typeof i == 'object' && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }), + (f.max = function (i, a) { + return i.cmp(a) > 0 ? i : a; + }), + (f.min = function (i, a) { + return i.cmp(a) < 0 ? i : a; + }), + (f.prototype._init = function (i, a, h2) { + if (typeof i == 'number') return this._initNumber(i, a, h2); + if (typeof i == 'object') return this._initArray(i, a, h2); + a === 'hex' && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), (i = i.toString().replace(/\s+/g, '')); + var s = 0; + i[0] === '-' && (s++, (this.negative = 1)), s < i.length && (a === 16 ? this._parseHex(i, s, h2) : (this._parseBase(i, a, s), h2 === 'le' && this._initArray(this.toArray(), a, h2))); + }), + (f.prototype._initNumber = function (i, a, h2) { + i < 0 && ((this.negative = 1), (i = -i)), + i < 67108864 + ? ((this.words = [i & 67108863]), (this.length = 1)) + : i < 4503599627370496 + ? ((this.words = [i & 67108863, (i / 67108864) & 67108863]), (this.length = 2)) + : (r(i < 9007199254740992), (this.words = [i & 67108863, (i / 67108864) & 67108863, 1]), (this.length = 3)), + h2 === 'le' && this._initArray(this.toArray(), a, h2); + }), + (f.prototype._initArray = function (i, a, h2) { + if ((r(typeof i.length == 'number'), i.length <= 0)) return (this.words = [0]), (this.length = 1), this; + (this.length = Math.ceil(i.length / 3)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u, + c, + b2 = 0; + if (h2 === 'be') + for (s = i.length - 1, u = 0; s >= 0; s -= 3) + (c = i[s] | (i[s - 1] << 8) | (i[s - 2] << 16)), (this.words[u] |= (c << b2) & 67108863), (this.words[u + 1] = (c >>> (26 - b2)) & 67108863), (b2 += 24), b2 >= 26 && ((b2 -= 26), u++); + else if (h2 === 'le') + for (s = 0, u = 0; s < i.length; s += 3) (c = i[s] | (i[s + 1] << 8) | (i[s + 2] << 16)), (this.words[u] |= (c << b2) & 67108863), (this.words[u + 1] = (c >>> (26 - b2)) & 67108863), (b2 += 24), b2 >= 26 && ((b2 -= 26), u++); + return this.strip(); + }); + function m2(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : (a - 48) & 15; + } + function y2(v, i, a) { + var h2 = m2(v, a); + return a - 1 >= i && (h2 |= m2(v, a - 1) << 4), h2; + } + f.prototype._parseHex = function (i, a, h2) { + (this.length = Math.ceil((i.length - a) / 6)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u = 0, + c = 0, + b2; + if (h2 === 'be') for (s = i.length - 1; s >= a; s -= 2) (b2 = y2(i, a, s) << u), (this.words[c] |= b2 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b2 >>> 26)) : (u += 8); + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a; s < i.length; s += 2) (b2 = y2(i, a, s) << u), (this.words[c] |= b2 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b2 >>> 26)) : (u += 8); + } + this.strip(); + }; + function M(v, i, a, h2) { + for (var s = 0, u = Math.min(v.length, a), c = i; c < u; c++) { + var b2 = v.charCodeAt(c) - 48; + (s *= h2), b2 >= 49 ? (s += b2 - 49 + 10) : b2 >= 17 ? (s += b2 - 17 + 10) : (s += b2); + } + return s; + } + (f.prototype._parseBase = function (i, a, h2) { + (this.words = [0]), (this.length = 1); + for (var s = 0, u = 1; u <= 67108863; u *= a) s++; + s--, (u = (u / a) | 0); + for (var c = i.length - h2, b2 = c % s, l = Math.min(c, c - b2) + h2, n = 0, d = h2; d < l; d += s) (n = M(i, d, d + s, a)), this.imuln(u), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + if (b2 !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0; d < b2; d++) w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + } + this.strip(); + }), + (f.prototype.copy = function (i) { + i.words = new Array(this.length); + for (var a = 0; a < this.length; a++) i.words[a] = this.words[a]; + (i.length = this.length), (i.negative = this.negative), (i.red = this.red); + }), + (f.prototype.clone = function () { + var i = new f(null); + return this.copy(i), i; + }), + (f.prototype._expand = function (i) { + for (; this.length < i; ) this.words[this.length++] = 0; + return this; + }), + (f.prototype.strip = function () { + for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; + return this._normSign(); + }), + (f.prototype._normSign = function () { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }), + (f.prototype.inspect = function () { + return (this.red ? ''; + }); + var x = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ], + S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + E2 = [ + 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, + 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + (f.prototype.toString = function (i, a) { + (i = i || 10), (a = a | 0 || 1); + var h2; + if (i === 16 || i === 'hex') { + h2 = ''; + for (var s = 0, u = 0, c = 0; c < this.length; c++) { + var b2 = this.words[c], + l = (((b2 << s) | u) & 16777215).toString(16); + (u = (b2 >>> (24 - s)) & 16777215), u !== 0 || c !== this.length - 1 ? (h2 = x[6 - l.length] + l + h2) : (h2 = l + h2), (s += 2), s >= 26 && ((s -= 26), c--); + } + for (u !== 0 && (h2 = u.toString(16) + h2); h2.length % a !== 0; ) h2 = '0' + h2; + return this.negative !== 0 && (h2 = '-' + h2), h2; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], + d = E2[i]; + h2 = ''; + var w = this.clone(); + for (w.negative = 0; !w.isZero(); ) { + var g = w.modn(d).toString(i); + (w = w.idivn(d)), w.isZero() ? (h2 = g + h2) : (h2 = x[n - g.length] + g + h2); + } + for (this.isZero() && (h2 = '0' + h2); h2.length % a !== 0; ) h2 = '0' + h2; + return this.negative !== 0 && (h2 = '-' + h2), h2; + } + r(false, 'Base should be between 2 and 36'); + }), + (f.prototype.toNumber = function () { + var i = this.words[0]; + return ( + this.length === 2 ? (i += this.words[1] * 67108864) : this.length === 3 && this.words[2] === 1 ? (i += 4503599627370496 + this.words[1] * 67108864) : this.length > 2 && r(false, 'Number can only safely store up to 53 bits'), + this.negative !== 0 ? -i : i + ); + }), + (f.prototype.toJSON = function () { + return this.toString(16); + }), + (f.prototype.toBuffer = function (i, a) { + return r(typeof p < 'u'), this.toArrayLike(p, i, a); + }), + (f.prototype.toArray = function (i, a) { + return this.toArrayLike(Array, i, a); + }), + (f.prototype.toArrayLike = function (i, a, h2) { + var s = this.byteLength(), + u = h2 || Math.max(1, s); + r(s <= u, 'byte array longer than desired length'), r(u > 0, 'Requested array length <= 0'), this.strip(); + var c = a === 'le', + b2 = new i(u), + l, + n, + d = this.clone(); + if (c) { + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b2[n] = l); + for (; n < u; n++) b2[n] = 0; + } else { + for (n = 0; n < u - s; n++) b2[n] = 0; + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b2[u - n - 1] = l); + } + return b2; + }), + Math.clz32 + ? (f.prototype._countBits = function (i) { + return 32 - Math.clz32(i); + }) + : (f.prototype._countBits = function (i) { + var a = i, + h2 = 0; + return a >= 4096 && ((h2 += 13), (a >>>= 13)), a >= 64 && ((h2 += 7), (a >>>= 7)), a >= 8 && ((h2 += 4), (a >>>= 4)), a >= 2 && ((h2 += 2), (a >>>= 2)), h2 + a; + }), + (f.prototype._zeroBits = function (i) { + if (i === 0) return 26; + var a = i, + h2 = 0; + return (a & 8191) === 0 && ((h2 += 13), (a >>>= 13)), (a & 127) === 0 && ((h2 += 7), (a >>>= 7)), (a & 15) === 0 && ((h2 += 4), (a >>>= 4)), (a & 3) === 0 && ((h2 += 2), (a >>>= 2)), (a & 1) === 0 && h2++, h2; + }), + (f.prototype.bitLength = function () { + var i = this.words[this.length - 1], + a = this._countBits(i); + return (this.length - 1) * 26 + a; + }); + function B(v) { + for (var i = new Array(v.bitLength()), a = 0; a < i.length; a++) { + var h2 = (a / 26) | 0, + s = a % 26; + i[a] = (v.words[h2] & (1 << s)) >>> s; + } + return i; + } + (f.prototype.zeroBits = function () { + if (this.isZero()) return 0; + for (var i = 0, a = 0; a < this.length; a++) { + var h2 = this._zeroBits(this.words[a]); + if (((i += h2), h2 !== 26)) break; + } + return i; + }), + (f.prototype.byteLength = function () { + return Math.ceil(this.bitLength() / 8); + }), + (f.prototype.toTwos = function (i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }), + (f.prototype.fromTwos = function (i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }), + (f.prototype.isNeg = function () { + return this.negative !== 0; + }), + (f.prototype.neg = function () { + return this.clone().ineg(); + }), + (f.prototype.ineg = function () { + return this.isZero() || (this.negative ^= 1), this; + }), + (f.prototype.iuor = function (i) { + for (; this.length < i.length; ) this.words[this.length++] = 0; + for (var a = 0; a < i.length; a++) this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }), + (f.prototype.ior = function (i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }), + (f.prototype.or = function (i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }), + (f.prototype.uor = function (i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }), + (f.prototype.iuand = function (i) { + var a; + this.length > i.length ? (a = i) : (a = this); + for (var h2 = 0; h2 < a.length; h2++) this.words[h2] = this.words[h2] & i.words[h2]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.iand = function (i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }), + (f.prototype.and = function (i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }), + (f.prototype.uand = function (i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }), + (f.prototype.iuxor = function (i) { + var a, h2; + this.length > i.length ? ((a = this), (h2 = i)) : ((a = i), (h2 = this)); + for (var s = 0; s < h2.length; s++) this.words[s] = a.words[s] ^ h2.words[s]; + if (this !== a) for (; s < a.length; s++) this.words[s] = a.words[s]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.ixor = function (i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }), + (f.prototype.xor = function (i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }), + (f.prototype.uxor = function (i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }), + (f.prototype.inotn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = Math.ceil(i / 26) | 0, + h2 = i % 26; + this._expand(a), h2 > 0 && a--; + for (var s = 0; s < a; s++) this.words[s] = ~this.words[s] & 67108863; + return h2 > 0 && (this.words[s] = ~this.words[s] & (67108863 >> (26 - h2))), this.strip(); + }), + (f.prototype.notn = function (i) { + return this.clone().inotn(i); + }), + (f.prototype.setn = function (i, a) { + r(typeof i == 'number' && i >= 0); + var h2 = (i / 26) | 0, + s = i % 26; + return this._expand(h2 + 1), a ? (this.words[h2] = this.words[h2] | (1 << s)) : (this.words[h2] = this.words[h2] & ~(1 << s)), this.strip(); + }), + (f.prototype.iadd = function (i) { + var a; + if (this.negative !== 0 && i.negative === 0) return (this.negative = 0), (a = this.isub(i)), (this.negative ^= 1), this._normSign(); + if (this.negative === 0 && i.negative !== 0) return (i.negative = 0), (a = this.isub(i)), (i.negative = 1), a._normSign(); + var h2, s; + this.length > i.length ? ((h2 = this), (s = i)) : ((h2 = i), (s = this)); + for (var u = 0, c = 0; c < s.length; c++) (a = (h2.words[c] | 0) + (s.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + for (; u !== 0 && c < h2.length; c++) (a = (h2.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + if (((this.length = h2.length), u !== 0)) (this.words[this.length] = u), this.length++; + else if (h2 !== this) for (; c < h2.length; c++) this.words[c] = h2.words[c]; + return this; + }), + (f.prototype.add = function (i) { + var a; + return i.negative !== 0 && this.negative === 0 + ? ((i.negative = 0), (a = this.sub(i)), (i.negative ^= 1), a) + : i.negative === 0 && this.negative !== 0 + ? ((this.negative = 0), (a = i.sub(this)), (this.negative = 1), a) + : this.length > i.length + ? this.clone().iadd(i) + : i.clone().iadd(this); + }), + (f.prototype.isub = function (i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return (i.negative = 1), a._normSign(); + } else if (this.negative !== 0) return (this.negative = 0), this.iadd(i), (this.negative = 1), this._normSign(); + var h2 = this.cmp(i); + if (h2 === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; + var s, u; + h2 > 0 ? ((s = this), (u = i)) : ((s = i), (u = this)); + for (var c = 0, b2 = 0; b2 < u.length; b2++) (a = (s.words[b2] | 0) - (u.words[b2] | 0) + c), (c = a >> 26), (this.words[b2] = a & 67108863); + for (; c !== 0 && b2 < s.length; b2++) (a = (s.words[b2] | 0) + c), (c = a >> 26), (this.words[b2] = a & 67108863); + if (c === 0 && b2 < s.length && s !== this) for (; b2 < s.length; b2++) this.words[b2] = s.words[b2]; + return (this.length = Math.max(this.length, b2)), s !== this && (this.negative = 1), this.strip(); + }), + (f.prototype.sub = function (i) { + return this.clone().isub(i); + }); + function q2(v, i, a) { + a.negative = i.negative ^ v.negative; + var h2 = (v.length + i.length) | 0; + (a.length = h2), (h2 = (h2 - 1) | 0); + var s = v.words[0] | 0, + u = i.words[0] | 0, + c = s * u, + b2 = c & 67108863, + l = (c / 67108864) | 0; + a.words[0] = b2; + for (var n = 1; n < h2; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _2 = Math.max(0, n - v.length + 1); _2 <= g; _2++) { + var A2 = (n - _2) | 0; + (s = v.words[A2] | 0), (u = i.words[_2] | 0), (c = s * u + w), (d += (c / 67108864) | 0), (w = c & 67108863); + } + (a.words[n] = w | 0), (l = d | 0); + } + return l !== 0 ? (a.words[n] = l | 0) : a.length--, a.strip(); + } + var L2 = function (i, a, h2) { + var s = i.words, + u = a.words, + c = h2.words, + b2 = 0, + l, + n, + d, + w = s[0] | 0, + g = w & 8191, + _2 = w >>> 13, + A2 = s[1] | 0, + R2 = A2 & 8191, + I = A2 >>> 13, + Me = s[2] | 0, + k = Me & 8191, + D2 = Me >>> 13, + nt = s[3] | 0, + C2 = nt & 8191, + O = nt >>> 13, + vt = s[4] | 0, + F = vt & 8191, + U = vt >>> 13, + bt = s[5] | 0, + z2 = bt & 8191, + H = bt >>> 13, + mt = s[6] | 0, + W = mt & 8191, + K = mt >>> 13, + gt = s[7] | 0, + j = gt & 8191, + Z = gt >>> 13, + yt = s[8] | 0, + V = yt & 8191, + $2 = yt >>> 13, + wt = s[9] | 0, + G = wt & 8191, + Y = wt >>> 13, + Mt = u[0] | 0, + X = Mt & 8191, + J = Mt >>> 13, + _t = u[1] | 0, + Q = _t & 8191, + ee = _t >>> 13, + xt = u[2] | 0, + te = xt & 8191, + re = xt >>> 13, + St = u[3] | 0, + ie = St & 8191, + ne = St >>> 13, + Et = u[4] | 0, + fe = Et & 8191, + ae = Et >>> 13, + At = u[5] | 0, + oe = At & 8191, + se = At >>> 13, + Rt = u[6] | 0, + he = Rt & 8191, + ue = Rt >>> 13, + Bt = u[7] | 0, + le = Bt & 8191, + de = Bt >>> 13, + qt = u[8] | 0, + ce = qt & 8191, + pe = qt >>> 13, + It = u[9] | 0, + ve = It & 8191, + be = It >>> 13; + (h2.negative = i.negative ^ a.negative), (h2.length = 19), (l = Math.imul(g, X)), (n = Math.imul(g, J)), (n = (n + Math.imul(_2, X)) | 0), (d = Math.imul(_2, J)); + var ft = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (ft >>> 26)) | 0), + (ft &= 67108863), + (l = Math.imul(R2, X)), + (n = Math.imul(R2, J)), + (n = (n + Math.imul(I, X)) | 0), + (d = Math.imul(I, J)), + (l = (l + Math.imul(g, Q)) | 0), + (n = (n + Math.imul(g, ee)) | 0), + (n = (n + Math.imul(_2, Q)) | 0), + (d = (d + Math.imul(_2, ee)) | 0); + var Be = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Be >>> 26)) | 0), + (Be &= 67108863), + (l = Math.imul(k, X)), + (n = Math.imul(k, J)), + (n = (n + Math.imul(D2, X)) | 0), + (d = Math.imul(D2, J)), + (l = (l + Math.imul(R2, Q)) | 0), + (n = (n + Math.imul(R2, ee)) | 0), + (n = (n + Math.imul(I, Q)) | 0), + (d = (d + Math.imul(I, ee)) | 0), + (l = (l + Math.imul(g, te)) | 0), + (n = (n + Math.imul(g, re)) | 0), + (n = (n + Math.imul(_2, te)) | 0), + (d = (d + Math.imul(_2, re)) | 0); + var qe = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (qe >>> 26)) | 0), + (qe &= 67108863), + (l = Math.imul(C2, X)), + (n = Math.imul(C2, J)), + (n = (n + Math.imul(O, X)) | 0), + (d = Math.imul(O, J)), + (l = (l + Math.imul(k, Q)) | 0), + (n = (n + Math.imul(k, ee)) | 0), + (n = (n + Math.imul(D2, Q)) | 0), + (d = (d + Math.imul(D2, ee)) | 0), + (l = (l + Math.imul(R2, te)) | 0), + (n = (n + Math.imul(R2, re)) | 0), + (n = (n + Math.imul(I, te)) | 0), + (d = (d + Math.imul(I, re)) | 0), + (l = (l + Math.imul(g, ie)) | 0), + (n = (n + Math.imul(g, ne)) | 0), + (n = (n + Math.imul(_2, ie)) | 0), + (d = (d + Math.imul(_2, ne)) | 0); + var ze = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (ze >>> 26)) | 0), + (ze &= 67108863), + (l = Math.imul(F, X)), + (n = Math.imul(F, J)), + (n = (n + Math.imul(U, X)) | 0), + (d = Math.imul(U, J)), + (l = (l + Math.imul(C2, Q)) | 0), + (n = (n + Math.imul(C2, ee)) | 0), + (n = (n + Math.imul(O, Q)) | 0), + (d = (d + Math.imul(O, ee)) | 0), + (l = (l + Math.imul(k, te)) | 0), + (n = (n + Math.imul(k, re)) | 0), + (n = (n + Math.imul(D2, te)) | 0), + (d = (d + Math.imul(D2, re)) | 0), + (l = (l + Math.imul(R2, ie)) | 0), + (n = (n + Math.imul(R2, ne)) | 0), + (n = (n + Math.imul(I, ie)) | 0), + (d = (d + Math.imul(I, ne)) | 0), + (l = (l + Math.imul(g, fe)) | 0), + (n = (n + Math.imul(g, ae)) | 0), + (n = (n + Math.imul(_2, fe)) | 0), + (d = (d + Math.imul(_2, ae)) | 0); + var He = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (He >>> 26)) | 0), + (He &= 67108863), + (l = Math.imul(z2, X)), + (n = Math.imul(z2, J)), + (n = (n + Math.imul(H, X)) | 0), + (d = Math.imul(H, J)), + (l = (l + Math.imul(F, Q)) | 0), + (n = (n + Math.imul(F, ee)) | 0), + (n = (n + Math.imul(U, Q)) | 0), + (d = (d + Math.imul(U, ee)) | 0), + (l = (l + Math.imul(C2, te)) | 0), + (n = (n + Math.imul(C2, re)) | 0), + (n = (n + Math.imul(O, te)) | 0), + (d = (d + Math.imul(O, re)) | 0), + (l = (l + Math.imul(k, ie)) | 0), + (n = (n + Math.imul(k, ne)) | 0), + (n = (n + Math.imul(D2, ie)) | 0), + (d = (d + Math.imul(D2, ne)) | 0), + (l = (l + Math.imul(R2, fe)) | 0), + (n = (n + Math.imul(R2, ae)) | 0), + (n = (n + Math.imul(I, fe)) | 0), + (d = (d + Math.imul(I, ae)) | 0), + (l = (l + Math.imul(g, oe)) | 0), + (n = (n + Math.imul(g, se)) | 0), + (n = (n + Math.imul(_2, oe)) | 0), + (d = (d + Math.imul(_2, se)) | 0); + var We = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (We >>> 26)) | 0), + (We &= 67108863), + (l = Math.imul(W, X)), + (n = Math.imul(W, J)), + (n = (n + Math.imul(K, X)) | 0), + (d = Math.imul(K, J)), + (l = (l + Math.imul(z2, Q)) | 0), + (n = (n + Math.imul(z2, ee)) | 0), + (n = (n + Math.imul(H, Q)) | 0), + (d = (d + Math.imul(H, ee)) | 0), + (l = (l + Math.imul(F, te)) | 0), + (n = (n + Math.imul(F, re)) | 0), + (n = (n + Math.imul(U, te)) | 0), + (d = (d + Math.imul(U, re)) | 0), + (l = (l + Math.imul(C2, ie)) | 0), + (n = (n + Math.imul(C2, ne)) | 0), + (n = (n + Math.imul(O, ie)) | 0), + (d = (d + Math.imul(O, ne)) | 0), + (l = (l + Math.imul(k, fe)) | 0), + (n = (n + Math.imul(k, ae)) | 0), + (n = (n + Math.imul(D2, fe)) | 0), + (d = (d + Math.imul(D2, ae)) | 0), + (l = (l + Math.imul(R2, oe)) | 0), + (n = (n + Math.imul(R2, se)) | 0), + (n = (n + Math.imul(I, oe)) | 0), + (d = (d + Math.imul(I, se)) | 0), + (l = (l + Math.imul(g, he)) | 0), + (n = (n + Math.imul(g, ue)) | 0), + (n = (n + Math.imul(_2, he)) | 0), + (d = (d + Math.imul(_2, ue)) | 0); + var Ke = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ke >>> 26)) | 0), + (Ke &= 67108863), + (l = Math.imul(j, X)), + (n = Math.imul(j, J)), + (n = (n + Math.imul(Z, X)) | 0), + (d = Math.imul(Z, J)), + (l = (l + Math.imul(W, Q)) | 0), + (n = (n + Math.imul(W, ee)) | 0), + (n = (n + Math.imul(K, Q)) | 0), + (d = (d + Math.imul(K, ee)) | 0), + (l = (l + Math.imul(z2, te)) | 0), + (n = (n + Math.imul(z2, re)) | 0), + (n = (n + Math.imul(H, te)) | 0), + (d = (d + Math.imul(H, re)) | 0), + (l = (l + Math.imul(F, ie)) | 0), + (n = (n + Math.imul(F, ne)) | 0), + (n = (n + Math.imul(U, ie)) | 0), + (d = (d + Math.imul(U, ne)) | 0), + (l = (l + Math.imul(C2, fe)) | 0), + (n = (n + Math.imul(C2, ae)) | 0), + (n = (n + Math.imul(O, fe)) | 0), + (d = (d + Math.imul(O, ae)) | 0), + (l = (l + Math.imul(k, oe)) | 0), + (n = (n + Math.imul(k, se)) | 0), + (n = (n + Math.imul(D2, oe)) | 0), + (d = (d + Math.imul(D2, se)) | 0), + (l = (l + Math.imul(R2, he)) | 0), + (n = (n + Math.imul(R2, ue)) | 0), + (n = (n + Math.imul(I, he)) | 0), + (d = (d + Math.imul(I, ue)) | 0), + (l = (l + Math.imul(g, le)) | 0), + (n = (n + Math.imul(g, de)) | 0), + (n = (n + Math.imul(_2, le)) | 0), + (d = (d + Math.imul(_2, de)) | 0); + var je = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (je >>> 26)) | 0), + (je &= 67108863), + (l = Math.imul(V, X)), + (n = Math.imul(V, J)), + (n = (n + Math.imul($2, X)) | 0), + (d = Math.imul($2, J)), + (l = (l + Math.imul(j, Q)) | 0), + (n = (n + Math.imul(j, ee)) | 0), + (n = (n + Math.imul(Z, Q)) | 0), + (d = (d + Math.imul(Z, ee)) | 0), + (l = (l + Math.imul(W, te)) | 0), + (n = (n + Math.imul(W, re)) | 0), + (n = (n + Math.imul(K, te)) | 0), + (d = (d + Math.imul(K, re)) | 0), + (l = (l + Math.imul(z2, ie)) | 0), + (n = (n + Math.imul(z2, ne)) | 0), + (n = (n + Math.imul(H, ie)) | 0), + (d = (d + Math.imul(H, ne)) | 0), + (l = (l + Math.imul(F, fe)) | 0), + (n = (n + Math.imul(F, ae)) | 0), + (n = (n + Math.imul(U, fe)) | 0), + (d = (d + Math.imul(U, ae)) | 0), + (l = (l + Math.imul(C2, oe)) | 0), + (n = (n + Math.imul(C2, se)) | 0), + (n = (n + Math.imul(O, oe)) | 0), + (d = (d + Math.imul(O, se)) | 0), + (l = (l + Math.imul(k, he)) | 0), + (n = (n + Math.imul(k, ue)) | 0), + (n = (n + Math.imul(D2, he)) | 0), + (d = (d + Math.imul(D2, ue)) | 0), + (l = (l + Math.imul(R2, le)) | 0), + (n = (n + Math.imul(R2, de)) | 0), + (n = (n + Math.imul(I, le)) | 0), + (d = (d + Math.imul(I, de)) | 0), + (l = (l + Math.imul(g, ce)) | 0), + (n = (n + Math.imul(g, pe)) | 0), + (n = (n + Math.imul(_2, ce)) | 0), + (d = (d + Math.imul(_2, pe)) | 0); + var Ze = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ze >>> 26)) | 0), + (Ze &= 67108863), + (l = Math.imul(G, X)), + (n = Math.imul(G, J)), + (n = (n + Math.imul(Y, X)) | 0), + (d = Math.imul(Y, J)), + (l = (l + Math.imul(V, Q)) | 0), + (n = (n + Math.imul(V, ee)) | 0), + (n = (n + Math.imul($2, Q)) | 0), + (d = (d + Math.imul($2, ee)) | 0), + (l = (l + Math.imul(j, te)) | 0), + (n = (n + Math.imul(j, re)) | 0), + (n = (n + Math.imul(Z, te)) | 0), + (d = (d + Math.imul(Z, re)) | 0), + (l = (l + Math.imul(W, ie)) | 0), + (n = (n + Math.imul(W, ne)) | 0), + (n = (n + Math.imul(K, ie)) | 0), + (d = (d + Math.imul(K, ne)) | 0), + (l = (l + Math.imul(z2, fe)) | 0), + (n = (n + Math.imul(z2, ae)) | 0), + (n = (n + Math.imul(H, fe)) | 0), + (d = (d + Math.imul(H, ae)) | 0), + (l = (l + Math.imul(F, oe)) | 0), + (n = (n + Math.imul(F, se)) | 0), + (n = (n + Math.imul(U, oe)) | 0), + (d = (d + Math.imul(U, se)) | 0), + (l = (l + Math.imul(C2, he)) | 0), + (n = (n + Math.imul(C2, ue)) | 0), + (n = (n + Math.imul(O, he)) | 0), + (d = (d + Math.imul(O, ue)) | 0), + (l = (l + Math.imul(k, le)) | 0), + (n = (n + Math.imul(k, de)) | 0), + (n = (n + Math.imul(D2, le)) | 0), + (d = (d + Math.imul(D2, de)) | 0), + (l = (l + Math.imul(R2, ce)) | 0), + (n = (n + Math.imul(R2, pe)) | 0), + (n = (n + Math.imul(I, ce)) | 0), + (d = (d + Math.imul(I, pe)) | 0), + (l = (l + Math.imul(g, ve)) | 0), + (n = (n + Math.imul(g, be)) | 0), + (n = (n + Math.imul(_2, ve)) | 0), + (d = (d + Math.imul(_2, be)) | 0); + var Ve = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ve >>> 26)) | 0), + (Ve &= 67108863), + (l = Math.imul(G, Q)), + (n = Math.imul(G, ee)), + (n = (n + Math.imul(Y, Q)) | 0), + (d = Math.imul(Y, ee)), + (l = (l + Math.imul(V, te)) | 0), + (n = (n + Math.imul(V, re)) | 0), + (n = (n + Math.imul($2, te)) | 0), + (d = (d + Math.imul($2, re)) | 0), + (l = (l + Math.imul(j, ie)) | 0), + (n = (n + Math.imul(j, ne)) | 0), + (n = (n + Math.imul(Z, ie)) | 0), + (d = (d + Math.imul(Z, ne)) | 0), + (l = (l + Math.imul(W, fe)) | 0), + (n = (n + Math.imul(W, ae)) | 0), + (n = (n + Math.imul(K, fe)) | 0), + (d = (d + Math.imul(K, ae)) | 0), + (l = (l + Math.imul(z2, oe)) | 0), + (n = (n + Math.imul(z2, se)) | 0), + (n = (n + Math.imul(H, oe)) | 0), + (d = (d + Math.imul(H, se)) | 0), + (l = (l + Math.imul(F, he)) | 0), + (n = (n + Math.imul(F, ue)) | 0), + (n = (n + Math.imul(U, he)) | 0), + (d = (d + Math.imul(U, ue)) | 0), + (l = (l + Math.imul(C2, le)) | 0), + (n = (n + Math.imul(C2, de)) | 0), + (n = (n + Math.imul(O, le)) | 0), + (d = (d + Math.imul(O, de)) | 0), + (l = (l + Math.imul(k, ce)) | 0), + (n = (n + Math.imul(k, pe)) | 0), + (n = (n + Math.imul(D2, ce)) | 0), + (d = (d + Math.imul(D2, pe)) | 0), + (l = (l + Math.imul(R2, ve)) | 0), + (n = (n + Math.imul(R2, be)) | 0), + (n = (n + Math.imul(I, ve)) | 0), + (d = (d + Math.imul(I, be)) | 0); + var $e = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + ($e >>> 26)) | 0), + ($e &= 67108863), + (l = Math.imul(G, te)), + (n = Math.imul(G, re)), + (n = (n + Math.imul(Y, te)) | 0), + (d = Math.imul(Y, re)), + (l = (l + Math.imul(V, ie)) | 0), + (n = (n + Math.imul(V, ne)) | 0), + (n = (n + Math.imul($2, ie)) | 0), + (d = (d + Math.imul($2, ne)) | 0), + (l = (l + Math.imul(j, fe)) | 0), + (n = (n + Math.imul(j, ae)) | 0), + (n = (n + Math.imul(Z, fe)) | 0), + (d = (d + Math.imul(Z, ae)) | 0), + (l = (l + Math.imul(W, oe)) | 0), + (n = (n + Math.imul(W, se)) | 0), + (n = (n + Math.imul(K, oe)) | 0), + (d = (d + Math.imul(K, se)) | 0), + (l = (l + Math.imul(z2, he)) | 0), + (n = (n + Math.imul(z2, ue)) | 0), + (n = (n + Math.imul(H, he)) | 0), + (d = (d + Math.imul(H, ue)) | 0), + (l = (l + Math.imul(F, le)) | 0), + (n = (n + Math.imul(F, de)) | 0), + (n = (n + Math.imul(U, le)) | 0), + (d = (d + Math.imul(U, de)) | 0), + (l = (l + Math.imul(C2, ce)) | 0), + (n = (n + Math.imul(C2, pe)) | 0), + (n = (n + Math.imul(O, ce)) | 0), + (d = (d + Math.imul(O, pe)) | 0), + (l = (l + Math.imul(k, ve)) | 0), + (n = (n + Math.imul(k, be)) | 0), + (n = (n + Math.imul(D2, ve)) | 0), + (d = (d + Math.imul(D2, be)) | 0); + var Ge = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ge >>> 26)) | 0), + (Ge &= 67108863), + (l = Math.imul(G, ie)), + (n = Math.imul(G, ne)), + (n = (n + Math.imul(Y, ie)) | 0), + (d = Math.imul(Y, ne)), + (l = (l + Math.imul(V, fe)) | 0), + (n = (n + Math.imul(V, ae)) | 0), + (n = (n + Math.imul($2, fe)) | 0), + (d = (d + Math.imul($2, ae)) | 0), + (l = (l + Math.imul(j, oe)) | 0), + (n = (n + Math.imul(j, se)) | 0), + (n = (n + Math.imul(Z, oe)) | 0), + (d = (d + Math.imul(Z, se)) | 0), + (l = (l + Math.imul(W, he)) | 0), + (n = (n + Math.imul(W, ue)) | 0), + (n = (n + Math.imul(K, he)) | 0), + (d = (d + Math.imul(K, ue)) | 0), + (l = (l + Math.imul(z2, le)) | 0), + (n = (n + Math.imul(z2, de)) | 0), + (n = (n + Math.imul(H, le)) | 0), + (d = (d + Math.imul(H, de)) | 0), + (l = (l + Math.imul(F, ce)) | 0), + (n = (n + Math.imul(F, pe)) | 0), + (n = (n + Math.imul(U, ce)) | 0), + (d = (d + Math.imul(U, pe)) | 0), + (l = (l + Math.imul(C2, ve)) | 0), + (n = (n + Math.imul(C2, be)) | 0), + (n = (n + Math.imul(O, ve)) | 0), + (d = (d + Math.imul(O, be)) | 0); + var Ye = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ye >>> 26)) | 0), + (Ye &= 67108863), + (l = Math.imul(G, fe)), + (n = Math.imul(G, ae)), + (n = (n + Math.imul(Y, fe)) | 0), + (d = Math.imul(Y, ae)), + (l = (l + Math.imul(V, oe)) | 0), + (n = (n + Math.imul(V, se)) | 0), + (n = (n + Math.imul($2, oe)) | 0), + (d = (d + Math.imul($2, se)) | 0), + (l = (l + Math.imul(j, he)) | 0), + (n = (n + Math.imul(j, ue)) | 0), + (n = (n + Math.imul(Z, he)) | 0), + (d = (d + Math.imul(Z, ue)) | 0), + (l = (l + Math.imul(W, le)) | 0), + (n = (n + Math.imul(W, de)) | 0), + (n = (n + Math.imul(K, le)) | 0), + (d = (d + Math.imul(K, de)) | 0), + (l = (l + Math.imul(z2, ce)) | 0), + (n = (n + Math.imul(z2, pe)) | 0), + (n = (n + Math.imul(H, ce)) | 0), + (d = (d + Math.imul(H, pe)) | 0), + (l = (l + Math.imul(F, ve)) | 0), + (n = (n + Math.imul(F, be)) | 0), + (n = (n + Math.imul(U, ve)) | 0), + (d = (d + Math.imul(U, be)) | 0); + var Xe = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Xe >>> 26)) | 0), + (Xe &= 67108863), + (l = Math.imul(G, oe)), + (n = Math.imul(G, se)), + (n = (n + Math.imul(Y, oe)) | 0), + (d = Math.imul(Y, se)), + (l = (l + Math.imul(V, he)) | 0), + (n = (n + Math.imul(V, ue)) | 0), + (n = (n + Math.imul($2, he)) | 0), + (d = (d + Math.imul($2, ue)) | 0), + (l = (l + Math.imul(j, le)) | 0), + (n = (n + Math.imul(j, de)) | 0), + (n = (n + Math.imul(Z, le)) | 0), + (d = (d + Math.imul(Z, de)) | 0), + (l = (l + Math.imul(W, ce)) | 0), + (n = (n + Math.imul(W, pe)) | 0), + (n = (n + Math.imul(K, ce)) | 0), + (d = (d + Math.imul(K, pe)) | 0), + (l = (l + Math.imul(z2, ve)) | 0), + (n = (n + Math.imul(z2, be)) | 0), + (n = (n + Math.imul(H, ve)) | 0), + (d = (d + Math.imul(H, be)) | 0); + var Je = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Je >>> 26)) | 0), + (Je &= 67108863), + (l = Math.imul(G, he)), + (n = Math.imul(G, ue)), + (n = (n + Math.imul(Y, he)) | 0), + (d = Math.imul(Y, ue)), + (l = (l + Math.imul(V, le)) | 0), + (n = (n + Math.imul(V, de)) | 0), + (n = (n + Math.imul($2, le)) | 0), + (d = (d + Math.imul($2, de)) | 0), + (l = (l + Math.imul(j, ce)) | 0), + (n = (n + Math.imul(j, pe)) | 0), + (n = (n + Math.imul(Z, ce)) | 0), + (d = (d + Math.imul(Z, pe)) | 0), + (l = (l + Math.imul(W, ve)) | 0), + (n = (n + Math.imul(W, be)) | 0), + (n = (n + Math.imul(K, ve)) | 0), + (d = (d + Math.imul(K, be)) | 0); + var Qe = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Qe >>> 26)) | 0), + (Qe &= 67108863), + (l = Math.imul(G, le)), + (n = Math.imul(G, de)), + (n = (n + Math.imul(Y, le)) | 0), + (d = Math.imul(Y, de)), + (l = (l + Math.imul(V, ce)) | 0), + (n = (n + Math.imul(V, pe)) | 0), + (n = (n + Math.imul($2, ce)) | 0), + (d = (d + Math.imul($2, pe)) | 0), + (l = (l + Math.imul(j, ve)) | 0), + (n = (n + Math.imul(j, be)) | 0), + (n = (n + Math.imul(Z, ve)) | 0), + (d = (d + Math.imul(Z, be)) | 0); + var et = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (et >>> 26)) | 0), + (et &= 67108863), + (l = Math.imul(G, ce)), + (n = Math.imul(G, pe)), + (n = (n + Math.imul(Y, ce)) | 0), + (d = Math.imul(Y, pe)), + (l = (l + Math.imul(V, ve)) | 0), + (n = (n + Math.imul(V, be)) | 0), + (n = (n + Math.imul($2, ve)) | 0), + (d = (d + Math.imul($2, be)) | 0); + var tt = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (tt >>> 26)) | 0), (tt &= 67108863), (l = Math.imul(G, ve)), (n = Math.imul(G, be)), (n = (n + Math.imul(Y, ve)) | 0), (d = Math.imul(Y, be)); + var rt = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + return ( + (b2 = (((d + (n >>> 13)) | 0) + (rt >>> 26)) | 0), + (rt &= 67108863), + (c[0] = ft), + (c[1] = Be), + (c[2] = qe), + (c[3] = ze), + (c[4] = He), + (c[5] = We), + (c[6] = Ke), + (c[7] = je), + (c[8] = Ze), + (c[9] = Ve), + (c[10] = $e), + (c[11] = Ge), + (c[12] = Ye), + (c[13] = Xe), + (c[14] = Je), + (c[15] = Qe), + (c[16] = et), + (c[17] = tt), + (c[18] = rt), + b2 !== 0 && ((c[19] = b2), h2.length++), + h2 + ); + }; + Math.imul || (L2 = q2); + function ge(v, i, a) { + (a.negative = i.negative ^ v.negative), (a.length = v.length + i.length); + for (var h2 = 0, s = 0, u = 0; u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b2 = h2 & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1); n <= l; n++) { + var d = u - n, + w = v.words[d] | 0, + g = i.words[n] | 0, + _2 = w * g, + A2 = _2 & 67108863; + (c = (c + ((_2 / 67108864) | 0)) | 0), (A2 = (A2 + b2) | 0), (b2 = A2 & 67108863), (c = (c + (A2 >>> 26)) | 0), (s += c >>> 26), (c &= 67108863); + } + (a.words[u] = b2), (h2 = c), (c = s); + } + return h2 !== 0 ? (a.words[u] = h2) : a.length--, a.strip(); + } + function _e(v, i, a) { + var h2 = new N(); + return h2.mulp(v, i, a); + } + f.prototype.mulTo = function (i, a) { + var h2, + s = this.length + i.length; + return this.length === 10 && i.length === 10 ? (h2 = L2(this, i, a)) : s < 63 ? (h2 = q2(this, i, a)) : s < 1024 ? (h2 = ge(this, i, a)) : (h2 = _e(this, i, a)), h2; + }; + function N(v, i) { + (this.x = v), (this.y = i); + } + (N.prototype.makeRBT = function (i) { + for (var a = new Array(i), h2 = f.prototype._countBits(i) - 1, s = 0; s < i; s++) a[s] = this.revBin(s, h2, i); + return a; + }), + (N.prototype.revBin = function (i, a, h2) { + if (i === 0 || i === h2 - 1) return i; + for (var s = 0, u = 0; u < a; u++) (s |= (i & 1) << (a - u - 1)), (i >>= 1); + return s; + }), + (N.prototype.permute = function (i, a, h2, s, u, c) { + for (var b2 = 0; b2 < c; b2++) (s[b2] = a[i[b2]]), (u[b2] = h2[i[b2]]); + }), + (N.prototype.transform = function (i, a, h2, s, u, c) { + this.permute(c, i, a, h2, s, u); + for (var b2 = 1; b2 < u; b2 <<= 1) + for (var l = b2 << 1, n = Math.cos((2 * Math.PI) / l), d = Math.sin((2 * Math.PI) / l), w = 0; w < u; w += l) + for (var g = n, _2 = d, A2 = 0; A2 < b2; A2++) { + var R2 = h2[w + A2], + I = s[w + A2], + Me = h2[w + A2 + b2], + k = s[w + A2 + b2], + D2 = g * Me - _2 * k; + (k = g * k + _2 * Me), (Me = D2), (h2[w + A2] = R2 + Me), (s[w + A2] = I + k), (h2[w + A2 + b2] = R2 - Me), (s[w + A2 + b2] = I - k), A2 !== l && ((D2 = n * g - d * _2), (_2 = n * _2 + d * g), (g = D2)); + } + }), + (N.prototype.guessLen13b = function (i, a) { + var h2 = Math.max(a, i) | 1, + s = h2 & 1, + u = 0; + for (h2 = (h2 / 2) | 0; h2; h2 = h2 >>> 1) u++; + return 1 << (u + 1 + s); + }), + (N.prototype.conjugate = function (i, a, h2) { + if (!(h2 <= 1)) + for (var s = 0; s < h2 / 2; s++) { + var u = i[s]; + (i[s] = i[h2 - s - 1]), (i[h2 - s - 1] = u), (u = a[s]), (a[s] = -a[h2 - s - 1]), (a[h2 - s - 1] = -u); + } + }), + (N.prototype.normalize13b = function (i, a) { + for (var h2 = 0, s = 0; s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h2; + (i[s] = u & 67108863), u < 67108864 ? (h2 = 0) : (h2 = (u / 67108864) | 0); + } + return i; + }), + (N.prototype.convert13b = function (i, a, h2, s) { + for (var u = 0, c = 0; c < a; c++) (u = u + (i[c] | 0)), (h2[2 * c] = u & 8191), (u = u >>> 13), (h2[2 * c + 1] = u & 8191), (u = u >>> 13); + for (c = 2 * a; c < s; ++c) h2[c] = 0; + r(u === 0), r((u & -8192) === 0); + }), + (N.prototype.stub = function (i) { + for (var a = new Array(i), h2 = 0; h2 < i; h2++) a[h2] = 0; + return a; + }), + (N.prototype.mulp = function (i, a, h2) { + var s = 2 * this.guessLen13b(i.length, a.length), + u = this.makeRBT(s), + c = this.stub(s), + b2 = new Array(s), + l = new Array(s), + n = new Array(s), + d = new Array(s), + w = new Array(s), + g = new Array(s), + _2 = h2.words; + (_2.length = s), this.convert13b(i.words, i.length, b2, s), this.convert13b(a.words, a.length, d, s), this.transform(b2, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A2 = 0; A2 < s; A2++) { + var R2 = l[A2] * w[A2] - n[A2] * g[A2]; + (n[A2] = l[A2] * g[A2] + n[A2] * w[A2]), (l[A2] = R2); + } + return this.conjugate(l, n, s), this.transform(l, n, _2, c, s, u), this.conjugate(_2, c, s), this.normalize13b(_2, s), (h2.negative = i.negative ^ a.negative), (h2.length = i.length + a.length), h2.strip(); + }), + (f.prototype.mul = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), this.mulTo(i, a); + }), + (f.prototype.mulf = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), _e(this, i, a); + }), + (f.prototype.imul = function (i) { + return this.clone().mulTo(i, this); + }), + (f.prototype.imuln = function (i) { + r(typeof i == 'number'), r(i < 67108864); + for (var a = 0, h2 = 0; h2 < this.length; h2++) { + var s = (this.words[h2] | 0) * i, + u = (s & 67108863) + (a & 67108863); + (a >>= 26), (a += (s / 67108864) | 0), (a += u >>> 26), (this.words[h2] = u & 67108863); + } + return a !== 0 && ((this.words[h2] = a), this.length++), this; + }), + (f.prototype.muln = function (i) { + return this.clone().imuln(i); + }), + (f.prototype.sqr = function () { + return this.mul(this); + }), + (f.prototype.isqr = function () { + return this.imul(this.clone()); + }), + (f.prototype.pow = function (i) { + var a = B(i); + if (a.length === 0) return new f(1); + for (var h2 = this, s = 0; s < a.length && a[s] === 0; s++, h2 = h2.sqr()); + if (++s < a.length) for (var u = h2.sqr(); s < a.length; s++, u = u.sqr()) a[s] !== 0 && (h2 = h2.mul(u)); + return h2; + }), + (f.prototype.iushln = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26, + s = (67108863 >>> (26 - a)) << (26 - a), + u; + if (a !== 0) { + var c = 0; + for (u = 0; u < this.length; u++) { + var b2 = this.words[u] & s, + l = ((this.words[u] | 0) - b2) << a; + (this.words[u] = l | c), (c = b2 >>> (26 - a)); + } + c && ((this.words[u] = c), this.length++); + } + if (h2 !== 0) { + for (u = this.length - 1; u >= 0; u--) this.words[u + h2] = this.words[u]; + for (u = 0; u < h2; u++) this.words[u] = 0; + this.length += h2; + } + return this.strip(); + }), + (f.prototype.ishln = function (i) { + return r(this.negative === 0), this.iushln(i); + }), + (f.prototype.iushrn = function (i, a, h2) { + r(typeof i == 'number' && i >= 0); + var s; + a ? (s = (a - (a % 26)) / 26) : (s = 0); + var u = i % 26, + c = Math.min((i - u) / 26, this.length), + b2 = 67108863 ^ ((67108863 >>> u) << u), + l = h2; + if (((s -= c), (s = Math.max(0, s)), l)) { + for (var n = 0; n < c; n++) l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) for (this.length -= c, n = 0; n < this.length; n++) this.words[n] = this.words[n + c]; + else (this.words[0] = 0), (this.length = 1); + var d = 0; + for (n = this.length - 1; n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + (this.words[n] = (d << (26 - u)) | (w >>> u)), (d = w & b2); + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && ((this.words[0] = 0), (this.length = 1)), this.strip(); + }), + (f.prototype.ishrn = function (i, a, h2) { + return r(this.negative === 0), this.iushrn(i, a, h2); + }), + (f.prototype.shln = function (i) { + return this.clone().ishln(i); + }), + (f.prototype.ushln = function (i) { + return this.clone().iushln(i); + }), + (f.prototype.shrn = function (i) { + return this.clone().ishrn(i); + }), + (f.prototype.ushrn = function (i) { + return this.clone().iushrn(i); + }), + (f.prototype.testn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26, + s = 1 << a; + if (this.length <= h2) return false; + var u = this.words[h2]; + return !!(u & s); + }), + (f.prototype.imaskn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26; + if ((r(this.negative === 0, 'imaskn works only with positive numbers'), this.length <= h2)) return this; + if ((a !== 0 && h2++, (this.length = Math.min(h2, this.length)), a !== 0)) { + var s = 67108863 ^ ((67108863 >>> a) << a); + this.words[this.length - 1] &= s; + } + return this.strip(); + }), + (f.prototype.maskn = function (i) { + return this.clone().imaskn(i); + }), + (f.prototype.iaddn = function (i) { + return ( + r(typeof i == 'number'), + r(i < 67108864), + i < 0 + ? this.isubn(-i) + : this.negative !== 0 + ? this.length === 1 && (this.words[0] | 0) < i + ? ((this.words[0] = i - (this.words[0] | 0)), (this.negative = 0), this) + : ((this.negative = 0), this.isubn(i), (this.negative = 1), this) + : this._iaddn(i) + ); + }), + (f.prototype._iaddn = function (i) { + this.words[0] += i; + for (var a = 0; a < this.length && this.words[a] >= 67108864; a++) (this.words[a] -= 67108864), a === this.length - 1 ? (this.words[a + 1] = 1) : this.words[a + 1]++; + return (this.length = Math.max(this.length, a + 1)), this; + }), + (f.prototype.isubn = function (i) { + if ((r(typeof i == 'number'), r(i < 67108864), i < 0)) return this.iaddn(-i); + if (this.negative !== 0) return (this.negative = 0), this.iaddn(i), (this.negative = 1), this; + if (((this.words[0] -= i), this.length === 1 && this.words[0] < 0)) (this.words[0] = -this.words[0]), (this.negative = 1); + else for (var a = 0; a < this.length && this.words[a] < 0; a++) (this.words[a] += 67108864), (this.words[a + 1] -= 1); + return this.strip(); + }), + (f.prototype.addn = function (i) { + return this.clone().iaddn(i); + }), + (f.prototype.subn = function (i) { + return this.clone().isubn(i); + }), + (f.prototype.iabs = function () { + return (this.negative = 0), this; + }), + (f.prototype.abs = function () { + return this.clone().iabs(); + }), + (f.prototype._ishlnsubmul = function (i, a, h2) { + var s = i.length + h2, + u; + this._expand(s); + var c, + b2 = 0; + for (u = 0; u < i.length; u++) { + c = (this.words[u + h2] | 0) + b2; + var l = (i.words[u] | 0) * a; + (c -= l & 67108863), (b2 = (c >> 26) - ((l / 67108864) | 0)), (this.words[u + h2] = c & 67108863); + } + for (; u < this.length - h2; u++) (c = (this.words[u + h2] | 0) + b2), (b2 = c >> 26), (this.words[u + h2] = c & 67108863); + if (b2 === 0) return this.strip(); + for (r(b2 === -1), b2 = 0, u = 0; u < this.length; u++) (c = -(this.words[u] | 0) + b2), (b2 = c >> 26), (this.words[u] = c & 67108863); + return (this.negative = 1), this.strip(); + }), + (f.prototype._wordDiv = function (i, a) { + var h2 = this.length - i.length, + s = this.clone(), + u = i, + c = u.words[u.length - 1] | 0, + b2 = this._countBits(c); + (h2 = 26 - b2), h2 !== 0 && ((u = u.ushln(h2)), s.iushln(h2), (c = u.words[u.length - 1] | 0)); + var l = s.length - u.length, + n; + if (a !== 'mod') { + (n = new f(null)), (n.length = l + 1), (n.words = new Array(n.length)); + for (var d = 0; d < n.length; d++) n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && ((s = w), n && (n.words[l] = 1)); + for (var g = l - 1; g >= 0; g--) { + var _2 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_2 = Math.min((_2 / c) | 0, 67108863), s._ishlnsubmul(u, _2, g); s.negative !== 0; ) _2--, (s.negative = 0), s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _2); + } + return n && n.strip(), s.strip(), a !== 'div' && h2 !== 0 && s.iushrn(h2), {div: n || null, mod: s}; + }), + (f.prototype.divmod = function (i, a, h2) { + if ((r(!i.isZero()), this.isZero())) return {div: new f(0), mod: new f(0)}; + var s, u, c; + return this.negative !== 0 && i.negative === 0 + ? ((c = this.neg().divmod(i, a)), a !== 'mod' && (s = c.div.neg()), a !== 'div' && ((u = c.mod.neg()), h2 && u.negative !== 0 && u.iadd(i)), {div: s, mod: u}) + : this.negative === 0 && i.negative !== 0 + ? ((c = this.divmod(i.neg(), a)), a !== 'mod' && (s = c.div.neg()), {div: s, mod: c.mod}) + : (this.negative & i.negative) !== 0 + ? ((c = this.neg().divmod(i.neg(), a)), a !== 'div' && ((u = c.mod.neg()), h2 && u.negative !== 0 && u.isub(i)), {div: c.div, mod: u}) + : i.length > this.length || this.cmp(i) < 0 + ? {div: new f(0), mod: this} + : i.length === 1 + ? a === 'div' + ? {div: this.divn(i.words[0]), mod: null} + : a === 'mod' + ? {div: null, mod: new f(this.modn(i.words[0]))} + : {div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0]))} + : this._wordDiv(i, a); + }), + (f.prototype.div = function (i) { + return this.divmod(i, 'div', false).div; + }), + (f.prototype.mod = function (i) { + return this.divmod(i, 'mod', false).mod; + }), + (f.prototype.umod = function (i) { + return this.divmod(i, 'mod', true).mod; + }), + (f.prototype.divRound = function (i) { + var a = this.divmod(i); + if (a.mod.isZero()) return a.div; + var h2 = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, + s = i.ushrn(1), + u = i.andln(1), + c = h2.cmp(s); + return c < 0 || (u === 1 && c === 0) ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }), + (f.prototype.modn = function (i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h2 = 0, s = this.length - 1; s >= 0; s--) h2 = (a * h2 + (this.words[s] | 0)) % i; + return h2; + }), + (f.prototype.idivn = function (i) { + r(i <= 67108863); + for (var a = 0, h2 = this.length - 1; h2 >= 0; h2--) { + var s = (this.words[h2] | 0) + a * 67108864; + (this.words[h2] = (s / i) | 0), (a = s % i); + } + return this.strip(); + }), + (f.prototype.divn = function (i) { + return this.clone().idivn(i); + }), + (f.prototype.egcd = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h2 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = new f(0), b2 = new f(1), l = 0; a.isEven() && h2.isEven(); ) a.iushrn(1), h2.iushrn(1), ++l; + for (var n = h2.clone(), d = a.clone(); !a.isZero(); ) { + for (var w = 0, g = 1; (a.words[0] & g) === 0 && w < 26; ++w, g <<= 1); + if (w > 0) for (a.iushrn(w); w-- > 0; ) (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _2 = 0, A2 = 1; (h2.words[0] & A2) === 0 && _2 < 26; ++_2, A2 <<= 1); + if (_2 > 0) for (h2.iushrn(_2); _2-- > 0; ) (c.isOdd() || b2.isOdd()) && (c.iadd(n), b2.isub(d)), c.iushrn(1), b2.iushrn(1); + a.cmp(h2) >= 0 ? (a.isub(h2), s.isub(c), u.isub(b2)) : (h2.isub(a), c.isub(s), b2.isub(u)); + } + return {a: c, b: b2, gcd: h2.iushln(l)}; + }), + (f.prototype._invmp = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h2 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = h2.clone(); a.cmpn(1) > 0 && h2.cmpn(1) > 0; ) { + for (var b2 = 0, l = 1; (a.words[0] & l) === 0 && b2 < 26; ++b2, l <<= 1); + if (b2 > 0) for (a.iushrn(b2); b2-- > 0; ) s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1; (h2.words[0] & d) === 0 && n < 26; ++n, d <<= 1); + if (n > 0) for (h2.iushrn(n); n-- > 0; ) u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h2) >= 0 ? (a.isub(h2), s.isub(u)) : (h2.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? (w = s) : (w = u), w.cmpn(0) < 0 && w.iadd(i), w; + }), + (f.prototype.gcd = function (i) { + if (this.isZero()) return i.abs(); + if (i.isZero()) return this.abs(); + var a = this.clone(), + h2 = i.clone(); + (a.negative = 0), (h2.negative = 0); + for (var s = 0; a.isEven() && h2.isEven(); s++) a.iushrn(1), h2.iushrn(1); + do { + for (; a.isEven(); ) a.iushrn(1); + for (; h2.isEven(); ) h2.iushrn(1); + var u = a.cmp(h2); + if (u < 0) { + var c = a; + (a = h2), (h2 = c); + } else if (u === 0 || h2.cmpn(1) === 0) break; + a.isub(h2); + } while (true); + return h2.iushln(s); + }), + (f.prototype.invm = function (i) { + return this.egcd(i).a.umod(i); + }), + (f.prototype.isEven = function () { + return (this.words[0] & 1) === 0; + }), + (f.prototype.isOdd = function () { + return (this.words[0] & 1) === 1; + }), + (f.prototype.andln = function (i) { + return this.words[0] & i; + }), + (f.prototype.bincn = function (i) { + r(typeof i == 'number'); + var a = i % 26, + h2 = (i - a) / 26, + s = 1 << a; + if (this.length <= h2) return this._expand(h2 + 1), (this.words[h2] |= s), this; + for (var u = s, c = h2; u !== 0 && c < this.length; c++) { + var b2 = this.words[c] | 0; + (b2 += u), (u = b2 >>> 26), (b2 &= 67108863), (this.words[c] = b2); + } + return u !== 0 && ((this.words[c] = u), this.length++), this; + }), + (f.prototype.isZero = function () { + return this.length === 1 && this.words[0] === 0; + }), + (f.prototype.cmpn = function (i) { + var a = i < 0; + if (this.negative !== 0 && !a) return -1; + if (this.negative === 0 && a) return 1; + this.strip(); + var h2; + if (this.length > 1) h2 = 1; + else { + a && (i = -i), r(i <= 67108863, 'Number is too big'); + var s = this.words[0] | 0; + h2 = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h2 | 0 : h2; + }), + (f.prototype.cmp = function (i) { + if (this.negative !== 0 && i.negative === 0) return -1; + if (this.negative === 0 && i.negative !== 0) return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }), + (f.prototype.ucmp = function (i) { + if (this.length > i.length) return 1; + if (this.length < i.length) return -1; + for (var a = 0, h2 = this.length - 1; h2 >= 0; h2--) { + var s = this.words[h2] | 0, + u = i.words[h2] | 0; + if (s !== u) { + s < u ? (a = -1) : s > u && (a = 1); + break; + } + } + return a; + }), + (f.prototype.gtn = function (i) { + return this.cmpn(i) === 1; + }), + (f.prototype.gt = function (i) { + return this.cmp(i) === 1; + }), + (f.prototype.gten = function (i) { + return this.cmpn(i) >= 0; + }), + (f.prototype.gte = function (i) { + return this.cmp(i) >= 0; + }), + (f.prototype.ltn = function (i) { + return this.cmpn(i) === -1; + }), + (f.prototype.lt = function (i) { + return this.cmp(i) === -1; + }), + (f.prototype.lten = function (i) { + return this.cmpn(i) <= 0; + }), + (f.prototype.lte = function (i) { + return this.cmp(i) <= 0; + }), + (f.prototype.eqn = function (i) { + return this.cmpn(i) === 0; + }), + (f.prototype.eq = function (i) { + return this.cmp(i) === 0; + }), + (f.red = function (i) { + return new P(i); + }), + (f.prototype.toRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), r(this.negative === 0, 'red works only with positives'), i.convertTo(this)._forceRed(i); + }), + (f.prototype.fromRed = function () { + return r(this.red, 'fromRed works only with numbers in reduction context'), this.red.convertFrom(this); + }), + (f.prototype._forceRed = function (i) { + return (this.red = i), this; + }), + (f.prototype.forceRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), this._forceRed(i); + }), + (f.prototype.redAdd = function (i) { + return r(this.red, 'redAdd works only with red numbers'), this.red.add(this, i); + }), + (f.prototype.redIAdd = function (i) { + return r(this.red, 'redIAdd works only with red numbers'), this.red.iadd(this, i); + }), + (f.prototype.redSub = function (i) { + return r(this.red, 'redSub works only with red numbers'), this.red.sub(this, i); + }), + (f.prototype.redISub = function (i) { + return r(this.red, 'redISub works only with red numbers'), this.red.isub(this, i); + }), + (f.prototype.redShl = function (i) { + return r(this.red, 'redShl works only with red numbers'), this.red.shl(this, i); + }), + (f.prototype.redMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.mul(this, i); + }), + (f.prototype.redIMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.imul(this, i); + }), + (f.prototype.redSqr = function () { + return r(this.red, 'redSqr works only with red numbers'), this.red._verify1(this), this.red.sqr(this); + }), + (f.prototype.redISqr = function () { + return r(this.red, 'redISqr works only with red numbers'), this.red._verify1(this), this.red.isqr(this); + }), + (f.prototype.redSqrt = function () { + return r(this.red, 'redSqrt works only with red numbers'), this.red._verify1(this), this.red.sqrt(this); + }), + (f.prototype.redInvm = function () { + return r(this.red, 'redInvm works only with red numbers'), this.red._verify1(this), this.red.invm(this); + }), + (f.prototype.redNeg = function () { + return r(this.red, 'redNeg works only with red numbers'), this.red._verify1(this), this.red.neg(this); + }), + (f.prototype.redPow = function (i) { + return r(this.red && !i.red, 'redPow(normalNum)'), this.red._verify1(this), this.red.pow(this, i); + }); + var we = {k256: null, p224: null, p192: null, p25519: null}; + function ye(v, i) { + (this.name = v), (this.p = new f(i, 16)), (this.n = this.p.bitLength()), (this.k = new f(1).iushln(this.n).isub(this.p)), (this.tmp = this._tmp()); + } + (ye.prototype._tmp = function () { + var i = new f(null); + return (i.words = new Array(Math.ceil(this.n / 13))), i; + }), + (ye.prototype.ireduce = function (i) { + var a = i, + h2; + do this.split(a, this.tmp), (a = this.imulK(a)), (a = a.iadd(this.tmp)), (h2 = a.bitLength()); + while (h2 > this.n); + var s = h2 < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? ((a.words[0] = 0), (a.length = 1)) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }), + (ye.prototype.split = function (i, a) { + i.iushrn(this.n, 0, a); + }), + (ye.prototype.imulK = function (i) { + return i.imul(this.k); + }); + function xe() { + ye.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + o(xe, ye), + (xe.prototype.split = function (i, a) { + for (var h2 = 4194303, s = Math.min(i.length, 9), u = 0; u < s; u++) a.words[u] = i.words[u]; + if (((a.length = s), i.length <= 9)) { + (i.words[0] = 0), (i.length = 1); + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h2, u = 10; u < i.length; u++) { + var b2 = i.words[u] | 0; + (i.words[u - 10] = ((b2 & h2) << 4) | (c >>> 22)), (c = b2); + } + (c >>>= 22), (i.words[u - 10] = c), c === 0 && i.length > 10 ? (i.length -= 10) : (i.length -= 9); + }), + (xe.prototype.imulK = function (i) { + (i.words[i.length] = 0), (i.words[i.length + 1] = 0), (i.length += 2); + for (var a = 0, h2 = 0; h2 < i.length; h2++) { + var s = i.words[h2] | 0; + (a += s * 977), (i.words[h2] = a & 67108863), (a = s * 64 + ((a / 67108864) | 0)); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }); + function Re() { + ye.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + o(Re, ye); + function Ee() { + ye.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + o(Ee, ye); + function Ae() { + ye.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + o(Ae, ye), + (Ae.prototype.imulK = function (i) { + for (var a = 0, h2 = 0; h2 < i.length; h2++) { + var s = (i.words[h2] | 0) * 19 + a, + u = s & 67108863; + (s >>>= 26), (i.words[h2] = u), (a = s); + } + return a !== 0 && (i.words[i.length++] = a), i; + }), + (f._prime = function (i) { + if (we[i]) return we[i]; + var a; + if (i === 'k256') a = new xe(); + else if (i === 'p224') a = new Re(); + else if (i === 'p192') a = new Ee(); + else if (i === 'p25519') a = new Ae(); + else throw new Error('Unknown prime ' + i); + return (we[i] = a), a; + }); + function P(v) { + if (typeof v == 'string') { + var i = f._prime(v); + (this.m = i.p), (this.prime = i); + } else r(v.gtn(1), 'modulus must be greater than 1'), (this.m = v), (this.prime = null); + } + (P.prototype._verify1 = function (i) { + r(i.negative === 0, 'red works only with positives'), r(i.red, 'red works only with red numbers'); + }), + (P.prototype._verify2 = function (i, a) { + r((i.negative | a.negative) === 0, 'red works only with positives'), r(i.red && i.red === a.red, 'red works only with red numbers'); + }), + (P.prototype.imod = function (i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }), + (P.prototype.neg = function (i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }), + (P.prototype.add = function (i, a) { + this._verify2(i, a); + var h2 = i.add(a); + return h2.cmp(this.m) >= 0 && h2.isub(this.m), h2._forceRed(this); + }), + (P.prototype.iadd = function (i, a) { + this._verify2(i, a); + var h2 = i.iadd(a); + return h2.cmp(this.m) >= 0 && h2.isub(this.m), h2; + }), + (P.prototype.sub = function (i, a) { + this._verify2(i, a); + var h2 = i.sub(a); + return h2.cmpn(0) < 0 && h2.iadd(this.m), h2._forceRed(this); + }), + (P.prototype.isub = function (i, a) { + this._verify2(i, a); + var h2 = i.isub(a); + return h2.cmpn(0) < 0 && h2.iadd(this.m), h2; + }), + (P.prototype.shl = function (i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }), + (P.prototype.imul = function (i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }), + (P.prototype.mul = function (i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }), + (P.prototype.isqr = function (i) { + return this.imul(i, i.clone()); + }), + (P.prototype.sqr = function (i) { + return this.mul(i, i); + }), + (P.prototype.sqrt = function (i) { + if (i.isZero()) return i.clone(); + var a = this.m.andln(3); + if ((r(a % 2 === 1), a === 3)) { + var h2 = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h2); + } + for (var s = this.m.subn(1), u = 0; !s.isZero() && s.andln(1) === 0; ) u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), + b2 = c.redNeg(), + l = this.m.subn(1).iushrn(1), + n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this); this.pow(n, l).cmp(b2) !== 0; ) n.redIAdd(b2); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _2 = u; g.cmp(c) !== 0; ) { + for (var A2 = g, R2 = 0; A2.cmp(c) !== 0; R2++) A2 = A2.redSqr(); + r(R2 < _2); + var I = this.pow(d, new f(1).iushln(_2 - R2 - 1)); + (w = w.redMul(I)), (d = I.redSqr()), (g = g.redMul(d)), (_2 = R2); + } + return w; + }), + (P.prototype.invm = function (i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? ((a.negative = 0), this.imod(a).redNeg()) : this.imod(a); + }), + (P.prototype.pow = function (i, a) { + if (a.isZero()) return new f(1).toRed(this); + if (a.cmpn(1) === 0) return i.clone(); + var h2 = 4, + s = new Array(1 << h2); + (s[0] = new f(1).toRed(this)), (s[1] = i); + for (var u = 2; u < s.length; u++) s[u] = this.mul(s[u - 1], i); + var c = s[0], + b2 = 0, + l = 0, + n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1; u >= 0; u--) { + for (var d = a.words[u], w = n - 1; w >= 0; w--) { + var g = (d >> w) & 1; + if ((c !== s[0] && (c = this.sqr(c)), g === 0 && b2 === 0)) { + l = 0; + continue; + } + (b2 <<= 1), (b2 |= g), l++, !(l !== h2 && (u !== 0 || w !== 0)) && ((c = this.mul(c, s[b2])), (l = 0), (b2 = 0)); + } + n = 26; + } + return c; + }), + (P.prototype.convertTo = function (i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }), + (P.prototype.convertFrom = function (i) { + var a = i.clone(); + return (a.red = null), a; + }), + (f.mont = function (i) { + return new Se(i); + }); + function Se(v) { + P.call(this, v), + (this.shift = this.m.bitLength()), + this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), + (this.r = new f(1).iushln(this.shift)), + (this.r2 = this.imod(this.r.sqr())), + (this.rinv = this.r._invmp(this.m)), + (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), + (this.minv = this.minv.umod(this.r)), + (this.minv = this.r.sub(this.minv)); + } + o(Se, P), + (Se.prototype.convertTo = function (i) { + return this.imod(i.ushln(this.shift)); + }), + (Se.prototype.convertFrom = function (i) { + var a = this.imod(i.mul(this.rinv)); + return (a.red = null), a; + }), + (Se.prototype.imul = function (i, a) { + if (i.isZero() || a.isZero()) return (i.words[0] = 0), (i.length = 1), i; + var h2 = i.imul(a), + s = h2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h2.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.mul = function (i, a) { + if (i.isZero() || a.isZero()) return new f(0)._forceRed(this); + var h2 = i.mul(a), + s = h2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h2.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.invm = function (i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }); + })(typeof Xu > 'u' || Xu, Gm); + }); + Xm = T2(() => {}); + As = T2(($T, el) => { + var Ju; + el.exports = function (e) { + return Ju || (Ju = new Zi(null)), Ju.generate(e); + }; + function Zi(t) { + this.rand = t; + } + el.exports.Rand = Zi; + Zi.prototype.generate = function (e) { + return this._rand(e); + }; + Zi.prototype._rand = function (e) { + if (this.rand.getBytes) return this.rand.getBytes(e); + for (var r = new Uint8Array(e), o = 0; o < r.length; o++) r[o] = this.rand.getByte(); + return r; + }; + if (typeof self == 'object') + self.crypto && self.crypto.getRandomValues + ? (Zi.prototype._rand = function (e) { + var r = new Uint8Array(e); + return self.crypto.getRandomValues(r), r; + }) + : self.msCrypto && self.msCrypto.getRandomValues + ? (Zi.prototype._rand = function (e) { + var r = new Uint8Array(e); + return self.msCrypto.getRandomValues(r), r; + }) + : typeof window == 'object' && + (Zi.prototype._rand = function () { + throw new Error('Not implemented yet'); + }); + else + try { + if (((Qu = Xm()), typeof Qu.randomBytes != 'function')) throw new Error('Not supported'); + Zi.prototype._rand = function (e) { + return Qu.randomBytes(e); + }; + } catch {} + var Qu; + }); + tl = T2((GT, Jm) => { + var In = Ym(), + Q9 = As(); + function Tn(t) { + this.rand = t || new Q9.Rand(); + } + Jm.exports = Tn; + Tn.create = function (e) { + return new Tn(e); + }; + Tn.prototype._randbelow = function (e) { + var r = e.bitLength(), + o = Math.ceil(r / 8); + do var f = new In(this.rand.generate(o)); + while (f.cmp(e) >= 0); + return f; + }; + Tn.prototype._randrange = function (e, r) { + var o = r.sub(e); + return e.add(this._randbelow(o)); + }; + Tn.prototype.test = function (e, r, o) { + var f = e.bitLength(), + p = In.mont(e), + m2 = new In(1).toRed(p); + r || (r = Math.max(1, (f / 48) | 0)); + for (var y2 = e.subn(1), M = 0; !y2.testn(M); M++); + for (var x = e.shrn(M), S = y2.toRed(p), E2 = true; r > 0; r--) { + var B = this._randrange(new In(2), y2); + o && o(B); + var q2 = B.toRed(p).redPow(x); + if (!(q2.cmp(m2) === 0 || q2.cmp(S) === 0)) { + for (var L2 = 1; L2 < M; L2++) { + if (((q2 = q2.redSqr()), q2.cmp(m2) === 0)) return false; + if (q2.cmp(S) === 0) break; + } + if (L2 === M) return false; + } + } + return E2; + }; + Tn.prototype.getDivisor = function (e, r) { + var o = e.bitLength(), + f = In.mont(e), + p = new In(1).toRed(f); + r || (r = Math.max(1, (o / 48) | 0)); + for (var m2 = e.subn(1), y2 = 0; !m2.testn(y2); y2++); + for (var M = e.shrn(y2), x = m2.toRed(f); r > 0; r--) { + var S = this._randrange(new In(2), m2), + E2 = e.gcd(S); + if (E2.cmpn(1) !== 0) return E2; + var B = S.toRed(f).redPow(M); + if (!(B.cmp(p) === 0 || B.cmp(x) === 0)) { + for (var q2 = 1; q2 < y2; q2++) { + if (((B = B.redSqr()), B.cmp(p) === 0)) return B.fromRed().subn(1).gcd(e); + if (B.cmp(x) === 0) break; + } + if (q2 === y2) return (B = B.redSqr()), B.fromRed().subn(1).gcd(e); + } + } + return false; + }; + }); + ol = T2((ek, tg) => { + var eS = on(); + tg.exports = al; + al.simpleSieve = nl; + al.fermatTest = fl; + var Ht = Yu(), + tS = new Ht(24), + rS = tl(), + Qm = new rS(), + iS = new Ht(1), + il = new Ht(2), + nS = new Ht(5), + YT = new Ht(16), + XT = new Ht(8), + fS = new Ht(10), + aS = new Ht(3), + JT = new Ht(7), + oS = new Ht(11), + eg = new Ht(4), + QT = new Ht(12), + rl = null; + function sS() { + if (rl !== null) return rl; + var t = 1048576, + e = []; + e[0] = 2; + for (var r = 1, o = 3; o < t; o += 2) { + for (var f = Math.ceil(Math.sqrt(o)), p = 0; p < r && e[p] <= f && o % e[p] !== 0; p++); + (r !== p && e[p] <= f) || (e[r++] = o); + } + return (rl = e), e; + } + function nl(t) { + for (var e = sS(), r = 0; r < e.length; r++) if (t.modn(e[r]) === 0) return t.cmpn(e[r]) === 0; + return true; + } + function fl(t) { + var e = Ht.mont(t); + return il.toRed(e).redPow(t.subn(1)).fromRed().cmpn(1) === 0; + } + function al(t, e) { + if (t < 16) return e === 2 || e === 5 ? new Ht([140, 123]) : new Ht([140, 39]); + e = new Ht(e); + for (var r, o; ; ) { + for (r = new Ht(eS(Math.ceil(t / 8))); r.bitLength() > t; ) r.ishrn(1); + if ((r.isEven() && r.iadd(iS), r.testn(1) || r.iadd(il), e.cmp(il))) { + if (!e.cmp(nS)) for (; r.mod(fS).cmp(aS); ) r.iadd(eg); + } else for (; r.mod(tS).cmp(oS); ) r.iadd(eg); + if (((o = r.shrn(1)), nl(o) && nl(r) && fl(o) && fl(r) && Qm.test(o) && Qm.test(r))) return r; + } + } + }); + rg = T2((tk, hS) => { + hS.exports = { + modp1: {gen: '02', prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff'}, + modp2: { + gen: '02', + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff' + }, + modp5: { + gen: '02', + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff' + }, + modp14: { + gen: '02', + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff' + }, + modp15: { + gen: '02', + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff' + }, + modp16: { + gen: '02', + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff' + }, + modp17: { + gen: '02', + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff' + }, + modp18: { + gen: '02', + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff' + } + }; + }); + ag = T2((rk, fg) => { + var yr = Yu(), + uS = tl(), + ig = new uS(), + lS = new yr(24), + dS = new yr(11), + cS = new yr(10), + pS = new yr(3), + vS = new yr(7), + ng = ol(), + bS = on(); + fg.exports = Si; + function mS(t, e) { + return (e = e || 'utf8'), Buffer.isBuffer(t) || (t = new Buffer(t, e)), (this._pub = new yr(t)), this; + } + function gS(t, e) { + return (e = e || 'utf8'), Buffer.isBuffer(t) || (t = new Buffer(t, e)), (this._priv = new yr(t)), this; + } + var Rs = {}; + function yS(t, e) { + var r = e.toString('hex'), + o = [r, t.toString(16)].join('_'); + if (o in Rs) return Rs[o]; + var f = 0; + if (t.isEven() || !ng.simpleSieve || !ng.fermatTest(t) || !ig.test(t)) return (f += 1), r === '02' || r === '05' ? (f += 8) : (f += 4), (Rs[o] = f), f; + ig.test(t.shrn(1)) || (f += 2); + var p; + switch (r) { + case '02': + t.mod(lS).cmp(dS) && (f += 8); + break; + case '05': + (p = t.mod(cS)), p.cmp(pS) && p.cmp(vS) && (f += 8); + break; + default: + f += 4; + } + return (Rs[o] = f), f; + } + function Si(t, e, r) { + this.setGenerator(e), + (this.__prime = new yr(t)), + (this._prime = yr.mont(this.__prime)), + (this._primeLen = t.length), + (this._pub = undefined), + (this._priv = undefined), + (this._primeCode = undefined), + r ? ((this.setPublicKey = mS), (this.setPrivateKey = gS)) : (this._primeCode = 8); + } + Object.defineProperty(Si.prototype, 'verifyError', { + enumerable: true, + get: function () { + return typeof this._primeCode != 'number' && (this._primeCode = yS(this.__prime, this.__gen)), this._primeCode; + } + }); + Si.prototype.generateKeys = function () { + return this._priv || (this._priv = new yr(bS(this._primeLen))), (this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed()), this.getPublicKey(); + }; + Si.prototype.computeSecret = function (t) { + (t = new yr(t)), (t = t.toRed(this._prime)); + var e = t.redPow(this._priv).fromRed(), + r = new Buffer(e.toArray()), + o = this.getPrime(); + if (r.length < o.length) { + var f = new Buffer(o.length - r.length); + f.fill(0), (r = Buffer.concat([f, r])); + } + return r; + }; + Si.prototype.getPublicKey = function (e) { + return Bs(this._pub, e); + }; + Si.prototype.getPrivateKey = function (e) { + return Bs(this._priv, e); + }; + Si.prototype.getPrime = function (t) { + return Bs(this.__prime, t); + }; + Si.prototype.getGenerator = function (t) { + return Bs(this._gen, t); + }; + Si.prototype.setGenerator = function (t, e) { + return (e = e || 'utf8'), Buffer.isBuffer(t) || (t = new Buffer(t, e)), (this.__gen = t), (this._gen = new yr(t)), this; + }; + function Bs(t, e) { + var r = new Buffer(t.toArray()); + return e ? r.toString(e) : r; + } + }); + hg = T2(_f => { + var wS = ol(), + og = rg(), + sl = ag(); + function MS(t) { + var e = new Buffer(og[t].prime, 'hex'), + r = new Buffer(og[t].gen, 'hex'); + return new sl(e, r); + } + var _S = {binary: true, hex: true, base64: true}; + function sg(t, e, r, o) { + return Buffer.isBuffer(e) || _S[e] === undefined + ? sg(t, 'binary', e, r) + : ((e = e || 'binary'), + (o = o || 'binary'), + (r = r || new Buffer([2])), + Buffer.isBuffer(r) || (r = new Buffer(r, o)), + typeof t == 'number' ? new sl(wS(t, r), r, true) : (Buffer.isBuffer(t) || (t = new Buffer(t, e)), new sl(t, r, true))); + } + _f.DiffieHellmanGroup = _f.createDiffieHellmanGroup = _f.getDiffieHellman = MS; + _f.createDiffieHellman = _f.DiffieHellman = sg; + }); + hl = T2((nk, ug) => { + ug.exports = ki().EventEmitter; + }); + pg = T2((fk, cg) => { + function lg(t, e) { + var r = Object.keys(t); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(t); + e && + (o = o.filter(function (f) { + return Object.getOwnPropertyDescriptor(t, f).enumerable; + })), + r.push.apply(r, o); + } + return r; + } + function xS(t) { + for (var e = 1; e < arguments.length; e++) { + var r = arguments[e] != null ? arguments[e] : {}; + e % 2 + ? lg(Object(r), true).forEach(function (o) { + SS(t, o, r[o]); + }) + : Object.getOwnPropertyDescriptors + ? Object.defineProperties(t, Object.getOwnPropertyDescriptors(r)) + : lg(Object(r)).forEach(function (o) { + Object.defineProperty(t, o, Object.getOwnPropertyDescriptor(r, o)); + }); + } + return t; + } + function SS(t, e, r) { + return e in t ? Object.defineProperty(t, e, {value: r, enumerable: true, configurable: true, writable: true}) : (t[e] = r), t; + } + function ES(t, e) { + if (!(t instanceof e)) throw new TypeError('Cannot call a class as a function'); + } + function dg(t, e) { + for (var r = 0; r < e.length; r++) { + var o = e[r]; + (o.enumerable = o.enumerable || false), (o.configurable = true), 'value' in o && (o.writable = true), Object.defineProperty(t, o.key, o); + } + } + function AS(t, e, r) { + return e && dg(t.prototype, e), r && dg(t, r), t; + } + var RS = Ut(), + qs = RS.Buffer, + BS = $f(), + ul = BS.inspect, + qS = (ul && ul.custom) || 'inspect'; + function IS(t, e, r) { + qs.prototype.copy.call(t, e, r); + } + cg.exports = (function () { + function t() { + ES(this, t), (this.head = null), (this.tail = null), (this.length = 0); + } + return ( + AS(t, [ + { + key: 'push', + value: function (r) { + var o = {data: r, next: null}; + this.length > 0 ? (this.tail.next = o) : (this.head = o), (this.tail = o), ++this.length; + } + }, + { + key: 'unshift', + value: function (r) { + var o = {data: r, next: this.head}; + this.length === 0 && (this.tail = o), (this.head = o), ++this.length; + } + }, + { + key: 'shift', + value: function () { + if (this.length !== 0) { + var r = this.head.data; + return this.length === 1 ? (this.head = this.tail = null) : (this.head = this.head.next), --this.length, r; + } + } + }, + { + key: 'clear', + value: function () { + (this.head = this.tail = null), (this.length = 0); + } + }, + { + key: 'join', + value: function (r) { + if (this.length === 0) return ''; + for (var o = this.head, f = '' + o.data; (o = o.next); ) f += r + o.data; + return f; + } + }, + { + key: 'concat', + value: function (r) { + if (this.length === 0) return qs.alloc(0); + for (var o = qs.allocUnsafe(r >>> 0), f = this.head, p = 0; f; ) IS(f.data, o, p), (p += f.data.length), (f = f.next); + return o; + } + }, + { + key: 'consume', + value: function (r, o) { + var f; + return r < this.head.data.length ? ((f = this.head.data.slice(0, r)), (this.head.data = this.head.data.slice(r))) : r === this.head.data.length ? (f = this.shift()) : (f = o ? this._getString(r) : this._getBuffer(r)), f; + } + }, + { + key: 'first', + value: function () { + return this.head.data; + } + }, + { + key: '_getString', + value: function (r) { + var o = this.head, + f = 1, + p = o.data; + for (r -= p.length; (o = o.next); ) { + var m2 = o.data, + y2 = r > m2.length ? m2.length : r; + if ((y2 === m2.length ? (p += m2) : (p += m2.slice(0, r)), (r -= y2), r === 0)) { + y2 === m2.length ? (++f, o.next ? (this.head = o.next) : (this.head = this.tail = null)) : ((this.head = o), (o.data = m2.slice(y2))); + break; + } + ++f; + } + return (this.length -= f), p; + } + }, + { + key: '_getBuffer', + value: function (r) { + var o = qs.allocUnsafe(r), + f = this.head, + p = 1; + for (f.data.copy(o), r -= f.data.length; (f = f.next); ) { + var m2 = f.data, + y2 = r > m2.length ? m2.length : r; + if ((m2.copy(o, o.length - r, 0, y2), (r -= y2), r === 0)) { + y2 === m2.length ? (++p, f.next ? (this.head = f.next) : (this.head = this.tail = null)) : ((this.head = f), (f.data = m2.slice(y2))); + break; + } + ++p; + } + return (this.length -= p), o; + } + }, + { + key: qS, + value: function (r, o) { + return ul(this, xS({}, o, {depth: 0, customInspect: false})); + } + } + ]), + t + ); + })(); + }); + dl = T2((ak, bg) => { + function TS(t, e) { + var r = this, + o = this._readableState && this._readableState.destroyed, + f = this._writableState && this._writableState.destroyed; + return o || f + ? (e ? e(t) : t && (this._writableState ? this._writableState.errorEmitted || ((this._writableState.errorEmitted = true), process.nextTick(ll, this, t)) : process.nextTick(ll, this, t)), this) + : (this._readableState && (this._readableState.destroyed = true), + this._writableState && (this._writableState.destroyed = true), + this._destroy(t || null, function (p) { + !e && p + ? r._writableState + ? r._writableState.errorEmitted + ? process.nextTick(Is, r) + : ((r._writableState.errorEmitted = true), process.nextTick(vg, r, p)) + : process.nextTick(vg, r, p) + : e + ? (process.nextTick(Is, r), e(p)) + : process.nextTick(Is, r); + }), + this); + } + function vg(t, e) { + ll(t, e), Is(t); + } + function Is(t) { + (t._writableState && !t._writableState.emitClose) || (t._readableState && !t._readableState.emitClose) || t.emit('close'); + } + function kS() { + this._readableState && ((this._readableState.destroyed = false), (this._readableState.reading = false), (this._readableState.ended = false), (this._readableState.endEmitted = false)), + this._writableState && + ((this._writableState.destroyed = false), + (this._writableState.ended = false), + (this._writableState.ending = false), + (this._writableState.finalCalled = false), + (this._writableState.prefinished = false), + (this._writableState.finished = false), + (this._writableState.errorEmitted = false)); + } + function ll(t, e) { + t.emit('error', e); + } + function LS(t, e) { + var {_readableState: r, _writableState: o} = t; + (r && r.autoDestroy) || (o && o.autoDestroy) ? t.destroy(e) : t.emit('error', e); + } + bg.exports = {destroy: TS, undestroy: kS, errorOrDestroy: LS}; + }); + kn = T2((ok, yg) => { + function NS(t, e) { + (t.prototype = Object.create(e.prototype)), (t.prototype.constructor = t), (t.__proto__ = e); + } + var gg = {}; + function wr(t, e, r) { + r || (r = Error); + function o(p, m2, y2) { + return typeof e == 'string' ? e : e(p, m2, y2); + } + var f = (function (p) { + NS(m2, p); + function m2(y2, M, x) { + return p.call(this, o(y2, M, x)) || this; + } + return m2; + })(r); + (f.prototype.name = r.name), (f.prototype.code = t), (gg[t] = f); + } + function mg(t, e) { + if (Array.isArray(t)) { + var r = t.length; + return ( + (t = t.map(function (o) { + return String(o); + })), + r > 2 ? 'one of '.concat(e, ' ').concat(t.slice(0, r - 1).join(', '), ', or ') + t[r - 1] : r === 2 ? 'one of '.concat(e, ' ').concat(t[0], ' or ').concat(t[1]) : 'of '.concat(e, ' ').concat(t[0]) + ); + } else return 'of '.concat(e, ' ').concat(String(t)); + } + function DS(t, e, r) { + return t.substr(!r || r < 0 ? 0 : +r, e.length) === e; + } + function PS(t, e, r) { + return (r === undefined || r > t.length) && (r = t.length), t.substring(r - e.length, r) === e; + } + function CS(t, e, r) { + return typeof r != 'number' && (r = 0), r + e.length > t.length ? false : t.indexOf(e, r) !== -1; + } + wr( + 'ERR_INVALID_OPT_VALUE', + function (t, e) { + return 'The value "' + e + '" is invalid for option "' + t + '"'; + }, + TypeError + ); + wr( + 'ERR_INVALID_ARG_TYPE', + function (t, e, r) { + var o; + typeof e == 'string' && DS(e, 'not ') ? ((o = 'must not be'), (e = e.replace(/^not /, ''))) : (o = 'must be'); + var f; + if (PS(t, ' argument')) f = 'The '.concat(t, ' ').concat(o, ' ').concat(mg(e, 'type')); + else { + var p = CS(t, '.') ? 'property' : 'argument'; + f = 'The "'.concat(t, '" ').concat(p, ' ').concat(o, ' ').concat(mg(e, 'type')); + } + return (f += '. Received type '.concat(typeof r)), f; + }, + TypeError + ); + wr('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + wr('ERR_METHOD_NOT_IMPLEMENTED', function (t) { + return 'The ' + t + ' method is not implemented'; + }); + wr('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + wr('ERR_STREAM_DESTROYED', function (t) { + return 'Cannot call ' + t + ' after a stream was destroyed'; + }); + wr('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); + wr('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); + wr('ERR_STREAM_WRITE_AFTER_END', 'write after end'); + wr('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); + wr( + 'ERR_UNKNOWN_ENCODING', + function (t) { + return 'Unknown encoding: ' + t; + }, + TypeError + ); + wr('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + yg.exports.codes = gg; + }); + cl = T2((sk, wg) => { + var OS = kn().codes.ERR_INVALID_OPT_VALUE; + function FS(t, e, r) { + return t.highWaterMark != null ? t.highWaterMark : e ? t[r] : null; + } + function US(t, e, r, o) { + var f = FS(e, o, r); + if (f != null) { + if (!(isFinite(f) && Math.floor(f) === f) || f < 0) { + var p = o ? r : 'highWaterMark'; + throw new OS(p, f); + } + return Math.floor(f); + } + return t.objectMode ? 16 : 16 * 1024; + } + wg.exports = {getHighWaterMark: US}; + }); + bl = T2((hk, Ag) => { + Ag.exports = ut; + function _g(t) { + var e = this; + (this.next = null), + (this.entry = null), + (this.finish = function () { + cE(e, t); + }); + } + var xf; + ut.WritableState = ka; + var zS = {deprecate: G0()}, + xg = hl(), + ks = Ut().Buffer, + HS = global.Uint8Array || function () {}; + function WS(t) { + return ks.from(t); + } + function KS(t) { + return ks.isBuffer(t) || t instanceof HS; + } + var vl = dl(), + jS = cl(), + ZS = jS.getHighWaterMark, + Vi = kn().codes, + VS = Vi.ERR_INVALID_ARG_TYPE, + $S = Vi.ERR_METHOD_NOT_IMPLEMENTED, + GS = Vi.ERR_MULTIPLE_CALLBACK, + YS = Vi.ERR_STREAM_CANNOT_PIPE, + XS = Vi.ERR_STREAM_DESTROYED, + JS = Vi.ERR_STREAM_NULL_VALUES, + QS = Vi.ERR_STREAM_WRITE_AFTER_END, + eE = Vi.ERR_UNKNOWN_ENCODING, + Sf = vl.errorOrDestroy; + Ie()(ut, xg); + function tE() {} + function ka(t, e, r) { + (xf = xf || Ln()), + (t = t || {}), + typeof r != 'boolean' && (r = e instanceof xf), + (this.objectMode = !!t.objectMode), + r && (this.objectMode = this.objectMode || !!t.writableObjectMode), + (this.highWaterMark = ZS(this, t, 'writableHighWaterMark', r)), + (this.finalCalled = false), + (this.needDrain = false), + (this.ending = false), + (this.ended = false), + (this.finished = false), + (this.destroyed = false); + var o = t.decodeStrings === false; + (this.decodeStrings = !o), + (this.defaultEncoding = t.defaultEncoding || 'utf8'), + (this.length = 0), + (this.writing = false), + (this.corked = 0), + (this.sync = true), + (this.bufferProcessing = false), + (this.onwrite = function (f) { + sE(e, f); + }), + (this.writecb = null), + (this.writelen = 0), + (this.bufferedRequest = null), + (this.lastBufferedRequest = null), + (this.pendingcb = 0), + (this.prefinished = false), + (this.errorEmitted = false), + (this.emitClose = t.emitClose !== false), + (this.autoDestroy = !!t.autoDestroy), + (this.bufferedRequestCount = 0), + (this.corkedRequestsFree = new _g(this)); + } + ka.prototype.getBuffer = function () { + for (var e = this.bufferedRequest, r = []; e; ) r.push(e), (e = e.next); + return r; + }; + (function () { + try { + Object.defineProperty(ka.prototype, 'buffer', { + get: zS.deprecate( + function () { + return this.getBuffer(); + }, + '_writableState.buffer is deprecated. Use _writableState.getBuffer instead.', + 'DEP0003' + ) + }); + } catch {} + })(); + var Ts; + typeof Symbol == 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] == 'function' + ? ((Ts = Function.prototype[Symbol.hasInstance]), + Object.defineProperty(ut, Symbol.hasInstance, { + value: function (e) { + return Ts.call(this, e) ? true : this !== ut ? false : e && e._writableState instanceof ka; + } + })) + : (Ts = function (e) { + return e instanceof this; + }); + function ut(t) { + xf = xf || Ln(); + var e = this instanceof xf; + if (!e && !Ts.call(ut, this)) return new ut(t); + (this._writableState = new ka(t, this, e)), + (this.writable = true), + t && + (typeof t.write == 'function' && (this._write = t.write), + typeof t.writev == 'function' && (this._writev = t.writev), + typeof t.destroy == 'function' && (this._destroy = t.destroy), + typeof t.final == 'function' && (this._final = t.final)), + xg.call(this); + } + ut.prototype.pipe = function () { + Sf(this, new YS()); + }; + function rE(t, e) { + var r = new QS(); + Sf(t, r), process.nextTick(e, r); + } + function iE(t, e, r, o) { + var f; + return r === null ? (f = new JS()) : typeof r != 'string' && !e.objectMode && (f = new VS('chunk', ['string', 'Buffer'], r)), f ? (Sf(t, f), process.nextTick(o, f), false) : true; + } + ut.prototype.write = function (t, e, r) { + var o = this._writableState, + f = false, + p = !o.objectMode && KS(t); + return ( + p && !ks.isBuffer(t) && (t = WS(t)), + typeof e == 'function' && ((r = e), (e = null)), + p ? (e = 'buffer') : e || (e = o.defaultEncoding), + typeof r != 'function' && (r = tE), + o.ending ? rE(this, r) : (p || iE(this, o, t, r)) && (o.pendingcb++, (f = fE(this, o, p, t, e, r))), + f + ); + }; + ut.prototype.cork = function () { + this._writableState.corked++; + }; + ut.prototype.uncork = function () { + var t = this._writableState; + t.corked && (t.corked--, !t.writing && !t.corked && !t.bufferProcessing && t.bufferedRequest && Sg(this, t)); + }; + ut.prototype.setDefaultEncoding = function (e) { + if ((typeof e == 'string' && (e = e.toLowerCase()), !(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((e + '').toLowerCase()) > -1))) throw new eE(e); + return (this._writableState.defaultEncoding = e), this; + }; + Object.defineProperty(ut.prototype, 'writableBuffer', { + enumerable: false, + get: function () { + return this._writableState && this._writableState.getBuffer(); + } + }); + function nE(t, e, r) { + return !t.objectMode && t.decodeStrings !== false && typeof e == 'string' && (e = ks.from(e, r)), e; + } + Object.defineProperty(ut.prototype, 'writableHighWaterMark', { + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } + }); + function fE(t, e, r, o, f, p) { + if (!r) { + var m2 = nE(e, o, f); + o !== m2 && ((r = true), (f = 'buffer'), (o = m2)); + } + var y2 = e.objectMode ? 1 : o.length; + e.length += y2; + var M = e.length < e.highWaterMark; + if ((M || (e.needDrain = true), e.writing || e.corked)) { + var x = e.lastBufferedRequest; + (e.lastBufferedRequest = {chunk: o, encoding: f, isBuf: r, callback: p, next: null}), x ? (x.next = e.lastBufferedRequest) : (e.bufferedRequest = e.lastBufferedRequest), (e.bufferedRequestCount += 1); + } else pl(t, e, false, y2, o, f, p); + return M; + } + function pl(t, e, r, o, f, p, m2) { + (e.writelen = o), (e.writecb = m2), (e.writing = true), (e.sync = true), e.destroyed ? e.onwrite(new XS('write')) : r ? t._writev(f, e.onwrite) : t._write(f, p, e.onwrite), (e.sync = false); + } + function aE(t, e, r, o, f) { + --e.pendingcb, r ? (process.nextTick(f, o), process.nextTick(Ta, t, e), (t._writableState.errorEmitted = true), Sf(t, o)) : (f(o), (t._writableState.errorEmitted = true), Sf(t, o), Ta(t, e)); + } + function oE(t) { + (t.writing = false), (t.writecb = null), (t.length -= t.writelen), (t.writelen = 0); + } + function sE(t, e) { + var r = t._writableState, + o = r.sync, + f = r.writecb; + if (typeof f != 'function') throw new GS(); + if ((oE(r), e)) aE(t, r, o, e, f); + else { + var p = Eg(r) || t.destroyed; + !p && !r.corked && !r.bufferProcessing && r.bufferedRequest && Sg(t, r), o ? process.nextTick(Mg, t, r, p, f) : Mg(t, r, p, f); + } + } + function Mg(t, e, r, o) { + r || hE(t, e), e.pendingcb--, o(), Ta(t, e); + } + function hE(t, e) { + e.length === 0 && e.needDrain && ((e.needDrain = false), t.emit('drain')); + } + function Sg(t, e) { + e.bufferProcessing = true; + var r = e.bufferedRequest; + if (t._writev && r && r.next) { + var o = e.bufferedRequestCount, + f = new Array(o), + p = e.corkedRequestsFree; + p.entry = r; + for (var m2 = 0, y2 = true; r; ) (f[m2] = r), r.isBuf || (y2 = false), (r = r.next), (m2 += 1); + (f.allBuffers = y2), + pl(t, e, true, e.length, f, '', p.finish), + e.pendingcb++, + (e.lastBufferedRequest = null), + p.next ? ((e.corkedRequestsFree = p.next), (p.next = null)) : (e.corkedRequestsFree = new _g(e)), + (e.bufferedRequestCount = 0); + } else { + for (; r; ) { + var {chunk: M, encoding: x, callback: S} = r, + E2 = e.objectMode ? 1 : M.length; + if ((pl(t, e, false, E2, M, x, S), (r = r.next), e.bufferedRequestCount--, e.writing)) break; + } + r === null && (e.lastBufferedRequest = null); + } + (e.bufferedRequest = r), (e.bufferProcessing = false); + } + ut.prototype._write = function (t, e, r) { + r(new $S('_write()')); + }; + ut.prototype._writev = null; + ut.prototype.end = function (t, e, r) { + var o = this._writableState; + return typeof t == 'function' ? ((r = t), (t = null), (e = null)) : typeof e == 'function' && ((r = e), (e = null)), t != null && this.write(t, e), o.corked && ((o.corked = 1), this.uncork()), o.ending || dE(this, o, r), this; + }; + Object.defineProperty(ut.prototype, 'writableLength', { + enumerable: false, + get: function () { + return this._writableState.length; + } + }); + function Eg(t) { + return t.ending && t.length === 0 && t.bufferedRequest === null && !t.finished && !t.writing; + } + function uE(t, e) { + t._final(function (r) { + e.pendingcb--, r && Sf(t, r), (e.prefinished = true), t.emit('prefinish'), Ta(t, e); + }); + } + function lE(t, e) { + !e.prefinished && !e.finalCalled && (typeof t._final == 'function' && !e.destroyed ? (e.pendingcb++, (e.finalCalled = true), process.nextTick(uE, t, e)) : ((e.prefinished = true), t.emit('prefinish'))); + } + function Ta(t, e) { + var r = Eg(e); + if (r && (lE(t, e), e.pendingcb === 0 && ((e.finished = true), t.emit('finish'), e.autoDestroy))) { + var o = t._readableState; + (!o || (o.autoDestroy && o.endEmitted)) && t.destroy(); + } + return r; + } + function dE(t, e, r) { + (e.ending = true), Ta(t, e), r && (e.finished ? process.nextTick(r) : t.once('finish', r)), (e.ended = true), (t.writable = false); + } + function cE(t, e, r) { + var o = t.entry; + for (t.entry = null; o; ) { + var f = o.callback; + e.pendingcb--, f(r), (o = o.next); + } + e.corkedRequestsFree.next = t; + } + Object.defineProperty(ut.prototype, 'destroyed', { + enumerable: false, + get: function () { + return this._writableState === undefined ? false : this._writableState.destroyed; + }, + set: function (e) { + !this._writableState || (this._writableState.destroyed = e); + } + }); + ut.prototype.destroy = vl.destroy; + ut.prototype._undestroy = vl.undestroy; + ut.prototype._destroy = function (t, e) { + e(t); + }; + }); + Ln = T2((uk, Bg) => { + var pE = + Object.keys || + function (t) { + var e = []; + for (var r in t) e.push(r); + return e; + }; + Bg.exports = ti; + var Rg = yl(), + gl = bl(); + Ie()(ti, Rg); + for (ml = pE(gl.prototype), Ls = 0; Ls < ml.length; Ls++) (Ns = ml[Ls]), ti.prototype[Ns] || (ti.prototype[Ns] = gl.prototype[Ns]); + var ml, Ns, Ls; + function ti(t) { + if (!(this instanceof ti)) return new ti(t); + Rg.call(this, t), + gl.call(this, t), + (this.allowHalfOpen = true), + t && (t.readable === false && (this.readable = false), t.writable === false && (this.writable = false), t.allowHalfOpen === false && ((this.allowHalfOpen = false), this.once('end', vE))); + } + Object.defineProperty(ti.prototype, 'writableHighWaterMark', { + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(ti.prototype, 'writableBuffer', { + enumerable: false, + get: function () { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(ti.prototype, 'writableLength', { + enumerable: false, + get: function () { + return this._writableState.length; + } + }); + function vE() { + this._writableState.ended || process.nextTick(bE, this); + } + function bE(t) { + t.end(); + } + Object.defineProperty(ti.prototype, 'destroyed', { + enumerable: false, + get: function () { + return this._readableState === undefined || this._writableState === undefined ? false : this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (e) { + this._readableState === undefined || this._writableState === undefined || ((this._readableState.destroyed = e), (this._writableState.destroyed = e)); + } + }); + }); + Ds = T2((lk, Tg) => { + var qg = kn().codes.ERR_STREAM_PREMATURE_CLOSE; + function mE(t) { + var e = false; + return function () { + if (!e) { + e = true; + for (var r = arguments.length, o = new Array(r), f = 0; f < r; f++) o[f] = arguments[f]; + t.apply(this, o); + } + }; + } + function gE() {} + function yE(t) { + return t.setHeader && typeof t.abort == 'function'; + } + function Ig(t, e, r) { + if (typeof e == 'function') return Ig(t, null, e); + e || (e = {}), (r = mE(r || gE)); + var o = e.readable || (e.readable !== false && t.readable), + f = e.writable || (e.writable !== false && t.writable), + p = function () { + t.writable || y2(); + }, + m2 = t._writableState && t._writableState.finished, + y2 = function () { + (f = false), (m2 = true), o || r.call(t); + }, + M = t._readableState && t._readableState.endEmitted, + x = function () { + (o = false), (M = true), f || r.call(t); + }, + S = function (L2) { + r.call(t, L2); + }, + E2 = function () { + var L2; + if (o && !M) return (!t._readableState || !t._readableState.ended) && (L2 = new qg()), r.call(t, L2); + if (f && !m2) return (!t._writableState || !t._writableState.ended) && (L2 = new qg()), r.call(t, L2); + }, + B = function () { + t.req.on('finish', y2); + }; + return ( + yE(t) ? (t.on('complete', y2), t.on('abort', E2), t.req ? B() : t.on('request', B)) : f && !t._writableState && (t.on('end', p), t.on('close', p)), + t.on('end', x), + t.on('finish', y2), + e.error !== false && t.on('error', S), + t.on('close', E2), + function () { + t.removeListener('complete', y2), + t.removeListener('abort', E2), + t.removeListener('request', B), + t.req && t.req.removeListener('finish', y2), + t.removeListener('end', p), + t.removeListener('close', p), + t.removeListener('finish', y2), + t.removeListener('end', x), + t.removeListener('error', S), + t.removeListener('close', E2); + } + ); + } + Tg.exports = Ig; + }); + Lg = T2((dk, kg) => { + var Ps; + function $i(t, e, r) { + return e in t ? Object.defineProperty(t, e, {value: r, enumerable: true, configurable: true, writable: true}) : (t[e] = r), t; + } + var wE = Ds(), + Gi = Symbol('lastResolve'), + Nn = Symbol('lastReject'), + La = Symbol('error'), + Cs = Symbol('ended'), + Dn = Symbol('lastPromise'), + wl = Symbol('handlePromise'), + Pn = Symbol('stream'); + function Yi(t, e) { + return {value: t, done: e}; + } + function ME(t) { + var e = t[Gi]; + if (e !== null) { + var r = t[Pn].read(); + r !== null && ((t[Dn] = null), (t[Gi] = null), (t[Nn] = null), e(Yi(r, false))); + } + } + function _E(t) { + process.nextTick(ME, t); + } + function xE(t, e) { + return function (r, o) { + t.then(function () { + if (e[Cs]) { + r(Yi(undefined, true)); + return; + } + e[wl](r, o); + }, o); + }; + } + var SE = Object.getPrototypeOf(function () {}), + EE = Object.setPrototypeOf( + ((Ps = { + get stream() { + return this[Pn]; + }, + next: function () { + var e = this, + r = this[La]; + if (r !== null) return Promise.reject(r); + if (this[Cs]) return Promise.resolve(Yi(undefined, true)); + if (this[Pn].destroyed) + return new Promise(function (m2, y2) { + process.nextTick(function () { + e[La] ? y2(e[La]) : m2(Yi(undefined, true)); + }); + }); + var o = this[Dn], + f; + if (o) f = new Promise(xE(o, this)); + else { + var p = this[Pn].read(); + if (p !== null) return Promise.resolve(Yi(p, false)); + f = new Promise(this[wl]); + } + return (this[Dn] = f), f; + } + }), + $i(Ps, Symbol.asyncIterator, function () { + return this; + }), + $i(Ps, 'return', function () { + var e = this; + return new Promise(function (r, o) { + e[Pn].destroy(null, function (f) { + if (f) { + o(f); + return; + } + r(Yi(undefined, true)); + }); + }); + }), + Ps), + SE + ), + AE = function (e) { + var r, + o = Object.create( + EE, + ((r = {}), + $i(r, Pn, {value: e, writable: true}), + $i(r, Gi, {value: null, writable: true}), + $i(r, Nn, {value: null, writable: true}), + $i(r, La, {value: null, writable: true}), + $i(r, Cs, {value: e._readableState.endEmitted, writable: true}), + $i(r, wl, { + value: function (p, m2) { + var y2 = o[Pn].read(); + y2 ? ((o[Dn] = null), (o[Gi] = null), (o[Nn] = null), p(Yi(y2, false))) : ((o[Gi] = p), (o[Nn] = m2)); + }, + writable: true + }), + r) + ); + return ( + (o[Dn] = null), + wE(e, function (f) { + if (f && f.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var p = o[Nn]; + p !== null && ((o[Dn] = null), (o[Gi] = null), (o[Nn] = null), p(f)), (o[La] = f); + return; + } + var m2 = o[Gi]; + m2 !== null && ((o[Dn] = null), (o[Gi] = null), (o[Nn] = null), m2(Yi(undefined, true))), (o[Cs] = true); + }), + e.on('readable', _E.bind(null, o)), + o + ); + }; + kg.exports = AE; + }); + Dg = T2((ck, Ng) => { + Ng.exports = function () { + throw new Error('Readable.from is not available in the browser'); + }; + }); + yl = T2((vk, jg) => { + jg.exports = Oe; + var Ef; + Oe.ReadableState = Fg; + var pk = ki().EventEmitter, + Og = function (e, r) { + return e.listeners(r).length; + }, + Da = hl(), + Os = Ut().Buffer, + RE = global.Uint8Array || function () {}; + function BE(t) { + return Os.from(t); + } + function qE(t) { + return Os.isBuffer(t) || t instanceof RE; + } + var Ml = $f(), + De; + Ml && Ml.debuglog ? (De = Ml.debuglog('stream')) : (De = function () {}); + var IE = pg(), + Bl = dl(), + TE = cl(), + kE = TE.getHighWaterMark, + Fs = kn().codes, + LE = Fs.ERR_INVALID_ARG_TYPE, + NE = Fs.ERR_STREAM_PUSH_AFTER_EOF, + DE = Fs.ERR_METHOD_NOT_IMPLEMENTED, + PE = Fs.ERR_STREAM_UNSHIFT_AFTER_END_EVENT, + Af, + _l, + xl; + Ie()(Oe, Da); + var Na = Bl.errorOrDestroy, + Sl = ['error', 'close', 'destroy', 'pause', 'resume']; + function CE(t, e, r) { + if (typeof t.prependListener == 'function') return t.prependListener(e, r); + !t._events || !t._events[e] ? t.on(e, r) : Array.isArray(t._events[e]) ? t._events[e].unshift(r) : (t._events[e] = [r, t._events[e]]); + } + function Fg(t, e, r) { + (Ef = Ef || Ln()), + (t = t || {}), + typeof r != 'boolean' && (r = e instanceof Ef), + (this.objectMode = !!t.objectMode), + r && (this.objectMode = this.objectMode || !!t.readableObjectMode), + (this.highWaterMark = kE(this, t, 'readableHighWaterMark', r)), + (this.buffer = new IE()), + (this.length = 0), + (this.pipes = null), + (this.pipesCount = 0), + (this.flowing = null), + (this.ended = false), + (this.endEmitted = false), + (this.reading = false), + (this.sync = true), + (this.needReadable = false), + (this.emittedReadable = false), + (this.readableListening = false), + (this.resumeScheduled = false), + (this.paused = true), + (this.emitClose = t.emitClose !== false), + (this.autoDestroy = !!t.autoDestroy), + (this.destroyed = false), + (this.defaultEncoding = t.defaultEncoding || 'utf8'), + (this.awaitDrain = 0), + (this.readingMore = false), + (this.decoder = null), + (this.encoding = null), + t.encoding && (Af || (Af = (Qf(), ur(Jf)).StringDecoder), (this.decoder = new Af(t.encoding)), (this.encoding = t.encoding)); + } + function Oe(t) { + if (((Ef = Ef || Ln()), !(this instanceof Oe))) return new Oe(t); + var e = this instanceof Ef; + (this._readableState = new Fg(t, this, e)), (this.readable = true), t && (typeof t.read == 'function' && (this._read = t.read), typeof t.destroy == 'function' && (this._destroy = t.destroy)), Da.call(this); + } + Object.defineProperty(Oe.prototype, 'destroyed', { + enumerable: false, + get: function () { + return this._readableState === undefined ? false : this._readableState.destroyed; + }, + set: function (e) { + !this._readableState || (this._readableState.destroyed = e); + } + }); + Oe.prototype.destroy = Bl.destroy; + Oe.prototype._undestroy = Bl.undestroy; + Oe.prototype._destroy = function (t, e) { + e(t); + }; + Oe.prototype.push = function (t, e) { + var r = this._readableState, + o; + return r.objectMode ? (o = true) : typeof t == 'string' && ((e = e || r.defaultEncoding), e !== r.encoding && ((t = Os.from(t, e)), (e = '')), (o = true)), Ug(this, t, e, false, o); + }; + Oe.prototype.unshift = function (t) { + return Ug(this, t, null, true, false); + }; + function Ug(t, e, r, o, f) { + De('readableAddChunk', e); + var p = t._readableState; + if (e === null) (p.reading = false), UE(t, p); + else { + var m2; + if ((f || (m2 = OE(p, e)), m2)) Na(t, m2); + else if (p.objectMode || (e && e.length > 0)) + if ((typeof e != 'string' && !p.objectMode && Object.getPrototypeOf(e) !== Os.prototype && (e = BE(e)), o)) p.endEmitted ? Na(t, new PE()) : El(t, p, e, true); + else if (p.ended) Na(t, new NE()); + else { + if (p.destroyed) return false; + (p.reading = false), p.decoder && !r ? ((e = p.decoder.write(e)), p.objectMode || e.length !== 0 ? El(t, p, e, false) : Rl(t, p)) : El(t, p, e, false); + } + else o || ((p.reading = false), Rl(t, p)); + } + return !p.ended && (p.length < p.highWaterMark || p.length === 0); + } + function El(t, e, r, o) { + e.flowing && e.length === 0 && !e.sync ? ((e.awaitDrain = 0), t.emit('data', r)) : ((e.length += e.objectMode ? 1 : r.length), o ? e.buffer.unshift(r) : e.buffer.push(r), e.needReadable && Us(t)), Rl(t, e); + } + function OE(t, e) { + var r; + return !qE(e) && typeof e != 'string' && e !== undefined && !t.objectMode && (r = new LE('chunk', ['string', 'Buffer', 'Uint8Array'], e)), r; + } + Oe.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + Oe.prototype.setEncoding = function (t) { + Af || (Af = (Qf(), ur(Jf)).StringDecoder); + var e = new Af(t); + (this._readableState.decoder = e), (this._readableState.encoding = this._readableState.decoder.encoding); + for (var r = this._readableState.buffer.head, o = ''; r !== null; ) (o += e.write(r.data)), (r = r.next); + return this._readableState.buffer.clear(), o !== '' && this._readableState.buffer.push(o), (this._readableState.length = o.length), this; + }; + var Pg = 1073741824; + function FE(t) { + return t >= Pg ? (t = Pg) : (t--, (t |= t >>> 1), (t |= t >>> 2), (t |= t >>> 4), (t |= t >>> 8), (t |= t >>> 16), t++), t; + } + function Cg(t, e) { + return t <= 0 || (e.length === 0 && e.ended) + ? 0 + : e.objectMode + ? 1 + : t !== t + ? e.flowing && e.length + ? e.buffer.head.data.length + : e.length + : (t > e.highWaterMark && (e.highWaterMark = FE(t)), t <= e.length ? t : e.ended ? e.length : ((e.needReadable = true), 0)); + } + Oe.prototype.read = function (t) { + De('read', t), (t = parseInt(t, 10)); + var e = this._readableState, + r = t; + if ((t !== 0 && (e.emittedReadable = false), t === 0 && e.needReadable && ((e.highWaterMark !== 0 ? e.length >= e.highWaterMark : e.length > 0) || e.ended))) + return De('read: emitReadable', e.length, e.ended), e.length === 0 && e.ended ? Al(this) : Us(this), null; + if (((t = Cg(t, e)), t === 0 && e.ended)) return e.length === 0 && Al(this), null; + var o = e.needReadable; + De('need readable', o), + (e.length === 0 || e.length - t < e.highWaterMark) && ((o = true), De('length less than watermark', o)), + e.ended || e.reading + ? ((o = false), De('reading or ended', o)) + : o && (De('do read'), (e.reading = true), (e.sync = true), e.length === 0 && (e.needReadable = true), this._read(e.highWaterMark), (e.sync = false), e.reading || (t = Cg(r, e))); + var f; + return ( + t > 0 ? (f = Wg(t, e)) : (f = null), + f === null ? ((e.needReadable = e.length <= e.highWaterMark), (t = 0)) : ((e.length -= t), (e.awaitDrain = 0)), + e.length === 0 && (e.ended || (e.needReadable = true), r !== t && e.ended && Al(this)), + f !== null && this.emit('data', f), + f + ); + }; + function UE(t, e) { + if ((De('onEofChunk'), !e.ended)) { + if (e.decoder) { + var r = e.decoder.end(); + r && r.length && (e.buffer.push(r), (e.length += e.objectMode ? 1 : r.length)); + } + (e.ended = true), e.sync ? Us(t) : ((e.needReadable = false), e.emittedReadable || ((e.emittedReadable = true), zg(t))); + } + } + function Us(t) { + var e = t._readableState; + De('emitReadable', e.needReadable, e.emittedReadable), (e.needReadable = false), e.emittedReadable || (De('emitReadable', e.flowing), (e.emittedReadable = true), process.nextTick(zg, t)); + } + function zg(t) { + var e = t._readableState; + De('emitReadable_', e.destroyed, e.length, e.ended), !e.destroyed && (e.length || e.ended) && (t.emit('readable'), (e.emittedReadable = false)), (e.needReadable = !e.flowing && !e.ended && e.length <= e.highWaterMark), ql(t); + } + function Rl(t, e) { + e.readingMore || ((e.readingMore = true), process.nextTick(zE, t, e)); + } + function zE(t, e) { + for (; !e.reading && !e.ended && (e.length < e.highWaterMark || (e.flowing && e.length === 0)); ) { + var r = e.length; + if ((De('maybeReadMore read 0'), t.read(0), r === e.length)) break; + } + e.readingMore = false; + } + Oe.prototype._read = function (t) { + Na(this, new DE('_read()')); + }; + Oe.prototype.pipe = function (t, e) { + var r = this, + o = this._readableState; + switch (o.pipesCount) { + case 0: + o.pipes = t; + break; + case 1: + o.pipes = [o.pipes, t]; + break; + default: + o.pipes.push(t); + break; + } + (o.pipesCount += 1), De('pipe count=%d opts=%j', o.pipesCount, e); + var f = (!e || e.end !== false) && t !== process.stdout && t !== process.stderr, + p = f ? y2 : ge; + o.endEmitted ? process.nextTick(p) : r.once('end', p), t.on('unpipe', m2); + function m2(_e, N) { + De('onunpipe'), _e === r && N && N.hasUnpiped === false && ((N.hasUnpiped = true), S()); + } + function y2() { + De('onend'), t.end(); + } + var M = HE(r); + t.on('drain', M); + var x = false; + function S() { + De('cleanup'), + t.removeListener('close', q2), + t.removeListener('finish', L2), + t.removeListener('drain', M), + t.removeListener('error', B), + t.removeListener('unpipe', m2), + r.removeListener('end', y2), + r.removeListener('end', ge), + r.removeListener('data', E2), + (x = true), + o.awaitDrain && (!t._writableState || t._writableState.needDrain) && M(); + } + r.on('data', E2); + function E2(_e) { + De('ondata'); + var N = t.write(_e); + De('dest.write', N), N === false && (((o.pipesCount === 1 && o.pipes === t) || (o.pipesCount > 1 && Kg(o.pipes, t) !== -1)) && !x && (De('false write response, pause', o.awaitDrain), o.awaitDrain++), r.pause()); + } + function B(_e) { + De('onerror', _e), ge(), t.removeListener('error', B), Og(t, 'error') === 0 && Na(t, _e); + } + CE(t, 'error', B); + function q2() { + t.removeListener('finish', L2), ge(); + } + t.once('close', q2); + function L2() { + De('onfinish'), t.removeListener('close', q2), ge(); + } + t.once('finish', L2); + function ge() { + De('unpipe'), r.unpipe(t); + } + return t.emit('pipe', r), o.flowing || (De('pipe resume'), r.resume()), t; + }; + function HE(t) { + return function () { + var r = t._readableState; + De('pipeOnDrain', r.awaitDrain), r.awaitDrain && r.awaitDrain--, r.awaitDrain === 0 && Og(t, 'data') && ((r.flowing = true), ql(t)); + }; + } + Oe.prototype.unpipe = function (t) { + var e = this._readableState, + r = {hasUnpiped: false}; + if (e.pipesCount === 0) return this; + if (e.pipesCount === 1) return t && t !== e.pipes ? this : (t || (t = e.pipes), (e.pipes = null), (e.pipesCount = 0), (e.flowing = false), t && t.emit('unpipe', this, r), this); + if (!t) { + var {pipes: o, pipesCount: f} = e; + (e.pipes = null), (e.pipesCount = 0), (e.flowing = false); + for (var p = 0; p < f; p++) o[p].emit('unpipe', this, {hasUnpiped: false}); + return this; + } + var m2 = Kg(e.pipes, t); + return m2 === -1 ? this : (e.pipes.splice(m2, 1), (e.pipesCount -= 1), e.pipesCount === 1 && (e.pipes = e.pipes[0]), t.emit('unpipe', this, r), this); + }; + Oe.prototype.on = function (t, e) { + var r = Da.prototype.on.call(this, t, e), + o = this._readableState; + return ( + t === 'data' + ? ((o.readableListening = this.listenerCount('readable') > 0), o.flowing !== false && this.resume()) + : t === 'readable' && + !o.endEmitted && + !o.readableListening && + ((o.readableListening = o.needReadable = true), (o.flowing = false), (o.emittedReadable = false), De('on readable', o.length, o.reading), o.length ? Us(this) : o.reading || process.nextTick(WE, this)), + r + ); + }; + Oe.prototype.addListener = Oe.prototype.on; + Oe.prototype.removeListener = function (t, e) { + var r = Da.prototype.removeListener.call(this, t, e); + return t === 'readable' && process.nextTick(Hg, this), r; + }; + Oe.prototype.removeAllListeners = function (t) { + var e = Da.prototype.removeAllListeners.apply(this, arguments); + return (t === 'readable' || t === undefined) && process.nextTick(Hg, this), e; + }; + function Hg(t) { + var e = t._readableState; + (e.readableListening = t.listenerCount('readable') > 0), e.resumeScheduled && !e.paused ? (e.flowing = true) : t.listenerCount('data') > 0 && t.resume(); + } + function WE(t) { + De('readable nexttick read 0'), t.read(0); + } + Oe.prototype.resume = function () { + var t = this._readableState; + return t.flowing || (De('resume'), (t.flowing = !t.readableListening), KE(this, t)), (t.paused = false), this; + }; + function KE(t, e) { + e.resumeScheduled || ((e.resumeScheduled = true), process.nextTick(jE, t, e)); + } + function jE(t, e) { + De('resume', e.reading), e.reading || t.read(0), (e.resumeScheduled = false), t.emit('resume'), ql(t), e.flowing && !e.reading && t.read(0); + } + Oe.prototype.pause = function () { + return De('call pause flowing=%j', this._readableState.flowing), this._readableState.flowing !== false && (De('pause'), (this._readableState.flowing = false), this.emit('pause')), (this._readableState.paused = true), this; + }; + function ql(t) { + var e = t._readableState; + for (De('flow', e.flowing); e.flowing && t.read() !== null; ); + } + Oe.prototype.wrap = function (t) { + var e = this, + r = this._readableState, + o = false; + t.on('end', function () { + if ((De('wrapped end'), r.decoder && !r.ended)) { + var m2 = r.decoder.end(); + m2 && m2.length && e.push(m2); + } + e.push(null); + }), + t.on('data', function (m2) { + if ((De('wrapped data'), r.decoder && (m2 = r.decoder.write(m2)), !(r.objectMode && m2 == null) && !(!r.objectMode && (!m2 || !m2.length)))) { + var y2 = e.push(m2); + y2 || ((o = true), t.pause()); + } + }); + for (var f in t) + this[f] === undefined && + typeof t[f] == 'function' && + (this[f] = (function (y2) { + return function () { + return t[y2].apply(t, arguments); + }; + })(f)); + for (var p = 0; p < Sl.length; p++) t.on(Sl[p], this.emit.bind(this, Sl[p])); + return ( + (this._read = function (m2) { + De('wrapped _read', m2), o && ((o = false), t.resume()); + }), + this + ); + }; + typeof Symbol == 'function' && + (Oe.prototype[Symbol.asyncIterator] = function () { + return _l === undefined && (_l = Lg()), _l(this); + }); + Object.defineProperty(Oe.prototype, 'readableHighWaterMark', { + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Oe.prototype, 'readableBuffer', { + enumerable: false, + get: function () { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Oe.prototype, 'readableFlowing', { + enumerable: false, + get: function () { + return this._readableState.flowing; + }, + set: function (e) { + this._readableState && (this._readableState.flowing = e); + } + }); + Oe._fromList = Wg; + Object.defineProperty(Oe.prototype, 'readableLength', { + enumerable: false, + get: function () { + return this._readableState.length; + } + }); + function Wg(t, e) { + if (e.length === 0) return null; + var r; + return ( + e.objectMode + ? (r = e.buffer.shift()) + : !t || t >= e.length + ? (e.decoder ? (r = e.buffer.join('')) : e.buffer.length === 1 ? (r = e.buffer.first()) : (r = e.buffer.concat(e.length)), e.buffer.clear()) + : (r = e.buffer.consume(t, e.decoder)), + r + ); + } + function Al(t) { + var e = t._readableState; + De('endReadable', e.endEmitted), e.endEmitted || ((e.ended = true), process.nextTick(ZE, e, t)); + } + function ZE(t, e) { + if ((De('endReadableNT', t.endEmitted, t.length), !t.endEmitted && t.length === 0 && ((t.endEmitted = true), (e.readable = false), e.emit('end'), t.autoDestroy))) { + var r = e._writableState; + (!r || (r.autoDestroy && r.finished)) && e.destroy(); + } + } + typeof Symbol == 'function' && + (Oe.from = function (t, e) { + return xl === undefined && (xl = Dg()), xl(Oe, t, e); + }); + function Kg(t, e) { + for (var r = 0, o = t.length; r < o; r++) if (t[r] === e) return r; + return -1; + } + }); + Il = T2((bk, Vg) => { + Vg.exports = Ei; + var zs = kn().codes, + VE = zs.ERR_METHOD_NOT_IMPLEMENTED, + $E = zs.ERR_MULTIPLE_CALLBACK, + GE = zs.ERR_TRANSFORM_ALREADY_TRANSFORMING, + YE = zs.ERR_TRANSFORM_WITH_LENGTH_0, + Hs = Ln(); + Ie()(Ei, Hs); + function XE(t, e) { + var r = this._transformState; + r.transforming = false; + var o = r.writecb; + if (o === null) return this.emit('error', new $E()); + (r.writechunk = null), (r.writecb = null), e != null && this.push(e), o(t); + var f = this._readableState; + (f.reading = false), (f.needReadable || f.length < f.highWaterMark) && this._read(f.highWaterMark); + } + function Ei(t) { + if (!(this instanceof Ei)) return new Ei(t); + Hs.call(this, t), + (this._transformState = {afterTransform: XE.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null}), + (this._readableState.needReadable = true), + (this._readableState.sync = false), + t && (typeof t.transform == 'function' && (this._transform = t.transform), typeof t.flush == 'function' && (this._flush = t.flush)), + this.on('prefinish', JE); + } + function JE() { + var t = this; + typeof this._flush == 'function' && !this._readableState.destroyed + ? this._flush(function (e, r) { + Zg(t, e, r); + }) + : Zg(this, null, null); + } + Ei.prototype.push = function (t, e) { + return (this._transformState.needTransform = false), Hs.prototype.push.call(this, t, e); + }; + Ei.prototype._transform = function (t, e, r) { + r(new VE('_transform()')); + }; + Ei.prototype._write = function (t, e, r) { + var o = this._transformState; + if (((o.writecb = r), (o.writechunk = t), (o.writeencoding = e), !o.transforming)) { + var f = this._readableState; + (o.needTransform || f.needReadable || f.length < f.highWaterMark) && this._read(f.highWaterMark); + } + }; + Ei.prototype._read = function (t) { + var e = this._transformState; + e.writechunk !== null && !e.transforming ? ((e.transforming = true), this._transform(e.writechunk, e.writeencoding, e.afterTransform)) : (e.needTransform = true); + }; + Ei.prototype._destroy = function (t, e) { + Hs.prototype._destroy.call(this, t, function (r) { + e(r); + }); + }; + function Zg(t, e, r) { + if (e) return t.emit('error', e); + if ((r != null && t.push(r), t._writableState.length)) throw new YE(); + if (t._transformState.transforming) throw new GE(); + return t.push(null); + } + }); + Yg = T2((mk, Gg) => { + Gg.exports = Pa; + var $g = Il(); + Ie()(Pa, $g); + function Pa(t) { + if (!(this instanceof Pa)) return new Pa(t); + $g.call(this, t); + } + Pa.prototype._transform = function (t, e, r) { + r(null, t); + }; + }); + t2 = T2((gk, e2) => { + var Tl; + function QE(t) { + var e = false; + return function () { + e || ((e = true), t.apply(undefined, arguments)); + }; + } + var Qg = kn().codes, + eA = Qg.ERR_MISSING_ARGS, + tA = Qg.ERR_STREAM_DESTROYED; + function Xg(t) { + if (t) throw t; + } + function rA(t) { + return t.setHeader && typeof t.abort == 'function'; + } + function iA(t, e, r, o) { + o = QE(o); + var f = false; + t.on('close', function () { + f = true; + }), + Tl === undefined && (Tl = Ds()), + Tl(t, {readable: e, writable: r}, function (m2) { + if (m2) return o(m2); + (f = true), o(); + }); + var p = false; + return function (m2) { + if (!f && !p) { + if (((p = true), rA(t))) return t.abort(); + if (typeof t.destroy == 'function') return t.destroy(); + o(m2 || new tA('pipe')); + } + }; + } + function Jg(t) { + t(); + } + function nA(t, e) { + return t.pipe(e); + } + function fA(t) { + return !t.length || typeof t[t.length - 1] != 'function' ? Xg : t.pop(); + } + function aA() { + for (var t = arguments.length, e = new Array(t), r = 0; r < t; r++) e[r] = arguments[r]; + var o = fA(e); + if ((Array.isArray(e[0]) && (e = e[0]), e.length < 2)) throw new eA('streams'); + var f, + p = e.map(function (m2, y2) { + var M = y2 < e.length - 1, + x = y2 > 0; + return iA(m2, M, x, function (S) { + f || (f = S), S && p.forEach(Jg), !M && (p.forEach(Jg), o(f)); + }); + }); + return e.reduce(nA); + } + e2.exports = aA; + }); + i2 = T2((Mr, r2) => { + Mr = r2.exports = yl(); + Mr.Stream = Mr; + Mr.Readable = Mr; + Mr.Writable = bl(); + Mr.Duplex = Ln(); + Mr.Transform = Il(); + Mr.PassThrough = Yg(); + Mr.finished = Ds(); + Mr.pipeline = t2(); + }); + Ws = T2((n2, kl) => { + (function (t, e) { + function r(h2, s) { + if (!h2) throw new Error(s || 'Assertion failed'); + } + function o(h2, s) { + h2.super_ = s; + var u = function () {}; + (u.prototype = s.prototype), (h2.prototype = new u()), (h2.prototype.constructor = h2); + } + function f(h2, s, u) { + if (f.isBN(h2)) return h2; + (this.negative = 0), (this.words = null), (this.length = 0), (this.red = null), h2 !== null && ((s === 'le' || s === 'be') && ((u = s), (s = 10)), this._init(h2 || 0, s || 10, u || 'be')); + } + typeof t == 'object' ? (t.exports = f) : (e.BN = f), (f.BN = f), (f.wordSize = 26); + var p; + try { + typeof window < 'u' && typeof window.Buffer < 'u' ? (p = window.Buffer) : (p = ji().Buffer); + } catch {} + (f.isBN = function (s) { + return s instanceof f ? true : s !== null && typeof s == 'object' && s.constructor.wordSize === f.wordSize && Array.isArray(s.words); + }), + (f.max = function (s, u) { + return s.cmp(u) > 0 ? s : u; + }), + (f.min = function (s, u) { + return s.cmp(u) < 0 ? s : u; + }), + (f.prototype._init = function (s, u, c) { + if (typeof s == 'number') return this._initNumber(s, u, c); + if (typeof s == 'object') return this._initArray(s, u, c); + u === 'hex' && (u = 16), r(u === (u | 0) && u >= 2 && u <= 36), (s = s.toString().replace(/\s+/g, '')); + var b2 = 0; + s[0] === '-' && (b2++, (this.negative = 1)), b2 < s.length && (u === 16 ? this._parseHex(s, b2, c) : (this._parseBase(s, u, b2), c === 'le' && this._initArray(this.toArray(), u, c))); + }), + (f.prototype._initNumber = function (s, u, c) { + s < 0 && ((this.negative = 1), (s = -s)), + s < 67108864 + ? ((this.words = [s & 67108863]), (this.length = 1)) + : s < 4503599627370496 + ? ((this.words = [s & 67108863, (s / 67108864) & 67108863]), (this.length = 2)) + : (r(s < 9007199254740992), (this.words = [s & 67108863, (s / 67108864) & 67108863, 1]), (this.length = 3)), + c === 'le' && this._initArray(this.toArray(), u, c); + }), + (f.prototype._initArray = function (s, u, c) { + if ((r(typeof s.length == 'number'), s.length <= 0)) return (this.words = [0]), (this.length = 1), this; + (this.length = Math.ceil(s.length / 3)), (this.words = new Array(this.length)); + for (var b2 = 0; b2 < this.length; b2++) this.words[b2] = 0; + var l, + n, + d = 0; + if (c === 'be') + for (b2 = s.length - 1, l = 0; b2 >= 0; b2 -= 3) + (n = s[b2] | (s[b2 - 1] << 8) | (s[b2 - 2] << 16)), (this.words[l] |= (n << d) & 67108863), (this.words[l + 1] = (n >>> (26 - d)) & 67108863), (d += 24), d >= 26 && ((d -= 26), l++); + else if (c === 'le') + for (b2 = 0, l = 0; b2 < s.length; b2 += 3) (n = s[b2] | (s[b2 + 1] << 8) | (s[b2 + 2] << 16)), (this.words[l] |= (n << d) & 67108863), (this.words[l + 1] = (n >>> (26 - d)) & 67108863), (d += 24), d >= 26 && ((d -= 26), l++); + return this._strip(); + }); + function m2(h2, s) { + var u = h2.charCodeAt(s); + if (u >= 48 && u <= 57) return u - 48; + if (u >= 65 && u <= 70) return u - 55; + if (u >= 97 && u <= 102) return u - 87; + r(false, 'Invalid character in ' + h2); + } + function y2(h2, s, u) { + var c = m2(h2, u); + return u - 1 >= s && (c |= m2(h2, u - 1) << 4), c; + } + f.prototype._parseHex = function (s, u, c) { + (this.length = Math.ceil((s.length - u) / 6)), (this.words = new Array(this.length)); + for (var b2 = 0; b2 < this.length; b2++) this.words[b2] = 0; + var l = 0, + n = 0, + d; + if (c === 'be') for (b2 = s.length - 1; b2 >= u; b2 -= 2) (d = y2(s, u, b2) << l), (this.words[n] |= d & 67108863), l >= 18 ? ((l -= 18), (n += 1), (this.words[n] |= d >>> 26)) : (l += 8); + else { + var w = s.length - u; + for (b2 = w % 2 === 0 ? u + 1 : u; b2 < s.length; b2 += 2) (d = y2(s, u, b2) << l), (this.words[n] |= d & 67108863), l >= 18 ? ((l -= 18), (n += 1), (this.words[n] |= d >>> 26)) : (l += 8); + } + this._strip(); + }; + function M(h2, s, u, c) { + for (var b2 = 0, l = 0, n = Math.min(h2.length, u), d = s; d < n; d++) { + var w = h2.charCodeAt(d) - 48; + (b2 *= c), w >= 49 ? (l = w - 49 + 10) : w >= 17 ? (l = w - 17 + 10) : (l = w), r(w >= 0 && l < c, 'Invalid character'), (b2 += l); + } + return b2; + } + (f.prototype._parseBase = function (s, u, c) { + (this.words = [0]), (this.length = 1); + for (var b2 = 0, l = 1; l <= 67108863; l *= u) b2++; + b2--, (l = (l / u) | 0); + for (var n = s.length - c, d = n % b2, w = Math.min(n, n - d) + c, g = 0, _2 = c; _2 < w; _2 += b2) (g = M(s, _2, _2 + b2, u)), this.imuln(l), this.words[0] + g < 67108864 ? (this.words[0] += g) : this._iaddn(g); + if (d !== 0) { + var A2 = 1; + for (g = M(s, _2, s.length, u), _2 = 0; _2 < d; _2++) A2 *= u; + this.imuln(A2), this.words[0] + g < 67108864 ? (this.words[0] += g) : this._iaddn(g); + } + this._strip(); + }), + (f.prototype.copy = function (s) { + s.words = new Array(this.length); + for (var u = 0; u < this.length; u++) s.words[u] = this.words[u]; + (s.length = this.length), (s.negative = this.negative), (s.red = this.red); + }); + function x(h2, s) { + (h2.words = s.words), (h2.length = s.length), (h2.negative = s.negative), (h2.red = s.red); + } + if ( + ((f.prototype._move = function (s) { + x(s, this); + }), + (f.prototype.clone = function () { + var s = new f(null); + return this.copy(s), s; + }), + (f.prototype._expand = function (s) { + for (; this.length < s; ) this.words[this.length++] = 0; + return this; + }), + (f.prototype._strip = function () { + for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; + return this._normSign(); + }), + (f.prototype._normSign = function () { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }), + typeof Symbol < 'u' && typeof Symbol.for == 'function') + ) + try { + f.prototype[Symbol.for('nodejs.util.inspect.custom')] = S; + } catch { + f.prototype.inspect = S; + } + else f.prototype.inspect = S; + function S() { + return (this.red ? ''; + } + var E2 = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ], + B = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + q2 = [ + 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, + 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + (f.prototype.toString = function (s, u) { + (s = s || 10), (u = u | 0 || 1); + var c; + if (s === 16 || s === 'hex') { + c = ''; + for (var b2 = 0, l = 0, n = 0; n < this.length; n++) { + var d = this.words[n], + w = (((d << b2) | l) & 16777215).toString(16); + (l = (d >>> (24 - b2)) & 16777215), (b2 += 2), b2 >= 26 && ((b2 -= 26), n--), l !== 0 || n !== this.length - 1 ? (c = E2[6 - w.length] + w + c) : (c = w + c); + } + for (l !== 0 && (c = l.toString(16) + c); c.length % u !== 0; ) c = '0' + c; + return this.negative !== 0 && (c = '-' + c), c; + } + if (s === (s | 0) && s >= 2 && s <= 36) { + var g = B[s], + _2 = q2[s]; + c = ''; + var A2 = this.clone(); + for (A2.negative = 0; !A2.isZero(); ) { + var R2 = A2.modrn(_2).toString(s); + (A2 = A2.idivn(_2)), A2.isZero() ? (c = R2 + c) : (c = E2[g - R2.length] + R2 + c); + } + for (this.isZero() && (c = '0' + c); c.length % u !== 0; ) c = '0' + c; + return this.negative !== 0 && (c = '-' + c), c; + } + r(false, 'Base should be between 2 and 36'); + }), + (f.prototype.toNumber = function () { + var s = this.words[0]; + return ( + this.length === 2 ? (s += this.words[1] * 67108864) : this.length === 3 && this.words[2] === 1 ? (s += 4503599627370496 + this.words[1] * 67108864) : this.length > 2 && r(false, 'Number can only safely store up to 53 bits'), + this.negative !== 0 ? -s : s + ); + }), + (f.prototype.toJSON = function () { + return this.toString(16, 2); + }), + p && + (f.prototype.toBuffer = function (s, u) { + return this.toArrayLike(p, s, u); + }), + (f.prototype.toArray = function (s, u) { + return this.toArrayLike(Array, s, u); + }); + var L2 = function (s, u) { + return s.allocUnsafe ? s.allocUnsafe(u) : new s(u); + }; + (f.prototype.toArrayLike = function (s, u, c) { + this._strip(); + var b2 = this.byteLength(), + l = c || Math.max(1, b2); + r(b2 <= l, 'byte array longer than desired length'), r(l > 0, 'Requested array length <= 0'); + var n = L2(s, l), + d = u === 'le' ? 'LE' : 'BE'; + return this['_toArrayLike' + d](n, b2), n; + }), + (f.prototype._toArrayLikeLE = function (s, u) { + for (var c = 0, b2 = 0, l = 0, n = 0; l < this.length; l++) { + var d = (this.words[l] << n) | b2; + (s[c++] = d & 255), c < s.length && (s[c++] = (d >> 8) & 255), c < s.length && (s[c++] = (d >> 16) & 255), n === 6 ? (c < s.length && (s[c++] = (d >> 24) & 255), (b2 = 0), (n = 0)) : ((b2 = d >>> 24), (n += 2)); + } + if (c < s.length) for (s[c++] = b2; c < s.length; ) s[c++] = 0; + }), + (f.prototype._toArrayLikeBE = function (s, u) { + for (var c = s.length - 1, b2 = 0, l = 0, n = 0; l < this.length; l++) { + var d = (this.words[l] << n) | b2; + (s[c--] = d & 255), c >= 0 && (s[c--] = (d >> 8) & 255), c >= 0 && (s[c--] = (d >> 16) & 255), n === 6 ? (c >= 0 && (s[c--] = (d >> 24) & 255), (b2 = 0), (n = 0)) : ((b2 = d >>> 24), (n += 2)); + } + if (c >= 0) for (s[c--] = b2; c >= 0; ) s[c--] = 0; + }), + Math.clz32 + ? (f.prototype._countBits = function (s) { + return 32 - Math.clz32(s); + }) + : (f.prototype._countBits = function (s) { + var u = s, + c = 0; + return u >= 4096 && ((c += 13), (u >>>= 13)), u >= 64 && ((c += 7), (u >>>= 7)), u >= 8 && ((c += 4), (u >>>= 4)), u >= 2 && ((c += 2), (u >>>= 2)), c + u; + }), + (f.prototype._zeroBits = function (s) { + if (s === 0) return 26; + var u = s, + c = 0; + return (u & 8191) === 0 && ((c += 13), (u >>>= 13)), (u & 127) === 0 && ((c += 7), (u >>>= 7)), (u & 15) === 0 && ((c += 4), (u >>>= 4)), (u & 3) === 0 && ((c += 2), (u >>>= 2)), (u & 1) === 0 && c++, c; + }), + (f.prototype.bitLength = function () { + var s = this.words[this.length - 1], + u = this._countBits(s); + return (this.length - 1) * 26 + u; + }); + function ge(h2) { + for (var s = new Array(h2.bitLength()), u = 0; u < s.length; u++) { + var c = (u / 26) | 0, + b2 = u % 26; + s[u] = (h2.words[c] >>> b2) & 1; + } + return s; + } + (f.prototype.zeroBits = function () { + if (this.isZero()) return 0; + for (var s = 0, u = 0; u < this.length; u++) { + var c = this._zeroBits(this.words[u]); + if (((s += c), c !== 26)) break; + } + return s; + }), + (f.prototype.byteLength = function () { + return Math.ceil(this.bitLength() / 8); + }), + (f.prototype.toTwos = function (s) { + return this.negative !== 0 ? this.abs().inotn(s).iaddn(1) : this.clone(); + }), + (f.prototype.fromTwos = function (s) { + return this.testn(s - 1) ? this.notn(s).iaddn(1).ineg() : this.clone(); + }), + (f.prototype.isNeg = function () { + return this.negative !== 0; + }), + (f.prototype.neg = function () { + return this.clone().ineg(); + }), + (f.prototype.ineg = function () { + return this.isZero() || (this.negative ^= 1), this; + }), + (f.prototype.iuor = function (s) { + for (; this.length < s.length; ) this.words[this.length++] = 0; + for (var u = 0; u < s.length; u++) this.words[u] = this.words[u] | s.words[u]; + return this._strip(); + }), + (f.prototype.ior = function (s) { + return r((this.negative | s.negative) === 0), this.iuor(s); + }), + (f.prototype.or = function (s) { + return this.length > s.length ? this.clone().ior(s) : s.clone().ior(this); + }), + (f.prototype.uor = function (s) { + return this.length > s.length ? this.clone().iuor(s) : s.clone().iuor(this); + }), + (f.prototype.iuand = function (s) { + var u; + this.length > s.length ? (u = s) : (u = this); + for (var c = 0; c < u.length; c++) this.words[c] = this.words[c] & s.words[c]; + return (this.length = u.length), this._strip(); + }), + (f.prototype.iand = function (s) { + return r((this.negative | s.negative) === 0), this.iuand(s); + }), + (f.prototype.and = function (s) { + return this.length > s.length ? this.clone().iand(s) : s.clone().iand(this); + }), + (f.prototype.uand = function (s) { + return this.length > s.length ? this.clone().iuand(s) : s.clone().iuand(this); + }), + (f.prototype.iuxor = function (s) { + var u, c; + this.length > s.length ? ((u = this), (c = s)) : ((u = s), (c = this)); + for (var b2 = 0; b2 < c.length; b2++) this.words[b2] = u.words[b2] ^ c.words[b2]; + if (this !== u) for (; b2 < u.length; b2++) this.words[b2] = u.words[b2]; + return (this.length = u.length), this._strip(); + }), + (f.prototype.ixor = function (s) { + return r((this.negative | s.negative) === 0), this.iuxor(s); + }), + (f.prototype.xor = function (s) { + return this.length > s.length ? this.clone().ixor(s) : s.clone().ixor(this); + }), + (f.prototype.uxor = function (s) { + return this.length > s.length ? this.clone().iuxor(s) : s.clone().iuxor(this); + }), + (f.prototype.inotn = function (s) { + r(typeof s == 'number' && s >= 0); + var u = Math.ceil(s / 26) | 0, + c = s % 26; + this._expand(u), c > 0 && u--; + for (var b2 = 0; b2 < u; b2++) this.words[b2] = ~this.words[b2] & 67108863; + return c > 0 && (this.words[b2] = ~this.words[b2] & (67108863 >> (26 - c))), this._strip(); + }), + (f.prototype.notn = function (s) { + return this.clone().inotn(s); + }), + (f.prototype.setn = function (s, u) { + r(typeof s == 'number' && s >= 0); + var c = (s / 26) | 0, + b2 = s % 26; + return this._expand(c + 1), u ? (this.words[c] = this.words[c] | (1 << b2)) : (this.words[c] = this.words[c] & ~(1 << b2)), this._strip(); + }), + (f.prototype.iadd = function (s) { + var u; + if (this.negative !== 0 && s.negative === 0) return (this.negative = 0), (u = this.isub(s)), (this.negative ^= 1), this._normSign(); + if (this.negative === 0 && s.negative !== 0) return (s.negative = 0), (u = this.isub(s)), (s.negative = 1), u._normSign(); + var c, b2; + this.length > s.length ? ((c = this), (b2 = s)) : ((c = s), (b2 = this)); + for (var l = 0, n = 0; n < b2.length; n++) (u = (c.words[n] | 0) + (b2.words[n] | 0) + l), (this.words[n] = u & 67108863), (l = u >>> 26); + for (; l !== 0 && n < c.length; n++) (u = (c.words[n] | 0) + l), (this.words[n] = u & 67108863), (l = u >>> 26); + if (((this.length = c.length), l !== 0)) (this.words[this.length] = l), this.length++; + else if (c !== this) for (; n < c.length; n++) this.words[n] = c.words[n]; + return this; + }), + (f.prototype.add = function (s) { + var u; + return s.negative !== 0 && this.negative === 0 + ? ((s.negative = 0), (u = this.sub(s)), (s.negative ^= 1), u) + : s.negative === 0 && this.negative !== 0 + ? ((this.negative = 0), (u = s.sub(this)), (this.negative = 1), u) + : this.length > s.length + ? this.clone().iadd(s) + : s.clone().iadd(this); + }), + (f.prototype.isub = function (s) { + if (s.negative !== 0) { + s.negative = 0; + var u = this.iadd(s); + return (s.negative = 1), u._normSign(); + } else if (this.negative !== 0) return (this.negative = 0), this.iadd(s), (this.negative = 1), this._normSign(); + var c = this.cmp(s); + if (c === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; + var b2, l; + c > 0 ? ((b2 = this), (l = s)) : ((b2 = s), (l = this)); + for (var n = 0, d = 0; d < l.length; d++) (u = (b2.words[d] | 0) - (l.words[d] | 0) + n), (n = u >> 26), (this.words[d] = u & 67108863); + for (; n !== 0 && d < b2.length; d++) (u = (b2.words[d] | 0) + n), (n = u >> 26), (this.words[d] = u & 67108863); + if (n === 0 && d < b2.length && b2 !== this) for (; d < b2.length; d++) this.words[d] = b2.words[d]; + return (this.length = Math.max(this.length, d)), b2 !== this && (this.negative = 1), this._strip(); + }), + (f.prototype.sub = function (s) { + return this.clone().isub(s); + }); + function _e(h2, s, u) { + u.negative = s.negative ^ h2.negative; + var c = (h2.length + s.length) | 0; + (u.length = c), (c = (c - 1) | 0); + var b2 = h2.words[0] | 0, + l = s.words[0] | 0, + n = b2 * l, + d = n & 67108863, + w = (n / 67108864) | 0; + u.words[0] = d; + for (var g = 1; g < c; g++) { + for (var _2 = w >>> 26, A2 = w & 67108863, R2 = Math.min(g, s.length - 1), I = Math.max(0, g - h2.length + 1); I <= R2; I++) { + var Me = (g - I) | 0; + (b2 = h2.words[Me] | 0), (l = s.words[I] | 0), (n = b2 * l + A2), (_2 += (n / 67108864) | 0), (A2 = n & 67108863); + } + (u.words[g] = A2 | 0), (w = _2 | 0); + } + return w !== 0 ? (u.words[g] = w | 0) : u.length--, u._strip(); + } + var N = function (s, u, c) { + var b2 = s.words, + l = u.words, + n = c.words, + d = 0, + w, + g, + _2, + A2 = b2[0] | 0, + R2 = A2 & 8191, + I = A2 >>> 13, + Me = b2[1] | 0, + k = Me & 8191, + D2 = Me >>> 13, + nt = b2[2] | 0, + C2 = nt & 8191, + O = nt >>> 13, + vt = b2[3] | 0, + F = vt & 8191, + U = vt >>> 13, + bt = b2[4] | 0, + z2 = bt & 8191, + H = bt >>> 13, + mt = b2[5] | 0, + W = mt & 8191, + K = mt >>> 13, + gt = b2[6] | 0, + j = gt & 8191, + Z = gt >>> 13, + yt = b2[7] | 0, + V = yt & 8191, + $2 = yt >>> 13, + wt = b2[8] | 0, + G = wt & 8191, + Y = wt >>> 13, + Mt = b2[9] | 0, + X = Mt & 8191, + J = Mt >>> 13, + _t = l[0] | 0, + Q = _t & 8191, + ee = _t >>> 13, + xt = l[1] | 0, + te = xt & 8191, + re = xt >>> 13, + St = l[2] | 0, + ie = St & 8191, + ne = St >>> 13, + Et = l[3] | 0, + fe = Et & 8191, + ae = Et >>> 13, + At = l[4] | 0, + oe = At & 8191, + se = At >>> 13, + Rt = l[5] | 0, + he = Rt & 8191, + ue = Rt >>> 13, + Bt = l[6] | 0, + le = Bt & 8191, + de = Bt >>> 13, + qt = l[7] | 0, + ce = qt & 8191, + pe = qt >>> 13, + It = l[8] | 0, + ve = It & 8191, + be = It >>> 13, + ft = l[9] | 0, + Be = ft & 8191, + qe = ft >>> 13; + (c.negative = s.negative ^ u.negative), (c.length = 19), (w = Math.imul(R2, Q)), (g = Math.imul(R2, ee)), (g = (g + Math.imul(I, Q)) | 0), (_2 = Math.imul(I, ee)); + var ze = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (ze >>> 26)) | 0), + (ze &= 67108863), + (w = Math.imul(k, Q)), + (g = Math.imul(k, ee)), + (g = (g + Math.imul(D2, Q)) | 0), + (_2 = Math.imul(D2, ee)), + (w = (w + Math.imul(R2, te)) | 0), + (g = (g + Math.imul(R2, re)) | 0), + (g = (g + Math.imul(I, te)) | 0), + (_2 = (_2 + Math.imul(I, re)) | 0); + var He = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (He >>> 26)) | 0), + (He &= 67108863), + (w = Math.imul(C2, Q)), + (g = Math.imul(C2, ee)), + (g = (g + Math.imul(O, Q)) | 0), + (_2 = Math.imul(O, ee)), + (w = (w + Math.imul(k, te)) | 0), + (g = (g + Math.imul(k, re)) | 0), + (g = (g + Math.imul(D2, te)) | 0), + (_2 = (_2 + Math.imul(D2, re)) | 0), + (w = (w + Math.imul(R2, ie)) | 0), + (g = (g + Math.imul(R2, ne)) | 0), + (g = (g + Math.imul(I, ie)) | 0), + (_2 = (_2 + Math.imul(I, ne)) | 0); + var We = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (We >>> 26)) | 0), + (We &= 67108863), + (w = Math.imul(F, Q)), + (g = Math.imul(F, ee)), + (g = (g + Math.imul(U, Q)) | 0), + (_2 = Math.imul(U, ee)), + (w = (w + Math.imul(C2, te)) | 0), + (g = (g + Math.imul(C2, re)) | 0), + (g = (g + Math.imul(O, te)) | 0), + (_2 = (_2 + Math.imul(O, re)) | 0), + (w = (w + Math.imul(k, ie)) | 0), + (g = (g + Math.imul(k, ne)) | 0), + (g = (g + Math.imul(D2, ie)) | 0), + (_2 = (_2 + Math.imul(D2, ne)) | 0), + (w = (w + Math.imul(R2, fe)) | 0), + (g = (g + Math.imul(R2, ae)) | 0), + (g = (g + Math.imul(I, fe)) | 0), + (_2 = (_2 + Math.imul(I, ae)) | 0); + var Ke = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (Ke >>> 26)) | 0), + (Ke &= 67108863), + (w = Math.imul(z2, Q)), + (g = Math.imul(z2, ee)), + (g = (g + Math.imul(H, Q)) | 0), + (_2 = Math.imul(H, ee)), + (w = (w + Math.imul(F, te)) | 0), + (g = (g + Math.imul(F, re)) | 0), + (g = (g + Math.imul(U, te)) | 0), + (_2 = (_2 + Math.imul(U, re)) | 0), + (w = (w + Math.imul(C2, ie)) | 0), + (g = (g + Math.imul(C2, ne)) | 0), + (g = (g + Math.imul(O, ie)) | 0), + (_2 = (_2 + Math.imul(O, ne)) | 0), + (w = (w + Math.imul(k, fe)) | 0), + (g = (g + Math.imul(k, ae)) | 0), + (g = (g + Math.imul(D2, fe)) | 0), + (_2 = (_2 + Math.imul(D2, ae)) | 0), + (w = (w + Math.imul(R2, oe)) | 0), + (g = (g + Math.imul(R2, se)) | 0), + (g = (g + Math.imul(I, oe)) | 0), + (_2 = (_2 + Math.imul(I, se)) | 0); + var je = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (je >>> 26)) | 0), + (je &= 67108863), + (w = Math.imul(W, Q)), + (g = Math.imul(W, ee)), + (g = (g + Math.imul(K, Q)) | 0), + (_2 = Math.imul(K, ee)), + (w = (w + Math.imul(z2, te)) | 0), + (g = (g + Math.imul(z2, re)) | 0), + (g = (g + Math.imul(H, te)) | 0), + (_2 = (_2 + Math.imul(H, re)) | 0), + (w = (w + Math.imul(F, ie)) | 0), + (g = (g + Math.imul(F, ne)) | 0), + (g = (g + Math.imul(U, ie)) | 0), + (_2 = (_2 + Math.imul(U, ne)) | 0), + (w = (w + Math.imul(C2, fe)) | 0), + (g = (g + Math.imul(C2, ae)) | 0), + (g = (g + Math.imul(O, fe)) | 0), + (_2 = (_2 + Math.imul(O, ae)) | 0), + (w = (w + Math.imul(k, oe)) | 0), + (g = (g + Math.imul(k, se)) | 0), + (g = (g + Math.imul(D2, oe)) | 0), + (_2 = (_2 + Math.imul(D2, se)) | 0), + (w = (w + Math.imul(R2, he)) | 0), + (g = (g + Math.imul(R2, ue)) | 0), + (g = (g + Math.imul(I, he)) | 0), + (_2 = (_2 + Math.imul(I, ue)) | 0); + var Ze = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (Ze >>> 26)) | 0), + (Ze &= 67108863), + (w = Math.imul(j, Q)), + (g = Math.imul(j, ee)), + (g = (g + Math.imul(Z, Q)) | 0), + (_2 = Math.imul(Z, ee)), + (w = (w + Math.imul(W, te)) | 0), + (g = (g + Math.imul(W, re)) | 0), + (g = (g + Math.imul(K, te)) | 0), + (_2 = (_2 + Math.imul(K, re)) | 0), + (w = (w + Math.imul(z2, ie)) | 0), + (g = (g + Math.imul(z2, ne)) | 0), + (g = (g + Math.imul(H, ie)) | 0), + (_2 = (_2 + Math.imul(H, ne)) | 0), + (w = (w + Math.imul(F, fe)) | 0), + (g = (g + Math.imul(F, ae)) | 0), + (g = (g + Math.imul(U, fe)) | 0), + (_2 = (_2 + Math.imul(U, ae)) | 0), + (w = (w + Math.imul(C2, oe)) | 0), + (g = (g + Math.imul(C2, se)) | 0), + (g = (g + Math.imul(O, oe)) | 0), + (_2 = (_2 + Math.imul(O, se)) | 0), + (w = (w + Math.imul(k, he)) | 0), + (g = (g + Math.imul(k, ue)) | 0), + (g = (g + Math.imul(D2, he)) | 0), + (_2 = (_2 + Math.imul(D2, ue)) | 0), + (w = (w + Math.imul(R2, le)) | 0), + (g = (g + Math.imul(R2, de)) | 0), + (g = (g + Math.imul(I, le)) | 0), + (_2 = (_2 + Math.imul(I, de)) | 0); + var Ve = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (Ve >>> 26)) | 0), + (Ve &= 67108863), + (w = Math.imul(V, Q)), + (g = Math.imul(V, ee)), + (g = (g + Math.imul($2, Q)) | 0), + (_2 = Math.imul($2, ee)), + (w = (w + Math.imul(j, te)) | 0), + (g = (g + Math.imul(j, re)) | 0), + (g = (g + Math.imul(Z, te)) | 0), + (_2 = (_2 + Math.imul(Z, re)) | 0), + (w = (w + Math.imul(W, ie)) | 0), + (g = (g + Math.imul(W, ne)) | 0), + (g = (g + Math.imul(K, ie)) | 0), + (_2 = (_2 + Math.imul(K, ne)) | 0), + (w = (w + Math.imul(z2, fe)) | 0), + (g = (g + Math.imul(z2, ae)) | 0), + (g = (g + Math.imul(H, fe)) | 0), + (_2 = (_2 + Math.imul(H, ae)) | 0), + (w = (w + Math.imul(F, oe)) | 0), + (g = (g + Math.imul(F, se)) | 0), + (g = (g + Math.imul(U, oe)) | 0), + (_2 = (_2 + Math.imul(U, se)) | 0), + (w = (w + Math.imul(C2, he)) | 0), + (g = (g + Math.imul(C2, ue)) | 0), + (g = (g + Math.imul(O, he)) | 0), + (_2 = (_2 + Math.imul(O, ue)) | 0), + (w = (w + Math.imul(k, le)) | 0), + (g = (g + Math.imul(k, de)) | 0), + (g = (g + Math.imul(D2, le)) | 0), + (_2 = (_2 + Math.imul(D2, de)) | 0), + (w = (w + Math.imul(R2, ce)) | 0), + (g = (g + Math.imul(R2, pe)) | 0), + (g = (g + Math.imul(I, ce)) | 0), + (_2 = (_2 + Math.imul(I, pe)) | 0); + var $e = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + ($e >>> 26)) | 0), + ($e &= 67108863), + (w = Math.imul(G, Q)), + (g = Math.imul(G, ee)), + (g = (g + Math.imul(Y, Q)) | 0), + (_2 = Math.imul(Y, ee)), + (w = (w + Math.imul(V, te)) | 0), + (g = (g + Math.imul(V, re)) | 0), + (g = (g + Math.imul($2, te)) | 0), + (_2 = (_2 + Math.imul($2, re)) | 0), + (w = (w + Math.imul(j, ie)) | 0), + (g = (g + Math.imul(j, ne)) | 0), + (g = (g + Math.imul(Z, ie)) | 0), + (_2 = (_2 + Math.imul(Z, ne)) | 0), + (w = (w + Math.imul(W, fe)) | 0), + (g = (g + Math.imul(W, ae)) | 0), + (g = (g + Math.imul(K, fe)) | 0), + (_2 = (_2 + Math.imul(K, ae)) | 0), + (w = (w + Math.imul(z2, oe)) | 0), + (g = (g + Math.imul(z2, se)) | 0), + (g = (g + Math.imul(H, oe)) | 0), + (_2 = (_2 + Math.imul(H, se)) | 0), + (w = (w + Math.imul(F, he)) | 0), + (g = (g + Math.imul(F, ue)) | 0), + (g = (g + Math.imul(U, he)) | 0), + (_2 = (_2 + Math.imul(U, ue)) | 0), + (w = (w + Math.imul(C2, le)) | 0), + (g = (g + Math.imul(C2, de)) | 0), + (g = (g + Math.imul(O, le)) | 0), + (_2 = (_2 + Math.imul(O, de)) | 0), + (w = (w + Math.imul(k, ce)) | 0), + (g = (g + Math.imul(k, pe)) | 0), + (g = (g + Math.imul(D2, ce)) | 0), + (_2 = (_2 + Math.imul(D2, pe)) | 0), + (w = (w + Math.imul(R2, ve)) | 0), + (g = (g + Math.imul(R2, be)) | 0), + (g = (g + Math.imul(I, ve)) | 0), + (_2 = (_2 + Math.imul(I, be)) | 0); + var Ge = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (Ge >>> 26)) | 0), + (Ge &= 67108863), + (w = Math.imul(X, Q)), + (g = Math.imul(X, ee)), + (g = (g + Math.imul(J, Q)) | 0), + (_2 = Math.imul(J, ee)), + (w = (w + Math.imul(G, te)) | 0), + (g = (g + Math.imul(G, re)) | 0), + (g = (g + Math.imul(Y, te)) | 0), + (_2 = (_2 + Math.imul(Y, re)) | 0), + (w = (w + Math.imul(V, ie)) | 0), + (g = (g + Math.imul(V, ne)) | 0), + (g = (g + Math.imul($2, ie)) | 0), + (_2 = (_2 + Math.imul($2, ne)) | 0), + (w = (w + Math.imul(j, fe)) | 0), + (g = (g + Math.imul(j, ae)) | 0), + (g = (g + Math.imul(Z, fe)) | 0), + (_2 = (_2 + Math.imul(Z, ae)) | 0), + (w = (w + Math.imul(W, oe)) | 0), + (g = (g + Math.imul(W, se)) | 0), + (g = (g + Math.imul(K, oe)) | 0), + (_2 = (_2 + Math.imul(K, se)) | 0), + (w = (w + Math.imul(z2, he)) | 0), + (g = (g + Math.imul(z2, ue)) | 0), + (g = (g + Math.imul(H, he)) | 0), + (_2 = (_2 + Math.imul(H, ue)) | 0), + (w = (w + Math.imul(F, le)) | 0), + (g = (g + Math.imul(F, de)) | 0), + (g = (g + Math.imul(U, le)) | 0), + (_2 = (_2 + Math.imul(U, de)) | 0), + (w = (w + Math.imul(C2, ce)) | 0), + (g = (g + Math.imul(C2, pe)) | 0), + (g = (g + Math.imul(O, ce)) | 0), + (_2 = (_2 + Math.imul(O, pe)) | 0), + (w = (w + Math.imul(k, ve)) | 0), + (g = (g + Math.imul(k, be)) | 0), + (g = (g + Math.imul(D2, ve)) | 0), + (_2 = (_2 + Math.imul(D2, be)) | 0), + (w = (w + Math.imul(R2, Be)) | 0), + (g = (g + Math.imul(R2, qe)) | 0), + (g = (g + Math.imul(I, Be)) | 0), + (_2 = (_2 + Math.imul(I, qe)) | 0); + var Ye = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (Ye >>> 26)) | 0), + (Ye &= 67108863), + (w = Math.imul(X, te)), + (g = Math.imul(X, re)), + (g = (g + Math.imul(J, te)) | 0), + (_2 = Math.imul(J, re)), + (w = (w + Math.imul(G, ie)) | 0), + (g = (g + Math.imul(G, ne)) | 0), + (g = (g + Math.imul(Y, ie)) | 0), + (_2 = (_2 + Math.imul(Y, ne)) | 0), + (w = (w + Math.imul(V, fe)) | 0), + (g = (g + Math.imul(V, ae)) | 0), + (g = (g + Math.imul($2, fe)) | 0), + (_2 = (_2 + Math.imul($2, ae)) | 0), + (w = (w + Math.imul(j, oe)) | 0), + (g = (g + Math.imul(j, se)) | 0), + (g = (g + Math.imul(Z, oe)) | 0), + (_2 = (_2 + Math.imul(Z, se)) | 0), + (w = (w + Math.imul(W, he)) | 0), + (g = (g + Math.imul(W, ue)) | 0), + (g = (g + Math.imul(K, he)) | 0), + (_2 = (_2 + Math.imul(K, ue)) | 0), + (w = (w + Math.imul(z2, le)) | 0), + (g = (g + Math.imul(z2, de)) | 0), + (g = (g + Math.imul(H, le)) | 0), + (_2 = (_2 + Math.imul(H, de)) | 0), + (w = (w + Math.imul(F, ce)) | 0), + (g = (g + Math.imul(F, pe)) | 0), + (g = (g + Math.imul(U, ce)) | 0), + (_2 = (_2 + Math.imul(U, pe)) | 0), + (w = (w + Math.imul(C2, ve)) | 0), + (g = (g + Math.imul(C2, be)) | 0), + (g = (g + Math.imul(O, ve)) | 0), + (_2 = (_2 + Math.imul(O, be)) | 0), + (w = (w + Math.imul(k, Be)) | 0), + (g = (g + Math.imul(k, qe)) | 0), + (g = (g + Math.imul(D2, Be)) | 0), + (_2 = (_2 + Math.imul(D2, qe)) | 0); + var Xe = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (Xe >>> 26)) | 0), + (Xe &= 67108863), + (w = Math.imul(X, ie)), + (g = Math.imul(X, ne)), + (g = (g + Math.imul(J, ie)) | 0), + (_2 = Math.imul(J, ne)), + (w = (w + Math.imul(G, fe)) | 0), + (g = (g + Math.imul(G, ae)) | 0), + (g = (g + Math.imul(Y, fe)) | 0), + (_2 = (_2 + Math.imul(Y, ae)) | 0), + (w = (w + Math.imul(V, oe)) | 0), + (g = (g + Math.imul(V, se)) | 0), + (g = (g + Math.imul($2, oe)) | 0), + (_2 = (_2 + Math.imul($2, se)) | 0), + (w = (w + Math.imul(j, he)) | 0), + (g = (g + Math.imul(j, ue)) | 0), + (g = (g + Math.imul(Z, he)) | 0), + (_2 = (_2 + Math.imul(Z, ue)) | 0), + (w = (w + Math.imul(W, le)) | 0), + (g = (g + Math.imul(W, de)) | 0), + (g = (g + Math.imul(K, le)) | 0), + (_2 = (_2 + Math.imul(K, de)) | 0), + (w = (w + Math.imul(z2, ce)) | 0), + (g = (g + Math.imul(z2, pe)) | 0), + (g = (g + Math.imul(H, ce)) | 0), + (_2 = (_2 + Math.imul(H, pe)) | 0), + (w = (w + Math.imul(F, ve)) | 0), + (g = (g + Math.imul(F, be)) | 0), + (g = (g + Math.imul(U, ve)) | 0), + (_2 = (_2 + Math.imul(U, be)) | 0), + (w = (w + Math.imul(C2, Be)) | 0), + (g = (g + Math.imul(C2, qe)) | 0), + (g = (g + Math.imul(O, Be)) | 0), + (_2 = (_2 + Math.imul(O, qe)) | 0); + var Je = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (Je >>> 26)) | 0), + (Je &= 67108863), + (w = Math.imul(X, fe)), + (g = Math.imul(X, ae)), + (g = (g + Math.imul(J, fe)) | 0), + (_2 = Math.imul(J, ae)), + (w = (w + Math.imul(G, oe)) | 0), + (g = (g + Math.imul(G, se)) | 0), + (g = (g + Math.imul(Y, oe)) | 0), + (_2 = (_2 + Math.imul(Y, se)) | 0), + (w = (w + Math.imul(V, he)) | 0), + (g = (g + Math.imul(V, ue)) | 0), + (g = (g + Math.imul($2, he)) | 0), + (_2 = (_2 + Math.imul($2, ue)) | 0), + (w = (w + Math.imul(j, le)) | 0), + (g = (g + Math.imul(j, de)) | 0), + (g = (g + Math.imul(Z, le)) | 0), + (_2 = (_2 + Math.imul(Z, de)) | 0), + (w = (w + Math.imul(W, ce)) | 0), + (g = (g + Math.imul(W, pe)) | 0), + (g = (g + Math.imul(K, ce)) | 0), + (_2 = (_2 + Math.imul(K, pe)) | 0), + (w = (w + Math.imul(z2, ve)) | 0), + (g = (g + Math.imul(z2, be)) | 0), + (g = (g + Math.imul(H, ve)) | 0), + (_2 = (_2 + Math.imul(H, be)) | 0), + (w = (w + Math.imul(F, Be)) | 0), + (g = (g + Math.imul(F, qe)) | 0), + (g = (g + Math.imul(U, Be)) | 0), + (_2 = (_2 + Math.imul(U, qe)) | 0); + var Qe = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (Qe >>> 26)) | 0), + (Qe &= 67108863), + (w = Math.imul(X, oe)), + (g = Math.imul(X, se)), + (g = (g + Math.imul(J, oe)) | 0), + (_2 = Math.imul(J, se)), + (w = (w + Math.imul(G, he)) | 0), + (g = (g + Math.imul(G, ue)) | 0), + (g = (g + Math.imul(Y, he)) | 0), + (_2 = (_2 + Math.imul(Y, ue)) | 0), + (w = (w + Math.imul(V, le)) | 0), + (g = (g + Math.imul(V, de)) | 0), + (g = (g + Math.imul($2, le)) | 0), + (_2 = (_2 + Math.imul($2, de)) | 0), + (w = (w + Math.imul(j, ce)) | 0), + (g = (g + Math.imul(j, pe)) | 0), + (g = (g + Math.imul(Z, ce)) | 0), + (_2 = (_2 + Math.imul(Z, pe)) | 0), + (w = (w + Math.imul(W, ve)) | 0), + (g = (g + Math.imul(W, be)) | 0), + (g = (g + Math.imul(K, ve)) | 0), + (_2 = (_2 + Math.imul(K, be)) | 0), + (w = (w + Math.imul(z2, Be)) | 0), + (g = (g + Math.imul(z2, qe)) | 0), + (g = (g + Math.imul(H, Be)) | 0), + (_2 = (_2 + Math.imul(H, qe)) | 0); + var et = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (et >>> 26)) | 0), + (et &= 67108863), + (w = Math.imul(X, he)), + (g = Math.imul(X, ue)), + (g = (g + Math.imul(J, he)) | 0), + (_2 = Math.imul(J, ue)), + (w = (w + Math.imul(G, le)) | 0), + (g = (g + Math.imul(G, de)) | 0), + (g = (g + Math.imul(Y, le)) | 0), + (_2 = (_2 + Math.imul(Y, de)) | 0), + (w = (w + Math.imul(V, ce)) | 0), + (g = (g + Math.imul(V, pe)) | 0), + (g = (g + Math.imul($2, ce)) | 0), + (_2 = (_2 + Math.imul($2, pe)) | 0), + (w = (w + Math.imul(j, ve)) | 0), + (g = (g + Math.imul(j, be)) | 0), + (g = (g + Math.imul(Z, ve)) | 0), + (_2 = (_2 + Math.imul(Z, be)) | 0), + (w = (w + Math.imul(W, Be)) | 0), + (g = (g + Math.imul(W, qe)) | 0), + (g = (g + Math.imul(K, Be)) | 0), + (_2 = (_2 + Math.imul(K, qe)) | 0); + var tt = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (tt >>> 26)) | 0), + (tt &= 67108863), + (w = Math.imul(X, le)), + (g = Math.imul(X, de)), + (g = (g + Math.imul(J, le)) | 0), + (_2 = Math.imul(J, de)), + (w = (w + Math.imul(G, ce)) | 0), + (g = (g + Math.imul(G, pe)) | 0), + (g = (g + Math.imul(Y, ce)) | 0), + (_2 = (_2 + Math.imul(Y, pe)) | 0), + (w = (w + Math.imul(V, ve)) | 0), + (g = (g + Math.imul(V, be)) | 0), + (g = (g + Math.imul($2, ve)) | 0), + (_2 = (_2 + Math.imul($2, be)) | 0), + (w = (w + Math.imul(j, Be)) | 0), + (g = (g + Math.imul(j, qe)) | 0), + (g = (g + Math.imul(Z, Be)) | 0), + (_2 = (_2 + Math.imul(Z, qe)) | 0); + var rt = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (rt >>> 26)) | 0), + (rt &= 67108863), + (w = Math.imul(X, ce)), + (g = Math.imul(X, pe)), + (g = (g + Math.imul(J, ce)) | 0), + (_2 = Math.imul(J, pe)), + (w = (w + Math.imul(G, ve)) | 0), + (g = (g + Math.imul(G, be)) | 0), + (g = (g + Math.imul(Y, ve)) | 0), + (_2 = (_2 + Math.imul(Y, be)) | 0), + (w = (w + Math.imul(V, Be)) | 0), + (g = (g + Math.imul(V, qe)) | 0), + (g = (g + Math.imul($2, Be)) | 0), + (_2 = (_2 + Math.imul($2, qe)) | 0); + var S0 = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (S0 >>> 26)) | 0), + (S0 &= 67108863), + (w = Math.imul(X, ve)), + (g = Math.imul(X, be)), + (g = (g + Math.imul(J, ve)) | 0), + (_2 = Math.imul(J, be)), + (w = (w + Math.imul(G, Be)) | 0), + (g = (g + Math.imul(G, qe)) | 0), + (g = (g + Math.imul(Y, Be)) | 0), + (_2 = (_2 + Math.imul(Y, qe)) | 0); + var E0 = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + (d = (((_2 + (g >>> 13)) | 0) + (E0 >>> 26)) | 0), (E0 &= 67108863), (w = Math.imul(X, Be)), (g = Math.imul(X, qe)), (g = (g + Math.imul(J, Be)) | 0), (_2 = Math.imul(J, qe)); + var A0 = (((d + w) | 0) + ((g & 8191) << 13)) | 0; + return ( + (d = (((_2 + (g >>> 13)) | 0) + (A0 >>> 26)) | 0), + (A0 &= 67108863), + (n[0] = ze), + (n[1] = He), + (n[2] = We), + (n[3] = Ke), + (n[4] = je), + (n[5] = Ze), + (n[6] = Ve), + (n[7] = $e), + (n[8] = Ge), + (n[9] = Ye), + (n[10] = Xe), + (n[11] = Je), + (n[12] = Qe), + (n[13] = et), + (n[14] = tt), + (n[15] = rt), + (n[16] = S0), + (n[17] = E0), + (n[18] = A0), + d !== 0 && ((n[19] = d), c.length++), + c + ); + }; + Math.imul || (N = _e); + function we(h2, s, u) { + (u.negative = s.negative ^ h2.negative), (u.length = h2.length + s.length); + for (var c = 0, b2 = 0, l = 0; l < u.length - 1; l++) { + var n = b2; + b2 = 0; + for (var d = c & 67108863, w = Math.min(l, s.length - 1), g = Math.max(0, l - h2.length + 1); g <= w; g++) { + var _2 = l - g, + A2 = h2.words[_2] | 0, + R2 = s.words[g] | 0, + I = A2 * R2, + Me = I & 67108863; + (n = (n + ((I / 67108864) | 0)) | 0), (Me = (Me + d) | 0), (d = Me & 67108863), (n = (n + (Me >>> 26)) | 0), (b2 += n >>> 26), (n &= 67108863); + } + (u.words[l] = d), (c = n), (n = b2); + } + return c !== 0 ? (u.words[l] = c) : u.length--, u._strip(); + } + function ye(h2, s, u) { + return we(h2, s, u); + } + f.prototype.mulTo = function (s, u) { + var c, + b2 = this.length + s.length; + return this.length === 10 && s.length === 10 ? (c = N(this, s, u)) : b2 < 63 ? (c = _e(this, s, u)) : b2 < 1024 ? (c = we(this, s, u)) : (c = ye(this, s, u)), c; + }; + function xe(h2, s) { + (this.x = h2), (this.y = s); + } + (xe.prototype.makeRBT = function (s) { + for (var u = new Array(s), c = f.prototype._countBits(s) - 1, b2 = 0; b2 < s; b2++) u[b2] = this.revBin(b2, c, s); + return u; + }), + (xe.prototype.revBin = function (s, u, c) { + if (s === 0 || s === c - 1) return s; + for (var b2 = 0, l = 0; l < u; l++) (b2 |= (s & 1) << (u - l - 1)), (s >>= 1); + return b2; + }), + (xe.prototype.permute = function (s, u, c, b2, l, n) { + for (var d = 0; d < n; d++) (b2[d] = u[s[d]]), (l[d] = c[s[d]]); + }), + (xe.prototype.transform = function (s, u, c, b2, l, n) { + this.permute(n, s, u, c, b2, l); + for (var d = 1; d < l; d <<= 1) + for (var w = d << 1, g = Math.cos((2 * Math.PI) / w), _2 = Math.sin((2 * Math.PI) / w), A2 = 0; A2 < l; A2 += w) + for (var R2 = g, I = _2, Me = 0; Me < d; Me++) { + var k = c[A2 + Me], + D2 = b2[A2 + Me], + nt = c[A2 + Me + d], + C2 = b2[A2 + Me + d], + O = R2 * nt - I * C2; + (C2 = R2 * C2 + I * nt), (nt = O), (c[A2 + Me] = k + nt), (b2[A2 + Me] = D2 + C2), (c[A2 + Me + d] = k - nt), (b2[A2 + Me + d] = D2 - C2), Me !== w && ((O = g * R2 - _2 * I), (I = g * I + _2 * R2), (R2 = O)); + } + }), + (xe.prototype.guessLen13b = function (s, u) { + var c = Math.max(u, s) | 1, + b2 = c & 1, + l = 0; + for (c = (c / 2) | 0; c; c = c >>> 1) l++; + return 1 << (l + 1 + b2); + }), + (xe.prototype.conjugate = function (s, u, c) { + if (!(c <= 1)) + for (var b2 = 0; b2 < c / 2; b2++) { + var l = s[b2]; + (s[b2] = s[c - b2 - 1]), (s[c - b2 - 1] = l), (l = u[b2]), (u[b2] = -u[c - b2 - 1]), (u[c - b2 - 1] = -l); + } + }), + (xe.prototype.normalize13b = function (s, u) { + for (var c = 0, b2 = 0; b2 < u / 2; b2++) { + var l = Math.round(s[2 * b2 + 1] / u) * 8192 + Math.round(s[2 * b2] / u) + c; + (s[b2] = l & 67108863), l < 67108864 ? (c = 0) : (c = (l / 67108864) | 0); + } + return s; + }), + (xe.prototype.convert13b = function (s, u, c, b2) { + for (var l = 0, n = 0; n < u; n++) (l = l + (s[n] | 0)), (c[2 * n] = l & 8191), (l = l >>> 13), (c[2 * n + 1] = l & 8191), (l = l >>> 13); + for (n = 2 * u; n < b2; ++n) c[n] = 0; + r(l === 0), r((l & -8192) === 0); + }), + (xe.prototype.stub = function (s) { + for (var u = new Array(s), c = 0; c < s; c++) u[c] = 0; + return u; + }), + (xe.prototype.mulp = function (s, u, c) { + var b2 = 2 * this.guessLen13b(s.length, u.length), + l = this.makeRBT(b2), + n = this.stub(b2), + d = new Array(b2), + w = new Array(b2), + g = new Array(b2), + _2 = new Array(b2), + A2 = new Array(b2), + R2 = new Array(b2), + I = c.words; + (I.length = b2), this.convert13b(s.words, s.length, d, b2), this.convert13b(u.words, u.length, _2, b2), this.transform(d, n, w, g, b2, l), this.transform(_2, n, A2, R2, b2, l); + for (var Me = 0; Me < b2; Me++) { + var k = w[Me] * A2[Me] - g[Me] * R2[Me]; + (g[Me] = w[Me] * R2[Me] + g[Me] * A2[Me]), (w[Me] = k); + } + return this.conjugate(w, g, b2), this.transform(w, g, I, n, b2, l), this.conjugate(I, n, b2), this.normalize13b(I, b2), (c.negative = s.negative ^ u.negative), (c.length = s.length + u.length), c._strip(); + }), + (f.prototype.mul = function (s) { + var u = new f(null); + return (u.words = new Array(this.length + s.length)), this.mulTo(s, u); + }), + (f.prototype.mulf = function (s) { + var u = new f(null); + return (u.words = new Array(this.length + s.length)), ye(this, s, u); + }), + (f.prototype.imul = function (s) { + return this.clone().mulTo(s, this); + }), + (f.prototype.imuln = function (s) { + var u = s < 0; + u && (s = -s), r(typeof s == 'number'), r(s < 67108864); + for (var c = 0, b2 = 0; b2 < this.length; b2++) { + var l = (this.words[b2] | 0) * s, + n = (l & 67108863) + (c & 67108863); + (c >>= 26), (c += (l / 67108864) | 0), (c += n >>> 26), (this.words[b2] = n & 67108863); + } + return c !== 0 && ((this.words[b2] = c), this.length++), u ? this.ineg() : this; + }), + (f.prototype.muln = function (s) { + return this.clone().imuln(s); + }), + (f.prototype.sqr = function () { + return this.mul(this); + }), + (f.prototype.isqr = function () { + return this.imul(this.clone()); + }), + (f.prototype.pow = function (s) { + var u = ge(s); + if (u.length === 0) return new f(1); + for (var c = this, b2 = 0; b2 < u.length && u[b2] === 0; b2++, c = c.sqr()); + if (++b2 < u.length) for (var l = c.sqr(); b2 < u.length; b2++, l = l.sqr()) u[b2] !== 0 && (c = c.mul(l)); + return c; + }), + (f.prototype.iushln = function (s) { + r(typeof s == 'number' && s >= 0); + var u = s % 26, + c = (s - u) / 26, + b2 = (67108863 >>> (26 - u)) << (26 - u), + l; + if (u !== 0) { + var n = 0; + for (l = 0; l < this.length; l++) { + var d = this.words[l] & b2, + w = ((this.words[l] | 0) - d) << u; + (this.words[l] = w | n), (n = d >>> (26 - u)); + } + n && ((this.words[l] = n), this.length++); + } + if (c !== 0) { + for (l = this.length - 1; l >= 0; l--) this.words[l + c] = this.words[l]; + for (l = 0; l < c; l++) this.words[l] = 0; + this.length += c; + } + return this._strip(); + }), + (f.prototype.ishln = function (s) { + return r(this.negative === 0), this.iushln(s); + }), + (f.prototype.iushrn = function (s, u, c) { + r(typeof s == 'number' && s >= 0); + var b2; + u ? (b2 = (u - (u % 26)) / 26) : (b2 = 0); + var l = s % 26, + n = Math.min((s - l) / 26, this.length), + d = 67108863 ^ ((67108863 >>> l) << l), + w = c; + if (((b2 -= n), (b2 = Math.max(0, b2)), w)) { + for (var g = 0; g < n; g++) w.words[g] = this.words[g]; + w.length = n; + } + if (n !== 0) + if (this.length > n) for (this.length -= n, g = 0; g < this.length; g++) this.words[g] = this.words[g + n]; + else (this.words[0] = 0), (this.length = 1); + var _2 = 0; + for (g = this.length - 1; g >= 0 && (_2 !== 0 || g >= b2); g--) { + var A2 = this.words[g] | 0; + (this.words[g] = (_2 << (26 - l)) | (A2 >>> l)), (_2 = A2 & d); + } + return w && _2 !== 0 && (w.words[w.length++] = _2), this.length === 0 && ((this.words[0] = 0), (this.length = 1)), this._strip(); + }), + (f.prototype.ishrn = function (s, u, c) { + return r(this.negative === 0), this.iushrn(s, u, c); + }), + (f.prototype.shln = function (s) { + return this.clone().ishln(s); + }), + (f.prototype.ushln = function (s) { + return this.clone().iushln(s); + }), + (f.prototype.shrn = function (s) { + return this.clone().ishrn(s); + }), + (f.prototype.ushrn = function (s) { + return this.clone().iushrn(s); + }), + (f.prototype.testn = function (s) { + r(typeof s == 'number' && s >= 0); + var u = s % 26, + c = (s - u) / 26, + b2 = 1 << u; + if (this.length <= c) return false; + var l = this.words[c]; + return !!(l & b2); + }), + (f.prototype.imaskn = function (s) { + r(typeof s == 'number' && s >= 0); + var u = s % 26, + c = (s - u) / 26; + if ((r(this.negative === 0, 'imaskn works only with positive numbers'), this.length <= c)) return this; + if ((u !== 0 && c++, (this.length = Math.min(c, this.length)), u !== 0)) { + var b2 = 67108863 ^ ((67108863 >>> u) << u); + this.words[this.length - 1] &= b2; + } + return this._strip(); + }), + (f.prototype.maskn = function (s) { + return this.clone().imaskn(s); + }), + (f.prototype.iaddn = function (s) { + return ( + r(typeof s == 'number'), + r(s < 67108864), + s < 0 + ? this.isubn(-s) + : this.negative !== 0 + ? this.length === 1 && (this.words[0] | 0) <= s + ? ((this.words[0] = s - (this.words[0] | 0)), (this.negative = 0), this) + : ((this.negative = 0), this.isubn(s), (this.negative = 1), this) + : this._iaddn(s) + ); + }), + (f.prototype._iaddn = function (s) { + this.words[0] += s; + for (var u = 0; u < this.length && this.words[u] >= 67108864; u++) (this.words[u] -= 67108864), u === this.length - 1 ? (this.words[u + 1] = 1) : this.words[u + 1]++; + return (this.length = Math.max(this.length, u + 1)), this; + }), + (f.prototype.isubn = function (s) { + if ((r(typeof s == 'number'), r(s < 67108864), s < 0)) return this.iaddn(-s); + if (this.negative !== 0) return (this.negative = 0), this.iaddn(s), (this.negative = 1), this; + if (((this.words[0] -= s), this.length === 1 && this.words[0] < 0)) (this.words[0] = -this.words[0]), (this.negative = 1); + else for (var u = 0; u < this.length && this.words[u] < 0; u++) (this.words[u] += 67108864), (this.words[u + 1] -= 1); + return this._strip(); + }), + (f.prototype.addn = function (s) { + return this.clone().iaddn(s); + }), + (f.prototype.subn = function (s) { + return this.clone().isubn(s); + }), + (f.prototype.iabs = function () { + return (this.negative = 0), this; + }), + (f.prototype.abs = function () { + return this.clone().iabs(); + }), + (f.prototype._ishlnsubmul = function (s, u, c) { + var b2 = s.length + c, + l; + this._expand(b2); + var n, + d = 0; + for (l = 0; l < s.length; l++) { + n = (this.words[l + c] | 0) + d; + var w = (s.words[l] | 0) * u; + (n -= w & 67108863), (d = (n >> 26) - ((w / 67108864) | 0)), (this.words[l + c] = n & 67108863); + } + for (; l < this.length - c; l++) (n = (this.words[l + c] | 0) + d), (d = n >> 26), (this.words[l + c] = n & 67108863); + if (d === 0) return this._strip(); + for (r(d === -1), d = 0, l = 0; l < this.length; l++) (n = -(this.words[l] | 0) + d), (d = n >> 26), (this.words[l] = n & 67108863); + return (this.negative = 1), this._strip(); + }), + (f.prototype._wordDiv = function (s, u) { + var c = this.length - s.length, + b2 = this.clone(), + l = s, + n = l.words[l.length - 1] | 0, + d = this._countBits(n); + (c = 26 - d), c !== 0 && ((l = l.ushln(c)), b2.iushln(c), (n = l.words[l.length - 1] | 0)); + var w = b2.length - l.length, + g; + if (u !== 'mod') { + (g = new f(null)), (g.length = w + 1), (g.words = new Array(g.length)); + for (var _2 = 0; _2 < g.length; _2++) g.words[_2] = 0; + } + var A2 = b2.clone()._ishlnsubmul(l, 1, w); + A2.negative === 0 && ((b2 = A2), g && (g.words[w] = 1)); + for (var R2 = w - 1; R2 >= 0; R2--) { + var I = (b2.words[l.length + R2] | 0) * 67108864 + (b2.words[l.length + R2 - 1] | 0); + for (I = Math.min((I / n) | 0, 67108863), b2._ishlnsubmul(l, I, R2); b2.negative !== 0; ) I--, (b2.negative = 0), b2._ishlnsubmul(l, 1, R2), b2.isZero() || (b2.negative ^= 1); + g && (g.words[R2] = I); + } + return g && g._strip(), b2._strip(), u !== 'div' && c !== 0 && b2.iushrn(c), {div: g || null, mod: b2}; + }), + (f.prototype.divmod = function (s, u, c) { + if ((r(!s.isZero()), this.isZero())) return {div: new f(0), mod: new f(0)}; + var b2, l, n; + return this.negative !== 0 && s.negative === 0 + ? ((n = this.neg().divmod(s, u)), u !== 'mod' && (b2 = n.div.neg()), u !== 'div' && ((l = n.mod.neg()), c && l.negative !== 0 && l.iadd(s)), {div: b2, mod: l}) + : this.negative === 0 && s.negative !== 0 + ? ((n = this.divmod(s.neg(), u)), u !== 'mod' && (b2 = n.div.neg()), {div: b2, mod: n.mod}) + : (this.negative & s.negative) !== 0 + ? ((n = this.neg().divmod(s.neg(), u)), u !== 'div' && ((l = n.mod.neg()), c && l.negative !== 0 && l.isub(s)), {div: n.div, mod: l}) + : s.length > this.length || this.cmp(s) < 0 + ? {div: new f(0), mod: this} + : s.length === 1 + ? u === 'div' + ? {div: this.divn(s.words[0]), mod: null} + : u === 'mod' + ? {div: null, mod: new f(this.modrn(s.words[0]))} + : {div: this.divn(s.words[0]), mod: new f(this.modrn(s.words[0]))} + : this._wordDiv(s, u); + }), + (f.prototype.div = function (s) { + return this.divmod(s, 'div', false).div; + }), + (f.prototype.mod = function (s) { + return this.divmod(s, 'mod', false).mod; + }), + (f.prototype.umod = function (s) { + return this.divmod(s, 'mod', true).mod; + }), + (f.prototype.divRound = function (s) { + var u = this.divmod(s); + if (u.mod.isZero()) return u.div; + var c = u.div.negative !== 0 ? u.mod.isub(s) : u.mod, + b2 = s.ushrn(1), + l = s.andln(1), + n = c.cmp(b2); + return n < 0 || (l === 1 && n === 0) ? u.div : u.div.negative !== 0 ? u.div.isubn(1) : u.div.iaddn(1); + }), + (f.prototype.modrn = function (s) { + var u = s < 0; + u && (s = -s), r(s <= 67108863); + for (var c = (1 << 26) % s, b2 = 0, l = this.length - 1; l >= 0; l--) b2 = (c * b2 + (this.words[l] | 0)) % s; + return u ? -b2 : b2; + }), + (f.prototype.modn = function (s) { + return this.modrn(s); + }), + (f.prototype.idivn = function (s) { + var u = s < 0; + u && (s = -s), r(s <= 67108863); + for (var c = 0, b2 = this.length - 1; b2 >= 0; b2--) { + var l = (this.words[b2] | 0) + c * 67108864; + (this.words[b2] = (l / s) | 0), (c = l % s); + } + return this._strip(), u ? this.ineg() : this; + }), + (f.prototype.divn = function (s) { + return this.clone().idivn(s); + }), + (f.prototype.egcd = function (s) { + r(s.negative === 0), r(!s.isZero()); + var u = this, + c = s.clone(); + u.negative !== 0 ? (u = u.umod(s)) : (u = u.clone()); + for (var b2 = new f(1), l = new f(0), n = new f(0), d = new f(1), w = 0; u.isEven() && c.isEven(); ) u.iushrn(1), c.iushrn(1), ++w; + for (var g = c.clone(), _2 = u.clone(); !u.isZero(); ) { + for (var A2 = 0, R2 = 1; (u.words[0] & R2) === 0 && A2 < 26; ++A2, R2 <<= 1); + if (A2 > 0) for (u.iushrn(A2); A2-- > 0; ) (b2.isOdd() || l.isOdd()) && (b2.iadd(g), l.isub(_2)), b2.iushrn(1), l.iushrn(1); + for (var I = 0, Me = 1; (c.words[0] & Me) === 0 && I < 26; ++I, Me <<= 1); + if (I > 0) for (c.iushrn(I); I-- > 0; ) (n.isOdd() || d.isOdd()) && (n.iadd(g), d.isub(_2)), n.iushrn(1), d.iushrn(1); + u.cmp(c) >= 0 ? (u.isub(c), b2.isub(n), l.isub(d)) : (c.isub(u), n.isub(b2), d.isub(l)); + } + return {a: n, b: d, gcd: c.iushln(w)}; + }), + (f.prototype._invmp = function (s) { + r(s.negative === 0), r(!s.isZero()); + var u = this, + c = s.clone(); + u.negative !== 0 ? (u = u.umod(s)) : (u = u.clone()); + for (var b2 = new f(1), l = new f(0), n = c.clone(); u.cmpn(1) > 0 && c.cmpn(1) > 0; ) { + for (var d = 0, w = 1; (u.words[0] & w) === 0 && d < 26; ++d, w <<= 1); + if (d > 0) for (u.iushrn(d); d-- > 0; ) b2.isOdd() && b2.iadd(n), b2.iushrn(1); + for (var g = 0, _2 = 1; (c.words[0] & _2) === 0 && g < 26; ++g, _2 <<= 1); + if (g > 0) for (c.iushrn(g); g-- > 0; ) l.isOdd() && l.iadd(n), l.iushrn(1); + u.cmp(c) >= 0 ? (u.isub(c), b2.isub(l)) : (c.isub(u), l.isub(b2)); + } + var A2; + return u.cmpn(1) === 0 ? (A2 = b2) : (A2 = l), A2.cmpn(0) < 0 && A2.iadd(s), A2; + }), + (f.prototype.gcd = function (s) { + if (this.isZero()) return s.abs(); + if (s.isZero()) return this.abs(); + var u = this.clone(), + c = s.clone(); + (u.negative = 0), (c.negative = 0); + for (var b2 = 0; u.isEven() && c.isEven(); b2++) u.iushrn(1), c.iushrn(1); + do { + for (; u.isEven(); ) u.iushrn(1); + for (; c.isEven(); ) c.iushrn(1); + var l = u.cmp(c); + if (l < 0) { + var n = u; + (u = c), (c = n); + } else if (l === 0 || c.cmpn(1) === 0) break; + u.isub(c); + } while (true); + return c.iushln(b2); + }), + (f.prototype.invm = function (s) { + return this.egcd(s).a.umod(s); + }), + (f.prototype.isEven = function () { + return (this.words[0] & 1) === 0; + }), + (f.prototype.isOdd = function () { + return (this.words[0] & 1) === 1; + }), + (f.prototype.andln = function (s) { + return this.words[0] & s; + }), + (f.prototype.bincn = function (s) { + r(typeof s == 'number'); + var u = s % 26, + c = (s - u) / 26, + b2 = 1 << u; + if (this.length <= c) return this._expand(c + 1), (this.words[c] |= b2), this; + for (var l = b2, n = c; l !== 0 && n < this.length; n++) { + var d = this.words[n] | 0; + (d += l), (l = d >>> 26), (d &= 67108863), (this.words[n] = d); + } + return l !== 0 && ((this.words[n] = l), this.length++), this; + }), + (f.prototype.isZero = function () { + return this.length === 1 && this.words[0] === 0; + }), + (f.prototype.cmpn = function (s) { + var u = s < 0; + if (this.negative !== 0 && !u) return -1; + if (this.negative === 0 && u) return 1; + this._strip(); + var c; + if (this.length > 1) c = 1; + else { + u && (s = -s), r(s <= 67108863, 'Number is too big'); + var b2 = this.words[0] | 0; + c = b2 === s ? 0 : b2 < s ? -1 : 1; + } + return this.negative !== 0 ? -c | 0 : c; + }), + (f.prototype.cmp = function (s) { + if (this.negative !== 0 && s.negative === 0) return -1; + if (this.negative === 0 && s.negative !== 0) return 1; + var u = this.ucmp(s); + return this.negative !== 0 ? -u | 0 : u; + }), + (f.prototype.ucmp = function (s) { + if (this.length > s.length) return 1; + if (this.length < s.length) return -1; + for (var u = 0, c = this.length - 1; c >= 0; c--) { + var b2 = this.words[c] | 0, + l = s.words[c] | 0; + if (b2 !== l) { + b2 < l ? (u = -1) : b2 > l && (u = 1); + break; + } + } + return u; + }), + (f.prototype.gtn = function (s) { + return this.cmpn(s) === 1; + }), + (f.prototype.gt = function (s) { + return this.cmp(s) === 1; + }), + (f.prototype.gten = function (s) { + return this.cmpn(s) >= 0; + }), + (f.prototype.gte = function (s) { + return this.cmp(s) >= 0; + }), + (f.prototype.ltn = function (s) { + return this.cmpn(s) === -1; + }), + (f.prototype.lt = function (s) { + return this.cmp(s) === -1; + }), + (f.prototype.lten = function (s) { + return this.cmpn(s) <= 0; + }), + (f.prototype.lte = function (s) { + return this.cmp(s) <= 0; + }), + (f.prototype.eqn = function (s) { + return this.cmpn(s) === 0; + }), + (f.prototype.eq = function (s) { + return this.cmp(s) === 0; + }), + (f.red = function (s) { + return new i(s); + }), + (f.prototype.toRed = function (s) { + return r(!this.red, 'Already a number in reduction context'), r(this.negative === 0, 'red works only with positives'), s.convertTo(this)._forceRed(s); + }), + (f.prototype.fromRed = function () { + return r(this.red, 'fromRed works only with numbers in reduction context'), this.red.convertFrom(this); + }), + (f.prototype._forceRed = function (s) { + return (this.red = s), this; + }), + (f.prototype.forceRed = function (s) { + return r(!this.red, 'Already a number in reduction context'), this._forceRed(s); + }), + (f.prototype.redAdd = function (s) { + return r(this.red, 'redAdd works only with red numbers'), this.red.add(this, s); + }), + (f.prototype.redIAdd = function (s) { + return r(this.red, 'redIAdd works only with red numbers'), this.red.iadd(this, s); + }), + (f.prototype.redSub = function (s) { + return r(this.red, 'redSub works only with red numbers'), this.red.sub(this, s); + }), + (f.prototype.redISub = function (s) { + return r(this.red, 'redISub works only with red numbers'), this.red.isub(this, s); + }), + (f.prototype.redShl = function (s) { + return r(this.red, 'redShl works only with red numbers'), this.red.shl(this, s); + }), + (f.prototype.redMul = function (s) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, s), this.red.mul(this, s); + }), + (f.prototype.redIMul = function (s) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, s), this.red.imul(this, s); + }), + (f.prototype.redSqr = function () { + return r(this.red, 'redSqr works only with red numbers'), this.red._verify1(this), this.red.sqr(this); + }), + (f.prototype.redISqr = function () { + return r(this.red, 'redISqr works only with red numbers'), this.red._verify1(this), this.red.isqr(this); + }), + (f.prototype.redSqrt = function () { + return r(this.red, 'redSqrt works only with red numbers'), this.red._verify1(this), this.red.sqrt(this); + }), + (f.prototype.redInvm = function () { + return r(this.red, 'redInvm works only with red numbers'), this.red._verify1(this), this.red.invm(this); + }), + (f.prototype.redNeg = function () { + return r(this.red, 'redNeg works only with red numbers'), this.red._verify1(this), this.red.neg(this); + }), + (f.prototype.redPow = function (s) { + return r(this.red && !s.red, 'redPow(normalNum)'), this.red._verify1(this), this.red.pow(this, s); + }); + var Re = {k256: null, p224: null, p192: null, p25519: null}; + function Ee(h2, s) { + (this.name = h2), (this.p = new f(s, 16)), (this.n = this.p.bitLength()), (this.k = new f(1).iushln(this.n).isub(this.p)), (this.tmp = this._tmp()); + } + (Ee.prototype._tmp = function () { + var s = new f(null); + return (s.words = new Array(Math.ceil(this.n / 13))), s; + }), + (Ee.prototype.ireduce = function (s) { + var u = s, + c; + do this.split(u, this.tmp), (u = this.imulK(u)), (u = u.iadd(this.tmp)), (c = u.bitLength()); + while (c > this.n); + var b2 = c < this.n ? -1 : u.ucmp(this.p); + return b2 === 0 ? ((u.words[0] = 0), (u.length = 1)) : b2 > 0 ? u.isub(this.p) : u.strip !== undefined ? u.strip() : u._strip(), u; + }), + (Ee.prototype.split = function (s, u) { + s.iushrn(this.n, 0, u); + }), + (Ee.prototype.imulK = function (s) { + return s.imul(this.k); + }); + function Ae() { + Ee.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + o(Ae, Ee), + (Ae.prototype.split = function (s, u) { + for (var c = 4194303, b2 = Math.min(s.length, 9), l = 0; l < b2; l++) u.words[l] = s.words[l]; + if (((u.length = b2), s.length <= 9)) { + (s.words[0] = 0), (s.length = 1); + return; + } + var n = s.words[9]; + for (u.words[u.length++] = n & c, l = 10; l < s.length; l++) { + var d = s.words[l] | 0; + (s.words[l - 10] = ((d & c) << 4) | (n >>> 22)), (n = d); + } + (n >>>= 22), (s.words[l - 10] = n), n === 0 && s.length > 10 ? (s.length -= 10) : (s.length -= 9); + }), + (Ae.prototype.imulK = function (s) { + (s.words[s.length] = 0), (s.words[s.length + 1] = 0), (s.length += 2); + for (var u = 0, c = 0; c < s.length; c++) { + var b2 = s.words[c] | 0; + (u += b2 * 977), (s.words[c] = u & 67108863), (u = b2 * 64 + ((u / 67108864) | 0)); + } + return s.words[s.length - 1] === 0 && (s.length--, s.words[s.length - 1] === 0 && s.length--), s; + }); + function P() { + Ee.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + o(P, Ee); + function Se() { + Ee.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + o(Se, Ee); + function v() { + Ee.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + o(v, Ee), + (v.prototype.imulK = function (s) { + for (var u = 0, c = 0; c < s.length; c++) { + var b2 = (s.words[c] | 0) * 19 + u, + l = b2 & 67108863; + (b2 >>>= 26), (s.words[c] = l), (u = b2); + } + return u !== 0 && (s.words[s.length++] = u), s; + }), + (f._prime = function (s) { + if (Re[s]) return Re[s]; + var u; + if (s === 'k256') u = new Ae(); + else if (s === 'p224') u = new P(); + else if (s === 'p192') u = new Se(); + else if (s === 'p25519') u = new v(); + else throw new Error('Unknown prime ' + s); + return (Re[s] = u), u; + }); + function i(h2) { + if (typeof h2 == 'string') { + var s = f._prime(h2); + (this.m = s.p), (this.prime = s); + } else r(h2.gtn(1), 'modulus must be greater than 1'), (this.m = h2), (this.prime = null); + } + (i.prototype._verify1 = function (s) { + r(s.negative === 0, 'red works only with positives'), r(s.red, 'red works only with red numbers'); + }), + (i.prototype._verify2 = function (s, u) { + r((s.negative | u.negative) === 0, 'red works only with positives'), r(s.red && s.red === u.red, 'red works only with red numbers'); + }), + (i.prototype.imod = function (s) { + return this.prime ? this.prime.ireduce(s)._forceRed(this) : (x(s, s.umod(this.m)._forceRed(this)), s); + }), + (i.prototype.neg = function (s) { + return s.isZero() ? s.clone() : this.m.sub(s)._forceRed(this); + }), + (i.prototype.add = function (s, u) { + this._verify2(s, u); + var c = s.add(u); + return c.cmp(this.m) >= 0 && c.isub(this.m), c._forceRed(this); + }), + (i.prototype.iadd = function (s, u) { + this._verify2(s, u); + var c = s.iadd(u); + return c.cmp(this.m) >= 0 && c.isub(this.m), c; + }), + (i.prototype.sub = function (s, u) { + this._verify2(s, u); + var c = s.sub(u); + return c.cmpn(0) < 0 && c.iadd(this.m), c._forceRed(this); + }), + (i.prototype.isub = function (s, u) { + this._verify2(s, u); + var c = s.isub(u); + return c.cmpn(0) < 0 && c.iadd(this.m), c; + }), + (i.prototype.shl = function (s, u) { + return this._verify1(s), this.imod(s.ushln(u)); + }), + (i.prototype.imul = function (s, u) { + return this._verify2(s, u), this.imod(s.imul(u)); + }), + (i.prototype.mul = function (s, u) { + return this._verify2(s, u), this.imod(s.mul(u)); + }), + (i.prototype.isqr = function (s) { + return this.imul(s, s.clone()); + }), + (i.prototype.sqr = function (s) { + return this.mul(s, s); + }), + (i.prototype.sqrt = function (s) { + if (s.isZero()) return s.clone(); + var u = this.m.andln(3); + if ((r(u % 2 === 1), u === 3)) { + var c = this.m.add(new f(1)).iushrn(2); + return this.pow(s, c); + } + for (var b2 = this.m.subn(1), l = 0; !b2.isZero() && b2.andln(1) === 0; ) l++, b2.iushrn(1); + r(!b2.isZero()); + var n = new f(1).toRed(this), + d = n.redNeg(), + w = this.m.subn(1).iushrn(1), + g = this.m.bitLength(); + for (g = new f(2 * g * g).toRed(this); this.pow(g, w).cmp(d) !== 0; ) g.redIAdd(d); + for (var _2 = this.pow(g, b2), A2 = this.pow(s, b2.addn(1).iushrn(1)), R2 = this.pow(s, b2), I = l; R2.cmp(n) !== 0; ) { + for (var Me = R2, k = 0; Me.cmp(n) !== 0; k++) Me = Me.redSqr(); + r(k < I); + var D2 = this.pow(_2, new f(1).iushln(I - k - 1)); + (A2 = A2.redMul(D2)), (_2 = D2.redSqr()), (R2 = R2.redMul(_2)), (I = k); + } + return A2; + }), + (i.prototype.invm = function (s) { + var u = s._invmp(this.m); + return u.negative !== 0 ? ((u.negative = 0), this.imod(u).redNeg()) : this.imod(u); + }), + (i.prototype.pow = function (s, u) { + if (u.isZero()) return new f(1).toRed(this); + if (u.cmpn(1) === 0) return s.clone(); + var c = 4, + b2 = new Array(1 << c); + (b2[0] = new f(1).toRed(this)), (b2[1] = s); + for (var l = 2; l < b2.length; l++) b2[l] = this.mul(b2[l - 1], s); + var n = b2[0], + d = 0, + w = 0, + g = u.bitLength() % 26; + for (g === 0 && (g = 26), l = u.length - 1; l >= 0; l--) { + for (var _2 = u.words[l], A2 = g - 1; A2 >= 0; A2--) { + var R2 = (_2 >> A2) & 1; + if ((n !== b2[0] && (n = this.sqr(n)), R2 === 0 && d === 0)) { + w = 0; + continue; + } + (d <<= 1), (d |= R2), w++, !(w !== c && (l !== 0 || A2 !== 0)) && ((n = this.mul(n, b2[d])), (w = 0), (d = 0)); + } + g = 26; + } + return n; + }), + (i.prototype.convertTo = function (s) { + var u = s.umod(this.m); + return u === s ? u.clone() : u; + }), + (i.prototype.convertFrom = function (s) { + var u = s.clone(); + return (u.red = null), u; + }), + (f.mont = function (s) { + return new a(s); + }); + function a(h2) { + i.call(this, h2), + (this.shift = this.m.bitLength()), + this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), + (this.r = new f(1).iushln(this.shift)), + (this.r2 = this.imod(this.r.sqr())), + (this.rinv = this.r._invmp(this.m)), + (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), + (this.minv = this.minv.umod(this.r)), + (this.minv = this.r.sub(this.minv)); + } + o(a, i), + (a.prototype.convertTo = function (s) { + return this.imod(s.ushln(this.shift)); + }), + (a.prototype.convertFrom = function (s) { + var u = this.imod(s.mul(this.rinv)); + return (u.red = null), u; + }), + (a.prototype.imul = function (s, u) { + if (s.isZero() || u.isZero()) return (s.words[0] = 0), (s.length = 1), s; + var c = s.imul(u), + b2 = c.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + l = c.isub(b2).iushrn(this.shift), + n = l; + return l.cmp(this.m) >= 0 ? (n = l.isub(this.m)) : l.cmpn(0) < 0 && (n = l.iadd(this.m)), n._forceRed(this); + }), + (a.prototype.mul = function (s, u) { + if (s.isZero() || u.isZero()) return new f(0)._forceRed(this); + var c = s.mul(u), + b2 = c.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + l = c.isub(b2).iushrn(this.shift), + n = l; + return l.cmp(this.m) >= 0 ? (n = l.isub(this.m)) : l.cmpn(0) < 0 && (n = l.iadd(this.m)), n._forceRed(this); + }), + (a.prototype.invm = function (s) { + var u = this.imod(s._invmp(this.m).mul(this.r2)); + return u._forceRed(this); + }); + })(typeof kl > 'u' || kl, n2); + }); + Ks = T2((yk, o2) => { + var Rf = Ws(), + oA = on(); + function sA(t) { + var e = f2(t), + r = e.toRed(Rf.mont(t.modulus)).redPow(new Rf(t.publicExponent)).fromRed(); + return {blinder: r, unblinder: e.invm(t.modulus)}; + } + function f2(t) { + var e = t.modulus.byteLength(), + r; + do r = new Rf(oA(e)); + while (r.cmp(t.modulus) >= 0 || !r.umod(t.prime1) || !r.umod(t.prime2)); + return r; + } + function a2(t, e) { + var r = sA(e), + o = e.modulus.byteLength(), + f = new Rf(t).mul(r.blinder).umod(e.modulus), + p = f.toRed(Rf.mont(e.prime1)), + m2 = f.toRed(Rf.mont(e.prime2)), + y2 = e.coefficient, + M = e.prime1, + x = e.prime2, + S = p.redPow(e.exponent1).fromRed(), + E2 = m2.redPow(e.exponent2).fromRed(), + B = S.isub(E2).imul(y2).umod(M).imul(x); + return E2.iadd(B).imul(r.unblinder).umod(e.modulus).toArrayLike(Buffer, 'be', o); + } + a2.getr = f2; + o2.exports = a2; + }); + s2 = T2((wk, hA) => { + hA.exports = { + name: 'elliptic', + version: '6.5.4', + description: 'EC cryptography', + main: 'lib/elliptic.js', + files: ['lib'], + scripts: {lint: 'eslint lib test', 'lint:fix': 'npm run lint -- --fix', unit: 'istanbul test _mocha --reporter=spec test/index.js', test: 'npm run lint && npm run unit', version: 'grunt dist && git add dist/'}, + repository: {type: 'git', url: 'git@github.com:indutny/elliptic'}, + keywords: ['EC', 'Elliptic', 'curve', 'Cryptography'], + author: 'Fedor Indutny ', + license: 'MIT', + bugs: {url: 'https://github.com/indutny/elliptic/issues'}, + homepage: 'https://github.com/indutny/elliptic', + devDependencies: { + brfs: '^2.0.2', + coveralls: '^3.1.0', + eslint: '^7.6.0', + grunt: '^1.2.1', + 'grunt-browserify': '^5.3.0', + 'grunt-cli': '^1.3.2', + 'grunt-contrib-connect': '^3.0.0', + 'grunt-contrib-copy': '^1.0.0', + 'grunt-contrib-uglify': '^5.0.0', + 'grunt-mocha-istanbul': '^5.0.2', + 'grunt-saucelabs': '^9.0.1', + istanbul: '^0.4.5', + mocha: '^8.0.1' + }, + dependencies: {'bn.js': '^4.11.9', brorand: '^1.1.0', 'hash.js': '^1.0.0', 'hmac-drbg': '^1.0.1', inherits: '^2.0.4', 'minimalistic-assert': '^1.0.1', 'minimalistic-crypto-utils': '^1.0.1'} + }; + }); + ri = T2((h2, Ll) => { + (function (t, e) { + function r(v, i) { + if (!v) throw new Error(i || 'Assertion failed'); + } + function o(v, i) { + v.super_ = i; + var a = function () {}; + (a.prototype = i.prototype), (v.prototype = new a()), (v.prototype.constructor = v); + } + function f(v, i, a) { + if (f.isBN(v)) return v; + (this.negative = 0), (this.words = null), (this.length = 0), (this.red = null), v !== null && ((i === 'le' || i === 'be') && ((a = i), (i = 10)), this._init(v || 0, i || 10, a || 'be')); + } + typeof t == 'object' ? (t.exports = f) : (e.BN = f), (f.BN = f), (f.wordSize = 26); + var p; + try { + typeof window < 'u' && typeof window.Buffer < 'u' ? (p = window.Buffer) : (p = ji().Buffer); + } catch {} + (f.isBN = function (i) { + return i instanceof f ? true : i !== null && typeof i == 'object' && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }), + (f.max = function (i, a) { + return i.cmp(a) > 0 ? i : a; + }), + (f.min = function (i, a) { + return i.cmp(a) < 0 ? i : a; + }), + (f.prototype._init = function (i, a, h3) { + if (typeof i == 'number') return this._initNumber(i, a, h3); + if (typeof i == 'object') return this._initArray(i, a, h3); + a === 'hex' && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), (i = i.toString().replace(/\s+/g, '')); + var s = 0; + i[0] === '-' && (s++, (this.negative = 1)), s < i.length && (a === 16 ? this._parseHex(i, s, h3) : (this._parseBase(i, a, s), h3 === 'le' && this._initArray(this.toArray(), a, h3))); + }), + (f.prototype._initNumber = function (i, a, h3) { + i < 0 && ((this.negative = 1), (i = -i)), + i < 67108864 + ? ((this.words = [i & 67108863]), (this.length = 1)) + : i < 4503599627370496 + ? ((this.words = [i & 67108863, (i / 67108864) & 67108863]), (this.length = 2)) + : (r(i < 9007199254740992), (this.words = [i & 67108863, (i / 67108864) & 67108863, 1]), (this.length = 3)), + h3 === 'le' && this._initArray(this.toArray(), a, h3); + }), + (f.prototype._initArray = function (i, a, h3) { + if ((r(typeof i.length == 'number'), i.length <= 0)) return (this.words = [0]), (this.length = 1), this; + (this.length = Math.ceil(i.length / 3)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u, + c, + b2 = 0; + if (h3 === 'be') + for (s = i.length - 1, u = 0; s >= 0; s -= 3) + (c = i[s] | (i[s - 1] << 8) | (i[s - 2] << 16)), (this.words[u] |= (c << b2) & 67108863), (this.words[u + 1] = (c >>> (26 - b2)) & 67108863), (b2 += 24), b2 >= 26 && ((b2 -= 26), u++); + else if (h3 === 'le') + for (s = 0, u = 0; s < i.length; s += 3) (c = i[s] | (i[s + 1] << 8) | (i[s + 2] << 16)), (this.words[u] |= (c << b2) & 67108863), (this.words[u + 1] = (c >>> (26 - b2)) & 67108863), (b2 += 24), b2 >= 26 && ((b2 -= 26), u++); + return this.strip(); + }); + function m2(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : (a - 48) & 15; + } + function y2(v, i, a) { + var h3 = m2(v, a); + return a - 1 >= i && (h3 |= m2(v, a - 1) << 4), h3; + } + f.prototype._parseHex = function (i, a, h3) { + (this.length = Math.ceil((i.length - a) / 6)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u = 0, + c = 0, + b2; + if (h3 === 'be') for (s = i.length - 1; s >= a; s -= 2) (b2 = y2(i, a, s) << u), (this.words[c] |= b2 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b2 >>> 26)) : (u += 8); + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a; s < i.length; s += 2) (b2 = y2(i, a, s) << u), (this.words[c] |= b2 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b2 >>> 26)) : (u += 8); + } + this.strip(); + }; + function M(v, i, a, h3) { + for (var s = 0, u = Math.min(v.length, a), c = i; c < u; c++) { + var b2 = v.charCodeAt(c) - 48; + (s *= h3), b2 >= 49 ? (s += b2 - 49 + 10) : b2 >= 17 ? (s += b2 - 17 + 10) : (s += b2); + } + return s; + } + (f.prototype._parseBase = function (i, a, h3) { + (this.words = [0]), (this.length = 1); + for (var s = 0, u = 1; u <= 67108863; u *= a) s++; + s--, (u = (u / a) | 0); + for (var c = i.length - h3, b2 = c % s, l = Math.min(c, c - b2) + h3, n = 0, d = h3; d < l; d += s) (n = M(i, d, d + s, a)), this.imuln(u), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + if (b2 !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0; d < b2; d++) w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + } + this.strip(); + }), + (f.prototype.copy = function (i) { + i.words = new Array(this.length); + for (var a = 0; a < this.length; a++) i.words[a] = this.words[a]; + (i.length = this.length), (i.negative = this.negative), (i.red = this.red); + }), + (f.prototype.clone = function () { + var i = new f(null); + return this.copy(i), i; + }), + (f.prototype._expand = function (i) { + for (; this.length < i; ) this.words[this.length++] = 0; + return this; + }), + (f.prototype.strip = function () { + for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; + return this._normSign(); + }), + (f.prototype._normSign = function () { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }), + (f.prototype.inspect = function () { + return (this.red ? ''; + }); + var x = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ], + S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + E2 = [ + 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, + 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + (f.prototype.toString = function (i, a) { + (i = i || 10), (a = a | 0 || 1); + var h3; + if (i === 16 || i === 'hex') { + h3 = ''; + for (var s = 0, u = 0, c = 0; c < this.length; c++) { + var b2 = this.words[c], + l = (((b2 << s) | u) & 16777215).toString(16); + (u = (b2 >>> (24 - s)) & 16777215), u !== 0 || c !== this.length - 1 ? (h3 = x[6 - l.length] + l + h3) : (h3 = l + h3), (s += 2), s >= 26 && ((s -= 26), c--); + } + for (u !== 0 && (h3 = u.toString(16) + h3); h3.length % a !== 0; ) h3 = '0' + h3; + return this.negative !== 0 && (h3 = '-' + h3), h3; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], + d = E2[i]; + h3 = ''; + var w = this.clone(); + for (w.negative = 0; !w.isZero(); ) { + var g = w.modn(d).toString(i); + (w = w.idivn(d)), w.isZero() ? (h3 = g + h3) : (h3 = x[n - g.length] + g + h3); + } + for (this.isZero() && (h3 = '0' + h3); h3.length % a !== 0; ) h3 = '0' + h3; + return this.negative !== 0 && (h3 = '-' + h3), h3; + } + r(false, 'Base should be between 2 and 36'); + }), + (f.prototype.toNumber = function () { + var i = this.words[0]; + return ( + this.length === 2 ? (i += this.words[1] * 67108864) : this.length === 3 && this.words[2] === 1 ? (i += 4503599627370496 + this.words[1] * 67108864) : this.length > 2 && r(false, 'Number can only safely store up to 53 bits'), + this.negative !== 0 ? -i : i + ); + }), + (f.prototype.toJSON = function () { + return this.toString(16); + }), + (f.prototype.toBuffer = function (i, a) { + return r(typeof p < 'u'), this.toArrayLike(p, i, a); + }), + (f.prototype.toArray = function (i, a) { + return this.toArrayLike(Array, i, a); + }), + (f.prototype.toArrayLike = function (i, a, h3) { + var s = this.byteLength(), + u = h3 || Math.max(1, s); + r(s <= u, 'byte array longer than desired length'), r(u > 0, 'Requested array length <= 0'), this.strip(); + var c = a === 'le', + b2 = new i(u), + l, + n, + d = this.clone(); + if (c) { + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b2[n] = l); + for (; n < u; n++) b2[n] = 0; + } else { + for (n = 0; n < u - s; n++) b2[n] = 0; + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b2[u - n - 1] = l); + } + return b2; + }), + Math.clz32 + ? (f.prototype._countBits = function (i) { + return 32 - Math.clz32(i); + }) + : (f.prototype._countBits = function (i) { + var a = i, + h3 = 0; + return a >= 4096 && ((h3 += 13), (a >>>= 13)), a >= 64 && ((h3 += 7), (a >>>= 7)), a >= 8 && ((h3 += 4), (a >>>= 4)), a >= 2 && ((h3 += 2), (a >>>= 2)), h3 + a; + }), + (f.prototype._zeroBits = function (i) { + if (i === 0) return 26; + var a = i, + h3 = 0; + return (a & 8191) === 0 && ((h3 += 13), (a >>>= 13)), (a & 127) === 0 && ((h3 += 7), (a >>>= 7)), (a & 15) === 0 && ((h3 += 4), (a >>>= 4)), (a & 3) === 0 && ((h3 += 2), (a >>>= 2)), (a & 1) === 0 && h3++, h3; + }), + (f.prototype.bitLength = function () { + var i = this.words[this.length - 1], + a = this._countBits(i); + return (this.length - 1) * 26 + a; + }); + function B(v) { + for (var i = new Array(v.bitLength()), a = 0; a < i.length; a++) { + var h3 = (a / 26) | 0, + s = a % 26; + i[a] = (v.words[h3] & (1 << s)) >>> s; + } + return i; + } + (f.prototype.zeroBits = function () { + if (this.isZero()) return 0; + for (var i = 0, a = 0; a < this.length; a++) { + var h3 = this._zeroBits(this.words[a]); + if (((i += h3), h3 !== 26)) break; + } + return i; + }), + (f.prototype.byteLength = function () { + return Math.ceil(this.bitLength() / 8); + }), + (f.prototype.toTwos = function (i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }), + (f.prototype.fromTwos = function (i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }), + (f.prototype.isNeg = function () { + return this.negative !== 0; + }), + (f.prototype.neg = function () { + return this.clone().ineg(); + }), + (f.prototype.ineg = function () { + return this.isZero() || (this.negative ^= 1), this; + }), + (f.prototype.iuor = function (i) { + for (; this.length < i.length; ) this.words[this.length++] = 0; + for (var a = 0; a < i.length; a++) this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }), + (f.prototype.ior = function (i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }), + (f.prototype.or = function (i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }), + (f.prototype.uor = function (i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }), + (f.prototype.iuand = function (i) { + var a; + this.length > i.length ? (a = i) : (a = this); + for (var h3 = 0; h3 < a.length; h3++) this.words[h3] = this.words[h3] & i.words[h3]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.iand = function (i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }), + (f.prototype.and = function (i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }), + (f.prototype.uand = function (i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }), + (f.prototype.iuxor = function (i) { + var a, h3; + this.length > i.length ? ((a = this), (h3 = i)) : ((a = i), (h3 = this)); + for (var s = 0; s < h3.length; s++) this.words[s] = a.words[s] ^ h3.words[s]; + if (this !== a) for (; s < a.length; s++) this.words[s] = a.words[s]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.ixor = function (i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }), + (f.prototype.xor = function (i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }), + (f.prototype.uxor = function (i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }), + (f.prototype.inotn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = Math.ceil(i / 26) | 0, + h3 = i % 26; + this._expand(a), h3 > 0 && a--; + for (var s = 0; s < a; s++) this.words[s] = ~this.words[s] & 67108863; + return h3 > 0 && (this.words[s] = ~this.words[s] & (67108863 >> (26 - h3))), this.strip(); + }), + (f.prototype.notn = function (i) { + return this.clone().inotn(i); + }), + (f.prototype.setn = function (i, a) { + r(typeof i == 'number' && i >= 0); + var h3 = (i / 26) | 0, + s = i % 26; + return this._expand(h3 + 1), a ? (this.words[h3] = this.words[h3] | (1 << s)) : (this.words[h3] = this.words[h3] & ~(1 << s)), this.strip(); + }), + (f.prototype.iadd = function (i) { + var a; + if (this.negative !== 0 && i.negative === 0) return (this.negative = 0), (a = this.isub(i)), (this.negative ^= 1), this._normSign(); + if (this.negative === 0 && i.negative !== 0) return (i.negative = 0), (a = this.isub(i)), (i.negative = 1), a._normSign(); + var h3, s; + this.length > i.length ? ((h3 = this), (s = i)) : ((h3 = i), (s = this)); + for (var u = 0, c = 0; c < s.length; c++) (a = (h3.words[c] | 0) + (s.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + for (; u !== 0 && c < h3.length; c++) (a = (h3.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + if (((this.length = h3.length), u !== 0)) (this.words[this.length] = u), this.length++; + else if (h3 !== this) for (; c < h3.length; c++) this.words[c] = h3.words[c]; + return this; + }), + (f.prototype.add = function (i) { + var a; + return i.negative !== 0 && this.negative === 0 + ? ((i.negative = 0), (a = this.sub(i)), (i.negative ^= 1), a) + : i.negative === 0 && this.negative !== 0 + ? ((this.negative = 0), (a = i.sub(this)), (this.negative = 1), a) + : this.length > i.length + ? this.clone().iadd(i) + : i.clone().iadd(this); + }), + (f.prototype.isub = function (i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return (i.negative = 1), a._normSign(); + } else if (this.negative !== 0) return (this.negative = 0), this.iadd(i), (this.negative = 1), this._normSign(); + var h3 = this.cmp(i); + if (h3 === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; + var s, u; + h3 > 0 ? ((s = this), (u = i)) : ((s = i), (u = this)); + for (var c = 0, b2 = 0; b2 < u.length; b2++) (a = (s.words[b2] | 0) - (u.words[b2] | 0) + c), (c = a >> 26), (this.words[b2] = a & 67108863); + for (; c !== 0 && b2 < s.length; b2++) (a = (s.words[b2] | 0) + c), (c = a >> 26), (this.words[b2] = a & 67108863); + if (c === 0 && b2 < s.length && s !== this) for (; b2 < s.length; b2++) this.words[b2] = s.words[b2]; + return (this.length = Math.max(this.length, b2)), s !== this && (this.negative = 1), this.strip(); + }), + (f.prototype.sub = function (i) { + return this.clone().isub(i); + }); + function q2(v, i, a) { + a.negative = i.negative ^ v.negative; + var h3 = (v.length + i.length) | 0; + (a.length = h3), (h3 = (h3 - 1) | 0); + var s = v.words[0] | 0, + u = i.words[0] | 0, + c = s * u, + b2 = c & 67108863, + l = (c / 67108864) | 0; + a.words[0] = b2; + for (var n = 1; n < h3; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _2 = Math.max(0, n - v.length + 1); _2 <= g; _2++) { + var A2 = (n - _2) | 0; + (s = v.words[A2] | 0), (u = i.words[_2] | 0), (c = s * u + w), (d += (c / 67108864) | 0), (w = c & 67108863); + } + (a.words[n] = w | 0), (l = d | 0); + } + return l !== 0 ? (a.words[n] = l | 0) : a.length--, a.strip(); + } + var L2 = function (i, a, h3) { + var s = i.words, + u = a.words, + c = h3.words, + b2 = 0, + l, + n, + d, + w = s[0] | 0, + g = w & 8191, + _2 = w >>> 13, + A2 = s[1] | 0, + R2 = A2 & 8191, + I = A2 >>> 13, + Me = s[2] | 0, + k = Me & 8191, + D2 = Me >>> 13, + nt = s[3] | 0, + C2 = nt & 8191, + O = nt >>> 13, + vt = s[4] | 0, + F = vt & 8191, + U = vt >>> 13, + bt = s[5] | 0, + z2 = bt & 8191, + H = bt >>> 13, + mt = s[6] | 0, + W = mt & 8191, + K = mt >>> 13, + gt = s[7] | 0, + j = gt & 8191, + Z = gt >>> 13, + yt = s[8] | 0, + V = yt & 8191, + $2 = yt >>> 13, + wt = s[9] | 0, + G = wt & 8191, + Y = wt >>> 13, + Mt = u[0] | 0, + X = Mt & 8191, + J = Mt >>> 13, + _t = u[1] | 0, + Q = _t & 8191, + ee = _t >>> 13, + xt = u[2] | 0, + te = xt & 8191, + re = xt >>> 13, + St = u[3] | 0, + ie = St & 8191, + ne = St >>> 13, + Et = u[4] | 0, + fe = Et & 8191, + ae = Et >>> 13, + At = u[5] | 0, + oe = At & 8191, + se = At >>> 13, + Rt = u[6] | 0, + he = Rt & 8191, + ue = Rt >>> 13, + Bt = u[7] | 0, + le = Bt & 8191, + de = Bt >>> 13, + qt = u[8] | 0, + ce = qt & 8191, + pe = qt >>> 13, + It = u[9] | 0, + ve = It & 8191, + be = It >>> 13; + (h3.negative = i.negative ^ a.negative), (h3.length = 19), (l = Math.imul(g, X)), (n = Math.imul(g, J)), (n = (n + Math.imul(_2, X)) | 0), (d = Math.imul(_2, J)); + var ft = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (ft >>> 26)) | 0), + (ft &= 67108863), + (l = Math.imul(R2, X)), + (n = Math.imul(R2, J)), + (n = (n + Math.imul(I, X)) | 0), + (d = Math.imul(I, J)), + (l = (l + Math.imul(g, Q)) | 0), + (n = (n + Math.imul(g, ee)) | 0), + (n = (n + Math.imul(_2, Q)) | 0), + (d = (d + Math.imul(_2, ee)) | 0); + var Be = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Be >>> 26)) | 0), + (Be &= 67108863), + (l = Math.imul(k, X)), + (n = Math.imul(k, J)), + (n = (n + Math.imul(D2, X)) | 0), + (d = Math.imul(D2, J)), + (l = (l + Math.imul(R2, Q)) | 0), + (n = (n + Math.imul(R2, ee)) | 0), + (n = (n + Math.imul(I, Q)) | 0), + (d = (d + Math.imul(I, ee)) | 0), + (l = (l + Math.imul(g, te)) | 0), + (n = (n + Math.imul(g, re)) | 0), + (n = (n + Math.imul(_2, te)) | 0), + (d = (d + Math.imul(_2, re)) | 0); + var qe = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (qe >>> 26)) | 0), + (qe &= 67108863), + (l = Math.imul(C2, X)), + (n = Math.imul(C2, J)), + (n = (n + Math.imul(O, X)) | 0), + (d = Math.imul(O, J)), + (l = (l + Math.imul(k, Q)) | 0), + (n = (n + Math.imul(k, ee)) | 0), + (n = (n + Math.imul(D2, Q)) | 0), + (d = (d + Math.imul(D2, ee)) | 0), + (l = (l + Math.imul(R2, te)) | 0), + (n = (n + Math.imul(R2, re)) | 0), + (n = (n + Math.imul(I, te)) | 0), + (d = (d + Math.imul(I, re)) | 0), + (l = (l + Math.imul(g, ie)) | 0), + (n = (n + Math.imul(g, ne)) | 0), + (n = (n + Math.imul(_2, ie)) | 0), + (d = (d + Math.imul(_2, ne)) | 0); + var ze = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (ze >>> 26)) | 0), + (ze &= 67108863), + (l = Math.imul(F, X)), + (n = Math.imul(F, J)), + (n = (n + Math.imul(U, X)) | 0), + (d = Math.imul(U, J)), + (l = (l + Math.imul(C2, Q)) | 0), + (n = (n + Math.imul(C2, ee)) | 0), + (n = (n + Math.imul(O, Q)) | 0), + (d = (d + Math.imul(O, ee)) | 0), + (l = (l + Math.imul(k, te)) | 0), + (n = (n + Math.imul(k, re)) | 0), + (n = (n + Math.imul(D2, te)) | 0), + (d = (d + Math.imul(D2, re)) | 0), + (l = (l + Math.imul(R2, ie)) | 0), + (n = (n + Math.imul(R2, ne)) | 0), + (n = (n + Math.imul(I, ie)) | 0), + (d = (d + Math.imul(I, ne)) | 0), + (l = (l + Math.imul(g, fe)) | 0), + (n = (n + Math.imul(g, ae)) | 0), + (n = (n + Math.imul(_2, fe)) | 0), + (d = (d + Math.imul(_2, ae)) | 0); + var He = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (He >>> 26)) | 0), + (He &= 67108863), + (l = Math.imul(z2, X)), + (n = Math.imul(z2, J)), + (n = (n + Math.imul(H, X)) | 0), + (d = Math.imul(H, J)), + (l = (l + Math.imul(F, Q)) | 0), + (n = (n + Math.imul(F, ee)) | 0), + (n = (n + Math.imul(U, Q)) | 0), + (d = (d + Math.imul(U, ee)) | 0), + (l = (l + Math.imul(C2, te)) | 0), + (n = (n + Math.imul(C2, re)) | 0), + (n = (n + Math.imul(O, te)) | 0), + (d = (d + Math.imul(O, re)) | 0), + (l = (l + Math.imul(k, ie)) | 0), + (n = (n + Math.imul(k, ne)) | 0), + (n = (n + Math.imul(D2, ie)) | 0), + (d = (d + Math.imul(D2, ne)) | 0), + (l = (l + Math.imul(R2, fe)) | 0), + (n = (n + Math.imul(R2, ae)) | 0), + (n = (n + Math.imul(I, fe)) | 0), + (d = (d + Math.imul(I, ae)) | 0), + (l = (l + Math.imul(g, oe)) | 0), + (n = (n + Math.imul(g, se)) | 0), + (n = (n + Math.imul(_2, oe)) | 0), + (d = (d + Math.imul(_2, se)) | 0); + var We = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (We >>> 26)) | 0), + (We &= 67108863), + (l = Math.imul(W, X)), + (n = Math.imul(W, J)), + (n = (n + Math.imul(K, X)) | 0), + (d = Math.imul(K, J)), + (l = (l + Math.imul(z2, Q)) | 0), + (n = (n + Math.imul(z2, ee)) | 0), + (n = (n + Math.imul(H, Q)) | 0), + (d = (d + Math.imul(H, ee)) | 0), + (l = (l + Math.imul(F, te)) | 0), + (n = (n + Math.imul(F, re)) | 0), + (n = (n + Math.imul(U, te)) | 0), + (d = (d + Math.imul(U, re)) | 0), + (l = (l + Math.imul(C2, ie)) | 0), + (n = (n + Math.imul(C2, ne)) | 0), + (n = (n + Math.imul(O, ie)) | 0), + (d = (d + Math.imul(O, ne)) | 0), + (l = (l + Math.imul(k, fe)) | 0), + (n = (n + Math.imul(k, ae)) | 0), + (n = (n + Math.imul(D2, fe)) | 0), + (d = (d + Math.imul(D2, ae)) | 0), + (l = (l + Math.imul(R2, oe)) | 0), + (n = (n + Math.imul(R2, se)) | 0), + (n = (n + Math.imul(I, oe)) | 0), + (d = (d + Math.imul(I, se)) | 0), + (l = (l + Math.imul(g, he)) | 0), + (n = (n + Math.imul(g, ue)) | 0), + (n = (n + Math.imul(_2, he)) | 0), + (d = (d + Math.imul(_2, ue)) | 0); + var Ke = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ke >>> 26)) | 0), + (Ke &= 67108863), + (l = Math.imul(j, X)), + (n = Math.imul(j, J)), + (n = (n + Math.imul(Z, X)) | 0), + (d = Math.imul(Z, J)), + (l = (l + Math.imul(W, Q)) | 0), + (n = (n + Math.imul(W, ee)) | 0), + (n = (n + Math.imul(K, Q)) | 0), + (d = (d + Math.imul(K, ee)) | 0), + (l = (l + Math.imul(z2, te)) | 0), + (n = (n + Math.imul(z2, re)) | 0), + (n = (n + Math.imul(H, te)) | 0), + (d = (d + Math.imul(H, re)) | 0), + (l = (l + Math.imul(F, ie)) | 0), + (n = (n + Math.imul(F, ne)) | 0), + (n = (n + Math.imul(U, ie)) | 0), + (d = (d + Math.imul(U, ne)) | 0), + (l = (l + Math.imul(C2, fe)) | 0), + (n = (n + Math.imul(C2, ae)) | 0), + (n = (n + Math.imul(O, fe)) | 0), + (d = (d + Math.imul(O, ae)) | 0), + (l = (l + Math.imul(k, oe)) | 0), + (n = (n + Math.imul(k, se)) | 0), + (n = (n + Math.imul(D2, oe)) | 0), + (d = (d + Math.imul(D2, se)) | 0), + (l = (l + Math.imul(R2, he)) | 0), + (n = (n + Math.imul(R2, ue)) | 0), + (n = (n + Math.imul(I, he)) | 0), + (d = (d + Math.imul(I, ue)) | 0), + (l = (l + Math.imul(g, le)) | 0), + (n = (n + Math.imul(g, de)) | 0), + (n = (n + Math.imul(_2, le)) | 0), + (d = (d + Math.imul(_2, de)) | 0); + var je = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (je >>> 26)) | 0), + (je &= 67108863), + (l = Math.imul(V, X)), + (n = Math.imul(V, J)), + (n = (n + Math.imul($2, X)) | 0), + (d = Math.imul($2, J)), + (l = (l + Math.imul(j, Q)) | 0), + (n = (n + Math.imul(j, ee)) | 0), + (n = (n + Math.imul(Z, Q)) | 0), + (d = (d + Math.imul(Z, ee)) | 0), + (l = (l + Math.imul(W, te)) | 0), + (n = (n + Math.imul(W, re)) | 0), + (n = (n + Math.imul(K, te)) | 0), + (d = (d + Math.imul(K, re)) | 0), + (l = (l + Math.imul(z2, ie)) | 0), + (n = (n + Math.imul(z2, ne)) | 0), + (n = (n + Math.imul(H, ie)) | 0), + (d = (d + Math.imul(H, ne)) | 0), + (l = (l + Math.imul(F, fe)) | 0), + (n = (n + Math.imul(F, ae)) | 0), + (n = (n + Math.imul(U, fe)) | 0), + (d = (d + Math.imul(U, ae)) | 0), + (l = (l + Math.imul(C2, oe)) | 0), + (n = (n + Math.imul(C2, se)) | 0), + (n = (n + Math.imul(O, oe)) | 0), + (d = (d + Math.imul(O, se)) | 0), + (l = (l + Math.imul(k, he)) | 0), + (n = (n + Math.imul(k, ue)) | 0), + (n = (n + Math.imul(D2, he)) | 0), + (d = (d + Math.imul(D2, ue)) | 0), + (l = (l + Math.imul(R2, le)) | 0), + (n = (n + Math.imul(R2, de)) | 0), + (n = (n + Math.imul(I, le)) | 0), + (d = (d + Math.imul(I, de)) | 0), + (l = (l + Math.imul(g, ce)) | 0), + (n = (n + Math.imul(g, pe)) | 0), + (n = (n + Math.imul(_2, ce)) | 0), + (d = (d + Math.imul(_2, pe)) | 0); + var Ze = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ze >>> 26)) | 0), + (Ze &= 67108863), + (l = Math.imul(G, X)), + (n = Math.imul(G, J)), + (n = (n + Math.imul(Y, X)) | 0), + (d = Math.imul(Y, J)), + (l = (l + Math.imul(V, Q)) | 0), + (n = (n + Math.imul(V, ee)) | 0), + (n = (n + Math.imul($2, Q)) | 0), + (d = (d + Math.imul($2, ee)) | 0), + (l = (l + Math.imul(j, te)) | 0), + (n = (n + Math.imul(j, re)) | 0), + (n = (n + Math.imul(Z, te)) | 0), + (d = (d + Math.imul(Z, re)) | 0), + (l = (l + Math.imul(W, ie)) | 0), + (n = (n + Math.imul(W, ne)) | 0), + (n = (n + Math.imul(K, ie)) | 0), + (d = (d + Math.imul(K, ne)) | 0), + (l = (l + Math.imul(z2, fe)) | 0), + (n = (n + Math.imul(z2, ae)) | 0), + (n = (n + Math.imul(H, fe)) | 0), + (d = (d + Math.imul(H, ae)) | 0), + (l = (l + Math.imul(F, oe)) | 0), + (n = (n + Math.imul(F, se)) | 0), + (n = (n + Math.imul(U, oe)) | 0), + (d = (d + Math.imul(U, se)) | 0), + (l = (l + Math.imul(C2, he)) | 0), + (n = (n + Math.imul(C2, ue)) | 0), + (n = (n + Math.imul(O, he)) | 0), + (d = (d + Math.imul(O, ue)) | 0), + (l = (l + Math.imul(k, le)) | 0), + (n = (n + Math.imul(k, de)) | 0), + (n = (n + Math.imul(D2, le)) | 0), + (d = (d + Math.imul(D2, de)) | 0), + (l = (l + Math.imul(R2, ce)) | 0), + (n = (n + Math.imul(R2, pe)) | 0), + (n = (n + Math.imul(I, ce)) | 0), + (d = (d + Math.imul(I, pe)) | 0), + (l = (l + Math.imul(g, ve)) | 0), + (n = (n + Math.imul(g, be)) | 0), + (n = (n + Math.imul(_2, ve)) | 0), + (d = (d + Math.imul(_2, be)) | 0); + var Ve = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ve >>> 26)) | 0), + (Ve &= 67108863), + (l = Math.imul(G, Q)), + (n = Math.imul(G, ee)), + (n = (n + Math.imul(Y, Q)) | 0), + (d = Math.imul(Y, ee)), + (l = (l + Math.imul(V, te)) | 0), + (n = (n + Math.imul(V, re)) | 0), + (n = (n + Math.imul($2, te)) | 0), + (d = (d + Math.imul($2, re)) | 0), + (l = (l + Math.imul(j, ie)) | 0), + (n = (n + Math.imul(j, ne)) | 0), + (n = (n + Math.imul(Z, ie)) | 0), + (d = (d + Math.imul(Z, ne)) | 0), + (l = (l + Math.imul(W, fe)) | 0), + (n = (n + Math.imul(W, ae)) | 0), + (n = (n + Math.imul(K, fe)) | 0), + (d = (d + Math.imul(K, ae)) | 0), + (l = (l + Math.imul(z2, oe)) | 0), + (n = (n + Math.imul(z2, se)) | 0), + (n = (n + Math.imul(H, oe)) | 0), + (d = (d + Math.imul(H, se)) | 0), + (l = (l + Math.imul(F, he)) | 0), + (n = (n + Math.imul(F, ue)) | 0), + (n = (n + Math.imul(U, he)) | 0), + (d = (d + Math.imul(U, ue)) | 0), + (l = (l + Math.imul(C2, le)) | 0), + (n = (n + Math.imul(C2, de)) | 0), + (n = (n + Math.imul(O, le)) | 0), + (d = (d + Math.imul(O, de)) | 0), + (l = (l + Math.imul(k, ce)) | 0), + (n = (n + Math.imul(k, pe)) | 0), + (n = (n + Math.imul(D2, ce)) | 0), + (d = (d + Math.imul(D2, pe)) | 0), + (l = (l + Math.imul(R2, ve)) | 0), + (n = (n + Math.imul(R2, be)) | 0), + (n = (n + Math.imul(I, ve)) | 0), + (d = (d + Math.imul(I, be)) | 0); + var $e = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + ($e >>> 26)) | 0), + ($e &= 67108863), + (l = Math.imul(G, te)), + (n = Math.imul(G, re)), + (n = (n + Math.imul(Y, te)) | 0), + (d = Math.imul(Y, re)), + (l = (l + Math.imul(V, ie)) | 0), + (n = (n + Math.imul(V, ne)) | 0), + (n = (n + Math.imul($2, ie)) | 0), + (d = (d + Math.imul($2, ne)) | 0), + (l = (l + Math.imul(j, fe)) | 0), + (n = (n + Math.imul(j, ae)) | 0), + (n = (n + Math.imul(Z, fe)) | 0), + (d = (d + Math.imul(Z, ae)) | 0), + (l = (l + Math.imul(W, oe)) | 0), + (n = (n + Math.imul(W, se)) | 0), + (n = (n + Math.imul(K, oe)) | 0), + (d = (d + Math.imul(K, se)) | 0), + (l = (l + Math.imul(z2, he)) | 0), + (n = (n + Math.imul(z2, ue)) | 0), + (n = (n + Math.imul(H, he)) | 0), + (d = (d + Math.imul(H, ue)) | 0), + (l = (l + Math.imul(F, le)) | 0), + (n = (n + Math.imul(F, de)) | 0), + (n = (n + Math.imul(U, le)) | 0), + (d = (d + Math.imul(U, de)) | 0), + (l = (l + Math.imul(C2, ce)) | 0), + (n = (n + Math.imul(C2, pe)) | 0), + (n = (n + Math.imul(O, ce)) | 0), + (d = (d + Math.imul(O, pe)) | 0), + (l = (l + Math.imul(k, ve)) | 0), + (n = (n + Math.imul(k, be)) | 0), + (n = (n + Math.imul(D2, ve)) | 0), + (d = (d + Math.imul(D2, be)) | 0); + var Ge = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ge >>> 26)) | 0), + (Ge &= 67108863), + (l = Math.imul(G, ie)), + (n = Math.imul(G, ne)), + (n = (n + Math.imul(Y, ie)) | 0), + (d = Math.imul(Y, ne)), + (l = (l + Math.imul(V, fe)) | 0), + (n = (n + Math.imul(V, ae)) | 0), + (n = (n + Math.imul($2, fe)) | 0), + (d = (d + Math.imul($2, ae)) | 0), + (l = (l + Math.imul(j, oe)) | 0), + (n = (n + Math.imul(j, se)) | 0), + (n = (n + Math.imul(Z, oe)) | 0), + (d = (d + Math.imul(Z, se)) | 0), + (l = (l + Math.imul(W, he)) | 0), + (n = (n + Math.imul(W, ue)) | 0), + (n = (n + Math.imul(K, he)) | 0), + (d = (d + Math.imul(K, ue)) | 0), + (l = (l + Math.imul(z2, le)) | 0), + (n = (n + Math.imul(z2, de)) | 0), + (n = (n + Math.imul(H, le)) | 0), + (d = (d + Math.imul(H, de)) | 0), + (l = (l + Math.imul(F, ce)) | 0), + (n = (n + Math.imul(F, pe)) | 0), + (n = (n + Math.imul(U, ce)) | 0), + (d = (d + Math.imul(U, pe)) | 0), + (l = (l + Math.imul(C2, ve)) | 0), + (n = (n + Math.imul(C2, be)) | 0), + (n = (n + Math.imul(O, ve)) | 0), + (d = (d + Math.imul(O, be)) | 0); + var Ye = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Ye >>> 26)) | 0), + (Ye &= 67108863), + (l = Math.imul(G, fe)), + (n = Math.imul(G, ae)), + (n = (n + Math.imul(Y, fe)) | 0), + (d = Math.imul(Y, ae)), + (l = (l + Math.imul(V, oe)) | 0), + (n = (n + Math.imul(V, se)) | 0), + (n = (n + Math.imul($2, oe)) | 0), + (d = (d + Math.imul($2, se)) | 0), + (l = (l + Math.imul(j, he)) | 0), + (n = (n + Math.imul(j, ue)) | 0), + (n = (n + Math.imul(Z, he)) | 0), + (d = (d + Math.imul(Z, ue)) | 0), + (l = (l + Math.imul(W, le)) | 0), + (n = (n + Math.imul(W, de)) | 0), + (n = (n + Math.imul(K, le)) | 0), + (d = (d + Math.imul(K, de)) | 0), + (l = (l + Math.imul(z2, ce)) | 0), + (n = (n + Math.imul(z2, pe)) | 0), + (n = (n + Math.imul(H, ce)) | 0), + (d = (d + Math.imul(H, pe)) | 0), + (l = (l + Math.imul(F, ve)) | 0), + (n = (n + Math.imul(F, be)) | 0), + (n = (n + Math.imul(U, ve)) | 0), + (d = (d + Math.imul(U, be)) | 0); + var Xe = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Xe >>> 26)) | 0), + (Xe &= 67108863), + (l = Math.imul(G, oe)), + (n = Math.imul(G, se)), + (n = (n + Math.imul(Y, oe)) | 0), + (d = Math.imul(Y, se)), + (l = (l + Math.imul(V, he)) | 0), + (n = (n + Math.imul(V, ue)) | 0), + (n = (n + Math.imul($2, he)) | 0), + (d = (d + Math.imul($2, ue)) | 0), + (l = (l + Math.imul(j, le)) | 0), + (n = (n + Math.imul(j, de)) | 0), + (n = (n + Math.imul(Z, le)) | 0), + (d = (d + Math.imul(Z, de)) | 0), + (l = (l + Math.imul(W, ce)) | 0), + (n = (n + Math.imul(W, pe)) | 0), + (n = (n + Math.imul(K, ce)) | 0), + (d = (d + Math.imul(K, pe)) | 0), + (l = (l + Math.imul(z2, ve)) | 0), + (n = (n + Math.imul(z2, be)) | 0), + (n = (n + Math.imul(H, ve)) | 0), + (d = (d + Math.imul(H, be)) | 0); + var Je = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Je >>> 26)) | 0), + (Je &= 67108863), + (l = Math.imul(G, he)), + (n = Math.imul(G, ue)), + (n = (n + Math.imul(Y, he)) | 0), + (d = Math.imul(Y, ue)), + (l = (l + Math.imul(V, le)) | 0), + (n = (n + Math.imul(V, de)) | 0), + (n = (n + Math.imul($2, le)) | 0), + (d = (d + Math.imul($2, de)) | 0), + (l = (l + Math.imul(j, ce)) | 0), + (n = (n + Math.imul(j, pe)) | 0), + (n = (n + Math.imul(Z, ce)) | 0), + (d = (d + Math.imul(Z, pe)) | 0), + (l = (l + Math.imul(W, ve)) | 0), + (n = (n + Math.imul(W, be)) | 0), + (n = (n + Math.imul(K, ve)) | 0), + (d = (d + Math.imul(K, be)) | 0); + var Qe = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (Qe >>> 26)) | 0), + (Qe &= 67108863), + (l = Math.imul(G, le)), + (n = Math.imul(G, de)), + (n = (n + Math.imul(Y, le)) | 0), + (d = Math.imul(Y, de)), + (l = (l + Math.imul(V, ce)) | 0), + (n = (n + Math.imul(V, pe)) | 0), + (n = (n + Math.imul($2, ce)) | 0), + (d = (d + Math.imul($2, pe)) | 0), + (l = (l + Math.imul(j, ve)) | 0), + (n = (n + Math.imul(j, be)) | 0), + (n = (n + Math.imul(Z, ve)) | 0), + (d = (d + Math.imul(Z, be)) | 0); + var et = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (et >>> 26)) | 0), + (et &= 67108863), + (l = Math.imul(G, ce)), + (n = Math.imul(G, pe)), + (n = (n + Math.imul(Y, ce)) | 0), + (d = Math.imul(Y, pe)), + (l = (l + Math.imul(V, ve)) | 0), + (n = (n + Math.imul(V, be)) | 0), + (n = (n + Math.imul($2, ve)) | 0), + (d = (d + Math.imul($2, be)) | 0); + var tt = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + (b2 = (((d + (n >>> 13)) | 0) + (tt >>> 26)) | 0), (tt &= 67108863), (l = Math.imul(G, ve)), (n = Math.imul(G, be)), (n = (n + Math.imul(Y, ve)) | 0), (d = Math.imul(Y, be)); + var rt = (((b2 + l) | 0) + ((n & 8191) << 13)) | 0; + return ( + (b2 = (((d + (n >>> 13)) | 0) + (rt >>> 26)) | 0), + (rt &= 67108863), + (c[0] = ft), + (c[1] = Be), + (c[2] = qe), + (c[3] = ze), + (c[4] = He), + (c[5] = We), + (c[6] = Ke), + (c[7] = je), + (c[8] = Ze), + (c[9] = Ve), + (c[10] = $e), + (c[11] = Ge), + (c[12] = Ye), + (c[13] = Xe), + (c[14] = Je), + (c[15] = Qe), + (c[16] = et), + (c[17] = tt), + (c[18] = rt), + b2 !== 0 && ((c[19] = b2), h3.length++), + h3 + ); + }; + Math.imul || (L2 = q2); + function ge(v, i, a) { + (a.negative = i.negative ^ v.negative), (a.length = v.length + i.length); + for (var h3 = 0, s = 0, u = 0; u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b2 = h3 & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1); n <= l; n++) { + var d = u - n, + w = v.words[d] | 0, + g = i.words[n] | 0, + _2 = w * g, + A2 = _2 & 67108863; + (c = (c + ((_2 / 67108864) | 0)) | 0), (A2 = (A2 + b2) | 0), (b2 = A2 & 67108863), (c = (c + (A2 >>> 26)) | 0), (s += c >>> 26), (c &= 67108863); + } + (a.words[u] = b2), (h3 = c), (c = s); + } + return h3 !== 0 ? (a.words[u] = h3) : a.length--, a.strip(); + } + function _e(v, i, a) { + var h3 = new N(); + return h3.mulp(v, i, a); + } + f.prototype.mulTo = function (i, a) { + var h3, + s = this.length + i.length; + return this.length === 10 && i.length === 10 ? (h3 = L2(this, i, a)) : s < 63 ? (h3 = q2(this, i, a)) : s < 1024 ? (h3 = ge(this, i, a)) : (h3 = _e(this, i, a)), h3; + }; + function N(v, i) { + (this.x = v), (this.y = i); + } + (N.prototype.makeRBT = function (i) { + for (var a = new Array(i), h3 = f.prototype._countBits(i) - 1, s = 0; s < i; s++) a[s] = this.revBin(s, h3, i); + return a; + }), + (N.prototype.revBin = function (i, a, h3) { + if (i === 0 || i === h3 - 1) return i; + for (var s = 0, u = 0; u < a; u++) (s |= (i & 1) << (a - u - 1)), (i >>= 1); + return s; + }), + (N.prototype.permute = function (i, a, h3, s, u, c) { + for (var b2 = 0; b2 < c; b2++) (s[b2] = a[i[b2]]), (u[b2] = h3[i[b2]]); + }), + (N.prototype.transform = function (i, a, h3, s, u, c) { + this.permute(c, i, a, h3, s, u); + for (var b2 = 1; b2 < u; b2 <<= 1) + for (var l = b2 << 1, n = Math.cos((2 * Math.PI) / l), d = Math.sin((2 * Math.PI) / l), w = 0; w < u; w += l) + for (var g = n, _2 = d, A2 = 0; A2 < b2; A2++) { + var R2 = h3[w + A2], + I = s[w + A2], + Me = h3[w + A2 + b2], + k = s[w + A2 + b2], + D2 = g * Me - _2 * k; + (k = g * k + _2 * Me), (Me = D2), (h3[w + A2] = R2 + Me), (s[w + A2] = I + k), (h3[w + A2 + b2] = R2 - Me), (s[w + A2 + b2] = I - k), A2 !== l && ((D2 = n * g - d * _2), (_2 = n * _2 + d * g), (g = D2)); + } + }), + (N.prototype.guessLen13b = function (i, a) { + var h3 = Math.max(a, i) | 1, + s = h3 & 1, + u = 0; + for (h3 = (h3 / 2) | 0; h3; h3 = h3 >>> 1) u++; + return 1 << (u + 1 + s); + }), + (N.prototype.conjugate = function (i, a, h3) { + if (!(h3 <= 1)) + for (var s = 0; s < h3 / 2; s++) { + var u = i[s]; + (i[s] = i[h3 - s - 1]), (i[h3 - s - 1] = u), (u = a[s]), (a[s] = -a[h3 - s - 1]), (a[h3 - s - 1] = -u); + } + }), + (N.prototype.normalize13b = function (i, a) { + for (var h3 = 0, s = 0; s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h3; + (i[s] = u & 67108863), u < 67108864 ? (h3 = 0) : (h3 = (u / 67108864) | 0); + } + return i; + }), + (N.prototype.convert13b = function (i, a, h3, s) { + for (var u = 0, c = 0; c < a; c++) (u = u + (i[c] | 0)), (h3[2 * c] = u & 8191), (u = u >>> 13), (h3[2 * c + 1] = u & 8191), (u = u >>> 13); + for (c = 2 * a; c < s; ++c) h3[c] = 0; + r(u === 0), r((u & -8192) === 0); + }), + (N.prototype.stub = function (i) { + for (var a = new Array(i), h3 = 0; h3 < i; h3++) a[h3] = 0; + return a; + }), + (N.prototype.mulp = function (i, a, h3) { + var s = 2 * this.guessLen13b(i.length, a.length), + u = this.makeRBT(s), + c = this.stub(s), + b2 = new Array(s), + l = new Array(s), + n = new Array(s), + d = new Array(s), + w = new Array(s), + g = new Array(s), + _2 = h3.words; + (_2.length = s), this.convert13b(i.words, i.length, b2, s), this.convert13b(a.words, a.length, d, s), this.transform(b2, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A2 = 0; A2 < s; A2++) { + var R2 = l[A2] * w[A2] - n[A2] * g[A2]; + (n[A2] = l[A2] * g[A2] + n[A2] * w[A2]), (l[A2] = R2); + } + return this.conjugate(l, n, s), this.transform(l, n, _2, c, s, u), this.conjugate(_2, c, s), this.normalize13b(_2, s), (h3.negative = i.negative ^ a.negative), (h3.length = i.length + a.length), h3.strip(); + }), + (f.prototype.mul = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), this.mulTo(i, a); + }), + (f.prototype.mulf = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), _e(this, i, a); + }), + (f.prototype.imul = function (i) { + return this.clone().mulTo(i, this); + }), + (f.prototype.imuln = function (i) { + r(typeof i == 'number'), r(i < 67108864); + for (var a = 0, h3 = 0; h3 < this.length; h3++) { + var s = (this.words[h3] | 0) * i, + u = (s & 67108863) + (a & 67108863); + (a >>= 26), (a += (s / 67108864) | 0), (a += u >>> 26), (this.words[h3] = u & 67108863); + } + return a !== 0 && ((this.words[h3] = a), this.length++), this; + }), + (f.prototype.muln = function (i) { + return this.clone().imuln(i); + }), + (f.prototype.sqr = function () { + return this.mul(this); + }), + (f.prototype.isqr = function () { + return this.imul(this.clone()); + }), + (f.prototype.pow = function (i) { + var a = B(i); + if (a.length === 0) return new f(1); + for (var h3 = this, s = 0; s < a.length && a[s] === 0; s++, h3 = h3.sqr()); + if (++s < a.length) for (var u = h3.sqr(); s < a.length; s++, u = u.sqr()) a[s] !== 0 && (h3 = h3.mul(u)); + return h3; + }), + (f.prototype.iushln = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h3 = (i - a) / 26, + s = (67108863 >>> (26 - a)) << (26 - a), + u; + if (a !== 0) { + var c = 0; + for (u = 0; u < this.length; u++) { + var b2 = this.words[u] & s, + l = ((this.words[u] | 0) - b2) << a; + (this.words[u] = l | c), (c = b2 >>> (26 - a)); + } + c && ((this.words[u] = c), this.length++); + } + if (h3 !== 0) { + for (u = this.length - 1; u >= 0; u--) this.words[u + h3] = this.words[u]; + for (u = 0; u < h3; u++) this.words[u] = 0; + this.length += h3; + } + return this.strip(); + }), + (f.prototype.ishln = function (i) { + return r(this.negative === 0), this.iushln(i); + }), + (f.prototype.iushrn = function (i, a, h3) { + r(typeof i == 'number' && i >= 0); + var s; + a ? (s = (a - (a % 26)) / 26) : (s = 0); + var u = i % 26, + c = Math.min((i - u) / 26, this.length), + b2 = 67108863 ^ ((67108863 >>> u) << u), + l = h3; + if (((s -= c), (s = Math.max(0, s)), l)) { + for (var n = 0; n < c; n++) l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) for (this.length -= c, n = 0; n < this.length; n++) this.words[n] = this.words[n + c]; + else (this.words[0] = 0), (this.length = 1); + var d = 0; + for (n = this.length - 1; n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + (this.words[n] = (d << (26 - u)) | (w >>> u)), (d = w & b2); + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && ((this.words[0] = 0), (this.length = 1)), this.strip(); + }), + (f.prototype.ishrn = function (i, a, h3) { + return r(this.negative === 0), this.iushrn(i, a, h3); + }), + (f.prototype.shln = function (i) { + return this.clone().ishln(i); + }), + (f.prototype.ushln = function (i) { + return this.clone().iushln(i); + }), + (f.prototype.shrn = function (i) { + return this.clone().ishrn(i); + }), + (f.prototype.ushrn = function (i) { + return this.clone().iushrn(i); + }), + (f.prototype.testn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h3 = (i - a) / 26, + s = 1 << a; + if (this.length <= h3) return false; + var u = this.words[h3]; + return !!(u & s); + }), + (f.prototype.imaskn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h3 = (i - a) / 26; + if ((r(this.negative === 0, 'imaskn works only with positive numbers'), this.length <= h3)) return this; + if ((a !== 0 && h3++, (this.length = Math.min(h3, this.length)), a !== 0)) { + var s = 67108863 ^ ((67108863 >>> a) << a); + this.words[this.length - 1] &= s; + } + return this.strip(); + }), + (f.prototype.maskn = function (i) { + return this.clone().imaskn(i); + }), + (f.prototype.iaddn = function (i) { + return ( + r(typeof i == 'number'), + r(i < 67108864), + i < 0 + ? this.isubn(-i) + : this.negative !== 0 + ? this.length === 1 && (this.words[0] | 0) < i + ? ((this.words[0] = i - (this.words[0] | 0)), (this.negative = 0), this) + : ((this.negative = 0), this.isubn(i), (this.negative = 1), this) + : this._iaddn(i) + ); + }), + (f.prototype._iaddn = function (i) { + this.words[0] += i; + for (var a = 0; a < this.length && this.words[a] >= 67108864; a++) (this.words[a] -= 67108864), a === this.length - 1 ? (this.words[a + 1] = 1) : this.words[a + 1]++; + return (this.length = Math.max(this.length, a + 1)), this; + }), + (f.prototype.isubn = function (i) { + if ((r(typeof i == 'number'), r(i < 67108864), i < 0)) return this.iaddn(-i); + if (this.negative !== 0) return (this.negative = 0), this.iaddn(i), (this.negative = 1), this; + if (((this.words[0] -= i), this.length === 1 && this.words[0] < 0)) (this.words[0] = -this.words[0]), (this.negative = 1); + else for (var a = 0; a < this.length && this.words[a] < 0; a++) (this.words[a] += 67108864), (this.words[a + 1] -= 1); + return this.strip(); + }), + (f.prototype.addn = function (i) { + return this.clone().iaddn(i); + }), + (f.prototype.subn = function (i) { + return this.clone().isubn(i); + }), + (f.prototype.iabs = function () { + return (this.negative = 0), this; + }), + (f.prototype.abs = function () { + return this.clone().iabs(); + }), + (f.prototype._ishlnsubmul = function (i, a, h3) { + var s = i.length + h3, + u; + this._expand(s); + var c, + b2 = 0; + for (u = 0; u < i.length; u++) { + c = (this.words[u + h3] | 0) + b2; + var l = (i.words[u] | 0) * a; + (c -= l & 67108863), (b2 = (c >> 26) - ((l / 67108864) | 0)), (this.words[u + h3] = c & 67108863); + } + for (; u < this.length - h3; u++) (c = (this.words[u + h3] | 0) + b2), (b2 = c >> 26), (this.words[u + h3] = c & 67108863); + if (b2 === 0) return this.strip(); + for (r(b2 === -1), b2 = 0, u = 0; u < this.length; u++) (c = -(this.words[u] | 0) + b2), (b2 = c >> 26), (this.words[u] = c & 67108863); + return (this.negative = 1), this.strip(); + }), + (f.prototype._wordDiv = function (i, a) { + var h3 = this.length - i.length, + s = this.clone(), + u = i, + c = u.words[u.length - 1] | 0, + b2 = this._countBits(c); + (h3 = 26 - b2), h3 !== 0 && ((u = u.ushln(h3)), s.iushln(h3), (c = u.words[u.length - 1] | 0)); + var l = s.length - u.length, + n; + if (a !== 'mod') { + (n = new f(null)), (n.length = l + 1), (n.words = new Array(n.length)); + for (var d = 0; d < n.length; d++) n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && ((s = w), n && (n.words[l] = 1)); + for (var g = l - 1; g >= 0; g--) { + var _2 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_2 = Math.min((_2 / c) | 0, 67108863), s._ishlnsubmul(u, _2, g); s.negative !== 0; ) _2--, (s.negative = 0), s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _2); + } + return n && n.strip(), s.strip(), a !== 'div' && h3 !== 0 && s.iushrn(h3), {div: n || null, mod: s}; + }), + (f.prototype.divmod = function (i, a, h3) { + if ((r(!i.isZero()), this.isZero())) return {div: new f(0), mod: new f(0)}; + var s, u, c; + return this.negative !== 0 && i.negative === 0 + ? ((c = this.neg().divmod(i, a)), a !== 'mod' && (s = c.div.neg()), a !== 'div' && ((u = c.mod.neg()), h3 && u.negative !== 0 && u.iadd(i)), {div: s, mod: u}) + : this.negative === 0 && i.negative !== 0 + ? ((c = this.divmod(i.neg(), a)), a !== 'mod' && (s = c.div.neg()), {div: s, mod: c.mod}) + : (this.negative & i.negative) !== 0 + ? ((c = this.neg().divmod(i.neg(), a)), a !== 'div' && ((u = c.mod.neg()), h3 && u.negative !== 0 && u.isub(i)), {div: c.div, mod: u}) + : i.length > this.length || this.cmp(i) < 0 + ? {div: new f(0), mod: this} + : i.length === 1 + ? a === 'div' + ? {div: this.divn(i.words[0]), mod: null} + : a === 'mod' + ? {div: null, mod: new f(this.modn(i.words[0]))} + : {div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0]))} + : this._wordDiv(i, a); + }), + (f.prototype.div = function (i) { + return this.divmod(i, 'div', false).div; + }), + (f.prototype.mod = function (i) { + return this.divmod(i, 'mod', false).mod; + }), + (f.prototype.umod = function (i) { + return this.divmod(i, 'mod', true).mod; + }), + (f.prototype.divRound = function (i) { + var a = this.divmod(i); + if (a.mod.isZero()) return a.div; + var h3 = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, + s = i.ushrn(1), + u = i.andln(1), + c = h3.cmp(s); + return c < 0 || (u === 1 && c === 0) ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }), + (f.prototype.modn = function (i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h3 = 0, s = this.length - 1; s >= 0; s--) h3 = (a * h3 + (this.words[s] | 0)) % i; + return h3; + }), + (f.prototype.idivn = function (i) { + r(i <= 67108863); + for (var a = 0, h3 = this.length - 1; h3 >= 0; h3--) { + var s = (this.words[h3] | 0) + a * 67108864; + (this.words[h3] = (s / i) | 0), (a = s % i); + } + return this.strip(); + }), + (f.prototype.divn = function (i) { + return this.clone().idivn(i); + }), + (f.prototype.egcd = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h3 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = new f(0), b2 = new f(1), l = 0; a.isEven() && h3.isEven(); ) a.iushrn(1), h3.iushrn(1), ++l; + for (var n = h3.clone(), d = a.clone(); !a.isZero(); ) { + for (var w = 0, g = 1; (a.words[0] & g) === 0 && w < 26; ++w, g <<= 1); + if (w > 0) for (a.iushrn(w); w-- > 0; ) (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _2 = 0, A2 = 1; (h3.words[0] & A2) === 0 && _2 < 26; ++_2, A2 <<= 1); + if (_2 > 0) for (h3.iushrn(_2); _2-- > 0; ) (c.isOdd() || b2.isOdd()) && (c.iadd(n), b2.isub(d)), c.iushrn(1), b2.iushrn(1); + a.cmp(h3) >= 0 ? (a.isub(h3), s.isub(c), u.isub(b2)) : (h3.isub(a), c.isub(s), b2.isub(u)); + } + return {a: c, b: b2, gcd: h3.iushln(l)}; + }), + (f.prototype._invmp = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h3 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = h3.clone(); a.cmpn(1) > 0 && h3.cmpn(1) > 0; ) { + for (var b2 = 0, l = 1; (a.words[0] & l) === 0 && b2 < 26; ++b2, l <<= 1); + if (b2 > 0) for (a.iushrn(b2); b2-- > 0; ) s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1; (h3.words[0] & d) === 0 && n < 26; ++n, d <<= 1); + if (n > 0) for (h3.iushrn(n); n-- > 0; ) u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h3) >= 0 ? (a.isub(h3), s.isub(u)) : (h3.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? (w = s) : (w = u), w.cmpn(0) < 0 && w.iadd(i), w; + }), + (f.prototype.gcd = function (i) { + if (this.isZero()) return i.abs(); + if (i.isZero()) return this.abs(); + var a = this.clone(), + h3 = i.clone(); + (a.negative = 0), (h3.negative = 0); + for (var s = 0; a.isEven() && h3.isEven(); s++) a.iushrn(1), h3.iushrn(1); + do { + for (; a.isEven(); ) a.iushrn(1); + for (; h3.isEven(); ) h3.iushrn(1); + var u = a.cmp(h3); + if (u < 0) { + var c = a; + (a = h3), (h3 = c); + } else if (u === 0 || h3.cmpn(1) === 0) break; + a.isub(h3); + } while (true); + return h3.iushln(s); + }), + (f.prototype.invm = function (i) { + return this.egcd(i).a.umod(i); + }), + (f.prototype.isEven = function () { + return (this.words[0] & 1) === 0; + }), + (f.prototype.isOdd = function () { + return (this.words[0] & 1) === 1; + }), + (f.prototype.andln = function (i) { + return this.words[0] & i; + }), + (f.prototype.bincn = function (i) { + r(typeof i == 'number'); + var a = i % 26, + h3 = (i - a) / 26, + s = 1 << a; + if (this.length <= h3) return this._expand(h3 + 1), (this.words[h3] |= s), this; + for (var u = s, c = h3; u !== 0 && c < this.length; c++) { + var b2 = this.words[c] | 0; + (b2 += u), (u = b2 >>> 26), (b2 &= 67108863), (this.words[c] = b2); + } + return u !== 0 && ((this.words[c] = u), this.length++), this; + }), + (f.prototype.isZero = function () { + return this.length === 1 && this.words[0] === 0; + }), + (f.prototype.cmpn = function (i) { + var a = i < 0; + if (this.negative !== 0 && !a) return -1; + if (this.negative === 0 && a) return 1; + this.strip(); + var h3; + if (this.length > 1) h3 = 1; + else { + a && (i = -i), r(i <= 67108863, 'Number is too big'); + var s = this.words[0] | 0; + h3 = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h3 | 0 : h3; + }), + (f.prototype.cmp = function (i) { + if (this.negative !== 0 && i.negative === 0) return -1; + if (this.negative === 0 && i.negative !== 0) return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }), + (f.prototype.ucmp = function (i) { + if (this.length > i.length) return 1; + if (this.length < i.length) return -1; + for (var a = 0, h3 = this.length - 1; h3 >= 0; h3--) { + var s = this.words[h3] | 0, + u = i.words[h3] | 0; + if (s !== u) { + s < u ? (a = -1) : s > u && (a = 1); + break; + } + } + return a; + }), + (f.prototype.gtn = function (i) { + return this.cmpn(i) === 1; + }), + (f.prototype.gt = function (i) { + return this.cmp(i) === 1; + }), + (f.prototype.gten = function (i) { + return this.cmpn(i) >= 0; + }), + (f.prototype.gte = function (i) { + return this.cmp(i) >= 0; + }), + (f.prototype.ltn = function (i) { + return this.cmpn(i) === -1; + }), + (f.prototype.lt = function (i) { + return this.cmp(i) === -1; + }), + (f.prototype.lten = function (i) { + return this.cmpn(i) <= 0; + }), + (f.prototype.lte = function (i) { + return this.cmp(i) <= 0; + }), + (f.prototype.eqn = function (i) { + return this.cmpn(i) === 0; + }), + (f.prototype.eq = function (i) { + return this.cmp(i) === 0; + }), + (f.red = function (i) { + return new P(i); + }), + (f.prototype.toRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), r(this.negative === 0, 'red works only with positives'), i.convertTo(this)._forceRed(i); + }), + (f.prototype.fromRed = function () { + return r(this.red, 'fromRed works only with numbers in reduction context'), this.red.convertFrom(this); + }), + (f.prototype._forceRed = function (i) { + return (this.red = i), this; + }), + (f.prototype.forceRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), this._forceRed(i); + }), + (f.prototype.redAdd = function (i) { + return r(this.red, 'redAdd works only with red numbers'), this.red.add(this, i); + }), + (f.prototype.redIAdd = function (i) { + return r(this.red, 'redIAdd works only with red numbers'), this.red.iadd(this, i); + }), + (f.prototype.redSub = function (i) { + return r(this.red, 'redSub works only with red numbers'), this.red.sub(this, i); + }), + (f.prototype.redISub = function (i) { + return r(this.red, 'redISub works only with red numbers'), this.red.isub(this, i); + }), + (f.prototype.redShl = function (i) { + return r(this.red, 'redShl works only with red numbers'), this.red.shl(this, i); + }), + (f.prototype.redMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.mul(this, i); + }), + (f.prototype.redIMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.imul(this, i); + }), + (f.prototype.redSqr = function () { + return r(this.red, 'redSqr works only with red numbers'), this.red._verify1(this), this.red.sqr(this); + }), + (f.prototype.redISqr = function () { + return r(this.red, 'redISqr works only with red numbers'), this.red._verify1(this), this.red.isqr(this); + }), + (f.prototype.redSqrt = function () { + return r(this.red, 'redSqrt works only with red numbers'), this.red._verify1(this), this.red.sqrt(this); + }), + (f.prototype.redInvm = function () { + return r(this.red, 'redInvm works only with red numbers'), this.red._verify1(this), this.red.invm(this); + }), + (f.prototype.redNeg = function () { + return r(this.red, 'redNeg works only with red numbers'), this.red._verify1(this), this.red.neg(this); + }), + (f.prototype.redPow = function (i) { + return r(this.red && !i.red, 'redPow(normalNum)'), this.red._verify1(this), this.red.pow(this, i); + }); + var we = {k256: null, p224: null, p192: null, p25519: null}; + function ye(v, i) { + (this.name = v), (this.p = new f(i, 16)), (this.n = this.p.bitLength()), (this.k = new f(1).iushln(this.n).isub(this.p)), (this.tmp = this._tmp()); + } + (ye.prototype._tmp = function () { + var i = new f(null); + return (i.words = new Array(Math.ceil(this.n / 13))), i; + }), + (ye.prototype.ireduce = function (i) { + var a = i, + h3; + do this.split(a, this.tmp), (a = this.imulK(a)), (a = a.iadd(this.tmp)), (h3 = a.bitLength()); + while (h3 > this.n); + var s = h3 < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? ((a.words[0] = 0), (a.length = 1)) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }), + (ye.prototype.split = function (i, a) { + i.iushrn(this.n, 0, a); + }), + (ye.prototype.imulK = function (i) { + return i.imul(this.k); + }); + function xe() { + ye.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + o(xe, ye), + (xe.prototype.split = function (i, a) { + for (var h3 = 4194303, s = Math.min(i.length, 9), u = 0; u < s; u++) a.words[u] = i.words[u]; + if (((a.length = s), i.length <= 9)) { + (i.words[0] = 0), (i.length = 1); + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h3, u = 10; u < i.length; u++) { + var b2 = i.words[u] | 0; + (i.words[u - 10] = ((b2 & h3) << 4) | (c >>> 22)), (c = b2); + } + (c >>>= 22), (i.words[u - 10] = c), c === 0 && i.length > 10 ? (i.length -= 10) : (i.length -= 9); + }), + (xe.prototype.imulK = function (i) { + (i.words[i.length] = 0), (i.words[i.length + 1] = 0), (i.length += 2); + for (var a = 0, h3 = 0; h3 < i.length; h3++) { + var s = i.words[h3] | 0; + (a += s * 977), (i.words[h3] = a & 67108863), (a = s * 64 + ((a / 67108864) | 0)); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }); + function Re() { + ye.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + o(Re, ye); + function Ee() { + ye.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + o(Ee, ye); + function Ae() { + ye.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + o(Ae, ye), + (Ae.prototype.imulK = function (i) { + for (var a = 0, h3 = 0; h3 < i.length; h3++) { + var s = (i.words[h3] | 0) * 19 + a, + u = s & 67108863; + (s >>>= 26), (i.words[h3] = u), (a = s); + } + return a !== 0 && (i.words[i.length++] = a), i; + }), + (f._prime = function (i) { + if (we[i]) return we[i]; + var a; + if (i === 'k256') a = new xe(); + else if (i === 'p224') a = new Re(); + else if (i === 'p192') a = new Ee(); + else if (i === 'p25519') a = new Ae(); + else throw new Error('Unknown prime ' + i); + return (we[i] = a), a; + }); + function P(v) { + if (typeof v == 'string') { + var i = f._prime(v); + (this.m = i.p), (this.prime = i); + } else r(v.gtn(1), 'modulus must be greater than 1'), (this.m = v), (this.prime = null); + } + (P.prototype._verify1 = function (i) { + r(i.negative === 0, 'red works only with positives'), r(i.red, 'red works only with red numbers'); + }), + (P.prototype._verify2 = function (i, a) { + r((i.negative | a.negative) === 0, 'red works only with positives'), r(i.red && i.red === a.red, 'red works only with red numbers'); + }), + (P.prototype.imod = function (i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }), + (P.prototype.neg = function (i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }), + (P.prototype.add = function (i, a) { + this._verify2(i, a); + var h3 = i.add(a); + return h3.cmp(this.m) >= 0 && h3.isub(this.m), h3._forceRed(this); + }), + (P.prototype.iadd = function (i, a) { + this._verify2(i, a); + var h3 = i.iadd(a); + return h3.cmp(this.m) >= 0 && h3.isub(this.m), h3; + }), + (P.prototype.sub = function (i, a) { + this._verify2(i, a); + var h3 = i.sub(a); + return h3.cmpn(0) < 0 && h3.iadd(this.m), h3._forceRed(this); + }), + (P.prototype.isub = function (i, a) { + this._verify2(i, a); + var h3 = i.isub(a); + return h3.cmpn(0) < 0 && h3.iadd(this.m), h3; + }), + (P.prototype.shl = function (i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }), + (P.prototype.imul = function (i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }), + (P.prototype.mul = function (i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }), + (P.prototype.isqr = function (i) { + return this.imul(i, i.clone()); + }), + (P.prototype.sqr = function (i) { + return this.mul(i, i); + }), + (P.prototype.sqrt = function (i) { + if (i.isZero()) return i.clone(); + var a = this.m.andln(3); + if ((r(a % 2 === 1), a === 3)) { + var h3 = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h3); + } + for (var s = this.m.subn(1), u = 0; !s.isZero() && s.andln(1) === 0; ) u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), + b2 = c.redNeg(), + l = this.m.subn(1).iushrn(1), + n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this); this.pow(n, l).cmp(b2) !== 0; ) n.redIAdd(b2); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _2 = u; g.cmp(c) !== 0; ) { + for (var A2 = g, R2 = 0; A2.cmp(c) !== 0; R2++) A2 = A2.redSqr(); + r(R2 < _2); + var I = this.pow(d, new f(1).iushln(_2 - R2 - 1)); + (w = w.redMul(I)), (d = I.redSqr()), (g = g.redMul(d)), (_2 = R2); + } + return w; + }), + (P.prototype.invm = function (i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? ((a.negative = 0), this.imod(a).redNeg()) : this.imod(a); + }), + (P.prototype.pow = function (i, a) { + if (a.isZero()) return new f(1).toRed(this); + if (a.cmpn(1) === 0) return i.clone(); + var h3 = 4, + s = new Array(1 << h3); + (s[0] = new f(1).toRed(this)), (s[1] = i); + for (var u = 2; u < s.length; u++) s[u] = this.mul(s[u - 1], i); + var c = s[0], + b2 = 0, + l = 0, + n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1; u >= 0; u--) { + for (var d = a.words[u], w = n - 1; w >= 0; w--) { + var g = (d >> w) & 1; + if ((c !== s[0] && (c = this.sqr(c)), g === 0 && b2 === 0)) { + l = 0; + continue; + } + (b2 <<= 1), (b2 |= g), l++, !(l !== h3 && (u !== 0 || w !== 0)) && ((c = this.mul(c, s[b2])), (l = 0), (b2 = 0)); + } + n = 26; + } + return c; + }), + (P.prototype.convertTo = function (i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }), + (P.prototype.convertFrom = function (i) { + var a = i.clone(); + return (a.red = null), a; + }), + (f.mont = function (i) { + return new Se(i); + }); + function Se(v) { + P.call(this, v), + (this.shift = this.m.bitLength()), + this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), + (this.r = new f(1).iushln(this.shift)), + (this.r2 = this.imod(this.r.sqr())), + (this.rinv = this.r._invmp(this.m)), + (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), + (this.minv = this.minv.umod(this.r)), + (this.minv = this.r.sub(this.minv)); + } + o(Se, P), + (Se.prototype.convertTo = function (i) { + return this.imod(i.ushln(this.shift)); + }), + (Se.prototype.convertFrom = function (i) { + var a = this.imod(i.mul(this.rinv)); + return (a.red = null), a; + }), + (Se.prototype.imul = function (i, a) { + if (i.isZero() || a.isZero()) return (i.words[0] = 0), (i.length = 1), i; + var h3 = i.imul(a), + s = h3.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h3.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.mul = function (i, a) { + if (i.isZero() || a.isZero()) return new f(0)._forceRed(this); + var h3 = i.mul(a), + s = h3.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h3.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.invm = function (i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }); + })(typeof Ll > 'u' || Ll, h2); + }); + Nl = T2(d2 => { + var js = d2; + function uA(t, e) { + if (Array.isArray(t)) return t.slice(); + if (!t) return []; + var r = []; + if (typeof t != 'string') { + for (var o = 0; o < t.length; o++) r[o] = t[o] | 0; + return r; + } + if (e === 'hex') { + (t = t.replace(/[^a-z0-9]+/gi, '')), t.length % 2 !== 0 && (t = '0' + t); + for (var o = 0; o < t.length; o += 2) r.push(parseInt(t[o] + t[o + 1], 16)); + } else + for (var o = 0; o < t.length; o++) { + var f = t.charCodeAt(o), + p = f >> 8, + m2 = f & 255; + p ? r.push(p, m2) : r.push(m2); + } + return r; + } + js.toArray = uA; + function u2(t) { + return t.length === 1 ? '0' + t : t; + } + js.zero2 = u2; + function l2(t) { + for (var e = '', r = 0; r < t.length; r++) e += u2(t[r].toString(16)); + return e; + } + js.toHex = l2; + js.encode = function (e, r) { + return r === 'hex' ? l2(e) : e; + }; + }); + or = T2(c2 => { + var Pr = c2, + lA = ri(), + dA = ar(), + Zs = Nl(); + Pr.assert = dA; + Pr.toArray = Zs.toArray; + Pr.zero2 = Zs.zero2; + Pr.toHex = Zs.toHex; + Pr.encode = Zs.encode; + function cA(t, e, r) { + var o = new Array(Math.max(t.bitLength(), r) + 1); + o.fill(0); + for (var f = 1 << (e + 1), p = t.clone(), m2 = 0; m2 < o.length; m2++) { + var y2, + M = p.andln(f - 1); + p.isOdd() ? (M > (f >> 1) - 1 ? (y2 = (f >> 1) - M) : (y2 = M), p.isubn(y2)) : (y2 = 0), (o[m2] = y2), p.iushrn(1); + } + return o; + } + Pr.getNAF = cA; + function pA(t, e) { + var r = [[], []]; + (t = t.clone()), (e = e.clone()); + for (var o = 0, f = 0, p; t.cmpn(-o) > 0 || e.cmpn(-f) > 0; ) { + var m2 = (t.andln(3) + o) & 3, + y2 = (e.andln(3) + f) & 3; + m2 === 3 && (m2 = -1), y2 === 3 && (y2 = -1); + var M; + (m2 & 1) === 0 ? (M = 0) : ((p = (t.andln(7) + o) & 7), (p === 3 || p === 5) && y2 === 2 ? (M = -m2) : (M = m2)), r[0].push(M); + var x; + (y2 & 1) === 0 ? (x = 0) : ((p = (e.andln(7) + f) & 7), (p === 3 || p === 5) && m2 === 2 ? (x = -y2) : (x = y2)), r[1].push(x), 2 * o === M + 1 && (o = 1 - o), 2 * f === x + 1 && (f = 1 - f), t.iushrn(1), e.iushrn(1); + } + return r; + } + Pr.getJSF = pA; + function vA(t, e, r) { + var o = '_' + e; + t.prototype[e] = function () { + return this[o] !== undefined ? this[o] : (this[o] = r.call(this)); + }; + } + Pr.cachedProperty = vA; + function bA(t) { + return typeof t == 'string' ? Pr.toArray(t, 'hex') : t; + } + Pr.parseBytes = bA; + function mA(t) { + return new lA(t, 'hex', 'le'); + } + Pr.intFromLE = mA; + }); + Oa = T2((xk, p2) => { + var Cn = ri(), + Ca = or(), + Vs = Ca.getNAF, + gA = Ca.getJSF, + $s = Ca.assert; + function Xi(t, e) { + (this.type = t), + (this.p = new Cn(e.p, 16)), + (this.red = e.prime ? Cn.red(e.prime) : Cn.mont(this.p)), + (this.zero = new Cn(0).toRed(this.red)), + (this.one = new Cn(1).toRed(this.red)), + (this.two = new Cn(2).toRed(this.red)), + (this.n = e.n && new Cn(e.n, 16)), + (this.g = e.g && this.pointFromJSON(e.g, e.gRed)), + (this._wnafT1 = new Array(4)), + (this._wnafT2 = new Array(4)), + (this._wnafT3 = new Array(4)), + (this._wnafT4 = new Array(4)), + (this._bitLength = this.n ? this.n.bitLength() : 0); + var r = this.n && this.p.div(this.n); + !r || r.cmpn(100) > 0 ? (this.redN = null) : ((this._maxwellTrick = true), (this.redN = this.n.toRed(this.red))); + } + p2.exports = Xi; + Xi.prototype.point = function () { + throw new Error('Not implemented'); + }; + Xi.prototype.validate = function () { + throw new Error('Not implemented'); + }; + Xi.prototype._fixedNafMul = function (e, r) { + $s(e.precomputed); + var o = e._getDoubles(), + f = Vs(r, 1, this._bitLength), + p = (1 << (o.step + 1)) - (o.step % 2 === 0 ? 2 : 1); + p /= 3; + var m2 = [], + y2, + M; + for (y2 = 0; y2 < f.length; y2 += o.step) { + M = 0; + for (var x = y2 + o.step - 1; x >= y2; x--) M = (M << 1) + f[x]; + m2.push(M); + } + for (var S = this.jpoint(null, null, null), E2 = this.jpoint(null, null, null), B = p; B > 0; B--) { + for (y2 = 0; y2 < m2.length; y2++) (M = m2[y2]), M === B ? (E2 = E2.mixedAdd(o.points[y2])) : M === -B && (E2 = E2.mixedAdd(o.points[y2].neg())); + S = S.add(E2); + } + return S.toP(); + }; + Xi.prototype._wnafMul = function (e, r) { + var o = 4, + f = e._getNAFPoints(o); + o = f.wnd; + for (var p = f.points, m2 = Vs(r, o, this._bitLength), y2 = this.jpoint(null, null, null), M = m2.length - 1; M >= 0; M--) { + for (var x = 0; M >= 0 && m2[M] === 0; M--) x++; + if ((M >= 0 && x++, (y2 = y2.dblp(x)), M < 0)) break; + var S = m2[M]; + $s(S !== 0), e.type === 'affine' ? (S > 0 ? (y2 = y2.mixedAdd(p[(S - 1) >> 1])) : (y2 = y2.mixedAdd(p[(-S - 1) >> 1].neg()))) : S > 0 ? (y2 = y2.add(p[(S - 1) >> 1])) : (y2 = y2.add(p[(-S - 1) >> 1].neg())); + } + return e.type === 'affine' ? y2.toP() : y2; + }; + Xi.prototype._wnafMulAdd = function (e, r, o, f, p) { + var m2 = this._wnafT1, + y2 = this._wnafT2, + M = this._wnafT3, + x = 0, + S, + E2, + B; + for (S = 0; S < f; S++) { + B = r[S]; + var q2 = B._getNAFPoints(e); + (m2[S] = q2.wnd), (y2[S] = q2.points); + } + for (S = f - 1; S >= 1; S -= 2) { + var L2 = S - 1, + ge = S; + if (m2[L2] !== 1 || m2[ge] !== 1) { + (M[L2] = Vs(o[L2], m2[L2], this._bitLength)), (M[ge] = Vs(o[ge], m2[ge], this._bitLength)), (x = Math.max(M[L2].length, x)), (x = Math.max(M[ge].length, x)); + continue; + } + var _e = [r[L2], null, null, r[ge]]; + r[L2].y.cmp(r[ge].y) === 0 + ? ((_e[1] = r[L2].add(r[ge])), (_e[2] = r[L2].toJ().mixedAdd(r[ge].neg()))) + : r[L2].y.cmp(r[ge].y.redNeg()) === 0 + ? ((_e[1] = r[L2].toJ().mixedAdd(r[ge])), (_e[2] = r[L2].add(r[ge].neg()))) + : ((_e[1] = r[L2].toJ().mixedAdd(r[ge])), (_e[2] = r[L2].toJ().mixedAdd(r[ge].neg()))); + var N = [-3, -1, -5, -7, 0, 7, 5, 1, 3], + we = gA(o[L2], o[ge]); + for (x = Math.max(we[0].length, x), M[L2] = new Array(x), M[ge] = new Array(x), E2 = 0; E2 < x; E2++) { + var ye = we[0][E2] | 0, + xe = we[1][E2] | 0; + (M[L2][E2] = N[(ye + 1) * 3 + (xe + 1)]), (M[ge][E2] = 0), (y2[L2] = _e); + } + } + var Re = this.jpoint(null, null, null), + Ee = this._wnafT4; + for (S = x; S >= 0; S--) { + for (var Ae = 0; S >= 0; ) { + var P = true; + for (E2 = 0; E2 < f; E2++) (Ee[E2] = M[E2][S] | 0), Ee[E2] !== 0 && (P = false); + if (!P) break; + Ae++, S--; + } + if ((S >= 0 && Ae++, (Re = Re.dblp(Ae)), S < 0)) break; + for (E2 = 0; E2 < f; E2++) { + var Se = Ee[E2]; + Se !== 0 && (Se > 0 ? (B = y2[E2][(Se - 1) >> 1]) : Se < 0 && (B = y2[E2][(-Se - 1) >> 1].neg()), B.type === 'affine' ? (Re = Re.mixedAdd(B)) : (Re = Re.add(B))); + } + } + for (S = 0; S < f; S++) y2[S] = null; + return p ? Re : Re.toP(); + }; + function _r(t, e) { + (this.curve = t), (this.type = e), (this.precomputed = null); + } + Xi.BasePoint = _r; + _r.prototype.eq = function () { + throw new Error('Not implemented'); + }; + _r.prototype.validate = function () { + return this.curve.validate(this); + }; + Xi.prototype.decodePoint = function (e, r) { + e = Ca.toArray(e, r); + var o = this.p.byteLength(); + if ((e[0] === 4 || e[0] === 6 || e[0] === 7) && e.length - 1 === 2 * o) { + e[0] === 6 ? $s(e[e.length - 1] % 2 === 0) : e[0] === 7 && $s(e[e.length - 1] % 2 === 1); + var f = this.point(e.slice(1, 1 + o), e.slice(1 + o, 1 + 2 * o)); + return f; + } else if ((e[0] === 2 || e[0] === 3) && e.length - 1 === o) return this.pointFromX(e.slice(1, 1 + o), e[0] === 3); + throw new Error('Unknown point format'); + }; + _r.prototype.encodeCompressed = function (e) { + return this.encode(e, true); + }; + _r.prototype._encode = function (e) { + var r = this.curve.p.byteLength(), + o = this.getX().toArray('be', r); + return e ? [this.getY().isEven() ? 2 : 3].concat(o) : [4].concat(o, this.getY().toArray('be', r)); + }; + _r.prototype.encode = function (e, r) { + return Ca.encode(this._encode(r), e); + }; + _r.prototype.precompute = function (e) { + if (this.precomputed) return this; + var r = {doubles: null, naf: null, beta: null}; + return (r.naf = this._getNAFPoints(8)), (r.doubles = this._getDoubles(4, e)), (r.beta = this._getBeta()), (this.precomputed = r), this; + }; + _r.prototype._hasDoubles = function (e) { + if (!this.precomputed) return false; + var r = this.precomputed.doubles; + return r ? r.points.length >= Math.ceil((e.bitLength() + 1) / r.step) : false; + }; + _r.prototype._getDoubles = function (e, r) { + if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles; + for (var o = [this], f = this, p = 0; p < r; p += e) { + for (var m2 = 0; m2 < e; m2++) f = f.dbl(); + o.push(f); + } + return {step: e, points: o}; + }; + _r.prototype._getNAFPoints = function (e) { + if (this.precomputed && this.precomputed.naf) return this.precomputed.naf; + for (var r = [this], o = (1 << e) - 1, f = o === 1 ? null : this.dbl(), p = 1; p < o; p++) r[p] = r[p - 1].add(f); + return {wnd: e, points: r}; + }; + _r.prototype._getBeta = function () { + return null; + }; + _r.prototype.dblp = function (e) { + for (var r = this, o = 0; o < e; o++) r = r.dbl(); + return r; + }; + }); + b2 = T2((Sk, v2) => { + var yA = or(), + lt = ri(), + Dl = Ie(), + Bf = Oa(), + wA = yA.assert; + function xr(t) { + Bf.call(this, 'short', t), + (this.a = new lt(t.a, 16).toRed(this.red)), + (this.b = new lt(t.b, 16).toRed(this.red)), + (this.tinv = this.two.redInvm()), + (this.zeroA = this.a.fromRed().cmpn(0) === 0), + (this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0), + (this.endo = this._getEndomorphism(t)), + (this._endoWnafT1 = new Array(4)), + (this._endoWnafT2 = new Array(4)); + } + Dl(xr, Bf); + v2.exports = xr; + xr.prototype._getEndomorphism = function (e) { + if (!(!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)) { + var r, o; + if (e.beta) r = new lt(e.beta, 16).toRed(this.red); + else { + var f = this._getEndoRoots(this.p); + (r = f[0].cmp(f[1]) < 0 ? f[0] : f[1]), (r = r.toRed(this.red)); + } + if (e.lambda) o = new lt(e.lambda, 16); + else { + var p = this._getEndoRoots(this.n); + this.g.mul(p[0]).x.cmp(this.g.x.redMul(r)) === 0 ? (o = p[0]) : ((o = p[1]), wA(this.g.mul(o).x.cmp(this.g.x.redMul(r)) === 0)); + } + var m2; + return ( + e.basis + ? (m2 = e.basis.map(function (y2) { + return {a: new lt(y2.a, 16), b: new lt(y2.b, 16)}; + })) + : (m2 = this._getEndoBasis(o)), + {beta: r, lambda: o, basis: m2} + ); + } + }; + xr.prototype._getEndoRoots = function (e) { + var r = e === this.p ? this.red : lt.mont(e), + o = new lt(2).toRed(r).redInvm(), + f = o.redNeg(), + p = new lt(3).toRed(r).redNeg().redSqrt().redMul(o), + m2 = f.redAdd(p).fromRed(), + y2 = f.redSub(p).fromRed(); + return [m2, y2]; + }; + xr.prototype._getEndoBasis = function (e) { + for (var r = this.n.ushrn(Math.floor(this.n.bitLength() / 2)), o = e, f = this.n.clone(), p = new lt(1), m2 = new lt(0), y2 = new lt(0), M = new lt(1), x, S, E2, B, q2, L2, ge, _e = 0, N, we; o.cmpn(0) !== 0; ) { + var ye = f.div(o); + (N = f.sub(ye.mul(o))), (we = y2.sub(ye.mul(p))); + var xe = M.sub(ye.mul(m2)); + if (!E2 && N.cmp(r) < 0) (x = ge.neg()), (S = p), (E2 = N.neg()), (B = we); + else if (E2 && ++_e === 2) break; + (ge = N), (f = o), (o = N), (y2 = p), (p = we), (M = m2), (m2 = xe); + } + (q2 = N.neg()), (L2 = we); + var Re = E2.sqr().add(B.sqr()), + Ee = q2.sqr().add(L2.sqr()); + return ( + Ee.cmp(Re) >= 0 && ((q2 = x), (L2 = S)), + E2.negative && ((E2 = E2.neg()), (B = B.neg())), + q2.negative && ((q2 = q2.neg()), (L2 = L2.neg())), + [ + {a: E2, b: B}, + {a: q2, b: L2} + ] + ); + }; + xr.prototype._endoSplit = function (e) { + var r = this.endo.basis, + o = r[0], + f = r[1], + p = f.b.mul(e).divRound(this.n), + m2 = o.b.neg().mul(e).divRound(this.n), + y2 = p.mul(o.a), + M = m2.mul(f.a), + x = p.mul(o.b), + S = m2.mul(f.b), + E2 = e.sub(y2).sub(M), + B = x.add(S).neg(); + return {k1: E2, k2: B}; + }; + xr.prototype.pointFromX = function (e, r) { + (e = new lt(e, 16)), e.red || (e = e.toRed(this.red)); + var o = e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b), + f = o.redSqrt(); + if (f.redSqr().redSub(o).cmp(this.zero) !== 0) throw new Error('invalid point'); + var p = f.fromRed().isOdd(); + return ((r && !p) || (!r && p)) && (f = f.redNeg()), this.point(e, f); + }; + xr.prototype.validate = function (e) { + if (e.inf) return true; + var {x: r, y: o} = e, + f = this.a.redMul(r), + p = r.redSqr().redMul(r).redIAdd(f).redIAdd(this.b); + return o.redSqr().redISub(p).cmpn(0) === 0; + }; + xr.prototype._endoWnafMulAdd = function (e, r, o) { + for (var f = this._endoWnafT1, p = this._endoWnafT2, m2 = 0; m2 < e.length; m2++) { + var y2 = this._endoSplit(r[m2]), + M = e[m2], + x = M._getBeta(); + y2.k1.negative && (y2.k1.ineg(), (M = M.neg(true))), y2.k2.negative && (y2.k2.ineg(), (x = x.neg(true))), (f[m2 * 2] = M), (f[m2 * 2 + 1] = x), (p[m2 * 2] = y2.k1), (p[m2 * 2 + 1] = y2.k2); + } + for (var S = this._wnafMulAdd(1, f, p, m2 * 2, o), E2 = 0; E2 < m2 * 2; E2++) (f[E2] = null), (p[E2] = null); + return S; + }; + function Ct(t, e, r, o) { + Bf.BasePoint.call(this, t, 'affine'), + e === null && r === null + ? ((this.x = null), (this.y = null), (this.inf = true)) + : ((this.x = new lt(e, 16)), + (this.y = new lt(r, 16)), + o && (this.x.forceRed(this.curve.red), this.y.forceRed(this.curve.red)), + this.x.red || (this.x = this.x.toRed(this.curve.red)), + this.y.red || (this.y = this.y.toRed(this.curve.red)), + (this.inf = false)); + } + Dl(Ct, Bf.BasePoint); + xr.prototype.point = function (e, r, o) { + return new Ct(this, e, r, o); + }; + xr.prototype.pointFromJSON = function (e, r) { + return Ct.fromJSON(this, e, r); + }; + Ct.prototype._getBeta = function () { + if (!!this.curve.endo) { + var e = this.precomputed; + if (e && e.beta) return e.beta; + var r = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (e) { + var o = this.curve, + f = function (p) { + return o.point(p.x.redMul(o.endo.beta), p.y); + }; + (e.beta = r), (r.precomputed = {beta: null, naf: e.naf && {wnd: e.naf.wnd, points: e.naf.points.map(f)}, doubles: e.doubles && {step: e.doubles.step, points: e.doubles.points.map(f)}}); + } + return r; + } + }; + Ct.prototype.toJSON = function () { + return this.precomputed + ? [ + this.x, + this.y, + this.precomputed && { + doubles: this.precomputed.doubles && {step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1)}, + naf: this.precomputed.naf && {wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1)} + } + ] + : [this.x, this.y]; + }; + Ct.fromJSON = function (e, r, o) { + typeof r == 'string' && (r = JSON.parse(r)); + var f = e.point(r[0], r[1], o); + if (!r[2]) return f; + function p(y2) { + return e.point(y2[0], y2[1], o); + } + var m2 = r[2]; + return (f.precomputed = {beta: null, doubles: m2.doubles && {step: m2.doubles.step, points: [f].concat(m2.doubles.points.map(p))}, naf: m2.naf && {wnd: m2.naf.wnd, points: [f].concat(m2.naf.points.map(p))}}), f; + }; + Ct.prototype.inspect = function () { + return this.isInfinity() ? '' : ''; + }; + Ct.prototype.isInfinity = function () { + return this.inf; + }; + Ct.prototype.add = function (e) { + if (this.inf) return e; + if (e.inf) return this; + if (this.eq(e)) return this.dbl(); + if (this.neg().eq(e)) return this.curve.point(null, null); + if (this.x.cmp(e.x) === 0) return this.curve.point(null, null); + var r = this.y.redSub(e.y); + r.cmpn(0) !== 0 && (r = r.redMul(this.x.redSub(e.x).redInvm())); + var o = r.redSqr().redISub(this.x).redISub(e.x), + f = r.redMul(this.x.redSub(o)).redISub(this.y); + return this.curve.point(o, f); + }; + Ct.prototype.dbl = function () { + if (this.inf) return this; + var e = this.y.redAdd(this.y); + if (e.cmpn(0) === 0) return this.curve.point(null, null); + var r = this.curve.a, + o = this.x.redSqr(), + f = e.redInvm(), + p = o.redAdd(o).redIAdd(o).redIAdd(r).redMul(f), + m2 = p.redSqr().redISub(this.x.redAdd(this.x)), + y2 = p.redMul(this.x.redSub(m2)).redISub(this.y); + return this.curve.point(m2, y2); + }; + Ct.prototype.getX = function () { + return this.x.fromRed(); + }; + Ct.prototype.getY = function () { + return this.y.fromRed(); + }; + Ct.prototype.mul = function (e) { + return (e = new lt(e, 16)), this.isInfinity() ? this : this._hasDoubles(e) ? this.curve._fixedNafMul(this, e) : this.curve.endo ? this.curve._endoWnafMulAdd([this], [e]) : this.curve._wnafMul(this, e); + }; + Ct.prototype.mulAdd = function (e, r, o) { + var f = [this, r], + p = [e, o]; + return this.curve.endo ? this.curve._endoWnafMulAdd(f, p) : this.curve._wnafMulAdd(1, f, p, 2); + }; + Ct.prototype.jmulAdd = function (e, r, o) { + var f = [this, r], + p = [e, o]; + return this.curve.endo ? this.curve._endoWnafMulAdd(f, p, true) : this.curve._wnafMulAdd(1, f, p, 2, true); + }; + Ct.prototype.eq = function (e) { + return this === e || (this.inf === e.inf && (this.inf || (this.x.cmp(e.x) === 0 && this.y.cmp(e.y) === 0))); + }; + Ct.prototype.neg = function (e) { + if (this.inf) return this; + var r = this.curve.point(this.x, this.y.redNeg()); + if (e && this.precomputed) { + var o = this.precomputed, + f = function (p) { + return p.neg(); + }; + r.precomputed = {naf: o.naf && {wnd: o.naf.wnd, points: o.naf.points.map(f)}, doubles: o.doubles && {step: o.doubles.step, points: o.doubles.points.map(f)}}; + } + return r; + }; + Ct.prototype.toJ = function () { + if (this.inf) return this.curve.jpoint(null, null, null); + var e = this.curve.jpoint(this.x, this.y, this.curve.one); + return e; + }; + function Wt(t, e, r, o) { + Bf.BasePoint.call(this, t, 'jacobian'), + e === null && r === null && o === null ? ((this.x = this.curve.one), (this.y = this.curve.one), (this.z = new lt(0))) : ((this.x = new lt(e, 16)), (this.y = new lt(r, 16)), (this.z = new lt(o, 16))), + this.x.red || (this.x = this.x.toRed(this.curve.red)), + this.y.red || (this.y = this.y.toRed(this.curve.red)), + this.z.red || (this.z = this.z.toRed(this.curve.red)), + (this.zOne = this.z === this.curve.one); + } + Dl(Wt, Bf.BasePoint); + xr.prototype.jpoint = function (e, r, o) { + return new Wt(this, e, r, o); + }; + Wt.prototype.toP = function () { + if (this.isInfinity()) return this.curve.point(null, null); + var e = this.z.redInvm(), + r = e.redSqr(), + o = this.x.redMul(r), + f = this.y.redMul(r).redMul(e); + return this.curve.point(o, f); + }; + Wt.prototype.neg = function () { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); + }; + Wt.prototype.add = function (e) { + if (this.isInfinity()) return e; + if (e.isInfinity()) return this; + var r = e.z.redSqr(), + o = this.z.redSqr(), + f = this.x.redMul(r), + p = e.x.redMul(o), + m2 = this.y.redMul(r.redMul(e.z)), + y2 = e.y.redMul(o.redMul(this.z)), + M = f.redSub(p), + x = m2.redSub(y2); + if (M.cmpn(0) === 0) return x.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); + var S = M.redSqr(), + E2 = S.redMul(M), + B = f.redMul(S), + q2 = x.redSqr().redIAdd(E2).redISub(B).redISub(B), + L2 = x.redMul(B.redISub(q2)).redISub(m2.redMul(E2)), + ge = this.z.redMul(e.z).redMul(M); + return this.curve.jpoint(q2, L2, ge); + }; + Wt.prototype.mixedAdd = function (e) { + if (this.isInfinity()) return e.toJ(); + if (e.isInfinity()) return this; + var r = this.z.redSqr(), + o = this.x, + f = e.x.redMul(r), + p = this.y, + m2 = e.y.redMul(r).redMul(this.z), + y2 = o.redSub(f), + M = p.redSub(m2); + if (y2.cmpn(0) === 0) return M.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); + var x = y2.redSqr(), + S = x.redMul(y2), + E2 = o.redMul(x), + B = M.redSqr().redIAdd(S).redISub(E2).redISub(E2), + q2 = M.redMul(E2.redISub(B)).redISub(p.redMul(S)), + L2 = this.z.redMul(y2); + return this.curve.jpoint(B, q2, L2); + }; + Wt.prototype.dblp = function (e) { + if (e === 0) return this; + if (this.isInfinity()) return this; + if (!e) return this.dbl(); + var r; + if (this.curve.zeroA || this.curve.threeA) { + var o = this; + for (r = 0; r < e; r++) o = o.dbl(); + return o; + } + var f = this.curve.a, + p = this.curve.tinv, + m2 = this.x, + y2 = this.y, + M = this.z, + x = M.redSqr().redSqr(), + S = y2.redAdd(y2); + for (r = 0; r < e; r++) { + var E2 = m2.redSqr(), + B = S.redSqr(), + q2 = B.redSqr(), + L2 = E2.redAdd(E2).redIAdd(E2).redIAdd(f.redMul(x)), + ge = m2.redMul(B), + _e = L2.redSqr().redISub(ge.redAdd(ge)), + N = ge.redISub(_e), + we = L2.redMul(N); + we = we.redIAdd(we).redISub(q2); + var ye = S.redMul(M); + r + 1 < e && (x = x.redMul(q2)), (m2 = _e), (M = ye), (S = we); + } + return this.curve.jpoint(m2, S.redMul(p), M); + }; + Wt.prototype.dbl = function () { + return this.isInfinity() ? this : this.curve.zeroA ? this._zeroDbl() : this.curve.threeA ? this._threeDbl() : this._dbl(); + }; + Wt.prototype._zeroDbl = function () { + var e, r, o; + if (this.zOne) { + var f = this.x.redSqr(), + p = this.y.redSqr(), + m2 = p.redSqr(), + y2 = this.x.redAdd(p).redSqr().redISub(f).redISub(m2); + y2 = y2.redIAdd(y2); + var M = f.redAdd(f).redIAdd(f), + x = M.redSqr().redISub(y2).redISub(y2), + S = m2.redIAdd(m2); + (S = S.redIAdd(S)), (S = S.redIAdd(S)), (e = x), (r = M.redMul(y2.redISub(x)).redISub(S)), (o = this.y.redAdd(this.y)); + } else { + var E2 = this.x.redSqr(), + B = this.y.redSqr(), + q2 = B.redSqr(), + L2 = this.x.redAdd(B).redSqr().redISub(E2).redISub(q2); + L2 = L2.redIAdd(L2); + var ge = E2.redAdd(E2).redIAdd(E2), + _e = ge.redSqr(), + N = q2.redIAdd(q2); + (N = N.redIAdd(N)), (N = N.redIAdd(N)), (e = _e.redISub(L2).redISub(L2)), (r = ge.redMul(L2.redISub(e)).redISub(N)), (o = this.y.redMul(this.z)), (o = o.redIAdd(o)); + } + return this.curve.jpoint(e, r, o); + }; + Wt.prototype._threeDbl = function () { + var e, r, o; + if (this.zOne) { + var f = this.x.redSqr(), + p = this.y.redSqr(), + m2 = p.redSqr(), + y2 = this.x.redAdd(p).redSqr().redISub(f).redISub(m2); + y2 = y2.redIAdd(y2); + var M = f.redAdd(f).redIAdd(f).redIAdd(this.curve.a), + x = M.redSqr().redISub(y2).redISub(y2); + e = x; + var S = m2.redIAdd(m2); + (S = S.redIAdd(S)), (S = S.redIAdd(S)), (r = M.redMul(y2.redISub(x)).redISub(S)), (o = this.y.redAdd(this.y)); + } else { + var E2 = this.z.redSqr(), + B = this.y.redSqr(), + q2 = this.x.redMul(B), + L2 = this.x.redSub(E2).redMul(this.x.redAdd(E2)); + L2 = L2.redAdd(L2).redIAdd(L2); + var ge = q2.redIAdd(q2); + ge = ge.redIAdd(ge); + var _e = ge.redAdd(ge); + (e = L2.redSqr().redISub(_e)), (o = this.y.redAdd(this.z).redSqr().redISub(B).redISub(E2)); + var N = B.redSqr(); + (N = N.redIAdd(N)), (N = N.redIAdd(N)), (N = N.redIAdd(N)), (r = L2.redMul(ge.redISub(e)).redISub(N)); + } + return this.curve.jpoint(e, r, o); + }; + Wt.prototype._dbl = function () { + var e = this.curve.a, + r = this.x, + o = this.y, + f = this.z, + p = f.redSqr().redSqr(), + m2 = r.redSqr(), + y2 = o.redSqr(), + M = m2.redAdd(m2).redIAdd(m2).redIAdd(e.redMul(p)), + x = r.redAdd(r); + x = x.redIAdd(x); + var S = x.redMul(y2), + E2 = M.redSqr().redISub(S.redAdd(S)), + B = S.redISub(E2), + q2 = y2.redSqr(); + (q2 = q2.redIAdd(q2)), (q2 = q2.redIAdd(q2)), (q2 = q2.redIAdd(q2)); + var L2 = M.redMul(B).redISub(q2), + ge = o.redAdd(o).redMul(f); + return this.curve.jpoint(E2, L2, ge); + }; + Wt.prototype.trpl = function () { + if (!this.curve.zeroA) return this.dbl().add(this); + var e = this.x.redSqr(), + r = this.y.redSqr(), + o = this.z.redSqr(), + f = r.redSqr(), + p = e.redAdd(e).redIAdd(e), + m2 = p.redSqr(), + y2 = this.x.redAdd(r).redSqr().redISub(e).redISub(f); + (y2 = y2.redIAdd(y2)), (y2 = y2.redAdd(y2).redIAdd(y2)), (y2 = y2.redISub(m2)); + var M = y2.redSqr(), + x = f.redIAdd(f); + (x = x.redIAdd(x)), (x = x.redIAdd(x)), (x = x.redIAdd(x)); + var S = p.redIAdd(y2).redSqr().redISub(m2).redISub(M).redISub(x), + E2 = r.redMul(S); + (E2 = E2.redIAdd(E2)), (E2 = E2.redIAdd(E2)); + var B = this.x.redMul(M).redISub(E2); + (B = B.redIAdd(B)), (B = B.redIAdd(B)); + var q2 = this.y.redMul(S.redMul(x.redISub(S)).redISub(y2.redMul(M))); + (q2 = q2.redIAdd(q2)), (q2 = q2.redIAdd(q2)), (q2 = q2.redIAdd(q2)); + var L2 = this.z.redAdd(y2).redSqr().redISub(o).redISub(M); + return this.curve.jpoint(B, q2, L2); + }; + Wt.prototype.mul = function (e, r) { + return (e = new lt(e, r)), this.curve._wnafMul(this, e); + }; + Wt.prototype.eq = function (e) { + if (e.type === 'affine') return this.eq(e.toJ()); + if (this === e) return true; + var r = this.z.redSqr(), + o = e.z.redSqr(); + if (this.x.redMul(o).redISub(e.x.redMul(r)).cmpn(0) !== 0) return false; + var f = r.redMul(this.z), + p = o.redMul(e.z); + return this.y.redMul(p).redISub(e.y.redMul(f)).cmpn(0) === 0; + }; + Wt.prototype.eqXToP = function (e) { + var r = this.z.redSqr(), + o = e.toRed(this.curve.red).redMul(r); + if (this.x.cmp(o) === 0) return true; + for (var f = e.clone(), p = this.curve.redN.redMul(r); ; ) { + if ((f.iadd(this.curve.n), f.cmp(this.curve.p) >= 0)) return false; + if ((o.redIAdd(p), this.x.cmp(o) === 0)) return true; + } + }; + Wt.prototype.inspect = function () { + return this.isInfinity() ? '' : ''; + }; + Wt.prototype.isInfinity = function () { + return this.z.cmpn(0) === 0; + }; + }); + y2 = T2((Ek, g2) => { + var qf = ri(), + m2 = Ie(), + Gs = Oa(), + MA = or(); + function If(t) { + Gs.call(this, 'mont', t), + (this.a = new qf(t.a, 16).toRed(this.red)), + (this.b = new qf(t.b, 16).toRed(this.red)), + (this.i4 = new qf(4).toRed(this.red).redInvm()), + (this.two = new qf(2).toRed(this.red)), + (this.a24 = this.i4.redMul(this.a.redAdd(this.two))); + } + m2(If, Gs); + g2.exports = If; + If.prototype.validate = function (e) { + var r = e.normalize().x, + o = r.redSqr(), + f = o.redMul(r).redAdd(o.redMul(this.a)).redAdd(r), + p = f.redSqrt(); + return p.redSqr().cmp(f) === 0; + }; + function Ot(t, e, r) { + Gs.BasePoint.call(this, t, 'projective'), + e === null && r === null + ? ((this.x = this.curve.one), (this.z = this.curve.zero)) + : ((this.x = new qf(e, 16)), (this.z = new qf(r, 16)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.z.red || (this.z = this.z.toRed(this.curve.red))); + } + m2(Ot, Gs.BasePoint); + If.prototype.decodePoint = function (e, r) { + return this.point(MA.toArray(e, r), 1); + }; + If.prototype.point = function (e, r) { + return new Ot(this, e, r); + }; + If.prototype.pointFromJSON = function (e) { + return Ot.fromJSON(this, e); + }; + Ot.prototype.precompute = function () {}; + Ot.prototype._encode = function () { + return this.getX().toArray('be', this.curve.p.byteLength()); + }; + Ot.fromJSON = function (e, r) { + return new Ot(e, r[0], r[1] || e.one); + }; + Ot.prototype.inspect = function () { + return this.isInfinity() ? '' : ''; + }; + Ot.prototype.isInfinity = function () { + return this.z.cmpn(0) === 0; + }; + Ot.prototype.dbl = function () { + var e = this.x.redAdd(this.z), + r = e.redSqr(), + o = this.x.redSub(this.z), + f = o.redSqr(), + p = r.redSub(f), + m3 = r.redMul(f), + y3 = p.redMul(f.redAdd(this.curve.a24.redMul(p))); + return this.curve.point(m3, y3); + }; + Ot.prototype.add = function () { + throw new Error('Not supported on Montgomery curve'); + }; + Ot.prototype.diffAdd = function (e, r) { + var o = this.x.redAdd(this.z), + f = this.x.redSub(this.z), + p = e.x.redAdd(e.z), + m3 = e.x.redSub(e.z), + y3 = m3.redMul(o), + M = p.redMul(f), + x = r.z.redMul(y3.redAdd(M).redSqr()), + S = r.x.redMul(y3.redISub(M).redSqr()); + return this.curve.point(x, S); + }; + Ot.prototype.mul = function (e) { + for (var r = e.clone(), o = this, f = this.curve.point(null, null), p = this, m3 = []; r.cmpn(0) !== 0; r.iushrn(1)) m3.push(r.andln(1)); + for (var y3 = m3.length - 1; y3 >= 0; y3--) m3[y3] === 0 ? ((o = o.diffAdd(f, p)), (f = f.dbl())) : ((f = o.diffAdd(f, p)), (o = o.dbl())); + return f; + }; + Ot.prototype.mulAdd = function () { + throw new Error('Not supported on Montgomery curve'); + }; + Ot.prototype.jumlAdd = function () { + throw new Error('Not supported on Montgomery curve'); + }; + Ot.prototype.eq = function (e) { + return this.getX().cmp(e.getX()) === 0; + }; + Ot.prototype.normalize = function () { + return (this.x = this.x.redMul(this.z.redInvm())), (this.z = this.curve.one), this; + }; + Ot.prototype.getX = function () { + return this.normalize(), this.x.fromRed(); + }; + }); + _2 = T2((Ak, M2) => { + var _A = or(), + Ai = ri(), + w2 = Ie(), + Ys = Oa(), + xA = _A.assert; + function ii(t) { + (this.twisted = (t.a | 0) !== 1), + (this.mOneA = this.twisted && (t.a | 0) === -1), + (this.extended = this.mOneA), + Ys.call(this, 'edwards', t), + (this.a = new Ai(t.a, 16).umod(this.red.m)), + (this.a = this.a.toRed(this.red)), + (this.c = new Ai(t.c, 16).toRed(this.red)), + (this.c2 = this.c.redSqr()), + (this.d = new Ai(t.d, 16).toRed(this.red)), + (this.dd = this.d.redAdd(this.d)), + xA(!this.twisted || this.c.fromRed().cmpn(1) === 0), + (this.oneC = (t.c | 0) === 1); + } + w2(ii, Ys); + M2.exports = ii; + ii.prototype._mulA = function (e) { + return this.mOneA ? e.redNeg() : this.a.redMul(e); + }; + ii.prototype._mulC = function (e) { + return this.oneC ? e : this.c.redMul(e); + }; + ii.prototype.jpoint = function (e, r, o, f) { + return this.point(e, r, o, f); + }; + ii.prototype.pointFromX = function (e, r) { + (e = new Ai(e, 16)), e.red || (e = e.toRed(this.red)); + var o = e.redSqr(), + f = this.c2.redSub(this.a.redMul(o)), + p = this.one.redSub(this.c2.redMul(this.d).redMul(o)), + m2 = f.redMul(p.redInvm()), + y3 = m2.redSqrt(); + if (y3.redSqr().redSub(m2).cmp(this.zero) !== 0) throw new Error('invalid point'); + var M = y3.fromRed().isOdd(); + return ((r && !M) || (!r && M)) && (y3 = y3.redNeg()), this.point(e, y3); + }; + ii.prototype.pointFromY = function (e, r) { + (e = new Ai(e, 16)), e.red || (e = e.toRed(this.red)); + var o = e.redSqr(), + f = o.redSub(this.c2), + p = o.redMul(this.d).redMul(this.c2).redSub(this.a), + m2 = f.redMul(p.redInvm()); + if (m2.cmp(this.zero) === 0) { + if (r) throw new Error('invalid point'); + return this.point(this.zero, e); + } + var y3 = m2.redSqrt(); + if (y3.redSqr().redSub(m2).cmp(this.zero) !== 0) throw new Error('invalid point'); + return y3.fromRed().isOdd() !== r && (y3 = y3.redNeg()), this.point(y3, e); + }; + ii.prototype.validate = function (e) { + if (e.isInfinity()) return true; + e.normalize(); + var r = e.x.redSqr(), + o = e.y.redSqr(), + f = r.redMul(this.a).redAdd(o), + p = this.c2.redMul(this.one.redAdd(this.d.redMul(r).redMul(o))); + return f.cmp(p) === 0; + }; + function at(t, e, r, o, f) { + Ys.BasePoint.call(this, t, 'projective'), + e === null && r === null && o === null + ? ((this.x = this.curve.zero), (this.y = this.curve.one), (this.z = this.curve.one), (this.t = this.curve.zero), (this.zOne = true)) + : ((this.x = new Ai(e, 16)), + (this.y = new Ai(r, 16)), + (this.z = o ? new Ai(o, 16) : this.curve.one), + (this.t = f && new Ai(f, 16)), + this.x.red || (this.x = this.x.toRed(this.curve.red)), + this.y.red || (this.y = this.y.toRed(this.curve.red)), + this.z.red || (this.z = this.z.toRed(this.curve.red)), + this.t && !this.t.red && (this.t = this.t.toRed(this.curve.red)), + (this.zOne = this.z === this.curve.one), + this.curve.extended && !this.t && ((this.t = this.x.redMul(this.y)), this.zOne || (this.t = this.t.redMul(this.z.redInvm())))); + } + w2(at, Ys.BasePoint); + ii.prototype.pointFromJSON = function (e) { + return at.fromJSON(this, e); + }; + ii.prototype.point = function (e, r, o, f) { + return new at(this, e, r, o, f); + }; + at.fromJSON = function (e, r) { + return new at(e, r[0], r[1], r[2]); + }; + at.prototype.inspect = function () { + return this.isInfinity() ? '' : ''; + }; + at.prototype.isInfinity = function () { + return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || (this.zOne && this.y.cmp(this.curve.c) === 0)); + }; + at.prototype._extDbl = function () { + var e = this.x.redSqr(), + r = this.y.redSqr(), + o = this.z.redSqr(); + o = o.redIAdd(o); + var f = this.curve._mulA(e), + p = this.x.redAdd(this.y).redSqr().redISub(e).redISub(r), + m2 = f.redAdd(r), + y3 = m2.redSub(o), + M = f.redSub(r), + x = p.redMul(y3), + S = m2.redMul(M), + E2 = p.redMul(M), + B = y3.redMul(m2); + return this.curve.point(x, S, B, E2); + }; + at.prototype._projDbl = function () { + var e = this.x.redAdd(this.y).redSqr(), + r = this.x.redSqr(), + o = this.y.redSqr(), + f, + p, + m2, + y3, + M, + x; + if (this.curve.twisted) { + y3 = this.curve._mulA(r); + var S = y3.redAdd(o); + this.zOne + ? ((f = e.redSub(r).redSub(o).redMul(S.redSub(this.curve.two))), (p = S.redMul(y3.redSub(o))), (m2 = S.redSqr().redSub(S).redSub(S))) + : ((M = this.z.redSqr()), (x = S.redSub(M).redISub(M)), (f = e.redSub(r).redISub(o).redMul(x)), (p = S.redMul(y3.redSub(o))), (m2 = S.redMul(x))); + } else (y3 = r.redAdd(o)), (M = this.curve._mulC(this.z).redSqr()), (x = y3.redSub(M).redSub(M)), (f = this.curve._mulC(e.redISub(y3)).redMul(x)), (p = this.curve._mulC(y3).redMul(r.redISub(o))), (m2 = y3.redMul(x)); + return this.curve.point(f, p, m2); + }; + at.prototype.dbl = function () { + return this.isInfinity() ? this : this.curve.extended ? this._extDbl() : this._projDbl(); + }; + at.prototype._extAdd = function (e) { + var r = this.y.redSub(this.x).redMul(e.y.redSub(e.x)), + o = this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)), + f = this.t.redMul(this.curve.dd).redMul(e.t), + p = this.z.redMul(e.z.redAdd(e.z)), + m2 = o.redSub(r), + y3 = p.redSub(f), + M = p.redAdd(f), + x = o.redAdd(r), + S = m2.redMul(y3), + E2 = M.redMul(x), + B = m2.redMul(x), + q2 = y3.redMul(M); + return this.curve.point(S, E2, q2, B); + }; + at.prototype._projAdd = function (e) { + var r = this.z.redMul(e.z), + o = r.redSqr(), + f = this.x.redMul(e.x), + p = this.y.redMul(e.y), + m2 = this.curve.d.redMul(f).redMul(p), + y3 = o.redSub(m2), + M = o.redAdd(m2), + x = this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(f).redISub(p), + S = r.redMul(y3).redMul(x), + E2, + B; + return this.curve.twisted ? ((E2 = r.redMul(M).redMul(p.redSub(this.curve._mulA(f)))), (B = y3.redMul(M))) : ((E2 = r.redMul(M).redMul(p.redSub(f))), (B = this.curve._mulC(y3).redMul(M))), this.curve.point(S, E2, B); + }; + at.prototype.add = function (e) { + return this.isInfinity() ? e : e.isInfinity() ? this : this.curve.extended ? this._extAdd(e) : this._projAdd(e); + }; + at.prototype.mul = function (e) { + return this._hasDoubles(e) ? this.curve._fixedNafMul(this, e) : this.curve._wnafMul(this, e); + }; + at.prototype.mulAdd = function (e, r, o) { + return this.curve._wnafMulAdd(1, [this, r], [e, o], 2, false); + }; + at.prototype.jmulAdd = function (e, r, o) { + return this.curve._wnafMulAdd(1, [this, r], [e, o], 2, true); + }; + at.prototype.normalize = function () { + if (this.zOne) return this; + var e = this.z.redInvm(); + return (this.x = this.x.redMul(e)), (this.y = this.y.redMul(e)), this.t && (this.t = this.t.redMul(e)), (this.z = this.curve.one), (this.zOne = true), this; + }; + at.prototype.neg = function () { + return this.curve.point(this.x.redNeg(), this.y, this.z, this.t && this.t.redNeg()); + }; + at.prototype.getX = function () { + return this.normalize(), this.x.fromRed(); + }; + at.prototype.getY = function () { + return this.normalize(), this.y.fromRed(); + }; + at.prototype.eq = function (e) { + return this === e || (this.getX().cmp(e.getX()) === 0 && this.getY().cmp(e.getY()) === 0); + }; + at.prototype.eqXToP = function (e) { + var r = e.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(r) === 0) return true; + for (var o = e.clone(), f = this.curve.redN.redMul(this.z); ; ) { + if ((o.iadd(this.curve.n), o.cmp(this.curve.p) >= 0)) return false; + if ((r.redIAdd(f), this.x.cmp(r) === 0)) return true; + } + }; + at.prototype.toP = at.prototype.normalize; + at.prototype.mixedAdd = at.prototype.add; + }); + Pl = T2(x2 => { + var Xs = x2; + Xs.base = Oa(); + Xs.short = b2(); + Xs.mont = y2(); + Xs.edwards = _2(); + }); + Cr = T2(it => { + var SA = ar(), + EA = Ie(); + it.inherits = EA; + function AA(t, e) { + return (t.charCodeAt(e) & 64512) !== 55296 || e < 0 || e + 1 >= t.length ? false : (t.charCodeAt(e + 1) & 64512) === 56320; + } + function RA(t, e) { + if (Array.isArray(t)) return t.slice(); + if (!t) return []; + var r = []; + if (typeof t == 'string') + if (e) { + if (e === 'hex') for (t = t.replace(/[^a-z0-9]+/gi, ''), t.length % 2 !== 0 && (t = '0' + t), f = 0; f < t.length; f += 2) r.push(parseInt(t[f] + t[f + 1], 16)); + } else + for (var o = 0, f = 0; f < t.length; f++) { + var p = t.charCodeAt(f); + p < 128 + ? (r[o++] = p) + : p < 2048 + ? ((r[o++] = (p >> 6) | 192), (r[o++] = (p & 63) | 128)) + : AA(t, f) + ? ((p = 65536 + ((p & 1023) << 10) + (t.charCodeAt(++f) & 1023)), (r[o++] = (p >> 18) | 240), (r[o++] = ((p >> 12) & 63) | 128), (r[o++] = ((p >> 6) & 63) | 128), (r[o++] = (p & 63) | 128)) + : ((r[o++] = (p >> 12) | 224), (r[o++] = ((p >> 6) & 63) | 128), (r[o++] = (p & 63) | 128)); + } + else for (f = 0; f < t.length; f++) r[f] = t[f] | 0; + return r; + } + it.toArray = RA; + function BA(t) { + for (var e = '', r = 0; r < t.length; r++) e += E2(t[r].toString(16)); + return e; + } + it.toHex = BA; + function S2(t) { + var e = (t >>> 24) | ((t >>> 8) & 65280) | ((t << 8) & 16711680) | ((t & 255) << 24); + return e >>> 0; + } + it.htonl = S2; + function qA(t, e) { + for (var r = '', o = 0; o < t.length; o++) { + var f = t[o]; + e === 'little' && (f = S2(f)), (r += A2(f.toString(16))); + } + return r; + } + it.toHex32 = qA; + function E2(t) { + return t.length === 1 ? '0' + t : t; + } + it.zero2 = E2; + function A2(t) { + return t.length === 7 ? '0' + t : t.length === 6 ? '00' + t : t.length === 5 ? '000' + t : t.length === 4 ? '0000' + t : t.length === 3 ? '00000' + t : t.length === 2 ? '000000' + t : t.length === 1 ? '0000000' + t : t; + } + it.zero8 = A2; + function IA(t, e, r, o) { + var f = r - e; + SA(f % 4 === 0); + for (var p = new Array(f / 4), m2 = 0, y3 = e; m2 < p.length; m2++, y3 += 4) { + var M; + o === 'big' ? (M = (t[y3] << 24) | (t[y3 + 1] << 16) | (t[y3 + 2] << 8) | t[y3 + 3]) : (M = (t[y3 + 3] << 24) | (t[y3 + 2] << 16) | (t[y3 + 1] << 8) | t[y3]), (p[m2] = M >>> 0); + } + return p; + } + it.join32 = IA; + function TA(t, e) { + for (var r = new Array(t.length * 4), o = 0, f = 0; o < t.length; o++, f += 4) { + var p = t[o]; + e === 'big' ? ((r[f] = p >>> 24), (r[f + 1] = (p >>> 16) & 255), (r[f + 2] = (p >>> 8) & 255), (r[f + 3] = p & 255)) : ((r[f + 3] = p >>> 24), (r[f + 2] = (p >>> 16) & 255), (r[f + 1] = (p >>> 8) & 255), (r[f] = p & 255)); + } + return r; + } + it.split32 = TA; + function kA(t, e) { + return (t >>> e) | (t << (32 - e)); + } + it.rotr32 = kA; + function LA(t, e) { + return (t << e) | (t >>> (32 - e)); + } + it.rotl32 = LA; + function NA(t, e) { + return (t + e) >>> 0; + } + it.sum32 = NA; + function DA(t, e, r) { + return (t + e + r) >>> 0; + } + it.sum32_3 = DA; + function PA(t, e, r, o) { + return (t + e + r + o) >>> 0; + } + it.sum32_4 = PA; + function CA(t, e, r, o, f) { + return (t + e + r + o + f) >>> 0; + } + it.sum32_5 = CA; + function OA(t, e, r, o) { + var f = t[e], + p = t[e + 1], + m2 = (o + p) >>> 0, + y3 = (m2 < o ? 1 : 0) + r + f; + (t[e] = y3 >>> 0), (t[e + 1] = m2); + } + it.sum64 = OA; + function FA(t, e, r, o) { + var f = (e + o) >>> 0, + p = (f < e ? 1 : 0) + t + r; + return p >>> 0; + } + it.sum64_hi = FA; + function UA(t, e, r, o) { + var f = e + o; + return f >>> 0; + } + it.sum64_lo = UA; + function zA(t, e, r, o, f, p, m2, y3) { + var M = 0, + x = e; + (x = (x + o) >>> 0), (M += x < e ? 1 : 0), (x = (x + p) >>> 0), (M += x < p ? 1 : 0), (x = (x + y3) >>> 0), (M += x < y3 ? 1 : 0); + var S = t + r + f + m2 + M; + return S >>> 0; + } + it.sum64_4_hi = zA; + function HA(t, e, r, o, f, p, m2, y3) { + var M = e + o + p + y3; + return M >>> 0; + } + it.sum64_4_lo = HA; + function WA(t, e, r, o, f, p, m2, y3, M, x) { + var S = 0, + E3 = e; + (E3 = (E3 + o) >>> 0), (S += E3 < e ? 1 : 0), (E3 = (E3 + p) >>> 0), (S += E3 < p ? 1 : 0), (E3 = (E3 + y3) >>> 0), (S += E3 < y3 ? 1 : 0), (E3 = (E3 + x) >>> 0), (S += E3 < x ? 1 : 0); + var B = t + r + f + m2 + M + S; + return B >>> 0; + } + it.sum64_5_hi = WA; + function KA(t, e, r, o, f, p, m2, y3, M, x) { + var S = e + o + p + y3 + x; + return S >>> 0; + } + it.sum64_5_lo = KA; + function jA(t, e, r) { + var o = (e << (32 - r)) | (t >>> r); + return o >>> 0; + } + it.rotr64_hi = jA; + function ZA(t, e, r) { + var o = (t << (32 - r)) | (e >>> r); + return o >>> 0; + } + it.rotr64_lo = ZA; + function VA(t, e, r) { + return t >>> r; + } + it.shr64_hi = VA; + function $A(t, e, r) { + var o = (t << (32 - r)) | (e >>> r); + return o >>> 0; + } + it.shr64_lo = $A; + }); + Tf = T2(B2 => { + var R2 = Cr(), + GA = ar(); + function Js() { + (this.pending = null), + (this.pendingTotal = 0), + (this.blockSize = this.constructor.blockSize), + (this.outSize = this.constructor.outSize), + (this.hmacStrength = this.constructor.hmacStrength), + (this.padLength = this.constructor.padLength / 8), + (this.endian = 'big'), + (this._delta8 = this.blockSize / 8), + (this._delta32 = this.blockSize / 32); + } + B2.BlockHash = Js; + Js.prototype.update = function (e, r) { + if (((e = R2.toArray(e, r)), this.pending ? (this.pending = this.pending.concat(e)) : (this.pending = e), (this.pendingTotal += e.length), this.pending.length >= this._delta8)) { + e = this.pending; + var o = e.length % this._delta8; + (this.pending = e.slice(e.length - o, e.length)), this.pending.length === 0 && (this.pending = null), (e = R2.join32(e, 0, e.length - o, this.endian)); + for (var f = 0; f < e.length; f += this._delta32) this._update(e, f, f + this._delta32); + } + return this; + }; + Js.prototype.digest = function (e) { + return this.update(this._pad()), GA(this.pending === null), this._digest(e); + }; + Js.prototype._pad = function () { + var e = this.pendingTotal, + r = this._delta8, + o = r - ((e + this.padLength) % r), + f = new Array(o + this.padLength); + f[0] = 128; + for (var p = 1; p < o; p++) f[p] = 0; + if (((e <<= 3), this.endian === 'big')) { + for (var m2 = 8; m2 < this.padLength; m2++) f[p++] = 0; + (f[p++] = 0), (f[p++] = 0), (f[p++] = 0), (f[p++] = 0), (f[p++] = (e >>> 24) & 255), (f[p++] = (e >>> 16) & 255), (f[p++] = (e >>> 8) & 255), (f[p++] = e & 255); + } else for (f[p++] = e & 255, f[p++] = (e >>> 8) & 255, f[p++] = (e >>> 16) & 255, f[p++] = (e >>> 24) & 255, f[p++] = 0, f[p++] = 0, f[p++] = 0, f[p++] = 0, m2 = 8; m2 < this.padLength; m2++) f[p++] = 0; + return f; + }; + }); + Cl = T2(Ri => { + var YA = Cr(), + ni = YA.rotr32; + function XA(t, e, r, o) { + if (t === 0) return q2(e, r, o); + if (t === 1 || t === 3) return T22(e, r, o); + if (t === 2) return I2(e, r, o); + } + Ri.ft_1 = XA; + function q2(t, e, r) { + return (t & e) ^ (~t & r); + } + Ri.ch32 = q2; + function I2(t, e, r) { + return (t & e) ^ (t & r) ^ (e & r); + } + Ri.maj32 = I2; + function T22(t, e, r) { + return t ^ e ^ r; + } + Ri.p32 = T22; + function JA(t) { + return ni(t, 2) ^ ni(t, 13) ^ ni(t, 22); + } + Ri.s0_256 = JA; + function QA(t) { + return ni(t, 6) ^ ni(t, 11) ^ ni(t, 25); + } + Ri.s1_256 = QA; + function eR(t) { + return ni(t, 7) ^ ni(t, 18) ^ (t >>> 3); + } + Ri.g0_256 = eR; + function tR(t) { + return ni(t, 17) ^ ni(t, 19) ^ (t >>> 10); + } + Ri.g1_256 = tR; + }); + N2 = T2((Tk, L2) => { + var kf = Cr(), + rR = Tf(), + iR = Cl(), + Ol = kf.rotl32, + Fa = kf.sum32, + nR = kf.sum32_5, + fR = iR.ft_1, + k2 = rR.BlockHash, + aR = [1518500249, 1859775393, 2400959708, 3395469782]; + function fi() { + if (!(this instanceof fi)) return new fi(); + k2.call(this), (this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]), (this.W = new Array(80)); + } + kf.inherits(fi, k2); + L2.exports = fi; + fi.blockSize = 512; + fi.outSize = 160; + fi.hmacStrength = 80; + fi.padLength = 64; + fi.prototype._update = function (e, r) { + for (var o = this.W, f = 0; f < 16; f++) o[f] = e[r + f]; + for (; f < o.length; f++) o[f] = Ol(o[f - 3] ^ o[f - 8] ^ o[f - 14] ^ o[f - 16], 1); + var p = this.h[0], + m2 = this.h[1], + y3 = this.h[2], + M = this.h[3], + x = this.h[4]; + for (f = 0; f < o.length; f++) { + var S = ~~(f / 20), + E2 = nR(Ol(p, 5), fR(S, m2, y3, M), x, o[f], aR[S]); + (x = M), (M = y3), (y3 = Ol(m2, 30)), (m2 = p), (p = E2); + } + (this.h[0] = Fa(this.h[0], p)), (this.h[1] = Fa(this.h[1], m2)), (this.h[2] = Fa(this.h[2], y3)), (this.h[3] = Fa(this.h[3], M)), (this.h[4] = Fa(this.h[4], x)); + }; + fi.prototype._digest = function (e) { + return e === 'hex' ? kf.toHex32(this.h, 'big') : kf.split32(this.h, 'big'); + }; + }); + Fl = T2((kk, P2) => { + var Lf = Cr(), + oR = Tf(), + Nf = Cl(), + sR = ar(), + Or = Lf.sum32, + hR = Lf.sum32_4, + uR = Lf.sum32_5, + lR = Nf.ch32, + dR = Nf.maj32, + cR = Nf.s0_256, + pR = Nf.s1_256, + vR = Nf.g0_256, + bR = Nf.g1_256, + D2 = oR.BlockHash, + mR = [ + 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, + 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, + 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, + 2428436474, 2756734187, 3204031479, 3329325298 + ]; + function ai() { + if (!(this instanceof ai)) return new ai(); + D2.call(this), (this.h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]), (this.k = mR), (this.W = new Array(64)); + } + Lf.inherits(ai, D2); + P2.exports = ai; + ai.blockSize = 512; + ai.outSize = 256; + ai.hmacStrength = 192; + ai.padLength = 64; + ai.prototype._update = function (e, r) { + for (var o = this.W, f = 0; f < 16; f++) o[f] = e[r + f]; + for (; f < o.length; f++) o[f] = hR(bR(o[f - 2]), o[f - 7], vR(o[f - 15]), o[f - 16]); + var p = this.h[0], + m2 = this.h[1], + y3 = this.h[2], + M = this.h[3], + x = this.h[4], + S = this.h[5], + E2 = this.h[6], + B = this.h[7]; + for (sR(this.k.length === o.length), f = 0; f < o.length; f++) { + var q2 = uR(B, pR(x), lR(x, S, E2), this.k[f], o[f]), + L2 = Or(cR(p), dR(p, m2, y3)); + (B = E2), (E2 = S), (S = x), (x = Or(M, q2)), (M = y3), (y3 = m2), (m2 = p), (p = Or(q2, L2)); + } + (this.h[0] = Or(this.h[0], p)), + (this.h[1] = Or(this.h[1], m2)), + (this.h[2] = Or(this.h[2], y3)), + (this.h[3] = Or(this.h[3], M)), + (this.h[4] = Or(this.h[4], x)), + (this.h[5] = Or(this.h[5], S)), + (this.h[6] = Or(this.h[6], E2)), + (this.h[7] = Or(this.h[7], B)); + }; + ai.prototype._digest = function (e) { + return e === 'hex' ? Lf.toHex32(this.h, 'big') : Lf.split32(this.h, 'big'); + }; + }); + F2 = T2((Lk, O2) => { + var Ul = Cr(), + C2 = Fl(); + function Bi() { + if (!(this instanceof Bi)) return new Bi(); + C2.call(this), (this.h = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]); + } + Ul.inherits(Bi, C2); + O2.exports = Bi; + Bi.blockSize = 512; + Bi.outSize = 224; + Bi.hmacStrength = 192; + Bi.padLength = 64; + Bi.prototype._digest = function (e) { + return e === 'hex' ? Ul.toHex32(this.h.slice(0, 7), 'big') : Ul.split32(this.h.slice(0, 7), 'big'); + }; + }); + Wl = T2((Nk, W2) => { + var ir = Cr(), + gR = Tf(), + yR = ar(), + oi = ir.rotr64_hi, + si = ir.rotr64_lo, + U2 = ir.shr64_hi, + z2 = ir.shr64_lo, + Ji = ir.sum64, + zl = ir.sum64_hi, + Hl = ir.sum64_lo, + wR = ir.sum64_4_hi, + MR = ir.sum64_4_lo, + _R = ir.sum64_5_hi, + xR = ir.sum64_5_lo, + H2 = gR.BlockHash, + SR = [ + 1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, + 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, + 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, + 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, + 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, + 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, + 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, + 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, + 1607167915, 987167468, 1816402316, 1246189591 + ]; + function Fr() { + if (!(this instanceof Fr)) return new Fr(); + H2.call(this), + (this.h = [1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209]), + (this.k = SR), + (this.W = new Array(160)); + } + ir.inherits(Fr, H2); + W2.exports = Fr; + Fr.blockSize = 1024; + Fr.outSize = 512; + Fr.hmacStrength = 192; + Fr.padLength = 128; + Fr.prototype._prepareBlock = function (e, r) { + for (var o = this.W, f = 0; f < 32; f++) o[f] = e[r + f]; + for (; f < o.length; f += 2) { + var p = DR(o[f - 4], o[f - 3]), + m2 = PR(o[f - 4], o[f - 3]), + y3 = o[f - 14], + M = o[f - 13], + x = LR(o[f - 30], o[f - 29]), + S = NR(o[f - 30], o[f - 29]), + E2 = o[f - 32], + B = o[f - 31]; + (o[f] = wR(p, m2, y3, M, x, S, E2, B)), (o[f + 1] = MR(p, m2, y3, M, x, S, E2, B)); + } + }; + Fr.prototype._update = function (e, r) { + this._prepareBlock(e, r); + var o = this.W, + f = this.h[0], + p = this.h[1], + m2 = this.h[2], + y3 = this.h[3], + M = this.h[4], + x = this.h[5], + S = this.h[6], + E2 = this.h[7], + B = this.h[8], + q2 = this.h[9], + L2 = this.h[10], + ge = this.h[11], + _e = this.h[12], + N = this.h[13], + we = this.h[14], + ye = this.h[15]; + yR(this.k.length === o.length); + for (var xe = 0; xe < o.length; xe += 2) { + var Re = we, + Ee = ye, + Ae = TR(B, q2), + P = kR(B, q2), + Se = ER(B, q2, L2, ge, _e, N), + v = AR(B, q2, L2, ge, _e, N), + i = this.k[xe], + a = this.k[xe + 1], + h2 = o[xe], + s = o[xe + 1], + u = _R(Re, Ee, Ae, P, Se, v, i, a, h2, s), + c = xR(Re, Ee, Ae, P, Se, v, i, a, h2, s); + (Re = qR(f, p)), (Ee = IR(f, p)), (Ae = RR(f, p, m2, y3, M, x)), (P = BR(f, p, m2, y3, M, x)); + var b3 = zl(Re, Ee, Ae, P), + l = Hl(Re, Ee, Ae, P); + (we = _e), (ye = N), (_e = L2), (N = ge), (L2 = B), (ge = q2), (B = zl(S, E2, u, c)), (q2 = Hl(E2, E2, u, c)), (S = M), (E2 = x), (M = m2), (x = y3), (m2 = f), (y3 = p), (f = zl(u, c, b3, l)), (p = Hl(u, c, b3, l)); + } + Ji(this.h, 0, f, p), Ji(this.h, 2, m2, y3), Ji(this.h, 4, M, x), Ji(this.h, 6, S, E2), Ji(this.h, 8, B, q2), Ji(this.h, 10, L2, ge), Ji(this.h, 12, _e, N), Ji(this.h, 14, we, ye); + }; + Fr.prototype._digest = function (e) { + return e === 'hex' ? ir.toHex32(this.h, 'big') : ir.split32(this.h, 'big'); + }; + function ER(t, e, r, o, f) { + var p = (t & r) ^ (~t & f); + return p < 0 && (p += 4294967296), p; + } + function AR(t, e, r, o, f, p) { + var m2 = (e & o) ^ (~e & p); + return m2 < 0 && (m2 += 4294967296), m2; + } + function RR(t, e, r, o, f) { + var p = (t & r) ^ (t & f) ^ (r & f); + return p < 0 && (p += 4294967296), p; + } + function BR(t, e, r, o, f, p) { + var m2 = (e & o) ^ (e & p) ^ (o & p); + return m2 < 0 && (m2 += 4294967296), m2; + } + function qR(t, e) { + var r = oi(t, e, 28), + o = oi(e, t, 2), + f = oi(e, t, 7), + p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function IR(t, e) { + var r = si(t, e, 28), + o = si(e, t, 2), + f = si(e, t, 7), + p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function TR(t, e) { + var r = oi(t, e, 14), + o = oi(t, e, 18), + f = oi(e, t, 9), + p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function kR(t, e) { + var r = si(t, e, 14), + o = si(t, e, 18), + f = si(e, t, 9), + p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function LR(t, e) { + var r = oi(t, e, 1), + o = oi(t, e, 8), + f = U2(t, e, 7), + p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function NR(t, e) { + var r = si(t, e, 1), + o = si(t, e, 8), + f = z2(t, e, 7), + p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function DR(t, e) { + var r = oi(t, e, 19), + o = oi(e, t, 29), + f = U2(t, e, 6), + p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function PR(t, e) { + var r = si(t, e, 19), + o = si(e, t, 29), + f = z2(t, e, 6), + p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + }); + Z2 = T2((Dk, j2) => { + var Kl = Cr(), + K2 = Wl(); + function qi() { + if (!(this instanceof qi)) return new qi(); + K2.call(this), (this.h = [3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428]); + } + Kl.inherits(qi, K2); + j2.exports = qi; + qi.blockSize = 1024; + qi.outSize = 384; + qi.hmacStrength = 192; + qi.padLength = 128; + qi.prototype._digest = function (e) { + return e === 'hex' ? Kl.toHex32(this.h.slice(0, 12), 'big') : Kl.split32(this.h.slice(0, 12), 'big'); + }; + }); + V2 = T2(Df => { + Df.sha1 = N2(); + Df.sha224 = F2(); + Df.sha256 = Fl(); + Df.sha384 = Z2(); + Df.sha512 = Wl(); + }); + Q2 = T2(J2 => { + var On = Cr(), + CR = Tf(), + Qs = On.rotl32, + $2 = On.sum32, + Ua = On.sum32_3, + G2 = On.sum32_4, + X2 = CR.BlockHash; + function hi() { + if (!(this instanceof hi)) return new hi(); + X2.call(this), (this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]), (this.endian = 'little'); + } + On.inherits(hi, X2); + J2.ripemd160 = hi; + hi.blockSize = 512; + hi.outSize = 160; + hi.hmacStrength = 192; + hi.padLength = 64; + hi.prototype._update = function (e, r) { + for (var o = this.h[0], f = this.h[1], p = this.h[2], m2 = this.h[3], y3 = this.h[4], M = o, x = f, S = p, E2 = m2, B = y3, q2 = 0; q2 < 80; q2++) { + var L2 = $2(Qs(G2(o, Y2(q2, f, p, m2), e[UR[q2] + r], OR(q2)), HR[q2]), y3); + (o = y3), (y3 = m2), (m2 = Qs(p, 10)), (p = f), (f = L2), (L2 = $2(Qs(G2(M, Y2(79 - q2, x, S, E2), e[zR[q2] + r], FR(q2)), WR[q2]), B)), (M = B), (B = E2), (E2 = Qs(S, 10)), (S = x), (x = L2); + } + (L2 = Ua(this.h[1], p, E2)), (this.h[1] = Ua(this.h[2], m2, B)), (this.h[2] = Ua(this.h[3], y3, M)), (this.h[3] = Ua(this.h[4], o, x)), (this.h[4] = Ua(this.h[0], f, S)), (this.h[0] = L2); + }; + hi.prototype._digest = function (e) { + return e === 'hex' ? On.toHex32(this.h, 'little') : On.split32(this.h, 'little'); + }; + function Y2(t, e, r, o) { + return t <= 15 ? e ^ r ^ o : t <= 31 ? (e & r) | (~e & o) : t <= 47 ? (e | ~r) ^ o : t <= 63 ? (e & o) | (r & ~o) : e ^ (r | ~o); + } + function OR(t) { + return t <= 15 ? 0 : t <= 31 ? 1518500249 : t <= 47 ? 1859775393 : t <= 63 ? 2400959708 : 2840853838; + } + function FR(t) { + return t <= 15 ? 1352829926 : t <= 31 ? 1548603684 : t <= 47 ? 1836072691 : t <= 63 ? 2053994217 : 0; + } + var UR = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, + 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 + ], + zR = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, + 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 + ], + HR = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, + 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 + ], + WR = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, + 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 + ]; + }); + ty = T2((Ok, ey) => { + var KR = Cr(), + jR = ar(); + function Pf(t, e, r) { + if (!(this instanceof Pf)) return new Pf(t, e, r); + (this.Hash = t), (this.blockSize = t.blockSize / 8), (this.outSize = t.outSize / 8), (this.inner = null), (this.outer = null), this._init(KR.toArray(e, r)); + } + ey.exports = Pf; + Pf.prototype._init = function (e) { + e.length > this.blockSize && (e = new this.Hash().update(e).digest()), jR(e.length <= this.blockSize); + for (var r = e.length; r < this.blockSize; r++) e.push(0); + for (r = 0; r < e.length; r++) e[r] ^= 54; + for (this.inner = new this.Hash().update(e), r = 0; r < e.length; r++) e[r] ^= 106; + this.outer = new this.Hash().update(e); + }; + Pf.prototype.update = function (e, r) { + return this.inner.update(e, r), this; + }; + Pf.prototype.digest = function (e) { + return this.outer.update(this.inner.digest()), this.outer.digest(e); + }; + }); + e0 = T2(ry => { + var Kt = ry; + Kt.utils = Cr(); + Kt.common = Tf(); + Kt.sha = V2(); + Kt.ripemd = Q2(); + Kt.hmac = ty(); + Kt.sha1 = Kt.sha.sha1; + Kt.sha256 = Kt.sha.sha256; + Kt.sha224 = Kt.sha.sha224; + Kt.sha384 = Kt.sha.sha384; + Kt.sha512 = Kt.sha.sha512; + Kt.ripemd160 = Kt.ripemd.ripemd160; + }); + ny = T2((Uk, iy) => { + iy.exports = { + doubles: { + step: 4, + points: [ + ['e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'], + ['8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'], + ['175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'], + ['363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'], + ['8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'], + ['723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'], + ['eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'], + ['100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'], + ['e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'], + ['feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'], + ['da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'], + ['53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'], + ['8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'], + ['385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'], + ['6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'], + ['3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'], + ['85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'], + ['948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'], + ['6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'], + ['e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'], + ['e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'], + ['213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'], + ['4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'], + ['fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'], + ['76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'], + ['c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'], + ['d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'], + ['b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'], + ['e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'], + ['a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'], + ['90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'], + ['8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'], + ['e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'], + ['8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'], + ['e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'], + ['b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'], + ['d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'], + ['324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'], + ['4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'], + ['9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'], + ['6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'], + ['a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'], + ['7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'], + ['928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'], + ['85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'], + ['ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'], + ['827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'], + ['eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'], + ['e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'], + ['1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'], + ['146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'], + ['fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'], + ['da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'], + ['a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'], + ['174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'], + ['959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'], + ['d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'], + ['64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'], + ['8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'], + ['13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'], + ['bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'], + ['8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'], + ['8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'], + ['dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'], + ['f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'] + ] + }, + naf: { + wnd: 7, + points: [ + ['f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'], + ['2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'], + ['5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'], + ['acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'], + ['774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'], + ['f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'], + ['d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'], + ['defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'], + ['2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'], + ['352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'], + ['2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'], + ['9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'], + ['daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'], + ['c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'], + ['6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'], + ['1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'], + ['605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'], + ['62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'], + ['80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'], + ['7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'], + ['d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'], + ['49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'], + ['77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'], + ['f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'], + ['463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'], + ['f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'], + ['caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'], + ['2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'], + ['7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'], + ['754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'], + ['e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'], + ['186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'], + ['df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'], + ['5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'], + ['290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'], + ['af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'], + ['766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'], + ['59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'], + ['f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'], + ['7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'], + ['948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'], + ['7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'], + ['3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'], + ['d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'], + ['1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'], + ['733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'], + ['15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'], + ['a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'], + ['e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'], + ['311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'], + ['34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'], + ['f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'], + ['d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'], + ['32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'], + ['7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'], + ['ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'], + ['16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'], + ['eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'], + ['78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'], + ['494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'], + ['a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'], + ['c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'], + ['841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'], + ['5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'], + ['36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'], + ['336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'], + ['8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'], + ['1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'], + ['85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'], + ['29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'], + ['a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'], + ['4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'], + ['d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'], + ['ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'], + ['af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'], + ['e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'], + ['591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'], + ['11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'], + ['3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'], + ['cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'], + ['c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'], + ['c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'], + ['a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'], + ['347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'], + ['da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'], + ['c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'], + ['4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'], + ['3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'], + ['cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'], + ['b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'], + ['d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'], + ['48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'], + ['dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'], + ['6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'], + ['e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'], + ['eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'], + ['13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'], + ['ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'], + ['b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'], + ['ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'], + ['8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'], + ['52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'], + ['e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'], + ['7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'], + ['5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'], + ['32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'], + ['e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'], + ['8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'], + ['4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'], + ['3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'], + ['674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'], + ['d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'], + ['30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'], + ['be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'], + ['93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'], + ['b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'], + ['d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'], + ['d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'], + ['463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'], + ['7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'], + ['74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'], + ['30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'], + ['9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'], + ['176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'], + ['75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'], + ['809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'], + ['1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'] + ] + } + }; + }); + t0 = T2(oy => { + var Zl = oy, + Qi = e0(), + jl = Pl(), + ZR = or(), + fy = ZR.assert; + function ay(t) { + t.type === 'short' ? (this.curve = new jl.short(t)) : t.type === 'edwards' ? (this.curve = new jl.edwards(t)) : (this.curve = new jl.mont(t)), + (this.g = this.curve.g), + (this.n = this.curve.n), + (this.hash = t.hash), + fy(this.g.validate(), 'Invalid curve'), + fy(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); + } + Zl.PresetCurve = ay; + function en(t, e) { + Object.defineProperty(Zl, t, { + configurable: true, + enumerable: true, + get: function () { + var r = new ay(e); + return Object.defineProperty(Zl, t, {configurable: true, enumerable: true, value: r}), r; + } + }); + } + en('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: Qi.sha256, + gRed: false, + g: ['188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'] + }); + en('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: Qi.sha256, + gRed: false, + g: ['b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'] + }); + en('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: Qi.sha256, + gRed: false, + g: ['6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'] + }); + en('p384', { + type: 'short', + prime: null, + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff', + a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc', + b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', + n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', + hash: Qi.sha384, + gRed: false, + g: ['aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7', '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'] + }); + en('p521', { + type: 'short', + prime: null, + p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff', + a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc', + b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', + n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', + hash: Qi.sha512, + gRed: false, + g: [ + '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', + '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650' + ] + }); + en('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '1', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: Qi.sha256, + gRed: false, + g: ['9'] + }); + en('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: Qi.sha256, + gRed: false, + g: ['216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', '6666666666666666666666666666666666666666666666666666666666666658'] + }); + var Vl; + try { + Vl = ny(); + } catch { + Vl = undefined; + } + en('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: Qi.sha256, + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + {a: '3086d221a7d46bcde86c90e49284eb15', b: '-e4437ed6010e88286f547fa90abfe4c3'}, + {a: '114ca50f7a8e2f3f657c1108d9d44cfd8', b: '3086d221a7d46bcde86c90e49284eb15'} + ], + gRed: false, + g: ['79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', Vl] + }); + }); + uy = T2((Hk, hy) => { + var VR = e0(), + Fn = Nl(), + sy = ar(); + function tn(t) { + if (!(this instanceof tn)) return new tn(t); + (this.hash = t.hash), + (this.predResist = !!t.predResist), + (this.outLen = this.hash.outSize), + (this.minEntropy = t.minEntropy || this.hash.hmacStrength), + (this._reseed = null), + (this.reseedInterval = null), + (this.K = null), + (this.V = null); + var e = Fn.toArray(t.entropy, t.entropyEnc || 'hex'), + r = Fn.toArray(t.nonce, t.nonceEnc || 'hex'), + o = Fn.toArray(t.pers, t.persEnc || 'hex'); + sy(e.length >= this.minEntropy / 8, 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'), this._init(e, r, o); + } + hy.exports = tn; + tn.prototype._init = function (e, r, o) { + var f = e.concat(r).concat(o); + (this.K = new Array(this.outLen / 8)), (this.V = new Array(this.outLen / 8)); + for (var p = 0; p < this.V.length; p++) (this.K[p] = 0), (this.V[p] = 1); + this._update(f), (this._reseed = 1), (this.reseedInterval = 281474976710656); + }; + tn.prototype._hmac = function () { + return new VR.hmac(this.hash, this.K); + }; + tn.prototype._update = function (e) { + var r = this._hmac().update(this.V).update([0]); + e && (r = r.update(e)), (this.K = r.digest()), (this.V = this._hmac().update(this.V).digest()), e && ((this.K = this._hmac().update(this.V).update([1]).update(e).digest()), (this.V = this._hmac().update(this.V).digest())); + }; + tn.prototype.reseed = function (e, r, o, f) { + typeof r != 'string' && ((f = o), (o = r), (r = null)), + (e = Fn.toArray(e, r)), + (o = Fn.toArray(o, f)), + sy(e.length >= this.minEntropy / 8, 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'), + this._update(e.concat(o || [])), + (this._reseed = 1); + }; + tn.prototype.generate = function (e, r, o, f) { + if (this._reseed > this.reseedInterval) throw new Error('Reseed is required'); + typeof r != 'string' && ((f = o), (o = r), (r = null)), o && ((o = Fn.toArray(o, f || 'hex')), this._update(o)); + for (var p = []; p.length < e; ) (this.V = this._hmac().update(this.V).digest()), (p = p.concat(this.V)); + var m2 = p.slice(0, e); + return this._update(o), this._reseed++, Fn.encode(m2, r); + }; + }); + dy = T2((Wk, ly) => { + var $R = ri(), + GR = or(), + $l = GR.assert; + function Gt(t, e) { + (this.ec = t), (this.priv = null), (this.pub = null), e.priv && this._importPrivate(e.priv, e.privEnc), e.pub && this._importPublic(e.pub, e.pubEnc); + } + ly.exports = Gt; + Gt.fromPublic = function (e, r, o) { + return r instanceof Gt ? r : new Gt(e, {pub: r, pubEnc: o}); + }; + Gt.fromPrivate = function (e, r, o) { + return r instanceof Gt ? r : new Gt(e, {priv: r, privEnc: o}); + }; + Gt.prototype.validate = function () { + var e = this.getPublic(); + return e.isInfinity() + ? {result: false, reason: 'Invalid public key'} + : e.validate() + ? e.mul(this.ec.curve.n).isInfinity() + ? {result: true, reason: null} + : {result: false, reason: 'Public key * N != O'} + : {result: false, reason: 'Public key is not a point'}; + }; + Gt.prototype.getPublic = function (e, r) { + return typeof e == 'string' && ((r = e), (e = null)), this.pub || (this.pub = this.ec.g.mul(this.priv)), r ? this.pub.encode(r, e) : this.pub; + }; + Gt.prototype.getPrivate = function (e) { + return e === 'hex' ? this.priv.toString(16, 2) : this.priv; + }; + Gt.prototype._importPrivate = function (e, r) { + (this.priv = new $R(e, r || 16)), (this.priv = this.priv.umod(this.ec.curve.n)); + }; + Gt.prototype._importPublic = function (e, r) { + if (e.x || e.y) { + this.ec.curve.type === 'mont' ? $l(e.x, 'Need x coordinate') : (this.ec.curve.type === 'short' || this.ec.curve.type === 'edwards') && $l(e.x && e.y, 'Need both x and y coordinate'), (this.pub = this.ec.curve.point(e.x, e.y)); + return; + } + this.pub = this.ec.curve.decodePoint(e, r); + }; + Gt.prototype.derive = function (e) { + return e.validate() || $l(e.validate(), 'public point not validated'), e.mul(this.priv).getX(); + }; + Gt.prototype.sign = function (e, r, o) { + return this.ec.sign(e, this, r, o); + }; + Gt.prototype.verify = function (e, r) { + return this.ec.verify(e, r, this); + }; + Gt.prototype.inspect = function () { + return ''; + }; + }); + vy = T2((Kk, py) => { + var r0 = ri(), + Xl = or(), + YR = Xl.assert; + function i0(t, e) { + if (t instanceof i0) return t; + this._importDER(t, e) || (YR(t.r && t.s, 'Signature without r or s'), (this.r = new r0(t.r, 16)), (this.s = new r0(t.s, 16)), t.recoveryParam === undefined ? (this.recoveryParam = null) : (this.recoveryParam = t.recoveryParam)); + } + py.exports = i0; + function XR() { + this.place = 0; + } + function Gl(t, e) { + var r = t[e.place++]; + if (!(r & 128)) return r; + var o = r & 15; + if (o === 0 || o > 4) return false; + for (var f = 0, p = 0, m2 = e.place; p < o; p++, m2++) (f <<= 8), (f |= t[m2]), (f >>>= 0); + return f <= 127 ? false : ((e.place = m2), f); + } + function cy(t) { + for (var e = 0, r = t.length - 1; !t[e] && !(t[e + 1] & 128) && e < r; ) e++; + return e === 0 ? t : t.slice(e); + } + i0.prototype._importDER = function (e, r) { + e = Xl.toArray(e, r); + var o = new XR(); + if (e[o.place++] !== 48) return false; + var f = Gl(e, o); + if (f === false || f + o.place !== e.length || e[o.place++] !== 2) return false; + var p = Gl(e, o); + if (p === false) return false; + var m2 = e.slice(o.place, p + o.place); + if (((o.place += p), e[o.place++] !== 2)) return false; + var y3 = Gl(e, o); + if (y3 === false || e.length !== y3 + o.place) return false; + var M = e.slice(o.place, y3 + o.place); + if (m2[0] === 0) + if (m2[1] & 128) m2 = m2.slice(1); + else return false; + if (M[0] === 0) + if (M[1] & 128) M = M.slice(1); + else return false; + return (this.r = new r0(m2)), (this.s = new r0(M)), (this.recoveryParam = null), true; + }; + function Yl(t, e) { + if (e < 128) { + t.push(e); + return; + } + var r = 1 + ((Math.log(e) / Math.LN2) >>> 3); + for (t.push(r | 128); --r; ) t.push((e >>> (r << 3)) & 255); + t.push(e); + } + i0.prototype.toDER = function (e) { + var r = this.r.toArray(), + o = this.s.toArray(); + for (r[0] & 128 && (r = [0].concat(r)), o[0] & 128 && (o = [0].concat(o)), r = cy(r), o = cy(o); !o[0] && !(o[1] & 128); ) o = o.slice(1); + var f = [2]; + Yl(f, r.length), (f = f.concat(r)), f.push(2), Yl(f, o.length); + var p = f.concat(o), + m2 = [48]; + return Yl(m2, p.length), (m2 = m2.concat(p)), Xl.encode(m2, e); + }; + }); + yy = T2((jk, gy) => { + var Un = ri(), + by = uy(), + JR = or(), + Jl = t0(), + QR = As(), + my = JR.assert, + Ql = dy(), + n0 = vy(); + function Sr(t) { + if (!(this instanceof Sr)) return new Sr(t); + typeof t == 'string' && (my(Object.prototype.hasOwnProperty.call(Jl, t), 'Unknown curve ' + t), (t = Jl[t])), + t instanceof Jl.PresetCurve && (t = {curve: t}), + (this.curve = t.curve.curve), + (this.n = this.curve.n), + (this.nh = this.n.ushrn(1)), + (this.g = this.curve.g), + (this.g = t.curve.g), + this.g.precompute(t.curve.n.bitLength() + 1), + (this.hash = t.hash || t.curve.hash); + } + gy.exports = Sr; + Sr.prototype.keyPair = function (e) { + return new Ql(this, e); + }; + Sr.prototype.keyFromPrivate = function (e, r) { + return Ql.fromPrivate(this, e, r); + }; + Sr.prototype.keyFromPublic = function (e, r) { + return Ql.fromPublic(this, e, r); + }; + Sr.prototype.genKeyPair = function (e) { + e || (e = {}); + for ( + var r = new by({hash: this.hash, pers: e.pers, persEnc: e.persEnc || 'utf8', entropy: e.entropy || QR(this.hash.hmacStrength), entropyEnc: (e.entropy && e.entropyEnc) || 'utf8', nonce: this.n.toArray()}), + o = this.n.byteLength(), + f = this.n.sub(new Un(2)); + ; + + ) { + var p = new Un(r.generate(o)); + if (!(p.cmp(f) > 0)) return p.iaddn(1), this.keyFromPrivate(p); + } + }; + Sr.prototype._truncateToN = function (e, r) { + var o = e.byteLength() * 8 - this.n.bitLength(); + return o > 0 && (e = e.ushrn(o)), !r && e.cmp(this.n) >= 0 ? e.sub(this.n) : e; + }; + Sr.prototype.sign = function (e, r, o, f) { + typeof o == 'object' && ((f = o), (o = null)), f || (f = {}), (r = this.keyFromPrivate(r, o)), (e = this._truncateToN(new Un(e, 16))); + for (var p = this.n.byteLength(), m2 = r.getPrivate().toArray('be', p), y3 = e.toArray('be', p), M = new by({hash: this.hash, entropy: m2, nonce: y3, pers: f.pers, persEnc: f.persEnc || 'utf8'}), x = this.n.sub(new Un(1)), S = 0; ; S++) { + var E2 = f.k ? f.k(S) : new Un(M.generate(this.n.byteLength())); + if (((E2 = this._truncateToN(E2, true)), !(E2.cmpn(1) <= 0 || E2.cmp(x) >= 0))) { + var B = this.g.mul(E2); + if (!B.isInfinity()) { + var q2 = B.getX(), + L2 = q2.umod(this.n); + if (L2.cmpn(0) !== 0) { + var ge = E2.invm(this.n).mul(L2.mul(r.getPrivate()).iadd(e)); + if (((ge = ge.umod(this.n)), ge.cmpn(0) !== 0)) { + var _e = (B.getY().isOdd() ? 1 : 0) | (q2.cmp(L2) !== 0 ? 2 : 0); + return f.canonical && ge.cmp(this.nh) > 0 && ((ge = this.n.sub(ge)), (_e ^= 1)), new n0({r: L2, s: ge, recoveryParam: _e}); + } + } + } + } + } + }; + Sr.prototype.verify = function (e, r, o, f) { + (e = this._truncateToN(new Un(e, 16))), (o = this.keyFromPublic(o, f)), (r = new n0(r, 'hex')); + var {r: p, s: m2} = r; + if (p.cmpn(1) < 0 || p.cmp(this.n) >= 0 || m2.cmpn(1) < 0 || m2.cmp(this.n) >= 0) return false; + var y3 = m2.invm(this.n), + M = y3.mul(e).umod(this.n), + x = y3.mul(p).umod(this.n), + S; + return this.curve._maxwellTrick ? ((S = this.g.jmulAdd(M, o.getPublic(), x)), S.isInfinity() ? false : S.eqXToP(p)) : ((S = this.g.mulAdd(M, o.getPublic(), x)), S.isInfinity() ? false : S.getX().umod(this.n).cmp(p) === 0); + }; + Sr.prototype.recoverPubKey = function (t, e, r, o) { + my((3 & r) === r, 'The recovery param is more than two bits'), (e = new n0(e, o)); + var f = this.n, + p = new Un(t), + m2 = e.r, + y3 = e.s, + M = r & 1, + x = r >> 1; + if (m2.cmp(this.curve.p.umod(this.curve.n)) >= 0 && x) throw new Error('Unable to find sencond key candinate'); + x ? (m2 = this.curve.pointFromX(m2.add(this.curve.n), M)) : (m2 = this.curve.pointFromX(m2, M)); + var S = e.r.invm(f), + E2 = f.sub(p).mul(S).umod(f), + B = y3.mul(S).umod(f); + return this.g.mulAdd(E2, m2, B); + }; + Sr.prototype.getKeyRecoveryParam = function (t, e, r, o) { + if (((e = new n0(e, o)), e.recoveryParam !== null)) return e.recoveryParam; + for (var f = 0; f < 4; f++) { + var p; + try { + p = this.recoverPubKey(t, e, f); + } catch { + continue; + } + if (p.eq(r)) return f; + } + throw new Error('Unable to find valid recovery factor'); + }; + }); + xy = T2((Zk, _y) => { + var za = or(), + My = za.assert, + wy = za.parseBytes, + Cf = za.cachedProperty; + function Ft(t, e) { + (this.eddsa = t), (this._secret = wy(e.secret)), t.isPoint(e.pub) ? (this._pub = e.pub) : (this._pubBytes = wy(e.pub)); + } + Ft.fromPublic = function (e, r) { + return r instanceof Ft ? r : new Ft(e, {pub: r}); + }; + Ft.fromSecret = function (e, r) { + return r instanceof Ft ? r : new Ft(e, {secret: r}); + }; + Ft.prototype.secret = function () { + return this._secret; + }; + Cf(Ft, 'pubBytes', function () { + return this.eddsa.encodePoint(this.pub()); + }); + Cf(Ft, 'pub', function () { + return this._pubBytes ? this.eddsa.decodePoint(this._pubBytes) : this.eddsa.g.mul(this.priv()); + }); + Cf(Ft, 'privBytes', function () { + var e = this.eddsa, + r = this.hash(), + o = e.encodingLength - 1, + f = r.slice(0, e.encodingLength); + return (f[0] &= 248), (f[o] &= 127), (f[o] |= 64), f; + }); + Cf(Ft, 'priv', function () { + return this.eddsa.decodeInt(this.privBytes()); + }); + Cf(Ft, 'hash', function () { + return this.eddsa.hash().update(this.secret()).digest(); + }); + Cf(Ft, 'messagePrefix', function () { + return this.hash().slice(this.eddsa.encodingLength); + }); + Ft.prototype.sign = function (e) { + return My(this._secret, 'KeyPair can only verify'), this.eddsa.sign(e, this); + }; + Ft.prototype.verify = function (e, r) { + return this.eddsa.verify(e, r, this); + }; + Ft.prototype.getSecret = function (e) { + return My(this._secret, 'KeyPair is public only'), za.encode(this.secret(), e); + }; + Ft.prototype.getPublic = function (e) { + return za.encode(this.pubBytes(), e); + }; + _y.exports = Ft; + }); + Ey = T2((Vk, Sy) => { + var eB = ri(), + f0 = or(), + tB = f0.assert, + a0 = f0.cachedProperty, + rB = f0.parseBytes; + function zn(t, e) { + (this.eddsa = t), + typeof e != 'object' && (e = rB(e)), + Array.isArray(e) && (e = {R: e.slice(0, t.encodingLength), S: e.slice(t.encodingLength)}), + tB(e.R && e.S, 'Signature without R or S'), + t.isPoint(e.R) && (this._R = e.R), + e.S instanceof eB && (this._S = e.S), + (this._Rencoded = Array.isArray(e.R) ? e.R : e.Rencoded), + (this._Sencoded = Array.isArray(e.S) ? e.S : e.Sencoded); + } + a0(zn, 'S', function () { + return this.eddsa.decodeInt(this.Sencoded()); + }); + a0(zn, 'R', function () { + return this.eddsa.decodePoint(this.Rencoded()); + }); + a0(zn, 'Rencoded', function () { + return this.eddsa.encodePoint(this.R()); + }); + a0(zn, 'Sencoded', function () { + return this.eddsa.encodeInt(this.S()); + }); + zn.prototype.toBytes = function () { + return this.Rencoded().concat(this.Sencoded()); + }; + zn.prototype.toHex = function () { + return f0.encode(this.toBytes(), 'hex').toUpperCase(); + }; + Sy.exports = zn; + }); + Iy = T2(($k, qy) => { + var iB = e0(), + nB = t0(), + Of = or(), + fB = Of.assert, + Ry = Of.parseBytes, + By = xy(), + Ay = Ey(); + function nr(t) { + if ((fB(t === 'ed25519', 'only tested with ed25519 so far'), !(this instanceof nr))) return new nr(t); + (t = nB[t].curve), (this.curve = t), (this.g = t.g), this.g.precompute(t.n.bitLength() + 1), (this.pointClass = t.point().constructor), (this.encodingLength = Math.ceil(t.n.bitLength() / 8)), (this.hash = iB.sha512); + } + qy.exports = nr; + nr.prototype.sign = function (e, r) { + e = Ry(e); + var o = this.keyFromSecret(r), + f = this.hashInt(o.messagePrefix(), e), + p = this.g.mul(f), + m2 = this.encodePoint(p), + y3 = this.hashInt(m2, o.pubBytes(), e).mul(o.priv()), + M = f.add(y3).umod(this.curve.n); + return this.makeSignature({R: p, S: M, Rencoded: m2}); + }; + nr.prototype.verify = function (e, r, o) { + (e = Ry(e)), (r = this.makeSignature(r)); + var f = this.keyFromPublic(o), + p = this.hashInt(r.Rencoded(), f.pubBytes(), e), + m2 = this.g.mul(r.S()), + y3 = r.R().add(f.pub().mul(p)); + return y3.eq(m2); + }; + nr.prototype.hashInt = function () { + for (var e = this.hash(), r = 0; r < arguments.length; r++) e.update(arguments[r]); + return Of.intFromLE(e.digest()).umod(this.curve.n); + }; + nr.prototype.keyFromPublic = function (e) { + return By.fromPublic(this, e); + }; + nr.prototype.keyFromSecret = function (e) { + return By.fromSecret(this, e); + }; + nr.prototype.makeSignature = function (e) { + return e instanceof Ay ? e : new Ay(this, e); + }; + nr.prototype.encodePoint = function (e) { + var r = e.getY().toArray('le', this.encodingLength); + return (r[this.encodingLength - 1] |= e.getX().isOdd() ? 128 : 0), r; + }; + nr.prototype.decodePoint = function (e) { + e = Of.parseBytes(e); + var r = e.length - 1, + o = e.slice(0, r).concat(e[r] & -129), + f = (e[r] & 128) !== 0, + p = Of.intFromLE(o); + return this.curve.pointFromY(p, f); + }; + nr.prototype.encodeInt = function (e) { + return e.toArray('le', this.encodingLength); + }; + nr.prototype.decodeInt = function (e) { + return Of.intFromLE(e); + }; + nr.prototype.isPoint = function (e) { + return e instanceof this.pointClass; + }; + }); + o0 = T2(Ty => { + var Hn = Ty; + Hn.version = s2().version; + Hn.utils = or(); + Hn.rand = As(); + Hn.curve = Pl(); + Hn.curves = t0(); + Hn.ec = yy(); + Hn.eddsa = Iy(); + }); + td = T2((ky, ed) => { + (function (t, e) { + function r(v, i) { + if (!v) throw new Error(i || 'Assertion failed'); + } + function o(v, i) { + v.super_ = i; + var a = function () {}; + (a.prototype = i.prototype), (v.prototype = new a()), (v.prototype.constructor = v); + } + function f(v, i, a) { + if (f.isBN(v)) return v; + (this.negative = 0), (this.words = null), (this.length = 0), (this.red = null), v !== null && ((i === 'le' || i === 'be') && ((a = i), (i = 10)), this._init(v || 0, i || 10, a || 'be')); + } + typeof t == 'object' ? (t.exports = f) : (e.BN = f), (f.BN = f), (f.wordSize = 26); + var p; + try { + typeof window < 'u' && typeof window.Buffer < 'u' ? (p = window.Buffer) : (p = ji().Buffer); + } catch {} + (f.isBN = function (i) { + return i instanceof f ? true : i !== null && typeof i == 'object' && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }), + (f.max = function (i, a) { + return i.cmp(a) > 0 ? i : a; + }), + (f.min = function (i, a) { + return i.cmp(a) < 0 ? i : a; + }), + (f.prototype._init = function (i, a, h2) { + if (typeof i == 'number') return this._initNumber(i, a, h2); + if (typeof i == 'object') return this._initArray(i, a, h2); + a === 'hex' && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), (i = i.toString().replace(/\s+/g, '')); + var s = 0; + i[0] === '-' && (s++, (this.negative = 1)), s < i.length && (a === 16 ? this._parseHex(i, s, h2) : (this._parseBase(i, a, s), h2 === 'le' && this._initArray(this.toArray(), a, h2))); + }), + (f.prototype._initNumber = function (i, a, h2) { + i < 0 && ((this.negative = 1), (i = -i)), + i < 67108864 + ? ((this.words = [i & 67108863]), (this.length = 1)) + : i < 4503599627370496 + ? ((this.words = [i & 67108863, (i / 67108864) & 67108863]), (this.length = 2)) + : (r(i < 9007199254740992), (this.words = [i & 67108863, (i / 67108864) & 67108863, 1]), (this.length = 3)), + h2 === 'le' && this._initArray(this.toArray(), a, h2); + }), + (f.prototype._initArray = function (i, a, h2) { + if ((r(typeof i.length == 'number'), i.length <= 0)) return (this.words = [0]), (this.length = 1), this; + (this.length = Math.ceil(i.length / 3)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u, + c, + b3 = 0; + if (h2 === 'be') + for (s = i.length - 1, u = 0; s >= 0; s -= 3) + (c = i[s] | (i[s - 1] << 8) | (i[s - 2] << 16)), (this.words[u] |= (c << b3) & 67108863), (this.words[u + 1] = (c >>> (26 - b3)) & 67108863), (b3 += 24), b3 >= 26 && ((b3 -= 26), u++); + else if (h2 === 'le') + for (s = 0, u = 0; s < i.length; s += 3) (c = i[s] | (i[s + 1] << 8) | (i[s + 2] << 16)), (this.words[u] |= (c << b3) & 67108863), (this.words[u + 1] = (c >>> (26 - b3)) & 67108863), (b3 += 24), b3 >= 26 && ((b3 -= 26), u++); + return this.strip(); + }); + function m2(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : (a - 48) & 15; + } + function y3(v, i, a) { + var h2 = m2(v, a); + return a - 1 >= i && (h2 |= m2(v, a - 1) << 4), h2; + } + f.prototype._parseHex = function (i, a, h2) { + (this.length = Math.ceil((i.length - a) / 6)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u = 0, + c = 0, + b3; + if (h2 === 'be') for (s = i.length - 1; s >= a; s -= 2) (b3 = y3(i, a, s) << u), (this.words[c] |= b3 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b3 >>> 26)) : (u += 8); + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a; s < i.length; s += 2) (b3 = y3(i, a, s) << u), (this.words[c] |= b3 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b3 >>> 26)) : (u += 8); + } + this.strip(); + }; + function M(v, i, a, h2) { + for (var s = 0, u = Math.min(v.length, a), c = i; c < u; c++) { + var b3 = v.charCodeAt(c) - 48; + (s *= h2), b3 >= 49 ? (s += b3 - 49 + 10) : b3 >= 17 ? (s += b3 - 17 + 10) : (s += b3); + } + return s; + } + (f.prototype._parseBase = function (i, a, h2) { + (this.words = [0]), (this.length = 1); + for (var s = 0, u = 1; u <= 67108863; u *= a) s++; + s--, (u = (u / a) | 0); + for (var c = i.length - h2, b3 = c % s, l = Math.min(c, c - b3) + h2, n = 0, d = h2; d < l; d += s) (n = M(i, d, d + s, a)), this.imuln(u), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + if (b3 !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0; d < b3; d++) w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + } + this.strip(); + }), + (f.prototype.copy = function (i) { + i.words = new Array(this.length); + for (var a = 0; a < this.length; a++) i.words[a] = this.words[a]; + (i.length = this.length), (i.negative = this.negative), (i.red = this.red); + }), + (f.prototype.clone = function () { + var i = new f(null); + return this.copy(i), i; + }), + (f.prototype._expand = function (i) { + for (; this.length < i; ) this.words[this.length++] = 0; + return this; + }), + (f.prototype.strip = function () { + for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; + return this._normSign(); + }), + (f.prototype._normSign = function () { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }), + (f.prototype.inspect = function () { + return (this.red ? ''; + }); + var x = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ], + S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + E2 = [ + 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, + 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + (f.prototype.toString = function (i, a) { + (i = i || 10), (a = a | 0 || 1); + var h2; + if (i === 16 || i === 'hex') { + h2 = ''; + for (var s = 0, u = 0, c = 0; c < this.length; c++) { + var b3 = this.words[c], + l = (((b3 << s) | u) & 16777215).toString(16); + (u = (b3 >>> (24 - s)) & 16777215), u !== 0 || c !== this.length - 1 ? (h2 = x[6 - l.length] + l + h2) : (h2 = l + h2), (s += 2), s >= 26 && ((s -= 26), c--); + } + for (u !== 0 && (h2 = u.toString(16) + h2); h2.length % a !== 0; ) h2 = '0' + h2; + return this.negative !== 0 && (h2 = '-' + h2), h2; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], + d = E2[i]; + h2 = ''; + var w = this.clone(); + for (w.negative = 0; !w.isZero(); ) { + var g = w.modn(d).toString(i); + (w = w.idivn(d)), w.isZero() ? (h2 = g + h2) : (h2 = x[n - g.length] + g + h2); + } + for (this.isZero() && (h2 = '0' + h2); h2.length % a !== 0; ) h2 = '0' + h2; + return this.negative !== 0 && (h2 = '-' + h2), h2; + } + r(false, 'Base should be between 2 and 36'); + }), + (f.prototype.toNumber = function () { + var i = this.words[0]; + return ( + this.length === 2 ? (i += this.words[1] * 67108864) : this.length === 3 && this.words[2] === 1 ? (i += 4503599627370496 + this.words[1] * 67108864) : this.length > 2 && r(false, 'Number can only safely store up to 53 bits'), + this.negative !== 0 ? -i : i + ); + }), + (f.prototype.toJSON = function () { + return this.toString(16); + }), + (f.prototype.toBuffer = function (i, a) { + return r(typeof p < 'u'), this.toArrayLike(p, i, a); + }), + (f.prototype.toArray = function (i, a) { + return this.toArrayLike(Array, i, a); + }), + (f.prototype.toArrayLike = function (i, a, h2) { + var s = this.byteLength(), + u = h2 || Math.max(1, s); + r(s <= u, 'byte array longer than desired length'), r(u > 0, 'Requested array length <= 0'), this.strip(); + var c = a === 'le', + b3 = new i(u), + l, + n, + d = this.clone(); + if (c) { + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b3[n] = l); + for (; n < u; n++) b3[n] = 0; + } else { + for (n = 0; n < u - s; n++) b3[n] = 0; + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b3[u - n - 1] = l); + } + return b3; + }), + Math.clz32 + ? (f.prototype._countBits = function (i) { + return 32 - Math.clz32(i); + }) + : (f.prototype._countBits = function (i) { + var a = i, + h2 = 0; + return a >= 4096 && ((h2 += 13), (a >>>= 13)), a >= 64 && ((h2 += 7), (a >>>= 7)), a >= 8 && ((h2 += 4), (a >>>= 4)), a >= 2 && ((h2 += 2), (a >>>= 2)), h2 + a; + }), + (f.prototype._zeroBits = function (i) { + if (i === 0) return 26; + var a = i, + h2 = 0; + return (a & 8191) === 0 && ((h2 += 13), (a >>>= 13)), (a & 127) === 0 && ((h2 += 7), (a >>>= 7)), (a & 15) === 0 && ((h2 += 4), (a >>>= 4)), (a & 3) === 0 && ((h2 += 2), (a >>>= 2)), (a & 1) === 0 && h2++, h2; + }), + (f.prototype.bitLength = function () { + var i = this.words[this.length - 1], + a = this._countBits(i); + return (this.length - 1) * 26 + a; + }); + function B(v) { + for (var i = new Array(v.bitLength()), a = 0; a < i.length; a++) { + var h2 = (a / 26) | 0, + s = a % 26; + i[a] = (v.words[h2] & (1 << s)) >>> s; + } + return i; + } + (f.prototype.zeroBits = function () { + if (this.isZero()) return 0; + for (var i = 0, a = 0; a < this.length; a++) { + var h2 = this._zeroBits(this.words[a]); + if (((i += h2), h2 !== 26)) break; + } + return i; + }), + (f.prototype.byteLength = function () { + return Math.ceil(this.bitLength() / 8); + }), + (f.prototype.toTwos = function (i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }), + (f.prototype.fromTwos = function (i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }), + (f.prototype.isNeg = function () { + return this.negative !== 0; + }), + (f.prototype.neg = function () { + return this.clone().ineg(); + }), + (f.prototype.ineg = function () { + return this.isZero() || (this.negative ^= 1), this; + }), + (f.prototype.iuor = function (i) { + for (; this.length < i.length; ) this.words[this.length++] = 0; + for (var a = 0; a < i.length; a++) this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }), + (f.prototype.ior = function (i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }), + (f.prototype.or = function (i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }), + (f.prototype.uor = function (i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }), + (f.prototype.iuand = function (i) { + var a; + this.length > i.length ? (a = i) : (a = this); + for (var h2 = 0; h2 < a.length; h2++) this.words[h2] = this.words[h2] & i.words[h2]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.iand = function (i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }), + (f.prototype.and = function (i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }), + (f.prototype.uand = function (i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }), + (f.prototype.iuxor = function (i) { + var a, h2; + this.length > i.length ? ((a = this), (h2 = i)) : ((a = i), (h2 = this)); + for (var s = 0; s < h2.length; s++) this.words[s] = a.words[s] ^ h2.words[s]; + if (this !== a) for (; s < a.length; s++) this.words[s] = a.words[s]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.ixor = function (i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }), + (f.prototype.xor = function (i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }), + (f.prototype.uxor = function (i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }), + (f.prototype.inotn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = Math.ceil(i / 26) | 0, + h2 = i % 26; + this._expand(a), h2 > 0 && a--; + for (var s = 0; s < a; s++) this.words[s] = ~this.words[s] & 67108863; + return h2 > 0 && (this.words[s] = ~this.words[s] & (67108863 >> (26 - h2))), this.strip(); + }), + (f.prototype.notn = function (i) { + return this.clone().inotn(i); + }), + (f.prototype.setn = function (i, a) { + r(typeof i == 'number' && i >= 0); + var h2 = (i / 26) | 0, + s = i % 26; + return this._expand(h2 + 1), a ? (this.words[h2] = this.words[h2] | (1 << s)) : (this.words[h2] = this.words[h2] & ~(1 << s)), this.strip(); + }), + (f.prototype.iadd = function (i) { + var a; + if (this.negative !== 0 && i.negative === 0) return (this.negative = 0), (a = this.isub(i)), (this.negative ^= 1), this._normSign(); + if (this.negative === 0 && i.negative !== 0) return (i.negative = 0), (a = this.isub(i)), (i.negative = 1), a._normSign(); + var h2, s; + this.length > i.length ? ((h2 = this), (s = i)) : ((h2 = i), (s = this)); + for (var u = 0, c = 0; c < s.length; c++) (a = (h2.words[c] | 0) + (s.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + for (; u !== 0 && c < h2.length; c++) (a = (h2.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + if (((this.length = h2.length), u !== 0)) (this.words[this.length] = u), this.length++; + else if (h2 !== this) for (; c < h2.length; c++) this.words[c] = h2.words[c]; + return this; + }), + (f.prototype.add = function (i) { + var a; + return i.negative !== 0 && this.negative === 0 + ? ((i.negative = 0), (a = this.sub(i)), (i.negative ^= 1), a) + : i.negative === 0 && this.negative !== 0 + ? ((this.negative = 0), (a = i.sub(this)), (this.negative = 1), a) + : this.length > i.length + ? this.clone().iadd(i) + : i.clone().iadd(this); + }), + (f.prototype.isub = function (i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return (i.negative = 1), a._normSign(); + } else if (this.negative !== 0) return (this.negative = 0), this.iadd(i), (this.negative = 1), this._normSign(); + var h2 = this.cmp(i); + if (h2 === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; + var s, u; + h2 > 0 ? ((s = this), (u = i)) : ((s = i), (u = this)); + for (var c = 0, b3 = 0; b3 < u.length; b3++) (a = (s.words[b3] | 0) - (u.words[b3] | 0) + c), (c = a >> 26), (this.words[b3] = a & 67108863); + for (; c !== 0 && b3 < s.length; b3++) (a = (s.words[b3] | 0) + c), (c = a >> 26), (this.words[b3] = a & 67108863); + if (c === 0 && b3 < s.length && s !== this) for (; b3 < s.length; b3++) this.words[b3] = s.words[b3]; + return (this.length = Math.max(this.length, b3)), s !== this && (this.negative = 1), this.strip(); + }), + (f.prototype.sub = function (i) { + return this.clone().isub(i); + }); + function q2(v, i, a) { + a.negative = i.negative ^ v.negative; + var h2 = (v.length + i.length) | 0; + (a.length = h2), (h2 = (h2 - 1) | 0); + var s = v.words[0] | 0, + u = i.words[0] | 0, + c = s * u, + b3 = c & 67108863, + l = (c / 67108864) | 0; + a.words[0] = b3; + for (var n = 1; n < h2; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _3 = Math.max(0, n - v.length + 1); _3 <= g; _3++) { + var A2 = (n - _3) | 0; + (s = v.words[A2] | 0), (u = i.words[_3] | 0), (c = s * u + w), (d += (c / 67108864) | 0), (w = c & 67108863); + } + (a.words[n] = w | 0), (l = d | 0); + } + return l !== 0 ? (a.words[n] = l | 0) : a.length--, a.strip(); + } + var L2 = function (i, a, h2) { + var s = i.words, + u = a.words, + c = h2.words, + b3 = 0, + l, + n, + d, + w = s[0] | 0, + g = w & 8191, + _3 = w >>> 13, + A2 = s[1] | 0, + R2 = A2 & 8191, + I = A2 >>> 13, + Me = s[2] | 0, + k = Me & 8191, + D2 = Me >>> 13, + nt = s[3] | 0, + C2 = nt & 8191, + O = nt >>> 13, + vt = s[4] | 0, + F = vt & 8191, + U = vt >>> 13, + bt = s[5] | 0, + z2 = bt & 8191, + H = bt >>> 13, + mt = s[6] | 0, + W = mt & 8191, + K = mt >>> 13, + gt = s[7] | 0, + j = gt & 8191, + Z = gt >>> 13, + yt = s[8] | 0, + V = yt & 8191, + $2 = yt >>> 13, + wt = s[9] | 0, + G = wt & 8191, + Y = wt >>> 13, + Mt = u[0] | 0, + X = Mt & 8191, + J = Mt >>> 13, + _t = u[1] | 0, + Q = _t & 8191, + ee = _t >>> 13, + xt = u[2] | 0, + te = xt & 8191, + re = xt >>> 13, + St = u[3] | 0, + ie = St & 8191, + ne = St >>> 13, + Et = u[4] | 0, + fe = Et & 8191, + ae = Et >>> 13, + At = u[5] | 0, + oe = At & 8191, + se = At >>> 13, + Rt = u[6] | 0, + he = Rt & 8191, + ue = Rt >>> 13, + Bt = u[7] | 0, + le = Bt & 8191, + de = Bt >>> 13, + qt = u[8] | 0, + ce = qt & 8191, + pe = qt >>> 13, + It = u[9] | 0, + ve = It & 8191, + be = It >>> 13; + (h2.negative = i.negative ^ a.negative), (h2.length = 19), (l = Math.imul(g, X)), (n = Math.imul(g, J)), (n = (n + Math.imul(_3, X)) | 0), (d = Math.imul(_3, J)); + var ft = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (ft >>> 26)) | 0), + (ft &= 67108863), + (l = Math.imul(R2, X)), + (n = Math.imul(R2, J)), + (n = (n + Math.imul(I, X)) | 0), + (d = Math.imul(I, J)), + (l = (l + Math.imul(g, Q)) | 0), + (n = (n + Math.imul(g, ee)) | 0), + (n = (n + Math.imul(_3, Q)) | 0), + (d = (d + Math.imul(_3, ee)) | 0); + var Be = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Be >>> 26)) | 0), + (Be &= 67108863), + (l = Math.imul(k, X)), + (n = Math.imul(k, J)), + (n = (n + Math.imul(D2, X)) | 0), + (d = Math.imul(D2, J)), + (l = (l + Math.imul(R2, Q)) | 0), + (n = (n + Math.imul(R2, ee)) | 0), + (n = (n + Math.imul(I, Q)) | 0), + (d = (d + Math.imul(I, ee)) | 0), + (l = (l + Math.imul(g, te)) | 0), + (n = (n + Math.imul(g, re)) | 0), + (n = (n + Math.imul(_3, te)) | 0), + (d = (d + Math.imul(_3, re)) | 0); + var qe = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (qe >>> 26)) | 0), + (qe &= 67108863), + (l = Math.imul(C2, X)), + (n = Math.imul(C2, J)), + (n = (n + Math.imul(O, X)) | 0), + (d = Math.imul(O, J)), + (l = (l + Math.imul(k, Q)) | 0), + (n = (n + Math.imul(k, ee)) | 0), + (n = (n + Math.imul(D2, Q)) | 0), + (d = (d + Math.imul(D2, ee)) | 0), + (l = (l + Math.imul(R2, te)) | 0), + (n = (n + Math.imul(R2, re)) | 0), + (n = (n + Math.imul(I, te)) | 0), + (d = (d + Math.imul(I, re)) | 0), + (l = (l + Math.imul(g, ie)) | 0), + (n = (n + Math.imul(g, ne)) | 0), + (n = (n + Math.imul(_3, ie)) | 0), + (d = (d + Math.imul(_3, ne)) | 0); + var ze = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (ze >>> 26)) | 0), + (ze &= 67108863), + (l = Math.imul(F, X)), + (n = Math.imul(F, J)), + (n = (n + Math.imul(U, X)) | 0), + (d = Math.imul(U, J)), + (l = (l + Math.imul(C2, Q)) | 0), + (n = (n + Math.imul(C2, ee)) | 0), + (n = (n + Math.imul(O, Q)) | 0), + (d = (d + Math.imul(O, ee)) | 0), + (l = (l + Math.imul(k, te)) | 0), + (n = (n + Math.imul(k, re)) | 0), + (n = (n + Math.imul(D2, te)) | 0), + (d = (d + Math.imul(D2, re)) | 0), + (l = (l + Math.imul(R2, ie)) | 0), + (n = (n + Math.imul(R2, ne)) | 0), + (n = (n + Math.imul(I, ie)) | 0), + (d = (d + Math.imul(I, ne)) | 0), + (l = (l + Math.imul(g, fe)) | 0), + (n = (n + Math.imul(g, ae)) | 0), + (n = (n + Math.imul(_3, fe)) | 0), + (d = (d + Math.imul(_3, ae)) | 0); + var He = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (He >>> 26)) | 0), + (He &= 67108863), + (l = Math.imul(z2, X)), + (n = Math.imul(z2, J)), + (n = (n + Math.imul(H, X)) | 0), + (d = Math.imul(H, J)), + (l = (l + Math.imul(F, Q)) | 0), + (n = (n + Math.imul(F, ee)) | 0), + (n = (n + Math.imul(U, Q)) | 0), + (d = (d + Math.imul(U, ee)) | 0), + (l = (l + Math.imul(C2, te)) | 0), + (n = (n + Math.imul(C2, re)) | 0), + (n = (n + Math.imul(O, te)) | 0), + (d = (d + Math.imul(O, re)) | 0), + (l = (l + Math.imul(k, ie)) | 0), + (n = (n + Math.imul(k, ne)) | 0), + (n = (n + Math.imul(D2, ie)) | 0), + (d = (d + Math.imul(D2, ne)) | 0), + (l = (l + Math.imul(R2, fe)) | 0), + (n = (n + Math.imul(R2, ae)) | 0), + (n = (n + Math.imul(I, fe)) | 0), + (d = (d + Math.imul(I, ae)) | 0), + (l = (l + Math.imul(g, oe)) | 0), + (n = (n + Math.imul(g, se)) | 0), + (n = (n + Math.imul(_3, oe)) | 0), + (d = (d + Math.imul(_3, se)) | 0); + var We = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (We >>> 26)) | 0), + (We &= 67108863), + (l = Math.imul(W, X)), + (n = Math.imul(W, J)), + (n = (n + Math.imul(K, X)) | 0), + (d = Math.imul(K, J)), + (l = (l + Math.imul(z2, Q)) | 0), + (n = (n + Math.imul(z2, ee)) | 0), + (n = (n + Math.imul(H, Q)) | 0), + (d = (d + Math.imul(H, ee)) | 0), + (l = (l + Math.imul(F, te)) | 0), + (n = (n + Math.imul(F, re)) | 0), + (n = (n + Math.imul(U, te)) | 0), + (d = (d + Math.imul(U, re)) | 0), + (l = (l + Math.imul(C2, ie)) | 0), + (n = (n + Math.imul(C2, ne)) | 0), + (n = (n + Math.imul(O, ie)) | 0), + (d = (d + Math.imul(O, ne)) | 0), + (l = (l + Math.imul(k, fe)) | 0), + (n = (n + Math.imul(k, ae)) | 0), + (n = (n + Math.imul(D2, fe)) | 0), + (d = (d + Math.imul(D2, ae)) | 0), + (l = (l + Math.imul(R2, oe)) | 0), + (n = (n + Math.imul(R2, se)) | 0), + (n = (n + Math.imul(I, oe)) | 0), + (d = (d + Math.imul(I, se)) | 0), + (l = (l + Math.imul(g, he)) | 0), + (n = (n + Math.imul(g, ue)) | 0), + (n = (n + Math.imul(_3, he)) | 0), + (d = (d + Math.imul(_3, ue)) | 0); + var Ke = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ke >>> 26)) | 0), + (Ke &= 67108863), + (l = Math.imul(j, X)), + (n = Math.imul(j, J)), + (n = (n + Math.imul(Z, X)) | 0), + (d = Math.imul(Z, J)), + (l = (l + Math.imul(W, Q)) | 0), + (n = (n + Math.imul(W, ee)) | 0), + (n = (n + Math.imul(K, Q)) | 0), + (d = (d + Math.imul(K, ee)) | 0), + (l = (l + Math.imul(z2, te)) | 0), + (n = (n + Math.imul(z2, re)) | 0), + (n = (n + Math.imul(H, te)) | 0), + (d = (d + Math.imul(H, re)) | 0), + (l = (l + Math.imul(F, ie)) | 0), + (n = (n + Math.imul(F, ne)) | 0), + (n = (n + Math.imul(U, ie)) | 0), + (d = (d + Math.imul(U, ne)) | 0), + (l = (l + Math.imul(C2, fe)) | 0), + (n = (n + Math.imul(C2, ae)) | 0), + (n = (n + Math.imul(O, fe)) | 0), + (d = (d + Math.imul(O, ae)) | 0), + (l = (l + Math.imul(k, oe)) | 0), + (n = (n + Math.imul(k, se)) | 0), + (n = (n + Math.imul(D2, oe)) | 0), + (d = (d + Math.imul(D2, se)) | 0), + (l = (l + Math.imul(R2, he)) | 0), + (n = (n + Math.imul(R2, ue)) | 0), + (n = (n + Math.imul(I, he)) | 0), + (d = (d + Math.imul(I, ue)) | 0), + (l = (l + Math.imul(g, le)) | 0), + (n = (n + Math.imul(g, de)) | 0), + (n = (n + Math.imul(_3, le)) | 0), + (d = (d + Math.imul(_3, de)) | 0); + var je = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (je >>> 26)) | 0), + (je &= 67108863), + (l = Math.imul(V, X)), + (n = Math.imul(V, J)), + (n = (n + Math.imul($2, X)) | 0), + (d = Math.imul($2, J)), + (l = (l + Math.imul(j, Q)) | 0), + (n = (n + Math.imul(j, ee)) | 0), + (n = (n + Math.imul(Z, Q)) | 0), + (d = (d + Math.imul(Z, ee)) | 0), + (l = (l + Math.imul(W, te)) | 0), + (n = (n + Math.imul(W, re)) | 0), + (n = (n + Math.imul(K, te)) | 0), + (d = (d + Math.imul(K, re)) | 0), + (l = (l + Math.imul(z2, ie)) | 0), + (n = (n + Math.imul(z2, ne)) | 0), + (n = (n + Math.imul(H, ie)) | 0), + (d = (d + Math.imul(H, ne)) | 0), + (l = (l + Math.imul(F, fe)) | 0), + (n = (n + Math.imul(F, ae)) | 0), + (n = (n + Math.imul(U, fe)) | 0), + (d = (d + Math.imul(U, ae)) | 0), + (l = (l + Math.imul(C2, oe)) | 0), + (n = (n + Math.imul(C2, se)) | 0), + (n = (n + Math.imul(O, oe)) | 0), + (d = (d + Math.imul(O, se)) | 0), + (l = (l + Math.imul(k, he)) | 0), + (n = (n + Math.imul(k, ue)) | 0), + (n = (n + Math.imul(D2, he)) | 0), + (d = (d + Math.imul(D2, ue)) | 0), + (l = (l + Math.imul(R2, le)) | 0), + (n = (n + Math.imul(R2, de)) | 0), + (n = (n + Math.imul(I, le)) | 0), + (d = (d + Math.imul(I, de)) | 0), + (l = (l + Math.imul(g, ce)) | 0), + (n = (n + Math.imul(g, pe)) | 0), + (n = (n + Math.imul(_3, ce)) | 0), + (d = (d + Math.imul(_3, pe)) | 0); + var Ze = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ze >>> 26)) | 0), + (Ze &= 67108863), + (l = Math.imul(G, X)), + (n = Math.imul(G, J)), + (n = (n + Math.imul(Y, X)) | 0), + (d = Math.imul(Y, J)), + (l = (l + Math.imul(V, Q)) | 0), + (n = (n + Math.imul(V, ee)) | 0), + (n = (n + Math.imul($2, Q)) | 0), + (d = (d + Math.imul($2, ee)) | 0), + (l = (l + Math.imul(j, te)) | 0), + (n = (n + Math.imul(j, re)) | 0), + (n = (n + Math.imul(Z, te)) | 0), + (d = (d + Math.imul(Z, re)) | 0), + (l = (l + Math.imul(W, ie)) | 0), + (n = (n + Math.imul(W, ne)) | 0), + (n = (n + Math.imul(K, ie)) | 0), + (d = (d + Math.imul(K, ne)) | 0), + (l = (l + Math.imul(z2, fe)) | 0), + (n = (n + Math.imul(z2, ae)) | 0), + (n = (n + Math.imul(H, fe)) | 0), + (d = (d + Math.imul(H, ae)) | 0), + (l = (l + Math.imul(F, oe)) | 0), + (n = (n + Math.imul(F, se)) | 0), + (n = (n + Math.imul(U, oe)) | 0), + (d = (d + Math.imul(U, se)) | 0), + (l = (l + Math.imul(C2, he)) | 0), + (n = (n + Math.imul(C2, ue)) | 0), + (n = (n + Math.imul(O, he)) | 0), + (d = (d + Math.imul(O, ue)) | 0), + (l = (l + Math.imul(k, le)) | 0), + (n = (n + Math.imul(k, de)) | 0), + (n = (n + Math.imul(D2, le)) | 0), + (d = (d + Math.imul(D2, de)) | 0), + (l = (l + Math.imul(R2, ce)) | 0), + (n = (n + Math.imul(R2, pe)) | 0), + (n = (n + Math.imul(I, ce)) | 0), + (d = (d + Math.imul(I, pe)) | 0), + (l = (l + Math.imul(g, ve)) | 0), + (n = (n + Math.imul(g, be)) | 0), + (n = (n + Math.imul(_3, ve)) | 0), + (d = (d + Math.imul(_3, be)) | 0); + var Ve = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ve >>> 26)) | 0), + (Ve &= 67108863), + (l = Math.imul(G, Q)), + (n = Math.imul(G, ee)), + (n = (n + Math.imul(Y, Q)) | 0), + (d = Math.imul(Y, ee)), + (l = (l + Math.imul(V, te)) | 0), + (n = (n + Math.imul(V, re)) | 0), + (n = (n + Math.imul($2, te)) | 0), + (d = (d + Math.imul($2, re)) | 0), + (l = (l + Math.imul(j, ie)) | 0), + (n = (n + Math.imul(j, ne)) | 0), + (n = (n + Math.imul(Z, ie)) | 0), + (d = (d + Math.imul(Z, ne)) | 0), + (l = (l + Math.imul(W, fe)) | 0), + (n = (n + Math.imul(W, ae)) | 0), + (n = (n + Math.imul(K, fe)) | 0), + (d = (d + Math.imul(K, ae)) | 0), + (l = (l + Math.imul(z2, oe)) | 0), + (n = (n + Math.imul(z2, se)) | 0), + (n = (n + Math.imul(H, oe)) | 0), + (d = (d + Math.imul(H, se)) | 0), + (l = (l + Math.imul(F, he)) | 0), + (n = (n + Math.imul(F, ue)) | 0), + (n = (n + Math.imul(U, he)) | 0), + (d = (d + Math.imul(U, ue)) | 0), + (l = (l + Math.imul(C2, le)) | 0), + (n = (n + Math.imul(C2, de)) | 0), + (n = (n + Math.imul(O, le)) | 0), + (d = (d + Math.imul(O, de)) | 0), + (l = (l + Math.imul(k, ce)) | 0), + (n = (n + Math.imul(k, pe)) | 0), + (n = (n + Math.imul(D2, ce)) | 0), + (d = (d + Math.imul(D2, pe)) | 0), + (l = (l + Math.imul(R2, ve)) | 0), + (n = (n + Math.imul(R2, be)) | 0), + (n = (n + Math.imul(I, ve)) | 0), + (d = (d + Math.imul(I, be)) | 0); + var $e = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + ($e >>> 26)) | 0), + ($e &= 67108863), + (l = Math.imul(G, te)), + (n = Math.imul(G, re)), + (n = (n + Math.imul(Y, te)) | 0), + (d = Math.imul(Y, re)), + (l = (l + Math.imul(V, ie)) | 0), + (n = (n + Math.imul(V, ne)) | 0), + (n = (n + Math.imul($2, ie)) | 0), + (d = (d + Math.imul($2, ne)) | 0), + (l = (l + Math.imul(j, fe)) | 0), + (n = (n + Math.imul(j, ae)) | 0), + (n = (n + Math.imul(Z, fe)) | 0), + (d = (d + Math.imul(Z, ae)) | 0), + (l = (l + Math.imul(W, oe)) | 0), + (n = (n + Math.imul(W, se)) | 0), + (n = (n + Math.imul(K, oe)) | 0), + (d = (d + Math.imul(K, se)) | 0), + (l = (l + Math.imul(z2, he)) | 0), + (n = (n + Math.imul(z2, ue)) | 0), + (n = (n + Math.imul(H, he)) | 0), + (d = (d + Math.imul(H, ue)) | 0), + (l = (l + Math.imul(F, le)) | 0), + (n = (n + Math.imul(F, de)) | 0), + (n = (n + Math.imul(U, le)) | 0), + (d = (d + Math.imul(U, de)) | 0), + (l = (l + Math.imul(C2, ce)) | 0), + (n = (n + Math.imul(C2, pe)) | 0), + (n = (n + Math.imul(O, ce)) | 0), + (d = (d + Math.imul(O, pe)) | 0), + (l = (l + Math.imul(k, ve)) | 0), + (n = (n + Math.imul(k, be)) | 0), + (n = (n + Math.imul(D2, ve)) | 0), + (d = (d + Math.imul(D2, be)) | 0); + var Ge = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ge >>> 26)) | 0), + (Ge &= 67108863), + (l = Math.imul(G, ie)), + (n = Math.imul(G, ne)), + (n = (n + Math.imul(Y, ie)) | 0), + (d = Math.imul(Y, ne)), + (l = (l + Math.imul(V, fe)) | 0), + (n = (n + Math.imul(V, ae)) | 0), + (n = (n + Math.imul($2, fe)) | 0), + (d = (d + Math.imul($2, ae)) | 0), + (l = (l + Math.imul(j, oe)) | 0), + (n = (n + Math.imul(j, se)) | 0), + (n = (n + Math.imul(Z, oe)) | 0), + (d = (d + Math.imul(Z, se)) | 0), + (l = (l + Math.imul(W, he)) | 0), + (n = (n + Math.imul(W, ue)) | 0), + (n = (n + Math.imul(K, he)) | 0), + (d = (d + Math.imul(K, ue)) | 0), + (l = (l + Math.imul(z2, le)) | 0), + (n = (n + Math.imul(z2, de)) | 0), + (n = (n + Math.imul(H, le)) | 0), + (d = (d + Math.imul(H, de)) | 0), + (l = (l + Math.imul(F, ce)) | 0), + (n = (n + Math.imul(F, pe)) | 0), + (n = (n + Math.imul(U, ce)) | 0), + (d = (d + Math.imul(U, pe)) | 0), + (l = (l + Math.imul(C2, ve)) | 0), + (n = (n + Math.imul(C2, be)) | 0), + (n = (n + Math.imul(O, ve)) | 0), + (d = (d + Math.imul(O, be)) | 0); + var Ye = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ye >>> 26)) | 0), + (Ye &= 67108863), + (l = Math.imul(G, fe)), + (n = Math.imul(G, ae)), + (n = (n + Math.imul(Y, fe)) | 0), + (d = Math.imul(Y, ae)), + (l = (l + Math.imul(V, oe)) | 0), + (n = (n + Math.imul(V, se)) | 0), + (n = (n + Math.imul($2, oe)) | 0), + (d = (d + Math.imul($2, se)) | 0), + (l = (l + Math.imul(j, he)) | 0), + (n = (n + Math.imul(j, ue)) | 0), + (n = (n + Math.imul(Z, he)) | 0), + (d = (d + Math.imul(Z, ue)) | 0), + (l = (l + Math.imul(W, le)) | 0), + (n = (n + Math.imul(W, de)) | 0), + (n = (n + Math.imul(K, le)) | 0), + (d = (d + Math.imul(K, de)) | 0), + (l = (l + Math.imul(z2, ce)) | 0), + (n = (n + Math.imul(z2, pe)) | 0), + (n = (n + Math.imul(H, ce)) | 0), + (d = (d + Math.imul(H, pe)) | 0), + (l = (l + Math.imul(F, ve)) | 0), + (n = (n + Math.imul(F, be)) | 0), + (n = (n + Math.imul(U, ve)) | 0), + (d = (d + Math.imul(U, be)) | 0); + var Xe = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Xe >>> 26)) | 0), + (Xe &= 67108863), + (l = Math.imul(G, oe)), + (n = Math.imul(G, se)), + (n = (n + Math.imul(Y, oe)) | 0), + (d = Math.imul(Y, se)), + (l = (l + Math.imul(V, he)) | 0), + (n = (n + Math.imul(V, ue)) | 0), + (n = (n + Math.imul($2, he)) | 0), + (d = (d + Math.imul($2, ue)) | 0), + (l = (l + Math.imul(j, le)) | 0), + (n = (n + Math.imul(j, de)) | 0), + (n = (n + Math.imul(Z, le)) | 0), + (d = (d + Math.imul(Z, de)) | 0), + (l = (l + Math.imul(W, ce)) | 0), + (n = (n + Math.imul(W, pe)) | 0), + (n = (n + Math.imul(K, ce)) | 0), + (d = (d + Math.imul(K, pe)) | 0), + (l = (l + Math.imul(z2, ve)) | 0), + (n = (n + Math.imul(z2, be)) | 0), + (n = (n + Math.imul(H, ve)) | 0), + (d = (d + Math.imul(H, be)) | 0); + var Je = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Je >>> 26)) | 0), + (Je &= 67108863), + (l = Math.imul(G, he)), + (n = Math.imul(G, ue)), + (n = (n + Math.imul(Y, he)) | 0), + (d = Math.imul(Y, ue)), + (l = (l + Math.imul(V, le)) | 0), + (n = (n + Math.imul(V, de)) | 0), + (n = (n + Math.imul($2, le)) | 0), + (d = (d + Math.imul($2, de)) | 0), + (l = (l + Math.imul(j, ce)) | 0), + (n = (n + Math.imul(j, pe)) | 0), + (n = (n + Math.imul(Z, ce)) | 0), + (d = (d + Math.imul(Z, pe)) | 0), + (l = (l + Math.imul(W, ve)) | 0), + (n = (n + Math.imul(W, be)) | 0), + (n = (n + Math.imul(K, ve)) | 0), + (d = (d + Math.imul(K, be)) | 0); + var Qe = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Qe >>> 26)) | 0), + (Qe &= 67108863), + (l = Math.imul(G, le)), + (n = Math.imul(G, de)), + (n = (n + Math.imul(Y, le)) | 0), + (d = Math.imul(Y, de)), + (l = (l + Math.imul(V, ce)) | 0), + (n = (n + Math.imul(V, pe)) | 0), + (n = (n + Math.imul($2, ce)) | 0), + (d = (d + Math.imul($2, pe)) | 0), + (l = (l + Math.imul(j, ve)) | 0), + (n = (n + Math.imul(j, be)) | 0), + (n = (n + Math.imul(Z, ve)) | 0), + (d = (d + Math.imul(Z, be)) | 0); + var et = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (et >>> 26)) | 0), + (et &= 67108863), + (l = Math.imul(G, ce)), + (n = Math.imul(G, pe)), + (n = (n + Math.imul(Y, ce)) | 0), + (d = Math.imul(Y, pe)), + (l = (l + Math.imul(V, ve)) | 0), + (n = (n + Math.imul(V, be)) | 0), + (n = (n + Math.imul($2, ve)) | 0), + (d = (d + Math.imul($2, be)) | 0); + var tt = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (tt >>> 26)) | 0), (tt &= 67108863), (l = Math.imul(G, ve)), (n = Math.imul(G, be)), (n = (n + Math.imul(Y, ve)) | 0), (d = Math.imul(Y, be)); + var rt = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + return ( + (b3 = (((d + (n >>> 13)) | 0) + (rt >>> 26)) | 0), + (rt &= 67108863), + (c[0] = ft), + (c[1] = Be), + (c[2] = qe), + (c[3] = ze), + (c[4] = He), + (c[5] = We), + (c[6] = Ke), + (c[7] = je), + (c[8] = Ze), + (c[9] = Ve), + (c[10] = $e), + (c[11] = Ge), + (c[12] = Ye), + (c[13] = Xe), + (c[14] = Je), + (c[15] = Qe), + (c[16] = et), + (c[17] = tt), + (c[18] = rt), + b3 !== 0 && ((c[19] = b3), h2.length++), + h2 + ); + }; + Math.imul || (L2 = q2); + function ge(v, i, a) { + (a.negative = i.negative ^ v.negative), (a.length = v.length + i.length); + for (var h2 = 0, s = 0, u = 0; u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b3 = h2 & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1); n <= l; n++) { + var d = u - n, + w = v.words[d] | 0, + g = i.words[n] | 0, + _3 = w * g, + A2 = _3 & 67108863; + (c = (c + ((_3 / 67108864) | 0)) | 0), (A2 = (A2 + b3) | 0), (b3 = A2 & 67108863), (c = (c + (A2 >>> 26)) | 0), (s += c >>> 26), (c &= 67108863); + } + (a.words[u] = b3), (h2 = c), (c = s); + } + return h2 !== 0 ? (a.words[u] = h2) : a.length--, a.strip(); + } + function _e(v, i, a) { + var h2 = new N(); + return h2.mulp(v, i, a); + } + f.prototype.mulTo = function (i, a) { + var h2, + s = this.length + i.length; + return this.length === 10 && i.length === 10 ? (h2 = L2(this, i, a)) : s < 63 ? (h2 = q2(this, i, a)) : s < 1024 ? (h2 = ge(this, i, a)) : (h2 = _e(this, i, a)), h2; + }; + function N(v, i) { + (this.x = v), (this.y = i); + } + (N.prototype.makeRBT = function (i) { + for (var a = new Array(i), h2 = f.prototype._countBits(i) - 1, s = 0; s < i; s++) a[s] = this.revBin(s, h2, i); + return a; + }), + (N.prototype.revBin = function (i, a, h2) { + if (i === 0 || i === h2 - 1) return i; + for (var s = 0, u = 0; u < a; u++) (s |= (i & 1) << (a - u - 1)), (i >>= 1); + return s; + }), + (N.prototype.permute = function (i, a, h2, s, u, c) { + for (var b3 = 0; b3 < c; b3++) (s[b3] = a[i[b3]]), (u[b3] = h2[i[b3]]); + }), + (N.prototype.transform = function (i, a, h2, s, u, c) { + this.permute(c, i, a, h2, s, u); + for (var b3 = 1; b3 < u; b3 <<= 1) + for (var l = b3 << 1, n = Math.cos((2 * Math.PI) / l), d = Math.sin((2 * Math.PI) / l), w = 0; w < u; w += l) + for (var g = n, _3 = d, A2 = 0; A2 < b3; A2++) { + var R2 = h2[w + A2], + I = s[w + A2], + Me = h2[w + A2 + b3], + k = s[w + A2 + b3], + D2 = g * Me - _3 * k; + (k = g * k + _3 * Me), (Me = D2), (h2[w + A2] = R2 + Me), (s[w + A2] = I + k), (h2[w + A2 + b3] = R2 - Me), (s[w + A2 + b3] = I - k), A2 !== l && ((D2 = n * g - d * _3), (_3 = n * _3 + d * g), (g = D2)); + } + }), + (N.prototype.guessLen13b = function (i, a) { + var h2 = Math.max(a, i) | 1, + s = h2 & 1, + u = 0; + for (h2 = (h2 / 2) | 0; h2; h2 = h2 >>> 1) u++; + return 1 << (u + 1 + s); + }), + (N.prototype.conjugate = function (i, a, h2) { + if (!(h2 <= 1)) + for (var s = 0; s < h2 / 2; s++) { + var u = i[s]; + (i[s] = i[h2 - s - 1]), (i[h2 - s - 1] = u), (u = a[s]), (a[s] = -a[h2 - s - 1]), (a[h2 - s - 1] = -u); + } + }), + (N.prototype.normalize13b = function (i, a) { + for (var h2 = 0, s = 0; s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h2; + (i[s] = u & 67108863), u < 67108864 ? (h2 = 0) : (h2 = (u / 67108864) | 0); + } + return i; + }), + (N.prototype.convert13b = function (i, a, h2, s) { + for (var u = 0, c = 0; c < a; c++) (u = u + (i[c] | 0)), (h2[2 * c] = u & 8191), (u = u >>> 13), (h2[2 * c + 1] = u & 8191), (u = u >>> 13); + for (c = 2 * a; c < s; ++c) h2[c] = 0; + r(u === 0), r((u & -8192) === 0); + }), + (N.prototype.stub = function (i) { + for (var a = new Array(i), h2 = 0; h2 < i; h2++) a[h2] = 0; + return a; + }), + (N.prototype.mulp = function (i, a, h2) { + var s = 2 * this.guessLen13b(i.length, a.length), + u = this.makeRBT(s), + c = this.stub(s), + b3 = new Array(s), + l = new Array(s), + n = new Array(s), + d = new Array(s), + w = new Array(s), + g = new Array(s), + _3 = h2.words; + (_3.length = s), this.convert13b(i.words, i.length, b3, s), this.convert13b(a.words, a.length, d, s), this.transform(b3, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A2 = 0; A2 < s; A2++) { + var R2 = l[A2] * w[A2] - n[A2] * g[A2]; + (n[A2] = l[A2] * g[A2] + n[A2] * w[A2]), (l[A2] = R2); + } + return this.conjugate(l, n, s), this.transform(l, n, _3, c, s, u), this.conjugate(_3, c, s), this.normalize13b(_3, s), (h2.negative = i.negative ^ a.negative), (h2.length = i.length + a.length), h2.strip(); + }), + (f.prototype.mul = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), this.mulTo(i, a); + }), + (f.prototype.mulf = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), _e(this, i, a); + }), + (f.prototype.imul = function (i) { + return this.clone().mulTo(i, this); + }), + (f.prototype.imuln = function (i) { + r(typeof i == 'number'), r(i < 67108864); + for (var a = 0, h2 = 0; h2 < this.length; h2++) { + var s = (this.words[h2] | 0) * i, + u = (s & 67108863) + (a & 67108863); + (a >>= 26), (a += (s / 67108864) | 0), (a += u >>> 26), (this.words[h2] = u & 67108863); + } + return a !== 0 && ((this.words[h2] = a), this.length++), this; + }), + (f.prototype.muln = function (i) { + return this.clone().imuln(i); + }), + (f.prototype.sqr = function () { + return this.mul(this); + }), + (f.prototype.isqr = function () { + return this.imul(this.clone()); + }), + (f.prototype.pow = function (i) { + var a = B(i); + if (a.length === 0) return new f(1); + for (var h2 = this, s = 0; s < a.length && a[s] === 0; s++, h2 = h2.sqr()); + if (++s < a.length) for (var u = h2.sqr(); s < a.length; s++, u = u.sqr()) a[s] !== 0 && (h2 = h2.mul(u)); + return h2; + }), + (f.prototype.iushln = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26, + s = (67108863 >>> (26 - a)) << (26 - a), + u; + if (a !== 0) { + var c = 0; + for (u = 0; u < this.length; u++) { + var b3 = this.words[u] & s, + l = ((this.words[u] | 0) - b3) << a; + (this.words[u] = l | c), (c = b3 >>> (26 - a)); + } + c && ((this.words[u] = c), this.length++); + } + if (h2 !== 0) { + for (u = this.length - 1; u >= 0; u--) this.words[u + h2] = this.words[u]; + for (u = 0; u < h2; u++) this.words[u] = 0; + this.length += h2; + } + return this.strip(); + }), + (f.prototype.ishln = function (i) { + return r(this.negative === 0), this.iushln(i); + }), + (f.prototype.iushrn = function (i, a, h2) { + r(typeof i == 'number' && i >= 0); + var s; + a ? (s = (a - (a % 26)) / 26) : (s = 0); + var u = i % 26, + c = Math.min((i - u) / 26, this.length), + b3 = 67108863 ^ ((67108863 >>> u) << u), + l = h2; + if (((s -= c), (s = Math.max(0, s)), l)) { + for (var n = 0; n < c; n++) l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) for (this.length -= c, n = 0; n < this.length; n++) this.words[n] = this.words[n + c]; + else (this.words[0] = 0), (this.length = 1); + var d = 0; + for (n = this.length - 1; n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + (this.words[n] = (d << (26 - u)) | (w >>> u)), (d = w & b3); + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && ((this.words[0] = 0), (this.length = 1)), this.strip(); + }), + (f.prototype.ishrn = function (i, a, h2) { + return r(this.negative === 0), this.iushrn(i, a, h2); + }), + (f.prototype.shln = function (i) { + return this.clone().ishln(i); + }), + (f.prototype.ushln = function (i) { + return this.clone().iushln(i); + }), + (f.prototype.shrn = function (i) { + return this.clone().ishrn(i); + }), + (f.prototype.ushrn = function (i) { + return this.clone().iushrn(i); + }), + (f.prototype.testn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26, + s = 1 << a; + if (this.length <= h2) return false; + var u = this.words[h2]; + return !!(u & s); + }), + (f.prototype.imaskn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26; + if ((r(this.negative === 0, 'imaskn works only with positive numbers'), this.length <= h2)) return this; + if ((a !== 0 && h2++, (this.length = Math.min(h2, this.length)), a !== 0)) { + var s = 67108863 ^ ((67108863 >>> a) << a); + this.words[this.length - 1] &= s; + } + return this.strip(); + }), + (f.prototype.maskn = function (i) { + return this.clone().imaskn(i); + }), + (f.prototype.iaddn = function (i) { + return ( + r(typeof i == 'number'), + r(i < 67108864), + i < 0 + ? this.isubn(-i) + : this.negative !== 0 + ? this.length === 1 && (this.words[0] | 0) < i + ? ((this.words[0] = i - (this.words[0] | 0)), (this.negative = 0), this) + : ((this.negative = 0), this.isubn(i), (this.negative = 1), this) + : this._iaddn(i) + ); + }), + (f.prototype._iaddn = function (i) { + this.words[0] += i; + for (var a = 0; a < this.length && this.words[a] >= 67108864; a++) (this.words[a] -= 67108864), a === this.length - 1 ? (this.words[a + 1] = 1) : this.words[a + 1]++; + return (this.length = Math.max(this.length, a + 1)), this; + }), + (f.prototype.isubn = function (i) { + if ((r(typeof i == 'number'), r(i < 67108864), i < 0)) return this.iaddn(-i); + if (this.negative !== 0) return (this.negative = 0), this.iaddn(i), (this.negative = 1), this; + if (((this.words[0] -= i), this.length === 1 && this.words[0] < 0)) (this.words[0] = -this.words[0]), (this.negative = 1); + else for (var a = 0; a < this.length && this.words[a] < 0; a++) (this.words[a] += 67108864), (this.words[a + 1] -= 1); + return this.strip(); + }), + (f.prototype.addn = function (i) { + return this.clone().iaddn(i); + }), + (f.prototype.subn = function (i) { + return this.clone().isubn(i); + }), + (f.prototype.iabs = function () { + return (this.negative = 0), this; + }), + (f.prototype.abs = function () { + return this.clone().iabs(); + }), + (f.prototype._ishlnsubmul = function (i, a, h2) { + var s = i.length + h2, + u; + this._expand(s); + var c, + b3 = 0; + for (u = 0; u < i.length; u++) { + c = (this.words[u + h2] | 0) + b3; + var l = (i.words[u] | 0) * a; + (c -= l & 67108863), (b3 = (c >> 26) - ((l / 67108864) | 0)), (this.words[u + h2] = c & 67108863); + } + for (; u < this.length - h2; u++) (c = (this.words[u + h2] | 0) + b3), (b3 = c >> 26), (this.words[u + h2] = c & 67108863); + if (b3 === 0) return this.strip(); + for (r(b3 === -1), b3 = 0, u = 0; u < this.length; u++) (c = -(this.words[u] | 0) + b3), (b3 = c >> 26), (this.words[u] = c & 67108863); + return (this.negative = 1), this.strip(); + }), + (f.prototype._wordDiv = function (i, a) { + var h2 = this.length - i.length, + s = this.clone(), + u = i, + c = u.words[u.length - 1] | 0, + b3 = this._countBits(c); + (h2 = 26 - b3), h2 !== 0 && ((u = u.ushln(h2)), s.iushln(h2), (c = u.words[u.length - 1] | 0)); + var l = s.length - u.length, + n; + if (a !== 'mod') { + (n = new f(null)), (n.length = l + 1), (n.words = new Array(n.length)); + for (var d = 0; d < n.length; d++) n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && ((s = w), n && (n.words[l] = 1)); + for (var g = l - 1; g >= 0; g--) { + var _3 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_3 = Math.min((_3 / c) | 0, 67108863), s._ishlnsubmul(u, _3, g); s.negative !== 0; ) _3--, (s.negative = 0), s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _3); + } + return n && n.strip(), s.strip(), a !== 'div' && h2 !== 0 && s.iushrn(h2), {div: n || null, mod: s}; + }), + (f.prototype.divmod = function (i, a, h2) { + if ((r(!i.isZero()), this.isZero())) return {div: new f(0), mod: new f(0)}; + var s, u, c; + return this.negative !== 0 && i.negative === 0 + ? ((c = this.neg().divmod(i, a)), a !== 'mod' && (s = c.div.neg()), a !== 'div' && ((u = c.mod.neg()), h2 && u.negative !== 0 && u.iadd(i)), {div: s, mod: u}) + : this.negative === 0 && i.negative !== 0 + ? ((c = this.divmod(i.neg(), a)), a !== 'mod' && (s = c.div.neg()), {div: s, mod: c.mod}) + : (this.negative & i.negative) !== 0 + ? ((c = this.neg().divmod(i.neg(), a)), a !== 'div' && ((u = c.mod.neg()), h2 && u.negative !== 0 && u.isub(i)), {div: c.div, mod: u}) + : i.length > this.length || this.cmp(i) < 0 + ? {div: new f(0), mod: this} + : i.length === 1 + ? a === 'div' + ? {div: this.divn(i.words[0]), mod: null} + : a === 'mod' + ? {div: null, mod: new f(this.modn(i.words[0]))} + : {div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0]))} + : this._wordDiv(i, a); + }), + (f.prototype.div = function (i) { + return this.divmod(i, 'div', false).div; + }), + (f.prototype.mod = function (i) { + return this.divmod(i, 'mod', false).mod; + }), + (f.prototype.umod = function (i) { + return this.divmod(i, 'mod', true).mod; + }), + (f.prototype.divRound = function (i) { + var a = this.divmod(i); + if (a.mod.isZero()) return a.div; + var h2 = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, + s = i.ushrn(1), + u = i.andln(1), + c = h2.cmp(s); + return c < 0 || (u === 1 && c === 0) ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }), + (f.prototype.modn = function (i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h2 = 0, s = this.length - 1; s >= 0; s--) h2 = (a * h2 + (this.words[s] | 0)) % i; + return h2; + }), + (f.prototype.idivn = function (i) { + r(i <= 67108863); + for (var a = 0, h2 = this.length - 1; h2 >= 0; h2--) { + var s = (this.words[h2] | 0) + a * 67108864; + (this.words[h2] = (s / i) | 0), (a = s % i); + } + return this.strip(); + }), + (f.prototype.divn = function (i) { + return this.clone().idivn(i); + }), + (f.prototype.egcd = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h2 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = new f(0), b3 = new f(1), l = 0; a.isEven() && h2.isEven(); ) a.iushrn(1), h2.iushrn(1), ++l; + for (var n = h2.clone(), d = a.clone(); !a.isZero(); ) { + for (var w = 0, g = 1; (a.words[0] & g) === 0 && w < 26; ++w, g <<= 1); + if (w > 0) for (a.iushrn(w); w-- > 0; ) (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _3 = 0, A2 = 1; (h2.words[0] & A2) === 0 && _3 < 26; ++_3, A2 <<= 1); + if (_3 > 0) for (h2.iushrn(_3); _3-- > 0; ) (c.isOdd() || b3.isOdd()) && (c.iadd(n), b3.isub(d)), c.iushrn(1), b3.iushrn(1); + a.cmp(h2) >= 0 ? (a.isub(h2), s.isub(c), u.isub(b3)) : (h2.isub(a), c.isub(s), b3.isub(u)); + } + return {a: c, b: b3, gcd: h2.iushln(l)}; + }), + (f.prototype._invmp = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h2 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = h2.clone(); a.cmpn(1) > 0 && h2.cmpn(1) > 0; ) { + for (var b3 = 0, l = 1; (a.words[0] & l) === 0 && b3 < 26; ++b3, l <<= 1); + if (b3 > 0) for (a.iushrn(b3); b3-- > 0; ) s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1; (h2.words[0] & d) === 0 && n < 26; ++n, d <<= 1); + if (n > 0) for (h2.iushrn(n); n-- > 0; ) u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h2) >= 0 ? (a.isub(h2), s.isub(u)) : (h2.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? (w = s) : (w = u), w.cmpn(0) < 0 && w.iadd(i), w; + }), + (f.prototype.gcd = function (i) { + if (this.isZero()) return i.abs(); + if (i.isZero()) return this.abs(); + var a = this.clone(), + h2 = i.clone(); + (a.negative = 0), (h2.negative = 0); + for (var s = 0; a.isEven() && h2.isEven(); s++) a.iushrn(1), h2.iushrn(1); + do { + for (; a.isEven(); ) a.iushrn(1); + for (; h2.isEven(); ) h2.iushrn(1); + var u = a.cmp(h2); + if (u < 0) { + var c = a; + (a = h2), (h2 = c); + } else if (u === 0 || h2.cmpn(1) === 0) break; + a.isub(h2); + } while (true); + return h2.iushln(s); + }), + (f.prototype.invm = function (i) { + return this.egcd(i).a.umod(i); + }), + (f.prototype.isEven = function () { + return (this.words[0] & 1) === 0; + }), + (f.prototype.isOdd = function () { + return (this.words[0] & 1) === 1; + }), + (f.prototype.andln = function (i) { + return this.words[0] & i; + }), + (f.prototype.bincn = function (i) { + r(typeof i == 'number'); + var a = i % 26, + h2 = (i - a) / 26, + s = 1 << a; + if (this.length <= h2) return this._expand(h2 + 1), (this.words[h2] |= s), this; + for (var u = s, c = h2; u !== 0 && c < this.length; c++) { + var b3 = this.words[c] | 0; + (b3 += u), (u = b3 >>> 26), (b3 &= 67108863), (this.words[c] = b3); + } + return u !== 0 && ((this.words[c] = u), this.length++), this; + }), + (f.prototype.isZero = function () { + return this.length === 1 && this.words[0] === 0; + }), + (f.prototype.cmpn = function (i) { + var a = i < 0; + if (this.negative !== 0 && !a) return -1; + if (this.negative === 0 && a) return 1; + this.strip(); + var h2; + if (this.length > 1) h2 = 1; + else { + a && (i = -i), r(i <= 67108863, 'Number is too big'); + var s = this.words[0] | 0; + h2 = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h2 | 0 : h2; + }), + (f.prototype.cmp = function (i) { + if (this.negative !== 0 && i.negative === 0) return -1; + if (this.negative === 0 && i.negative !== 0) return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }), + (f.prototype.ucmp = function (i) { + if (this.length > i.length) return 1; + if (this.length < i.length) return -1; + for (var a = 0, h2 = this.length - 1; h2 >= 0; h2--) { + var s = this.words[h2] | 0, + u = i.words[h2] | 0; + if (s !== u) { + s < u ? (a = -1) : s > u && (a = 1); + break; + } + } + return a; + }), + (f.prototype.gtn = function (i) { + return this.cmpn(i) === 1; + }), + (f.prototype.gt = function (i) { + return this.cmp(i) === 1; + }), + (f.prototype.gten = function (i) { + return this.cmpn(i) >= 0; + }), + (f.prototype.gte = function (i) { + return this.cmp(i) >= 0; + }), + (f.prototype.ltn = function (i) { + return this.cmpn(i) === -1; + }), + (f.prototype.lt = function (i) { + return this.cmp(i) === -1; + }), + (f.prototype.lten = function (i) { + return this.cmpn(i) <= 0; + }), + (f.prototype.lte = function (i) { + return this.cmp(i) <= 0; + }), + (f.prototype.eqn = function (i) { + return this.cmpn(i) === 0; + }), + (f.prototype.eq = function (i) { + return this.cmp(i) === 0; + }), + (f.red = function (i) { + return new P(i); + }), + (f.prototype.toRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), r(this.negative === 0, 'red works only with positives'), i.convertTo(this)._forceRed(i); + }), + (f.prototype.fromRed = function () { + return r(this.red, 'fromRed works only with numbers in reduction context'), this.red.convertFrom(this); + }), + (f.prototype._forceRed = function (i) { + return (this.red = i), this; + }), + (f.prototype.forceRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), this._forceRed(i); + }), + (f.prototype.redAdd = function (i) { + return r(this.red, 'redAdd works only with red numbers'), this.red.add(this, i); + }), + (f.prototype.redIAdd = function (i) { + return r(this.red, 'redIAdd works only with red numbers'), this.red.iadd(this, i); + }), + (f.prototype.redSub = function (i) { + return r(this.red, 'redSub works only with red numbers'), this.red.sub(this, i); + }), + (f.prototype.redISub = function (i) { + return r(this.red, 'redISub works only with red numbers'), this.red.isub(this, i); + }), + (f.prototype.redShl = function (i) { + return r(this.red, 'redShl works only with red numbers'), this.red.shl(this, i); + }), + (f.prototype.redMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.mul(this, i); + }), + (f.prototype.redIMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.imul(this, i); + }), + (f.prototype.redSqr = function () { + return r(this.red, 'redSqr works only with red numbers'), this.red._verify1(this), this.red.sqr(this); + }), + (f.prototype.redISqr = function () { + return r(this.red, 'redISqr works only with red numbers'), this.red._verify1(this), this.red.isqr(this); + }), + (f.prototype.redSqrt = function () { + return r(this.red, 'redSqrt works only with red numbers'), this.red._verify1(this), this.red.sqrt(this); + }), + (f.prototype.redInvm = function () { + return r(this.red, 'redInvm works only with red numbers'), this.red._verify1(this), this.red.invm(this); + }), + (f.prototype.redNeg = function () { + return r(this.red, 'redNeg works only with red numbers'), this.red._verify1(this), this.red.neg(this); + }), + (f.prototype.redPow = function (i) { + return r(this.red && !i.red, 'redPow(normalNum)'), this.red._verify1(this), this.red.pow(this, i); + }); + var we = {k256: null, p224: null, p192: null, p25519: null}; + function ye(v, i) { + (this.name = v), (this.p = new f(i, 16)), (this.n = this.p.bitLength()), (this.k = new f(1).iushln(this.n).isub(this.p)), (this.tmp = this._tmp()); + } + (ye.prototype._tmp = function () { + var i = new f(null); + return (i.words = new Array(Math.ceil(this.n / 13))), i; + }), + (ye.prototype.ireduce = function (i) { + var a = i, + h2; + do this.split(a, this.tmp), (a = this.imulK(a)), (a = a.iadd(this.tmp)), (h2 = a.bitLength()); + while (h2 > this.n); + var s = h2 < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? ((a.words[0] = 0), (a.length = 1)) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }), + (ye.prototype.split = function (i, a) { + i.iushrn(this.n, 0, a); + }), + (ye.prototype.imulK = function (i) { + return i.imul(this.k); + }); + function xe() { + ye.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + o(xe, ye), + (xe.prototype.split = function (i, a) { + for (var h2 = 4194303, s = Math.min(i.length, 9), u = 0; u < s; u++) a.words[u] = i.words[u]; + if (((a.length = s), i.length <= 9)) { + (i.words[0] = 0), (i.length = 1); + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h2, u = 10; u < i.length; u++) { + var b3 = i.words[u] | 0; + (i.words[u - 10] = ((b3 & h2) << 4) | (c >>> 22)), (c = b3); + } + (c >>>= 22), (i.words[u - 10] = c), c === 0 && i.length > 10 ? (i.length -= 10) : (i.length -= 9); + }), + (xe.prototype.imulK = function (i) { + (i.words[i.length] = 0), (i.words[i.length + 1] = 0), (i.length += 2); + for (var a = 0, h2 = 0; h2 < i.length; h2++) { + var s = i.words[h2] | 0; + (a += s * 977), (i.words[h2] = a & 67108863), (a = s * 64 + ((a / 67108864) | 0)); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }); + function Re() { + ye.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + o(Re, ye); + function Ee() { + ye.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + o(Ee, ye); + function Ae() { + ye.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + o(Ae, ye), + (Ae.prototype.imulK = function (i) { + for (var a = 0, h2 = 0; h2 < i.length; h2++) { + var s = (i.words[h2] | 0) * 19 + a, + u = s & 67108863; + (s >>>= 26), (i.words[h2] = u), (a = s); + } + return a !== 0 && (i.words[i.length++] = a), i; + }), + (f._prime = function (i) { + if (we[i]) return we[i]; + var a; + if (i === 'k256') a = new xe(); + else if (i === 'p224') a = new Re(); + else if (i === 'p192') a = new Ee(); + else if (i === 'p25519') a = new Ae(); + else throw new Error('Unknown prime ' + i); + return (we[i] = a), a; + }); + function P(v) { + if (typeof v == 'string') { + var i = f._prime(v); + (this.m = i.p), (this.prime = i); + } else r(v.gtn(1), 'modulus must be greater than 1'), (this.m = v), (this.prime = null); + } + (P.prototype._verify1 = function (i) { + r(i.negative === 0, 'red works only with positives'), r(i.red, 'red works only with red numbers'); + }), + (P.prototype._verify2 = function (i, a) { + r((i.negative | a.negative) === 0, 'red works only with positives'), r(i.red && i.red === a.red, 'red works only with red numbers'); + }), + (P.prototype.imod = function (i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }), + (P.prototype.neg = function (i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }), + (P.prototype.add = function (i, a) { + this._verify2(i, a); + var h2 = i.add(a); + return h2.cmp(this.m) >= 0 && h2.isub(this.m), h2._forceRed(this); + }), + (P.prototype.iadd = function (i, a) { + this._verify2(i, a); + var h2 = i.iadd(a); + return h2.cmp(this.m) >= 0 && h2.isub(this.m), h2; + }), + (P.prototype.sub = function (i, a) { + this._verify2(i, a); + var h2 = i.sub(a); + return h2.cmpn(0) < 0 && h2.iadd(this.m), h2._forceRed(this); + }), + (P.prototype.isub = function (i, a) { + this._verify2(i, a); + var h2 = i.isub(a); + return h2.cmpn(0) < 0 && h2.iadd(this.m), h2; + }), + (P.prototype.shl = function (i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }), + (P.prototype.imul = function (i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }), + (P.prototype.mul = function (i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }), + (P.prototype.isqr = function (i) { + return this.imul(i, i.clone()); + }), + (P.prototype.sqr = function (i) { + return this.mul(i, i); + }), + (P.prototype.sqrt = function (i) { + if (i.isZero()) return i.clone(); + var a = this.m.andln(3); + if ((r(a % 2 === 1), a === 3)) { + var h2 = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h2); + } + for (var s = this.m.subn(1), u = 0; !s.isZero() && s.andln(1) === 0; ) u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), + b3 = c.redNeg(), + l = this.m.subn(1).iushrn(1), + n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this); this.pow(n, l).cmp(b3) !== 0; ) n.redIAdd(b3); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _3 = u; g.cmp(c) !== 0; ) { + for (var A2 = g, R2 = 0; A2.cmp(c) !== 0; R2++) A2 = A2.redSqr(); + r(R2 < _3); + var I = this.pow(d, new f(1).iushln(_3 - R2 - 1)); + (w = w.redMul(I)), (d = I.redSqr()), (g = g.redMul(d)), (_3 = R2); + } + return w; + }), + (P.prototype.invm = function (i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? ((a.negative = 0), this.imod(a).redNeg()) : this.imod(a); + }), + (P.prototype.pow = function (i, a) { + if (a.isZero()) return new f(1).toRed(this); + if (a.cmpn(1) === 0) return i.clone(); + var h2 = 4, + s = new Array(1 << h2); + (s[0] = new f(1).toRed(this)), (s[1] = i); + for (var u = 2; u < s.length; u++) s[u] = this.mul(s[u - 1], i); + var c = s[0], + b3 = 0, + l = 0, + n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1; u >= 0; u--) { + for (var d = a.words[u], w = n - 1; w >= 0; w--) { + var g = (d >> w) & 1; + if ((c !== s[0] && (c = this.sqr(c)), g === 0 && b3 === 0)) { + l = 0; + continue; + } + (b3 <<= 1), (b3 |= g), l++, !(l !== h2 && (u !== 0 || w !== 0)) && ((c = this.mul(c, s[b3])), (l = 0), (b3 = 0)); + } + n = 26; + } + return c; + }), + (P.prototype.convertTo = function (i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }), + (P.prototype.convertFrom = function (i) { + var a = i.clone(); + return (a.red = null), a; + }), + (f.mont = function (i) { + return new Se(i); + }); + function Se(v) { + P.call(this, v), + (this.shift = this.m.bitLength()), + this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), + (this.r = new f(1).iushln(this.shift)), + (this.r2 = this.imod(this.r.sqr())), + (this.rinv = this.r._invmp(this.m)), + (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), + (this.minv = this.minv.umod(this.r)), + (this.minv = this.r.sub(this.minv)); + } + o(Se, P), + (Se.prototype.convertTo = function (i) { + return this.imod(i.ushln(this.shift)); + }), + (Se.prototype.convertFrom = function (i) { + var a = this.imod(i.mul(this.rinv)); + return (a.red = null), a; + }), + (Se.prototype.imul = function (i, a) { + if (i.isZero() || a.isZero()) return (i.words[0] = 0), (i.length = 1), i; + var h2 = i.imul(a), + s = h2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h2.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.mul = function (i, a) { + if (i.isZero() || a.isZero()) return new f(0)._forceRed(this); + var h2 = i.mul(a), + s = h2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h2.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.invm = function (i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }); + })(typeof ed > 'u' || ed, ky); + }); + h0 = T2((Yk, Ly) => { + var s0 = Ut(), + Ff = s0.Buffer, + Er = {}, + Ar; + for (Ar in s0) !s0.hasOwnProperty(Ar) || Ar === 'SlowBuffer' || Ar === 'Buffer' || (Er[Ar] = s0[Ar]); + var Uf = (Er.Buffer = {}); + for (Ar in Ff) !Ff.hasOwnProperty(Ar) || Ar === 'allocUnsafe' || Ar === 'allocUnsafeSlow' || (Uf[Ar] = Ff[Ar]); + Er.Buffer.prototype = Ff.prototype; + (!Uf.from || Uf.from === Uint8Array.from) && + (Uf.from = function (t, e, r) { + if (typeof t == 'number') throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof t); + if (t && typeof t.length > 'u') throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof t); + return Ff(t, e, r); + }); + Uf.alloc || + (Uf.alloc = function (t, e, r) { + if (typeof t != 'number') throw new TypeError('The "size" argument must be of type number. Received type ' + typeof t); + if (t < 0 || t >= 2 * (1 << 30)) throw new RangeError('The value "' + t + '" is invalid for option "size"'); + var o = Ff(t); + return !e || e.length === 0 ? o.fill(0) : typeof r == 'string' ? o.fill(e, r) : o.fill(e), o; + }); + if (!Er.kStringMaxLength) + try { + Er.kStringMaxLength = process.binding('buffer').kStringMaxLength; + } catch {} + Er.constants || ((Er.constants = {MAX_LENGTH: Er.kMaxLength}), Er.kStringMaxLength && (Er.constants.MAX_STRING_LENGTH = Er.kStringMaxLength)); + Ly.exports = Er; + }); + u0 = T2(Ny => { + var aB = Ie(); + function Rr(t) { + this._reporterState = {obj: null, path: [], options: t || {}, errors: []}; + } + Ny.Reporter = Rr; + Rr.prototype.isError = function (e) { + return e instanceof zf; + }; + Rr.prototype.save = function () { + let e = this._reporterState; + return {obj: e.obj, pathLen: e.path.length}; + }; + Rr.prototype.restore = function (e) { + let r = this._reporterState; + (r.obj = e.obj), (r.path = r.path.slice(0, e.pathLen)); + }; + Rr.prototype.enterKey = function (e) { + return this._reporterState.path.push(e); + }; + Rr.prototype.exitKey = function (e) { + let r = this._reporterState; + r.path = r.path.slice(0, e - 1); + }; + Rr.prototype.leaveKey = function (e, r, o) { + let f = this._reporterState; + this.exitKey(e), f.obj !== null && (f.obj[r] = o); + }; + Rr.prototype.path = function () { + return this._reporterState.path.join('/'); + }; + Rr.prototype.enterObject = function () { + let e = this._reporterState, + r = e.obj; + return (e.obj = {}), r; + }; + Rr.prototype.leaveObject = function (e) { + let r = this._reporterState, + o = r.obj; + return (r.obj = e), o; + }; + Rr.prototype.error = function (e) { + let r, + o = this._reporterState, + f = e instanceof zf; + if ( + (f + ? (r = e) + : (r = new zf( + o.path + .map(function (p) { + return '[' + JSON.stringify(p) + ']'; + }) + .join(''), + e.message || e, + e.stack + )), + !o.options.partial) + ) + throw r; + return f || o.errors.push(r), r; + }; + Rr.prototype.wrapResult = function (e) { + let r = this._reporterState; + return r.options.partial ? {result: this.isError(e) ? null : e, errors: r.errors} : e; + }; + function zf(t, e) { + (this.path = t), this.rethrow(e); + } + aB(zf, Error); + zf.prototype.rethrow = function (e) { + if (((this.message = e + ' at: ' + (this.path || '(shallow)')), Error.captureStackTrace && Error.captureStackTrace(this, zf), !this.stack)) + try { + throw new Error(this.message); + } catch (r) { + this.stack = r.stack; + } + return this; + }; + }); + Kf = T2(rd => { + var oB = Ie(), + l0 = u0().Reporter, + Hf = h0().Buffer; + function Br(t, e) { + if ((l0.call(this, e), !Hf.isBuffer(t))) { + this.error('Input not Buffer'); + return; + } + (this.base = t), (this.offset = 0), (this.length = t.length); + } + oB(Br, l0); + rd.DecoderBuffer = Br; + Br.isDecoderBuffer = function (e) { + return e instanceof Br + ? true + : typeof e == 'object' && + Hf.isBuffer(e.base) && + e.constructor.name === 'DecoderBuffer' && + typeof e.offset == 'number' && + typeof e.length == 'number' && + typeof e.save == 'function' && + typeof e.restore == 'function' && + typeof e.isEmpty == 'function' && + typeof e.readUInt8 == 'function' && + typeof e.skip == 'function' && + typeof e.raw == 'function'; + }; + Br.prototype.save = function () { + return {offset: this.offset, reporter: l0.prototype.save.call(this)}; + }; + Br.prototype.restore = function (e) { + let r = new Br(this.base); + return (r.offset = e.offset), (r.length = this.offset), (this.offset = e.offset), l0.prototype.restore.call(this, e.reporter), r; + }; + Br.prototype.isEmpty = function () { + return this.offset === this.length; + }; + Br.prototype.readUInt8 = function (e) { + return this.offset + 1 <= this.length ? this.base.readUInt8(this.offset++, true) : this.error(e || 'DecoderBuffer overrun'); + }; + Br.prototype.skip = function (e, r) { + if (!(this.offset + e <= this.length)) return this.error(r || 'DecoderBuffer overrun'); + let o = new Br(this.base); + return (o._reporterState = this._reporterState), (o.offset = this.offset), (o.length = this.offset + e), (this.offset += e), o; + }; + Br.prototype.raw = function (e) { + return this.base.slice(e ? e.offset : this.offset, this.length); + }; + function Wf(t, e) { + if (Array.isArray(t)) + (this.length = 0), + (this.value = t.map(function (r) { + return Wf.isEncoderBuffer(r) || (r = new Wf(r, e)), (this.length += r.length), r; + }, this)); + else if (typeof t == 'number') { + if (!(0 <= t && t <= 255)) return e.error('non-byte EncoderBuffer value'); + (this.value = t), (this.length = 1); + } else if (typeof t == 'string') (this.value = t), (this.length = Hf.byteLength(t)); + else if (Hf.isBuffer(t)) (this.value = t), (this.length = t.length); + else return e.error('Unsupported type: ' + typeof t); + } + rd.EncoderBuffer = Wf; + Wf.isEncoderBuffer = function (e) { + return e instanceof Wf ? true : typeof e == 'object' && e.constructor.name === 'EncoderBuffer' && typeof e.length == 'number' && typeof e.join == 'function'; + }; + Wf.prototype.join = function (e, r) { + return ( + e || (e = Hf.alloc(this.length)), + r || (r = 0), + this.length === 0 || + (Array.isArray(this.value) + ? this.value.forEach(function (o) { + o.join(e, r), (r += o.length); + }) + : (typeof this.value == 'number' ? (e[r] = this.value) : typeof this.value == 'string' ? e.write(this.value, r) : Hf.isBuffer(this.value) && this.value.copy(e, r), (r += this.length))), + e + ); + }; + }); + d0 = T2((Qk, Py) => { + var sB = u0().Reporter, + hB = Kf().EncoderBuffer, + uB = Kf().DecoderBuffer, + Qt = ar(), + Dy = [ + 'seq', + 'seqof', + 'set', + 'setof', + 'objid', + 'bool', + 'gentime', + 'utctime', + 'null_', + 'enum', + 'int', + 'objDesc', + 'bitstr', + 'bmpstr', + 'charstr', + 'genstr', + 'graphstr', + 'ia5str', + 'iso646str', + 'numstr', + 'octstr', + 'printstr', + 't61str', + 'unistr', + 'utf8str', + 'videostr' + ], + lB = ['key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains'].concat(Dy), + dB = [ + '_peekTag', + '_decodeTag', + '_use', + '_decodeStr', + '_decodeObjid', + '_decodeTime', + '_decodeNull', + '_decodeInt', + '_decodeBool', + '_decodeList', + '_encodeComposite', + '_encodeStr', + '_encodeObjid', + '_encodeTime', + '_encodeNull', + '_encodeInt', + '_encodeBool' + ]; + function Ue(t, e, r) { + let o = {}; + (this._baseState = o), + (o.name = r), + (o.enc = t), + (o.parent = e || null), + (o.children = null), + (o.tag = null), + (o.args = null), + (o.reverseArgs = null), + (o.choice = null), + (o.optional = false), + (o.any = false), + (o.obj = false), + (o.use = null), + (o.useDecoder = null), + (o.key = null), + (o.default = null), + (o.explicit = null), + (o.implicit = null), + (o.contains = null), + o.parent || ((o.children = []), this._wrap()); + } + Py.exports = Ue; + var cB = ['enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains']; + Ue.prototype.clone = function () { + let e = this._baseState, + r = {}; + cB.forEach(function (f) { + r[f] = e[f]; + }); + let o = new this.constructor(r.parent); + return (o._baseState = r), o; + }; + Ue.prototype._wrap = function () { + let e = this._baseState; + lB.forEach(function (r) { + this[r] = function () { + let f = new this.constructor(this); + return e.children.push(f), f[r].apply(f, arguments); + }; + }, this); + }; + Ue.prototype._init = function (e) { + let r = this._baseState; + Qt(r.parent === null), + e.call(this), + (r.children = r.children.filter(function (o) { + return o._baseState.parent === this; + }, this)), + Qt.equal(r.children.length, 1, 'Root node can have only one child'); + }; + Ue.prototype._useArgs = function (e) { + let r = this._baseState, + o = e.filter(function (f) { + return f instanceof this.constructor; + }, this); + (e = e.filter(function (f) { + return !(f instanceof this.constructor); + }, this)), + o.length !== 0 && + (Qt(r.children === null), + (r.children = o), + o.forEach(function (f) { + f._baseState.parent = this; + }, this)), + e.length !== 0 && + (Qt(r.args === null), + (r.args = e), + (r.reverseArgs = e.map(function (f) { + if (typeof f != 'object' || f.constructor !== Object) return f; + let p = {}; + return ( + Object.keys(f).forEach(function (m2) { + m2 == (m2 | 0) && (m2 |= 0); + let y3 = f[m2]; + p[y3] = m2; + }), + p + ); + }))); + }; + dB.forEach(function (t) { + Ue.prototype[t] = function () { + let r = this._baseState; + throw new Error(t + ' not implemented for encoding: ' + r.enc); + }; + }); + Dy.forEach(function (t) { + Ue.prototype[t] = function () { + let r = this._baseState, + o = Array.prototype.slice.call(arguments); + return Qt(r.tag === null), (r.tag = t), this._useArgs(o), this; + }; + }); + Ue.prototype.use = function (e) { + Qt(e); + let r = this._baseState; + return Qt(r.use === null), (r.use = e), this; + }; + Ue.prototype.optional = function () { + let e = this._baseState; + return (e.optional = true), this; + }; + Ue.prototype.def = function (e) { + let r = this._baseState; + return Qt(r.default === null), (r.default = e), (r.optional = true), this; + }; + Ue.prototype.explicit = function (e) { + let r = this._baseState; + return Qt(r.explicit === null && r.implicit === null), (r.explicit = e), this; + }; + Ue.prototype.implicit = function (e) { + let r = this._baseState; + return Qt(r.explicit === null && r.implicit === null), (r.implicit = e), this; + }; + Ue.prototype.obj = function () { + let e = this._baseState, + r = Array.prototype.slice.call(arguments); + return (e.obj = true), r.length !== 0 && this._useArgs(r), this; + }; + Ue.prototype.key = function (e) { + let r = this._baseState; + return Qt(r.key === null), (r.key = e), this; + }; + Ue.prototype.any = function () { + let e = this._baseState; + return (e.any = true), this; + }; + Ue.prototype.choice = function (e) { + let r = this._baseState; + return ( + Qt(r.choice === null), + (r.choice = e), + this._useArgs( + Object.keys(e).map(function (o) { + return e[o]; + }) + ), + this + ); + }; + Ue.prototype.contains = function (e) { + let r = this._baseState; + return Qt(r.use === null), (r.contains = e), this; + }; + Ue.prototype._decode = function (e, r) { + let o = this._baseState; + if (o.parent === null) return e.wrapResult(o.children[0]._decode(e, r)); + let f = o.default, + p = true, + m2 = null; + if ((o.key !== null && (m2 = e.enterKey(o.key)), o.optional)) { + let M = null; + if ((o.explicit !== null ? (M = o.explicit) : o.implicit !== null ? (M = o.implicit) : o.tag !== null && (M = o.tag), M === null && !o.any)) { + let x = e.save(); + try { + o.choice === null ? this._decodeGeneric(o.tag, e, r) : this._decodeChoice(e, r), (p = true); + } catch { + p = false; + } + e.restore(x); + } else if (((p = this._peekTag(e, M, o.any)), e.isError(p))) return p; + } + let y3; + if ((o.obj && p && (y3 = e.enterObject()), p)) { + if (o.explicit !== null) { + let x = this._decodeTag(e, o.explicit); + if (e.isError(x)) return x; + e = x; + } + let M = e.offset; + if (o.use === null && o.choice === null) { + let x; + o.any && (x = e.save()); + let S = this._decodeTag(e, o.implicit !== null ? o.implicit : o.tag, o.any); + if (e.isError(S)) return S; + o.any ? (f = e.raw(x)) : (e = S); + } + if ( + (r && r.track && o.tag !== null && r.track(e.path(), M, e.length, 'tagged'), + r && r.track && o.tag !== null && r.track(e.path(), e.offset, e.length, 'content'), + o.any || (o.choice === null ? (f = this._decodeGeneric(o.tag, e, r)) : (f = this._decodeChoice(e, r))), + e.isError(f)) + ) + return f; + if ( + (!o.any && + o.choice === null && + o.children !== null && + o.children.forEach(function (S) { + S._decode(e, r); + }), + o.contains && (o.tag === 'octstr' || o.tag === 'bitstr')) + ) { + let x = new uB(f); + f = this._getUse(o.contains, e._reporterState.obj)._decode(x, r); + } + } + return o.obj && p && (f = e.leaveObject(y3)), o.key !== null && (f !== null || p === true) ? e.leaveKey(m2, o.key, f) : m2 !== null && e.exitKey(m2), f; + }; + Ue.prototype._decodeGeneric = function (e, r, o) { + let f = this._baseState; + return e === 'seq' || e === 'set' + ? null + : e === 'seqof' || e === 'setof' + ? this._decodeList(r, e, f.args[0], o) + : /str$/.test(e) + ? this._decodeStr(r, e, o) + : e === 'objid' && f.args + ? this._decodeObjid(r, f.args[0], f.args[1], o) + : e === 'objid' + ? this._decodeObjid(r, null, null, o) + : e === 'gentime' || e === 'utctime' + ? this._decodeTime(r, e, o) + : e === 'null_' + ? this._decodeNull(r, o) + : e === 'bool' + ? this._decodeBool(r, o) + : e === 'objDesc' + ? this._decodeStr(r, e, o) + : e === 'int' || e === 'enum' + ? this._decodeInt(r, f.args && f.args[0], o) + : f.use !== null + ? this._getUse(f.use, r._reporterState.obj)._decode(r, o) + : r.error('unknown tag: ' + e); + }; + Ue.prototype._getUse = function (e, r) { + let o = this._baseState; + return ( + (o.useDecoder = this._use(e, r)), + Qt(o.useDecoder._baseState.parent === null), + (o.useDecoder = o.useDecoder._baseState.children[0]), + o.implicit !== o.useDecoder._baseState.implicit && ((o.useDecoder = o.useDecoder.clone()), (o.useDecoder._baseState.implicit = o.implicit)), + o.useDecoder + ); + }; + Ue.prototype._decodeChoice = function (e, r) { + let o = this._baseState, + f = null, + p = false; + return ( + Object.keys(o.choice).some(function (m2) { + let y3 = e.save(), + M = o.choice[m2]; + try { + let x = M._decode(e, r); + if (e.isError(x)) return false; + (f = {type: m2, value: x}), (p = true); + } catch { + return e.restore(y3), false; + } + return true; + }, this), + p ? f : e.error('Choice not matched') + ); + }; + Ue.prototype._createEncoderBuffer = function (e) { + return new hB(e, this.reporter); + }; + Ue.prototype._encode = function (e, r, o) { + let f = this._baseState; + if (f.default !== null && f.default === e) return; + let p = this._encodeValue(e, r, o); + if (p !== undefined && !this._skipDefault(p, r, o)) return p; + }; + Ue.prototype._encodeValue = function (e, r, o) { + let f = this._baseState; + if (f.parent === null) return f.children[0]._encode(e, r || new sB()); + let p = null; + if (((this.reporter = r), f.optional && e === undefined)) + if (f.default !== null) e = f.default; + else return; + let m2 = null, + y3 = false; + if (f.any) p = this._createEncoderBuffer(e); + else if (f.choice) p = this._encodeChoice(e, r); + else if (f.contains) (m2 = this._getUse(f.contains, o)._encode(e, r)), (y3 = true); + else if (f.children) + (m2 = f.children + .map(function (M) { + if (M._baseState.tag === 'null_') return M._encode(null, r, e); + if (M._baseState.key === null) return r.error('Child should have a key'); + let x = r.enterKey(M._baseState.key); + if (typeof e != 'object') return r.error('Child expected, but input is not object'); + let S = M._encode(e[M._baseState.key], r, e); + return r.leaveKey(x), S; + }, this) + .filter(function (M) { + return M; + })), + (m2 = this._createEncoderBuffer(m2)); + else if (f.tag === 'seqof' || f.tag === 'setof') { + if (!(f.args && f.args.length === 1)) return r.error('Too many args for : ' + f.tag); + if (!Array.isArray(e)) return r.error('seqof/setof, but data is not Array'); + let M = this.clone(); + (M._baseState.implicit = null), + (m2 = this._createEncoderBuffer( + e.map(function (x) { + let S = this._baseState; + return this._getUse(S.args[0], e)._encode(x, r); + }, M) + )); + } else f.use !== null ? (p = this._getUse(f.use, o)._encode(e, r)) : ((m2 = this._encodePrimitive(f.tag, e)), (y3 = true)); + if (!f.any && f.choice === null) { + let M = f.implicit !== null ? f.implicit : f.tag, + x = f.implicit === null ? 'universal' : 'context'; + M === null ? f.use === null && r.error('Tag could be omitted only for .use()') : f.use === null && (p = this._encodeComposite(M, y3, x, m2)); + } + return f.explicit !== null && (p = this._encodeComposite(f.explicit, false, 'context', p)), p; + }; + Ue.prototype._encodeChoice = function (e, r) { + let o = this._baseState, + f = o.choice[e.type]; + return f || Qt(false, e.type + ' not found in ' + JSON.stringify(Object.keys(o.choice))), f._encode(e.value, r); + }; + Ue.prototype._encodePrimitive = function (e, r) { + let o = this._baseState; + if (/str$/.test(e)) return this._encodeStr(r, e); + if (e === 'objid' && o.args) return this._encodeObjid(r, o.reverseArgs[0], o.args[1]); + if (e === 'objid') return this._encodeObjid(r, null, null); + if (e === 'gentime' || e === 'utctime') return this._encodeTime(r, e); + if (e === 'null_') return this._encodeNull(); + if (e === 'int' || e === 'enum') return this._encodeInt(r, o.args && o.reverseArgs[0]); + if (e === 'bool') return this._encodeBool(r); + if (e === 'objDesc') return this._encodeStr(r, e); + throw new Error('Unsupported tag: ' + e); + }; + Ue.prototype._isNumstr = function (e) { + return /^[0-9 ]*$/.test(e); + }; + Ue.prototype._isPrintstr = function (e) { + return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(e); + }; + }); + c0 = T2(Wn => { + function Cy(t) { + let e = {}; + return ( + Object.keys(t).forEach(function (r) { + (r | 0) == r && (r = r | 0); + let o = t[r]; + e[o] = r; + }), + e + ); + } + Wn.tagClass = {0: 'universal', 1: 'application', 2: 'context', 3: 'private'}; + Wn.tagClassByName = Cy(Wn.tagClass); + Wn.tag = { + 0: 'end', + 1: 'bool', + 2: 'int', + 3: 'bitstr', + 4: 'octstr', + 5: 'null_', + 6: 'objid', + 7: 'objDesc', + 8: 'external', + 9: 'real', + 10: 'enum', + 11: 'embed', + 12: 'utf8str', + 13: 'relativeOid', + 16: 'seq', + 17: 'set', + 18: 'numstr', + 19: 'printstr', + 20: 't61str', + 21: 'videostr', + 22: 'ia5str', + 23: 'utctime', + 24: 'gentime', + 25: 'graphstr', + 26: 'iso646str', + 27: 'genstr', + 28: 'unistr', + 29: 'charstr', + 30: 'bmpstr' + }; + Wn.tagByName = Cy(Wn.tag); + }); + nd = T2((tL, Uy) => { + var pB = Ie(), + Ii = h0().Buffer, + Oy = d0(), + id = c0(); + function Fy(t) { + (this.enc = 'der'), (this.name = t.name), (this.entity = t), (this.tree = new Ur()), this.tree._init(t.body); + } + Uy.exports = Fy; + Fy.prototype.encode = function (e, r) { + return this.tree._encode(e, r).join(); + }; + function Ur(t) { + Oy.call(this, 'der', t); + } + pB(Ur, Oy); + Ur.prototype._encodeComposite = function (e, r, o, f) { + let p = vB(e, r, o, this.reporter); + if (f.length < 128) { + let M = Ii.alloc(2); + return (M[0] = p), (M[1] = f.length), this._createEncoderBuffer([M, f]); + } + let m2 = 1; + for (let M = f.length; M >= 256; M >>= 8) m2++; + let y3 = Ii.alloc(1 + 1 + m2); + (y3[0] = p), (y3[1] = 128 | m2); + for (let M = 1 + m2, x = f.length; x > 0; M--, x >>= 8) y3[M] = x & 255; + return this._createEncoderBuffer([y3, f]); + }; + Ur.prototype._encodeStr = function (e, r) { + if (r === 'bitstr') return this._createEncoderBuffer([e.unused | 0, e.data]); + if (r === 'bmpstr') { + let o = Ii.alloc(e.length * 2); + for (let f = 0; f < e.length; f++) o.writeUInt16BE(e.charCodeAt(f), f * 2); + return this._createEncoderBuffer(o); + } else + return r === 'numstr' + ? this._isNumstr(e) + ? this._createEncoderBuffer(e) + : this.reporter.error('Encoding of string type: numstr supports only digits and space') + : r === 'printstr' + ? this._isPrintstr(e) + ? this._createEncoderBuffer(e) + : this.reporter.error( + 'Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark' + ) + : /str$/.test(r) + ? this._createEncoderBuffer(e) + : r === 'objDesc' + ? this._createEncoderBuffer(e) + : this.reporter.error('Encoding of string type: ' + r + ' unsupported'); + }; + Ur.prototype._encodeObjid = function (e, r, o) { + if (typeof e == 'string') { + if (!r) return this.reporter.error('string objid given, but no values map found'); + if (!r.hasOwnProperty(e)) return this.reporter.error('objid not found in values map'); + e = r[e].split(/[\s.]+/g); + for (let y3 = 0; y3 < e.length; y3++) e[y3] |= 0; + } else if (Array.isArray(e)) { + e = e.slice(); + for (let y3 = 0; y3 < e.length; y3++) e[y3] |= 0; + } + if (!Array.isArray(e)) return this.reporter.error('objid() should be either array or string, got: ' + JSON.stringify(e)); + if (!o) { + if (e[1] >= 40) return this.reporter.error('Second objid identifier OOB'); + e.splice(0, 2, e[0] * 40 + e[1]); + } + let f = 0; + for (let y3 = 0; y3 < e.length; y3++) { + let M = e[y3]; + for (f++; M >= 128; M >>= 7) f++; + } + let p = Ii.alloc(f), + m2 = p.length - 1; + for (let y3 = e.length - 1; y3 >= 0; y3--) { + let M = e[y3]; + for (p[m2--] = M & 127; (M >>= 7) > 0; ) p[m2--] = 128 | (M & 127); + } + return this._createEncoderBuffer(p); + }; + function qr(t) { + return t < 10 ? '0' + t : t; + } + Ur.prototype._encodeTime = function (e, r) { + let o, + f = new Date(e); + return ( + r === 'gentime' + ? (o = [qr(f.getUTCFullYear()), qr(f.getUTCMonth() + 1), qr(f.getUTCDate()), qr(f.getUTCHours()), qr(f.getUTCMinutes()), qr(f.getUTCSeconds()), 'Z'].join('')) + : r === 'utctime' + ? (o = [qr(f.getUTCFullYear() % 100), qr(f.getUTCMonth() + 1), qr(f.getUTCDate()), qr(f.getUTCHours()), qr(f.getUTCMinutes()), qr(f.getUTCSeconds()), 'Z'].join('')) + : this.reporter.error('Encoding ' + r + ' time is not supported yet'), + this._encodeStr(o, 'octstr') + ); + }; + Ur.prototype._encodeNull = function () { + return this._createEncoderBuffer(''); + }; + Ur.prototype._encodeInt = function (e, r) { + if (typeof e == 'string') { + if (!r) return this.reporter.error('String int or enum given, but no values map'); + if (!r.hasOwnProperty(e)) return this.reporter.error("Values map doesn't contain: " + JSON.stringify(e)); + e = r[e]; + } + if (typeof e != 'number' && !Ii.isBuffer(e)) { + let p = e.toArray(); + !e.sign && p[0] & 128 && p.unshift(0), (e = Ii.from(p)); + } + if (Ii.isBuffer(e)) { + let p = e.length; + e.length === 0 && p++; + let m2 = Ii.alloc(p); + return e.copy(m2), e.length === 0 && (m2[0] = 0), this._createEncoderBuffer(m2); + } + if (e < 128) return this._createEncoderBuffer(e); + if (e < 256) return this._createEncoderBuffer([0, e]); + let o = 1; + for (let p = e; p >= 256; p >>= 8) o++; + let f = new Array(o); + for (let p = f.length - 1; p >= 0; p--) (f[p] = e & 255), (e >>= 8); + return f[0] & 128 && f.unshift(0), this._createEncoderBuffer(Ii.from(f)); + }; + Ur.prototype._encodeBool = function (e) { + return this._createEncoderBuffer(e ? 255 : 0); + }; + Ur.prototype._use = function (e, r) { + return typeof e == 'function' && (e = e(r)), e._getEncoder('der').tree; + }; + Ur.prototype._skipDefault = function (e, r, o) { + let f = this._baseState, + p; + if (f.default === null) return false; + let m2 = e.join(); + if ((f.defaultBuffer === undefined && (f.defaultBuffer = this._encodeValue(f.default, r, o).join()), m2.length !== f.defaultBuffer.length)) return false; + for (p = 0; p < m2.length; p++) if (m2[p] !== f.defaultBuffer[p]) return false; + return true; + }; + function vB(t, e, r, o) { + let f; + if ((t === 'seqof' ? (t = 'seq') : t === 'setof' && (t = 'set'), id.tagByName.hasOwnProperty(t))) f = id.tagByName[t]; + else if (typeof t == 'number' && (t | 0) === t) f = t; + else return o.error('Unknown tag: ' + t); + return f >= 31 ? o.error('Multi-octet tag encoding unsupported') : (e || (f |= 32), (f |= id.tagClassByName[r || 'universal'] << 6), f); + } + }); + Hy = T2((rL, zy) => { + var bB = Ie(), + fd = nd(); + function ad(t) { + fd.call(this, t), (this.enc = 'pem'); + } + bB(ad, fd); + zy.exports = ad; + ad.prototype.encode = function (e, r) { + let f = fd.prototype.encode.call(this, e).toString('base64'), + p = ['-----BEGIN ' + r.label + '-----']; + for (let m2 = 0; m2 < f.length; m2 += 64) p.push(f.slice(m2, m2 + 64)); + return ( + p.push('-----END ' + r.label + '-----'), + p.join(` +`) + ); + }; + }); + od = T2(Ky => { + var Wy = Ky; + Wy.der = nd(); + Wy.pem = Hy(); + }); + hd = T2((nL, Yy) => { + var mB = Ie(), + gB = td(), + jy = Kf().DecoderBuffer, + Vy = d0(), + Zy = c0(); + function $y(t) { + (this.enc = 'der'), (this.name = t.name), (this.entity = t), (this.tree = new sr()), this.tree._init(t.body); + } + Yy.exports = $y; + $y.prototype.decode = function (e, r) { + return jy.isDecoderBuffer(e) || (e = new jy(e, r)), this.tree._decode(e, r); + }; + function sr(t) { + Vy.call(this, 'der', t); + } + mB(sr, Vy); + sr.prototype._peekTag = function (e, r, o) { + if (e.isEmpty()) return false; + let f = e.save(), + p = sd(e, 'Failed to peek tag: "' + r + '"'); + return e.isError(p) ? p : (e.restore(f), p.tag === r || p.tagStr === r || p.tagStr + 'of' === r || o); + }; + sr.prototype._decodeTag = function (e, r, o) { + let f = sd(e, 'Failed to decode tag of "' + r + '"'); + if (e.isError(f)) return f; + let p = Gy(e, f.primitive, 'Failed to get length of "' + r + '"'); + if (e.isError(p)) return p; + if (!o && f.tag !== r && f.tagStr !== r && f.tagStr + 'of' !== r) return e.error('Failed to match tag: "' + r + '"'); + if (f.primitive || p !== null) return e.skip(p, 'Failed to match body of: "' + r + '"'); + let m2 = e.save(), + y3 = this._skipUntilEnd(e, 'Failed to skip indefinite length body: "' + this.tag + '"'); + return e.isError(y3) ? y3 : ((p = e.offset - m2.offset), e.restore(m2), e.skip(p, 'Failed to match body of: "' + r + '"')); + }; + sr.prototype._skipUntilEnd = function (e, r) { + for (;;) { + let o = sd(e, r); + if (e.isError(o)) return o; + let f = Gy(e, o.primitive, r); + if (e.isError(f)) return f; + let p; + if ((o.primitive || f !== null ? (p = e.skip(f)) : (p = this._skipUntilEnd(e, r)), e.isError(p))) return p; + if (o.tagStr === 'end') break; + } + }; + sr.prototype._decodeList = function (e, r, o, f) { + let p = []; + for (; !e.isEmpty(); ) { + let m2 = this._peekTag(e, 'end'); + if (e.isError(m2)) return m2; + let y3 = o.decode(e, 'der', f); + if (e.isError(y3) && m2) break; + p.push(y3); + } + return p; + }; + sr.prototype._decodeStr = function (e, r) { + if (r === 'bitstr') { + let o = e.readUInt8(); + return e.isError(o) ? o : {unused: o, data: e.raw()}; + } else if (r === 'bmpstr') { + let o = e.raw(); + if (o.length % 2 === 1) return e.error('Decoding of string type: bmpstr length mismatch'); + let f = ''; + for (let p = 0; p < o.length / 2; p++) f += String.fromCharCode(o.readUInt16BE(p * 2)); + return f; + } else if (r === 'numstr') { + let o = e.raw().toString('ascii'); + return this._isNumstr(o) ? o : e.error('Decoding of string type: numstr unsupported characters'); + } else { + if (r === 'octstr') return e.raw(); + if (r === 'objDesc') return e.raw(); + if (r === 'printstr') { + let o = e.raw().toString('ascii'); + return this._isPrintstr(o) ? o : e.error('Decoding of string type: printstr unsupported characters'); + } else return /str$/.test(r) ? e.raw().toString() : e.error('Decoding of string type: ' + r + ' unsupported'); + } + }; + sr.prototype._decodeObjid = function (e, r, o) { + let f, + p = [], + m2 = 0, + y3 = 0; + for (; !e.isEmpty(); ) (y3 = e.readUInt8()), (m2 <<= 7), (m2 |= y3 & 127), (y3 & 128) === 0 && (p.push(m2), (m2 = 0)); + y3 & 128 && p.push(m2); + let M = (p[0] / 40) | 0, + x = p[0] % 40; + if ((o ? (f = p) : (f = [M, x].concat(p.slice(1))), r)) { + let S = r[f.join(' ')]; + S === undefined && (S = r[f.join('.')]), S !== undefined && (f = S); + } + return f; + }; + sr.prototype._decodeTime = function (e, r) { + let o = e.raw().toString(), + f, + p, + m2, + y3, + M, + x; + if (r === 'gentime') (f = o.slice(0, 4) | 0), (p = o.slice(4, 6) | 0), (m2 = o.slice(6, 8) | 0), (y3 = o.slice(8, 10) | 0), (M = o.slice(10, 12) | 0), (x = o.slice(12, 14) | 0); + else if (r === 'utctime') (f = o.slice(0, 2) | 0), (p = o.slice(2, 4) | 0), (m2 = o.slice(4, 6) | 0), (y3 = o.slice(6, 8) | 0), (M = o.slice(8, 10) | 0), (x = o.slice(10, 12) | 0), f < 70 ? (f = 2000 + f) : (f = 1900 + f); + else return e.error('Decoding ' + r + ' time is not supported yet'); + return Date.UTC(f, p - 1, m2, y3, M, x, 0); + }; + sr.prototype._decodeNull = function () { + return null; + }; + sr.prototype._decodeBool = function (e) { + let r = e.readUInt8(); + return e.isError(r) ? r : r !== 0; + }; + sr.prototype._decodeInt = function (e, r) { + let o = e.raw(), + f = new gB(o); + return r && (f = r[f.toString(10)] || f), f; + }; + sr.prototype._use = function (e, r) { + return typeof e == 'function' && (e = e(r)), e._getDecoder('der').tree; + }; + function sd(t, e) { + let r = t.readUInt8(e); + if (t.isError(r)) return r; + let o = Zy.tagClass[r >> 6], + f = (r & 32) === 0; + if ((r & 31) === 31) { + let m2 = r; + for (r = 0; (m2 & 128) === 128; ) { + if (((m2 = t.readUInt8(e)), t.isError(m2))) return m2; + (r <<= 7), (r |= m2 & 127); + } + } else r &= 31; + let p = Zy.tag[r]; + return {cls: o, primitive: f, tag: r, tagStr: p}; + } + function Gy(t, e, r) { + let o = t.readUInt8(r); + if (t.isError(o)) return o; + if (!e && o === 128) return null; + if ((o & 128) === 0) return o; + let f = o & 127; + if (f > 4) return t.error('length octect is too long'); + o = 0; + for (let p = 0; p < f; p++) { + o <<= 8; + let m2 = t.readUInt8(r); + if (t.isError(m2)) return m2; + o |= m2; + } + return o; + } + }); + Jy = T2((fL, Xy) => { + var yB = Ie(), + wB = h0().Buffer, + ud = hd(); + function ld(t) { + ud.call(this, t), (this.enc = 'pem'); + } + yB(ld, ud); + Xy.exports = ld; + ld.prototype.decode = function (e, r) { + let o = e.toString().split(/[\r\n]+/g), + f = r.label.toUpperCase(), + p = /^-----(BEGIN|END) ([^-]+)-----$/, + m2 = -1, + y3 = -1; + for (let S = 0; S < o.length; S++) { + let E2 = o[S].match(p); + if (E2 !== null && E2[2] === f) + if (m2 === -1) { + if (E2[1] !== 'BEGIN') break; + m2 = S; + } else { + if (E2[1] !== 'END') break; + y3 = S; + break; + } + } + if (m2 === -1 || y3 === -1) throw new Error('PEM section not found for: ' + f); + let M = o.slice(m2 + 1, y3).join(''); + M.replace(/[^a-z0-9+/=]+/gi, ''); + let x = wB.from(M, 'base64'); + return ud.prototype.decode.call(this, x, r); + }; + }); + dd = T2(e3 => { + var Qy = e3; + Qy.der = hd(); + Qy.pem = Jy(); + }); + r3 = T2(t3 => { + var MB = od(), + _B = dd(), + xB = Ie(), + SB = t3; + SB.define = function (e, r) { + return new jf(e, r); + }; + function jf(t, e) { + (this.name = t), (this.body = e), (this.decoders = {}), (this.encoders = {}); + } + jf.prototype._createNamed = function (e) { + let r = this.name; + function o(f) { + this._initNamed(f, r); + } + return ( + xB(o, e), + (o.prototype._initNamed = function (p, m2) { + e.call(this, p, m2); + }), + new o(this) + ); + }; + jf.prototype._getDecoder = function (e) { + return (e = e || 'der'), this.decoders.hasOwnProperty(e) || (this.decoders[e] = this._createNamed(_B[e])), this.decoders[e]; + }; + jf.prototype.decode = function (e, r, o) { + return this._getDecoder(r).decode(e, o); + }; + jf.prototype._getEncoder = function (e) { + return (e = e || 'der'), this.encoders.hasOwnProperty(e) || (this.encoders[e] = this._createNamed(MB[e])), this.encoders[e]; + }; + jf.prototype.encode = function (e, r, o) { + return this._getEncoder(r).encode(e, o); + }; + }); + n3 = T2(i3 => { + var p0 = i3; + p0.Reporter = u0().Reporter; + p0.DecoderBuffer = Kf().DecoderBuffer; + p0.EncoderBuffer = Kf().EncoderBuffer; + p0.Node = d0(); + }); + o3 = T2(a3 => { + var f3 = a3; + f3._reverse = function (e) { + let r = {}; + return ( + Object.keys(e).forEach(function (o) { + (o | 0) == o && (o = o | 0); + let f = e[o]; + r[f] = o; + }), + r + ); + }; + f3.der = c0(); + }); + cd = T2(s3 => { + var Zf = s3; + Zf.bignum = td(); + Zf.define = r3().define; + Zf.base = n3(); + Zf.constants = o3(); + Zf.decoders = dd(); + Zf.encoders = od(); + }); + d3 = T2((lL, l3) => { + var zr = cd(), + h3 = zr.define('Time', function () { + this.choice({utcTime: this.utctime(), generalTime: this.gentime()}); + }), + EB = zr.define('AttributeTypeValue', function () { + this.seq().obj(this.key('type').objid(), this.key('value').any()); + }), + pd = zr.define('AlgorithmIdentifier', function () { + this.seq().obj(this.key('algorithm').objid(), this.key('parameters').optional(), this.key('curve').objid().optional()); + }), + AB = zr.define('SubjectPublicKeyInfo', function () { + this.seq().obj(this.key('algorithm').use(pd), this.key('subjectPublicKey').bitstr()); + }), + RB = zr.define('RelativeDistinguishedName', function () { + this.setof(EB); + }), + BB = zr.define('RDNSequence', function () { + this.seqof(RB); + }), + u3 = zr.define('Name', function () { + this.choice({rdnSequence: this.use(BB)}); + }), + qB = zr.define('Validity', function () { + this.seq().obj(this.key('notBefore').use(h3), this.key('notAfter').use(h3)); + }), + IB = zr.define('Extension', function () { + this.seq().obj(this.key('extnID').objid(), this.key('critical').bool().def(false), this.key('extnValue').octstr()); + }), + TB = zr.define('TBSCertificate', function () { + this.seq().obj( + this.key('version').explicit(0).int().optional(), + this.key('serialNumber').int(), + this.key('signature').use(pd), + this.key('issuer').use(u3), + this.key('validity').use(qB), + this.key('subject').use(u3), + this.key('subjectPublicKeyInfo').use(AB), + this.key('issuerUniqueID').implicit(1).bitstr().optional(), + this.key('subjectUniqueID').implicit(2).bitstr().optional(), + this.key('extensions').explicit(3).seqof(IB).optional() + ); + }), + kB = zr.define('X509Certificate', function () { + this.seq().obj(this.key('tbsCertificate').use(TB), this.key('signatureAlgorithm').use(pd), this.key('signatureValue').bitstr()); + }); + l3.exports = kB; + }); + p3 = T2(Wr => { + var Hr = cd(); + Wr.certificate = d3(); + var LB = Hr.define('RSAPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('modulus').int(), + this.key('publicExponent').int(), + this.key('privateExponent').int(), + this.key('prime1').int(), + this.key('prime2').int(), + this.key('exponent1').int(), + this.key('exponent2').int(), + this.key('coefficient').int() + ); + }); + Wr.RSAPrivateKey = LB; + var NB = Hr.define('RSAPublicKey', function () { + this.seq().obj(this.key('modulus').int(), this.key('publicExponent').int()); + }); + Wr.RSAPublicKey = NB; + var DB = Hr.define('SubjectPublicKeyInfo', function () { + this.seq().obj(this.key('algorithm').use(c3), this.key('subjectPublicKey').bitstr()); + }); + Wr.PublicKey = DB; + var c3 = Hr.define('AlgorithmIdentifier', function () { + this.seq().obj(this.key('algorithm').objid(), this.key('none').null_().optional(), this.key('curve').objid().optional(), this.key('params').seq().obj(this.key('p').int(), this.key('q').int(), this.key('g').int()).optional()); + }), + PB = Hr.define('PrivateKeyInfo', function () { + this.seq().obj(this.key('version').int(), this.key('algorithm').use(c3), this.key('subjectPrivateKey').octstr()); + }); + Wr.PrivateKey = PB; + var CB = Hr.define('EncryptedPrivateKeyInfo', function () { + this.seq().obj( + this.key('algorithm') + .seq() + .obj( + this.key('id').objid(), + this.key('decrypt') + .seq() + .obj( + this.key('kde') + .seq() + .obj(this.key('id').objid(), this.key('kdeparams').seq().obj(this.key('salt').octstr(), this.key('iters').int())), + this.key('cipher').seq().obj(this.key('algo').objid(), this.key('iv').octstr()) + ) + ), + this.key('subjectPrivateKey').octstr() + ); + }); + Wr.EncryptedPrivateKey = CB; + var OB = Hr.define('DSAPrivateKey', function () { + this.seq().obj(this.key('version').int(), this.key('p').int(), this.key('q').int(), this.key('g').int(), this.key('pub_key').int(), this.key('priv_key').int()); + }); + Wr.DSAPrivateKey = OB; + Wr.DSAparam = Hr.define('DSAparam', function () { + this.int(); + }); + var FB = Hr.define('ECPrivateKey', function () { + this.seq().obj(this.key('version').int(), this.key('privateKey').octstr(), this.key('parameters').optional().explicit(0).use(UB), this.key('publicKey').optional().explicit(1).bitstr()); + }); + Wr.ECPrivateKey = FB; + var UB = Hr.define('ECParameters', function () { + this.choice({namedCurve: this.objid()}); + }); + Wr.signature = Hr.define('signature', function () { + this.seq().obj(this.key('r').int(), this.key('s').int()); + }); + }); + v3 = T2((cL, zB) => { + zB.exports = { + '2.16.840.1.101.3.4.1.1': 'aes-128-ecb', + '2.16.840.1.101.3.4.1.2': 'aes-128-cbc', + '2.16.840.1.101.3.4.1.3': 'aes-128-ofb', + '2.16.840.1.101.3.4.1.4': 'aes-128-cfb', + '2.16.840.1.101.3.4.1.21': 'aes-192-ecb', + '2.16.840.1.101.3.4.1.22': 'aes-192-cbc', + '2.16.840.1.101.3.4.1.23': 'aes-192-ofb', + '2.16.840.1.101.3.4.1.24': 'aes-192-cfb', + '2.16.840.1.101.3.4.1.41': 'aes-256-ecb', + '2.16.840.1.101.3.4.1.42': 'aes-256-cbc', + '2.16.840.1.101.3.4.1.43': 'aes-256-ofb', + '2.16.840.1.101.3.4.1.44': 'aes-256-cfb' + }; + }); + m3 = T2((pL, b3) => { + var HB = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m, + WB = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m, + KB = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m, + jB = Ba(), + ZB = Es(), + v0 = Te().Buffer; + b3.exports = function (t, e) { + var r = t.toString(), + o = r.match(HB), + f; + if (o) { + var m2 = 'aes' + o[1], + y3 = v0.from(o[2], 'hex'), + M = v0.from(o[3].replace(/[\r\n]/g, ''), 'base64'), + x = jB(e, y3.slice(0, 8), parseInt(o[1], 10)).key, + S = [], + E2 = ZB.createDecipheriv(m2, x, y3); + S.push(E2.update(M)), S.push(E2.final()), (f = v0.concat(S)); + } else { + var p = r.match(KB); + f = v0.from(p[2].replace(/[\r\n]/g, ''), 'base64'); + } + var B = r.match(WB)[1]; + return {tag: B, data: f}; + }; + }); + Ha = T2((vL, y3) => { + var fr = p3(), + VB = v3(), + $B = m3(), + GB = Es(), + YB = Iu(), + vd = Te().Buffer; + y3.exports = g3; + function g3(t) { + var e; + typeof t == 'object' && !vd.isBuffer(t) && ((e = t.passphrase), (t = t.key)), typeof t == 'string' && (t = vd.from(t)); + var r = $B(t, e), + o = r.tag, + f = r.data, + p, + m2; + switch (o) { + case 'CERTIFICATE': + m2 = fr.certificate.decode(f, 'der').tbsCertificate.subjectPublicKeyInfo; + case 'PUBLIC KEY': + switch ((m2 || (m2 = fr.PublicKey.decode(f, 'der')), (p = m2.algorithm.algorithm.join('.')), p)) { + case '1.2.840.113549.1.1.1': + return fr.RSAPublicKey.decode(m2.subjectPublicKey.data, 'der'); + case '1.2.840.10045.2.1': + return (m2.subjectPrivateKey = m2.subjectPublicKey), {type: 'ec', data: m2}; + case '1.2.840.10040.4.1': + return (m2.algorithm.params.pub_key = fr.DSAparam.decode(m2.subjectPublicKey.data, 'der')), {type: 'dsa', data: m2.algorithm.params}; + default: + throw new Error('unknown key id ' + p); + } + case 'ENCRYPTED PRIVATE KEY': + (f = fr.EncryptedPrivateKey.decode(f, 'der')), (f = XB(f, e)); + case 'PRIVATE KEY': + switch (((m2 = fr.PrivateKey.decode(f, 'der')), (p = m2.algorithm.algorithm.join('.')), p)) { + case '1.2.840.113549.1.1.1': + return fr.RSAPrivateKey.decode(m2.subjectPrivateKey, 'der'); + case '1.2.840.10045.2.1': + return {curve: m2.algorithm.curve, privateKey: fr.ECPrivateKey.decode(m2.subjectPrivateKey, 'der').privateKey}; + case '1.2.840.10040.4.1': + return (m2.algorithm.params.priv_key = fr.DSAparam.decode(m2.subjectPrivateKey, 'der')), {type: 'dsa', params: m2.algorithm.params}; + default: + throw new Error('unknown key id ' + p); + } + case 'RSA PUBLIC KEY': + return fr.RSAPublicKey.decode(f, 'der'); + case 'RSA PRIVATE KEY': + return fr.RSAPrivateKey.decode(f, 'der'); + case 'DSA PRIVATE KEY': + return {type: 'dsa', params: fr.DSAPrivateKey.decode(f, 'der')}; + case 'EC PRIVATE KEY': + return (f = fr.ECPrivateKey.decode(f, 'der')), {curve: f.parameters.value, privateKey: f.privateKey}; + default: + throw new Error('unknown key type ' + o); + } + } + g3.signature = fr.signature; + function XB(t, e) { + var r = t.algorithm.decrypt.kde.kdeparams.salt, + o = parseInt(t.algorithm.decrypt.kde.kdeparams.iters.toString(), 10), + f = VB[t.algorithm.decrypt.cipher.algo.join('.')], + p = t.algorithm.decrypt.cipher.iv, + m2 = t.subjectPrivateKey, + y4 = parseInt(f.split('-')[1], 10) / 8, + M = YB.pbkdf2Sync(e, r, o, y4, 'sha1'), + x = GB.createDecipheriv(f, M, p), + S = []; + return S.push(x.update(m2)), S.push(x.final()), vd.concat(S); + } + }); + bd = T2((bL, JB) => { + JB.exports = {'1.3.132.0.10': 'secp256k1', '1.3.132.0.33': 'p224', '1.2.840.10045.3.1.1': 'p192', '1.2.840.10045.3.1.7': 'p256', '1.3.132.0.34': 'p384', '1.3.132.0.35': 'p521'}; + }); + _3 = T2((mL, m0) => { + var Yt = Te().Buffer, + Kn = wu(), + QB = Ks(), + eq = o0().ec, + b0 = Ws(), + tq = Ha(), + rq = bd(); + function iq(t, e, r, o, f) { + var p = tq(e); + if (p.curve) { + if (o !== 'ecdsa' && o !== 'ecdsa/rsa') throw new Error('wrong private key type'); + return nq(t, p); + } else if (p.type === 'dsa') { + if (o !== 'dsa') throw new Error('wrong private key type'); + return fq(t, p, r); + } else if (o !== 'rsa' && o !== 'ecdsa/rsa') throw new Error('wrong private key type'); + t = Yt.concat([f, t]); + for (var m2 = p.modulus.byteLength(), y3 = [0, 1]; t.length + y3.length + 1 < m2; ) y3.push(255); + y3.push(0); + for (var M = -1; ++M < t.length; ) y3.push(t[M]); + var x = QB(y3, p); + return x; + } + function nq(t, e) { + var r = rq[e.curve.join('.')]; + if (!r) throw new Error('unknown curve ' + e.curve.join('.')); + var o = new eq(r), + f = o.keyFromPrivate(e.privateKey), + p = f.sign(t); + return Yt.from(p.toDER()); + } + function fq(t, e, r) { + for (var o = e.params.priv_key, f = e.params.p, p = e.params.q, m2 = e.params.g, y3 = new b0(0), M, x = md(t, p).mod(p), S = false, E2 = w3(o, p, t, r); S === false; ) + (M = M3(p, E2, r)), + (y3 = sq(m2, M, f, p)), + (S = M.invm(p) + .imul(x.add(o.mul(y3))) + .mod(p)), + S.cmpn(0) === 0 && ((S = false), (y3 = new b0(0))); + return aq(y3, S); + } + function aq(t, e) { + (t = t.toArray()), (e = e.toArray()), t[0] & 128 && (t = [0].concat(t)), e[0] & 128 && (e = [0].concat(e)); + var r = t.length + e.length + 4, + o = [48, r, 2, t.length]; + return (o = o.concat(t, [2, e.length], e)), Yt.from(o); + } + function w3(t, e, r, o) { + if (((t = Yt.from(t.toArray())), t.length < e.byteLength())) { + var f = Yt.alloc(e.byteLength() - t.length); + t = Yt.concat([f, t]); + } + var p = r.length, + m2 = oq(r, e), + y3 = Yt.alloc(p); + y3.fill(1); + var M = Yt.alloc(p); + return ( + (M = Kn(o, M) + .update(y3) + .update(Yt.from([0])) + .update(t) + .update(m2) + .digest()), + (y3 = Kn(o, M).update(y3).digest()), + (M = Kn(o, M) + .update(y3) + .update(Yt.from([1])) + .update(t) + .update(m2) + .digest()), + (y3 = Kn(o, M).update(y3).digest()), + {k: M, v: y3} + ); + } + function md(t, e) { + var r = new b0(t), + o = (t.length << 3) - e.bitLength(); + return o > 0 && r.ishrn(o), r; + } + function oq(t, e) { + (t = md(t, e)), (t = t.mod(e)); + var r = Yt.from(t.toArray()); + if (r.length < e.byteLength()) { + var o = Yt.alloc(e.byteLength() - r.length); + r = Yt.concat([o, r]); + } + return r; + } + function M3(t, e, r) { + var o, f; + do { + for (o = Yt.alloc(0); o.length * 8 < t.bitLength(); ) (e.v = Kn(r, e.k).update(e.v).digest()), (o = Yt.concat([o, e.v])); + (f = md(o, t)), + (e.k = Kn(r, e.k) + .update(e.v) + .update(Yt.from([0])) + .digest()), + (e.v = Kn(r, e.k).update(e.v).digest()); + } while (f.cmp(t) !== -1); + return f; + } + function sq(t, e, r, o) { + return t.toRed(b0.mont(r)).redPow(e).fromRed().mod(o); + } + m0.exports = iq; + m0.exports.getKey = w3; + m0.exports.makeKey = M3; + }); + A3 = T2((gL, E3) => { + var gd = Te().Buffer, + Wa = Ws(), + hq = o0().ec, + S3 = Ha(), + uq = bd(); + function lq(t, e, r, o, f) { + var p = S3(r); + if (p.type === 'ec') { + if (o !== 'ecdsa' && o !== 'ecdsa/rsa') throw new Error('wrong public key type'); + return dq(t, e, p); + } else if (p.type === 'dsa') { + if (o !== 'dsa') throw new Error('wrong public key type'); + return cq(t, e, p); + } else if (o !== 'rsa' && o !== 'ecdsa/rsa') throw new Error('wrong public key type'); + e = gd.concat([f, e]); + for (var m2 = p.modulus.byteLength(), y3 = [1], M = 0; e.length + y3.length + 2 < m2; ) y3.push(255), M++; + y3.push(0); + for (var x = -1; ++x < e.length; ) y3.push(e[x]); + y3 = gd.from(y3); + var S = Wa.mont(p.modulus); + (t = new Wa(t).toRed(S)), (t = t.redPow(new Wa(p.publicExponent))), (t = gd.from(t.fromRed().toArray())); + var E2 = M < 8 ? 1 : 0; + for (m2 = Math.min(t.length, y3.length), t.length !== y3.length && (E2 = 1), x = -1; ++x < m2; ) E2 |= t[x] ^ y3[x]; + return E2 === 0; + } + function dq(t, e, r) { + var o = uq[r.data.algorithm.curve.join('.')]; + if (!o) throw new Error('unknown curve ' + r.data.algorithm.curve.join('.')); + var f = new hq(o), + p = r.data.subjectPrivateKey.data; + return f.verify(e, t, p); + } + function cq(t, e, r) { + var o = r.data.p, + f = r.data.q, + p = r.data.g, + m2 = r.data.pub_key, + y3 = S3.signature.decode(t, 'der'), + M = y3.s, + x = y3.r; + x3(M, f), x3(x, f); + var S = Wa.mont(o), + E2 = M.invm(f), + B = p + .toRed(S) + .redPow(new Wa(e).mul(E2).mod(f)) + .fromRed() + .mul(m2.toRed(S).redPow(x.mul(E2).mod(f)).fromRed()) + .mod(o) + .mod(f); + return B.cmp(x) === 0; + } + function x3(t, e) { + if (t.cmpn(0) <= 0) throw new Error('invalid sig'); + if (t.cmp(e) >= e) throw new Error('invalid sig'); + } + E3.exports = lq; + }); + k3 = T2((yL, T3) => { + var g0 = Te().Buffer, + q3 = bf(), + y0 = i2(), + I3 = Ie(), + pq = _3(), + vq = A3(), + jn = Mu(); + Object.keys(jn).forEach(function (t) { + (jn[t].id = g0.from(jn[t].id, 'hex')), (jn[t.toLowerCase()] = jn[t]); + }); + function Ka(t) { + y0.Writable.call(this); + var e = jn[t]; + if (!e) throw new Error('Unknown message digest'); + (this._hashType = e.hash), (this._hash = q3(e.hash)), (this._tag = e.id), (this._signType = e.sign); + } + I3(Ka, y0.Writable); + Ka.prototype._write = function (e, r, o) { + this._hash.update(e), o(); + }; + Ka.prototype.update = function (e, r) { + return typeof e == 'string' && (e = g0.from(e, r)), this._hash.update(e), this; + }; + Ka.prototype.sign = function (e, r) { + this.end(); + var o = this._hash.digest(), + f = pq(o, e, this._hashType, this._signType, this._tag); + return r ? f.toString(r) : f; + }; + function ja(t) { + y0.Writable.call(this); + var e = jn[t]; + if (!e) throw new Error('Unknown message digest'); + (this._hash = q3(e.hash)), (this._tag = e.id), (this._signType = e.sign); + } + I3(ja, y0.Writable); + ja.prototype._write = function (e, r, o) { + this._hash.update(e), o(); + }; + ja.prototype.update = function (e, r) { + return typeof e == 'string' && (e = g0.from(e, r)), this._hash.update(e), this; + }; + ja.prototype.verify = function (e, r, o) { + typeof r == 'string' && (r = g0.from(r, o)), this.end(); + var f = this._hash.digest(); + return vq(r, f, e, this._signType, this._tag); + }; + function R3(t) { + return new Ka(t); + } + function B3(t) { + return new ja(t); + } + T3.exports = {Sign: R3, Verify: B3, createSign: R3, createVerify: B3}; + }); + N3 = T2((L3, yd) => { + (function (t, e) { + function r(v, i) { + if (!v) throw new Error(i || 'Assertion failed'); + } + function o(v, i) { + v.super_ = i; + var a = function () {}; + (a.prototype = i.prototype), (v.prototype = new a()), (v.prototype.constructor = v); + } + function f(v, i, a) { + if (f.isBN(v)) return v; + (this.negative = 0), (this.words = null), (this.length = 0), (this.red = null), v !== null && ((i === 'le' || i === 'be') && ((a = i), (i = 10)), this._init(v || 0, i || 10, a || 'be')); + } + typeof t == 'object' ? (t.exports = f) : (e.BN = f), (f.BN = f), (f.wordSize = 26); + var p; + try { + typeof window < 'u' && typeof window.Buffer < 'u' ? (p = window.Buffer) : (p = ji().Buffer); + } catch {} + (f.isBN = function (i) { + return i instanceof f ? true : i !== null && typeof i == 'object' && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }), + (f.max = function (i, a) { + return i.cmp(a) > 0 ? i : a; + }), + (f.min = function (i, a) { + return i.cmp(a) < 0 ? i : a; + }), + (f.prototype._init = function (i, a, h2) { + if (typeof i == 'number') return this._initNumber(i, a, h2); + if (typeof i == 'object') return this._initArray(i, a, h2); + a === 'hex' && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), (i = i.toString().replace(/\s+/g, '')); + var s = 0; + i[0] === '-' && (s++, (this.negative = 1)), s < i.length && (a === 16 ? this._parseHex(i, s, h2) : (this._parseBase(i, a, s), h2 === 'le' && this._initArray(this.toArray(), a, h2))); + }), + (f.prototype._initNumber = function (i, a, h2) { + i < 0 && ((this.negative = 1), (i = -i)), + i < 67108864 + ? ((this.words = [i & 67108863]), (this.length = 1)) + : i < 4503599627370496 + ? ((this.words = [i & 67108863, (i / 67108864) & 67108863]), (this.length = 2)) + : (r(i < 9007199254740992), (this.words = [i & 67108863, (i / 67108864) & 67108863, 1]), (this.length = 3)), + h2 === 'le' && this._initArray(this.toArray(), a, h2); + }), + (f.prototype._initArray = function (i, a, h2) { + if ((r(typeof i.length == 'number'), i.length <= 0)) return (this.words = [0]), (this.length = 1), this; + (this.length = Math.ceil(i.length / 3)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u, + c, + b3 = 0; + if (h2 === 'be') + for (s = i.length - 1, u = 0; s >= 0; s -= 3) + (c = i[s] | (i[s - 1] << 8) | (i[s - 2] << 16)), (this.words[u] |= (c << b3) & 67108863), (this.words[u + 1] = (c >>> (26 - b3)) & 67108863), (b3 += 24), b3 >= 26 && ((b3 -= 26), u++); + else if (h2 === 'le') + for (s = 0, u = 0; s < i.length; s += 3) (c = i[s] | (i[s + 1] << 8) | (i[s + 2] << 16)), (this.words[u] |= (c << b3) & 67108863), (this.words[u + 1] = (c >>> (26 - b3)) & 67108863), (b3 += 24), b3 >= 26 && ((b3 -= 26), u++); + return this.strip(); + }); + function m2(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : (a - 48) & 15; + } + function y3(v, i, a) { + var h2 = m2(v, a); + return a - 1 >= i && (h2 |= m2(v, a - 1) << 4), h2; + } + f.prototype._parseHex = function (i, a, h2) { + (this.length = Math.ceil((i.length - a) / 6)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u = 0, + c = 0, + b3; + if (h2 === 'be') for (s = i.length - 1; s >= a; s -= 2) (b3 = y3(i, a, s) << u), (this.words[c] |= b3 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b3 >>> 26)) : (u += 8); + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a; s < i.length; s += 2) (b3 = y3(i, a, s) << u), (this.words[c] |= b3 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b3 >>> 26)) : (u += 8); + } + this.strip(); + }; + function M(v, i, a, h2) { + for (var s = 0, u = Math.min(v.length, a), c = i; c < u; c++) { + var b3 = v.charCodeAt(c) - 48; + (s *= h2), b3 >= 49 ? (s += b3 - 49 + 10) : b3 >= 17 ? (s += b3 - 17 + 10) : (s += b3); + } + return s; + } + (f.prototype._parseBase = function (i, a, h2) { + (this.words = [0]), (this.length = 1); + for (var s = 0, u = 1; u <= 67108863; u *= a) s++; + s--, (u = (u / a) | 0); + for (var c = i.length - h2, b3 = c % s, l = Math.min(c, c - b3) + h2, n = 0, d = h2; d < l; d += s) (n = M(i, d, d + s, a)), this.imuln(u), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + if (b3 !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0; d < b3; d++) w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + } + this.strip(); + }), + (f.prototype.copy = function (i) { + i.words = new Array(this.length); + for (var a = 0; a < this.length; a++) i.words[a] = this.words[a]; + (i.length = this.length), (i.negative = this.negative), (i.red = this.red); + }), + (f.prototype.clone = function () { + var i = new f(null); + return this.copy(i), i; + }), + (f.prototype._expand = function (i) { + for (; this.length < i; ) this.words[this.length++] = 0; + return this; + }), + (f.prototype.strip = function () { + for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; + return this._normSign(); + }), + (f.prototype._normSign = function () { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }), + (f.prototype.inspect = function () { + return (this.red ? ''; + }); + var x = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ], + S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + E2 = [ + 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, + 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + (f.prototype.toString = function (i, a) { + (i = i || 10), (a = a | 0 || 1); + var h2; + if (i === 16 || i === 'hex') { + h2 = ''; + for (var s = 0, u = 0, c = 0; c < this.length; c++) { + var b3 = this.words[c], + l = (((b3 << s) | u) & 16777215).toString(16); + (u = (b3 >>> (24 - s)) & 16777215), u !== 0 || c !== this.length - 1 ? (h2 = x[6 - l.length] + l + h2) : (h2 = l + h2), (s += 2), s >= 26 && ((s -= 26), c--); + } + for (u !== 0 && (h2 = u.toString(16) + h2); h2.length % a !== 0; ) h2 = '0' + h2; + return this.negative !== 0 && (h2 = '-' + h2), h2; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], + d = E2[i]; + h2 = ''; + var w = this.clone(); + for (w.negative = 0; !w.isZero(); ) { + var g = w.modn(d).toString(i); + (w = w.idivn(d)), w.isZero() ? (h2 = g + h2) : (h2 = x[n - g.length] + g + h2); + } + for (this.isZero() && (h2 = '0' + h2); h2.length % a !== 0; ) h2 = '0' + h2; + return this.negative !== 0 && (h2 = '-' + h2), h2; + } + r(false, 'Base should be between 2 and 36'); + }), + (f.prototype.toNumber = function () { + var i = this.words[0]; + return ( + this.length === 2 ? (i += this.words[1] * 67108864) : this.length === 3 && this.words[2] === 1 ? (i += 4503599627370496 + this.words[1] * 67108864) : this.length > 2 && r(false, 'Number can only safely store up to 53 bits'), + this.negative !== 0 ? -i : i + ); + }), + (f.prototype.toJSON = function () { + return this.toString(16); + }), + (f.prototype.toBuffer = function (i, a) { + return r(typeof p < 'u'), this.toArrayLike(p, i, a); + }), + (f.prototype.toArray = function (i, a) { + return this.toArrayLike(Array, i, a); + }), + (f.prototype.toArrayLike = function (i, a, h2) { + var s = this.byteLength(), + u = h2 || Math.max(1, s); + r(s <= u, 'byte array longer than desired length'), r(u > 0, 'Requested array length <= 0'), this.strip(); + var c = a === 'le', + b3 = new i(u), + l, + n, + d = this.clone(); + if (c) { + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b3[n] = l); + for (; n < u; n++) b3[n] = 0; + } else { + for (n = 0; n < u - s; n++) b3[n] = 0; + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b3[u - n - 1] = l); + } + return b3; + }), + Math.clz32 + ? (f.prototype._countBits = function (i) { + return 32 - Math.clz32(i); + }) + : (f.prototype._countBits = function (i) { + var a = i, + h2 = 0; + return a >= 4096 && ((h2 += 13), (a >>>= 13)), a >= 64 && ((h2 += 7), (a >>>= 7)), a >= 8 && ((h2 += 4), (a >>>= 4)), a >= 2 && ((h2 += 2), (a >>>= 2)), h2 + a; + }), + (f.prototype._zeroBits = function (i) { + if (i === 0) return 26; + var a = i, + h2 = 0; + return (a & 8191) === 0 && ((h2 += 13), (a >>>= 13)), (a & 127) === 0 && ((h2 += 7), (a >>>= 7)), (a & 15) === 0 && ((h2 += 4), (a >>>= 4)), (a & 3) === 0 && ((h2 += 2), (a >>>= 2)), (a & 1) === 0 && h2++, h2; + }), + (f.prototype.bitLength = function () { + var i = this.words[this.length - 1], + a = this._countBits(i); + return (this.length - 1) * 26 + a; + }); + function B(v) { + for (var i = new Array(v.bitLength()), a = 0; a < i.length; a++) { + var h2 = (a / 26) | 0, + s = a % 26; + i[a] = (v.words[h2] & (1 << s)) >>> s; + } + return i; + } + (f.prototype.zeroBits = function () { + if (this.isZero()) return 0; + for (var i = 0, a = 0; a < this.length; a++) { + var h2 = this._zeroBits(this.words[a]); + if (((i += h2), h2 !== 26)) break; + } + return i; + }), + (f.prototype.byteLength = function () { + return Math.ceil(this.bitLength() / 8); + }), + (f.prototype.toTwos = function (i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }), + (f.prototype.fromTwos = function (i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }), + (f.prototype.isNeg = function () { + return this.negative !== 0; + }), + (f.prototype.neg = function () { + return this.clone().ineg(); + }), + (f.prototype.ineg = function () { + return this.isZero() || (this.negative ^= 1), this; + }), + (f.prototype.iuor = function (i) { + for (; this.length < i.length; ) this.words[this.length++] = 0; + for (var a = 0; a < i.length; a++) this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }), + (f.prototype.ior = function (i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }), + (f.prototype.or = function (i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }), + (f.prototype.uor = function (i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }), + (f.prototype.iuand = function (i) { + var a; + this.length > i.length ? (a = i) : (a = this); + for (var h2 = 0; h2 < a.length; h2++) this.words[h2] = this.words[h2] & i.words[h2]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.iand = function (i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }), + (f.prototype.and = function (i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }), + (f.prototype.uand = function (i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }), + (f.prototype.iuxor = function (i) { + var a, h2; + this.length > i.length ? ((a = this), (h2 = i)) : ((a = i), (h2 = this)); + for (var s = 0; s < h2.length; s++) this.words[s] = a.words[s] ^ h2.words[s]; + if (this !== a) for (; s < a.length; s++) this.words[s] = a.words[s]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.ixor = function (i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }), + (f.prototype.xor = function (i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }), + (f.prototype.uxor = function (i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }), + (f.prototype.inotn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = Math.ceil(i / 26) | 0, + h2 = i % 26; + this._expand(a), h2 > 0 && a--; + for (var s = 0; s < a; s++) this.words[s] = ~this.words[s] & 67108863; + return h2 > 0 && (this.words[s] = ~this.words[s] & (67108863 >> (26 - h2))), this.strip(); + }), + (f.prototype.notn = function (i) { + return this.clone().inotn(i); + }), + (f.prototype.setn = function (i, a) { + r(typeof i == 'number' && i >= 0); + var h2 = (i / 26) | 0, + s = i % 26; + return this._expand(h2 + 1), a ? (this.words[h2] = this.words[h2] | (1 << s)) : (this.words[h2] = this.words[h2] & ~(1 << s)), this.strip(); + }), + (f.prototype.iadd = function (i) { + var a; + if (this.negative !== 0 && i.negative === 0) return (this.negative = 0), (a = this.isub(i)), (this.negative ^= 1), this._normSign(); + if (this.negative === 0 && i.negative !== 0) return (i.negative = 0), (a = this.isub(i)), (i.negative = 1), a._normSign(); + var h2, s; + this.length > i.length ? ((h2 = this), (s = i)) : ((h2 = i), (s = this)); + for (var u = 0, c = 0; c < s.length; c++) (a = (h2.words[c] | 0) + (s.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + for (; u !== 0 && c < h2.length; c++) (a = (h2.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + if (((this.length = h2.length), u !== 0)) (this.words[this.length] = u), this.length++; + else if (h2 !== this) for (; c < h2.length; c++) this.words[c] = h2.words[c]; + return this; + }), + (f.prototype.add = function (i) { + var a; + return i.negative !== 0 && this.negative === 0 + ? ((i.negative = 0), (a = this.sub(i)), (i.negative ^= 1), a) + : i.negative === 0 && this.negative !== 0 + ? ((this.negative = 0), (a = i.sub(this)), (this.negative = 1), a) + : this.length > i.length + ? this.clone().iadd(i) + : i.clone().iadd(this); + }), + (f.prototype.isub = function (i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return (i.negative = 1), a._normSign(); + } else if (this.negative !== 0) return (this.negative = 0), this.iadd(i), (this.negative = 1), this._normSign(); + var h2 = this.cmp(i); + if (h2 === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; + var s, u; + h2 > 0 ? ((s = this), (u = i)) : ((s = i), (u = this)); + for (var c = 0, b3 = 0; b3 < u.length; b3++) (a = (s.words[b3] | 0) - (u.words[b3] | 0) + c), (c = a >> 26), (this.words[b3] = a & 67108863); + for (; c !== 0 && b3 < s.length; b3++) (a = (s.words[b3] | 0) + c), (c = a >> 26), (this.words[b3] = a & 67108863); + if (c === 0 && b3 < s.length && s !== this) for (; b3 < s.length; b3++) this.words[b3] = s.words[b3]; + return (this.length = Math.max(this.length, b3)), s !== this && (this.negative = 1), this.strip(); + }), + (f.prototype.sub = function (i) { + return this.clone().isub(i); + }); + function q2(v, i, a) { + a.negative = i.negative ^ v.negative; + var h2 = (v.length + i.length) | 0; + (a.length = h2), (h2 = (h2 - 1) | 0); + var s = v.words[0] | 0, + u = i.words[0] | 0, + c = s * u, + b3 = c & 67108863, + l = (c / 67108864) | 0; + a.words[0] = b3; + for (var n = 1; n < h2; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _4 = Math.max(0, n - v.length + 1); _4 <= g; _4++) { + var A2 = (n - _4) | 0; + (s = v.words[A2] | 0), (u = i.words[_4] | 0), (c = s * u + w), (d += (c / 67108864) | 0), (w = c & 67108863); + } + (a.words[n] = w | 0), (l = d | 0); + } + return l !== 0 ? (a.words[n] = l | 0) : a.length--, a.strip(); + } + var L2 = function (i, a, h2) { + var s = i.words, + u = a.words, + c = h2.words, + b3 = 0, + l, + n, + d, + w = s[0] | 0, + g = w & 8191, + _4 = w >>> 13, + A2 = s[1] | 0, + R2 = A2 & 8191, + I = A2 >>> 13, + Me = s[2] | 0, + k = Me & 8191, + D2 = Me >>> 13, + nt = s[3] | 0, + C2 = nt & 8191, + O = nt >>> 13, + vt = s[4] | 0, + F = vt & 8191, + U = vt >>> 13, + bt = s[5] | 0, + z2 = bt & 8191, + H = bt >>> 13, + mt = s[6] | 0, + W = mt & 8191, + K = mt >>> 13, + gt = s[7] | 0, + j = gt & 8191, + Z = gt >>> 13, + yt = s[8] | 0, + V = yt & 8191, + $2 = yt >>> 13, + wt = s[9] | 0, + G = wt & 8191, + Y = wt >>> 13, + Mt = u[0] | 0, + X = Mt & 8191, + J = Mt >>> 13, + _t = u[1] | 0, + Q = _t & 8191, + ee = _t >>> 13, + xt = u[2] | 0, + te = xt & 8191, + re = xt >>> 13, + St = u[3] | 0, + ie = St & 8191, + ne = St >>> 13, + Et = u[4] | 0, + fe = Et & 8191, + ae = Et >>> 13, + At = u[5] | 0, + oe = At & 8191, + se = At >>> 13, + Rt = u[6] | 0, + he = Rt & 8191, + ue = Rt >>> 13, + Bt = u[7] | 0, + le = Bt & 8191, + de = Bt >>> 13, + qt = u[8] | 0, + ce = qt & 8191, + pe = qt >>> 13, + It = u[9] | 0, + ve = It & 8191, + be = It >>> 13; + (h2.negative = i.negative ^ a.negative), (h2.length = 19), (l = Math.imul(g, X)), (n = Math.imul(g, J)), (n = (n + Math.imul(_4, X)) | 0), (d = Math.imul(_4, J)); + var ft = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (ft >>> 26)) | 0), + (ft &= 67108863), + (l = Math.imul(R2, X)), + (n = Math.imul(R2, J)), + (n = (n + Math.imul(I, X)) | 0), + (d = Math.imul(I, J)), + (l = (l + Math.imul(g, Q)) | 0), + (n = (n + Math.imul(g, ee)) | 0), + (n = (n + Math.imul(_4, Q)) | 0), + (d = (d + Math.imul(_4, ee)) | 0); + var Be = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Be >>> 26)) | 0), + (Be &= 67108863), + (l = Math.imul(k, X)), + (n = Math.imul(k, J)), + (n = (n + Math.imul(D2, X)) | 0), + (d = Math.imul(D2, J)), + (l = (l + Math.imul(R2, Q)) | 0), + (n = (n + Math.imul(R2, ee)) | 0), + (n = (n + Math.imul(I, Q)) | 0), + (d = (d + Math.imul(I, ee)) | 0), + (l = (l + Math.imul(g, te)) | 0), + (n = (n + Math.imul(g, re)) | 0), + (n = (n + Math.imul(_4, te)) | 0), + (d = (d + Math.imul(_4, re)) | 0); + var qe = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (qe >>> 26)) | 0), + (qe &= 67108863), + (l = Math.imul(C2, X)), + (n = Math.imul(C2, J)), + (n = (n + Math.imul(O, X)) | 0), + (d = Math.imul(O, J)), + (l = (l + Math.imul(k, Q)) | 0), + (n = (n + Math.imul(k, ee)) | 0), + (n = (n + Math.imul(D2, Q)) | 0), + (d = (d + Math.imul(D2, ee)) | 0), + (l = (l + Math.imul(R2, te)) | 0), + (n = (n + Math.imul(R2, re)) | 0), + (n = (n + Math.imul(I, te)) | 0), + (d = (d + Math.imul(I, re)) | 0), + (l = (l + Math.imul(g, ie)) | 0), + (n = (n + Math.imul(g, ne)) | 0), + (n = (n + Math.imul(_4, ie)) | 0), + (d = (d + Math.imul(_4, ne)) | 0); + var ze = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (ze >>> 26)) | 0), + (ze &= 67108863), + (l = Math.imul(F, X)), + (n = Math.imul(F, J)), + (n = (n + Math.imul(U, X)) | 0), + (d = Math.imul(U, J)), + (l = (l + Math.imul(C2, Q)) | 0), + (n = (n + Math.imul(C2, ee)) | 0), + (n = (n + Math.imul(O, Q)) | 0), + (d = (d + Math.imul(O, ee)) | 0), + (l = (l + Math.imul(k, te)) | 0), + (n = (n + Math.imul(k, re)) | 0), + (n = (n + Math.imul(D2, te)) | 0), + (d = (d + Math.imul(D2, re)) | 0), + (l = (l + Math.imul(R2, ie)) | 0), + (n = (n + Math.imul(R2, ne)) | 0), + (n = (n + Math.imul(I, ie)) | 0), + (d = (d + Math.imul(I, ne)) | 0), + (l = (l + Math.imul(g, fe)) | 0), + (n = (n + Math.imul(g, ae)) | 0), + (n = (n + Math.imul(_4, fe)) | 0), + (d = (d + Math.imul(_4, ae)) | 0); + var He = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (He >>> 26)) | 0), + (He &= 67108863), + (l = Math.imul(z2, X)), + (n = Math.imul(z2, J)), + (n = (n + Math.imul(H, X)) | 0), + (d = Math.imul(H, J)), + (l = (l + Math.imul(F, Q)) | 0), + (n = (n + Math.imul(F, ee)) | 0), + (n = (n + Math.imul(U, Q)) | 0), + (d = (d + Math.imul(U, ee)) | 0), + (l = (l + Math.imul(C2, te)) | 0), + (n = (n + Math.imul(C2, re)) | 0), + (n = (n + Math.imul(O, te)) | 0), + (d = (d + Math.imul(O, re)) | 0), + (l = (l + Math.imul(k, ie)) | 0), + (n = (n + Math.imul(k, ne)) | 0), + (n = (n + Math.imul(D2, ie)) | 0), + (d = (d + Math.imul(D2, ne)) | 0), + (l = (l + Math.imul(R2, fe)) | 0), + (n = (n + Math.imul(R2, ae)) | 0), + (n = (n + Math.imul(I, fe)) | 0), + (d = (d + Math.imul(I, ae)) | 0), + (l = (l + Math.imul(g, oe)) | 0), + (n = (n + Math.imul(g, se)) | 0), + (n = (n + Math.imul(_4, oe)) | 0), + (d = (d + Math.imul(_4, se)) | 0); + var We = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (We >>> 26)) | 0), + (We &= 67108863), + (l = Math.imul(W, X)), + (n = Math.imul(W, J)), + (n = (n + Math.imul(K, X)) | 0), + (d = Math.imul(K, J)), + (l = (l + Math.imul(z2, Q)) | 0), + (n = (n + Math.imul(z2, ee)) | 0), + (n = (n + Math.imul(H, Q)) | 0), + (d = (d + Math.imul(H, ee)) | 0), + (l = (l + Math.imul(F, te)) | 0), + (n = (n + Math.imul(F, re)) | 0), + (n = (n + Math.imul(U, te)) | 0), + (d = (d + Math.imul(U, re)) | 0), + (l = (l + Math.imul(C2, ie)) | 0), + (n = (n + Math.imul(C2, ne)) | 0), + (n = (n + Math.imul(O, ie)) | 0), + (d = (d + Math.imul(O, ne)) | 0), + (l = (l + Math.imul(k, fe)) | 0), + (n = (n + Math.imul(k, ae)) | 0), + (n = (n + Math.imul(D2, fe)) | 0), + (d = (d + Math.imul(D2, ae)) | 0), + (l = (l + Math.imul(R2, oe)) | 0), + (n = (n + Math.imul(R2, se)) | 0), + (n = (n + Math.imul(I, oe)) | 0), + (d = (d + Math.imul(I, se)) | 0), + (l = (l + Math.imul(g, he)) | 0), + (n = (n + Math.imul(g, ue)) | 0), + (n = (n + Math.imul(_4, he)) | 0), + (d = (d + Math.imul(_4, ue)) | 0); + var Ke = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ke >>> 26)) | 0), + (Ke &= 67108863), + (l = Math.imul(j, X)), + (n = Math.imul(j, J)), + (n = (n + Math.imul(Z, X)) | 0), + (d = Math.imul(Z, J)), + (l = (l + Math.imul(W, Q)) | 0), + (n = (n + Math.imul(W, ee)) | 0), + (n = (n + Math.imul(K, Q)) | 0), + (d = (d + Math.imul(K, ee)) | 0), + (l = (l + Math.imul(z2, te)) | 0), + (n = (n + Math.imul(z2, re)) | 0), + (n = (n + Math.imul(H, te)) | 0), + (d = (d + Math.imul(H, re)) | 0), + (l = (l + Math.imul(F, ie)) | 0), + (n = (n + Math.imul(F, ne)) | 0), + (n = (n + Math.imul(U, ie)) | 0), + (d = (d + Math.imul(U, ne)) | 0), + (l = (l + Math.imul(C2, fe)) | 0), + (n = (n + Math.imul(C2, ae)) | 0), + (n = (n + Math.imul(O, fe)) | 0), + (d = (d + Math.imul(O, ae)) | 0), + (l = (l + Math.imul(k, oe)) | 0), + (n = (n + Math.imul(k, se)) | 0), + (n = (n + Math.imul(D2, oe)) | 0), + (d = (d + Math.imul(D2, se)) | 0), + (l = (l + Math.imul(R2, he)) | 0), + (n = (n + Math.imul(R2, ue)) | 0), + (n = (n + Math.imul(I, he)) | 0), + (d = (d + Math.imul(I, ue)) | 0), + (l = (l + Math.imul(g, le)) | 0), + (n = (n + Math.imul(g, de)) | 0), + (n = (n + Math.imul(_4, le)) | 0), + (d = (d + Math.imul(_4, de)) | 0); + var je = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (je >>> 26)) | 0), + (je &= 67108863), + (l = Math.imul(V, X)), + (n = Math.imul(V, J)), + (n = (n + Math.imul($2, X)) | 0), + (d = Math.imul($2, J)), + (l = (l + Math.imul(j, Q)) | 0), + (n = (n + Math.imul(j, ee)) | 0), + (n = (n + Math.imul(Z, Q)) | 0), + (d = (d + Math.imul(Z, ee)) | 0), + (l = (l + Math.imul(W, te)) | 0), + (n = (n + Math.imul(W, re)) | 0), + (n = (n + Math.imul(K, te)) | 0), + (d = (d + Math.imul(K, re)) | 0), + (l = (l + Math.imul(z2, ie)) | 0), + (n = (n + Math.imul(z2, ne)) | 0), + (n = (n + Math.imul(H, ie)) | 0), + (d = (d + Math.imul(H, ne)) | 0), + (l = (l + Math.imul(F, fe)) | 0), + (n = (n + Math.imul(F, ae)) | 0), + (n = (n + Math.imul(U, fe)) | 0), + (d = (d + Math.imul(U, ae)) | 0), + (l = (l + Math.imul(C2, oe)) | 0), + (n = (n + Math.imul(C2, se)) | 0), + (n = (n + Math.imul(O, oe)) | 0), + (d = (d + Math.imul(O, se)) | 0), + (l = (l + Math.imul(k, he)) | 0), + (n = (n + Math.imul(k, ue)) | 0), + (n = (n + Math.imul(D2, he)) | 0), + (d = (d + Math.imul(D2, ue)) | 0), + (l = (l + Math.imul(R2, le)) | 0), + (n = (n + Math.imul(R2, de)) | 0), + (n = (n + Math.imul(I, le)) | 0), + (d = (d + Math.imul(I, de)) | 0), + (l = (l + Math.imul(g, ce)) | 0), + (n = (n + Math.imul(g, pe)) | 0), + (n = (n + Math.imul(_4, ce)) | 0), + (d = (d + Math.imul(_4, pe)) | 0); + var Ze = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ze >>> 26)) | 0), + (Ze &= 67108863), + (l = Math.imul(G, X)), + (n = Math.imul(G, J)), + (n = (n + Math.imul(Y, X)) | 0), + (d = Math.imul(Y, J)), + (l = (l + Math.imul(V, Q)) | 0), + (n = (n + Math.imul(V, ee)) | 0), + (n = (n + Math.imul($2, Q)) | 0), + (d = (d + Math.imul($2, ee)) | 0), + (l = (l + Math.imul(j, te)) | 0), + (n = (n + Math.imul(j, re)) | 0), + (n = (n + Math.imul(Z, te)) | 0), + (d = (d + Math.imul(Z, re)) | 0), + (l = (l + Math.imul(W, ie)) | 0), + (n = (n + Math.imul(W, ne)) | 0), + (n = (n + Math.imul(K, ie)) | 0), + (d = (d + Math.imul(K, ne)) | 0), + (l = (l + Math.imul(z2, fe)) | 0), + (n = (n + Math.imul(z2, ae)) | 0), + (n = (n + Math.imul(H, fe)) | 0), + (d = (d + Math.imul(H, ae)) | 0), + (l = (l + Math.imul(F, oe)) | 0), + (n = (n + Math.imul(F, se)) | 0), + (n = (n + Math.imul(U, oe)) | 0), + (d = (d + Math.imul(U, se)) | 0), + (l = (l + Math.imul(C2, he)) | 0), + (n = (n + Math.imul(C2, ue)) | 0), + (n = (n + Math.imul(O, he)) | 0), + (d = (d + Math.imul(O, ue)) | 0), + (l = (l + Math.imul(k, le)) | 0), + (n = (n + Math.imul(k, de)) | 0), + (n = (n + Math.imul(D2, le)) | 0), + (d = (d + Math.imul(D2, de)) | 0), + (l = (l + Math.imul(R2, ce)) | 0), + (n = (n + Math.imul(R2, pe)) | 0), + (n = (n + Math.imul(I, ce)) | 0), + (d = (d + Math.imul(I, pe)) | 0), + (l = (l + Math.imul(g, ve)) | 0), + (n = (n + Math.imul(g, be)) | 0), + (n = (n + Math.imul(_4, ve)) | 0), + (d = (d + Math.imul(_4, be)) | 0); + var Ve = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ve >>> 26)) | 0), + (Ve &= 67108863), + (l = Math.imul(G, Q)), + (n = Math.imul(G, ee)), + (n = (n + Math.imul(Y, Q)) | 0), + (d = Math.imul(Y, ee)), + (l = (l + Math.imul(V, te)) | 0), + (n = (n + Math.imul(V, re)) | 0), + (n = (n + Math.imul($2, te)) | 0), + (d = (d + Math.imul($2, re)) | 0), + (l = (l + Math.imul(j, ie)) | 0), + (n = (n + Math.imul(j, ne)) | 0), + (n = (n + Math.imul(Z, ie)) | 0), + (d = (d + Math.imul(Z, ne)) | 0), + (l = (l + Math.imul(W, fe)) | 0), + (n = (n + Math.imul(W, ae)) | 0), + (n = (n + Math.imul(K, fe)) | 0), + (d = (d + Math.imul(K, ae)) | 0), + (l = (l + Math.imul(z2, oe)) | 0), + (n = (n + Math.imul(z2, se)) | 0), + (n = (n + Math.imul(H, oe)) | 0), + (d = (d + Math.imul(H, se)) | 0), + (l = (l + Math.imul(F, he)) | 0), + (n = (n + Math.imul(F, ue)) | 0), + (n = (n + Math.imul(U, he)) | 0), + (d = (d + Math.imul(U, ue)) | 0), + (l = (l + Math.imul(C2, le)) | 0), + (n = (n + Math.imul(C2, de)) | 0), + (n = (n + Math.imul(O, le)) | 0), + (d = (d + Math.imul(O, de)) | 0), + (l = (l + Math.imul(k, ce)) | 0), + (n = (n + Math.imul(k, pe)) | 0), + (n = (n + Math.imul(D2, ce)) | 0), + (d = (d + Math.imul(D2, pe)) | 0), + (l = (l + Math.imul(R2, ve)) | 0), + (n = (n + Math.imul(R2, be)) | 0), + (n = (n + Math.imul(I, ve)) | 0), + (d = (d + Math.imul(I, be)) | 0); + var $e = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + ($e >>> 26)) | 0), + ($e &= 67108863), + (l = Math.imul(G, te)), + (n = Math.imul(G, re)), + (n = (n + Math.imul(Y, te)) | 0), + (d = Math.imul(Y, re)), + (l = (l + Math.imul(V, ie)) | 0), + (n = (n + Math.imul(V, ne)) | 0), + (n = (n + Math.imul($2, ie)) | 0), + (d = (d + Math.imul($2, ne)) | 0), + (l = (l + Math.imul(j, fe)) | 0), + (n = (n + Math.imul(j, ae)) | 0), + (n = (n + Math.imul(Z, fe)) | 0), + (d = (d + Math.imul(Z, ae)) | 0), + (l = (l + Math.imul(W, oe)) | 0), + (n = (n + Math.imul(W, se)) | 0), + (n = (n + Math.imul(K, oe)) | 0), + (d = (d + Math.imul(K, se)) | 0), + (l = (l + Math.imul(z2, he)) | 0), + (n = (n + Math.imul(z2, ue)) | 0), + (n = (n + Math.imul(H, he)) | 0), + (d = (d + Math.imul(H, ue)) | 0), + (l = (l + Math.imul(F, le)) | 0), + (n = (n + Math.imul(F, de)) | 0), + (n = (n + Math.imul(U, le)) | 0), + (d = (d + Math.imul(U, de)) | 0), + (l = (l + Math.imul(C2, ce)) | 0), + (n = (n + Math.imul(C2, pe)) | 0), + (n = (n + Math.imul(O, ce)) | 0), + (d = (d + Math.imul(O, pe)) | 0), + (l = (l + Math.imul(k, ve)) | 0), + (n = (n + Math.imul(k, be)) | 0), + (n = (n + Math.imul(D2, ve)) | 0), + (d = (d + Math.imul(D2, be)) | 0); + var Ge = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ge >>> 26)) | 0), + (Ge &= 67108863), + (l = Math.imul(G, ie)), + (n = Math.imul(G, ne)), + (n = (n + Math.imul(Y, ie)) | 0), + (d = Math.imul(Y, ne)), + (l = (l + Math.imul(V, fe)) | 0), + (n = (n + Math.imul(V, ae)) | 0), + (n = (n + Math.imul($2, fe)) | 0), + (d = (d + Math.imul($2, ae)) | 0), + (l = (l + Math.imul(j, oe)) | 0), + (n = (n + Math.imul(j, se)) | 0), + (n = (n + Math.imul(Z, oe)) | 0), + (d = (d + Math.imul(Z, se)) | 0), + (l = (l + Math.imul(W, he)) | 0), + (n = (n + Math.imul(W, ue)) | 0), + (n = (n + Math.imul(K, he)) | 0), + (d = (d + Math.imul(K, ue)) | 0), + (l = (l + Math.imul(z2, le)) | 0), + (n = (n + Math.imul(z2, de)) | 0), + (n = (n + Math.imul(H, le)) | 0), + (d = (d + Math.imul(H, de)) | 0), + (l = (l + Math.imul(F, ce)) | 0), + (n = (n + Math.imul(F, pe)) | 0), + (n = (n + Math.imul(U, ce)) | 0), + (d = (d + Math.imul(U, pe)) | 0), + (l = (l + Math.imul(C2, ve)) | 0), + (n = (n + Math.imul(C2, be)) | 0), + (n = (n + Math.imul(O, ve)) | 0), + (d = (d + Math.imul(O, be)) | 0); + var Ye = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ye >>> 26)) | 0), + (Ye &= 67108863), + (l = Math.imul(G, fe)), + (n = Math.imul(G, ae)), + (n = (n + Math.imul(Y, fe)) | 0), + (d = Math.imul(Y, ae)), + (l = (l + Math.imul(V, oe)) | 0), + (n = (n + Math.imul(V, se)) | 0), + (n = (n + Math.imul($2, oe)) | 0), + (d = (d + Math.imul($2, se)) | 0), + (l = (l + Math.imul(j, he)) | 0), + (n = (n + Math.imul(j, ue)) | 0), + (n = (n + Math.imul(Z, he)) | 0), + (d = (d + Math.imul(Z, ue)) | 0), + (l = (l + Math.imul(W, le)) | 0), + (n = (n + Math.imul(W, de)) | 0), + (n = (n + Math.imul(K, le)) | 0), + (d = (d + Math.imul(K, de)) | 0), + (l = (l + Math.imul(z2, ce)) | 0), + (n = (n + Math.imul(z2, pe)) | 0), + (n = (n + Math.imul(H, ce)) | 0), + (d = (d + Math.imul(H, pe)) | 0), + (l = (l + Math.imul(F, ve)) | 0), + (n = (n + Math.imul(F, be)) | 0), + (n = (n + Math.imul(U, ve)) | 0), + (d = (d + Math.imul(U, be)) | 0); + var Xe = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Xe >>> 26)) | 0), + (Xe &= 67108863), + (l = Math.imul(G, oe)), + (n = Math.imul(G, se)), + (n = (n + Math.imul(Y, oe)) | 0), + (d = Math.imul(Y, se)), + (l = (l + Math.imul(V, he)) | 0), + (n = (n + Math.imul(V, ue)) | 0), + (n = (n + Math.imul($2, he)) | 0), + (d = (d + Math.imul($2, ue)) | 0), + (l = (l + Math.imul(j, le)) | 0), + (n = (n + Math.imul(j, de)) | 0), + (n = (n + Math.imul(Z, le)) | 0), + (d = (d + Math.imul(Z, de)) | 0), + (l = (l + Math.imul(W, ce)) | 0), + (n = (n + Math.imul(W, pe)) | 0), + (n = (n + Math.imul(K, ce)) | 0), + (d = (d + Math.imul(K, pe)) | 0), + (l = (l + Math.imul(z2, ve)) | 0), + (n = (n + Math.imul(z2, be)) | 0), + (n = (n + Math.imul(H, ve)) | 0), + (d = (d + Math.imul(H, be)) | 0); + var Je = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Je >>> 26)) | 0), + (Je &= 67108863), + (l = Math.imul(G, he)), + (n = Math.imul(G, ue)), + (n = (n + Math.imul(Y, he)) | 0), + (d = Math.imul(Y, ue)), + (l = (l + Math.imul(V, le)) | 0), + (n = (n + Math.imul(V, de)) | 0), + (n = (n + Math.imul($2, le)) | 0), + (d = (d + Math.imul($2, de)) | 0), + (l = (l + Math.imul(j, ce)) | 0), + (n = (n + Math.imul(j, pe)) | 0), + (n = (n + Math.imul(Z, ce)) | 0), + (d = (d + Math.imul(Z, pe)) | 0), + (l = (l + Math.imul(W, ve)) | 0), + (n = (n + Math.imul(W, be)) | 0), + (n = (n + Math.imul(K, ve)) | 0), + (d = (d + Math.imul(K, be)) | 0); + var Qe = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Qe >>> 26)) | 0), + (Qe &= 67108863), + (l = Math.imul(G, le)), + (n = Math.imul(G, de)), + (n = (n + Math.imul(Y, le)) | 0), + (d = Math.imul(Y, de)), + (l = (l + Math.imul(V, ce)) | 0), + (n = (n + Math.imul(V, pe)) | 0), + (n = (n + Math.imul($2, ce)) | 0), + (d = (d + Math.imul($2, pe)) | 0), + (l = (l + Math.imul(j, ve)) | 0), + (n = (n + Math.imul(j, be)) | 0), + (n = (n + Math.imul(Z, ve)) | 0), + (d = (d + Math.imul(Z, be)) | 0); + var et = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (et >>> 26)) | 0), + (et &= 67108863), + (l = Math.imul(G, ce)), + (n = Math.imul(G, pe)), + (n = (n + Math.imul(Y, ce)) | 0), + (d = Math.imul(Y, pe)), + (l = (l + Math.imul(V, ve)) | 0), + (n = (n + Math.imul(V, be)) | 0), + (n = (n + Math.imul($2, ve)) | 0), + (d = (d + Math.imul($2, be)) | 0); + var tt = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (tt >>> 26)) | 0), (tt &= 67108863), (l = Math.imul(G, ve)), (n = Math.imul(G, be)), (n = (n + Math.imul(Y, ve)) | 0), (d = Math.imul(Y, be)); + var rt = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + return ( + (b3 = (((d + (n >>> 13)) | 0) + (rt >>> 26)) | 0), + (rt &= 67108863), + (c[0] = ft), + (c[1] = Be), + (c[2] = qe), + (c[3] = ze), + (c[4] = He), + (c[5] = We), + (c[6] = Ke), + (c[7] = je), + (c[8] = Ze), + (c[9] = Ve), + (c[10] = $e), + (c[11] = Ge), + (c[12] = Ye), + (c[13] = Xe), + (c[14] = Je), + (c[15] = Qe), + (c[16] = et), + (c[17] = tt), + (c[18] = rt), + b3 !== 0 && ((c[19] = b3), h2.length++), + h2 + ); + }; + Math.imul || (L2 = q2); + function ge(v, i, a) { + (a.negative = i.negative ^ v.negative), (a.length = v.length + i.length); + for (var h2 = 0, s = 0, u = 0; u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b3 = h2 & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1); n <= l; n++) { + var d = u - n, + w = v.words[d] | 0, + g = i.words[n] | 0, + _4 = w * g, + A2 = _4 & 67108863; + (c = (c + ((_4 / 67108864) | 0)) | 0), (A2 = (A2 + b3) | 0), (b3 = A2 & 67108863), (c = (c + (A2 >>> 26)) | 0), (s += c >>> 26), (c &= 67108863); + } + (a.words[u] = b3), (h2 = c), (c = s); + } + return h2 !== 0 ? (a.words[u] = h2) : a.length--, a.strip(); + } + function _e(v, i, a) { + var h2 = new N(); + return h2.mulp(v, i, a); + } + f.prototype.mulTo = function (i, a) { + var h2, + s = this.length + i.length; + return this.length === 10 && i.length === 10 ? (h2 = L2(this, i, a)) : s < 63 ? (h2 = q2(this, i, a)) : s < 1024 ? (h2 = ge(this, i, a)) : (h2 = _e(this, i, a)), h2; + }; + function N(v, i) { + (this.x = v), (this.y = i); + } + (N.prototype.makeRBT = function (i) { + for (var a = new Array(i), h2 = f.prototype._countBits(i) - 1, s = 0; s < i; s++) a[s] = this.revBin(s, h2, i); + return a; + }), + (N.prototype.revBin = function (i, a, h2) { + if (i === 0 || i === h2 - 1) return i; + for (var s = 0, u = 0; u < a; u++) (s |= (i & 1) << (a - u - 1)), (i >>= 1); + return s; + }), + (N.prototype.permute = function (i, a, h2, s, u, c) { + for (var b3 = 0; b3 < c; b3++) (s[b3] = a[i[b3]]), (u[b3] = h2[i[b3]]); + }), + (N.prototype.transform = function (i, a, h2, s, u, c) { + this.permute(c, i, a, h2, s, u); + for (var b3 = 1; b3 < u; b3 <<= 1) + for (var l = b3 << 1, n = Math.cos((2 * Math.PI) / l), d = Math.sin((2 * Math.PI) / l), w = 0; w < u; w += l) + for (var g = n, _4 = d, A2 = 0; A2 < b3; A2++) { + var R2 = h2[w + A2], + I = s[w + A2], + Me = h2[w + A2 + b3], + k = s[w + A2 + b3], + D2 = g * Me - _4 * k; + (k = g * k + _4 * Me), (Me = D2), (h2[w + A2] = R2 + Me), (s[w + A2] = I + k), (h2[w + A2 + b3] = R2 - Me), (s[w + A2 + b3] = I - k), A2 !== l && ((D2 = n * g - d * _4), (_4 = n * _4 + d * g), (g = D2)); + } + }), + (N.prototype.guessLen13b = function (i, a) { + var h2 = Math.max(a, i) | 1, + s = h2 & 1, + u = 0; + for (h2 = (h2 / 2) | 0; h2; h2 = h2 >>> 1) u++; + return 1 << (u + 1 + s); + }), + (N.prototype.conjugate = function (i, a, h2) { + if (!(h2 <= 1)) + for (var s = 0; s < h2 / 2; s++) { + var u = i[s]; + (i[s] = i[h2 - s - 1]), (i[h2 - s - 1] = u), (u = a[s]), (a[s] = -a[h2 - s - 1]), (a[h2 - s - 1] = -u); + } + }), + (N.prototype.normalize13b = function (i, a) { + for (var h2 = 0, s = 0; s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h2; + (i[s] = u & 67108863), u < 67108864 ? (h2 = 0) : (h2 = (u / 67108864) | 0); + } + return i; + }), + (N.prototype.convert13b = function (i, a, h2, s) { + for (var u = 0, c = 0; c < a; c++) (u = u + (i[c] | 0)), (h2[2 * c] = u & 8191), (u = u >>> 13), (h2[2 * c + 1] = u & 8191), (u = u >>> 13); + for (c = 2 * a; c < s; ++c) h2[c] = 0; + r(u === 0), r((u & -8192) === 0); + }), + (N.prototype.stub = function (i) { + for (var a = new Array(i), h2 = 0; h2 < i; h2++) a[h2] = 0; + return a; + }), + (N.prototype.mulp = function (i, a, h2) { + var s = 2 * this.guessLen13b(i.length, a.length), + u = this.makeRBT(s), + c = this.stub(s), + b3 = new Array(s), + l = new Array(s), + n = new Array(s), + d = new Array(s), + w = new Array(s), + g = new Array(s), + _4 = h2.words; + (_4.length = s), this.convert13b(i.words, i.length, b3, s), this.convert13b(a.words, a.length, d, s), this.transform(b3, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A2 = 0; A2 < s; A2++) { + var R2 = l[A2] * w[A2] - n[A2] * g[A2]; + (n[A2] = l[A2] * g[A2] + n[A2] * w[A2]), (l[A2] = R2); + } + return this.conjugate(l, n, s), this.transform(l, n, _4, c, s, u), this.conjugate(_4, c, s), this.normalize13b(_4, s), (h2.negative = i.negative ^ a.negative), (h2.length = i.length + a.length), h2.strip(); + }), + (f.prototype.mul = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), this.mulTo(i, a); + }), + (f.prototype.mulf = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), _e(this, i, a); + }), + (f.prototype.imul = function (i) { + return this.clone().mulTo(i, this); + }), + (f.prototype.imuln = function (i) { + r(typeof i == 'number'), r(i < 67108864); + for (var a = 0, h2 = 0; h2 < this.length; h2++) { + var s = (this.words[h2] | 0) * i, + u = (s & 67108863) + (a & 67108863); + (a >>= 26), (a += (s / 67108864) | 0), (a += u >>> 26), (this.words[h2] = u & 67108863); + } + return a !== 0 && ((this.words[h2] = a), this.length++), this; + }), + (f.prototype.muln = function (i) { + return this.clone().imuln(i); + }), + (f.prototype.sqr = function () { + return this.mul(this); + }), + (f.prototype.isqr = function () { + return this.imul(this.clone()); + }), + (f.prototype.pow = function (i) { + var a = B(i); + if (a.length === 0) return new f(1); + for (var h2 = this, s = 0; s < a.length && a[s] === 0; s++, h2 = h2.sqr()); + if (++s < a.length) for (var u = h2.sqr(); s < a.length; s++, u = u.sqr()) a[s] !== 0 && (h2 = h2.mul(u)); + return h2; + }), + (f.prototype.iushln = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26, + s = (67108863 >>> (26 - a)) << (26 - a), + u; + if (a !== 0) { + var c = 0; + for (u = 0; u < this.length; u++) { + var b3 = this.words[u] & s, + l = ((this.words[u] | 0) - b3) << a; + (this.words[u] = l | c), (c = b3 >>> (26 - a)); + } + c && ((this.words[u] = c), this.length++); + } + if (h2 !== 0) { + for (u = this.length - 1; u >= 0; u--) this.words[u + h2] = this.words[u]; + for (u = 0; u < h2; u++) this.words[u] = 0; + this.length += h2; + } + return this.strip(); + }), + (f.prototype.ishln = function (i) { + return r(this.negative === 0), this.iushln(i); + }), + (f.prototype.iushrn = function (i, a, h2) { + r(typeof i == 'number' && i >= 0); + var s; + a ? (s = (a - (a % 26)) / 26) : (s = 0); + var u = i % 26, + c = Math.min((i - u) / 26, this.length), + b3 = 67108863 ^ ((67108863 >>> u) << u), + l = h2; + if (((s -= c), (s = Math.max(0, s)), l)) { + for (var n = 0; n < c; n++) l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) for (this.length -= c, n = 0; n < this.length; n++) this.words[n] = this.words[n + c]; + else (this.words[0] = 0), (this.length = 1); + var d = 0; + for (n = this.length - 1; n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + (this.words[n] = (d << (26 - u)) | (w >>> u)), (d = w & b3); + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && ((this.words[0] = 0), (this.length = 1)), this.strip(); + }), + (f.prototype.ishrn = function (i, a, h2) { + return r(this.negative === 0), this.iushrn(i, a, h2); + }), + (f.prototype.shln = function (i) { + return this.clone().ishln(i); + }), + (f.prototype.ushln = function (i) { + return this.clone().iushln(i); + }), + (f.prototype.shrn = function (i) { + return this.clone().ishrn(i); + }), + (f.prototype.ushrn = function (i) { + return this.clone().iushrn(i); + }), + (f.prototype.testn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26, + s = 1 << a; + if (this.length <= h2) return false; + var u = this.words[h2]; + return !!(u & s); + }), + (f.prototype.imaskn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26; + if ((r(this.negative === 0, 'imaskn works only with positive numbers'), this.length <= h2)) return this; + if ((a !== 0 && h2++, (this.length = Math.min(h2, this.length)), a !== 0)) { + var s = 67108863 ^ ((67108863 >>> a) << a); + this.words[this.length - 1] &= s; + } + return this.strip(); + }), + (f.prototype.maskn = function (i) { + return this.clone().imaskn(i); + }), + (f.prototype.iaddn = function (i) { + return ( + r(typeof i == 'number'), + r(i < 67108864), + i < 0 + ? this.isubn(-i) + : this.negative !== 0 + ? this.length === 1 && (this.words[0] | 0) < i + ? ((this.words[0] = i - (this.words[0] | 0)), (this.negative = 0), this) + : ((this.negative = 0), this.isubn(i), (this.negative = 1), this) + : this._iaddn(i) + ); + }), + (f.prototype._iaddn = function (i) { + this.words[0] += i; + for (var a = 0; a < this.length && this.words[a] >= 67108864; a++) (this.words[a] -= 67108864), a === this.length - 1 ? (this.words[a + 1] = 1) : this.words[a + 1]++; + return (this.length = Math.max(this.length, a + 1)), this; + }), + (f.prototype.isubn = function (i) { + if ((r(typeof i == 'number'), r(i < 67108864), i < 0)) return this.iaddn(-i); + if (this.negative !== 0) return (this.negative = 0), this.iaddn(i), (this.negative = 1), this; + if (((this.words[0] -= i), this.length === 1 && this.words[0] < 0)) (this.words[0] = -this.words[0]), (this.negative = 1); + else for (var a = 0; a < this.length && this.words[a] < 0; a++) (this.words[a] += 67108864), (this.words[a + 1] -= 1); + return this.strip(); + }), + (f.prototype.addn = function (i) { + return this.clone().iaddn(i); + }), + (f.prototype.subn = function (i) { + return this.clone().isubn(i); + }), + (f.prototype.iabs = function () { + return (this.negative = 0), this; + }), + (f.prototype.abs = function () { + return this.clone().iabs(); + }), + (f.prototype._ishlnsubmul = function (i, a, h2) { + var s = i.length + h2, + u; + this._expand(s); + var c, + b3 = 0; + for (u = 0; u < i.length; u++) { + c = (this.words[u + h2] | 0) + b3; + var l = (i.words[u] | 0) * a; + (c -= l & 67108863), (b3 = (c >> 26) - ((l / 67108864) | 0)), (this.words[u + h2] = c & 67108863); + } + for (; u < this.length - h2; u++) (c = (this.words[u + h2] | 0) + b3), (b3 = c >> 26), (this.words[u + h2] = c & 67108863); + if (b3 === 0) return this.strip(); + for (r(b3 === -1), b3 = 0, u = 0; u < this.length; u++) (c = -(this.words[u] | 0) + b3), (b3 = c >> 26), (this.words[u] = c & 67108863); + return (this.negative = 1), this.strip(); + }), + (f.prototype._wordDiv = function (i, a) { + var h2 = this.length - i.length, + s = this.clone(), + u = i, + c = u.words[u.length - 1] | 0, + b3 = this._countBits(c); + (h2 = 26 - b3), h2 !== 0 && ((u = u.ushln(h2)), s.iushln(h2), (c = u.words[u.length - 1] | 0)); + var l = s.length - u.length, + n; + if (a !== 'mod') { + (n = new f(null)), (n.length = l + 1), (n.words = new Array(n.length)); + for (var d = 0; d < n.length; d++) n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && ((s = w), n && (n.words[l] = 1)); + for (var g = l - 1; g >= 0; g--) { + var _4 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_4 = Math.min((_4 / c) | 0, 67108863), s._ishlnsubmul(u, _4, g); s.negative !== 0; ) _4--, (s.negative = 0), s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _4); + } + return n && n.strip(), s.strip(), a !== 'div' && h2 !== 0 && s.iushrn(h2), {div: n || null, mod: s}; + }), + (f.prototype.divmod = function (i, a, h2) { + if ((r(!i.isZero()), this.isZero())) return {div: new f(0), mod: new f(0)}; + var s, u, c; + return this.negative !== 0 && i.negative === 0 + ? ((c = this.neg().divmod(i, a)), a !== 'mod' && (s = c.div.neg()), a !== 'div' && ((u = c.mod.neg()), h2 && u.negative !== 0 && u.iadd(i)), {div: s, mod: u}) + : this.negative === 0 && i.negative !== 0 + ? ((c = this.divmod(i.neg(), a)), a !== 'mod' && (s = c.div.neg()), {div: s, mod: c.mod}) + : (this.negative & i.negative) !== 0 + ? ((c = this.neg().divmod(i.neg(), a)), a !== 'div' && ((u = c.mod.neg()), h2 && u.negative !== 0 && u.isub(i)), {div: c.div, mod: u}) + : i.length > this.length || this.cmp(i) < 0 + ? {div: new f(0), mod: this} + : i.length === 1 + ? a === 'div' + ? {div: this.divn(i.words[0]), mod: null} + : a === 'mod' + ? {div: null, mod: new f(this.modn(i.words[0]))} + : {div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0]))} + : this._wordDiv(i, a); + }), + (f.prototype.div = function (i) { + return this.divmod(i, 'div', false).div; + }), + (f.prototype.mod = function (i) { + return this.divmod(i, 'mod', false).mod; + }), + (f.prototype.umod = function (i) { + return this.divmod(i, 'mod', true).mod; + }), + (f.prototype.divRound = function (i) { + var a = this.divmod(i); + if (a.mod.isZero()) return a.div; + var h2 = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, + s = i.ushrn(1), + u = i.andln(1), + c = h2.cmp(s); + return c < 0 || (u === 1 && c === 0) ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }), + (f.prototype.modn = function (i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h2 = 0, s = this.length - 1; s >= 0; s--) h2 = (a * h2 + (this.words[s] | 0)) % i; + return h2; + }), + (f.prototype.idivn = function (i) { + r(i <= 67108863); + for (var a = 0, h2 = this.length - 1; h2 >= 0; h2--) { + var s = (this.words[h2] | 0) + a * 67108864; + (this.words[h2] = (s / i) | 0), (a = s % i); + } + return this.strip(); + }), + (f.prototype.divn = function (i) { + return this.clone().idivn(i); + }), + (f.prototype.egcd = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h2 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = new f(0), b3 = new f(1), l = 0; a.isEven() && h2.isEven(); ) a.iushrn(1), h2.iushrn(1), ++l; + for (var n = h2.clone(), d = a.clone(); !a.isZero(); ) { + for (var w = 0, g = 1; (a.words[0] & g) === 0 && w < 26; ++w, g <<= 1); + if (w > 0) for (a.iushrn(w); w-- > 0; ) (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _4 = 0, A2 = 1; (h2.words[0] & A2) === 0 && _4 < 26; ++_4, A2 <<= 1); + if (_4 > 0) for (h2.iushrn(_4); _4-- > 0; ) (c.isOdd() || b3.isOdd()) && (c.iadd(n), b3.isub(d)), c.iushrn(1), b3.iushrn(1); + a.cmp(h2) >= 0 ? (a.isub(h2), s.isub(c), u.isub(b3)) : (h2.isub(a), c.isub(s), b3.isub(u)); + } + return {a: c, b: b3, gcd: h2.iushln(l)}; + }), + (f.prototype._invmp = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h2 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = h2.clone(); a.cmpn(1) > 0 && h2.cmpn(1) > 0; ) { + for (var b3 = 0, l = 1; (a.words[0] & l) === 0 && b3 < 26; ++b3, l <<= 1); + if (b3 > 0) for (a.iushrn(b3); b3-- > 0; ) s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1; (h2.words[0] & d) === 0 && n < 26; ++n, d <<= 1); + if (n > 0) for (h2.iushrn(n); n-- > 0; ) u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h2) >= 0 ? (a.isub(h2), s.isub(u)) : (h2.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? (w = s) : (w = u), w.cmpn(0) < 0 && w.iadd(i), w; + }), + (f.prototype.gcd = function (i) { + if (this.isZero()) return i.abs(); + if (i.isZero()) return this.abs(); + var a = this.clone(), + h2 = i.clone(); + (a.negative = 0), (h2.negative = 0); + for (var s = 0; a.isEven() && h2.isEven(); s++) a.iushrn(1), h2.iushrn(1); + do { + for (; a.isEven(); ) a.iushrn(1); + for (; h2.isEven(); ) h2.iushrn(1); + var u = a.cmp(h2); + if (u < 0) { + var c = a; + (a = h2), (h2 = c); + } else if (u === 0 || h2.cmpn(1) === 0) break; + a.isub(h2); + } while (true); + return h2.iushln(s); + }), + (f.prototype.invm = function (i) { + return this.egcd(i).a.umod(i); + }), + (f.prototype.isEven = function () { + return (this.words[0] & 1) === 0; + }), + (f.prototype.isOdd = function () { + return (this.words[0] & 1) === 1; + }), + (f.prototype.andln = function (i) { + return this.words[0] & i; + }), + (f.prototype.bincn = function (i) { + r(typeof i == 'number'); + var a = i % 26, + h2 = (i - a) / 26, + s = 1 << a; + if (this.length <= h2) return this._expand(h2 + 1), (this.words[h2] |= s), this; + for (var u = s, c = h2; u !== 0 && c < this.length; c++) { + var b3 = this.words[c] | 0; + (b3 += u), (u = b3 >>> 26), (b3 &= 67108863), (this.words[c] = b3); + } + return u !== 0 && ((this.words[c] = u), this.length++), this; + }), + (f.prototype.isZero = function () { + return this.length === 1 && this.words[0] === 0; + }), + (f.prototype.cmpn = function (i) { + var a = i < 0; + if (this.negative !== 0 && !a) return -1; + if (this.negative === 0 && a) return 1; + this.strip(); + var h2; + if (this.length > 1) h2 = 1; + else { + a && (i = -i), r(i <= 67108863, 'Number is too big'); + var s = this.words[0] | 0; + h2 = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h2 | 0 : h2; + }), + (f.prototype.cmp = function (i) { + if (this.negative !== 0 && i.negative === 0) return -1; + if (this.negative === 0 && i.negative !== 0) return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }), + (f.prototype.ucmp = function (i) { + if (this.length > i.length) return 1; + if (this.length < i.length) return -1; + for (var a = 0, h2 = this.length - 1; h2 >= 0; h2--) { + var s = this.words[h2] | 0, + u = i.words[h2] | 0; + if (s !== u) { + s < u ? (a = -1) : s > u && (a = 1); + break; + } + } + return a; + }), + (f.prototype.gtn = function (i) { + return this.cmpn(i) === 1; + }), + (f.prototype.gt = function (i) { + return this.cmp(i) === 1; + }), + (f.prototype.gten = function (i) { + return this.cmpn(i) >= 0; + }), + (f.prototype.gte = function (i) { + return this.cmp(i) >= 0; + }), + (f.prototype.ltn = function (i) { + return this.cmpn(i) === -1; + }), + (f.prototype.lt = function (i) { + return this.cmp(i) === -1; + }), + (f.prototype.lten = function (i) { + return this.cmpn(i) <= 0; + }), + (f.prototype.lte = function (i) { + return this.cmp(i) <= 0; + }), + (f.prototype.eqn = function (i) { + return this.cmpn(i) === 0; + }), + (f.prototype.eq = function (i) { + return this.cmp(i) === 0; + }), + (f.red = function (i) { + return new P(i); + }), + (f.prototype.toRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), r(this.negative === 0, 'red works only with positives'), i.convertTo(this)._forceRed(i); + }), + (f.prototype.fromRed = function () { + return r(this.red, 'fromRed works only with numbers in reduction context'), this.red.convertFrom(this); + }), + (f.prototype._forceRed = function (i) { + return (this.red = i), this; + }), + (f.prototype.forceRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), this._forceRed(i); + }), + (f.prototype.redAdd = function (i) { + return r(this.red, 'redAdd works only with red numbers'), this.red.add(this, i); + }), + (f.prototype.redIAdd = function (i) { + return r(this.red, 'redIAdd works only with red numbers'), this.red.iadd(this, i); + }), + (f.prototype.redSub = function (i) { + return r(this.red, 'redSub works only with red numbers'), this.red.sub(this, i); + }), + (f.prototype.redISub = function (i) { + return r(this.red, 'redISub works only with red numbers'), this.red.isub(this, i); + }), + (f.prototype.redShl = function (i) { + return r(this.red, 'redShl works only with red numbers'), this.red.shl(this, i); + }), + (f.prototype.redMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.mul(this, i); + }), + (f.prototype.redIMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.imul(this, i); + }), + (f.prototype.redSqr = function () { + return r(this.red, 'redSqr works only with red numbers'), this.red._verify1(this), this.red.sqr(this); + }), + (f.prototype.redISqr = function () { + return r(this.red, 'redISqr works only with red numbers'), this.red._verify1(this), this.red.isqr(this); + }), + (f.prototype.redSqrt = function () { + return r(this.red, 'redSqrt works only with red numbers'), this.red._verify1(this), this.red.sqrt(this); + }), + (f.prototype.redInvm = function () { + return r(this.red, 'redInvm works only with red numbers'), this.red._verify1(this), this.red.invm(this); + }), + (f.prototype.redNeg = function () { + return r(this.red, 'redNeg works only with red numbers'), this.red._verify1(this), this.red.neg(this); + }), + (f.prototype.redPow = function (i) { + return r(this.red && !i.red, 'redPow(normalNum)'), this.red._verify1(this), this.red.pow(this, i); + }); + var we = {k256: null, p224: null, p192: null, p25519: null}; + function ye(v, i) { + (this.name = v), (this.p = new f(i, 16)), (this.n = this.p.bitLength()), (this.k = new f(1).iushln(this.n).isub(this.p)), (this.tmp = this._tmp()); + } + (ye.prototype._tmp = function () { + var i = new f(null); + return (i.words = new Array(Math.ceil(this.n / 13))), i; + }), + (ye.prototype.ireduce = function (i) { + var a = i, + h2; + do this.split(a, this.tmp), (a = this.imulK(a)), (a = a.iadd(this.tmp)), (h2 = a.bitLength()); + while (h2 > this.n); + var s = h2 < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? ((a.words[0] = 0), (a.length = 1)) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }), + (ye.prototype.split = function (i, a) { + i.iushrn(this.n, 0, a); + }), + (ye.prototype.imulK = function (i) { + return i.imul(this.k); + }); + function xe() { + ye.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + o(xe, ye), + (xe.prototype.split = function (i, a) { + for (var h2 = 4194303, s = Math.min(i.length, 9), u = 0; u < s; u++) a.words[u] = i.words[u]; + if (((a.length = s), i.length <= 9)) { + (i.words[0] = 0), (i.length = 1); + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h2, u = 10; u < i.length; u++) { + var b3 = i.words[u] | 0; + (i.words[u - 10] = ((b3 & h2) << 4) | (c >>> 22)), (c = b3); + } + (c >>>= 22), (i.words[u - 10] = c), c === 0 && i.length > 10 ? (i.length -= 10) : (i.length -= 9); + }), + (xe.prototype.imulK = function (i) { + (i.words[i.length] = 0), (i.words[i.length + 1] = 0), (i.length += 2); + for (var a = 0, h2 = 0; h2 < i.length; h2++) { + var s = i.words[h2] | 0; + (a += s * 977), (i.words[h2] = a & 67108863), (a = s * 64 + ((a / 67108864) | 0)); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }); + function Re() { + ye.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + o(Re, ye); + function Ee() { + ye.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + o(Ee, ye); + function Ae() { + ye.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + o(Ae, ye), + (Ae.prototype.imulK = function (i) { + for (var a = 0, h2 = 0; h2 < i.length; h2++) { + var s = (i.words[h2] | 0) * 19 + a, + u = s & 67108863; + (s >>>= 26), (i.words[h2] = u), (a = s); + } + return a !== 0 && (i.words[i.length++] = a), i; + }), + (f._prime = function (i) { + if (we[i]) return we[i]; + var a; + if (i === 'k256') a = new xe(); + else if (i === 'p224') a = new Re(); + else if (i === 'p192') a = new Ee(); + else if (i === 'p25519') a = new Ae(); + else throw new Error('Unknown prime ' + i); + return (we[i] = a), a; + }); + function P(v) { + if (typeof v == 'string') { + var i = f._prime(v); + (this.m = i.p), (this.prime = i); + } else r(v.gtn(1), 'modulus must be greater than 1'), (this.m = v), (this.prime = null); + } + (P.prototype._verify1 = function (i) { + r(i.negative === 0, 'red works only with positives'), r(i.red, 'red works only with red numbers'); + }), + (P.prototype._verify2 = function (i, a) { + r((i.negative | a.negative) === 0, 'red works only with positives'), r(i.red && i.red === a.red, 'red works only with red numbers'); + }), + (P.prototype.imod = function (i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }), + (P.prototype.neg = function (i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }), + (P.prototype.add = function (i, a) { + this._verify2(i, a); + var h2 = i.add(a); + return h2.cmp(this.m) >= 0 && h2.isub(this.m), h2._forceRed(this); + }), + (P.prototype.iadd = function (i, a) { + this._verify2(i, a); + var h2 = i.iadd(a); + return h2.cmp(this.m) >= 0 && h2.isub(this.m), h2; + }), + (P.prototype.sub = function (i, a) { + this._verify2(i, a); + var h2 = i.sub(a); + return h2.cmpn(0) < 0 && h2.iadd(this.m), h2._forceRed(this); + }), + (P.prototype.isub = function (i, a) { + this._verify2(i, a); + var h2 = i.isub(a); + return h2.cmpn(0) < 0 && h2.iadd(this.m), h2; + }), + (P.prototype.shl = function (i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }), + (P.prototype.imul = function (i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }), + (P.prototype.mul = function (i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }), + (P.prototype.isqr = function (i) { + return this.imul(i, i.clone()); + }), + (P.prototype.sqr = function (i) { + return this.mul(i, i); + }), + (P.prototype.sqrt = function (i) { + if (i.isZero()) return i.clone(); + var a = this.m.andln(3); + if ((r(a % 2 === 1), a === 3)) { + var h2 = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h2); + } + for (var s = this.m.subn(1), u = 0; !s.isZero() && s.andln(1) === 0; ) u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), + b3 = c.redNeg(), + l = this.m.subn(1).iushrn(1), + n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this); this.pow(n, l).cmp(b3) !== 0; ) n.redIAdd(b3); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _4 = u; g.cmp(c) !== 0; ) { + for (var A2 = g, R2 = 0; A2.cmp(c) !== 0; R2++) A2 = A2.redSqr(); + r(R2 < _4); + var I = this.pow(d, new f(1).iushln(_4 - R2 - 1)); + (w = w.redMul(I)), (d = I.redSqr()), (g = g.redMul(d)), (_4 = R2); + } + return w; + }), + (P.prototype.invm = function (i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? ((a.negative = 0), this.imod(a).redNeg()) : this.imod(a); + }), + (P.prototype.pow = function (i, a) { + if (a.isZero()) return new f(1).toRed(this); + if (a.cmpn(1) === 0) return i.clone(); + var h2 = 4, + s = new Array(1 << h2); + (s[0] = new f(1).toRed(this)), (s[1] = i); + for (var u = 2; u < s.length; u++) s[u] = this.mul(s[u - 1], i); + var c = s[0], + b3 = 0, + l = 0, + n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1; u >= 0; u--) { + for (var d = a.words[u], w = n - 1; w >= 0; w--) { + var g = (d >> w) & 1; + if ((c !== s[0] && (c = this.sqr(c)), g === 0 && b3 === 0)) { + l = 0; + continue; + } + (b3 <<= 1), (b3 |= g), l++, !(l !== h2 && (u !== 0 || w !== 0)) && ((c = this.mul(c, s[b3])), (l = 0), (b3 = 0)); + } + n = 26; + } + return c; + }), + (P.prototype.convertTo = function (i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }), + (P.prototype.convertFrom = function (i) { + var a = i.clone(); + return (a.red = null), a; + }), + (f.mont = function (i) { + return new Se(i); + }); + function Se(v) { + P.call(this, v), + (this.shift = this.m.bitLength()), + this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), + (this.r = new f(1).iushln(this.shift)), + (this.r2 = this.imod(this.r.sqr())), + (this.rinv = this.r._invmp(this.m)), + (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), + (this.minv = this.minv.umod(this.r)), + (this.minv = this.r.sub(this.minv)); + } + o(Se, P), + (Se.prototype.convertTo = function (i) { + return this.imod(i.ushln(this.shift)); + }), + (Se.prototype.convertFrom = function (i) { + var a = this.imod(i.mul(this.rinv)); + return (a.red = null), a; + }), + (Se.prototype.imul = function (i, a) { + if (i.isZero() || a.isZero()) return (i.words[0] = 0), (i.length = 1), i; + var h2 = i.imul(a), + s = h2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h2.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.mul = function (i, a) { + if (i.isZero() || a.isZero()) return new f(0)._forceRed(this); + var h2 = i.mul(a), + s = h2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h2.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.invm = function (i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }); + })(typeof yd > 'u' || yd, L3); + }); + P3 = T2((wL, D3) => { + var bq = o0(), + mq = N3(); + D3.exports = function (e) { + return new Zn(e); + }; + var hr = { + secp256k1: {name: 'secp256k1', byteLength: 32}, + secp224r1: {name: 'p224', byteLength: 28}, + prime256v1: {name: 'p256', byteLength: 32}, + prime192v1: {name: 'p192', byteLength: 24}, + ed25519: {name: 'ed25519', byteLength: 32}, + secp384r1: {name: 'p384', byteLength: 48}, + secp521r1: {name: 'p521', byteLength: 66} + }; + hr.p224 = hr.secp224r1; + hr.p256 = hr.secp256r1 = hr.prime256v1; + hr.p192 = hr.secp192r1 = hr.prime192v1; + hr.p384 = hr.secp384r1; + hr.p521 = hr.secp521r1; + function Zn(t) { + (this.curveType = hr[t]), this.curveType || (this.curveType = {name: t}), (this.curve = new bq.ec(this.curveType.name)), (this.keys = undefined); + } + Zn.prototype.generateKeys = function (t, e) { + return (this.keys = this.curve.genKeyPair()), this.getPublicKey(t, e); + }; + Zn.prototype.computeSecret = function (t, e, r) { + (e = e || 'utf8'), Buffer.isBuffer(t) || (t = new Buffer(t, e)); + var o = this.curve.keyFromPublic(t).getPublic(), + f = o.mul(this.keys.getPrivate()).getX(); + return wd(f, r, this.curveType.byteLength); + }; + Zn.prototype.getPublicKey = function (t, e) { + var r = this.keys.getPublic(e === 'compressed', true); + return e === 'hybrid' && (r[r.length - 1] % 2 ? (r[0] = 7) : (r[0] = 6)), wd(r, t); + }; + Zn.prototype.getPrivateKey = function (t) { + return wd(this.keys.getPrivate(), t); + }; + Zn.prototype.setPublicKey = function (t, e) { + return (e = e || 'utf8'), Buffer.isBuffer(t) || (t = new Buffer(t, e)), this.keys._importPublic(t), this; + }; + Zn.prototype.setPrivateKey = function (t, e) { + (e = e || 'utf8'), Buffer.isBuffer(t) || (t = new Buffer(t, e)); + var r = new mq(t); + return (r = r.toString(16)), (this.keys = this.curve.genKeyPair()), this.keys._importPrivate(r), this; + }; + function wd(t, e, r) { + Array.isArray(t) || (t = t.toArray()); + var o = new Buffer(t); + if (r && o.length < r) { + var f = new Buffer(r - o.length); + f.fill(0), (o = Buffer.concat([f, o])); + } + return e ? o.toString(e) : o; + } + }); + _d = T2((ML, C3) => { + var gq = bf(), + Md = Te().Buffer; + C3.exports = function (t, e) { + for (var r = Md.alloc(0), o = 0, f; r.length < e; ) (f = yq(o++)), (r = Md.concat([r, gq('sha1').update(t).update(f).digest()])); + return r.slice(0, e); + }; + function yq(t) { + var e = Md.allocUnsafe(4); + return e.writeUInt32BE(t, 0), e; + } + }); + xd = T2((_L, O3) => { + O3.exports = function (e, r) { + for (var o = e.length, f = -1; ++f < o; ) e[f] ^= r[f]; + return e; + }; + }); + w0 = T2((F3, Sd) => { + (function (t, e) { + function r(v, i) { + if (!v) throw new Error(i || 'Assertion failed'); + } + function o(v, i) { + v.super_ = i; + var a = function () {}; + (a.prototype = i.prototype), (v.prototype = new a()), (v.prototype.constructor = v); + } + function f(v, i, a) { + if (f.isBN(v)) return v; + (this.negative = 0), (this.words = null), (this.length = 0), (this.red = null), v !== null && ((i === 'le' || i === 'be') && ((a = i), (i = 10)), this._init(v || 0, i || 10, a || 'be')); + } + typeof t == 'object' ? (t.exports = f) : (e.BN = f), (f.BN = f), (f.wordSize = 26); + var p; + try { + typeof window < 'u' && typeof window.Buffer < 'u' ? (p = window.Buffer) : (p = ji().Buffer); + } catch {} + (f.isBN = function (i) { + return i instanceof f ? true : i !== null && typeof i == 'object' && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }), + (f.max = function (i, a) { + return i.cmp(a) > 0 ? i : a; + }), + (f.min = function (i, a) { + return i.cmp(a) < 0 ? i : a; + }), + (f.prototype._init = function (i, a, h2) { + if (typeof i == 'number') return this._initNumber(i, a, h2); + if (typeof i == 'object') return this._initArray(i, a, h2); + a === 'hex' && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), (i = i.toString().replace(/\s+/g, '')); + var s = 0; + i[0] === '-' && (s++, (this.negative = 1)), s < i.length && (a === 16 ? this._parseHex(i, s, h2) : (this._parseBase(i, a, s), h2 === 'le' && this._initArray(this.toArray(), a, h2))); + }), + (f.prototype._initNumber = function (i, a, h2) { + i < 0 && ((this.negative = 1), (i = -i)), + i < 67108864 + ? ((this.words = [i & 67108863]), (this.length = 1)) + : i < 4503599627370496 + ? ((this.words = [i & 67108863, (i / 67108864) & 67108863]), (this.length = 2)) + : (r(i < 9007199254740992), (this.words = [i & 67108863, (i / 67108864) & 67108863, 1]), (this.length = 3)), + h2 === 'le' && this._initArray(this.toArray(), a, h2); + }), + (f.prototype._initArray = function (i, a, h2) { + if ((r(typeof i.length == 'number'), i.length <= 0)) return (this.words = [0]), (this.length = 1), this; + (this.length = Math.ceil(i.length / 3)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u, + c, + b3 = 0; + if (h2 === 'be') + for (s = i.length - 1, u = 0; s >= 0; s -= 3) + (c = i[s] | (i[s - 1] << 8) | (i[s - 2] << 16)), (this.words[u] |= (c << b3) & 67108863), (this.words[u + 1] = (c >>> (26 - b3)) & 67108863), (b3 += 24), b3 >= 26 && ((b3 -= 26), u++); + else if (h2 === 'le') + for (s = 0, u = 0; s < i.length; s += 3) (c = i[s] | (i[s + 1] << 8) | (i[s + 2] << 16)), (this.words[u] |= (c << b3) & 67108863), (this.words[u + 1] = (c >>> (26 - b3)) & 67108863), (b3 += 24), b3 >= 26 && ((b3 -= 26), u++); + return this.strip(); + }); + function m2(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : (a - 48) & 15; + } + function y3(v, i, a) { + var h2 = m2(v, a); + return a - 1 >= i && (h2 |= m2(v, a - 1) << 4), h2; + } + f.prototype._parseHex = function (i, a, h2) { + (this.length = Math.ceil((i.length - a) / 6)), (this.words = new Array(this.length)); + for (var s = 0; s < this.length; s++) this.words[s] = 0; + var u = 0, + c = 0, + b3; + if (h2 === 'be') for (s = i.length - 1; s >= a; s -= 2) (b3 = y3(i, a, s) << u), (this.words[c] |= b3 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b3 >>> 26)) : (u += 8); + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a; s < i.length; s += 2) (b3 = y3(i, a, s) << u), (this.words[c] |= b3 & 67108863), u >= 18 ? ((u -= 18), (c += 1), (this.words[c] |= b3 >>> 26)) : (u += 8); + } + this.strip(); + }; + function M(v, i, a, h2) { + for (var s = 0, u = Math.min(v.length, a), c = i; c < u; c++) { + var b3 = v.charCodeAt(c) - 48; + (s *= h2), b3 >= 49 ? (s += b3 - 49 + 10) : b3 >= 17 ? (s += b3 - 17 + 10) : (s += b3); + } + return s; + } + (f.prototype._parseBase = function (i, a, h2) { + (this.words = [0]), (this.length = 1); + for (var s = 0, u = 1; u <= 67108863; u *= a) s++; + s--, (u = (u / a) | 0); + for (var c = i.length - h2, b3 = c % s, l = Math.min(c, c - b3) + h2, n = 0, d = h2; d < l; d += s) (n = M(i, d, d + s, a)), this.imuln(u), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + if (b3 !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0; d < b3; d++) w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? (this.words[0] += n) : this._iaddn(n); + } + this.strip(); + }), + (f.prototype.copy = function (i) { + i.words = new Array(this.length); + for (var a = 0; a < this.length; a++) i.words[a] = this.words[a]; + (i.length = this.length), (i.negative = this.negative), (i.red = this.red); + }), + (f.prototype.clone = function () { + var i = new f(null); + return this.copy(i), i; + }), + (f.prototype._expand = function (i) { + for (; this.length < i; ) this.words[this.length++] = 0; + return this; + }), + (f.prototype.strip = function () { + for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; + return this._normSign(); + }), + (f.prototype._normSign = function () { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }), + (f.prototype.inspect = function () { + return (this.red ? ''; + }); + var x = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ], + S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + E2 = [ + 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, + 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + (f.prototype.toString = function (i, a) { + (i = i || 10), (a = a | 0 || 1); + var h2; + if (i === 16 || i === 'hex') { + h2 = ''; + for (var s = 0, u = 0, c = 0; c < this.length; c++) { + var b3 = this.words[c], + l = (((b3 << s) | u) & 16777215).toString(16); + (u = (b3 >>> (24 - s)) & 16777215), u !== 0 || c !== this.length - 1 ? (h2 = x[6 - l.length] + l + h2) : (h2 = l + h2), (s += 2), s >= 26 && ((s -= 26), c--); + } + for (u !== 0 && (h2 = u.toString(16) + h2); h2.length % a !== 0; ) h2 = '0' + h2; + return this.negative !== 0 && (h2 = '-' + h2), h2; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], + d = E2[i]; + h2 = ''; + var w = this.clone(); + for (w.negative = 0; !w.isZero(); ) { + var g = w.modn(d).toString(i); + (w = w.idivn(d)), w.isZero() ? (h2 = g + h2) : (h2 = x[n - g.length] + g + h2); + } + for (this.isZero() && (h2 = '0' + h2); h2.length % a !== 0; ) h2 = '0' + h2; + return this.negative !== 0 && (h2 = '-' + h2), h2; + } + r(false, 'Base should be between 2 and 36'); + }), + (f.prototype.toNumber = function () { + var i = this.words[0]; + return ( + this.length === 2 ? (i += this.words[1] * 67108864) : this.length === 3 && this.words[2] === 1 ? (i += 4503599627370496 + this.words[1] * 67108864) : this.length > 2 && r(false, 'Number can only safely store up to 53 bits'), + this.negative !== 0 ? -i : i + ); + }), + (f.prototype.toJSON = function () { + return this.toString(16); + }), + (f.prototype.toBuffer = function (i, a) { + return r(typeof p < 'u'), this.toArrayLike(p, i, a); + }), + (f.prototype.toArray = function (i, a) { + return this.toArrayLike(Array, i, a); + }), + (f.prototype.toArrayLike = function (i, a, h2) { + var s = this.byteLength(), + u = h2 || Math.max(1, s); + r(s <= u, 'byte array longer than desired length'), r(u > 0, 'Requested array length <= 0'), this.strip(); + var c = a === 'le', + b3 = new i(u), + l, + n, + d = this.clone(); + if (c) { + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b3[n] = l); + for (; n < u; n++) b3[n] = 0; + } else { + for (n = 0; n < u - s; n++) b3[n] = 0; + for (n = 0; !d.isZero(); n++) (l = d.andln(255)), d.iushrn(8), (b3[u - n - 1] = l); + } + return b3; + }), + Math.clz32 + ? (f.prototype._countBits = function (i) { + return 32 - Math.clz32(i); + }) + : (f.prototype._countBits = function (i) { + var a = i, + h2 = 0; + return a >= 4096 && ((h2 += 13), (a >>>= 13)), a >= 64 && ((h2 += 7), (a >>>= 7)), a >= 8 && ((h2 += 4), (a >>>= 4)), a >= 2 && ((h2 += 2), (a >>>= 2)), h2 + a; + }), + (f.prototype._zeroBits = function (i) { + if (i === 0) return 26; + var a = i, + h2 = 0; + return (a & 8191) === 0 && ((h2 += 13), (a >>>= 13)), (a & 127) === 0 && ((h2 += 7), (a >>>= 7)), (a & 15) === 0 && ((h2 += 4), (a >>>= 4)), (a & 3) === 0 && ((h2 += 2), (a >>>= 2)), (a & 1) === 0 && h2++, h2; + }), + (f.prototype.bitLength = function () { + var i = this.words[this.length - 1], + a = this._countBits(i); + return (this.length - 1) * 26 + a; + }); + function B(v) { + for (var i = new Array(v.bitLength()), a = 0; a < i.length; a++) { + var h2 = (a / 26) | 0, + s = a % 26; + i[a] = (v.words[h2] & (1 << s)) >>> s; + } + return i; + } + (f.prototype.zeroBits = function () { + if (this.isZero()) return 0; + for (var i = 0, a = 0; a < this.length; a++) { + var h2 = this._zeroBits(this.words[a]); + if (((i += h2), h2 !== 26)) break; + } + return i; + }), + (f.prototype.byteLength = function () { + return Math.ceil(this.bitLength() / 8); + }), + (f.prototype.toTwos = function (i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }), + (f.prototype.fromTwos = function (i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }), + (f.prototype.isNeg = function () { + return this.negative !== 0; + }), + (f.prototype.neg = function () { + return this.clone().ineg(); + }), + (f.prototype.ineg = function () { + return this.isZero() || (this.negative ^= 1), this; + }), + (f.prototype.iuor = function (i) { + for (; this.length < i.length; ) this.words[this.length++] = 0; + for (var a = 0; a < i.length; a++) this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }), + (f.prototype.ior = function (i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }), + (f.prototype.or = function (i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }), + (f.prototype.uor = function (i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }), + (f.prototype.iuand = function (i) { + var a; + this.length > i.length ? (a = i) : (a = this); + for (var h2 = 0; h2 < a.length; h2++) this.words[h2] = this.words[h2] & i.words[h2]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.iand = function (i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }), + (f.prototype.and = function (i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }), + (f.prototype.uand = function (i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }), + (f.prototype.iuxor = function (i) { + var a, h2; + this.length > i.length ? ((a = this), (h2 = i)) : ((a = i), (h2 = this)); + for (var s = 0; s < h2.length; s++) this.words[s] = a.words[s] ^ h2.words[s]; + if (this !== a) for (; s < a.length; s++) this.words[s] = a.words[s]; + return (this.length = a.length), this.strip(); + }), + (f.prototype.ixor = function (i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }), + (f.prototype.xor = function (i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }), + (f.prototype.uxor = function (i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }), + (f.prototype.inotn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = Math.ceil(i / 26) | 0, + h2 = i % 26; + this._expand(a), h2 > 0 && a--; + for (var s = 0; s < a; s++) this.words[s] = ~this.words[s] & 67108863; + return h2 > 0 && (this.words[s] = ~this.words[s] & (67108863 >> (26 - h2))), this.strip(); + }), + (f.prototype.notn = function (i) { + return this.clone().inotn(i); + }), + (f.prototype.setn = function (i, a) { + r(typeof i == 'number' && i >= 0); + var h2 = (i / 26) | 0, + s = i % 26; + return this._expand(h2 + 1), a ? (this.words[h2] = this.words[h2] | (1 << s)) : (this.words[h2] = this.words[h2] & ~(1 << s)), this.strip(); + }), + (f.prototype.iadd = function (i) { + var a; + if (this.negative !== 0 && i.negative === 0) return (this.negative = 0), (a = this.isub(i)), (this.negative ^= 1), this._normSign(); + if (this.negative === 0 && i.negative !== 0) return (i.negative = 0), (a = this.isub(i)), (i.negative = 1), a._normSign(); + var h2, s; + this.length > i.length ? ((h2 = this), (s = i)) : ((h2 = i), (s = this)); + for (var u = 0, c = 0; c < s.length; c++) (a = (h2.words[c] | 0) + (s.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + for (; u !== 0 && c < h2.length; c++) (a = (h2.words[c] | 0) + u), (this.words[c] = a & 67108863), (u = a >>> 26); + if (((this.length = h2.length), u !== 0)) (this.words[this.length] = u), this.length++; + else if (h2 !== this) for (; c < h2.length; c++) this.words[c] = h2.words[c]; + return this; + }), + (f.prototype.add = function (i) { + var a; + return i.negative !== 0 && this.negative === 0 + ? ((i.negative = 0), (a = this.sub(i)), (i.negative ^= 1), a) + : i.negative === 0 && this.negative !== 0 + ? ((this.negative = 0), (a = i.sub(this)), (this.negative = 1), a) + : this.length > i.length + ? this.clone().iadd(i) + : i.clone().iadd(this); + }), + (f.prototype.isub = function (i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return (i.negative = 1), a._normSign(); + } else if (this.negative !== 0) return (this.negative = 0), this.iadd(i), (this.negative = 1), this._normSign(); + var h2 = this.cmp(i); + if (h2 === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; + var s, u; + h2 > 0 ? ((s = this), (u = i)) : ((s = i), (u = this)); + for (var c = 0, b3 = 0; b3 < u.length; b3++) (a = (s.words[b3] | 0) - (u.words[b3] | 0) + c), (c = a >> 26), (this.words[b3] = a & 67108863); + for (; c !== 0 && b3 < s.length; b3++) (a = (s.words[b3] | 0) + c), (c = a >> 26), (this.words[b3] = a & 67108863); + if (c === 0 && b3 < s.length && s !== this) for (; b3 < s.length; b3++) this.words[b3] = s.words[b3]; + return (this.length = Math.max(this.length, b3)), s !== this && (this.negative = 1), this.strip(); + }), + (f.prototype.sub = function (i) { + return this.clone().isub(i); + }); + function q2(v, i, a) { + a.negative = i.negative ^ v.negative; + var h2 = (v.length + i.length) | 0; + (a.length = h2), (h2 = (h2 - 1) | 0); + var s = v.words[0] | 0, + u = i.words[0] | 0, + c = s * u, + b3 = c & 67108863, + l = (c / 67108864) | 0; + a.words[0] = b3; + for (var n = 1; n < h2; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _4 = Math.max(0, n - v.length + 1); _4 <= g; _4++) { + var A2 = (n - _4) | 0; + (s = v.words[A2] | 0), (u = i.words[_4] | 0), (c = s * u + w), (d += (c / 67108864) | 0), (w = c & 67108863); + } + (a.words[n] = w | 0), (l = d | 0); + } + return l !== 0 ? (a.words[n] = l | 0) : a.length--, a.strip(); + } + var L2 = function (i, a, h2) { + var s = i.words, + u = a.words, + c = h2.words, + b3 = 0, + l, + n, + d, + w = s[0] | 0, + g = w & 8191, + _4 = w >>> 13, + A2 = s[1] | 0, + R2 = A2 & 8191, + I = A2 >>> 13, + Me = s[2] | 0, + k = Me & 8191, + D2 = Me >>> 13, + nt = s[3] | 0, + C2 = nt & 8191, + O = nt >>> 13, + vt = s[4] | 0, + F = vt & 8191, + U = vt >>> 13, + bt = s[5] | 0, + z2 = bt & 8191, + H = bt >>> 13, + mt = s[6] | 0, + W = mt & 8191, + K = mt >>> 13, + gt = s[7] | 0, + j = gt & 8191, + Z = gt >>> 13, + yt = s[8] | 0, + V = yt & 8191, + $2 = yt >>> 13, + wt = s[9] | 0, + G = wt & 8191, + Y = wt >>> 13, + Mt = u[0] | 0, + X = Mt & 8191, + J = Mt >>> 13, + _t = u[1] | 0, + Q = _t & 8191, + ee = _t >>> 13, + xt = u[2] | 0, + te = xt & 8191, + re = xt >>> 13, + St = u[3] | 0, + ie = St & 8191, + ne = St >>> 13, + Et = u[4] | 0, + fe = Et & 8191, + ae = Et >>> 13, + At = u[5] | 0, + oe = At & 8191, + se = At >>> 13, + Rt = u[6] | 0, + he = Rt & 8191, + ue = Rt >>> 13, + Bt = u[7] | 0, + le = Bt & 8191, + de = Bt >>> 13, + qt = u[8] | 0, + ce = qt & 8191, + pe = qt >>> 13, + It = u[9] | 0, + ve = It & 8191, + be = It >>> 13; + (h2.negative = i.negative ^ a.negative), (h2.length = 19), (l = Math.imul(g, X)), (n = Math.imul(g, J)), (n = (n + Math.imul(_4, X)) | 0), (d = Math.imul(_4, J)); + var ft = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (ft >>> 26)) | 0), + (ft &= 67108863), + (l = Math.imul(R2, X)), + (n = Math.imul(R2, J)), + (n = (n + Math.imul(I, X)) | 0), + (d = Math.imul(I, J)), + (l = (l + Math.imul(g, Q)) | 0), + (n = (n + Math.imul(g, ee)) | 0), + (n = (n + Math.imul(_4, Q)) | 0), + (d = (d + Math.imul(_4, ee)) | 0); + var Be = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Be >>> 26)) | 0), + (Be &= 67108863), + (l = Math.imul(k, X)), + (n = Math.imul(k, J)), + (n = (n + Math.imul(D2, X)) | 0), + (d = Math.imul(D2, J)), + (l = (l + Math.imul(R2, Q)) | 0), + (n = (n + Math.imul(R2, ee)) | 0), + (n = (n + Math.imul(I, Q)) | 0), + (d = (d + Math.imul(I, ee)) | 0), + (l = (l + Math.imul(g, te)) | 0), + (n = (n + Math.imul(g, re)) | 0), + (n = (n + Math.imul(_4, te)) | 0), + (d = (d + Math.imul(_4, re)) | 0); + var qe = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (qe >>> 26)) | 0), + (qe &= 67108863), + (l = Math.imul(C2, X)), + (n = Math.imul(C2, J)), + (n = (n + Math.imul(O, X)) | 0), + (d = Math.imul(O, J)), + (l = (l + Math.imul(k, Q)) | 0), + (n = (n + Math.imul(k, ee)) | 0), + (n = (n + Math.imul(D2, Q)) | 0), + (d = (d + Math.imul(D2, ee)) | 0), + (l = (l + Math.imul(R2, te)) | 0), + (n = (n + Math.imul(R2, re)) | 0), + (n = (n + Math.imul(I, te)) | 0), + (d = (d + Math.imul(I, re)) | 0), + (l = (l + Math.imul(g, ie)) | 0), + (n = (n + Math.imul(g, ne)) | 0), + (n = (n + Math.imul(_4, ie)) | 0), + (d = (d + Math.imul(_4, ne)) | 0); + var ze = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (ze >>> 26)) | 0), + (ze &= 67108863), + (l = Math.imul(F, X)), + (n = Math.imul(F, J)), + (n = (n + Math.imul(U, X)) | 0), + (d = Math.imul(U, J)), + (l = (l + Math.imul(C2, Q)) | 0), + (n = (n + Math.imul(C2, ee)) | 0), + (n = (n + Math.imul(O, Q)) | 0), + (d = (d + Math.imul(O, ee)) | 0), + (l = (l + Math.imul(k, te)) | 0), + (n = (n + Math.imul(k, re)) | 0), + (n = (n + Math.imul(D2, te)) | 0), + (d = (d + Math.imul(D2, re)) | 0), + (l = (l + Math.imul(R2, ie)) | 0), + (n = (n + Math.imul(R2, ne)) | 0), + (n = (n + Math.imul(I, ie)) | 0), + (d = (d + Math.imul(I, ne)) | 0), + (l = (l + Math.imul(g, fe)) | 0), + (n = (n + Math.imul(g, ae)) | 0), + (n = (n + Math.imul(_4, fe)) | 0), + (d = (d + Math.imul(_4, ae)) | 0); + var He = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (He >>> 26)) | 0), + (He &= 67108863), + (l = Math.imul(z2, X)), + (n = Math.imul(z2, J)), + (n = (n + Math.imul(H, X)) | 0), + (d = Math.imul(H, J)), + (l = (l + Math.imul(F, Q)) | 0), + (n = (n + Math.imul(F, ee)) | 0), + (n = (n + Math.imul(U, Q)) | 0), + (d = (d + Math.imul(U, ee)) | 0), + (l = (l + Math.imul(C2, te)) | 0), + (n = (n + Math.imul(C2, re)) | 0), + (n = (n + Math.imul(O, te)) | 0), + (d = (d + Math.imul(O, re)) | 0), + (l = (l + Math.imul(k, ie)) | 0), + (n = (n + Math.imul(k, ne)) | 0), + (n = (n + Math.imul(D2, ie)) | 0), + (d = (d + Math.imul(D2, ne)) | 0), + (l = (l + Math.imul(R2, fe)) | 0), + (n = (n + Math.imul(R2, ae)) | 0), + (n = (n + Math.imul(I, fe)) | 0), + (d = (d + Math.imul(I, ae)) | 0), + (l = (l + Math.imul(g, oe)) | 0), + (n = (n + Math.imul(g, se)) | 0), + (n = (n + Math.imul(_4, oe)) | 0), + (d = (d + Math.imul(_4, se)) | 0); + var We = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (We >>> 26)) | 0), + (We &= 67108863), + (l = Math.imul(W, X)), + (n = Math.imul(W, J)), + (n = (n + Math.imul(K, X)) | 0), + (d = Math.imul(K, J)), + (l = (l + Math.imul(z2, Q)) | 0), + (n = (n + Math.imul(z2, ee)) | 0), + (n = (n + Math.imul(H, Q)) | 0), + (d = (d + Math.imul(H, ee)) | 0), + (l = (l + Math.imul(F, te)) | 0), + (n = (n + Math.imul(F, re)) | 0), + (n = (n + Math.imul(U, te)) | 0), + (d = (d + Math.imul(U, re)) | 0), + (l = (l + Math.imul(C2, ie)) | 0), + (n = (n + Math.imul(C2, ne)) | 0), + (n = (n + Math.imul(O, ie)) | 0), + (d = (d + Math.imul(O, ne)) | 0), + (l = (l + Math.imul(k, fe)) | 0), + (n = (n + Math.imul(k, ae)) | 0), + (n = (n + Math.imul(D2, fe)) | 0), + (d = (d + Math.imul(D2, ae)) | 0), + (l = (l + Math.imul(R2, oe)) | 0), + (n = (n + Math.imul(R2, se)) | 0), + (n = (n + Math.imul(I, oe)) | 0), + (d = (d + Math.imul(I, se)) | 0), + (l = (l + Math.imul(g, he)) | 0), + (n = (n + Math.imul(g, ue)) | 0), + (n = (n + Math.imul(_4, he)) | 0), + (d = (d + Math.imul(_4, ue)) | 0); + var Ke = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ke >>> 26)) | 0), + (Ke &= 67108863), + (l = Math.imul(j, X)), + (n = Math.imul(j, J)), + (n = (n + Math.imul(Z, X)) | 0), + (d = Math.imul(Z, J)), + (l = (l + Math.imul(W, Q)) | 0), + (n = (n + Math.imul(W, ee)) | 0), + (n = (n + Math.imul(K, Q)) | 0), + (d = (d + Math.imul(K, ee)) | 0), + (l = (l + Math.imul(z2, te)) | 0), + (n = (n + Math.imul(z2, re)) | 0), + (n = (n + Math.imul(H, te)) | 0), + (d = (d + Math.imul(H, re)) | 0), + (l = (l + Math.imul(F, ie)) | 0), + (n = (n + Math.imul(F, ne)) | 0), + (n = (n + Math.imul(U, ie)) | 0), + (d = (d + Math.imul(U, ne)) | 0), + (l = (l + Math.imul(C2, fe)) | 0), + (n = (n + Math.imul(C2, ae)) | 0), + (n = (n + Math.imul(O, fe)) | 0), + (d = (d + Math.imul(O, ae)) | 0), + (l = (l + Math.imul(k, oe)) | 0), + (n = (n + Math.imul(k, se)) | 0), + (n = (n + Math.imul(D2, oe)) | 0), + (d = (d + Math.imul(D2, se)) | 0), + (l = (l + Math.imul(R2, he)) | 0), + (n = (n + Math.imul(R2, ue)) | 0), + (n = (n + Math.imul(I, he)) | 0), + (d = (d + Math.imul(I, ue)) | 0), + (l = (l + Math.imul(g, le)) | 0), + (n = (n + Math.imul(g, de)) | 0), + (n = (n + Math.imul(_4, le)) | 0), + (d = (d + Math.imul(_4, de)) | 0); + var je = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (je >>> 26)) | 0), + (je &= 67108863), + (l = Math.imul(V, X)), + (n = Math.imul(V, J)), + (n = (n + Math.imul($2, X)) | 0), + (d = Math.imul($2, J)), + (l = (l + Math.imul(j, Q)) | 0), + (n = (n + Math.imul(j, ee)) | 0), + (n = (n + Math.imul(Z, Q)) | 0), + (d = (d + Math.imul(Z, ee)) | 0), + (l = (l + Math.imul(W, te)) | 0), + (n = (n + Math.imul(W, re)) | 0), + (n = (n + Math.imul(K, te)) | 0), + (d = (d + Math.imul(K, re)) | 0), + (l = (l + Math.imul(z2, ie)) | 0), + (n = (n + Math.imul(z2, ne)) | 0), + (n = (n + Math.imul(H, ie)) | 0), + (d = (d + Math.imul(H, ne)) | 0), + (l = (l + Math.imul(F, fe)) | 0), + (n = (n + Math.imul(F, ae)) | 0), + (n = (n + Math.imul(U, fe)) | 0), + (d = (d + Math.imul(U, ae)) | 0), + (l = (l + Math.imul(C2, oe)) | 0), + (n = (n + Math.imul(C2, se)) | 0), + (n = (n + Math.imul(O, oe)) | 0), + (d = (d + Math.imul(O, se)) | 0), + (l = (l + Math.imul(k, he)) | 0), + (n = (n + Math.imul(k, ue)) | 0), + (n = (n + Math.imul(D2, he)) | 0), + (d = (d + Math.imul(D2, ue)) | 0), + (l = (l + Math.imul(R2, le)) | 0), + (n = (n + Math.imul(R2, de)) | 0), + (n = (n + Math.imul(I, le)) | 0), + (d = (d + Math.imul(I, de)) | 0), + (l = (l + Math.imul(g, ce)) | 0), + (n = (n + Math.imul(g, pe)) | 0), + (n = (n + Math.imul(_4, ce)) | 0), + (d = (d + Math.imul(_4, pe)) | 0); + var Ze = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ze >>> 26)) | 0), + (Ze &= 67108863), + (l = Math.imul(G, X)), + (n = Math.imul(G, J)), + (n = (n + Math.imul(Y, X)) | 0), + (d = Math.imul(Y, J)), + (l = (l + Math.imul(V, Q)) | 0), + (n = (n + Math.imul(V, ee)) | 0), + (n = (n + Math.imul($2, Q)) | 0), + (d = (d + Math.imul($2, ee)) | 0), + (l = (l + Math.imul(j, te)) | 0), + (n = (n + Math.imul(j, re)) | 0), + (n = (n + Math.imul(Z, te)) | 0), + (d = (d + Math.imul(Z, re)) | 0), + (l = (l + Math.imul(W, ie)) | 0), + (n = (n + Math.imul(W, ne)) | 0), + (n = (n + Math.imul(K, ie)) | 0), + (d = (d + Math.imul(K, ne)) | 0), + (l = (l + Math.imul(z2, fe)) | 0), + (n = (n + Math.imul(z2, ae)) | 0), + (n = (n + Math.imul(H, fe)) | 0), + (d = (d + Math.imul(H, ae)) | 0), + (l = (l + Math.imul(F, oe)) | 0), + (n = (n + Math.imul(F, se)) | 0), + (n = (n + Math.imul(U, oe)) | 0), + (d = (d + Math.imul(U, se)) | 0), + (l = (l + Math.imul(C2, he)) | 0), + (n = (n + Math.imul(C2, ue)) | 0), + (n = (n + Math.imul(O, he)) | 0), + (d = (d + Math.imul(O, ue)) | 0), + (l = (l + Math.imul(k, le)) | 0), + (n = (n + Math.imul(k, de)) | 0), + (n = (n + Math.imul(D2, le)) | 0), + (d = (d + Math.imul(D2, de)) | 0), + (l = (l + Math.imul(R2, ce)) | 0), + (n = (n + Math.imul(R2, pe)) | 0), + (n = (n + Math.imul(I, ce)) | 0), + (d = (d + Math.imul(I, pe)) | 0), + (l = (l + Math.imul(g, ve)) | 0), + (n = (n + Math.imul(g, be)) | 0), + (n = (n + Math.imul(_4, ve)) | 0), + (d = (d + Math.imul(_4, be)) | 0); + var Ve = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ve >>> 26)) | 0), + (Ve &= 67108863), + (l = Math.imul(G, Q)), + (n = Math.imul(G, ee)), + (n = (n + Math.imul(Y, Q)) | 0), + (d = Math.imul(Y, ee)), + (l = (l + Math.imul(V, te)) | 0), + (n = (n + Math.imul(V, re)) | 0), + (n = (n + Math.imul($2, te)) | 0), + (d = (d + Math.imul($2, re)) | 0), + (l = (l + Math.imul(j, ie)) | 0), + (n = (n + Math.imul(j, ne)) | 0), + (n = (n + Math.imul(Z, ie)) | 0), + (d = (d + Math.imul(Z, ne)) | 0), + (l = (l + Math.imul(W, fe)) | 0), + (n = (n + Math.imul(W, ae)) | 0), + (n = (n + Math.imul(K, fe)) | 0), + (d = (d + Math.imul(K, ae)) | 0), + (l = (l + Math.imul(z2, oe)) | 0), + (n = (n + Math.imul(z2, se)) | 0), + (n = (n + Math.imul(H, oe)) | 0), + (d = (d + Math.imul(H, se)) | 0), + (l = (l + Math.imul(F, he)) | 0), + (n = (n + Math.imul(F, ue)) | 0), + (n = (n + Math.imul(U, he)) | 0), + (d = (d + Math.imul(U, ue)) | 0), + (l = (l + Math.imul(C2, le)) | 0), + (n = (n + Math.imul(C2, de)) | 0), + (n = (n + Math.imul(O, le)) | 0), + (d = (d + Math.imul(O, de)) | 0), + (l = (l + Math.imul(k, ce)) | 0), + (n = (n + Math.imul(k, pe)) | 0), + (n = (n + Math.imul(D2, ce)) | 0), + (d = (d + Math.imul(D2, pe)) | 0), + (l = (l + Math.imul(R2, ve)) | 0), + (n = (n + Math.imul(R2, be)) | 0), + (n = (n + Math.imul(I, ve)) | 0), + (d = (d + Math.imul(I, be)) | 0); + var $e = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + ($e >>> 26)) | 0), + ($e &= 67108863), + (l = Math.imul(G, te)), + (n = Math.imul(G, re)), + (n = (n + Math.imul(Y, te)) | 0), + (d = Math.imul(Y, re)), + (l = (l + Math.imul(V, ie)) | 0), + (n = (n + Math.imul(V, ne)) | 0), + (n = (n + Math.imul($2, ie)) | 0), + (d = (d + Math.imul($2, ne)) | 0), + (l = (l + Math.imul(j, fe)) | 0), + (n = (n + Math.imul(j, ae)) | 0), + (n = (n + Math.imul(Z, fe)) | 0), + (d = (d + Math.imul(Z, ae)) | 0), + (l = (l + Math.imul(W, oe)) | 0), + (n = (n + Math.imul(W, se)) | 0), + (n = (n + Math.imul(K, oe)) | 0), + (d = (d + Math.imul(K, se)) | 0), + (l = (l + Math.imul(z2, he)) | 0), + (n = (n + Math.imul(z2, ue)) | 0), + (n = (n + Math.imul(H, he)) | 0), + (d = (d + Math.imul(H, ue)) | 0), + (l = (l + Math.imul(F, le)) | 0), + (n = (n + Math.imul(F, de)) | 0), + (n = (n + Math.imul(U, le)) | 0), + (d = (d + Math.imul(U, de)) | 0), + (l = (l + Math.imul(C2, ce)) | 0), + (n = (n + Math.imul(C2, pe)) | 0), + (n = (n + Math.imul(O, ce)) | 0), + (d = (d + Math.imul(O, pe)) | 0), + (l = (l + Math.imul(k, ve)) | 0), + (n = (n + Math.imul(k, be)) | 0), + (n = (n + Math.imul(D2, ve)) | 0), + (d = (d + Math.imul(D2, be)) | 0); + var Ge = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ge >>> 26)) | 0), + (Ge &= 67108863), + (l = Math.imul(G, ie)), + (n = Math.imul(G, ne)), + (n = (n + Math.imul(Y, ie)) | 0), + (d = Math.imul(Y, ne)), + (l = (l + Math.imul(V, fe)) | 0), + (n = (n + Math.imul(V, ae)) | 0), + (n = (n + Math.imul($2, fe)) | 0), + (d = (d + Math.imul($2, ae)) | 0), + (l = (l + Math.imul(j, oe)) | 0), + (n = (n + Math.imul(j, se)) | 0), + (n = (n + Math.imul(Z, oe)) | 0), + (d = (d + Math.imul(Z, se)) | 0), + (l = (l + Math.imul(W, he)) | 0), + (n = (n + Math.imul(W, ue)) | 0), + (n = (n + Math.imul(K, he)) | 0), + (d = (d + Math.imul(K, ue)) | 0), + (l = (l + Math.imul(z2, le)) | 0), + (n = (n + Math.imul(z2, de)) | 0), + (n = (n + Math.imul(H, le)) | 0), + (d = (d + Math.imul(H, de)) | 0), + (l = (l + Math.imul(F, ce)) | 0), + (n = (n + Math.imul(F, pe)) | 0), + (n = (n + Math.imul(U, ce)) | 0), + (d = (d + Math.imul(U, pe)) | 0), + (l = (l + Math.imul(C2, ve)) | 0), + (n = (n + Math.imul(C2, be)) | 0), + (n = (n + Math.imul(O, ve)) | 0), + (d = (d + Math.imul(O, be)) | 0); + var Ye = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Ye >>> 26)) | 0), + (Ye &= 67108863), + (l = Math.imul(G, fe)), + (n = Math.imul(G, ae)), + (n = (n + Math.imul(Y, fe)) | 0), + (d = Math.imul(Y, ae)), + (l = (l + Math.imul(V, oe)) | 0), + (n = (n + Math.imul(V, se)) | 0), + (n = (n + Math.imul($2, oe)) | 0), + (d = (d + Math.imul($2, se)) | 0), + (l = (l + Math.imul(j, he)) | 0), + (n = (n + Math.imul(j, ue)) | 0), + (n = (n + Math.imul(Z, he)) | 0), + (d = (d + Math.imul(Z, ue)) | 0), + (l = (l + Math.imul(W, le)) | 0), + (n = (n + Math.imul(W, de)) | 0), + (n = (n + Math.imul(K, le)) | 0), + (d = (d + Math.imul(K, de)) | 0), + (l = (l + Math.imul(z2, ce)) | 0), + (n = (n + Math.imul(z2, pe)) | 0), + (n = (n + Math.imul(H, ce)) | 0), + (d = (d + Math.imul(H, pe)) | 0), + (l = (l + Math.imul(F, ve)) | 0), + (n = (n + Math.imul(F, be)) | 0), + (n = (n + Math.imul(U, ve)) | 0), + (d = (d + Math.imul(U, be)) | 0); + var Xe = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Xe >>> 26)) | 0), + (Xe &= 67108863), + (l = Math.imul(G, oe)), + (n = Math.imul(G, se)), + (n = (n + Math.imul(Y, oe)) | 0), + (d = Math.imul(Y, se)), + (l = (l + Math.imul(V, he)) | 0), + (n = (n + Math.imul(V, ue)) | 0), + (n = (n + Math.imul($2, he)) | 0), + (d = (d + Math.imul($2, ue)) | 0), + (l = (l + Math.imul(j, le)) | 0), + (n = (n + Math.imul(j, de)) | 0), + (n = (n + Math.imul(Z, le)) | 0), + (d = (d + Math.imul(Z, de)) | 0), + (l = (l + Math.imul(W, ce)) | 0), + (n = (n + Math.imul(W, pe)) | 0), + (n = (n + Math.imul(K, ce)) | 0), + (d = (d + Math.imul(K, pe)) | 0), + (l = (l + Math.imul(z2, ve)) | 0), + (n = (n + Math.imul(z2, be)) | 0), + (n = (n + Math.imul(H, ve)) | 0), + (d = (d + Math.imul(H, be)) | 0); + var Je = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Je >>> 26)) | 0), + (Je &= 67108863), + (l = Math.imul(G, he)), + (n = Math.imul(G, ue)), + (n = (n + Math.imul(Y, he)) | 0), + (d = Math.imul(Y, ue)), + (l = (l + Math.imul(V, le)) | 0), + (n = (n + Math.imul(V, de)) | 0), + (n = (n + Math.imul($2, le)) | 0), + (d = (d + Math.imul($2, de)) | 0), + (l = (l + Math.imul(j, ce)) | 0), + (n = (n + Math.imul(j, pe)) | 0), + (n = (n + Math.imul(Z, ce)) | 0), + (d = (d + Math.imul(Z, pe)) | 0), + (l = (l + Math.imul(W, ve)) | 0), + (n = (n + Math.imul(W, be)) | 0), + (n = (n + Math.imul(K, ve)) | 0), + (d = (d + Math.imul(K, be)) | 0); + var Qe = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (Qe >>> 26)) | 0), + (Qe &= 67108863), + (l = Math.imul(G, le)), + (n = Math.imul(G, de)), + (n = (n + Math.imul(Y, le)) | 0), + (d = Math.imul(Y, de)), + (l = (l + Math.imul(V, ce)) | 0), + (n = (n + Math.imul(V, pe)) | 0), + (n = (n + Math.imul($2, ce)) | 0), + (d = (d + Math.imul($2, pe)) | 0), + (l = (l + Math.imul(j, ve)) | 0), + (n = (n + Math.imul(j, be)) | 0), + (n = (n + Math.imul(Z, ve)) | 0), + (d = (d + Math.imul(Z, be)) | 0); + var et = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (et >>> 26)) | 0), + (et &= 67108863), + (l = Math.imul(G, ce)), + (n = Math.imul(G, pe)), + (n = (n + Math.imul(Y, ce)) | 0), + (d = Math.imul(Y, pe)), + (l = (l + Math.imul(V, ve)) | 0), + (n = (n + Math.imul(V, be)) | 0), + (n = (n + Math.imul($2, ve)) | 0), + (d = (d + Math.imul($2, be)) | 0); + var tt = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + (b3 = (((d + (n >>> 13)) | 0) + (tt >>> 26)) | 0), (tt &= 67108863), (l = Math.imul(G, ve)), (n = Math.imul(G, be)), (n = (n + Math.imul(Y, ve)) | 0), (d = Math.imul(Y, be)); + var rt = (((b3 + l) | 0) + ((n & 8191) << 13)) | 0; + return ( + (b3 = (((d + (n >>> 13)) | 0) + (rt >>> 26)) | 0), + (rt &= 67108863), + (c[0] = ft), + (c[1] = Be), + (c[2] = qe), + (c[3] = ze), + (c[4] = He), + (c[5] = We), + (c[6] = Ke), + (c[7] = je), + (c[8] = Ze), + (c[9] = Ve), + (c[10] = $e), + (c[11] = Ge), + (c[12] = Ye), + (c[13] = Xe), + (c[14] = Je), + (c[15] = Qe), + (c[16] = et), + (c[17] = tt), + (c[18] = rt), + b3 !== 0 && ((c[19] = b3), h2.length++), + h2 + ); + }; + Math.imul || (L2 = q2); + function ge(v, i, a) { + (a.negative = i.negative ^ v.negative), (a.length = v.length + i.length); + for (var h2 = 0, s = 0, u = 0; u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b3 = h2 & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1); n <= l; n++) { + var d = u - n, + w = v.words[d] | 0, + g = i.words[n] | 0, + _4 = w * g, + A2 = _4 & 67108863; + (c = (c + ((_4 / 67108864) | 0)) | 0), (A2 = (A2 + b3) | 0), (b3 = A2 & 67108863), (c = (c + (A2 >>> 26)) | 0), (s += c >>> 26), (c &= 67108863); + } + (a.words[u] = b3), (h2 = c), (c = s); + } + return h2 !== 0 ? (a.words[u] = h2) : a.length--, a.strip(); + } + function _e(v, i, a) { + var h2 = new N(); + return h2.mulp(v, i, a); + } + f.prototype.mulTo = function (i, a) { + var h2, + s = this.length + i.length; + return this.length === 10 && i.length === 10 ? (h2 = L2(this, i, a)) : s < 63 ? (h2 = q2(this, i, a)) : s < 1024 ? (h2 = ge(this, i, a)) : (h2 = _e(this, i, a)), h2; + }; + function N(v, i) { + (this.x = v), (this.y = i); + } + (N.prototype.makeRBT = function (i) { + for (var a = new Array(i), h2 = f.prototype._countBits(i) - 1, s = 0; s < i; s++) a[s] = this.revBin(s, h2, i); + return a; + }), + (N.prototype.revBin = function (i, a, h2) { + if (i === 0 || i === h2 - 1) return i; + for (var s = 0, u = 0; u < a; u++) (s |= (i & 1) << (a - u - 1)), (i >>= 1); + return s; + }), + (N.prototype.permute = function (i, a, h2, s, u, c) { + for (var b3 = 0; b3 < c; b3++) (s[b3] = a[i[b3]]), (u[b3] = h2[i[b3]]); + }), + (N.prototype.transform = function (i, a, h2, s, u, c) { + this.permute(c, i, a, h2, s, u); + for (var b3 = 1; b3 < u; b3 <<= 1) + for (var l = b3 << 1, n = Math.cos((2 * Math.PI) / l), d = Math.sin((2 * Math.PI) / l), w = 0; w < u; w += l) + for (var g = n, _4 = d, A2 = 0; A2 < b3; A2++) { + var R2 = h2[w + A2], + I = s[w + A2], + Me = h2[w + A2 + b3], + k = s[w + A2 + b3], + D2 = g * Me - _4 * k; + (k = g * k + _4 * Me), (Me = D2), (h2[w + A2] = R2 + Me), (s[w + A2] = I + k), (h2[w + A2 + b3] = R2 - Me), (s[w + A2 + b3] = I - k), A2 !== l && ((D2 = n * g - d * _4), (_4 = n * _4 + d * g), (g = D2)); + } + }), + (N.prototype.guessLen13b = function (i, a) { + var h2 = Math.max(a, i) | 1, + s = h2 & 1, + u = 0; + for (h2 = (h2 / 2) | 0; h2; h2 = h2 >>> 1) u++; + return 1 << (u + 1 + s); + }), + (N.prototype.conjugate = function (i, a, h2) { + if (!(h2 <= 1)) + for (var s = 0; s < h2 / 2; s++) { + var u = i[s]; + (i[s] = i[h2 - s - 1]), (i[h2 - s - 1] = u), (u = a[s]), (a[s] = -a[h2 - s - 1]), (a[h2 - s - 1] = -u); + } + }), + (N.prototype.normalize13b = function (i, a) { + for (var h2 = 0, s = 0; s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h2; + (i[s] = u & 67108863), u < 67108864 ? (h2 = 0) : (h2 = (u / 67108864) | 0); + } + return i; + }), + (N.prototype.convert13b = function (i, a, h2, s) { + for (var u = 0, c = 0; c < a; c++) (u = u + (i[c] | 0)), (h2[2 * c] = u & 8191), (u = u >>> 13), (h2[2 * c + 1] = u & 8191), (u = u >>> 13); + for (c = 2 * a; c < s; ++c) h2[c] = 0; + r(u === 0), r((u & -8192) === 0); + }), + (N.prototype.stub = function (i) { + for (var a = new Array(i), h2 = 0; h2 < i; h2++) a[h2] = 0; + return a; + }), + (N.prototype.mulp = function (i, a, h2) { + var s = 2 * this.guessLen13b(i.length, a.length), + u = this.makeRBT(s), + c = this.stub(s), + b3 = new Array(s), + l = new Array(s), + n = new Array(s), + d = new Array(s), + w = new Array(s), + g = new Array(s), + _4 = h2.words; + (_4.length = s), this.convert13b(i.words, i.length, b3, s), this.convert13b(a.words, a.length, d, s), this.transform(b3, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A2 = 0; A2 < s; A2++) { + var R2 = l[A2] * w[A2] - n[A2] * g[A2]; + (n[A2] = l[A2] * g[A2] + n[A2] * w[A2]), (l[A2] = R2); + } + return this.conjugate(l, n, s), this.transform(l, n, _4, c, s, u), this.conjugate(_4, c, s), this.normalize13b(_4, s), (h2.negative = i.negative ^ a.negative), (h2.length = i.length + a.length), h2.strip(); + }), + (f.prototype.mul = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), this.mulTo(i, a); + }), + (f.prototype.mulf = function (i) { + var a = new f(null); + return (a.words = new Array(this.length + i.length)), _e(this, i, a); + }), + (f.prototype.imul = function (i) { + return this.clone().mulTo(i, this); + }), + (f.prototype.imuln = function (i) { + r(typeof i == 'number'), r(i < 67108864); + for (var a = 0, h2 = 0; h2 < this.length; h2++) { + var s = (this.words[h2] | 0) * i, + u = (s & 67108863) + (a & 67108863); + (a >>= 26), (a += (s / 67108864) | 0), (a += u >>> 26), (this.words[h2] = u & 67108863); + } + return a !== 0 && ((this.words[h2] = a), this.length++), this; + }), + (f.prototype.muln = function (i) { + return this.clone().imuln(i); + }), + (f.prototype.sqr = function () { + return this.mul(this); + }), + (f.prototype.isqr = function () { + return this.imul(this.clone()); + }), + (f.prototype.pow = function (i) { + var a = B(i); + if (a.length === 0) return new f(1); + for (var h2 = this, s = 0; s < a.length && a[s] === 0; s++, h2 = h2.sqr()); + if (++s < a.length) for (var u = h2.sqr(); s < a.length; s++, u = u.sqr()) a[s] !== 0 && (h2 = h2.mul(u)); + return h2; + }), + (f.prototype.iushln = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26, + s = (67108863 >>> (26 - a)) << (26 - a), + u; + if (a !== 0) { + var c = 0; + for (u = 0; u < this.length; u++) { + var b3 = this.words[u] & s, + l = ((this.words[u] | 0) - b3) << a; + (this.words[u] = l | c), (c = b3 >>> (26 - a)); + } + c && ((this.words[u] = c), this.length++); + } + if (h2 !== 0) { + for (u = this.length - 1; u >= 0; u--) this.words[u + h2] = this.words[u]; + for (u = 0; u < h2; u++) this.words[u] = 0; + this.length += h2; + } + return this.strip(); + }), + (f.prototype.ishln = function (i) { + return r(this.negative === 0), this.iushln(i); + }), + (f.prototype.iushrn = function (i, a, h2) { + r(typeof i == 'number' && i >= 0); + var s; + a ? (s = (a - (a % 26)) / 26) : (s = 0); + var u = i % 26, + c = Math.min((i - u) / 26, this.length), + b3 = 67108863 ^ ((67108863 >>> u) << u), + l = h2; + if (((s -= c), (s = Math.max(0, s)), l)) { + for (var n = 0; n < c; n++) l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) for (this.length -= c, n = 0; n < this.length; n++) this.words[n] = this.words[n + c]; + else (this.words[0] = 0), (this.length = 1); + var d = 0; + for (n = this.length - 1; n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + (this.words[n] = (d << (26 - u)) | (w >>> u)), (d = w & b3); + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && ((this.words[0] = 0), (this.length = 1)), this.strip(); + }), + (f.prototype.ishrn = function (i, a, h2) { + return r(this.negative === 0), this.iushrn(i, a, h2); + }), + (f.prototype.shln = function (i) { + return this.clone().ishln(i); + }), + (f.prototype.ushln = function (i) { + return this.clone().iushln(i); + }), + (f.prototype.shrn = function (i) { + return this.clone().ishrn(i); + }), + (f.prototype.ushrn = function (i) { + return this.clone().iushrn(i); + }), + (f.prototype.testn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26, + s = 1 << a; + if (this.length <= h2) return false; + var u = this.words[h2]; + return !!(u & s); + }), + (f.prototype.imaskn = function (i) { + r(typeof i == 'number' && i >= 0); + var a = i % 26, + h2 = (i - a) / 26; + if ((r(this.negative === 0, 'imaskn works only with positive numbers'), this.length <= h2)) return this; + if ((a !== 0 && h2++, (this.length = Math.min(h2, this.length)), a !== 0)) { + var s = 67108863 ^ ((67108863 >>> a) << a); + this.words[this.length - 1] &= s; + } + return this.strip(); + }), + (f.prototype.maskn = function (i) { + return this.clone().imaskn(i); + }), + (f.prototype.iaddn = function (i) { + return ( + r(typeof i == 'number'), + r(i < 67108864), + i < 0 + ? this.isubn(-i) + : this.negative !== 0 + ? this.length === 1 && (this.words[0] | 0) < i + ? ((this.words[0] = i - (this.words[0] | 0)), (this.negative = 0), this) + : ((this.negative = 0), this.isubn(i), (this.negative = 1), this) + : this._iaddn(i) + ); + }), + (f.prototype._iaddn = function (i) { + this.words[0] += i; + for (var a = 0; a < this.length && this.words[a] >= 67108864; a++) (this.words[a] -= 67108864), a === this.length - 1 ? (this.words[a + 1] = 1) : this.words[a + 1]++; + return (this.length = Math.max(this.length, a + 1)), this; + }), + (f.prototype.isubn = function (i) { + if ((r(typeof i == 'number'), r(i < 67108864), i < 0)) return this.iaddn(-i); + if (this.negative !== 0) return (this.negative = 0), this.iaddn(i), (this.negative = 1), this; + if (((this.words[0] -= i), this.length === 1 && this.words[0] < 0)) (this.words[0] = -this.words[0]), (this.negative = 1); + else for (var a = 0; a < this.length && this.words[a] < 0; a++) (this.words[a] += 67108864), (this.words[a + 1] -= 1); + return this.strip(); + }), + (f.prototype.addn = function (i) { + return this.clone().iaddn(i); + }), + (f.prototype.subn = function (i) { + return this.clone().isubn(i); + }), + (f.prototype.iabs = function () { + return (this.negative = 0), this; + }), + (f.prototype.abs = function () { + return this.clone().iabs(); + }), + (f.prototype._ishlnsubmul = function (i, a, h2) { + var s = i.length + h2, + u; + this._expand(s); + var c, + b3 = 0; + for (u = 0; u < i.length; u++) { + c = (this.words[u + h2] | 0) + b3; + var l = (i.words[u] | 0) * a; + (c -= l & 67108863), (b3 = (c >> 26) - ((l / 67108864) | 0)), (this.words[u + h2] = c & 67108863); + } + for (; u < this.length - h2; u++) (c = (this.words[u + h2] | 0) + b3), (b3 = c >> 26), (this.words[u + h2] = c & 67108863); + if (b3 === 0) return this.strip(); + for (r(b3 === -1), b3 = 0, u = 0; u < this.length; u++) (c = -(this.words[u] | 0) + b3), (b3 = c >> 26), (this.words[u] = c & 67108863); + return (this.negative = 1), this.strip(); + }), + (f.prototype._wordDiv = function (i, a) { + var h2 = this.length - i.length, + s = this.clone(), + u = i, + c = u.words[u.length - 1] | 0, + b3 = this._countBits(c); + (h2 = 26 - b3), h2 !== 0 && ((u = u.ushln(h2)), s.iushln(h2), (c = u.words[u.length - 1] | 0)); + var l = s.length - u.length, + n; + if (a !== 'mod') { + (n = new f(null)), (n.length = l + 1), (n.words = new Array(n.length)); + for (var d = 0; d < n.length; d++) n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && ((s = w), n && (n.words[l] = 1)); + for (var g = l - 1; g >= 0; g--) { + var _4 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_4 = Math.min((_4 / c) | 0, 67108863), s._ishlnsubmul(u, _4, g); s.negative !== 0; ) _4--, (s.negative = 0), s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _4); + } + return n && n.strip(), s.strip(), a !== 'div' && h2 !== 0 && s.iushrn(h2), {div: n || null, mod: s}; + }), + (f.prototype.divmod = function (i, a, h2) { + if ((r(!i.isZero()), this.isZero())) return {div: new f(0), mod: new f(0)}; + var s, u, c; + return this.negative !== 0 && i.negative === 0 + ? ((c = this.neg().divmod(i, a)), a !== 'mod' && (s = c.div.neg()), a !== 'div' && ((u = c.mod.neg()), h2 && u.negative !== 0 && u.iadd(i)), {div: s, mod: u}) + : this.negative === 0 && i.negative !== 0 + ? ((c = this.divmod(i.neg(), a)), a !== 'mod' && (s = c.div.neg()), {div: s, mod: c.mod}) + : (this.negative & i.negative) !== 0 + ? ((c = this.neg().divmod(i.neg(), a)), a !== 'div' && ((u = c.mod.neg()), h2 && u.negative !== 0 && u.isub(i)), {div: c.div, mod: u}) + : i.length > this.length || this.cmp(i) < 0 + ? {div: new f(0), mod: this} + : i.length === 1 + ? a === 'div' + ? {div: this.divn(i.words[0]), mod: null} + : a === 'mod' + ? {div: null, mod: new f(this.modn(i.words[0]))} + : {div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0]))} + : this._wordDiv(i, a); + }), + (f.prototype.div = function (i) { + return this.divmod(i, 'div', false).div; + }), + (f.prototype.mod = function (i) { + return this.divmod(i, 'mod', false).mod; + }), + (f.prototype.umod = function (i) { + return this.divmod(i, 'mod', true).mod; + }), + (f.prototype.divRound = function (i) { + var a = this.divmod(i); + if (a.mod.isZero()) return a.div; + var h2 = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, + s = i.ushrn(1), + u = i.andln(1), + c = h2.cmp(s); + return c < 0 || (u === 1 && c === 0) ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }), + (f.prototype.modn = function (i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h2 = 0, s = this.length - 1; s >= 0; s--) h2 = (a * h2 + (this.words[s] | 0)) % i; + return h2; + }), + (f.prototype.idivn = function (i) { + r(i <= 67108863); + for (var a = 0, h2 = this.length - 1; h2 >= 0; h2--) { + var s = (this.words[h2] | 0) + a * 67108864; + (this.words[h2] = (s / i) | 0), (a = s % i); + } + return this.strip(); + }), + (f.prototype.divn = function (i) { + return this.clone().idivn(i); + }), + (f.prototype.egcd = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h2 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = new f(0), b3 = new f(1), l = 0; a.isEven() && h2.isEven(); ) a.iushrn(1), h2.iushrn(1), ++l; + for (var n = h2.clone(), d = a.clone(); !a.isZero(); ) { + for (var w = 0, g = 1; (a.words[0] & g) === 0 && w < 26; ++w, g <<= 1); + if (w > 0) for (a.iushrn(w); w-- > 0; ) (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _4 = 0, A2 = 1; (h2.words[0] & A2) === 0 && _4 < 26; ++_4, A2 <<= 1); + if (_4 > 0) for (h2.iushrn(_4); _4-- > 0; ) (c.isOdd() || b3.isOdd()) && (c.iadd(n), b3.isub(d)), c.iushrn(1), b3.iushrn(1); + a.cmp(h2) >= 0 ? (a.isub(h2), s.isub(c), u.isub(b3)) : (h2.isub(a), c.isub(s), b3.isub(u)); + } + return {a: c, b: b3, gcd: h2.iushln(l)}; + }), + (f.prototype._invmp = function (i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, + h2 = i.clone(); + a.negative !== 0 ? (a = a.umod(i)) : (a = a.clone()); + for (var s = new f(1), u = new f(0), c = h2.clone(); a.cmpn(1) > 0 && h2.cmpn(1) > 0; ) { + for (var b3 = 0, l = 1; (a.words[0] & l) === 0 && b3 < 26; ++b3, l <<= 1); + if (b3 > 0) for (a.iushrn(b3); b3-- > 0; ) s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1; (h2.words[0] & d) === 0 && n < 26; ++n, d <<= 1); + if (n > 0) for (h2.iushrn(n); n-- > 0; ) u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h2) >= 0 ? (a.isub(h2), s.isub(u)) : (h2.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? (w = s) : (w = u), w.cmpn(0) < 0 && w.iadd(i), w; + }), + (f.prototype.gcd = function (i) { + if (this.isZero()) return i.abs(); + if (i.isZero()) return this.abs(); + var a = this.clone(), + h2 = i.clone(); + (a.negative = 0), (h2.negative = 0); + for (var s = 0; a.isEven() && h2.isEven(); s++) a.iushrn(1), h2.iushrn(1); + do { + for (; a.isEven(); ) a.iushrn(1); + for (; h2.isEven(); ) h2.iushrn(1); + var u = a.cmp(h2); + if (u < 0) { + var c = a; + (a = h2), (h2 = c); + } else if (u === 0 || h2.cmpn(1) === 0) break; + a.isub(h2); + } while (true); + return h2.iushln(s); + }), + (f.prototype.invm = function (i) { + return this.egcd(i).a.umod(i); + }), + (f.prototype.isEven = function () { + return (this.words[0] & 1) === 0; + }), + (f.prototype.isOdd = function () { + return (this.words[0] & 1) === 1; + }), + (f.prototype.andln = function (i) { + return this.words[0] & i; + }), + (f.prototype.bincn = function (i) { + r(typeof i == 'number'); + var a = i % 26, + h2 = (i - a) / 26, + s = 1 << a; + if (this.length <= h2) return this._expand(h2 + 1), (this.words[h2] |= s), this; + for (var u = s, c = h2; u !== 0 && c < this.length; c++) { + var b3 = this.words[c] | 0; + (b3 += u), (u = b3 >>> 26), (b3 &= 67108863), (this.words[c] = b3); + } + return u !== 0 && ((this.words[c] = u), this.length++), this; + }), + (f.prototype.isZero = function () { + return this.length === 1 && this.words[0] === 0; + }), + (f.prototype.cmpn = function (i) { + var a = i < 0; + if (this.negative !== 0 && !a) return -1; + if (this.negative === 0 && a) return 1; + this.strip(); + var h2; + if (this.length > 1) h2 = 1; + else { + a && (i = -i), r(i <= 67108863, 'Number is too big'); + var s = this.words[0] | 0; + h2 = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h2 | 0 : h2; + }), + (f.prototype.cmp = function (i) { + if (this.negative !== 0 && i.negative === 0) return -1; + if (this.negative === 0 && i.negative !== 0) return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }), + (f.prototype.ucmp = function (i) { + if (this.length > i.length) return 1; + if (this.length < i.length) return -1; + for (var a = 0, h2 = this.length - 1; h2 >= 0; h2--) { + var s = this.words[h2] | 0, + u = i.words[h2] | 0; + if (s !== u) { + s < u ? (a = -1) : s > u && (a = 1); + break; + } + } + return a; + }), + (f.prototype.gtn = function (i) { + return this.cmpn(i) === 1; + }), + (f.prototype.gt = function (i) { + return this.cmp(i) === 1; + }), + (f.prototype.gten = function (i) { + return this.cmpn(i) >= 0; + }), + (f.prototype.gte = function (i) { + return this.cmp(i) >= 0; + }), + (f.prototype.ltn = function (i) { + return this.cmpn(i) === -1; + }), + (f.prototype.lt = function (i) { + return this.cmp(i) === -1; + }), + (f.prototype.lten = function (i) { + return this.cmpn(i) <= 0; + }), + (f.prototype.lte = function (i) { + return this.cmp(i) <= 0; + }), + (f.prototype.eqn = function (i) { + return this.cmpn(i) === 0; + }), + (f.prototype.eq = function (i) { + return this.cmp(i) === 0; + }), + (f.red = function (i) { + return new P(i); + }), + (f.prototype.toRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), r(this.negative === 0, 'red works only with positives'), i.convertTo(this)._forceRed(i); + }), + (f.prototype.fromRed = function () { + return r(this.red, 'fromRed works only with numbers in reduction context'), this.red.convertFrom(this); + }), + (f.prototype._forceRed = function (i) { + return (this.red = i), this; + }), + (f.prototype.forceRed = function (i) { + return r(!this.red, 'Already a number in reduction context'), this._forceRed(i); + }), + (f.prototype.redAdd = function (i) { + return r(this.red, 'redAdd works only with red numbers'), this.red.add(this, i); + }), + (f.prototype.redIAdd = function (i) { + return r(this.red, 'redIAdd works only with red numbers'), this.red.iadd(this, i); + }), + (f.prototype.redSub = function (i) { + return r(this.red, 'redSub works only with red numbers'), this.red.sub(this, i); + }), + (f.prototype.redISub = function (i) { + return r(this.red, 'redISub works only with red numbers'), this.red.isub(this, i); + }), + (f.prototype.redShl = function (i) { + return r(this.red, 'redShl works only with red numbers'), this.red.shl(this, i); + }), + (f.prototype.redMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.mul(this, i); + }), + (f.prototype.redIMul = function (i) { + return r(this.red, 'redMul works only with red numbers'), this.red._verify2(this, i), this.red.imul(this, i); + }), + (f.prototype.redSqr = function () { + return r(this.red, 'redSqr works only with red numbers'), this.red._verify1(this), this.red.sqr(this); + }), + (f.prototype.redISqr = function () { + return r(this.red, 'redISqr works only with red numbers'), this.red._verify1(this), this.red.isqr(this); + }), + (f.prototype.redSqrt = function () { + return r(this.red, 'redSqrt works only with red numbers'), this.red._verify1(this), this.red.sqrt(this); + }), + (f.prototype.redInvm = function () { + return r(this.red, 'redInvm works only with red numbers'), this.red._verify1(this), this.red.invm(this); + }), + (f.prototype.redNeg = function () { + return r(this.red, 'redNeg works only with red numbers'), this.red._verify1(this), this.red.neg(this); + }), + (f.prototype.redPow = function (i) { + return r(this.red && !i.red, 'redPow(normalNum)'), this.red._verify1(this), this.red.pow(this, i); + }); + var we = {k256: null, p224: null, p192: null, p25519: null}; + function ye(v, i) { + (this.name = v), (this.p = new f(i, 16)), (this.n = this.p.bitLength()), (this.k = new f(1).iushln(this.n).isub(this.p)), (this.tmp = this._tmp()); + } + (ye.prototype._tmp = function () { + var i = new f(null); + return (i.words = new Array(Math.ceil(this.n / 13))), i; + }), + (ye.prototype.ireduce = function (i) { + var a = i, + h2; + do this.split(a, this.tmp), (a = this.imulK(a)), (a = a.iadd(this.tmp)), (h2 = a.bitLength()); + while (h2 > this.n); + var s = h2 < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? ((a.words[0] = 0), (a.length = 1)) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }), + (ye.prototype.split = function (i, a) { + i.iushrn(this.n, 0, a); + }), + (ye.prototype.imulK = function (i) { + return i.imul(this.k); + }); + function xe() { + ye.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + o(xe, ye), + (xe.prototype.split = function (i, a) { + for (var h2 = 4194303, s = Math.min(i.length, 9), u = 0; u < s; u++) a.words[u] = i.words[u]; + if (((a.length = s), i.length <= 9)) { + (i.words[0] = 0), (i.length = 1); + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h2, u = 10; u < i.length; u++) { + var b3 = i.words[u] | 0; + (i.words[u - 10] = ((b3 & h2) << 4) | (c >>> 22)), (c = b3); + } + (c >>>= 22), (i.words[u - 10] = c), c === 0 && i.length > 10 ? (i.length -= 10) : (i.length -= 9); + }), + (xe.prototype.imulK = function (i) { + (i.words[i.length] = 0), (i.words[i.length + 1] = 0), (i.length += 2); + for (var a = 0, h2 = 0; h2 < i.length; h2++) { + var s = i.words[h2] | 0; + (a += s * 977), (i.words[h2] = a & 67108863), (a = s * 64 + ((a / 67108864) | 0)); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }); + function Re() { + ye.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + o(Re, ye); + function Ee() { + ye.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + o(Ee, ye); + function Ae() { + ye.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + o(Ae, ye), + (Ae.prototype.imulK = function (i) { + for (var a = 0, h2 = 0; h2 < i.length; h2++) { + var s = (i.words[h2] | 0) * 19 + a, + u = s & 67108863; + (s >>>= 26), (i.words[h2] = u), (a = s); + } + return a !== 0 && (i.words[i.length++] = a), i; + }), + (f._prime = function (i) { + if (we[i]) return we[i]; + var a; + if (i === 'k256') a = new xe(); + else if (i === 'p224') a = new Re(); + else if (i === 'p192') a = new Ee(); + else if (i === 'p25519') a = new Ae(); + else throw new Error('Unknown prime ' + i); + return (we[i] = a), a; + }); + function P(v) { + if (typeof v == 'string') { + var i = f._prime(v); + (this.m = i.p), (this.prime = i); + } else r(v.gtn(1), 'modulus must be greater than 1'), (this.m = v), (this.prime = null); + } + (P.prototype._verify1 = function (i) { + r(i.negative === 0, 'red works only with positives'), r(i.red, 'red works only with red numbers'); + }), + (P.prototype._verify2 = function (i, a) { + r((i.negative | a.negative) === 0, 'red works only with positives'), r(i.red && i.red === a.red, 'red works only with red numbers'); + }), + (P.prototype.imod = function (i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }), + (P.prototype.neg = function (i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }), + (P.prototype.add = function (i, a) { + this._verify2(i, a); + var h2 = i.add(a); + return h2.cmp(this.m) >= 0 && h2.isub(this.m), h2._forceRed(this); + }), + (P.prototype.iadd = function (i, a) { + this._verify2(i, a); + var h2 = i.iadd(a); + return h2.cmp(this.m) >= 0 && h2.isub(this.m), h2; + }), + (P.prototype.sub = function (i, a) { + this._verify2(i, a); + var h2 = i.sub(a); + return h2.cmpn(0) < 0 && h2.iadd(this.m), h2._forceRed(this); + }), + (P.prototype.isub = function (i, a) { + this._verify2(i, a); + var h2 = i.isub(a); + return h2.cmpn(0) < 0 && h2.iadd(this.m), h2; + }), + (P.prototype.shl = function (i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }), + (P.prototype.imul = function (i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }), + (P.prototype.mul = function (i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }), + (P.prototype.isqr = function (i) { + return this.imul(i, i.clone()); + }), + (P.prototype.sqr = function (i) { + return this.mul(i, i); + }), + (P.prototype.sqrt = function (i) { + if (i.isZero()) return i.clone(); + var a = this.m.andln(3); + if ((r(a % 2 === 1), a === 3)) { + var h2 = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h2); + } + for (var s = this.m.subn(1), u = 0; !s.isZero() && s.andln(1) === 0; ) u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), + b3 = c.redNeg(), + l = this.m.subn(1).iushrn(1), + n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this); this.pow(n, l).cmp(b3) !== 0; ) n.redIAdd(b3); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _4 = u; g.cmp(c) !== 0; ) { + for (var A2 = g, R2 = 0; A2.cmp(c) !== 0; R2++) A2 = A2.redSqr(); + r(R2 < _4); + var I = this.pow(d, new f(1).iushln(_4 - R2 - 1)); + (w = w.redMul(I)), (d = I.redSqr()), (g = g.redMul(d)), (_4 = R2); + } + return w; + }), + (P.prototype.invm = function (i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? ((a.negative = 0), this.imod(a).redNeg()) : this.imod(a); + }), + (P.prototype.pow = function (i, a) { + if (a.isZero()) return new f(1).toRed(this); + if (a.cmpn(1) === 0) return i.clone(); + var h2 = 4, + s = new Array(1 << h2); + (s[0] = new f(1).toRed(this)), (s[1] = i); + for (var u = 2; u < s.length; u++) s[u] = this.mul(s[u - 1], i); + var c = s[0], + b3 = 0, + l = 0, + n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1; u >= 0; u--) { + for (var d = a.words[u], w = n - 1; w >= 0; w--) { + var g = (d >> w) & 1; + if ((c !== s[0] && (c = this.sqr(c)), g === 0 && b3 === 0)) { + l = 0; + continue; + } + (b3 <<= 1), (b3 |= g), l++, !(l !== h2 && (u !== 0 || w !== 0)) && ((c = this.mul(c, s[b3])), (l = 0), (b3 = 0)); + } + n = 26; + } + return c; + }), + (P.prototype.convertTo = function (i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }), + (P.prototype.convertFrom = function (i) { + var a = i.clone(); + return (a.red = null), a; + }), + (f.mont = function (i) { + return new Se(i); + }); + function Se(v) { + P.call(this, v), + (this.shift = this.m.bitLength()), + this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), + (this.r = new f(1).iushln(this.shift)), + (this.r2 = this.imod(this.r.sqr())), + (this.rinv = this.r._invmp(this.m)), + (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), + (this.minv = this.minv.umod(this.r)), + (this.minv = this.r.sub(this.minv)); + } + o(Se, P), + (Se.prototype.convertTo = function (i) { + return this.imod(i.ushln(this.shift)); + }), + (Se.prototype.convertFrom = function (i) { + var a = this.imod(i.mul(this.rinv)); + return (a.red = null), a; + }), + (Se.prototype.imul = function (i, a) { + if (i.isZero() || a.isZero()) return (i.words[0] = 0), (i.length = 1), i; + var h2 = i.imul(a), + s = h2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h2.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.mul = function (i, a) { + if (i.isZero() || a.isZero()) return new f(0)._forceRed(this); + var h2 = i.mul(a), + s = h2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), + u = h2.isub(s).iushrn(this.shift), + c = u; + return u.cmp(this.m) >= 0 ? (c = u.isub(this.m)) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }), + (Se.prototype.invm = function (i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }); + })(typeof Sd > 'u' || Sd, F3); + }); + Ed = T2((xL, z3) => { + var U3 = w0(), + wq = Te().Buffer; + function Mq(t, e) { + return wq.from(t.toRed(U3.mont(e.modulus)).redPow(new U3(e.publicExponent)).fromRed().toArray()); + } + z3.exports = Mq; + }); + j3 = T2((SL, K3) => { + var _q = Ha(), + Ad = on(), + xq = bf(), + H3 = _d(), + W3 = xd(), + Rd = w0(), + Sq = Ed(), + Eq = Ks(), + Kr = Te().Buffer; + K3.exports = function (e, r, o) { + var f; + e.padding ? (f = e.padding) : o ? (f = 1) : (f = 4); + var p = _q(e), + m2; + if (f === 4) m2 = Aq(p, r); + else if (f === 1) m2 = Rq(p, r, o); + else if (f === 3) { + if (((m2 = new Rd(r)), m2.cmp(p.modulus) >= 0)) throw new Error('data too long for modulus'); + } else throw new Error('unknown padding'); + return o ? Eq(m2, p) : Sq(m2, p); + }; + function Aq(t, e) { + var r = t.modulus.byteLength(), + o = e.length, + f = xq('sha1').update(Kr.alloc(0)).digest(), + p = f.length, + m2 = 2 * p; + if (o > r - m2 - 2) throw new Error('message too long'); + var y3 = Kr.alloc(r - o - m2 - 2), + M = r - p - 1, + x = Ad(p), + S = W3(Kr.concat([f, y3, Kr.alloc(1, 1), e], M), H3(x, M)), + E2 = W3(x, H3(S, p)); + return new Rd(Kr.concat([Kr.alloc(1), E2, S], r)); + } + function Rq(t, e, r) { + var o = e.length, + f = t.modulus.byteLength(); + if (o > f - 11) throw new Error('message too long'); + var p; + return r ? (p = Kr.alloc(f - o - 3, 255)) : (p = Bq(f - o - 3)), new Rd(Kr.concat([Kr.from([0, r ? 1 : 2]), p, Kr.alloc(1), e], f)); + } + function Bq(t) { + for (var e = Kr.allocUnsafe(t), r = 0, o = Ad(t * 2), f = 0, p; r < t; ) f === o.length && ((o = Ad(t * 2)), (f = 0)), (p = o[f++]), p && (e[r++] = p); + return e; + } + }); + Y3 = T2((EL, G3) => { + var qq = Ha(), + Z3 = _d(), + V3 = xd(), + $3 = w0(), + Iq = Ks(), + Tq = bf(), + kq = Ed(), + Za = Te().Buffer; + G3.exports = function (e, r, o) { + var f; + e.padding ? (f = e.padding) : o ? (f = 1) : (f = 4); + var p = qq(e), + m2 = p.modulus.byteLength(); + if (r.length > m2 || new $3(r).cmp(p.modulus) >= 0) throw new Error('decryption error'); + var y3; + o ? (y3 = kq(new $3(r), p)) : (y3 = Iq(r, p)); + var M = Za.alloc(m2 - y3.length); + if (((y3 = Za.concat([M, y3], m2)), f === 4)) return Lq(p, y3); + if (f === 1) return Nq(p, y3, o); + if (f === 3) return y3; + throw new Error('unknown padding'); + }; + function Lq(t, e) { + var r = t.modulus.byteLength(), + o = Tq('sha1').update(Za.alloc(0)).digest(), + f = o.length; + if (e[0] !== 0) throw new Error('decryption error'); + var p = e.slice(1, f + 1), + m2 = e.slice(f + 1), + y3 = V3(p, Z3(m2, f)), + M = V3(m2, Z3(y3, r - f - 1)); + if (Dq(o, M.slice(0, f))) throw new Error('decryption error'); + for (var x = f; M[x] === 0; ) x++; + if (M[x++] !== 1) throw new Error('decryption error'); + return M.slice(x); + } + function Nq(t, e, r) { + for (var o = e.slice(0, 2), f = 2, p = 0; e[f++] !== 0; ) + if (f >= e.length) { + p++; + break; + } + var m2 = e.slice(2, f - 1); + if ((((o.toString('hex') !== '0002' && !r) || (o.toString('hex') !== '0001' && r)) && p++, m2.length < 8 && p++, p)) throw new Error('decryption error'); + return e.slice(f); + } + function Dq(t, e) { + (t = Za.from(t)), (e = Za.from(e)); + var r = 0, + o = t.length; + t.length !== e.length && (r++, (o = Math.min(t.length, e.length))); + for (var f = -1; ++f < o; ) r += t[f] ^ e[f]; + return r; + } + }); + X3 = T2(Vn => { + Vn.publicEncrypt = j3(); + Vn.privateDecrypt = Y3(); + Vn.privateEncrypt = function (e, r) { + return Vn.publicEncrypt(e, r, true); + }; + Vn.publicDecrypt = function (e, r) { + return Vn.privateDecrypt(e, r, true); + }; + }); + ow = T2(Va => { + function J3() { + throw new Error(`secure random number generation not supported by this browser +use chrome, FireFox or Internet Explorer 11`); + } + var ew = Te(), + Q3 = on(), + tw = ew.Buffer, + rw = ew.kMaxLength, + Bd = global.crypto || global.msCrypto, + iw = Math.pow(2, 32) - 1; + function nw(t, e) { + if (typeof t != 'number' || t !== t) throw new TypeError('offset must be a number'); + if (t > iw || t < 0) throw new TypeError('offset must be a uint32'); + if (t > rw || t > e) throw new RangeError('offset out of range'); + } + function fw(t, e, r) { + if (typeof t != 'number' || t !== t) throw new TypeError('size must be a number'); + if (t > iw || t < 0) throw new TypeError('size must be a uint32'); + if (t + e > r || t > rw) throw new RangeError('buffer too small'); + } + Bd && Bd.getRandomValues ? ((Va.randomFill = Pq), (Va.randomFillSync = Cq)) : ((Va.randomFill = J3), (Va.randomFillSync = J3)); + function Pq(t, e, r, o) { + if (!tw.isBuffer(t) && !(t instanceof global.Uint8Array)) throw new TypeError('"buf" argument must be a Buffer or Uint8Array'); + if (typeof e == 'function') (o = e), (e = 0), (r = t.length); + else if (typeof r == 'function') (o = r), (r = t.length - e); + else if (typeof o != 'function') throw new TypeError('"cb" argument must be a function'); + return nw(e, t.length), fw(r, e, t.length), aw(t, e, r, o); + } + function aw(t, e, r, o) { + if (true) { + var f = t.buffer, + p = new Uint8Array(f, e, r); + if ((Bd.getRandomValues(p), o)) { + process.nextTick(function () { + o(null, t); + }); + return; + } + return t; + } + if (o) { + Q3(r, function (y3, M) { + if (y3) return o(y3); + M.copy(t, e), o(null, t); + }); + return; + } + var m2 = Q3(r); + return m2.copy(t, e), t; + } + function Cq(t, e, r) { + if ((typeof e > 'u' && (e = 0), !tw.isBuffer(t) && !(t instanceof global.Uint8Array))) throw new TypeError('"buf" argument must be a Buffer or Uint8Array'); + return nw(e, t.length), r === undefined && (r = t.length - e), fw(r, e, t.length), aw(t, e, r); + } + }); + qd = T2(ke => { + ke.randomBytes = ke.rng = ke.pseudoRandomBytes = ke.prng = on(); + ke.createHash = ke.Hash = bf(); + ke.createHmac = ke.Hmac = wu(); + var Oq = Eb(), + Fq = Object.keys(Oq), + Uq = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(Fq); + ke.getHashes = function () { + return Uq; + }; + var sw = Iu(); + ke.pbkdf2 = sw.pbkdf2; + ke.pbkdf2Sync = sw.pbkdf2Sync; + var ui = Vm(); + ke.Cipher = ui.Cipher; + ke.createCipher = ui.createCipher; + ke.Cipheriv = ui.Cipheriv; + ke.createCipheriv = ui.createCipheriv; + ke.Decipher = ui.Decipher; + ke.createDecipher = ui.createDecipher; + ke.Decipheriv = ui.Decipheriv; + ke.createDecipheriv = ui.createDecipheriv; + ke.getCiphers = ui.getCiphers; + ke.listCiphers = ui.listCiphers; + var $a = hg(); + ke.DiffieHellmanGroup = $a.DiffieHellmanGroup; + ke.createDiffieHellmanGroup = $a.createDiffieHellmanGroup; + ke.getDiffieHellman = $a.getDiffieHellman; + ke.createDiffieHellman = $a.createDiffieHellman; + ke.DiffieHellman = $a.DiffieHellman; + var M0 = k3(); + ke.createSign = M0.createSign; + ke.Sign = M0.Sign; + ke.createVerify = M0.createVerify; + ke.Verify = M0.Verify; + ke.createECDH = P3(); + var _0 = X3(); + ke.publicEncrypt = _0.publicEncrypt; + ke.privateEncrypt = _0.privateEncrypt; + ke.publicDecrypt = _0.publicDecrypt; + ke.privateDecrypt = _0.privateDecrypt; + var hw = ow(); + ke.randomFill = hw.randomFill; + ke.randomFillSync = hw.randomFillSync; + ke.createCredentials = function () { + throw new Error( + ['sorry, createCredentials is not implemented yet', 'we accept pull requests', 'https://github.com/crypto-browserify/crypto-browserify'].join(` +`) + ); + }; + ke.constants = { + DH_CHECK_P_NOT_SAFE_PRIME: 2, + DH_CHECK_P_NOT_PRIME: 1, + DH_UNABLE_TO_CHECK_GENERATOR: 4, + DH_NOT_SUITABLE_GENERATOR: 8, + NPN_ENABLED: 1, + ALPN_ENABLED: 1, + RSA_PKCS1_PADDING: 1, + RSA_SSLV23_PADDING: 2, + RSA_NO_PADDING: 3, + RSA_PKCS1_OAEP_PADDING: 4, + RSA_X931_PADDING: 5, + RSA_PKCS1_PSS_PADDING: 6, + POINT_CONVERSION_COMPRESSED: 2, + POINT_CONVERSION_UNCOMPRESSED: 4, + POINT_CONVERSION_HYBRID: 6 + }; + }); + Xt = {}; + Ja(Xt, {DEFAULT_ENCODING: () => Ga, default: () => Wq, getCurves: () => dw, getRandomValues: () => uw, randomUUID: () => lw, scrypt: () => Td, scryptSync: () => Id, timingSafeEqual: () => x0, webcrypto: () => cw}); + ot(Xt, rn(qd())); + zq = rn(qd()); + Ga = 'buffer'; + uw = t => crypto.getRandomValues(t); + lw = () => crypto.randomUUID(); + Hq = ['p192', 'p224', 'p256', 'p384', 'p521', 'curve25519', 'ed25519', 'secp256k1', 'secp224r1', 'prime256v1', 'prime192v1', 'ed25519', 'secp384r1', 'secp521r1']; + x0 = + 'timingSafeEqual' in crypto + ? (t, e) => { + let {byteLength: r} = t, + {byteLength: o} = e; + if (typeof r != 'number' || typeof o != 'number') throw new TypeError('Input must be an array buffer view'); + if (r !== o) throw new RangeError('Input buffers must have the same length'); + return crypto.timingSafeEqual(t, e); + } + : undefined; + Id = + 'scryptSync' in crypto + ? (t, e, r, o) => { + let f = crypto.scryptSync(t, e, r, o); + return Ga !== 'buffer' ? new Buffer(f).toString(Ga) : new Buffer(f); + } + : undefined; + Td = + 'scryptSync' in crypto + ? function (t, e, r, o, f) { + if ((typeof o == 'function' && ((f = o), (o = undefined)), typeof f != 'function')) { + var p = new TypeError('callback must be a function'); + throw ((p.code = 'ERR_INVALID_CALLBACK'), p); + } + try { + let m2 = crypto.scryptSync(t, e, r, o); + process.nextTick(f, null, Ga !== 'buffer' ? new Buffer(m2).toString(Ga) : new Buffer(m2)); + } catch (m2) { + throw m2; + } + } + : undefined; + x0 && (Object.defineProperty(x0, 'name', {value: '::bunternal::'}), Object.defineProperty(Td, 'name', {value: '::bunternal::'}), Object.defineProperty(Id, 'name', {value: '::bunternal::'})); + cw = crypto; + Wq = {...zq, getRandomValues: uw, randomUUID: lw, timingSafeEqual: x0, scryptSync: Id, scrypt: Td, webcrypto: cw, getCurves: dw}; + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ +}); + +// node_modules/node-forge/lib/pbkdf2.js +var require_pbkdf2 = __commonJS((exports, module) => { + var forge = require_forge(); + require_hmac(); + require_md(); + require_util(); + var pkcs5 = (forge.pkcs5 = forge.pkcs5 || {}); + var crypto2; + if (forge.util.isNodejs && !forge.options.usePureJavaScript) { + crypto2 = (init_crypto(), __toCommonJS(exports_crypto)); + } + module.exports = + forge.pbkdf2 = + pkcs5.pbkdf2 = + function (p, s, c, dkLen, md, callback) { + if (typeof md === 'function') { + callback = md; + md = null; + } + if (forge.util.isNodejs && !forge.options.usePureJavaScript && crypto2.pbkdf2 && (md === null || typeof md !== 'object') && (crypto2.pbkdf2Sync.length > 4 || !md || md === 'sha1')) { + if (typeof md !== 'string') { + md = 'sha1'; + } + p = Buffer.from(p, 'binary'); + s = Buffer.from(s, 'binary'); + if (!callback) { + if (crypto2.pbkdf2Sync.length === 4) { + return crypto2.pbkdf2Sync(p, s, c, dkLen).toString('binary'); + } + return crypto2.pbkdf2Sync(p, s, c, dkLen, md).toString('binary'); + } + if (crypto2.pbkdf2Sync.length === 4) { + return crypto2.pbkdf2(p, s, c, dkLen, function (err2, key) { + if (err2) { + return callback(err2); + } + callback(null, key.toString('binary')); + }); + } + return crypto2.pbkdf2(p, s, c, dkLen, md, function (err2, key) { + if (err2) { + return callback(err2); + } + callback(null, key.toString('binary')); + }); + } + if (typeof md === 'undefined' || md === null) { + md = 'sha1'; + } + if (typeof md === 'string') { + if (!(md in forge.md.algorithms)) { + throw new Error('Unknown hash algorithm: ' + md); + } + md = forge.md[md].create(); + } + var hLen = md.digestLength; + if (dkLen > 4294967295 * hLen) { + var err = new Error('Derived key is too long.'); + if (callback) { + return callback(err); + } + throw err; + } + var len = Math.ceil(dkLen / hLen); + var r = dkLen - (len - 1) * hLen; + var prf = forge.hmac.create(); + prf.start(md, p); + var dk = ''; + var xor, u_c, u_c1; + if (!callback) { + for (var i = 1; i <= len; ++i) { + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + for (var j = 2; j <= c; ++j) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + } + dk += i < len ? xor : xor.substr(0, r); + } + return dk; + } + var i = 1, + j; + function outer() { + if (i > len) { + return callback(null, dk); + } + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + j = 2; + inner(); + } + function inner() { + if (j <= c) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + ++j; + return forge.util.setImmediate(inner); + } + dk += i < len ? xor : xor.substr(0, r); + ++i; + outer(); + } + outer(); + }; +}); + +// node_modules/node-forge/lib/sha256.js +var require_sha256 = __commonJS((exports, module) => { + var _init = function () { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 64); + _k = [ + 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, + 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, + 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, + 2428436474, 2756734187, 3204031479, 3329325298 + ]; + _initialized = true; + }; + var _update = function (s, w, bytes) { + var t1, t22, s0, s1, ch, maj, i, a, b3, c, d, e, f, g, h2; + var len = bytes.length(); + while (len >= 64) { + for (i = 0; i < 16; ++i) { + w[i] = bytes.getInt32(); + } + for (; i < 64; ++i) { + t1 = w[i - 2]; + t1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10); + t22 = w[i - 15]; + t22 = ((t22 >>> 7) | (t22 << 25)) ^ ((t22 >>> 18) | (t22 << 14)) ^ (t22 >>> 3); + w[i] = (t1 + w[i - 7] + t22 + w[i - 16]) | 0; + } + a = s.h0; + b3 = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + f = s.h5; + g = s.h6; + h2 = s.h7; + for (i = 0; i < 64; ++i) { + s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); + ch = g ^ (e & (f ^ g)); + s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); + maj = (a & b3) | (c & (a ^ b3)); + t1 = h2 + s1 + ch + _k[i] + w[i]; + t22 = s0 + maj; + h2 = g; + g = f; + f = e; + e = (d + t1) >>> 0; + d = c; + c = b3; + b3 = a; + a = (t1 + t22) >>> 0; + } + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b3) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + s.h5 = (s.h5 + f) | 0; + s.h6 = (s.h6 + g) | 0; + s.h7 = (s.h7 + h2) | 0; + len -= 64; + } + }; + var forge = require_forge(); + require_md(); + require_util(); + var sha256 = (module.exports = forge.sha256 = forge.sha256 || {}); + forge.md.sha256 = forge.md.algorithms.sha256 = sha256; + sha256.create = function () { + if (!_initialized) { + _init(); + } + var _state = null; + var _input = forge.util.createBuffer(); + var _w = new Array(64); + var md = { + algorithm: 'sha256', + blockLength: 64, + digestLength: 32, + messageLength: 0, + fullMessageLength: null, + messageLengthSize: 8 + }; + md.start = function () { + md.messageLength = 0; + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 1779033703, + h1: 3144134277, + h2: 1013904242, + h3: 2773480762, + h4: 1359893119, + h5: 2600822924, + h6: 528734635, + h7: 1541459225 + }; + return md; + }; + md.start(); + md.update = function (msg, encoding) { + if (encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + var len = msg.length; + md.messageLength += len; + len = [(len / 4294967296) >>> 0, len >>> 0]; + for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 4294967296) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = (len[1] / 4294967296) >>> 0; + } + _input.putBytes(msg); + _update(_state, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + return md; + }; + md.digest = function () { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 4294967296) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + var s22 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4, + h5: _state.h5, + h6: _state.h6, + h7: _state.h7 + }; + _update(s22, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s22.h0); + rval.putInt32(s22.h1); + rval.putInt32(s22.h2); + rval.putInt32(s22.h3); + rval.putInt32(s22.h4); + rval.putInt32(s22.h5); + rval.putInt32(s22.h6); + rval.putInt32(s22.h7); + return rval; + }; + return md; + }; + var _padding = null; + var _initialized = false; + var _k = null; +}); + +// node_modules/node-forge/lib/prng.js +var require_prng = __commonJS((exports, module) => { + var forge = require_forge(); + require_util(); + var _crypto = null; + if (forge.util.isNodejs && !forge.options.usePureJavaScript && !process.versions['node-webkit']) { + _crypto = (init_crypto(), __toCommonJS(exports_crypto)); + } + var prng = (module.exports = forge.prng = forge.prng || {}); + prng.create = function (plugin) { + var ctx = { + plugin, + key: null, + seed: null, + time: null, + reseeds: 0, + generated: 0, + keyBytes: '' + }; + var md = plugin.md; + var pools = new Array(32); + for (var i = 0; i < 32; ++i) { + pools[i] = md.create(); + } + ctx.pools = pools; + ctx.pool = 0; + ctx.generate = function (count, callback) { + if (!callback) { + return ctx.generateSync(count); + } + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + var b3 = forge.util.createBuffer(); + ctx.key = null; + generate(); + function generate(err) { + if (err) { + return callback(err); + } + if (b3.length() >= count) { + return callback(null, b3.getBytes(count)); + } + if (ctx.generated > 1048575) { + ctx.key = null; + } + if (ctx.key === null) { + return forge.util.nextTick(function () { + _reseed(generate); + }); + } + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b3.putBytes(bytes); + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + forge.util.setImmediate(generate); + } + }; + ctx.generateSync = function (count) { + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + ctx.key = null; + var b3 = forge.util.createBuffer(); + while (b3.length() < count) { + if (ctx.generated > 1048575) { + ctx.key = null; + } + if (ctx.key === null) { + _reseedSync(); + } + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b3.putBytes(bytes); + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + } + return b3.getBytes(count); + }; + function _reseed(callback) { + if (ctx.pools[0].messageLength >= 32) { + _seed(); + return callback(); + } + var needed = (32 - ctx.pools[0].messageLength) << 5; + ctx.seedFile(needed, function (err, bytes) { + if (err) { + return callback(err); + } + ctx.collect(bytes); + _seed(); + callback(); + }); + } + function _reseedSync() { + if (ctx.pools[0].messageLength >= 32) { + return _seed(); + } + var needed = (32 - ctx.pools[0].messageLength) << 5; + ctx.collect(ctx.seedFileSync(needed)); + _seed(); + } + function _seed() { + ctx.reseeds = ctx.reseeds === 4294967295 ? 0 : ctx.reseeds + 1; + var md2 = ctx.plugin.md.create(); + md2.update(ctx.keyBytes); + var _2powK = 1; + for (var k = 0; k < 32; ++k) { + if (ctx.reseeds % _2powK === 0) { + md2.update(ctx.pools[k].digest().getBytes()); + ctx.pools[k].start(); + } + _2powK = _2powK << 1; + } + ctx.keyBytes = md2.digest().getBytes(); + md2.start(); + md2.update(ctx.keyBytes); + var seedBytes = md2.digest().getBytes(); + ctx.key = ctx.plugin.formatKey(ctx.keyBytes); + ctx.seed = ctx.plugin.formatSeed(seedBytes); + ctx.generated = 0; + } + function defaultSeedFile(needed) { + var getRandomValues = null; + var globalScope = forge.util.globalScope; + var _crypto2 = globalScope.crypto || globalScope.msCrypto; + if (_crypto2 && _crypto2.getRandomValues) { + getRandomValues = function (arr) { + return _crypto2.getRandomValues(arr); + }; + } + var b3 = forge.util.createBuffer(); + if (getRandomValues) { + while (b3.length() < needed) { + var count = Math.max(1, Math.min(needed - b3.length(), 65536) / 4); + var entropy = new Uint32Array(Math.floor(count)); + try { + getRandomValues(entropy); + for (var i3 = 0; i3 < entropy.length; ++i3) { + b3.putInt32(entropy[i3]); + } + } catch (e) { + if (!(typeof QuotaExceededError !== 'undefined' && e instanceof QuotaExceededError)) { + throw e; + } + } + } + } + if (b3.length() < needed) { + var hi, lo, next; + var seed = Math.floor(Math.random() * 65536); + while (b3.length() < needed) { + lo = 16807 * (seed & 65535); + hi = 16807 * (seed >> 16); + lo += (hi & 32767) << 16; + lo += hi >> 15; + lo = (lo & 2147483647) + (lo >> 31); + seed = lo & 4294967295; + for (var i3 = 0; i3 < 3; ++i3) { + next = seed >>> (i3 << 3); + next ^= Math.floor(Math.random() * 256); + b3.putByte(next & 255); + } + } + } + return b3.getBytes(needed); + } + if (_crypto) { + ctx.seedFile = function (needed, callback) { + _crypto.randomBytes(needed, function (err, bytes) { + if (err) { + return callback(err); + } + callback(null, bytes.toString()); + }); + }; + ctx.seedFileSync = function (needed) { + return _crypto.randomBytes(needed).toString(); + }; + } else { + ctx.seedFile = function (needed, callback) { + try { + callback(null, defaultSeedFile(needed)); + } catch (e) { + callback(e); + } + }; + ctx.seedFileSync = defaultSeedFile; + } + ctx.collect = function (bytes) { + var count = bytes.length; + for (var i3 = 0; i3 < count; ++i3) { + ctx.pools[ctx.pool].update(bytes.substr(i3, 1)); + ctx.pool = ctx.pool === 31 ? 0 : ctx.pool + 1; + } + }; + ctx.collectInt = function (i3, n) { + var bytes = ''; + for (var x = 0; x < n; x += 8) { + bytes += String.fromCharCode((i3 >> x) & 255); + } + ctx.collect(bytes); + }; + ctx.registerWorker = function (worker) { + if (worker === self) { + ctx.seedFile = function (needed, callback) { + function listener2(e) { + var data = e.data; + if (data.forge && data.forge.prng) { + self.removeEventListener('message', listener2); + callback(data.forge.prng.err, data.forge.prng.bytes); + } + } + self.addEventListener('message', listener2); + self.postMessage({forge: {prng: {needed}}}); + }; + } else { + var listener = function (e) { + var data = e.data; + if (data.forge && data.forge.prng) { + ctx.seedFile(data.forge.prng.needed, function (err, bytes) { + worker.postMessage({forge: {prng: {err, bytes}}}); + }); + } + }; + worker.addEventListener('message', listener); + } + }; + return ctx; + }; +}); + +// node_modules/node-forge/lib/random.js +var require_random = __commonJS((exports, module) => { + var forge = require_forge(); + require_aes(); + require_sha256(); + require_prng(); + require_util(); + (function () { + if (forge.random && forge.random.getBytes) { + module.exports = forge.random; + return; + } + (function (jQuery2) { + var prng_aes = {}; + var _prng_aes_output = new Array(4); + var _prng_aes_buffer = forge.util.createBuffer(); + prng_aes.formatKey = function (key2) { + var tmp = forge.util.createBuffer(key2); + key2 = new Array(4); + key2[0] = tmp.getInt32(); + key2[1] = tmp.getInt32(); + key2[2] = tmp.getInt32(); + key2[3] = tmp.getInt32(); + return forge.aes._expandKey(key2, false); + }; + prng_aes.formatSeed = function (seed) { + var tmp = forge.util.createBuffer(seed); + seed = new Array(4); + seed[0] = tmp.getInt32(); + seed[1] = tmp.getInt32(); + seed[2] = tmp.getInt32(); + seed[3] = tmp.getInt32(); + return seed; + }; + prng_aes.cipher = function (key2, seed) { + forge.aes._updateBlock(key2, seed, _prng_aes_output, false); + _prng_aes_buffer.putInt32(_prng_aes_output[0]); + _prng_aes_buffer.putInt32(_prng_aes_output[1]); + _prng_aes_buffer.putInt32(_prng_aes_output[2]); + _prng_aes_buffer.putInt32(_prng_aes_output[3]); + return _prng_aes_buffer.getBytes(); + }; + prng_aes.increment = function (seed) { + ++seed[3]; + return seed; + }; + prng_aes.md = forge.md.sha256; + function spawnPrng() { + var ctx = forge.prng.create(prng_aes); + ctx.getBytes = function (count, callback) { + return ctx.generate(count, callback); + }; + ctx.getBytesSync = function (count) { + return ctx.generate(count); + }; + return ctx; + } + var _ctx = spawnPrng(); + var getRandomValues = null; + var globalScope = forge.util.globalScope; + var _crypto = globalScope.crypto || globalScope.msCrypto; + if (_crypto && _crypto.getRandomValues) { + getRandomValues = function (arr) { + return _crypto.getRandomValues(arr); + }; + } + if (forge.options.usePureJavaScript || (!forge.util.isNodejs && !getRandomValues)) { + if (typeof window === 'undefined' || window.document === undefined) { + } + _ctx.collectInt(+new Date(), 32); + if (typeof navigator !== 'undefined') { + var _navBytes = ''; + for (var key in navigator) { + try { + if (typeof navigator[key] == 'string') { + _navBytes += navigator[key]; + } + } catch (e) {} + } + _ctx.collect(_navBytes); + _navBytes = null; + } + if (jQuery2) { + jQuery2().mousemove(function (e) { + _ctx.collectInt(e.clientX, 16); + _ctx.collectInt(e.clientY, 16); + }); + jQuery2().keypress(function (e) { + _ctx.collectInt(e.charCode, 8); + }); + } + } + if (!forge.random) { + forge.random = _ctx; + } else { + for (var key in _ctx) { + forge.random[key] = _ctx[key]; + } + } + forge.random.createInstance = spawnPrng; + module.exports = forge.random; + })(typeof jQuery !== 'undefined' ? jQuery : null); + })(); +}); + +// node_modules/node-forge/lib/rc2.js +var require_rc2 = __commonJS((exports, module) => { + var forge = require_forge(); + require_util(); + var piTable = [ + 217, 120, 249, 196, 25, 221, 181, 237, 40, 233, 253, 121, 74, 160, 216, 157, 198, 126, 55, 131, 43, 118, 83, 142, 98, 76, 100, 136, 68, 139, 251, 162, 23, 154, 89, 245, 135, 179, 79, 19, 97, 69, 109, 141, 9, 129, 125, 50, 189, 143, 64, 235, + 134, 183, 123, 11, 240, 149, 33, 34, 92, 107, 78, 130, 84, 214, 101, 147, 206, 96, 178, 28, 115, 86, 192, 20, 167, 140, 241, 220, 18, 117, 202, 31, 59, 190, 228, 209, 66, 61, 212, 48, 163, 60, 182, 38, 111, 191, 14, 218, 70, 105, 7, 87, 39, + 242, 29, 155, 188, 148, 67, 3, 248, 17, 199, 246, 144, 239, 62, 231, 6, 195, 213, 47, 200, 102, 30, 215, 8, 232, 234, 222, 128, 82, 238, 247, 132, 170, 114, 172, 53, 77, 106, 42, 150, 26, 210, 113, 90, 21, 73, 116, 75, 159, 208, 94, 4, 24, + 164, 236, 194, 224, 65, 110, 15, 81, 203, 204, 36, 145, 175, 80, 161, 244, 112, 57, 153, 124, 58, 133, 35, 184, 180, 122, 252, 2, 54, 91, 37, 85, 151, 49, 45, 93, 250, 152, 227, 138, 146, 174, 5, 223, 41, 16, 103, 108, 186, 201, 211, 0, 230, + 207, 225, 158, 168, 44, 99, 22, 1, 63, 88, 226, 137, 169, 13, 56, 52, 27, 171, 51, 255, 176, 187, 72, 12, 95, 185, 177, 205, 46, 197, 243, 219, 71, 229, 165, 156, 119, 10, 166, 32, 104, 254, 127, 193, 173 + ]; + var s = [1, 2, 3, 5]; + var rol = function (word, bits) { + return ((word << bits) & 65535) | ((word & 65535) >> (16 - bits)); + }; + var ror = function (word, bits) { + return ((word & 65535) >> bits) | ((word << (16 - bits)) & 65535); + }; + module.exports = forge.rc2 = forge.rc2 || {}; + forge.rc2.expandKey = function (key, effKeyBits) { + if (typeof key === 'string') { + key = forge.util.createBuffer(key); + } + effKeyBits = effKeyBits || 128; + var L2 = key; + var T3 = key.length(); + var T1 = effKeyBits; + var T8 = Math.ceil(T1 / 8); + var TM = 255 >> (T1 & 7); + var i; + for (i = T3; i < 128; i++) { + L2.putByte(piTable[(L2.at(i - 1) + L2.at(i - T3)) & 255]); + } + L2.setAt(128 - T8, piTable[L2.at(128 - T8) & TM]); + for (i = 127 - T8; i >= 0; i--) { + L2.setAt(i, piTable[L2.at(i + 1) ^ L2.at(i + T8)]); + } + return L2; + }; + var createCipher = function (key, bits, encrypt) { + var _finish = false, + _input = null, + _output = null, + _iv = null; + var mixRound, mashRound; + var i, + j, + K = []; + key = forge.rc2.expandKey(key, bits); + for (i = 0; i < 64; i++) { + K.push(key.getInt16Le()); + } + if (encrypt) { + mixRound = function (R2) { + for (i = 0; i < 4; i++) { + R2[i] += K[j] + (R2[(i + 3) % 4] & R2[(i + 2) % 4]) + (~R2[(i + 3) % 4] & R2[(i + 1) % 4]); + R2[i] = rol(R2[i], s[i]); + j++; + } + }; + mashRound = function (R2) { + for (i = 0; i < 4; i++) { + R2[i] += K[R2[(i + 3) % 4] & 63]; + } + }; + } else { + mixRound = function (R2) { + for (i = 3; i >= 0; i--) { + R2[i] = ror(R2[i], s[i]); + R2[i] -= K[j] + (R2[(i + 3) % 4] & R2[(i + 2) % 4]) + (~R2[(i + 3) % 4] & R2[(i + 1) % 4]); + j--; + } + }; + mashRound = function (R2) { + for (i = 3; i >= 0; i--) { + R2[i] -= K[R2[(i + 3) % 4] & 63]; + } + }; + } + var runPlan = function (plan) { + var R2 = []; + for (i = 0; i < 4; i++) { + var val = _input.getInt16Le(); + if (_iv !== null) { + if (encrypt) { + val ^= _iv.getInt16Le(); + } else { + _iv.putInt16Le(val); + } + } + R2.push(val & 65535); + } + j = encrypt ? 0 : 63; + for (var ptr = 0; ptr < plan.length; ptr++) { + for (var ctr = 0; ctr < plan[ptr][0]; ctr++) { + plan[ptr][1](R2); + } + } + for (i = 0; i < 4; i++) { + if (_iv !== null) { + if (encrypt) { + _iv.putInt16Le(R2[i]); + } else { + R2[i] ^= _iv.getInt16Le(); + } + } + _output.putInt16Le(R2[i]); + } + }; + var cipher = null; + cipher = { + start: function (iv, output) { + if (iv) { + if (typeof iv === 'string') { + iv = forge.util.createBuffer(iv); + } + } + _finish = false; + _input = forge.util.createBuffer(); + _output = output || new forge.util.createBuffer(); + _iv = iv; + cipher.output = _output; + }, + update: function (input) { + if (!_finish) { + _input.putBuffer(input); + } + while (_input.length() >= 8) { + runPlan([ + [5, mixRound], + [1, mashRound], + [6, mixRound], + [1, mashRound], + [5, mixRound] + ]); + } + }, + finish: function (pad) { + var rval = true; + if (encrypt) { + if (pad) { + rval = pad(8, _input, !encrypt); + } else { + var padding = _input.length() === 8 ? 8 : 8 - _input.length(); + _input.fillWithByte(padding, padding); + } + } + if (rval) { + _finish = true; + cipher.update(); + } + if (!encrypt) { + rval = _input.length() === 0; + if (rval) { + if (pad) { + rval = pad(8, _output, !encrypt); + } else { + var len = _output.length(); + var count = _output.at(len - 1); + if (count > len) { + rval = false; + } else { + _output.truncate(count); + } + } + } + } + return rval; + } + }; + return cipher; + }; + forge.rc2.startEncrypting = function (key, iv, output) { + var cipher = forge.rc2.createEncryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; + }; + forge.rc2.createEncryptionCipher = function (key, bits) { + return createCipher(key, bits, true); + }; + forge.rc2.startDecrypting = function (key, iv, output) { + var cipher = forge.rc2.createDecryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; + }; + forge.rc2.createDecryptionCipher = function (key, bits) { + return createCipher(key, bits, false); + }; +}); + +// node_modules/node-forge/lib/jsbn.js +var require_jsbn = __commonJS((exports, module) => { + var BigInteger = function (a, b3, c) { + this.data = []; + if (a != null) + if (typeof a == 'number') this.fromNumber(a, b3, c); + else if (b3 == null && typeof a != 'string') this.fromString(a, 256); + else this.fromString(a, b3); + }; + var nbi = function () { + return new BigInteger(null); + }; + var am1 = function (i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this.data[i++] + w.data[j] + c; + c = Math.floor(v / 67108864); + w.data[j++] = v & 67108863; + } + return c; + }; + var am2 = function (i, x, w, j, c, n) { + var xl = x & 32767, + xh = x >> 15; + while (--n >= 0) { + var l = this.data[i] & 32767; + var h2 = this.data[i++] >> 15; + var m2 = xh * l + h2 * xl; + l = xl * l + ((m2 & 32767) << 15) + w.data[j] + (c & 1073741823); + c = (l >>> 30) + (m2 >>> 15) + xh * h2 + (c >>> 30); + w.data[j++] = l & 1073741823; + } + return c; + }; + var am3 = function (i, x, w, j, c, n) { + var xl = x & 16383, + xh = x >> 14; + while (--n >= 0) { + var l = this.data[i] & 16383; + var h2 = this.data[i++] >> 14; + var m2 = xh * l + h2 * xl; + l = xl * l + ((m2 & 16383) << 14) + w.data[j] + c; + c = (l >> 28) + (m2 >> 14) + xh * h2; + w.data[j++] = l & 268435455; + } + return c; + }; + var int2char = function (n) { + return BI_RM.charAt(n); + }; + var intAt = function (s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return c == null ? -1 : c; + }; + var bnpCopyTo = function (r) { + for (var i = this.t - 1; i >= 0; --i) r.data[i] = this.data[i]; + r.t = this.t; + r.s = this.s; + }; + var bnpFromInt = function (x) { + this.t = 1; + this.s = x < 0 ? -1 : 0; + if (x > 0) this.data[0] = x; + else if (x < -1) this.data[0] = x + this.DV; + else this.t = 0; + }; + var nbv = function (i) { + var r = nbi(); + r.fromInt(i); + return r; + }; + var bnpFromString = function (s, b3) { + var k; + if (b3 == 16) k = 4; + else if (b3 == 8) k = 3; + else if (b3 == 256) k = 8; + else if (b3 == 2) k = 1; + else if (b3 == 32) k = 5; + else if (b3 == 4) k = 2; + else { + this.fromRadix(s, b3); + return; + } + this.t = 0; + this.s = 0; + var i = s.length, + mi = false, + sh = 0; + while (--i >= 0) { + var x = k == 8 ? s[i] & 255 : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == '-') mi = true; + continue; + } + mi = false; + if (sh == 0) this.data[this.t++] = x; + else if (sh + k > this.DB) { + this.data[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; + this.data[this.t++] = x >> (this.DB - sh); + } else this.data[this.t - 1] |= x << sh; + sh += k; + if (sh >= this.DB) sh -= this.DB; + } + if (k == 8 && (s[0] & 128) != 0) { + this.s = -1; + if (sh > 0) this.data[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; + } + this.clamp(); + if (mi) BigInteger.ZERO.subTo(this, this); + }; + var bnpClamp = function () { + var c = this.s & this.DM; + while (this.t > 0 && this.data[this.t - 1] == c) --this.t; + }; + var bnToString = function (b3) { + if (this.s < 0) return '-' + this.negate().toString(b3); + var k; + if (b3 == 16) k = 4; + else if (b3 == 8) k = 3; + else if (b3 == 2) k = 1; + else if (b3 == 32) k = 5; + else if (b3 == 4) k = 2; + else return this.toRadix(b3); + var km = (1 << k) - 1, + d, + m2 = false, + r = '', + i = this.t; + var p = this.DB - ((i * this.DB) % k); + if (i-- > 0) { + if (p < this.DB && (d = this.data[i] >> p) > 0) { + m2 = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this.data[i] & ((1 << p) - 1)) << (k - p); + d |= this.data[--i] >> (p += this.DB - k); + } else { + d = (this.data[i] >> (p -= k)) & km; + if (p <= 0) { + p += this.DB; + --i; + } + } + if (d > 0) m2 = true; + if (m2) r += int2char(d); + } + } + return m2 ? r : '0'; + }; + var bnNegate = function () { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; + }; + var bnAbs = function () { + return this.s < 0 ? this.negate() : this; + }; + var bnCompareTo = function (a) { + var r = this.s - a.s; + if (r != 0) return r; + var i = this.t; + r = i - a.t; + if (r != 0) return this.s < 0 ? -r : r; + while (--i >= 0) if ((r = this.data[i] - a.data[i]) != 0) return r; + return 0; + }; + var nbits = function (x) { + var r = 1, + t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; + } + if ((t = x >> 8) != 0) { + x = t; + r += 8; + } + if ((t = x >> 4) != 0) { + x = t; + r += 4; + } + if ((t = x >> 2) != 0) { + x = t; + r += 2; + } + if ((t = x >> 1) != 0) { + x = t; + r += 1; + } + return r; + }; + var bnBitLength = function () { + if (this.t <= 0) return 0; + return this.DB * (this.t - 1) + nbits(this.data[this.t - 1] ^ (this.s & this.DM)); + }; + var bnpDLShiftTo = function (n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) r.data[i + n] = this.data[i]; + for (i = n - 1; i >= 0; --i) r.data[i] = 0; + r.t = this.t + n; + r.s = this.s; + }; + var bnpDRShiftTo = function (n, r) { + for (var i = n; i < this.t; ++i) r.data[i - n] = this.data[i]; + r.t = Math.max(this.t - n, 0); + r.s = this.s; + }; + var bnpLShiftTo = function (n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm2 = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB), + c = (this.s << bs) & this.DM, + i; + for (i = this.t - 1; i >= 0; --i) { + r.data[i + ds + 1] = (this.data[i] >> cbs) | c; + c = (this.data[i] & bm2) << bs; + } + for (i = ds - 1; i >= 0; --i) r.data[i] = 0; + r.data[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); + }; + var bnpRShiftTo = function (n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm2 = (1 << bs) - 1; + r.data[0] = this.data[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r.data[i - ds - 1] |= (this.data[i] & bm2) << cbs; + r.data[i - ds] = this.data[i] >> bs; + } + if (bs > 0) r.data[this.t - ds - 1] |= (this.s & bm2) << cbs; + r.t = this.t - ds; + r.clamp(); + }; + var bnpSubTo = function (a, r) { + var i = 0, + c = 0, + m2 = Math.min(a.t, this.t); + while (i < m2) { + c += this.data[i] - a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c -= a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = c < 0 ? -1 : 0; + if (c < -1) r.data[i++] = this.DV + c; + else if (c > 0) r.data[i++] = c; + r.t = i; + r.clamp(); + }; + var bnpMultiplyTo = function (a, r) { + var x = this.abs(), + y3 = a.abs(); + var i = x.t; + r.t = i + y3.t; + while (--i >= 0) r.data[i] = 0; + for (i = 0; i < y3.t; ++i) r.data[i + x.t] = x.am(0, y3.data[i], r, i, 0, x.t); + r.s = 0; + r.clamp(); + if (this.s != a.s) BigInteger.ZERO.subTo(r, r); + }; + var bnpSquareTo = function (r) { + var x = this.abs(); + var i = (r.t = 2 * x.t); + while (--i >= 0) r.data[i] = 0; + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x.data[i], r, 2 * i, 0, 1); + if ((r.data[i + x.t] += x.am(i + 1, 2 * x.data[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r.data[i + x.t] -= x.DV; + r.data[i + x.t + 1] = 1; + } + } + if (r.t > 0) r.data[r.t - 1] += x.am(i, x.data[i], r, 2 * i, 0, 1); + r.s = 0; + r.clamp(); + }; + var bnpDivRemTo = function (m2, q2, r) { + var pm2 = m2.abs(); + if (pm2.t <= 0) return; + var pt = this.abs(); + if (pt.t < pm2.t) { + if (q2 != null) q2.fromInt(0); + if (r != null) this.copyTo(r); + return; + } + if (r == null) r = nbi(); + var y3 = nbi(), + ts = this.s, + ms = m2.s; + var nsh = this.DB - nbits(pm2.data[pm2.t - 1]); + if (nsh > 0) { + pm2.lShiftTo(nsh, y3); + pt.lShiftTo(nsh, r); + } else { + pm2.copyTo(y3); + pt.copyTo(r); + } + var ys = y3.t; + var y0 = y3.data[ys - 1]; + if (y0 == 0) return; + var yt = y0 * (1 << this.F1) + (ys > 1 ? y3.data[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt, + d2 = (1 << this.F1) / yt, + e = 1 << this.F2; + var i = r.t, + j = i - ys, + t = q2 == null ? nbi() : q2; + y3.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r.data[r.t++] = 1; + r.subTo(t, r); + } + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y3, y3); + while (y3.t < ys) y3.data[y3.t++] = 0; + while (--j >= 0) { + var qd2 = r.data[--i] == y0 ? this.DM : Math.floor(r.data[i] * d1 + (r.data[i - 1] + e) * d2); + if ((r.data[i] += y3.am(0, qd2, r, j, 0, ys)) < qd2) { + y3.dlShiftTo(j, t); + r.subTo(t, r); + while (r.data[i] < --qd2) r.subTo(t, r); + } + } + if (q2 != null) { + r.drShiftTo(ys, q2); + if (ts != ms) BigInteger.ZERO.subTo(q2, q2); + } + r.t = ys; + r.clamp(); + if (nsh > 0) r.rShiftTo(nsh, r); + if (ts < 0) BigInteger.ZERO.subTo(r, r); + }; + var bnMod = function (a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); + return r; + }; + var Classic = function (m2) { + this.m = m2; + }; + var cConvert = function (x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; + }; + var cRevert = function (x) { + return x; + }; + var cReduce = function (x) { + x.divRemTo(this.m, null, x); + }; + var cMulTo = function (x, y3, r) { + x.multiplyTo(y3, r); + this.reduce(r); + }; + var cSqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + var bnpInvDigit = function () { + if (this.t < 1) return 0; + var x = this.data[0]; + if ((x & 1) == 0) return 0; + var y3 = x & 3; + y3 = (y3 * (2 - (x & 15) * y3)) & 15; + y3 = (y3 * (2 - (x & 255) * y3)) & 255; + y3 = (y3 * (2 - (((x & 65535) * y3) & 65535))) & 65535; + y3 = (y3 * (2 - ((x * y3) % this.DV))) % this.DV; + return y3 > 0 ? this.DV - y3 : -y3; + }; + var Montgomery = function (m2) { + this.m = m2; + this.mp = m2.invDigit(); + this.mpl = this.mp & 32767; + this.mph = this.mp >> 15; + this.um = (1 << (m2.DB - 15)) - 1; + this.mt2 = 2 * m2.t; + }; + var montConvert = function (x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); + return r; + }; + var montRevert = function (x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + }; + var montReduce = function (x) { + while (x.t <= this.mt2) x.data[x.t++] = 0; + for (var i = 0; i < this.m.t; ++i) { + var j = x.data[i] & 32767; + var u02 = (j * this.mpl + (((j * this.mph + (x.data[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; + j = i + this.m.t; + x.data[j] += this.m.am(0, u02, x, i, 0, this.m.t); + while (x.data[j] >= x.DV) { + x.data[j] -= x.DV; + x.data[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + }; + var montSqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + var montMulTo = function (x, y3, r) { + x.multiplyTo(y3, r); + this.reduce(r); + }; + var bnpIsEven = function () { + return (this.t > 0 ? this.data[0] & 1 : this.s) == 0; + }; + var bnpExp = function (e, z2) { + if (e > 4294967295 || e < 1) return BigInteger.ONE; + var r = nbi(), + r2 = nbi(), + g = z2.convert(this), + i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z2.sqrTo(r, r2); + if ((e & (1 << i)) > 0) z2.mulTo(r2, g, r); + else { + var t = r; + r = r2; + r2 = t; + } + } + return z2.revert(r); + }; + var bnModPowInt = function (e, m2) { + var z2; + if (e < 256 || m2.isEven()) z2 = new Classic(m2); + else z2 = new Montgomery(m2); + return this.exp(e, z2); + }; + var bnClone = function () { + var r = nbi(); + this.copyTo(r); + return r; + }; + var bnIntValue = function () { + if (this.s < 0) { + if (this.t == 1) return this.data[0] - this.DV; + else if (this.t == 0) return -1; + } else if (this.t == 1) return this.data[0]; + else if (this.t == 0) return 0; + return ((this.data[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this.data[0]; + }; + var bnByteValue = function () { + return this.t == 0 ? this.s : (this.data[0] << 24) >> 24; + }; + var bnShortValue = function () { + return this.t == 0 ? this.s : (this.data[0] << 16) >> 16; + }; + var bnpChunkSize = function (r) { + return Math.floor((Math.LN2 * this.DB) / Math.log(r)); + }; + var bnSigNum = function () { + if (this.s < 0) return -1; + else if (this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0; + else return 1; + }; + var bnpToRadix = function (b3) { + if (b3 == null) b3 = 10; + if (this.signum() == 0 || b3 < 2 || b3 > 36) return '0'; + var cs = this.chunkSize(b3); + var a = Math.pow(b3, cs); + var d = nbv(a), + y3 = nbi(), + z2 = nbi(), + r = ''; + this.divRemTo(d, y3, z2); + while (y3.signum() > 0) { + r = (a + z2.intValue()).toString(b3).substr(1) + r; + y3.divRemTo(d, y3, z2); + } + return z2.intValue().toString(b3) + r; + }; + var bnpFromRadix = function (s, b3) { + this.fromInt(0); + if (b3 == null) b3 = 10; + var cs = this.chunkSize(b3); + var d = Math.pow(b3, cs), + mi = false, + j = 0, + w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == '-' && this.signum() == 0) mi = true; + continue; + } + w = b3 * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; + } + } + if (j > 0) { + this.dMultiply(Math.pow(b3, j)); + this.dAddOffset(w, 0); + } + if (mi) BigInteger.ZERO.subTo(this, this); + }; + var bnpFromNumber = function (a, b3, c) { + if (typeof b3 == 'number') { + if (a < 2) this.fromInt(1); + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + if (this.isEven()) this.dAddOffset(1, 0); + while (!this.isProbablePrime(b3)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } + } + } else { + var x = new Array(), + t = a & 7; + x.length = (a >> 3) + 1; + b3.nextBytes(x); + if (t > 0) x[0] &= (1 << t) - 1; + else x[0] = 0; + this.fromString(x, 256); + } + }; + var bnToByteArray = function () { + var i = this.t, + r = new Array(); + r[0] = this.s; + var p = this.DB - ((i * this.DB) % 8), + d, + k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this.data[i] >> p) != (this.s & this.DM) >> p) r[k++] = d | (this.s << (this.DB - p)); + while (i >= 0) { + if (p < 8) { + d = (this.data[i] & ((1 << p) - 1)) << (8 - p); + d |= this.data[--i] >> (p += this.DB - 8); + } else { + d = (this.data[i] >> (p -= 8)) & 255; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 128) != 0) d |= -256; + if (k == 0 && (this.s & 128) != (d & 128)) ++k; + if (k > 0 || d != this.s) r[k++] = d; + } + } + return r; + }; + var bnEquals = function (a) { + return this.compareTo(a) == 0; + }; + var bnMin = function (a) { + return this.compareTo(a) < 0 ? this : a; + }; + var bnMax = function (a) { + return this.compareTo(a) > 0 ? this : a; + }; + var bnpBitwiseTo = function (a, op, r) { + var i, + f, + m2 = Math.min(a.t, this.t); + for (i = 0; i < m2; ++i) r.data[i] = op(this.data[i], a.data[i]); + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m2; i < this.t; ++i) r.data[i] = op(this.data[i], f); + r.t = this.t; + } else { + f = this.s & this.DM; + for (i = m2; i < a.t; ++i) r.data[i] = op(f, a.data[i]); + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); + }; + var op_and = function (x, y3) { + return x & y3; + }; + var bnAnd = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; + }; + var op_or = function (x, y3) { + return x | y3; + }; + var bnOr = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; + }; + var op_xor = function (x, y3) { + return x ^ y3; + }; + var bnXor = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; + }; + var op_andnot = function (x, y3) { + return x & ~y3; + }; + var bnAndNot = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; + }; + var bnNot = function () { + var r = nbi(); + for (var i = 0; i < this.t; ++i) r.data[i] = this.DM & ~this.data[i]; + r.t = this.t; + r.s = ~this.s; + return r; + }; + var bnShiftLeft = function (n) { + var r = nbi(); + if (n < 0) this.rShiftTo(-n, r); + else this.lShiftTo(n, r); + return r; + }; + var bnShiftRight = function (n) { + var r = nbi(); + if (n < 0) this.lShiftTo(-n, r); + else this.rShiftTo(n, r); + return r; + }; + var lbit = function (x) { + if (x == 0) return -1; + var r = 0; + if ((x & 65535) == 0) { + x >>= 16; + r += 16; + } + if ((x & 255) == 0) { + x >>= 8; + r += 8; + } + if ((x & 15) == 0) { + x >>= 4; + r += 4; + } + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0) ++r; + return r; + }; + var bnGetLowestSetBit = function () { + for (var i = 0; i < this.t; ++i) if (this.data[i] != 0) return i * this.DB + lbit(this.data[i]); + if (this.s < 0) return this.t * this.DB; + return -1; + }; + var cbit = function (x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; + }; + var bnBitCount = function () { + var r = 0, + x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) r += cbit(this.data[i] ^ x); + return r; + }; + var bnTestBit = function (n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) return this.s != 0; + return (this.data[j] & (1 << n % this.DB)) != 0; + }; + var bnpChangeBit = function (n, op) { + var r = BigInteger.ONE.shiftLeft(n); + this.bitwiseTo(r, op, r); + return r; + }; + var bnSetBit = function (n) { + return this.changeBit(n, op_or); + }; + var bnClearBit = function (n) { + return this.changeBit(n, op_andnot); + }; + var bnFlipBit = function (n) { + return this.changeBit(n, op_xor); + }; + var bnpAddTo = function (a, r) { + var i = 0, + c = 0, + m2 = Math.min(a.t, this.t); + while (i < m2) { + c += this.data[i] + a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c += a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = c < 0 ? -1 : 0; + if (c > 0) r.data[i++] = c; + else if (c < -1) r.data[i++] = this.DV + c; + r.t = i; + r.clamp(); + }; + var bnAdd = function (a) { + var r = nbi(); + this.addTo(a, r); + return r; + }; + var bnSubtract = function (a) { + var r = nbi(); + this.subTo(a, r); + return r; + }; + var bnMultiply = function (a) { + var r = nbi(); + this.multiplyTo(a, r); + return r; + }; + var bnDivide = function (a) { + var r = nbi(); + this.divRemTo(a, r, null); + return r; + }; + var bnRemainder = function (a) { + var r = nbi(); + this.divRemTo(a, null, r); + return r; + }; + var bnDivideAndRemainder = function (a) { + var q2 = nbi(), + r = nbi(); + this.divRemTo(a, q2, r); + return new Array(q2, r); + }; + var bnpDMultiply = function (n) { + this.data[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); + }; + var bnpDAddOffset = function (n, w) { + if (n == 0) return; + while (this.t <= w) this.data[this.t++] = 0; + this.data[w] += n; + while (this.data[w] >= this.DV) { + this.data[w] -= this.DV; + if (++w >= this.t) this.data[this.t++] = 0; + ++this.data[w]; + } + }; + var NullExp = function () {}; + var nNop = function (x) { + return x; + }; + var nMulTo = function (x, y3, r) { + x.multiplyTo(y3, r); + }; + var nSqrTo = function (x, r) { + x.squareTo(r); + }; + var bnPow = function (e) { + return this.exp(e, new NullExp()); + }; + var bnpMultiplyLowerTo = function (a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; + r.t = i; + while (i > 0) r.data[--i] = 0; + var j; + for (j = r.t - this.t; i < j; ++i) r.data[i + this.t] = this.am(0, a.data[i], r, i, 0, this.t); + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a.data[i], r, i, 0, n - i); + r.clamp(); + }; + var bnpMultiplyUpperTo = function (a, n, r) { + --n; + var i = (r.t = this.t + a.t - n); + r.s = 0; + while (--i >= 0) r.data[i] = 0; + for (i = Math.max(n - this.t, 0); i < a.t; ++i) r.data[this.t + i - n] = this.am(n - i, a.data[i], r, 0, 0, this.t + i - n); + r.clamp(); + r.drShiftTo(1, r); + }; + var Barrett = function (m2) { + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m2.t, this.r2); + this.mu = this.r2.divide(m2); + this.m = m2; + }; + var barrettConvert = function (x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); + else if (x.compareTo(this.m) < 0) return x; + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + }; + var barrettRevert = function (x) { + return x; + }; + var barrettReduce = function (x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + }; + var barrettSqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + var barrettMulTo = function (x, y3, r) { + x.multiplyTo(y3, r); + this.reduce(r); + }; + var bnModPow = function (e, m2) { + var i = e.bitLength(), + k, + r = nbv(1), + z2; + if (i <= 0) return r; + else if (i < 18) k = 1; + else if (i < 48) k = 3; + else if (i < 144) k = 4; + else if (i < 768) k = 5; + else k = 6; + if (i < 8) z2 = new Classic(m2); + else if (m2.isEven()) z2 = new Barrett(m2); + else z2 = new Montgomery(m2); + var g = new Array(), + n = 3, + k12 = k - 1, + km = (1 << k) - 1; + g[1] = z2.convert(this); + if (k > 1) { + var g2 = nbi(); + z2.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z2.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + var j = e.t - 1, + w, + is1 = true, + r2 = nbi(), + t; + i = nbits(e.data[j]) - 1; + while (j >= 0) { + if (i >= k12) w = (e.data[j] >> (i - k12)) & km; + else { + w = (e.data[j] & ((1 << (i + 1)) - 1)) << (k12 - i); + if (j > 0) w |= e.data[j - 1] >> (this.DB + i - k12); + } + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { + g[w].copyTo(r); + is1 = false; + } else { + while (n > 1) { + z2.sqrTo(r, r2); + z2.sqrTo(r2, r); + n -= 2; + } + if (n > 0) z2.sqrTo(r, r2); + else { + t = r; + r = r2; + r2 = t; + } + z2.mulTo(r2, g[w], r); + } + while (j >= 0 && (e.data[j] & (1 << i)) == 0) { + z2.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z2.revert(r); + }; + var bnGCD = function (a) { + var x = this.s < 0 ? this.negate() : this.clone(); + var y3 = a.s < 0 ? a.negate() : a.clone(); + if (x.compareTo(y3) < 0) { + var t = x; + x = y3; + y3 = t; + } + var i = x.getLowestSetBit(), + g = y3.getLowestSetBit(); + if (g < 0) return x; + if (i < g) g = i; + if (g > 0) { + x.rShiftTo(g, x); + y3.rShiftTo(g, y3); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); + if ((i = y3.getLowestSetBit()) > 0) y3.rShiftTo(i, y3); + if (x.compareTo(y3) >= 0) { + x.subTo(y3, x); + x.rShiftTo(1, x); + } else { + y3.subTo(x, y3); + y3.rShiftTo(1, y3); + } + } + if (g > 0) y3.lShiftTo(g, y3); + return y3; + }; + var bnpModInt = function (n) { + if (n <= 0) return 0; + var d = this.DV % n, + r = this.s < 0 ? n - 1 : 0; + if (this.t > 0) + if (d == 0) r = this.data[0] % n; + else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this.data[i]) % n; + return r; + }; + var bnModInverse = function (m2) { + var ac = m2.isEven(); + if ((this.isEven() && ac) || m2.signum() == 0) return BigInteger.ZERO; + var u = m2.clone(), + v = this.clone(); + var a = nbv(1), + b3 = nbv(0), + c = nbv(0), + d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b3.isEven()) { + a.addTo(this, a); + b3.subTo(m2, b3); + } + a.rShiftTo(1, a); + } else if (!b3.isEven()) b3.subTo(m2, b3); + b3.rShiftTo(1, b3); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m2, d); + } + c.rShiftTo(1, c); + } else if (!d.isEven()) d.subTo(m2, d); + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) a.subTo(c, a); + b3.subTo(d, b3); + } else { + v.subTo(u, v); + if (ac) c.subTo(a, c); + d.subTo(b3, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if (d.compareTo(m2) >= 0) return d.subtract(m2); + if (d.signum() < 0) d.addTo(m2, d); + else return d; + if (d.signum() < 0) return d.add(m2); + else return d; + }; + var bnIsProbablePrime = function (t) { + var i, + x = this.abs(); + if (x.t == 1 && x.data[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) if (x.data[0] == lowprimes[i]) return true; + return false; + } + if (x.isEven()) return false; + i = 1; + while (i < lowprimes.length) { + var m2 = lowprimes[i], + j = i + 1; + while (j < lowprimes.length && m2 < lplim) m2 *= lowprimes[j++]; + m2 = x.modInt(m2); + while (i < j) if (m2 % lowprimes[i++] == 0) return false; + } + return x.millerRabin(t); + }; + var bnpMillerRabin = function (t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) return false; + var r = n1.shiftRight(k); + var prng = bnGetPrng(); + var a; + for (var i = 0; i < t; ++i) { + do { + a = new BigInteger(this.bitLength(), prng); + } while (a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); + var y3 = a.modPow(r, this); + if (y3.compareTo(BigInteger.ONE) != 0 && y3.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y3.compareTo(n1) != 0) { + y3 = y3.modPowInt(2, this); + if (y3.compareTo(BigInteger.ONE) == 0) return false; + } + if (y3.compareTo(n1) != 0) return false; + } + } + return true; + }; + var bnGetPrng = function () { + return { + nextBytes: function (x) { + for (var i = 0; i < x.length; ++i) { + x[i] = Math.floor(Math.random() * 256); + } + } + }; + }; + var forge = require_forge(); + module.exports = forge.jsbn = forge.jsbn || {}; + var dbits; + var canary = 244837814094590; + var j_lm = (canary & 16777215) == 15715070; + forge.jsbn.BigInteger = BigInteger; + if (typeof navigator === 'undefined') { + BigInteger.prototype.am = am3; + dbits = 28; + } else if (j_lm && navigator.appName == 'Microsoft Internet Explorer') { + BigInteger.prototype.am = am2; + dbits = 30; + } else if (j_lm && navigator.appName != 'Netscape') { + BigInteger.prototype.am = am1; + dbits = 26; + } else { + BigInteger.prototype.am = am3; + dbits = 28; + } + BigInteger.prototype.DB = dbits; + BigInteger.prototype.DM = (1 << dbits) - 1; + BigInteger.prototype.DV = 1 << dbits; + var BI_FP = 52; + BigInteger.prototype.FV = Math.pow(2, BI_FP); + BigInteger.prototype.F1 = BI_FP - dbits; + BigInteger.prototype.F2 = 2 * dbits - BI_FP; + var BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz'; + var BI_RC = new Array(); + var rr; + var vv; + rr = '0'.charCodeAt(0); + for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; + rr = 'a'.charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + rr = 'A'.charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + Classic.prototype.convert = cConvert; + Classic.prototype.revert = cRevert; + Classic.prototype.reduce = cReduce; + Classic.prototype.mulTo = cMulTo; + Classic.prototype.sqrTo = cSqrTo; + Montgomery.prototype.convert = montConvert; + Montgomery.prototype.revert = montRevert; + Montgomery.prototype.reduce = montReduce; + Montgomery.prototype.mulTo = montMulTo; + Montgomery.prototype.sqrTo = montSqrTo; + BigInteger.prototype.copyTo = bnpCopyTo; + BigInteger.prototype.fromInt = bnpFromInt; + BigInteger.prototype.fromString = bnpFromString; + BigInteger.prototype.clamp = bnpClamp; + BigInteger.prototype.dlShiftTo = bnpDLShiftTo; + BigInteger.prototype.drShiftTo = bnpDRShiftTo; + BigInteger.prototype.lShiftTo = bnpLShiftTo; + BigInteger.prototype.rShiftTo = bnpRShiftTo; + BigInteger.prototype.subTo = bnpSubTo; + BigInteger.prototype.multiplyTo = bnpMultiplyTo; + BigInteger.prototype.squareTo = bnpSquareTo; + BigInteger.prototype.divRemTo = bnpDivRemTo; + BigInteger.prototype.invDigit = bnpInvDigit; + BigInteger.prototype.isEven = bnpIsEven; + BigInteger.prototype.exp = bnpExp; + BigInteger.prototype.toString = bnToString; + BigInteger.prototype.negate = bnNegate; + BigInteger.prototype.abs = bnAbs; + BigInteger.prototype.compareTo = bnCompareTo; + BigInteger.prototype.bitLength = bnBitLength; + BigInteger.prototype.mod = bnMod; + BigInteger.prototype.modPowInt = bnModPowInt; + BigInteger.ZERO = nbv(0); + BigInteger.ONE = nbv(1); + NullExp.prototype.convert = nNop; + NullExp.prototype.revert = nNop; + NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.sqrTo = nSqrTo; + Barrett.prototype.convert = barrettConvert; + Barrett.prototype.revert = barrettRevert; + Barrett.prototype.reduce = barrettReduce; + Barrett.prototype.mulTo = barrettMulTo; + Barrett.prototype.sqrTo = barrettSqrTo; + var lowprimes = [ + 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, + 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509 + ]; + var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + BigInteger.prototype.chunkSize = bnpChunkSize; + BigInteger.prototype.toRadix = bnpToRadix; + BigInteger.prototype.fromRadix = bnpFromRadix; + BigInteger.prototype.fromNumber = bnpFromNumber; + BigInteger.prototype.bitwiseTo = bnpBitwiseTo; + BigInteger.prototype.changeBit = bnpChangeBit; + BigInteger.prototype.addTo = bnpAddTo; + BigInteger.prototype.dMultiply = bnpDMultiply; + BigInteger.prototype.dAddOffset = bnpDAddOffset; + BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; + BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; + BigInteger.prototype.modInt = bnpModInt; + BigInteger.prototype.millerRabin = bnpMillerRabin; + BigInteger.prototype.clone = bnClone; + BigInteger.prototype.intValue = bnIntValue; + BigInteger.prototype.byteValue = bnByteValue; + BigInteger.prototype.shortValue = bnShortValue; + BigInteger.prototype.signum = bnSigNum; + BigInteger.prototype.toByteArray = bnToByteArray; + BigInteger.prototype.equals = bnEquals; + BigInteger.prototype.min = bnMin; + BigInteger.prototype.max = bnMax; + BigInteger.prototype.and = bnAnd; + BigInteger.prototype.or = bnOr; + BigInteger.prototype.xor = bnXor; + BigInteger.prototype.andNot = bnAndNot; + BigInteger.prototype.not = bnNot; + BigInteger.prototype.shiftLeft = bnShiftLeft; + BigInteger.prototype.shiftRight = bnShiftRight; + BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; + BigInteger.prototype.bitCount = bnBitCount; + BigInteger.prototype.testBit = bnTestBit; + BigInteger.prototype.setBit = bnSetBit; + BigInteger.prototype.clearBit = bnClearBit; + BigInteger.prototype.flipBit = bnFlipBit; + BigInteger.prototype.add = bnAdd; + BigInteger.prototype.subtract = bnSubtract; + BigInteger.prototype.multiply = bnMultiply; + BigInteger.prototype.divide = bnDivide; + BigInteger.prototype.remainder = bnRemainder; + BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; + BigInteger.prototype.modPow = bnModPow; + BigInteger.prototype.modInverse = bnModInverse; + BigInteger.prototype.pow = bnPow; + BigInteger.prototype.gcd = bnGCD; + BigInteger.prototype.isProbablePrime = bnIsProbablePrime; +}); + +// node_modules/node-forge/lib/sha1.js +var require_sha1 = __commonJS((exports, module) => { + var _init = function () { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 64); + _initialized = true; + }; + var _update = function (s, w, bytes) { + var t, a, b3, c, d, e, f, i; + var len = bytes.length(); + while (len >= 64) { + a = s.h0; + b3 = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + for (i = 0; i < 16; ++i) { + t = bytes.getInt32(); + w[i] = t; + f = d ^ (b3 & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 1518500249 + t; + e = d; + d = c; + c = ((b3 << 30) | (b3 >>> 2)) >>> 0; + b3 = a; + a = t; + } + for (; i < 20; ++i) { + t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; + t = (t << 1) | (t >>> 31); + w[i] = t; + f = d ^ (b3 & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 1518500249 + t; + e = d; + d = c; + c = ((b3 << 30) | (b3 >>> 2)) >>> 0; + b3 = a; + a = t; + } + for (; i < 32; ++i) { + t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; + t = (t << 1) | (t >>> 31); + w[i] = t; + f = b3 ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 1859775393 + t; + e = d; + d = c; + c = ((b3 << 30) | (b3 >>> 2)) >>> 0; + b3 = a; + a = t; + } + for (; i < 40; ++i) { + t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b3 ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 1859775393 + t; + e = d; + d = c; + c = ((b3 << 30) | (b3 >>> 2)) >>> 0; + b3 = a; + a = t; + } + for (; i < 60; ++i) { + t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; + t = (t << 2) | (t >>> 30); + w[i] = t; + f = (b3 & c) | (d & (b3 ^ c)); + t = ((a << 5) | (a >>> 27)) + f + e + 2400959708 + t; + e = d; + d = c; + c = ((b3 << 30) | (b3 >>> 2)) >>> 0; + b3 = a; + a = t; + } + for (; i < 80; ++i) { + t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b3 ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 3395469782 + t; + e = d; + d = c; + c = ((b3 << 30) | (b3 >>> 2)) >>> 0; + b3 = a; + a = t; + } + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b3) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + len -= 64; + } + }; + var forge = require_forge(); + require_md(); + require_util(); + var sha1 = (module.exports = forge.sha1 = forge.sha1 || {}); + forge.md.sha1 = forge.md.algorithms.sha1 = sha1; + sha1.create = function () { + if (!_initialized) { + _init(); + } + var _state = null; + var _input = forge.util.createBuffer(); + var _w = new Array(80); + var md = { + algorithm: 'sha1', + blockLength: 64, + digestLength: 20, + messageLength: 0, + fullMessageLength: null, + messageLengthSize: 8 + }; + md.start = function () { + md.messageLength = 0; + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 1732584193, + h1: 4023233417, + h2: 2562383102, + h3: 271733878, + h4: 3285377520 + }; + return md; + }; + md.start(); + md.update = function (msg, encoding) { + if (encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + var len = msg.length; + md.messageLength += len; + len = [(len / 4294967296) >>> 0, len >>> 0]; + for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 4294967296) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = (len[1] / 4294967296) >>> 0; + } + _input.putBytes(msg); + _update(_state, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + return md; + }; + md.digest = function () { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 4294967296) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + var s22 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4 + }; + _update(s22, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s22.h0); + rval.putInt32(s22.h1); + rval.putInt32(s22.h2); + rval.putInt32(s22.h3); + rval.putInt32(s22.h4); + return rval; + }; + return md; + }; + var _padding = null; + var _initialized = false; +}); + +// node_modules/node-forge/lib/pkcs1.js +var require_pkcs1 = __commonJS((exports, module) => { + var rsa_mgf1 = function (seed, maskLength, hash) { + if (!hash) { + hash = forge.md.sha1.create(); + } + var t = ''; + var count = Math.ceil(maskLength / hash.digestLength); + for (var i = 0; i < count; ++i) { + var c = String.fromCharCode((i >> 24) & 255, (i >> 16) & 255, (i >> 8) & 255, i & 255); + hash.start(); + hash.update(seed + c); + t += hash.digest().getBytes(); + } + return t.substring(0, maskLength); + }; + var forge = require_forge(); + require_util(); + require_random(); + require_sha1(); + var pkcs1 = (module.exports = forge.pkcs1 = forge.pkcs1 || {}); + pkcs1.encode_rsa_oaep = function (key, message, options) { + var label; + var seed; + var md; + var mgf1Md; + if (typeof options === 'string') { + label = options; + seed = arguments[3] || undefined; + md = arguments[4] || undefined; + } else if (options) { + label = options.label || undefined; + seed = options.seed || undefined; + md = options.md || undefined; + if (options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + if (!md) { + md = forge.md.sha1.create(); + } else { + md.start(); + } + if (!mgf1Md) { + mgf1Md = md; + } + var keyLength = Math.ceil(key.n.bitLength() / 8); + var maxLength = keyLength - 2 * md.digestLength - 2; + if (message.length > maxLength) { + var error = new Error('RSAES-OAEP input message length is too long.'); + error.length = message.length; + error.maxLength = maxLength; + throw error; + } + if (!label) { + label = ''; + } + md.update(label, 'raw'); + var lHash = md.digest(); + var PS = ''; + var PS_length = maxLength - message.length; + for (var i = 0; i < PS_length; i++) { + PS += '\0'; + } + var DB = lHash.getBytes() + PS + '\x01' + message; + if (!seed) { + seed = forge.random.getBytes(md.digestLength); + } else if (seed.length !== md.digestLength) { + var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' + 'match the digest length.'); + error.seedLength = seed.length; + error.digestLength = md.digestLength; + throw error; + } + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); + return '\0' + maskedSeed + maskedDB; + }; + pkcs1.decode_rsa_oaep = function (key, em2, options) { + var label; + var md; + var mgf1Md; + if (typeof options === 'string') { + label = options; + md = arguments[3] || undefined; + } else if (options) { + label = options.label || undefined; + md = options.md || undefined; + if (options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + var keyLength = Math.ceil(key.n.bitLength() / 8); + if (em2.length !== keyLength) { + var error = new Error('RSAES-OAEP encoded message length is invalid.'); + error.length = em2.length; + error.expectedLength = keyLength; + throw error; + } + if (md === undefined) { + md = forge.md.sha1.create(); + } else { + md.start(); + } + if (!mgf1Md) { + mgf1Md = md; + } + if (keyLength < 2 * md.digestLength + 2) { + throw new Error('RSAES-OAEP key is too short for the hash function.'); + } + if (!label) { + label = ''; + } + md.update(label, 'raw'); + var lHash = md.digest().getBytes(); + var y3 = em2.charAt(0); + var maskedSeed = em2.substring(1, md.digestLength + 1); + var maskedDB = em2.substring(1 + md.digestLength); + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var db2 = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); + var lHashPrime = db2.substring(0, md.digestLength); + var error = y3 !== '\0'; + for (var i = 0; i < md.digestLength; ++i) { + error |= lHash.charAt(i) !== lHashPrime.charAt(i); + } + var in_ps = 1; + var index = md.digestLength; + for (var j = md.digestLength; j < db2.length; j++) { + var code = db2.charCodeAt(j); + var is_0 = (code & 1) ^ 1; + var error_mask = in_ps ? 65534 : 0; + error |= code & error_mask; + in_ps = in_ps & is_0; + index += in_ps; + } + if (error || db2.charCodeAt(index) !== 1) { + throw new Error('Invalid RSAES-OAEP padding.'); + } + return db2.substring(index + 1); + }; +}); + +// node_modules/node-forge/lib/prime.js +var require_prime = __commonJS((exports, module) => { + var forge = require_forge(); + require_util(); + require_jsbn(); + require_random(); + (function () { + if (forge.prime) { + module.exports = forge.prime; + return; + } + var prime = (module.exports = forge.prime = forge.prime || {}); + var BigInteger = forge.jsbn.BigInteger; + var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + var THIRTY = new BigInteger(null); + THIRTY.fromInt(30); + var op_or = function (x, y3) { + return x | y3; + }; + prime.generateProbablePrime = function (bits, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + var algorithm = options.algorithm || 'PRIMEINC'; + if (typeof algorithm === 'string') { + algorithm = {name: algorithm}; + } + algorithm.options = algorithm.options || {}; + var prng = options.prng || forge.random; + var rng = { + nextBytes: function (x) { + var b3 = prng.getBytesSync(x.length); + for (var i = 0; i < x.length; ++i) { + x[i] = b3.charCodeAt(i); + } + } + }; + if (algorithm.name === 'PRIMEINC') { + return primeincFindPrime(bits, rng, algorithm.options, callback); + } + throw new Error('Invalid prime generation algorithm: ' + algorithm.name); + }; + function primeincFindPrime(bits, rng, options, callback) { + if ('workers' in options) { + return primeincFindPrimeWithWorkers(bits, rng, options, callback); + } + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + } + function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { + var num = generateRandom(bits, rng); + var deltaIdx = 0; + var mrTests = getMillerRabinTests(num.bitLength()); + if ('millerRabinTests' in options) { + mrTests = options.millerRabinTests; + } + var maxBlockTime = 10; + if ('maxBlockTime' in options) { + maxBlockTime = options.maxBlockTime; + } + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + } + function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { + var start = +new Date(); + do { + if (num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + if (num.isProbablePrime(mrTests)) { + return callback(null, num); + } + num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } while (maxBlockTime < 0 || +new Date() - start < maxBlockTime); + forge.util.setImmediate(function () { + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + }); + } + function primeincFindPrimeWithWorkers(bits, rng, options, callback) { + if (typeof Worker === 'undefined') { + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + } + var num = generateRandom(bits, rng); + var numWorkers = options.workers; + var workLoad = options.workLoad || 100; + var range = (workLoad * 30) / 8; + var workerScript = options.workerScript || 'forge/prime.worker.js'; + if (numWorkers === -1) { + return forge.util.estimateCores(function (err, cores) { + if (err) { + cores = 2; + } + numWorkers = cores - 1; + generate(); + }); + } + generate(); + function generate() { + numWorkers = Math.max(1, numWorkers); + var workers = []; + for (var i = 0; i < numWorkers; ++i) { + workers[i] = new Worker(workerScript); + } + var running = numWorkers; + for (var i = 0; i < numWorkers; ++i) { + workers[i].addEventListener('message', workerMessage); + } + var found = false; + function workerMessage(e) { + if (found) { + return; + } + --running; + var data = e.data; + if (data.found) { + for (var i3 = 0; i3 < workers.length; ++i3) { + workers[i3].terminate(); + } + found = true; + return callback(null, new BigInteger(data.prime, 16)); + } + if (num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + var hex = num.toString(16); + e.target.postMessage({ + hex, + workLoad + }); + num.dAddOffset(range, 0); + } + } + } + function generateRandom(bits, rng) { + var num = new BigInteger(bits, rng); + var bits1 = bits - 1; + if (!num.testBit(bits1)) { + num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); + } + num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); + return num; + } + function getMillerRabinTests(bits) { + if (bits <= 100) return 27; + if (bits <= 150) return 18; + if (bits <= 200) return 15; + if (bits <= 250) return 12; + if (bits <= 300) return 9; + if (bits <= 350) return 8; + if (bits <= 400) return 7; + if (bits <= 500) return 6; + if (bits <= 600) return 5; + if (bits <= 800) return 4; + if (bits <= 1250) return 3; + return 2; + } + })(); +}); + +// node_modules/node-forge/lib/rsa.js +var require_rsa = __commonJS((exports, module) => { + var _encodePkcs1_v1_5 = function (m2, key, bt) { + var eb2 = forge.util.createBuffer(); + var k = Math.ceil(key.n.bitLength() / 8); + if (m2.length > k - 11) { + var error = new Error('Message is too long for PKCS#1 v1.5 padding.'); + error.length = m2.length; + error.max = k - 11; + throw error; + } + eb2.putByte(0); + eb2.putByte(bt); + var padNum = k - 3 - m2.length; + var padByte; + if (bt === 0 || bt === 1) { + padByte = bt === 0 ? 0 : 255; + for (var i = 0; i < padNum; ++i) { + eb2.putByte(padByte); + } + } else { + while (padNum > 0) { + var numZeros = 0; + var padBytes = forge.random.getBytes(padNum); + for (var i = 0; i < padNum; ++i) { + padByte = padBytes.charCodeAt(i); + if (padByte === 0) { + ++numZeros; + } else { + eb2.putByte(padByte); + } + } + padNum = numZeros; + } + } + eb2.putByte(0); + eb2.putBytes(m2); + return eb2; + }; + var _decodePkcs1_v1_5 = function (em2, key, pub, ml) { + var k = Math.ceil(key.n.bitLength() / 8); + var eb2 = forge.util.createBuffer(em2); + var first = eb2.getByte(); + var bt = eb2.getByte(); + if (first !== 0 || (pub && bt !== 0 && bt !== 1) || (!pub && bt != 2) || (pub && bt === 0 && typeof ml === 'undefined')) { + throw new Error('Encryption block is invalid.'); + } + var padNum = 0; + if (bt === 0) { + padNum = k - 3 - ml; + for (var i = 0; i < padNum; ++i) { + if (eb2.getByte() !== 0) { + throw new Error('Encryption block is invalid.'); + } + } + } else if (bt === 1) { + padNum = 0; + while (eb2.length() > 1) { + if (eb2.getByte() !== 255) { + --eb2.read; + break; + } + ++padNum; + } + } else if (bt === 2) { + padNum = 0; + while (eb2.length() > 1) { + if (eb2.getByte() === 0) { + --eb2.read; + break; + } + ++padNum; + } + } + var zero = eb2.getByte(); + if (zero !== 0 || padNum !== k - 3 - eb2.length()) { + throw new Error('Encryption block is invalid.'); + } + return eb2.getBytes(); + }; + var _generateKeyPair = function (state, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + var opts = { + algorithm: { + name: options.algorithm || 'PRIMEINC', + options: { + workers: options.workers || 2, + workLoad: options.workLoad || 100, + workerScript: options.workerScript + } + } + }; + if ('prng' in options) { + opts.prng = options.prng; + } + generate(); + function generate() { + getPrime(state.pBits, function (err, num) { + if (err) { + return callback(err); + } + state.p = num; + if (state.q !== null) { + return finish(err, state.q); + } + getPrime(state.qBits, finish); + }); + } + function getPrime(bits, callback2) { + forge.prime.generateProbablePrime(bits, opts, callback2); + } + function finish(err, num) { + if (err) { + return callback(err); + } + state.q = num; + if (state.p.compareTo(state.q) < 0) { + var tmp = state.p; + state.p = state.q; + state.q = tmp; + } + if (state.p.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + state.p = null; + generate(); + return; + } + if (state.q.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + state.q = null; + getPrime(state.qBits, finish); + return; + } + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + if (state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + state.p = state.q = null; + generate(); + return; + } + state.n = state.p.multiply(state.q); + if (state.n.bitLength() !== state.bits) { + state.q = null; + getPrime(state.qBits, finish); + return; + } + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki.rsa.setPrivateKey(state.n, state.e, d, state.p, state.q, d.mod(state.p1), d.mod(state.q1), state.q.modInverse(state.p)), + publicKey: pki.rsa.setPublicKey(state.n, state.e) + }; + callback(null, state.keys); + } + }; + var _bnToBytes = function (b3) { + var hex = b3.toString(16); + if (hex[0] >= '8') { + hex = '00' + hex; + } + var bytes = forge.util.hexToBytes(hex); + if (bytes.length > 1 && ((bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 128) === 0) || (bytes.charCodeAt(0) === 255 && (bytes.charCodeAt(1) & 128) === 128))) { + return bytes.substr(1); + } + return bytes; + }; + var _getMillerRabinTests = function (bits) { + if (bits <= 100) return 27; + if (bits <= 150) return 18; + if (bits <= 200) return 15; + if (bits <= 250) return 12; + if (bits <= 300) return 9; + if (bits <= 350) return 8; + if (bits <= 400) return 7; + if (bits <= 500) return 6; + if (bits <= 600) return 5; + if (bits <= 800) return 4; + if (bits <= 1250) return 3; + return 2; + }; + var _detectNodeCrypto = function (fn) { + return forge.util.isNodejs && typeof _crypto[fn] === 'function'; + }; + var _detectSubtleCrypto = function (fn) { + return typeof util.globalScope !== 'undefined' && typeof util.globalScope.crypto === 'object' && typeof util.globalScope.crypto.subtle === 'object' && typeof util.globalScope.crypto.subtle[fn] === 'function'; + }; + var _detectSubtleMsCrypto = function (fn) { + return typeof util.globalScope !== 'undefined' && typeof util.globalScope.msCrypto === 'object' && typeof util.globalScope.msCrypto.subtle === 'object' && typeof util.globalScope.msCrypto.subtle[fn] === 'function'; + }; + var _intToUint8Array = function (x) { + var bytes = forge.util.hexToBytes(x.toString(16)); + var buffer = new Uint8Array(bytes.length); + for (var i = 0; i < bytes.length; ++i) { + buffer[i] = bytes.charCodeAt(i); + } + return buffer; + }; + var forge = require_forge(); + require_asn1(); + require_jsbn(); + require_oids(); + require_pkcs1(); + require_prime(); + require_random(); + require_util(); + if (typeof BigInteger === 'undefined') { + BigInteger = forge.jsbn.BigInteger; + } + var BigInteger; + var _crypto = forge.util.isNodejs ? (init_crypto(), __toCommonJS(exports_crypto)) : null; + var asn1 = forge.asn1; + var util = forge.util; + forge.pki = forge.pki || {}; + module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; + var pki = forge.pki; + var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + var privateKeyValidator = { + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'PrivateKeyInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, + { + name: 'PrivateKeyInfo.privateKeyAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'privateKeyOid' + } + ] + }, + { + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'privateKey' + } + ] + }; + var rsaPrivateKeyValidator = { + name: 'RSAPrivateKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'RSAPrivateKey.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, + { + name: 'RSAPrivateKey.modulus', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyModulus' + }, + { + name: 'RSAPrivateKey.publicExponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPublicExponent' + }, + { + name: 'RSAPrivateKey.privateExponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrivateExponent' + }, + { + name: 'RSAPrivateKey.prime1', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrime1' + }, + { + name: 'RSAPrivateKey.prime2', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrime2' + }, + { + name: 'RSAPrivateKey.exponent1', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyExponent1' + }, + { + name: 'RSAPrivateKey.exponent2', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyExponent2' + }, + { + name: 'RSAPrivateKey.coefficient', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyCoefficient' + } + ] + }; + var rsaPublicKeyValidator = { + name: 'RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'RSAPublicKey.modulus', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'publicKeyModulus' + }, + { + name: 'RSAPublicKey.exponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'publicKeyExponent' + } + ] + }; + var publicKeyValidator = (forge.pki.rsa.publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [ + { + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + } + ] + }, + { + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [ + { + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + } + ] + } + ] + }); + var digestInfoValidator = { + name: 'DigestInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'DigestInfo.DigestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'algorithmIdentifier' + }, + { + name: 'DigestInfo.DigestAlgorithm.parameters', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.NULL, + capture: 'parameters', + optional: true, + constructed: false + } + ] + }, + { + name: 'DigestInfo.digest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'digest' + } + ] + }; + var emsaPkcs1v15encode = function (md) { + var oid; + if (md.algorithm in pki.oids) { + oid = pki.oids[md.algorithm]; + } else { + var error = new Error('Unknown message digest algorithm.'); + error.algorithm = md.algorithm; + throw error; + } + var oidBytes = asn1.oidToDer(oid).getBytes(); + var digestInfo = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var digestAlgorithm = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes)); + digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')); + var digest = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, md.digest().getBytes()); + digestInfo.value.push(digestAlgorithm); + digestInfo.value.push(digest); + return asn1.toDer(digestInfo).getBytes(); + }; + var _modPow = function (x, key, pub) { + if (pub) { + return x.modPow(key.e, key.n); + } + if (!key.p || !key.q) { + return x.modPow(key.d, key.n); + } + if (!key.dP) { + key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); + } + if (!key.dQ) { + key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); + } + if (!key.qInv) { + key.qInv = key.q.modInverse(key.p); + } + var r; + do { + r = new BigInteger(forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), 16); + } while (r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); + x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); + var xp = x.mod(key.p).modPow(key.dP, key.p); + var xq = x.mod(key.q).modPow(key.dQ, key.q); + while (xp.compareTo(xq) < 0) { + xp = xp.add(key.p); + } + var y3 = xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq); + y3 = y3.multiply(r.modInverse(key.n)).mod(key.n); + return y3; + }; + pki.rsa.encrypt = function (m2, key, bt) { + var pub = bt; + var eb2; + var k = Math.ceil(key.n.bitLength() / 8); + if (bt !== false && bt !== true) { + pub = bt === 2; + eb2 = _encodePkcs1_v1_5(m2, key, bt); + } else { + eb2 = forge.util.createBuffer(); + eb2.putBytes(m2); + } + var x = new BigInteger(eb2.toHex(), 16); + var y3 = _modPow(x, key, pub); + var yhex = y3.toString(16); + var ed = forge.util.createBuffer(); + var zeros = k - Math.ceil(yhex.length / 2); + while (zeros > 0) { + ed.putByte(0); + --zeros; + } + ed.putBytes(forge.util.hexToBytes(yhex)); + return ed.getBytes(); + }; + pki.rsa.decrypt = function (ed, key, pub, ml) { + var k = Math.ceil(key.n.bitLength() / 8); + if (ed.length !== k) { + var error = new Error('Encrypted message length is invalid.'); + error.length = ed.length; + error.expected = k; + throw error; + } + var y3 = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); + if (y3.compareTo(key.n) >= 0) { + throw new Error('Encrypted message is invalid.'); + } + var x = _modPow(y3, key, pub); + var xhex = x.toString(16); + var eb2 = forge.util.createBuffer(); + var zeros = k - Math.ceil(xhex.length / 2); + while (zeros > 0) { + eb2.putByte(0); + --zeros; + } + eb2.putBytes(forge.util.hexToBytes(xhex)); + if (ml !== false) { + return _decodePkcs1_v1_5(eb2.getBytes(), key, pub); + } + return eb2.getBytes(); + }; + pki.rsa.createKeyPairGenerationState = function (bits, e, options) { + if (typeof bits === 'string') { + bits = parseInt(bits, 10); + } + bits = bits || 2048; + options = options || {}; + var prng = options.prng || forge.random; + var rng = { + nextBytes: function (x) { + var b3 = prng.getBytesSync(x.length); + for (var i = 0; i < x.length; ++i) { + x[i] = b3.charCodeAt(i); + } + } + }; + var algorithm = options.algorithm || 'PRIMEINC'; + var rval; + if (algorithm === 'PRIMEINC') { + rval = { + algorithm, + state: 0, + bits, + rng, + eInt: e || 65537, + e: new BigInteger(null), + p: null, + q: null, + qBits: bits >> 1, + pBits: bits - (bits >> 1), + pqState: 0, + num: null, + keys: null + }; + rval.e.fromInt(rval.eInt); + } else { + throw new Error('Invalid key generation algorithm: ' + algorithm); + } + return rval; + }; + pki.rsa.stepKeyPairGenerationState = function (state, n) { + if (!('algorithm' in state)) { + state.algorithm = 'PRIMEINC'; + } + var THIRTY = new BigInteger(null); + THIRTY.fromInt(30); + var deltaIdx = 0; + var op_or = function (x, y3) { + return x | y3; + }; + var t1 = +new Date(); + var t22; + var total = 0; + while (state.keys === null && (n <= 0 || total < n)) { + if (state.state === 0) { + var bits = state.p === null ? state.pBits : state.qBits; + var bits1 = bits - 1; + if (state.pqState === 0) { + state.num = new BigInteger(bits, state.rng); + if (!state.num.testBit(bits1)) { + state.num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, state.num); + } + state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); + deltaIdx = 0; + ++state.pqState; + } else if (state.pqState === 1) { + if (state.num.bitLength() > bits) { + state.pqState = 0; + } else if (state.num.isProbablePrime(_getMillerRabinTests(state.num.bitLength()))) { + ++state.pqState; + } else { + state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } + } else if (state.pqState === 2) { + state.pqState = state.num.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) === 0 ? 3 : 0; + } else if (state.pqState === 3) { + state.pqState = 0; + if (state.p === null) { + state.p = state.num; + } else { + state.q = state.num; + } + if (state.p !== null && state.q !== null) { + ++state.state; + } + state.num = null; + } + } else if (state.state === 1) { + if (state.p.compareTo(state.q) < 0) { + state.num = state.p; + state.p = state.q; + state.q = state.num; + } + ++state.state; + } else if (state.state === 2) { + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + ++state.state; + } else if (state.state === 3) { + if (state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { + ++state.state; + } else { + state.p = null; + state.q = null; + state.state = 0; + } + } else if (state.state === 4) { + state.n = state.p.multiply(state.q); + if (state.n.bitLength() === state.bits) { + ++state.state; + } else { + state.q = null; + state.state = 0; + } + } else if (state.state === 5) { + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki.rsa.setPrivateKey(state.n, state.e, d, state.p, state.q, d.mod(state.p1), d.mod(state.q1), state.q.modInverse(state.p)), + publicKey: pki.rsa.setPublicKey(state.n, state.e) + }; + } + t22 = +new Date(); + total += t22 - t1; + t1 = t22; + } + return state.keys !== null; + }; + pki.rsa.generateKeyPair = function (bits, e, options, callback) { + if (arguments.length === 1) { + if (typeof bits === 'object') { + options = bits; + bits = undefined; + } else if (typeof bits === 'function') { + callback = bits; + bits = undefined; + } + } else if (arguments.length === 2) { + if (typeof bits === 'number') { + if (typeof e === 'function') { + callback = e; + e = undefined; + } else if (typeof e !== 'number') { + options = e; + e = undefined; + } + } else { + options = bits; + callback = e; + bits = undefined; + e = undefined; + } + } else if (arguments.length === 3) { + if (typeof e === 'number') { + if (typeof options === 'function') { + callback = options; + options = undefined; + } + } else { + callback = options; + options = e; + e = undefined; + } + } + options = options || {}; + if (bits === undefined) { + bits = options.bits || 2048; + } + if (e === undefined) { + e = options.e || 65537; + } + if (!forge.options.usePureJavaScript && !options.prng && bits >= 256 && bits <= 16384 && (e === 65537 || e === 3)) { + if (callback) { + if (_detectNodeCrypto('generateKeyPair')) { + return _crypto.generateKeyPair( + 'rsa', + { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: 'spki', + format: 'pem' + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem' + } + }, + function (err, pub, priv) { + if (err) { + return callback(err); + } + callback(null, { + privateKey: pki.privateKeyFromPem(priv), + publicKey: pki.publicKeyFromPem(pub) + }); + } + ); + } + if (_detectSubtleCrypto('generateKey') && _detectSubtleCrypto('exportKey')) { + return util.globalScope.crypto.subtle + .generateKey( + { + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: {name: 'SHA-256'} + }, + true, + ['sign', 'verify'] + ) + .then(function (pair) { + return util.globalScope.crypto.subtle.exportKey('pkcs8', pair.privateKey); + }) + .then(undefined, function (err) { + callback(err); + }) + .then(function (pkcs8) { + if (pkcs8) { + var privateKey = pki.privateKeyFromAsn1(asn1.fromDer(forge.util.createBuffer(pkcs8))); + callback(null, { + privateKey, + publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) + }); + } + }); + } + if (_detectSubtleMsCrypto('generateKey') && _detectSubtleMsCrypto('exportKey')) { + var genOp = util.globalScope.msCrypto.subtle.generateKey( + { + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: {name: 'SHA-256'} + }, + true, + ['sign', 'verify'] + ); + genOp.oncomplete = function (e2) { + var pair = e2.target.result; + var exportOp = util.globalScope.msCrypto.subtle.exportKey('pkcs8', pair.privateKey); + exportOp.oncomplete = function (e3) { + var pkcs8 = e3.target.result; + var privateKey = pki.privateKeyFromAsn1(asn1.fromDer(forge.util.createBuffer(pkcs8))); + callback(null, { + privateKey, + publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) + }); + }; + exportOp.onerror = function (err) { + callback(err); + }; + }; + genOp.onerror = function (err) { + callback(err); + }; + return; + } + } else { + if (_detectNodeCrypto('generateKeyPairSync')) { + var keypair = _crypto.generateKeyPairSync('rsa', { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: 'spki', + format: 'pem' + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem' + } + }); + return { + privateKey: pki.privateKeyFromPem(keypair.privateKey), + publicKey: pki.publicKeyFromPem(keypair.publicKey) + }; + } + } + } + var state = pki.rsa.createKeyPairGenerationState(bits, e, options); + if (!callback) { + pki.rsa.stepKeyPairGenerationState(state, 0); + return state.keys; + } + _generateKeyPair(state, options, callback); + }; + pki.setRsaPublicKey = pki.rsa.setPublicKey = function (n, e) { + var key = { + n, + e + }; + key.encrypt = function (data, scheme, schemeOptions) { + if (typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if (scheme === undefined) { + scheme = 'RSAES-PKCS1-V1_5'; + } + if (scheme === 'RSAES-PKCS1-V1_5') { + scheme = { + encode: function (m2, key2, pub) { + return _encodePkcs1_v1_5(m2, key2, 2).getBytes(); + } + }; + } else if (scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { + scheme = { + encode: function (m2, key2) { + return forge.pkcs1.encode_rsa_oaep(key2, m2, schemeOptions); + } + }; + } else if (['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { + scheme = { + encode: function (e3) { + return e3; + } + }; + } else if (typeof scheme === 'string') { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } + var e2 = scheme.encode(data, key, true); + return pki.rsa.encrypt(e2, key, true); + }; + key.verify = function (digest, signature, scheme, options) { + if (typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if (scheme === undefined) { + scheme = 'RSASSA-PKCS1-V1_5'; + } + if (options === undefined) { + options = { + _parseAllDigestBytes: true + }; + } + if (!('_parseAllDigestBytes' in options)) { + options._parseAllDigestBytes = true; + } + if (scheme === 'RSASSA-PKCS1-V1_5') { + scheme = { + verify: function (digest2, d2) { + d2 = _decodePkcs1_v1_5(d2, key, true); + var obj = asn1.fromDer(d2, { + parseAllBytes: options._parseAllDigestBytes + }); + var capture = {}; + var errors = []; + if (!asn1.validate(obj, digestInfoValidator, capture, errors)) { + var error = new Error('ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' + 'DigestInfo value.'); + error.errors = errors; + throw error; + } + var oid = asn1.derToOid(capture.algorithmIdentifier); + if ( + !( + oid === forge.oids.md2 || + oid === forge.oids.md5 || + oid === forge.oids.sha1 || + oid === forge.oids.sha224 || + oid === forge.oids.sha256 || + oid === forge.oids.sha384 || + oid === forge.oids.sha512 || + oid === forge.oids['sha512-224'] || + oid === forge.oids['sha512-256'] + ) + ) { + var error = new Error('Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.'); + error.oid = oid; + throw error; + } + if (oid === forge.oids.md2 || oid === forge.oids.md5) { + if (!('parameters' in capture)) { + throw new Error('ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' + 'DigestInfo value. ' + 'Missing algorithm identifer NULL parameters.'); + } + } + return digest2 === capture.digest; + } + }; + } else if (scheme === 'NONE' || scheme === 'NULL' || scheme === null) { + scheme = { + verify: function (digest2, d2) { + d2 = _decodePkcs1_v1_5(d2, key, true); + return digest2 === d2; + } + }; + } + var d = pki.rsa.decrypt(signature, key, true, false); + return scheme.verify(digest, d, key.n.bitLength()); + }; + return key; + }; + pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function (n, e, d, p, q2, dP, dQ, qInv) { + var key = { + n, + e, + d, + p, + q: q2, + dP, + dQ, + qInv + }; + key.decrypt = function (data, scheme, schemeOptions) { + if (typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if (scheme === undefined) { + scheme = 'RSAES-PKCS1-V1_5'; + } + var d2 = pki.rsa.decrypt(data, key, false, false); + if (scheme === 'RSAES-PKCS1-V1_5') { + scheme = {decode: _decodePkcs1_v1_5}; + } else if (scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { + scheme = { + decode: function (d4, key2) { + return forge.pkcs1.decode_rsa_oaep(key2, d4, schemeOptions); + } + }; + } else if (['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { + scheme = { + decode: function (d4) { + return d4; + } + }; + } else { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } + return scheme.decode(d2, key, false); + }; + key.sign = function (md, scheme) { + var bt = false; + if (typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } + if (scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') { + scheme = {encode: emsaPkcs1v15encode}; + bt = 1; + } else if (scheme === 'NONE' || scheme === 'NULL' || scheme === null) { + scheme = { + encode: function () { + return md; + } + }; + bt = 1; + } + var d2 = scheme.encode(md, key.n.bitLength()); + return pki.rsa.encrypt(d2, key, bt); + }; + return key; + }; + pki.wrapRsaPrivateKey = function (rsaKey) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(0).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(rsaKey).getBytes()) + ]); + }; + pki.privateKeyFromAsn1 = function (obj) { + var capture = {}; + var errors = []; + if (asn1.validate(obj, privateKeyValidator, capture, errors)) { + obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); + } + capture = {}; + errors = []; + if (!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { + var error = new Error('Cannot read private key. ' + 'ASN.1 object does not contain an RSAPrivateKey.'); + error.errors = errors; + throw error; + } + var n, e, d, p, q2, dP, dQ, qInv; + n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); + e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); + d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); + p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); + q2 = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); + dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); + dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); + qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); + return pki.setRsaPrivateKey(new BigInteger(n, 16), new BigInteger(e, 16), new BigInteger(d, 16), new BigInteger(p, 16), new BigInteger(q2, 16), new BigInteger(dP, 16), new BigInteger(dQ, 16), new BigInteger(qInv, 16)); + }; + pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function (key) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(0).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.n)), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.e)), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.d)), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.p)), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.q)), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.dP)), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.dQ)), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.qInv)) + ]); + }; + pki.publicKeyFromAsn1 = function (obj) { + var capture = {}; + var errors = []; + if (asn1.validate(obj, publicKeyValidator, capture, errors)) { + var oid = asn1.derToOid(capture.publicKeyOid); + if (oid !== pki.oids.rsaEncryption) { + var error = new Error('Cannot read public key. Unknown OID.'); + error.oid = oid; + throw error; + } + obj = capture.rsaPublicKey; + } + errors = []; + if (!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { + var error = new Error('Cannot read public key. ' + 'ASN.1 object does not contain an RSAPublicKey.'); + error.errors = errors; + throw error; + } + var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); + var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); + return pki.setRsaPublicKey(new BigInteger(n, 16), new BigInteger(e, 16)); + }; + pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function (key) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [pki.publicKeyToRSAPublicKey(key)]) + ]); + }; + pki.publicKeyToRSAPublicKey = function (key) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.n)), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.e))]); + }; +}); + +// node_modules/node-forge/lib/pbe.js +var require_pbe = __commonJS((exports, module) => { + var hash = function (md, bytes) { + return md.start().update(bytes).digest().getBytes(); + }; + var prfOidToMessageDigest = function (prfOid) { + var prfAlgorithm; + if (!prfOid) { + prfAlgorithm = 'hmacWithSHA1'; + } else { + prfAlgorithm = pki.oids[asn1.derToOid(prfOid)]; + if (!prfAlgorithm) { + var error = new Error('Unsupported PRF OID.'); + error.oid = prfOid; + error.supported = ['hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', 'hmacWithSHA512']; + throw error; + } + } + return prfAlgorithmToMessageDigest(prfAlgorithm); + }; + var prfAlgorithmToMessageDigest = function (prfAlgorithm) { + var factory = forge.md; + switch (prfAlgorithm) { + case 'hmacWithSHA224': + factory = forge.md.sha512; + case 'hmacWithSHA1': + case 'hmacWithSHA256': + case 'hmacWithSHA384': + case 'hmacWithSHA512': + prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); + break; + default: + var error = new Error('Unsupported PRF algorithm.'); + error.algorithm = prfAlgorithm; + error.supported = ['hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', 'hmacWithSHA512']; + throw error; + } + if (!factory || !(prfAlgorithm in factory)) { + throw new Error('Unknown hash algorithm: ' + prfAlgorithm); + } + return factory[prfAlgorithm].create(); + }; + var createPbkdf2Params = function (salt, countBytes, dkLen, prfAlgorithm) { + var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, countBytes.getBytes())]); + if (prfAlgorithm !== 'hmacWithSHA1') { + params.value.push( + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(dkLen.toString(16))), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')]) + ); + } + return params; + }; + var forge = require_forge(); + require_aes(); + require_asn1(); + require_des(); + require_md(); + require_oids(); + require_pbkdf2(); + require_pem(); + require_random(); + require_rc2(); + require_rsa(); + require_util(); + if (typeof BigInteger === 'undefined') { + BigInteger = forge.jsbn.BigInteger; + } + var BigInteger; + var asn1 = forge.asn1; + var pki = (forge.pki = forge.pki || {}); + module.exports = pki.pbe = forge.pbe = forge.pbe || {}; + var oids = pki.oids; + var encryptedPrivateKeyValidator = { + name: 'EncryptedPrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encryptionOid' + }, + { + name: 'AlgorithmIdentifier.parameters', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'encryptionParams' + } + ] + }, + { + name: 'EncryptedPrivateKeyInfo.encryptedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encryptedData' + } + ] + }; + var PBES2AlgorithmsValidator = { + name: 'PBES2Algorithms', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'PBES2Algorithms.keyDerivationFunc', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'PBES2Algorithms.keyDerivationFunc.oid', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'kdfOid' + }, + { + name: 'PBES2Algorithms.params', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'PBES2Algorithms.params.salt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'kdfSalt' + }, + { + name: 'PBES2Algorithms.params.iterationCount', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'kdfIterationCount' + }, + { + name: 'PBES2Algorithms.params.keyLength', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: 'keyLength' + }, + { + name: 'PBES2Algorithms.params.prf', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + value: [ + { + name: 'PBES2Algorithms.params.prf.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'prfOid' + } + ] + } + ] + } + ] + }, + { + name: 'PBES2Algorithms.encryptionScheme', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'PBES2Algorithms.encryptionScheme.oid', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encOid' + }, + { + name: 'PBES2Algorithms.encryptionScheme.iv', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encIv' + } + ] + } + ] + }; + var pkcs12PbeParamsValidator = { + name: 'pkcs-12PbeParams', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'pkcs-12PbeParams.salt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'salt' + }, + { + name: 'pkcs-12PbeParams.iterations', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'iterations' + } + ] + }; + pki.encryptPrivateKeyInfo = function (obj, password, options) { + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || 'aes128'; + options.prfAlgorithm = options.prfAlgorithm || 'sha1'; + var salt = forge.random.getBytesSync(options.saltSize); + var count = options.count; + var countBytes = asn1.integerToDer(count); + var dkLen; + var encryptionAlgorithm; + var encryptedData; + if (options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') { + var ivLen, encOid, cipherFn; + switch (options.algorithm) { + case 'aes128': + dkLen = 16; + ivLen = 16; + encOid = oids['aes128-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes192': + dkLen = 24; + ivLen = 16; + encOid = oids['aes192-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes256': + dkLen = 32; + ivLen = 16; + encOid = oids['aes256-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'des': + dkLen = 8; + ivLen = 8; + encOid = oids['desCBC']; + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); + error.algorithm = options.algorithm; + throw error; + } + var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase(); + var md = prfAlgorithmToMessageDigest(prfAlgorithm); + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = forge.random.getBytesSync(ivLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); + encryptionAlgorithm = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids['pkcs5PBES2']).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()), params]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(encOid).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)]) + ]) + ]); + } else if (options.algorithm === '3des') { + dkLen = 24; + var saltBytes = new forge.util.ByteBuffer(salt); + var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); + var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); + var cipher = forge.des.createEncryptionCipher(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + encryptionAlgorithm = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, countBytes.getBytes())]) + ]); + } else { + var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); + error.algorithm = options.algorithm; + throw error; + } + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [encryptionAlgorithm, asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)]); + return rval; + }; + pki.decryptPrivateKeyInfo = function (obj, password) { + var rval = null; + var capture = {}; + var errors = []; + if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { + var error = new Error('Cannot read encrypted private key. ' + 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + var oid = asn1.derToOid(capture.encryptionOid); + var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password); + var encrypted = forge.util.createBuffer(capture.encryptedData); + cipher.update(encrypted); + if (cipher.finish()) { + rval = asn1.fromDer(cipher.output); + } + return rval; + }; + pki.encryptedPrivateKeyToPem = function (epki, maxline) { + var msg = { + type: 'ENCRYPTED PRIVATE KEY', + body: asn1.toDer(epki).getBytes() + }; + return forge.pem.encode(msg, {maxline}); + }; + pki.encryptedPrivateKeyFromPem = function (pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== 'ENCRYPTED PRIVATE KEY') { + var error = new Error('Could not convert encrypted private key from PEM; ' + 'PEM header type is "ENCRYPTED PRIVATE KEY".'); + error.headerType = msg.type; + throw error; + } + if (msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert encrypted private key from PEM; ' + 'PEM is encrypted.'); + } + return asn1.fromDer(msg.body); + }; + pki.encryptRsaPrivateKey = function (rsaKey, password, options) { + options = options || {}; + if (!options.legacy) { + var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey)); + rval = pki.encryptPrivateKeyInfo(rval, password, options); + return pki.encryptedPrivateKeyToPem(rval); + } + var algorithm; + var iv; + var dkLen; + var cipherFn; + switch (options.algorithm) { + case 'aes128': + algorithm = 'AES-128-CBC'; + dkLen = 16; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes192': + algorithm = 'AES-192-CBC'; + dkLen = 24; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes256': + algorithm = 'AES-256-CBC'; + dkLen = 32; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case '3des': + algorithm = 'DES-EDE3-CBC'; + dkLen = 24; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + case 'des': + algorithm = 'DES-CBC'; + dkLen = 8; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error = new Error('Could not encrypt RSA private key; unsupported ' + 'encryption algorithm "' + options.algorithm + '".'); + error.algorithm = options.algorithm; + throw error; + } + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey))); + cipher.finish(); + var msg = { + type: 'RSA PRIVATE KEY', + procType: { + version: '4', + type: 'ENCRYPTED' + }, + dekInfo: { + algorithm, + parameters: forge.util.bytesToHex(iv).toUpperCase() + }, + body: cipher.output.getBytes() + }; + return forge.pem.encode(msg); + }; + pki.decryptRsaPrivateKey = function (pem, password) { + var rval = null; + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== 'ENCRYPTED PRIVATE KEY' && msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') { + var error = new Error('Could not convert private key from PEM; PEM header type ' + 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); + error.headerType = error; + throw error; + } + if (msg.procType && msg.procType.type === 'ENCRYPTED') { + var dkLen; + var cipherFn; + switch (msg.dekInfo.algorithm) { + case 'DES-CBC': + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'DES-EDE3-CBC': + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'AES-128-CBC': + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'AES-192-CBC': + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'AES-256-CBC': + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'RC2-40-CBC': + dkLen = 5; + cipherFn = function (key) { + return forge.rc2.createDecryptionCipher(key, 40); + }; + break; + case 'RC2-64-CBC': + dkLen = 8; + cipherFn = function (key) { + return forge.rc2.createDecryptionCipher(key, 64); + }; + break; + case 'RC2-128-CBC': + dkLen = 16; + cipherFn = function (key) { + return forge.rc2.createDecryptionCipher(key, 128); + }; + break; + default: + var error = new Error('Could not decrypt private key; unsupported ' + 'encryption algorithm "' + msg.dekInfo.algorithm + '".'); + error.algorithm = msg.dekInfo.algorithm; + throw error; + } + var iv = forge.util.hexToBytes(msg.dekInfo.parameters); + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(forge.util.createBuffer(msg.body)); + if (cipher.finish()) { + rval = cipher.output.getBytes(); + } else { + return rval; + } + } else { + rval = msg.body; + } + if (msg.type === 'ENCRYPTED PRIVATE KEY') { + rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password); + } else { + rval = asn1.fromDer(rval); + } + if (rval !== null) { + rval = pki.privateKeyFromAsn1(rval); + } + return rval; + }; + pki.pbe.generatePkcs12Key = function (password, salt, id, iter, n, md) { + var j, l; + if (typeof md === 'undefined' || md === null) { + if (!('sha1' in forge.md)) { + throw new Error('"sha1" hash algorithm unavailable.'); + } + md = forge.md.sha1.create(); + } + var u = md.digestLength; + var v = md.blockLength; + var result = new forge.util.ByteBuffer(); + var passBuf = new forge.util.ByteBuffer(); + if (password !== null && password !== undefined) { + for (l = 0; l < password.length; l++) { + passBuf.putInt16(password.charCodeAt(l)); + } + passBuf.putInt16(0); + } + var p = passBuf.length(); + var s = salt.length(); + var D2 = new forge.util.ByteBuffer(); + D2.fillWithByte(id, v); + var Slen = v * Math.ceil(s / v); + var S = new forge.util.ByteBuffer(); + for (l = 0; l < Slen; l++) { + S.putByte(salt.at(l % s)); + } + var Plen = v * Math.ceil(p / v); + var P = new forge.util.ByteBuffer(); + for (l = 0; l < Plen; l++) { + P.putByte(passBuf.at(l % p)); + } + var I = S; + I.putBuffer(P); + var c = Math.ceil(n / u); + for (var i = 1; i <= c; i++) { + var buf = new forge.util.ByteBuffer(); + buf.putBytes(D2.bytes()); + buf.putBytes(I.bytes()); + for (var round = 0; round < iter; round++) { + md.start(); + md.update(buf.getBytes()); + buf = md.digest(); + } + var B = new forge.util.ByteBuffer(); + for (l = 0; l < v; l++) { + B.putByte(buf.at(l % u)); + } + var k = Math.ceil(s / v) + Math.ceil(p / v); + var Inew = new forge.util.ByteBuffer(); + for (j = 0; j < k; j++) { + var chunk = new forge.util.ByteBuffer(I.getBytes(v)); + var x = 511; + for (l = B.length() - 1; l >= 0; l--) { + x = x >> 8; + x += B.at(l) + chunk.at(l); + chunk.setAt(l, x & 255); + } + Inew.putBuffer(chunk); + } + I = Inew; + result.putBuffer(buf); + } + result.truncate(result.length() - n); + return result; + }; + pki.pbe.getCipher = function (oid, params, password) { + switch (oid) { + case pki.oids['pkcs5PBES2']: + return pki.pbe.getCipherForPBES2(oid, params, password); + case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: + case pki.oids['pbewithSHAAnd40BitRC2-CBC']: + return pki.pbe.getCipherForPKCS12PBE(oid, params, password); + default: + var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.'); + error.oid = oid; + error.supportedOids = ['pkcs5PBES2', 'pbeWithSHAAnd3-KeyTripleDES-CBC', 'pbewithSHAAnd40BitRC2-CBC']; + throw error; + } + }; + pki.pbe.getCipherForPBES2 = function (oid, params, password) { + var capture = {}; + var errors = []; + if (!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { + var error = new Error('Cannot read password-based-encryption algorithm ' + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + oid = asn1.derToOid(capture.kdfOid); + if (oid !== pki.oids['pkcs5PBKDF2']) { + var error = new Error('Cannot read encrypted private key. ' + 'Unsupported key derivation function OID.'); + error.oid = oid; + error.supportedOids = ['pkcs5PBKDF2']; + throw error; + } + oid = asn1.derToOid(capture.encOid); + if (oid !== pki.oids['aes128-CBC'] && oid !== pki.oids['aes192-CBC'] && oid !== pki.oids['aes256-CBC'] && oid !== pki.oids['des-EDE3-CBC'] && oid !== pki.oids['desCBC']) { + var error = new Error('Cannot read encrypted private key. ' + 'Unsupported encryption scheme OID.'); + error.oid = oid; + error.supportedOids = ['aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC']; + throw error; + } + var salt = capture.kdfSalt; + var count = forge.util.createBuffer(capture.kdfIterationCount); + count = count.getInt(count.length() << 3); + var dkLen; + var cipherFn; + switch (pki.oids[oid]) { + case 'aes128-CBC': + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'aes192-CBC': + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'aes256-CBC': + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'des-EDE3-CBC': + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'desCBC': + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + } + var md = prfOidToMessageDigest(capture.prfOid); + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = capture.encIv; + var cipher = cipherFn(dk); + cipher.start(iv); + return cipher; + }; + pki.pbe.getCipherForPKCS12PBE = function (oid, params, password) { + var capture = {}; + var errors = []; + if (!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { + var error = new Error('Cannot read password-based-encryption algorithm ' + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + var salt = forge.util.createBuffer(capture.salt); + var count = forge.util.createBuffer(capture.iterations); + count = count.getInt(count.length() << 3); + var dkLen, dIvLen, cipherFn; + switch (oid) { + case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: + dkLen = 24; + dIvLen = 8; + cipherFn = forge.des.startDecrypting; + break; + case pki.oids['pbewithSHAAnd40BitRC2-CBC']: + dkLen = 5; + dIvLen = 8; + cipherFn = function (key2, iv2) { + var cipher = forge.rc2.createDecryptionCipher(key2, 40); + cipher.start(iv2, null); + return cipher; + }; + break; + default: + var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.'); + error.oid = oid; + throw error; + } + var md = prfOidToMessageDigest(capture.prfOid); + var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); + md.start(); + var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); + return cipherFn(key, iv); + }; + pki.pbe.opensslDeriveBytes = function (password, salt, dkLen, md) { + if (typeof md === 'undefined' || md === null) { + if (!('md5' in forge.md)) { + throw new Error('"md5" hash algorithm unavailable.'); + } + md = forge.md.md5.create(); + } + if (salt === null) { + salt = ''; + } + var digests = [hash(md, password + salt)]; + for (var length = 16, i = 1; length < dkLen; ++i, length += 16) { + digests.push(hash(md, digests[i - 1] + password + salt)); + } + return digests.join('').substr(0, dkLen); + }; +}); + +// node_modules/node-forge/lib/pkcs7asn1.js +var require_pkcs7asn1 = __commonJS((exports, module) => { + var forge = require_forge(); + require_asn1(); + require_util(); + var asn1 = forge.asn1; + var p7v = (module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}); + forge.pkcs7 = forge.pkcs7 || {}; + forge.pkcs7.asn1 = p7v; + var contentInfoValidator = { + name: 'ContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'ContentInfo.ContentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, + { + name: 'ContentInfo.content', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + captureAsn1: 'content' + } + ] + }; + p7v.contentInfoValidator = contentInfoValidator; + var encryptedContentInfoValidator = { + name: 'EncryptedContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'EncryptedContentInfo.contentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, + { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encAlgorithm' + }, + { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: 'encParameter' + } + ] + }, + { + name: 'EncryptedContentInfo.encryptedContent', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + capture: 'encryptedContent', + captureAsn1: 'encryptedContentAsn1' + } + ] + }; + p7v.envelopedDataValidator = { + name: 'EnvelopedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'EnvelopedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, + { + name: 'EnvelopedData.RecipientInfos', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: 'recipientInfos' + } + ].concat(encryptedContentInfoValidator) + }; + p7v.encryptedDataValidator = { + name: 'EncryptedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'EncryptedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + } + ].concat(encryptedContentInfoValidator) + }; + var signerValidator = { + name: 'SignerInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'SignerInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false + }, + { + name: 'SignerInfo.issuerAndSerialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'SignerInfo.issuerAndSerialNumber.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'issuer' + }, + { + name: 'SignerInfo.issuerAndSerialNumber.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'serial' + } + ] + }, + { + name: 'SignerInfo.digestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'SignerInfo.digestAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'digestAlgorithm' + }, + { + name: 'SignerInfo.digestAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: 'digestParameter', + optional: true + } + ] + }, + { + name: 'SignerInfo.authenticatedAttributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: 'authenticatedAttributes' + }, + { + name: 'SignerInfo.digestEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + capture: 'signatureAlgorithm' + }, + { + name: 'SignerInfo.encryptedDigest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'signature' + }, + { + name: 'SignerInfo.unauthenticatedAttributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + capture: 'unauthenticatedAttributes' + } + ] + }; + p7v.signedDataValidator = { + name: 'SignedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'SignedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, + { + name: 'SignedData.DigestAlgorithms', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: 'digestAlgorithms' + }, + contentInfoValidator, + { + name: 'SignedData.Certificates', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + optional: true, + captureAsn1: 'certificates' + }, + { + name: 'SignedData.CertificateRevocationLists', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + optional: true, + captureAsn1: 'crls' + }, + { + name: 'SignedData.SignerInfos', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + capture: 'signerInfos', + optional: true, + value: [signerValidator] + } + ] + }; + p7v.recipientInfoValidator = { + name: 'RecipientInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'RecipientInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, + { + name: 'RecipientInfo.issuerAndSerial', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'RecipientInfo.issuerAndSerial.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'issuer' + }, + { + name: 'RecipientInfo.issuerAndSerial.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'serial' + } + ] + }, + { + name: 'RecipientInfo.keyEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encAlgorithm' + }, + { + name: 'RecipientInfo.keyEncryptionAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: 'encParameter', + optional: true + } + ] + }, + { + name: 'RecipientInfo.encryptedKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encKey' + } + ] + }; +}); + +// node_modules/node-forge/lib/mgf1.js +var require_mgf1 = __commonJS((exports, module) => { + var forge = require_forge(); + require_util(); + forge.mgf = forge.mgf || {}; + var mgf1 = (module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}); + mgf1.create = function (md) { + var mgf = { + generate: function (seed, maskLen) { + var t = new forge.util.ByteBuffer(); + var len = Math.ceil(maskLen / md.digestLength); + for (var i = 0; i < len; i++) { + var c = new forge.util.ByteBuffer(); + c.putInt32(i); + md.start(); + md.update(seed + c.getBytes()); + t.putBuffer(md.digest()); + } + t.truncate(t.length() - maskLen); + return t.getBytes(); + } + }; + return mgf; + }; +}); + +// node_modules/node-forge/lib/mgf.js +var require_mgf = __commonJS((exports, module) => { + var forge = require_forge(); + require_mgf1(); + module.exports = forge.mgf = forge.mgf || {}; + forge.mgf.mgf1 = forge.mgf1; +}); + +// node_modules/node-forge/lib/pss.js +var require_pss = __commonJS((exports, module) => { + var forge = require_forge(); + require_random(); + require_util(); + var pss = (module.exports = forge.pss = forge.pss || {}); + pss.create = function (options) { + if (arguments.length === 3) { + options = { + md: arguments[0], + mgf: arguments[1], + saltLength: arguments[2] + }; + } + var hash = options.md; + var mgf = options.mgf; + var hLen = hash.digestLength; + var salt_ = options.salt || null; + if (typeof salt_ === 'string') { + salt_ = forge.util.createBuffer(salt_); + } + var sLen; + if ('saltLength' in options) { + sLen = options.saltLength; + } else if (salt_ !== null) { + sLen = salt_.length(); + } else { + throw new Error('Salt length not specified or specific salt not given.'); + } + if (salt_ !== null && salt_.length() !== sLen) { + throw new Error('Given salt length does not match length of given salt.'); + } + var prng = options.prng || forge.random; + var pssobj = {}; + pssobj.encode = function (md, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + var mHash = md.digest().getBytes(); + if (emLen < hLen + sLen + 2) { + throw new Error('Message is too long to encrypt.'); + } + var salt; + if (salt_ === null) { + salt = prng.getBytesSync(sLen); + } else { + salt = salt_.bytes(); + } + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + hash.start(); + hash.update(m_.getBytes()); + var h2 = hash.digest().getBytes(); + var ps = new forge.util.ByteBuffer(); + ps.fillWithByte(0, emLen - sLen - hLen - 2); + ps.putByte(1); + ps.putBytes(salt); + var db2 = ps.getBytes(); + var maskLen = emLen - hLen - 1; + var dbMask = mgf.generate(h2, maskLen); + var maskedDB = ''; + for (i = 0; i < maskLen; i++) { + maskedDB += String.fromCharCode(db2.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + var mask = (65280 >> (8 * emLen - emBits)) & 255; + maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1); + return maskedDB + h2 + String.fromCharCode(188); + }; + pssobj.verify = function (mHash, em2, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + em2 = em2.substr(-emLen); + if (emLen < hLen + sLen + 2) { + throw new Error('Inconsistent parameters to PSS signature verification.'); + } + if (em2.charCodeAt(emLen - 1) !== 188) { + throw new Error('Encoded message does not end in 0xBC.'); + } + var maskLen = emLen - hLen - 1; + var maskedDB = em2.substr(0, maskLen); + var h2 = em2.substr(maskLen, hLen); + var mask = (65280 >> (8 * emLen - emBits)) & 255; + if ((maskedDB.charCodeAt(0) & mask) !== 0) { + throw new Error('Bits beyond keysize not zero as expected.'); + } + var dbMask = mgf.generate(h2, maskLen); + var db2 = ''; + for (i = 0; i < maskLen; i++) { + db2 += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + db2 = String.fromCharCode(db2.charCodeAt(0) & ~mask) + db2.substr(1); + var checkLen = emLen - hLen - sLen - 2; + for (i = 0; i < checkLen; i++) { + if (db2.charCodeAt(i) !== 0) { + throw new Error('Leftmost octets not zero as expected'); + } + } + if (db2.charCodeAt(checkLen) !== 1) { + throw new Error('Inconsistent PSS signature, 0x01 marker not found'); + } + var salt = db2.substr(-sLen); + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + hash.start(); + hash.update(m_.getBytes()); + var h_ = hash.digest().getBytes(); + return h2 === h_; + }; + return pssobj; + }; +}); + +// node_modules/node-forge/lib/x509.js +var require_x509 = __commonJS((exports, module) => { + var _getAttribute = function (obj, options) { + if (typeof options === 'string') { + options = {shortName: options}; + } + var rval = null; + var attr; + for (var i = 0; rval === null && i < obj.attributes.length; ++i) { + attr = obj.attributes[i]; + if (options.type && options.type === attr.type) { + rval = attr; + } else if (options.name && options.name === attr.name) { + rval = attr; + } else if (options.shortName && options.shortName === attr.shortName) { + rval = attr; + } + } + return rval; + }; + var _dnToAsn1 = function (obj) { + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var attr, set; + var attrs = obj.attributes; + for (var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + var value = attr.value; + var valueTagClass = asn1.Type.PRINTABLESTRING; + if ('valueTagClass' in attr) { + valueTagClass = attr.valueTagClass; + if (valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + } + set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()), asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)]) + ]); + rval.value.push(set); + } + return rval; + }; + var _fillMissingFields = function (attrs) { + var attr; + for (var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + if (typeof attr.name === 'undefined') { + if (attr.type && attr.type in pki.oids) { + attr.name = pki.oids[attr.type]; + } else if (attr.shortName && attr.shortName in _shortNames) { + attr.name = pki.oids[_shortNames[attr.shortName]]; + } + } + if (typeof attr.type === 'undefined') { + if (attr.name && attr.name in pki.oids) { + attr.type = pki.oids[attr.name]; + } else { + var error = new Error('Attribute type not specified.'); + error.attribute = attr; + throw error; + } + } + if (typeof attr.shortName === 'undefined') { + if (attr.name && attr.name in _shortNames) { + attr.shortName = _shortNames[attr.name]; + } + } + if (attr.type === oids.extensionRequest) { + attr.valueConstructed = true; + attr.valueTagClass = asn1.Type.SEQUENCE; + if (!attr.value && attr.extensions) { + attr.value = []; + for (var ei = 0; ei < attr.extensions.length; ++ei) { + attr.value.push(pki.certificateExtensionToAsn1(_fillMissingExtensionFields(attr.extensions[ei]))); + } + } + } + if (typeof attr.value === 'undefined') { + var error = new Error('Attribute value not specified.'); + error.attribute = attr; + throw error; + } + } + }; + var _fillMissingExtensionFields = function (e, options) { + options = options || {}; + if (typeof e.name === 'undefined') { + if (e.id && e.id in pki.oids) { + e.name = pki.oids[e.id]; + } + } + if (typeof e.id === 'undefined') { + if (e.name && e.name in pki.oids) { + e.id = pki.oids[e.name]; + } else { + var error = new Error('Extension ID not specified.'); + error.extension = e; + throw error; + } + } + if (typeof e.value !== 'undefined') { + return e; + } + if (e.name === 'keyUsage') { + var unused = 0; + var b22 = 0; + var b3 = 0; + if (e.digitalSignature) { + b22 |= 128; + unused = 7; + } + if (e.nonRepudiation) { + b22 |= 64; + unused = 6; + } + if (e.keyEncipherment) { + b22 |= 32; + unused = 5; + } + if (e.dataEncipherment) { + b22 |= 16; + unused = 4; + } + if (e.keyAgreement) { + b22 |= 8; + unused = 3; + } + if (e.keyCertSign) { + b22 |= 4; + unused = 2; + } + if (e.cRLSign) { + b22 |= 2; + unused = 1; + } + if (e.encipherOnly) { + b22 |= 1; + unused = 0; + } + if (e.decipherOnly) { + b3 |= 128; + unused = 7; + } + var value = String.fromCharCode(unused); + if (b3 !== 0) { + value += String.fromCharCode(b22) + String.fromCharCode(b3); + } else if (b22 !== 0) { + value += String.fromCharCode(b22); + } + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value); + } else if (e.name === 'basicConstraints') { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + if (e.cA) { + e.value.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, String.fromCharCode(255))); + } + if ('pathLenConstraint' in e) { + e.value.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(e.pathLenConstraint).getBytes())); + } + } else if (e.name === 'extKeyUsage') { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + for (var key in e) { + if (e[key] !== true) { + continue; + } + if (key in oids) { + seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids[key]).getBytes())); + } else if (key.indexOf('.') !== -1) { + seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(key).getBytes())); + } + } + } else if (e.name === 'nsCertType') { + var unused = 0; + var b22 = 0; + if (e.client) { + b22 |= 128; + unused = 7; + } + if (e.server) { + b22 |= 64; + unused = 6; + } + if (e.email) { + b22 |= 32; + unused = 5; + } + if (e.objsign) { + b22 |= 16; + unused = 4; + } + if (e.reserved) { + b22 |= 8; + unused = 3; + } + if (e.sslCA) { + b22 |= 4; + unused = 2; + } + if (e.emailCA) { + b22 |= 2; + unused = 1; + } + if (e.objCA) { + b22 |= 1; + unused = 0; + } + var value = String.fromCharCode(unused); + if (b22 !== 0) { + value += String.fromCharCode(b22); + } + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value); + } else if (e.name === 'subjectAltName' || e.name === 'issuerAltName') { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var altName; + for (var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + if (altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if (value === null) { + var error = new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.'); + error.extension = e; + throw error; + } + } else if (altName.type === 8) { + if (altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + value = asn1.oidToDer(value); + } + } + e.value.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, altName.type, false, value)); + } + } else if (e.name === 'nsComment' && options.cert) { + if (!/^[\x00-\x7F]*$/.test(e.comment) || e.comment.length < 1 || e.comment.length > 128) { + throw new Error('Invalid "nsComment" content.'); + } + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment); + } else if (e.name === 'subjectKeyIdentifier' && options.cert) { + var ski = options.cert.generateSubjectKeyIdentifier(); + e.subjectKeyIdentifier = ski.toHex(); + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes()); + } else if (e.name === 'authorityKeyIdentifier' && options.cert) { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + if (e.keyIdentifier) { + var keyIdentifier = e.keyIdentifier === true ? options.cert.generateSubjectKeyIdentifier().getBytes() : e.keyIdentifier; + seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier)); + } + if (e.authorityCertIssuer) { + var authorityCertIssuer = [asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [_dnToAsn1(e.authorityCertIssuer === true ? options.cert.issuer : e.authorityCertIssuer)])]; + seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer)); + } + if (e.serialNumber) { + var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? options.cert.serialNumber : e.serialNumber); + seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber)); + } + } else if (e.name === 'cRLDistributionPoints') { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + var subSeq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var fullNameGeneralNames = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + var altName; + for (var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + if (altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if (value === null) { + var error = new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.'); + error.extension = e; + throw error; + } + } else if (altName.type === 8) { + if (altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + value = asn1.oidToDer(value); + } + } + fullNameGeneralNames.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, altName.type, false, value)); + } + subSeq.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames])); + seq.push(subSeq); + } + if (typeof e.value === 'undefined') { + var error = new Error('Extension value not specified.'); + error.extension = e; + throw error; + } + return e; + }; + var _signatureParametersToAsn1 = function (oid, params) { + switch (oid) { + case oids['RSASSA-PSS']: + var parts = []; + if (params.hash.algorithmOid !== undefined) { + parts.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.hash.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ]) + ); + } + if (params.mgf.algorithmOid !== undefined) { + parts.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.mgf.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ]) + ]) + ); + } + if (params.saltLength !== undefined) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(params.saltLength).getBytes())])); + } + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); + default: + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''); + } + }; + var _CRIAttributesToAsn1 = function (csr) { + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + if (csr.attributes.length === 0) { + return rval; + } + var attrs = csr.attributes; + for (var i = 0; i < attrs.length; ++i) { + var attr = attrs[i]; + var value = attr.value; + var valueTagClass = asn1.Type.UTF8; + if ('valueTagClass' in attr) { + valueTagClass = attr.valueTagClass; + } + if (valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + var valueConstructed = false; + if ('valueConstructed' in attr) { + valueConstructed = attr.valueConstructed; + } + var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [asn1.create(asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)]) + ]); + rval.value.push(seq); + } + return rval; + }; + var _dateToAsn1 = function (date) { + if (date >= jan_1_1950 && date < jan_1_2050) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, asn1.dateToUtcTime(date)); + } else { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, asn1.dateToGeneralizedTime(date)); + } + }; + var forge = require_forge(); + require_aes(); + require_asn1(); + require_des(); + require_md(); + require_mgf(); + require_oids(); + require_pem(); + require_pss(); + require_rsa(); + require_util(); + var asn1 = forge.asn1; + var pki = (module.exports = forge.pki = forge.pki || {}); + var oids = pki.oids; + var _shortNames = {}; + _shortNames['CN'] = oids['commonName']; + _shortNames['commonName'] = 'CN'; + _shortNames['C'] = oids['countryName']; + _shortNames['countryName'] = 'C'; + _shortNames['L'] = oids['localityName']; + _shortNames['localityName'] = 'L'; + _shortNames['ST'] = oids['stateOrProvinceName']; + _shortNames['stateOrProvinceName'] = 'ST'; + _shortNames['O'] = oids['organizationName']; + _shortNames['organizationName'] = 'O'; + _shortNames['OU'] = oids['organizationalUnitName']; + _shortNames['organizationalUnitName'] = 'OU'; + _shortNames['E'] = oids['emailAddress']; + _shortNames['emailAddress'] = 'E'; + var publicKeyValidator = forge.pki.rsa.publicKeyValidator; + var x509CertificateValidator = { + name: 'Certificate', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'Certificate.TBSCertificate', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'tbsCertificate', + value: [ + { + name: 'Certificate.TBSCertificate.version', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + value: [ + { + name: 'Certificate.TBSCertificate.version.integer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certVersion' + } + ] + }, + { + name: 'Certificate.TBSCertificate.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certSerialNumber' + }, + { + name: 'Certificate.TBSCertificate.signature', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'Certificate.TBSCertificate.signature.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certinfoSignatureOid' + }, + { + name: 'Certificate.TBSCertificate.signature.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'certinfoSignatureParams' + } + ] + }, + { + name: 'Certificate.TBSCertificate.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certIssuer' + }, + { + name: 'Certificate.TBSCertificate.validity', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'Certificate.TBSCertificate.validity.notBefore (utc)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: 'certValidity1UTCTime' + }, + { + name: 'Certificate.TBSCertificate.validity.notBefore (generalized)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: 'certValidity2GeneralizedTime' + }, + { + name: 'Certificate.TBSCertificate.validity.notAfter (utc)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: 'certValidity3UTCTime' + }, + { + name: 'Certificate.TBSCertificate.validity.notAfter (generalized)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: 'certValidity4GeneralizedTime' + } + ] + }, + { + name: 'Certificate.TBSCertificate.subject', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certSubject' + }, + publicKeyValidator, + { + name: 'Certificate.TBSCertificate.issuerUniqueID', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + value: [ + { + name: 'Certificate.TBSCertificate.issuerUniqueID.id', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'certIssuerUniqueId' + } + ] + }, + { + name: 'Certificate.TBSCertificate.subjectUniqueID', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + constructed: true, + optional: true, + value: [ + { + name: 'Certificate.TBSCertificate.subjectUniqueID.id', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'certSubjectUniqueId' + } + ] + }, + { + name: 'Certificate.TBSCertificate.extensions', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + constructed: true, + captureAsn1: 'certExtensions', + optional: true + } + ] + }, + { + name: 'Certificate.signatureAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'Certificate.signatureAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certSignatureOid' + }, + { + name: 'Certificate.TBSCertificate.signature.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'certSignatureParams' + } + ] + }, + { + name: 'Certificate.signatureValue', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'certSignature' + } + ] + }; + var rsassaPssParameterValidator = { + name: 'rsapss', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'rsapss.hashAlgorithm', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + value: [ + { + name: 'rsapss.hashAlgorithm.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [ + { + name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'hashOid' + } + ] + } + ] + }, + { + name: 'rsapss.maskGenAlgorithm', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + value: [ + { + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [ + { + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'maskGenOid' + }, + { + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'maskGenHashOid' + } + ] + } + ] + } + ] + }, + { + name: 'rsapss.saltLength', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + optional: true, + value: [ + { + name: 'rsapss.saltLength.saltLength', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: 'saltLength' + } + ] + }, + { + name: 'rsapss.trailerField', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + optional: true, + value: [ + { + name: 'rsapss.trailer.trailer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: 'trailer' + } + ] + } + ] + }; + var certificationRequestInfoValidator = { + name: 'CertificationRequestInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certificationRequestInfo', + value: [ + { + name: 'CertificationRequestInfo.integer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certificationRequestInfoVersion' + }, + { + name: 'CertificationRequestInfo.subject', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certificationRequestInfoSubject' + }, + publicKeyValidator, + { + name: 'CertificationRequestInfo.attributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: 'certificationRequestInfoAttributes', + value: [ + { + name: 'CertificationRequestInfo.attributes', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'CertificationRequestInfo.attributes.type', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false + }, + { + name: 'CertificationRequestInfo.attributes.value', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true + } + ] + } + ] + } + ] + }; + var certificationRequestValidator = { + name: 'CertificationRequest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'csr', + value: [ + certificationRequestInfoValidator, + { + name: 'CertificationRequest.signatureAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'CertificationRequest.signatureAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'csrSignatureOid' + }, + { + name: 'CertificationRequest.signatureAlgorithm.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'csrSignatureParams' + } + ] + }, + { + name: 'CertificationRequest.signature', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'csrSignature' + } + ] + }; + pki.RDNAttributesAsArray = function (rdn, md) { + var rval = []; + var set, attr, obj; + for (var si = 0; si < rdn.value.length; ++si) { + set = rdn.value[si]; + for (var i = 0; i < set.value.length; ++i) { + obj = {}; + attr = set.value[i]; + obj.type = asn1.derToOid(attr.value[0].value); + obj.value = attr.value[1].value; + obj.valueTagClass = attr.value[1].type; + if (obj.type in oids) { + obj.name = oids[obj.type]; + if (obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + if (md) { + md.update(obj.type); + md.update(obj.value); + } + rval.push(obj); + } + } + return rval; + }; + pki.CRIAttributesAsArray = function (attributes) { + var rval = []; + for (var si = 0; si < attributes.length; ++si) { + var seq = attributes[si]; + var type = asn1.derToOid(seq.value[0].value); + var values = seq.value[1].value; + for (var vi = 0; vi < values.length; ++vi) { + var obj = {}; + obj.type = type; + obj.value = values[vi].value; + obj.valueTagClass = values[vi].type; + if (obj.type in oids) { + obj.name = oids[obj.type]; + if (obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + if (obj.type === oids.extensionRequest) { + obj.extensions = []; + for (var ei = 0; ei < obj.value.length; ++ei) { + obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei])); + } + } + rval.push(obj); + } + } + return rval; + }; + var _readSignatureParameters = function (oid, obj, fillDefaults) { + var params = {}; + if (oid !== oids['RSASSA-PSS']) { + return params; + } + if (fillDefaults) { + params = { + hash: { + algorithmOid: oids['sha1'] + }, + mgf: { + algorithmOid: oids['mgf1'], + hash: { + algorithmOid: oids['sha1'] + } + }, + saltLength: 20 + }; + } + var capture = {}; + var errors = []; + if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { + var error = new Error('Cannot read RSASSA-PSS parameter block.'); + error.errors = errors; + throw error; + } + if (capture.hashOid !== undefined) { + params.hash = params.hash || {}; + params.hash.algorithmOid = asn1.derToOid(capture.hashOid); + } + if (capture.maskGenOid !== undefined) { + params.mgf = params.mgf || {}; + params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); + params.mgf.hash = params.mgf.hash || {}; + params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); + } + if (capture.saltLength !== undefined) { + params.saltLength = capture.saltLength.charCodeAt(0); + } + return params; + }; + var _createSignatureDigest = function (options) { + switch (oids[options.signatureOid]) { + case 'sha1WithRSAEncryption': + case 'sha1WithRSASignature': + return forge.md.sha1.create(); + case 'md5WithRSAEncryption': + return forge.md.md5.create(); + case 'sha256WithRSAEncryption': + return forge.md.sha256.create(); + case 'sha384WithRSAEncryption': + return forge.md.sha384.create(); + case 'sha512WithRSAEncryption': + return forge.md.sha512.create(); + case 'RSASSA-PSS': + return forge.md.sha256.create(); + default: + var error = new Error('Could not compute ' + options.type + ' digest. ' + 'Unknown signature OID.'); + error.signatureOid = options.signatureOid; + throw error; + } + }; + var _verifySignature = function (options) { + var cert = options.certificate; + var scheme; + switch (cert.signatureOid) { + case oids.sha1WithRSAEncryption: + case oids.sha1WithRSASignature: + break; + case oids['RSASSA-PSS']: + var hash, mgf; + hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; + if (hash === undefined || forge.md[hash] === undefined) { + var error = new Error('Unsupported MGF hash function.'); + error.oid = cert.signatureParameters.mgf.hash.algorithmOid; + error.name = hash; + throw error; + } + mgf = oids[cert.signatureParameters.mgf.algorithmOid]; + if (mgf === undefined || forge.mgf[mgf] === undefined) { + var error = new Error('Unsupported MGF function.'); + error.oid = cert.signatureParameters.mgf.algorithmOid; + error.name = mgf; + throw error; + } + mgf = forge.mgf[mgf].create(forge.md[hash].create()); + hash = oids[cert.signatureParameters.hash.algorithmOid]; + if (hash === undefined || forge.md[hash] === undefined) { + var error = new Error('Unsupported RSASSA-PSS hash function.'); + error.oid = cert.signatureParameters.hash.algorithmOid; + error.name = hash; + throw error; + } + scheme = forge.pss.create(forge.md[hash].create(), mgf, cert.signatureParameters.saltLength); + break; + } + return cert.publicKey.verify(options.md.digest().getBytes(), options.signature, scheme); + }; + pki.certificateFromPem = function (pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== 'CERTIFICATE' && msg.type !== 'X509 CERTIFICATE' && msg.type !== 'TRUSTED CERTIFICATE') { + var error = new Error('Could not convert certificate from PEM; PEM header type ' + 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); + error.headerType = msg.type; + throw error; + } + if (msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certificate from PEM; PEM is encrypted.'); + } + var obj = asn1.fromDer(msg.body, strict); + return pki.certificateFromAsn1(obj, computeHash); + }; + pki.certificateToPem = function (cert, maxline) { + var msg = { + type: 'CERTIFICATE', + body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes() + }; + return forge.pem.encode(msg, {maxline}); + }; + pki.publicKeyFromPem = function (pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') { + var error = new Error('Could not convert public key from PEM; PEM header ' + 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); + error.headerType = msg.type; + throw error; + } + if (msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert public key from PEM; PEM is encrypted.'); + } + var obj = asn1.fromDer(msg.body); + return pki.publicKeyFromAsn1(obj); + }; + pki.publicKeyToPem = function (key, maxline) { + var msg = { + type: 'PUBLIC KEY', + body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline}); + }; + pki.publicKeyToRSAPublicKeyPem = function (key, maxline) { + var msg = { + type: 'RSA PUBLIC KEY', + body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline}); + }; + pki.getPublicKeyFingerprint = function (key, options) { + options = options || {}; + var md = options.md || forge.md.sha1.create(); + var type = options.type || 'RSAPublicKey'; + var bytes; + switch (type) { + case 'RSAPublicKey': + bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes(); + break; + case 'SubjectPublicKeyInfo': + bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes(); + break; + default: + throw new Error('Unknown fingerprint type "' + options.type + '".'); + } + md.start(); + md.update(bytes); + var digest = md.digest(); + if (options.encoding === 'hex') { + var hex = digest.toHex(); + if (options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if (options.encoding === 'binary') { + return digest.getBytes(); + } else if (options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; + }; + pki.certificationRequestFromPem = function (pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== 'CERTIFICATE REQUEST') { + var error = new Error('Could not convert certification request from PEM; ' + 'PEM header type is not "CERTIFICATE REQUEST".'); + error.headerType = msg.type; + throw error; + } + if (msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certification request from PEM; ' + 'PEM is encrypted.'); + } + var obj = asn1.fromDer(msg.body, strict); + return pki.certificationRequestFromAsn1(obj, computeHash); + }; + pki.certificationRequestToPem = function (csr, maxline) { + var msg = { + type: 'CERTIFICATE REQUEST', + body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes() + }; + return forge.pem.encode(msg, {maxline}); + }; + pki.createCertificate = function () { + var cert = {}; + cert.version = 2; + cert.serialNumber = '00'; + cert.signatureOid = null; + cert.signature = null; + cert.siginfo = {}; + cert.siginfo.algorithmOid = null; + cert.validity = {}; + cert.validity.notBefore = new Date(); + cert.validity.notAfter = new Date(); + cert.issuer = {}; + cert.issuer.getField = function (sn2) { + return _getAttribute(cert.issuer, sn2); + }; + cert.issuer.addField = function (attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = []; + cert.issuer.hash = null; + cert.subject = {}; + cert.subject.getField = function (sn2) { + return _getAttribute(cert.subject, sn2); + }; + cert.subject.addField = function (attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = []; + cert.subject.hash = null; + cert.extensions = []; + cert.publicKey = null; + cert.md = null; + cert.setSubject = function (attrs, uniqueId) { + _fillMissingFields(attrs); + cert.subject.attributes = attrs; + delete cert.subject.uniqueId; + if (uniqueId) { + cert.subject.uniqueId = uniqueId; + } + cert.subject.hash = null; + }; + cert.setIssuer = function (attrs, uniqueId) { + _fillMissingFields(attrs); + cert.issuer.attributes = attrs; + delete cert.issuer.uniqueId; + if (uniqueId) { + cert.issuer.uniqueId = uniqueId; + } + cert.issuer.hash = null; + }; + cert.setExtensions = function (exts) { + for (var i = 0; i < exts.length; ++i) { + _fillMissingExtensionFields(exts[i], {cert}); + } + cert.extensions = exts; + }; + cert.getExtension = function (options) { + if (typeof options === 'string') { + options = {name: options}; + } + var rval = null; + var ext; + for (var i = 0; rval === null && i < cert.extensions.length; ++i) { + ext = cert.extensions[i]; + if (options.id && ext.id === options.id) { + rval = ext; + } else if (options.name && ext.name === options.name) { + rval = ext; + } + } + return rval; + }; + cert.sign = function (key, md) { + cert.md = md || forge.md.sha1.create(); + var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption']; + if (!algorithmOid) { + var error = new Error('Could not compute certificate digest. ' + 'Unknown message digest algorithm OID.'); + error.algorithm = cert.md.algorithm; + throw error; + } + cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; + cert.tbsCertificate = pki.getTBSCertificate(cert); + var bytes = asn1.toDer(cert.tbsCertificate); + cert.md.update(bytes.getBytes()); + cert.signature = key.sign(cert.md); + }; + cert.verify = function (child) { + var rval = false; + if (!cert.issued(child)) { + var issuer = child.issuer; + var subject = cert.subject; + var error = new Error('The parent certificate did not issue the given child ' + "certificate; the child certificate's issuer does not match the " + "parent's subject."); + error.expectedIssuer = subject.attributes; + error.actualIssuer = issuer.attributes; + throw error; + } + var md = child.md; + if (md === null) { + md = _createSignatureDigest({ + signatureOid: child.signatureOid, + type: 'certificate' + }); + var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child); + var bytes = asn1.toDer(tbsCertificate); + md.update(bytes.getBytes()); + } + if (md !== null) { + rval = _verifySignature({ + certificate: cert, + md, + signature: child.signature + }); + } + return rval; + }; + cert.isIssuer = function (parent) { + var rval = false; + var i = cert.issuer; + var s = parent.subject; + if (i.hash && s.hash) { + rval = i.hash === s.hash; + } else if (i.attributes.length === s.attributes.length) { + rval = true; + var iattr, sattr; + for (var n = 0; rval && n < i.attributes.length; ++n) { + iattr = i.attributes[n]; + sattr = s.attributes[n]; + if (iattr.type !== sattr.type || iattr.value !== sattr.value) { + rval = false; + } + } + } + return rval; + }; + cert.issued = function (child) { + return child.isIssuer(cert); + }; + cert.generateSubjectKeyIdentifier = function () { + return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'}); + }; + cert.verifySubjectKeyIdentifier = function () { + var oid = oids['subjectKeyIdentifier']; + for (var i = 0; i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if (ext.id === oid) { + var ski = cert.generateSubjectKeyIdentifier().getBytes(); + return forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski; + } + } + return false; + }; + return cert; + }; + pki.certificateFromAsn1 = function (obj, computeHash) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, x509CertificateValidator, capture, errors)) { + var error = new Error('Cannot read X.509 certificate. ' + 'ASN.1 object is not an X509v3 Certificate.'); + error.errors = errors; + throw error; + } + var oid = asn1.derToOid(capture.publicKeyOid); + if (oid !== pki.oids.rsaEncryption) { + throw new Error('Cannot read public key. OID is not RSA.'); + } + var cert = pki.createCertificate(); + cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0; + var serial = forge.util.createBuffer(capture.certSerialNumber); + cert.serialNumber = serial.toHex(); + cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid); + cert.signatureParameters = _readSignatureParameters(cert.signatureOid, capture.certSignatureParams, true); + cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid); + cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid, capture.certinfoSignatureParams, false); + cert.signature = capture.certSignature; + var validity = []; + if (capture.certValidity1UTCTime !== undefined) { + validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); + } + if (capture.certValidity2GeneralizedTime !== undefined) { + validity.push(asn1.generalizedTimeToDate(capture.certValidity2GeneralizedTime)); + } + if (capture.certValidity3UTCTime !== undefined) { + validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); + } + if (capture.certValidity4GeneralizedTime !== undefined) { + validity.push(asn1.generalizedTimeToDate(capture.certValidity4GeneralizedTime)); + } + if (validity.length > 2) { + throw new Error('Cannot read notBefore/notAfter validity times; more ' + 'than two times were provided in the certificate.'); + } + if (validity.length < 2) { + throw new Error('Cannot read notBefore/notAfter validity times; they ' + 'were not provided as either UTCTime or GeneralizedTime.'); + } + cert.validity.notBefore = validity[0]; + cert.validity.notAfter = validity[1]; + cert.tbsCertificate = capture.tbsCertificate; + if (computeHash) { + cert.md = _createSignatureDigest({ + signatureOid: cert.signatureOid, + type: 'certificate' + }); + var bytes = asn1.toDer(cert.tbsCertificate); + cert.md.update(bytes.getBytes()); + } + var imd = forge.md.sha1.create(); + var ibytes = asn1.toDer(capture.certIssuer); + imd.update(ibytes.getBytes()); + cert.issuer.getField = function (sn2) { + return _getAttribute(cert.issuer, sn2); + }; + cert.issuer.addField = function (attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer); + if (capture.certIssuerUniqueId) { + cert.issuer.uniqueId = capture.certIssuerUniqueId; + } + cert.issuer.hash = imd.digest().toHex(); + var smd = forge.md.sha1.create(); + var sbytes = asn1.toDer(capture.certSubject); + smd.update(sbytes.getBytes()); + cert.subject.getField = function (sn2) { + return _getAttribute(cert.subject, sn2); + }; + cert.subject.addField = function (attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject); + if (capture.certSubjectUniqueId) { + cert.subject.uniqueId = capture.certSubjectUniqueId; + } + cert.subject.hash = smd.digest().toHex(); + if (capture.certExtensions) { + cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions); + } else { + cert.extensions = []; + } + cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + return cert; + }; + pki.certificateExtensionsFromAsn1 = function (exts) { + var rval = []; + for (var i = 0; i < exts.value.length; ++i) { + var extseq = exts.value[i]; + for (var ei = 0; ei < extseq.value.length; ++ei) { + rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei])); + } + } + return rval; + }; + pki.certificateExtensionFromAsn1 = function (ext) { + var e = {}; + e.id = asn1.derToOid(ext.value[0].value); + e.critical = false; + if (ext.value[1].type === asn1.Type.BOOLEAN) { + e.critical = ext.value[1].value.charCodeAt(0) !== 0; + e.value = ext.value[2].value; + } else { + e.value = ext.value[1].value; + } + if (e.id in oids) { + e.name = oids[e.id]; + if (e.name === 'keyUsage') { + var ev = asn1.fromDer(e.value); + var b22 = 0; + var b3 = 0; + if (ev.value.length > 1) { + b22 = ev.value.charCodeAt(1); + b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; + } + e.digitalSignature = (b22 & 128) === 128; + e.nonRepudiation = (b22 & 64) === 64; + e.keyEncipherment = (b22 & 32) === 32; + e.dataEncipherment = (b22 & 16) === 16; + e.keyAgreement = (b22 & 8) === 8; + e.keyCertSign = (b22 & 4) === 4; + e.cRLSign = (b22 & 2) === 2; + e.encipherOnly = (b22 & 1) === 1; + e.decipherOnly = (b3 & 128) === 128; + } else if (e.name === 'basicConstraints') { + var ev = asn1.fromDer(e.value); + if (ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { + e.cA = ev.value[0].value.charCodeAt(0) !== 0; + } else { + e.cA = false; + } + var value = null; + if (ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { + value = ev.value[0].value; + } else if (ev.value.length > 1) { + value = ev.value[1].value; + } + if (value !== null) { + e.pathLenConstraint = asn1.derToInteger(value); + } + } else if (e.name === 'extKeyUsage') { + var ev = asn1.fromDer(e.value); + for (var vi = 0; vi < ev.value.length; ++vi) { + var oid = asn1.derToOid(ev.value[vi].value); + if (oid in oids) { + e[oids[oid]] = true; + } else { + e[oid] = true; + } + } + } else if (e.name === 'nsCertType') { + var ev = asn1.fromDer(e.value); + var b22 = 0; + if (ev.value.length > 1) { + b22 = ev.value.charCodeAt(1); + } + e.client = (b22 & 128) === 128; + e.server = (b22 & 64) === 64; + e.email = (b22 & 32) === 32; + e.objsign = (b22 & 16) === 16; + e.reserved = (b22 & 8) === 8; + e.sslCA = (b22 & 4) === 4; + e.emailCA = (b22 & 2) === 2; + e.objCA = (b22 & 1) === 1; + } else if (e.name === 'subjectAltName' || e.name === 'issuerAltName') { + e.altNames = []; + var gn; + var ev = asn1.fromDer(e.value); + for (var n = 0; n < ev.value.length; ++n) { + gn = ev.value[n]; + var altName = { + type: gn.type, + value: gn.value + }; + e.altNames.push(altName); + switch (gn.type) { + case 1: + case 2: + case 6: + break; + case 7: + altName.ip = forge.util.bytesToIP(gn.value); + break; + case 8: + altName.oid = asn1.derToOid(gn.value); + break; + default: + } + } + } else if (e.name === 'subjectKeyIdentifier') { + var ev = asn1.fromDer(e.value); + e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value); + } + } + return e; + }; + pki.certificationRequestFromAsn1 = function (obj, computeHash) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, certificationRequestValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#10 certificate request. ' + 'ASN.1 object is not a PKCS#10 CertificationRequest.'); + error.errors = errors; + throw error; + } + var oid = asn1.derToOid(capture.publicKeyOid); + if (oid !== pki.oids.rsaEncryption) { + throw new Error('Cannot read public key. OID is not RSA.'); + } + var csr = pki.createCertificationRequest(); + csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; + csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.signatureParameters = _readSignatureParameters(csr.signatureOid, capture.csrSignatureParams, true); + csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.siginfo.parameters = _readSignatureParameters(csr.siginfo.algorithmOid, capture.csrSignatureParams, false); + csr.signature = capture.csrSignature; + csr.certificationRequestInfo = capture.certificationRequestInfo; + if (computeHash) { + csr.md = _createSignatureDigest({ + signatureOid: csr.signatureOid, + type: 'certification request' + }); + var bytes = asn1.toDer(csr.certificationRequestInfo); + csr.md.update(bytes.getBytes()); + } + var smd = forge.md.sha1.create(); + csr.subject.getField = function (sn2) { + return _getAttribute(csr.subject, sn2); + }; + csr.subject.addField = function (attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = pki.RDNAttributesAsArray(capture.certificationRequestInfoSubject, smd); + csr.subject.hash = smd.digest().toHex(); + csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + csr.getAttribute = function (sn2) { + return _getAttribute(csr, sn2); + }; + csr.addAttribute = function (attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.attributes = pki.CRIAttributesAsArray(capture.certificationRequestInfoAttributes || []); + return csr; + }; + pki.createCertificationRequest = function () { + var csr = {}; + csr.version = 0; + csr.signatureOid = null; + csr.signature = null; + csr.siginfo = {}; + csr.siginfo.algorithmOid = null; + csr.subject = {}; + csr.subject.getField = function (sn2) { + return _getAttribute(csr.subject, sn2); + }; + csr.subject.addField = function (attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = []; + csr.subject.hash = null; + csr.publicKey = null; + csr.attributes = []; + csr.getAttribute = function (sn2) { + return _getAttribute(csr, sn2); + }; + csr.addAttribute = function (attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.md = null; + csr.setSubject = function (attrs) { + _fillMissingFields(attrs); + csr.subject.attributes = attrs; + csr.subject.hash = null; + }; + csr.setAttributes = function (attrs) { + _fillMissingFields(attrs); + csr.attributes = attrs; + }; + csr.sign = function (key, md) { + csr.md = md || forge.md.sha1.create(); + var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption']; + if (!algorithmOid) { + var error = new Error('Could not compute certification request digest. ' + 'Unknown message digest algorithm OID.'); + error.algorithm = csr.md.algorithm; + throw error; + } + csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; + csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(csr.certificationRequestInfo); + csr.md.update(bytes.getBytes()); + csr.signature = key.sign(csr.md); + }; + csr.verify = function () { + var rval = false; + var md = csr.md; + if (md === null) { + md = _createSignatureDigest({ + signatureOid: csr.signatureOid, + type: 'certification request' + }); + var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(cri); + md.update(bytes.getBytes()); + } + if (md !== null) { + rval = _verifySignature({ + certificate: csr, + md, + signature: csr.signature + }); + } + return rval; + }; + return csr; + }; + var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); + var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); + pki.getTBSCertificate = function (cert) { + var notBefore = _dateToAsn1(cert.validity.notBefore); + var notAfter = _dateToAsn1(cert.validity.notAfter); + var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(cert.version).getBytes())]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(cert.serialNumber)), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()), + _signatureParametersToAsn1(cert.siginfo.algorithmOid, cert.siginfo.parameters) + ]), + _dnToAsn1(cert.issuer), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [notBefore, notAfter]), + _dnToAsn1(cert.subject), + pki.publicKeyToAsn1(cert.publicKey) + ]); + if (cert.issuer.uniqueId) { + tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, String.fromCharCode(0) + cert.issuer.uniqueId)])); + } + if (cert.subject.uniqueId) { + tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, String.fromCharCode(0) + cert.subject.uniqueId)])); + } + if (cert.extensions.length > 0) { + tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions)); + } + return tbs; + }; + pki.getCertificationRequestInfo = function (csr) { + var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(csr.version).getBytes()), + _dnToAsn1(csr.subject), + pki.publicKeyToAsn1(csr.publicKey), + _CRIAttributesToAsn1(csr) + ]); + return cri; + }; + pki.distinguishedNameToAsn1 = function (dn) { + return _dnToAsn1(dn); + }; + pki.certificateToAsn1 = function (cert) { + var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert); + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + tbsCertificate, + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(cert.signatureOid).getBytes()), _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, String.fromCharCode(0) + cert.signature) + ]); + }; + pki.certificateExtensionsToAsn1 = function (exts) { + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); + var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + rval.value.push(seq); + for (var i = 0; i < exts.length; ++i) { + seq.value.push(pki.certificateExtensionToAsn1(exts[i])); + } + return rval; + }; + pki.certificateExtensionToAsn1 = function (ext) { + var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + extseq.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(ext.id).getBytes())); + if (ext.critical) { + extseq.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, String.fromCharCode(255))); + } + var value = ext.value; + if (typeof ext.value !== 'string') { + value = asn1.toDer(value).getBytes(); + } + extseq.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value)); + return extseq; + }; + pki.certificationRequestToAsn1 = function (csr) { + var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr); + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + cri, + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(csr.signatureOid).getBytes()), _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, String.fromCharCode(0) + csr.signature) + ]); + }; + pki.createCaStore = function (certs) { + var caStore = { + certs: {} + }; + caStore.getIssuer = function (cert2) { + var rval = getBySubject(cert2.issuer); + return rval; + }; + caStore.addCertificate = function (cert2) { + if (typeof cert2 === 'string') { + cert2 = forge.pki.certificateFromPem(cert2); + } + ensureSubjectHasHash(cert2.subject); + if (!caStore.hasCertificate(cert2)) { + if (cert2.subject.hash in caStore.certs) { + var tmp = caStore.certs[cert2.subject.hash]; + if (!forge.util.isArray(tmp)) { + tmp = [tmp]; + } + tmp.push(cert2); + caStore.certs[cert2.subject.hash] = tmp; + } else { + caStore.certs[cert2.subject.hash] = cert2; + } + } + }; + caStore.hasCertificate = function (cert2) { + if (typeof cert2 === 'string') { + cert2 = forge.pki.certificateFromPem(cert2); + } + var match = getBySubject(cert2.subject); + if (!match) { + return false; + } + if (!forge.util.isArray(match)) { + match = [match]; + } + var der1 = asn1.toDer(pki.certificateToAsn1(cert2)).getBytes(); + for (var i3 = 0; i3 < match.length; ++i3) { + var der2 = asn1.toDer(pki.certificateToAsn1(match[i3])).getBytes(); + if (der1 === der2) { + return true; + } + } + return false; + }; + caStore.listAllCertificates = function () { + var certList = []; + for (var hash in caStore.certs) { + if (caStore.certs.hasOwnProperty(hash)) { + var value = caStore.certs[hash]; + if (!forge.util.isArray(value)) { + certList.push(value); + } else { + for (var i3 = 0; i3 < value.length; ++i3) { + certList.push(value[i3]); + } + } + } + } + return certList; + }; + caStore.removeCertificate = function (cert2) { + var result; + if (typeof cert2 === 'string') { + cert2 = forge.pki.certificateFromPem(cert2); + } + ensureSubjectHasHash(cert2.subject); + if (!caStore.hasCertificate(cert2)) { + return null; + } + var match = getBySubject(cert2.subject); + if (!forge.util.isArray(match)) { + result = caStore.certs[cert2.subject.hash]; + delete caStore.certs[cert2.subject.hash]; + return result; + } + var der1 = asn1.toDer(pki.certificateToAsn1(cert2)).getBytes(); + for (var i3 = 0; i3 < match.length; ++i3) { + var der2 = asn1.toDer(pki.certificateToAsn1(match[i3])).getBytes(); + if (der1 === der2) { + result = match[i3]; + match.splice(i3, 1); + } + } + if (match.length === 0) { + delete caStore.certs[cert2.subject.hash]; + } + return result; + }; + function getBySubject(subject) { + ensureSubjectHasHash(subject); + return caStore.certs[subject.hash] || null; + } + function ensureSubjectHasHash(subject) { + if (!subject.hash) { + var md = forge.md.sha1.create(); + subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md); + subject.hash = md.digest().toHex(); + } + } + if (certs) { + for (var i = 0; i < certs.length; ++i) { + var cert = certs[i]; + caStore.addCertificate(cert); + } + } + return caStore; + }; + pki.certificateError = { + bad_certificate: 'forge.pki.BadCertificate', + unsupported_certificate: 'forge.pki.UnsupportedCertificate', + certificate_revoked: 'forge.pki.CertificateRevoked', + certificate_expired: 'forge.pki.CertificateExpired', + certificate_unknown: 'forge.pki.CertificateUnknown', + unknown_ca: 'forge.pki.UnknownCertificateAuthority' + }; + pki.verifyCertificateChain = function (caStore, chain2, options) { + if (typeof options === 'function') { + options = {verify: options}; + } + options = options || {}; + chain2 = chain2.slice(0); + var certs = chain2.slice(0); + var validityCheckDate = options.validityCheckDate; + if (typeof validityCheckDate === 'undefined') { + validityCheckDate = new Date(); + } + var first = true; + var error = null; + var depth = 0; + do { + var cert = chain2.shift(); + var parent = null; + var selfSigned = false; + if (validityCheckDate) { + if (validityCheckDate < cert.validity.notBefore || validityCheckDate > cert.validity.notAfter) { + error = { + message: 'Certificate is not valid yet or has expired.', + error: pki.certificateError.certificate_expired, + notBefore: cert.validity.notBefore, + notAfter: cert.validity.notAfter, + now: validityCheckDate + }; + } + } + if (error === null) { + parent = chain2[0] || caStore.getIssuer(cert); + if (parent === null) { + if (cert.isIssuer(cert)) { + selfSigned = true; + parent = cert; + } + } + if (parent) { + var parents = parent; + if (!forge.util.isArray(parents)) { + parents = [parents]; + } + var verified = false; + while (!verified && parents.length > 0) { + parent = parents.shift(); + try { + verified = parent.verify(cert); + } catch (ex) {} + } + if (!verified) { + error = { + message: 'Certificate signature is invalid.', + error: pki.certificateError.bad_certificate + }; + } + } + if (error === null && (!parent || selfSigned) && !caStore.hasCertificate(cert)) { + error = { + message: 'Certificate is not trusted.', + error: pki.certificateError.unknown_ca + }; + } + } + if (error === null && parent && !cert.isIssuer(parent)) { + error = { + message: 'Certificate issuer is invalid.', + error: pki.certificateError.bad_certificate + }; + } + if (error === null) { + var se = { + keyUsage: true, + basicConstraints: true + }; + for (var i = 0; error === null && i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if (ext.critical && !(ext.name in se)) { + error = { + message: 'Certificate has an unsupported critical extension.', + error: pki.certificateError.unsupported_certificate + }; + } + } + } + if (error === null && (!first || (chain2.length === 0 && (!parent || selfSigned)))) { + var bcExt = cert.getExtension('basicConstraints'); + var keyUsageExt = cert.getExtension('keyUsage'); + if (keyUsageExt !== null) { + if (!keyUsageExt.keyCertSign || bcExt === null) { + error = { + message: + 'Certificate keyUsage or basicConstraints conflict ' + + 'or indicate that the certificate is not a CA. ' + + 'If the certificate is the only one in the chain or ' + + "isn't the first then the certificate must be a " + + 'valid CA.', + error: pki.certificateError.bad_certificate + }; + } + } + if (error === null && bcExt !== null && !bcExt.cA) { + error = { + message: 'Certificate basicConstraints indicates the certificate ' + 'is not a CA.', + error: pki.certificateError.bad_certificate + }; + } + if (error === null && keyUsageExt !== null && 'pathLenConstraint' in bcExt) { + var pathLen = depth - 1; + if (pathLen > bcExt.pathLenConstraint) { + error = { + message: 'Certificate basicConstraints pathLenConstraint violated.', + error: pki.certificateError.bad_certificate + }; + } + } + } + var vfd = error === null ? true : error.error; + var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; + if (ret === true) { + error = null; + } else { + if (vfd === true) { + error = { + message: 'The application rejected the certificate.', + error: pki.certificateError.bad_certificate + }; + } + if (ret || ret === 0) { + if (typeof ret === 'object' && !forge.util.isArray(ret)) { + if (ret.message) { + error.message = ret.message; + } + if (ret.error) { + error.error = ret.error; + } + } else if (typeof ret === 'string') { + error.error = ret; + } + } + throw error; + } + first = false; + ++depth; + } while (chain2.length > 0); + return true; + }; +}); + +// node_modules/node-forge/lib/pkcs12.js +var require_pkcs12 = __commonJS((exports, module) => { + var _getBagsByAttribute = function (safeContents, attrName, attrValue, bagType) { + var result = []; + for (var i = 0; i < safeContents.length; i++) { + for (var j = 0; j < safeContents[i].safeBags.length; j++) { + var bag = safeContents[i].safeBags[j]; + if (bagType !== undefined && bag.type !== bagType) { + continue; + } + if (attrName === null) { + result.push(bag); + continue; + } + if (bag.attributes[attrName] !== undefined && bag.attributes[attrName].indexOf(attrValue) >= 0) { + result.push(bag); + } + } + } + return result; + }; + var _decodePkcs7Data = function (data) { + if (data.composed || data.constructed) { + var value = forge.util.createBuffer(); + for (var i = 0; i < data.value.length; ++i) { + value.putBytes(data.value[i].value); + } + data.composed = data.constructed = false; + data.value = value.getBytes(); + } + return data; + }; + var _decodeAuthenticatedSafe = function (pfx, authSafe, strict, password) { + authSafe = asn1.fromDer(authSafe, strict); + if (authSafe.tagClass !== asn1.Class.UNIVERSAL || authSafe.type !== asn1.Type.SEQUENCE || authSafe.constructed !== true) { + throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' + 'SEQUENCE OF ContentInfo'); + } + for (var i = 0; i < authSafe.value.length; i++) { + var contentInfo = authSafe.value[i]; + var capture = {}; + var errors = []; + if (!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { + var error = new Error('Cannot read ContentInfo.'); + error.errors = errors; + throw error; + } + var obj = { + encrypted: false + }; + var safeContents = null; + var data = capture.content.value[0]; + switch (asn1.derToOid(capture.contentType)) { + case pki.oids.data: + if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { + throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.'); + } + safeContents = _decodePkcs7Data(data).value; + break; + case pki.oids.encryptedData: + safeContents = _decryptSafeContents(data, password); + obj.encrypted = true; + break; + default: + var error = new Error('Unsupported PKCS#12 contentType.'); + error.contentType = asn1.derToOid(capture.contentType); + throw error; + } + obj.safeBags = _decodeSafeContents(safeContents, strict, password); + pfx.safeContents.push(obj); + } + }; + var _decryptSafeContents = function (data, password) { + var capture = {}; + var errors = []; + if (!asn1.validate(data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) { + var error = new Error('Cannot read EncryptedContentInfo.'); + error.errors = errors; + throw error; + } + var oid = asn1.derToOid(capture.contentType); + if (oid !== pki.oids.data) { + var error = new Error('PKCS#12 EncryptedContentInfo ContentType is not Data.'); + error.oid = oid; + throw error; + } + oid = asn1.derToOid(capture.encAlgorithm); + var cipher = pki.pbe.getCipher(oid, capture.encParameter, password); + var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); + var encrypted = forge.util.createBuffer(encryptedContentAsn1.value); + cipher.update(encrypted); + if (!cipher.finish()) { + throw new Error('Failed to decrypt PKCS#12 SafeContents.'); + } + return cipher.output.getBytes(); + }; + var _decodeSafeContents = function (safeContents, strict, password) { + if (!strict && safeContents.length === 0) { + return []; + } + safeContents = asn1.fromDer(safeContents, strict); + if (safeContents.tagClass !== asn1.Class.UNIVERSAL || safeContents.type !== asn1.Type.SEQUENCE || safeContents.constructed !== true) { + throw new Error('PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.'); + } + var res = []; + for (var i = 0; i < safeContents.value.length; i++) { + var safeBag = safeContents.value[i]; + var capture = {}; + var errors = []; + if (!asn1.validate(safeBag, safeBagValidator, capture, errors)) { + var error = new Error('Cannot read SafeBag.'); + error.errors = errors; + throw error; + } + var bag = { + type: asn1.derToOid(capture.bagId), + attributes: _decodeBagAttributes(capture.bagAttributes) + }; + res.push(bag); + var validator, decoder; + var bagAsn1 = capture.bagValue.value[0]; + switch (bag.type) { + case pki.oids.pkcs8ShroudedKeyBag: + bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password); + if (bagAsn1 === null) { + throw new Error('Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?'); + } + case pki.oids.keyBag: + try { + bag.key = pki.privateKeyFromAsn1(bagAsn1); + } catch (e) { + bag.key = null; + bag.asn1 = bagAsn1; + } + continue; + case pki.oids.certBag: + validator = certBagValidator; + decoder = function () { + if (asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) { + var error2 = new Error('Unsupported certificate type, only X.509 supported.'); + error2.oid = asn1.derToOid(capture.certId); + throw error2; + } + var certAsn1 = asn1.fromDer(capture.cert, strict); + try { + bag.cert = pki.certificateFromAsn1(certAsn1, true); + } catch (e) { + bag.cert = null; + bag.asn1 = certAsn1; + } + }; + break; + default: + var error = new Error('Unsupported PKCS#12 SafeBag type.'); + error.oid = bag.type; + throw error; + } + if (validator !== undefined && !asn1.validate(bagAsn1, validator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 ' + validator.name); + error.errors = errors; + throw error; + } + decoder(); + } + return res; + }; + var _decodeBagAttributes = function (attributes) { + var decodedAttrs = {}; + if (attributes !== undefined) { + for (var i = 0; i < attributes.length; ++i) { + var capture = {}; + var errors = []; + if (!asn1.validate(attributes[i], attributeValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 BagAttribute.'); + error.errors = errors; + throw error; + } + var oid = asn1.derToOid(capture.oid); + if (pki.oids[oid] === undefined) { + continue; + } + decodedAttrs[pki.oids[oid]] = []; + for (var j = 0; j < capture.values.length; ++j) { + decodedAttrs[pki.oids[oid]].push(capture.values[j].value); + } + } + } + return decodedAttrs; + }; + var forge = require_forge(); + require_asn1(); + require_hmac(); + require_oids(); + require_pkcs7asn1(); + require_pbe(); + require_random(); + require_rsa(); + require_sha1(); + require_util(); + require_x509(); + var asn1 = forge.asn1; + var pki = forge.pki; + var p12 = (module.exports = forge.pkcs12 = forge.pkcs12 || {}); + var contentInfoValidator = { + name: 'ContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'ContentInfo.contentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, + { + name: 'ContentInfo.content', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: 'content' + } + ] + }; + var pfxValidator = { + name: 'PFX', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'PFX.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, + contentInfoValidator, + { + name: 'PFX.macData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'mac', + value: [ + { + name: 'PFX.macData.mac', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'PFX.macData.mac.digestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'PFX.macData.mac.digestAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'macAlgorithm' + }, + { + name: 'PFX.macData.mac.digestAlgorithm.parameters', + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: 'macAlgorithmParameters' + } + ] + }, + { + name: 'PFX.macData.mac.digest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'macDigest' + } + ] + }, + { + name: 'PFX.macData.macSalt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'macSalt' + }, + { + name: 'PFX.macData.iterations', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: 'macIterations' + } + ] + } + ] + }; + var safeBagValidator = { + name: 'SafeBag', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'SafeBag.bagId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'bagId' + }, + { + name: 'SafeBag.bagValue', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: 'bagValue' + }, + { + name: 'SafeBag.bagAttributes', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + optional: true, + capture: 'bagAttributes' + } + ] + }; + var attributeValidator = { + name: 'Attribute', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'Attribute.attrId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'oid' + }, + { + name: 'Attribute.attrValues', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + capture: 'values' + } + ] + }; + var certBagValidator = { + name: 'CertBag', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'CertBag.certId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certId' + }, + { + name: 'CertBag.certValue', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + value: [ + { + name: 'CertBag.certValue[0]', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.OCTETSTRING, + constructed: false, + capture: 'cert' + } + ] + } + ] + }; + p12.pkcs12FromAsn1 = function (obj, strict, password) { + if (typeof strict === 'string') { + password = strict; + strict = true; + } else if (strict === undefined) { + strict = true; + } + var capture = {}; + var errors = []; + if (!asn1.validate(obj, pfxValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 PFX. ' + 'ASN.1 object is not an PKCS#12 PFX.'); + error.errors = error; + throw error; + } + var pfx = { + version: capture.version.charCodeAt(0), + safeContents: [], + getBags: function (filter) { + var rval = {}; + var localKeyId; + if ('localKeyId' in filter) { + localKeyId = filter.localKeyId; + } else if ('localKeyIdHex' in filter) { + localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); + } + if (localKeyId === undefined && !('friendlyName' in filter) && 'bagType' in filter) { + rval[filter.bagType] = _getBagsByAttribute(pfx.safeContents, null, null, filter.bagType); + } + if (localKeyId !== undefined) { + rval.localKeyId = _getBagsByAttribute(pfx.safeContents, 'localKeyId', localKeyId, filter.bagType); + } + if ('friendlyName' in filter) { + rval.friendlyName = _getBagsByAttribute(pfx.safeContents, 'friendlyName', filter.friendlyName, filter.bagType); + } + return rval; + }, + getBagsByFriendlyName: function (friendlyName, bagType) { + return _getBagsByAttribute(pfx.safeContents, 'friendlyName', friendlyName, bagType); + }, + getBagsByLocalKeyId: function (localKeyId, bagType) { + return _getBagsByAttribute(pfx.safeContents, 'localKeyId', localKeyId, bagType); + } + }; + if (capture.version.charCodeAt(0) !== 3) { + var error = new Error('PKCS#12 PFX of version other than 3 not supported.'); + error.version = capture.version.charCodeAt(0); + throw error; + } + if (asn1.derToOid(capture.contentType) !== pki.oids.data) { + var error = new Error('Only PKCS#12 PFX in password integrity mode supported.'); + error.oid = asn1.derToOid(capture.contentType); + throw error; + } + var data = capture.content.value[0]; + if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { + throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.'); + } + data = _decodePkcs7Data(data); + if (capture.mac) { + var md = null; + var macKeyBytes = 0; + var macAlgorithm = asn1.derToOid(capture.macAlgorithm); + switch (macAlgorithm) { + case pki.oids.sha1: + md = forge.md.sha1.create(); + macKeyBytes = 20; + break; + case pki.oids.sha256: + md = forge.md.sha256.create(); + macKeyBytes = 32; + break; + case pki.oids.sha384: + md = forge.md.sha384.create(); + macKeyBytes = 48; + break; + case pki.oids.sha512: + md = forge.md.sha512.create(); + macKeyBytes = 64; + break; + case pki.oids.md5: + md = forge.md.md5.create(); + macKeyBytes = 16; + break; + } + if (md === null) { + throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm); + } + var macSalt = new forge.util.ByteBuffer(capture.macSalt); + var macIterations = 'macIterations' in capture ? parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1; + var macKey = p12.generateKey(password, macSalt, 3, macIterations, macKeyBytes, md); + var mac = forge.hmac.create(); + mac.start(md, macKey); + mac.update(data.value); + var macValue = mac.getMac(); + if (macValue.getBytes() !== capture.macDigest) { + throw new Error('PKCS#12 MAC could not be verified. Invalid password?'); + } + } + _decodeAuthenticatedSafe(pfx, data.value, strict, password); + return pfx; + }; + p12.toPkcs12Asn1 = function (key, cert, password, options) { + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || options.encAlgorithm || 'aes128'; + if (!('useMac' in options)) { + options.useMac = true; + } + if (!('localKeyId' in options)) { + options.localKeyId = null; + } + if (!('generateLocalKeyId' in options)) { + options.generateLocalKeyId = true; + } + var localKeyId = options.localKeyId; + var bagAttrs; + if (localKeyId !== null) { + localKeyId = forge.util.hexToBytes(localKeyId); + } else if (options.generateLocalKeyId) { + if (cert) { + var pairedCert = forge.util.isArray(cert) ? cert[0] : cert; + if (typeof pairedCert === 'string') { + pairedCert = pki.certificateFromPem(pairedCert); + } + var sha1 = forge.md.sha1.create(); + sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes()); + localKeyId = sha1.digest().getBytes(); + } else { + localKeyId = forge.random.getBytes(20); + } + } + var attrs = []; + if (localKeyId !== null) { + attrs.push( + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.localKeyId).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, localKeyId)]) + ]) + ); + } + if ('friendlyName' in options) { + attrs.push( + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.friendlyName).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false, options.friendlyName)]) + ]) + ); + } + if (attrs.length > 0) { + bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); + } + var contents = []; + var chain2 = []; + if (cert !== null) { + if (forge.util.isArray(cert)) { + chain2 = cert; + } else { + chain2 = [cert]; + } + } + var certSafeBags = []; + for (var i = 0; i < chain2.length; ++i) { + cert = chain2[i]; + if (typeof cert === 'string') { + cert = pki.certificateFromPem(cert); + } + var certBagAttrs = i === 0 ? bagAttrs : undefined; + var certAsn1 = pki.certificateToAsn1(cert); + var certSafeBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.certBag).getBytes()), + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.x509Certificate).getBytes()), + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(certAsn1).getBytes())]) + ]) + ]), + certBagAttrs + ]); + certSafeBags.push(certSafeBag); + } + if (certSafeBags.length > 0) { + var certSafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags); + var certCI = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.data).getBytes()), + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(certSafeContents).getBytes())]) + ]); + contents.push(certCI); + } + var keyBag = null; + if (key !== null) { + var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key)); + if (password === null) { + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.keyBag).getBytes()), + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [pkAsn1]), + bagAttrs + ]); + } else { + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()), + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [pki.encryptPrivateKeyInfo(pkAsn1, password, options)]), + bagAttrs + ]); + } + var keySafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); + var keyCI = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.data).getBytes()), + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(keySafeContents).getBytes())]) + ]); + contents.push(keyCI); + } + var safe = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents); + var macData; + if (options.useMac) { + var sha1 = forge.md.sha1.create(); + var macSalt = new forge.util.ByteBuffer(forge.random.getBytes(options.saltSize)); + var count = options.count; + var key = p12.generateKey(password, macSalt, 3, count, 20); + var mac = forge.hmac.create(); + mac.start(sha1, key); + mac.update(asn1.toDer(safe).getBytes()); + var macValue = mac.getMac(); + macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.sha1).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macValue.getBytes()) + ]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(count).getBytes()) + ]); + } + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(3).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.data).getBytes()), + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(safe).getBytes())]) + ]), + macData + ]); + }; + p12.generateKey = forge.pbe.generatePkcs12Key; +}); + +// node_modules/node-forge/lib/pki.js +var require_pki = __commonJS((exports, module) => { + var forge = require_forge(); + require_asn1(); + require_oids(); + require_pbe(); + require_pem(); + require_pbkdf2(); + require_pkcs12(); + require_pss(); + require_rsa(); + require_util(); + require_x509(); + var asn1 = forge.asn1; + var pki = (module.exports = forge.pki = forge.pki || {}); + pki.pemToDer = function (pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert PEM to DER; PEM is encrypted.'); + } + return forge.util.createBuffer(msg.body); + }; + pki.privateKeyFromPem = function (pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') { + var error = new Error('Could not convert private key from PEM; PEM ' + 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); + error.headerType = msg.type; + throw error; + } + if (msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert private key from PEM; PEM is encrypted.'); + } + var obj = asn1.fromDer(msg.body); + return pki.privateKeyFromAsn1(obj); + }; + pki.privateKeyToPem = function (key, maxline) { + var msg = { + type: 'RSA PRIVATE KEY', + body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline}); + }; + pki.privateKeyInfoToPem = function (pki2, maxline) { + var msg = { + type: 'PRIVATE KEY', + body: asn1.toDer(pki2).getBytes() + }; + return forge.pem.encode(msg, {maxline}); + }; +}); + +// node_modules/node-forge/lib/tls.js +var require_tls = __commonJS((exports, module) => { + var forge = require_forge(); + require_asn1(); + require_hmac(); + require_md5(); + require_pem(); + require_pki(); + require_random(); + require_sha1(); + require_util(); + var prf_TLS1 = function (secret, label, seed, length) { + var rval = forge.util.createBuffer(); + var idx = secret.length >> 1; + var slen = idx + (secret.length & 1); + var s1 = secret.substr(0, slen); + var s22 = secret.substr(idx, slen); + var ai = forge.util.createBuffer(); + var hmac = forge.hmac.create(); + seed = label + seed; + var md5itr = Math.ceil(length / 16); + var sha1itr = Math.ceil(length / 20); + hmac.start('MD5', s1); + var md5bytes = forge.util.createBuffer(); + ai.putBytes(seed); + for (var i = 0; i < md5itr; ++i) { + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + md5bytes.putBuffer(hmac.digest()); + } + hmac.start('SHA1', s22); + var sha1bytes = forge.util.createBuffer(); + ai.clear(); + ai.putBytes(seed); + for (var i = 0; i < sha1itr; ++i) { + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + sha1bytes.putBuffer(hmac.digest()); + } + rval.putBytes(forge.util.xorBytes(md5bytes.getBytes(), sha1bytes.getBytes(), length)); + return rval; + }; + var hmac_sha1 = function (key2, seqNum, record) { + var hmac = forge.hmac.create(); + hmac.start('SHA1', key2); + var b3 = forge.util.createBuffer(); + b3.putInt32(seqNum[0]); + b3.putInt32(seqNum[1]); + b3.putByte(record.type); + b3.putByte(record.version.major); + b3.putByte(record.version.minor); + b3.putInt16(record.length); + b3.putBytes(record.fragment.bytes()); + hmac.update(b3.getBytes()); + return hmac.digest().getBytes(); + }; + var deflate = function (c, record, s) { + var rval = false; + try { + var bytes = c.deflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch (ex) {} + return rval; + }; + var inflate = function (c, record, s) { + var rval = false; + try { + var bytes = c.inflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch (ex) {} + return rval; + }; + var readVector = function (b3, lenBytes) { + var len = 0; + switch (lenBytes) { + case 1: + len = b3.getByte(); + break; + case 2: + len = b3.getInt16(); + break; + case 3: + len = b3.getInt24(); + break; + case 4: + len = b3.getInt32(); + break; + } + return forge.util.createBuffer(b3.getBytes(len)); + }; + var writeVector = function (b3, lenBytes, v) { + b3.putInt(v.length(), lenBytes << 3); + b3.putBuffer(v); + }; + var tls = {}; + tls.Versions = { + TLS_1_0: {major: 3, minor: 1}, + TLS_1_1: {major: 3, minor: 2}, + TLS_1_2: {major: 3, minor: 3} + }; + tls.SupportedVersions = [tls.Versions.TLS_1_1, tls.Versions.TLS_1_0]; + tls.Version = tls.SupportedVersions[0]; + tls.MaxFragment = 16384 - 1024; + tls.ConnectionEnd = { + server: 0, + client: 1 + }; + tls.PRFAlgorithm = { + tls_prf_sha256: 0 + }; + tls.BulkCipherAlgorithm = { + none: null, + rc4: 0, + des3: 1, + aes: 2 + }; + tls.CipherType = { + stream: 0, + block: 1, + aead: 2 + }; + tls.MACAlgorithm = { + none: null, + hmac_md5: 0, + hmac_sha1: 1, + hmac_sha256: 2, + hmac_sha384: 3, + hmac_sha512: 4 + }; + tls.CompressionMethod = { + none: 0, + deflate: 1 + }; + tls.ContentType = { + change_cipher_spec: 20, + alert: 21, + handshake: 22, + application_data: 23, + heartbeat: 24 + }; + tls.HandshakeType = { + hello_request: 0, + client_hello: 1, + server_hello: 2, + certificate: 11, + server_key_exchange: 12, + certificate_request: 13, + server_hello_done: 14, + certificate_verify: 15, + client_key_exchange: 16, + finished: 20 + }; + tls.Alert = {}; + tls.Alert.Level = { + warning: 1, + fatal: 2 + }; + tls.Alert.Description = { + close_notify: 0, + unexpected_message: 10, + bad_record_mac: 20, + decryption_failed: 21, + record_overflow: 22, + decompression_failure: 30, + handshake_failure: 40, + bad_certificate: 42, + unsupported_certificate: 43, + certificate_revoked: 44, + certificate_expired: 45, + certificate_unknown: 46, + illegal_parameter: 47, + unknown_ca: 48, + access_denied: 49, + decode_error: 50, + decrypt_error: 51, + export_restriction: 60, + protocol_version: 70, + insufficient_security: 71, + internal_error: 80, + user_canceled: 90, + no_renegotiation: 100 + }; + tls.HeartbeatMessageType = { + heartbeat_request: 1, + heartbeat_response: 2 + }; + tls.CipherSuites = {}; + tls.getCipherSuite = function (twoBytes) { + var rval = null; + for (var key2 in tls.CipherSuites) { + var cs = tls.CipherSuites[key2]; + if (cs.id[0] === twoBytes.charCodeAt(0) && cs.id[1] === twoBytes.charCodeAt(1)) { + rval = cs; + break; + } + } + return rval; + }; + tls.handleUnexpected = function (c, record) { + var ignore = !c.open && c.entity === tls.ConnectionEnd.client; + if (!ignore) { + c.error(c, { + message: 'Unexpected message. Received TLS record out of order.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unexpected_message + } + }); + } + }; + tls.handleHelloRequest = function (c, record, length) { + if (!c.handshaking && c.handshakes > 0) { + tls.queue( + c, + tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.no_renegotiation + }) + ); + tls.flush(c); + } + c.process(); + }; + tls.parseHelloMessage = function (c, record, length) { + var msg = null; + var client = c.entity === tls.ConnectionEnd.client; + if (length < 38) { + c.error(c, { + message: client ? 'Invalid ServerHello message. Message too short.' : 'Invalid ClientHello message. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } else { + var b3 = record.fragment; + var remaining = b3.length(); + msg = { + version: { + major: b3.getByte(), + minor: b3.getByte() + }, + random: forge.util.createBuffer(b3.getBytes(32)), + session_id: readVector(b3, 1), + extensions: [] + }; + if (client) { + msg.cipher_suite = b3.getBytes(2); + msg.compression_method = b3.getByte(); + } else { + msg.cipher_suites = readVector(b3, 2); + msg.compression_methods = readVector(b3, 1); + } + remaining = length - (remaining - b3.length()); + if (remaining > 0) { + var exts = readVector(b3, 2); + while (exts.length() > 0) { + msg.extensions.push({ + type: [exts.getByte(), exts.getByte()], + data: readVector(exts, 2) + }); + } + if (!client) { + for (var i = 0; i < msg.extensions.length; ++i) { + var ext = msg.extensions[i]; + if (ext.type[0] === 0 && ext.type[1] === 0) { + var snl = readVector(ext.data, 2); + while (snl.length() > 0) { + var snType = snl.getByte(); + if (snType !== 0) { + break; + } + c.session.extensions.server_name.serverNameList.push(readVector(snl, 2).getBytes()); + } + } + } + } + } + if (c.session.version) { + if (msg.version.major !== c.session.version.major || msg.version.minor !== c.session.version.minor) { + return c.error(c, { + message: 'TLS version change is disallowed during renegotiation.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + if (client) { + c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); + } else { + var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); + while (tmp.length() > 0) { + c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); + if (c.session.cipherSuite !== null) { + break; + } + } + } + if (c.session.cipherSuite === null) { + return c.error(c, { + message: 'No cipher suites in common.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + }, + cipherSuite: forge.util.bytesToHex(msg.cipher_suite) + }); + } + if (client) { + c.session.compressionMethod = msg.compression_method; + } else { + c.session.compressionMethod = tls.CompressionMethod.none; + } + } + return msg; + }; + tls.createSecurityParameters = function (c, msg) { + var client = c.entity === tls.ConnectionEnd.client; + var msgRandom = msg.random.bytes(); + var cRandom = client ? c.session.sp.client_random : msgRandom; + var sRandom = client ? msgRandom : tls.createRandom().getBytes(); + c.session.sp = { + entity: c.entity, + prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, + bulk_cipher_algorithm: null, + cipher_type: null, + enc_key_length: null, + block_length: null, + fixed_iv_length: null, + record_iv_length: null, + mac_algorithm: null, + mac_length: null, + mac_key_length: null, + compression_algorithm: c.session.compressionMethod, + pre_master_secret: null, + master_secret: null, + client_random: cRandom, + server_random: sRandom + }; + }; + tls.handleServerHello = function (c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if (c.fail) { + return; + } + if (msg.version.minor <= c.version.minor) { + c.version.minor = msg.version.minor; + } else { + return c.error(c, { + message: 'Incompatible TLS version.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + c.session.version = c.version; + var sessionId = msg.session_id.bytes(); + if (sessionId.length > 0 && sessionId === c.session.id) { + c.expect = SCC; + c.session.resuming = true; + c.session.sp.server_random = msg.random.bytes(); + } else { + c.expect = SCE; + c.session.resuming = false; + tls.createSecurityParameters(c, msg); + } + c.session.id = sessionId; + c.process(); + }; + tls.handleClientHello = function (c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if (c.fail) { + return; + } + var sessionId = msg.session_id.bytes(); + var session = null; + if (c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + if (session === null) { + sessionId = ''; + } else if (session.version.major !== msg.version.major || session.version.minor > msg.version.minor) { + session = null; + sessionId = ''; + } + } + if (sessionId.length === 0) { + sessionId = forge.random.getBytes(32); + } + c.session.id = sessionId; + c.session.clientHelloVersion = msg.version; + c.session.sp = {}; + if (session) { + c.version = c.session.version = session.version; + c.session.sp = session.sp; + } else { + var version; + for (var i = 1; i < tls.SupportedVersions.length; ++i) { + version = tls.SupportedVersions[i]; + if (version.minor <= msg.version.minor) { + break; + } + } + c.version = {major: version.major, minor: version.minor}; + c.session.version = c.version; + } + if (session !== null) { + c.expect = CCC; + c.session.resuming = true; + c.session.sp.client_random = msg.random.bytes(); + } else { + c.expect = c.verifyClient !== false ? CCE : CKE; + c.session.resuming = false; + tls.createSecurityParameters(c, msg); + } + c.open = true; + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHello(c) + }) + ); + if (c.session.resuming) { + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + }) + ); + c.state.pending = tls.createConnectionState(c); + c.state.current.write = c.state.pending.write; + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + }) + ); + } else { + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + }) + ); + if (!c.fail) { + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerKeyExchange(c) + }) + ); + if (c.verifyClient !== false) { + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificateRequest(c) + }) + ); + } + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHelloDone(c) + }) + ); + } + } + tls.flush(c); + c.process(); + }; + tls.handleCertificate = function (c, record, length) { + if (length < 3) { + return c.error(c, { + message: 'Invalid Certificate message. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var b3 = record.fragment; + var msg = { + certificate_list: readVector(b3, 3) + }; + var cert, asn1; + var certs = []; + try { + while (msg.certificate_list.length() > 0) { + cert = readVector(msg.certificate_list, 3); + asn1 = forge.asn1.fromDer(cert); + cert = forge.pki.certificateFromAsn1(asn1, true); + certs.push(cert); + } + } catch (ex) { + return c.error(c, { + message: 'Could not parse certificate list.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } + }); + } + var client = c.entity === tls.ConnectionEnd.client; + if ((client || c.verifyClient === true) && certs.length === 0) { + c.error(c, { + message: client ? 'No server certificate provided.' : 'No client certificate provided.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } else if (certs.length === 0) { + c.expect = client ? SKE : CKE; + } else { + if (client) { + c.session.serverCertificate = certs[0]; + } else { + c.session.clientCertificate = certs[0]; + } + if (tls.verifyCertificateChain(c, certs)) { + c.expect = client ? SKE : CKE; + } + } + c.process(); + }; + tls.handleServerKeyExchange = function (c, record, length) { + if (length > 0) { + return c.error(c, { + message: 'Invalid key parameters. Only RSA is supported.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } + c.expect = SCR; + c.process(); + }; + tls.handleClientKeyExchange = function (c, record, length) { + if (length < 48) { + return c.error(c, { + message: 'Invalid key parameters. Only RSA is supported.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } + var b3 = record.fragment; + var msg = { + enc_pre_master_secret: readVector(b3, 2).getBytes() + }; + var privateKey = null; + if (c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.serverCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch (ex) { + c.error(c, { + message: 'Could not get private key.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + } + if (privateKey === null) { + return c.error(c, { + message: 'No private key set.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + try { + var sp = c.session.sp; + sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); + var version = c.session.clientHelloVersion; + if (version.major !== sp.pre_master_secret.charCodeAt(0) || version.minor !== sp.pre_master_secret.charCodeAt(1)) { + throw new Error('TLS version rollback attack detected.'); + } + } catch (ex) { + sp.pre_master_secret = forge.random.getBytes(48); + } + c.expect = CCC; + if (c.session.clientCertificate !== null) { + c.expect = CCV; + } + c.process(); + }; + tls.handleCertificateRequest = function (c, record, length) { + if (length < 3) { + return c.error(c, { + message: 'Invalid CertificateRequest. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var b3 = record.fragment; + var msg = { + certificate_types: readVector(b3, 1), + certificate_authorities: readVector(b3, 2) + }; + c.session.certificateRequest = msg; + c.expect = SHD; + c.process(); + }; + tls.handleCertificateVerify = function (c, record, length) { + if (length < 2) { + return c.error(c, { + message: 'Invalid CertificateVerify. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var b3 = record.fragment; + b3.read -= 4; + var msgBytes = b3.bytes(); + b3.read += 4; + var msg = { + signature: readVector(b3, 2).getBytes() + }; + var verify = forge.util.createBuffer(); + verify.putBuffer(c.session.md5.digest()); + verify.putBuffer(c.session.sha1.digest()); + verify = verify.getBytes(); + try { + var cert = c.session.clientCertificate; + if (!cert.publicKey.verify(verify, msg.signature, 'NONE')) { + throw new Error('CertificateVerify signature does not match.'); + } + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + } catch (ex) { + return c.error(c, { + message: 'Bad signature in CertificateVerify.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + } + }); + } + c.expect = CCC; + c.process(); + }; + tls.handleServerHelloDone = function (c, record, length) { + if (length > 0) { + return c.error(c, { + message: 'Invalid ServerHelloDone message. Invalid length.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.record_overflow + } + }); + } + if (c.serverCertificate === null) { + var error = { + message: 'No server certificate provided. Not enough security.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.insufficient_security + } + }; + var depth = 0; + var ret = c.verify(c, error.alert.description, depth, []); + if (ret !== true) { + if (ret || ret === 0) { + if (typeof ret === 'object' && !forge.util.isArray(ret)) { + if (ret.message) { + error.message = ret.message; + } + if (ret.alert) { + error.alert.description = ret.alert; + } + } else if (typeof ret === 'number') { + error.alert.description = ret; + } + } + return c.error(c, error); + } + } + if (c.session.certificateRequest !== null) { + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + }); + tls.queue(c, record); + } + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientKeyExchange(c) + }); + tls.queue(c, record); + c.expect = SER; + var callback = function (c2, signature) { + if (c2.session.certificateRequest !== null && c2.session.clientCertificate !== null) { + tls.queue( + c2, + tls.createRecord(c2, { + type: tls.ContentType.handshake, + data: tls.createCertificateVerify(c2, signature) + }) + ); + } + tls.queue( + c2, + tls.createRecord(c2, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + }) + ); + c2.state.pending = tls.createConnectionState(c2); + c2.state.current.write = c2.state.pending.write; + tls.queue( + c2, + tls.createRecord(c2, { + type: tls.ContentType.handshake, + data: tls.createFinished(c2) + }) + ); + c2.expect = SCC; + tls.flush(c2); + c2.process(); + }; + if (c.session.certificateRequest === null || c.session.clientCertificate === null) { + return callback(c, null); + } + tls.getClientSignature(c, callback); + }; + tls.handleChangeCipherSpec = function (c, record) { + if (record.fragment.getByte() !== 1) { + return c.error(c, { + message: 'Invalid ChangeCipherSpec message received.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var client = c.entity === tls.ConnectionEnd.client; + if ((c.session.resuming && client) || (!c.session.resuming && !client)) { + c.state.pending = tls.createConnectionState(c); + } + c.state.current.read = c.state.pending.read; + if ((!c.session.resuming && client) || (c.session.resuming && !client)) { + c.state.pending = null; + } + c.expect = client ? SFI : CFI; + c.process(); + }; + tls.handleFinished = function (c, record, length) { + var b3 = record.fragment; + b3.read -= 4; + var msgBytes = b3.bytes(); + b3.read += 4; + var vd = record.fragment.getBytes(); + b3 = forge.util.createBuffer(); + b3.putBuffer(c.session.md5.digest()); + b3.putBuffer(c.session.sha1.digest()); + var client = c.entity === tls.ConnectionEnd.client; + var label = client ? 'server finished' : 'client finished'; + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + b3 = prf(sp.master_secret, label, b3.getBytes(), vdl); + if (b3.getBytes() !== vd) { + return c.error(c, { + message: 'Invalid verify_data in Finished message.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decrypt_error + } + }); + } + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + if ((c.session.resuming && client) || (!c.session.resuming && !client)) { + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + }) + ); + c.state.current.write = c.state.pending.write; + c.state.pending = null; + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + }) + ); + } + c.expect = client ? SAD : CAD; + c.handshaking = false; + ++c.handshakes; + c.peerCertificate = client ? c.session.serverCertificate : c.session.clientCertificate; + tls.flush(c); + c.isConnected = true; + c.connected(c); + c.process(); + }; + tls.handleAlert = function (c, record) { + var b3 = record.fragment; + var alert = { + level: b3.getByte(), + description: b3.getByte() + }; + var msg; + switch (alert.description) { + case tls.Alert.Description.close_notify: + msg = 'Connection closed.'; + break; + case tls.Alert.Description.unexpected_message: + msg = 'Unexpected message.'; + break; + case tls.Alert.Description.bad_record_mac: + msg = 'Bad record MAC.'; + break; + case tls.Alert.Description.decryption_failed: + msg = 'Decryption failed.'; + break; + case tls.Alert.Description.record_overflow: + msg = 'Record overflow.'; + break; + case tls.Alert.Description.decompression_failure: + msg = 'Decompression failed.'; + break; + case tls.Alert.Description.handshake_failure: + msg = 'Handshake failure.'; + break; + case tls.Alert.Description.bad_certificate: + msg = 'Bad certificate.'; + break; + case tls.Alert.Description.unsupported_certificate: + msg = 'Unsupported certificate.'; + break; + case tls.Alert.Description.certificate_revoked: + msg = 'Certificate revoked.'; + break; + case tls.Alert.Description.certificate_expired: + msg = 'Certificate expired.'; + break; + case tls.Alert.Description.certificate_unknown: + msg = 'Certificate unknown.'; + break; + case tls.Alert.Description.illegal_parameter: + msg = 'Illegal parameter.'; + break; + case tls.Alert.Description.unknown_ca: + msg = 'Unknown certificate authority.'; + break; + case tls.Alert.Description.access_denied: + msg = 'Access denied.'; + break; + case tls.Alert.Description.decode_error: + msg = 'Decode error.'; + break; + case tls.Alert.Description.decrypt_error: + msg = 'Decrypt error.'; + break; + case tls.Alert.Description.export_restriction: + msg = 'Export restriction.'; + break; + case tls.Alert.Description.protocol_version: + msg = 'Unsupported protocol version.'; + break; + case tls.Alert.Description.insufficient_security: + msg = 'Insufficient security.'; + break; + case tls.Alert.Description.internal_error: + msg = 'Internal error.'; + break; + case tls.Alert.Description.user_canceled: + msg = 'User canceled.'; + break; + case tls.Alert.Description.no_renegotiation: + msg = 'Renegotiation not supported.'; + break; + default: + msg = 'Unknown error.'; + break; + } + if (alert.description === tls.Alert.Description.close_notify) { + return c.close(); + } + c.error(c, { + message: msg, + send: false, + origin: c.entity === tls.ConnectionEnd.client ? 'server' : 'client', + alert + }); + c.process(); + }; + tls.handleHandshake = function (c, record) { + var b3 = record.fragment; + var type = b3.getByte(); + var length = b3.getInt24(); + if (length > b3.length()) { + c.fragmented = record; + record.fragment = forge.util.createBuffer(); + b3.read -= 4; + return c.process(); + } + c.fragmented = null; + b3.read -= 4; + var bytes = b3.bytes(length + 4); + b3.read += 4; + if (type in hsTable[c.entity][c.expect]) { + if (c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { + c.handshaking = true; + c.session = { + version: null, + extensions: { + server_name: { + serverNameList: [] + } + }, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + clientCertificate: null, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; + } + if (type !== tls.HandshakeType.hello_request && type !== tls.HandshakeType.certificate_verify && type !== tls.HandshakeType.finished) { + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + } + hsTable[c.entity][c.expect][type](c, record, length); + } else { + tls.handleUnexpected(c, record); + } + }; + tls.handleApplicationData = function (c, record) { + c.data.putBuffer(record.fragment); + c.dataReady(c); + c.process(); + }; + tls.handleHeartbeat = function (c, record) { + var b3 = record.fragment; + var type = b3.getByte(); + var length = b3.getInt16(); + var payload = b3.getBytes(length); + if (type === tls.HeartbeatMessageType.heartbeat_request) { + if (c.handshaking || length > payload.length) { + return c.process(); + } + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat(tls.HeartbeatMessageType.heartbeat_response, payload) + }) + ); + tls.flush(c); + } else if (type === tls.HeartbeatMessageType.heartbeat_response) { + if (payload !== c.expectedHeartbeatPayload) { + return c.process(); + } + if (c.heartbeatReceived) { + c.heartbeatReceived(c, forge.util.createBuffer(payload)); + } + } + c.process(); + }; + var SHE = 0; + var SCE = 1; + var SKE = 2; + var SCR = 3; + var SHD = 4; + var SCC = 5; + var SFI = 6; + var SAD = 7; + var SER = 8; + var CHE = 0; + var CCE = 1; + var CKE = 2; + var CCV = 3; + var CCC = 4; + var CFI = 5; + var CAD = 6; + var __ = tls.handleUnexpected; + var R02 = tls.handleChangeCipherSpec; + var R1 = tls.handleAlert; + var R2 = tls.handleHandshake; + var R3 = tls.handleApplicationData; + var R4 = tls.handleHeartbeat; + var ctTable = []; + ctTable[tls.ConnectionEnd.client] = [ + [__, R1, R2, __, R4], + [__, R1, R2, __, R4], + [__, R1, R2, __, R4], + [__, R1, R2, __, R4], + [__, R1, R2, __, R4], + [R02, R1, __, __, R4], + [__, R1, R2, __, R4], + [__, R1, R2, R3, R4], + [__, R1, R2, __, R4] + ]; + ctTable[tls.ConnectionEnd.server] = [ + [__, R1, R2, __, R4], + [__, R1, R2, __, R4], + [__, R1, R2, __, R4], + [__, R1, R2, __, R4], + [R02, R1, __, __, R4], + [__, R1, R2, __, R4], + [__, R1, R2, R3, R4], + [__, R1, R2, __, R4] + ]; + var H0 = tls.handleHelloRequest; + var H1 = tls.handleServerHello; + var H2 = tls.handleCertificate; + var H3 = tls.handleServerKeyExchange; + var H4 = tls.handleCertificateRequest; + var H5 = tls.handleServerHelloDone; + var H6 = tls.handleFinished; + var hsTable = []; + hsTable[tls.ConnectionEnd.client] = [ + [__, __, H1, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + [H0, __, __, __, __, __, __, __, __, __, __, H2, H3, H4, H5, __, __, __, __, __, __], + [H0, __, __, __, __, __, __, __, __, __, __, __, H3, H4, H5, __, __, __, __, __, __], + [H0, __, __, __, __, __, __, __, __, __, __, __, __, H4, H5, __, __, __, __, __, __], + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, H5, __, __, __, __, __, __], + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] + ]; + var H7 = tls.handleClientHello; + var H8 = tls.handleClientKeyExchange; + var H9 = tls.handleCertificateVerify; + hsTable[tls.ConnectionEnd.server] = [ + [__, H7, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + [__, __, __, __, __, __, __, __, __, __, __, H2, __, __, __, __, __, __, __, __, __], + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H8, __, __, __, __], + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H9, __, __, __, __, __], + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] + ]; + tls.generateKeys = function (c, sp) { + var prf = prf_TLS1; + var random = sp.client_random + sp.server_random; + if (!c.session.resuming) { + sp.master_secret = prf(sp.pre_master_secret, 'master secret', random, 48).bytes(); + sp.pre_master_secret = null; + } + random = sp.server_random + sp.client_random; + var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; + var tls10 = c.version.major === tls.Versions.TLS_1_0.major && c.version.minor === tls.Versions.TLS_1_0.minor; + if (tls10) { + length += 2 * sp.fixed_iv_length; + } + var km = prf(sp.master_secret, 'key expansion', random, length); + var rval = { + client_write_MAC_key: km.getBytes(sp.mac_key_length), + server_write_MAC_key: km.getBytes(sp.mac_key_length), + client_write_key: km.getBytes(sp.enc_key_length), + server_write_key: km.getBytes(sp.enc_key_length) + }; + if (tls10) { + rval.client_write_IV = km.getBytes(sp.fixed_iv_length); + rval.server_write_IV = km.getBytes(sp.fixed_iv_length); + } + return rval; + }; + tls.createConnectionState = function (c) { + var client = c.entity === tls.ConnectionEnd.client; + var createMode = function () { + var mode = { + sequenceNumber: [0, 0], + macKey: null, + macLength: 0, + macFunction: null, + cipherState: null, + cipherFunction: function (record) { + return true; + }, + compressionState: null, + compressFunction: function (record) { + return true; + }, + updateSequenceNumber: function () { + if (mode.sequenceNumber[1] === 4294967295) { + mode.sequenceNumber[1] = 0; + ++mode.sequenceNumber[0]; + } else { + ++mode.sequenceNumber[1]; + } + } + }; + return mode; + }; + var state = { + read: createMode(), + write: createMode() + }; + state.read.update = function (c2, record) { + if (!state.read.cipherFunction(record, state.read)) { + c2.error(c2, { + message: 'Could not decrypt record or bad MAC.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_record_mac + } + }); + } else if (!state.read.compressFunction(c2, record, state.read)) { + c2.error(c2, { + message: 'Could not decompress record.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decompression_failure + } + }); + } + return !c2.fail; + }; + state.write.update = function (c2, record) { + if (!state.write.compressFunction(c2, record, state.write)) { + c2.error(c2, { + message: 'Could not compress record.', + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } else if (!state.write.cipherFunction(record, state.write)) { + c2.error(c2, { + message: 'Could not encrypt record.', + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + return !c2.fail; + }; + if (c.session) { + var sp = c.session.sp; + c.session.cipherSuite.initSecurityParameters(sp); + sp.keys = tls.generateKeys(c, sp); + state.read.macKey = client ? sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; + state.write.macKey = client ? sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; + c.session.cipherSuite.initConnectionState(state, c, sp); + switch (sp.compression_algorithm) { + case tls.CompressionMethod.none: + break; + case tls.CompressionMethod.deflate: + state.read.compressFunction = inflate; + state.write.compressFunction = deflate; + break; + default: + throw new Error('Unsupported compression algorithm.'); + } + } + return state; + }; + tls.createRandom = function () { + var d = new Date(); + var utc = +d + d.getTimezoneOffset() * 60000; + var rval = forge.util.createBuffer(); + rval.putInt32(utc); + rval.putBytes(forge.random.getBytes(28)); + return rval; + }; + tls.createRecord = function (c, options) { + if (!options.data) { + return null; + } + var record = { + type: options.type, + version: { + major: c.version.major, + minor: c.version.minor + }, + length: options.data.length(), + fragment: options.data + }; + return record; + }; + tls.createAlert = function (c, alert) { + var b3 = forge.util.createBuffer(); + b3.putByte(alert.level); + b3.putByte(alert.description); + return tls.createRecord(c, { + type: tls.ContentType.alert, + data: b3 + }); + }; + tls.createClientHello = function (c) { + c.session.clientHelloVersion = { + major: c.version.major, + minor: c.version.minor + }; + var cipherSuites = forge.util.createBuffer(); + for (var i = 0; i < c.cipherSuites.length; ++i) { + var cs = c.cipherSuites[i]; + cipherSuites.putByte(cs.id[0]); + cipherSuites.putByte(cs.id[1]); + } + var cSuites = cipherSuites.length(); + var compressionMethods = forge.util.createBuffer(); + compressionMethods.putByte(tls.CompressionMethod.none); + var cMethods = compressionMethods.length(); + var extensions = forge.util.createBuffer(); + if (c.virtualHost) { + var ext = forge.util.createBuffer(); + ext.putByte(0); + ext.putByte(0); + var serverName = forge.util.createBuffer(); + serverName.putByte(0); + writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost)); + var snList = forge.util.createBuffer(); + writeVector(snList, 2, serverName); + writeVector(ext, 2, snList); + extensions.putBuffer(ext); + } + var extLength = extensions.length(); + if (extLength > 0) { + extLength += 2; + } + var sessionId = c.session.id; + var length = sessionId.length + 1 + 2 + 4 + 28 + 2 + cSuites + 1 + cMethods + extLength; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_hello); + rval.putInt24(length); + rval.putByte(c.version.major); + rval.putByte(c.version.minor); + rval.putBytes(c.session.sp.client_random); + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + writeVector(rval, 2, cipherSuites); + writeVector(rval, 1, compressionMethods); + if (extLength > 0) { + writeVector(rval, 2, extensions); + } + return rval; + }; + tls.createServerHello = function (c) { + var sessionId = c.session.id; + var length = sessionId.length + 1 + 2 + 4 + 28 + 2 + 1; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello); + rval.putInt24(length); + rval.putByte(c.version.major); + rval.putByte(c.version.minor); + rval.putBytes(c.session.sp.server_random); + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + rval.putByte(c.session.cipherSuite.id[0]); + rval.putByte(c.session.cipherSuite.id[1]); + rval.putByte(c.session.compressionMethod); + return rval; + }; + tls.createCertificate = function (c) { + var client = c.entity === tls.ConnectionEnd.client; + var cert = null; + if (c.getCertificate) { + var hint; + if (client) { + hint = c.session.certificateRequest; + } else { + hint = c.session.extensions.server_name.serverNameList; + } + cert = c.getCertificate(c, hint); + } + var certList = forge.util.createBuffer(); + if (cert !== null) { + try { + if (!forge.util.isArray(cert)) { + cert = [cert]; + } + var asn1 = null; + for (var i = 0; i < cert.length; ++i) { + var msg = forge.pem.decode(cert[i])[0]; + if (msg.type !== 'CERTIFICATE' && msg.type !== 'X509 CERTIFICATE' && msg.type !== 'TRUSTED CERTIFICATE') { + var error = new Error('Could not convert certificate from PEM; PEM ' + 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' + '"TRUSTED CERTIFICATE".'); + error.headerType = msg.type; + throw error; + } + if (msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certificate from PEM; PEM is encrypted.'); + } + var der = forge.util.createBuffer(msg.body); + if (asn1 === null) { + asn1 = forge.asn1.fromDer(der.bytes(), false); + } + var certBuffer = forge.util.createBuffer(); + writeVector(certBuffer, 3, der); + certList.putBuffer(certBuffer); + } + cert = forge.pki.certificateFromAsn1(asn1); + if (client) { + c.session.clientCertificate = cert; + } else { + c.session.serverCertificate = cert; + } + } catch (ex) { + return c.error(c, { + message: 'Could not send certificate list.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } + }); + } + } + var length = 3 + certList.length(); + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate); + rval.putInt24(length); + writeVector(rval, 3, certList); + return rval; + }; + tls.createClientKeyExchange = function (c) { + var b3 = forge.util.createBuffer(); + b3.putByte(c.session.clientHelloVersion.major); + b3.putByte(c.session.clientHelloVersion.minor); + b3.putBytes(forge.random.getBytes(46)); + var sp = c.session.sp; + sp.pre_master_secret = b3.getBytes(); + var key2 = c.session.serverCertificate.publicKey; + b3 = key2.encrypt(sp.pre_master_secret); + var length = b3.length + 2; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_key_exchange); + rval.putInt24(length); + rval.putInt16(b3.length); + rval.putBytes(b3); + return rval; + }; + tls.createServerKeyExchange = function (c) { + var length = 0; + var rval = forge.util.createBuffer(); + if (length > 0) { + rval.putByte(tls.HandshakeType.server_key_exchange); + rval.putInt24(length); + } + return rval; + }; + tls.getClientSignature = function (c, callback) { + var b3 = forge.util.createBuffer(); + b3.putBuffer(c.session.md5.digest()); + b3.putBuffer(c.session.sha1.digest()); + b3 = b3.getBytes(); + c.getSignature = + c.getSignature || + function (c2, b4, callback2) { + var privateKey = null; + if (c2.getPrivateKey) { + try { + privateKey = c2.getPrivateKey(c2, c2.session.clientCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch (ex) { + c2.error(c2, { + message: 'Could not get private key.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + } + if (privateKey === null) { + c2.error(c2, { + message: 'No private key set.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } else { + b4 = privateKey.sign(b4, null); + } + callback2(c2, b4); + }; + c.getSignature(c, b3, callback); + }; + tls.createCertificateVerify = function (c, signature) { + var length = signature.length + 2; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_verify); + rval.putInt24(length); + rval.putInt16(signature.length); + rval.putBytes(signature); + return rval; + }; + tls.createCertificateRequest = function (c) { + var certTypes = forge.util.createBuffer(); + certTypes.putByte(1); + var cAs = forge.util.createBuffer(); + for (var key2 in c.caStore.certs) { + var cert = c.caStore.certs[key2]; + var dn = forge.pki.distinguishedNameToAsn1(cert.subject); + var byteBuffer = forge.asn1.toDer(dn); + cAs.putInt16(byteBuffer.length()); + cAs.putBuffer(byteBuffer); + } + var length = 1 + certTypes.length() + 2 + cAs.length(); + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_request); + rval.putInt24(length); + writeVector(rval, 1, certTypes); + writeVector(rval, 2, cAs); + return rval; + }; + tls.createServerHelloDone = function (c) { + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello_done); + rval.putInt24(0); + return rval; + }; + tls.createChangeCipherSpec = function () { + var rval = forge.util.createBuffer(); + rval.putByte(1); + return rval; + }; + tls.createFinished = function (c) { + var b3 = forge.util.createBuffer(); + b3.putBuffer(c.session.md5.digest()); + b3.putBuffer(c.session.sha1.digest()); + var client = c.entity === tls.ConnectionEnd.client; + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + var label = client ? 'client finished' : 'server finished'; + b3 = prf(sp.master_secret, label, b3.getBytes(), vdl); + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.finished); + rval.putInt24(b3.length()); + rval.putBuffer(b3); + return rval; + }; + tls.createHeartbeat = function (type, payload, payloadLength) { + if (typeof payloadLength === 'undefined') { + payloadLength = payload.length; + } + var rval = forge.util.createBuffer(); + rval.putByte(type); + rval.putInt16(payloadLength); + rval.putBytes(payload); + var plaintextLength = rval.length(); + var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); + rval.putBytes(forge.random.getBytes(paddingLength)); + return rval; + }; + tls.queue = function (c, record) { + if (!record) { + return; + } + if (record.fragment.length() === 0) { + if (record.type === tls.ContentType.handshake || record.type === tls.ContentType.alert || record.type === tls.ContentType.change_cipher_spec) { + return; + } + } + if (record.type === tls.ContentType.handshake) { + var bytes = record.fragment.bytes(); + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + bytes = null; + } + var records; + if (record.fragment.length() <= tls.MaxFragment) { + records = [record]; + } else { + records = []; + var data = record.fragment.bytes(); + while (data.length > tls.MaxFragment) { + records.push( + tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data.slice(0, tls.MaxFragment)) + }) + ); + data = data.slice(tls.MaxFragment); + } + if (data.length > 0) { + records.push( + tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data) + }) + ); + } + } + for (var i = 0; i < records.length && !c.fail; ++i) { + var rec = records[i]; + var s = c.state.current.write; + if (s.update(c, rec)) { + c.records.push(rec); + } + } + }; + tls.flush = function (c) { + for (var i = 0; i < c.records.length; ++i) { + var record = c.records[i]; + c.tlsData.putByte(record.type); + c.tlsData.putByte(record.version.major); + c.tlsData.putByte(record.version.minor); + c.tlsData.putInt16(record.fragment.length()); + c.tlsData.putBuffer(c.records[i].fragment); + } + c.records = []; + return c.tlsDataReady(c); + }; + var _certErrorToAlertDesc = function (error) { + switch (error) { + case true: + return true; + case forge.pki.certificateError.bad_certificate: + return tls.Alert.Description.bad_certificate; + case forge.pki.certificateError.unsupported_certificate: + return tls.Alert.Description.unsupported_certificate; + case forge.pki.certificateError.certificate_revoked: + return tls.Alert.Description.certificate_revoked; + case forge.pki.certificateError.certificate_expired: + return tls.Alert.Description.certificate_expired; + case forge.pki.certificateError.certificate_unknown: + return tls.Alert.Description.certificate_unknown; + case forge.pki.certificateError.unknown_ca: + return tls.Alert.Description.unknown_ca; + default: + return tls.Alert.Description.bad_certificate; + } + }; + var _alertDescToCertError = function (desc) { + switch (desc) { + case true: + return true; + case tls.Alert.Description.bad_certificate: + return forge.pki.certificateError.bad_certificate; + case tls.Alert.Description.unsupported_certificate: + return forge.pki.certificateError.unsupported_certificate; + case tls.Alert.Description.certificate_revoked: + return forge.pki.certificateError.certificate_revoked; + case tls.Alert.Description.certificate_expired: + return forge.pki.certificateError.certificate_expired; + case tls.Alert.Description.certificate_unknown: + return forge.pki.certificateError.certificate_unknown; + case tls.Alert.Description.unknown_ca: + return forge.pki.certificateError.unknown_ca; + default: + return forge.pki.certificateError.bad_certificate; + } + }; + tls.verifyCertificateChain = function (c, chain2) { + try { + var options = {}; + for (var key2 in c.verifyOptions) { + options[key2] = c.verifyOptions[key2]; + } + options.verify = function (vfd, depth, chain3) { + var desc = _certErrorToAlertDesc(vfd); + var ret = c.verify(c, vfd, depth, chain3); + if (ret !== true) { + if (typeof ret === 'object' && !forge.util.isArray(ret)) { + var error = new Error('The application rejected the certificate.'); + error.send = true; + error.alert = { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + }; + if (ret.message) { + error.message = ret.message; + } + if (ret.alert) { + error.alert.description = ret.alert; + } + throw error; + } + if (ret !== vfd) { + ret = _alertDescToCertError(ret); + } + } + return ret; + }; + forge.pki.verifyCertificateChain(c.caStore, chain2, options); + } catch (ex) { + var err = ex; + if (typeof err !== 'object' || forge.util.isArray(err)) { + err = { + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(ex) + } + }; + } + if (!('send' in err)) { + err.send = true; + } + if (!('alert' in err)) { + err.alert = { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(err.error) + }; + } + c.error(c, err); + } + return !c.fail; + }; + tls.createSessionCache = function (cache, capacity) { + var rval = null; + if (cache && cache.getSession && cache.setSession && cache.order) { + rval = cache; + } else { + rval = {}; + rval.cache = cache || {}; + rval.capacity = Math.max(capacity || 100, 1); + rval.order = []; + for (var key2 in cache) { + if (rval.order.length <= capacity) { + rval.order.push(key2); + } else { + delete cache[key2]; + } + } + rval.getSession = function (sessionId) { + var session = null; + var key3 = null; + if (sessionId) { + key3 = forge.util.bytesToHex(sessionId); + } else if (rval.order.length > 0) { + key3 = rval.order[0]; + } + if (key3 !== null && key3 in rval.cache) { + session = rval.cache[key3]; + delete rval.cache[key3]; + for (var i in rval.order) { + if (rval.order[i] === key3) { + rval.order.splice(i, 1); + break; + } + } + } + return session; + }; + rval.setSession = function (sessionId, session) { + if (rval.order.length === rval.capacity) { + var key3 = rval.order.shift(); + delete rval.cache[key3]; + } + var key3 = forge.util.bytesToHex(sessionId); + rval.order.push(key3); + rval.cache[key3] = session; + }; + } + return rval; + }; + tls.createConnection = function (options) { + var caStore = null; + if (options.caStore) { + if (forge.util.isArray(options.caStore)) { + caStore = forge.pki.createCaStore(options.caStore); + } else { + caStore = options.caStore; + } + } else { + caStore = forge.pki.createCaStore(); + } + var cipherSuites = options.cipherSuites || null; + if (cipherSuites === null) { + cipherSuites = []; + for (var key2 in tls.CipherSuites) { + cipherSuites.push(tls.CipherSuites[key2]); + } + } + var entity = options.server ? tls.ConnectionEnd.server : tls.ConnectionEnd.client; + var sessionCache = options.sessionCache ? tls.createSessionCache(options.sessionCache) : null; + var c = { + version: {major: tls.Version.major, minor: tls.Version.minor}, + entity, + sessionId: options.sessionId, + caStore, + sessionCache, + cipherSuites, + connected: options.connected, + virtualHost: options.virtualHost || null, + verifyClient: options.verifyClient || false, + verify: + options.verify || + function (cn, vfd, dpth, cts) { + return vfd; + }, + verifyOptions: options.verifyOptions || {}, + getCertificate: options.getCertificate || null, + getPrivateKey: options.getPrivateKey || null, + getSignature: options.getSignature || null, + input: forge.util.createBuffer(), + tlsData: forge.util.createBuffer(), + data: forge.util.createBuffer(), + tlsDataReady: options.tlsDataReady, + dataReady: options.dataReady, + heartbeatReceived: options.heartbeatReceived, + closed: options.closed, + error: function (c2, ex) { + ex.origin = ex.origin || (c2.entity === tls.ConnectionEnd.client ? 'client' : 'server'); + if (ex.send) { + tls.queue(c2, tls.createAlert(c2, ex.alert)); + tls.flush(c2); + } + var fatal = ex.fatal !== false; + if (fatal) { + c2.fail = true; + } + options.error(c2, ex); + if (fatal) { + c2.close(false); + } + }, + deflate: options.deflate || null, + inflate: options.inflate || null + }; + c.reset = function (clearFail) { + c.version = {major: tls.Version.major, minor: tls.Version.minor}; + c.record = null; + c.session = null; + c.peerCertificate = null; + c.state = { + pending: null, + current: null + }; + c.expect = c.entity === tls.ConnectionEnd.client ? SHE : CHE; + c.fragmented = null; + c.records = []; + c.open = false; + c.handshakes = 0; + c.handshaking = false; + c.isConnected = false; + c.fail = !(clearFail || typeof clearFail === 'undefined'); + c.input.clear(); + c.tlsData.clear(); + c.data.clear(); + c.state.current = tls.createConnectionState(c); + }; + c.reset(); + var _update = function (c2, record) { + var aligned = record.type - tls.ContentType.change_cipher_spec; + var handlers = ctTable[c2.entity][c2.expect]; + if (aligned in handlers) { + handlers[aligned](c2, record); + } else { + tls.handleUnexpected(c2, record); + } + }; + var _readRecordHeader = function (c2) { + var rval = 0; + var b3 = c2.input; + var len = b3.length(); + if (len < 5) { + rval = 5 - len; + } else { + c2.record = { + type: b3.getByte(), + version: { + major: b3.getByte(), + minor: b3.getByte() + }, + length: b3.getInt16(), + fragment: forge.util.createBuffer(), + ready: false + }; + var compatibleVersion = c2.record.version.major === c2.version.major; + if (compatibleVersion && c2.session && c2.session.version) { + compatibleVersion = c2.record.version.minor === c2.version.minor; + } + if (!compatibleVersion) { + c2.error(c2, { + message: 'Incompatible TLS version.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + return rval; + }; + var _readRecord = function (c2) { + var rval = 0; + var b3 = c2.input; + var len = b3.length(); + if (len < c2.record.length) { + rval = c2.record.length - len; + } else { + c2.record.fragment.putBytes(b3.getBytes(c2.record.length)); + b3.compact(); + var s = c2.state.current.read; + if (s.update(c2, c2.record)) { + if (c2.fragmented !== null) { + if (c2.fragmented.type === c2.record.type) { + c2.fragmented.fragment.putBuffer(c2.record.fragment); + c2.record = c2.fragmented; + } else { + c2.error(c2, { + message: 'Invalid fragmented record.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unexpected_message + } + }); + } + } + c2.record.ready = true; + } + } + return rval; + }; + c.handshake = function (sessionId) { + if (c.entity !== tls.ConnectionEnd.client) { + c.error(c, { + message: 'Cannot initiate handshake as a server.', + fatal: false + }); + } else if (c.handshaking) { + c.error(c, { + message: 'Handshake already in progress.', + fatal: false + }); + } else { + if (c.fail && !c.open && c.handshakes === 0) { + c.fail = false; + } + c.handshaking = true; + sessionId = sessionId || ''; + var session = null; + if (sessionId.length > 0) { + if (c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + } + if (session === null) { + sessionId = ''; + } + } + if (sessionId.length === 0 && c.sessionCache) { + session = c.sessionCache.getSession(); + if (session !== null) { + sessionId = session.id; + } + } + c.session = { + id: sessionId, + version: null, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + certificateRequest: null, + clientCertificate: null, + sp: {}, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; + if (session) { + c.version = session.version; + c.session.sp = session.sp; + } + c.session.sp.client_random = tls.createRandom().getBytes(); + c.open = true; + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientHello(c) + }) + ); + tls.flush(c); + } + }; + c.process = function (data) { + var rval = 0; + if (data) { + c.input.putBytes(data); + } + if (!c.fail) { + if (c.record !== null && c.record.ready && c.record.fragment.isEmpty()) { + c.record = null; + } + if (c.record === null) { + rval = _readRecordHeader(c); + } + if (!c.fail && c.record !== null && !c.record.ready) { + rval = _readRecord(c); + } + if (!c.fail && c.record !== null && c.record.ready) { + _update(c, c.record); + } + } + return rval; + }; + c.prepare = function (data) { + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.application_data, + data: forge.util.createBuffer(data) + }) + ); + return tls.flush(c); + }; + c.prepareHeartbeatRequest = function (payload, payloadLength) { + if (payload instanceof forge.util.ByteBuffer) { + payload = payload.bytes(); + } + if (typeof payloadLength === 'undefined') { + payloadLength = payload.length; + } + c.expectedHeartbeatPayload = payload; + tls.queue( + c, + tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat(tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength) + }) + ); + return tls.flush(c); + }; + c.close = function (clearFail) { + if (!c.fail && c.sessionCache && c.session) { + var session = { + id: c.session.id, + version: c.session.version, + sp: c.session.sp + }; + session.sp.keys = null; + c.sessionCache.setSession(session.id, session); + } + if (c.open) { + c.open = false; + c.input.clear(); + if (c.isConnected || c.handshaking) { + c.isConnected = c.handshaking = false; + tls.queue( + c, + tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.close_notify + }) + ); + tls.flush(c); + } + c.closed(c); + } + c.reset(clearFail); + }; + return c; + }; + module.exports = forge.tls = forge.tls || {}; + for (key in tls) { + if (typeof tls[key] !== 'function') { + forge.tls[key] = tls[key]; + } + } + var key; + forge.tls.prf_tls1 = prf_TLS1; + forge.tls.hmac_sha1 = hmac_sha1; + forge.tls.createSessionCache = tls.createSessionCache; + forge.tls.createConnection = tls.createConnection; +}); + +// node_modules/node-forge/lib/aesCipherSuites.js +var require_aesCipherSuites = __commonJS((exports, module) => { + var initConnectionState = function (state, c, sp) { + var client = c.entity === forge.tls.ConnectionEnd.client; + state.read.cipherState = { + init: false, + cipher: forge.cipher.createDecipher('AES-CBC', client ? sp.keys.server_write_key : sp.keys.client_write_key), + iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV + }; + state.write.cipherState = { + init: false, + cipher: forge.cipher.createCipher('AES-CBC', client ? sp.keys.client_write_key : sp.keys.server_write_key), + iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV + }; + state.read.cipherFunction = decrypt_aes_cbc_sha1; + state.write.cipherFunction = encrypt_aes_cbc_sha1; + state.read.macLength = state.write.macLength = sp.mac_length; + state.read.macFunction = state.write.macFunction = tls.hmac_sha1; + }; + var encrypt_aes_cbc_sha1 = function (record, s) { + var rval = false; + var mac = s.macFunction(s.macKey, s.sequenceNumber, record); + record.fragment.putBytes(mac); + s.updateSequenceNumber(); + var iv; + if (record.version.minor === tls.Versions.TLS_1_0.minor) { + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + iv = forge.random.getBytesSync(16); + } + s.cipherState.init = true; + var cipher = s.cipherState.cipher; + cipher.start({iv}); + if (record.version.minor >= tls.Versions.TLS_1_1.minor) { + cipher.output.putBytes(iv); + } + cipher.update(record.fragment); + if (cipher.finish(encrypt_aes_cbc_sha1_padding)) { + record.fragment = cipher.output; + record.length = record.fragment.length(); + rval = true; + } + return rval; + }; + var encrypt_aes_cbc_sha1_padding = function (blockSize, input, decrypt) { + if (!decrypt) { + var padding = blockSize - (input.length() % blockSize); + input.fillWithByte(padding - 1, padding); + } + return true; + }; + var decrypt_aes_cbc_sha1_padding = function (blockSize, output, decrypt) { + var rval = true; + if (decrypt) { + var len = output.length(); + var paddingLength = output.last(); + for (var i = len - 1 - paddingLength; i < len - 1; ++i) { + rval = rval && output.at(i) == paddingLength; + } + if (rval) { + output.truncate(paddingLength + 1); + } + } + return rval; + }; + var decrypt_aes_cbc_sha1 = function (record, s) { + var rval = false; + var iv; + if (record.version.minor === tls.Versions.TLS_1_0.minor) { + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + iv = record.fragment.getBytes(16); + } + s.cipherState.init = true; + var cipher = s.cipherState.cipher; + cipher.start({iv}); + cipher.update(record.fragment); + rval = cipher.finish(decrypt_aes_cbc_sha1_padding); + var macLen = s.macLength; + var mac = forge.random.getBytesSync(macLen); + var len = cipher.output.length(); + if (len >= macLen) { + record.fragment = cipher.output.getBytes(len - macLen); + mac = cipher.output.getBytes(macLen); + } else { + record.fragment = cipher.output.getBytes(); + } + record.fragment = forge.util.createBuffer(record.fragment); + record.length = record.fragment.length(); + var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); + s.updateSequenceNumber(); + rval = compareMacs(s.macKey, mac, mac2) && rval; + return rval; + }; + var compareMacs = function (key, mac1, mac2) { + var hmac = forge.hmac.create(); + hmac.start('SHA1', key); + hmac.update(mac1); + mac1 = hmac.digest().getBytes(); + hmac.start(null, null); + hmac.update(mac2); + mac2 = hmac.digest().getBytes(); + return mac1 === mac2; + }; + var forge = require_forge(); + require_aes(); + require_tls(); + var tls = (module.exports = forge.tls); + tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = { + id: [0, 47], + name: 'TLS_RSA_WITH_AES_128_CBC_SHA', + initSecurityParameters: function (sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 16; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState + }; + tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = { + id: [0, 53], + name: 'TLS_RSA_WITH_AES_256_CBC_SHA', + initSecurityParameters: function (sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 32; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState + }; +}); + +// node_modules/node-forge/lib/sha512.js +var require_sha512 = __commonJS((exports, module) => { + var _init = function () { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 128); + _k = [ + [1116352408, 3609767458], + [1899447441, 602891725], + [3049323471, 3964484399], + [3921009573, 2173295548], + [961987163, 4081628472], + [1508970993, 3053834265], + [2453635748, 2937671579], + [2870763221, 3664609560], + [3624381080, 2734883394], + [310598401, 1164996542], + [607225278, 1323610764], + [1426881987, 3590304994], + [1925078388, 4068182383], + [2162078206, 991336113], + [2614888103, 633803317], + [3248222580, 3479774868], + [3835390401, 2666613458], + [4022224774, 944711139], + [264347078, 2341262773], + [604807628, 2007800933], + [770255983, 1495990901], + [1249150122, 1856431235], + [1555081692, 3175218132], + [1996064986, 2198950837], + [2554220882, 3999719339], + [2821834349, 766784016], + [2952996808, 2566594879], + [3210313671, 3203337956], + [3336571891, 1034457026], + [3584528711, 2466948901], + [113926993, 3758326383], + [338241895, 168717936], + [666307205, 1188179964], + [773529912, 1546045734], + [1294757372, 1522805485], + [1396182291, 2643833823], + [1695183700, 2343527390], + [1986661051, 1014477480], + [2177026350, 1206759142], + [2456956037, 344077627], + [2730485921, 1290863460], + [2820302411, 3158454273], + [3259730800, 3505952657], + [3345764771, 106217008], + [3516065817, 3606008344], + [3600352804, 1432725776], + [4094571909, 1467031594], + [275423344, 851169720], + [430227734, 3100823752], + [506948616, 1363258195], + [659060556, 3750685593], + [883997877, 3785050280], + [958139571, 3318307427], + [1322822218, 3812723403], + [1537002063, 2003034995], + [1747873779, 3602036899], + [1955562222, 1575990012], + [2024104815, 1125592928], + [2227730452, 2716904306], + [2361852424, 442776044], + [2428436474, 593698344], + [2756734187, 3733110249], + [3204031479, 2999351573], + [3329325298, 3815920427], + [3391569614, 3928383900], + [3515267271, 566280711], + [3940187606, 3454069534], + [4118630271, 4000239992], + [116418474, 1914138554], + [174292421, 2731055270], + [289380356, 3203993006], + [460393269, 320620315], + [685471733, 587496836], + [852142971, 1086792851], + [1017036298, 365543100], + [1126000580, 2618297676], + [1288033470, 3409855158], + [1501505948, 4234509866], + [1607167915, 987167468], + [1816402316, 1246189591] + ]; + _states = {}; + _states['SHA-512'] = [ + [1779033703, 4089235720], + [3144134277, 2227873595], + [1013904242, 4271175723], + [2773480762, 1595750129], + [1359893119, 2917565137], + [2600822924, 725511199], + [528734635, 4215389547], + [1541459225, 327033209] + ]; + _states['SHA-384'] = [ + [3418070365, 3238371032], + [1654270250, 914150663], + [2438529370, 812702999], + [355462360, 4144912697], + [1731405415, 4290775857], + [2394180231, 1750603025], + [3675008525, 1694076839], + [1203062813, 3204075428] + ]; + _states['SHA-512/256'] = [ + [573645204, 4230739756], + [2673172387, 3360449730], + [596883563, 1867755857], + [2520282905, 1497426621], + [2519219938, 2827943907], + [3193839141, 1401305490], + [721525244, 746961066], + [246885852, 2177182882] + ]; + _states['SHA-512/224'] = [ + [2352822216, 424955298], + [1944164710, 2312950998], + [502970286, 855612546], + [1738396948, 1479516111], + [258812777, 2077511080], + [2011393907, 79989058], + [1067287976, 1780299464], + [286451373, 2446758561] + ]; + _initialized = true; + }; + var _update = function (s, w, bytes) { + var t1_hi, t1_lo; + var t2_hi, t2_lo; + var s0_hi, s0_lo; + var s1_hi, s1_lo; + var ch_hi, ch_lo; + var maj_hi, maj_lo; + var a_hi, a_lo; + var b_hi, b_lo; + var c_hi, c_lo; + var d_hi, d_lo; + var e_hi, e_lo; + var f_hi, f_lo; + var g_hi, g_lo; + var h_hi, h_lo; + var i, hi, lo, w2, w7, w15, w16; + var len = bytes.length(); + while (len >= 128) { + for (i = 0; i < 16; ++i) { + w[i][0] = bytes.getInt32() >>> 0; + w[i][1] = bytes.getInt32() >>> 0; + } + for (; i < 80; ++i) { + w2 = w[i - 2]; + hi = w2[0]; + lo = w2[1]; + t1_hi = (((hi >>> 19) | (lo << 13)) ^ ((lo >>> 29) | (hi << 3)) ^ (hi >>> 6)) >>> 0; + t1_lo = (((hi << 13) | (lo >>> 19)) ^ ((lo << 3) | (hi >>> 29)) ^ ((hi << 26) | (lo >>> 6))) >>> 0; + w15 = w[i - 15]; + hi = w15[0]; + lo = w15[1]; + t2_hi = (((hi >>> 1) | (lo << 31)) ^ ((hi >>> 8) | (lo << 24)) ^ (hi >>> 7)) >>> 0; + t2_lo = (((hi << 31) | (lo >>> 1)) ^ ((hi << 24) | (lo >>> 8)) ^ ((hi << 25) | (lo >>> 7))) >>> 0; + w7 = w[i - 7]; + w16 = w[i - 16]; + lo = t1_lo + w7[1] + t2_lo + w16[1]; + w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] + ((lo / 4294967296) >>> 0)) >>> 0; + w[i][1] = lo >>> 0; + } + a_hi = s[0][0]; + a_lo = s[0][1]; + b_hi = s[1][0]; + b_lo = s[1][1]; + c_hi = s[2][0]; + c_lo = s[2][1]; + d_hi = s[3][0]; + d_lo = s[3][1]; + e_hi = s[4][0]; + e_lo = s[4][1]; + f_hi = s[5][0]; + f_lo = s[5][1]; + g_hi = s[6][0]; + g_lo = s[6][1]; + h_hi = s[7][0]; + h_lo = s[7][1]; + for (i = 0; i < 80; ++i) { + s1_hi = (((e_hi >>> 14) | (e_lo << 18)) ^ ((e_hi >>> 18) | (e_lo << 14)) ^ ((e_lo >>> 9) | (e_hi << 23))) >>> 0; + s1_lo = (((e_hi << 18) | (e_lo >>> 14)) ^ ((e_hi << 14) | (e_lo >>> 18)) ^ ((e_lo << 23) | (e_hi >>> 9))) >>> 0; + ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0; + ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0; + s0_hi = (((a_hi >>> 28) | (a_lo << 4)) ^ ((a_lo >>> 2) | (a_hi << 30)) ^ ((a_lo >>> 7) | (a_hi << 25))) >>> 0; + s0_lo = (((a_hi << 4) | (a_lo >>> 28)) ^ ((a_lo << 30) | (a_hi >>> 2)) ^ ((a_lo << 25) | (a_hi >>> 7))) >>> 0; + maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0; + maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0; + lo = h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]; + t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + ((lo / 4294967296) >>> 0)) >>> 0; + t1_lo = lo >>> 0; + lo = s0_lo + maj_lo; + t2_hi = (s0_hi + maj_hi + ((lo / 4294967296) >>> 0)) >>> 0; + t2_lo = lo >>> 0; + h_hi = g_hi; + h_lo = g_lo; + g_hi = f_hi; + g_lo = f_lo; + f_hi = e_hi; + f_lo = e_lo; + lo = d_lo + t1_lo; + e_hi = (d_hi + t1_hi + ((lo / 4294967296) >>> 0)) >>> 0; + e_lo = lo >>> 0; + d_hi = c_hi; + d_lo = c_lo; + c_hi = b_hi; + c_lo = b_lo; + b_hi = a_hi; + b_lo = a_lo; + lo = t1_lo + t2_lo; + a_hi = (t1_hi + t2_hi + ((lo / 4294967296) >>> 0)) >>> 0; + a_lo = lo >>> 0; + } + lo = s[0][1] + a_lo; + s[0][0] = (s[0][0] + a_hi + ((lo / 4294967296) >>> 0)) >>> 0; + s[0][1] = lo >>> 0; + lo = s[1][1] + b_lo; + s[1][0] = (s[1][0] + b_hi + ((lo / 4294967296) >>> 0)) >>> 0; + s[1][1] = lo >>> 0; + lo = s[2][1] + c_lo; + s[2][0] = (s[2][0] + c_hi + ((lo / 4294967296) >>> 0)) >>> 0; + s[2][1] = lo >>> 0; + lo = s[3][1] + d_lo; + s[3][0] = (s[3][0] + d_hi + ((lo / 4294967296) >>> 0)) >>> 0; + s[3][1] = lo >>> 0; + lo = s[4][1] + e_lo; + s[4][0] = (s[4][0] + e_hi + ((lo / 4294967296) >>> 0)) >>> 0; + s[4][1] = lo >>> 0; + lo = s[5][1] + f_lo; + s[5][0] = (s[5][0] + f_hi + ((lo / 4294967296) >>> 0)) >>> 0; + s[5][1] = lo >>> 0; + lo = s[6][1] + g_lo; + s[6][0] = (s[6][0] + g_hi + ((lo / 4294967296) >>> 0)) >>> 0; + s[6][1] = lo >>> 0; + lo = s[7][1] + h_lo; + s[7][0] = (s[7][0] + h_hi + ((lo / 4294967296) >>> 0)) >>> 0; + s[7][1] = lo >>> 0; + len -= 128; + } + }; + var forge = require_forge(); + require_md(); + require_util(); + var sha512 = (module.exports = forge.sha512 = forge.sha512 || {}); + forge.md.sha512 = forge.md.algorithms.sha512 = sha512; + var sha384 = (forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}); + sha384.create = function () { + return sha512.create('SHA-384'); + }; + forge.md.sha384 = forge.md.algorithms.sha384 = sha384; + forge.sha512.sha256 = forge.sha512.sha256 || { + create: function () { + return sha512.create('SHA-512/256'); + } + }; + forge.md['sha512/256'] = forge.md.algorithms['sha512/256'] = forge.sha512.sha256; + forge.sha512.sha224 = forge.sha512.sha224 || { + create: function () { + return sha512.create('SHA-512/224'); + } + }; + forge.md['sha512/224'] = forge.md.algorithms['sha512/224'] = forge.sha512.sha224; + sha512.create = function (algorithm) { + if (!_initialized) { + _init(); + } + if (typeof algorithm === 'undefined') { + algorithm = 'SHA-512'; + } + if (!(algorithm in _states)) { + throw new Error('Invalid SHA-512 algorithm: ' + algorithm); + } + var _state = _states[algorithm]; + var _h = null; + var _input = forge.util.createBuffer(); + var _w = new Array(80); + for (var wi = 0; wi < 80; ++wi) { + _w[wi] = new Array(2); + } + var digestLength = 64; + switch (algorithm) { + case 'SHA-384': + digestLength = 48; + break; + case 'SHA-512/256': + digestLength = 32; + break; + case 'SHA-512/224': + digestLength = 28; + break; + } + var md = { + algorithm: algorithm.replace('-', '').toLowerCase(), + blockLength: 128, + digestLength, + messageLength: 0, + fullMessageLength: null, + messageLengthSize: 16 + }; + md.start = function () { + md.messageLength = 0; + md.fullMessageLength = md.messageLength128 = []; + var int32s = md.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _h = new Array(_state.length); + for (var i = 0; i < _state.length; ++i) { + _h[i] = _state[i].slice(0); + } + return md; + }; + md.start(); + md.update = function (msg, encoding) { + if (encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + var len = msg.length; + md.messageLength += len; + len = [(len / 4294967296) >>> 0, len >>> 0]; + for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 4294967296) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = (len[1] / 4294967296) >>> 0; + } + _input.putBytes(msg); + _update(_h, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + return md; + }; + md.digest = function () { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 4294967296) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + var h2 = new Array(_h.length); + for (var i = 0; i < _h.length; ++i) { + h2[i] = _h[i].slice(0); + } + _update(h2, _w, finalBlock); + var rval = forge.util.createBuffer(); + var hlen; + if (algorithm === 'SHA-512') { + hlen = h2.length; + } else if (algorithm === 'SHA-384') { + hlen = h2.length - 2; + } else { + hlen = h2.length - 4; + } + for (var i = 0; i < hlen; ++i) { + rval.putInt32(h2[i][0]); + if (i !== hlen - 1 || algorithm !== 'SHA-512/224') { + rval.putInt32(h2[i][1]); + } + } + return rval; + }; + return md; + }; + var _padding = null; + var _initialized = false; + var _k = null; + var _states = null; +}); + +// node_modules/node-forge/lib/asn1-validator.js +var require_asn1_validator = __commonJS(exports => { + var forge = require_forge(); + require_asn1(); + var asn1 = forge.asn1; + exports.privateKeyValidator = { + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'PrivateKeyInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, + { + name: 'PrivateKeyInfo.privateKeyAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'privateKeyOid' + } + ] + }, + { + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'privateKey' + } + ] + }; + exports.publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [ + { + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + } + ] + }, + { + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + composed: true, + captureBitStringValue: 'ed25519PublicKey' + } + ] + }; +}); + +// node_modules/node-forge/lib/ed25519.js +var require_ed25519 = __commonJS((exports, module) => { + var messageToNativeBuffer = function (options) { + var message = options.message; + if (message instanceof Uint8Array || message instanceof NativeBuffer) { + return message; + } + var encoding = options.encoding; + if (message === undefined) { + if (options.md) { + message = options.md.digest().getBytes(); + encoding = 'binary'; + } else { + throw new TypeError('"options.message" or "options.md" not specified.'); + } + } + if (typeof message === 'string' && !encoding) { + throw new TypeError('"options.encoding" must be "binary" or "utf8".'); + } + if (typeof message === 'string') { + if (typeof Buffer !== 'undefined') { + return Buffer.from(message, encoding); + } + message = new ByteBuffer(message, encoding); + } else if (!(message instanceof ByteBuffer)) { + throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ' + 'ByteBuffer, or a string with "options.encoding" specifying its ' + 'encoding.'); + } + var buffer = new NativeBuffer(message.length()); + for (var i = 0; i < buffer.length; ++i) { + buffer[i] = message.at(i); + } + return buffer; + }; + var sha512 = function (msg, msgLen) { + var md = forge.md.sha512.create(); + var buffer = new ByteBuffer(msg); + md.update(buffer.getBytes(msgLen), 'binary'); + var hash = md.digest().getBytes(); + if (typeof Buffer !== 'undefined') { + return Buffer.from(hash, 'binary'); + } + var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); + for (var i = 0; i < 64; ++i) { + out[i] = hash.charCodeAt(i); + } + return out; + }; + var crypto_sign_keypair = function (pk, sk) { + var p = [gf(), gf(), gf(), gf()]; + var i; + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + scalarbase(p, d); + pack(pk, p); + for (i = 0; i < 32; ++i) { + sk[i + 32] = pk[i]; + } + return 0; + }; + var crypto_sign = function (sm, m2, n, sk) { + var i, + j, + x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + var smlen = n + 64; + for (i = 0; i < n; ++i) { + sm[64 + i] = m2[i]; + } + for (i = 0; i < 32; ++i) { + sm[32 + i] = d[32 + i]; + } + var r = sha512(sm.subarray(32), n + 32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + for (i = 32; i < 64; ++i) { + sm[i] = sk[i]; + } + var h2 = sha512(sm, n + 64); + reduce(h2); + for (i = 32; i < 64; ++i) { + x[i] = 0; + } + for (i = 0; i < 32; ++i) { + x[i] = r[i]; + } + for (i = 0; i < 32; ++i) { + for (j = 0; j < 32; j++) { + x[i + j] += h2[i] * d[j]; + } + } + modL(sm.subarray(32), x); + return smlen; + }; + var crypto_sign_open = function (m2, sm, n, pk) { + var i, mlen; + var t = new NativeBuffer(32); + var p = [gf(), gf(), gf(), gf()], + q2 = [gf(), gf(), gf(), gf()]; + mlen = -1; + if (n < 64) { + return -1; + } + if (unpackneg(q2, pk)) { + return -1; + } + for (i = 0; i < n; ++i) { + m2[i] = sm[i]; + } + for (i = 0; i < 32; ++i) { + m2[i + 32] = pk[i]; + } + var h2 = sha512(m2, n); + reduce(h2); + scalarmult(p, q2, h2); + scalarbase(q2, sm.subarray(32)); + add(p, q2); + pack(t, p); + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; ++i) { + m2[i] = 0; + } + return -1; + } + for (i = 0; i < n; ++i) { + m2[i] = sm[i + 64]; + } + mlen = n; + return mlen; + }; + var modL = function (r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L2[j - (i - 32)]; + carry = (x[j] + 128) >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; ++j) { + x[j] += carry - (x[31] >> 4) * L2[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; ++j) { + x[j] -= carry * L2[j]; + } + for (i = 0; i < 32; ++i) { + x[i + 1] += x[i] >> 8; + r[i] = x[i] & 255; + } + }; + var reduce = function (r) { + var x = new Float64Array(64); + for (var i = 0; i < 64; ++i) { + x[i] = r[i]; + r[i] = 0; + } + modL(r, x); + }; + var add = function (p, q2) { + var a = gf(), + b3 = gf(), + c = gf(), + d = gf(), + e = gf(), + f = gf(), + g = gf(), + h2 = gf(), + t = gf(); + Z(a, p[1], p[0]); + Z(t, q2[1], q2[0]); + M(a, a, t); + A2(b3, p[0], p[1]); + A2(t, q2[0], q2[1]); + M(b3, b3, t); + M(c, p[3], q2[3]); + M(c, c, D22); + M(d, p[2], q2[2]); + A2(d, d, d); + Z(e, b3, a); + Z(f, d, c); + A2(g, d, c); + A2(h2, b3, a); + M(p[0], e, f); + M(p[1], h2, g); + M(p[2], g, f); + M(p[3], e, h2); + }; + var cswap = function (p, q2, b3) { + for (var i = 0; i < 4; ++i) { + sel25519(p[i], q2[i], b3); + } + }; + var pack = function (r, p) { + var tx = gf(), + ty2 = gf(), + zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty2, p[1], zi); + pack25519(r, ty2); + r[31] ^= par25519(tx) << 7; + }; + var pack25519 = function (o, n) { + var i, j, b3; + var m2 = gf(), + t = gf(); + for (i = 0; i < 16; ++i) { + t[i] = n[i]; + } + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; ++j) { + m2[0] = t[0] - 65517; + for (i = 1; i < 15; ++i) { + m2[i] = t[i] - 65535 - ((m2[i - 1] >> 16) & 1); + m2[i - 1] &= 65535; + } + m2[15] = t[15] - 32767 - ((m2[14] >> 16) & 1); + b3 = (m2[15] >> 16) & 1; + m2[14] &= 65535; + sel25519(t, m2, 1 - b3); + } + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 255; + o[2 * i + 1] = t[i] >> 8; + } + }; + var unpackneg = function (r, p) { + var t = gf(), + chk = gf(), + num = gf(), + den = gf(), + den2 = gf(), + den4 = gf(), + den6 = gf(); + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D2); + Z(num, num, r[2]); + A2(den, r[2], den); + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) { + M(r[0], r[0], I); + } + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) { + return -1; + } + if (par25519(r[0]) === p[31] >> 7) { + Z(r[0], gf0, r[0]); + } + M(r[3], r[0], r[1]); + return 0; + }; + var unpack25519 = function (o, n) { + var i; + for (i = 0; i < 16; ++i) { + o[i] = n[2 * i] + (n[2 * i + 1] << 8); + } + o[15] &= 32767; + }; + var pow2523 = function (o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for (a = 250; a >= 0; --a) { + S(c, c); + if (a !== 1) { + M(c, c, i); + } + } + for (a = 0; a < 16; ++a) { + o[a] = c[a]; + } + }; + var neq25519 = function (a, b3) { + var c = new NativeBuffer(32); + var d = new NativeBuffer(32); + pack25519(c, a); + pack25519(d, b3); + return crypto_verify_32(c, 0, d, 0); + }; + var crypto_verify_32 = function (x, xi, y3, yi2) { + return vn(x, xi, y3, yi2, 32); + }; + var vn = function (x, xi, y3, yi2, n) { + var i, + d = 0; + for (i = 0; i < n; ++i) { + d |= x[xi + i] ^ y3[yi2 + i]; + } + return (1 & ((d - 1) >>> 8)) - 1; + }; + var par25519 = function (a) { + var d = new NativeBuffer(32); + pack25519(d, a); + return d[0] & 1; + }; + var scalarmult = function (p, q2, s) { + var b3, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b3 = (s[(i / 8) | 0] >> (i & 7)) & 1; + cswap(p, q2, b3); + add(q2, p); + add(p, p); + cswap(p, q2, b3); + } + }; + var scalarbase = function (p, s) { + var q2 = [gf(), gf(), gf(), gf()]; + set25519(q2[0], X); + set25519(q2[1], Y); + set25519(q2[2], gf1); + M(q2[3], X, Y); + scalarmult(p, q2, s); + }; + var set25519 = function (r, a) { + var i; + for (i = 0; i < 16; i++) { + r[i] = a[i] | 0; + } + }; + var inv25519 = function (o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for (a = 253; a >= 0; --a) { + S(c, c); + if (a !== 2 && a !== 4) { + M(c, c, i); + } + } + for (a = 0; a < 16; ++a) { + o[a] = c[a]; + } + }; + var car25519 = function (o) { + var i, + v, + c = 1; + for (i = 0; i < 16; ++i) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c - 1 + 37 * (c - 1); + }; + var sel25519 = function (p, q2, b3) { + var t, + c = ~(b3 - 1); + for (var i = 0; i < 16; ++i) { + t = c & (p[i] ^ q2[i]); + p[i] ^= t; + q2[i] ^= t; + } + }; + var gf = function (init2) { + var i, + r = new Float64Array(16); + if (init2) { + for (i = 0; i < init2.length; ++i) { + r[i] = init2[i]; + } + } + return r; + }; + var A2 = function (o, a, b3) { + for (var i = 0; i < 16; ++i) { + o[i] = a[i] + b3[i]; + } + }; + var Z = function (o, a, b3) { + for (var i = 0; i < 16; ++i) { + o[i] = a[i] - b3[i]; + } + }; + var S = function (o, a) { + M(o, a, a); + }; + var M = function (o, a, b3) { + var v, + c, + t02 = 0, + t1 = 0, + t22 = 0, + t3 = 0, + t4 = 0, + t5 = 0, + t6 = 0, + t7 = 0, + t8 = 0, + t9 = 0, + t10 = 0, + t11 = 0, + t12 = 0, + t13 = 0, + t14 = 0, + t15 = 0, + t16 = 0, + t17 = 0, + t18 = 0, + t19 = 0, + t20 = 0, + t21 = 0, + t222 = 0, + t23 = 0, + t24 = 0, + t25 = 0, + t26 = 0, + t27 = 0, + t28 = 0, + t29 = 0, + t30 = 0, + b0 = b3[0], + b1 = b3[1], + b22 = b3[2], + b32 = b3[3], + b4 = b3[4], + b5 = b3[5], + b6 = b3[6], + b7 = b3[7], + b8 = b3[8], + b9 = b3[9], + b10 = b3[10], + b11 = b3[11], + b12 = b3[12], + b13 = b3[13], + b14 = b3[14], + b15 = b3[15]; + v = a[0]; + t02 += v * b0; + t1 += v * b1; + t22 += v * b22; + t3 += v * b32; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t22 += v * b1; + t3 += v * b22; + t4 += v * b32; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t22 += v * b0; + t3 += v * b1; + t4 += v * b22; + t5 += v * b32; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b22; + t6 += v * b32; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b22; + t7 += v * b32; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b22; + t8 += v * b32; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b22; + t9 += v * b32; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b22; + t10 += v * b32; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t222 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b22; + t11 += v * b32; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t222 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b22; + t12 += v * b32; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t222 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b22; + t13 += v * b32; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t222 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b22; + t14 += v * b32; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t222 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b22; + t15 += v * b32; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t222 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b22; + t16 += v * b32; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t222 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b22; + t17 += v * b32; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t222 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b22; + t18 += v * b32; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t222 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + t02 += 38 * t16; + t1 += 38 * t17; + t22 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t222; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + c = 1; + v = t02 + c + 65535; + c = Math.floor(v / 65536); + t02 = v - c * 65536; + v = t1 + c + 65535; + c = Math.floor(v / 65536); + t1 = v - c * 65536; + v = t22 + c + 65535; + c = Math.floor(v / 65536); + t22 = v - c * 65536; + v = t3 + c + 65535; + c = Math.floor(v / 65536); + t3 = v - c * 65536; + v = t4 + c + 65535; + c = Math.floor(v / 65536); + t4 = v - c * 65536; + v = t5 + c + 65535; + c = Math.floor(v / 65536); + t5 = v - c * 65536; + v = t6 + c + 65535; + c = Math.floor(v / 65536); + t6 = v - c * 65536; + v = t7 + c + 65535; + c = Math.floor(v / 65536); + t7 = v - c * 65536; + v = t8 + c + 65535; + c = Math.floor(v / 65536); + t8 = v - c * 65536; + v = t9 + c + 65535; + c = Math.floor(v / 65536); + t9 = v - c * 65536; + v = t10 + c + 65535; + c = Math.floor(v / 65536); + t10 = v - c * 65536; + v = t11 + c + 65535; + c = Math.floor(v / 65536); + t11 = v - c * 65536; + v = t12 + c + 65535; + c = Math.floor(v / 65536); + t12 = v - c * 65536; + v = t13 + c + 65535; + c = Math.floor(v / 65536); + t13 = v - c * 65536; + v = t14 + c + 65535; + c = Math.floor(v / 65536); + t14 = v - c * 65536; + v = t15 + c + 65535; + c = Math.floor(v / 65536); + t15 = v - c * 65536; + t02 += c - 1 + 37 * (c - 1); + c = 1; + v = t02 + c + 65535; + c = Math.floor(v / 65536); + t02 = v - c * 65536; + v = t1 + c + 65535; + c = Math.floor(v / 65536); + t1 = v - c * 65536; + v = t22 + c + 65535; + c = Math.floor(v / 65536); + t22 = v - c * 65536; + v = t3 + c + 65535; + c = Math.floor(v / 65536); + t3 = v - c * 65536; + v = t4 + c + 65535; + c = Math.floor(v / 65536); + t4 = v - c * 65536; + v = t5 + c + 65535; + c = Math.floor(v / 65536); + t5 = v - c * 65536; + v = t6 + c + 65535; + c = Math.floor(v / 65536); + t6 = v - c * 65536; + v = t7 + c + 65535; + c = Math.floor(v / 65536); + t7 = v - c * 65536; + v = t8 + c + 65535; + c = Math.floor(v / 65536); + t8 = v - c * 65536; + v = t9 + c + 65535; + c = Math.floor(v / 65536); + t9 = v - c * 65536; + v = t10 + c + 65535; + c = Math.floor(v / 65536); + t10 = v - c * 65536; + v = t11 + c + 65535; + c = Math.floor(v / 65536); + t11 = v - c * 65536; + v = t12 + c + 65535; + c = Math.floor(v / 65536); + t12 = v - c * 65536; + v = t13 + c + 65535; + c = Math.floor(v / 65536); + t13 = v - c * 65536; + v = t14 + c + 65535; + c = Math.floor(v / 65536); + t14 = v - c * 65536; + v = t15 + c + 65535; + c = Math.floor(v / 65536); + t15 = v - c * 65536; + t02 += c - 1 + 37 * (c - 1); + o[0] = t02; + o[1] = t1; + o[2] = t22; + o[3] = t3; + o[4] = t4; + o[5] = t5; + o[6] = t6; + o[7] = t7; + o[8] = t8; + o[9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; + }; + var forge = require_forge(); + require_jsbn(); + require_random(); + require_sha512(); + require_util(); + var asn1Validator = require_asn1_validator(); + var publicKeyValidator = asn1Validator.publicKeyValidator; + var privateKeyValidator = asn1Validator.privateKeyValidator; + if (typeof BigInteger === 'undefined') { + BigInteger = forge.jsbn.BigInteger; + } + var BigInteger; + var ByteBuffer = forge.util.ByteBuffer; + var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer; + forge.pki = forge.pki || {}; + module.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; + var ed25519 = forge.ed25519; + ed25519.constants = {}; + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; + ed25519.constants.SEED_BYTE_LENGTH = 32; + ed25519.constants.SIGN_BYTE_LENGTH = 64; + ed25519.constants.HASH_BYTE_LENGTH = 64; + ed25519.generateKeyPair = function (options) { + options = options || {}; + var seed = options.seed; + if (seed === undefined) { + seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); + } else if (typeof seed === 'string') { + if (seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { + throw new TypeError('"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + ' bytes in length.'); + } + } else if (!(seed instanceof Uint8Array)) { + throw new TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.'); + } + seed = messageToNativeBuffer({message: seed, encoding: 'binary'}); + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + for (var i = 0; i < 32; ++i) { + sk[i] = seed[i]; + } + crypto_sign_keypair(pk, sk); + return {publicKey: pk, privateKey: sk}; + }; + ed25519.privateKeyFromAsn1 = function (obj) { + var capture = {}; + var errors = []; + var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors); + if (!valid) { + var error = new Error('Invalid Key.'); + error.errors = errors; + throw error; + } + var oid = forge.asn1.derToOid(capture.privateKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if (oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); + } + var privateKey = capture.privateKey; + var privateKeyBytes = messageToNativeBuffer({ + message: forge.asn1.fromDer(privateKey).value, + encoding: 'binary' + }); + return {privateKeyBytes}; + }; + ed25519.publicKeyFromAsn1 = function (obj) { + var capture = {}; + var errors = []; + var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors); + if (!valid) { + var error = new Error('Invalid Key.'); + error.errors = errors; + throw error; + } + var oid = forge.asn1.derToOid(capture.publicKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if (oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); + } + var publicKeyBytes = capture.ed25519PublicKey; + if (publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new Error('Key length is invalid.'); + } + return messageToNativeBuffer({ + message: publicKeyBytes, + encoding: 'binary' + }); + }; + ed25519.publicKeyFromPrivateKey = function (options) { + options = options || {}; + var privateKey = messageToNativeBuffer({ + message: options.privateKey, + encoding: 'binary' + }); + if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError('"options.privateKey" must have a byte length of ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + } + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + for (var i = 0; i < pk.length; ++i) { + pk[i] = privateKey[32 + i]; + } + return pk; + }; + ed25519.sign = function (options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + var privateKey = messageToNativeBuffer({ + message: options.privateKey, + encoding: 'binary' + }); + if (privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { + var keyPair = ed25519.generateKeyPair({seed: privateKey}); + privateKey = keyPair.privateKey; + } else if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError('"options.privateKey" must have a byte length of ' + ed25519.constants.SEED_BYTE_LENGTH + ' or ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + } + var signedMsg = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + crypto_sign(signedMsg, msg, msg.length, privateKey); + var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); + for (var i = 0; i < sig.length; ++i) { + sig[i] = signedMsg[i]; + } + return sig; + }; + ed25519.verify = function (options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + if (options.signature === undefined) { + throw new TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' + 'ByteBuffer, or a binary string.'); + } + var sig = messageToNativeBuffer({ + message: options.signature, + encoding: 'binary' + }); + if (sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { + throw new TypeError('"options.signature" must have a byte length of ' + ed25519.constants.SIGN_BYTE_LENGTH); + } + var publicKey = messageToNativeBuffer({ + message: options.publicKey, + encoding: 'binary' + }); + if (publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new TypeError('"options.publicKey" must have a byte length of ' + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + } + var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var m2 = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var i; + for (i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { + sm[i] = sig[i]; + } + for (i = 0; i < msg.length; ++i) { + sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; + } + return crypto_sign_open(m2, sm, sm.length, publicKey) >= 0; + }; + var gf0 = gf(); + var gf1 = gf([1]); + var D2 = gf([30883, 4953, 19914, 30187, 55467, 16705, 2637, 112, 59544, 30585, 16505, 36039, 65139, 11119, 27886, 20995]); + var D22 = gf([61785, 9906, 39828, 60374, 45398, 33411, 5274, 224, 53552, 61171, 33010, 6542, 64743, 22239, 55772, 9222]); + var X = gf([54554, 36645, 11616, 51542, 42930, 38181, 51040, 26924, 56412, 64982, 57905, 49316, 21502, 52590, 14035, 8553]); + var Y = gf([26200, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214]); + var L2 = new Float64Array([237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16]); + var I = gf([41136, 18958, 6951, 50414, 58488, 44335, 6150, 12099, 55207, 15867, 153, 11085, 57099, 20417, 9344, 11139]); +}); + +// node_modules/node-forge/lib/kem.js +var require_kem = __commonJS((exports, module) => { + var _createKDF = function (kdf, md, counterStart, digestLength) { + kdf.generate = function (x, length) { + var key = new forge.util.ByteBuffer(); + var k = Math.ceil(length / digestLength) + counterStart; + var c = new forge.util.ByteBuffer(); + for (var i = counterStart; i < k; ++i) { + c.putInt32(i); + md.start(); + md.update(x + c.getBytes()); + var hash = md.digest(); + key.putBytes(hash.getBytes(digestLength)); + } + key.truncate(key.length() - length); + return key.getBytes(); + }; + }; + var forge = require_forge(); + require_util(); + require_random(); + require_jsbn(); + module.exports = forge.kem = forge.kem || {}; + var BigInteger = forge.jsbn.BigInteger; + forge.kem.rsa = {}; + forge.kem.rsa.create = function (kdf, options) { + options = options || {}; + var prng = options.prng || forge.random; + var kem = {}; + kem.encrypt = function (publicKey, keyLength) { + var byteLength = Math.ceil(publicKey.n.bitLength() / 8); + var r; + do { + r = new BigInteger(forge.util.bytesToHex(prng.getBytesSync(byteLength)), 16).mod(publicKey.n); + } while (r.compareTo(BigInteger.ONE) <= 0); + r = forge.util.hexToBytes(r.toString(16)); + var zeros = byteLength - r.length; + if (zeros > 0) { + r = forge.util.fillString(String.fromCharCode(0), zeros) + r; + } + var encapsulation = publicKey.encrypt(r, 'NONE'); + var key = kdf.generate(r, keyLength); + return {encapsulation, key}; + }; + kem.decrypt = function (privateKey, encapsulation, keyLength) { + var r = privateKey.decrypt(encapsulation, 'NONE'); + return kdf.generate(r, keyLength); + }; + return kem; + }; + forge.kem.kdf1 = function (md, digestLength) { + _createKDF(this, md, 0, digestLength || md.digestLength); + }; + forge.kem.kdf2 = function (md, digestLength) { + _createKDF(this, md, 1, digestLength || md.digestLength); + }; +}); + +// node_modules/node-forge/lib/log.js +var require_log = __commonJS((exports, module) => { + var forge = require_forge(); + require_util(); + module.exports = forge.log = forge.log || {}; + forge.log.levels = ['none', 'error', 'warning', 'info', 'debug', 'verbose', 'max']; + var sLevelInfo = {}; + var sLoggers = []; + var sConsoleLogger = null; + forge.log.LEVEL_LOCKED = 1 << 1; + forge.log.NO_LEVEL_CHECK = 1 << 2; + forge.log.INTERPOLATE = 1 << 3; + for (i = 0; i < forge.log.levels.length; ++i) { + level = forge.log.levels[i]; + sLevelInfo[level] = { + index: i, + name: level.toUpperCase() + }; + } + var level; + var i; + forge.log.logMessage = function (message) { + var messageLevelIndex = sLevelInfo[message.level].index; + for (var i3 = 0; i3 < sLoggers.length; ++i3) { + var logger2 = sLoggers[i3]; + if (logger2.flags & forge.log.NO_LEVEL_CHECK) { + logger2.f(message); + } else { + var loggerLevelIndex = sLevelInfo[logger2.level].index; + if (messageLevelIndex <= loggerLevelIndex) { + logger2.f(logger2, message); + } + } + } + }; + forge.log.prepareStandard = function (message) { + if (!('standard' in message)) { + message.standard = sLevelInfo[message.level].name + ' [' + message.category + '] ' + message.message; + } + }; + forge.log.prepareFull = function (message) { + if (!('full' in message)) { + var args = [message.message]; + args = args.concat([]); + message.full = forge.util.format.apply(this, args); + } + }; + forge.log.prepareStandardFull = function (message) { + if (!('standardFull' in message)) { + forge.log.prepareStandard(message); + message.standardFull = message.standard; + } + }; + if (true) { + levels = ['error', 'warning', 'info', 'debug', 'verbose']; + for (i = 0; i < levels.length; ++i) { + (function (level2) { + forge.log[level2] = function (category, message) { + var args = Array.prototype.slice.call(arguments).slice(2); + var msg = { + timestamp: new Date(), + level: level2, + category, + message, + arguments: args + }; + forge.log.logMessage(msg); + }; + })(levels[i]); + } + } + var levels; + var i; + forge.log.makeLogger = function (logFunction) { + var logger2 = { + flags: 0, + f: logFunction + }; + forge.log.setLevel(logger2, 'none'); + return logger2; + }; + forge.log.setLevel = function (logger2, level2) { + var rval = false; + if (logger2 && !(logger2.flags & forge.log.LEVEL_LOCKED)) { + for (var i3 = 0; i3 < forge.log.levels.length; ++i3) { + var aValidLevel = forge.log.levels[i3]; + if (level2 == aValidLevel) { + logger2.level = level2; + rval = true; + break; + } + } + } + return rval; + }; + forge.log.lock = function (logger2, lock2) { + if (typeof lock2 === 'undefined' || lock2) { + logger2.flags |= forge.log.LEVEL_LOCKED; + } else { + logger2.flags &= ~forge.log.LEVEL_LOCKED; + } + }; + forge.log.addLogger = function (logger2) { + sLoggers.push(logger2); + }; + if (typeof console !== 'undefined' && 'log' in console) { + if (console.error && console.warn && console.info && console.debug) { + levelHandlers = { + error: console.error, + warning: console.warn, + info: console.info, + debug: console.debug, + verbose: console.debug + }; + f = function (logger2, message) { + forge.log.prepareStandard(message); + var handler = levelHandlers[message.level]; + var args = [message.standard]; + args = args.concat(message['arguments'].slice()); + handler.apply(console, args); + }; + logger = forge.log.makeLogger(f); + } else { + f = function (logger2, message) { + forge.log.prepareStandardFull(message); + console.log(message.standardFull); + }; + logger = forge.log.makeLogger(f); + } + forge.log.setLevel(logger, 'debug'); + forge.log.addLogger(logger); + sConsoleLogger = logger; + } else { + console = { + log: function () {} + }; + } + var logger; + var levelHandlers; + var f; + if (sConsoleLogger !== null && typeof window !== 'undefined' && window.location) { + query = new URL(window.location.href).searchParams; + if (query.has('console.level')) { + forge.log.setLevel(sConsoleLogger, query.get('console.level').slice(-1)[0]); + } + if (query.has('console.lock')) { + lock = query.get('console.lock').slice(-1)[0]; + if (lock == 'true') { + forge.log.lock(sConsoleLogger); + } + } + } + var query; + var lock; + forge.log.consoleLogger = sConsoleLogger; +}); + +// node_modules/node-forge/lib/md.all.js +var require_md_all = __commonJS((exports, module) => { + module.exports = require_md(); + require_md5(); + require_sha1(); + require_sha256(); + require_sha512(); +}); + +// node_modules/node-forge/lib/pkcs7.js +var require_pkcs7 = __commonJS((exports, module) => { + var _recipientFromAsn1 = function (obj) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 RecipientInfo. ' + 'ASN.1 object is not an PKCS#7 RecipientInfo.'); + error.errors = errors; + throw error; + } + return { + version: capture.version.charCodeAt(0), + issuer: forge.pki.RDNAttributesAsArray(capture.issuer), + serialNumber: forge.util.createBuffer(capture.serial).toHex(), + encryptedContent: { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: capture.encParameter ? capture.encParameter.value : undefined, + content: capture.encKey + } + }; + }; + var _recipientToAsn1 = function (obj) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(obj.version).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(obj.serialNumber))]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.encryptedContent.content) + ]); + }; + var _recipientsFromAsn1 = function (infos) { + var ret = []; + for (var i = 0; i < infos.length; ++i) { + ret.push(_recipientFromAsn1(infos[i])); + } + return ret; + }; + var _recipientsToAsn1 = function (recipients) { + var ret = []; + for (var i = 0; i < recipients.length; ++i) { + ret.push(_recipientToAsn1(recipients[i])); + } + return ret; + }; + var _signerToAsn1 = function (obj) { + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(obj.version).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(obj.serialNumber))]), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.digestAlgorithm).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')]) + ]); + if (obj.authenticatedAttributesAsn1) { + rval.value.push(obj.authenticatedAttributesAsn1); + } + rval.value.push( + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.signatureAlgorithm).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')]) + ); + rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature)); + if (obj.unauthenticatedAttributes.length > 0) { + var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); + for (var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { + var attr = obj.unauthenticatedAttributes[i]; + attrsAsn1.values.push(_attributeToAsn1(attr)); + } + rval.value.push(attrsAsn1); + } + return rval; + }; + var _signersToAsn1 = function (signers) { + var ret = []; + for (var i = 0; i < signers.length; ++i) { + ret.push(_signerToAsn1(signers[i])); + } + return ret; + }; + var _attributeToAsn1 = function (attr) { + var value; + if (attr.type === forge.pki.oids.contentType) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.value).getBytes()); + } else if (attr.type === forge.pki.oids.messageDigest) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, attr.value.bytes()); + } else if (attr.type === forge.pki.oids.signingTime) { + var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); + var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); + var date = attr.value; + if (typeof date === 'string') { + var timestamp = Date.parse(date); + if (!isNaN(timestamp)) { + date = new Date(timestamp); + } else if (date.length === 13) { + date = asn1.utcTimeToDate(date); + } else { + date = asn1.generalizedTimeToDate(date); + } + } + if (date >= jan_1_1950 && date < jan_1_2050) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, asn1.dateToUtcTime(date)); + } else { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, asn1.dateToGeneralizedTime(date)); + } + } + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [value])]); + }; + var _encryptedContentToAsn1 = function (ec) { + return [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(forge.pki.oids.data).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(ec.algorithm).getBytes()), + !ec.parameter ? undefined : asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ec.parameter.getBytes()) + ]), + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ec.content.getBytes())]) + ]; + }; + var _fromAsn1 = function (msg, obj, validator) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, validator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 message. ' + 'ASN.1 object is not a supported PKCS#7 message.'); + error.errors = error; + throw error; + } + var contentType = asn1.derToOid(capture.contentType); + if (contentType !== forge.pki.oids.data) { + throw new Error('Unsupported PKCS#7 message. ' + 'Only wrapped ContentType Data supported.'); + } + if (capture.encryptedContent) { + var content = ''; + if (forge.util.isArray(capture.encryptedContent)) { + for (var i = 0; i < capture.encryptedContent.length; ++i) { + if (capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { + throw new Error('Malformed PKCS#7 message, expecting encrypted ' + 'content constructed of only OCTET STRING objects.'); + } + content += capture.encryptedContent[i].value; + } + } else { + content = capture.encryptedContent; + } + msg.encryptedContent = { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: forge.util.createBuffer(capture.encParameter.value), + content: forge.util.createBuffer(content) + }; + } + if (capture.content) { + var content = ''; + if (forge.util.isArray(capture.content)) { + for (var i = 0; i < capture.content.length; ++i) { + if (capture.content[i].type !== asn1.Type.OCTETSTRING) { + throw new Error('Malformed PKCS#7 message, expecting ' + 'content constructed of only OCTET STRING objects.'); + } + content += capture.content[i].value; + } + } else { + content = capture.content; + } + msg.content = forge.util.createBuffer(content); + } + msg.version = capture.version.charCodeAt(0); + msg.rawCapture = capture; + return capture; + }; + var _decryptContent = function (msg) { + if (msg.encryptedContent.key === undefined) { + throw new Error('Symmetric key not available.'); + } + if (msg.content === undefined) { + var ciph; + switch (msg.encryptedContent.algorithm) { + case forge.pki.oids['aes128-CBC']: + case forge.pki.oids['aes192-CBC']: + case forge.pki.oids['aes256-CBC']: + ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key); + break; + case forge.pki.oids['desCBC']: + case forge.pki.oids['des-EDE3-CBC']: + ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key); + break; + default: + throw new Error('Unsupported symmetric cipher, OID ' + msg.encryptedContent.algorithm); + } + ciph.start(msg.encryptedContent.parameter); + ciph.update(msg.encryptedContent.content); + if (!ciph.finish()) { + throw new Error('Symmetric decryption failed.'); + } + msg.content = ciph.output; + } + }; + var forge = require_forge(); + require_aes(); + require_asn1(); + require_des(); + require_oids(); + require_pem(); + require_pkcs7asn1(); + require_random(); + require_util(); + require_x509(); + var asn1 = forge.asn1; + var p7 = (module.exports = forge.pkcs7 = forge.pkcs7 || {}); + p7.messageFromPem = function (pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== 'PKCS7') { + var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' + 'header type is not "PKCS#7".'); + error.headerType = msg.type; + throw error; + } + if (msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.'); + } + var obj = asn1.fromDer(msg.body); + return p7.messageFromAsn1(obj); + }; + p7.messageToPem = function (msg, maxline) { + var pemObj = { + type: 'PKCS7', + body: asn1.toDer(msg.toAsn1()).getBytes() + }; + return forge.pem.encode(pemObj, {maxline}); + }; + p7.messageFromAsn1 = function (obj) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 message. ' + 'ASN.1 object is not an PKCS#7 ContentInfo.'); + error.errors = errors; + throw error; + } + var contentType = asn1.derToOid(capture.contentType); + var msg; + switch (contentType) { + case forge.pki.oids.envelopedData: + msg = p7.createEnvelopedData(); + break; + case forge.pki.oids.encryptedData: + msg = p7.createEncryptedData(); + break; + case forge.pki.oids.signedData: + msg = p7.createSignedData(); + break; + default: + throw new Error('Cannot read PKCS#7 message. ContentType with OID ' + contentType + ' is not (yet) supported.'); + } + msg.fromAsn1(capture.content.value[0]); + return msg; + }; + p7.createSignedData = function () { + var msg = null; + msg = { + type: forge.pki.oids.signedData, + version: 1, + certificates: [], + crls: [], + signers: [], + digestAlgorithmIdentifiers: [], + contentInfo: null, + signerInfos: [], + fromAsn1: function (obj) { + _fromAsn1(msg, obj, p7.asn1.signedDataValidator); + msg.certificates = []; + msg.crls = []; + msg.digestAlgorithmIdentifiers = []; + msg.contentInfo = null; + msg.signerInfos = []; + if (msg.rawCapture.certificates) { + var certs = msg.rawCapture.certificates.value; + for (var i = 0; i < certs.length; ++i) { + msg.certificates.push(forge.pki.certificateFromAsn1(certs[i])); + } + } + }, + toAsn1: function () { + if (!msg.contentInfo) { + msg.sign(); + } + var certs = []; + for (var i = 0; i < msg.certificates.length; ++i) { + certs.push(forge.pki.certificateToAsn1(msg.certificates[i])); + } + var crls = []; + var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(msg.version).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, msg.digestAlgorithmIdentifiers), + msg.contentInfo + ]) + ]); + if (certs.length > 0) { + signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs)); + } + if (crls.length > 0) { + signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls)); + } + signedData.value[0].value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, msg.signerInfos)); + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(msg.type).getBytes()), signedData]); + }, + addSigner: function (signer) { + var issuer = signer.issuer; + var serialNumber = signer.serialNumber; + if (signer.certificate) { + var cert = signer.certificate; + if (typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + issuer = cert.issuer.attributes; + serialNumber = cert.serialNumber; + } + var key = signer.key; + if (!key) { + throw new Error('Could not add PKCS#7 signer; no private key specified.'); + } + if (typeof key === 'string') { + key = forge.pki.privateKeyFromPem(key); + } + var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1; + switch (digestAlgorithm) { + case forge.pki.oids.sha1: + case forge.pki.oids.sha256: + case forge.pki.oids.sha384: + case forge.pki.oids.sha512: + case forge.pki.oids.md5: + break; + default: + throw new Error('Could not add PKCS#7 signer; unknown message digest algorithm: ' + digestAlgorithm); + } + var authenticatedAttributes = signer.authenticatedAttributes || []; + if (authenticatedAttributes.length > 0) { + var contentType = false; + var messageDigest = false; + for (var i = 0; i < authenticatedAttributes.length; ++i) { + var attr = authenticatedAttributes[i]; + if (!contentType && attr.type === forge.pki.oids.contentType) { + contentType = true; + if (messageDigest) { + break; + } + continue; + } + if (!messageDigest && attr.type === forge.pki.oids.messageDigest) { + messageDigest = true; + if (contentType) { + break; + } + continue; + } + } + if (!contentType || !messageDigest) { + throw new Error('Invalid signer.authenticatedAttributes. If ' + 'signer.authenticatedAttributes is specified, then it must ' + 'contain at least two attributes, PKCS #9 content-type and ' + 'PKCS #9 message-digest.'); + } + } + msg.signers.push({ + key, + version: 1, + issuer, + serialNumber, + digestAlgorithm, + signatureAlgorithm: forge.pki.oids.rsaEncryption, + signature: null, + authenticatedAttributes, + unauthenticatedAttributes: [] + }); + }, + sign: function (options) { + options = options || {}; + if (typeof msg.content !== 'object' || msg.contentInfo === null) { + msg.contentInfo = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(forge.pki.oids.data).getBytes())]); + if ('content' in msg) { + var content; + if (msg.content instanceof forge.util.ByteBuffer) { + content = msg.content.bytes(); + } else if (typeof msg.content === 'string') { + content = forge.util.encodeUtf8(msg.content); + } + if (options.detached) { + msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); + } else { + msg.contentInfo.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content)])); + } + } + } + if (msg.signers.length === 0) { + return; + } + var mds = addDigestAlgorithmIds(); + addSignerInfos(mds); + }, + verify: function () { + throw new Error('PKCS#7 signature verification not yet implemented.'); + }, + addCertificate: function (cert) { + if (typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + msg.certificates.push(cert); + }, + addCertificateRevokationList: function (crl) { + throw new Error('PKCS#7 CRL support not yet implemented.'); + } + }; + return msg; + function addDigestAlgorithmIds() { + var mds = {}; + for (var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + var oid = signer.digestAlgorithm; + if (!(oid in mds)) { + mds[oid] = forge.md[forge.pki.oids[oid]].create(); + } + if (signer.authenticatedAttributes.length === 0) { + signer.md = mds[oid]; + } else { + signer.md = forge.md[forge.pki.oids[oid]].create(); + } + } + msg.digestAlgorithmIdentifiers = []; + for (var oid in mds) { + msg.digestAlgorithmIdentifiers.push( + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oid).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')]) + ); + } + return mds; + } + function addSignerInfos(mds) { + var content; + if (msg.detachedContent) { + content = msg.detachedContent; + } else { + content = msg.contentInfo.value[1]; + content = content.value[0]; + } + if (!content) { + throw new Error('Could not sign PKCS#7 message; there is no content to sign.'); + } + var contentType = asn1.derToOid(msg.contentInfo.value[0].value); + var bytes = asn1.toDer(content); + bytes.getByte(); + asn1.getBerValueLength(bytes); + bytes = bytes.getBytes(); + for (var oid in mds) { + mds[oid].start().update(bytes); + } + var signingTime = new Date(); + for (var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + if (signer.authenticatedAttributes.length === 0) { + if (contentType !== forge.pki.oids.data) { + throw new Error('Invalid signer; authenticatedAttributes must be present ' + 'when the ContentInfo content type is not PKCS#7 Data.'); + } + } else { + signer.authenticatedAttributesAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + var attrsAsn1 = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, []); + for (var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { + var attr = signer.authenticatedAttributes[ai]; + if (attr.type === forge.pki.oids.messageDigest) { + attr.value = mds[signer.digestAlgorithm].digest(); + } else if (attr.type === forge.pki.oids.signingTime) { + if (!attr.value) { + attr.value = signingTime; + } + } + attrsAsn1.value.push(_attributeToAsn1(attr)); + signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); + } + bytes = asn1.toDer(attrsAsn1).getBytes(); + signer.md.start().update(bytes); + } + signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5'); + } + msg.signerInfos = _signersToAsn1(msg.signers); + } + }; + p7.createEncryptedData = function () { + var msg = null; + msg = { + type: forge.pki.oids.encryptedData, + version: 0, + encryptedContent: { + algorithm: forge.pki.oids['aes256-CBC'] + }, + fromAsn1: function (obj) { + _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); + }, + decrypt: function (key) { + if (key !== undefined) { + msg.encryptedContent.key = key; + } + _decryptContent(msg); + } + }; + return msg; + }; + p7.createEnvelopedData = function () { + var msg = null; + msg = { + type: forge.pki.oids.envelopedData, + version: 0, + recipients: [], + encryptedContent: { + algorithm: forge.pki.oids['aes256-CBC'] + }, + fromAsn1: function (obj) { + var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); + msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); + }, + toAsn1: function () { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(msg.type).getBytes()), + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(msg.version).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, _recipientsToAsn1(msg.recipients)), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, _encryptedContentToAsn1(msg.encryptedContent)) + ]) + ]) + ]); + }, + findRecipient: function (cert) { + var sAttr = cert.issuer.attributes; + for (var i = 0; i < msg.recipients.length; ++i) { + var r = msg.recipients[i]; + var rAttr = r.issuer; + if (r.serialNumber !== cert.serialNumber) { + continue; + } + if (rAttr.length !== sAttr.length) { + continue; + } + var match = true; + for (var j = 0; j < sAttr.length; ++j) { + if (rAttr[j].type !== sAttr[j].type || rAttr[j].value !== sAttr[j].value) { + match = false; + break; + } + } + if (match) { + return r; + } + } + return null; + }, + decrypt: function (recipient, privKey) { + if (msg.encryptedContent.key === undefined && recipient !== undefined && privKey !== undefined) { + switch (recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + case forge.pki.oids.desCBC: + var key = privKey.decrypt(recipient.encryptedContent.content); + msg.encryptedContent.key = forge.util.createBuffer(key); + break; + default: + throw new Error('Unsupported asymmetric cipher, ' + 'OID ' + recipient.encryptedContent.algorithm); + } + } + _decryptContent(msg); + }, + addRecipient: function (cert) { + msg.recipients.push({ + version: 0, + issuer: cert.issuer.attributes, + serialNumber: cert.serialNumber, + encryptedContent: { + algorithm: forge.pki.oids.rsaEncryption, + key: cert.publicKey + } + }); + }, + encrypt: function (key, cipher) { + if (msg.encryptedContent.content === undefined) { + cipher = cipher || msg.encryptedContent.algorithm; + key = key || msg.encryptedContent.key; + var keyLen, ivLen, ciphFn; + switch (cipher) { + case forge.pki.oids['aes128-CBC']: + keyLen = 16; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + case forge.pki.oids['aes192-CBC']: + keyLen = 24; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + case forge.pki.oids['aes256-CBC']: + keyLen = 32; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + case forge.pki.oids['des-EDE3-CBC']: + keyLen = 24; + ivLen = 8; + ciphFn = forge.des.createEncryptionCipher; + break; + default: + throw new Error('Unsupported symmetric cipher, OID ' + cipher); + } + if (key === undefined) { + key = forge.util.createBuffer(forge.random.getBytes(keyLen)); + } else if (key.length() != keyLen) { + throw new Error('Symmetric key has wrong length; ' + 'got ' + key.length() + ' bytes, expected ' + keyLen + '.'); + } + msg.encryptedContent.algorithm = cipher; + msg.encryptedContent.key = key; + msg.encryptedContent.parameter = forge.util.createBuffer(forge.random.getBytes(ivLen)); + var ciph = ciphFn(key); + ciph.start(msg.encryptedContent.parameter.copy()); + ciph.update(msg.content); + if (!ciph.finish()) { + throw new Error('Symmetric encryption failed.'); + } + msg.encryptedContent.content = ciph.output; + } + for (var i = 0; i < msg.recipients.length; ++i) { + var recipient = msg.recipients[i]; + if (recipient.encryptedContent.content !== undefined) { + continue; + } + switch (recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt(msg.encryptedContent.key.data); + break; + default: + throw new Error('Unsupported asymmetric cipher, OID ' + recipient.encryptedContent.algorithm); + } + } + } + }; + return msg; + }; +}); + +// node_modules/node-forge/lib/ssh.js +var require_ssh = __commonJS((exports, module) => { + var _addBigIntegerToBuffer = function (buffer, val) { + var hexVal = val.toString(16); + if (hexVal[0] >= '8') { + hexVal = '00' + hexVal; + } + var bytes = forge.util.hexToBytes(hexVal); + buffer.putInt32(bytes.length); + buffer.putBytes(bytes); + }; + var _addStringToBuffer = function (buffer, val) { + buffer.putInt32(val.length); + buffer.putString(val); + }; + var _sha1 = function () { + var sha = forge.md.sha1.create(); + var num = arguments.length; + for (var i = 0; i < num; ++i) { + sha.update(arguments[i]); + } + return sha.digest(); + }; + var forge = require_forge(); + require_aes(); + require_hmac(); + require_md5(); + require_sha1(); + require_util(); + var ssh = (module.exports = forge.ssh = forge.ssh || {}); + ssh.privateKeyToPutty = function (privateKey, passphrase, comment) { + comment = comment || ''; + passphrase = passphrase || ''; + var algorithm = 'ssh-rsa'; + var encryptionAlgorithm = passphrase === '' ? 'none' : 'aes256-cbc'; + var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\r\n'; + ppk += 'Encryption: ' + encryptionAlgorithm + '\r\n'; + ppk += 'Comment: ' + comment + '\r\n'; + var pubbuffer = forge.util.createBuffer(); + _addStringToBuffer(pubbuffer, algorithm); + _addBigIntegerToBuffer(pubbuffer, privateKey.e); + _addBigIntegerToBuffer(pubbuffer, privateKey.n); + var pub = forge.util.encode64(pubbuffer.bytes(), 64); + var length = Math.floor(pub.length / 66) + 1; + ppk += 'Public-Lines: ' + length + '\r\n'; + ppk += pub; + var privbuffer = forge.util.createBuffer(); + _addBigIntegerToBuffer(privbuffer, privateKey.d); + _addBigIntegerToBuffer(privbuffer, privateKey.p); + _addBigIntegerToBuffer(privbuffer, privateKey.q); + _addBigIntegerToBuffer(privbuffer, privateKey.qInv); + var priv; + if (!passphrase) { + priv = forge.util.encode64(privbuffer.bytes(), 64); + } else { + var encLen = privbuffer.length() + 16 - 1; + encLen -= encLen % 16; + var padding = _sha1(privbuffer.bytes()); + padding.truncate(padding.length() - encLen + privbuffer.length()); + privbuffer.putBuffer(padding); + var aeskey = forge.util.createBuffer(); + aeskey.putBuffer(_sha1('\0\0\0\0', passphrase)); + aeskey.putBuffer(_sha1('\0\0\0\x01', passphrase)); + var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC'); + cipher.start(forge.util.createBuffer().fillWithByte(0, 16)); + cipher.update(privbuffer.copy()); + cipher.finish(); + var encrypted = cipher.output; + encrypted.truncate(16); + priv = forge.util.encode64(encrypted.bytes(), 64); + } + length = Math.floor(priv.length / 66) + 1; + ppk += '\r\nPrivate-Lines: ' + length + '\r\n'; + ppk += priv; + var mackey = _sha1('putty-private-key-file-mac-key', passphrase); + var macbuffer = forge.util.createBuffer(); + _addStringToBuffer(macbuffer, algorithm); + _addStringToBuffer(macbuffer, encryptionAlgorithm); + _addStringToBuffer(macbuffer, comment); + macbuffer.putInt32(pubbuffer.length()); + macbuffer.putBuffer(pubbuffer); + macbuffer.putInt32(privbuffer.length()); + macbuffer.putBuffer(privbuffer); + var hmac = forge.hmac.create(); + hmac.start('sha1', mackey); + hmac.update(macbuffer.bytes()); + ppk += '\r\nPrivate-MAC: ' + hmac.digest().toHex() + '\r\n'; + return ppk; + }; + ssh.publicKeyToOpenSSH = function (key, comment) { + var type = 'ssh-rsa'; + comment = comment || ''; + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment; + }; + ssh.privateKeyToOpenSSH = function (privateKey, passphrase) { + if (!passphrase) { + return forge.pki.privateKeyToPem(privateKey); + } + return forge.pki.encryptRsaPrivateKey(privateKey, passphrase, {legacy: true, algorithm: 'aes128'}); + }; + ssh.getPublicKeyFingerprint = function (key, options) { + options = options || {}; + var md = options.md || forge.md.md5.create(); + var type = 'ssh-rsa'; + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + md.start(); + md.update(buffer.getBytes()); + var digest = md.digest(); + if (options.encoding === 'hex') { + var hex = digest.toHex(); + if (options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if (options.encoding === 'binary') { + return digest.getBytes(); + } else if (options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; + }; +}); + +// node_modules/node-forge/lib/index.js +var require_lib = __commonJS((exports, module) => { + module.exports = require_forge(); + require_aes(); + require_aesCipherSuites(); + require_asn1(); + require_cipher(); + require_des(); + require_ed25519(); + require_hmac(); + require_kem(); + require_log(); + require_md_all(); + require_mgf1(); + require_pbkdf2(); + require_pem(); + require_pkcs1(); + require_pkcs12(); + require_pkcs7(); + require_pki(); + require_prime(); + require_prng(); + require_pss(); + require_random(); + require_rc2(); + require_ssh(); + require_tls(); + require_util(); +}); + +// src/lostcity/engine/World.ts +init_path(); +var {default: fs29} = () => ({}); + +// node_modules/kleur/index.mjs +var run = function (arr, str) { + let i = 0, + tmp, + beg = '', + end = ''; + for (; i < arr.length; i++) { + tmp = arr[i]; + beg += tmp.open; + end += tmp.close; + if (!!~str.indexOf(tmp.close)) { + str = str.replace(tmp.rgx, tmp.close + tmp.open); + } + } + return beg + str + end; +}; +var chain = function (has, keys) { + let ctx = {has, keys}; + ctx.reset = $.reset.bind(ctx); + ctx.bold = $.bold.bind(ctx); + ctx.dim = $.dim.bind(ctx); + ctx.italic = $.italic.bind(ctx); + ctx.underline = $.underline.bind(ctx); + ctx.inverse = $.inverse.bind(ctx); + ctx.hidden = $.hidden.bind(ctx); + ctx.strikethrough = $.strikethrough.bind(ctx); + ctx.black = $.black.bind(ctx); + ctx.red = $.red.bind(ctx); + ctx.green = $.green.bind(ctx); + ctx.yellow = $.yellow.bind(ctx); + ctx.blue = $.blue.bind(ctx); + ctx.magenta = $.magenta.bind(ctx); + ctx.cyan = $.cyan.bind(ctx); + ctx.white = $.white.bind(ctx); + ctx.gray = $.gray.bind(ctx); + ctx.grey = $.grey.bind(ctx); + ctx.bgBlack = $.bgBlack.bind(ctx); + ctx.bgRed = $.bgRed.bind(ctx); + ctx.bgGreen = $.bgGreen.bind(ctx); + ctx.bgYellow = $.bgYellow.bind(ctx); + ctx.bgBlue = $.bgBlue.bind(ctx); + ctx.bgMagenta = $.bgMagenta.bind(ctx); + ctx.bgCyan = $.bgCyan.bind(ctx); + ctx.bgWhite = $.bgWhite.bind(ctx); + return ctx; +}; +var init = function (open, close) { + let blk = { + open: `\x1B[${open}m`, + close: `\x1B[${close}m`, + rgx: new RegExp(`\\x1b\\[${close}m`, 'g') + }; + return function (txt) { + if (this !== undefined && this.has !== undefined) { + !!~this.has.indexOf(open) || (this.has.push(open), this.keys.push(blk)); + return txt === undefined ? this : $.enabled ? run(this.keys, txt + '') : txt + ''; + } + return txt === undefined ? chain([open], [blk]) : $.enabled ? run([blk], txt + '') : txt + ''; + }; +}; +var FORCE_COLOR; +var NODE_DISABLE_COLORS; +var NO_COLOR; +var TERM; +var isTTY = true; +if (typeof process !== 'undefined') { + ({FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM} = process.env || {}); + isTTY = process.stdout && process.stdout.isTTY; +} +var $ = { + enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && ((FORCE_COLOR != null && FORCE_COLOR !== '0') || isTTY), + reset: init(0, 0), + bold: init(1, 22), + dim: init(2, 22), + italic: init(3, 23), + underline: init(4, 24), + inverse: init(7, 27), + hidden: init(8, 28), + strikethrough: init(9, 29), + black: init(30, 39), + red: init(31, 39), + green: init(32, 39), + yellow: init(33, 39), + blue: init(34, 39), + magenta: init(35, 39), + cyan: init(36, 39), + white: init(37, 39), + gray: init(90, 39), + grey: init(90, 39), + bgBlack: init(40, 49), + bgRed: init(41, 49), + bgGreen: init(42, 49), + bgYellow: init(43, 49), + bgBlue: init(44, 49), + bgMagenta: init(45, 49), + bgCyan: init(46, 49), + bgWhite: init(47, 49) +}; +var kleur_default = $; + +// src/jagex2/jstring/JString.ts +function toBase37(string) { + string = string.trim(); + let l = 0n; + for (let i = 0; i < string.length && i < 12; i++) { + const c = string.charCodeAt(i); + l *= 37n; + if (c >= 65 && c <= 90) { + l += BigInt(c + 1 - 65); + } else if (c >= 97 && c <= 122) { + l += BigInt(c + 1 - 97); + } else if (c >= 48 && c <= 57) { + l += BigInt(c + 27 - 48); + } + } + return l; +} +function fromBase37(value) { + if (value < 0n || value >= 6582952005840035281n) { + return 'invalid_name'; + } + if (value % 37n === 0n) { + return 'invalid_name'; + } + let len = 0; + const chars = Array(12); + while (value !== 0n) { + const l1 = value; + value /= 37n; + chars[11 - len++] = BASE37_LOOKUP[Number(l1 - value * 37n)]; + } + return chars.slice(12 - len).join(''); +} +function toTitleCase(str) { + return str.replace(/\w\S*/g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()); +} +function toSafeName(name) { + return fromBase37(toBase37(name)); +} +function toDisplayName(name) { + return toTitleCase(toSafeName(name).replaceAll('_', ' ')); +} +var BASE37_LOOKUP = ['_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; + +// src/lostcity/cache/config/CategoryType.ts +var {default: fs2} = () => ({}); + +// src/jagex2/io/Packet.ts +init_path(); +var import_node_forge = __toESM(require_lib(), 1); +var {default: fs} = () => ({}); + +// src/jagex2/datastruct/Linkable.ts +class Linkable { + key; + next; + prev; + constructor() { + this.key = 0n; + this.next = this; + this.prev = this; + } + unlink() { + if (!this.prev || !this.next) { + return; + } + this.prev.next = this.next; + this.next.prev = this.prev; + this.next = null; + this.prev = null; + } +} + +// src/jagex2/datastruct/LinkList.ts +class LinkList { + sentinel; + cursor = null; + constructor() { + const head = new Linkable(); + head.next = head; + head.prev = head; + this.sentinel = head; + } + addTail(node) { + if (node.prev) { + node.unlink(); + } + node.prev = this.sentinel.prev; + node.next = this.sentinel; + if (node.prev) { + node.prev.next = node; + } + node.next.prev = node; + } + addHead(node) { + if (node.prev) { + node.unlink(); + } + node.prev = this.sentinel; + node.next = this.sentinel.next; + node.prev.next = node; + if (node.next) { + node.next.prev = node; + } + } + removeHead() { + const node = this.sentinel.next; + if (node === this.sentinel) { + return null; + } + node?.unlink(); + return node; + } + head() { + const node = this.sentinel.next; + if (node === this.sentinel) { + this.cursor = null; + return null; + } + this.cursor = node?.next || null; + return node; + } + tail() { + const node = this.sentinel.prev; + if (node === this.sentinel) { + this.cursor = null; + return null; + } + this.cursor = node?.prev || null; + return node; + } + next() { + const node = this.cursor; + if (node === this.sentinel) { + this.cursor = null; + return null; + } + this.cursor = node?.next || null; + return node; + } + prev() { + const node = this.cursor; + if (node === this.sentinel) { + this.cursor = null; + return null; + } + this.cursor = node?.prev || null; + return node; + } + clear() { + while (true) { + const node = this.sentinel.next; + if (node === this.sentinel) { + return; + } + node?.unlink(); + } + } +} + +// src/jagex2/datastruct/Hashable.ts +class Hashable extends Linkable { + nextHashable; + prevHashable; + constructor() { + super(); + this.nextHashable = this; + this.prevHashable = this; + } + uncache() { + if (!this.prevHashable || !this.nextHashable) { + return; + } + this.prevHashable.nextHashable = this.nextHashable; + this.nextHashable.prevHashable = this.prevHashable; + this.nextHashable = null; + this.prevHashable = null; + } +} + +// src/jagex2/io/Packet.ts +var PrivateKey = import_node_forge.default.pki.rsa.PrivateKey; +var BigInteger = import_node_forge.default.jsbn.BigInteger; + +class Packet extends Hashable { + static crctable = new Int32Array(256); + static bitmask = new Uint32Array(33); + static crc32b = 3988292384; + static { + for (let i = 0; i < 32; i++) { + this.bitmask[i] = (1 << i) - 1; + } + this.bitmask[32] = 4294967295; + for (let b3 = 0; b3 < 256; b3++) { + let remainder = b3; + for (let bit = 0; bit < 8; bit++) { + if ((remainder & 1) == 1) { + remainder = (remainder >>> 1) ^ this.crc32b; + } else { + remainder >>>= 1; + } + } + this.crctable[b3] = remainder; + } + } + static getcrc(src, offset, length) { + let crc = 4294967295; + for (let i = offset; i < length; i++) { + crc = (crc >>> 8) ^ this.crctable[(crc ^ src[i]) & 255]; + } + return ~crc; + } + static checkcrc(src, offset, length, expected = 0) { + const checksum = Packet.getcrc(src, offset, length); + return checksum == expected; + } + static alloc(type) { + let packet = null; + if (type === 0 && this.cacheMinCount > 0) { + packet = this.cacheMin.removeHead(); + this.cacheMinCount--; + } else if (type === 1 && this.cacheMidCount > 0) { + packet = this.cacheMid.removeHead(); + this.cacheMidCount--; + } else if (type === 2 && this.cacheMaxCount > 0) { + packet = this.cacheMax.removeHead(); + this.cacheMaxCount--; + } else if (type === 3 && this.cacheBigCount > 0) { + packet = this.cacheBig.removeHead(); + this.cacheBigCount--; + } else if (type === 4 && this.cacheHugeCount > 0) { + packet = this.cacheHuge.removeHead(); + this.cacheHugeCount--; + } else if (type === 5 && this.cacheUnimaginableCount > 0) { + packet = this.cacheUnimaginable.removeHead(); + this.cacheUnimaginableCount--; + } + if (packet !== null) { + packet.pos = 0; + packet.bitPos = 0; + return packet; + } + if (type === 0) { + return new Packet(new Uint8Array(100)); + } else if (type === 1) { + return new Packet(new Uint8Array(5000)); + } else if (type === 2) { + return new Packet(new Uint8Array(30000)); + } else if (type === 3) { + return new Packet(new Uint8Array(1e5)); + } else if (type === 4) { + return new Packet(new Uint8Array(500000)); + } else if (type === 5) { + return new Packet(new Uint8Array(2000000)); + } else { + return new Packet(new Uint8Array(type)); + } + } + static load(path, seekToEnd = false) { + const packet = new Packet(new Uint8Array(fs.readFileSync(path))); + if (seekToEnd) { + packet.pos = packet.data.length; + } + return packet; + } + static async loadAsync(path, seekToEnd = false) { + const packet = new Packet(new Uint8Array(await (await fetch(path)).arrayBuffer())); + if (seekToEnd) { + packet.pos = packet.data.length; + } + return packet; + } + static cacheMinCount = 0; + static cacheMidCount = 0; + static cacheMaxCount = 0; + static cacheBigCount = 0; + static cacheHugeCount = 0; + static cacheUnimaginableCount = 0; + static cacheMin = new LinkList(); + static cacheMid = new LinkList(); + static cacheMax = new LinkList(); + static cacheBig = new LinkList(); + static cacheHuge = new LinkList(); + static cacheUnimaginable = new LinkList(); + data; + #view; + pos; + bitPos; + constructor(src) { + super(); + this.data = src; + this.#view = new DataView(this.data.buffer); + this.pos = 0; + this.bitPos = 0; + } + get available() { + return this.data.length - this.pos; + } + get length() { + return this.data.length; + } + release() { + this.pos = 0; + this.bitPos = 0; + if (this.data.length === 100 && Packet.cacheMinCount < 1000) { + Packet.cacheMin.addTail(this); + Packet.cacheMinCount++; + } else if (this.data.length === 5000 && Packet.cacheMidCount < 250) { + Packet.cacheMid.addTail(this); + Packet.cacheMidCount++; + } else if (this.data.length === 30000 && Packet.cacheMaxCount < 50) { + Packet.cacheMax.addTail(this); + Packet.cacheMaxCount++; + } else if (this.data.length === 1e5 && Packet.cacheBigCount < 10) { + Packet.cacheBig.addTail(this); + Packet.cacheBigCount++; + } else if (this.data.length === 500000 && Packet.cacheHugeCount < 5) { + Packet.cacheHuge.addTail(this); + Packet.cacheHugeCount++; + } else if (this.data.length === 2000000 && Packet.cacheUnimaginableCount < 2) { + Packet.cacheUnimaginable.addTail(this); + Packet.cacheUnimaginableCount++; + } + } + save(filePath, length = this.pos, start = 0) { + if (typeof self !== 'undefined') { + const blob = new Blob([this.data.subarray(start, start + length)], {type: 'application/octet-stream'}); + const url = URL.createObjectURL(blob); + self.postMessage({type: 'save', value: url, path: filePath}); + } else { + const dir = q.dirname(filePath); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, {recursive: true}); + } + fs.writeFileSync(filePath, this.data.subarray(start, start + length)); + } + } + p1(value) { + this.#view.setUint8(this.pos++, value); + } + p2(value) { + this.#view.setUint16(this.pos, value); + this.pos += 2; + } + ip2(value) { + this.#view.setUint16(this.pos, value, true); + this.pos += 2; + } + p3(value) { + this.#view.setUint8(this.pos++, value >> 16); + this.#view.setUint16(this.pos, value); + this.pos += 2; + } + p4(value) { + this.#view.setInt32(this.pos, value); + this.pos += 4; + } + ip4(value) { + this.#view.setInt32(this.pos, value, true); + this.pos += 4; + } + p8(value) { + this.#view.setBigInt64(this.pos, value); + this.pos += 8; + } + pbool(value) { + this.p1(value ? 1 : 0); + } + pjstr(str, terminator = 10) { + const length = str.length; + for (let i = 0; i < length; i++) { + this.#view.setUint8(this.pos++, str.charCodeAt(i)); + } + this.#view.setUint8(this.pos++, terminator); + } + pdata(src, offset, length) { + this.data.set(src.subarray(offset, offset + length), this.pos); + this.pos += length - offset; + } + psize4(size) { + this.#view.setUint32(this.pos - size - 4, size); + } + psize2(size) { + this.#view.setUint16(this.pos - size - 2, size); + } + psize1(size) { + this.#view.setUint8(this.pos - size - 1, size); + } + psmarts(value) { + if (value < 64 && value >= 64) { + this.p1(value + 64); + } else if (value < 16384 && value >= -16384) { + this.p2(value + 49152); + } else { + throw new Error('Error psmarts out of range: ' + value); + } + } + psmart(value) { + if (value >= 0 && value < 128) { + this.p1(value); + } else if (value >= 0 && value < 32768) { + this.p2(value + 32768); + } else { + throw new Error('Error psmart out of range: ' + value); + } + } + g1() { + return this.#view.getUint8(this.pos++); + } + g1b() { + return this.#view.getInt8(this.pos++); + } + g2() { + this.pos += 2; + return this.#view.getUint16(this.pos - 2); + } + g2s() { + this.pos += 2; + return this.#view.getInt16(this.pos - 2); + } + ig2() { + this.pos += 2; + return this.#view.getUint16(this.pos - 2, true); + } + g3() { + const result = (this.#view.getUint8(this.pos++) << 16) | this.#view.getUint16(this.pos); + this.pos += 2; + return result; + } + g4() { + this.pos += 4; + return this.#view.getInt32(this.pos - 4); + } + ig4() { + this.pos += 4; + return this.#view.getInt32(this.pos - 4, true); + } + g8() { + this.pos += 8; + return this.#view.getBigInt64(this.pos - 8); + } + gbool() { + return this.g1() === 1; + } + gjstr(terminator = 10) { + const length = this.data.length; + let str = ''; + let b3; + while ((b3 = this.#view.getUint8(this.pos++)) !== terminator && this.pos < length) { + str += String.fromCharCode(b3); + } + return str; + } + gdata(dest, offset, length) { + dest.set(this.data.subarray(this.pos, this.pos + length), offset); + this.pos += length; + } + gsmarts() { + return this.#view.getUint8(this.pos) < 128 ? this.g1() - 64 : this.g2() - 49152; + } + gsmart() { + return this.#view.getUint8(this.pos) < 128 ? this.g1() : this.g2() - 32768; + } + bits() { + this.bitPos = this.pos << 3; + } + bytes() { + this.pos = (this.bitPos + 7) >>> 3; + } + gBit(n) { + let bytePos = this.bitPos >>> 3; + let remaining = 8 - (this.bitPos & 7); + let value = 0; + this.bitPos += n; + for (; n > remaining; remaining = 8) { + value += (this.#view.getUint8(bytePos++) & Packet.bitmask[remaining]) << (n - remaining); + n -= remaining; + } + if (n == remaining) { + value += this.#view.getUint8(bytePos) & Packet.bitmask[remaining]; + } else { + value += (this.#view.getUint8(bytePos) >>> (remaining - n)) & Packet.bitmask[n]; + } + return value; + } + pBit(n, value) { + const pos = this.bitPos; + this.bitPos += n; + let bytePos = pos >>> 3; + let remaining = 8 - (pos & 7); + const view = this.#view; + for (; n > remaining; remaining = 8) { + const shift2 = (1 << remaining) - 1; + const byte2 = view.getUint8(bytePos); + view.setUint8(bytePos++, (byte2 & ~shift2) | ((value >>> (n - remaining)) & shift2)); + n -= remaining; + } + const r = remaining - n; + const shift = (1 << n) - 1; + const byte = view.getUint8(bytePos); + view.setUint8(bytePos, (byte & (~shift << r)) | ((value & shift) << r)); + } + rsaenc(pem) { + const length = this.pos; + this.pos = 0; + const dec = new Uint8Array(length); + this.gdata(dec, 0, dec.length); + const bigRaw = new BigInteger(Array.from(dec)); + const rawEnc = Uint8Array.from(bigRaw.modPow(pem.e, pem.n).toByteArray()); + this.pos = 0; + this.p1(rawEnc.length); + this.pdata(rawEnc, 0, rawEnc.length); + } + rsadec(pem) { + const p = pem.p; + const q2 = pem.q; + const dP = pem.dP; + const dQ = pem.dQ; + const qInv = pem.qInv; + const enc = new Uint8Array(this.g1()); + this.gdata(enc, 0, enc.length); + const bigRaw = new BigInteger(Array.from(enc)); + const m1 = bigRaw.mod(p).modPow(dP, p); + const m2 = bigRaw.mod(q2).modPow(dQ, q2); + const h2 = qInv.multiply(m1.subtract(m2)).mod(p); + const rawDec = new Uint8Array(m2.add(h2.multiply(q2)).toByteArray()); + this.pos = 0; + this.pdata(rawDec, 0, rawDec.length); + this.pos = 0; + } +} + +// src/lostcity/cache/config/ConfigType.ts +class ConfigType { + id; + debugname = null; + constructor(id) { + this.id = id; + } + decodeType(dat) { + while (dat.available > 0) { + const code = dat.g1(); + if (code === 0) { + break; + } + this.decode(code, dat); + } + } +} + +// src/lostcity/cache/config/CategoryType.ts +class CategoryType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs2.existsSync(`${dir}/server/category.dat`)) { + console.log('Warning: No category.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/category.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/category.dat`)).ok) { + console.log('Warning: No category.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/category.dat`); + this.parse(dat); + } + static parse(dat) { + CategoryType.configNames = new Map(); + CategoryType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config = new CategoryType(id); + config.decodeType(dat); + CategoryType.configs[id] = config; + if (config.debugname) { + CategoryType.configNames.set(config.debugname, id); + } + } + } + static get(id) { + return CategoryType.configs[id]; + } + static getId(name) { + return CategoryType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + decode(code, dat) { + this.debugname = dat.gjstr(); + } + toString() { + return this.debugname ?? `category_${this.id}`; + } +} + +// src/lostcity/cache/config/DbRowType.ts +var {default: fs4} = () => ({}); + +// src/lostcity/cache/config/DbTableType.ts +var {default: fs3} = () => ({}); + +// src/lostcity/cache/config/ScriptVarType.ts +class ScriptVarType { + static INT = 105; + static AUTOINT = 255; + static STRING = 115; + static ENUM = 103; + static OBJ = 111; + static LOC = 108; + static COMPONENT = 73; + static NAMEDOBJ = 79; + static STRUCT = 74; + static BOOLEAN = 49; + static COORD = 99; + static CATEGORY = 121; + static SPOTANIM = 116; + static NPC = 110; + static INV = 118; + static SYNTH = 80; + static SEQ = 65; + static STAT = 83; + static VARP = 86; + static PLAYER_UID = 112; + static NPC_UID = 78; + static INTERFACE = 97; + static NPC_STAT = 254; + static IDKIT = 75; + static getType(type) { + switch (type) { + case ScriptVarType.INT: + return 'int'; + case ScriptVarType.STRING: + return 'string'; + case ScriptVarType.ENUM: + return 'enum'; + case ScriptVarType.OBJ: + return 'obj'; + case ScriptVarType.LOC: + return 'loc'; + case ScriptVarType.COMPONENT: + return 'component'; + case ScriptVarType.NAMEDOBJ: + return 'namedobj'; + case ScriptVarType.STRUCT: + return 'struct'; + case ScriptVarType.BOOLEAN: + return 'boolean'; + case ScriptVarType.COORD: + return 'coord'; + case ScriptVarType.CATEGORY: + return 'category'; + case ScriptVarType.SPOTANIM: + return 'spotanim'; + case ScriptVarType.NPC: + return 'npc'; + case ScriptVarType.INV: + return 'inv'; + case ScriptVarType.SYNTH: + return 'synth'; + case ScriptVarType.SEQ: + return 'seq'; + case ScriptVarType.STAT: + return 'stat'; + case ScriptVarType.AUTOINT: + return 'autoint'; + case ScriptVarType.VARP: + return 'varp'; + case ScriptVarType.PLAYER_UID: + return 'player_uid'; + case ScriptVarType.NPC_UID: + return 'npc_uid'; + case ScriptVarType.INTERFACE: + return 'interface'; + case ScriptVarType.NPC_STAT: + return 'npc_stat'; + case ScriptVarType.IDKIT: + return 'idkit'; + default: + return 'unknown'; + } + } + static getTypeChar(type) { + let char = 'i'; + switch (type) { + case 'int': + char = 'i'; + break; + case 'autoint': + char = '\xFF'; + break; + case 'string': + char = 's'; + break; + case 'enum': + char = 'g'; + break; + case 'obj': + char = 'o'; + break; + case 'loc': + char = 'l'; + break; + case 'component': + char = 'I'; + break; + case 'namedobj': + char = 'O'; + break; + case 'struct': + char = 'J'; + break; + case 'boolean': + char = '1'; + break; + case 'coord': + char = 'c'; + break; + case 'category': + char = 'y'; + break; + case 'spotanim': + char = 't'; + break; + case 'npc': + char = 'n'; + break; + case 'inv': + char = 'v'; + break; + case 'synth': + char = 'P'; + break; + case 'seq': + char = 'A'; + break; + case 'stat': + char = 'S'; + break; + case 'varp': + char = 'V'; + break; + case 'player_uid': + char = 'p'; + break; + case 'npc_uid': + char = 'N'; + break; + case 'interface': + char = 'a'; + break; + case 'npc_stat': + char = '\xFE'; + break; + case 'idkit': + char = 'K'; + break; + default: + return null; + } + return char.charCodeAt(0); + } + static getDefault(type) { + if (type === ScriptVarType.STRING) { + return ''; + } else if (type === ScriptVarType.BOOLEAN) { + return 0; + } else { + return -1; + } + } +} + +// src/lostcity/cache/config/DbTableType.ts +class DbTableType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs3.existsSync(`${dir}/server/dbtable.dat`)) { + console.log('Warning: No dbtable.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/dbtable.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/dbtable.dat`)).ok) { + console.log('Warning: No dbtable.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/dbtable.dat`); + this.parse(dat); + } + static parse(dat) { + DbTableType.configNames = new Map(); + DbTableType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config = new DbTableType(id); + config.decodeType(dat); + DbTableType.configs[id] = config; + if (config.debugname) { + DbTableType.configNames.set(config.debugname, id); + } + } + } + static get(id) { + return DbTableType.configs[id]; + } + static getId(name) { + return DbTableType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + types = []; + defaultValues = []; + columnNames = []; + decode(code, dat) { + if (code === 1) { + this.types = new Array(dat.g1()); + for (let setting = dat.g1(); setting != 255; setting = dat.g1()) { + const column = setting & 127; + const hasDefault = (setting & 128) !== 0; + const columnTypes = new Array(dat.g1()); + for (let i = 0; i < columnTypes.length; i++) { + columnTypes[i] = dat.g1(); + } + this.types[column] = columnTypes; + if (hasDefault) { + if (!this.defaultValues) { + this.defaultValues = new Array(this.types.length); + } + this.defaultValues[column] = this.decodeValues(dat, column); + } + } + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else if (code === 251) { + this.columnNames = new Array(dat.g1()); + for (let i = 0; i < this.columnNames.length; i++) { + this.columnNames[i] = dat.gjstr(); + } + } else { + throw new Error(`Unrecognized dbtable config code: ${code}`); + } + } + getDefault(column) { + if (!this.defaultValues[column]) { + const defaults = []; + for (let i = 0; i < this.types[column].length; i++) { + defaults[i] = ScriptVarType.getDefault(this.types[column][i]); + } + return defaults; + } + return this.defaultValues[column]; + } + decodeValues(dat, column) { + const types = this.types[column]; + const fieldCount = dat.g1(); + const values = new Array(fieldCount * types.length); + for (let fieldId = 0; fieldId < fieldCount; fieldId++) { + for (let typeId = 0; typeId < types.length; typeId++) { + const type = types[typeId]; + const index = typeId + fieldId * types.length; + if (type === ScriptVarType.STRING) { + values[index] = dat.gjstr(); + } else { + values[index] = dat.g4(); + } + } + } + return values; + } +} + +// src/lostcity/cache/config/DbRowType.ts +class DbRowType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs4.existsSync(`${dir}/server/dbrow.dat`)) { + console.log('Warning: No dbrow.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/dbrow.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/dbrow.dat`)).ok) { + console.log('Warning: No dbrow.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/dbrow.dat`); + this.parse(dat); + } + static parse(dat) { + DbRowType.configNames = new Map(); + DbRowType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config = new DbRowType(id); + config.decodeType(dat); + DbRowType.configs[id] = config; + if (config.debugname) { + DbRowType.configNames.set(config.debugname, id); + } + } + } + static get(id) { + return DbRowType.configs[id]; + } + static getId(name) { + return DbRowType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + static getInTable(tableId) { + return DbRowType.configs.filter(config => config.tableId === tableId); + } + tableId = 0; + types = []; + columnValues = []; + decode(code, dat) { + if (code === 3) { + const numColumns = dat.g1(); + this.types = new Array(numColumns); + this.columnValues = new Array(numColumns); + for (let columnId = dat.g1(); columnId != 255; columnId = dat.g1()) { + const columnTypes = new Array(dat.g1()); + for (let i = 0; i < columnTypes.length; i++) { + columnTypes[i] = dat.g1(); + } + this.types[columnId] = columnTypes; + this.columnValues[columnId] = this.decodeValues(dat, columnId); + } + } else if (code === 4) { + this.tableId = dat.g2(); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized dbtable config code: ${code}`); + } + } + getValue(column, listIndex) { + const value = this.columnValues[column].slice(listIndex * this.types[column].length, (listIndex + 1) * this.types[column].length); + if (!value.length) { + return DbTableType.get(this.tableId).getDefault(column); + } + return value; + } + decodeValues(dat, column) { + const types = this.types[column]; + const fieldCount = dat.g1(); + const values = new Array(fieldCount * types.length); + for (let fieldId = 0; fieldId < fieldCount; fieldId++) { + for (let typeId = 0; typeId < types.length; typeId++) { + const type = types[typeId]; + const index = typeId + fieldId * types.length; + if (type === ScriptVarType.STRING) { + values[index] = dat.gjstr(); + } else { + values[index] = dat.g4(); + } + } + } + return values; + } +} + +// src/lostcity/cache/config/EnumType.ts +var {default: fs5} = () => ({}); +class EnumType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs5.existsSync(`${dir}/server/enum.dat`)) { + console.log('Warning: No enum.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/enum.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/enum.dat`)).ok) { + console.log('Warning: No enum.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/enum.dat`); + this.parse(dat); + } + static parse(dat) { + EnumType.configNames = new Map(); + EnumType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config = new EnumType(id); + config.decodeType(dat); + EnumType.configs[id] = config; + if (config.debugname) { + EnumType.configNames.set(config.debugname, id); + } + } + } + static get(id) { + return EnumType.configs[id]; + } + static getId(name) { + return EnumType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + inputtype = ScriptVarType.INT; + outputtype = ScriptVarType.INT; + defaultInt = 0; + defaultString = 'null'; + values = new Map(); + decode(code, dat) { + if (code === 1) { + this.inputtype = dat.g1(); + } else if (code === 2) { + this.outputtype = dat.g1(); + } else if (code === 3) { + this.defaultString = dat.gjstr(); + } else if (code === 4) { + this.defaultInt = dat.g4(); + } else if (code === 5) { + const count = dat.g2(); + for (let i = 0; i < count; i++) { + this.values.set(dat.g4(), dat.gjstr()); + } + } else if (code === 6) { + const count = dat.g2(); + for (let i = 0; i < count; i++) { + this.values.set(dat.g4(), dat.g4()); + } + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized enum config code: ${code}`); + } + } +} + +// src/3rdparty/bzip2-wasm/bzip2-1.0.8/bzip2.mjs +var loadBZip2WASM = (() => { + var _scriptName = import.meta.url; + return async function (moduleArg = {}) { + var moduleRtn; + var Module = Object.assign({}, moduleArg); + var readyPromiseResolve, readyPromiseReject; + var readyPromise = new Promise((resolve, reject) => { + readyPromiseResolve = resolve; + readyPromiseReject = reject; + }); + ['_BZ2_bzBuffToBuffDecompress', '_BZ2_bzBuffToBuffCompress', '_malloc', '_free', '_memory', '___indirect_function_table', 'onRuntimeInitialized'].forEach(prop => { + if (!Object.getOwnPropertyDescriptor(readyPromise, prop)) { + Object.defineProperty(readyPromise, prop, { + get: () => abort('You are getting ' + prop + ' on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js'), + set: () => abort('You are setting ' + prop + ' on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') + }); + } + }); + var ENVIRONMENT_IS_WEB = typeof window == 'object'; + var ENVIRONMENT_IS_WORKER = typeof importScripts == 'function'; + var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions == 'object' && typeof process.versions.node == 'string'; + var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; + if (Module['ENVIRONMENT']) { + throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)'); + } + if (ENVIRONMENT_IS_NODE) { + const {createRequire} = await import('module'); + var require2 = createRequire(import.meta.url); + } + var moduleOverrides = Object.assign({}, Module); + var arguments_ = []; + var thisProgram = './this.program'; + var quit_ = (status, toThrow) => { + throw toThrow; + }; + var scriptDirectory = ''; + function locateFile(path) { + if (Module['locateFile']) { + return Module['locateFile'](path, scriptDirectory); + } + return scriptDirectory + path; + } + var read_, readAsync, readBinary; + if (ENVIRONMENT_IS_NODE) { + if (typeof process == 'undefined' || !process.release || process.release.name !== 'node') + throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); + var nodeVersion = process.versions.node; + var numericVersion = nodeVersion.split('.').slice(0, 3); + numericVersion = numericVersion[0] * 1e4 + numericVersion[1] * 100 + numericVersion[2].split('-')[0] * 1; + var minVersion = 160000; + if (numericVersion < 160000) { + throw new Error('This emscripten-generated code requires node v16.0.0 (detected v' + nodeVersion + ')'); + } + var fs6 = require2('fs'); + var nodePath = require2('path'); + scriptDirectory = require2('url').fileURLToPath(new URL('./', import.meta.url)); + read_ = (filename, binary) => { + filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename); + return fs6.readFileSync(filename, binary ? undefined : 'utf8'); + }; + readBinary = filename => { + var ret = read_(filename, true); + if (!ret.buffer) { + ret = new Uint8Array(ret); + } + assert(ret.buffer); + return ret; + }; + readAsync = (filename, onload, onerror, binary = true) => { + filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename); + fs6.readFile(filename, binary ? undefined : 'utf8', (err2, data) => { + if (err2) onerror(err2); + else onload(binary ? data.buffer : data); + }); + }; + if (!Module['thisProgram'] && process.argv.length > 1) { + thisProgram = process.argv[1].replace(/\\/g, '/'); + } + arguments_ = process.argv.slice(2); + quit_ = (status, toThrow) => { + process.exitCode = status; + throw toThrow; + }; + } else if (ENVIRONMENT_IS_SHELL) { + if ((typeof process == 'object' && typeof require2 === 'function') || typeof window == 'object' || typeof importScripts == 'function') + throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); + } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { + if (ENVIRONMENT_IS_WORKER) { + scriptDirectory = self.location.href; + } else if (typeof document != 'undefined' && document.currentScript) { + scriptDirectory = document.currentScript.src; + } + if (_scriptName) { + scriptDirectory = _scriptName; + } + if (scriptDirectory.startsWith('blob:')) { + scriptDirectory = ''; + } else { + scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, '').lastIndexOf('/') + 1); + } + if (!(typeof window == 'object' || typeof importScripts == 'function')) + throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); + { + read_ = url => { + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, false); + xhr.send(null); + return xhr.responseText; + }; + if (ENVIRONMENT_IS_WORKER) { + readBinary = url => { + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, false); + xhr.responseType = 'arraybuffer'; + xhr.send(null); + return new Uint8Array(xhr.response); + }; + } + readAsync = (url, onload, onerror) => { + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + xhr.responseType = 'arraybuffer'; + xhr.onload = () => { + if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { + onload(xhr.response); + return; + } + onerror(); + }; + xhr.onerror = onerror; + xhr.send(null); + }; + } + } else { + throw new Error('environment detection error'); + } + var out = Module['print'] || console.log.bind(console); + var err = Module['printErr'] || console.error.bind(console); + Object.assign(Module, moduleOverrides); + moduleOverrides = null; + checkIncomingModuleAPI(); + if (Module['arguments']) arguments_ = Module['arguments']; + legacyModuleProp('arguments', 'arguments_'); + if (Module['thisProgram']) thisProgram = Module['thisProgram']; + legacyModuleProp('thisProgram', 'thisProgram'); + if (Module['quit']) quit_ = Module['quit']; + legacyModuleProp('quit', 'quit_'); + assert(typeof Module['memoryInitializerPrefixURL'] == 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead'); + assert(typeof Module['pthreadMainPrefixURL'] == 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead'); + assert(typeof Module['cdInitializerPrefixURL'] == 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead'); + assert(typeof Module['filePackagePrefixURL'] == 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead'); + assert(typeof Module['read'] == 'undefined', 'Module.read option was removed (modify read_ in JS)'); + assert(typeof Module['readAsync'] == 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)'); + assert(typeof Module['readBinary'] == 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)'); + assert(typeof Module['setWindowTitle'] == 'undefined', 'Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)'); + assert(typeof Module['TOTAL_MEMORY'] == 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY'); + legacyModuleProp('asm', 'wasmExports'); + legacyModuleProp('read', 'read_'); + legacyModuleProp('readAsync', 'readAsync'); + legacyModuleProp('readBinary', 'readBinary'); + legacyModuleProp('setWindowTitle', 'setWindowTitle'); + var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js'; + var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js'; + var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js'; + var FETCHFS = 'FETCHFS is no longer included by default; build with -lfetchfs.js'; + var ICASEFS = 'ICASEFS is no longer included by default; build with -licasefs.js'; + var JSFILEFS = 'JSFILEFS is no longer included by default; build with -ljsfilefs.js'; + var OPFS = 'OPFS is no longer included by default; build with -lopfs.js'; + var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js'; + assert(!ENVIRONMENT_IS_SHELL, 'shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.'); + var wasmBinary; + if (Module['wasmBinary']) wasmBinary = Module['wasmBinary']; + legacyModuleProp('wasmBinary', 'wasmBinary'); + if (typeof WebAssembly != 'object') { + err('no native wasm support detected'); + } + var wasmMemory; + var ABORT = false; + var EXITSTATUS; + function assert(condition, text) { + if (!condition) { + abort('Assertion failed' + (text ? ': ' + text : '')); + } + } + var HEAP, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64; + function updateMemoryViews() { + var b3 = wasmMemory.buffer; + Module['HEAP8'] = HEAP8 = new Int8Array(b3); + Module['HEAP16'] = HEAP16 = new Int16Array(b3); + Module['HEAPU8'] = HEAPU8 = new Uint8Array(b3); + Module['HEAPU16'] = HEAPU16 = new Uint16Array(b3); + Module['HEAP32'] = HEAP32 = new Int32Array(b3); + Module['HEAPU32'] = HEAPU32 = new Uint32Array(b3); + Module['HEAPF32'] = HEAPF32 = new Float32Array(b3); + Module['HEAPF64'] = HEAPF64 = new Float64Array(b3); + } + assert(!Module['STACK_SIZE'], 'STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time'); + assert(typeof Int32Array != 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray != null && Int32Array.prototype.set != null, 'JS engine does not provide full typed array support'); + assert(!Module['wasmMemory'], 'Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally'); + assert(!Module['INITIAL_MEMORY'], 'Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically'); + function writeStackCookie() { + var max = _emscripten_stack_get_end(); + assert((max & 3) == 0); + if (max == 0) { + max += 4; + } + HEAPU32[max >> 2] = 34821223; + HEAPU32[(max + 4) >> 2] = 2310721022; + HEAPU32[0] = 1668509029; + } + function checkStackCookie() { + if (ABORT) return; + var max = _emscripten_stack_get_end(); + if (max == 0) { + max += 4; + } + var cookie1 = HEAPU32[max >> 2]; + var cookie2 = HEAPU32[(max + 4) >> 2]; + if (cookie1 != 34821223 || cookie2 != 2310721022) { + abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`); + } + if (HEAPU32[0] != 1668509029) { + abort('Runtime error: The application has corrupted its heap memory area (address zero)!'); + } + } + (function () { + var h16 = new Int16Array(1); + var h8 = new Int8Array(h16.buffer); + h16[0] = 25459; + if (h8[0] !== 115 || h8[1] !== 99) throw 'Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)'; + })(); + var __ATPRERUN__ = []; + var __ATINIT__ = []; + var __ATEXIT__ = []; + var __ATPOSTRUN__ = []; + var runtimeInitialized = false; + function preRun() { + if (Module['preRun']) { + if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']]; + while (Module['preRun'].length) { + addOnPreRun(Module['preRun'].shift()); + } + } + callRuntimeCallbacks(__ATPRERUN__); + } + function initRuntime() { + assert(!runtimeInitialized); + runtimeInitialized = true; + checkStackCookie(); + callRuntimeCallbacks(__ATINIT__); + } + function postRun() { + checkStackCookie(); + if (Module['postRun']) { + if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']]; + while (Module['postRun'].length) { + addOnPostRun(Module['postRun'].shift()); + } + } + callRuntimeCallbacks(__ATPOSTRUN__); + } + function addOnPreRun(cb) { + __ATPRERUN__.unshift(cb); + } + function addOnInit(cb) { + __ATINIT__.unshift(cb); + } + function addOnExit(cb) {} + function addOnPostRun(cb) { + __ATPOSTRUN__.unshift(cb); + } + assert(Math.imul, 'This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); + assert(Math.fround, 'This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); + assert(Math.clz32, 'This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); + assert(Math.trunc, 'This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); + var runDependencies = 0; + var runDependencyWatcher = null; + var dependenciesFulfilled = null; + var runDependencyTracking = {}; + function getUniqueRunDependency(id) { + var orig = id; + while (true) { + if (!runDependencyTracking[id]) return id; + id = orig + Math.random(); + } + } + function addRunDependency(id) { + runDependencies++; + Module['monitorRunDependencies']?.(runDependencies); + if (id) { + assert(!runDependencyTracking[id]); + runDependencyTracking[id] = 1; + if (runDependencyWatcher === null && typeof setInterval != 'undefined') { + runDependencyWatcher = setInterval(() => { + if (ABORT) { + clearInterval(runDependencyWatcher); + runDependencyWatcher = null; + return; + } + var shown = false; + for (var dep in runDependencyTracking) { + if (!shown) { + shown = true; + err('still waiting on run dependencies:'); + } + err(`dependency: ${dep}`); + } + if (shown) { + err('(end of list)'); + } + }, 1e4); + } + } else { + err('warning: run dependency added without ID'); + } + } + function removeRunDependency(id) { + runDependencies--; + Module['monitorRunDependencies']?.(runDependencies); + if (id) { + assert(runDependencyTracking[id]); + delete runDependencyTracking[id]; + } else { + err('warning: run dependency removed without ID'); + } + if (runDependencies == 0) { + if (runDependencyWatcher !== null) { + clearInterval(runDependencyWatcher); + runDependencyWatcher = null; + } + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled; + dependenciesFulfilled = null; + callback(); + } + } + } + function abort(what) { + Module['onAbort']?.(what); + what = 'Aborted(' + what + ')'; + err(what); + ABORT = true; + EXITSTATUS = 1; + var e = new WebAssembly.RuntimeError(what); + readyPromiseReject(e); + throw e; + } + var FS = { + error() { + abort( + 'Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM' + ); + }, + init() { + FS.error(); + }, + createDataFile() { + FS.error(); + }, + createPreloadedFile() { + FS.error(); + }, + createLazyFile() { + FS.error(); + }, + open() { + FS.error(); + }, + mkdev() { + FS.error(); + }, + registerDevice() { + FS.error(); + }, + analyzePath() { + FS.error(); + }, + ErrnoError() { + FS.error(); + } + }; + Module['FS_createDataFile'] = FS.createDataFile; + Module['FS_createPreloadedFile'] = FS.createPreloadedFile; + var dataURIPrefix = 'data:application/octet-stream;base64,'; + var isDataURI = filename => filename.startsWith(dataURIPrefix); + var isFileURI = filename => filename.startsWith('file://'); + function createExportWrapper(name, nargs) { + return (...args) => { + assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`); + var f = wasmExports[name]; + assert(f, `exported native function \`${name}\` not found`); + assert(args.length <= nargs, `native function \`${name}\` called with ${args.length} args but expects ${nargs}`); + return f(...args); + }; + } + function findWasmBinary() { + if (Module['locateFile']) { + var f = 'bzip2.wasm'; + if (!isDataURI(f)) { + return locateFile(f); + } + return f; + } + return new URL('bzip2.wasm', import.meta.url).href; + } + var wasmBinaryFile; + function getBinarySync(file) { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary); + } + if (readBinary) { + return readBinary(file); + } + throw 'both async and sync fetching of the wasm failed'; + } + function getBinaryPromise(binaryFile) { + if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { + if (typeof fetch == 'function' && !isFileURI(binaryFile)) { + return fetch(binaryFile, {credentials: 'same-origin'}) + .then(response => { + if (!response['ok']) { + throw `failed to load wasm binary file at '${binaryFile}'`; + } + return response['arrayBuffer'](); + }) + .catch(() => getBinarySync(binaryFile)); + } else if (readAsync) { + return new Promise((resolve, reject) => { + readAsync(binaryFile, response => resolve(new Uint8Array(response)), reject); + }); + } + } + return Promise.resolve().then(() => getBinarySync(binaryFile)); + } + function instantiateArrayBuffer(binaryFile, imports, receiver) { + return getBinaryPromise(binaryFile) + .then(binary => { + return WebAssembly.instantiate(binary, imports); + }) + .then(receiver, reason => { + err(`failed to asynchronously prepare wasm: ${reason}`); + if (isFileURI(wasmBinaryFile)) { + err( + `warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing` + ); + } + abort(reason); + }); + } + function instantiateAsync(binary, binaryFile, imports, callback) { + if (!binary && typeof WebAssembly.instantiateStreaming == 'function' && !isDataURI(binaryFile) && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE && typeof fetch == 'function') { + return fetch(binaryFile, {credentials: 'same-origin'}).then(response => { + var result = WebAssembly.instantiateStreaming(response, imports); + return result.then(callback, function (reason) { + err(`wasm streaming compile failed: ${reason}`); + err('falling back to ArrayBuffer instantiation'); + return instantiateArrayBuffer(binaryFile, imports, callback); + }); + }); + } + return instantiateArrayBuffer(binaryFile, imports, callback); + } + function getWasmImports() { + return { + env: wasmImports, + wasi_snapshot_preview1: wasmImports + }; + } + function createWasm() { + var info = getWasmImports(); + function receiveInstance(instance, module) { + wasmExports = instance.exports; + wasmMemory = wasmExports['memory']; + assert(wasmMemory, 'memory not found in wasm exports'); + updateMemoryViews(); + addOnInit(wasmExports['__wasm_call_ctors']); + removeRunDependency('wasm-instantiate'); + return wasmExports; + } + addRunDependency('wasm-instantiate'); + var trueModule = Module; + function receiveInstantiationResult(result) { + assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?'); + trueModule = null; + receiveInstance(result['instance']); + } + if (Module['instantiateWasm']) { + try { + return Module['instantiateWasm'](info, receiveInstance); + } catch (e) { + err(`Module.instantiateWasm callback failed with error: ${e}`); + readyPromiseReject(e); + } + } + if (!wasmBinaryFile) wasmBinaryFile = findWasmBinary(); + instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult).catch(readyPromiseReject); + return {}; + } + var tempDouble; + var tempI64; + function legacyModuleProp(prop, newName, incoming = true) { + if (!Object.getOwnPropertyDescriptor(Module, prop)) { + Object.defineProperty(Module, prop, { + configurable: true, + get() { + let extra = incoming ? ' (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)' : ''; + abort(`\`Module.${prop}\` has been replaced by \`${newName}\`` + extra); + } + }); + } + } + function ignoredModuleProp(prop) { + if (Object.getOwnPropertyDescriptor(Module, prop)) { + abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`); + } + } + function isExportedByForceFilesystem(name) { + return ( + name === 'FS_createPath' || + name === 'FS_createDataFile' || + name === 'FS_createPreloadedFile' || + name === 'FS_unlink' || + name === 'addRunDependency' || + name === 'FS_createLazyFile' || + name === 'FS_createDevice' || + name === 'removeRunDependency' + ); + } + function missingGlobal(sym, msg) { + if (typeof globalThis != 'undefined') { + Object.defineProperty(globalThis, sym, { + configurable: true, + get() { + warnOnce(`\`${sym}\` is not longer defined by emscripten. ${msg}`); + return; + } + }); + } + } + missingGlobal('buffer', 'Please use HEAP8.buffer or wasmMemory.buffer'); + missingGlobal('asm', 'Please use wasmExports instead'); + function missingLibrarySymbol(sym) { + if (typeof globalThis != 'undefined' && !Object.getOwnPropertyDescriptor(globalThis, sym)) { + Object.defineProperty(globalThis, sym, { + configurable: true, + get() { + var msg = `\`${sym}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`; + var librarySymbol = sym; + if (!librarySymbol.startsWith('_')) { + librarySymbol = '$' + sym; + } + msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`; + if (isExportedByForceFilesystem(sym)) { + msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you'; + } + warnOnce(msg); + return; + } + }); + } + unexportedRuntimeSymbol(sym); + } + function unexportedRuntimeSymbol(sym) { + if (!Object.getOwnPropertyDescriptor(Module, sym)) { + Object.defineProperty(Module, sym, { + configurable: true, + get() { + var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`; + if (isExportedByForceFilesystem(sym)) { + msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you'; + } + abort(msg); + } + }); + } + } + function dbg(...args) { + console.warn(...args); + } + function ExitStatus(status) { + this.name = 'ExitStatus'; + this.message = `Program terminated with exit(${status})`; + this.status = status; + } + var callRuntimeCallbacks = callbacks => { + while (callbacks.length > 0) { + callbacks.shift()(Module); + } + }; + function getValue(ptr, type = 'i8') { + if (type.endsWith('*')) type = '*'; + switch (type) { + case 'i1': + return HEAP8[ptr]; + case 'i8': + return HEAP8[ptr]; + case 'i16': + return HEAP16[ptr >> 1]; + case 'i32': + return HEAP32[ptr >> 2]; + case 'i64': + abort('to do getValue(i64) use WASM_BIGINT'); + case 'float': + return HEAPF32[ptr >> 2]; + case 'double': + return HEAPF64[ptr >> 3]; + case '*': + return HEAPU32[ptr >> 2]; + default: + abort(`invalid type for getValue: ${type}`); + } + } + var noExitRuntime = Module['noExitRuntime'] || true; + var ptrToString = ptr => { + assert(typeof ptr === 'number'); + ptr >>>= 0; + return '0x' + ptr.toString(16).padStart(8, '0'); + }; + function setValue(ptr, value, type = 'i8') { + if (type.endsWith('*')) type = '*'; + switch (type) { + case 'i1': + HEAP8[ptr] = value; + break; + case 'i8': + HEAP8[ptr] = value; + break; + case 'i16': + HEAP16[ptr >> 1] = value; + break; + case 'i32': + HEAP32[ptr >> 2] = value; + break; + case 'i64': + abort('to do setValue(i64) use WASM_BIGINT'); + case 'float': + HEAPF32[ptr >> 2] = value; + break; + case 'double': + HEAPF64[ptr >> 3] = value; + break; + case '*': + HEAPU32[ptr >> 2] = value; + break; + default: + abort(`invalid type for setValue: ${type}`); + } + } + var stackRestore = val => __emscripten_stack_restore(val); + var stackSave = () => _emscripten_stack_get_current(); + var warnOnce = text => { + warnOnce.shown ||= {}; + if (!warnOnce.shown[text]) { + warnOnce.shown[text] = 1; + if (ENVIRONMENT_IS_NODE) text = 'warning: ' + text; + err(text); + } + }; + var __emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num); + var getHeapMax = () => 2147483648; + var growMemory = size => { + var b3 = wasmMemory.buffer; + var pages = (size - b3.byteLength + 65535) / 65536; + try { + wasmMemory.grow(pages); + updateMemoryViews(); + return 1; + } catch (e) { + err(`growMemory: Attempted to grow heap from ${b3.byteLength} bytes to ${size} bytes, but got error: ${e}`); + } + }; + var _emscripten_resize_heap = requestedSize => { + var oldSize = HEAPU8.length; + requestedSize >>>= 0; + assert(requestedSize > oldSize); + var maxHeapSize = getHeapMax(); + if (requestedSize > maxHeapSize) { + err(`Cannot enlarge memory, requested ${requestedSize} bytes, but the limit is ${maxHeapSize} bytes!`); + return false; + } + var alignUp = (x, multiple) => x + ((multiple - (x % multiple)) % multiple); + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); + overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); + var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)); + var replacement = growMemory(newSize); + if (replacement) { + return true; + } + } + err(`Failed to grow the heap from ${oldSize} bytes to ${newSize} bytes, not enough memory!`); + return false; + }; + var runtimeKeepaliveCounter = 0; + var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0; + var _proc_exit = code => { + EXITSTATUS = code; + if (!keepRuntimeAlive()) { + Module['onExit']?.(code); + ABORT = true; + } + quit_(code, new ExitStatus(code)); + }; + var exitJS = (status, implicit) => { + EXITSTATUS = status; + checkUnflushedContent(); + if (keepRuntimeAlive() && !implicit) { + var msg = `program exited (with status: ${status}), but keepRuntimeAlive() is set (counter=${runtimeKeepaliveCounter}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`; + readyPromiseReject(msg); + err(msg); + } + _proc_exit(status); + }; + var _exit = exitJS; + var UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined; + var UTF8ArrayToString = (heapOrArray, idx, maxBytesToRead) => { + var endIdx = idx + maxBytesToRead; + var endPtr = idx; + while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr; + if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) { + return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr)); + } + var str = ''; + while (idx < endPtr) { + var u02 = heapOrArray[idx++]; + if (!(u02 & 128)) { + str += String.fromCharCode(u02); + continue; + } + var u1 = heapOrArray[idx++] & 63; + if ((u02 & 224) == 192) { + str += String.fromCharCode(((u02 & 31) << 6) | u1); + continue; + } + var u2 = heapOrArray[idx++] & 63; + if ((u02 & 240) == 224) { + u02 = ((u02 & 15) << 12) | (u1 << 6) | u2; + } else { + if ((u02 & 248) != 240) warnOnce('Invalid UTF-8 leading byte ' + ptrToString(u02) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!'); + u02 = ((u02 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63); + } + if (u02 < 65536) { + str += String.fromCharCode(u02); + } else { + var ch = u02 - 65536; + str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023)); + } + } + return str; + }; + var UTF8ToString = (ptr, maxBytesToRead) => { + assert(typeof ptr == 'number', `UTF8ToString expects a number (got ${typeof ptr})`); + return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ''; + }; + var SYSCALLS = { + varargs: undefined, + getStr(ptr) { + var ret = UTF8ToString(ptr); + return ret; + } + }; + var _fd_close = fd => { + abort('fd_close called without SYSCALLS_REQUIRE_FILESYSTEM'); + }; + var convertI32PairToI53Checked = (lo, hi) => { + assert(lo == lo >>> 0 || lo == (lo | 0)); + assert(hi === (hi | 0)); + return (hi + 2097152) >>> 0 < 4194305 - !!lo ? (lo >>> 0) + hi * 4294967296 : NaN; + }; + function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); + return 70; + } + var printCharBuffers = [null, [], []]; + var printChar = (stream, curr) => { + var buffer = printCharBuffers[stream]; + assert(buffer); + if (curr === 0 || curr === 10) { + (stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0)); + buffer.length = 0; + } else { + buffer.push(curr); + } + }; + var flush_NO_FILESYSTEM = () => { + _fflush(0); + if (printCharBuffers[1].length) printChar(1, 10); + if (printCharBuffers[2].length) printChar(2, 10); + }; + var _fd_write = (fd, iov, iovcnt, pnum) => { + var num = 0; + for (var i = 0; i < iovcnt; i++) { + var ptr = HEAPU32[iov >> 2]; + var len = HEAPU32[(iov + 4) >> 2]; + iov += 8; + for (var j = 0; j < len; j++) { + printChar(fd, HEAPU8[ptr + j]); + } + num += len; + } + HEAPU32[pnum >> 2] = num; + return 0; + }; + function checkIncomingModuleAPI() { + ignoredModuleProp('fetchSettings'); + } + var wasmImports = { + _emscripten_memcpy_js: __emscripten_memcpy_js, + emscripten_resize_heap: _emscripten_resize_heap, + exit: _exit, + fd_close: _fd_close, + fd_seek: _fd_seek, + fd_write: _fd_write + }; + var wasmExports = createWasm(); + var ___wasm_call_ctors = createExportWrapper('__wasm_call_ctors', 0); + var _malloc = (Module['_malloc'] = createExportWrapper('malloc', 1)); + var _free = (Module['_free'] = createExportWrapper('free', 1)); + var _fflush = createExportWrapper('fflush', 1); + var _BZ2_bzBuffToBuffCompress = (Module['_BZ2_bzBuffToBuffCompress'] = createExportWrapper('BZ2_bzBuffToBuffCompress', 7)); + var _BZ2_bzBuffToBuffDecompress = (Module['_BZ2_bzBuffToBuffDecompress'] = createExportWrapper('BZ2_bzBuffToBuffDecompress', 6)); + var _emscripten_stack_init = () => (_emscripten_stack_init = wasmExports['emscripten_stack_init'])(); + var _emscripten_stack_get_free = () => (_emscripten_stack_get_free = wasmExports['emscripten_stack_get_free'])(); + var _emscripten_stack_get_base = () => (_emscripten_stack_get_base = wasmExports['emscripten_stack_get_base'])(); + var _emscripten_stack_get_end = () => (_emscripten_stack_get_end = wasmExports['emscripten_stack_get_end'])(); + var __emscripten_stack_restore = a0 => (__emscripten_stack_restore = wasmExports['_emscripten_stack_restore'])(a0); + var __emscripten_stack_alloc = a0 => (__emscripten_stack_alloc = wasmExports['_emscripten_stack_alloc'])(a0); + var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports['emscripten_stack_get_current'])(); + var dynCall_jiji = (Module['dynCall_jiji'] = createExportWrapper('dynCall_jiji', 5)); + Module['setValue'] = setValue; + Module['getValue'] = getValue; + var missingLibrarySymbols = [ + 'writeI53ToI64', + 'writeI53ToI64Clamped', + 'writeI53ToI64Signaling', + 'writeI53ToU64Clamped', + 'writeI53ToU64Signaling', + 'readI53FromI64', + 'readI53FromU64', + 'convertI32PairToI53', + 'convertU32PairToI53', + 'stackAlloc', + 'getTempRet0', + 'setTempRet0', + 'zeroMemory', + 'isLeapYear', + 'ydayFromDate', + 'arraySum', + 'addDays', + 'inetPton4', + 'inetNtop4', + 'inetPton6', + 'inetNtop6', + 'readSockaddr', + 'writeSockaddr', + 'initRandomFill', + 'randomFill', + 'emscriptenLog', + 'readEmAsmArgs', + 'jstoi_q', + 'getExecutableName', + 'listenOnce', + 'autoResumeAudioContext', + 'dynCallLegacy', + 'getDynCaller', + 'dynCall', + 'handleException', + 'runtimeKeepalivePush', + 'runtimeKeepalivePop', + 'callUserCallback', + 'maybeExit', + 'asmjsMangle', + 'asyncLoad', + 'alignMemory', + 'mmapAlloc', + 'HandleAllocator', + 'getNativeTypeSize', + 'STACK_SIZE', + 'STACK_ALIGN', + 'POINTER_SIZE', + 'ASSERTIONS', + 'getCFunc', + 'ccall', + 'cwrap', + 'uleb128Encode', + 'sigToWasmTypes', + 'generateFuncType', + 'convertJsFunctionToWasm', + 'getEmptyTableSlot', + 'updateTableMap', + 'getFunctionAddress', + 'addFunction', + 'removeFunction', + 'reallyNegative', + 'unSign', + 'strLen', + 'reSign', + 'formatString', + 'stringToUTF8Array', + 'stringToUTF8', + 'lengthBytesUTF8', + 'intArrayFromString', + 'intArrayToString', + 'AsciiToString', + 'stringToAscii', + 'UTF16ToString', + 'stringToUTF16', + 'lengthBytesUTF16', + 'UTF32ToString', + 'stringToUTF32', + 'lengthBytesUTF32', + 'stringToNewUTF8', + 'stringToUTF8OnStack', + 'writeArrayToMemory', + 'registerKeyEventCallback', + 'maybeCStringToJsString', + 'findEventTarget', + 'getBoundingClientRect', + 'fillMouseEventData', + 'registerMouseEventCallback', + 'registerWheelEventCallback', + 'registerUiEventCallback', + 'registerFocusEventCallback', + 'fillDeviceOrientationEventData', + 'registerDeviceOrientationEventCallback', + 'fillDeviceMotionEventData', + 'registerDeviceMotionEventCallback', + 'screenOrientation', + 'fillOrientationChangeEventData', + 'registerOrientationChangeEventCallback', + 'fillFullscreenChangeEventData', + 'registerFullscreenChangeEventCallback', + 'JSEvents_requestFullscreen', + 'JSEvents_resizeCanvasForFullscreen', + 'registerRestoreOldStyle', + 'hideEverythingExceptGivenElement', + 'restoreHiddenElements', + 'setLetterbox', + 'softFullscreenResizeWebGLRenderTarget', + 'doRequestFullscreen', + 'fillPointerlockChangeEventData', + 'registerPointerlockChangeEventCallback', + 'registerPointerlockErrorEventCallback', + 'requestPointerLock', + 'fillVisibilityChangeEventData', + 'registerVisibilityChangeEventCallback', + 'registerTouchEventCallback', + 'fillGamepadEventData', + 'registerGamepadEventCallback', + 'registerBeforeUnloadEventCallback', + 'fillBatteryEventData', + 'battery', + 'registerBatteryEventCallback', + 'setCanvasElementSize', + 'getCanvasElementSize', + 'jsStackTrace', + 'getCallstack', + 'convertPCtoSourceLocation', + 'getEnvStrings', + 'checkWasiClock', + 'wasiRightsToMuslOFlags', + 'wasiOFlagsToMuslOFlags', + 'createDyncallWrapper', + 'safeSetTimeout', + 'setImmediateWrapped', + 'clearImmediateWrapped', + 'polyfillSetImmediate', + 'getPromise', + 'makePromise', + 'idsToPromises', + 'makePromiseCallback', + 'ExceptionInfo', + 'findMatchingCatch', + 'Browser_asyncPrepareDataCounter', + 'setMainLoop', + 'getSocketFromFD', + 'getSocketAddress', + 'FS_createPreloadedFile', + 'FS_modeStringToFlags', + 'FS_getMode', + 'FS_stdin_getChar', + 'FS_createDataFile', + 'FS_unlink', + 'FS_mkdirTree', + '_setNetworkCallback', + 'heapObjectForWebGLType', + 'toTypedArrayIndex', + 'webgl_enable_ANGLE_instanced_arrays', + 'webgl_enable_OES_vertex_array_object', + 'webgl_enable_WEBGL_draw_buffers', + 'webgl_enable_WEBGL_multi_draw', + 'emscriptenWebGLGet', + 'computeUnpackAlignedImageSize', + 'colorChannelsInGlTextureFormat', + 'emscriptenWebGLGetTexPixelData', + 'emscriptenWebGLGetUniform', + 'webglGetUniformLocation', + 'webglPrepareUniformLocationsBeforeFirstUse', + 'webglGetLeftBracePos', + 'emscriptenWebGLGetVertexAttrib', + '__glGetActiveAttribOrUniform', + 'writeGLArray', + 'registerWebGlEventCallback', + 'runAndAbortIfError', + 'ALLOC_NORMAL', + 'ALLOC_STACK', + 'allocate', + 'writeStringToMemory', + 'writeAsciiToMemory', + 'setErrNo', + 'demangle', + 'stackTrace' + ]; + missingLibrarySymbols.forEach(missingLibrarySymbol); + var unexportedSymbols = [ + 'run', + 'addOnPreRun', + 'addOnInit', + 'addOnPreMain', + 'addOnExit', + 'addOnPostRun', + 'addRunDependency', + 'removeRunDependency', + 'FS_createFolder', + 'FS_createPath', + 'FS_createLazyFile', + 'FS_createLink', + 'FS_createDevice', + 'FS_readFile', + 'out', + 'err', + 'callMain', + 'abort', + 'wasmMemory', + 'wasmExports', + 'writeStackCookie', + 'checkStackCookie', + 'convertI32PairToI53Checked', + 'stackSave', + 'stackRestore', + 'ptrToString', + 'exitJS', + 'getHeapMax', + 'growMemory', + 'ENV', + 'MONTH_DAYS_REGULAR', + 'MONTH_DAYS_LEAP', + 'MONTH_DAYS_REGULAR_CUMULATIVE', + 'MONTH_DAYS_LEAP_CUMULATIVE', + 'ERRNO_CODES', + 'ERRNO_MESSAGES', + 'DNS', + 'Protocols', + 'Sockets', + 'timers', + 'warnOnce', + 'readEmAsmArgsArray', + 'jstoi_s', + 'keepRuntimeAlive', + 'wasmTable', + 'noExitRuntime', + 'freeTableIndexes', + 'functionsInTableMap', + 'PATH', + 'PATH_FS', + 'UTF8Decoder', + 'UTF8ArrayToString', + 'UTF8ToString', + 'UTF16Decoder', + 'JSEvents', + 'specialHTMLTargets', + 'findCanvasEventTarget', + 'currentFullscreenStrategy', + 'restoreOldWindowedStyle', + 'UNWIND_CACHE', + 'ExitStatus', + 'flush_NO_FILESYSTEM', + 'promiseMap', + 'uncaughtExceptionCount', + 'exceptionLast', + 'exceptionCaught', + 'Browser', + 'getPreloadedImageData__data', + 'wget', + 'SYSCALLS', + 'preloadPlugins', + 'FS_stdin_getChar_buffer', + 'FS', + 'MEMFS', + 'TTY', + 'PIPEFS', + 'SOCKFS', + 'tempFixedLengthArray', + 'miniTempWebGLFloatBuffers', + 'miniTempWebGLIntBuffers', + 'GL', + 'AL', + 'GLUT', + 'EGL', + 'GLEW', + 'IDBStore', + 'SDL', + 'SDL_gfx', + 'allocateUTF8', + 'allocateUTF8OnStack' + ]; + unexportedSymbols.forEach(unexportedRuntimeSymbol); + var calledRun; + dependenciesFulfilled = function runCaller() { + if (!calledRun) run2(); + if (!calledRun) dependenciesFulfilled = runCaller; + }; + function stackCheckInit() { + _emscripten_stack_init(); + writeStackCookie(); + } + function run2() { + if (runDependencies > 0) { + return; + } + stackCheckInit(); + preRun(); + if (runDependencies > 0) { + return; + } + function doRun() { + if (calledRun) return; + calledRun = true; + Module['calledRun'] = true; + if (ABORT) return; + initRuntime(); + readyPromiseResolve(Module); + if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized'](); + assert(!Module['_main'], 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'); + postRun(); + } + if (Module['setStatus']) { + Module['setStatus']('Running...'); + setTimeout(function () { + setTimeout(function () { + Module['setStatus'](''); + }, 1); + doRun(); + }, 1); + } else { + doRun(); + } + checkStackCookie(); + } + function checkUnflushedContent() { + var oldOut = out; + var oldErr = err; + var has = false; + out = err = x => { + has = true; + }; + try { + flush_NO_FILESYSTEM(); + } catch (e) {} + out = oldOut; + err = oldErr; + if (has) { + warnOnce('stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the Emscripten FAQ), or make sure to emit a newline when you printf etc.'); + warnOnce('(this may also be due to not including full filesystem support - try building with -sFORCE_FILESYSTEM)'); + } + } + if (Module['preInit']) { + if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']]; + while (Module['preInit'].length > 0) { + Module['preInit'].pop()(); + } + } + run2(); + moduleRtn = readyPromise; + for (const prop of Object.keys(Module)) { + if (!(prop in moduleArg)) { + Object.defineProperty(moduleArg, prop, { + configurable: true, + get() { + abort(`Access to module property ('${prop}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`); + } + }); + } + } + return moduleRtn; + }; +})(); +var bzip2_default = loadBZip2WASM; + +// src/3rdparty/bzip2-wasm/bzip2-wasm.js +var ERROR_MESSAGES = { + '-2': 'BZ_PARAM_ERROR: incorrect parameters', + '-3': "BZ_MEM_ERROR: couldn't allocate enough memory", + '-4': 'BZ_DATA_ERROR: data integrity error when decompressing', + '-5': 'BZ_DATA_ERROR_MAGIC: compressed data has incorrect header', + '-7': 'BZ_UNEXPECTED_EOF: compressed data ends too early', + '-8': 'BZ_OUTBUFF_FULL: destination buffer is full' +}; + +class BZip2 { + constructor() { + this.wasmModule = undefined; + } + async init() { + if (this.wasmModule) { + return; + } + if (typeof process !== 'undefined') { + const {dirname} = await Promise.resolve().then(() => (init_path(), exports_path)); + const {createRequire} = await import('module'); + globalThis.__dirname = dirname(import.meta.url); + globalThis.require = createRequire(import.meta.url); + } + this.wasmModule = await bzip2_default(); + } + ensureInitialized() { + if (!this.wasmModule) { + throw new Error(`${this.constructor.name} not initalized. call .init()`); + } + } + handleError(returnValue, destPtr, destLengthPtr) { + if (returnValue === 0) { + return; + } + this.wasmModule._free(destPtr); + this.wasmModule._free(destLengthPtr); + const errorMessage = ERROR_MESSAGES[returnValue]; + if (errorMessage) { + throw new Error(errorMessage); + } + throw new Error(`error code: ${returnValue}`); + } + createWASMBuffers(source, destLength) { + const {_malloc, setValue, HEAPU8} = this.wasmModule; + const sourcePtr = _malloc(source.length); + HEAPU8.set(source, sourcePtr); + const destPtr = _malloc(destLength); + const destLengthPtr = _malloc(destLength); + setValue(destLengthPtr, destLength, 'i32'); + return {sourcePtr, destPtr, destLengthPtr}; + } + createBuffer(destPtr, destLengthPtr) { + const {_free, getValue, HEAPU8} = this.wasmModule; + const destLength = getValue(destLengthPtr, 'i32'); + const dest = new Uint8Array(destLength); + dest.set(HEAPU8.subarray(destPtr, destPtr + destLength)); + _free(destPtr); + _free(destLengthPtr); + return dest; + } + decompress(compressed, decompressedLength, prependHeader = false, containsDecompressedLength = false) { + if (containsDecompressedLength) { + decompressedLength = (compressed[0] << 24) | (compressed[1] << 16) | (compressed[2] << 8) | compressed[3]; + compressed[0] = 'B'.charCodeAt(0); + compressed[1] = 'Z'.charCodeAt(0); + compressed[2] = 'h'.charCodeAt(0); + compressed[3] = '1'.charCodeAt(0); + prependHeader = false; + } + if (prependHeader) { + const temp = new Uint8Array(compressed.length + 4); + temp[0] = 'B'.charCodeAt(0); + temp[1] = 'Z'.charCodeAt(0); + temp[2] = 'h'.charCodeAt(0); + temp[3] = '1'.charCodeAt(0); + temp.set(compressed, 4); + compressed = temp; + } + this.ensureInitialized(); + const {sourcePtr: compressedPtr, destPtr: decompressedPtr, destLengthPtr: decompressedLengthPtr} = this.createWASMBuffers(compressed, decompressedLength); + const returnValue = this.wasmModule._BZ2_bzBuffToBuffDecompress(decompressedPtr, decompressedLengthPtr, compressedPtr, compressed.length, 0, 0); + this.wasmModule._free(compressedPtr); + this.handleError(returnValue, decompressedPtr, decompressedLengthPtr); + return this.createBuffer(decompressedPtr, decompressedLengthPtr); + } + compress(decompressed, prefixLength = false, removeHeader = false, blockSize = 1, compressedLength = 0) { + this.ensureInitialized(); + if (!compressedLength) { + compressedLength = decompressed.length + 1024; + } + if (compressedLength < 128) { + compressedLength = 128; + } + if (blockSize <= 0 || blockSize > 9) { + throw new RangeError('blockSize should be between 1-9'); + } + const {sourcePtr: decompressedPtr, destPtr: compressedPtr, destLengthPtr: compressedLengthPtr} = this.createWASMBuffers(decompressed, compressedLength); + const returnValue = this.wasmModule._BZ2_bzBuffToBuffCompress(compressedPtr, compressedLengthPtr, decompressedPtr, decompressed.length, blockSize, 0, 30); + this.wasmModule._free(decompressedPtr); + this.handleError(returnValue, compressedPtr, compressedLengthPtr); + const buf = this.createBuffer(compressedPtr, compressedLengthPtr); + if (prefixLength) { + buf[0] = (decompressed.length >> 24) & 255; + buf[1] = (decompressed.length >> 16) & 255; + buf[2] = (decompressed.length >> 8) & 255; + buf[3] = decompressed.length & 255; + } + if (removeHeader) { + return buf.subarray(4); + } + return buf; + } +} +var bzip2_wasm_default = BZip2; + +// src/jagex2/io/BZip2.ts +var bzip22 = new bzip2_wasm_default(); +await bzip22.init(); +var BZip2_default = bzip22; + +// src/jagex2/io/Jagfile.ts +function genHash(name) { + let hash = 0; + name = name.toUpperCase(); + for (let i = 0; i < name.length; i++) { + hash = (hash * 61 + name.charCodeAt(i) - 32) | 0; + } + return hash; +} + +class Jagfile { + data = null; + fileCount = 0; + fileHash = []; + fileName = []; + fileUnpackedSize = []; + filePackedSize = []; + filePos = []; + unpacked = false; + fileQueue = []; + fileWrite = []; + static load(path) { + return new Jagfile(Packet.load(path)); + } + static async loadAsync(path) { + return new Jagfile(await Packet.loadAsync(path)); + } + constructor(src) { + if (!src) { + return; + } + const unpackedSize = src.g3(); + const packedSize = src.g3(); + if (unpackedSize === packedSize) { + this.data = new Uint8Array(src.data); + this.unpacked = false; + } else { + this.data = BZip2_default.decompress(src.data, unpackedSize, true); + src = new Packet(this.data); + this.unpacked = true; + } + this.fileCount = src.g2(); + let pos = src.pos + this.fileCount * 10; + for (let i = 0; i < this.fileCount; i++) { + this.fileHash[i] = src.g4(); + const hashMatch = KNOWN_HASHES.findIndex(x => x === this.fileHash[i]); + if (hashMatch !== -1) { + this.fileName[i] = KNOWN_NAMES[hashMatch]; + } + this.fileUnpackedSize[i] = src.g3(); + this.filePackedSize[i] = src.g3(); + this.filePos[i] = pos; + pos += this.filePackedSize[i]; + } + } + get(index) { + if (index < 0 || index >= this.fileCount) { + return null; + } + if (this.data === null) { + throw new Error('Jagfile data is not loaded'); + } + const src = this.data.subarray(this.filePos[index], this.filePos[index] + this.filePackedSize[index]); + if (this.unpacked) { + return new Packet(src); + } else { + return new Packet(BZip2_default.decompress(src, this.fileUnpackedSize[index], true)); + } + } + read(name) { + const hash = genHash(name); + for (let i = 0; i < this.fileCount; i++) { + if (this.fileHash[i] === hash) { + return this.get(i); + } + } + return null; + } + write(name, data) { + const hash = genHash(name); + this.fileQueue.push({hash, name, write: true, data: data.data.subarray(0, data.pos)}); + } + delete(name) { + const hash = genHash(name); + this.fileQueue.push({hash, name, delete: true}); + } + rename(oldName, newName) { + const oldHash = genHash(oldName); + const newHash = genHash(newName); + this.fileQueue.push({ + hash: oldHash, + name: oldName, + rename: true, + newName, + newHash + }); + } + save(path, doNotCompressWhole = false) { + let buf = Packet.alloc(5); + for (let i = 0; i < this.fileQueue.length; i++) { + const queued = this.fileQueue[i]; + let index = this.fileHash.findIndex(x => x === queued.hash); + if (queued.write) { + if (index === -1) { + index = this.fileCount++; + this.fileHash[index] = queued.hash; + this.fileName[index] = queued.name; + } + if (!queued.data) { + throw new Error('Cannot write without data'); + } + this.fileUnpackedSize[index] = queued.data.length; + this.filePackedSize[index] = queued.data.length; + this.filePos[index] = -1; + this.fileWrite[index] = queued.data; + } + if (queued.delete && index !== -1) { + this.fileHash.splice(index, 1); + this.fileName.splice(index, 1); + this.fileUnpackedSize.splice(index, 1); + this.filePackedSize.splice(index, 1); + this.filePos.splice(index, 1); + this.fileCount--; + } + if (queued.rename && index !== -1) { + if (!queued.newHash) { + throw new Error('Cannot rename without newHash'); + } + if (!queued.newName) { + throw new Error('Cannot rename without newName'); + } + this.fileHash[index] = queued.newHash; + this.fileName[index] = queued.newName; + } + this.fileQueue.splice(i, 1); + i--; + } + let compressWhole = this.fileCount === 1; + if (doNotCompressWhole && compressWhole) { + compressWhole = false; + } + buf.p2(this.fileCount); + for (let i = 0; i < this.fileCount; i++) { + buf.p4(this.fileHash[i]); + buf.p3(this.fileUnpackedSize[i]); + if (this.fileWrite[i] && !compressWhole) { + this.fileWrite[i] = BZip2_default.compress(this.fileWrite[i], false, true); + this.filePackedSize[i] = this.fileWrite[i].length; + } + buf.p3(this.filePackedSize[i]); + } + for (let i = 0; i < this.fileCount; i++) { + const data = this.fileWrite[i]; + buf.pdata(data, 0, data.length); + } + const jag = Packet.alloc(5); + jag.p3(buf.pos); + if (compressWhole) { + buf = new Packet(BZip2_default.compress(buf.data, false, true)); + } + if (compressWhole) { + jag.p3(buf.data.length); + jag.pdata(buf.data, 0, buf.data.length); + } else { + jag.p3(buf.pos); + jag.pdata(buf.data, 0, buf.pos); + } + jag.save(path); + buf.release(); + jag.release(); + } + deconstruct(name) { + const dat = this.read(name + '.dat'); + const idx = this.read(name + '.idx'); + if (dat === null || idx === null) { + throw new Error('Failed to read dat or idx'); + } + const count = idx.g2(); + const sizes = new Array(count); + const offsets = new Array(count); + let offset = 2; + for (let i = 0; i < count; i++) { + sizes[i] = idx.g2(); + offsets[i] = offset; + offset += sizes[i]; + } + const checksums = new Array(count); + for (let i = 0; i < count; i++) { + dat.pos = offsets[i]; + checksums[i] = Packet.getcrc(dat.data, offset, sizes[i]); + } + return {count, sizes, offsets, checksums}; + } +} +var KNOWN_NAMES = [ + 'index.dat', + 'logo.dat', + 'p11.dat', + 'p12.dat', + 'b12.dat', + 'q8.dat', + 'runes.dat', + 'title.dat', + 'titlebox.dat', + 'titlebutton.dat', + 'p11_full.dat', + 'p12_full.dat', + 'b12_full.dat', + 'q8_full.dat', + 'flo.dat', + 'flo.idx', + 'idk.dat', + 'idk.idx', + 'loc.dat', + 'loc.idx', + 'npc.dat', + 'npc.idx', + 'obj.dat', + 'obj.idx', + 'seq.dat', + 'seq.idx', + 'spotanim.dat', + 'spotanim.idx', + 'varp.dat', + 'varp.idx', + 'varbit.dat', + 'varbit.idx', + 'mesanim.dat', + 'mesanim.idx', + 'mes.dat', + 'mes.idx', + 'param.dat', + 'param.idx', + 'hunt.dat', + 'hunt.idx', + 'data', + 'backbase1.dat', + 'backbase2.dat', + 'backhmid1.dat', + 'backhmid2.dat', + 'backleft1.dat', + 'backleft2.dat', + 'backright1.dat', + 'backright2.dat', + 'backtop1.dat', + 'backtop2.dat', + 'backvmid1.dat', + 'backvmid2.dat', + 'backvmid3.dat', + 'chatback.dat', + 'combatboxes.dat', + 'combaticons.dat', + 'combaticons2.dat', + 'combaticons3.dat', + 'compass.dat', + 'cross.dat', + 'gnomeball_buttons.dat', + 'headicons.dat', + 'hitmarks.dat', + 'invback.dat', + 'leftarrow.dat', + 'magicoff.dat', + 'magicoff2.dat', + 'magicon.dat', + 'magicon2.dat', + 'mapback.dat', + 'mapdots.dat', + 'mapflag.dat', + 'mapfunction.dat', + 'mapscene.dat', + 'miscgraphics.dat', + 'miscgraphics2.dat', + 'miscgraphics3.dat', + 'prayerglow.dat', + 'prayeroff.dat', + 'prayeron.dat', + 'redstone1.dat', + 'redstone2.dat', + 'redstone3.dat', + 'rightarrow.dat', + 'scrollbar.dat', + 'sideicons.dat', + 'staticons.dat', + 'staticons2.dat', + 'steelborder.dat', + 'steelborder2.dat', + 'sworddecor.dat', + 'tradebacking.dat', + 'wornicons.dat', + 'mapmarker.dat', + 'mod_icons.dat', + 'mapedge.dat', + 'blackmark.dat', + 'button_brown.dat', + 'button_brown_big.dat', + 'button_red.dat', + 'chest.dat', + 'coins.dat', + 'headicons_hint.dat', + 'headicons_pk.dat', + 'headicons_prayer.dat', + 'key.dat', + 'keys.dat', + 'leftarrow_small.dat', + 'letter.dat', + 'number_button.dat', + 'overlay_duel.dat', + 'overlay_multiway.dat', + 'pen.dat', + 'rightarrow_small.dat', + 'startgame.dat', + 'tex_brown.dat', + 'tex_red.dat', + 'titlescroll.dat', + 'base_head.dat', + 'base_label.dat', + 'base_type.dat', + 'frame_del.dat', + 'frame_head.dat', + 'frame_tran1.dat', + 'frame_tran2.dat', + 'ob_axis.dat', + 'ob_face1.dat', + 'ob_face2.dat', + 'ob_face3.dat', + 'ob_face4.dat', + 'ob_face5.dat', + 'ob_head.dat', + 'ob_point1.dat', + 'ob_point2.dat', + 'ob_point3.dat', + 'ob_point4.dat', + 'ob_point5.dat', + 'ob_vertex1.dat', + 'ob_vertex2.dat', + 'anim_crc', + 'anim_index', + 'anim_version', + 'map_crc', + 'map_index', + 'map_version', + 'midi_crc', + 'midi_index', + 'midi_version', + 'model_crc', + 'model_index', + 'model_version', + '0.dat', + '1.dat', + '2.dat', + '3.dat', + '4.dat', + '5.dat', + '6.dat', + '7.dat', + '8.dat', + '9.dat', + '10.dat', + '11.dat', + '12.dat', + '13.dat', + '14.dat', + '15.dat', + '16.dat', + '17.dat', + '18.dat', + '19.dat', + '20.dat', + '21.dat', + '22.dat', + '23.dat', + '24.dat', + '25.dat', + '26.dat', + '27.dat', + '28.dat', + '29.dat', + '30.dat', + '31.dat', + '32.dat', + '33.dat', + '34.dat', + '35.dat', + '36.dat', + '37.dat', + '38.dat', + '39.dat', + '40.dat', + '41.dat', + '42.dat', + '43.dat', + '44.dat', + '45.dat', + '46.dat', + '47.dat', + '48.dat', + '49.dat', + 'badenc.txt', + 'domainenc.txt', + 'fragmentsenc.txt', + 'tldlist.txt', + 'sounds.dat', + 'labels.dat', + 'floorcol.dat', + 'underlay.dat', + 'overlay.dat', + 'size.dat' +]; +var KNOWN_HASHES = []; +for (let i = 0; i < KNOWN_NAMES.length; i++) { + KNOWN_HASHES[i] = genHash(KNOWN_NAMES[i]); +} + +// src/lostcity/cache/config/FontType.ts +class FontType { + static CHAR_LOOKUP = []; + static instances = []; + static { + const charset = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!"\xA3$%^&*()-_=+[{]};:'@#~,<.>/?\\| `; + for (let i = 0; i < 256; i++) { + let c = charset.indexOf(String.fromCharCode(i)); + if (c == -1) { + c = 74; + } + FontType.CHAR_LOOKUP[i] = c; + } + } + static load(dir) { + const title = Jagfile.load(`${dir}/client/title`); + FontType.instances[0] = new FontType(title, 'p11'); + FontType.instances[1] = new FontType(title, 'p12'); + FontType.instances[2] = new FontType(title, 'b12'); + FontType.instances[3] = new FontType(title, 'q8'); + } + static async loadAsync(dir) { + const title = await Jagfile.loadAsync(`${dir}/client/title`); + FontType.instances[0] = new FontType(title, 'p11'); + FontType.instances[1] = new FontType(title, 'p12'); + FontType.instances[2] = new FontType(title, 'b12'); + FontType.instances[3] = new FontType(title, 'q8'); + } + static get(id) { + return FontType.instances[id]; + } + static get count() { + return this.instances.length; + } + charMask = new Array(94); + charMaskWidth = new Uint8Array(94); + charMaskHeight = new Uint8Array(94); + charOffsetX = new Uint8Array(94); + charOffsetY = new Uint8Array(94); + charAdvance = new Uint8Array(95); + drawWidth = new Uint8Array(256); + height = 0; + constructor(title, font) { + const dat = title.read(`${font}.dat`); + const idx = title.read('index.dat'); + if (!dat || !idx) { + return; + } + idx.pos = dat.g2() + 4; + const off = idx.g1(); + if (off > 0) { + idx.pos += (off - 1) * 3; + } + for (let i = 0; i < 94; i++) { + this.charOffsetX[i] = idx.g1(); + this.charOffsetY[i] = idx.g1(); + const w = (this.charMaskWidth[i] = idx.g2()); + const h2 = (this.charMaskHeight[i] = idx.g2()); + const type = idx.g1(); + const len = w * h2; + this.charMask[i] = new Uint8Array(len); + if (type == 0) { + for (let j = 0; j < len; j++) { + this.charMask[i][j] = dat.g1(); + } + } else if (type == 1) { + for (let x = 0; x < w; x++) { + for (let y3 = 0; y3 < h2; y3++) { + this.charMask[i][x + y3 * w] = dat.g1(); + } + } + } + if (h2 > this.height) { + this.height = h2; + } + this.charOffsetX[i] = 1; + this.charAdvance[i] = w + 2; + let space = 0; + for (let y3 = Math.floor(h2 / 7); y3 < h2; y3++) { + space += this.charMask[i][y3 * w]; + } + if (space <= Math.floor(h2 / 7)) { + this.charAdvance[i]--; + this.charOffsetX[i] = 0; + } + space = 0; + for (let y3 = Math.floor(h2 / 7); y3 < h2; y3++) { + space += this.charMask[i][w + y3 * w - 1]; + } + if (space <= Math.floor(h2 / 7)) { + this.charAdvance[i]--; + } + } + this.charAdvance[94] = this.charAdvance[8]; + for (let c = 0; c < 256; c++) { + this.drawWidth[c] = this.charAdvance[FontType.CHAR_LOOKUP[c]]; + } + } + stringWidth(str) { + if (str == null) { + return 0; + } + let size = 0; + for (let c = 0; c < str.length; c++) { + if (str.charAt(c) == '@' && c + 4 < str.length && str.charAt(c + 4) == '@') { + c += 4; + } else { + size += this.drawWidth[str.charCodeAt(c)]; + } + } + return size; + } + split(str, maxWidth) { + if (str.length === 0) { + return [str]; + } + const lines = []; + while (str.length > 0) { + const width = this.stringWidth(str); + if (width <= maxWidth && str.indexOf('|') === -1) { + lines.push(str); + break; + } + let splitIndex = str.length; + for (let i = 0; i < str.length; i++) { + if (str[i] === ' ') { + const w = this.stringWidth(str.substring(0, i)); + if (w > maxWidth) { + break; + } + splitIndex = i; + } else if (str[i] === '|') { + splitIndex = i; + break; + } + } + lines.push(str.substring(0, splitIndex)); + str = str.substring(splitIndex + 1); + } + return lines; + } +} + +// src/lostcity/cache/config/HuntType.ts +var {default: fs6} = () => ({}); + +// src/lostcity/entity/hunt/HuntCheckNotTooStrong.ts +var HuntCheckNotTooStrong; +(HuntCheckNotTooStrong2 => { + HuntCheckNotTooStrong2[(HuntCheckNotTooStrong2['OFF'] = 0)] = 'OFF'; + HuntCheckNotTooStrong2[(HuntCheckNotTooStrong2['OUTSIDE_WILDERNESS'] = 1)] = 'OUTSIDE_WILDERNESS'; +})((HuntCheckNotTooStrong ||= {})); +var HuntCheckNotTooStrong_default = HuntCheckNotTooStrong; + +// src/lostcity/entity/hunt/HuntModeType.ts +var HuntModeType; +(HuntModeType2 => { + HuntModeType2[(HuntModeType2['OFF'] = 0)] = 'OFF'; + HuntModeType2[(HuntModeType2['PLAYER'] = 1)] = 'PLAYER'; + HuntModeType2[(HuntModeType2['NPC'] = 2)] = 'NPC'; + HuntModeType2[(HuntModeType2['OBJ'] = 3)] = 'OBJ'; + HuntModeType2[(HuntModeType2['SCENERY'] = 4)] = 'SCENERY'; +})((HuntModeType ||= {})); +var HuntModeType_default = HuntModeType; + +// src/lostcity/entity/hunt/HuntNobodyNear.ts +var HuntNobodyNear; +(HuntNobodyNear2 => { + HuntNobodyNear2[(HuntNobodyNear2['KEEPHUNTING'] = 0)] = 'KEEPHUNTING'; + HuntNobodyNear2[(HuntNobodyNear2['PAUSEHUNT'] = 1)] = 'PAUSEHUNT'; +})((HuntNobodyNear ||= {})); +var HuntNobodyNear_default = HuntNobodyNear; + +// src/lostcity/entity/hunt/HuntVis.ts +var HuntVis; +(HuntVis2 => { + HuntVis2[(HuntVis2['OFF'] = 0)] = 'OFF'; + HuntVis2[(HuntVis2['LINEOFSIGHT'] = 1)] = 'LINEOFSIGHT'; + HuntVis2[(HuntVis2['LINEOFWALK'] = 2)] = 'LINEOFWALK'; +})((HuntVis ||= {})); +var HuntVis_default = HuntVis; + +// src/lostcity/entity/NpcMode.ts +var NpcMode; +(NpcMode2 => { + NpcMode2[(NpcMode2['NULL'] = -1)] = 'NULL'; + NpcMode2[(NpcMode2['NONE'] = 0)] = 'NONE'; + NpcMode2[(NpcMode2['WANDER'] = 1)] = 'WANDER'; + NpcMode2[(NpcMode2['PATROL'] = 2)] = 'PATROL'; + NpcMode2[(NpcMode2['PLAYERESCAPE'] = 3)] = 'PLAYERESCAPE'; + NpcMode2[(NpcMode2['PLAYERFOLLOW'] = 4)] = 'PLAYERFOLLOW'; + NpcMode2[(NpcMode2['PLAYERFACE'] = 5)] = 'PLAYERFACE'; + NpcMode2[(NpcMode2['PLAYERFACECLOSE'] = 6)] = 'PLAYERFACECLOSE'; + NpcMode2[(NpcMode2['OPPLAYER1'] = 7)] = 'OPPLAYER1'; + NpcMode2[(NpcMode2['OPPLAYER2'] = 8)] = 'OPPLAYER2'; + NpcMode2[(NpcMode2['OPPLAYER3'] = 9)] = 'OPPLAYER3'; + NpcMode2[(NpcMode2['OPPLAYER4'] = 10)] = 'OPPLAYER4'; + NpcMode2[(NpcMode2['OPPLAYER5'] = 11)] = 'OPPLAYER5'; + NpcMode2[(NpcMode2['APPLAYER1'] = 12)] = 'APPLAYER1'; + NpcMode2[(NpcMode2['APPLAYER2'] = 13)] = 'APPLAYER2'; + NpcMode2[(NpcMode2['APPLAYER3'] = 14)] = 'APPLAYER3'; + NpcMode2[(NpcMode2['APPLAYER4'] = 15)] = 'APPLAYER4'; + NpcMode2[(NpcMode2['APPLAYER5'] = 16)] = 'APPLAYER5'; + NpcMode2[(NpcMode2['OPLOC1'] = 17)] = 'OPLOC1'; + NpcMode2[(NpcMode2['OPLOC2'] = 18)] = 'OPLOC2'; + NpcMode2[(NpcMode2['OPLOC3'] = 19)] = 'OPLOC3'; + NpcMode2[(NpcMode2['OPLOC4'] = 20)] = 'OPLOC4'; + NpcMode2[(NpcMode2['OPLOC5'] = 21)] = 'OPLOC5'; + NpcMode2[(NpcMode2['APLOC1'] = 22)] = 'APLOC1'; + NpcMode2[(NpcMode2['APLOC2'] = 23)] = 'APLOC2'; + NpcMode2[(NpcMode2['APLOC3'] = 24)] = 'APLOC3'; + NpcMode2[(NpcMode2['APLOC4'] = 25)] = 'APLOC4'; + NpcMode2[(NpcMode2['APLOC5'] = 26)] = 'APLOC5'; + NpcMode2[(NpcMode2['OPOBJ1'] = 27)] = 'OPOBJ1'; + NpcMode2[(NpcMode2['OPOBJ2'] = 28)] = 'OPOBJ2'; + NpcMode2[(NpcMode2['OPOBJ3'] = 29)] = 'OPOBJ3'; + NpcMode2[(NpcMode2['OPOBJ4'] = 30)] = 'OPOBJ4'; + NpcMode2[(NpcMode2['OPOBJ5'] = 31)] = 'OPOBJ5'; + NpcMode2[(NpcMode2['APOBJ1'] = 32)] = 'APOBJ1'; + NpcMode2[(NpcMode2['APOBJ2'] = 33)] = 'APOBJ2'; + NpcMode2[(NpcMode2['APOBJ3'] = 34)] = 'APOBJ3'; + NpcMode2[(NpcMode2['APOBJ4'] = 35)] = 'APOBJ4'; + NpcMode2[(NpcMode2['APOBJ5'] = 36)] = 'APOBJ5'; + NpcMode2[(NpcMode2['OPNPC1'] = 37)] = 'OPNPC1'; + NpcMode2[(NpcMode2['OPNPC2'] = 38)] = 'OPNPC2'; + NpcMode2[(NpcMode2['OPNPC3'] = 39)] = 'OPNPC3'; + NpcMode2[(NpcMode2['OPNPC4'] = 40)] = 'OPNPC4'; + NpcMode2[(NpcMode2['OPNPC5'] = 41)] = 'OPNPC5'; + NpcMode2[(NpcMode2['APNPC1'] = 42)] = 'APNPC1'; + NpcMode2[(NpcMode2['APNPC2'] = 43)] = 'APNPC2'; + NpcMode2[(NpcMode2['APNPC3'] = 44)] = 'APNPC3'; + NpcMode2[(NpcMode2['APNPC4'] = 45)] = 'APNPC4'; + NpcMode2[(NpcMode2['APNPC5'] = 46)] = 'APNPC5'; + NpcMode2[(NpcMode2['QUEUE1'] = 47)] = 'QUEUE1'; + NpcMode2[(NpcMode2['QUEUE2'] = 48)] = 'QUEUE2'; + NpcMode2[(NpcMode2['QUEUE3'] = 49)] = 'QUEUE3'; + NpcMode2[(NpcMode2['QUEUE4'] = 50)] = 'QUEUE4'; + NpcMode2[(NpcMode2['QUEUE5'] = 51)] = 'QUEUE5'; + NpcMode2[(NpcMode2['QUEUE6'] = 52)] = 'QUEUE6'; + NpcMode2[(NpcMode2['QUEUE7'] = 53)] = 'QUEUE7'; + NpcMode2[(NpcMode2['QUEUE8'] = 54)] = 'QUEUE8'; + NpcMode2[(NpcMode2['QUEUE9'] = 55)] = 'QUEUE9'; + NpcMode2[(NpcMode2['QUEUE10'] = 56)] = 'QUEUE10'; + NpcMode2[(NpcMode2['QUEUE11'] = 57)] = 'QUEUE11'; + NpcMode2[(NpcMode2['QUEUE12'] = 58)] = 'QUEUE12'; + NpcMode2[(NpcMode2['QUEUE13'] = 59)] = 'QUEUE13'; + NpcMode2[(NpcMode2['QUEUE14'] = 60)] = 'QUEUE14'; + NpcMode2[(NpcMode2['QUEUE15'] = 61)] = 'QUEUE15'; + NpcMode2[(NpcMode2['QUEUE16'] = 62)] = 'QUEUE16'; + NpcMode2[(NpcMode2['QUEUE17'] = 63)] = 'QUEUE17'; + NpcMode2[(NpcMode2['QUEUE18'] = 64)] = 'QUEUE18'; + NpcMode2[(NpcMode2['QUEUE19'] = 65)] = 'QUEUE19'; + NpcMode2[(NpcMode2['QUEUE20'] = 66)] = 'QUEUE20'; +})((NpcMode ||= {})); +var NpcMode_default = NpcMode; + +// src/lostcity/cache/config/HuntType.ts +class HuntType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs6.existsSync(`${dir}/server/hunt.dat`)) { + console.log('Warning: No hunt.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/hunt.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/hunt.dat`)).ok) { + console.log('Warning: No hunt.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/hunt.dat`); + this.parse(dat); + } + static parse(dat) { + HuntType.configNames = new Map(); + HuntType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config = new HuntType(id); + config.decodeType(dat); + HuntType.configs[id] = config; + if (config.debugname) { + HuntType.configNames.set(config.debugname, id); + } + } + } + static get(id) { + return HuntType.configs[id]; + } + static getId(name) { + return HuntType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + type = HuntModeType_default.OFF; + checkVis = HuntVis_default.OFF; + checkNotTooStrong = HuntCheckNotTooStrong_default.OFF; + checkNotBusy = false; + findKeepHunting = false; + findNewMode = NpcMode_default.NONE; + nobodyNear = HuntNobodyNear_default.PAUSEHUNT; + checkNotCombat = -1; + checkNotCombatSelf = -1; + checkAfk = true; + rate = 1; + checkCategory = -1; + checkNpc = -1; + checkObj = -1; + checkLoc = -1; + checkInv = -1; + checkObjParam = -1; + checkInvMinQuantity = -1; + checkInvMaxQuantity = -1; + decode(code, dat) { + if (code === 1) { + this.type = dat.g1(); + } else if (code == 2) { + this.checkVis = dat.g1(); + } else if (code == 3) { + this.checkNotTooStrong = dat.g1(); + } else if (code == 4) { + this.checkNotBusy = true; + } else if (code == 5) { + this.findKeepHunting = true; + } else if (code == 6) { + this.findNewMode = dat.g1(); + } else if (code == 7) { + this.nobodyNear = dat.g1(); + } else if (code === 8) { + this.checkNotCombat = dat.g2(); + } else if (code === 9) { + this.checkNotCombatSelf = dat.g2(); + } else if (code === 10) { + this.checkAfk = false; + } else if (code === 11) { + this.rate = dat.g2(); + } else if (code === 12) { + this.checkCategory = dat.g2(); + } else if (code === 13) { + this.checkNpc = dat.g2(); + } else if (code === 14) { + this.checkObj = dat.g2(); + } else if (code === 15) { + this.checkLoc = dat.g2(); + } else if (code === 16) { + this.checkInv = dat.g2(); + this.checkObj = dat.g2(); + this.checkInvMinQuantity = dat.g4(); + this.checkInvMaxQuantity = dat.g4(); + } else if (code === 17) { + this.checkInv = dat.g2(); + this.checkObjParam = dat.g2(); + this.checkInvMinQuantity = dat.g4(); + this.checkInvMaxQuantity = dat.g4(); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized hunt config code: ${code}`); + } + } +} + +// src/lostcity/cache/config/IdkType.ts +var {default: fs7} = () => ({}); +class IdkType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs7.existsSync(`${dir}/server/idk.dat`)) { + console.log('Warning: No idk.dat found.'); + return; + } + const server = Packet.load(`${dir}/server/idk.dat`); + const jag = Jagfile.load(`${dir}/client/config`); + this.parse(server, jag); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/idk.dat`)).ok) { + console.log('Warning: No idk.dat found.'); + return; + } + const server = await Packet.loadAsync(`${dir}/server/idk.dat`); + const jag = await Jagfile.loadAsync(`${dir}/client/config`); + this.parse(server, jag); + } + static parse(server, jag) { + IdkType.configNames = new Map(); + IdkType.configs = []; + const count = server.g2(); + const client = jag.read('idk.dat'); + client.pos = 2; + for (let id = 0; id < count; id++) { + const config = new IdkType(id); + config.decodeType(server); + config.decodeType(client); + IdkType.configs[id] = config; + if (config.debugname) { + IdkType.configNames.set(config.debugname, id); + } + } + } + static get(id) { + return IdkType.configs[id]; + } + static getId(name) { + return IdkType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + type = -1; + models = null; + heads = new Uint16Array(5).fill(-1); + recol_s = new Uint16Array(6).fill(0); + recol_d = new Uint16Array(6).fill(0); + disable = false; + decode(code, dat) { + if (code === 1) { + this.type = dat.g1(); + } else if (code === 2) { + const count = dat.g1(); + this.models = new Uint16Array(count); + for (let i = 0; i < count; i++) { + this.models[i] = dat.g2(); + } + } else if (code === 3) { + this.disable = true; + } else if (code >= 40 && code < 50) { + this.recol_s[code - 40] = dat.g2(); + } else if (code >= 50 && code < 60) { + this.recol_d[code - 50] = dat.g2(); + } else if (code >= 60 && code < 70) { + this.heads[code - 60] = dat.g2(); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized idk config code: ${code}`); + } + } +} + +// src/lostcity/cache/config/Component.ts +var {default: fs8} = () => ({}); +class Component { + static TYPE_LAYER = 0; + static TYPE_UNUSED = 1; + static TYPE_INVENTORY = 2; + static TYPE_RECT = 3; + static TYPE_TEXT = 4; + static TYPE_SPRITE = 5; + static TYPE_MODEL = 6; + static TYPE_INVENTORY_TEXT = 7; + static NO_BUTTON = 0; + static BUTTON = 1; + static TARGET_BUTTON = 2; + static CLOSE_BUTTON = 3; + static TOGGLE_BUTTON = 4; + static SELECT_BUTTON = 5; + static PAUSE_BUTTON = 6; + static componentNames = new Map(); + static components = []; + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/interface.dat`)).ok) { + console.log('Warning: No interface.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/interface.dat`); + this.parse(dat); + } + static load(dir) { + if (!fs8.existsSync(`${dir}/server/interface.dat`)) { + console.log('Warning: No interface.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/interface.dat`); + this.parse(dat); + } + static parse(dat) { + this.componentNames = new Map(); + this.components = []; + dat.g2(); + let rootLayer = -1; + while (dat.available > 0) { + let id = dat.g2(); + if (id === 65535) { + rootLayer = dat.g2(); + id = dat.g2(); + } + const com = new Component(); + com.id = id; + com.rootLayer = rootLayer; + com.comName = dat.gjstr(); + com.overlay = dat.gbool(); + com.type = dat.g1(); + com.buttonType = dat.g1(); + com.clientCode = dat.g2(); + com.width = dat.g2(); + com.height = dat.g2(); + com.overLayer = dat.g1(); + if (com.overLayer == 0) { + com.overLayer = -1; + } else { + com.overLayer = ((com.overLayer - 1) << 8) + dat.g1(); + } + const comparatorCount = dat.g1(); + if (comparatorCount > 0) { + com.scriptComparator = new Uint8Array(comparatorCount).fill(0); + com.scriptOperand = new Uint16Array(comparatorCount).fill(0); + for (let i = 0; i < comparatorCount; i++) { + com.scriptComparator[i] = dat.g1(); + com.scriptOperand[i] = dat.g2(); + } + } + const scriptCount = dat.g1(); + if (scriptCount > 0) { + com.scripts = new Array(scriptCount).fill(null); + for (let i = 0; i < scriptCount; i++) { + const opcodeCount = dat.g2(); + com.scripts[i] = new Uint16Array(opcodeCount).fill(0); + for (let j = 0; j < opcodeCount; j++) { + com.scripts[i][j] = dat.g2(); + } + } + } + switch (com.type) { + case Component.TYPE_LAYER: { + com.scroll = dat.g2(); + com.hide = dat.gbool(); + const childCount = dat.g1(); + com.childId = new Uint16Array(childCount).fill(0); + com.childX = new Uint16Array(childCount).fill(0); + com.childY = new Uint16Array(childCount).fill(0); + for (let i = 0; i < childCount; i++) { + com.childId[i] = dat.g2(); + com.childX[i] = dat.g2s(); + com.childY[i] = dat.g2s(); + } + break; + } + case Component.TYPE_UNUSED: + dat.pos += 10; + break; + case Component.TYPE_INVENTORY: { + com.draggable = dat.gbool(); + com.interactable = dat.gbool(); + com.usable = dat.gbool(); + com.marginX = dat.g1(); + com.marginY = dat.g1(); + com.inventorySlotOffsetX = new Uint16Array(20).fill(0); + com.inventorySlotOffsetY = new Uint16Array(20).fill(0); + com.inventorySlotGraphic = new Array(20).fill(null); + for (let i = 0; i < 20; i++) { + if (dat.gbool()) { + com.inventorySlotOffsetX[i] = dat.g2s(); + com.inventorySlotOffsetY[i] = dat.g2s(); + com.inventorySlotGraphic[i] = dat.gjstr(); + } + } + com.inventoryOptions = new Array(5).fill(null); + for (let i = 0; i < 5; i++) { + com.inventoryOptions[i] = dat.gjstr(); + } + com.actionVerb = dat.gjstr(); + com.action = dat.gjstr(); + com.actionTarget = dat.g2(); + break; + } + case Component.TYPE_RECT: + com.fill = dat.gbool(); + com.colour = dat.g4(); + com.activeColour = dat.g4(); + com.overColour = dat.g4(); + break; + case Component.TYPE_TEXT: + com.center = dat.gbool(); + com.font = dat.g1(); + com.shadowed = dat.gbool(); + com.text = dat.gjstr(); + com.activeText = dat.gjstr(); + com.colour = dat.g4(); + com.activeColour = dat.g4(); + com.overColour = dat.g4(); + break; + case Component.TYPE_SPRITE: + com.graphic = dat.gjstr(); + com.activeGraphic = dat.gjstr(); + break; + case Component.TYPE_MODEL: { + com.model = dat.g1(); + if (com.model != 0) { + com.model = ((com.model - 1) << 8) + dat.g1(); + } + com.activeModel = dat.g1(); + if (com.activeModel != 0) { + com.activeModel = ((com.activeModel - 1) << 8) + dat.g1(); + } + com.anim = dat.g1(); + if (com.anim == 0) { + com.anim = -1; + } else { + com.anim = ((com.anim - 1) << 8) + dat.g1(); + } + com.activeAnim = dat.g1(); + if (com.activeAnim == 0) { + com.activeAnim = -1; + } else { + com.activeAnim = ((com.activeAnim - 1) << 8) + dat.g1(); + } + com.zoom = dat.g2(); + com.xan = dat.g2(); + com.yan = dat.g2(); + break; + } + case Component.TYPE_INVENTORY_TEXT: { + com.center = dat.gbool(); + com.font = dat.g1(); + com.shadowed = dat.gbool(); + com.colour = dat.g4(); + com.marginX = dat.g2s(); + com.marginY = dat.g2s(); + com.interactable = dat.gbool(); + com.inventoryOptions = new Array(5).fill(null); + for (let i = 0; i < 5; i++) { + com.inventoryOptions[i] = dat.gjstr(); + } + break; + } + } + switch (com.buttonType) { + case Component.NO_BUTTON: + break; + case Component.TARGET_BUTTON: + com.actionVerb = dat.gjstr(); + com.action = dat.gjstr(); + com.actionTarget = dat.g2(); + break; + case Component.BUTTON: + case Component.TOGGLE_BUTTON: + case Component.SELECT_BUTTON: + case Component.PAUSE_BUTTON: + com.option = dat.gjstr(); + break; + } + Component.components[id] = com; + if (com.comName) { + Component.componentNames.set(com.comName, id); + } + } + } + static get(id) { + return Component.components[id]; + } + static getId(name) { + return Component.componentNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + id = -1; + rootLayer = -1; + comName = null; + overlay = false; + type = -1; + buttonType = -1; + clientCode = 0; + width = 0; + height = 0; + overLayer = -1; + scriptComparator = null; + scriptOperand = null; + scripts = null; + scroll = 0; + hide = false; + draggable = false; + interactable = false; + usable = false; + marginX = 0; + marginY = 0; + inventorySlotOffsetX = null; + inventorySlotOffsetY = null; + inventorySlotGraphic = null; + inventoryOptions = null; + fill = false; + center = false; + font = 0; + shadowed = false; + text = null; + activeText = null; + colour = 0; + activeColour = 0; + overColour = 0; + graphic = null; + activeGraphic = null; + model = -1; + activeModel = -1; + anim = -1; + activeAnim = -1; + zoom = 0; + xan = 0; + yan = 0; + actionVerb = null; + action = null; + actionTarget = -1; + option = null; + childId = null; + childX = null; + childY = null; +} + +// src/lostcity/cache/config/InvType.ts +var {default: fs9} = () => ({}); +class InvType extends ConfigType { + static configNames = new Map(); + static configs = []; + static SCOPE_TEMP = 0; + static SCOPE_PERM = 1; + static SCOPE_SHARED = 2; + static INV = -1; + static WORN = -1; + static load(dir) { + if (!fs9.existsSync(`${dir}/server/inv.dat`)) { + console.log('Warning: No inv.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/inv.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/inv.dat`)).ok) { + console.log('Warning: No inv.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/inv.dat`); + this.parse(dat); + } + static parse(dat) { + InvType.configNames = new Map(); + InvType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config = new InvType(id); + config.decodeType(dat); + InvType.configs[id] = config; + if (config.debugname) { + InvType.configNames.set(config.debugname, id); + } + } + InvType.INV = InvType.getId('inv'); + InvType.WORN = InvType.getId('worn'); + } + static get(id) { + return InvType.configs[id]; + } + static getId(name) { + return InvType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + scope = 0; + size = 1; + stackall = false; + restock = false; + allstock = false; + stockobj = null; + stockcount = null; + stockrate = null; + protect = true; + runweight = false; + dummyinv = false; + decode(code, dat) { + if (code === 1) { + this.scope = dat.g1(); + } else if (code === 2) { + this.size = dat.g2(); + } else if (code === 3) { + this.stackall = true; + } else if (code === 4) { + const count = dat.g1(); + this.stockobj = new Uint16Array(count); + this.stockcount = new Uint16Array(count); + this.stockrate = new Int32Array(count); + for (let j = 0; j < count; j++) { + this.stockobj[j] = dat.g2(); + this.stockcount[j] = dat.g2(); + this.stockrate[j] = dat.g4(); + } + } else if (code === 5) { + this.restock = true; + } else if (code === 6) { + this.allstock = true; + } else if (code === 7) { + this.protect = false; + } else if (code === 8) { + this.runweight = true; + } else if (code === 9) { + this.dummyinv = true; + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized inv config code: ${code}`); + } + } +} + +// src/lostcity/cache/config/LocType.ts +var {default: fs10} = () => ({}); + +// src/lostcity/cache/config/ParamHelper.ts +var ParamHelper = { + getStringParam: function (id, holder, defaultValue) { + const value = holder.params?.get(id); + if (typeof value !== 'string') { + return defaultValue ?? 'null'; + } + return value; + }, + getIntParam: function (id, holder, defaultValue) { + const value = holder.params?.get(id); + if (typeof value !== 'number') { + return defaultValue; + } + return value; + }, + decodeParams: function (dat) { + const count = dat.g1(); + const params = new Map(); + for (let i = 0; i < count; i++) { + const key = dat.g3(); + const isString = dat.gbool(); + if (isString) { + params.set(key, dat.gjstr()); + } else { + params.set(key, dat.g4()); + } + } + return params; + } +}; + +// src/lostcity/cache/config/LocType.ts +class LocType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs10.existsSync(`${dir}/server/loc.dat`)) { + console.log('Warning: No loc.dat found.'); + return; + } + const server = Packet.load(`${dir}/server/loc.dat`); + const jag = Jagfile.load(`${dir}/client/config`); + this.parse(server, jag); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/loc.dat`)).ok) { + console.log('Warning: No loc.dat found.'); + return; + } + const server = await Packet.loadAsync(`${dir}/server/loc.dat`); + const jag = await Jagfile.loadAsync(`${dir}/client/config`); + this.parse(server, jag); + } + static parse(server, jag) { + LocType.configNames = new Map(); + LocType.configs = []; + const count = server.g2(); + const client = jag.read('loc.dat'); + client.pos = 2; + for (let id = 0; id < count; id++) { + const config = new LocType(id); + config.active = -1; + config.decodeType(server); + config.decodeType(client); + if (config.active === -1 && config.shapes) { + config.active = config.shapes.length > 0 && config.shapes[0] === 10 ? 1 : 0; + if (config.op && config.op.length > 0) { + config.active = 1; + } + } + LocType.configs[id] = config; + if (config.debugname) { + LocType.configNames.set(config.debugname, id); + } + } + } + static get(id) { + return LocType.configs[id]; + } + static getId(name) { + return LocType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === undefined || id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + models = null; + shapes = null; + name = null; + desc = null; + recol_s = null; + recol_d = null; + width = 1; + length = 1; + blockwalk = true; + blockrange = true; + active = 0; + hillskew = false; + sharelight = false; + occlude = false; + anim = -1; + hasalpha = false; + wallwidth = 16; + ambient = 0; + contrast = 0; + op = null; + mapfunction = -1; + mapscene = -1; + mirror = false; + shadow = true; + resizex = 128; + resizey = 128; + resizez = 128; + forceapproach = 0; + xoff = 0; + yoff = 0; + zoff = 0; + forcedecor = false; + category = -1; + params = new Map(); + decode(code, dat) { + if (code === 1) { + const count = dat.g1(); + this.models = new Uint16Array(count); + this.shapes = new Uint8Array(count); + for (let i = 0; i < count; i++) { + this.models[i] = dat.g2(); + this.shapes[i] = dat.g1(); + } + } else if (code === 2) { + this.name = dat.gjstr(); + } else if (code === 3) { + this.desc = dat.gjstr(); + } else if (code === 14) { + this.width = dat.g1(); + } else if (code === 15) { + this.length = dat.g1(); + } else if (code === 17) { + this.blockwalk = false; + } else if (code === 18) { + this.blockrange = false; + } else if (code === 19) { + this.active = dat.g1(); + } else if (code === 21) { + this.hillskew = true; + } else if (code === 22) { + this.sharelight = true; + } else if (code === 23) { + this.occlude = true; + } else if (code === 24) { + this.anim = dat.g2(); + if (this.anim == 65535) { + this.anim = -1; + } + } else if (code === 25) { + this.hasalpha = true; + } else if (code === 28) { + this.wallwidth = dat.g1(); + } else if (code === 29) { + this.ambient = dat.g1b(); + } else if (code === 39) { + this.contrast = dat.g1b(); + } else if (code >= 30 && code < 35) { + if (!this.op) { + this.op = new Array(5).fill(null); + } + this.op[code - 30] = dat.gjstr(); + if (this.op[code - 30] === 'hidden') { + this.op[code - 30] = null; + } + } else if (code === 40) { + const count = dat.g1(); + this.recol_s = new Uint16Array(count); + this.recol_d = new Uint16Array(count); + for (let i = 0; i < count; i++) { + this.recol_s[i] = dat.g2(); + this.recol_d[i] = dat.g2(); + } + } else if (code === 60) { + this.mapfunction = dat.g2(); + } else if (code === 62) { + this.mirror = true; + } else if (code === 64) { + this.shadow = false; + } else if (code === 65) { + this.resizex = dat.g2(); + } else if (code === 66) { + this.resizey = dat.g2(); + } else if (code === 67) { + this.resizez = dat.g2(); + } else if (code === 68) { + this.mapscene = dat.g2(); + } else if (code === 69) { + this.forceapproach = dat.g1(); + } else if (code === 70) { + this.xoff = dat.g2s(); + } else if (code === 71) { + this.yoff = dat.g2s(); + } else if (code === 72) { + this.zoff = dat.g2s(); + } else if (code === 73) { + this.forcedecor = true; + } else if (code === 200) { + this.category = dat.g2(); + } else if (code === 249) { + this.params = ParamHelper.decodeParams(dat); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized loc config code: ${code}`); + } + } +} + +// src/lostcity/cache/config/MesanimType.ts +var {default: fs11} = () => ({}); +class MesanimType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs11.existsSync(`${dir}/server/mesanim.dat`)) { + console.log('Warning: No mesanim.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/mesanim.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/mesanim.dat`)).ok) { + console.log('Warning: No mesanim.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/mesanim.dat`); + this.parse(dat); + } + static parse(dat) { + MesanimType.configNames = new Map(); + MesanimType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config = new MesanimType(id); + config.decodeType(dat); + MesanimType.configs[id] = config; + if (config.debugname) { + MesanimType.configNames.set(config.debugname, id); + } + } + } + static get(id) { + return MesanimType.configs[id]; + } + static getId(name) { + return MesanimType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + len = new Array(4).fill(-1); + decode(code, dat) { + if (code >= 1 && code < 5) { + this.len[code - 1] = dat.g2(); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized mesanim config code: ${code}`); + } + } +} + +// src/lostcity/cache/config/NpcType.ts +var {default: fs12} = () => ({}); + +// src/lostcity/entity/BlockWalk.ts +var BlockWalk; +(BlockWalk2 => { + BlockWalk2[(BlockWalk2['NONE'] = 0)] = 'NONE'; + BlockWalk2[(BlockWalk2['NPC'] = 1)] = 'NPC'; + BlockWalk2[(BlockWalk2['ALL'] = 2)] = 'ALL'; +})((BlockWalk ||= {})); +var BlockWalk_default = BlockWalk; + +// src/lostcity/entity/MoveRestrict.ts +var MoveRestrict; +(MoveRestrict2 => { + MoveRestrict2[(MoveRestrict2['NORMAL'] = 0)] = 'NORMAL'; + MoveRestrict2[(MoveRestrict2['BLOCKED'] = 1)] = 'BLOCKED'; + MoveRestrict2[(MoveRestrict2['BLOCKED_NORMAL'] = 2)] = 'BLOCKED_NORMAL'; + MoveRestrict2[(MoveRestrict2['INDOORS'] = 3)] = 'INDOORS'; + MoveRestrict2[(MoveRestrict2['OUTDOORS'] = 4)] = 'OUTDOORS'; + MoveRestrict2[(MoveRestrict2['NOMOVE'] = 5)] = 'NOMOVE'; + MoveRestrict2[(MoveRestrict2['PASSTHRU'] = 6)] = 'PASSTHRU'; +})((MoveRestrict ||= {})); +var MoveRestrict_default = MoveRestrict; + +// src/lostcity/entity/NpcStat.ts +var NpcStat; +(NpcStat2 => { + NpcStat2[(NpcStat2['ATTACK'] = 0)] = 'ATTACK'; + NpcStat2[(NpcStat2['DEFENCE'] = 1)] = 'DEFENCE'; + NpcStat2[(NpcStat2['STRENGTH'] = 2)] = 'STRENGTH'; + NpcStat2[(NpcStat2['HITPOINTS'] = 3)] = 'HITPOINTS'; + NpcStat2[(NpcStat2['RANGED'] = 4)] = 'RANGED'; + NpcStat2[(NpcStat2['MAGIC'] = 5)] = 'MAGIC'; +})((NpcStat ||= {})); +var NpcStat_default = NpcStat; + +// src/lostcity/cache/config/NpcType.ts +class NpcType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs12.existsSync(`${dir}/server/npc.dat`)) { + console.log('Warning: No npc.dat found.'); + return; + } + const server = Packet.load(`${dir}/server/npc.dat`); + const jag = Jagfile.load(`${dir}/client/config`); + this.parse(server, jag); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/npc.dat`)).ok) { + console.log('Warning: No npc.dat found.'); + return; + } + const server = await Packet.loadAsync(`${dir}/server/npc.dat`); + const jag = await Jagfile.loadAsync(`${dir}/client/config`); + this.parse(server, jag); + } + static parse(server, jag) { + NpcType.configNames = new Map(); + NpcType.configs = []; + const count = server.g2(); + const client = jag.read('npc.dat'); + client.pos = 2; + for (let id = 0; id < count; id++) { + const config = new NpcType(id); + config.decodeType(server); + config.decodeType(client); + NpcType.configs[id] = config; + if (config.debugname) { + NpcType.configNames.set(config.debugname, id); + } + } + } + static get(id) { + return NpcType.configs[id]; + } + static getId(name) { + return NpcType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + name = null; + desc = null; + size = 1; + models = null; + heads = null; + hasanim = false; + readyanim = -1; + walkanim = -1; + walkanim_b = -1; + walkanim_r = -1; + walkanim_l = -1; + hasalpha = false; + recol_s = null; + recol_d = null; + op = null; + resizex = -1; + resizey = -1; + resizez = -1; + minimap = true; + vislevel = -1; + resizeh = 128; + resizev = 128; + category = -1; + wanderrange = 5; + maxrange = 7; + huntrange = 5; + timer = -1; + respawnrate = 100; + stats = [1, 1, 1, 1, 1, 1]; + moverestrict = MoveRestrict_default.NORMAL; + attackrange = 1; + huntmode = -1; + defaultmode = NpcMode_default.WANDER; + members = false; + blockwalk = BlockWalk_default.NPC; + params = new Map(); + patrolCoord = []; + patrolDelay = []; + givechase = true; + decode(code, dat) { + if (code === 1) { + const count = dat.g1(); + this.models = new Uint16Array(count); + for (let i = 0; i < count; i++) { + this.models[i] = dat.g2(); + } + } else if (code === 2) { + this.name = dat.gjstr(); + } else if (code === 3) { + this.desc = dat.gjstr(); + } else if (code === 12) { + this.size = dat.g1(); + } else if (code === 13) { + this.readyanim = dat.g2(); + } else if (code === 14) { + this.walkanim = dat.g2(); + } else if (code === 16) { + this.hasanim = true; + } else if (code === 17) { + this.walkanim = dat.g2(); + this.walkanim_b = dat.g2(); + this.walkanim_r = dat.g2(); + this.walkanim_l = dat.g2(); + } else if (code === 18) { + this.category = dat.g2(); + } else if (code >= 30 && code < 40) { + if (!this.op) { + this.op = new Array(5).fill(null); + } + this.op[code - 30] = dat.gjstr(); + if (this.op[code - 30] === 'hidden') { + this.op[code - 30] = null; + } + } else if (code === 40) { + const count = dat.g1(); + this.recol_s = new Uint16Array(count); + this.recol_d = new Uint16Array(count); + for (let i = 0; i < count; i++) { + this.recol_s[i] = dat.g2(); + this.recol_d[i] = dat.g2(); + } + } else if (code === 60) { + const count = dat.g1(); + this.heads = new Uint16Array(count); + for (let i = 0; i < count; i++) { + this.heads[i] = dat.g2(); + } + } else if (code === 74) { + this.stats[NpcStat_default.ATTACK] = dat.g2(); + } else if (code === 75) { + this.stats[NpcStat_default.DEFENCE] = dat.g2(); + } else if (code === 76) { + this.stats[NpcStat_default.STRENGTH] = dat.g2(); + } else if (code === 77) { + this.stats[NpcStat_default.HITPOINTS] = dat.g2(); + } else if (code === 78) { + this.stats[NpcStat_default.RANGED] = dat.g2(); + } else if (code === 79) { + this.stats[NpcStat_default.MAGIC] = dat.g2(); + } else if (code === 90) { + this.resizex = dat.g2(); + } else if (code === 91) { + this.resizey = dat.g2(); + } else if (code === 92) { + this.resizez = dat.g2(); + } else if (code === 93) { + this.minimap = false; + } else if (code === 95) { + this.vislevel = dat.g2(); + } else if (code === 97) { + this.resizeh = dat.g2(); + } else if (code === 98) { + this.resizev = dat.g2(); + } else if (code === 200) { + this.wanderrange = dat.g1(); + } else if (code === 201) { + this.maxrange = dat.g1(); + } else if (code === 202) { + this.huntrange = dat.g1(); + } else if (code === 203) { + this.timer = dat.g2(); + } else if (code === 204) { + this.respawnrate = dat.g2(); + } else if (code === 206) { + this.moverestrict = dat.g1(); + } else if (code == 207) { + this.attackrange = dat.g1(); + } else if (code === 208) { + this.blockwalk = dat.g1(); + } else if (code === 209) { + this.huntmode = dat.g1(); + } else if (code === 210) { + this.defaultmode = dat.g1(); + } else if (code === 211) { + this.members = true; + } else if (code === 212) { + const count = dat.g1(); + this.patrolCoord = new Array(count); + this.patrolDelay = new Array(count); + for (let j = 0; j < count; j++) { + this.patrolCoord[j] = dat.g4(); + this.patrolDelay[j] = dat.g1(); + } + } else if (code === 213) { + this.givechase = false; + } else if (code === 249) { + this.params = ParamHelper.decodeParams(dat); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + console.error('Unrecognized npc config code: ' + code); + console.error('Try `npm run build` and report an issue if this still happens.'); + process.exit(1); + } + } +} + +// src/lostcity/cache/config/ObjType.ts +var {default: fs14} = () => ({}); + +// src/lostcity/cache/config/ParamType.ts +var {default: fs13} = () => ({}); +class ParamType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs13.existsSync(`${dir}/server/param.dat`)) { + console.log('Warning: No param.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/param.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/param.dat`)).ok) { + console.log('Warning: No param.dat found.'); + } + const dat = await Packet.loadAsync(`${dir}/server/param.dat`); + this.parse(dat); + } + static parse(dat) { + ParamType.configNames = new Map(); + ParamType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config = new ParamType(id); + config.decodeType(dat); + ParamType.configs[id] = config; + if (config.debugname) { + ParamType.configNames.set(config.debugname, id); + } + } + } + static get(id) { + return ParamType.configs[id]; + } + static getId(name) { + return ParamType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + type = ScriptVarType.INT; + defaultInt = -1; + defaultString = null; + autodisable = true; + decode(code, dat) { + if (code === 1) { + this.type = dat.g1(); + } else if (code === 2) { + this.defaultInt = dat.g4(); + } else if (code === 4) { + this.autodisable = false; + } else if (code === 5) { + this.defaultString = dat.gjstr(); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized param config code: ${code}`); + } + } + getType() { + switch (this.type) { + case ScriptVarType.INT: + return 'int'; + case ScriptVarType.STRING: + return 'string'; + case ScriptVarType.ENUM: + return 'enum'; + case ScriptVarType.OBJ: + return 'obj'; + case ScriptVarType.LOC: + return 'loc'; + case ScriptVarType.COMPONENT: + return 'component'; + case ScriptVarType.NAMEDOBJ: + return 'namedobj'; + case ScriptVarType.STRUCT: + return 'struct'; + case ScriptVarType.BOOLEAN: + return 'boolean'; + case ScriptVarType.COORD: + return 'coord'; + case ScriptVarType.CATEGORY: + return 'category'; + case ScriptVarType.SPOTANIM: + return 'spotanim'; + case ScriptVarType.NPC: + return 'npc'; + case ScriptVarType.INV: + return 'inv'; + case ScriptVarType.SYNTH: + return 'synth'; + case ScriptVarType.SEQ: + return 'seq'; + case ScriptVarType.STAT: + return 'stat'; + case ScriptVarType.INTERFACE: + return 'interface'; + default: + return 'unknown'; + } + } + isString() { + return this.type === ScriptVarType.STRING; + } + get default() { + return this.isString() ? this.defaultString : this.defaultInt; + } +} + +// src/lostcity/util/Environment.ts + +// src/lostcity/util/TryParse.ts +function tryParseBoolean(value, defaultValue) { + if (value === 'true' || value === true) { + return true; + } else if (value === 'false' || value === false) { + return false; + } else { + return defaultValue; + } +} +function tryParseInt(value, defaultValue) { + if (typeof value === 'number') { + return value; + } + if (typeof value !== 'string' && typeof value !== 'number') { + return defaultValue; + } + const intValue = parseInt(value); + if (!isNaN(intValue)) { + return intValue; + } + return defaultValue; +} +function tryParseString(value, defaultValue) { + if (typeof value !== 'string') { + return defaultValue; + } + return value; +} +function tryParseArray(value, defaultValue) { + if (!Array.isArray(value)) { + return defaultValue; + } + return value; +} + +// src/lostcity/util/Environment.ts +var Environment_default = { + WEB_PORT: tryParseInt('', 8888), + WEB_CORS: tryParseBoolean('', true), + NODE_ID: tryParseInt('', 10), + NODE_PORT: tryParseInt('', 43594), + NODE_MEMBERS: tryParseBoolean('', true), + NODE_XPRATE: tryParseInt('', 1), + NODE_PRODUCTION: tryParseBoolean('', false), + NODE_KILLTIMER: tryParseInt('', 50), + NODE_ALLOW_CHEATS: tryParseBoolean('', true), + NODE_DEBUG: tryParseBoolean('', true), + NODE_DEBUG_PROFILE: tryParseBoolean('', false), + NODE_STAFF: tryParseArray(''?.split(','), ['pazaz']), + NODE_CLIENT_ROUTEFINDER: tryParseBoolean('', true), + NODE_SOCKET_TIMEOUT: tryParseBoolean('', true), + LOGIN_HOST: tryParseString('', 'localhost'), + LOGIN_PORT: tryParseInt('', 43500), + LOGIN_KEY: tryParseString('', ''), + DB_HOST: tryParseString('', 'localhost'), + DB_USER: tryParseString('', 'root'), + DB_PASS: tryParseString('', 'password'), + DB_NAME: tryParseString('', 'lostcity'), + BUILD_JAVA_PATH: tryParseString('', 'java'), + BUILD_STARTUP: tryParseBoolean('', true), + BUILD_STARTUP_UPDATE: tryParseBoolean('', true), + BUILD_VERIFY: tryParseBoolean('', true), + BUILD_VERIFY_FOLDER: tryParseBoolean('', true), + BUILD_VERIFY_PACK: tryParseBoolean('', true), + BUILD_SRC_DIR: tryParseString('', 'data/src') +}; + +// src/lostcity/cache/config/ObjType.ts +class ObjType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs14.existsSync(`${dir}/server/obj.dat`)) { + console.log('Warning: No obj.dat found.'); + return; + } + const server = Packet.load(`${dir}/server/obj.dat`); + const jag = Jagfile.load(`${dir}/client/config`); + this.parse(server, jag); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/obj.dat`)).ok) { + console.log('Warning: No obj.dat found.'); + return; + } + const server = await Packet.loadAsync(`${dir}/server/obj.dat`); + const jag = await Jagfile.loadAsync(`${dir}/client/config`); + this.parse(server, jag); + } + static parse(server, jag) { + ObjType.configNames = new Map(); + ObjType.configs = []; + const count = server.g2(); + const client = jag.read('obj.dat'); + client.pos = 2; + for (let id = 0; id < count; id++) { + const config2 = new ObjType(id); + config2.decodeType(server); + config2.decodeType(client); + ObjType.configs[id] = config2; + if (config2.debugname) { + ObjType.configNames.set(config2.debugname, id); + } + } + for (let id = 0; id < count; id++) { + const config2 = ObjType.configs[id]; + if (config2.certtemplate != -1) { + config2.toCertificate(); + } + if (!Environment_default.NODE_MEMBERS && config2.members) { + config2.tradeable = false; + config2.op = null; + config2.iop = null; + config2.params.forEach((_4, key) => { + if (ParamType.get(key)?.autodisable) { + config2.params.delete(key); + } + }); + } + } + } + static get(id) { + return ObjType.configs[id]; + } + static getId(name) { + return ObjType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + static getWearPosId(name) { + switch (name) { + case 'hat': + return 0; + case 'back': + return 1; + case 'front': + return 2; + case 'righthand': + return 3; + case 'torso': + return 4; + case 'lefthand': + return 5; + case 'arms': + return 6; + case 'legs': + return 7; + case 'head': + return 8; + case 'hands': + return 9; + case 'feet': + return 10; + case 'jaw': + return 11; + case 'ring': + return 12; + case 'quiver': + return 13; + default: + return -1; + } + } + model = 0; + name = null; + desc = null; + recol_s = null; + recol_d = null; + zoom2d = 2000; + xan2d = 0; + yan2d = 0; + zan2d = 0; + xof2d = 0; + yof2d = 0; + code9 = false; + code10 = -1; + stackable = false; + cost = 1; + members = false; + op = null; + iop = null; + manwear = -1; + manwear2 = -1; + manwearOffsetY = 0; + womanwear = -1; + womanwear2 = -1; + womanwearOffsetY = 0; + manwear3 = -1; + womanwear3 = -1; + manhead = -1; + manhead2 = -1; + womanhead = -1; + womanhead2 = -1; + countobj = null; + countco = null; + certlink = -1; + certtemplate = -1; + wearpos = -1; + wearpos2 = -1; + wearpos3 = -1; + weight = 0; + category = -1; + dummyitem = 0; + tradeable = false; + respawnrate = 100; + params = new Map(); + decode(code, dat) { + if (code === 1) { + this.model = dat.g2(); + } else if (code === 2) { + this.name = dat.gjstr(); + } else if (code === 3) { + this.desc = dat.gjstr(); + } else if (code === 4) { + this.zoom2d = dat.g2(); + } else if (code === 5) { + this.xan2d = dat.g2(); + } else if (code === 6) { + this.yan2d = dat.g2(); + } else if (code === 7) { + this.xof2d = dat.g2s(); + } else if (code === 8) { + this.yof2d = dat.g2s(); + } else if (code === 9) { + this.code9 = true; + } else if (code === 10) { + this.code10 = dat.g2(); + } else if (code === 11) { + this.stackable = true; + } else if (code === 12) { + this.cost = dat.g4(); + } else if (code === 13) { + this.wearpos = dat.g1(); + } else if (code === 14) { + this.wearpos2 = dat.g1(); + } else if (code === 16) { + this.members = true; + } else if (code === 23) { + this.manwear = dat.g2(); + this.manwearOffsetY = dat.g1b(); + } else if (code === 24) { + this.manwear2 = dat.g2(); + } else if (code === 25) { + this.womanwear = dat.g2(); + this.womanwearOffsetY = dat.g1b(); + } else if (code === 26) { + this.womanwear2 = dat.g2(); + } else if (code === 27) { + this.wearpos3 = dat.g1(); + } else if (code >= 30 && code < 35) { + if (!this.op) { + this.op = new Array(5).fill(null); + } + this.op[code - 30] = dat.gjstr(); + } else if (code >= 35 && code < 40) { + if (!this.iop) { + this.iop = new Array(5).fill(null); + } + this.iop[code - 35] = dat.gjstr(); + } else if (code === 40) { + const count = dat.g1(); + this.recol_s = new Uint16Array(count); + this.recol_d = new Uint16Array(count); + for (let i = 0; i < count; i++) { + this.recol_s[i] = dat.g2(); + this.recol_d[i] = dat.g2(); + } + } else if (code === 75) { + this.weight = dat.g2s(); + } else if (code === 78) { + this.manwear3 = dat.g2(); + } else if (code === 79) { + this.womanwear3 = dat.g2(); + } else if (code === 90) { + this.manhead = dat.g2(); + } else if (code === 91) { + this.womanhead = dat.g2(); + } else if (code === 92) { + this.manhead2 = dat.g2(); + } else if (code === 93) { + this.womanhead2 = dat.g2(); + } else if (code === 94) { + this.category = dat.g2(); + } else if (code === 95) { + this.zan2d = dat.g2(); + } else if (code === 96) { + this.dummyitem = dat.g1(); + } else if (code === 97) { + this.certlink = dat.g2(); + } else if (code === 98) { + this.certtemplate = dat.g2(); + } else if (code >= 100 && code < 110) { + if (!this.countobj || !this.countco) { + this.countobj = new Uint16Array(10); + this.countco = new Uint16Array(10); + } + this.countobj[code - 100] = dat.g2(); + this.countco[code - 100] = dat.g2(); + } else if (code === 200) { + this.tradeable = true; + } else if (code === 201) { + this.respawnrate = dat.g2(); + } else if (code === 249) { + this.params = ParamHelper.decodeParams(dat); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized obj config code: ${code}`); + } + } + toCertificate() { + const template = ObjType.get(this.certtemplate); + this.model = template.model; + this.zoom2d = template.zoom2d; + this.xan2d = template.xan2d; + this.yan2d = template.yan2d; + this.zan2d = template.zan2d; + this.xof2d = template.xof2d; + this.yof2d = template.yof2d; + this.recol_s = template.recol_s; + this.recol_d = template.recol_d; + const link = ObjType.get(this.certlink); + this.name = link.name; + this.members = link.members; + this.cost = link.cost; + this.tradeable = link.tradeable; + let article = 'a'; + const c = (link.name || '').toLowerCase().charAt(0); + if (c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u') { + article = 'an'; + } + this.desc = `Swap this note at any bank for ${article} ${link.name}.`; + this.stackable = true; + } +} + +// src/lostcity/cache/config/SeqFrame.ts +var {default: fs15} = () => ({}); +class SeqFrame { + static instances = []; + static load(dir) { + if (!fs15.existsSync(`${dir}/server/frame_del.dat`)) { + console.log('Warning: No frame_del.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/frame_del.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/frame_del.dat`)).ok) { + console.log('Warning: No frame_del.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/frame_del.dat`); + this.parse(dat); + } + static parse(dat) { + SeqFrame.instances = []; + for (let i = 0; i < dat.data.length; i++) { + const frame = new SeqFrame(); + frame.delay = dat.g1(); + SeqFrame.instances[i] = frame; + } + } + delay = 0; +} + +// src/lostcity/cache/config/SeqType.ts +var {default: fs16} = () => ({}); +class SeqType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs16.existsSync(`${dir}/server/seq.dat`)) { + console.log('Warning: No seq.dat found.'); + return; + } + const server = Packet.load(`${dir}/server/seq.dat`); + const jag = Jagfile.load(`${dir}/client/config`); + this.parse(server, jag); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/seq.dat`)).ok) { + console.log('Warning: No seq.dat found.'); + return; + } + const server = await Packet.loadAsync(`${dir}/server/seq.dat`); + const jag = await Jagfile.loadAsync(`${dir}/client/config`); + this.parse(server, jag); + } + static parse(server, jag) { + SeqType.configNames = new Map(); + SeqType.configs = []; + const count = server.g2(); + const client = jag.read('seq.dat'); + client.pos = 2; + for (let id = 0; id < count; id++) { + const config2 = new SeqType(id); + config2.decodeType(server); + config2.decodeType(client); + SeqType.configs[id] = config2; + if (config2.debugname) { + SeqType.configNames.set(config2.debugname, id); + } + } + } + static get(id) { + return SeqType.configs[id]; + } + static getId(name) { + return SeqType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return SeqType.configs.length; + } + frames = null; + iframes = null; + delay = null; + replayoff = -1; + walkmerge = null; + stretches = false; + priority = 5; + mainhand = -1; + offhand = -1; + replaycount = 99; + duration = 0; + decode(code, dat) { + if (code === 1) { + const count = dat.g1(); + this.frames = new Int32Array(count); + this.iframes = new Int32Array(count); + this.delay = new Int32Array(count); + for (let i = 0; i < count; i++) { + this.frames[i] = dat.g2(); + this.iframes[i] = dat.g2(); + if (this.iframes[i] === 65535) { + this.iframes[i] = -1; + } + this.delay[i] = dat.g2(); + if (this.delay[i] === 0) { + this.delay[i] = SeqFrame.instances[this.frames[i]].delay; + } + if (this.delay[i] === 0) { + this.delay[i] = 1; + } + this.duration += this.delay[i]; + } + } else if (code === 2) { + this.replayoff = dat.g2(); + } else if (code === 3) { + const count = dat.g1(); + this.walkmerge = new Int32Array(count + 1); + for (let i = 0; i < count; i++) { + this.walkmerge[i] = dat.g1(); + } + this.walkmerge[count] = 9999999; + } else if (code === 4) { + this.stretches = true; + } else if (code === 5) { + this.priority = dat.g1(); + } else if (code === 6) { + this.mainhand = dat.g2(); + } else if (code === 7) { + this.offhand = dat.g2(); + } else if (code === 8) { + this.replaycount = dat.g1(); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized seq config code: ${code}`); + } + } +} + +// src/lostcity/cache/config/StructType.ts +var {default: fs17} = () => ({}); +class StructType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs17.existsSync(`${dir}/server/struct.dat`)) { + console.log('Warning: No struct.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/struct.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/struct.dat`)).ok) { + console.log('Warning: No struct.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/struct.dat`); + this.parse(dat); + } + static parse(dat) { + StructType.configNames = new Map(); + StructType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config2 = new StructType(id); + config2.decodeType(dat); + StructType.configs[id] = config2; + if (config2.debugname) { + StructType.configNames.set(config2.debugname, id); + } + } + } + static get(id) { + return StructType.configs[id]; + } + static getId(name) { + return StructType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + params = null; + decode(code, dat) { + if (code === 249) { + this.params = ParamHelper.decodeParams(dat); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized struct config code: ${code}`); + } + } +} + +// src/lostcity/cache/config/VarNpcType.ts +var {default: fs18} = () => ({}); +class VarNpcType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs18.existsSync(`${dir}/server/varn.dat`)) { + console.log('Warning: No varn.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/varn.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/varn.dat`)).ok) { + console.log('Warning: No varn.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/varn.dat`); + this.parse(dat); + } + static parse(dat) { + VarNpcType.configNames = new Map(); + VarNpcType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config2 = new VarNpcType(id); + config2.decodeType(dat); + VarNpcType.configs[id] = config2; + if (config2.debugname) { + VarNpcType.configNames.set(config2.debugname, id); + } + } + } + static get(id) { + return VarNpcType.configs[id]; + } + static getId(name) { + return VarNpcType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + type = ScriptVarType.INT; + decode(code, dat) { + if (code === 1) { + this.type = dat.g1(); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + console.error(`Unrecognized varn config code: ${code}`); + } + } +} + +// src/lostcity/cache/config/VarPlayerType.ts +var {default: fs19} = () => ({}); +class VarPlayerType extends ConfigType { + static configNames = new Map(); + static configs = []; + static SCOPE_TEMP = 0; + static SCOPE_PERM = 1; + static PLAYER_RUN = -1; + static TEMP_RUN = -1; + static LASTCOMBAT = -1; + static load(dir) { + if (!fs19.existsSync(`${dir}/server/varp.dat`)) { + console.log('Warning: No varp.dat found.'); + return; + } + const server = Packet.load(`${dir}/server/varp.dat`); + const jag = Jagfile.load(`${dir}/client/config`); + this.parse(server, jag); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/varp.dat`)).ok) { + console.log('Warning: No varp.dat found.'); + return; + } + const server = await Packet.loadAsync(`${dir}/server/varp.dat`); + const jag = await Jagfile.loadAsync(`${dir}/client/config`); + this.parse(server, jag); + } + static parse(server, jag) { + VarPlayerType.configNames = new Map(); + VarPlayerType.configs = []; + const count = server.g2(); + const client = jag.read('varp.dat'); + client.pos = 2; + for (let id = 0; id < count; id++) { + const config2 = new VarPlayerType(id); + config2.decodeType(server); + config2.decodeType(client); + VarPlayerType.configs[id] = config2; + if (config2.debugname) { + VarPlayerType.configNames.set(config2.debugname, id); + } + } + VarPlayerType.PLAYER_RUN = VarPlayerType.getId('player_run'); + VarPlayerType.TEMP_RUN = VarPlayerType.getId('temp_run'); + VarPlayerType.LASTCOMBAT = VarPlayerType.getId('lastcombat'); + } + static get(id) { + return VarPlayerType.configs[id]; + } + static getId(name) { + return VarPlayerType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + clientcode = 0; + scope = VarPlayerType.SCOPE_TEMP; + type = ScriptVarType.INT; + protect = true; + transmit = false; + decode(code, dat) { + if (code === 1) { + this.scope = dat.g1(); + } else if (code === 2) { + this.type = dat.g1(); + } else if (code === 4) { + this.protect = false; + } else if (code === 5) { + this.clientcode = dat.g2(); + } else if (code === 6) { + this.transmit = true; + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + console.error(`Unrecognized varp config code: ${code}`); + } + } +} + +// src/lostcity/cache/config/VarSharedType.ts +var {default: fs20} = () => ({}); +class VarSharedType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs20.existsSync(`${dir}/server/vars.dat`)) { + console.log('Warning: No vars.dat found.'); + return; + } + const dat = Packet.load(`${dir}/server/vars.dat`); + this.parse(dat); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/vars.dat`)).ok) { + console.log('Warning: No vars.dat found.'); + return; + } + const dat = await Packet.loadAsync(`${dir}/server/vars.dat`); + this.parse(dat); + } + static parse(dat) { + VarSharedType.configNames = new Map(); + VarSharedType.configs = []; + const count = dat.g2(); + for (let id = 0; id < count; id++) { + const config2 = new VarSharedType(id); + config2.decodeType(dat); + VarSharedType.configs[id] = config2; + if (config2.debugname) { + VarSharedType.configNames.set(config2.debugname, id); + } + } + } + static get(id) { + return VarSharedType.configs[id]; + } + static getId(name) { + return VarSharedType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + type = ScriptVarType.INT; + decode(code, dat) { + switch (code) { + case 1: + this.type = dat.g1(); + break; + case 250: + this.debugname = dat.gjstr(); + break; + default: + console.error(`Unrecognized vars config code: ${code}`); + break; + } + } +} + +// src/lostcity/cache/wordenc/WordEnc.ts +var {default: fs21} = () => ({}); + +// src/lostcity/cache/wordenc/WordEncFragments.ts +class WordEncFragments { + fragments = []; + filter(chars) { + for (let currentIndex = 0; currentIndex < chars.length; ) { + const numberIndex = this.indexOfNumber(chars, currentIndex); + if (numberIndex === -1) { + return; + } + let isSymbolOrNotLowercaseAlpha = false; + for (let index = currentIndex; index >= 0 && index < numberIndex && !isSymbolOrNotLowercaseAlpha; index++) { + if (!WordEnc2.isSymbol(chars[index]) && !WordEnc2.isNotLowercaseAlpha(chars[index])) { + isSymbolOrNotLowercaseAlpha = true; + } + } + let startIndex = 0; + if (isSymbolOrNotLowercaseAlpha) { + startIndex = 0; + } + if (startIndex === 0) { + startIndex = 1; + currentIndex = numberIndex; + } + let value = 0; + for (let index = numberIndex; index < chars.length && index < currentIndex; index++) { + value = value * 10 + chars[index].charCodeAt(0) - 48; + } + if (value <= 255 && currentIndex - numberIndex <= 8) { + startIndex++; + } else { + startIndex = 0; + } + if (startIndex === 4) { + WordEnc2.maskChars(numberIndex, currentIndex, chars); + startIndex = 0; + } + currentIndex = this.indexOfNonNumber(currentIndex, chars); + } + } + isBadFragment(chars) { + if (WordEnc2.isNumericalChars(chars)) { + return true; + } + const value = this.getInteger(chars); + const fragments = this.fragments; + const fragmentsLength = fragments.length; + if (value === fragments[0] || value === fragments[fragmentsLength - 1]) { + return true; + } + let start = 0; + let end = fragmentsLength - 1; + while (start <= end) { + const mid = ((start + end) / 2) | 0; + if (value === fragments[mid]) { + return true; + } else if (value < fragments[mid]) { + end = mid - 1; + } else { + start = mid + 1; + } + } + return false; + } + getInteger(chars) { + if (chars.length > 6) { + return 0; + } + let value = 0; + for (let index = 0; index < chars.length; index++) { + const char = chars[chars.length - index - 1]; + if (WordEnc2.isLowercaseAlpha(char)) { + value = value * 38 + char.charCodeAt(0) + 1 - 'a'.charCodeAt(0); + } else if (char == "'") { + value = value * 38 + 27; + } else if (WordEnc2.isNumerical(char)) { + value = value * 38 + char.charCodeAt(0) + 28 - '0'.charCodeAt(0); + } else if (char != '\0') { + return 0; + } + } + return value; + } + indexOfNumber(chars, offset) { + for (let index = offset; index < chars.length && index >= 0; index++) { + if (WordEnc2.isNumerical(chars[index])) { + return index; + } + } + return -1; + } + indexOfNonNumber(offset, chars) { + for (let index = offset; index < chars.length && index >= 0; index++) { + if (!WordEnc2.isNumerical(chars[index])) { + return index; + } + } + return chars.length; + } +} + +// src/lostcity/cache/wordenc/WordEncBadWords.ts +class WordEncBadWords { + wordEncFragments; + bads = []; + badCombinations = []; + constructor(wordEncFragments) { + this.wordEncFragments = wordEncFragments; + } + filter(chars) { + for (let comboIndex = 0; comboIndex < 2; comboIndex++) { + for (let index = this.bads.length - 1; index >= 0; index--) { + this.filterBadCombinations(this.badCombinations[index], chars, this.bads[index]); + } + } + } + filterBadCombinations(combos, chars, bads) { + if (bads.length > chars.length) { + return; + } + for (let startIndex = 0; startIndex <= chars.length - bads.length; startIndex++) { + let currentIndex = startIndex; + const {currentIndex: updatedCurrentIndex, badIndex, hasSymbol, hasNumber, hasDigit} = this.processBadCharacters(chars, bads, currentIndex); + currentIndex = updatedCurrentIndex; + let currentChar = chars[currentIndex]; + let nextChar = currentIndex + 1 < chars.length ? chars[currentIndex + 1] : '\0'; + if (!(badIndex >= bads.length && (!hasNumber || !hasDigit))) { + continue; + } + let shouldFilter = true; + let localIndex; + if (hasSymbol) { + let isBeforeSymbol = false; + let isAfterSymbol = false; + if (startIndex - 1 < 0 || (WordEnc2.isSymbol(chars[startIndex - 1]) && chars[startIndex - 1] != "'")) { + isBeforeSymbol = true; + } + if (currentIndex >= chars.length || (WordEnc2.isSymbol(chars[currentIndex]) && chars[currentIndex] != "'")) { + isAfterSymbol = true; + } + if (!isBeforeSymbol || !isAfterSymbol) { + let isSubstringValid = false; + localIndex = startIndex - 2; + if (isBeforeSymbol) { + localIndex = startIndex; + } + while (!isSubstringValid && localIndex < currentIndex) { + if (localIndex >= 0 && (!WordEnc2.isSymbol(chars[localIndex]) || chars[localIndex] == "'")) { + const localSubString = []; + let localSubStringIndex; + for ( + localSubStringIndex = 0; + localSubStringIndex < 3 && localIndex + localSubStringIndex < chars.length && (!WordEnc2.isSymbol(chars[localIndex + localSubStringIndex]) || chars[localIndex + localSubStringIndex] == "'"); + localSubStringIndex++ + ) { + localSubString[localSubStringIndex] = chars[localIndex + localSubStringIndex]; + } + let isSubStringValidCondition = true; + if (localSubStringIndex == 0) { + isSubStringValidCondition = false; + } + if (localSubStringIndex < 3 && localIndex - 1 >= 0 && (!WordEnc2.isSymbol(chars[localIndex - 1]) || chars[localIndex - 1] == "'")) { + isSubStringValidCondition = false; + } + if (isSubStringValidCondition && !this.wordEncFragments.isBadFragment(localSubString)) { + isSubstringValid = true; + } + } + localIndex++; + } + if (!isSubstringValid) { + shouldFilter = false; + } + } + } else { + currentChar = ' '; + if (startIndex - 1 >= 0) { + currentChar = chars[startIndex - 1]; + } + nextChar = ' '; + if (currentIndex < chars.length) { + nextChar = chars[currentIndex]; + } + const current = this.getIndex(currentChar); + const next = this.getIndex(nextChar); + if (combos != null && this.comboMatches(current, combos, next)) { + shouldFilter = false; + } + } + if (!shouldFilter) { + continue; + } + let numeralCount = 0; + let alphaCount = 0; + for (let index = startIndex; index < currentIndex; index++) { + if (WordEnc2.isNumerical(chars[index])) { + numeralCount++; + } else if (WordEnc2.isAlpha(chars[index])) { + alphaCount++; + } + } + if (numeralCount <= alphaCount) { + WordEnc2.maskChars(startIndex, currentIndex, chars); + } + } + } + processBadCharacters(chars, bads, startIndex) { + let index = startIndex; + let badIndex = 0; + let count = 0; + let hasSymbol = false; + let hasNumber = false; + let hasDigit = false; + for (; index < chars.length && !(hasNumber && hasDigit); ) { + if (index >= chars.length || (hasNumber && hasDigit)) { + break; + } + const currentChar = chars[index]; + const nextChar = index + 1 < chars.length ? chars[index + 1] : '\0'; + let currentLength; + if (badIndex < bads.length && (currentLength = this.getEmulatedBadCharLen(nextChar, String.fromCharCode(bads[badIndex]), currentChar)) > 0) { + if (currentLength === 1 && WordEnc2.isNumerical(currentChar)) { + hasNumber = true; + } + if (currentLength === 2 && (WordEnc2.isNumerical(currentChar) || WordEnc2.isNumerical(nextChar))) { + hasNumber = true; + } + index += currentLength; + badIndex++; + } else { + if (badIndex === 0) { + break; + } + let previousLength; + if ((previousLength = this.getEmulatedBadCharLen(nextChar, String.fromCharCode(bads[badIndex - 1]), currentChar)) > 0) { + index += previousLength; + } else { + if (badIndex >= bads.length || !WordEnc2.isNotLowercaseAlpha(currentChar)) { + break; + } + if (WordEnc2.isSymbol(currentChar) && currentChar !== "'") { + hasSymbol = true; + } + if (WordEnc2.isNumerical(currentChar)) { + hasDigit = true; + } + index++; + count++; + if ((((count * 100) / (index - startIndex)) | 0) > 90) { + break; + } + } + } + } + return { + currentIndex: index, + badIndex, + hasSymbol, + hasNumber, + hasDigit + }; + } + getEmulatedBadCharLen(nextChar, badChar, currentChar) { + if (badChar == currentChar) { + return 1; + } + if (badChar >= 'a' && badChar <= 'm') { + if (badChar == 'a') { + if (currentChar != '4' && currentChar != '@' && currentChar != '^') { + if (currentChar == '/' && nextChar == '\\') { + return 2; + } + return 0; + } + return 1; + } + if (badChar == 'b') { + if (currentChar != '6' && currentChar != '8') { + if (currentChar == '1' && nextChar == '3') { + return 2; + } + return 0; + } + return 1; + } + if (badChar == 'c') { + if (currentChar != '(' && currentChar != '<' && currentChar != '{' && currentChar != '[') { + return 0; + } + return 1; + } + if (badChar == 'd') { + if (currentChar == '[' && nextChar == ')') { + return 2; + } + return 0; + } + if (badChar == 'e') { + if (currentChar != '3' && currentChar != '\u20AC') { + return 0; + } + return 1; + } + if (badChar == 'f') { + if (currentChar == 'p' && nextChar == 'h') { + return 2; + } + if (currentChar == '\xA3') { + return 1; + } + return 0; + } + if (badChar == 'g') { + if (currentChar != '9' && currentChar != '6') { + return 0; + } + return 1; + } + if (badChar == 'h') { + if (currentChar == '#') { + return 1; + } + return 0; + } + if (badChar == 'i') { + if (currentChar != 'y' && currentChar != 'l' && currentChar != 'j' && currentChar != '1' && currentChar != '!' && currentChar != ':' && currentChar != ';' && currentChar != '|') { + return 0; + } + return 1; + } + if (badChar == 'j') { + return 0; + } + if (badChar == 'k') { + return 0; + } + if (badChar == 'l') { + if (currentChar != '1' && currentChar != '|' && currentChar != 'i') { + return 0; + } + return 1; + } + if (badChar == 'm') { + return 0; + } + } + if (badChar >= 'n' && badChar <= 'z') { + if (badChar == 'n') { + return 0; + } + if (badChar == 'o') { + if (currentChar != '0' && currentChar != '*') { + if ((currentChar != '(' || nextChar != ')') && (currentChar != '[' || nextChar != ']') && (currentChar != '{' || nextChar != '}') && (currentChar != '<' || nextChar != '>')) { + return 0; + } + return 2; + } + return 1; + } + if (badChar == 'p') { + return 0; + } + if (badChar == 'q') { + return 0; + } + if (badChar == 'r') { + return 0; + } + if (badChar == 's') { + if (currentChar != '5' && currentChar != 'z' && currentChar != '$' && currentChar != '2') { + return 0; + } + return 1; + } + if (badChar == 't') { + if (currentChar != '7' && currentChar != '+') { + return 0; + } + return 1; + } + if (badChar == 'u') { + if (currentChar == 'v') { + return 1; + } + if ((currentChar != '\\' || nextChar != '/') && (currentChar != '\\' || nextChar != '|') && (currentChar != '|' || nextChar != '/')) { + return 0; + } + return 2; + } + if (badChar == 'v') { + if ((currentChar != '\\' || nextChar != '/') && (currentChar != '\\' || nextChar != '|') && (currentChar != '|' || nextChar != '/')) { + return 0; + } + return 2; + } + if (badChar == 'w') { + if (currentChar == 'v' && nextChar == 'v') { + return 2; + } + return 0; + } + if (badChar == 'x') { + if ((currentChar != ')' || nextChar != '(') && (currentChar != '}' || nextChar != '{') && (currentChar != ']' || nextChar != '[') && (currentChar != '>' || nextChar != '<')) { + return 0; + } + return 2; + } + if (badChar == 'y') { + return 0; + } + if (badChar == 'z') { + return 0; + } + } + if (badChar >= '0' && badChar <= '9') { + if (badChar == '0') { + if (currentChar == 'o' || currentChar == 'O') { + return 1; + } else if ((currentChar != '(' || nextChar != ')') && (currentChar != '{' || nextChar != '}') && (currentChar != '[' || nextChar != ']')) { + return 0; + } else { + return 2; + } + } else if (badChar == '1') { + return currentChar == 'l' ? 1 : 0; + } else { + return 0; + } + } else if (badChar == ',') { + return currentChar == '.' ? 1 : 0; + } else if (badChar == '.') { + return currentChar == ',' ? 1 : 0; + } else if (badChar == '!') { + return currentChar == 'i' ? 1 : 0; + } + return 0; + } + comboMatches(currentIndex, combos, nextIndex) { + let start = 0; + let end = combos.length - 1; + while (start <= end) { + const mid = ((start + end) / 2) | 0; + if (combos[mid][0] === currentIndex && combos[mid][1] === nextIndex) { + return true; + } else if (currentIndex < combos[mid][0] || (currentIndex === combos[mid][0] && nextIndex < combos[mid][1])) { + end = mid - 1; + } else { + start = mid + 1; + } + } + return false; + } + getIndex(char) { + if (WordEnc2.isLowercaseAlpha(char)) { + return char.charCodeAt(0) + 1 - 'a'.charCodeAt(0); + } else if (char == "'") { + return 28; + } else if (WordEnc2.isNumerical(char)) { + return char.charCodeAt(0) + 29 - '0'.charCodeAt(0); + } + return 27; + } +} + +// src/lostcity/cache/wordenc/WordEncDomains.ts +class WordEncDomains { + wordEncBadWords; + domains = []; + constructor(wordEncBadWords) { + this.wordEncBadWords = wordEncBadWords; + } + filter(chars) { + const ampersat = [...chars]; + const period = [...chars]; + this.wordEncBadWords.filterBadCombinations(null, ampersat, WordEnc2.AMPERSAT); + this.wordEncBadWords.filterBadCombinations(null, period, WordEnc2.PERIOD); + for (let index = this.domains.length - 1; index >= 0; index--) { + this.filterDomain(period, ampersat, this.domains[index], chars); + } + } + getEmulatedDomainCharLen(nextChar, domainChar, currentChar) { + if (domainChar == currentChar) { + return 1; + } else if (domainChar == 'o' && currentChar == '0') { + return 1; + } else if (domainChar == 'o' && currentChar == '(' && nextChar == ')') { + return 2; + } else if (domainChar == 'c' && (currentChar == '(' || currentChar == '<' || currentChar == '[')) { + return 1; + } else if (domainChar == 'e' && currentChar == '\u20AC') { + return 1; + } else if (domainChar == 's' && currentChar == '$') { + return 1; + } else if (domainChar == 'l' && currentChar == 'i') { + return 1; + } + return 0; + } + filterDomain(period, ampersat, domain, chars) { + const domainLength = domain.length; + const charsLength = chars.length; + for (let index = 0; index <= charsLength - domainLength; index++) { + const {matched, currentIndex} = this.findMatchingDomain(index, domain, chars); + if (!matched) { + continue; + } + const ampersatStatus = WordEnc2.prefixSymbolStatus(index, chars, 3, ampersat, ['@']); + const periodStatus = WordEnc2.suffixSymbolStatus(currentIndex - 1, chars, 3, period, ['.', ',']); + const shouldFilter = ampersatStatus > 2 || periodStatus > 2; + if (!shouldFilter) { + continue; + } + WordEnc2.maskChars(index, currentIndex, chars); + } + } + findMatchingDomain(startIndex, domain, chars) { + const domainLength = domain.length; + let currentIndex = startIndex; + let domainIndex = 0; + while (currentIndex < chars.length && domainIndex < domainLength) { + const currentChar = chars[currentIndex]; + const nextChar = currentIndex + 1 < chars.length ? chars[currentIndex + 1] : '\0'; + const currentLength = this.getEmulatedDomainCharLen(nextChar, String.fromCharCode(domain[domainIndex]), currentChar); + if (currentLength > 0) { + currentIndex += currentLength; + domainIndex++; + } else { + if (domainIndex === 0) break; + const previousLength = this.getEmulatedDomainCharLen(nextChar, String.fromCharCode(domain[domainIndex - 1]), currentChar); + if (previousLength > 0) { + currentIndex += previousLength; + if (domainIndex === 1) startIndex++; + } else { + if (domainIndex >= domainLength || !WordEnc2.isSymbol(currentChar)) break; + currentIndex++; + } + } + } + return {matched: domainIndex >= domainLength, currentIndex}; + } +} + +// src/lostcity/cache/wordenc/WordEncTlds.ts +class WordEncTlds { + wordEncBadWords; + wordEncDomains; + tlds = []; + tldTypes = []; + constructor(wordEncBadWords, wordEncDomains) { + this.wordEncBadWords = wordEncBadWords; + this.wordEncDomains = wordEncDomains; + } + filter(chars) { + const period = [...chars]; + const slash = [...chars]; + this.wordEncBadWords.filterBadCombinations(null, period, WordEnc2.PERIOD); + this.wordEncBadWords.filterBadCombinations(null, slash, WordEnc2.SLASH); + for (let index = 0; index < this.tlds.length; index++) { + this.filterTld(slash, this.tldTypes[index], chars, this.tlds[index], period); + } + } + filterTld(slash, tldType, chars, tld, period) { + if (tld.length > chars.length) { + return; + } + for (let index = 0; index <= chars.length - tld.length; index++) { + const {currentIndex, tldIndex} = this.processTlds(chars, tld, index); + if (tldIndex < tld.length) { + continue; + } + let shouldFilter = false; + const periodFilterStatus = WordEnc2.prefixSymbolStatus(index, chars, 3, period, [',', '.']); + const slashFilterStatus = WordEnc2.suffixSymbolStatus(currentIndex - 1, chars, 5, slash, ['\\', '/']); + if (tldType == 1 && periodFilterStatus > 0 && slashFilterStatus > 0) { + shouldFilter = true; + } + if (tldType == 2 && ((periodFilterStatus > 2 && slashFilterStatus > 0) || (periodFilterStatus > 0 && slashFilterStatus > 2))) { + shouldFilter = true; + } + if (tldType == 3 && periodFilterStatus > 0 && slashFilterStatus > 2) { + shouldFilter = true; + } + if (!shouldFilter) { + continue; + } + let startFilterIndex = index; + let endFilterIndex = currentIndex - 1; + let foundPeriod = false; + let periodIndex; + if (periodFilterStatus > 2) { + if (periodFilterStatus == 4) { + foundPeriod = false; + for (periodIndex = index - 1; periodIndex >= 0; periodIndex--) { + if (foundPeriod) { + if (period[periodIndex] != '*') { + break; + } + startFilterIndex = periodIndex; + } else if (period[periodIndex] == '*') { + startFilterIndex = periodIndex; + foundPeriod = true; + } + } + } + foundPeriod = false; + for (periodIndex = startFilterIndex - 1; periodIndex >= 0; periodIndex--) { + if (foundPeriod) { + if (WordEnc2.isSymbol(chars[periodIndex])) { + break; + } + startFilterIndex = periodIndex; + } else if (!WordEnc2.isSymbol(chars[periodIndex])) { + foundPeriod = true; + startFilterIndex = periodIndex; + } + } + } + if (slashFilterStatus > 2) { + if (slashFilterStatus == 4) { + foundPeriod = false; + for (periodIndex = endFilterIndex + 1; periodIndex < chars.length; periodIndex++) { + if (foundPeriod) { + if (slash[periodIndex] != '*') { + break; + } + endFilterIndex = periodIndex; + } else if (slash[periodIndex] == '*') { + endFilterIndex = periodIndex; + foundPeriod = true; + } + } + } + foundPeriod = false; + for (periodIndex = endFilterIndex + 1; periodIndex < chars.length; periodIndex++) { + if (foundPeriod) { + if (WordEnc2.isSymbol(chars[periodIndex])) { + break; + } + endFilterIndex = periodIndex; + } else if (!WordEnc2.isSymbol(chars[periodIndex])) { + foundPeriod = true; + endFilterIndex = periodIndex; + } + } + } + WordEnc2.maskChars(startFilterIndex, endFilterIndex + 1, chars); + } + } + processTlds(chars, tld, currentIndex) { + let tldIndex = 0; + while (currentIndex < chars.length && tldIndex < tld.length) { + const currentChar = chars[currentIndex]; + const nextChar = currentIndex + 1 < chars.length ? chars[currentIndex + 1] : '\0'; + let currentLength; + if ((currentLength = this.wordEncDomains.getEmulatedDomainCharLen(nextChar, String.fromCharCode(tld[tldIndex]), currentChar)) > 0) { + currentIndex += currentLength; + tldIndex++; + } else { + if (tldIndex === 0) { + break; + } + let previousLength; + if ((previousLength = this.wordEncDomains.getEmulatedDomainCharLen(nextChar, String.fromCharCode(tld[tldIndex - 1]), currentChar)) > 0) { + currentIndex += previousLength; + } else { + if (!WordEnc2.isSymbol(currentChar)) { + break; + } + currentIndex++; + } + } + } + return {currentIndex, tldIndex}; + } +} + +// src/lostcity/cache/wordenc/WordEnc.ts +class WordEnc2 { + static PERIOD = new Uint16Array( + ['d', 'o', 't'] + .join('') + .split('') + .map(char => char.charCodeAt(0)) + ); + static AMPERSAT = new Uint16Array( + ['(', 'a', ')'] + .join('') + .split('') + .map(char => char.charCodeAt(0)) + ); + static SLASH = new Uint16Array( + ['s', 'l', 'a', 's', 'h'] + .join('') + .split('') + .map(char => char.charCodeAt(0)) + ); + static wordEncFragments = new WordEncFragments(); + static wordEncBadWords = new WordEncBadWords(this.wordEncFragments); + static wordEncDomains = new WordEncDomains(this.wordEncBadWords); + static wordEncTlds = new WordEncTlds(this.wordEncBadWords, this.wordEncDomains); + static whitelist = ['cook', "cook's", 'cooks', 'seeks', 'sheet']; + static async load(dir) { + if (!fs21.existsSync(`${dir}/client/wordenc`)) { + console.log('Warning: No wordenc found.'); + return; + } + const wordenc = Jagfile.load(`${dir}/client/wordenc`); + this.readAll(wordenc); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/client/wordenc`)).ok) { + console.log('Warning: No wordenc found.'); + return; + } + const wordenc = await Jagfile.loadAsync(`${dir}/client/wordenc`); + this.readAll(wordenc); + } + static readAll(wordenc) { + const fragmentsenc = wordenc.read('fragmentsenc.txt'); + if (!fragmentsenc) { + console.log('Warning: No fragmentsenc found.'); + return; + } + const badenc = wordenc.read('badenc.txt'); + if (!badenc) { + console.log('Warning: No badenc found.'); + return; + } + const domainenc = wordenc.read('domainenc.txt'); + if (!domainenc) { + console.log('Warning: No domainenc found.'); + return; + } + const tldlist = wordenc.read('tldlist.txt'); + if (!tldlist) { + console.log('Warning: No tldlist found.'); + return; + } + this.decodeBadEnc(badenc); + this.decodeDomainEnc(domainenc); + this.decodeFragmentsEnc(fragmentsenc); + this.decodeTldList(tldlist); + } + static filter(input) { + const characters = [...input]; + this.format(characters); + const trimmed = characters.join('').trim(); + const lowercase = trimmed.toLowerCase(); + const filtered = [...lowercase]; + this.wordEncTlds.filter(filtered); + this.wordEncBadWords.filter(filtered); + this.wordEncDomains.filter(filtered); + this.wordEncFragments.filter(filtered); + for (let index = 0; index < this.whitelist.length; index++) { + let offset = -1; + while ((offset = lowercase.indexOf(this.whitelist[index], offset + 1)) !== -1) { + const whitelisted = [...this.whitelist[index]]; + for (let charIndex = 0; charIndex < whitelisted.length; charIndex++) { + filtered[charIndex + offset] = whitelisted[charIndex]; + } + } + } + this.replaceUppercases(filtered, [...trimmed]); + this.formatUppercases(filtered); + return filtered.join('').trim(); + } + static isSymbol(char) { + return !this.isAlpha(char) && !this.isNumerical(char); + } + static isNotLowercaseAlpha(char) { + return this.isLowercaseAlpha(char) ? char == 'v' || char == 'x' || char == 'j' || char == 'q' || char == 'z' : true; + } + static isAlpha(char) { + return this.isLowercaseAlpha(char) || this.isUppercaseAlpha(char); + } + static isNumerical(char) { + return char >= '0' && char <= '9'; + } + static isLowercaseAlpha(char) { + return char >= 'a' && char <= 'z'; + } + static isUppercaseAlpha(char) { + return char >= 'A' && char <= 'Z'; + } + static isNumericalChars(chars) { + for (let index = 0; index < chars.length; index++) { + if (!this.isNumerical(chars[index]) && chars[index] !== '\0') { + return false; + } + } + return true; + } + static maskChars(offset, length, chars) { + for (let index = offset; index < length; index++) { + chars[index] = '*'; + } + } + static maskedCountBackwards(chars, offset) { + let count = 0; + for (let index = offset - 1; index >= 0 && WordEnc2.isSymbol(chars[index]); index--) { + if (chars[index] === '*') { + count++; + } + } + return count; + } + static maskedCountForwards(chars, offset) { + let count = 0; + for (let index = offset + 1; index < chars.length && this.isSymbol(chars[index]); index++) { + if (chars[index] === '*') { + count++; + } + } + return count; + } + static maskedCharsStatus(chars, filtered, offset, length, prefix) { + const count = prefix ? this.maskedCountBackwards(filtered, offset) : this.maskedCountForwards(filtered, offset); + if (count >= length) { + return 4; + } else if (this.isSymbol(prefix ? chars[offset - 1] : chars[offset + 1])) { + return 1; + } + return 0; + } + static prefixSymbolStatus(offset, chars, length, symbolChars, symbols) { + if (offset === 0) { + return 2; + } + for (let index = offset - 1; index >= 0 && WordEnc2.isSymbol(chars[index]); index--) { + if (symbols.includes(chars[index])) { + return 3; + } + } + return WordEnc2.maskedCharsStatus(chars, symbolChars, offset, length, true); + } + static suffixSymbolStatus(offset, chars, length, symbolChars, symbols) { + if (offset + 1 === chars.length) { + return 2; + } + for (let index = offset + 1; index < chars.length && WordEnc2.isSymbol(chars[index]); index++) { + if (symbols.includes(chars[index])) { + return 3; + } + } + return WordEnc2.maskedCharsStatus(chars, symbolChars, offset, length, false); + } + static decodeTldList(packet) { + const count = packet.g4(); + for (let index = 0; index < count; index++) { + this.wordEncTlds.tldTypes[index] = packet.g1(); + this.wordEncTlds.tlds[index] = new Uint16Array(packet.g1()).map(() => packet.g1()); + } + } + static decodeBadEnc(packet) { + const count = packet.g4(); + for (let index = 0; index < count; index++) { + this.wordEncBadWords.bads[index] = new Uint16Array(packet.g1()).map(() => packet.g1()); + const combos = new Array(packet.g1()).fill([]).map(() => [packet.g1b(), packet.g1b()]); + if (combos.length > 0) { + this.wordEncBadWords.badCombinations[index] = combos; + } + } + } + static decodeDomainEnc(packet) { + const count = packet.g4(); + for (let index = 0; index < count; index++) { + this.wordEncDomains.domains[index] = new Uint16Array(packet.g1()).map(() => packet.g1()); + } + } + static decodeFragmentsEnc(packet) { + const count = packet.g4(); + for (let index = 0; index < count; index++) { + this.wordEncFragments.fragments[index] = packet.g2(); + } + } + static format(chars) { + let pos = 0; + for (let index = 0; index < chars.length; index++) { + if (this.isCharacterAllowed(chars[index])) { + chars[pos] = chars[index]; + } else { + chars[pos] = ' '; + } + if (pos === 0 || chars[pos] !== ' ' || chars[pos - 1] !== ' ') { + pos++; + } + } + for (let index = pos; index < chars.length; index++) { + chars[index] = ' '; + } + } + static isCharacterAllowed(char) { + return (char >= ' ' && char <= '\x7F') || char == ' ' || char == '\n' || char == '\t' || char == '\xA3' || char == '\u20AC'; + } + static replaceUppercases(chars, comparison) { + for (let index = 0; index < comparison.length; index++) { + if (chars[index] !== '*' && this.isUppercaseAlpha(comparison[index])) { + chars[index] = comparison[index]; + } + } + } + static formatUppercases(chars) { + let flagged = true; + for (let index = 0; index < chars.length; index++) { + const char = chars[index]; + if (!this.isAlpha(char)) { + flagged = true; + } else if (flagged) { + if (this.isLowercaseAlpha(char)) { + flagged = false; + } + } else if (this.isUppercaseAlpha(char)) { + chars[index] = String.fromCharCode(char.charCodeAt(0) + 'a'.charCodeAt(0) - 65); + } + } + } +} + +// src/lostcity/cache/config/SpotanimType.ts +var {default: fs22} = () => ({}); +class SpotanimType extends ConfigType { + static configNames = new Map(); + static configs = []; + static load(dir) { + if (!fs22.existsSync(`${dir}/server/spotanim.dat`)) { + console.log('Warning: No spotanim.dat found.'); + return; + } + const server = Packet.load(`${dir}/server/spotanim.dat`); + const jag = Jagfile.load(`${dir}/client/config`); + this.parse(server, jag); + } + static async loadAsync(dir) { + if (!(await fetch(`${dir}/server/spotanim.dat`)).ok) { + console.log('Warning: No spotanim.dat found.'); + return; + } + const server = await Packet.loadAsync(`${dir}/server/spotanim.dat`); + const jag = await Jagfile.loadAsync(`${dir}/client/config`); + this.parse(server, jag); + } + static parse(server, jag) { + SpotanimType.configNames = new Map(); + SpotanimType.configs = []; + const count = server.g2(); + const client = jag.read('spotanim.dat'); + client.pos = 2; + for (let id = 0; id < count; id++) { + const config2 = new SpotanimType(id); + config2.decodeType(server); + config2.decodeType(client); + SpotanimType.configs[id] = config2; + if (config2.debugname) { + SpotanimType.configNames.set(config2.debugname, id); + } + } + } + static get(id) { + return SpotanimType.configs[id]; + } + static getId(name) { + return SpotanimType.configNames.get(name) ?? -1; + } + static getByName(name) { + const id = this.getId(name); + if (id === -1) { + return null; + } + return this.get(id); + } + static get count() { + return this.configs.length; + } + model = 0; + anim = -1; + hasalpha = false; + recol_s = new Uint16Array(6); + recol_d = new Uint16Array(6); + resizeh = 128; + resizev = 128; + orientation = 0; + ambient = 0; + contrast = 0; + decode(code, dat) { + if (code === 1) { + this.model = dat.g2(); + } else if (code === 2) { + this.anim = dat.g2(); + } else if (code === 3) { + this.hasalpha = true; + } else if (code === 4) { + this.resizeh = dat.g2(); + } else if (code === 5) { + this.resizev = dat.g2(); + } else if (code === 6) { + this.orientation = dat.g2(); + } else if (code === 7) { + this.ambient = dat.g1(); + } else if (code === 8) { + this.contrast = dat.g1(); + } else if (code >= 40 && code < 50) { + this.recol_s[code - 40] = dat.g2(); + } else if (code >= 50 && code < 60) { + this.recol_d[code - 50] = dat.g2(); + } else if (code === 250) { + this.debugname = dat.gjstr(); + } else { + throw new Error(`Unrecognized spotanim config code: ${code}`); + } + } +} + +// src/lostcity/engine/GameMap.ts +var {default: fs25} = () => ({}); + +// src/lostcity/engine/script/ScriptPointer.ts +function checkedHandler(pointer, handler) { + return function (state) { + if (typeof pointer === 'number') { + state.pointerCheck(pointer); + } else { + state.pointerCheck(pointer[state.intOperand]); + } + handler(state); + }; +} +var ScriptPointer; +(ScriptPointer2 => { + ScriptPointer2[(ScriptPointer2['ActivePlayer'] = 0)] = 'ActivePlayer'; + ScriptPointer2[(ScriptPointer2['ActivePlayer2'] = 1)] = 'ActivePlayer2'; + ScriptPointer2[(ScriptPointer2['ProtectedActivePlayer'] = 2)] = 'ProtectedActivePlayer'; + ScriptPointer2[(ScriptPointer2['ProtectedActivePlayer2'] = 3)] = 'ProtectedActivePlayer2'; + ScriptPointer2[(ScriptPointer2['ActiveNpc'] = 4)] = 'ActiveNpc'; + ScriptPointer2[(ScriptPointer2['ActiveNpc2'] = 5)] = 'ActiveNpc2'; + ScriptPointer2[(ScriptPointer2['ActiveLoc'] = 6)] = 'ActiveLoc'; + ScriptPointer2[(ScriptPointer2['ActiveLoc2'] = 7)] = 'ActiveLoc2'; + ScriptPointer2[(ScriptPointer2['ActiveObj'] = 8)] = 'ActiveObj'; + ScriptPointer2[(ScriptPointer2['ActiveObj2'] = 9)] = 'ActiveObj2'; + ScriptPointer2[(ScriptPointer2['_LAST'] = 10)] = '_LAST'; +})((ScriptPointer ||= {})); +var ActiveNpc = [4 /* ActiveNpc */, 5 /* ActiveNpc2 */]; +var ActiveLoc = [6 /* ActiveLoc */, 7 /* ActiveLoc2 */]; +var ActiveObj = [8 /* ActiveObj */, 9 /* ActiveObj2 */]; +var ActivePlayer = [0 /* ActivePlayer */, 1 /* ActivePlayer2 */]; +var ProtectedActivePlayer = [2 /* ProtectedActivePlayer */, 3 /* ProtectedActivePlayer2 */]; +var ScriptPointer_default = ScriptPointer; + +// src/lostcity/engine/script/Script.ts +init_path(); + +// src/lostcity/engine/script/ScriptOpcode.ts +var ScriptOpcode; +(ScriptOpcode2 => { + ScriptOpcode2[(ScriptOpcode2['PUSH_CONSTANT_INT'] = 0)] = 'PUSH_CONSTANT_INT'; + ScriptOpcode2[(ScriptOpcode2['PUSH_VARP'] = 1)] = 'PUSH_VARP'; + ScriptOpcode2[(ScriptOpcode2['POP_VARP'] = 2)] = 'POP_VARP'; + ScriptOpcode2[(ScriptOpcode2['PUSH_CONSTANT_STRING'] = 3)] = 'PUSH_CONSTANT_STRING'; + ScriptOpcode2[(ScriptOpcode2['PUSH_VARN'] = 4)] = 'PUSH_VARN'; + ScriptOpcode2[(ScriptOpcode2['POP_VARN'] = 5)] = 'POP_VARN'; + ScriptOpcode2[(ScriptOpcode2['BRANCH'] = 6)] = 'BRANCH'; + ScriptOpcode2[(ScriptOpcode2['BRANCH_NOT'] = 7)] = 'BRANCH_NOT'; + ScriptOpcode2[(ScriptOpcode2['BRANCH_EQUALS'] = 8)] = 'BRANCH_EQUALS'; + ScriptOpcode2[(ScriptOpcode2['BRANCH_LESS_THAN'] = 9)] = 'BRANCH_LESS_THAN'; + ScriptOpcode2[(ScriptOpcode2['BRANCH_GREATER_THAN'] = 10)] = 'BRANCH_GREATER_THAN'; + ScriptOpcode2[(ScriptOpcode2['PUSH_VARS'] = 11)] = 'PUSH_VARS'; + ScriptOpcode2[(ScriptOpcode2['POP_VARS'] = 12)] = 'POP_VARS'; + ScriptOpcode2[(ScriptOpcode2['RETURN'] = 21)] = 'RETURN'; + ScriptOpcode2[(ScriptOpcode2['GOSUB'] = 22)] = 'GOSUB'; + ScriptOpcode2[(ScriptOpcode2['JUMP'] = 23)] = 'JUMP'; + ScriptOpcode2[(ScriptOpcode2['SWITCH'] = 24)] = 'SWITCH'; + ScriptOpcode2[(ScriptOpcode2['BRANCH_LESS_THAN_OR_EQUALS'] = 31)] = 'BRANCH_LESS_THAN_OR_EQUALS'; + ScriptOpcode2[(ScriptOpcode2['BRANCH_GREATER_THAN_OR_EQUALS'] = 32)] = 'BRANCH_GREATER_THAN_OR_EQUALS'; + ScriptOpcode2[(ScriptOpcode2['PUSH_INT_LOCAL'] = 33)] = 'PUSH_INT_LOCAL'; + ScriptOpcode2[(ScriptOpcode2['POP_INT_LOCAL'] = 34)] = 'POP_INT_LOCAL'; + ScriptOpcode2[(ScriptOpcode2['PUSH_STRING_LOCAL'] = 35)] = 'PUSH_STRING_LOCAL'; + ScriptOpcode2[(ScriptOpcode2['POP_STRING_LOCAL'] = 36)] = 'POP_STRING_LOCAL'; + ScriptOpcode2[(ScriptOpcode2['JOIN_STRING'] = 37)] = 'JOIN_STRING'; + ScriptOpcode2[(ScriptOpcode2['POP_INT_DISCARD'] = 38)] = 'POP_INT_DISCARD'; + ScriptOpcode2[(ScriptOpcode2['POP_STRING_DISCARD'] = 39)] = 'POP_STRING_DISCARD'; + ScriptOpcode2[(ScriptOpcode2['GOSUB_WITH_PARAMS'] = 40)] = 'GOSUB_WITH_PARAMS'; + ScriptOpcode2[(ScriptOpcode2['JUMP_WITH_PARAMS'] = 41)] = 'JUMP_WITH_PARAMS'; + ScriptOpcode2[(ScriptOpcode2['DEFINE_ARRAY'] = 44)] = 'DEFINE_ARRAY'; + ScriptOpcode2[(ScriptOpcode2['PUSH_ARRAY_INT'] = 45)] = 'PUSH_ARRAY_INT'; + ScriptOpcode2[(ScriptOpcode2['POP_ARRAY_INT'] = 46)] = 'POP_ARRAY_INT'; + ScriptOpcode2[(ScriptOpcode2['COORDX'] = 1000)] = 'COORDX'; + ScriptOpcode2[(ScriptOpcode2['COORDY'] = 1001)] = 'COORDY'; + ScriptOpcode2[(ScriptOpcode2['COORDZ'] = 1002)] = 'COORDZ'; + ScriptOpcode2[(ScriptOpcode2['DISTANCE'] = 1003)] = 'DISTANCE'; + ScriptOpcode2[(ScriptOpcode2['HUNTALL'] = 1004)] = 'HUNTALL'; + ScriptOpcode2[(ScriptOpcode2['HUNTNEXT'] = 1005)] = 'HUNTNEXT'; + ScriptOpcode2[(ScriptOpcode2['INZONE'] = 1006)] = 'INZONE'; + ScriptOpcode2[(ScriptOpcode2['LINEOFSIGHT'] = 1007)] = 'LINEOFSIGHT'; + ScriptOpcode2[(ScriptOpcode2['LINEOFWALK'] = 1008)] = 'LINEOFWALK'; + ScriptOpcode2[(ScriptOpcode2['MAP_BLOCKED'] = 1009)] = 'MAP_BLOCKED'; + ScriptOpcode2[(ScriptOpcode2['MAP_INDOORS'] = 1010)] = 'MAP_INDOORS'; + ScriptOpcode2[(ScriptOpcode2['MAP_CLOCK'] = 1011)] = 'MAP_CLOCK'; + ScriptOpcode2[(ScriptOpcode2['MAP_LOCADDUNSAFE'] = 1012)] = 'MAP_LOCADDUNSAFE'; + ScriptOpcode2[(ScriptOpcode2['MAP_MEMBERS'] = 1013)] = 'MAP_MEMBERS'; + ScriptOpcode2[(ScriptOpcode2['MAP_PLAYERCOUNT'] = 1014)] = 'MAP_PLAYERCOUNT'; + ScriptOpcode2[(ScriptOpcode2['MOVECOORD'] = 1015)] = 'MOVECOORD'; + ScriptOpcode2[(ScriptOpcode2['PLAYERCOUNT'] = 1016)] = 'PLAYERCOUNT'; + ScriptOpcode2[(ScriptOpcode2['PROJANIM_MAP'] = 1017)] = 'PROJANIM_MAP'; + ScriptOpcode2[(ScriptOpcode2['PROJANIM_NPC'] = 1018)] = 'PROJANIM_NPC'; + ScriptOpcode2[(ScriptOpcode2['PROJANIM_PL'] = 1019)] = 'PROJANIM_PL'; + ScriptOpcode2[(ScriptOpcode2['SEQLENGTH'] = 1020)] = 'SEQLENGTH'; + ScriptOpcode2[(ScriptOpcode2['SPLIT_GET'] = 1021)] = 'SPLIT_GET'; + ScriptOpcode2[(ScriptOpcode2['SPLIT_GETANIM'] = 1022)] = 'SPLIT_GETANIM'; + ScriptOpcode2[(ScriptOpcode2['SPLIT_INIT'] = 1023)] = 'SPLIT_INIT'; + ScriptOpcode2[(ScriptOpcode2['SPLIT_LINECOUNT'] = 1024)] = 'SPLIT_LINECOUNT'; + ScriptOpcode2[(ScriptOpcode2['SPLIT_PAGECOUNT'] = 1025)] = 'SPLIT_PAGECOUNT'; + ScriptOpcode2[(ScriptOpcode2['SPOTANIM_MAP'] = 1026)] = 'SPOTANIM_MAP'; + ScriptOpcode2[(ScriptOpcode2['STAT_RANDOM'] = 1027)] = 'STAT_RANDOM'; + ScriptOpcode2[(ScriptOpcode2['STRUCT_PARAM'] = 1028)] = 'STRUCT_PARAM'; + ScriptOpcode2[(ScriptOpcode2['WORLD_DELAY'] = 1029)] = 'WORLD_DELAY'; + ScriptOpcode2[(ScriptOpcode2['NPCCOUNT'] = 1030)] = 'NPCCOUNT'; + ScriptOpcode2[(ScriptOpcode2['ZONECOUNT'] = 1031)] = 'ZONECOUNT'; + ScriptOpcode2[(ScriptOpcode2['LOCCOUNT'] = 1032)] = 'LOCCOUNT'; + ScriptOpcode2[(ScriptOpcode2['OBJCOUNT'] = 1033)] = 'OBJCOUNT'; + ScriptOpcode2[(ScriptOpcode2['ALLOWDESIGN'] = 2000)] = 'ALLOWDESIGN'; + ScriptOpcode2[(ScriptOpcode2['ANIM'] = 2001)] = 'ANIM'; + ScriptOpcode2[(ScriptOpcode2['BAS_READYANIM'] = 2002)] = 'BAS_READYANIM'; + ScriptOpcode2[(ScriptOpcode2['BAS_RUNNING'] = 2003)] = 'BAS_RUNNING'; + ScriptOpcode2[(ScriptOpcode2['BAS_TURNONSPOT'] = 2004)] = 'BAS_TURNONSPOT'; + ScriptOpcode2[(ScriptOpcode2['BAS_WALK_B'] = 2005)] = 'BAS_WALK_B'; + ScriptOpcode2[(ScriptOpcode2['BAS_WALK_F'] = 2006)] = 'BAS_WALK_F'; + ScriptOpcode2[(ScriptOpcode2['BAS_WALK_L'] = 2007)] = 'BAS_WALK_L'; + ScriptOpcode2[(ScriptOpcode2['BAS_WALK_R'] = 2008)] = 'BAS_WALK_R'; + ScriptOpcode2[(ScriptOpcode2['BUFFER_FULL'] = 2009)] = 'BUFFER_FULL'; + ScriptOpcode2[(ScriptOpcode2['BUILDAPPEARANCE'] = 2010)] = 'BUILDAPPEARANCE'; + ScriptOpcode2[(ScriptOpcode2['BUSY'] = 2011)] = 'BUSY'; + ScriptOpcode2[(ScriptOpcode2['CAM_LOOKAT'] = 2012)] = 'CAM_LOOKAT'; + ScriptOpcode2[(ScriptOpcode2['CAM_MOVETO'] = 2013)] = 'CAM_MOVETO'; + ScriptOpcode2[(ScriptOpcode2['CAM_RESET'] = 2014)] = 'CAM_RESET'; + ScriptOpcode2[(ScriptOpcode2['CAM_SHAKE'] = 2015)] = 'CAM_SHAKE'; + ScriptOpcode2[(ScriptOpcode2['CLEARQUEUE'] = 2016)] = 'CLEARQUEUE'; + ScriptOpcode2[(ScriptOpcode2['CLEARSOFTTIMER'] = 2017)] = 'CLEARSOFTTIMER'; + ScriptOpcode2[(ScriptOpcode2['CLEARTIMER'] = 2018)] = 'CLEARTIMER'; + ScriptOpcode2[(ScriptOpcode2['COORD'] = 2019)] = 'COORD'; + ScriptOpcode2[(ScriptOpcode2['DAMAGE'] = 2020)] = 'DAMAGE'; + ScriptOpcode2[(ScriptOpcode2['DISPLAYNAME'] = 2021)] = 'DISPLAYNAME'; + ScriptOpcode2[(ScriptOpcode2['FACESQUARE'] = 2022)] = 'FACESQUARE'; + ScriptOpcode2[(ScriptOpcode2['FINDUID'] = 2023)] = 'FINDUID'; + ScriptOpcode2[(ScriptOpcode2['GENDER'] = 2024)] = 'GENDER'; + ScriptOpcode2[(ScriptOpcode2['GETQUEUE'] = 2025)] = 'GETQUEUE'; + ScriptOpcode2[(ScriptOpcode2['GIVEXP'] = 2026)] = 'GIVEXP'; + ScriptOpcode2[(ScriptOpcode2['HEADICONS_GET'] = 2027)] = 'HEADICONS_GET'; + ScriptOpcode2[(ScriptOpcode2['HEADICONS_SET'] = 2028)] = 'HEADICONS_SET'; + ScriptOpcode2[(ScriptOpcode2['HEALENERGY'] = 2029)] = 'HEALENERGY'; + ScriptOpcode2[(ScriptOpcode2['HINT_COORD'] = 2030)] = 'HINT_COORD'; + ScriptOpcode2[(ScriptOpcode2['HINT_NPC'] = 2031)] = 'HINT_NPC'; + ScriptOpcode2[(ScriptOpcode2['HINT_PLAYER'] = 2032)] = 'HINT_PLAYER'; + ScriptOpcode2[(ScriptOpcode2['HINT_STOP'] = 2033)] = 'HINT_STOP'; + ScriptOpcode2[(ScriptOpcode2['IF_CLOSE'] = 2034)] = 'IF_CLOSE'; + ScriptOpcode2[(ScriptOpcode2['IF_CLOSESTICKY'] = 2035)] = 'IF_CLOSESTICKY'; + ScriptOpcode2[(ScriptOpcode2['IF_MULTIZONE'] = 2036)] = 'IF_MULTIZONE'; + ScriptOpcode2[(ScriptOpcode2['IF_OPENCHAT'] = 2037)] = 'IF_OPENCHAT'; + ScriptOpcode2[(ScriptOpcode2['IF_OPENCHATSTICKY'] = 2038)] = 'IF_OPENCHATSTICKY'; + ScriptOpcode2[(ScriptOpcode2['IF_OPENMAINMODAL'] = 2039)] = 'IF_OPENMAINMODAL'; + ScriptOpcode2[(ScriptOpcode2['IF_OPENMAINMODALSIDEOVERLAY'] = 2040)] = 'IF_OPENMAINMODALSIDEOVERLAY'; + ScriptOpcode2[(ScriptOpcode2['IF_OPENSIDEOVERLAY'] = 2041)] = 'IF_OPENSIDEOVERLAY'; + ScriptOpcode2[(ScriptOpcode2['IF_SETANIM'] = 2042)] = 'IF_SETANIM'; + ScriptOpcode2[(ScriptOpcode2['IF_SETCOLOUR'] = 2043)] = 'IF_SETCOLOUR'; + ScriptOpcode2[(ScriptOpcode2['IF_SETHIDE'] = 2044)] = 'IF_SETHIDE'; + ScriptOpcode2[(ScriptOpcode2['IF_SETMODEL'] = 2045)] = 'IF_SETMODEL'; + ScriptOpcode2[(ScriptOpcode2['IF_SETRECOL'] = 2046)] = 'IF_SETRECOL'; + ScriptOpcode2[(ScriptOpcode2['IF_SETNPCHEAD'] = 2047)] = 'IF_SETNPCHEAD'; + ScriptOpcode2[(ScriptOpcode2['IF_SETOBJECT'] = 2048)] = 'IF_SETOBJECT'; + ScriptOpcode2[(ScriptOpcode2['IF_SETPLAYERHEAD'] = 2049)] = 'IF_SETPLAYERHEAD'; + ScriptOpcode2[(ScriptOpcode2['IF_SETPOSITION'] = 2050)] = 'IF_SETPOSITION'; + ScriptOpcode2[(ScriptOpcode2['IF_SETRESUMEBUTTONS'] = 2051)] = 'IF_SETRESUMEBUTTONS'; + ScriptOpcode2[(ScriptOpcode2['IF_SETTAB'] = 2052)] = 'IF_SETTAB'; + ScriptOpcode2[(ScriptOpcode2['IF_SETTABACTIVE'] = 2053)] = 'IF_SETTABACTIVE'; + ScriptOpcode2[(ScriptOpcode2['IF_SETTABFLASH'] = 2054)] = 'IF_SETTABFLASH'; + ScriptOpcode2[(ScriptOpcode2['IF_SETTEXT'] = 2055)] = 'IF_SETTEXT'; + ScriptOpcode2[(ScriptOpcode2['LAST_LOGIN_INFO'] = 2056)] = 'LAST_LOGIN_INFO'; + ScriptOpcode2[(ScriptOpcode2['LAST_COM'] = 2057)] = 'LAST_COM'; + ScriptOpcode2[(ScriptOpcode2['LAST_INT'] = 2058)] = 'LAST_INT'; + ScriptOpcode2[(ScriptOpcode2['LAST_ITEM'] = 2059)] = 'LAST_ITEM'; + ScriptOpcode2[(ScriptOpcode2['LAST_SLOT'] = 2060)] = 'LAST_SLOT'; + ScriptOpcode2[(ScriptOpcode2['LAST_TARGETSLOT'] = 2061)] = 'LAST_TARGETSLOT'; + ScriptOpcode2[(ScriptOpcode2['LAST_USEITEM'] = 2062)] = 'LAST_USEITEM'; + ScriptOpcode2[(ScriptOpcode2['LAST_USESLOT'] = 2063)] = 'LAST_USESLOT'; + ScriptOpcode2[(ScriptOpcode2['LONGQUEUE'] = 2064)] = 'LONGQUEUE'; + ScriptOpcode2[(ScriptOpcode2['MES'] = 2065)] = 'MES'; + ScriptOpcode2[(ScriptOpcode2['MIDI_JINGLE'] = 2066)] = 'MIDI_JINGLE'; + ScriptOpcode2[(ScriptOpcode2['MIDI_SONG'] = 2067)] = 'MIDI_SONG'; + ScriptOpcode2[(ScriptOpcode2['NAME'] = 2068)] = 'NAME'; + ScriptOpcode2[(ScriptOpcode2['P_APRANGE'] = 2069)] = 'P_APRANGE'; + ScriptOpcode2[(ScriptOpcode2['P_ARRIVEDELAY'] = 2070)] = 'P_ARRIVEDELAY'; + ScriptOpcode2[(ScriptOpcode2['P_COUNTDIALOG'] = 2071)] = 'P_COUNTDIALOG'; + ScriptOpcode2[(ScriptOpcode2['P_DELAY'] = 2072)] = 'P_DELAY'; + ScriptOpcode2[(ScriptOpcode2['P_EXACTMOVE'] = 2073)] = 'P_EXACTMOVE'; + ScriptOpcode2[(ScriptOpcode2['P_FINDUID'] = 2074)] = 'P_FINDUID'; + ScriptOpcode2[(ScriptOpcode2['P_LOCMERGE'] = 2075)] = 'P_LOCMERGE'; + ScriptOpcode2[(ScriptOpcode2['P_LOGOUT'] = 2076)] = 'P_LOGOUT'; + ScriptOpcode2[(ScriptOpcode2['P_OPHELD'] = 2077)] = 'P_OPHELD'; + ScriptOpcode2[(ScriptOpcode2['P_OPLOC'] = 2078)] = 'P_OPLOC'; + ScriptOpcode2[(ScriptOpcode2['P_OPNPC'] = 2079)] = 'P_OPNPC'; + ScriptOpcode2[(ScriptOpcode2['P_OPNPCT'] = 2080)] = 'P_OPNPCT'; + ScriptOpcode2[(ScriptOpcode2['P_OPOBJ'] = 2081)] = 'P_OPOBJ'; + ScriptOpcode2[(ScriptOpcode2['P_OPPLAYER'] = 2082)] = 'P_OPPLAYER'; + ScriptOpcode2[(ScriptOpcode2['P_OPPLAYERT'] = 2083)] = 'P_OPPLAYERT'; + ScriptOpcode2[(ScriptOpcode2['P_PAUSEBUTTON'] = 2084)] = 'P_PAUSEBUTTON'; + ScriptOpcode2[(ScriptOpcode2['P_STOPACTION'] = 2085)] = 'P_STOPACTION'; + ScriptOpcode2[(ScriptOpcode2['P_TELEJUMP'] = 2086)] = 'P_TELEJUMP'; + ScriptOpcode2[(ScriptOpcode2['P_TELEPORT'] = 2087)] = 'P_TELEPORT'; + ScriptOpcode2[(ScriptOpcode2['P_WALK'] = 2088)] = 'P_WALK'; + ScriptOpcode2[(ScriptOpcode2['PLAYER_FINDALLZONE'] = 2089)] = 'PLAYER_FINDALLZONE'; + ScriptOpcode2[(ScriptOpcode2['PLAYER_FINDNEXT'] = 2090)] = 'PLAYER_FINDNEXT'; + ScriptOpcode2[(ScriptOpcode2['QUEUE'] = 2091)] = 'QUEUE'; + ScriptOpcode2[(ScriptOpcode2['SAY'] = 2092)] = 'SAY'; + ScriptOpcode2[(ScriptOpcode2['WALKTRIGGER'] = 2093)] = 'WALKTRIGGER'; + ScriptOpcode2[(ScriptOpcode2['SETTIMER'] = 2094)] = 'SETTIMER'; + ScriptOpcode2[(ScriptOpcode2['SOFTTIMER'] = 2095)] = 'SOFTTIMER'; + ScriptOpcode2[(ScriptOpcode2['SOUND_SYNTH'] = 2096)] = 'SOUND_SYNTH'; + ScriptOpcode2[(ScriptOpcode2['SPOTANIM_PL'] = 2097)] = 'SPOTANIM_PL'; + ScriptOpcode2[(ScriptOpcode2['STAFFMODLEVEL'] = 2098)] = 'STAFFMODLEVEL'; + ScriptOpcode2[(ScriptOpcode2['STAT'] = 2099)] = 'STAT'; + ScriptOpcode2[(ScriptOpcode2['STAT_ADD'] = 2100)] = 'STAT_ADD'; + ScriptOpcode2[(ScriptOpcode2['STAT_BASE'] = 2101)] = 'STAT_BASE'; + ScriptOpcode2[(ScriptOpcode2['STAT_HEAL'] = 2102)] = 'STAT_HEAL'; + ScriptOpcode2[(ScriptOpcode2['STAT_SUB'] = 2103)] = 'STAT_SUB'; + ScriptOpcode2[(ScriptOpcode2['STRONGQUEUE'] = 2104)] = 'STRONGQUEUE'; + ScriptOpcode2[(ScriptOpcode2['UID'] = 2105)] = 'UID'; + ScriptOpcode2[(ScriptOpcode2['WEAKQUEUE'] = 2106)] = 'WEAKQUEUE'; + ScriptOpcode2[(ScriptOpcode2['IF_OPENMAINOVERLAY'] = 2107)] = 'IF_OPENMAINOVERLAY'; + ScriptOpcode2[(ScriptOpcode2['AFK_EVENT'] = 2108)] = 'AFK_EVENT'; + ScriptOpcode2[(ScriptOpcode2['LOWMEMORY'] = 2109)] = 'LOWMEMORY'; + ScriptOpcode2[(ScriptOpcode2['SETIDKIT'] = 2110)] = 'SETIDKIT'; + ScriptOpcode2[(ScriptOpcode2['P_CLEARPENDINGACTION'] = 2111)] = 'P_CLEARPENDINGACTION'; + ScriptOpcode2[(ScriptOpcode2['GETWALKTRIGGER'] = 2112)] = 'GETWALKTRIGGER'; + ScriptOpcode2[(ScriptOpcode2['BUSY2'] = 2113)] = 'BUSY2'; + ScriptOpcode2[(ScriptOpcode2['FINDHERO'] = 2114)] = 'FINDHERO'; + ScriptOpcode2[(ScriptOpcode2['BOTH_HEROPOINTS'] = 2115)] = 'BOTH_HEROPOINTS'; + ScriptOpcode2[(ScriptOpcode2['SETGENDER'] = 2116)] = 'SETGENDER'; + ScriptOpcode2[(ScriptOpcode2['SETSKINCOLOUR'] = 2117)] = 'SETSKINCOLOUR'; + ScriptOpcode2[(ScriptOpcode2['P_ANIMPROTECT'] = 2118)] = 'P_ANIMPROTECT'; + ScriptOpcode2[(ScriptOpcode2['RUNENERGY'] = 2119)] = 'RUNENERGY'; + ScriptOpcode2[(ScriptOpcode2['WEIGHT'] = 2120)] = 'WEIGHT'; + ScriptOpcode2[(ScriptOpcode2['LAST_COORD'] = 2121)] = 'LAST_COORD'; + ScriptOpcode2[(ScriptOpcode2['NPC_ADD'] = 2500)] = 'NPC_ADD'; + ScriptOpcode2[(ScriptOpcode2['NPC_ANIM'] = 2501)] = 'NPC_ANIM'; + ScriptOpcode2[(ScriptOpcode2['NPC_BASESTAT'] = 2502)] = 'NPC_BASESTAT'; + ScriptOpcode2[(ScriptOpcode2['NPC_CATEGORY'] = 2503)] = 'NPC_CATEGORY'; + ScriptOpcode2[(ScriptOpcode2['NPC_CHANGETYPE'] = 2504)] = 'NPC_CHANGETYPE'; + ScriptOpcode2[(ScriptOpcode2['NPC_COORD'] = 2505)] = 'NPC_COORD'; + ScriptOpcode2[(ScriptOpcode2['NPC_DAMAGE'] = 2506)] = 'NPC_DAMAGE'; + ScriptOpcode2[(ScriptOpcode2['NPC_DEL'] = 2507)] = 'NPC_DEL'; + ScriptOpcode2[(ScriptOpcode2['NPC_DELAY'] = 2508)] = 'NPC_DELAY'; + ScriptOpcode2[(ScriptOpcode2['NPC_FACESQUARE'] = 2509)] = 'NPC_FACESQUARE'; + ScriptOpcode2[(ScriptOpcode2['NPC_FIND'] = 2510)] = 'NPC_FIND'; + ScriptOpcode2[(ScriptOpcode2['NPC_FINDALLANY'] = 2511)] = 'NPC_FINDALLANY'; + ScriptOpcode2[(ScriptOpcode2['NPC_FINDEXACT'] = 2512)] = 'NPC_FINDEXACT'; + ScriptOpcode2[(ScriptOpcode2['NPC_FINDHERO'] = 2513)] = 'NPC_FINDHERO'; + ScriptOpcode2[(ScriptOpcode2['NPC_FINDALLZONE'] = 2514)] = 'NPC_FINDALLZONE'; + ScriptOpcode2[(ScriptOpcode2['NPC_FINDNEXT'] = 2515)] = 'NPC_FINDNEXT'; + ScriptOpcode2[(ScriptOpcode2['NPC_FINDUID'] = 2516)] = 'NPC_FINDUID'; + ScriptOpcode2[(ScriptOpcode2['NPC_GETMODE'] = 2517)] = 'NPC_GETMODE'; + ScriptOpcode2[(ScriptOpcode2['NPC_HEROPOINTS'] = 2518)] = 'NPC_HEROPOINTS'; + ScriptOpcode2[(ScriptOpcode2['NPC_NAME'] = 2519)] = 'NPC_NAME'; + ScriptOpcode2[(ScriptOpcode2['NPC_PARAM'] = 2520)] = 'NPC_PARAM'; + ScriptOpcode2[(ScriptOpcode2['NPC_QUEUE'] = 2521)] = 'NPC_QUEUE'; + ScriptOpcode2[(ScriptOpcode2['NPC_RANGE'] = 2522)] = 'NPC_RANGE'; + ScriptOpcode2[(ScriptOpcode2['NPC_SAY'] = 2523)] = 'NPC_SAY'; + ScriptOpcode2[(ScriptOpcode2['NPC_HUNTALL'] = 2524)] = 'NPC_HUNTALL'; + ScriptOpcode2[(ScriptOpcode2['NPC_HUNTNEXT'] = 2525)] = 'NPC_HUNTNEXT'; + ScriptOpcode2[(ScriptOpcode2['NPC_SETHUNT'] = 2526)] = 'NPC_SETHUNT'; + ScriptOpcode2[(ScriptOpcode2['NPC_SETHUNTMODE'] = 2527)] = 'NPC_SETHUNTMODE'; + ScriptOpcode2[(ScriptOpcode2['NPC_SETMODE'] = 2528)] = 'NPC_SETMODE'; + ScriptOpcode2[(ScriptOpcode2['NPC_WALKTRIGGER'] = 2529)] = 'NPC_WALKTRIGGER'; + ScriptOpcode2[(ScriptOpcode2['NPC_SETTIMER'] = 2530)] = 'NPC_SETTIMER'; + ScriptOpcode2[(ScriptOpcode2['NPC_STAT'] = 2531)] = 'NPC_STAT'; + ScriptOpcode2[(ScriptOpcode2['NPC_STATADD'] = 2532)] = 'NPC_STATADD'; + ScriptOpcode2[(ScriptOpcode2['NPC_STATHEAL'] = 2533)] = 'NPC_STATHEAL'; + ScriptOpcode2[(ScriptOpcode2['NPC_STATSUB'] = 2534)] = 'NPC_STATSUB'; + ScriptOpcode2[(ScriptOpcode2['NPC_TELE'] = 2535)] = 'NPC_TELE'; + ScriptOpcode2[(ScriptOpcode2['NPC_TYPE'] = 2536)] = 'NPC_TYPE'; + ScriptOpcode2[(ScriptOpcode2['NPC_UID'] = 2537)] = 'NPC_UID'; + ScriptOpcode2[(ScriptOpcode2['SPOTANIM_NPC'] = 2538)] = 'SPOTANIM_NPC'; + ScriptOpcode2[(ScriptOpcode2['NPC_WALK'] = 2539)] = 'NPC_WALK'; + ScriptOpcode2[(ScriptOpcode2['NPC_ATTACKRANGE'] = 2540)] = 'NPC_ATTACKRANGE'; + ScriptOpcode2[(ScriptOpcode2['LOC_ADD'] = 3000)] = 'LOC_ADD'; + ScriptOpcode2[(ScriptOpcode2['LOC_ANGLE'] = 3001)] = 'LOC_ANGLE'; + ScriptOpcode2[(ScriptOpcode2['LOC_ANIM'] = 3002)] = 'LOC_ANIM'; + ScriptOpcode2[(ScriptOpcode2['LOC_CATEGORY'] = 3003)] = 'LOC_CATEGORY'; + ScriptOpcode2[(ScriptOpcode2['LOC_CHANGE'] = 3004)] = 'LOC_CHANGE'; + ScriptOpcode2[(ScriptOpcode2['LOC_COORD'] = 3005)] = 'LOC_COORD'; + ScriptOpcode2[(ScriptOpcode2['LOC_DEL'] = 3006)] = 'LOC_DEL'; + ScriptOpcode2[(ScriptOpcode2['LOC_FIND'] = 3007)] = 'LOC_FIND'; + ScriptOpcode2[(ScriptOpcode2['LOC_FINDALLZONE'] = 3008)] = 'LOC_FINDALLZONE'; + ScriptOpcode2[(ScriptOpcode2['LOC_FINDNEXT'] = 3009)] = 'LOC_FINDNEXT'; + ScriptOpcode2[(ScriptOpcode2['LOC_NAME'] = 3010)] = 'LOC_NAME'; + ScriptOpcode2[(ScriptOpcode2['LOC_PARAM'] = 3011)] = 'LOC_PARAM'; + ScriptOpcode2[(ScriptOpcode2['LOC_SHAPE'] = 3012)] = 'LOC_SHAPE'; + ScriptOpcode2[(ScriptOpcode2['LOC_TYPE'] = 3013)] = 'LOC_TYPE'; + ScriptOpcode2[(ScriptOpcode2['OBJ_ADD'] = 3500)] = 'OBJ_ADD'; + ScriptOpcode2[(ScriptOpcode2['OBJ_ADDALL'] = 3501)] = 'OBJ_ADDALL'; + ScriptOpcode2[(ScriptOpcode2['OBJ_COORD'] = 3502)] = 'OBJ_COORD'; + ScriptOpcode2[(ScriptOpcode2['OBJ_COUNT'] = 3503)] = 'OBJ_COUNT'; + ScriptOpcode2[(ScriptOpcode2['OBJ_DEL'] = 3504)] = 'OBJ_DEL'; + ScriptOpcode2[(ScriptOpcode2['OBJ_NAME'] = 3505)] = 'OBJ_NAME'; + ScriptOpcode2[(ScriptOpcode2['OBJ_PARAM'] = 3506)] = 'OBJ_PARAM'; + ScriptOpcode2[(ScriptOpcode2['OBJ_TAKEITEM'] = 3507)] = 'OBJ_TAKEITEM'; + ScriptOpcode2[(ScriptOpcode2['OBJ_TYPE'] = 3508)] = 'OBJ_TYPE'; + ScriptOpcode2[(ScriptOpcode2['NC_CATEGORY'] = 4000)] = 'NC_CATEGORY'; + ScriptOpcode2[(ScriptOpcode2['NC_DEBUGNAME'] = 4001)] = 'NC_DEBUGNAME'; + ScriptOpcode2[(ScriptOpcode2['NC_DESC'] = 4002)] = 'NC_DESC'; + ScriptOpcode2[(ScriptOpcode2['NC_NAME'] = 4003)] = 'NC_NAME'; + ScriptOpcode2[(ScriptOpcode2['NC_OP'] = 4004)] = 'NC_OP'; + ScriptOpcode2[(ScriptOpcode2['NC_PARAM'] = 4005)] = 'NC_PARAM'; + ScriptOpcode2[(ScriptOpcode2['LC_CATEGORY'] = 4100)] = 'LC_CATEGORY'; + ScriptOpcode2[(ScriptOpcode2['LC_DEBUGNAME'] = 4101)] = 'LC_DEBUGNAME'; + ScriptOpcode2[(ScriptOpcode2['LC_DESC'] = 4102)] = 'LC_DESC'; + ScriptOpcode2[(ScriptOpcode2['LC_NAME'] = 4103)] = 'LC_NAME'; + ScriptOpcode2[(ScriptOpcode2['LC_OP'] = 4104)] = 'LC_OP'; + ScriptOpcode2[(ScriptOpcode2['LC_PARAM'] = 4105)] = 'LC_PARAM'; + ScriptOpcode2[(ScriptOpcode2['LC_WIDTH'] = 4106)] = 'LC_WIDTH'; + ScriptOpcode2[(ScriptOpcode2['LC_LENGTH'] = 4107)] = 'LC_LENGTH'; + ScriptOpcode2[(ScriptOpcode2['OC_CATEGORY'] = 4200)] = 'OC_CATEGORY'; + ScriptOpcode2[(ScriptOpcode2['OC_CERT'] = 4201)] = 'OC_CERT'; + ScriptOpcode2[(ScriptOpcode2['OC_COST'] = 4202)] = 'OC_COST'; + ScriptOpcode2[(ScriptOpcode2['OC_DEBUGNAME'] = 4203)] = 'OC_DEBUGNAME'; + ScriptOpcode2[(ScriptOpcode2['OC_DESC'] = 4204)] = 'OC_DESC'; + ScriptOpcode2[(ScriptOpcode2['OC_IOP'] = 4205)] = 'OC_IOP'; + ScriptOpcode2[(ScriptOpcode2['OC_MEMBERS'] = 4206)] = 'OC_MEMBERS'; + ScriptOpcode2[(ScriptOpcode2['OC_NAME'] = 4207)] = 'OC_NAME'; + ScriptOpcode2[(ScriptOpcode2['OC_OP'] = 4208)] = 'OC_OP'; + ScriptOpcode2[(ScriptOpcode2['OC_PARAM'] = 4209)] = 'OC_PARAM'; + ScriptOpcode2[(ScriptOpcode2['OC_STACKABLE'] = 4210)] = 'OC_STACKABLE'; + ScriptOpcode2[(ScriptOpcode2['OC_TRADEABLE'] = 4211)] = 'OC_TRADEABLE'; + ScriptOpcode2[(ScriptOpcode2['OC_UNCERT'] = 4212)] = 'OC_UNCERT'; + ScriptOpcode2[(ScriptOpcode2['OC_WEARPOS2'] = 4213)] = 'OC_WEARPOS2'; + ScriptOpcode2[(ScriptOpcode2['OC_WEARPOS3'] = 4214)] = 'OC_WEARPOS3'; + ScriptOpcode2[(ScriptOpcode2['OC_WEARPOS'] = 4215)] = 'OC_WEARPOS'; + ScriptOpcode2[(ScriptOpcode2['OC_WEIGHT'] = 4216)] = 'OC_WEIGHT'; + ScriptOpcode2[(ScriptOpcode2['INV_ALLSTOCK'] = 4300)] = 'INV_ALLSTOCK'; + ScriptOpcode2[(ScriptOpcode2['INV_SIZE'] = 4301)] = 'INV_SIZE'; + ScriptOpcode2[(ScriptOpcode2['INV_STOCKBASE'] = 4302)] = 'INV_STOCKBASE'; + ScriptOpcode2[(ScriptOpcode2['INV_ADD'] = 4303)] = 'INV_ADD'; + ScriptOpcode2[(ScriptOpcode2['INV_CHANGESLOT'] = 4304)] = 'INV_CHANGESLOT'; + ScriptOpcode2[(ScriptOpcode2['INV_CLEAR'] = 4305)] = 'INV_CLEAR'; + ScriptOpcode2[(ScriptOpcode2['INV_DEL'] = 4306)] = 'INV_DEL'; + ScriptOpcode2[(ScriptOpcode2['INV_DELSLOT'] = 4307)] = 'INV_DELSLOT'; + ScriptOpcode2[(ScriptOpcode2['INV_DROPITEM'] = 4308)] = 'INV_DROPITEM'; + ScriptOpcode2[(ScriptOpcode2['INV_DROPSLOT'] = 4309)] = 'INV_DROPSLOT'; + ScriptOpcode2[(ScriptOpcode2['INV_FREESPACE'] = 4310)] = 'INV_FREESPACE'; + ScriptOpcode2[(ScriptOpcode2['INV_GETNUM'] = 4311)] = 'INV_GETNUM'; + ScriptOpcode2[(ScriptOpcode2['INV_GETOBJ'] = 4312)] = 'INV_GETOBJ'; + ScriptOpcode2[(ScriptOpcode2['INV_ITEMSPACE'] = 4313)] = 'INV_ITEMSPACE'; + ScriptOpcode2[(ScriptOpcode2['INV_ITEMSPACE2'] = 4314)] = 'INV_ITEMSPACE2'; + ScriptOpcode2[(ScriptOpcode2['INV_MOVEFROMSLOT'] = 4315)] = 'INV_MOVEFROMSLOT'; + ScriptOpcode2[(ScriptOpcode2['INV_MOVETOSLOT'] = 4316)] = 'INV_MOVETOSLOT'; + ScriptOpcode2[(ScriptOpcode2['BOTH_MOVEINV'] = 4317)] = 'BOTH_MOVEINV'; + ScriptOpcode2[(ScriptOpcode2['INV_MOVEITEM'] = 4318)] = 'INV_MOVEITEM'; + ScriptOpcode2[(ScriptOpcode2['INV_MOVEITEM_CERT'] = 4319)] = 'INV_MOVEITEM_CERT'; + ScriptOpcode2[(ScriptOpcode2['INV_MOVEITEM_UNCERT'] = 4320)] = 'INV_MOVEITEM_UNCERT'; + ScriptOpcode2[(ScriptOpcode2['INV_SETSLOT'] = 4321)] = 'INV_SETSLOT'; + ScriptOpcode2[(ScriptOpcode2['INV_TOTAL'] = 4322)] = 'INV_TOTAL'; + ScriptOpcode2[(ScriptOpcode2['INV_TOTALCAT'] = 4323)] = 'INV_TOTALCAT'; + ScriptOpcode2[(ScriptOpcode2['INV_TRANSMIT'] = 4324)] = 'INV_TRANSMIT'; + ScriptOpcode2[(ScriptOpcode2['INVOTHER_TRANSMIT'] = 4325)] = 'INVOTHER_TRANSMIT'; + ScriptOpcode2[(ScriptOpcode2['INV_STOPTRANSMIT'] = 4326)] = 'INV_STOPTRANSMIT'; + ScriptOpcode2[(ScriptOpcode2['BOTH_DROPSLOT'] = 4327)] = 'BOTH_DROPSLOT'; + ScriptOpcode2[(ScriptOpcode2['INV_DROPALL'] = 4328)] = 'INV_DROPALL'; + ScriptOpcode2[(ScriptOpcode2['INV_TOTALPARAM'] = 4329)] = 'INV_TOTALPARAM'; + ScriptOpcode2[(ScriptOpcode2['INV_TOTALPARAM_STACK'] = 4330)] = 'INV_TOTALPARAM_STACK'; + ScriptOpcode2[(ScriptOpcode2['ENUM'] = 4400)] = 'ENUM'; + ScriptOpcode2[(ScriptOpcode2['ENUM_GETOUTPUTCOUNT'] = 4401)] = 'ENUM_GETOUTPUTCOUNT'; + ScriptOpcode2[(ScriptOpcode2['APPEND_NUM'] = 4500)] = 'APPEND_NUM'; + ScriptOpcode2[(ScriptOpcode2['APPEND'] = 4501)] = 'APPEND'; + ScriptOpcode2[(ScriptOpcode2['APPEND_SIGNNUM'] = 4502)] = 'APPEND_SIGNNUM'; + ScriptOpcode2[(ScriptOpcode2['LOWERCASE'] = 4503)] = 'LOWERCASE'; + ScriptOpcode2[(ScriptOpcode2['TEXT_GENDER'] = 4504)] = 'TEXT_GENDER'; + ScriptOpcode2[(ScriptOpcode2['TOSTRING'] = 4505)] = 'TOSTRING'; + ScriptOpcode2[(ScriptOpcode2['COMPARE'] = 4506)] = 'COMPARE'; + ScriptOpcode2[(ScriptOpcode2['TEXT_SWITCH'] = 4507)] = 'TEXT_SWITCH'; + ScriptOpcode2[(ScriptOpcode2['APPEND_CHAR'] = 4508)] = 'APPEND_CHAR'; + ScriptOpcode2[(ScriptOpcode2['STRING_LENGTH'] = 4509)] = 'STRING_LENGTH'; + ScriptOpcode2[(ScriptOpcode2['SUBSTRING'] = 4510)] = 'SUBSTRING'; + ScriptOpcode2[(ScriptOpcode2['STRING_INDEXOF_CHAR'] = 4511)] = 'STRING_INDEXOF_CHAR'; + ScriptOpcode2[(ScriptOpcode2['STRING_INDEXOF_STRING'] = 4512)] = 'STRING_INDEXOF_STRING'; + ScriptOpcode2[(ScriptOpcode2['ADD'] = 4600)] = 'ADD'; + ScriptOpcode2[(ScriptOpcode2['SUB'] = 4601)] = 'SUB'; + ScriptOpcode2[(ScriptOpcode2['MULTIPLY'] = 4602)] = 'MULTIPLY'; + ScriptOpcode2[(ScriptOpcode2['DIVIDE'] = 4603)] = 'DIVIDE'; + ScriptOpcode2[(ScriptOpcode2['RANDOM'] = 4604)] = 'RANDOM'; + ScriptOpcode2[(ScriptOpcode2['RANDOMINC'] = 4605)] = 'RANDOMINC'; + ScriptOpcode2[(ScriptOpcode2['INTERPOLATE'] = 4606)] = 'INTERPOLATE'; + ScriptOpcode2[(ScriptOpcode2['ADDPERCENT'] = 4607)] = 'ADDPERCENT'; + ScriptOpcode2[(ScriptOpcode2['SETBIT'] = 4608)] = 'SETBIT'; + ScriptOpcode2[(ScriptOpcode2['CLEARBIT'] = 4609)] = 'CLEARBIT'; + ScriptOpcode2[(ScriptOpcode2['TESTBIT'] = 4610)] = 'TESTBIT'; + ScriptOpcode2[(ScriptOpcode2['MODULO'] = 4611)] = 'MODULO'; + ScriptOpcode2[(ScriptOpcode2['POW'] = 4612)] = 'POW'; + ScriptOpcode2[(ScriptOpcode2['INVPOW'] = 4613)] = 'INVPOW'; + ScriptOpcode2[(ScriptOpcode2['AND'] = 4614)] = 'AND'; + ScriptOpcode2[(ScriptOpcode2['OR'] = 4615)] = 'OR'; + ScriptOpcode2[(ScriptOpcode2['MIN'] = 4616)] = 'MIN'; + ScriptOpcode2[(ScriptOpcode2['MAX'] = 4617)] = 'MAX'; + ScriptOpcode2[(ScriptOpcode2['SCALE'] = 4618)] = 'SCALE'; + ScriptOpcode2[(ScriptOpcode2['BITCOUNT'] = 4619)] = 'BITCOUNT'; + ScriptOpcode2[(ScriptOpcode2['TOGGLEBIT'] = 4620)] = 'TOGGLEBIT'; + ScriptOpcode2[(ScriptOpcode2['SETBIT_RANGE'] = 4621)] = 'SETBIT_RANGE'; + ScriptOpcode2[(ScriptOpcode2['CLEARBIT_RANGE'] = 4622)] = 'CLEARBIT_RANGE'; + ScriptOpcode2[(ScriptOpcode2['GETBIT_RANGE'] = 4623)] = 'GETBIT_RANGE'; + ScriptOpcode2[(ScriptOpcode2['SETBIT_RANGE_TOINT'] = 4624)] = 'SETBIT_RANGE_TOINT'; + ScriptOpcode2[(ScriptOpcode2['SIN_DEG'] = 4625)] = 'SIN_DEG'; + ScriptOpcode2[(ScriptOpcode2['COS_DEG'] = 4626)] = 'COS_DEG'; + ScriptOpcode2[(ScriptOpcode2['ATAN2_DEG'] = 4627)] = 'ATAN2_DEG'; + ScriptOpcode2[(ScriptOpcode2['ABS'] = 4628)] = 'ABS'; + ScriptOpcode2[(ScriptOpcode2['DB_FIND_WITH_COUNT'] = 7500)] = 'DB_FIND_WITH_COUNT'; + ScriptOpcode2[(ScriptOpcode2['DB_FINDNEXT'] = 7501)] = 'DB_FINDNEXT'; + ScriptOpcode2[(ScriptOpcode2['DB_GETFIELD'] = 7502)] = 'DB_GETFIELD'; + ScriptOpcode2[(ScriptOpcode2['DB_GETFIELDCOUNT'] = 7503)] = 'DB_GETFIELDCOUNT'; + ScriptOpcode2[(ScriptOpcode2['DB_LISTALL_WITH_COUNT'] = 7504)] = 'DB_LISTALL_WITH_COUNT'; + ScriptOpcode2[(ScriptOpcode2['DB_GETROWTABLE'] = 7505)] = 'DB_GETROWTABLE'; + ScriptOpcode2[(ScriptOpcode2['DB_FINDBYINDEX'] = 7506)] = 'DB_FINDBYINDEX'; + ScriptOpcode2[(ScriptOpcode2['DB_FIND_REFINE_WITH_COUNT'] = 7507)] = 'DB_FIND_REFINE_WITH_COUNT'; + ScriptOpcode2[(ScriptOpcode2['DB_FIND'] = 7508)] = 'DB_FIND'; + ScriptOpcode2[(ScriptOpcode2['DB_FIND_REFINE'] = 7509)] = 'DB_FIND_REFINE'; + ScriptOpcode2[(ScriptOpcode2['DB_LISTALL'] = 7510)] = 'DB_LISTALL'; + ScriptOpcode2[(ScriptOpcode2['ERROR'] = 1e4)] = 'ERROR'; + ScriptOpcode2[(ScriptOpcode2['MAP_PRODUCTION'] = 10001)] = 'MAP_PRODUCTION'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTCLOCK'] = 10002)] = 'MAP_LASTCLOCK'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTWORLD'] = 10003)] = 'MAP_LASTWORLD'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTCLIENTIN'] = 10004)] = 'MAP_LASTCLIENTIN'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTNPC'] = 10005)] = 'MAP_LASTNPC'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTPLAYER'] = 10006)] = 'MAP_LASTPLAYER'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTLOGOUT'] = 10007)] = 'MAP_LASTLOGOUT'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTLOGIN'] = 10008)] = 'MAP_LASTLOGIN'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTZONE'] = 10009)] = 'MAP_LASTZONE'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTCLIENTOUT'] = 10010)] = 'MAP_LASTCLIENTOUT'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTCLEANUP'] = 10011)] = 'MAP_LASTCLEANUP'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTBANDWIDTHIN'] = 10012)] = 'MAP_LASTBANDWIDTHIN'; + ScriptOpcode2[(ScriptOpcode2['MAP_LASTBANDWIDTHOUT'] = 10013)] = 'MAP_LASTBANDWIDTHOUT'; +})((ScriptOpcode ||= {})); +var ScriptOpcode_default = ScriptOpcode; + +// src/lostcity/engine/script/Script.ts +class Script { + info = { + scriptName: '', + sourceFilePath: '', + lookupKey: -1, + parameterTypes: [], + pcs: [], + lines: [] + }; + id; + intLocalCount = 0; + stringLocalCount = 0; + intArgCount = 0; + stringArgCount = 0; + switchTables = []; + opcodes = []; + intOperands = []; + stringOperands = []; + static isLargeOperand(opcode) { + if (opcode > 100) { + return false; + } + switch (opcode) { + case ScriptOpcode_default.RETURN: + case ScriptOpcode_default.POP_INT_DISCARD: + case ScriptOpcode_default.POP_STRING_DISCARD: + case ScriptOpcode_default.GOSUB: + case ScriptOpcode_default.JUMP: + return false; + } + return true; + } + static decode(id, stream) { + const length = stream.data.length; + if (length < 16) { + throw new Error('Invalid script file (minimum length)'); + } + stream.pos = length - 2; + const trailerLen = stream.g2(); + const trailerPos = length - trailerLen - 12 - 2; + if (trailerPos < 0 || trailerPos >= length) { + throw new Error('Invalid script file (bad trailer pos)'); + } + stream.pos = trailerPos; + const script = new Script(id); + const _instructions = stream.g4(); + script.intLocalCount = stream.g2(); + script.stringLocalCount = stream.g2(); + script.intArgCount = stream.g2(); + script.stringArgCount = stream.g2(); + const switches = stream.g1(); + for (let i = 0; i < switches; i++) { + const count = stream.g2(); + const table = []; + for (let j = 0; j < count; j++) { + const key = stream.g4(); + const offset = stream.g4(); + table[key] = offset; + } + script.switchTables[i] = table; + } + stream.pos = 0; + script.info.scriptName = stream.gjstr(0); + script.info.sourceFilePath = stream.gjstr(0); + script.info.lookupKey = stream.g4(); + const parameterTypeCount = stream.g1(); + for (let i = 0; i < parameterTypeCount; i++) { + script.info.parameterTypes.push(stream.g1()); + } + const lineNumberTableLength = stream.g2(); + for (let i = 0; i < lineNumberTableLength; i++) { + script.info.pcs.push(stream.g4()); + script.info.lines.push(stream.g4()); + } + let instr = 0; + while (trailerPos > stream.pos) { + const opcode = stream.g2(); + if (opcode === ScriptOpcode_default.PUSH_CONSTANT_STRING) { + script.stringOperands[instr] = stream.gjstr(0); + } else if (Script.isLargeOperand(opcode)) { + script.intOperands[instr] = stream.g4(); + } else { + script.intOperands[instr] = stream.g1(); + } + script.opcodes[instr++] = opcode; + } + return script; + } + constructor(id) { + this.id = id; + } + get name() { + return this.info.scriptName; + } + get fileName() { + return q.basename(this.info.sourceFilePath); + } + lineNumber(pc2) { + for (let i = 0; i < this.info.pcs.length; i++) { + if (this.info.pcs[i] > pc2) { + return this.info.lines[i - 1]; + } + } + return this.info.lines[this.info.lines.length - 1]; + } +} + +// src/lostcity/engine/script/ScriptProvider.ts +class ScriptProvider { + static COMPILER_VERSION = 18; + static scripts = []; + static scriptLookup = new Map(); + static scriptNames = new Map(); + static load(dir) { + const dat = Packet.load(`${dir}/server/script.dat`); + const idx = Packet.load(`${dir}/server/script.idx`); + return this.parse(dat, idx); + } + static async loadAsync(dir) { + const dat = await Packet.loadAsync(`${dir}/server/script.dat`); + const idx = await Packet.loadAsync(`${dir}/server/script.idx`); + return this.parse(dat, idx); + } + static parse(dat, idx) { + if (!dat.data.length || !idx.data.length) { + console.log('\nFatal: No script.dat or script.idx found. Please run the server:build script.'); + process.exit(1); + } + const entries = dat.g2(); + idx.pos += 2; + const version = dat.g4(); + if (version !== ScriptProvider.COMPILER_VERSION) { + console.error('\nFatal: Scripts were compiled with an older RuneScript compiler. Please update it, try `npm run build` and then restart the server.'); + process.exit(1); + } + const scripts = new Array(entries); + const scriptNames = new Map(); + const scriptLookup = new Map(); + let loaded = 0; + for (let id = 0; id < entries; id++) { + const size = idx.g2(); + if (size === 0) { + continue; + } + try { + const data = new Uint8Array(size); + dat.gdata(data, 0, data.length); + const script = Script.decode(id, new Packet(data)); + scripts[id] = script; + scriptNames.set(script.name, id); + if (script.info.lookupKey !== 4294967295) { + scriptLookup.set(script.info.lookupKey, script); + } + loaded++; + } catch (err) { + console.error(err); + console.error(`Warning: Failed to load script ${id}, something may have been partially written`); + return -1; + } + } + ScriptProvider.scripts = scripts; + ScriptProvider.scriptNames = scriptNames; + ScriptProvider.scriptLookup = scriptLookup; + return loaded; + } + static get(id) { + return this.scripts[id]; + } + static getByName(name) { + const id = ScriptProvider.scriptNames.get(name); + if (id === undefined) { + return; + } + return ScriptProvider.scripts[id]; + } + static getByTrigger(trigger, type = -1, category = -1) { + let script = ScriptProvider.scriptLookup.get(trigger | (2 << 8) | (type << 10)); + if (script) { + return script; + } + script = ScriptProvider.scriptLookup.get(trigger | (1 << 8) | (category << 10)); + if (script) { + return script; + } + return ScriptProvider.scriptLookup.get(trigger); + } + static getByTriggerSpecific(trigger, type = -1, category = -1) { + if (type !== -1) { + return ScriptProvider.scriptLookup.get(trigger | (2 << 8) | (type << 10)); + } else if (category !== -1) { + return ScriptProvider.scriptLookup.get(trigger | (1 << 8) | (category << 10)); + } + return ScriptProvider.scriptLookup.get(trigger); + } +} + +// src/lostcity/engine/script/ScriptRunner.ts +init_path(); + +// src/lostcity/util/Numbers.ts +function toInt32(num) { + return num | 0; +} +function bitcount(num) { + num = num - ((num >> 1) & 1431655765); + num = (num & 858993459) + ((num >> 2) & 858993459); + return (((num + (num >> 4)) & 252645135) * 16843009) >> 24; +} +function setBitRange(num, startBit, endBit) { + const mask = MASK[endBit - startBit + 1]; + return num | (mask << startBit); +} +function clearBitRange(num, startBit, endBit) { + const mask = MASK[endBit - startBit + 1]; + return num & ~(mask << startBit); +} +var initMaskArray = function () { + const data = [0]; + let incrementor = 2; + for (let i = 1; i < 33; ++i) { + data[i] = toInt32(incrementor - 1); + incrementor += incrementor; + } + return data; +}; +var MASK = initMaskArray(); + +// src/lostcity/engine/script/ScriptState.ts +class ScriptState { + static ABORTED = -1; + static RUNNING = 0; + static FINISHED = 1; + static SUSPENDED = 2; + static PAUSEBUTTON = 3; + static COUNTDIALOG = 4; + static NPC_SUSPENDED = 5; + static WORLD_SUSPENDED = 6; + script; + trigger; + execution = ScriptState.RUNNING; + executionHistory = []; + pc = -1; + opcount = 0; + frames = []; + fp = 0; + debugFrames = []; + debugFp = 0; + intStack = []; + isp = 0; + stringStack = []; + ssp = 0; + intLocals = []; + stringLocals = []; + pointers = 0; + self = null; + _activePlayer = null; + _activePlayer2 = null; + _activeNpc = null; + _activeNpc2 = null; + _activeLoc = null; + _activeLoc2 = null; + _activeObj = null; + _activeObj2 = null; + splitPages = []; + splitMesanim = -1; + dbTable = null; + dbColumn = -1; + dbRow = -1; + dbRowQuery = []; + huntIterator = null; + npcIterator = null; + locIterator = null; + lastInt = 0; + constructor(script, args = []) { + this.script = script; + this.trigger = script.info.lookupKey & 255; + if (args) { + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (typeof arg === 'number') { + this.intLocals.push(arg); + } else { + this.stringLocals.push(arg); + } + } + } + } + pointerSet(...pointers) { + this.pointers = 0; + for (let i = 0; i < pointers.length; i++) { + this.pointers |= 1 << pointers[i]; + } + } + pointerAdd(pointer) { + this.pointers |= 1 << pointer; + } + pointerRemove(pointer) { + this.pointers &= ~(1 << pointer); + } + pointerGet(pointer) { + return (this.pointers & (1 << pointer)) != 0; + } + pointerCheck(...pointers) { + for (let i = 0; i < pointers.length; i++) { + const flag = 1 << pointers[i]; + if ((this.pointers & flag) != flag) { + throw new Error(`Required pointer: ${ScriptState.pointerPrint(flag)}, current: ${ScriptState.pointerPrint(this.pointers)}`); + } + } + } + static pointerPrint(flags) { + let text = ''; + for (let i = 0; i < ScriptPointer_default._LAST; i++) { + if ((flags & (1 << i)) != 0) { + text += `${ScriptPointer_default[i]}, `; + } + } + return text.substring(0, text.lastIndexOf(',')); + } + get activePlayer() { + const player = this.intOperand === 0 ? this._activePlayer : this._activePlayer2; + if (player === null) { + throw new Error('Attempt to access null active_player'); + } + return player; + } + set activePlayer(player) { + if (this.intOperand === 0) { + this._activePlayer = player; + } else { + this._activePlayer2 = player; + } + } + get activeNpc() { + const npc = this.intOperand === 0 ? this._activeNpc : this._activeNpc2; + if (npc === null) { + throw new Error('Attempt to access null active_npc'); + } + return npc; + } + set activeNpc(npc) { + if (this.intOperand === 0) { + this._activeNpc = npc; + } else { + this._activeNpc2 = npc; + } + } + get activeLoc() { + const loc = this.intOperand === 0 ? this._activeLoc : this._activeLoc2; + if (loc === null) { + throw new Error('Attempt to access null active_loc'); + } + return loc; + } + set activeLoc(loc) { + if (this.intOperand === 0) { + this._activeLoc = loc; + } else { + this._activeLoc2 = loc; + } + } + get activeObj() { + const obj = this.intOperand === 0 ? this._activeObj : this._activeObj2; + if (obj === null) { + throw new Error('Attempt to access null active_obj'); + } + return obj; + } + set activeObj(obj) { + if (this.intOperand === 0) { + this._activeObj = obj; + } else { + this._activeObj2 = obj; + } + } + get intOperand() { + return this.script.intOperands[this.pc]; + } + get stringOperand() { + return this.script.stringOperands[this.pc]; + } + popInt() { + const value = this.intStack[--this.isp]; + if (!value) { + return 0; + } + return toInt32(value); + } + popInts(amount) { + const ints = Array(amount); + for (let i = amount - 1; i >= 0; i--) { + ints[i] = this.popInt(); + } + return ints; + } + pushInt(value) { + this.intStack[this.isp++] = toInt32(value); + } + popString() { + return this.stringStack[--this.ssp] ?? ''; + } + popStrings(amount) { + const strings = Array(amount); + for (let i = amount - 1; i >= 0; i--) { + strings[i] = this.popString(); + } + return strings; + } + pushString(value) { + this.stringStack[this.ssp++] = value; + } + reset() { + this.pc = -1; + this.frames = []; + this.fp = 0; + this.intStack = []; + this.isp = 0; + this.stringStack = []; + this.ssp = 0; + this.intLocals = []; + this.stringLocals = []; + this.pointers = 0; + } +} + +// src/lostcity/engine/Inventory.ts +class InventoryTransaction { + requested = 0; + completed = 0; + items = []; + constructor(requested, completed = 0, items = []) { + this.requested = requested; + this.completed = completed; + this.items = items; + } + getLeftOver() { + return this.requested - this.completed; + } + hasSucceeded() { + return this.completed == this.requested; + } + hasFailed() { + return !this.hasSucceeded(); + } + revert(from) { + for (let i = 0; i < this.items.length; i++) { + const item = this.items[i].item; + from.remove(item.id, item.count, this.items[i].slot); + } + } +} + +class Inventory { + static STACK_LIMIT = 2147483647; + static NORMAL_STACK = 0; + static ALWAYS_STACK = 1; + static NEVER_STACK = 2; + static fromType(inv) { + if (inv === -1) { + throw new Error('Invalid inventory type'); + } + const type = InvType.get(inv); + let stackType = Inventory.NORMAL_STACK; + if (type.stackall) { + stackType = Inventory.ALWAYS_STACK; + } + const container = new Inventory(inv, type.size, stackType); + if (type.stockobj && type.stockcount && type.stockobj.length) { + for (let i = 0; i < type.stockobj.length; i++) { + container.set(i, { + id: type.stockobj[i], + count: type.stockcount[i] + }); + } + } + return container; + } + stackType; + capacity; + type; + items; + update = false; + constructor(type, capacity, stackType = Inventory.NORMAL_STACK) { + this.type = type; + this.capacity = capacity; + this.stackType = stackType; + this.items = new Array(capacity).fill(null); + } + contains(id) { + return this.items.some(item => item && item.id == id); + } + hasAt(slot, id) { + const item = this.items[slot]; + return item && item.id == id; + } + get nextFreeSlot() { + return this.items.indexOf(null, 0); + } + get freeSlotCount() { + return this.items.filter(item => item == null).length; + } + get occupiedSlotCount() { + return this.items.filter(item => item != null).length; + } + get isFull() { + return this.occupiedSlotCount == this.capacity; + } + get isEmpty() { + return this.occupiedSlotCount == 0; + } + get hasAny() { + return this.items.some(item => item != null); + } + get hasSpace() { + return this.nextFreeSlot != -1; + } + get itemsFiltered() { + return this.items.filter(item => item != null); + } + getItemCount(id) { + let count = 0; + for (let i = 0; i < this.capacity; i++) { + const item = this.items[i]; + if (item && item.id == id) { + count += item.count; + } + } + return Math.min(Inventory.STACK_LIMIT, count); + } + getItemIndex(id) { + return this.items.findIndex(item => item && item.id == id); + } + removeAll() { + this.items.fill(null, 0, this.capacity); + this.update = true; + } + add(id, count = 1, beginSlot = -1, assureFullInsertion = true, forceNoStack = false, dryRun = false) { + const type = ObjType.get(id); + const stockObj = InvType.get(this.type).stockobj?.includes(id) === true; + const stack = !forceNoStack && this.stackType != Inventory.NEVER_STACK && (type.stackable || this.stackType == Inventory.ALWAYS_STACK); + let previousCount = 0; + if (stack) { + previousCount = this.getItemCount(id); + } + if (previousCount == Inventory.STACK_LIMIT) { + return new InventoryTransaction(count, 0, []); + } + const freeSlotCount = this.freeSlotCount; + if (freeSlotCount == 0 && (!stack || (stack && previousCount == 0 && !stockObj))) { + return new InventoryTransaction(count, 0, []); + } + if (assureFullInsertion) { + if (stack && previousCount > Inventory.STACK_LIMIT - count) { + return new InventoryTransaction(count, 0, []); + } + if (!stack && count > freeSlotCount) { + return new InventoryTransaction(count, 0, []); + } + } else { + if (stack && previousCount == Inventory.STACK_LIMIT) { + return new InventoryTransaction(count, 0, []); + } else if (!stack && freeSlotCount == 0) { + return new InventoryTransaction(count, 0, []); + } + } + let completed = 0; + const added = []; + if (!stack) { + const startSlot = Math.max(0, beginSlot); + for (let i = startSlot; i < this.capacity; i++) { + if (this.items[i] != null) { + continue; + } + const add = {id, count: 1}; + if (!dryRun) { + this.set(i, add); + } + added.push({slot: i, item: add}); + if (++completed >= count) { + break; + } + } + } else { + let stackIndex = this.getItemIndex(id); + if (stackIndex == -1) { + if (beginSlot == -1) { + stackIndex = this.nextFreeSlot; + } else { + stackIndex = this.items.indexOf(null, beginSlot); + } + if (stackIndex == -1) { + return new InventoryTransaction(count, completed, []); + } + } + const stackCount = this.get(stackIndex)?.count ?? 0; + const total = Math.min(Inventory.STACK_LIMIT, stackCount + count); + const add = {id, count: total}; + if (!dryRun) { + this.set(stackIndex, add); + } + added.push({slot: stackIndex, item: add}); + completed = total - stackCount; + } + return new InventoryTransaction(count, completed, added); + } + remove(id, count = 1, beginSlot = -1, assureFullRemoval = false) { + const hasCount = this.getItemCount(id); + const stockObj = InvType.get(this.type).stockobj?.includes(id) === true; + if (assureFullRemoval && hasCount < count) { + return new InventoryTransaction(count, 0, []); + } else if (!assureFullRemoval && hasCount < 1) { + return new InventoryTransaction(count, 0, []); + } + let totalRemoved = 0; + const removed = []; + let skippedIndices = null; + if (beginSlot != -1) { + skippedIndices = []; + for (let i = 0; i < beginSlot; i++) { + skippedIndices.push(i); + } + } + let index = 0; + if (beginSlot != -1) { + index = beginSlot; + } + for (let i = index; i < this.capacity; i++) { + const curItem = this.items[i]; + if (!curItem || curItem.id != id) { + continue; + } + const removeCount = Math.min(curItem.count, count - totalRemoved); + totalRemoved += removeCount; + curItem.count -= removeCount; + if (curItem.count == 0 && !stockObj) { + const removedItem = this.items[i]; + this.items[i] = null; + if (removedItem) { + removed.push({slot: i, item: removedItem}); + } + } + if (totalRemoved >= count) { + break; + } + } + if (skippedIndices != null && totalRemoved < count) { + for (let i = 0; i < skippedIndices.length; i++) { + const curItem = this.items[i]; + if (!curItem || curItem.id != id) { + continue; + } + const removeCount = Math.min(curItem.count, count - totalRemoved); + totalRemoved += removeCount; + curItem.count -= removeCount; + if (curItem.count == 0 && !stockObj) { + const removedItem = this.items[i]; + this.items[i] = null; + if (removedItem) { + removed.push({slot: i, item: removedItem}); + } + } + if (totalRemoved >= count) { + break; + } + } + } + if (totalRemoved > 0) { + this.update = true; + } + return new InventoryTransaction(count, totalRemoved, removed); + } + delete(slot) { + this.items[slot] = null; + this.update = true; + } + swap(from, to) { + const temp = this.items[from]; + this.set(from, this.items[to]); + this.set(to, temp); + } + shift() { + this.items.sort((a, b3) => { + if (a === null || b3 === null) { + return +(a === null) - +(b3 === null); + } else { + return +(a > b3) || -(a < b3); + } + }); + this.update = true; + } + get(slot) { + return this.items[slot]; + } + set(slot, item) { + this.items[slot] = item; + this.update = true; + } + validSlot(slot) { + return slot >= 0 && slot < this.capacity; + } + transfer(to, item, fromSlot = -1, toSlot = -1, note = false, unnote = false) { + if (item.count <= 0) { + return null; + } + const count = Math.min(item.count, this.getItemCount(item.id)); + const objType = ObjType.get(item.id); + let finalItem = {id: item.id, count}; + if (note && objType.certlink !== -1 && objType.certtemplate === -1) { + finalItem = {id: objType.certlink, count}; + } else if (unnote && objType.certlink !== -1 && objType.certtemplate >= 0) { + finalItem = {id: objType.certlink, count}; + } + const add = to.add(finalItem.id, finalItem.count, toSlot, false); + if (add.completed == 0) { + return null; + } + const remove = this.remove(item.id, add.completed, fromSlot, false); + if (remove.completed == 0) { + return null; + } + return remove; + } +} + +// node_modules/@2004scape/rsmod-pathfinder/dist/rsmod-pathfinder.js +async function instantiate(module, imports = {}) { + const adaptedImports = { + env: Object.assign(Object.create(globalThis), imports.env || {}, { + abort(message, fileName, lineNumber, columnNumber) { + message = __liftString(message >>> 0); + fileName = __liftString(fileName >>> 0); + lineNumber = lineNumber >>> 0; + columnNumber = columnNumber >>> 0; + (() => { + throw Error(`${message} in ${fileName}:${lineNumber}:${columnNumber}`); + })(); + }, + seed() { + return (() => { + return Date.now() * Math.random(); + })(); + } + }) + }; + const {exports} = await WebAssembly.instantiate(module, adaptedImports); + const memory = exports.memory || imports.env.memory; + const adaptedExports = Object.setPrototypeOf( + { + findPath(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, shape, moveNear, blockAccessFlags, maxWaypoints, collision) { + moveNear = moveNear ? 1 : 0; + exports.__setArgumentsLength(arguments.length); + return __liftStaticArray(__getI32, 2, exports.findPath(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, shape, moveNear, blockAccessFlags, maxWaypoints, collision) >>> 0); + }, + findNaivePath(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags, collision) { + exports.__setArgumentsLength(arguments.length); + return __liftStaticArray(__getI32, 2, exports.findNaivePath(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags, collision) >>> 0); + }, + changeFloor(x, z2, level, add) { + add = add ? 1 : 0; + exports.changeFloor(x, z2, level, add); + }, + changeLoc(x, z2, level, width, length, blockrange, breakroutefinding, add) { + blockrange = blockrange ? 1 : 0; + breakroutefinding = breakroutefinding ? 1 : 0; + add = add ? 1 : 0; + exports.changeLoc(x, z2, level, width, length, blockrange, breakroutefinding, add); + }, + changeNpc(x, z2, level, size, add) { + add = add ? 1 : 0; + exports.changeNpc(x, z2, level, size, add); + }, + changePlayer(x, z2, level, size, add) { + add = add ? 1 : 0; + exports.changePlayer(x, z2, level, size, add); + }, + changeRoof(x, z2, level, add) { + add = add ? 1 : 0; + exports.changeRoof(x, z2, level, add); + }, + changeWall(x, z2, level, angle, shape, blockrange, breakroutefinding, add) { + blockrange = blockrange ? 1 : 0; + breakroutefinding = breakroutefinding ? 1 : 0; + add = add ? 1 : 0; + exports.changeWall(x, z2, level, angle, shape, blockrange, breakroutefinding, add); + }, + allocateIfAbsent(absoluteX, absoluteZ, level) { + return __liftStaticArray(__getI32, 2, exports.allocateIfAbsent(absoluteX, absoluteZ, level) >>> 0); + }, + isZoneAllocated(absoluteX, absoluteZ, level) { + return exports.isZoneAllocated(absoluteX, absoluteZ, level) != 0; + }, + isFlagged(x, z2, level, masks) { + return exports.isFlagged(x, z2, level, masks) != 0; + }, + canTravel(level, x, z2, offsetX, offsetZ, size, extraFlag, collision) { + exports.__setArgumentsLength(arguments.length); + return exports.canTravel(level, x, z2, offsetX, offsetZ, size, extraFlag, collision) != 0; + }, + hasLineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { + exports.__setArgumentsLength(arguments.length); + return exports.hasLineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) != 0; + }, + hasLineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { + exports.__setArgumentsLength(arguments.length); + return exports.hasLineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) != 0; + }, + lineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { + exports.__setArgumentsLength(arguments.length); + return __liftStaticArray(__getI32, 2, exports.lineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) >>> 0); + }, + lineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { + exports.__setArgumentsLength(arguments.length); + return __liftStaticArray(__getI32, 2, exports.lineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) >>> 0); + }, + reached(level, srcX, srcZ, destX, destZ, destWidth, destHeight, srcSize, angle, shape, blockAccessFlags) { + exports.__setArgumentsLength(arguments.length); + return exports.reached(level, srcX, srcZ, destX, destZ, destWidth, destHeight, srcSize, angle, shape, blockAccessFlags) != 0; + }, + __collides(srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight) { + return exports.__collides(srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight) != 0; + }, + __reachRectangle1(level, srcX, srcZ, destX, destZ, destWidth, destHeight, blockAccessFlags) { + return exports.__reachRectangle1(level, srcX, srcZ, destX, destZ, destWidth, destHeight, blockAccessFlags) != 0; + }, + __reachRectangleN(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags) { + return exports.__reachRectangleN(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags) != 0; + }, + __reachRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) { + return exports.__reachRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) != 0; + }, + __reachExclusiveRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) { + return exports.__reachExclusiveRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) != 0; + }, + CollisionFlag: (values => ( + (values[(values.NULL = exports['CollisionFlag.NULL'].valueOf())] = 'NULL'), + (values[(values.OPEN = exports['CollisionFlag.OPEN'].valueOf())] = 'OPEN'), + (values[(values.WALL_NORTH_WEST = exports['CollisionFlag.WALL_NORTH_WEST'].valueOf())] = 'WALL_NORTH_WEST'), + (values[(values.WALL_NORTH = exports['CollisionFlag.WALL_NORTH'].valueOf())] = 'WALL_NORTH'), + (values[(values.WALL_NORTH_EAST = exports['CollisionFlag.WALL_NORTH_EAST'].valueOf())] = 'WALL_NORTH_EAST'), + (values[(values.WALL_EAST = exports['CollisionFlag.WALL_EAST'].valueOf())] = 'WALL_EAST'), + (values[(values.WALL_SOUTH_EAST = exports['CollisionFlag.WALL_SOUTH_EAST'].valueOf())] = 'WALL_SOUTH_EAST'), + (values[(values.WALL_SOUTH = exports['CollisionFlag.WALL_SOUTH'].valueOf())] = 'WALL_SOUTH'), + (values[(values.WALL_SOUTH_WEST = exports['CollisionFlag.WALL_SOUTH_WEST'].valueOf())] = 'WALL_SOUTH_WEST'), + (values[(values.WALL_WEST = exports['CollisionFlag.WALL_WEST'].valueOf())] = 'WALL_WEST'), + (values[(values.LOC = exports['CollisionFlag.LOC'].valueOf())] = 'LOC'), + (values[(values.WALL_NORTH_WEST_PROJ_BLOCKER = exports['CollisionFlag.WALL_NORTH_WEST_PROJ_BLOCKER'].valueOf())] = 'WALL_NORTH_WEST_PROJ_BLOCKER'), + (values[(values.WALL_NORTH_PROJ_BLOCKER = exports['CollisionFlag.WALL_NORTH_PROJ_BLOCKER'].valueOf())] = 'WALL_NORTH_PROJ_BLOCKER'), + (values[(values.WALL_NORTH_EAST_PROJ_BLOCKER = exports['CollisionFlag.WALL_NORTH_EAST_PROJ_BLOCKER'].valueOf())] = 'WALL_NORTH_EAST_PROJ_BLOCKER'), + (values[(values.WALL_EAST_PROJ_BLOCKER = exports['CollisionFlag.WALL_EAST_PROJ_BLOCKER'].valueOf())] = 'WALL_EAST_PROJ_BLOCKER'), + (values[(values.WALL_SOUTH_EAST_PROJ_BLOCKER = exports['CollisionFlag.WALL_SOUTH_EAST_PROJ_BLOCKER'].valueOf())] = 'WALL_SOUTH_EAST_PROJ_BLOCKER'), + (values[(values.WALL_SOUTH_PROJ_BLOCKER = exports['CollisionFlag.WALL_SOUTH_PROJ_BLOCKER'].valueOf())] = 'WALL_SOUTH_PROJ_BLOCKER'), + (values[(values.WALL_SOUTH_WEST_PROJ_BLOCKER = exports['CollisionFlag.WALL_SOUTH_WEST_PROJ_BLOCKER'].valueOf())] = 'WALL_SOUTH_WEST_PROJ_BLOCKER'), + (values[(values.WALL_WEST_PROJ_BLOCKER = exports['CollisionFlag.WALL_WEST_PROJ_BLOCKER'].valueOf())] = 'WALL_WEST_PROJ_BLOCKER'), + (values[(values.LOC_PROJ_BLOCKER = exports['CollisionFlag.LOC_PROJ_BLOCKER'].valueOf())] = 'LOC_PROJ_BLOCKER'), + (values[(values.FLOOR_DECORATION = exports['CollisionFlag.FLOOR_DECORATION'].valueOf())] = 'FLOOR_DECORATION'), + (values[(values.NPC = exports['CollisionFlag.NPC'].valueOf())] = 'NPC'), + (values[(values.PLAYER = exports['CollisionFlag.PLAYER'].valueOf())] = 'PLAYER'), + (values[(values.FLOOR = exports['CollisionFlag.FLOOR'].valueOf())] = 'FLOOR'), + (values[(values.WALL_NORTH_WEST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_NORTH_WEST_ROUTE_BLOCKER'].valueOf())] = 'WALL_NORTH_WEST_ROUTE_BLOCKER'), + (values[(values.WALL_NORTH_ROUTE_BLOCKER = exports['CollisionFlag.WALL_NORTH_ROUTE_BLOCKER'].valueOf())] = 'WALL_NORTH_ROUTE_BLOCKER'), + (values[(values.WALL_NORTH_EAST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_NORTH_EAST_ROUTE_BLOCKER'].valueOf())] = 'WALL_NORTH_EAST_ROUTE_BLOCKER'), + (values[(values.WALL_EAST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_EAST_ROUTE_BLOCKER'].valueOf())] = 'WALL_EAST_ROUTE_BLOCKER'), + (values[(values.WALL_SOUTH_EAST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_SOUTH_EAST_ROUTE_BLOCKER'].valueOf())] = 'WALL_SOUTH_EAST_ROUTE_BLOCKER'), + (values[(values.WALL_SOUTH_ROUTE_BLOCKER = exports['CollisionFlag.WALL_SOUTH_ROUTE_BLOCKER'].valueOf())] = 'WALL_SOUTH_ROUTE_BLOCKER'), + (values[(values.WALL_SOUTH_WEST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_SOUTH_WEST_ROUTE_BLOCKER'].valueOf())] = 'WALL_SOUTH_WEST_ROUTE_BLOCKER'), + (values[(values.WALL_WEST_ROUTE_BLOCKER = exports['CollisionFlag.WALL_WEST_ROUTE_BLOCKER'].valueOf())] = 'WALL_WEST_ROUTE_BLOCKER'), + (values[(values.LOC_ROUTE_BLOCKER = exports['CollisionFlag.LOC_ROUTE_BLOCKER'].valueOf())] = 'LOC_ROUTE_BLOCKER'), + (values[(values.ROOF = exports['CollisionFlag.ROOF'].valueOf())] = 'ROOF'), + (values[(values.FLOOR_BLOCKED = exports['CollisionFlag.FLOOR_BLOCKED'].valueOf())] = 'FLOOR_BLOCKED'), + (values[(values.WALK_BLOCKED = exports['CollisionFlag.WALK_BLOCKED'].valueOf())] = 'WALK_BLOCKED'), + (values[(values.BLOCK_WEST = exports['CollisionFlag.BLOCK_WEST'].valueOf())] = 'BLOCK_WEST'), + (values[(values.BLOCK_EAST = exports['CollisionFlag.BLOCK_EAST'].valueOf())] = 'BLOCK_EAST'), + (values[(values.BLOCK_SOUTH = exports['CollisionFlag.BLOCK_SOUTH'].valueOf())] = 'BLOCK_SOUTH'), + (values[(values.BLOCK_NORTH = exports['CollisionFlag.BLOCK_NORTH'].valueOf())] = 'BLOCK_NORTH'), + (values[(values.BLOCK_SOUTH_WEST = exports['CollisionFlag.BLOCK_SOUTH_WEST'].valueOf())] = 'BLOCK_SOUTH_WEST'), + (values[(values.BLOCK_SOUTH_EAST = exports['CollisionFlag.BLOCK_SOUTH_EAST'].valueOf())] = 'BLOCK_SOUTH_EAST'), + (values[(values.BLOCK_NORTH_WEST = exports['CollisionFlag.BLOCK_NORTH_WEST'].valueOf())] = 'BLOCK_NORTH_WEST'), + (values[(values.BLOCK_NORTH_EAST = exports['CollisionFlag.BLOCK_NORTH_EAST'].valueOf())] = 'BLOCK_NORTH_EAST'), + (values[(values.BLOCK_NORTH_AND_SOUTH_EAST = exports['CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST'].valueOf())] = 'BLOCK_NORTH_AND_SOUTH_EAST'), + (values[(values.BLOCK_NORTH_AND_SOUTH_WEST = exports['CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST'].valueOf())] = 'BLOCK_NORTH_AND_SOUTH_WEST'), + (values[(values.BLOCK_NORTH_EAST_AND_WEST = exports['CollisionFlag.BLOCK_NORTH_EAST_AND_WEST'].valueOf())] = 'BLOCK_NORTH_EAST_AND_WEST'), + (values[(values.BLOCK_SOUTH_EAST_AND_WEST = exports['CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST'].valueOf())] = 'BLOCK_SOUTH_EAST_AND_WEST'), + (values[(values.BLOCK_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_WEST_ROUTE_BLOCKER'), + (values[(values.BLOCK_EAST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_EAST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_EAST_ROUTE_BLOCKER'), + (values[(values.BLOCK_SOUTH_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_SOUTH_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_SOUTH_ROUTE_BLOCKER'), + (values[(values.BLOCK_NORTH_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_ROUTE_BLOCKER'), + (values[(values.BLOCK_SOUTH_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_SOUTH_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_SOUTH_WEST_ROUTE_BLOCKER'), + (values[(values.BLOCK_SOUTH_EAST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_SOUTH_EAST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_SOUTH_EAST_ROUTE_BLOCKER'), + (values[(values.BLOCK_NORTH_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_WEST_ROUTE_BLOCKER'), + (values[(values.BLOCK_NORTH_EAST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_EAST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_EAST_ROUTE_BLOCKER'), + (values[(values.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER'), + (values[(values.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER'), + (values[(values.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER'), + (values[(values.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER = exports['CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER'].valueOf())] = 'BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER'), + values + ))({}), + LocShape: (values => ( + (values[(values.WALL_STRAIGHT = exports['LocShape.WALL_STRAIGHT'].valueOf())] = 'WALL_STRAIGHT'), + (values[(values.WALL_DIAGONAL_CORNER = exports['LocShape.WALL_DIAGONAL_CORNER'].valueOf())] = 'WALL_DIAGONAL_CORNER'), + (values[(values.WALL_L = exports['LocShape.WALL_L'].valueOf())] = 'WALL_L'), + (values[(values.WALL_SQUARE_CORNER = exports['LocShape.WALL_SQUARE_CORNER'].valueOf())] = 'WALL_SQUARE_CORNER'), + (values[(values.WALLDECOR_STRAIGHT_NOOFFSET = exports['LocShape.WALLDECOR_STRAIGHT_NOOFFSET'].valueOf())] = 'WALLDECOR_STRAIGHT_NOOFFSET'), + (values[(values.WALLDECOR_STRAIGHT_OFFSET = exports['LocShape.WALLDECOR_STRAIGHT_OFFSET'].valueOf())] = 'WALLDECOR_STRAIGHT_OFFSET'), + (values[(values.WALLDECOR_DIAGONAL_OFFSET = exports['LocShape.WALLDECOR_DIAGONAL_OFFSET'].valueOf())] = 'WALLDECOR_DIAGONAL_OFFSET'), + (values[(values.WALLDECOR_DIAGONAL_NOOFFSET = exports['LocShape.WALLDECOR_DIAGONAL_NOOFFSET'].valueOf())] = 'WALLDECOR_DIAGONAL_NOOFFSET'), + (values[(values.WALLDECOR_DIAGONAL_BOTH = exports['LocShape.WALLDECOR_DIAGONAL_BOTH'].valueOf())] = 'WALLDECOR_DIAGONAL_BOTH'), + (values[(values.WALL_DIAGONAL = exports['LocShape.WALL_DIAGONAL'].valueOf())] = 'WALL_DIAGONAL'), + (values[(values.CENTREPIECE_STRAIGHT = exports['LocShape.CENTREPIECE_STRAIGHT'].valueOf())] = 'CENTREPIECE_STRAIGHT'), + (values[(values.CENTREPIECE_DIAGONAL = exports['LocShape.CENTREPIECE_DIAGONAL'].valueOf())] = 'CENTREPIECE_DIAGONAL'), + (values[(values.ROOF_STRAIGHT = exports['LocShape.ROOF_STRAIGHT'].valueOf())] = 'ROOF_STRAIGHT'), + (values[(values.ROOF_DIAGONAL_WITH_ROOFEDGE = exports['LocShape.ROOF_DIAGONAL_WITH_ROOFEDGE'].valueOf())] = 'ROOF_DIAGONAL_WITH_ROOFEDGE'), + (values[(values.ROOF_DIAGONAL = exports['LocShape.ROOF_DIAGONAL'].valueOf())] = 'ROOF_DIAGONAL'), + (values[(values.ROOF_L_CONCAVE = exports['LocShape.ROOF_L_CONCAVE'].valueOf())] = 'ROOF_L_CONCAVE'), + (values[(values.ROOF_L_CONVEX = exports['LocShape.ROOF_L_CONVEX'].valueOf())] = 'ROOF_L_CONVEX'), + (values[(values.ROOF_FLAT = exports['LocShape.ROOF_FLAT'].valueOf())] = 'ROOF_FLAT'), + (values[(values.ROOFEDGE_STRAIGHT = exports['LocShape.ROOFEDGE_STRAIGHT'].valueOf())] = 'ROOFEDGE_STRAIGHT'), + (values[(values.ROOFEDGE_DIAGONAL_CORNER = exports['LocShape.ROOFEDGE_DIAGONAL_CORNER'].valueOf())] = 'ROOFEDGE_DIAGONAL_CORNER'), + (values[(values.ROOFEDGE_L = exports['LocShape.ROOFEDGE_L'].valueOf())] = 'ROOFEDGE_L'), + (values[(values.ROOFEDGE_SQUARE_CORNER = exports['LocShape.ROOFEDGE_SQUARE_CORNER'].valueOf())] = 'ROOFEDGE_SQUARE_CORNER'), + (values[(values.GROUND_DECOR = exports['LocShape.GROUND_DECOR'].valueOf())] = 'GROUND_DECOR'), + values + ))({}), + LocAngle: (values => ( + (values[(values.WEST = exports['LocAngle.WEST'].valueOf())] = 'WEST'), + (values[(values.NORTH = exports['LocAngle.NORTH'].valueOf())] = 'NORTH'), + (values[(values.EAST = exports['LocAngle.EAST'].valueOf())] = 'EAST'), + (values[(values.SOUTH = exports['LocAngle.SOUTH'].valueOf())] = 'SOUTH'), + values + ))({}), + CollisionType: (values => ( + (values[(values.NORMAL = exports['CollisionType.NORMAL'].valueOf())] = 'NORMAL'), + (values[(values.BLOCKED = exports['CollisionType.BLOCKED'].valueOf())] = 'BLOCKED'), + (values[(values.INDOORS = exports['CollisionType.INDOORS'].valueOf())] = 'INDOORS'), + (values[(values.OUTDOORS = exports['CollisionType.OUTDOORS'].valueOf())] = 'OUTDOORS'), + (values[(values.LINE_OF_SIGHT = exports['CollisionType.LINE_OF_SIGHT'].valueOf())] = 'LINE_OF_SIGHT'), + values + ))({}), + LocLayer: (values => ( + (values[(values.WALL = exports['LocLayer.WALL'].valueOf())] = 'WALL'), + (values[(values.WALL_DECOR = exports['LocLayer.WALL_DECOR'].valueOf())] = 'WALL_DECOR'), + (values[(values.GROUND = exports['LocLayer.GROUND'].valueOf())] = 'GROUND'), + (values[(values.GROUND_DECOR = exports['LocLayer.GROUND_DECOR'].valueOf())] = 'GROUND_DECOR'), + values + ))({}), + BlockAccessFlag: (values => ( + (values[(values.BLOCK_NORTH = exports['BlockAccessFlag.BLOCK_NORTH'].valueOf())] = 'BLOCK_NORTH'), + (values[(values.BLOCK_EAST = exports['BlockAccessFlag.BLOCK_EAST'].valueOf())] = 'BLOCK_EAST'), + (values[(values.BLOCK_SOUTH = exports['BlockAccessFlag.BLOCK_SOUTH'].valueOf())] = 'BLOCK_SOUTH'), + (values[(values.BLOCK_WEST = exports['BlockAccessFlag.BLOCK_WEST'].valueOf())] = 'BLOCK_WEST'), + values + ))({}) + }, + exports + ); + function __liftString(pointer) { + if (!pointer) return null; + const end = (pointer + new Uint32Array(memory.buffer)[(pointer - 4) >>> 2]) >>> 1, + memoryU16 = new Uint16Array(memory.buffer); + let start = pointer >>> 1, + string = ''; + while (end - start > 1024) string += String.fromCharCode(...memoryU16.subarray(start, (start += 1024))); + return string + String.fromCharCode(...memoryU16.subarray(start, end)); + } + function __liftStaticArray(liftElement, align, pointer) { + if (!pointer) return null; + const length = __getU32(pointer - 4) >>> align, + values = new Array(length); + for (let i = 0; i < length; ++i) values[i] = liftElement(pointer + ((i << align) >>> 0)); + return values; + } + let __dataview = new DataView(memory.buffer); + function __getI32(pointer) { + try { + return __dataview.getInt32(pointer, true); + } catch { + __dataview = new DataView(memory.buffer); + return __dataview.getInt32(pointer, true); + } + } + function __getU32(pointer) { + try { + return __dataview.getUint32(pointer, true); + } catch { + __dataview = new DataView(memory.buffer); + return __dataview.getUint32(pointer, true); + } + } + return adaptedExports; +} +var { + memory, + findPath, + findNaivePath, + changeFloor, + changeLoc, + changeNpc, + changePlayer, + changeRoof, + changeWall, + allocateIfAbsent, + deallocateIfPresent, + isZoneAllocated, + isFlagged, + canTravel, + hasLineOfSight, + hasLineOfWalk, + lineOfSight, + lineOfWalk, + reached, + locShapeLayer, + __get, + __set, + __add, + __remove, + __rotate, + __rotateFlags, + __collides, + __reachRectangle1, + __reachRectangleN, + __alteredRotation, + __reachRectangle, + __reachExclusiveRectangle, + CollisionFlag, + LocShape, + LocAngle, + CollisionType, + LocLayer, + BlockAccessFlag +} = await (async url => + instantiate( + await (async () => { + try { + return await globalThis.WebAssembly.compileStreaming(globalThis.fetch(url)); + } catch { + return globalThis.WebAssembly.compile(await (await import('node:fs/promises')).readFile(url)); + } + })(), + {} + ))(new URL('rsmod-pathfinder.wasm', import.meta.url)); + +// src/lostcity/entity/Position.ts +var Direction = { + NORTH_WEST: 0, + NORTH: 1, + NORTH_EAST: 2, + WEST: 3, + EAST: 4, + SOUTH_WEST: 5, + SOUTH: 6, + SOUTH_EAST: 7 +}; +var Position = { + zone: pos => pos >> 3, + zoneCenter: pos => Position.zone(pos) - 6, + zoneOrigin: pos => Position.zoneCenter(pos) << 3, + mapsquare: pos => pos >> 6, + local: (pos, origin) => pos - (Position.zoneCenter(origin) << 3), + face: (srcX, srcZ, dstX, dstZ) => { + if (srcX == dstX) { + if (srcZ > dstZ) { + return Direction.SOUTH; + } else if (srcZ < dstZ) { + return Direction.NORTH; + } + } else if (srcX > dstX) { + if (srcZ > dstZ) { + return Direction.SOUTH_WEST; + } else if (srcZ < dstZ) { + return Direction.NORTH_WEST; + } else { + return Direction.WEST; + } + } else { + if (srcZ > dstZ) { + return Direction.SOUTH_EAST; + } else if (srcZ < dstZ) { + return Direction.NORTH_EAST; + } else { + return Direction.EAST; + } + } + return -1; + }, + moveX: (pos, dir) => { + return pos + Position.deltaX(dir); + }, + moveZ: (pos, dir) => { + return pos + Position.deltaZ(dir); + }, + distanceTo(pos, other) { + const p1 = Position.closest(pos, other); + const p2 = Position.closest(other, pos); + return Math.max(Math.abs(p1.x - p2.x), Math.abs(p1.z - p2.z)); + }, + closest(pos, other) { + const occupiedX = pos.x + pos.width - 1; + const occupiedZ = pos.z + pos.length - 1; + return { + x: other.x <= pos.x ? pos.x : other.x >= occupiedX ? occupiedX : other.x, + z: other.z <= pos.z ? pos.z : other.z >= occupiedZ ? occupiedZ : other.z + }; + }, + distanceToSW(pos, other) { + const deltaX = Math.abs(pos.x - other.x); + const deltaZ = Math.abs(pos.z - other.z); + return Math.max(deltaX, deltaZ); + }, + isWithinDistanceSW(pos, other, distance) { + if (Math.abs(pos.x - other.x) > distance || Math.abs(pos.z - other.z) > distance) { + return false; + } + return true; + }, + deltaX(dir) { + switch (dir) { + case Direction.SOUTH_EAST: + case Direction.NORTH_EAST: + case Direction.EAST: + return 1; + case Direction.SOUTH_WEST: + case Direction.NORTH_WEST: + case Direction.WEST: + return -1; + } + return 0; + }, + deltaZ(dir) { + switch (dir) { + case Direction.NORTH_WEST: + case Direction.NORTH_EAST: + case Direction.NORTH: + return 1; + case Direction.SOUTH_WEST: + case Direction.SOUTH_EAST: + case Direction.SOUTH: + return -1; + } + return 0; + }, + unpackCoord(coord) { + const level = (coord >> 28) & 3; + const x = (coord >> 14) & 16383; + const z2 = coord & 16383; + return {level, x, z: z2}; + }, + packCoord(level, x, z2) { + return (z2 & 16383) | ((x & 16383) << 14) | ((level & 3) << 28); + }, + packZoneCoord(x, z2) { + return ((x & 7) << 4) | (z2 & 7); + }, + intersects(srcX, srcZ, srcWidth, srcHeight, destX, destZ, destWidth, destHeight) { + const srcHorizontal = srcX + srcWidth; + const srcVertical = srcZ + srcHeight; + const destHorizontal = destX + destWidth; + const destVertical = destZ + destHeight; + return !(destX >= srcHorizontal || destHorizontal <= srcX || destZ >= srcVertical || destVertical <= srcZ); + }, + formatString(level, x, z2, separator = '_') { + const mx = x >> 6; + const mz = z2 >> 6; + const lx = x & 63; + const lz = z2 & 63; + return level + separator + mx + separator + mz + separator + lx + separator + lz; + } +}; + +// src/lostcity/entity/HitType.ts +var HitType; +(HitType2 => { + HitType2[(HitType2['BLOCK'] = 0)] = 'BLOCK'; + HitType2[(HitType2['DAMAGE'] = 1)] = 'DAMAGE'; + HitType2[(HitType2['POISON'] = 2)] = 'POISON'; +})((HitType ||= {})); +var HitType_default = HitType; + +// src/lostcity/entity/PlayerStat.ts +var PlayerStat; +(PlayerStat2 => { + PlayerStat2[(PlayerStat2['ATTACK'] = 0)] = 'ATTACK'; + PlayerStat2[(PlayerStat2['DEFENCE'] = 1)] = 'DEFENCE'; + PlayerStat2[(PlayerStat2['STRENGTH'] = 2)] = 'STRENGTH'; + PlayerStat2[(PlayerStat2['HITPOINTS'] = 3)] = 'HITPOINTS'; + PlayerStat2[(PlayerStat2['RANGED'] = 4)] = 'RANGED'; + PlayerStat2[(PlayerStat2['PRAYER'] = 5)] = 'PRAYER'; + PlayerStat2[(PlayerStat2['MAGIC'] = 6)] = 'MAGIC'; + PlayerStat2[(PlayerStat2['COOKING'] = 7)] = 'COOKING'; + PlayerStat2[(PlayerStat2['WOODCUTTING'] = 8)] = 'WOODCUTTING'; + PlayerStat2[(PlayerStat2['FLETCHING'] = 9)] = 'FLETCHING'; + PlayerStat2[(PlayerStat2['FISHING'] = 10)] = 'FISHING'; + PlayerStat2[(PlayerStat2['FIREMAKING'] = 11)] = 'FIREMAKING'; + PlayerStat2[(PlayerStat2['CRAFTING'] = 12)] = 'CRAFTING'; + PlayerStat2[(PlayerStat2['SMITHING'] = 13)] = 'SMITHING'; + PlayerStat2[(PlayerStat2['MINING'] = 14)] = 'MINING'; + PlayerStat2[(PlayerStat2['HERBLORE'] = 15)] = 'HERBLORE'; + PlayerStat2[(PlayerStat2['AGILITY'] = 16)] = 'AGILITY'; + PlayerStat2[(PlayerStat2['THIEVING'] = 17)] = 'THIEVING'; + PlayerStat2[(PlayerStat2['STAT18'] = 18)] = 'STAT18'; + PlayerStat2[(PlayerStat2['STAT19'] = 19)] = 'STAT19'; + PlayerStat2[(PlayerStat2['RUNECRAFT'] = 20)] = 'RUNECRAFT'; +})((PlayerStat ||= {})); +var PlayerStat_default = PlayerStat; + +// src/lostcity/engine/script/ScriptValidators.ts +function check(input, validator) { + return validator.validate(input); +} + +class ScriptInputNumberNotNullValidator { + validate(input) { + if (input !== -1) return input; + throw Error('An input number was null(-1).'); + } +} + +class ScriptInputStringNotNullValidator { + validate(input) { + if (input.length > 0) return input; + throw Error('An input string was null(-1).'); + } +} + +class ScriptInputConfigTypeValidator { + type; + count; + name; + constructor(type, count, name) { + this.type = type; + this.count = count; + this.name = name; + } + validate(input) { + if (this.count(input)) return this.type(input); + throw new Error(`An input for a ${this.name} type was not valid to use. Input was ${input}.`); + } +} + +class ScriptInputRangeValidator { + min; + max; + name; + constructor(min, max, name) { + this.min = min; + this.max = max; + this.name = name; + } + validate(input) { + if (input >= this.min && input <= this.max) { + return input; + } + throw new Error(`An input for a ${this.name} was out of range. Range should be: ${this.min} to ${this.max}. Input was ${input}.`); + } +} + +class ScriptInputCoordValidator extends ScriptInputRangeValidator { + validate(input) { + if (input >= this.min && input <= this.max) { + return Position.unpackCoord(input); + } + throw new Error(`An input for a ${this.name} was out of range. Range should be: ${this.min} to ${this.max}. Input was ${input}.`); + } +} +var NumberNotNull = new ScriptInputNumberNotNullValidator(); +var StringNotNull = new ScriptInputStringNotNullValidator(); +var LocTypeValid = new ScriptInputConfigTypeValidator(LocType.get, input => input >= 0 && input < LocType.count, 'Loc'); +var LocAngleValid = new ScriptInputRangeValidator(LocAngle.WEST, LocAngle.SOUTH, 'LocAngle'); +var LocShapeValid = new ScriptInputRangeValidator(LocShape.WALL_STRAIGHT, LocShape.GROUND_DECOR, 'LocShape'); +var DurationValid = new ScriptInputRangeValidator(1, 2147483647, 'Duration'); +var CoordValid = new ScriptInputCoordValidator(0, 2147483647, 'Coord'); +var ParamTypeValid = new ScriptInputConfigTypeValidator(ParamType.get, input => input >= 0 && input < ParamType.count, 'Param'); +var NpcTypeValid = new ScriptInputConfigTypeValidator(NpcType.get, input => input >= 0 && input < NpcType.count, 'Npc'); +var NpcStatValid = new ScriptInputRangeValidator(NpcStat_default.ATTACK, NpcStat_default.MAGIC, 'NpcStat'); +var PlayerStatValid = new ScriptInputRangeValidator(PlayerStat_default.ATTACK, PlayerStat_default.RUNECRAFT, 'PlayerStat'); +var QueueValid = new ScriptInputRangeValidator(0, 19, 'AIQueue'); +var HuntTypeValid = new ScriptInputConfigTypeValidator(HuntType.get, input => input >= 0 && input < HuntType.count, 'Hunt'); +var NpcModeValid = new ScriptInputRangeValidator(NpcMode_default.NULL, NpcMode_default.APNPC5, 'NpcMode'); +var HitTypeValid = new ScriptInputRangeValidator(HitType_default.BLOCK, HitType_default.POISON, 'Hit'); +var SpotAnimTypeValid = new ScriptInputConfigTypeValidator(SpotanimType.get, input => input >= 0 && input < SpotanimType.count, 'Spotanim'); +var EnumTypeValid = new ScriptInputConfigTypeValidator(EnumType.get, input => input >= 0 && input < EnumType.count, 'Enum'); +var ObjTypeValid = new ScriptInputConfigTypeValidator(ObjType.get, input => input >= 0 && input < ObjType.count, 'Obj'); +var ObjStackValid = new ScriptInputRangeValidator(1, Inventory.STACK_LIMIT, 'ObjStack'); +var InvTypeValid = new ScriptInputConfigTypeValidator(InvType.get, input => input >= 0 && input < InvType.count, 'Inv'); +var CategoryTypeValid = new ScriptInputConfigTypeValidator(CategoryType.get, input => input >= 0 && input < CategoryType.count, 'Cat'); +var IDKTypeValid = new ScriptInputConfigTypeValidator(IdkType.get, input => input >= 0 && input < IdkType.count, 'Idk'); +var HuntVisValid = new ScriptInputRangeValidator(HuntVis_default.OFF, HuntVis_default.LINEOFWALK, 'HuntVis'); +var SeqTypeValid = new ScriptInputConfigTypeValidator(SeqType.get, input => input >= 0 && input < SeqType.count, 'Seq'); +var VarPlayerValid = new ScriptInputConfigTypeValidator(VarPlayerType.get, input => input >= 0 && input < VarPlayerType.count, 'Varp'); +var VarNpcValid = new ScriptInputConfigTypeValidator(VarNpcType.get, input => input >= 0 && input < VarNpcType.count, 'Varn'); +var VarSharedValid = new ScriptInputConfigTypeValidator(VarSharedType.get, input => input >= 0 && input < VarSharedType.count, 'Vars'); +var FontTypeValid = new ScriptInputConfigTypeValidator(FontType.get, input => input >= 0 && input < FontType.count, 'Font'); +var MesanimValid = new ScriptInputConfigTypeValidator(MesanimType.get, input => input >= 0 && input < MesanimType.count, 'Mesanim'); +var StructTypeValid = new ScriptInputConfigTypeValidator(StructType.get, input => input >= 0 && input < StructType.count, 'Struct'); +var DbRowTypeValid = new ScriptInputConfigTypeValidator(DbRowType.get, input => input >= 0 && input < DbRowType.count, 'Dbrow'); +var DbTableTypeValid = new ScriptInputConfigTypeValidator(DbTableType.get, input => input >= 0 && input < DbTableType.count, 'Dbtable'); +var GenderValid = new ScriptInputRangeValidator(0, 1, 'Gender'); +var SkinColourValid = new ScriptInputRangeValidator(0, 7, 'SkinColour'); + +// src/lostcity/engine/script/handlers/CoreOps.ts +var gosub = function (state, id) { + if (state.fp >= 50) { + throw new Error('stack overflow'); + } + state.frames[state.fp++] = { + script: state.script, + pc: state.pc, + intLocals: state.intLocals, + stringLocals: state.stringLocals + }; + const script = ScriptProvider.get(id); + if (!script) { + throw new Error(`unable to find proc ${script}`); + } + setupNewScript(state, script); +}; +var jump = function (state, id) { + const label = ScriptProvider.get(id); + if (!label) { + throw new Error(`unable to find label ${id}`); + } + state.debugFrames[state.debugFp++] = { + script: state.script, + pc: state.pc + }; + setupNewScript(state, label); + state.fp = 0; + state.frames = []; +}; +var setupNewScript = function (state, script) { + state.script = script; + state.pc = -1; + state.intLocals = state.popInts(script.intArgCount); + state.stringLocals = state.popStrings(script.stringArgCount); +}; +var CoreOps = { + [ScriptOpcode_default.PUSH_CONSTANT_INT]: state => { + state.pushInt(state.intOperand); + }, + [ScriptOpcode_default.PUSH_CONSTANT_STRING]: state => { + state.pushString(state.stringOperand); + }, + [ScriptOpcode_default.PUSH_VARP]: state => { + const secondary = (state.intOperand >> 16) & 1; + if (secondary && !state._activePlayer2) { + throw new Error('No secondary active_player.'); + } else if (!secondary && !state._activePlayer) { + throw new Error('No active_player.'); + } + const varpType = check(state.intOperand & 65535, VarPlayerValid); + if (varpType.type === ScriptVarType.STRING) { + state.pushString(secondary ? state._activePlayer2.getVar(varpType.id) : state._activePlayer.getVar(varpType.id)); + } else { + state.pushInt(secondary ? state._activePlayer2.getVar(varpType.id) : state._activePlayer.getVar(varpType.id)); + } + }, + [ScriptOpcode_default.POP_VARP]: state => { + const secondary = (state.intOperand >> 16) & 1; + if (secondary && !state._activePlayer2) { + throw new Error('No secondary active_player.'); + } else if (!secondary && !state._activePlayer) { + throw new Error('No active_player.'); + } + const varpType = check(state.intOperand & 65535, VarPlayerValid); + if (!state.pointerGet(ProtectedActivePlayer[secondary]) && varpType.protect) { + throw new Error(`%${varpType.debugname} requires protected access`); + } + if (varpType.type === ScriptVarType.STRING) { + const value = state.popString(); + if (secondary) { + state._activePlayer2.setVar(varpType.id, value); + } else { + state._activePlayer.setVar(varpType.id, value); + } + } else { + const value = state.popInt(); + if (secondary) { + state._activePlayer2.setVar(varpType.id, value); + } else { + state._activePlayer.setVar(varpType.id, value); + } + } + }, + [ScriptOpcode_default.PUSH_VARN]: state => { + const secondary = (state.intOperand >> 16) & 1; + if (secondary && !state._activeNpc2) { + throw new Error('No secondary active_npc.'); + } else if (!secondary && !state._activeNpc) { + throw new Error('No active_npc.'); + } + const varnType = check(state.intOperand & 65535, VarNpcValid); + if (varnType.type === ScriptVarType.STRING) { + state.pushString(secondary ? state._activeNpc2.getVar(varnType.id) : state._activeNpc.getVar(varnType.id)); + } else { + state.pushInt(secondary ? state._activeNpc2.getVar(varnType.id) : state._activeNpc.getVar(varnType.id)); + } + }, + [ScriptOpcode_default.POP_VARN]: state => { + const secondary = (state.intOperand >> 16) & 1; + if (secondary && !state._activeNpc2) { + throw new Error('No secondary active_npc.'); + } else if (!secondary && !state._activeNpc) { + throw new Error('No active_npc.'); + } + const varnType = check(state.intOperand & 65535, VarNpcValid); + if (varnType.type === ScriptVarType.STRING) { + const value = state.popInt(); + if (secondary) { + state._activeNpc2.setVar(varnType.id, value); + } else { + state._activeNpc.setVar(varnType.id, value); + } + } else { + const value = state.popInt(); + if (secondary) { + state._activeNpc2.setVar(varnType.id, value); + } else { + state._activeNpc.setVar(varnType.id, value); + } + } + }, + [ScriptOpcode_default.PUSH_INT_LOCAL]: state => { + state.pushInt(state.intLocals[state.intOperand]); + }, + [ScriptOpcode_default.POP_INT_LOCAL]: state => { + state.intLocals[state.intOperand] = state.popInt(); + }, + [ScriptOpcode_default.PUSH_STRING_LOCAL]: state => { + state.pushString(state.stringLocals[state.intOperand]); + }, + [ScriptOpcode_default.POP_STRING_LOCAL]: state => { + state.stringLocals[state.intOperand] = state.popString(); + }, + [ScriptOpcode_default.BRANCH]: state => { + state.pc += state.intOperand; + }, + [ScriptOpcode_default.BRANCH_NOT]: state => { + const b3 = state.popInt(); + const a = state.popInt(); + if (a !== b3) { + state.pc += state.intOperand; + } + }, + [ScriptOpcode_default.BRANCH_EQUALS]: state => { + const b3 = state.popInt(); + const a = state.popInt(); + if (a === b3) { + state.pc += state.intOperand; + } + }, + [ScriptOpcode_default.BRANCH_LESS_THAN]: state => { + const b3 = state.popInt(); + const a = state.popInt(); + if (a < b3) { + state.pc += state.intOperand; + } + }, + [ScriptOpcode_default.BRANCH_GREATER_THAN]: state => { + const b3 = state.popInt(); + const a = state.popInt(); + if (a > b3) { + state.pc += state.intOperand; + } + }, + [ScriptOpcode_default.BRANCH_LESS_THAN_OR_EQUALS]: state => { + const b3 = state.popInt(); + const a = state.popInt(); + if (a <= b3) { + state.pc += state.intOperand; + } + }, + [ScriptOpcode_default.BRANCH_GREATER_THAN_OR_EQUALS]: state => { + const b3 = state.popInt(); + const a = state.popInt(); + if (a >= b3) { + state.pc += state.intOperand; + } + }, + [ScriptOpcode_default.POP_INT_DISCARD]: state => { + state.isp--; + }, + [ScriptOpcode_default.POP_STRING_DISCARD]: state => { + state.ssp--; + }, + [ScriptOpcode_default.RETURN]: state => { + if (state.fp === 0) { + state.execution = ScriptState.FINISHED; + return; + } + const frame = state.frames[--state.fp]; + state.pc = frame.pc; + state.script = frame.script; + state.intLocals = frame.intLocals; + state.stringLocals = frame.stringLocals; + }, + [ScriptOpcode_default.JOIN_STRING]: state => { + const count = state.intOperand; + const strings = []; + for (let i = 0; i < count; i++) { + strings.push(state.popString()); + } + state.pushString(strings.reverse().join('')); + }, + [ScriptOpcode_default.GOSUB]: state => { + gosub(state, state.popInt()); + }, + [ScriptOpcode_default.GOSUB_WITH_PARAMS]: state => { + gosub(state, state.intOperand); + }, + [ScriptOpcode_default.JUMP]: state => { + jump(state, state.popInt()); + }, + [ScriptOpcode_default.JUMP_WITH_PARAMS]: state => { + jump(state, state.intOperand); + }, + [ScriptOpcode_default.DEFINE_ARRAY]: state => { + throw new Error('unimplemented'); + }, + [ScriptOpcode_default.PUSH_ARRAY_INT]: state => { + throw new Error('unimplemented'); + }, + [ScriptOpcode_default.POP_ARRAY_INT]: state => { + throw new Error('unimplemented'); + }, + [ScriptOpcode_default.SWITCH]: state => { + const key = state.popInt(); + const table = state.script.switchTables[state.intOperand]; + if (table === undefined) { + return; + } + const result = table[key]; + if (result) { + state.pc += result; + } + }, + [ScriptOpcode_default.PUSH_VARS]: state => { + const varsType = check(state.intOperand & 65535, VarSharedValid); + if (varsType.type === ScriptVarType.STRING) { + state.pushString(World_default.varsString[varsType.id] ?? ''); + } else { + state.pushInt(World_default.vars[varsType.id]); + } + }, + [ScriptOpcode_default.POP_VARS]: state => { + const varsType = check(state.intOperand & 65535, VarSharedValid); + if (varsType.type === ScriptVarType.STRING) { + World_default.varsString[varsType.id] = state.popString(); + } else { + World_default.vars[varsType.id] = state.popInt(); + } + } +}; +var CoreOps_default = CoreOps; + +// src/lostcity/engine/script/handlers/DbOps.ts +var DebugOps = { + [ScriptOpcode_default.DB_FIND_WITH_COUNT]: state => { + throw new Error('unimplemented'); + }, + [ScriptOpcode_default.DB_FINDNEXT]: state => { + if (!state.dbTable) { + throw new Error('No table selected'); + } + if (state.dbRow + 1 >= state.dbRowQuery.length) { + state.pushInt(-1); + return; + } + state.dbRow++; + state.pushInt(check(state.dbRowQuery[state.dbRow], DbRowTypeValid).id); + }, + [ScriptOpcode_default.DB_GETFIELD]: state => { + const [row, tableColumnPacked, listIndex] = state.popInts(3); + const table = (tableColumnPacked >> 12) & 65535; + const column = (tableColumnPacked >> 4) & 127; + const tuple = tableColumnPacked & 63; + const rowType = check(row, DbRowTypeValid); + const tableType = check(table, DbTableTypeValid); + let values; + if (rowType.tableId !== table) { + values = tableType.getDefault(column); + } else { + values = rowType.getValue(column, listIndex); + } + const valueTypes = tableType.types[column]; + for (let i = 0; i < values.length; i++) { + if (valueTypes[i] === ScriptVarType.STRING) { + state.pushString(values[i]); + } else { + state.pushInt(values[i]); + } + } + }, + [ScriptOpcode_default.DB_GETFIELDCOUNT]: state => { + const [row, tableColumnPacked] = state.popInts(2); + const table = (tableColumnPacked >> 12) & 65535; + const column = (tableColumnPacked >> 4) & 127; + const tuple = tableColumnPacked & 63; + const rowType = check(row, DbRowTypeValid); + const tableType = check(table, DbTableTypeValid); + if (rowType.tableId !== table) { + state.pushInt(0); + return; + } + state.pushInt(rowType.columnValues[column].length / tableType.types[column].length); + }, + [ScriptOpcode_default.DB_LISTALL_WITH_COUNT]: state => { + throw new Error('unimplemented'); + }, + [ScriptOpcode_default.DB_GETROWTABLE]: state => { + state.pushInt(check(state.popInt(), DbRowTypeValid).tableId); + }, + [ScriptOpcode_default.DB_FINDBYINDEX]: state => { + throw new Error('unimplemented'); + }, + [ScriptOpcode_default.DB_FIND_REFINE_WITH_COUNT]: state => { + throw new Error('unimplemented'); + }, + [ScriptOpcode_default.DB_FIND]: state => { + const isString = state.popInt() == 2; + const query = isString ? state.popString() : state.popInt(); + const tableColumnPacked = state.popInt(); + const table = (tableColumnPacked >> 12) & 65535; + const column = (tableColumnPacked >> 4) & 127; + const tuple = tableColumnPacked & 63; + state.dbTable = check(table, DbTableTypeValid); + state.dbRow = -1; + state.dbRowQuery = []; + const rows = DbRowType.getInTable(table); + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if (row.columnValues[column].includes(query)) { + state.dbRowQuery.push(row.id); + } + } + state.pushInt(state.dbRowQuery.length); + }, + [ScriptOpcode_default.DB_FIND_REFINE]: state => { + const isString = state.popInt() == 2; + const query = isString ? state.popString() : state.popInt(); + const tableColumnPacked = state.popInt(); + const table = (tableColumnPacked >> 12) & 65535; + const column = (tableColumnPacked >> 4) & 127; + const tuple = tableColumnPacked & 63; + const found = []; + const rows = DbRowType.getInTable(table); + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if (row.columnValues[column].includes(query)) { + found.push(row.id); + } + } + const prevQuery = state.dbRowQuery; + state.dbRow = -1; + state.dbRowQuery = []; + for (let i = 0; i < prevQuery.length; i++) { + if (found.includes(prevQuery[i])) { + state.dbRowQuery.push(prevQuery[i]); + } + } + state.pushInt(state.dbRowQuery.length); + }, + [ScriptOpcode_default.DB_LISTALL]: state => { + throw new Error('unimplemented'); + } +}; +var DbOps_default = DebugOps; + +// src/lostcity/engine/WorldStat.ts +var WorldStat; +(WorldStat2 => { + WorldStat2[(WorldStat2['CYCLE'] = 0)] = 'CYCLE'; + WorldStat2[(WorldStat2['WORLD'] = 1)] = 'WORLD'; + WorldStat2[(WorldStat2['CLIENT_IN'] = 2)] = 'CLIENT_IN'; + WorldStat2[(WorldStat2['NPC'] = 3)] = 'NPC'; + WorldStat2[(WorldStat2['PLAYER'] = 4)] = 'PLAYER'; + WorldStat2[(WorldStat2['LOGOUT'] = 5)] = 'LOGOUT'; + WorldStat2[(WorldStat2['LOGIN'] = 6)] = 'LOGIN'; + WorldStat2[(WorldStat2['ZONE'] = 7)] = 'ZONE'; + WorldStat2[(WorldStat2['CLIENT_OUT'] = 8)] = 'CLIENT_OUT'; + WorldStat2[(WorldStat2['CLEANUP'] = 9)] = 'CLEANUP'; + WorldStat2[(WorldStat2['BANDWIDTH_IN'] = 10)] = 'BANDWIDTH_IN'; + WorldStat2[(WorldStat2['BANDWIDTH_OUT'] = 11)] = 'BANDWIDTH_OUT'; +})((WorldStat ||= {})); +var WorldStat_default = WorldStat; + +// src/lostcity/engine/script/handlers/DebugOps.ts +var DebugOps2 = { + [ScriptOpcode_default.ERROR]: state => { + throw new Error(state.popString()); + }, + [ScriptOpcode_default.MAP_PRODUCTION]: state => { + state.pushInt(Environment_default.NODE_PRODUCTION ? 1 : 0); + }, + [ScriptOpcode_default.MAP_LASTCLOCK]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.CYCLE]); + }, + [ScriptOpcode_default.MAP_LASTWORLD]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.WORLD]); + }, + [ScriptOpcode_default.MAP_LASTCLIENTIN]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.CLIENT_IN]); + }, + [ScriptOpcode_default.MAP_LASTNPC]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.NPC]); + }, + [ScriptOpcode_default.MAP_LASTPLAYER]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.PLAYER]); + }, + [ScriptOpcode_default.MAP_LASTLOGOUT]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.LOGOUT]); + }, + [ScriptOpcode_default.MAP_LASTLOGIN]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.LOGIN]); + }, + [ScriptOpcode_default.MAP_LASTZONE]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.ZONE]); + }, + [ScriptOpcode_default.MAP_LASTCLIENTOUT]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.CLIENT_OUT]); + }, + [ScriptOpcode_default.MAP_LASTCLEANUP]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.CLEANUP]); + }, + [ScriptOpcode_default.MAP_LASTBANDWIDTHIN]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.BANDWIDTH_IN]); + }, + [ScriptOpcode_default.MAP_LASTBANDWIDTHOUT]: state => { + state.pushInt(World_default.lastCycleStats[WorldStat_default.BANDWIDTH_OUT]); + } +}; +var DebugOps_default = DebugOps2; + +// src/lostcity/engine/script/handlers/EnumOps.ts +var EnumOps = { + [ScriptOpcode_default.ENUM]: state => { + const [inputType, outputType, enumId, key] = state.popInts(4); + const enumType = check(enumId, EnumTypeValid); + if (enumType.inputtype !== inputType || enumType.outputtype !== outputType) { + throw new Error(`Type validation error: ${enumType.debugname} key: ${key}. Expected input: ${inputType} got: ${enumType.inputtype}. Expected output: ${outputType} got: ${enumType.outputtype}`); + } + const value = enumType.values.get(key); + if (typeof value === 'string') { + state.pushString(value ?? enumType.defaultString); + } else { + state.pushInt(value ?? enumType.defaultInt); + } + }, + [ScriptOpcode_default.ENUM_GETOUTPUTCOUNT]: state => { + state.pushInt(check(state.popInt(), EnumTypeValid).values.size); + } +}; +var EnumOps_default = EnumOps; + +// src/lostcity/entity/EntityLifeCycle.ts +var EntityLifeCycle; +(EntityLifeCycle2 => { + EntityLifeCycle2[(EntityLifeCycle2['FOREVER'] = 0)] = 'FOREVER'; + EntityLifeCycle2[(EntityLifeCycle2['RESPAWN'] = 1)] = 'RESPAWN'; + EntityLifeCycle2[(EntityLifeCycle2['DESPAWN'] = 2)] = 'DESPAWN'; +})((EntityLifeCycle ||= {})); +var EntityLifeCycle_default = EntityLifeCycle; + +// src/lostcity/entity/Entity.ts +class Entity { + level; + x; + z; + width; + length; + lifecycle; + lifecycleTick = -1; + lastLifecycleTick = -1; + constructor(level, x, z2, width, length, lifecycle) { + this.level = level; + this.x = x; + this.z = z2; + this.width = width; + this.length = length; + this.lifecycle = lifecycle; + } + updateLifeCycle(tick) { + return this.lifecycleTick === tick && this.lifecycle !== EntityLifeCycle_default.FOREVER; + } + checkLifeCycle(tick) { + if (this.lifecycle === EntityLifeCycle_default.FOREVER) { + return true; + } + if (this.lifecycle === EntityLifeCycle_default.RESPAWN) { + return this.lifecycleTick < tick; + } + if (this.lifecycle === EntityLifeCycle_default.DESPAWN) { + return this.lifecycleTick > tick; + } + return false; + } + setLifeCycle(tick) { + this.lifecycleTick = tick; + this.lastLifecycleTick = World_default.currentTick; + } +} + +// src/lostcity/entity/NonPathingEntity.ts +class NonPathingEntity extends Entity { + resetEntity(respawn) {} +} + +// src/lostcity/entity/Obj.ts +class Obj extends NonPathingEntity { + type; + count; + receiverId = -1; + reveal = -1; + constructor(level, x, z2, lifecycle, type, count) { + super(level, x, z2, 1, 1, lifecycle); + this.type = type; + this.count = count; + } +} + +// src/lostcity/engine/script/handlers/InvOps.ts +var InvOps = { + [ScriptOpcode_default.INV_ALLSTOCK]: state => { + const invType = check(state.popInt(), InvTypeValid); + state.pushInt(invType.allstock ? 1 : 0); + }, + [ScriptOpcode_default.INV_SIZE]: state => { + const invType = check(state.popInt(), InvTypeValid); + state.pushInt(invType.size); + }, + [ScriptOpcode_default.INV_STOCKBASE]: state => { + const [inv, obj] = state.popInts(2); + const invType = check(inv, InvTypeValid); + const objType = check(obj, ObjTypeValid); + if (!invType.stockobj || !invType.stockcount) { + state.pushInt(-1); + return; + } + const index = invType.stockobj.indexOf(objType.id); + state.pushInt(index >= 0 ? invType.stockcount[index] : -1); + }, + [ScriptOpcode_default.INV_ADD]: checkedHandler(ActivePlayer, state => { + const [inv, objId, count] = state.popInts(3); + const invType = check(inv, InvTypeValid); + const objType = check(objId, ObjTypeValid); + check(count, ObjStackValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${invType.debugname}`); + } + if (!invType.dummyinv && objType.dummyitem !== 0) { + throw new Error(`dummyitem in non-dummyinv: ${objType.debugname} -> ${invType.debugname}`); + } + const player = state.activePlayer; + const overflow = count - player.invAdd(invType.id, objType.id, count); + if (overflow > 0) { + World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, objType.id, overflow), player.pid, 200); + } + }), + [ScriptOpcode_default.INV_CHANGESLOT]: checkedHandler(ActivePlayer, state => { + const [inv, find, replace, replaceCount] = state.popInts(4); + throw new Error('unimplemented'); + }), + [ScriptOpcode_default.INV_CLEAR]: checkedHandler(ActivePlayer, state => { + const invType = check(state.popInt(), InvTypeValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${invType.debugname}`); + } + state.activePlayer.invClear(invType.id); + }), + [ScriptOpcode_default.INV_DEL]: checkedHandler(ActivePlayer, state => { + const [inv, obj, count] = state.popInts(3); + const invType = check(inv, InvTypeValid); + const objType = check(obj, ObjTypeValid); + check(count, ObjStackValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${invType.debugname}`); + } + state.activePlayer.invDel(invType.id, objType.id, count); + }), + [ScriptOpcode_default.INV_DELSLOT]: checkedHandler(ActivePlayer, state => { + const [inv, slot] = state.popInts(2); + const invType = check(inv, InvTypeValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${invType.debugname}`); + } + const obj = state.activePlayer.invGetSlot(invType.id, slot); + if (!obj) { + return; + } + state.activePlayer.invDelSlot(invType.id, slot); + }), + [ScriptOpcode_default.INV_DROPITEM]: checkedHandler(ActivePlayer, state => { + const [inv, coord, obj, count, duration] = state.popInts(5); + const invType = check(inv, InvTypeValid); + const position = check(coord, CoordValid); + const objType = check(obj, ObjTypeValid); + check(count, ObjStackValid); + check(duration, DurationValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${invType.debugname}`); + } + const player = state.activePlayer; + const completed = player.invDel(invType.id, objType.id, count); + if (completed == 0) { + return; + } + player.playerLog('Dropped item from', invType.debugname, objType.debugname); + const floorObj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objType.id, completed); + World_default.addObj(floorObj, player.pid, duration); + state.activeObj = floorObj; + state.pointerAdd(ActiveObj[state.intOperand]); + }), + [ScriptOpcode_default.INV_DROPSLOT]: checkedHandler(ActivePlayer, state => { + const [inv, coord, slot, duration] = state.popInts(4); + const invType = check(inv, InvTypeValid); + check(duration, DurationValid); + const position = check(coord, CoordValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${invType.debugname}`); + } + const obj = state.activePlayer.invGetSlot(invType.id, slot); + if (!obj) { + throw new Error('$slot is empty'); + } + const player = state.activePlayer; + const completed = player.invDel(invType.id, obj.id, obj.count, slot); + if (completed === 0) { + return; + } + const objType = ObjType.get(obj.id); + player.playerLog('Dropped item from', invType.debugname, objType.debugname); + const floorObj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, obj.id, completed); + World_default.addObj(floorObj, player.pid, duration); + state.activeObj = floorObj; + state.pointerAdd(ActiveObj[state.intOperand]); + }), + [ScriptOpcode_default.INV_FREESPACE]: checkedHandler(ActivePlayer, state => { + const invType = check(state.popInt(), InvTypeValid); + state.pushInt(state.activePlayer.invFreeSpace(invType.id)); + }), + [ScriptOpcode_default.INV_GETNUM]: checkedHandler(ActivePlayer, state => { + const [inv, slot] = state.popInts(2); + const invType = check(inv, InvTypeValid); + state.pushInt(state.activePlayer.invGetSlot(invType.id, slot)?.count ?? 0); + }), + [ScriptOpcode_default.INV_GETOBJ]: checkedHandler(ActivePlayer, state => { + const [inv, slot] = state.popInts(2); + const invType = check(inv, InvTypeValid); + state.pushInt(state.activePlayer.invGetSlot(invType.id, slot)?.id ?? -1); + }), + [ScriptOpcode_default.INV_ITEMSPACE]: checkedHandler(ActivePlayer, state => { + const [inv, obj, count, size] = state.popInts(4); + const invType = check(inv, InvTypeValid); + const objType = check(obj, ObjTypeValid); + check(count, ObjStackValid); + if (size < 0 || size > invType.size) { + throw new Error(`\$count is out of range: ${count}`); + } + state.pushInt(state.activePlayer.invItemSpace(invType.id, objType.id, count, size) === 0 ? 1 : 0); + }), + [ScriptOpcode_default.INV_ITEMSPACE2]: checkedHandler(ActivePlayer, state => { + const [inv, obj, count, size] = state.popInts(4); + const invType = check(inv, InvTypeValid); + const objType = check(obj, ObjTypeValid); + check(count, ObjStackValid); + state.pushInt(state.activePlayer.invItemSpace(invType.id, objType.id, count, size)); + }), + [ScriptOpcode_default.INV_MOVEFROMSLOT]: checkedHandler(ActivePlayer, state => { + const [fromInv, toInv, fromSlot] = state.popInts(3); + const fromInvType = check(fromInv, InvTypeValid); + const toInvType = check(toInv, InvTypeValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${fromInvType.debugname}`); + } + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${toInvType.debugname}`); + } + const player = state.activePlayer; + const {overflow, fromObj} = player.invMoveFromSlot(fromInvType.id, toInvType.id, fromSlot); + if (overflow > 0) { + World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, fromObj, overflow), player.pid, 200); + } + }), + [ScriptOpcode_default.INV_MOVETOSLOT]: checkedHandler(ActivePlayer, state => { + const [fromInv, toInv, fromSlot, toSlot] = state.popInts(4); + const fromInvType = check(fromInv, InvTypeValid); + const toInvType = check(toInv, InvTypeValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${fromInvType.debugname}`); + } + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${toInvType.debugname}`); + } + state.activePlayer.invMoveToSlot(fromInvType.id, toInvType.id, fromSlot, toSlot); + }), + [ScriptOpcode_default.BOTH_MOVEINV]: checkedHandler(ActivePlayer, state => { + const [from, to] = state.popInts(2); + const fromInvType = check(from, InvTypeValid); + const toInvType = check(to, InvTypeValid); + const secondary = state.intOperand == 1; + const fromPlayer = secondary ? state._activePlayer2 : state._activePlayer; + const toPlayer = secondary ? state._activePlayer : state._activePlayer2; + if (!fromPlayer || !toPlayer) { + throw new Error('player is null'); + } + if (!state.pointerGet(ProtectedActivePlayer[secondary ? 1 : 0]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$from_inv requires protected access: ${fromInvType.debugname}`); + } + if (!state.pointerGet(ProtectedActivePlayer[secondary ? 0 : 1]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$to_inv requires protected access: ${toInvType.debugname}`); + } + const fromInv = fromPlayer.getInventory(from); + const toInv = toPlayer.getInventory(to); + if (!fromInv || !toInv) { + throw new Error('inv is null'); + } + for (let slot = 0; slot < fromInv.capacity; slot++) { + const obj = fromInv.get(slot); + if (!obj) { + continue; + } + fromInv.delete(slot); + toInv.add(obj.id, obj.count); + fromPlayer.playerLog('Gave ' + ObjType.get(obj.id).name + ' x' + obj.count + ' during trade with ' + toPlayer.username); + toPlayer.playerLog('Received ' + ObjType.get(obj.id).name + ' x' + obj.count + ' during trade with ' + fromPlayer.username); + } + }), + [ScriptOpcode_default.INV_MOVEITEM]: checkedHandler(ActivePlayer, state => { + const [fromInv, toInv, obj, count] = state.popInts(4); + const fromInvType = check(fromInv, InvTypeValid); + const toInvType = check(toInv, InvTypeValid); + const objType = check(obj, ObjTypeValid); + check(count, ObjStackValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${fromInvType.debugname}`); + } + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${toInvType.debugname}`); + } + const player = state.activePlayer; + const completed = player.invDel(fromInvType.id, objType.id, count); + if (completed == 0) { + return; + } + const overflow = count - player.invAdd(toInvType.id, objType.id, completed); + if (overflow > 0) { + World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, objType.id, overflow), player.pid, 200); + } + }), + [ScriptOpcode_default.INV_MOVEITEM_CERT]: checkedHandler(ActivePlayer, state => { + const [fromInv, toInv, obj, count] = state.popInts(4); + const fromInvType = check(fromInv, InvTypeValid); + const toInvType = check(toInv, InvTypeValid); + const objType = check(obj, ObjTypeValid); + check(count, ObjStackValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${fromInvType.debugname}`); + } + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${toInvType.debugname}`); + } + const player = state.activePlayer; + const completed = player.invDel(fromInvType.id, objType.id, count); + if (completed == 0) { + return; + } + let finalObj = objType.id; + if (objType.certtemplate === -1 && objType.certlink >= 0) { + finalObj = objType.certlink; + } + const overflow = count - player.invAdd(toInvType.id, finalObj, completed); + if (overflow > 0) { + World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, finalObj, overflow), player.pid, 200); + } + }), + [ScriptOpcode_default.INV_MOVEITEM_UNCERT]: checkedHandler(ActivePlayer, state => { + const [fromInv, toInv, obj, count] = state.popInts(4); + const fromInvType = check(fromInv, InvTypeValid); + const toInvType = check(toInv, InvTypeValid); + const objType = check(obj, ObjTypeValid); + check(count, ObjStackValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${fromInvType.debugname}`); + } + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${toInvType.debugname}`); + } + const player = state.activePlayer; + const completed = player.invDel(fromInvType.id, objType.id, count); + if (completed == 0) { + return; + } + if (objType.certtemplate >= 0 && objType.certlink >= 0) { + player.invAdd(toInvType.id, objType.certlink, completed); + } else { + player.invAdd(toInvType.id, objType.id, completed); + } + }), + [ScriptOpcode_default.INV_SETSLOT]: checkedHandler(ActivePlayer, state => { + const [inv, slot, objId, count] = state.popInts(4); + const invType = check(inv, InvTypeValid); + const objType = check(objId, ObjTypeValid); + check(count, ObjStackValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${invType.debugname}`); + } + if (!invType.dummyinv && objType.dummyitem !== 0) { + throw new Error(`dummyitem in non-dummyinv: ${objType.debugname} -> ${invType.debugname}`); + } + state.activePlayer.invSet(invType.id, objType.id, count, slot); + }), + [ScriptOpcode_default.INV_TOTAL]: checkedHandler(ActivePlayer, state => { + const [inv, obj] = state.popInts(2); + const invType = check(inv, InvTypeValid); + if (obj === -1) { + state.pushInt(0); + return; + } + state.pushInt(state.activePlayer.invTotal(invType.id, obj)); + }), + [ScriptOpcode_default.INV_TOTALCAT]: checkedHandler(ActivePlayer, state => { + const [inv, category] = state.popInts(2); + const invType = check(inv, InvTypeValid); + const catType = check(category, CategoryTypeValid); + state.pushInt(state.activePlayer.invTotalCat(invType.id, catType.id)); + }), + [ScriptOpcode_default.INV_TRANSMIT]: checkedHandler(ActivePlayer, state => { + const [inv, com] = state.popInts(2); + const invType = check(inv, InvTypeValid); + check(com, NumberNotNull); + state.activePlayer.invListenOnCom(invType.id, com, state.activePlayer.uid); + }), + [ScriptOpcode_default.INVOTHER_TRANSMIT]: checkedHandler(ActivePlayer, state => { + const [uid, inv, com] = state.popInts(3); + check(uid, NumberNotNull); + const invType = check(inv, InvTypeValid); + check(com, NumberNotNull); + state.activePlayer.invListenOnCom(invType.id, com, uid); + }), + [ScriptOpcode_default.INV_STOPTRANSMIT]: checkedHandler(ActivePlayer, state => { + const com = check(state.popInt(), NumberNotNull); + state.activePlayer.invStopListenOnCom(com); + }), + [ScriptOpcode_default.BOTH_DROPSLOT]: checkedHandler(ActivePlayer, state => { + const [inv, coord, slot, duration] = state.popInts(4); + const invType = check(inv, InvTypeValid); + check(duration, DurationValid); + const position = check(coord, CoordValid); + const secondary = state.intOperand == 1; + const fromPlayer = secondary ? state._activePlayer2 : state._activePlayer; + const toPlayer = secondary ? state._activePlayer : state._activePlayer2; + if (!fromPlayer || !toPlayer) { + throw new Error('player is null'); + } + if (!state.pointerGet(ProtectedActivePlayer[secondary ? 1 : 0]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`inv requires protected access: ${invType.debugname}`); + } + const obj = fromPlayer.invGetSlot(invType.id, slot); + if (!obj) { + throw new Error('$slot is empty'); + } + const completed = fromPlayer.invDel(invType.id, obj.id, obj.count, slot); + if (completed === 0) { + return; + } + const objType = ObjType.get(obj.id); + fromPlayer.playerLog('Dropped item from', invType.debugname, objType.debugname); + if (!objType.tradeable) { + return; + } + World_default.addObj(new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, obj.id, completed), toPlayer.pid, duration); + }), + [ScriptOpcode_default.INV_DROPALL]: checkedHandler(ActivePlayer, state => { + const [inv, coord, duration] = state.popInts(3); + const invType = check(inv, InvTypeValid); + check(duration, DurationValid); + const position = check(coord, CoordValid); + if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { + throw new Error(`\$inv requires protected access: ${invType.debugname}`); + } + const inventory = state.activePlayer.getInventory(invType.id); + if (!inventory) { + return; + } + for (let slot = 0; slot < inventory.capacity; slot++) { + const obj = inventory.get(slot); + if (!obj) { + continue; + } + inventory.delete(slot); + const objType = ObjType.get(obj.id); + if (!objType.tradeable) { + continue; + } + World_default.addObj(new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, obj.id, obj.count), -1, duration); + } + }), + [ScriptOpcode_default.INV_TOTALPARAM]: checkedHandler(ActivePlayer, state => { + const [inv, param] = state.popInts(2); + state.pushInt(state.activePlayer.invTotalParam(inv, param)); + }), + [ScriptOpcode_default.INV_TOTALPARAM_STACK]: checkedHandler(ActivePlayer, state => { + const [inv, param] = state.popInts(2); + state.pushInt(state.activePlayer.invTotalParamStack(inv, param)); + }) +}; +var InvOps_default = InvOps; + +// src/lostcity/entity/NpcIteratorType.ts +var NpcIteratorType; +(NpcIteratorType2 => { + NpcIteratorType2[(NpcIteratorType2['ZONE'] = 0)] = 'ZONE'; + NpcIteratorType2[(NpcIteratorType2['DISTANCE'] = 1)] = 'DISTANCE'; +})((NpcIteratorType ||= {})); +var NpcIteratorType_default = NpcIteratorType; + +// src/lostcity/engine/script/ScriptIterators.ts +class ScriptIterator { + iterator; + tick; + constructor(tick) { + this.iterator = this.generator(); + this.tick = tick; + } + [Symbol.iterator]() { + return this.iterator; + } + next() { + return this.iterator.next(); + } +} + +class HuntIterator extends ScriptIterator { + x; + z; + level; + minX; + maxX; + minZ; + maxZ; + distance; + checkVis; + checkType; + checkCategory; + type; + constructor(tick, level, x, z2, distance, checkVis, checkType, checkCategory, type) { + super(tick); + const centerX = Position.zone(x); + const centerZ = Position.zone(z2); + const radius = (1 + distance / 8) | 0; + this.x = x; + this.z = z2; + this.level = level; + this.maxX = centerX + radius; + this.minX = centerX - radius; + this.maxZ = centerZ + radius; + this.minZ = centerZ - radius; + this.distance = distance; + this.checkVis = checkVis; + this.checkType = checkType; + this.checkCategory = checkCategory; + this.type = type; + } + *generator() { + for (let x = this.maxX; x >= this.minX; x--) { + const zoneX = x << 3; + for (let z2 = this.maxZ; z2 >= this.minZ; z2--) { + const zoneZ = z2 << 3; + if (this.type === HuntModeType_default.PLAYER) { + for (const player of World_default.getZone(zoneX, zoneZ, this.level).getAllPlayersSafe()) { + if (World_default.currentTick > this.tick) { + throw new Error('[HuntIterator] tried to use an old iterator. Create a new iterator instead.'); + } + if (Position.distanceToSW({x: this.x, z: this.z}, player) > this.distance) { + continue; + } + if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, player.x, player.z, 1, 1, 1, 1)) { + continue; + } + if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, player.x, player.z, 1, 1, 1, 1)) { + continue; + } + yield player; + } + } else if (this.type === HuntModeType_default.NPC) { + for (const npc of World_default.getZone(zoneX, zoneZ, this.level).getAllNpcsSafe()) { + if (World_default.currentTick > this.tick) { + throw new Error('[HuntIterator] tried to use an old iterator. Create a new iterator instead.'); + } + if (this.checkType !== -1 && npc.type !== this.checkType) { + continue; + } + const npcType = NpcType.get(npc.type); + if (this.checkCategory !== -1 && npcType.category !== this.checkCategory) { + continue; + } + if (!npcType.op) { + continue; + } + if (!npcType.op[1]) { + continue; + } + if (Position.distanceToSW({x: this.x, z: this.z}, npc) > this.distance) { + continue; + } + if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { + continue; + } + if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { + continue; + } + yield npc; + } + } else if (this.type === HuntModeType_default.OBJ) { + for (const obj of World_default.getZone(zoneX, zoneZ, this.level).getAllObjsSafe()) { + if (World_default.currentTick > this.tick) { + throw new Error('[HuntIterator] tried to use an old iterator. Create a new iterator instead.'); + } + if (this.checkType !== -1 && obj.type !== this.checkType) { + continue; + } + const objType = ObjType.get(obj.type); + if (this.checkCategory !== -1 && objType.category !== this.checkCategory) { + continue; + } + if (Position.distanceToSW({x: this.x, z: this.z}, obj) > this.distance) { + continue; + } + if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, obj.x, obj.z, 1, 1, 1, 1)) { + continue; + } + if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, obj.x, obj.z, 1, 1, 1, 1)) { + continue; + } + yield obj; + } + } else if (this.type === HuntModeType_default.SCENERY) { + for (const loc of World_default.getZone(zoneX, zoneZ, this.level).getAllLocsSafe()) { + if (World_default.currentTick > this.tick) { + throw new Error('[HuntIterator] tried to use an old iterator. Create a new iterator instead.'); + } + if (this.checkType !== -1 && loc.type !== this.checkType) { + continue; + } + const locType = LocType.get(loc.type); + if (this.checkCategory !== -1 && locType.category !== this.checkCategory) { + continue; + } + if (Position.distanceToSW({x: this.x, z: this.z}, loc) > this.distance) { + continue; + } + if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, loc.x, loc.z, 1, 1, 1, 1)) { + continue; + } + if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, loc.x, loc.z, 1, 1, 1, 1)) { + continue; + } + yield loc; + } + } + } + } + } +} + +class NpcIterator extends ScriptIterator { + level; + x; + z; + minX; + maxX; + minZ; + maxZ; + distance; + checkVis; + type; + constructor(tick, level, x, z2, distance, checkVis, type) { + super(tick); + const centerX = Position.zone(x); + const centerZ = Position.zone(z2); + const radius = (1 + distance / 8) | 0; + this.x = x; + this.z = z2; + this.level = level; + this.maxX = centerX + radius; + this.minX = centerX - radius; + this.maxZ = centerZ + radius; + this.minZ = centerZ - radius; + this.distance = distance; + this.checkVis = checkVis; + this.type = type; + } + *generator() { + if (this.type === NpcIteratorType_default.ZONE) { + for (const npc of World_default.getZone(this.x, this.z, this.level).getAllNpcsSafe()) { + if (World_default.currentTick > this.tick) { + throw new Error('[NpcIterator] tried to use an old iterator. Create a new iterator instead.'); + } + yield npc; + } + } else if (this.type === NpcIteratorType_default.DISTANCE) { + for (let x = this.maxX; x >= this.minX; x--) { + const zoneX = x << 3; + for (let z2 = this.maxZ; z2 >= this.minZ; z2--) { + const zoneZ = z2 << 3; + for (const npc of World_default.getZone(zoneX, zoneZ, this.level).getAllNpcsSafe()) { + if (World_default.currentTick > this.tick) { + throw new Error('[NpcIterator] tried to use an old iterator. Create a new iterator instead.'); + } + if (Position.distanceToSW({x: this.x, z: this.z}, npc) > this.distance) { + continue; + } + if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { + continue; + } + if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { + continue; + } + yield npc; + } + } + } + } + } +} + +class LocIterator extends ScriptIterator { + level; + x; + z; + constructor(tick, level, x, z2) { + super(tick); + this.level = level; + this.x = x; + this.z = z2; + } + *generator() { + for (const loc of World_default.getZone(this.x, this.z, this.level).getAllLocsSafe()) { + if (World_default.currentTick > this.tick) { + throw new Error('[LocIterator] tried to use an old iterator. Create a new iterator instead.'); + } + yield loc; + } + } +} + +// src/lostcity/entity/Loc.ts +class Loc extends NonPathingEntity { + info; + constructor(level, x, z2, width, length, lifecycle, type, shape, angle) { + super(level, x, z2, width, length, lifecycle); + this.info = (type & 16383) | ((shape & 31) << 14) | ((angle & 3) << 19); + } + get type() { + return this.info & 16383; + } + get shape() { + return (this.info >> 14) & 31; + } + get angle() { + return (this.info >> 19) & 3; + } +} + +// src/lostcity/engine/script/handlers/LocOps.ts +var LocOps = { + [ScriptOpcode_default.LOC_ADD]: state => { + const [coord, type, angle, shape, duration] = state.popInts(5); + const position = check(coord, CoordValid); + const locType = check(type, LocTypeValid); + const locAngle = check(angle, LocAngleValid); + const locShape = check(shape, LocShapeValid); + check(duration, DurationValid); + const created = new Loc(position.level, position.x, position.z, locType.width, locType.length, EntityLifeCycle_default.DESPAWN, locType.id, locShape, locAngle); + const locs = World_default.getZone(position.x, position.z, position.level).getLocsUnsafe(Position.packZoneCoord(position.x, position.z)); + for (const loc of locs) { + if (loc !== created && loc.angle === locAngle && loc.shape === locShape) { + World_default.removeLoc(loc, duration); + break; + } + } + World_default.addLoc(created, duration); + state.activeLoc = created; + state.pointerAdd(ActiveLoc[state.intOperand]); + }, + [ScriptOpcode_default.LOC_ANGLE]: checkedHandler(ActiveLoc, state => { + state.pushInt(check(state.activeLoc.angle, LocAngleValid)); + }), + [ScriptOpcode_default.LOC_ANIM]: checkedHandler(ActiveLoc, state => { + const seqType = check(state.popInt(), SeqTypeValid); + World_default.animLoc(state.activeLoc, seqType.id); + }), + [ScriptOpcode_default.LOC_CATEGORY]: checkedHandler(ActiveLoc, state => { + state.pushInt(check(state.activeLoc.type, LocTypeValid).category); + }), + [ScriptOpcode_default.LOC_CHANGE]: checkedHandler(ActiveLoc, state => { + const [id, duration] = state.popInts(2); + const locType = check(id, LocTypeValid); + check(duration, DurationValid); + World_default.removeLoc(state.activeLoc, duration); + const {level, x, z: z2, angle, shape} = state.activeLoc; + const created = new Loc(level, x, z2, locType.width, locType.length, EntityLifeCycle_default.DESPAWN, locType.id, shape, angle); + const locs = World_default.getZone(x, z2, level).getLocsUnsafe(Position.packZoneCoord(x, z2)); + for (const loc of locs) { + if (loc !== created && loc.angle === angle && loc.shape === shape) { + World_default.removeLoc(loc, duration); + break; + } + } + World_default.addLoc(created, duration); + state.activeLoc = created; + state.pointerAdd(ActiveLoc[state.intOperand]); + }), + [ScriptOpcode_default.LOC_COORD]: checkedHandler(ActiveLoc, state => { + const position = state.activeLoc; + state.pushInt(Position.packCoord(position.level, position.x, position.z)); + }), + [ScriptOpcode_default.LOC_DEL]: checkedHandler(ActiveLoc, state => { + const duration = check(state.popInt(), DurationValid); + const {level, x, z: z2, angle, shape} = state.activeLoc; + const locs = World_default.getZone(x, z2, level).getLocsUnsafe(Position.packZoneCoord(x, z2)); + for (const loc of locs) { + if (loc !== state.activeLoc && loc.angle === angle && loc.shape === shape) { + World_default.removeLoc(loc, duration); + break; + } + } + World_default.removeLoc(state.activeLoc, duration); + }), + [ScriptOpcode_default.LOC_FIND]: state => { + const [coord, locId] = state.popInts(2); + const locType = check(locId, LocTypeValid); + const position = check(coord, CoordValid); + const loc = World_default.getLoc(position.x, position.z, position.level, locType.id); + if (!loc) { + state.pushInt(0); + return; + } + state.activeLoc = loc; + state.pointerAdd(ActiveLoc[state.intOperand]); + state.pushInt(1); + }, + [ScriptOpcode_default.LOC_FINDALLZONE]: state => { + const position = check(state.popInt(), CoordValid); + state.locIterator = new LocIterator(World_default.currentTick, position.level, position.x, position.z); + if (state._activeLoc) { + state._activeLoc2 = state._activeLoc; + state.pointerAdd(ScriptPointer_default.ActiveLoc2); + } + }, + [ScriptOpcode_default.LOC_FINDNEXT]: state => { + const result = state.locIterator?.next(); + if (!result || result.done) { + state.pushInt(0); + return; + } + state.activeLoc = result.value; + state.pointerAdd(ActiveLoc[state.intOperand]); + state.pushInt(1); + }, + [ScriptOpcode_default.LOC_PARAM]: checkedHandler(ActiveLoc, state => { + const paramType = check(state.popInt(), ParamTypeValid); + const locType = check(state.activeLoc.type, LocTypeValid); + if (paramType.isString()) { + state.pushString(ParamHelper.getStringParam(paramType.id, locType, paramType.defaultString)); + } else { + state.pushInt(ParamHelper.getIntParam(paramType.id, locType, paramType.defaultInt)); + } + }), + [ScriptOpcode_default.LOC_TYPE]: checkedHandler(ActiveLoc, state => { + state.pushInt(check(state.activeLoc.type, LocTypeValid).id); + }), + [ScriptOpcode_default.LOC_NAME]: checkedHandler(ActiveLoc, state => { + state.pushString(check(state.activeLoc.type, LocTypeValid).name ?? 'null'); + }), + [ScriptOpcode_default.LOC_SHAPE]: checkedHandler(ActiveLoc, state => { + state.pushInt(check(state.activeLoc.shape, LocShapeValid)); + }) +}; +var LocOps_default = LocOps; + +// src/lostcity/engine/script/handlers/LocConfigOps.ts +var LocConfigOps = { + [ScriptOpcode_default.LC_NAME]: state => { + const locType = check(state.popInt(), LocTypeValid); + state.pushString(locType.name ?? locType.debugname ?? 'null'); + }, + [ScriptOpcode_default.LC_PARAM]: state => { + const [locId, paramId] = state.popInts(2); + const locType = check(locId, LocTypeValid); + const paramType = check(paramId, ParamTypeValid); + if (paramType.isString()) { + state.pushString(ParamHelper.getStringParam(paramType.id, locType, paramType.defaultString)); + } else { + state.pushInt(ParamHelper.getIntParam(paramType.id, locType, paramType.defaultInt)); + } + }, + [ScriptOpcode_default.LC_CATEGORY]: state => { + state.pushInt(check(state.popInt(), LocTypeValid).category); + }, + [ScriptOpcode_default.LC_DESC]: state => { + state.pushString(check(state.popInt(), LocTypeValid).desc ?? 'null'); + }, + [ScriptOpcode_default.LC_DEBUGNAME]: state => { + state.pushString(check(state.popInt(), LocTypeValid).debugname ?? 'null'); + }, + [ScriptOpcode_default.LC_WIDTH]: state => { + state.pushInt(check(state.popInt(), LocTypeValid).width); + }, + [ScriptOpcode_default.LC_LENGTH]: state => { + state.pushInt(check(state.popInt(), LocTypeValid).length); + } +}; +var LocConfigOps_default = LocConfigOps; + +// src/lostcity/engine/script/ServerTriggerType.ts +var ServerTriggerType; +(ServerTriggerType2 => { + ServerTriggerType2[(ServerTriggerType2['PROC'] = 0)] = 'PROC'; + ServerTriggerType2[(ServerTriggerType2['LABEL'] = 1)] = 'LABEL'; + ServerTriggerType2[(ServerTriggerType2['DEBUGPROC'] = 2)] = 'DEBUGPROC'; + ServerTriggerType2[(ServerTriggerType2['APNPC1'] = 3)] = 'APNPC1'; + ServerTriggerType2[(ServerTriggerType2['APNPC2'] = 4)] = 'APNPC2'; + ServerTriggerType2[(ServerTriggerType2['APNPC3'] = 5)] = 'APNPC3'; + ServerTriggerType2[(ServerTriggerType2['APNPC4'] = 6)] = 'APNPC4'; + ServerTriggerType2[(ServerTriggerType2['APNPC5'] = 7)] = 'APNPC5'; + ServerTriggerType2[(ServerTriggerType2['APNPCU'] = 8)] = 'APNPCU'; + ServerTriggerType2[(ServerTriggerType2['APNPCT'] = 9)] = 'APNPCT'; + ServerTriggerType2[(ServerTriggerType2['OPNPC1'] = 10)] = 'OPNPC1'; + ServerTriggerType2[(ServerTriggerType2['OPNPC2'] = 11)] = 'OPNPC2'; + ServerTriggerType2[(ServerTriggerType2['OPNPC3'] = 12)] = 'OPNPC3'; + ServerTriggerType2[(ServerTriggerType2['OPNPC4'] = 13)] = 'OPNPC4'; + ServerTriggerType2[(ServerTriggerType2['OPNPC5'] = 14)] = 'OPNPC5'; + ServerTriggerType2[(ServerTriggerType2['OPNPCU'] = 15)] = 'OPNPCU'; + ServerTriggerType2[(ServerTriggerType2['OPNPCT'] = 16)] = 'OPNPCT'; + ServerTriggerType2[(ServerTriggerType2['AI_APNPC1'] = 17)] = 'AI_APNPC1'; + ServerTriggerType2[(ServerTriggerType2['AI_APNPC2'] = 18)] = 'AI_APNPC2'; + ServerTriggerType2[(ServerTriggerType2['AI_APNPC3'] = 19)] = 'AI_APNPC3'; + ServerTriggerType2[(ServerTriggerType2['AI_APNPC4'] = 20)] = 'AI_APNPC4'; + ServerTriggerType2[(ServerTriggerType2['AI_APNPC5'] = 21)] = 'AI_APNPC5'; + ServerTriggerType2[(ServerTriggerType2['AI_OPNPC1'] = 24)] = 'AI_OPNPC1'; + ServerTriggerType2[(ServerTriggerType2['AI_OPNPC2'] = 25)] = 'AI_OPNPC2'; + ServerTriggerType2[(ServerTriggerType2['AI_OPNPC3'] = 26)] = 'AI_OPNPC3'; + ServerTriggerType2[(ServerTriggerType2['AI_OPNPC4'] = 27)] = 'AI_OPNPC4'; + ServerTriggerType2[(ServerTriggerType2['AI_OPNPC5'] = 28)] = 'AI_OPNPC5'; + ServerTriggerType2[(ServerTriggerType2['APOBJ1'] = 31)] = 'APOBJ1'; + ServerTriggerType2[(ServerTriggerType2['APOBJ2'] = 32)] = 'APOBJ2'; + ServerTriggerType2[(ServerTriggerType2['APOBJ3'] = 33)] = 'APOBJ3'; + ServerTriggerType2[(ServerTriggerType2['APOBJ4'] = 34)] = 'APOBJ4'; + ServerTriggerType2[(ServerTriggerType2['APOBJ5'] = 35)] = 'APOBJ5'; + ServerTriggerType2[(ServerTriggerType2['APOBJU'] = 36)] = 'APOBJU'; + ServerTriggerType2[(ServerTriggerType2['APOBJT'] = 37)] = 'APOBJT'; + ServerTriggerType2[(ServerTriggerType2['OPOBJ1'] = 38)] = 'OPOBJ1'; + ServerTriggerType2[(ServerTriggerType2['OPOBJ2'] = 39)] = 'OPOBJ2'; + ServerTriggerType2[(ServerTriggerType2['OPOBJ3'] = 40)] = 'OPOBJ3'; + ServerTriggerType2[(ServerTriggerType2['OPOBJ4'] = 41)] = 'OPOBJ4'; + ServerTriggerType2[(ServerTriggerType2['OPOBJ5'] = 42)] = 'OPOBJ5'; + ServerTriggerType2[(ServerTriggerType2['OPOBJU'] = 43)] = 'OPOBJU'; + ServerTriggerType2[(ServerTriggerType2['OPOBJT'] = 44)] = 'OPOBJT'; + ServerTriggerType2[(ServerTriggerType2['AI_APOBJ1'] = 45)] = 'AI_APOBJ1'; + ServerTriggerType2[(ServerTriggerType2['AI_APOBJ2'] = 46)] = 'AI_APOBJ2'; + ServerTriggerType2[(ServerTriggerType2['AI_APOBJ3'] = 47)] = 'AI_APOBJ3'; + ServerTriggerType2[(ServerTriggerType2['AI_APOBJ4'] = 48)] = 'AI_APOBJ4'; + ServerTriggerType2[(ServerTriggerType2['AI_APOBJ5'] = 49)] = 'AI_APOBJ5'; + ServerTriggerType2[(ServerTriggerType2['AI_OPOBJ1'] = 52)] = 'AI_OPOBJ1'; + ServerTriggerType2[(ServerTriggerType2['AI_OPOBJ2'] = 53)] = 'AI_OPOBJ2'; + ServerTriggerType2[(ServerTriggerType2['AI_OPOBJ3'] = 54)] = 'AI_OPOBJ3'; + ServerTriggerType2[(ServerTriggerType2['AI_OPOBJ4'] = 55)] = 'AI_OPOBJ4'; + ServerTriggerType2[(ServerTriggerType2['AI_OPOBJ5'] = 56)] = 'AI_OPOBJ5'; + ServerTriggerType2[(ServerTriggerType2['APLOC1'] = 59)] = 'APLOC1'; + ServerTriggerType2[(ServerTriggerType2['APLOC2'] = 60)] = 'APLOC2'; + ServerTriggerType2[(ServerTriggerType2['APLOC3'] = 61)] = 'APLOC3'; + ServerTriggerType2[(ServerTriggerType2['APLOC4'] = 62)] = 'APLOC4'; + ServerTriggerType2[(ServerTriggerType2['APLOC5'] = 63)] = 'APLOC5'; + ServerTriggerType2[(ServerTriggerType2['APLOCU'] = 64)] = 'APLOCU'; + ServerTriggerType2[(ServerTriggerType2['APLOCT'] = 65)] = 'APLOCT'; + ServerTriggerType2[(ServerTriggerType2['OPLOC1'] = 66)] = 'OPLOC1'; + ServerTriggerType2[(ServerTriggerType2['OPLOC2'] = 67)] = 'OPLOC2'; + ServerTriggerType2[(ServerTriggerType2['OPLOC3'] = 68)] = 'OPLOC3'; + ServerTriggerType2[(ServerTriggerType2['OPLOC4'] = 69)] = 'OPLOC4'; + ServerTriggerType2[(ServerTriggerType2['OPLOC5'] = 70)] = 'OPLOC5'; + ServerTriggerType2[(ServerTriggerType2['OPLOCU'] = 71)] = 'OPLOCU'; + ServerTriggerType2[(ServerTriggerType2['OPLOCT'] = 72)] = 'OPLOCT'; + ServerTriggerType2[(ServerTriggerType2['AI_APLOC1'] = 73)] = 'AI_APLOC1'; + ServerTriggerType2[(ServerTriggerType2['AI_APLOC2'] = 74)] = 'AI_APLOC2'; + ServerTriggerType2[(ServerTriggerType2['AI_APLOC3'] = 75)] = 'AI_APLOC3'; + ServerTriggerType2[(ServerTriggerType2['AI_APLOC4'] = 76)] = 'AI_APLOC4'; + ServerTriggerType2[(ServerTriggerType2['AI_APLOC5'] = 77)] = 'AI_APLOC5'; + ServerTriggerType2[(ServerTriggerType2['AI_OPLOC1'] = 80)] = 'AI_OPLOC1'; + ServerTriggerType2[(ServerTriggerType2['AI_OPLOC2'] = 81)] = 'AI_OPLOC2'; + ServerTriggerType2[(ServerTriggerType2['AI_OPLOC3'] = 82)] = 'AI_OPLOC3'; + ServerTriggerType2[(ServerTriggerType2['AI_OPLOC4'] = 83)] = 'AI_OPLOC4'; + ServerTriggerType2[(ServerTriggerType2['AI_OPLOC5'] = 84)] = 'AI_OPLOC5'; + ServerTriggerType2[(ServerTriggerType2['APPLAYER1'] = 87)] = 'APPLAYER1'; + ServerTriggerType2[(ServerTriggerType2['APPLAYER2'] = 88)] = 'APPLAYER2'; + ServerTriggerType2[(ServerTriggerType2['APPLAYER3'] = 89)] = 'APPLAYER3'; + ServerTriggerType2[(ServerTriggerType2['APPLAYER4'] = 90)] = 'APPLAYER4'; + ServerTriggerType2[(ServerTriggerType2['APPLAYER5'] = 91)] = 'APPLAYER5'; + ServerTriggerType2[(ServerTriggerType2['APPLAYERU'] = 92)] = 'APPLAYERU'; + ServerTriggerType2[(ServerTriggerType2['APPLAYERT'] = 93)] = 'APPLAYERT'; + ServerTriggerType2[(ServerTriggerType2['OPPLAYER1'] = 94)] = 'OPPLAYER1'; + ServerTriggerType2[(ServerTriggerType2['OPPLAYER2'] = 95)] = 'OPPLAYER2'; + ServerTriggerType2[(ServerTriggerType2['OPPLAYER3'] = 96)] = 'OPPLAYER3'; + ServerTriggerType2[(ServerTriggerType2['OPPLAYER4'] = 97)] = 'OPPLAYER4'; + ServerTriggerType2[(ServerTriggerType2['OPPLAYER5'] = 98)] = 'OPPLAYER5'; + ServerTriggerType2[(ServerTriggerType2['OPPLAYERU'] = 99)] = 'OPPLAYERU'; + ServerTriggerType2[(ServerTriggerType2['OPPLAYERT'] = 100)] = 'OPPLAYERT'; + ServerTriggerType2[(ServerTriggerType2['AI_APPLAYER1'] = 101)] = 'AI_APPLAYER1'; + ServerTriggerType2[(ServerTriggerType2['AI_APPLAYER2'] = 102)] = 'AI_APPLAYER2'; + ServerTriggerType2[(ServerTriggerType2['AI_APPLAYER3'] = 103)] = 'AI_APPLAYER3'; + ServerTriggerType2[(ServerTriggerType2['AI_APPLAYER4'] = 104)] = 'AI_APPLAYER4'; + ServerTriggerType2[(ServerTriggerType2['AI_APPLAYER5'] = 105)] = 'AI_APPLAYER5'; + ServerTriggerType2[(ServerTriggerType2['AI_OPPLAYER1'] = 108)] = 'AI_OPPLAYER1'; + ServerTriggerType2[(ServerTriggerType2['AI_OPPLAYER2'] = 109)] = 'AI_OPPLAYER2'; + ServerTriggerType2[(ServerTriggerType2['AI_OPPLAYER3'] = 110)] = 'AI_OPPLAYER3'; + ServerTriggerType2[(ServerTriggerType2['AI_OPPLAYER4'] = 111)] = 'AI_OPPLAYER4'; + ServerTriggerType2[(ServerTriggerType2['AI_OPPLAYER5'] = 112)] = 'AI_OPPLAYER5'; + ServerTriggerType2[(ServerTriggerType2['QUEUE'] = 116)] = 'QUEUE'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE1'] = 117)] = 'AI_QUEUE1'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE2'] = 118)] = 'AI_QUEUE2'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE3'] = 119)] = 'AI_QUEUE3'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE4'] = 120)] = 'AI_QUEUE4'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE5'] = 121)] = 'AI_QUEUE5'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE6'] = 122)] = 'AI_QUEUE6'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE7'] = 123)] = 'AI_QUEUE7'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE8'] = 124)] = 'AI_QUEUE8'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE9'] = 125)] = 'AI_QUEUE9'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE10'] = 126)] = 'AI_QUEUE10'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE11'] = 127)] = 'AI_QUEUE11'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE12'] = 128)] = 'AI_QUEUE12'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE13'] = 129)] = 'AI_QUEUE13'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE14'] = 130)] = 'AI_QUEUE14'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE15'] = 131)] = 'AI_QUEUE15'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE16'] = 132)] = 'AI_QUEUE16'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE17'] = 133)] = 'AI_QUEUE17'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE18'] = 134)] = 'AI_QUEUE18'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE19'] = 135)] = 'AI_QUEUE19'; + ServerTriggerType2[(ServerTriggerType2['AI_QUEUE20'] = 136)] = 'AI_QUEUE20'; + ServerTriggerType2[(ServerTriggerType2['SOFTTIMER'] = 137)] = 'SOFTTIMER'; + ServerTriggerType2[(ServerTriggerType2['TIMER'] = 138)] = 'TIMER'; + ServerTriggerType2[(ServerTriggerType2['AI_TIMER'] = 139)] = 'AI_TIMER'; + ServerTriggerType2[(ServerTriggerType2['OPHELD1'] = 140)] = 'OPHELD1'; + ServerTriggerType2[(ServerTriggerType2['OPHELD2'] = 141)] = 'OPHELD2'; + ServerTriggerType2[(ServerTriggerType2['OPHELD3'] = 142)] = 'OPHELD3'; + ServerTriggerType2[(ServerTriggerType2['OPHELD4'] = 143)] = 'OPHELD4'; + ServerTriggerType2[(ServerTriggerType2['OPHELD5'] = 144)] = 'OPHELD5'; + ServerTriggerType2[(ServerTriggerType2['OPHELDU'] = 145)] = 'OPHELDU'; + ServerTriggerType2[(ServerTriggerType2['OPHELDT'] = 146)] = 'OPHELDT'; + ServerTriggerType2[(ServerTriggerType2['IF_BUTTON'] = 147)] = 'IF_BUTTON'; + ServerTriggerType2[(ServerTriggerType2['INV_BUTTON1'] = 148)] = 'INV_BUTTON1'; + ServerTriggerType2[(ServerTriggerType2['INV_BUTTON2'] = 149)] = 'INV_BUTTON2'; + ServerTriggerType2[(ServerTriggerType2['INV_BUTTON3'] = 150)] = 'INV_BUTTON3'; + ServerTriggerType2[(ServerTriggerType2['INV_BUTTON4'] = 151)] = 'INV_BUTTON4'; + ServerTriggerType2[(ServerTriggerType2['INV_BUTTON5'] = 152)] = 'INV_BUTTON5'; + ServerTriggerType2[(ServerTriggerType2['INV_BUTTOND'] = 153)] = 'INV_BUTTOND'; + ServerTriggerType2[(ServerTriggerType2['IF_CLOSE'] = 154)] = 'IF_CLOSE'; + ServerTriggerType2[(ServerTriggerType2['LOGIN'] = 155)] = 'LOGIN'; + ServerTriggerType2[(ServerTriggerType2['LOGOUT'] = 156)] = 'LOGOUT'; + ServerTriggerType2[(ServerTriggerType2['TUTORIAL_CLICKSIDE'] = 157)] = 'TUTORIAL_CLICKSIDE'; + ServerTriggerType2[(ServerTriggerType2['MOVE'] = 158)] = 'MOVE'; + ServerTriggerType2[(ServerTriggerType2['WALKTRIGGER'] = 159)] = 'WALKTRIGGER'; + ServerTriggerType2[(ServerTriggerType2['AI_WALKTRIGGER'] = 160)] = 'AI_WALKTRIGGER'; + ServerTriggerType2[(ServerTriggerType2['LEVELUP'] = 161)] = 'LEVELUP'; +})((ServerTriggerType ||= {})); +(ServerTriggerType => { + function toString(trigger) { + return ServerTriggerType[trigger].toLowerCase(); + } + ServerTriggerType.toString = toString; +})((ServerTriggerType ||= {})); +var ServerTriggerType_default = ServerTriggerType; + +// src/lostcity/entity/Interaction.ts +var Interaction; +(Interaction2 => { + Interaction2[(Interaction2['SCRIPT'] = 0)] = 'SCRIPT'; + Interaction2[(Interaction2['ENGINE'] = 1)] = 'ENGINE'; +})((Interaction ||= {})); +var Interaction_default = Interaction; + +// src/lostcity/engine/script/handlers/NpcOps.ts +var NpcOps = { + [ScriptOpcode_default.NPC_FINDUID]: state => { + const npcUid = state.popInt(); + const slot = npcUid & 65535; + const expectedType = (npcUid >> 16) & 65535; + const npc = World_default.getNpc(slot); + if (!npc || npc.type !== expectedType) { + state.pushInt(0); + return; + } + state.activeNpc = npc; + state.pointerAdd(ActiveNpc[state.intOperand]); + state.pushInt(1); + }, + [ScriptOpcode_default.NPC_ADD]: state => { + const [coord, id, duration] = state.popInts(3); + const position = check(coord, CoordValid); + const npcType = check(id, NpcTypeValid); + check(duration, DurationValid); + const npc = new Npc2(position.level, position.x, position.z, npcType.size, npcType.size, EntityLifeCycle_default.DESPAWN, World_default.getNextNid(), npcType.id, npcType.moverestrict, npcType.blockwalk); + World_default.addNpc(npc, duration); + state.activeNpc = npc; + state.pointerAdd(ActiveNpc[state.intOperand]); + }, + [ScriptOpcode_default.NPC_ANIM]: checkedHandler(ActiveNpc, state => { + const delay = check(state.popInt(), NumberNotNull); + const seq = state.popInt(); + state.activeNpc.playAnimation(seq, delay); + }), + [ScriptOpcode_default.NPC_BASESTAT]: checkedHandler(ActiveNpc, state => { + const stat = check(state.popInt(), NpcStatValid); + state.pushInt(state.activeNpc.baseLevels[stat]); + }), + [ScriptOpcode_default.NPC_CATEGORY]: checkedHandler(ActiveNpc, state => { + state.pushInt(check(state.activeNpc.type, NpcTypeValid).category); + }), + [ScriptOpcode_default.NPC_COORD]: checkedHandler(ActiveNpc, state => { + const position = state.activeNpc; + state.pushInt(Position.packCoord(position.level, position.x, position.z)); + }), + [ScriptOpcode_default.NPC_DEL]: checkedHandler(ActiveNpc, state => { + World_default.removeNpc(state.activeNpc, check(state.activeNpc.type, NpcTypeValid).respawnrate); + }), + [ScriptOpcode_default.NPC_DELAY]: checkedHandler(ActiveNpc, state => { + state.activeNpc.delay = state.popInt() + 1; + state.execution = ScriptState.NPC_SUSPENDED; + }), + [ScriptOpcode_default.NPC_FACESQUARE]: checkedHandler(ActiveNpc, state => { + const position = check(state.popInt(), CoordValid); + state.activeNpc.faceSquare(position.x, position.z); + }), + [ScriptOpcode_default.NPC_FINDEXACT]: state => { + const [coord, id] = state.popInts(2); + const position = check(coord, CoordValid); + const npcType = check(id, NpcTypeValid); + state.npcIterator = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, 0, 0, NpcIteratorType_default.ZONE); + for (const npc of state.npcIterator) { + if (npc.type === npcType.id && npc.x === position.x && npc.level === position.level && npc.z === position.z) { + state.activeNpc = npc; + state.pointerAdd(ActiveNpc[state.intOperand]); + state.pushInt(1); + return; + } + } + state.pushInt(0); + return; + }, + [ScriptOpcode_default.NPC_FINDHERO]: checkedHandler(ActiveNpc, state => { + const uid = state.activeNpc.findHero(); + if (uid === -1) { + state.pushInt(0); + return; + } + const player = World_default.getPlayerByUid(uid); + if (!player) { + state.pushInt(0); + return; + } + state.activePlayer = player; + state.pointerAdd(ScriptPointer_default.ActivePlayer); + state.pushInt(1); + }), + [ScriptOpcode_default.NPC_PARAM]: checkedHandler(ActiveNpc, state => { + const paramType = check(state.popInt(), ParamTypeValid); + const npcType = check(state.activeNpc.type, NpcTypeValid); + if (paramType.isString()) { + state.pushString(ParamHelper.getStringParam(paramType.id, npcType, paramType.defaultString)); + } else { + state.pushInt(ParamHelper.getIntParam(paramType.id, npcType, paramType.defaultInt)); + } + }), + [ScriptOpcode_default.NPC_QUEUE]: checkedHandler(ActiveNpc, state => { + const delay = check(state.popInt(), NumberNotNull); + const arg = state.popInt(); + const queueId = check(state.popInt(), QueueValid); + const npcType = check(state.activeNpc.type, NpcTypeValid); + const script = ScriptProvider.getByTrigger(ServerTriggerType_default.AI_QUEUE1 + queueId - 1, npcType.id, npcType.category); + if (script) { + state.activeNpc.enqueueScript(script, delay, arg); + } + }), + [ScriptOpcode_default.NPC_RANGE]: checkedHandler(ActiveNpc, state => { + const position = check(state.popInt(), CoordValid); + const npc = state.activeNpc; + if (position.level !== npc.level) { + state.pushInt(-1); + } else { + state.pushInt( + Position.distanceTo(npc, { + x: position.x, + z: position.z, + width: 1, + length: 1 + }) + ); + } + }), + [ScriptOpcode_default.NPC_SAY]: checkedHandler(ActiveNpc, state => { + state.activeNpc.say(state.popString()); + }), + [ScriptOpcode_default.NPC_SETHUNT]: checkedHandler(ActiveNpc, state => { + state.activeNpc.huntrange = check(state.popInt(), NumberNotNull); + }), + [ScriptOpcode_default.NPC_SETHUNTMODE]: checkedHandler(ActiveNpc, state => { + state.activeNpc.huntMode = check(state.popInt(), HuntTypeValid).id; + }), + [ScriptOpcode_default.NPC_SETMODE]: checkedHandler(ActiveNpc, state => { + const mode = check(state.popInt(), NpcModeValid); + state.activeNpc.clearWaypoints(); + if (mode === NpcMode_default.NULL || mode === NpcMode_default.NONE || mode === NpcMode_default.WANDER || mode === NpcMode_default.PATROL) { + state.activeNpc.clearInteraction(); + state.activeNpc.targetOp = mode; + return; + } + state.activeNpc.targetOp = mode; + let target; + if (mode >= NpcMode_default.OPNPC1) { + target = state._activeNpc2; + } else if (mode >= NpcMode_default.OPOBJ1) { + target = state._activeObj; + } else if (mode >= NpcMode_default.OPLOC1) { + target = state._activeLoc; + } else { + target = state._activePlayer; + } + if (target) { + if (target instanceof Npc2 || target instanceof Obj || target instanceof Loc) { + state.activeNpc.setInteraction(Interaction_default.SCRIPT, target, mode, {type: target.type, com: -1}); + } else { + state.activeNpc.setInteraction(Interaction_default.SCRIPT, target, mode); + } + } else { + state.activeNpc.noMode(); + } + }), + [ScriptOpcode_default.NPC_STAT]: checkedHandler(ActiveNpc, state => { + const stat = check(state.popInt(), NpcStatValid); + state.pushInt(state.activeNpc.levels[stat]); + }), + [ScriptOpcode_default.NPC_STATHEAL]: checkedHandler(ActiveNpc, state => { + const [stat, constant, percent] = state.popInts(3); + check(stat, NpcStatValid); + check(constant, NumberNotNull); + check(percent, NumberNotNull); + const npc = state.activeNpc; + const base = npc.baseLevels[stat]; + const current = npc.levels[stat]; + const healed = current + (constant + (current * percent) / 100); + npc.levels[stat] = Math.min(healed, base); + if (stat === 0 && npc.levels[stat] === npc.baseLevels[stat]) { + npc.resetHeroPoints(); + } + }), + [ScriptOpcode_default.NPC_TYPE]: checkedHandler(ActiveNpc, state => { + state.pushInt(check(state.activeNpc.type, NpcTypeValid).id); + }), + [ScriptOpcode_default.NPC_DAMAGE]: checkedHandler(ActiveNpc, state => { + const amount = check(state.popInt(), NumberNotNull); + const type = check(state.popInt(), HitTypeValid); + state.activeNpc.applyDamage(amount, type); + }), + [ScriptOpcode_default.NPC_NAME]: checkedHandler(ActiveNpc, state => { + state.pushString(check(state.activeNpc.type, NpcTypeValid).name ?? 'null'); + }), + [ScriptOpcode_default.NPC_UID]: checkedHandler(ActiveNpc, state => { + state.pushInt(state.activeNpc.uid); + }), + [ScriptOpcode_default.NPC_SETTIMER]: checkedHandler(ActiveNpc, state => { + state.activeNpc.setTimer(check(state.popInt(), NumberNotNull)); + }), + [ScriptOpcode_default.SPOTANIM_NPC]: checkedHandler(ActiveNpc, state => { + const delay = check(state.popInt(), NumberNotNull); + const height = check(state.popInt(), NumberNotNull); + const spotanimType = check(state.popInt(), SpotAnimTypeValid); + state.activeNpc.spotanim(spotanimType.id, height, delay); + }), + [ScriptOpcode_default.NPC_FIND]: state => { + const [coord, npc, distance, checkVis] = state.popInts(4); + const position = check(coord, CoordValid); + const npcType = check(npc, NpcTypeValid); + check(distance, NumberNotNull); + const huntvis = check(checkVis, HuntVisValid); + let closestNpc; + let closestDistance = distance; + const npcs = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, NpcIteratorType_default.DISTANCE); + for (const npc2 of npcs) { + if (npc2 && npc2.type === npcType.id) { + const npcDistance = Position.distanceToSW(position, npc2); + if (npcDistance <= closestDistance) { + closestNpc = npc2; + closestDistance = npcDistance; + } + } + } + if (!closestNpc) { + state.pushInt(0); + return; + } + state.activeNpc = closestNpc; + state.pointerAdd(ActiveNpc[state.intOperand]); + state.pushInt(1); + }, + [ScriptOpcode_default.NPC_FINDALLANY]: state => { + const [coord, distance, checkVis] = state.popInts(3); + const position = check(coord, CoordValid); + check(distance, NumberNotNull); + const huntvis = check(checkVis, HuntVisValid); + state.npcIterator = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, NpcIteratorType_default.DISTANCE); + if (state._activeNpc) { + state._activeNpc2 = state._activeNpc; + state.pointerAdd(ScriptPointer_default.ActiveNpc2); + } + }, + [ScriptOpcode_default.NPC_FINDALLZONE]: state => { + const position = check(state.popInt(), CoordValid); + state.npcIterator = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, 0, 0, NpcIteratorType_default.ZONE); + if (state._activeNpc) { + state._activeNpc2 = state._activeNpc; + state.pointerAdd(ScriptPointer_default.ActiveNpc2); + } + }, + [ScriptOpcode_default.NPC_FINDNEXT]: state => { + const result = state.npcIterator?.next(); + if (!result || result.done) { + state.pushInt(0); + return; + } + state.activeNpc = result.value; + state.pointerAdd(ActiveNpc[state.intOperand]); + state.pushInt(1); + }, + [ScriptOpcode_default.NPC_TELE]: checkedHandler(ActiveNpc, state => { + const position = check(state.popInt(), CoordValid); + state.activeNpc.teleport(position.x, position.z, position.level); + }), + [ScriptOpcode_default.NPC_WALK]: checkedHandler(ActiveNpc, state => { + const position = check(state.popInt(), CoordValid); + state.activeNpc.queueWaypoint(position.x, position.z); + }), + [ScriptOpcode_default.NPC_CHANGETYPE]: checkedHandler(ActiveNpc, state => { + state.activeNpc.changeType(check(state.popInt(), NpcTypeValid).id); + }), + [ScriptOpcode_default.NPC_GETMODE]: checkedHandler(ActiveNpc, state => { + state.pushInt(state.activeNpc.targetOp); + }), + [ScriptOpcode_default.NPC_HEROPOINTS]: checkedHandler([ScriptPointer_default.ActivePlayer, ...ActiveNpc], state => { + state.activeNpc.addHero(state.activePlayer.uid, check(state.popInt(), NumberNotNull)); + }), + [ScriptOpcode_default.NPC_WALKTRIGGER]: checkedHandler(ActiveNpc, state => { + const [queueId, arg] = state.popInts(2); + check(queueId, QueueValid); + state.activeNpc.walktrigger = queueId - 1; + state.activeNpc.walktriggerArg = arg; + }), + [ScriptOpcode_default.NPC_STATADD]: checkedHandler(ActiveNpc, state => { + const [stat, constant, percent] = state.popInts(3); + check(stat, NpcStatValid); + check(constant, NumberNotNull); + check(percent, NumberNotNull); + const npc = state.activeNpc; + const current = npc.levels[stat]; + const added = current + (constant + (current * percent) / 100); + npc.levels[stat] = Math.min(added, 255); + if (stat === 0 && npc.levels[stat] >= npc.baseLevels[stat]) { + npc.resetHeroPoints(); + } + }), + [ScriptOpcode_default.NPC_STATSUB]: checkedHandler(ActiveNpc, state => { + const [stat, constant, percent] = state.popInts(3); + check(stat, NpcStatValid); + check(constant, NumberNotNull); + check(percent, NumberNotNull); + const npc = state.activeNpc; + const current = npc.levels[stat]; + const subbed = current - (constant + (current * percent) / 100); + npc.levels[stat] = Math.max(subbed, 0); + }), + [ScriptOpcode_default.NPC_ATTACKRANGE]: checkedHandler(ActiveNpc, state => { + state.pushInt(check(state.activeNpc.type, NpcTypeValid).attackrange); + }) +}; +var NpcOps_default = NpcOps; + +// src/lostcity/engine/script/handlers/NpcConfigOps.ts +var NpcConfigOps = { + [ScriptOpcode_default.NC_NAME]: state => { + const npcType = check(state.popInt(), NpcTypeValid); + state.pushString(npcType.name ?? npcType.debugname ?? 'null'); + }, + [ScriptOpcode_default.NC_PARAM]: state => { + const [npcId, paramId] = state.popInts(2); + const npcType = check(npcId, NpcTypeValid); + const paramType = check(paramId, ParamTypeValid); + if (paramType.isString()) { + state.pushString(ParamHelper.getStringParam(paramId, npcType, paramType.defaultString)); + } else { + state.pushInt(ParamHelper.getIntParam(paramId, npcType, paramType.defaultInt)); + } + }, + [ScriptOpcode_default.NC_CATEGORY]: state => { + state.pushInt(check(state.popInt(), NpcTypeValid).category); + }, + [ScriptOpcode_default.NC_DESC]: state => { + state.pushString(check(state.popInt(), NpcTypeValid).desc ?? 'null'); + }, + [ScriptOpcode_default.NC_DEBUGNAME]: state => { + state.pushString(check(state.popInt(), NpcTypeValid).debugname ?? 'null'); + }, + [ScriptOpcode_default.NC_OP]: state => { + const [npcId, op] = state.popInts(2); + const npcType = check(npcId, NpcTypeValid); + check(op, NumberNotNull); + if (!npcType.op) { + state.pushString(''); + return; + } + state.pushString(npcType.op[op - 1] ?? ''); + } +}; +var NpcConfigOps_default = NpcConfigOps; + +// src/jagex2/Trig.ts +class Trig { + static _sin = new Int32Array(16384); + static _cos = new Int32Array(16384); + static { + const size = 0.0003834951969714103; + for (let index = 0; index < 16384; index++) { + this._sin[index] = (Math.sin(index * size) * 16384) | 0; + this._cos[index] = (Math.cos(index * size) * 16384) | 0; + } + } + static radians(x) { + return ((x & 16383) / 16384) * 6.283185307179586; + } + static atan2(y3, x) { + return (Math.round(Math.atan2(y3, x) * 2607.5945876176133) & 16383) | 0; + } + static sin(x) { + return this._sin[x & 16383]; + } + static cos(x) { + return this._cos[x & 16383]; + } +} + +// src/lostcity/engine/script/handlers/NumberOps.ts +var NumberOps = { + [ScriptOpcode_default.ADD]: state => { + const b3 = state.popInt(); + const a = state.popInt(); + state.pushInt(a + b3); + }, + [ScriptOpcode_default.SUB]: state => { + const b3 = state.popInt(); + const a = state.popInt(); + state.pushInt(a - b3); + }, + [ScriptOpcode_default.MULTIPLY]: state => { + const b3 = state.popInt(); + const a = state.popInt(); + state.pushInt(a * b3); + }, + [ScriptOpcode_default.DIVIDE]: state => { + const b3 = state.popInt(); + const a = state.popInt(); + state.pushInt(a / b3); + }, + [ScriptOpcode_default.RANDOM]: state => { + const a = state.popInt(); + state.pushInt(Math.random() * a); + }, + [ScriptOpcode_default.RANDOMINC]: state => { + const a = state.popInt(); + state.pushInt(Math.random() * (a + 1)); + }, + [ScriptOpcode_default.INTERPOLATE]: state => { + const [y0, y1, x02, x1, x] = state.popInts(5); + const lerp = Math.floor((y1 - y0) / (x1 - x02)) * (x - x02) + y0; + state.pushInt(lerp); + }, + [ScriptOpcode_default.ADDPERCENT]: state => { + const [num, percent] = state.popInts(2); + state.pushInt(((num * percent) / 100 + num) | 0); + }, + [ScriptOpcode_default.SETBIT]: state => { + const [value, bit] = state.popInts(2); + state.pushInt(value | (1 << bit)); + }, + [ScriptOpcode_default.CLEARBIT]: state => { + const [value, bit] = state.popInts(2); + state.pushInt(value & ~(1 << bit)); + }, + [ScriptOpcode_default.TESTBIT]: state => { + const [value, bit] = state.popInts(2); + state.pushInt(value & (1 << bit) ? 1 : 0); + }, + [ScriptOpcode_default.MODULO]: state => { + const [n1, n2] = state.popInts(2); + state.pushInt(n1 % n2); + }, + [ScriptOpcode_default.POW]: state => { + const [base, exponent] = state.popInts(2); + state.pushInt(Math.pow(base, exponent)); + }, + [ScriptOpcode_default.INVPOW]: state => { + const [n1, n2] = state.popInts(2); + if (n1 === 0 || n2 === 0) { + state.pushInt(0); + } else { + switch (n2) { + case 1: + state.pushInt(n1); + return; + case 2: + state.pushInt(Math.sqrt(n1)); + return; + case 3: + state.pushInt(Math.cbrt(n1)); + return; + case 4: + state.pushInt(Math.sqrt(Math.sqrt(n1))); + return; + default: + state.pushInt(Math.pow(n1, 1 / n2)); + return; + } + } + }, + [ScriptOpcode_default.AND]: state => { + const [n1, n2] = state.popInts(2); + state.pushInt(n1 & n2); + }, + [ScriptOpcode_default.OR]: state => { + const [n1, n2] = state.popInts(2); + state.pushInt(n1 | n2); + }, + [ScriptOpcode_default.MIN]: state => { + const [a, b3] = state.popInts(2); + state.pushInt(Math.min(a, b3)); + }, + [ScriptOpcode_default.MAX]: state => { + const [a, b3] = state.popInts(2); + state.pushInt(Math.max(a, b3)); + }, + [ScriptOpcode_default.SCALE]: state => { + const [a, b3, c] = state.popInts(3); + state.pushInt((a * c) / b3); + }, + [ScriptOpcode_default.BITCOUNT]: state => { + state.pushInt(bitcount(state.popInt())); + }, + [ScriptOpcode_default.TOGGLEBIT]: state => { + const [value, bit] = state.popInts(2); + state.pushInt(value ^ (1 << bit)); + }, + [ScriptOpcode_default.SETBIT_RANGE]: state => { + const [num, startBit, endBit] = state.popInts(3); + state.pushInt(setBitRange(num, startBit, endBit)); + }, + [ScriptOpcode_default.CLEARBIT_RANGE]: state => { + const [num, startBit, endBit] = state.popInts(3); + state.pushInt(clearBitRange(num, startBit, endBit)); + }, + [ScriptOpcode_default.GETBIT_RANGE]: state => { + const [num, startBit, endBit] = state.popInts(3); + const a = 31 - endBit; + state.pushInt((num << a) >>> (startBit + a)); + }, + [ScriptOpcode_default.SETBIT_RANGE_TOINT]: state => { + const [num, value, startBit, endBit] = state.popInts(4); + const clearedBitRange = clearBitRange(num, startBit, endBit); + const maxValue = MASK[endBit - startBit + 1]; + let assignValue = value; + if (value > maxValue) { + assignValue = maxValue; + } + state.pushInt(clearedBitRange | (assignValue << startBit)); + }, + [ScriptOpcode_default.SIN_DEG]: state => { + state.pushInt(Trig.sin(state.popInt())); + }, + [ScriptOpcode_default.COS_DEG]: state => { + state.pushInt(Trig.cos(state.popInt())); + }, + [ScriptOpcode_default.ATAN2_DEG]: state => { + state.pushInt(Trig.atan2(state.popInt(), state.popInt())); + }, + [ScriptOpcode_default.ABS]: state => { + state.pushInt(Math.abs(state.popInt())); + } +}; +var NumberOps_default = NumberOps; + +// src/lostcity/engine/script/handlers/ObjOps.ts +var ObjOps = { + [ScriptOpcode_default.OBJ_ADD]: state => { + const [coord, objId, count, duration] = state.popInts(4); + if (objId === -1 || count === -1) { + return; + } + const objType = check(objId, ObjTypeValid); + check(duration, DurationValid); + const position = check(coord, CoordValid); + check(count, ObjStackValid); + if (objType.dummyitem !== 0) { + throw new Error(`attempted to add dummy item: ${objType.debugname}`); + } + if (objType.members && !Environment_default.NODE_MEMBERS) { + return; + } + if (!objType.stackable || count === 1) { + for (let i = 0; i < count; i++) { + const obj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objId, 1); + World_default.addObj(obj, state.activePlayer.pid, duration); + state.activeObj = obj; + state.pointerAdd(ActiveObj[state.intOperand]); + } + } else { + const obj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objId, count); + World_default.addObj(obj, state.activePlayer.pid, duration); + state.activeObj = obj; + state.pointerAdd(ActiveObj[state.intOperand]); + } + }, + [ScriptOpcode_default.OBJ_ADDALL]: state => { + const [coord, objId, count, duration] = state.popInts(4); + if (objId === -1 || count === -1) { + return; + } + const objType = check(objId, ObjTypeValid); + check(duration, DurationValid); + const position = check(coord, CoordValid); + check(count, ObjStackValid); + if (objType.dummyitem !== 0) { + throw new Error(`attempted to add dummy item: ${objType.debugname}`); + } + if (objType.members && !Environment_default.NODE_MEMBERS) { + return; + } + if (!objType.stackable || count === 1) { + for (let i = 0; i < count; i++) { + const obj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objId, 1); + World_default.addObj(obj, -1, duration); + state.activeObj = obj; + state.pointerAdd(ActiveObj[state.intOperand]); + } + } else { + const obj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objId, count); + World_default.addObj(obj, -1, duration); + state.activeObj = obj; + state.pointerAdd(ActiveObj[state.intOperand]); + } + }, + [ScriptOpcode_default.OBJ_PARAM]: state => { + const paramType = check(state.popInt(), ParamTypeValid); + const objType = check(state.activeObj.type, ObjTypeValid); + if (paramType.isString()) { + state.pushString(ParamHelper.getStringParam(paramType.id, objType, paramType.defaultString)); + } else { + state.pushInt(ParamHelper.getIntParam(paramType.id, objType, paramType.defaultInt)); + } + }, + [ScriptOpcode_default.OBJ_NAME]: state => { + const objType = check(state.activeObj.type, ObjTypeValid); + state.pushString(objType.name ?? objType.debugname ?? 'null'); + }, + [ScriptOpcode_default.OBJ_DEL]: state => { + const duration = ObjType.get(state.activeObj.type).respawnrate; + if (state.pointerGet(ActivePlayer[state.intOperand])) { + World_default.removeObj(state.activeObj, duration); + } else { + World_default.removeObj(state.activeObj, duration); + } + }, + [ScriptOpcode_default.OBJ_COUNT]: state => { + state.pushInt(check(state.activeObj.count, ObjStackValid)); + }, + [ScriptOpcode_default.OBJ_TYPE]: state => { + state.pushInt(check(state.activeObj.type, ObjTypeValid).id); + }, + [ScriptOpcode_default.OBJ_TAKEITEM]: state => { + const invType = check(state.popInt(), InvTypeValid); + const obj = state.activeObj; + const objType = ObjType.get(obj.type); + const zone = World_default.getZone(obj.x, obj.z, obj.level); + for (const o of zone.getObjsSafe(Position.packZoneCoord(obj.x, obj.z))) { + if (o.type !== obj.type || o.count !== obj.count) { + continue; + } + if (o.receiverId !== -1 && o.receiverId !== state.activePlayer.pid) { + continue; + } + state.activePlayer.playerLog('Picked up item', objType.debugname); + state.activePlayer.invAdd(invType.id, obj.type, obj.count); + if (obj.lifecycle === EntityLifeCycle_default.RESPAWN) { + World_default.removeObj(obj, objType.respawnrate); + break; + } else if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { + World_default.removeObj(obj, 0); + break; + } + } + }, + [ScriptOpcode_default.OBJ_COORD]: state => { + const position = state.activeObj; + state.pushInt(Position.packCoord(position.level, position.x, position.z)); + } +}; +var ObjOps_default = ObjOps; + +// src/lostcity/engine/script/handlers/ObjConfigOps.ts +var ObjConfigOps = { + [ScriptOpcode_default.OC_NAME]: state => { + const objType = check(state.popInt(), ObjTypeValid); + state.pushString(objType.name ?? objType.debugname ?? 'null'); + }, + [ScriptOpcode_default.OC_PARAM]: state => { + const [objId, paramId] = state.popInts(2); + const objType = check(objId, ObjTypeValid); + const paramType = check(paramId, ParamTypeValid); + if (paramType.isString()) { + state.pushString(ParamHelper.getStringParam(paramType.id, objType, paramType.defaultString)); + } else { + state.pushInt(ParamHelper.getIntParam(paramType.id, objType, paramType.defaultInt)); + } + }, + [ScriptOpcode_default.OC_CATEGORY]: state => { + state.pushInt(check(state.popInt(), ObjTypeValid).category); + }, + [ScriptOpcode_default.OC_DESC]: state => { + state.pushString(check(state.popInt(), ObjTypeValid).desc ?? 'null'); + }, + [ScriptOpcode_default.OC_MEMBERS]: state => { + state.pushInt(check(state.popInt(), ObjTypeValid).members ? 1 : 0); + }, + [ScriptOpcode_default.OC_WEIGHT]: state => { + state.pushInt(check(state.popInt(), ObjTypeValid).weight); + }, + [ScriptOpcode_default.OC_WEARPOS]: state => { + state.pushInt(check(state.popInt(), ObjTypeValid).wearpos); + }, + [ScriptOpcode_default.OC_WEARPOS2]: state => { + state.pushInt(check(state.popInt(), ObjTypeValid).wearpos2); + }, + [ScriptOpcode_default.OC_WEARPOS3]: state => { + state.pushInt(check(state.popInt(), ObjTypeValid).wearpos3); + }, + [ScriptOpcode_default.OC_COST]: state => { + state.pushInt(check(state.popInt(), ObjTypeValid).cost); + }, + [ScriptOpcode_default.OC_TRADEABLE]: state => { + state.pushInt(check(state.popInt(), ObjTypeValid).tradeable ? 1 : 0); + }, + [ScriptOpcode_default.OC_DEBUGNAME]: state => { + state.pushString(check(state.popInt(), ObjTypeValid).debugname ?? 'null'); + }, + [ScriptOpcode_default.OC_CERT]: state => { + const objType = check(state.popInt(), ObjTypeValid); + if (objType.certtemplate == -1 && objType.certlink >= 0) { + state.pushInt(objType.certlink); + } else { + state.pushInt(objType.id); + } + }, + [ScriptOpcode_default.OC_UNCERT]: state => { + const objType = check(state.popInt(), ObjTypeValid); + if (objType.certtemplate >= 0 && objType.certlink >= 0) { + state.pushInt(objType.certlink); + } else { + state.pushInt(objType.id); + } + }, + [ScriptOpcode_default.OC_STACKABLE]: state => { + state.pushInt(check(state.popInt(), ObjTypeValid).stackable ? 1 : 0); + } +}; +var ObjConfigOps_default = ObjConfigOps; + +// src/lostcity/entity/EntityQueueRequest.ts +class EntityQueueRequest extends Linkable { + type; + script; + args; + delay; + lastInt = 0; + constructor(type, script, args, delay) { + super(); + this.type = type; + this.script = script; + this.args = args; + this.delay = delay; + } +} + +class EntityQueueState extends Linkable { + script; + delay; + constructor(script, delay) { + super(); + this.script = script; + this.delay = delay; + } +} + +// src/lostcity/entity/NetworkPlayer.ts +var {default: fs24} = () => ({}); + +// src/lostcity/network/225/outgoing/prot/ServerProt.ts +class ServerProt { + id; + length; + static all = []; + static byId = []; + static IF_OPENCHATMODAL = new ServerProt(14, 2); + static IF_OPENMAINSIDEMODAL = new ServerProt(28, 4); + static IF_CLOSE = new ServerProt(129, 0); + static IF_OPENSIDEOVERLAY = new ServerProt(167, 3); + static IF_OPENMAINMODAL = new ServerProt(168, 2); + static IF_OPENSIDEMODAL = new ServerProt(195, 2); + static IF_SETCOLOUR = new ServerProt(2, 4); + static IF_SETHIDE = new ServerProt(26, 3); + static IF_SETOBJECT = new ServerProt(46, 6); + static IF_SHOWSIDE = new ServerProt(84, 1); + static IF_SETMODEL = new ServerProt(87, 4); + static IF_SETRECOL = new ServerProt(103, 6); + static IF_SETANIM = new ServerProt(146, 4); + static IF_SETPLAYERHEAD = new ServerProt(197, 2); + static IF_SETTEXT = new ServerProt(201, -2); + static IF_SETNPCHEAD = new ServerProt(204, 4); + static IF_SETPOSITION = new ServerProt(209, 6); + static TUTORIAL_FLASHSIDE = new ServerProt(126, 1); + static TUTORIAL_OPENCHAT = new ServerProt(185, 2); + static UPDATE_INV_STOP_TRANSMIT = new ServerProt(15, 2); + static UPDATE_INV_FULL = new ServerProt(98, -2); + static UPDATE_INV_PARTIAL = new ServerProt(213, -2); + static CAM_LOOKAT = new ServerProt(74, 6); + static CAM_SHAKE = new ServerProt(13, 4); + static CAM_MOVETO = new ServerProt(3, 6); + static CAM_RESET = new ServerProt(239, 0); + static NPC_INFO = new ServerProt(1, -2); + static PLAYER_INFO = new ServerProt(184, -2); + static FINISH_TRACKING = new ServerProt(133, 0); + static ENABLE_TRACKING = new ServerProt(226, 0); + static MESSAGE_GAME = new ServerProt(4, -1); + static UPDATE_IGNORELIST = new ServerProt(21, -2); + static CHAT_FILTER_SETTINGS = new ServerProt(32, 3); + static MESSAGE_PRIVATE = new ServerProt(41, -1); + static UPDATE_FRIENDLIST = new ServerProt(152, 9); + static UNSET_MAP_FLAG = new ServerProt(19, 0); + static UPDATE_RUNWEIGHT = new ServerProt(22, 2); + static HINT_ARROW = new ServerProt(25, 6); + static UPDATE_REBOOT_TIMER = new ServerProt(43, 2); + static UPDATE_STAT = new ServerProt(44, 6); + static UPDATE_RUNENERGY = new ServerProt(68, 1); + static RESET_ANIMS = new ServerProt(136, 0); + static UPDATE_UID192 = new ServerProt(139, 2); + static LAST_LOGIN_INFO = new ServerProt(140, 9); + static LOGOUT = new ServerProt(142, 0); + static P_COUNTDIALOG = new ServerProt(243, 0); + static SET_MULTIWAY = new ServerProt(254, 1); + static DATA_LOC_DONE = new ServerProt(20, 2); + static DATA_LAND_DONE = new ServerProt(80, 2); + static DATA_LAND = new ServerProt(132, -2); + static DATA_LOC = new ServerProt(220, -2); + static REBUILD_NORMAL = new ServerProt(237, -2); + static VARP_SMALL = new ServerProt(150, 3); + static VARP_LARGE = new ServerProt(175, 6); + static RESET_CLIENT_VARCACHE = new ServerProt(193, 0); + static SYNTH_SOUND = new ServerProt(12, 5); + static MIDI_SONG = new ServerProt(54, -1); + static MIDI_JINGLE = new ServerProt(212, -2); + static UPDATE_ZONE_PARTIAL_FOLLOWS = new ServerProt(7, 2); + static UPDATE_ZONE_FULL_FOLLOWS = new ServerProt(135, 2); + static UPDATE_ZONE_PARTIAL_ENCLOSED = new ServerProt(162, -2); + constructor(id, length) { + this.id = id; + this.length = length; + ServerProt.all.push(this); + ServerProt.byId[id] = this; + } +} + +// src/lostcity/entity/Player.ts + +// src/lostcity/entity/MoveSpeed.ts +var MoveSpeed; +(MoveSpeed2 => { + MoveSpeed2[(MoveSpeed2['STATIONARY'] = 0)] = 'STATIONARY'; + MoveSpeed2[(MoveSpeed2['CRAWL'] = 1)] = 'CRAWL'; + MoveSpeed2[(MoveSpeed2['WALK'] = 2)] = 'WALK'; + MoveSpeed2[(MoveSpeed2['RUN'] = 3)] = 'RUN'; + MoveSpeed2[(MoveSpeed2['INSTANT'] = 4)] = 'INSTANT'; +})((MoveSpeed ||= {})); +var MoveSpeed_default = MoveSpeed; + +// src/lostcity/entity/MoveStrategy.ts +var MoveStrategy; +(MoveStrategy2 => { + MoveStrategy2[(MoveStrategy2['SMART'] = 0)] = 'SMART'; + MoveStrategy2[(MoveStrategy2['NAIVE'] = 1)] = 'NAIVE'; + MoveStrategy2[(MoveStrategy2['FLY'] = 2)] = 'FLY'; +})((MoveStrategy ||= {})); +var MoveStrategy_default = MoveStrategy; + +// src/lostcity/entity/PathingEntity.ts +class PathingEntity extends Entity { + moveRestrict; + blockWalk; + moveStrategy; + coordmask; + entitymask; + moveSpeed = MoveSpeed_default.INSTANT; + walkDir = -1; + runDir = -1; + waypointIndex = -1; + waypoints = new Int32Array(25); + lastX = -1; + lastZ = -1; + lastLevel = -1; + tele = false; + jump = false; + lastStepX = -1; + lastStepZ = -1; + stepsTaken = 0; + lastInt = -1; + lastCrawl = false; + walktrigger = -1; + walktriggerArg = 0; + orientation = Direction.SOUTH; + interacted = false; + repathed = false; + target = null; + targetOp = -1; + targetSubject = {type: -1, com: -1}; + targetX = -1; + targetZ = -1; + apRange = 10; + apRangeCalled = false; + alreadyFacedCoord = false; + alreadyFacedEntity = false; + mask = 0; + exactStartX = -1; + exactStartZ = -1; + exactEndX = -1; + exactEndZ = -1; + exactMoveStart = -1; + exactMoveEnd = -1; + exactMoveDirection = -1; + faceX = -1; + faceZ = -1; + faceEntity = -1; + damageTaken = -1; + damageType = -1; + animId = -1; + animDelay = -1; + chat = null; + graphicId = -1; + graphicHeight = -1; + graphicDelay = -1; + constructor(level, x, z2, width, length, lifecycle, moveRestrict, blockWalk, moveStrategy, coordmask, entitymask) { + super(level, x, z2, width, length, lifecycle); + this.moveRestrict = moveRestrict; + this.blockWalk = blockWalk; + this.moveStrategy = moveStrategy; + this.coordmask = coordmask; + this.entitymask = entitymask; + this.lastStepX = x - 1; + this.lastStepZ = z2; + } + processMovement() { + if (!this.hasWaypoints() || this.moveSpeed === MoveSpeed_default.STATIONARY || this.moveSpeed === MoveSpeed_default.INSTANT) { + return false; + } + if (this.moveSpeed === MoveSpeed_default.CRAWL) { + this.lastCrawl = !this.lastCrawl; + if (this.lastCrawl && this.walkDir === -1) { + this.walkDir = this.validateAndAdvanceStep(); + } + return true; + } + if (this.walkDir === -1) { + this.walkDir = this.validateAndAdvanceStep(); + if (this.moveSpeed === MoveSpeed_default.RUN && this.walkDir !== -1 && this.runDir === -1) { + this.runDir = this.validateAndAdvanceStep(); + } + } + return true; + } + refreshZonePresence(previousX, previousZ, previousLevel) { + if (this.x != previousX || this.z !== previousZ || this.level !== previousLevel) { + switch (this.blockWalk) { + case BlockWalk_default.NPC: + World_default.gameMap.changeNpcCollision(this.width, previousX, previousZ, previousLevel, false); + World_default.gameMap.changeNpcCollision(this.width, this.x, this.z, this.level, true); + break; + case BlockWalk_default.ALL: + World_default.gameMap.changeNpcCollision(this.width, previousX, previousZ, previousLevel, false); + World_default.gameMap.changeNpcCollision(this.width, this.x, this.z, this.level, true); + World_default.gameMap.changePlayerCollision(this.width, previousX, previousZ, previousLevel, false); + World_default.gameMap.changePlayerCollision(this.width, this.x, this.z, this.level, true); + break; + } + this.lastStepX = previousX; + this.lastStepZ = previousZ; + } + if (Position.zone(previousX) !== Position.zone(this.x) || Position.zone(previousZ) !== Position.zone(this.z) || previousLevel != this.level) { + World_default.getZone(previousX, previousZ, previousLevel).leave(this); + World_default.getZone(this.x, this.z, this.level).enter(this); + } + } + validateAndAdvanceStep() { + const dir = this.takeStep(); + if (dir === null) { + return -1; + } + if (dir === -1) { + this.waypointIndex--; + if (this.waypointIndex != -1) { + return this.validateAndAdvanceStep(); + } + return -1; + } + const previousX = this.x; + const previousZ = this.z; + this.x = Position.moveX(this.x, dir); + this.z = Position.moveZ(this.z, dir); + this.orientation = dir; + this.stepsTaken++; + this.refreshZonePresence(previousX, previousZ, this.level); + return dir; + } + queueWaypoint(x, z2) { + this.waypoints[0] = Position.packCoord(0, x, z2); + this.waypointIndex = 0; + } + queueWaypoints(waypoints) { + let index = -1; + for (let input = waypoints.length - 1, output = 0; input >= 0 && output < this.waypoints.length; input--, output++) { + this.waypoints[output] = waypoints[input]; + index++; + } + this.waypointIndex = index; + } + clearWaypoints() { + this.waypointIndex = -1; + } + teleJump(x, z2, level) { + this.teleport(x, z2, level); + this.jump = true; + } + teleport(x, z2, level) { + if (isNaN(level)) { + level = 0; + } + level = Math.max(0, Math.min(level, 3)); + const previousX = this.x; + const previousZ = this.z; + const previousLevel = this.level; + this.x = x; + this.z = z2; + this.level = level; + this.refreshZonePresence(previousX, previousZ, previousLevel); + this.lastStepX = this.x - 1; + this.lastStepZ = this.z; + this.moveSpeed = MoveSpeed_default.INSTANT; + if (previousLevel != level) { + this.jump = true; + } + } + validateDistanceWalked() { + const distanceCheck = + Position.distanceTo(this, { + x: this.lastX, + z: this.lastZ, + width: this.width, + length: this.length + }) > 2; + if (distanceCheck) { + this.jump = true; + } + } + convertMovementDir() { + let walkDir = this.walkDir; + let runDir = this.runDir; + let tele = this.moveSpeed === MoveSpeed_default.INSTANT; + const distanceMoved = Position.distanceTo(this, { + x: this.lastX, + z: this.lastZ, + width: this.width, + length: this.length + }); + if (tele && !this.jump && distanceMoved <= 2) { + if (distanceMoved === 2) { + const firstX = ((this.x + this.lastX) / 2) | 0; + const firstZ = ((this.z + this.lastZ) / 2) | 0; + walkDir = Position.face(this.lastX, this.lastZ, firstX, firstZ); + runDir = Position.face(firstX, firstZ, this.x, this.z); + } else { + walkDir = Position.face(this.lastX, this.lastZ, this.x, this.z); + runDir = -1; + } + tele = false; + } + this.walkDir = walkDir; + this.runDir = runDir; + this.tele = tele; + } + hasWaypoints() { + return this.waypointIndex !== -1; + } + isLastOrNoWaypoint() { + return this.waypointIndex <= 0; + } + inOperableDistance(target) { + if (target.level !== this.level) { + return false; + } + if (target instanceof PathingEntity) { + return reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, target.orientation, -2); + } else if (target instanceof Loc) { + const forceapproach = LocType.get(target.type).forceapproach; + return reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, target.angle, target.shape, forceapproach); + } + const reachedAdjacent = reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, 0, -2); + if (isFlagged(target.x, target.z, target.level, CollisionFlag.WALK_BLOCKED)) { + return reachedAdjacent; + } + if (!this.hasWaypoints() && reachedAdjacent) { + return true; + } + return reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, 0, -1); + } + inApproachDistance(range, target) { + if (target.level !== this.level) { + return false; + } + if (target instanceof PathingEntity && Position.intersects(this.x, this.z, this.width, this.length, target.x, target.z, target.width, target.length)) { + return false; + } + return Position.distanceTo(this, target) <= range && hasLineOfSight(this.level, this.x, this.z, target.x, target.z, this.width, this.length, target.width, target.length, CollisionFlag.PLAYER); + } + pathToMoveClick(input, needsfinding) { + if (this.moveStrategy === MoveStrategy_default.SMART) { + if (needsfinding) { + const {x, z: z2} = Position.unpackCoord(input[0]); + this.queueWaypoints(findPath(this.level, this.x, this.z, x, z2)); + } else { + this.queueWaypoints(input); + } + } else { + const {x, z: z2} = Position.unpackCoord(input[input.length - 1]); + this.queueWaypoint(x, z2); + } + } + pathToPathingTarget() { + if (!this.target || !(this.target instanceof PathingEntity)) { + return; + } + if (!this.isLastOrNoWaypoint()) { + return; + } + if (this.targetOp === ServerTriggerType_default.APPLAYER3 || this.targetOp === ServerTriggerType_default.OPPLAYER3) { + this.queueWaypoint(this.target.lastStepX, this.target.lastStepZ); + return; + } + this.pathToTarget(); + } + pathToTarget() { + if (!this.target) { + return; + } + this.targetX = this.target.x; + this.targetZ = this.target.z; + if (this.moveStrategy === MoveStrategy_default.SMART) { + if (this.target instanceof PathingEntity) { + this.queueWaypoints(findPath(this.level, this.x, this.z, this.target.x, this.target.z, this.width, this.target.width, this.target.length, this.target.orientation, -2)); + } else if (this.target instanceof Loc) { + const forceapproach = LocType.get(this.target.type).forceapproach; + this.queueWaypoints(findPath(this.level, this.x, this.z, this.target.x, this.target.z, this.width, this.target.width, this.target.length, this.target.angle, this.target.shape, true, forceapproach)); + } else { + this.queueWaypoints(findPath(this.level, this.x, this.z, this.target.x, this.target.z)); + } + } else if (this.moveStrategy === MoveStrategy_default.NAIVE) { + const collisionStrategy = this.getCollisionStrategy(); + if (collisionStrategy === null) { + return; + } + const extraFlag = this.blockWalkFlag(); + if (extraFlag === CollisionFlag.NULL) { + return; + } + if (this.target instanceof PathingEntity) { + this.queueWaypoints(findNaivePath(this.level, this.x, this.z, this.target.x, this.target.z, this.width, this.length, this.target.width, this.target.length, extraFlag, collisionStrategy)); + } else { + this.queueWaypoint(this.target.x, this.target.z); + } + } else { + const collisionStrategy = this.getCollisionStrategy(); + if (collisionStrategy === null) { + return; + } + const extraFlag = this.blockWalkFlag(); + if (extraFlag === CollisionFlag.NULL) { + return; + } + this.queueWaypoint(this.target.x, this.target.z); + } + } + setInteraction(interaction, target, op, subject) { + this.target = target; + this.targetOp = op; + this.targetSubject = subject ?? {type: -1, com: -1}; + this.targetX = target.x; + this.targetZ = target.z; + this.apRange = 10; + this.apRangeCalled = false; + if (target instanceof Player2) { + const pid = target.pid + 32768; + if (this.faceEntity !== pid) { + this.faceEntity = pid; + this.mask |= this.entitymask; + } + } else if (target instanceof Npc2) { + const nid = target.nid; + if (this.faceEntity !== nid) { + this.faceEntity = nid; + this.mask |= this.entitymask; + } + } else { + const faceX = target.x * 2 + target.width; + const faceZ = target.z * 2 + target.length; + if (this.faceX !== faceX || this.faceZ !== faceZ) { + this.faceX = faceX; + this.faceZ = faceZ; + this.mask |= this.coordmask; + } + } + if (interaction === Interaction_default.SCRIPT) { + this.pathToTarget(); + } + } + clearInteraction() { + this.target = null; + this.targetOp = -1; + this.targetSubject = {type: -1, com: -1}; + this.targetX = -1; + this.targetZ = -1; + this.apRange = 10; + this.apRangeCalled = false; + this.alreadyFacedCoord = true; + this.alreadyFacedEntity = true; + } + getCollisionStrategy() { + if (this.moveRestrict === MoveRestrict_default.NORMAL) { + return CollisionType.NORMAL; + } else if (this.moveRestrict === MoveRestrict_default.BLOCKED) { + return CollisionType.BLOCKED; + } else if (this.moveRestrict === MoveRestrict_default.BLOCKED_NORMAL) { + return CollisionType.LINE_OF_SIGHT; + } else if (this.moveRestrict === MoveRestrict_default.INDOORS) { + return CollisionType.INDOORS; + } else if (this.moveRestrict === MoveRestrict_default.OUTDOORS) { + return CollisionType.OUTDOORS; + } else if (this.moveRestrict === MoveRestrict_default.NOMOVE) { + return null; + } else if (this.moveRestrict === MoveRestrict_default.PASSTHRU) { + return CollisionType.NORMAL; + } + return null; + } + resetPathingEntity() { + this.moveSpeed = this.defaultMoveSpeed(); + this.walkDir = -1; + this.runDir = -1; + this.jump = false; + this.tele = false; + this.lastX = this.x; + this.lastZ = this.z; + this.lastLevel = this.level; + this.stepsTaken = 0; + this.interacted = false; + this.apRangeCalled = false; + this.mask = 0; + this.exactStartX = -1; + this.exactStartZ = -1; + this.exactEndX = -1; + this.exactEndZ = -1; + this.exactMoveStart = -1; + this.exactMoveEnd = -1; + this.exactMoveDirection = -1; + this.animId = -1; + this.animDelay = -1; + this.animId = -1; + this.animDelay = -1; + this.chat = null; + this.damageTaken = -1; + this.damageType = -1; + this.graphicId = -1; + this.graphicHeight = -1; + this.graphicDelay = -1; + if (this.faceX !== -1) { + this.orientation = Position.face(this.x, this.z, this.faceX, this.faceZ); + } else if (this.target) { + this.orientation = Position.face(this.x, this.z, this.target.x, this.target.z); + } + if (this.alreadyFacedCoord && this.faceX !== -1 && !this.hasWaypoints()) { + this.faceX = -1; + this.faceZ = -1; + this.alreadyFacedCoord = false; + } else if (this.alreadyFacedEntity && !this.target && this.faceEntity !== -1) { + this.mask |= this.entitymask; + this.faceEntity = -1; + this.alreadyFacedEntity = false; + } + } + takeStep() { + if (this.waypointIndex === -1) { + return null; + } + const srcX = this.x; + const srcZ = this.z; + const {x, z: z2} = Position.unpackCoord(this.waypoints[this.waypointIndex]); + const dir = Position.face(srcX, srcZ, x, z2); + const dx = Position.deltaX(dir); + const dz = Position.deltaZ(dir); + if (dx == 0 && dz == 0) { + return -1; + } + const collisionStrategy = this.getCollisionStrategy(); + if (collisionStrategy === null) { + return -1; + } + const extraFlag = this.blockWalkFlag(); + if (extraFlag === CollisionFlag.NULL) { + return -1; + } + if (this.moveStrategy === MoveStrategy_default.FLY) { + return dir; + } + if (canTravel(this.level, this.x, this.z, dx, dz, this.width, extraFlag, collisionStrategy)) { + return dir; + } + if (dx != 0 && canTravel(this.level, this.x, this.z, dx, 0, this.width, extraFlag, collisionStrategy)) { + return Position.face(srcX, srcZ, x, srcZ); + } + if (dz != 0 && canTravel(this.level, this.x, this.z, 0, dz, this.width, extraFlag, collisionStrategy)) { + return Position.face(srcX, srcZ, srcX, z2); + } + return null; + } +} + +// src/jagex2/datastruct/Stack.ts +class Stack { + sentinel; + cursor = null; + constructor() { + const head = new Hashable(); + head.nextHashable = head; + head.prevHashable = head; + this.sentinel = head; + } + push(node) { + if (node.prevHashable) { + node.uncache(); + } + node.prevHashable = this.sentinel.prevHashable; + node.nextHashable = this.sentinel; + if (node.prevHashable) { + node.prevHashable.nextHashable = node; + } + node.nextHashable.prevHashable = node; + } + pop() { + const node = this.sentinel.nextHashable; + if (node === this.sentinel) { + return null; + } + node?.uncache(); + return node; + } + head() { + const node = this.sentinel.nextHashable; + if (node === this.sentinel) { + this.cursor = null; + return null; + } + this.cursor = node?.nextHashable || null; + return node; + } + next() { + const node = this.cursor; + if (node === this.sentinel) { + this.cursor = null; + return null; + } + this.cursor = node?.nextHashable || null; + return node; + } +} + +// src/lostcity/server/PreloadedPacks.ts +var {default: fs23} = () => ({}); +function preloadClient() { + const allMaps = fs23.readdirSync('data/pack/client/maps'); + for (let i = 0; i < allMaps.length; i++) { + const name = allMaps[i]; + const map = new Uint8Array(fs23.readFileSync(`data/pack/client/maps/${name}`)); + const crc = Packet.getcrc(map, 0, map.length); + PRELOADED.set(name, map); + PRELOADED_CRC.set(name, crc); + } + const allSongs = fs23.readdirSync('data/pack/client/songs'); + for (let i = 0; i < allSongs.length; i++) { + const name = allSongs[i]; + const song = new Uint8Array(fs23.readFileSync(`data/pack/client/songs/${name}`)); + const crc = Packet.getcrc(song, 0, song.length); + PRELOADED.set(name, song); + PRELOADED_CRC.set(name, crc); + } + const allJingles = fs23.readdirSync('data/pack/client/jingles'); + for (let i = 0; i < allJingles.length; i++) { + const name = allJingles[i]; + const jingle = new Uint8Array(fs23.readFileSync(`data/pack/client/jingles/${name}`).subarray(4)); + const crc = Packet.getcrc(jingle, 0, jingle.length); + PRELOADED.set(name, jingle); + PRELOADED_CRC.set(name, crc); + } +} +async function preloadClientAsync() { + const allMaps = [ + 'l29_75', + 'l30_75', + 'l31_75', + 'l32_70', + 'l32_71', + 'l32_72', + 'l32_73', + 'l32_74', + 'l32_75', + 'l33_70', + 'l33_71', + 'l33_72', + 'l33_73', + 'l33_74', + 'l33_75', + 'l33_76', + 'l34_70', + 'l34_71', + 'l34_72', + 'l34_73', + 'l34_74', + 'l34_75', + 'l34_76', + 'l35_20', + 'l35_75', + 'l35_76', + 'l36_146', + 'l36_147', + 'l36_148', + 'l36_149', + 'l36_150', + 'l36_153', + 'l36_154', + 'l36_52', + 'l36_53', + 'l36_54', + 'l36_72', + 'l36_73', + 'l36_74', + 'l36_75', + 'l36_76', + 'l37_146', + 'l37_147', + 'l37_148', + 'l37_149', + 'l37_150', + 'l37_151', + 'l37_152', + 'l37_153', + 'l37_154', + 'l37_48', + 'l37_49', + 'l37_50', + 'l37_51', + 'l37_52', + 'l37_53', + 'l37_54', + 'l37_55', + 'l37_72', + 'l37_73', + 'l37_74', + 'l37_75', + 'l38_146', + 'l38_147', + 'l38_148', + 'l38_149', + 'l38_150', + 'l38_151', + 'l38_152', + 'l38_153', + 'l38_154', + 'l38_155', + 'l38_45', + 'l38_46', + 'l38_47', + 'l38_48', + 'l38_49', + 'l38_50', + 'l38_51', + 'l38_52', + 'l38_53', + 'l38_54', + 'l38_55', + 'l38_72', + 'l38_73', + 'l38_74', + 'l39_147', + 'l39_148', + 'l39_149', + 'l39_150', + 'l39_151', + 'l39_152', + 'l39_153', + 'l39_154', + 'l39_155', + 'l39_45', + 'l39_46', + 'l39_47', + 'l39_48', + 'l39_49', + 'l39_50', + 'l39_51', + 'l39_52', + 'l39_53', + 'l39_54', + 'l39_55', + 'l39_72', + 'l39_73', + 'l39_74', + 'l39_75', + 'l39_76', + 'l40_147', + 'l40_148', + 'l40_149', + 'l40_150', + 'l40_151', + 'l40_152', + 'l40_153', + 'l40_154', + 'l40_45', + 'l40_46', + 'l40_47', + 'l40_48', + 'l40_49', + 'l40_50', + 'l40_51', + 'l40_52', + 'l40_53', + 'l40_54', + 'l40_55', + 'l40_72', + 'l40_73', + 'l40_74', + 'l40_75', + 'l40_76', + 'l41_146', + 'l41_149', + 'l41_151', + 'l41_152', + 'l41_153', + 'l41_154', + 'l41_45', + 'l41_46', + 'l41_47', + 'l41_48', + 'l41_49', + 'l41_50', + 'l41_51', + 'l41_52', + 'l41_53', + 'l41_54', + 'l41_55', + 'l41_56', + 'l41_72', + 'l41_73', + 'l41_74', + 'l41_75', + 'l42_144', + 'l42_145', + 'l42_146', + 'l42_151', + 'l42_152', + 'l42_153', + 'l42_49', + 'l42_50', + 'l42_51', + 'l42_52', + 'l42_53', + 'l42_54', + 'l42_55', + 'l42_56', + 'l42_72', + 'l42_73', + 'l42_74', + 'l42_75', + 'l43_144', + 'l43_145', + 'l43_146', + 'l43_153', + 'l43_154', + 'l43_45', + 'l43_46', + 'l43_47', + 'l43_48', + 'l43_49', + 'l43_50', + 'l43_51', + 'l43_52', + 'l43_53', + 'l43_54', + 'l43_55', + 'l43_56', + 'l43_72', + 'l43_73', + 'l43_74', + 'l43_75', + 'l44_144', + 'l44_145', + 'l44_146', + 'l44_148', + 'l44_149', + 'l44_150', + 'l44_151', + 'l44_152', + 'l44_153', + 'l44_154', + 'l44_155', + 'l44_45', + 'l44_46', + 'l44_47', + 'l44_48', + 'l44_49', + 'l44_50', + 'l44_51', + 'l44_52', + 'l44_53', + 'l44_54', + 'l44_55', + 'l44_72', + 'l44_73', + 'l44_74', + 'l44_75', + 'l45_145', + 'l45_146', + 'l45_148', + 'l45_150', + 'l45_151', + 'l45_152', + 'l45_153', + 'l45_154', + 'l45_155', + 'l45_45', + 'l45_46', + 'l45_47', + 'l45_48', + 'l45_49', + 'l45_50', + 'l45_51', + 'l45_52', + 'l45_53', + 'l45_54', + 'l45_55', + 'l45_56', + 'l45_57', + 'l45_58', + 'l45_59', + 'l45_60', + 'l45_61', + 'l45_62', + 'l45_73', + 'l45_74', + 'l45_75', + 'l45_76', + 'l46_149', + 'l46_150', + 'l46_152', + 'l46_153', + 'l46_154', + 'l46_161', + 'l46_45', + 'l46_46', + 'l46_47', + 'l46_48', + 'l46_49', + 'l46_50', + 'l46_51', + 'l46_52', + 'l46_53', + 'l46_54', + 'l46_55', + 'l46_56', + 'l46_57', + 'l46_58', + 'l46_59', + 'l46_60', + 'l46_61', + 'l46_62', + 'l46_75', + 'l47_148', + 'l47_149', + 'l47_150', + 'l47_152', + 'l47_153', + 'l47_160', + 'l47_161', + 'l47_47', + 'l47_48', + 'l47_49', + 'l47_50', + 'l47_51', + 'l47_52', + 'l47_53', + 'l47_54', + 'l47_55', + 'l47_56', + 'l47_57', + 'l47_58', + 'l47_59', + 'l47_60', + 'l47_61', + 'l47_62', + 'l47_75', + 'l48_148', + 'l48_149', + 'l48_152', + 'l48_153', + 'l48_154', + 'l48_155', + 'l48_156', + 'l48_47', + 'l48_48', + 'l48_49', + 'l48_50', + 'l48_51', + 'l48_52', + 'l48_53', + 'l48_54', + 'l48_55', + 'l48_56', + 'l48_57', + 'l48_58', + 'l48_59', + 'l48_60', + 'l48_61', + 'l48_62', + 'l49_148', + 'l49_149', + 'l49_153', + 'l49_154', + 'l49_155', + 'l49_156', + 'l49_46', + 'l49_47', + 'l49_48', + 'l49_49', + 'l49_50', + 'l49_51', + 'l49_52', + 'l49_53', + 'l49_54', + 'l49_55', + 'l49_56', + 'l49_57', + 'l49_58', + 'l49_59', + 'l49_60', + 'l49_61', + 'l49_62', + 'l50_149', + 'l50_150', + 'l50_152', + 'l50_153', + 'l50_154', + 'l50_46', + 'l50_47', + 'l50_48', + 'l50_49', + 'l50_50', + 'l50_51', + 'l50_52', + 'l50_53', + 'l50_54', + 'l50_55', + 'l50_56', + 'l50_57', + 'l50_58', + 'l50_59', + 'l50_60', + 'l50_61', + 'l50_62', + 'l51_147', + 'l51_154', + 'l51_46', + 'l51_47', + 'l51_48', + 'l51_49', + 'l51_50', + 'l51_51', + 'l51_52', + 'l51_53', + 'l51_54', + 'l51_55', + 'l51_56', + 'l51_57', + 'l51_58', + 'l51_59', + 'l51_60', + 'l51_61', + 'l51_62', + 'l52_152', + 'l52_153', + 'l52_154', + 'l52_46', + 'l52_47', + 'l52_48', + 'l52_49', + 'l52_50', + 'l52_51', + 'l52_52', + 'l52_53', + 'l52_54', + 'l52_55', + 'l52_56', + 'l52_57', + 'l52_58', + 'l52_59', + 'l52_60', + 'l52_61', + 'l52_62', + 'l53_49', + 'l53_50', + 'l53_51', + 'l53_52', + 'l53_53', + 'm29_75', + 'm30_75', + 'm31_75', + 'm32_70', + 'm32_71', + 'm32_72', + 'm32_73', + 'm32_74', + 'm32_75', + 'm33_70', + 'm33_71', + 'm33_72', + 'm33_73', + 'm33_74', + 'm33_75', + 'm33_76', + 'm34_70', + 'm34_71', + 'm34_72', + 'm34_73', + 'm34_74', + 'm34_75', + 'm34_76', + 'm35_20', + 'm35_75', + 'm35_76', + 'm36_146', + 'm36_147', + 'm36_148', + 'm36_149', + 'm36_150', + 'm36_153', + 'm36_154', + 'm36_52', + 'm36_53', + 'm36_54', + 'm36_72', + 'm36_73', + 'm36_74', + 'm36_75', + 'm36_76', + 'm37_146', + 'm37_147', + 'm37_148', + 'm37_149', + 'm37_150', + 'm37_151', + 'm37_152', + 'm37_153', + 'm37_154', + 'm37_48', + 'm37_49', + 'm37_50', + 'm37_51', + 'm37_52', + 'm37_53', + 'm37_54', + 'm37_55', + 'm37_72', + 'm37_73', + 'm37_74', + 'm37_75', + 'm38_146', + 'm38_147', + 'm38_148', + 'm38_149', + 'm38_150', + 'm38_151', + 'm38_152', + 'm38_153', + 'm38_154', + 'm38_155', + 'm38_45', + 'm38_46', + 'm38_47', + 'm38_48', + 'm38_49', + 'm38_50', + 'm38_51', + 'm38_52', + 'm38_53', + 'm38_54', + 'm38_55', + 'm38_72', + 'm38_73', + 'm38_74', + 'm39_147', + 'm39_148', + 'm39_149', + 'm39_150', + 'm39_151', + 'm39_152', + 'm39_153', + 'm39_154', + 'm39_155', + 'm39_45', + 'm39_46', + 'm39_47', + 'm39_48', + 'm39_49', + 'm39_50', + 'm39_51', + 'm39_52', + 'm39_53', + 'm39_54', + 'm39_55', + 'm39_72', + 'm39_73', + 'm39_74', + 'm39_75', + 'm39_76', + 'm40_147', + 'm40_148', + 'm40_149', + 'm40_150', + 'm40_151', + 'm40_152', + 'm40_153', + 'm40_154', + 'm40_45', + 'm40_46', + 'm40_47', + 'm40_48', + 'm40_49', + 'm40_50', + 'm40_51', + 'm40_52', + 'm40_53', + 'm40_54', + 'm40_55', + 'm40_72', + 'm40_73', + 'm40_74', + 'm40_75', + 'm40_76', + 'm41_146', + 'm41_149', + 'm41_151', + 'm41_152', + 'm41_153', + 'm41_154', + 'm41_45', + 'm41_46', + 'm41_47', + 'm41_48', + 'm41_49', + 'm41_50', + 'm41_51', + 'm41_52', + 'm41_53', + 'm41_54', + 'm41_55', + 'm41_56', + 'm41_72', + 'm41_73', + 'm41_74', + 'm41_75', + 'm42_144', + 'm42_145', + 'm42_146', + 'm42_151', + 'm42_152', + 'm42_153', + 'm42_49', + 'm42_50', + 'm42_51', + 'm42_52', + 'm42_53', + 'm42_54', + 'm42_55', + 'm42_56', + 'm42_72', + 'm42_73', + 'm42_74', + 'm42_75', + 'm43_144', + 'm43_145', + 'm43_146', + 'm43_153', + 'm43_154', + 'm43_45', + 'm43_46', + 'm43_47', + 'm43_48', + 'm43_49', + 'm43_50', + 'm43_51', + 'm43_52', + 'm43_53', + 'm43_54', + 'm43_55', + 'm43_56', + 'm43_72', + 'm43_73', + 'm43_74', + 'm43_75', + 'm44_144', + 'm44_145', + 'm44_146', + 'm44_148', + 'm44_149', + 'm44_150', + 'm44_151', + 'm44_152', + 'm44_153', + 'm44_154', + 'm44_155', + 'm44_45', + 'm44_46', + 'm44_47', + 'm44_48', + 'm44_49', + 'm44_50', + 'm44_51', + 'm44_52', + 'm44_53', + 'm44_54', + 'm44_55', + 'm44_72', + 'm44_73', + 'm44_74', + 'm44_75', + 'm45_145', + 'm45_146', + 'm45_148', + 'm45_150', + 'm45_151', + 'm45_152', + 'm45_153', + 'm45_154', + 'm45_155', + 'm45_45', + 'm45_46', + 'm45_47', + 'm45_48', + 'm45_49', + 'm45_50', + 'm45_51', + 'm45_52', + 'm45_53', + 'm45_54', + 'm45_55', + 'm45_56', + 'm45_57', + 'm45_58', + 'm45_59', + 'm45_60', + 'm45_61', + 'm45_62', + 'm45_73', + 'm45_74', + 'm45_75', + 'm45_76', + 'm46_149', + 'm46_150', + 'm46_152', + 'm46_153', + 'm46_154', + 'm46_161', + 'm46_45', + 'm46_46', + 'm46_47', + 'm46_48', + 'm46_49', + 'm46_50', + 'm46_51', + 'm46_52', + 'm46_53', + 'm46_54', + 'm46_55', + 'm46_56', + 'm46_57', + 'm46_58', + 'm46_59', + 'm46_60', + 'm46_61', + 'm46_62', + 'm46_75', + 'm47_148', + 'm47_149', + 'm47_150', + 'm47_152', + 'm47_153', + 'm47_160', + 'm47_161', + 'm47_47', + 'm47_48', + 'm47_49', + 'm47_50', + 'm47_51', + 'm47_52', + 'm47_53', + 'm47_54', + 'm47_55', + 'm47_56', + 'm47_57', + 'm47_58', + 'm47_59', + 'm47_60', + 'm47_61', + 'm47_62', + 'm47_75', + 'm48_148', + 'm48_149', + 'm48_152', + 'm48_153', + 'm48_154', + 'm48_155', + 'm48_156', + 'm48_47', + 'm48_48', + 'm48_49', + 'm48_50', + 'm48_51', + 'm48_52', + 'm48_53', + 'm48_54', + 'm48_55', + 'm48_56', + 'm48_57', + 'm48_58', + 'm48_59', + 'm48_60', + 'm48_61', + 'm48_62', + 'm49_148', + 'm49_149', + 'm49_153', + 'm49_154', + 'm49_155', + 'm49_156', + 'm49_46', + 'm49_47', + 'm49_48', + 'm49_49', + 'm49_50', + 'm49_51', + 'm49_52', + 'm49_53', + 'm49_54', + 'm49_55', + 'm49_56', + 'm49_57', + 'm49_58', + 'm49_59', + 'm49_60', + 'm49_61', + 'm49_62', + 'm50_149', + 'm50_150', + 'm50_152', + 'm50_153', + 'm50_154', + 'm50_46', + 'm50_47', + 'm50_48', + 'm50_49', + 'm50_50', + 'm50_51', + 'm50_52', + 'm50_53', + 'm50_54', + 'm50_55', + 'm50_56', + 'm50_57', + 'm50_58', + 'm50_59', + 'm50_60', + 'm50_61', + 'm50_62', + 'm51_147', + 'm51_154', + 'm51_46', + 'm51_47', + 'm51_48', + 'm51_49', + 'm51_50', + 'm51_51', + 'm51_52', + 'm51_53', + 'm51_54', + 'm51_55', + 'm51_56', + 'm51_57', + 'm51_58', + 'm51_59', + 'm51_60', + 'm51_61', + 'm51_62', + 'm52_152', + 'm52_153', + 'm52_154', + 'm52_46', + 'm52_47', + 'm52_48', + 'm52_49', + 'm52_50', + 'm52_51', + 'm52_52', + 'm52_53', + 'm52_54', + 'm52_55', + 'm52_56', + 'm52_57', + 'm52_58', + 'm52_59', + 'm52_60', + 'm52_61', + 'm52_62', + 'm53_49', + 'm53_50', + 'm53_51', + 'm53_52', + 'm53_53' + ]; + for (let i = 0; i < allMaps.length; i++) { + const name = allMaps[i]; + const map = new Uint8Array(await (await fetch(`data/pack/client/maps/${name}`)).arrayBuffer()); + const crc = Packet.getcrc(map, 0, map.length); + PRELOADED.set(name, map); + PRELOADED_CRC.set(name, crc); + } + const allSongs = [ + 'adventure.mid', + 'al_kharid.mid', + 'alone.mid', + 'ambience_2.mid', + 'ambience_3.mid', + 'ambience_4.mid', + 'ambient_jungle.mid', + 'arabian.mid', + 'arabian2.mid', + 'arabian3.mid', + 'arabique.mid', + 'army_of_darkness.mid', + 'arrival.mid', + 'attack1.mid', + 'attack2.mid', + 'attack3.mid', + 'attack4.mid', + 'attack5.mid', + 'attack6.mid', + 'attention.mid', + 'autumn_voyage.mid', + 'background2.mid', + 'ballad_of_enchantment.mid', + 'baroque.mid', + 'beyond.mid', + 'big_chords.mid', + 'book_of_spells.mid', + 'camelot.mid', + 'cave_background1.mid', + 'cavern.mid', + 'cellar_song1.mid', + 'chain_of_command.mid', + 'chompy_hunt.mid', + 'close_quarters.mid', + 'crystal_cave.mid', + 'crystal_sword.mid', + 'cursed.mid', + 'dangerous.mid', + 'dark2.mid', + 'deep_wildy.mid', + 'desert_voyage.mid', + 'doorways.mid', + 'dream1.mid', + 'duel_arena.mid', + 'dunjun.mid', + 'egypt.mid', + 'emotion.mid', + 'emperor.mid', + 'escape.mid', + 'expanse.mid', + 'expecting.mid', + 'expedition.mid', + 'fade_test.mid', + 'faerie.mid', + 'fanfare.mid', + 'fanfare2.mid', + 'fanfare3.mid', + 'fishing.mid', + 'flute_salad.mid', + 'forbidden.mid', + 'forever.mid', + 'game_intro_1.mid', + 'gaol.mid', + 'garden.mid', + 'gnome.mid', + 'gnome_king.mid', + 'gnome_theme.mid', + 'gnome_village.mid', + 'gnome_village2.mid', + 'gnomeball.mid', + 'greatness.mid', + 'grumpy.mid', + 'harmony.mid', + 'harmony2.mid', + 'heart_and_mind.mid', + 'high_seas.mid', + 'horizon.mid', + 'iban.mid', + 'ice_melody.mid', + 'in_the_manor.mid', + 'inspiration.mid', + 'intrepid.mid', + 'jolly-r.mid', + 'jungle_island.mid', + 'jungly1.mid', + 'jungly2.mid', + 'jungly3.mid', + 'knightly.mid', + 'landlubber.mid', + 'lasting.mid', + 'legion.mid', + 'lightness.mid', + 'lightwalk.mid', + 'lonesome.mid', + 'long_ago.mid', + 'long_way_home.mid', + 'lullaby.mid', + 'mage_arena.mid', + 'magic_dance.mid', + 'magical_journey.mid', + 'march2.mid', + 'medieval.mid', + 'mellow.mid', + 'miles_away.mid', + 'miracle_dance.mid', + 'monarch_waltz.mid', + 'moody.mid', + 'neverland.mid', + 'newbie_melody.mid', + 'nightfall.mid', + 'nomad.mid', + 'null.mid', + 'organ_music_1.mid', + 'organ_music_2.mid', + 'oriental.mid', + 'overture.mid', + 'parade.mid', + 'quest.mid', + 'regal2.mid', + 'reggae.mid', + 'reggae2.mid', + 'riverside.mid', + 'royale.mid', + 'rune_essence.mid', + 'sad_meadow.mid', + 'scape_cave.mid', + 'scape_main.mid', + 'scape_sad1.mid', + 'scape_soft.mid', + 'scape_wild1.mid', + 'sea_shanty.mid', + 'sea_shanty2.mid', + 'serenade.mid', + 'serene.mid', + 'shine.mid', + 'shining.mid', + 'silence.mid', + 'soundscape.mid', + 'spirit.mid', + 'splendour.mid', + 'spooky2.mid', + 'spooky_jungle.mid', + 'starlight.mid', + 'start.mid', + 'still_night.mid', + 'talking_forest.mid', + 'the_desert.mid', + 'the_shadow.mid', + 'the_tower.mid', + 'theme.mid', + 'tomorrow.mid', + 'trawler.mid', + 'trawler_minor.mid', + 'tree_spirits.mid', + 'tribal.mid', + 'tribal2.mid', + 'tribal_background.mid', + 'trinity.mid', + 'troubled.mid', + 'undercurrent.mid', + 'underground.mid', + 'understanding.mid', + 'unknown_land.mid', + 'upass1.mid', + 'upcoming.mid', + 'venture.mid', + 'venture2.mid', + 'vision.mid', + 'voodoo_cult.mid', + 'voyage.mid', + 'wander.mid', + 'waterfall.mid', + 'wilderness2.mid', + 'wilderness3.mid', + 'wilderness4.mid', + 'witching.mid', + 'wolf_mountain.mid', + 'wonder.mid', + 'wonderous.mid', + 'workshop.mid', + 'yesteryear.mid', + 'zealot.mid' + ]; + for (let i = 0; i < allSongs.length; i++) { + const name = allSongs[i]; + const song = new Uint8Array(await (await fetch(`data/pack/client/songs/${name}`)).arrayBuffer()); + const crc = Packet.getcrc(song, 0, song.length); + PRELOADED.set(name, song); + PRELOADED_CRC.set(name, crc); + } + const allJingles = [ + 'advance agility.mid', + 'advance attack.mid', + 'advance attack2.mid', + 'advance cooking.mid', + 'advance cooking2.mid', + 'advance crafting.mid', + 'advance crafting2.mid', + 'advance defense.mid', + 'advance defense2.mid', + 'advance firemarking.mid', + 'advance firemarking2.mid', + 'advance fishing.mid', + 'advance fishing2.mid', + 'advance fletching.mid', + 'advance fletching2.mid', + 'advance herblaw.mid', + 'advance herblaw2.mid', + 'advance hitpoints.mid', + 'advance hitpoints2.mid', + 'advance magic.mid', + 'advance magic2.mid', + 'advance mining.mid', + 'advance mining2.mid', + 'advance prayer.mid', + 'advance prayer2.mid', + 'advance ranged.mid', + 'advance ranged2.mid', + 'advance runecraft.mid', + 'advance runecraft2.mid', + 'advance smithing.mid', + 'advance smithing2.mid', + 'advance strength.mid', + 'advance strength2.mid', + 'advance thieving.mid', + 'advance thieving2.mid', + 'advance woodcutting.mid', + 'advance woodcutting2.mid', + 'death.mid', + 'death2.mid', + 'dice lose.mid', + 'dice win.mid', + 'duel start.mid', + 'duel win2.mid', + 'quest complete 1.mid', + 'quest complete 2.mid', + 'quest complete 3.mid', + 'sailing journey.mid', + 'treasure hunt win.mid' + ]; + for (let i = 0; i < allJingles.length; i++) { + const name = allJingles[i]; + const jingle = new Uint8Array(await (await fetch(`data/pack/client/jingles/${name}`)).arrayBuffer()).subarray(4); + const crc = Packet.getcrc(jingle, 0, jingle.length); + PRELOADED.set(name, jingle); + PRELOADED_CRC.set(name, crc); + } +} +var PRELOADED = new Map(); +var PRELOADED_CRC = new Map(); + +// src/lostcity/network/outgoing/OutgoingMessage.ts +class OutgoingMessage extends Hashable {} + +// src/lostcity/network/outgoing/prot/ServerProtPriority.ts +class ServerProtPriority { + static LOW = new ServerProtPriority(); + static HIGH = new ServerProtPriority(); +} + +// src/lostcity/network/outgoing/model/IfClose.ts +class IfClose extends OutgoingMessage { + priority = ServerProtPriority.LOW; +} + +// src/lostcity/network/outgoing/model/UpdateUid192.ts +class UpdateUid192 extends OutgoingMessage { + uid; + priority = ServerProtPriority.HIGH; + constructor(uid) { + super(); + this.uid = uid; + } +} + +// src/lostcity/network/outgoing/model/ResetAnims.ts +class ResetAnims extends OutgoingMessage { + priority = ServerProtPriority.HIGH; +} + +// src/lostcity/network/outgoing/model/ResetClientVarCache.ts +class ResetClientVarCache extends OutgoingMessage { + priority = ServerProtPriority.HIGH; +} + +// src/lostcity/network/outgoing/model/TutorialOpenChat.ts +class TutorialOpenChat extends OutgoingMessage { + component; + priority = ServerProtPriority.LOW; + constructor(component) { + super(); + this.component = component; + } +} + +// src/lostcity/network/outgoing/model/UpdateInvStopTransmit.ts +class UpdateInvStopTransmit extends OutgoingMessage { + component; + priority = ServerProtPriority.HIGH; + constructor(component) { + super(); + this.component = component; + } +} + +// src/lostcity/network/outgoing/model/VarpSmall.ts +class VarpSmall extends OutgoingMessage { + varp; + value; + priority = ServerProtPriority.HIGH; + constructor(varp, value) { + super(); + this.varp = varp; + this.value = value; + } +} + +// src/lostcity/network/outgoing/model/VarpLarge.ts +class VarpLarge extends OutgoingMessage { + varp; + value; + priority = ServerProtPriority.HIGH; + constructor(varp, value) { + super(); + this.varp = varp; + this.value = value; + } +} + +// src/lostcity/network/outgoing/model/MidiSong.ts +class MidiSong extends OutgoingMessage { + name; + crc; + length; + priority = ServerProtPriority.LOW; + constructor(name, crc, length) { + super(); + this.name = name; + this.crc = crc; + this.length = length; + } +} + +// src/lostcity/network/outgoing/model/MidiJingle.ts +class MidiJingle extends OutgoingMessage { + delay; + data; + priority = ServerProtPriority.LOW; + constructor(delay, data) { + super(); + this.delay = delay; + this.data = data; + } +} + +// src/lostcity/network/outgoing/model/IfOpenSideOverlay.ts +class IfOpenSideOverlay extends OutgoingMessage { + component; + tab; + priority = ServerProtPriority.LOW; + constructor(component, tab) { + super(); + this.component = component; + this.tab = tab; + } +} + +// src/lostcity/network/outgoing/model/UnsetMapFlag.ts +class UnsetMapFlag extends OutgoingMessage { + priority = ServerProtPriority.HIGH; +} + +// src/lostcity/network/outgoing/model/HintArrow.ts +class HintArrow extends OutgoingMessage { + type; + nid; + pid; + x; + z2; + y3; + priority = ServerProtPriority.LOW; + constructor(type, nid, pid, x, z2, y3) { + super(); + this.type = type; + this.nid = nid; + this.pid = pid; + this.x = x; + this.z = z2; + this.y = y3; + } +} + +// src/lostcity/network/outgoing/model/LastLoginInfo.ts +class LastLoginInfo extends OutgoingMessage { + lastLoginIp; + daysSinceLogin; + daysSinceRecoveryChange; + unreadMessageCount; + priority = ServerProtPriority.LOW; + constructor(lastLoginIp, daysSinceLogin, daysSinceRecoveryChange, unreadMessageCount) { + super(); + this.lastLoginIp = lastLoginIp; + this.daysSinceLogin = daysSinceLogin; + this.daysSinceRecoveryChange = daysSinceRecoveryChange; + this.unreadMessageCount = unreadMessageCount; + } +} + +// src/lostcity/network/outgoing/model/MessageGame.ts +class MessageGame extends OutgoingMessage { + msg; + priority = ServerProtPriority.HIGH; + constructor(msg) { + super(); + this.msg = msg; + } +} + +// src/lostcity/engine/zone/ZoneEventType.ts +var ZoneEventType; +(ZoneEventType2 => { + ZoneEventType2[(ZoneEventType2['ENCLOSED'] = 0)] = 'ENCLOSED'; + ZoneEventType2[(ZoneEventType2['FOLLOWS'] = 1)] = 'FOLLOWS'; +})((ZoneEventType ||= {})); +var ZoneEventType_default = ZoneEventType; + +// src/lostcity/network/outgoing/model/UpdateZonePartialEnclosed.ts +class UpdateZonePartialEnclosed extends OutgoingMessage { + zoneX; + zoneZ; + originX; + originZ; + data; + priority = ServerProtPriority.HIGH; + constructor(zoneX, zoneZ, originX, originZ, data) { + super(); + this.zoneX = zoneX; + this.zoneZ = zoneZ; + this.originX = originX; + this.originZ = originZ; + this.data = data; + } +} + +// src/lostcity/network/outgoing/model/UpdateZoneFullFollows.ts +class UpdateZoneFullFollows extends OutgoingMessage { + zoneX; + zoneZ; + originX; + originZ; + priority = ServerProtPriority.HIGH; + constructor(zoneX, zoneZ, originX, originZ) { + super(); + this.zoneX = zoneX; + this.zoneZ = zoneZ; + this.originX = originX; + this.originZ = originZ; + } +} + +// src/lostcity/network/outgoing/model/UpdateZonePartialFollows.ts +class UpdateZonePartialFollows extends OutgoingMessage { + zoneX; + zoneZ; + originX; + originZ; + priority = ServerProtPriority.HIGH; + constructor(zoneX, zoneZ, originX, originZ) { + super(); + this.zoneX = zoneX; + this.zoneZ = zoneZ; + this.originX = originX; + this.originZ = originZ; + } +} + +// src/lostcity/network/outgoing/ZoneMessage.ts +class ZoneMessage extends OutgoingMessage { + coord; + priority = ServerProtPriority.HIGH; + constructor(coord) { + super(); + this.coord = coord; + } +} + +// src/lostcity/network/outgoing/model/ObjAdd.ts +class ObjAdd extends ZoneMessage { + coord; + obj; + count; + constructor(coord, obj, count) { + super(coord); + this.coord = coord; + this.obj = obj; + this.count = count; + } +} + +// src/lostcity/network/outgoing/model/LocAddChange.ts +class LocAddChange extends ZoneMessage { + coord; + loc; + shape; + angle; + constructor(coord, loc, shape, angle) { + super(coord); + this.coord = coord; + this.loc = loc; + this.shape = shape; + this.angle = angle; + } +} + +// src/lostcity/network/outgoing/model/LocDel.ts +class LocDel extends ZoneMessage { + coord; + shape; + angle; + constructor(coord, shape, angle) { + super(coord); + this.coord = coord; + this.shape = shape; + this.angle = angle; + } +} + +// src/lostcity/network/outgoing/model/MapProjAnim.ts +class MapProjAnim extends ZoneMessage { + srcX; + srcZ; + dstX; + dstZ; + target; + spotanim; + srcHeight; + dstHeight; + startDelay; + endDelay; + peak; + arc; + constructor(srcX, srcZ, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) { + super(Position.packZoneCoord(srcX, srcZ)); + this.srcX = srcX; + this.srcZ = srcZ; + this.dstX = dstX; + this.dstZ = dstZ; + this.target = target; + this.spotanim = spotanim; + this.srcHeight = srcHeight; + this.dstHeight = dstHeight; + this.startDelay = startDelay; + this.endDelay = endDelay; + this.peak = peak; + this.arc = arc; + } +} + +// src/lostcity/network/outgoing/model/MapAnim.ts +class MapAnim extends ZoneMessage { + coord; + spotanim; + height; + delay; + constructor(coord, spotanim, height, delay) { + super(coord); + this.coord = coord; + this.spotanim = spotanim; + this.height = height; + this.delay = delay; + } +} + +// src/lostcity/network/outgoing/model/ObjDel.ts +class ObjDel extends ZoneMessage { + coord; + obj; + constructor(coord, obj) { + super(coord); + this.coord = coord; + this.obj = obj; + } +} + +// src/lostcity/network/outgoing/model/ObjCount.ts +class ObjCount extends ZoneMessage { + coord; + obj; + oldCount; + newCount; + constructor(coord, obj, oldCount, newCount) { + super(coord); + this.coord = coord; + this.obj = obj; + this.oldCount = oldCount; + this.newCount = newCount; + } +} + +// src/lostcity/network/outgoing/model/ObjReveal.ts +class ObjReveal extends ZoneMessage { + coord; + obj; + count; + receiverId; + constructor(coord, obj, count, receiverId) { + super(coord); + this.coord = coord; + this.obj = obj; + this.count = count; + this.receiverId = receiverId; + } +} + +// src/lostcity/network/outgoing/model/LocAnim.ts +class LocAnim extends ZoneMessage { + coord; + shape; + angle; + seq; + constructor(coord, shape, angle, seq) { + super(coord); + this.coord = coord; + this.shape = shape; + this.angle = angle; + this.seq = seq; + } +} + +// src/lostcity/network/outgoing/model/LocMerge.ts +class LocMerge extends ZoneMessage { + srcX; + srcZ; + shape; + angle; + locId; + startCycle; + endCycle; + pid; + east; + south; + west; + north; + constructor(srcX, srcZ, shape, angle, locId, startCycle, endCycle, pid, east, south, west, north) { + super(Position.packZoneCoord(srcX, srcZ)); + this.srcX = srcX; + this.srcZ = srcZ; + this.shape = shape; + this.angle = angle; + this.locId = locId; + this.startCycle = startCycle; + this.endCycle = endCycle; + this.pid = pid; + this.east = east; + this.south = south; + this.west = west; + this.north = north; + } +} + +// src/lostcity/network/outgoing/codec/MessageEncoder.ts +class MessageEncoder { + test(_4) { + return this.prot.length; + } +} + +// src/lostcity/network/225/outgoing/codec/IfOpenChatModalEncoder.ts +class IfOpenChatModalEncoder extends MessageEncoder { + prot = ServerProt.IF_OPENCHATMODAL; + encode(buf, message) { + buf.p2(message.component); + } +} + +// src/lostcity/network/outgoing/model/IfOpenChatModal.ts +class IfOpenChatModal extends OutgoingMessage { + component; + priority = ServerProtPriority.LOW; + constructor(component) { + super(); + this.component = component; + } +} + +// src/lostcity/network/outgoing/model/PlayerInfo.ts +class PlayerInfo extends OutgoingMessage { + buildArea; + level; + x; + z2; + originX; + originZ; + uid; + mask; + tele; + jump2; + walkDir; + runDir; + priority = ServerProtPriority.HIGH; + accumulator = 0; + constructor(buildArea, level, x, z2, originX, originZ, uid, mask, tele, jump2, walkDir, runDir) { + super(); + this.buildArea = buildArea; + this.level = level; + this.x = x; + this.z = z2; + this.originX = originX; + this.originZ = originZ; + this.uid = uid; + this.mask = mask; + this.tele = tele; + this.jump = jump2; + this.walkDir = walkDir; + this.runDir = runDir; + } +} + +// src/lostcity/network/225/outgoing/codec/PlayerInfoEncoder.ts +class PlayerInfoEncoder extends MessageEncoder { + static BITS_NEW = 11 + 5 + 5 + 1 + 1; + static BITS_RUN = 1 + 2 + 3 + 3 + 1 + 1; + static BITS_WALK = 1 + 2 + 3 + 1 + 1; + static BITS_EXTENDED = 1 + 2; + static BYTES_LIMIT = 4997; + prot = ServerProt.PLAYER_INFO; + encode(buf, message) { + const buildArea = message.buildArea; + buildArea.resize(); + this.writeLocalPlayer(buf, message); + this.writePlayers(buf, message); + this.writeNewPlayers(buf, message); + const extended = buildArea.extendedInfo; + if (extended.size > 0) { + for (const info of extended) { + const other = World_default.getPlayerByUid(info.id); + if (!other) { + buf.p1(0); + continue; + } + this.writeExtendedInfo(other, message, buf, info.id === message.uid, info.added); + } + } + buildArea.clearExtended(); + } + test(_4) { + return PlayerInfoEncoder.BYTES_LIMIT; + } + writeLocalPlayer(buf, message) { + const {buildArea, uid, level, x, z: z2, mask, tele, jump: jump2, walkDir, runDir} = message; + const player = World_default.getPlayerByUid(uid); + if (!player) { + return; + } + const extendedInfo = mask > 0; + buf.bits(); + buf.pBit(1, tele || runDir !== -1 || walkDir !== -1 || extendedInfo ? 1 : 0); + if (tele) { + buf.pBit(2, 3); + buf.pBit(2, level); + buf.pBit(7, Position.local(x, player.originX)); + buf.pBit(7, Position.local(z2, player.originZ)); + buf.pBit(1, jump2 ? 1 : 0); + buf.pBit(1, extendedInfo ? 1 : 0); + } else if (runDir !== -1) { + buf.pBit(2, 2); + buf.pBit(3, walkDir); + buf.pBit(3, runDir); + buf.pBit(1, extendedInfo ? 1 : 0); + } else if (walkDir !== -1) { + buf.pBit(2, 1); + buf.pBit(3, walkDir); + buf.pBit(1, extendedInfo ? 1 : 0); + } else if (extendedInfo) { + buf.pBit(2, 0); + } + if (extendedInfo) { + buildArea.extendedInfo.add({id: uid, added: false}); + message.accumulator += this.calculateExtendedInfo(player, message, true, true); + } + } + writePlayers(buf, message) { + const buildArea = message.buildArea; + buf.pBit(8, buildArea.players.size); + for (const uid of buildArea.players) { + const other = World_default.getPlayerByUid(uid); + if (!other || other.tele || other.level !== message.level || !Position.isWithinDistanceSW(message, other, buildArea.viewDistance) || !other.checkLifeCycle(World_default.currentTick)) { + buf.pBit(1, 1); + buf.pBit(2, 3); + buildArea.players.delete(uid); + continue; + } + let extendedInfo = other.mask > 0; + const {walkDir, runDir} = other; + let bits = 0; + if (runDir !== -1) { + bits = PlayerInfoEncoder.BITS_RUN; + } else if (walkDir !== -1) { + bits = PlayerInfoEncoder.BITS_WALK; + } else if (extendedInfo) { + bits = PlayerInfoEncoder.BITS_EXTENDED; + } + const updateSize = extendedInfo ? this.calculateExtendedInfo(other, message, false, false) : 0; + if (((buf.bitPos + bits) >>> 3) + (message.accumulator += updateSize) > this.test(message)) { + extendedInfo = false; + } + buf.pBit(1, runDir !== -1 || walkDir !== -1 || extendedInfo ? 1 : 0); + if (runDir !== -1) { + buf.pBit(2, 2); + buf.pBit(3, walkDir); + buf.pBit(3, runDir); + buf.pBit(1, extendedInfo ? 1 : 0); + } else if (walkDir !== -1) { + buf.pBit(2, 1); + buf.pBit(3, walkDir); + buf.pBit(1, extendedInfo ? 1 : 0); + } else if (extendedInfo) { + buf.pBit(2, 0); + } + if (extendedInfo) { + buildArea.extendedInfo.add({id: uid, added: false}); + } + } + } + writeNewPlayers(buf, message) { + const buildArea = message.buildArea; + for (const other of buildArea.getNearbyPlayers(message.uid, message.x, message.z, message.originX, message.originZ)) { + const extendedInfo = !buildArea.hasAppearance(other.pid, other.lastAppearance); + const updateSize = extendedInfo ? this.calculateExtendedInfo(other, message, false, true) : 0; + if (((buf.bitPos + PlayerInfoEncoder.BITS_NEW + 11) >>> 3) + (message.accumulator += updateSize) > this.test(message)) { + break; + } + buf.pBit(11, other.pid); + buf.pBit(5, other.x - message.x); + buf.pBit(5, other.z - message.z); + buf.pBit(1, other.jump ? 1 : 0); + buf.pBit(1, extendedInfo ? 1 : 0); + if (extendedInfo) { + buildArea.extendedInfo.add({id: other.uid, added: true}); + } + buildArea.players.add(other.uid); + } + if (buildArea.extendedInfo.size > 0) { + buf.pBit(11, 2047); + } + buf.bytes(); + } + writeExtendedInfo(player, message, buf, self2 = false, newlyObserved = false) { + let mask = player.mask; + if (newlyObserved) { + mask |= Player2.APPEARANCE; + } + if (newlyObserved && (player.orientation !== -1 || player.faceX !== -1 || player.faceZ !== -1)) { + mask |= Player2.FACE_COORD; + } + if (newlyObserved && player.faceEntity !== -1) { + mask |= Player2.FACE_ENTITY; + } + if (mask > 255) { + mask |= Player2.BIG_UPDATE; + } + if (self2 && mask & Player2.CHAT) { + mask &= ~Player2.CHAT; + } + if (message.buildArea.hasAppearance(player.pid, player.lastAppearance)) { + mask &= ~Player2.APPEARANCE; + } + buf.p1(mask & 255); + if (mask & Player2.BIG_UPDATE) { + buf.p1(mask >> 8); + } + if (mask & Player2.APPEARANCE) { + buf.p1(player.appearance.length); + buf.pdata(player.appearance, 0, player.appearance.length); + message.buildArea.saveAppearance(player.pid, player.lastAppearance); + } + if (mask & Player2.ANIM) { + buf.p2(player.animId); + buf.p1(player.animDelay); + } + if (mask & Player2.FACE_ENTITY) { + if (player.faceEntity !== -1) { + player.alreadyFacedEntity = true; + } + buf.p2(player.faceEntity); + } + if (mask & Player2.SAY) { + buf.pjstr(player.chat ?? ''); + } + if (mask & Player2.DAMAGE) { + buf.p1(player.damageTaken); + buf.p1(player.damageType); + buf.p1(player.levels[PlayerStat_default.HITPOINTS]); + buf.p1(player.baseLevels[PlayerStat_default.HITPOINTS]); + } + if (mask & Player2.FACE_COORD) { + if (player.faceX !== -1) { + player.alreadyFacedCoord = true; + } + if (newlyObserved && player.faceX !== -1) { + buf.p2(player.faceX); + buf.p2(player.faceZ); + } else if (newlyObserved && player.orientation !== -1) { + const faceX = Position.moveX(player.x, player.orientation); + const faceZ = Position.moveZ(player.z, player.orientation); + buf.p2(faceX * 2 + 1); + buf.p2(faceZ * 2 + 1); + } else { + buf.p2(player.faceX); + buf.p2(player.faceZ); + } + } + if (mask & Player2.CHAT) { + buf.p1(player.messageColor); + buf.p1(player.messageEffect); + buf.p1(player.messageType); + buf.p1(player.message.length); + buf.pdata(player.message, 0, player.message.length); + } + if (mask & Player2.SPOTANIM) { + buf.p2(player.graphicId); + buf.p2(player.graphicHeight); + buf.p2(player.graphicDelay); + } + if (mask & Player2.EXACT_MOVE) { + buf.p1(player.exactStartX - Position.zoneOrigin(message.originX)); + buf.p1(player.exactStartZ - Position.zoneOrigin(message.originZ)); + buf.p1(player.exactEndX - Position.zoneOrigin(message.originX)); + buf.p1(player.exactEndZ - Position.zoneOrigin(message.originZ)); + buf.p2(player.exactMoveStart); + buf.p2(player.exactMoveEnd); + buf.p1(player.exactMoveDirection); + } + } + calculateExtendedInfo(player, message, self2 = false, newlyObserved = false) { + let length = 0; + let mask = player.mask; + if (newlyObserved) { + mask |= Player2.APPEARANCE; + } + if (newlyObserved && (player.orientation !== -1 || player.faceX !== -1 || player.faceZ !== -1)) { + mask |= Player2.FACE_COORD; + } + if (newlyObserved && player.faceEntity !== -1) { + mask |= Player2.FACE_ENTITY; + } + if (mask > 255) { + mask |= Player2.BIG_UPDATE; + } + if (self2 && mask & Player2.CHAT) { + mask &= ~Player2.CHAT; + } + if (message.buildArea.hasAppearance(player.pid, player.lastAppearance)) { + mask &= ~Player2.APPEARANCE; + } + length += 1; + if (mask & Player2.BIG_UPDATE) { + length += 1; + } + if (mask & Player2.APPEARANCE) { + length += 1; + length += player.appearance?.length ?? 0; + } + if (mask & Player2.ANIM) { + length += 3; + } + if (mask & Player2.FACE_ENTITY) { + length += 2; + } + if (mask & Player2.SAY) { + length += (player.chat?.length ?? 0) + 1; + } + if (mask & Player2.DAMAGE) { + length += 4; + } + if (mask & Player2.FACE_COORD) { + length += 4; + } + if (mask & Player2.CHAT) { + length += 4; + length += player.message?.length ?? 0; + } + if (mask & Player2.SPOTANIM) { + length += 6; + } + if (mask & Player2.EXACT_MOVE) { + length += 9; + } + return length; + } +} + +// src/lostcity/network/outgoing/model/RebuildNormal.ts +class RebuildNormal extends OutgoingMessage { + zoneX; + zoneZ; + priority = ServerProtPriority.HIGH; + constructor(zoneX, zoneZ) { + super(); + this.zoneX = zoneX; + this.zoneZ = zoneZ; + } + get mapsquares() { + const minX = this.zoneX - 6; + const maxX = this.zoneX + 6; + const minZ = this.zoneZ - 6; + const maxZ = this.zoneZ + 6; + const result = new Set(); + for (let x = minX; x <= maxX; x++) { + const mx = Position.mapsquare(x << 3); + for (let z2 = minZ; z2 <= maxZ; z2++) { + const mz = Position.mapsquare(z2 << 3); + result.add((mx << 8) | mz); + } + } + return result; + } +} + +// src/lostcity/network/225/outgoing/codec/RebuildNormalEncoder.ts +class RebuildNormalEncoder extends MessageEncoder { + prot = ServerProt.REBUILD_NORMAL; + encode(buf, message) { + buf.p2(message.zoneX); + buf.p2(message.zoneZ); + for (const packed of message.mapsquares) { + const x = packed >> 8; + const z2 = packed & 255; + buf.p1(x); + buf.p1(z2); + buf.p4(PRELOADED_CRC.get(`m${x}_${z2}`) ?? 0); + buf.p4(PRELOADED_CRC.get(`l${x}_${z2}`) ?? 0); + } + } + test(message) { + return 2 + 2 + message.mapsquares.size * (1 + 1 + 4 + 4); + } +} + +// src/lostcity/network/outgoing/model/DataLand.ts +class DataLand extends OutgoingMessage { + x; + z2; + offset; + length; + data; + priority = ServerProtPriority.HIGH; + constructor(x, z2, offset, length, data) { + super(); + this.x = x; + this.z = z2; + this.offset = offset; + this.length = length; + this.data = data; + } +} + +// src/lostcity/network/225/outgoing/codec/DataLandEncoder.ts +class DataLandEncoder extends MessageEncoder { + prot = ServerProt.DATA_LAND; + encode(buf, message) { + buf.p1(message.x); + buf.p1(message.z); + buf.p2(message.offset); + buf.p2(message.length); + buf.pdata(message.data, 0, message.data.length); + } + test(message) { + return 1 + 1 + 2 + 2 + message.data.length; + } +} + +// src/lostcity/network/outgoing/model/DataLandDone.ts +class DataLandDone extends OutgoingMessage { + x; + z2; + priority = ServerProtPriority.HIGH; + constructor(x, z2) { + super(); + this.x = x; + this.z = z2; + } +} + +// src/lostcity/network/225/outgoing/codec/DataLandDoneEncoder.ts +class DataLandDoneEncoder extends MessageEncoder { + prot = ServerProt.DATA_LAND_DONE; + encode(buf, message) { + buf.p1(message.x); + buf.p1(message.z); + } +} + +// src/lostcity/network/outgoing/model/DataLoc.ts +class DataLoc extends OutgoingMessage { + x; + z2; + offset; + length; + data; + priority = ServerProtPriority.HIGH; + constructor(x, z2, offset, length, data) { + super(); + this.x = x; + this.z = z2; + this.offset = offset; + this.length = length; + this.data = data; + } +} + +// src/lostcity/network/225/outgoing/codec/DataLocEncoder.ts +class DataLocEncoder extends MessageEncoder { + prot = ServerProt.DATA_LOC; + encode(buf, message) { + buf.p1(message.x); + buf.p1(message.z); + buf.p2(message.offset); + buf.p2(message.length); + buf.pdata(message.data, 0, message.data.length); + } + test(message) { + return 1 + 1 + 2 + 2 + message.data.length; + } +} + +// src/lostcity/network/outgoing/model/DataLocDone.ts +class DataLocDone extends OutgoingMessage { + x; + z2; + priority = ServerProtPriority.HIGH; + constructor(x, z2) { + super(); + this.x = x; + this.z = z2; + } +} + +// src/lostcity/network/225/outgoing/codec/DataLocDoneEncoder.ts +class DataLocDoneEncoder extends MessageEncoder { + prot = ServerProt.DATA_LOC_DONE; + encode(buf, message) { + buf.p1(message.x); + buf.p1(message.z); + } +} + +// src/lostcity/network/outgoing/model/CamLookAt.ts +class CamLookAt extends OutgoingMessage { + x; + z2; + height; + speed; + multiplier; + priority = ServerProtPriority.LOW; + constructor(x, z2, height, speed, multiplier) { + super(); + this.x = x; + this.z = z2; + this.height = height; + this.speed = speed; + this.multiplier = multiplier; + } +} + +// src/lostcity/network/225/outgoing/codec/CamLookAtEncoder.ts +class CamLookAtEncoder extends MessageEncoder { + prot = ServerProt.CAM_LOOKAT; + encode(buf, message) { + buf.p1(message.x); + buf.p1(message.z); + buf.p2(message.height); + buf.p1(message.speed); + buf.p1(message.multiplier); + } +} + +// src/lostcity/network/outgoing/model/CamMoveTo.ts +class CamMoveTo extends OutgoingMessage { + x; + z2; + height; + speed; + multiplier; + priority = ServerProtPriority.LOW; + constructor(x, z2, height, speed, multiplier) { + super(); + this.x = x; + this.z = z2; + this.height = height; + this.speed = speed; + this.multiplier = multiplier; + } +} + +// src/lostcity/network/225/outgoing/codec/CamMoveToEncoder.ts +class CamMoveToEncoder extends MessageEncoder { + prot = ServerProt.CAM_MOVETO; + encode(buf, message) { + buf.p1(message.x); + buf.p1(message.z); + buf.p2(message.height); + buf.p1(message.speed); + buf.p1(message.multiplier); + } +} + +// src/lostcity/network/outgoing/model/CamReset.ts +class CamReset extends OutgoingMessage { + priority = ServerProtPriority.LOW; +} + +// src/lostcity/network/225/outgoing/codec/CamResetEncoder.ts +class CamResetEncoder extends MessageEncoder { + prot = ServerProt.CAM_RESET; + encode(_4, __) {} +} + +// src/lostcity/network/outgoing/model/CamShake.ts +class CamShake extends OutgoingMessage { + type; + jitter; + amplitude; + frequency; + priority = ServerProtPriority.LOW; + constructor(type, jitter, amplitude, frequency) { + super(); + this.type = type; + this.jitter = jitter; + this.amplitude = amplitude; + this.frequency = frequency; + } +} + +// src/lostcity/network/225/outgoing/codec/CamShakeEncoder.ts +class CamShakeEncoder extends MessageEncoder { + prot = ServerProt.CAM_SHAKE; + encode(buf, message) { + buf.p1(message.type); + buf.p1(message.jitter); + buf.p1(message.amplitude); + buf.p1(message.frequency); + } +} + +// src/lostcity/network/outgoing/model/ChatFilterSettings.ts +class ChatFilterSettings extends OutgoingMessage { + publicChat; + privateChat; + tradeDuel; + priority = ServerProtPriority.HIGH; + constructor(publicChat, privateChat, tradeDuel) { + super(); + this.publicChat = publicChat; + this.privateChat = privateChat; + this.tradeDuel = tradeDuel; + } +} + +// src/lostcity/network/225/outgoing/codec/ChatFilterSettingsEncoder.ts +class ChatFilterSettingsEncoder extends MessageEncoder { + prot = ServerProt.CHAT_FILTER_SETTINGS; + encode(buf, message) { + buf.p1(message.publicChat); + buf.p1(message.privateChat); + buf.p1(message.tradeDuel); + } +} + +// src/lostcity/network/outgoing/model/EnableTracking.ts +class EnableTracking extends OutgoingMessage { + priority = ServerProtPriority.LOW; +} + +// src/lostcity/network/225/outgoing/codec/EnableTrackingEncoder.ts +class EnableTrackingEncoder extends MessageEncoder { + prot = ServerProt.ENABLE_TRACKING; + encode(_4, __) {} +} + +// src/lostcity/network/outgoing/model/FinishTracking.ts +class FinishTracking extends OutgoingMessage { + priority = ServerProtPriority.LOW; +} + +// src/lostcity/network/225/outgoing/codec/FinishTrackingEncoder.ts +class FinishTrackingEncoder extends MessageEncoder { + prot = ServerProt.FINISH_TRACKING; + encode(_4, __) {} +} + +// src/lostcity/network/225/outgoing/codec/HintArrowEncoder.ts +class HintArrowEncoder extends MessageEncoder { + prot = ServerProt.HINT_ARROW; + encode(buf, message) { + const {type, nid, pid, x, z: z2, y: y3} = message; + if (type === 1) { + buf.p1(type); + buf.p2(nid); + buf.p2(0); + buf.p1(0); + } else if (type >= 2 && type <= 6) { + buf.p1(type); + buf.p2(x); + buf.p2(z2); + buf.p1(y3); + } else if (type === 10) { + buf.p1(type); + buf.p2(pid); + buf.p2(0); + buf.p1(0); + } else if (type === -1) { + buf.p1(-1); + buf.p2(0); + buf.p2(0); + buf.p1(0); + } + } +} + +// src/lostcity/network/225/outgoing/codec/IfCloseEncoder.ts +class IfCloseEncoder extends MessageEncoder { + prot = ServerProt.IF_CLOSE; + encode(_4, __) {} +} + +// src/lostcity/network/outgoing/model/IfOpenMainModal.ts +class IfOpenMainModal extends OutgoingMessage { + component; + priority = ServerProtPriority.LOW; + constructor(component) { + super(); + this.component = component; + } +} + +// src/lostcity/network/225/outgoing/codec/IfOpenMainModalEncoder.ts +class IfOpenMainModalEncoder extends MessageEncoder { + prot = ServerProt.IF_OPENMAINMODAL; + encode(buf, message) { + buf.p2(message.component); + } +} + +// src/lostcity/network/outgoing/model/IfOpenMainSideModal.ts +class IfOpenMainSideModal extends OutgoingMessage { + main; + side; + priority = ServerProtPriority.LOW; + constructor(main, side) { + super(); + this.main = main; + this.side = side; + } +} + +// src/lostcity/network/225/outgoing/codec/IfOpenMainSideModalEncoder.ts +class IfOpenMainSideModalEncoder extends MessageEncoder { + prot = ServerProt.IF_OPENMAINSIDEMODAL; + encode(buf, message) { + buf.p2(message.main); + buf.p2(message.side); + } +} + +// src/lostcity/network/outgoing/model/IfOpenSideModal.ts +class IfOpenSideModal extends OutgoingMessage { + component; + priority = ServerProtPriority.LOW; + constructor(component) { + super(); + this.component = component; + } +} + +// src/lostcity/network/225/outgoing/codec/IfOpenSideModalEncoder.ts +class IfOpenSideModalEncoder extends MessageEncoder { + prot = ServerProt.IF_OPENSIDEMODAL; + encode(buf, message) { + buf.p2(message.component); + } +} + +// src/lostcity/network/225/outgoing/codec/IfOpenSideOverlayEncoder.ts +class IfOpenSideOverlayEncoder extends MessageEncoder { + prot = ServerProt.IF_OPENSIDEOVERLAY; + encode(buf, message) { + buf.p2(message.component); + buf.p1(message.tab); + } +} + +// src/lostcity/network/outgoing/model/IfSetAnim.ts +class IfSetAnim extends OutgoingMessage { + component; + seq; + priority = ServerProtPriority.LOW; + constructor(component, seq) { + super(); + this.component = component; + this.seq = seq; + } +} + +// src/lostcity/network/225/outgoing/codec/IfSetAnimEncoder.ts +class IfSetAnimEncoder extends MessageEncoder { + prot = ServerProt.IF_SETANIM; + encode(buf, message) { + buf.p2(message.component); + buf.p2(message.seq); + } +} + +// src/lostcity/network/outgoing/model/IfSetColour.ts +class IfSetColour extends OutgoingMessage { + component; + colour; + priority = ServerProtPriority.LOW; + constructor(component, colour) { + super(); + this.component = component; + this.colour = colour; + } +} + +// src/lostcity/network/225/outgoing/codec/IfSetColourEncoder.ts +class IfSetColourEncoder extends MessageEncoder { + prot = ServerProt.IF_SETCOLOUR; + encode(buf, message) { + buf.p2(message.component); + buf.p2(message.colour); + } +} + +// src/lostcity/network/outgoing/model/IfSetHide.ts +class IfSetHide extends OutgoingMessage { + component; + hidden; + priority = ServerProtPriority.LOW; + constructor(component, hidden) { + super(); + this.component = component; + this.hidden = hidden; + } +} + +// src/lostcity/network/225/outgoing/codec/IfSetHideEncoder.ts +class IfSetHideEncoder extends MessageEncoder { + prot = ServerProt.IF_SETHIDE; + encode(buf, message) { + buf.p2(message.component); + buf.pbool(message.hidden); + } +} + +// src/lostcity/network/outgoing/model/IfSetModel.ts +class IfSetModel extends OutgoingMessage { + component; + model; + priority = ServerProtPriority.LOW; + constructor(component, model) { + super(); + this.component = component; + this.model = model; + } +} + +// src/lostcity/network/225/outgoing/codec/IfSetModelEncoder.ts +class IfSetModelEncoder extends MessageEncoder { + prot = ServerProt.IF_SETMODEL; + encode(buf, message) { + buf.p2(message.component); + buf.p2(message.model); + } +} + +// src/lostcity/network/outgoing/model/IfSetNpcHead.ts +class IfSetNpcHead extends OutgoingMessage { + component; + npc; + priority = ServerProtPriority.LOW; + constructor(component, npc) { + super(); + this.component = component; + this.npc = npc; + } +} + +// src/lostcity/network/225/outgoing/codec/IfSetNpcHeadEncoder.ts +class IfSetNpcHeadEncoder extends MessageEncoder { + prot = ServerProt.IF_SETNPCHEAD; + encode(buf, message) { + buf.p2(message.component); + buf.p2(message.npc); + } +} + +// src/lostcity/network/outgoing/model/IfSetObject.ts +class IfSetObject extends OutgoingMessage { + component; + obj; + scale; + priority = ServerProtPriority.LOW; + constructor(component, obj, scale) { + super(); + this.component = component; + this.obj = obj; + this.scale = scale; + } +} + +// src/lostcity/network/225/outgoing/codec/IfSetObjectEncoder.ts +class IfSetObjectEncoder extends MessageEncoder { + prot = ServerProt.IF_SETOBJECT; + encode(buf, message) { + buf.p2(message.component); + buf.p2(message.obj); + buf.p2(message.scale); + } +} + +// src/lostcity/network/outgoing/model/IfSetPlayerHead.ts +class IfSetPlayerHead extends OutgoingMessage { + component; + priority = ServerProtPriority.LOW; + constructor(component) { + super(); + this.component = component; + } +} + +// src/lostcity/network/225/outgoing/codec/IfSetPlayerHeadEncoder.ts +class IfSetPlayerHeadEncoder extends MessageEncoder { + prot = ServerProt.IF_SETPLAYERHEAD; + encode(buf, message) { + buf.p2(message.component); + } +} + +// src/lostcity/network/outgoing/model/IfSetPosition.ts +class IfSetPosition extends OutgoingMessage { + component; + x; + y3; + priority = ServerProtPriority.LOW; + constructor(component, x, y3) { + super(); + this.component = component; + this.x = x; + this.y = y3; + } +} + +// src/lostcity/network/225/outgoing/codec/IfSetPositionEncoder.ts +class IfSetPositionEncoder extends MessageEncoder { + prot = ServerProt.IF_SETPOSITION; + encode(buf, message) { + buf.p2(message.component); + buf.p2(message.x); + buf.p2(message.y); + } +} + +// src/lostcity/network/outgoing/model/IfSetRecol.ts +class IfSetRecol extends OutgoingMessage { + component; + src; + dst; + priority = ServerProtPriority.LOW; + constructor(component, src, dst) { + super(); + this.component = component; + this.src = src; + this.dst = dst; + } +} + +// src/lostcity/network/225/outgoing/codec/IfSetRecolEncoder.ts +class IfSetRecolEncoder extends MessageEncoder { + prot = ServerProt.IF_SETRECOL; + encode(buf, message) { + buf.p2(message.component); + buf.p2(message.src); + buf.p2(message.dst); + } +} + +// src/lostcity/network/outgoing/model/IfSetText.ts +class IfSetText extends OutgoingMessage { + component; + text; + priority = ServerProtPriority.LOW; + constructor(component, text) { + super(); + this.component = component; + this.text = text; + } +} + +// src/lostcity/network/225/outgoing/codec/IfSetTextEncoder.ts +class IfSetTextEncoder extends MessageEncoder { + prot = ServerProt.IF_SETTEXT; + encode(buf, message) { + buf.p2(message.component); + buf.pjstr(message.text); + } + test(message) { + return 2 + 1 + message.text.length; + } +} + +// src/lostcity/network/outgoing/model/IfShowSide.ts +class IfShowSide extends OutgoingMessage { + tab; + priority = ServerProtPriority.LOW; + constructor(tab) { + super(); + this.tab = tab; + } +} + +// src/lostcity/network/225/outgoing/codec/IfShowSideEncoder.ts +class IfShowSideEncoder extends MessageEncoder { + prot = ServerProt.IF_SHOWSIDE; + encode(buf, message) { + buf.p1(message.tab); + } +} + +// src/lostcity/network/225/outgoing/codec/LastLoginInfoEncoder.ts +class LastLoginInfoEncoder extends MessageEncoder { + prot = ServerProt.LAST_LOGIN_INFO; + encode(buf, message) { + buf.p4(message.lastLoginIp); + buf.p2(message.daysSinceLogin); + buf.p1(message.daysSinceRecoveryChange); + buf.p2(message.unreadMessageCount); + } +} + +// src/lostcity/network/225/outgoing/prot/ZoneProt.ts +class ZoneProt extends ServerProt { + static LOC_MERGE = new ZoneProt(23, 14); + static LOC_ANIM = new ZoneProt(42, 4); + static OBJ_DEL = new ZoneProt(49, 3); + static OBJ_REVEAL = new ZoneProt(50, 7); + static LOC_ADD_CHANGE = new ZoneProt(59, 4); + static MAP_PROJANIM = new ZoneProt(69, 15); + static LOC_DEL = new ZoneProt(76, 2); + static OBJ_COUNT = new ZoneProt(151, 7); + static MAP_ANIM = new ZoneProt(191, 6); + static OBJ_ADD = new ZoneProt(223, 5); +} + +// src/lostcity/network/outgoing/codec/ZoneMessageEncoder.ts +class ZoneMessageEncoder extends MessageEncoder { + enclose(message) { + const buf = new Packet(new Uint8Array(1 + this.prot.length)); + buf.p1(this.prot.id); + this.encode(buf, message); + return buf.data; + } +} + +// src/lostcity/network/225/outgoing/codec/LocAddChangeEncoder.ts +class LocAddChangeEncoder extends ZoneMessageEncoder { + prot = ZoneProt.LOC_ADD_CHANGE; + encode(buf, message) { + buf.p1(message.coord); + buf.p1((message.shape << 2) | (message.angle & 3)); + buf.p2(message.loc); + } +} + +// src/lostcity/network/225/outgoing/codec/LocAnimEncoder.ts +class LocAnimEncoder extends ZoneMessageEncoder { + prot = ZoneProt.LOC_ANIM; + encode(buf, message) { + buf.p1(message.coord); + buf.p1((message.shape << 2) | (message.angle & 3)); + buf.p2(message.seq); + } +} + +// src/lostcity/network/225/outgoing/codec/LocDelEncoder.ts +class LocDelEncoder extends ZoneMessageEncoder { + prot = ZoneProt.LOC_DEL; + encode(buf, message) { + buf.p1(message.coord); + buf.p1((message.shape << 2) | (message.angle & 3)); + } +} + +// src/lostcity/network/225/outgoing/codec/LocMergeEncoder.ts +class LocMergeEncoder extends ZoneMessageEncoder { + prot = ZoneProt.LOC_MERGE; + encode(buf, message) { + buf.p1(message.coord); + buf.p1((message.shape << 2) | (message.angle & 3)); + buf.p2(message.locId); + buf.p2(message.startCycle); + buf.p2(message.endCycle); + buf.p2(message.pid); + buf.p1(message.east - message.srcX); + buf.p1(message.south - message.srcZ); + buf.p1(message.west - message.srcX); + buf.p1(message.north - message.srcZ); + } +} + +// src/lostcity/network/outgoing/model/Logout.ts +class Logout extends OutgoingMessage { + priority = ServerProtPriority.HIGH; +} + +// src/lostcity/network/225/outgoing/codec/LogoutEncoder.ts +class LogoutEncoder extends MessageEncoder { + prot = ServerProt.LOGOUT; + encode(_4, __) {} +} + +// src/lostcity/network/225/outgoing/codec/MapAnimEncoder.ts +class MapAnimEncoder extends ZoneMessageEncoder { + prot = ZoneProt.MAP_ANIM; + encode(buf, message) { + buf.p1(message.coord); + buf.p2(message.spotanim); + buf.p1(message.height); + buf.p2(message.delay); + } +} + +// src/lostcity/network/225/outgoing/codec/MapProjAnimEncoder.ts +class MapProjAnimEncoder extends ZoneMessageEncoder { + prot = ZoneProt.MAP_PROJANIM; + encode(buf, message) { + buf.p1(message.coord); + buf.p1(message.dstX - message.srcX); + buf.p1(message.dstZ - message.srcZ); + buf.p2(message.target); + buf.p2(message.spotanim); + buf.p1(message.srcHeight); + buf.p1(message.dstHeight); + buf.p2(message.startDelay); + buf.p2(message.endDelay); + buf.p1(message.peak); + buf.p1(message.arc); + } +} + +// src/lostcity/network/225/outgoing/codec/MessageGameEncoder.ts +class MessageGameEncoder extends MessageEncoder { + prot = ServerProt.MESSAGE_GAME; + encode(buf, message) { + buf.pjstr(message.msg); + } + test(message) { + return 1 + message.msg.length; + } +} + +// src/jagex2/wordenc/WordPack.ts +class WordPack { + static CHAR_LOOKUP = [ + ' ', + 'e', + 't', + 'a', + 'o', + 'i', + 'h', + 'n', + 's', + 'r', + 'd', + 'l', + 'u', + 'm', + 'w', + 'c', + 'y', + 'f', + 'g', + 'p', + 'b', + 'v', + 'k', + 'x', + 'j', + 'q', + 'z', + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + ' ', + '!', + '?', + '.', + ',', + ':', + ';', + '(', + ')', + '-', + '&', + '*', + '\\', + "'", + '@', + '#', + '+', + '=', + '\xA3', + '$', + '%', + '"', + '[', + ']' + ]; + static unpack(packet, length) { + const charBuffer = []; + let pos = 0; + let carry = -1; + let nibble; + for (let i = 0; i < length && pos < 80; i++) { + const data = packet.g1(); + nibble = (data >> 4) & 15; + if (carry !== -1) { + charBuffer[pos++] = this.CHAR_LOOKUP[(carry << 4) + nibble - 195]; + carry = -1; + } else if (nibble < 13) { + charBuffer[pos++] = this.CHAR_LOOKUP[nibble]; + } else { + carry = nibble; + } + nibble = data & 15; + if (carry != -1) { + charBuffer[pos++] = this.CHAR_LOOKUP[(carry << 4) + nibble - 195]; + carry = -1; + } else if (nibble < 13) { + charBuffer[pos++] = this.CHAR_LOOKUP[nibble]; + } else { + carry = nibble; + } + } + return this.toSentenceCase(charBuffer.slice(0, pos).join('')); + } + static pack(packet, input) { + if (input.length > 80) { + input = input.substring(0, 80); + } + input = input.toLowerCase(); + let carry = -1; + for (let i = 0; i < input.length; i++) { + const char = input.charAt(i); + let index = 0; + for (let j = 0; j < this.CHAR_LOOKUP.length; j++) { + if (char === this.CHAR_LOOKUP[j]) { + index = j; + break; + } + } + if (index > 12) { + index += 195; + } + if (carry == -1) { + if (index < 13) { + carry = index; + } else { + packet.p1(index); + } + } else if (index < 13) { + packet.p1((carry << 4) + index); + carry = -1; + } else { + packet.p1((carry << 4) + (index >> 4)); + carry = index & 15; + } + } + if (carry != -1) { + packet.p1(carry << 4); + } + } + static toSentenceCase(input) { + const chars = [...input.toLowerCase()]; + let punctuation = true; + for (let index = 0; index < chars.length; index++) { + const char = chars[index]; + if (punctuation && char >= 'a' && char <= 'z') { + chars[index] = char.toUpperCase(); + punctuation = false; + } + if (char === '.' || char === '!') { + punctuation = true; + } + } + return chars.join(''); + } +} + +// src/lostcity/network/225/outgoing/codec/MessagePrivateEncoder.ts +class MessagePrivateEncoder extends MessageEncoder { + prot = ServerProt.MESSAGE_PRIVATE; + encode(buf, message) { + buf.p8(message.from); + buf.p4(message.messageId); + buf.p1(message.staffModLevel); + WordPack.pack(buf, WordEnc2.filter(message.msg)); + } + test(message) { + return 8 + 4 + 1 + 1 + message.msg.length; + } +} + +// src/lostcity/network/outgoing/model/MessagePrivate.ts +class MessagePrivate extends OutgoingMessage { + from; + messageId; + staffModLevel; + msg; + priority = ServerProtPriority.HIGH; + constructor(from, messageId, staffModLevel, msg) { + super(); + this.from = from; + this.messageId = messageId; + this.staffModLevel = staffModLevel; + this.msg = msg; + } +} + +// src/lostcity/network/225/outgoing/codec/MidiJingleEncoder.ts +class MidiJingleEncoder extends MessageEncoder { + prot = ServerProt.MIDI_JINGLE; + encode(buf, message) { + buf.p2(message.delay); + buf.p4(message.data.length); + buf.pdata(message.data, 0, message.data.length); + } + test(message) { + return 2 + 4 + message.data.length; + } +} + +// src/lostcity/network/225/outgoing/codec/MidiSongEncoder.ts +class MidiSongEncoder extends MessageEncoder { + prot = ServerProt.MIDI_SONG; + encode(buf, message) { + buf.pjstr(message.name); + buf.p4(message.crc); + buf.p4(message.length); + } + test(message) { + return 1 + message.name.length + 4 + 4; + } +} + +// src/lostcity/network/225/outgoing/codec/ObjAddEncoder.ts +class ObjAddEncoder extends ZoneMessageEncoder { + prot = ZoneProt.OBJ_ADD; + encode(buf, message) { + buf.p1(message.coord); + buf.p2(message.obj); + buf.p2(Math.min(message.count, 65535)); + } +} + +// src/lostcity/network/225/outgoing/codec/ObjCountEncoder.ts +class ObjCountEncoder extends ZoneMessageEncoder { + prot = ZoneProt.OBJ_COUNT; + encode(buf, message) { + buf.p1(message.coord); + buf.p2(message.obj); + buf.p2(Math.min(message.oldCount, 65535)); + buf.p2(Math.min(message.newCount, 65535)); + } +} + +// src/lostcity/network/225/outgoing/codec/ObjDelEncoder.ts +class ObjDelEncoder extends ZoneMessageEncoder { + prot = ZoneProt.OBJ_DEL; + encode(buf, message) { + buf.p1(message.coord); + buf.p2(message.obj); + } +} + +// src/lostcity/network/225/outgoing/codec/ObjRevealEncoder.ts +class ObjRevealEncoder extends ZoneMessageEncoder { + prot = ZoneProt.OBJ_REVEAL; + encode(buf, message) { + buf.p1(message.coord); + buf.p2(message.obj); + buf.p2(Math.min(message.count, 65535)); + buf.p2(message.receiverId); + } +} + +// src/lostcity/network/outgoing/model/PCountDialog.ts +class PCountDialog extends OutgoingMessage { + priority = ServerProtPriority.LOW; +} + +// src/lostcity/network/225/outgoing/codec/PCountDialogEncoder.ts +class PCountDialogEncoder extends MessageEncoder { + prot = ServerProt.P_COUNTDIALOG; + encode(_4, __) {} +} + +// src/lostcity/network/225/outgoing/codec/ResetAnimsEncoder.ts +class ResetAnimsEncoder extends MessageEncoder { + prot = ServerProt.RESET_ANIMS; + encode(_4, __) {} +} + +// src/lostcity/network/225/outgoing/codec/ResetClientVarCacheEncoder.ts +class ResetClientVarCacheEncoder extends MessageEncoder { + prot = ServerProt.RESET_CLIENT_VARCACHE; + encode(_4, __) {} +} + +// src/lostcity/network/outgoing/model/SetMultiway.ts +class SetMultiway extends OutgoingMessage { + hidden; + priority = ServerProtPriority.LOW; + constructor(hidden) { + super(); + this.hidden = hidden; + } +} + +// src/lostcity/network/225/outgoing/codec/SetMultiwayEncoder.ts +class SetMultiwayEncoder extends MessageEncoder { + prot = ServerProt.SET_MULTIWAY; + encode(buf, message) { + buf.pbool(message.hidden); + } +} + +// src/lostcity/network/outgoing/model/SynthSound.ts +class SynthSound extends OutgoingMessage { + synth; + loops; + delay; + priority = ServerProtPriority.LOW; + constructor(synth, loops, delay) { + super(); + this.synth = synth; + this.loops = loops; + this.delay = delay; + } +} + +// src/lostcity/network/225/outgoing/codec/SynthSoundEncoder.ts +class SynthSoundEncoder extends MessageEncoder { + prot = ServerProt.SYNTH_SOUND; + encode(buf, message) { + buf.p2(message.synth); + buf.p1(message.loops); + buf.p2(message.delay); + } +} + +// src/lostcity/network/outgoing/model/TutorialFlashSide.ts +class TutorialFlashSide extends OutgoingMessage { + tab; + priority = ServerProtPriority.LOW; + constructor(tab) { + super(); + this.tab = tab; + } +} + +// src/lostcity/network/225/outgoing/codec/TutorialFlashSideEncoder.ts +class TutorialFlashSideEncoder extends MessageEncoder { + prot = ServerProt.TUTORIAL_FLASHSIDE; + encode(buf, message) { + buf.p1(message.tab); + } +} + +// src/lostcity/network/225/outgoing/codec/TutorialOpenChatEncoder.ts +class TutorialOpenChatEncoder extends MessageEncoder { + prot = ServerProt.TUTORIAL_OPENCHAT; + encode(buf, message) { + buf.p2(message.component); + } +} + +// src/lostcity/network/225/outgoing/codec/UnsetMapFlagEncoder.ts +class UnsetMapFlagEncoder extends MessageEncoder { + prot = ServerProt.UNSET_MAP_FLAG; + encode(_4, __) {} +} + +// src/lostcity/network/outgoing/model/UpdateFriendList.ts +class UpdateFriendList extends OutgoingMessage { + name; + nodeId; + priority = ServerProtPriority.LOW; + constructor(name, nodeId) { + super(); + this.name = name; + this.nodeId = nodeId; + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateFriendListEncoder.ts +class UpdateFriendListEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_FRIENDLIST; + encode(buf, message) { + buf.p8(message.name); + buf.p1(message.nodeId); + } +} + +// src/lostcity/network/outgoing/model/UpdateIgnoreList.ts +class UpdateIgnoreList extends OutgoingMessage { + names; + priority = ServerProtPriority.LOW; + constructor(names) { + super(); + this.names = names; + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateIgnoreListEncoder.ts +class UpdateIgnoreListEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_IGNORELIST; + encode(buf, message) { + for (const name of message.names) { + buf.p8(name); + } + } + test(message) { + return 8 * message.names.length; + } +} + +// src/lostcity/network/outgoing/model/UpdateInvFull.ts +class UpdateInvFull extends OutgoingMessage { + component; + inv; + priority = ServerProtPriority.HIGH; + constructor(component, inv) { + super(); + this.component = component; + this.inv = inv; + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateInvFullEncoder.ts +class UpdateInvFullEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_INV_FULL; + encode(buf, message) { + const {component, inv} = message; + const comType = Component.get(component); + const size = Math.min(inv.capacity, comType.width * comType.height); + buf.p2(component); + buf.p1(size); + for (let slot = 0; slot < size; slot++) { + const obj = inv.get(slot); + if (obj) { + buf.p2(obj.id + 1); + if (obj.count >= 255) { + buf.p1(255); + buf.p4(obj.count); + } else { + buf.p1(obj.count); + } + } else { + buf.p2(0); + buf.p1(0); + } + } + } + test(message) { + const {component, inv} = message; + const comType = Component.get(component); + const size = Math.min(inv.capacity, comType.width * comType.height); + let length = 0; + length += 3; + for (let slot = 0; slot < size; slot++) { + const obj = inv.get(slot); + if (obj) { + length += 2; + if (obj.count >= 255) { + length += 5; + } else { + length += 1; + } + } else { + length += 3; + } + } + return length; + } +} + +// src/lostcity/network/outgoing/model/UpdateInvPartial.ts +class UpdateInvPartial extends OutgoingMessage { + component; + inv; + priority = ServerProtPriority.HIGH; + slots; + constructor(component, inv, ...slots) { + super(); + this.component = component; + this.inv = inv; + this.slots = slots; + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateInvPartialEncoder.ts +class UpdateInvPartialEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_INV_PARTIAL; + encode(buf, message) { + const {component, inv} = message; + buf.p2(component); + for (const slot of message.slots) { + const obj = inv.get(slot); + buf.p1(slot); + if (obj) { + buf.p2(obj.id + 1); + if (obj.count >= 255) { + buf.p1(255); + buf.p4(obj.count); + } else { + buf.p1(obj.count); + } + } else { + buf.p2(0); + buf.p1(0); + } + } + } + test(message) { + const {inv} = message; + let length = 0; + length += 2; + for (const slot of message.slots) { + const obj = inv.get(slot); + length += 1; + if (obj) { + length += 2; + if (obj.count >= 255) { + length += 5; + } else { + length += 1; + } + } else { + length += 3; + } + } + return length; + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateInvStopTransmitEncoder.ts +class UpdateInvStopTransmitEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_INV_STOP_TRANSMIT; + encode(buf, message) { + buf.p2(message.component); + } +} + +// src/lostcity/network/outgoing/model/UpdateRunEnergy.ts +class UpdateRunEnergy extends OutgoingMessage { + energy; + priority = ServerProtPriority.LOW; + constructor(energy) { + super(); + this.energy = energy; + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateRunEnergyEncoder.ts +class UpdateRunEnergyEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_RUNENERGY; + encode(buf, message) { + buf.p1((message.energy / 100) | 0); + } +} + +// src/lostcity/network/outgoing/model/UpdateRunWeight.ts +class UpdateRunWeight extends OutgoingMessage { + kg; + priority = ServerProtPriority.LOW; + constructor(kg) { + super(); + this.kg = kg; + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateRunWeightEncoder.ts +class UpdateRunWeightEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_RUNWEIGHT; + encode(buf, message) { + buf.p2(message.kg); + } +} + +// src/lostcity/network/outgoing/model/UpdateStat.ts +class UpdateStat extends OutgoingMessage { + stat; + exp; + level; + priority = ServerProtPriority.LOW; + constructor(stat, exp, level) { + super(); + this.stat = stat; + this.exp = exp; + this.level = level; + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateStatEncoder.ts +class UpdateStatEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_STAT; + encode(buf, message) { + buf.p1(message.stat); + buf.p4((message.exp / 10) | 0); + buf.p1(message.level); + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateUid192Encoder.ts +class UpdateUid192Encoder extends MessageEncoder { + prot = ServerProt.UPDATE_UID192; + encode(buf, message) { + buf.p2(message.uid); + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateZoneFullFollowsEncoder.ts +class UpdateZoneFullFollowsEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_ZONE_FULL_FOLLOWS; + encode(buf, message) { + buf.p1((message.zoneX << 3) - Position.zoneOrigin(message.originX)); + buf.p1((message.zoneZ << 3) - Position.zoneOrigin(message.originZ)); + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateZonePartialFollowsEncoder.ts +class UpdateZonePartialFollowsEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_ZONE_PARTIAL_FOLLOWS; + encode(buf, message) { + buf.p1((message.zoneX << 3) - Position.zoneOrigin(message.originX)); + buf.p1((message.zoneZ << 3) - Position.zoneOrigin(message.originZ)); + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateZonePartialEnclosedEncoder.ts +class UpdateZonePartialEnclosedEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_ZONE_PARTIAL_ENCLOSED; + encode(buf, message) { + buf.p1((message.zoneX << 3) - Position.zoneOrigin(message.originX)); + buf.p1((message.zoneZ << 3) - Position.zoneOrigin(message.originZ)); + buf.pdata(message.data, 0, message.data.length); + } + test(message) { + return 1 + 1 + message.data.length; + } +} + +// src/lostcity/network/225/outgoing/codec/VarpLargeEncoder.ts +class VarpLargeEncoder extends MessageEncoder { + prot = ServerProt.VARP_LARGE; + encode(buf, message) { + buf.p2(message.varp); + buf.p4(message.value); + } +} + +// src/lostcity/network/225/outgoing/codec/VarpSmallEncoder.ts +class VarpSmallEncoder extends MessageEncoder { + prot = ServerProt.VARP_SMALL; + encode(buf, message) { + buf.p2(message.varp); + buf.p1(message.value); + } +} + +// src/lostcity/network/outgoing/model/NpcInfo.ts +class NpcInfo extends OutgoingMessage { + buildArea; + level; + x; + z2; + originX; + originZ; + priority = ServerProtPriority.HIGH; + accumulator = 0; + constructor(buildArea, level, x, z2, originX, originZ) { + super(); + this.buildArea = buildArea; + this.level = level; + this.x = x; + this.z = z2; + this.originX = originX; + this.originZ = originZ; + } +} + +// src/lostcity/network/225/outgoing/codec/NpcInfoEncoder.ts +class NpcInfoEncoder extends MessageEncoder { + static BITS_NEW = 13 + 11 + 5 + 5 + 1; + static BITS_RUN = 1 + 2 + 3 + 3 + 1; + static BITS_WALK = 1 + 2 + 3 + 1; + static BITS_EXTENDED = 1 + 2; + static BYTES_LIMIT = 4997; + prot = ServerProt.NPC_INFO; + encode(buf, message) { + const buildArea = message.buildArea; + this.writeNpcs(buf, message); + this.writeNewNpcs(buf, message); + const extended = buildArea.extendedInfo; + if (extended.size > 0) { + for (const info of extended) { + const npc = World_default.getNpc(info.id); + if (!npc) { + buf.p1(0); + continue; + } + this.writeExtendedInfo(npc, buf, info.added); + } + } + buildArea.clearExtended(); + } + test(_4) { + return NpcInfoEncoder.BYTES_LIMIT; + } + writeNpcs(buf, message) { + const buildArea = message.buildArea; + buf.bits(); + buf.pBit(8, buildArea.npcs.size); + for (const nid of buildArea.npcs) { + const npc = World_default.getNpc(nid); + if (!npc || npc.tele || npc.level !== message.level || !Position.isWithinDistanceSW(message, npc, 15) || !npc.checkLifeCycle(World_default.currentTick)) { + buf.pBit(1, 1); + buf.pBit(2, 3); + buildArea.npcs.delete(nid); + continue; + } + let extendedInfo = npc.mask > 0; + const {walkDir, runDir} = npc; + let bits = 0; + if (runDir !== -1) { + bits = NpcInfoEncoder.BITS_RUN; + } else if (walkDir !== -1) { + bits = NpcInfoEncoder.BITS_WALK; + } else if (extendedInfo) { + bits = NpcInfoEncoder.BITS_EXTENDED; + } + const updateSize = extendedInfo ? this.calculateExtendedInfo(npc, false) : 0; + if (((buf.bitPos + bits) >>> 3) + (message.accumulator += updateSize) > this.test(message)) { + extendedInfo = false; + } + buf.pBit(1, runDir !== -1 || walkDir !== -1 || extendedInfo ? 1 : 0); + if (runDir !== -1) { + buf.pBit(2, 2); + buf.pBit(3, walkDir); + buf.pBit(3, runDir); + buf.pBit(1, extendedInfo ? 1 : 0); + } else if (walkDir !== -1) { + buf.pBit(2, 1); + buf.pBit(3, walkDir); + buf.pBit(1, extendedInfo ? 1 : 0); + } else if (extendedInfo) { + buf.pBit(2, 0); + } + if (extendedInfo) { + buildArea.extendedInfo.add({id: nid, added: false}); + } + } + } + writeNewNpcs(buf, message) { + const buildArea = message.buildArea; + for (const npc of buildArea.getNearbyNpcs(message.x, message.z, message.originX, message.originZ)) { + const extendedInfo = npc.mask > 0 || npc.orientation !== -1 || npc.faceX !== -1 || npc.faceZ !== -1 || npc.faceEntity !== -1; + const updateSize = extendedInfo ? this.calculateExtendedInfo(npc, true) : 0; + if (((buf.bitPos + NpcInfoEncoder.BITS_NEW + 13) >>> 3) + (message.accumulator += updateSize) > this.test(message)) { + break; + } + buf.pBit(13, npc.nid); + buf.pBit(11, npc.type); + buf.pBit(5, npc.x - message.x); + buf.pBit(5, npc.z - message.z); + buf.pBit(1, extendedInfo ? 1 : 0); + if (extendedInfo) { + buildArea.extendedInfo.add({id: npc.nid, added: true}); + } + buildArea.npcs.add(npc.nid); + } + if (buildArea.extendedInfo.size > 0) { + buf.pBit(13, 8191); + } + buf.bytes(); + } + writeExtendedInfo(npc, buf, newlyObserved) { + let mask = npc.mask; + if (newlyObserved && (npc.orientation !== -1 || npc.faceX !== -1 || npc.faceZ != -1)) { + mask |= Npc2.FACE_COORD; + } + if (newlyObserved && npc.faceEntity !== -1) { + mask |= Npc2.FACE_ENTITY; + } + buf.p1(mask); + if (mask & Npc2.ANIM) { + buf.p2(npc.animId); + buf.p1(npc.animDelay); + } + if (mask & Npc2.FACE_ENTITY) { + if (npc.faceEntity !== -1) { + npc.alreadyFacedEntity = true; + } + buf.p2(npc.faceEntity); + } + if (mask & Npc2.SAY) { + buf.pjstr(npc.chat ?? ''); + } + if (mask & Npc2.DAMAGE) { + buf.p1(npc.damageTaken); + buf.p1(npc.damageType); + buf.p1(npc.levels[NpcStat_default.HITPOINTS]); + buf.p1(npc.baseLevels[NpcStat_default.HITPOINTS]); + } + if (mask & Npc2.CHANGE_TYPE) { + buf.p2(npc.type); + } + if (mask & Npc2.SPOTANIM) { + buf.p2(npc.graphicId); + buf.p2(npc.graphicHeight); + buf.p2(npc.graphicDelay); + } + if (mask & Npc2.FACE_COORD) { + if (npc.faceX !== -1) { + npc.alreadyFacedCoord = true; + } + if (newlyObserved && npc.faceX != -1) { + buf.p2(npc.faceX); + buf.p2(npc.faceZ); + } else if (newlyObserved && npc.orientation != -1) { + const faceX = Position.moveX(npc.x, npc.orientation); + const faceZ = Position.moveZ(npc.z, npc.orientation); + buf.p2(faceX * 2 + 1); + buf.p2(faceZ * 2 + 1); + } else { + buf.p2(npc.faceX); + buf.p2(npc.faceZ); + } + } + } + calculateExtendedInfo(npc, newlyObserved) { + let length = 0; + let mask = npc.mask; + if (newlyObserved && (npc.orientation !== -1 || npc.faceX !== -1 || npc.faceZ != -1)) { + mask |= Npc2.FACE_COORD; + } + if (newlyObserved && npc.faceEntity !== -1) { + mask |= Npc2.FACE_ENTITY; + } + length += 1; + if (mask & Npc2.ANIM) { + length += 3; + } + if (mask & Npc2.FACE_ENTITY) { + length += 2; + } + if (mask & Npc2.SAY) { + length += npc.chat ? npc.chat.length + 1 : 1; + } + if (mask & Npc2.DAMAGE) { + length += 4; + } + if (mask & Npc2.CHANGE_TYPE) { + length += 2; + } + if (mask & Npc2.SPOTANIM) { + length += 6; + } + if (mask & Npc2.FACE_COORD) { + length += 4; + } + return length; + } +} + +// src/lostcity/network/outgoing/model/UpdateRebootTimer.ts +class UpdateRebootTimer extends OutgoingMessage { + ticks; + priority = ServerProtPriority.LOW; + constructor(ticks) { + super(); + this.ticks = ticks; + } +} + +// src/lostcity/network/225/outgoing/codec/UpdateRebootTimerEncoder.ts +class UpdateRebootTimerEncoder extends MessageEncoder { + prot = ServerProt.UPDATE_REBOOT_TIMER; + encode(buf, message) { + buf.p2(message.ticks); + } +} + +// src/lostcity/network/225/outgoing/prot/ServerProtRepository.ts +class ServerProtRepository { + encoders = new Map(); + bind(message, encoder) { + if (this.encoders.has(message)) { + throw new Error(`[ServerProtRepository] Already defines a ${message.name}.`); + } + this.encoders.set(message, encoder); + } + constructor() { + this.bind(CamLookAt, new CamLookAtEncoder()); + this.bind(CamMoveTo, new CamMoveToEncoder()); + this.bind(CamReset, new CamResetEncoder()); + this.bind(CamShake, new CamShakeEncoder()); + this.bind(ChatFilterSettings, new ChatFilterSettingsEncoder()); + this.bind(DataLand, new DataLandEncoder()); + this.bind(DataLandDone, new DataLandDoneEncoder()); + this.bind(DataLoc, new DataLocEncoder()); + this.bind(DataLocDone, new DataLocDoneEncoder()); + this.bind(EnableTracking, new EnableTrackingEncoder()); + this.bind(FinishTracking, new FinishTrackingEncoder()); + this.bind(HintArrow, new HintArrowEncoder()); + this.bind(IfClose, new IfCloseEncoder()); + this.bind(IfOpenChatModal, new IfOpenChatModalEncoder()); + this.bind(IfOpenMainModal, new IfOpenMainModalEncoder()); + this.bind(IfOpenMainSideModal, new IfOpenMainSideModalEncoder()); + this.bind(IfOpenSideModal, new IfOpenSideModalEncoder()); + this.bind(IfOpenSideOverlay, new IfOpenSideOverlayEncoder()); + this.bind(IfSetAnim, new IfSetAnimEncoder()); + this.bind(IfSetColour, new IfSetColourEncoder()); + this.bind(IfSetHide, new IfSetHideEncoder()); + this.bind(IfSetModel, new IfSetModelEncoder()); + this.bind(IfSetNpcHead, new IfSetNpcHeadEncoder()); + this.bind(IfSetObject, new IfSetObjectEncoder()); + this.bind(IfSetPlayerHead, new IfSetPlayerHeadEncoder()); + this.bind(IfSetPosition, new IfSetPositionEncoder()); + this.bind(IfSetRecol, new IfSetRecolEncoder()); + this.bind(IfSetText, new IfSetTextEncoder()); + this.bind(IfShowSide, new IfShowSideEncoder()); + this.bind(LastLoginInfo, new LastLoginInfoEncoder()); + this.bind(LocAddChange, new LocAddChangeEncoder()); + this.bind(LocAnim, new LocAnimEncoder()); + this.bind(LocDel, new LocDelEncoder()); + this.bind(LocMerge, new LocMergeEncoder()); + this.bind(Logout, new LogoutEncoder()); + this.bind(MapAnim, new MapAnimEncoder()); + this.bind(MapProjAnim, new MapProjAnimEncoder()); + this.bind(MessageGame, new MessageGameEncoder()); + this.bind(MessagePrivate, new MessagePrivateEncoder()); + this.bind(MidiJingle, new MidiJingleEncoder()); + this.bind(MidiSong, new MidiSongEncoder()); + this.bind(NpcInfo, new NpcInfoEncoder()); + this.bind(ObjAdd, new ObjAddEncoder()); + this.bind(ObjCount, new ObjCountEncoder()); + this.bind(ObjDel, new ObjDelEncoder()); + this.bind(ObjReveal, new ObjRevealEncoder()); + this.bind(PCountDialog, new PCountDialogEncoder()); + this.bind(PlayerInfo, new PlayerInfoEncoder()); + this.bind(RebuildNormal, new RebuildNormalEncoder()); + this.bind(ResetAnims, new ResetAnimsEncoder()); + this.bind(ResetClientVarCache, new ResetClientVarCacheEncoder()); + this.bind(SetMultiway, new SetMultiwayEncoder()); + this.bind(SynthSound, new SynthSoundEncoder()); + this.bind(TutorialFlashSide, new TutorialFlashSideEncoder()); + this.bind(TutorialOpenChat, new TutorialOpenChatEncoder()); + this.bind(UnsetMapFlag, new UnsetMapFlagEncoder()); + this.bind(UpdateFriendList, new UpdateFriendListEncoder()); + this.bind(UpdateIgnoreList, new UpdateIgnoreListEncoder()); + this.bind(UpdateInvFull, new UpdateInvFullEncoder()); + this.bind(UpdateInvPartial, new UpdateInvPartialEncoder()); + this.bind(UpdateInvStopTransmit, new UpdateInvStopTransmitEncoder()); + this.bind(UpdateRunEnergy, new UpdateRunEnergyEncoder()); + this.bind(UpdateRunWeight, new UpdateRunWeightEncoder()); + this.bind(UpdateRebootTimer, new UpdateRebootTimerEncoder()); + this.bind(UpdateStat, new UpdateStatEncoder()); + this.bind(UpdateUid192, new UpdateUid192Encoder()); + this.bind(UpdateZoneFullFollows, new UpdateZoneFullFollowsEncoder()); + this.bind(UpdateZonePartialEnclosed, new UpdateZonePartialEnclosedEncoder()); + this.bind(UpdateZonePartialFollows, new UpdateZonePartialFollowsEncoder()); + this.bind(VarpLarge, new VarpLargeEncoder()); + this.bind(VarpSmall, new VarpSmallEncoder()); + } + getEncoder(message) { + return this.encoders.get(message.constructor); + } + getZoneEncoder(message) { + return this.encoders.get(message.constructor); + } +} +var ServerProtRepository_default = new ServerProtRepository(); + +// src/lostcity/engine/zone/ZoneEntityList.ts +class ZoneEntityList extends Array { + capacity; + onFilled; + constructor(capacity, onFilled) { + super(); + this.capacity = capacity; + this.onFilled = onFilled; + } + *stack(coord) { + const items = this[coord]; + if (typeof items === 'undefined') { + return; + } + for (let index = 0; index < items.length; index++) { + yield items[index]; + } + } + *all(reverse = false) { + for (let index = 0; index < this.length; index++) { + const items = this[index]; + if (typeof items === 'undefined') { + continue; + } + if (reverse) { + for (let i = items.length - 1; i >= 0; i--) { + yield items[i]; + } + } else { + for (let i = 0; i < items.length; i++) { + yield items[i]; + } + } + } + } + addLast(coord, item, unchecked = false) { + this.check(coord, unchecked); + this[coord]?.push(item); + } + addFirst(coord, item, unchecked = false) { + this.check(coord, unchecked); + this[coord]?.unshift(item); + } + sortStack(coord, unchecked = false) { + const top = this.nextTopStack(coord); + if (typeof top === 'undefined') { + return; + } + const items = this[coord]; + if (typeof items === 'undefined') { + return; + } + if (items[0] !== top) { + this.remove(coord, top); + this.addFirst(coord, top, unchecked); + } + } + remove(coord, item) { + const items = this[coord]; + if (typeof items === 'undefined') { + return; + } + const index = items.indexOf(item); + if (index === -1) { + return; + } + items.splice(index, 1); + } + contains(coord, item) { + const items = this[coord]; + if (typeof items === 'undefined') { + return false; + } + return items.indexOf(item) !== -1; + } + check(coord, unchecked) { + const items = this[coord]; + if (typeof items === 'undefined') { + this[coord] = []; + } + if (!unchecked && this.total === this.capacity) { + const bottom = this.nextBottomAll(); + if (typeof bottom !== 'undefined') { + this.onFilled(bottom); + } + } + } + get total() { + let total = 0; + for (let index = 0; index < this.length; index++) { + const items = this[index]; + if (typeof items === 'undefined') { + continue; + } + total += items.length; + } + return total; + } +} + +class LocList extends ZoneEntityList { + nextTopStack(coord) { + const locs = this[coord]; + if (typeof locs === 'undefined') { + return; + } + let topCost = -99999999; + let topLoc; + for (const loc of locs) { + const cost = loc.lifecycle; + if (cost > topCost) { + topCost = cost; + topLoc = loc; + } + } + return topLoc; + } + nextBottomAll() { + let bottomCost = Number.POSITIVE_INFINITY; + let bottomLoc; + for (let index = 0; index < this.length; index++) { + const locs = this[index]; + if (typeof locs === 'undefined') { + continue; + } + for (const loc of locs) { + if (bottomCost === 0) { + break; + } + if (loc.lifecycle !== EntityLifeCycle_default.DESPAWN) { + continue; + } + const cost = loc.lifecycle; + if (cost < bottomCost) { + bottomCost = cost; + bottomLoc = loc; + } + } + } + return bottomLoc; + } +} + +class ObjList extends ZoneEntityList { + nextTopStack(coord) { + const objs = this[coord]; + if (typeof objs === 'undefined') { + return; + } + let topCost = -99999999; + let topObj; + for (const obj of objs) { + const type = ObjType.get(obj.type); + let cost = type.cost; + if (type.stackable) { + cost *= obj.count + 1; + } + cost += obj.lifecycle; + if (cost > topCost) { + topCost = cost; + topObj = obj; + } + } + return topObj; + } + nextBottomAll() { + let bottomCost = Number.POSITIVE_INFINITY; + let bottomObj; + for (let index = 0; index < this.length; index++) { + const objs = this[index]; + if (typeof objs === 'undefined') { + continue; + } + for (const obj of objs) { + if (bottomCost === 0) { + break; + } + if (obj.lifecycle !== EntityLifeCycle_default.DESPAWN) { + continue; + } + const type = ObjType.get(obj.type); + let cost = type.cost; + if (type.stackable) { + cost *= obj.count + 1; + } + cost += obj.lifecycle; + if (cost < bottomCost) { + bottomCost = cost; + bottomObj = obj; + } + } + } + return bottomObj; + } +} + +// src/lostcity/engine/zone/Zone.ts +class Zone { + static SIZE = 8 * 8; + static LOCS = this.SIZE << 2; + static OBJS = (this.SIZE << 1) + 1; + index; + x; + z; + level; + players; + npcs; + locs; + objs; + events; + shared = null; + totalLocs = 0; + totalObjs = 0; + constructor(index) { + this.index = index; + const coord = ZoneMap2.unpackIndex(index); + this.x = coord.x >> 3; + this.z = coord.z >> 3; + this.level = coord.level; + this.events = new Set(); + this.players = new Set(); + this.npcs = new Set(); + this.locs = new LocList(Zone.LOCS, loc => World_default.removeLoc(loc, 100)); + this.objs = new ObjList(Zone.OBJS, obj => World_default.removeObj(obj, 100)); + } + enter(entity) { + if (entity instanceof Player2) { + this.players.add(entity.uid); + World_default.getZoneGrid(this.level).flag(this.x, this.z); + } else if (entity instanceof Npc2) { + this.npcs.add(entity.nid); + } + } + leave(entity) { + if (entity instanceof Player2) { + this.players.delete(entity.uid); + if (this.players.size === 0) { + World_default.getZoneGrid(this.level).unflag(this.x, this.z); + } + } else if (entity instanceof Npc2) { + this.npcs.delete(entity.nid); + } + } + tick(tick) { + let updated; + do { + updated = false; + for (const obj of this.getAllObjsUnsafe()) { + if (!obj.updateLifeCycle(tick) || obj.lastLifecycleTick === tick) { + continue; + } + if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { + if (obj.receiverId !== -1) { + World_default.revealObj(obj); + } else { + World_default.removeObj(obj, 0); + updated = true; + } + } else if (obj.lifecycle === EntityLifeCycle_default.RESPAWN) { + World_default.addObj(obj, -1, 0); + updated = true; + } + } + for (const loc of this.getAllLocsUnsafe()) { + if (!loc.updateLifeCycle(tick) || loc.lastLifecycleTick === tick) { + continue; + } + if (loc.lifecycle === EntityLifeCycle_default.DESPAWN) { + World_default.removeLoc(loc, 0); + updated = true; + } else if (loc.lifecycle === EntityLifeCycle_default.RESPAWN) { + World_default.addLoc(loc, 0); + updated = true; + } + } + } while (updated); + } + computeShared() { + this.shared = null; + let length = 0; + const enclosed = []; + for (const event of this.events.values()) { + if (event.type !== ZoneEventType_default.ENCLOSED) { + continue; + } + const encoder = ServerProtRepository_default.getZoneEncoder(event.message); + if (typeof encoder === 'undefined') { + continue; + } + const bytes = encoder.enclose(event.message); + enclosed.push(bytes); + length += bytes.length; + } + if (enclosed.length === 0 || length === 0) { + return; + } + const shared = new Uint8Array(length); + let ptr = 0; + for (const bytes of enclosed) { + shared.set(bytes, ptr); + ptr += bytes.length; + } + this.shared = shared; + } + writeFullFollows(player) { + player.write(new UpdateZoneFullFollows(this.x, this.z, player.originX, player.originZ)); + for (const obj of this.getAllObjsUnsafe(true)) { + if (obj.receiverId !== -1 && obj.receiverId !== player.pid) { + continue; + } + player.write(new UpdateZonePartialFollows(this.x, this.z, player.originX, player.originZ)); + if (obj.lifecycle === EntityLifeCycle_default.DESPAWN && obj.checkLifeCycle(World_default.currentTick)) { + player.write(new ObjAdd(Position.packZoneCoord(obj.x, obj.z), obj.type, obj.count)); + } else if (obj.lifecycle === EntityLifeCycle_default.RESPAWN && obj.checkLifeCycle(World_default.currentTick)) { + player.write(new ObjAdd(Position.packZoneCoord(obj.x, obj.z), obj.type, obj.count)); + } + } + for (const loc of this.getAllLocsUnsafe(true)) { + if (loc.lifecycle === EntityLifeCycle_default.DESPAWN && loc.checkLifeCycle(World_default.currentTick)) { + player.write(new LocAddChange(Position.packZoneCoord(loc.x, loc.z), loc.type, loc.shape, loc.angle)); + } else if (loc.lifecycle === EntityLifeCycle_default.RESPAWN && !loc.checkLifeCycle(World_default.currentTick)) { + player.write(new LocDel(Position.packZoneCoord(loc.x, loc.z), loc.shape, loc.angle)); + } + } + } + writePartialEncloses(player) { + if (!this.shared) { + return; + } + player.write(new UpdateZonePartialEnclosed(this.x, this.z, player.originX, player.originZ, this.shared)); + } + writePartialFollows(player) { + if (this.events.size === 0) { + return; + } + player.write(new UpdateZonePartialFollows(this.x, this.z, player.originX, player.originZ)); + for (const event of this.events) { + if (event.type !== ZoneEventType_default.FOLLOWS) { + continue; + } + if (event.receiverId !== -1 && event.receiverId !== player.pid) { + continue; + } + player.write(event.message); + } + } + reset() { + this.events.clear(); + } + addStaticLoc(loc) { + const coord = Position.packZoneCoord(loc.x, loc.z); + this.locs.addLast(coord, loc, true); + this.totalLocs++; + this.locs.sortStack(coord, true); + } + addStaticObj(obj) { + const coord = Position.packZoneCoord(obj.x, obj.z); + this.objs.addLast(coord, obj, true); + this.totalObjs++; + this.objs.sortStack(coord, true); + } + addLoc(loc) { + const coord = Position.packZoneCoord(loc.x, loc.z); + if (loc.lifecycle === EntityLifeCycle_default.DESPAWN) { + this.locs.addLast(coord, loc); + this.totalLocs++; + } + this.locs.sortStack(coord); + this.events.add({ + type: ZoneEventType_default.ENCLOSED, + receiverId: -1, + message: new LocAddChange(coord, loc.type, loc.shape, loc.angle) + }); + } + removeLoc(loc) { + const coord = Position.packZoneCoord(loc.x, loc.z); + if (loc.lifecycle === EntityLifeCycle_default.DESPAWN) { + this.locs.remove(coord, loc); + this.totalLocs--; + } + this.locs.sortStack(coord); + this.events.add({ + type: ZoneEventType_default.ENCLOSED, + receiverId: -1, + message: new LocDel(coord, loc.shape, loc.angle) + }); + } + getLoc(x, z2, type) { + for (const loc of this.getLocsSafe(Position.packZoneCoord(x, z2))) { + if (loc.type === type) { + return loc; + } + } + return null; + } + mergeLoc(loc, player, startCycle, endCycle, south, east, north, west) { + this.events.add({ + type: ZoneEventType_default.ENCLOSED, + receiverId: -1, + message: new LocMerge(loc.x, loc.z, loc.shape, loc.angle, loc.type, startCycle, endCycle, player.pid, east, south, west, north) + }); + } + animLoc(loc, seq) { + this.events.add({ + type: ZoneEventType_default.ENCLOSED, + receiverId: -1, + message: new LocAnim(Position.packZoneCoord(loc.x, loc.z), loc.shape, loc.angle, seq) + }); + } + addObj(obj, receiverId) { + const coord = Position.packZoneCoord(obj.x, obj.z); + if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { + this.objs.addLast(coord, obj); + this.totalObjs++; + } + this.objs.sortStack(coord); + if (obj.lifecycle === EntityLifeCycle_default.RESPAWN || obj.receiverId === -1) { + this.events.add({ + type: ZoneEventType_default.ENCLOSED, + receiverId, + message: new ObjAdd(coord, obj.type, obj.count) + }); + } else if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { + this.events.add({ + type: ZoneEventType_default.FOLLOWS, + receiverId, + message: new ObjAdd(coord, obj.type, obj.count) + }); + } + } + revealObj(obj, receiverId) { + obj.receiverId = -1; + obj.reveal = -1; + const coord = Position.packZoneCoord(obj.x, obj.z); + this.objs.sortStack(coord); + this.events.add({ + type: ZoneEventType_default.ENCLOSED, + receiverId: -1, + message: new ObjReveal(coord, obj.type, obj.count, receiverId) + }); + } + changeObj(obj, receiverId, oldCount, newCount) { + obj.count = newCount; + const coord = Position.packZoneCoord(obj.x, obj.z); + this.objs.sortStack(coord); + this.events.add({ + type: ZoneEventType_default.FOLLOWS, + receiverId, + message: new ObjCount(coord, obj.type, oldCount, newCount) + }); + } + removeObj(obj) { + const coord = Position.packZoneCoord(obj.x, obj.z); + if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { + this.objs.remove(coord, obj); + this.totalObjs--; + } + this.objs.sortStack(coord); + if (obj.lifecycle === EntityLifeCycle_default.RESPAWN || obj.receiverId === -1) { + this.events.add({ + type: ZoneEventType_default.ENCLOSED, + receiverId: -1, + message: new ObjDel(coord, obj.type) + }); + } else if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { + this.events.add({ + type: ZoneEventType_default.FOLLOWS, + receiverId: -1, + message: new ObjDel(coord, obj.type) + }); + } + } + animMap(x, z2, spotanim, height, delay) { + this.events.add({ + type: ZoneEventType_default.ENCLOSED, + receiverId: -1, + message: new MapAnim(Position.packZoneCoord(x, z2), spotanim, height, delay) + }); + } + mapProjAnim(x, z2, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) { + this.events.add({ + type: ZoneEventType_default.ENCLOSED, + receiverId: -1, + message: new MapProjAnim(x, z2, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) + }); + } + getObj(x, z2, type, receiverId) { + for (const obj of this.getObjsSafe(Position.packZoneCoord(x, z2))) { + if ((obj.receiverId !== -1 && obj.receiverId !== receiverId) || obj.type !== type) { + continue; + } + return obj; + } + return null; + } + *getAllPlayersSafe() { + for (const uid of this.players) { + const player = World_default.getPlayerByUid(uid); + if (player && player.checkLifeCycle(World_default.currentTick)) { + yield player; + } + } + } + *getAllNpcsSafe() { + for (const nid of this.npcs) { + const npc = World_default.getNpc(nid); + if (npc && npc.checkLifeCycle(World_default.currentTick)) { + yield npc; + } + } + } + *getAllObjsSafe() { + for (const obj of this.objs.all()) { + if (obj.checkLifeCycle(World_default.currentTick)) { + yield obj; + } + } + } + *getObjsSafe(coord) { + for (const obj of this.objs.stack(coord)) { + if (obj.checkLifeCycle(World_default.currentTick)) { + yield obj; + } + } + } + *getObjsUnsafe(coord) { + yield* this.objs.stack(coord); + } + *getAllObjsUnsafe(reverse = false) { + yield* this.objs.all(reverse); + } + *getAllLocsSafe() { + for (const loc of this.locs.all()) { + if (loc.checkLifeCycle(World_default.currentTick)) { + yield loc; + } + } + } + *getLocsSafe(coord) { + for (const loc of this.locs.stack(coord)) { + if (loc.checkLifeCycle(World_default.currentTick)) { + yield loc; + } + } + } + *getLocsUnsafe(coord) { + yield* this.locs.stack(coord); + } + *getAllLocsUnsafe(reverse = false) { + yield* this.locs.all(reverse); + } +} + +// src/lostcity/engine/zone/ZoneGrid.ts +class ZoneGrid { + static GRID_SIZE = 2048; + static INT_BITS = 5; + static INT_BITS_FLAG = (1 << this.INT_BITS) - 1; + static DEFAULT_GRID_SIZE = this.GRID_SIZE * (this.GRID_SIZE >> this.INT_BITS); + grid; + constructor(size = ZoneGrid.DEFAULT_GRID_SIZE) { + this.grid = new Int32Array(size); + } + index(zoneX, zoneY) { + return (zoneX << ZoneGrid.INT_BITS) | (zoneY >>> ZoneGrid.INT_BITS); + } + flag(zoneX, zoneY) { + this.grid[this.index(zoneX, zoneY)] |= 1 << (zoneY & ZoneGrid.INT_BITS_FLAG); + } + unflag(zoneX, zoneY) { + this.grid[this.index(zoneX, zoneY)] &= ~(1 << (zoneY & ZoneGrid.INT_BITS_FLAG)); + } + isFlagged(zoneX, zoneY, radius) { + const minX = Math.max(0, zoneX - radius); + const maxX = Math.min(ZoneGrid.GRID_SIZE - 1, zoneX + radius); + const minY = Math.max(0, zoneY - radius); + const maxY = Math.min(ZoneGrid.GRID_SIZE - 1, zoneY + radius); + const bits = ZoneGrid.INT_BITS_FLAG; + const startY = minY & ~bits; + const endY = (maxY >>> ZoneGrid.INT_BITS) << ZoneGrid.INT_BITS; + for (let x = minX; x <= maxX; x++) { + for (let y3 = startY; y3 <= endY; y3 += 32) { + const index = this.index(x, y3); + const line = this.grid[index]; + let trailingTrimmed = line; + if (y3 + bits > maxY) { + trailingTrimmed = line & ((1 << (maxY - y3 + 1)) - 1); + } + let leadingTrimmed = trailingTrimmed; + if (y3 < minY) { + leadingTrimmed = trailingTrimmed >>> (minY - y3); + } + if (leadingTrimmed !== 0) { + return true; + } + } + } + return false; + } +} + +// src/lostcity/engine/zone/ZoneMap.ts +class ZoneMap2 { + static zoneIndex(x, z2, level) { + return ((x >> 3) & 2047) | (((z2 >> 3) & 2047) << 11) | ((level & 3) << 22); + } + static unpackIndex(index) { + const x = (index & 2047) << 3; + const z2 = ((index >> 11) & 2047) << 3; + const level = index >> 22; + return {x, z: z2, level}; + } + zones; + grids; + constructor() { + this.zones = new Map(); + this.grids = new Map(); + } + zone(x, z2, level) { + const zoneIndex = ZoneMap2.zoneIndex(x, z2, level); + let zone = this.zones.get(zoneIndex); + if (typeof zone == 'undefined') { + zone = new Zone(zoneIndex); + this.zones.set(zoneIndex, zone); + } + return zone; + } + zoneByIndex(index) { + let zone = this.zones.get(index); + if (typeof zone == 'undefined') { + zone = new Zone(index); + this.zones.set(index, zone); + } + return zone; + } + grid(level) { + let grid = this.grids.get(level); + if (typeof grid == 'undefined') { + grid = new ZoneGrid(); + this.grids.set(level, grid); + } + return grid; + } + zoneCount() { + return this.zones.size; + } + locCount() { + let total = 0; + for (const zone of this.zones.values()) { + total += zone.totalLocs; + } + return total; + } + objCount() { + let total = 0; + for (const zone of this.zones.values()) { + total += zone.totalObjs; + } + return total; + } +} + +// src/lostcity/entity/BuildArea.ts +class BuildArea { + static INTERVAL = 10; + static PREFERRED_PLAYERS = 250; + static PREFERRED_NPCS = 255; + static PREFERRED_VIEW_DISTANCE = 15; + npcs; + players; + loadedZones; + activeZones; + extendedInfo; + appearances; + forceViewDistance = false; + viewDistance = BuildArea.PREFERRED_VIEW_DISTANCE; + lastResize = 0; + constructor() { + this.npcs = new Set(); + this.players = new Set(); + this.loadedZones = new Set(); + this.activeZones = new Set(); + this.extendedInfo = new Set(); + this.appearances = new Map(); + } + resize() { + if (this.forceViewDistance) { + return; + } + if (this.players.size >= BuildArea.PREFERRED_PLAYERS) { + if (this.viewDistance > 1) { + this.viewDistance--; + } + this.lastResize = 0; + return; + } + if (++this.lastResize >= BuildArea.INTERVAL) { + if (this.viewDistance < BuildArea.PREFERRED_VIEW_DISTANCE) { + this.viewDistance++; + } else { + this.lastResize = 0; + } + } + } + clearExtended() { + this.extendedInfo.clear(); + } + hasAppearance(pid, tick) { + const appearance = this.appearances.get(pid); + if (typeof appearance === 'undefined') { + return false; + } + return appearance === tick; + } + saveAppearance(pid, tick) { + this.appearances.set(pid, tick); + } + *getNearbyPlayers(uid, x, z2, originX, originZ) { + players: for (const zoneIndex of this.proximitySort(x, z2, this.activeZones)) { + for (const other of this.getNearby(World_default.getZoneIndex(zoneIndex).getAllPlayersSafe(), x, z2, originX, originZ, this.viewDistance)) { + if (this.players.size >= BuildArea.PREFERRED_PLAYERS) { + break players; + } + if (this.players.has(other.uid)) { + continue; + } + if (other.uid === uid) { + continue; + } + yield other; + } + } + } + *getNearbyNpcs(x, z2, originX, originZ) { + npcs: for (const zoneIndex of this.proximitySort(x, z2, this.activeZones)) { + for (const npc of this.getNearby(World_default.getZoneIndex(zoneIndex).getAllNpcsSafe(), x, z2, originX, originZ, 15)) { + if (this.npcs.size >= BuildArea.PREFERRED_NPCS) { + break npcs; + } + if (this.npcs.has(npc.nid)) { + continue; + } + yield npc; + } + } + } + *getNearby(entities, x, z2, originX, originZ, distance) { + const absLeftX = originX - 48; + const absRightX = originX + 48; + const absTopZ = originZ + 48; + const absBottomZ = originZ - 48; + for (const entity of entities) { + if (entity.x <= absLeftX || entity.x >= absRightX || entity.z >= absTopZ || entity.z <= absBottomZ) { + continue; + } + if (!Position.isWithinDistanceSW({x, z: z2}, entity, distance)) { + continue; + } + yield entity; + } + } + proximitySort(zoneX, zoneZ, zones) { + return Array.from(zones.values()) + .map(zoneIndex => this.zoneToDistance(zoneIndex, zoneX, zoneZ)) + .sort((a, b3) => a.distance - b3.distance) + .map(({zoneIndex}) => zoneIndex); + } + zoneToDistance(zoneIndex, zoneX, zoneZ) { + const pos = ZoneMap2.unpackIndex(zoneIndex); + const distance = Math.abs(pos.x - zoneX) + Math.abs(pos.z - zoneZ); + return {zoneIndex, distance}; + } +} + +// src/lostcity/entity/Player.ts +function getLevelByExp(exp) { + for (let i = 98; i >= 0; i--) { + if (exp >= levelExperience[i]) { + return Math.min(i + 2, 99); + } + } + return 1; +} +function getExpByLevel(level) { + return levelExperience[level - 2]; +} +var levelExperience = new Int32Array(99); +var acc = 0; +for (let i = 0; i < 99; i++) { + const level = i + 1; + const delta = Math.floor(level + Math.pow(2, level / 7) * 300); + acc += delta; + levelExperience[i] = Math.floor(acc / 4) * 10; +} + +class Player2 extends PathingEntity { + static APPEARANCE = 1; + static ANIM = 2; + static FACE_ENTITY = 4; + static SAY = 8; + static DAMAGE = 16; + static FACE_COORD = 32; + static CHAT = 64; + static BIG_UPDATE = 128; + static SPOTANIM = 256; + static EXACT_MOVE = 512; + static SKILLS = [ + 'attack', + 'defence', + 'strength', + 'hitpoints', + 'ranged', + 'prayer', + 'magic', + 'cooking', + 'woodcutting', + 'fletching', + 'fishing', + 'firemaking', + 'crafting', + 'smithing', + 'mining', + 'herblore', + 'agility', + 'thieving', + 'stat18', + 'stat19', + 'runecraft' + ]; + static DESIGN_BODY_COLORS = [ + [6798, 107, 10283, 16, 4797, 7744, 5799, 4634, 33697, 22433, 2983, 54193], + [8741, 12, 64030, 43162, 7735, 8404, 1701, 38430, 24094, 10153, 56621, 4783, 1341, 16578, 35003, 25239], + [25238, 8742, 12, 64030, 43162, 7735, 8404, 1701, 38430, 24094, 10153, 56621, 4783, 1341, 16578, 35003], + [4626, 11146, 6439, 12, 4758, 10270], + [4550, 4537, 5681, 5673, 5790, 6806, 8076, 4574] + ]; + save() { + const sav = Packet.alloc(1); + sav.p2(8196); + sav.p2(3); + sav.p2(this.x); + sav.p2(this.z); + sav.p1(this.level); + for (let i = 0; i < 7; i++) { + sav.p1(this.body[i]); + } + for (let i = 0; i < 5; i++) { + sav.p1(this.colors[i]); + } + sav.p1(this.gender); + sav.p2(this.runenergy); + sav.p4(this.playtime); + for (let i = 0; i < 21; i++) { + sav.p4(this.stats[i]); + sav.p1(this.levels[i]); + } + sav.p2(this.vars.length); + for (let i = 0; i < this.vars.length; i++) { + const type = VarPlayerType.get(i); + if (type.scope === VarPlayerType.SCOPE_PERM) { + sav.p4(this.vars[i]); + } else { + sav.p4(0); + } + } + let invCount = 0; + const invStartPos = sav.pos; + sav.p1(0); + for (const [typeId, inventory] of this.invs) { + const invType = InvType.get(typeId); + if (invType.scope !== InvType.SCOPE_PERM) { + continue; + } + sav.p2(typeId); + for (let slot = 0; slot < inventory.capacity; slot++) { + const obj = inventory.get(slot); + if (!obj) { + sav.p2(0); + continue; + } + sav.p2(obj.id + 1); + if (obj.count >= 255) { + sav.p1(255); + sav.p4(obj.count); + } else { + sav.p1(obj.count); + } + } + invCount++; + } + sav.data[invStartPos] = invCount; + sav.p1(this.afkZones.length); + for (let index = 0; index < this.afkZones.length; index++) { + sav.p4(this.afkZones[index]); + } + sav.p2(this.lastAfkZone); + sav.p4(Packet.getcrc(sav.data, 0, sav.pos)); + const safeName = fromBase37(this.username37); + sav.save(`data/players/${safeName}.sav`); + return sav; + } + username; + username37; + displayName; + body; + colors; + gender; + runenergy = 1e4; + lastRunEnergy = -1; + runweight; + playtime; + stats = new Int32Array(21); + levels = new Uint8Array(21); + vars; + varsString; + invs = new Map(); + pid = -1; + uid = -1; + lowMemory = false; + webClient = false; + combatLevel = 3; + headicons = 0; + appearance = null; + lastAppearance = 0; + baseLevels = new Uint8Array(21); + lastStats = new Int32Array(21); + lastLevels = new Uint8Array(21); + originX = -1; + originZ = -1; + buildArea = new BuildArea(); + lastMovement = 0; + basReadyAnim = -1; + basTurnOnSpot = -1; + basWalkForward = -1; + basWalkBackward = -1; + basWalkLeft = -1; + basWalkRight = -1; + basRunning = -1; + animProtect = 0; + logoutRequested = false; + invListeners = []; + allowDesign = false; + afkEventReady = false; + interactWalkTrigger = false; + highPriorityOut = new Stack(); + lowPriorityOut = new Stack(); + lastResponse = -1; + messageColor = null; + messageEffect = null; + messageType = null; + message = null; + delay = 0; + queue = new LinkList(); + weakQueue = new LinkList(); + engineQueue = new LinkList(); + cameraPackets = new LinkList(); + timers = new Map(); + modalState = 0; + modalTop = -1; + lastModalTop = -1; + modalBottom = -1; + lastModalBottom = -1; + modalSidebar = -1; + lastModalSidebar = -1; + refreshModalClose = false; + refreshModal = false; + modalSticky = -1; + overlaySide = new Array(14).fill(-1); + receivedFirstClose = false; + protect = false; + activeScript = null; + resumeButtons = []; + lastItem = -1; + lastSlot = -1; + lastUseItem = -1; + lastUseSlot = -1; + lastTargetSlot = -1; + lastCom = -1; + staffModLevel = 0; + heroPoints = new Array(16); + afkZones = new Int32Array(2); + lastAfkZone = 0; + constructor(username, username37) { + super(0, 3094, 3106, 1, 1, EntityLifeCycle_default.FOREVER, MoveRestrict_default.NORMAL, BlockWalk_default.NPC, MoveStrategy_default.SMART, Player2.FACE_COORD, Player2.FACE_ENTITY); + this.username = username; + this.username37 = username37; + this.displayName = toDisplayName(username); + this.vars = new Int32Array(VarPlayerType.count); + this.varsString = new Array(VarPlayerType.count); + this.body = [0, 10, 18, 26, 33, 36, 42]; + this.colors = [0, 0, 0, 0, 0]; + this.gender = 0; + this.runenergy = 1e4; + this.runweight = 0; + this.playtime = 0; + this.lastStats.fill(-1); + this.lastLevels.fill(-1); + } + resetHeroPoints() { + this.heroPoints = new Array(16); + this.heroPoints.fill({uid: -1, points: 0}); + } + addHero(uid, points) { + const index = this.heroPoints.findIndex(hero => hero && hero.uid === uid); + if (index !== -1) { + this.heroPoints[index].points += points; + return; + } + const emptyIndex = this.heroPoints.findIndex(hero => hero && hero.uid === -1); + if (emptyIndex !== -1) { + this.heroPoints[emptyIndex] = {uid, points}; + return; + } + } + findHero() { + this.heroPoints.sort((a, b3) => { + return b3.points - a.points; + }); + return this.heroPoints[0]?.uid ?? -1; + } + resetEntity(respawn) { + if (respawn) { + } + super.resetPathingEntity(); + this.repathed = false; + this.protect = false; + this.messageColor = null; + this.messageEffect = null; + this.messageType = null; + this.message = null; + } + onLogin() { + this.playerLog('Logging in'); + this.write(new IfClose()); + this.write(new UpdateUid192(this.pid)); + this.unsetMapFlag(); + this.write(new ResetAnims()); + this.resetHeroPoints(); + this.write(new ResetClientVarCache()); + for (let varp = 0; varp < this.vars.length; varp++) { + const type = VarPlayerType.get(varp); + const value = this.vars[varp]; + if (type.transmit) { + this.writeVarp(varp, value); + } + } + const loginTrigger = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.LOGIN, -1, -1); + if (loginTrigger) { + this.executeScript(ScriptRunner2.init(loginTrigger, this), true); + } + const moveTrigger = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.MOVE, -1, -1); + if (moveTrigger) { + const script = ScriptRunner2.init(moveTrigger, this); + this.runScript(script, true); + } + this.lastStepX = this.x - 1; + this.lastStepZ = this.z; + } + calculateRunWeight() { + this.runweight = 0; + const invs = this.invs.values(); + for (let i = 0; i < this.invs.size; i++) { + const inv = invs.next().value; + if (!inv) { + continue; + } + const invType = InvType.get(inv.type); + if (!invType || !invType.runweight) { + continue; + } + for (let slot = 0; slot < inv.capacity; slot++) { + const item = inv.get(slot); + if (!item) { + continue; + } + const type = ObjType.get(item.id); + if (!type || type.stackable) { + continue; + } + this.runweight += type.weight * item.count; + } + } + } + playerLog(message, ...args) {} + processEngineQueue() { + for (let request = this.engineQueue.head(); request !== null; request = this.engineQueue.next()) { + const delay = request.delay--; + if (this.canAccess() && delay <= 0) { + const script = ScriptRunner2.init(request.script, this, null, request.args); + this.executeScript(script, true); + request.unlink(); + } + } + } + updateMovement(repathAllowed = true) { + if (this.containsModalInterface()) { + this.recoverEnergy(false); + return false; + } + if (repathAllowed && this.target instanceof PathingEntity && !this.interacted && this.walktrigger === -1) { + this.pathToPathingTarget(); + } + if (this.hasWaypoints() && this.walktrigger !== -1 && !this.protect && !this.delayed()) { + const trigger = ScriptProvider.get(this.walktrigger); + this.walktrigger = -1; + if (trigger) { + const script = ScriptRunner2.init(trigger, this); + this.runScript(script, true); + } + } + if (this.moveSpeed !== MoveSpeed_default.INSTANT) { + this.moveSpeed = this.defaultMoveSpeed(); + if (this.basRunning === -1) { + this.moveSpeed = MoveSpeed_default.WALK; + } else if (this.getVar(VarPlayerType.TEMP_RUN)) { + this.moveSpeed = MoveSpeed_default.RUN; + } + } + if (!super.processMovement()) { + this.setVar(VarPlayerType.TEMP_RUN, 0); + } + const moved = this.lastX !== this.x || this.lastZ !== this.z; + if (moved) { + const trigger = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.MOVE, -1, -1); + if (trigger) { + this.runScript(ScriptRunner2.init(trigger, this), true); + } + } + this.drainEnergy(moved); + this.recoverEnergy(moved); + if (this.runenergy === 0) { + this.setVar(VarPlayerType.PLAYER_RUN, 0); + this.setVar(VarPlayerType.TEMP_RUN, 0); + } + return moved; + } + drainEnergy(moved) { + if (!moved || this.stepsTaken === 0) { + return; + } + if (!this.delayed() && this.moveSpeed === MoveSpeed_default.RUN && this.stepsTaken > 1) { + const weightKg = Math.floor(this.runweight / 1000); + const clampWeight = Math.min(Math.max(weightKg, 0), 64); + const loss = (67 + (67 * clampWeight) / 64) | 0; + this.runenergy = Math.max(this.runenergy - loss, 0); + } + } + recoverEnergy(moved) { + if (!this.delayed() && (!moved || this.moveSpeed !== MoveSpeed_default.RUN) && this.runenergy < 1e4) { + const recovered = ((this.baseLevels[PlayerStat_default.AGILITY] / 9) | 0) + 8; + this.runenergy = Math.min(this.runenergy + recovered, 1e4); + } + } + blockWalkFlag() { + return CollisionFlag.PLAYER; + } + defaultMoveSpeed() { + return this.getVar(VarPlayerType.PLAYER_RUN) ? MoveSpeed_default.RUN : MoveSpeed_default.WALK; + } + closeSticky() { + if (this.modalSticky !== -1) { + const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalSticky); + if (closeTrigger) { + this.enqueueScript(closeTrigger, 1 /* ENGINE */); + } + this.modalSticky = -1; + this.write(new TutorialOpenChat(-1)); + } + } + closeModal() { + if (!this.receivedFirstClose) { + this.receivedFirstClose = true; + return; + } + this.weakQueue.clear(); + if (!this.delayed()) { + this.protect = false; + } + if (this.modalState === 0) { + return; + } + if (this.modalTop !== -1) { + const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalTop); + if (closeTrigger) { + this.enqueueScript(closeTrigger, 1 /* ENGINE */); + } + this.modalTop = -1; + } + if (this.modalBottom !== -1) { + const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalBottom); + if (closeTrigger) { + this.enqueueScript(closeTrigger, 1 /* ENGINE */); + } + this.modalBottom = -1; + } + if (this.modalSidebar !== -1) { + const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalSidebar); + if (closeTrigger) { + this.enqueueScript(closeTrigger, 1 /* ENGINE */); + } + this.modalSidebar = -1; + } + this.modalState = 0; + this.refreshModalClose = true; + } + delayed() { + return this.delay > 0; + } + containsModalInterface() { + return (this.modalState & 1) === 1 || (this.modalState & 2) === 2 || (this.modalState & 16) === 16; + } + busy() { + return this.delayed() || this.containsModalInterface(); + } + canAccess() { + return !this.protect && !this.busy(); + } + enqueueScript(script, type = 0 /* NORMAL */, delay = 0, args = []) { + const request = new EntityQueueRequest(type, script, args, delay); + if (type === 1 /* ENGINE */) { + request.delay = 0; + this.engineQueue.addTail(request); + } else if (type === 2 /* WEAK */) { + this.weakQueue.addTail(request); + } else { + this.queue.addTail(request); + } + } + processQueues() { + let hasStrong = false; + for (let request = this.queue.head(); request !== null; request = this.queue.next()) { + if (request.type === 3 /* STRONG */) { + hasStrong = true; + break; + } + } + if (hasStrong) { + this.closeModal(); + } + this.processQueue(); + this.processWeakQueue(); + } + processQueue() { + for (let request = this.queue.head(); request !== null; request = this.queue.next()) { + if (request.type === 3 /* STRONG */) { + this.closeModal(); + } + const delay = request.delay--; + if (this.canAccess() && delay <= 0) { + const script = ScriptRunner2.init(request.script, this, null, request.args); + this.executeScript(script, true); + request.unlink(); + } + } + } + processWeakQueue() { + for (let request = this.weakQueue.head(); request !== null; request = this.weakQueue.next()) { + const delay = request.delay--; + if (this.canAccess() && delay <= 0) { + const script = ScriptRunner2.init(request.script, this, null, request.args); + this.executeScript(script, true); + request.unlink(); + } + } + } + setTimer(type, script, args = [], interval) { + const timerId = script.id; + const timer = { + type, + script, + args, + interval, + clock: interval + }; + this.timers.set(timerId, timer); + } + clearTimer(timerId) { + this.timers.delete(timerId); + } + processTimers(type) { + for (const timer of this.timers.values()) { + if (type !== timer.type) { + continue; + } + if (--timer.clock <= 0 && (timer.type === 1 /* SOFT */ || this.canAccess())) { + timer.clock = timer.interval; + const script = ScriptRunner2.init(timer.script, this, null, timer.args); + this.runScript(script, timer.type === 0 /* NORMAL */); + } + } + } + stopAction() { + this.clearPendingAction(); + this.unsetMapFlag(); + } + clearPendingAction() { + this.clearInteraction(); + this.closeModal(); + } + hasInteraction() { + return this.target !== null; + } + getOpTrigger() { + if (!this.target) { + return null; + } + let typeId = -1; + let categoryId = -1; + if (this.target instanceof Npc2 || this.target instanceof Loc || this.target instanceof Obj) { + const type = this.target instanceof Npc2 ? NpcType.get(this.target.type) : this.target instanceof Loc ? LocType.get(this.target.type) : ObjType.get(this.target.type); + typeId = type.id; + categoryId = type.category; + } + if (this.targetSubject.type !== -1) { + typeId = this.targetSubject.type; + } + if (this.targetSubject.com !== -1) { + typeId = this.targetSubject.com; + } + return ScriptProvider.getByTrigger(this.targetOp + 7, typeId, categoryId) ?? null; + } + getApTrigger() { + if (!this.target) { + return null; + } + let typeId = -1; + let categoryId = -1; + if (this.target instanceof Npc2 || this.target instanceof Loc || this.target instanceof Obj) { + const type = this.target instanceof Npc2 ? NpcType.get(this.target.type) : this.target instanceof Loc ? LocType.get(this.target.type) : ObjType.get(this.target.type); + typeId = type.id; + categoryId = type.category; + } + if (this.targetSubject.type !== -1) { + typeId = this.targetSubject.type; + } + if (this.targetSubject.com !== -1) { + typeId = this.targetSubject.com; + } + return ScriptProvider.getByTrigger(this.targetOp, typeId, categoryId) ?? null; + } + processInteraction() { + if (this.target === null || !this.canAccess()) { + this.updateMovement(); + return; + } + if (this.target.level !== this.level) { + this.clearInteraction(); + this.unsetMapFlag(); + return; + } + if (this.target instanceof Npc2 && (typeof World_default.getNpc(this.target.nid) === 'undefined' || this.target.delayed())) { + this.clearInteraction(); + this.unsetMapFlag(); + return; + } + if (this.target instanceof Npc2 && this.targetSubject.type !== -1 && World_default.getNpcByUid((this.targetSubject.type << 16) | this.target.nid) === null) { + this.clearInteraction(); + this.unsetMapFlag(); + return; + } + if (this.target instanceof Obj && World_default.getObj(this.target.x, this.target.z, this.level, this.target.type, this.pid) === null) { + this.clearInteraction(); + this.unsetMapFlag(); + return; + } + if (this.target instanceof Loc && World_default.getLoc(this.target.x, this.target.z, this.level, this.target.type) === null) { + this.clearInteraction(); + this.unsetMapFlag(); + return; + } + if (this.target instanceof Player2 && World_default.getPlayerByUid(this.target.uid) === null) { + this.clearInteraction(); + this.unsetMapFlag(); + return; + } + if (this.targetOp === ServerTriggerType_default.APPLAYER3 || this.targetOp === ServerTriggerType_default.OPPLAYER3) { + const moved2 = this.updateMovement(false); + if (moved2) { + this.alreadyFacedEntity = false; + this.alreadyFacedCoord = false; + this.lastMovement = World_default.currentTick + 1; + } + return; + } + const opTrigger = this.getOpTrigger(); + const apTrigger = this.getApTrigger(); + if (opTrigger && this.target instanceof PathingEntity && this.inOperableDistance(this.target)) { + const target = this.target; + this.target = null; + this.executeScript(ScriptRunner2.init(opTrigger, this, target), true); + if (this.target === null) { + this.unsetMapFlag(); + } + this.interacted = true; + this.clearWaypoints(); + } else if (apTrigger && this.inApproachDistance(this.apRange, this.target)) { + const target = this.target; + this.target = null; + this.executeScript(ScriptRunner2.init(apTrigger, this, target), true); + if (this.apRangeCalled) { + this.target = target; + } else { + this.clearWaypoints(); + this.interacted = true; + } + if (this.target === null) { + this.unsetMapFlag(); + } + } else if (this.target instanceof PathingEntity && this.inOperableDistance(this.target)) { + if (Environment_default.NODE_DEBUG && !opTrigger && !apTrigger) { + let debugname = '_'; + if (this.target instanceof Npc2) { + if ((this.targetSubject.com !== -1 && this.targetOp === ServerTriggerType_default.APNPCT) || this.targetOp === ServerTriggerType_default.OPNPCT) { + debugname = Component.get(this.targetSubject.com)?.comName ?? this.targetSubject.toString(); + } else { + debugname = NpcType.get(this.target.type)?.debugname ?? this.target.type.toString(); + } + } else if (this.target instanceof Loc) { + debugname = LocType.get(this.target.type)?.debugname ?? this.target.type.toString(); + } else if (this.target instanceof Obj) { + debugname = ObjType.get(this.target.type)?.debugname ?? this.target.type.toString(); + } else if ( + (this.targetSubject.com !== -1 && this.targetOp === ServerTriggerType_default.APNPCT) || + this.targetOp === ServerTriggerType_default.APPLAYERT || + this.targetOp === ServerTriggerType_default.APLOCT || + this.targetOp === ServerTriggerType_default.APOBJT + ) { + debugname = Component.get(this.targetSubject.com)?.comName ?? this.targetSubject.toString(); + } else if (this.targetSubject.type !== -1) { + debugname = ObjType.get(this.targetSubject.type)?.debugname ?? this.targetSubject.toString(); + } + this.messageGame(`No trigger for [${ServerTriggerType_default[this.targetOp + 7].toLowerCase()},${debugname}]`); + } + this.target = null; + this.messageGame('Nothing interesting happens.'); + this.interacted = true; + this.clearWaypoints(); + } + const moved = this.updateMovement(); + if (moved) { + this.alreadyFacedEntity = false; + this.alreadyFacedCoord = false; + this.lastMovement = World_default.currentTick + 1; + } + if (this.target && (!this.interacted || this.apRangeCalled)) { + this.interacted = false; + if (opTrigger && (this.target instanceof PathingEntity || !moved) && this.inOperableDistance(this.target)) { + const target = this.target; + this.target = null; + this.executeScript(ScriptRunner2.init(opTrigger, this, target), true); + if (this.target === null) { + this.unsetMapFlag(); + } + this.interacted = true; + this.clearWaypoints(); + } else if (apTrigger && this.inApproachDistance(this.apRange, this.target)) { + this.apRangeCalled = false; + const target = this.target; + this.target = null; + this.executeScript(ScriptRunner2.init(apTrigger, this, target), true); + if (this.apRangeCalled) { + this.target = target; + } else { + this.clearWaypoints(); + this.interacted = true; + } + if (this.target === null) { + this.unsetMapFlag(); + } + } else if ((this.target instanceof PathingEntity || !moved) && this.inOperableDistance(this.target)) { + if (!Environment_default.NODE_PRODUCTION && !opTrigger && !apTrigger) { + let debugname = '_'; + if (this.target instanceof Npc2) { + debugname = NpcType.get(this.target.type)?.debugname ?? this.target.type.toString(); + } else if (this.target instanceof Loc) { + debugname = LocType.get(this.target.type)?.debugname ?? this.target.type.toString(); + } else if (this.target instanceof Obj) { + debugname = ObjType.get(this.target.type)?.debugname ?? this.target.type.toString(); + } else if ( + (this.targetSubject.com !== -1 && this.targetOp === ServerTriggerType_default.APNPCT) || + this.targetOp === ServerTriggerType_default.APPLAYERT || + this.targetOp === ServerTriggerType_default.APLOCT || + this.targetOp === ServerTriggerType_default.APOBJT + ) { + debugname = Component.get(this.targetSubject.com)?.comName ?? this.targetSubject.toString(); + } else if (this.targetSubject.type !== -1) { + debugname = ObjType.get(this.targetSubject.type)?.debugname ?? this.targetSubject.toString(); + } + this.messageGame(`No trigger for [${ServerTriggerType_default[this.targetOp + 7].toLowerCase()},${debugname}]`); + } + this.target = null; + this.messageGame('Nothing interesting happens.'); + this.interacted = true; + this.clearWaypoints(); + } + } + if (!this.interactWalkTrigger && this.walktrigger !== -1 && !this.protect && !this.delayed()) { + const trigger = ScriptProvider.get(this.walktrigger); + this.walktrigger = -1; + if (trigger) { + const script = ScriptRunner2.init(trigger, this); + this.interactWalkTrigger = true; + this.unsetMapFlag(); + this.runScript(script, true); + } + } + if (!this.interacted && !this.hasWaypoints() && !moved) { + this.messageGame("I can't reach that!"); + this.clearInteraction(); + } + if (this.interacted && !this.apRangeCalled && this.target === null) { + this.clearInteraction(); + } + } + getAppearanceInSlot(slot) { + let part = -1; + if (slot === 8) { + part = this.body[0]; + } else if (slot === 11) { + part = this.body[1]; + } else if (slot === 4) { + part = this.body[2]; + } else if (slot === 6) { + part = this.body[3]; + } else if (slot === 9) { + part = this.body[4]; + } else if (slot === 7) { + part = this.body[5]; + } else if (slot === 10) { + part = this.body[6]; + } + if (part === -1) { + return 0; + } else { + return 256 + part; + } + } + getCombatLevel() { + const base = 0.25 * (this.baseLevels[PlayerStat_default.DEFENCE] + this.baseLevels[PlayerStat_default.HITPOINTS] + Math.floor(this.baseLevels[PlayerStat_default.PRAYER] / 2)); + const melee = 0.325 * (this.baseLevels[PlayerStat_default.ATTACK] + this.baseLevels[PlayerStat_default.STRENGTH]); + const range = 0.325 * (Math.floor(this.baseLevels[PlayerStat_default.RANGED] / 2) + this.baseLevels[PlayerStat_default.RANGED]); + const magic = 0.325 * (Math.floor(this.baseLevels[PlayerStat_default.MAGIC] / 2) + this.baseLevels[PlayerStat_default.MAGIC]); + return Math.floor(base + Math.max(melee, range, magic)); + } + generateAppearance(inv) { + const stream = Packet.alloc(0); + stream.p1(this.gender); + stream.p1(this.headicons); + const skippedSlots = []; + let worn = this.getInventory(inv); + if (!worn) { + worn = new Inventory(InvType.WORN, 0); + } + for (let i = 0; i < worn.capacity; i++) { + const equip = worn.get(i); + if (!equip) { + continue; + } + const config3 = ObjType.get(equip.id); + if (config3.wearpos2 !== -1) { + if (skippedSlots.indexOf(config3.wearpos2) === -1) { + skippedSlots.push(config3.wearpos2); + } + } + if (config3.wearpos3 !== -1) { + if (skippedSlots.indexOf(config3.wearpos3) === -1) { + skippedSlots.push(config3.wearpos3); + } + } + } + for (let slot = 0; slot < 12; slot++) { + if (skippedSlots.indexOf(slot) !== -1) { + stream.p1(0); + continue; + } + const equip = worn.get(slot); + if (!equip) { + const appearanceValue = this.getAppearanceInSlot(slot); + if (appearanceValue < 1) { + stream.p1(0); + } else { + stream.p2(appearanceValue); + } + } else { + stream.p2(512 + equip.id); + } + } + for (let i = 0; i < this.colors.length; i++) { + stream.p1(this.colors[i]); + } + stream.p2(this.basReadyAnim); + stream.p2(this.basTurnOnSpot); + stream.p2(this.basWalkForward); + stream.p2(this.basWalkBackward); + stream.p2(this.basWalkLeft); + stream.p2(this.basWalkRight); + stream.p2(this.basRunning); + stream.p8(this.username37); + stream.p1(this.combatLevel); + this.mask |= Player2.APPEARANCE; + this.appearance = new Uint8Array(stream.pos); + stream.pos = 0; + stream.gdata(this.appearance, 0, this.appearance.length); + stream.release(); + this.lastAppearance = World_default.currentTick; + } + getInventoryFromListener(listener) { + if (listener.source === -1) { + return World_default.getInventory(listener.type); + } else { + const player = World_default.getPlayerByUid(listener.source); + if (!player) { + return null; + } + return player.getInventory(listener.type); + } + } + getInventory(inv) { + if (inv === -1) { + return null; + } + const invType = InvType.get(inv); + let container = null; + if (!invType) { + return null; + } + if (invType.scope === InvType.SCOPE_SHARED) { + container = World_default.getInventory(inv); + } else { + container = this.invs.get(inv); + if (!container) { + container = Inventory.fromType(inv); + this.invs.set(inv, container); + } + } + return container; + } + invListenOnCom(inv, com, source) { + if (inv === -1) { + return; + } + const index = this.invListeners.findIndex(l => l.type === inv && l.com === com); + if (index !== -1) { + return; + } + const invType = InvType.get(inv); + if (invType.scope === InvType.SCOPE_SHARED) { + source = -1; + } + this.invListeners.push({type: inv, com, source, firstSeen: true}); + } + invStopListenOnCom(com) { + const index = this.invListeners.findIndex(l => l.com === com); + if (index === -1) { + return; + } + this.invListeners.splice(index, 1); + this.write(new UpdateInvStopTransmit(com)); + } + invGetSlot(inv, slot) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invGetSlot: Invalid inventory type: ' + inv); + } + if (!container.validSlot(slot)) { + throw new Error('invGetSlot: Invalid slot: ' + slot); + } + return container.get(slot); + } + invClear(inv) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invClear: Invalid inventory type: ' + inv); + } + container.removeAll(); + } + invAdd(inv, obj, count, assureFullInsertion = true) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invAdd: Invalid inventory type: ' + inv); + } + const transaction = container.add(obj, count, -1, assureFullInsertion); + return transaction.completed; + } + invSet(inv, obj, count, slot) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invSet: Invalid inventory type: ' + inv); + } + if (!container.validSlot(slot)) { + throw new Error('invSet: Invalid slot: ' + slot); + } + container.set(slot, {id: obj, count}); + } + invDel(inv, obj, count, beginSlot = -1) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invDel: Invalid inventory type: ' + inv); + } + if (beginSlot < -1 || beginSlot >= this.invSize(inv)) { + throw new Error('invDel: Invalid beginSlot: ' + beginSlot); + } + const transaction = container.remove(obj, count, beginSlot); + return transaction.completed; + } + invDelSlot(inv, slot) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invDelSlot: Invalid inventory type: ' + inv); + } + if (!container.validSlot(slot)) { + throw new Error('invDelSlot: Invalid slot: ' + slot); + } + container.delete(slot); + } + invSize(inv) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invSize: Invalid inventory type: ' + inv); + } + return container.capacity; + } + invTotal(inv, obj) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invTotal: Invalid inventory type: ' + inv); + } + return container.getItemCount(obj); + } + invFreeSpace(inv) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invFreeSpace: Invalid inventory type: ' + inv); + } + return container.freeSlotCount; + } + invItemSpace(inv, obj, count, size) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invItemSpace: Invalid inventory type: ' + inv); + } + const objType = ObjType.get(obj); + let uncert = obj; + if (objType.certtemplate >= 0 && objType.certlink >= 0) { + uncert = objType.certlink; + } + if (objType.stackable || uncert != obj || container.stackType == Inventory.ALWAYS_STACK) { + const stockObj = InvType.get(inv).stockobj?.includes(obj) === true; + if (this.invTotal(inv, obj) == 0 && this.invFreeSpace(inv) == 0 && !stockObj) { + return count; + } + return Math.max(0, count - (Inventory.STACK_LIMIT - this.invTotal(inv, obj))); + } + return Math.max(0, count - (this.invFreeSpace(inv) - (this.invSize(inv) - size))); + } + invMoveToSlot(fromInv, toInv, fromSlot, toSlot) { + const from = this.getInventory(fromInv); + if (!from) { + throw new Error('invMoveToSlot: Invalid inventory type: ' + fromInv); + } + if (!from.validSlot(fromSlot)) { + throw new Error('invMoveToSlot: Invalid from slot: ' + fromSlot); + } + const to = this.getInventory(toInv); + if (!to) { + throw new Error('invMoveToSlot: Invalid inventory type: ' + toInv); + } + if (!to.validSlot(toSlot)) { + throw new Error('invMoveToSlot: Invalid to slot: ' + toSlot); + } + const fromObj = this.invGetSlot(fromInv, fromSlot); + if (!fromObj) { + throw new Error(`invMoveToSlot: Invalid from obj was null. This means the obj does not exist at this slot: ${fromSlot}`); + } + const toObj = this.invGetSlot(toInv, toSlot); + this.invSet(toInv, fromObj.id, fromObj.count, toSlot); + if (toObj) { + this.invSet(fromInv, toObj.id, toObj.count, fromSlot); + } else { + this.invDelSlot(fromInv, fromSlot); + } + } + invMoveFromSlot(fromInv, toInv, fromSlot) { + const from = this.getInventory(fromInv); + if (!from) { + throw new Error('invMoveFromSlot: Invalid inventory type: ' + fromInv); + } + const to = this.getInventory(toInv); + if (!to) { + throw new Error('invMoveFromSlot: Invalid inventory type: ' + toInv); + } + if (!from.validSlot(fromSlot)) { + throw new Error('invMoveFromSlot: Invalid from slot: ' + fromSlot); + } + const fromObj = this.invGetSlot(fromInv, fromSlot); + if (!fromObj) { + throw new Error(`invMoveFromSlot: Invalid from obj was null. This means the obj does not exist at this slot: ${fromSlot}`); + } + return { + overflow: fromObj.count - this.invAdd(toInv, fromObj.id, fromObj.count), + fromObj: fromObj.id + }; + } + invTotalCat(inv, category) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invTotalCat: Invalid inventory type: ' + inv); + } + return container.itemsFiltered.filter(obj => ObjType.get(obj.id).category == category).reduce((count, obj) => count + obj.count, 0); + } + _invTotalParam(inv, param, stack) { + const container = this.getInventory(inv); + if (!container) { + throw new Error('invTotalParam: Invalid inventory type: ' + inv); + } + const paramType = ParamType.get(param); + let total = 0; + for (let slot = 0; slot < container.capacity; slot++) { + const item = container.items[slot]; + if (!item || item.id < 0 || item.id >= ObjType.count) { + continue; + } + const obj = ObjType.get(item.id); + const value = ParamHelper.getIntParam(paramType.id, obj, paramType.defaultInt); + if (stack) { + total += item.count * value; + } else { + total += value; + } + } + return total; + } + invTotalParam(inv, param) { + return this._invTotalParam(inv, param, false); + } + invTotalParamStack(inv, param) { + return this._invTotalParam(inv, param, true); + } + getVar(id) { + const varp = VarPlayerType.get(id); + return varp.type === ScriptVarType.STRING ? this.varsString[varp.id] : this.vars[varp.id]; + } + setVar(id, value) { + const varp = VarPlayerType.get(id); + if (varp.type === ScriptVarType.STRING && typeof value === 'string') { + this.varsString[varp.id] = value; + } else if (typeof value === 'number') { + this.vars[varp.id] = value; + if (varp.transmit) { + this.writeVarp(id, value); + } + } + } + writeVarp(id, value) { + if (value >= -128 && value <= 127) { + this.write(new VarpSmall(id, value)); + } else { + this.write(new VarpLarge(id, value)); + } + } + addXp(stat, xp) { + if (xp < 0) { + throw new Error(`Invalid xp parameter for addXp call: Stat was: ${stat}, Exp was: ${xp}`); + } + if (xp == 0) { + return; + } + const multi = Number(Environment_default.NODE_XPRATE) || 1; + this.stats[stat] += xp * multi; + if (this.stats[stat] > 2000000000) { + this.stats[stat] = 2000000000; + } + const before = this.baseLevels[stat]; + if (this.levels[stat] === this.baseLevels[stat]) { + this.levels[stat] = getLevelByExp(this.stats[stat]); + } + this.baseLevels[stat] = getLevelByExp(this.stats[stat]); + if (this.baseLevels[stat] > before) { + if (this.levels[stat] < before) { + this.levels[stat] += 1; + } + const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.LEVELUP, stat, -1); + if (script) { + this.enqueueScript(script, 1 /* ENGINE */); + } + } + if (this.combatLevel != this.getCombatLevel()) { + this.combatLevel = this.getCombatLevel(); + this.generateAppearance(InvType.WORN); + } + } + setLevel(stat, level) { + level = Math.min(99, Math.max(1, level)); + this.baseLevels[stat] = level; + this.levels[stat] = level; + this.stats[stat] = getExpByLevel(level); + if (this.getCombatLevel() != this.combatLevel) { + this.combatLevel = this.getCombatLevel(); + this.generateAppearance(InvType.WORN); + } + } + playAnimation(anim, delay) { + if (anim >= SeqType.count || this.animProtect) { + return; + } + if (anim == -1 || this.animId == -1 || SeqType.get(anim).priority > SeqType.get(this.animId).priority || SeqType.get(this.animId).priority === 0) { + this.animId = anim; + this.animDelay = delay; + this.mask |= Player2.ANIM; + } + } + spotanim(spotanim, height, delay) { + this.graphicId = spotanim; + this.graphicHeight = height; + this.graphicDelay = delay; + this.mask |= Player2.SPOTANIM; + } + applyDamage(damage, type) { + this.damageTaken = damage; + this.damageType = type; + const current = this.levels[PlayerStat_default.HITPOINTS]; + if (current - damage <= 0) { + this.levels[PlayerStat_default.HITPOINTS] = 0; + this.damageTaken = current; + } else { + this.levels[PlayerStat_default.HITPOINTS] = current - damage; + } + this.mask |= Player2.DAMAGE; + } + say(message) { + this.chat = message; + this.mask |= Player2.SAY; + } + faceSquare(x, z2) { + this.faceX = x * 2 + 1; + this.faceZ = z2 * 2 + 1; + this.orientation = Position.face(this.x, this.z, x, z2); + this.mask |= Player2.FACE_COORD; + } + playSong(name) { + name = name.toLowerCase().replaceAll(' ', '_'); + if (!name) { + return; + } + const song = PRELOADED.get(name + '.mid'); + const crc = PRELOADED_CRC.get(name + '.mid'); + if (song && crc) { + const length = song.length; + this.write(new MidiSong(name, crc, length)); + } + } + playJingle(delay, name) { + name = name.toLowerCase().replaceAll('_', ' '); + if (!name) { + return; + } + const jingle = PRELOADED.get(name + '.mid'); + if (jingle) { + this.write(new MidiJingle(delay, jingle)); + } + } + openMainModal(com) { + if (this.modalState & 4) { + this.write(new IfClose()); + this.modalState &= ~4; + this.modalSidebar = -1; + } + this.modalState |= 1; + this.modalTop = com; + this.refreshModal = true; + } + openChat(com) { + this.modalState |= 2; + this.modalBottom = com; + this.refreshModal = true; + } + openSideOverlay(com) { + this.modalState |= 4; + this.modalSidebar = com; + this.refreshModal = true; + } + openChatSticky(com) { + this.write(new TutorialOpenChat(com)); + this.modalState |= 8; + this.modalSticky = com; + } + openMainModalSideOverlay(top, side) { + this.modalState |= 1; + this.modalTop = top; + this.modalState |= 4; + this.modalSidebar = side; + this.refreshModal = true; + } + exactMove(startX, startZ, endX, endZ, startCycle, endCycle, direction) { + this.exactStartX = startX; + this.exactStartZ = startZ; + this.exactEndX = endX; + this.exactEndZ = endZ; + this.exactMoveStart = startCycle; + this.exactMoveEnd = endCycle; + this.exactMoveDirection = direction; + this.mask |= Player2.EXACT_MOVE; + this.x = endX; + this.z = endZ; + this.lastStepX = this.x - 1; + this.lastStepZ = this.z; + } + setTab(com, tab) { + this.overlaySide[tab] = com; + this.write(new IfOpenSideOverlay(com, tab)); + } + isComponentVisible(com) { + return this.modalTop === com.rootLayer || this.modalBottom === com.rootLayer || this.modalSidebar === com.rootLayer || this.overlaySide.findIndex(l => l === com.rootLayer) !== -1 || this.modalSticky === com.rootLayer; + } + updateAfkZones() { + this.lastAfkZone = Math.min(1000, this.lastAfkZone + 1); + if (this.withinAfkZone()) { + return; + } + const coord = Position.packCoord(0, this.x - 10, this.z - 10); + if (this.moveSpeed === MoveSpeed_default.INSTANT && this.jump) { + this.afkZones[1] = coord; + } else { + this.afkZones[1] = this.afkZones[0]; + } + this.afkZones[0] = coord; + this.lastAfkZone = 0; + } + zonesAfk() { + return this.lastAfkZone === 1000; + } + withinAfkZone() { + const size = 21; + for (let index = 0; index < this.afkZones.length; index++) { + const coord = Position.unpackCoord(this.afkZones[index]); + if (Position.intersects(this.x, this.z, this.width, this.length, coord.x, coord.z, size, size)) { + return true; + } + } + return false; + } + isInWilderness() { + if (this.x >= 2944 && this.x < 3392 && this.z >= 3520 && this.z < 6400) { + return true; + } else if (this.x >= 2944 && this.x < 3392 && this.z >= 9920 && this.z < 12800) { + return true; + } else { + return false; + } + } + runScript(script, protect = false, force = false) { + if (!force && protect && (this.protect || this.delayed())) { + return -1; + } + if (protect) { + script.pointerAdd(ScriptPointer_default.ProtectedActivePlayer); + this.protect = true; + } + const state = ScriptRunner2.execute(script); + if (protect) { + this.protect = false; + } + if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer) && script._activePlayer) { + script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer); + script._activePlayer.protect = false; + } + if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer2) && script._activePlayer2) { + script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer2); + script._activePlayer2.protect = false; + } + return state; + } + executeScript(script, protect = false, force = false) { + const state = this.runScript(script, protect, force); + if (state === -1) { + return; + } + if (state !== ScriptState.FINISHED && state !== ScriptState.ABORTED) { + if (state === ScriptState.WORLD_SUSPENDED) { + World_default.enqueueScript(script, script.popInt()); + } else if (state === ScriptState.NPC_SUSPENDED) { + script.activeNpc.activeScript = script; + } else { + script.activePlayer.activeScript = script; + script.activePlayer.protect = protect; + } + } else if (script === this.activeScript) { + this.activeScript = null; + if ((this.modalState & 1) == 0) { + this.closeModal(); + } + } + } + wrappedMessageGame(mes) { + const font = FontType.get(1); + const lines = font.split(mes, 456); + for (const line of lines) { + this.messageGame(line); + } + } + write(message) { + if (message.priority === ServerProtPriority.HIGH) { + this.highPriorityOut.push(message); + } else { + this.lowPriorityOut.push(message); + } + } + unsetMapFlag() { + this.clearWaypoints(); + this.write(new UnsetMapFlag()); + } + hintNpc(nid) { + this.write(new HintArrow(1, nid, 0, 0, 0, 0)); + } + hintTile(offset, x, z2, height) { + this.write(new HintArrow(offset, 0, 0, x, z2, height)); + } + hintPlayer(pid) { + this.write(new HintArrow(10, 0, pid, 0, 0, 0)); + } + stopHint() { + this.write(new HintArrow(-1, 0, 0, 0, 0, 0)); + } + lastLoginInfo(lastLoginIp, daysSinceLogin, daysSinceRecoveryChange, unreadMessageCount) { + this.write(new LastLoginInfo(lastLoginIp, daysSinceLogin, daysSinceRecoveryChange, unreadMessageCount)); + this.modalState |= 16; + } + logout() {} + terminate() {} + messageGame(msg) { + this.write(new MessageGame(msg)); + } +} + +// src/lostcity/network/225/incoming/prot/ClientProt.ts +class ClientProt { + index; + id; + length; + static all = []; + static byId = []; + static REBUILD_GETMAPS = new ClientProt(4, 150, -1); + static NO_TIMEOUT = new ClientProt(6, 108, 0); + static IDLE_TIMER = new ClientProt(30, 70, 0); + static EVENT_TRACKING = new ClientProt(34, 81, -2); + static EVENT_CAMERA_POSITION = new ClientProt(35, 189, 6); + static ANTICHEAT_OPLOGIC1 = new ClientProt(60, 7, 4); + static ANTICHEAT_OPLOGIC2 = new ClientProt(61, 88, 4); + static ANTICHEAT_OPLOGIC3 = new ClientProt(62, 30, 3); + static ANTICHEAT_OPLOGIC4 = new ClientProt(63, 176, 2); + static ANTICHEAT_OPLOGIC5 = new ClientProt(64, 220, 0); + static ANTICHEAT_OPLOGIC6 = new ClientProt(65, 66, 4); + static ANTICHEAT_OPLOGIC7 = new ClientProt(66, 17, 4); + static ANTICHEAT_OPLOGIC8 = new ClientProt(67, 2, 2); + static ANTICHEAT_OPLOGIC9 = new ClientProt(68, 238, 1); + static ANTICHEAT_CYCLELOGIC1 = new ClientProt(70, 233, 1); + static ANTICHEAT_CYCLELOGIC2 = new ClientProt(71, 146, -1); + static ANTICHEAT_CYCLELOGIC3 = new ClientProt(74, 215, 3); + static ANTICHEAT_CYCLELOGIC4 = new ClientProt(72, 236, 4); + static ANTICHEAT_CYCLELOGIC5 = new ClientProt(75, 85, 0); + static ANTICHEAT_CYCLELOGIC6 = new ClientProt(73, 219, -1); + static OPOBJ1 = new ClientProt(80, 140, 6); + static OPOBJ2 = new ClientProt(81, 40, 6); + static OPOBJ3 = new ClientProt(82, 200, 6); + static OPOBJ4 = new ClientProt(83, 178, 6); + static OPOBJ5 = new ClientProt(84, 247, 6); + static OPOBJT = new ClientProt(88, 138, 8); + static OPOBJU = new ClientProt(89, 239, 12); + static OPNPC1 = new ClientProt(100, 194, 2); + static OPNPC2 = new ClientProt(101, 8, 2); + static OPNPC3 = new ClientProt(102, 27, 2); + static OPNPC4 = new ClientProt(103, 113, 2); + static OPNPC5 = new ClientProt(104, 100, 2); + static OPNPCT = new ClientProt(108, 134, 4); + static OPNPCU = new ClientProt(109, 202, 8); + static OPLOC1 = new ClientProt(120, 245, 6); + static OPLOC2 = new ClientProt(121, 172, 6); + static OPLOC3 = new ClientProt(122, 96, 6); + static OPLOC4 = new ClientProt(123, 97, 6); + static OPLOC5 = new ClientProt(124, 116, 6); + static OPLOCT = new ClientProt(128, 9, 8); + static OPLOCU = new ClientProt(129, 75, 12); + static OPPLAYER1 = new ClientProt(140, 164, 2); + static OPPLAYER2 = new ClientProt(141, 53, 2); + static OPPLAYER3 = new ClientProt(142, 185, 2); + static OPPLAYER4 = new ClientProt(143, 206, 2); + static OPPLAYERT = new ClientProt(148, 177, 4); + static OPPLAYERU = new ClientProt(149, 248, 8); + static OPHELD1 = new ClientProt(160, 195, 6); + static OPHELD2 = new ClientProt(161, 71, 6); + static OPHELD3 = new ClientProt(162, 133, 6); + static OPHELD4 = new ClientProt(163, 157, 6); + static OPHELD5 = new ClientProt(164, 211, 6); + static OPHELDT = new ClientProt(168, 48, 8); + static OPHELDU = new ClientProt(169, 130, 12); + static INV_BUTTON1 = new ClientProt(190, 31, 6); + static INV_BUTTON2 = new ClientProt(191, 59, 6); + static INV_BUTTON3 = new ClientProt(192, 212, 6); + static INV_BUTTON4 = new ClientProt(193, 38, 6); + static INV_BUTTON5 = new ClientProt(194, 6, 6); + static IF_BUTTON = new ClientProt(200, 155, 2); + static RESUME_PAUSEBUTTON = new ClientProt(201, 235, 2); + static CLOSE_MODAL = new ClientProt(202, 231, 0); + static RESUME_P_COUNTDIALOG = new ClientProt(203, 237, 4); + static TUTORIAL_CLICKSIDE = new ClientProt(204, 175, 1); + static MOVE_OPCLICK = new ClientProt(242, 93, -1); + static BUG_REPORT = new ClientProt(243, 190, 10); + static MOVE_MINIMAPCLICK = new ClientProt(244, 165, -1); + static INV_BUTTOND = new ClientProt(245, 159, 6); + static IGNORELIST_DEL = new ClientProt(246, 171, 8); + static IGNORELIST_ADD = new ClientProt(247, 79, 8); + static IF_PLAYERDESIGN = new ClientProt(248, 52, 13); + static CHAT_SETMODE = new ClientProt(249, 244, 3); + static MESSAGE_PRIVATE = new ClientProt(250, 148, -1); + static FRIENDLIST_DEL = new ClientProt(251, 11, 8); + static FRIENDLIST_ADD = new ClientProt(252, 118, 8); + static CLIENT_CHEAT = new ClientProt(253, 4, -1); + static MESSAGE_PUBLIC = new ClientProt(254, 158, -1); + static MOVE_GAMECLICK = new ClientProt(255, 181, -1); + constructor(index, id, length) { + this.index = index; + this.id = id; + this.length = length; + ClientProt.all[index] = this; + ClientProt.byId[id] = this; + } +} + +// src/lostcity/network/incoming/codec/MessageDecoder.ts +class MessageDecoder {} + +// src/lostcity/network/incoming/IncomingMessage.ts +class IncomingMessage {} + +// src/lostcity/network/incoming/prot/ClientProtCategory.ts +class ClientProtCategory { + id; + limit; + static CLIENT_EVENT = new ClientProtCategory(0, 20); + static USER_EVENT = new ClientProtCategory(1, 5); + constructor(id, limit) { + this.id = id; + this.limit = limit; + } +} + +// src/lostcity/network/incoming/model/ClientCheat.ts +class ClientCheat extends IncomingMessage { + input; + category = ClientProtCategory.USER_EVENT; + constructor(input) { + super(); + this.input = input; + } +} + +// src/lostcity/network/225/incoming/codec/ClientCheatDecoder.ts +class ClientCheatDecoder extends MessageDecoder { + prot = ClientProt.CLIENT_CHEAT; + decode(buf) { + const input = buf.gjstr(); + return new ClientCheat(input); + } +} + +// src/lostcity/network/incoming/model/CloseModal.ts +class CloseModal extends IncomingMessage { + category = ClientProtCategory.USER_EVENT; +} + +// src/lostcity/network/225/incoming/codec/CloseModalDecoder.ts +class CloseModalDecoder extends MessageDecoder { + prot = ClientProt.CLOSE_MODAL; + decode() { + return new CloseModal(); + } +} + +// src/lostcity/network/incoming/model/IdleTimer.ts +class IdleTimer extends IncomingMessage { + category = ClientProtCategory.CLIENT_EVENT; +} + +// src/lostcity/network/225/incoming/codec/IdleTimerDecoder.ts +class IdleTimerDecoder extends MessageDecoder { + prot = ClientProt.IDLE_TIMER; + decode() { + return new IdleTimer(); + } +} + +// src/lostcity/network/incoming/model/IfButton.ts +class IfButton extends IncomingMessage { + component; + category = ClientProtCategory.USER_EVENT; + constructor(component) { + super(); + this.component = component; + } +} + +// src/lostcity/network/225/incoming/codec/IfButtonDecoder.ts +class IfButtonDecoder extends MessageDecoder { + prot = ClientProt.IF_BUTTON; + decode(buf) { + const component = buf.g2(); + return new IfButton(component); + } +} + +// src/lostcity/network/incoming/model/IfPlayerDesign.ts +class IfPlayerDesign extends IncomingMessage { + gender; + idkit; + color; + category = ClientProtCategory.USER_EVENT; + constructor(gender, idkit, color) { + super(); + this.gender = gender; + this.idkit = idkit; + this.color = color; + } +} + +// src/lostcity/network/225/incoming/codec/IfPlayerDesignDecoder.ts +class IfPlayerDesignDecoder extends MessageDecoder { + prot = ClientProt.IF_PLAYERDESIGN; + decode(buf) { + const gender = buf.g1(); + const idkit = []; + for (let i = 0; i < 7; i++) { + idkit[i] = buf.g1(); + if (idkit[i] === 255) { + idkit[i] = -1; + } + } + const color = []; + for (let i = 0; i < 5; i++) { + color[i] = buf.g1(); + } + return new IfPlayerDesign(gender, idkit, color); + } +} + +// src/lostcity/network/incoming/model/InvButton.ts +class InvButton extends IncomingMessage { + op; + obj; + slot; + component; + category = ClientProtCategory.USER_EVENT; + constructor(op, obj, slot, component) { + super(); + this.op = op; + this.obj = obj; + this.slot = slot; + this.component = component; + } +} + +// src/lostcity/network/225/incoming/codec/InvButtonDecoder.ts +class InvButtonDecoder extends MessageDecoder { + prot; + op; + constructor(prot, op) { + super(); + this.prot = prot; + this.op = op; + } + decode(buf) { + const obj = buf.g2(); + const slot = buf.g2(); + const component = buf.g2(); + return new InvButton(this.op, obj, slot, component); + } +} + +// src/lostcity/network/incoming/model/InvButtonD.ts +class InvButtonD extends IncomingMessage { + component; + slot; + targetSlot; + category = ClientProtCategory.USER_EVENT; + constructor(component, slot, targetSlot) { + super(); + this.component = component; + this.slot = slot; + this.targetSlot = targetSlot; + } +} + +// src/lostcity/network/225/incoming/codec/InvButtonDDecoder.ts +class InvButtonDDecoder extends MessageDecoder { + prot = ClientProt.INV_BUTTOND; + decode(buf) { + const component = buf.g2(); + const slot = buf.g2(); + const targetSlot = buf.g2(); + return new InvButtonD(component, slot, targetSlot); + } +} + +// src/lostcity/network/incoming/model/MessagePrivate.ts +class MessagePrivate3 extends IncomingMessage { + username; + input; + category = ClientProtCategory.USER_EVENT; + constructor(username, input) { + super(); + this.username = username; + this.input = input; + } +} + +// src/lostcity/network/225/incoming/codec/MessagePrivateDecoder.ts +class MessagePrivateDecoder extends MessageDecoder { + prot = ClientProt.MESSAGE_PRIVATE; + decode(buf) { + const username = buf.g8(); + const input = WordPack.unpack(buf, buf.length - 8); + return new MessagePrivate3(username, input); + } +} + +// src/lostcity/network/incoming/model/MessagePublic.ts +class MessagePublic extends IncomingMessage { + input; + color; + effect; + category = ClientProtCategory.USER_EVENT; + constructor(input, color, effect) { + super(); + this.input = input; + this.color = color; + this.effect = effect; + } +} + +// src/lostcity/network/225/incoming/codec/MessagePublicDecoder.ts +class MessagePublicDecoder extends MessageDecoder { + prot = ClientProt.MESSAGE_PUBLIC; + decode(buf) { + const color = buf.g1(); + const effect = buf.g1(); + const input = WordPack.unpack(buf, buf.length - 2); + return new MessagePublic(input, color, effect); + } +} + +// src/lostcity/network/incoming/model/OpHeld.ts +class OpHeld extends IncomingMessage { + op; + obj; + slot; + component; + category = ClientProtCategory.USER_EVENT; + constructor(op, obj, slot, component) { + super(); + this.op = op; + this.obj = obj; + this.slot = slot; + this.component = component; + } +} + +// src/lostcity/network/225/incoming/codec/OpHeldDecoder.ts +class OpHeldDecoder extends MessageDecoder { + prot; + op; + constructor(prot, op) { + super(); + this.prot = prot; + this.op = op; + } + decode(buf) { + const obj = buf.g2(); + const slot = buf.g2(); + const component = buf.g2(); + return new OpHeld(this.op, obj, slot, component); + } +} + +// src/lostcity/network/incoming/model/OpHeldT.ts +class OpHeldT extends IncomingMessage { + obj; + slot; + component; + spellComponent; + category = ClientProtCategory.USER_EVENT; + constructor(obj, slot, component, spellComponent) { + super(); + this.obj = obj; + this.slot = slot; + this.component = component; + this.spellComponent = spellComponent; + } +} + +// src/lostcity/network/225/incoming/codec/OpHeldTDecoder.ts +class OpHeldTDecoder extends MessageDecoder { + prot = ClientProt.OPHELDT; + decode(buf) { + const obj = buf.g2(); + const slot = buf.g2(); + const component = buf.g2(); + const spellComponent = buf.g2(); + return new OpHeldT(obj, slot, component, spellComponent); + } +} + +// src/lostcity/network/incoming/model/OpHeldU.ts +class OpHeldU extends IncomingMessage { + obj; + slot; + component; + useObj; + useSlot; + useComponent; + category = ClientProtCategory.USER_EVENT; + constructor(obj, slot, component, useObj, useSlot, useComponent) { + super(); + this.obj = obj; + this.slot = slot; + this.component = component; + this.useObj = useObj; + this.useSlot = useSlot; + this.useComponent = useComponent; + } +} + +// src/lostcity/network/225/incoming/codec/OpHeldUDecoder.ts +class OpHeldUDecoder extends MessageDecoder { + prot = ClientProt.OPHELDU; + decode(buf) { + const obj = buf.g2(); + const slot = buf.g2(); + const component = buf.g2(); + const useObj = buf.g2(); + const useSlot = buf.g2(); + const useComponent = buf.g2(); + return new OpHeldU(obj, slot, component, useObj, useSlot, useComponent); + } +} + +// src/lostcity/network/incoming/model/OpLoc.ts +class OpLoc extends IncomingMessage { + op; + x; + z2; + loc; + category = ClientProtCategory.USER_EVENT; + constructor(op, x, z2, loc) { + super(); + this.op = op; + this.x = x; + this.z = z2; + this.loc = loc; + } +} + +// src/lostcity/network/225/incoming/codec/OpLocDecoder.ts +class OpLocDecoder extends MessageDecoder { + prot; + op; + constructor(prot, op) { + super(); + this.prot = prot; + this.op = op; + } + decode(buf) { + const x = buf.g2(); + const z2 = buf.g2(); + const loc = buf.g2(); + return new OpLoc(this.op, x, z2, loc); + } +} + +// src/lostcity/network/incoming/model/OpLocT.ts +class OpLocT extends IncomingMessage { + x; + z2; + loc; + spellComponent; + category = ClientProtCategory.USER_EVENT; + constructor(x, z2, loc, spellComponent) { + super(); + this.x = x; + this.z = z2; + this.loc = loc; + this.spellComponent = spellComponent; + } +} + +// src/lostcity/network/225/incoming/codec/OpLocTDecoder.ts +class OpLocTDecoder extends MessageDecoder { + prot = ClientProt.OPLOCT; + decode(buf) { + const x = buf.g2(); + const z2 = buf.g2(); + const loc = buf.g2(); + const spellComponent = buf.g2(); + return new OpLocT(x, z2, loc, spellComponent); + } +} + +// src/lostcity/network/incoming/model/OpLocU.ts +class OpLocU extends IncomingMessage { + x; + z2; + loc; + useObj; + useSlot; + useComponent; + category = ClientProtCategory.USER_EVENT; + constructor(x, z2, loc, useObj, useSlot, useComponent) { + super(); + this.x = x; + this.z = z2; + this.loc = loc; + this.useObj = useObj; + this.useSlot = useSlot; + this.useComponent = useComponent; + } +} + +// src/lostcity/network/225/incoming/codec/OpLocUDecoder.ts +class OpLocUDecoder extends MessageDecoder { + prot = ClientProt.OPLOCU; + decode(buf) { + const x = buf.g2(); + const z2 = buf.g2(); + const loc = buf.g2(); + const useObj = buf.g2(); + const useSlot = buf.g2(); + const useComponent = buf.g2(); + return new OpLocU(x, z2, loc, useObj, useSlot, useComponent); + } +} + +// src/lostcity/network/incoming/model/OpNpc.ts +class OpNpc extends IncomingMessage { + op; + nid; + category = ClientProtCategory.USER_EVENT; + constructor(op, nid) { + super(); + this.op = op; + this.nid = nid; + } +} + +// src/lostcity/network/225/incoming/codec/OpNpcDecoder.ts +class OpNpcDecoder extends MessageDecoder { + prot; + op; + constructor(prot, op) { + super(); + this.prot = prot; + this.op = op; + } + decode(buf) { + const nid = buf.g2(); + return new OpNpc(this.op, nid); + } +} + +// src/lostcity/network/incoming/model/OpNpcT.ts +class OpNpcT extends IncomingMessage { + nid; + spellComponent; + category = ClientProtCategory.USER_EVENT; + constructor(nid, spellComponent) { + super(); + this.nid = nid; + this.spellComponent = spellComponent; + } +} + +// src/lostcity/network/225/incoming/codec/OpNpcTDecoder.ts +class OpNpcTDecoder extends MessageDecoder { + prot = ClientProt.OPNPCT; + decode(buf) { + const nid = buf.g2(); + const spellComponent = buf.g2(); + return new OpNpcT(nid, spellComponent); + } +} + +// src/lostcity/network/incoming/model/OpNpcU.ts +class OpNpcU extends IncomingMessage { + nid; + useObj; + useSlot; + useComponent; + category = ClientProtCategory.USER_EVENT; + constructor(nid, useObj, useSlot, useComponent) { + super(); + this.nid = nid; + this.useObj = useObj; + this.useSlot = useSlot; + this.useComponent = useComponent; + } +} + +// src/lostcity/network/225/incoming/codec/OpNpcUDecoder.ts +class OpNpcUDecoder extends MessageDecoder { + prot = ClientProt.OPNPCU; + decode(buf) { + const nid = buf.g2(); + const useObj = buf.g2(); + const useSlot = buf.g2(); + const useComponent = buf.g2(); + return new OpNpcU(nid, useObj, useSlot, useComponent); + } +} + +// src/lostcity/network/incoming/model/OpObj.ts +class OpObj extends IncomingMessage { + op; + x; + z2; + obj; + category = ClientProtCategory.USER_EVENT; + constructor(op, x, z2, obj) { + super(); + this.op = op; + this.x = x; + this.z = z2; + this.obj = obj; + } +} + +// src/lostcity/network/225/incoming/codec/OpObjDecoder.ts +class OpObjDecoder extends MessageDecoder { + prot; + op; + constructor(prot, op) { + super(); + this.prot = prot; + this.op = op; + } + decode(buf) { + const x = buf.g2(); + const z2 = buf.g2(); + const obj = buf.g2(); + return new OpObj(this.op, x, z2, obj); + } +} + +// src/lostcity/network/incoming/model/OpObjT.ts +class OpObjT extends IncomingMessage { + x; + z2; + obj; + spellComponent; + category = ClientProtCategory.USER_EVENT; + constructor(x, z2, obj, spellComponent) { + super(); + this.x = x; + this.z = z2; + this.obj = obj; + this.spellComponent = spellComponent; + } +} + +// src/lostcity/network/225/incoming/codec/OpObjTDecoder.ts +class OpObjTDecoder extends MessageDecoder { + prot = ClientProt.OPOBJT; + decode(buf) { + const x = buf.g2(); + const z2 = buf.g2(); + const obj = buf.g2(); + const spellComponent = buf.g2(); + return new OpObjT(x, z2, obj, spellComponent); + } +} + +// src/lostcity/network/incoming/model/OpObjU.ts +class OpObjU extends IncomingMessage { + x; + z2; + obj; + useObj; + useSlot; + useComponent; + category = ClientProtCategory.USER_EVENT; + constructor(x, z2, obj, useObj, useSlot, useComponent) { + super(); + this.x = x; + this.z = z2; + this.obj = obj; + this.useObj = useObj; + this.useSlot = useSlot; + this.useComponent = useComponent; + } +} + +// src/lostcity/network/225/incoming/codec/OpObjUDecoder.ts +class OpObjUDecoder extends MessageDecoder { + prot = ClientProt.OPOBJU; + decode(buf) { + const x = buf.g2(); + const z2 = buf.g2(); + const obj = buf.g2(); + const useObj = buf.g2(); + const useSlot = buf.g2(); + const useComponent = buf.g2(); + return new OpObjU(x, z2, obj, useObj, useSlot, useComponent); + } +} + +// src/lostcity/network/incoming/model/OpPlayer.ts +class OpPlayer extends IncomingMessage { + op; + pid; + category = ClientProtCategory.USER_EVENT; + constructor(op, pid) { + super(); + this.op = op; + this.pid = pid; + } +} + +// src/lostcity/network/225/incoming/codec/OpPlayerDecoder.ts +class OpPlayerDecoder extends MessageDecoder { + prot; + op; + constructor(prot, op) { + super(); + this.prot = prot; + this.op = op; + } + decode(buf) { + const pid = buf.g2(); + return new OpPlayer(this.op, pid); + } +} + +// src/lostcity/network/incoming/model/OpPlayerT.ts +class OpPlayerT extends IncomingMessage { + pid; + spellComponent; + category = ClientProtCategory.USER_EVENT; + constructor(pid, spellComponent) { + super(); + this.pid = pid; + this.spellComponent = spellComponent; + } +} + +// src/lostcity/network/225/incoming/codec/OpPlayerTDecoder.ts +class OpPlayerTDecoder extends MessageDecoder { + prot = ClientProt.OPPLAYERT; + decode(buf) { + const pid = buf.g2(); + const spellComponent = buf.g2(); + return new OpPlayerT(pid, spellComponent); + } +} + +// src/lostcity/network/incoming/model/OpPlayerU.ts +class OpPlayerU extends IncomingMessage { + pid; + useObj; + useSlot; + useComponent; + category = ClientProtCategory.USER_EVENT; + constructor(pid, useObj, useSlot, useComponent) { + super(); + this.pid = pid; + this.useObj = useObj; + this.useSlot = useSlot; + this.useComponent = useComponent; + } +} + +// src/lostcity/network/225/incoming/codec/OpPlayerUDecoder.ts +class OpPlayerUDecoder extends MessageDecoder { + prot = ClientProt.OPPLAYERU; + decode(buf) { + const pid = buf.g2(); + const useObj = buf.g2(); + const useSlot = buf.g2(); + const useComponent = buf.g2(); + return new OpPlayerU(pid, useObj, useSlot, useComponent); + } +} + +// src/lostcity/network/incoming/model/RebuildGetMaps.ts +class RebuildGetMaps extends IncomingMessage { + maps; + category = ClientProtCategory.USER_EVENT; + constructor(maps) { + super(); + this.maps = maps; + } +} + +// src/lostcity/network/225/incoming/codec/RebuildGetMapsDecoder.ts +class RebuildGetMapsDecoder extends MessageDecoder { + prot = ClientProt.REBUILD_GETMAPS; + decode(buf) { + const maps = []; + const count = buf.length / 3; + for (let i = 0; i < count; i++) { + const type = buf.g1(); + const x = buf.g1(); + const z2 = buf.g1(); + maps.push({type, x, z: z2}); + } + return new RebuildGetMaps(maps); + } +} + +// src/lostcity/network/incoming/model/ResumePauseButton.ts +class ResumePauseButton extends IncomingMessage { + category = ClientProtCategory.USER_EVENT; +} + +// src/lostcity/network/225/incoming/codec/ResumePauseButtonDecoder.ts +class ResumePauseButtonDecoder extends MessageDecoder { + prot = ClientProt.RESUME_PAUSEBUTTON; + decode() { + return new ResumePauseButton(); + } +} + +// src/lostcity/network/incoming/model/ResumePCountDialog.ts +class ResumePCountDialog extends IncomingMessage { + input; + category = ClientProtCategory.USER_EVENT; + constructor(input) { + super(); + this.input = input; + } +} + +// src/lostcity/network/225/incoming/codec/ResumePCountDialogDecoder.ts +class ResumePCountDialogDecoder extends MessageDecoder { + prot = ClientProt.RESUME_P_COUNTDIALOG; + decode(buf) { + const input = buf.g4(); + return new ResumePCountDialog(input); + } +} + +// src/lostcity/network/incoming/model/TutorialClickSide.ts +class TutorialClickSide extends IncomingMessage { + tab; + category = ClientProtCategory.USER_EVENT; + constructor(tab) { + super(); + this.tab = tab; + } +} + +// src/lostcity/network/225/incoming/codec/TutorialClickSideDecoder.ts +class TutorialClickSideDecoder extends MessageDecoder { + prot = ClientProt.TUTORIAL_CLICKSIDE; + decode(buf) { + const tab = buf.g1(); + return new TutorialClickSide(tab); + } +} + +// src/lostcity/network/incoming/handler/MessageHandler.ts +class MessageHandler {} + +// src/lostcity/network/225/incoming/handler/InvButtonHandler.ts +class InvButtonHandler extends MessageHandler { + handle(message, player) { + const {op, obj: item, slot, component: comId} = message; + const com = Component.get(comId); + if (typeof com === 'undefined' || !com.inventoryOptions || !com.inventoryOptions.length || !player.isComponentVisible(com)) { + return false; + } + if (!com.inventoryOptions[op - 1]) { + return false; + } + const listener = player.invListeners.find(l => l.com === comId); + if (!listener) { + return false; + } + const inv = player.getInventoryFromListener(listener); + if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { + return false; + } + if (player.delayed()) { + return false; + } + player.lastItem = item; + player.lastSlot = slot; + let trigger; + if (op === 1) { + trigger = ServerTriggerType_default.INV_BUTTON1; + } else if (op === 2) { + trigger = ServerTriggerType_default.INV_BUTTON2; + } else if (op === 3) { + trigger = ServerTriggerType_default.INV_BUTTON3; + } else if (op === 4) { + trigger = ServerTriggerType_default.INV_BUTTON4; + } else { + trigger = ServerTriggerType_default.INV_BUTTON5; + } + const script = ScriptProvider.getByTrigger(trigger, comId, -1); + if (script) { + const root = Component.get(com.rootLayer); + player.executeScript(ScriptRunner2.init(script, player), root.overlay == false); + } else if (Environment_default.NODE_DEBUG) { + player.messageGame(`No trigger for [${ServerTriggerType_default.toString(trigger)},${com.comName}]`); + } + return true; + } +} + +// src/lostcity/server/ClientSocket.ts +class ClientSocket { + static TCP = 0; + static WEBSOCKET = 1; + socket = null; + type = -1; + state = -1; + remoteAddress; + totalBytesRead = 0; + totalBytesWritten = 0; + uniqueId; + encryptor = null; + decryptor = null; + in = new Uint8Array(5000); + inOffset = 0; + inCount = new Uint8Array(256); + out = new Packet(new Uint8Array(5000)); + player = null; + constructor(uniqueId, socket, remoteAddress, type = ClientSocket.TCP, state = -1) { + this.uniqueId = uniqueId; + this.socket = socket; + this.remoteAddress = remoteAddress; + this.type = type; + this.state = state; + } + isTCP() { + return this.type === ClientSocket.TCP; + } + isWebSocket() { + return this.type === ClientSocket.WEBSOCKET; + } + send(data) { + if (typeof self !== 'undefined') { + this.totalBytesWritten += data.length; + self.postMessage(data); + } else { + if (!this.socket) { + return; + } + this.totalBytesWritten += data.length; + if (this.isTCP()) { + this.socket.write(data); + } else if (this.isWebSocket()) { + this.socket.send(data); + } + } + } + close() { + if (typeof self !== 'undefined') { + setTimeout(() => { + self.close(); + }, 100); + } else { + if (!this.socket) { + return; + } + setTimeout(() => { + if (this.isTCP()) { + this.socket.end(); + } else if (this.isWebSocket()) { + this.socket.close(); + } + }, 100); + } + } + terminate() { + if (typeof self !== 'undefined') { + self.close(); + } else { + if (!this.socket) { + return; + } + if (this.isTCP()) { + this.socket.destroy(); + } else if (this.isWebSocket()) { + this.socket.terminate(); + } + } + } + reset() { + this.inOffset = 0; + this.inCount.fill(0); + } + writeImmediate(data) { + this.send(data); + } + flush() { + const out = this.out; + if (out.pos === 0) { + return; + } + this.send(out.data.subarray(0, out.pos)); + out.pos = 0; + } +} + +// src/lostcity/server/NullClientSocket.ts +class NullClientSocket extends ClientSocket { + constructor() { + super(null, ''); + } + isTCP() { + return this.type === ClientSocket.TCP; + } + isWebSocket() { + return this.type === ClientSocket.WEBSOCKET; + } + send(data) { + if (!this.socket) { + return; + } + } + close() { + if (!this.socket) { + return; + } + } + terminate() { + if (!this.socket) { + return; + } + } + reset() { + this.inOffset = 0; + this.inCount.fill(0); + } +} + +// src/lostcity/network/225/incoming/handler/ClientCheatHandler.ts +class ClientCheatHandler extends MessageHandler { + handle(message, player) { + if (message.input.length > 80) { + return false; + } + const {input: cheat} = message; + const args = cheat.toLowerCase().split(' '); + const cmd = args.shift(); + if (cmd === undefined || cmd.length <= 0) { + return false; + } + player.playerLog('Cheat ran', cheat); + if (player.staffModLevel >= 3) { + if (cmd === 'reload' && typeof self === 'undefined' && !Environment_default.NODE_PRODUCTION) { + World_default.reload(); + const count = ScriptProvider.load('data/pack'); + player.messageGame(`Reloaded ${count} scripts.`); + } else if (cmd === 'rebuild' && !Environment_default.NODE_PRODUCTION) { + World_default.devThread.postMessage({ + type: 'pack' + }); + } else if (cmd === 'serverdrop') { + player.terminate(); + } else if (cmd === 'bench') { + const start = Date.now(); + for (let index = 0; index < 1e5; index++) { + findPath(player.level, player.x, player.z, player.x, player.z + 10); + } + const end = Date.now(); + console.log(`took = ${end - start} ms`); + } else if (cmd === 'bots') { + player.messageGame('Adding bots'); + for (let i = 0; i < 2000; i++) { + const bot = new NetworkPlayer2(`bot${i}`, toBase37(`bot${i}`), new NullClientSocket()); + bot.onLogin(); + World_default.addPlayer(bot); + } + } else if (cmd === 'teleall') { + player.messageGame('Teleporting all players'); + for (const player2 of World_default.players) { + player2.closeModal(); + do { + const x = Math.floor(Math.random() * 64) + 3200; + const z2 = Math.floor(Math.random() * 64) + 3200; + player2.teleport(x + Math.floor(Math.random() * 64) - 32, z2 + Math.floor(Math.random() * 64) - 32, 0); + } while (isFlagged(player2.x, player2.z, player2.level, CollisionFlag.WALK_BLOCKED)); + } + } else if (cmd === 'moveall') { + player.messageGame('Moving all players'); + console.time('moveall'); + for (const player2 of World_default.players) { + player2.closeModal(); + player2.queueWaypoints(findPath(player2.level, player2.x, player2.z, ((player2.x >>> 6) << 6) + 32, ((player2.z >>> 6) << 6) + 32)); + } + console.timeEnd('moveall'); + } else if (cmd === 'speed') { + if (args.length < 1) { + player.messageGame('Usage: ::speed '); + return false; + } + const speed = tryParseInt(args.shift(), 20); + if (speed < 20) { + player.messageGame('::speed input was too low.'); + return false; + } + player.messageGame(`World speed was changed to ${speed}ms`); + World_default.tickRate = speed; + } else if (cmd === 'fly') { + if (player.moveStrategy === MoveStrategy_default.FLY) { + player.moveStrategy = MoveStrategy_default.SMART; + } else { + player.moveStrategy = MoveStrategy_default.FLY; + } + player.messageGame(`Fly is on? ${player.moveStrategy === MoveStrategy_default.FLY}`); + } else if (cmd === 'naive') { + if (player.moveStrategy === MoveStrategy_default.NAIVE) { + player.moveStrategy = MoveStrategy_default.SMART; + } else { + player.moveStrategy = MoveStrategy_default.NAIVE; + } + player.messageGame(`Naive is on? ${player.moveStrategy === MoveStrategy_default.NAIVE}`); + } else if (cmd === 'teleto') { + if (args.length < 1) { + return false; + } + const other = World_default.getPlayerByUsername(args[0]); + if (!other) { + player.messageGame(`${args[0]} is not logged in.`); + return false; + } + player.teleJump(other.x, other.z, other.level); + } else if (cmd === 'teleother') { + if (args.length < 1) { + return false; + } + const other = World_default.getPlayerByUsername(args[0]); + if (!other) { + player.messageGame(`${args[0]} is not logged in.`); + return false; + } + other.teleJump(player.x, player.z, player.level); + } else if (cmd === 'setvarother') { + if (args.length < 3) { + return false; + } + const other = World_default.getPlayerByUsername(args[0]); + if (!other) { + player.messageGame(`${args[0]} is not logged in.`); + return false; + } + const varp = VarPlayerType.getId(args[1]); + const value = Math.max(-2147483648, Math.min(tryParseInt(args[2], 0), 2147483647)); + if (varp === -1) { + return false; + } + other.setVar(varp, value); + player.messageGame('set ' + args[1] + ': to ' + value + ' on ' + other.username); + } else if (cmd === 'shutdown') { + if (args.length < 1) { + return false; + } + World_default.rebootTimer(tryParseInt(args[0], 50)); + } + } + if (Environment_default.NODE_ALLOW_CHEATS || player.staffModLevel >= 2) { + if (cmd === 'tele') { + if (args.length < 1) { + return false; + } + if (args[0] === 'up') { + player.teleJump(player.x, player.z, player.level + 1); + player.messageGame('::tele ' + Position.formatString(player.level, player.x, player.z, ',')); + } else if (args[0] === 'down') { + player.teleJump(player.x, player.z, player.level - 1); + player.messageGame('::tele ' + Position.formatString(player.level, player.x, player.z, ',')); + } else if (args[0].indexOf(',') === -1) { + player.teleJump(tryParseInt(args[0], 3200), tryParseInt(args[1], 3200), tryParseInt(args[2], player.level)); + } else { + const coord = args[0].split(','); + if (coord.length !== 5) { + return false; + } + const level = tryParseInt(coord[0], 0); + const mx = tryParseInt(coord[1], 50); + const mz = tryParseInt(coord[2], 50); + const lx = tryParseInt(coord[3], 0); + const lz = tryParseInt(coord[4], 0); + if (level < 0 || level > 3 || mx < 0 || mx > 255 || mz < 0 || mz > 255 || lx < 0 || lx > 63 || lz < 0 || lz > 63) { + return false; + } + player.teleJump((mx << 6) + lx, (mz << 6) + lz, level); + } + } else if (cmd === 'setvar') { + if (args.length < 2) { + return false; + } + const varp = VarPlayerType.getId(args[0]); + const value = Math.max(-2147483648, Math.min(tryParseInt(args[1], 0), 2147483647)); + if (varp === -1) { + return false; + } + player.setVar(varp, value); + player.messageGame('set ' + args[0] + ': to ' + value); + } else if (cmd === 'random') { + player.afkEventReady = true; + } else if (cmd === 'minme') { + for (let i = 0; i < Player2.SKILLS.length; i++) { + if (i === PlayerStat_default.HITPOINTS) { + player.setLevel(i, 10); + } else { + player.setLevel(i, 1); + } + } + } else if (cmd === 'setxp') { + if (args.length < 2) { + player.messageGame('Usage: ::setxp '); + return false; + } + const stat = Player2.SKILLS.indexOf(args[0]); + if (stat === -1) { + player.messageGame(`Unknown stat ${args[0]}`); + return false; + } + const exp = parseInt(args[1]) * 10; + player.stats[stat] = exp; + } else if (cmd === 'setstat') { + if (args.length < 2) { + return false; + } + const stat = Player2.SKILLS.indexOf(args[0]); + if (stat === -1) { + return false; + } + player.setLevel(stat, parseInt(args[1])); + } else if (cmd === 'advancestat') { + if (args.length < 1) { + return false; + } + const stat = Player2.SKILLS.indexOf(args[0]); + const level = Math.min(99, Math.max(1, tryParseInt(args[1], 1))); + if (stat === -1) { + return false; + } + player.setLevel(stat, player.baseLevels[stat] + level); + } else if (cmd === 'getvar') { + if (args.length < 1) { + return false; + } + const varp = VarPlayerType.getId(args[0]); + if (varp === -1) { + return false; + } + const value = player.getVar(varp); + player.messageGame('get ' + args[0] + ': ' + value); + } else if (cmd === 'give') { + if (args.length < 1) { + return false; + } + const obj = ObjType.getId(args[0]); + const count = Math.max(1, Math.min(tryParseInt(args[1], 1), 2147483647)); + if (obj === -1) { + return false; + } + player.invAdd(InvType.INV, obj, count, false); + } else if (cmd === 'givecrap') { + } else if (cmd === 'givemany') { + } + } + if (Environment_default.NODE_ALLOW_CHEATS || player.staffModLevel >= 1) { + if (cmd === 'getcoord') { + player.messageGame(Position.formatString(player.level, player.x, player.z, '_')); + } + } + if (Environment_default.NODE_ALLOW_CHEATS || player.staffModLevel >= 2) { + const script = ScriptProvider.getByName(`[debugproc,${cmd}]`); + if (!script) { + return false; + } + const params = new Array(script.info.parameterTypes.length).fill(-1); + for (let i = 0; i < script.info.parameterTypes.length; i++) { + const type = script.info.parameterTypes[i]; + try { + switch (type) { + case ScriptVarType.STRING: { + const value = args.shift(); + params[i] = value ?? ''; + break; + } + case ScriptVarType.INT: { + const value = args.shift(); + params[i] = parseInt(value ?? '0', 10) | 0; + break; + } + case ScriptVarType.OBJ: + case ScriptVarType.NAMEDOBJ: { + const name = args.shift(); + params[i] = ObjType.getId(name ?? ''); + break; + } + case ScriptVarType.NPC: { + const name = args.shift(); + params[i] = NpcType.getId(name ?? ''); + break; + } + case ScriptVarType.LOC: { + const name = args.shift(); + params[i] = LocType.getId(name ?? ''); + break; + } + case ScriptVarType.SEQ: { + const name = args.shift(); + params[i] = SeqType.getId(name ?? ''); + break; + } + case ScriptVarType.STAT: { + const name = args.shift(); + params[i] = Player2.SKILLS.indexOf(name ?? ''); + break; + } + case ScriptVarType.INV: { + const name = args.shift(); + params[i] = InvType.getId(name ?? ''); + break; + } + case ScriptVarType.COORD: { + const args2 = cheat.split('_'); + const level = parseInt(args2[0].slice(6)); + const mx = parseInt(args2[1]); + const mz = parseInt(args2[2]); + const lx = parseInt(args2[3]); + const lz = parseInt(args2[4]); + params[i] = Position.packCoord(level, (mx << 6) + lx, (mz << 6) + lz); + break; + } + case ScriptVarType.INTERFACE: { + const name = args.shift(); + params[i] = Component.getId(name ?? ''); + break; + } + case ScriptVarType.SPOTANIM: { + const name = args.shift(); + params[i] = SpotanimType.getId(name ?? ''); + break; + } + case ScriptVarType.IDKIT: { + const name = args.shift(); + params[i] = IdkType.getId(name ?? ''); + break; + } + } + } catch (err) { + return false; + } + } + player.executeScript(ScriptRunner2.init(script, player, null, params), false); + } + return true; + } +} + +// src/lostcity/network/225/incoming/handler/CloseModalHandler.ts +class CloseModalHandler extends MessageHandler { + handle(_message, player) { + player.closeModal(); + return true; + } +} + +// src/lostcity/network/225/incoming/handler/IdleTimerHandler.ts +class IdleTimerHandler extends MessageHandler { + handle(_message, player) { + if (Environment_default.NODE_PRODUCTION) { + player.logout(); + player.logoutRequested = true; + } + return true; + } +} + +// src/lostcity/network/225/incoming/handler/IfButtonHandler.ts +class IfButtonHandler extends MessageHandler { + handle(message, player) { + const {component: comId} = message; + const com = Component.get(comId); + if (typeof com === 'undefined' || !player.isComponentVisible(com)) { + return false; + } + player.lastCom = comId; + if (player.resumeButtons.indexOf(player.lastCom) !== -1) { + if (player.activeScript) { + player.executeScript(player.activeScript, true); + } + } else { + const root = Component.get(com.rootLayer); + const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.IF_BUTTON, comId, -1); + if (script) { + player.executeScript(ScriptRunner2.init(script, player), root.overlay == false); + } else if (Environment_default.NODE_DEBUG) { + player.messageGame(`No trigger for [if_button,${com.comName}]`); + } + } + return true; + } +} + +// src/lostcity/network/225/incoming/handler/IfPlayerDesignHandler.ts +class IfPlayerDesignHandler extends MessageHandler { + handle(message, player) { + const {gender, idkit, color} = message; + if (!player.allowDesign) { + return false; + } + if (gender > 1) { + return false; + } + let pass = true; + for (let i = 0; i < 7; i++) { + let type = i; + if (gender === 1) { + type += 7; + } + if (type == 8 && idkit[i] === -1) { + continue; + } + const idk = IdkType.get(idkit[i]); + if (!idk || idk.disable || idk.type != type) { + pass = false; + break; + } + } + if (!pass) { + return false; + } + for (let i = 0; i < 5; i++) { + if (color[i] >= Player2.DESIGN_BODY_COLORS[i].length) { + pass = false; + break; + } + } + if (!pass) { + return false; + } + player.gender = gender; + player.body = idkit; + player.colors = color; + player.generateAppearance(InvType.WORN); + return true; + } +} + +// src/lostcity/network/225/incoming/handler/InvButtonDHandler.ts +class InvButtonDHandler extends MessageHandler { + handle(message, player) { + const {component: comId, slot, targetSlot} = message; + const com = Component.get(comId); + if (typeof com === 'undefined' || !player.isComponentVisible(com)) { + return false; + } + const listener = player.invListeners.find(l => l.com === comId); + if (!listener) { + return false; + } + const inv = player.getInventoryFromListener(listener); + if (!inv || !inv.validSlot(slot) || !inv.get(slot) || !inv.validSlot(targetSlot)) { + return false; + } + if (player.delayed()) { + player.write(new UpdateInvPartial(comId, inv, slot, targetSlot)); + return false; + } + player.lastSlot = slot; + player.lastTargetSlot = targetSlot; + const dragTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.INV_BUTTOND, comId); + if (dragTrigger) { + const root = Component.get(com.rootLayer); + player.executeScript(ScriptRunner2.init(dragTrigger, player), root.overlay == false); + } else if (Environment_default.NODE_DEBUG) { + player.messageGame(`No trigger for [inv_buttond,${com.comName}]`); + } + return true; + } +} + +// src/lostcity/network/225/incoming/handler/MessagePrivateHandler.ts +class MessagePrivateHandler extends MessageHandler { + handle(message, player) { + return true; + } +} + +// src/lostcity/network/225/incoming/handler/MessagePublicHandler.ts +class MessagePublicHandler extends MessageHandler { + handle(message, player) { + const {color, effect, input} = message; + if (color < 0 || color > 11 || effect < 0 || effect > 2 || input.length > 100) { + return false; + } + player.messageColor = color; + player.messageEffect = effect; + player.messageType = 0; + const out = Packet.alloc(0); + WordPack.pack(out, WordEnc2.filter(input)); + player.message = new Uint8Array(out.pos); + out.pos = 0; + out.gdata(player.message, 0, player.message.length); + out.release(); + player.mask |= Player2.CHAT; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpHeldHandler.ts +class OpHeldHandler extends MessageHandler { + handle(message, player) { + const {obj: item, slot, component: comId} = message; + const com = Component.get(comId); + if (typeof com === 'undefined' || !player.isComponentVisible(com)) { + return false; + } + const type = ObjType.get(item); + if (message.op !== 5 && ((type.iop && !type.iop[message.op - 1]) || !type.iop)) { + return false; + } + const listener = player.invListeners.find(l => l.com === comId); + if (!listener) { + return false; + } + const inv = player.getInventoryFromListener(listener); + if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { + return false; + } + if (player.delayed()) { + return false; + } + player.lastItem = item; + player.lastSlot = slot; + player.clearInteraction(); + player.closeModal(); + let trigger; + if (message.op === 1) { + trigger = ServerTriggerType_default.OPHELD1; + } else if (message.op === 2) { + trigger = ServerTriggerType_default.OPHELD2; + } else if (message.op === 3) { + trigger = ServerTriggerType_default.OPHELD3; + } else if (message.op === 4) { + trigger = ServerTriggerType_default.OPHELD4; + } else { + trigger = ServerTriggerType_default.OPHELD5; + } + const script = ScriptProvider.getByTrigger(trigger, type.id, type.category); + if (script) { + player.executeScript(ScriptRunner2.init(script, player), true); + } else if (Environment_default.NODE_DEBUG) { + player.messageGame(`No trigger for [${ServerTriggerType_default.toString(trigger)},${type.debugname}]`); + } + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpHeldTHandler.ts +class OpHeldTHandler extends MessageHandler { + handle(message, player) { + const {obj: item, slot, component: comId, spellComponent: spellComId} = message; + const com = Component.get(comId); + if (typeof com === 'undefined' || !player.isComponentVisible(com)) { + player.unsetMapFlag(); + return false; + } + const spellCom = Component.get(comId); + if (typeof spellCom === 'undefined' || !player.isComponentVisible(spellCom)) { + player.unsetMapFlag(); + return false; + } + const listener = player.invListeners.find(l => l.com === comId); + if (!listener) { + player.unsetMapFlag(); + return false; + } + const inv = player.getInventoryFromListener(listener); + if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { + player.unsetMapFlag(); + return false; + } + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + player.lastItem = item; + player.lastSlot = slot; + player.clearInteraction(); + player.closeModal(); + const script = ScriptProvider.getByTrigger(ServerTriggerType_default.OPHELDT, spellComId, -1); + if (script) { + player.executeScript(ScriptRunner2.init(script, player), true); + } else { + if (Environment_default.NODE_DEBUG) { + player.messageGame(`No trigger for [opheldt,${spellCom.comName}]`); + } + player.messageGame('Nothing interesting happens.'); + } + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpHeldUHandler.ts +class OpHeldUHandler extends MessageHandler { + handle(message, player) { + const {obj: item, slot, component: comId, useObj: useItem, useSlot, useComponent: useComId} = message; + const com = Component.get(comId); + if (typeof com === 'undefined' || !player.isComponentVisible(com)) { + player.unsetMapFlag(); + return false; + } + const useCom = Component.get(comId); + if (typeof useCom === 'undefined' || !player.isComponentVisible(useCom)) { + player.unsetMapFlag(); + return false; + } + { + const listener = player.invListeners.find(l => l.com === comId); + if (!listener) { + player.unsetMapFlag(); + return false; + } + const inv = player.getInventoryFromListener(listener); + if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { + player.unsetMapFlag(); + return false; + } + } + { + const listener = player.invListeners.find(l => l.com === useComId); + if (!listener) { + player.unsetMapFlag(); + return false; + } + const inv = player.getInventoryFromListener(listener); + if (!inv || !inv.validSlot(useSlot) || !inv.hasAt(useSlot, useItem)) { + player.unsetMapFlag(); + return false; + } + } + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + player.lastItem = item; + player.lastSlot = slot; + player.lastUseItem = useItem; + player.lastUseSlot = useSlot; + const objType = ObjType.get(player.lastItem); + const useObjType = ObjType.get(player.lastUseItem); + if ((objType.members || useObjType.members) && !Environment_default.NODE_MEMBERS) { + player.messageGame("To use this item please login to a members' server."); + player.unsetMapFlag(); + return false; + } + let script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, objType.id, -1); + if (!script) { + script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, useObjType.id, -1); + [player.lastItem, player.lastUseItem] = [player.lastUseItem, player.lastItem]; + [player.lastSlot, player.lastUseSlot] = [player.lastUseSlot, player.lastSlot]; + } + const objCategory = objType.category !== -1 ? CategoryType.get(objType.category) : null; + if (!script && objCategory) { + script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, -1, objCategory.id); + } + const useObjCategory = useObjType.category !== -1 ? CategoryType.get(useObjType.category) : null; + if (!script && useObjCategory) { + script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, -1, useObjCategory.id); + [player.lastItem, player.lastUseItem] = [player.lastUseItem, player.lastItem]; + [player.lastSlot, player.lastUseSlot] = [player.lastUseSlot, player.lastSlot]; + } + player.clearInteraction(); + player.closeModal(); + if (script) { + player.executeScript(ScriptRunner2.init(script, player), true); + } else { + if (Environment_default.NODE_DEBUG) { + player.messageGame(`No trigger for [opheldu,${objType.debugname}]`); + } + player.messageGame('Nothing interesting happens.'); + } + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpLocHandler.ts +class OpLocHandler extends MessageHandler { + handle(message, player) { + const {x, z: z2, loc: locId} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const absLeftX = player.originX - 52; + const absRightX = player.originX + 52; + const absTopZ = player.originZ + 52; + const absBottomZ = player.originZ - 52; + if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { + return false; + } + const loc = World_default.getLoc(x, z2, player.level, locId); + if (!loc) { + player.unsetMapFlag(); + return false; + } + const locType = LocType.get(loc.type); + if (!locType.op || !locType.op[message.op - 1]) { + player.unsetMapFlag(); + return false; + } + let mode; + if (message.op === 1) { + mode = ServerTriggerType_default.APLOC1; + } else if (message.op === 2) { + mode = ServerTriggerType_default.APLOC2; + } else if (message.op === 3) { + mode = ServerTriggerType_default.APLOC3; + } else if (message.op === 4) { + mode = ServerTriggerType_default.APLOC4; + } else { + mode = ServerTriggerType_default.APLOC5; + } + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, loc, mode); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpLocTHandler.ts +class OpLocTHandler extends MessageHandler { + handle(message, player) { + const {x, z: z2, loc: locId, spellComponent: spellComId} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const spellCom = Component.get(spellComId); + if (typeof spellCom === 'undefined' || !player.isComponentVisible(spellCom)) { + player.unsetMapFlag(); + return false; + } + const absLeftX = player.originX - 52; + const absRightX = player.originX + 52; + const absTopZ = player.originZ + 52; + const absBottomZ = player.originZ - 52; + if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { + player.unsetMapFlag(); + return false; + } + const loc = World_default.getLoc(x, z2, player.level, locId); + if (!loc) { + player.unsetMapFlag(); + return false; + } + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, loc, ServerTriggerType_default.APLOCT, {type: loc.type, com: spellComId}); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpLocUHandler.ts +class OpLocUHandler extends MessageHandler { + handle(message, player) { + const {x, z: z2, loc: locId, useObj: item, useSlot: slot, useComponent: comId} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const com = Component.get(comId); + if (typeof com === 'undefined' || !player.isComponentVisible(com)) { + player.unsetMapFlag(); + return false; + } + const absLeftX = player.originX - 52; + const absRightX = player.originX + 52; + const absTopZ = player.originZ + 52; + const absBottomZ = player.originZ - 52; + if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { + player.unsetMapFlag(); + return false; + } + const listener = player.invListeners.find(l => l.com === comId); + if (!listener) { + player.unsetMapFlag(); + return false; + } + const inv = player.getInventoryFromListener(listener); + if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { + player.unsetMapFlag(); + return false; + } + const loc = World_default.getLoc(x, z2, player.level, locId); + if (!loc) { + player.unsetMapFlag(); + return false; + } + if (ObjType.get(item).members && !Environment_default.NODE_MEMBERS) { + player.messageGame("To use this item please login to a members' server."); + player.unsetMapFlag(); + return false; + } + player.lastUseItem = item; + player.lastUseSlot = slot; + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, loc, ServerTriggerType_default.APLOCU); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpNpcHandler.ts +class OpNpcHandler extends MessageHandler { + handle(message, player) { + const {nid} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const npc = World_default.getNpc(nid); + if (!npc || npc.delayed()) { + player.unsetMapFlag(); + return false; + } + if (!player.buildArea.npcs.has(npc.nid)) { + player.unsetMapFlag(); + return false; + } + const npcType = NpcType.get(npc.type); + if (!npcType.op || !npcType.op[message.op - 1]) { + player.unsetMapFlag(); + return false; + } + let mode; + if (message.op === 1) { + mode = ServerTriggerType_default.APNPC1; + } else if (message.op === 2) { + mode = ServerTriggerType_default.APNPC2; + } else if (message.op === 3) { + mode = ServerTriggerType_default.APNPC3; + } else if (message.op === 4) { + mode = ServerTriggerType_default.APNPC4; + } else { + mode = ServerTriggerType_default.APNPC5; + } + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, npc, mode, {type: npc.type, com: -1}); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpNpcTHandler.ts +class OpNpcTHandler extends MessageHandler { + handle(message, player) { + const {nid, spellComponent: spellComId} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const spellCom = Component.get(spellComId); + if (typeof spellCom === 'undefined' || !player.isComponentVisible(spellCom)) { + player.unsetMapFlag(); + return false; + } + const npc = World_default.getNpc(nid); + if (!npc || npc.delayed()) { + player.unsetMapFlag(); + return false; + } + if (!player.buildArea.npcs.has(npc.nid)) { + player.unsetMapFlag(); + return false; + } + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, npc, ServerTriggerType_default.APNPCT, {type: npc.type, com: spellComId}); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpNpcUHandler.ts +class OpNpcUHandler extends MessageHandler { + handle(message, player) { + const {nid, useObj: item, useSlot: slot, useComponent: comId} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const com = Component.get(comId); + if (typeof com === 'undefined' || !player.isComponentVisible(com)) { + player.unsetMapFlag(); + return false; + } + const listener = player.invListeners.find(l => l.com === comId); + if (!listener) { + player.unsetMapFlag(); + return false; + } + const inv = player.getInventoryFromListener(listener); + if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { + player.unsetMapFlag(); + return false; + } + const npc = World_default.getNpc(nid); + if (!npc || npc.delayed()) { + player.unsetMapFlag(); + return false; + } + if (!player.buildArea.npcs.has(npc.nid)) { + player.unsetMapFlag(); + return false; + } + if (ObjType.get(item).members && !Environment_default.NODE_MEMBERS) { + player.messageGame("To use this item please login to a members' server."); + player.unsetMapFlag(); + return false; + } + player.lastUseItem = item; + player.lastUseSlot = slot; + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, npc, ServerTriggerType_default.APNPCU, {type: npc.type, com: -1}); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpObjHandler.ts +class OpObjHandler extends MessageHandler { + handle(message, player) { + const {x, z: z2, obj: objId} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const absLeftX = player.originX - 52; + const absRightX = player.originX + 52; + const absTopZ = player.originZ + 52; + const absBottomZ = player.originZ - 52; + if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { + player.unsetMapFlag(); + return false; + } + const obj = World_default.getObj(x, z2, player.level, objId, player.pid); + if (!obj) { + player.unsetMapFlag(); + return false; + } + const objType = ObjType.get(obj.type); + if ((message.op === 1 && ((objType.op && !objType.op[0]) || !objType.op)) || (message.op === 4 && ((objType.op && !objType.op[3]) || !objType.op))) { + player.unsetMapFlag(); + return false; + } + let mode; + if (message.op === 1) { + mode = ServerTriggerType_default.APOBJ1; + } else if (message.op === 2) { + mode = ServerTriggerType_default.APOBJ2; + } else if (message.op === 3) { + mode = ServerTriggerType_default.APOBJ3; + } else if (message.op === 4) { + mode = ServerTriggerType_default.APOBJ4; + } else { + mode = ServerTriggerType_default.APOBJ5; + } + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, obj, mode); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpObjTHandler.ts +class OpObjTHandler extends MessageHandler { + handle(message, player) { + const {x, z: z2, obj: objId, spellComponent: spellComId} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const spellCom = Component.get(spellComId); + if (typeof spellCom === 'undefined' || !player.isComponentVisible(spellCom)) { + player.unsetMapFlag(); + return false; + } + const absLeftX = player.originX - 52; + const absRightX = player.originX + 52; + const absTopZ = player.originZ + 52; + const absBottomZ = player.originZ - 52; + if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { + player.unsetMapFlag(); + return false; + } + const obj = World_default.getObj(x, z2, player.level, objId, player.pid); + if (!obj) { + player.unsetMapFlag(); + return false; + } + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, obj, ServerTriggerType_default.APOBJT, {type: obj.type, com: spellComId}); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpObjUHandler.ts +class OpObjUHandler extends MessageHandler { + handle(message, player) { + const {x, z: z2, obj: objId, useObj: item, useSlot: slot, useComponent: comId} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const com = Component.get(comId); + if (typeof com === 'undefined' || !player.isComponentVisible(com)) { + player.unsetMapFlag(); + return false; + } + const absLeftX = player.originX - 52; + const absRightX = player.originX + 52; + const absTopZ = player.originZ + 52; + const absBottomZ = player.originZ - 52; + if (x < absLeftX || x > absRightX || z2 < absBottomZ || z2 > absTopZ) { + player.unsetMapFlag(); + return false; + } + const listener = player.invListeners.find(l => l.com === comId); + if (!listener) { + player.unsetMapFlag(); + return false; + } + const inv = player.getInventoryFromListener(listener); + if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { + player.unsetMapFlag(); + return false; + } + const obj = World_default.getObj(x, z2, player.level, objId, player.pid); + if (!obj) { + player.unsetMapFlag(); + return false; + } + if (ObjType.get(item).members && !Environment_default.NODE_MEMBERS) { + player.messageGame("To use this item please login to a members' server."); + player.unsetMapFlag(); + return false; + } + player.lastUseItem = item; + player.lastUseSlot = slot; + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, obj, ServerTriggerType_default.APOBJU); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpPlayerHandler.ts +class OpPlayerHandler extends MessageHandler { + handle(message, player) { + const {pid} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const other = World_default.getPlayer(pid); + if (!other) { + player.unsetMapFlag(); + return false; + } + if (!player.buildArea.players.has(other.uid)) { + player.unsetMapFlag(); + return false; + } + let mode; + if (message.op === 1) { + mode = ServerTriggerType_default.APPLAYER1; + } else if (message.op === 2) { + mode = ServerTriggerType_default.APPLAYER2; + } else if (message.op === 3) { + mode = ServerTriggerType_default.APPLAYER3; + } else { + mode = ServerTriggerType_default.APPLAYER4; + } + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, other, mode); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpPlayerTHandler.ts +class OpPlayerTHandler extends MessageHandler { + handle(message, player) { + const {pid, spellComponent: spellComId} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const spellCom = Component.get(spellComId); + if (typeof spellCom === 'undefined' || !player.isComponentVisible(spellCom)) { + player.unsetMapFlag(); + return false; + } + const other = World_default.getPlayer(pid); + if (!other) { + player.unsetMapFlag(); + return false; + } + if (!player.buildArea.players.has(other.uid)) { + player.unsetMapFlag(); + return false; + } + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, other, ServerTriggerType_default.APPLAYERT, {type: -1, com: spellComId}); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/OpPlayerUHandler.ts +class OpPlayerUHandler extends MessageHandler { + handle(message, player) { + const {pid, useObj: item, useSlot: slot, useComponent: comId} = message; + if (player.delayed()) { + player.unsetMapFlag(); + return false; + } + const com = Component.get(comId); + if (typeof com === 'undefined' || !player.isComponentVisible(com)) { + player.unsetMapFlag(); + return false; + } + const listener = player.invListeners.find(l => l.com === comId); + if (!listener) { + player.unsetMapFlag(); + return false; + } + const inv = player.getInventoryFromListener(listener); + if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { + player.unsetMapFlag(); + return false; + } + const other = World_default.getPlayer(pid); + if (!other) { + player.unsetMapFlag(); + return false; + } + if (!player.buildArea.players.has(other.uid)) { + player.unsetMapFlag(); + return false; + } + if (ObjType.get(item).members && !Environment_default.NODE_MEMBERS) { + player.messageGame("To use this item please login to a members' server."); + player.unsetMapFlag(); + return false; + } + player.lastUseSlot = slot; + player.clearPendingAction(); + player.setInteraction(Interaction_default.ENGINE, other, ServerTriggerType_default.APPLAYERU, {type: item, com: -1}); + player.opcalled = true; + return true; + } +} + +// src/lostcity/network/225/incoming/handler/RebuildGetMapsHandler.ts +class RebuildGetMapsHandler extends MessageHandler { + handle(message, player) { + const {maps: requested} = message; + for (let i = 0; i < requested.length; i++) { + const {type, x, z: z2} = requested[i]; + const CHUNK_SIZE = 1000 - 1 - 2 - 1 - 1 - 2 - 2; + if (type == 0) { + const land = PRELOADED.get(`m${x}_${z2}`); + if (!land) { + continue; + } + for (let off = 0; off < land.length; off += CHUNK_SIZE) { + player.write(new DataLand(x, z2, off, land.length, land.subarray(off, off + CHUNK_SIZE))); + } + player.write(new DataLandDone(x, z2)); + } else if (type == 1) { + const loc = PRELOADED.get(`l${x}_${z2}`); + if (!loc) { + continue; + } + for (let off = 0; off < loc.length; off += CHUNK_SIZE) { + player.write(new DataLoc(x, z2, off, loc.length, loc.subarray(off, off + CHUNK_SIZE))); + } + player.write(new DataLocDone(x, z2)); + } + } + return true; + } +} + +// src/lostcity/network/225/incoming/handler/ResumePauseButtonHandler.ts +class ResumePauseButtonHandler extends MessageHandler { + handle(_message, player) { + if (!player.activeScript || player.activeScript.execution !== ScriptState.PAUSEBUTTON) { + return false; + } + player.executeScript(player.activeScript, true); + return true; + } +} + +// src/lostcity/network/225/incoming/handler/ResumePCountDialogHandler.ts +class ResumePCountDialogHandler extends MessageHandler { + handle(message, player) { + const {input} = message; + if (!player.activeScript || player.activeScript.execution !== ScriptState.COUNTDIALOG) { + return false; + } + player.activeScript.lastInt = input; + player.executeScript(player.activeScript, true); + return true; + } +} + +// src/lostcity/network/225/incoming/handler/TutorialClickSideHandler.ts +class TutorialClickSideHandler extends MessageHandler { + handle(message, player) { + const {tab} = message; + if (tab < 0 || tab > 13) { + return false; + } + const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.TUTORIAL_CLICKSIDE, -1, -1); + if (script) { + player.executeScript(ScriptRunner2.init(script, player), true); + } + return true; + } +} + +// src/lostcity/network/incoming/model/MoveClick.ts +class MoveClick extends IncomingMessage { + path; + ctrlHeld; + opClick; + category = ClientProtCategory.USER_EVENT; + constructor(path, ctrlHeld, opClick) { + super(); + this.path = path; + this.ctrlHeld = ctrlHeld; + this.opClick = opClick; + } +} + +// src/lostcity/network/225/incoming/codec/MoveClickDecoder.ts +class MoveClickDecoder extends MessageDecoder { + prot; + constructor(prot) { + super(); + this.prot = prot; + } + decode(buf) { + const ctrlHeld = buf.g1(); + const startX = buf.g2(); + const startZ = buf.g2(); + const offset = this.prot === ClientProt.MOVE_MINIMAPCLICK ? 14 : 0; + const waypoints = (buf.available - offset) >> 1; + const path = [{x: startX, z: startZ}]; + for (let index = 1; index <= waypoints && index < 25; index++) { + path.push({ + x: startX + buf.g1b(), + z: startZ + buf.g1b() + }); + } + return new MoveClick(path, ctrlHeld, this.prot === ClientProt.MOVE_OPCLICK); + } +} + +// src/lostcity/network/225/incoming/handler/MoveClickHandler.ts +class MoveClickHandler extends MessageHandler { + handle(message, player) { + const start = message.path[0]; + if (player.delayed() || message.ctrlHeld < 0 || message.ctrlHeld > 1 || Position.distanceToSW(player, {x: start.x, z: start.z}) > 104) { + player.unsetMapFlag(); + player.userPath = []; + return false; + } + if (Environment_default.NODE_CLIENT_ROUTEFINDER) { + player.userPath = []; + for (let i = 0; i < message.path.length; i++) { + player.userPath[i] = Position.packCoord(player.level, message.path[i].x, message.path[i].z); + } + } else { + const dest = message.path[message.path.length - 1]; + player.userPath = [Position.packCoord(player.level, dest.x, dest.z)]; + } + player.interactWalkTrigger = false; + if (!message.opClick) { + player.clearInteraction(); + player.closeModal(); + } + if (player.runenergy < 100) { + player.setVar(VarPlayerType.TEMP_RUN, 0); + } else { + player.setVar(VarPlayerType.TEMP_RUN, message.ctrlHeld); + } + return true; + } +} + +// src/lostcity/network/225/incoming/prot/ClientProtRepository.ts +class ClientProtRepository { + decoders = new Map(); + handlers = new Map(); + bind(decoder, handler) { + if (this.decoders.has(decoder.prot.id)) { + throw new Error(`[ClientProtRepository] Already defines a ${decoder.prot.id}.`); + } + this.decoders.set(decoder.prot.id, decoder); + if (handler) { + this.handlers.set(decoder.prot.id, handler); + } + } + constructor() { + this.bind(new ClientCheatDecoder(), new ClientCheatHandler()); + this.bind(new CloseModalDecoder(), new CloseModalHandler()); + this.bind(new IdleTimerDecoder(), new IdleTimerHandler()); + this.bind(new IfButtonDecoder(), new IfButtonHandler()); + this.bind(new IfPlayerDesignDecoder(), new IfPlayerDesignHandler()); + this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON1, 1), new InvButtonHandler()); + this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON2, 2), new InvButtonHandler()); + this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON3, 3), new InvButtonHandler()); + this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON4, 4), new InvButtonHandler()); + this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON5, 5), new InvButtonHandler()); + this.bind(new InvButtonDDecoder(), new InvButtonDHandler()); + this.bind(new MessagePrivateDecoder(), new MessagePrivateHandler()); + this.bind(new MessagePublicDecoder(), new MessagePublicHandler()); + this.bind(new MoveClickDecoder(ClientProt.MOVE_GAMECLICK), new MoveClickHandler()); + this.bind(new MoveClickDecoder(ClientProt.MOVE_OPCLICK), new MoveClickHandler()); + this.bind(new MoveClickDecoder(ClientProt.MOVE_MINIMAPCLICK), new MoveClickHandler()); + this.bind(new OpHeldDecoder(ClientProt.OPHELD1, 1), new OpHeldHandler()); + this.bind(new OpHeldDecoder(ClientProt.OPHELD2, 2), new OpHeldHandler()); + this.bind(new OpHeldDecoder(ClientProt.OPHELD3, 3), new OpHeldHandler()); + this.bind(new OpHeldDecoder(ClientProt.OPHELD4, 4), new OpHeldHandler()); + this.bind(new OpHeldDecoder(ClientProt.OPHELD5, 5), new OpHeldHandler()); + this.bind(new OpHeldTDecoder(), new OpHeldTHandler()); + this.bind(new OpHeldUDecoder(), new OpHeldUHandler()); + this.bind(new OpLocDecoder(ClientProt.OPLOC1, 1), new OpLocHandler()); + this.bind(new OpLocDecoder(ClientProt.OPLOC2, 2), new OpLocHandler()); + this.bind(new OpLocDecoder(ClientProt.OPLOC3, 3), new OpLocHandler()); + this.bind(new OpLocDecoder(ClientProt.OPLOC4, 4), new OpLocHandler()); + this.bind(new OpLocDecoder(ClientProt.OPLOC5, 5), new OpLocHandler()); + this.bind(new OpLocTDecoder(), new OpLocTHandler()); + this.bind(new OpLocUDecoder(), new OpLocUHandler()); + this.bind(new OpNpcDecoder(ClientProt.OPNPC1, 1), new OpNpcHandler()); + this.bind(new OpNpcDecoder(ClientProt.OPNPC2, 2), new OpNpcHandler()); + this.bind(new OpNpcDecoder(ClientProt.OPNPC3, 3), new OpNpcHandler()); + this.bind(new OpNpcDecoder(ClientProt.OPNPC4, 4), new OpNpcHandler()); + this.bind(new OpNpcDecoder(ClientProt.OPNPC5, 5), new OpNpcHandler()); + this.bind(new OpNpcTDecoder(), new OpNpcTHandler()); + this.bind(new OpNpcUDecoder(), new OpNpcUHandler()); + this.bind(new OpObjDecoder(ClientProt.OPOBJ1, 1), new OpObjHandler()); + this.bind(new OpObjDecoder(ClientProt.OPOBJ2, 2), new OpObjHandler()); + this.bind(new OpObjDecoder(ClientProt.OPOBJ3, 3), new OpObjHandler()); + this.bind(new OpObjDecoder(ClientProt.OPOBJ4, 4), new OpObjHandler()); + this.bind(new OpObjDecoder(ClientProt.OPOBJ5, 5), new OpObjHandler()); + this.bind(new OpObjTDecoder(), new OpObjTHandler()); + this.bind(new OpObjUDecoder(), new OpObjUHandler()); + this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER1, 1), new OpPlayerHandler()); + this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER2, 2), new OpPlayerHandler()); + this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER3, 3), new OpPlayerHandler()); + this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER4, 4), new OpPlayerHandler()); + this.bind(new OpPlayerTDecoder(), new OpPlayerTHandler()); + this.bind(new OpPlayerUDecoder(), new OpPlayerUHandler()); + this.bind(new RebuildGetMapsDecoder(), new RebuildGetMapsHandler()); + this.bind(new ResumePauseButtonDecoder(), new ResumePauseButtonHandler()); + this.bind(new ResumePCountDialogDecoder(), new ResumePCountDialogHandler()); + this.bind(new TutorialClickSideDecoder(), new TutorialClickSideHandler()); + } + getDecoder(prot) { + return this.decoders.get(prot.id); + } + getHandler(prot) { + return this.handlers.get(prot.id); + } +} +var ClientProtRepository_default = new ClientProtRepository(); + +// src/lostcity/entity/NetworkPlayer.ts +function isNetworkPlayer(player) { + return player.client !== null && player.client !== undefined; +} + +class NetworkPlayer2 extends Player2 { + client = null; + userPath = []; + opcalled = false; + constructor(username, username37, client) { + super(username, username37); + this.client = client; + this.client.player = this; + } + decodeIn() { + this.userPath = []; + this.opcalled = false; + if (this.client === null) { + return; + } + let offset = 0; + this.lastResponse = World_default.currentTick; + World_default.cycleStats[WorldStat_default.BANDWIDTH_IN] += this.client.inOffset; + while (this.client.inOffset > offset) { + const packetType = ClientProt.byId[this.client.in[offset++]]; + let length = packetType.length; + if (length == -1) { + length = this.client.in[offset++]; + } else if (length == -2) { + length = (this.client.in[offset++] << 8) | this.client.in[offset++]; + } + const data = new Packet(this.client.in.slice(offset, offset + length)); + offset += length; + const decoder = ClientProtRepository_default.getDecoder(packetType); + if (decoder) { + const message = decoder.decode(data); + const handler = ClientProtRepository_default.getHandler(packetType); + if (handler) { + handler.handle(message, this); + } + } + } + this.client?.reset(); + } + encodeOut() { + if (!this.client) { + return; + } + if (this.modalTop !== this.lastModalTop || this.modalBottom !== this.lastModalBottom || this.modalSidebar !== this.lastModalSidebar || this.refreshModalClose) { + if (this.refreshModalClose) { + this.write(new IfClose()); + } + this.refreshModalClose = false; + this.lastModalTop = this.modalTop; + this.lastModalBottom = this.modalBottom; + this.lastModalSidebar = this.modalSidebar; + } + if (this.refreshModal) { + if ((this.modalState & 1) === 1 && (this.modalState & 4) === 4) { + this.write(new IfOpenMainSideModal(this.modalTop, this.modalSidebar)); + } else if ((this.modalState & 1) === 1) { + this.write(new IfOpenMainModal(this.modalTop)); + } else if ((this.modalState & 2) === 2) { + this.write(new IfOpenChatModal(this.modalBottom)); + } else if ((this.modalState & 4) === 4) { + this.write(new IfOpenSideModal(this.modalSidebar)); + } + this.refreshModal = false; + } + for (let message = this.highPriorityOut.head(); message; message = this.highPriorityOut.next()) { + this.writeInner(message); + message.uncache(); + } + for (let message = this.lowPriorityOut.head(); message; message = this.lowPriorityOut.next()) { + this.writeInner(message); + message.uncache(); + } + this.client.flush(); + } + writeInner(message) { + const client = this.client; + if (!client) { + return; + } + const encoder = ServerProtRepository_default.getEncoder(message); + if (!encoder) { + console.error('No encoder for message', message); + return; + } + const prot = encoder.prot; + const buf = client.out; + const test = 1 + (prot.length === -1 ? 1 : prot.length === -2 ? 2 : 0) + encoder.test(message); + if (buf.pos + test >= buf.length) { + client.flush(); + } + const pos = buf.pos; + buf.p1(prot.id); + if (prot.length === -1) { + buf.pos += 1; + } else if (prot.length === -2) { + buf.pos += 2; + } + const start = buf.pos; + encoder.encode(buf, message); + if (prot.length === -1) { + buf.psize1(buf.pos - start); + } else if (prot.length === -2) { + buf.psize2(buf.pos - start); + } + if (client.encryptor) { + buf.data[pos] = (buf.data[pos] + client.encryptor.nextInt()) & 255; + } + World_default.cycleStats[WorldStat_default.BANDWIDTH_OUT] += buf.pos - pos; + } + logout() { + this.writeInner(new Logout()); + this.client?.flush(); + } + terminate() { + this.client?.terminate(); + this.client = null; + } + playerLog(message, ...args) { + if (typeof self !== 'undefined') { + return; + } + if (args.length > 0) { + fs24.appendFileSync(`data/players/${this.username}.log`, `[${new Date().toISOString().split('T')[0]} ${this.client?.remoteAddress}]: ${message} ${args.join(' ')}\n`); + } else { + fs24.appendFileSync(`data/players/${this.username}.log`, `[${new Date().toISOString().split('T')[0]} ${this.client?.remoteAddress}]: ${message}\n`); + } + } + updateMap() { + const loadedZones = this.buildArea.loadedZones; + const activeZones = this.buildArea.activeZones; + const reloadLeftX = (Position.zone(this.originX) - 4) << 3; + const reloadRightX = (Position.zone(this.originX) + 5) << 3; + const reloadTopZ = (Position.zone(this.originZ) + 5) << 3; + const reloadBottomZ = (Position.zone(this.originZ) - 4) << 3; + if (this.x < reloadLeftX || this.z < reloadBottomZ || this.x > reloadRightX - 1 || this.z > reloadTopZ - 1) { + this.write(new RebuildNormal(Position.zone(this.x), Position.zone(this.z))); + this.originX = this.x; + this.originZ = this.z; + loadedZones.clear(); + } + for (let info = this.cameraPackets.head(); info !== null; info = this.cameraPackets.next()) { + const localX = info.camX - Position.zoneOrigin(this.originX); + const localZ = info.camZ - Position.zoneOrigin(this.originZ); + if (info.type === ServerProt.CAM_MOVETO) { + this.write(new CamMoveTo(localX, localZ, info.height, info.rotationSpeed, info.rotationMultiplier)); + } else if (info.type === ServerProt.CAM_LOOKAT) { + this.write(new CamLookAt(localX, localZ, info.height, info.rotationSpeed, info.rotationMultiplier)); + } + info.unlink(); + } + if (this.moveSpeed === MoveSpeed_default.INSTANT && this.jump) { + loadedZones.clear(); + } + activeZones.clear(); + const centerX = Position.zone(this.x); + const centerZ = Position.zone(this.z); + const leftX = Position.zone(this.originX) - 6; + const rightX = Position.zone(this.originX) + 6; + const topZ = Position.zone(this.originZ) + 6; + const bottomZ = Position.zone(this.originZ) - 6; + for (let x = centerX - 3; x <= centerX + 3; x++) { + for (let z2 = centerZ - 3; z2 <= centerZ + 3; z2++) { + if (x < leftX || x > rightX || z2 > topZ || z2 < bottomZ) { + continue; + } + activeZones.add(ZoneMap2.zoneIndex(x << 3, z2 << 3, this.level)); + } + } + } + updatePlayers() { + this.write(new PlayerInfo(this.buildArea, this.level, this.x, this.z, this.originX, this.originZ, this.uid, this.mask, this.tele, this.jump, this.walkDir, this.runDir)); + } + updateNpcs() { + this.write(new NpcInfo(this.buildArea, this.level, this.x, this.z, this.originX, this.originZ)); + } + updateZones() { + const loadedZones = this.buildArea.loadedZones; + const activeZones = this.buildArea.activeZones; + for (const zoneIndex of loadedZones) { + if (!activeZones.has(zoneIndex)) { + loadedZones.delete(zoneIndex); + } + } + for (const zoneIndex of activeZones) { + const zone = World_default.getZoneIndex(zoneIndex); + if (!loadedZones.has(zone.index)) { + zone.writeFullFollows(this); + } else { + zone.writePartialEncloses(this); + zone.writePartialFollows(this); + } + loadedZones.add(zone.index); + } + } + updateStats() { + for (let i = 0; i < this.stats.length; i++) { + if (this.stats[i] !== this.lastStats[i] || this.levels[i] !== this.lastLevels[i]) { + this.write(new UpdateStat(i, this.stats[i], this.levels[i])); + this.lastStats[i] = this.stats[i]; + this.lastLevels[i] = this.levels[i]; + } + } + if (Math.floor(this.runenergy) / 100 !== Math.floor(this.lastRunEnergy) / 100) { + this.write(new UpdateRunEnergy(this.runenergy)); + this.lastRunEnergy = this.runenergy; + } + } + updateInvs() { + let runWeightChanged = false; + let firstSeen = false; + for (let i = 0; i < this.invListeners.length; i++) { + const listener = this.invListeners[i]; + if (!listener) { + continue; + } + if (listener.source === -1) { + const inv = World_default.getInventory(listener.type); + if (!inv) { + continue; + } + if (inv.update || listener.firstSeen) { + this.write(new UpdateInvFull(listener.com, inv)); + listener.firstSeen = false; + } + } else { + const player = World_default.getPlayerByUid(listener.source); + if (!player) { + continue; + } + const inv = player.getInventory(listener.type); + if (!inv) { + continue; + } + if (inv.update || listener.firstSeen) { + this.write(new UpdateInvFull(listener.com, inv)); + if (listener.firstSeen) { + firstSeen = true; + } + listener.firstSeen = false; + const invType = InvType.get(listener.type); + if (invType.runweight) { + runWeightChanged = true; + } + } + } + } + if (runWeightChanged) { + const current = this.runweight; + this.calculateRunWeight(); + runWeightChanged = current !== this.runweight; + } + if (runWeightChanged || firstSeen) { + this.write(new UpdateRunWeight(Math.ceil(this.runweight / 1000))); + } + } +} + +// src/lostcity/entity/CameraInfo.ts +class CameraInfo extends Linkable { + type; + camX; + camZ; + height; + rotationSpeed; + rotationMultiplier; + constructor(type, camX, camZ, height, rotationSpeed, rotationMultiplier) { + super(); + this.type = type; + this.camX = camX; + this.camZ = camZ; + this.height = height; + this.rotationSpeed = rotationSpeed; + this.rotationMultiplier = rotationMultiplier; + } +} + +// src/lostcity/util/ColorConversion.ts +class ColorConversion { + static hsl24to16(hue, saturation, lightness) { + if (lightness > 243) { + saturation >>= 4; + } else if (lightness > 217) { + saturation >>= 3; + } else if (lightness > 192) { + saturation >>= 2; + } else if (lightness > 179) { + saturation >>= 1; + } + return (((hue & 255) >> 2) << 10) + ((saturation >> 5) << 7) + (lightness >> 1); + } + static rgb15to24(rgb) { + const r = (rgb >> 10) & 31; + const g = (rgb >> 5) & 31; + const b3 = rgb & 31; + return ((r << 3) << 16) + ((g << 3) << 8) + (b3 << 3); + } + static rgb15toHsl16(rgb) { + const r = (rgb >> 10) & 31; + const g = (rgb >> 5) & 31; + const b3 = rgb & 31; + const red = r / 31; + const green = g / 31; + const blue = b3 / 31; + return ColorConversion.rgbToHsl(red, green, blue); + } + static rgb24to15(rgb) { + const r = (rgb >> 16) & 255; + const g = (rgb >> 8) & 255; + const b3 = rgb & 255; + return ((r >> 3) << 10) + ((g >> 3) << 5) + (b3 >> 3); + } + static rgb24toHsl16(rgb) { + const r = (rgb >> 16) & 255; + const g = (rgb >> 8) & 255; + const b3 = rgb & 255; + const red = r / 256; + const green = g / 256; + const blue = b3 / 256; + return ColorConversion.rgbToHsl(red, green, blue); + } + static rgbToHsl(red, green, blue) { + let min = red; + if (green < min) { + min = green; + } + if (blue < min) { + min = blue; + } + let max = red; + if (green > max) { + max = green; + } + if (blue > max) { + max = blue; + } + let hNorm = 0; + let sNorm = 0; + const lNorm = (min + max) / 2; + if (min !== max) { + if (lNorm < 0.5) { + sNorm = (max - min) / (max + min); + } else if (lNorm >= 0.5) { + sNorm = (max - min) / (2 - max - min); + } + if (red === max) { + hNorm = (green - blue) / (max - min); + } else if (green === max) { + hNorm = (blue - red) / (max - min) + 2; + } else if (blue === max) { + hNorm = (red - green) / (max - min) + 4; + } + } + hNorm /= 6; + const hue = (hNorm * 256) | 0; + let saturation = (sNorm * 256) | 0; + let lightness = (lNorm * 256) | 0; + if (saturation < 0) { + saturation = 0; + } else if (saturation > 255) { + saturation = 255; + } + if (lightness < 0) { + lightness = 0; + } else if (lightness > 255) { + lightness = 255; + } + return ColorConversion.hsl24to16(hue, saturation, lightness); + } + static RGB15_HSL16 = new Int32Array(32768); + static { + for (let rgb = 0; rgb < 32768; rgb++) { + ColorConversion.RGB15_HSL16[rgb] = ColorConversion.rgb15toHsl16(rgb); + } + } + static reverseHsl(hsl) { + const possible = []; + for (let rgb = 0; rgb < 32768; rgb++) { + if (ColorConversion.RGB15_HSL16[rgb] === hsl) { + possible.push(rgb); + } + } + return possible; + } +} + +// src/lostcity/engine/script/handlers/PlayerOps.ts +var popScriptArgs = function (state) { + const types = state.popString(); + const count = types.length; + const args = []; + for (let i = count - 1; i >= 0; i--) { + const type = types.charAt(i); + if (type === 's') { + args[i] = state.popString(); + } else { + args[i] = state.popInt(); + } + } + return args; +}; +var PlayerOps = { + [ScriptOpcode_default.FINDUID]: state => { + const uid = state.popInt(); + const player = World_default.getPlayerByUid(uid); + if (!player) { + state.pushInt(0); + return; + } + state.activePlayer = player; + state.pointerAdd(ActivePlayer[state.intOperand]); + state.pushInt(1); + }, + [ScriptOpcode_default.P_FINDUID]: state => { + const uid = state.popInt() >>> 0; + const player = World_default.getPlayerByUid(uid); + if (state.pointerGet(ProtectedActivePlayer[state.intOperand]) && state.activePlayer.uid === uid) { + state.pushInt(1); + return; + } + if (!player || !player.canAccess()) { + state.pushInt(0); + return; + } + state.activePlayer = player; + state.pointerAdd(ActivePlayer[state.intOperand]); + state.pointerAdd(ProtectedActivePlayer[state.intOperand]); + state.pushInt(1); + }, + [ScriptOpcode_default.STRONGQUEUE]: checkedHandler(ActivePlayer, state => { + const args = popScriptArgs(state); + const delay = check(state.popInt(), NumberNotNull); + const scriptId = state.popInt(); + const script = ScriptProvider.get(scriptId); + if (!script) { + throw new Error(`Unable to find queue script: ${scriptId}`); + } + state.activePlayer.enqueueScript(script, 3 /* STRONG */, delay, args); + }), + [ScriptOpcode_default.WEAKQUEUE]: checkedHandler(ActivePlayer, state => { + const args = popScriptArgs(state); + const delay = check(state.popInt(), NumberNotNull); + const scriptId = state.popInt(); + const script = ScriptProvider.get(scriptId); + if (!script) { + throw new Error(`Unable to find queue script: ${scriptId}`); + } + state.activePlayer.enqueueScript(script, 2 /* WEAK */, delay, args); + }), + [ScriptOpcode_default.QUEUE]: checkedHandler(ActivePlayer, state => { + const args = popScriptArgs(state); + const delay = check(state.popInt(), NumberNotNull); + const scriptId = state.popInt(); + const script = ScriptProvider.get(scriptId); + if (!script) { + throw new Error(`Unable to find queue script: ${scriptId}`); + } + state.activePlayer.enqueueScript(script, 0 /* NORMAL */, delay, args); + }), + [ScriptOpcode_default.ANIM]: checkedHandler(ActivePlayer, state => { + const delay = state.popInt(); + const seq = state.popInt(); + state.activePlayer.playAnimation(seq, delay); + }), + [ScriptOpcode_default.BUFFER_FULL]: checkedHandler(ActivePlayer, state => { + throw new Error('unimplemented'); + }), + [ScriptOpcode_default.BUILDAPPEARANCE]: checkedHandler(ActivePlayer, state => { + state.activePlayer.generateAppearance(check(state.popInt(), InvTypeValid).id); + }), + [ScriptOpcode_default.CAM_LOOKAT]: checkedHandler(ActivePlayer, state => { + const [coord, height, rotationSpeed, rotationMultiplier] = state.popInts(4); + const pos = check(coord, CoordValid); + state.activePlayer.cameraPackets.addTail(new CameraInfo(ServerProt.CAM_LOOKAT, pos.x, pos.z, height, rotationSpeed, rotationMultiplier)); + }), + [ScriptOpcode_default.CAM_MOVETO]: checkedHandler(ActivePlayer, state => { + const [coord, height, rotationSpeed, rotationMultiplier] = state.popInts(4); + const pos = check(coord, CoordValid); + state.activePlayer.cameraPackets.addTail(new CameraInfo(ServerProt.CAM_MOVETO, pos.x, pos.z, height, rotationSpeed, rotationMultiplier)); + }), + [ScriptOpcode_default.CAM_SHAKE]: checkedHandler(ActivePlayer, state => { + const [type, jitter, amplitude, frequency] = state.popInts(4); + state.activePlayer.write(new CamShake(type, jitter, amplitude, frequency)); + }), + [ScriptOpcode_default.CAM_RESET]: checkedHandler(ActivePlayer, state => { + state.activePlayer.write(new CamReset()); + }), + [ScriptOpcode_default.COORD]: checkedHandler(ActivePlayer, state => { + const position = state.activePlayer; + state.pushInt(Position.packCoord(position.level, position.x, position.z)); + }), + [ScriptOpcode_default.DISPLAYNAME]: checkedHandler(ActivePlayer, state => { + state.pushString(state.activePlayer.displayName); + }), + [ScriptOpcode_default.FACESQUARE]: checkedHandler(ActivePlayer, state => { + const pos = check(state.popInt(), CoordValid); + state.activePlayer.faceSquare(pos.x, pos.z); + }), + [ScriptOpcode_default.IF_CLOSE]: checkedHandler(ActivePlayer, state => { + state.activePlayer.closeModal(); + }), + [ScriptOpcode_default.LAST_COM]: state => { + state.pushInt(state.activePlayer.lastCom); + }, + [ScriptOpcode_default.LAST_INT]: state => { + state.pushInt(state.lastInt); + }, + [ScriptOpcode_default.LAST_ITEM]: state => { + const allowedTriggers = [ + ServerTriggerType_default.OPHELD1, + ServerTriggerType_default.OPHELD2, + ServerTriggerType_default.OPHELD3, + ServerTriggerType_default.OPHELD4, + ServerTriggerType_default.OPHELD5, + ServerTriggerType_default.OPHELDU, + ServerTriggerType_default.OPHELDT, + ServerTriggerType_default.INV_BUTTON1, + ServerTriggerType_default.INV_BUTTON2, + ServerTriggerType_default.INV_BUTTON3, + ServerTriggerType_default.INV_BUTTON4, + ServerTriggerType_default.INV_BUTTON5 + ]; + if (!allowedTriggers.includes(state.trigger)) { + throw new Error('is not safe to use in this trigger'); + } + state.pushInt(state.activePlayer.lastItem); + }, + [ScriptOpcode_default.LAST_SLOT]: state => { + const allowedTriggers = [ + ServerTriggerType_default.OPHELD1, + ServerTriggerType_default.OPHELD2, + ServerTriggerType_default.OPHELD3, + ServerTriggerType_default.OPHELD4, + ServerTriggerType_default.OPHELD5, + ServerTriggerType_default.OPHELDU, + ServerTriggerType_default.OPHELDT, + ServerTriggerType_default.INV_BUTTON1, + ServerTriggerType_default.INV_BUTTON2, + ServerTriggerType_default.INV_BUTTON3, + ServerTriggerType_default.INV_BUTTON4, + ServerTriggerType_default.INV_BUTTON5, + ServerTriggerType_default.INV_BUTTOND + ]; + if (!allowedTriggers.includes(state.trigger)) { + throw new Error('is not safe to use in this trigger'); + } + state.pushInt(state.activePlayer.lastSlot); + }, + [ScriptOpcode_default.LAST_USEITEM]: state => { + const allowedTriggers = [ + ServerTriggerType_default.OPHELDU, + ServerTriggerType_default.APOBJU, + ServerTriggerType_default.APLOCU, + ServerTriggerType_default.APNPCU, + ServerTriggerType_default.APPLAYERU, + ServerTriggerType_default.OPOBJU, + ServerTriggerType_default.OPLOCU, + ServerTriggerType_default.OPNPCU, + ServerTriggerType_default.OPPLAYERU + ]; + if (!allowedTriggers.includes(state.trigger)) { + throw new Error('is not safe to use in this trigger'); + } + state.pushInt(state.activePlayer.lastUseItem); + }, + [ScriptOpcode_default.LAST_USESLOT]: state => { + const allowedTriggers = [ + ServerTriggerType_default.OPHELDU, + ServerTriggerType_default.APOBJU, + ServerTriggerType_default.APLOCU, + ServerTriggerType_default.APNPCU, + ServerTriggerType_default.APPLAYERU, + ServerTriggerType_default.OPOBJU, + ServerTriggerType_default.OPLOCU, + ServerTriggerType_default.OPNPCU, + ServerTriggerType_default.OPPLAYERU + ]; + if (!allowedTriggers.includes(state.trigger)) { + throw new Error('is not safe to use in this trigger'); + } + state.pushInt(state.activePlayer.lastUseSlot); + }, + [ScriptOpcode_default.MES]: checkedHandler(ActivePlayer, state => { + const message = state.popString(); + state.activePlayer.messageGame(message); + }), + [ScriptOpcode_default.NAME]: checkedHandler(ActivePlayer, state => { + state.pushString(state.activePlayer.username); + }), + [ScriptOpcode_default.P_APRANGE]: checkedHandler(ProtectedActivePlayer, state => { + state.activePlayer.apRange = check(state.popInt(), NumberNotNull); + state.activePlayer.apRangeCalled = true; + }), + [ScriptOpcode_default.P_ARRIVEDELAY]: checkedHandler(ProtectedActivePlayer, state => { + if (state.activePlayer.lastMovement < World_default.currentTick) { + return; + } + state.activePlayer.delay = 1; + state.execution = ScriptState.SUSPENDED; + }), + [ScriptOpcode_default.P_COUNTDIALOG]: checkedHandler(ProtectedActivePlayer, state => { + state.activePlayer.write(new PCountDialog()); + state.execution = ScriptState.COUNTDIALOG; + }), + [ScriptOpcode_default.P_DELAY]: checkedHandler(ProtectedActivePlayer, state => { + state.activePlayer.delay = check(state.popInt(), NumberNotNull) + 1; + state.execution = ScriptState.SUSPENDED; + }), + [ScriptOpcode_default.P_OPHELD]: checkedHandler(ProtectedActivePlayer, state => { + throw new Error('unimplemented'); + }), + [ScriptOpcode_default.P_OPLOC]: checkedHandler(ProtectedActivePlayer, state => { + const type = check(state.popInt(), NumberNotNull) - 1; + if (type < 0 || type >= 5) { + throw new Error(`Invalid oploc: ${type + 1}`); + } + state.activePlayer.stopAction(); + state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeLoc, ServerTriggerType_default.APLOC1 + type); + }), + [ScriptOpcode_default.P_OPNPC]: checkedHandler(ProtectedActivePlayer, state => { + const type = check(state.popInt(), NumberNotNull) - 1; + if (type < 0 || type >= 5) { + throw new Error(`Invalid opnpc: ${type + 1}`); + } + state.activePlayer.stopAction(); + state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeNpc, ServerTriggerType_default.APNPC1 + type, {type: state.activeNpc.type, com: -1}); + }), + [ScriptOpcode_default.P_OPNPCT]: checkedHandler(ProtectedActivePlayer, state => { + const spellId = check(state.popInt(), NumberNotNull); + state.activePlayer.stopAction(); + state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeNpc, ServerTriggerType_default.APNPCT, {type: state.activeNpc.type, com: spellId}); + }), + [ScriptOpcode_default.P_PAUSEBUTTON]: checkedHandler(ProtectedActivePlayer, state => { + state.execution = ScriptState.PAUSEBUTTON; + }), + [ScriptOpcode_default.P_STOPACTION]: checkedHandler(ProtectedActivePlayer, state => { + state.activePlayer.stopAction(); + }), + [ScriptOpcode_default.P_CLEARPENDINGACTION]: checkedHandler(ProtectedActivePlayer, state => { + state.activePlayer.clearPendingAction(); + }), + [ScriptOpcode_default.P_TELEJUMP]: checkedHandler(ProtectedActivePlayer, state => { + const position = check(state.popInt(), CoordValid); + state.activePlayer.teleJump(position.x, position.z, position.level); + }), + [ScriptOpcode_default.P_TELEPORT]: checkedHandler(ProtectedActivePlayer, state => { + const position = check(state.popInt(), CoordValid); + state.activePlayer.teleport(position.x, position.z, position.level); + }), + [ScriptOpcode_default.P_WALK]: checkedHandler(ProtectedActivePlayer, state => { + const pos = check(state.popInt(), CoordValid); + const player = state.activePlayer; + player.queueWaypoints(findPath(player.level, player.x, player.z, pos.x, pos.z, player.width, player.width, player.length, player.orientation)); + player.updateMovement(false); + }), + [ScriptOpcode_default.SAY]: checkedHandler(ActivePlayer, state => { + state.activePlayer.say(state.popString()); + }), + [ScriptOpcode_default.SOUND_SYNTH]: checkedHandler(ActivePlayer, state => { + const [synth, loops, delay] = state.popInts(3); + state.activePlayer.write(new SynthSound(synth, loops, delay)); + }), + [ScriptOpcode_default.STAFFMODLEVEL]: checkedHandler(ActivePlayer, state => { + state.pushInt(state.activePlayer.staffModLevel); + }), + [ScriptOpcode_default.STAT]: checkedHandler(ActivePlayer, state => { + const stat = check(state.popInt(), PlayerStatValid); + state.pushInt(state.activePlayer.levels[stat]); + }), + [ScriptOpcode_default.STAT_BASE]: checkedHandler(ActivePlayer, state => { + const stat = check(state.popInt(), PlayerStatValid); + state.pushInt(state.activePlayer.baseLevels[stat]); + }), + [ScriptOpcode_default.STAT_ADD]: checkedHandler(ActivePlayer, state => { + const [stat, constant, percent] = state.popInts(3); + check(stat, PlayerStatValid); + check(constant, NumberNotNull); + check(percent, NumberNotNull); + const player = state.activePlayer; + const current = player.levels[stat]; + const added = current + (constant + (current * percent) / 100); + player.levels[stat] = Math.min(added, 255); + if (stat === 3 && player.levels[3] >= player.baseLevels[3]) { + player.resetHeroPoints(); + } + }), + [ScriptOpcode_default.STAT_SUB]: checkedHandler(ActivePlayer, state => { + const [stat, constant, percent] = state.popInts(3); + check(stat, PlayerStatValid); + check(constant, NumberNotNull); + check(percent, NumberNotNull); + const player = state.activePlayer; + const current = player.levels[stat]; + const subbed = current - (constant + (current * percent) / 100); + player.levels[stat] = Math.max(subbed, 0); + }), + [ScriptOpcode_default.SPOTANIM_PL]: checkedHandler(ActivePlayer, state => { + const delay = check(state.popInt(), NumberNotNull); + const height = state.popInt(); + const spotanimType = check(state.popInt(), SpotAnimTypeValid); + state.activePlayer.spotanim(spotanimType.id, height, delay); + }), + [ScriptOpcode_default.STAT_HEAL]: checkedHandler(ActivePlayer, state => { + const [stat, constant, percent] = state.popInts(3); + check(stat, PlayerStatValid); + check(constant, NumberNotNull); + check(percent, NumberNotNull); + const player = state.activePlayer; + const base = player.baseLevels[stat]; + const current = player.levels[stat]; + const healed = current + (constant + (current * percent) / 100); + player.levels[stat] = Math.max(Math.min(healed, base), current); + if (stat === 3 && player.levels[3] >= player.baseLevels[3]) { + player.resetHeroPoints(); + } + }), + [ScriptOpcode_default.UID]: checkedHandler(ActivePlayer, state => { + state.pushInt(state.activePlayer.uid); + }), + [ScriptOpcode_default.P_LOGOUT]: checkedHandler(ProtectedActivePlayer, state => { + state.activePlayer.logoutRequested = true; + }), + [ScriptOpcode_default.IF_SETCOLOUR]: checkedHandler(ActivePlayer, state => { + const [com, colour] = state.popInts(2); + check(com, NumberNotNull); + check(colour, NumberNotNull); + state.activePlayer.write(new IfSetColour(com, ColorConversion.rgb24to15(colour))); + }), + [ScriptOpcode_default.IF_OPENCHAT]: checkedHandler(ActivePlayer, state => { + state.activePlayer.openChat(check(state.popInt(), NumberNotNull)); + }), + [ScriptOpcode_default.IF_OPENMAINMODALSIDEOVERLAY]: checkedHandler(ActivePlayer, state => { + const [main, side] = state.popInts(2); + check(main, NumberNotNull); + check(side, NumberNotNull); + state.activePlayer.openMainModalSideOverlay(main, side); + }), + [ScriptOpcode_default.IF_SETHIDE]: checkedHandler(ActivePlayer, state => { + const [com, hide] = state.popInts(2); + check(com, NumberNotNull); + check(hide, NumberNotNull); + state.activePlayer.write(new IfSetHide(com, hide === 1)); + }), + [ScriptOpcode_default.IF_SETOBJECT]: checkedHandler(ActivePlayer, state => { + const [com, obj, scale] = state.popInts(3); + check(com, NumberNotNull); + check(obj, ObjTypeValid); + check(scale, NumberNotNull); + state.activePlayer.write(new IfSetObject(com, obj, scale)); + }), + [ScriptOpcode_default.IF_SETTABACTIVE]: checkedHandler(ActivePlayer, state => { + state.activePlayer.write(new IfShowSide(check(state.popInt(), NumberNotNull))); + }), + [ScriptOpcode_default.IF_SETMODEL]: checkedHandler(ActivePlayer, state => { + const [com, model] = state.popInts(2); + check(com, NumberNotNull); + check(model, NumberNotNull); + state.activePlayer.write(new IfSetModel(com, model)); + }), + [ScriptOpcode_default.IF_SETRECOL]: checkedHandler(ActivePlayer, state => { + const [com, src, dest] = state.popInts(3); + check(com, NumberNotNull); + state.activePlayer.write(new IfSetRecol(com, src, dest)); + }), + [ScriptOpcode_default.IF_SETTABFLASH]: checkedHandler(ActivePlayer, state => { + state.activePlayer.write(new TutorialFlashSide(check(state.popInt(), NumberNotNull))); + }), + [ScriptOpcode_default.IF_SETANIM]: checkedHandler(ActivePlayer, state => { + const [com, seq] = state.popInts(2); + check(com, NumberNotNull); + if (seq === -1) { + return; + } + state.activePlayer.write(new IfSetAnim(com, seq)); + }), + [ScriptOpcode_default.IF_SETTAB]: checkedHandler(ActivePlayer, state => { + const [com, tab] = state.popInts(2); + check(tab, NumberNotNull); + state.activePlayer.setTab(com, tab); + }), + [ScriptOpcode_default.IF_OPENMAINMODAL]: checkedHandler(ActivePlayer, state => { + state.activePlayer.openMainModal(check(state.popInt(), NumberNotNull)); + }), + [ScriptOpcode_default.IF_OPENCHATSTICKY]: checkedHandler(ActivePlayer, state => { + state.activePlayer.openChatSticky(check(state.popInt(), NumberNotNull)); + }), + [ScriptOpcode_default.IF_OPENSIDEOVERLAY]: checkedHandler(ActivePlayer, state => { + state.activePlayer.openSideOverlay(check(state.popInt(), NumberNotNull)); + }), + [ScriptOpcode_default.IF_SETPLAYERHEAD]: checkedHandler(ActivePlayer, state => { + state.activePlayer.write(new IfSetPlayerHead(check(state.popInt(), NumberNotNull))); + }), + [ScriptOpcode_default.IF_SETTEXT]: checkedHandler(ActivePlayer, state => { + const text = state.popString(); + const com = check(state.popInt(), NumberNotNull); + state.activePlayer.write(new IfSetText(com, text)); + }), + [ScriptOpcode_default.IF_SETNPCHEAD]: checkedHandler(ActivePlayer, state => { + const [com, npc] = state.popInts(2); + check(com, NumberNotNull); + check(npc, NpcTypeValid); + state.activePlayer.write(new IfSetNpcHead(com, npc)); + }), + [ScriptOpcode_default.IF_SETPOSITION]: checkedHandler(ActivePlayer, state => { + const [com, x, y3] = state.popInts(3); + check(com, NumberNotNull); + state.activePlayer.write(new IfSetPosition(com, x, y3)); + }), + [ScriptOpcode_default.IF_MULTIZONE]: checkedHandler(ActivePlayer, state => { + state.activePlayer.write(new SetMultiway(check(state.popInt(), NumberNotNull) === 1)); + }), + [ScriptOpcode_default.GIVEXP]: checkedHandler(ProtectedActivePlayer, state => { + const [stat, xp] = state.popInts(2); + check(stat, NumberNotNull); + check(xp, NumberNotNull); + state.activePlayer.addXp(stat, xp); + }), + [ScriptOpcode_default.DAMAGE]: state => { + const amount = check(state.popInt(), NumberNotNull); + const type = check(state.popInt(), HitTypeValid); + const uid = check(state.popInt(), NumberNotNull); + const player = World_default.getPlayerByUid(uid); + if (!player) { + return; + } + player.applyDamage(amount, type); + }, + [ScriptOpcode_default.IF_SETRESUMEBUTTONS]: checkedHandler(ActivePlayer, state => { + const [button1, button2, button3, button4, button5] = state.popInts(5); + state.activePlayer.resumeButtons = [button1, button2, button3, button4, button5]; + }), + [ScriptOpcode_default.TEXT_GENDER]: checkedHandler(ActivePlayer, state => { + const [male, female] = state.popStrings(2); + if (state.activePlayer.gender == 0) { + state.pushString(male); + } else { + state.pushString(female); + } + }), + [ScriptOpcode_default.MIDI_SONG]: state => { + state.activePlayer.playSong(check(state.popString(), StringNotNull)); + }, + [ScriptOpcode_default.MIDI_JINGLE]: state => { + const delay = check(state.popInt(), NumberNotNull); + const name = check(state.popString(), StringNotNull); + state.activePlayer.playJingle(delay, name); + }, + [ScriptOpcode_default.SOFTTIMER]: checkedHandler(ActivePlayer, state => { + const args = popScriptArgs(state); + const interval = state.popInt(); + const timerId = state.popInt(); + const script = ScriptProvider.get(timerId); + if (!script) { + throw new Error(`Unable to find timer script: ${timerId}`); + } + state.activePlayer.setTimer(1 /* SOFT */, script, args, interval); + }), + [ScriptOpcode_default.CLEARSOFTTIMER]: checkedHandler(ActivePlayer, state => { + state.activePlayer.clearTimer(state.popInt()); + }), + [ScriptOpcode_default.SETTIMER]: checkedHandler(ActivePlayer, state => { + const args = popScriptArgs(state); + const interval = state.popInt(); + const timerId = state.popInt(); + const script = ScriptProvider.get(timerId); + if (!script) { + throw new Error(`Unable to find timer script: ${timerId}`); + } + state.activePlayer.setTimer(0 /* NORMAL */, script, args, interval); + }), + [ScriptOpcode_default.CLEARTIMER]: checkedHandler(ActivePlayer, state => { + state.activePlayer.clearTimer(state.popInt()); + }), + [ScriptOpcode_default.HINT_COORD]: state => { + const [offset, coord, height] = state.popInts(3); + const position = check(coord, CoordValid); + state.activePlayer.hintTile(offset, position.x, position.z, height); + }, + [ScriptOpcode_default.HINT_STOP]: state => { + state.activePlayer.stopHint(); + }, + [ScriptOpcode_default.IF_CLOSESTICKY]: state => { + state.activePlayer.closeSticky(); + }, + [ScriptOpcode_default.P_EXACTMOVE]: checkedHandler(ProtectedActivePlayer, state => { + const [start, end, startCycle, endCycle, direction] = state.popInts(5); + const startPos = check(start, CoordValid); + const endPos = check(end, CoordValid); + state.activePlayer.unsetMapFlag(); + state.activePlayer.exactMove(startPos.x, startPos.z, endPos.x, endPos.z, startCycle, endCycle, direction); + }), + [ScriptOpcode_default.BUSY]: state => { + state.pushInt(state.activePlayer.busy() ? 1 : 0); + }, + [ScriptOpcode_default.BUSY2]: state => { + state.pushInt(state.activePlayer.hasInteraction() || state.activePlayer.hasWaypoints() ? 1 : 0); + }, + [ScriptOpcode_default.GETQUEUE]: state => { + const scriptId = state.popInt(); + let count = 0; + for (let request = state.activePlayer.queue.head(); request !== null; request = state.activePlayer.queue.next()) { + if (request.script.id === scriptId) { + count++; + } + } + for (let request = state.activePlayer.weakQueue.head(); request !== null; request = state.activePlayer.weakQueue.next()) { + if (request.script.id === scriptId) { + count++; + } + } + state.pushInt(count); + }, + [ScriptOpcode_default.P_LOCMERGE]: checkedHandler(ProtectedActivePlayer, state => { + const [startCycle, endCycle, southEast, northWest] = state.popInts(4); + const se = check(southEast, CoordValid); + const nw = check(northWest, CoordValid); + World_default.mergeLoc(state.activeLoc, state.activePlayer, startCycle, endCycle, se.z, se.x, nw.z, nw.x); + }), + [ScriptOpcode_default.LAST_LOGIN_INFO]: state => { + const player = state.activePlayer; + if (!isNetworkPlayer(player) || player.client === null) { + return; + } + const client = player.client; + const remoteAddress = client.remoteAddress; + if (remoteAddress == null) { + return; + } + const lastLoginIp = new Uint32Array(new Uint8Array(remoteAddress.split('.').map(x => parseInt(x))).reverse().buffer)[0]; + player.lastLoginInfo(lastLoginIp, 0, 201, 0); + }, + [ScriptOpcode_default.BAS_READYANIM]: state => { + state.activePlayer.basReadyAnim = check(state.popInt(), SeqTypeValid).id; + }, + [ScriptOpcode_default.BAS_TURNONSPOT]: state => { + state.activePlayer.basTurnOnSpot = check(state.popInt(), SeqTypeValid).id; + }, + [ScriptOpcode_default.BAS_WALK_F]: state => { + state.activePlayer.basWalkForward = check(state.popInt(), SeqTypeValid).id; + }, + [ScriptOpcode_default.BAS_WALK_B]: state => { + state.activePlayer.basWalkBackward = check(state.popInt(), SeqTypeValid).id; + }, + [ScriptOpcode_default.BAS_WALK_L]: state => { + state.activePlayer.basWalkLeft = check(state.popInt(), SeqTypeValid).id; + }, + [ScriptOpcode_default.BAS_WALK_R]: state => { + state.activePlayer.basWalkRight = check(state.popInt(), SeqTypeValid).id; + }, + [ScriptOpcode_default.BAS_RUNNING]: state => { + const seq = state.popInt(); + if (seq === -1) { + state.activePlayer.basRunning = -1; + return; + } + state.activePlayer.basRunning = check(seq, SeqTypeValid).id; + }, + [ScriptOpcode_default.GENDER]: state => { + state.pushInt(state.activePlayer.gender); + }, + [ScriptOpcode_default.HINT_NPC]: state => { + state.activePlayer.hintNpc(check(state.popInt(), NumberNotNull)); + }, + [ScriptOpcode_default.HINT_PLAYER]: state => { + const uid = check(state.popInt(), NumberNotNull); + const player = World_default.getPlayerByUid(uid); + if (!player) { + return; + } + state.activePlayer.hintPlayer(player.pid); + }, + [ScriptOpcode_default.HEADICONS_GET]: state => { + state.pushInt(state.activePlayer.headicons); + }, + [ScriptOpcode_default.HEADICONS_SET]: state => { + state.activePlayer.headicons = check(state.popInt(), NumberNotNull); + }, + [ScriptOpcode_default.P_OPOBJ]: checkedHandler(ProtectedActivePlayer, state => { + const type = check(state.popInt(), NumberNotNull) - 1; + if (type < 0 || type >= 5) { + throw new Error(`Invalid opobj: ${type + 1}`); + } + state.activePlayer.stopAction(); + state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeObj, ServerTriggerType_default.APOBJ1 + type); + }), + [ScriptOpcode_default.P_OPPLAYER]: checkedHandler(ProtectedActivePlayer, state => { + const type = check(state.popInt(), NumberNotNull) - 1; + if (type < 0 || type >= 5) { + throw new Error(`Invalid opplayer: ${type + 1}`); + } + const target = state._activePlayer2; + if (!target) { + return; + } + state.activePlayer.stopAction(); + state.activePlayer.setInteraction(Interaction_default.SCRIPT, target, ServerTriggerType_default.APPLAYER1 + type); + }), + [ScriptOpcode_default.ALLOWDESIGN]: state => { + state.activePlayer.allowDesign = check(state.popInt(), NumberNotNull) === 1; + }, + [ScriptOpcode_default.LAST_TARGETSLOT]: state => { + const allowedTriggers = [ServerTriggerType_default.INV_BUTTOND]; + if (!allowedTriggers.includes(state.trigger)) { + throw new Error('is not safe to use in this trigger'); + } + state.pushInt(state.activePlayer.lastTargetSlot); + }, + [ScriptOpcode_default.WALKTRIGGER]: state => { + state.activePlayer.walktrigger = state.popInt(); + }, + [ScriptOpcode_default.GETWALKTRIGGER]: state => { + state.pushInt(state.activePlayer.walktrigger); + }, + [ScriptOpcode_default.CLEARQUEUE]: state => { + const scriptId = state.popInt(); + for (let request = state.activePlayer.queue.head(); request !== null; request = state.activePlayer.queue.next()) { + if (request.script.id === scriptId) { + request.unlink(); + } + } + for (let request = state.activePlayer.weakQueue.head(); request !== null; request = state.activePlayer.weakQueue.next()) { + if (request.script.id === scriptId) { + request.unlink(); + } + } + }, + [ScriptOpcode_default.HEALENERGY]: state => { + const amount = check(state.popInt(), NumberNotNull); + const player = state.activePlayer; + player.runenergy = Math.min(Math.max(player.runenergy + amount, 0), 1e4); + }, + [ScriptOpcode_default.AFK_EVENT]: state => { + state.pushInt(state.activePlayer.afkEventReady ? 1 : 0); + state.activePlayer.afkEventReady = false; + }, + [ScriptOpcode_default.LOWMEMORY]: state => { + state.pushInt(state.activePlayer.lowMemory ? 1 : 0); + }, + [ScriptOpcode_default.SETIDKIT]: state => { + const [idkit, color] = state.popInts(2); + const idkType = check(idkit, IDKTypeValid); + let slot = idkType.type; + if (state.activePlayer.gender === 1) { + slot -= 7; + } + state.activePlayer.body[slot] = idkType.id; + let type = idkType.type; + if (state.activePlayer.gender === 1) { + type -= 7; + } + let colorSlot = -1; + if (type === 0 || type === 1) { + colorSlot = 0; + } else if (type === 2 || type === 3) { + colorSlot = 1; + } else if (type === 4) { + } else if (type === 5) { + colorSlot = 2; + } else if (type === 6) { + colorSlot = 3; + } + if (colorSlot !== -1) { + state.activePlayer.colors[colorSlot] = color; + } + }, + [ScriptOpcode_default.SETGENDER]: state => { + const gender = check(state.popInt(), GenderValid); + for (let i = 0; i < 7; i++) { + state.activePlayer.body[i] = -1; + for (let j = 0; j < IdkType.count; j++) { + if (!IdkType.get(j).disable && IdkType.get(j).type == i + (gender === 0 ? 0 : 7)) { + state.activePlayer.body[i] = j; + break; + } + } + } + state.activePlayer.gender = gender; + }, + [ScriptOpcode_default.SETSKINCOLOUR]: state => { + const skin = check(state.popInt(), SkinColourValid); + state.activePlayer.colors[4] = skin; + }, + [ScriptOpcode_default.P_OPPLAYERT]: checkedHandler(ProtectedActivePlayer, state => { + const spellId = check(state.popInt(), NumberNotNull); + const target = state._activePlayer2; + if (!target) { + return; + } + state.activePlayer.stopAction(); + state.activePlayer.setInteraction(Interaction_default.SCRIPT, target, ServerTriggerType_default.APPLAYERT, {type: -1, com: spellId}); + }), + [ScriptOpcode_default.FINDHERO]: checkedHandler(ActivePlayer, state => { + const uid = state.activePlayer.findHero(); + if (uid === -1) { + state.pushInt(0); + return; + } + const player = World_default.getPlayerByUid(uid); + if (!player) { + state.pushInt(0); + return; + } + state._activePlayer2 = player; + state.pointerAdd(ScriptPointer_default.ActivePlayer2); + state.pushInt(1); + }), + [ScriptOpcode_default.BOTH_HEROPOINTS]: checkedHandler(ActivePlayer, state => { + const damage = check(state.popInt(), NumberNotNull); + const secondary = state.intOperand === 1; + const fromPlayer = secondary ? state._activePlayer2 : state._activePlayer; + const toPlayer = secondary ? state._activePlayer : state._activePlayer2; + if (!fromPlayer || !toPlayer) { + throw new Error('player is null'); + } + toPlayer.addHero(fromPlayer.uid, damage); + }), + [ScriptOpcode_default.P_ANIMPROTECT]: checkedHandler(ProtectedActivePlayer, state => { + state.activePlayer.animProtect = check(state.popInt(), NumberNotNull); + }), + [ScriptOpcode_default.RUNENERGY]: checkedHandler(ActivePlayer, state => { + const player = state.activePlayer; + state.pushInt(player.runenergy); + }), + [ScriptOpcode_default.WEIGHT]: checkedHandler(ProtectedActivePlayer, state => { + state.pushInt(state.activePlayer.runweight); + }), + [ScriptOpcode_default.LAST_COORD]: checkedHandler(ActivePlayer, state => { + state.pushInt(Position.packCoord(state.activePlayer.level, state.activePlayer.lastX, state.activePlayer.lastZ)); + }) +}; +var PlayerOps_default = PlayerOps; + +// src/lostcity/engine/script/handlers/ServerOps.ts +var ServerOps = { + [ScriptOpcode_default.MAP_CLOCK]: state => { + state.pushInt(World_default.currentTick); + }, + [ScriptOpcode_default.MAP_MEMBERS]: state => { + state.pushInt(Environment_default.NODE_MEMBERS ? 1 : 0); + }, + [ScriptOpcode_default.MAP_PLAYERCOUNT]: state => { + const [c1, c2] = state.popInts(2); + const from = check(c1, CoordValid); + const to = check(c2, CoordValid); + let count = 0; + for (let x = Math.floor(from.x / 8); x <= Math.ceil(to.x / 8); x++) { + for (let z2 = Math.floor(from.z / 8); z2 <= Math.ceil(to.z / 8); z2++) { + for (const player of World_default.getZone(x << 3, z2 << 3, from.level).getAllPlayersSafe()) { + if (player.x >= from.x && player.x <= to.x && player.z >= from.z && player.z <= to.z) { + count++; + } + } + } + } + state.pushInt(count); + }, + [ScriptOpcode_default.HUNTALL]: state => { + const [coord, distance, checkVis] = state.popInts(3); + const position = check(coord, CoordValid); + check(distance, NumberNotNull); + const huntvis = check(checkVis, HuntVisValid); + state.huntIterator = new HuntIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, -1, -1, HuntModeType_default.PLAYER); + }, + [ScriptOpcode_default.HUNTNEXT]: state => { + const result = state.huntIterator?.next(); + if (!result || result.done) { + state.pushInt(0); + return; + } + if (!(result.value instanceof Player2)) { + throw new Error('[ServerOps] huntnext command must result instance of Player.'); + } + state.activePlayer = result.value; + state.pointerAdd(ActivePlayer[state.intOperand]); + state.pushInt(1); + }, + [ScriptOpcode_default.NPC_HUNTALL]: state => { + const [coord, distance, checkVis] = state.popInts(3); + const position = check(coord, CoordValid); + check(distance, NumberNotNull); + const huntvis = check(checkVis, HuntVisValid); + state.huntIterator = new HuntIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, -1, -1, HuntModeType_default.NPC); + }, + [ScriptOpcode_default.NPC_HUNTNEXT]: state => { + const result = state.huntIterator?.next(); + if (!result || result.done) { + state.pushInt(0); + return; + } + if (!(result.value instanceof Npc2)) { + throw new Error('[ServerOps] npc_huntnext command must result instance of Npc.'); + } + state.activeNpc = result.value; + state.pointerAdd(ActiveNpc[state.intOperand]); + state.pushInt(1); + }, + [ScriptOpcode_default.INZONE]: state => { + const [c1, c2, c3] = state.popInts(3); + const from = check(c1, CoordValid); + const to = check(c2, CoordValid); + const pos = check(c3, CoordValid); + if (pos.x < from.x || pos.x > to.x) { + state.pushInt(0); + } else if (pos.level < from.level || pos.level > to.level) { + state.pushInt(0); + } else if (pos.z < from.z || pos.z > to.z) { + state.pushInt(0); + } else { + state.pushInt(1); + } + }, + [ScriptOpcode_default.LINEOFWALK]: state => { + const [c1, c2] = state.popInts(2); + const from = check(c1, CoordValid); + const to = check(c2, CoordValid); + if (from.level !== to.level) { + state.pushInt(0); + return; + } + state.pushInt(hasLineOfWalk(from.level, from.x, from.z, to.x, to.z, 1, 1, 1, 1) ? 1 : 0); + }, + [ScriptOpcode_default.STAT_RANDOM]: state => { + const [level, low, high] = state.popInts(3); + const value = Math.floor((low * (99 - level)) / 98) + Math.floor((high * (level - 1)) / 98) + 1; + const chance = Math.floor(Math.random() * 256); + state.pushInt(value > chance ? 1 : 0); + }, + [ScriptOpcode_default.SPOTANIM_MAP]: state => { + const [spotanim, coord, height, delay] = state.popInts(4); + const position = check(coord, CoordValid); + const spotanimType = check(spotanim, SpotAnimTypeValid); + World_default.animMap(position.level, position.x, position.z, spotanimType.id, height, delay); + }, + [ScriptOpcode_default.DISTANCE]: state => { + const [c1, c2] = state.popInts(2); + const from = check(c1, CoordValid); + const to = check(c2, CoordValid); + state.pushInt(Position.distanceToSW(from, to)); + }, + [ScriptOpcode_default.MOVECOORD]: state => { + const [coord, x, y3, z2] = state.popInts(4); + const position = check(coord, CoordValid); + state.pushInt(Position.packCoord(position.level + y3, position.x + x, position.z + z2)); + }, + [ScriptOpcode_default.SEQLENGTH]: state => { + state.pushInt(check(state.popInt(), SeqTypeValid).duration); + }, + [ScriptOpcode_default.SPLIT_INIT]: state => { + const [maxWidth, linesPerPage, fontId] = state.popInts(3); + let text = state.popString(); + const font = check(fontId, FontTypeValid); + if (text.startsWith('') !== -1) { + const mesanim = text.substring(3, text.indexOf('>')); + state.splitMesanim = MesanimType.getId(mesanim); + text = text.substring(text.indexOf('>') + 1); + } else { + state.splitMesanim = -1; + } + state.splitPages = []; + const lines = font.split(text, maxWidth); + while (lines.length > 0) { + state.splitPages.push(lines.splice(0, linesPerPage)); + } + }, + [ScriptOpcode_default.SPLIT_GET]: state => { + const [page, line] = state.popInts(2); + state.pushString(state.splitPages[page][line]); + }, + [ScriptOpcode_default.SPLIT_PAGECOUNT]: state => { + state.pushInt(state.splitPages.length); + }, + [ScriptOpcode_default.SPLIT_LINECOUNT]: state => { + const page = state.popInt(); + state.pushInt(state.splitPages[page].length); + }, + [ScriptOpcode_default.SPLIT_GETANIM]: state => { + const page = state.popInt(); + if (state.splitMesanim === -1) { + state.pushInt(-1); + return; + } + state.pushInt(check(state.splitMesanim, MesanimValid).len[state.splitPages[page].length - 1]); + }, + [ScriptOpcode_default.STRUCT_PARAM]: state => { + const [structId, paramId] = state.popInts(2); + const paramType = check(paramId, ParamTypeValid); + const structType = check(structId, StructTypeValid); + if (paramType.isString()) { + state.pushString(ParamHelper.getStringParam(paramType.id, structType, paramType.defaultString)); + } else { + state.pushInt(ParamHelper.getIntParam(paramType.id, structType, paramType.defaultInt)); + } + }, + [ScriptOpcode_default.COORDX]: state => { + state.pushInt(check(state.popInt(), CoordValid).x); + }, + [ScriptOpcode_default.COORDY]: state => { + state.pushInt(check(state.popInt(), CoordValid).level); + }, + [ScriptOpcode_default.COORDZ]: state => { + state.pushInt(check(state.popInt(), CoordValid).z); + }, + [ScriptOpcode_default.PLAYERCOUNT]: state => { + state.pushInt(World_default.getTotalPlayers()); + }, + [ScriptOpcode_default.MAP_BLOCKED]: state => { + const position = check(state.popInt(), CoordValid); + state.pushInt(isFlagged(position.x, position.z, position.level, CollisionFlag.WALK_BLOCKED) ? 1 : 0); + }, + [ScriptOpcode_default.MAP_INDOORS]: state => { + const position = check(state.popInt(), CoordValid); + state.pushInt(isFlagged(position.x, position.z, position.level, CollisionFlag.ROOF) ? 1 : 0); + }, + [ScriptOpcode_default.LINEOFSIGHT]: state => { + const [c1, c2] = state.popInts(2); + const from = check(c1, CoordValid); + const to = check(c2, CoordValid); + if (from.level !== to.level) { + state.pushInt(0); + return; + } + state.pushInt(hasLineOfSight(from.level, from.x, from.z, to.x, to.z, 1, 1, 1, 1) ? 1 : 0); + }, + [ScriptOpcode_default.WORLD_DELAY]: state => { + state.execution = ScriptState.WORLD_SUSPENDED; + }, + [ScriptOpcode_default.PROJANIM_PL]: state => { + const [srcCoord, uid, spotanim, srcHeight, dstHeight, delay, duration, peak, arc] = state.popInts(9); + const srcPos = check(srcCoord, CoordValid); + const spotanimType = check(spotanim, SpotAnimTypeValid); + const player = World_default.getPlayerByUid(uid); + if (!player) { + throw new Error(`attempted to use invalid player uid: ${uid}`); + } + World_default.mapProjAnim(srcPos.level, srcPos.x, srcPos.z, player.x, player.z, -player.pid - 1, spotanimType.id, srcHeight + 100, dstHeight + 100, delay, duration, peak, arc); + }, + [ScriptOpcode_default.PROJANIM_NPC]: state => { + const [srcCoord, npcUid, spotanim, srcHeight, dstHeight, delay, duration, peak, arc] = state.popInts(9); + const srcPos = check(srcCoord, CoordValid); + const spotanimType = check(spotanim, SpotAnimTypeValid); + const slot = npcUid & 65535; + const expectedType = (npcUid >> 16) & 65535; + const npc = World_default.getNpc(slot); + if (!npc) { + throw new Error(`attempted to use invalid npc uid: ${npcUid}`); + } + World_default.mapProjAnim(srcPos.level, srcPos.x, srcPos.z, npc.x, npc.z, npc.nid + 1, spotanimType.id, srcHeight + 100, dstHeight + 100, delay, duration, peak, arc); + }, + [ScriptOpcode_default.PROJANIM_MAP]: state => { + const [srcCoord, dstCoord, spotanim, srcHeight, dstHeight, delay, duration, peak, arc] = state.popInts(9); + const spotanimType = check(spotanim, SpotAnimTypeValid); + const srcPos = check(srcCoord, CoordValid); + const dstPos = check(dstCoord, CoordValid); + World_default.mapProjAnim(srcPos.level, srcPos.x, srcPos.z, dstPos.x, dstPos.z, 0, spotanimType.id, srcHeight + 100, dstHeight, delay, duration, peak, arc); + }, + [ScriptOpcode_default.MAP_LOCADDUNSAFE]: state => { + const pos = check(state.popInt(), CoordValid); + for (const loc of World_default.getZone(pos.x, pos.z, pos.level).getAllLocsUnsafe()) { + const type = check(loc.type, LocTypeValid); + if (type.active !== 1) { + continue; + } + const layer = locShapeLayer(loc.shape); + if (!loc.checkLifeCycle(World_default.currentTick) && layer === LocLayer.WALL) { + continue; + } + if (layer === LocLayer.WALL) { + if (loc.x === pos.x && loc.z === pos.z) { + state.pushInt(1); + return; + } + } else if (layer === LocLayer.GROUND) { + const width = loc.angle === LocAngle.NORTH || loc.angle === LocAngle.SOUTH ? loc.length : loc.width; + const length = loc.angle === LocAngle.NORTH || loc.angle === LocAngle.SOUTH ? loc.width : loc.length; + for (let index = 0; index < width * length; index++) { + const deltaX = loc.x + (index % width); + const deltaZ = loc.z + ((index / width) | 0); + if (deltaX === pos.x && deltaZ === pos.z) { + state.pushInt(1); + return; + } + } + } else if (layer === LocLayer.GROUND_DECOR) { + if (loc.x === pos.x && loc.z === pos.z) { + state.pushInt(1); + return; + } + } + } + state.pushInt(0); + }, + [ScriptOpcode_default.NPCCOUNT]: state => { + state.pushInt(World_default.getTotalNpcs()); + }, + [ScriptOpcode_default.ZONECOUNT]: state => { + state.pushInt(World_default.getTotalZones()); + }, + [ScriptOpcode_default.LOCCOUNT]: state => { + state.pushInt(World_default.getTotalLocs()); + }, + [ScriptOpcode_default.OBJCOUNT]: state => { + state.pushInt(World_default.getTotalObjs()); + } +}; +var ServerOps_default = ServerOps; + +// src/lostcity/engine/script/handlers/StringOps.ts +var javaStringCompare = function (a, b3) { + const len1 = a.length; + const len2 = b3.length; + const lim = Math.min(len1, len2); + let k = 0; + while (k < lim) { + const c1 = a.charCodeAt(k); + const c2 = b3.charCodeAt(k); + if (c1 != c2) { + return c1 - c2; + } + k++; + } + return len1 - len2; +}; +var StringOps = { + [ScriptOpcode_default.APPEND_NUM]: state => { + const text = state.popString(); + const num = state.popInt(); + state.pushString(text + num); + }, + [ScriptOpcode_default.APPEND]: state => { + const [t1, t22] = state.popStrings(2); + state.pushString(t1 + t22); + }, + [ScriptOpcode_default.APPEND_SIGNNUM]: state => { + const text = state.popString(); + const num = state.popInt(); + if (num >= 0) { + state.pushString(`${text}+${num}`); + } else { + state.pushString(text + num); + } + }, + [ScriptOpcode_default.LOWERCASE]: state => { + state.pushString(state.popString().toLowerCase()); + }, + [ScriptOpcode_default.TOSTRING]: state => { + state.pushString(state.popInt().toString()); + }, + [ScriptOpcode_default.COMPARE]: state => { + const [s1, s22] = state.popStrings(2); + state.pushInt(javaStringCompare(s1, s22)); + }, + [ScriptOpcode_default.TEXT_SWITCH]: state => { + const value = state.popInt(); + const [s1, s22] = state.popStrings(2); + state.pushString(value === 1 ? s1 : s22); + }, + [ScriptOpcode_default.APPEND_CHAR]: state => { + const text = state.popString(); + const char = state.popInt(); + state.pushString(text + String.fromCharCode(char)); + }, + [ScriptOpcode_default.STRING_LENGTH]: state => { + state.pushInt(state.popString().length); + }, + [ScriptOpcode_default.SUBSTRING]: state => { + const text = state.popString(); + const [start, end] = state.popInts(2); + state.pushString(text.substring(start, end)); + }, + [ScriptOpcode_default.STRING_INDEXOF_CHAR]: state => { + const text = state.popString(); + const find = String.fromCharCode(state.popInt()); + state.pushInt(text.indexOf(find)); + }, + [ScriptOpcode_default.STRING_INDEXOF_STRING]: state => { + const text = state.popString(); + const find = state.popString(); + state.pushInt(text.indexOf(find)); + } +}; +var StringOps_default = StringOps; + +// src/lostcity/engine/script/ScriptRunner.ts +class ScriptRunner2 { + static HANDLERS = { + ...CoreOps_default, + ...ServerOps_default, + ...PlayerOps_default, + ...NpcOps_default, + ...LocOps_default, + ...ObjOps_default, + ...NpcConfigOps_default, + ...LocConfigOps_default, + ...ObjConfigOps_default, + ...InvOps_default, + ...EnumOps_default, + ...StringOps_default, + ...NumberOps_default, + ...DbOps_default, + ...DebugOps_default + }; + static init(script, self2 = null, target = null, args = []) { + const state = new ScriptState(script, args); + state.self = self2; + if (self2 instanceof Player2) { + state._activePlayer = self2; + state.pointerAdd(ScriptPointer_default.ActivePlayer); + } else if (self2 instanceof Npc2) { + state._activeNpc = self2; + state.pointerAdd(ScriptPointer_default.ActiveNpc); + } else if (self2 instanceof Loc) { + state._activeLoc = self2; + state.pointerAdd(ScriptPointer_default.ActiveLoc); + } else if (self2 instanceof Obj) { + state._activeObj = self2; + state.pointerAdd(ScriptPointer_default.ActiveObj); + } + if (target instanceof Player2) { + if (self2 instanceof Player2) { + state._activePlayer2 = target; + state.pointerAdd(ScriptPointer_default.ActivePlayer2); + } else { + state._activePlayer = target; + state.pointerAdd(ScriptPointer_default.ActivePlayer); + } + } else if (target instanceof Npc2) { + if (self2 instanceof Npc2) { + state._activeNpc2 = target; + state.pointerAdd(ScriptPointer_default.ActiveNpc2); + } else { + state._activeNpc = target; + state.pointerAdd(ScriptPointer_default.ActiveNpc); + } + } else if (target instanceof Loc) { + if (self2 instanceof Loc) { + state._activeLoc2 = target; + state.pointerAdd(ScriptPointer_default.ActiveLoc2); + } else { + state._activeLoc = target; + state.pointerAdd(ScriptPointer_default.ActiveLoc); + } + } else if (target instanceof Obj) { + if (self2 instanceof Obj) { + state._activeObj2 = target; + state.pointerAdd(ScriptPointer_default.ActiveObj2); + } else { + state._activeObj = target; + state.pointerAdd(ScriptPointer_default.ActiveObj); + } + } + return state; + } + static execute(state, reset = false, benchmark = false) { + if (!state || !state.script || !state.script.info) { + return ScriptState.ABORTED; + } + try { + if (reset) { + state.reset(); + } + if (state.execution !== ScriptState.RUNNING) { + state.executionHistory.push(state.execution); + } + state.execution = ScriptState.RUNNING; + const start = performance.now() * 1000; + while (state.execution === ScriptState.RUNNING) { + if (state.pc >= state.script.opcodes.length || state.pc < -1) { + throw new Error('Invalid program counter: ' + state.pc + ', max expected: ' + state.script.opcodes.length); + } + if (!benchmark && state.opcount > 500000) { + throw new Error('Too many instructions'); + } + state.opcount++; + ScriptRunner2.executeInner(state, state.script.opcodes[++state.pc]); + } + const time = (performance.now() * 1000 - start) | 0; + if (Environment_default.NODE_DEBUG_PROFILE && time > 1000) { + const message = `Warning [cpu time]: Script: ${state.script.info.scriptName}, time: ${time}us`; + if (state.self instanceof Player2) { + state.self.wrappedMessageGame(message); + } else { + console.warn(message); + } + } + } catch (err) { + if (state.pc >= 0 && state.pc < state.script.opcodes.length) { + const opcode = state.script.opcodes[state.pc]; + let secondary = state.intOperand; + if (opcode === ScriptOpcode_default.POP_VARP || opcode === ScriptOpcode_default.POP_VARN || opcode === ScriptOpcode_default.PUSH_VARP || opcode === ScriptOpcode_default.PUSH_VARN) { + secondary = (state.intOperand >> 16) & 1; + } else if (opcode <= ScriptOpcode_default.POP_ARRAY_INT) { + secondary = 0; + } + err.message = ScriptOpcode_default[opcode].toLowerCase() + ' ' + err.message; + if (secondary) { + err.message = '.' + err.message; + } + } + if (state.self instanceof Player2) { + state.self.wrappedMessageGame(`script error: ${err.message}`); + state.self.wrappedMessageGame(`file: ${q.basename(state.script.info.sourceFilePath)}`); + state.self.wrappedMessageGame(''); + state.self.wrappedMessageGame('stack backtrace:'); + state.self.wrappedMessageGame(` 1: ${state.script.name} - ${state.script.fileName}:${state.script.lineNumber(state.pc)}`); + let trace2 = 1; + for (let i = state.fp; i > 0; i--) { + const frame = state.frames[i]; + if (frame) { + trace2++; + state.self.wrappedMessageGame(` ${trace2}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); + } + } + for (let i = state.debugFp; i >= 0; i--) { + const frame = state.debugFrames[i]; + if (frame) { + trace2++; + state.self.wrappedMessageGame(` ${trace2}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); + } + } + } + console.error(`script error: ${err.message}`); + console.error(`file: ${q.basename(state.script.info.sourceFilePath)}`); + console.error(''); + console.error('stack backtrace:'); + console.error(` 1: ${state.script.name} - ${state.script.fileName}:${state.script.lineNumber(state.pc)}`); + let trace = 1; + for (let i = state.fp; i > 0; i--) { + const frame = state.frames[i]; + if (frame) { + trace++; + console.error(` ${trace}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); + } + } + for (let i = state.debugFp; i >= 0; i--) { + const frame = state.debugFrames[i]; + if (frame) { + trace++; + console.error(` ${trace}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); + } + } + state.execution = ScriptState.ABORTED; + } + return state.execution; + } + static executeInner(state, opcode) { + const handler = ScriptRunner2.HANDLERS[opcode]; + if (!handler) { + throw new Error(`Unknown opcode ${opcode}`); + } + handler(state); + } +} + +// src/lostcity/entity/Npc.ts +class Npc2 extends PathingEntity { + static ANIM = 2; + static FACE_ENTITY = 4; + static SAY = 8; + static DAMAGE = 16; + static CHANGE_TYPE = 32; + static SPOTANIM = 64; + static FACE_COORD = 128; + nid; + type; + uid; + origType; + startX; + startZ; + levels = new Uint8Array(6); + baseLevels = new Uint8Array(6); + vars; + varsString; + activeScript = null; + delay = 0; + queue = new LinkList(); + timerInterval = 0; + timerClock = 0; + huntMode = -1; + nextHuntTick = -1; + huntrange = 5; + nextPatrolTick = -1; + nextPatrolPoint = 0; + delayedPatrol = false; + heroPoints = new Array(16); + constructor(level, x, z2, width, length, lifecycle, nid, type, moveRestrict, blockWalk) { + super(level, x, z2, width, length, lifecycle, moveRestrict, blockWalk, MoveStrategy_default.NAIVE, Npc2.FACE_COORD, Npc2.FACE_ENTITY); + this.nid = nid; + this.type = type; + this.uid = (type << 16) | nid; + this.startX = this.x; + this.startZ = this.z; + this.origType = type; + const npcType = NpcType.get(type); + for (let index = 0; index < npcType.stats.length; index++) { + const level2 = npcType.stats[index]; + this.levels[index] = level2; + this.baseLevels[index] = level2; + } + if (npcType.timer !== -1) { + this.setTimer(npcType.timer); + } + this.vars = new Int32Array(VarNpcType.count); + this.varsString = new Array(VarNpcType.count); + this.targetOp = npcType.defaultmode; + this.huntMode = npcType.huntmode; + this.huntrange = npcType.huntrange; + } + resetHeroPoints() { + this.heroPoints = new Array(16); + this.heroPoints.fill({uid: -1, points: 0}); + } + addHero(uid, points) { + const index = this.heroPoints.findIndex(hero => hero && hero.uid === uid); + if (index !== -1) { + this.heroPoints[index].points += points; + return; + } + const emptyIndex = this.heroPoints.findIndex(hero => hero && hero.uid === -1); + if (emptyIndex !== -1) { + this.heroPoints[emptyIndex] = {uid, points}; + return; + } + } + findHero() { + this.heroPoints.sort((a, b3) => { + return b3.points - a.points; + }); + return this.heroPoints[0]?.uid ?? -1; + } + getVar(id) { + const varn = VarNpcType.get(id); + return varn.type === ScriptVarType.STRING ? this.varsString[varn.id] : this.vars[varn.id]; + } + setVar(id, value) { + const varn = VarNpcType.get(id); + if (varn.type === ScriptVarType.STRING && typeof value === 'string') { + this.varsString[varn.id] = value; + } else if (typeof value === 'number') { + this.vars[varn.id] = value; + } + } + resetEntity(respawn) { + if (respawn) { + this.type = this.origType; + this.uid = (this.type << 16) | this.nid; + this.orientation = Direction.SOUTH; + for (let index = 0; index < this.baseLevels.length; index++) { + this.levels[index] = this.baseLevels[index]; + } + this.resetHeroPoints(); + this.defaultMode(); + const npcType = NpcType.get(this.type); + this.huntrange = npcType.huntrange; + } + super.resetPathingEntity(); + } + updateMovement(repathAllowed = true) { + const type = NpcType.get(this.type); + if (type.moverestrict === MoveRestrict_default.NOMOVE) { + return false; + } + if (this.target && this.targetOp !== NpcMode_default.PLAYERFOLLOW && this.targetOp !== NpcMode_default.WANDER) { + if (this.targetOp === NpcMode_default.PLAYERESCAPE) { + const distanceToEscape = Position.distanceTo(this, { + x: this.startX, + z: this.startZ, + width: this.width, + length: this.length + }); + const targetDistanceFromStart = Position.distanceTo(this.target, { + x: this.startX, + z: this.startZ, + width: this.target.width, + length: this.target.length + }); + if (targetDistanceFromStart > type.maxrange && distanceToEscape > type.maxrange) { + return false; + } + } + let attackRange = 0; + if (this.targetOp === NpcMode_default.OPPLAYER2) { + attackRange = 1; + } else if (this.targetOp === NpcMode_default.APPLAYER2) { + attackRange = type.attackrange; + } + if (Position.distanceToSW(this.target, {x: this.startX, z: this.startZ}) > type.maxrange + attackRange) { + this.defaultMode(); + return false; + } + } + if (repathAllowed && this.target instanceof PathingEntity && !this.interacted && this.walktrigger === -1) { + this.pathToPathingTarget(); + } + if (this.walktrigger !== -1) { + const type2 = NpcType.get(this.type); + const script = ScriptProvider.getByTrigger(ServerTriggerType_default.AI_QUEUE1 + this.walktrigger, type2.id, type2.category); + this.walktrigger = -1; + if (script) { + const state = ScriptRunner2.init(script, this, null, [this.walktriggerArg]); + ScriptRunner2.execute(state); + } + } + if (this.moveSpeed !== MoveSpeed_default.INSTANT) { + this.moveSpeed = this.defaultMoveSpeed(); + } + return super.processMovement(); + } + blockWalkFlag() { + if (this.moveRestrict === MoveRestrict_default.NORMAL) { + return CollisionFlag.NPC; + } else if (this.moveRestrict === MoveRestrict_default.BLOCKED) { + return CollisionFlag.OPEN; + } else if (this.moveRestrict === MoveRestrict_default.BLOCKED_NORMAL) { + return CollisionFlag.NPC; + } else if (this.moveRestrict === MoveRestrict_default.INDOORS) { + return CollisionFlag.NPC; + } else if (this.moveRestrict === MoveRestrict_default.OUTDOORS) { + return CollisionFlag.NPC; + } else if (this.moveRestrict === MoveRestrict_default.NOMOVE) { + return CollisionFlag.NULL; + } else if (this.moveRestrict === MoveRestrict_default.PASSTHRU) { + return CollisionFlag.OPEN; + } + return CollisionFlag.NULL; + } + defaultMoveSpeed() { + return MoveSpeed_default.WALK; + } + delayed() { + return this.delay > 0; + } + setTimer(interval) { + this.timerInterval = interval; + this.timerClock = 0; + } + executeScript(script) { + if (!script) { + return; + } + const state = ScriptRunner2.execute(script); + if (state !== ScriptState.FINISHED && state !== ScriptState.ABORTED) { + if (state === ScriptState.WORLD_SUSPENDED) { + World_default.enqueueScript(script, script.popInt()); + } else if (state === ScriptState.NPC_SUSPENDED) { + script.activeNpc.activeScript = script; + } else { + script.activePlayer.activeScript = script; + } + } else if (script === this.activeScript) { + this.activeScript = null; + } + if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer) && script._activePlayer) { + script._activePlayer.protect = false; + script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer); + } + if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer2) && script._activePlayer2) { + script._activePlayer2.protect = false; + script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer2); + } + } + processTimers() { + if (this.timerInterval !== 0 && ++this.timerClock >= this.timerInterval) { + this.timerClock = 0; + const type = NpcType.get(this.type); + const script = ScriptProvider.getByTrigger(ServerTriggerType_default.AI_TIMER, type.id, type.category); + if (script) { + this.executeScript(ScriptRunner2.init(script, this)); + } + } + } + processQueue() { + for (let request = this.queue.head(); request !== null; request = this.queue.next()) { + if (!this.delayed()) { + request.delay--; + } + if (!this.delayed() && request.delay <= 0) { + const state = ScriptRunner2.init(request.script, this, null, request.args); + state.lastInt = request.lastInt; + this.executeScript(state); + request.unlink(); + } + } + } + enqueueScript(script, delay = 0, arg = 0) { + const request = new EntityQueueRequest(0 /* NORMAL */, script, [], delay); + request.lastInt = arg; + this.queue.addTail(request); + } + randomWalk(range) { + const dx = Math.round(Math.random() * (range * 2) - range); + const dz = Math.round(Math.random() * (range * 2) - range); + const destX = this.startX + dx; + const destZ = this.startZ + dz; + if (destX !== this.x || destZ !== this.z) { + this.queueWaypoint(destX, destZ); + } + } + processNpcModes() { + if (this.targetOp === NpcMode_default.NULL) { + this.defaultMode(); + } else if (this.targetOp === NpcMode_default.NONE) { + this.noMode(); + } else if (this.targetOp === NpcMode_default.WANDER) { + this.wanderMode(); + } else if (this.targetOp === NpcMode_default.PATROL) { + this.patrolMode(); + } else if (this.targetOp === NpcMode_default.PLAYERESCAPE) { + this.playerEscapeMode(); + } else if (this.targetOp === NpcMode_default.PLAYERFOLLOW) { + this.playerFollowMode(); + } else if (this.targetOp === NpcMode_default.PLAYERFACE) { + this.playerFaceMode(); + } else if (this.targetOp === NpcMode_default.PLAYERFACECLOSE) { + this.playerFaceCloseMode(); + } else { + this.aiMode(); + } + } + noMode() { + this.clearInteraction(); + this.updateMovement(false); + this.targetOp = NpcMode_default.NONE; + this.faceEntity = -1; + this.mask |= Npc2.FACE_ENTITY; + } + defaultMode() { + this.clearInteraction(); + this.updateMovement(false); + const type = NpcType.get(this.type); + this.targetOp = type.defaultmode; + this.faceEntity = -1; + this.mask |= Npc2.FACE_ENTITY; + } + wanderMode() { + const type = NpcType.get(this.type); + if (type.moverestrict !== MoveRestrict_default.NOMOVE && Math.random() < 0.125) { + this.randomWalk(type.wanderrange); + } + this.updateMovement(false); + } + patrolMode() { + const type = NpcType.get(this.type); + const patrolPoints = type.patrolCoord; + const patrolDelay = type.patrolDelay[this.nextPatrolPoint]; + let dest = Position.unpackCoord(patrolPoints[this.nextPatrolPoint]); + this.updateMovement(false); + if (!this.hasWaypoints() && !this.target) { + this.queueWaypoint(dest.x, dest.z); + } + if (!(this.x === dest.x && this.z === dest.z) && World_default.currentTick >= this.nextPatrolTick) { + this.teleport(dest.x, dest.z, dest.level); + } + if (this.x === dest.x && this.z === dest.z && !this.delayedPatrol) { + this.nextPatrolTick = World_default.currentTick + patrolDelay; + this.delayedPatrol = true; + } + if (this.nextPatrolTick > World_default.currentTick) { + return; + } + this.nextPatrolPoint = (this.nextPatrolPoint + 1) % patrolPoints.length; + this.nextPatrolTick = World_default.currentTick + 30; + this.delayedPatrol = false; + dest = Position.unpackCoord(patrolPoints[this.nextPatrolPoint]); + this.queueWaypoint(dest.x, dest.z); + } + playerEscapeMode() { + if (!this.target) { + this.defaultMode(); + return; + } + if (!(this.target instanceof Player2)) { + throw new Error('[Npc] Target must be a Player for playerescape mode.'); + } + if (World_default.getPlayerByUid(this.target.uid) === null) { + this.defaultMode(); + return; + } + if (Position.distanceToSW(this, this.target) > 25) { + this.defaultMode(); + return; + } + let direction; + let flags; + if (this.target.x >= this.x && this.target.z >= this.z) { + direction = Direction.SOUTH_WEST; + flags = CollisionFlag.WALL_SOUTH | CollisionFlag.WALL_WEST; + } else if (this.target.x >= this.x && this.target.z < this.z) { + direction = Direction.NORTH_WEST; + flags = CollisionFlag.WALL_NORTH | CollisionFlag.WALL_WEST; + } else if (this.target.x < this.x && this.target.z >= this.z) { + direction = Direction.SOUTH_EAST; + flags = CollisionFlag.WALL_SOUTH | CollisionFlag.WALL_EAST; + } else { + direction = Direction.NORTH_EAST; + flags = CollisionFlag.WALL_NORTH | CollisionFlag.WALL_EAST; + } + const mx = Position.moveX(this.x, direction); + const mz = Position.moveZ(this.z, direction); + if (isFlagged(mx, mz, this.level, flags)) { + this.defaultMode(); + return; + } + const position = {x: mx, z: mz, level: this.level}; + if ( + Position.distanceToSW(position, { + x: this.startX, + z: this.startZ + }) < NpcType.get(this.type).maxrange + ) { + this.queueWaypoint(position.x, position.z); + this.updateMovement(false); + return; + } + if (direction === Direction.NORTH_EAST || direction === Direction.NORTH_WEST) { + this.queueWaypoint(this.x, position.z); + } else { + this.queueWaypoint(position.x, this.z); + } + this.updateMovement(false); + } + playerFollowMode() { + if (!this.target) { + this.defaultMode(); + return; + } + if (!(this.target instanceof Player2)) { + throw new Error('[Npc] Target must be a Player for playerfollow mode.'); + } + if (World_default.getPlayerByUid(this.target.uid) === null) { + this.defaultMode(); + return; + } + if (this.level !== this.target.level) { + this.defaultMode(); + return; + } + this.pathToTarget(); + this.updateMovement(); + } + playerFaceMode() { + if (!this.target) { + this.defaultMode(); + return; + } + if (!(this.target instanceof Player2)) { + throw new Error('[Npc] Target must be a Player for playerface mode.'); + } + if (World_default.getPlayerByUid(this.target.uid) === null) { + this.defaultMode(); + return; + } + if (this.level !== this.target.level) { + this.defaultMode(); + return; + } + const type = NpcType.get(this.type); + if (Position.distanceTo(this, this.target) > type.maxrange) { + this.defaultMode(); + return; + } + this.updateMovement(false); + } + playerFaceCloseMode() { + if (!this.target) { + this.defaultMode(); + return; + } + if (!(this.target instanceof Player2)) { + throw new Error('[Npc] Target must be a Player for playerfaceclose mode.'); + } + if (World_default.getPlayerByUid(this.target.uid) == null) { + this.defaultMode(); + return; + } + if (this.level !== this.target.level) { + this.defaultMode(); + return; + } + if (Position.distanceTo(this, this.target) > 1) { + this.defaultMode(); + return; + } + this.updateMovement(false); + } + aiMode() { + if (this.delayed() || !this.target) { + this.defaultMode(); + return; + } + if (this.target.level !== this.level) { + this.defaultMode(); + return; + } + if (this.target instanceof Npc2 && (typeof World_default.getNpc(this.target.nid) === 'undefined' || this.target.delayed())) { + this.defaultMode(); + return; + } + if (this.target instanceof Npc2 && this.targetSubject.type !== -1 && World_default.getNpcByUid((this.targetSubject.type << 16) | this.target.nid) === null) { + this.defaultMode(); + return; + } + if (this.target instanceof Obj && World_default.getObj(this.target.x, this.target.z, this.level, this.target.type, -1) === null) { + this.defaultMode(); + return; + } + if (this.target instanceof Loc && World_default.getLoc(this.target.x, this.target.z, this.level, this.target.type) === null) { + this.defaultMode(); + return; + } + if (this.target instanceof Player2 && World_default.getPlayerByUid(this.target.uid) === null) { + this.defaultMode(); + return; + } + const type = NpcType.get(this.type); + const apTrigger = + (this.targetOp >= NpcMode_default.APNPC1 && this.targetOp <= NpcMode_default.APNPC5) || + (this.targetOp >= NpcMode_default.APPLAYER1 && this.targetOp <= NpcMode_default.APPLAYER5) || + (this.targetOp >= NpcMode_default.APLOC1 && this.targetOp <= NpcMode_default.APLOC5) || + (this.targetOp >= NpcMode_default.APOBJ1 && this.targetOp <= NpcMode_default.APOBJ5); + const opTrigger = !apTrigger; + const script = this.getTrigger(); + if (script && opTrigger && this.inOperableDistance(this.target) && this.target instanceof PathingEntity) { + this.executeScript(ScriptRunner2.init(script, this, this.target)); + this.interacted = true; + this.clearWaypoints(); + } else if (script && apTrigger && this.inApproachDistance(type.attackrange, this.target)) { + this.executeScript(ScriptRunner2.init(script, this, this.target)); + this.interacted = true; + this.clearWaypoints(); + } else if (this.inOperableDistance(this.target) && this.target instanceof PathingEntity) { + this.target = null; + this.interacted = true; + this.clearWaypoints(); + } + const moved = this.updateMovement(); + if (moved) { + this.alreadyFacedEntity = false; + this.alreadyFacedCoord = false; + } + if (this.target && !this.interacted) { + this.interacted = false; + if (script && opTrigger && this.inOperableDistance(this.target) && (this.target instanceof PathingEntity || !moved)) { + this.executeScript(ScriptRunner2.init(script, this, this.target)); + this.interacted = true; + this.clearWaypoints(); + } else if (script && apTrigger && this.inApproachDistance(type.attackrange, this.target)) { + this.executeScript(ScriptRunner2.init(script, this, this.target)); + this.interacted = true; + this.clearWaypoints(); + } else if (this.inOperableDistance(this.target) && (this.target instanceof PathingEntity || !moved)) { + this.target = null; + this.interacted = true; + this.clearWaypoints(); + } + } + } + getTrigger() { + const trigger = this.getTriggerForMode(this.targetOp); + if (trigger) { + return ScriptProvider.getByTrigger(trigger, this.type, -1) ?? null; + } + return null; + } + getTriggerForMode(mode) { + if (mode === NpcMode_default.OPPLAYER1) { + return ServerTriggerType_default.AI_OPPLAYER1; + } else if (mode === NpcMode_default.OPPLAYER2) { + return ServerTriggerType_default.AI_OPPLAYER2; + } else if (mode === NpcMode_default.OPPLAYER3) { + return ServerTriggerType_default.AI_OPPLAYER3; + } else if (mode === NpcMode_default.OPPLAYER4) { + return ServerTriggerType_default.AI_OPPLAYER4; + } else if (mode === NpcMode_default.OPPLAYER5) { + return ServerTriggerType_default.AI_OPPLAYER5; + } else if (mode === NpcMode_default.APPLAYER1) { + return ServerTriggerType_default.AI_APPLAYER1; + } else if (mode === NpcMode_default.APPLAYER2) { + return ServerTriggerType_default.AI_APPLAYER2; + } else if (mode === NpcMode_default.APPLAYER3) { + return ServerTriggerType_default.AI_APPLAYER3; + } else if (mode === NpcMode_default.APPLAYER4) { + return ServerTriggerType_default.AI_APPLAYER4; + } else if (mode === NpcMode_default.APPLAYER5) { + return ServerTriggerType_default.AI_APPLAYER5; + } else if (mode === NpcMode_default.OPLOC1) { + return ServerTriggerType_default.AI_OPLOC1; + } else if (mode === NpcMode_default.OPLOC2) { + return ServerTriggerType_default.AI_OPLOC2; + } else if (mode === NpcMode_default.OPLOC3) { + return ServerTriggerType_default.AI_OPLOC3; + } else if (mode === NpcMode_default.OPLOC4) { + return ServerTriggerType_default.AI_OPLOC4; + } else if (mode === NpcMode_default.OPLOC5) { + return ServerTriggerType_default.AI_OPLOC5; + } else if (mode === NpcMode_default.APLOC1) { + return ServerTriggerType_default.AI_APLOC1; + } else if (mode === NpcMode_default.APLOC2) { + return ServerTriggerType_default.AI_APLOC2; + } else if (mode === NpcMode_default.APLOC3) { + return ServerTriggerType_default.AI_APLOC3; + } else if (mode === NpcMode_default.APLOC4) { + return ServerTriggerType_default.AI_APLOC4; + } else if (mode === NpcMode_default.APLOC5) { + return ServerTriggerType_default.AI_APLOC5; + } else if (mode === NpcMode_default.OPOBJ1) { + return ServerTriggerType_default.AI_OPOBJ1; + } else if (mode === NpcMode_default.OPOBJ2) { + return ServerTriggerType_default.AI_OPOBJ2; + } else if (mode === NpcMode_default.OPOBJ3) { + return ServerTriggerType_default.AI_OPOBJ3; + } else if (mode === NpcMode_default.OPOBJ4) { + return ServerTriggerType_default.AI_OPOBJ4; + } else if (mode === NpcMode_default.OPOBJ5) { + return ServerTriggerType_default.AI_OPOBJ5; + } else if (mode === NpcMode_default.APOBJ1) { + return ServerTriggerType_default.AI_APOBJ1; + } else if (mode === NpcMode_default.APOBJ2) { + return ServerTriggerType_default.AI_APOBJ2; + } else if (mode === NpcMode_default.APOBJ3) { + return ServerTriggerType_default.AI_APOBJ3; + } else if (mode === NpcMode_default.APOBJ4) { + return ServerTriggerType_default.AI_APOBJ4; + } else if (mode === NpcMode_default.APOBJ5) { + return ServerTriggerType_default.AI_APOBJ5; + } else if (mode === NpcMode_default.OPNPC1) { + return ServerTriggerType_default.AI_OPNPC1; + } else if (mode === NpcMode_default.OPNPC2) { + return ServerTriggerType_default.AI_OPNPC2; + } else if (mode === NpcMode_default.OPNPC3) { + return ServerTriggerType_default.AI_OPNPC3; + } else if (mode === NpcMode_default.OPNPC4) { + return ServerTriggerType_default.AI_OPNPC4; + } else if (mode === NpcMode_default.OPNPC5) { + return ServerTriggerType_default.AI_OPNPC5; + } else if (mode === NpcMode_default.APNPC1) { + return ServerTriggerType_default.AI_APNPC1; + } else if (mode === NpcMode_default.APNPC2) { + return ServerTriggerType_default.AI_APNPC2; + } else if (mode === NpcMode_default.APNPC3) { + return ServerTriggerType_default.AI_APNPC3; + } else if (mode === NpcMode_default.APNPC4) { + return ServerTriggerType_default.AI_APNPC4; + } else if (mode === NpcMode_default.APNPC5) { + return ServerTriggerType_default.AI_APNPC5; + } else if (mode === NpcMode_default.QUEUE1) { + return ServerTriggerType_default.AI_QUEUE1; + } else if (mode === NpcMode_default.QUEUE2) { + return ServerTriggerType_default.AI_QUEUE2; + } else if (mode === NpcMode_default.QUEUE3) { + return ServerTriggerType_default.AI_QUEUE3; + } else if (mode === NpcMode_default.QUEUE4) { + return ServerTriggerType_default.AI_QUEUE4; + } else if (mode === NpcMode_default.QUEUE5) { + return ServerTriggerType_default.AI_QUEUE5; + } else if (mode === NpcMode_default.QUEUE6) { + return ServerTriggerType_default.AI_QUEUE6; + } else if (mode === NpcMode_default.QUEUE7) { + return ServerTriggerType_default.AI_QUEUE7; + } else if (mode === NpcMode_default.QUEUE8) { + return ServerTriggerType_default.AI_QUEUE8; + } else if (mode === NpcMode_default.QUEUE9) { + return ServerTriggerType_default.AI_QUEUE9; + } else if (mode === NpcMode_default.QUEUE10) { + return ServerTriggerType_default.AI_QUEUE10; + } else if (mode === NpcMode_default.QUEUE11) { + return ServerTriggerType_default.AI_QUEUE11; + } else if (mode === NpcMode_default.QUEUE12) { + return ServerTriggerType_default.AI_QUEUE12; + } else if (mode === NpcMode_default.QUEUE13) { + return ServerTriggerType_default.AI_QUEUE13; + } else if (mode === NpcMode_default.QUEUE14) { + return ServerTriggerType_default.AI_QUEUE14; + } else if (mode === NpcMode_default.QUEUE15) { + return ServerTriggerType_default.AI_QUEUE15; + } else if (mode === NpcMode_default.QUEUE16) { + return ServerTriggerType_default.AI_QUEUE16; + } else if (mode === NpcMode_default.QUEUE17) { + return ServerTriggerType_default.AI_QUEUE17; + } else if (mode === NpcMode_default.QUEUE18) { + return ServerTriggerType_default.AI_QUEUE18; + } else if (mode === NpcMode_default.QUEUE19) { + return ServerTriggerType_default.AI_QUEUE19; + } else if (mode === NpcMode_default.QUEUE20) { + return ServerTriggerType_default.AI_QUEUE20; + } + return null; + } + huntAll() { + if (this.nextHuntTick > World_default.currentTick) { + return; + } + const hunt = HuntType.get(this.huntMode); + if (hunt.type === HuntModeType_default.OFF) { + return; + } + if (hunt.nobodyNear === HuntNobodyNear_default.PAUSEHUNT && !World_default.getZoneGrid(this.level).isFlagged(Position.zone(this.x), Position.zone(this.z), 5)) { + return; + } + if (!hunt.findKeepHunting && this.target !== null) { + return; + } + let hunted; + if (hunt.type === HuntModeType_default.PLAYER) { + hunted = this.huntPlayers(hunt); + } else if (hunt.type === HuntModeType_default.NPC) { + hunted = this.huntNpcs(hunt); + } else if (hunt.type === HuntModeType_default.OBJ) { + hunted = this.huntObjs(hunt); + } else { + hunted = this.huntLocs(hunt); + } + if (hunted.length > 0) { + const entity = hunted[Math.floor(Math.random() * hunted.length)]; + this.setInteraction(Interaction_default.SCRIPT, entity, hunt.findNewMode); + } + this.nextHuntTick = World_default.currentTick + hunt.rate; + } + huntPlayers(hunt) { + const type = NpcType.get(this.type); + const players = []; + const hunted = new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, -1, -1, HuntModeType_default.PLAYER); + for (const player of hunted) { + if (!(player instanceof Player2)) { + throw new Error('[Npc] huntAll must be of type Player here.'); + } + if (hunt.checkAfk && player.zonesAfk()) { + continue; + } + if (hunt.checkNotTooStrong === HuntCheckNotTooStrong_default.OUTSIDE_WILDERNESS && !player.isInWilderness() && player.combatLevel > type.vislevel * 2) { + continue; + } + if (hunt.checkNotCombat !== -1 && player.getVar(hunt.checkNotCombat) + 8 > World_default.currentTick) { + continue; + } else if (hunt.checkNotCombatSelf !== -1 && this.getVar(hunt.checkNotCombatSelf) >= World_default.currentTick) { + continue; + } + if (hunt.checkInv !== -1) { + let quantity = 0; + if (hunt.checkObj !== -1) { + quantity = player.invTotal(hunt.checkInv, hunt.checkObj); + } else if (hunt.checkObjParam !== -1) { + quantity = player.invTotalParam(hunt.checkInv, hunt.checkObjParam); + } + if (quantity < hunt.checkInvMinQuantity || quantity > hunt.checkInvMaxQuantity) { + continue; + } + } + if (hunt.checkNotBusy && player.busy()) { + continue; + } + players.push(player); + } + return players; + } + huntNpcs(hunt) { + return Array.from(new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, hunt.checkNpc, hunt.checkCategory, HuntModeType_default.NPC)); + } + huntObjs(hunt) { + return Array.from(new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, hunt.checkObj, hunt.checkCategory, HuntModeType_default.OBJ)); + } + huntLocs(hunt) { + return Array.from(new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, hunt.checkLoc, hunt.checkCategory, HuntModeType_default.SCENERY)); + } + playAnimation(anim, delay) { + if (anim >= SeqType.count) { + return; + } + if (anim == -1 || this.animId == -1 || SeqType.get(anim).priority > SeqType.get(this.animId).priority || SeqType.get(this.animId).priority === 0) { + this.animId = anim; + this.animDelay = delay; + this.mask |= Npc2.ANIM; + } + } + spotanim(spotanim, height, delay) { + this.graphicId = spotanim; + this.graphicHeight = height; + this.graphicDelay = delay; + this.mask |= Npc2.SPOTANIM; + } + applyDamage(damage, type) { + this.damageTaken = damage; + this.damageType = type; + const current = this.levels[NpcStat_default.HITPOINTS]; + if (current - damage <= 0) { + this.levels[NpcStat_default.HITPOINTS] = 0; + this.damageTaken = current; + } else { + this.levels[NpcStat_default.HITPOINTS] = current - damage; + } + this.mask |= Npc2.DAMAGE; + } + say(text) { + if (!text) { + return; + } + this.chat = text; + this.mask |= Npc2.SAY; + } + faceSquare(x, z2) { + this.faceX = x * 2 + 1; + this.faceZ = z2 * 2 + 1; + this.orientation = Position.face(this.x, this.z, x, z2); + this.mask |= Npc2.FACE_COORD; + } + changeType(type) { + this.type = type; + this.mask |= Npc2.CHANGE_TYPE; + this.uid = (type << 16) | this.nid; + const npcType = NpcType.get(type); + this.setTimer(npcType.timer); + } +} + +// src/lostcity/engine/GameMap.ts +class GameMap { + static OPEN = 0; + static BLOCKED = 1; + static BRIDGE = 2; + static ROOF = 4; + static WALL = 8; + static LOWMEMORY = 16; + static Y = 4; + static X = 64; + static Z = 64; + static MAPSQUARE = GameMap.X * GameMap.Y * GameMap.Z; + init(zoneMap) { + console.time('Loading game map'); + const path = 'data/pack/server/maps/'; + const maps = fs25.readdirSync(path).filter(x => x[0] === 'm'); + for (let index = 0; index < maps.length; index++) { + const [mx, mz] = maps[index].substring(1).split('_').map(Number); + const mapsquareX = mx << 6; + const mapsquareZ = mz << 6; + this.decodeNpcs(Packet.load(`${path}n${mx}_${mz}`), mapsquareX, mapsquareZ); + this.decodeObjs(Packet.load(`${path}o${mx}_${mz}`), mapsquareX, mapsquareZ, zoneMap); + const lands = new Int8Array(GameMap.MAPSQUARE); + this.decodeLands(lands, Packet.load(`${path}m${mx}_${mz}`), mapsquareX, mapsquareZ); + this.decodeLocs(lands, Packet.load(`${path}l${mx}_${mz}`), mapsquareX, mapsquareZ, zoneMap); + } + console.timeEnd('Loading game map'); + } + async initAsync(zoneMap) { + console.time('Loading game map'); + const path = 'data/pack/server/maps/'; + const maps = [ + 'm29_75', + 'm30_75', + 'm31_75', + 'm32_70', + 'm32_71', + 'm32_72', + 'm32_73', + 'm32_74', + 'm32_75', + 'm33_70', + 'm33_71', + 'm33_72', + 'm33_73', + 'm33_74', + 'm33_75', + 'm33_76', + 'm34_70', + 'm34_71', + 'm34_72', + 'm34_73', + 'm34_74', + 'm34_75', + 'm34_76', + 'm35_20', + 'm35_75', + 'm35_76', + 'm36_146', + 'm36_147', + 'm36_148', + 'm36_149', + 'm36_150', + 'm36_153', + 'm36_154', + 'm36_52', + 'm36_53', + 'm36_54', + 'm36_72', + 'm36_73', + 'm36_74', + 'm36_75', + 'm36_76', + 'm37_146', + 'm37_147', + 'm37_148', + 'm37_149', + 'm37_150', + 'm37_151', + 'm37_152', + 'm37_153', + 'm37_154', + 'm37_48', + 'm37_49', + 'm37_50', + 'm37_51', + 'm37_52', + 'm37_53', + 'm37_54', + 'm37_55', + 'm37_72', + 'm37_73', + 'm37_74', + 'm37_75', + 'm38_146', + 'm38_147', + 'm38_148', + 'm38_149', + 'm38_150', + 'm38_151', + 'm38_152', + 'm38_153', + 'm38_154', + 'm38_155', + 'm38_45', + 'm38_46', + 'm38_47', + 'm38_48', + 'm38_49', + 'm38_50', + 'm38_51', + 'm38_52', + 'm38_53', + 'm38_54', + 'm38_55', + 'm38_72', + 'm38_73', + 'm38_74', + 'm39_147', + 'm39_148', + 'm39_149', + 'm39_150', + 'm39_151', + 'm39_152', + 'm39_153', + 'm39_154', + 'm39_155', + 'm39_45', + 'm39_46', + 'm39_47', + 'm39_48', + 'm39_49', + 'm39_50', + 'm39_51', + 'm39_52', + 'm39_53', + 'm39_54', + 'm39_55', + 'm39_72', + 'm39_73', + 'm39_74', + 'm39_75', + 'm39_76', + 'm40_147', + 'm40_148', + 'm40_149', + 'm40_150', + 'm40_151', + 'm40_152', + 'm40_153', + 'm40_154', + 'm40_45', + 'm40_46', + 'm40_47', + 'm40_48', + 'm40_49', + 'm40_50', + 'm40_51', + 'm40_52', + 'm40_53', + 'm40_54', + 'm40_55', + 'm40_72', + 'm40_73', + 'm40_74', + 'm40_75', + 'm40_76', + 'm41_146', + 'm41_149', + 'm41_151', + 'm41_152', + 'm41_153', + 'm41_154', + 'm41_45', + 'm41_46', + 'm41_47', + 'm41_48', + 'm41_49', + 'm41_50', + 'm41_51', + 'm41_52', + 'm41_53', + 'm41_54', + 'm41_55', + 'm41_56', + 'm41_72', + 'm41_73', + 'm41_74', + 'm41_75', + 'm42_144', + 'm42_145', + 'm42_146', + 'm42_151', + 'm42_152', + 'm42_153', + 'm42_49', + 'm42_50', + 'm42_51', + 'm42_52', + 'm42_53', + 'm42_54', + 'm42_55', + 'm42_56', + 'm42_72', + 'm42_73', + 'm42_74', + 'm42_75', + 'm43_144', + 'm43_145', + 'm43_146', + 'm43_153', + 'm43_154', + 'm43_45', + 'm43_46', + 'm43_47', + 'm43_48', + 'm43_49', + 'm43_50', + 'm43_51', + 'm43_52', + 'm43_53', + 'm43_54', + 'm43_55', + 'm43_56', + 'm43_72', + 'm43_73', + 'm43_74', + 'm43_75', + 'm44_144', + 'm44_145', + 'm44_146', + 'm44_148', + 'm44_149', + 'm44_150', + 'm44_151', + 'm44_152', + 'm44_153', + 'm44_154', + 'm44_155', + 'm44_45', + 'm44_46', + 'm44_47', + 'm44_48', + 'm44_49', + 'm44_50', + 'm44_51', + 'm44_52', + 'm44_53', + 'm44_54', + 'm44_55', + 'm44_72', + 'm44_73', + 'm44_74', + 'm44_75', + 'm45_145', + 'm45_146', + 'm45_148', + 'm45_150', + 'm45_151', + 'm45_152', + 'm45_153', + 'm45_154', + 'm45_155', + 'm45_45', + 'm45_46', + 'm45_47', + 'm45_48', + 'm45_49', + 'm45_50', + 'm45_51', + 'm45_52', + 'm45_53', + 'm45_54', + 'm45_55', + 'm45_56', + 'm45_57', + 'm45_58', + 'm45_59', + 'm45_60', + 'm45_61', + 'm45_62', + 'm45_73', + 'm45_74', + 'm45_75', + 'm45_76', + 'm46_149', + 'm46_150', + 'm46_152', + 'm46_153', + 'm46_154', + 'm46_161', + 'm46_45', + 'm46_46', + 'm46_47', + 'm46_48', + 'm46_49', + 'm46_50', + 'm46_51', + 'm46_52', + 'm46_53', + 'm46_54', + 'm46_55', + 'm46_56', + 'm46_57', + 'm46_58', + 'm46_59', + 'm46_60', + 'm46_61', + 'm46_62', + 'm46_75', + 'm47_148', + 'm47_149', + 'm47_150', + 'm47_152', + 'm47_153', + 'm47_160', + 'm47_161', + 'm47_47', + 'm47_48', + 'm47_49', + 'm47_50', + 'm47_51', + 'm47_52', + 'm47_53', + 'm47_54', + 'm47_55', + 'm47_56', + 'm47_57', + 'm47_58', + 'm47_59', + 'm47_60', + 'm47_61', + 'm47_62', + 'm47_75', + 'm48_148', + 'm48_149', + 'm48_152', + 'm48_153', + 'm48_154', + 'm48_155', + 'm48_156', + 'm48_47', + 'm48_48', + 'm48_49', + 'm48_50', + 'm48_51', + 'm48_52', + 'm48_53', + 'm48_54', + 'm48_55', + 'm48_56', + 'm48_57', + 'm48_58', + 'm48_59', + 'm48_60', + 'm48_61', + 'm48_62', + 'm49_148', + 'm49_149', + 'm49_153', + 'm49_154', + 'm49_155', + 'm49_156', + 'm49_46', + 'm49_47', + 'm49_48', + 'm49_49', + 'm49_50', + 'm49_51', + 'm49_52', + 'm49_53', + 'm49_54', + 'm49_55', + 'm49_56', + 'm49_57', + 'm49_58', + 'm49_59', + 'm49_60', + 'm49_61', + 'm49_62', + 'm50_149', + 'm50_150', + 'm50_152', + 'm50_153', + 'm50_154', + 'm50_46', + 'm50_47', + 'm50_48', + 'm50_49', + 'm50_50', + 'm50_51', + 'm50_52', + 'm50_53', + 'm50_54', + 'm50_55', + 'm50_56', + 'm50_57', + 'm50_58', + 'm50_59', + 'm50_60', + 'm50_61', + 'm50_62', + 'm51_147', + 'm51_154', + 'm51_46', + 'm51_47', + 'm51_48', + 'm51_49', + 'm51_50', + 'm51_51', + 'm51_52', + 'm51_53', + 'm51_54', + 'm51_55', + 'm51_56', + 'm51_57', + 'm51_58', + 'm51_59', + 'm51_60', + 'm51_61', + 'm51_62', + 'm52_152', + 'm52_153', + 'm52_154', + 'm52_46', + 'm52_47', + 'm52_48', + 'm52_49', + 'm52_50', + 'm52_51', + 'm52_52', + 'm52_53', + 'm52_54', + 'm52_55', + 'm52_56', + 'm52_57', + 'm52_58', + 'm52_59', + 'm52_60', + 'm52_61', + 'm52_62', + 'm53_49', + 'm53_50', + 'm53_51', + 'm53_52', + 'm53_53' + ]; + for (let index = 0; index < maps.length; index++) { + const [mx, mz] = maps[index].substring(1).split('_').map(Number); + const mapsquareX = mx << 6; + const mapsquareZ = mz << 6; + this.decodeNpcs(await Packet.loadAsync(`${path}n${mx}_${mz}`), mapsquareX, mapsquareZ); + this.decodeObjs(await Packet.loadAsync(`${path}o${mx}_${mz}`), mapsquareX, mapsquareZ, zoneMap); + const lands = new Int8Array(GameMap.MAPSQUARE); + this.decodeLands(lands, await Packet.loadAsync(`${path}m${mx}_${mz}`), mapsquareX, mapsquareZ); + this.decodeLocs(lands, await Packet.loadAsync(`${path}l${mx}_${mz}`), mapsquareX, mapsquareZ, zoneMap); + } + console.timeEnd('Loading game map'); + } + changeLandCollision(x, z2, level, add) { + changeFloor(x, z2, level, add); + } + changeLocCollision(shape, angle, blockrange, length, width, active, x, z2, level, add) { + const locLayer = locShapeLayer(shape); + if (locLayer === LocLayer.WALL) { + changeWall(x, z2, level, angle, shape, blockrange, false, add); + } else if (locLayer === LocLayer.GROUND) { + if (angle === LocAngle.NORTH || angle === LocAngle.SOUTH) { + changeLoc(x, z2, level, length, width, blockrange, false, add); + } else { + changeLoc(x, z2, level, width, length, blockrange, false, add); + } + } else if (locLayer === LocLayer.GROUND_DECOR) { + if (active === 1) { + changeFloor(x, z2, level, add); + } + } + } + changeNpcCollision(size, x, z2, level, add) { + changeNpc(x, z2, level, size, add); + } + changePlayerCollision(size, x, z2, level, add) { + changePlayer(x, z2, level, size, add); + } + changeRoofCollision(x, z2, level, add) { + changeRoof(x, z2, level, add); + } + decodeNpcs(packet, mapsquareX, mapsquareZ) { + while (packet.available > 0) { + const {x, z: z2, level} = this.unpackCoord(packet.g2()); + const absoluteX = mapsquareX + x; + const absoluteZ = mapsquareZ + z2; + const count = packet.g1(); + for (let index = 0; index < count; index++) { + const npcType = NpcType.get(packet.g2()); + const size = npcType.size; + const npc = new Npc2(level, absoluteX, absoluteZ, size, size, EntityLifeCycle_default.RESPAWN, World_default.getNextNid(), npcType.id, npcType.moverestrict, npcType.blockwalk); + if ((npcType.members && Environment_default.NODE_MEMBERS) || !npcType.members) { + World_default.addNpc(npc, -1); + } + } + } + } + decodeObjs(packet, mapsquareX, mapsquareZ, zoneMap) { + while (packet.available > 0) { + const {x, z: z2, level} = this.unpackCoord(packet.g2()); + const absoluteX = mapsquareX + x; + const absoluteZ = mapsquareZ + z2; + const count = packet.g1(); + for (let j = 0; j < count; j++) { + const objType = ObjType.get(packet.g2()); + const obj = new Obj(level, absoluteX, absoluteZ, EntityLifeCycle_default.RESPAWN, objType.id, packet.g1()); + if ((objType.members && Environment_default.NODE_MEMBERS) || !objType.members) { + zoneMap.zone(obj.x, obj.z, obj.level).addStaticObj(obj); + } + } + } + } + decodeLands(lands, packet, mapsquareX, mapsquareZ) { + for (let level = 0; level < GameMap.Y; level++) { + for (let x = 0; x < GameMap.X; x++) { + for (let z2 = 0; z2 < GameMap.Z; z2++) { + while (true) { + const opcode = packet.g1(); + if (opcode === 0) { + break; + } else if (opcode === 1) { + packet.pos++; + break; + } + if (opcode <= 49) { + packet.pos++; + } else if (opcode <= 81) { + lands[this.packCoord(x, z2, level)] = opcode - 49; + } + } + } + } + } + for (let level = 0; level < GameMap.Y; level++) { + for (let x = 0; x < GameMap.X; x++) { + const absoluteX = x + mapsquareX; + for (let z2 = 0; z2 < GameMap.Z; z2++) { + const absoluteZ = z2 + mapsquareZ; + if (x % 7 === 0 && z2 % 7 === 0) { + allocateIfAbsent(absoluteX, absoluteZ, level); + } + const land = lands[this.packCoord(x, z2, level)]; + if ((land & GameMap.ROOF) !== GameMap.OPEN) { + this.changeRoofCollision(absoluteX, absoluteZ, level, true); + } + if ((land & GameMap.BLOCKED) !== GameMap.BLOCKED) { + continue; + } + const bridged = (level === 1 ? land & GameMap.BRIDGE : lands[this.packCoord(x, z2, 1)] & GameMap.BRIDGE) === GameMap.BRIDGE; + const actualLevel = bridged ? level - 1 : level; + if (actualLevel < 0) { + continue; + } + this.changeLandCollision(absoluteX, absoluteZ, actualLevel, true); + } + } + } + } + decodeLocs(lands, packet, mapsquareX, mapsquareZ, zoneMap) { + let locId = -1; + let locIdOffset = packet.gsmart(); + while (locIdOffset !== 0) { + locId += locIdOffset; + let coord = 0; + let coordOffset = packet.gsmart(); + while (coordOffset !== 0) { + const {x, z: z2, level} = this.unpackCoord((coord += coordOffset - 1)); + const info = packet.g1(); + coordOffset = packet.gsmart(); + const bridged = (level === 1 ? lands[coord] & GameMap.BRIDGE : lands[this.packCoord(x, z2, 1)] & GameMap.BRIDGE) === GameMap.BRIDGE; + const actualLevel = bridged ? level - 1 : level; + if (actualLevel < 0) { + continue; + } + const type = LocType.get(locId); + const width = type.width; + const length = type.length; + const shape = info >> 2; + const angle = info & 3; + const absoluteX = x + mapsquareX; + const absoluteZ = z2 + mapsquareZ; + zoneMap.zone(absoluteX, absoluteZ, actualLevel).addStaticLoc(new Loc(actualLevel, absoluteX, absoluteZ, width, length, EntityLifeCycle_default.RESPAWN, locId, shape, angle)); + if (type.blockwalk) { + this.changeLocCollision(shape, angle, type.blockrange, length, width, type.active, absoluteX, absoluteZ, actualLevel, true); + } + } + locIdOffset = packet.gsmart(); + } + } + packCoord(x, z2, level) { + return (z2 & 63) | ((x & 63) << 6) | ((level & 3) << 12); + } + unpackCoord(packed) { + const z2 = packed & 63; + const x = (packed >> 6) & 63; + const level = (packed >> 12) & 3; + return {x, z: z2, level}; + } +} + +// src/lostcity/engine/Login.ts + +// src/jagex2/io/Isaac.ts +class Isaac { + count = 0; + rsl = new Int32Array(256); + mem = new Int32Array(256); + a = 0; + b = 0; + c = 0; + constructor(seed = [0, 0, 0, 0]) { + for (let i = 0; i < seed.length; i++) { + this.rsl[i] = seed[i]; + } + this.init(); + } + init() { + let a = 2654435769, + b3 = 2654435769, + c = 2654435769, + d = 2654435769, + e = 2654435769, + f = 2654435769, + g = 2654435769, + h2 = 2654435769; + for (let i = 0; i < 4; i++) { + a ^= b3 << 11; + d += a; + b3 += c; + b3 ^= c >>> 2; + e += b3; + c += d; + c ^= d << 8; + f += c; + d += e; + d ^= e >>> 16; + g += d; + e += f; + e ^= f << 10; + h2 += e; + f += g; + f ^= g >>> 4; + a += f; + g += h2; + g ^= h2 << 8; + b3 += g; + h2 += a; + h2 ^= a >>> 9; + c += h2; + a += b3; + } + for (let i = 0; i < 256; i += 8) { + a += this.rsl[i]; + b3 += this.rsl[i + 1]; + c += this.rsl[i + 2]; + d += this.rsl[i + 3]; + e += this.rsl[i + 4]; + f += this.rsl[i + 5]; + g += this.rsl[i + 6]; + h2 += this.rsl[i + 7]; + a ^= b3 << 11; + d += a; + b3 += c; + b3 ^= c >>> 2; + e += b3; + c += d; + c ^= d << 8; + f += c; + d += e; + d ^= e >>> 16; + g += d; + e += f; + e ^= f << 10; + h2 += e; + f += g; + f ^= g >>> 4; + a += f; + g += h2; + g ^= h2 << 8; + b3 += g; + h2 += a; + h2 ^= a >>> 9; + c += h2; + a += b3; + this.mem[i] = a; + this.mem[i + 1] = b3; + this.mem[i + 2] = c; + this.mem[i + 3] = d; + this.mem[i + 4] = e; + this.mem[i + 5] = f; + this.mem[i + 6] = g; + this.mem[i + 7] = h2; + } + for (let i = 0; i < 256; i += 8) { + a += this.mem[i]; + b3 += this.mem[i + 1]; + c += this.mem[i + 2]; + d += this.mem[i + 3]; + e += this.mem[i + 4]; + f += this.mem[i + 5]; + g += this.mem[i + 6]; + h2 += this.mem[i + 7]; + a ^= b3 << 11; + d += a; + b3 += c; + b3 ^= c >>> 2; + e += b3; + c += d; + c ^= d << 8; + f += c; + d += e; + d ^= e >>> 16; + g += d; + e += f; + e ^= f << 10; + h2 += e; + f += g; + f ^= g >>> 4; + a += f; + g += h2; + g ^= h2 << 8; + b3 += g; + h2 += a; + h2 ^= a >>> 9; + c += h2; + a += b3; + this.mem[i] = a; + this.mem[i + 1] = b3; + this.mem[i + 2] = c; + this.mem[i + 3] = d; + this.mem[i + 4] = e; + this.mem[i + 5] = f; + this.mem[i + 6] = g; + this.mem[i + 7] = h2; + } + this.isaac(); + this.count = 256; + } + isaac() { + this.c++; + this.b += this.c; + for (let i = 0; i < 256; i++) { + const x = this.mem[i]; + switch (i & 3) { + case 0: + this.a ^= this.a << 13; + break; + case 1: + this.a ^= this.a >>> 6; + break; + case 2: + this.a ^= this.a << 2; + break; + case 3: + this.a ^= this.a >>> 16; + break; + } + this.a += this.mem[(i + 128) & 255]; + let y3; + this.mem[i] = y3 = this.mem[(x >>> 2) & 255] + this.a + this.b; + this.rsl[i] = this.b = this.mem[((y3 >>> 8) >>> 2) & 255] + x; + } + } + nextInt() { + if (this.count-- === 0) { + this.isaac(); + this.count = 255; + } + return this.rsl[this.count]; + } +} + +// src/lostcity/entity/PlayerLoading.ts +var {default: fs26} = () => ({}); +class PlayerLoading { + static loadFromFile(name) { + const name37 = toBase37(name); + const safeName = fromBase37(name37); + let save; + if (fs26.existsSync(`data/players/${safeName}.sav`)) { + save = Packet.load(`data/players/${safeName}.sav`); + } else { + save = new Packet(new Uint8Array()); + } + return PlayerLoading.load(name, save, null); + } + static load(name, sav, client) { + const name37 = toBase37(name); + const safeName = fromBase37(name37); + const player = client ? new NetworkPlayer2(safeName, name37, client) : new Player2(safeName, name37); + if (sav.data.length < 2) { + for (let i = 0; i < 21; i++) { + player.stats[i] = 0; + player.baseLevels[i] = 1; + player.levels[i] = 1; + } + player.stats[PlayerStat_default.HITPOINTS] = getExpByLevel(10); + player.baseLevels[PlayerStat_default.HITPOINTS] = 10; + player.levels[PlayerStat_default.HITPOINTS] = 10; + return player; + } + if (sav.g2() !== 8196) { + throw new Error('Invalid player save'); + } + const version = sav.g2(); + if (version > 3) { + throw new Error('Unsupported player save format'); + } + sav.pos = sav.data.length - 4; + const crc = sav.g4(); + if (crc != Packet.getcrc(sav.data, 0, sav.data.length - 4)) { + throw new Error('Player save corrupted'); + } + sav.pos = 4; + player.x = sav.g2(); + player.z = sav.g2(); + player.level = sav.g1(); + for (let i = 0; i < 7; i++) { + player.body[i] = sav.g1(); + if (player.body[i] === 255) { + player.body[i] = -1; + } + } + for (let i = 0; i < 5; i++) { + player.colors[i] = sav.g1(); + } + player.gender = sav.g1(); + player.runenergy = sav.g2(); + if (version >= 2) { + player.playtime = sav.g4(); + } else { + player.playtime = sav.g2(); + } + for (let i = 0; i < 21; i++) { + player.stats[i] = sav.g4(); + player.baseLevels[i] = getLevelByExp(player.stats[i]); + player.levels[i] = sav.g1(); + } + const varpCount = sav.g2(); + for (let i = 0; i < varpCount; i++) { + player.vars[i] = sav.g4(); + } + const invCount = sav.g1(); + for (let i = 0; i < invCount; i++) { + const type = sav.g2(); + const inv = player.getInventory(type); + if (inv) { + for (let j = 0; j < inv.capacity; j++) { + const id = sav.g2(); + if (id === 0) { + continue; + } + let count = sav.g1(); + if (count === 255) { + count = sav.g4(); + } + inv.set(j, { + id: id - 1, + count + }); + } + } + } + if (version >= 3) { + const afkZones = sav.g1(); + for (let index = 0; index < afkZones; index++) { + player.afkZones[index] = sav.g4(); + } + player.lastAfkZone = sav.g2(); + } + player.combatLevel = player.getCombatLevel(); + player.lastResponse = World_default.currentTick; + if (!Environment_default.NODE_PRODUCTION) { + player.staffModLevel = 3; + } else if (Environment_default.NODE_STAFF.find(name2 => name2 === safeName) !== undefined) { + player.staffModLevel = 3; + } + return player; + } +} + +// src/lostcity/util/WorkerFactory.ts +var {Worker: NodeWorker} = () => ({}); +function createWorker(fileName) { + if (typeof self !== 'undefined') { + return new Worker(fileName, {type: 'module'}); + } else { + return new NodeWorker(fileName); + } +} + +// src/lostcity/server/LoginServer.ts +var {default: fs27} = () => ({}); +var {default: fsp} = () => ({}); + +// node:net +var r = function (e) { + return s.test(e); +}; +var o = function (e) { + return u.test(e); +}; +var c = function (e) { + return r(e) ? 4 : o(e) ? 6 : 0; +}; +var n = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])'; +var t = `(?:${n}\\.){3}${n}`; +var s = new RegExp(`^${t}\$`); +var $2 = '(?:[0-9a-fA-F]{1,4})'; +var u = new RegExp( + `^(?:(?:${$2}:){7}(?:${$2}|:)|(?:${$2}:){6}(?:${t}|:${$2}|:)|(?:${$2}:){5}(?::${t}|(?::${$2}){1,2}|:)|(?:${$2}:){4}(?:(?::${$2}){0,1}:${t}|(?::${$2}){1,3}|:)|(?:${$2}:){3}(?:(?::${$2}){0,2}:${t}|(?::${$2}){1,4}|:)|(?:${$2}:){2}(?:(?::${$2}){0,3}:${t}|(?::${$2}){1,5}|:)|(?:${$2}:){1}(?:(?::${$2}){0,4}:${t}|(?::${$2}){1,6}|:)|(?::(?:(?::${$2}){0,5}:${t}|(?::${$2}){1,7}|:)))(?:%[0-9a-zA-Z-.:]{1,})?\$` +); +var i = {isIP: c, isIPv4: r, isIPv6: o}; + +// src/lostcity/server/LoginServer.ts + +// src/lostcity/server/NetworkStream.ts +class NetworkStream { + queue = []; + available = 0; + buffer = null; + offset = 0; + waiting = 0; + received(buf) { + this.queue.push(buf); + this.available += buf.length; + } + clear() { + this.queue = []; + this.available = 0; + this.buffer = null; + this.offset = 0; + } + async readByte(socket) { + if (socket === null || socket.closed) { + return 0; + } + if (this.available < 1) { + await new Promise(res => setTimeout(res, 10)); + return this.readByte(socket); + } + if (this.buffer === null) { + this.buffer = this.queue.shift() ?? null; + this.offset = 0; + } + const value = this.buffer?.[this.offset] ?? 0; + this.offset++; + this.available--; + if (this.buffer && this.offset === this.buffer.length) { + this.buffer = null; + } + return value; + } + async readBytes(socket, destination, offset, length, full = true) { + if (socket === null || socket.closed) { + return 0; + } + if (this.available < length) { + if (full) { + await new Promise(res => setTimeout(res, 10)); + return this.readBytes(socket, destination, offset, length); + } else { + length = this.available; + } + } + destination.pos = offset; + for (let i3 = 0; i3 < length; i3++) { + if (this.buffer === null) { + this.buffer = this.queue.shift() ?? null; + this.offset = 0; + } + destination.data[offset + i3] = this.buffer?.[this.offset] ?? 0; + this.offset++; + this.available--; + if (this.buffer && this.offset === this.buffer.length) { + this.buffer = null; + } + } + return length; + } +} + +// src/lostcity/server/LoginServer.ts +class LoginResponse { + static SUCCESSFUL = Uint8Array.from([2]); + static INVALID_USER_OR_PASS = Uint8Array.from([3]); + static ACCOUNT_DISABLED = Uint8Array.from([4]); + static LOGGED_IN = Uint8Array.from([5]); + static SERVER_UPDATED = Uint8Array.from([6]); + static WORLD_FULL = Uint8Array.from([7]); + static LOGIN_SERVER_OFFLINE = Uint8Array.from([8]); + static LOGIN_LIMIT_EXCEEDED = Uint8Array.from([9]); + static UNABLE_TO_CONNECT = Uint8Array.from([10]); + static LOGIN_REJECTED = Uint8Array.from([11]); + static NEED_MEMBERS_ACCOUNT = Uint8Array.from([12]); + static COULD_NOT_COMPLETE = Uint8Array.from([13]); + static SERVER_UPDATING = Uint8Array.from([14]); + static RECONNECTING = Uint8Array.from([15]); + static LOGIN_ATTEMPTS_EXCEEDED = Uint8Array.from([16]); + static STANDING_IN_MEMBERS = Uint8Array.from([17]); + static STAFF_MOD_LEVEL = Uint8Array.from([18]); +} +class LoginClient { + socket = null; + stream = new NetworkStream(); + async connect() { + if (this.socket) { + return; + } + return new Promise(res => { + this.socket = i.createConnection({ + port: Environment_default.LOGIN_PORT, + host: Environment_default.LOGIN_HOST + }); + this.socket.setNoDelay(true); + this.socket.setTimeout(1000); + this.socket.on('data', async buf => { + this.stream.received(buf); + }); + this.socket.once('close', () => { + this.disconnect(); + res(); + }); + this.socket.once('error', () => { + this.disconnect(); + res(); + }); + this.socket.once('connect', () => { + res(); + }); + }); + } + disconnect() { + if (this.socket === null) { + return; + } + this.socket.destroy(); + this.socket = null; + this.stream.clear(); + } + async write(socket, opcode, data = null, full = true) { + if (socket === null) { + return; + } + const packet = new Packet(new Uint8Array(1 + 2 + (data !== null ? data?.length : 0))); + packet.p1(opcode); + if (data !== null) { + packet.p2(data.length); + packet.pdata(data, 0, data.length); + } else { + packet.p2(0); + } + const done = socket.write(packet.data); + if (!done && full) { + await new Promise(res => { + const interval = setInterval(() => { + if (socket === null || socket.closed) { + clearInterval(interval); + res(); + } + }, 100); + socket.once('drain', () => { + clearInterval(interval); + res(); + }); + }); + } + } + async load(username37, password, uid) { + await this.connect(); + if (this.socket === null) { + return {reply: -1, data: null}; + } + const request = new Packet(new Uint8Array(2 + 8 + password.length + 1 + 4)); + request.p2(Environment_default.NODE_ID); + request.p8(username37); + request.pjstr(password); + request.p4(uid); + await this.write(this.socket, 1, request.data); + const reply = await this.stream.readByte(this.socket); + if (reply !== 1) { + this.disconnect(); + return {reply, data: null}; + } + const data = new Packet(new Uint8Array(2)); + await this.stream.readBytes(this.socket, data, 0, 2); + const length = data.g2(); + const data2 = new Packet(new Uint8Array(length)); + await this.stream.readBytes(this.socket, data2, 0, length); + this.disconnect(); + return {reply, data: data2}; + } + async save(username37, save) { + await this.connect(); + if (this.socket === null) { + return -1; + } + const request = new Packet(new Uint8Array(2 + 8 + 2 + save.length)); + request.p2(Environment_default.NODE_ID); + request.p8(username37); + request.p2(save.length); + request.pdata(save, 0, save.length); + await this.write(this.socket, 2, request.data); + const reply = await this.stream.readByte(this.socket); + this.disconnect(); + return reply; + } + async reset() { + await this.connect(); + if (this.socket === null) { + return -1; + } + const request = new Packet(new Uint8Array(2)); + request.p2(Environment_default.NODE_ID); + await this.write(this.socket, 3, request.data); + this.disconnect(); + } + async count(world) { + await this.connect(); + if (this.socket === null) { + return -1; + } + const request = new Packet(new Uint8Array(2)); + request.p2(world); + await this.write(this.socket, 4, request.data); + const reply = new Packet(new Uint8Array(2)); + await this.stream.readBytes(this.socket, reply, 0, 2); + const count = reply.g2(); + this.disconnect(); + return count; + } + async heartbeat(players) { + await this.connect(); + if (this.socket === null) { + return -1; + } + const request = new Packet(new Uint8Array(2 + 2 + players.length * 8)); + request.p2(Environment_default.NODE_ID); + request.p2(players.length); + for (const player of players) { + request.p8(player); + } + await this.write(this.socket, 5, request.data); + this.disconnect(); + } +} + +// src/lostcity/server/CrcTable.ts +var {default: fs28} = () => ({}); +var makeCrc = function (path) { + if (!fs28.existsSync(path)) { + return; + } + const packet = Packet.load(path); + const crc = Packet.getcrc(packet.data, 0, packet.data.length); + CrcTable.push(crc); + CrcBuffer.p4(crc); +}; +function makeCrcs() { + CrcTable = []; + CrcBuffer.pos = 0; + CrcBuffer.p4(0); + makeCrc('data/pack/client/title'); + makeCrc('data/pack/client/config'); + makeCrc('data/pack/client/interface'); + makeCrc('data/pack/client/media'); + makeCrc('data/pack/client/models'); + makeCrc('data/pack/client/textures'); + makeCrc('data/pack/client/wordenc'); + makeCrc('data/pack/client/sounds'); + CrcBuffer32 = Packet.getcrc(CrcBuffer.data, 0, CrcBuffer.data.length); +} +var CrcBuffer = new Packet(new Uint8Array(4 * 9)); +var CrcTable = []; +var CrcBuffer32 = 0; +if (typeof self === 'undefined') { + if (fs28.existsSync('data/pack/client/')) { + makeCrcs(); + } +} + +// src/lostcity/engine/Login.ts +class Login { + loginThread = createWorker(typeof self !== 'undefined' ? 'LoginThread.js' : './src/lostcity/server/LoginThread.ts'); + loginRequests = new Map(); + logoutRequests = new Set(); + constructor() { + const onMsg = msg => { + try { + this.onMessage(msg); + } catch (err) { + console.error('Login Thread:', err); + } + }; + if (typeof self !== 'undefined') { + if (this.loginThread instanceof Worker) { + this.loginThread.onmessage = onMsg; + } + } else { + if (this.loginThread instanceof NodeWorker2) { + this.loginThread.on('message', onMsg); + } + } + } + async readIn(socket, data) { + const opcode = data.g1(); + if (opcode === 16) { + const length = data.g1(); + if (data.available < length) { + socket.terminate(); + return; + } + const post = new Uint8Array(length); + data.gdata(post, 0, post.length); + data.pos -= post.length; + const revision = data.g1(); + if (revision !== 225) { + socket.writeImmediate(LoginResponse.SERVER_UPDATED); + return; + } + data.pos += 1; + const crcs = new Uint8Array(9 * 4); + data.gdata(crcs, 0, crcs.length); + if (typeof self === 'undefined') { + if (!Packet.checkcrc(crcs, 0, crcs.length, CrcBuffer32)) { + socket.writeImmediate(LoginResponse.SERVER_UPDATED); + return; + } + } + this.loginThread.postMessage({ + type: 'loginreq', + opcode, + data: post, + socket: socket.uniqueId + }); + this.loginRequests.set(socket.uniqueId, socket); + } else { + socket.terminate(); + } + } + logout(player) { + if (this.logoutRequests.has(player.username37)) { + return; + } + const save = player.save(); + this.loginThread.postMessage({ + type: 'logout', + username: player.username, + save: save.data.subarray(0, save.pos) + }); + save.release(); + } + onMessage(msg) { + if (typeof self === 'undefined') { + switch (msg.type) { + case 'loginreply': { + const {status, socket} = msg; + const client = this.loginRequests.get(socket); + if (!client) { + return; + } + this.loginRequests.delete(socket); + if (status[0] !== 2) { + client.writeImmediate(status); + client.close(); + return; + } + const {info, seed, username, save} = msg; + if (World_default.getTotalPlayers() >= 2000) { + client.writeImmediate(LoginResponse.WORLD_FULL); + client.close(); + return; + } + if (World_default.shutdownTick > -1 && World_default.currentTick - World_default.shutdownTick > 0) { + client.writeImmediate(LoginResponse.SERVER_UPDATING); + client.close(); + return; + } + if (!Environment_default.LOGIN_KEY) { + for (const player2 of World_default.players) { + if (player2.username === username) { + client.writeImmediate(LoginResponse.LOGGED_IN); + client.close(); + return; + } + } + } + client.decryptor = new Isaac(seed); + for (let i3 = 0; i3 < 4; i3++) { + seed[i3] += 50; + } + client.encryptor = new Isaac(seed); + const player = PlayerLoading.load(username, new Packet(save), client); + player.lowMemory = (info & 1) !== 0; + player.webClient = client.isWebSocket(); + World_default.addPlayer(player); + break; + } + case 'logoutreply': { + const {username} = msg; + const player = World_default.getPlayerByUsername(username); + if (player) { + World_default.getZone(player.x, player.z, player.level).leave(player); + World_default.players.remove(player.pid); + player.pid = -1; + player.terminate(); + this.logoutRequests.delete(player.username37); + } + break; + } + default: + throw new Error('Unknown message type: ' + msg.type); + } + } else { + switch (msg.data.type) { + case 'loginreply': { + const {status, socket} = msg.data; + const client = this.loginRequests.get(socket); + if (!client) { + return; + } + this.loginRequests.delete(socket); + if (status[0] !== 2) { + client.writeImmediate(status); + client.close(); + return; + } + const {info, seed, username, save} = msg.data; + if (World_default.getTotalPlayers() >= 2000) { + client.writeImmediate(LoginResponse.WORLD_FULL); + client.close(); + return; + } + if (World_default.shutdownTick > -1 && World_default.currentTick - World_default.shutdownTick > 0) { + client.writeImmediate(LoginResponse.SERVER_UPDATING); + client.close(); + return; + } + if (!Environment_default.LOGIN_KEY) { + for (const player2 of World_default.players) { + if (player2.username === username) { + client.writeImmediate(LoginResponse.LOGGED_IN); + client.close(); + return; + } + } + } + client.decryptor = new Isaac(seed); + for (let i3 = 0; i3 < 4; i3++) { + seed[i3] += 50; + } + client.encryptor = new Isaac(seed); + const player = PlayerLoading.load(username, new Packet(save), client); + player.lowMemory = (info & 1) !== 0; + player.webClient = true; + World_default.addPlayer(player); + break; + } + case 'logoutreply': { + const {username} = msg.data; + const player = World_default.getPlayerByUsername(username); + if (player) { + World_default.getZone(player.x, player.z, player.level).leave(player); + World_default.players.remove(player.pid); + player.pid = -1; + player.terminate(); + this.logoutRequests.delete(player.username37); + } + break; + } + default: + throw new Error('Unknown message type: ' + msg.data.type); + } + } + } +} +var Login_default = new Login(); + +// src/lostcity/entity/EntityList.ts +class EntityList extends Array { + free; + indexPadding; + ids; + lastUsedIndex = 0; + constructor(size, indexPadding) { + super(size); + this.ids = new Int32Array(size).fill(-1); + this.free = new Set(Array.from({length: size}, (_4, index) => index)); + this.indexPadding = indexPadding; + } + next(_4 = false, start = this.lastUsedIndex + 1) { + const length = this.ids.length; + for (let index = start; index < length; index++) { + if (this.ids[index] === -1) { + return index; + } + } + for (let index = this.indexPadding; index < start; index++) { + if (this.ids[index] === -1) { + return index; + } + } + throw new Error('[EntityList] no space for new entities'); + } + *[Symbol.iterator]() { + for (const index of this.ids) { + if (index === -1) { + continue; + } + const entity = this[index]; + if (typeof entity === 'undefined') { + continue; + } + yield entity; + } + } + get count() { + let count = 0; + for (const _4 of this[Symbol.iterator]()) { + count++; + } + return count; + } + get(id) { + const index = this.ids[id]; + return index !== -1 ? this[index] : undefined; + } + set(id, entity) { + if (!this.free.size) { + throw new Error('[EntityList] cannot find available entities slot.'); + } + const index = this.free.values().next().value; + this.free.delete(index); + this.ids[id] = index; + this[index] = entity; + this.lastUsedIndex = id; + } + remove(id) { + const index = this.ids[id]; + if (index !== -1) { + this.ids[id] = -1; + this.free.add(index); + } + } + reset() { + this.length = 0; + this.ids.fill(-1); + this.free.clear(); + for (let i3 = 0; i3 < this.ids.length; i3++) { + this.free.add(i3); + } + } +} + +class NpcList extends EntityList { + constructor(size) { + super(size, 0); + } +} + +class PlayerList extends EntityList { + constructor(size) { + super(size, 1); + } + next(priority = false, start = this.lastUsedIndex + 1) { + if (priority) { + const init2 = start === 0 ? 1 : 0; + for (let i3 = init2; i3 < 100; i3++) { + const index = start + i3; + const id = this.ids[index]; + if (id === -1) { + return index; + } + } + } + return super.next(); + } +} + +// src/lostcity/engine/World.ts +class World35 { + static PLAYERS = 2048; + static NPCS = 8192; + static NORMAL_TICKRATE = 600; + static SHUTDOWN_TICKRATE = 1; + static LOGIN_PINGRATE = 100; + static INV_STOCKRATE = 100; + static AFK_EVENTRATE = 500; + static PLAYER_SAVERATE = 1500; + static SHUTDOWN_TICKS = 24000; + static TIMEOUT_IDLE_TICKS = 75; + static TIMEOUT_LOGOUT_TICKS = 100; + gameMap; + zoneMap; + invs; + newPlayers; + players; + npcs; + zonesTracking; + queue; + lastCycleStats; + cycleStats; + tickRate = World35.NORMAL_TICKRATE; + currentTick = 0; + shutdownTick = -1; + allLastModified = 0; + datLastModified = new Map(); + vars = new Int32Array(); + varsString = []; + devWatcher = null; + devThread = null; + devRebuilding = false; + devMTime = new Map(); + constructor() { + this.gameMap = new GameMap(); + this.zoneMap = new ZoneMap2(); + this.invs = new Set(); + this.newPlayers = new Set(); + this.players = new PlayerList(World35.PLAYERS); + this.npcs = new NpcList(World35.NPCS); + this.zonesTracking = new Map(); + this.queue = new LinkList(); + this.lastCycleStats = new Array(12).fill(0); + this.cycleStats = new Array(12).fill(0); + } + shouldReload(type, client = false) { + if (typeof self !== 'undefined') { + return true; + } else { + const current = Math.max(getModified(`data/pack/server/${type}.dat`), client ? getModified('data/pack/client/config') : 0); + if (!this.datLastModified.has(type)) { + this.datLastModified.set(type, current); + return true; + } + const changed = this.datLastModified.get(type) !== current; + if (changed) { + this.datLastModified.set(type, current); + } + return changed; + } + } + reload() { + let transmitted = false; + if (this.shouldReload('varp', true)) { + VarPlayerType.load('data/pack'); + transmitted = true; + } + if (this.shouldReload('param')) { + ParamType.load('data/pack'); + } + if (this.shouldReload('obj', true)) { + ObjType.load('data/pack'); + transmitted = true; + } + if (this.shouldReload('loc', true)) { + LocType.load('data/pack'); + transmitted = true; + } + if (this.shouldReload('npc', true)) { + NpcType.load('data/pack'); + transmitted = true; + } + if (this.shouldReload('idk', true)) { + IdkType.load('data/pack'); + transmitted = true; + } + if (this.shouldReload('frame_del')) { + SeqFrame.load('data/pack'); + } + if (this.shouldReload('seq', true)) { + SeqType.load('data/pack'); + transmitted = true; + } + if (this.shouldReload('spotanim', true)) { + SpotanimType.load('data/pack'); + transmitted = true; + } + if (this.shouldReload('category')) { + CategoryType.load('data/pack'); + } + if (this.shouldReload('enum')) { + EnumType.load('data/pack'); + } + if (this.shouldReload('struct')) { + StructType.load('data/pack'); + } + if (this.shouldReload('inv')) { + InvType.load('data/pack'); + this.invs.clear(); + for (let i3 = 0; i3 < InvType.count; i3++) { + const inv = InvType.get(i3); + if (inv && inv.scope === InvType.SCOPE_SHARED) { + this.invs.add(Inventory.fromType(i3)); + } + } + } + if (this.shouldReload('mesanim')) { + MesanimType.load('data/pack'); + } + if (this.shouldReload('dbtable')) { + DbTableType.load('data/pack'); + } + if (this.shouldReload('dbrow')) { + DbRowType.load('data/pack'); + } + if (this.shouldReload('hunt')) { + HuntType.load('data/pack'); + } + if (this.shouldReload('varn')) { + VarNpcType.load('data/pack'); + } + if (this.shouldReload('vars')) { + VarSharedType.load('data/pack'); + if (this.vars.length !== VarSharedType.count) { + const old = this.vars; + this.vars = new Int32Array(VarSharedType.count); + for (let i3 = 0; i3 < VarSharedType.count && i3 < old.length; i3++) { + this.vars[i3] = old[i3]; + } + const oldString = this.varsString; + this.varsString = new Array(VarSharedType.count); + for (let i3 = 0; i3 < VarSharedType.count && i3 < old.length; i3++) { + this.varsString[i3] = oldString[i3]; + } + } + } + if (this.shouldReload('interface')) { + Component.load('data/pack'); + transmitted = true; + } + if (this.shouldReload('script')) { + const count = ScriptProvider.load('data/pack'); + if (count === -1) { + this.broadcastMes('There was an issue while reloading scripts.'); + } else { + this.broadcastMes(`Reloaded ${count} scripts.`); + } + } + makeCrcs(); + preloadClient(); + this.allLastModified = getLatestModified('data/pack', '.dat'); + } + async reloadAsync() { + let transmitted = false; + if (this.shouldReload('varp', true)) { + await VarPlayerType.loadAsync('data/pack'); + transmitted = true; + } + if (this.shouldReload('param')) { + await ParamType.loadAsync('data/pack'); + } + if (this.shouldReload('obj', true)) { + await ObjType.loadAsync('data/pack'); + transmitted = true; + } + if (this.shouldReload('loc', true)) { + await LocType.loadAsync('data/pack'); + transmitted = true; + } + if (this.shouldReload('npc', true)) { + await NpcType.loadAsync('data/pack'); + transmitted = true; + } + if (this.shouldReload('idk', true)) { + await IdkType.loadAsync('data/pack'); + transmitted = true; + } + if (this.shouldReload('frame_del')) { + await SeqFrame.loadAsync('data/pack'); + } + if (this.shouldReload('seq', true)) { + await SeqType.loadAsync('data/pack'); + transmitted = true; + } + if (this.shouldReload('spotanim', true)) { + await SpotanimType.loadAsync('data/pack'); + transmitted = true; + } + if (this.shouldReload('category')) { + await CategoryType.loadAsync('data/pack'); + } + if (this.shouldReload('enum')) { + await EnumType.loadAsync('data/pack'); + } + if (this.shouldReload('struct')) { + await StructType.loadAsync('data/pack'); + } + if (this.shouldReload('inv')) { + await InvType.loadAsync('data/pack'); + this.invs.clear(); + for (let i3 = 0; i3 < InvType.count; i3++) { + const inv = InvType.get(i3); + if (inv && inv.scope === InvType.SCOPE_SHARED) { + this.invs.add(Inventory.fromType(i3)); + } + } + } + if (this.shouldReload('mesanim')) { + await MesanimType.loadAsync('data/pack'); + } + if (this.shouldReload('dbtable')) { + await DbTableType.loadAsync('data/pack'); + } + if (this.shouldReload('dbrow')) { + await DbRowType.loadAsync('data/pack'); + } + if (this.shouldReload('hunt')) { + await HuntType.loadAsync('data/pack'); + } + if (this.shouldReload('varn')) { + await VarNpcType.loadAsync('data/pack'); + } + if (this.shouldReload('vars')) { + await VarSharedType.loadAsync('data/pack'); + if (this.vars.length !== VarSharedType.count) { + const old = this.vars; + this.vars = new Int32Array(VarSharedType.count); + for (let i3 = 0; i3 < VarSharedType.count && i3 < old.length; i3++) { + this.vars[i3] = old[i3]; + } + const oldString = this.varsString; + this.varsString = new Array(VarSharedType.count); + for (let i3 = 0; i3 < VarSharedType.count && i3 < old.length; i3++) { + this.varsString[i3] = oldString[i3]; + } + } + } + if (this.shouldReload('interface')) { + await Component.loadAsync('data/pack'); + transmitted = true; + } + if (this.shouldReload('script')) { + const count = await ScriptProvider.loadAsync('data/pack'); + if (count === -1) { + this.broadcastMes('There was an issue while reloading scripts.'); + } else { + this.broadcastMes(`Reloaded ${count} scripts.`); + } + } + await preloadClientAsync(); + } + broadcastMes(message) { + for (const player of this.players) { + player.messageGame(message); + } + } + async start(skipMaps = false, startCycle = true) { + console.log('Starting world...'); + if (typeof self === 'undefined') { + FontType.load('data/pack'); + WordEnc2.load('data/pack'); + this.reload(); + if (!skipMaps) { + this.gameMap.init(this.zoneMap); + } + } else { + await FontType.loadAsync('data/pack'); + await WordEnc2.loadAsync('data/pack'); + await this.reloadAsync(); + if (!skipMaps) { + await this.gameMap.initAsync(this.zoneMap); + } + } + Login_default.loginThread.postMessage({ + type: 'reset' + }); + if (typeof self === 'undefined' && !Environment_default.NODE_PRODUCTION) { + this.startDevWatcher(); + if (Environment_default.BUILD_STARTUP && (shouldBuildFileAny('data/pack/client', 'data/pack/client/lastbuild.pack') || shouldBuildFileAny('data/pack/server', 'data/pack/server/lastbuild.pack'))) { + this.devThread.postMessage({ + type: 'pack' + }); + } + } + if (Environment_default.WEB_PORT === 80) { + console.log(kleur_default.green().bold('World ready') + kleur_default.white().bold(': http://localhost')); + } else { + console.log(kleur_default.green().bold('World ready') + kleur_default.white().bold(': http://localhost:' + Environment_default.WEB_PORT)); + } + if (startCycle) { + await this.cycle(); + } + } + startDevWatcher() { + this.devThread = createWorker('./src/lostcity/server/DevThread.ts'); + this.devThread.on('message', msg => { + if (msg.type === 'done') { + this.devRebuilding = false; + this.reload(); + } + }); + this.devThread.on('exit', () => { + this.devRebuilding = false; + this.stopDevWatcher(); + if (this.shutdownTick === -1) { + this.broadcastMes('Error while rebuilding - see console for more info.'); + this.startDevWatcher(); + } + }); + this.devWatcher = new Watcher('./data/src', { + recursive: true + }); + this.devWatcher.on('add', targetPath => { + if (targetPath.endsWith('.pack')) { + return; + } + const stat = fs29.statSync(targetPath); + this.devMTime.set(targetPath, stat.mtimeMs); + }); + this.devWatcher.on('change', targetPath => { + if (targetPath.endsWith('.pack')) { + return; + } + const stat = fs29.statSync(targetPath); + const known = this.devMTime.get(targetPath); + if (known && known >= stat.mtimeMs) { + return; + } + this.devMTime.set(targetPath, stat.mtimeMs); + if (this.devRebuilding) { + return; + } + console.log('dev:', q.basename(targetPath), 'was edited'); + this.devRebuilding = true; + this.broadcastMes('Rebuilding, please wait...'); + if (!this.devThread) { + this.devThread = createWorker('./src/lostcity/server/DevThread.ts'); + } + this.devThread.postMessage({ + type: 'pack' + }); + }); + } + stopDevWatcher() { + if (this.devWatcher) { + this.devWatcher.close(); + } + if (this.devThread) { + this.devThread.terminate(); + this.devThread = null; + } + } + rebootTimer(duration) { + this.shutdownTick = this.currentTick + duration; + this.stopDevWatcher(); + for (const player of this.players) { + player.write(new UpdateRebootTimer(this.shutdownTick - this.currentTick)); + } + } + async cycle(continueCycle = true) { + const start = Date.now(); + this.processWorld(); + await this.processClientsIn(); + this.processNpcs(); + await this.processPlayers(); + await this.processLogouts(); + await this.processLogins(); + this.processZones(); + this.processMovementDirections(); + await this.processClientsOut(); + this.processCleanup(); + const tick = this.currentTick; + if (tick % World35.LOGIN_PINGRATE === 0) { + this.heartbeat(); + } + if (this.shutdownTick > -1 && tick >= this.shutdownTick) { + await this.processShutdown(); + } + if (tick % World35.PLAYER_SAVERATE === 0 && tick > 0) { + this.savePlayers(); + } + this.currentTick++; + this.cycleStats[WorldStat_default.CYCLE] = Date.now() - start; + this.lastCycleStats[WorldStat_default.CYCLE] = this.cycleStats[WorldStat_default.CYCLE]; + this.lastCycleStats[WorldStat_default.WORLD] = this.cycleStats[WorldStat_default.WORLD]; + this.lastCycleStats[WorldStat_default.CLIENT_IN] = this.cycleStats[WorldStat_default.CLIENT_IN]; + this.lastCycleStats[WorldStat_default.NPC] = this.cycleStats[WorldStat_default.NPC]; + this.lastCycleStats[WorldStat_default.PLAYER] = this.cycleStats[WorldStat_default.PLAYER]; + this.lastCycleStats[WorldStat_default.LOGOUT] = this.cycleStats[WorldStat_default.LOGOUT]; + this.lastCycleStats[WorldStat_default.LOGIN] = this.cycleStats[WorldStat_default.LOGIN]; + this.lastCycleStats[WorldStat_default.ZONE] = this.cycleStats[WorldStat_default.ZONE]; + this.lastCycleStats[WorldStat_default.CLIENT_OUT] = this.cycleStats[WorldStat_default.CLIENT_OUT]; + this.lastCycleStats[WorldStat_default.CLEANUP] = this.cycleStats[WorldStat_default.CLEANUP]; + this.lastCycleStats[WorldStat_default.BANDWIDTH_IN] = this.cycleStats[WorldStat_default.BANDWIDTH_IN]; + this.lastCycleStats[WorldStat_default.BANDWIDTH_OUT] = this.cycleStats[WorldStat_default.BANDWIDTH_OUT]; + if (continueCycle) { + setTimeout(this.cycle.bind(this), this.tickRate - this.cycleStats[WorldStat_default.CYCLE]); + } + } + processWorld() { + const start = Date.now(); + const tick = this.currentTick; + for (let request = this.queue.head(); request; request = this.queue.next()) { + const delay = request.delay--; + if (delay > 0) { + continue; + } + const script = request.script; + try { + const state = ScriptRunner2.execute(script); + request.unlink(); + if (state === ScriptState.SUSPENDED) { + script.activePlayer.activeScript = script; + } else if (state === ScriptState.NPC_SUSPENDED) { + script.activeNpc.activeScript = script; + } else if (state === ScriptState.WORLD_SUSPENDED) { + this.enqueueScript(script, script.popInt()); + } + } catch (err) { + console.error(err); + } + } + if (tick % World35.AFK_EVENTRATE === 0) { + for (const player of this.players) { + player.afkEventReady = Math.random() < (player.zonesAfk() ? 0.1666 : 0.0833); + } + } + for (const npc of this.npcs) { + if (!npc.updateLifeCycle(tick)) { + continue; + } + if (npc.lifecycle === EntityLifeCycle_default.RESPAWN) { + this.addNpc(npc, -1); + } else if (npc.lifecycle === EntityLifeCycle_default.DESPAWN) { + this.removeNpc(npc, -1); + } + } + for (const npc of this.npcs) { + if (!npc.checkLifeCycle(tick) || npc.delayed()) { + continue; + } + if (npc.huntMode !== -1) { + npc.huntAll(); + } + } + this.cycleStats[WorldStat_default.WORLD] = Date.now() - start; + } + async processClientsIn() { + const start = Date.now(); + this.cycleStats[WorldStat_default.BANDWIDTH_IN] = 0; + for (const player of this.players) { + if (!isNetworkPlayer(player)) { + continue; + } + try { + player.decodeIn(); + } catch (err) { + console.error(err); + await this.removePlayer(player); + } + } + for (const player of this.players) { + if (!isNetworkPlayer(player)) { + continue; + } + if (player.userPath.length > 0 || player.opcalled) { + if (player.delayed()) { + player.unsetMapFlag(); + continue; + } + if ((!player.target || player.target instanceof Loc || player.target instanceof Obj) && player.faceEntity !== -1) { + player.faceEntity = -1; + player.mask |= Player2.FACE_ENTITY; + } + if (player.opcalled && (player.userPath.length === 0 || !Environment_default.NODE_CLIENT_ROUTEFINDER)) { + player.pathToTarget(); + continue; + } + player.pathToMoveClick(player.userPath, !Environment_default.NODE_CLIENT_ROUTEFINDER); + } + if (player.target instanceof Player2 && (player.targetOp === ServerTriggerType_default.APPLAYER3 || player.targetOp === ServerTriggerType_default.OPPLAYER3)) { + if (Position.distanceToSW(player, player.target) <= 25) { + player.pathToPathingTarget(); + } else { + player.clearWaypoints(); + } + } + } + this.cycleStats[WorldStat_default.CLIENT_IN] = Date.now() - start; + } + processNpcs() { + const start = Date.now(); + for (const npc of this.npcs) { + if (!npc.checkLifeCycle(this.currentTick)) { + continue; + } + try { + if (npc.delayed()) { + npc.delay--; + } + if (npc.delayed()) { + continue; + } + if (npc.activeScript) { + npc.executeScript(npc.activeScript); + } + if (!npc.checkLifeCycle(this.currentTick)) { + continue; + } + npc.processTimers(); + npc.processQueue(); + npc.processNpcModes(); + npc.validateDistanceWalked(); + } catch (err) { + console.error(err); + this.removeNpc(npc, -1); + } + } + this.cycleStats[WorldStat_default.NPC] = Date.now() - start; + } + async processPlayers() { + const start = Date.now(); + for (const player of this.players) { + try { + player.playtime++; + if (player.delayed()) { + player.delay--; + } + if (player.activeScript && !player.delayed() && player.activeScript.execution === ScriptState.SUSPENDED) { + player.executeScript(player.activeScript, true); + } + player.processQueues(); + player.processTimers(0 /* NORMAL */); + player.processTimers(1 /* SOFT */); + player.processEngineQueue(); + player.processInteraction(); + if ((player.mask & Player2.EXACT_MOVE) == 0) { + player.validateDistanceWalked(); + } + if (this.shutdownTick < this.currentTick) { + if (Environment_default.NODE_SOCKET_TIMEOUT && this.currentTick - player.lastResponse >= World35.TIMEOUT_IDLE_TICKS) { + player.logoutRequested = true; + } + } + if (player.logoutRequested) { + player.closeModal(); + } + } catch (err) { + console.error(err); + await this.removePlayer(player); + } + } + this.cycleStats[WorldStat_default.PLAYER] = Date.now() - start; + } + async processLogouts() { + const start = Date.now(); + for (const player of this.players) { + if (Environment_default.NODE_SOCKET_TIMEOUT && this.currentTick - player.lastResponse >= World35.TIMEOUT_LOGOUT_TICKS) { + player.queue.clear(); + player.weakQueue.clear(); + player.engineQueue.clear(); + player.clearInteraction(); + player.closeModal(); + player.unsetMapFlag(); + player.logoutRequested = true; + player.setVar(VarPlayerType.LASTCOMBAT, 0); + } + if (!player.logoutRequested) { + continue; + } + if (player.queue.head() === null) { + const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.LOGOUT, -1, -1); + if (!script) { + console.error('LOGOUT TRIGGER IS BROKEN!'); + continue; + } + const state = ScriptRunner2.init(script, player); + state.pointerAdd(ScriptPointer_default.ProtectedActivePlayer); + ScriptRunner2.execute(state); + const result = state.popInt(); + if (result === 0) { + player.logoutRequested = false; + } + if (player.logoutRequested) { + await this.removePlayer(player); + } + } else { + player.messageGame('[DEBUG]: Waiting for queue to empty before logging out.'); + } + } + this.cycleStats[WorldStat_default.LOGOUT] = Date.now() - start; + } + async processLogins() { + const start = Date.now(); + player: for (const player of this.newPlayers) { + if (!isNetworkPlayer(player)) { + continue; + } + for (const other of this.players) { + if (player.username !== other.username) { + continue; + } + player.client?.send(LoginResponse.LOGGED_IN); + player.client?.close(); + continue player; + } + let pid; + try { + pid = this.getNextPid(player.client); + } catch (e) { + player.client?.send(LoginResponse.WORLD_FULL); + player.client?.close(); + continue; + } + this.players.set(pid, player); + player.pid = pid; + player.uid = ((Number(player.username37 & 0x1fffffn) << 11) | player.pid) >>> 0; + player.tele = true; + this.getZone(player.x, player.z, player.level).enter(player); + player.onLogin(); + if (this.shutdownTick > -1) { + player.write(new UpdateRebootTimer(this.shutdownTick - this.currentTick)); + } + if (player.client) { + player.client.state = 1; + if (player.staffModLevel >= 2) { + player.client.send(LoginResponse.STAFF_MOD_LEVEL); + } else { + player.client.send(LoginResponse.SUCCESSFUL); + } + } + } + this.newPlayers.clear(); + this.cycleStats[WorldStat_default.LOGIN] = Date.now() - start; + } + processZones() { + const start = Date.now(); + const tick = this.currentTick; + const zones = this.zonesTracking.get(tick); + if (typeof zones !== 'undefined') { + for (const zone of zones) { + zone.tick(tick); + } + } + this.computeSharedEvents(); + this.cycleStats[WorldStat_default.ZONE] = Date.now() - start; + } + processMovementDirections() { + for (const player of this.players) { + player.convertMovementDir(); + } + for (const npc of this.npcs) { + npc.convertMovementDir(); + } + } + async processClientsOut() { + const start = Date.now(); + this.cycleStats[WorldStat_default.BANDWIDTH_OUT] = 0; + for (const player of this.players) { + if (!isNetworkPlayer(player)) { + continue; + } + try { + player.updateMap(); + player.updatePlayers(); + player.updateNpcs(); + player.updateZones(); + player.updateInvs(); + player.updateStats(); + player.updateAfkZones(); + player.encodeOut(); + } catch (err) { + console.error(err); + await this.removePlayer(player); + } + } + this.cycleStats[WorldStat_default.CLIENT_OUT] = Date.now() - start; + } + processCleanup() { + const start = Date.now(); + const tick = this.currentTick; + const zones = this.zonesTracking.get(tick); + if (typeof zones !== 'undefined') { + for (const zone of zones) { + zone.reset(); + } + } + this.zonesTracking.delete(tick); + for (const player of this.players) { + player.resetEntity(false); + for (const inv of player.invs.values()) { + if (!inv) { + continue; + } + inv.update = false; + } + } + for (const npc of this.npcs) { + if (!npc.checkLifeCycle(tick)) { + continue; + } + npc.resetEntity(false); + } + for (const inv of this.invs) { + inv.update = false; + const invType = InvType.get(inv.type); + if (!invType.restock || !invType.stockcount || !invType.stockrate) { + continue; + } + for (let index = 0; index < inv.items.length; index++) { + const item = inv.items[index]; + if (!item) { + continue; + } + if (item.count < invType.stockcount[index] && tick % invType.stockrate[index] === 0) { + inv.add(item?.id, 1, index, true, false, false); + inv.update = true; + continue; + } + if (item.count > invType.stockcount[index] && tick % invType.stockrate[index] === 0) { + inv.remove(item?.id, 1, index, true); + inv.update = true; + continue; + } + if (invType.allstock && !invType.stockcount[index] && tick % World35.INV_STOCKRATE === 0) { + inv.remove(item?.id, 1, index, true); + inv.update = true; + } + } + } + this.cycleStats[WorldStat_default.CLEANUP] = Date.now() - start; + } + heartbeat() { + const players = []; + for (const player of this.players) { + players.push(player.username37); + } + Login_default.loginThread.postMessage({ + type: 'heartbeat', + players + }); + } + async processShutdown() { + const duration = this.currentTick - this.shutdownTick; + const online = this.getTotalPlayers(); + if (online) { + for (const player of this.players) { + player.logoutRequested = true; + if (isNetworkPlayer(player)) { + player.logout(); + if (player.client && duration > 2) { + player.client.close(); + } + } + } + this.npcs.reset(); + if (duration > 2) { + console.log('Super fast shutdown initiated...'); + if (this.tickRate > World35.SHUTDOWN_TICKRATE) { + this.tickRate = World35.SHUTDOWN_TICKRATE; + } + if (duration > World35.SHUTDOWN_TICKS) { + for (const player of this.players) { + await this.removePlayer(player); + } + this.tickRate = World35.NORMAL_TICKRATE; + } + if (!Environment_default.NODE_PRODUCTION) { + process.exit(0); + } + } + } else { + process.exit(0); + } + } + savePlayers() { + if (typeof self === 'undefined') { + for (const player of this.players) { + player.save().release(); + } + } + } + enqueueScript(script, delay = 0) { + this.queue.addTail(new EntityQueueState(script, delay + 1)); + } + getInventory(inv) { + if (inv === -1) { + return null; + } + for (const inventory2 of this.invs) { + if (inventory2.type === inv) { + return inventory2; + } + } + const inventory = Inventory.fromType(inv); + this.invs.add(inventory); + return inventory; + } + getZone(x, z2, level) { + return this.zoneMap.zone(x, z2, level); + } + getZoneIndex(zoneIndex) { + return this.zoneMap.zoneByIndex(zoneIndex); + } + getZoneGrid(level) { + return this.zoneMap.grid(level); + } + computeSharedEvents() { + const zones = new Set(); + for (const player of this.players) { + if (!isNetworkPlayer(player)) { + continue; + } + for (const zone of player.buildArea.loadedZones) { + zones.add(zone); + } + } + for (const zoneIndex of zones) { + this.getZoneIndex(zoneIndex).computeShared(); + } + } + addNpc(npc, duration) { + this.npcs.set(npc.nid, npc); + npc.x = npc.startX; + npc.z = npc.startZ; + const zone = this.getZone(npc.x, npc.z, npc.level); + zone.enter(npc); + switch (npc.blockWalk) { + case BlockWalk_default.NPC: + this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, true); + break; + case BlockWalk_default.ALL: + this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, true); + this.gameMap.changePlayerCollision(npc.width, npc.x, npc.z, npc.level, true); + break; + } + npc.resetEntity(true); + npc.playAnimation(-1, 0); + npc.setLifeCycle(this.currentTick + duration); + } + removeNpc(npc, duration) { + const zone = this.getZone(npc.x, npc.z, npc.level); + zone.leave(npc); + switch (npc.blockWalk) { + case BlockWalk_default.NPC: + this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, false); + break; + case BlockWalk_default.ALL: + this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, false); + this.gameMap.changePlayerCollision(npc.width, npc.x, npc.z, npc.level, false); + break; + } + if (npc.lifecycle === EntityLifeCycle_default.DESPAWN) { + this.npcs.remove(npc.nid); + } else if (npc.lifecycle === EntityLifeCycle_default.RESPAWN) { + npc.setLifeCycle(this.currentTick + duration); + } + } + getLoc(x, z2, level, locId) { + return this.getZone(x, z2, level).getLoc(x, z2, locId); + } + getObj(x, z2, level, objId, receiverId) { + return this.getZone(x, z2, level).getObj(x, z2, objId, receiverId); + } + trackZone(tick, zone) { + let zones; + const active = this.zonesTracking.get(tick); + if (!active) { + zones = new Set(); + } else { + zones = active; + } + zones.add(zone); + this.zonesTracking.set(tick, zones); + } + addLoc(loc, duration) { + const type = LocType.get(loc.type); + if (type.blockwalk) { + this.gameMap.changeLocCollision(loc.shape, loc.angle, type.blockrange, type.length, type.width, type.active, loc.x, loc.z, loc.level, true); + } + const zone = this.getZone(loc.x, loc.z, loc.level); + zone.addLoc(loc); + loc.setLifeCycle(this.currentTick + duration); + this.trackZone(this.currentTick + duration, zone); + this.trackZone(this.currentTick, zone); + } + mergeLoc(loc, player, startCycle, endCycle, south, east, north, west) { + const zone = this.getZone(loc.x, loc.z, loc.level); + zone.mergeLoc(loc, player, startCycle, endCycle, south, east, north, west); + this.trackZone(this.currentTick, zone); + } + animLoc(loc, seq) { + const zone = this.getZone(loc.x, loc.z, loc.level); + zone.animLoc(loc, seq); + this.trackZone(this.currentTick, zone); + } + removeLoc(loc, duration) { + const type = LocType.get(loc.type); + if (type.blockwalk) { + this.gameMap.changeLocCollision(loc.shape, loc.angle, type.blockrange, type.length, type.width, type.active, loc.x, loc.z, loc.level, false); + } + const zone = this.getZone(loc.x, loc.z, loc.level); + zone.removeLoc(loc); + loc.setLifeCycle(this.currentTick + duration); + this.trackZone(this.currentTick + duration, zone); + this.trackZone(this.currentTick, zone); + } + addObj(obj, receiverId, duration) { + const objType = ObjType.get(obj.type); + const existing = this.getObj(obj.x, obj.z, obj.level, obj.type, receiverId); + if (existing && existing.lifecycle === EntityLifeCycle_default.DESPAWN && obj.lifecycle === EntityLifeCycle_default.DESPAWN) { + const nextCount = obj.count + existing.count; + if (objType.stackable && nextCount <= Inventory.STACK_LIMIT) { + this.changeObj(existing, receiverId, nextCount); + return; + } + } + const zone = this.getZone(obj.x, obj.z, obj.level); + zone.addObj(obj, receiverId); + if (receiverId !== -1 && objType.tradeable) { + obj.setLifeCycle(this.currentTick + 100); + this.trackZone(this.currentTick + 100, zone); + this.trackZone(this.currentTick, zone); + obj.receiverId = receiverId; + obj.reveal = duration; + } else { + obj.setLifeCycle(this.currentTick + duration); + this.trackZone(this.currentTick + duration, zone); + this.trackZone(this.currentTick, zone); + } + } + revealObj(obj) { + const duration = obj.reveal; + const zone = this.getZone(obj.x, obj.z, obj.level); + zone.revealObj(obj, obj.receiverId); + obj.setLifeCycle(this.currentTick + duration); + this.trackZone(this.currentTick + duration, zone); + this.trackZone(this.currentTick, zone); + } + changeObj(obj, receiverId, newCount) { + const zone = this.getZone(obj.x, obj.z, obj.level); + zone.changeObj(obj, receiverId, obj.count, newCount); + this.trackZone(this.currentTick, zone); + } + removeObj(obj, duration) { + const zone = this.getZone(obj.x, obj.z, obj.level); + zone.removeObj(obj); + obj.setLifeCycle(this.currentTick + duration); + this.trackZone(this.currentTick + duration, zone); + this.trackZone(this.currentTick, zone); + } + animMap(level, x, z2, spotanim, height, delay) { + const zone = this.getZone(x, z2, level); + zone.animMap(x, z2, spotanim, height, delay); + this.trackZone(this.currentTick, zone); + } + mapProjAnim(level, x, z2, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) { + const zone = this.getZone(x, z2, level); + zone.mapProjAnim(x, z2, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc); + this.trackZone(this.currentTick, zone); + } + async readIn(socket, stream) { + while (stream.available > 0) { + const start = stream.pos; + let opcode = stream.g1(); + if (socket.decryptor) { + opcode = (opcode - socket.decryptor.nextInt()) & 255; + stream.data[start] = opcode; + } + if (typeof ClientProt.byId[opcode] === 'undefined') { + socket.state = -1; + socket.close(); + return; + } + let length = ClientProt.byId[opcode].length; + if (length === -1) { + length = stream.g1(); + } else if (length === -2) { + length = stream.g2(); + } + if (stream.available < length) { + break; + } + stream.pos += length; + socket.inCount[opcode]++; + if (socket.inCount[opcode] > 5) { + continue; + } + const data = new Uint8Array(stream.pos - start); + const pos = stream.pos; + stream.pos = start; + stream.gdata(data, 0, data.length); + stream.pos = pos; + socket.in.set(data, socket.inOffset); + socket.inOffset += stream.pos - start; + } + } + addPlayer(player) { + this.newPlayers.add(player); + } + async removePlayer(player) { + if (player.pid === -1) { + return; + } + player.playerLog('Logging out'); + if (isNetworkPlayer(player)) { + player.logout(); + player.client.close(); + player.client = null; + } + Login_default.logout(player); + } + getPlayer(pid) { + return this.players.get(pid); + } + getPlayerByUid(uid) { + const pid = uid & 2047; + const name37 = (uid >> 11) & 2097151; + const player = this.getPlayer(pid); + if (!player) { + return null; + } + if (Number(player.username37 & 0x1fffffn) !== name37) { + return null; + } + return player; + } + getPlayerByUsername(username) { + const username37 = toBase37(username); + for (const player of this.players) { + if (player.username37 === username37) { + return player; + } + } + for (const player of this.newPlayers) { + if (player.username37 === username37) { + return player; + } + } + return; + } + getTotalPlayers() { + return this.players.count; + } + getTotalNpcs() { + return this.npcs.count; + } + getTotalZones() { + return this.zoneMap.zoneCount(); + } + getTotalLocs() { + return this.zoneMap.locCount(); + } + getTotalObjs() { + return this.zoneMap.objCount(); + } + getNpc(nid) { + return this.npcs.get(nid); + } + getNpcByUid(uid) { + const slot = uid & 65535; + const type = (uid >> 16) & 65535; + const npc = this.getNpc(slot); + if (!npc || npc.type !== type) { + return null; + } + return npc; + } + getNextNid() { + return this.npcs.next(); + } + getNextPid(client = null) { + if (client) { + const ip = client.remoteAddress; + const octets = ip.split('.'); + const start = (parseInt(octets[3]) % 20) * 100; + return this.players.next(true, start); + } + return this.players.next(); + } +} +var World_default = new World35(); + +// src/lostcity/server/WorkerServer.ts +class WorkerServer { + socket = new ClientSocket(self.crypto.randomUUID(), null, '127.0.0.1'); + constructor() {} + start() { + const seed = new Packet(new Uint8Array(4 + 4)); + seed.p4(Math.floor(Math.random() * 4294967295)); + seed.p4(Math.floor(Math.random() * 4294967295)); + this.socket.send(seed.data); + self.onmessage = async e => { + const packet = new Packet(new Uint8Array(e.data)); + switch (e.data.type) { + default: + try { + if (this.socket.state === 1) { + await World_default.readIn(this.socket, packet); + } else { + await Login_default.readIn(this.socket, packet); + } + } catch (err) { + this.socket.close(); + } + break; + } + }; + } +} + +// src/lostcity/worker.ts +await World_default.start(); +var workerServer = new WorkerServer(); +workerServer.start();