UNPKG

brocha

Version:

Universal Brotli decompressor written in 100% TypeScript with zero dependencies. Blazing fast, lightweight, and compatible with any ES2015+ environment.

4 lines 308 kB
{ "version": 3, "sources": ["../../mod.ts", "../../src/internal/primordials.ts", "../../src/internal/tables.ts", "../../src/internal/helpers.ts", "../../src/internal/encoding.ts", "../../src/internal/input.ts", "../../src/errors.ts", "../../src/internal/transforms.ts", "../../src/state.ts", "../../src/decompress.ts"], "sourcesContent": ["export * from \"./src/decompress.ts\";\nexport * from \"./src/types.ts\";\nexport * from \"./src/state.ts\";\nexport * from \"./src/errors.ts\";\n\nexport { default } from \"./src/decompress.ts\";\n", "// deno-lint-ignore-file no-explicit-any\n// @ts-ignore TS9016\n\ndeclare const global: typeof globalThis | undefined;\ndeclare const root: typeof globalThis | undefined;\ndeclare const self: typeof globalThis | undefined;\ndeclare const window: typeof globalThis | undefined;\n\nexport const $global: typeof globalThis = (() => {\n if (typeof globalThis === \"object\" && !!globalThis) {\n return globalThis;\n }\n try {\n return (0, eval)(\"this\");\n } catch {\n if (typeof global === \"object\" && !!global) {\n return global;\n } else if (typeof window === \"object\" && !!window) {\n return window;\n } else if (typeof root === \"object\" && !!root) {\n return root;\n } else if (typeof self === \"object\" && !!self) {\n return self;\n } else if (typeof this === \"object\" && !!this) {\n return this;\n }\n throw {\n message: \"Unable to locate global `this`\",\n toString() {\n return this.message;\n },\n };\n }\n})();\n\nexport type UncurryThis = {\n <T, A extends readonly unknown[], R>(\n fn: (this: T, ...args: A) => R,\n thisArg?: T,\n ): [T] extends [never] ? (thisArg: unknown, ...args: A) => R\n : (thisArg: T, ...args: A) => R;\n};\n\nexport type Uncurry<T, This = void> = T extends\n (this: infer ThisArg, ...args: infer A) => infer R\n ? [This] extends [void] ? (thisArg: ThisArg, ...args: A) => R\n : (thisArg: This, ...args: A) => R\n : T extends (...args: infer A) => infer R\n ? (thisArg: [This] extends [void] ? unknown : This, ...args: A) => R\n : never;\n\nexport type UncurryGetter<T, This = void> = T extends { get(): infer R }\n ? UncurryGetter<R, This>\n : [This] extends [void] ? UncurryGetter<T, unknown>\n : (thisArg: This) => T;\n\nexport type UncurrySetter<T, This = void> = T extends\n { set(value: infer R): void } ? UncurrySetter<R, This>\n : [This] extends [void] ? UncurrySetter<T, unknown>\n : (thisArg: This, value: T) => void;\n\ntype ToValue<T, K extends PropertyKey, U extends boolean = false> = K extends\n keyof T ? Exclude<T[K], undefined> | ([U] extends [true] ? undefined : never)\n : unknown;\n\nexport type TypedArrayConstructor =\n | Int8ArrayConstructor\n | Uint8ArrayConstructor\n | Uint8ClampedArrayConstructor\n | Int16ArrayConstructor\n | Uint16ArrayConstructor\n | Int32ArrayConstructor\n | Uint32ArrayConstructor\n | Float16ArrayConstructor\n | Float32ArrayConstructor\n | Float64ArrayConstructor\n | BigInt64ArrayConstructor\n | BigUint64ArrayConstructor;\n\nexport type TypedArray = TypedArrayConstructor extends\n abstract new (...args: any) => infer T ? T : never;\n\nexport type TypedArrayToStringTag = TypedArray[typeof Symbol.toStringTag];\n\nexport type TypedArrayFromTag<T extends TypedArrayToStringTag> =\n TypedArray extends infer A extends TypedArray\n ? A extends { [Symbol.toStringTag]: T } ? A : never\n : never;\n\nexport const Object: typeof globalThis.Object = $global.Object;\nexport const ObjectGetPrototypeOf = Object.getPrototypeOf;\nexport const ObjectDefineProperty = Object.defineProperty;\nexport const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nexport const ObjectFreeze: typeof Object.freeze = Object.freeze;\n\nconst { bind, call } = $global.Function.prototype;\n\nexport const uncurryThis: UncurryThis = (fn) => {\n const bound = bind.call(call, fn);\n ObjectDefineProperty(bound, \"name\", { value: fn.name });\n return bound;\n};\n\nexport function uncurryGetter<T, K extends keyof T>(\n o: T,\n p: K,\n): UncurryGetter<T[K], T> {\n return uncurryThis(lookupGetter(o, p)) as unknown as UncurryGetter<T[K], T>;\n}\n\nexport function uncurrySetter<T, K extends keyof T>(\n o: T,\n p: K,\n): UncurrySetter<T[K], T> {\n return uncurryThis(lookupSetter(o, p)) as unknown as UncurrySetter<T[K], T>;\n}\n\nexport function lookupGetter<\n T,\n K extends PropertyKey = keyof T,\n U extends boolean = false,\n>(\n o: T,\n p: K,\n _allowUndefined?: U,\n): () => ToValue<T, K, U> {\n return ObjectGetOwnPropertyDescriptor(o, p)?.get ?? (() => undefined);\n}\n\nexport function lookupSetter<\n T,\n K extends PropertyKey = keyof T,\n U extends boolean = false,\n>(\n o: T,\n p: K,\n _allowUndefined?: U,\n): (value: ToValue<T, K, U>) => void {\n return ObjectGetOwnPropertyDescriptor(o, p)?.set ?? (() => undefined);\n}\n\nexport const toString: (self: unknown) => string = uncurryThis(\n Object.prototype.toString,\n);\n\nexport const Error: typeof globalThis.Error = $global.Error;\nexport const TypeError: typeof globalThis.TypeError = $global.TypeError;\nexport const RangeError: typeof globalThis.RangeError = $global.RangeError;\nexport const ReferenceError: typeof globalThis.ReferenceError =\n $global.ReferenceError;\n\nexport const Array: typeof globalThis.Array = $global.Array;\nexport const Symbol: typeof globalThis.Symbol = $global.Symbol;\n\nexport const String: typeof globalThis.String = $global.String;\nexport const StringFromCharCode: typeof String.fromCharCode =\n String.fromCharCode;\nexport const StringPrototype: typeof String.prototype = String.prototype;\nexport const StringPrototypeCharCodeAt: Uncurry<\n typeof String.prototype.charCodeAt,\n string\n> = uncurryThis(StringPrototype.charCodeAt);\nexport const StringPrototypeReplace: Uncurry<\n typeof String.prototype.replace,\n string\n> = uncurryThis(StringPrototype.replace);\nexport const StringPrototypeSlice: Uncurry<\n typeof String.prototype.slice,\n string\n> = uncurryThis(StringPrototype.slice);\nexport const StringPrototypeCodePointAt: Uncurry<\n typeof String.prototype.codePointAt,\n string\n> = uncurryThis(StringPrototype.codePointAt);\nexport const StringPrototypeToLowerCase: Uncurry<\n typeof String.prototype.toLowerCase,\n string\n> = uncurryThis(StringPrototype.toLowerCase);\n\nexport const ArrayBuffer: typeof globalThis.ArrayBuffer = $global.ArrayBuffer;\nexport type ArrayBuffer = InstanceType<typeof ArrayBuffer>;\n\nexport const ArrayBufferIsView: (x: unknown) => x is ArrayBufferView =\n ArrayBuffer.isView;\nexport const ArrayBufferPrototype: ArrayBuffer = ArrayBuffer.prototype;\nexport const ArrayBufferPrototypeGetByteLength: (self: unknown) => number =\n uncurryThis(\n lookupGetter(ArrayBuffer.prototype, \"byteLength\"),\n );\n\nexport const SharedArrayBuffer: typeof globalThis.SharedArrayBuffer =\n $global.SharedArrayBuffer;\nexport type SharedArrayBuffer = globalThis.SharedArrayBuffer;\n\nexport const SharedArrayBufferPrototype: SharedArrayBuffer =\n SharedArrayBuffer.prototype;\nexport const SharedArrayBufferPrototypeGetByteLength: (\n self: unknown,\n) => number = uncurryThis(\n lookupGetter(SharedArrayBuffer.prototype, \"byteLength\"),\n);\n\nexport const Uint8Array: Uint8ArrayConstructor = $global.Uint8Array;\nexport type Uint8Array = globalThis.Uint8Array;\nexport const Uint8ArrayPrototypeSlice: Uncurry<\n typeof Uint8Array.prototype.slice,\n Uint8Array\n> = uncurryThis(Uint8Array.prototype.slice);\n\nexport const Uint8ArrayPrototypeSubarray: Uncurry<\n typeof Uint8Array.prototype.subarray,\n Uint8Array\n> = uncurryThis(Uint8Array.prototype.subarray);\n\nexport const DataView: DataViewConstructor = $global.DataView;\nexport type DataView = globalThis.DataView;\n\nexport const Int16Array: Int16ArrayConstructor = $global.Int16Array;\nexport type Int16Array = globalThis.Int16Array;\nexport const Int16ArrayOf: (...n: number[]) => Int16Array = Int16Array?.of.bind(\n Int16Array,\n);\n\nexport const Int32Array: Int32ArrayConstructor = $global.Int32Array;\nexport type Int32Array = globalThis.Int32Array;\nexport const Int32ArrayOf: (...n: number[]) => Int32Array = Int32Array?.of.bind(\n Int32Array,\n);\n\nexport const Int8Array: Int8ArrayConstructor = $global.Int8Array;\nexport type Int8Array = globalThis.Int8Array;\n\nexport const TypedArray: TypedArrayConstructor = ObjectGetPrototypeOf(\n Uint8Array,\n);\nexport const TypedArrayPrototype: InstanceType<TypedArrayConstructor> =\n TypedArray?.prototype!;\nexport const TypedArrayPrototypeGetToStringTag: (\n this: unknown,\n) =>\n | \"Int8Array\"\n | \"BigUint64Array\"\n | \"Uint8Array\"\n | \"Int16Array\"\n | \"Int32Array\"\n | \"Uint8ClampedArray\"\n | \"Uint16Array\"\n | \"Uint32Array\"\n | \"Float16Array\"\n | \"Float32Array\"\n | \"Float64Array\"\n | \"BigInt64Array\" = lookupGetter(\n TypedArrayPrototype,\n Symbol.toStringTag,\n );\nexport const TypedArrayPrototypeSubarray: Uncurry<\n typeof TypedArrayPrototype.subarray,\n typeof TypedArrayPrototype\n> = uncurryThis(TypedArrayPrototype.subarray as any) as any;\n", "import {\n Int16ArrayOf,\n Int32Array,\n Int32ArrayOf,\n StringPrototypeCharCodeAt,\n} from \"./primordials.ts\";\n\n// #region Offsets, Lengths, and Sizes\n/**\n * Represents the maximum number of symbols in a Huffman table. This is used to\n * calculate the maximum number of bits required to represent a Huffman code.\n * @category Constants\n */\n// deno-fmt-ignore\nexport const MAX_HUFFMAN_TABLE_SIZE: Int32Array = Int32ArrayOf(\n 256, 402, 436, 468, 500, 534, 566, 598, 630, 662, 694, 726, 758, 790, 822,\n 854, 886, 920, 952, 984, 1016, 1048, 1080,\n);\n\n/**\n * Controls the order of the Huffman code lengths.\n * @category Constants\n */\n// deno-fmt-ignore\nexport const CODE_LENGTH_CODE_ORDER: Int32Array = Int32ArrayOf(\n 0x1, 0x2, 0x3, 0x4, 0x0, 0x5, 0x11, 0x6, 0x10, 0x7, 0x8, 0x9,\n 0xA, 0xB,0xC, 0xD, 0xE, 0xF,\n);\n\n/**\n * Index offsets for the distance symbol code lengths.\n * @category Constants\n */\n// deno-fmt-ignore\nexport const DSC_INDEX_OFFSET: Int32Array = Int32ArrayOf(\n 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3,\n);\n\n/**\n * Value offsets for the distance symbol code lengths.\n * @category Constants\n */\n// deno-fmt-ignore\nexport const DSC_VALUE_OFFSET: Int32Array = Int32ArrayOf(\n 0, 0, 0, 0, -1, 1, -2, 2, -3, 3, -1, 1, -2, 2, -3, 3,\n);\n\n/**\n * The fixed Huffman literal code lengths.\n * @category Constants\n */\n// deno-fmt-ignore\nexport const FIXED_TABLE: Int32Array = Int32ArrayOf(\n 0x020000, 0x020004, 0x020003, 0x030002, 0x020000, 0x020004, 0x020003,\n 0x040001, 0x020000, 0x020004, 0x020003, 0x030002, 0x020000, 0x020004,\n 0x020003, 0x040005,\n);\n\n/**\n * Block length offsets for the block types.\n * @category Constants\n */\n// deno-fmt-ignore\nexport const BLOCK_LENGTH_OFFSET: Int32Array = Int32ArrayOf(\n 1, 5, 9, 13, 17, 25, 33, 41, 49, 65, 81, 97, 113, 145, 177, 209, 241, 305,\n 369, 497, 753, 1265, 2289, 4337, 8433, 16625,\n);\n\n/**\n * Represents the number of bits required to represent the block lengths.\n * @category Constants\n */\n// deno-fmt-ignore\nexport const BLOCK_LENGTH_N_BITS: Int32Array = Int32ArrayOf(\n 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x05,\n 0x05, 0x05, 0x05, 0x06, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x18,\n);\n\n/**\n * The number of bits required to represent the insert length.\n * @category Constants\n */\n// deno-fmt-ignore\nexport const INSERT_LENGTH_N_BITS: Int16Array = Int16ArrayOf(\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03,\n 0x04, 0x04, 0x05, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0C, 0x0E, 0x18,\n);\n\n/**\n * The number of bits required to represent the copy length.\n * @category Constants\n */\n// deno-fmt-ignore\nexport const COPY_LENGTH_N_BITS: Int16Array = Int16ArrayOf(\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x02, 0x02,\n 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x18,\n);\n// #endregion Offsets, Lengths, and Sizes\n\n// #region Lookup Tables\nexport const LOOKUP: Int32Array = unpackLookupTable(new Int32Array(2048));\n\nexport const COMMAND_LOOKUP_TABLE: Int16Array = unpackCommandLookupTable(\n new Int16Array(2816),\n);\n\nfunction unpackCommandLookupTable(cmdLookup: Int16Array): Int16Array {\n const insertLengthOffsets = new Int32Array(24);\n const copyLengthOffsets = new Int32Array(24);\n copyLengthOffsets[0] = 2;\n for (let i = 0; i < 23; ++i) {\n insertLengthOffsets[i + 1] = insertLengthOffsets[i] +\n (1 << INSERT_LENGTH_N_BITS[i]);\n copyLengthOffsets[i + 1] = copyLengthOffsets[i] +\n (1 << COPY_LENGTH_N_BITS[i]);\n }\n for (let cmdCode = 0; cmdCode < 704; ++cmdCode) {\n let rangeIdx = cmdCode >>> 6;\n let distanceContextOffset = -4;\n if (rangeIdx >= 2) {\n rangeIdx -= 2;\n distanceContextOffset = 0;\n }\n const insertCode = (((0x29850 >>> (rangeIdx * 2)) & 0x3) << 3) |\n ((cmdCode >>> 3) & 7);\n const copyCode = (((0x26244 >>> (rangeIdx * 2)) & 0x3) << 3) |\n (cmdCode & 7);\n const copyLengthOffset = copyLengthOffsets[copyCode];\n const distanceContext = distanceContextOffset +\n (copyLengthOffset > 4 ? 3 : (copyLengthOffset - 2));\n const index = cmdCode * 4;\n cmdLookup[index] = INSERT_LENGTH_N_BITS[insertCode] |\n (COPY_LENGTH_N_BITS[copyCode] << 8);\n cmdLookup[index + 1] = insertLengthOffsets[insertCode];\n cmdLookup[index + 2] = copyLengthOffsets[copyCode];\n cmdLookup[index + 3] = distanceContext;\n }\n\n return cmdLookup;\n}\n\nfunction unpackLookupTable(lookup: Int32Array): Int32Array {\n const map =\n \" !! ! \\\"#$##%#$&'##(#)#++++++++++((&*'##,---,---,-----,-----,-----&#'###.///.///./////./////./////&#'# \";\n const rle = \"A/* ': & : $ \\x81 @\";\n\n for (let i = 0; i < 256; ++i) {\n lookup[i] = i & 0x3F;\n lookup[512 + i] = i >> 2;\n lookup[1792 + i] = 2 + (i >> 6);\n }\n for (let i = 0; i < 128; ++i) {\n lookup[1024 + i] = 4 * (StringPrototypeCharCodeAt(map, i) - 32);\n }\n for (let i = 0; i < 64; ++i) {\n lookup[1152 + i] = i & 1;\n lookup[1216 + i] = 2 + (i & 1);\n }\n let offset = 1280;\n for (let k = 0; k < 19; ++k) {\n const value = k & 3;\n const rep = rle.charCodeAt(k) - 32;\n for (let i = 0; i < rep; ++i) lookup[offset++] = value;\n }\n for (let i = 0; i < 16; ++i) lookup[1792 + i] = 1, lookup[2032 + i] = 6;\n lookup[1792] = 0, lookup[2047] = 7;\n for (let i = 0; i < 256; ++i) lookup[1536 + i] = lookup[1792 + i] << 3;\n\n return lookup;\n}\n// #endregion Lookup Tables\n\n// #region Huffman table functions\nfunction getNextKey(key: number, len: number): number {\n let step = 1 << (len - 1);\n while ((key & step) !== 0) step = step >> 1;\n return (key & (step - 1)) + step;\n}\n\nfunction replicateValue(\n table: Int32Array,\n offset: number,\n step: number,\n end: number,\n item: number,\n): void {\n let pos = end;\n do {\n pos -= step;\n table[offset + pos] = item;\n } while (pos > 0);\n}\n\nfunction nextTableBitSize(\n count: Int32Array,\n len: number,\n rootBits: number,\n): number {\n let bits = len, left = 1 << (bits - rootBits);\n while (bits < 15) {\n left -= count[bits];\n if (left <= 0) break;\n bits++;\n left <<= 1;\n }\n return bits - rootBits;\n}\n\nexport function buildHuffmanTable(\n tableGroup: Int32Array,\n tableIdx: number,\n rootBits: number,\n codeLengths: Int32Array,\n codeLengthsSize: number,\n): number {\n const tableOffset = tableGroup[tableIdx];\n const sorted = new Int32Array(codeLengthsSize);\n const count = new Int32Array(16), offset = new Int32Array(16);\n\n for (let sym = 0; sym < codeLengthsSize; ++sym) count[codeLengths[sym]]++;\n\n offset[1] = 0;\n for (let len = 1; len < 15; ++len) {\n offset[len + 1] = offset[len] + count[len];\n }\n for (let sym = 0; sym < codeLengthsSize; ++sym) {\n if (codeLengths[sym] !== 0) {\n sorted[offset[codeLengths[sym]]++] = sym;\n }\n }\n let tableBits = rootBits, tableSize = 1 << tableBits, totalSize = tableSize;\n if (offset[15] === 1) {\n for (let k = 0; k < totalSize; ++k) {\n tableGroup[tableOffset + k] = sorted[0];\n }\n return totalSize;\n }\n\n let key = 0, symbol = 0, step = 1;\n for (let len = 1; len <= rootBits; ++len) {\n step <<= 1;\n while (count[len] > 0) {\n replicateValue(\n tableGroup,\n tableOffset + key,\n step,\n tableSize,\n len << 16 | sorted[symbol++],\n );\n key = getNextKey(key, len);\n count[len]--;\n }\n }\n\n const mask = totalSize - 1;\n let low = -1, currentOffset = tableOffset;\n step = 1;\n\n for (let len = rootBits + 1; len <= 15; ++len) {\n step <<= 1;\n\n while (count[len] > 0) {\n if ((key & mask) !== low) {\n currentOffset += tableSize;\n tableBits = nextTableBitSize(count, len, rootBits);\n tableSize = 1 << tableBits;\n totalSize += tableSize;\n low = key & mask;\n tableGroup[tableOffset + low] = (tableBits + rootBits) << 16 |\n (currentOffset - tableOffset - low);\n }\n\n replicateValue(\n tableGroup,\n currentOffset + (key >> rootBits),\n step,\n tableSize,\n (len - rootBits) << 16 | sorted[symbol++],\n );\n\n key = getNextKey(key, len);\n count[len]--;\n }\n }\n\n return totalSize;\n}\n// #endregion Huffman table functions\n", "export function log2floor(i: number): number {\n let result = -1, step = 16, v = i;\n while (step > 0) {\n const next = v >>> step;\n if (next !== 0) result += step, v = next;\n step = step >> 1;\n }\n return result + v;\n}\n\nexport function min(a: number, b: number): number {\n return a < b ? a : b;\n}\n", "// import \"jsr:@nick/utf8@0.3.3/shim\";\nimport {\n ArrayBufferIsView,\n Int8Array,\n StringPrototypeCharCodeAt,\n type TypedArray,\n TypedArrayPrototypeGetToStringTag,\n type TypedArrayToStringTag,\n Uint8Array,\n} from \"./primordials.ts\";\n\nexport function isTypedArray<T extends TypedArrayToStringTag>(\n it: unknown,\n type?: T | undefined,\n): it is Extract<TypedArray, { [Symbol.toStringTag]: T }> {\n try {\n const tag = TypedArrayPrototypeGetToStringTag?.call(it);\n return typeof tag !== \"undefined\" && (type == null || tag === type);\n } catch {\n return false;\n }\n}\n\nexport function toUsAsciiBytes(src: string): Int8Array {\n const n = src.length;\n const result = new Int8Array(n);\n for (let i = 0; i < n; ++i) result[i] = StringPrototypeCharCodeAt(src, i);\n return result;\n}\n\nexport function toInt8Array(bs: string | BufferSource): Int8Array {\n if (typeof bs === \"string\") return toUsAsciiBytes(bs);\n if (isTypedArray(bs, \"Int8Array\")) return bs;\n if (ArrayBufferIsView(bs)) {\n const { buffer, byteOffset, byteLength } = bs;\n return new Int8Array(buffer, byteOffset, byteLength);\n }\n return new Int8Array(bs);\n}\n\nexport function toUint8Array(bs: string | BufferSource): Uint8Array {\n if (typeof bs === \"string\") bs = new TextEncoder().encode(bs);\n if (isTypedArray(bs, \"Uint8Array\")) return bs;\n if (ArrayBufferIsView(bs)) {\n const { buffer, byteOffset, byteLength } = bs;\n return new Uint8Array(buffer, byteOffset, byteLength);\n }\n return new Uint8Array(bs);\n}\n", "import { Int8Array } from \"./primordials.ts\";\nimport { toInt8Array } from \"./encoding.ts\";\n\n/**\n * Represents a stream of input data, either as a string or binary data buffer.\n *\n * All input types are converted to an `Int8Array` byte buffer prior to being\n * processed by the decompression algorithm.\n */\nexport class InputStream {\n data: Int8Array = new Int8Array(0);\n\n constructor(data: string | BufferSource, public offset = 0) {\n if (data) this.data = toInt8Array(data);\n }\n}\n", "// deno-lint-ignore-file no-explicit-any ban-types\nimport { BrotliErrorCode, BrotliResultCode } from \"./internal/constants.ts\";\nimport { Error, TypeError } from \"./internal/primordials.ts\";\n\n// #region BrotliDecoderError\n\n/**\n * Used to resolve a human-readable error name from a numeric error code.\n *\n * @category Errors\n * @tags Utility\n */\nexport type BrotliErrorName<K extends BrotliErrorCode = BrotliErrorCode> =\n & string\n & keyof {\n [\n P in keyof typeof BrotliErrorCode as P extends string\n ? typeof BrotliErrorCode[P] extends K ? P : never\n : never\n ]: P;\n }\n & {};\n\n/**\n * Represents the options for a Brotli decoder error.\n *\n * @category Errors\n * @tags Options\n */\nexport interface BrotliErrorOptions<\n K extends BrotliErrorCode = BrotliErrorCode,\n> extends ErrorOptions {\n code?: K | undefined;\n kind?: BrotliErrorName<K> | undefined;\n name?: string | undefined;\n message?: string | undefined;\n cause?: unknown;\n}\n\n/**\n * Represents a Brotli decoder error's JSON representation.\n *\n * @category Errors\n * @tags JSON\n */\nexport interface BrotliErrorJson<K extends BrotliErrorCode = BrotliErrorCode> {\n code: K;\n kind: BrotliErrorName<K>;\n name: string;\n message: string;\n cause?: unknown;\n stack?: string | undefined;\n}\n\n/**\n * Represents a Brotli decoder error.\n *\n * @category Errors\n * @abstract\n */\nexport abstract class BrotliDecoderError<\n K extends BrotliErrorCode = BrotliErrorCode.UNKNOWN,\n> extends Error {\n static readonly prefix = \"BROTLI_DECODER_ERROR\";\n\n abstract readonly code: K;\n abstract readonly kind: BrotliErrorName<K>;\n override readonly message!: string;\n readonly options: BrotliErrorOptions<K> = {};\n\n constructor(\n message?: string | null,\n options?: BrotliErrorOptions<K> | null,\n ) {\n if (new.target === BrotliDecoderError) {\n throw new TypeError(\n \"Abstract class BrotliDecoderError cannot be instantiated directly.\",\n );\n }\n const { cause, message: msg } = options ??= {};\n super(message ?? msg ?? cause + \"\", { cause });\n this.options = options;\n this.message = options.message ??= this.message ?? cause + \"\";\n // @ts-ignore abstract member assignment in constructor\n this.code = options.code ??= this.code ?? BrotliErrorCode.UNKNOWN;\n // @ts-ignore abstract member assignment in constructor\n this.kind = options.kind ??= this.kind ?? \"UNKNOWN\";\n }\n\n override get name(): `${typeof BrotliDecoderError.prefix}_${BrotliErrorName<\n K\n >}` {\n return `${BrotliDecoderError.prefix}_${this.kind}` as const;\n }\n\n override get cause(): string | Error | undefined {\n return (super.cause ?? this.options.cause) as string | Error;\n }\n\n toJSON(): BrotliErrorJson<K> {\n const { code, name, kind, message, cause, stack } = this;\n return { code, kind, name, message, cause, stack };\n }\n}\n\n/**\n * Represents an unknown error.\n * @category Errors\n */\nexport class BrotliDecoderUnknownError extends BrotliDecoderError<\n BrotliErrorCode.UNKNOWN\n> {\n readonly code = BrotliErrorCode.UNKNOWN;\n readonly kind = \"UNKNOWN\";\n override readonly message = \"Unknown error occurred.\";\n}\n\n/**\n * Represents an unreachable code error.\n * @category Errors\n */\nexport class BrotliDecoderUnreachableError extends BrotliDecoderError<\n BrotliErrorCode.UNREACHABLE\n> {\n readonly code = BrotliErrorCode.UNREACHABLE;\n readonly kind = \"UNREACHABLE\";\n override readonly message = \"Unreachable code reached.\";\n}\n\n/**\n * Represents an error when allocating block kind trees.\n * @category Errors\n */\nexport class BrotliDecoderAllocBlockTypeTreesError extends BrotliDecoderError<\n BrotliErrorCode.ALLOC_BLOCK_TYPE_TREES\n> {\n readonly code = BrotliErrorCode.ALLOC_BLOCK_TYPE_TREES;\n readonly kind = \"ALLOC_BLOCK_TYPE_TREES\";\n override readonly message = \"Failed to allocate block kind trees.\";\n}\n\n/**\n * Represents an error when allocating ring buffer 2.\n * @category Errors\n */\nexport class BrotliDecoderAllocRingBuffer2Error extends BrotliDecoderError<\n BrotliErrorCode.ALLOC_RING_BUFFER_2\n> {\n readonly code = BrotliErrorCode.ALLOC_RING_BUFFER_2;\n readonly kind = \"ALLOC_RING_BUFFER_2\";\n override readonly message = \"Failed to allocate ring buffer 2.\";\n}\n\n/**\n * Represents an error when allocating ring buffer 1.\n * @category Errors\n */\nexport class BrotliDecoderAllocRingBuffer1Error extends BrotliDecoderError<\n BrotliErrorCode.ALLOC_RING_BUFFER_1\n> {\n readonly code = BrotliErrorCode.ALLOC_RING_BUFFER_1;\n readonly kind = \"ALLOC_RING_BUFFER_1\";\n override readonly message = \"Failed to allocate ring buffer 1.\";\n}\n\n/**\n * Represents an error when allocating context map.\n * @category Errors\n */\nexport class BrotliDecoderAllocContextMapError extends BrotliDecoderError<\n BrotliErrorCode.ALLOC_CONTEXT_MAP\n> {\n readonly code = BrotliErrorCode.ALLOC_CONTEXT_MAP;\n readonly kind = \"ALLOC_CONTEXT_MAP\";\n override readonly message = \"Failed to allocate context map.\";\n}\n\n/**\n * Represents an error when allocating tree groups.\n * @category Errors\n */\nexport class BrotliDecoderAllocTreeGroupsError extends BrotliDecoderError<\n BrotliErrorCode.ALLOC_TREE_GROUPS\n> {\n readonly code = BrotliErrorCode.ALLOC_TREE_GROUPS;\n readonly kind = \"ALLOC_TREE_GROUPS\";\n override readonly message = \"Failed to allocate tree groups.\";\n}\n\n/**\n * Represents an error when allocating context modes.\n * @category Errors\n */\nexport class BrotliDecoderAllocContextModesError extends BrotliDecoderError<\n BrotliErrorCode.ALLOC_CONTEXT_MODES\n> {\n readonly code = BrotliErrorCode.ALLOC_CONTEXT_MODES;\n readonly kind = \"ALLOC_CONTEXT_MODES\";\n override readonly message = \"Failed to allocate context modes.\";\n}\n\n/**\n * Represents an error due to invalid arguments.\n * @category Errors\n */\nexport class BrotliDecoderInvalidArgumentsError extends BrotliDecoderError<\n BrotliErrorCode.INVALID_ARGUMENTS\n> {\n readonly code = BrotliErrorCode.INVALID_ARGUMENTS;\n readonly kind = \"INVALID_ARGUMENTS\";\n override readonly message = \"Invalid arguments.\";\n}\n\n/**\n * Represents an error when the dictionary is not set.\n * @category Errors\n */\nexport class BrotliDecoderDictionaryNotSetError extends BrotliDecoderError<\n BrotliErrorCode.DICTIONARY_NOT_SET\n> {\n readonly code = BrotliErrorCode.DICTIONARY_NOT_SET;\n readonly kind = \"DICTIONARY_NOT_SET\";\n override readonly message = \"Dictionary not set.\";\n}\n\n/**\n * Represents an error due to invalid distance.\n * @category Errors\n */\nexport class BrotliDecoderDistanceError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_DISTANCE\n> {\n readonly code = BrotliErrorCode.FORMAT_DISTANCE;\n readonly kind = \"FORMAT_DISTANCE\";\n override readonly message = \"Invalid distance found.\";\n}\n\n/**\n * Represents an error due to invalid padding bits in the last metablock.\n * @category Errors\n */\nexport class BrotliDecoderPadding2Error extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_PADDING_2\n> {\n readonly code = BrotliErrorCode.FORMAT_PADDING_2;\n readonly kind = \"FORMAT_PADDING_2\";\n override readonly message =\n \"Invalid padding bits found in the last metablock.\";\n}\n\n/**\n * Represents an error due to invalid padding bits.\n * @category Errors\n */\nexport class BrotliDecoderPadding1Error extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_PADDING_1\n> {\n readonly code = BrotliErrorCode.FORMAT_PADDING_1;\n readonly kind = \"FORMAT_PADDING_1\";\n override readonly message = \"Invalid padding bits found.\";\n}\n\n/**\n * Represents an error due to invalid window size.\n * @category Errors\n */\nexport class BrotliDecoderWindowBitsError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_WINDOW_BITS\n> {\n readonly code = BrotliErrorCode.FORMAT_WINDOW_BITS;\n readonly kind = \"FORMAT_WINDOW_BITS\";\n override readonly message = \"Invalid window size found.\";\n}\n\n/**\n * Represents an error due to invalid dictionary size or distance.\n * @category Errors\n */\nexport class BrotliDecoderDictionaryError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_DICTIONARY\n> {\n readonly code = BrotliErrorCode.FORMAT_DICTIONARY;\n readonly kind = \"FORMAT_DICTIONARY\";\n override readonly message = \"Invalid dictionary size or distance found.\";\n}\n\n/**\n * Represents an error due to a reserved transform.\n * @category Errors\n */\nexport class BrotliDecoderTransformError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_TRANSFORM\n> {\n readonly code = BrotliErrorCode.FORMAT_TRANSFORM;\n readonly kind = \"FORMAT_TRANSFORM\";\n override readonly message = \"Reserved transform found.\";\n}\n\n/**\n * Represents an error due to block length being too long.\n * @category Errors\n */\nexport class BrotliDecoderBlockLength2Error extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_BLOCK_LENGTH_2\n> {\n readonly code = BrotliErrorCode.FORMAT_BLOCK_LENGTH_2;\n readonly kind = \"FORMAT_BLOCK_LENGTH_2\";\n override readonly message = \"Block length is too long.\";\n}\n\n/**\n * Represents an error due to block length being too short.\n * @category Errors\n */\nexport class BrotliDecoderBlockLength1Error extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_BLOCK_LENGTH_1\n> {\n readonly code = BrotliErrorCode.FORMAT_BLOCK_LENGTH_1;\n readonly kind = \"FORMAT_BLOCK_LENGTH_1\";\n override readonly message = \"Block length is too short.\";\n}\n\n/**\n * Represents an error due to context map repeat being too long.\n * @category Errors\n */\nexport class BrotliDecoderContextMapRepeatError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_CONTEXT_MAP_REPEAT\n> {\n readonly code = BrotliErrorCode.FORMAT_CONTEXT_MAP_REPEAT;\n readonly kind = \"FORMAT_CONTEXT_MAP_REPEAT\";\n override readonly message = \"Context map repeat is too long.\";\n}\n\n/**\n * Represents an error due to distance code being too far back for the huffman code.\n * @category Errors\n */\nexport class BrotliDecoderHuffmanSpaceError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_HUFFMAN_SPACE\n> {\n readonly code = BrotliErrorCode.FORMAT_HUFFMAN_SPACE;\n readonly kind = \"FORMAT_HUFFMAN_SPACE\";\n override readonly message =\n \"Distance code is too far back for the huffman code.\";\n}\n\n/**\n * Represents an error due to distance code being too far back.\n * @category Errors\n */\nexport class BrotliDecoderClSpaceError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_CL_SPACE\n> {\n readonly code = BrotliErrorCode.FORMAT_CL_SPACE;\n readonly kind = \"FORMAT_CL_SPACE\";\n override readonly message = \"Distance code is too far back.\";\n}\n\n/**\n * Represents an error due to duplicate simple Huffman symbols.\n * @category Errors\n */\nexport class BrotliDecoderSimpleHuffmanSameError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_SIMPLE_HUFFMAN_SAME\n> {\n readonly code = BrotliErrorCode.FORMAT_SIMPLE_HUFFMAN_SAME;\n readonly kind = \"FORMAT_SIMPLE_HUFFMAN_SAME\";\n override readonly message = \"Duplicate simple Huffman symbols.\";\n}\n\n/**\n * Represents an error due to simple Huffman code alphabet error.\n * @category Errors\n */\nexport class BrotliDecoderSimpleHuffmanAlphabetError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_SIMPLE_HUFFMAN_ALPHABET\n> {\n readonly code = BrotliErrorCode.FORMAT_SIMPLE_HUFFMAN_ALPHABET;\n readonly kind = \"FORMAT_SIMPLE_HUFFMAN_ALPHABET\";\n override readonly message = \"Simple Huffman code alphabet error.\";\n}\n\n/**\n * Represents an error due to invalid meta-block nibble.\n * @category Errors\n */\nexport class BrotliDecoderExuberantMetaNibbleError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_EXUBERANT_META_NIBBLE\n> {\n readonly code = BrotliErrorCode.FORMAT_EXUBERANT_META_NIBBLE;\n readonly kind = \"FORMAT_EXUBERANT_META_NIBBLE\";\n override readonly message = \"Invalid meta-block nibble.\";\n}\n\n/**\n * Represents an error due to reserved format.\n * @category Errors\n */\nexport class BrotliDecoderReservedError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_RESERVED\n> {\n readonly code = BrotliErrorCode.FORMAT_RESERVED;\n readonly kind = \"FORMAT_RESERVED\";\n override readonly message = \"Reserved format error.\";\n}\n\n/**\n * Represents an error due to invalid nibble.\n * @category Errors\n */\nexport class BrotliDecoderExuberantNibbleError extends BrotliDecoderError<\n BrotliErrorCode.FORMAT_EXUBERANT_NIBBLE\n> {\n readonly code = BrotliErrorCode.FORMAT_EXUBERANT_NIBBLE;\n readonly kind = \"FORMAT_EXUBERANT_NIBBLE\";\n override readonly message = \"Invalid nibble.\";\n}\n\n/**\n * Represents a no error state.\n * @category Errors\n */\nexport class BrotliDecoderNoError extends BrotliDecoderError<\n BrotliErrorCode.NO_ERROR\n> {\n readonly code = BrotliErrorCode.NO_ERROR;\n readonly kind = \"NO_ERROR\";\n override readonly message = \"No error occurred.\";\n}\n// #endregion BrotliDecoderError\n\n// #region BrotliDecoderResult\n\n/**\n * Represents the result of a Brotli decoder operation.\n *\n * - `ERROR`: The decompression operation failed.\n * - `SUCCESS`: The decompression operation was successful.\n * - `NEEDS_MORE_INPUT`: The decoder needs more input data to continue.\n * - `NEEDS_MORE_OUTPUT`: The decoder needs more output space to continue.\n *\n * @category Results\n * @abstract\n */\nexport abstract class BrotliDecoderResult<\n K extends BrotliResultCode = BrotliResultCode,\n> extends Error {\n abstract readonly code: K;\n abstract readonly kind: string;\n override readonly message: string = \"\";\n\n constructor(message?: string | null) {\n if (new.target === BrotliDecoderResult) {\n throw new TypeError(\n \"Abstract class BrotliDecoderResult cannot be instantiated directly.\",\n );\n }\n super(message || \"\");\n this.message = message || this.message || \"\";\n }\n\n toJSON(): {\n readonly type: \"BrotliDecoderResult\";\n code: K;\n kind: string;\n message: string;\n } {\n const { code, kind, message } = this;\n const type = \"BrotliDecoderResult\";\n return { type, code, kind, message };\n }\n}\n\n/**\n * Represents the result of a failed Brotli decoder operation.\n *\n * @category Results\n * @tags Error\n */\nexport class BrotliDecoderErrorResult<\n T extends BrotliDecoderError<BrotliErrorCode> = BrotliDecoderError<any>,\n> extends BrotliDecoderResult<BrotliResultCode.ERROR> {\n readonly code = BrotliResultCode.ERROR;\n readonly kind = \"BROTLI_DECODER_RESULT_ERROR\";\n\n constructor(readonly error: T) {\n super(`Decompression failed: ${error.message}`);\n }\n}\n\n/**\n * Represents the result of a successful Brotli decoder operation.\n *\n * @category Results\n * @tags Success\n */\nexport class BrotliDecoderSuccessResult\n extends BrotliDecoderResult<BrotliResultCode.SUCCESS> {\n readonly code = BrotliResultCode.SUCCESS;\n readonly kind = \"BROTLI_DECODER_RESULT_SUCCESS\";\n override readonly message = \"Decompression successful.\";\n}\n\n/**\n * Represents the result of a Brotli decoder operation that needs more input data.\n *\n * @category Results\n * @tags NeedsMoreInput, streaming\n */\nexport class BrotliDecoderNeedsMoreInputResult\n extends BrotliDecoderResult<BrotliResultCode.NEEDS_MORE_INPUT> {\n readonly code = BrotliResultCode.NEEDS_MORE_INPUT;\n readonly kind = \"BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT\";\n override readonly message = \"Decoder needs more input data to continue.\";\n}\n\n/**\n * Represents the result of a Brotli decoder operation that needs more output space.\n *\n * @category Results\n * @tags NeedsMoreOutput, streaming\n */\nexport class BrotliDecoderNeedsMoreOutputResult\n extends BrotliDecoderResult<BrotliResultCode.NEEDS_MORE_OUTPUT> {\n readonly code = BrotliResultCode.NEEDS_MORE_OUTPUT;\n readonly kind = \"BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT\";\n override readonly message = \"Decoder needs more output space to continue.\";\n}\n\n// #endregion BrotliDecoderResult\n", "import { BrotliDecoderTransformError } from \"../errors.ts\";\nimport { Int16Array, Int32Array, Int8Array } from \"./primordials.ts\";\n\n/**\n * Represents the transforms used by the Brotli decoder to decompress data.\n *\n * @internal\n */\nexport class Transforms {\n readonly triplets: Int32Array = new Int32Array(0);\n readonly prefixSuffixStorage: Int8Array = new Int8Array(0);\n readonly prefixSuffixHeads: Int32Array = new Int32Array(0);\n readonly params: Int16Array = new Int16Array(0);\n\n constructor(\n readonly numTransforms: number,\n readonly prefixSuffixLen: number,\n readonly prefixSuffixCount: number,\n ) {\n this.numTransforms = numTransforms;\n this.triplets = new Int32Array(numTransforms * 3);\n this.params = new Int16Array(numTransforms);\n this.prefixSuffixStorage = new Int8Array(prefixSuffixLen);\n this.prefixSuffixHeads = new Int32Array(prefixSuffixCount + 1);\n }\n\n unpack(\n prefixSuffixSrc: string,\n transformsSrc: string,\n ): this {\n const expectedLen = this.prefixSuffixLen + this.prefixSuffixCount;\n const n = prefixSuffixSrc.length;\n if (n !== expectedLen) {\n throw new BrotliDecoderTransformError(\n `PrefixSuffix length mismatch: ${n} != ${expectedLen} expected`,\n );\n }\n\n let index = 1, j = 0;\n for (let i = 0; i < n; ++i) {\n const c = prefixSuffixSrc.charCodeAt(i);\n if (c === 35) {\n this.prefixSuffixHeads[index++] = j;\n } else {\n this.prefixSuffixStorage[j++] = c;\n }\n }\n\n if (transformsSrc.length !== this.triplets.length) {\n throw new BrotliDecoderTransformError(\n `transformsSrc length mismatch: ${transformsSrc.length} != ${this.triplets.length} expected`,\n );\n }\n\n for (let i = 0; i < this.triplets.length; ++i) {\n this.triplets[i] = transformsSrc.charCodeAt(i) - 32;\n }\n\n return this;\n }\n\n transformDictionaryWord(\n dst: Int8Array,\n dstOffset: number,\n src: Int8Array,\n srcOffset: number,\n wordLen: number,\n transformIndex: number,\n ): number {\n let offset = dstOffset;\n const transformOffset = 3 * transformIndex;\n const prefixIdx = this.triplets[transformOffset];\n const transform = this.triplets[transformOffset + 1];\n const suffixIdx = this.triplets[transformOffset + 2];\n const prefixEnd = this.prefixSuffixHeads[prefixIdx + 1];\n const suffixEnd = this.prefixSuffixHeads[suffixIdx + 1];\n\n let prefix = this.prefixSuffixHeads[prefixIdx];\n let suffix = this.prefixSuffixHeads[suffixIdx];\n\n let omitFirst = transform - 11, omitLast = transform;\n if (omitFirst < 1 || omitFirst > 9) omitFirst = 0;\n if (omitLast < 1 || omitLast > 9) omitLast = 0;\n\n while (prefix !== prefixEnd) {\n dst[offset++] = this.prefixSuffixStorage[prefix++];\n }\n\n let len = wordLen;\n if (omitFirst > len) omitFirst = len;\n let dictOffset = srcOffset + omitFirst;\n\n for (let i = len -= omitFirst + omitLast; i > 0; i--) {\n dst[offset++] = src[dictOffset++];\n }\n if (transform === 10 || transform === 11) {\n let upperOffset = offset - len;\n if (transform === 10) len = 1;\n while (len > 0) {\n const c0 = dst[upperOffset] & 0xFF;\n if (c0 < 0xC0) {\n if (c0 >= 97 && c0 <= 122) {\n dst[upperOffset] = dst[upperOffset] ^ 32;\n }\n upperOffset += 1;\n len -= 1;\n } else if (c0 < 0xE0) {\n dst[upperOffset + 1] = dst[upperOffset + 1] ^ 32;\n upperOffset += 2;\n len -= 2;\n } else {\n dst[upperOffset + 2] = dst[upperOffset + 2] ^ 5;\n upperOffset += 3;\n len -= 3;\n }\n }\n } else if (transform === 21 || transform === 22) {\n let shift = offset - len;\n const param = this.params[transformIndex];\n let scalar = (param & 0x7FFF) + (0x1000000 - (param & 0x8000));\n while (len > 0) {\n let step = 1;\n const c0 = dst[shift] & 0xFF;\n if (c0 < 0x80) {\n scalar += c0;\n dst[shift] = scalar & 0x7F;\n } else if (c0 < 0xC0) {\n /* ignore */\n } else if (c0 < 0xE0) {\n if (len >= 2) {\n const c1 = dst[shift + 1];\n scalar += (c1 & 0x3F) | ((c0 & 0x1F) << 6);\n dst[shift] = 0xC0 | ((scalar >> 6) & 0x1F);\n dst[shift + 1] = (c1 & 0xC0) | (scalar & 0x3F);\n step = 2;\n } else {\n step = len;\n }\n } else if (c0 < 0xF0) {\n if (len >= 3) {\n const c1 = dst[shift + 1];\n const c2 = dst[shift + 2];\n scalar += (c2 & 0x3F) | ((c1 & 0x3F) << 6) | ((c0 & 0x0F) << 12);\n dst[shift] = 0xE0 | ((scalar >> 12) & 0x0F);\n dst[shift + 1] = (c1 & 0xC0) | ((scalar >> 6) & 0x3F);\n dst[shift + 2] = (c2 & 0xC0) | (scalar & 0x3F);\n step = 3;\n } else {\n step = len;\n }\n } else if (c0 < 0xF8) {\n if (len >= 4) {\n const c1 = dst[shift + 1], c2 = dst[shift + 2], c3 = dst[shift + 3];\n scalar += (c3 & 0x3F) | ((c2 & 0x3F) << 6) | ((c1 & 0x3F) << 12) |\n ((c0 & 0x07) << 18);\n dst[shift] = 0xF0 | ((scalar >> 18) & 0x07);\n dst[shift + 1] = (c1 & 0xC0) | ((scalar >> 12) & 0x3F);\n dst[shift + 2] = (c2 & 0xC0) | ((scalar >> 6) & 0x3F);\n dst[shift + 3] = (c3 & 0xC0) | (scalar & 0x3F);\n step = 4;\n } else {\n step = len;\n }\n }\n shift += step;\n len -= step;\n if (transform === 21) len = 0;\n }\n }\n while (suffix !== suffixEnd) {\n dst[offset++] = this.prefixSuffixStorage[suffix++];\n }\n return offset - dstOffset;\n }\n}\n", "import {\n BLOCK_LENGTH_N_BITS,\n BLOCK_LENGTH_OFFSET,\n CODE_LENGTH_CODE_ORDER,\n COMMAND_LOOKUP_TABLE,\n DSC_INDEX_OFFSET,\n DSC_VALUE_OFFSET,\n FIXED_TABLE,\n LOOKUP,\n MAX_HUFFMAN_TABLE_SIZE,\n} from \"./internal/tables.ts\";\nimport { CHUNK_SIZE } from \"./internal/constants.ts\";\nimport {\n Array,\n ArrayBufferIsView,\n ArrayBufferPrototypeGetByteLength,\n Int16Array,\n Int32Array,\n Int8Array,\n SharedArrayBufferPrototypeGetByteLength,\n StringPrototypeCharCodeAt,\n Uint8Array,\n} from \"./internal/primordials.ts\";\nimport { log2floor } from \"./internal/helpers.ts\";\nimport { InputStream } from \"./internal/input.ts\";\nimport { isTypedArray, toUsAsciiBytes } from \"./internal/encoding.ts\";\nimport { Transforms } from \"./internal/transforms.ts\";\nimport { buildHuffmanTable } from \"./internal/tables.ts\";\nimport {\n BrotliDecoderAllocBlockTypeTreesError,\n // BrotliDecoderUnknownError,\n // BrotliDecoderPadding2Error,\n // BrotliDecoderAllocRingBuffer2Error,\n BrotliDecoderAllocContextMapError,\n BrotliDecoderAllocContextModesError,\n BrotliDecoderAllocRingBuffer1Error,\n BrotliDecoderAllocTreeGroupsError,\n BrotliDecoderBlockLength1Error,\n BrotliDecoderBlockLength2Error,\n BrotliDecoderClSpaceError,\n BrotliDecoderContextMapRepeatError,\n BrotliDecoderDictionaryError,\n BrotliDecoderDictionaryNotSetError,\n BrotliDecoderDistanceError,\n BrotliDecoderExuberantMetaNibbleError,\n BrotliDecoderExuberantNibbleError,\n BrotliDecoderHuffmanSpaceError,\n BrotliDecoderInvalidArgumentsError,\n BrotliDecoderNeedsMoreInputResult,\n BrotliDecoderNeedsMoreOutputResult,\n BrotliDecoderPadding1Error,\n BrotliDecoderReservedError,\n BrotliDecoderSimpleHuffmanAlphabetError,\n BrotliDecoderSimpleHuffmanSameError,\n BrotliDecoderTransformError,\n BrotliDecoderUnreachableError,\n BrotliDecoderWindowBitsError,\n} from \"./errors.ts\";\n\n/**\n * The core of the Brotli decompression algorithm, implemented as a stateful\n * class that can be used to decompress multiple chunks of data in sequence.\n *\n * This is used internally by the {@linkcode decompress} function, but can also\n * be used directly to decompress data in a streaming fashion. It's a low-level\n * API that provides fine-grained control over the decompression process, so\n * it's not as user-friendly as the top-level function.\n */\nexport class State {\n static #initialized = false;\n static #dictionaryData = new Int8Array(0);\n static #transforms: Transforms; // initialized in the static block below\n static readonly #offsets = new Int32Array(32);\n static readonly #sizeBits = new Int32Array(32);\n\n /**\n * The input stream object that is being used to read the compressed data.\n * This can be useful for checking the current offset into the input data, or\n * for reading the input data directly. It can also be used to implement\n * custom streaming input sources.\n */\n readonly input: InputStream = new InputStream(new Int8Array(0));\n /**\n * The total number of bytes that have been decompressed so far. When the\n * decompression job is complete, this value will represent the total length\n * of the decompressed data.\n */\n totalOutput: number = 0;\n // deno-fmt-ignore\n /** @internal */ outputUsed: number = 0;\n /** @internal */ outputOffset: number = 0;\n /** @internal */ outputLength: number = 0;\n /** @internal */ expectedTotalSize: number = 0;\n /** @internal */ runningState: number = 0;\n /** @internal */ nextRunningState: number = 0;\n /** @internal */ chunks: Int8Array[] = [];\n /** @internal */ byteBuffer: Int8Array = new Int8Array(0);\n /** @internal */ output: Int8Array = new Int8Array(0);\n /** @internal */ ringBuffer: Int8Array = new Int8Array(0);\n /** @internal */ contextModes: Int8Array = new Int8Array(0);\n /** @internal */ contextMap: Int8Array = new Int8Array(0);\n /** @internal */ distContextMap: Int8Array = new Int8Array(0);\n /** @internal */ distExtraBits: Int8Array = new Int8Array(0);\n /** @internal */ shortBuffer: Int16Array = new Int16Array(0);\n /** @internal */ rings: Int32Array = new Int32Array(0);\n /** @internal */ blockTrees: Int32Array = new Int32Array(0);\n /** @internal */ commandTreeGroup: Int32Array = new Int32Array(0);\n /** @internal */ distanceTreeGroup: Int32Array = new Int32Array(0);\n /** @internal */ literalTreeGroup: Int32Array = new Int32Array(0);\n /** @internal */ distOffset: Int32Array = new Int32Array(0);\n /** @internal */ bitOffset: number = 0;\n /** @internal */ halfOffset: number = 0;\n /** @internal */ accumulator32: number = 0;\n /** @internal */ tailBytes: number = 0;\n /** @internal */ endOfStreamReached: number = 0;\n /** @internal */ inputEnd: number = 0;\n /** @internal */ isUncompressed: number = 0;\n /** @internal */ isMetadata: number = 0;\n /** @internal */ isEager: number = 0;\n /** @internal */ isLargeWindow: number = 0;\n /** @internal */ numLiteralBlockTypes: number = 0;\n /** @internal */ numCommandBlockTypes: number = 0;\n /** @internal */ numDistanceBlockTypes: number = 0;\n /** @internal */ trivialLiteralContext: number = 0;\n /** @internal */ literalTreeIdx: number = 0;\n /** @internal */ commandTreeIdx: number = 0;\n /** @internal */ pos: number = 0;\n /** @internal */ j: number = 0;\n /** @internal */ contextMapSlice: number = 0;\n /** @internal */ contextLookupOffset1: number = 0;\n /** @internal */ contextLookupOffset2: number = 0;\n /** @internal */ numDirectDistanceCodes: number = 0;\n /** @internal */ insertLength: number = 0;\n /** @internal */ copyLength: number = 0;\n /** @internal */ metaBlockLength: number = 0;\n /** @internal */ commandBlockLength: number = 0;\n /** @internal */ literalBlockLength: number = 0;\n /** @internal */ distanceBlockLength: number = 0;\n /** @internal */ distContextMapSlice: number = 0;\n /** @internal */ distanceCode: number = 0;\n /** @internal */ distancePostfixBits: number = 0;\n /** @internal */ distance: number = 0;\n /** @internal */ distRbIdx: number = 0;\n /** @internal */ maxDistance: number = 0;\n /** @internal */ maxBackwardDistance: number = 0;\n /** @internal */ maxRingBufferSize: number = 0;\n /** @internal */ ringBufferSize: number = 0;\n /** @internal */ ringBufferBytesWritten: number = 0;\n /** @internal */ ringBufferBytesReady: number = 0;\n /** @internal */ cdNumChunks: number = 0;\n /** @internal */ cdTotalSize: number = 0;\n /** @internal */ cdBrIndex: number = 0;\n /** @internal */ cdBrOffset: number = 0;\n /** @internal */ cdBrLength: number = 0;\n /** @internal */ cdBrCopied: number = 0;\n /** @internal */ cdChunks: Int8Array[] = [];\n /** @internal */ cdChunkOffsets: Int32Array = new Int32Array(0);\n /** @internal */ cdBlockBits = 0;\n /** @internal */ cdBlockMap: Int8Array = new Int8Array(0);\n\n /**\n * Creates a new `State` instance, optionally with a custom dictionary, and\n * initializes the decompression job. The input data can be provided as a\n * string or a `BufferSource` object, and the dictionary can be provided as\n * a string, `BufferSource`, or `null` to use the default dictionary.\n *\n * This is the core of the Brotli decompression algorithm.\n */\n constructor(\n bytes?: BufferSource,\n dict?: BufferSource | null,\n ) {\n if (!dict && !State.initialized) {\n State.initializeDefaultDictionary();\n State.#initialized = true;\n }\n this.ringBuffer = new Int8Array(0);\n this.rings = new Int32Array(10);\n this.rings[0] = 16;\n this.rings[1] = 15;\n this.rings[2] = 11;\n this.rings[3] = 4;\n if (bytes) this.input = new InputStream(bytes);\n this.init();\n if (dict) this.attachDictionaryChunk(dict);\n }\n\n /**\n * Decompresses a Brotli-compressed input source (either from a string or