@k67/kaitai-struct-ts 0.8.0 → 0.10.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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../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"],"sourcesContent":["/**\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","/**\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 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 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 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 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 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: AttributeSpec & { value?: string | number | boolean },\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, 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 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 const encoding = this.schema.meta?.encoding || 'UTF-8'\n\n if (type === 'strz') {\n // Null-terminated string with default parameters\n return stream.readStrz(encoding, 0, false, true, true)\n } else if (type === 'str') {\n // str type requires size, size-eos, or terminator\n throw new ParseError(\n 'str type requires size, size-eos, or terminator attribute'\n )\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBO,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,M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AM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,QACrG;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;;;AbrpBO,SAAS,MACd,SACA,QACA,UAAwB,CAAC,GACA;AACzB,QAAM,EAAE,WAAW,MAAM,SAAS,MAAM,IAAI;AAG5C,QAAM,SAAS,IAAI,UAAU;AAC7B,QAAM,SAAS,OAAO,MAAM,SAAS,EAAE,UAAU,OAAO,CAAC;AAGzD,QAAM,SAAS,IAAI,aAAa,MAAM;AAGtC,QAAM,cAAc,IAAI,gBAAgB,MAAM;AAC9C,SAAO,YAAY,MAAM,MAAM;AACjC;","names":["parseYaml"]}
1
+ {"version":3,"sources":["../src/index.ts","../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/utils/process.ts","../src/interpreter/TypeInterpreter.ts"],"sourcesContent":["/**\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","/**\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 public context?: Uint8Array\n ) {\n super(KaitaiError.formatMessage(message, position, context))\n this.name = 'KaitaiError'\n Object.setPrototypeOf(this, KaitaiError.prototype)\n }\n\n /**\n * Format error message with position and context.\n * @private\n */\n private static formatMessage(\n message: string,\n position?: number,\n context?: Uint8Array\n ): string {\n let formatted = message\n\n if (position !== undefined) {\n formatted += ` (at byte offset 0x${position.toString(16).toUpperCase()})`\n }\n\n if (context && context.length > 0) {\n const hexContext = KaitaiError.formatHexContext(context, position)\n formatted += `\\n${hexContext}`\n }\n\n return formatted\n }\n\n /**\n * Format hex dump context around error position.\n * @private\n */\n private static formatHexContext(data: Uint8Array, position?: number): string {\n const contextSize = 16 // Show 16 bytes before and after\n const start = Math.max(0, (position ?? 0) - contextSize)\n const end = Math.min(data.length, (position ?? 0) + contextSize)\n const chunk = data.slice(start, end)\n\n const lines: string[] = ['Context:']\n let offset = start\n\n for (let i = 0; i < chunk.length; i += 16) {\n const lineBytes = chunk.slice(i, i + 16)\n const hex = Array.from(lineBytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(' ')\n const ascii = Array.from(lineBytes)\n .map((b) => (b >= 32 && b <= 126 ? String.fromCharCode(b) : '.'))\n .join('')\n\n const offsetStr = ` ${(offset + i).toString(16).padStart(8, '0')}`\n const marker =\n position !== undefined &&\n position >= offset + i &&\n position < offset + i + lineBytes.length\n ? ' <--'\n : ''\n\n lines.push(`${offsetStr}: ${hex.padEnd(48, ' ')} | ${ascii}${marker}`)\n }\n\n return lines.join('\\n')\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, context?: Uint8Array) {\n super(message, position, context)\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, context?: Uint8Array) {\n super(message, position, context)\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(\n message: string = 'Unexpected end of stream',\n position?: number,\n context?: Uint8Array\n ) {\n super(message, position, context)\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 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 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 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 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 if ((BUILTIN_TYPES as readonly string[]).includes(type)) return true\n // Bit field types: b1, b2, ..., b64\n if (/^b\\d+$/.test(type)) return true\n return false\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 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 * @throws {ParseError} If import resolution fails\n * @example\n * ```typescript\n * const parser = new KsyParser()\n * const imports = new Map([\n * ['/common/riff', riffYamlContent]\n * ])\n * const schema = parser.parseWithImports(wavYaml, imports)\n * ```\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 // If no imports declared, return as-is\n if (!mainSchema.meta.imports || mainSchema.meta.imports.length === 0) {\n return mainSchema\n }\n\n // Resolve imports\n const resolvedTypes: Record<string, KsySchema> = {}\n\n for (const importPath of mainSchema.meta.imports) {\n // Check if import is provided\n if (!imports.has(importPath)) {\n throw new ParseError(\n `Import not found: ${importPath}. Available imports: ${Array.from(imports.keys()).join(', ')}`\n )\n }\n\n // Parse the imported schema\n const importYaml = imports.get(importPath)!\n const importedSchema = this.parse(importYaml, {\n ...options,\n validate: false, // Skip validation for imported schemas\n })\n\n // Extract the namespace from the import path\n // e.g., '/common/riff' -> 'riff'\n const namespace = this.extractNamespace(importPath)\n\n // Add imported types to the resolved types with namespace prefix\n if (importedSchema.types) {\n for (const [typeName, typeSchema] of Object.entries(\n importedSchema.types\n )) {\n const qualifiedName = `${namespace}::${typeName}`\n resolvedTypes[qualifiedName] = typeSchema\n }\n }\n\n // Add the root imported schema as a type\n // This allows referencing the imported schema directly\n resolvedTypes[namespace] = {\n meta: importedSchema.meta,\n seq: importedSchema.seq,\n instances: importedSchema.instances,\n types: importedSchema.types,\n enums: importedSchema.enums,\n }\n\n // Merge enums from imported schema\n if (importedSchema.enums) {\n if (!mainSchema.enums) {\n mainSchema.enums = {}\n }\n for (const [enumName, enumSpec] of Object.entries(\n importedSchema.enums\n )) {\n const qualifiedEnumName = `${namespace}::${enumName}`\n mainSchema.enums[qualifiedEnumName] = enumSpec\n }\n }\n }\n\n // Merge resolved types into main schema\n if (Object.keys(resolvedTypes).length > 0) {\n mainSchema.types = {\n ...resolvedTypes,\n ...mainSchema.types,\n }\n }\n\n return mainSchema\n }\n\n /**\n * Extract namespace from import path.\n * Converts paths like '/common/riff' or 'common/riff' to 'riff'.\n *\n * @param importPath - Import path from meta.imports\n * @returns Namespace identifier\n * @private\n */\n private extractNamespace(importPath: string): string {\n // Remove leading slash if present\n const normalized = importPath.startsWith('/')\n ? importPath.slice(1)\n : importPath\n\n // Get the last segment of the path\n const segments = normalized.split('/')\n return segments[segments.length - 1]\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 // Handle binary numbers (0b...)\n if (this.current === '0' && this.peek() === 'b') {\n value += this.current\n this.advance()\n value += this.current\n this.advance()\n\n while (this.current !== null && /[01]/.test(this.current)) {\n value += this.current\n this.advance()\n }\n\n return createToken(TokenType.NUMBER, parseInt(value, 2), 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 * Array literal node ([a, b, c]).\n */\nexport interface ArrayLiteralNode extends ASTNode {\n kind: 'ArrayLiteral'\n elements: ASTNode[]\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 | ArrayLiteralNode\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/**\n * Create an array literal node.\n */\nexport function createArrayLiteral(elements: ASTNode[]): ArrayLiteralNode {\n return { kind: 'ArrayLiteral', elements }\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 createArrayLiteral,\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 // Array literal\n if (this.match(TokenType.LBRACKET)) {\n const elements: ASTNode[] = []\n if (this.current().type !== TokenType.RBRACKET) {\n elements.push(this.parseTernary())\n while (this.match(TokenType.COMMA)) {\n elements.push(this.parseTernary())\n }\n }\n this.expect(TokenType.RBRACKET, 'Expected ] after array literal')\n return createArrayLiteral(elements)\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 case 'ArrayLiteral':\n return this.evaluateArrayLiteral(n.elements, 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.bitwiseOp(leftVal, rightVal, (a, b) => a << b)\n case '>>':\n return this.bitwiseOp(leftVal, rightVal, (a, b) => a >> b)\n case '&':\n return this.bitwiseOp(leftVal, rightVal, (a, b) => a & b)\n case '|':\n return this.bitwiseOp(leftVal, rightVal, (a, b) => a | b)\n case '^':\n return this.bitwiseOp(leftVal, rightVal, (a, b) => a ^ b)\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 // Handle special Kaitai Struct pseudo-properties that act like methods\n if (property === 'to_i') {\n // Convert to integer (works for numbers, strings, etc.)\n if (typeof obj === 'number') return Math.floor(obj)\n if (typeof obj === 'bigint') return Number(obj)\n if (typeof obj === 'string') return parseInt(obj, 10)\n if (typeof obj === 'boolean') return obj ? 1 : 0\n return this.toInt(obj)\n }\n\n if (property === 'to_s') {\n return String(obj)\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 const evalArgs = args.map((arg) => this.evaluate(arg, context))\n\n // Array/String length\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 // Type conversions\n if (method === 'to_i') {\n const base = evalArgs.length > 0 ? this.toInt(evalArgs[0]) : 10\n if (typeof obj === 'string') {\n return parseInt(obj, base)\n }\n return this.toInt(obj)\n }\n\n if (method === 'to_s') {\n return String(obj)\n }\n\n // String methods\n if (typeof obj === 'string') {\n return this.evaluateStringMethod(obj, method, evalArgs)\n }\n\n // Array methods\n if (Array.isArray(obj) || obj instanceof Uint8Array) {\n return this.evaluateArrayMethod(obj, method, evalArgs)\n }\n\n throw new ParseError(`Unknown method: ${method}`)\n }\n\n /**\n * Evaluate string methods.\n * @private\n */\n private evaluateStringMethod(\n str: string,\n method: string,\n args: unknown[]\n ): unknown {\n switch (method) {\n case 'substring': {\n const start = args.length > 0 ? this.toInt(args[0]) : 0\n const end = args.length > 1 ? this.toInt(args[1]) : undefined\n return str.substring(start, end)\n }\n\n case 'substr': {\n const start = args.length > 0 ? this.toInt(args[0]) : 0\n const length = args.length > 1 ? this.toInt(args[1]) : undefined\n return str.substr(start, length)\n }\n\n case 'reverse':\n return str.split('').reverse().join('')\n\n case 'to_i': {\n const base = args.length > 0 ? this.toInt(args[0]) : 10\n return parseInt(str, base)\n }\n\n case 'length':\n case 'size':\n return str.length\n\n // Ruby-style string methods used in Kaitai\n case 'upcase':\n case 'to_upper':\n return str.toUpperCase()\n\n case 'downcase':\n case 'to_lower':\n return str.toLowerCase()\n\n case 'capitalize':\n return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()\n\n case 'strip':\n case 'trim':\n return str.trim()\n\n case 'lstrip':\n case 'trim_start':\n return str.trimStart()\n\n case 'rstrip':\n case 'trim_end':\n return str.trimEnd()\n\n case 'starts_with':\n case 'startsWith': {\n if (args.length === 0) {\n throw new ParseError('starts_with requires 1 argument')\n }\n return str.startsWith(String(args[0]))\n }\n\n case 'ends_with':\n case 'endsWith': {\n if (args.length === 0) {\n throw new ParseError('ends_with requires 1 argument')\n }\n return str.endsWith(String(args[0]))\n }\n\n case 'includes':\n case 'contains': {\n if (args.length === 0) {\n throw new ParseError('includes requires 1 argument')\n }\n return str.includes(String(args[0]))\n }\n\n case 'index_of':\n case 'indexOf': {\n if (args.length === 0) {\n throw new ParseError('index_of requires 1 argument')\n }\n return str.indexOf(String(args[0]))\n }\n\n case 'split': {\n if (args.length === 0) {\n throw new ParseError('split requires 1 argument')\n }\n return str.split(String(args[0]))\n }\n\n case 'replace': {\n if (args.length < 2) {\n throw new ParseError('replace requires 2 arguments')\n }\n return str.replace(String(args[0]), String(args[1]))\n }\n\n case 'replace_all':\n case 'replaceAll': {\n if (args.length < 2) {\n throw new ParseError('replace_all requires 2 arguments')\n }\n const search = String(args[0])\n const replace = String(args[1])\n // Use split/join for compatibility with older targets\n return str.split(search).join(replace)\n }\n\n case 'pad_left':\n case 'padStart': {\n if (args.length === 0) {\n throw new ParseError('pad_left requires at least 1 argument')\n }\n const length = this.toInt(args[0])\n const fillString = args.length > 1 ? String(args[1]) : ' '\n return str.padStart(length, fillString)\n }\n\n case 'pad_right':\n case 'padEnd': {\n if (args.length === 0) {\n throw new ParseError('pad_right requires at least 1 argument')\n }\n const length = this.toInt(args[0])\n const fillString = args.length > 1 ? String(args[1]) : ' '\n return str.padEnd(length, fillString)\n }\n\n default:\n throw new ParseError(`Unknown string method: ${method}`)\n }\n }\n\n /**\n * Evaluate array methods.\n * @private\n */\n private evaluateArrayMethod(\n arr: unknown[] | Uint8Array,\n method: string,\n args: unknown[]\n ): unknown {\n const array = Array.isArray(arr) ? arr : Array.from(arr)\n\n switch (method) {\n case 'length':\n case 'size':\n return array.length\n\n case 'first':\n return array[0]\n\n case 'last':\n return array[array.length - 1]\n\n case 'min':\n return Math.min(...array.map((v) => this.toNumber(v)))\n\n case 'max':\n return Math.max(...array.map((v) => this.toNumber(v)))\n\n case 'reverse':\n return [...array].reverse()\n\n case 'sort':\n return [...array].sort((a, b) => this.compare(a, b))\n\n case 'includes':\n case 'contains': {\n if (args.length === 0) {\n throw new ParseError('includes requires 1 argument')\n }\n return array.some((item) => this.equals(item, args[0]))\n }\n\n case 'index_of':\n case 'indexOf': {\n if (args.length === 0) {\n throw new ParseError('index_of requires 1 argument')\n }\n return array.findIndex((item) => this.equals(item, args[0]))\n }\n\n case 'slice': {\n const start = args.length > 0 ? this.toInt(args[0]) : 0\n const end = args.length > 1 ? this.toInt(args[1]) : undefined\n return array.slice(start, end)\n }\n\n default:\n throw new ParseError(`Unknown array method: ${method}`)\n }\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: Bitwise operation with BigInt support.\n * JavaScript bitwise operators work on 32-bit integers, but Kaitai\n * may use 64-bit values. For values that fit in 32 bits, use native ops.\n * For larger values, convert to BigInt (with limitations).\n * @private\n */\n private bitwiseOp(\n left: unknown,\n right: unknown,\n op: (a: number, b: number) => number\n ): number | bigint {\n // Check if we're dealing with BigInt values\n if (typeof left === 'bigint' || typeof right === 'bigint') {\n // Convert to BigInt and perform operation\n const leftBig = typeof left === 'bigint' ? left : BigInt(left as number)\n const rightBig =\n typeof right === 'bigint' ? right : BigInt(right as number)\n\n // BigInt bitwise operations\n // Note: Shift operations require the right operand to be a regular number\n if (op.toString().includes('<<')) {\n return leftBig << BigInt(Number(rightBig))\n }\n if (op.toString().includes('>>')) {\n return leftBig >> BigInt(Number(rightBig))\n }\n if (op.toString().includes('&')) {\n return leftBig & rightBig\n }\n if (op.toString().includes('|')) {\n return leftBig | rightBig\n }\n if (op.toString().includes('^')) {\n return leftBig ^ rightBig\n }\n }\n\n // Handle undefined/null values\n if (\n left === undefined ||\n left === null ||\n right === undefined ||\n right === null\n ) {\n throw new ParseError('Cannot perform bitwise operation on null/undefined')\n }\n\n // For regular numbers, use 32-bit operations\n return op(this.toInt(left), this.toInt(right))\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\n // Sequence equality: support number[] and Uint8Array\n const toArray = (v: unknown): number[] | null => {\n if (Array.isArray(v))\n return v.map((x) => (typeof x === 'bigint' ? Number(x) : (x as number)))\n if (v instanceof Uint8Array) return Array.from(v)\n return null\n }\n\n const leftArr = toArray(left)\n const rightArr = toArray(right)\n if (leftArr && rightArr) {\n if (leftArr.length !== rightArr.length) return false\n for (let i = 0; i < leftArr.length; i++) {\n if (leftArr[i] !== rightArr[i]) return false\n }\n return true\n }\n\n return left === right\n }\n\n /**\n * Evaluate an array literal.\n * @private\n */\n private evaluateArrayLiteral(\n elements: ASTNode[],\n context: Context\n ): unknown[] {\n return elements.map((e) => this.evaluate(e, context))\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 // Strip unsupported generic cast syntax like .as<bytes>\n // This is a no-op for our evaluator since we infer types dynamically.\n const preprocessed = expression.replace(/\\.as<[^>]+>/g, '')\n // Lexical analysis\n const lexer = new Lexer(preprocessed)\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 Data processing utilities for Kaitai Struct\n * @module utils/process\n * @author Fabiano Pinto\n * @license MIT\n */\n\nimport { ParseError } from './errors'\nimport { inflate } from 'pako'\n\n/**\n * Process algorithms supported by Kaitai Struct.\n * These transform data before parsing (decompression, decryption, etc.)\n */\nexport type ProcessAlgorithm =\n | 'zlib'\n | 'xor'\n | 'rol'\n | 'ror'\n | 'bswap2'\n | 'bswap4'\n | 'bswap8'\n | 'bswap16'\n\n/**\n * Process specification - can be a string or object with parameters.\n */\nexport interface ProcessSpec {\n /** Algorithm name */\n algorithm?: string\n /** XOR key (for xor algorithm) */\n key?: number | number[]\n /** Rotation amount (for rol/ror algorithms) */\n amount?: number\n /** Group size (for rol/ror algorithms) */\n group?: number\n}\n\n/**\n * Apply processing transformation to data.\n *\n * @param data - Input data to process\n * @param process - Processing specification (string or object)\n * @returns Processed data\n * @throws {ParseError} If processing fails or algorithm is unknown\n *\n * @example\n * ```typescript\n * // XOR with single byte key\n * const decrypted = applyProcess(encrypted, { algorithm: 'xor', key: 0xFF })\n *\n * // Zlib decompression\n * const decompressed = applyProcess(compressed, 'zlib')\n *\n * // Rotate left by 3 bits\n * const rotated = applyProcess(data, { algorithm: 'rol', amount: 3 })\n * ```\n */\nexport function applyProcess(\n data: Uint8Array,\n process: string | ProcessSpec\n): Uint8Array {\n // Parse process specification\n const spec: ProcessSpec =\n typeof process === 'string' ? { algorithm: process } : process\n\n const algorithm = spec.algorithm\n\n if (!algorithm) {\n throw new ParseError('Process specification missing algorithm')\n }\n\n switch (algorithm) {\n case 'zlib':\n return processZlib(data)\n\n case 'xor':\n return processXor(data, spec.key)\n\n case 'rol':\n return processRol(data, spec.amount, spec.group)\n\n case 'ror':\n return processRor(data, spec.amount, spec.group)\n\n case 'bswap2':\n return processByteswap(data, 2)\n\n case 'bswap4':\n return processByteswap(data, 4)\n\n case 'bswap8':\n return processByteswap(data, 8)\n\n case 'bswap16':\n return processByteswap(data, 16)\n\n default:\n throw new ParseError(\n `Unknown process algorithm: ${algorithm}. ` +\n `Supported: zlib, xor, rol, ror, bswap2, bswap4, bswap8, bswap16`\n )\n }\n}\n\n/**\n * Decompress data using zlib/deflate algorithm.\n *\n * @param data - Compressed data\n * @returns Decompressed data\n * @throws {ParseError} If decompression fails\n * @private\n */\nfunction processZlib(data: Uint8Array): Uint8Array {\n try {\n return inflate(data)\n } catch (error) {\n throw new ParseError(\n `Zlib decompression failed: ${error instanceof Error ? error.message : String(error)}`\n )\n }\n}\n\n/**\n * XOR data with a key.\n * Supports single-byte key or multi-byte key (repeated cyclically).\n *\n * @param data - Input data\n * @param key - XOR key (number or array of numbers)\n * @returns XORed data\n * @throws {ParseError} If key is invalid\n * @private\n */\nfunction processXor(\n data: Uint8Array,\n key: number | number[] | undefined\n): Uint8Array {\n if (key === undefined) {\n throw new ParseError('XOR process requires a key parameter')\n }\n\n const result = new Uint8Array(data.length)\n const keyBytes = Array.isArray(key) ? key : [key]\n\n if (keyBytes.length === 0) {\n throw new ParseError('XOR key cannot be empty')\n }\n\n for (let i = 0; i < data.length; i++) {\n result[i] = data[i] ^ keyBytes[i % keyBytes.length]\n }\n\n return result\n}\n\n/**\n * Rotate bits left (ROL).\n * Rotates each byte or group of bytes left by the specified amount.\n *\n * @param data - Input data\n * @param amount - Number of bits to rotate (default: 1)\n * @param group - Group size in bytes (default: 1)\n * @returns Rotated data\n * @throws {ParseError} If parameters are invalid\n * @private\n */\nfunction processRol(\n data: Uint8Array,\n amount: number | undefined,\n group: number | undefined\n): Uint8Array {\n const bits = amount ?? 1\n const groupSize = group ?? 1\n\n if (bits < 0 || bits > 7) {\n throw new ParseError('ROL amount must be between 0 and 7')\n }\n\n if (groupSize !== 1) {\n throw new ParseError('ROL with group size > 1 not yet supported')\n }\n\n const result = new Uint8Array(data.length)\n\n for (let i = 0; i < data.length; i++) {\n const byte = data[i]\n result[i] = ((byte << bits) | (byte >> (8 - bits))) & 0xff\n }\n\n return result\n}\n\n/**\n * Rotate bits right (ROR).\n * Rotates each byte or group of bytes right by the specified amount.\n *\n * @param data - Input data\n * @param amount - Number of bits to rotate (default: 1)\n * @param group - Group size in bytes (default: 1)\n * @returns Rotated data\n * @throws {ParseError} If parameters are invalid\n * @private\n */\nfunction processRor(\n data: Uint8Array,\n amount: number | undefined,\n group: number | undefined\n): Uint8Array {\n const bits = amount ?? 1\n const groupSize = group ?? 1\n\n if (bits < 0 || bits > 7) {\n throw new ParseError('ROR amount must be between 0 and 7')\n }\n\n if (groupSize !== 1) {\n throw new ParseError('ROR with group size > 1 not yet supported')\n }\n\n const result = new Uint8Array(data.length)\n\n for (let i = 0; i < data.length; i++) {\n const byte = data[i]\n result[i] = ((byte >> bits) | (byte << (8 - bits))) & 0xff\n }\n\n return result\n}\n\n/**\n * Byte swap (reverse byte order in groups).\n * Swaps bytes within groups of the specified size.\n *\n * @param data - Input data\n * @param groupSize - Size of groups to swap (2, 4, 8, or 16 bytes)\n * @returns Byte-swapped data\n * @throws {ParseError} If group size is invalid or data length is not aligned\n * @private\n */\nfunction processByteswap(data: Uint8Array, groupSize: number): Uint8Array {\n if (![2, 4, 8, 16].includes(groupSize)) {\n throw new ParseError(\n `Invalid byteswap group size: ${groupSize}. Must be 2, 4, 8, or 16`\n )\n }\n\n if (data.length % groupSize !== 0) {\n throw new ParseError(\n `Data length ${data.length} is not aligned to group size ${groupSize}`\n )\n }\n\n const result = new Uint8Array(data.length)\n\n for (let i = 0; i < data.length; i += groupSize) {\n for (let j = 0; j < groupSize; j++) {\n result[i + j] = data[i + groupSize - 1 - j]\n }\n }\n\n return result\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/KaitaiStream'\nimport {\n KsySchema,\n AttributeSpec,\n Endianness,\n EndianExpression,\n isBuiltinType,\n getBaseType,\n getTypeEndianness,\n isIntegerType,\n isFloatType,\n isStringType,\n} from '../parser/schema'\nimport { Context } from './Context'\nimport { evaluateExpression } from '../expression'\nimport { ParseError, ValidationError } from '../utils/errors'\nimport { applyProcess } from '../utils/process'\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 * Safely extract a KaitaiStream from an object that may expose `_io`.\n * Avoids using `any` casts to satisfy linting.\n */\n private static getKaitaiIO(val: unknown): KaitaiStream | null {\n if (val && typeof val === 'object') {\n const rec = val as Record<string, unknown>\n const maybe = rec['_io']\n if (maybe instanceof KaitaiStream) return maybe\n }\n return null\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 * @param root - Root object of the parse tree (for nested types)\n * @returns Parsed object\n */\n parse(\n stream: KaitaiStream,\n parent?: unknown,\n typeArgs?: Array<string | number | boolean>,\n root?: unknown\n ): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n\n // For top-level parse, result is the root; for nested, use provided root\n const actualRoot = root || result\n const context = new Context(stream, actualRoot, parent, this.schema.enums)\n context.current = result\n\n // Track starting position for _sizeof calculation\n const startPos = stream.pos\n\n // Expose current stream for use in expressions (e.g., slot._io)\n ;(result as Record<string, unknown>)['_io'] = stream\n\n // Expose root for nested types\n if (root) {\n ;(result as Record<string, unknown>)['_root'] = root\n }\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 // Set up lazy-evaluated instances BEFORE parsing seq fields\n // This allows seq fields to reference instances in their expressions\n if (this.schema.instances) {\n this.setupInstances(result, stream, context)\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 // Calculate and store _sizeof (number of bytes consumed)\n const endPos = stream.pos\n ;(result as Record<string, unknown>)['_sizeof'] = endPos - startPos\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: AttributeSpec & { value?: string | number | boolean },\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, 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 // Determine the stream to use (support custom I/O via attr.io)\n let stream: KaitaiStream = context.io\n if (attr.io !== undefined) {\n const ioVal = this.evaluateValue(attr.io, context)\n if (ioVal instanceof KaitaiStream) {\n stream = ioVal\n } else {\n const kio = TypeInterpreter.getKaitaiIO(ioVal)\n if (kio) {\n stream = kio\n } else {\n throw new ParseError(\n 'io must evaluate to a KaitaiStream or an object with _io'\n )\n }\n }\n }\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 // Custom I/O handled above by selecting stream\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 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 =\n attr.encoding ||\n this.schema.meta?.encoding ||\n this.parentMeta?.encoding ||\n '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 =\n attr.encoding ||\n this.schema.meta?.encoding ||\n this.parentMeta?.encoding ||\n '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 =\n attr.encoding ||\n this.schema.meta?.encoding ||\n this.parentMeta?.encoding ||\n 'UTF-8'\n const bytes = stream.readBytesFull()\n // eslint-disable-next-line no-undef\n return new TextDecoder(encoding).decode(bytes)\n } else {\n let bytes = stream.readBytesFull()\n // Apply processing if specified\n if (attr.process) {\n bytes = this.applyProcessing(bytes, attr.process)\n }\n if (type) {\n const sub = new KaitaiStream(bytes)\n return this.parseType(type, sub, context, attr['type-args'])\n }\n return bytes\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 // Parse parameterized type syntax: type_name(arg1, arg2, ...)\n const { typeName, args } = this.parseParameterizedType(type, context)\n const effectiveArgs = args.length > 0 ? args : typeArgs\n\n // Handle built-in types\n if (isBuiltinType(typeName)) {\n return this.parseBuiltinType(typeName, stream, context)\n }\n\n // Handle user-defined types\n if (this.schema.types && typeName in this.schema.types) {\n const typeSchema = this.schema.types[typeName]\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(\n stream,\n context.current,\n effectiveArgs,\n context.root\n )\n }\n\n throw new ParseError(`Unknown type: ${typeName}`)\n }\n\n /**\n * Parse parameterized type syntax and extract type name and arguments.\n * Supports: type_name(arg1, arg2, ...) or just type_name\n *\n * @param typeSpec - Type specification string\n * @param context - Execution context for evaluating argument expressions\n * @returns Object with typeName and evaluated args\n * @private\n */\n private parseParameterizedType(\n typeSpec: string,\n context: Context\n ): { typeName: string; args: Array<string | number | boolean> } {\n // Check if type has parameters: type_name(...)\n const match = typeSpec.match(/^([a-z_][a-z0-9_]*)\\((.*)\\)$/i)\n\n if (!match) {\n // No parameters, return as-is\n return { typeName: typeSpec, args: [] }\n }\n\n const typeName = match[1]\n const argsString = match[2].trim()\n\n if (!argsString) {\n // Empty parameters: type_name()\n return { typeName, args: [] }\n }\n\n // Parse arguments - handle strings, numbers, booleans, and expressions\n const args: Array<string | number | boolean> = []\n let current = ''\n let inString = false\n let stringChar = ''\n let parenDepth = 0\n\n for (let i = 0; i < argsString.length; i++) {\n const char = argsString[i]\n\n if (inString) {\n current += char\n if (char === stringChar && argsString[i - 1] !== '\\\\') {\n inString = false\n }\n } else if (char === '\"' || char === \"'\") {\n inString = true\n stringChar = char\n current += char\n } else if (char === '(') {\n parenDepth++\n current += char\n } else if (char === ')') {\n parenDepth--\n current += char\n } else if (char === ',' && parenDepth === 0) {\n // Argument separator\n args.push(this.parseArgument(current.trim(), context))\n current = ''\n } else {\n current += char\n }\n }\n\n // Add last argument\n if (current.trim()) {\n args.push(this.parseArgument(current.trim(), context))\n }\n\n return { typeName, args }\n }\n\n /**\n * Parse and evaluate a single type argument.\n *\n * @param arg - Argument string\n * @param context - Execution context\n * @returns Evaluated argument value\n * @private\n */\n private parseArgument(\n arg: string,\n context: Context\n ): string | number | boolean {\n // Boolean literals\n if (arg === 'true') return true\n if (arg === 'false') return false\n\n // String literals\n if (\n (arg.startsWith('\"') && arg.endsWith('\"')) ||\n (arg.startsWith(\"'\") && arg.endsWith(\"'\"))\n ) {\n return arg.slice(1, -1)\n }\n\n // Numeric literals\n if (/^-?\\d+$/.test(arg)) {\n return parseInt(arg, 10)\n }\n if (/^-?\\d+\\.\\d+$/.test(arg)) {\n return parseFloat(arg)\n }\n if (/^0x[0-9a-f]+$/i.test(arg)) {\n return parseInt(arg, 16)\n }\n\n // Expression - evaluate in context\n try {\n const result = this.evaluateValue(arg, context)\n // Convert to primitive types\n if (\n typeof result === 'string' ||\n typeof result === 'number' ||\n typeof result === 'boolean'\n ) {\n return result\n }\n // For other types, convert to number if possible\n return Number(result)\n } catch {\n // If evaluation fails, treat as string\n return arg\n }\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\n // Resolve endianness (static or expression-based)\n let endian: Endianness\n if (typeEndian) {\n // Type-specific endianness (e.g., u4le, u4be)\n endian = typeEndian\n } else if (typeof metaEndian === 'string') {\n // Static endianness from meta\n endian = metaEndian\n } else if (metaEndian && typeof metaEndian === 'object') {\n // Expression-based endianness (switch-on)\n endian = this.evaluateEndianExpression(metaEndian, context)\n } else {\n // Default to little-endian\n endian = 'le'\n }\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 // Bit field types: b1, b2, ..., b64 (default bit-endian: BE)\n if (/^b\\d+$/.test(type)) {\n const n = parseInt(type.slice(1), 10)\n const val = stream.readBitsIntBe(n)\n // Return number when safely representable, else BigInt\n const maxSafe = BigInt(Number.MAX_SAFE_INTEGER)\n return val <= maxSafe ? Number(val) : val\n }\n\n // String types\n if (isStringType(type)) {\n const encoding = this.schema.meta?.encoding || 'UTF-8'\n\n if (type === 'strz') {\n // Null-terminated string with default parameters\n return stream.readStrz(encoding, 0, false, true, true)\n } else if (type === 'str') {\n // str type requires size, size-eos, or terminator\n throw new ParseError(\n 'str type requires size, size-eos, or terminator attribute'\n )\n }\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 * Delegates to the process utility module.\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 return applyProcess(data, process)\n }\n\n /**\n * Evaluate expression-based endianness (switch-on).\n *\n * @param endianExpr - Endianness expression with switch-on and cases\n * @param context - Execution context\n * @returns Resolved endianness ('le' or 'be')\n * @private\n */\n private evaluateEndianExpression(\n endianExpr: EndianExpression,\n context: Context\n ): Endianness {\n const switchOn = endianExpr['switch-on']\n const cases = endianExpr.cases\n\n if (!switchOn || typeof switchOn !== 'string') {\n throw new ParseError('Endian expression missing \"switch-on\" field')\n }\n\n if (!cases || typeof cases !== 'object') {\n throw new ParseError('Endian expression missing \"cases\" field')\n }\n\n // Evaluate the switch-on expression\n const switchValue = this.evaluateValue(switchOn, context)\n\n // Convert to string for case matching\n const key = String(switchValue)\n\n // Look up the endianness in cases\n if (key in cases) {\n const endian = cases[key]\n if (endian !== 'le' && endian !== 'be') {\n throw new ParseError(`Invalid endianness value: ${endian}`)\n }\n return endian\n }\n\n // Default to little-endian if no match\n return 'le'\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBO,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA,EACrC,YACE,SACO,UACA,SACP;AACA,UAAM,aAAY,cAAc,SAAS,UAAU,OAAO,CAAC;AAHpD;AACA;AAGP,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,aAAY,SAAS;AAAA,EACnD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAe,cACb,SACA,UACA,SACQ;AACR,QAAI,YAAY;AAEhB,QAAI,aAAa,QAAW;AAC1B,mBAAa,sBAAsB,SAAS,SAAS,EAAE,EAAE,YAAY,CAAC;AAAA,IACxE;AAEA,QAAI,WAAW,QAAQ,SAAS,GAAG;AACjC,YAAM,aAAa,aAAY,iBAAiB,SAAS,QAAQ;AACjE,mBAAa;AAAA,EAAK,UAAU;AAAA,IAC9B;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAe,iBAAiB,MAAkB,UAA2B;AAC3E,UAAM,cAAc;AACpB,UAAM,QAAQ,KAAK,IAAI,IAAI,YAAY,KAAK,WAAW;AACvD,UAAM,MAAM,KAAK,IAAI,KAAK,SAAS,YAAY,KAAK,WAAW;AAC/D,UAAM,QAAQ,KAAK,MAAM,OAAO,GAAG;AAEnC,UAAM,QAAkB,CAAC,UAAU;AACn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