@k67/kaitai-struct-ts 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/errors.ts","../src/utils/encoding.ts","../src/stream/KaitaiStream.ts","../src/parser/schema.ts","../src/parser/KsyParser.ts","../src/interpreter/Context.ts","../src/expression/Token.ts","../src/expression/Lexer.ts","../src/expression/AST.ts","../src/expression/Parser.ts","../src/expression/Evaluator.ts","../src/expression/index.ts","../src/interpreter/TypeInterpreter.ts","../src/index.ts"],"sourcesContent":["/**\n * @fileoverview Custom error classes for Kaitai Struct parsing and validation\n * @module utils/errors\n * @author Fabiano Pinto\n * @license MIT\n */\n\n/**\n * Base error class for all Kaitai Struct errors.\n * All custom errors in this library extend from this class.\n *\n * @class KaitaiError\n * @extends Error\n * @example\n * ```typescript\n * throw new KaitaiError('Something went wrong', 42)\n * ```\n */\nexport class KaitaiError extends Error {\n constructor(\n message: string,\n public position?: number\n ) {\n super(message)\n this.name = 'KaitaiError'\n Object.setPrototypeOf(this, KaitaiError.prototype)\n }\n}\n\n/**\n * Error thrown when validation fails.\n * Used when parsed data doesn't match expected constraints.\n *\n * @class ValidationError\n * @extends KaitaiError\n * @example\n * ```typescript\n * throw new ValidationError('Magic bytes mismatch', 0)\n * ```\n */\nexport class ValidationError extends KaitaiError {\n constructor(message: string, position?: number) {\n super(message, position)\n this.name = 'ValidationError'\n Object.setPrototypeOf(this, ValidationError.prototype)\n }\n}\n\n/**\n * Error thrown when parsing fails.\n * Used for general parsing errors that don't fit other categories.\n *\n * @class ParseError\n * @extends KaitaiError\n * @example\n * ```typescript\n * throw new ParseError('Invalid format structure', 100)\n * ```\n */\nexport class ParseError extends KaitaiError {\n constructor(message: string, position?: number) {\n super(message, position)\n this.name = 'ParseError'\n Object.setPrototypeOf(this, ParseError.prototype)\n }\n}\n\n/**\n * Error thrown when end of stream is reached unexpectedly.\n * Indicates an attempt to read beyond available data.\n *\n * @class EOFError\n * @extends KaitaiError\n * @example\n * ```typescript\n * throw new EOFError('Unexpected end of stream', 1024)\n * ```\n */\nexport class EOFError extends KaitaiError {\n constructor(message: string = 'Unexpected end of stream', position?: number) {\n super(message, position)\n this.name = 'EOFError'\n Object.setPrototypeOf(this, EOFError.prototype)\n }\n}\n\n/**\n * Error thrown when a required feature is not yet implemented.\n * Used during development to mark incomplete functionality.\n *\n * @class NotImplementedError\n * @extends KaitaiError\n * @example\n * ```typescript\n * throw new NotImplementedError('Custom processing')\n * ```\n */\nexport class NotImplementedError extends KaitaiError {\n constructor(feature: string) {\n super(`Feature not yet implemented: ${feature}`)\n this.name = 'NotImplementedError'\n Object.setPrototypeOf(this, NotImplementedError.prototype)\n }\n}\n","/**\n * @fileoverview String encoding and decoding utilities for binary data\n * @module utils/encoding\n * @author Fabiano Pinto\n * @license MIT\n */\n\n/**\n * Decode bytes to string using specified encoding.\n * Supports UTF-8, ASCII, Latin-1, UTF-16LE, and UTF-16BE.\n * Falls back to TextDecoder for other encodings if available.\n *\n * @param bytes - Byte array to decode\n * @param encoding - Character encoding name (e.g., 'UTF-8', 'ASCII')\n * @returns Decoded string\n * @throws {Error} If encoding is not supported\n * @example\n * ```typescript\n * const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f])\n * const str = decodeString(bytes, 'UTF-8') // \"Hello\"\n * ```\n */\nexport function decodeString(bytes: Uint8Array, encoding: string): string {\n // Normalize encoding name\n const normalizedEncoding = encoding.toLowerCase().replace(/[-_]/g, '')\n\n // Handle common encodings\n switch (normalizedEncoding) {\n case 'utf8':\n case 'utf-8':\n return decodeUtf8(bytes)\n\n case 'ascii':\n case 'usascii':\n return decodeAscii(bytes)\n\n case 'utf16':\n case 'utf16le':\n case 'utf-16le':\n return decodeUtf16Le(bytes)\n\n case 'utf16be':\n case 'utf-16be':\n return decodeUtf16Be(bytes)\n\n case 'latin1':\n case 'iso88591':\n case 'iso-8859-1':\n return decodeLatin1(bytes)\n\n default:\n // Try using TextDecoder if available (browser/modern Node.js)\n // eslint-disable-next-line no-undef\n if (typeof TextDecoder !== 'undefined') {\n try {\n // eslint-disable-next-line no-undef\n return new TextDecoder(encoding).decode(bytes)\n } catch {\n throw new Error(`Unsupported encoding: ${encoding}`)\n }\n }\n throw new Error(`Unsupported encoding: ${encoding}`)\n }\n}\n\n/**\n * Decode UTF-8 bytes to string.\n * Handles 1-4 byte UTF-8 sequences including surrogate pairs.\n *\n * @param bytes - UTF-8 encoded byte array\n * @returns Decoded string\n * @private\n */\nfunction decodeUtf8(bytes: Uint8Array): string {\n // eslint-disable-next-line no-undef\n if (typeof TextDecoder !== 'undefined') {\n // eslint-disable-next-line no-undef\n return new TextDecoder('utf-8').decode(bytes)\n }\n\n // Fallback implementation\n let result = ''\n let i = 0\n\n while (i < bytes.length) {\n const byte1 = bytes[i++]\n\n if (byte1 < 0x80) {\n // 1-byte character (ASCII)\n result += String.fromCharCode(byte1)\n } else if (byte1 < 0xe0) {\n // 2-byte character\n const byte2 = bytes[i++]\n result += String.fromCharCode(((byte1 & 0x1f) << 6) | (byte2 & 0x3f))\n } else if (byte1 < 0xf0) {\n // 3-byte character\n const byte2 = bytes[i++]\n const byte3 = bytes[i++]\n result += String.fromCharCode(\n ((byte1 & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f)\n )\n } else {\n // 4-byte character (surrogate pair)\n const byte2 = bytes[i++]\n const byte3 = bytes[i++]\n const byte4 = bytes[i++]\n let codePoint =\n ((byte1 & 0x07) << 18) |\n ((byte2 & 0x3f) << 12) |\n ((byte3 & 0x3f) << 6) |\n (byte4 & 0x3f)\n codePoint -= 0x10000\n result += String.fromCharCode(\n 0xd800 + (codePoint >> 10),\n 0xdc00 + (codePoint & 0x3ff)\n )\n }\n }\n\n return result\n}\n\n/**\n * Decode ASCII bytes to string.\n * Only uses the lower 7 bits of each byte.\n *\n * @param bytes - ASCII encoded byte array\n * @returns Decoded string\n * @private\n */\nfunction decodeAscii(bytes: Uint8Array): string {\n let result = ''\n for (let i = 0; i < bytes.length; i++) {\n result += String.fromCharCode(bytes[i] & 0x7f)\n }\n return result\n}\n\n/**\n * Decode Latin-1 (ISO-8859-1) bytes to string.\n * Each byte directly maps to a Unicode code point.\n *\n * @param bytes - Latin-1 encoded byte array\n * @returns Decoded string\n * @private\n */\nfunction decodeLatin1(bytes: Uint8Array): string {\n let result = ''\n for (let i = 0; i < bytes.length; i++) {\n result += String.fromCharCode(bytes[i])\n }\n return result\n}\n\n/**\n * Decode UTF-16 Little Endian bytes to string.\n * Reads 2 bytes per character in little-endian order.\n *\n * @param bytes - UTF-16LE encoded byte array\n * @returns Decoded string\n * @private\n */\nfunction decodeUtf16Le(bytes: Uint8Array): string {\n // eslint-disable-next-line no-undef\n if (typeof TextDecoder !== 'undefined') {\n // eslint-disable-next-line no-undef\n return new TextDecoder('utf-16le').decode(bytes)\n }\n\n let result = ''\n for (let i = 0; i < bytes.length; i += 2) {\n const charCode = bytes[i] | (bytes[i + 1] << 8)\n result += String.fromCharCode(charCode)\n }\n return result\n}\n\n/**\n * Decode UTF-16 Big Endian bytes to string.\n * Reads 2 bytes per character in big-endian order.\n *\n * @param bytes - UTF-16BE encoded byte array\n * @returns Decoded string\n * @private\n */\nfunction decodeUtf16Be(bytes: Uint8Array): string {\n // eslint-disable-next-line no-undef\n if (typeof TextDecoder !== 'undefined') {\n // eslint-disable-next-line no-undef\n return new TextDecoder('utf-16be').decode(bytes)\n }\n\n let result = ''\n for (let i = 0; i < bytes.length; i += 2) {\n const charCode = (bytes[i] << 8) | bytes[i + 1]\n result += String.fromCharCode(charCode)\n }\n return result\n}\n","/**\n * @fileoverview Binary stream reader for Kaitai Struct\n * @module stream/KaitaiStream\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { EOFError } from '../utils/errors'\nimport { decodeString } from '../utils/encoding'\n\n/**\n * KaitaiStream provides methods for reading binary data with proper type handling\n * and endianness support. It's the core class for parsing binary formats.\n *\n * Supports reading:\n * - Unsigned integers (u1, u2, u4, u8) in both little and big endian\n * - Signed integers (s1, s2, s4, s8) in both little and big endian\n * - Floating point numbers (f4, f8) in both little and big endian\n * - Byte arrays (fixed length, until terminator, or all remaining)\n * - Strings with various encodings\n * - Bit-level data\n *\n * @class KaitaiStream\n * @example\n * ```typescript\n * const buffer = new Uint8Array([0x01, 0x02, 0x03, 0x04])\n * const stream = new KaitaiStream(buffer)\n *\n * const byte = stream.readU1() // Read 1 byte\n * const word = stream.readU2le() // Read 2 bytes little-endian\n * const str = stream.readStr(5, 'UTF-8') // Read 5-byte string\n * ```\n */\nexport class KaitaiStream {\n private buffer: Uint8Array\n private view: DataView\n private _pos: number = 0\n private _bits: number = 0\n private _bitsLeft: number = 0\n\n /**\n * Create a new KaitaiStream from a buffer\n * @param buffer - ArrayBuffer or Uint8Array containing the binary data\n */\n constructor(buffer: ArrayBuffer | Uint8Array) {\n if (buffer instanceof ArrayBuffer) {\n this.buffer = new Uint8Array(buffer)\n this.view = new DataView(buffer)\n } else {\n this.buffer = buffer\n this.view = new DataView(\n buffer.buffer,\n buffer.byteOffset,\n buffer.byteLength\n )\n }\n }\n\n /**\n * Current position in the stream\n */\n get pos(): number {\n return this._pos\n }\n\n set pos(value: number) {\n this._pos = value\n this._bitsLeft = 0 // Reset bit reading when seeking\n }\n\n /**\n * Total size of the stream in bytes\n */\n get size(): number {\n return this.buffer.length\n }\n\n /**\n * Check if we've reached the end of the stream\n */\n isEof(): boolean {\n return this._pos >= this.buffer.length\n }\n\n /**\n * Seek to a specific position in the stream\n * @param pos - Position to seek to\n */\n seek(pos: number): void {\n if (pos < 0 || pos > this.buffer.length) {\n throw new Error(`Invalid seek position: ${pos}`)\n }\n this.pos = pos\n }\n\n /**\n * Ensure we have enough bytes available\n * @param count - Number of bytes needed\n */\n private ensureBytes(count: number): void {\n if (this._pos + count > this.buffer.length) {\n throw new EOFError(\n `Requested ${count} bytes at position ${this._pos}, but only ${\n this.buffer.length - this._pos\n } bytes available`,\n this._pos\n )\n }\n }\n\n // ==================== Unsigned Integers ====================\n\n /**\n * Read 1-byte unsigned integer (0 to 255)\n */\n readU1(): number {\n this.ensureBytes(1)\n return this.buffer[this._pos++]\n }\n\n /**\n * Read 2-byte unsigned integer, little-endian\n */\n readU2le(): number {\n this.ensureBytes(2)\n const value = this.view.getUint16(this._pos, true)\n this._pos += 2\n return value\n }\n\n /**\n * Read 2-byte unsigned integer, big-endian\n */\n readU2be(): number {\n this.ensureBytes(2)\n const value = this.view.getUint16(this._pos, false)\n this._pos += 2\n return value\n }\n\n /**\n * Read 4-byte unsigned integer, little-endian\n */\n readU4le(): number {\n this.ensureBytes(4)\n const value = this.view.getUint32(this._pos, true)\n this._pos += 4\n return value\n }\n\n /**\n * Read 4-byte unsigned integer, big-endian\n */\n readU4be(): number {\n this.ensureBytes(4)\n const value = this.view.getUint32(this._pos, false)\n this._pos += 4\n return value\n }\n\n /**\n * Read 8-byte unsigned integer, little-endian\n * Returns BigInt for values > Number.MAX_SAFE_INTEGER\n */\n readU8le(): bigint {\n this.ensureBytes(8)\n const value = this.view.getBigUint64(this._pos, true)\n this._pos += 8\n return value\n }\n\n /**\n * Read 8-byte unsigned integer, big-endian\n * Returns BigInt for values > Number.MAX_SAFE_INTEGER\n */\n readU8be(): bigint {\n this.ensureBytes(8)\n const value = this.view.getBigUint64(this._pos, false)\n this._pos += 8\n return value\n }\n\n // ==================== Signed Integers ====================\n\n /**\n * Read 1-byte signed integer (-128 to 127)\n */\n readS1(): number {\n this.ensureBytes(1)\n return this.view.getInt8(this._pos++)\n }\n\n /**\n * Read 2-byte signed integer, little-endian\n */\n readS2le(): number {\n this.ensureBytes(2)\n const value = this.view.getInt16(this._pos, true)\n this._pos += 2\n return value\n }\n\n /**\n * Read 2-byte signed integer, big-endian\n */\n readS2be(): number {\n this.ensureBytes(2)\n const value = this.view.getInt16(this._pos, false)\n this._pos += 2\n return value\n }\n\n /**\n * Read 4-byte signed integer, little-endian\n */\n readS4le(): number {\n this.ensureBytes(4)\n const value = this.view.getInt32(this._pos, true)\n this._pos += 4\n return value\n }\n\n /**\n * Read 4-byte signed integer, big-endian\n */\n readS4be(): number {\n this.ensureBytes(4)\n const value = this.view.getInt32(this._pos, false)\n this._pos += 4\n return value\n }\n\n /**\n * Read 8-byte signed integer, little-endian\n * Returns BigInt for values outside Number.MAX_SAFE_INTEGER range\n */\n readS8le(): bigint {\n this.ensureBytes(8)\n const value = this.view.getBigInt64(this._pos, true)\n this._pos += 8\n return value\n }\n\n /**\n * Read 8-byte signed integer, big-endian\n * Returns BigInt for values outside Number.MAX_SAFE_INTEGER range\n */\n readS8be(): bigint {\n this.ensureBytes(8)\n const value = this.view.getBigInt64(this._pos, false)\n this._pos += 8\n return value\n }\n\n // ==================== Floating Point ====================\n\n /**\n * Read 4-byte IEEE 754 single-precision float, little-endian\n */\n readF4le(): number {\n this.ensureBytes(4)\n const value = this.view.getFloat32(this._pos, true)\n this._pos += 4\n return value\n }\n\n /**\n * Read 4-byte IEEE 754 single-precision float, big-endian\n */\n readF4be(): number {\n this.ensureBytes(4)\n const value = this.view.getFloat32(this._pos, false)\n this._pos += 4\n return value\n }\n\n /**\n * Read 8-byte IEEE 754 double-precision float, little-endian\n */\n readF8le(): number {\n this.ensureBytes(8)\n const value = this.view.getFloat64(this._pos, true)\n this._pos += 8\n return value\n }\n\n /**\n * Read 8-byte IEEE 754 double-precision float, big-endian\n */\n readF8be(): number {\n this.ensureBytes(8)\n const value = this.view.getFloat64(this._pos, false)\n this._pos += 8\n return value\n }\n\n // ==================== Byte Arrays ====================\n\n /**\n * Read a fixed number of bytes\n * @param length - Number of bytes to read\n */\n readBytes(length: number): Uint8Array {\n this.ensureBytes(length)\n const bytes = this.buffer.slice(this._pos, this._pos + length)\n this._pos += length\n return bytes\n }\n\n /**\n * Read all remaining bytes until end of stream\n */\n readBytesFull(): Uint8Array {\n const bytes = this.buffer.slice(this._pos)\n this._pos = this.buffer.length\n return bytes\n }\n\n /**\n * Read bytes until a terminator byte is found\n * @param term - Terminator byte value\n * @param include - Include terminator in result\n * @param consume - Consume terminator from stream\n * @param eosError - Throw error if EOS reached before terminator\n */\n readBytesterm(\n term: number,\n include: boolean = false,\n consume: boolean = true,\n eosError: boolean = true\n ): Uint8Array {\n const start = this._pos\n let end = start\n\n // Find terminator\n while (end < this.buffer.length && this.buffer[end] !== term) {\n end++\n }\n\n // Check if we found the terminator\n const foundTerm = end < this.buffer.length\n\n if (!foundTerm && eosError) {\n throw new EOFError(\n `Terminator byte ${term} not found before end of stream`,\n this._pos\n )\n }\n\n // Extract bytes\n const includeEnd = include && foundTerm ? end + 1 : end\n const bytes = this.buffer.slice(start, includeEnd)\n\n // Update position\n if (foundTerm && consume) {\n this._pos = end + 1\n } else {\n this._pos = end\n }\n\n return bytes\n }\n\n // ==================== Strings ====================\n\n /**\n * Read a fixed-length string\n * @param length - Number of bytes to read\n * @param encoding - Character encoding (default: UTF-8)\n */\n readStr(length: number, encoding: string = 'UTF-8'): string {\n const bytes = this.readBytes(length)\n return decodeString(bytes, encoding)\n }\n\n /**\n * Read a null-terminated string\n * @param encoding - Character encoding (default: UTF-8)\n * @param term - Terminator byte (default: 0)\n * @param include - Include terminator in result\n * @param consume - Consume terminator from stream\n * @param eosError - Throw error if EOS reached before terminator\n */\n readStrz(\n encoding: string = 'UTF-8',\n term: number = 0,\n include: boolean = false,\n consume: boolean = true,\n eosError: boolean = true\n ): string {\n const bytes = this.readBytesterm(term, include, consume, eosError)\n return decodeString(bytes, encoding)\n }\n\n // ==================== Bit-level Reading ====================\n\n /**\n * Align bit reading to byte boundary\n */\n alignToByte(): void {\n this._bitsLeft = 0\n }\n\n /**\n * Read specified number of bits as unsigned integer (big-endian)\n * @param n - Number of bits to read (1-64)\n */\n readBitsIntBe(n: number): bigint {\n if (n < 1 || n > 64) {\n throw new Error(`Invalid bit count: ${n}. Must be between 1 and 64`)\n }\n\n let result = 0n\n\n for (let bitsNeeded = n; bitsNeeded > 0; ) {\n if (this._bitsLeft === 0) {\n this._bits = this.readU1()\n this._bitsLeft = 8\n }\n\n const bitsToRead = Math.min(bitsNeeded, this._bitsLeft)\n const mask = (1 << bitsToRead) - 1\n const shift = this._bitsLeft - bitsToRead\n\n result =\n (result << BigInt(bitsToRead)) | BigInt((this._bits >> shift) & mask)\n\n this._bitsLeft -= bitsToRead\n bitsNeeded -= bitsToRead\n }\n\n return result\n }\n\n /**\n * Read specified number of bits as unsigned integer (little-endian)\n * @param n - Number of bits to read (1-64)\n */\n readBitsIntLe(n: number): bigint {\n if (n < 1 || n > 64) {\n throw new Error(`Invalid bit count: ${n}. Must be between 1 and 64`)\n }\n\n let result = 0n\n let bitPos = 0\n\n for (let bitsNeeded = n; bitsNeeded > 0; ) {\n if (this._bitsLeft === 0) {\n this._bits = this.readU1()\n this._bitsLeft = 8\n }\n\n const bitsToRead = Math.min(bitsNeeded, this._bitsLeft)\n const mask = (1 << bitsToRead) - 1\n\n result |= BigInt(this._bits & mask) << BigInt(bitPos)\n\n this._bits >>= bitsToRead\n this._bitsLeft -= bitsToRead\n bitsNeeded -= bitsToRead\n bitPos += bitsToRead\n }\n\n return result\n }\n\n // ==================== Utility Methods ====================\n\n /**\n * Get the underlying buffer\n */\n getBuffer(): Uint8Array {\n return this.buffer\n }\n\n /**\n * Create a substream from current position with specified size\n * @param size - Size of the substream in bytes\n */\n substream(size: number): KaitaiStream {\n this.ensureBytes(size)\n const subBuffer = this.buffer.slice(this._pos, this._pos + size)\n this._pos += size\n return new KaitaiStream(subBuffer)\n }\n}\n","/**\n * @fileoverview Type definitions for Kaitai Struct YAML schema (.ksy files)\n * @module parser/schema\n * @author Fabiano Pinto\n * @license MIT\n */\n\n/**\n * Root schema definition for a Kaitai Struct format.\n * Represents a complete .ksy file structure.\n *\n * @interface KsySchema\n * @example\n * ```typescript\n * const schema: KsySchema = {\n * meta: {\n * id: 'my_format',\n * endian: 'le'\n * },\n * seq: [\n * { id: 'magic', contents: [0x4D, 0x5A] },\n * { id: 'version', type: 'u2' }\n * ]\n * }\n * ```\n */\nexport interface KsySchema {\n /** Metadata about the format */\n meta: MetaSpec\n\n /** Sequential attributes (fields read in order) */\n seq?: AttributeSpec[]\n\n /** Named instances (lazy-evaluated fields) */\n instances?: Record<string, InstanceSpec>\n\n /** Nested type definitions */\n types?: Record<string, KsySchema>\n\n /** Enum definitions (named integer constants) */\n enums?: Record<string, EnumSpec>\n\n /** Documentation for this type */\n doc?: string\n\n /** Reference to documentation */\n 'doc-ref'?: string | string[]\n\n /** Parameters for parametric types */\n params?: ParamSpec[]\n}\n\n/**\n * Metadata section of a Kaitai Struct schema.\n * Contains information about the format itself.\n *\n * @interface MetaSpec\n */\nexport interface MetaSpec {\n /** Identifier for this format (required) */\n id: string\n\n /** Title/name of the format */\n title?: string\n\n /** Application that uses this format */\n application?: string | string[]\n\n /** File extension(s) for this format */\n 'file-extension'?: string | string[]\n\n /** MIME type(s) for this format */\n xref?: Record<string, string | string[]>\n\n /** License for the format specification */\n license?: string\n\n /** KS compatibility version */\n 'ks-version'?: string | number\n\n /** Debug mode flag */\n 'ks-debug'?: boolean\n\n /** Opaque types flag */\n 'ks-opaque-types'?: boolean\n\n /** Default endianness for the format */\n endian?: Endianness | EndianExpression\n\n /** Default encoding for strings */\n encoding?: string\n\n /** Imported type definitions */\n imports?: string[]\n\n /** Documentation */\n doc?: string\n\n /** Reference to documentation */\n 'doc-ref'?: string | string[]\n}\n\n/**\n * Endianness specification.\n */\nexport type Endianness = 'le' | 'be'\n\n/**\n * Expression-based endianness (switch on expression).\n *\n * @interface EndianExpression\n */\nexport interface EndianExpression {\n /** Expression to evaluate */\n 'switch-on': string\n\n /** Cases mapping values to endianness */\n cases: Record<string, Endianness>\n}\n\n/**\n * Attribute specification for sequential fields.\n * Describes how to read a single field from the stream.\n *\n * @interface AttributeSpec\n */\nexport interface AttributeSpec {\n /** Field identifier (name) */\n id?: string\n\n /** Data type to read */\n type?: string | SwitchType\n\n /** Arguments for parametric types */\n 'type-args'?: Array<string | number | boolean>\n\n /** Size of the field (in bytes or expression) */\n size?: number | string\n\n /** Size until specific byte value */\n 'size-eos'?: boolean\n\n /** Repeat specification */\n repeat?: RepeatSpec\n\n /** Number of repetitions (for repeat: expr) */\n 'repeat-expr'?: string | number\n\n /** Condition for repetition (for repeat: until) */\n 'repeat-until'?: string\n\n /** Conditional parsing */\n if?: string\n\n /** Expected contents (validation) */\n contents?: number[] | string\n\n /** String encoding */\n encoding?: string\n\n /** Pad right to alignment */\n 'pad-right'?: number\n\n /** Terminator byte for strings/arrays */\n terminator?: number\n\n /** Include terminator in result */\n include?: boolean\n\n /** Consume terminator from stream */\n consume?: boolean\n\n /** Throw error if terminator not found */\n 'eos-error'?: boolean\n\n /** Enum type name */\n enum?: string\n\n /** Absolute position to seek to */\n pos?: number | string\n\n /** Custom I/O stream */\n io?: string\n\n /** Processing directive (compression, encryption, etc.) */\n process?: string | ProcessSpec\n\n /** Documentation */\n doc?: string\n\n /** Reference to documentation */\n 'doc-ref'?: string | string[]\n\n /** Original field ID (for reference) */\n '-orig-id'?: string\n}\n\n/**\n * Instance specification for lazy-evaluated fields.\n * Similar to AttributeSpec but for instances section.\n *\n * @interface InstanceSpec\n */\nexport interface InstanceSpec extends Omit<AttributeSpec, 'id'> {\n /** Value instance (calculated field) */\n value?: string | number | boolean\n\n /** Position in stream (for pos instances) */\n pos?: number | string\n\n /** Custom I/O stream */\n io?: string\n}\n\n/**\n * Repeat specification types.\n */\nexport type RepeatSpec = 'expr' | 'eos' | 'until'\n\n/**\n * Switch-based type selection.\n * Allows different types based on an expression value.\n *\n * @interface SwitchType\n */\nexport interface SwitchType {\n /** Expression to evaluate for switching */\n 'switch-on': string\n\n /** Cases mapping values to types */\n cases: Record<string, string>\n\n /** Default type if no case matches */\n default?: string\n}\n\n/**\n * Processing specification for data transformation.\n *\n * @type ProcessSpec\n */\nexport type ProcessSpec = string | ProcessObject\n\n/**\n * Processing object with algorithm and parameters.\n *\n * @interface ProcessObject\n */\nexport interface ProcessObject {\n /** Processing algorithm */\n algorithm: string\n\n /** Algorithm parameters */\n [key: string]: unknown\n}\n\n/**\n * Enum specification (named integer constants).\n *\n * @type EnumSpec\n */\nexport type EnumSpec = Record<string | number, string | number>\n\n/**\n * Parameter specification for parametric types.\n *\n * @interface ParamSpec\n */\nexport interface ParamSpec {\n /** Parameter identifier */\n id: string\n\n /** Parameter type */\n type?: string\n\n /** Documentation */\n doc?: string\n\n /** Reference to documentation */\n 'doc-ref'?: string | string[]\n}\n\n/**\n * Validation result for schema validation.\n *\n * @interface ValidationResult\n */\nexport interface ValidationResult {\n /** Whether the schema is valid */\n valid: boolean\n\n /** Validation errors */\n errors: ValidationError[]\n\n /** Validation warnings */\n warnings: ValidationWarning[]\n}\n\n/**\n * Validation error.\n *\n * @interface ValidationError\n */\nexport interface ValidationError {\n /** Error message */\n message: string\n\n /** Path to the error in the schema */\n path: string[]\n\n /** Error code */\n code: string\n}\n\n/**\n * Validation warning.\n *\n * @interface ValidationWarning\n */\nexport interface ValidationWarning {\n /** Warning message */\n message: string\n\n /** Path to the warning in the schema */\n path: string[]\n\n /** Warning code */\n code: string\n}\n\n/**\n * Built-in Kaitai Struct types.\n */\nexport const BUILTIN_TYPES = [\n // Unsigned integers\n 'u1',\n 'u2',\n 'u2le',\n 'u2be',\n 'u4',\n 'u4le',\n 'u4be',\n 'u8',\n 'u8le',\n 'u8be',\n // Signed integers\n 's1',\n 's2',\n 's2le',\n 's2be',\n 's4',\n 's4le',\n 's4be',\n 's8',\n 's8le',\n 's8be',\n // Floating point\n 'f4',\n 'f4le',\n 'f4be',\n 'f8',\n 'f8le',\n 'f8be',\n // String\n 'str',\n 'strz',\n] as const\n\n/**\n * Type guard to check if a type is a built-in type.\n *\n * @param type - Type name to check\n * @returns True if the type is built-in\n */\nexport function isBuiltinType(type: string): boolean {\n return (BUILTIN_TYPES as readonly string[]).includes(type)\n}\n\n/**\n * Get the default endianness for a type.\n * Returns the endianness suffix if present, otherwise undefined.\n *\n * @param type - Type name\n * @returns Endianness ('le', 'be', or undefined for default)\n */\nexport function getTypeEndianness(type: string): Endianness | undefined {\n if (type.endsWith('le')) return 'le'\n if (type.endsWith('be')) return 'be'\n return undefined\n}\n\n/**\n * Get the base type without endianness suffix.\n *\n * @param type - Type name\n * @returns Base type name\n * @example\n * ```typescript\n * getBaseType('u4le') // returns 'u4'\n * getBaseType('s2be') // returns 's2'\n * getBaseType('str') // returns 'str'\n * ```\n */\nexport function getBaseType(type: string): string {\n if (type.endsWith('le') || type.endsWith('be')) {\n return type.slice(0, -2)\n }\n return type\n}\n\n/**\n * Check if a type is an integer type.\n *\n * @param type - Type name\n * @returns True if the type is an integer\n */\nexport function isIntegerType(type: string): boolean {\n const base = getBaseType(type)\n return /^[us][1248]$/.test(base)\n}\n\n/**\n * Check if a type is a floating point type.\n *\n * @param type - Type name\n * @returns True if the type is a float\n */\nexport function isFloatType(type: string): boolean {\n const base = getBaseType(type)\n return /^f[48]$/.test(base)\n}\n\n/**\n * Check if a type is a string type.\n *\n * @param type - Type name\n * @returns True if the type is a string\n */\nexport function isStringType(type: string): boolean {\n return type === 'str' || type === 'strz'\n}\n","/**\n * @fileoverview Parser for Kaitai Struct YAML (.ksy) files\n * @module parser/KsyParser\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { parse as parseYaml } from 'yaml'\nimport {\n ParseError,\n ValidationError as KaitaiValidationError,\n} from '../utils/errors'\nimport type {\n KsySchema,\n ValidationResult,\n ValidationError,\n ValidationWarning,\n} from './schema'\n\n/**\n * Parser for Kaitai Struct YAML (.ksy) format definitions.\n * Converts YAML text into typed schema objects and validates them.\n *\n * @class KsyParser\n * @example\n * ```typescript\n * const parser = new KsyParser()\n * const schema = parser.parse(ksyYamlString)\n * ```\n */\nexport class KsyParser {\n /**\n * Parse a .ksy YAML string into a typed schema object.\n *\n * @param yaml - YAML string containing the .ksy definition\n * @param options - Parsing options\n * @returns Parsed and validated schema\n * @throws {ParseError} If YAML parsing fails\n * @throws {ValidationError} If schema validation fails\n */\n parse(yaml: string, options: ParseOptions = {}): KsySchema {\n const { validate = true, strict = false } = options\n\n // Parse YAML\n let parsed: unknown\n try {\n parsed = parseYaml(yaml)\n } catch (error) {\n throw new ParseError(\n `Failed to parse YAML: ${error instanceof Error ? error.message : String(error)}`\n )\n }\n\n // Ensure we have an object\n if (typeof parsed !== 'object' || parsed === null) {\n throw new ParseError('KSY file must contain an object')\n }\n\n const schema = parsed as KsySchema\n\n // Validate if requested\n if (validate) {\n const result = this.validate(schema, { strict })\n if (!result.valid) {\n const errorMessages = result.errors.map((e) => e.message).join('; ')\n throw new KaitaiValidationError(\n `Schema validation failed: ${errorMessages}`\n )\n }\n\n // Log warnings if any\n if (result.warnings.length > 0 && !strict) {\n // eslint-disable-next-line no-undef\n console.warn(\n 'Schema validation warnings:',\n result.warnings.map((w) => w.message)\n )\n }\n }\n\n return schema\n }\n\n /**\n * Validate a schema object.\n *\n * @param schema - Schema to validate\n * @param options - Validation options\n * @returns Validation result with errors and warnings\n */\n validate(\n schema: KsySchema,\n options: ValidationOptions = {}\n ): ValidationResult {\n const { strict = false, isNested = false } = options\n const errors: ValidationError[] = []\n const warnings: ValidationWarning[] = []\n\n // Validate meta section (required for root schemas, optional for nested)\n if (!schema.meta && !isNested) {\n errors.push({\n message: 'Missing required \"meta\" section',\n path: [],\n code: 'MISSING_META',\n })\n } else if (schema.meta) {\n // Validate meta.id (required)\n if (!schema.meta.id) {\n errors.push({\n message: 'Missing required \"meta.id\" field',\n path: ['meta'],\n code: 'MISSING_META_ID',\n })\n } else if (typeof schema.meta.id !== 'string') {\n errors.push({\n message: '\"meta.id\" must be a string',\n path: ['meta', 'id'],\n code: 'INVALID_META_ID_TYPE',\n })\n } else if (!/^[a-z][a-z0-9_]*$/.test(schema.meta.id)) {\n warnings.push({\n message: '\"meta.id\" should follow snake_case naming convention',\n path: ['meta', 'id'],\n code: 'META_ID_NAMING',\n })\n }\n\n // Validate endianness\n if (schema.meta.endian) {\n if (\n typeof schema.meta.endian === 'string' &&\n schema.meta.endian !== 'le' &&\n schema.meta.endian !== 'be'\n ) {\n errors.push({\n message: '\"meta.endian\" must be \"le\" or \"be\"',\n path: ['meta', 'endian'],\n code: 'INVALID_ENDIAN',\n })\n }\n }\n }\n\n // Validate seq section\n if (schema.seq) {\n if (!Array.isArray(schema.seq)) {\n errors.push({\n message: '\"seq\" must be an array',\n path: ['seq'],\n code: 'INVALID_SEQ_TYPE',\n })\n } else {\n schema.seq.forEach((attr, index) => {\n this.validateAttribute(\n attr as Record<string, unknown>,\n ['seq', String(index)],\n errors,\n warnings,\n strict\n )\n })\n }\n }\n\n // Validate instances section\n if (schema.instances) {\n if (typeof schema.instances !== 'object') {\n errors.push({\n message: '\"instances\" must be an object',\n path: ['instances'],\n code: 'INVALID_INSTANCES_TYPE',\n })\n } else {\n Object.entries(schema.instances).forEach(([key, instance]) => {\n this.validateAttribute(\n instance as Record<string, unknown>,\n ['instances', key],\n errors,\n warnings,\n strict\n )\n })\n }\n }\n\n // Validate types section\n if (schema.types) {\n if (typeof schema.types !== 'object') {\n errors.push({\n message: '\"types\" must be an object',\n path: ['types'],\n code: 'INVALID_TYPES_TYPE',\n })\n } else {\n Object.entries(schema.types).forEach(([key, type]) => {\n // Nested types don't require meta section\n const typeResult = this.validate(type, { ...options, isNested: true })\n errors.push(\n ...typeResult.errors.map((e) => ({\n ...e,\n path: ['types', key, ...e.path],\n }))\n )\n warnings.push(\n ...typeResult.warnings.map((w) => ({\n ...w,\n path: ['types', key, ...w.path],\n }))\n )\n })\n }\n }\n\n // Validate enums section\n if (schema.enums) {\n if (typeof schema.enums !== 'object') {\n errors.push({\n message: '\"enums\" must be an object',\n path: ['enums'],\n code: 'INVALID_ENUMS_TYPE',\n })\n }\n }\n\n return {\n valid: errors.length === 0 && (strict ? warnings.length === 0 : true),\n errors,\n warnings,\n }\n }\n\n /**\n * Validate an attribute specification.\n *\n * @param attr - Attribute to validate\n * @param path - Path to this attribute in the schema\n * @param errors - Array to collect errors\n * @param warnings - Array to collect warnings\n * @param strict - Whether to be strict about warnings\n * @private\n */\n private validateAttribute(\n attr: Record<string, unknown>,\n path: string[],\n errors: ValidationError[],\n warnings: ValidationWarning[],\n _strict: boolean\n ): void {\n // Validate id naming\n if (attr.id && typeof attr.id === 'string') {\n if (!/^[a-z][a-z0-9_]*$/.test(attr.id)) {\n warnings.push({\n message: `Field \"${attr.id}\" should follow snake_case naming convention`,\n path: [...path, 'id'],\n code: 'FIELD_ID_NAMING',\n })\n }\n }\n\n // Validate repeat\n if (attr.repeat) {\n if (\n attr.repeat !== 'expr' &&\n attr.repeat !== 'eos' &&\n attr.repeat !== 'until'\n ) {\n errors.push({\n message: '\"repeat\" must be \"expr\", \"eos\", or \"until\"',\n path: [...path, 'repeat'],\n code: 'INVALID_REPEAT',\n })\n }\n\n // Check for required fields based on repeat type\n if (attr.repeat === 'expr' && !attr['repeat-expr']) {\n errors.push({\n message: '\"repeat-expr\" is required when repeat is \"expr\"',\n path: [...path, 'repeat-expr'],\n code: 'MISSING_REPEAT_EXPR',\n })\n }\n\n if (attr.repeat === 'until' && !attr['repeat-until']) {\n errors.push({\n message: '\"repeat-until\" is required when repeat is \"until\"',\n path: [...path, 'repeat-until'],\n code: 'MISSING_REPEAT_UNTIL',\n })\n }\n }\n\n // Validate size-eos\n if (attr['size-eos'] && attr.size) {\n warnings.push({\n message: '\"size-eos\" and \"size\" are mutually exclusive',\n path: [...path],\n code: 'SIZE_EOS_WITH_SIZE',\n })\n }\n\n // Validate contents\n if (attr.contents) {\n if (!Array.isArray(attr.contents) && typeof attr.contents !== 'string') {\n errors.push({\n message: '\"contents\" must be an array or string',\n path: [...path, 'contents'],\n code: 'INVALID_CONTENTS_TYPE',\n })\n }\n }\n }\n\n /**\n * Parse multiple .ksy files and resolve imports.\n *\n * @param mainYaml - Main .ksy file content\n * @param imports - Map of import names to their YAML content\n * @param options - Parsing options\n * @returns Parsed schema with resolved imports\n */\n parseWithImports(\n mainYaml: string,\n _imports: Map<string, string>,\n options: ParseOptions = {}\n ): KsySchema {\n // Parse main schema\n const mainSchema = this.parse(mainYaml, options)\n\n // TODO: Resolve imports\n // This will be implemented when we add import support\n\n return mainSchema\n }\n}\n\n/**\n * Options for parsing .ksy files.\n *\n * @interface ParseOptions\n */\nexport interface ParseOptions {\n /** Whether to validate the schema (default: true) */\n validate?: boolean\n\n /** Whether to treat warnings as errors (default: false) */\n strict?: boolean\n}\n\n/**\n * Options for schema validation.\n *\n * @interface ValidationOptions\n */\nexport interface ValidationOptions {\n /** Whether to treat warnings as errors (default: false) */\n strict?: boolean\n\n /** Whether this is a nested type (meta section optional) (default: false) */\n isNested?: boolean\n}\n","/**\n * @fileoverview Execution context for Kaitai Struct parsing\n * @module interpreter/Context\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport type { KaitaiStream } from '../stream'\nimport type { EnumSpec } from '../parser/schema'\n\n/**\n * Execution context for parsing operations.\n * Provides access to the current object, parent, root, and stream.\n *\n * @class Context\n * @example\n * ```typescript\n * const context = new Context(stream, root)\n * context.pushParent(currentObject)\n * const value = evaluator.evaluate(expression, context)\n * context.popParent()\n * ```\n */\nexport class Context {\n /** Stack of parent objects */\n private parentStack: unknown[] = []\n\n /** Current object being parsed */\n private _current: Record<string, unknown> = {}\n\n /** Enum definitions from schema */\n private _enums: Record<string, EnumSpec> = {}\n\n /**\n * Create a new execution context.\n *\n * @param _io - Binary stream being read\n * @param _root - Root object of the parse tree\n * @param _parent - Parent object (optional)\n * @param enums - Enum definitions from schema (optional)\n */\n constructor(\n private _io: KaitaiStream,\n private _root: unknown = null,\n _parent: unknown = null,\n enums?: Record<string, EnumSpec>\n ) {\n if (_parent !== null) {\n this.parentStack.push(_parent)\n }\n if (enums) {\n this._enums = enums\n }\n }\n\n /**\n * Get the current I/O stream.\n * Accessible in expressions as `_io`.\n *\n * @returns Current stream\n */\n get io(): KaitaiStream {\n return this._io\n }\n\n /**\n * Get the root object.\n * Accessible in expressions as `_root`.\n *\n * @returns Root object\n */\n get root(): unknown {\n return this._root\n }\n\n /**\n * Get the parent object.\n * Accessible in expressions as `_parent`.\n *\n * @returns Parent object or null if at root\n */\n get parent(): unknown {\n return this.parentStack.length > 0\n ? this.parentStack[this.parentStack.length - 1]\n : null\n }\n\n /**\n * Get the current object being parsed.\n * Used to access fields defined earlier in the sequence.\n *\n * @returns Current object\n */\n get current(): Record<string, unknown> {\n return this._current\n }\n\n /**\n * Set the current object.\n *\n * @param obj - Object to set as current\n */\n set current(obj: Record<string, unknown>) {\n this._current = obj\n }\n\n /**\n * Push a new parent onto the stack.\n * Used when entering a nested type.\n *\n * @param parent - Parent object to push\n */\n pushParent(parent: unknown): void {\n this.parentStack.push(parent)\n }\n\n /**\n * Pop the current parent from the stack.\n * Used when exiting a nested type.\n *\n * @returns The popped parent object\n */\n popParent(): unknown {\n return this.parentStack.pop()\n }\n\n /**\n * Get a value from the context by path.\n * Supports special names: _io, _root, _parent, _index.\n *\n * @param name - Name or path to resolve\n * @returns Resolved value\n */\n resolve(name: string): unknown {\n // Handle special names\n switch (name) {\n case '_io':\n return this._io\n case '_root':\n return this._root\n case '_parent':\n return this.parent\n case '_index':\n // Index is set externally during repetition\n return (this._current as Record<string, unknown>)['_index']\n default:\n // Look in current object\n if (name in this._current) {\n return this._current[name]\n }\n // Not found\n return undefined\n }\n }\n\n /**\n * Set a value in the current object.\n *\n * @param name - Field name\n * @param value - Value to set\n */\n set(name: string, value: unknown): void {\n this._current[name] = value\n }\n\n /**\n * Get enum value by name.\n * Used for enum access in expressions (EnumName::value).\n *\n * @param enumName - Name of the enum\n * @param valueName - Name of the enum value\n * @returns Enum value (number) or undefined\n */\n getEnumValue(enumName: string, valueName: string): unknown {\n const enumDef = this._enums[enumName]\n if (!enumDef) {\n return undefined\n }\n\n // Enum definitions map integer values to string names\n // e.g., { 0: \"unknown\", 1: \"text\" }\n // We need to reverse-lookup: given \"text\", return 1\n for (const [key, value] of Object.entries(enumDef)) {\n if (value === valueName) {\n // Convert key to number\n const numKey = Number(key)\n return isNaN(numKey) ? key : numKey\n }\n }\n\n return undefined\n }\n\n /**\n * Check if an enum exists.\n *\n * @param enumName - Name of the enum\n * @returns True if enum exists\n */\n hasEnum(enumName: string): boolean {\n return enumName in this._enums\n }\n\n /**\n * Create a child context for nested parsing.\n * The current object becomes the parent in the child context.\n *\n * @param stream - Stream for the child context (defaults to current stream)\n * @returns New child context\n */\n createChild(stream?: KaitaiStream): Context {\n const childContext = new Context(\n stream || this._io,\n this._root || this._current,\n this._current,\n this._enums\n )\n return childContext\n }\n\n /**\n * Clone this context.\n * Creates a shallow copy with the same stream, root, and parent.\n *\n * @returns Cloned context\n */\n clone(): Context {\n const cloned = new Context(this._io, this._root, this.parent, this._enums)\n cloned._current = { ...this._current }\n cloned.parentStack = [...this.parentStack]\n return cloned\n }\n}\n","/**\n * @fileoverview Token types for Kaitai Struct expression language\n * @module expression/Token\n * @author Fabiano Pinto\n * @license MIT\n */\n\n/**\n * Token types in the expression language.\n */\nexport enum TokenType {\n // Literals\n NUMBER = 'NUMBER',\n STRING = 'STRING',\n BOOLEAN = 'BOOLEAN',\n IDENTIFIER = 'IDENTIFIER',\n\n // Operators\n PLUS = 'PLUS', // +\n MINUS = 'MINUS', // -\n STAR = 'STAR', // *\n SLASH = 'SLASH', // /\n PERCENT = 'PERCENT', // %\n\n // Comparison\n LT = 'LT', // <\n LE = 'LE', // <=\n GT = 'GT', // >\n GE = 'GE', // >=\n EQ = 'EQ', // ==\n NE = 'NE', // !=\n\n // Bitwise\n LSHIFT = 'LSHIFT', // <<\n RSHIFT = 'RSHIFT', // >>\n AMPERSAND = 'AMPERSAND', // &\n PIPE = 'PIPE', // |\n CARET = 'CARET', // ^\n\n // Logical\n AND = 'AND', // and\n OR = 'OR', // or\n NOT = 'NOT', // not\n\n // Ternary\n QUESTION = 'QUESTION', // ?\n COLON = 'COLON', // :\n\n // Grouping\n LPAREN = 'LPAREN', // (\n RPAREN = 'RPAREN', // )\n LBRACKET = 'LBRACKET', // [\n RBRACKET = 'RBRACKET', // ]\n\n // Access\n DOT = 'DOT', // .\n DOUBLE_COLON = 'DOUBLE_COLON', // ::\n COMMA = 'COMMA', // ,\n\n // Special\n EOF = 'EOF',\n}\n\n/**\n * Token in the expression language.\n *\n * @interface Token\n */\nexport interface Token {\n /** Token type */\n type: TokenType\n\n /** Token value (for literals and identifiers) */\n value: string | number | boolean | null\n\n /** Position in the source string */\n position: number\n}\n\n/**\n * Create a token.\n *\n * @param type - Token type\n * @param value - Token value\n * @param position - Position in source\n * @returns Token object\n */\nexport function createToken(\n type: TokenType,\n value: string | number | boolean | null = null,\n position: number = 0\n): Token {\n return { type, value, position }\n}\n","/**\n * @fileoverview Lexer for Kaitai Struct expression language\n * @module expression/Lexer\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { ParseError } from '../utils/errors'\nimport { Token, TokenType, createToken } from './Token'\n\n/**\n * Lexer for tokenizing Kaitai Struct expressions.\n * Converts expression strings into a stream of tokens.\n *\n * @class Lexer\n * @example\n * ```typescript\n * const lexer = new Lexer('field1 + field2 * 2')\n * const tokens = lexer.tokenize()\n * ```\n */\nexport class Lexer {\n private input: string\n private position: number = 0\n private current: string | null = null\n\n /**\n * Create a new lexer.\n *\n * @param input - Expression string to tokenize\n */\n constructor(input: string) {\n this.input = input\n this.current = input.length > 0 ? input[0] : null\n }\n\n /**\n * Tokenize the entire input string.\n *\n * @returns Array of tokens\n * @throws {ParseError} If invalid syntax is encountered\n */\n tokenize(): Token[] {\n const tokens: Token[] = []\n\n while (this.current !== null) {\n // Skip whitespace\n if (this.isWhitespace(this.current)) {\n this.skipWhitespace()\n continue\n }\n\n // Numbers\n if (this.isDigit(this.current)) {\n tokens.push(this.readNumber())\n continue\n }\n\n // Identifiers and keywords\n if (this.isIdentifierStart(this.current)) {\n tokens.push(this.readIdentifierOrKeyword())\n continue\n }\n\n // Strings\n if (this.current === '\"' || this.current === \"'\") {\n tokens.push(this.readString())\n continue\n }\n\n // Operators and punctuation\n const token = this.readOperator()\n if (token) {\n tokens.push(token)\n continue\n }\n\n throw new ParseError(\n `Unexpected character: ${this.current}`,\n this.position\n )\n }\n\n tokens.push(createToken(TokenType.EOF, null, this.position))\n return tokens\n }\n\n /**\n * Advance to the next character.\n * @private\n */\n private advance(): void {\n this.position++\n this.current =\n this.position < this.input.length ? this.input[this.position] : null\n }\n\n /**\n * Peek at the next character without advancing.\n * @private\n */\n private peek(offset: number = 1): string | null {\n const pos = this.position + offset\n return pos < this.input.length ? this.input[pos] : null\n }\n\n /**\n * Check if character is whitespace.\n * @private\n */\n private isWhitespace(char: string): boolean {\n return /\\s/.test(char)\n }\n\n /**\n * Check if character is a digit.\n * @private\n */\n private isDigit(char: string): boolean {\n return /[0-9]/.test(char)\n }\n\n /**\n * Check if character can start an identifier.\n * @private\n */\n private isIdentifierStart(char: string): boolean {\n return /[a-zA-Z_]/.test(char)\n }\n\n /**\n * Check if character can be part of an identifier.\n * @private\n */\n private isIdentifierPart(char: string): boolean {\n return /[a-zA-Z0-9_]/.test(char)\n }\n\n /**\n * Skip whitespace characters.\n * @private\n */\n private skipWhitespace(): void {\n while (this.current !== null && this.isWhitespace(this.current)) {\n this.advance()\n }\n }\n\n /**\n * Read a number token.\n * @private\n */\n private readNumber(): Token {\n const start = this.position\n let value = ''\n\n // Handle hex numbers (0x...)\n if (this.current === '0' && this.peek() === 'x') {\n value += this.current\n this.advance()\n value += this.current\n this.advance()\n\n while (this.current !== null && /[0-9a-fA-F]/.test(this.current)) {\n value += this.current\n this.advance()\n }\n\n return createToken(TokenType.NUMBER, parseInt(value, 16), start)\n }\n\n // Regular decimal number\n while (this.current !== null && this.isDigit(this.current)) {\n value += this.current\n this.advance()\n }\n\n // Handle decimal point\n if (this.current === '.' && this.peek() && this.isDigit(this.peek()!)) {\n value += this.current\n this.advance()\n\n while (this.current !== null && this.isDigit(this.current)) {\n value += this.current\n this.advance()\n }\n\n return createToken(TokenType.NUMBER, parseFloat(value), start)\n }\n\n return createToken(TokenType.NUMBER, parseInt(value, 10), start)\n }\n\n /**\n * Read an identifier or keyword token.\n * @private\n */\n private readIdentifierOrKeyword(): Token {\n const start = this.position\n let value = ''\n\n while (this.current !== null && this.isIdentifierPart(this.current)) {\n value += this.current\n this.advance()\n }\n\n // Check for keywords\n switch (value) {\n case 'true':\n return createToken(TokenType.BOOLEAN, true, start)\n case 'false':\n return createToken(TokenType.BOOLEAN, false, start)\n case 'and':\n return createToken(TokenType.AND, value, start)\n case 'or':\n return createToken(TokenType.OR, value, start)\n case 'not':\n return createToken(TokenType.NOT, value, start)\n default:\n return createToken(TokenType.IDENTIFIER, value, start)\n }\n }\n\n /**\n * Read a string token.\n * @private\n */\n private readString(): Token {\n const start = this.position\n const quote = this.current\n let value = ''\n\n this.advance() // Skip opening quote\n\n while (this.current !== null && this.current !== quote) {\n if (this.current === '\\\\') {\n this.advance()\n if (this.current === null) {\n throw new ParseError('Unterminated string', start)\n }\n // Handle escape sequences\n const ch = this.current as string\n if (ch === 'n') {\n value += '\\n'\n } else if (ch === 't') {\n value += '\\t'\n } else if (ch === 'r') {\n value += '\\r'\n } else if (ch === '\\\\') {\n value += '\\\\'\n } else if (ch === '\"') {\n value += '\"'\n } else if (ch === \"'\") {\n value += \"'\"\n } else {\n value += ch\n }\n } else {\n value += this.current\n }\n this.advance()\n }\n\n if (this.current === null) {\n throw new ParseError('Unterminated string', start)\n }\n\n this.advance() // Skip closing quote\n\n return createToken(TokenType.STRING, value, start)\n }\n\n /**\n * Read an operator or punctuation token.\n * @private\n */\n private readOperator(): Token | null {\n const start = this.position\n const char = this.current!\n\n switch (char) {\n case '+':\n this.advance()\n return createToken(TokenType.PLUS, char, start)\n\n case '-':\n this.advance()\n return createToken(TokenType.MINUS, char, start)\n\n case '*':\n this.advance()\n return createToken(TokenType.STAR, char, start)\n\n case '/':\n this.advance()\n return createToken(TokenType.SLASH, char, start)\n\n case '%':\n this.advance()\n return createToken(TokenType.PERCENT, char, start)\n\n case '<':\n this.advance()\n if (this.current === '=') {\n this.advance()\n return createToken(TokenType.LE, '<=', start)\n } else if (this.current === '<') {\n this.advance()\n return createToken(TokenType.LSHIFT, '<<', start)\n }\n return createToken(TokenType.LT, '<', start)\n\n case '>':\n this.advance()\n if (this.current === '=') {\n this.advance()\n return createToken(TokenType.GE, '>=', start)\n } else if (this.current === '>') {\n this.advance()\n return createToken(TokenType.RSHIFT, '>>', start)\n }\n return createToken(TokenType.GT, '>', start)\n\n case '=':\n this.advance()\n if (this.current === '=') {\n this.advance()\n return createToken(TokenType.EQ, '==', start)\n }\n throw new ParseError('Expected == for equality', start)\n\n case '!':\n this.advance()\n if (this.current === '=') {\n this.advance()\n return createToken(TokenType.NE, '!=', start)\n }\n throw new ParseError('Expected != for inequality', start)\n\n case '&':\n this.advance()\n return createToken(TokenType.AMPERSAND, char, start)\n\n case '|':\n this.advance()\n return createToken(TokenType.PIPE, char, start)\n\n case '^':\n this.advance()\n return createToken(TokenType.CARET, char, start)\n\n case '?':\n this.advance()\n return createToken(TokenType.QUESTION, char, start)\n\n case ':':\n this.advance()\n if (this.current === ':') {\n this.advance()\n return createToken(TokenType.DOUBLE_COLON, '::', start)\n }\n return createToken(TokenType.COLON, char, start)\n\n case '(':\n this.advance()\n return createToken(TokenType.LPAREN, char, start)\n\n case ')':\n this.advance()\n return createToken(TokenType.RPAREN, char, start)\n\n case '[':\n this.advance()\n return createToken(TokenType.LBRACKET, char, start)\n\n case ']':\n this.advance()\n return createToken(TokenType.RBRACKET, char, start)\n\n case '.':\n this.advance()\n return createToken(TokenType.DOT, char, start)\n\n case ',':\n this.advance()\n return createToken(TokenType.COMMA, char, start)\n\n default:\n return null\n }\n }\n}\n","/**\n * @fileoverview Abstract Syntax Tree nodes for expression language\n * @module expression/AST\n * @author Fabiano Pinto\n * @license MIT\n */\n\n/**\n * Base interface for all AST nodes.\n */\nexport interface ASTNode {\n /** Node type discriminator */\n kind: string\n}\n\n/**\n * Literal value node (number, string, boolean).\n */\nexport interface LiteralNode extends ASTNode {\n kind: 'Literal'\n value: number | string | boolean\n}\n\n/**\n * Identifier node (variable reference).\n */\nexport interface IdentifierNode extends ASTNode {\n kind: 'Identifier'\n name: string\n}\n\n/**\n * Binary operation node (e.g., a + b).\n */\nexport interface BinaryOpNode extends ASTNode {\n kind: 'BinaryOp'\n operator: string\n left: ASTNode\n right: ASTNode\n}\n\n/**\n * Unary operation node (e.g., -a, not b).\n */\nexport interface UnaryOpNode extends ASTNode {\n kind: 'UnaryOp'\n operator: string\n operand: ASTNode\n}\n\n/**\n * Ternary conditional node (condition ? ifTrue : ifFalse).\n */\nexport interface TernaryNode extends ASTNode {\n kind: 'Ternary'\n condition: ASTNode\n ifTrue: ASTNode\n ifFalse: ASTNode\n}\n\n/**\n * Member access node (object.property).\n */\nexport interface MemberAccessNode extends ASTNode {\n kind: 'MemberAccess'\n object: ASTNode\n property: string\n}\n\n/**\n * Array/index access node (array[index]).\n */\nexport interface IndexAccessNode extends ASTNode {\n kind: 'IndexAccess'\n object: ASTNode\n index: ASTNode\n}\n\n/**\n * Method call node (object.method()).\n */\nexport interface MethodCallNode extends ASTNode {\n kind: 'MethodCall'\n object: ASTNode\n method: string\n args: ASTNode[]\n}\n\n/**\n * Enum access node (EnumName::value).\n */\nexport interface EnumAccessNode extends ASTNode {\n kind: 'EnumAccess'\n enumName: string\n value: string\n}\n\n/**\n * Type union for all AST nodes.\n */\nexport type Expression =\n | LiteralNode\n | IdentifierNode\n | BinaryOpNode\n | UnaryOpNode\n | TernaryNode\n | MemberAccessNode\n | IndexAccessNode\n | MethodCallNode\n | EnumAccessNode\n\n/**\n * Create a literal node.\n */\nexport function createLiteral(value: number | string | boolean): LiteralNode {\n return { kind: 'Literal', value }\n}\n\n/**\n * Create an identifier node.\n */\nexport function createIdentifier(name: string): IdentifierNode {\n return { kind: 'Identifier', name }\n}\n\n/**\n * Create a binary operation node.\n */\nexport function createBinaryOp(\n operator: string,\n left: ASTNode,\n right: ASTNode\n): BinaryOpNode {\n return { kind: 'BinaryOp', operator, left, right }\n}\n\n/**\n * Create a unary operation node.\n */\nexport function createUnaryOp(operator: string, operand: ASTNode): UnaryOpNode {\n return { kind: 'UnaryOp', operator, operand }\n}\n\n/**\n * Create a ternary conditional node.\n */\nexport function createTernary(\n condition: ASTNode,\n ifTrue: ASTNode,\n ifFalse: ASTNode\n): TernaryNode {\n return { kind: 'Ternary', condition, ifTrue, ifFalse }\n}\n\n/**\n * Create a member access node.\n */\nexport function createMemberAccess(\n object: ASTNode,\n property: string\n): MemberAccessNode {\n return { kind: 'MemberAccess', object, property }\n}\n\n/**\n * Create an index access node.\n */\nexport function createIndexAccess(\n object: ASTNode,\n index: ASTNode\n): IndexAccessNode {\n return { kind: 'IndexAccess', object, index }\n}\n\n/**\n * Create a method call node.\n */\nexport function createMethodCall(\n object: ASTNode,\n method: string,\n args: ASTNode[]\n): MethodCallNode {\n return { kind: 'MethodCall', object, method, args }\n}\n\n/**\n * Create an enum access node.\n */\nexport function createEnumAccess(\n enumName: string,\n value: string\n): EnumAccessNode {\n return { kind: 'EnumAccess', enumName, value }\n}\n","/**\n * @fileoverview Parser for Kaitai Struct expression language\n * @module expression/Parser\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { ParseError } from '../utils/errors'\nimport { Token, TokenType } from './Token'\nimport type { ASTNode } from './AST'\nimport {\n createLiteral,\n createIdentifier,\n createBinaryOp,\n createUnaryOp,\n createTernary,\n createMemberAccess,\n createIndexAccess,\n createMethodCall,\n createEnumAccess,\n} from './AST'\n\n/**\n * Parser for Kaitai Struct expressions.\n * Converts tokens into an Abstract Syntax Tree (AST).\n *\n * @class ExpressionParser\n * @example\n * ```typescript\n * const lexer = new Lexer('field1 + field2 * 2')\n * const tokens = lexer.tokenize()\n * const parser = new ExpressionParser(tokens)\n * const ast = parser.parse()\n * ```\n */\nexport class ExpressionParser {\n private tokens: Token[]\n private position: number = 0\n\n /**\n * Create a new expression parser.\n *\n * @param tokens - Array of tokens to parse\n */\n constructor(tokens: Token[]) {\n this.tokens = tokens\n }\n\n /**\n * Parse the tokens into an AST.\n *\n * @returns Root AST node\n * @throws {ParseError} If invalid syntax is encountered\n */\n parse(): ASTNode {\n const expr = this.parseTernary()\n if (!this.isAtEnd()) {\n throw new ParseError(\n `Unexpected token: ${this.current().type}`,\n this.current().position\n )\n }\n return expr\n }\n\n /**\n * Get the current token.\n * @private\n */\n private current(): Token {\n return this.tokens[this.position]\n }\n\n /**\n * Check if we're at the end of tokens.\n * @private\n */\n private isAtEnd(): boolean {\n return this.current().type === TokenType.EOF\n }\n\n /**\n * Advance to the next token.\n * @private\n */\n private advance(): Token {\n if (!this.isAtEnd()) {\n this.position++\n }\n return this.tokens[this.position - 1]\n }\n\n /**\n * Check if current token matches any of the given types.\n * @private\n */\n private match(...types: TokenType[]): boolean {\n for (const type of types) {\n if (this.current().type === type) {\n this.advance()\n return true\n }\n }\n return false\n }\n\n /**\n * Expect a specific token type and advance.\n * @private\n */\n private expect(type: TokenType, message: string): Token {\n if (this.current().type !== type) {\n throw new ParseError(message, this.current().position)\n }\n return this.advance()\n }\n\n /**\n * Parse ternary conditional (lowest precedence).\n * condition ? ifTrue : ifFalse\n * @private\n */\n private parseTernary(): ASTNode {\n let expr = this.parseLogicalOr()\n\n if (this.match(TokenType.QUESTION)) {\n const ifTrue = this.parseTernary()\n this.expect(TokenType.COLON, 'Expected : in ternary expression')\n const ifFalse = this.parseTernary()\n return createTernary(expr, ifTrue, ifFalse)\n }\n\n return expr\n }\n\n /**\n * Parse logical OR.\n * @private\n */\n private parseLogicalOr(): ASTNode {\n let left = this.parseLogicalAnd()\n\n while (this.match(TokenType.OR)) {\n const operator = 'or'\n const right = this.parseLogicalAnd()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse logical AND.\n * @private\n */\n private parseLogicalAnd(): ASTNode {\n let left = this.parseBitwiseOr()\n\n while (this.match(TokenType.AND)) {\n const operator = 'and'\n const right = this.parseBitwiseOr()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse bitwise OR.\n * @private\n */\n private parseBitwiseOr(): ASTNode {\n let left = this.parseBitwiseXor()\n\n while (this.match(TokenType.PIPE)) {\n const operator = '|'\n const right = this.parseBitwiseXor()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse bitwise XOR.\n * @private\n */\n private parseBitwiseXor(): ASTNode {\n let left = this.parseBitwiseAnd()\n\n while (this.match(TokenType.CARET)) {\n const operator = '^'\n const right = this.parseBitwiseAnd()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse bitwise AND.\n * @private\n */\n private parseBitwiseAnd(): ASTNode {\n let left = this.parseEquality()\n\n while (this.match(TokenType.AMPERSAND)) {\n const operator = '&'\n const right = this.parseEquality()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse equality operators (==, !=).\n * @private\n */\n private parseEquality(): ASTNode {\n let left = this.parseRelational()\n\n while (this.match(TokenType.EQ, TokenType.NE)) {\n const operator = this.tokens[this.position - 1].value as string\n const right = this.parseRelational()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse relational operators (<, <=, >, >=).\n * @private\n */\n private parseRelational(): ASTNode {\n let left = this.parseBitShift()\n\n while (this.match(TokenType.LT, TokenType.LE, TokenType.GT, TokenType.GE)) {\n const operator = this.tokens[this.position - 1].value as string\n const right = this.parseBitShift()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse bit shift operators (<<, >>).\n * @private\n */\n private parseBitShift(): ASTNode {\n let left = this.parseAdditive()\n\n while (this.match(TokenType.LSHIFT, TokenType.RSHIFT)) {\n const operator = this.tokens[this.position - 1].value as string\n const right = this.parseAdditive()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse additive operators (+, -).\n * @private\n */\n private parseAdditive(): ASTNode {\n let left = this.parseMultiplicative()\n\n while (this.match(TokenType.PLUS, TokenType.MINUS)) {\n const operator = this.tokens[this.position - 1].value as string\n const right = this.parseMultiplicative()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse multiplicative operators (*, /, %).\n * @private\n */\n private parseMultiplicative(): ASTNode {\n let left = this.parseUnary()\n\n while (this.match(TokenType.STAR, TokenType.SLASH, TokenType.PERCENT)) {\n const operator = this.tokens[this.position - 1].value as string\n const right = this.parseUnary()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse unary operators (-, not).\n * @private\n */\n private parseUnary(): ASTNode {\n if (this.match(TokenType.MINUS, TokenType.NOT)) {\n const operator = this.tokens[this.position - 1].value as string\n const operand = this.parseUnary()\n return createUnaryOp(operator, operand)\n }\n\n return this.parsePostfix()\n }\n\n /**\n * Parse postfix operators (., [], ()).\n * @private\n */\n private parsePostfix(): ASTNode {\n let expr = this.parsePrimary()\n\n while (true) {\n if (this.match(TokenType.DOT)) {\n const property = this.expect(\n TokenType.IDENTIFIER,\n 'Expected property name after .'\n )\n expr = createMemberAccess(expr, property.value as string)\n } else if (this.match(TokenType.LBRACKET)) {\n const index = this.parseTernary()\n this.expect(TokenType.RBRACKET, 'Expected ] after array index')\n expr = createIndexAccess(expr, index)\n } else if (this.current().type === TokenType.LPAREN) {\n // Method call (only if expr is a member access)\n if (expr.kind === 'MemberAccess') {\n this.advance() // consume (\n const args: ASTNode[] = []\n\n if (this.current().type !== TokenType.RPAREN) {\n args.push(this.parseTernary())\n while (this.match(TokenType.COMMA)) {\n args.push(this.parseTernary())\n }\n }\n\n this.expect(TokenType.RPAREN, 'Expected ) after arguments')\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const memberExpr = expr as any\n expr = createMethodCall(memberExpr.object, memberExpr.property, args)\n } else {\n break\n }\n } else {\n break\n }\n }\n\n return expr\n }\n\n /**\n * Parse primary expressions (literals, identifiers, grouping).\n * @private\n */\n private parsePrimary(): ASTNode {\n // Literals\n if (this.match(TokenType.NUMBER, TokenType.STRING, TokenType.BOOLEAN)) {\n const token = this.tokens[this.position - 1]\n return createLiteral(token.value as number | string | boolean)\n }\n\n // Identifiers and enum access\n if (this.match(TokenType.IDENTIFIER)) {\n const name = this.tokens[this.position - 1].value as string\n\n // Check for enum access (EnumName::value)\n if (this.match(TokenType.DOUBLE_COLON)) {\n const value = this.expect(\n TokenType.IDENTIFIER,\n 'Expected enum value after ::'\n )\n return createEnumAccess(name, value.value as string)\n }\n\n return createIdentifier(name)\n }\n\n // Grouping\n if (this.match(TokenType.LPAREN)) {\n const expr = this.parseTernary()\n this.expect(TokenType.RPAREN, 'Expected ) after expression')\n return expr\n }\n\n throw new ParseError(\n `Unexpected token: ${this.current().type}`,\n this.current().position\n )\n }\n}\n","/**\n * @fileoverview Evaluator for Kaitai Struct expression AST\n * @module expression/Evaluator\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { ParseError } from '../utils/errors'\nimport type { Context } from '../interpreter/Context'\nimport type { ASTNode } from './AST'\n\n/**\n * Evaluator for expression AST nodes.\n * Executes expressions in the context of parsed data.\n *\n * @class Evaluator\n * @example\n * ```typescript\n * const evaluator = new Evaluator()\n * const result = evaluator.evaluate(ast, context)\n * ```\n */\nexport class Evaluator {\n /**\n * Evaluate an AST node in the given context.\n *\n * @param node - AST node to evaluate\n * @param context - Execution context\n * @returns Evaluated value\n * @throws {ParseError} If evaluation fails\n */\n evaluate(node: ASTNode, context: Context): unknown {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const n = node as any\n switch (node.kind) {\n case 'Literal':\n return n.value\n\n case 'Identifier':\n return this.evaluateIdentifier(n.name, context)\n\n case 'BinaryOp':\n return this.evaluateBinaryOp(n.operator, n.left, n.right, context)\n\n case 'UnaryOp':\n return this.evaluateUnaryOp(n.operator, n.operand, context)\n\n case 'Ternary':\n return this.evaluateTernary(n.condition, n.ifTrue, n.ifFalse, context)\n\n case 'MemberAccess':\n return this.evaluateMemberAccess(n.object, n.property, context)\n\n case 'IndexAccess':\n return this.evaluateIndexAccess(n.object, n.index, context)\n\n case 'MethodCall':\n return this.evaluateMethodCall(n.object, n.method, n.args, context)\n\n case 'EnumAccess':\n return this.evaluateEnumAccess(n.enumName, n.value, context)\n\n default:\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n throw new ParseError(`Unknown AST node kind: ${(node as any).kind}`)\n }\n }\n\n /**\n * Evaluate an identifier.\n * @private\n */\n private evaluateIdentifier(name: string, context: Context): unknown {\n return context.resolve(name)\n }\n\n /**\n * Evaluate a binary operation.\n * @private\n */\n private evaluateBinaryOp(\n operator: string,\n left: ASTNode,\n right: ASTNode,\n context: Context\n ): unknown {\n const leftVal = this.evaluate(left, context)\n const rightVal = this.evaluate(right, context)\n\n switch (operator) {\n // Arithmetic\n case '+':\n return this.add(leftVal, rightVal)\n case '-':\n return this.toNumber(leftVal) - this.toNumber(rightVal)\n case '*':\n return this.toNumber(leftVal) * this.toNumber(rightVal)\n case '/':\n return this.toNumber(leftVal) / this.toNumber(rightVal)\n case '%':\n return this.modulo(this.toNumber(leftVal), this.toNumber(rightVal))\n\n // Comparison\n case '<':\n return this.compare(leftVal, rightVal) < 0\n case '<=':\n return this.compare(leftVal, rightVal) <= 0\n case '>':\n return this.compare(leftVal, rightVal) > 0\n case '>=':\n return this.compare(leftVal, rightVal) >= 0\n case '==':\n return this.equals(leftVal, rightVal)\n case '!=':\n return !this.equals(leftVal, rightVal)\n\n // Bitwise\n case '<<':\n return this.toInt(leftVal) << this.toInt(rightVal)\n case '>>':\n return this.toInt(leftVal) >> this.toInt(rightVal)\n case '&':\n return this.toInt(leftVal) & this.toInt(rightVal)\n case '|':\n return this.toInt(leftVal) | this.toInt(rightVal)\n case '^':\n return this.toInt(leftVal) ^ this.toInt(rightVal)\n\n // Logical\n case 'and':\n return this.toBoolean(leftVal) && this.toBoolean(rightVal)\n case 'or':\n return this.toBoolean(leftVal) || this.toBoolean(rightVal)\n\n default:\n throw new ParseError(`Unknown binary operator: ${operator}`)\n }\n }\n\n /**\n * Evaluate a unary operation.\n * @private\n */\n private evaluateUnaryOp(\n operator: string,\n operand: ASTNode,\n context: Context\n ): unknown {\n const value = this.evaluate(operand, context)\n\n switch (operator) {\n case '-':\n return -this.toNumber(value)\n case 'not':\n return !this.toBoolean(value)\n default:\n throw new ParseError(`Unknown unary operator: ${operator}`)\n }\n }\n\n /**\n * Evaluate a ternary conditional.\n * @private\n */\n private evaluateTernary(\n condition: ASTNode,\n ifTrue: ASTNode,\n ifFalse: ASTNode,\n context: Context\n ): unknown {\n const condValue = this.evaluate(condition, context)\n return this.toBoolean(condValue)\n ? this.evaluate(ifTrue, context)\n : this.evaluate(ifFalse, context)\n }\n\n /**\n * Evaluate member access (object.property).\n * @private\n */\n private evaluateMemberAccess(\n object: ASTNode,\n property: string,\n context: Context\n ): unknown {\n const obj = this.evaluate(object, context)\n\n if (obj === null || obj === undefined) {\n throw new ParseError(\n `Cannot access property ${property} of null/undefined`\n )\n }\n\n if (typeof obj === 'object') {\n return (obj as Record<string, unknown>)[property]\n }\n\n throw new ParseError(`Cannot access property ${property} of non-object`)\n }\n\n /**\n * Evaluate index access (array[index]).\n * @private\n */\n private evaluateIndexAccess(\n object: ASTNode,\n index: ASTNode,\n context: Context\n ): unknown {\n const obj = this.evaluate(object, context)\n const idx = this.evaluate(index, context)\n\n if (Array.isArray(obj)) {\n const numIdx = this.toInt(idx)\n return obj[numIdx]\n }\n\n if (obj instanceof Uint8Array) {\n const numIdx = this.toInt(idx)\n return obj[numIdx]\n }\n\n throw new ParseError('Index access requires an array')\n }\n\n /**\n * Evaluate method call (object.method()).\n * @private\n */\n private evaluateMethodCall(\n object: ASTNode,\n method: string,\n _args: ASTNode[],\n context: Context\n ): unknown {\n const obj = this.evaluate(object, context)\n // TODO: Use args for method calls that need them\n // const evalArgs = args.map((arg) => this.evaluate(arg, context))\n\n // Handle common methods\n if (method === 'length' || method === 'size') {\n if (Array.isArray(obj)) return obj.length\n if (obj instanceof Uint8Array) return obj.length\n if (typeof obj === 'string') return obj.length\n throw new ParseError(`Object does not have a ${method} property`)\n }\n\n if (method === 'to_i') {\n return this.toInt(obj)\n }\n\n if (method === 'to_s') {\n return String(obj)\n }\n\n throw new ParseError(`Unknown method: ${method}`)\n }\n\n /**\n * Evaluate enum access (EnumName::value).\n * @private\n */\n private evaluateEnumAccess(\n enumName: string,\n valueName: string,\n context: Context\n ): unknown {\n const value = context.getEnumValue(enumName, valueName)\n if (value === undefined) {\n throw new ParseError(`Enum value \"${enumName}::${valueName}\" not found`)\n }\n return value\n }\n\n /**\n * Helper: Add two values (handles strings and numbers).\n * @private\n */\n private add(left: unknown, right: unknown): unknown {\n if (typeof left === 'string' || typeof right === 'string') {\n return String(left) + String(right)\n }\n return this.toNumber(left) + this.toNumber(right)\n }\n\n /**\n * Helper: Modulo operation (Kaitai-style, not remainder).\n * @private\n */\n private modulo(a: number, b: number): number {\n const result = a % b\n return result < 0 ? result + b : result\n }\n\n /**\n * Helper: Compare two values.\n * @private\n */\n private compare(left: unknown, right: unknown): number {\n if (typeof left === 'string' && typeof right === 'string') {\n return left < right ? -1 : left > right ? 1 : 0\n }\n const leftNum = this.toNumber(left)\n const rightNum = this.toNumber(right)\n return leftNum < rightNum ? -1 : leftNum > rightNum ? 1 : 0\n }\n\n /**\n * Helper: Check equality.\n * @private\n */\n private equals(left: unknown, right: unknown): boolean {\n // Handle bigint comparison\n if (typeof left === 'bigint' || typeof right === 'bigint') {\n return BigInt(left as number) === BigInt(right as number)\n }\n return left === right\n }\n\n /**\n * Helper: Convert to number.\n * @private\n */\n private toNumber(value: unknown): number {\n if (typeof value === 'number') return value\n if (typeof value === 'bigint') return Number(value)\n if (typeof value === 'boolean') return value ? 1 : 0\n if (typeof value === 'string') return parseFloat(value)\n throw new ParseError(`Cannot convert ${typeof value} to number`)\n }\n\n /**\n * Helper: Convert to integer.\n * @private\n */\n private toInt(value: unknown): number {\n return Math.floor(this.toNumber(value))\n }\n\n /**\n * Helper: Convert to boolean.\n * @private\n */\n private toBoolean(value: unknown): boolean {\n if (typeof value === 'boolean') return value\n if (typeof value === 'number') return value !== 0\n if (typeof value === 'bigint') return value !== 0n\n if (typeof value === 'string') return value.length > 0\n if (value === null || value === undefined) return false\n return true\n }\n}\n","/**\n * @fileoverview Expression evaluation module\n * @module expression\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { Lexer } from './Lexer'\nimport { ExpressionParser } from './Parser'\nimport { Evaluator } from './Evaluator'\nimport type { Context } from '../interpreter/Context'\n\nexport * from './Token'\nexport * from './AST'\nexport * from './Lexer'\nexport * from './Parser'\nexport * from './Evaluator'\n\n/**\n * Evaluate a Kaitai Struct expression string.\n * Convenience function that combines lexing, parsing, and evaluation.\n *\n * @param expression - Expression string to evaluate\n * @param context - Execution context\n * @returns Evaluated value\n * @throws {ParseError} If parsing or evaluation fails\n *\n * @example\n * ```typescript\n * const result = evaluateExpression('field1 + field2 * 2', context)\n * ```\n */\nexport function evaluateExpression(\n expression: string,\n context: Context\n): unknown {\n // Lexical analysis\n const lexer = new Lexer(expression)\n const tokens = lexer.tokenize()\n\n // Parsing\n const parser = new ExpressionParser(tokens)\n const ast = parser.parse()\n\n // Evaluation\n const evaluator = new Evaluator()\n return evaluator.evaluate(ast, context)\n}\n","/**\n * @fileoverview Type interpreter for executing Kaitai Struct schemas\n * @module interpreter/TypeInterpreter\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { KaitaiStream } from '../stream'\nimport {\n ParseError,\n ValidationError,\n NotImplementedError,\n} from '../utils/errors'\nimport type { KsySchema, AttributeSpec, Endianness } from '../parser/schema'\nimport {\n isBuiltinType,\n getTypeEndianness,\n getBaseType,\n isIntegerType,\n isFloatType,\n isStringType,\n} from '../parser/schema'\nimport { Context } from './Context'\nimport { evaluateExpression } from '../expression'\n\n/**\n * Interprets Kaitai Struct schemas and parses binary data.\n * Executes schema definitions against binary streams to produce structured objects.\n *\n * @class TypeInterpreter\n * @example\n * ```typescript\n * const interpreter = new TypeInterpreter(schema)\n * const stream = new KaitaiStream(buffer)\n * const result = interpreter.parse(stream)\n * ```\n */\nexport class TypeInterpreter {\n /**\n * Create a new type interpreter.\n *\n * @param schema - Kaitai Struct schema to interpret\n * @param parentMeta - Parent schema's meta (for nested types)\n */\n constructor(\n private schema: KsySchema,\n private parentMeta?: {\n id: string\n endian?: Endianness | object\n encoding?: string\n }\n ) {\n // For root schemas, meta.id is required\n // For nested types, we can inherit from parent\n if (!schema.meta && !parentMeta) {\n throw new ParseError('Schema must have meta section')\n }\n if (schema.meta && !schema.meta.id && !parentMeta) {\n throw new ParseError('Root schema must have meta.id')\n }\n }\n\n /**\n * Parse binary data according to the schema.\n *\n * @param stream - Binary stream to parse\n * @param parent - Parent object (for nested types)\n * @param typeArgs - Arguments for parametric types\n * @returns Parsed object\n */\n parse(\n stream: KaitaiStream,\n parent?: unknown,\n typeArgs?: Array<string | number | boolean>\n ): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n const context = new Context(stream, result, parent, this.schema.enums)\n context.current = result\n\n // Set parameters in context if this is a parametric type\n if (typeArgs && this.schema.params) {\n for (\n let i = 0;\n i < this.schema.params.length && i < typeArgs.length;\n i++\n ) {\n const param = this.schema.params[i]\n const argValue = typeArgs[i]\n // Evaluate the argument if it's a string expression\n const evaluatedArg =\n typeof argValue === 'string'\n ? this.evaluateValue(argValue, context)\n : argValue\n context.set(param.id, evaluatedArg)\n }\n }\n\n // Parse sequential fields\n if (this.schema.seq) {\n for (const attr of this.schema.seq) {\n const value = this.parseAttribute(attr, context)\n if (attr.id) {\n result[attr.id] = value\n }\n }\n }\n\n // Set up lazy-evaluated instances\n if (this.schema.instances) {\n this.setupInstances(result, stream, context)\n }\n\n return result\n }\n\n /**\n * Set up lazy-evaluated instance getters.\n * Instances are computed on first access and cached.\n *\n * @param result - Result object to add getters to\n * @param stream - Stream for parsing\n * @param context - Execution context\n * @private\n */\n private setupInstances(\n result: Record<string, unknown>,\n stream: KaitaiStream,\n context: Context\n ): void {\n if (!this.schema.instances) return\n\n for (const [name, instance] of Object.entries(this.schema.instances)) {\n // Cache for lazy evaluation\n let cached: unknown = undefined\n let evaluated = false\n\n Object.defineProperty(result, name, {\n get: () => {\n if (!evaluated) {\n cached = this.parseInstance(\n instance as Record<string, unknown>,\n stream,\n context\n )\n evaluated = true\n }\n return cached\n },\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n /**\n * Parse an instance (lazy-evaluated field).\n *\n * @param instance - Instance specification\n * @param stream - Stream to read from\n * @param context - Execution context\n * @returns Parsed or calculated value\n * @private\n */\n private parseInstance(\n instance: Record<string, unknown>,\n stream: KaitaiStream,\n context: Context\n ): unknown {\n // Handle value instances (calculated fields)\n if ('value' in instance) {\n return this.evaluateValue(\n instance.value as string | number | boolean | undefined,\n context\n )\n }\n\n // Save current position\n const savedPos = stream.pos\n\n try {\n // Handle pos attribute for positioned reads\n if (instance.pos !== undefined) {\n const pos = this.evaluateValue(\n instance.pos as string | number | boolean | undefined,\n context\n )\n if (typeof pos === 'number') {\n stream.seek(pos)\n } else if (typeof pos === 'bigint') {\n stream.seek(Number(pos))\n } else {\n throw new ParseError(\n `pos must evaluate to a number, got ${typeof pos}`\n )\n }\n }\n\n // Parse as a regular attribute\n const value = this.parseAttribute(instance as any, context)\n return value\n } finally {\n // Restore position if pos was used\n if (instance.pos !== undefined) {\n stream.seek(savedPos)\n }\n }\n }\n\n /**\n * Parse a single attribute according to its specification.\n *\n * @param attr - Attribute specification\n * @param context - Execution context\n * @returns Parsed value\n * @private\n */\n private parseAttribute(attr: AttributeSpec, context: Context): unknown {\n const stream = context.io\n\n // Handle conditional parsing\n if (attr.if) {\n const condition = this.evaluateValue(attr.if, context)\n // If condition is false or falsy, skip this attribute\n if (!condition) {\n return undefined\n }\n }\n\n // Handle absolute positioning\n if (attr.pos !== undefined) {\n const pos = this.evaluateValue(attr.pos, context)\n if (typeof pos === 'number') {\n stream.seek(pos)\n } else if (typeof pos === 'bigint') {\n stream.seek(Number(pos))\n } else {\n throw new ParseError(`pos must evaluate to a number, got ${typeof pos}`)\n }\n }\n\n // Handle custom I/O\n if (attr.io) {\n throw new NotImplementedError('Custom I/O streams')\n }\n\n // Handle repetition\n if (attr.repeat) {\n return this.parseRepeated(attr, context)\n }\n\n // Handle contents validation\n if (attr.contents) {\n return this.parseContents(attr, context)\n }\n\n // Parse single value\n const value = this.parseValue(attr, context)\n\n // Note: We don't apply enum mapping here to keep values as integers\n // This allows enum comparisons in expressions to work correctly\n // Enum mapping should be done at the presentation layer if needed\n\n return value\n }\n\n /**\n * Parse a repeated attribute.\n *\n * @param attr - Attribute specification with repeat\n * @param context - Execution context\n * @returns Array of parsed values\n * @private\n */\n private parseRepeated(attr: AttributeSpec, context: Context): unknown[] {\n const stream = context.io\n const result: unknown[] = []\n\n switch (attr.repeat) {\n case 'expr': {\n // Fixed number of repetitions\n const countValue = this.evaluateValue(attr['repeat-expr'], context)\n const count =\n typeof countValue === 'number'\n ? countValue\n : typeof countValue === 'bigint'\n ? Number(countValue)\n : 0\n\n if (count < 0) {\n throw new ParseError(`repeat-expr must be non-negative, got ${count}`)\n }\n\n for (let i = 0; i < count; i++) {\n // Set _index for expressions\n context.set('_index', i)\n const value = this.parseAttribute(\n { ...attr, repeat: undefined, 'repeat-expr': undefined },\n context\n )\n result.push(value)\n }\n break\n }\n\n case 'eos': {\n // Repeat until end of stream\n while (!stream.isEof()) {\n context.set('_index', result.length)\n result.push(this.parseValue(attr, context))\n }\n break\n }\n\n case 'until': {\n // Repeat until condition is true\n if (!attr['repeat-until']) {\n throw new ParseError('repeat-until expression is required')\n }\n\n let index = 0\n // eslint-disable-next-line no-constant-condition\n while (true) {\n context.set('_index', index)\n\n // Parse the value first\n const value = this.parseAttribute(\n { ...attr, repeat: undefined, 'repeat-until': undefined },\n context\n )\n result.push(value)\n\n // Set _ to the last parsed value for the condition\n context.set('_', value)\n\n // Evaluate the condition\n const condition = this.evaluateValue(attr['repeat-until'], context)\n\n // Break if condition is true\n if (condition) {\n break\n }\n\n // Check for EOF to prevent infinite loops\n if (stream.isEof()) {\n break\n }\n\n index++\n }\n break\n }\n\n default:\n throw new ParseError(`Unknown repeat type: ${attr.repeat}`)\n }\n\n return result\n }\n\n /**\n * Parse and validate contents.\n *\n * @param attr - Attribute specification with contents\n * @param context - Execution context\n * @returns The validated contents\n * @private\n */\n private parseContents(\n attr: AttributeSpec,\n context: Context\n ): Uint8Array | string {\n const stream = context.io\n const expected = attr.contents!\n\n if (Array.isArray(expected)) {\n // Byte array contents\n const bytes = stream.readBytes(expected.length)\n for (let i = 0; i < expected.length; i++) {\n if (bytes[i] !== expected[i]) {\n throw new ValidationError(\n `Contents mismatch at byte ${i}: expected ${expected[i]}, got ${bytes[i]}`,\n stream.pos - expected.length + i\n )\n }\n }\n return bytes\n } else {\n // String contents\n const encoding = attr.encoding || this.schema.meta.encoding || 'UTF-8'\n const str = stream.readStr(expected.length, encoding)\n if (str !== expected) {\n throw new ValidationError(\n `Contents mismatch: expected \"${expected}\", got \"${str}\"`,\n stream.pos - expected.length\n )\n }\n return str\n }\n }\n\n /**\n * Parse a single value according to its type.\n *\n * @param attr - Attribute specification\n * @param context - Execution context\n * @returns Parsed value\n * @private\n */\n private parseValue(attr: AttributeSpec, context: Context): unknown {\n const stream = context.io\n const type = attr.type\n\n // Handle sized reads\n if (attr.size !== undefined) {\n const sizeValue = this.evaluateValue(attr.size, context)\n const size =\n typeof sizeValue === 'number'\n ? sizeValue\n : typeof sizeValue === 'bigint'\n ? Number(sizeValue)\n : 0\n\n if (size < 0) {\n throw new ParseError(`size must be non-negative, got ${size}`)\n }\n\n if (type === 'str' || !type) {\n // String or raw bytes\n const encoding = attr.encoding || this.schema.meta.encoding || 'UTF-8'\n let data: Uint8Array\n if (type === 'str') {\n data = stream.readBytes(size)\n // Apply processing if specified\n if (attr.process) {\n data = this.applyProcessing(data, attr.process)\n }\n // eslint-disable-next-line no-undef\n return new TextDecoder(encoding).decode(data)\n } else {\n data = stream.readBytes(size)\n // Apply processing if specified\n if (attr.process) {\n data = this.applyProcessing(data, attr.process)\n }\n return data\n }\n } else {\n // Sized substream for complex type\n let data = stream.readBytes(size)\n // Apply processing if specified\n if (attr.process) {\n data = this.applyProcessing(data, attr.process)\n }\n const substream = new KaitaiStream(data)\n return this.parseType(type, substream, context, attr['type-args'])\n }\n }\n\n // Handle size-eos\n if (attr['size-eos']) {\n if (type === 'str') {\n const encoding = attr.encoding || this.schema.meta.encoding || 'UTF-8'\n const bytes = stream.readBytesFull()\n // eslint-disable-next-line no-undef\n return new TextDecoder(encoding).decode(bytes)\n } else {\n return stream.readBytesFull()\n }\n }\n\n // Handle type-based parsing\n if (!type) {\n throw new ParseError('Attribute must have either type, size, or contents')\n }\n\n return this.parseType(type, stream, context, attr['type-args'])\n }\n\n /**\n * Parse a value of a specific type.\n *\n * @param type - Type name or switch specification\n * @param stream - Stream to read from\n * @param context - Execution context\n * @param typeArgs - Arguments for parametric types\n * @returns Parsed value\n * @private\n */\n private parseType(\n type: string | object,\n stream: KaitaiStream,\n context: Context,\n typeArgs?: Array<string | number | boolean>\n ): unknown {\n // Handle switch types\n if (typeof type === 'object') {\n return this.parseSwitchType(\n type as Record<string, unknown>,\n stream,\n context\n )\n }\n\n // Handle built-in types\n if (isBuiltinType(type)) {\n return this.parseBuiltinType(type, stream, context)\n }\n\n // Handle user-defined types\n if (this.schema.types && type in this.schema.types) {\n const typeSchema = this.schema.types[type]\n // Pass parent meta for nested types\n const meta = this.schema.meta || this.parentMeta\n\n // Inherit parent enums if nested type doesn't have its own\n if (this.schema.enums && !typeSchema.enums) {\n typeSchema.enums = this.schema.enums\n }\n\n // Inherit parent types if nested type doesn't have its own\n if (this.schema.types && !typeSchema.types) {\n typeSchema.types = this.schema.types\n }\n\n const interpreter = new TypeInterpreter(typeSchema, meta)\n return interpreter.parse(stream, context.current, typeArgs)\n }\n\n throw new ParseError(`Unknown type: ${type}`)\n }\n\n /**\n * Parse a switch type (type selection based on expression).\n *\n * @param switchType - Switch type specification\n * @param stream - Stream to read from\n * @param context - Execution context\n * @returns Parsed value\n * @private\n */\n private parseSwitchType(\n switchType: Record<string, unknown>,\n stream: KaitaiStream,\n context: Context\n ): unknown {\n const switchOn = switchType['switch-on']\n const cases = switchType['cases'] as Record<string, string> | undefined\n const defaultType = switchType['default'] as string | undefined\n\n if (!switchOn || typeof switchOn !== 'string') {\n throw new ParseError('switch-on expression is required for switch types')\n }\n\n if (!cases) {\n throw new ParseError('cases are required for switch types')\n }\n\n // Evaluate the switch expression\n const switchValue = this.evaluateValue(switchOn, context)\n\n // Convert switch value to string for case matching\n const switchKey = String(switchValue)\n\n // Find matching case\n let selectedType: string | undefined = cases[switchKey]\n\n // Use default if no case matches\n if (selectedType === undefined && defaultType) {\n selectedType = defaultType\n }\n\n if (selectedType === undefined) {\n throw new ParseError(\n `No matching case for switch value \"${switchKey}\" and no default type specified`\n )\n }\n\n // Parse using the selected type\n return this.parseType(selectedType, stream, context)\n }\n\n /**\n * Parse a built-in type.\n *\n * @param type - Built-in type name\n * @param stream - Stream to read from\n * @param context - Execution context\n * @returns Parsed value\n * @private\n */\n private parseBuiltinType(\n type: string,\n stream: KaitaiStream,\n _context: Context\n ): unknown {\n const base = getBaseType(type)\n const typeEndian = getTypeEndianness(type)\n // Get endianness from schema or parent\n const meta = this.schema.meta || this.parentMeta\n const metaEndian = meta?.endian\n // Handle expression-based endianness (not yet implemented)\n const endian: Endianness =\n typeEndian || (typeof metaEndian === 'string' ? metaEndian : 'le')\n\n // Integer types\n if (isIntegerType(type)) {\n return this.readInteger(base, endian, stream)\n }\n\n // Float types\n if (isFloatType(type)) {\n return this.readFloat(base, endian, stream)\n }\n\n // String types\n if (isStringType(type)) {\n throw new ParseError('String types require size, size-eos, or terminator')\n }\n\n throw new ParseError(`Unknown built-in type: ${type}`)\n }\n\n /**\n * Read an integer value.\n *\n * @param type - Integer type (u1, u2, u4, u8, s1, s2, s4, s8)\n * @param endian - Endianness\n * @param stream - Stream to read from\n * @returns Integer value\n * @private\n */\n private readInteger(\n type: string,\n endian: Endianness,\n stream: KaitaiStream\n ): number | bigint {\n switch (type) {\n case 'u1':\n return stream.readU1()\n case 'u2':\n return endian === 'le' ? stream.readU2le() : stream.readU2be()\n case 'u4':\n return endian === 'le' ? stream.readU4le() : stream.readU4be()\n case 'u8':\n return endian === 'le' ? stream.readU8le() : stream.readU8be()\n case 's1':\n return stream.readS1()\n case 's2':\n return endian === 'le' ? stream.readS2le() : stream.readS2be()\n case 's4':\n return endian === 'le' ? stream.readS4le() : stream.readS4be()\n case 's8':\n return endian === 'le' ? stream.readS8le() : stream.readS8be()\n default:\n throw new ParseError(`Unknown integer type: ${type}`)\n }\n }\n\n /**\n * Read a floating point value.\n *\n * @param type - Float type (f4, f8)\n * @param endian - Endianness\n * @param stream - Stream to read from\n * @returns Float value\n * @private\n */\n private readFloat(\n type: string,\n endian: Endianness,\n stream: KaitaiStream\n ): number {\n switch (type) {\n case 'f4':\n return endian === 'le' ? stream.readF4le() : stream.readF4be()\n case 'f8':\n return endian === 'le' ? stream.readF8le() : stream.readF8be()\n default:\n throw new ParseError(`Unknown float type: ${type}`)\n }\n }\n\n /**\n * Apply processing transformation to data.\n * Supports basic transformations like zlib decompression.\n *\n * @param data - Data to process\n * @param process - Processing specification\n * @returns Processed data\n * @private\n */\n private applyProcessing(\n data: Uint8Array,\n process: string | Record<string, unknown>\n ): Uint8Array {\n const processType = typeof process === 'string' ? process : process.algorithm\n\n // For now, return data as-is with a note that processing isn't fully implemented\n // Full implementation would require zlib, encryption libraries, etc.\n if (processType) {\n throw new NotImplementedError(\n `Processing type \"${processType}\" is not yet implemented. ` +\n `Supported in future versions with zlib, encryption, etc.`\n )\n }\n\n return data\n }\n\n /**\n * Evaluate a value that can be an expression or literal.\n *\n * @param value - Value to evaluate (expression string, number, or boolean)\n * @param context - Execution context\n * @returns Evaluated result\n * @private\n */\n private evaluateValue(\n value: string | number | boolean | undefined,\n context: Context\n ): unknown {\n if (value === undefined) {\n return undefined\n }\n\n // If it's a number or boolean, return as-is\n if (typeof value === 'number' || typeof value === 'boolean') {\n return value\n }\n\n // If it's a string, evaluate as expression\n if (typeof value === 'string') {\n try {\n return evaluateExpression(value, context)\n } catch (error) {\n throw new ParseError(\n `Failed to evaluate expression \"${value}\": ${error instanceof Error ? error.message : String(error)}`\n )\n }\n }\n\n return value\n }\n}\n","/**\n * @fileoverview Main entry point for kaitai-struct-ts library\n * @module kaitai-struct-ts\n * @author Fabiano Pinto\n * @license MIT\n * @version 0.2.0\n *\n * @description\n * A runtime interpreter for Kaitai Struct binary format definitions in TypeScript.\n * Parse any binary data format by providing a .ksy (Kaitai Struct YAML) definition file.\n *\n * @example\n * ```typescript\n * import { parse } from 'kaitai-struct-ts'\n *\n * const ksyDefinition = `\n * meta:\n * id: my_format\n * endian: le\n * seq:\n * - id: magic\n * contents: [0x4D, 0x5A]\n * - id: version\n * type: u2\n * `\n *\n * const buffer = new Uint8Array([0x4D, 0x5A, 0x01, 0x00])\n * const result = parse(ksyDefinition, buffer)\n * console.log(result.version) // 1\n * ```\n */\n\nimport { KaitaiStream } from './stream'\nimport { KsyParser } from './parser'\nimport { TypeInterpreter } from './interpreter'\n\n// Export main classes\nexport { KaitaiStream } from './stream'\nexport { KsyParser } from './parser'\nexport { TypeInterpreter } from './interpreter'\nexport { Context } from './interpreter'\n\n// Export types from schema\nexport type {\n KsySchema,\n MetaSpec,\n AttributeSpec,\n InstanceSpec,\n SwitchType,\n EnumSpec,\n ParamSpec,\n Endianness,\n EndianExpression,\n RepeatSpec,\n ProcessSpec,\n ProcessObject,\n ValidationResult,\n ValidationError as SchemaValidationError,\n ValidationWarning,\n} from './parser/schema'\n\nexport {\n BUILTIN_TYPES,\n isBuiltinType,\n getTypeEndianness,\n getBaseType,\n isIntegerType,\n isFloatType,\n isStringType,\n} from './parser/schema'\n\n// Export error classes\nexport * from './utils/errors'\n\n/**\n * Parse binary data using a Kaitai Struct definition.\n * This is the main convenience function for parsing.\n *\n * @param ksyYaml - YAML string containing the .ksy definition\n * @param buffer - Binary data to parse (ArrayBuffer or Uint8Array)\n * @param options - Parsing options\n * @returns Parsed object with fields defined in the .ksy file\n * @throws {ParseError} If YAML parsing fails\n * @throws {ValidationError} If schema validation fails\n * @throws {EOFError} If unexpected end of stream is reached\n *\n * @example\n * ```typescript\n * const result = parse(ksyYaml, binaryData)\n * console.log(result.fieldName)\n * ```\n */\nexport function parse(\n ksyYaml: string,\n buffer: ArrayBuffer | Uint8Array,\n options: ParseOptions = {}\n): Record<string, unknown> {\n const { validate = true, strict = false } = options\n\n // Parse the KSY schema\n const parser = new KsyParser()\n const schema = parser.parse(ksyYaml, { validate, strict })\n\n // Create a stream from the buffer\n const stream = new KaitaiStream(buffer)\n\n // Create an interpreter and parse\n const interpreter = new TypeInterpreter(schema)\n return interpreter.parse(stream)\n}\n\n/**\n * Options for the parse function.\n *\n * @interface ParseOptions\n */\nexport interface ParseOptions {\n /** Whether to validate the schema (default: true) */\n validate?: boolean\n\n /** Whether to treat warnings as errors (default: false) */\n strict?: boolean\n}\n"],"mappings":";AAkBO,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA,EACrC,YACE,SACO,UACP;AACA,UAAM,OAAO;AAFN;AAGP,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,aAAY,SAAS;AAAA,EACnD;AACF;AAaO,IAAM,kBAAN,MAAM,yBAAwB,YAAY;AAAA,EAC/C,YAAY,SAAiB,UAAmB;AAC9C,UAAM,SAAS,QAAQ;AACvB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,iBAAgB,SAAS;AAAA,EACvD;AACF;AAaO,IAAM,aAAN,MAAM,oBAAmB,YAAY;AAAA,EAC1C,YAAY,SAAiB,UAAmB;AAC9C,UAAM,SAAS,QAAQ;AACvB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,YAAW,SAAS;AAAA,EAClD;AACF;AAaO,IAAM,WAAN,MAAM,kBAAiB,YAAY;AAAA,EACxC,YAAY,U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gB,MAAM;AAC9C,SAAO,YAAY,MAAM,MAAM;AACjC;","names":[]}
1
+ {"version":3,"sources":["../src/utils/errors.ts","../src/utils/encoding.ts","../src/stream/KaitaiStream.ts","../src/parser/schema.ts","../src/parser/KsyParser.ts","../src/interpreter/Context.ts","../src/expression/Token.ts","../src/expression/Lexer.ts","../src/expression/AST.ts","../src/expression/Parser.ts","../src/expression/Evaluator.ts","../src/expression/index.ts","../src/interpreter/TypeInterpreter.ts","../src/index.ts"],"sourcesContent":["/**\n * @fileoverview Custom error classes for Kaitai Struct parsing and validation\n * @module utils/errors\n * @author Fabiano Pinto\n * @license MIT\n */\n\n/**\n * Base error class for all Kaitai Struct errors.\n * All custom errors in this library extend from this class.\n *\n * @class KaitaiError\n * @extends Error\n * @example\n * ```typescript\n * throw new KaitaiError('Something went wrong', 42)\n * ```\n */\nexport class KaitaiError extends Error {\n constructor(\n message: string,\n public position?: number\n ) {\n super(message)\n this.name = 'KaitaiError'\n Object.setPrototypeOf(this, KaitaiError.prototype)\n }\n}\n\n/**\n * Error thrown when validation fails.\n * Used when parsed data doesn't match expected constraints.\n *\n * @class ValidationError\n * @extends KaitaiError\n * @example\n * ```typescript\n * throw new ValidationError('Magic bytes mismatch', 0)\n * ```\n */\nexport class ValidationError extends KaitaiError {\n constructor(message: string, position?: number) {\n super(message, position)\n this.name = 'ValidationError'\n Object.setPrototypeOf(this, ValidationError.prototype)\n }\n}\n\n/**\n * Error thrown when parsing fails.\n * Used for general parsing errors that don't fit other categories.\n *\n * @class ParseError\n * @extends KaitaiError\n * @example\n * ```typescript\n * throw new ParseError('Invalid format structure', 100)\n * ```\n */\nexport class ParseError extends KaitaiError {\n constructor(message: string, position?: number) {\n super(message, position)\n this.name = 'ParseError'\n Object.setPrototypeOf(this, ParseError.prototype)\n }\n}\n\n/**\n * Error thrown when end of stream is reached unexpectedly.\n * Indicates an attempt to read beyond available data.\n *\n * @class EOFError\n * @extends KaitaiError\n * @example\n * ```typescript\n * throw new EOFError('Unexpected end of stream', 1024)\n * ```\n */\nexport class EOFError extends KaitaiError {\n constructor(message: string = 'Unexpected end of stream', position?: number) {\n super(message, position)\n this.name = 'EOFError'\n Object.setPrototypeOf(this, EOFError.prototype)\n }\n}\n\n/**\n * Error thrown when a required feature is not yet implemented.\n * Used during development to mark incomplete functionality.\n *\n * @class NotImplementedError\n * @extends KaitaiError\n * @example\n * ```typescript\n * throw new NotImplementedError('Custom processing')\n * ```\n */\nexport class NotImplementedError extends KaitaiError {\n constructor(feature: string) {\n super(`Feature not yet implemented: ${feature}`)\n this.name = 'NotImplementedError'\n Object.setPrototypeOf(this, NotImplementedError.prototype)\n }\n}\n","/**\n * @fileoverview String encoding and decoding utilities for binary data\n * @module utils/encoding\n * @author Fabiano Pinto\n * @license MIT\n */\n\n/**\n * Decode bytes to string using specified encoding.\n * Supports UTF-8, ASCII, Latin-1, UTF-16LE, and UTF-16BE.\n * Falls back to TextDecoder for other encodings if available.\n *\n * @param bytes - Byte array to decode\n * @param encoding - Character encoding name (e.g., 'UTF-8', 'ASCII')\n * @returns Decoded string\n * @throws {Error} If encoding is not supported\n * @example\n * ```typescript\n * const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f])\n * const str = decodeString(bytes, 'UTF-8') // \"Hello\"\n * ```\n */\nexport function decodeString(bytes: Uint8Array, encoding: string): string {\n // Normalize encoding name\n const normalizedEncoding = encoding.toLowerCase().replace(/[-_]/g, '')\n\n // Handle common encodings\n switch (normalizedEncoding) {\n case 'utf8':\n case 'utf-8':\n return decodeUtf8(bytes)\n\n case 'ascii':\n case 'usascii':\n return decodeAscii(bytes)\n\n case 'utf16':\n case 'utf16le':\n case 'utf-16le':\n return decodeUtf16Le(bytes)\n\n case 'utf16be':\n case 'utf-16be':\n return decodeUtf16Be(bytes)\n\n case 'latin1':\n case 'iso88591':\n case 'iso-8859-1':\n return decodeLatin1(bytes)\n\n default:\n // Try using TextDecoder if available (browser/modern Node.js)\n // eslint-disable-next-line no-undef\n if (typeof TextDecoder !== 'undefined') {\n try {\n // eslint-disable-next-line no-undef\n return new TextDecoder(encoding).decode(bytes)\n } catch {\n throw new Error(`Unsupported encoding: ${encoding}`)\n }\n }\n throw new Error(`Unsupported encoding: ${encoding}`)\n }\n}\n\n/**\n * Decode UTF-8 bytes to string.\n * Handles 1-4 byte UTF-8 sequences including surrogate pairs.\n *\n * @param bytes - UTF-8 encoded byte array\n * @returns Decoded string\n * @private\n */\nfunction decodeUtf8(bytes: Uint8Array): string {\n // eslint-disable-next-line no-undef\n if (typeof TextDecoder !== 'undefined') {\n // eslint-disable-next-line no-undef\n return new TextDecoder('utf-8').decode(bytes)\n }\n\n // Fallback implementation\n let result = ''\n let i = 0\n\n while (i < bytes.length) {\n const byte1 = bytes[i++]\n\n if (byte1 < 0x80) {\n // 1-byte character (ASCII)\n result += String.fromCharCode(byte1)\n } else if (byte1 < 0xe0) {\n // 2-byte character\n const byte2 = bytes[i++]\n result += String.fromCharCode(((byte1 & 0x1f) << 6) | (byte2 & 0x3f))\n } else if (byte1 < 0xf0) {\n // 3-byte character\n const byte2 = bytes[i++]\n const byte3 = bytes[i++]\n result += String.fromCharCode(\n ((byte1 & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f)\n )\n } else {\n // 4-byte character (surrogate pair)\n const byte2 = bytes[i++]\n const byte3 = bytes[i++]\n const byte4 = bytes[i++]\n let codePoint =\n ((byte1 & 0x07) << 18) |\n ((byte2 & 0x3f) << 12) |\n ((byte3 & 0x3f) << 6) |\n (byte4 & 0x3f)\n codePoint -= 0x10000\n result += String.fromCharCode(\n 0xd800 + (codePoint >> 10),\n 0xdc00 + (codePoint & 0x3ff)\n )\n }\n }\n\n return result\n}\n\n/**\n * Decode ASCII bytes to string.\n * Only uses the lower 7 bits of each byte.\n *\n * @param bytes - ASCII encoded byte array\n * @returns Decoded string\n * @private\n */\nfunction decodeAscii(bytes: Uint8Array): string {\n let result = ''\n for (let i = 0; i < bytes.length; i++) {\n result += String.fromCharCode(bytes[i] & 0x7f)\n }\n return result\n}\n\n/**\n * Decode Latin-1 (ISO-8859-1) bytes to string.\n * Each byte directly maps to a Unicode code point.\n *\n * @param bytes - Latin-1 encoded byte array\n * @returns Decoded string\n * @private\n */\nfunction decodeLatin1(bytes: Uint8Array): string {\n let result = ''\n for (let i = 0; i < bytes.length; i++) {\n result += String.fromCharCode(bytes[i])\n }\n return result\n}\n\n/**\n * Decode UTF-16 Little Endian bytes to string.\n * Reads 2 bytes per character in little-endian order.\n *\n * @param bytes - UTF-16LE encoded byte array\n * @returns Decoded string\n * @private\n */\nfunction decodeUtf16Le(bytes: Uint8Array): string {\n // eslint-disable-next-line no-undef\n if (typeof TextDecoder !== 'undefined') {\n // eslint-disable-next-line no-undef\n return new TextDecoder('utf-16le').decode(bytes)\n }\n\n let result = ''\n for (let i = 0; i < bytes.length; i += 2) {\n const charCode = bytes[i] | (bytes[i + 1] << 8)\n result += String.fromCharCode(charCode)\n }\n return result\n}\n\n/**\n * Decode UTF-16 Big Endian bytes to string.\n * Reads 2 bytes per character in big-endian order.\n *\n * @param bytes - UTF-16BE encoded byte array\n * @returns Decoded string\n * @private\n */\nfunction decodeUtf16Be(bytes: Uint8Array): string {\n // eslint-disable-next-line no-undef\n if (typeof TextDecoder !== 'undefined') {\n // eslint-disable-next-line no-undef\n return new TextDecoder('utf-16be').decode(bytes)\n }\n\n let result = ''\n for (let i = 0; i < bytes.length; i += 2) {\n const charCode = (bytes[i] << 8) | bytes[i + 1]\n result += String.fromCharCode(charCode)\n }\n return result\n}\n","/**\n * @fileoverview Binary stream reader for Kaitai Struct\n * @module stream/KaitaiStream\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { EOFError } from '../utils/errors'\nimport { decodeString } from '../utils/encoding'\n\n/**\n * KaitaiStream provides methods for reading binary data with proper type handling\n * and endianness support. It's the core class for parsing binary formats.\n *\n * Supports reading:\n * - Unsigned integers (u1, u2, u4, u8) in both little and big endian\n * - Signed integers (s1, s2, s4, s8) in both little and big endian\n * - Floating point numbers (f4, f8) in both little and big endian\n * - Byte arrays (fixed length, until terminator, or all remaining)\n * - Strings with various encodings\n * - Bit-level data\n *\n * @class KaitaiStream\n * @example\n * ```typescript\n * const buffer = new Uint8Array([0x01, 0x02, 0x03, 0x04])\n * const stream = new KaitaiStream(buffer)\n *\n * const byte = stream.readU1() // Read 1 byte\n * const word = stream.readU2le() // Read 2 bytes little-endian\n * const str = stream.readStr(5, 'UTF-8') // Read 5-byte string\n * ```\n */\nexport class KaitaiStream {\n private buffer: Uint8Array\n private view: DataView\n private _pos: number = 0\n private _bits: number = 0\n private _bitsLeft: number = 0\n\n /**\n * Create a new KaitaiStream from a buffer\n * @param buffer - ArrayBuffer or Uint8Array containing the binary data\n */\n constructor(buffer: ArrayBuffer | Uint8Array) {\n if (buffer instanceof ArrayBuffer) {\n this.buffer = new Uint8Array(buffer)\n this.view = new DataView(buffer)\n } else {\n this.buffer = buffer\n this.view = new DataView(\n buffer.buffer,\n buffer.byteOffset,\n buffer.byteLength\n )\n }\n }\n\n /**\n * Current position in the stream\n */\n get pos(): number {\n return this._pos\n }\n\n set pos(value: number) {\n this._pos = value\n this._bitsLeft = 0 // Reset bit reading when seeking\n }\n\n /**\n * Total size of the stream in bytes\n */\n get size(): number {\n return this.buffer.length\n }\n\n /**\n * Check if we've reached the end of the stream\n */\n isEof(): boolean {\n return this._pos >= this.buffer.length\n }\n\n /**\n * Seek to a specific position in the stream\n * @param pos - Position to seek to\n */\n seek(pos: number): void {\n if (pos < 0 || pos > this.buffer.length) {\n throw new Error(`Invalid seek position: ${pos}`)\n }\n this.pos = pos\n }\n\n /**\n * Ensure we have enough bytes available\n * @param count - Number of bytes needed\n */\n private ensureBytes(count: number): void {\n if (this._pos + count > this.buffer.length) {\n throw new EOFError(\n `Requested ${count} bytes at position ${this._pos}, but only ${\n this.buffer.length - this._pos\n } bytes available`,\n this._pos\n )\n }\n }\n\n // ==================== Unsigned Integers ====================\n\n /**\n * Read 1-byte unsigned integer (0 to 255)\n */\n readU1(): number {\n this.ensureBytes(1)\n return this.buffer[this._pos++]\n }\n\n /**\n * Read 2-byte unsigned integer, little-endian\n */\n readU2le(): number {\n this.ensureBytes(2)\n const value = this.view.getUint16(this._pos, true)\n this._pos += 2\n return value\n }\n\n /**\n * Read 2-byte unsigned integer, big-endian\n */\n readU2be(): number {\n this.ensureBytes(2)\n const value = this.view.getUint16(this._pos, false)\n this._pos += 2\n return value\n }\n\n /**\n * Read 4-byte unsigned integer, little-endian\n */\n readU4le(): number {\n this.ensureBytes(4)\n const value = this.view.getUint32(this._pos, true)\n this._pos += 4\n return value\n }\n\n /**\n * Read 4-byte unsigned integer, big-endian\n */\n readU4be(): number {\n this.ensureBytes(4)\n const value = this.view.getUint32(this._pos, false)\n this._pos += 4\n return value\n }\n\n /**\n * Read 8-byte unsigned integer, little-endian\n * Returns BigInt for values > Number.MAX_SAFE_INTEGER\n */\n readU8le(): bigint {\n this.ensureBytes(8)\n const value = this.view.getBigUint64(this._pos, true)\n this._pos += 8\n return value\n }\n\n /**\n * Read 8-byte unsigned integer, big-endian\n * Returns BigInt for values > Number.MAX_SAFE_INTEGER\n */\n readU8be(): bigint {\n this.ensureBytes(8)\n const value = this.view.getBigUint64(this._pos, false)\n this._pos += 8\n return value\n }\n\n // ==================== Signed Integers ====================\n\n /**\n * Read 1-byte signed integer (-128 to 127)\n */\n readS1(): number {\n this.ensureBytes(1)\n return this.view.getInt8(this._pos++)\n }\n\n /**\n * Read 2-byte signed integer, little-endian\n */\n readS2le(): number {\n this.ensureBytes(2)\n const value = this.view.getInt16(this._pos, true)\n this._pos += 2\n return value\n }\n\n /**\n * Read 2-byte signed integer, big-endian\n */\n readS2be(): number {\n this.ensureBytes(2)\n const value = this.view.getInt16(this._pos, false)\n this._pos += 2\n return value\n }\n\n /**\n * Read 4-byte signed integer, little-endian\n */\n readS4le(): number {\n this.ensureBytes(4)\n const value = this.view.getInt32(this._pos, true)\n this._pos += 4\n return value\n }\n\n /**\n * Read 4-byte signed integer, big-endian\n */\n readS4be(): number {\n this.ensureBytes(4)\n const value = this.view.getInt32(this._pos, false)\n this._pos += 4\n return value\n }\n\n /**\n * Read 8-byte signed integer, little-endian\n * Returns BigInt for values outside Number.MAX_SAFE_INTEGER range\n */\n readS8le(): bigint {\n this.ensureBytes(8)\n const value = this.view.getBigInt64(this._pos, true)\n this._pos += 8\n return value\n }\n\n /**\n * Read 8-byte signed integer, big-endian\n * Returns BigInt for values outside Number.MAX_SAFE_INTEGER range\n */\n readS8be(): bigint {\n this.ensureBytes(8)\n const value = this.view.getBigInt64(this._pos, false)\n this._pos += 8\n return value\n }\n\n // ==================== Floating Point ====================\n\n /**\n * Read 4-byte IEEE 754 single-precision float, little-endian\n */\n readF4le(): number {\n this.ensureBytes(4)\n const value = this.view.getFloat32(this._pos, true)\n this._pos += 4\n return value\n }\n\n /**\n * Read 4-byte IEEE 754 single-precision float, big-endian\n */\n readF4be(): number {\n this.ensureBytes(4)\n const value = this.view.getFloat32(this._pos, false)\n this._pos += 4\n return value\n }\n\n /**\n * Read 8-byte IEEE 754 double-precision float, little-endian\n */\n readF8le(): number {\n this.ensureBytes(8)\n const value = this.view.getFloat64(this._pos, true)\n this._pos += 8\n return value\n }\n\n /**\n * Read 8-byte IEEE 754 double-precision float, big-endian\n */\n readF8be(): number {\n this.ensureBytes(8)\n const value = this.view.getFloat64(this._pos, false)\n this._pos += 8\n return value\n }\n\n // ==================== Byte Arrays ====================\n\n /**\n * Read a fixed number of bytes\n * @param length - Number of bytes to read\n */\n readBytes(length: number): Uint8Array {\n this.ensureBytes(length)\n const bytes = this.buffer.slice(this._pos, this._pos + length)\n this._pos += length\n return bytes\n }\n\n /**\n * Read all remaining bytes until end of stream\n */\n readBytesFull(): Uint8Array {\n const bytes = this.buffer.slice(this._pos)\n this._pos = this.buffer.length\n return bytes\n }\n\n /**\n * Read bytes until a terminator byte is found\n * @param term - Terminator byte value\n * @param include - Include terminator in result\n * @param consume - Consume terminator from stream\n * @param eosError - Throw error if EOS reached before terminator\n */\n readBytesterm(\n term: number,\n include: boolean = false,\n consume: boolean = true,\n eosError: boolean = true\n ): Uint8Array {\n const start = this._pos\n let end = start\n\n // Find terminator\n while (end < this.buffer.length && this.buffer[end] !== term) {\n end++\n }\n\n // Check if we found the terminator\n const foundTerm = end < this.buffer.length\n\n if (!foundTerm && eosError) {\n throw new EOFError(\n `Terminator byte ${term} not found before end of stream`,\n this._pos\n )\n }\n\n // Extract bytes\n const includeEnd = include && foundTerm ? end + 1 : end\n const bytes = this.buffer.slice(start, includeEnd)\n\n // Update position\n if (foundTerm && consume) {\n this._pos = end + 1\n } else {\n this._pos = end\n }\n\n return bytes\n }\n\n // ==================== Strings ====================\n\n /**\n * Read a fixed-length string\n * @param length - Number of bytes to read\n * @param encoding - Character encoding (default: UTF-8)\n */\n readStr(length: number, encoding: string = 'UTF-8'): string {\n const bytes = this.readBytes(length)\n return decodeString(bytes, encoding)\n }\n\n /**\n * Read a null-terminated string\n * @param encoding - Character encoding (default: UTF-8)\n * @param term - Terminator byte (default: 0)\n * @param include - Include terminator in result\n * @param consume - Consume terminator from stream\n * @param eosError - Throw error if EOS reached before terminator\n */\n readStrz(\n encoding: string = 'UTF-8',\n term: number = 0,\n include: boolean = false,\n consume: boolean = true,\n eosError: boolean = true\n ): string {\n const bytes = this.readBytesterm(term, include, consume, eosError)\n return decodeString(bytes, encoding)\n }\n\n // ==================== Bit-level Reading ====================\n\n /**\n * Align bit reading to byte boundary\n */\n alignToByte(): void {\n this._bitsLeft = 0\n }\n\n /**\n * Read specified number of bits as unsigned integer (big-endian)\n * @param n - Number of bits to read (1-64)\n */\n readBitsIntBe(n: number): bigint {\n if (n < 1 || n > 64) {\n throw new Error(`Invalid bit count: ${n}. Must be between 1 and 64`)\n }\n\n let result = 0n\n\n for (let bitsNeeded = n; bitsNeeded > 0; ) {\n if (this._bitsLeft === 0) {\n this._bits = this.readU1()\n this._bitsLeft = 8\n }\n\n const bitsToRead = Math.min(bitsNeeded, this._bitsLeft)\n const mask = (1 << bitsToRead) - 1\n const shift = this._bitsLeft - bitsToRead\n\n result =\n (result << BigInt(bitsToRead)) | BigInt((this._bits >> shift) & mask)\n\n this._bitsLeft -= bitsToRead\n bitsNeeded -= bitsToRead\n }\n\n return result\n }\n\n /**\n * Read specified number of bits as unsigned integer (little-endian)\n * @param n - Number of bits to read (1-64)\n */\n readBitsIntLe(n: number): bigint {\n if (n < 1 || n > 64) {\n throw new Error(`Invalid bit count: ${n}. Must be between 1 and 64`)\n }\n\n let result = 0n\n let bitPos = 0\n\n for (let bitsNeeded = n; bitsNeeded > 0; ) {\n if (this._bitsLeft === 0) {\n this._bits = this.readU1()\n this._bitsLeft = 8\n }\n\n const bitsToRead = Math.min(bitsNeeded, this._bitsLeft)\n const mask = (1 << bitsToRead) - 1\n\n result |= BigInt(this._bits & mask) << BigInt(bitPos)\n\n this._bits >>= bitsToRead\n this._bitsLeft -= bitsToRead\n bitsNeeded -= bitsToRead\n bitPos += bitsToRead\n }\n\n return result\n }\n\n // ==================== Utility Methods ====================\n\n /**\n * Get the underlying buffer\n */\n getBuffer(): Uint8Array {\n return this.buffer\n }\n\n /**\n * Create a substream from current position with specified size\n * @param size - Size of the substream in bytes\n */\n substream(size: number): KaitaiStream {\n this.ensureBytes(size)\n const subBuffer = this.buffer.slice(this._pos, this._pos + size)\n this._pos += size\n return new KaitaiStream(subBuffer)\n }\n}\n","/**\n * @fileoverview Type definitions for Kaitai Struct YAML schema (.ksy files)\n * @module parser/schema\n * @author Fabiano Pinto\n * @license MIT\n */\n\n/**\n * Root schema definition for a Kaitai Struct format.\n * Represents a complete .ksy file structure.\n *\n * @interface KsySchema\n * @example\n * ```typescript\n * const schema: KsySchema = {\n * meta: {\n * id: 'my_format',\n * endian: 'le'\n * },\n * seq: [\n * { id: 'magic', contents: [0x4D, 0x5A] },\n * { id: 'version', type: 'u2' }\n * ]\n * }\n * ```\n */\nexport interface KsySchema {\n /** Metadata about the format */\n meta: MetaSpec\n\n /** Sequential attributes (fields read in order) */\n seq?: AttributeSpec[]\n\n /** Named instances (lazy-evaluated fields) */\n instances?: Record<string, InstanceSpec>\n\n /** Nested type definitions */\n types?: Record<string, KsySchema>\n\n /** Enum definitions (named integer constants) */\n enums?: Record<string, EnumSpec>\n\n /** Documentation for this type */\n doc?: string\n\n /** Reference to documentation */\n 'doc-ref'?: string | string[]\n\n /** Parameters for parametric types */\n params?: ParamSpec[]\n}\n\n/**\n * Metadata section of a Kaitai Struct schema.\n * Contains information about the format itself.\n *\n * @interface MetaSpec\n */\nexport interface MetaSpec {\n /** Identifier for this format (required) */\n id: string\n\n /** Title/name of the format */\n title?: string\n\n /** Application that uses this format */\n application?: string | string[]\n\n /** File extension(s) for this format */\n 'file-extension'?: string | string[]\n\n /** MIME type(s) for this format */\n xref?: Record<string, string | string[]>\n\n /** License for the format specification */\n license?: string\n\n /** KS compatibility version */\n 'ks-version'?: string | number\n\n /** Debug mode flag */\n 'ks-debug'?: boolean\n\n /** Opaque types flag */\n 'ks-opaque-types'?: boolean\n\n /** Default endianness for the format */\n endian?: Endianness | EndianExpression\n\n /** Default encoding for strings */\n encoding?: string\n\n /** Imported type definitions */\n imports?: string[]\n\n /** Documentation */\n doc?: string\n\n /** Reference to documentation */\n 'doc-ref'?: string | string[]\n}\n\n/**\n * Endianness specification.\n */\nexport type Endianness = 'le' | 'be'\n\n/**\n * Expression-based endianness (switch on expression).\n *\n * @interface EndianExpression\n */\nexport interface EndianExpression {\n /** Expression to evaluate */\n 'switch-on': string\n\n /** Cases mapping values to endianness */\n cases: Record<string, Endianness>\n}\n\n/**\n * Attribute specification for sequential fields.\n * Describes how to read a single field from the stream.\n *\n * @interface AttributeSpec\n */\nexport interface AttributeSpec {\n /** Field identifier (name) */\n id?: string\n\n /** Data type to read */\n type?: string | SwitchType\n\n /** Arguments for parametric types */\n 'type-args'?: Array<string | number | boolean>\n\n /** Size of the field (in bytes or expression) */\n size?: number | string\n\n /** Size until specific byte value */\n 'size-eos'?: boolean\n\n /** Repeat specification */\n repeat?: RepeatSpec\n\n /** Number of repetitions (for repeat: expr) */\n 'repeat-expr'?: string | number\n\n /** Condition for repetition (for repeat: until) */\n 'repeat-until'?: string\n\n /** Conditional parsing */\n if?: string\n\n /** Expected contents (validation) */\n contents?: number[] | string\n\n /** String encoding */\n encoding?: string\n\n /** Pad right to alignment */\n 'pad-right'?: number\n\n /** Terminator byte for strings/arrays */\n terminator?: number\n\n /** Include terminator in result */\n include?: boolean\n\n /** Consume terminator from stream */\n consume?: boolean\n\n /** Throw error if terminator not found */\n 'eos-error'?: boolean\n\n /** Enum type name */\n enum?: string\n\n /** Absolute position to seek to */\n pos?: number | string\n\n /** Custom I/O stream */\n io?: string\n\n /** Processing directive (compression, encryption, etc.) */\n process?: string | ProcessSpec\n\n /** Documentation */\n doc?: string\n\n /** Reference to documentation */\n 'doc-ref'?: string | string[]\n\n /** Original field ID (for reference) */\n '-orig-id'?: string\n}\n\n/**\n * Instance specification for lazy-evaluated fields.\n * Similar to AttributeSpec but for instances section.\n *\n * @interface InstanceSpec\n */\nexport interface InstanceSpec extends Omit<AttributeSpec, 'id'> {\n /** Value instance (calculated field) */\n value?: string | number | boolean\n\n /** Position in stream (for pos instances) */\n pos?: number | string\n\n /** Custom I/O stream */\n io?: string\n}\n\n/**\n * Repeat specification types.\n */\nexport type RepeatSpec = 'expr' | 'eos' | 'until'\n\n/**\n * Switch-based type selection.\n * Allows different types based on an expression value.\n *\n * @interface SwitchType\n */\nexport interface SwitchType {\n /** Expression to evaluate for switching */\n 'switch-on': string\n\n /** Cases mapping values to types */\n cases: Record<string, string>\n\n /** Default type if no case matches */\n default?: string\n}\n\n/**\n * Processing specification for data transformation.\n *\n * @type ProcessSpec\n */\nexport type ProcessSpec = string | ProcessObject\n\n/**\n * Processing object with algorithm and parameters.\n *\n * @interface ProcessObject\n */\nexport interface ProcessObject {\n /** Processing algorithm */\n algorithm: string\n\n /** Algorithm parameters */\n [key: string]: unknown\n}\n\n/**\n * Enum specification (named integer constants).\n *\n * @type EnumSpec\n */\nexport type EnumSpec = Record<string | number, string | number>\n\n/**\n * Parameter specification for parametric types.\n *\n * @interface ParamSpec\n */\nexport interface ParamSpec {\n /** Parameter identifier */\n id: string\n\n /** Parameter type */\n type?: string\n\n /** Documentation */\n doc?: string\n\n /** Reference to documentation */\n 'doc-ref'?: string | string[]\n}\n\n/**\n * Validation result for schema validation.\n *\n * @interface ValidationResult\n */\nexport interface ValidationResult {\n /** Whether the schema is valid */\n valid: boolean\n\n /** Validation errors */\n errors: ValidationError[]\n\n /** Validation warnings */\n warnings: ValidationWarning[]\n}\n\n/**\n * Validation error.\n *\n * @interface ValidationError\n */\nexport interface ValidationError {\n /** Error message */\n message: string\n\n /** Path to the error in the schema */\n path: string[]\n\n /** Error code */\n code: string\n}\n\n/**\n * Validation warning.\n *\n * @interface ValidationWarning\n */\nexport interface ValidationWarning {\n /** Warning message */\n message: string\n\n /** Path to the warning in the schema */\n path: string[]\n\n /** Warning code */\n code: string\n}\n\n/**\n * Built-in Kaitai Struct types.\n */\nexport const BUILTIN_TYPES = [\n // Unsigned integers\n 'u1',\n 'u2',\n 'u2le',\n 'u2be',\n 'u4',\n 'u4le',\n 'u4be',\n 'u8',\n 'u8le',\n 'u8be',\n // Signed integers\n 's1',\n 's2',\n 's2le',\n 's2be',\n 's4',\n 's4le',\n 's4be',\n 's8',\n 's8le',\n 's8be',\n // Floating point\n 'f4',\n 'f4le',\n 'f4be',\n 'f8',\n 'f8le',\n 'f8be',\n // String\n 'str',\n 'strz',\n] as const\n\n/**\n * Type guard to check if a type is a built-in type.\n *\n * @param type - Type name to check\n * @returns True if the type is built-in\n */\nexport function isBuiltinType(type: string): boolean {\n return (BUILTIN_TYPES as readonly string[]).includes(type)\n}\n\n/**\n * Get the default endianness for a type.\n * Returns the endianness suffix if present, otherwise undefined.\n *\n * @param type - Type name\n * @returns Endianness ('le', 'be', or undefined for default)\n */\nexport function getTypeEndianness(type: string): Endianness | undefined {\n if (type.endsWith('le')) return 'le'\n if (type.endsWith('be')) return 'be'\n return undefined\n}\n\n/**\n * Get the base type without endianness suffix.\n *\n * @param type - Type name\n * @returns Base type name\n * @example\n * ```typescript\n * getBaseType('u4le') // returns 'u4'\n * getBaseType('s2be') // returns 's2'\n * getBaseType('str') // returns 'str'\n * ```\n */\nexport function getBaseType(type: string): string {\n if (type.endsWith('le') || type.endsWith('be')) {\n return type.slice(0, -2)\n }\n return type\n}\n\n/**\n * Check if a type is an integer type.\n *\n * @param type - Type name\n * @returns True if the type is an integer\n */\nexport function isIntegerType(type: string): boolean {\n const base = getBaseType(type)\n return /^[us][1248]$/.test(base)\n}\n\n/**\n * Check if a type is a floating point type.\n *\n * @param type - Type name\n * @returns True if the type is a float\n */\nexport function isFloatType(type: string): boolean {\n const base = getBaseType(type)\n return /^f[48]$/.test(base)\n}\n\n/**\n * Check if a type is a string type.\n *\n * @param type - Type name\n * @returns True if the type is a string\n */\nexport function isStringType(type: string): boolean {\n return type === 'str' || type === 'strz'\n}\n","/**\n * @fileoverview Parser for Kaitai Struct YAML (.ksy) files\n * @module parser/KsyParser\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { parse as parseYaml } from 'yaml'\nimport {\n ParseError,\n ValidationError as KaitaiValidationError,\n} from '../utils/errors'\nimport type {\n KsySchema,\n ValidationResult,\n ValidationError,\n ValidationWarning,\n} from './schema'\n\n/**\n * Parser for Kaitai Struct YAML (.ksy) format definitions.\n * Converts YAML text into typed schema objects and validates them.\n *\n * @class KsyParser\n * @example\n * ```typescript\n * const parser = new KsyParser()\n * const schema = parser.parse(ksyYamlString)\n * ```\n */\nexport class KsyParser {\n /**\n * Parse a .ksy YAML string into a typed schema object.\n *\n * @param yaml - YAML string containing the .ksy definition\n * @param options - Parsing options\n * @returns Parsed and validated schema\n * @throws {ParseError} If YAML parsing fails\n * @throws {ValidationError} If schema validation fails\n */\n parse(yaml: string, options: ParseOptions = {}): KsySchema {\n const { validate = true, strict = false } = options\n\n // Parse YAML\n let parsed: unknown\n try {\n parsed = parseYaml(yaml)\n } catch (error) {\n throw new ParseError(\n `Failed to parse YAML: ${error instanceof Error ? error.message : String(error)}`\n )\n }\n\n // Ensure we have an object\n if (typeof parsed !== 'object' || parsed === null) {\n throw new ParseError('KSY file must contain an object')\n }\n\n const schema = parsed as KsySchema\n\n // Validate if requested\n if (validate) {\n const result = this.validate(schema, { strict })\n if (!result.valid) {\n const errorMessages = result.errors.map((e) => e.message).join('; ')\n throw new KaitaiValidationError(\n `Schema validation failed: ${errorMessages}`\n )\n }\n\n // Log warnings if any\n if (result.warnings.length > 0 && !strict) {\n // eslint-disable-next-line no-undef\n console.warn(\n 'Schema validation warnings:',\n result.warnings.map((w) => w.message)\n )\n }\n }\n\n return schema\n }\n\n /**\n * Validate a schema object.\n *\n * @param schema - Schema to validate\n * @param options - Validation options\n * @returns Validation result with errors and warnings\n */\n validate(\n schema: KsySchema,\n options: ValidationOptions = {}\n ): ValidationResult {\n const { strict = false, isNested = false } = options\n const errors: ValidationError[] = []\n const warnings: ValidationWarning[] = []\n\n // Validate meta section (required for root schemas, optional for nested)\n if (!schema.meta && !isNested) {\n errors.push({\n message: 'Missing required \"meta\" section',\n path: [],\n code: 'MISSING_META',\n })\n } else if (schema.meta) {\n // Validate meta.id (required)\n if (!schema.meta.id) {\n errors.push({\n message: 'Missing required \"meta.id\" field',\n path: ['meta'],\n code: 'MISSING_META_ID',\n })\n } else if (typeof schema.meta.id !== 'string') {\n errors.push({\n message: '\"meta.id\" must be a string',\n path: ['meta', 'id'],\n code: 'INVALID_META_ID_TYPE',\n })\n } else if (!/^[a-z][a-z0-9_]*$/.test(schema.meta.id)) {\n warnings.push({\n message: '\"meta.id\" should follow snake_case naming convention',\n path: ['meta', 'id'],\n code: 'META_ID_NAMING',\n })\n }\n\n // Validate endianness\n if (schema.meta.endian) {\n if (\n typeof schema.meta.endian === 'string' &&\n schema.meta.endian !== 'le' &&\n schema.meta.endian !== 'be'\n ) {\n errors.push({\n message: '\"meta.endian\" must be \"le\" or \"be\"',\n path: ['meta', 'endian'],\n code: 'INVALID_ENDIAN',\n })\n }\n }\n }\n\n // Validate seq section\n if (schema.seq) {\n if (!Array.isArray(schema.seq)) {\n errors.push({\n message: '\"seq\" must be an array',\n path: ['seq'],\n code: 'INVALID_SEQ_TYPE',\n })\n } else {\n schema.seq.forEach((attr, index) => {\n this.validateAttribute(\n attr as Record<string, unknown>,\n ['seq', String(index)],\n errors,\n warnings,\n strict\n )\n })\n }\n }\n\n // Validate instances section\n if (schema.instances) {\n if (typeof schema.instances !== 'object') {\n errors.push({\n message: '\"instances\" must be an object',\n path: ['instances'],\n code: 'INVALID_INSTANCES_TYPE',\n })\n } else {\n Object.entries(schema.instances).forEach(([key, instance]) => {\n this.validateAttribute(\n instance as Record<string, unknown>,\n ['instances', key],\n errors,\n warnings,\n strict\n )\n })\n }\n }\n\n // Validate types section\n if (schema.types) {\n if (typeof schema.types !== 'object') {\n errors.push({\n message: '\"types\" must be an object',\n path: ['types'],\n code: 'INVALID_TYPES_TYPE',\n })\n } else {\n Object.entries(schema.types).forEach(([key, type]) => {\n // Nested types don't require meta section\n const typeResult = this.validate(type, { ...options, isNested: true })\n errors.push(\n ...typeResult.errors.map((e) => ({\n ...e,\n path: ['types', key, ...e.path],\n }))\n )\n warnings.push(\n ...typeResult.warnings.map((w) => ({\n ...w,\n path: ['types', key, ...w.path],\n }))\n )\n })\n }\n }\n\n // Validate enums section\n if (schema.enums) {\n if (typeof schema.enums !== 'object') {\n errors.push({\n message: '\"enums\" must be an object',\n path: ['enums'],\n code: 'INVALID_ENUMS_TYPE',\n })\n }\n }\n\n return {\n valid: errors.length === 0 && (strict ? warnings.length === 0 : true),\n errors,\n warnings,\n }\n }\n\n /**\n * Validate an attribute specification.\n *\n * @param attr - Attribute to validate\n * @param path - Path to this attribute in the schema\n * @param errors - Array to collect errors\n * @param warnings - Array to collect warnings\n * @param strict - Whether to be strict about warnings\n * @private\n */\n private validateAttribute(\n attr: Record<string, unknown>,\n path: string[],\n errors: ValidationError[],\n warnings: ValidationWarning[],\n _strict: boolean\n ): void {\n // Validate id naming\n if (attr.id && typeof attr.id === 'string') {\n if (!/^[a-z][a-z0-9_]*$/.test(attr.id)) {\n warnings.push({\n message: `Field \"${attr.id}\" should follow snake_case naming convention`,\n path: [...path, 'id'],\n code: 'FIELD_ID_NAMING',\n })\n }\n }\n\n // Validate repeat\n if (attr.repeat) {\n if (\n attr.repeat !== 'expr' &&\n attr.repeat !== 'eos' &&\n attr.repeat !== 'until'\n ) {\n errors.push({\n message: '\"repeat\" must be \"expr\", \"eos\", or \"until\"',\n path: [...path, 'repeat'],\n code: 'INVALID_REPEAT',\n })\n }\n\n // Check for required fields based on repeat type\n if (attr.repeat === 'expr' && !attr['repeat-expr']) {\n errors.push({\n message: '\"repeat-expr\" is required when repeat is \"expr\"',\n path: [...path, 'repeat-expr'],\n code: 'MISSING_REPEAT_EXPR',\n })\n }\n\n if (attr.repeat === 'until' && !attr['repeat-until']) {\n errors.push({\n message: '\"repeat-until\" is required when repeat is \"until\"',\n path: [...path, 'repeat-until'],\n code: 'MISSING_REPEAT_UNTIL',\n })\n }\n }\n\n // Validate size-eos\n if (attr['size-eos'] && attr.size) {\n warnings.push({\n message: '\"size-eos\" and \"size\" are mutually exclusive',\n path: [...path],\n code: 'SIZE_EOS_WITH_SIZE',\n })\n }\n\n // Validate contents\n if (attr.contents) {\n if (!Array.isArray(attr.contents) && typeof attr.contents !== 'string') {\n errors.push({\n message: '\"contents\" must be an array or string',\n path: [...path, 'contents'],\n code: 'INVALID_CONTENTS_TYPE',\n })\n }\n }\n }\n\n /**\n * Parse multiple .ksy files and resolve imports.\n *\n * @param mainYaml - Main .ksy file content\n * @param imports - Map of import names to their YAML content\n * @param options - Parsing options\n * @returns Parsed schema with resolved imports\n */\n parseWithImports(\n mainYaml: string,\n _imports: Map<string, string>,\n options: ParseOptions = {}\n ): KsySchema {\n // Parse main schema\n const mainSchema = this.parse(mainYaml, options)\n\n // TODO: Resolve imports\n // This will be implemented when we add import support\n\n return mainSchema\n }\n}\n\n/**\n * Options for parsing .ksy files.\n *\n * @interface ParseOptions\n */\nexport interface ParseOptions {\n /** Whether to validate the schema (default: true) */\n validate?: boolean\n\n /** Whether to treat warnings as errors (default: false) */\n strict?: boolean\n}\n\n/**\n * Options for schema validation.\n *\n * @interface ValidationOptions\n */\nexport interface ValidationOptions {\n /** Whether to treat warnings as errors (default: false) */\n strict?: boolean\n\n /** Whether this is a nested type (meta section optional) (default: false) */\n isNested?: boolean\n}\n","/**\n * @fileoverview Execution context for Kaitai Struct parsing\n * @module interpreter/Context\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport type { KaitaiStream } from '../stream'\nimport type { EnumSpec } from '../parser/schema'\n\n/**\n * Execution context for parsing operations.\n * Provides access to the current object, parent, root, and stream.\n *\n * @class Context\n * @example\n * ```typescript\n * const context = new Context(stream, root)\n * context.pushParent(currentObject)\n * const value = evaluator.evaluate(expression, context)\n * context.popParent()\n * ```\n */\nexport class Context {\n /** Stack of parent objects */\n private parentStack: unknown[] = []\n\n /** Current object being parsed */\n private _current: Record<string, unknown> = {}\n\n /** Enum definitions from schema */\n private _enums: Record<string, EnumSpec> = {}\n\n /**\n * Create a new execution context.\n *\n * @param _io - Binary stream being read\n * @param _root - Root object of the parse tree\n * @param _parent - Parent object (optional)\n * @param enums - Enum definitions from schema (optional)\n */\n constructor(\n private _io: KaitaiStream,\n private _root: unknown = null,\n _parent: unknown = null,\n enums?: Record<string, EnumSpec>\n ) {\n if (_parent !== null) {\n this.parentStack.push(_parent)\n }\n if (enums) {\n this._enums = enums\n }\n }\n\n /**\n * Get the current I/O stream.\n * Accessible in expressions as `_io`.\n *\n * @returns Current stream\n */\n get io(): KaitaiStream {\n return this._io\n }\n\n /**\n * Get the root object.\n * Accessible in expressions as `_root`.\n *\n * @returns Root object\n */\n get root(): unknown {\n return this._root\n }\n\n /**\n * Get the parent object.\n * Accessible in expressions as `_parent`.\n *\n * @returns Parent object or null if at root\n */\n get parent(): unknown {\n return this.parentStack.length > 0\n ? this.parentStack[this.parentStack.length - 1]\n : null\n }\n\n /**\n * Get the current object being parsed.\n * Used to access fields defined earlier in the sequence.\n *\n * @returns Current object\n */\n get current(): Record<string, unknown> {\n return this._current\n }\n\n /**\n * Set the current object.\n *\n * @param obj - Object to set as current\n */\n set current(obj: Record<string, unknown>) {\n this._current = obj\n }\n\n /**\n * Push a new parent onto the stack.\n * Used when entering a nested type.\n *\n * @param parent - Parent object to push\n */\n pushParent(parent: unknown): void {\n this.parentStack.push(parent)\n }\n\n /**\n * Pop the current parent from the stack.\n * Used when exiting a nested type.\n *\n * @returns The popped parent object\n */\n popParent(): unknown {\n return this.parentStack.pop()\n }\n\n /**\n * Get a value from the context by path.\n * Supports special names: _io, _root, _parent, _index.\n *\n * @param name - Name or path to resolve\n * @returns Resolved value\n */\n resolve(name: string): unknown {\n // Handle special names\n switch (name) {\n case '_io':\n return this._io\n case '_root':\n return this._root\n case '_parent':\n return this.parent\n case '_index':\n // Index is set externally during repetition\n return (this._current as Record<string, unknown>)['_index']\n default:\n // Look in current object\n if (name in this._current) {\n return this._current[name]\n }\n // Not found\n return undefined\n }\n }\n\n /**\n * Set a value in the current object.\n *\n * @param name - Field name\n * @param value - Value to set\n */\n set(name: string, value: unknown): void {\n this._current[name] = value\n }\n\n /**\n * Get enum value by name.\n * Used for enum access in expressions (EnumName::value).\n *\n * @param enumName - Name of the enum\n * @param valueName - Name of the enum value\n * @returns Enum value (number) or undefined\n */\n getEnumValue(enumName: string, valueName: string): unknown {\n const enumDef = this._enums[enumName]\n if (!enumDef) {\n return undefined\n }\n\n // Enum definitions map integer values to string names\n // e.g., { 0: \"unknown\", 1: \"text\" }\n // We need to reverse-lookup: given \"text\", return 1\n for (const [key, value] of Object.entries(enumDef)) {\n if (value === valueName) {\n // Convert key to number\n const numKey = Number(key)\n return isNaN(numKey) ? key : numKey\n }\n }\n\n return undefined\n }\n\n /**\n * Check if an enum exists.\n *\n * @param enumName - Name of the enum\n * @returns True if enum exists\n */\n hasEnum(enumName: string): boolean {\n return enumName in this._enums\n }\n\n /**\n * Create a child context for nested parsing.\n * The current object becomes the parent in the child context.\n *\n * @param stream - Stream for the child context (defaults to current stream)\n * @returns New child context\n */\n createChild(stream?: KaitaiStream): Context {\n const childContext = new Context(\n stream || this._io,\n this._root || this._current,\n this._current,\n this._enums\n )\n return childContext\n }\n\n /**\n * Clone this context.\n * Creates a shallow copy with the same stream, root, and parent.\n *\n * @returns Cloned context\n */\n clone(): Context {\n const cloned = new Context(this._io, this._root, this.parent, this._enums)\n cloned._current = { ...this._current }\n cloned.parentStack = [...this.parentStack]\n return cloned\n }\n}\n","/**\n * @fileoverview Token types for Kaitai Struct expression language\n * @module expression/Token\n * @author Fabiano Pinto\n * @license MIT\n */\n\n/**\n * Token types in the expression language.\n */\nexport enum TokenType {\n // Literals\n NUMBER = 'NUMBER',\n STRING = 'STRING',\n BOOLEAN = 'BOOLEAN',\n IDENTIFIER = 'IDENTIFIER',\n\n // Operators\n PLUS = 'PLUS', // +\n MINUS = 'MINUS', // -\n STAR = 'STAR', // *\n SLASH = 'SLASH', // /\n PERCENT = 'PERCENT', // %\n\n // Comparison\n LT = 'LT', // <\n LE = 'LE', // <=\n GT = 'GT', // >\n GE = 'GE', // >=\n EQ = 'EQ', // ==\n NE = 'NE', // !=\n\n // Bitwise\n LSHIFT = 'LSHIFT', // <<\n RSHIFT = 'RSHIFT', // >>\n AMPERSAND = 'AMPERSAND', // &\n PIPE = 'PIPE', // |\n CARET = 'CARET', // ^\n\n // Logical\n AND = 'AND', // and\n OR = 'OR', // or\n NOT = 'NOT', // not\n\n // Ternary\n QUESTION = 'QUESTION', // ?\n COLON = 'COLON', // :\n\n // Grouping\n LPAREN = 'LPAREN', // (\n RPAREN = 'RPAREN', // )\n LBRACKET = 'LBRACKET', // [\n RBRACKET = 'RBRACKET', // ]\n\n // Access\n DOT = 'DOT', // .\n DOUBLE_COLON = 'DOUBLE_COLON', // ::\n COMMA = 'COMMA', // ,\n\n // Special\n EOF = 'EOF',\n}\n\n/**\n * Token in the expression language.\n *\n * @interface Token\n */\nexport interface Token {\n /** Token type */\n type: TokenType\n\n /** Token value (for literals and identifiers) */\n value: string | number | boolean | null\n\n /** Position in the source string */\n position: number\n}\n\n/**\n * Create a token.\n *\n * @param type - Token type\n * @param value - Token value\n * @param position - Position in source\n * @returns Token object\n */\nexport function createToken(\n type: TokenType,\n value: string | number | boolean | null = null,\n position: number = 0\n): Token {\n return { type, value, position }\n}\n","/**\n * @fileoverview Lexer for Kaitai Struct expression language\n * @module expression/Lexer\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { ParseError } from '../utils/errors'\nimport { Token, TokenType, createToken } from './Token'\n\n/**\n * Lexer for tokenizing Kaitai Struct expressions.\n * Converts expression strings into a stream of tokens.\n *\n * @class Lexer\n * @example\n * ```typescript\n * const lexer = new Lexer('field1 + field2 * 2')\n * const tokens = lexer.tokenize()\n * ```\n */\nexport class Lexer {\n private input: string\n private position: number = 0\n private current: string | null = null\n\n /**\n * Create a new lexer.\n *\n * @param input - Expression string to tokenize\n */\n constructor(input: string) {\n this.input = input\n this.current = input.length > 0 ? input[0] : null\n }\n\n /**\n * Tokenize the entire input string.\n *\n * @returns Array of tokens\n * @throws {ParseError} If invalid syntax is encountered\n */\n tokenize(): Token[] {\n const tokens: Token[] = []\n\n while (this.current !== null) {\n // Skip whitespace\n if (this.isWhitespace(this.current)) {\n this.skipWhitespace()\n continue\n }\n\n // Numbers\n if (this.isDigit(this.current)) {\n tokens.push(this.readNumber())\n continue\n }\n\n // Identifiers and keywords\n if (this.isIdentifierStart(this.current)) {\n tokens.push(this.readIdentifierOrKeyword())\n continue\n }\n\n // Strings\n if (this.current === '\"' || this.current === \"'\") {\n tokens.push(this.readString())\n continue\n }\n\n // Operators and punctuation\n const token = this.readOperator()\n if (token) {\n tokens.push(token)\n continue\n }\n\n throw new ParseError(\n `Unexpected character: ${this.current}`,\n this.position\n )\n }\n\n tokens.push(createToken(TokenType.EOF, null, this.position))\n return tokens\n }\n\n /**\n * Advance to the next character.\n * @private\n */\n private advance(): void {\n this.position++\n this.current =\n this.position < this.input.length ? this.input[this.position] : null\n }\n\n /**\n * Peek at the next character without advancing.\n * @private\n */\n private peek(offset: number = 1): string | null {\n const pos = this.position + offset\n return pos < this.input.length ? this.input[pos] : null\n }\n\n /**\n * Check if character is whitespace.\n * @private\n */\n private isWhitespace(char: string): boolean {\n return /\\s/.test(char)\n }\n\n /**\n * Check if character is a digit.\n * @private\n */\n private isDigit(char: string): boolean {\n return /[0-9]/.test(char)\n }\n\n /**\n * Check if character can start an identifier.\n * @private\n */\n private isIdentifierStart(char: string): boolean {\n return /[a-zA-Z_]/.test(char)\n }\n\n /**\n * Check if character can be part of an identifier.\n * @private\n */\n private isIdentifierPart(char: string): boolean {\n return /[a-zA-Z0-9_]/.test(char)\n }\n\n /**\n * Skip whitespace characters.\n * @private\n */\n private skipWhitespace(): void {\n while (this.current !== null && this.isWhitespace(this.current)) {\n this.advance()\n }\n }\n\n /**\n * Read a number token.\n * @private\n */\n private readNumber(): Token {\n const start = this.position\n let value = ''\n\n // Handle hex numbers (0x...)\n if (this.current === '0' && this.peek() === 'x') {\n value += this.current\n this.advance()\n value += this.current\n this.advance()\n\n while (this.current !== null && /[0-9a-fA-F]/.test(this.current)) {\n value += this.current\n this.advance()\n }\n\n return createToken(TokenType.NUMBER, parseInt(value, 16), start)\n }\n\n // Regular decimal number\n while (this.current !== null && this.isDigit(this.current)) {\n value += this.current\n this.advance()\n }\n\n // Handle decimal point\n if (this.current === '.' && this.peek() && this.isDigit(this.peek()!)) {\n value += this.current\n this.advance()\n\n while (this.current !== null && this.isDigit(this.current)) {\n value += this.current\n this.advance()\n }\n\n return createToken(TokenType.NUMBER, parseFloat(value), start)\n }\n\n return createToken(TokenType.NUMBER, parseInt(value, 10), start)\n }\n\n /**\n * Read an identifier or keyword token.\n * @private\n */\n private readIdentifierOrKeyword(): Token {\n const start = this.position\n let value = ''\n\n while (this.current !== null && this.isIdentifierPart(this.current)) {\n value += this.current\n this.advance()\n }\n\n // Check for keywords\n switch (value) {\n case 'true':\n return createToken(TokenType.BOOLEAN, true, start)\n case 'false':\n return createToken(TokenType.BOOLEAN, false, start)\n case 'and':\n return createToken(TokenType.AND, value, start)\n case 'or':\n return createToken(TokenType.OR, value, start)\n case 'not':\n return createToken(TokenType.NOT, value, start)\n default:\n return createToken(TokenType.IDENTIFIER, value, start)\n }\n }\n\n /**\n * Read a string token.\n * @private\n */\n private readString(): Token {\n const start = this.position\n const quote = this.current\n let value = ''\n\n this.advance() // Skip opening quote\n\n while (this.current !== null && this.current !== quote) {\n if (this.current === '\\\\') {\n this.advance()\n if (this.current === null) {\n throw new ParseError('Unterminated string', start)\n }\n // Handle escape sequences\n const ch = this.current as string\n if (ch === 'n') {\n value += '\\n'\n } else if (ch === 't') {\n value += '\\t'\n } else if (ch === 'r') {\n value += '\\r'\n } else if (ch === '\\\\') {\n value += '\\\\'\n } else if (ch === '\"') {\n value += '\"'\n } else if (ch === \"'\") {\n value += \"'\"\n } else {\n value += ch\n }\n } else {\n value += this.current\n }\n this.advance()\n }\n\n if (this.current === null) {\n throw new ParseError('Unterminated string', start)\n }\n\n this.advance() // Skip closing quote\n\n return createToken(TokenType.STRING, value, start)\n }\n\n /**\n * Read an operator or punctuation token.\n * @private\n */\n private readOperator(): Token | null {\n const start = this.position\n const char = this.current!\n\n switch (char) {\n case '+':\n this.advance()\n return createToken(TokenType.PLUS, char, start)\n\n case '-':\n this.advance()\n return createToken(TokenType.MINUS, char, start)\n\n case '*':\n this.advance()\n return createToken(TokenType.STAR, char, start)\n\n case '/':\n this.advance()\n return createToken(TokenType.SLASH, char, start)\n\n case '%':\n this.advance()\n return createToken(TokenType.PERCENT, char, start)\n\n case '<':\n this.advance()\n if (this.current === '=') {\n this.advance()\n return createToken(TokenType.LE, '<=', start)\n } else if (this.current === '<') {\n this.advance()\n return createToken(TokenType.LSHIFT, '<<', start)\n }\n return createToken(TokenType.LT, '<', start)\n\n case '>':\n this.advance()\n if (this.current === '=') {\n this.advance()\n return createToken(TokenType.GE, '>=', start)\n } else if (this.current === '>') {\n this.advance()\n return createToken(TokenType.RSHIFT, '>>', start)\n }\n return createToken(TokenType.GT, '>', start)\n\n case '=':\n this.advance()\n if (this.current === '=') {\n this.advance()\n return createToken(TokenType.EQ, '==', start)\n }\n throw new ParseError('Expected == for equality', start)\n\n case '!':\n this.advance()\n if (this.current === '=') {\n this.advance()\n return createToken(TokenType.NE, '!=', start)\n }\n throw new ParseError('Expected != for inequality', start)\n\n case '&':\n this.advance()\n return createToken(TokenType.AMPERSAND, char, start)\n\n case '|':\n this.advance()\n return createToken(TokenType.PIPE, char, start)\n\n case '^':\n this.advance()\n return createToken(TokenType.CARET, char, start)\n\n case '?':\n this.advance()\n return createToken(TokenType.QUESTION, char, start)\n\n case ':':\n this.advance()\n if (this.current === ':') {\n this.advance()\n return createToken(TokenType.DOUBLE_COLON, '::', start)\n }\n return createToken(TokenType.COLON, char, start)\n\n case '(':\n this.advance()\n return createToken(TokenType.LPAREN, char, start)\n\n case ')':\n this.advance()\n return createToken(TokenType.RPAREN, char, start)\n\n case '[':\n this.advance()\n return createToken(TokenType.LBRACKET, char, start)\n\n case ']':\n this.advance()\n return createToken(TokenType.RBRACKET, char, start)\n\n case '.':\n this.advance()\n return createToken(TokenType.DOT, char, start)\n\n case ',':\n this.advance()\n return createToken(TokenType.COMMA, char, start)\n\n default:\n return null\n }\n }\n}\n","/**\n * @fileoverview Abstract Syntax Tree nodes for expression language\n * @module expression/AST\n * @author Fabiano Pinto\n * @license MIT\n */\n\n/**\n * Base interface for all AST nodes.\n */\nexport interface ASTNode {\n /** Node type discriminator */\n kind: string\n}\n\n/**\n * Literal value node (number, string, boolean).\n */\nexport interface LiteralNode extends ASTNode {\n kind: 'Literal'\n value: number | string | boolean\n}\n\n/**\n * Identifier node (variable reference).\n */\nexport interface IdentifierNode extends ASTNode {\n kind: 'Identifier'\n name: string\n}\n\n/**\n * Binary operation node (e.g., a + b).\n */\nexport interface BinaryOpNode extends ASTNode {\n kind: 'BinaryOp'\n operator: string\n left: ASTNode\n right: ASTNode\n}\n\n/**\n * Unary operation node (e.g., -a, not b).\n */\nexport interface UnaryOpNode extends ASTNode {\n kind: 'UnaryOp'\n operator: string\n operand: ASTNode\n}\n\n/**\n * Ternary conditional node (condition ? ifTrue : ifFalse).\n */\nexport interface TernaryNode extends ASTNode {\n kind: 'Ternary'\n condition: ASTNode\n ifTrue: ASTNode\n ifFalse: ASTNode\n}\n\n/**\n * Member access node (object.property).\n */\nexport interface MemberAccessNode extends ASTNode {\n kind: 'MemberAccess'\n object: ASTNode\n property: string\n}\n\n/**\n * Array/index access node (array[index]).\n */\nexport interface IndexAccessNode extends ASTNode {\n kind: 'IndexAccess'\n object: ASTNode\n index: ASTNode\n}\n\n/**\n * Method call node (object.method()).\n */\nexport interface MethodCallNode extends ASTNode {\n kind: 'MethodCall'\n object: ASTNode\n method: string\n args: ASTNode[]\n}\n\n/**\n * Enum access node (EnumName::value).\n */\nexport interface EnumAccessNode extends ASTNode {\n kind: 'EnumAccess'\n enumName: string\n value: string\n}\n\n/**\n * Type union for all AST nodes.\n */\nexport type Expression =\n | LiteralNode\n | IdentifierNode\n | BinaryOpNode\n | UnaryOpNode\n | TernaryNode\n | MemberAccessNode\n | IndexAccessNode\n | MethodCallNode\n | EnumAccessNode\n\n/**\n * Create a literal node.\n */\nexport function createLiteral(value: number | string | boolean): LiteralNode {\n return { kind: 'Literal', value }\n}\n\n/**\n * Create an identifier node.\n */\nexport function createIdentifier(name: string): IdentifierNode {\n return { kind: 'Identifier', name }\n}\n\n/**\n * Create a binary operation node.\n */\nexport function createBinaryOp(\n operator: string,\n left: ASTNode,\n right: ASTNode\n): BinaryOpNode {\n return { kind: 'BinaryOp', operator, left, right }\n}\n\n/**\n * Create a unary operation node.\n */\nexport function createUnaryOp(operator: string, operand: ASTNode): UnaryOpNode {\n return { kind: 'UnaryOp', operator, operand }\n}\n\n/**\n * Create a ternary conditional node.\n */\nexport function createTernary(\n condition: ASTNode,\n ifTrue: ASTNode,\n ifFalse: ASTNode\n): TernaryNode {\n return { kind: 'Ternary', condition, ifTrue, ifFalse }\n}\n\n/**\n * Create a member access node.\n */\nexport function createMemberAccess(\n object: ASTNode,\n property: string\n): MemberAccessNode {\n return { kind: 'MemberAccess', object, property }\n}\n\n/**\n * Create an index access node.\n */\nexport function createIndexAccess(\n object: ASTNode,\n index: ASTNode\n): IndexAccessNode {\n return { kind: 'IndexAccess', object, index }\n}\n\n/**\n * Create a method call node.\n */\nexport function createMethodCall(\n object: ASTNode,\n method: string,\n args: ASTNode[]\n): MethodCallNode {\n return { kind: 'MethodCall', object, method, args }\n}\n\n/**\n * Create an enum access node.\n */\nexport function createEnumAccess(\n enumName: string,\n value: string\n): EnumAccessNode {\n return { kind: 'EnumAccess', enumName, value }\n}\n","/**\n * @fileoverview Parser for Kaitai Struct expression language\n * @module expression/Parser\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { ParseError } from '../utils/errors'\nimport { Token, TokenType } from './Token'\nimport type { ASTNode } from './AST'\nimport {\n createLiteral,\n createIdentifier,\n createBinaryOp,\n createUnaryOp,\n createTernary,\n createMemberAccess,\n createIndexAccess,\n createMethodCall,\n createEnumAccess,\n} from './AST'\n\n/**\n * Parser for Kaitai Struct expressions.\n * Converts tokens into an Abstract Syntax Tree (AST).\n *\n * @class ExpressionParser\n * @example\n * ```typescript\n * const lexer = new Lexer('field1 + field2 * 2')\n * const tokens = lexer.tokenize()\n * const parser = new ExpressionParser(tokens)\n * const ast = parser.parse()\n * ```\n */\nexport class ExpressionParser {\n private tokens: Token[]\n private position: number = 0\n\n /**\n * Create a new expression parser.\n *\n * @param tokens - Array of tokens to parse\n */\n constructor(tokens: Token[]) {\n this.tokens = tokens\n }\n\n /**\n * Parse the tokens into an AST.\n *\n * @returns Root AST node\n * @throws {ParseError} If invalid syntax is encountered\n */\n parse(): ASTNode {\n const expr = this.parseTernary()\n if (!this.isAtEnd()) {\n throw new ParseError(\n `Unexpected token: ${this.current().type}`,\n this.current().position\n )\n }\n return expr\n }\n\n /**\n * Get the current token.\n * @private\n */\n private current(): Token {\n return this.tokens[this.position]\n }\n\n /**\n * Check if we're at the end of tokens.\n * @private\n */\n private isAtEnd(): boolean {\n return this.current().type === TokenType.EOF\n }\n\n /**\n * Advance to the next token.\n * @private\n */\n private advance(): Token {\n if (!this.isAtEnd()) {\n this.position++\n }\n return this.tokens[this.position - 1]\n }\n\n /**\n * Check if current token matches any of the given types.\n * @private\n */\n private match(...types: TokenType[]): boolean {\n for (const type of types) {\n if (this.current().type === type) {\n this.advance()\n return true\n }\n }\n return false\n }\n\n /**\n * Expect a specific token type and advance.\n * @private\n */\n private expect(type: TokenType, message: string): Token {\n if (this.current().type !== type) {\n throw new ParseError(message, this.current().position)\n }\n return this.advance()\n }\n\n /**\n * Parse ternary conditional (lowest precedence).\n * condition ? ifTrue : ifFalse\n * @private\n */\n private parseTernary(): ASTNode {\n let expr = this.parseLogicalOr()\n\n if (this.match(TokenType.QUESTION)) {\n const ifTrue = this.parseTernary()\n this.expect(TokenType.COLON, 'Expected : in ternary expression')\n const ifFalse = this.parseTernary()\n return createTernary(expr, ifTrue, ifFalse)\n }\n\n return expr\n }\n\n /**\n * Parse logical OR.\n * @private\n */\n private parseLogicalOr(): ASTNode {\n let left = this.parseLogicalAnd()\n\n while (this.match(TokenType.OR)) {\n const operator = 'or'\n const right = this.parseLogicalAnd()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse logical AND.\n * @private\n */\n private parseLogicalAnd(): ASTNode {\n let left = this.parseBitwiseOr()\n\n while (this.match(TokenType.AND)) {\n const operator = 'and'\n const right = this.parseBitwiseOr()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse bitwise OR.\n * @private\n */\n private parseBitwiseOr(): ASTNode {\n let left = this.parseBitwiseXor()\n\n while (this.match(TokenType.PIPE)) {\n const operator = '|'\n const right = this.parseBitwiseXor()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse bitwise XOR.\n * @private\n */\n private parseBitwiseXor(): ASTNode {\n let left = this.parseBitwiseAnd()\n\n while (this.match(TokenType.CARET)) {\n const operator = '^'\n const right = this.parseBitwiseAnd()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse bitwise AND.\n * @private\n */\n private parseBitwiseAnd(): ASTNode {\n let left = this.parseEquality()\n\n while (this.match(TokenType.AMPERSAND)) {\n const operator = '&'\n const right = this.parseEquality()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse equality operators (==, !=).\n * @private\n */\n private parseEquality(): ASTNode {\n let left = this.parseRelational()\n\n while (this.match(TokenType.EQ, TokenType.NE)) {\n const operator = this.tokens[this.position - 1].value as string\n const right = this.parseRelational()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse relational operators (<, <=, >, >=).\n * @private\n */\n private parseRelational(): ASTNode {\n let left = this.parseBitShift()\n\n while (this.match(TokenType.LT, TokenType.LE, TokenType.GT, TokenType.GE)) {\n const operator = this.tokens[this.position - 1].value as string\n const right = this.parseBitShift()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse bit shift operators (<<, >>).\n * @private\n */\n private parseBitShift(): ASTNode {\n let left = this.parseAdditive()\n\n while (this.match(TokenType.LSHIFT, TokenType.RSHIFT)) {\n const operator = this.tokens[this.position - 1].value as string\n const right = this.parseAdditive()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse additive operators (+, -).\n * @private\n */\n private parseAdditive(): ASTNode {\n let left = this.parseMultiplicative()\n\n while (this.match(TokenType.PLUS, TokenType.MINUS)) {\n const operator = this.tokens[this.position - 1].value as string\n const right = this.parseMultiplicative()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse multiplicative operators (*, /, %).\n * @private\n */\n private parseMultiplicative(): ASTNode {\n let left = this.parseUnary()\n\n while (this.match(TokenType.STAR, TokenType.SLASH, TokenType.PERCENT)) {\n const operator = this.tokens[this.position - 1].value as string\n const right = this.parseUnary()\n left = createBinaryOp(operator, left, right)\n }\n\n return left\n }\n\n /**\n * Parse unary operators (-, not).\n * @private\n */\n private parseUnary(): ASTNode {\n if (this.match(TokenType.MINUS, TokenType.NOT)) {\n const operator = this.tokens[this.position - 1].value as string\n const operand = this.parseUnary()\n return createUnaryOp(operator, operand)\n }\n\n return this.parsePostfix()\n }\n\n /**\n * Parse postfix operators (., [], ()).\n * @private\n */\n private parsePostfix(): ASTNode {\n let expr = this.parsePrimary()\n\n while (true) {\n if (this.match(TokenType.DOT)) {\n const property = this.expect(\n TokenType.IDENTIFIER,\n 'Expected property name after .'\n )\n expr = createMemberAccess(expr, property.value as string)\n } else if (this.match(TokenType.LBRACKET)) {\n const index = this.parseTernary()\n this.expect(TokenType.RBRACKET, 'Expected ] after array index')\n expr = createIndexAccess(expr, index)\n } else if (this.current().type === TokenType.LPAREN) {\n // Method call (only if expr is a member access)\n if (expr.kind === 'MemberAccess') {\n this.advance() // consume (\n const args: ASTNode[] = []\n\n if (this.current().type !== TokenType.RPAREN) {\n args.push(this.parseTernary())\n while (this.match(TokenType.COMMA)) {\n args.push(this.parseTernary())\n }\n }\n\n this.expect(TokenType.RPAREN, 'Expected ) after arguments')\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const memberExpr = expr as any\n expr = createMethodCall(memberExpr.object, memberExpr.property, args)\n } else {\n break\n }\n } else {\n break\n }\n }\n\n return expr\n }\n\n /**\n * Parse primary expressions (literals, identifiers, grouping).\n * @private\n */\n private parsePrimary(): ASTNode {\n // Literals\n if (this.match(TokenType.NUMBER, TokenType.STRING, TokenType.BOOLEAN)) {\n const token = this.tokens[this.position - 1]\n return createLiteral(token.value as number | string | boolean)\n }\n\n // Identifiers and enum access\n if (this.match(TokenType.IDENTIFIER)) {\n const name = this.tokens[this.position - 1].value as string\n\n // Check for enum access (EnumName::value)\n if (this.match(TokenType.DOUBLE_COLON)) {\n const value = this.expect(\n TokenType.IDENTIFIER,\n 'Expected enum value after ::'\n )\n return createEnumAccess(name, value.value as string)\n }\n\n return createIdentifier(name)\n }\n\n // Grouping\n if (this.match(TokenType.LPAREN)) {\n const expr = this.parseTernary()\n this.expect(TokenType.RPAREN, 'Expected ) after expression')\n return expr\n }\n\n throw new ParseError(\n `Unexpected token: ${this.current().type}`,\n this.current().position\n )\n }\n}\n","/**\n * @fileoverview Evaluator for Kaitai Struct expression AST\n * @module expression/Evaluator\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { ParseError } from '../utils/errors'\nimport type { Context } from '../interpreter/Context'\nimport type { ASTNode } from './AST'\n\n/**\n * Evaluator for expression AST nodes.\n * Executes expressions in the context of parsed data.\n *\n * @class Evaluator\n * @example\n * ```typescript\n * const evaluator = new Evaluator()\n * const result = evaluator.evaluate(ast, context)\n * ```\n */\nexport class Evaluator {\n /**\n * Evaluate an AST node in the given context.\n *\n * @param node - AST node to evaluate\n * @param context - Execution context\n * @returns Evaluated value\n * @throws {ParseError} If evaluation fails\n */\n evaluate(node: ASTNode, context: Context): unknown {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const n = node as any\n switch (node.kind) {\n case 'Literal':\n return n.value\n\n case 'Identifier':\n return this.evaluateIdentifier(n.name, context)\n\n case 'BinaryOp':\n return this.evaluateBinaryOp(n.operator, n.left, n.right, context)\n\n case 'UnaryOp':\n return this.evaluateUnaryOp(n.operator, n.operand, context)\n\n case 'Ternary':\n return this.evaluateTernary(n.condition, n.ifTrue, n.ifFalse, context)\n\n case 'MemberAccess':\n return this.evaluateMemberAccess(n.object, n.property, context)\n\n case 'IndexAccess':\n return this.evaluateIndexAccess(n.object, n.index, context)\n\n case 'MethodCall':\n return this.evaluateMethodCall(n.object, n.method, n.args, context)\n\n case 'EnumAccess':\n return this.evaluateEnumAccess(n.enumName, n.value, context)\n\n default:\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n throw new ParseError(`Unknown AST node kind: ${(node as any).kind}`)\n }\n }\n\n /**\n * Evaluate an identifier.\n * @private\n */\n private evaluateIdentifier(name: string, context: Context): unknown {\n return context.resolve(name)\n }\n\n /**\n * Evaluate a binary operation.\n * @private\n */\n private evaluateBinaryOp(\n operator: string,\n left: ASTNode,\n right: ASTNode,\n context: Context\n ): unknown {\n const leftVal = this.evaluate(left, context)\n const rightVal = this.evaluate(right, context)\n\n switch (operator) {\n // Arithmetic\n case '+':\n return this.add(leftVal, rightVal)\n case '-':\n return this.toNumber(leftVal) - this.toNumber(rightVal)\n case '*':\n return this.toNumber(leftVal) * this.toNumber(rightVal)\n case '/':\n return this.toNumber(leftVal) / this.toNumber(rightVal)\n case '%':\n return this.modulo(this.toNumber(leftVal), this.toNumber(rightVal))\n\n // Comparison\n case '<':\n return this.compare(leftVal, rightVal) < 0\n case '<=':\n return this.compare(leftVal, rightVal) <= 0\n case '>':\n return this.compare(leftVal, rightVal) > 0\n case '>=':\n return this.compare(leftVal, rightVal) >= 0\n case '==':\n return this.equals(leftVal, rightVal)\n case '!=':\n return !this.equals(leftVal, rightVal)\n\n // Bitwise\n case '<<':\n return this.toInt(leftVal) << this.toInt(rightVal)\n case '>>':\n return this.toInt(leftVal) >> this.toInt(rightVal)\n case '&':\n return this.toInt(leftVal) & this.toInt(rightVal)\n case '|':\n return this.toInt(leftVal) | this.toInt(rightVal)\n case '^':\n return this.toInt(leftVal) ^ this.toInt(rightVal)\n\n // Logical\n case 'and':\n return this.toBoolean(leftVal) && this.toBoolean(rightVal)\n case 'or':\n return this.toBoolean(leftVal) || this.toBoolean(rightVal)\n\n default:\n throw new ParseError(`Unknown binary operator: ${operator}`)\n }\n }\n\n /**\n * Evaluate a unary operation.\n * @private\n */\n private evaluateUnaryOp(\n operator: string,\n operand: ASTNode,\n context: Context\n ): unknown {\n const value = this.evaluate(operand, context)\n\n switch (operator) {\n case '-':\n return -this.toNumber(value)\n case 'not':\n return !this.toBoolean(value)\n default:\n throw new ParseError(`Unknown unary operator: ${operator}`)\n }\n }\n\n /**\n * Evaluate a ternary conditional.\n * @private\n */\n private evaluateTernary(\n condition: ASTNode,\n ifTrue: ASTNode,\n ifFalse: ASTNode,\n context: Context\n ): unknown {\n const condValue = this.evaluate(condition, context)\n return this.toBoolean(condValue)\n ? this.evaluate(ifTrue, context)\n : this.evaluate(ifFalse, context)\n }\n\n /**\n * Evaluate member access (object.property).\n * @private\n */\n private evaluateMemberAccess(\n object: ASTNode,\n property: string,\n context: Context\n ): unknown {\n const obj = this.evaluate(object, context)\n\n if (obj === null || obj === undefined) {\n throw new ParseError(\n `Cannot access property ${property} of null/undefined`\n )\n }\n\n if (typeof obj === 'object') {\n return (obj as Record<string, unknown>)[property]\n }\n\n throw new ParseError(`Cannot access property ${property} of non-object`)\n }\n\n /**\n * Evaluate index access (array[index]).\n * @private\n */\n private evaluateIndexAccess(\n object: ASTNode,\n index: ASTNode,\n context: Context\n ): unknown {\n const obj = this.evaluate(object, context)\n const idx = this.evaluate(index, context)\n\n if (Array.isArray(obj)) {\n const numIdx = this.toInt(idx)\n return obj[numIdx]\n }\n\n if (obj instanceof Uint8Array) {\n const numIdx = this.toInt(idx)\n return obj[numIdx]\n }\n\n throw new ParseError('Index access requires an array')\n }\n\n /**\n * Evaluate method call (object.method()).\n * @private\n */\n private evaluateMethodCall(\n object: ASTNode,\n method: string,\n _args: ASTNode[],\n context: Context\n ): unknown {\n const obj = this.evaluate(object, context)\n // TODO: Use args for method calls that need them\n // const evalArgs = args.map((arg) => this.evaluate(arg, context))\n\n // Handle common methods\n if (method === 'length' || method === 'size') {\n if (Array.isArray(obj)) return obj.length\n if (obj instanceof Uint8Array) return obj.length\n if (typeof obj === 'string') return obj.length\n throw new ParseError(`Object does not have a ${method} property`)\n }\n\n if (method === 'to_i') {\n return this.toInt(obj)\n }\n\n if (method === 'to_s') {\n return String(obj)\n }\n\n throw new ParseError(`Unknown method: ${method}`)\n }\n\n /**\n * Evaluate enum access (EnumName::value).\n * @private\n */\n private evaluateEnumAccess(\n enumName: string,\n valueName: string,\n context: Context\n ): unknown {\n const value = context.getEnumValue(enumName, valueName)\n if (value === undefined) {\n throw new ParseError(`Enum value \"${enumName}::${valueName}\" not found`)\n }\n return value\n }\n\n /**\n * Helper: Add two values (handles strings and numbers).\n * @private\n */\n private add(left: unknown, right: unknown): unknown {\n if (typeof left === 'string' || typeof right === 'string') {\n return String(left) + String(right)\n }\n return this.toNumber(left) + this.toNumber(right)\n }\n\n /**\n * Helper: Modulo operation (Kaitai-style, not remainder).\n * @private\n */\n private modulo(a: number, b: number): number {\n const result = a % b\n return result < 0 ? result + b : result\n }\n\n /**\n * Helper: Compare two values.\n * @private\n */\n private compare(left: unknown, right: unknown): number {\n if (typeof left === 'string' && typeof right === 'string') {\n return left < right ? -1 : left > right ? 1 : 0\n }\n const leftNum = this.toNumber(left)\n const rightNum = this.toNumber(right)\n return leftNum < rightNum ? -1 : leftNum > rightNum ? 1 : 0\n }\n\n /**\n * Helper: Check equality.\n * @private\n */\n private equals(left: unknown, right: unknown): boolean {\n // Handle bigint comparison\n if (typeof left === 'bigint' || typeof right === 'bigint') {\n return BigInt(left as number) === BigInt(right as number)\n }\n return left === right\n }\n\n /**\n * Helper: Convert to number.\n * @private\n */\n private toNumber(value: unknown): number {\n if (typeof value === 'number') return value\n if (typeof value === 'bigint') return Number(value)\n if (typeof value === 'boolean') return value ? 1 : 0\n if (typeof value === 'string') return parseFloat(value)\n throw new ParseError(`Cannot convert ${typeof value} to number`)\n }\n\n /**\n * Helper: Convert to integer.\n * @private\n */\n private toInt(value: unknown): number {\n return Math.floor(this.toNumber(value))\n }\n\n /**\n * Helper: Convert to boolean.\n * @private\n */\n private toBoolean(value: unknown): boolean {\n if (typeof value === 'boolean') return value\n if (typeof value === 'number') return value !== 0\n if (typeof value === 'bigint') return value !== 0n\n if (typeof value === 'string') return value.length > 0\n if (value === null || value === undefined) return false\n return true\n }\n}\n","/**\n * @fileoverview Expression evaluation module\n * @module expression\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { Lexer } from './Lexer'\nimport { ExpressionParser } from './Parser'\nimport { Evaluator } from './Evaluator'\nimport type { Context } from '../interpreter/Context'\n\nexport * from './Token'\nexport * from './AST'\nexport * from './Lexer'\nexport * from './Parser'\nexport * from './Evaluator'\n\n/**\n * Evaluate a Kaitai Struct expression string.\n * Convenience function that combines lexing, parsing, and evaluation.\n *\n * @param expression - Expression string to evaluate\n * @param context - Execution context\n * @returns Evaluated value\n * @throws {ParseError} If parsing or evaluation fails\n *\n * @example\n * ```typescript\n * const result = evaluateExpression('field1 + field2 * 2', context)\n * ```\n */\nexport function evaluateExpression(\n expression: string,\n context: Context\n): unknown {\n // Lexical analysis\n const lexer = new Lexer(expression)\n const tokens = lexer.tokenize()\n\n // Parsing\n const parser = new ExpressionParser(tokens)\n const ast = parser.parse()\n\n // Evaluation\n const evaluator = new Evaluator()\n return evaluator.evaluate(ast, context)\n}\n","/**\n * @fileoverview Type interpreter for executing Kaitai Struct schemas\n * @module interpreter/TypeInterpreter\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { KaitaiStream } from '../stream'\nimport {\n ParseError,\n ValidationError,\n NotImplementedError,\n} from '../utils/errors'\nimport type { KsySchema, AttributeSpec, Endianness } from '../parser/schema'\nimport {\n isBuiltinType,\n getTypeEndianness,\n getBaseType,\n isIntegerType,\n isFloatType,\n isStringType,\n} from '../parser/schema'\nimport { Context } from './Context'\nimport { evaluateExpression } from '../expression'\n\n/**\n * Interprets Kaitai Struct schemas and parses binary data.\n * Executes schema definitions against binary streams to produce structured objects.\n *\n * @class TypeInterpreter\n * @example\n * ```typescript\n * const interpreter = new TypeInterpreter(schema)\n * const stream = new KaitaiStream(buffer)\n * const result = interpreter.parse(stream)\n * ```\n */\nexport class TypeInterpreter {\n /**\n * Create a new type interpreter.\n *\n * @param schema - Kaitai Struct schema to interpret\n * @param parentMeta - Parent schema's meta (for nested types)\n */\n constructor(\n private schema: KsySchema,\n private parentMeta?: {\n id: string\n endian?: Endianness | object\n encoding?: string\n }\n ) {\n // For root schemas, meta.id is required\n // For nested types, we can inherit from parent\n if (!schema.meta && !parentMeta) {\n throw new ParseError('Schema must have meta section')\n }\n if (schema.meta && !schema.meta.id && !parentMeta) {\n throw new ParseError('Root schema must have meta.id')\n }\n }\n\n /**\n * Parse binary data according to the schema.\n *\n * @param stream - Binary stream to parse\n * @param parent - Parent object (for nested types)\n * @param typeArgs - Arguments for parametric types\n * @returns Parsed object\n */\n parse(\n stream: KaitaiStream,\n parent?: unknown,\n typeArgs?: Array<string | number | boolean>\n ): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n const context = new Context(stream, result, parent, this.schema.enums)\n context.current = result\n\n // Set parameters in context if this is a parametric type\n if (typeArgs && this.schema.params) {\n for (\n let i = 0;\n i < this.schema.params.length && i < typeArgs.length;\n i++\n ) {\n const param = this.schema.params[i]\n const argValue = typeArgs[i]\n // Evaluate the argument if it's a string expression\n const evaluatedArg =\n typeof argValue === 'string'\n ? this.evaluateValue(argValue, context)\n : argValue\n context.set(param.id, evaluatedArg)\n }\n }\n\n // Parse sequential fields\n if (this.schema.seq) {\n for (const attr of this.schema.seq) {\n const value = this.parseAttribute(attr, context)\n if (attr.id) {\n result[attr.id] = value\n }\n }\n }\n\n // Set up lazy-evaluated instances\n if (this.schema.instances) {\n this.setupInstances(result, stream, context)\n }\n\n return result\n }\n\n /**\n * Set up lazy-evaluated instance getters.\n * Instances are computed on first access and cached.\n *\n * @param result - Result object to add getters to\n * @param stream - Stream for parsing\n * @param context - Execution context\n * @private\n */\n private setupInstances(\n result: Record<string, unknown>,\n stream: KaitaiStream,\n context: Context\n ): void {\n if (!this.schema.instances) return\n\n for (const [name, instance] of Object.entries(this.schema.instances)) {\n // Cache for lazy evaluation\n let cached: unknown = undefined\n let evaluated = false\n\n Object.defineProperty(result, name, {\n get: () => {\n if (!evaluated) {\n cached = this.parseInstance(\n instance as Record<string, unknown>,\n stream,\n context\n )\n evaluated = true\n }\n return cached\n },\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n /**\n * Parse an instance (lazy-evaluated field).\n *\n * @param instance - Instance specification\n * @param stream - Stream to read from\n * @param context - Execution context\n * @returns Parsed or calculated value\n * @private\n */\n private parseInstance(\n instance: Record<string, unknown>,\n stream: KaitaiStream,\n context: Context\n ): unknown {\n // Handle value instances (calculated fields)\n if ('value' in instance) {\n return this.evaluateValue(\n instance.value as string | number | boolean | undefined,\n context\n )\n }\n\n // Save current position\n const savedPos = stream.pos\n\n try {\n // Handle pos attribute for positioned reads\n if (instance.pos !== undefined) {\n const pos = this.evaluateValue(\n instance.pos as string | number | boolean | undefined,\n context\n )\n if (typeof pos === 'number') {\n stream.seek(pos)\n } else if (typeof pos === 'bigint') {\n stream.seek(Number(pos))\n } else {\n throw new ParseError(\n `pos must evaluate to a number, got ${typeof pos}`\n )\n }\n }\n\n // Parse as a regular attribute\n const value = this.parseAttribute(instance as any, context)\n return value\n } finally {\n // Restore position if pos was used\n if (instance.pos !== undefined) {\n stream.seek(savedPos)\n }\n }\n }\n\n /**\n * Parse a single attribute according to its specification.\n *\n * @param attr - Attribute specification\n * @param context - Execution context\n * @returns Parsed value\n * @private\n */\n private parseAttribute(attr: AttributeSpec, context: Context): unknown {\n const stream = context.io\n\n // Handle conditional parsing\n if (attr.if) {\n const condition = this.evaluateValue(attr.if, context)\n // If condition is false or falsy, skip this attribute\n if (!condition) {\n return undefined\n }\n }\n\n // Handle absolute positioning\n if (attr.pos !== undefined) {\n const pos = this.evaluateValue(attr.pos, context)\n if (typeof pos === 'number') {\n stream.seek(pos)\n } else if (typeof pos === 'bigint') {\n stream.seek(Number(pos))\n } else {\n throw new ParseError(`pos must evaluate to a number, got ${typeof pos}`)\n }\n }\n\n // Handle custom I/O\n if (attr.io) {\n throw new NotImplementedError('Custom I/O streams')\n }\n\n // Handle repetition\n if (attr.repeat) {\n return this.parseRepeated(attr, context)\n }\n\n // Handle contents validation\n if (attr.contents) {\n return this.parseContents(attr, context)\n }\n\n // Parse single value\n const value = this.parseValue(attr, context)\n\n // Note: We don't apply enum mapping here to keep values as integers\n // This allows enum comparisons in expressions to work correctly\n // Enum mapping should be done at the presentation layer if needed\n\n return value\n }\n\n /**\n * Parse a repeated attribute.\n *\n * @param attr - Attribute specification with repeat\n * @param context - Execution context\n * @returns Array of parsed values\n * @private\n */\n private parseRepeated(attr: AttributeSpec, context: Context): unknown[] {\n const stream = context.io\n const result: unknown[] = []\n\n switch (attr.repeat) {\n case 'expr': {\n // Fixed number of repetitions\n const countValue = this.evaluateValue(attr['repeat-expr'], context)\n const count =\n typeof countValue === 'number'\n ? countValue\n : typeof countValue === 'bigint'\n ? Number(countValue)\n : 0\n\n if (count < 0) {\n throw new ParseError(`repeat-expr must be non-negative, got ${count}`)\n }\n\n for (let i = 0; i < count; i++) {\n // Set _index for expressions\n context.set('_index', i)\n const value = this.parseAttribute(\n { ...attr, repeat: undefined, 'repeat-expr': undefined },\n context\n )\n result.push(value)\n }\n break\n }\n\n case 'eos': {\n // Repeat until end of stream\n while (!stream.isEof()) {\n context.set('_index', result.length)\n result.push(this.parseValue(attr, context))\n }\n break\n }\n\n case 'until': {\n // Repeat until condition is true\n if (!attr['repeat-until']) {\n throw new ParseError('repeat-until expression is required')\n }\n\n let index = 0\n // eslint-disable-next-line no-constant-condition\n while (true) {\n context.set('_index', index)\n\n // Parse the value first\n const value = this.parseAttribute(\n { ...attr, repeat: undefined, 'repeat-until': undefined },\n context\n )\n result.push(value)\n\n // Set _ to the last parsed value for the condition\n context.set('_', value)\n\n // Evaluate the condition\n const condition = this.evaluateValue(attr['repeat-until'], context)\n\n // Break if condition is true\n if (condition) {\n break\n }\n\n // Check for EOF to prevent infinite loops\n if (stream.isEof()) {\n break\n }\n\n index++\n }\n break\n }\n\n default:\n throw new ParseError(`Unknown repeat type: ${attr.repeat}`)\n }\n\n return result\n }\n\n /**\n * Parse and validate contents.\n *\n * @param attr - Attribute specification with contents\n * @param context - Execution context\n * @returns The validated contents\n * @private\n */\n private parseContents(\n attr: AttributeSpec,\n context: Context\n ): Uint8Array | string {\n const stream = context.io\n const expected = attr.contents!\n\n if (Array.isArray(expected)) {\n // Byte array contents\n const bytes = stream.readBytes(expected.length)\n for (let i = 0; i < expected.length; i++) {\n if (bytes[i] !== expected[i]) {\n throw new ValidationError(\n `Contents mismatch at byte ${i}: expected ${expected[i]}, got ${bytes[i]}`,\n stream.pos - expected.length + i\n )\n }\n }\n return bytes\n } else {\n // String contents\n const encoding = attr.encoding || this.schema.meta.encoding || 'UTF-8'\n const str = stream.readStr(expected.length, encoding)\n if (str !== expected) {\n throw new ValidationError(\n `Contents mismatch: expected \"${expected}\", got \"${str}\"`,\n stream.pos - expected.length\n )\n }\n return str\n }\n }\n\n /**\n * Parse a single value according to its type.\n *\n * @param attr - Attribute specification\n * @param context - Execution context\n * @returns Parsed value\n * @private\n */\n private parseValue(attr: AttributeSpec, context: Context): unknown {\n const stream = context.io\n const type = attr.type\n\n // Handle sized reads\n if (attr.size !== undefined) {\n const sizeValue = this.evaluateValue(attr.size, context)\n const size =\n typeof sizeValue === 'number'\n ? sizeValue\n : typeof sizeValue === 'bigint'\n ? Number(sizeValue)\n : 0\n\n if (size < 0) {\n throw new ParseError(`size must be non-negative, got ${size}`)\n }\n\n if (type === 'str' || !type) {\n // String or raw bytes\n const encoding = attr.encoding || this.schema.meta.encoding || 'UTF-8'\n let data: Uint8Array\n if (type === 'str') {\n data = stream.readBytes(size)\n // Apply processing if specified\n if (attr.process) {\n data = this.applyProcessing(data, attr.process)\n }\n // eslint-disable-next-line no-undef\n return new TextDecoder(encoding).decode(data)\n } else {\n data = stream.readBytes(size)\n // Apply processing if specified\n if (attr.process) {\n data = this.applyProcessing(data, attr.process)\n }\n return data\n }\n } else {\n // Sized substream for complex type\n let data = stream.readBytes(size)\n // Apply processing if specified\n if (attr.process) {\n data = this.applyProcessing(data, attr.process)\n }\n const substream = new KaitaiStream(data)\n return this.parseType(type, substream, context, attr['type-args'])\n }\n }\n\n // Handle size-eos\n if (attr['size-eos']) {\n if (type === 'str') {\n const encoding = attr.encoding || this.schema.meta.encoding || 'UTF-8'\n const bytes = stream.readBytesFull()\n // eslint-disable-next-line no-undef\n return new TextDecoder(encoding).decode(bytes)\n } else {\n return stream.readBytesFull()\n }\n }\n\n // Handle type-based parsing\n if (!type) {\n throw new ParseError('Attribute must have either type, size, or contents')\n }\n\n return this.parseType(type, stream, context, attr['type-args'])\n }\n\n /**\n * Parse a value of a specific type.\n *\n * @param type - Type name or switch specification\n * @param stream - Stream to read from\n * @param context - Execution context\n * @param typeArgs - Arguments for parametric types\n * @returns Parsed value\n * @private\n */\n private parseType(\n type: string | object,\n stream: KaitaiStream,\n context: Context,\n typeArgs?: Array<string | number | boolean>\n ): unknown {\n // Handle switch types\n if (typeof type === 'object') {\n return this.parseSwitchType(\n type as Record<string, unknown>,\n stream,\n context\n )\n }\n\n // Handle built-in types\n if (isBuiltinType(type)) {\n return this.parseBuiltinType(type, stream, context)\n }\n\n // Handle user-defined types\n if (this.schema.types && type in this.schema.types) {\n const typeSchema = this.schema.types[type]\n // Pass parent meta for nested types\n const meta = this.schema.meta || this.parentMeta\n\n // Inherit parent enums if nested type doesn't have its own\n if (this.schema.enums && !typeSchema.enums) {\n typeSchema.enums = this.schema.enums\n }\n\n // Inherit parent types if nested type doesn't have its own\n if (this.schema.types && !typeSchema.types) {\n typeSchema.types = this.schema.types\n }\n\n const interpreter = new TypeInterpreter(typeSchema, meta)\n return interpreter.parse(stream, context.current, typeArgs)\n }\n\n throw new ParseError(`Unknown type: ${type}`)\n }\n\n /**\n * Parse a switch type (type selection based on expression).\n *\n * @param switchType - Switch type specification\n * @param stream - Stream to read from\n * @param context - Execution context\n * @returns Parsed value\n * @private\n */\n private parseSwitchType(\n switchType: Record<string, unknown>,\n stream: KaitaiStream,\n context: Context\n ): unknown {\n const switchOn = switchType['switch-on']\n const cases = switchType['cases'] as Record<string, string> | undefined\n const defaultType = switchType['default'] as string | undefined\n\n if (!switchOn || typeof switchOn !== 'string') {\n throw new ParseError('switch-on expression is required for switch types')\n }\n\n if (!cases) {\n throw new ParseError('cases are required for switch types')\n }\n\n // Evaluate the switch expression\n const switchValue = this.evaluateValue(switchOn, context)\n\n // Convert switch value to string for case matching\n const switchKey = String(switchValue)\n\n // Find matching case\n let selectedType: string | undefined = cases[switchKey]\n\n // Use default if no case matches\n if (selectedType === undefined && defaultType) {\n selectedType = defaultType\n }\n\n if (selectedType === undefined) {\n throw new ParseError(\n `No matching case for switch value \"${switchKey}\" and no default type specified`\n )\n }\n\n // Parse using the selected type\n return this.parseType(selectedType, stream, context)\n }\n\n /**\n * Parse a built-in type.\n *\n * @param type - Built-in type name\n * @param stream - Stream to read from\n * @param context - Execution context\n * @returns Parsed value\n * @private\n */\n private parseBuiltinType(\n type: string,\n stream: KaitaiStream,\n _context: Context\n ): unknown {\n const base = getBaseType(type)\n const typeEndian = getTypeEndianness(type)\n // Get endianness from schema or parent\n const meta = this.schema.meta || this.parentMeta\n const metaEndian = meta?.endian\n // Handle expression-based endianness (not yet implemented)\n const endian: Endianness =\n typeEndian || (typeof metaEndian === 'string' ? metaEndian : 'le')\n\n // Integer types\n if (isIntegerType(type)) {\n return this.readInteger(base, endian, stream)\n }\n\n // Float types\n if (isFloatType(type)) {\n return this.readFloat(base, endian, stream)\n }\n\n // String types\n if (isStringType(type)) {\n throw new ParseError('String types require size, size-eos, or terminator')\n }\n\n throw new ParseError(`Unknown built-in type: ${type}`)\n }\n\n /**\n * Read an integer value.\n *\n * @param type - Integer type (u1, u2, u4, u8, s1, s2, s4, s8)\n * @param endian - Endianness\n * @param stream - Stream to read from\n * @returns Integer value\n * @private\n */\n private readInteger(\n type: string,\n endian: Endianness,\n stream: KaitaiStream\n ): number | bigint {\n switch (type) {\n case 'u1':\n return stream.readU1()\n case 'u2':\n return endian === 'le' ? stream.readU2le() : stream.readU2be()\n case 'u4':\n return endian === 'le' ? stream.readU4le() : stream.readU4be()\n case 'u8':\n return endian === 'le' ? stream.readU8le() : stream.readU8be()\n case 's1':\n return stream.readS1()\n case 's2':\n return endian === 'le' ? stream.readS2le() : stream.readS2be()\n case 's4':\n return endian === 'le' ? stream.readS4le() : stream.readS4be()\n case 's8':\n return endian === 'le' ? stream.readS8le() : stream.readS8be()\n default:\n throw new ParseError(`Unknown integer type: ${type}`)\n }\n }\n\n /**\n * Read a floating point value.\n *\n * @param type - Float type (f4, f8)\n * @param endian - Endianness\n * @param stream - Stream to read from\n * @returns Float value\n * @private\n */\n private readFloat(\n type: string,\n endian: Endianness,\n stream: KaitaiStream\n ): number {\n switch (type) {\n case 'f4':\n return endian === 'le' ? stream.readF4le() : stream.readF4be()\n case 'f8':\n return endian === 'le' ? stream.readF8le() : stream.readF8be()\n default:\n throw new ParseError(`Unknown float type: ${type}`)\n }\n }\n\n /**\n * Apply processing transformation to data.\n * Supports basic transformations like zlib decompression.\n *\n * @param data - Data to process\n * @param process - Processing specification\n * @returns Processed data\n * @private\n */\n private applyProcessing(\n data: Uint8Array,\n process: string | Record<string, unknown>\n ): Uint8Array {\n const processType =\n typeof process === 'string' ? process : process.algorithm\n\n // For now, return data as-is with a note that processing isn't fully implemented\n // Full implementation would require zlib, encryption libraries, etc.\n if (processType) {\n throw new NotImplementedError(\n `Processing type \"${processType}\" is not yet implemented. ` +\n `Supported in future versions with zlib, encryption, etc.`\n )\n }\n\n return data\n }\n\n /**\n * Evaluate a value that can be an expression or literal.\n *\n * @param value - Value to evaluate (expression string, number, or boolean)\n * @param context - Execution context\n * @returns Evaluated result\n * @private\n */\n private evaluateValue(\n value: string | number | boolean | undefined,\n context: Context\n ): unknown {\n if (value === undefined) {\n return undefined\n }\n\n // If it's a number or boolean, return as-is\n if (typeof value === 'number' || typeof value === 'boolean') {\n return value\n }\n\n // If it's a string, evaluate as expression\n if (typeof value === 'string') {\n try {\n return evaluateExpression(value, context)\n } catch (error) {\n throw new ParseError(\n `Failed to evaluate expression \"${value}\": ${error instanceof Error ? error.message : String(error)}`\n )\n }\n }\n\n return value\n }\n}\n","/**\n * @fileoverview Main entry point for kaitai-struct-ts library\n * @module kaitai-struct-ts\n * @author Fabiano Pinto\n * @license MIT\n * @version 0.2.0\n *\n * @description\n * A runtime interpreter for Kaitai Struct binary format definitions in TypeScript.\n * Parse any binary data format by providing a .ksy (Kaitai Struct YAML) definition file.\n *\n * @example\n * ```typescript\n * import { parse } from 'kaitai-struct-ts'\n *\n * const ksyDefinition = `\n * meta:\n * id: my_format\n * endian: le\n * seq:\n * - id: magic\n * contents: [0x4D, 0x5A]\n * - id: version\n * type: u2\n * `\n *\n * const buffer = new Uint8Array([0x4D, 0x5A, 0x01, 0x00])\n * const result = parse(ksyDefinition, buffer)\n * console.log(result.version) // 1\n * ```\n */\n\nimport { KaitaiStream } from './stream'\nimport { KsyParser } from './parser'\nimport { TypeInterpreter } from './interpreter'\n\n// Export main classes\nexport { KaitaiStream } from './stream'\nexport { KsyParser } from './parser'\nexport { TypeInterpreter } from './interpreter'\nexport { Context } from './interpreter'\n\n// Export types from schema\nexport type {\n KsySchema,\n MetaSpec,\n AttributeSpec,\n InstanceSpec,\n SwitchType,\n EnumSpec,\n ParamSpec,\n Endianness,\n EndianExpression,\n RepeatSpec,\n ProcessSpec,\n ProcessObject,\n ValidationResult,\n ValidationError as SchemaValidationError,\n ValidationWarning,\n} from './parser/schema'\n\nexport {\n BUILTIN_TYPES,\n isBuiltinType,\n getTypeEndianness,\n getBaseType,\n isIntegerType,\n isFloatType,\n isStringType,\n} from './parser/schema'\n\n// Export error classes\nexport * from './utils/errors'\n\n/**\n * Parse binary data using a Kaitai Struct definition.\n * This is the main convenience function for parsing.\n *\n * @param ksyYaml - YAML string containing the .ksy definition\n * @param buffer - Binary data to parse (ArrayBuffer or Uint8Array)\n * @param options - Parsing options\n * @returns Parsed object with fields defined in the .ksy file\n * @throws {ParseError} If YAML parsing fails\n * @throws {ValidationError} If schema validation fails\n * @throws {EOFError} If unexpected end of stream is reached\n *\n * @example\n * ```typescript\n * const result = parse(ksyYaml, binaryData)\n * console.log(result.fieldName)\n * ```\n */\nexport function parse(\n ksyYaml: string,\n buffer: ArrayBuffer | Uint8Array,\n options: ParseOptions = {}\n): Record<string, unknown> {\n const { validate = true, strict = false } = options\n\n // Parse the KSY schema\n const parser = new KsyParser()\n const schema = parser.parse(ksyYaml, { validate, strict })\n\n // Create a stream from the buffer\n const stream = new KaitaiStream(buffer)\n\n // Create an interpreter and parse\n const interpreter = new TypeInterpreter(schema)\n return interpreter.parse(stream)\n}\n\n/**\n * Options for the parse function.\n *\n * @interface ParseOptions\n */\nexport interface ParseOptions {\n /** Whether to validate the schema (default: true) */\n validate?: boolean\n\n /** Whether to treat warnings as errors (default: false) */\n strict?: boolean\n}\n"],"mappings":";AAkBO,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA,EACrC,YACE,SACO,UACP;AACA,UAAM,OAAO;AAFN;AAGP,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,aAAY,SAAS;AAAA,EACnD;AACF;AAaO,IAAM,kBAAN,MAAM,yBAAwB,YAAY;AAAA,EAC/C,YAAY,SAAiB,UAAmB;AAC9C,UAAM,SAAS,QAAQ;AACvB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,iBAAgB,SAAS;AAAA,EACvD;AACF;AAaO,IAAM,aAAN,MAAM,oBAAmB,YAAY;AAAA,EAC1C,YAAY,SAAiB,UAAmB;AAC9C,UAAM,SAAS,QAAQ;AACvB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,YAAW,SAAS;AAAA,EAClD;AACF;AAaO,IAAM,WAAN,MAAM,kBAAiB,YAAY;AAAA,EACxC,YAAY,UAAkB,4BAA4B,UAAmB;AAC3E,UAAM,SAAS,QAAQ;AACvB,SAAK,OAAO;AACZ,W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