@remotex-labs/xjet 1.0.1 → 1.1.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/README.md +1 -0
- package/dist/bash.js +16 -16
- package/dist/bash.js.map +5 -5
- package/dist/index.d.ts +441 -90
- package/dist/index.js +23 -23
- package/dist/index.js.map +1 -1
- package/dist/shared.d.ts +337 -0
- package/dist/shared.js +59 -59
- package/dist/shared.js.map +5 -5
- package/package.json +4 -4
package/dist/shared.js.map
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["https://github.com/remotex-labs/xAnsi/src/services/ast.service.ts", "https://github.com/remotex-labs/xAnsi/src/components/ansi.component.ts", "https://github.com/remotex-labs/xAnsi/src/services/shadow.service.ts", "https://github.com/remotex-labs/xAnsi/src/providers/styles.provider.ts", "https://github.com/remotex-labs/xAnsi/src/components/xterm.component.ts", "https://github.com/remotex-labs/xjet-expect/src/components/object.component.ts", "https://github.com/remotex-labs/xjet-expect/src/components/promise.component.ts", "https://github.com/remotex-labs/xjet-expect/src/components/serialize.component.ts", "https://github.com/remotex-labs/xjet-expect/src/modules/diff/providers/string.provider.ts", "https://github.com/remotex-labs/xjet-expect/src/modules/diff/components/semantic.component.ts", "https://github.com/remotex-labs/xjet-expect/src/components/color.component.ts", "https://github.com/remotex-labs/xjet-expect/src/modules/diff/components/diff.component.ts", "https://github.com/remotex-labs/xjet-expect/src/errors/base.error.ts", "https://github.com/remotex-labs/xjet-expect/src/components/format.component.ts", "https://github.com/remotex-labs/xjet-expect/src/errors/type.error.ts", "https://github.com/remotex-labs/xjet-expect/src/errors/expect.error.ts", "https://github.com/remotex-labs/xjet-expect/src/handlers/matchers.handler.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/functions.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/string.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/handlers/number.handler.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/number.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/handlers/mock.handler.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/mock.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/equality.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/object.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers.provider.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/abstract.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/any.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/array-of.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/close-to.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/anything.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/string-matching.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/array-containing.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/object-containing.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/string-containing.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns.provider.ts", "https://github.com/remotex-labs/xjet-expect/src/errors/promise.error.ts", "https://github.com/remotex-labs/xjet-expect/src/services/matcher.service.ts", "https://github.com/remotex-labs/xjet-expect/src/components/expect.component.ts", "../src/modules/shared/states/mock.state.ts", "../src/modules/symlinks/services/inject.service.ts", "https://github.com/remotex-lab/xStruct/src/components/buffer.component.ts", "https://github.com/remotex-lab/xStruct/src/components/struct.component.ts", "https://github.com/remotex-lab/xStruct/src/components/primitive.component.ts", "https://github.com/remotex-lab/xStruct/src/components/bitfield.component.ts", "https://github.com/remotex-lab/xStruct/src/components/string.component.ts", "https://github.com/remotex-lab/xStruct/src/services/struct.service.ts", "../src/modules/packets/schema/packet.schema.ts", "../src/modules/packets/constants/packet-schema.constants.ts", "../src/modules/packets/packets.module.ts", "../src/modules/shared/services/emit.service.ts", "../src/modules/messages/constants/report.constant.ts", "../src/modules/shared/models/describe.model.ts", "../src/modules/shared/errors/execution.error.ts", "../src/modules/shared/states/suite.state.ts", "https://github.com/remotex-lab/xmap/src/components/parser.component.ts", "../src/components/location.component.ts", "../src/modules/shared/components/log.component.ts", "../src/modules/shared/mock/spy.mock.ts", "../src/modules/shared/components/printf.component.ts", "../src/modules/shared/directives/each.directive.ts", "../src/errors/timeout.error.ts", "../src/components/timeout.component.ts", "../src/modules/shared/errors/failing.error.ts", "../src/modules/shared/models/test.model.ts", "../src/modules/shared/directives/test.directive.ts", "../src/modules/shared/directives/describe.directive.ts", "../src/modules/shared/mock/fn.mock.ts", "../src/modules/shared/models/hook.model.ts", "../src/modules/shared/directives/hook.directive.ts", "../src/modules/shared/shared.module.ts"],
|
|
4
|
-
"sourceRoot": "https://github.com/remotex-lab/xJet/tree/v1.0
|
|
5
|
-
"sourcesContent": ["/**\n * Maps ANSI styling codes to their corresponding reset codes\n *\n * @remarks\n * This mapping defines the relationship between ANSI control codes and the codes needed to reset each style.\n * The map is organized into text styling codes, foreground\n * colors, background colors, and reset codes. For reset codes, the value is null as they\n * don't require a specific reset code themselves.\n *\n * Text styles (1-9) map to their specific reset codes, while foreground colors (30-37)\n * all reset with code 39, and background colors (40-47) all reset with code 49.\n *\n * @example\n * ```ts\n * // Get the reset code for bold text (code 1)\n * const boldResetCode = ANSI_RESET_MAP['1']; // Returns '22'\n *\n * // Check if a code is a reset code itself\n * const isResetCode = ANSI_RESET_MAP['0'] === null; // Returns true\n * ```\n *\n * @since 1.0.0\n */\n\nconst ANSI_RESET_MAP: Record<string, string | null> = {\n // Text styles\n '1': '22',\n '2': '22',\n '3': '23',\n '4': '24',\n '5': '25',\n '7': '27',\n '8': '28',\n '9': '29',\n\n // Foreground colors\n '30': '39',\n '31': '39',\n '32': '39',\n '33': '39',\n '34': '39',\n '35': '39',\n '36': '39',\n '37': '39',\n '38': '39',\n '90': '39',\n '91': '39',\n '92': '39',\n '93': '39',\n '94': '39',\n '95': '39',\n '96': '39',\n '97': '39',\n\n // Background colors\n '40': '49',\n '41': '49',\n '42': '49',\n '43': '49',\n '44': '49',\n '45': '49',\n '46': '49',\n '47': '49',\n '48': '49',\n '100': '49',\n '101': '49',\n '102': '49',\n '103': '49',\n '104': '49',\n '105': '49',\n '106': '49',\n '107': '49',\n\n // Resets\n '0': null,\n '22': null,\n '23': null,\n '24': null,\n '25': null,\n '27': null,\n '28': null,\n '29': null,\n '39': null,\n '49': null\n};\n\n/**\n * Splits a string containing ANSI escape codes into individual characters,\n * preserving all active styling for each character.\n *\n * @param str - The ANSI-styled string to process.\n *\n * @returns An array of strings, where each element represents a single character\n * wrapped with its full active ANSI codes and corresponding reset codes.\n *\n * @remarks\n * This function handles ANSI escape sequences in a string and ensures that each\n * visible character retains the correct styling context.\n *\n * Behavior:\n * - Handles plain text characters and surrogate pairs correctly.\n * - Maintains multiple simultaneous ANSI styles.\n * - Resets styles when encountering `\\x1b[0m`.\n * - Supports one-time ANSI codes that affect only the next character.\n *\n * Implementation details:\n * - Tracks active ANSI codes in `prefix` and `suffix` arrays.\n * - Builds `currPrefixStr` and `currSuffixStr` for efficient string reconstruction.\n * - Uses `Array.from` to handle Unicode surrogate pairs.\n *\n * Example usage:\n * ```ts\n * const input = \"\\x1b[1m\\x1b[31mBold Red\\x1b[0m\";\n * const chars = splitWithAnsiContext(input);\n * // chars[0] = \"'\\x1B[1;31mB\\x1B[22;39m\"\n * // chars[1] = \"\\x1B[1;31mo\\x1B[22;39m\"\n * ```\n *\n * @since 1.0.0\n */\n\nexport function splitWithAnsiContext(str: string): Array<string> {\n if (!str) return [ '' ];\n\n const result: Array<string> = [];\n const prefix: Array<string> = [];\n const suffix: Array<string> = [];\n\n let oneTimePrefix = '';\n let currPrefixStr = '';\n let currSuffixStr = '';\n\n const ansiRe = /\\x1b\\[[0-9;]*m/g;\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = ansiRe.exec(str))) {\n const chunk = str.slice(lastIndex, match.index);\n\n // Use Array.from to handle surrogate pairs correctly\n for (const char of Array.from(chunk)) {\n result.push(oneTimePrefix + currPrefixStr + char + currSuffixStr);\n oneTimePrefix = '';\n }\n\n const token = match[0];\n const codeSeq = token.slice(2, -1);\n const semi = codeSeq.indexOf(';');\n const code = semi < 0 ? codeSeq : codeSeq.slice(0, semi);\n const resetCode = ANSI_RESET_MAP[code];\n\n if(code === '0') {\n prefix.length = 0;\n suffix.length = 0;\n currPrefixStr = '';\n currSuffixStr = '';\n oneTimePrefix += token;\n } else {\n if (resetCode && prefix[prefix.length - 1] !== codeSeq) {\n prefix.push(codeSeq);\n suffix.push(resetCode);\n currPrefixStr = `\\x1b[${ prefix.join(';') }m`;\n currSuffixStr = `\\x1b[${ suffix.join(';') }m`;\n } else if (suffix[suffix.length - 1] === codeSeq) {\n prefix.pop();\n suffix.pop();\n currPrefixStr = prefix.length ? `\\x1b[${ prefix.join(';') }m` : '';\n currSuffixStr = suffix.length ? `\\x1b[${ suffix.join(';') }m` : '';\n } else {\n oneTimePrefix += token;\n }\n }\n\n lastIndex = ansiRe.lastIndex;\n }\n\n const remaining = str.slice(lastIndex);\n for (const char of Array.from(remaining)) {\n result.push(oneTimePrefix + currPrefixStr + char + currSuffixStr);\n oneTimePrefix = '';\n }\n\n return result;\n}\n", "/**\n * Writes raw data directly to the standard output stream without any processing\n *\n * @param data - The string or Buffer to write to stdout\n *\n * @returns Nothing\n *\n * @example\n * ```ts\n * // Write an ANSI escape sequence followed by text\n * writeRaw('\\x1b[31mThis text is red\\x1b[0m');\n * ```\n *\n * @since 1.0.0\n */\n\nexport function writeRaw(data: string | Buffer): void {\n if(process.stdout.write)\n process.stdout.write(data);\n else\n console.log(data);\n}\n\n/**\n * Generates an ANSI escape sequence to move the terminal cursor to the specified position\n *\n * @param row - The row (line) number to move the cursor to (1-based index)\n * @param column - The column position to move the cursor to (1-based index)\n *\n * @returns ANSI escape sequence string that moves the cursor when written to the terminal\n *\n * @example\n * ```ts\n * // Move cursor to the beginning of line 5\n * const escapeSequence = moveCursor(5, 1);\n * process.stdout.write(escapeSequence);\n * ```\n *\n * @since 1.0.0\n */\n\nexport function moveCursor(row: number, column: number = 0): string {\n return `\\x1b[${ row };${ column }H`;\n}\n\n/**\n * Removes ANSI escape sequences from a string\n *\n * @param str - The input string containing ANSI escape sequences\n * @returns A plain string with all ANSI escape sequences removed\n *\n * @remarks\n * This function uses a regular expression to match and remove ANSI escape sequences\n * that control text styling in terminal output. These sequences typically start with\n * the escape character (x1b) followed by square brackets and control codes.\n *\n * The function is useful for:\n * - Getting accurate string length measurements without styling codes\n * - Preparing terminal output for non-terminal destinations (files, logs)\n * - Normalizing text for comparison or processing\n *\n * @example\n * ```ts\n * import { xterm, stripAnsi } from '@remotex-labs/xansi';\n *\n * const coloredText = xterm.red('Error!');\n * console.log(stripAnsi(coloredText)); // \"Error!\" (without ANSI codes)\n * ```\n *\n * @since 1.0.0\n */\n\nexport function stripAnsi(str: string): string {\n // Matches ANSI escape sequences like \\x1b[31m or \\x1b[0m etc.\n return str.replace(/\\x1b\\[[0-9;]*m/g, '');\n}\n\n/**\n * Contains ANSI escape sequence constants for terminal control operations\n *\n * @remarks\n * These ANSI escape codes are used to control terminal output behavior such as\n * cursor movement, screen clearing, and visibility. The enum provides a type-safe\n * way to access these constants without having to remember the raw escape sequences.\n *\n * Each constant is an escape sequence that can be written directly to the terminal\n * to achieve the described effect.\n *\n * @see ShadowRenderer\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code\n *\n * @since 1.0.0\n */\n\nexport const ANSI = {\n /**\n * Clears from the cursor to the end of the line\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n CLEAR_LINE: '\\x1B[K',\n\n /**\n * Moves the cursor to the \"home\" position (row 1, column 1).\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.2.0\n */\n\n CURSOR_HOME: '\\x1b[H',\n\n /**\n * Hides the cursor\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n HIDE_CURSOR: '\\x1B[?25l',\n\n /**\n * Shows the cursor\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n SHOW_CURSOR: '\\x1B[?25h',\n\n /**\n * Saves the current cursor position\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n SAVE_CURSOR: '\\x1B[s',\n\n /**\n * Restores the cursor to the previously saved position\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n RESTORE_CURSOR: '\\x1B[u',\n\n /**\n * Resets the terminal to its initial state (RIS - Reset to Initial State).\n * Clears screen, scrollback buffer, and most settings.\n * This is a \"hard reset\" escape code.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#Reset_(RIS)\n * @since 1.0.0\n */\n\n RESET_TERMINAL: '\\x1bc',\n\n /**\n * Clears the screen from the cursor position to the end of the screen.\n *\n * Equivalent to `ESC[J` or `ESC[0J`.\n * Leaves the scrollback buffer intact.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n CLEAR_SCREEN_DOWN: '\\x1b[0J',\n\n /**\n * Clears the screen from the cursor position to the beginning of the screen.\n *\n * Equivalent to `ESC[1J`.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n CLEAR_SCREEN_UP: '\\x1b[1J',\n\n /**\n * Clears the entire screen and moves the cursor to the home position (top-left).\n *\n * Equivalent to `ESC[2JESC[H`.\n * Does not clear the scrollback buffer.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n CLEAR_SCREEN: '\\x1b[2J\\x1b[H',\n\n /**\n * Clears the entire screen and deletes all lines saved in the scrollback buffer.\n *\n * Equivalent to `ESC[3JESC[H`.\n * Supported in xterm and many modern terminal emulators.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n CLEAR_SCREEN_FULL: '\\x1b[3J\\x1b[H',\n\n /**\n * Moves the cursor to the beginning of the current line (column 1).\n *\n * @remarks\n * Unlike `\\r` (carriage return), this is an ANSI escape sequence that\n * explicitly positions the cursor at column 1, regardless of terminal state.\n * It does not affect the row \u2014 only the horizontal position is changed.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.3.0\n */\n\n CURSOR_LINE_START: '\\x1b[1G'\n} as const;\n", "/**\n * Import will remove at compile time\n */\n\nimport type { CellInterface, RenderContextInterface } from '@services/interfaces/shadow-service.interface';\n\n/**\n * Imports\n */\n\nimport { splitWithAnsiContext } from '@services/ast.service';\nimport { ANSI, writeRaw, moveCursor, stripAnsi } from '@components/ansi.component';\n\n/**\n * A virtual terminal renderer that manages efficient screen updates\n *\n * ShadowRenderer provides a mechanism to render content to the terminal\n * while minimizing the number of draw operations needed. It does this by\n * maintaining an internal representation of both the desired content and\n * the current terminal state, only updating parts of the screen that have\n * changed between render cycles.\n *\n * @remarks\n * The renderer maintains separate buffers for content (what should be displayed)\n * and view (what is currently displayed). During rendering, it performs a diff\n * between these buffers to determine the minimal set of changes needed to update\n * the terminal display.\n *\n * This class supports:\n * - Partial screen updates for performance\n * - Content scrolling\n * - Variable viewport dimensions\n * - Rich text styling through cell properties\n *\n * @example\n * ```ts\n * // Create a new renderer positioned at row 2, column 3 with dimensions 80x24\n * const renderer = new ShadowRenderer(2, 3, 80, 24);\n *\n * // Set some content and render it\n * renderer.writeText(0, 0, contentCells);\n * renderer.render();\n * ```\n *\n * @since 1.0.0\n */\n\nexport class ShadowRenderer {\n /**\n * Current scroll position in the content\n *\n * @remarks\n * Tracks the index of the first row visible at the top of the viewport.\n * A value of 0 indicates the content is not scrolled, while higher values\n * indicate the content has been scrolled down by that many rows.\n *\n * This value is used during rendering to determine which portion of the\n * contentBuffer to display in the visible area of the terminal.\n *\n * @see scroll - The getter for accessing this value\n *\n * @private\n */\n\n private scrollPosition: number = 0;\n\n /**\n * Internal buffer representing the current visible state of the terminal\n *\n * @remarks\n * This two-dimensional array stores the actual rendered content as it appears in the terminal.\n * It's organized in a row-major format, with each row containing an array of strings.\n *\n * Unlike contentBuffer which stores full cell information, viewBuffer only contains\n * the string representation of each cell. This buffer is used for diffing against\n * new content to determine what needs to be redrawn during render operations,\n * allowing for efficient partial updates to the terminal display.\n *\n * @private\n */\n\n private viewBuffer: Array<string[]> = [];\n\n /**\n * Internal buffer containing the content to be rendered\n *\n * @remarks\n * This two-dimensional array stores all content cells in a row-major format,\n * where each row is an array of CellInterface objects representing individual\n * characters with their associated style information.\n *\n * The outer array represents rows, while the inner arrays represent columns within each row.\n * This structure allows for efficient access and manipulation of cell data during\n * the rendering process.\n *\n * @private\n * @see CellInterface\n */\n\n private contentBuffer: Array<CellInterface[]> = [];\n\n /**\n * Creates a new ShadowRenderer instance for terminal-based UI rendering\n *\n * @param terminalHeight - The height of the terminal viewport in rows\n * @param terminalWidth - The width of the terminal viewport in columns\n * @param topPosition - The top-offset position within the terminal\n * @param leftPosition - The left offset position within the terminal\n *\n * @since 1.0.0\n */\n\n constructor(\n private terminalHeight: number,\n private terminalWidth: number,\n private topPosition: number,\n private leftPosition: number\n ) {\n }\n\n /**\n * Gets the top position offset of the renderer in the terminal\n *\n * @returns The row offset from the top edge of the terminal\n *\n * @since 1.0.0\n */\n\n get top(): number {\n return this.topPosition;\n }\n\n /**\n * Gets the left position offset of the renderer in the terminal\n *\n * @returns The column offset from the left edge of the terminal\n *\n * @since 1.0.0\n */\n\n get left(): number {\n return this.leftPosition;\n }\n\n /**\n * Gets the width of the renderer's viewport\n *\n * @returns The number of columns visible in the renderer's viewport\n *\n * @since 1.0.0\n */\n\n get width(): number {\n return this.terminalWidth;\n }\n\n /**\n * Gets the height of the renderer's viewport\n *\n * @returns The number of rows visible in the renderer's viewport\n *\n * @since 1.0.0\n */\n\n get height(): number {\n return this.terminalHeight;\n }\n\n /**\n * Gets the current scroll position\n *\n * @returns The current row index at the top of the viewport\n *\n * @since 1.0.0\n */\n\n get scroll(): number {\n return this.scrollPosition;\n }\n\n /**\n * Sets the top position offset of the renderer in the terminal\n *\n * @param top - The row offset from the top edge of the terminal\n *\n * @remarks\n * This setter updates the vertical positioning of the renderer's viewport\n * within the terminal. The top position is used as an offset when calculating\n * absolute cursor positions during rendering operations.\n *\n * Note that changing the top position does not automatically trigger a re-render.\n * You should call the render() method separately after changing the position.\n *\n * @since 1.0.0\n */\n\n set top(top: number) {\n this.topPosition = top;\n }\n\n /**\n * Sets the left position offset of the renderer in the terminal\n *\n * @param left - The column offset from the left edge of the terminal\n *\n * @remarks\n * This setter updates the horizontal positioning of the renderer's viewport\n * within the terminal. The left position is used as an offset when calculating\n * absolute cursor positions during rendering operations.\n *\n * Note that changing the left position does not automatically trigger a re-render.\n * You should call the render() method separately after changing the position.\n *\n * @since 1.0.0\n */\n\n set left(left: number) {\n this.leftPosition = left;\n }\n\n /**\n * Sets the width of the renderer's viewport\n *\n * @param terminalWidth - The number of columns visible in the renderer's viewport\n *\n * @remarks\n * This setter updates the internal width property which controls how many\n * columns are rendered during the rendering process. This should be updated\n * whenever the terminal or display area is resized.\n *\n * Note that changing the width does not automatically trigger a re-render.\n * You should call the render() method separately after changing dimensions.\n *\n * @since 1.0.0\n */\n\n set width(terminalWidth: number) {\n this.terminalWidth = terminalWidth;\n }\n\n /**\n * Sets the height of the renderer's viewport\n *\n * @param terminalHeight - The number of rows visible in the renderer's viewport\n *\n * @remarks\n * This setter updates the internal height property which controls how many\n * rows are rendered during the rendering process. This should be updated\n * whenever the terminal or display area is resized.\n *\n * Note that changing the height does not automatically trigger a re-render.\n * You should call the render() method separately after changing dimensions.\n *\n * @since 1.0.0\n */\n\n set height(terminalHeight: number) {\n this.terminalHeight = terminalHeight;\n }\n\n /**\n * Sets the scroll position and renders the updated view\n *\n * @param position - New scroll position or relative movement (if negative)\n *\n * @remarks\n * This setter handles both absolute and relative scrolling:\n * - Positive values set the absolute scroll position\n * - Negative values move relative to the current position\n *\n * If the requested position scrolls beyond the end of the content,\n * the operation is ignored. After setting a valid scroll position,\n * the view is automatically re-rendered.\n *\n * @example\n * ```ts\n * // Set absolute scroll position to row 10\n * renderer.scroll = 10;\n *\n * // Scroll up 3 rows (relative movement)\n * renderer.scroll = -3;\n * ```\n *\n * @since 1.0.0\n */\n\n set scroll(position: number) {\n // Calculate target position (handle negative values as relative movement)\n const targetPosition = position < 0\n ? this.scrollPosition + position // Relative position\n : position; // Absolute position\n\n const guardedPosition = Math.min(Math.max(targetPosition, 0), this.contentBuffer.length - 1);\n\n if (guardedPosition === this.scrollPosition) return;\n this.scrollPosition = guardedPosition;\n this.render();\n }\n\n /**\n * Clears all content from the renderer and resets its internal state.\n *\n * @remarks\n * This method removes all entries from both the `viewBuffer` and `contentBuffer`,\n * effectively resetting the renderer to its initial empty state.\n *\n * @returns void \u2014 This method does not produce a return value.\n *\n * @example\n * ```ts\n * // Completely reset the renderer's buffers\n * renderer.clear();\n * ```\n *\n * @since 1.0.0\n */\n\n clear(): void {\n this.viewBuffer = [];\n this.contentBuffer = [];\n }\n\n /**\n * Clears the visible content from the terminal screen\n *\n * @returns Nothing\n *\n * @remarks\n * This method builds a string of ANSI escape sequences that move the cursor\n * to the beginning of each line in the view buffer and then clears each line.\n * It doesn't reset the internal buffers, only clears the visible output.\n *\n * @example\n * ```ts\n * // Clear just the screen output without resetting buffers\n * renderer.clearScreen();\n * ```\n *\n * @since 1.0.0\n */\n\n clearScreen(): void {\n let output = '';\n for (let i = 0; i < this.viewBuffer.length; i++) {\n output += this.moveCursor(i, 0);\n output += ANSI.CLEAR_LINE;\n }\n\n output += ANSI.CURSOR_HOME;\n writeRaw(output);\n }\n\n /**\n * Writes text to the specified position in the content buffer\n *\n * @param row - Row position (0-based)\n * @param column - Column position (0-based)\n * @param text - Text to write\n * @param clean - Whether to clear existing content first\n *\n * @remarks\n * This method only updates the internal content buffer and marks cells as dirty.\n * It doesn't immediately render to the screen - call render() to display changes.\n * Only the first line of multi-line text is processed, and a text is truncated\n * if it exceeds terminal boundaries.\n *\n * @example\n * ```ts\n * // Write text in the top-left corner\n * renderer.writeText(0, 0, \"Hello world\");\n *\n * // Write text at position (5,10) and clear any existing content\n * renderer.writeText(5, 10, \"Menu Options\", true);\n *\n * // Display the changes\n * renderer.render();\n * ```\n *\n * @since 1.0.0\n */\n\n writeText(row: number, column: number, text: string, clean: boolean = false): void {\n // Validate input\n if (row < 0 || column >= this.terminalWidth) return;\n if(clean) this.contentBuffer[row] = [];\n\n text = text.split('\\n')[0];\n const line = this.contentBuffer[row] ??= [];\n const stripContent = stripAnsi(text);\n const length = Math.min(this.terminalWidth - column, stripContent.length);\n const content = splitWithAnsiContext(text);\n\n for (let i = 0; i < length; i++) {\n const col = column + i;\n const char = content[i];\n if (!line[col]) line[col] = { char: '', dirty: true };\n\n // Mark as dirty only if content changed\n if (line[col].char !== char) {\n line[col].char = char;\n line[col].dirty = true;\n }\n }\n\n // clean the rest of the line ? `line.length = Math.min(this.terminalWidth, column + length);`\n line.length = Math.min(Math.max(column + length, this.terminalWidth), this.terminalWidth);\n }\n\n /**\n * Writes multi-line text into the content buffer.\n *\n * @param row - Starting row position (0-based).\n * @param column - Starting column position (0-based).\n * @param text - Text to write, either as a string (may contain newlines) or an array of strings (one per line).\n * @param clean - Whether to clear existing content before writing.\n * Only applies to the first written line; subsequent lines always append.\n *\n * @remarks\n * Unlike {@link writeText}, this method supports writing multiple lines\n * at once. If the input is a single string, it is split by newline characters.\n * If an array of strings is provided, each element represents a line.\n *\n * This method automatically allocates new rows in the content buffer\n * as needed, making it suitable for rendering large blocks of text\n * that can later be scrolled with the renderer.\n *\n * @example\n * Writing a block of text from a single string:\n * ```ts\n * renderer.writeBlock(0, 0, \"Line 1\\nLine 2\\nLine 3\");\n * renderer.render();\n * ```\n *\n * @example\n * Writing a block of text from an array:\n * ```ts\n * renderer.writeBlock(2, 4, [\"Indented line 1\", \"Indented line 2\"]);\n * renderer.render();\n * ```\n *\n * @since 1.2.0\n */\n\n writeBlock(row: number, column: number, text: string | Array<string>, clean: boolean = false): void {\n const lines = Array.isArray(text) ? text : text.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const currentRow = row + i;\n this.writeText(currentRow, column, lines[i], clean);\n }\n }\n\n /**\n * Renders the content buffer to the screen using optimized terminal output\n *\n * @param force - Forces all cells to be redrawn, even if they haven't changed\n *\n * @remarks\n * This method performs an optimized render by:\n * - Only rendering the visible portion of the content buffer based on scroll position\n * - Only updating cells that have been marked as dirty (unless force=true)\n * - Clearing trailing content from previous renders\n * - Repositioning the cursor to the bottom right when finished\n *\n * If the content buffer is empty or all content is scrolled out of view,\n * the method will return early without performing any operations.\n *\n * @example\n * ```ts\n * // Normal render - only updates what changed\n * renderer.render();\n *\n * // Force redraw of everything, useful after terminal resize\n * renderer.render(true);\n * ```\n *\n * @since 1.0.0\n */\n\n render(force: boolean = false): void {\n const startRow = Math.min(this.scrollPosition, this.contentBuffer.length);\n const endRow = Math.min(startRow + this.terminalHeight, this.contentBuffer.length);\n\n if (startRow >= endRow) return;\n const context: RenderContextInterface = {\n force,\n output: '',\n viewLine: [],\n screenRow: 1,\n contentLine: []\n };\n\n for (let bufferRow = startRow; bufferRow < endRow; bufferRow++, context.screenRow++) {\n context.contentLine = this.contentBuffer[bufferRow];\n if(!context.contentLine) continue; // empty line\n\n context.viewLine = this.viewBuffer[context.screenRow] ??= [];\n this.renderLine(context);\n\n // Clean up any trailing content from previous renders\n if (context.viewLine.length > context.contentLine.length) {\n context.output += ANSI.CLEAR_LINE;\n context.viewLine.length = context.contentLine.length;\n }\n }\n\n // Clear any rows below our content\n if (endRow >= this.contentBuffer.length) {\n this.viewBuffer.length = context.screenRow;\n for (let i = context.screenRow; i <= this.terminalHeight; i++) {\n context.output += this.moveCursor(i, 0);\n context.output += ANSI.CLEAR_LINE;\n }\n }\n\n context.output += this.moveCursor(this.viewBuffer.length, this.terminalWidth);\n writeRaw(context.output);\n }\n\n /**\n * Flushes the current content buffer directly to the terminal.\n *\n * @remarks\n * This method writes all rows from {@link contentBuffer} to `stdout`,\n * appending a newline after each row. It also clears each line with\n * {@link ANSI.CLEAR_LINE} before writing, ensuring no stale characters\n * remain on screen.\n *\n * Once flushing is complete, both {@link viewBuffer} and {@link contentBuffer}\n * are reset to empty arrays, preparing the renderer for the next cycle.\n *\n * Unlike {@link render}, this method bypasses diffing and incremental\n * optimizations. It always emits the full buffer to the terminal, which\n * guarantees a complete reset of the visible state but may be less\n * efficient for large outputs.\n *\n * @returns void \u2014 This method does not produce a return value.\n *\n * @example\n * ```ts\n * // Write a block of text to the buffer\n * renderer.writeBlock(0, 0, \"Hello\\nWorld\");\n * renderer.clearScreen();\n *\n * // Forcefully flush everything to the terminal\n * renderer.flushToTerminal();\n * ```\n *\n * @since 1.2.0\n */\n\n flushToTerminal(): void {\n let output = '\\n';\n\n for (let row = 0; row < this.contentBuffer.length; row++) {\n const line = this.contentBuffer[row];\n if (!line) continue;\n\n output += ANSI.CLEAR_LINE;\n for (let col = 0; col < line.length; col++) {\n const cell = line[col];\n output += cell?.char ?? ' ';\n }\n\n output += '\\n';\n }\n\n this.clear();\n writeRaw(output);\n }\n\n /**\n * Renders a single line of content to the output buffer\n *\n * @param context - The current rendering context\n *\n * @remarks\n * This private method handles the optimization of terminal output by:\n * - Skipping cells that haven't changed since the last render\n * - Only moving the cursor when necessary\n * - Updating the view buffer to reflect what's been rendered\n * - Clearing the dirty flag on cells after they're processed\n *\n * The context object contains all states needed for the rendering process,\n * including the accumulating output string and references to the current\n * content and view lines.\n *\n * @private\n * @since 1.0.0\n */\n\n private renderLine(context: RenderContextInterface): void {\n // Track when cursor movement is needed\n let needsCursorMove = true;\n\n // Process each cell in the row\n for (let col = 0; col < context.contentLine.length; col++) {\n const cell = context.contentLine[col];\n\n if (cell && !cell.dirty && cell.char === context.viewLine[col] && !context.force) {\n needsCursorMove = true;\n continue;\n }\n\n if (needsCursorMove) {\n context.output += this.moveCursor(context.screenRow, col + 1);\n needsCursorMove = false;\n }\n\n if (!cell) {\n context.viewLine[col] = ' ';\n context.output += ' ';\n continue;\n }\n\n // Update view buffer and output the character\n context.viewLine[col] = cell.char;\n context.output += cell.char;\n cell.dirty = false;\n }\n }\n\n /**\n * Generates an ANSI escape sequence to move the cursor to a position\n *\n * @param row - The row position relative to renderer's viewport\n * @param column - The column position relative to renderer's viewport (defaults to 0)\n * @returns ANSI escape sequence string for cursor positioning\n *\n * @remarks\n * This private helper method translates relative viewport coordinates to\n * absolute terminal coordinates by adding the renderer's top and left\n * position offsets. The returned value is a string containing the\n * appropriate ANSI escape sequence.\n *\n * @private\n * @since 1.0.0\n */\n\n private moveCursor(row: number, column: number = 0): string {\n return moveCursor(row + this.topPosition, column + this.leftPosition);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { StyleCodeType } from '@providers/interfaces/styles-provider.interface';\n\n/**\n * Collection of ANSI text modifier codes for terminal styling\n *\n * @returns An object mapping modifier names to their corresponding ANSI style codes\n *\n * @remarks\n * Provides commonly used text modifiers like bold, dim, etc. Each entry contains\n * a pair of codes: the first to apply the style and the second to reset it.\n * These modifiers change the appearance of text without affecting its color.\n *\n * @example\n * ```ts\n * // Apply bold styling to text\n * const boldCode = ansiModifiers.bold;\n * console.log(`\\x1b[${boldCode[0]}mBold Text\\x1b[${boldCode[1]}m`);\n * ```\n *\n * @see StyleCodeType\n * @since 1.0.0\n */\n\nexport const ansiModifiers = {\n dim: [ 2, 22 ],\n bold: [ 1, 22 ],\n reset: [ 0, 0 ],\n hidden: [ 8, 28 ],\n inverse: [ 7, 27 ]\n} satisfies Record<string, StyleCodeType>;\n\n/**\n * Collection of ANSI foreground color codes for terminal text coloring\n *\n * @returns An object mapping color names to their corresponding ANSI foreground style codes\n *\n * @remarks\n * Provides standard and bright variants of terminal foreground colors.\n * Each entry contains a pair of codes: the first to apply the color and\n * the second (39) to reset to the default foreground color.\n *\n * @example\n * ```ts\n * // Apply red foreground color to text\n * const redCode = ansiForegroundColors.red;\n * console.log(`\\x1b[${redCode[0]}mRed Text\\x1b[${redCode[1]}m`);\n *\n * // Apply bright blue color\n * const brightBlueCode = ansiForegroundColors.blueBright;\n * console.log(`\\x1b[${brightBlueCode[0]}mBright Blue\\x1b[${brightBlueCode[1]}m`);\n * ```\n *\n * @see StyleCodeType\n * @since 1.0.0\n */\n\nexport const ansiForegroundColors = {\n red: [ 31, 39 ],\n gray: [ 90, 39 ],\n blue: [ 34, 39 ],\n cyan: [ 36, 39 ],\n black: [ 30, 39 ],\n white: [ 37, 39 ],\n green: [ 32, 39 ],\n yellow: [ 33, 39 ],\n magenta: [ 35, 39 ],\n redBright: [ 91, 39 ],\n blueBright: [ 94, 39 ],\n cyanBright: [ 96, 39 ],\n whiteBright: [ 97, 39 ],\n greenBright: [ 92, 39 ],\n blackBright: [ 90, 39 ],\n yellowBright: [ 93, 39 ],\n magentaBright: [ 95, 39 ],\n darkGray: [ '38;5;238', 39 ],\n lightGray: [ '38;5;252', 39 ],\n lightCyan: [ '38;5;81', 39 ],\n lightCoral: [ '38;5;203', 39 ],\n oliveGreen: [ '38;5;149', 39 ],\n deepOrange: [ '38;5;166', 39 ],\n brightPink: [ '38;5;197', 39 ],\n lightOrange: [ '38;5;215', 39 ],\n burntOrange: [ '38;5;208', 39 ],\n lightYellow: [ '38;5;230', 39 ],\n canaryYellow: [ '38;5;227', 39 ],\n lightGoldenrodYellow: [ '38;5;221', 39 ]\n} satisfies Record<string, StyleCodeType>;\n\n/**\n * Collection of ANSI background color codes for terminal text backgrounds\n *\n * @returns An object mapping color names to their corresponding ANSI background style codes\n *\n * @remarks\n * Provides standard and bright variants of terminal background colors.\n * Each entry contains a pair of codes: the first to apply the background color and\n * the second (49) to reset to the default background.\n * All background color names are prefixed with 'bg' to distinguish them from foreground colors.\n *\n * @example\n * ```ts\n * // Apply red background to text\n * const bgRedCode = ansiBackgroundColors.bgRed;\n * console.log(`\\x1b[${bgRedCode[0]}mText with Red Background\\x1b[${bgRedCode[1]}m`);\n *\n * // Apply bright cyan background\n * const bgCyanBrightCode = ansiBackgroundColors.bgCyanBright;\n * console.log(`\\x1b[${bgCyanBrightCode[0]}mBright Cyan Background\\x1b[${bgCyanBrightCode[1]}m`);\n * ```\n *\n * @see StyleCodeType\n * @since 1.0.0\n */\n\nexport const ansiBackgroundColors = {\n bgRed: [ 41, 49 ],\n bgBlue: [ 44, 49 ],\n bgCyan: [ 46, 49 ],\n bgGray: [ 100, 49 ],\n bgBlack: [ 40, 49 ],\n bgGreen: [ 42, 49 ],\n bgWhite: [ 47, 49 ],\n bgYellow: [ 43, 49 ],\n bgMagenta: [ 45, 49 ],\n bgRedBright: [ 101, 49 ],\n bgBlueBright: [ 104, 49 ],\n bgCyanBright: [ 106, 49 ],\n bgBlackBright: [ 100, 49 ],\n bgWhiteBright: [ 107, 49 ],\n bgGreenBright: [ 102, 49 ],\n bgYellowBright: [ 103, 49 ],\n bgMagentaBright: [ 105, 49 ]\n} satisfies Record<string, StyleCodeType>;\n", "/**\n * Import will remove at compile time\n */\n\nimport type { StyleCodeType } from '@providers/interfaces/styles-provider.interface';\nimport type { AnsiChainableBuilderType } from '@components/interfaces/xterm-component.interface';\n\n/**\n * Imports\n */\n\nimport { ansiBackgroundColors, ansiForegroundColors, ansiModifiers } from '@providers/styles.provider';\n\n\n/**\n * Exports\n */\n\nexport type * from '@components/interfaces/xterm-component.interface';\n\n/**\n * Unified collection of all ANSI style codes for efficient lookup\n *\n * @returns A merged record of all style codes including modifiers, foreground and background colors\n *\n * @remarks\n * This constant combines all style types (modifiers, foreground colors, and background colors)\n * into a single lookup object for improved performance when accessing style codes.\n * It's particularly useful in hot paths where style code lookups happen frequently.\n *\n * @example\n * ```ts\n * // Get the style code for bold text\n * const boldCode = styles.bold;\n *\n * // Get the style code for red foreground\n * const redCode = styles.red;\n *\n * // Get the style code for a blue background\n * const bgBlueCode = styles.bgBlue;\n * ```\n *\n * @see ansiModifiers\n * @see ansiForegroundColors\n * @see ansiBackgroundColors\n * @see StyleCodeType\n * @since 1.0.0\n */\n\nconst styles: Record<string, StyleCodeType> = {\n ...ansiModifiers,\n ...ansiForegroundColors,\n ...ansiBackgroundColors\n};\n\n/**\n * ANSI escape sequence prefix for terminal control codes\n *\n * @remarks\n * This constant defines the standard ANSI escape sequence prefix used to start\n * a terminal control code. Using a constant improves performance by avoiding\n * string recreation in performance-critical code paths.\n *\n * @see ESC_END\n * @since 1.0.0\n */\n\nconst ESC = '\\x1b[';\n\n/**\n * ANSI escape sequence suffix for terminal style codes\n *\n * @remarks\n * This constant defines the standard ANSI escape sequence suffix that completes\n * a terminal style control code. Used in conjunction with ESC and style codes\n * to form complete ANSI styling sequences.\n *\n * @see ESC\n * @since 1.0.0\n */\n\nconst ESC_END = 'm';\n\n/**\n * Wraps text with ANSI escape sequences to apply terminal styling\n *\n * @param codes - Array of StyleCodeType tuples to apply to the text\n * @param text - The string to be styled with ANSI codes\n * @returns The input text wrapped with appropriate ANSI escape sequences\n *\n * @remarks\n * This function efficiently applies multiple style codes to a text string by\n * wrapping it with the appropriate ANSI escape sequences. It handles proper nesting\n * of styles by ensuring that reset codes are applied in reverse order.\n *\n * The function has three optimized code paths:\n * - For an empty codes array, it returns the original text without modification\n * - For a single code, it directly concatenates without using arrays\n * - For multiple codes, it pre-allocates arrays for improved performance\n *\n * @example\n * ```ts\n * // Apply a single style (bold)\n * const boldText = wrapWithAnsi([styles.bold], \"Hello World\");\n *\n * // Apply multiple styles (bold and red)\n * const boldRedText = wrapWithAnsi([styles.bold, styles.red], \"Hello World\");\n * ```\n *\n * @see StyleCodeType\n * @see ESC\n * @see ESC_END\n * @since 1.0.0\n */\n\nfunction wrapWithAnsi(codes: Array<StyleCodeType>, text: string): string {\n if (globalThis.NO_COLOR) return text;\n const codesLength = codes.length;\n\n if (codesLength === 0) return text;\n if (codesLength === 1) {\n return `${ ESC }${ codes[0][0] }${ ESC_END }${ text }${ ESC }${ codes[0][1] }${ ESC_END }`;\n }\n\n const endCodes = new Array<string>(codesLength);\n const startCodes = new Array<string>(codesLength);\n\n for (let i = 0; i < codesLength; i++) {\n startCodes[i] = `${ ESC }${ codes[i][0] }${ ESC_END }`;\n // Build end codes in reverse order for proper nesting\n endCodes[codesLength - i - 1] = `${ ESC }${ codes[i][1] }${ ESC_END }`;\n }\n\n return startCodes.concat(text, endCodes).join('');\n}\n\n/**\n * Generates ANSI RGB color code for terminal foreground or background styling\n *\n * @param type - Color application type: 'fg' for foreground or 'bg' for background\n * @param r - Red color component (0-255)\n * @param g - Green color component (0-255)\n * @param b - Blue color component (0-255)\n * @returns A StyleCodeType tuple containing the RGB color code and its reset code\n *\n * @throws Error - When any of the RGB values are not numbers\n *\n * @remarks\n * This function creates ANSI 24-bit color codes (true color) for terminals that support them.\n * It generates the appropriate code based on whether the color should be applied to\n * the foreground (text color) or background.\n *\n * The function performs type checking on RGB values to ensure they are numbers\n * before generating the style code.\n *\n * @example\n * ```ts\n * // Create a foreground RGB color (red)\n * const redFg = rgbCode('fg', 255, 0, 0);\n *\n * // Create a background RGB color (blue)\n * const blueBg = rgbCode('bg', 0, 0, 255);\n *\n * // Apply the RGB color to text\n * const coloredText = wrapWithAnsi([redFg], \"This text is custom red\");\n * ```\n *\n * @see StyleCodeType\n * @see wrapWithAnsi\n *\n * @since 1.0.0\n */\n\nfunction rgbCode(type: 'fg', r: number, g: number, b: number): StyleCodeType;\nfunction rgbCode(type: 'bg', r: number, g: number, b: number): StyleCodeType;\nfunction rgbCode(type: 'fg' | 'bg', r: number | unknown, g: number | unknown, b: number | unknown): StyleCodeType {\n if (typeof r !== 'number' || typeof g !== 'number' || typeof b !== 'number') {\n throw new Error(`RGB values must be numbers, received: r=${ typeof r }, g=${ typeof g }, b=${ typeof b }`);\n }\n\n const code = type === 'fg' ? 38 : 48;\n const reset = type === 'fg' ? 39 : 49;\n\n return [ `${ code };2;${ r };${ g };${ b }`, reset ];\n}\n\n/**\n * Converts a hexadecimal color string to RGB components\n *\n * @param hex - Hexadecimal color string (with or without leading #)\n * @returns Tuple of [red, green, blue] values as numbers in the range 0-255\n *\n * @throws Error - When the provided hex string is not a valid 3 or 6 digit hex color\n *\n * @remarks\n * This utility function parses both 3-digit shorthand (#RGB) and 6-digit standard (#RRGGBB)\n * hexadecimal color formats into their corresponding RGB numeric values.\n *\n * For 3-digit hex values, each digit is duplicated to create the equivalent 6-digit value\n * (e.g., #F00 becomes #FF0000).\n *\n * @example\n * ```ts\n * // 6-digit hex\n * const [r, g, b] = hexToRgb('#FF5500');\n * console.log(r, g, b); // 255, 85, 0\n *\n * // 3-digit hex\n * const [r, g, b] = hexToRgb('#F50');\n * console.log(r, g, b); // 255, 85, 0\n *\n * // Without # prefix\n * const [r, g, b] = hexToRgb('00FF00');\n * console.log(r, g, b); // 0, 255, 0\n * ```\n *\n * @see rgbCode - Function that uses RGB values to create ANSI color codes\n * @since 1.0.0\n */\n\nfunction hexToRgb(hex: `#${ string }` | string): [ number, number, number ] {\n // Remove leading # if present\n const cleanHex = hex.replace(/^#/, '').toLowerCase();\n\n // Validate hex format\n if (!/^([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(cleanHex)) {\n throw new Error(`Invalid hex color format: \"${ hex }\". Expected 3 or 6 hex digits.`);\n }\n\n // Parse 3-digit hex\n if (cleanHex.length === 3) {\n const r = parseInt(cleanHex[0] + cleanHex[0], 16);\n const g = parseInt(cleanHex[1] + cleanHex[1], 16);\n const b = parseInt(cleanHex[2] + cleanHex[2], 16);\n\n return [ r, g, b ];\n }\n\n // Parse 6-digit hex\n const r = parseInt(cleanHex.slice(0, 2), 16);\n const g = parseInt(cleanHex.slice(2, 4), 16);\n const b = parseInt(cleanHex.slice(4, 6), 16);\n\n return [ r, g, b ];\n}\n\n/**\n * Creates a chainable builder for styling text with ANSI escape sequences\n *\n * @param codes - Initial style codes to apply (empty by default)\n * @returns A chainable builder object that acts as both a function and a proxy for style methods\n *\n * @remarks\n * This function creates a chainable API for terminal text styling that supports both\n * function call and property access patterns. The returned object is both callable\n * (to format text) and provides property access for style chaining.\n *\n * The implementation uses a JavaScript Proxy to intercept property access and dynamically\n * create new chain instances with additional style codes. The formatter function handles\n * both regular arguments and tagged template literals.\n *\n * The builder supports:\n * - Basic styles (bold, dim, italic, etc.) via property access\n * - RGB colors via .rgb() and .bgRgb() methods\n * - Hex colors via .hex() and .bgHex() methods\n * - Function call with strings or template literals to apply styles\n *\n * @example\n * ```ts\n * // Basic usage\n * const colorizer = createXtermChain();\n * console.log(colorizer.bold.red(\"This is bold and red\"));\n *\n * // Chaining multiple styles\n * console.log(colorizer.bold.underline.hex('#3498db')(\"Styled text\"));\n *\n * // Using template literals\n * const name = \"World\";\n * console.log(colorizer.green`Hello ${name}!`);\n *\n * // Starting with initial styles\n * const warningStyle = createXtermChain([styles.yellow, styles.bold]);\n * console.log(warningStyle(\"Warning message\"));\n * ```\n *\n * @see styles\n * @see rgbCode\n * @see hexToRgb\n * @see wrapWithAnsi\n * @see AnsiChainableBuilderType\n *\n * @since 1.0.0\n */\n\nfunction createXtermChain(codes: Array<StyleCodeType> = []): AnsiChainableBuilderType {\n const formatter = (...args: Array<unknown>): string => {\n if (Array.isArray(args[0]) && 'raw' in args[0]) {\n const [ strings, ...values ] = args as [ TemplateStringsArray, ...Array<unknown> ];\n\n const combined = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? String(values[i] ?? '') : ''),\n ''\n );\n\n return wrapWithAnsi(codes, combined);\n }\n\n // Handle regular arguments\n return wrapWithAnsi(codes, args.join(' '));\n };\n\n // Define color method handlers for reuse\n const colorHandlers = {\n // RGB foreground color\n rgb: (r: number, g: number, b: number): AnsiChainableBuilderType =>\n createXtermChain([ ...codes, rgbCode('fg', r, g, b) ]),\n\n bgRgb: (r: number, g: number, b: number): AnsiChainableBuilderType =>\n createXtermChain([ ...codes, rgbCode('bg', r, g, b) ]),\n\n hex: (hex: string): AnsiChainableBuilderType =>\n createXtermChain([ ...codes, rgbCode('fg', ...hexToRgb(hex)) ]),\n\n bgHex: (hex: string): AnsiChainableBuilderType =>\n createXtermChain([ ...codes, rgbCode('bg', ...hexToRgb(hex)) ])\n };\n\n // Create a proxy to handle property access for chaining\n return <AnsiChainableBuilderType>new Proxy(formatter, {\n get(target, prop: string | symbol): unknown {\n if (typeof prop !== 'string') {\n throw new Error(`Invalid property: ${ String(prop) }`);\n }\n\n // Handle standard styles from the styles object\n if (prop in styles) {\n return createXtermChain([ ...codes, styles[prop] ]);\n }\n\n // Handle color methods\n if (prop in colorHandlers) {\n return colorHandlers[prop as keyof typeof colorHandlers];\n }\n\n // Fall back to the target's own properties\n return Reflect.get(target, prop);\n }\n });\n}\n\n/**\n * Pre-configured ANSI terminal styling utility with chainable methods\n *\n * @example\n * ```ts\n * // Basic styling\n * console.log(xterm.bold(\"This is bold text\"));\n * console.log(xterm.red(\"This is red text\"));\n *\n * // Chain multiple styles\n * console.log(xterm.bold.red(\"This is bold and red\"));\n * console.log(xterm.green(\"This is green\"));\n *\n * // Use with template literals\n * const name = \"World\";\n * console.log(xterm.cyan`Hello ${name}!`);\n *\n * // RGB and Hex colors\n * console.log(xterm.rgb(255, 136, 0)(\"Custom orange text\"));\n * console.log(xterm.hex(\"#FF8800\")(\"Hex orange text\"));\n *\n * // Background colors\n * console.log(xterm.bgGreen(\"Text with green background\"));\n * console.log(xterm.bgHex(\"#333333\")(\"Text with a dark background\"));\n * ```\n *\n * @remarks\n * The `xterm` export provides a convenient, ready-to-use instance of the chainable\n * styling builder. It supports all standard ANSI styles, RGB colors, and hexadecimal\n * color definitions for both foreground and background.\n *\n * This is the recommended entry point for using the styling functionality in most cases.\n * For custom styling chains with pre-applied styles, use `createXtermChain()` directly.\n *\n * @see createXtermChain\n * @see AnsiChainableBuilderType\n *\n * @since 1.0.0\n */\n\nexport const xterm = createXtermChain();\n", "/**\n * Import will remove at compile time\n */\n\nimport type { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Checks if a given value is an instance of the specified constructor.\n *\n * @param constructor - The constructor function to check against\n * @param value - The value to test\n *\n * @returns True if the value is not null or undefined and its constructor matches the specified constructor; otherwise false\n *\n * @example\n * ```ts\n * class MyClass {}\n * const instance = new MyClass();\n * console.log(isA(MyClass, instance)); // true\n * console.log(isA(Array, instance)); // false\n * ```\n *\n * @since 1.0.0\n */\n\nexport function isA(constructor: unknown, value: unknown): boolean {\n return value !== null && value !== undefined && (value.constructor === constructor || typeof value === 'function');\n}\n\n/**\n * Checks if the specified key exists as an own property on the given object.\n *\n * @param obj - The object to check for the key\n * @param key - The property key (string or symbol) to look for\n *\n * @returns True if the object has the specified own property key; otherwise false\n *\n * @example\n * ```ts\n * const obj = { foo: 123 };\n * console.log(hasKey(obj, 'foo')); // true\n * console.log(hasKey(obj, 'bar')); // false\n * ```\n *\n * @since 1.0.0\n */\n\nexport function hasKey(obj: unknown, key: string | symbol): boolean {\n if (obj == null || (typeof obj !== 'object' && typeof obj !== 'function'))\n return false;\n\n return key in obj || Object.prototype.hasOwnProperty.call(obj, key);\n}\n\n/**\n * Determines whether the given object implements the `AbstractPattern` interface.\n *\n * @param obj - The object to test\n *\n * @returns A type guard indicating whether the object has a `matches` method\n *\n * @remarks\n * This function checks if the object is truthy and has a `matches` method,\n * which is expected for objects implementing `AbstractPattern`.\n *\n * @example\n * ```ts\n * if (isAsymmetric(someObj)) {\n * someObj.matches(value);\n * }\n * ```\n *\n * @see AbstractPattern - The interface that defines the `matches` method\n *\n * @since 1.0.0\n */\n\nexport function isAsymmetric(obj: unknown): obj is AbstractPattern {\n return !!obj && hasKey(obj, 'expectedLabel') && isA(Function, (obj as AbstractPattern).matches);\n}\n\n/**\n * Attempts an asymmetric match between two values if either implements `AbstractPattern`.\n *\n * @param a - The first value to test for asymmetric matching\n * @param b - The second value to test for asymmetric matching\n *\n * @returns `true` if `a` matches `b`, `false` if it does not match,\n * `undefined` if neither value implements asymmetric matching or if both do (defer)\n *\n * @remarks\n * This function uses the `isAsymmetric` type guard to detect if either value implements\n * the `AbstractPattern` interface. If both are asymmetric, the comparison is deferred by returning `undefined`.\n * If only one is asymmetric, it performs the match accordingly.\n *\n * @example\n * ```ts\n * const pattern = { matches: (v: any) => v > 10 };\n * console.log(asymmetricMatch(pattern, 15)); // true\n * ```\n *\n * @see isAsymmetric - Helper to detect asymmetric matchers\n * @see AbstractPattern - Interface defining the `matches` method\n *\n * @since 1.0.0\n */\n\nexport function asymmetricMatch(a: unknown, b: unknown): boolean | undefined {\n const asymmetricA = isAsymmetric(a);\n const asymmetricB = isAsymmetric(b);\n\n if (asymmetricA && asymmetricB) {\n return undefined; // Defer comparison; neither dominates\n }\n\n if (asymmetricA) return a.matches(b);\n if (asymmetricB) return b.matches(a);\n\n return undefined;\n}\n\n/**\n * Performs a deep equality comparison between two objects or arrays.\n *\n * @param a - The first object or array to compare.\n * @param b - The second object or array to compare.\n * @param strictCheck - Whether to require exact shape matching (default: true).\n * If false, `b` can be a superset of `a`.\n *\n * @returns A boolean indicating whether the two inputs are deeply equal.\n *\n * @remarks\n * This function is used internally by `equals` to recursively compare arrays and objects.\n *\n * - For arrays:\n * - If `strictCheck` is true, their lengths must match.\n * - If false, only the elements of `a` must match the corresponding elements in `b`.\n *\n * - For objects:\n * - If `strictCheck` is true, both must have exactly the same keys.\n * - If false, `b` may contain extra keys, but all keys in `a` must match.\n *\n * Keys and values are compared recursively using `equals`, which supports deep matching.\n *\n * @example\n * ```ts\n * deepEquals({ a: 1 }, { a: 1 }, true); // true\n * deepEquals({ a: 1 }, { a: 1, b: 2 }, false); // true\n * deepEquals([1, 2], [1, 2, 3], false); // true\n * deepEquals([1, 2], [2, 1], true); // false\n * ```\n *\n * @see equals - Performs a general equality comparison (shallow or deep)\n *\n * @since 1.0.0\n */\n\nfunction deepEquals(a: object, b: object, strictCheck: boolean = true): boolean {\n if (Array.isArray(a) && Array.isArray(b)) {\n if(strictCheck && a.length !== b.length) return false;\n\n return a.every((val, i) => equals(val, b[i], strictCheck));\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (strictCheck && aKeys.length !== bKeys.length) return false;\n\n for (const key of aKeys) {\n if (!hasKey(b, key)) return false;\n if (!equals((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], strictCheck)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether two values are equal, supporting both strict and partial deep equality.\n *\n * @param a - The first value to compare.\n * @param b - The second value to compare.\n * @param strictCheck - If true (default), requires exact deep equality.\n * If false, allows partial (asymmetric) matching.\n *\n * @returns `true` if the values are considered equal; otherwise, `false`.\n *\n * @remarks\n * This function performs a deep comparison between two values:\n *\n * - Primitives are compared using `Object.is`.\n * - Special objects (Date, RegExp, URL) are compared by value.\n * - Arrays and plain objects are compared recursively via `deepEquals`.\n * - Supports asymmetric matching when `strictCheck` is false (e.g., partial matching).\n *\n * The following helper functions are assumed to exist:\n * - `asymmetricMatch`: handles custom matchers or partial match behavior\n * - `deepEquals`: recursively compares arrays and objects\n *\n * @example\n * ```ts\n * equals(1, 1); // true\n * equals(1, '1'); // false\n * equals({ x: 1 }, { x: 1 }); // true\n * equals({ x: 1 }, { x: 1, y: 2 }, false); // true (partial match)\n * equals([1, 2], [1, 2, 3], false); // true (partial match)\n * ```\n *\n * @since 1.0.0\n */\n\nexport function equals(a: unknown, b: unknown, strictCheck = true): boolean {\n if (a === b) return true; // Fast path for strict equality\n if (Object.is(a, b)) return true; // Handle identical references or primitive equality\n if (a === null || b === null) return false; // Handle null or undefined cases\n\n const asymmetricResult = asymmetricMatch(a, b);\n if (asymmetricResult !== undefined) return asymmetricResult;\n\n if (a instanceof Date && b instanceof Date)\n\n return a.getTime() === b.getTime();\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n\n if (globalThis.URL && a instanceof globalThis.URL && b instanceof globalThis.URL)\n return a.href === b.href;\n\n if (typeof a === 'object' && typeof b === 'object') {\n return deepEquals(a, b, strictCheck);\n }\n\n return false;\n}\n\n/**\n * Serializes an {@link Error} object into a generic key-value object.\n *\n * @template T - The type of values in the returned record (defaults to `unknown`).\n * @param error - The error instance to serialize.\n * @returns A record containing all own enumerable properties of the error,\n * including `name`, `message`, and `stack`.\n *\n * @remarks\n * This function ensures that all enumerable properties of the error are preserved,\n * while always including the standard `name`, `message`, and `stack` properties.\n * It is useful for structured logging, transmitting errors across process boundaries,\n * or converting errors to a format suitable for JSON serialization.\n *\n * @example\n * ```ts\n * try {\n * throw new Error(\"Something went wrong\");\n * } catch (err) {\n * const serialized = serializesError<string>(err);\n * console.log(serialized.name); // \"Error\"\n * console.log(serialized.message); // \"Something went wrong\"\n * }\n * ```\n *\n * @since 2.1.0\n */\n\nexport function serializesError<T = unknown>(error: Error): Record<string, T> {\n const json: Record<string, unknown> = {};\n\n // Copy all own (non-inherited) enumerable properties\n for (const key of Object.keys(error)) {\n const value = error[key as keyof Error];\n if(value) json[key] = value;\n }\n\n // Ensure `name`, `message`, and `stack` are included\n json.name = error.name;\n json.stack = error.stack;\n json.message = error.message;\n\n return <Record<string, T>> json;\n}\n", "/**\n * Determines whether the given candidate is a Promise-like object.\n *\n * @template T - The type of the resolved value of the Promise\n *\n * @param candidate - The value to test for Promise-like behavior\n *\n * @returns A type guard indicating whether the candidate is a Promise-like object\n *\n * @remarks\n * This function checks if the candidate is non-null and either an object or a function,\n * then verifies the presence of a `then` method to identify Promise-like objects.\n *\n * @example\n * ```ts\n * if (isPromise(someValue)) {\n * someValue.then(value => {\n * console.log('Resolved with', value);\n * });\n * }\n * ```\n *\n * @since 1.0.0\n */\n\nexport function isPromise<T = unknown>(candidate: unknown): candidate is PromiseLike<T> {\n return (\n candidate != null &&\n (typeof candidate === 'object' || typeof candidate === 'function') &&\n typeof (candidate as Promise<unknown>).then === 'function'\n );\n}\n", "/**\n * Imports\n */\n\nimport { isAsymmetric } from '@components/object.component';\n\n/**\n * Default indentation string used throughout the serialization system.\n *\n * @remarks\n * This constant defines the standard indentation as two spaces (' ') used\n * when generating multi-line serialized representations of complex data structures.\n * It's used as the default value for indent parameters across various serialization functions.\n *\n * @example\n * ```ts\n * // Using the default indentation\n * const serialized = serialize(complexObject);\n *\n * // Overriding with custom indentation\n * const customIndented = serialize(complexObject, ' '); // 4 spaces instead\n * ```\n *\n * @since 1.0.0\n */\n\nconst INDENT = ' ';\n\n/**\n * Converts primitive JavaScript values to their string representation.\n *\n * @param element - The value to be serialized\n * @returns A string representation of the value, or null if serialization is not supported\n *\n * @remarks\n * This function handles serialization of various JavaScript primitive types and built-in objects:\n * - Strings (returns quoted string unless it contains newlines)\n * - Numbers (handles NaN and finite numbers)\n * - Booleans, Symbols, BigInts\n * - Functions (with name or as anonymous)\n * - null, undefined\n * - Built-in objects (Date, RegExp, Error, Promise)\n * - TypedArray views (ArrayBuffer, DataView)\n *\n * The function returns null for complex objects that require custom serialization\n * or for strings containing newlines, which should be handled differently.\n *\n * @example\n * ```ts\n * serializePrimitive(\"hello\") // Returns: \"\\\"hello\\\"\"\n * serializePrimitive(42) // Returns: \"42\"\n * serializePrimitive(null) // Returns: \"null\"\n * serializePrimitive(new Date()) // Returns: \"[Date: 2023-05-01T00:00:00.000Z]\"\n * serializePrimitive({}) // Returns: null (complex objects not handled)\n * ```\n *\n * @see serialize - For complete object serialization including complex objects\n *\n * @since 1.0.0\n */\n\nexport function serializePrimitive(element: unknown): string | null {\n if (typeof element === 'string') return element.includes('\\n') ? null : `\"${ element }\"`;\n if (typeof element === 'number') return `${ Number.isFinite(element) ? element : element.toString() }`;\n if (typeof element === 'boolean') return `${ element }`;\n if (typeof element === 'symbol') return `${ element.toString() }`;\n if (typeof element === 'bigint') return `${ element }n`;\n if (typeof element === 'function') return `[Function: ${ element.name || 'anonymous' }]`;\n\n if (element === null) return 'null';\n if (element === undefined) return 'undefined';\n if (isAsymmetric(element)) return element.expectedLabel ?? element.constructor.name;\n if (element instanceof Date) return `[Date: ${ element.toISOString() }]`;\n if (element instanceof RegExp) return element.toString();\n if (element instanceof Error) return `[${ element.name }: ${ element.message }]`;\n if (element instanceof Promise) return '[Promise <pending>]';\n if (element instanceof ArrayBuffer) return `ArrayBuffer { byteLength: ${ element.byteLength } }`;\n if (element instanceof DataView) {\n return `DataView { byteLength: ${ element.byteLength }, byteOffset: ${ element.byteOffset } }`;\n }\n\n return null;\n}\n\n/**\n * Provides a string representation of Map keys for serialization purposes.\n *\n * @param key - The Map key to be converted to a string\n * @returns A consistent string representation of the key\n *\n * @remarks\n * This utility function ensures consistent string representation of Map keys\n * when serializing Map objects for display or comparison purposes:\n *\n * - Special handling for null and undefined values\n * - Uses class/type information for object keys via Object.prototype.toString\n * - Properly quotes and escapes string values using JSON.stringify\n *\n * The function is particularly useful when working with Maps containing\n * complex keys that need to be represented in a human-readable format.\n *\n * @example\n * ```ts\n * // When serializing a Map:\n * const map = new Map([[{id: 1}, 'value'], ['key2', 123]]);\n *\n * const entries = Array.from(map.entries()).map(([key, value]) => {\n * return `${serializeMapKey(key)} => ${serializePrimitive(value) || '...'}`;\n * });\n *\n * // Results in: [\"[object Object] => \\\"value\\\"\", \"\\\"key2\\\" => 123\"]\n * ```\n *\n * @see serialize - For complete object serialization\n *\n * @since 1.0.0\n */\n\nexport function serializeMapKey(key: unknown): string {\n if (key === null) return 'null';\n if (key === undefined) return 'undefined';\n if (typeof key === 'object') return Object.prototype.toString.call(key);\n\n return JSON.stringify(key);\n}\n\n/**\n * Appends formatted lines from a source array to a target array with proper indentation and separators.\n *\n * @param source - Array of strings to be appended\n * @param target - Array where the formatted lines will be added\n * @param key - Prefix to be added to the first line\n * @param isLast - Whether this is the last element in a sequence (affects comma placement)\n * @param indent - String used for indentation (default is empty string)\n * @returns void - Modifies the target array in place\n *\n * @remarks\n * This utility function handles the formatting logic when appending multi-line content\n * to a string array representation of a structured object. It properly handles:\n * - Adding the key prefix only to the first line\n * - Applying consistent indentation to all lines\n * - Adding trailing commas to non-last elements\n * - Special handling for single-line and empty source arrays\n *\n * The function is particularly useful for serializing object properties or array elements\n * that span multiple lines while maintaining proper structure formatting.\n *\n * @example\n * ```ts\n * const source = [\"{\", \" value: 42\", \"}\"];\n * const target = [];\n *\n * appendLines(source, target, \"property: \", false, \" \");\n * // Results in target containing:\n * // [\" property: {\", \" value: 42\", \" },\"]\n *\n * appendLines([\"simple\"], target, \"last: \", true, \" \");\n * // Adds: [\" last: simple\"]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function appendLines(source: Array<string>, target: Array<string>, key: string, isLast: boolean, indent: string = ''): void {\n if (source.length === 0) return;\n if (source.length < 2) {\n const last = `${ indent }${ key }${ source[source.length - 1] }`;\n target.push(isLast ? last : `${ last },`);\n\n return;\n }\n\n target.push(`${ indent }${ key }${ source[0] }`);\n for (let i = 1; i < source.length - 1; i++) {\n target.push(indent + source[i]);\n }\n\n const last = `${ indent }${ source[source.length - 1] }`;\n target.push(isLast ? last : `${ last },`);\n}\n\n/**\n * Serializes a JavaScript Map object into a multi-line string representation.\n *\n * @param map - The Map object to serialize\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @param seen - Set of objects that have already been serialized (used to detect circular references)\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts a Map object into a human-readable string representation\n * with proper formatting and indentation. The serialization process:\n *\n * 1. Handles empty Maps with a compact `Map {}` representation\n * 2. For non-empty Maps, creates a multi-line representation with each entry on separate lines\n * 3. Formats each entry as `key => value` with proper serialization of both key and value\n * 4. Preserves complex structure of nested values through recursive serialization\n * 5. Applies consistent indentation for nested structures\n *\n * The output format is similar to Node.js console.log representation of Maps\n * but with enhanced formatting for nested structures.\n *\n * @example\n * ```ts\n * const map = new Map([\n * [\"key1\", \"value1\"],\n * [42, {nested: true}]\n * ]);\n * const result = [];\n *\n * serializeMap(map, result, \" \");\n * // the result now contains:\n * // [\"Map {\",\n * // \"\\\"key1\\\" => \\\"value1\\\",\",\n * // \"42 => {\",\n * // \" nested: true\",\n * // \"}\",\n * // \"}\"]\n * ```\n *\n * @see serializeMapKey - Function used to serialize Map keys\n * @see serializeValue - Function used to serialize Map values\n * @see appendLines - Helper for handling multi-line formatting\n *\n * @since 1.0.0\n */\n\nexport function serializeMap(map: Map<unknown, unknown>, lines: Array<string>, indent: string, seen: WeakSet<object>): void {\n if (map.size === 0) {\n lines.push('Map {}');\n\n return;\n }\n\n lines.push('Map {');\n const entries = Array.from(map.entries());\n entries.forEach(([ key, val ], i) => {\n const keyStr = serializeMapKey(key);\n const subLines: Array<string> = [];\n serializeValue(val, subLines, indent, seen);\n appendLines(subLines, lines, `${ keyStr } => `, i === entries.length - 1, indent);\n });\n lines.push('}');\n}\n\n/**\n * Serializes a JavaScript array into a multi-line string representation.\n *\n * @param arr - The array to be serialized\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @param seen - Set of objects that have already been serialized (used to detect circular references)\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts an array into a human-readable string representation\n * with proper formatting and indentation. The serialization follows these rules:\n *\n * 1. Empty arrays are represented as the compact string \"Array []\"\n * 2. Non-empty arrays are formatted with each element on a separate line\n * 3. Each element is properly serialized based on its type\n * 4. Nested structures (objects, arrays, maps) maintain consistent indentation\n * 5. The format is similar to Node.js console.log representation but with enhanced readability\n *\n * The function is designed to work with arrays containing elements of any type,\n * including complex nested structures, by recursively serializing each element.\n *\n * @example\n * ```ts\n * const array = [1, \"text\", {a: true}, [2, 3]];\n * const result = [];\n *\n * serializeArray(array, result, \" \");\n * // the result now contains:\n * // [\"Array [\",\n * // \"1,\",\n * // \"\\\"text\\\",\",\n * // \"{\",\n * // \" a: true\",\n * // \"},\",\n * // \"Array [\",\n * // \" 2,\",\n * // \" 3\",\n * // \"]\",\n * // \"]\"]\n * ```\n *\n * @see serializeValue - Function used to serialize individual array elements\n * @see appendLines - Helper for handling multi-line formatting\n *\n * @since 1.0.0\n */\n\nexport function serializeArray(arr: Array<unknown>, lines: Array<string>, indent: string, seen: WeakSet<object>): void {\n if (arr.length === 0) {\n lines.push('[]');\n\n return;\n }\n\n lines.push('[');\n arr.forEach((item, i) => {\n const subLines: Array<string> = [];\n serializeValue(item, subLines, indent, seen);\n appendLines(subLines, lines, '', i === arr.length - 1, indent);\n });\n lines.push(']');\n}\n\n/**\n * Serializes a JavaScript Set object into a multi-line string representation.\n *\n * @param set - The Set object to serialize\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @param seen - Set of objects that have already been serialized (used to detect circular references)\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts a Set object into a human-readable string representation\n * with proper formatting and indentation. The serialization process:\n *\n * 1. Handles empty Sets with a compact `Set {}` representation\n * 2. For non-empty Sets, creates a multi-line representation with each value on separate lines\n * 3. Properly serializes each value based on its type\n * 4. Preserves complex structure of nested values through recursive serialization\n * 5. Applies consistent indentation for nested structures\n *\n * Since Sets maintain insertion order in JavaScript, the serialized output will\n * reflect this order, displaying elements in the sequence they were added to the Set.\n *\n * @example\n * ```ts\n * const set = new Set([1, \"text\", {a: true}, [2, 3]]);\n * const result = [];\n *\n * serializeSet(set, result, \" \");\n * // the result now contains:\n * // [\"Set {\",\n * // \"1,\",\n * // \"\\\"text\\\",\",\n * // \"{\",\n * // \" a: true\",\n * // \"},\",\n * // \"Array [\",\n * // \" 2,\",\n * // \" 3\",\n * // \"]\",\n * // \"}\"]\n * ```\n *\n * @see serializeValue - Function used to serialize individual Set values\n * @see appendLines - Helper for handling multi-line formatting\n *\n * @since 1.0.0\n */\n\nexport function serializeSet(set: Set<unknown>, lines: Array<string>, indent: string, seen: WeakSet<object>): void {\n if (set.size === 0) {\n lines.push('Set {}');\n\n return;\n }\n\n lines.push('Set {');\n const arr = Array.from(set);\n arr.forEach((item, i) => {\n const subLines: Array<string> = [];\n serializeValue(item, subLines, indent, seen);\n appendLines(subLines, lines, '', i === arr.length - 1, indent);\n });\n lines.push('}');\n}\n\n/**\n * Serializes a Node.js Buffer object into a multi-line string representation.\n *\n * @param arr - The Buffer object to serialize\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts a Buffer object into a human-readable string representation\n * with proper formatting and indentation. The serialization process:\n *\n * 1. Handles empty Buffers with a compact `Buffer {}` representation\n * 2. For non-empty Buffers, creates a multi-line representation with each byte value on separate lines\n * 3. Shows numeric byte values without any conversion to characters\n * 4. Adds trailing commas to all bytes except the last one\n * 5. Maintains a consistent indentation level for all byte values\n *\n * The function first converts the Buffer to an array of numeric values to ensure\n * consistent handling of byte data regardless of the Buffer implementation.\n *\n * @example\n * ```ts\n * const buffer = Buffer.from([104, 101, 108, 108, 111]); // \"hello\" in ASCII\n * const result = [];\n *\n * serializeBuffer(buffer, result, \" \");\n * // the result now contains:\n * // [\"Buffer {\",\n * // \" 104,\",\n * // \" 101,\",\n * // \" 108,\",\n * // \" 108,\",\n * // \" 111\",\n * // \"}\"]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeBuffer(arr: Buffer, lines: Array<string>, indent: string): void {\n const values = Array.from(arr as unknown as Array<number>);\n if (values.length === 0) {\n lines.push('Buffer {}');\n\n return;\n }\n\n lines.push('Buffer {');\n for (let i = 0; i < values.length; i++) {\n const val = values[i];\n const comma = i === values.length - 1 ? '' : ',';\n\n lines.push(`${ indent }${ val }${ comma }`);\n }\n lines.push('}');\n}\n\n/**\n * Serializes a JavaScript TypedArray object into a multi-line string representation.\n *\n * @param arr - The ArrayBufferView (TypedArray) object to serialize\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts any TypedArray (such as Int8Array, Uint8Array, Float32Array, etc.)\n * into a human-readable string representation with proper formatting and indentation.\n * The serialization process:\n *\n * 1. Dynamically determines the specific TypedArray type using Object.prototype.toString\n * 2. Handles empty TypedArrays with a compact `{TypeName} []` representation\n * 3. For non-empty TypedArrays, creates a multi-line representation with each numeric value on separate lines\n * 4. Adds trailing commas to all values except the last one\n * 5. Maintains consistent indentation for all values\n *\n * The function first converts the TypedArray to a standard array of numeric values\n * to ensure consistent handling across different TypedArray implementations.\n *\n * @example\n * ```ts\n * const int32Array = new Int32Array([42, 100, -5]);\n * const result = [];\n *\n * serializeTypedArray(int32Array, result, \" \");\n * // the result now contains:\n * // [\"Int32Array [\",\n * // \" 42,\",\n * // \" 100,\",\n * // \" -5\",\n * // \"]\"]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeTypedArray(arr: ArrayBufferView, lines: Array<string>, indent: string): void {\n const name = Object.prototype.toString.call(arr).slice(8, -1);\n const values = Array.from(arr as unknown as Array<number>);\n if (values.length === 0) {\n lines.push(`${ name } []`);\n\n return;\n }\n\n lines.push(`${ name } [`);\n for (let i = 0; i < values.length; i++) {\n const val = values[i];\n const comma = i === values.length - 1 ? '' : ',';\n\n lines.push(`${ indent }${ val }${ comma }`);\n }\n lines.push(']');\n}\n\n/**\n * Serializes a JavaScript object into a multi-line string representation.\n *\n * @param obj - The object to serialize\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @param seen - Set of objects that have already been serialized (used to detect circular references)\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts an object into a human-readable string representation\n * with proper formatting and indentation. The serialization process:\n *\n * 1. Includes the constructor name in the output (e.g., `Date {}` instead of just `{}`)\n * 2. Falls back to \"Object\" if the constructor is not available or is the base Object constructor\n * 3. Handles empty objects with a compact `{ConstructorName} {}` representation\n * 4. For non-empty objects, creates a multi-line representation with each property on separate lines\n * 5. Formats each property as \"key: value\" with proper indentation\n * 6. Serializes property values recursively to handle nested objects and complex values\n *\n * The function uses Object.entries() to list own enumerable properties,\n * which means non-enumerable properties and those in the prototype chain will not be included.\n *\n * @example\n * ```ts\n * const object = {\n * name: \"example\",\n * count: 42,\n * nested: { flag: true }\n * };\n * const result = [];\n *\n * serializeObject(object, result, \" \");\n * // the result now contains:\n * // [\"Object {\",\n * // \" name: \\\"example\\\",\",\n * // \" count: 42,\",\n * // \"nested: Object {\",\n * // \" flag: true\",\n * // \" }\",\n * // \"}\"]\n * ```\n *\n * @see serializeValue - Function used to serialize property values\n * @see appendLines - Helper for handling multi-line formatting\n *\n * @since 1.0.0\n */\n\nexport function serializeObject(obj: object, lines: Array<string>, indent: string, seen: WeakSet<object>): void {\n const name = obj.constructor && obj.constructor !== Object ? obj.constructor.name : 'Object';\n const entries = Object.entries(obj);\n if (entries.length === 0) {\n lines.push(`${ name } {}`);\n\n return;\n }\n\n lines.push(`${ name } {`);\n entries.forEach(([ key, val ], i) => {\n const subLines: Array<string> = [];\n serializeValue(val, subLines, indent, seen);\n appendLines(subLines, lines, `${ String(key) }: `, i === entries.length - 1, indent);\n });\n lines.push('}');\n}\n\n/**\n * Serializes any JavaScript value into a human-readable string representation.\n *\n * @param value - The value to serialize (can be of any type)\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures (defaults to a predefined indent value)\n * @param seen - Set of objects that have already been serialized (used to detect circular references)\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function serves as the main entry point for the serialization system, dispatching\n * to specialized serializers based on the value type. The serialization process:\n *\n * 1. First attempts to serialize primitive values (null, undefined, booleans, numbers, symbols)\n * 2. Handles multi-line strings with special formatting - each line is properly indented\n * 3. Uses specialized serializers for common complex types:\n * - Maps\n * - Arrays\n * - Sets\n * - Buffers\n * - TypedArrays (Int8Array, Uint8Array, Float32Array, etc.)\n * 4. Falls back to object serialization for any other non-primitive values\n *\n * The function generates a clear, structured representation that maintains the\n * hierarchical relationships between nested objects and preserves type information.\n *\n * @example\n * ```ts\n * const complexValue = {\n * name: \"example\",\n * numbers: [1, 2, 3],\n * settings: new Map([[\"active\", true], [\"mode\", \"advanced\"]]),\n * data: new Uint8Array([10, 20, 30])\n * };\n *\n * const result = [];\n * serializeValue(complexValue, result);\n * // result contains a multi-line representation of the entire object structure\n * ```\n *\n * @see serializePrimitive - Helper for handling primitive values\n * @see serializeMap - Helper for serializing Map objects\n * @see serializeArray - Helper for serializing Arrays\n * @see serializeSet - Helper for serializing Sets\n * @see serializeBuffer - Helper for serializing Buffers\n * @see serializeTypedArray - Helper for serializing TypedArrays\n * @see serializeObject - Helper for serializing generic objects\n *\n * @since 1.0.0\n */\n\nexport function serializeValue(value: unknown, lines: Array<string>, indent: string = INDENT, seen: WeakSet<object>): void {\n const primitive = serializePrimitive(value);\n if (primitive !== null) {\n lines.push(primitive);\n\n return;\n }\n\n // Handle multi-line strings\n if (typeof value === 'string') {\n const stringLines = value.split('\\n');\n lines.push('String \"'); // opening quote line\n for (const line of stringLines) {\n lines.push(`${ indent }${ line }`);\n }\n lines.push('\"'); // closing quote line\n\n return;\n }\n\n if (typeof value === 'object' && value !== null) {\n if (seen.has(<object> value)) {\n lines.push('[Circular]');\n\n return;\n }\n\n seen.add(<object> value);\n\n if (value instanceof Map) {\n serializeMap(value, lines, indent, seen);\n } else if (Array.isArray(value)) {\n serializeArray(value, lines, indent, seen);\n } else if (value instanceof Set) {\n serializeSet(value, lines, indent, seen);\n } else if (value instanceof Buffer) {\n serializeBuffer(value, lines, indent);\n } else if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {\n serializeTypedArray(value, lines, indent);\n } else {\n serializeObject(value as object, lines, indent, seen);\n }\n\n return;\n }\n\n serializeObject(value as object, lines, indent, seen);\n}\n\n/**\n * Serializes an error object into a plain object containing its enumerable properties and common error fields.\n *\n * @param error - The error value to serialize.\n *\n * @returns A plain object with the error's enumerable properties and the `name`, `message`, and `stack` fields if available.\n * Returns the original value if it is not an object.\n *\n * @remarks\n * This function copies all own enumerable properties from the provided error,\n * ensuring that the `name`, `message`, and `stack` fields are preserved even if they are non-enumerable.\n * If the input is not an object, it is returned unchanged.\n *\n * @example\n * ```ts\n * const err = new Error('Something went wrong');\n * const serialized = serializeError(err);\n * // {\n * // name: 'Error',\n * // message: 'Something went wrong',\n * // stack: 'Error: Something went wrong\\n at ...'\n * // }\n *\n * const notAnError = 'oops';\n * serializeError(notAnError); // 'oops'\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeError(error: Record<string, unknown> | unknown): Record<string, unknown> | unknown {\n if (error && typeof error === 'object') {\n if('toJSON' in error && typeof error.toJSON === 'function') {\n return error.toJSON();\n }\n\n const json: Record<string, unknown> = {};\n\n for (const [ key, value ] of Object.entries(error)) {\n if (value !== undefined) {\n json[key] = value;\n }\n }\n\n json.name = (error as { name?: unknown })?.name ?? json.name;\n json.message = (error as { message?: unknown })?.message ?? json.message;\n json.stack = (error as { stack?: unknown })?.stack ?? json.stack;\n\n return json;\n }\n\n return error;\n}\n\n/**\n * Converts any JavaScript value into an array of strings representing its serialized form.\n *\n * @param element - The value to serialize (can be of any type)\n * @param indent - String used for indentation of nested structures (defaults to a predefined indent value)\n * @returns Array of strings containing the serialized representation\n *\n * @remarks\n * This function serves as a convenient public API for the serialization system.\n * It creates an empty array, delegates the actual serialization work to the\n * specialized `serializeValue` function, and returns the resulting array of\n * string lines.\n *\n * Each element in the returned array represents a single line in the serialized\n * output, with proper indentation and formatting already applied. This makes it\n * easy to either join the lines for display or process them individually.\n *\n * Unlike direct use of `serializeValue`, this function handles the creation and\n * management of the output array, simplifying the API for consumers.\n *\n * @example\n * ```ts\n * // Serialize a simple object\n * const obj = { name: \"example\", values: [1, 2, 3] };\n * const lines = serialize(obj);\n * console.log(lines.join('\\n'));\n * // Output:\n * // Object {\n * // name: \"example\",\n * // values: Array [\n * // 1,\n * // 2,\n * // 3\n * // ]\n * // }\n * ```\n *\n * @see serializeValue - The underlying function that performs the actual serialization\n *\n * @since 1.0.0\n */\n\nexport function serialize(element: unknown, indent: string = INDENT): Array<string> {\n const lines: Array<string> = [];\n serializeValue(element, lines, indent, new WeakSet());\n\n return lines;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ContextInterface, DiffSegmentType } from '@diff/providers/interfaces/string-provider.interface';\nimport type { FoundSubsequenceType, IsMatchType } from '@diff/providers/interfaces/string-provider.interface';\n\n/**\n * Enumeration of diff operation types representing delete, equal, and insert operations.\n *\n * @remarks\n * These values correspond to the standard diff operation convention:\n * - DELETE (-1): Content exists in the first sequence but not in the second.\n * - EQUAL (0): Content exists identically in both sequences.\n * - INSERT (1): Content exists in the second sequence but not in the first.\n *\n * @example\n * ```ts\n * const operation = DiffTypes.DELETE; // -1\n * const diffSegment = [DiffTypes.EQUAL, \"shared text\"]; // [0, \"shared text\"]\n * ```\n *\n * @since 1.0.0\n */\n\nexport const enum DiffTypes {\n DELETE = -1,\n EQUAL = 0,\n INSERT = 1,\n}\n\n/**\n * Counts the number of matching characters from the end positions of two sequences.\n *\n * @returns The count of matching characters in backward direction\n *\n * @remarks\n * This function works backwards from the end boundaries of both sequences\n * to find common suffix text. It is used to optimize the diff algorithm\n * by identifying and handling common suffixes separately.\n *\n * @example\n * ```ts\n * const context = {\n * aStart: 0, aEnd: text1.length,\n * bStart: 0, bEnd: text2.length,\n * isMatch: (i, j) => text1[i] === text2[j]\n * };\n * const suffixLength = countCommonBackward.call(context);\n * ```\n *\n * @since 1.0.0\n */\n\nfunction countCommonForward(this: ContextInterface): number {\n let count = 0;\n while (\n this.aStart + count < this.aEnd &&\n this.bStart + count < this.bEnd &&\n this.isMatch(this.aStart + count, this.bStart + count)\n ) {\n count++;\n }\n\n return count;\n}\n\n/**\n * Counts the number of matching characters from the end positions of two sequences.\n *\n * @returns The count of matching characters in backward direction\n *\n * @remarks\n * This function works backwards from the end boundaries of both sequences\n * to find common suffix text. It continues counting as long as characters match,\n * and the indices remain within the valid sequence bounds.\n *\n * @example\n * ```ts\n * const context = {\n * aStart: 0, aEnd: text1.length,\n * bStart: 0, bEnd: text2.length,\n * isMatch: (i, j) => text1[i] === text2[j]\n * };\n * const suffixLength = countCommonBackward.call(context);\n * ```\n *\n * @since 1.0.0\n */\n\nfunction countCommonBackward(this: ContextInterface): number {\n let count = 0;\n while (\n this.aEnd - 1 - count >= this.aStart &&\n this.bEnd - 1 - count >= this.bStart &&\n this.isMatch(this.aEnd - 1 - count, this.bEnd - 1 - count)\n ) {\n count++;\n }\n\n return count;\n}\n\n/**\n * Reconstructs the edit path from the trace matrix created during the Myers diff algorithm execution.\n *\n * @param trace - Array of vectors storing the x coordinates for each diagonal at each edit distance\n * @param offset - Offset value for indexing into the vectors (typically max edit distance)\n * @param dFinal - The final edit distance at which the end point was found\n *\n * @remarks\n * This function works by backtracking through the trace matrix, starting from the endpoint and\n * following the path back to the start. It reconstructs the sequence of operations (inserts,\n * deletes, and equals) needed to transform the first sequence into the second sequence.\n *\n * The backtracking process involves determining whether horizontal, vertical, or diagonal\n * movements were made in the edit graph, corresponding to insertions, deletions, or matches\n * respectively.\n *\n * @example\n * ```ts\n * const context = {\n * aStart: 0, aEnd: textA.length,\n * bStart: 0, bEnd: textB.length,\n * isMatch: (i, j) => textA[i] === textB[j],\n * foundSubsequence: (n, aIdx, bIdx) => { \\/* handle subsequence *\\/ }\n * };\n *\n * // During findMiddleSnake:\n * backtrackFlat.call(context, trace, max, dFinal);\n * ```\n *\n * @see findMiddleSnake\n * @see diffSequence\n *\n * @since 1.0.0\n */\n\nfunction backtrackFlat(this: ContextInterface, trace: Array<number[]>, offset: number, dFinal: number): void {\n let x = this.aEnd - this.aStart;\n let y = this.bEnd - this.bStart;\n const result: Array<[ number, number, number ]> = [];\n\n for (let d = dFinal; d > 0; d--) {\n const vPrev = trace[d - 1];\n const k = x - y;\n\n let prevK: number;\n const kMinus = vPrev[k - 1 + offset];\n const kPlus = vPrev[k + 1 + offset];\n\n if (k === -d || (k !== d && kMinus < kPlus)) {\n prevK = k + 1;\n } else {\n prevK = k - 1;\n }\n\n const prevKIndex = prevK + offset;\n const prevX = vPrev[prevKIndex];\n const prevY = prevX - prevK;\n\n // Diagonal: matching characters\n while (x > prevX && y > prevY) {\n --x;\n --y;\n result.push([ 1, this.aStart + x, this.bStart + y ]);\n }\n\n if (x === prevX) {\n result.push([ 0, this.aStart + prevX, this.bStart + prevY ]);\n } else {\n result.push([ 0, this.aStart + prevX, this.bStart + prevY ]);\n }\n\n x = prevX;\n y = prevY;\n }\n\n for (const item of result.reverse()) {\n this.foundSubsequence(...item);\n }\n}\n\n/**\n * Implements the central part of Myers' diff algorithm by finding the middle snake of the shortest edit script.\n *\n * @remarks\n * This function implements the core of the Myers diff algorithm. It works by:\n * 1. Computing the length of both sequences\n * 2. Iterating through possible edit distances (d)\n * 3. For each d, computing the furthest reaching paths along each diagonal k\n * 4. When the paths from opposite directions meet, a middle snake is found\n * 5. Calling backtrackFlat to reconstruct the edit path when end point is reached\n *\n * The algorithm uses a \"divide and conquer\" approach to find the shortest edit script\n * between two sequences efficiently, with worst-case time complexity of O((n+m)D).\n *\n * @example\n * ```ts\n * const context = {\n * aStart: 0, aEnd: text1.length,\n * bStart: 0, bEnd: text2.length,\n * isMatch: (i, j) => text1[i] === text2[j]\n * };\n * findMiddleSnake.call(context);\n * ```\n *\n * @see backtrackFlat\n * @see diffSequence\n *\n * @since 1.0.0\n */\n\nfunction findMiddleSnake(this: ContextInterface): void {\n const n = this.aEnd - this.aStart;\n const m = this.bEnd - this.bStart;\n const max = n + m;\n\n let dFinal = 0;\n const v = new Array(2 * max + 1).fill(0);\n const trace: Array<number[]> = [];\n\n for (let d = 0; d <= max; d++) {\n const vCopy = new Array(2 * max + 1);\n trace[d] = vCopy;\n\n for (let k = -d; k <= d; k += 2) {\n const kIndex = k + max;\n\n let x: number;\n if (k === -d || (k !== d && v[k - 1 + max] < v[k + 1 + max])) {\n x = v[k + 1 + max];\n } else {\n x = v[k - 1 + max] + 1;\n }\n\n let y = x - k;\n while (x < n && y < m && this.isMatch(this.aStart + x, this.bStart + y)) {\n x++;\n y++;\n }\n\n v[kIndex] = x;\n vCopy[kIndex] = x;\n if (x >= n && y >= m) {\n dFinal = d;\n\n return backtrackFlat.call(this, trace, max, dFinal);\n }\n }\n }\n}\n\n/**\n * Performs a diff operation between two sequences by implementing an optimized Myers algorithm.\n *\n * @remarks\n * This function efficiently computes the differences between two sequences by:\n * 1. First identifying common prefix and suffix elements to reduce the problem size\n * 2. Handling the special case where sequences are fully equal\n * 3. Adjusting sequence boundaries to exclude common prefix/suffix\n * 4. Applying the Myers diff algorithm via findMiddleSnake to find the shortest edit path\n * 5. Reporting common subsequences through the context's foundSubsequence method\n *\n * This optimization significantly improves performance for sequences with common\n * prefixes or suffixes, which is a common case in many text diff scenarios.\n *\n * @example\n * ```ts\n * const context = {\n * aStart: 0, aEnd: textA.length,\n * bStart: 0, bEnd: textB.length,\n * isMatch: (i, j) => textA[i] === textB[j],\n * foundSubsequence: (n, aIdx, bIdx) => { \\/* handle subsequence *\\/ }\n * };\n * diffSequence.call(context);\n * ```\n *\n * @since 1.0.0\n */\n\nexport function diffSequence(this: ContextInterface): void {\n const prefixLen = countCommonForward.call(this);\n const isFullyEqual = this.aStart + prefixLen >= this.aEnd && this.bStart + prefixLen >= this.bEnd;\n if (prefixLen > 0) {\n this.foundSubsequence(prefixLen, this.aStart, this.bStart);\n\n if (isFullyEqual) {\n return;\n }\n }\n\n this.aStart += prefixLen;\n this.bStart += prefixLen;\n\n const suffixLen = countCommonBackward.call(this);\n this.aEnd -= suffixLen;\n this.bEnd -= suffixLen;\n if (this.aStart < this.aEnd || this.bStart < this.bEnd) {\n findMiddleSnake.call(this);\n }\n\n if (suffixLen > 0) {\n this.foundSubsequence(suffixLen, this.aEnd, this.bEnd);\n }\n}\n\n/**\n * Creates and executes a diff operation between two sequences of elements.\n *\n * @param aLength - Length of the first sequence\n * @param bLength - Length of the second sequence\n * @param isMatch - Function that determines if elements at specified positions match\n * @param foundSubsequence - Callback function that processes found common subsequences\n *\n * @remarks\n * This function serves as a convenient wrapper around the core diff algorithm.\n * It constructs a context object with the provided parameters and invokes the\n * diff sequence calculation. The results are reported through the foundSubsequence\n * callback as common subsequences are identified.\n *\n * The comparison is performed using the provided isMatch function, allowing\n * for custom equality logic between sequence elements.\n *\n * @example\n * ```ts\n * createDiff(\n * textA.length,\n * textB.length,\n * (iA, iB) => textA[iA] === textB[iB],\n * (nCommon, aCommon, bCommon) => {\n * // Process the found common subsequence\n * }\n * );\n * ```\n *\n * @see diffSequence\n * @see ContextInterface\n *\n * @since 1.0.0\n */\n\nexport function createDiff(\n aLength: number, bLength: number, isMatch: IsMatchType, foundSubsequence: FoundSubsequenceType\n): void {\n const context: ContextInterface = {\n aStart: 0,\n bStart: 0,\n aEnd: aLength,\n bEnd: bLength,\n isMatch,\n foundSubsequence\n };\n\n diffSequence.call(context);\n}\n\n/**\n * Compares two strings and returns an array of diff operations.\n * Implements an optimized version of the Myers diff algorithm.\n *\n * @param a - First string to compare\n * @param b - Second string to compare\n * @returns Array of diff operations, where each operation is a tuple of [type, text]\n *\n * @throws Never throws exceptions but may produce unexpected results with invalid inputs\n *\n * @remarks\n * This function implements a highly optimized version of the Myers diff algorithm.\n * It efficiently finds the shortest edit script between two strings and\n * represents the differences as a series of delete, equal, and insert operations.\n *\n * @example\n * ```ts\n * const diff = diffStringsRaw('abc', 'abxc');\n * // Returns: [[0, 'ab'], [-1, 'c'], [1, 'xc']]\n * ```\n *\n * @see DiffSegmentType\n * @see ContextInterface\n * @since 1.0.0\n */\n\nexport function diffStringsRaw(a: string, b: string): Array<DiffSegmentType> {\n let aIndex = 0;\n let bIndex = 0;\n let pendingInsert = '';\n let pendingDelete = '';\n const diffs: Array<DiffSegmentType> = [];\n\n // Helper to merge with last diff if same type\n function pushDiff(type: DiffTypes, text: string): void {\n const last = diffs[diffs.length - 1];\n if (last && last[0] === type) {\n last[1] += text;\n } else {\n diffs.push([ type, text ]);\n }\n }\n\n createDiff(a.length, b.length, (iA: number, iB: number): boolean => {\n return a[iA] === b[iB];\n }, (nCommon: number, aCommon: number, bCommon: number): void => {\n if (aIndex !== aCommon) {\n pendingDelete += a.slice(aIndex, aCommon);\n }\n if (bIndex !== bCommon) {\n pendingInsert += b.slice(bIndex, bCommon);\n }\n\n if (nCommon > 0) {\n // Flush pending delete/insert together before equal\n if (pendingDelete) {\n pushDiff(DiffTypes.DELETE, pendingDelete);\n pendingDelete = '';\n }\n if (pendingInsert) {\n pushDiff(DiffTypes.INSERT, pendingInsert);\n pendingInsert = '';\n }\n\n // Push equal segment\n pushDiff(DiffTypes.EQUAL, b.slice(bCommon, bCommon + nCommon));\n }\n\n aIndex = aCommon + nCommon;\n bIndex = bCommon + nCommon;\n });\n\n // After the last common subsequence, push remaining change items.\n if (aIndex !== a.length) pendingDelete += a.slice(aIndex);\n if (bIndex !== b.length) pendingInsert += b.slice(bIndex);\n\n // Final flush\n if (pendingDelete) diffs.push([ DiffTypes.DELETE, pendingDelete ]);\n if (pendingInsert) diffs.push([ DiffTypes.INSERT, pendingInsert ]);\n\n return diffs;\n}\n\n/**\n * Compares two arrays of strings line by line and returns an array of diff operations.\n *\n * @param a - First array of strings (lines) to compare\n * @param b - Second array of strings (lines) to compare\n * @returns Array of diff operations, where each operation is a tuple of [type, text]\n *\n * @remarks\n * This function implements a line-by-line comparison algorithm that identifies differences\n * between two text arrays. The comparison is performed using strict equality between lines.\n *\n * The function produces a sequence of operations (delete, insert, equal) that represent\n * the minimal set of changes needed to transform the first array into the second array.\n * Each operation is represented as a tuple where:\n * - The first element is the operation type (-1 for delete, 0 for equal, 1 for insert)\n * - The second element is the affected line\n *\n * @example\n * ```ts\n * const result = diffLinesRaw(\n * ['line 1', 'line 2', 'line 3'],\n * ['line 1', 'new line', 'line 3']\n * );\n * // Returns: [[0, 'line 1'], [-1, 'line 2'], [1, 'new line'], [0, 'line 3']]\n * ```\n *\n * @see DiffTypes\n * @see DiffSegmentType\n *\n * @since 1.0.0\n */\n\nexport function diffLinesRaw(a: Array<string>, b: Array<string>): Array<DiffSegmentType> {\n let aIndex = 0;\n let bIndex = 0;\n const diffs: Array<DiffSegmentType> = [];\n\n createDiff(a.length, b.length, (iA: number, iB: number): boolean => {\n // Why do we do this?\n // When serializing objects, the last property does NOT have a trailing comma because that is a valid syntax.\n // For example,\n // { name: \"ssss\" }\n //\n // But if one object has an extra property, it will have a comma on the previous last property:\n // { name: \"ssss\", yyy: \"sdx\" }\n //\n // This means during diffing, one line might have a trailing comma and the other might not.\n // This causes false positives where the diff thinks lines differ when only the comma is missing.\n //\n // To fix this, if one line has a trailing comma but the other doesn't,\n // we add the missing comma to the line without it before comparing.\n // This normalizes the lines so the diff ignores trailing comma differences.\n\n const hasCommaA = a[iA].trimEnd().endsWith(',');\n const hasCommaB = b[iB].trimEnd().endsWith(',');\n\n if (hasCommaA && !hasCommaB) {\n b[iB] += ',';\n } else if (!hasCommaA && hasCommaB) {\n a[iA] += ',';\n }\n\n return a[iA] === b[iB];\n }, (nCommon: number, aCommon: number, bCommon: number): void => {\n for (; aIndex !== aCommon; aIndex += 1) {\n diffs.push([ DiffTypes.DELETE, a[aIndex] ]);\n }\n for (; bIndex !== bCommon; bIndex += 1) {\n diffs.push([ DiffTypes.INSERT, b[bIndex] ]);\n }\n for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) {\n diffs.push([ DiffTypes.EQUAL, b[bIndex] ]);\n }\n });\n\n // After the last common subsequence, push remaining change items.\n for (; aIndex !== a.length; aIndex += 1) {\n diffs.push([ DiffTypes.DELETE, a[aIndex] ]);\n }\n for (; bIndex !== b.length; bIndex += 1) {\n diffs.push([ DiffTypes.INSERT, b[bIndex] ]);\n }\n\n return diffs;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { DiffSegmentType } from '@diff/providers/interfaces/string-provider.interface';\n\n/**\n * Imports\n */\n\nimport { DiffTypes } from '@diff/providers/string.provider';\n\n/**\n * Improves the semantic meaning of a diff result by merging short equal segments into delete/insert\n * operations, making the diff more human-readable.\n *\n * @param diffs - Array of diff segments to process\n *\n * @returns A new array of diff segments with improved semantic meaning\n *\n * @remarks\n * This function handles cases where very short equal segments (1 character or less) are better\n * represented as part of delete/insert operations for improved readability. It maintains longer\n * equal segments (more than 1 character) as separate segments.\n *\n * The algorithm works by:\n * 1. Collecting delete and insert operations in buffers\n * 2. When encountering small equal segments (1 char or less), adding them to both buffers\n * 3. When encountering larger equal segments, flushing the buffers as separate operations\n *\n * @example\n * ```ts\n * const diffs = [\n * [DiffTypes.DELETE, 'te'],\n * [DiffTypes.EQUAL, 's'],\n * [DiffTypes.INSERT, 'a']\n * ];\n * const result = cleanupSemantic(diffs);\n * // Result: [[DiffTypes.DELETE, 'tes'], [DiffTypes.INSERT, 'as']]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function cleanupSemantic(diffs: Array<DiffSegmentType>): Array<DiffSegmentType> {\n let delBuf: string[] = [];\n let insBuf: string[] = [];\n const result: Array<DiffSegmentType> = [];\n\n const flushBuffers = (): void => {\n if (delBuf.length) {\n result.push([ DiffTypes.DELETE, delBuf.join('') ]);\n delBuf = [];\n }\n if (insBuf.length) {\n result.push([ DiffTypes.INSERT, insBuf.join('') ]);\n insBuf = [];\n }\n };\n\n for (let i = 0; i < diffs.length; i++) {\n const [ type, text ] = diffs[i];\n\n if (type === DiffTypes.EQUAL) {\n if (text.length <= 1) {\n const prevType = i > 0 ? diffs[i - 1][0] : null;\n const nextType = i + 1 < diffs.length ? diffs[i + 1][0] : null;\n const isEdit = (t: DiffTypes | null): boolean =>\n t === DiffTypes.DELETE || t === DiffTypes.INSERT;\n\n // Merge if surrounded by any edits (delete or insert)\n const surroundedByEdit = isEdit(prevType) && isEdit(nextType);\n\n if (surroundedByEdit) {\n for (const ch of text) {\n delBuf.push(ch);\n insBuf.push(ch);\n }\n continue;\n }\n }\n\n // Otherwise flush and keep equal\n flushBuffers();\n result.push([ DiffTypes.EQUAL, text ]);\n } else if (type === DiffTypes.DELETE) {\n for (const ch of text) delBuf.push(ch);\n } else if (type === DiffTypes.INSERT) {\n for (const ch of text) insBuf.push(ch);\n } else {\n flushBuffers();\n result.push([ type, text ]);\n }\n }\n\n flushBuffers();\n\n return result;\n}\n", "/**\n * Imports\n */\n\nimport { xterm } from '@remotex-labs/xansi';\n\n/**\n * Formats text with dimmed styling for less emphasized content.\n *\n * @param text - The text to format with dim styling\n * @returns The text wrapped with ANSI dim styling codes\n *\n * @since 1.0.0\n */\n\nexport const DIM = xterm.dim;\n\n/**\n * Formats text with light orange highlighting for important values.\n *\n * @param text - The text to format in lightOrange\n * @returns The text wrapped with ANSI light orange styling codes\n *\n * @since 1.0.0\n */\n\nexport const MARK = xterm.lightOrange;\n\n/**\n * Formats text in red, typically used for labeling received/actual values.\n *\n * @param text - The text to format in red\n * @returns The text wrapped with ANSI red styling codes\n *\n * @since 1.0.0\n */\n\nexport const RECEIVED = xterm.lightCoral;\n\n/**\n * Formats text in green, typically used for labeling expected values.\n *\n * @param text - The text to format in green\n * @returns The text wrapped with ANSI green styling codes\n *\n * @since 1.0.0\n */\n\nexport const EXPECTED = xterm.oliveGreen;\n\n/**\n * Formats text in cyan color.\n *\n * @param text - The text to format in cyan\n * @returns The text wrapped with ANSI cyan styling codes\n *\n * @since 1.0.0\n */\n\nexport const CYAN = xterm.cyan;\n\n/**\n * Formats text with inverse styling (swapping foreground and background colors).\n *\n * @param text - The text to format with inverse styling\n * @returns The text wrapped with ANSI inverse styling codes\n *\n * @since 1.0.0\n */\n\nexport const INVERSE = xterm.inverse;\n\n/**\n * Formats text with bright white styling, typically used for titles or headings.\n *\n * @param text - The text to format in bright white\n * @returns The text wrapped with ANSI bright white styling codes\n *\n * @since 1.0.0\n */\n\nexport const TITLE = xterm.whiteBright;\n", "/**\n * Imports\n */\n\nimport { serialize } from '@components/serialize.component';\nimport { cleanupSemantic } from '@diff/components/semantic.component';\nimport { asymmetricMatch, isAsymmetric } from '@components/object.component';\nimport { CYAN, DIM, EXPECTED, INVERSE, RECEIVED } from '@components/color.component';\nimport { diffLinesRaw, diffStringsRaw, DiffTypes } from '@diff/providers/string.provider';\n\n/**\n * Determines the type of any JavaScript value as a string representation.\n *\n * @param value - The value whose type should be determined\n * @returns A string representing the type of the value\n *\n * @remarks\n * This function provides a more detailed type description than JavaScript's built-in\n * `typeof` operator by also identifying specific object types through their constructor\n * names. The function handles special cases:\n *\n * - For `null`, it returns the string \"null\" (unlike `typeof` which returns \"object\")\n * - For primitive types (string, number, boolean, undefined), it returns the standard typeof result\n * - For objects, it returns the constructor name when available (e.g., \"Array\", \"Map\", \"Set\", \"Date\")\n * - For objects with missing or invalid constructor information, it falls back to \"Object\"\n *\n * This makes the function particularly useful for debugging, error messages, and\n * test frameworks where precise type identification helps diagnose issues.\n *\n * @example\n * ```ts\n * getType(null); // \"null\"\n * getType(undefined); // \"undefined\"\n * getType(42); // \"number\"\n * getType(\"hello\"); // \"string\"\n * getType(true); // \"boolean\"\n * getType([1, 2, 3]); // \"Array\"\n * getType(new Map()); // \"Map\"\n * getType(new Date()); // \"Date\"\n * getType({}); // \"Object\"\n * getType(Object.create(null)); // \"Object\" (no constructor)\n * ```\n *\n * @since 1.0.0\n */\n\nexport function getType(value: unknown): string {\n if (value === null) return 'null';\n if (value === true) return 'true';\n if (value === false) return 'false';\n\n return value && typeof value === 'object' ? value.constructor?.name ?? 'Object' : typeof value;\n}\n\n/**\n * Normalizes two strings by computing a semantic diff and marking differences with inverse formatting.\n *\n * This function uses a raw diff algorithm followed by semantic cleanup to align matching parts,\n * then inverts added or removed segments to visually highlight differences.\n *\n * @param a - The first string to normalize.\n * @param b - The second string to normalize.\n * @param clean - Whether to apply semantic cleanup to diffs for improved readability\n * @returns A tuple of strings with aligned and marked differences.\n *\n * @remarks\n * - The result uses `INVERSE` formatting for added or removed segments.\n * - Matching segments are preserved as-is.\n * - Empty strings are replaced with a tab (`\\t`) to ensure diffing is stable.\n *\n * @example\n * ```ts\n * const [a, b] = normalizeStrings(\"hello\", \"hallo\");\n * // a: \"h\\u001b[7me\\u001b[27mllo\"\n * // b: \"h\\u001b[7ma\\u001b[27mllo\"\n * ```\n *\n * @since 1.0.0\n */\n\nexport function normalizeStrings(a: string, b: string, clean: boolean = true): [ string, string ] {\n let resultA = '';\n let resultB = '';\n let diffs = diffStringsRaw(a || '\\t', b || '\\t');\n if (clean) diffs = cleanupSemantic(diffs);\n\n for (const [ type, text ] of diffs) {\n if (type === DiffTypes.EQUAL) {\n resultA += text;\n resultB += text;\n } else if (type === DiffTypes.DELETE) {\n resultA += INVERSE(text);\n } else if (type === DiffTypes.INSERT) {\n resultB += INVERSE(text);\n }\n }\n\n return [ resultA, resultB ];\n}\n\n/**\n * Recursively normalizes two arrays by aligning each element.\n *\n * The function mutates both input arrays in-place, recursively normalizing\n * each pair of elements by index. If arrays differ in length, undefined\n * elements will be normalized as well.\n *\n * @param a - The first array to normalize.\n * @param b - The second array to normalize.\n * @returns A tuple containing the normalized arrays.\n *\n * @remarks\n * - Elements are normalized using {@link normalizeAsymmetric}.\n * - The result is the same reference as the original arrays, modified in-place.\n * - The resulting arrays will have the same length, equal to the longer of the two.\n *\n * @example\n * ```ts\n * const [a, b] = normalizeArrays([1, 2], [1, xExpect.any(Number)]);\n * // a: [1, 2]\n * // b: [1, 2]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function normalizeArrays(a: Array<unknown>, b: Array<unknown>): [ Array<unknown>, Array<unknown> ] {\n const aResult = [ ...a ];\n const bResult = [ ...b ];\n\n const len = Math.max(a.length, b.length);\n for (let i = 0; i < len; i++) {\n [ aResult[i], bResult[i] ] = normalizeAsymmetric(a[i], b[i]);\n }\n\n return [ aResult, bResult ];\n}\n\n/**\n * Recursively normalizes two objects by aligning values at shared keys.\n *\n * The function mutates both input objects in-place, normalizing values\n * only for keys that exist in both objects. Missing keys are ignored.\n *\n * @param a - The first object to normalize.\n * @param b - The second object to normalize.\n * @returns A tuple containing the normalized objects.\n *\n * @remarks\n * - Values are normalized using {@link normalizeAsymmetric}.\n * - Only keys present in both `a` and `b` are processed.\n * - Keys present in one object but not the other are left untouched.\n * - The function operates recursively on nested objects.\n *\n * @example\n * ```ts\n * const objA = { foo: xExpect.any(String), bar: 42 };\n * const objB = { foo: \"hello\", bar: 42 };\n *\n * const [a, b] = normalizeObjects(objA, objB);\n * // a: { foo: \"hello\", bar: 42 }\n * // b: { foo: \"hello\", bar: 42 }\n * ```\n *\n * @since 1.0.0\n */\n\nexport function normalizeObjects(a: Record<string, unknown>, b: Record<string, unknown>): [ Record<string, unknown>, Record<string, unknown> ] {\n const aResult = { ...a };\n const bResult = { ...b };\n\n const keys = new Set([ ...Object.keys(a), ...Object.keys(b) ]);\n for (const key of keys) {\n if (key in a && key in b) {\n [ aResult[key], bResult[key] ] = normalizeAsymmetric(a[key], b[key]);\n }\n }\n\n return [ aResult, bResult ];\n}\n\n/**\n * Creates a colored, human-readable unified diff between two strings.\n *\n * @param a - The first string (original content) to compare\n * @param b - The second string (modified content) to compare\n * @param clean - Whether to apply semantic cleanup to diffs for improved readability\n * @returns A formatted string containing the unified diff representation\n *\n * @remarks\n * This function generates a git-style unified diff output with syntax highlighting\n * for easy readability. It processes the input strings as follows:\n *\n * 1. Splits both strings into lines\n * 2. Adds a unified diff header showing line counts\n * 3. For each line pair:\n * - Unchanged lines are shown dimmed with a leading space\n * - Changed lines are analyzed character by character\n * - Removed content is highlighted in green with a leading \"-\"\n * - Added content is highlighted in red with a leading \"+\"\n * - Changed portions within lines are additionally inverted for emphasis\n *\n * The result array is populated with formatted lines and then joined with newlines\n * to create the final string output.\n *\n * @example\n * ```ts\n * const original = \"line one\\nline two\\nline three\";\n * const modified = \"line one\\nmodified line\\nline three\";\n * const result = [];\n *\n * const diffOutput = diffStrings(original, modified, result);\n * console.log(diffOutput);\n * // Output will be a colored diff showing:\n * // @@ -1,3 +1,3 @@\n * // line one\n * // - line two\n * // + modified line\n * // line three\n * ```\n *\n * @see diffStringsRaw - The underlying function that generates the raw diff data\n * @see DiffTypes - Enum defining the types of diff operations\n *\n * @since 1.0.0\n */\n\nexport function normalizeAsymmetric(a: unknown, b: unknown, clean: boolean = true): [ unknown, unknown ] {\n if (a === b) return [ a, b ];\n\n const aType = typeof a;\n const bType = typeof b;\n const match = asymmetricMatch(a, b);\n if (match === true) {\n if (isAsymmetric(a)) a = b;\n if (isAsymmetric(b)) b = a;\n\n return [ a, b ];\n }\n\n if (aType === 'string' && bType === 'string') return normalizeStrings(<string> a, <string> b, clean);\n if (!a || !b || aType !== 'object' || bType !== 'object') {\n return [ a, b ];\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n return normalizeArrays(a, b);\n }\n\n return normalizeObjects(a as Record<string, unknown>, b as Record<string, unknown>);\n}\n\n/**\n * Creates a colored, human-readable unified diff between two strings.\n *\n * @param a - The first string (original content) to compare\n * @param b - The second string (modified content) to compare\n * @param result - Array that will be populated with formatted diff output lines\n * @param clean - Whether to apply semantic cleanup to diffs for improved readability\n * @returns A formatted string containing the unified diff representation\n *\n * @remarks\n * This function generates a git-style unified diff output with syntax highlighting\n * for easy readability. It processes the input strings as follows:\n *\n * 1. Splits both strings into lines\n * 2. Adds a unified diff header showing line counts\n * 3. For each line pair:\n * - Unchanged lines are shown dimmed with a leading space\n * - Changed lines are analyzed character by character\n * - Removed content is highlighted in green with a leading \"-\"\n * - Added content is highlighted in red with a leading \"+\"\n * - Changed portions within lines are additionally inverted for emphasis\n *\n * The result array is populated with formatted lines and then joined with newlines\n * to create the final string output.\n *\n * @example\n * ```ts\n * const original = \"line one\\nline two\\nline three\";\n * const modified = \"line one\\nmodified line\\nline three\";\n * const result = [];\n *\n * const diffOutput = diffStrings(original, modified, result);\n * console.log(diffOutput);\n * // Output will be a colored diff showing:\n * // @@ -1,3 +1,3 @@\n * // line one\n * // - line two\n * // + modified line\n * // line three\n * ```\n *\n * @see diffStringsRaw - The underlying function that generates the raw diff data\n * @see DiffTypes - Enum defining the types of diff operations\n *\n * @since 1.0.0\n */\n\nexport function diffStrings(a: string, b: string, result: Array<string>, clean: boolean = true): string {\n const aLines = a.split('\\n');\n const bLines = b.split('\\n');\n result.push(CYAN(`\\n@@ -1,${ aLines.length } +1,${ bLines.length } @@\\n`));\n\n const max = Math.max(aLines.length, bLines.length);\n for (let i = 0; i < max; i++) {\n const lineA = aLines[i];\n const lineB = bLines[i];\n\n if (lineA === lineB) {\n if (lineA) result.push(DIM(` ${ lineA }`));\n continue;\n }\n\n const expectedLine = [];\n const receivedLine = [];\n\n if (lineA !== undefined && lineB !== undefined) {\n let diffs = diffStringsRaw(lineA || '\\t', lineB || '\\t');\n if (clean) diffs = cleanupSemantic(diffs);\n\n for (const [ type, text ] of diffs) {\n if (type === DiffTypes.EQUAL) {\n expectedLine.push(text);\n receivedLine.push(text);\n } else if (type === DiffTypes.DELETE) {\n expectedLine.push(INVERSE(text));\n } else if (type === DiffTypes.INSERT) {\n receivedLine.push(INVERSE(text));\n }\n }\n }\n\n if (lineA === undefined) receivedLine.push(lineB);\n if (!lineB === undefined) expectedLine.push(lineA);\n\n if (expectedLine.length > 0) result.push(EXPECTED(`- ${ expectedLine.join('') }`));\n if (receivedLine.length > 0) result.push(RECEIVED(`+ ${ receivedLine.join('') }`));\n }\n\n return result.join('\\n');\n}\n\n/**\n * Produces a colorized diff between two argument lists, handling asymmetric values and trailing commas.\n *\n * @param a - The expected value or argument list.\n * @param b - The received value or argument list.\n * @returns An array of strings representing the colorized diff, with:\n * - Equal values dimmed using {@link DIM}.\n * - Inserted (extra) values highlighted using {@link RECEIVED}.\n * - Trailing commas preserved and appended after diff highlighting.\n *\n * @remarks\n * - Both `a` and `b` are normalized using {@link normalizeAsymmetric} to support asymmetric matchers.\n * - Values are serialized via {@link serialize}.\n * - Uses {@link diffLinesRaw} to compute differences.\n * - This function ensures that commas at the end of values are preserved but not highlighted.\n *\n * @example\n * ```ts\n * const expected = [1, 2];\n * const received = [1, 3];\n *\n * console.log(diffArgs(expected, received));\n * // Output (with ANSI colors):\n * // [\n * // '\\x1B[2m1\\x1B[22m,',\n * // '\\x1B[31m3\\x1B[39m'\n * // ]\n * ```\n *\n * @example\n * ```ts\n * // Works with trailing commas\n * const expected = [4, \"x\"];\n * const received = [4, \"y\"];\n *\n * console.log(diffArgs(expected, received));\n * // [\n * // '\\x1B[2m4\\x1B[22m,',\n * // '\\x1B[31m\"y\"\\x1B[39m'\n * // ]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function diffArgs(a: unknown, b: unknown): Array<string> {\n const result: Array<string> = [];\n\n [ a, b ] = normalizeAsymmetric(a, b, true);\n const aLines = serialize(a, '');\n const bLines = serialize(b, '');\n\n const diffs = diffLinesRaw(aLines, bLines);\n for (const [ type, line ] of diffs) {\n let value = line;\n let comma = '';\n\n if (value.endsWith(',')) {\n value = value.slice(0, -1);\n comma = ',';\n }\n\n if (type === DiffTypes.EQUAL) result.push(DIM(value) + comma);\n else if (type === DiffTypes.INSERT) result.push(RECEIVED(value) + comma);\n }\n\n return result;\n}\n\n/**\n * Creates a formatted, colored diff representation between any two JavaScript values.\n *\n * @param a - The expected value to compare\n * @param b - The received value to compare\n * @param clean - Whether to apply semantic cleanup to diffs for improved readability\n * @returns A formatted string containing the diff representation with colored highlighting\n *\n * @remarks\n * This versatile diff function can compare any JavaScript values, intelligently handling\n * different types of data:\n *\n * 1. It first identifies and displays the types of both values\n * 2. For string values, it generates a character-level diff with highlighted changes\n * 3. For all other values, it serializes them into string representations and creates a line-by-line diff\n *\n * The output is formatted similar to git's unified diff format with:\n * - A header showing expected and received types\n * - A unified diff header (`@@ -1,n +1,m @@`) showing line counts\n * - Line prefixes that indicate unchanged lines (dimmed with two spaces)\n * - Line prefixes that indicate removed lines (green with a \"-\" prefix)\n * - Line prefixes that indicate added lines (red with a \"+\" prefix)\n *\n * This function is particularly useful for test frameworks to visualize the differences\n * between expected and actual values in assertion failures.\n *\n * @example\n * ```ts\n * // Comparing two objects\n * const expected = { name: \"test\", value: 123 };\n * const received = { name: \"test\", value: 456 };\n *\n * console.log(diffComponent(expected, received));\n * // Output will include:\n * // Expected: Object\n * // Received: Object\n * // @@ -1,4 +1,4 @@\n * // Object {\n * // name: \"test\",\n * // - value: 123\n * // + value: 456\n * // }\n * ```\n *\n * @see diffStrings - Function used for string-to-string comparison\n * @see diffLinesRaw - Function used for line-by-line comparison of serialized values\n * @see getType - Function used to determine the types of input values\n * @see serialize - Function used to convert values to string representations\n *\n * @since 1.0.0\n */\n\nexport function diffComponent(a: unknown, b: unknown, clean: boolean = true): string {\n const aType = getType(a);\n const bType = getType(b);\n const result: Array<string> = [];\n\n if (aType !== bType) {\n result.push('Expected type: ' + EXPECTED(aType));\n result.push('Received type: ' + RECEIVED(bType));\n }\n\n if (aType === 'string' && bType === 'string') {\n return diffStrings(<string>a, <string>b, result, clean);\n }\n\n const [ aNormalize, bNormalize ] = normalizeAsymmetric(a, b, clean);\n const aLines = serialize(aNormalize);\n const bLines = serialize(bNormalize);\n result.push(CYAN(`\\n@@ -1,${ aLines.length } +1,${ bLines.length } @@\\n`));\n\n const diffs = diffLinesRaw(aLines, bLines);\n for (const [ type, line ] of diffs) {\n if (type === DiffTypes.EQUAL) result.push(DIM(` ${ line }`));\n else if (type === DiffTypes.DELETE) result.push(EXPECTED(`- ${ line }`));\n else if (type === DiffTypes.INSERT) result.push(RECEIVED(`+ ${ line }`));\n }\n\n return result.join('\\n');\n}\n", "/**\n * Base abstract error class for all xJet-specific errors\n *\n * Extends the native `Error` class with improved stack trace handling\n * and serialization capabilities for better error reporting.\n *\n * @remarks\n * This class serves as the foundation for all custom error types in the xJet framework.\n * It ensures consistent error behavior, proper prototype chain setup, and serialization\n * to support error logging and transmission across boundaries.\n *\n * @example\n * ```ts\n * // Extending the base error class\n * export class ValidationError extends xJetBaseError {\n * constructor(message: string) {\n * super(message);\n * this.name = 'ValidationError';\n * }\n * }\n * ```\n *\n * @since 1.0.0\n */\nimport { serializesError } from '@components/object.component';\n\nexport abstract class xJetBaseError extends Error {\n /**\n * Creates a new instance of the base error class.\n *\n * @param message - The error message describing the problem.\n * @param name - Optional name for the error class; defaults to `'xJetError'`.\n *\n * @remarks\n * This constructor ensures the correct prototype chain for proper `instanceof` checks.\n * It also captures the stack trace if supported by the runtime environment.\n *\n * @example\n * ```ts\n * class MyError extends xJetBaseError {}\n * throw new MyError('Something went wrong');\n * ```\n *\n * @since 1.0.0\n */\n\n protected constructor(message: string, name: string = 'xJetError') {\n super(message);\n\n // Ensure correct prototype chain (important for `instanceof`)\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Serializes the xJetError instance to a plain object suitable for JSON conversion.\n *\n * @returns A plain object containing all properties of the error instance\n *\n * @remarks\n * This method creates a serializable representation of the error by copying all own\n * enumerable properties to a new object. It also explicitly ensures that critical properties\n * like name, message, and stack are included in the result, even if they are non-enumerable\n * in the original error object.\n *\n * The resulting object can be used with JSON.stringify() to create a complete JSON\n * representation of the error, which is useful for logging, error reporting, and\n * transmitting error details across process boundaries.\n *\n * @example\n * ```ts\n * const error = new xJetError('Expected value to be truthy');\n * const serialized = error.toJSON();\n * const json = JSON.stringify(serialized);\n *\n * // Later, this can be used for error reporting\n * console.error(json);\n * ```\n *\n * @since 1.0.0\n */\n\n toJSON(): Record<string, unknown> {\n return serializesError(this);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ComposeStatementInterface } from '@components/interfaces/format-component.interface';\n\n/**\n * Imports\n */\n\nimport { DIM, EXPECTED, RECEIVED } from '@components/color.component';\n\n/**\n * Constructs a formatted Jest-style matcher statement string with optional ANSI coloring.\n *\n * Builds a string that resembles a Jest assertion call, e.g.:\n * `xExpect(received).toEqual(expected)` or `xExpect(received).rejects.toThrow()`,\n * with the ability to include multiple expected values and an optional trailing comment.\n *\n * @param options - Configuration options for composing the matcher statement.\n * Properties:\n * - `assertionChain`: Non-empty array of matcher methods (e.g., ['rejects', 'toThrow'])\n * - `expectedLabels`: Array of expected argument labels, defaults to empty array\n * - `receivedLabeled`: Label for the received value, defaults to 'received'\n * - `comment`: Optional trailing comment appended after the statement\n *\n * @returns The fully formatted matcher statement as a string, including ANSI coloring if enabled\n *\n * @throws Error - Throws if `assertionChain` is empty or not provided\n *\n * @remarks\n * This function helps create consistent, colored assertion strings for testing frameworks\n * that support Jest-like matchers. It supports chaining matcher names and multiple expected arguments,\n * as well as adding inline comments for additional context.\n *\n * @example\n * ```ts\n * composeStatement({\n * receivedLabeled: 'received',\n * assertionChain: ['rejects', 'toThrow'],\n * expectedLabels: [],\n * comment: 'should throw an error'\n * });\n * // Returns: xExpect(received).rejects.toThrow() // should throw an error (with ANSI colors)\n *\n * composeStatement({\n * assertionChain: ['toEqual'],\n * expectedLabels: ['expectedValue']\n * });\n * // Returns: xExpect(received).toEqual(expectedValue) (with ANSI colors)\n * ```\n *\n * @default options.expectedLabels - []\n * @default options.receivedLabeled - 'received'\n *\n * @see ComposeStatementInterface - Interface for the `options` parameter\n *\n * @since 1.0.0\n */\n\nexport function composeStatement(options: ComposeStatementInterface): string {\n const { comment, assertionChain, expectedLabels = [], receivedLabeled = 'received' } = options;\n\n if (!assertionChain.length)\n throw new Error('Expected non-empty matcher chain (e.g., [\"toEqual\"]). Received an empty array.');\n\n const parts = [\n DIM('expect('),\n RECEIVED(receivedLabeled),\n DIM(')'),\n '.',\n assertionChain.join('.')\n ];\n\n if (expectedLabels.length > 0) {\n parts.push('(');\n parts.push(\n expectedLabels.map(value => EXPECTED(value)).join(', ')\n );\n parts.push(')');\n } else {\n parts.push('()');\n }\n\n if (comment) {\n parts.push(DIM(' // ' + comment));\n }\n\n return parts.join('');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { OptionsTypeErrorInterface } from '@errors/interfaces/type-error.interface';\n\n/**\n * Imports\n */\n\nimport { xJetBaseError } from '@errors/base.error';\nimport { serialize } from '@components/serialize.component';\nimport { composeStatement } from '@components/format.component';\nimport { EXPECTED, RECEIVED } from '@components/color.component';\n\n/**\n * Error class for type mismatches and validation failures.\n *\n * @remarks\n * This specialized error provides detailed information about type mismatches,\n * including the expected and received values with their types.\n * The formatted message includes:\n * - A hint chain showing the context where the error occurred\n * - A specific error message describing the issue\n * - Type and value information for both expected and received values when available\n *\n * Color highlighting (via EXPECTED and RECEIVED) is applied to make the\n * differences stand out in terminal output.\n *\n * @see xJetBaseError\n * @see OptionsTypeErrorInterface\n *\n * @since 1.0.0\n */\n\nexport class xJetTypeError extends xJetBaseError {\n\n /**\n * Creates a new type error with formatted message showing the mismatch details.\n *\n * @param options - Configuration object containing error details.\n *\n * @remarks\n * This constructor builds a multi-line error message that clearly shows:\n * - The property path where the error occurred (via assertionChain)\n * - The specific error message\n * - Type and serialized value of the expected value (if provided)\n * - Type and serialized value of the received value (if provided)\n *\n * @see OptionsTypeErrorInterface\n *\n * @since 1.0.0\n */\n\n constructor(options: OptionsTypeErrorInterface) {\n const lines = [\n `${ composeStatement(options) }\\n`,\n `Matcher error: ${ options.message }\\n`\n ];\n\n if (options.expected) {\n if(options.expected.type) lines.push(`Expected has type: ${ options.expected.type }`);\n lines.push(`Expected has value: ${\n EXPECTED(serialize(options.expected.value).join('\\n'))\n }`);\n }\n\n if (options.received) {\n if(options.received.type) lines.push(`Received has type: ${ options.received.type }`);\n lines.push(`Received has value: ${\n RECEIVED(serialize(options.received.value).join('\\n'))\n }`);\n }\n\n super(lines.join('\\n'), 'xJetTypeError');\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { AssertionResultInterface, OptionsExpectErrorInterface } from '@errors/interfaces/expect-error.interface';\n\n/**\n * Imports\n */\n\nimport { xJetBaseError } from '@errors/base.error';\nimport { composeStatement } from '@components/format.component';\n\n/**\n * Error class representing an expectation failure in xJet framework.\n *\n * @remarks\n * This error encapsulates details from matcher evaluation results,\n * including pass/fail status and error messages.\n *\n * The error message is composed of the formatted assertion statement and optional info lines.\n *\n * @since 1.0.0\n */\n\nexport class xJetExpectError extends xJetBaseError {\n /**\n * The result of the matcher function evaluation.\n *\n * @remarks\n * This optional property stores the result returned from a matcher function\n * when executed against the actual value. The result object contains important\n * information about the assertion outcome, including whether it passed or failed,\n * and custom error messages.\n *\n * When a matcher is executed, it returns an object conforming to the AssertionResultInterface,\n * which typically includes:\n * - pass: A boolean indicating if the assertion passed\n * - message: A function or string representing the formatted error message\n * - expected: The expected value for comparison\n * - received: The actual value received\n *\n * This property may be undefined when the error is generated before a matcher\n * function is executed, such as when an invalid promise is provided.\n *\n * @see AssertionResultInterface\n *\n * @since 1.0.0\n */\n\n matcherResult?: AssertionResultInterface;\n\n /**\n * Creates a new xJetExpectError instance.\n *\n * @param options - Options containing assertion details and optional info lines.\n *\n * @see OptionsExpectErrorInterface\n *\n * @since 1.0.0\n */\n\n constructor(options: OptionsExpectErrorInterface) {\n const lines = [ `${ composeStatement(options) }\\n` ];\n if (options.info) lines.push(...options.info);\n\n super(lines.join('\\n'), 'xJetExpectError');\n if (options.assertion) {\n this.matcherResult = options.assertion;\n this.matcherResult.message = this.message;\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { AssertionResultInterface } from '@errors/interfaces/expect-error.interface';\nimport type { HandleDiffFailureInterface, HandleFailureInterface } from './interfaces/matchers-handler.interface';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { xJetExpectError } from '@errors/expect.error';\nimport { diffComponent, getType } from '@diff/diff.module';\nimport { serialize } from '@components/serialize.component';\nimport { DIM, EXPECTED, RECEIVED } from '@components/color.component';\n\n/**\n * Ensures that a given value matches one of the specified types.\n *\n * Throws an ` xJetTypeError ` if the value's type does not match any of the allowed types.\n *\n * @param value - The value to check.\n * @param types - An array of allowed type names as strings.\n * @param label - Specifies whether the value is 'Expected' or 'Received' (used in an error message).\n * @param expectedLabels - Array of expected argument labels\n *\n * @throws xJetTypeError - When the value's type is not included in `types`.\n *\n * @example\n * ```ts\n * // Inside a MatcherService context\n * this.ensureType(42, ['number', 'bigint'], 'Received'); // Passes\n * this.ensureType('hello', ['number'], 'Expected'); // Throws xJetTypeError\n * ```\n *\n * @since 1.0.0\n */\n\nexport function ensureType(this: MatcherService, value: unknown, types: Array<string>, label: string, expectedLabels: Array<string> = []): void {\n const type = getType(value);\n if (!types.includes(type) && !types.includes(typeof value)) {\n throw new xJetTypeError({\n expectedLabels,\n assertionChain: this.assertionChain,\n message: `${ (label === 'Received' ? RECEIVED : EXPECTED)(label) } value must be a ${ types.join(' or ') }`,\n [label === 'Expected' ? 'expected' : 'received']: { value, type }\n });\n }\n}\n\n/**\n * Ensures that a given value is neither `null` nor `undefined`.\n *\n * Throws an ` xJetTypeError ` if the value is `null` or `undefined`.\n *\n * @param value - The value to check.\n * @param label - Specifies whether the value is 'Expected' or 'Received' (used in an error message).\n * @param expectedLabels - Array of expected argument labels\n *\n * @throws xJetTypeError - When the value is `null` or `undefined`.\n *\n * @example\n * ```ts\n * // Inside a MatcherService context\n * this.ensureNotNullish(0, 'Received'); // Passes\n * this.ensureNotNullish(null, 'Expected'); // Throws xJetTypeError\n * this.ensureNotNullish(undefined, 'Received'); // Throws xJetTypeError\n * ```\n *\n * @since 1.0.0\n */\n\nexport function ensureNotNullish(this: MatcherService, value: unknown, label: 'Expected' | 'Received', expectedLabels: Array<string> = []): void {\n if (value === null || value === undefined) {\n throw new xJetTypeError({\n expectedLabels,\n assertionChain: this.assertionChain,\n message: `${ (label === 'Received' ? RECEIVED : EXPECTED)(label) } value must not be null nor undefined`,\n [label === 'Expected' ? 'expected' : 'received']: { value }\n });\n }\n}\n\n/**\n * Serializes a value into a single-line human-readable string representation.\n *\n * @param value - The value to serialize.\n * @returns A single-line string representation of the serialized value.\n *\n * @example\n * ```ts\n * serializeOneLine({ a: 1, b: [2, 3] });\n * // Returns: \"Object { a: 1, b: Array [ 2, 3 ] }\"\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeOneLine(value: unknown): string {\n return serialize(value, '').join(' ');\n}\n\n/**\n * Handles matcher failures by evaluating pass/fail status and throwing an error if needed.\n *\n * @param options - Configuration options describing the failure details.\n *\n * @remarks\n * Determines whether to throw an error based on the pass status and the current \"not\" modifier.\n * Calls optional handlers `handleNot` or `handleInfo` to populate additional info messages.\n * Throws a formatted xJetExpectError with composed assertion details and info.\n *\n * The function is intended to be called with `this` bound to an instance of `MatcherService`.\n *\n * @throws xJetExpectError - When the assertion fails, according to the logic.\n *\n * @since 1.0.0\n */\n\nexport function handleFailure(this: MatcherService, options: HandleFailureInterface): void {\n const { pass } = options;\n const shouldThrow = (pass && this.notModifier) || (!pass && !this.notModifier);\n if (!shouldThrow) return;\n\n const info: Array<string> = [];\n const assertion: AssertionResultInterface = {\n pass,\n name: this.macherName,\n received: this.received,\n expected: options.expected\n };\n\n if (this.notModifier) {\n options.handleNot?.call(this, info);\n } else {\n options.handleInfo?.call(this, info);\n }\n\n throw new xJetExpectError({\n info,\n assertion,\n ...options,\n assertionChain: this.assertionChain\n });\n}\n\n/**\n * Handles matcher failures involving detailed diff information.\n *\n * @param options - Configuration options describing the failure with diff details.\n *\n * @remarks\n * Calls `handleFailure` with custom `handleNot` and `handleInfo` handlers:\n * - `handleNot` adds an inverted expectation message.\n * - `handleInfo` adds a note (if present) and a formatted diff between expected and received values.\n *\n * The function is intended to be called with `this` bound to an instance of `MatcherService`.\n *\n * @since 1.0.0\n */\n\nexport function handleDiffFailure(this: MatcherService, options: HandleDiffFailureInterface): void {\n handleFailure.call(this, {\n ...options,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: not ${ EXPECTED(serializeOneLine(this.received)) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>) {\n if (options.note) info.push(DIM(options.note), '');\n info.push(diffComponent(options.expected, this.received, true));\n }\n });\n}\n\n/**\n * Handles matcher failures involving simple comparisons with an operator.\n *\n * @param options - Configuration options describing the failure.\n * @param operator - The operator string used in the comparison (e.g., '===', '!==').\n *\n * @remarks\n * Calls `handleFailure` with custom `handleNot` and `handleInfo` handlers that\n * format expected and received values with the given operator, including alignment.\n *\n * The function is intended to be called with `this` bound to an instance of `MatcherService`.\n *\n * @since 1.0.0\n */\n\nexport function handleComparisonFailure(this: MatcherService, options: HandleFailureInterface, operator: string): void {\n const space = ' '.repeat(operator.length);\n\n handleFailure.call(this, {\n ...options,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: not ${ operator } ${ EXPECTED(serializeOneLine(options.expected)) }`);\n info.push(`Received: ${ space } ${ RECEIVED(serializeOneLine(this.received)) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: ${ operator } ${ EXPECTED(serializeOneLine(options.expected)) }`);\n info.push(`Received: ${ space } ${ RECEIVED(serializeOneLine(this.received)) }`);\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { AbstractPattern } from '@patterns/abstract.pattern';\nimport type { ConstructorLikeType } from '@interfaces/functions.interface';\nimport type { ThrownType, ThrownValueType } from '@matchers/interfaces/functions-matcher.interface';\nimport type { HandleInfoType, HandleNotType } from '@handlers/interfaces/matchers-handler.interface';\n\n/**\n * Imports\n */\n\nimport { diffComponent } from '@diff/components/diff.component';\nimport { serializeError } from '@components/serialize.component';\nimport { equals, isAsymmetric } from '@components/object.component';\nimport { EXPECTED, INVERSE, RECEIVED } from '@components/color.component';\nimport { ensureType, handleFailure, serializeOneLine } from '@handlers/matchers.handler';\n\n/**\n * Converts any thrown value into a {@link ThrownType}, normalizing Errors and non-Error values.\n *\n * @param err - The value that was thrown.\n *\n * @returns A {@link ThrownType} containing the value, type information, and message.\n *\n * @remarks\n * Ensures consistent handling of thrown values in matcher assertions.\n * Distinguishes between actual Error instances and arbitrary thrown objects/values.\n *\n * @example\n * ```ts\n * const thrown = getThrown(new Error('Oops'));\n * console.log(thrown.message); // \"Oops\"\n * console.log(thrown.isError); // true\n * ```\n *\n * @see ThrownType\n *\n * @since 1.0.0\n */\n\nexport function getThrown(err: unknown): ThrownType {\n const e = err as Record<string, unknown>;\n const hasMessage = e != null && typeof e.message === 'string';\n const isError = hasMessage && typeof e.name === 'string' && typeof e.stack === 'string';\n\n return {\n isError,\n value: err,\n message: hasMessage ? String(e.message) : String(err),\n hasMessage: isError ? true : hasMessage,\n serializedError: serializeError(err)\n } as ThrownType;\n}\n\n/**\n * Builds handler functions for reporting matcher failures.\n *\n * @param expectedLabel - The label describing the expected value (e.g., 'constructor', 'substring').\n * @param expectedValue - The expected value representation (stringifies if necessary).\n * @param thrown - The thrown value or null.\n * @param asymmetric - Optional flag for asymmetric matchers.\n *\n * @returns A tuple `[handleNot, handleInfo]` for failure reporting.\n *\n * @see HandleNotType\n * @see HandleInfoType\n *\n * @since 1.0.0\n */\n\nfunction buildInfo(expectedLabel: string, expectedValue: string, thrown: ThrownType | null, asymmetric = false): [ HandleNotType, HandleInfoType ] {\n const handleNot = (info: Array<string>): void => {\n info.push(`Expected ${ expectedLabel }: not ${ EXPECTED(expectedValue) }`);\n if (thrown?.hasMessage) {\n info.push(`Received message: ${ RECEIVED(serializeOneLine(asymmetric ? thrown.message : INVERSE(thrown.message))) }\\n`);\n } else {\n info.push(`Received value: ${ RECEIVED(serializeOneLine(thrown?.value)) }`);\n }\n };\n\n const handleInfo = (info: Array<string>): void => {\n info.push(`Expected ${ expectedLabel }: ${ EXPECTED(expectedValue) }`);\n if (thrown?.hasMessage) {\n if (asymmetric) {\n info.push(`Received name: ${ RECEIVED(serializeOneLine((thrown.value as Error)?.name)) }`);\n }\n info.push(`Received message: ${ RECEIVED(serializeOneLine(thrown.message)) }\\n`);\n } else {\n info.push(`Received value: ${ RECEIVED(serializeOneLine(thrown?.value)) }`);\n }\n };\n\n return [ handleNot, handleInfo ] as const;\n}\n\n/**\n * Checks whether a thrown value matches an expected constructor.\n *\n * @param expected - The expected error constructor.\n * @param thrown - The thrown value or null.\n *\n * @returns A {@link ThrownValueType} tuple: `[pass, handleNot, handleInfo]`.\n *\n * @see ThrownValueType\n * @since 1.0.0\n */\n\nexport function toThrowExpectedClass(this: MatcherService, expected: ConstructorLikeType, thrown: ThrownType | null): ThrownValueType {\n const pass = thrown != null && thrown.value instanceof expected;\n const [ handleNot, handleInfo ] = buildInfo('constructor', expected.name, thrown);\n\n return [ pass, handleNot, handleInfo ];\n}\n\n/**\n * Checks whether a thrown error message contains an expected string.\n *\n * @param expected - The expected substring.\n * @param thrown - The thrown value or null.\n *\n * @returns A {@link ThrownValueType} tuple: `[pass, handleNot, handleInfo]`.\n *\n * @see ThrownValueType\n * @since 1.0.0\n */\n\nexport function toThrowExpectedString(this: MatcherService, expected: string, thrown: ThrownType | null): ThrownValueType {\n const pass = thrown != null && thrown.message.includes(expected);\n const [ handleNot, handleInfo ] = buildInfo('substring', `\"${ expected }\"`, thrown);\n\n return [ pass, handleNot, handleInfo ];\n}\n\n/**\n * Checks whether a thrown error message matches an expected RegExp.\n *\n * @param expected - The expected pattern.\n * @param thrown - The thrown value or null.\n *\n * @returns A {@link ThrownValueType} tuple: `[pass, handleNot, handleInfo]`.\n *\n * @see ThrownValueType\n * @since 1.0.0\n */\n\nexport function toThrowExpectedRegExp(this: MatcherService, expected: RegExp, thrown: ThrownType | null): ThrownValueType {\n const pass = thrown != null && expected.test(thrown.message);\n const [ handleNot, handleInfo ] = buildInfo('pattern', serializeOneLine(expected), thrown);\n\n return [ pass, handleNot, handleInfo ];\n}\n\n/**\n * Checks whether a thrown value matches an asymmetric matcher pattern.\n *\n * @param expected - The asymmetric pattern matcher.\n * @param thrown - The thrown value or null.\n *\n * @returns A {@link ThrownValueType} tuple: `[pass, handleNot, handleInfo]`.\n *\n * @see ThrownValueType\n * @since 1.0.0\n */\n\nexport function toThrowExpectedAsymmetric(this: MatcherService, expected: AbstractPattern, thrown: ThrownType | null): ThrownValueType {\n const pass = thrown != null && expected.matches(thrown.value);\n const [ handleNot, handleInfo ] = buildInfo('asymmetric', serializeOneLine(expected), thrown, true);\n\n return [ pass, handleNot, handleInfo ];\n}\n\n/**\n * Checks whether a thrown value matches an expected object.\n *\n * @param expected - The expected object.\n * @param thrown - The thrown value or null.\n *\n * @returns A {@link ThrownValueType} tuple: `[pass, handleNot, handleInfo]`.\n *\n * @see ThrownValueType\n * @since 1.0.0\n */\n\nexport function toThrowExpectedObject(this: MatcherService, expected: object, thrown: ThrownType): ThrownValueType {\n const pass = thrown != null && equals(serializeError(expected), thrown.serializedError);\n\n const handleNot = (info: Array<string>): void => {\n info.push(`Expected: not ${ EXPECTED(serializeOneLine(thrown.serializedError)) }`);\n };\n\n const handleInfo = (info: Array<string>): void => {\n info.push(diffComponent(expected, thrown.serializedError, true));\n };\n\n return [ pass, handleNot, handleInfo ];\n}\n\n\n/**\n * Asserts that a function or promise throws a value that matches the expected criteria.\n *\n * @param expected - Optional expectation: constructor, string, RegExp, object, or asymmetric pattern.\n *\n * @throws xJetTypeError - If `this.received` is not a function when expected, or if the expected type is invalid.\n *\n * @remarks\n * Supports multiple forms of expectation:\n * - Constructor: function must throw instance of that class.\n * - String: function must throw with message-containing substring.\n * - RegExp: function must throw with a message matching pattern.\n * - Object: function must throw an object equal to expected.\n * - Asymmetric: function must throw a value matching a custom pattern.\n *\n * Updates `this.received` with a serialized thrown value.\n * Delegates failure reporting to {@link handleFailure}.\n *\n * @example\n * ```ts\n * xExpect(() => { throw new Error('Oops'); }).toThrow('Oops');\n * xExpect(() => { throw new TypeError(); }).toThrow(TypeError);\n * xExpect(() => { throw { code: 123 }; }).toThrow({ code: 123 });\n * xExpect(() => { throw new Error('fail'); }).not.toThrow('pass');\n * ```\n *\n * @see MatcherService\n * @see ConstructorLikeType\n *\n * @since 1.0.0\n */\n\nexport function toThrow(this: MatcherService, expected?: RegExp | string | ConstructorLikeType | object): void {\n let thrown: ThrownType | null = null;\n const expectedLabels = expected ? [ 'expected' ] : [];\n\n if (this.rejectsModifier) {\n thrown = getThrown(this.received);\n } else if (typeof this.received === 'function') {\n try {\n this.received();\n } catch (error) {\n thrown = getThrown(error);\n }\n } else {\n ensureType.call(this, this.received, [ 'function' ], 'Received', expectedLabels);\n }\n\n let pass = false;\n let handleNot: HandleNotType;\n let handleInfo: HandleInfoType;\n\n if (!expected) {\n pass = thrown != null;\n handleNot = (info: Array<string>): void => {\n if (thrown?.hasMessage) {\n info.push(`Error name: ${ RECEIVED((thrown.value as Error)?.name) }`);\n info.push(`Error message: ${ RECEIVED(serializeOneLine(thrown.message)) }\\n`);\n } else {\n info.push(`Error value: ${ RECEIVED(serializeOneLine(thrown?.value)) }`);\n }\n };\n } else if (typeof expected === 'function') {\n [ pass, handleNot, handleInfo ] = toThrowExpectedClass.call(this, <ConstructorLikeType> expected, thrown);\n } else if (typeof expected === 'string') {\n [ pass, handleNot, handleInfo ] = toThrowExpectedString.call(this, expected, thrown);\n } else if (expected instanceof RegExp) {\n [ pass, handleNot, handleInfo ] = toThrowExpectedRegExp.call(this, expected, thrown);\n } else if (isAsymmetric(expected)) {\n [ pass, handleNot, handleInfo ] = toThrowExpectedAsymmetric.call(this, expected, thrown);\n } else if (thrown !== null && typeof expected === 'object') {\n [ pass, handleNot, handleInfo ] = toThrowExpectedObject.call(this, expected, thrown);\n } else {\n ensureType.call(this, expected, [ 'string', 'function', 'RegExp', 'object' ], 'Expected', expectedLabels);\n }\n\n handleFailure.call(Object.assign({}, this, { received: thrown?.serializedError }), {\n pass,\n expected,\n expectedLabels,\n handleNot(this: MatcherService, info: Array<string>) {\n handleNot?.call(this, info);\n },\n handleInfo(this: MatcherService, info: Array<string>) {\n if (!thrown) {\n info.push(`${ RECEIVED('Received') } function did not throw`);\n } else {\n handleInfo?.call(this, info);\n }\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { EXPECTED, RECEIVED } from '@components/color.component';\nimport { diffComponent, getType } from '@diff/components/diff.component';\nimport { ensureType, handleFailure, serializeOneLine } from '@handlers/matchers.handler';\n\n/**\n * Asserts that a received string has the specified length.\n *\n * @param length - The expected length of the string.\n *\n * @remarks\n * - Works with both `number` and `bigint` for the expected length.\n * - Throws an `xJetTypeError` if the received value does not have a numeric `length` property.\n *\n * @example\n * ```ts\n * xExpect(\"abc\").toHaveLength(3); // Passes\n * xExpect(\"abc\").toHaveLength(5); // Fails\n * xExpect(\"abc\").not.toHaveLength(2); // Passes\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveLength(this: MatcherService<string>, length: number | bigint): void {\n const expectedLabels = [ 'length' ];\n ensureType.call(this, length, [ 'number', 'bigint' ], 'Expected', expectedLabels);\n\n if(!Object.hasOwn(<object> <unknown> this.received, 'length') || !Number.isSafeInteger(this.received.length)) {\n throw new xJetTypeError({\n expectedLabels,\n message: `${ RECEIVED('received') } value must have a length property whose value must be a number`,\n received: { value: this.received, type: getType(this.received) },\n assertionChain: this.assertionChain\n });\n }\n\n const received = this.received;\n const pass = received.length == length;\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected length: not ${ EXPECTED(serializeOneLine(length)) }`);\n info.push(`Received string: ${ RECEIVED(serializeOneLine(received)) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`Expected length: ${ EXPECTED(serializeOneLine(length)) }`);\n info.push(`Received length: ${ RECEIVED(serializeOneLine(received.length)) }`);\n info.push(`Received string: ${ RECEIVED(serializeOneLine(received)) }`);\n }\n });\n}\n\n/**\n * Asserts that a received string matches a given substring or regular expression.\n *\n * @param expected - A string to search for, or a `RegExp` pattern to match against.\n *\n * @remarks\n * - Accepts both `string` and `RegExp` as the expected value.\n * - For `string` matching, it checks if the substring exists within the received value.\n * - For `RegExp` matching, it uses `RegExp.test()` to verify the pattern.\n *\n * @example\n * ```ts\n * xExpect(\"Hello World\").toMatch(\"World\"); // Passes\n * xExpect(\"Hello World\").toMatch(/world/i); // Passes (case-insensitive)\n * xExpect(\"Hello World\").not.toMatch(\"Earth\"); // Passes\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toMatch(this: MatcherService<string>, expected: RegExp | string): void {\n const expectedLabels = [ 'expected' ];\n ensureType.call(this, this.received, [ 'string' ], 'Received', expectedLabels);\n ensureType.call(this, expected, [ 'string', 'RegExp' ], 'Expected', expectedLabels);\n\n const received = this.received;\n const pass = typeof expected === 'string'\n ? received.includes(expected)\n : new RegExp(expected).test(received);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: not ${ EXPECTED(serializeOneLine(received)) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n if(expected instanceof RegExp) {\n info.push(`Expected pattern: ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received string: ${ RECEIVED(serializeOneLine(received)) }`);\n } else {\n info.push(diffComponent(expected, received, true));\n }\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { NumberOperatorType, NumericType } from '@matchers/interfaces/number-matcher.interface';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { getType } from '@diff/components/diff.component';\nimport { EXPECTED, RECEIVED } from '@components/color.component';\nimport { ensureType, handleComparisonFailure } from '@handlers/matchers.handler';\n\n/**\n * Ensures that the provided value is a positive number or bigint.\n *\n * @param value - The value to validate.\n * @param label - Label describing the value (e.g., `'Received'` or `'Expected'`).\n * @param expectedLabels - Optional list of expected value descriptions for error reporting.\n *\n * @throws xJetTypeError - Thrown if the value is not a number or bigint, or if it is less than zero.\n *\n * @remarks\n * This method first validates that the type of `value` is `number` or `bigint`\n * via {@link ensureType}, then asserts that the numeric value is greater than or equal to zero.\n * If the validation fails, an {@link xJetTypeError} is thrown with contextual details.\n *\n * @see ensureType\n * @see xJetTypeError\n *\n * @since 1.0.0\n */\n\nexport function ensurePositiveNumber(this: MatcherService, value: unknown, label: string, expectedLabels: Array<string> = []): void {\n ensureType.call(this, value, [ 'number', 'bigint' ], label, expectedLabels);\n\n if (<number> value < 0) {\n throw new xJetTypeError({\n expectedLabels,\n assertionChain: this.assertionChain,\n message: `${ (label === 'Received' ? RECEIVED : EXPECTED)(label) } value must be positive number`,\n [label === 'Received' ? 'received' : 'expected']: { value, type: getType(value) }\n });\n }\n}\n\n/**\n * Performs a numeric comparison between the received and expected values, then delegates failure handling.\n *\n * @param expected - The expected numeric value.\n * @param operator - The comparison operator (`'>'`, `'>='`, `'<'`, `'<='`).\n * @param matcherName - The name of the matcher invoking this comparison.\n *\n * @remarks\n * This is the core comparison logic shared by `toBeGreaterThan`, `toBeGreaterThanOrEqual`,\n * `toBeLessThan`, and `toBeLessThanOrEqual`.\n *\n * @example\n * ```ts\n * handleNumericComparison.call({ received: 5, notModifier: false }, 3, '>', 'toBeGreaterThan');\n * // Passes silently\n * ```\n *\n * @example\n * ```ts\n * handleNumericComparison.call({ received: 2, notModifier: false }, 5, '>', 'toBeGreaterThan');\n * // Throws a comparison failure\n * ```\n *\n * @see toBeLessThan\n * @see toBeGreaterThan\n *\n * @since 1.0.0\n */\n\nexport function handleNumericComparison(\n this: MatcherService<NumericType>, expected: NumericType, operator: NumberOperatorType\n): void {\n const received = this.received;\n const expectedLabels = [ 'Expected' ];\n ensureType.call(this, expected, [ 'number', 'bigint' ], 'Expected', expectedLabels);\n ensureType.call(this, received, [ 'number', 'bigint' ], 'Received', expectedLabels);\n\n let pass: boolean;\n switch (operator) {\n case '>':\n pass = received > expected;\n break;\n case '>=':\n pass = received >= expected;\n break;\n case '<':\n pass = received < expected;\n break;\n case '<=':\n pass = received <= expected;\n break;\n default:\n pass = false;\n }\n\n handleComparisonFailure.call(this, { pass, expectedLabels, expected }, operator);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { NumericType } from '@matchers/interfaces/number-matcher.interface';\n\n/**\n * Imports\n */\n\nimport { EXPECTED, RECEIVED } from '@components/color.component';\nimport { handleNumericComparison } from '@handlers/number.handler';\nimport { ensureType, handleFailure, serializeOneLine } from '@handlers/matchers.handler';\n\n/**\n * Asserts that the received number is close to the expected number within a given decimal prevision.\n *\n * @param expected - The target number.\n * @param precision - The number of decimal places to check. Defaults to `2`.\n *\n * @remarks\n * Uses an absolute difference check with a tolerance of `10^(-precision) / 2`.\n * Works with both positive and negative numbers.\n *\n * @example\n * ```ts\n * xExpect(0.2 + 0.1).toBeCloseTo(0.3, 2); // Passes\n * ```\n *\n * @example\n * ```ts\n * xExpect(0.2 + 0.1).not.toBeCloseTo(0.3, 5); // Fails\n * ```\n *\n * @see handleFailure\n * @see throwIfNotNumber\n *\n * @since 1.0.0\n */\n\nexport function toBeCloseTo(this: MatcherService<number>, expected: number, precision: number = 2): void {\n const expectedLabels = [ 'expected', 'precision' ];\n ensureType.call(this, expected, [ 'number' ], 'Expected', expectedLabels);\n ensureType.call(this, this.received, [ 'number' ], 'Received', expectedLabels);\n\n const actual = this.received;\n const receivedDifference = Math.abs(expected - actual);\n const expectedDifference = Math.pow(10, -precision) / 2;\n const expectedDifferenceStr = (precision < 20) ? expectedDifference.toFixed(precision + 1) : expectedDifference.toString();\n\n const not = this.notModifier ? ' ' : ' ';\n const notLabel = this.notModifier ? 'not < ' : '< ';\n const pass = receivedDifference < expectedDifference;\n\n const details = [\n `Expected precision: ${ not }${ EXPECTED(precision.toString()) }`,\n `Expected difference: ${ notLabel }${ EXPECTED(expectedDifferenceStr) }`,\n `Received difference: ${ not }${ RECEIVED(receivedDifference.toString()) }`\n ];\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n handleNot(info) {\n info.push(`Expected: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received: ${ RECEIVED(serializeOneLine(actual)) }\\n`);\n info.push(...details);\n },\n handleInfo(info) {\n info.push(`Expected: ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received: ${ RECEIVED(serializeOneLine(actual)) }\\n`);\n info.push(...details);\n }\n });\n}\n\n/**\n * Asserts that the received value is greater than the expected value.\n *\n * @param expected - The value to compare against.\n *\n * @example\n * ```ts\n * xExpect(10).toBeGreaterThan(5); // Passes\n * ```\n *\n * @example\n * ```ts\n * xExpect(5).toBeGreaterThan(10); // Fails\n * ```\n *\n * @see handleNumericComparison\n * @since 1.0.0\n */\n\nexport function toBeGreaterThan(this: MatcherService<NumericType>, expected: NumericType): void {\n handleNumericComparison.call(this, expected, '>');\n}\n\n/**\n * Asserts that the received value is greater than or equal to the expected value.\n *\n * @param expected - The value to compare against.\n *\n * @example\n * ```ts\n * xExpect(5).toBeGreaterThanOrEqual(5); // Passes\n * ```\n *\n * @example\n * ```ts\n * xExpect(4).toBeGreaterThanOrEqual(5); // Fails\n * ```\n *\n * @see handleNumericComparison\n * @since 1.0.0\n */\n\nexport function toBeGreaterThanOrEqual(this: MatcherService<NumericType>, expected: NumericType): void {\n handleNumericComparison.call(this, expected, '>=');\n}\n\n/**\n * Asserts that the received value is less than the expected value.\n *\n * @param expected - The value to compare against.\n *\n * @example\n * ```ts\n * xExpect(3).toBeLessThan(5); // Passes\n * ```\n *\n * @example\n * ```ts\n * xExpect(6).toBeLessThan(5); // Fails\n * ```\n *\n * @see handleNumericComparison\n *\n * @since 1.0.0\n */\n\nexport function toBeLessThan(this: MatcherService<NumericType>, expected: NumericType): void {\n handleNumericComparison.call(this, expected, '<');\n}\n\n/**\n * Asserts that the received value is less than or equal to the expected value.\n *\n * @param expected - The value to compare against.\n *\n * @example\n * ```ts\n * xExpect(5).toBeLessThanOrEqual(5); // Passes\n * ```\n *\n * @example\n * ```ts\n * xExpect(7).toBeLessThanOrEqual(5); // Fails\n * ```\n *\n * @see handleNumericComparison\n * @since 1.0.0\n */\n\nexport function toBeLessThanOrEqual(this: MatcherService<NumericType>, expected: NumericType): void {\n handleNumericComparison.call(this, expected, '<=');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { MockStateInterface } from '@matchers/interfaces/mock-matcher.interface';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { diffArgs } from '@diff/components/diff.component';\nimport { serialize } from '@components/serialize.component';\nimport { EXPECTED, RECEIVED } from '@components/color.component';\n\n/**\n * Ensures that the received value is an `xJet` mock or spy function.\n *\n * This function is intended to be used within matcher implementations to\n * assert that a value under test is a mock created by the `xJet` mocking system.\n *\n * @param expectedLabels - Optional labels describing the expected value,\n * used in error messages for improved clarity.\n *\n * @throws {@link xJetTypeError}\n * Thrown when the received value is not recognized as an `xJet` mock or spy function.\n *\n * @remarks\n * Validates that the `this.received` object contains both the `xJetMock` flag\n * and a valid `mock` state. If either condition is not met, an `xJetTypeError`\n * is thrown with an appropriate failure message.\n *\n * @since 1.0.0\n */\n\nexport function ensureMock(this: MatcherService<MockStateInterface>, expectedLabels: Array<string> = []): void {\n if (!this.received?.xJetMock || !this.received?.mock) {\n throw new xJetTypeError({\n expectedLabels,\n assertionChain: this.assertionChain,\n message: `${ RECEIVED('Received') } value must be a mock or spy function`,\n received: { value: this.received }\n });\n }\n}\n\n/**\n * Serializes an array of call arguments into a single formatted string.\n *\n * Each argument is serialized, trimmed of enclosing brackets, and highlighted using {@link EXPECTED}.\n * Commas inside individual arguments are removed to avoid conflicts with the joining commas.\n *\n * @param args - The array of arguments to serialize.\n * @returns A string with all arguments serialized and comma-separated.\n *\n * @remarks\n * - Removes any commas inside individual arguments to prevent confusion when joining.\n * - Uses {@link EXPECTED} to colorize each argument consistently.\n *\n * @example\n * ```ts\n * const args = [1, \"test\", true];\n * console.log(serializeCallArgs(args));\n * // Output (with ANSI colors):\n * // 1, test, true\n * ```\n *\n * @example\n * ```ts\n * // Arguments containing commas\n * const args = [\"a,b\", \"c\"];\n * console.log(serializeCallArgs(args));\n * // Output:\n * // a b, c\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeCallArgs(args: Array<unknown>): string {\n const serialized = serialize(args, '').slice(1, -1);\n\n return serialized.map((arg) => {\n return EXPECTED(arg.replace(',', ''));\n }).join(', ');\n}\n\n/**\n * Serializes a list of calls or values into a formatted, optionally highlighted string.\n *\n * Each line contains an index, optional highlight symbol, and a diff of the call/value against the expected value.\n *\n * @param expected - The expected value to diff against each item.\n * @param items - The array of calls or values to serialize.\n * @param offset - Optional 1-based index to highlight.\n * @param symbol - Symbol to use for highlighting the selected line. Default is `'->'`.\n * @param sliceArgs - Whether to slice the diff result to remove outer brackets. Default is `false`.\n * @param maxLines - Maximum number of lines to include. Default is `3`.\n * @returns A formatted string representing the serialized list, or an empty string if `items` is empty.\n *\n * @example\n * ```ts\n * const expected = [1, 2];\n * const calls = [[1, 3], [1, 2], [2, 2]];\n * console.log(serializeList(expected, calls));\n * // Output (with ANSI colors):\n * // 1: 1 \\x1B[31m3\\x1B[39m\n * // 2: 1 2\n * // 3: \\x1B[31m2\\x1B[39m 2\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeList(\n expected: unknown, items: Array<unknown>, offset?: number, symbol: string = '->', sliceArgs: boolean = false, maxLines: number = 3\n): string {\n if (!items?.length) return '';\n\n\n let start = 0;\n let highlightIndex = -1;\n const total = items.length;\n\n if (offset && offset >= 1 && offset <= total) {\n highlightIndex = offset - 1;\n start = Math.max(0, Math.min(highlightIndex - 1, total - (maxLines - 1)));\n }\n\n const end = Math.min(start + maxLines, total);\n const width = String(end).length;\n const symbolPad = ' '.repeat(symbol.length + 1);\n const result: Array<string> = new Array(end - start);\n\n for (let i = start; i < end; i++) {\n const args = items[i];\n const num = String(i + 1).padStart(width, ' ');\n const prefix = i === highlightIndex ? `${ symbol } ` : symbolPad;\n\n if(sliceArgs && Array.isArray(args) && args.length < 1) {\n result[i - start] = `${ prefix }${ num }: called with 0 arguments`;\n continue;\n }\n\n const diff = sliceArgs\n ? diffArgs(expected, args).slice(1, -1)\n : diffArgs(expected, args);\n\n result[i - start] = `${ prefix }${ num }: ${ diff.join(' ') }`;\n }\n\n return result.join('\\n');\n}\n\n\n/**\n * Serializes a list of highlighted calls with diffs against the expected values.\n *\n * Only the calls at the specified `highlights` indices are included, up to `maxLines`.\n *\n * @param expected - The expected argument array.\n * @param calls - Array of actual calls to diff against `expected`.\n * @param highlights - 1-based indices of calls to include in the output.\n * @param maxLines - Maximum number of lines to include. Default is `3`.\n * @returns A formatted string of the highlighted calls, or an empty string if no calls or highlights.\n *\n * @example\n * ```ts\n * const expected = [1, 2];\n * const calls = [[1, 3], [1, 2], [2, 2]];\n * console.log(serializeHighlightedCalls(expected, calls, [1, 3]));\n * // Output:\n * // 1: 1 \\x1B[31m3\\x1B[39m\n * // 3: \\x1B[31m2\\x1B[39m 2\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeHighlightedCalls(expected: Array<unknown>, calls: Array<unknown[]>, highlights: Array<number> = [], maxLines: number = 3): string {\n if (!calls?.length || !highlights.length) return '';\n\n const total = calls.length;\n const width = String(total).length + 3;\n\n const results: Array<string> = [];\n for (let i = 0; i < highlights.length; i++) {\n const idx = highlights[i] - 1; // convert 1-based to 0-based\n if (idx < 0 || idx >= total) continue;\n\n const diff = diffArgs(expected, calls[idx]).slice(1, -1);\n\n results.push(`${ String(idx + 1).padStart(width, ' ') }: ${ diff.join(' ') }`);\n if(results.length >= maxLines) break;\n }\n\n return results.join('\\n');\n}\n\n/**\n * Serializes a list of calls with diffs, slicing the arguments for concise output.\n *\n * @param expected - The expected argument array.\n * @param returns - Array of actual calls to diff against `expected`.\n * @param offset - Optional 1-based index to highlight.\n * @param symbol - Symbol to highlight the selected line.\n * @returns A formatted string representing the serialized calls.\n *\n * @see serializeList\n * @since 1.0.0\n */\n\nexport function serializeCallList(expected: Array<unknown>, returns: Array<unknown[]>, offset?: number, symbol?: string): string {\n return serializeList(expected, returns, offset, symbol, true);\n}\n\n/**\n * Serializes a list of return values with diffs against the expected value.\n *\n * @param expected - The expected value.\n * @param calls - Array of return values to diff against `expected`.\n * @param offset - Optional 1-based index to highlight.\n * @param symbol - Symbol to highlight the selected line.\n * @returns A formatted string representing the serialized return values.\n *\n * @see serializeList\n * @since 1.0.0\n */\n\nexport function serializeReturnList(expected: unknown, calls: Array<unknown>, offset?: number, symbol?: string): string {\n return serializeList(expected, calls, offset, symbol, false);\n}\n\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { MockInvocationResultInterface, MockStateInterface } from '@matchers/interfaces/mock-matcher.interface';\n\n/**\n * Imports\n */\n\nimport { equals } from '@components/object.component';\nimport { ensurePositiveNumber } from '@handlers/number.handler';\nimport { EXPECTED, RECEIVED } from '@components/color.component';\nimport { handleFailure, serializeOneLine } from '@handlers/matchers.handler';\nimport { serializeHighlightedCalls, serializeReturnList } from '@handlers/mock.handler';\nimport { ensureMock, serializeCallArgs, serializeCallList } from '@handlers/mock.handler';\n\n/**\n * Asserts that a mock function has been called at least once.\n *\n * @remarks\n * This matcher validates that the mock function represented by `this.received`\n * has been invoked one or more times. It uses {@link handleFailure} to report\n * a descriptive failure message if the assertion does not pass.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn();\n * xExpect(mockFn).toHaveBeenCalled(); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * xExpect(mockFn).toHaveBeenCalled(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveBeenCalled(this: MatcherService<MockStateInterface>): void {\n ensureMock.call(this);\n const calls = this.received.mock.calls;\n const count = this.received.mock.calls.length;\n\n handleFailure.call(this, {\n pass: count > 0,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`Expected calls: ${ EXPECTED('0') }`);\n info.push(`Received calls: ${ RECEIVED(count.toString()) }\\n`);\n info.push(serializeCallList([], calls));\n },\n handleInfo(info) {\n info.push(`Expected calls: >= ${ EXPECTED('1') }`);\n info.push(`Received calls: ${ RECEIVED(count.toString()) }\\n`);\n }\n });\n}\n\n/**\n * Asserts that a mock function has been called a specific number of times.\n *\n * @param expected - The exact number of times the mock function is expected to have been called.\n *\n * @remarks\n * This matcher validates that the mock function represented by `this.received`\n * has been invoked exactly `expected` times. It performs the following checks:\n * 1. Ensures that `this.received` is a mock function via {@link ensureMock}.\n * 2. Ensures that `expected` is a positive number using {@link ensurePositiveNumber}.\n * 3. Compares the actual call count to `expected` and reports via {@link handleFailure}.\n *\n * @throws {@link xJetTypeError} If `expected` is not a positive number.\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn();\n * xExpect(mockFn).toHaveBeenCalledTimes(1); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * xExpect(mockFn).toHaveBeenCalledTimes(2); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveBeenCalledTimes(this: MatcherService<MockStateInterface>, expected: number | bigint): void {\n const expectedLabels = [ 'expected' ];\n\n ensureMock.call(this, expectedLabels);\n ensurePositiveNumber.call(this, expected, 'expected', expectedLabels);\n\n const count = this.received.mock.calls.length;\n handleFailure.call(this, {\n expected,\n pass: count == expected,\n expectedLabels,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`Expected calls: != ${ EXPECTED(expected.toString()) }`);\n },\n handleInfo(info) {\n info.push(`Expected calls: ${ EXPECTED(expected.toString()) }`);\n info.push(`Received calls: ${ RECEIVED(count.toString()) }\\n`);\n }\n });\n}\n\n/**\n * Asserts that a mock function has been called with specific arguments at least once.\n *\n * @param args - The expected arguments to check against the mock function calls.\n *\n * @remarks\n * This matcher validates that the mock function represented by `this.received`\n * has been invoked at least once with arguments exactly matching `args`. It performs the following:\n * 1. Ensures that `this.received` is a mock function via {@link ensureMock}.\n * 2. Compares each call to the expected arguments using {@link equals}.\n * 3. Records the indices of calls that match the expected arguments.\n * 4. Reports assertion results and detailed call differences using {@link handleFailure},\n * {@link serializeCallArgs}, {@link serializeCallList}, and {@link serializeHighlightedCalls}.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(1, 'test');\n * xExpect(mockFn).toHaveBeenCalledWith(1, 'test'); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(2, 'test');\n * xExpect(mockFn).toHaveBeenCalledWith(1, 'test'); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveBeenCalledWith(this: MatcherService<MockStateInterface>, ...args: Array<unknown>): void {\n const expectedLabels = [ '...args' ];\n ensureMock.call(this, expectedLabels);\n\n const calls = this.received.mock.calls;\n const count = this.received.mock.calls.length;\n const indices: Array<number> = [];\n\n calls.forEach((call, index) => {\n if (call.length === args.length && equals(args, call)) {\n indices.push(index + 1);\n }\n });\n\n const pass = indices.length > 0;\n handleFailure.call(this, {\n pass,\n expectedLabels,\n expected: args,\n receivedLabeled: this.received.name,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: not ${ serializeCallArgs(args) }`);\n info.push(`Received:\\n\\n${ serializeHighlightedCalls(args, calls, indices) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: ${ serializeCallArgs(args) }`);\n info.push(`Received: \\n\\n${ serializeCallList(args, calls) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that a mock function was last called with the specified arguments.\n *\n * @param args - The expected arguments to check against the last mock function call.\n *\n * @remarks\n * This matcher validates that the mock function represented by `this.received`\n * was invoked last with arguments exactly matching `args`. It performs the following:\n * 1. Ensures that `this.received` is a mock function via {@link ensureMock}.\n * 2. Retrieves the last call from the mock\u2019s call history.\n * 3. Compares the last call arguments with the expected arguments using {@link equals}.\n * 4. Reports assertion results and detailed call differences using {@link handleFailure},\n * {@link serializeCallArgs}, and {@link serializeCallList}.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(1, 'first');\n * mockFn(2, 'last');\n * xExpect(mockFn).toHaveBeenLastCalledWith(2, 'last'); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(1, 'first');\n * mockFn(2, 'last');\n * xExpect(mockFn).toHaveBeenLastCalledWith(1, 'first'); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveBeenLastCalledWith(this: MatcherService<MockStateInterface>, ...args: Array<unknown>): void {\n const expectedLabels = [ '...args' ];\n ensureMock.call(this, expectedLabels);\n\n const calls = this.received.mock.calls;\n const count = calls.length;\n const callIndex = this.received.mock.calls.at(-1);\n const pass = callIndex !== undefined && equals(args, callIndex);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n expected: args,\n receivedLabeled: this.received.name,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: not ${ serializeCallArgs(args) }`);\n info.push(`Received: \\n\\n${ serializeCallList(args, calls, calls.length) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: ${ serializeCallArgs(args) }`);\n info.push(`Received: \\n\\n${ serializeCallList(args, calls, calls.length) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that a mock function was called with the specified arguments on its N-th invocation.\n *\n * @param nthCall - The 1-based index of the call to check.\n * @param args - The expected arguments to check for the N-th call.\n *\n * @remarks\n * This matcher performs the following steps:\n * 1. Validates that `this.received` is a mock function using {@link ensureMock}.\n * 2. Ensures that `nthCall` is a positive number via {@link ensurePositiveNumber}.\n * 3. Retrieves the N-th call from the mock\u2019s call history.\n * 4. Compares the N-th call arguments to the expected `args` using {@link equals}.\n * 5. Reports assertion results and detailed call differences using {@link handleFailure},\n * {@link serializeCallArgs}, and {@link serializeCallList}.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n * @throws If `nthCall` is not a positive number, {@link ensurePositiveNumber} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn('first');\n * mockFn('second');\n * xExpect(mockFn).toHaveBeenNthCalledWith(2, 'second'); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn('first');\n * mockFn('second');\n * xExpect(mockFn).toHaveBeenNthCalledWith(1, 'second'); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveBeenNthCalledWith(this: MatcherService<MockStateInterface>, nthCall: number, ...args: Array<unknown>): void {\n const expectedLabels = [ 'nthCall', '...args' ];\n ensureMock.call(this, expectedLabels);\n ensurePositiveNumber.call(this, nthCall, 'nthCall', expectedLabels);\n\n const calls = this.received.mock.calls;\n const count = calls.length;\n const callIndex = this.received.mock.calls.at(nthCall - 1);\n const pass = callIndex !== undefined && equals(args, callIndex);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n expected: args,\n receivedLabeled: this.received.name,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`nthCall: ${ nthCall }`);\n info.push(`Expected: not ${ serializeCallArgs(args) }`);\n info.push(`Received: \\n\\n${ serializeCallList(args, calls, nthCall) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`nthCall: ${ nthCall }`);\n info.push(`Expected: ${ serializeCallArgs(args) }`);\n info.push(`Received: \\n\\n${ serializeCallList(args, calls, nthCall) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that a mock function has returned at least once.\n *\n * @remarks\n * This matcher performs the following steps:\n * 1. Validates that `this.received` is a mock function using {@link ensureMock}.\n * 2. Iterates over the mock\u2019s results to count how many invocations returned a value.\n * 3. Collects all returned values for reporting.\n * 4. Delegates assertion reporting to {@link handleFailure}, including a summary of returned values\n * and total calls using {@link serializeReturnList}.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn();\n * xExpect(mockFn).toHaveReturned(); // Passes if the function returned at least once\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * xExpect(mockFn).toHaveReturned(); // Fails if the function was never called or never returned\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveReturned(this: MatcherService<MockStateInterface>): void {\n ensureMock.call(this);\n const results: Array<unknown> = [];\n const count = this.received.mock.calls.length;\n const resultsCount = this.received.mock.results.reduce(\n (n: number, result: MockInvocationResultInterface<unknown>) => {\n if (result.type === 'return') {\n results.push(result.value);\n\n return n + 1;\n }\n\n return n;\n },\n 0\n );\n\n handleFailure.call(this, {\n pass: resultsCount > 0,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`Expected returns: ${ EXPECTED('0') }`);\n info.push(`Received returns: ${ RECEIVED(resultsCount.toString()) }\\n`);\n info.push(serializeReturnList(undefined, results));\n info.push(`\\nCalls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(info) {\n info.push(`Expected returns: >= ${ EXPECTED('1') }`);\n info.push(`Received returns: ${ RECEIVED(resultsCount.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that a mock function has returned a specific number of times.\n *\n * @param expected - The expected number of times the mock function should have returned.\n *\n * @remarks\n * This matcher performs the following steps:\n * 1. Validates that `this.received` is a mock function using {@link ensureMock}.\n * 2. Ensures that the `expected` value is a positive number using {@link ensurePositiveNumber}.\n * 3. Counts the number of returned values in the mock's results.\n * 4. Delegates assertion reporting to {@link handleFailure}, including a summary of total calls.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n * @throws If `expected` is not a positive number, {@link ensurePositiveNumber} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn();\n * xExpect(mockFn).toHaveReturnedTimes(1); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * xExpect(mockFn).toHaveReturnedTimes(2); // Fails if the function returned fewer or more times\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveReturnedTimes(this: MatcherService<MockStateInterface>, expected: number): void {\n const expectedLabels = [ 'expected' ];\n ensureMock.call(this, expectedLabels);\n ensurePositiveNumber.call(this, expected, 'expected', expectedLabels);\n\n const count = this.received.mock.calls.length;\n const resultsCount = this.received.mock.results.reduce(\n (n: number, result: MockInvocationResultInterface<unknown>) => result.type === 'return' ? n + 1 : n,\n 0\n );\n\n handleFailure.call(this, {\n expectedLabels,\n pass: resultsCount == expected,\n expected: expected,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`Expected returns: != ${ EXPECTED(expected.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(info) {\n info.push(`Expected returns: ${ EXPECTED(expected.toString()) }`);\n info.push(`Received returns: ${ RECEIVED(resultsCount.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that the last return value of a mock function matches the expected value.\n *\n * @param expected - The value expected to have been returned by the last invocation of the mock.\n *\n * @remarks\n * This matcher performs the following steps:\n * 1. Ensures `this.received` is a mock function using {@link ensureMock}.\n * 2. Collects all return values from the mock's results.\n * 3. Compares the last returned value to `expected` using deep equality via {@link equals}.\n * 4. Delegates assertion reporting to {@link handleFailure}, including serialized return values and call count.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(1);\n * mockFn(2);\n * xExpect(mockFn).toHaveLastReturnedWith(2); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(1);\n * xExpect(mockFn).toHaveLastReturnedWith(2); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveLastReturnedWith(this: MatcherService<MockStateInterface>, expected: unknown): void {\n const expectedLabels = [ 'expected' ];\n ensureMock.call(this, expectedLabels);\n\n const results: Array<unknown> = [];\n const count = this.received.mock.calls.length;\n const resultsCount = this.received.mock.results.reduce(\n (n: number, result: MockInvocationResultInterface<unknown>) => {\n if (result.type === 'return') {\n results.push(result.value);\n\n return n + 1;\n }\n\n return n;\n },\n 0\n );\n\n const result = results.at(-1);\n const pass = results.length > 0 && equals(expected, result);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n expected: expected,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`Expected returns: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push('Received returns:\\n');\n info.push(serializeReturnList(expected, results, resultsCount));\n info.push(`\\nCalls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(info) {\n info.push(`Expected returns: ${ EXPECTED(serializeOneLine(expected)) }`);\n if (results.length > 0) {\n info.push('Received returns:\\n');\n info.push(serializeReturnList(expected, results, resultsCount));\n }\n\n info.push(`\\nReturns: ${ RECEIVED(resultsCount.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that a specific invocation of a mock function returned the expected value.\n *\n * @param nthCall - The 1-based index of the call to check.\n * @param expected - The value expected to have been returned by the `nthCall` invocation.\n *\n * @remarks\n * This matcher performs the following steps:\n * 1. Ensures `this.received` is a mock function using {@link ensureMock}.\n * 2. Validates that `nthCall` is a positive number using {@link ensurePositiveNumber}.\n * 3. Collects all return values from the mock's results.\n * 4. Compares the return value of the `nthCall` invocation to `expected` using deep equality via {@link equals}.\n * 5. Delegates assertion reporting to {@link handleFailure}, including serialized return values, the call index, and call count.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n * @throws If `nthCall` is not a positive number, {@link ensurePositiveNumber} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn('a');\n * mockFn('b');\n * xExpect(mockFn).toHaveNthReturnedWith(2, 'b'); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn('a');\n * xExpect(mockFn).toHaveNthReturnedWith(2, 'b'); // Fails, only one call\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveNthReturnedWith(this: MatcherService<MockStateInterface>, nthCall: number, expected: unknown): void {\n const expectedLabels = [ 'nthCall', 'expected' ];\n ensureMock.call(this, expectedLabels);\n ensurePositiveNumber.call(this, nthCall, 'nthCall', expectedLabels);\n\n const results: Array<unknown> = [];\n const count = this.received.mock.calls.length;\n const resultsCount = this.received.mock.results.reduce(\n (n: number, result: MockInvocationResultInterface<unknown>) => {\n if (result.type === 'return') {\n results.push(result.value);\n\n return n + 1;\n }\n\n return n;\n },\n 0\n );\n\n const result = results.at(nthCall - 1);\n const pass = nthCall <= results.length && equals(expected, result);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n expected: expected,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`nthCall: ${ nthCall }`);\n info.push(`Expected returns: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push('Received returns:\\n');\n info.push(serializeReturnList(expected, results, nthCall));\n info.push(`\\nReturns: ${ RECEIVED(resultsCount.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(info) {\n info.push(`nthCall: ${ nthCall }`);\n info.push(`Expected returns: ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push('Received returns:\\n');\n info.push(serializeReturnList(expected, results, nthCall));\n\n info.push(`\\nReturns: ${ RECEIVED(resultsCount.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\n\n/**\n * Imports\n */\n\nimport { EXPECTED, RECEIVED } from '@components/color.component';\nimport { equals, isAsymmetric } from '@components/object.component';\nimport { handleDiffFailure, handleFailure, serializeOneLine } from '@handlers/matchers.handler';\n\n/**\n * Checks if the received value is exactly the expected value using Object.is,\n * or matches an asymmetric matcher.\n *\n * @param expected - The expected value or asymmetric matcher.\n *\n * @remarks\n * Uses Object.is for strict equality comparison unless an asymmetric matcher\n * is provided, which will be used to match the received value.\n *\n * If the check fails but the values are deeply equal,\n * a note suggests using \"toEqual\" instead.\n *\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(['hello']).toBe(['hello']); // Fails because arrays differ by reference\n * xExpect(['hello']).toBe(xExpect.arrayContaining(['hello'])); // Passes with asymmetric matcher\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBe(this: MatcherService, expected: unknown): void {\n const pass = isAsymmetric(expected)\n ? expected.matches(this.received)\n : Object.is(this.received, expected);\n\n const note =\n !pass && equals(this.received, expected)\n ? 'If it should pass with deep equality, replace \"toBe\" with \"toEqual\"'\n : undefined;\n\n handleDiffFailure.call(this, {\n note,\n pass,\n expected,\n comment: 'Object.is equality',\n expectedLabels: [ 'expected' ]\n });\n}\n\n/**\n * Checks if the received value deeply equals the expected value.\n *\n * @param expected - The expected value to compare deeply against.\n *\n * @remarks\n * Uses deep equality comparison via `equals` function.\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect({ a: 1 }).toEqual({ a: 1 }); // Passes with deep equality\n * xExpect({ a: 1 }).toEqual(xExpect.objectContaining({ a: 1 })); // Passes with asymmetric matcher\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toEqual(this: MatcherService, expected: unknown): void {\n const pass = equals(this.received, expected);\n handleDiffFailure.call(this, {\n pass,\n expected,\n comment: 'deep equality',\n expectedLabels: [ 'expected' ]\n });\n}\n\n/**\n * Checks if the received value is exactly null.\n *\n * @remarks\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(null).toBeNull(); // Passes\n * xExpect(undefined).toBeNull(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeNull(this: MatcherService): void {\n const pass = this.received === null;\n handleDiffFailure.call(this, {\n pass,\n expected: null\n });\n}\n\n/**\n * Checks if the received value is exactly undefined.\n *\n * @remarks\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(undefined).toBeUndefined(); // Passes\n * xExpect(null).toBeUndefined(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeUndefined(this: MatcherService): void {\n const pass = this.received === undefined;\n handleDiffFailure.call(this, {\n pass,\n expected: undefined\n });\n}\n\n/**\n * Checks if the received value is NaN.\n *\n * @remarks\n * Uses Number.isNaN for validation.\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(NaN).toBeNaN(); // Passes\n * xExpect(0 / 0).toBeNaN(); // Passes\n * xExpect(1).toBeNaN(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeNaN(this: MatcherService): void {\n const pass = Number.isNaN(this.received);\n handleDiffFailure.call(this, {\n pass,\n expected: NaN\n });\n}\n\n/**\n * Checks if the received value is truthy.\n *\n * @remarks\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(1).toBeTruthy(); // Passes\n * xExpect('non-empty string').toBeTruthy(); // Passes\n * xExpect(false).toBeTruthy(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeTruthy(this: MatcherService): void {\n const pass = !!this.received;\n handleDiffFailure.call(this, {\n pass,\n expected: true\n });\n}\n\n/**\n * Checks if the received value is falsy.\n *\n * @remarks\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(0).toBeFalsy(); // Passes\n * xExpect('').toBeFalsy(); // Passes\n * xExpect(true).toBeFalsy(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeFalsy(this: MatcherService): void {\n const pass = !this.received;\n handleDiffFailure.call(this, {\n pass,\n expected: false\n });\n}\n\n\n/**\n * Checks if the received value is defined (not undefined).\n *\n * @remarks\n * Throws an error if the assertion fails.\n * Provides custom messages for \"not\" modifier showing expected and received values.\n *\n * @example\n * ```ts\n * xExpect('value').toBeDefined(); // Passes\n * xExpect(undefined).toBeDefined(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeDefined(this: MatcherService): void {\n const pass = this.received !== void 0;\n handleFailure.call(this, {\n pass,\n expected: undefined,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: ${ EXPECTED(serializeOneLine(undefined)) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`Received: ${ RECEIVED(serializeOneLine(this.received)) }`);\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { ConstructorType, FunctionType } from '@interfaces/functions.interface';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { equals } from '@components/object.component';\nimport { getType } from '@diff/components/diff.component';\nimport { serialize } from '@components/serialize.component';\nimport { handleFailure, serializeOneLine } from '@handlers/matchers.handler';\nimport { DIM, EXPECTED, INVERSE, MARK, RECEIVED } from '@components/color.component';\nimport { ensureNotNullish, ensureType, handleDiffFailure } from '@handlers/matchers.handler';\n\n/**\n * Asserts that the received object contains the specified property path,\n * and optionally that the value at that path equals the expected value.\n *\n * @param path - Dot-separated string or array of strings representing the property path.\n * @param expectedValue - Optional expected value at the given path.\n *\n * @throws xJetTypeError - Throws if the received value is null/undefined, or if path is not string/array.\n *\n * @remarks\n * This matcher supports nested properties using dot notation.\n * If the `expectedValue` is provided, it also checks strict equality (Object.is) at the property path.\n *\n * @example\n * ```ts\n * xExpect({ a: { b: 42 } }).toHaveProperty('a.b', 42); // Passes\n * xExpect({ a: {} }).toHaveProperty(['a', 'b']); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveProperty(this: MatcherService<object>, path: string | Array<string>, expectedValue?: unknown): void {\n const expectedLabels = [ 'path', 'value' ];\n ensureNotNullish.call(this, this.received, 'Received', expectedLabels);\n ensureType.call(this, path, [ 'string', 'Array' ], 'Expected path', expectedLabels);\n\n let pass = true;\n let current = this.received;\n const pathFound: Array<string> = [];\n const pathArray = typeof path === 'string' ? path.split('.').filter(Boolean) : path;\n\n for (const segment of pathArray) {\n if (!current || !Object.hasOwn(current, segment)) {\n pass = false;\n break;\n }\n\n pathFound.push(segment);\n current = current[segment as keyof object];\n }\n\n if (pass && expectedValue !== undefined)\n pass = equals(current, expectedValue);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n handleNot(info) {\n info.push(`Expected: not ${ EXPECTED(serializeOneLine(pathArray)) }\\n`);\n\n if (expectedValue) {\n info.push(`Expected value: ${ EXPECTED(serializeOneLine(expectedValue)) }`);\n } else {\n info.push(`Received value: ${ RECEIVED(serializeOneLine(current)) }`);\n }\n },\n handleInfo(info) {\n info.push(`Expected path: ${ EXPECTED(serializeOneLine(pathArray)) }`);\n if (!Object.is(pathFound.join(''), pathArray.join('')))\n info.push(`Received path: ${ RECEIVED(serializeOneLine(pathFound)) }`);\n\n info.push('');\n if (expectedValue) {\n info.push(`Expected value: ${ EXPECTED(serializeOneLine(expectedValue)) }`);\n }\n\n info.push(`Received value: ${ RECEIVED(serializeOneLine(current)) }`);\n }\n });\n}\n\n/**\n * Asserts that the received value is an instance of the provided constructor.\n *\n * @param instance - Constructor function or class to match against.\n *\n * @throws xJetTypeError - Throws if `instance` is not a function.\n *\n * @remarks\n * Useful for validating that a value is created from a specific class or constructor.\n * Works with built-in classes as well as custom constructors.\n *\n * @example\n * ```ts\n * xExpect(new Date()).toBeInstanceOf(Date); // Passes\n * xExpect({}).toBeInstanceOf(Array); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeInstanceOf(this: MatcherService, instance: FunctionType | ConstructorType): void {\n const expectedLabels = [ 'expected' ];\n ensureType.call(this, instance, [ 'function' ], 'Received', expectedLabels);\n\n const received = this.received;\n const pass = received instanceof instance;\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n handleNot(info) {\n info.push(`Expected constructor: not ${ EXPECTED(instance.name) }\\n`);\n },\n handleInfo(info) {\n info.push(`Expected constructor: ${ EXPECTED(instance.name) }`);\n\n if (received !== null && typeof received === 'object' && Object.getPrototypeOf(received) !== null && 'constructor' in received) {\n info.push(`Received constructor: ${ RECEIVED((received as object).constructor.name) }`);\n } else {\n info.push('\\nReceived value has no prototype');\n info.push(`Received value: ${ RECEIVED(serializeOneLine(received)) }`);\n }\n }\n });\n}\n\n/**\n * Asserts that the received string or array contains the expected value.\n *\n * @param expected - The value or substring to search for.\n *\n * @throws xJetTypeError - Throws if received is a string and expected is not a string,\n * or if received is not string/array.\n *\n * @remarks\n * For arrays, this matcher uses reference equality.\n * For strings, it checks for substring inclusion.\n * Use `toContainEqual` for deep equality in arrays.\n *\n * @example\n * ```ts\n * xExpect([1, 2, 3]).toContain(2); // Passes\n * xExpect('hello world').toContain('world'); // Passes\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toContain(this: MatcherService<Array<unknown> | string>, expected: unknown): void {\n const expectedLabels = [ 'expected' ];\n ensureType.call(this, this.received, [ 'string', 'Array' ], 'Received', expectedLabels);\n\n const received = this.received;\n const receivedType = getType(received);\n\n if (typeof received === 'string' && typeof expected !== 'string') {\n throw new xJetTypeError({\n expectedLabels,\n message: `${ EXPECTED('expected') } value must be a string if ${ RECEIVED('received') } value is a string`,\n expected: { value: expected, type: getType(expected) },\n received: { value: received, type: receivedType },\n assertionChain: this.assertionChain\n });\n }\n\n const index = received.indexOf(<string> expected);\n const pass = index !== -1;\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n comment: 'indexOf',\n handleNot(info) {\n if (receivedType === 'string') {\n info.push(`Expected substring: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received string: ${ RECEIVED(serializeOneLine(received)).replace(\n String(expected), INVERSE(String(expected))\n ) }`);\n } else {\n info.push(`Expected value: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received array: ${ RECEIVED(serializeOneLine(received)).replace(\n serializeOneLine(expected), INVERSE(serializeOneLine(expected))\n ) }`);\n }\n },\n handleInfo(info) {\n if (receivedType === 'string') {\n info.push(`Expected substring: ${ EXPECTED(serialize(expected, '').join('\\n')) }`);\n info.push(`Received string: ${ RECEIVED(serialize(receivedType, '').join('\\n')) }`);\n } else {\n const x = [ ...received ].findIndex(item =>\n equals(item, expected)\n );\n\n if (x !== -1) {\n info.push(\n DIM(\n 'Looks like you wanted to test for object/array equality with the stricter `toContain` matcher.\\n' +\n `You probably need to use \\`${ MARK('toContainEqual') }\\` instead.\\n`\n )\n );\n }\n\n info.push(`Expected value: ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received array: ${ RECEIVED(serializeOneLine(receivedType)) }`);\n }\n }\n });\n}\n\n/**\n * Asserts that the received array contains an element deeply equal to the expected value.\n *\n * @param expected - The value to search for using deep equality.\n *\n * @throws xJetTypeError - Throws if received is not an array.\n *\n * @remarks\n * Use this matcher when you need deep equality comparison (e.g., objects or arrays inside an array).\n * For primitive arrays or substring checks, use `toContain`.\n *\n * @example\n * ```ts\n * xExpect([{ a: 1 }, { b: 2 }]).toContainEqual({ a: 1 }); // Passes\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toContainEqual(this: MatcherService<Array<unknown>>, expected: unknown): void {\n const expectedLabels = [ 'expected' ];\n ensureType.call(this, this.received, [ 'string', 'Array' ], 'Received', expectedLabels);\n\n const received = this.received;\n const receivedType = getType(received);\n\n\n const index = [ ...received ].findIndex(item =>\n equals(item, expected)\n );\n\n const pass = index !== -1;\n handleFailure.call(this, {\n pass,\n expectedLabels,\n comment: 'deep equality',\n handleNot(info) {\n info.push(`Expected value: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received array: ${ RECEIVED(serializeOneLine(received)).replace(\n serializeOneLine(expected), INVERSE(serializeOneLine(expected))\n ) }`);\n },\n handleInfo(info) {\n if (receivedType === 'string' && typeof expected === 'string' && received.indexOf(expected) !== -1) {\n info.push(\n DIM(\n 'Looks like you wanted to test for string equality with the stricter `toContainEqual` matcher. ' +\n 'You probably need to use `toContain` instead.\\n'\n )\n );\n }\n\n info.push(`Expected: ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received: ${ RECEIVED(serializeOneLine(received)) }`);\n }\n });\n}\n\n/**\n * Asserts that the received object matches the expected object.\n * Performs a deep equality comparison for all keys in the expected object.\n *\n * @param expected - The expected object to match against.\n *\n * @throws xJetTypeError - Throws if received or expected is not an object.\n *\n * @remarks\n * Only the keys present in `expected` are checked. Extra keys in the received object are ignored.\n * Useful for partial object matching.\n *\n * @example\n * ```ts\n * xExpect({ a: 1, b: 2 }).toMatchObject({ a: 1 }); // Passes\n * xExpect({ a: 1 }).toMatchObject({ a: 1, b: 2 }); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toMatchObject(this: MatcherService<object>, expected: object): void {\n const expectedLabels = [ 'expected' ];\n ensureNotNullish.call(this, this.received, 'Received', expectedLabels);\n ensureType.call(this, this.received, [ 'object' ], 'Received', expectedLabels);\n ensureType.call(this, expected, [ 'object' ], 'Expected', expectedLabels);\n\n const received = this.received;\n const pass = equals(expected, received, false);\n\n handleDiffFailure.call(this, {\n pass,\n expected,\n expectedLabels\n });\n}\n", "/**\n * Imports\n */\n\nimport { toThrow } from '@matchers/functions.matcher';\nimport { toHaveLength, toMatch } from '@matchers/string.matcher';\nimport { toBeCloseTo, toBeGreaterThan } from '@matchers/number.matcher';\nimport { toHaveReturned, toHaveReturnedTimes } from '@matchers/mock.matcher';\nimport { toBeTruthy, toBeFalsy, toBeDefined } from '@matchers/equality.matcher';\nimport { toHaveLastReturnedWith, toHaveNthReturnedWith } from '@matchers/mock.matcher';\nimport { toHaveBeenLastCalledWith, toHaveBeenNthCalledWith } from '@matchers/mock.matcher';\nimport { toBe, toEqual, toBeNull, toBeUndefined, toBeNaN } from '@matchers/equality.matcher';\nimport { toBeGreaterThanOrEqual, toBeLessThan, toBeLessThanOrEqual } from '@matchers/number.matcher';\nimport { toHaveBeenCalled, toHaveBeenCalledTimes, toHaveBeenCalledWith } from '@matchers/mock.matcher';\nimport { toHaveProperty, toBeInstanceOf, toContain, toContainEqual, toMatchObject } from '@matchers/object.matcher';\n\n/**\n * Unified collection of matcher factories for use in the xJet framework.\n *\n * Exposes asymmetric matcher creators across multiple domains, including\n * numbers, strings, objects, equality, mocks, and functions.\n *\n * @remarks\n * All matchers are provided as immutable factories (`as const`) and can be used\n * directly in test assertions for expressive, readable expectations.\n *\n * @example\n * ```ts\n * xExpect(42).toSatisfy(Matchers.number.greaterThan(10));\n * xExpect('hello').toSatisfy(Matchers.strings.contains('ell'));\n * xExpect(fn).toSatisfy(Matchers.functions.calledOnce());\n * ```\n *\n * @since 1.0.0\n */\n\nexport const Matchers = {\n // functions\n toThrow,\n\n // strings\n toMatch,\n toHaveLength,\n\n // objects\n toContain,\n toMatchObject,\n toHaveProperty,\n toBeInstanceOf,\n toContainEqual,\n\n // equality\n toBe,\n toEqual,\n toBeNaN,\n toBeNull,\n toBeFalsy,\n toBeTruthy,\n toBeDefined,\n toBeUndefined,\n\n // numbers\n toBeCloseTo,\n toBeLessThan,\n toBeGreaterThan,\n toBeLessThanOrEqual,\n toBeGreaterThanOrEqual,\n\n // mock\n toHaveReturned,\n toHaveBeenCalled,\n toHaveReturnedTimes,\n toHaveBeenCalledWith,\n toHaveBeenCalledTimes,\n toHaveNthReturnedWith,\n toHaveLastReturnedWith,\n toHaveBeenNthCalledWith,\n toHaveBeenLastCalledWith\n} as const;\n", "/**\n * Abstract base class for asymmetric matchers with support for inversion logic.\n *\n * Provides a foundation for matchers that can optionally invert their match results.\n * Includes a name identifier and a flag indicating whether to invert the match outcome.\n *\n * @param name - The name of the pattern, used for identification or debugging\n * @param isInverse - If true, the match result is inverted; defaults to false\n *\n * @remarks\n * Subclasses must implement the `matches` method to perform the matching logic and\n * the `expectedLabel` getter to provide a label describing the expected pattern.\n *\n * The protected method `applyInverse` applies inversion to the boolean result based\n * on the `isInverse` flag.\n *\n * @since 1.0.0\n */\n\nexport abstract class AbstractPattern {\n /**\n * Creates an instance of the pattern with a name and optional inversion flag.\n *\n * @param name - The name of the pattern, used for identification or debugging\n * @param isInverse - Indicates whether the match result should be inverted (default is false)\n *\n * @since 1.0.0\n */\n\n protected constructor(public readonly name: string, public readonly isInverse = false) {\n }\n\n /**\n * Determines whether the received value matches this pattern.\n *\n * @param received - The value to test against the pattern\n * @returns True if the value matches the pattern (after applying inversion if enabled)\n *\n * @since 1.0.0\n */\n\n abstract matches(received: unknown): boolean;\n\n /**\n * A label describing the expected pattern, used in error messages or debugging.\n *\n * @since 1.0.0\n */\n\n abstract get expectedLabel(): string;\n\n /**\n * Applies inversion logic to the given result based on the `isInverse` flag.\n *\n * @param result - The original match result\n * @returns The possibly inverted match result\n *\n * @since 1.0.0\n */\n\n protected applyInverse(result: boolean): boolean {\n return this.isInverse ? !result : result;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConstructorType } from '@interfaces/functions.interface';\n\n/**\n * Imports\n */\n\nimport { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Asymmetric matcher that matches any value of the specified constructor type.\n *\n * Supports common JavaScript types with specialized checks for primitive wrappers\n * and arrays, falling back to `instanceof` for other types.\n *\n * @throws TypeError - If called with `undefined` as the expected constructor\n *\n * @remarks\n * Use `AnyPattern.create` to instantiate the matcher. Throws a `TypeError` if called\n * without a constructor argument.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.any(Number));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class AnyPattern extends AbstractPattern {\n /**\n * Map of constructor names to type-checking functions for common JavaScript types.\n *\n * Each function returns true if the given value matches the corresponding type,\n * including primitive wrappers and arrays.\n *\n * @since 1.0.0\n */\n\n private static readonly TYPE_CHECKS: Record<string, (value: unknown) => boolean> = {\n String: (actual) => typeof actual === 'string' || actual instanceof String,\n Number: (actual) => typeof actual === 'number' || actual instanceof Number,\n Function: (actual) => typeof actual === 'function' || actual instanceof Function,\n Boolean: (actual) => typeof actual === 'boolean' || actual instanceof Boolean,\n BigInt: (actual) => typeof actual === 'bigint' || actual instanceof BigInt,\n Symbol: (actual) => typeof actual === 'symbol' || actual instanceof Symbol,\n Object: (actual) => typeof actual === 'object',\n Array: Array.isArray\n };\n\n /**\n * Constructs a new `AnyPattern` instance with the specified expected constructor.\n *\n * @param expected - The constructor function this pattern will match against\n *\n * @since 1.0.0\n */\n\n private constructor(public readonly expected: ConstructorType) {\n super(`Any<${ expected.name }>`);\n }\n\n /**\n * Creates a new `AnyPattern` matcher for the specified constructor.\n *\n * @param expected - The constructor function to match values against\n * @returns A new `AnyPattern` instance\n *\n * @throws TypeError - If `expected` is `undefined`\n *\n * @example\n * ```ts\n * const matcher = AnyPattern.create(Number);\n * ```\n *\n * @since 1.0.0\n */\n\n static create(expected: ConstructorType): AnyPattern {\n if (expected === undefined) {\n throw new TypeError(\n 'any() expects to be passed a constructor function. ' +\n 'Please pass one or use anything() to match any object.'\n );\n }\n\n return new AnyPattern(expected);\n }\n\n /**\n * A label describing the expected constructor type.\n *\n * @returns A string of the form `Any<ConstructorName>`\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return `Any<${ this.expected.name }>`;\n }\n\n /**\n * Determines whether the received value matches the expected constructor type.\n *\n * @param received - The value to test\n * @returns True if the value matches the expected type; otherwise false\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (this.expected.name in AnyPattern.TYPE_CHECKS)\n return AnyPattern.TYPE_CHECKS[this.expected.name](received);\n\n return received instanceof this.expected;\n }\n}\n", "/**\n * Imports\n */\n\nimport { serialize } from '@components/serialize.component';\nimport { AbstractPattern } from '@patterns/abstract.pattern';\nimport { equals, isAsymmetric } from '@components/object.component';\n\n/**\n * Asymmetric matcher that checks if every element in an array matches a given matcher or value.\n *\n * Supports optional inversion of the match result.\n *\n * @param isInverse - Indicates whether the match result should be inverted\n * @param expected - The matcher or value that each element is expected to match\n *\n * @remarks\n * Use `ArrayOfPattern.create` to instantiate this matcher. Throws a `TypeError` if `expected` is `undefined`.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.arrayOf(42));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class ArrayOfPattern extends AbstractPattern {\n /**\n * Constructs a new `ArrayOfPattern`.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected matcher or value for each element\n *\n * @since 1.0.0\n */\n\n private constructor(isInverse: boolean, private expected: unknown) {\n super('ArrayOf', isInverse);\n }\n\n /**\n * Creates an `ArrayOfPattern` matcher.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The matcher or value that each element should match\n *\n * @returns A new `ArrayOfPattern` instance\n *\n * @throws TypeError - If `expected` is `undefined`\n *\n * @since 1.0.0\n */\n\n static create(isInverse: boolean, expected: unknown): ArrayOfPattern {\n if (expected === undefined) {\n throw new TypeError('arrayOf() expects a matcher or value.');\n }\n\n return new ArrayOfPattern(isInverse, expected);\n }\n\n /**\n * A label describing the expected array-of pattern.\n *\n * @returns A string indicating the expected matcher/value and inversion status\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return `${ this.isInverse ? 'Not ' : '' }ArrayOf( ${ this.describe(this.expected) } )`;\n }\n\n /**\n * Determines whether every element in the received array matches the expected matcher or value.\n *\n * @param received - The array to test\n *\n * @returns True if all elements match; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (!Array.isArray(received)) {\n return this.applyInverse(false);\n }\n\n // Check every element matches elementMatcher\n const allMatch = received.every((item) => this.matchElement(item, this.expected));\n\n return this.applyInverse(allMatch);\n }\n\n /**\n * Tests whether an item matches a matcher or equals a value, supporting asymmetric matchers.\n *\n * @param item - The actual item to test\n * @param matcher - The matcher or value to compare against\n *\n * @returns True if the item matches the matcher or equals the value; otherwise false\n *\n * @since 1.0.0\n */\n\n private matchElement(item: unknown, matcher: unknown): boolean {\n if (isAsymmetric(matcher)) return matcher.matches(item);\n\n return equals(item, matcher);\n }\n\n /**\n * Returns a string description of the expected matcher or value, supporting asymmetric matchers.\n *\n * @param value - The value to describe\n *\n * @returns A string description of the value\n *\n * @since 1.0.0\n */\n\n private describe(value: unknown): string {\n if (isAsymmetric(value)) return value.expectedLabel;\n if (typeof value === 'string') return `\"${ value }\"`;\n\n return serialize(value, '').join(' ');\n }\n}\n", "/**\n * Imports\n */\n\nimport { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Asymmetric matcher that checks if a number is close to an expected value within a specified precision.\n *\n * Supports optional inversion of the match result.\n *\n * @param inverse - Indicates whether the match result should be inverted\n * @param expected - The expected numeric value to compare against\n * @param precision - Number of decimal digits for precision (default is 2)\n *\n * @remarks\n * Use `CloseToPattern.create` to instantiate this matcher.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.closeTo(3.14, 2));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class CloseToPattern extends AbstractPattern {\n /**\n * Constructs a new `CloseToPattern`.\n *\n * @param inverse - Whether to invert the match result\n * @param expected - The expected numeric value\n * @param precision - Decimal precision, defaults to 2\n *\n * @since 1.0.0\n */\n\n private constructor(inverse: boolean, public readonly expected: number, public readonly precision: number = 2) {\n super('CloseTo', inverse);\n }\n\n /**\n * Creates a `CloseToPattern` matcher.\n *\n * @param inverse - Whether to invert the match result\n * @param expected - The expected numeric value\n * @param precision - Optional decimal precision\n *\n * @returns A new `CloseToPattern` instance\n *\n * @since 1.0.0\n */\n\n static create(inverse: boolean, expected: number, precision?: number): CloseToPattern {\n return new CloseToPattern(inverse, expected, precision);\n }\n\n /**\n * A label describing the expected close-to pattern.\n *\n * @returns A string describing the expected value and precision, indicating inversion if applicable\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n const not = this.isInverse ? 'Not ' : '';\n const precisionLabel = this.precision !== 1 ? 's' : '';\n\n return `${ not }CloseTo(${ this.expected }, ${ this.precision } digit${ precisionLabel })`;\n }\n\n /**\n * Determines whether the received value is close to the expected value within the specified precision.\n *\n * @param received - The value to test\n *\n * @returns True if the value is within the precision range; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n const sample: unknown = this.expected;\n\n if (typeof received !== 'number' || typeof sample !== 'number')\n return this.applyInverse(false);\n\n return this.applyInverse(\n Math.abs(received - sample) < Math.pow(10, -this.precision) / 2\n );\n }\n}\n", "/**\n * Imports\n */\n\nimport { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Asymmetric matcher that matches any non-null and non-undefined value.\n *\n * @remarks\n * Use `AnythingPattern.create` to instantiate this matcher.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.anything());\n * ```\n *\n * @since 1.0.0\n */\n\nexport class AnythingPattern extends AbstractPattern {\n /**\n * Constructs a new `AnythingPattern` instance.\n *\n * @since 1.0.0\n */\n\n private constructor() {\n super('Anything');\n }\n\n /**\n * Creates a new `AnythingPattern` matcher.\n *\n * @returns A new `AnythingPattern` instance\n *\n * @since 1.0.0\n */\n\n static create(): AnythingPattern {\n return new AnythingPattern();\n }\n\n /**\n * A label describing the expected pattern.\n *\n * @returns The string `'Anything'`\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return 'Anything';\n }\n\n /**\n * Determines whether the received value is not `null` or `undefined`.\n *\n * @param received - The value to test\n *\n * @returns True if the value is not `null` or `undefined`; otherwise false\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n return received != null;\n }\n}\n", "/**\n * Imports\n */\n\nimport { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Asymmetric matcher that checks if a string matches an expected substring or regular expression.\n *\n * Supports optional inversion of the match result.\n *\n * @param isInverse - Indicates whether the match result should be inverted\n * @param expected - The string or RegExp pattern expected to be matched\n *\n * @remarks\n * Use `StringMatchingPattern.create` to instantiate this matcher.\n * Throws a `TypeError` if `expected` is not a string or RegExp.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.stringMatching('hello'));\n * xExpect(value).toEqual(xExpect.stringMatching(/world$/));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class StringMatchingPattern extends AbstractPattern {\n /**\n * Constructs a new `StringMatchingPattern`.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected string or RegExp to match\n *\n * @since 1.0.0\n */\n\n private constructor(isInverse: boolean, private readonly expected: string | RegExp) {\n super('StringMatching', isInverse);\n }\n\n /**\n * Creates a `StringMatchingPattern` matcher.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The string or RegExp to match against\n *\n * @returns A new `StringMatchingPattern` instance\n *\n * @throws TypeError - If `expected` is not a string or RegExp, or is null/undefined\n *\n * @since 1.0.0\n */\n\n static create(isInverse: boolean, expected: string | RegExp): StringMatchingPattern {\n const expectedType = typeof expected;\n\n if (expected === undefined || expected === null)\n throw new TypeError('stringMatching() expects a string or RegExp.');\n\n if (expectedType !== 'string' && !(expected instanceof RegExp))\n throw new TypeError('stringMatching() expects a string or RegExp.');\n\n return new StringMatchingPattern(isInverse, expected);\n }\n\n /**\n * A label describing the expected string matching pattern.\n *\n * @returns A string indicating the expected substring or pattern and inversion status\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n const not = this.isInverse ? 'Not ' : '';\n if (typeof this.expected === 'string')\n return `${ not }stringMatching(\"${ this.expected }\")`;\n\n return `${ not }stringMatching(${ this.expected.toString() })`;\n }\n\n /**\n * Determines whether the received string matches the expected substring or RegExp.\n *\n * @param received - The string to test\n *\n * @returns True if the string matches; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (typeof received !== 'string') {\n return this.applyInverse(false);\n }\n\n let pass: boolean;\n if (typeof this.expected === 'string') {\n pass = received.includes(this.expected);\n } else {\n pass = this.expected.test(received);\n }\n\n return this.applyInverse(pass);\n }\n}\n", "/**\n * Imports\n */\n\nimport { serialize } from '@components/serialize.component';\nimport { AbstractPattern } from '@patterns/abstract.pattern';\nimport { equals, isAsymmetric } from '@components/object.component';\n\n/**\n * Asymmetric matcher that checks if an array contains all expected elements.\n *\n * Supports optional inversion of the match result.\n *\n * @param isInverse - Indicates whether the match result should be inverted\n * @param expected - The array of elements expected to be contained within the tested array\n *\n * @remarks\n * Use `ArrayContainingPattern.create` to instantiate this matcher. Throws a `TypeError` if the expected value is not an array.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.arrayContaining([1, 2]));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class ArrayContainingPattern extends AbstractPattern {\n /**\n * Constructs a new `ArrayContainingPattern`.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected array elements\n *\n * @since 1.0.0\n */\n\n private constructor(isInverse: boolean, private readonly expected: unknown[]) {\n super('ArrayContaining', isInverse);\n }\n\n /**\n * Creates an `ArrayContainingPattern` matcher.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected array elements\n *\n * @returns A new `ArrayContainingPattern` instance\n *\n * @throws TypeError - If `expected` is not an array\n *\n * @since 1.0.0\n */\n\n static create(isInverse: boolean, expected: Array<unknown>): ArrayContainingPattern {\n if (!Array.isArray(expected)) {\n throw new TypeError('arrayContaining() expects an array.');\n }\n\n return new ArrayContainingPattern(isInverse, expected);\n }\n\n /**\n * A label describing the expected array containing pattern.\n *\n * @returns A string indicating the expected elements and inversion status\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return `${ this.isInverse ? 'Not ' : '' }ArrayContaining(${ this.describe(this.expected) })`;\n }\n\n /**\n * Determines whether the received array contains all expected elements.\n *\n * @param received - The array to test\n *\n * @returns True if all expected elements are contained; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (!Array.isArray(received))\n return this.applyInverse(false);\n\n const allContained = this.expected.every((expItem) =>\n received.some((recItem) => this.matchElement(recItem, expItem))\n );\n\n return this.applyInverse(allContained);\n }\n\n /**\n * Tests whether an item matches a matcher, supporting asymmetric matchers.\n *\n * @param item - The actual item to test\n * @param matcher - The matcher or value to compare against\n *\n * @returns True if the item matches the matcher; otherwise false\n *\n * @since 1.0.0\n */\n\n private matchElement(item: unknown, matcher: unknown): boolean {\n if (isAsymmetric(matcher)) return matcher.matches(item);\n\n return equals(item, matcher);\n }\n\n /**\n * Returns a string description of the expected value, supporting asymmetric matchers.\n *\n * @param value - The value to describe\n * @returns A string description of the value\n *\n * @since 1.0.0\n */\n\n private describe(value: unknown): string {\n if (isAsymmetric(value)) return value.expectedLabel;\n\n return serialize(value, '').join(' ');\n }\n}\n", "/**\n * Imports\n */\n\nimport { serialize } from '@components/serialize.component';\nimport { AbstractPattern } from '@patterns/abstract.pattern';\nimport { equals, isAsymmetric, hasKey } from '@components/object.component';\n\n/**\n * Asymmetric matcher that checks if an object contains the expected key-value pairs.\n *\n * Supports optional inversion of the match result.\n *\n * @param isInverse - Indicates whether the match result should be inverted\n * @param expected - A plain object containing key-value pairs expected to be present\n *\n * @remarks\n * Use `ObjectContainingPattern.create` to instantiate this matcher.\n * Throws a `TypeError` if `expected` is not a plain object.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.objectContaining({ foo: 'bar' }));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class ObjectContainingPattern extends AbstractPattern {\n /**\n * Constructs a new `ObjectContainingPattern`.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected key-value pairs to match\n *\n * @since 1.0.0\n */\n\n private constructor(isInverse: boolean, private readonly expected: Record<string, unknown>) {\n super('ObjectContaining', isInverse);\n }\n\n /**\n * Creates an `ObjectContainingPattern` matcher.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected key-value pairs\n *\n * @returns A new `ObjectContainingPattern` instance\n *\n * @throws TypeError - If `expected` is not a plain object\n *\n * @since 1.0.0\n */\n\n static create(isInverse: boolean, expected: Record<string, unknown>): ObjectContainingPattern {\n if (typeof expected !== 'object' || expected === null || Array.isArray(expected)) {\n throw new TypeError('objectContaining() expects a plain object.');\n }\n\n return new ObjectContainingPattern(isInverse, expected);\n }\n\n /**\n * A label describing the expected object containing pattern.\n *\n * @returns A string indicating the expected key-value pairs and inversion status\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return `${ this.isInverse ? 'Not ' : '' }ObjectContaining(${ this.describe(this.expected) })`;\n }\n\n /**\n * Determines whether the received object contains all expected key-value pairs.\n *\n * @param received - The object to test\n *\n * @returns True if all expected pairs are contained; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (typeof received !== 'object' || received === null) {\n return this.applyInverse(false);\n }\n\n const allMatch = Object.keys(this.expected).every((key) => {\n if (!hasKey(received, key)) return false;\n\n return this.matchElement((received as Record<string, unknown>)[key], this.expected[key]);\n });\n\n return this.applyInverse(allMatch);\n }\n\n /**\n * Tests whether an item matches a matcher or equals a value, supporting asymmetric matchers.\n *\n * @param item - The actual item to test\n * @param matcher - The matcher or value to compare against\n *\n * @returns True if the item matches the matcher or equals the value; otherwise false\n *\n * @since 1.0.0\n */\n\n private matchElement(item: unknown, matcher: unknown): boolean {\n if (isAsymmetric(matcher)) return matcher.matches(item);\n\n return equals(item, matcher);\n }\n\n /**\n * Returns a string description of the expected value, supporting asymmetric matchers.\n *\n * @param value - The value to describe\n *\n * @returns A string description of the value\n *\n * @since 1.0.0\n */\n\n private describe(value: unknown): string {\n if (isAsymmetric(value)) return value.expectedLabel;\n\n return serialize(value, '').join(' ');\n }\n}\n", "/**\n * Imports\n */\n\nimport { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Asymmetric matcher that checks if a string contains the expected substring.\n *\n * Supports optional inversion of the match result.\n *\n * @param isInverse - Indicates whether the match result should be inverted\n * @param expected - The substring expected to be contained within the tested string\n *\n * @remarks\n * Use `StringContainingPattern.create` to instantiate this matcher. Throws a `TypeError` if the expected value is not a string.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.stringContaining('hello'));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class StringContainingPattern extends AbstractPattern {\n /**\n * Constructs a new `StringContainingPattern`.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected substring\n *\n * @since 1.0.0\n */\n\n private constructor(isInverse: boolean, public readonly expected: string) {\n super('StringContaining', isInverse);\n }\n\n /**\n * Creates a `StringContainingPattern` matcher.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected substring\n *\n * @returns A new `StringContainingPattern` instance\n *\n * @throws TypeError - If `expected` is not a string\n *\n * @since 1.0.0\n */\n\n static create(isInverse: boolean, expected: string): StringContainingPattern {\n const expectedType = typeof expected;\n if (expectedType !== 'string')\n throw new TypeError('stringContaining() expects a string.');\n\n return new StringContainingPattern(isInverse, expected);\n }\n\n /**\n * A label describing the expected string containing a pattern.\n *\n * @returns A string indicating the expected substring and inversion status\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return `${ this.isInverse ? 'Not ' : '' }stringContaining(\"${ this.expected }\")`;\n }\n\n /**\n * Determines whether the received string contains the expected substring.\n *\n * @param received - The string to test\n *\n * @returns True if the string contains the substring; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (typeof received !== 'string') {\n return this.applyInverse(false);\n }\n\n return this.applyInverse(received.includes(this.expected));\n }\n}\n", "/**\n * Imports\n */\n\nimport { AnyPattern } from '@patterns/any.pattern';\nimport { ArrayOfPattern } from '@patterns/array-of.pattern';\nimport { CloseToPattern } from '@patterns/close-to.pattern';\nimport { AnythingPattern } from '@patterns/anything.pattern';\nimport { StringMatchingPattern } from '@patterns/string-matching.pattern';\nimport { ArrayContainingPattern } from '@patterns/array-containing.pattern';\nimport { ObjectContainingPattern } from '@patterns/object-containing.pattern';\nimport { StringContainingPattern } from '@patterns/string-containing.pattern';\n\n/**\n * Collection of factory methods for creating common pattern matchers in the xJet framework.\n *\n * Provides easy access to asymmetric matcher creators for various matching strategies,\n * including positive and negated (`not`) variants.\n *\n * @remarks\n * Each factory method returns an instance of a pattern matcher configured\n * for the specified matching behavior.\n *\n * The `not` namespace provides inverse matchers that negate the match result.\n *\n * @example\n * ```ts\n * const pattern = Patterns.any(String);\n * const notPattern = Patterns.not.closeTo(5, 0.1);\n * ```\n *\n * @since 1.0.0\n */\n\nexport const Patterns = {\n any: AnyPattern.create,\n anything: AnythingPattern.create,\n closeTo: CloseToPattern.create.bind(null, false),\n arrayOf: ArrayOfPattern.create.bind(null, false),\n stringMatching: StringMatchingPattern.create.bind(null, false),\n arrayContaining: ArrayContainingPattern.create.bind(null, false),\n objectContaining: ObjectContainingPattern.create.bind(null, false),\n stringContaining: StringContainingPattern.create.bind(null, false),\n not: {\n closeTo: CloseToPattern.create.bind(null, true),\n arrayOf: ArrayOfPattern.create.bind(null, true),\n stringMatching: StringMatchingPattern.create.bind(null, true),\n arrayContaining: ArrayContainingPattern.create.bind(null, true),\n objectContaining: ObjectContainingPattern.create.bind(null, false),\n stringContaining: StringContainingPattern.create.bind(null, true)\n }\n} as const;\n\n\n\n", "/**\n * Import will remove at compile time\n */\n\nimport type { OptionsPromiseErrorInterface } from '@errors/interfaces/promise-error.interface';\n\n/**\n * Imports\n */\n\nimport { xJetBaseError } from '@errors/base.error';\nimport { RECEIVED } from '@components/color.component';\nimport { serialize } from '@components/serialize.component';\nimport { composeStatement } from '@components/format.component';\n\n/**\n * Error type representing a failed Promise-related matcher assertion.\n *\n * @remarks\n * Extends xJetBaseError to provide a formatted, Jest-style error message\n * for failed promise expectations. The message includes:\n * - A matcher statement from the provided assertion chain.\n * - A clear description of the matcher failure.\n * - The kind of promise result (`Resolved` or `Rejected`) and its serialized value.\n *\n * Formatting is handled using:\n * - composeStatement to construct the matcher statement.\n * - RECEIVED for styling the received value.\n * - serialize to generate a readable string representation.\n *\n * @example\n * ```ts\n * throw new xJetPromiseError({\n * message: `${RECEIVED('received')} promise resolved instead of rejected`,\n * received: myValue,\n * promiseKind: 'Resolved',\n * assertionChain: ['rejects', 'toThrow'],\n * });\n * ```\n *\n * @see RECEIVED\n * @see serialize\n * @see composeStatement\n * @see OptionsPromiseErrorInterface\n *\n * @since 1.0.0\n */\n\nexport class xJetPromiseError extends xJetBaseError {\n\n /**\n * Creates an xJetPromiseError instance with a formatted,\n * Jest-style matcher error message for promise-related failures.\n *\n * @param options - Configuration object containing the matcher\n * details, failure message, received value, and result kind.\n *\n * @throws Error - If the assertion chain is empty\n * (thrown by composeStatement).\n *\n * @see composeStatement\n * @see OptionsPromiseErrorInterface\n *\n * @since 1.0.0\n */\n\n constructor(options: OptionsPromiseErrorInterface) {\n const lines = [\n `${ composeStatement(options) }\\n`,\n `Matcher error: ${ options.message }`,\n `${ options.promiseKind } to value: ${\n RECEIVED(serialize(options.received, '').join(' '))\n }`\n ];\n\n super(lines.join('\\n'), 'xJetPromiseError');\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionType } from '@interfaces/functions.interface';\nimport type { PromisifiedMatchersType } from '@interfaces/matchers.interface';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { RECEIVED } from '@components/color.component';\nimport { xJetPromiseError } from '@errors/promise.error';\nimport { isPromise } from '@components/promise.component';\nimport { getType } from '@diff/components/diff.component';\n\n/**\n * Service class for managing matcher assertions with support for modifiers and async handling.\n *\n * @template T - Type of the value being tested.\n *\n * @remarks\n * This class provides the core logic for matcher evaluation in the xJet framework,\n * including support for `.not`, `.resolves`, and `.rejects` modifiers.\n * It handles synchronous and asynchronous matcher invocation, promise validation,\n * and error throwing with detailed context.\n *\n * Internally tracks an assertion chain for composing error messages.\n *\n * @example\n * ```ts\n * await xExpect(promiseValue).resolves.toBe(expectedValue)\n * ```\n *\n * @since 1.0.0\n */\n\nexport class MatcherService<T = unknown> {\n /**\n * The name of the matcher or assertion that was invoked.\n *\n * @since 1.0.0\n */\n\n macherName: string = '';\n\n /**\n * Indicates if the matcher is dealing with a promise resolution or rejection.\n *\n * @internal\n * @since 1.0.0\n */\n\n protected promise?: 'resolves' | 'rejects';\n\n /**\n * Tracks whether the `.not` modifier has been applied.\n *\n * @internal\n * @since 1.0.0\n */\n\n protected notModifier: boolean = false;\n\n /**\n * Chains the sequence of assertions and modifiers applied.\n *\n * @internal\n * @since 1.0.0\n */\n\n protected assertionChain: Array<string> = [];\n\n /**\n * Tracks if the `.rejects` modifier has been applied.\n *\n * @internal\n * @since 1.0.0\n */\n\n protected rejectsModifier: boolean = false;\n\n /**\n * Tracks if the `.resolves` modifier has been applied.\n *\n * @internal\n * @since 1.0.0\n */\n\n protected resolvesModifier: boolean = false;\n\n /**\n * Creates a new MatcherService instance for the received value.\n *\n * @param received - The value or function under test.\n *\n * @since 1.0.0\n */\n\n constructor(protected received: T) {\n }\n\n /**\n * Applies the `.not` modifier, inverting matcher logic.\n *\n * @returns The matcher instance with `.not` applied, excluding chaining `.not`, `.rejects`, and `.resolves`.\n *\n * @since 1.0.0\n */\n\n get not(): Omit<this & PromisifiedMatchersType, 'not' | 'rejects' | 'resolved'> {\n this.notModifier = true;\n\n return <this & PromisifiedMatchersType>this;\n }\n\n\n /**\n * Applies the `.rejects` modifier, expecting the promise to reject.\n *\n * @throws Error - If `.resolves` was previously applied.\n *\n * @returns The matcher instance with `.rejects` applied, excluding chaining `.rejects` and `.resolves`.\n *\n * @since 1.0.0\n */\n\n get rejects(): Omit<PromisifiedMatchersType & this, 'rejects' | 'resolved'> {\n if (this.resolvesModifier) throw new Error('Cannot use \"rejects\" modifier after \"resolved\" modifier.');\n this.rejectsModifier = true;\n\n return <PromisifiedMatchersType & this>this;\n }\n\n /**\n * Applies the `.resolves` modifier, expecting the promise to resolve.\n *\n * @throws Error - If `.rejects` was previously applied.\n *\n * @returns The matcher instance with `.resolves` applied, excluding chaining `.rejects` and `.resolves`.\n *\n * @since 1.0.0\n */\n\n get resolves(): Omit<PromisifiedMatchersType & this, 'rejects' | 'resolved'> {\n if (this.rejectsModifier) throw new Error('Cannot use \"resolved\" modifier after \"rejects\" modifier.');\n this.resolvesModifier = true;\n\n return <PromisifiedMatchersType & this>this;\n }\n\n /**\n * Invokes the matcher synchronously or asynchronously based on modifiers.\n *\n * @param name - The matcher method name.\n * @param matcher - The matcher function to invoke.\n * @param args - Arguments to pass to the matcher.\n *\n * @returns Possibly a Promise resolving when async matchers are used, otherwise void.\n *\n * @since 1.0.0\n */\n\n protected invoke(name: string, matcher: FunctionType, args: Array<unknown>): void | Promise<void> {\n this.macherName = name;\n\n // todo remove invoke and invokeAsync from the stack\n if (this.rejectsModifier || this.resolvesModifier) {\n this.pushToChain(name);\n this.promise = this.resolvesModifier ? 'resolves' : 'rejects';\n\n return this.invokeAsync(matcher, args);\n }\n\n this.pushToChain(name);\n\n return matcher.call(this, ...args);\n }\n\n /**\n * Invokes the matcher asynchronously, handling promises and throwing detailed errors on mismatch.\n *\n * @param matcher - The matcher function to invoke.\n * @param args - Arguments to pass to the matcher.\n *\n * @throws xJetTypeError - If the received value or function result is not a Promise.\n * @throws xJetPromiseError - If the promise resolves or rejects contrary to the expected modifier.\n *\n * @returns A Promise resolving after matcher invocation.\n *\n * @since 1.0.0\n */\n\n protected async invokeAsync(matcher: FunctionType, args: Array<unknown>): Promise<void> {\n let isResolved = false;\n const isFunction = typeof this.received === 'function';\n const valueOrPromise = isFunction ? (this.received as FunctionType)() : this.received;\n\n if (!isPromise(valueOrPromise)) {\n throw new xJetTypeError({\n message: `${ RECEIVED('received') } value must be a promise or a function returning a promise`,\n assertionChain: this.assertionChain,\n received: {\n type: getType(valueOrPromise),\n value: valueOrPromise\n }\n });\n }\n\n try {\n this.received = <T> await valueOrPromise;\n isResolved = true;\n\n } catch (error) {\n if (this.resolvesModifier) this.throwPromiseError('Rejected', error);\n this.received = error as T;\n }\n\n if (isResolved && this.rejectsModifier) this.throwPromiseError('Resolved', this.received);\n\n return matcher.call(this, ...args);\n }\n\n /**\n * Adds modifiers and matcher name to the assertion chain for error message composition.\n *\n * @param name - The matcher method name to add.\n *\n * @internal\n * @since 1.0.0\n */\n\n private pushToChain(name: string): void {\n if (this.promise) this.assertionChain.push(this.promise);\n if (this.notModifier) this.assertionChain.push('not');\n this.assertionChain.push(name);\n }\n\n /**\n * Throws a detailed xJetPromiseError indicating promise resolution/rejection mismatch.\n *\n * @param kind - The kind of promise result encountered ('Resolved' or 'Rejected').\n * @param receivedValue - The actual resolved or rejected value.\n *\n * @throws xJetPromiseError\n *\n * @internal\n * @since 1.0.0\n */\n\n private throwPromiseError(kind: 'Resolved' | 'Rejected', receivedValue: unknown): never {\n const received = kind === 'Resolved' ? 'resolved' : 'rejected';\n const expected = kind === 'Resolved' ? 'rejected' : 'resolved';\n throw new xJetPromiseError({\n message: `${ RECEIVED('received') } promise ${ received } instead of ${ expected }`,\n received: receivedValue,\n promiseKind: kind,\n assertionChain: this.assertionChain\n });\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BoundMatchersType } from '@interfaces/matchers.interface';\n\n/**\n * Imports\n */\n\nimport { Matchers } from '@providers/matchers.provider';\nimport { Patterns } from '@providers/patterns.provider';\nimport { MatcherService } from '@services/matcher.service';\n\n/**\n * Dynamically adds matcher methods to the MatcherService prototype by iterating through\n * the Matchers object and defining properties for each matcher function.\n *\n * @remarks\n * This code creates a dynamic interface for matchers by:\n * 1. Iterating through each key in Matchers object\n * 2. Retrieving the corresponding matcher function\n * 3. Defining a property on the MatcherService prototype with the same name\n * 4. The property value is a function that invokes the matcher via the MatcherService.invoke method\n *\n * This approach allows for extending the matcher functionality without modifying the\n * MatcherService class directly. Each matcher function is bound to the MatcherService\n * instance context when invoked.\n *\n * @example\n * ```ts\n * // Define a matcher in Matchers object\n * const Matchers = {\n * isTrue: function(this: MatcherService) {\n * return this.invoke('isTrue', (actual) => actual === true);\n * }\n * };\n *\n * // The above code will automatically make this available:\n * xExpect(value).isTrue();\n * ```\n *\n * @see Matchers - The object containing all matcher functions\n * @see MatcherService - The service that processes and executes matchers\n *\n * @since 1.0.0\n */\n\nfor (const key of Object.keys(Matchers) as Array<keyof typeof Matchers>) {\n const proto = <MatcherService & BoundMatchersType> MatcherService.prototype;\n const matcherFn = Matchers[key];\n\n Object.defineProperty(proto, key, {\n value: function (...args: Array<unknown>) {\n return this.invoke(key, matcherFn, args);\n }\n });\n\n Object.defineProperty(proto[key], 'name', { value: key });\n}\n\n/**\n * Creates a new matcher service instance for the provided actual value to perform assertions against.\n *\n * @param received - The value to perform assertions on\n * @param rest - Additional arguments (not supported, included only for error handling)\n * @returns An augmented MatcherService instance with bound matcher methods\n *\n * @throws Error - When more than one argument is provided to the function\n *\n * @remarks\n * This function serves as the core implementation of the xExpect function. It creates a new\n * MatcherService instance with the provided value and augments it with all available matcher\n * methods defined in the BoundMatchersType. The resulting object provides a fluent API for\n * writing test assertions.\n *\n * @example\n * ```ts\n * // Basic usage with a single argument\n * const result = coreExpect(42);\n * result.toBe(42); // Passes\n *\n * // Will throw an error due to extra arguments\n * coreExpect(42, 'extra'); // Error: Expect takes at most one argument\n * ```\n *\n * @see MatcherService - The service that processes and executes matchers\n * @see BoundMatchersType - The type that defines all available matcher methods\n *\n * @since 1.0.0\n */\n\nconst coreExpect = (received: unknown, ...rest: Array<never>): MatcherService & BoundMatchersType => {\n if (rest.length > 0) {\n throw new Error(`Expect takes at most one argument. Received ${ rest.length + 1 } arguments instead.`);\n }\n\n return new MatcherService(received) as MatcherService & BoundMatchersType;\n};\n\n/**\n * Main assertion function that creates a new matcher service for the provided value and\n * extends it with additional pattern matching utilities.\n *\n * @remarks\n * This is the primary entry point for the assertion library. It combines the core expect\n * functionality with pattern matchers that allow for powerful asymmetric matching.\n * The `Object.assign` merges the core assertion function with pattern matchers, making\n * them available as properties on the xExpect function itself.\n *\n * @example\n * ```ts\n * // Basic value assertion\n * xExpect(value).toBe(expected);\n *\n * // Using pattern matchers\n * xExpect(value).toEqual(xExpect.any(Number));\n *\n * // Direct use of patterns\n * const matcher = xExpect.any(String);\n * ```\n *\n * @see coreExpect - The base assertion function\n * @see Patterns - Collection of asymmetric matcher patterns\n *\n * @since 2.0.0\n */\n\nexport const xExpect: typeof coreExpect & typeof Patterns = Object.assign(coreExpect, Patterns);\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BoundInterface } from '@shared/components/interfaces/polyfill-component.interface';\nimport type { FunctionLikeType, RejectedValueType, ResolvedValueType } from '@remotex-labs/xjet-expect';\nimport type { MockInvocationResultInterface, MocksStateInterface } from './interfaces/mock-state.interface';\n\n/**\n * @template DEFAULT_MOCK_NAME\n * A constant that holds the default name used for mocking purposes.\n * It is commonly used in testing scenarios to provide a standard mock identifier.\n *\n * @remarks\n * The value of `DEFAULT_MOCK_NAME` is set to 'xJet.mock()'. It is recommended\n * to use this variable as the default name to maintain consistency across\n * mock-related functionalities in your application.\n *\n * @since 1.0.0\n */\n\nconst DEFAULT_MOCK_NAME = 'xJet.mock()';\n\n/**\n * A class representing the mock state for tracking and managing the behavior of mocked functions or classes.\n *\n * @template ReturnType - The type of value returned by the mock function.\n * @template Context - The type representing the context (`this` value) used in the mock function.\n * @template Args - The types of arguments for the mocked function.\n *\n * @remarks\n * This class provides mechanisms to customize and manage the behavior of mocked functions or constructors.\n * It tracks invocation details, allows for behavior customization, and enables resetting or restoring the mock to its original state.\n *\n * @since v1.0.0\n */\n\nexport class MockState<ReturnType = unknown, Args extends Array<unknown> = unknown[], Context = unknown> extends Function {\n /**\n * List of all mocks that created\n */\n\n static mocks: Array<MockState> = [];\n\n /**\n * The `name` property represents the name of the mock function.\n */\n\n override name: string;\n\n /**\n * Flag to detect mock functions\n */\n\n readonly xJetMock: boolean = true;\n\n /**\n * The `state` property holds the detailed state of the mock invocations.\n * It tracks information such as the arguments passed, the results returned, the context (`this` value) used,\n * the instances created, and the order of invocations.\n * This data is automatically updated after each call to the mock.\n *\n * @template ReturnType - The type of value returned by the mock function.\n * @template Context - The type representing the context (`this` value) used in the mock function.\n * @template Args - The types of arguments for the mocked function.\n *\n * @see MocksStateInterface\n *\n * @since v1.0.0\n */\n\n private state: MocksStateInterface<ReturnType, Args, Context>;\n\n /**\n * A private function that restores the mocks original implementation.\n * It resets the mock to its initial state, typically used when restoring\n * the mock after a call to `mockReset` or `mockRestore`.\n *\n * This function is invoked internally to ensure that the mock behaves as\n * originally defined before any changes were made to its behavior or implementation.\n *\n * @since v1.0.0\n */\n\n private readonly restore: FunctionLikeType<void>;\n\n /**\n * A private array that stores the implementations queued to be executed\n * for future invocations of the mock.\n * Each function in this array is invoked in sequence when the mock function is called,\n * with the first queued implementation being used on the first call, the second on the second call, and so on.\n *\n * This property is used in conjunction with methods like `mockImplementationOnce`\n * to specify different behaviors for consecutive calls to the mock.\n *\n * @since v1.0.0\n */\n\n private queuedImplementations: Array<FunctionLikeType<ReturnType, Args, Context>> = [];\n\n /**\n * A private property that holds the current implementation of the mock function.\n * This function is executed whenever the mock is invoked, and can be changed\n * using methods like `mockImplementation` or `mockImplementationOnce`.\n *\n * The `implementation` allows for customizing the behavior of the mock,\n * such as returning specific values, throwing errors, or performing actions.\n *\n * @since v1.0.0\n */\n\n private implementation: FunctionLikeType<ReturnType, Args, Context> | undefined;\n\n /**\n * A private property that holds the original implementation of the mock function.\n * This is the initial function passed to the constructor that defines the mock's default behavior\n * before any customization.\n *\n * @template ReturnType - The type of value returned by the original function.\n * @template Args - The types of arguments for the original function.\n * @template Context - The type representing the context (`this` value) used in the original function.\n *\n * @remarks\n * This property stores the initial implementation provided when creating the mock.\n * If no implementation is provided during construction, it defaults to a function\n * that returns `undefined` cast to the appropriate return type.\n * Unlike `implementation` which can be modified, this property maintains a reference\n * to the original function for scenarios where the original behavior needs to be preserved\n * or restored.\n *\n * @see FunctionLikeType\n * @see MockState.original\n *\n * @since 1.0.0\n */\n\n private readonly originalImplementation: FunctionLikeType<ReturnType, Args, Context>;\n\n /**\n * Constructs a mock object that allows custom implementation, restore capability,\n * and optional naming functionality. This mock is proxied to handle function invocation\n * and class instantiation.\n *\n * @template ReturnType - The type of the value returned by the mock function.\n * @template Context - The type of the context (`this`) for the mock function.\n * @template Args - The type of arguments accepted by the mock function.\n *\n * @param implementation - Optional implementation for the mock function.\n * @param restore - Optional function to restore the mock to its initial state. Defaults to resetting to the provided implementation.\n * @param name - Optional name for the mock instance. Default to a predefined mock name if not provided.\n *\n * @returns A proxied mock object capable of behaving as a callable function or a constructible class.\n *\n * @remarks\n * The mock object can work as both a function and a class, using JavaScript's Proxy API. The restore functionality\n * allows resetting to the original state or implementation. If no implementation is provided, the mock remains uninitialized\n * but still functional.\n *\n * @see FunctionLikeType\n * @see VoidFunctionType\n *\n * @since 1.0.0\n */\n\n constructor(implementation?: FunctionLikeType<ReturnType, Args, Context>, restore?: FunctionLikeType<void>, name?: string) {\n super();\n this.name = name ?? DEFAULT_MOCK_NAME;\n this.state = this.initState();\n this.implementation = implementation;\n this.restore = restore ? restore : (): void => {\n this.implementation = implementation;\n };\n\n this.originalImplementation = implementation || ((): ReturnType => undefined as unknown as ReturnType);\n\n return <this> new Proxy(this, {\n apply: this.invokeFunction,\n construct: <ProxyHandler<object>['construct']> this.invokeClass\n });\n }\n\n /**\n * todo remove it\n * only for jest expect will support this mock\n */\n\n getMockName(): string {\n return this.name;\n }\n\n /**\n * Retrieves the current state of mocks.\n *\n * @return The current state of the mocks.\n * @see MocksStateInterface\n *\n * @since 1.0.0\n */\n\n get mock(): Readonly<MocksStateInterface<ReturnType, Args, Context>> {\n return this.state;\n }\n\n /**\n * Returns the original implementation of the function that was instrumented\n *\n * @returns The original function implementation that was wrapped or modified\n *\n * @remarks\n * This getter provides access to the unmodified function that was originally passed\n * to the instrumentation system. Useful for debugging, testing, or when you need\n * to bypass the instrumented behavior temporarily.\n *\n * @example\n * ```ts\n * const mockFn = jest.fn(x => x * 2);\n * // Later in test\n * const originalImplementation = mockFn.original;\n * expect(originalImplementation(5)).toBe(10);\n * ```\n *\n * @see FunctionLikeType\n *\n * @since 1.0.0\n */\n\n get original(): FunctionLikeType<ReturnType, Args, Context> {\n return this.originalImplementation;\n }\n\n /**\n * Clears the `mock.calls`, `mock.results`, `mock.contexts`, `mock.instances`, and `mock.invocationCallOrder` properties.\n *\n * @returns The current instance of the mock, allowing for method chaining.\n *\n * @remarks\n * This method resets the state of the mock function, clearing all invocation data and results,\n * ensuring that previous mock states do not affect the following tests.\n * Equivalent to calling `.mockClear()` on every mocked function.\n *\n * @see MockState.initState\n *\n * @since v1.0.0\n */\n\n mockClear(): this {\n this.state = this.initState();\n\n return this;\n }\n\n /**\n * Resets the mock function to its initial state.\n *\n * @returns The current instance of the mock, allowing for method chaining.\n *\n * @remarks\n * The `mockReset` method clears all invocation data and results by calling `mockClear()`, and also resets\n * the queued implementations,\n * removing any previously queued behavior set by methods like `mockImplementationOnce`.\n * This ensures that the mock is in a clean state and ready for new invocations or configurations.\n *\n * @see MockState.mockClear\n *\n * @since v1.0.0\n */\n\n mockReset(): this {\n this.mockClear();\n this.queuedImplementations = [];\n\n return this;\n }\n\n /**\n * Restores the mock function to its original implementation and resets its state.\n *\n * @returns The current instance of the mock, allowing for method chaining.\n *\n * @remarks\n * The `mockRestore` method does two things:\n * 1. It restores the mock to its initial implementation, which was set during the mocks creation or\n * via the `mockImplementation` method.\n * 2. It clears all tracking data, such as calls, results, contexts, instances, and invocation call order\n * by calling `mockReset()`, ensuring the mock is fully reset and ready for new invocations.\n *\n * This method is useful for ensuring that the mock is completely restored and cleared, making it behave as it did\n * when it was first created or last restored.\n *\n * @see MockState.restore\n * @see MockState.mockReset\n *\n * @since v1.0.0\n */\n\n mockRestore(): this {\n this.restore();\n this.mockReset();\n\n const index = MockState.mocks.indexOf(<MockState> <unknown> this);\n if (index !== -1) {\n MockState.mocks.splice(index, 1);\n }\n\n return this;\n }\n\n /**\n * Retrieves the mock implementation for a function, if available.\n *\n * @template ReturnType The type of the return value of the function.\n * @template Context The type of the `this` context for the function.\n * @template Args The type of the argument(s) of the function.\n *\n * @return A function matching `FunctionLikeType` that represents the mock implementation,\n * or `undefined` if no implementation is set.\n *\n * @remarks\n * This method returns the mock implementation associated with the instance.\n * If no mock implementation exists, it returns `undefined`.\n *\n * @since 1.0.0\n */\n\n getMockImplementation(): FunctionLikeType<ReturnType, Args, Context> | undefined {\n return this.implementation;\n }\n\n /**\n * Retrieves the next implementation from the queued implementations or defaults to the current implementation.\n *\n * @template ReturnType The return type of the function-like implementation.\n * @template Context The context in which the implementation executes.\n * @template Args The argument types expected by the implementation.\n *\n * @return The next implementation from the queue if available, or the current implementation.\n * Returns are `undefined` if no implementation is found.\n *\n * @remarks\n * This method first checks if there are any queued implementations available.\n * If a queued implementation exists, it will be removed from the queue and returned.\n * If the queue is empty, the primary current implementation is returned.\n * Returns are `undefined` if there is no implementation available.\n *\n * @since 1.0.0\n */\n\n getNextImplementation(): FunctionLikeType<ReturnType, Args, Context> | undefined {\n return this.queuedImplementations.length ? this.queuedImplementations.shift() : this.implementation;\n }\n\n /**\n * Replaces the default implementation of a mock function with the provided function.\n *\n * @template ReturnType - The type of the value returned by the implementation function.\n * @template Context - The context (`this`) expected by the implementation function.\n * @template Args - The types of the arguments expected by the implementation function.\n *\n * @param fn - The function to be used as the mock implementation. It defines\n * the behavior of the mock when called.\n *\n * @return Returns the instance of the current object for method chaining.\n *\n * @remarks\n * This method is useful when you need to mock the behavior of a function\n * dynamically during tests or in controlled scenarios.\n *\n * @since 1.0.0\n */\n\n mockImplementation(fn: FunctionLikeType<ReturnType, Args, Context>): this {\n this.implementation = fn;\n\n return this;\n }\n\n /**\n * Sets a mock implementation that will be used once for the next call to the mocked function.\n *\n * @template ReturnType The type of the value that the mock function will return.\n * @template Context The type of the `this` context for the mock function.\n * @template Args The type of arguments that the mock function will receive.\n *\n * @param fn - The function to be used as the mock implementation for the next call.\n * @returns The current instance, allowing for chaining of mock configurations.\n *\n * @remarks\n * The provided mock implementation will only be executed once. Further calls will fall back\n * to a different implementation, if provided, or the default behavior of the mock function.\n *\n * @example\n * ```ts\n * const mockFn = new MockState();\n *\n * // Set default implementation\n * mockFn.mockImplementation(() => 'default');\n *\n * // Set one-time behavior for the next call\n * mockFn.mockImplementationOnce(() => 'first call');\n *\n * console.log(mockFn()); // Output: 'first call' (from mockImplementationOnce)\n * console.log(mockFn()); // Output: 'default' (from mockImplementation)\n * ```\n *\n * @see FunctionLikeType\n *\n * @since 1.0.0\n */\n\n mockImplementationOnce(fn: FunctionLikeType<ReturnType, Args, Context>): this {\n this.queuedImplementations.push(fn);\n\n return this;\n }\n\n /**\n * Sets a mock implementation to always return a specified value when invoked.\n *\n * @template ReturnType The type of the value returned by the mock implementation.\n *\n * @param value - The value to always return when the mock function is called.\n * @return The current instance for chaining.\n *\n * @remarks\n * This method overrides any previous mock implementation configured for the function.\n *\n * @example\n * ```ts\n * const mockFn = new MockState();\n *\n * // Set mock to return 'Hello World' on each call\n * mockFn.mockReturnValue('Hello World');\n *\n * console.log(mockFn()); // Output: 'Hello World'\n * console.log(mockFn()); // Output: 'Hello World'\n * ```\n *\n * @since 1.0.0\n */\n\n mockReturnValue(value: ReturnType): this {\n this.mockImplementation(() => value);\n\n return this;\n }\n\n /**\n * Sets up a mock function to always resolve a promise with the specified value when called.\n *\n * @template ResolvedValueType - The type of the value to be resolved by the promise.\n * @template ReturnType - The return type of the function, which should include a Promise of the specified resolved value type.\n *\n * @param value - The value to be returned as the resolved value of the promise.\n * @returns The mock function instance, enabling method chaining.\n *\n * @remarks\n * This method is particularly useful for mocking asynchronous functions that return promises.\n * It ensures that the mock function resolves with the provided value every time it is called.\n *\n * @example\n * ```ts\n * const mockFn = new MockState<Promise<string>>();\n *\n * // Set mock to return a resolved promise with the value 'Success'\n * mockFn.mockResolvedValue('Success');\n *\n * mockFn().then((result: string) => {\n * console.log(result); // Output: 'Success'\n * });\n * ```\n *\n * @since 1.0.0\n */\n\n mockResolvedValue(value: ResolvedValueType<ReturnType>): this {\n this.mockImplementation(() => <ReturnType> Promise.resolve(value));\n\n return this;\n }\n\n /**\n * Sets a mock implementation for a single call that resolves to the specified value.\n *\n * @template ReturnType The type of the resolved value.\n * @template ResolvedValueType The type of the input value to be resolved.\n *\n * @param value - The value that the promise should resolve with when the mock is called once.\n * @return The current mock object instance, enabling method chaining.\n *\n * @remarks\n * This method is useful for defining custom behavior for a specific invocation of a mocked function,\n * returning a resolved promise with the provided value.\n *\n * @example\n * ```ts\n * const mockFn = new MockState(async () => {\n * return 'end';\n * });\n *\n * // Set mock to return a resolved promise with the value 'Success'\n * mockFn.mockResolvedValueOnce('Success');\n *\n * mockFn().then((result: string) => {\n * console.log(result); // Output: 'Success'\n * });\n *\n * mockFn().then((result: string) => {\n * console.log(result); // Output: 'end'\n * });\n * ```\n *\n * @since 1.0.0\n */\n\n mockResolvedValueOnce(value: ResolvedValueType<ReturnType>): this {\n this.mockImplementationOnce(() => <ReturnType> Promise.resolve(value));\n\n return this;\n }\n\n /**\n * Sets the return value of the mock function for a single call.\n *\n * @template ReturnType The type of the value to be returned.\n *\n * @param value - The value to be returned by the mock function for the next call.\n * @return The mock function instance, allowing for method chaining.\n *\n * @remarks\n * This method only affects the return value for the next call to the mock function.\n * All further calls will use the usual mock implementation or other specified behaviors.\n *\n * @example\n * ```ts\n * const mockFn = new MockState();\n *\n * // Set default return value\n * mockFn.mockReturnValue('Default Value');\n *\n * // Set one-time return value for the next call\n * mockFn.mockReturnValueOnce('First Call');\n * mockFn.mockReturnValueOnce('Second Call');\n *\n * console.log(mockFn()); // Output: 'First Call' (from mockReturnValueOnce)\n * console.log(mockFn()); // Output: 'Second Call' (from mockReturnValueOnce)\n * console.log(mockFn()); // Output: 'Default Value' (from mockReturnValue)\n * ```\n *\n * @since 1.0.0\n */\n\n mockReturnValueOnce(value: ReturnType): this {\n this.mockImplementationOnce(() => value);\n\n return this;\n }\n\n /**\n * Mocks the method to always return a rejected Promise with the specified value.\n *\n * @template ReturnType - The expected type of the return value for the mocked method.\n * @template RejectedValueType - The type of the value used to reject the Promise.\n *\n * @param value - The value with which the mocked Promise will be rejected.\n *\n * @return The current instance of the mock for chaining purposes.\n *\n * @remarks\n * This method is useful for testing scenarios where the function being mocked\n * is expected to reject with a specific value.\n *\n * @example\n * ```ts\n * const mockFn = new MockState<Promise<string>>();\n *\n * // Set mock to return a rejected promise with the value 'Error'\n * mockFn.mockRejectedValue('Error');\n *\n * mockFn().catch(error => {\n * console.log(error); // Output: 'Error'\n * });\n * ```\n *\n * @since 1.0.0\n */\n\n mockRejectedValue(value: RejectedValueType<ReturnType>): this {\n this.mockImplementation(() => <ReturnType> Promise.reject(value));\n\n return this;\n }\n\n /**\n * Adds a one-time rejection with the provided value to the mock function.\n *\n * @template ReturnType - The type of the value the mock function would return.\n *\n * @param value - The value to reject the promise with in the mock function.\n * @return The current instance of the mock function, allowing for method chaining.\n *\n * @remarks\n * This method configures a mock function to return a rejected promise with the\n * specified value the next time it is called. After the rejection occurs, the\n * mock function's behavior will revert to the next defined mock behavior, or\n * to the default behavior if no behaviors are defined.\n *\n * @example\n * ```ts\n * const mockFn = new MockState<Promise<string>>();\n *\n * // Set default rejected value\n * mockFn.mockRejectedValue('Default Error');\n *\n * // Set one-time rejected value for the next call\n * mockFn.mockRejectedValueOnce('First Call Error');\n *\n * mockFn().catch(error => {\n * console.log(error); // Output: 'First Call Error' (from mockRejectedValueOnce)\n * });\n *\n * mockFn().catch(error => {\n * console.log(error); // Output: 'Default Error' (from mockRejectedValue)\n * });\n * ```\n *\n * @since 1.0.0\n */\n\n mockRejectedValueOnce(value: RejectedValueType<ReturnType>): this {\n this.mockImplementationOnce(() => <ReturnType> Promise.reject(value));\n\n return this;\n }\n\n // todo: withImplementation\n\n /**\n * Custom inspection method for the `util.inspect` function.\n *\n * @returns A string representing the mock constructor with the specified `name` property.\n *\n * @remarks\n * This method is triggered when `util.inspect` is invoked on an instance of this class.\n * It provides a customized string representation of the class instance, enhancing debugging\n * and inspection output for developers.\n *\n * @example\n * ```ts\n * const mockFn = new MockState();\n * mockFn.name = 'MyMockFunction';\n *\n * // Inspect the mock function\n * console.log(mockFn); // Output: <Mock Constructor MyMockFunction>\n * ```\n *\n * @since 1.0.0\n */\n\n [Symbol.for('nodejs.util.inspect.custom')](): string {\n return `<Mock Constructor ${ this.name }>`;\n }\n\n /**\n * Initializes and returns the state object for mock function tracking.\n *\n * @return An object containing the initialized mock function state.\n *\n * @remarks\n * The state object contains the structure necessary to keep track of\n * calls, results, contexts, instances, and invocation orders of the function.\n *\n * @see MocksStateInterface\n *\n * @since v1.0.0\n */\n\n private initState(): MocksStateInterface<ReturnType, Args, Context> {\n return {\n calls: [],\n results: [],\n lastCall: undefined,\n contexts: [],\n instances: [],\n invocationCallOrder: []\n };\n }\n\n /**\n * Invokes the next implementation of a mock function with the provided context and arguments.\n *\n * @template Context The type of `this` context in which the function is invoked.\n * @template Args The type of the arguments passed to the function.\n * @template ReturnType The type of the return value, of the function being invoked.\n *\n * @param thisArg - The context (`this`) in which the function is executed.\n * @param args - The arguments to be passed to the function.\n *\n * @returns The result of the function invocation, which is either the return value, the thrown error, or undefined.\n *\n * @remarks\n * This method simulates the function call for a mocked implementation. It tracks all invocations,\n * including the call order, the provided arguments, and the context. It handles binding, default\n * arguments, and maintains a record of results (either successful returns or thrown errors).\n *\n * @since 1.0.0\n */\n\n private invoke(thisArg: Context, args: Args): ReturnType | undefined {\n let thisContext = thisArg;\n const impl = <FunctionLikeType<ReturnType, Args, Context> & BoundInterface> this.getNextImplementation();\n\n const argsArray = <Array<unknown>> args;\n if (typeof impl === 'function') {\n if (impl.__boundArgs) argsArray.unshift(...impl.__boundArgs);\n if (impl.__boundThis) thisContext = <Context> impl.__boundThis;\n }\n\n this.state.calls.push(<Args> argsArray);\n this.state.contexts.push(<Context> thisContext);\n this.state.invocationCallOrder.push(this.state.invocationCallOrder.length + 1);\n\n let result: MockInvocationResultInterface<ReturnType>;\n const index = this.state.results.push({ value: undefined, type: 'incomplete' }) - 1;\n\n if (impl) {\n try {\n const value = impl.call(<Context> undefined, ...args);\n result = { type: 'return', value };\n } catch (error) {\n result = { value: error, type: 'throw' };\n }\n } else {\n result = { type: 'return', value: undefined };\n }\n\n this.state.lastCall = args;\n this.state.results[index] = result;\n\n return <ReturnType> result.value;\n }\n\n /**\n * Invokes a function within a specific context and with provided arguments.\n *\n * @template Context The type of the context in which the function is invoked.\n * @template Args The type of the arguments passed to the function.\n * @template ReturnType The type of the value that the invoked function returns.\n *\n * @param target - The instance of the class containing the method to be invoked.\n * @param thisArg - The context object that will be bound to the invoked function.\n * @param argumentsList - The list of arguments to pass to the invoked function.\n * @returns The result of the invoked function or `undefined` if no value is returned.\n *\n * @remarks\n * This method modifies the state of the `target` instance by adding the `thisArg`\n * to the `target.state.instances` array before invoking the function.\n *\n * @since 1.0.0\n */\n\n private invokeFunction(target: this, thisArg: Context, argumentsList: Args): ReturnType | undefined {\n target.state.instances.push(thisArg);\n\n return target.invoke.call(target, thisArg, argumentsList);\n }\n\n /**\n * Invokes a class method on the provided target with specified arguments and a new target.\n *\n * @template Args - The type of arguments to be passed to the invoked method.\n *\n * @param target - The object on which the class method is invoked.\n * @param argArray - The array of arguments to pass to the invoked method.\n * @param newTarget - The new object used as the invocation context.\n * @returns The result of the invocation, typically an object. If the result is not an object,\n * the `newTarget` is returned instead.\n *\n * @remarks\n * This method ensures that the result is stored in the `instances` array of the target's state\n * if it is detected as a proper class instance. Otherwise, the `newTarget` is registered.\n *\n * @since 1.0.0\n */\n\n private invokeClass(target: this, argArray: Args, newTarget: object): object {\n const result = target.invoke.call(target, <Context> newTarget, argArray);\n const isClassInstance = typeof result === 'object' && result !== null && result.constructor;\n target.state.instances.push(isClassInstance ? <Context> result : <Context> newTarget);\n\n return typeof result === 'object' ? <object> result : newTarget;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConstructorType } from '@remotex-labs/xjet-expect';\nimport type { InjectableOptionsInterface, TokenElementType } from '@symlinks/interfaces/symlinks.interface';\n\n/**\n * Stores singleton instances of injectable classes.\n *\n * @since 1.0.0\n */\n\nconst SINGLETONS = new Map<ConstructorType, unknown>();\n\n/**\n * Stores metadata for classes marked as injectable via `@Injectable`.\n *\n * @internal\n * @since 1.0.0\n */\n\nconst INJECTABLES = new Map<ConstructorType, InjectableOptionsInterface>();\n\n/**\n * Marks a class as injectable and stores its configuration metadata.\n *\n * @template T - The type of the class instance\n * @template Args - The types of arguments accepted by the constructor, defaults to `unknown[]`\n *\n * @param options - Optional configuration for the injectable, including scope and factory\n *\n * @example\n * ```ts\n * @Injectable({ scope: 'singleton' })\n * class MyService {}\n * ```\n *\n * @see InjectableOptionsInterface\n * @since 1.0.0\n */\n\nexport function Injectable<T = unknown, Args extends Array<unknown> = unknown[]>(options?: InjectableOptionsInterface) {\n return function (target: new (...args: Args) => T): void {\n INJECTABLES.set(target, options || {});\n };\n}\n\n/**\n * Resolves and returns an instance of the given injectable token.\n *\n * @template T - The type of the instance to return\n * @template Args - The types of arguments passed to the constructor or factory\n *\n * @param token - The injectable class or token to resolve\n * @param args - Arguments to pass to the constructor or factory\n *\n * @returns The resolved instance of type `T`\n *\n * @throws Error - If the token is not registered as injectable via `@Injectable`\n *\n * @remarks\n * If the injectable is marked with scope `'singleton'`, the same instance will be returned\n * on the following calls. Otherwise, a new instance is created for each call.\n *\n * @example\n * ```ts\n * const service = inject(MyService);\n * ```\n *\n * @see TokenElementType\n * @since 1.0.0\n */\n\nexport function inject<T, Args extends Array<unknown>>(token: TokenElementType<T, Args>, ...args: Args): T {\n if (SINGLETONS.has(token)) return <T>SINGLETONS.get(token);\n\n const metadata = INJECTABLES.get(token);\n if (!metadata) throw new Error(`Cannot inject ${ token.name } \u2013 not marked @Injectable`);\n\n const instance: T = metadata.factory\n ? <T>metadata.factory(...args)\n : new token(...args);\n\n if (metadata?.scope === 'singleton') {\n SINGLETONS.set(token, instance);\n }\n\n return instance;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ReadMethodType, WriteMethodType } from '@components/interfaces/buffer-component.interface';\n\n/**\n * Retrieves a bound buffer method for reading from or writing to a Buffer\n *\n * @template T - The type of the returned buffer method\n *\n * @param buffer - The Buffer instance to get the method from\n * @param operation - The operation type ('read' or 'write')\n * @param type - The data type to read or write (e.g., 'UInt8', 'Int16LE')\n * @returns The bound buffer method of the specified type\n *\n * @throws Error - When the type parameter is empty or invalid\n * @throws Error - When the method does not exist on the Buffer object\n *\n * @remarks\n * This is a utility function that dynamically retrieves and binds Buffer methods.\n * It constructs method names by combining the operation and type parameters.\n * The returned method is bound to the buffer instance for immediate use.\n *\n * @example\n * ```ts\n * const buffer = Buffer.from([0x01, 0x02, 0x03, 0x04]);\n * const readUInt16LE = getBufferMethod<(offset: number) => number>(buffer, 'read', 'UInt16LE');\n * const value = readUInt16LE(0); // Returns 513 (0x0201)\n * ```\n *\n * @since 2.0.0\n */\n\nexport function getBufferMethod<T>(buffer: Buffer, operation: 'read' | 'write', type: string): T {\n const methodName = `${operation}${type}` as keyof Buffer;\n const method = <WriteMethodType<number>> buffer[methodName];\n\n if (!type)\n throw new Error(`Invalid type(${ type }) parameter`);\n\n if (!(methodName in buffer))\n throw new Error(`Method \"${ methodName.toString() }\" does not exist on Buffer`);\n\n return method.bind(buffer) as T;\n}\n\n/**\n * Gets a bound read method from a Buffer for the specified data type\n *\n * @template T - The type of value that will be read, defaults to number (number | bigint)\n *\n * @param buffer - The Buffer instance to read from\n * @param type - The data type to read (e.g., 'UInt8', 'Int16LE')\n * @returns A bound read method of the specified type\n *\n * @throws Error - When the type parameter is empty or invalid\n * @throws Error - When the method does not exist on the Buffer object\n *\n * @remarks\n * This function is a specialized wrapper around getBufferMethod that\n * specifically retrieves read methods from the Buffer instance.\n * It simplifies the API by fixing the operation parameter to 'read'.\n *\n * @example\n * ```ts\n * const buffer = Buffer.from([0x01, 0x02, 0x03, 0x04]);\n * const readUInt16LE = readMethod(buffer, 'UInt16LE');\n * const value = readUInt16LE(0); // Returns 513 (0x0201)\n * ```\n *\n * @see getBufferMethod - The underlying implementation\n * @since 2.0.0\n */\n\nexport function readMethod<T extends number | bigint = number>(buffer: Buffer, type: string): ReadMethodType<T> {\n return getBufferMethod<ReadMethodType<T>>(buffer, 'read', type);\n}\n\n/**\n * Gets a bound write method from a Buffer for the specified data type\n *\n * @template T - The type of value that will be written, defaults to number\n *\n * @param buffer - The Buffer instance to write to\n * @param type - The data type to write (e.g., 'UInt8', 'Int16LE')\n * @returns A bound write method of the specified type\n *\n * @throws Error - When the type parameter is empty or invalid\n * @throws Error - When the method does not exist on the Buffer object\n *\n * @remarks\n * This function is a specialized wrapper around getBufferMethod that\n * specifically retrieves write methods from the Buffer instance.\n * It simplifies the API by fixing the operation parameter to 'write'.\n *\n * @example\n * ```ts\n * const buffer = Buffer.alloc(4);\n * const writeUInt16LE = writeMethod(buffer, 'UInt16LE');\n * writeUInt16LE(513, 0); // Writes [0x01, 0x02, 0x00, 0x00] to buffer\n * ```\n *\n * @see getBufferMethod - The underlying implementation\n * @since 2.0.0\n */\n\nexport function writeMethod<T extends number | bigint = number>(buffer: Buffer, type: string): WriteMethodType<T> {\n return getBufferMethod<WriteMethodType<T>>(buffer, 'write', type);\n}\n\n/**\n * Splits a buffer into two parts with an optional gap between them\n *\n * @param buffer - The Buffer instance to split\n * @param splitPosition - The position at which to split the buffer\n * @param skipBytes - The number of bytes to skip after the split position\n * @returns A tuple containing two Buffer instances: the portion before the split and the portion after the gap\n *\n * @throws Error - When the split position is negative\n * @throws Error - When the split position exceeds the buffer length\n *\n * @remarks\n * This function divides a buffer at the specified position and allows skipping a number of bytes\n * after the split position before creating the second buffer.\n * If the skip extends beyond the buffer's length, the second buffer will be empty.\n *\n * @example\n * ```ts\n * const buffer = Buffer.from([1, 2, 3, 4, 5, 6]);\n * const [first, second] = splitBufferWithGap(buffer, 2, 1);\n * // first: Buffer [1, 2]\n * // second: Buffer [4, 5, 6]\n * ```\n *\n * @since 2.0.0\n */\n\nexport function splitBufferWithGap(buffer: Buffer, splitPosition: number, skipBytes: number = 0): [ Buffer, Buffer ] {\n if (splitPosition < 0)\n throw new Error('Split position cannot be negative');\n\n if (splitPosition > buffer.length)\n throw new Error('Split position cannot exceed buffer length');\n\n const beforeSplit = buffer.subarray(0, splitPosition);\n const afterPosition = splitPosition + skipBytes;\n\n if (afterPosition >= buffer.length)\n return [ beforeSplit, Buffer.alloc(0) ];\n\n return [ beforeSplit, buffer.subarray(afterPosition) ];\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n StructType,\n StructDataType,\n StructContextInterface\n} from '@components/interfaces/struct-component.interface';\n\n/**\n * Imports\n */\n\nimport { splitBufferWithGap } from '@components/buffer.component';\n\n/**\n * Reads a single structure from a binary buffer at a specified position\n *\n * @param arrayOffset - Optional offset to apply when reading structures within an array (defaults to 0)\n * @returns The deserialized structure object with its properties populated from binary data\n *\n * @throws Error - If the binary data is malformed or cannot be deserialized into the expected structure\n *\n * @remarks\n * This function calculates the absolute position in the buffer by combining the base offset,\n * the structure's defined position, and any additional array offset. It then uses the structure's\n * type definition to deserialize the binary data at that position into a JavaScript object.\n * The callback provided to toObject updates the context's offset to account for any dynamic-sized data.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: myBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct\n * }\n * };\n *\n * const person = readSingleStruct.call(context);\n * ```\n *\n * @see writeStruct\n * @see readStructArray\n *\n * @since 2.0.0\n */\n\nexport function readSingleStruct(this: StructContextInterface, arrayOffset: number = 0): StructType {\n const { position, type } = this.descriptor;\n const absolutePosition = this.offset + position + arrayOffset;\n\n return <StructType> type.toObject(this.buffer.subarray(absolutePosition), (offset) => {\n this.offset += offset;\n });\n}\n\n/**\n * Reads an array of structures from a binary buffer\n *\n * @returns An array of deserialized structure objects\n *\n * @throws Error - If the binary data is malformed or cannot be deserialized into the expected structures\n *\n * @remarks\n * This function extracts multiple structure instances from a binary buffer based on the descriptor's\n * arraySize property. It pre-allocates the result array for performance and calls readSingleStruct\n * for each structure in the array, calculating the appropriate offset based on the structure size.\n * The arraySize in the descriptor determines how many structures will be read from the buffer.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: myBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct,\n * arraySize: 5,\n * size: 32\n * }\n * };\n *\n * const people = readStructArray.call(context);\n * // Returns an array of 5 person objects\n * ```\n *\n * @see readSingleStruct\n * @see writeStructArray\n *\n * @since 2.0.0\n */\n\nexport function readStructArray(this: StructContextInterface): Array<StructType> {\n const result: Array<StructType> = [];\n const { arraySize = 0, size } = this.descriptor;\n\n result.length = arraySize;\n for (let i = 0; i < arraySize; i++) {\n result[i] = readSingleStruct.call(this, i * size);\n }\n\n return result;\n}\n\n/**\n * Reads a structure or array of structures from a binary buffer based on the descriptor\n *\n * @returns A single structure object or an array of structure objects depending on the descriptor configuration\n *\n * @throws Error - If the binary data is malformed or cannot be deserialized into the expected structure(s)\n *\n * @remarks\n * This function serves as a dispatcher that determines whether to read a single structure or\n * an array of structures based on the descriptor's configuration. It checks if the descriptor\n * contains an arraySize property with a truthy value, and if so, delegates to readStructArray.\n * Otherwise, it calls readSingleStruct to deserialize a single structure instance.\n *\n * @example\n * ```ts\n * // For a single structure descriptor\n * const singleContext = {\n * buffer: myBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct\n * }\n * };\n * const person = readStruct.call(singleContext);\n *\n * // For an array structure descriptor\n * const arrayContext = {\n * buffer: myBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct,\n * arraySize: 5,\n * size: 32\n * }\n * };\n * const people = readStruct.call(arrayContext);\n * ```\n *\n * @see writeStruct\n * @see readStructArray\n * @see readSingleStruct\n *\n * @since 2.0.0\n */\n\nexport function readStruct(this: StructContextInterface): StructDataType {\n if(('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return readStructArray.call(this);\n\n return readSingleStruct.call(this);\n}\n\n/**\n * Writes a single structure to a binary buffer at a specified position\n *\n * @param value - The structure object to serialize into binary format\n * @param arrayOffset - Optional offset to apply when writing structures within an array (defaults to 0)\n *\n * @throws Error - If the structure cannot be properly serialized or buffer operations fail\n *\n * @remarks\n * This function serializes a structure object into binary data and writes it to the buffer at\n * the calculated absolute position. It handles null/undefined values by defaulting to an empty object.\n * The function splits the existing buffer at the insertion point with appropriate sizing,\n * then reconstructs the buffer by concatenating the start segment, the serialized structure,\n * and the end segment. If the serialized structure is larger than the expected size, it also\n * adjusts the current offset to account for the dynamic sizing.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: existingBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct,\n * size: 32\n * }\n * };\n *\n * const person = { name: \"John\", age: 30 };\n * writeSingleStruct.call(context, person);\n * ```\n *\n * @see readSingleStruct\n * @see writeStructArray\n *\n * @since 2.0.0\n */\n\nexport function writeSingleStruct(this: StructContextInterface, value: StructType, arrayOffset: number = 0): void {\n value ??= {};\n const { position, type, size } = this.descriptor;\n const StructBuffer = type.toBuffer(value);\n const absolutePosition = this.offset + position + arrayOffset;\n const [ start, end ] = splitBufferWithGap(this.buffer, absolutePosition, size);\n\n this.buffer = Buffer.concat([ start, StructBuffer, end ]);\n if (StructBuffer.length > size) {\n this.offset += (StructBuffer.length - size);\n }\n}\n\n/**\n * Writes an array of structures to a binary buffer\n *\n * @param values - The array of structure objects to serialize into binary format\n * @returns Nothing\n *\n * @throws Error - If the structures cannot be properly serialized or buffer operations fail\n *\n * @remarks\n * This function writes multiple structure instances to the binary buffer based on the descriptor's\n * arraySize property. It iterates through each position in the array and calls writeSingleStruct\n * for each structure, calculating the appropriate offset based on the structure size.\n * If there are fewer values provided than the arraySize specification, empty objects will be\n * written for the remaining positions to ensure the full array space is properly initialized.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: existingBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct,\n * arraySize: 5,\n * size: 32\n * }\n * };\n *\n * const people = [\n * { name: \"John\", age: 30 },\n * { name: \"Jane\", age: 28 },\n * { name: \"Bob\", age: 45 }\n * ];\n *\n * writeStructArray.call(context, people);\n * // Writes the 3 provided people and 2 empty objects to fill the array\n * ```\n *\n * @see readStructArray\n * @see writeSingleStruct\n *\n * @since 2.0.0\n */\n\nexport function writeStructArray(this: StructContextInterface, values: Array<StructType>): void {\n const { arraySize = 0, size } = this.descriptor;\n\n for (let i = 0; i < arraySize; i++) {\n const elementValue = i < values.length ? values[i] : {};\n writeSingleStruct.call(this, elementValue, i * size);\n }\n}\n\n/**\n * Writes a structure or array of structures to a binary buffer based on the descriptor\n *\n * @param value - The structure object or array of structure objects to serialize\n *\n * @throws Error - If the structure(s) cannot be properly serialized or buffer operations fail\n *\n * @remarks\n * This function serves as a dispatcher that determines whether to write a single structure or\n * an array of structures based on the descriptor's configuration. It checks if the descriptor\n * contains an arraySize property with a truthy value, and if so, delegates to writeStructArray.\n * Otherwise, it calls writeSingleStruct to serialize a single structure instance.\n *\n * The function handles type mismatches between the provided value and the descriptor configuration:\n * - When descriptor indicates an array but a single object is provided, it wraps the object in an array\n * - When descriptor indicates a single object but an array is provided, it uses the first element of the array\n *\n * @example\n * ```ts\n * // For a single structure descriptor\n * const singleContext = {\n * buffer: existingBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct\n * }\n * };\n * const person = { name: \"John\", age: 30 };\n * writeStruct.call(singleContext, person);\n *\n * // For an array structure descriptor\n * const arrayContext = {\n * buffer: existingBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct,\n * arraySize: 3,\n * size: 32\n * }\n * };\n * const people = [\n * { name: \"John\", age: 30 },\n * { name: \"Jane\", age: 28 }\n * ];\n * writeStruct.call(arrayContext, people);\n * ```\n *\n * @see readStruct\n * @see writeStructArray\n * @see writeSingleStruct\n *\n * @since 2.0.0\n */\n\nexport function writeStruct(this: StructContextInterface, value: StructDataType): void {\n if (('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return writeStructArray.call(this, Array.isArray(value) ? value : [ value ]);\n\n return writeSingleStruct.call(this, Array.isArray(value) ? (value[0] || {}) : value);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n PrimitiveType,\n PrimitiveDataType,\n FloatPrimitiveType,\n PrimitiveContextInterface,\n PositionedPrimitiveDescriptorType\n} from '@components/interfaces/primitive-component.interface';\n\n/**\n * Imports\n */\n\nimport { readMethod, writeMethod } from '@components/buffer.component';\n\n/**\n * Maps primitive data types to their size in bits\n *\n * @returns A record mapping each primitive type to its size in bits\n *\n * @remarks\n * This constant provides a mapping between all supported primitive types and their\n * corresponding bit sizes. The sizes are expressed in bits, not bytes.\n * - 8-bit types: Int8, UInt8\n * - 16-bit types: Int16LE, Int16BE, UInt16LE, UInt16BE\n * - 32-bit types: Int32LE, Int32BE, UInt32LE, UInt32BE, FloatLE, FloatBE\n * - 64-bit types: BigInt64LE, BigInt64BE, BigUInt64LE, BigUInt64BE, DoubleLE, DoubleBE\n *\n * The 'LE' and 'BE' suffixes indicate Little Endian and Big Endian byte order respectively.\n *\n * @example\n * ```ts\n * // Get the size of a UInt32LE\n * const bitSize = PRIMITIVE_TYPE_SIZES['UInt32LE']; // 32\n *\n * // Calculate byte size\n * const byteSize = PRIMITIVE_TYPE_SIZES['BigInt64BE'] / 8; // 8 bytes\n * ```\n *\n * @since 2.0.0\n */\n\nexport const PRIMITIVE_TYPE_SIZES: Record<PrimitiveType | FloatPrimitiveType, number> = {\n 'Int8': 8,\n 'UInt8': 8,\n 'Int16LE': 16,\n 'Int16BE': 16,\n 'UInt16LE': 16,\n 'UInt16BE': 16,\n 'FloatLE': 32,\n 'FloatBE': 32,\n 'Int32LE': 32,\n 'Int32BE': 32,\n 'UInt32LE': 32,\n 'UInt32BE': 32,\n 'DoubleLE': 64,\n 'DoubleBE': 64,\n 'BigInt64LE': 64,\n 'BigInt64BE': 64,\n 'BigUInt64LE': 64,\n 'BigUInt64BE': 64\n};\n\n/**\n * Parses a string representation of a primitive type descriptor into a structured positioned object\n *\n * @param field - String representation of the primitive descriptor in format \"type\" or \"type[size]\"\n * @param position - The starting byte position of this element within the buffer\n * @returns A structured PositionedPrimitiveDescriptorType object\n *\n * @throws Error - When the descriptor format is invalid\n * @throws Error - When the primitive type is not supported\n *\n * @remarks\n * This function converts a string-based primitive type specification into a structured descriptor object with positioning information.\n * The input string can be in one of two formats:\n * - A simple type name (e.g., \"UInt8\", \"Int16LE\")\n * - An array type with size (e.g., \"UInt8[10]\", \"Float32[4]\")\n *\n * The function validates that:\n * 1. The input string matches the expected pattern for a valid primitive descriptor\n * 2. The specified type is supported by checking against the PRIMITIVE_TYPE_SIZES registry\n *\n * If the descriptor includes an array size specification, it is parsed as an integer.\n * For non-array types, the arraySize field will be undefined.\n *\n * @example\n * ```ts\n * // Parse a simple primitive type at offset 0\n * const descriptor1 = parsePrimitiveDescriptor('UInt8');\n * // Returns: { type: 'UInt8', size: 1, offset: 0, arraySize: undefined }\n *\n * // Parse an array primitive type at offset 4\n * const descriptor2 = parsePrimitiveDescriptor('Int16LE[5]', 4);\n * // Returns: { type: 'Int16LE', size: 2, offset: 4, arraySize: 5 }\n *\n * // The following would throw errors:\n * // Invalid format: parsePrimitiveDescriptor('UInt8[]');\n * // Invalid format: parsePrimitiveDescriptor('8UInt');\n * // Invalid type: parsePrimitiveDescriptor('Unknown[5]');\n * ```\n *\n * @see PRIMITIVE_TYPE_SIZES\n * @see PositionedPrimitiveDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function parsePrimitiveDescriptor(field: string, position: number = 0): PositionedPrimitiveDescriptorType {\n const pattern = /^([A-Za-z][A-Za-z0-9]*)(?:\\[(\\d+)\\])?$/i;\n const match = <[string, PrimitiveType, string]> field.match(pattern);\n\n if (!match)\n throw new Error(`Invalid primitive descriptor: ${ field }`);\n\n const size = PRIMITIVE_TYPE_SIZES[match[1]];\n if (!size)\n throw new Error(`Invalid primitive type: ${ match[1] }`);\n\n const type = match[1];\n const arraySize = match[2] ? parseInt(match[2]) : undefined;\n\n return { type, position, size: size / 8, arraySize, kind: 'primitive' };\n}\n\n/**\n * Reads a single primitive value from the buffer at the specified position\n *\n * @param arrayOffset - Optional offset within an array structure, defaults to 0\n *\n * @returns The primitive value (number or bigint) read from the buffer\n *\n * @remarks\n * Uses the descriptor's position and type information to determine where and how to read from the buffer.\n * The absolute position is calculated by adding the context offset, descriptor position, and any array offset.\n *\n * The function supports all primitive types defined in the PrimitiveType interface, including both\n * signed and unsigned integers of various sizes with their respective endianness formats.\n *\n * @example\n * ```ts\n * const context: PrimitiveContextInterface = {\n * buffer: Buffer.alloc(16),\n * offset: 4,\n * descriptor: {\n * position: 2,\n * type: 'UInt32LE'\n * }\n * };\n *\n * const value = readSinglePrimitive.call(context);\n * ```\n *\n * @see readMethod\n * @see PrimitiveContextInterface\n *\n * @since 2.0.0\n */\n\nexport function readSinglePrimitive(this: PrimitiveContextInterface, arrayOffset: number = 0): number | bigint {\n const { position, type } = this.descriptor;\n const absolutePosition = this.offset + position + arrayOffset;\n\n return readMethod<number | bigint>(this.buffer, type)(absolutePosition);\n}\n\n/**\n * Reads an array of primitive values from the buffer based on descriptor information\n *\n * @returns An array of primitive values (numbers or bigint's) read from the buffer\n *\n * @throws Error - If the arraySize is not defined in the descriptor\n *\n * @remarks\n * Uses the descriptor's arraySize and size properties to determine how many values to read\n * and the stride between array elements. The array is pre-allocated to avoid resizing\n * during population.\n *\n * This function is used internally when processing primitive array types as defined in the\n * PrimitiveArrayType.\n *\n * @example\n * ```ts\n * const context: PrimitiveContextInterface = {\n * buffer: Buffer.alloc(32),\n * offset: 0,\n * descriptor: {\n * position: 0,\n * type: 'UInt16BE',\n * arraySize: 8,\n * size: 2\n * }\n * };\n *\n * const values = readPrimitiveArray.call(context);\n * ```\n *\n * @see readSinglePrimitive\n *\n * @since 2.0.0\n */\n\nexport function readPrimitiveArray(this: PrimitiveContextInterface): Array<bigint | number> {\n const result: Array<number | bigint> = [];\n const { arraySize = 0, size } = this.descriptor;\n\n // Preallocate the array to avoid resizing\n result.length = arraySize;\n for (let i = 0; i < arraySize; i++) {\n result[i] = readSinglePrimitive.call(this, i * size);\n }\n\n return result;\n}\n\n/**\n * Reads primitive data from the buffer based on the context's descriptor\n *\n * @returns A primitive value or array of primitive values (number|bigint or Array\\<number | bigint\\>)\n *\n * @remarks\n * This function acts as a smart dispatcher that determines whether to read a single primitive value\n * or an array of primitive values based on the descriptor's configuration.\n *\n * If the descriptor contains an 'arraySize' property with a truthy value, the function will call\n * readPrimitiveArray to read multiple values. Otherwise, it calls readSinglePrimitive to read\n * a single value.\n *\n * This is the main entry point for reading primitive data from a buffer and should be used\n * in preference to calling readSinglePrimitive or readPrimitiveArray directly.\n *\n * @example\n * ```ts\n * // Reading a single value\n * const singleContext: PrimitiveContextInterface = {\n * buffer: buffer,\n * offset: 0,\n * descriptor: { position: 4, type: 'UInt8' }\n * };\n * const singleValue = readPrimitive.call(singleContext);\n *\n * // Reading an array\n * const arrayContext: PrimitiveContextInterface = {\n * buffer: buffer,\n * offset: 0,\n * descriptor: { position: 0, type: 'Int32LE', arraySize: 5, size: 4 }\n * };\n * const arrayValues = readPrimitive.call(arrayContext);\n * ```\n *\n * @see readPrimitiveArray\n * @see readSinglePrimitive\n *\n * @since 2.0.0\n */\n\nexport function readPrimitive(this: PrimitiveContextInterface): PrimitiveDataType {\n if(('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return readPrimitiveArray.call(this);\n\n return readSinglePrimitive.call(this);\n}\n\n/**\n * Writes a single primitive value to the buffer at the specified position\n *\n * @param value - The primitive value (number or bigint) to write to the buffer\n * @param arrayOffset - Optional offset within an array structure, defaults to 0\n *\n * @throws TypeError - If the provided value type doesn't match the expected type for the field\n * (e.g., providing a number for a BigInt field or a BigInt for a number field)\n *\n * @remarks\n * Uses the descriptor's position and type information to determine where and how to write to the buffer.\n * The absolute position is calculated by adding the context offset, descriptor position, and any array offset.\n *\n * The function automatically validates that the value type matches the expected type based on the field descriptor:\n * - BigInt types (fields whose names include 'Big') require bigint values\n * - Non-BigInt types require number values\n *\n * @example\n * ```ts\n * const context: PrimitiveContextInterface = {\n * buffer: Buffer.alloc(16),\n * offset: 4,\n * descriptor: {\n * position: 2,\n * type: 'UInt32LE'\n * }\n * };\n *\n * // Write a 32-bit unsigned integer\n * writeSinglePrimitive.call(context, 42);\n *\n * // For BigInt types\n * const bigIntContext: PrimitiveContextInterface = {\n * buffer: Buffer.alloc(16),\n * offset: 0,\n * descriptor: {\n * position: 0,\n * type: 'BigInt64LE'\n * }\n * };\n *\n * // Write a 64-bit signed integer\n * writeSinglePrimitive.call(bigIntContext, BigInt(9007199254740991));\n * ```\n *\n * @since 2.0.0\n */\n\nexport function writeSinglePrimitive(this: PrimitiveContextInterface, value: number | bigint, arrayOffset: number = 0): void {\n value ??= 0;\n const { position, type } = this.descriptor;\n const isBigIntType = type.includes('Big');\n\n if(isBigIntType && value === 0)\n value = BigInt(0);\n\n if (isBigIntType && typeof value !== 'bigint')\n throw new TypeError(`Expected a BigInt for field \"${ type }\", but received ${ value }`);\n\n if (!isBigIntType && typeof value !== 'number')\n throw new TypeError(`Expected a number for field \"${ type }\", but received ${ value }`);\n\n\n const absolutePosition = this.offset + position + arrayOffset;\n writeMethod<number | bigint>(this.buffer, type)(value, absolutePosition);\n}\n\n/**\n * Writes an array of primitive values to the buffer based on descriptor information\n *\n * @param values - Array of primitive values (numbers or bigint's) to write to the buffer\n *\n * @remarks\n * Uses the descriptor's arraySize and size properties to determine how many values to write\n * and the stride between array elements. If the provided values array is shorter than the\n * arraySize specified in the descriptor, the remaining elements will be filled with zeros.\n *\n * Each element is written using the writeSinglePrimitive function, which enforces type checking\n * based on the field descriptor.\n *\n * @example\n * ```ts\n * const context: PrimitiveContextInterface = {\n * buffer: Buffer.alloc(32),\n * offset: 0,\n * descriptor: {\n * position: 0,\n * type: 'UInt16BE',\n * arraySize: 8,\n * size: 2\n * }\n * };\n *\n * // Write an array of 16-bit unsigned integers\n * writePrimitiveArray.call(context, [1, 2, 3, 4, 5, 6, 7, 8]);\n *\n * // If fewer values are provided, remaining slots are filled with zeros\n * writePrimitiveArray.call(context, [100, 200, 300]); // Writes [100, 200, 300, 0, 0, 0, 0, 0]\n * ```\n *\n * @see writeSinglePrimitive\n *\n * @since 2.0.0\n */\n\nexport function writePrimitiveArray(this: PrimitiveContextInterface, values: Array<number | bigint>): void {\n const { arraySize = 0, size } = this.descriptor;\n\n for (let i = 0; i < arraySize; i++) {\n const elementValue = i < values.length ? values[i] : 0;\n writeSinglePrimitive.call(this, elementValue, i * size);\n }\n}\n\n/**\n * Writes primitive data to the buffer based on the context's descriptor\n *\n * @param value - A primitive value or array of primitive values (number|bigint or (number|bigint)[])\n *\n * @remarks\n * This function acts as a smart dispatcher that determines whether to write a single primitive value\n * or an array of primitive values based on the descriptor's configuration.\n *\n * If the descriptor contains an 'arraySize' property with a truthy value, the function will call\n * writePrimitiveArray to write multiple values. Otherwise, it calls writeSinglePrimitive to write\n * a single value.\n *\n * The function handles type conversion intelligently:\n * - When writing to an array field, a single value will be converted to a single-element array\n * - When writing to a single field, an array input will use only the first element (or 0 if empty)\n *\n * This is the main entry point for writing primitive data to a buffer and should be used\n * in preference to calling writeSinglePrimitive or writePrimitiveArray directly.\n *\n * @example\n * ```ts\n * // Writing a single value\n * const singleContext: PrimitiveContextInterface = {\n * buffer: buffer,\n * offset: 0,\n * descriptor: { position: 4, type: 'UInt8' }\n * };\n * writePrimitive.call(singleContext, 42);\n *\n * // Writing an array\n * const arrayContext: PrimitiveContextInterface = {\n * buffer: buffer,\n * offset: 0,\n * descriptor: { position: 0, type: 'Int32LE', arraySize: 5, size: 4 }\n * };\n * writePrimitive.call(arrayContext, [10, 20, 30, 40, 50]);\n * ```\n *\n * @see writePrimitiveArray\n * @see writeSinglePrimitive\n *\n * @since 2.0.0\n */\n\nexport function writePrimitive(this: PrimitiveContextInterface, value: PrimitiveDataType): void {\n if(('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return writePrimitiveArray.call(this, Array.isArray(value) ? value : [ value ]);\n\n writeSinglePrimitive.call(this, Array.isArray(value) ? (value[0] || 0) : value);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n BitfieldContextInterface,\n BitfieldDescriptorInterface,\n PositionedBitfieldDescriptorType\n} from '@components/interfaces/bitfield-component.interface';\nimport type { PrimitiveType } from '@components/interfaces/primitive-component.interface';\n\n/**\n * Imports\n */\n\nimport { PRIMITIVE_TYPE_SIZES } from '@components/primitive.component';\n\n/**\n * Cache for bit masks to improve the performance of bitfield operations\n *\n * @remarks\n * This map caches bit masks for different bit sizes to avoid recalculating\n * them repeatedly. The keys represent bit sizes, and the values are pre-calculated\n * masks for those sizes (e.g., 3 bits \u2192 0b111, 4 bits \u2192 0b1111).\n *\n * Using this cache improves performance in applications with heavy bitfield operations,\n * as mask generation is a common operation that can be optimized through caching.\n *\n * @private\n * @since 2.0.0\n */\n\nexport const maskCache = new Map<number, number>();\n\n/**\n * Determines if a primitive type is signed\n *\n * @param type - The primitive type name to check\n * @returns `true` if the type is signed, `false` otherwise\n *\n * @remarks\n * This function checks if a given primitive type represents a signed value.\n * Types that start with \"Int\" (e.g., Int8, Int16, Int32) are considered signed,\n * while other types (e.g., UInt8, Float32) are considered unsigned.\n *\n * @example\n * ```ts\n * isSignedType('Int8'); // Returns true\n * isSignedType('UInt8'); // Returns false\n * ```\n *\n * @since 2.0.0\n */\n\nexport function isSignedType(type: string): boolean {\n return type.startsWith('Int');\n}\n\n/**\n * Creates a bit mask of a specific size with optimized caching\n *\n * @param size - The number of bits to set in the mask (from the least significant bit)\n * @returns A number with the specified number of the least significant bits set to 1\n *\n * @remarks\n * This function generates a bit mask with the specified number of the least significant bits set to 1.\n * For performance optimization, it uses a cache to store previously calculated masks.\n * For example, for size 3, it returns 0b111 (decimal 7).\n *\n * The function first checks if the requested mask already exists in the cache.\n * If found, it returns the cached value; otherwise, it calculates a new mask,\n * stores it in the cache for future use, and returns it.\n *\n * @example\n * ```ts\n * getBitMask(3); // Returns 7 (binary 0b111)\n * getBitMask(8); // Returns 255 (binary 0b11111111)\n * ```\n *\n * @since 2.0.0\n */\n\nexport function getBitMask(size: number): number {\n let mask = maskCache.get(size);\n if (mask === undefined) {\n mask = (1 << size) - 1;\n maskCache.set(size, mask);\n }\n\n return mask;\n}\n\n/**\n * Processes a value according to the bitfield's type specifications\n *\n * @param descriptor - The descriptor defining the bitfield's properties\n * @param value - The numeric value to process\n * @returns The processed value, adjusted for the bitfield's type\n *\n * @remarks\n * This function ensures that a numeric value is properly formatted according to\n * the constraints of a bitfield descriptor. For signed types, it applies the correct\n * sign extension using BigInt operations to handle possible overflow/underflow\n * situations, then converts the result back to a JavaScript number.\n *\n * For unsigned types, the value is returned unchanged as no additional processing\n * is needed.\n *\n * @example\n * ```ts\n * // Process a value for a signed 4-bit field\n * const descriptor: BitfieldDescriptorInterface = {\n * type: 'Int8',\n * bitSize: 4,\n * bitPosition: 0\n * };\n *\n * processValueForBitfield(descriptor, 15); // Returns -1 (sign extension applied)\n * processValueForBitfield(descriptor, 7); // Returns 7 (no sign extension needed)\n * ```\n *\n * @since 2.0.0\n */\n\nexport function processValueForBitfield(descriptor: BitfieldDescriptorInterface, value: number): number {\n if (isSignedType(descriptor.type as string)) {\n return Number(BigInt.asIntN(descriptor.bitSize, BigInt(value)));\n }\n\n return value;\n}\n\n/**\n * Validates that a value fits within the bounds of a specified bitfield\n *\n * @param descriptor - The descriptor defining the bitfield's properties\n * @param value - The numeric value to validate\n *\n * @throws RangeError - When the value exceeds the allowable range for the bitfield\n *\n * @remarks\n * This function checks if a given value can be safely stored in a bitfield with\n * the specified characteristics. It calculates the minimum and maximum allowable values\n * based on the bitfield's size and whether it's signed or unsigned.\n *\n * For unsigned bitfields, the range is 0 to (2^bitSize - 1).\n * For signed bitfields, the range is -(2^(bitSize-1)) to (2^(bitSize-1) - 1).\n *\n * If the value falls outside the valid range, a RangeError is thrown with a\n * descriptive message indicating the constraint violation.\n *\n * @example\n * ```ts\n * // Validate a value for a 3-bit unsigned field\n * const unsignedField: BitfieldDescriptorInterface = {\n * type: 'UInt8',\n * bitSize: 3,\n * bitPosition: 0\n * };\n * validateBitFieldBounds(unsignedField, 5); // Valid (0-7 is valid range)\n * validateBitFieldBounds(unsignedField, 8); // Throws RangeError\n *\n * // Validate a value for a 3-bit signed field\n * const signedField: BitfieldDescriptorInterface = {\n * type: 'Int8',\n * bitSize: 3,\n * bitPosition: 0\n * };\n * validateBitFieldBounds(signedField, -4); // Valid (-4 to 3 is valid range)\n * validateBitFieldBounds(signedField, 4); // Throws RangeError\n * ```\n *\n * @since 2.0.0\n */\n\nexport function validateBitFieldBounds(descriptor: BitfieldDescriptorInterface, value: number): void {\n const isSigned = isSignedType(descriptor.type as string);\n const { bitSize, type } = descriptor;\n\n // Fix operator precedence with parentheses for shift operations\n const maxBitValue = isSigned ? ((1 << (bitSize - 1)) - 1) : ((1 << bitSize) - 1);\n const minBitValue = isSigned ? -(1 << (bitSize - 1)) : 0;\n\n if (value < minBitValue || value > maxBitValue) {\n throw new RangeError(\n `Value ${ value } does not fit within ${ bitSize } bits for type ${ type }`\n );\n }\n}\n\n/**\n * Validates the structural parameters of a bitfield descriptor\n *\n * @param descriptor - The bitfield descriptor to validate\n * @param operation - A string describing the operation context (for error messages)\n *\n * @throws Error - When the descriptor has invalid parameters\n *\n * @remarks\n * This function performs two key validation checks on bitfield descriptors:\n *\n * 1. It verifies that the primitive type size is supported (currently limited to 32 bits or fewer)\n * 2. It ensures that the bitfield's position and size do not exceed the bounds of its containing type\n *\n * These validations help prevent buffer overflows, data corruption, and other\n * potential issues that could occur when working with binary data structures.\n *\n * The operation parameter is used in error messages to provide context about\n * where the validation failure occurred.\n *\n * @example\n * ```ts\n * // Valid bitfield descriptor\n * const validDescriptor: BitfieldDescriptorInterface = {\n * type: 'UInt8',\n * bitSize: 3,\n * bitPosition: 5\n * };\n * validateBitfieldParameters(validDescriptor, 'read'); // No error thrown\n *\n * // Invalid: position + size exceeds type size (8 bits for UInt8)\n * const invalidDescriptor: BitfieldDescriptorInterface = {\n * type: 'UInt8',\n * bitSize: 6,\n * bitPosition: 4\n * };\n * validateBitfieldParameters(invalidDescriptor, 'write'); // Throws Error\n * ```\n *\n * @since 2.0.0\n */\n\nexport function validateBitfieldParameters(descriptor: BitfieldDescriptorInterface, operation: string): void {\n if (descriptor.bitSize < 1 || descriptor.bitPosition < 0) {\n throw new Error(`bitSize(${ descriptor.bitSize }) and bitPosition(${ descriptor.bitPosition }) ` +\n `must be greater than bitSize(1) and bitPosition(0) for ${ operation }`);\n }\n\n if (PRIMITIVE_TYPE_SIZES[descriptor.type] > 32) {\n throw new Error(`${ descriptor.type } is not supported yet`);\n }\n\n if (descriptor.bitPosition + descriptor.bitSize > PRIMITIVE_TYPE_SIZES[descriptor.type]) {\n throw new Error(\n `bitPosition(${ descriptor.bitPosition }) + bitSize(${ descriptor.bitSize }) ` +\n `exceeds ${ descriptor.type } size for ${ operation }`\n );\n }\n}\n\n/**\n * Extracts a bitfield value from a raw numeric value\n *\n * @param rawValue - The source value containing the bitfield\n * @param descriptor - The descriptor defining the bitfield's properties\n * @returns The extracted value from the bitfield\n *\n * @throws Error - When the bitfield parameters are invalid\n *\n * @remarks\n * This function extracts a specific bitfield from a larger numeric value according\n * to the provided descriptor. It first validates the bitfield parameters to ensure\n * they are within allowable bounds. Then it performs the following operations:\n *\n * 1. Creates an appropriate bit mask for the field's size\n * 2. Shifts the raw value right to align the target bits with the least significant position\n * 3. Applies the mask to extract only the relevant bits\n * 4. For signed types, if the most significant bit is set (indicating a negative value),\n * it extends the sign bit by OR'ing with the complement of the mask\n *\n * This function properly handles both signed and unsigned bitfields of various sizes.\n *\n * @example\n * ```ts\n * // Extracting an unsigned 3-bit field from bit position 2\n * const unsignedField: BitfieldDescriptorInterface = {\n * type: 'UInt8',\n * bitSize: 3,\n * bitPosition: 2\n * };\n *\n * extractBitfieldValue(0b10111100, unsignedField); // Returns 7 (0b111)\n *\n * // Extracting a signed 3-bit field from bit position 2\n * const signedField: BitfieldDescriptorInterface = {\n * type: 'Int8',\n * bitSize: 3,\n * bitPosition: 2\n * };\n *\n * extractBitfieldValue(0b10111100, signedField); // Returns -1 (sign extended from 0b111)\n * extractBitfieldValue(0b00011100, signedField); // Returns 3 (positive value 0b011)\n * ```\n *\n * @since 2.0.0\n */\n\nexport function extractBitfieldValue(rawValue: number, descriptor: BitfieldDescriptorInterface): number {\n validateBitfieldParameters(descriptor, 'read operation');\n\n const { type, bitPosition, bitSize } = descriptor;\n const mask = getBitMask(bitSize);\n const extractedValue = (rawValue >> bitPosition) & mask;\n\n if (isSignedType(type as string) && (extractedValue & (1 << (bitSize - 1)))) {\n return extractedValue | (~mask);\n }\n\n return extractedValue;\n}\n\n/**\n * Composes a new value by integrating a bitfield into a larger number\n *\n * @param rawValue - The original value containing multiple bitfields\n * @param descriptor - The descriptor defining the target bitfield's properties\n * @param value - The value to integrate into the bitfield\n * @returns A new composite value with the specified bitfield updated\n *\n * @throws Error - When the bitfield parameters are invalid\n * @throws RangeError - When the provided value exceeds the bounds of the bitfield\n *\n * @remarks\n * This function composes a new numeric value by integrating a specific bitfield with an existing value.\n * It precisely targets and modifies only the bits defined\n * by the descriptor while preserving all other bits in the original value.\n * The process involves:\n *\n * 1. Validating the bitfield parameters to ensure they are within allowable bounds\n * 2. Validating that the value to integrate fits within the bitfield's size constraints\n * 3. Processing the value to account for the bitfield's type (signed/unsigned)\n * 4. Creating an appropriate bit mask for the field's size\n * 5. Clearing only the target bits in the original value\n * 6. Inserting the new bits at the appropriate position\n *\n * The original value is not modified; instead, a new composite value is returned.\n *\n * @example\n * ```ts\n * // Composing a value with an unsigned 3-bit field at bit position 2\n * const unsignedField: BitfieldDescriptorInterface = {\n * type: 'UInt8',\n * bitSize: 3,\n * bitPosition: 2\n * };\n *\n * // Original: 0b10000010 (130)\n * // Composed: 0b10011010 (154)\n * composeBitfieldValue(0b10000010, unsignedField, 6); // Returns 154\n *\n * // Composing a value with a signed 3-bit field at bit position 1\n * const signedField: BitfieldDescriptorInterface = {\n * type: 'Int8',\n * bitSize: 3,\n * bitPosition: 1\n * };\n *\n * // Original: 0b11110000 (240)\n * // Composed: 0b11101110 (238) - integrating -1 (0b111 in 3-bit signed form)\n * composeBitfieldValue(0b11110000, signedField, -1); // Returns 238\n * ```\n *\n * @since 2.0.0\n */\n\nexport function composeBitfieldValue(rawValue: number, descriptor: BitfieldDescriptorInterface, value: number): number {\n validateBitfieldParameters(descriptor, 'write operation');\n validateBitFieldBounds(descriptor, value);\n\n const { bitPosition, bitSize } = descriptor;\n const processedValue = processValueForBitfield(descriptor, value);\n const mask = getBitMask(bitSize);\n const shiftedMask = mask << bitPosition;\n\n // Clear the bits at the target position and then set the new value\n return (rawValue & ~shiftedMask) | ((processedValue << bitPosition) & shiftedMask);\n}\n\n/**\n * Parses a string representation of a bitfield and returns a structured positioned descriptor object\n *\n * @param field - String in the format \"type:bitSize\" where type is a primitive type (e.g., \"Int8\", \"UInt16BE\")\n * and bitSize is the number of bits to allocate (e.g., \"Int8:4\")\n * @param position - The starting byte position of this element within the buffer\n * @param bitPosition - Starting position of the bitfield within the primitive type (0-based index, defaults to 0)\n * @returns A PositionedBitfieldDescriptorType object containing the parsed type, size, offset, bitSize, and bitPosition\n *\n * @throws Error - When the type is not supported (not found in PRIMITIVE_TYPE_SIZES)\n * @throws Error - When the bitPosition is negative or greater than or equal to the type size\n * @throws Error - When the bitSize is invalid (zero or non-numeric)\n * @throws Error - When the bitSize + bitPosition exceeds the available bits in the type\n *\n * @remarks\n * This function parses a string descriptor for a bitfield and validates that the\n * specified bitfield can fit within the given primitive type.\n * It creates a positioned descriptor that includes both the bitfield definition and its location in memory.\n * It ensures that:\n * - The primitive type is supported\n * - The bit position is within the valid range for the type\n * - The bit size is a valid number greater than zero\n * - The bitfield (of size bitSize starting at bitPosition) fits within the primitive type\n *\n * @example\n * ```ts\n * // Parse an 8-bit signed integer with 3 bits starting at position 0, at offset 0\n * const descriptor = parseBitfieldDescriptor('Int8:3');\n * // Returns: { type: 'Int8', size: 1, offset: 0, bitSize: 3, bitPosition: 0 }\n *\n * // Parse a 16-bit unsigned integer with 5 bits starting at position 2, at offset 4\n * const descriptor = parseBitfieldDescriptor('UInt16:5', 4, 2);\n * // Returns: { type: 'UInt16LE', size: 2, offset: 4, bitSize: 5, bitPosition: 2 }\n * ```\n *\n * @see PRIMITIVE_TYPE_SIZES\n * @see PositionedBitfieldDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function parseBitfieldDescriptor(field: string, position: number = 0, bitPosition: number = 0): PositionedBitfieldDescriptorType {\n const [ type, bitSizeStr ] = <[PrimitiveType, string]> field.split(':', 2);\n const bitSize = parseInt(bitSizeStr, 10);\n const typeSize = PRIMITIVE_TYPE_SIZES[type];\n const isBigEndian = type.endsWith('BE');\n\n if (!typeSize)\n throw new Error(`${ type } is not supported`);\n\n if (bitPosition < 0 || bitPosition >= typeSize)\n throw new Error(`Bitfield position ${ bitPosition } is out of bounds (must be between 0 and ${ typeSize - 1 })`);\n\n if (!bitSize)\n throw new Error(`${ field } is not valid`);\n\n if (bitSize + bitPosition >= typeSize)\n throw new Error(`${ type } size (${ typeSize }) is not enough to hold ${ bitSize } bits starting at position ${ bitPosition }`);\n\n return {\n kind: 'bitfield',\n type,\n size: typeSize / 8,\n position,\n bitSize,\n bitPosition,\n isBigEndian\n };\n}\n\n/**\n * Reads a bitfield value from a buffer at the specified position based on the provided context.\n *\n * @returns The extracted bitfield value after applying masks and shifts\n *\n * @throws Error - If the buffer is too small for the requested read\n *\n * @remarks\n * This function handles both big-endian and little-endian values based on the descriptor's\n * isBigEndian property. The function uses the BitfieldContextInterface as its 'this' context\n * to access buffer, descriptor, and offset properties.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: Buffer.from([0x12, 0x34, 0x56, 0x78]),\n * descriptor: {\n * position: 0,\n * size: 2,\n * isBigEndian: true,\n * bitOffset: 4,\n * bitLength: 8,\n * type: 'UInt16'\n * },\n * offset: 0\n * };\n * const value = readBitfield.call(context);\n * ```\n *\n * @see extractBitfieldValue\n * @see BitfieldContextInterface\n * @see PositionedBitfieldDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function readBitfield(this: BitfieldContextInterface): number {\n const absolutePosition = this.descriptor.position + this.offset;\n const endianMethod = this.descriptor.isBigEndian ? 'BE' : 'LE';\n const rawValue = this.buffer[`readUInt${ endianMethod }`](absolutePosition, this.descriptor.size);\n\n return extractBitfieldValue(rawValue, this.descriptor);\n}\n\n/**\n * Writes a bitfield value to a buffer at the specified position based on the provided context.\n *\n * @param value - The value to write to the bitfield\n * @returns\n *\n * @throws Error - If the buffer is too small for the requested write\n *\n * @remarks\n * This function handles both big-endian and little-endian values based on the descriptor's isBigEndian property.\n * It first reads the current value, modifies the specific bits, and then\n * writes the updated value back to the buffer.\n * The function uses the BitfieldContextInterface as its 'this' context to access buffer, descriptor, and offset.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: Buffer.alloc(4),\n * descriptor: {\n * position: 0,\n * size: 2,\n * isBigEndian: true,\n * bitOffset: 4,\n * bitLength: 8\n * },\n * offset: 0\n * };\n * writeBitfield.call(context, 0xAB);\n * ```\n *\n * @see composeBitfieldValue\n * @see BitfieldContextInterface\n * @see PositionedBitfieldDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function writeBitfield(this: BitfieldContextInterface, value: number): void {\n const absolutePosition = this.descriptor.position + this.offset;\n const endianMethod = this.descriptor.isBigEndian ? 'BE' : 'LE';\n const rawValue = this.buffer[`readUInt${ endianMethod }`](absolutePosition, this.descriptor.size);\n const bitFieldValue = composeBitfieldValue(rawValue, this.descriptor, value);\n\n this.buffer[`writeUInt${ endianMethod }`](bitFieldValue, absolutePosition, this.descriptor.size);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n StringType,\n StringContextInterface,\n PositionedStringDescriptorType, StringDataType\n} from '@components/interfaces/string-component.interface';\n\n/**\n * Imports\n */\n\nimport { readMethod, splitBufferWithGap, writeMethod } from '@components/buffer.component';\n\n/**\n * A set containing all valid string primitive type identifiers\n *\n * @remarks\n * This constant provides a convenient way\n * to validate or check if a given string represents a valid string primitive type.\n * The set contains all supported string\n * encoding formats that can be used in data structures:\n * - 'utf8': UTF-8 encoding supporting the full Unicode character set\n * - 'ascii': ASCII encoding limited to 7-bit ASCII characters\n * - 'string': Default string representation based on the system's encoding\n *\n * This collection is useful for validation functions, type checking, or when\n * determining if a string identifier refers to a string primitive type.\n *\n * @example\n * ```ts\n * function isStringPrimitive(type: string): boolean {\n * return STRING_PRIMITIVE_LIST.has(type.toLowerCase());\n * }\n * ```\n *\n * @see StringType\n *\n * @since 2.0.0\n */\n\nexport const STRING_PRIMITIVE_LIST: Set<string> = new Set([ 'utf8', 'ascii', 'string' ]);\n\n/**\n * Parses a string representation of a string type descriptor into a structured object with positioning information\n *\n * @param field - String representation of the string descriptor in format \"type\" or \"type[size]\"\n * @param position - The starting position of this string within the buffer (defaults to 0)\n * @returns A structured PositionedStringDescriptor object with type, size, and offset information\n *\n * @throws Error - When the descriptor format doesn't match the expected pattern\n *\n * @remarks\n * This function converts a string-based string type specification into a structured descriptor object.\n * The input string can be in one of two formats:\n * - A simple string type name (e.g., \"utf8\", \"ascii\", \"string\")\n * - A string type with array size specification (e.g., \"utf8[10]\", \"ascii[25]\")\n *\n * When an array size is specified (e.g., \"utf8[10]\"),\n * it represents an array of 10 dynamic strings, each with its own length prefix.\n * Each string is stored sequentially in the buffer, one after another.\n *\n * The function validates that the input string matches the expected pattern for a valid string descriptor.\n * If an array size is specified in the descriptor, it is parsed as an integer and included in the returned object.\n *\n * By default, the function sets lengthType to 'UInt16LE', which means each string will be encoded with a\n * 2-byte length prefix, and size is initialized to 2 to account for the length prefix.\n *\n * @example\n * ```ts\n * // Parse a simple string type with offset\n * const descriptor1 = parseStringDescriptor('utf8', 0);\n * // Returns: { type: 'utf8', lengthType: 'UInt16LE', arraySize: undefined, offset: 0, size: 2 }\n *\n * // Parse a string type as an array of 15 dynamic strings with offset\n * const descriptor2 = parseStringDescriptor('ascii[15]', 24);\n * // Returns: { type: 'ascii', lengthType: 'UInt16LE', arraySize: 15, offset: 24, size: 2 }\n * ```\n *\n * @see StringType\n * @see UnsignedPrimitiveType\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function parseStringDescriptor(field: string, position: number = 0): PositionedStringDescriptorType {\n const pattern = /^(utf8|ascii|string)(?:\\[(\\d+)\\])?$/i;\n const match = <[string, StringType, string]> field.match(pattern);\n\n if (!match)\n throw new Error(`Invalid string descriptor: ${ field }`);\n\n const type = <StringType> match[1].toLowerCase();\n const arraySize = match[2] ? parseInt(match[2]) : undefined;\n\n return { type, arraySize, position, size: 2, lengthType: 'UInt16LE', kind: 'string' };\n}\n\n/**\n * Reads a single string from a buffer at the specified position based on the provided context.\n *\n * @param arrayOffset - Optional offset for reading strings within an array, defaults to 0\n * @returns The string value read from the buffer\n *\n * @throws Error - If null string exceeds the specified maxLength constraint\n * @throws Error - If BigInt is used in lengthType (e.g., 'BigInt64' or 'BigUint64')\n * @throws Error - If the buffer is too small for the requested read or if the encoding is invalid\n * @throws Error - If the string's length prefix indicates a size that would exceed the buffer's bounds\n *\n * @remarks\n * This function supports three different string formats:\n * 1. Length-prefixed strings - Where a length value precedes the string data (using lengthType)\n * 2. Null-terminated strings - Where the string ends with a null byte (0x00)\n * 3. Fixed-size strings - Where the string has a predetermined size\n *\n * The function uses the StringContextInterface as its 'this' context to access buffer,\n * descriptor, and offset properties. The encoding is determined by the descriptor's type property.\n *\n * @example\n * ```ts\n * // Reading a null-terminated string\n * const context = {\n * buffer: Buffer.from(\"Hello\\0World\"),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 6,\n * nullTerminated: true\n * },\n * offset: 0\n * };\n * const str = readSingleString.call(context);\n * // Returns: \"Hello\"\n * ```\n *\n * @see readMethod\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function readSingleString(this: StringContextInterface, arrayOffset: number = 0): string {\n const { position, type, size } = this.descriptor;\n const absolutePosition = this.offset + position + arrayOffset;\n const encoding = type === 'string' ? 'utf8' : type;\n\n if ('lengthType' in this.descriptor && this.descriptor.lengthType) {\n if(this.descriptor.lengthType.includes('Big'))\n throw new Error('BigInt are not supported');\n\n const lengthType = this.descriptor.lengthType as string;\n const stringLength = Number(readMethod<bigint | number>(this.buffer, lengthType)(absolutePosition));\n const dataOffset = absolutePosition + size;\n this.offset += stringLength;\n\n if((dataOffset + stringLength) > this.buffer.length)\n throw new Error(\n `String prefix length exceeds buffer position: ${ dataOffset } size: ${ stringLength } > ${ this.buffer.length }`\n );\n\n return this.buffer.subarray(dataOffset, dataOffset + stringLength).toString(encoding);\n }\n\n if ('nullTerminated' in this.descriptor) {\n let endPos = absolutePosition;\n const maxLength = 'maxLength' in this.descriptor ? this.descriptor.maxLength : 0;\n while (endPos < this.buffer.length && this.buffer[endPos] !== 0) {\n if(maxLength && endPos > maxLength)\n throw new Error(`NullTerminated String exceeds maximum length of ${ maxLength }`);\n\n endPos++;\n }\n\n const stringLength = endPos - absolutePosition;\n this.offset += stringLength + 1;\n\n return this.buffer.subarray(absolutePosition, endPos).toString(encoding);\n }\n\n return this.buffer.subarray(absolutePosition, absolutePosition + size).toString(encoding);\n}\n\n/**\n * Reads an array of strings from a buffer based on the provided context.\n *\n * @returns An array of strings read from the buffer\n *\n * @throws Error - If the buffer is too small for the requested read or if the encoding is invalid\n *\n * @remarks\n * This function reads multiple strings from a buffer by iteratively calling readSingleString\n * for each element in the array. The number of strings to read is determined by the descriptor's\n * arraySize property. For performance optimization, the result array is pre-allocated to the\n * exact size needed.\n *\n * The function uses the StringContextInterface as its 'this' context to access buffer,\n * descriptor, and offset properties. Each string in the array is positioned at intervals\n * determined by the descriptor's size property.\n *\n * @example\n * ```ts\n * // Reading an array of two fixed-length strings\n * const context = {\n * buffer: Buffer.from(\"HelloWorld\"),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 5,\n * arraySize: 2\n * },\n * offset: 0\n * };\n * const strArray = readStringArray.call(context);\n * // Returns: [\"Hello\", \"World\"]\n * ```\n *\n * @see readSingleString\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function readStringArray(this: StringContextInterface): Array<string> {\n const result: Array<string> = [];\n const { arraySize = 0, size } = this.descriptor;\n\n // Preallocate the array to avoid resizing\n result.length = arraySize;\n for (let i = 0; i < arraySize; i++) {\n result[i] = readSingleString.call(this, i * size);\n }\n\n return result;\n}\n\n/**\n * Reads a string or array of strings from a buffer based on the provided context.\n *\n * @returns A string value or array of strings depending on the descriptor configuration\n *\n * @throws Error - If the buffer is too small for the requested read or if the encoding is invalid\n *\n * @remarks\n * This function acts as a dispatcher that determines whether to read a single string\n * or an array of strings based on the descriptor's arraySize property. It uses the\n * StringContextInterface as its 'this' context to access buffer, descriptor, and offset properties.\n *\n * @example\n * ```ts\n * // Reading a single string\n * const singleStringContext = {\n * buffer: Buffer.from(\"Hello\\0World\"),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 6,\n * nullTerminated: true\n * },\n * offset: 0\n * };\n * const str = readString.call(singleStringContext);\n * // Returns: \"Hello\"\n *\n * // Reading an array of strings\n * const arrayStringContext = {\n * buffer: Buffer.from(\"HelloWorld\"),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 5,\n * arraySize: 2\n * },\n * offset: 0\n * };\n * const strArray = readString.call(arrayStringContext);\n * // Returns: [\"Hello\", \"World\"]\n * ```\n *\n * @see readStringArray\n * @see readSingleString\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function readString(this: StringContextInterface): StringDataType {\n if(('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return readStringArray.call(this);\n\n return readSingleString.call(this);\n}\n\n/**\n * Writes a single string to a buffer at the specified position based on the provided context.\n *\n * @param value - The string value to write to the buffer\n * @param arrayOffset - Optional offset for writing strings within an array, defaults to 0\n * @returns void\n *\n * @throws Error - If the buffer is too small or if the encoding is invalid\n * @throws Error - If BigInt is used in lengthType (e.g., 'BigInt64' or 'BigUint64')\n *\n * @remarks\n * This function supports three different string formats:\n * 1. Length-prefixed strings - Where a length value precedes the string data (using lengthType)\n * 2. Null-terminated strings - Where the string ends with a null byte (0x00)\n * 3. Fixed-size strings - Where the string has a predetermined size\n *\n * The function uses the StringContextInterface as its 'this' context to access buffer,\n * descriptor, and offset properties. The encoding is determined by the descriptor's type property.\n *\n * For length-prefixed and null-terminated strings, the buffer may be resized to accommodate\n * the string data using the splitBufferWithGap utility.\n *\n * @example\n * ```ts\n * // Writing a null-terminated string\n * const context = {\n * buffer: Buffer.alloc(10),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 6,\n * nullTerminated: true\n * },\n * offset: 0\n * };\n * writeSingleString.call(context, \"Hello\");\n * // Result: Buffer contains \"Hello\\0\"\n * ```\n *\n * @see writeMethod\n * @see splitBufferWithGap\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function writeSingleString(this: StringContextInterface, value: string, arrayOffset: number = 0): void {\n value ??= '';\n const { position, type, size } = this.descriptor;\n const absolutePosition = this.offset + position + arrayOffset;\n const encoding = type === 'string' ? 'utf8' : type;\n\n if ('lengthType' in this.descriptor && this.descriptor.lengthType) {\n if(this.descriptor.lengthType.includes('Big'))\n throw new Error('BigInt are not supported');\n\n const stringBuffer = Buffer.from(value, encoding);\n writeMethod<bigint | number>(\n this.buffer,\n this.descriptor.lengthType as string\n )(stringBuffer.length, absolutePosition);\n\n const [ start, end ] = splitBufferWithGap(this.buffer, absolutePosition + size);\n this.buffer = Buffer.concat([ start, stringBuffer, end ]);\n this.offset += stringBuffer.length;\n\n return;\n }\n\n if ('nullTerminated' in this.descriptor) {\n if('maxLength' in this.descriptor && this.descriptor.maxLength)\n value = value.length > this.descriptor.maxLength ? value.slice(0, this.descriptor.maxLength) : value;\n\n const nullTerminatedString = value.endsWith('\\0') ? value : `${value}\\0`;\n const stringBuffer = Buffer.from(nullTerminatedString, encoding);\n const [ start, end ] = splitBufferWithGap(this.buffer, absolutePosition, size);\n\n this.buffer = Buffer.concat([ start, stringBuffer, end ]);\n this.offset += stringBuffer.length;\n\n return;\n }\n\n this.buffer.write(value, absolutePosition, size, encoding);\n}\n\n/**\n * Writes an array of strings to a buffer based on the provided context.\n *\n * @param values - The array of string values to write to the buffer\n * @returns void\n *\n * @throws Error - If the buffer is too small or if the encoding is invalid\n *\n * @remarks\n * This function writes multiple strings to a buffer by iteratively calling writeSingleString\n * for each element in the input array. The number of strings to write is determined by\n * the descriptor's arraySize property.\n *\n * If the input array contains fewer elements than arraySize, empty strings will be written\n * for the remaining positions. Each string in the array is positioned at intervals\n * determined by the descriptor's size property.\n *\n * The function uses the StringContextInterface as its 'this' context to access buffer,\n * descriptor, and offset properties.\n *\n * @example\n * ```ts\n * // Writing an array of two fixed-length strings\n * const context = {\n * buffer: Buffer.alloc(10),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 5,\n * arraySize: 2\n * },\n * offset: 0\n * };\n * writeStringArray.call(context, [\"Hello\", \"World\"]);\n * // Result: Buffer contains \"HelloWorld\"\n * ```\n *\n * @see writeSingleString\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function writeStringArray(this: StringContextInterface, values: Array<string>): void {\n const { arraySize = 0, size } = this.descriptor;\n\n for (let i = 0; i < arraySize; i++) {\n const elementValue = i < values.length ? values[i] : '';\n writeSingleString.call(this, elementValue, i * size);\n }\n}\n\n/**\n * Writes a string or array of strings to a buffer based on the provided context.\n *\n * @param value - The string value or array of strings to write to the buffer\n * @returns void\n *\n * @throws Error - If the buffer is too small for the write operation or if the encoding is invalid\n *\n * @remarks\n * This function acts as a dispatcher that determines whether to write a single string\n * or an array of strings based on the descriptor's arraySize property. It handles\n * type conversion to ensure compatibility between the provided value and the expected format.\n *\n * - If the descriptor specifies an array (arraySize property exists), any single string\n * will be wrapped in an array before being processed.\n * - If the descriptor does not specify an array but an array is provided, only the first\n * element (or an empty string if the array is empty) will be used.\n *\n * The function uses the StringContextInterface as its 'this' context to access buffer,\n * descriptor, and offset properties.\n *\n * @example\n * ```ts\n * // Writing a single string\n * const singleStringContext = {\n * buffer: Buffer.alloc(10),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 6,\n * nullTerminated: true\n * },\n * offset: 0\n * };\n * writeString.call(singleStringContext, \"Hello\");\n * // Result: Buffer contains \"Hello\\0\"\n *\n * // Writing an array of strings\n * const arrayStringContext = {\n * buffer: Buffer.alloc(10),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 5,\n * arraySize: 2\n * },\n * offset: 0\n * };\n * writeString.call(arrayStringContext, [\"Hello\", \"World\"]);\n * // Result: Buffer contains \"HelloWorld\"\n * ```\n *\n * @see writeSingleString\n * @see writeStringArray\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function writeString(this: StringContextInterface, value: StringDataType): void {\n if(('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return writeStringArray.call(this, Array.isArray(value) ? value : [ value ]);\n\n return writeSingleString.call(this, Array.isArray(value) ? (value[0] || '') : value);\n}\n", "/**\n * Type imports\n */\n\nimport type {\n StringType,\n StringDataType,\n StringContextInterface,\n PositionedStringDescriptorType,\n LengthPrefixedDescriptorInterface\n} from '@components/interfaces/string-component.interface';\n\nimport type {\n PrimitiveType,\n PrimitiveDataType,\n PrimitiveContextInterface,\n PositionedDescriptorInterface\n} from '@components/interfaces/primitive-component.interface';\n\nimport type {\n FieldsType,\n StringFieldType,\n ContextInterface,\n DescriptorFieldType,\n AccumulatorInterface,\n StructSchemaInterface,\n PositionedDescriptorFieldType\n} from '@services/interfaces/struct-service.interface';\n\nimport type {\n BitfieldContextInterface,\n PositionedBitfieldDescriptorType\n} from '@components/interfaces/bitfield-component.interface';\n\nimport type {\n StructDataType,\n StructContextInterface\n} from '@components/interfaces/struct-component.interface';\n\n/**\n * Implementation imports\n */\n\nimport { readStruct, writeStruct } from '@components/struct.component';\nimport { parseBitfieldDescriptor, readBitfield, writeBitfield } from '@components/bitfield.component';\nimport { parseStringDescriptor, readString, STRING_PRIMITIVE_LIST, writeString } from '@components/string.component';\nimport {\n readPrimitive,\n writePrimitive,\n PRIMITIVE_TYPE_SIZES,\n parsePrimitiveDescriptor\n} from '@components/primitive.component';\n\n/**\n * A versatile class for creating and manipulating structured binary data objects\n *\n * @template T - The type of the object structure this class represents\n * @remarks\n * The Struct class provides a type-safe way to define, read, and write structured binary data.\n * It supports various field types including:\n *\n * Numeric types with explicit size and endianness:\n * - `UInt8`, `Int8`, `UInt16LE/BE`, `Int16LE/BE`, `UInt32LE/BE`, `Int32LE/BE`\n * - `BigUInt64LE/BE`, `BigInt64LE/BE`, `FloatLE/BE`, `DoubleLE/BE`\n *\n * Arrays of numeric types:\n * - `UInt8[20]`, `Int32LE[15]`\n *\n * Bitfields:\n * - `UInt16LE:7` (7 bits within a 16-bit field)\n * - `UInt8:4` (4 bits within an 8-bit field)\n * - `UInt16BE:12` (12 bits within a 16-bit big-endian field)\n *\n * String types:\n * - Array of strings: `string[10]`, `ascii[10]`, `utf8[10]`\n * (array of 10 strings, each preceded by a UInt16LE length prefix)\n * - Null-terminated: `{ type: 'string', nullTerminated: true }`\n * (variable-length string that reads until the first null character)\n * - Length-prefixed: `{ type: 'string', lengthType: 'UInt32LE' }`\n * (variable-length string preceded by its length stored as UInt32LE)\n * - Fixed-length string: `{ type: 'string', size: 10, arraySize: 2 }`\n * (array of 2 fixed-length strings, each 10 characters long)\n *\n * Nested structures:\n * - `Struct` (nested structure)\n * - `{ type: Struct, arraySize: 2 }` (array of structures)\n *\n * @since 2.0.0\n */\n\nexport class Struct<T extends object = object> {\n /**\n * The total fixed size of the schema in bytes.\n *\n * @since 2.0.0\n */\n\n readonly size: number;\n\n /**\n * Internal map that stores field descriptors with their positions in the binary structure.\n * Maps property names to their corresponding descriptor metadata.\n *\n * @since 2.0.0\n */\n\n private readonly schema: Map<string, PositionedDescriptorFieldType> = new Map();\n\n /**\n * Creates a new binary structure schema instance.\n *\n * @param schema - The structure schema definition that describes field types and their layout\n *\n * @throws SchemaValidationError - When the provided schema contains invalid field definitions\n *\n * @since 2.0.0\n */\n\n constructor(schema: StructSchemaInterface) {\n this.size = this.compileSchema(schema);\n }\n\n /**\n * Deserializes binary data from a Buffer into a structured object according to the defined schema.\n *\n * @param buffer - The binary buffer containing the serialized data to convert to an object\n * @param getDynamicOffset - Optional callback function that receives the offset of dynamic content that changes the buffer's static size.\n * The offset represents the difference between the original and final buffer positions.\n *\n * @throws Error - When the provided input is not a Buffer instance\n * @throws Error - When the provided buffer size is smaller than the expected schema size\n * @throws DeserializationError - When buffer data doesn't match the expected schema format\n *\n * @since 2.0.0\n */\n\n toObject(buffer: Buffer, getDynamicOffset?: (offset: number) => void): Required<T> {\n if(!Buffer.isBuffer(buffer))\n throw new Error(`Expected a buffer, but received ${ typeof buffer }`);\n\n if(buffer.length < this.size)\n throw new Error(`Buffer size is less than expected: ${ buffer.length } < ${ this.size }`);\n\n const result: Record<string, unknown> = {};\n const context: ContextInterface = {\n buffer,\n offset: 0\n } as ContextInterface;\n\n for (const [ name, descriptor ] of this.schema) {\n context.descriptor = descriptor;\n result[name] = this.readValue(context, descriptor.kind);\n }\n\n if (getDynamicOffset && typeof getDynamicOffset === 'function')\n getDynamicOffset(context.offset);\n\n return result as Required<T>;\n }\n\n /**\n * Serializes a structured object into a binary buffer according to the defined schema.\n *\n * @param data - The object containing fields to be serialized\n * @returns A buffer containing the binary representation of the data\n *\n * @throws Error - When input is not an object or when field values don't match their type definitions\n *\n * @since 2.0.0\n */\n\n toBuffer(data: T): Buffer {\n if (!data || typeof data !== 'object')\n throw new Error(`Expected an object of fields, but received ${ typeof data }`);\n\n const context: ContextInterface = {\n buffer: Buffer.alloc(this.size),\n offset: 0\n } as ContextInterface;\n\n for (const [ name, descriptor ] of this.schema) {\n context.descriptor = descriptor;\n const value = data[name as keyof T];\n this.writeValue(context, descriptor.kind, value);\n }\n\n return context.buffer;\n }\n\n /**\n * Reads a value from the buffer based on its descriptor kind.\n *\n * @param context - The current reading context containing buffer and offset information\n * @param kind - The descriptor kind that determines how to interpret binary data\n * @returns The deserialized value of the appropriate type\n *\n * @see ContextInterface\n * @see PositionedDescriptorInterface\n *\n * @since 2.0.0\n */\n\n private readValue(context: ContextInterface, kind: PositionedDescriptorInterface['kind']): unknown {\n switch (kind) {\n case 'struct':\n return readStruct.call(context as StructContextInterface);\n case 'bitfield':\n return readBitfield.call(context as BitfieldContextInterface);\n case 'string':\n return readString.call(context as StringContextInterface);\n default:\n return readPrimitive.call(context as PrimitiveContextInterface);\n }\n }\n\n /**\n * Writes a value to the buffer based on its descriptor kind.\n *\n * @param context - The current writing context containing buffer and offset information\n * @param kind - The descriptor kind that determines how to serialize the data\n * @param value - The value to write into the buffer\n *\n * @throws Error - When the value type doesn't match the expected type for the given descriptor\n *\n * @see ContextInterface\n * @see PositionedDescriptorInterface\n *\n * @since 2.0.0\n */\n\n private writeValue(context: ContextInterface, kind: PositionedDescriptorInterface['kind'], value: unknown): void {\n switch (kind) {\n case 'struct':\n writeStruct.call(context as StructContextInterface, value as StructDataType);\n break;\n case 'bitfield':\n writeBitfield.call(context as BitfieldContextInterface, value as number);\n break;\n case 'string':\n writeString.call(context as StringContextInterface, value as StringDataType);\n break;\n default:\n writePrimitive.call(context as PrimitiveContextInterface, value as PrimitiveDataType);\n }\n }\n\n /**\n * Calculates the size and position of a field within the binary structure.\n *\n * @param field - The field descriptor containing type information\n * @param position - The current position in the buffer where this field should be placed\n * @returns A positioned field descriptor with size and position information\n *\n * @throws Error - When an invalid field type is encountered\n *\n * @see DescriptorFieldType\n * @see PositionedDescriptorFieldType\n *\n * @since 2.0.0\n */\n\n private computeFieldSize(field: DescriptorFieldType, position: number): PositionedDescriptorFieldType {\n if (field.type instanceof Struct)\n return { ...field, position, size: field.type.size, kind: 'struct' };\n\n if (STRING_PRIMITIVE_LIST.has(field.type as StringType))\n return this.computeStringFieldSize(field, position);\n\n const size = PRIMITIVE_TYPE_SIZES[field.type as PrimitiveType];\n if (size !== undefined)\n return { ...field, position, size: size / 8, kind: 'primitive' };\n\n throw new Error(`Invalid field type: ${ field.type }`);\n }\n\n /**\n * Calculates the size and position information for string fields based on their configuration.\n *\n * @param field - The string field descriptor containing type and encoding information\n * @param position - The current position in the buffer where this field should be placed\n * @returns A positioned string field descriptor with size and position information\n *\n * @see DescriptorFieldType\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\n private computeStringFieldSize(field: DescriptorFieldType, position: number): PositionedStringDescriptorType {\n const positionedDescriptor: PositionedStringDescriptorType = {\n ...field,\n position,\n kind: 'string'\n } as PositionedStringDescriptorType;\n\n if ('lengthType' in field && field.lengthType) {\n const primitiveSize = PRIMITIVE_TYPE_SIZES[field.lengthType as PrimitiveType];\n if (!primitiveSize) {\n throw new Error(`Invalid length type: ${field.lengthType}`);\n }\n\n positionedDescriptor.size = primitiveSize / 8;\n } else if ('nullTerminated' in field && field.nullTerminated) {\n positionedDescriptor.size = 0;\n } else if (!('size' in field) || !field.size) {\n (positionedDescriptor as LengthPrefixedDescriptorInterface).lengthType = 'UInt16LE';\n positionedDescriptor.size = PRIMITIVE_TYPE_SIZES['UInt16LE'] / 8;\n }\n\n return positionedDescriptor;\n }\n\n /**\n * Parses a string field notation into a properly typed descriptor with position information.\n *\n * @param fieldNotation - The string representation of the field definition\n * @param offset - The current offset in the buffer where this field should be placed\n * @returns A positioned field descriptor with the appropriate type (bitfield, string, or primitive)\n *\n * @see StringFieldType\n * @see PositionedDescriptorFieldType\n *\n * @since 2.0.0\n */\n\n\n private parseStringNotation(fieldNotation: StringFieldType, offset: number): PositionedDescriptorFieldType {\n if (fieldNotation.includes(':'))\n return parseBitfieldDescriptor(fieldNotation, offset);\n\n const stringType = [ ...STRING_PRIMITIVE_LIST ].find(prefix =>\n fieldNotation.startsWith(prefix));\n\n return stringType\n ? parseStringDescriptor(fieldNotation, offset)\n : parsePrimitiveDescriptor(fieldNotation, offset);\n }\n\n /**\n * Converts a field definition into a positioned descriptor with size information.\n *\n * @param field - The field to convert, which can be a Struct instance, string notation, or field descriptor\n * @param position - The current position in the buffer where this field should be placed\n * @returns A positioned field descriptor with calculated size and position information\n *\n * @see FieldsType\n * @see PositionedDescriptorFieldType\n *\n * @since 2.0.0\n */\n\n private convertToSizedField(field: FieldsType, position: number): PositionedDescriptorFieldType {\n if (field instanceof Struct)\n return { type: field, position, size: field.size, kind: 'struct' };\n\n return typeof field === 'string'\n ? this.parseStringNotation(field, position)\n : this.computeFieldSize(field, position);\n }\n\n /**\n * Compiles a schema definition into a binary structure with calculated field positions and sizes.\n *\n * @param schema - The structure schema definition containing field definitions\n * @returns The total size of the compiled structure in bytes\n *\n * @throws Error - If any field's array size exceeds Number.MAX_SAFE_INTEGER\n *\n * @remarks\n * This method processes the schema field by field, handling both standard fields and bitfields.\n * For bitfields, it tracks bit positions and packs them appropriately.\n * The final byte count includes any remaining bits from the last bitfield.\n *\n * @see StructSchemaInterface\n * @since 2.0.0\n */\n\n private compileSchema(schema: StructSchemaInterface): number {\n const accumulator: AccumulatorInterface = {\n bits: 0,\n bytes: 0,\n bitFieldSize: 0,\n bitFieldType: 'UInt8'\n };\n\n for (const [ fieldName, field ] of Object.entries(schema)) {\n const sizedField = this.convertToSizedField(field, accumulator.bytes);\n if('arraySize' in sizedField && sizedField.arraySize) {\n if(sizedField.arraySize >= Number.MAX_SAFE_INTEGER) {\n throw new Error(`Array size exceeds maximum safe integer: ${ sizedField.arraySize }`);\n }\n }\n\n if ('bitSize' in sizedField && sizedField.bitSize > 0) {\n this.processBitfield(accumulator, fieldName, sizedField);\n } else {\n this.processStandardField(accumulator, fieldName, sizedField);\n }\n }\n\n if (accumulator.bits > 0)\n accumulator.bytes += accumulator.bitFieldSize;\n\n return accumulator.bytes;\n }\n\n /**\n * Processes a bitfield descriptor and updates the structure's accumulator.\n *\n * @param accumulator - The current state accumulator for the schema compilation\n * @param name - The field name in the schema\n * @param field - The positioned bitfield descriptor with size and type information\n\n * @remarks\n * This method handles the placement of bitfields within the structure.\n * It determines whether a new bitfield container needs to be started based on:\n * - If the current bitfield is full\n * - If the requested type differs from the current bitfield type\n * - If the sizes don't match\n *\n * When a new bitfield container is needed, the byte position is advanced\n * and bit counting resets. The field's bit position is tracked for later\n * value extraction/insertion.\n *\n * @see AccumulatorInterface\n * @see PositionedBitfieldDescriptorType\n *\n * @since 2.0.0\n */\n\n private processBitfield(accumulator: AccumulatorInterface, name: string, field: PositionedBitfieldDescriptorType): void {\n const bitsInField = field.size * 8;\n const requestedBitSize = field.bitSize;\n\n const needsNewBitfield =\n accumulator.bits + requestedBitSize > bitsInField ||\n accumulator.bitFieldType !== field.type ||\n accumulator.bitFieldSize !== field.size;\n\n if (needsNewBitfield) {\n accumulator.bytes += accumulator.bitFieldSize;\n accumulator.bits = 0;\n field.position = accumulator.bytes;\n }\n\n field.bitPosition = accumulator.bits;\n this.schema.set(name, field);\n\n accumulator.bits += requestedBitSize;\n accumulator.bitFieldType = field.type;\n accumulator.bitFieldSize = field.size;\n }\n\n /**\n * Processes a standard (non-bitfield) field descriptor and updates the structure's accumulator.\n *\n * @param accumulator - The current state accumulator for the schema compilation\n * @param name - The field name in the schema\n * @param field - The positioned field descriptor with size information\n *\n * @remarks\n * This method handles the placement of standard fields within the structure.\n * If there's an active bitfield being processed (accumulator.bits \\> 0), it finalizes\n * that bitfield first by advancing the byte position before placing this new field.\n *\n * For array fields, the total size is calculated as the product of the element size\n * and the array size. The accumulator's byte position is advanced by the total field size.\n *\n * @see AccumulatorInterface\n * @see PositionedDescriptorFieldType\n *\n * @since 2.0.0\n */\n\n private processStandardField(accumulator: AccumulatorInterface, name: string, field: PositionedDescriptorFieldType): void {\n if (accumulator.bits > 0) {\n accumulator.bytes += accumulator.bitFieldSize;\n accumulator.bits = 0;\n field.position = accumulator.bytes;\n }\n\n this.schema.set(name, field);\n const arraySize = 'arraySize' in field ? field.arraySize || 0 : 0;\n const totalSize = arraySize > 0 ? field.size * arraySize : field.size;\n accumulator.bytes += totalSize;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PacketLogInterface, PacketStatusInterface } from '@packets/interfaces/packet-schema.interface';\nimport type { PacketErrorInterface, PacketEventsInterface } from '@packets/interfaces/packet-schema.interface';\nimport type { PacketHeaderInterface, PacketInvocationInterface } from '@packets/interfaces/packet-schema.interface';\n\n/**\n * Imports\n */\n\nimport { Struct } from '@remotex-labs/xstruct';\n\n/**\n * Schema for serializing and deserializing {@link PacketInvocationInterface} data.\n *\n * @remarks\n * Represents the location in source code where a test, describe, or log originates.\n *\n * @since 1.0.0\n */\n\nexport const invocationSchema = new Struct<PacketInvocationInterface>({\n line: 'UInt32LE',\n column: 'UInt32LE',\n source: 'string'\n});\n\n/**\n * Schema for serializing and deserializing {@link PacketHeaderInterface} data.\n *\n * @remarks\n * Contains metadata for each packet, including kind, suite and runner identifiers, and timestamp.\n *\n * @since 1.0.0\n */\n\nexport const headerSchema = new Struct<PacketHeaderInterface>({\n kind: 'UInt8:4',\n suiteId: { type: 'string', size: 14 },\n runnerId: { type: 'string', size: 14 },\n timestamp: 'string'\n});\n\n/**\n * Schema for serializing and deserializing {@link PacketLogInterface} data.\n *\n * @remarks\n * Used for console-like logs emitted by tests or describes, including message, level, ancestry, and invocation.\n *\n * @since 1.0.0\n */\n\nexport const logSchema = new Struct<PacketLogInterface>({\n level: 'UInt8',\n message: { type: 'string', lengthType: 'UInt32LE' },\n ancestry: { type: 'string', lengthType: 'UInt32LE' },\n invocation: invocationSchema\n});\n\n/**\n * Schema for serializing and deserializing {@link PacketErrorInterface} data.\n *\n * @remarks\n * Represents suite-level fatal errors that are not tied to specific tests or describes.\n *\n * @since 1.0.0\n */\n\nexport const errorSchema = new Struct<PacketErrorInterface>({\n error: { type: 'string', lengthType: 'UInt32LE' }\n});\n\n/**\n * Schema for serializing and deserializing {@link PacketStatusInterface} data.\n *\n * @remarks\n * Represents status updates for individual tests or describe blocks,\n * including whether it is TODO, skipped, and its ancestry and description.\n *\n * @since 1.0.0\n */\n\nexport const statusSchema = new Struct<PacketStatusInterface>({\n type: 'UInt8:5',\n todo: 'UInt8:1',\n skipped: 'UInt8:1',\n duration: 'UInt32LE',\n ancestry: { type: 'string', lengthType: 'UInt32LE' },\n description: { type: 'string', lengthType: 'UInt32LE' }\n});\n\n/**\n * Schema for serializing and deserializing {@link PacketEventsInterface} data.\n *\n * @remarks\n * Represents events emitted during the test or describe execution,\n * including pass/fail status, duration, error messages, ancestry, and invocation.\n *\n * @since 1.0.0\n */\n\nexport const eventsSchema = new Struct<PacketEventsInterface>({\n type: 'UInt8:5',\n passed: 'UInt8:1',\n duration: 'UInt32LE',\n ancestry: { type: 'string', lengthType: 'UInt32LE' },\n description: { type: 'string', lengthType: 'UInt32LE' },\n errors: { type: 'string', lengthType: 'UInt32LE' }\n});\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Struct } from '@remotex-labs/xstruct';\n\n/**\n * Imports\n */\n\nimport { errorSchema, eventsSchema, logSchema, statusSchema } from '@packets/schema/packet.schema';\n\n/**\n * Defines the different kinds of packets that can be transmitted or received.\n *\n * @remarks\n * Each packet kind corresponds to a specific type of event or message in the test framework:\n * - `Log`: Console or logging messages\n * - `Error`: Suite-level fatal errors\n * - `Status`: Test or describe start events, including `skipped` and `todo` flags\n * - `Events`: Test or describe end events, only for completed tests/describes (no skipped or TODO)\n *\n * @since 1.0.0\n */\n\nexport const enum PacketKind {\n /**\n * Represents a log message packet, e.g., `console.log`, `console.error`.\n * @since 1.0.0\n */\n\n Log = 1,\n\n /**\n * Represents a fatal suite-level error.\n * Not associated with any test, describe, or hook.\n * @since 1.0.0\n */\n\n Error = 2,\n\n /**\n * Represents a status packet for test or describe start events.\n *\n * @remarks\n * Includes flags for:\n * - `skipped`: Whether the test or describe was skipped\n * - `todo`: Whether the test is marked as TODO\n *\n * @since 1.0.0\n */\n\n Status = 3,\n\n /**\n * Represents an event packet for test or describe end events.\n *\n * @remarks\n * Only includes completed tests/describes; skipped or TODO tests are not included.\n * Contains information such as `passed` and `duration`.\n *\n * @since 1.0.0\n */\n\n Events = 4\n}\n\n/**\n * Maps each {@link PacketKind} to its corresponding {@link Struct} schema for serialization/deserialization.\n *\n * @remarks\n * This object allows encoding and decoding packets of different kinds using\n * their respective `xStruct` schemas. Use `PacketSchemas[PacketKind.Log]` to\n * get the schema for log packets, etc.\n *\n * @see PacketKind\n * @see Struct\n *\n * @since 1.0.0\n */\n\nexport const PacketSchemas: Record<PacketKind, Struct> = {\n [PacketKind.Log]: logSchema,\n [PacketKind.Error]: errorSchema,\n [PacketKind.Status]: statusSchema,\n [PacketKind.Events]: eventsSchema\n} as const;\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PacketHeaderInterface } from '@packets/interfaces/packet-schema.interface';\nimport type { DecodedPacketType, PacketPayloadMapType } from '@packets/interfaces/packets.interface';\n\n/**\n * Imports\n */\n\nimport { serializeError } from '@remotex-labs/xjet-expect';\nimport { PacketKind } from '@packets/constants/packet-schema.constants';\nimport { errorSchema, headerSchema } from '@packets/schema/packet.schema';\nimport { PacketSchemas } from '@packets/constants/packet-schema.constants';\n\n/**\n * Exports constants\n */\n\nexport * from '@packets/constants/packet-schema.constants';\n\n/**\n * Exports interfaces\n */\n\nexport * from '@packets/interfaces/packets.interface';\nexport * from '@packets/interfaces/packet-schema.interface';\n\n/**\n * Encodes a packet of a given kind into a `Buffer`.\n *\n * @template T - The packet kind (`PacketKind.Log`, `PacketKind.Error`, `PacketKind.Status`, or `PacketKind.Events`)\n *\n * @param kind - The type of packet to encode\n * @param data - Partial data matching the packet type; will be combined with header information\n *\n * @returns A `Buffer` containing the serialized packet\n *\n * @throws Error if the provided `kind` does not correspond to a known packet schema\n *\n * @remarks\n * This function combines a header and the payload according to the packet kind.\n * The header includes the suite ID, runner ID, and a timestamp.\n *\n * @since 1.0.0\n */\n\nexport function encodePacket<T extends PacketKind>(kind: T, data: Partial<PacketPayloadMapType[T]>): Buffer {\n const schema = PacketSchemas[kind];\n if (!schema) throw new Error(`Invalid schema kind: ${ kind }`);\n\n const header: PacketHeaderInterface = {\n kind: kind,\n suiteId: globalThis?.__XJET?.runtime?.suiteId ?? '',\n runnerId: globalThis?.__XJET?.runtime.runnerId ?? '',\n timestamp: (new Date()).toISOString()\n };\n\n return Buffer.concat([\n headerSchema.toBuffer(header),\n schema.toBuffer(data)\n ]);\n}\n\n/**\n * Decodes a packet from a `Buffer` into its corresponding object representation.\n *\n * @template T - The expected packet kind (`PacketKind.Log`, `PacketKind.Error`, `PacketKind.Status`, or `PacketKind.Events`)\n *\n * @param buffer - The buffer containing the encoded packet\n * @returns The decoded packet object, combining the header and payload fields\n *\n * @throws Error if the packet kind is unknown or invalid\n *\n * @remarks\n * Decodes both the header and payload based on the packet kind.\n *\n * @since 1.0.0\n */\n\nexport function decodePacket<T extends PacketKind>(buffer: Buffer): DecodedPacketType<T> {\n let offset = headerSchema.size;\n const header = headerSchema.toObject(buffer, (dynamicOffset: number): void => {\n offset += dynamicOffset;\n });\n\n const type = header.kind as PacketKind;\n const schema = PacketSchemas[type];\n if (!schema) {\n throw new Error(`Unknown packet kind: ${ type }`);\n }\n\n const dataBuffer = buffer.subarray(offset);\n const data = schema.toObject(dataBuffer) as PacketPayloadMapType[T];\n\n return { ...header, ...data };\n}\n\n/**\n * Encodes an {@link Error} instance into a binary buffer following the packet schema.\n *\n * @param error - The error object to be serialized and encoded.\n * @param suiteId - Identifier of the suite where the error occurred.\n * @param runnerId - Identifier of the runner reporting the error.\n *\n * @returns A {@link Buffer} containing the encoded error packet, ready for transmission.\n *\n * @remarks\n * The function creates two binary sections:\n * - A **header**, describing the packet kind (`Error`), suite ID, runner ID, and timestamp.\n * - A **data buffer**, holding the serialized error details in JSON format.\n *\n * These two sections are concatenated into a single buffer.\n *\n * @example\n * ```ts\n * try {\n * throw new Error(\"Test failed\");\n * } catch (err) {\n * const buffer = encodeErrorSchema(err, \"suite-123\", \"runner-456\");\n * socket.send(buffer); // transmit over a transport channel\n * }\n * ```\n *\n * @see serializeError\n * @see PacketKind.Error\n *\n * @since 1.0.0\n */\n\nexport function encodeErrorSchema(error: Error, suiteId: string, runnerId: string): Buffer {\n const header = headerSchema.toBuffer({\n kind: PacketKind.Error,\n suiteId: suiteId ?? '',\n runnerId: runnerId ?? '',\n timestamp: (new Date()).toISOString()\n });\n\n const dataBuffer = errorSchema.toBuffer({\n error: JSON.stringify(serializeError(error))\n });\n\n return Buffer.concat([ header, dataBuffer ]);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MessageType } from '@messages/constants/report.constant';\nimport type { EmitEventInterface, EmitStatusInterface } from '@shared/services/interfaces/emit-service.interface';\n\n/**\n * Imports\n */\n\nimport { serializeError } from '@remotex-labs/xjet-expect';\nimport { encodePacket, PacketKind } from '@packets/packets.module';\n\n/**\n * Emits a status update packet to the dispatcher.\n *\n * @param type - The {@link MessageType} representing the kind of status (e.g., suite start, suite end).\n * @param notification - The {@link EmitStatusInterface} containing ancestry and description details.\n *\n * @remarks\n * This function encodes the notification into a `PacketKind.Status` packet\n * and sends it via the global `dispatch` mechanism.\n *\n * @see MessageType\n * @see encodePacket\n * @see PacketKind.Status\n * @see EmitStatusInterface\n *\n * @since 1.0.0\n */\n\nexport function emitStatus(type: MessageType, notification: EmitStatusInterface = {}): void {\n dispatch(encodePacket(PacketKind.Status, {\n type: type,\n todo: notification?.todo,\n skipped: notification?.skipped,\n duration: notification?.duration,\n ancestry: notification?.ancestry?.join(','),\n description: notification?.description\n }));\n}\n\n/**\n * Emits an action (event) packet to the dispatcher.\n *\n * @param type - The {@link MessageType} representing the kind of action (e.g., test end, describe end).\n * @param notification - The {@link EmitEventInterface} containing ancestry, description,\n * duration, and possible test errors.\n *\n * @remarks\n * - Errors are serialized with {@link serializeError} before being encoded.\n * - The function encodes the notification into a `PacketKind.Events` packet\n * and sends it via the global `dispatch` mechanism.\n *\n * @see MessageType\n * @see encodePacket\n * @see serializeError\n * @see PacketKind.Events\n * @see EmitEventInterface\n *\n * @since 1.0.0\n */\n\nexport function emitEvent(type: MessageType, notification: EmitEventInterface): void {\n const stringErrors = notification.errors?.map((error: Error) =>\n serializeError(error)\n ) || [];\n\n dispatch(encodePacket(PacketKind.Events, {\n type: type,\n errors: stringErrors.length > 0 ? JSON.stringify(stringErrors) : '',\n ancestry: notification.ancestry.join(''),\n duration: notification.duration,\n description: notification.description\n }));\n}\n", "/**\n * Defines the log verbosity levels for reporters and test execution.\n *\n * @remarks\n * Each level represents the minimum severity of messages that should be\n * captured or displayed. Higher levels include all messages from lower levels.\n *\n * @example\n * ```ts\n * if (log.level >= LogLevel.Warn) {\n * console.warn(log.message);\n * }\n * ```\n *\n * @since 1.0.0\n */\n\nexport enum LogLevel {\n Silent = 0,\n Error = 1,\n Warn = 2,\n Info = 3,\n Debug = 4\n}\n\n/**\n * Defines the types of messages emitted during test execution.\n *\n * @remarks\n * These message types are used internally by reporters, runners,\n * and event emitters to categorize test events. Each type corresponds\n * to a specific stage or element of the test lifecycle.\n *\n * @example\n * ```ts\n * if (message.type === MessageType.Test) {\n * console.log('Test event received');\n * }\n * ```\n *\n * @since 1.0.0\n */\n\nexport const enum MessageType {\n Test = 1,\n Describe = 2,\n EndSuite = 3,\n StartSuite = 4\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { HookModel } from './hook.model';\nimport type { TestModel } from '@shared/models/test.model';\nimport type { ContextType } from '@remotex-labs/xjet-expect';\nimport type { ContextInterface } from '@shared/models/interfaces/describe-model.interface';\nimport type { DescribeHooksInterface } from '@shared/models/interfaces/describe-model.interface';\nimport type { DescribeOptionsInterface } from '@shared/models/interfaces/describe-model.interface';\n\n/**\n * Imports\n */\n\nimport { MessageType } from '@messages/constants/report.constant';\nimport { emitEvent, emitStatus } from '@shared/services/emit.service';\nimport { HookType } from '@shared/models/constants/hook.model.constants';\n\n/**\n * Represents a test suite container that manages test execution flow and hierarchy\n *\n * @template T - Context type for test execution\n * @param description - The description of the test suite\n * @param describeFlags - Configuration options for the test suite\n * @returns A new DescribeModel instance that can contain tests and nested suites\n *\n * @remarks\n * The DescribeModel manages the execution lifecycle of tests, including\n * - Maintaining parent-child relationships between test suites\n * - Executing hooks in the correct order (beforeAll, beforeEach, afterEach, afterAll)\n * - Tracking test execution status and reporting results\n * - Supporting test filtering with skip/only options\n *\n * @example\n * ```ts\n * const rootSuite = new DescribeModel('Root suite');\n * const testCase = new TestModel('should work', () => {\n * expect(true).toBe(true);\n * });\n * rootSuite.addTest(testCase);\n * await rootSuite.run({});\n * ```\n *\n * @see TestModel\n * @see HookModel\n * @see DescribeHooksInterface\n *\n * @since 1.0.0\n */\n\nexport class DescribeModel {\n /**\n * Array containing the hierarchical path of parent describe blocks for this test suite\n *\n * @since 1.0.0\n */\n\n readonly ancestry: string[] = [];\n\n /**\n * Collection of test cases directly contained within this test suite\n *\n * @internal\n * @since 1.0.0\n */\n\n readonly testsStack: TestModel[] = [];\n\n /**\n * Collection of nested test suites within this suite\n *\n * @internal\n * @since 1.0.0\n */\n\n readonly describesStack: DescribeModel[] = [];\n\n /**\n * Timestamp when the test suite execution started\n *\n * @default 0\n * @internal\n * @since 1.0.0\n */\n\n private startTime = 0;\n\n /**\n * Collection of lifecycle hooks for this test suite\n *\n * @internal\n * @since 1.0.0\n */\n\n private readonly hooks: DescribeHooksInterface = {\n afterAll: [],\n afterEach: [],\n beforeAll: [],\n beforeEach: []\n };\n\n /**\n * Creates a new test suite with the specified description and options\n *\n * @param description - Human-readable description of the test suite\n * @param describeOptions - Configuration options to control test suite execution\n *\n * @since 1.0.0\n */\n\n constructor(\n readonly description: string = '',\n private readonly describeOptions: DescribeOptionsInterface = { skip: false, only: false }\n ) {\n }\n\n /**\n * Retrieves the execution configuration options for this test suite\n *\n * @returns Test suite configuration options\n *\n * @since 1.0.0\n */\n\n get options(): DescribeOptionsInterface {\n return this.describeOptions;\n }\n\n /**\n * Gets all tests in this suite, including tests from nested suites\n *\n * @returns Flattened array of all tests in this suite and its children\n *\n * @remarks\n * Recursively collects and flattens all test cases from this suite and any nested suites\n *\n * @since 1.0.0\n */\n\n get tests(): TestModel[] {\n // Use flatMap for cleaner code and better performance\n return [\n ...this.testsStack,\n ...this.describesStack.flatMap(child => child.tests)\n ];\n }\n\n /**\n * Registers a hook function to be executed at a specific point in the test lifecycle\n *\n * @param type - The lifecycle point at which to execute the hook\n * @param hook - The hook function model to register\n *\n * @throws Error - If an invalid hook type is provided\n *\n * @since 1.0.0\n */\n\n addHook(type: HookType, hook: HookModel): void {\n const hookArray = this.hooks[type];\n if (!hookArray) {\n throw new Error(`Invalid hook type: ${ type }`);\n }\n\n hookArray.push(hook);\n }\n\n /**\n * Adds a test case to this test suite\n *\n * @param test - The test model to add to the suite\n *\n * @remarks\n * When adding a test, this method automatically:\n * - Updates the test's ancestry to include this suite\n * - Propagates execution options (skip/only) from the suite to the test\n *\n * @since 1.0.0\n */\n\n addTest(test: TestModel): void {\n if (!test) return;\n\n test.setAncestry(this.ancestry);\n if (this.description) test.setAncestry([ this.description ]);\n test.applyExecutionFlags(this.options.skip, this.options.only);\n this.testsStack.push(test);\n }\n\n /**\n * Adds a nested test describe to this test describe\n *\n * @param describe - The child test describe to add\n *\n * @remarks\n * When adding nested describe, this method automatically:\n * - Sets up the parent-child relationship\n * - Propagates execution options and ancestry information from parent to child\n *\n * @since 1.0.0\n */\n\n addDescribe(describe: DescribeModel): void {\n if (!describe) return;\n\n describe.inheritFromParentDescribe(this);\n this.describesStack.push(describe);\n }\n\n /**\n * Executes the test suite and all contained tests\n *\n * @param context - The test execution context containing shared state\n * @returns Promise that resolves when all tests in the suite complete\n *\n * @remarks\n * Execution follows this order:\n * 1. Check if the suite is marked as skipped\n * 2. Execute all beforeAll hooks\n * 3. Run all tests in this suite\n * 4. Run all nested test suites\n * 5. Execute all afterAll hooks\n * If any step fails, the entire suite is marked as failed\n *\n * @example\n * ```ts\n * const suite = new DescribeModel('My test suite');\n * const context = createTestContext();\n * await suite.run(context);\n * ```\n *\n * @since 1.0.0\n */\n\n async run(context: ContextType<ContextInterface>): Promise<void> {\n this.startTime = Date.now();\n this.notifyDescribeStatus(this.options.skip);\n const afterAllErrorsEmpty = !context.afterAllErrors?.length;\n const beforeAllErrorsEmpty = !context.beforeAllErrors?.length;\n\n try {\n if (!context.beforeAllErrors?.length)\n await this.executeHooks(HookType.BEFORE_ALL, context);\n\n for (const test of this.shuffleTests(this.testsStack)) {\n if(context.hasError) return;\n await test.run(context, this.executeHooks.bind(this));\n }\n\n for (const describe of this.describesStack) {\n if(context.hasError) return;\n await describe.run(context);\n }\n\n await this.executeHooks(HookType.AFTER_ALL, context);\n\n if (context.afterAllErrors?.length) this.notifyDescribeFailure(context.afterAllErrors);\n else this.notifyDescribeAction();\n } catch (error) {\n this.notifyDescribeFailure([ error, ...context.afterAllErrors ]);\n if(globalThis.__XJET?.runtime.bail) {\n context.hasError = true;\n }\n } finally {\n if (afterAllErrorsEmpty) context.afterAllErrors = [];\n if (beforeAllErrorsEmpty) context.beforeAllErrors = [];\n }\n }\n\n /**\n * Inherits properties from a parent test suite\n *\n * @param parent - The parent test describe to inherit from\n *\n * @remarks\n * This method performs the following inheritance operations:\n * - Adds parent's ancestry chain to this suite's ancestry\n * - Propagates the 'skip' flag (if parent is skipped, child is skipped)\n * - Propagates the 'only' flag if the parent has it set\n *\n * @since 1.0.0\n */\n\n inheritFromParentDescribe(parent: DescribeModel): void {\n this.ancestry.push(...parent.ancestry);\n this.hooks.beforeEach = [ ...parent.hooks.beforeEach, ...this.hooks.beforeEach ];\n this.hooks.afterEach = [ ...parent.hooks.afterEach, ...this.hooks.afterEach ];\n\n if (parent.description)\n this.ancestry.push(parent.description);\n\n if (parent.options.skip) {\n this.describeOptions.skip = true;\n }\n\n if (parent.options.only) {\n this.describeOptions.only = true;\n }\n }\n\n /**\n * Executes all hooks of the specified type in sequence\n *\n * @param type - The lifecycle hook type to execute\n * @param context - The test execution context\n *\n * @throws Error - When a beforeEach or afterEach hook fails\n *\n * @remarks\n * Errors in beforeAll hooks are collected but don't immediately abort execution.\n * Errors in afterAll hooks are collected for reporting.\n * Errors in beforeEach/afterEach hooks cause immediate test failure.\n *\n * @internal\n * @since 1.0.0\n */\n\n private async executeHooks(type: HookType, context: ContextType<ContextInterface>): Promise<void> {\n if (this.options.skip) return;\n context.beforeAllErrors = context.beforeAllErrors || [];\n context.afterAllErrors = context.afterAllErrors || [];\n\n for (const hook of this.hooks[type]) {\n try {\n await hook.run(context);\n } catch (error) {\n await this.handleHookError(type, error, context);\n }\n }\n }\n\n /**\n * Handles errors that occur during hook execution\n *\n * @param type - The type of hook where the error occurred\n * @param error - The error that was thrown\n * @param context - The test execution context\n *\n * @throws Error - When the error occurs in a beforeEach or afterEach hook\n *\n * @remarks\n * Error handling differs by hook type:\n * - beforeAll: Error is collected but execution continues\n * - afterAll: Error is collected for reporting\n * - beforeEach/afterEach: Error is immediately thrown to fail the test\n *\n * @internal\n *\n * @since 1.0.0\n */\n\n private async handleHookError(type: HookType, error: unknown, context: ContextType<ContextInterface>): Promise<void> {\n if (type === HookType.BEFORE_ALL) {\n context.beforeAllErrors.push(error);\n } else if (type === HookType.AFTER_ALL) {\n context.afterAllErrors.push(error);\n } else {\n throw error;\n }\n }\n\n /**\n * Calculates the execution duration of the test suite in milliseconds\n *\n * @returns Duration in milliseconds since the test started, or 0 if not started\n *\n * @remarks\n * Returns the elapsed time between when the suite started execution and the current time\n * If the suite hasn't started (startTime is 0), returns 0 instead\n *\n * @internal\n * @since 1.0.0\n */\n\n private getExecutionDuration(): number {\n if (this.startTime === 0)\n return 0;\n\n return Date.now() - this.startTime;\n }\n\n private notifyDescribeStatus(skip: boolean = false): void {\n emitStatus(MessageType.Describe, {\n skipped: skip,\n ancestry: this.ancestry,\n description: this.description\n });\n }\n\n private notifyDescribeAction(errors: Array<unknown> = []): void {\n emitEvent(MessageType.Describe, {\n errors: <Array<Error>> errors,\n ancestry: this.ancestry,\n description: this.description,\n duration: this.getExecutionDuration()\n });\n }\n\n /**\n * Reports test suite failure with associated errors\n *\n * @param errors - Collection of errors that caused the test suite to fail\n *\n * @remarks\n * Skips reporting if no errors are provided\n * Uses notifyDescribeAction to emit a failure event with the error details\n *\n * @internal\n * @since 1.0.0\n */\n\n private notifyDescribeFailure(errors: Array<unknown>): void {\n if (!errors?.length) return;\n\n this.notifyDescribeAction(errors);\n }\n\n /**\n * Randomizes the order of tests in an array using the Fisher-Yates shuffle algorithm\n *\n * @param testsToShuffle - Array of test models to be randomly reordered\n * @returns The same array with elements potentially reordered in a random sequence\n *\n * @remarks\n * The shuffling only occurs if the global randomization flag is enabled\n * (accessed via globalThis.__XJET?.runtime.randomize) and the array has more\n * than one element. The algorithm used is Fisher-Yates shuffle, which ensures\n * each permutation has equal probability.\n *\n * @example\n * ```ts\n * const tests = [new TestModel('test1'), new TestModel('test2')];\n * const randomizedTests = this.shuffleTests(tests);\n * // The order of tests may be different from the original if randomization is enabled\n * ```\n *\n * @internal\n * @since 1.0.0\n */\n\n private shuffleTests(testsToShuffle: Array<TestModel>): Array<TestModel> {\n const randomize = globalThis.__XJET?.runtime.randomize ?? false;\n if (!randomize || testsToShuffle.length <= 1) return testsToShuffle;\n const length = testsToShuffle.length;\n\n // Start from the last element and swap with a random element\n // before the current position (including itself)\n for (let i = length - 1; i > 0; i--) {\n // Generate a random index from 0 to i (inclusive)\n const j = Math.floor(Math.random() * (i + 1));\n\n // Swap elements at indices i and j\n // Use destructuring assignment for a clean swap without a temp variable\n [ testsToShuffle[i], testsToShuffle[j] ] = [ testsToShuffle[j], testsToShuffle[i] ];\n }\n\n return testsToShuffle;\n }\n}\n", "/**\n * A base error class that extends the standard Error class with enhanced JSON serialization and location tracking\n *\n * @param message - The error message describing what went wrong\n * @param location - The precise source code location where the error occurred\n * @returns The constructed ExecutionError instance\n *\n * @remarks\n * Serves as a foundation for custom error types in the application.\n * It enhances the native Error object by adding JSON serialization capabilities\n * and source code location information, allowing for better error reporting,\n * debugging, and troubleshooting. The location tracking feature helps pinpoint\n * exactly where in the codebase an error originated.\n *\n * @example\n * ```ts\n * // Creating a basic execution error with location information\n * const error = new ExecutionError(\n * 'Failed to process data',\n * { line: 42, column: 10 }\n * );\n *\n * // The error can be thrown or used in promise rejection\n * throw error;\n * ```\n *\n * @see InvocationLocationType\n *\n * @since 1.0.0\n */\n\nexport class ExecutionError extends Error {\n\n /**\n * Creates a new ExecutionError instance with the specified error message and source code location\n *\n * @param message - The error message describing what went wrong\n *\n * @remarks\n * This constructor initializes both the standard Error message property and the location\n * information that helps pinpoint exactly where in the codebase the error originated. The\n * location parameter follows the InvocationLocationType structure, typically containing\n * line and column information.\n *\n * @example\n * ```ts\n * const error = new ExecutionError(\n * 'Failed to process input data',\n * { line: 42, column: 8 }\n * );\n * ```\n *\n * @since 1.0.0\n */\n\n constructor(message: string) {\n super(message);\n\n // Assign the name of the error\n this.name = 'xJetExecutionError';\n }\n\n /**\n * Converts the error instance to a plain JavaScript object for JSON serialization.\n *\n * @returns A plain object containing all properties of the error.\n *\n * @remarks\n * This method enhances error serialization by ensuring all properties from the error\n * instance are properly included in the resulting JSON representation. The standard\n * `JSON.stringify()` method doesn't properly serialize Error objects by default, as\n * their properties are typically not enumerable.\n *\n * @example\n * ```ts\n * const error = new ExecutionError('Something went wrong');\n * error.code = 'ERR_INVALID_INPUT';\n *\n * // Convert to JSON\n * const serialized = JSON.stringify(error);\n * // Result includes all properties: message, name, stack, code, etc.\n * ```\n *\n * @since 1.0.0\n */\n\n toJSON(): Record<string, unknown> {\n const json: Record<string, unknown> = {};\n\n for (const key of Object.keys(this)) {\n const value = this[key as keyof this];\n if(value) json[key] = value;\n }\n\n json.name = this.name;\n json.stack = this.stack;\n json.message = this.message;\n\n return json;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { TestModel } from '@shared/models/test.model';\nimport type { ContextType, FunctionType } from '@remotex-labs/xjet-expect';\nimport type { ContextInterface, DescribeOptionsInterface } from '@shared/models/interfaces/describe-model.interface';\n\n/**\n * Imports\n */\n\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { emitStatus } from '@shared/services/emit.service';\nimport { encodeErrorSchema } from '@packets/packets.module';\nimport { DescribeModel } from '@shared/models/describe.model';\nimport { ExecutionError } from '@shared/errors/execution.error';\nimport { MessageType } from '@messages/constants/report.constant';\n\n/**\n * Manages the state of test suites within the testing framework, tracking the hierarchy of describe blocks and test cases.\n * Implemented as a singleton to ensure a single source of truth for the test suite structure.\n *\n * @template TestModel - The model type representing individual test cases\n * @template FunctionType - The function type for describe block implementations\n * @template DescribeModel - The model type representing test suite describe blocks\n * @template DescribeOptionsInterface - Configuration options for describe blocks\n *\n * @throws Error - If you attempt to instantiate this class directly instead of using getInstance()\n *\n * @remarks\n * The singleton pattern ensures that all test registration operations work with the same\n * state instance, properly maintaining the hierarchical structure of tests.\n * Use the static getInstance() method to access the singleton instance.\n *\n * @example\n * ```ts\n * // Get the singleton instance\n * const suiteState = SuiteState.getInstance();\n *\n * // Add a describe block\n * suiteState.addDescribe('My test suite', () => {\n * // Test suite implementation\n * }, { only: true });\n *\n * // Add a test case to the current describe block\n * suiteState.addTest(new TestModel('should work', () => {}, { skip: false }));\n * ```\n *\n * @see TestModel\n * @see DescribeModel\n *\n * @since 1.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class SuiteState {\n /**\n * Tracks whether any test or describe block has the 'only' flag set\n *\n * @since 1.0.0\n */\n\n private onlyMode = false;\n\n /**\n * Reference to the currently active describe block in the test hierarchy\n *\n * @see DescribeModel\n * @since 1.0.0\n */\n\n private currentDescribe: DescribeModel;\n\n /**\n * Reference to the test currently being defined or executed\n *\n * @see TestModel\n * @since 1.0.0\n */\n\n private currentTest?: TestModel;\n\n /**\n * Suite has at least one test\n * @since 1.0.0\n */\n\n private hasTests = false;\n\n /**\n * The top-level describe block that contains all tests and nested describe blocks\n *\n * @see DescribeModel\n * @since 1.0.0\n */\n\n private readonly rootDescribe: DescribeModel;\n\n /**\n * Array of regular expressions used for filtering test paths\n *\n * @remarks\n * This array stores regular expressions created from filter strings specified in runtime configuration.\n * Used to determine which tests should be executed when filtering is enabled.\n *\n * @see SuiteState.matchesFilter - Method that uses these regex patterns for test filtering\n * @since 1.0.0\n */\n\n private readonly filterRegexChain: Array<RegExp> = [];\n\n /**\n * Creates a new instance of the class with a root describe block\n *\n * @internal\n * @since 1.0.0\n */\n\n constructor() {\n this.rootDescribe = new DescribeModel();\n this.currentDescribe = this.rootDescribe;\n\n if (Array.isArray(__XJET?.runtime.filter) && __XJET.runtime.filter.length > 0) {\n this.onlyMode = true;\n this.filterRegexChain = __XJET.runtime.filter.map(\n (part: string) => new RegExp(`^${ part }$`)\n );\n }\n }\n\n /**\n * Checks if a test path matches the provided regular expression filter patterns\n *\n * This method compares a test's full path (including ancestry and description) against one or more\n * regular expression patterns to determine if the test should be included in execution.\n *\n * @param path - Array of path segments representing test ancestry and description\n * @param filter - Array of RegExp objects to test against the path\n * @returns Boolean indicating whether the path matches the filter patterns\n *\n * @throws Error - When invalid regular expressions are provided\n *\n * @remarks\n * The method aligns the filter from the end of the path, allowing partial matching of nested test structures.\n * This is particularly useful for selecting specific test cases within a larger test hierarchy.\n *\n * @example\n * ```ts\n * // Match tests with description containing \"login\"\n * const matches = SuiteState.matchesFilter(\n * ['Auth', 'User', 'should handle login correctly'],\n * [/login/i]\n * );\n * // Returns: true\n *\n * // Match specific test path structure\n * const matches = SuiteState.matchesFilter(\n * ['API', 'GET', 'should return 200 status'],\n * [/API/, /GET/, /status/]\n * );\n * // Returns: true\n * ```\n *\n * @see filterChain - String-based alternative for exact matching\n * @see addTest - Method that uses matchesFilter to determine which tests to run\n *\n * @since 1.0.0\n */\n\n static matchesFilter(path: string[], filter: RegExp[]): boolean {\n if (filter.length > path.length) return false;\n\n // Align from the end of the path\n const offset = path.length - filter.length;\n\n return filter.every((re, i) => re.test(path[offset + i]));\n }\n\n /**\n * Indicates whether the test suite is running in \"only\" mode\n *\n * @returns True if only specifically marked tests should run\n *\n * @since 1.0.0\n */\n\n get isOnlyMode(): boolean {\n return this.onlyMode;\n }\n\n /**\n * Gets the root describe block of the test suite\n *\n * @returns The top-level describe block\n *\n * @see DescribeModel\n * @since 1.0.0\n */\n\n get root(): DescribeModel {\n return this.rootDescribe;\n }\n\n /**\n * Gets the current describe block being defined\n *\n * @returns The active describe block\n *\n * @see DescribeModel\n * @since 1.0.0\n */\n\n get describe(): DescribeModel {\n return this.currentDescribe;\n }\n\n /**\n * Gets the test currently being defined or executed\n *\n * @returns The current test or null if no test is active\n *\n * @see TestModel\n * @since 1.0.0\n */\n\n get test(): TestModel | undefined {\n return this.currentTest;\n }\n\n /**\n * Sets the current test being defined or executed\n *\n * @param test - The test to set as current\n *\n * @see TestModel\n * @since 1.0.0\n */\n\n set test(test: TestModel | undefined) {\n this.currentTest = test;\n }\n\n /**\n * Executes the entire test suite from the root describe block\n *\n * @param context - The execution context containing runtime information\n *\n * @throws Error - When test execution fails, the error is encoded and dispatched\n *\n * @remarks\n * This method initiates the test execution flow by calling run() on the root describe block\n * and emits an END status notification when all tests complete successfully. If an error\n * occurs during execution, it's captured, encoded, and dispatched through the error schema.\n *\n * @example\n * ```ts\n * const suiteState = SuiteState.getInstance();\n * await suiteState.run({\n * timeout: 5000,\n * currentPath: '/tests',\n * skipAfterFailure: true\n * });\n * ```\n *\n * @see emitStatus\n * @see DescribeModel\n *\n * @since 1.0.0\n */\n\n async run(context: ContextType<ContextInterface>): Promise<void> {\n try {\n const time = Date.now();\n emitStatus(MessageType.StartSuite);\n if (!this.hasTests)\n throw new ExecutionError('Your test suite must contain at least one test');\n\n await this.root.run(context);\n emitStatus(MessageType.EndSuite, { duration: Date.now() - time });\n } catch (e) {\n dispatch(\n encodeErrorSchema(<Error>e, __XJET.runtime.suiteId, __XJET.runtime.runnerId)\n );\n }\n }\n\n /**\n * Adds a new describe block to the test suite hierarchy\n *\n * @param description - The textual description of the describe block\n * @param describeFn - The function containing the tests and nested describes\n * @param flags - Configuration options for the describe block\n * @param describeArgs - Arguments to pass to the describe function\n *\n * @throws Error - If the describe function throws any exceptions\n *\n * @remarks\n * This method temporarily changes the current describe context while executing\n * the describeFn, then restores it afterward, ensuring proper nesting of test blocks.\n * If the 'only' flag is set, it enables only-mode for the entire test suite.\n *\n * @example\n * ```ts\n * suiteState.addDescribe(\n * 'my test group',\n * () => {\n * // test definitions here\n * },\n * { only: true }\n * );\n * ```\n *\n * @see FunctionType\n * @see DescribeModel\n * @see DescribeOptionsInterface\n *\n * @since 1.0.0\n */\n\n addDescribe(description: string, describeFn: FunctionType, flags: DescribeOptionsInterface = {}, describeArgs: Array<unknown> = []): void {\n const options = { skip: false, only: false, ...flags };\n if (options.only) {\n this.onlyMode = true;\n }\n\n if (this.filterRegexChain.length > 0) {\n const fullPath = [\n ...this.currentDescribe.ancestry,\n this.currentDescribe.description,\n description\n ];\n\n if (SuiteState.matchesFilter(fullPath, this.filterRegexChain)) {\n options.only = true;\n }\n }\n\n const newDescribe = new DescribeModel(description, options);\n this.currentDescribe.addDescribe(newDescribe);\n const previousDescribe = this.currentDescribe;\n this.currentDescribe = newDescribe;\n\n try {\n describeFn.apply({}, describeArgs);\n } finally {\n this.currentDescribe = previousDescribe;\n }\n }\n\n /**\n * Adds a test to the current describe block\n *\n * @param test - The test model to add\n *\n * @remarks\n * If the test has the 'only' option set, it enables only-mode for the entire test suite.\n *\n * @see TestModel\n * @since 1.0.0\n */\n\n addTest(test: TestModel): void {\n // Mark the suite as having at least one test\n this.hasTests = true;\n\n if (test.options.only) this.onlyMode = true;\n this.currentDescribe.addTest(test);\n\n if (this.filterRegexChain.length > 0) {\n const fullPath = [ ...test.ancestry, test.description ];\n\n if (SuiteState.matchesFilter(fullPath, this.filterRegexChain)) {\n test.options.only = true;\n }\n }\n }\n}\n", "/**\n * Export interfaces\n */\n\nexport type * from '@components/interfaces/parse-component.interface';\n\n/**\n * Import will remove at compile time\n */\n\nimport type { ParsedStackTraceInterface, StackFrameInterface } from '@components/interfaces/parse-component.interface';\n\n/**\n * Regular expression patterns for different JavaScript engines' stack traces\n *\n * @since 2.1.0\n */\n\nconst PATTERNS = {\n V8: {\n GLOBAL: /at\\s(.*):(\\d+):(\\d+)/,\n STANDARD: /at\\s(.*?)\\((?:(.+?):(\\d+):(\\d+)|(native))\\)/,\n EVAL: /^at\\s(.+?)\\s\\(eval\\sat\\s(.+?)\\s?\\((.*):(\\d+):(\\d+)\\),\\s(.+?):(\\d+):(\\d+)\\)$/\n },\n SPIDERMONKEY: {\n EVAL: /^(.*)@(.+?):(\\d+):(\\d+),\\s(.+?)@(.+?):(\\d+):(\\d+)$/,\n STANDARD: /^(.*)@(.*?)(?:(\\[native code\\])|:(\\d+):(\\d+))$/\n },\n JAVASCRIPT_CORE: {\n STANDARD: /^(?:(global|eval)\\s)?(.*)@(.*?)(?::(\\d+)(?::(\\d+))?)?$/\n }\n};\n\n/**\n * Enumeration of JavaScript engines that can be detected from stack traces\n *\n * @since 2.1.0\n */\n\nexport const enum JSEngines {\n V8,\n SPIDERMONKEY,\n JAVASCRIPT_CORE,\n UNKNOWN\n}\n\n/**\n * Detects the JavaScript engine based on the format of a stack trace line\n *\n * @param stack - The stack trace to analyze\n * @returns The identified JavaScript engine type\n *\n * @example\n * ```ts\n * const engine = detectJSEngine(\"at functionName (/path/to/file.js:10:15)\");\n * if (engine === JSEngines.V8) {\n * // Handle V8 specific logic\n * }\n * ```\n *\n * @since 2.1.0\n */\n\nexport function detectJSEngine(stack: string): JSEngines {\n if (stack.startsWith(' at ') || stack.startsWith('at '))\n return JSEngines.V8;\n\n if (stack.includes('@'))\n return /(?:global|eval) code@/.test(stack)\n ? JSEngines.JAVASCRIPT_CORE : JSEngines.SPIDERMONKEY;\n\n return JSEngines.UNKNOWN;\n}\n\n/**\n * Normalizes file paths from various formats to a standard format\n *\n * @param filePath - The file path to normalize, which may include protocol prefixes\n * @returns A normalized file path with consistent separators and without protocol prefixes\n *\n * @remarks\n * Handles both Windows and Unix-style paths, as well as file:// protocol URLs.\n * Converts all backslashes to forward slashes for consistency.\n *\n * @example\n * ```ts\n * // Windows file URL to a normal path\n * normalizePath(\"file:///C:/path/to/file.js\"); // \"C:/path/to/file.js\"\n *\n * // Unix file URL to a normal path\n * normalizePath(\"file:///path/to/file.js\"); // \"/path/to/file.js\"\n *\n * // Windows backslashes to forward slashes\n * normalizePath(\"C:\\\\path\\\\to\\\\file.js\"); // \"C:/path/to/file.js\"\n * ```\n *\n * @since 2.1.0\n */\n\nexport function normalizePath(filePath: string): string {\n // Handle file:// protocol URLs\n if (filePath.startsWith('file://')) {\n // Handle Windows file:/// format\n if (filePath.startsWith('file:///') && /^file:\\/\\/\\/[A-Za-z]:/.test(filePath)) {\n // Windows absolute path: file:///C:/path/to/file.js\n return filePath.substring(8);\n }\n\n // Handle *nix file:// format\n return filePath.substring(7);\n }\n\n // Handle Windows-style paths with backward slashes\n filePath = filePath.replace(/\\\\/g, '/');\n\n return filePath;\n}\n\n/**\n * Creates a default stack frame object with initial values\n *\n * @param source - The original source line from the stack trace\n * @returns A new StackFrameInterface object with default null values\n *\n * @see ParsedStackTraceInterface\n * @see StackFrameInterface\n *\n * @since 2.1.0\n */\n\nexport function createDefaultFrame(source: string): StackFrameInterface {\n return {\n source,\n eval: false,\n async: false,\n native: false,\n constructor: false\n };\n}\n\n/**\n * Safely parses a string value to an integer, handling undefined and null cases\n *\n * @param value - The string value to parse\n * @returns The parsed integer or null if the input is undefined/null\n *\n * @example\n * ```ts\n * safeParseInt(\"42\"); // 42\n * safeParseInt(undefined); // null\n * safeParseInt(null); // null\n * ```\n *\n * @since 2.1.0\n */\n\nexport function safeParseInt(value: string | undefined | null): number | undefined {\n return value && value.trim() !== '' ? parseInt(value, 10) : undefined;\n}\n\n/**\n * Parses a V8 JavaScript engine stack trace line into a structured StackFrameInterface object\n *\n * @param line - The stack trace line to parse\n * @returns A StackFrameInterface object containing the parsed information\n *\n * @remarks\n * Handles both standard V8 stack frames and eval-generated stack frames which\n * have a more complex structure with nested origin information.\n *\n * @example\n * ```ts\n * // Standard frame\n * parseV8StackLine(\"at functionName (/path/to/file.js:10:15)\");\n *\n * // Eval frame\n * parseV8StackLine(\"at eval (eval at evalFn (/source.js:5:10), <anonymous>:1:5)\");\n * ```\n *\n * @throws Error - If the line format doesn't match any known V8 pattern\n *\n * @see StackFrameInterface\n * @see createDefaultFrame\n *\n * @since 2.1.0\n */\n\nexport function parseV8StackLine(line: string): StackFrameInterface {\n const frame = createDefaultFrame(line);\n\n // Common flags that apply to all formats\n if (line.toLowerCase().includes('new')) frame.constructor = true;\n if (line.toLowerCase().includes('async')) frame.async = true;\n\n // Try to match against each pattern\n const evalMatch = line.match(PATTERNS.V8.EVAL);\n const globalMatch = line.match(PATTERNS.V8.GLOBAL);\n const standardMatch = !evalMatch && line.match(PATTERNS.V8.STANDARD);\n\n if (evalMatch) {\n // Handle eval format\n frame.eval = true;\n frame.functionName = evalMatch[1] || undefined;\n\n // Add eval origin information\n frame.evalOrigin = {\n line: safeParseInt(evalMatch[4]) ?? undefined,\n column: safeParseInt(evalMatch[5]) ?? undefined,\n fileName: evalMatch[3] ? normalizePath(evalMatch[3]) : undefined,\n functionName: evalMatch[2] || '<anonymous>'\n };\n\n // Position inside evaluated code\n frame.line = safeParseInt(evalMatch[7]) ?? undefined;\n frame.column = safeParseInt(evalMatch[8]) ?? undefined;\n frame.fileName = evalMatch[6] ? normalizePath(evalMatch[6]) : undefined;\n } else if (standardMatch) {\n // Handle standard format\n frame.functionName = standardMatch[1] ? standardMatch[1].trim() : undefined;\n\n if (standardMatch[5] === 'native') {\n frame.native = true;\n frame.fileName = '[native code]';\n } else {\n frame.line = safeParseInt(standardMatch[3]) ?? undefined;\n frame.column = safeParseInt(standardMatch[4]) ?? undefined;\n frame.fileName = standardMatch[2] ? normalizePath(standardMatch[2]) : undefined;\n if(frame.fileName?.includes('node:')) frame.native = true;\n }\n } else if (globalMatch) {\n frame.fileName = globalMatch[1] ? normalizePath(globalMatch[1]) : undefined;\n frame.line = safeParseInt(globalMatch[2]) ?? undefined;\n frame.column = safeParseInt(globalMatch[3]) ?? undefined;\n }\n\n return frame;\n}\n\n/**\n * Parses a SpiderMonkey JavaScript engine stack trace line into a structured StackFrameInterface object\n *\n * @param line - The stack trace line to parse\n * @returns A StackFrameInterface object containing the parsed information\n *\n * @remarks\n * Handles both standard SpiderMonkey stack frames and eval/Function-generated stack frames\n * which contain additional evaluation context information.\n *\n * @example\n * ```ts\n * // Standard frame\n * parseSpiderMonkeyStackLine(\"functionName@/path/to/file.js:10:15\");\n *\n * // Eval frame\n * parseSpiderMonkeyStackLine(\"evalFn@/source.js line 5 > eval:1:5\");\n * ```\n *\n * @see StackFrameInterface\n * @see createDefaultFrame\n *\n * @since 2.1.0\n */\n\nexport function parseSpiderMonkeyStackLine(line: string): StackFrameInterface {\n const frame = createDefaultFrame(line);\n\n // Check for eval/Function format\n const evalMatch = line.match(PATTERNS.SPIDERMONKEY.EVAL);\n if (evalMatch) {\n frame.eval = true;\n frame.functionName = evalMatch[1] ? evalMatch[1] : undefined;\n\n if (line.toLowerCase().includes('constructor'))\n frame.constructor = true;\n\n if (line.toLowerCase().includes('async'))\n frame.async = true;\n\n // Add eval origin information\n frame.evalOrigin = {\n line: safeParseInt(evalMatch[7]) ?? undefined,\n column: safeParseInt(evalMatch[8]) ?? undefined,\n fileName: normalizePath(evalMatch[6]),\n functionName: evalMatch[5] ? evalMatch[5] : undefined\n };\n\n // Position inside evaluated code\n frame.line = safeParseInt(evalMatch[3]) ?? undefined;\n frame.column = safeParseInt(evalMatch[4]) ?? undefined;\n\n return frame;\n }\n\n // Standard SpiderMonkey format\n const match = line.match(PATTERNS.SPIDERMONKEY.STANDARD);\n if (match) {\n frame.functionName = match[1] ? match[1] : undefined;\n frame.fileName = normalizePath(match[2]);\n\n if (match[3] === '[native code]') {\n frame.fileName = '[native code]';\n } else {\n frame.line = safeParseInt(match[4]) ?? undefined;\n frame.column = safeParseInt(match[5]) ?? undefined;\n }\n }\n\n return frame;\n}\n\n/**\n * Parses a JavaScriptCore engine stack trace line into a structured StackFrameInterface object\n *\n * @param line - The stack trace line to parse\n * @returns A StackFrameInterface object containing the parsed information\n *\n * @remarks\n * Handles both standard JavaScriptCore stack frames and eval-generated stack frames.\n * Special handling is provided for \"global code\" references and native code.\n *\n * @example\n * ```ts\n * // Standard frame\n * parseJavaScriptCoreStackLine(\"functionName@/path/to/file.js:10:15\");\n *\n * // Eval frame\n * parseJavaScriptCoreStackLine(\"eval code@\");\n * ```\n *\n * @see StackFrameInterface\n * @see createDefaultFrame\n *\n * @since 2.1.0\n */\n\nexport function parseJavaScriptCoreStackLine(line: string): StackFrameInterface {\n const frame = createDefaultFrame(line);\n\n // Standard JavaScriptCore format\n const match = line.match(PATTERNS.JAVASCRIPT_CORE.STANDARD);\n if (match) {\n frame.functionName = match[2];\n frame.eval = (match[1] === 'eval' || match[3] === 'eval');\n\n if (line.toLowerCase().includes('constructor'))\n frame.constructor = true;\n\n if (line.toLowerCase().includes('async'))\n frame.async = true;\n\n if (match[3] === '[native code]') {\n frame.native = true;\n frame.fileName = '[native code]';\n } else {\n frame.line = safeParseInt(match[4]) ?? undefined;\n frame.column = safeParseInt(match[5]) ?? undefined;\n frame.fileName = normalizePath(match[3]);\n }\n }\n\n return frame;\n}\n\n/**\n * Parses a stack trace line based on the detected JavaScript engine\n *\n * @param line - The stack trace line to parse\n * @param engine - The JavaScript engine type that generated the stack trace\n * @returns A StackFrameInterface object containing the parsed information\n *\n * @remarks\n * Delegates to the appropriate parsing function based on the JavaScript engine.\n * Defaults to V8 parsing if the engine is unknown.\n *\n * @example\n * ```ts\n * const engine = detectJSEngine(stackLine);\n * const frame = parseStackLine(stackLine, engine);\n * ```\n *\n * @see JSEngines\n * @see parseV8StackLine\n * @see parseSpiderMonkeyStackLine\n * @see parseJavaScriptCoreStackLine\n *\n * @since 2.1.0\n */\n\nexport function parseStackLine(line: string, engine: JSEngines): StackFrameInterface {\n switch (engine) {\n case JSEngines.SPIDERMONKEY:\n return parseSpiderMonkeyStackLine(line);\n case JSEngines.JAVASCRIPT_CORE:\n return parseJavaScriptCoreStackLine(line);\n case JSEngines.V8:\n default:\n return parseV8StackLine(line);\n }\n}\n\n/**\n * Extracts the stack frames from a full stack trace string, removing the error message line.\n *\n * @param stack - The full error stack string, possibly including the error message\n * @returns The stack trace starting from the first stack frame, or an empty string if no frames are found\n *\n * @remarks\n * This function scans the stack string for lines matching common stack frame formats,\n * including V8 (`at ...`) and SpiderMonkey/JavaScriptCore (`function@file:line:column`) patterns.\n * It returns only the portion of the stack that contains the frames, discarding the initial\n * error message or any non-stack lines.\n *\n * @example\n * ```ts\n * const stack = `\n * Error: Something went wrong\n * at doSomething (file.js:10:15)\n * at main (file.js:20:5)\n * `;\n *\n * console.log(getStackWithoutMessage(stack));\n * // Output:\n * // at doSomething (file.js:10:15)\n * // at main (file.js:20:5)\n * ```\n *\n * @since 4.0.1\n */\n\nexport function getStackWithoutMessage(stack: string): string {\n if (!stack) return '';\n\n const stackFramePattern = /^\\s*at .+$|^.+@.+:\\d+:\\d+$|^@.+:\\d+:\\d+$|^.+@\\[native code\\]$/;\n const lines = stack.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n if (stackFramePattern.test(lines[i])) {\n return lines.slice(i).join('\\n');\n }\n }\n\n return '';\n}\n\n/**\n * Parses a complete error stack trace into a structured format\n *\n * @param error - Error object or error message string to parse\n * @returns A ParsedStackTraceInterface object containing structured stack trace information\n *\n * @remarks\n * Automatically detects the JavaScript engine from the stack format.\n * Filters out redundant information like the error name/message line.\n * Handles both Error objects and string error messages.\n *\n * @example\n * ```ts\n * try {\n * throw new Error (\"Something went wrong\");\n * } catch (error) {\n * const parsedStack = parseErrorStack(error);\n * console.log(parsedStack.name); // \"Error\"\n * console.log(parsedStack.message); // \"Something went wrong\"\n * console.log(parsedStack.stack); // Array of StackFrameInterface objects\n * }\n * ```\n *\n * @see ParsedStackTraceInterface\n * @see StackFrameInterface\n * @see parseStackLine\n * @see detectJSEngine\n *\n * @since 2.1.0\n */\n\nexport function parseErrorStack(error: Error | string): ParsedStackTraceInterface {\n const errorObj = typeof error === 'string' ? { stack: error, message: error, name: '' } : error;\n const name = errorObj.name || 'Error';\n const stack = getStackWithoutMessage(errorObj.stack || '');\n const message = errorObj?.message || '';\n\n const engine = detectJSEngine(stack);\n const stackLines = stack.split('\\n')\n .map(line => line.trim())\n .filter(line => line.trim() !== '');\n\n return {\n name,\n message,\n stack: stackLines.map(line => parseStackLine(line, engine)),\n rawStack: stack\n };\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PacketInvocationInterface } from '@packets/interfaces/packet-schema.interface';\n\n/**\n * Imports\n */\n\nimport { parseErrorStack } from '@remotex-labs/xmap/parser.component';\n\n/**\n * Retrieves the location in the source code where this function was invoked.\n *\n * @param position - The stack frame index to inspect (default is 3). This allows skipping\n * internal frames to reach the actual caller.\n * @returns A {@link PacketInvocationInterface} containing `line`, `column`, and `source` file\n * of the invocation, or `undefined` if the location could not be determined.\n *\n * @remarks\n * This function generates a new `Error` to capture the stack trace, parses it using\n * {@link parseErrorStack}, and returns the requested frame as a structured object.\n * It is useful for logging or reporting the exact location of a call within test suites\n * or framework code.\n *\n * @see parseErrorStack\n * @see PacketInvocationInterface\n *\n * @since 1.0.0\n */\n\nexport function getInvocationLocation(position: number = 2): PacketInvocationInterface | undefined {\n const errorObject = parseErrorStack(new Error());\n const stack = errorObject.stack[position];\n\n if (stack?.line && stack?.column && stack?.fileName) {\n return {\n line: stack.line!,\n column: stack.column!,\n source: stack.fileName!\n };\n }\n\n return undefined;\n}\n\n/**\n * Returns a native-style stack trace string,\n * trimmed to start at the specified frame index.\n *\n * @remarks\n * The first line (error name/message) is preserved,\n * while the following lines are sliced starting from `position`.\n *\n * @param position - Index of the first stack frame to include.\n * Defaults to `2` to skip this helper and its caller.\n *\n * @returns A string identical in format to `Error.stack`,\n * or an empty string if the stack is unavailable.\n *\n * @example\n * ```ts\n * console.log(getTrimmedStackString(2));\n * ```\n *\n * @since 3.1.0\n */\n\nexport function getTrimmedStackString(position: number = 2): string {\n const err = new Error();\n if (!err.stack) return '';\n\n const lines = err.stack.split('\\n');\n const frames = lines.slice(position + 1);\n\n return frames.join('\\n');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { TestModel } from '@shared/models/test.model';\nimport type { DescribeModel } from '@shared/models/describe.model';\n\n/**\n * Imports\n */\n\nimport { serialize } from '@remotex-labs/xjet-expect';\nimport { encodePacket } from '@packets/packets.module';\nimport { SuiteState } from '@shared/states/suite.state';\nimport { inject } from '@symlinks/services/inject.service';\nimport { LogLevel } from '@messages/constants/report.constant';\nimport { getInvocationLocation } from '@components/location.component';\nimport { PacketKind } from '@packets/constants/packet-schema.constants';\n\n/**\n * Creates a logging function that formats and dispatches log messages with timestamps\n *\n * @template T - Console method type that determines the log level\n * @param type - The type of console method (log, info, warn, error) to create a handler for\n * @returns A function that accepts any number of arguments, formats them, and dispatches a log event\n *\n * @throws TypeError - When invalid arguments are provided to the returned function\n *\n * @remarks\n * This function acts as a factory for creating specialized logging handlers. Each handler:\n * - Timestamps the log entry with ISO format\n * - Formats all arguments into string representations\n * - Dispatches the log event with the appropriate log level\n * - Maintains a consistent format for all log messages\n *\n * @example\n * ```ts\n * const logInfo = createLogHandler('info');\n * logInfo('User', user.id, 'logged in successfully');\n * // Dispatches a log event with level: 'INFO', formatted arguments, and timestamp\n * ```\n *\n * @see formatValue\n * @see dispatch\n * @see SchemaType\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport function createLogHandler(type: keyof typeof LogLevel) {\n return function (...args: unknown[]): void {\n let parent: TestModel | DescribeModel | undefined = inject(SuiteState).test;\n if (!parent) {\n parent = inject(SuiteState).describe;\n }\n\n const context = [ ...parent?.ancestry ?? [], parent?.description ].join(',');\n\n // Format arguments for the description\n const formattedArgs = args.map((data: unknown) => serialize(data).join('\\n')).join(' ');\n const location = getInvocationLocation();\n\n // Dispatch log event\n dispatch(encodePacket(PacketKind.Log, {\n level: LogLevel[type],\n message: formattedArgs,\n ancestry: context ?? '',\n invocation: location\n }));\n };\n}\n\n/**\n * Standard log level function for general purpose logging\n *\n * @see createLogHandler\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport const log = createLogHandler('Info');\n\n/**\n * Informational log function for highlighting noteworthy application events\n *\n * @see createLogHandler\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport const info = createLogHandler('Info');\n\n/**\n * Warning log function for potential issues that aren't errors\n *\n * @see createLogHandler\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport const warn = createLogHandler('Warn');\n\n/**\n * Error log function for reporting application errors and exceptions\n *\n * @see createLogHandler\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport const error = createLogHandler('Error');\n\n/**\n * Debug log function for detailed diagnostic information\n *\n * @see createLogHandler\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport const debug = createLogHandler('Debug');\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConstructorLikeType, FunctionLikeType, FunctionType } from '@remotex-labs/xjet-expect';\nimport type { ConstructorKeysType, KeysExtendingConstructorType } from '@shared/mock/interfaces/spy-mock.interface';\n\n/**\n * Imports\n */\n\nimport { MockState } from '@shared/states/mock.state';\nimport { ExecutionError } from '@shared/errors/execution.error';\n\n/**\n * Intercepts and mocks the property descriptor of a specified property on a target object.\n *\n * @template Target - The target object type.\n * @template Key - The key of the property to be mocked.\n *\n * @param target - The object whose property descriptor is being intercepted and mocked.\n * @param key - The property key on the target object to spy on.\n * @return A `MockState` instance that provides control over the mocked property and its interactions.\n *\n * @remarks\n * This function replaces the property's getter and setter to allow interception and testing of their behavior.\n * A `MockState` instance is returned to control and observes mocked behavior.\n *\n * @since 1.0.0\n */\n\nexport function spyOnDescriptorProperty<Target, Key extends keyof Target>(target: Target, key: Key): MockState<Target[Key], []> {\n const original = target[key];\n const originalDescriptor = Object.getOwnPropertyDescriptor(target, key) || {};\n const mockInstance = new MockState(() => original, () => {\n target[key] = originalDescriptor.value;\n Object.defineProperty(target, key, originalDescriptor);\n }, 'xJet.spyOn()');\n\n MockState.mocks.push(mockInstance);\n Object.defineProperty(target, key, {\n get() {\n return mockInstance.apply(this, []);\n },\n set(value: unknown) {\n mockInstance.mockImplementation(() => <Target[Key]> value);\n\n return mockInstance.apply(this, [ value ]);\n }\n });\n\n return mockInstance;\n}\n\n/**\n * Creates a spy on a specified static method or static property of a target class (not a class instance).\n * Useful for mocking behavior during testing.\n *\n * @template Target - The type of the target class.\n * @template Key - The static method or static property key on the target object to spy on.\n *\n * @param target - The object on which to spy.\n * @param key - The key of the method or property of the target to spy on.\n * @returns If the spied-on property is a function, returns a `MockState` object for the function,\n * allowing tracking of calls and modifying the return value or behavior.\n * Otherwise, returns a `MockState` object for the property, enabling tracking and manipulation of its value.\n *\n * @throws Error Throws an error if the `target` is a primitive value.\n * @throws Error Throws an error if `key` is null or undefined.\n * @throws Error Throws an error if the specified property does not exist on the target object.\n *\n * @remarks\n * This function is commonly used in testing environments to replace or monitor functionality without\n * altering the actual logic in the source code. It provides fine-grained control over target behavior.\n *\n * @example\n * ```ts\n * class ClassTest {\n * static name: string = 'ClassTest';\n *\n * static x(param: string) {\n * console.log(`original static x ${ param }`);\n * }\n * }\n *\n * const spy1 = xJet.spyOn(ClassTest, 'name');\n * const spy2 = xJet.spyOn(ClassTest, 'x');\n *\n * spy1.mockReturnValueOnce('Mock name');\n * spy2.mockImplementationOnce((param: string) => {\n * console.log(`Mock x ${ param }`);\n * });\n *\n * console.log(ClassTest.name); // Mock name\n * console.log(ClassTest.name); // ClassTest\n *\n * ClassTest.x('test1'); // Mock x test1\n * ClassTest.x('test2'); // original static x test2\n * ```\n *\n * @see FunctionType\n * @see KeysExtendingConstructorType\n *\n * @since 1.0.0\n */\n\nexport function spyOnImplementation<Target, Key extends KeysExtendingConstructorType<Target>>(target: Target, key: Key): Target[Key] extends FunctionType\n ? MockState<ReturnType<Target[Key]>, Parameters<Target[Key]>, Target>\n : MockState<Target[Key], [], Target>;\n\n/**\n * Creates a mock spy on the specified method or constructor of the target object.\n *\n * @template Target The type of the target object.\n * @template Key The type of the method or constructor key on the target object.\n *\n * @param target - The object whose method or constructor needs to be spied on.\n * @param key - The property key of the method or constructor to spy on.\n * @return A mock state representing the spied method or constructor if the key corresponds to a constructor type;\n * otherwise, throws a type error.\n *\n * @throws Error Throws an error if the `target` is a primitive value.\n * @throws Error Throws an error if `key` is null or undefined.\n * @throws Error Throws an error if the specified property does not exist on the target object.\n *\n * @remarks\n * This method is typically used for testing purposes to observe or manipulate calls to the method or constructor of an object.\n * The returned mock state may allow additional configuration, such as altering its behavior or tracking calls.\n *\n * @example\n * ```ts\n * const coolObject = {\n * ClassTest: class {\n * constructor(param: number) {\n * console.log('original Constructor');\n * }\n *\n * justAnFunction() {\n * console.log('original justAnFunction');\n * }\n * }\n * };\n *\n * const spy = xJet.spyOn(coolObject, 'ClassTest');\n * spy.mockImplementationOnce((param: number) => {\n * console.log(`mock Constructor with param: ${ param }`);\n *\n * return <any> {\n * justAnFunction() {\n * console.log('mock justAnFunction');\n * }\n * };\n * });\n *\n * const instance = new coolObject.ClassTest(1); // mock Constructor with param: 1\n * instance.justAnFunction(); // mock justAnFunction\n *\n * const instance2 = new coolObject.ClassTest(2); // original Constructor\n * instance2.justAnFunction(); // original justAnFunction\n * ```\n *\n * @see ConstructorType\n * @see ConstructorKeysType\n *\n * @since 1.0.0\n */\n\nexport function spyOnImplementation<Target, Key extends ConstructorKeysType<Target>>(target: Target, key: Key): Target[Key] extends ConstructorLikeType\n ? MockState<InstanceType<Target[Key]>, ConstructorParameters<Target[Key]>, Target>\n : never;\n\n/**\n * Creates a spy on a specific method or property of the given target object.\n *\n * @template Target - The type of the target object to spy on.\n * @template Key - The key of the property or method to spy on within the target object.\n *\n * @param target - The target object containing the property or method to be spied upon.\n * @param key - The name of the property or method on the target object to spy on.\n * @returns If the spied target is a function, it returns a `MockState` object to observe calls and arguments of the function.\n * Otherwise, it returns a `MockState` object to observe the value or state of the property.\n *\n * @throws Error Throws an error if the `target` is a primitive value.\n * @throws Error Throws an error if `key` is null or undefined.\n * @throws Error Throws an error if the specified property does not exist on the target object.\n *\n * @remarks This method is commonly used in test environments to monitor and assert interactions with a specific property\n * or method on an object. The returned `MockState` can be used to retrieve call history or observe mutations.\n *\n * @example\n * ```ts\n * const coolObject = {\n * myMethod() {\n * return 'Original myMethod';\n * },\n * coolString: 'Original coolString'\n * };\n *\n * const spy = xJet.spyOn(coolObject, 'coolString');\n * const spy2 = xJet.spyOn(coolObject, 'myMethod');\n *\n * spy.mockImplementationOnce(() => 'mock coolString');\n * spy2.mockImplementationOnce(() => 'mock myMethod string');\n *\n * console.log(coolObject.coolString); // mock coolString\n * console.log(coolObject.coolString); // Original coolString\n * console.log(coolObject.myMethod()); // mock myMethod string\n * console.log(coolObject.myMethod()); // Original myMethod\n * ```\n *\n * @see FunctionType\n *\n * @since 1.0.0\n */\n\nexport function spyOnImplementation<Target, Key extends keyof Target>(target: Target, key: Key): Target[Key] extends FunctionType\n ? MockState<ReturnType<Target[Key]>, Parameters<Target[Key]>, ThisParameterType<Target[Key]>>\n : MockState<Target[Key] | void, [ Target[Key] ], ThisParameterType<Target[Key]>>\n\n/**\n * Creates a spy on the specified method or property of the given target object.\n *\n * Replaces the specified method or property with a mock implementation that can be tracked during testing.\n *\n * @template T - The type of the target object.\n * @template K - The keyof the target used to specify the method or property being spied upon.\n *\n * @param target - The object that contains the method or property to spy on. Must be a non-primitive object or function.\n * @param key - The name of the property or method to spy on.\n *\n * @return MockState A `MockState` instance representing the state of the spied-on property or method, allowing tracking and mocking.\n *\n * @throws Error If the target is null, undefined, or a primitive value such as a string or number.\n * @throws Error If the `key` parameter is null or undefined.\n * @throws Error If the specified property does not exist in the target object.\n *\n * @remarks\n * This function is part of a testing framework and is used to track interactions with an object's method or property.\n * It can modify non-function properties or replace function properties with a mock function for testing purposes.\n * The original method or property can be restored after the spy lifecycle is completed.\n *\n * This method will throw errors for invalid inputs, or if the target object does not have the specified property.\n *\n * @since 1.0.0\n */\n\nexport function spyOnImplementation<T extends object, K extends keyof T>(target: T, key: K): MockState {\n if (target == null || (typeof target !== 'object' && typeof target !== 'function'))\n throw new ExecutionError('Target must be an object or function');\n\n if (key === null)\n throw new ExecutionError('Spied property/method key is required');\n\n if (!(key in target))\n throw new ExecutionError(`Property/method '${ String(key) }' does not exist on target`);\n\n const method = <MockState | T[K]> Reflect.get(target, key);\n const targetObject = target as T & { default: T };\n\n if (!method)\n throw new Error(`Property '${ String(key) }' does not exist in the provided object`);\n\n if((<MockState> method).xJetMock) {\n return <MockState> method;\n }\n\n let descriptor = Object.getOwnPropertyDescriptor(target, key);\n if (descriptor?.get && !descriptor.configurable) {\n if ('default' in targetObject && targetObject.default[key] === method) {\n target = targetObject.default;\n descriptor = Object.getOwnPropertyDescriptor(target, key);\n } else {\n throw new Error(`Property '${ String(key) }' is not configurable in an getter object`);\n }\n }\n\n if (typeof method !== 'function' || descriptor?.get) {\n return spyOnDescriptorProperty(target, key);\n }\n\n let fn: FunctionLikeType = method as FunctionLikeType;\n const protoDesc = Object.getOwnPropertyDescriptor(fn, 'prototype');\n if (fn.prototype && protoDesc && !protoDesc.writable) {\n fn = (...args: unknown[]): unknown => new (method as ConstructorLikeType<unknown, unknown[]>)(...args);\n }\n\n const mockState = new MockState(fn, () => {\n Reflect.set(target, key, method);\n }, 'xJet.spyOn()');\n\n MockState.mocks.push(mockState);\n Reflect.set(target, key, mockState);\n\n return mockState;\n}\n", "/**\n * A regular expression pattern used to match variable-like strings prefixed with a `$` symbol.\n *\n * @default /\\$([#\\\\w.])+/g\n *\n * @see resolveVariable\n * @see interpolateVariables\n *\n * @since 1.0.0\n */\n\nconst VARIABLE_PATTERN = /\\$([#\\w.])+/g;\n\n/**\n * Formats a given value into a human-readable string representation.\n *\n * @param value - The value to be formatted\n * @returns The formatted string representation of the input value\n *\n * @remarks\n * This method ensures that non-string values are converted into a JSON string with\n * indentation for easier readability. If the input is a string, it is returned as-is.\n *\n * @example\n * ```ts\n * // String input is returned unchanged\n * const str = prettyFormat(\"hello\"); // Returns: \"hello\"\n *\n * // Objects are converted to indented JSON\n * const obj = prettyFormat({ name: \"John\", age: 30 });\n * // Returns:\n * // {\n * // \"name\": \"John\",\n * // \"age\": 30\n * // }\n * ```\n *\n * @see printf\n *\n * @since 1.0.0\n */\n\nexport function prettyFormat(value: unknown): string {\n if (typeof value === 'string') return value;\n\n return JSON.stringify(value, null, 4);\n}\n\n/**\n * Retrieves a value from a nested object structure based on a specified path.\n *\n * @param data - The object containing the nested data to traverse\n * @param path - An array of strings representing the sequence of keys to access the desired value\n * @returns The value found at the specified path within the object, or `undefined` if the path does not exist\n *\n * @remarks\n * This function safely traverses the given object structure without throwing errors\n * for missing keys or null/undefined values.\n *\n * @example\n * ```ts\n * const data = {\n * user: {\n * profile: {\n * name: \"John Doe\",\n * email: \"john@example.com\"\n * }\n * }\n * };\n *\n * const name = getValueByPath(data, [\"user\", \"profile\", \"name\"]);\n * // Returns: \"John Doe\"\n *\n * const missing = getValueByPath(data, [\"user\", \"settings\", \"theme\"]);\n * // Returns: undefined\n * ```\n *\n * @see resolveVariable\n *\n * @since 1.0.0\n */\n\nexport function getValueByPath(data: Record<string, unknown>, path: string[]): unknown {\n if (!path.length || !data) return undefined;\n\n try {\n return path.reduce((obj, key) => {\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n throw new Error('Path traversal failed');\n }\n\n return (obj as Record<string, unknown>)[key];\n }, data as unknown);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolves a variable token into its corresponding value from the provided data object.\n *\n * @param token - The variable token to resolve\n * @param data - The object containing data used for resolving the variable token\n * @param arrayIndex - The index value to be used if the token represents an array index (`$#`)\n * @returns The resolved value as a string, or the original token if resolution fails\n *\n * @remarks\n * This function assumes the use of dot notation in token paths to access nested properties\n * within the `data` object. Tokens starting with `$#` will be replaced by the array index.\n *\n * @example\n * ```ts\n * const data = {\n * user: {\n * name: \"John\"\n * }\n * };\n *\n * const value1 = resolveVariable(\"$user.name\", data, 0);\n * // Returns: \"John\"\n *\n * const value2 = resolveVariable(\"$#\", data, 5);\n * // Returns: \"5\"\n * ```\n *\n * @see getValueByPath\n * @see interpolateVariables\n *\n * @since 1.0.0\n */\n\nexport function resolveVariable(token: string, data: Record<string, unknown>, arrayIndex: number): string {\n if (!token || typeof <unknown> token !== 'string' || !token.startsWith('$'))\n return token;\n\n if (token === '$#')\n return String(arrayIndex);\n\n const propertyPath = token.slice(1).split('.');\n const resolvedValue = getValueByPath(data, propertyPath);\n\n if (resolvedValue === undefined || resolvedValue === null) {\n return token;\n }\n\n if (typeof resolvedValue === 'object') {\n try {\n return JSON.stringify(resolvedValue, (key, value) => {\n if (key && typeof value === 'object')\n return '[Object]';\n\n return value;\n });\n } catch {\n return String(resolvedValue);\n }\n }\n\n return String(resolvedValue);\n}\n\n/**\n * Replaces variable placeholders within a template string with corresponding values from a provided data object.\n *\n * @param template - The template string containing variable placeholders\n * @param data - An object mapping variable names to their respective values\n * @param arrayIndex - The index to be applied when resolving variables that reference array values\n * @returns The resulting string with all variable placeholders replaced by their resolved values\n *\n * @throws Error - If a required variable cannot be resolved\n *\n * @remarks\n * The function uses a regular expression to identify variable placeholders within the template string\n * and replaces them with corresponding values derived from the `data` object.\n *\n * @example\n * ```ts\n * const data = {\n * user: {\n * name: \"Jane\",\n * id: 42\n * },\n * status: \"active\"\n * };\n *\n * const result = interpolateVariables(\"User $user.name ($user.id) is $status\", data, 0);\n * // Returns: \"User Jane (42) is active\"\n * ```\n *\n * @see VARIABLE_PATTERN\n * @see resolveVariable\n *\n * @since 1.0.0\n */\n\nexport function interpolateVariables(template: string, data: Record<string, unknown>, arrayIndex: number): string {\n return template.replace(\n VARIABLE_PATTERN, (variableToken) => resolveVariable(variableToken, data, arrayIndex)\n );\n}\n\n/**\n * Formats a given string by interpolating it with the provided parameters.\n *\n * @param description - The format string containing variables or tokens to be replaced\n * @param params - An array of values to interpolate or substitute into the format string\n * @param index - An index used for specific token replacements (e.g., `%#`)\n * @returns The formatted string after performing substitutions and formatting\n *\n * @remarks\n * This function supports two formatting approaches:\n * 1. `$variable` style interpolation using the first object in the `params` array\n * 2. Printf-style format specifiers with the following options:\n * - `%p`: Pretty prints a value\n * - `%s`: Converts value to a string\n * - `%d`: Converts value to a numeric string\n * - `%i`: Converts value to an integer string (floor of the number)\n * - `%f`: Converts value to a floating-point string\n * - `%j`: Converts value to its JSON representation\n * - `%o`: Outputs the object's `toString` representation\n * - `%#`: Replaced with the provided `index`\n * - `%%`: Escapes the `%` character\n *\n * If the `description` contains `$`-style variables, it will interpolate those using the first object in the `params` array.\n * This behavior does not apply if the string also contains `%%`.\n *\n * @example\n * ```ts\n * // Format with printf-style specifiers\n * const result1 = printf(\"Value: %s, Number: %d\", [\"test\", 42], 0);\n * // Returns: \"Value: test, Number: 42\"\n *\n * // Format with variable interpolation\n * const data = { name: \"Alice\", age: 30 };\n * const result2 = printf(\"Name: $name, Age: $age\", [data], 0);\n * // Returns: \"Name: Alice, Age: 30\"\n * ```\n *\n * @see prettyFormat\n * @see interpolateVariables\n *\n * @since 1.0.0\n */\n\nexport function printf(description: string, params: Array<unknown>, index: number): string {\n let paramIndex = 0;\n // Handle $variable style interpolation first\n if (description.includes('$') && !description.includes('%%')) {\n description = interpolateVariables(description, <Record<string, unknown>> params[0], index);\n }\n\n return description.replace(/%([psdifjo#%])/g, (match, format) => {\n if (format === '%') return '%';\n if (format === '#') return String(index);\n\n const value = params[paramIndex++];\n switch (format) {\n case 'p':\n return prettyFormat(value);\n case 's':\n return String(value);\n case 'd':\n return Number(value).toString();\n case 'i':\n return Math.floor(Number(value)).toString();\n case 'f':\n return Number(value).toString();\n case 'j':\n return JSON.stringify(value);\n case 'o':\n return Object.prototype.toString.call(value);\n default:\n return match;\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionType } from '@remotex-labs/xjet-expect';\nimport type { InvokeType } from '@shared/directives/interfaces/each-directive.interface';\n\n/**\n * Imports\n */\n\nimport { printf } from '@shared/components/printf.component';\n\n/**\n * Converts a template string and input data into an array of structured objects\n *\n * @param templateString - Template string containing column headings separated by pipe characters\n * @param inputData - Array of values to be organized according to the template structure\n * @returns Array of objects where each object represents a row with properties named after the headings\n *\n * @throws Error - When template headings are empty or missing pipe delimiters\n * @throws Error - When the input data length is not a multiple of the headings length\n *\n * @example\n * ```ts\n * const template = parseTemplate(`name|age|role`, ['John', 30, 'Developer', 'Jane', 25, 'Designer']);\n * // Returns: [\n * // { name: 'John', age: 30, role: 'Developer' },\n * // { name: 'Jane', age: 25, role: 'Designer' }\n * // ]\n * ```\n *\n * @see each - Function that uses parseTemplate for test case generation\n *\n * @since 1.0.0\n */\n\nexport function parseTemplate(templateString: TemplateStringsArray, inputData: Array<unknown>): Array<Record<string, unknown>> {\n // Extract the column headings and remove any leading/trailing whitespace\n const headings: string[] = templateString[0].split('|').map((h: string) => h.trim());\n if (headings.length === 0 || headings.some((h) => h === ''))\n throw new Error('Template string headings must not be empty and should contain pipe delimiters.');\n\n if ((inputData.length % headings.length) !== 0)\n throw new Error('Not enough arguments supplied for given headings.');\n\n return Array.from({ length: inputData.length / headings.length }, (_, rowIndex) => {\n return headings.reduce((acc, heading, columnIndex) => {\n acc[heading] = inputData[rowIndex * headings.length + columnIndex];\n\n return acc;\n }, {} as Record<string, unknown>);\n });\n}\n\n/**\n * Executes a function block as a test case with the specified description\n *\n * @template T - Type extending Array of unknown values\n * @param executor - The function that will execute each test case\n * @param args - Arguments representing test cases or a tagged template literal\n * @returns A function that accepts a test name, test block function, and optional timeout\n *\n * @throws Error - When called with fewer than 2 arguments\n *\n * @remarks\n * This method provides a way to directly invoke a test function with optional arguments.\n * It is typically used with the `each` function to create parameterized test cases.\n * The provided description will be used for test reporting and identification.\n *\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * // As part of the each function with direct arguments\n * test.each(1, 2, 3)('test with %s', (val) => {\n * expect(val).toBeGreaterThan(0);\n * });\n *\n * test.each(\n * { name: 'John', age: 30 },\n * { name: 'Jane', age: 25 }\n * )('User %s is %s years old', (name, age) => {\n * expect(typeof name).toBe('string');\n * expect(typeof age).toBe('number');\n * });\n *\n * test.each`\n * a | b | sum\n * ${ 1 } | ${ 2 } | ${ 3 }\n * ${ 2 } | ${ 5 } | ${ 7 }\n * `('adds $a + $b -> $sum', ({ a, b, sum }) => {\n * expect(a + b).toBe(sum);\n * });\n *\n * describe.each` a | b | expected ${ 1 } | ${ 2 } | ${ 3 } ${ 2 } | ${ 3 } | ${ 5 }`\n * ('%# adds $a and $b to get $expected', ({ a, b, expected }) => {\n * test('calculates sum', () => {\n * expect(a + b).toBe(expected);\n * });\n * });\n * ```\n *\n * @see InvokeType - Type definition for the executor function\n * @see FunctionType - Type definition for the test block function\n * @see parseTemplate - Function used to parse tagged template literals\n *\n * @since 1.0.0\n */\n\nexport function each<T extends Array<unknown>>(executor: InvokeType, ...args: T) {\n if (args.length < 2) {\n throw new Error('`.each` must be called with at leas 2 argument or Tagged Template Literal.');\n }\n\n // eslint-disable-next-line\n const isTemplateStrings = args[0] instanceof Array && (<any> args[0]).raw !== undefined;\n const cases: Array<unknown> = isTemplateStrings ? parseTemplate(<TemplateStringsArray> args.shift(), args) : args;\n\n return (name: string, blockFn: FunctionType, timeout?: number): void => {\n cases.forEach((testCase, index) => {\n const parseArgs = Array.isArray(testCase) ? testCase : [ testCase ];\n executor(printf(name, parseArgs, Number(index)), blockFn, parseArgs, timeout);\n });\n };\n}\n", "export class TimeoutError extends Error {\n constructor(timeout: number, at: string, stack: string = '') {\n super(`Exceeded timeout of ${ timeout } ms at ${ at }`);\n\n // Ensure a correct prototype chain (important for `instanceof`)\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = 'xJetTimeoutError';\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = 'xJetFailingError';\n if(stack) {\n this.stack = `${ this.name }: ${ this.message }\\n${ stack }`;\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionLikeType } from '@remotex-labs/xjet-expect';\n\n/**\n * Imports\n */\n\nimport { TimeoutError } from '@errors/timeout.error';\n\n\n/**\n * Executes a given asynchronous or synchronous task with an optional timeout constraint.\n *\n * @typeParam T - The resolved value type.\n *\n * @param task - Either a function that returns a value or promise, or a promise itself.\n * @param delay - Timeout in milliseconds, or `-1` to disable the timeout.\n * @param at - A contextual label (e.g., method name or operation name) to aid debugging.\n * @param stack - Optional stack trace to provide more detailed error context.\n *\n * @throws {@link TimeoutError} If the task does not complete within the specified `delay`\n * (only when `delay` is not `-1`).\n *\n * @remarks\n * The function accepts either:\n * - a function returning a value or a promise, or\n * - a promise directly.\n *\n * If `delay` is `-1`, no timeout is applied. Otherwise the task is raced against\n * a timer and a {@link TimeoutError} is thrown on expiry.\n *\n * @example\n * ```ts\n * // Passing a function\n * await withTimeout(\n * () => fetchData(),\n * 5000,\n * 'fetchData'\n * );\n *\n * // Passing a promise directly\n * await withTimeout(\n * fetchData(),\n * 5000,\n * 'fetchDataDirect'\n * );\n *\n * // No timeout\n * await withTimeout(fetchData(), -1, 'fetchDataNoTimeout');\n * ```\n *\n * @since 1.1.0\n */\n\nexport async function withTimeout<T>(\n task: FunctionLikeType<T | Promise<T>> | Promise<T> | T, delay: number, at: string, stack?: string\n): Promise<T> {\n const taskPromise =\n typeof task === 'function'\n ? Promise.resolve((task as FunctionLikeType<T | Promise<T>>)())\n : Promise.resolve(task);\n\n if (delay === -1 || !globalThis?.setTimeout) {\n return taskPromise;\n }\n\n let timeoutId: ReturnType<typeof setTimeout>;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = globalThis?.setTimeout?.(\n () => reject(new TimeoutError(delay, at, stack)),\n delay\n );\n });\n\n try {\n return await Promise.race([ taskPromise, timeoutPromise ]);\n } finally {\n globalThis?.clearTimeout?.(timeoutId!);\n }\n}\n\n", "/**\n * Imports\n */\n\nimport { ExecutionError } from '@shared/errors/execution.error';\n\n\nexport class FailingError extends ExecutionError {\n\n\n constructor(stack: string) {\n super('Failing test passed even though it was supposed to fail. Remove `.failing` to remove error.');\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, FailingError);\n }\n\n this.name = 'xJetFailingError';\n this.stack = `${ this.name }: ${ this.message }\\n${ stack }`;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { TestFlagsType } from '@shared/models/interfaces/test-model.interface';\nimport type { ContextInterface } from '@shared/models/interfaces/describe-model.interface';\n\n/**\n * Imports\n */\n\nimport { SuiteState } from '@shared/states/suite.state';\nimport { inject } from '@symlinks/services/inject.service';\nimport { withTimeout } from '@components/timeout.component';\nimport { FailingError } from '@shared/errors/failing.error';\nimport { MessageType } from '@messages/constants/report.constant';\nimport { emitEvent, emitStatus } from '@shared/services/emit.service';\nimport { HookType } from '@shared/models/constants/hook.model.constants';\nimport { TestExecutionType } from '@shared/models/constants/test-model.constants';\nimport { type ContextType, type FunctionLikeType, type FunctionType, isPromise } from '@remotex-labs/xjet-expect';\n\n/**\n * Represents a test case within the testing framework that manages execution,\n * timing, and reporting of individual tests.\n *\n * @example\n * ```ts\n * const test = new TestModel(\n * 'should validate user input correctly',\n * async () => {\n * const result = await validateInput('test@example.com');\n * expect(result.isValid).toBe(true);\n * },\n * 2000\n * );\n *\n * // Set ancestry to show the test's location in the test hierarchy\n * test.ancestry = ['Authentication', 'Input Validation'];\n *\n * // Execute the test\n * await test.execute();\n * ```\n *\n * @remarks\n * The TestModel is responsible for tracking test execution time, handling timeouts,\n * managing test context, and reporting test status through the emit service.\n * It supports both synchronous and promise-based test implementations.\n *\n * @throws FailingError - When a test fails due to assertions or errors\n *\n * @see ContextInterface\n * @see EmitActionEventType\n * @see EmitStatusEventType\n * @see InvocationLocationType\n *\n * @since 1.0.0\n */\n\nexport class TestModel {\n /**\n * Stores the hierarchical path of parent test descriptions that contain this test\n *\n * @default []\n * @since 1.0.0\n */\n\n readonly ancestry: Array<string> = [];\n\n /**\n * Stores information about where this test is being executed in the source code\n *\n * @see InvocationLocationType\n * @since 1.0.0\n */\n\n private executionLocation: string = '';\n\n /**\n * Timestamp when test execution started, measured in milliseconds\n *\n * @default 0\n * @since 1.0.0\n */\n\n private executionStartTime: number = 0;\n\n /**\n * Creates a new instance of the TestModel to represent an executable test.\n *\n * @param description - The test description that explains the purpose of the test\n * @param testImplementation - The function containing the actual test code to be executed\n * @param timeoutDuration - The maximum time in milliseconds that the test is allowed to run\n * @param testParameters - An array of parameters to be passed to the test implementation\n * @param testOptions - Configuration options that control test execution behavior\n *\n * @example\n * ```ts\n * const test = new TestModel(\n * 'should calculate the correct sum',\n * () => expect(sum(2, 2)).toBe(4),\n * 5000\n * );\n * ```\n *\n * @since 1.0.0\n */\n\n constructor(\n readonly description: string,\n private readonly testImplementation: FunctionType,\n private readonly timeoutDuration: number,\n private readonly testParameters: unknown[] = [],\n private readonly testOptions: TestFlagsType = {}\n ) {}\n\n /**\n * Provides access to the test configuration options.\n *\n * @returns The test configuration options that control test execution behavior\n *\n * @since 1.0.0\n */\n\n get options(): TestFlagsType {\n return this.testOptions;\n }\n\n /**\n * Sets the location where the test is being executed.\n *\n * @param location - The execution location information containing position details\n *\n * @see InvocationLocationType\n * @since 1.0.0\n */\n\n setExecutionLocation(location: string): void {\n this.executionLocation = location;\n }\n\n /**\n * Applies execution control options to the test, allowing it to be skipped or run exclusively.\n *\n * @param skip - Flag indicating whether the test should be skipped during execution\n * @param only - Flag indicating whether only this test should be executed\n *\n * @remarks\n * This method uses logical OR assignment (||=) to ensure options are only set to true and\n * never reset from true to false. Existing flag values take precedence.\n *\n * @example\n * ```ts\n * testInstance.applyExecutionFlags(true, false); // Will mark test to be skipped\n * testInstance.applyExecutionFlags(false, true); // Will mark test to run exclusively\n * ```\n *\n * @see TestFlagsType\n * @since 1.0.0\n */\n\n applyExecutionFlags(skip?: boolean, only?: boolean): void {\n this.testOptions.skip ||= skip;\n this.testOptions.only ||= only;\n }\n\n /**\n * Sets the ancestry for this test by adding parent test descriptions to the ancestry chain.\n *\n * @param parentTests - Array of parent test description strings representing the test hierarchy\n *\n * @example\n * ```ts\n * const childTest = new TestModel(\"should work\", () => {}, 5000);\n * childTest.setAncestry([\"describe block A\", \"describe block B\"]);\n * ```\n *\n * @since 1.0.0\n */\n\n setAncestry(parentTests: string[]): void {\n this.ancestry.push(...parentTests);\n }\n\n /**\n * Executes the test within the specified context, managing test lifecycle and status reporting.\n *\n * @param context - The test execution context containing shared state and utilities\n * @param runLifecycleHooks - Function that runs before/after hooks at appropriate times\n * @param isExclusiveMode - Flag indicating if tests are running in exclusive mode (only marked tests)\n * @returns Promise that resolves when the test execution completes\n *\n * @throws Error - If any unhandled exceptions occur during test execution that aren't captured\n *\n * @remarks\n * The method tracks execution time, manages test lifecycle, handles skipping logic, and processes\n * test results. It also notifies about test status changes through observer pattern implementation.\n *\n * @example\n * ```ts\n * // Running a test with context and lifecycle hooks\n * await testInstance.run(\n * testContext,\n * async (hookType, ctx) => {\n * await runHooks(hookType, ctx);\n * },\n * false\n * );\n * ```\n *\n * @see HookType\n * @see ActionType\n * @see ContextInterface\n *\n * @since 1.0.0\n */\n\n async run(\n context: ContextType<ContextInterface>,\n runLifecycleHooks: FunctionLikeType<Promise<void>, [ HookType, ContextType<ContextInterface> ]>,\n isExclusiveMode: boolean = false\n ): Promise<void> {\n inject(SuiteState).test = this;\n this.executionStartTime = Date.now();\n\n if (this.shouldSkipDueToSetupErrors(context))\n return;\n\n if (this.determineSkipAction(isExclusiveMode)) return;\n\n try {\n await this.executeTestWithLifecycle(context, runLifecycleHooks);\n this.validateTestOutcome();\n } catch (error) {\n this.notifyTestFailure(error);\n if(globalThis.__XJET?.runtime.bail) {\n context.hasError = true;\n }\n } finally {\n inject(SuiteState).test = undefined;\n }\n }\n\n /**\n * Determines whether a test should be skipped due to errors in setup hooks.\n *\n * @param context - The test execution context containing shared state and potential setup errors\n * @returns Boolean indicating whether the test should be skipped\n *\n * @remarks\n * This method checks if any errors occurred in beforeAll hooks and reports them as test failures.\n * Tests are skipped when setup errors are present to prevent misleading test results.\n *\n * @see ContextInterface\n *\n * @internal\n *\n * @since 1.0.0\n */\n\n private shouldSkipDueToSetupErrors(context: ContextType<ContextInterface>): boolean {\n if (context.beforeAllErrors && context.beforeAllErrors.length > 0) {\n this.notifyTestFailure(context.beforeAllErrors as Array<unknown>);\n\n return true;\n }\n\n return false;\n }\n\n private determineSkipAction(isExclusiveMode: boolean): boolean {\n if(inject(SuiteState).isOnlyMode && !this.testOptions.only) {\n this.notifyTestStatus(true);\n\n return true;\n }\n\n if (this.testOptions.skip || this.testOptions.todo) {\n this.notifyTestStatus(this.testOptions.skip, this.testOptions.todo);\n\n return true;\n }\n\n if(isExclusiveMode && !this.testOptions.only) {\n this.notifyTestStatus(true);\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Executes a test with proper lifecycle hooks and timeout management.\n *\n * @param context - The test execution context containing shared state and utilities\n * @param runLifecycleHooks - Function that runs the specified hook type with the given context\n *\n * @returns Promise that resolves when the test and all its lifecycle hooks have completed\n *\n * @throws TimeoutError - When the test execution exceeds the configured timeout duration\n *\n * @remarks\n * This method orchestrates the complete test execution flow including:\n * 1. Running beforeEach hooks\n * 2. Executing the actual test body with timeout protection\n * 3. Running afterEach hooks regardless of test outcome\n *\n * @internal\n * @see HookType\n * @see ContextInterface\n * @see withTimeout\n *\n * @since 1.0.0\n */\n\n private async executeTestWithLifecycle(\n context: ContextType<ContextInterface>,\n runLifecycleHooks: FunctionLikeType<Promise<void>, [ HookType, ContextType<ContextInterface> ]>\n ): Promise<void> {\n await runLifecycleHooks(HookType.BEFORE_EACH, context);\n\n await withTimeout<void>(\n this.executeTestWithContext(context),\n this.timeoutDuration,\n `'${ this.timeoutDuration }' test`,\n this.executionLocation\n );\n\n await runLifecycleHooks(HookType.AFTER_EACH, context);\n }\n\n /**\n * Validates the test outcome, handling failing tests and notifying of success.\n *\n * @throws FailingError - When a test is marked as failing but successfully completes\n *\n * @remarks\n * This method implements special handling for tests marked with the 'failing' option.\n * For failing tests, it throws an error if the test unexpectedly succeeds.\n * For normal tests, it reports a successful test outcome.\n *\n * @internal\n * @see ActionType\n * @see FailingError\n *\n * @since 1.0.0\n */\n\n private validateTestOutcome(): void {\n if (this.testOptions.failing) {\n throw new FailingError(this.executionLocation!);\n }\n\n this.notifyTestAction();\n }\n\n /**\n * Determines if the test is using callback-style asynchronous execution.\n *\n * @returns Boolean indicating whether the test uses the callback pattern\n *\n * @remarks\n * This method analyzes the test implementation's parameter count to detect callback-style tests.\n * It identifies two callback patterns:\n * 1. A test function that expects exactly one parameter (the callback) with no test parameters\n * 2. A test function that expects exactly two parameters (test arguments and callback)\n *\n * The callback pattern is an alternative to Promise-based async tests.\n *\n * @internal\n * @since 1.0.0\n */\n\n private isCallbackStyle(): boolean {\n if (this.testImplementation.length === 1 && this.testParameters.length === 0)\n return true;\n\n // Or if it expects more parameters (test args + callback)\n return this.testImplementation.length === 2;\n }\n\n private getExecutionStrategy(): TestExecutionType {\n if (isPromise(this.testImplementation)) return TestExecutionType.ASYNC;\n if (this.isCallbackStyle()) return TestExecutionType.CALLBACK;\n\n return TestExecutionType.SYNC;\n }\n\n /**\n * Executes the test function with the appropriate execution strategy based on its type.\n *\n * @param context - The test execution context containing shared state and utilities\n *\n * @returns Promise that resolves when the test execution completes\n *\n * @throws Error - When the test execution fails for any reason\n *\n * @remarks\n * This method determines and applies the correct execution strategy for the test:\n * - For synchronous and async tests, it calls the test implementation directly with the context\n * - For callback-style tests, it delegates to a specialized execution method\n * The method ensures proper 'this' binding by using Function.prototype.apply\n *\n * @internal\n * @see ContextInterface\n * @see TestExecutionType\n *\n * @since 1.0.0\n */\n\n private async executeTestWithContext(context: ContextType<ContextInterface>): Promise<void> {\n const strategy = this.getExecutionStrategy();\n\n switch (strategy) {\n case TestExecutionType.ASYNC:\n case TestExecutionType.SYNC:\n await this.testImplementation.apply(context, this.testParameters);\n break;\n case TestExecutionType.CALLBACK:\n await this.executeCallbackStyleTest(context);\n break;\n }\n }\n\n /**\n * Executes a callback-style test by wrapping it in a Promise.\n *\n * @param context - The test execution context containing shared state and utilities\n *\n * @returns Promise that resolves when the callback is invoked without an error, or rejects when called with an error\n *\n * @throws Error - When the callback is invoked with an error parameter\n *\n * @remarks\n * This method adapts callback-style test functions to work within a Promise-based execution flow.\n * It creates a Promise wrapper around the test function and:\n * 1. Defines a callback function that resolves/rejects the Promise based on error parameter\n * 2. Appends this callback to the original test parameters\n * 3. Invokes the test with proper context binding using Function.prototype.apply\n *\n * The callback function follows Node.js convention with an optional error as first parameter.\n *\n * @internal\n * @see ContextInterface\n *\n * @since 1.0.0\n */\n\n private async executeCallbackStyleTest(context: ContextType<ContextInterface>): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const callbackFn = (error?: string | { message: string }): void => {\n if (error) reject(error);\n resolve();\n };\n\n const allParameters = [ ...this.testParameters ];\n allParameters.push(callbackFn);\n\n this.testImplementation.apply(context, allParameters);\n });\n }\n\n /**\n * Calculates the elapsed execution time of the test in milliseconds.\n *\n * @returns Number representing the test execution duration in milliseconds\n *\n * @remarks\n * This method computes the time difference between now and when the test started execution.\n * It returns 0 if the test has not yet started (when executionStartTime is 0).\n * The time measurement uses the system clock via Date.now().\n *\n * @internal\n * @since 1.0.0\n */\n\n private getExecutionDuration(): number {\n if (this.executionStartTime === 0) return 0;\n\n return Date.now() - this.executionStartTime;\n }\n\n\n private notifyTestStatus(skip: boolean = false, todo: boolean = false): void {\n emitStatus(MessageType.Test, {\n todo: todo,\n skipped: skip,\n ancestry: this.ancestry,\n description: this.description\n });\n }\n\n /**\n * Emits an action event when a test execution has a significant state change.\n *\n * @param type - The type of action event to emit (e.g., start, complete, skip)\n * @param errors - Collection of errors that occurred during test execution\n *\n * @remarks\n * This method broadcasts notifications about test execution actions through the event system.\n * It includes comprehensive information about the test:\n * - Any errors that occurred\n * - Test type as a KindType\n * - The test's ancestry (parent hierarchy)\n * - Execution duration up to the point of notification\n * - Source code location information\n * - The test's description text\n * These action events are typically consumed by reporters and test runners.\n *\n * @internal\n * @see KindType\n * @see EmitActionEventType\n *\n * @since 1.0.0\n */\n\n private notifyTestAction(errors: Array<unknown> = []): void {\n emitEvent(MessageType.Test, {\n errors: <Array<Error>> errors,\n ancestry: this.ancestry,\n duration: this.getExecutionDuration(),\n description: this.description\n });\n }\n\n /**\n * Emits a test failure action event with the associated error information.\n *\n * @param error - The error or errors that caused the test to fail\n *\n * @remarks\n * This method standardizes the reporting of test failures by:\n * 1. Ensuring errors are always passed as an array\n * 2. Converting single errors to array format when needed\n * 3. Delegating to the more general notifyTestAction method with the FAILURE action type\n * It serves as a specialized wrapper around the general action notification system.\n *\n * @internal\n * @see ActionType\n *\n * @since 1.0.0\n */\n\n private notifyTestFailure(error: unknown): void {\n this.notifyTestAction(Array.isArray(error) ? error : [ error ]);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionType } from '@remotex-labs/xjet-expect';\nimport type { TestFlagsType } from '@shared/models/interfaces/test-model.interface';\nimport type { TestCallbackType, TestDirectiveInterface } from '@shared/directives/interfaces/test-directive.interface';\n\n/**\n * Imports\n */\n\nimport { each } from './each.directive';\nimport { TestModel } from '@shared/models/test.model';\nimport { SuiteState } from '@shared/states/suite.state';\nimport { inject } from '@symlinks/services/inject.service';\nimport { getTrimmedStackString } from '@components/location.component';\n\n/**\n * Implementation of the test directive that allows for test definition with chainable modifiers.\n * Acts as a function that can be invoked directly while also providing chainable property access.\n *\n * @template T - Type parameter for the test callback return type\n *\n * @param description - The test description\n * @param block - The test implementation function\n * @param timeout - Optional timeout in milliseconds\n *\n * @returns void\n *\n * @throws Error - When attempting to nest tests inside other tests\n * @throws Error - When using incompatible flag combinations (e.g., skip with only)\n *\n * @remarks\n * This class extends Function to allow it to be invoked as a function while also\n * providing methods and properties. It uses a Proxy to capture function invocations\n * and redirects them to the invoke method.\n *\n * @example\n * ```ts\n * // Basic test\n * test('should work', () => {\n * expect(2 + 2).toBe(4);\n * });\n *\n * // With modifiers\n * test.only('runs exclusively', () => {\n * expect(true).toBe(true);\n * });\n *\n * // Parameterized tests\n * test.each([1, 2, 3])('test with value %s', (value) => {\n * expect(typeof value).toBe('number');\n * });\n * ```\n *\n * @see SuiteState\n * @see TestDirectiveInterface\n *\n * @since 1.0.0\n */\n\nexport class TestDirective extends Function {\n /**\n * Singleton instance of the TestDirective class.\n *\n * @see TestDirectiveInterface\n * @since 1.0.0\n */\n\n private static instance?: TestDirective;\n\n /**\n * Error messages for invalid flag combinations in test configuration.\n *\n * @since 1.0.0\n */\n\n private static readonly ERROR_MESSAGES = {\n SKIP_ONLY: 'Cannot use \"only\" flag on skipped test',\n ONLY_SKIP: 'Cannot use \"skip\" flag on only test',\n SKIP_TODO: 'Cannot use \"todo\" flag on skipped test',\n SKIP_FAILING: 'Cannot use \"failing\" flag on skipped test'\n };\n\n /**\n * Default timeout in milliseconds for test execution\n * @since 1.0.0\n */\n\n private static readonly DEFAULT_TIMEOUT = globalThis.__XJET?.runtime.timeout ?? 5000;\n\n /**\n * Configuration options controlling test behavior\n\n * @see TestFlagsType\n * @since 1.0.0\n */\n\n private options: TestFlagsType = {};\n\n /**\n * @param invokationStack - The precise source code invocationStack where the error occurred\n */\n\n private invocationStack: string = '';\n\n /**\n * Private constructor that initializes the TestDirective instance and returns a proxied version.\n *\n * @returns A Proxy that handles direct function invocation by redirecting to the invoke method\n *\n * @remarks\n * The constructor is private to enforce the singleton pattern. It creates a Proxy\n * that allows the object to be called as a function while maintaining its object properties.\n * When called as a function, the proxy redirects the call to the invoke method.\n *\n * @internal\n * @see invoke\n *\n * @since 1.0.0\n */\n\n private constructor() {\n super();\n\n return new Proxy(this, {\n apply: (target, _, args: [string, FunctionType, number?]): void => {\n const [ description, block, timeout ] = args;\n this.invocationStack = getTrimmedStackString(2);\n\n target.invoke(description, block, [], timeout);\n }\n });\n }\n\n /**\n * Returns the singleton instance of TestDirective, creating it if it doesn't exist\n *\n * @returns The singleton instance of the test directive implementation\n *\n * @remarks\n * This method implements the singleton pattern, ensuring only one instance of the test directive exists\n * throughout the application lifecycle\n *\n * @example\n * ```ts\n * const test = TestDirective.getInstance();\n * test('my test', () => {\n * // test implementation\n * });\n * ```\n *\n * @see TestDirectiveInterface\n *\n * @since 1.0.0\n */\n\n static getInstance(): TestDirectiveInterface {\n if (!TestDirective.instance) {\n TestDirective.instance = new TestDirective();\n }\n\n return TestDirective.instance as unknown as TestDirectiveInterface;\n }\n\n /**\n * Returns the singleton instance of TestDirective, creating it if it doesn't exist.\n *\n * @returns The singleton instance of TestDirective cast to TestDirectiveInterface\n *\n * @remarks\n * This method implements the Singleton pattern to ensure only one instance of\n * TestDirective exists in the application. It creates the instance on the first call\n * and returns the existing instance on subsequent calls.\n *\n * @example\n * ```ts\n * const test = TestDirective.getInstance();\n * test('example test', () => {\n * expect(true).toBe(true);\n * });\n * ```\n *\n * @since 1.0.0\n */\n\n get skip(): this {\n if (this.options.only) throw new Error(TestDirective.ERROR_MESSAGES.ONLY_SKIP);\n this.options.skip = true;\n\n return this;\n }\n\n /**\n * Sets the 'only' flag for this test, making it the only test to run in its suite.\n *\n * @returns This instance with the 'only' flag set\n *\n * @throws Error - When attempting to set 'only' flag on a skipped test\n *\n * @example\n * ```ts\n * test.only('this is the only test that will run', () => {\n * expect(true).toBe(true);\n * });\n * ```\n *\n * @see skip\n * @since 1.0.0\n */\n\n get only(): this {\n if (this.options.skip) throw new Error(TestDirective.ERROR_MESSAGES.SKIP_ONLY);\n this.options.only = true;\n\n return this;\n }\n\n /**\n * Marks a test as a todo item, indicating it's planned but not yet implemented\n *\n * @throws Error - When attempting to use todo flag on a skipped test\n *\n * @remarks\n * Todo tests appear in test reports to remind developers of planned work,\n * but don't execute any test code\n *\n * @example\n * ```ts\n * // Define a todo test\n * test.todo('feature that needs implementation');\n * ```\n *\n * @see TestFlagsType\n *\n * @since 1.0.0\n */\n\n get todo(): this {\n if (this.options.skip) throw new Error(TestDirective.ERROR_MESSAGES.SKIP_TODO);\n this.options.todo = true;\n\n return this;\n }\n\n /**\n * Marks the test as expected to fail.\n *\n * @returns This instance with the 'failing' flag set\n *\n * @throws Error - When attempting to mark a skipped test as failing\n *\n * @example\n * ```ts\n * test.failing('this test is expected to fail', () => {\n * throw new Error('This is an expected failure');\n * });\n * ```\n *\n * @see skip\n * @since 1.0.0\n */\n\n get failing(): this {\n if (this.options.skip) throw new Error(TestDirective.ERROR_MESSAGES.SKIP_FAILING);\n this.options.failing = true;\n\n return this;\n }\n\n /**\n * Creates a parameterized test using template strings.\n *\n * @template T - Array type containing the values to be used in the test\n *\n * @param string - Template string array used to create the test title\n * @param placeholders - Values to be inserted into the template string\n * @returns A callback function for creating the parameterized test\n *\n * @remarks\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * test.each`\n * a | b | expected\n * ${1} | ${1} | ${2}\n * ${2} | ${2} | ${4}\n * `('returns $expected when $a is added to $b', ({a, b, expected}) => {\n * expect(a + b).toBe(expected);\n * });\n * ```\n *\n * @see each.array\n * @since 1.0.0\n */\n\n each<T extends ReadonlyArray<unknown>>(string: TemplateStringsArray, ...placeholders: T): TestCallbackType<Record<string, T[number]>>;\n\n /**\n * Creates a parameterized test using arrays of test cases.\n *\n * @template T - Type representing the test case data structure\n *\n * @param cases - Arrays containing test case values\n * @returns A callback function for creating the parameterized test\n *\n * @remarks\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * test.each(\n * [1, 1, 2],\n * [1, 2, 3],\n * [2, 2, 4]\n * )('adds %i + %i to equal %i', (a, b, expected) => {\n * expect(a + b).toBe(expected);\n * });\n * ```\n *\n * @see each\n * @since 1.0.0\n */\n\n each<T extends Array<unknown> | [unknown]>(...cases: T[]): TestCallbackType<T>; // array\n\n /**\n * Creates a parameterized test using individual test case objects or primitive values.\n *\n * @template T - Type representing the test case data\n *\n * @param args - Test case objects or primitive values\n * @returns A callback function for creating the parameterized test\n *\n * @remarks\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * test.each(\n * { a: 1, b: 1, expected: 2 },\n * { a: 1, b: 2, expected: 3 },\n * { a: 2, b: 2, expected: 4 }\n * )('adds $a + $b to equal $expected', ({ a, b, expected }) => {\n * expect(a + b).toBe(expected);\n * });\n * ```\n *\n * @see each\n * @since 1.0.0\n */\n\n each<T>(...args: readonly T[]): TestCallbackType<T>; // object, and primitives\n\n /**\n * Creates a parameterized test using arrays of primitive values as test cases.\n *\n * @template T - Array type containing the primitive test values\n *\n * @param args - Arrays of primitive values to be used as test cases\n * @returns A callback function for creating the parameterized test\n *\n * @remarks\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * test.each(\n * [1, 2, 3],\n * [4, 5, 9],\n * [6, 7, 13]\n * )('adds %i + %i to equal %i', (a, b, expected) => {\n * expect(a + b).toBe(expected);\n * });\n * ```\n *\n * @see each\n * @since 1.0.0\n */\n\n each<T extends Array<unknown>>(...args: T): TestCallbackType<T[number]>; // primitives\n\n /**\n * Creates a parameterized test using various input formats.\n *\n * @param args - Test case data in array format\n * @returns A callback function for creating the parameterized test\n *\n * @remarks\n * This method delegates to the implementation after binding the invoke method to the current context.\n *\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * test.each(\n * [1, 1, 2],\n * [1, 2, 3],\n * [2, 2, 4]\n * )('adds %i + %i to equal %i', (a, b, expected) => {\n * expect(a + b).toBe(expected);\n * });\n * ```\n *\n * @see each.table\n * @see each.array\n * @since 1.0.0\n */\n\n each(...args: Array<unknown>): TestCallbackType<unknown> {\n return each(this.invoke.bind(this), ...args);\n }\n\n /**\n * Invokes a test with the provided description, test function, arguments, and optional timeout.\n *\n * @param description - The description of the test to be displayed in test reports\n * @param block - The test function containing the test logic\n * @param args - Additional arguments to be passed to the test function\n * @param timeout - Optional timeout value in milliseconds for the test\n *\n * @throws TestNestingError - When attempting to create a nested test\n *\n * @remarks\n * This method handles the complete test registration flow, including validation,\n * creation, registration, and flag management. If no test function is provided,\n * the test will be automatically marked as todo.\n *\n * @example\n * ```ts\n * invoke('should sum two numbers', (a, b) => {\n * expect(sum(a, b)).toBe(a + b);\n * }, [5, 10], 2000);\n * ```\n *\n * @internal\n * @since 1.0.0\n */\n\n invoke(description: string, block: FunctionType, args: Array<unknown> = [], timeout?: number): void {\n this.validateTestNesting(description);\n\n // Auto-set todo flag if no test function provided\n if (!block) {\n this.options.todo = true;\n }\n\n // Create and register the test\n const test = this.createTest(description, block, args, timeout);\n this.registerTest(test, this.invocationStack);\n\n // Reset options after test creation\n this.resetFlags();\n }\n\n /**\n * Validates that tests are not being nested inside other tests.\n *\n * @param description - The description of the test being validated\n *\n * @throws Error - When a test is nested inside another test, with details about both tests\n *\n * @remarks\n * Nesting tests is not supported in the testing framework as it can lead to unpredictable behavior\n * and difficult-to-debug test scenarios.\n *\n * @internal\n * @since 1.0.0\n */\n\n private validateTestNesting(description: string): void {\n const runningTest = inject(SuiteState).test;\n if (runningTest) {\n // set invokation\n throw new Error(`Cannot nest a test inside a test '${ description }' in '${ runningTest.description }'`);\n }\n }\n\n /**\n * Creates a new TestModel with the current configuration\n */\n private createTest(description: string, block: FunctionType, args: Array<unknown>, timeout?: number): TestModel {\n return new TestModel(\n description,\n block,\n timeout ?? TestDirective.DEFAULT_TIMEOUT,\n args,\n { ...this.options } // Clone options to prevent shared references\n );\n }\n\n /**\n * Registers a test with the test suite and sets its execution invocationStack.\n *\n * @param test - The test model to register\n * @param location - The precise source code invocationStack where the error occurred\n *\n * @remarks\n * This method determines the invocationStack where the test was invoked in the source code\n * and attaches that information to the test before adding it to the suite state.\n * Location information is useful for error reporting and test navigation.\n *\n * @internal\n * @since 1.0.0\n */\n\n private registerTest(test: TestModel, location: string): void {\n if (location) {\n test.setExecutionLocation(location);\n }\n inject(SuiteState).addTest(test);\n }\n\n /**\n * Resets all test configuration options to their default state.\n *\n * @returns Nothing\n *\n * @remarks\n * This method clears all previously set options to ensure that configuration\n * from one test doesn't leak into subsequent tests.\n *\n * @internal\n * @since 1.0.0\n */\n\n private resetFlags(): void {\n this.options = {};\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionType } from '@remotex-labs/xjet-expect';\nimport type { DescribeOptionsInterface } from '@shared/models/interfaces/describe-model.interface';\nimport type { DescribeCallbackType } from '@shared/directives/interfaces/describe-directive.interface';\nimport type { DescribeDirectiveInterface } from '@shared/directives/interfaces/describe-directive.interface';\n\n/**\n * Imports\n */\n\nimport { SuiteState } from '@shared/states/suite.state';\nimport { each } from '@shared/directives/each.directive';\nimport { inject } from '@symlinks/services/inject.service';\n\n/**\n * Implementation of the describe directive that allows for test suite definition with chainable modifiers.\n * Acts as a function that can be invoked directly while also providing chainable property access.\n *\n * @param description - The test suite description\n * @param block - The test suite implementation function\n *\n * @throws Error - When attempting to nest describe blocks inside tests\n * @throws Error - When using incompatible flag combinations (e.g., skip with only)\n *\n * @remarks\n * This class extends Function to allow it to be invoked as a function while also\n * providing methods and properties. It uses a Proxy to capture function invocations\n * and redirects them to the invoke method.\n *\n * The describe directive creates a group of related tests, providing organization and structure\n * to test suites. It supports chainable modifiers for customizing test suite behavior,\n * and parameterized testing via the 'each' method.\n *\n * @example\n * ```ts\n * // Basic describe block\n * describe('Calculator', () => {\n * test('should add numbers', () => {\n * expect(2 + 2).toBe(4);\n * });\n * });\n *\n * // With modifiers\n * describe.only('Priority feature', () => {\n * test('important test case', () => {\n * expect(true).toBe(true);\n * });\n * });\n *\n * // With parameterized tests using each\n * describe.each([1, 2, 3])('Math operations for %s', (value) => {\n * test('square', () => {\n * expect(value * value).toBeGreaterThan(0);\n * });\n * });\n * ```\n *\n * @see SuiteState\n * @see DescribeDirectiveInterface\n *\n * @since 1.0.0\n */\n\nexport class DescribeDirective extends Function {\n /**\n * Singleton instance of the DescribeDirective class.\n *\n * @see DescribeDirectiveInterface\n * @since 1.0.0\n */\n\n private static instance: DescribeDirectiveInterface | null = null;\n\n /**\n * Configuration options controlling test suite behavior\n *\n * @see DescribeOptionsInterface\n * @since 1.0.0\n */\n\n private options: DescribeOptionsInterface = {};\n\n /**\n * Private constructor that initializes the DescribeDirective instance and returns a proxied version.\n *\n * @returns A Proxy that handles direct function invocation by redirecting to the invoke method\n *\n * @remarks\n * The constructor is private to enforce the singleton pattern. It creates a Proxy\n * that allows the object to be called as a function while maintaining its object properties.\n * When called as a function, the proxy redirects the call to the invoke method.\n *\n * @internal\n * @see invoke\n *\n * @since 1.0.0\n */\n\n private constructor() {\n super();\n\n return <this>new Proxy(this, {\n apply(target, thisArg, args: [ string, FunctionType ]): void {\n target.invoke(args[0], args[1]);\n }\n });\n }\n\n /**\n * Returns the singleton instance of DescribeDirective, creating it if it doesn't exist\n *\n * @returns The singleton instance of the describe directive implementation\n *\n * @remarks\n * This method implements the singleton pattern, ensuring only one instance of the describe directive\n * exists throughout the application lifecycle.\n *\n * @see DescribeDirectiveInterface\n * @since 1.0.0\n */\n\n static getInstance(): DescribeDirectiveInterface {\n if (!DescribeDirective.instance) {\n DescribeDirective.instance = <DescribeDirectiveInterface><unknown>new DescribeDirective();\n }\n\n return DescribeDirective.instance;\n }\n\n /**\n * Creates a skipped test suite that will be recognized but not executed during test runs\n *\n * @returns The same DescribeDirective instance with skip flag enabled, allowing for method chaining\n * @throws Error - When attempting to combine with 'only' flag which would create conflicting behavior\n *\n * @remarks\n * When applied, the test suite will be marked as skipped in test reports but won't be executed.\n * Cannot be combined with the 'only' modifier due to conflicting behavior.\n *\n * @example\n * ```ts\n * describe.skip('temporarily disabled suite', () => {\n * test('will not run', () => {\n * expect(result).toBe(true);\n * });\n * });\n * ```\n *\n * @see DescribeDirectiveInterface\n * @since 1.0.0\n */\n\n get skip(): this {\n if (this.options.only) throw new Error('Cannot use \"skip\" flag on only test');\n this.options.skip = true;\n\n return this;\n }\n\n /**\n * Creates an exclusive test suite that will run while other non-exclusive suites are skipped\n *\n * @returns The same DescribeDirective instance with only flag enabled, allowing for method chaining\n * @throws Error - When attempting to combine with 'skip' flag which would create conflicting behavior\n *\n * @remarks\n * When applied, only this test suite and other suites marked with 'only' will be executed.\n * This is useful for focusing on specific test suites during development or debugging.\n * Cannot be combined with the 'skip' modifier due to conflicting behavior.\n *\n * @example\n * ```ts\n * describe.only('focus on this suite', () => {\n * test('will run', () => {\n * expect(result).toBe(expectedValue);\n * });\n * });\n * ```\n *\n * @see DescribeDirectiveInterface\n * @since 1.0.0\n */\n\n get only(): this {\n if (this.options.skip) throw new Error('Cannot use \"only\" flag on skipped test');\n this.options.only = true;\n\n return this;\n }\n\n /**\n * Generates parameterized test suites from template strings and placeholders.\n *\n * @template T - An array type extending ReadonlyArray<unknown> that contains the placeholder values\n *\n * @param string - A template string array that defines the structure of test suite descriptions\n * @param placeholders - Values to be inserted into the template strings to create test suites\n *\n * @returns A callback function compatible with Jest's describe method that provides parameterized test data\n *\n * @throws TypeError - When the number of placeholders doesn't match the template string requirements\n *\n * @remarks\n * This method uses tagged template literals to create parameterized test suites.\n * The values provided as placeholders will be passed to describe callbacks as named parameters.\n *\n * The returned function accepts the following parameters:\n * - name: String - The title of the describe block.\n * Generate unique describe titles by positionally injecting parameters with printf formatting:\n * %p - pretty-format.\n * %s - String.\n * %d - Number.\n * %i - Integer.\n * %f - Floating point value.\n * %j - JSON.\n * %o - Object.\n * %# - Index of the test suite.\n * %% - single percent sign ('%'). This does not consume an argument.\n * Or generate unique describe titles by injecting properties of test suite object with $variable:\n * - To inject nested object values use a keyPath i.e. $variable.path.to.value (only works for \"own\" properties)\n * - You can use $# to inject the index of the test suite\n * - You cannot use $variable with the printf formatting except for %%\n * - fn: Function - The describe callback to be run, this is the function that will receive the parameters in each row as function arguments.\n * - timeout (optional): Number - Time in milliseconds to wait for each row before aborting. Default is 5 seconds.\n *\n * @example\n * ```ts\n * describe.each`\n * a | b | expected\n * ${1} | ${1} | ${2}\n * ${1} | ${2} | ${3}\n * ${2} | ${2} | ${4}\n * `('addition: $a + $b = $expected', ({a, b, expected}) => {\n * test('equals expected value', () => {\n * expect(a + b).toBe(expected);\n * });\n * });\n * ```\n *\n * @see DescribeCallbackType\n * @since 1.0.0\n */\n\n each<T extends ReadonlyArray<unknown>>(string: TemplateStringsArray, ...placeholders: T): DescribeCallbackType<Record<string, T[number]>>;\n\n /**\n * Creates parameterized test suites from arrays of test case values.\n *\n * @template T - A type extending Array<unknown> or [unknown] that contains the test case values\n *\n * @param cases - Arrays of values representing individual test cases\n *\n * @returns A callback function compatible with Jest's describe method that provides parameterized test data\n *\n * @throws TypeError - When the test cases have inconsistent formats or types\n *\n * @remarks\n * This method allows creating parameterized test suites from arrays of values.\n * Each array provided as a case will be passed to the describe callback as separate arguments.\n *\n * The returned function accepts the following parameters:\n * - name: String - The title of the describe block.\n * Generate unique describe titles by positionally injecting parameters with printf formatting:\n * %p - pretty-format.\n * %s - String.\n * %d - Number.\n * %i - Integer.\n * %f - Floating point value.\n * %j - JSON.\n * %o - Object.\n * %# - Index of the test suite.\n * %% - single percent sign ('%'). This does not consume an argument.\n * Or generate unique describe titles by injecting properties of test suite object with $variable:\n * - To inject nested object values use a keyPath i.e. $variable.path.to.value (only works for \"own\" properties)\n * - You can use $# to inject the index of the test suite\n * - You cannot use $variable with the printf formatting except for %%\n * - fn: Function - The describe callback to be run, this is the function that will receive the parameters in each row as function arguments.\n * - timeout (optional): Number - Time in milliseconds to wait for each row before aborting. Default is 5 seconds.\n *\n * @example\n * ```ts\n * describe.each(\n * [1, 1, 2],\n * [1, 2, 3],\n * [2, 2, 4]\n * )('addition: %d + %d = %d', (a, b, expected) => {\n * test('equals expected value', () => {\n * expect(a + b).toBe(expected);\n * });\n * });\n * ```\n *\n * @see DescribeCallbackType\n * @since 1.0.0\n */\n\n each<T extends Array<unknown> | [ unknown ]>(...cases: T[]): DescribeCallbackType<T>; // array\n\n /**\n * Creates parameterized test suites from individual test case values.\n *\n * @template T - The type of test case values (objects or primitives)\n *\n * @param args - Individual test case values to be used in the test suites\n *\n * @returns A callback function compatible with Jest's describe method that provides parameterized test data\n *\n * @throws TypeError - When the test cases have incompatible types\n *\n * @remarks\n * This method allows creating parameterized test suites from individual values.\n * Each value provided as an argument will be passed to the describe callback.\n * This overload is particularly useful for objects and primitive values.\n *\n * The returned function accepts the following parameters:\n * - name: String - The title of the describe block.\n * Generate unique describe titles by positionally injecting parameters with printf formatting:\n * %p - pretty-format.\n * %s - String.\n * %d - Number.\n * %i - Integer.\n * %f - Floating point value.\n * %j - JSON.\n * %o - Object.\n * %# - Index of the test suite.\n * %% - single percent sign ('%'). This does not consume an argument.\n * Or generate unique describe titles by injecting properties of test suite object with $variable:\n * - To inject nested object values use a keyPath i.e. $variable.path.to.value (only works for \"own\" properties)\n * - You can use $# to inject the index of the test suite\n * - You cannot use $variable with the printf formatting except for %%\n * - fn: Function - The describe callback to be run, this is the function that will receive the test case value as an argument.\n * - timeout (optional): Number - Time in milliseconds to wait for each test case before aborting. Default is 5 seconds.\n *\n * @example\n * ```ts\n * describe.each(\n * { a: 1, b: 1, expected: 2 },\n * { a: 1, b: 2, expected: 3 },\n * { a: 2, b: 2, expected: 4 }\n * )('addition: $a + $b = $expected', ({ a, b, expected }) => {\n * test('equals expected value', () => {\n * expect(a + b).toBe(expected);\n * });\n * });\n * ```\n *\n * @see DescribeCallbackType\n * @since 1.0.0\n */\n\n each<T>(...args: readonly T[]): DescribeCallbackType<T>; // object, and primitives\n\n /**\n * Creates parameterized test suites from individual objects or primitive values.\n *\n * @template T - The type of test case values\n *\n * @param args - Individual objects or primitive values to be used as test cases\n *\n * @returns A callback function compatible with Jest's describe method\n *\n * @remarks\n * This method creates parameterized test suites where each argument represents a complete test case.\n * Useful for testing with objects or primitive values that each represent a single test scenario.\n *\n * The returned function accepts the following parameters:\n * - name: String - The title of the describe block.\n * Generate unique describe titles by positionally injecting parameters with printf formatting:\n * %p - pretty-format.\n * %s - String.\n * %d - Number.\n * %i - Integer.\n * %f - Floating point value.\n * %j - JSON.\n * %o - Object.\n * %# - Index of the test suite.\n * %% - single percent sign ('%'). This does not consume an argument.\n * Or generate unique describe titles by injecting properties of test suite object with $variable:\n * - To inject nested object values use a keyPath i.e. $variable.path.to.value (only works for \"own\" properties)\n * - You can use $# to inject the index of the test suite\n * - You cannot use $variable with the printf formatting except for %%\n * - fn: Function - The describe callback to be run, this is the function that will receive the test case value as an argument.\n * - timeout (optional): Number - Time in milliseconds to wait for each test case before aborting. Default is 5 seconds.\n *\n * @example\n * ```ts\n * describe.each(\n * { input: 'hello', expected: 'HELLO' },\n * { input: 'world', expected: 'WORLD' }\n * )('toUpperCase($input) \u2192 $expected', (testCase) => {\n * test('converts correctly', () => {\n * expect(testCase.input.toUpperCase()).toBe(testCase.expected);\n * });\n * });\n * ```\n *\n * @see DescribeCallbackType\n * @since 1.0.0\n */\n\n each<T extends Array<unknown>>(...args: T): DescribeCallbackType<T[number]>; // primitives\n\n /**\n * Creates parameterized test suites by delegating to the external 'each' function.\n *\n * @param args - Test case values to be used in the parameterized test suites\n *\n * @returns A callback function compatible with Jest's describe method\n *\n * @remarks\n * This method serves as a bridge between the describe context and the external 'each' utility.\n * It binds the current context's 'invoke' method and passes it along with the test cases\n * to the external 'each' function, which handles the creation of parameterized test suites.\n *\n * The returned function has the same behavior as the one returned by the external 'each' function,\n * but ensures that tests are executed within the proper describe context.\n *\n * The returned function accepts the following parameters:\n * - name: String - The title of the describe block, which can include parameter placeholders\n * - fn: Function - The describe callback function that will receive the test case values\n * - timeout (optional): Number - Time in milliseconds before test timeout\n *\n * @example\n * ```ts\n * // Internal implementation used when calling describe.each\n * // Users don't directly call this method, but rather use:\n * describe.each([1, 2, 3])('test with %d', (num) => {\n * test('works with ' + num, () => {\n * expect(num).toBeDefined();\n * });\n * });\n * ```\n *\n * @internal\n * @since 1.0.0\n */\n\n each(...args: Array<unknown>): DescribeCallbackType<unknown> {\n return each(this.invoke.bind(this), ...args);\n }\n\n /**\n * Executes a describe block with the given description and function.\n *\n * @param description - The title of the describe block\n * @param block - The function containing the tests to be run within this describe block\n * @param args - Optional array of arguments to pass to the block function\n *\n * @throws Error - When attempting to nest a describe block inside a test\n *\n * @remarks\n * This method is the core implementation for creating test suites in the testing framework.\n * It registers a describe block with the suite state manager and applies any options\n * that were set on the describe object before this method was called.\n *\n * This method is primarily called internally by the testing framework and\n * typically not meant to be called directly by users.\n *\n * @example\n * ```ts\n * // Internal implementation example - not for direct use\n * const describeObj = new Describe();\n * describeObj.invoke('My test suite', () => {\n * // Test implementations\n * });\n * ```\n *\n * @internal\n * @since 1.0.0\n */\n\n invoke(description: string, block: FunctionType, args: Array<unknown> = []): void {\n const suiteState = inject(SuiteState);\n const runningTest = suiteState.test;\n\n if (runningTest) {\n throw new Error(\n `Cannot nest a describe inside a test '${ description }' in '${ runningTest.description }'`\n );\n }\n\n suiteState.addDescribe(description, block, this.options, args);\n // Reset options after use\n this.options = {};\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FnMockInterface } from '@shared/mock/interfaces/fn-mock.interface';\nimport type { ConstructorLikeType, FunctionLikeType } from '@remotex-labs/xjet-expect';\n\n/**\n * Imports\n */\n\nimport { MockState } from '@shared/states/mock.state';\nimport { ExecutionError } from '@shared/errors/execution.error';\n\n/**\n * Retrieves the parent object of the specified function if it exists within the global context.\n *\n * @template FunctionLikeType - The type representing the input function.\n *\n * @param fn - The function whose parent object is to be retrieved.\n * @returns The parent object containing the function, or `undefined` if no such object is found.\n *\n * @remarks\n * This method searches for the parent object of a given function within the global context\n * by checking if the function name exists as a key of an object in the global scope.\n * If the function exists directly in the global scope, the global object itself is returned.\n *\n * @since 1.0.0\n */\n\nexport function getParentObject(fn: FunctionLikeType): Record<string, unknown> | undefined {\n if (fn.name in globalThis) return globalThis;\n\n const name = fn.name;\n const globalElements: typeof globalThis = globalThis;\n\n for (const key of Object.keys(globalThis) as unknown as (keyof typeof globalThis)[]) {\n const val = <Record<string, unknown>> globalElements[key];\n if(typeof val !== 'function' && typeof val !== 'object') continue;\n if (val && name in val) {\n return globalElements[key];\n }\n }\n\n return undefined;\n}\n\n/**\n * Creates a mock function interface with the specified implementation and optional restore function.\n *\n * @template ReturnType - The return type of the mocked function.\n * @template Context - The context type that the mocked function binds to.\n * @template Args - The argument type of the mocked function. Defaults to an array of unknown values.\n *\n * @param implementation - An optional implementation of the mocked function.\n * @param restore - An optional restore function used to reset the mock.\n * @returns A mocked function interface with the specified behaviors.\n *\n * @remarks\n * This function creates a mock function handler, typically used in testing scenarios.\n * You can provide an implementation for the mock behavior or specify a restore\n * handler for resetting the mock's state.\n *\n * @example\n * ```ts\n * // Creating a mock with a custom implementation\n * const mock = xJet.fn((x: number) => x * 2);\n * console.log(mock(5)); // 10\n *\n * // Creating a mock with a restore function\n * const mockWithRestore = xJet.fnImplementation(undefined, () => { console.log('Restored!'); });\n * mockWithRestore.restore(); // \"Restored!\"\n * ```\n *\n * @see MockState\n *\n * @since 1.0.0\n */\n\nexport function fnImplementation<ReturnType, Args extends Array<unknown>, Context>(\n implementation?: FunctionLikeType<ReturnType, Args, Context>,\n restore?: FunctionLikeType<void>\n): FnMockInterface<ReturnType, Args, Context> {\n const instance = new MockState(implementation, restore, 'xJet.fn()');\n\n return <FnMockInterface<ReturnType, Args, Context>> instance;\n}\n\n/**\n * Creates a mock instance for the given method or constructor.\n *\n * @template Method - The type of the method being mocked.\n * @template Context - The `this` context type of the method.\n * @template Args - The types of the arguments accepted by the method.\n *\n * @param method - The method or constructor to mock. This can either be a function-like type or a\n * constructor-like type.\n * @returns A `MockState` instance associated with the provided method, allowing for capturing\n * interactions and controlling behavior during testing.\n *\n * @remarks\n * This method identifies whether the provided method is a function or constructor and creates\n * a suitable mock state. If the method is already mocked, the existing mock state is returned.\n * Throws an error if the method does not belong to an object or if it has an invalid type.\n *\n * @example\n * ```ts\n * // Mocking a regular method\n * function greet(name: string) {\n * return `Hello, ${ name }`;\n * }\n *\n * const greetMock = xJet.mock(greet);\n * greetMock.mockImplementation(() => 'Hi!');\n * console.log(greet('World')); // \"Hi!\"\n *\n * // Mocking a constructor\n * class Person {\n * constructor(public name: string) {}\n * }\n * const personMock = xJet.mock(Person);\n * personMock.mockImplementation((name: string) => ({ name: `${name} (mocked)` }));\n * const person = new Person('Alice');\n * console.log(person.name); // \"Alice (mocked)\"\n *\n * // Restoring the original method\n * greetMock.mockRestore();\n * console.log(greet('World')); // \"Hello, World\"\n * ```\n *\n * @since 1.0.0\n */\n\nexport function mockImplementation<Method, Args extends Array<unknown>, Context>(\n method: FunctionLikeType<Method, Args, Context> | ConstructorLikeType<Method, Args>\n): MockState<Method, Args, Context> {\n if ((method as unknown as MockState).xJetMock)\n return <MockState<Method, Args, Context>> <unknown> method;\n\n let parentObject = getParentObject(<FunctionLikeType> method);\n if (!parentObject) {\n throw new ExecutionError('Method is not part of an object');\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(parentObject, method.name);\n if (descriptor?.get && !descriptor.configurable) {\n if ('default' in parentObject && (<Record<string, unknown>> parentObject.default)[method.name] === method) {\n parentObject = <typeof parentObject> parentObject.default;\n }\n }\n\n // todo bind to class constructor\n const originalMethod = parentObject[method.name];\n if (method.prototype && !Object.getOwnPropertyDescriptor(method, 'prototype')?.writable) {\n const mock = new MockState<Method, Args, Context>(\n (...args: Args) => new (method as ConstructorLikeType<Method, Args>)(...args),\n () => {\n parentObject[method.name] = originalMethod;\n }\n );\n\n parentObject[method.name] = mock;\n MockState.mocks.push(<MockState> <unknown> mock);\n\n return parentObject[method.name] as MockState<Method, Args, Context>;\n }\n\n if (typeof method === 'function') {\n const mock = new MockState(<FunctionLikeType> method, () => {\n parentObject[method.name] = originalMethod;\n });\n\n parentObject[method.name] = mock;\n MockState.mocks.push(<MockState> <unknown> mock);\n\n return parentObject[method.name] as MockState<Method, Args, Context>;\n }\n\n throw new ExecutionError('Invalid method type');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ContextType, FunctionType } from '@remotex-labs/xjet-expect';\nimport type { CallbackHandlerType } from '@shared/models/interfaces/hook-model.interface';\n\n\n/**\n * Imports\n */\n\nimport { isPromise } from '@remotex-labs/xjet-expect';\nimport { withTimeout } from '@components/timeout.component';\n\n/**\n * Represents a model for managing and executing hook functions with a specified timeout.\n * Provides functionality for associating invocation locations and handling errors during execution.\n *\n * @remarks\n * This class ensures that hooks are executed with proper timeout enforcement\n * and supports both synchronous and asynchronous hook functions.\n * It throws an error if an asynchronous hook\n * incorrectly uses a \"done\" callback or if it fails to complete execution within the specified timeout.\n *\n * @since 1.0.0\n */\n\nexport class HookModel {\n /**\n * Represents the current location of an invocation within the application or a fallback to undefined.\n *\n * @remarks\n * This variable is designed\n * to hold the interface representing the invocation's location for tracking.\n * If no invocation location is available, it defaults to undefined.\n *\n * @since 1.0.0\n */\n\n private location: string = '';\n\n /**\n * Constructs an instance of the class.\n *\n * @param hookFunction - The callback function that will be executed based on specific conditions.\n * @param timeout - The time in milliseconds before the callback function is triggered.\n * @throws Will throw an error if the provided timeout value is negative or invalid.\n *\n * @remarks This constructor sets up the necessary callback function and timeout configuration for the instance.\n *\n * @since 1.0.0\n */\n\n constructor(\n private readonly hookFunction: CallbackHandlerType, private readonly timeout: number\n ) {}\n\n /**\n * Sets the location of the invocation based on the provided location object.\n *\n * @param location - An object implementing the `InvocationLocationType` or `undefined`\n * to reset the location.\n *\n * @remarks\n * This method assigns a new location value to the current location of the invocation.\n * Passing `undefined` will clear the current location.\n *\n * @since 1.0.0\n */\n\n setLocation(location: string): void {\n this.location = location;\n }\n\n /**\n * Executes a hook function with a timeout mechanism.\n *\n * @param context - The context object passed to the hook function, containing execution-specific information.\n * @return A promise that resolves when the hook function completes its execution successfully.\n *\n * @throws TimeoutError - If the hook function does not call `done()` within the specified timeout duration.\n *\n * @remarks This method concurrently runs the hook function and a timeout check, ensuring that execution does not\n * exceed the predefined timeout.\n * If the timeout is reached without the hook function completing, an ` TimeoutError ` is thrown.\n *\n * @since 1.0.0\n */\n\n async run(context: ContextType<unknown>): Promise<void> {\n return withTimeout<void>(\n this.executeHook(this.hookFunction, context),\n this.timeout,\n 'hook while waiting for \\'done()\\' to be called.',\n this.location\n );\n }\n\n /**\n * Executes a given hook function, handling both synchronous and asynchronous hooks,\n * with or without a callback mechanism.\n *\n * @param hook - The function representing the hook to be executed.\n * It Can be a synchronous or asynchronous function.\n * @param context - An object to be used as the `this` context\n * when invoking the hook function.\n\n * @remarks This method ensures correct execution and error handling\n * for both callback-based and promise-based hooks.\n *\n * @since 1.0.0\n */\n\n private async executeHook(hook: FunctionType, context: unknown): Promise<void> {\n if (isPromise(hook) && hook.length > 0) {\n throw new Error(`Async hook '${ hook.name }' should not use 'done' callback.`);\n }\n\n if (hook.length > 0) {\n return this.executeCallbackHook(hook, context);\n }\n\n return hook.call(context);\n }\n\n /**\n * Executes a callback-style hook by wrapping it in a Promise\n *\n * @param hook - The callback hook function to execute\n * @param context - Execution context to bind to the hook function\n * @returns A Promise that resolves when the hook completes or rejects when it fails\n *\n * @throws Error - When the hook callback is invoked with an error parameter\n *\n * @remarks This method converts traditional Node.js-style callback patterns (error-first callbacks)\n * into Promise-based async/await compatible functions. The hook function receives a done callback\n * as its argument and must call it to signal completion.\n *\n * @example\n * ```ts\n * const callbackHook = (done) => {\n * setTimeout(() => done(), 100);\n * };\n *\n * await executeCallbackHook(callbackHook, this);\n * ```\n *\n * @see isPromise\n * @since 1.0.0\n */\n\n private executeCallbackHook(hook: FunctionType, context: unknown): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n hook.call(context, (error?: string | { message: string }): void => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionType } from '@remotex-labs/xjet-expect';\n\n/**\n * Imports\n */\n\nimport { HookModel } from '@shared/models/hook.model';\nimport { SuiteState } from '@shared/states/suite.state';\nimport { inject } from '@symlinks/services/inject.service';\nimport { getTrimmedStackString } from '@components/location.component';\nimport { HookType } from '@shared/models/constants/hook.model.constants';\n\n/**\n * Default timeout\n */\n\nconst DEFAULT_TIMEOUT = globalThis.__XJET?.runtime.timeout ?? 5000;\n\n/**\n * Creates and registers a hook with the current test suite\n *\n * @param hookType - Type of hook to register\n * @param callback - Function to execute for this hook\n * @param location - The precise source code location where the error occurred\n * @param timeout - Maximum execution time in milliseconds\n * @returns void\n *\n * @example\n * ```ts\n * createHook(HookType.BEFORE_EACH, () => {\n * // Setup code to run before each test\n * resetTestDatabase();\n * }, 10000);\n * ```\n *\n * @see HookType\n * @see HookModel\n * @see SuiteState\n *\n * @since 1.0.0\n */\n\nexport function createHook(hookType: HookType, callback: FunctionType, location: string, timeout: number = DEFAULT_TIMEOUT): void {\n const hook = new HookModel(callback, timeout);\n hook.setLocation(location);\n inject(SuiteState).describe.addHook(hookType, hook);\n}\n\n/**\n * Registers an after-all hook to be executed once after all tests in a suite have completed\n *\n * @param callback - Function to execute after all tests in the suite\n * @param timeout - Maximum execution time in milliseconds\n * @returns void\n *\n * @throws Error - If called outside a test suite context\n *\n * @remarks\n * This function is a wrapper around the createHook function, specifically for creating AFTER_ALL hooks.\n * After-all hooks are useful for cleanup operations that should occur once after all tests complete.\n *\n * @example\n * ```ts\n * afterAllDirective(() => {\n * // Teardown code to run after all tests\n * disconnectFromDatabase();\n * }, 10000);\n * ```\n *\n * @see createHook\n * @see HookType.AFTER_ALL\n *\n * @since 1.0.0\n */\n\nexport function afterAllDirective(callback: FunctionType, timeout?: number): void {\n createHook(HookType.AFTER_ALL, callback, getTrimmedStackString(), timeout);\n}\n\n/**\n * Registers a before-all hook to be executed once before any tests in a suite run\n *\n * @param callback - Function to execute before any tests in the suite\n * @param timeout - Maximum execution time in milliseconds\n * @returns void\n *\n * @throws Error - If called outside a test suite context\n *\n * @remarks\n * This function is a wrapper around the createHook function, specifically for creating BEFORE_ALL hooks.\n * Before-all hooks are useful for setup operations that should occur once before any tests run.\n *\n * @default timeout 5000\n *\n * @example\n * ```ts\n * beforeAllDirective(() => {\n * // Setup code to run before any tests\n * initializeTestDatabase();\n * }, 10000);\n * ```\n *\n * @see createHook\n * @see HookType.BEFORE_ALL\n *\n * @since 1.0.0\n */\n\nexport function beforeAllDirective(callback: FunctionType, timeout?: number): void {\n createHook(HookType.BEFORE_ALL, callback, getTrimmedStackString(), timeout);\n}\n\n/**\n * Registers an after-each hook to be executed after each test in a suite completes\n *\n * @param callback - Function to execute after each test\n * @param timeout - Maximum execution time in milliseconds\n * @returns void\n *\n * @throws Error - If called outside a test suite context\n *\n * @remarks\n * This function is a wrapper around the createHook function, specifically for creating AFTER_EACH hooks.\n * After-each hooks run after each test case and are useful for cleanup operations that should occur\n * after every individual test.\n *\n * @default timeout 5000\n *\n * @example\n * ```ts\n * afterEachDirective(() => {\n * // Cleanup code to run after each test\n * resetTestState();\n * }, 8000);\n * ```\n *\n * @see createHook\n * @see HookType.AFTER_EACH\n *\n * @since 1.0.0\n */\n\nexport function afterEachDirective(callback: FunctionType, timeout?: number): void {\n createHook(HookType.AFTER_EACH, callback, getTrimmedStackString(), timeout);\n}\n\n/**\n * Registers a before-each hook to be executed before each test in a suite runs\n *\n * @param callback - Function to execute before each test\n * @param timeout - Maximum execution time in milliseconds\n *\n * @returns void\n *\n * @throws Error - If called outside a test suite context\n *\n * @remarks\n * This function is a wrapper around the createHook function, specifically for creating BEFORE_EACH hooks.\n * Before-each hooks run before each test case and are useful for setup operations that should occur\n * before every individual test.\n *\n * @default timeout 5000\n *\n * @example\n * ```ts\n * beforeEachDirective(() => {\n * // Setup code to run before each test\n * prepareTestEnvironment();\n * }, 8000);\n * ```\n *\n * @see createHook\n * @see HookType.BEFORE_EACH\n *\n * @since 1.0.0\n */\n\nexport function beforeEachDirective(callback: FunctionType, timeout?: number): void {\n createHook(HookType.BEFORE_EACH, callback, getTrimmedStackString(), timeout); // Fixed a bug here - was using AFTER_ALL\n}\n", "/**\n * Imports\n */\n\nimport { xExpect } from '@remotex-labs/xjet-expect';\nimport { MockState } from '@shared/states/mock.state';\nimport { SuiteState } from '@shared/states/suite.state';\nimport { inject } from '@symlinks/services/inject.service';\nimport * as logging from '@shared/components/log.component';\nimport { spyOnImplementation } from '@shared/mock/spy.mock';\nimport { TestDirective } from '@shared/directives/test.directive';\nimport { DescribeDirective } from '@shared/directives/describe.directive';\nimport { fnImplementation, mockImplementation } from '@shared/mock/fn.mock';\nimport { afterAllDirective, afterEachDirective } from '@shared/directives/hook.directive';\nimport { beforeAllDirective, beforeEachDirective } from '@shared/directives/hook.directive';\n\n/**\n * Clears the specified mock method on all registered mocks\n *\n * @param method - The method name to clear on all mock instances\n *\n * @throws TypeError - When called with an invalid method name\n *\n * @remarks\n * This utility function iterates through all mocks registered in the MockState\n * and calls the specified method on each one, effectively performing a batch operation\n * across all mock instances.\n *\n * @example\n * ```ts\n * // Clear all recorded calls on all mocks\n * clearMocks('resetHistory');\n *\n * // Reset behavior on all mocks\n * clearMocks('resetBehavior');\n * ```\n *\n * @see MockState\n *\n * @since 1.0.0\n */\n\nfunction clearMocks(method: keyof MockState): void {\n const mock = [ ...MockState.mocks ];\n mock.map((mock) => {\n mock[method]();\n });\n}\n\n/**\n * Set global\n */\n\nconst setupGlobals = (): void => {\n const globals = globalThis as { [key: string]: unknown; };\n\n globals.xJet = {\n fn: fnImplementation,\n mock: mockImplementation,\n spyOn: spyOnImplementation,\n log: logging.log,\n info: logging.info,\n warn: logging.warn,\n error: logging.error,\n debug: logging.debug,\n clearAllMocks: (): void => clearMocks('mockClear'),\n resetAllMocks: (): void => clearMocks('mockReset'),\n restoreAllMocks: (): void => clearMocks('mockRestore')\n };\n\n globals.expect = xExpect;\n globals.state = inject(SuiteState);\n globals.it = TestDirective.getInstance();\n globals.test = TestDirective.getInstance();\n globals.describe = DescribeDirective.getInstance();\n globals.afterAll = afterAllDirective;\n globals.beforeAll = beforeAll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,CAC9E,CAFgBK,EAAAG,GAAA,sBAkCT,SAASC,GAAmBX,EAAwBE,EAAwB,CAC/EJ,eAAgCE,EAAUS,EAAsB,EAAGP,CAAO,CAC9E,CAFgBK,EAAAI,GAAA,sBAmCT,SAASC,GAAoBZ,EAAwBE,EAAwB,CAChFJ,gBAAiCE,EAAUS,EAAsB,EAAGP,CAAO,CAC/E,CAFgBK,EAAAK,GAAA,uBC3IhB,SAASC,GAAWC,EAA+B,CAClC,CAAE,GAAGC,EAAU,KAAM,EAC7B,IAAKC,GAAS,CACfA,EAAKF,CAAM,EAAE,CACjB,CAAC,CACL,CALSG,EAAAJ,GAAA,cAWT,IAAMK,GAAeD,EAAA,IAAY,CAC7B,IAAME,EAAU,WAEhBA,EAAQ,KAAO,CACX,GAAIC,GACJ,KAAMC,GACN,MAAOC,GACP,IAAaC,GACb,KAAcC,GACd,KAAcC,GACd,MAAeC,GACf,MAAeC,GACf,cAAeV,EAAA,IAAYJ,GAAW,WAAW,EAAlC,iBACf,cAAeI,EAAA,IAAYJ,GAAW,WAAW,EAAlC,iBACf,gBAAiBI,EAAA,IAAYJ,GAAW,aAAa,EAApC,kBACrB,EAEAM,EAAQ,OAASS,GACjBT,EAAQ,MAAQU,EAAOC,CAAU,EACjCX,EAAQ,GAAKY,GAAc,YAAY,EACvCZ,EAAQ,KAAOY,GAAc,YAAY,EACzCZ,EAAQ,SAAWa,GAAkB,YAAY,EACjDb,EAAQ,SAAWc,GACnBd,EAAQ,UAAYe,GACpBf,EAAQ,UAAYgB,GACpBhB,EAAQ,WAAaiB,EACzB,EA1BqB,gBA4BrBlB,GAAa",
|
|
7
|
-
"names": ["ansiModifiers", "ansiForegroundColors", "ansiBackgroundColors", "styles", "ESC", "ESC_END", "wrapWithAnsi", "codes", "text", "codesLength", "endCodes", "startCodes", "i", "rgbCode", "type", "r", "g", "b", "code", "reset", "hexToRgb", "hex", "cleanHex", "createXtermChain", "formatter", "__name", "args", "strings", "values", "combined", "acc", "str", "colorHandlers", "target", "prop", "xterm", "isA", "constructor", "value", "__name", "hasKey", "obj", "key", "isAsymmetric", "asymmetricMatch", "a", "b", "asymmetricA", "asymmetricB", "deepEquals", "strictCheck", "val", "i", "equals", "aKeys", "bKeys", "asymmetricResult", "serializesError", "error", "json", "isPromise", "candidate", "INDENT", "serializePrimitive", "element", "serializeMapKey", "appendLines", "source", "target", "isLast", "indent", "last", "serializeMap", "map", "lines", "seen", "entries", "keyStr", "subLines", "serializeValue", "serializeArray", "arr", "item", "serializeSet", "set", "serializeBuffer", "values", "comma", "serializeTypedArray", "name", "serializeObject", "primitive", "stringLines", "line", "serializeError", "serialize", "DiffTypes", "countCommonForward", "count", "countCommonBackward", "backtrackFlat", "trace", "offset", "dFinal", "x", "y", "result", "d", "vPrev", "k", "prevK", "kMinus", "kPlus", "prevKIndex", "prevX", "prevY", "findMiddleSnake", "n", "m", "max", "v", "vCopy", "kIndex", "diffSequence", "prefixLen", "isFullyEqual", "suffixLen", "createDiff", "aLength", "bLength", "isMatch", "foundSubsequence", "context", "diffStringsRaw", "aIndex", "bIndex", "pendingInsert", "pendingDelete", "diffs", "pushDiff", "type", "text", "iA", "iB", "nCommon", "aCommon", "bCommon", "diffLinesRaw", "hasCommaA", "hasCommaB", "cleanupSemantic", "delBuf", "insBuf", "flushBuffers", "prevType", "nextType", "isEdit", "t", "ch", "DIM", "xterm", "MARK", "RECEIVED", "EXPECTED", "CYAN", "INVERSE", "TITLE", "getType", "normalizeStrings", "clean", "resultA", "resultB", "normalizeArrays", "aResult", "bResult", "len", "normalizeAsymmetric", "normalizeObjects", "keys", "aType", "bType", "diffStrings", "aLines", "bLines", "lineA", "lineB", "expectedLine", "receivedLine", "diffArgs", "diffComponent", "aNormalize", "bNormalize", "xJetBaseError", "message", "composeStatement", "options", "comment", "assertionChain", "expectedLabels", "receivedLabeled", "parts", "xJetTypeError", "xJetExpectError", "ensureType", "types", "label", "ensureNotNullish", "serializeOneLine", "handleFailure", "pass", "info", "assertion", "handleDiffFailure", "handleComparisonFailure", "operator", "space", "getThrown", "err", "e", "hasMessage", "isError", "buildInfo", "expectedLabel", "expectedValue", "thrown", "asymmetric", "toThrowExpectedClass", "expected", "handleNot", "handleInfo", "toThrowExpectedString", "toThrowExpectedRegExp", "toThrowExpectedAsymmetric", "toThrowExpectedObject", "toThrow", "toHaveLength", "length", "received", "toMatch", "ensurePositiveNumber", "handleNumericComparison", "toBeCloseTo", "precision", "actual", "receivedDifference", "expectedDifference", "expectedDifferenceStr", "not", "notLabel", "details", "toBeGreaterThan", "toBeGreaterThanOrEqual", "toBeLessThan", "toBeLessThanOrEqual", "ensureMock", "serializeCallArgs", "args", "arg", "serializeList", "items", "symbol", "sliceArgs", "maxLines", "start", "highlightIndex", "total", "end", "width", "symbolPad", "num", "prefix", "diff", "serializeHighlightedCalls", "calls", "highlights", "results", "idx", "serializeCallList", "returns", "serializeReturnList", "toHaveBeenCalled", "toHaveBeenCalledTimes", "toHaveBeenCalledWith", "indices", "call", "index", "toHaveBeenLastCalledWith", "callIndex", "toHaveBeenNthCalledWith", "nthCall", "toHaveReturned", "resultsCount", "toHaveReturnedTimes", "toHaveLastReturnedWith", "toHaveNthReturnedWith", "toBe", "note", "toEqual", "toBeNull", "toBeUndefined", "toBeNaN", "toBeTruthy", "toBeFalsy", "toBeDefined", "toHaveProperty", "path", "current", "pathFound", "pathArray", "segment", "toBeInstanceOf", "instance", "toContain", "receivedType", "toContainEqual", "toMatchObject", "Matchers", "AbstractPattern", "isInverse", "AnyPattern", "_AnyPattern", "ArrayOfPattern", "_ArrayOfPattern", "allMatch", "matcher", "CloseToPattern", "_CloseToPattern", "inverse", "precisionLabel", "sample", "AnythingPattern", "_AnythingPattern", "StringMatchingPattern", "_StringMatchingPattern", "expectedType", "ArrayContainingPattern", "_ArrayContainingPattern", "allContained", "expItem", "recItem", "ObjectContainingPattern", "_ObjectContainingPattern", "StringContainingPattern", "_StringContainingPattern", "Patterns", "xJetPromiseError", "MatcherService", "isResolved", "valueOrPromise", "kind", "receivedValue", "proto", "matcherFn", "coreExpect", "rest", "xExpect", "DEFAULT_MOCK_NAME", "MockState", "_MockState", "__name", "implementation", "restore", "name", "index", "fn", "value", "thisArg", "args", "thisContext", "impl", "argsArray", "result", "error", "target", "argumentsList", "argArray", "newTarget", "isClassInstance", "SINGLETONS", "INJECTABLES", "Injectable", "options", "target", "__name", "inject", "token", "args", "metadata", "instance", "getBufferMethod", "buffer", "operation", "type", "methodName", "method", "readMethod", "writeMethod", "splitBufferWithGap", "splitPosition", "skipBytes", "beforeSplit", "afterPosition", "readSingleStruct", "arrayOffset", "position", "absolutePosition", "offset", "readStructArray", "result", "arraySize", "size", "readStruct", "writeSingleStruct", "value", "StructBuffer", "start", "end", "writeStructArray", "values", "elementValue", "writeStruct", "PRIMITIVE_TYPE_SIZES", "parsePrimitiveDescriptor", "field", "pattern", "match", "readSinglePrimitive", "readPrimitiveArray", "readPrimitive", "writeSinglePrimitive", "isBigIntType", "writePrimitiveArray", "writePrimitive", "maskCache", "isSignedType", "getBitMask", "mask", "processValueForBitfield", "descriptor", "validateBitFieldBounds", "isSigned", "bitSize", "maxBitValue", "minBitValue", "validateBitfieldParameters", "extractBitfieldValue", "rawValue", "bitPosition", "extractedValue", "composeBitfieldValue", "processedValue", "shiftedMask", "parseBitfieldDescriptor", "bitSizeStr", "typeSize", "isBigEndian", "readBitfield", "endianMethod", "writeBitfield", "bitFieldValue", "STRING_PRIMITIVE_LIST", "parseStringDescriptor", "readSingleString", "encoding", "lengthType", "stringLength", "dataOffset", "endPos", "maxLength", "readStringArray", "readString", "writeSingleString", "stringBuffer", "nullTerminatedString", "writeStringArray", "writeString", "Struct", "_Struct", "__name", "schema", "getDynamicOffset", "context", "name", "data", "kind", "positionedDescriptor", "primitiveSize", "fieldNotation", "prefix", "accumulator", "fieldName", "sizedField", "bitsInField", "requestedBitSize", "totalSize", "invocationSchema", "g", "headerSchema", "logSchema", "errorSchema", "statusSchema", "eventsSchema", "PacketSchemas", "logSchema", "errorSchema", "statusSchema", "eventsSchema", "encodePacket", "kind", "data", "schema", "PacketSchemas", "header", "headerSchema", "__name", "encodeErrorSchema", "error", "suiteId", "runnerId", "header", "headerSchema", "dataBuffer", "errorSchema", "ae", "__name", "emitStatus", "type", "notification", "encodePacket", "__name", "emitEvent", "stringErrors", "error", "ae", "LogLevel", "DescribeModel", "description", "describeOptions", "__name", "child", "type", "hook", "hookArray", "test", "describe", "context", "afterAllErrorsEmpty", "beforeAllErrorsEmpty", "error", "parent", "skip", "emitStatus", "errors", "emitEvent", "testsToShuffle", "length", "i", "j", "ExecutionError", "__name", "message", "json", "key", "value", "_SuiteState_decorators", "_init", "Injectable", "_SuiteState", "__name", "DescribeModel", "part", "path", "filter", "offset", "re", "i", "test", "context", "time", "emitStatus", "ExecutionError", "e", "encodeErrorSchema", "description", "describeFn", "flags", "describeArgs", "options", "fullPath", "newDescribe", "previousDescribe", "__decoratorStart", "__decorateElement", "__runInitializers", "SuiteState", "PATTERNS", "JSEngines", "detectJSEngine", "stack", "normalizePath", "filePath", "createDefaultFrame", "source", "safeParseInt", "value", "parseV8StackLine", "line", "frame", "evalMatch", "globalMatch", "standardMatch", "parseSpiderMonkeyStackLine", "match", "parseJavaScriptCoreStackLine", "parseStackLine", "engine", "getStackWithoutMessage", "stackFramePattern", "lines", "i", "parseErrorStack", "error", "errorObj", "name", "message", "stackLines", "getInvocationLocation", "position", "stack", "E", "__name", "getTrimmedStackString", "err", "createLogHandler", "type", "args", "parent", "inject", "SuiteState", "context", "formattedArgs", "data", "v", "location", "getInvocationLocation", "encodePacket", "LogLevel", "__name", "log", "info", "warn", "error", "debug", "spyOnDescriptorProperty", "target", "key", "original", "originalDescriptor", "mockInstance", "MockState", "value", "__name", "spyOnImplementation", "ExecutionError", "method", "targetObject", "descriptor", "fn", "protoDesc", "args", "mockState", "VARIABLE_PATTERN", "prettyFormat", "value", "__name", "getValueByPath", "data", "path", "obj", "key", "resolveVariable", "token", "arrayIndex", "propertyPath", "resolvedValue", "interpolateVariables", "template", "variableToken", "printf", "description", "params", "index", "paramIndex", "match", "format", "parseTemplate", "templateString", "inputData", "headings", "h", "_", "rowIndex", "acc", "heading", "columnIndex", "__name", "each", "executor", "args", "cases", "name", "blockFn", "timeout", "testCase", "index", "parseArgs", "printf", "TimeoutError", "__name", "timeout", "at", "stack", "withTimeout", "task", "delay", "at", "stack", "taskPromise", "timeoutId", "timeoutPromise", "_", "reject", "TimeoutError", "__name", "FailingError", "_FailingError", "ExecutionError", "__name", "stack", "TestModel", "description", "testImplementation", "timeoutDuration", "testParameters", "testOptions", "__name", "location", "skip", "only", "parentTests", "context", "runLifecycleHooks", "isExclusiveMode", "inject", "SuiteState", "error", "withTimeout", "FailingError", "me", "resolve", "reject", "callbackFn", "allParameters", "todo", "emitStatus", "errors", "emitEvent", "TestDirective", "_TestDirective", "__name", "target", "_", "args", "description", "block", "timeout", "getTrimmedStackString", "each", "test", "runningTest", "inject", "SuiteState", "TestModel", "location", "DescribeDirective", "_DescribeDirective", "__name", "target", "thisArg", "args", "each", "description", "block", "suiteState", "inject", "SuiteState", "runningTest", "getParentObject", "fn", "name", "globalElements", "key", "val", "__name", "fnImplementation", "implementation", "restore", "MockState", "mockImplementation", "method", "parentObject", "ExecutionError", "descriptor", "originalMethod", "mock", "args", "HookModel", "hookFunction", "timeout", "__name", "location", "context", "withTimeout", "hook", "me", "resolve", "reject", "error", "DEFAULT_TIMEOUT", "createHook", "hookType", "callback", "location", "timeout", "hook", "HookModel", "inject", "SuiteState", "__name", "afterAllDirective", "getTrimmedStackString", "beforeAllDirective", "afterEachDirective", "beforeEachDirective", "clearMocks", "method", "MockState", "mock", "__name", "setupGlobals", "globals", "fnImplementation", "mockImplementation", "spyOnImplementation", "log", "info", "warn", "error", "debug", "At", "inject", "SuiteState", "TestDirective", "DescribeDirective", "afterAllDirective", "beforeAllDirective", "afterEachDirective", "beforeEachDirective"]
|
|
3
|
+
"sources": ["https://github.com/remotex-labs/xAnsi/src/services/ast.service.ts", "https://github.com/remotex-labs/xAnsi/src/components/ansi.component.ts", "https://github.com/remotex-labs/xAnsi/src/services/shadow.service.ts", "https://github.com/remotex-labs/xAnsi/src/providers/styles.provider.ts", "https://github.com/remotex-labs/xAnsi/src/components/xterm.component.ts", "https://github.com/remotex-labs/xjet-expect/src/components/object.component.ts", "https://github.com/remotex-labs/xjet-expect/src/components/promise.component.ts", "https://github.com/remotex-labs/xjet-expect/src/components/serialize.component.ts", "https://github.com/remotex-labs/xjet-expect/src/modules/diff/providers/string.provider.ts", "https://github.com/remotex-labs/xjet-expect/src/modules/diff/components/semantic.component.ts", "https://github.com/remotex-labs/xjet-expect/src/components/color.component.ts", "https://github.com/remotex-labs/xjet-expect/src/modules/diff/components/diff.component.ts", "https://github.com/remotex-labs/xjet-expect/src/errors/base.error.ts", "https://github.com/remotex-labs/xjet-expect/src/components/format.component.ts", "https://github.com/remotex-labs/xjet-expect/src/errors/type.error.ts", "https://github.com/remotex-labs/xjet-expect/src/errors/expect.error.ts", "https://github.com/remotex-labs/xjet-expect/src/handlers/matchers.handler.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/functions.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/string.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/handlers/number.handler.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/number.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/handlers/mock.handler.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/mock.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/equality.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers/object.matcher.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/matchers.provider.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/abstract.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/any.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/array-of.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/close-to.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/anything.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/string-matching.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/array-containing.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/object-containing.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns/string-containing.pattern.ts", "https://github.com/remotex-labs/xjet-expect/src/providers/patterns.provider.ts", "https://github.com/remotex-labs/xjet-expect/src/errors/promise.error.ts", "https://github.com/remotex-labs/xjet-expect/src/services/matcher.service.ts", "https://github.com/remotex-labs/xjet-expect/src/components/expect.component.ts", "../src/modules/shared/states/mock.state.ts", "../src/modules/symlinks/services/inject.service.ts", "https://github.com/remotex-lab/xStruct/src/components/buffer.component.ts", "https://github.com/remotex-lab/xStruct/src/components/struct.component.ts", "https://github.com/remotex-lab/xStruct/src/components/primitive.component.ts", "https://github.com/remotex-lab/xStruct/src/components/bitfield.component.ts", "https://github.com/remotex-lab/xStruct/src/components/string.component.ts", "https://github.com/remotex-lab/xStruct/src/services/struct.service.ts", "../src/modules/packets/schema/packet.schema.ts", "../src/modules/packets/constants/packet-schema.constants.ts", "../src/modules/packets/packets.module.ts", "../src/modules/shared/services/emit.service.ts", "../src/modules/messages/constants/report.constant.ts", "../src/modules/shared/models/describe.model.ts", "../src/modules/shared/errors/execution.error.ts", "../src/modules/shared/states/suite.state.ts", "https://github.com/remotex-lab/xmap/src/components/parser.component.ts", "../src/components/location.component.ts", "../src/modules/shared/components/log.component.ts", "../src/modules/shared/mock/spy.mock.ts", "../src/modules/shared/services/timer.service.ts", "../src/modules/shared/components/printf.component.ts", "../src/modules/shared/directives/each.directive.ts", "../src/errors/timeout.error.ts", "../src/components/timeout.component.ts", "../src/modules/shared/errors/failing.error.ts", "../src/modules/shared/models/test.model.ts", "../src/modules/shared/directives/test.directive.ts", "../src/modules/shared/directives/describe.directive.ts", "../src/modules/shared/mock/fn.mock.ts", "../src/modules/shared/models/hook.model.ts", "../src/modules/shared/directives/hook.directive.ts", "../src/modules/shared/shared.module.ts"],
|
|
4
|
+
"sourceRoot": "https://github.com/remotex-lab/xJet/tree/v1.1.0/",
|
|
5
|
+
"sourcesContent": ["/**\n * Maps ANSI styling codes to their corresponding reset codes\n *\n * @remarks\n * This mapping defines the relationship between ANSI control codes and the codes needed to reset each style.\n * The map is organized into text styling codes, foreground\n * colors, background colors, and reset codes. For reset codes, the value is null as they\n * don't require a specific reset code themselves.\n *\n * Text styles (1-9) map to their specific reset codes, while foreground colors (30-37)\n * all reset with code 39, and background colors (40-47) all reset with code 49.\n *\n * @example\n * ```ts\n * // Get the reset code for bold text (code 1)\n * const boldResetCode = ANSI_RESET_MAP['1']; // Returns '22'\n *\n * // Check if a code is a reset code itself\n * const isResetCode = ANSI_RESET_MAP['0'] === null; // Returns true\n * ```\n *\n * @since 1.0.0\n */\n\nconst ANSI_RESET_MAP: Record<string, string | null> = {\n // Text styles\n '1': '22',\n '2': '22',\n '3': '23',\n '4': '24',\n '5': '25',\n '7': '27',\n '8': '28',\n '9': '29',\n\n // Foreground colors\n '30': '39',\n '31': '39',\n '32': '39',\n '33': '39',\n '34': '39',\n '35': '39',\n '36': '39',\n '37': '39',\n '38': '39',\n '90': '39',\n '91': '39',\n '92': '39',\n '93': '39',\n '94': '39',\n '95': '39',\n '96': '39',\n '97': '39',\n\n // Background colors\n '40': '49',\n '41': '49',\n '42': '49',\n '43': '49',\n '44': '49',\n '45': '49',\n '46': '49',\n '47': '49',\n '48': '49',\n '100': '49',\n '101': '49',\n '102': '49',\n '103': '49',\n '104': '49',\n '105': '49',\n '106': '49',\n '107': '49',\n\n // Resets\n '0': null,\n '22': null,\n '23': null,\n '24': null,\n '25': null,\n '27': null,\n '28': null,\n '29': null,\n '39': null,\n '49': null\n};\n\n/**\n * Splits a string containing ANSI escape codes into individual characters,\n * preserving all active styling for each character.\n *\n * @param str - The ANSI-styled string to process.\n *\n * @returns An array of strings, where each element represents a single character\n * wrapped with its full active ANSI codes and corresponding reset codes.\n *\n * @remarks\n * This function handles ANSI escape sequences in a string and ensures that each\n * visible character retains the correct styling context.\n *\n * Behavior:\n * - Handles plain text characters and surrogate pairs correctly.\n * - Maintains multiple simultaneous ANSI styles.\n * - Resets styles when encountering `\\x1b[0m`.\n * - Supports one-time ANSI codes that affect only the next character.\n *\n * Implementation details:\n * - Tracks active ANSI codes in `prefix` and `suffix` arrays.\n * - Builds `currPrefixStr` and `currSuffixStr` for efficient string reconstruction.\n * - Uses `Array.from` to handle Unicode surrogate pairs.\n *\n * Example usage:\n * ```ts\n * const input = \"\\x1b[1m\\x1b[31mBold Red\\x1b[0m\";\n * const chars = splitWithAnsiContext(input);\n * // chars[0] = \"'\\x1B[1;31mB\\x1B[22;39m\"\n * // chars[1] = \"\\x1B[1;31mo\\x1B[22;39m\"\n * ```\n *\n * @since 1.0.0\n */\n\nexport function splitWithAnsiContext(str: string): Array<string> {\n if (!str) return [ '' ];\n\n const result: Array<string> = [];\n const prefix: Array<string> = [];\n const suffix: Array<string> = [];\n\n let oneTimePrefix = '';\n let currPrefixStr = '';\n let currSuffixStr = '';\n\n const ansiRe = /\\x1b\\[[0-9;]*m/g;\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = ansiRe.exec(str))) {\n const chunk = str.slice(lastIndex, match.index);\n\n // Use Array.from to handle surrogate pairs correctly\n for (const char of Array.from(chunk)) {\n result.push(oneTimePrefix + currPrefixStr + char + currSuffixStr);\n oneTimePrefix = '';\n }\n\n const token = match[0];\n const codeSeq = token.slice(2, -1);\n const semi = codeSeq.indexOf(';');\n const code = semi < 0 ? codeSeq : codeSeq.slice(0, semi);\n const resetCode = ANSI_RESET_MAP[code];\n\n if(code === '0') {\n prefix.length = 0;\n suffix.length = 0;\n currPrefixStr = '';\n currSuffixStr = '';\n oneTimePrefix += token;\n } else {\n if (resetCode && prefix[prefix.length - 1] !== codeSeq) {\n prefix.push(codeSeq);\n suffix.push(resetCode);\n currPrefixStr = `\\x1b[${ prefix.join(';') }m`;\n currSuffixStr = `\\x1b[${ suffix.join(';') }m`;\n } else if (suffix[suffix.length - 1] === codeSeq) {\n prefix.pop();\n suffix.pop();\n currPrefixStr = prefix.length ? `\\x1b[${ prefix.join(';') }m` : '';\n currSuffixStr = suffix.length ? `\\x1b[${ suffix.join(';') }m` : '';\n } else {\n oneTimePrefix += token;\n }\n }\n\n lastIndex = ansiRe.lastIndex;\n }\n\n const remaining = str.slice(lastIndex);\n for (const char of Array.from(remaining)) {\n result.push(oneTimePrefix + currPrefixStr + char + currSuffixStr);\n oneTimePrefix = '';\n }\n\n return result;\n}\n", "/**\n * Writes raw data directly to the standard output stream without any processing\n *\n * @param data - The string or Buffer to write to stdout\n *\n * @returns Nothing\n *\n * @example\n * ```ts\n * // Write an ANSI escape sequence followed by text\n * writeRaw('\\x1b[31mThis text is red\\x1b[0m');\n * ```\n *\n * @since 1.0.0\n */\n\nexport function writeRaw(data: string | Buffer): void {\n if(process.stdout.write)\n process.stdout.write(data);\n else\n console.log(data);\n}\n\n/**\n * Generates an ANSI escape sequence to move the terminal cursor to the specified position\n *\n * @param row - The row (line) number to move the cursor to (1-based index)\n * @param column - The column position to move the cursor to (1-based index)\n *\n * @returns ANSI escape sequence string that moves the cursor when written to the terminal\n *\n * @example\n * ```ts\n * // Move cursor to the beginning of line 5\n * const escapeSequence = moveCursor(5, 1);\n * process.stdout.write(escapeSequence);\n * ```\n *\n * @since 1.0.0\n */\n\nexport function moveCursor(row: number, column: number = 0): string {\n return `\\x1b[${ row };${ column }H`;\n}\n\n/**\n * Removes ANSI escape sequences from a string\n *\n * @param str - The input string containing ANSI escape sequences\n * @returns A plain string with all ANSI escape sequences removed\n *\n * @remarks\n * This function uses a regular expression to match and remove ANSI escape sequences\n * that control text styling in terminal output. These sequences typically start with\n * the escape character (x1b) followed by square brackets and control codes.\n *\n * The function is useful for:\n * - Getting accurate string length measurements without styling codes\n * - Preparing terminal output for non-terminal destinations (files, logs)\n * - Normalizing text for comparison or processing\n *\n * @example\n * ```ts\n * import { xterm, stripAnsi } from '@remotex-labs/xansi';\n *\n * const coloredText = xterm.red('Error!');\n * console.log(stripAnsi(coloredText)); // \"Error!\" (without ANSI codes)\n * ```\n *\n * @since 1.0.0\n */\n\nexport function stripAnsi(str: string): string {\n // Matches ANSI escape sequences like \\x1b[31m or \\x1b[0m etc.\n return str.replace(/\\x1b\\[[0-9;]*m/g, '');\n}\n\n/**\n * Contains ANSI escape sequence constants for terminal control operations\n *\n * @remarks\n * These ANSI escape codes are used to control terminal output behavior such as\n * cursor movement, screen clearing, and visibility. The enum provides a type-safe\n * way to access these constants without having to remember the raw escape sequences.\n *\n * Each constant is an escape sequence that can be written directly to the terminal\n * to achieve the described effect.\n *\n * @see ShadowRenderer\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code\n *\n * @since 1.0.0\n */\n\nexport const ANSI = {\n /**\n * Clears from the cursor to the end of the line\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n CLEAR_LINE: '\\x1B[K',\n\n /**\n * Moves the cursor to the \"home\" position (row 1, column 1).\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.2.0\n */\n\n CURSOR_HOME: '\\x1b[H',\n\n /**\n * Hides the cursor\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n HIDE_CURSOR: '\\x1B[?25l',\n\n /**\n * Shows the cursor\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n SHOW_CURSOR: '\\x1B[?25h',\n\n /**\n * Saves the current cursor position\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n SAVE_CURSOR: '\\x1B[s',\n\n /**\n * Restores the cursor to the previously saved position\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n RESTORE_CURSOR: '\\x1B[u',\n\n /**\n * Resets the terminal to its initial state (RIS - Reset to Initial State).\n * Clears screen, scrollback buffer, and most settings.\n * This is a \"hard reset\" escape code.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#Reset_(RIS)\n * @since 1.0.0\n */\n\n RESET_TERMINAL: '\\x1bc',\n\n /**\n * Clears the screen from the cursor position to the end of the screen.\n *\n * Equivalent to `ESC[J` or `ESC[0J`.\n * Leaves the scrollback buffer intact.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n CLEAR_SCREEN_DOWN: '\\x1b[0J',\n\n /**\n * Clears the screen from the cursor position to the beginning of the screen.\n *\n * Equivalent to `ESC[1J`.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n CLEAR_SCREEN_UP: '\\x1b[1J',\n\n /**\n * Clears the entire screen and moves the cursor to the home position (top-left).\n *\n * Equivalent to `ESC[2JESC[H`.\n * Does not clear the scrollback buffer.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n CLEAR_SCREEN: '\\x1b[2J\\x1b[H',\n\n /**\n * Clears the entire screen and deletes all lines saved in the scrollback buffer.\n *\n * Equivalent to `ESC[3JESC[H`.\n * Supported in xterm and many modern terminal emulators.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.0.0\n */\n\n CLEAR_SCREEN_FULL: '\\x1b[3J\\x1b[H',\n\n /**\n * Moves the cursor to the beginning of the current line (column 1).\n *\n * @remarks\n * Unlike `\\r` (carriage return), this is an ANSI escape sequence that\n * explicitly positions the cursor at column 1, regardless of terminal state.\n * It does not affect the row \u2014 only the horizontal position is changed.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences\n * @since 1.3.0\n */\n\n CURSOR_LINE_START: '\\x1b[1G'\n} as const;\n", "/**\n * Import will remove at compile time\n */\n\nimport type { CellInterface, RenderContextInterface } from '@services/interfaces/shadow-service.interface';\n\n/**\n * Imports\n */\n\nimport { splitWithAnsiContext } from '@services/ast.service';\nimport { ANSI, writeRaw, moveCursor, stripAnsi } from '@components/ansi.component';\n\n/**\n * A virtual terminal renderer that manages efficient screen updates\n *\n * ShadowRenderer provides a mechanism to render content to the terminal\n * while minimizing the number of draw operations needed. It does this by\n * maintaining an internal representation of both the desired content and\n * the current terminal state, only updating parts of the screen that have\n * changed between render cycles.\n *\n * @remarks\n * The renderer maintains separate buffers for content (what should be displayed)\n * and view (what is currently displayed). During rendering, it performs a diff\n * between these buffers to determine the minimal set of changes needed to update\n * the terminal display.\n *\n * This class supports:\n * - Partial screen updates for performance\n * - Content scrolling\n * - Variable viewport dimensions\n * - Rich text styling through cell properties\n *\n * @example\n * ```ts\n * // Create a new renderer positioned at row 2, column 3 with dimensions 80x24\n * const renderer = new ShadowRenderer(2, 3, 80, 24);\n *\n * // Set some content and render it\n * renderer.writeText(0, 0, contentCells);\n * renderer.render();\n * ```\n *\n * @since 1.0.0\n */\n\nexport class ShadowRenderer {\n /**\n * Current scroll position in the content\n *\n * @remarks\n * Tracks the index of the first row visible at the top of the viewport.\n * A value of 0 indicates the content is not scrolled, while higher values\n * indicate the content has been scrolled down by that many rows.\n *\n * This value is used during rendering to determine which portion of the\n * contentBuffer to display in the visible area of the terminal.\n *\n * @see scroll - The getter for accessing this value\n *\n * @private\n */\n\n private scrollPosition: number = 0;\n\n /**\n * Internal buffer representing the current visible state of the terminal\n *\n * @remarks\n * This two-dimensional array stores the actual rendered content as it appears in the terminal.\n * It's organized in a row-major format, with each row containing an array of strings.\n *\n * Unlike contentBuffer which stores full cell information, viewBuffer only contains\n * the string representation of each cell. This buffer is used for diffing against\n * new content to determine what needs to be redrawn during render operations,\n * allowing for efficient partial updates to the terminal display.\n *\n * @private\n */\n\n private viewBuffer: Array<string[]> = [];\n\n /**\n * Internal buffer containing the content to be rendered\n *\n * @remarks\n * This two-dimensional array stores all content cells in a row-major format,\n * where each row is an array of CellInterface objects representing individual\n * characters with their associated style information.\n *\n * The outer array represents rows, while the inner arrays represent columns within each row.\n * This structure allows for efficient access and manipulation of cell data during\n * the rendering process.\n *\n * @private\n * @see CellInterface\n */\n\n private contentBuffer: Array<CellInterface[]> = [];\n\n /**\n * Creates a new ShadowRenderer instance for terminal-based UI rendering\n *\n * @param terminalHeight - The height of the terminal viewport in rows\n * @param terminalWidth - The width of the terminal viewport in columns\n * @param topPosition - The top-offset position within the terminal\n * @param leftPosition - The left offset position within the terminal\n *\n * @since 1.0.0\n */\n\n constructor(\n private terminalHeight: number,\n private terminalWidth: number,\n private topPosition: number,\n private leftPosition: number\n ) {\n }\n\n /**\n * Gets the top position offset of the renderer in the terminal\n *\n * @returns The row offset from the top edge of the terminal\n *\n * @since 1.0.0\n */\n\n get top(): number {\n return this.topPosition;\n }\n\n /**\n * Gets the left position offset of the renderer in the terminal\n *\n * @returns The column offset from the left edge of the terminal\n *\n * @since 1.0.0\n */\n\n get left(): number {\n return this.leftPosition;\n }\n\n /**\n * Gets the width of the renderer's viewport\n *\n * @returns The number of columns visible in the renderer's viewport\n *\n * @since 1.0.0\n */\n\n get width(): number {\n return this.terminalWidth;\n }\n\n /**\n * Gets the height of the renderer's viewport\n *\n * @returns The number of rows visible in the renderer's viewport\n *\n * @since 1.0.0\n */\n\n get height(): number {\n return this.terminalHeight;\n }\n\n /**\n * Gets the current scroll position\n *\n * @returns The current row index at the top of the viewport\n *\n * @since 1.0.0\n */\n\n get scroll(): number {\n return this.scrollPosition;\n }\n\n /**\n * Sets the top position offset of the renderer in the terminal\n *\n * @param top - The row offset from the top edge of the terminal\n *\n * @remarks\n * This setter updates the vertical positioning of the renderer's viewport\n * within the terminal. The top position is used as an offset when calculating\n * absolute cursor positions during rendering operations.\n *\n * Note that changing the top position does not automatically trigger a re-render.\n * You should call the render() method separately after changing the position.\n *\n * @since 1.0.0\n */\n\n set top(top: number) {\n this.topPosition = top;\n }\n\n /**\n * Sets the left position offset of the renderer in the terminal\n *\n * @param left - The column offset from the left edge of the terminal\n *\n * @remarks\n * This setter updates the horizontal positioning of the renderer's viewport\n * within the terminal. The left position is used as an offset when calculating\n * absolute cursor positions during rendering operations.\n *\n * Note that changing the left position does not automatically trigger a re-render.\n * You should call the render() method separately after changing the position.\n *\n * @since 1.0.0\n */\n\n set left(left: number) {\n this.leftPosition = left;\n }\n\n /**\n * Sets the width of the renderer's viewport\n *\n * @param terminalWidth - The number of columns visible in the renderer's viewport\n *\n * @remarks\n * This setter updates the internal width property which controls how many\n * columns are rendered during the rendering process. This should be updated\n * whenever the terminal or display area is resized.\n *\n * Note that changing the width does not automatically trigger a re-render.\n * You should call the render() method separately after changing dimensions.\n *\n * @since 1.0.0\n */\n\n set width(terminalWidth: number) {\n this.terminalWidth = terminalWidth;\n }\n\n /**\n * Sets the height of the renderer's viewport\n *\n * @param terminalHeight - The number of rows visible in the renderer's viewport\n *\n * @remarks\n * This setter updates the internal height property which controls how many\n * rows are rendered during the rendering process. This should be updated\n * whenever the terminal or display area is resized.\n *\n * Note that changing the height does not automatically trigger a re-render.\n * You should call the render() method separately after changing dimensions.\n *\n * @since 1.0.0\n */\n\n set height(terminalHeight: number) {\n this.terminalHeight = terminalHeight;\n }\n\n /**\n * Sets the scroll position and renders the updated view\n *\n * @param position - New scroll position or relative movement (if negative)\n *\n * @remarks\n * This setter handles both absolute and relative scrolling:\n * - Positive values set the absolute scroll position\n * - Negative values move relative to the current position\n *\n * If the requested position scrolls beyond the end of the content,\n * the operation is ignored. After setting a valid scroll position,\n * the view is automatically re-rendered.\n *\n * @example\n * ```ts\n * // Set absolute scroll position to row 10\n * renderer.scroll = 10;\n *\n * // Scroll up 3 rows (relative movement)\n * renderer.scroll = -3;\n * ```\n *\n * @since 1.0.0\n */\n\n set scroll(position: number) {\n // Calculate target position (handle negative values as relative movement)\n const targetPosition = position < 0\n ? this.scrollPosition + position // Relative position\n : position; // Absolute position\n\n const guardedPosition = Math.min(Math.max(targetPosition, 0), this.contentBuffer.length - 1);\n\n if (guardedPosition === this.scrollPosition) return;\n this.scrollPosition = guardedPosition;\n this.render();\n }\n\n /**\n * Clears all content from the renderer and resets its internal state.\n *\n * @remarks\n * This method removes all entries from both the `viewBuffer` and `contentBuffer`,\n * effectively resetting the renderer to its initial empty state.\n *\n * @returns void \u2014 This method does not produce a return value.\n *\n * @example\n * ```ts\n * // Completely reset the renderer's buffers\n * renderer.clear();\n * ```\n *\n * @since 1.0.0\n */\n\n clear(): void {\n this.viewBuffer = [];\n this.contentBuffer = [];\n }\n\n /**\n * Clears the visible content from the terminal screen\n *\n * @returns Nothing\n *\n * @remarks\n * This method builds a string of ANSI escape sequences that move the cursor\n * to the beginning of each line in the view buffer and then clears each line.\n * It doesn't reset the internal buffers, only clears the visible output.\n *\n * @example\n * ```ts\n * // Clear just the screen output without resetting buffers\n * renderer.clearScreen();\n * ```\n *\n * @since 1.0.0\n */\n\n clearScreen(): void {\n let output = '';\n for (let i = 0; i < this.viewBuffer.length; i++) {\n output += this.moveCursor(i, 0);\n output += ANSI.CLEAR_LINE;\n }\n\n output += ANSI.CURSOR_HOME;\n writeRaw(output);\n }\n\n /**\n * Writes text to the specified position in the content buffer\n *\n * @param row - Row position (0-based)\n * @param column - Column position (0-based)\n * @param text - Text to write\n * @param clean - Whether to clear existing content first\n *\n * @remarks\n * This method only updates the internal content buffer and marks cells as dirty.\n * It doesn't immediately render to the screen - call render() to display changes.\n * Only the first line of multi-line text is processed, and a text is truncated\n * if it exceeds terminal boundaries.\n *\n * @example\n * ```ts\n * // Write text in the top-left corner\n * renderer.writeText(0, 0, \"Hello world\");\n *\n * // Write text at position (5,10) and clear any existing content\n * renderer.writeText(5, 10, \"Menu Options\", true);\n *\n * // Display the changes\n * renderer.render();\n * ```\n *\n * @since 1.0.0\n */\n\n writeText(row: number, column: number, text: string, clean: boolean = false): void {\n // Validate input\n if (row < 0 || column >= this.terminalWidth) return;\n if(clean) this.contentBuffer[row] = [];\n\n text = text.split('\\n')[0];\n const line = this.contentBuffer[row] ??= [];\n const stripContent = stripAnsi(text);\n const length = Math.min(this.terminalWidth - column, stripContent.length);\n const content = splitWithAnsiContext(text);\n\n for (let i = 0; i < length; i++) {\n const col = column + i;\n const char = content[i];\n if (!line[col]) line[col] = { char: '', dirty: true };\n\n // Mark as dirty only if content changed\n if (line[col].char !== char) {\n line[col].char = char;\n line[col].dirty = true;\n }\n }\n\n // clean the rest of the line ? `line.length = Math.min(this.terminalWidth, column + length);`\n line.length = Math.min(Math.max(column + length, this.terminalWidth), this.terminalWidth);\n }\n\n /**\n * Writes multi-line text into the content buffer.\n *\n * @param row - Starting row position (0-based).\n * @param column - Starting column position (0-based).\n * @param text - Text to write, either as a string (may contain newlines) or an array of strings (one per line).\n * @param clean - Whether to clear existing content before writing.\n * Only applies to the first written line; subsequent lines always append.\n *\n * @remarks\n * Unlike {@link writeText}, this method supports writing multiple lines\n * at once. If the input is a single string, it is split by newline characters.\n * If an array of strings is provided, each element represents a line.\n *\n * This method automatically allocates new rows in the content buffer\n * as needed, making it suitable for rendering large blocks of text\n * that can later be scrolled with the renderer.\n *\n * @example\n * Writing a block of text from a single string:\n * ```ts\n * renderer.writeBlock(0, 0, \"Line 1\\nLine 2\\nLine 3\");\n * renderer.render();\n * ```\n *\n * @example\n * Writing a block of text from an array:\n * ```ts\n * renderer.writeBlock(2, 4, [\"Indented line 1\", \"Indented line 2\"]);\n * renderer.render();\n * ```\n *\n * @since 1.2.0\n */\n\n writeBlock(row: number, column: number, text: string | Array<string>, clean: boolean = false): void {\n const lines = Array.isArray(text) ? text : text.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const currentRow = row + i;\n this.writeText(currentRow, column, lines[i], clean);\n }\n }\n\n /**\n * Renders the content buffer to the screen using optimized terminal output\n *\n * @param force - Forces all cells to be redrawn, even if they haven't changed\n *\n * @remarks\n * This method performs an optimized render by:\n * - Only rendering the visible portion of the content buffer based on scroll position\n * - Only updating cells that have been marked as dirty (unless force=true)\n * - Clearing trailing content from previous renders\n * - Repositioning the cursor to the bottom right when finished\n *\n * If the content buffer is empty or all content is scrolled out of view,\n * the method will return early without performing any operations.\n *\n * @example\n * ```ts\n * // Normal render - only updates what changed\n * renderer.render();\n *\n * // Force redraw of everything, useful after terminal resize\n * renderer.render(true);\n * ```\n *\n * @since 1.0.0\n */\n\n render(force: boolean = false): void {\n const startRow = Math.min(this.scrollPosition, this.contentBuffer.length);\n const endRow = Math.min(startRow + this.terminalHeight, this.contentBuffer.length);\n\n if (startRow >= endRow) return;\n const context: RenderContextInterface = {\n force,\n output: '',\n viewLine: [],\n screenRow: 1,\n contentLine: []\n };\n\n for (let bufferRow = startRow; bufferRow < endRow; bufferRow++, context.screenRow++) {\n context.contentLine = this.contentBuffer[bufferRow];\n if(!context.contentLine) continue; // empty line\n\n context.viewLine = this.viewBuffer[context.screenRow] ??= [];\n this.renderLine(context);\n\n // Clean up any trailing content from previous renders\n if (context.viewLine.length > context.contentLine.length) {\n context.output += ANSI.CLEAR_LINE;\n context.viewLine.length = context.contentLine.length;\n }\n }\n\n // Clear any rows below our content\n if (endRow >= this.contentBuffer.length) {\n this.viewBuffer.length = context.screenRow;\n for (let i = context.screenRow; i <= this.terminalHeight; i++) {\n context.output += this.moveCursor(i, 0);\n context.output += ANSI.CLEAR_LINE;\n }\n }\n\n context.output += this.moveCursor(this.viewBuffer.length, this.terminalWidth);\n writeRaw(context.output);\n }\n\n /**\n * Flushes the current content buffer directly to the terminal.\n *\n * @remarks\n * This method writes all rows from {@link contentBuffer} to `stdout`,\n * appending a newline after each row. It also clears each line with\n * {@link ANSI.CLEAR_LINE} before writing, ensuring no stale characters\n * remain on screen.\n *\n * Once flushing is complete, both {@link viewBuffer} and {@link contentBuffer}\n * are reset to empty arrays, preparing the renderer for the next cycle.\n *\n * Unlike {@link render}, this method bypasses diffing and incremental\n * optimizations. It always emits the full buffer to the terminal, which\n * guarantees a complete reset of the visible state but may be less\n * efficient for large outputs.\n *\n * @returns void \u2014 This method does not produce a return value.\n *\n * @example\n * ```ts\n * // Write a block of text to the buffer\n * renderer.writeBlock(0, 0, \"Hello\\nWorld\");\n * renderer.clearScreen();\n *\n * // Forcefully flush everything to the terminal\n * renderer.flushToTerminal();\n * ```\n *\n * @since 1.2.0\n */\n\n flushToTerminal(): void {\n let output = '\\n';\n\n for (let row = 0; row < this.contentBuffer.length; row++) {\n const line = this.contentBuffer[row];\n if (!line) continue;\n\n output += ANSI.CLEAR_LINE;\n for (let col = 0; col < line.length; col++) {\n const cell = line[col];\n output += cell?.char ?? ' ';\n }\n\n output += '\\n';\n }\n\n this.clear();\n writeRaw(output);\n }\n\n /**\n * Renders a single line of content to the output buffer\n *\n * @param context - The current rendering context\n *\n * @remarks\n * This private method handles the optimization of terminal output by:\n * - Skipping cells that haven't changed since the last render\n * - Only moving the cursor when necessary\n * - Updating the view buffer to reflect what's been rendered\n * - Clearing the dirty flag on cells after they're processed\n *\n * The context object contains all states needed for the rendering process,\n * including the accumulating output string and references to the current\n * content and view lines.\n *\n * @private\n * @since 1.0.0\n */\n\n private renderLine(context: RenderContextInterface): void {\n // Track when cursor movement is needed\n let needsCursorMove = true;\n\n // Process each cell in the row\n for (let col = 0; col < context.contentLine.length; col++) {\n const cell = context.contentLine[col];\n\n if (cell && !cell.dirty && cell.char === context.viewLine[col] && !context.force) {\n needsCursorMove = true;\n continue;\n }\n\n if (needsCursorMove) {\n context.output += this.moveCursor(context.screenRow, col + 1);\n needsCursorMove = false;\n }\n\n if (!cell) {\n context.viewLine[col] = ' ';\n context.output += ' ';\n continue;\n }\n\n // Update view buffer and output the character\n context.viewLine[col] = cell.char;\n context.output += cell.char;\n cell.dirty = false;\n }\n }\n\n /**\n * Generates an ANSI escape sequence to move the cursor to a position\n *\n * @param row - The row position relative to renderer's viewport\n * @param column - The column position relative to renderer's viewport (defaults to 0)\n * @returns ANSI escape sequence string for cursor positioning\n *\n * @remarks\n * This private helper method translates relative viewport coordinates to\n * absolute terminal coordinates by adding the renderer's top and left\n * position offsets. The returned value is a string containing the\n * appropriate ANSI escape sequence.\n *\n * @private\n * @since 1.0.0\n */\n\n private moveCursor(row: number, column: number = 0): string {\n return moveCursor(row + this.topPosition, column + this.leftPosition);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { StyleCodeType } from '@providers/interfaces/styles-provider.interface';\n\n/**\n * Collection of ANSI text modifier codes for terminal styling\n *\n * @returns An object mapping modifier names to their corresponding ANSI style codes\n *\n * @remarks\n * Provides commonly used text modifiers like bold, dim, etc. Each entry contains\n * a pair of codes: the first to apply the style and the second to reset it.\n * These modifiers change the appearance of text without affecting its color.\n *\n * @example\n * ```ts\n * // Apply bold styling to text\n * const boldCode = ansiModifiers.bold;\n * console.log(`\\x1b[${boldCode[0]}mBold Text\\x1b[${boldCode[1]}m`);\n * ```\n *\n * @see StyleCodeType\n * @since 1.0.0\n */\n\nexport const ansiModifiers = {\n dim: [ 2, 22 ],\n bold: [ 1, 22 ],\n reset: [ 0, 0 ],\n hidden: [ 8, 28 ],\n inverse: [ 7, 27 ]\n} satisfies Record<string, StyleCodeType>;\n\n/**\n * Collection of ANSI foreground color codes for terminal text coloring\n *\n * @returns An object mapping color names to their corresponding ANSI foreground style codes\n *\n * @remarks\n * Provides standard and bright variants of terminal foreground colors.\n * Each entry contains a pair of codes: the first to apply the color and\n * the second (39) to reset to the default foreground color.\n *\n * @example\n * ```ts\n * // Apply red foreground color to text\n * const redCode = ansiForegroundColors.red;\n * console.log(`\\x1b[${redCode[0]}mRed Text\\x1b[${redCode[1]}m`);\n *\n * // Apply bright blue color\n * const brightBlueCode = ansiForegroundColors.blueBright;\n * console.log(`\\x1b[${brightBlueCode[0]}mBright Blue\\x1b[${brightBlueCode[1]}m`);\n * ```\n *\n * @see StyleCodeType\n * @since 1.0.0\n */\n\nexport const ansiForegroundColors = {\n red: [ 31, 39 ],\n gray: [ 90, 39 ],\n blue: [ 34, 39 ],\n cyan: [ 36, 39 ],\n black: [ 30, 39 ],\n white: [ 37, 39 ],\n green: [ 32, 39 ],\n yellow: [ 33, 39 ],\n magenta: [ 35, 39 ],\n redBright: [ 91, 39 ],\n blueBright: [ 94, 39 ],\n cyanBright: [ 96, 39 ],\n whiteBright: [ 97, 39 ],\n greenBright: [ 92, 39 ],\n blackBright: [ 90, 39 ],\n yellowBright: [ 93, 39 ],\n magentaBright: [ 95, 39 ],\n darkGray: [ '38;5;238', 39 ],\n lightGray: [ '38;5;252', 39 ],\n lightCyan: [ '38;5;81', 39 ],\n lightCoral: [ '38;5;203', 39 ],\n oliveGreen: [ '38;5;149', 39 ],\n deepOrange: [ '38;5;166', 39 ],\n brightPink: [ '38;5;197', 39 ],\n lightOrange: [ '38;5;215', 39 ],\n burntOrange: [ '38;5;208', 39 ],\n lightYellow: [ '38;5;230', 39 ],\n canaryYellow: [ '38;5;227', 39 ],\n lightGoldenrodYellow: [ '38;5;221', 39 ]\n} satisfies Record<string, StyleCodeType>;\n\n/**\n * Collection of ANSI background color codes for terminal text backgrounds\n *\n * @returns An object mapping color names to their corresponding ANSI background style codes\n *\n * @remarks\n * Provides standard and bright variants of terminal background colors.\n * Each entry contains a pair of codes: the first to apply the background color and\n * the second (49) to reset to the default background.\n * All background color names are prefixed with 'bg' to distinguish them from foreground colors.\n *\n * @example\n * ```ts\n * // Apply red background to text\n * const bgRedCode = ansiBackgroundColors.bgRed;\n * console.log(`\\x1b[${bgRedCode[0]}mText with Red Background\\x1b[${bgRedCode[1]}m`);\n *\n * // Apply bright cyan background\n * const bgCyanBrightCode = ansiBackgroundColors.bgCyanBright;\n * console.log(`\\x1b[${bgCyanBrightCode[0]}mBright Cyan Background\\x1b[${bgCyanBrightCode[1]}m`);\n * ```\n *\n * @see StyleCodeType\n * @since 1.0.0\n */\n\nexport const ansiBackgroundColors = {\n bgRed: [ 41, 49 ],\n bgBlue: [ 44, 49 ],\n bgCyan: [ 46, 49 ],\n bgGray: [ 100, 49 ],\n bgBlack: [ 40, 49 ],\n bgGreen: [ 42, 49 ],\n bgWhite: [ 47, 49 ],\n bgYellow: [ 43, 49 ],\n bgMagenta: [ 45, 49 ],\n bgRedBright: [ 101, 49 ],\n bgBlueBright: [ 104, 49 ],\n bgCyanBright: [ 106, 49 ],\n bgBlackBright: [ 100, 49 ],\n bgWhiteBright: [ 107, 49 ],\n bgGreenBright: [ 102, 49 ],\n bgYellowBright: [ 103, 49 ],\n bgMagentaBright: [ 105, 49 ]\n} satisfies Record<string, StyleCodeType>;\n", "/**\n * Import will remove at compile time\n */\n\nimport type { StyleCodeType } from '@providers/interfaces/styles-provider.interface';\nimport type { AnsiChainableBuilderType } from '@components/interfaces/xterm-component.interface';\n\n/**\n * Imports\n */\n\nimport { ansiBackgroundColors, ansiForegroundColors, ansiModifiers } from '@providers/styles.provider';\n\n\n/**\n * Exports\n */\n\nexport type * from '@components/interfaces/xterm-component.interface';\n\n/**\n * Unified collection of all ANSI style codes for efficient lookup\n *\n * @returns A merged record of all style codes including modifiers, foreground and background colors\n *\n * @remarks\n * This constant combines all style types (modifiers, foreground colors, and background colors)\n * into a single lookup object for improved performance when accessing style codes.\n * It's particularly useful in hot paths where style code lookups happen frequently.\n *\n * @example\n * ```ts\n * // Get the style code for bold text\n * const boldCode = styles.bold;\n *\n * // Get the style code for red foreground\n * const redCode = styles.red;\n *\n * // Get the style code for a blue background\n * const bgBlueCode = styles.bgBlue;\n * ```\n *\n * @see ansiModifiers\n * @see ansiForegroundColors\n * @see ansiBackgroundColors\n * @see StyleCodeType\n * @since 1.0.0\n */\n\nconst styles: Record<string, StyleCodeType> = {\n ...ansiModifiers,\n ...ansiForegroundColors,\n ...ansiBackgroundColors\n};\n\n/**\n * ANSI escape sequence prefix for terminal control codes\n *\n * @remarks\n * This constant defines the standard ANSI escape sequence prefix used to start\n * a terminal control code. Using a constant improves performance by avoiding\n * string recreation in performance-critical code paths.\n *\n * @see ESC_END\n * @since 1.0.0\n */\n\nconst ESC = '\\x1b[';\n\n/**\n * ANSI escape sequence suffix for terminal style codes\n *\n * @remarks\n * This constant defines the standard ANSI escape sequence suffix that completes\n * a terminal style control code. Used in conjunction with ESC and style codes\n * to form complete ANSI styling sequences.\n *\n * @see ESC\n * @since 1.0.0\n */\n\nconst ESC_END = 'm';\n\n/**\n * Wraps text with ANSI escape sequences to apply terminal styling\n *\n * @param codes - Array of StyleCodeType tuples to apply to the text\n * @param text - The string to be styled with ANSI codes\n * @returns The input text wrapped with appropriate ANSI escape sequences\n *\n * @remarks\n * This function efficiently applies multiple style codes to a text string by\n * wrapping it with the appropriate ANSI escape sequences. It handles proper nesting\n * of styles by ensuring that reset codes are applied in reverse order.\n *\n * The function has three optimized code paths:\n * - For an empty codes array, it returns the original text without modification\n * - For a single code, it directly concatenates without using arrays\n * - For multiple codes, it pre-allocates arrays for improved performance\n *\n * @example\n * ```ts\n * // Apply a single style (bold)\n * const boldText = wrapWithAnsi([styles.bold], \"Hello World\");\n *\n * // Apply multiple styles (bold and red)\n * const boldRedText = wrapWithAnsi([styles.bold, styles.red], \"Hello World\");\n * ```\n *\n * @see StyleCodeType\n * @see ESC\n * @see ESC_END\n * @since 1.0.0\n */\n\nfunction wrapWithAnsi(codes: Array<StyleCodeType>, text: string): string {\n if (globalThis.NO_COLOR) return text;\n const codesLength = codes.length;\n\n if (codesLength === 0) return text;\n if (codesLength === 1) {\n return `${ ESC }${ codes[0][0] }${ ESC_END }${ text }${ ESC }${ codes[0][1] }${ ESC_END }`;\n }\n\n const endCodes = new Array<string>(codesLength);\n const startCodes = new Array<string>(codesLength);\n\n for (let i = 0; i < codesLength; i++) {\n startCodes[i] = `${ ESC }${ codes[i][0] }${ ESC_END }`;\n // Build end codes in reverse order for proper nesting\n endCodes[codesLength - i - 1] = `${ ESC }${ codes[i][1] }${ ESC_END }`;\n }\n\n return startCodes.concat(text, endCodes).join('');\n}\n\n/**\n * Generates ANSI RGB color code for terminal foreground or background styling\n *\n * @param type - Color application type: 'fg' for foreground or 'bg' for background\n * @param r - Red color component (0-255)\n * @param g - Green color component (0-255)\n * @param b - Blue color component (0-255)\n * @returns A StyleCodeType tuple containing the RGB color code and its reset code\n *\n * @throws Error - When any of the RGB values are not numbers\n *\n * @remarks\n * This function creates ANSI 24-bit color codes (true color) for terminals that support them.\n * It generates the appropriate code based on whether the color should be applied to\n * the foreground (text color) or background.\n *\n * The function performs type checking on RGB values to ensure they are numbers\n * before generating the style code.\n *\n * @example\n * ```ts\n * // Create a foreground RGB color (red)\n * const redFg = rgbCode('fg', 255, 0, 0);\n *\n * // Create a background RGB color (blue)\n * const blueBg = rgbCode('bg', 0, 0, 255);\n *\n * // Apply the RGB color to text\n * const coloredText = wrapWithAnsi([redFg], \"This text is custom red\");\n * ```\n *\n * @see StyleCodeType\n * @see wrapWithAnsi\n *\n * @since 1.0.0\n */\n\nfunction rgbCode(type: 'fg', r: number, g: number, b: number): StyleCodeType;\nfunction rgbCode(type: 'bg', r: number, g: number, b: number): StyleCodeType;\nfunction rgbCode(type: 'fg' | 'bg', r: number | unknown, g: number | unknown, b: number | unknown): StyleCodeType {\n if (typeof r !== 'number' || typeof g !== 'number' || typeof b !== 'number') {\n throw new Error(`RGB values must be numbers, received: r=${ typeof r }, g=${ typeof g }, b=${ typeof b }`);\n }\n\n const code = type === 'fg' ? 38 : 48;\n const reset = type === 'fg' ? 39 : 49;\n\n return [ `${ code };2;${ r };${ g };${ b }`, reset ];\n}\n\n/**\n * Converts a hexadecimal color string to RGB components\n *\n * @param hex - Hexadecimal color string (with or without leading #)\n * @returns Tuple of [red, green, blue] values as numbers in the range 0-255\n *\n * @throws Error - When the provided hex string is not a valid 3 or 6 digit hex color\n *\n * @remarks\n * This utility function parses both 3-digit shorthand (#RGB) and 6-digit standard (#RRGGBB)\n * hexadecimal color formats into their corresponding RGB numeric values.\n *\n * For 3-digit hex values, each digit is duplicated to create the equivalent 6-digit value\n * (e.g., #F00 becomes #FF0000).\n *\n * @example\n * ```ts\n * // 6-digit hex\n * const [r, g, b] = hexToRgb('#FF5500');\n * console.log(r, g, b); // 255, 85, 0\n *\n * // 3-digit hex\n * const [r, g, b] = hexToRgb('#F50');\n * console.log(r, g, b); // 255, 85, 0\n *\n * // Without # prefix\n * const [r, g, b] = hexToRgb('00FF00');\n * console.log(r, g, b); // 0, 255, 0\n * ```\n *\n * @see rgbCode - Function that uses RGB values to create ANSI color codes\n * @since 1.0.0\n */\n\nfunction hexToRgb(hex: `#${ string }` | string): [ number, number, number ] {\n // Remove leading # if present\n const cleanHex = hex.replace(/^#/, '').toLowerCase();\n\n // Validate hex format\n if (!/^([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(cleanHex)) {\n throw new Error(`Invalid hex color format: \"${ hex }\". Expected 3 or 6 hex digits.`);\n }\n\n // Parse 3-digit hex\n if (cleanHex.length === 3) {\n const r = parseInt(cleanHex[0] + cleanHex[0], 16);\n const g = parseInt(cleanHex[1] + cleanHex[1], 16);\n const b = parseInt(cleanHex[2] + cleanHex[2], 16);\n\n return [ r, g, b ];\n }\n\n // Parse 6-digit hex\n const r = parseInt(cleanHex.slice(0, 2), 16);\n const g = parseInt(cleanHex.slice(2, 4), 16);\n const b = parseInt(cleanHex.slice(4, 6), 16);\n\n return [ r, g, b ];\n}\n\n/**\n * Creates a chainable builder for styling text with ANSI escape sequences\n *\n * @param codes - Initial style codes to apply (empty by default)\n * @returns A chainable builder object that acts as both a function and a proxy for style methods\n *\n * @remarks\n * This function creates a chainable API for terminal text styling that supports both\n * function call and property access patterns. The returned object is both callable\n * (to format text) and provides property access for style chaining.\n *\n * The implementation uses a JavaScript Proxy to intercept property access and dynamically\n * create new chain instances with additional style codes. The formatter function handles\n * both regular arguments and tagged template literals.\n *\n * The builder supports:\n * - Basic styles (bold, dim, italic, etc.) via property access\n * - RGB colors via .rgb() and .bgRgb() methods\n * - Hex colors via .hex() and .bgHex() methods\n * - Function call with strings or template literals to apply styles\n *\n * @example\n * ```ts\n * // Basic usage\n * const colorizer = createXtermChain();\n * console.log(colorizer.bold.red(\"This is bold and red\"));\n *\n * // Chaining multiple styles\n * console.log(colorizer.bold.underline.hex('#3498db')(\"Styled text\"));\n *\n * // Using template literals\n * const name = \"World\";\n * console.log(colorizer.green`Hello ${name}!`);\n *\n * // Starting with initial styles\n * const warningStyle = createXtermChain([styles.yellow, styles.bold]);\n * console.log(warningStyle(\"Warning message\"));\n * ```\n *\n * @see styles\n * @see rgbCode\n * @see hexToRgb\n * @see wrapWithAnsi\n * @see AnsiChainableBuilderType\n *\n * @since 1.0.0\n */\n\nfunction createXtermChain(codes: Array<StyleCodeType> = []): AnsiChainableBuilderType {\n const formatter = (...args: Array<unknown>): string => {\n if (Array.isArray(args[0]) && 'raw' in args[0]) {\n const [ strings, ...values ] = args as [ TemplateStringsArray, ...Array<unknown> ];\n\n const combined = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? String(values[i] ?? '') : ''),\n ''\n );\n\n return wrapWithAnsi(codes, combined);\n }\n\n // Handle regular arguments\n return wrapWithAnsi(codes, args.join(' '));\n };\n\n // Define color method handlers for reuse\n const colorHandlers = {\n // RGB foreground color\n rgb: (r: number, g: number, b: number): AnsiChainableBuilderType =>\n createXtermChain([ ...codes, rgbCode('fg', r, g, b) ]),\n\n bgRgb: (r: number, g: number, b: number): AnsiChainableBuilderType =>\n createXtermChain([ ...codes, rgbCode('bg', r, g, b) ]),\n\n hex: (hex: string): AnsiChainableBuilderType =>\n createXtermChain([ ...codes, rgbCode('fg', ...hexToRgb(hex)) ]),\n\n bgHex: (hex: string): AnsiChainableBuilderType =>\n createXtermChain([ ...codes, rgbCode('bg', ...hexToRgb(hex)) ])\n };\n\n // Create a proxy to handle property access for chaining\n return <AnsiChainableBuilderType>new Proxy(formatter, {\n get(target, prop: string | symbol): unknown {\n if (typeof prop !== 'string') {\n throw new Error(`Invalid property: ${ String(prop) }`);\n }\n\n // Handle standard styles from the styles object\n if (prop in styles) {\n return createXtermChain([ ...codes, styles[prop] ]);\n }\n\n // Handle color methods\n if (prop in colorHandlers) {\n return colorHandlers[prop as keyof typeof colorHandlers];\n }\n\n // Fall back to the target's own properties\n return Reflect.get(target, prop);\n }\n });\n}\n\n/**\n * Pre-configured ANSI terminal styling utility with chainable methods\n *\n * @example\n * ```ts\n * // Basic styling\n * console.log(xterm.bold(\"This is bold text\"));\n * console.log(xterm.red(\"This is red text\"));\n *\n * // Chain multiple styles\n * console.log(xterm.bold.red(\"This is bold and red\"));\n * console.log(xterm.green(\"This is green\"));\n *\n * // Use with template literals\n * const name = \"World\";\n * console.log(xterm.cyan`Hello ${name}!`);\n *\n * // RGB and Hex colors\n * console.log(xterm.rgb(255, 136, 0)(\"Custom orange text\"));\n * console.log(xterm.hex(\"#FF8800\")(\"Hex orange text\"));\n *\n * // Background colors\n * console.log(xterm.bgGreen(\"Text with green background\"));\n * console.log(xterm.bgHex(\"#333333\")(\"Text with a dark background\"));\n * ```\n *\n * @remarks\n * The `xterm` export provides a convenient, ready-to-use instance of the chainable\n * styling builder. It supports all standard ANSI styles, RGB colors, and hexadecimal\n * color definitions for both foreground and background.\n *\n * This is the recommended entry point for using the styling functionality in most cases.\n * For custom styling chains with pre-applied styles, use `createXtermChain()` directly.\n *\n * @see createXtermChain\n * @see AnsiChainableBuilderType\n *\n * @since 1.0.0\n */\n\nexport const xterm = createXtermChain();\n", "/**\n * Import will remove at compile time\n */\n\nimport type { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Checks if a given value is an instance of the specified constructor.\n *\n * @param constructor - The constructor function to check against\n * @param value - The value to test\n *\n * @returns True if the value is not null or undefined and its constructor matches the specified constructor; otherwise false\n *\n * @example\n * ```ts\n * class MyClass {}\n * const instance = new MyClass();\n * console.log(isA(MyClass, instance)); // true\n * console.log(isA(Array, instance)); // false\n * ```\n *\n * @since 1.0.0\n */\n\nexport function isA(constructor: unknown, value: unknown): boolean {\n return value !== null && value !== undefined && (value.constructor === constructor || typeof value === 'function');\n}\n\n/**\n * Checks if the specified key exists as an own property on the given object.\n *\n * @param obj - The object to check for the key\n * @param key - The property key (string or symbol) to look for\n *\n * @returns True if the object has the specified own property key; otherwise false\n *\n * @example\n * ```ts\n * const obj = { foo: 123 };\n * console.log(hasKey(obj, 'foo')); // true\n * console.log(hasKey(obj, 'bar')); // false\n * ```\n *\n * @since 1.0.0\n */\n\nexport function hasKey(obj: unknown, key: string | symbol): boolean {\n if (obj == null || (typeof obj !== 'object' && typeof obj !== 'function'))\n return false;\n\n return key in obj || Object.prototype.hasOwnProperty.call(obj, key);\n}\n\n/**\n * Determines whether the given object implements the `AbstractPattern` interface.\n *\n * @param obj - The object to test\n *\n * @returns A type guard indicating whether the object has a `matches` method\n *\n * @remarks\n * This function checks if the object is truthy and has a `matches` method,\n * which is expected for objects implementing `AbstractPattern`.\n *\n * @example\n * ```ts\n * if (isAsymmetric(someObj)) {\n * someObj.matches(value);\n * }\n * ```\n *\n * @see AbstractPattern - The interface that defines the `matches` method\n *\n * @since 1.0.0\n */\n\nexport function isAsymmetric(obj: unknown): obj is AbstractPattern {\n return !!obj && hasKey(obj, 'expectedLabel') && isA(Function, (obj as AbstractPattern).matches);\n}\n\n/**\n * Attempts an asymmetric match between two values if either implements `AbstractPattern`.\n *\n * @param a - The first value to test for asymmetric matching\n * @param b - The second value to test for asymmetric matching\n *\n * @returns `true` if `a` matches `b`, `false` if it does not match,\n * `undefined` if neither value implements asymmetric matching or if both do (defer)\n *\n * @remarks\n * This function uses the `isAsymmetric` type guard to detect if either value implements\n * the `AbstractPattern` interface. If both are asymmetric, the comparison is deferred by returning `undefined`.\n * If only one is asymmetric, it performs the match accordingly.\n *\n * @example\n * ```ts\n * const pattern = { matches: (v: any) => v > 10 };\n * console.log(asymmetricMatch(pattern, 15)); // true\n * ```\n *\n * @see isAsymmetric - Helper to detect asymmetric matchers\n * @see AbstractPattern - Interface defining the `matches` method\n *\n * @since 1.0.0\n */\n\nexport function asymmetricMatch(a: unknown, b: unknown): boolean | undefined {\n const asymmetricA = isAsymmetric(a);\n const asymmetricB = isAsymmetric(b);\n\n if (asymmetricA && asymmetricB) {\n return undefined; // Defer comparison; neither dominates\n }\n\n if (asymmetricA) return a.matches(b);\n if (asymmetricB) return b.matches(a);\n\n return undefined;\n}\n\n/**\n * Performs a deep equality comparison between two objects or arrays.\n *\n * @param a - The first object or array to compare.\n * @param b - The second object or array to compare.\n * @param strictCheck - Whether to require exact shape matching (default: true).\n * If false, `b` can be a superset of `a`.\n *\n * @returns A boolean indicating whether the two inputs are deeply equal.\n *\n * @remarks\n * This function is used internally by `equals` to recursively compare arrays and objects.\n *\n * - For arrays:\n * - If `strictCheck` is true, their lengths must match.\n * - If false, only the elements of `a` must match the corresponding elements in `b`.\n *\n * - For objects:\n * - If `strictCheck` is true, both must have exactly the same keys.\n * - If false, `b` may contain extra keys, but all keys in `a` must match.\n *\n * Keys and values are compared recursively using `equals`, which supports deep matching.\n *\n * @example\n * ```ts\n * deepEquals({ a: 1 }, { a: 1 }, true); // true\n * deepEquals({ a: 1 }, { a: 1, b: 2 }, false); // true\n * deepEquals([1, 2], [1, 2, 3], false); // true\n * deepEquals([1, 2], [2, 1], true); // false\n * ```\n *\n * @see equals - Performs a general equality comparison (shallow or deep)\n *\n * @since 1.0.0\n */\n\nfunction deepEquals(a: object, b: object, strictCheck: boolean = true): boolean {\n if (Array.isArray(a) && Array.isArray(b)) {\n if(strictCheck && a.length !== b.length) return false;\n\n return a.every((val, i) => equals(val, b[i], strictCheck));\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (strictCheck && aKeys.length !== bKeys.length) return false;\n\n for (const key of aKeys) {\n if (!hasKey(b, key)) return false;\n if (!equals((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], strictCheck)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether two values are equal, supporting both strict and partial deep equality.\n *\n * @param a - The first value to compare.\n * @param b - The second value to compare.\n * @param strictCheck - If true (default), requires exact deep equality.\n * If false, allows partial (asymmetric) matching.\n *\n * @returns `true` if the values are considered equal; otherwise, `false`.\n *\n * @remarks\n * This function performs a deep comparison between two values:\n *\n * - Primitives are compared using `Object.is`.\n * - Special objects (Date, RegExp, URL) are compared by value.\n * - Arrays and plain objects are compared recursively via `deepEquals`.\n * - Supports asymmetric matching when `strictCheck` is false (e.g., partial matching).\n *\n * The following helper functions are assumed to exist:\n * - `asymmetricMatch`: handles custom matchers or partial match behavior\n * - `deepEquals`: recursively compares arrays and objects\n *\n * @example\n * ```ts\n * equals(1, 1); // true\n * equals(1, '1'); // false\n * equals({ x: 1 }, { x: 1 }); // true\n * equals({ x: 1 }, { x: 1, y: 2 }, false); // true (partial match)\n * equals([1, 2], [1, 2, 3], false); // true (partial match)\n * ```\n *\n * @since 1.0.0\n */\n\nexport function equals(a: unknown, b: unknown, strictCheck = true): boolean {\n if (a === b) return true; // Fast path for strict equality\n if (Object.is(a, b)) return true; // Handle identical references or primitive equality\n if (a === null || b === null) return false; // Handle null or undefined cases\n\n const asymmetricResult = asymmetricMatch(a, b);\n if (asymmetricResult !== undefined) return asymmetricResult;\n\n if (a instanceof Date && b instanceof Date)\n\n return a.getTime() === b.getTime();\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n\n if (globalThis.URL && a instanceof globalThis.URL && b instanceof globalThis.URL)\n return a.href === b.href;\n\n if (typeof a === 'object' && typeof b === 'object') {\n return deepEquals(a, b, strictCheck);\n }\n\n return false;\n}\n\n/**\n * Serializes an {@link Error} object into a generic key-value object.\n *\n * @template T - The type of values in the returned record (defaults to `unknown`).\n * @param error - The error instance to serialize.\n * @returns A record containing all own enumerable properties of the error,\n * including `name`, `message`, and `stack`.\n *\n * @remarks\n * This function ensures that all enumerable properties of the error are preserved,\n * while always including the standard `name`, `message`, and `stack` properties.\n * It is useful for structured logging, transmitting errors across process boundaries,\n * or converting errors to a format suitable for JSON serialization.\n *\n * @example\n * ```ts\n * try {\n * throw new Error(\"Something went wrong\");\n * } catch (err) {\n * const serialized = serializesError<string>(err);\n * console.log(serialized.name); // \"Error\"\n * console.log(serialized.message); // \"Something went wrong\"\n * }\n * ```\n *\n * @since 2.1.0\n */\n\nexport function serializesError<T = unknown>(error: Error): Record<string, T> {\n const json: Record<string, unknown> = {};\n\n // Copy all own (non-inherited) enumerable properties\n for (const key of Object.keys(error)) {\n const value = error[key as keyof Error];\n if(value) json[key] = value;\n }\n\n // Ensure `name`, `message`, and `stack` are included\n json.name = error.name;\n json.stack = error.stack;\n json.message = error.message;\n\n return <Record<string, T>> json;\n}\n", "/**\n * Determines whether the given candidate is a Promise-like object.\n *\n * @template T - The type of the resolved value of the Promise\n *\n * @param candidate - The value to test for Promise-like behavior\n *\n * @returns A type guard indicating whether the candidate is a Promise-like object\n *\n * @remarks\n * This function checks if the candidate is non-null and either an object or a function,\n * then verifies the presence of a `then` method to identify Promise-like objects.\n *\n * @example\n * ```ts\n * if (isPromise(someValue)) {\n * someValue.then(value => {\n * console.log('Resolved with', value);\n * });\n * }\n * ```\n *\n * @since 1.0.0\n */\n\nexport function isPromise<T = unknown>(candidate: unknown): candidate is PromiseLike<T> {\n return (\n candidate != null &&\n (typeof candidate === 'object' || typeof candidate === 'function') &&\n typeof (candidate as Promise<unknown>).then === 'function'\n );\n}\n", "/**\n * Imports\n */\n\nimport { isAsymmetric } from '@components/object.component';\n\n/**\n * Default indentation string used throughout the serialization system.\n *\n * @remarks\n * This constant defines the standard indentation as two spaces (' ') used\n * when generating multi-line serialized representations of complex data structures.\n * It's used as the default value for indent parameters across various serialization functions.\n *\n * @example\n * ```ts\n * // Using the default indentation\n * const serialized = serialize(complexObject);\n *\n * // Overriding with custom indentation\n * const customIndented = serialize(complexObject, ' '); // 4 spaces instead\n * ```\n *\n * @since 1.0.0\n */\n\nconst INDENT = ' ';\n\n/**\n * Converts primitive JavaScript values to their string representation.\n *\n * @param element - The value to be serialized\n * @returns A string representation of the value, or null if serialization is not supported\n *\n * @remarks\n * This function handles serialization of various JavaScript primitive types and built-in objects:\n * - Strings (returns quoted string unless it contains newlines)\n * - Numbers (handles NaN and finite numbers)\n * - Booleans, Symbols, BigInts\n * - Functions (with name or as anonymous)\n * - null, undefined\n * - Built-in objects (Date, RegExp, Error, Promise)\n * - TypedArray views (ArrayBuffer, DataView)\n *\n * The function returns null for complex objects that require custom serialization\n * or for strings containing newlines, which should be handled differently.\n *\n * @example\n * ```ts\n * serializePrimitive(\"hello\") // Returns: \"\\\"hello\\\"\"\n * serializePrimitive(42) // Returns: \"42\"\n * serializePrimitive(null) // Returns: \"null\"\n * serializePrimitive(new Date()) // Returns: \"[Date: 2023-05-01T00:00:00.000Z]\"\n * serializePrimitive({}) // Returns: null (complex objects not handled)\n * ```\n *\n * @see serialize - For complete object serialization including complex objects\n *\n * @since 1.0.0\n */\n\nexport function serializePrimitive(element: unknown): string | null {\n if (typeof element === 'string') return element.includes('\\n') ? null : `\"${ element }\"`;\n if (typeof element === 'number') return `${ Number.isFinite(element) ? element : element.toString() }`;\n if (typeof element === 'boolean') return `${ element }`;\n if (typeof element === 'symbol') return `${ element.toString() }`;\n if (typeof element === 'bigint') return `${ element }n`;\n if (typeof element === 'function') return `[Function: ${ element.name || 'anonymous' }]`;\n\n if (element === null) return 'null';\n if (element === undefined) return 'undefined';\n if (isAsymmetric(element)) return element.expectedLabel ?? element.constructor.name;\n if (element instanceof Date) return `[Date: ${ element.toISOString() }]`;\n if (element instanceof RegExp) return element.toString();\n if (element instanceof Error) return `[${ element.name }: ${ element.message }]`;\n if (element instanceof Promise) return '[Promise <pending>]';\n if (element instanceof ArrayBuffer) return `ArrayBuffer { byteLength: ${ element.byteLength } }`;\n if (element instanceof DataView) {\n return `DataView { byteLength: ${ element.byteLength }, byteOffset: ${ element.byteOffset } }`;\n }\n\n return null;\n}\n\n/**\n * Provides a string representation of Map keys for serialization purposes.\n *\n * @param key - The Map key to be converted to a string\n * @returns A consistent string representation of the key\n *\n * @remarks\n * This utility function ensures consistent string representation of Map keys\n * when serializing Map objects for display or comparison purposes:\n *\n * - Special handling for null and undefined values\n * - Uses class/type information for object keys via Object.prototype.toString\n * - Properly quotes and escapes string values using JSON.stringify\n *\n * The function is particularly useful when working with Maps containing\n * complex keys that need to be represented in a human-readable format.\n *\n * @example\n * ```ts\n * // When serializing a Map:\n * const map = new Map([[{id: 1}, 'value'], ['key2', 123]]);\n *\n * const entries = Array.from(map.entries()).map(([key, value]) => {\n * return `${serializeMapKey(key)} => ${serializePrimitive(value) || '...'}`;\n * });\n *\n * // Results in: [\"[object Object] => \\\"value\\\"\", \"\\\"key2\\\" => 123\"]\n * ```\n *\n * @see serialize - For complete object serialization\n *\n * @since 1.0.0\n */\n\nexport function serializeMapKey(key: unknown): string {\n if (key === null) return 'null';\n if (key === undefined) return 'undefined';\n if (typeof key === 'object') return Object.prototype.toString.call(key);\n\n return JSON.stringify(key);\n}\n\n/**\n * Appends formatted lines from a source array to a target array with proper indentation and separators.\n *\n * @param source - Array of strings to be appended\n * @param target - Array where the formatted lines will be added\n * @param key - Prefix to be added to the first line\n * @param isLast - Whether this is the last element in a sequence (affects comma placement)\n * @param indent - String used for indentation (default is empty string)\n * @returns void - Modifies the target array in place\n *\n * @remarks\n * This utility function handles the formatting logic when appending multi-line content\n * to a string array representation of a structured object. It properly handles:\n * - Adding the key prefix only to the first line\n * - Applying consistent indentation to all lines\n * - Adding trailing commas to non-last elements\n * - Special handling for single-line and empty source arrays\n *\n * The function is particularly useful for serializing object properties or array elements\n * that span multiple lines while maintaining proper structure formatting.\n *\n * @example\n * ```ts\n * const source = [\"{\", \" value: 42\", \"}\"];\n * const target = [];\n *\n * appendLines(source, target, \"property: \", false, \" \");\n * // Results in target containing:\n * // [\" property: {\", \" value: 42\", \" },\"]\n *\n * appendLines([\"simple\"], target, \"last: \", true, \" \");\n * // Adds: [\" last: simple\"]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function appendLines(source: Array<string>, target: Array<string>, key: string, isLast: boolean, indent: string = ''): void {\n if (source.length === 0) return;\n if (source.length < 2) {\n const last = `${ indent }${ key }${ source[source.length - 1] }`;\n target.push(isLast ? last : `${ last },`);\n\n return;\n }\n\n target.push(`${ indent }${ key }${ source[0] }`);\n for (let i = 1; i < source.length - 1; i++) {\n target.push(indent + source[i]);\n }\n\n const last = `${ indent }${ source[source.length - 1] }`;\n target.push(isLast ? last : `${ last },`);\n}\n\n/**\n * Serializes a JavaScript Map object into a multi-line string representation.\n *\n * @param map - The Map object to serialize\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @param seen - Set of objects that have already been serialized (used to detect circular references)\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts a Map object into a human-readable string representation\n * with proper formatting and indentation. The serialization process:\n *\n * 1. Handles empty Maps with a compact `Map {}` representation\n * 2. For non-empty Maps, creates a multi-line representation with each entry on separate lines\n * 3. Formats each entry as `key => value` with proper serialization of both key and value\n * 4. Preserves complex structure of nested values through recursive serialization\n * 5. Applies consistent indentation for nested structures\n *\n * The output format is similar to Node.js console.log representation of Maps\n * but with enhanced formatting for nested structures.\n *\n * @example\n * ```ts\n * const map = new Map([\n * [\"key1\", \"value1\"],\n * [42, {nested: true}]\n * ]);\n * const result = [];\n *\n * serializeMap(map, result, \" \");\n * // the result now contains:\n * // [\"Map {\",\n * // \"\\\"key1\\\" => \\\"value1\\\",\",\n * // \"42 => {\",\n * // \" nested: true\",\n * // \"}\",\n * // \"}\"]\n * ```\n *\n * @see serializeMapKey - Function used to serialize Map keys\n * @see serializeValue - Function used to serialize Map values\n * @see appendLines - Helper for handling multi-line formatting\n *\n * @since 1.0.0\n */\n\nexport function serializeMap(map: Map<unknown, unknown>, lines: Array<string>, indent: string, seen: WeakSet<object>): void {\n if (map.size === 0) {\n lines.push('Map {}');\n\n return;\n }\n\n lines.push('Map {');\n const entries = Array.from(map.entries());\n entries.forEach(([ key, val ], i) => {\n const keyStr = serializeMapKey(key);\n const subLines: Array<string> = [];\n serializeValue(val, subLines, indent, seen);\n appendLines(subLines, lines, `${ keyStr } => `, i === entries.length - 1, indent);\n });\n lines.push('}');\n}\n\n/**\n * Serializes a JavaScript array into a multi-line string representation.\n *\n * @param arr - The array to be serialized\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @param seen - Set of objects that have already been serialized (used to detect circular references)\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts an array into a human-readable string representation\n * with proper formatting and indentation. The serialization follows these rules:\n *\n * 1. Empty arrays are represented as the compact string \"Array []\"\n * 2. Non-empty arrays are formatted with each element on a separate line\n * 3. Each element is properly serialized based on its type\n * 4. Nested structures (objects, arrays, maps) maintain consistent indentation\n * 5. The format is similar to Node.js console.log representation but with enhanced readability\n *\n * The function is designed to work with arrays containing elements of any type,\n * including complex nested structures, by recursively serializing each element.\n *\n * @example\n * ```ts\n * const array = [1, \"text\", {a: true}, [2, 3]];\n * const result = [];\n *\n * serializeArray(array, result, \" \");\n * // the result now contains:\n * // [\"Array [\",\n * // \"1,\",\n * // \"\\\"text\\\",\",\n * // \"{\",\n * // \" a: true\",\n * // \"},\",\n * // \"Array [\",\n * // \" 2,\",\n * // \" 3\",\n * // \"]\",\n * // \"]\"]\n * ```\n *\n * @see serializeValue - Function used to serialize individual array elements\n * @see appendLines - Helper for handling multi-line formatting\n *\n * @since 1.0.0\n */\n\nexport function serializeArray(arr: Array<unknown>, lines: Array<string>, indent: string, seen: WeakSet<object>): void {\n if (arr.length === 0) {\n lines.push('[]');\n\n return;\n }\n\n lines.push('[');\n arr.forEach((item, i) => {\n const subLines: Array<string> = [];\n serializeValue(item, subLines, indent, seen);\n appendLines(subLines, lines, '', i === arr.length - 1, indent);\n });\n lines.push(']');\n}\n\n/**\n * Serializes a JavaScript Set object into a multi-line string representation.\n *\n * @param set - The Set object to serialize\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @param seen - Set of objects that have already been serialized (used to detect circular references)\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts a Set object into a human-readable string representation\n * with proper formatting and indentation. The serialization process:\n *\n * 1. Handles empty Sets with a compact `Set {}` representation\n * 2. For non-empty Sets, creates a multi-line representation with each value on separate lines\n * 3. Properly serializes each value based on its type\n * 4. Preserves complex structure of nested values through recursive serialization\n * 5. Applies consistent indentation for nested structures\n *\n * Since Sets maintain insertion order in JavaScript, the serialized output will\n * reflect this order, displaying elements in the sequence they were added to the Set.\n *\n * @example\n * ```ts\n * const set = new Set([1, \"text\", {a: true}, [2, 3]]);\n * const result = [];\n *\n * serializeSet(set, result, \" \");\n * // the result now contains:\n * // [\"Set {\",\n * // \"1,\",\n * // \"\\\"text\\\",\",\n * // \"{\",\n * // \" a: true\",\n * // \"},\",\n * // \"Array [\",\n * // \" 2,\",\n * // \" 3\",\n * // \"]\",\n * // \"}\"]\n * ```\n *\n * @see serializeValue - Function used to serialize individual Set values\n * @see appendLines - Helper for handling multi-line formatting\n *\n * @since 1.0.0\n */\n\nexport function serializeSet(set: Set<unknown>, lines: Array<string>, indent: string, seen: WeakSet<object>): void {\n if (set.size === 0) {\n lines.push('Set {}');\n\n return;\n }\n\n lines.push('Set {');\n const arr = Array.from(set);\n arr.forEach((item, i) => {\n const subLines: Array<string> = [];\n serializeValue(item, subLines, indent, seen);\n appendLines(subLines, lines, '', i === arr.length - 1, indent);\n });\n lines.push('}');\n}\n\n/**\n * Serializes a Node.js Buffer object into a multi-line string representation.\n *\n * @param arr - The Buffer object to serialize\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts a Buffer object into a human-readable string representation\n * with proper formatting and indentation. The serialization process:\n *\n * 1. Handles empty Buffers with a compact `Buffer {}` representation\n * 2. For non-empty Buffers, creates a multi-line representation with each byte value on separate lines\n * 3. Shows numeric byte values without any conversion to characters\n * 4. Adds trailing commas to all bytes except the last one\n * 5. Maintains a consistent indentation level for all byte values\n *\n * The function first converts the Buffer to an array of numeric values to ensure\n * consistent handling of byte data regardless of the Buffer implementation.\n *\n * @example\n * ```ts\n * const buffer = Buffer.from([104, 101, 108, 108, 111]); // \"hello\" in ASCII\n * const result = [];\n *\n * serializeBuffer(buffer, result, \" \");\n * // the result now contains:\n * // [\"Buffer {\",\n * // \" 104,\",\n * // \" 101,\",\n * // \" 108,\",\n * // \" 108,\",\n * // \" 111\",\n * // \"}\"]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeBuffer(arr: Buffer, lines: Array<string>, indent: string): void {\n const values = Array.from(arr as unknown as Array<number>);\n if (values.length === 0) {\n lines.push('Buffer {}');\n\n return;\n }\n\n lines.push('Buffer {');\n for (let i = 0; i < values.length; i++) {\n const val = values[i];\n const comma = i === values.length - 1 ? '' : ',';\n\n lines.push(`${ indent }${ val }${ comma }`);\n }\n lines.push('}');\n}\n\n/**\n * Serializes a JavaScript TypedArray object into a multi-line string representation.\n *\n * @param arr - The ArrayBufferView (TypedArray) object to serialize\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts any TypedArray (such as Int8Array, Uint8Array, Float32Array, etc.)\n * into a human-readable string representation with proper formatting and indentation.\n * The serialization process:\n *\n * 1. Dynamically determines the specific TypedArray type using Object.prototype.toString\n * 2. Handles empty TypedArrays with a compact `{TypeName} []` representation\n * 3. For non-empty TypedArrays, creates a multi-line representation with each numeric value on separate lines\n * 4. Adds trailing commas to all values except the last one\n * 5. Maintains consistent indentation for all values\n *\n * The function first converts the TypedArray to a standard array of numeric values\n * to ensure consistent handling across different TypedArray implementations.\n *\n * @example\n * ```ts\n * const int32Array = new Int32Array([42, 100, -5]);\n * const result = [];\n *\n * serializeTypedArray(int32Array, result, \" \");\n * // the result now contains:\n * // [\"Int32Array [\",\n * // \" 42,\",\n * // \" 100,\",\n * // \" -5\",\n * // \"]\"]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeTypedArray(arr: ArrayBufferView, lines: Array<string>, indent: string): void {\n const name = Object.prototype.toString.call(arr).slice(8, -1);\n const values = Array.from(arr as unknown as Array<number>);\n if (values.length === 0) {\n lines.push(`${ name } []`);\n\n return;\n }\n\n lines.push(`${ name } [`);\n for (let i = 0; i < values.length; i++) {\n const val = values[i];\n const comma = i === values.length - 1 ? '' : ',';\n\n lines.push(`${ indent }${ val }${ comma }`);\n }\n lines.push(']');\n}\n\n/**\n * Serializes a JavaScript object into a multi-line string representation.\n *\n * @param obj - The object to serialize\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures\n * @param seen - Set of objects that have already been serialized (used to detect circular references)\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function converts an object into a human-readable string representation\n * with proper formatting and indentation. The serialization process:\n *\n * 1. Includes the constructor name in the output (e.g., `Date {}` instead of just `{}`)\n * 2. Falls back to \"Object\" if the constructor is not available or is the base Object constructor\n * 3. Handles empty objects with a compact `{ConstructorName} {}` representation\n * 4. For non-empty objects, creates a multi-line representation with each property on separate lines\n * 5. Formats each property as \"key: value\" with proper indentation\n * 6. Serializes property values recursively to handle nested objects and complex values\n *\n * The function uses Object.entries() to list own enumerable properties,\n * which means non-enumerable properties and those in the prototype chain will not be included.\n *\n * @example\n * ```ts\n * const object = {\n * name: \"example\",\n * count: 42,\n * nested: { flag: true }\n * };\n * const result = [];\n *\n * serializeObject(object, result, \" \");\n * // the result now contains:\n * // [\"Object {\",\n * // \" name: \\\"example\\\",\",\n * // \" count: 42,\",\n * // \"nested: Object {\",\n * // \" flag: true\",\n * // \" }\",\n * // \"}\"]\n * ```\n *\n * @see serializeValue - Function used to serialize property values\n * @see appendLines - Helper for handling multi-line formatting\n *\n * @since 1.0.0\n */\n\nexport function serializeObject(obj: object, lines: Array<string>, indent: string, seen: WeakSet<object>): void {\n const name = obj.constructor && obj.constructor !== Object ? obj.constructor.name : 'Object';\n const entries = Object.entries(obj);\n if (entries.length === 0) {\n lines.push(`${ name } {}`);\n\n return;\n }\n\n lines.push(`${ name } {`);\n entries.forEach(([ key, val ], i) => {\n const subLines: Array<string> = [];\n serializeValue(val, subLines, indent, seen);\n appendLines(subLines, lines, `${ String(key) }: `, i === entries.length - 1, indent);\n });\n lines.push('}');\n}\n\n/**\n * Serializes any JavaScript value into a human-readable string representation.\n *\n * @param value - The value to serialize (can be of any type)\n * @param lines - Array of strings where the serialized representation will be added\n * @param indent - String used for indentation of nested structures (defaults to a predefined indent value)\n * @param seen - Set of objects that have already been serialized (used to detect circular references)\n * @returns void - Modifies the line's array in place\n *\n * @remarks\n * This function serves as the main entry point for the serialization system, dispatching\n * to specialized serializers based on the value type. The serialization process:\n *\n * 1. First attempts to serialize primitive values (null, undefined, booleans, numbers, symbols)\n * 2. Handles multi-line strings with special formatting - each line is properly indented\n * 3. Uses specialized serializers for common complex types:\n * - Maps\n * - Arrays\n * - Sets\n * - Buffers\n * - TypedArrays (Int8Array, Uint8Array, Float32Array, etc.)\n * 4. Falls back to object serialization for any other non-primitive values\n *\n * The function generates a clear, structured representation that maintains the\n * hierarchical relationships between nested objects and preserves type information.\n *\n * @example\n * ```ts\n * const complexValue = {\n * name: \"example\",\n * numbers: [1, 2, 3],\n * settings: new Map([[\"active\", true], [\"mode\", \"advanced\"]]),\n * data: new Uint8Array([10, 20, 30])\n * };\n *\n * const result = [];\n * serializeValue(complexValue, result);\n * // result contains a multi-line representation of the entire object structure\n * ```\n *\n * @see serializePrimitive - Helper for handling primitive values\n * @see serializeMap - Helper for serializing Map objects\n * @see serializeArray - Helper for serializing Arrays\n * @see serializeSet - Helper for serializing Sets\n * @see serializeBuffer - Helper for serializing Buffers\n * @see serializeTypedArray - Helper for serializing TypedArrays\n * @see serializeObject - Helper for serializing generic objects\n *\n * @since 1.0.0\n */\n\nexport function serializeValue(value: unknown, lines: Array<string>, indent: string = INDENT, seen: WeakSet<object>): void {\n const primitive = serializePrimitive(value);\n if (primitive !== null) {\n lines.push(primitive);\n\n return;\n }\n\n // Handle multi-line strings\n if (typeof value === 'string') {\n const stringLines = value.split('\\n');\n lines.push('String \"'); // opening quote line\n for (const line of stringLines) {\n lines.push(`${ indent }${ line }`);\n }\n lines.push('\"'); // closing quote line\n\n return;\n }\n\n if (typeof value === 'object' && value !== null) {\n if (seen.has(<object> value)) {\n lines.push('[Circular]');\n\n return;\n }\n\n seen.add(<object> value);\n\n if (value instanceof Map) {\n serializeMap(value, lines, indent, seen);\n } else if (Array.isArray(value)) {\n serializeArray(value, lines, indent, seen);\n } else if (value instanceof Set) {\n serializeSet(value, lines, indent, seen);\n } else if (value instanceof Buffer) {\n serializeBuffer(value, lines, indent);\n } else if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {\n serializeTypedArray(value, lines, indent);\n } else {\n serializeObject(value as object, lines, indent, seen);\n }\n\n return;\n }\n\n serializeObject(value as object, lines, indent, seen);\n}\n\n/**\n * Serializes an error object into a plain object containing its enumerable properties and common error fields.\n *\n * @param error - The error value to serialize.\n *\n * @returns A plain object with the error's enumerable properties and the `name`, `message`, and `stack` fields if available.\n * Returns the original value if it is not an object.\n *\n * @remarks\n * This function copies all own enumerable properties from the provided error,\n * ensuring that the `name`, `message`, and `stack` fields are preserved even if they are non-enumerable.\n * If the input is not an object, it is returned unchanged.\n *\n * @example\n * ```ts\n * const err = new Error('Something went wrong');\n * const serialized = serializeError(err);\n * // {\n * // name: 'Error',\n * // message: 'Something went wrong',\n * // stack: 'Error: Something went wrong\\n at ...'\n * // }\n *\n * const notAnError = 'oops';\n * serializeError(notAnError); // 'oops'\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeError(error: Record<string, unknown> | unknown): Record<string, unknown> | unknown {\n if (error && typeof error === 'object') {\n if('toJSON' in error && typeof error.toJSON === 'function') {\n return error.toJSON();\n }\n\n const json: Record<string, unknown> = {};\n\n for (const [ key, value ] of Object.entries(error)) {\n if (value !== undefined) {\n json[key] = value;\n }\n }\n\n json.name = (error as { name?: unknown })?.name ?? json.name;\n json.message = (error as { message?: unknown })?.message ?? json.message;\n json.stack = (error as { stack?: unknown })?.stack ?? json.stack;\n\n return json;\n }\n\n return error;\n}\n\n/**\n * Converts any JavaScript value into an array of strings representing its serialized form.\n *\n * @param element - The value to serialize (can be of any type)\n * @param indent - String used for indentation of nested structures (defaults to a predefined indent value)\n * @returns Array of strings containing the serialized representation\n *\n * @remarks\n * This function serves as a convenient public API for the serialization system.\n * It creates an empty array, delegates the actual serialization work to the\n * specialized `serializeValue` function, and returns the resulting array of\n * string lines.\n *\n * Each element in the returned array represents a single line in the serialized\n * output, with proper indentation and formatting already applied. This makes it\n * easy to either join the lines for display or process them individually.\n *\n * Unlike direct use of `serializeValue`, this function handles the creation and\n * management of the output array, simplifying the API for consumers.\n *\n * @example\n * ```ts\n * // Serialize a simple object\n * const obj = { name: \"example\", values: [1, 2, 3] };\n * const lines = serialize(obj);\n * console.log(lines.join('\\n'));\n * // Output:\n * // Object {\n * // name: \"example\",\n * // values: Array [\n * // 1,\n * // 2,\n * // 3\n * // ]\n * // }\n * ```\n *\n * @see serializeValue - The underlying function that performs the actual serialization\n *\n * @since 1.0.0\n */\n\nexport function serialize(element: unknown, indent: string = INDENT): Array<string> {\n const lines: Array<string> = [];\n serializeValue(element, lines, indent, new WeakSet());\n\n return lines;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ContextInterface, DiffSegmentType } from '@diff/providers/interfaces/string-provider.interface';\nimport type { FoundSubsequenceType, IsMatchType } from '@diff/providers/interfaces/string-provider.interface';\n\n/**\n * Enumeration of diff operation types representing delete, equal, and insert operations.\n *\n * @remarks\n * These values correspond to the standard diff operation convention:\n * - DELETE (-1): Content exists in the first sequence but not in the second.\n * - EQUAL (0): Content exists identically in both sequences.\n * - INSERT (1): Content exists in the second sequence but not in the first.\n *\n * @example\n * ```ts\n * const operation = DiffTypes.DELETE; // -1\n * const diffSegment = [DiffTypes.EQUAL, \"shared text\"]; // [0, \"shared text\"]\n * ```\n *\n * @since 1.0.0\n */\n\nexport const enum DiffTypes {\n DELETE = -1,\n EQUAL = 0,\n INSERT = 1,\n}\n\n/**\n * Counts the number of matching characters from the end positions of two sequences.\n *\n * @returns The count of matching characters in backward direction\n *\n * @remarks\n * This function works backwards from the end boundaries of both sequences\n * to find common suffix text. It is used to optimize the diff algorithm\n * by identifying and handling common suffixes separately.\n *\n * @example\n * ```ts\n * const context = {\n * aStart: 0, aEnd: text1.length,\n * bStart: 0, bEnd: text2.length,\n * isMatch: (i, j) => text1[i] === text2[j]\n * };\n * const suffixLength = countCommonBackward.call(context);\n * ```\n *\n * @since 1.0.0\n */\n\nfunction countCommonForward(this: ContextInterface): number {\n let count = 0;\n while (\n this.aStart + count < this.aEnd &&\n this.bStart + count < this.bEnd &&\n this.isMatch(this.aStart + count, this.bStart + count)\n ) {\n count++;\n }\n\n return count;\n}\n\n/**\n * Counts the number of matching characters from the end positions of two sequences.\n *\n * @returns The count of matching characters in backward direction\n *\n * @remarks\n * This function works backwards from the end boundaries of both sequences\n * to find common suffix text. It continues counting as long as characters match,\n * and the indices remain within the valid sequence bounds.\n *\n * @example\n * ```ts\n * const context = {\n * aStart: 0, aEnd: text1.length,\n * bStart: 0, bEnd: text2.length,\n * isMatch: (i, j) => text1[i] === text2[j]\n * };\n * const suffixLength = countCommonBackward.call(context);\n * ```\n *\n * @since 1.0.0\n */\n\nfunction countCommonBackward(this: ContextInterface): number {\n let count = 0;\n while (\n this.aEnd - 1 - count >= this.aStart &&\n this.bEnd - 1 - count >= this.bStart &&\n this.isMatch(this.aEnd - 1 - count, this.bEnd - 1 - count)\n ) {\n count++;\n }\n\n return count;\n}\n\n/**\n * Reconstructs the edit path from the trace matrix created during the Myers diff algorithm execution.\n *\n * @param trace - Array of vectors storing the x coordinates for each diagonal at each edit distance\n * @param offset - Offset value for indexing into the vectors (typically max edit distance)\n * @param dFinal - The final edit distance at which the end point was found\n *\n * @remarks\n * This function works by backtracking through the trace matrix, starting from the endpoint and\n * following the path back to the start. It reconstructs the sequence of operations (inserts,\n * deletes, and equals) needed to transform the first sequence into the second sequence.\n *\n * The backtracking process involves determining whether horizontal, vertical, or diagonal\n * movements were made in the edit graph, corresponding to insertions, deletions, or matches\n * respectively.\n *\n * @example\n * ```ts\n * const context = {\n * aStart: 0, aEnd: textA.length,\n * bStart: 0, bEnd: textB.length,\n * isMatch: (i, j) => textA[i] === textB[j],\n * foundSubsequence: (n, aIdx, bIdx) => { \\/* handle subsequence *\\/ }\n * };\n *\n * // During findMiddleSnake:\n * backtrackFlat.call(context, trace, max, dFinal);\n * ```\n *\n * @see findMiddleSnake\n * @see diffSequence\n *\n * @since 1.0.0\n */\n\nfunction backtrackFlat(this: ContextInterface, trace: Array<number[]>, offset: number, dFinal: number): void {\n let x = this.aEnd - this.aStart;\n let y = this.bEnd - this.bStart;\n const result: Array<[ number, number, number ]> = [];\n\n for (let d = dFinal; d > 0; d--) {\n const vPrev = trace[d - 1];\n const k = x - y;\n\n let prevK: number;\n const kMinus = vPrev[k - 1 + offset];\n const kPlus = vPrev[k + 1 + offset];\n\n if (k === -d || (k !== d && kMinus < kPlus)) {\n prevK = k + 1;\n } else {\n prevK = k - 1;\n }\n\n const prevKIndex = prevK + offset;\n const prevX = vPrev[prevKIndex];\n const prevY = prevX - prevK;\n\n // Diagonal: matching characters\n while (x > prevX && y > prevY) {\n --x;\n --y;\n result.push([ 1, this.aStart + x, this.bStart + y ]);\n }\n\n if (x === prevX) {\n result.push([ 0, this.aStart + prevX, this.bStart + prevY ]);\n } else {\n result.push([ 0, this.aStart + prevX, this.bStart + prevY ]);\n }\n\n x = prevX;\n y = prevY;\n }\n\n for (const item of result.reverse()) {\n this.foundSubsequence(...item);\n }\n}\n\n/**\n * Implements the central part of Myers' diff algorithm by finding the middle snake of the shortest edit script.\n *\n * @remarks\n * This function implements the core of the Myers diff algorithm. It works by:\n * 1. Computing the length of both sequences\n * 2. Iterating through possible edit distances (d)\n * 3. For each d, computing the furthest reaching paths along each diagonal k\n * 4. When the paths from opposite directions meet, a middle snake is found\n * 5. Calling backtrackFlat to reconstruct the edit path when end point is reached\n *\n * The algorithm uses a \"divide and conquer\" approach to find the shortest edit script\n * between two sequences efficiently, with worst-case time complexity of O((n+m)D).\n *\n * @example\n * ```ts\n * const context = {\n * aStart: 0, aEnd: text1.length,\n * bStart: 0, bEnd: text2.length,\n * isMatch: (i, j) => text1[i] === text2[j]\n * };\n * findMiddleSnake.call(context);\n * ```\n *\n * @see backtrackFlat\n * @see diffSequence\n *\n * @since 1.0.0\n */\n\nfunction findMiddleSnake(this: ContextInterface): void {\n const n = this.aEnd - this.aStart;\n const m = this.bEnd - this.bStart;\n const max = n + m;\n\n let dFinal = 0;\n const v = new Array(2 * max + 1).fill(0);\n const trace: Array<number[]> = [];\n\n for (let d = 0; d <= max; d++) {\n const vCopy = new Array(2 * max + 1);\n trace[d] = vCopy;\n\n for (let k = -d; k <= d; k += 2) {\n const kIndex = k + max;\n\n let x: number;\n if (k === -d || (k !== d && v[k - 1 + max] < v[k + 1 + max])) {\n x = v[k + 1 + max];\n } else {\n x = v[k - 1 + max] + 1;\n }\n\n let y = x - k;\n while (x < n && y < m && this.isMatch(this.aStart + x, this.bStart + y)) {\n x++;\n y++;\n }\n\n v[kIndex] = x;\n vCopy[kIndex] = x;\n if (x >= n && y >= m) {\n dFinal = d;\n\n return backtrackFlat.call(this, trace, max, dFinal);\n }\n }\n }\n}\n\n/**\n * Performs a diff operation between two sequences by implementing an optimized Myers algorithm.\n *\n * @remarks\n * This function efficiently computes the differences between two sequences by:\n * 1. First identifying common prefix and suffix elements to reduce the problem size\n * 2. Handling the special case where sequences are fully equal\n * 3. Adjusting sequence boundaries to exclude common prefix/suffix\n * 4. Applying the Myers diff algorithm via findMiddleSnake to find the shortest edit path\n * 5. Reporting common subsequences through the context's foundSubsequence method\n *\n * This optimization significantly improves performance for sequences with common\n * prefixes or suffixes, which is a common case in many text diff scenarios.\n *\n * @example\n * ```ts\n * const context = {\n * aStart: 0, aEnd: textA.length,\n * bStart: 0, bEnd: textB.length,\n * isMatch: (i, j) => textA[i] === textB[j],\n * foundSubsequence: (n, aIdx, bIdx) => { \\/* handle subsequence *\\/ }\n * };\n * diffSequence.call(context);\n * ```\n *\n * @since 1.0.0\n */\n\nexport function diffSequence(this: ContextInterface): void {\n const prefixLen = countCommonForward.call(this);\n const isFullyEqual = this.aStart + prefixLen >= this.aEnd && this.bStart + prefixLen >= this.bEnd;\n if (prefixLen > 0) {\n this.foundSubsequence(prefixLen, this.aStart, this.bStart);\n\n if (isFullyEqual) {\n return;\n }\n }\n\n this.aStart += prefixLen;\n this.bStart += prefixLen;\n\n const suffixLen = countCommonBackward.call(this);\n this.aEnd -= suffixLen;\n this.bEnd -= suffixLen;\n if (this.aStart < this.aEnd || this.bStart < this.bEnd) {\n findMiddleSnake.call(this);\n }\n\n if (suffixLen > 0) {\n this.foundSubsequence(suffixLen, this.aEnd, this.bEnd);\n }\n}\n\n/**\n * Creates and executes a diff operation between two sequences of elements.\n *\n * @param aLength - Length of the first sequence\n * @param bLength - Length of the second sequence\n * @param isMatch - Function that determines if elements at specified positions match\n * @param foundSubsequence - Callback function that processes found common subsequences\n *\n * @remarks\n * This function serves as a convenient wrapper around the core diff algorithm.\n * It constructs a context object with the provided parameters and invokes the\n * diff sequence calculation. The results are reported through the foundSubsequence\n * callback as common subsequences are identified.\n *\n * The comparison is performed using the provided isMatch function, allowing\n * for custom equality logic between sequence elements.\n *\n * @example\n * ```ts\n * createDiff(\n * textA.length,\n * textB.length,\n * (iA, iB) => textA[iA] === textB[iB],\n * (nCommon, aCommon, bCommon) => {\n * // Process the found common subsequence\n * }\n * );\n * ```\n *\n * @see diffSequence\n * @see ContextInterface\n *\n * @since 1.0.0\n */\n\nexport function createDiff(\n aLength: number, bLength: number, isMatch: IsMatchType, foundSubsequence: FoundSubsequenceType\n): void {\n const context: ContextInterface = {\n aStart: 0,\n bStart: 0,\n aEnd: aLength,\n bEnd: bLength,\n isMatch,\n foundSubsequence\n };\n\n diffSequence.call(context);\n}\n\n/**\n * Compares two strings and returns an array of diff operations.\n * Implements an optimized version of the Myers diff algorithm.\n *\n * @param a - First string to compare\n * @param b - Second string to compare\n * @returns Array of diff operations, where each operation is a tuple of [type, text]\n *\n * @throws Never throws exceptions but may produce unexpected results with invalid inputs\n *\n * @remarks\n * This function implements a highly optimized version of the Myers diff algorithm.\n * It efficiently finds the shortest edit script between two strings and\n * represents the differences as a series of delete, equal, and insert operations.\n *\n * @example\n * ```ts\n * const diff = diffStringsRaw('abc', 'abxc');\n * // Returns: [[0, 'ab'], [-1, 'c'], [1, 'xc']]\n * ```\n *\n * @see DiffSegmentType\n * @see ContextInterface\n * @since 1.0.0\n */\n\nexport function diffStringsRaw(a: string, b: string): Array<DiffSegmentType> {\n let aIndex = 0;\n let bIndex = 0;\n let pendingInsert = '';\n let pendingDelete = '';\n const diffs: Array<DiffSegmentType> = [];\n\n // Helper to merge with last diff if same type\n function pushDiff(type: DiffTypes, text: string): void {\n const last = diffs[diffs.length - 1];\n if (last && last[0] === type) {\n last[1] += text;\n } else {\n diffs.push([ type, text ]);\n }\n }\n\n createDiff(a.length, b.length, (iA: number, iB: number): boolean => {\n return a[iA] === b[iB];\n }, (nCommon: number, aCommon: number, bCommon: number): void => {\n if (aIndex !== aCommon) {\n pendingDelete += a.slice(aIndex, aCommon);\n }\n if (bIndex !== bCommon) {\n pendingInsert += b.slice(bIndex, bCommon);\n }\n\n if (nCommon > 0) {\n // Flush pending delete/insert together before equal\n if (pendingDelete) {\n pushDiff(DiffTypes.DELETE, pendingDelete);\n pendingDelete = '';\n }\n if (pendingInsert) {\n pushDiff(DiffTypes.INSERT, pendingInsert);\n pendingInsert = '';\n }\n\n // Push equal segment\n pushDiff(DiffTypes.EQUAL, b.slice(bCommon, bCommon + nCommon));\n }\n\n aIndex = aCommon + nCommon;\n bIndex = bCommon + nCommon;\n });\n\n // After the last common subsequence, push remaining change items.\n if (aIndex !== a.length) pendingDelete += a.slice(aIndex);\n if (bIndex !== b.length) pendingInsert += b.slice(bIndex);\n\n // Final flush\n if (pendingDelete) diffs.push([ DiffTypes.DELETE, pendingDelete ]);\n if (pendingInsert) diffs.push([ DiffTypes.INSERT, pendingInsert ]);\n\n return diffs;\n}\n\n/**\n * Compares two arrays of strings line by line and returns an array of diff operations.\n *\n * @param a - First array of strings (lines) to compare\n * @param b - Second array of strings (lines) to compare\n * @returns Array of diff operations, where each operation is a tuple of [type, text]\n *\n * @remarks\n * This function implements a line-by-line comparison algorithm that identifies differences\n * between two text arrays. The comparison is performed using strict equality between lines.\n *\n * The function produces a sequence of operations (delete, insert, equal) that represent\n * the minimal set of changes needed to transform the first array into the second array.\n * Each operation is represented as a tuple where:\n * - The first element is the operation type (-1 for delete, 0 for equal, 1 for insert)\n * - The second element is the affected line\n *\n * @example\n * ```ts\n * const result = diffLinesRaw(\n * ['line 1', 'line 2', 'line 3'],\n * ['line 1', 'new line', 'line 3']\n * );\n * // Returns: [[0, 'line 1'], [-1, 'line 2'], [1, 'new line'], [0, 'line 3']]\n * ```\n *\n * @see DiffTypes\n * @see DiffSegmentType\n *\n * @since 1.0.0\n */\n\nexport function diffLinesRaw(a: Array<string>, b: Array<string>): Array<DiffSegmentType> {\n let aIndex = 0;\n let bIndex = 0;\n const diffs: Array<DiffSegmentType> = [];\n\n createDiff(a.length, b.length, (iA: number, iB: number): boolean => {\n // Why do we do this?\n // When serializing objects, the last property does NOT have a trailing comma because that is a valid syntax.\n // For example,\n // { name: \"ssss\" }\n //\n // But if one object has an extra property, it will have a comma on the previous last property:\n // { name: \"ssss\", yyy: \"sdx\" }\n //\n // This means during diffing, one line might have a trailing comma and the other might not.\n // This causes false positives where the diff thinks lines differ when only the comma is missing.\n //\n // To fix this, if one line has a trailing comma but the other doesn't,\n // we add the missing comma to the line without it before comparing.\n // This normalizes the lines so the diff ignores trailing comma differences.\n\n const hasCommaA = a[iA].trimEnd().endsWith(',');\n const hasCommaB = b[iB].trimEnd().endsWith(',');\n\n if (hasCommaA && !hasCommaB) {\n b[iB] += ',';\n } else if (!hasCommaA && hasCommaB) {\n a[iA] += ',';\n }\n\n return a[iA] === b[iB];\n }, (nCommon: number, aCommon: number, bCommon: number): void => {\n for (; aIndex !== aCommon; aIndex += 1) {\n diffs.push([ DiffTypes.DELETE, a[aIndex] ]);\n }\n for (; bIndex !== bCommon; bIndex += 1) {\n diffs.push([ DiffTypes.INSERT, b[bIndex] ]);\n }\n for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) {\n diffs.push([ DiffTypes.EQUAL, b[bIndex] ]);\n }\n });\n\n // After the last common subsequence, push remaining change items.\n for (; aIndex !== a.length; aIndex += 1) {\n diffs.push([ DiffTypes.DELETE, a[aIndex] ]);\n }\n for (; bIndex !== b.length; bIndex += 1) {\n diffs.push([ DiffTypes.INSERT, b[bIndex] ]);\n }\n\n return diffs;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { DiffSegmentType } from '@diff/providers/interfaces/string-provider.interface';\n\n/**\n * Imports\n */\n\nimport { DiffTypes } from '@diff/providers/string.provider';\n\n/**\n * Improves the semantic meaning of a diff result by merging short equal segments into delete/insert\n * operations, making the diff more human-readable.\n *\n * @param diffs - Array of diff segments to process\n *\n * @returns A new array of diff segments with improved semantic meaning\n *\n * @remarks\n * This function handles cases where very short equal segments (1 character or less) are better\n * represented as part of delete/insert operations for improved readability. It maintains longer\n * equal segments (more than 1 character) as separate segments.\n *\n * The algorithm works by:\n * 1. Collecting delete and insert operations in buffers\n * 2. When encountering small equal segments (1 char or less), adding them to both buffers\n * 3. When encountering larger equal segments, flushing the buffers as separate operations\n *\n * @example\n * ```ts\n * const diffs = [\n * [DiffTypes.DELETE, 'te'],\n * [DiffTypes.EQUAL, 's'],\n * [DiffTypes.INSERT, 'a']\n * ];\n * const result = cleanupSemantic(diffs);\n * // Result: [[DiffTypes.DELETE, 'tes'], [DiffTypes.INSERT, 'as']]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function cleanupSemantic(diffs: Array<DiffSegmentType>): Array<DiffSegmentType> {\n let delBuf: string[] = [];\n let insBuf: string[] = [];\n const result: Array<DiffSegmentType> = [];\n\n const flushBuffers = (): void => {\n if (delBuf.length) {\n result.push([ DiffTypes.DELETE, delBuf.join('') ]);\n delBuf = [];\n }\n if (insBuf.length) {\n result.push([ DiffTypes.INSERT, insBuf.join('') ]);\n insBuf = [];\n }\n };\n\n for (let i = 0; i < diffs.length; i++) {\n const [ type, text ] = diffs[i];\n\n if (type === DiffTypes.EQUAL) {\n if (text.length <= 1) {\n const prevType = i > 0 ? diffs[i - 1][0] : null;\n const nextType = i + 1 < diffs.length ? diffs[i + 1][0] : null;\n const isEdit = (t: DiffTypes | null): boolean =>\n t === DiffTypes.DELETE || t === DiffTypes.INSERT;\n\n // Merge if surrounded by any edits (delete or insert)\n const surroundedByEdit = isEdit(prevType) && isEdit(nextType);\n\n if (surroundedByEdit) {\n for (const ch of text) {\n delBuf.push(ch);\n insBuf.push(ch);\n }\n continue;\n }\n }\n\n // Otherwise flush and keep equal\n flushBuffers();\n result.push([ DiffTypes.EQUAL, text ]);\n } else if (type === DiffTypes.DELETE) {\n for (const ch of text) delBuf.push(ch);\n } else if (type === DiffTypes.INSERT) {\n for (const ch of text) insBuf.push(ch);\n } else {\n flushBuffers();\n result.push([ type, text ]);\n }\n }\n\n flushBuffers();\n\n return result;\n}\n", "/**\n * Imports\n */\n\nimport { xterm } from '@remotex-labs/xansi';\n\n/**\n * Formats text with dimmed styling for less emphasized content.\n *\n * @param text - The text to format with dim styling\n * @returns The text wrapped with ANSI dim styling codes\n *\n * @since 1.0.0\n */\n\nexport const DIM = xterm.dim;\n\n/**\n * Formats text with light orange highlighting for important values.\n *\n * @param text - The text to format in lightOrange\n * @returns The text wrapped with ANSI light orange styling codes\n *\n * @since 1.0.0\n */\n\nexport const MARK = xterm.lightOrange;\n\n/**\n * Formats text in red, typically used for labeling received/actual values.\n *\n * @param text - The text to format in red\n * @returns The text wrapped with ANSI red styling codes\n *\n * @since 1.0.0\n */\n\nexport const RECEIVED = xterm.lightCoral;\n\n/**\n * Formats text in green, typically used for labeling expected values.\n *\n * @param text - The text to format in green\n * @returns The text wrapped with ANSI green styling codes\n *\n * @since 1.0.0\n */\n\nexport const EXPECTED = xterm.oliveGreen;\n\n/**\n * Formats text in cyan color.\n *\n * @param text - The text to format in cyan\n * @returns The text wrapped with ANSI cyan styling codes\n *\n * @since 1.0.0\n */\n\nexport const CYAN = xterm.cyan;\n\n/**\n * Formats text with inverse styling (swapping foreground and background colors).\n *\n * @param text - The text to format with inverse styling\n * @returns The text wrapped with ANSI inverse styling codes\n *\n * @since 1.0.0\n */\n\nexport const INVERSE = xterm.inverse;\n\n/**\n * Formats text with bright white styling, typically used for titles or headings.\n *\n * @param text - The text to format in bright white\n * @returns The text wrapped with ANSI bright white styling codes\n *\n * @since 1.0.0\n */\n\nexport const TITLE = xterm.whiteBright;\n", "/**\n * Imports\n */\n\nimport { serialize } from '@components/serialize.component';\nimport { cleanupSemantic } from '@diff/components/semantic.component';\nimport { asymmetricMatch, isAsymmetric } from '@components/object.component';\nimport { CYAN, DIM, EXPECTED, INVERSE, RECEIVED } from '@components/color.component';\nimport { diffLinesRaw, diffStringsRaw, DiffTypes } from '@diff/providers/string.provider';\n\n/**\n * Determines the type of any JavaScript value as a string representation.\n *\n * @param value - The value whose type should be determined\n * @returns A string representing the type of the value\n *\n * @remarks\n * This function provides a more detailed type description than JavaScript's built-in\n * `typeof` operator by also identifying specific object types through their constructor\n * names. The function handles special cases:\n *\n * - For `null`, it returns the string \"null\" (unlike `typeof` which returns \"object\")\n * - For primitive types (string, number, boolean, undefined), it returns the standard typeof result\n * - For objects, it returns the constructor name when available (e.g., \"Array\", \"Map\", \"Set\", \"Date\")\n * - For objects with missing or invalid constructor information, it falls back to \"Object\"\n *\n * This makes the function particularly useful for debugging, error messages, and\n * test frameworks where precise type identification helps diagnose issues.\n *\n * @example\n * ```ts\n * getType(null); // \"null\"\n * getType(undefined); // \"undefined\"\n * getType(42); // \"number\"\n * getType(\"hello\"); // \"string\"\n * getType(true); // \"boolean\"\n * getType([1, 2, 3]); // \"Array\"\n * getType(new Map()); // \"Map\"\n * getType(new Date()); // \"Date\"\n * getType({}); // \"Object\"\n * getType(Object.create(null)); // \"Object\" (no constructor)\n * ```\n *\n * @since 1.0.0\n */\n\nexport function getType(value: unknown): string {\n if (value === null) return 'null';\n if (value === true) return 'true';\n if (value === false) return 'false';\n\n return value && typeof value === 'object' ? value.constructor?.name ?? 'Object' : typeof value;\n}\n\n/**\n * Normalizes two strings by computing a semantic diff and marking differences with inverse formatting.\n *\n * This function uses a raw diff algorithm followed by semantic cleanup to align matching parts,\n * then inverts added or removed segments to visually highlight differences.\n *\n * @param a - The first string to normalize.\n * @param b - The second string to normalize.\n * @param clean - Whether to apply semantic cleanup to diffs for improved readability\n * @returns A tuple of strings with aligned and marked differences.\n *\n * @remarks\n * - The result uses `INVERSE` formatting for added or removed segments.\n * - Matching segments are preserved as-is.\n * - Empty strings are replaced with a tab (`\\t`) to ensure diffing is stable.\n *\n * @example\n * ```ts\n * const [a, b] = normalizeStrings(\"hello\", \"hallo\");\n * // a: \"h\\u001b[7me\\u001b[27mllo\"\n * // b: \"h\\u001b[7ma\\u001b[27mllo\"\n * ```\n *\n * @since 1.0.0\n */\n\nexport function normalizeStrings(a: string, b: string, clean: boolean = true): [ string, string ] {\n let resultA = '';\n let resultB = '';\n let diffs = diffStringsRaw(a || '\\t', b || '\\t');\n if (clean) diffs = cleanupSemantic(diffs);\n\n for (const [ type, text ] of diffs) {\n if (type === DiffTypes.EQUAL) {\n resultA += text;\n resultB += text;\n } else if (type === DiffTypes.DELETE) {\n resultA += INVERSE(text);\n } else if (type === DiffTypes.INSERT) {\n resultB += INVERSE(text);\n }\n }\n\n return [ resultA, resultB ];\n}\n\n/**\n * Recursively normalizes two arrays by aligning each element.\n *\n * The function mutates both input arrays in-place, recursively normalizing\n * each pair of elements by index. If arrays differ in length, undefined\n * elements will be normalized as well.\n *\n * @param a - The first array to normalize.\n * @param b - The second array to normalize.\n * @returns A tuple containing the normalized arrays.\n *\n * @remarks\n * - Elements are normalized using {@link normalizeAsymmetric}.\n * - The result is the same reference as the original arrays, modified in-place.\n * - The resulting arrays will have the same length, equal to the longer of the two.\n *\n * @example\n * ```ts\n * const [a, b] = normalizeArrays([1, 2], [1, xExpect.any(Number)]);\n * // a: [1, 2]\n * // b: [1, 2]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function normalizeArrays(a: Array<unknown>, b: Array<unknown>): [ Array<unknown>, Array<unknown> ] {\n const aResult = [ ...a ];\n const bResult = [ ...b ];\n\n const len = Math.max(a.length, b.length);\n for (let i = 0; i < len; i++) {\n [ aResult[i], bResult[i] ] = normalizeAsymmetric(a[i], b[i]);\n }\n\n return [ aResult, bResult ];\n}\n\n/**\n * Recursively normalizes two objects by aligning values at shared keys.\n *\n * The function mutates both input objects in-place, normalizing values\n * only for keys that exist in both objects. Missing keys are ignored.\n *\n * @param a - The first object to normalize.\n * @param b - The second object to normalize.\n * @returns A tuple containing the normalized objects.\n *\n * @remarks\n * - Values are normalized using {@link normalizeAsymmetric}.\n * - Only keys present in both `a` and `b` are processed.\n * - Keys present in one object but not the other are left untouched.\n * - The function operates recursively on nested objects.\n *\n * @example\n * ```ts\n * const objA = { foo: xExpect.any(String), bar: 42 };\n * const objB = { foo: \"hello\", bar: 42 };\n *\n * const [a, b] = normalizeObjects(objA, objB);\n * // a: { foo: \"hello\", bar: 42 }\n * // b: { foo: \"hello\", bar: 42 }\n * ```\n *\n * @since 1.0.0\n */\n\nexport function normalizeObjects(a: Record<string, unknown>, b: Record<string, unknown>): [ Record<string, unknown>, Record<string, unknown> ] {\n const aResult = { ...a };\n const bResult = { ...b };\n\n const keys = new Set([ ...Object.keys(a), ...Object.keys(b) ]);\n for (const key of keys) {\n if (key in a && key in b) {\n [ aResult[key], bResult[key] ] = normalizeAsymmetric(a[key], b[key]);\n }\n }\n\n return [ aResult, bResult ];\n}\n\n/**\n * Creates a colored, human-readable unified diff between two strings.\n *\n * @param a - The first string (original content) to compare\n * @param b - The second string (modified content) to compare\n * @param clean - Whether to apply semantic cleanup to diffs for improved readability\n * @returns A formatted string containing the unified diff representation\n *\n * @remarks\n * This function generates a git-style unified diff output with syntax highlighting\n * for easy readability. It processes the input strings as follows:\n *\n * 1. Splits both strings into lines\n * 2. Adds a unified diff header showing line counts\n * 3. For each line pair:\n * - Unchanged lines are shown dimmed with a leading space\n * - Changed lines are analyzed character by character\n * - Removed content is highlighted in green with a leading \"-\"\n * - Added content is highlighted in red with a leading \"+\"\n * - Changed portions within lines are additionally inverted for emphasis\n *\n * The result array is populated with formatted lines and then joined with newlines\n * to create the final string output.\n *\n * @example\n * ```ts\n * const original = \"line one\\nline two\\nline three\";\n * const modified = \"line one\\nmodified line\\nline three\";\n * const result = [];\n *\n * const diffOutput = diffStrings(original, modified, result);\n * console.log(diffOutput);\n * // Output will be a colored diff showing:\n * // @@ -1,3 +1,3 @@\n * // line one\n * // - line two\n * // + modified line\n * // line three\n * ```\n *\n * @see diffStringsRaw - The underlying function that generates the raw diff data\n * @see DiffTypes - Enum defining the types of diff operations\n *\n * @since 1.0.0\n */\n\nexport function normalizeAsymmetric(a: unknown, b: unknown, clean: boolean = true): [ unknown, unknown ] {\n if (a === b) return [ a, b ];\n\n const aType = typeof a;\n const bType = typeof b;\n const match = asymmetricMatch(a, b);\n if (match === true) {\n if (isAsymmetric(a)) a = b;\n if (isAsymmetric(b)) b = a;\n\n return [ a, b ];\n }\n\n if (aType === 'string' && bType === 'string') return normalizeStrings(<string> a, <string> b, clean);\n if (!a || !b || aType !== 'object' || bType !== 'object') {\n return [ a, b ];\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n return normalizeArrays(a, b);\n }\n\n return normalizeObjects(a as Record<string, unknown>, b as Record<string, unknown>);\n}\n\n/**\n * Creates a colored, human-readable unified diff between two strings.\n *\n * @param a - The first string (original content) to compare\n * @param b - The second string (modified content) to compare\n * @param result - Array that will be populated with formatted diff output lines\n * @param clean - Whether to apply semantic cleanup to diffs for improved readability\n * @returns A formatted string containing the unified diff representation\n *\n * @remarks\n * This function generates a git-style unified diff output with syntax highlighting\n * for easy readability. It processes the input strings as follows:\n *\n * 1. Splits both strings into lines\n * 2. Adds a unified diff header showing line counts\n * 3. For each line pair:\n * - Unchanged lines are shown dimmed with a leading space\n * - Changed lines are analyzed character by character\n * - Removed content is highlighted in green with a leading \"-\"\n * - Added content is highlighted in red with a leading \"+\"\n * - Changed portions within lines are additionally inverted for emphasis\n *\n * The result array is populated with formatted lines and then joined with newlines\n * to create the final string output.\n *\n * @example\n * ```ts\n * const original = \"line one\\nline two\\nline three\";\n * const modified = \"line one\\nmodified line\\nline three\";\n * const result = [];\n *\n * const diffOutput = diffStrings(original, modified, result);\n * console.log(diffOutput);\n * // Output will be a colored diff showing:\n * // @@ -1,3 +1,3 @@\n * // line one\n * // - line two\n * // + modified line\n * // line three\n * ```\n *\n * @see diffStringsRaw - The underlying function that generates the raw diff data\n * @see DiffTypes - Enum defining the types of diff operations\n *\n * @since 1.0.0\n */\n\nexport function diffStrings(a: string, b: string, result: Array<string>, clean: boolean = true): string {\n const aLines = a.split('\\n');\n const bLines = b.split('\\n');\n result.push(CYAN(`\\n@@ -1,${ aLines.length } +1,${ bLines.length } @@\\n`));\n\n const max = Math.max(aLines.length, bLines.length);\n for (let i = 0; i < max; i++) {\n const lineA = aLines[i];\n const lineB = bLines[i];\n\n if (lineA === lineB) {\n if (lineA) result.push(DIM(` ${ lineA }`));\n continue;\n }\n\n const expectedLine = [];\n const receivedLine = [];\n\n if (lineA !== undefined && lineB !== undefined) {\n let diffs = diffStringsRaw(lineA || '\\t', lineB || '\\t');\n if (clean) diffs = cleanupSemantic(diffs);\n\n for (const [ type, text ] of diffs) {\n if (type === DiffTypes.EQUAL) {\n expectedLine.push(text);\n receivedLine.push(text);\n } else if (type === DiffTypes.DELETE) {\n expectedLine.push(INVERSE(text));\n } else if (type === DiffTypes.INSERT) {\n receivedLine.push(INVERSE(text));\n }\n }\n }\n\n if (lineA === undefined) receivedLine.push(lineB);\n if (!lineB === undefined) expectedLine.push(lineA);\n\n if (expectedLine.length > 0) result.push(EXPECTED(`- ${ expectedLine.join('') }`));\n if (receivedLine.length > 0) result.push(RECEIVED(`+ ${ receivedLine.join('') }`));\n }\n\n return result.join('\\n');\n}\n\n/**\n * Produces a colorized diff between two argument lists, handling asymmetric values and trailing commas.\n *\n * @param a - The expected value or argument list.\n * @param b - The received value or argument list.\n * @returns An array of strings representing the colorized diff, with:\n * - Equal values dimmed using {@link DIM}.\n * - Inserted (extra) values highlighted using {@link RECEIVED}.\n * - Trailing commas preserved and appended after diff highlighting.\n *\n * @remarks\n * - Both `a` and `b` are normalized using {@link normalizeAsymmetric} to support asymmetric matchers.\n * - Values are serialized via {@link serialize}.\n * - Uses {@link diffLinesRaw} to compute differences.\n * - This function ensures that commas at the end of values are preserved but not highlighted.\n *\n * @example\n * ```ts\n * const expected = [1, 2];\n * const received = [1, 3];\n *\n * console.log(diffArgs(expected, received));\n * // Output (with ANSI colors):\n * // [\n * // '\\x1B[2m1\\x1B[22m,',\n * // '\\x1B[31m3\\x1B[39m'\n * // ]\n * ```\n *\n * @example\n * ```ts\n * // Works with trailing commas\n * const expected = [4, \"x\"];\n * const received = [4, \"y\"];\n *\n * console.log(diffArgs(expected, received));\n * // [\n * // '\\x1B[2m4\\x1B[22m,',\n * // '\\x1B[31m\"y\"\\x1B[39m'\n * // ]\n * ```\n *\n * @since 1.0.0\n */\n\nexport function diffArgs(a: unknown, b: unknown): Array<string> {\n const result: Array<string> = [];\n\n [ a, b ] = normalizeAsymmetric(a, b, true);\n const aLines = serialize(a, '');\n const bLines = serialize(b, '');\n\n const diffs = diffLinesRaw(aLines, bLines);\n for (const [ type, line ] of diffs) {\n let value = line;\n let comma = '';\n\n if (value.endsWith(',')) {\n value = value.slice(0, -1);\n comma = ',';\n }\n\n if (type === DiffTypes.EQUAL) result.push(DIM(value) + comma);\n else if (type === DiffTypes.INSERT) result.push(RECEIVED(value) + comma);\n }\n\n return result;\n}\n\n/**\n * Creates a formatted, colored diff representation between any two JavaScript values.\n *\n * @param a - The expected value to compare\n * @param b - The received value to compare\n * @param clean - Whether to apply semantic cleanup to diffs for improved readability\n * @returns A formatted string containing the diff representation with colored highlighting\n *\n * @remarks\n * This versatile diff function can compare any JavaScript values, intelligently handling\n * different types of data:\n *\n * 1. It first identifies and displays the types of both values\n * 2. For string values, it generates a character-level diff with highlighted changes\n * 3. For all other values, it serializes them into string representations and creates a line-by-line diff\n *\n * The output is formatted similar to git's unified diff format with:\n * - A header showing expected and received types\n * - A unified diff header (`@@ -1,n +1,m @@`) showing line counts\n * - Line prefixes that indicate unchanged lines (dimmed with two spaces)\n * - Line prefixes that indicate removed lines (green with a \"-\" prefix)\n * - Line prefixes that indicate added lines (red with a \"+\" prefix)\n *\n * This function is particularly useful for test frameworks to visualize the differences\n * between expected and actual values in assertion failures.\n *\n * @example\n * ```ts\n * // Comparing two objects\n * const expected = { name: \"test\", value: 123 };\n * const received = { name: \"test\", value: 456 };\n *\n * console.log(diffComponent(expected, received));\n * // Output will include:\n * // Expected: Object\n * // Received: Object\n * // @@ -1,4 +1,4 @@\n * // Object {\n * // name: \"test\",\n * // - value: 123\n * // + value: 456\n * // }\n * ```\n *\n * @see diffStrings - Function used for string-to-string comparison\n * @see diffLinesRaw - Function used for line-by-line comparison of serialized values\n * @see getType - Function used to determine the types of input values\n * @see serialize - Function used to convert values to string representations\n *\n * @since 1.0.0\n */\n\nexport function diffComponent(a: unknown, b: unknown, clean: boolean = true): string {\n const aType = getType(a);\n const bType = getType(b);\n const result: Array<string> = [];\n\n if (aType !== bType) {\n result.push('Expected type: ' + EXPECTED(aType));\n result.push('Received type: ' + RECEIVED(bType));\n }\n\n if (aType === 'string' && bType === 'string') {\n return diffStrings(<string>a, <string>b, result, clean);\n }\n\n const [ aNormalize, bNormalize ] = normalizeAsymmetric(a, b, clean);\n const aLines = serialize(aNormalize);\n const bLines = serialize(bNormalize);\n result.push(CYAN(`\\n@@ -1,${ aLines.length } +1,${ bLines.length } @@\\n`));\n\n const diffs = diffLinesRaw(aLines, bLines);\n for (const [ type, line ] of diffs) {\n if (type === DiffTypes.EQUAL) result.push(DIM(` ${ line }`));\n else if (type === DiffTypes.DELETE) result.push(EXPECTED(`- ${ line }`));\n else if (type === DiffTypes.INSERT) result.push(RECEIVED(`+ ${ line }`));\n }\n\n return result.join('\\n');\n}\n", "/**\n * Base abstract error class for all xJet-specific errors\n *\n * Extends the native `Error` class with improved stack trace handling\n * and serialization capabilities for better error reporting.\n *\n * @remarks\n * This class serves as the foundation for all custom error types in the xJet framework.\n * It ensures consistent error behavior, proper prototype chain setup, and serialization\n * to support error logging and transmission across boundaries.\n *\n * @example\n * ```ts\n * // Extending the base error class\n * export class ValidationError extends xJetBaseError {\n * constructor(message: string) {\n * super(message);\n * this.name = 'ValidationError';\n * }\n * }\n * ```\n *\n * @since 1.0.0\n */\nimport { serializesError } from '@components/object.component';\n\nexport abstract class xJetBaseError extends Error {\n /**\n * Creates a new instance of the base error class.\n *\n * @param message - The error message describing the problem.\n * @param name - Optional name for the error class; defaults to `'xJetError'`.\n *\n * @remarks\n * This constructor ensures the correct prototype chain for proper `instanceof` checks.\n * It also captures the stack trace if supported by the runtime environment.\n *\n * @example\n * ```ts\n * class MyError extends xJetBaseError {}\n * throw new MyError('Something went wrong');\n * ```\n *\n * @since 1.0.0\n */\n\n protected constructor(message: string, name: string = 'xJetError') {\n super(message);\n\n // Ensure correct prototype chain (important for `instanceof`)\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Serializes the xJetError instance to a plain object suitable for JSON conversion.\n *\n * @returns A plain object containing all properties of the error instance\n *\n * @remarks\n * This method creates a serializable representation of the error by copying all own\n * enumerable properties to a new object. It also explicitly ensures that critical properties\n * like name, message, and stack are included in the result, even if they are non-enumerable\n * in the original error object.\n *\n * The resulting object can be used with JSON.stringify() to create a complete JSON\n * representation of the error, which is useful for logging, error reporting, and\n * transmitting error details across process boundaries.\n *\n * @example\n * ```ts\n * const error = new xJetError('Expected value to be truthy');\n * const serialized = error.toJSON();\n * const json = JSON.stringify(serialized);\n *\n * // Later, this can be used for error reporting\n * console.error(json);\n * ```\n *\n * @since 1.0.0\n */\n\n toJSON(): Record<string, unknown> {\n return serializesError(this);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ComposeStatementInterface } from '@components/interfaces/format-component.interface';\n\n/**\n * Imports\n */\n\nimport { DIM, EXPECTED, RECEIVED } from '@components/color.component';\n\n/**\n * Constructs a formatted Jest-style matcher statement string with optional ANSI coloring.\n *\n * Builds a string that resembles a Jest assertion call, e.g.:\n * `xExpect(received).toEqual(expected)` or `xExpect(received).rejects.toThrow()`,\n * with the ability to include multiple expected values and an optional trailing comment.\n *\n * @param options - Configuration options for composing the matcher statement.\n * Properties:\n * - `assertionChain`: Non-empty array of matcher methods (e.g., ['rejects', 'toThrow'])\n * - `expectedLabels`: Array of expected argument labels, defaults to empty array\n * - `receivedLabeled`: Label for the received value, defaults to 'received'\n * - `comment`: Optional trailing comment appended after the statement\n *\n * @returns The fully formatted matcher statement as a string, including ANSI coloring if enabled\n *\n * @throws Error - Throws if `assertionChain` is empty or not provided\n *\n * @remarks\n * This function helps create consistent, colored assertion strings for testing frameworks\n * that support Jest-like matchers. It supports chaining matcher names and multiple expected arguments,\n * as well as adding inline comments for additional context.\n *\n * @example\n * ```ts\n * composeStatement({\n * receivedLabeled: 'received',\n * assertionChain: ['rejects', 'toThrow'],\n * expectedLabels: [],\n * comment: 'should throw an error'\n * });\n * // Returns: xExpect(received).rejects.toThrow() // should throw an error (with ANSI colors)\n *\n * composeStatement({\n * assertionChain: ['toEqual'],\n * expectedLabels: ['expectedValue']\n * });\n * // Returns: xExpect(received).toEqual(expectedValue) (with ANSI colors)\n * ```\n *\n * @default options.expectedLabels - []\n * @default options.receivedLabeled - 'received'\n *\n * @see ComposeStatementInterface - Interface for the `options` parameter\n *\n * @since 1.0.0\n */\n\nexport function composeStatement(options: ComposeStatementInterface): string {\n const { comment, assertionChain, expectedLabels = [], receivedLabeled = 'received' } = options;\n\n if (!assertionChain.length)\n throw new Error('Expected non-empty matcher chain (e.g., [\"toEqual\"]). Received an empty array.');\n\n const parts = [\n DIM('expect('),\n RECEIVED(receivedLabeled),\n DIM(')'),\n '.',\n assertionChain.join('.')\n ];\n\n if (expectedLabels.length > 0) {\n parts.push('(');\n parts.push(\n expectedLabels.map(value => EXPECTED(value)).join(', ')\n );\n parts.push(')');\n } else {\n parts.push('()');\n }\n\n if (comment) {\n parts.push(DIM(' // ' + comment));\n }\n\n return parts.join('');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { OptionsTypeErrorInterface } from '@errors/interfaces/type-error.interface';\n\n/**\n * Imports\n */\n\nimport { xJetBaseError } from '@errors/base.error';\nimport { serialize } from '@components/serialize.component';\nimport { composeStatement } from '@components/format.component';\nimport { EXPECTED, RECEIVED } from '@components/color.component';\n\n/**\n * Error class for type mismatches and validation failures.\n *\n * @remarks\n * This specialized error provides detailed information about type mismatches,\n * including the expected and received values with their types.\n * The formatted message includes:\n * - A hint chain showing the context where the error occurred\n * - A specific error message describing the issue\n * - Type and value information for both expected and received values when available\n *\n * Color highlighting (via EXPECTED and RECEIVED) is applied to make the\n * differences stand out in terminal output.\n *\n * @see xJetBaseError\n * @see OptionsTypeErrorInterface\n *\n * @since 1.0.0\n */\n\nexport class xJetTypeError extends xJetBaseError {\n\n /**\n * Creates a new type error with formatted message showing the mismatch details.\n *\n * @param options - Configuration object containing error details.\n *\n * @remarks\n * This constructor builds a multi-line error message that clearly shows:\n * - The property path where the error occurred (via assertionChain)\n * - The specific error message\n * - Type and serialized value of the expected value (if provided)\n * - Type and serialized value of the received value (if provided)\n *\n * @see OptionsTypeErrorInterface\n *\n * @since 1.0.0\n */\n\n constructor(options: OptionsTypeErrorInterface) {\n const lines = [\n `${ composeStatement(options) }\\n`,\n `Matcher error: ${ options.message }\\n`\n ];\n\n if (options.expected) {\n if(options.expected.type) lines.push(`Expected has type: ${ options.expected.type }`);\n lines.push(`Expected has value: ${\n EXPECTED(serialize(options.expected.value).join('\\n'))\n }`);\n }\n\n if (options.received) {\n if(options.received.type) lines.push(`Received has type: ${ options.received.type }`);\n lines.push(`Received has value: ${\n RECEIVED(serialize(options.received.value).join('\\n'))\n }`);\n }\n\n super(lines.join('\\n'), 'xJetTypeError');\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { AssertionResultInterface, OptionsExpectErrorInterface } from '@errors/interfaces/expect-error.interface';\n\n/**\n * Imports\n */\n\nimport { xJetBaseError } from '@errors/base.error';\nimport { composeStatement } from '@components/format.component';\n\n/**\n * Error class representing an expectation failure in xJet framework.\n *\n * @remarks\n * This error encapsulates details from matcher evaluation results,\n * including pass/fail status and error messages.\n *\n * The error message is composed of the formatted assertion statement and optional info lines.\n *\n * @since 1.0.0\n */\n\nexport class xJetExpectError extends xJetBaseError {\n /**\n * The result of the matcher function evaluation.\n *\n * @remarks\n * This optional property stores the result returned from a matcher function\n * when executed against the actual value. The result object contains important\n * information about the assertion outcome, including whether it passed or failed,\n * and custom error messages.\n *\n * When a matcher is executed, it returns an object conforming to the AssertionResultInterface,\n * which typically includes:\n * - pass: A boolean indicating if the assertion passed\n * - message: A function or string representing the formatted error message\n * - expected: The expected value for comparison\n * - received: The actual value received\n *\n * This property may be undefined when the error is generated before a matcher\n * function is executed, such as when an invalid promise is provided.\n *\n * @see AssertionResultInterface\n *\n * @since 1.0.0\n */\n\n matcherResult?: AssertionResultInterface;\n\n /**\n * Creates a new xJetExpectError instance.\n *\n * @param options - Options containing assertion details and optional info lines.\n *\n * @see OptionsExpectErrorInterface\n *\n * @since 1.0.0\n */\n\n constructor(options: OptionsExpectErrorInterface) {\n const lines = [ `${ composeStatement(options) }\\n` ];\n if (options.info) lines.push(...options.info);\n\n super(lines.join('\\n'), 'xJetExpectError');\n if (options.assertion) {\n this.matcherResult = options.assertion;\n this.matcherResult.message = this.message;\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { AssertionResultInterface } from '@errors/interfaces/expect-error.interface';\nimport type { HandleDiffFailureInterface, HandleFailureInterface } from './interfaces/matchers-handler.interface';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { xJetExpectError } from '@errors/expect.error';\nimport { diffComponent, getType } from '@diff/diff.module';\nimport { serialize } from '@components/serialize.component';\nimport { DIM, EXPECTED, RECEIVED } from '@components/color.component';\n\n/**\n * Ensures that a given value matches one of the specified types.\n *\n * Throws an ` xJetTypeError ` if the value's type does not match any of the allowed types.\n *\n * @param value - The value to check.\n * @param types - An array of allowed type names as strings.\n * @param label - Specifies whether the value is 'Expected' or 'Received' (used in an error message).\n * @param expectedLabels - Array of expected argument labels\n *\n * @throws xJetTypeError - When the value's type is not included in `types`.\n *\n * @example\n * ```ts\n * // Inside a MatcherService context\n * this.ensureType(42, ['number', 'bigint'], 'Received'); // Passes\n * this.ensureType('hello', ['number'], 'Expected'); // Throws xJetTypeError\n * ```\n *\n * @since 1.0.0\n */\n\nexport function ensureType(this: MatcherService, value: unknown, types: Array<string>, label: string, expectedLabels: Array<string> = []): void {\n const type = getType(value);\n if (!types.includes(type) && !types.includes(typeof value)) {\n throw new xJetTypeError({\n expectedLabels,\n assertionChain: this.assertionChain,\n message: `${ (label === 'Received' ? RECEIVED : EXPECTED)(label) } value must be a ${ types.join(' or ') }`,\n [label === 'Expected' ? 'expected' : 'received']: { value, type }\n });\n }\n}\n\n/**\n * Ensures that a given value is neither `null` nor `undefined`.\n *\n * Throws an ` xJetTypeError ` if the value is `null` or `undefined`.\n *\n * @param value - The value to check.\n * @param label - Specifies whether the value is 'Expected' or 'Received' (used in an error message).\n * @param expectedLabels - Array of expected argument labels\n *\n * @throws xJetTypeError - When the value is `null` or `undefined`.\n *\n * @example\n * ```ts\n * // Inside a MatcherService context\n * this.ensureNotNullish(0, 'Received'); // Passes\n * this.ensureNotNullish(null, 'Expected'); // Throws xJetTypeError\n * this.ensureNotNullish(undefined, 'Received'); // Throws xJetTypeError\n * ```\n *\n * @since 1.0.0\n */\n\nexport function ensureNotNullish(this: MatcherService, value: unknown, label: 'Expected' | 'Received', expectedLabels: Array<string> = []): void {\n if (value === null || value === undefined) {\n throw new xJetTypeError({\n expectedLabels,\n assertionChain: this.assertionChain,\n message: `${ (label === 'Received' ? RECEIVED : EXPECTED)(label) } value must not be null nor undefined`,\n [label === 'Expected' ? 'expected' : 'received']: { value }\n });\n }\n}\n\n/**\n * Serializes a value into a single-line human-readable string representation.\n *\n * @param value - The value to serialize.\n * @returns A single-line string representation of the serialized value.\n *\n * @example\n * ```ts\n * serializeOneLine({ a: 1, b: [2, 3] });\n * // Returns: \"Object { a: 1, b: Array [ 2, 3 ] }\"\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeOneLine(value: unknown): string {\n return serialize(value, '').join(' ');\n}\n\n/**\n * Handles matcher failures by evaluating pass/fail status and throwing an error if needed.\n *\n * @param options - Configuration options describing the failure details.\n *\n * @remarks\n * Determines whether to throw an error based on the pass status and the current \"not\" modifier.\n * Calls optional handlers `handleNot` or `handleInfo` to populate additional info messages.\n * Throws a formatted xJetExpectError with composed assertion details and info.\n *\n * The function is intended to be called with `this` bound to an instance of `MatcherService`.\n *\n * @throws xJetExpectError - When the assertion fails, according to the logic.\n *\n * @since 1.0.0\n */\n\nexport function handleFailure(this: MatcherService, options: HandleFailureInterface): void {\n const { pass } = options;\n const shouldThrow = (pass && this.notModifier) || (!pass && !this.notModifier);\n if (!shouldThrow) return;\n\n const info: Array<string> = [];\n const assertion: AssertionResultInterface = {\n pass,\n name: this.macherName,\n received: this.received,\n expected: options.expected\n };\n\n if (this.notModifier) {\n options.handleNot?.call(this, info);\n } else {\n options.handleInfo?.call(this, info);\n }\n\n throw new xJetExpectError({\n info,\n assertion,\n ...options,\n assertionChain: this.assertionChain\n });\n}\n\n/**\n * Handles matcher failures involving detailed diff information.\n *\n * @param options - Configuration options describing the failure with diff details.\n *\n * @remarks\n * Calls `handleFailure` with custom `handleNot` and `handleInfo` handlers:\n * - `handleNot` adds an inverted expectation message.\n * - `handleInfo` adds a note (if present) and a formatted diff between expected and received values.\n *\n * The function is intended to be called with `this` bound to an instance of `MatcherService`.\n *\n * @since 1.0.0\n */\n\nexport function handleDiffFailure(this: MatcherService, options: HandleDiffFailureInterface): void {\n handleFailure.call(this, {\n ...options,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: not ${ EXPECTED(serializeOneLine(this.received)) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>) {\n if (options.note) info.push(DIM(options.note), '');\n info.push(diffComponent(options.expected, this.received, true));\n }\n });\n}\n\n/**\n * Handles matcher failures involving simple comparisons with an operator.\n *\n * @param options - Configuration options describing the failure.\n * @param operator - The operator string used in the comparison (e.g., '===', '!==').\n *\n * @remarks\n * Calls `handleFailure` with custom `handleNot` and `handleInfo` handlers that\n * format expected and received values with the given operator, including alignment.\n *\n * The function is intended to be called with `this` bound to an instance of `MatcherService`.\n *\n * @since 1.0.0\n */\n\nexport function handleComparisonFailure(this: MatcherService, options: HandleFailureInterface, operator: string): void {\n const space = ' '.repeat(operator.length);\n\n handleFailure.call(this, {\n ...options,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: not ${ operator } ${ EXPECTED(serializeOneLine(options.expected)) }`);\n info.push(`Received: ${ space } ${ RECEIVED(serializeOneLine(this.received)) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: ${ operator } ${ EXPECTED(serializeOneLine(options.expected)) }`);\n info.push(`Received: ${ space } ${ RECEIVED(serializeOneLine(this.received)) }`);\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { AbstractPattern } from '@patterns/abstract.pattern';\nimport type { ConstructorLikeType } from '@interfaces/functions.interface';\nimport type { ThrownType, ThrownValueType } from '@matchers/interfaces/functions-matcher.interface';\nimport type { HandleInfoType, HandleNotType } from '@handlers/interfaces/matchers-handler.interface';\n\n/**\n * Imports\n */\n\nimport { diffComponent } from '@diff/components/diff.component';\nimport { serializeError } from '@components/serialize.component';\nimport { equals, isAsymmetric } from '@components/object.component';\nimport { EXPECTED, INVERSE, RECEIVED } from '@components/color.component';\nimport { ensureType, handleFailure, serializeOneLine } from '@handlers/matchers.handler';\n\n/**\n * Converts any thrown value into a {@link ThrownType}, normalizing Errors and non-Error values.\n *\n * @param err - The value that was thrown.\n *\n * @returns A {@link ThrownType} containing the value, type information, and message.\n *\n * @remarks\n * Ensures consistent handling of thrown values in matcher assertions.\n * Distinguishes between actual Error instances and arbitrary thrown objects/values.\n *\n * @example\n * ```ts\n * const thrown = getThrown(new Error('Oops'));\n * console.log(thrown.message); // \"Oops\"\n * console.log(thrown.isError); // true\n * ```\n *\n * @see ThrownType\n *\n * @since 1.0.0\n */\n\nexport function getThrown(err: unknown): ThrownType {\n const e = err as Record<string, unknown>;\n const hasMessage = e != null && typeof e.message === 'string';\n const isError = hasMessage && typeof e.name === 'string' && typeof e.stack === 'string';\n\n return {\n isError,\n value: err,\n message: hasMessage ? String(e.message) : String(err),\n hasMessage: isError ? true : hasMessage,\n serializedError: serializeError(err)\n } as ThrownType;\n}\n\n/**\n * Builds handler functions for reporting matcher failures.\n *\n * @param expectedLabel - The label describing the expected value (e.g., 'constructor', 'substring').\n * @param expectedValue - The expected value representation (stringifies if necessary).\n * @param thrown - The thrown value or null.\n * @param asymmetric - Optional flag for asymmetric matchers.\n *\n * @returns A tuple `[handleNot, handleInfo]` for failure reporting.\n *\n * @see HandleNotType\n * @see HandleInfoType\n *\n * @since 1.0.0\n */\n\nfunction buildInfo(expectedLabel: string, expectedValue: string, thrown: ThrownType | null, asymmetric = false): [ HandleNotType, HandleInfoType ] {\n const handleNot = (info: Array<string>): void => {\n info.push(`Expected ${ expectedLabel }: not ${ EXPECTED(expectedValue) }`);\n if (thrown?.hasMessage) {\n info.push(`Received message: ${ RECEIVED(serializeOneLine(asymmetric ? thrown.message : INVERSE(thrown.message))) }\\n`);\n } else {\n info.push(`Received value: ${ RECEIVED(serializeOneLine(thrown?.value)) }`);\n }\n };\n\n const handleInfo = (info: Array<string>): void => {\n info.push(`Expected ${ expectedLabel }: ${ EXPECTED(expectedValue) }`);\n if (thrown?.hasMessage) {\n if (asymmetric) {\n info.push(`Received name: ${ RECEIVED(serializeOneLine((thrown.value as Error)?.name)) }`);\n }\n info.push(`Received message: ${ RECEIVED(serializeOneLine(thrown.message)) }\\n`);\n } else {\n info.push(`Received value: ${ RECEIVED(serializeOneLine(thrown?.value)) }`);\n }\n };\n\n return [ handleNot, handleInfo ] as const;\n}\n\n/**\n * Checks whether a thrown value matches an expected constructor.\n *\n * @param expected - The expected error constructor.\n * @param thrown - The thrown value or null.\n *\n * @returns A {@link ThrownValueType} tuple: `[pass, handleNot, handleInfo]`.\n *\n * @see ThrownValueType\n * @since 1.0.0\n */\n\nexport function toThrowExpectedClass(this: MatcherService, expected: ConstructorLikeType, thrown: ThrownType | null): ThrownValueType {\n const pass = thrown != null && thrown.value instanceof expected;\n const [ handleNot, handleInfo ] = buildInfo('constructor', expected.name, thrown);\n\n return [ pass, handleNot, handleInfo ];\n}\n\n/**\n * Checks whether a thrown error message contains an expected string.\n *\n * @param expected - The expected substring.\n * @param thrown - The thrown value or null.\n *\n * @returns A {@link ThrownValueType} tuple: `[pass, handleNot, handleInfo]`.\n *\n * @see ThrownValueType\n * @since 1.0.0\n */\n\nexport function toThrowExpectedString(this: MatcherService, expected: string, thrown: ThrownType | null): ThrownValueType {\n const pass = thrown != null && thrown.message.includes(expected);\n const [ handleNot, handleInfo ] = buildInfo('substring', `\"${ expected }\"`, thrown);\n\n return [ pass, handleNot, handleInfo ];\n}\n\n/**\n * Checks whether a thrown error message matches an expected RegExp.\n *\n * @param expected - The expected pattern.\n * @param thrown - The thrown value or null.\n *\n * @returns A {@link ThrownValueType} tuple: `[pass, handleNot, handleInfo]`.\n *\n * @see ThrownValueType\n * @since 1.0.0\n */\n\nexport function toThrowExpectedRegExp(this: MatcherService, expected: RegExp, thrown: ThrownType | null): ThrownValueType {\n const pass = thrown != null && expected.test(thrown.message);\n const [ handleNot, handleInfo ] = buildInfo('pattern', serializeOneLine(expected), thrown);\n\n return [ pass, handleNot, handleInfo ];\n}\n\n/**\n * Checks whether a thrown value matches an asymmetric matcher pattern.\n *\n * @param expected - The asymmetric pattern matcher.\n * @param thrown - The thrown value or null.\n *\n * @returns A {@link ThrownValueType} tuple: `[pass, handleNot, handleInfo]`.\n *\n * @see ThrownValueType\n * @since 1.0.0\n */\n\nexport function toThrowExpectedAsymmetric(this: MatcherService, expected: AbstractPattern, thrown: ThrownType | null): ThrownValueType {\n const pass = thrown != null && expected.matches(thrown.value);\n const [ handleNot, handleInfo ] = buildInfo('asymmetric', serializeOneLine(expected), thrown, true);\n\n return [ pass, handleNot, handleInfo ];\n}\n\n/**\n * Checks whether a thrown value matches an expected object.\n *\n * @param expected - The expected object.\n * @param thrown - The thrown value or null.\n *\n * @returns A {@link ThrownValueType} tuple: `[pass, handleNot, handleInfo]`.\n *\n * @see ThrownValueType\n * @since 1.0.0\n */\n\nexport function toThrowExpectedObject(this: MatcherService, expected: object, thrown: ThrownType): ThrownValueType {\n const pass = thrown != null && equals(serializeError(expected), thrown.serializedError);\n\n const handleNot = (info: Array<string>): void => {\n info.push(`Expected: not ${ EXPECTED(serializeOneLine(thrown.serializedError)) }`);\n };\n\n const handleInfo = (info: Array<string>): void => {\n info.push(diffComponent(expected, thrown.serializedError, true));\n };\n\n return [ pass, handleNot, handleInfo ];\n}\n\n\n/**\n * Asserts that a function or promise throws a value that matches the expected criteria.\n *\n * @param expected - Optional expectation: constructor, string, RegExp, object, or asymmetric pattern.\n *\n * @throws xJetTypeError - If `this.received` is not a function when expected, or if the expected type is invalid.\n *\n * @remarks\n * Supports multiple forms of expectation:\n * - Constructor: function must throw instance of that class.\n * - String: function must throw with message-containing substring.\n * - RegExp: function must throw with a message matching pattern.\n * - Object: function must throw an object equal to expected.\n * - Asymmetric: function must throw a value matching a custom pattern.\n *\n * Updates `this.received` with a serialized thrown value.\n * Delegates failure reporting to {@link handleFailure}.\n *\n * @example\n * ```ts\n * xExpect(() => { throw new Error('Oops'); }).toThrow('Oops');\n * xExpect(() => { throw new TypeError(); }).toThrow(TypeError);\n * xExpect(() => { throw { code: 123 }; }).toThrow({ code: 123 });\n * xExpect(() => { throw new Error('fail'); }).not.toThrow('pass');\n * ```\n *\n * @see MatcherService\n * @see ConstructorLikeType\n *\n * @since 1.0.0\n */\n\nexport function toThrow(this: MatcherService, expected?: RegExp | string | ConstructorLikeType | object): void {\n let thrown: ThrownType | null = null;\n const expectedLabels = expected ? [ 'expected' ] : [];\n\n if (this.rejectsModifier) {\n thrown = getThrown(this.received);\n } else if (typeof this.received === 'function') {\n try {\n this.received();\n } catch (error) {\n thrown = getThrown(error);\n }\n } else {\n ensureType.call(this, this.received, [ 'function' ], 'Received', expectedLabels);\n }\n\n let pass = false;\n let handleNot: HandleNotType;\n let handleInfo: HandleInfoType;\n\n if (!expected) {\n pass = thrown != null;\n handleNot = (info: Array<string>): void => {\n if (thrown?.hasMessage) {\n info.push(`Error name: ${ RECEIVED((thrown.value as Error)?.name) }`);\n info.push(`Error message: ${ RECEIVED(serializeOneLine(thrown.message)) }\\n`);\n } else {\n info.push(`Error value: ${ RECEIVED(serializeOneLine(thrown?.value)) }`);\n }\n };\n } else if (typeof expected === 'function') {\n [ pass, handleNot, handleInfo ] = toThrowExpectedClass.call(this, <ConstructorLikeType> expected, thrown);\n } else if (typeof expected === 'string') {\n [ pass, handleNot, handleInfo ] = toThrowExpectedString.call(this, expected, thrown);\n } else if (expected instanceof RegExp) {\n [ pass, handleNot, handleInfo ] = toThrowExpectedRegExp.call(this, expected, thrown);\n } else if (isAsymmetric(expected)) {\n [ pass, handleNot, handleInfo ] = toThrowExpectedAsymmetric.call(this, expected, thrown);\n } else if (thrown !== null && typeof expected === 'object') {\n [ pass, handleNot, handleInfo ] = toThrowExpectedObject.call(this, expected, thrown);\n } else {\n ensureType.call(this, expected, [ 'string', 'function', 'RegExp', 'object' ], 'Expected', expectedLabels);\n }\n\n handleFailure.call(Object.assign({}, this, { received: thrown?.serializedError }), {\n pass,\n expected,\n expectedLabels,\n handleNot(this: MatcherService, info: Array<string>) {\n handleNot?.call(this, info);\n },\n handleInfo(this: MatcherService, info: Array<string>) {\n if (!thrown) {\n info.push(`${ RECEIVED('Received') } function did not throw`);\n } else {\n handleInfo?.call(this, info);\n }\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { EXPECTED, RECEIVED } from '@components/color.component';\nimport { diffComponent, getType } from '@diff/components/diff.component';\nimport { ensureType, handleFailure, serializeOneLine } from '@handlers/matchers.handler';\n\n/**\n * Asserts that a received string has the specified length.\n *\n * @param length - The expected length of the string.\n *\n * @remarks\n * - Works with both `number` and `bigint` for the expected length.\n * - Throws an `xJetTypeError` if the received value does not have a numeric `length` property.\n *\n * @example\n * ```ts\n * xExpect(\"abc\").toHaveLength(3); // Passes\n * xExpect(\"abc\").toHaveLength(5); // Fails\n * xExpect(\"abc\").not.toHaveLength(2); // Passes\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveLength(this: MatcherService<string>, length: number | bigint): void {\n const expectedLabels = [ 'length' ];\n ensureType.call(this, length, [ 'number', 'bigint' ], 'Expected', expectedLabels);\n\n if(!Object.hasOwn(<object> <unknown> this.received, 'length') || !Number.isSafeInteger(this.received.length)) {\n throw new xJetTypeError({\n expectedLabels,\n message: `${ RECEIVED('received') } value must have a length property whose value must be a number`,\n received: { value: this.received, type: getType(this.received) },\n assertionChain: this.assertionChain\n });\n }\n\n const received = this.received;\n const pass = received.length == length;\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected length: not ${ EXPECTED(serializeOneLine(length)) }`);\n info.push(`Received string: ${ RECEIVED(serializeOneLine(received)) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`Expected length: ${ EXPECTED(serializeOneLine(length)) }`);\n info.push(`Received length: ${ RECEIVED(serializeOneLine(received.length)) }`);\n info.push(`Received string: ${ RECEIVED(serializeOneLine(received)) }`);\n }\n });\n}\n\n/**\n * Asserts that a received string matches a given substring or regular expression.\n *\n * @param expected - A string to search for, or a `RegExp` pattern to match against.\n *\n * @remarks\n * - Accepts both `string` and `RegExp` as the expected value.\n * - For `string` matching, it checks if the substring exists within the received value.\n * - For `RegExp` matching, it uses `RegExp.test()` to verify the pattern.\n *\n * @example\n * ```ts\n * xExpect(\"Hello World\").toMatch(\"World\"); // Passes\n * xExpect(\"Hello World\").toMatch(/world/i); // Passes (case-insensitive)\n * xExpect(\"Hello World\").not.toMatch(\"Earth\"); // Passes\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toMatch(this: MatcherService<string>, expected: RegExp | string): void {\n const expectedLabels = [ 'expected' ];\n ensureType.call(this, this.received, [ 'string' ], 'Received', expectedLabels);\n ensureType.call(this, expected, [ 'string', 'RegExp' ], 'Expected', expectedLabels);\n\n const received = this.received;\n const pass = typeof expected === 'string'\n ? received.includes(expected)\n : new RegExp(expected).test(received);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: not ${ EXPECTED(serializeOneLine(received)) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n if(expected instanceof RegExp) {\n info.push(`Expected pattern: ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received string: ${ RECEIVED(serializeOneLine(received)) }`);\n } else {\n info.push(diffComponent(expected, received, true));\n }\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { NumberOperatorType, NumericType } from '@matchers/interfaces/number-matcher.interface';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { getType } from '@diff/components/diff.component';\nimport { EXPECTED, RECEIVED } from '@components/color.component';\nimport { ensureType, handleComparisonFailure } from '@handlers/matchers.handler';\n\n/**\n * Ensures that the provided value is a positive number or bigint.\n *\n * @param value - The value to validate.\n * @param label - Label describing the value (e.g., `'Received'` or `'Expected'`).\n * @param expectedLabels - Optional list of expected value descriptions for error reporting.\n *\n * @throws xJetTypeError - Thrown if the value is not a number or bigint, or if it is less than zero.\n *\n * @remarks\n * This method first validates that the type of `value` is `number` or `bigint`\n * via {@link ensureType}, then asserts that the numeric value is greater than or equal to zero.\n * If the validation fails, an {@link xJetTypeError} is thrown with contextual details.\n *\n * @see ensureType\n * @see xJetTypeError\n *\n * @since 1.0.0\n */\n\nexport function ensurePositiveNumber(this: MatcherService, value: unknown, label: string, expectedLabels: Array<string> = []): void {\n ensureType.call(this, value, [ 'number', 'bigint' ], label, expectedLabels);\n\n if (<number> value < 0) {\n throw new xJetTypeError({\n expectedLabels,\n assertionChain: this.assertionChain,\n message: `${ (label === 'Received' ? RECEIVED : EXPECTED)(label) } value must be positive number`,\n [label === 'Received' ? 'received' : 'expected']: { value, type: getType(value) }\n });\n }\n}\n\n/**\n * Performs a numeric comparison between the received and expected values, then delegates failure handling.\n *\n * @param expected - The expected numeric value.\n * @param operator - The comparison operator (`'>'`, `'>='`, `'<'`, `'<='`).\n * @param matcherName - The name of the matcher invoking this comparison.\n *\n * @remarks\n * This is the core comparison logic shared by `toBeGreaterThan`, `toBeGreaterThanOrEqual`,\n * `toBeLessThan`, and `toBeLessThanOrEqual`.\n *\n * @example\n * ```ts\n * handleNumericComparison.call({ received: 5, notModifier: false }, 3, '>', 'toBeGreaterThan');\n * // Passes silently\n * ```\n *\n * @example\n * ```ts\n * handleNumericComparison.call({ received: 2, notModifier: false }, 5, '>', 'toBeGreaterThan');\n * // Throws a comparison failure\n * ```\n *\n * @see toBeLessThan\n * @see toBeGreaterThan\n *\n * @since 1.0.0\n */\n\nexport function handleNumericComparison(\n this: MatcherService<NumericType>, expected: NumericType, operator: NumberOperatorType\n): void {\n const received = this.received;\n const expectedLabels = [ 'Expected' ];\n ensureType.call(this, expected, [ 'number', 'bigint' ], 'Expected', expectedLabels);\n ensureType.call(this, received, [ 'number', 'bigint' ], 'Received', expectedLabels);\n\n let pass: boolean;\n switch (operator) {\n case '>':\n pass = received > expected;\n break;\n case '>=':\n pass = received >= expected;\n break;\n case '<':\n pass = received < expected;\n break;\n case '<=':\n pass = received <= expected;\n break;\n default:\n pass = false;\n }\n\n handleComparisonFailure.call(this, { pass, expectedLabels, expected }, operator);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { NumericType } from '@matchers/interfaces/number-matcher.interface';\n\n/**\n * Imports\n */\n\nimport { EXPECTED, RECEIVED } from '@components/color.component';\nimport { handleNumericComparison } from '@handlers/number.handler';\nimport { ensureType, handleFailure, serializeOneLine } from '@handlers/matchers.handler';\n\n/**\n * Asserts that the received number is close to the expected number within a given decimal prevision.\n *\n * @param expected - The target number.\n * @param precision - The number of decimal places to check. Defaults to `2`.\n *\n * @remarks\n * Uses an absolute difference check with a tolerance of `10^(-precision) / 2`.\n * Works with both positive and negative numbers.\n *\n * @example\n * ```ts\n * xExpect(0.2 + 0.1).toBeCloseTo(0.3, 2); // Passes\n * ```\n *\n * @example\n * ```ts\n * xExpect(0.2 + 0.1).not.toBeCloseTo(0.3, 5); // Fails\n * ```\n *\n * @see handleFailure\n * @see throwIfNotNumber\n *\n * @since 1.0.0\n */\n\nexport function toBeCloseTo(this: MatcherService<number>, expected: number, precision: number = 2): void {\n const expectedLabels = [ 'expected', 'precision' ];\n ensureType.call(this, expected, [ 'number' ], 'Expected', expectedLabels);\n ensureType.call(this, this.received, [ 'number' ], 'Received', expectedLabels);\n\n const actual = this.received;\n const receivedDifference = Math.abs(expected - actual);\n const expectedDifference = Math.pow(10, -precision) / 2;\n const expectedDifferenceStr = (precision < 20) ? expectedDifference.toFixed(precision + 1) : expectedDifference.toString();\n\n const not = this.notModifier ? ' ' : ' ';\n const notLabel = this.notModifier ? 'not < ' : '< ';\n const pass = receivedDifference < expectedDifference;\n\n const details = [\n `Expected precision: ${ not }${ EXPECTED(precision.toString()) }`,\n `Expected difference: ${ notLabel }${ EXPECTED(expectedDifferenceStr) }`,\n `Received difference: ${ not }${ RECEIVED(receivedDifference.toString()) }`\n ];\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n handleNot(info) {\n info.push(`Expected: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received: ${ RECEIVED(serializeOneLine(actual)) }\\n`);\n info.push(...details);\n },\n handleInfo(info) {\n info.push(`Expected: ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received: ${ RECEIVED(serializeOneLine(actual)) }\\n`);\n info.push(...details);\n }\n });\n}\n\n/**\n * Asserts that the received value is greater than the expected value.\n *\n * @param expected - The value to compare against.\n *\n * @example\n * ```ts\n * xExpect(10).toBeGreaterThan(5); // Passes\n * ```\n *\n * @example\n * ```ts\n * xExpect(5).toBeGreaterThan(10); // Fails\n * ```\n *\n * @see handleNumericComparison\n * @since 1.0.0\n */\n\nexport function toBeGreaterThan(this: MatcherService<NumericType>, expected: NumericType): void {\n handleNumericComparison.call(this, expected, '>');\n}\n\n/**\n * Asserts that the received value is greater than or equal to the expected value.\n *\n * @param expected - The value to compare against.\n *\n * @example\n * ```ts\n * xExpect(5).toBeGreaterThanOrEqual(5); // Passes\n * ```\n *\n * @example\n * ```ts\n * xExpect(4).toBeGreaterThanOrEqual(5); // Fails\n * ```\n *\n * @see handleNumericComparison\n * @since 1.0.0\n */\n\nexport function toBeGreaterThanOrEqual(this: MatcherService<NumericType>, expected: NumericType): void {\n handleNumericComparison.call(this, expected, '>=');\n}\n\n/**\n * Asserts that the received value is less than the expected value.\n *\n * @param expected - The value to compare against.\n *\n * @example\n * ```ts\n * xExpect(3).toBeLessThan(5); // Passes\n * ```\n *\n * @example\n * ```ts\n * xExpect(6).toBeLessThan(5); // Fails\n * ```\n *\n * @see handleNumericComparison\n *\n * @since 1.0.0\n */\n\nexport function toBeLessThan(this: MatcherService<NumericType>, expected: NumericType): void {\n handleNumericComparison.call(this, expected, '<');\n}\n\n/**\n * Asserts that the received value is less than or equal to the expected value.\n *\n * @param expected - The value to compare against.\n *\n * @example\n * ```ts\n * xExpect(5).toBeLessThanOrEqual(5); // Passes\n * ```\n *\n * @example\n * ```ts\n * xExpect(7).toBeLessThanOrEqual(5); // Fails\n * ```\n *\n * @see handleNumericComparison\n * @since 1.0.0\n */\n\nexport function toBeLessThanOrEqual(this: MatcherService<NumericType>, expected: NumericType): void {\n handleNumericComparison.call(this, expected, '<=');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { MockStateInterface } from '@matchers/interfaces/mock-matcher.interface';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { diffArgs } from '@diff/components/diff.component';\nimport { serialize } from '@components/serialize.component';\nimport { EXPECTED, RECEIVED } from '@components/color.component';\n\n/**\n * Ensures that the received value is an `xJet` mock or spy function.\n *\n * This function is intended to be used within matcher implementations to\n * assert that a value under test is a mock created by the `xJet` mocking system.\n *\n * @param expectedLabels - Optional labels describing the expected value,\n * used in error messages for improved clarity.\n *\n * @throws {@link xJetTypeError}\n * Thrown when the received value is not recognized as an `xJet` mock or spy function.\n *\n * @remarks\n * Validates that the `this.received` object contains both the `xJetMock` flag\n * and a valid `mock` state. If either condition is not met, an `xJetTypeError`\n * is thrown with an appropriate failure message.\n *\n * @since 1.0.0\n */\n\nexport function ensureMock(this: MatcherService<MockStateInterface>, expectedLabels: Array<string> = []): void {\n if (!this.received?.xJetMock || !this.received?.mock) {\n throw new xJetTypeError({\n expectedLabels,\n assertionChain: this.assertionChain,\n message: `${ RECEIVED('Received') } value must be a mock or spy function`,\n received: { value: this.received }\n });\n }\n}\n\n/**\n * Serializes an array of call arguments into a single formatted string.\n *\n * Each argument is serialized, trimmed of enclosing brackets, and highlighted using {@link EXPECTED}.\n * Commas inside individual arguments are removed to avoid conflicts with the joining commas.\n *\n * @param args - The array of arguments to serialize.\n * @returns A string with all arguments serialized and comma-separated.\n *\n * @remarks\n * - Removes any commas inside individual arguments to prevent confusion when joining.\n * - Uses {@link EXPECTED} to colorize each argument consistently.\n *\n * @example\n * ```ts\n * const args = [1, \"test\", true];\n * console.log(serializeCallArgs(args));\n * // Output (with ANSI colors):\n * // 1, test, true\n * ```\n *\n * @example\n * ```ts\n * // Arguments containing commas\n * const args = [\"a,b\", \"c\"];\n * console.log(serializeCallArgs(args));\n * // Output:\n * // a b, c\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeCallArgs(args: Array<unknown>): string {\n const serialized = serialize(args, '').slice(1, -1);\n\n return serialized.map((arg) => {\n return EXPECTED(arg.replace(',', ''));\n }).join(', ');\n}\n\n/**\n * Serializes a list of calls or values into a formatted, optionally highlighted string.\n *\n * Each line contains an index, optional highlight symbol, and a diff of the call/value against the expected value.\n *\n * @param expected - The expected value to diff against each item.\n * @param items - The array of calls or values to serialize.\n * @param offset - Optional 1-based index to highlight.\n * @param symbol - Symbol to use for highlighting the selected line. Default is `'->'`.\n * @param sliceArgs - Whether to slice the diff result to remove outer brackets. Default is `false`.\n * @param maxLines - Maximum number of lines to include. Default is `3`.\n * @returns A formatted string representing the serialized list, or an empty string if `items` is empty.\n *\n * @example\n * ```ts\n * const expected = [1, 2];\n * const calls = [[1, 3], [1, 2], [2, 2]];\n * console.log(serializeList(expected, calls));\n * // Output (with ANSI colors):\n * // 1: 1 \\x1B[31m3\\x1B[39m\n * // 2: 1 2\n * // 3: \\x1B[31m2\\x1B[39m 2\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeList(\n expected: unknown, items: Array<unknown>, offset?: number, symbol: string = '->', sliceArgs: boolean = false, maxLines: number = 3\n): string {\n if (!items?.length) return '';\n\n\n let start = 0;\n let highlightIndex = -1;\n const total = items.length;\n\n if (offset && offset >= 1 && offset <= total) {\n highlightIndex = offset - 1;\n start = Math.max(0, Math.min(highlightIndex - 1, total - (maxLines - 1)));\n }\n\n const end = Math.min(start + maxLines, total);\n const width = String(end).length;\n const symbolPad = ' '.repeat(symbol.length + 1);\n const result: Array<string> = new Array(end - start);\n\n for (let i = start; i < end; i++) {\n const args = items[i];\n const num = String(i + 1).padStart(width, ' ');\n const prefix = i === highlightIndex ? `${ symbol } ` : symbolPad;\n\n if(sliceArgs && Array.isArray(args) && args.length < 1) {\n result[i - start] = `${ prefix }${ num }: called with 0 arguments`;\n continue;\n }\n\n const diff = sliceArgs\n ? diffArgs(expected, args).slice(1, -1)\n : diffArgs(expected, args);\n\n result[i - start] = `${ prefix }${ num }: ${ diff.join(' ') }`;\n }\n\n return result.join('\\n');\n}\n\n\n/**\n * Serializes a list of highlighted calls with diffs against the expected values.\n *\n * Only the calls at the specified `highlights` indices are included, up to `maxLines`.\n *\n * @param expected - The expected argument array.\n * @param calls - Array of actual calls to diff against `expected`.\n * @param highlights - 1-based indices of calls to include in the output.\n * @param maxLines - Maximum number of lines to include. Default is `3`.\n * @returns A formatted string of the highlighted calls, or an empty string if no calls or highlights.\n *\n * @example\n * ```ts\n * const expected = [1, 2];\n * const calls = [[1, 3], [1, 2], [2, 2]];\n * console.log(serializeHighlightedCalls(expected, calls, [1, 3]));\n * // Output:\n * // 1: 1 \\x1B[31m3\\x1B[39m\n * // 3: \\x1B[31m2\\x1B[39m 2\n * ```\n *\n * @since 1.0.0\n */\n\nexport function serializeHighlightedCalls(expected: Array<unknown>, calls: Array<unknown[]>, highlights: Array<number> = [], maxLines: number = 3): string {\n if (!calls?.length || !highlights.length) return '';\n\n const total = calls.length;\n const width = String(total).length + 3;\n\n const results: Array<string> = [];\n for (let i = 0; i < highlights.length; i++) {\n const idx = highlights[i] - 1; // convert 1-based to 0-based\n if (idx < 0 || idx >= total) continue;\n\n const diff = diffArgs(expected, calls[idx]).slice(1, -1);\n\n results.push(`${ String(idx + 1).padStart(width, ' ') }: ${ diff.join(' ') }`);\n if(results.length >= maxLines) break;\n }\n\n return results.join('\\n');\n}\n\n/**\n * Serializes a list of calls with diffs, slicing the arguments for concise output.\n *\n * @param expected - The expected argument array.\n * @param returns - Array of actual calls to diff against `expected`.\n * @param offset - Optional 1-based index to highlight.\n * @param symbol - Symbol to highlight the selected line.\n * @returns A formatted string representing the serialized calls.\n *\n * @see serializeList\n * @since 1.0.0\n */\n\nexport function serializeCallList(expected: Array<unknown>, returns: Array<unknown[]>, offset?: number, symbol?: string): string {\n return serializeList(expected, returns, offset, symbol, true);\n}\n\n/**\n * Serializes a list of return values with diffs against the expected value.\n *\n * @param expected - The expected value.\n * @param calls - Array of return values to diff against `expected`.\n * @param offset - Optional 1-based index to highlight.\n * @param symbol - Symbol to highlight the selected line.\n * @returns A formatted string representing the serialized return values.\n *\n * @see serializeList\n * @since 1.0.0\n */\n\nexport function serializeReturnList(expected: unknown, calls: Array<unknown>, offset?: number, symbol?: string): string {\n return serializeList(expected, calls, offset, symbol, false);\n}\n\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { MockInvocationResultInterface, MockStateInterface } from '@matchers/interfaces/mock-matcher.interface';\n\n/**\n * Imports\n */\n\nimport { equals } from '@components/object.component';\nimport { ensurePositiveNumber } from '@handlers/number.handler';\nimport { EXPECTED, RECEIVED } from '@components/color.component';\nimport { handleFailure, serializeOneLine } from '@handlers/matchers.handler';\nimport { serializeHighlightedCalls, serializeReturnList } from '@handlers/mock.handler';\nimport { ensureMock, serializeCallArgs, serializeCallList } from '@handlers/mock.handler';\n\n/**\n * Asserts that a mock function has been called at least once.\n *\n * @remarks\n * This matcher validates that the mock function represented by `this.received`\n * has been invoked one or more times. It uses {@link handleFailure} to report\n * a descriptive failure message if the assertion does not pass.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn();\n * xExpect(mockFn).toHaveBeenCalled(); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * xExpect(mockFn).toHaveBeenCalled(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveBeenCalled(this: MatcherService<MockStateInterface>): void {\n ensureMock.call(this);\n const calls = this.received.mock.calls;\n const count = this.received.mock.calls.length;\n\n handleFailure.call(this, {\n pass: count > 0,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`Expected calls: ${ EXPECTED('0') }`);\n info.push(`Received calls: ${ RECEIVED(count.toString()) }\\n`);\n info.push(serializeCallList([], calls));\n },\n handleInfo(info) {\n info.push(`Expected calls: >= ${ EXPECTED('1') }`);\n info.push(`Received calls: ${ RECEIVED(count.toString()) }\\n`);\n }\n });\n}\n\n/**\n * Asserts that a mock function has been called a specific number of times.\n *\n * @param expected - The exact number of times the mock function is expected to have been called.\n *\n * @remarks\n * This matcher validates that the mock function represented by `this.received`\n * has been invoked exactly `expected` times. It performs the following checks:\n * 1. Ensures that `this.received` is a mock function via {@link ensureMock}.\n * 2. Ensures that `expected` is a positive number using {@link ensurePositiveNumber}.\n * 3. Compares the actual call count to `expected` and reports via {@link handleFailure}.\n *\n * @throws {@link xJetTypeError} If `expected` is not a positive number.\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn();\n * xExpect(mockFn).toHaveBeenCalledTimes(1); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * xExpect(mockFn).toHaveBeenCalledTimes(2); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveBeenCalledTimes(this: MatcherService<MockStateInterface>, expected: number | bigint): void {\n const expectedLabels = [ 'expected' ];\n\n ensureMock.call(this, expectedLabels);\n ensurePositiveNumber.call(this, expected, 'expected', expectedLabels);\n\n const count = this.received.mock.calls.length;\n handleFailure.call(this, {\n expected,\n pass: count == expected,\n expectedLabels,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`Expected calls: != ${ EXPECTED(expected.toString()) }`);\n },\n handleInfo(info) {\n info.push(`Expected calls: ${ EXPECTED(expected.toString()) }`);\n info.push(`Received calls: ${ RECEIVED(count.toString()) }\\n`);\n }\n });\n}\n\n/**\n * Asserts that a mock function has been called with specific arguments at least once.\n *\n * @param args - The expected arguments to check against the mock function calls.\n *\n * @remarks\n * This matcher validates that the mock function represented by `this.received`\n * has been invoked at least once with arguments exactly matching `args`. It performs the following:\n * 1. Ensures that `this.received` is a mock function via {@link ensureMock}.\n * 2. Compares each call to the expected arguments using {@link equals}.\n * 3. Records the indices of calls that match the expected arguments.\n * 4. Reports assertion results and detailed call differences using {@link handleFailure},\n * {@link serializeCallArgs}, {@link serializeCallList}, and {@link serializeHighlightedCalls}.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(1, 'test');\n * xExpect(mockFn).toHaveBeenCalledWith(1, 'test'); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(2, 'test');\n * xExpect(mockFn).toHaveBeenCalledWith(1, 'test'); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveBeenCalledWith(this: MatcherService<MockStateInterface>, ...args: Array<unknown>): void {\n const expectedLabels = [ '...args' ];\n ensureMock.call(this, expectedLabels);\n\n const calls = this.received.mock.calls;\n const count = this.received.mock.calls.length;\n const indices: Array<number> = [];\n\n calls.forEach((call, index) => {\n if (call.length === args.length && equals(args, call)) {\n indices.push(index + 1);\n }\n });\n\n const pass = indices.length > 0;\n handleFailure.call(this, {\n pass,\n expectedLabels,\n expected: args,\n receivedLabeled: this.received.name,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: not ${ serializeCallArgs(args) }`);\n info.push(`Received:\\n\\n${ serializeHighlightedCalls(args, calls, indices) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: ${ serializeCallArgs(args) }`);\n info.push(`Received: \\n\\n${ serializeCallList(args, calls) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that a mock function was last called with the specified arguments.\n *\n * @param args - The expected arguments to check against the last mock function call.\n *\n * @remarks\n * This matcher validates that the mock function represented by `this.received`\n * was invoked last with arguments exactly matching `args`. It performs the following:\n * 1. Ensures that `this.received` is a mock function via {@link ensureMock}.\n * 2. Retrieves the last call from the mock\u2019s call history.\n * 3. Compares the last call arguments with the expected arguments using {@link equals}.\n * 4. Reports assertion results and detailed call differences using {@link handleFailure},\n * {@link serializeCallArgs}, and {@link serializeCallList}.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(1, 'first');\n * mockFn(2, 'last');\n * xExpect(mockFn).toHaveBeenLastCalledWith(2, 'last'); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(1, 'first');\n * mockFn(2, 'last');\n * xExpect(mockFn).toHaveBeenLastCalledWith(1, 'first'); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveBeenLastCalledWith(this: MatcherService<MockStateInterface>, ...args: Array<unknown>): void {\n const expectedLabels = [ '...args' ];\n ensureMock.call(this, expectedLabels);\n\n const calls = this.received.mock.calls;\n const count = calls.length;\n const callIndex = this.received.mock.calls.at(-1);\n const pass = callIndex !== undefined && equals(args, callIndex);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n expected: args,\n receivedLabeled: this.received.name,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: not ${ serializeCallArgs(args) }`);\n info.push(`Received: \\n\\n${ serializeCallList(args, calls, calls.length) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: ${ serializeCallArgs(args) }`);\n info.push(`Received: \\n\\n${ serializeCallList(args, calls, calls.length) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that a mock function was called with the specified arguments on its N-th invocation.\n *\n * @param nthCall - The 1-based index of the call to check.\n * @param args - The expected arguments to check for the N-th call.\n *\n * @remarks\n * This matcher performs the following steps:\n * 1. Validates that `this.received` is a mock function using {@link ensureMock}.\n * 2. Ensures that `nthCall` is a positive number via {@link ensurePositiveNumber}.\n * 3. Retrieves the N-th call from the mock\u2019s call history.\n * 4. Compares the N-th call arguments to the expected `args` using {@link equals}.\n * 5. Reports assertion results and detailed call differences using {@link handleFailure},\n * {@link serializeCallArgs}, and {@link serializeCallList}.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n * @throws If `nthCall` is not a positive number, {@link ensurePositiveNumber} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn('first');\n * mockFn('second');\n * xExpect(mockFn).toHaveBeenNthCalledWith(2, 'second'); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn('first');\n * mockFn('second');\n * xExpect(mockFn).toHaveBeenNthCalledWith(1, 'second'); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveBeenNthCalledWith(this: MatcherService<MockStateInterface>, nthCall: number, ...args: Array<unknown>): void {\n const expectedLabels = [ 'nthCall', '...args' ];\n ensureMock.call(this, expectedLabels);\n ensurePositiveNumber.call(this, nthCall, 'nthCall', expectedLabels);\n\n const calls = this.received.mock.calls;\n const count = calls.length;\n const callIndex = this.received.mock.calls.at(nthCall - 1);\n const pass = callIndex !== undefined && equals(args, callIndex);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n expected: args,\n receivedLabeled: this.received.name,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`nthCall: ${ nthCall }`);\n info.push(`Expected: not ${ serializeCallArgs(args) }`);\n info.push(`Received: \\n\\n${ serializeCallList(args, calls, nthCall) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`nthCall: ${ nthCall }`);\n info.push(`Expected: ${ serializeCallArgs(args) }`);\n info.push(`Received: \\n\\n${ serializeCallList(args, calls, nthCall) }\\n`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that a mock function has returned at least once.\n *\n * @remarks\n * This matcher performs the following steps:\n * 1. Validates that `this.received` is a mock function using {@link ensureMock}.\n * 2. Iterates over the mock\u2019s results to count how many invocations returned a value.\n * 3. Collects all returned values for reporting.\n * 4. Delegates assertion reporting to {@link handleFailure}, including a summary of returned values\n * and total calls using {@link serializeReturnList}.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn();\n * xExpect(mockFn).toHaveReturned(); // Passes if the function returned at least once\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * xExpect(mockFn).toHaveReturned(); // Fails if the function was never called or never returned\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveReturned(this: MatcherService<MockStateInterface>): void {\n ensureMock.call(this);\n const results: Array<unknown> = [];\n const count = this.received.mock.calls.length;\n const resultsCount = this.received.mock.results.reduce(\n (n: number, result: MockInvocationResultInterface<unknown>) => {\n if (result.type === 'return') {\n results.push(result.value);\n\n return n + 1;\n }\n\n return n;\n },\n 0\n );\n\n handleFailure.call(this, {\n pass: resultsCount > 0,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`Expected returns: ${ EXPECTED('0') }`);\n info.push(`Received returns: ${ RECEIVED(resultsCount.toString()) }\\n`);\n info.push(serializeReturnList(undefined, results));\n info.push(`\\nCalls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(info) {\n info.push(`Expected returns: >= ${ EXPECTED('1') }`);\n info.push(`Received returns: ${ RECEIVED(resultsCount.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that a mock function has returned a specific number of times.\n *\n * @param expected - The expected number of times the mock function should have returned.\n *\n * @remarks\n * This matcher performs the following steps:\n * 1. Validates that `this.received` is a mock function using {@link ensureMock}.\n * 2. Ensures that the `expected` value is a positive number using {@link ensurePositiveNumber}.\n * 3. Counts the number of returned values in the mock's results.\n * 4. Delegates assertion reporting to {@link handleFailure}, including a summary of total calls.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n * @throws If `expected` is not a positive number, {@link ensurePositiveNumber} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn();\n * xExpect(mockFn).toHaveReturnedTimes(1); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * xExpect(mockFn).toHaveReturnedTimes(2); // Fails if the function returned fewer or more times\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveReturnedTimes(this: MatcherService<MockStateInterface>, expected: number): void {\n const expectedLabels = [ 'expected' ];\n ensureMock.call(this, expectedLabels);\n ensurePositiveNumber.call(this, expected, 'expected', expectedLabels);\n\n const count = this.received.mock.calls.length;\n const resultsCount = this.received.mock.results.reduce(\n (n: number, result: MockInvocationResultInterface<unknown>) => result.type === 'return' ? n + 1 : n,\n 0\n );\n\n handleFailure.call(this, {\n expectedLabels,\n pass: resultsCount == expected,\n expected: expected,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`Expected returns: != ${ EXPECTED(expected.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(info) {\n info.push(`Expected returns: ${ EXPECTED(expected.toString()) }`);\n info.push(`Received returns: ${ RECEIVED(resultsCount.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that the last return value of a mock function matches the expected value.\n *\n * @param expected - The value expected to have been returned by the last invocation of the mock.\n *\n * @remarks\n * This matcher performs the following steps:\n * 1. Ensures `this.received` is a mock function using {@link ensureMock}.\n * 2. Collects all return values from the mock's results.\n * 3. Compares the last returned value to `expected` using deep equality via {@link equals}.\n * 4. Delegates assertion reporting to {@link handleFailure}, including serialized return values and call count.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(1);\n * mockFn(2);\n * xExpect(mockFn).toHaveLastReturnedWith(2); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn(1);\n * xExpect(mockFn).toHaveLastReturnedWith(2); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveLastReturnedWith(this: MatcherService<MockStateInterface>, expected: unknown): void {\n const expectedLabels = [ 'expected' ];\n ensureMock.call(this, expectedLabels);\n\n const results: Array<unknown> = [];\n const count = this.received.mock.calls.length;\n const resultsCount = this.received.mock.results.reduce(\n (n: number, result: MockInvocationResultInterface<unknown>) => {\n if (result.type === 'return') {\n results.push(result.value);\n\n return n + 1;\n }\n\n return n;\n },\n 0\n );\n\n const result = results.at(-1);\n const pass = results.length > 0 && equals(expected, result);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n expected: expected,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`Expected returns: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push('Received returns:\\n');\n info.push(serializeReturnList(expected, results, resultsCount));\n info.push(`\\nCalls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(info) {\n info.push(`Expected returns: ${ EXPECTED(serializeOneLine(expected)) }`);\n if (results.length > 0) {\n info.push('Received returns:\\n');\n info.push(serializeReturnList(expected, results, resultsCount));\n }\n\n info.push(`\\nReturns: ${ RECEIVED(resultsCount.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n\n/**\n * Asserts that a specific invocation of a mock function returned the expected value.\n *\n * @param nthCall - The 1-based index of the call to check.\n * @param expected - The value expected to have been returned by the `nthCall` invocation.\n *\n * @remarks\n * This matcher performs the following steps:\n * 1. Ensures `this.received` is a mock function using {@link ensureMock}.\n * 2. Validates that `nthCall` is a positive number using {@link ensurePositiveNumber}.\n * 3. Collects all return values from the mock's results.\n * 4. Compares the return value of the `nthCall` invocation to `expected` using deep equality via {@link equals}.\n * 5. Delegates assertion reporting to {@link handleFailure}, including serialized return values, the call index, and call count.\n *\n * @throws If `this.received` is not a mock function, {@link ensureMock} will throw.\n * @throws If `nthCall` is not a positive number, {@link ensurePositiveNumber} will throw.\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn('a');\n * mockFn('b');\n * xExpect(mockFn).toHaveNthReturnedWith(2, 'b'); // Passes\n * ```\n *\n * @example\n * ```ts\n * const mockFn = xJet.fn();\n * mockFn('a');\n * xExpect(mockFn).toHaveNthReturnedWith(2, 'b'); // Fails, only one call\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveNthReturnedWith(this: MatcherService<MockStateInterface>, nthCall: number, expected: unknown): void {\n const expectedLabels = [ 'nthCall', 'expected' ];\n ensureMock.call(this, expectedLabels);\n ensurePositiveNumber.call(this, nthCall, 'nthCall', expectedLabels);\n\n const results: Array<unknown> = [];\n const count = this.received.mock.calls.length;\n const resultsCount = this.received.mock.results.reduce(\n (n: number, result: MockInvocationResultInterface<unknown>) => {\n if (result.type === 'return') {\n results.push(result.value);\n\n return n + 1;\n }\n\n return n;\n },\n 0\n );\n\n const result = results.at(nthCall - 1);\n const pass = nthCall <= results.length && equals(expected, result);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n expected: expected,\n receivedLabeled: this.received.name,\n handleNot(info) {\n info.push(`nthCall: ${ nthCall }`);\n info.push(`Expected returns: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push('Received returns:\\n');\n info.push(serializeReturnList(expected, results, nthCall));\n info.push(`\\nReturns: ${ RECEIVED(resultsCount.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n },\n handleInfo(info) {\n info.push(`nthCall: ${ nthCall }`);\n info.push(`Expected returns: ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push('Received returns:\\n');\n info.push(serializeReturnList(expected, results, nthCall));\n\n info.push(`\\nReturns: ${ RECEIVED(resultsCount.toString()) }`);\n info.push(`Calls: ${ RECEIVED(count.toString()) }`);\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\n\n/**\n * Imports\n */\n\nimport { EXPECTED, RECEIVED } from '@components/color.component';\nimport { equals, isAsymmetric } from '@components/object.component';\nimport { handleDiffFailure, handleFailure, serializeOneLine } from '@handlers/matchers.handler';\n\n/**\n * Checks if the received value is exactly the expected value using Object.is,\n * or matches an asymmetric matcher.\n *\n * @param expected - The expected value or asymmetric matcher.\n *\n * @remarks\n * Uses Object.is for strict equality comparison unless an asymmetric matcher\n * is provided, which will be used to match the received value.\n *\n * If the check fails but the values are deeply equal,\n * a note suggests using \"toEqual\" instead.\n *\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(['hello']).toBe(['hello']); // Fails because arrays differ by reference\n * xExpect(['hello']).toBe(xExpect.arrayContaining(['hello'])); // Passes with asymmetric matcher\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBe(this: MatcherService, expected: unknown): void {\n const pass = isAsymmetric(expected)\n ? expected.matches(this.received)\n : Object.is(this.received, expected);\n\n const note =\n !pass && equals(this.received, expected)\n ? 'If it should pass with deep equality, replace \"toBe\" with \"toEqual\"'\n : undefined;\n\n handleDiffFailure.call(this, {\n note,\n pass,\n expected,\n comment: 'Object.is equality',\n expectedLabels: [ 'expected' ]\n });\n}\n\n/**\n * Checks if the received value deeply equals the expected value.\n *\n * @param expected - The expected value to compare deeply against.\n *\n * @remarks\n * Uses deep equality comparison via `equals` function.\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect({ a: 1 }).toEqual({ a: 1 }); // Passes with deep equality\n * xExpect({ a: 1 }).toEqual(xExpect.objectContaining({ a: 1 })); // Passes with asymmetric matcher\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toEqual(this: MatcherService, expected: unknown): void {\n const pass = equals(this.received, expected);\n handleDiffFailure.call(this, {\n pass,\n expected,\n comment: 'deep equality',\n expectedLabels: [ 'expected' ]\n });\n}\n\n/**\n * Checks if the received value is exactly null.\n *\n * @remarks\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(null).toBeNull(); // Passes\n * xExpect(undefined).toBeNull(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeNull(this: MatcherService): void {\n const pass = this.received === null;\n handleDiffFailure.call(this, {\n pass,\n expected: null\n });\n}\n\n/**\n * Checks if the received value is exactly undefined.\n *\n * @remarks\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(undefined).toBeUndefined(); // Passes\n * xExpect(null).toBeUndefined(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeUndefined(this: MatcherService): void {\n const pass = this.received === undefined;\n handleDiffFailure.call(this, {\n pass,\n expected: undefined\n });\n}\n\n/**\n * Checks if the received value is NaN.\n *\n * @remarks\n * Uses Number.isNaN for validation.\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(NaN).toBeNaN(); // Passes\n * xExpect(0 / 0).toBeNaN(); // Passes\n * xExpect(1).toBeNaN(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeNaN(this: MatcherService): void {\n const pass = Number.isNaN(this.received);\n handleDiffFailure.call(this, {\n pass,\n expected: NaN\n });\n}\n\n/**\n * Checks if the received value is truthy.\n *\n * @remarks\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(1).toBeTruthy(); // Passes\n * xExpect('non-empty string').toBeTruthy(); // Passes\n * xExpect(false).toBeTruthy(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeTruthy(this: MatcherService): void {\n const pass = !!this.received;\n handleDiffFailure.call(this, {\n pass,\n expected: true\n });\n}\n\n/**\n * Checks if the received value is falsy.\n *\n * @remarks\n * Throws an error if the assertion fails.\n *\n * @example\n * ```ts\n * xExpect(0).toBeFalsy(); // Passes\n * xExpect('').toBeFalsy(); // Passes\n * xExpect(true).toBeFalsy(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeFalsy(this: MatcherService): void {\n const pass = !this.received;\n handleDiffFailure.call(this, {\n pass,\n expected: false\n });\n}\n\n\n/**\n * Checks if the received value is defined (not undefined).\n *\n * @remarks\n * Throws an error if the assertion fails.\n * Provides custom messages for \"not\" modifier showing expected and received values.\n *\n * @example\n * ```ts\n * xExpect('value').toBeDefined(); // Passes\n * xExpect(undefined).toBeDefined(); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeDefined(this: MatcherService): void {\n const pass = this.received !== void 0;\n handleFailure.call(this, {\n pass,\n expected: undefined,\n handleNot(this: MatcherService, info: Array<string>): void {\n info.push(`Expected: ${ EXPECTED(serializeOneLine(undefined)) }`);\n },\n handleInfo(this: MatcherService, info: Array<string>): void {\n info.push(`Received: ${ RECEIVED(serializeOneLine(this.received)) }`);\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MatcherService } from '@services/matcher.service';\nimport type { ConstructorType, FunctionType } from '@interfaces/functions.interface';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { equals } from '@components/object.component';\nimport { getType } from '@diff/components/diff.component';\nimport { serialize } from '@components/serialize.component';\nimport { handleFailure, serializeOneLine } from '@handlers/matchers.handler';\nimport { DIM, EXPECTED, INVERSE, MARK, RECEIVED } from '@components/color.component';\nimport { ensureNotNullish, ensureType, handleDiffFailure } from '@handlers/matchers.handler';\n\n/**\n * Asserts that the received object contains the specified property path,\n * and optionally that the value at that path equals the expected value.\n *\n * @param path - Dot-separated string or array of strings representing the property path.\n * @param expectedValue - Optional expected value at the given path.\n *\n * @throws xJetTypeError - Throws if the received value is null/undefined, or if path is not string/array.\n *\n * @remarks\n * This matcher supports nested properties using dot notation.\n * If the `expectedValue` is provided, it also checks strict equality (Object.is) at the property path.\n *\n * @example\n * ```ts\n * xExpect({ a: { b: 42 } }).toHaveProperty('a.b', 42); // Passes\n * xExpect({ a: {} }).toHaveProperty(['a', 'b']); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toHaveProperty(this: MatcherService<object>, path: string | Array<string>, expectedValue?: unknown): void {\n const expectedLabels = [ 'path', 'value' ];\n ensureNotNullish.call(this, this.received, 'Received', expectedLabels);\n ensureType.call(this, path, [ 'string', 'Array' ], 'Expected path', expectedLabels);\n\n let pass = true;\n let current = this.received;\n const pathFound: Array<string> = [];\n const pathArray = typeof path === 'string' ? path.split('.').filter(Boolean) : path;\n\n for (const segment of pathArray) {\n if (!current || !Object.hasOwn(current, segment)) {\n pass = false;\n break;\n }\n\n pathFound.push(segment);\n current = current[segment as keyof object];\n }\n\n if (pass && expectedValue !== undefined)\n pass = equals(current, expectedValue);\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n handleNot(info) {\n info.push(`Expected: not ${ EXPECTED(serializeOneLine(pathArray)) }\\n`);\n\n if (expectedValue) {\n info.push(`Expected value: ${ EXPECTED(serializeOneLine(expectedValue)) }`);\n } else {\n info.push(`Received value: ${ RECEIVED(serializeOneLine(current)) }`);\n }\n },\n handleInfo(info) {\n info.push(`Expected path: ${ EXPECTED(serializeOneLine(pathArray)) }`);\n if (!Object.is(pathFound.join(''), pathArray.join('')))\n info.push(`Received path: ${ RECEIVED(serializeOneLine(pathFound)) }`);\n\n info.push('');\n if (expectedValue) {\n info.push(`Expected value: ${ EXPECTED(serializeOneLine(expectedValue)) }`);\n }\n\n info.push(`Received value: ${ RECEIVED(serializeOneLine(current)) }`);\n }\n });\n}\n\n/**\n * Asserts that the received value is an instance of the provided constructor.\n *\n * @param instance - Constructor function or class to match against.\n *\n * @throws xJetTypeError - Throws if `instance` is not a function.\n *\n * @remarks\n * Useful for validating that a value is created from a specific class or constructor.\n * Works with built-in classes as well as custom constructors.\n *\n * @example\n * ```ts\n * xExpect(new Date()).toBeInstanceOf(Date); // Passes\n * xExpect({}).toBeInstanceOf(Array); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toBeInstanceOf(this: MatcherService, instance: FunctionType | ConstructorType): void {\n const expectedLabels = [ 'expected' ];\n ensureType.call(this, instance, [ 'function' ], 'Received', expectedLabels);\n\n const received = this.received;\n const pass = received instanceof instance;\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n handleNot(info) {\n info.push(`Expected constructor: not ${ EXPECTED(instance.name) }\\n`);\n },\n handleInfo(info) {\n info.push(`Expected constructor: ${ EXPECTED(instance.name) }`);\n\n if (received !== null && typeof received === 'object' && Object.getPrototypeOf(received) !== null && 'constructor' in received) {\n info.push(`Received constructor: ${ RECEIVED((received as object).constructor.name) }`);\n } else {\n info.push('\\nReceived value has no prototype');\n info.push(`Received value: ${ RECEIVED(serializeOneLine(received)) }`);\n }\n }\n });\n}\n\n/**\n * Asserts that the received string or array contains the expected value.\n *\n * @param expected - The value or substring to search for.\n *\n * @throws xJetTypeError - Throws if received is a string and expected is not a string,\n * or if received is not string/array.\n *\n * @remarks\n * For arrays, this matcher uses reference equality.\n * For strings, it checks for substring inclusion.\n * Use `toContainEqual` for deep equality in arrays.\n *\n * @example\n * ```ts\n * xExpect([1, 2, 3]).toContain(2); // Passes\n * xExpect('hello world').toContain('world'); // Passes\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toContain(this: MatcherService<Array<unknown> | string>, expected: unknown): void {\n const expectedLabels = [ 'expected' ];\n ensureType.call(this, this.received, [ 'string', 'Array' ], 'Received', expectedLabels);\n\n const received = this.received;\n const receivedType = getType(received);\n\n if (typeof received === 'string' && typeof expected !== 'string') {\n throw new xJetTypeError({\n expectedLabels,\n message: `${ EXPECTED('expected') } value must be a string if ${ RECEIVED('received') } value is a string`,\n expected: { value: expected, type: getType(expected) },\n received: { value: received, type: receivedType },\n assertionChain: this.assertionChain\n });\n }\n\n const index = received.indexOf(<string> expected);\n const pass = index !== -1;\n\n handleFailure.call(this, {\n pass,\n expectedLabels,\n comment: 'indexOf',\n handleNot(info) {\n if (receivedType === 'string') {\n info.push(`Expected substring: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received string: ${ RECEIVED(serializeOneLine(received)).replace(\n String(expected), INVERSE(String(expected))\n ) }`);\n } else {\n info.push(`Expected value: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received array: ${ RECEIVED(serializeOneLine(received)).replace(\n serializeOneLine(expected), INVERSE(serializeOneLine(expected))\n ) }`);\n }\n },\n handleInfo(info) {\n if (receivedType === 'string') {\n info.push(`Expected substring: ${ EXPECTED(serialize(expected, '').join('\\n')) }`);\n info.push(`Received string: ${ RECEIVED(serialize(receivedType, '').join('\\n')) }`);\n } else {\n const x = [ ...received ].findIndex(item =>\n equals(item, expected)\n );\n\n if (x !== -1) {\n info.push(\n DIM(\n 'Looks like you wanted to test for object/array equality with the stricter `toContain` matcher.\\n' +\n `You probably need to use \\`${ MARK('toContainEqual') }\\` instead.\\n`\n )\n );\n }\n\n info.push(`Expected value: ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received array: ${ RECEIVED(serializeOneLine(receivedType)) }`);\n }\n }\n });\n}\n\n/**\n * Asserts that the received array contains an element deeply equal to the expected value.\n *\n * @param expected - The value to search for using deep equality.\n *\n * @throws xJetTypeError - Throws if received is not an array.\n *\n * @remarks\n * Use this matcher when you need deep equality comparison (e.g., objects or arrays inside an array).\n * For primitive arrays or substring checks, use `toContain`.\n *\n * @example\n * ```ts\n * xExpect([{ a: 1 }, { b: 2 }]).toContainEqual({ a: 1 }); // Passes\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toContainEqual(this: MatcherService<Array<unknown>>, expected: unknown): void {\n const expectedLabels = [ 'expected' ];\n ensureType.call(this, this.received, [ 'string', 'Array' ], 'Received', expectedLabels);\n\n const received = this.received;\n const receivedType = getType(received);\n\n\n const index = [ ...received ].findIndex(item =>\n equals(item, expected)\n );\n\n const pass = index !== -1;\n handleFailure.call(this, {\n pass,\n expectedLabels,\n comment: 'deep equality',\n handleNot(info) {\n info.push(`Expected value: not ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received array: ${ RECEIVED(serializeOneLine(received)).replace(\n serializeOneLine(expected), INVERSE(serializeOneLine(expected))\n ) }`);\n },\n handleInfo(info) {\n if (receivedType === 'string' && typeof expected === 'string' && received.indexOf(expected) !== -1) {\n info.push(\n DIM(\n 'Looks like you wanted to test for string equality with the stricter `toContainEqual` matcher. ' +\n 'You probably need to use `toContain` instead.\\n'\n )\n );\n }\n\n info.push(`Expected: ${ EXPECTED(serializeOneLine(expected)) }`);\n info.push(`Received: ${ RECEIVED(serializeOneLine(received)) }`);\n }\n });\n}\n\n/**\n * Asserts that the received object matches the expected object.\n * Performs a deep equality comparison for all keys in the expected object.\n *\n * @param expected - The expected object to match against.\n *\n * @throws xJetTypeError - Throws if received or expected is not an object.\n *\n * @remarks\n * Only the keys present in `expected` are checked. Extra keys in the received object are ignored.\n * Useful for partial object matching.\n *\n * @example\n * ```ts\n * xExpect({ a: 1, b: 2 }).toMatchObject({ a: 1 }); // Passes\n * xExpect({ a: 1 }).toMatchObject({ a: 1, b: 2 }); // Fails\n * ```\n *\n * @since 1.0.0\n */\n\nexport function toMatchObject(this: MatcherService<object>, expected: object): void {\n const expectedLabels = [ 'expected' ];\n ensureNotNullish.call(this, this.received, 'Received', expectedLabels);\n ensureType.call(this, this.received, [ 'object' ], 'Received', expectedLabels);\n ensureType.call(this, expected, [ 'object' ], 'Expected', expectedLabels);\n\n const received = this.received;\n const pass = equals(expected, received, false);\n\n handleDiffFailure.call(this, {\n pass,\n expected,\n expectedLabels\n });\n}\n", "/**\n * Imports\n */\n\nimport { toThrow } from '@matchers/functions.matcher';\nimport { toHaveLength, toMatch } from '@matchers/string.matcher';\nimport { toBeCloseTo, toBeGreaterThan } from '@matchers/number.matcher';\nimport { toHaveReturned, toHaveReturnedTimes } from '@matchers/mock.matcher';\nimport { toBeTruthy, toBeFalsy, toBeDefined } from '@matchers/equality.matcher';\nimport { toHaveLastReturnedWith, toHaveNthReturnedWith } from '@matchers/mock.matcher';\nimport { toHaveBeenLastCalledWith, toHaveBeenNthCalledWith } from '@matchers/mock.matcher';\nimport { toBe, toEqual, toBeNull, toBeUndefined, toBeNaN } from '@matchers/equality.matcher';\nimport { toBeGreaterThanOrEqual, toBeLessThan, toBeLessThanOrEqual } from '@matchers/number.matcher';\nimport { toHaveBeenCalled, toHaveBeenCalledTimes, toHaveBeenCalledWith } from '@matchers/mock.matcher';\nimport { toHaveProperty, toBeInstanceOf, toContain, toContainEqual, toMatchObject } from '@matchers/object.matcher';\n\n/**\n * Unified collection of matcher factories for use in the xJet framework.\n *\n * Exposes asymmetric matcher creators across multiple domains, including\n * numbers, strings, objects, equality, mocks, and functions.\n *\n * @remarks\n * All matchers are provided as immutable factories (`as const`) and can be used\n * directly in test assertions for expressive, readable expectations.\n *\n * @example\n * ```ts\n * xExpect(42).toSatisfy(Matchers.number.greaterThan(10));\n * xExpect('hello').toSatisfy(Matchers.strings.contains('ell'));\n * xExpect(fn).toSatisfy(Matchers.functions.calledOnce());\n * ```\n *\n * @since 1.0.0\n */\n\nexport const Matchers = {\n // functions\n toThrow,\n\n // strings\n toMatch,\n toHaveLength,\n\n // objects\n toContain,\n toMatchObject,\n toHaveProperty,\n toBeInstanceOf,\n toContainEqual,\n\n // equality\n toBe,\n toEqual,\n toBeNaN,\n toBeNull,\n toBeFalsy,\n toBeTruthy,\n toBeDefined,\n toBeUndefined,\n\n // numbers\n toBeCloseTo,\n toBeLessThan,\n toBeGreaterThan,\n toBeLessThanOrEqual,\n toBeGreaterThanOrEqual,\n\n // mock\n toHaveReturned,\n toHaveBeenCalled,\n toHaveReturnedTimes,\n toHaveBeenCalledWith,\n toHaveBeenCalledTimes,\n toHaveNthReturnedWith,\n toHaveLastReturnedWith,\n toHaveBeenNthCalledWith,\n toHaveBeenLastCalledWith\n} as const;\n", "/**\n * Abstract base class for asymmetric matchers with support for inversion logic.\n *\n * Provides a foundation for matchers that can optionally invert their match results.\n * Includes a name identifier and a flag indicating whether to invert the match outcome.\n *\n * @param name - The name of the pattern, used for identification or debugging\n * @param isInverse - If true, the match result is inverted; defaults to false\n *\n * @remarks\n * Subclasses must implement the `matches` method to perform the matching logic and\n * the `expectedLabel` getter to provide a label describing the expected pattern.\n *\n * The protected method `applyInverse` applies inversion to the boolean result based\n * on the `isInverse` flag.\n *\n * @since 1.0.0\n */\n\nexport abstract class AbstractPattern {\n /**\n * Creates an instance of the pattern with a name and optional inversion flag.\n *\n * @param name - The name of the pattern, used for identification or debugging\n * @param isInverse - Indicates whether the match result should be inverted (default is false)\n *\n * @since 1.0.0\n */\n\n protected constructor(public readonly name: string, public readonly isInverse = false) {\n }\n\n /**\n * Determines whether the received value matches this pattern.\n *\n * @param received - The value to test against the pattern\n * @returns True if the value matches the pattern (after applying inversion if enabled)\n *\n * @since 1.0.0\n */\n\n abstract matches(received: unknown): boolean;\n\n /**\n * A label describing the expected pattern, used in error messages or debugging.\n *\n * @since 1.0.0\n */\n\n abstract get expectedLabel(): string;\n\n /**\n * Applies inversion logic to the given result based on the `isInverse` flag.\n *\n * @param result - The original match result\n * @returns The possibly inverted match result\n *\n * @since 1.0.0\n */\n\n protected applyInverse(result: boolean): boolean {\n return this.isInverse ? !result : result;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConstructorType } from '@interfaces/functions.interface';\n\n/**\n * Imports\n */\n\nimport { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Asymmetric matcher that matches any value of the specified constructor type.\n *\n * Supports common JavaScript types with specialized checks for primitive wrappers\n * and arrays, falling back to `instanceof` for other types.\n *\n * @throws TypeError - If called with `undefined` as the expected constructor\n *\n * @remarks\n * Use `AnyPattern.create` to instantiate the matcher. Throws a `TypeError` if called\n * without a constructor argument.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.any(Number));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class AnyPattern extends AbstractPattern {\n /**\n * Map of constructor names to type-checking functions for common JavaScript types.\n *\n * Each function returns true if the given value matches the corresponding type,\n * including primitive wrappers and arrays.\n *\n * @since 1.0.0\n */\n\n private static readonly TYPE_CHECKS: Record<string, (value: unknown) => boolean> = {\n String: (actual) => typeof actual === 'string' || actual instanceof String,\n Number: (actual) => typeof actual === 'number' || actual instanceof Number,\n Function: (actual) => typeof actual === 'function' || actual instanceof Function,\n Boolean: (actual) => typeof actual === 'boolean' || actual instanceof Boolean,\n BigInt: (actual) => typeof actual === 'bigint' || actual instanceof BigInt,\n Symbol: (actual) => typeof actual === 'symbol' || actual instanceof Symbol,\n Object: (actual) => typeof actual === 'object',\n Array: Array.isArray\n };\n\n /**\n * Constructs a new `AnyPattern` instance with the specified expected constructor.\n *\n * @param expected - The constructor function this pattern will match against\n *\n * @since 1.0.0\n */\n\n private constructor(public readonly expected: ConstructorType) {\n super(`Any<${ expected.name }>`);\n }\n\n /**\n * Creates a new `AnyPattern` matcher for the specified constructor.\n *\n * @param expected - The constructor function to match values against\n * @returns A new `AnyPattern` instance\n *\n * @throws TypeError - If `expected` is `undefined`\n *\n * @example\n * ```ts\n * const matcher = AnyPattern.create(Number);\n * ```\n *\n * @since 1.0.0\n */\n\n static create(expected: ConstructorType): AnyPattern {\n if (expected === undefined) {\n throw new TypeError(\n 'any() expects to be passed a constructor function. ' +\n 'Please pass one or use anything() to match any object.'\n );\n }\n\n return new AnyPattern(expected);\n }\n\n /**\n * A label describing the expected constructor type.\n *\n * @returns A string of the form `Any<ConstructorName>`\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return `Any<${ this.expected.name }>`;\n }\n\n /**\n * Determines whether the received value matches the expected constructor type.\n *\n * @param received - The value to test\n * @returns True if the value matches the expected type; otherwise false\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (this.expected.name in AnyPattern.TYPE_CHECKS)\n return AnyPattern.TYPE_CHECKS[this.expected.name](received);\n\n return received instanceof this.expected;\n }\n}\n", "/**\n * Imports\n */\n\nimport { serialize } from '@components/serialize.component';\nimport { AbstractPattern } from '@patterns/abstract.pattern';\nimport { equals, isAsymmetric } from '@components/object.component';\n\n/**\n * Asymmetric matcher that checks if every element in an array matches a given matcher or value.\n *\n * Supports optional inversion of the match result.\n *\n * @param isInverse - Indicates whether the match result should be inverted\n * @param expected - The matcher or value that each element is expected to match\n *\n * @remarks\n * Use `ArrayOfPattern.create` to instantiate this matcher. Throws a `TypeError` if `expected` is `undefined`.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.arrayOf(42));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class ArrayOfPattern extends AbstractPattern {\n /**\n * Constructs a new `ArrayOfPattern`.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected matcher or value for each element\n *\n * @since 1.0.0\n */\n\n private constructor(isInverse: boolean, private expected: unknown) {\n super('ArrayOf', isInverse);\n }\n\n /**\n * Creates an `ArrayOfPattern` matcher.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The matcher or value that each element should match\n *\n * @returns A new `ArrayOfPattern` instance\n *\n * @throws TypeError - If `expected` is `undefined`\n *\n * @since 1.0.0\n */\n\n static create(isInverse: boolean, expected: unknown): ArrayOfPattern {\n if (expected === undefined) {\n throw new TypeError('arrayOf() expects a matcher or value.');\n }\n\n return new ArrayOfPattern(isInverse, expected);\n }\n\n /**\n * A label describing the expected array-of pattern.\n *\n * @returns A string indicating the expected matcher/value and inversion status\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return `${ this.isInverse ? 'Not ' : '' }ArrayOf( ${ this.describe(this.expected) } )`;\n }\n\n /**\n * Determines whether every element in the received array matches the expected matcher or value.\n *\n * @param received - The array to test\n *\n * @returns True if all elements match; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (!Array.isArray(received)) {\n return this.applyInverse(false);\n }\n\n // Check every element matches elementMatcher\n const allMatch = received.every((item) => this.matchElement(item, this.expected));\n\n return this.applyInverse(allMatch);\n }\n\n /**\n * Tests whether an item matches a matcher or equals a value, supporting asymmetric matchers.\n *\n * @param item - The actual item to test\n * @param matcher - The matcher or value to compare against\n *\n * @returns True if the item matches the matcher or equals the value; otherwise false\n *\n * @since 1.0.0\n */\n\n private matchElement(item: unknown, matcher: unknown): boolean {\n if (isAsymmetric(matcher)) return matcher.matches(item);\n\n return equals(item, matcher);\n }\n\n /**\n * Returns a string description of the expected matcher or value, supporting asymmetric matchers.\n *\n * @param value - The value to describe\n *\n * @returns A string description of the value\n *\n * @since 1.0.0\n */\n\n private describe(value: unknown): string {\n if (isAsymmetric(value)) return value.expectedLabel;\n if (typeof value === 'string') return `\"${ value }\"`;\n\n return serialize(value, '').join(' ');\n }\n}\n", "/**\n * Imports\n */\n\nimport { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Asymmetric matcher that checks if a number is close to an expected value within a specified precision.\n *\n * Supports optional inversion of the match result.\n *\n * @param inverse - Indicates whether the match result should be inverted\n * @param expected - The expected numeric value to compare against\n * @param precision - Number of decimal digits for precision (default is 2)\n *\n * @remarks\n * Use `CloseToPattern.create` to instantiate this matcher.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.closeTo(3.14, 2));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class CloseToPattern extends AbstractPattern {\n /**\n * Constructs a new `CloseToPattern`.\n *\n * @param inverse - Whether to invert the match result\n * @param expected - The expected numeric value\n * @param precision - Decimal precision, defaults to 2\n *\n * @since 1.0.0\n */\n\n private constructor(inverse: boolean, public readonly expected: number, public readonly precision: number = 2) {\n super('CloseTo', inverse);\n }\n\n /**\n * Creates a `CloseToPattern` matcher.\n *\n * @param inverse - Whether to invert the match result\n * @param expected - The expected numeric value\n * @param precision - Optional decimal precision\n *\n * @returns A new `CloseToPattern` instance\n *\n * @since 1.0.0\n */\n\n static create(inverse: boolean, expected: number, precision?: number): CloseToPattern {\n return new CloseToPattern(inverse, expected, precision);\n }\n\n /**\n * A label describing the expected close-to pattern.\n *\n * @returns A string describing the expected value and precision, indicating inversion if applicable\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n const not = this.isInverse ? 'Not ' : '';\n const precisionLabel = this.precision !== 1 ? 's' : '';\n\n return `${ not }CloseTo(${ this.expected }, ${ this.precision } digit${ precisionLabel })`;\n }\n\n /**\n * Determines whether the received value is close to the expected value within the specified precision.\n *\n * @param received - The value to test\n *\n * @returns True if the value is within the precision range; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n const sample: unknown = this.expected;\n\n if (typeof received !== 'number' || typeof sample !== 'number')\n return this.applyInverse(false);\n\n return this.applyInverse(\n Math.abs(received - sample) < Math.pow(10, -this.precision) / 2\n );\n }\n}\n", "/**\n * Imports\n */\n\nimport { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Asymmetric matcher that matches any non-null and non-undefined value.\n *\n * @remarks\n * Use `AnythingPattern.create` to instantiate this matcher.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.anything());\n * ```\n *\n * @since 1.0.0\n */\n\nexport class AnythingPattern extends AbstractPattern {\n /**\n * Constructs a new `AnythingPattern` instance.\n *\n * @since 1.0.0\n */\n\n private constructor() {\n super('Anything');\n }\n\n /**\n * Creates a new `AnythingPattern` matcher.\n *\n * @returns A new `AnythingPattern` instance\n *\n * @since 1.0.0\n */\n\n static create(): AnythingPattern {\n return new AnythingPattern();\n }\n\n /**\n * A label describing the expected pattern.\n *\n * @returns The string `'Anything'`\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return 'Anything';\n }\n\n /**\n * Determines whether the received value is not `null` or `undefined`.\n *\n * @param received - The value to test\n *\n * @returns True if the value is not `null` or `undefined`; otherwise false\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n return received != null;\n }\n}\n", "/**\n * Imports\n */\n\nimport { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Asymmetric matcher that checks if a string matches an expected substring or regular expression.\n *\n * Supports optional inversion of the match result.\n *\n * @param isInverse - Indicates whether the match result should be inverted\n * @param expected - The string or RegExp pattern expected to be matched\n *\n * @remarks\n * Use `StringMatchingPattern.create` to instantiate this matcher.\n * Throws a `TypeError` if `expected` is not a string or RegExp.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.stringMatching('hello'));\n * xExpect(value).toEqual(xExpect.stringMatching(/world$/));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class StringMatchingPattern extends AbstractPattern {\n /**\n * Constructs a new `StringMatchingPattern`.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected string or RegExp to match\n *\n * @since 1.0.0\n */\n\n private constructor(isInverse: boolean, private readonly expected: string | RegExp) {\n super('StringMatching', isInverse);\n }\n\n /**\n * Creates a `StringMatchingPattern` matcher.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The string or RegExp to match against\n *\n * @returns A new `StringMatchingPattern` instance\n *\n * @throws TypeError - If `expected` is not a string or RegExp, or is null/undefined\n *\n * @since 1.0.0\n */\n\n static create(isInverse: boolean, expected: string | RegExp): StringMatchingPattern {\n const expectedType = typeof expected;\n\n if (expected === undefined || expected === null)\n throw new TypeError('stringMatching() expects a string or RegExp.');\n\n if (expectedType !== 'string' && !(expected instanceof RegExp))\n throw new TypeError('stringMatching() expects a string or RegExp.');\n\n return new StringMatchingPattern(isInverse, expected);\n }\n\n /**\n * A label describing the expected string matching pattern.\n *\n * @returns A string indicating the expected substring or pattern and inversion status\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n const not = this.isInverse ? 'Not ' : '';\n if (typeof this.expected === 'string')\n return `${ not }stringMatching(\"${ this.expected }\")`;\n\n return `${ not }stringMatching(${ this.expected.toString() })`;\n }\n\n /**\n * Determines whether the received string matches the expected substring or RegExp.\n *\n * @param received - The string to test\n *\n * @returns True if the string matches; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (typeof received !== 'string') {\n return this.applyInverse(false);\n }\n\n let pass: boolean;\n if (typeof this.expected === 'string') {\n pass = received.includes(this.expected);\n } else {\n pass = this.expected.test(received);\n }\n\n return this.applyInverse(pass);\n }\n}\n", "/**\n * Imports\n */\n\nimport { serialize } from '@components/serialize.component';\nimport { AbstractPattern } from '@patterns/abstract.pattern';\nimport { equals, isAsymmetric } from '@components/object.component';\n\n/**\n * Asymmetric matcher that checks if an array contains all expected elements.\n *\n * Supports optional inversion of the match result.\n *\n * @param isInverse - Indicates whether the match result should be inverted\n * @param expected - The array of elements expected to be contained within the tested array\n *\n * @remarks\n * Use `ArrayContainingPattern.create` to instantiate this matcher. Throws a `TypeError` if the expected value is not an array.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.arrayContaining([1, 2]));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class ArrayContainingPattern extends AbstractPattern {\n /**\n * Constructs a new `ArrayContainingPattern`.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected array elements\n *\n * @since 1.0.0\n */\n\n private constructor(isInverse: boolean, private readonly expected: unknown[]) {\n super('ArrayContaining', isInverse);\n }\n\n /**\n * Creates an `ArrayContainingPattern` matcher.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected array elements\n *\n * @returns A new `ArrayContainingPattern` instance\n *\n * @throws TypeError - If `expected` is not an array\n *\n * @since 1.0.0\n */\n\n static create(isInverse: boolean, expected: Array<unknown>): ArrayContainingPattern {\n if (!Array.isArray(expected)) {\n throw new TypeError('arrayContaining() expects an array.');\n }\n\n return new ArrayContainingPattern(isInverse, expected);\n }\n\n /**\n * A label describing the expected array containing pattern.\n *\n * @returns A string indicating the expected elements and inversion status\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return `${ this.isInverse ? 'Not ' : '' }ArrayContaining(${ this.describe(this.expected) })`;\n }\n\n /**\n * Determines whether the received array contains all expected elements.\n *\n * @param received - The array to test\n *\n * @returns True if all expected elements are contained; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (!Array.isArray(received))\n return this.applyInverse(false);\n\n const allContained = this.expected.every((expItem) =>\n received.some((recItem) => this.matchElement(recItem, expItem))\n );\n\n return this.applyInverse(allContained);\n }\n\n /**\n * Tests whether an item matches a matcher, supporting asymmetric matchers.\n *\n * @param item - The actual item to test\n * @param matcher - The matcher or value to compare against\n *\n * @returns True if the item matches the matcher; otherwise false\n *\n * @since 1.0.0\n */\n\n private matchElement(item: unknown, matcher: unknown): boolean {\n if (isAsymmetric(matcher)) return matcher.matches(item);\n\n return equals(item, matcher);\n }\n\n /**\n * Returns a string description of the expected value, supporting asymmetric matchers.\n *\n * @param value - The value to describe\n * @returns A string description of the value\n *\n * @since 1.0.0\n */\n\n private describe(value: unknown): string {\n if (isAsymmetric(value)) return value.expectedLabel;\n\n return serialize(value, '').join(' ');\n }\n}\n", "/**\n * Imports\n */\n\nimport { serialize } from '@components/serialize.component';\nimport { AbstractPattern } from '@patterns/abstract.pattern';\nimport { equals, isAsymmetric, hasKey } from '@components/object.component';\n\n/**\n * Asymmetric matcher that checks if an object contains the expected key-value pairs.\n *\n * Supports optional inversion of the match result.\n *\n * @param isInverse - Indicates whether the match result should be inverted\n * @param expected - A plain object containing key-value pairs expected to be present\n *\n * @remarks\n * Use `ObjectContainingPattern.create` to instantiate this matcher.\n * Throws a `TypeError` if `expected` is not a plain object.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.objectContaining({ foo: 'bar' }));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class ObjectContainingPattern extends AbstractPattern {\n /**\n * Constructs a new `ObjectContainingPattern`.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected key-value pairs to match\n *\n * @since 1.0.0\n */\n\n private constructor(isInverse: boolean, private readonly expected: Record<string, unknown>) {\n super('ObjectContaining', isInverse);\n }\n\n /**\n * Creates an `ObjectContainingPattern` matcher.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected key-value pairs\n *\n * @returns A new `ObjectContainingPattern` instance\n *\n * @throws TypeError - If `expected` is not a plain object\n *\n * @since 1.0.0\n */\n\n static create(isInverse: boolean, expected: Record<string, unknown>): ObjectContainingPattern {\n if (typeof expected !== 'object' || expected === null || Array.isArray(expected)) {\n throw new TypeError('objectContaining() expects a plain object.');\n }\n\n return new ObjectContainingPattern(isInverse, expected);\n }\n\n /**\n * A label describing the expected object containing pattern.\n *\n * @returns A string indicating the expected key-value pairs and inversion status\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return `${ this.isInverse ? 'Not ' : '' }ObjectContaining(${ this.describe(this.expected) })`;\n }\n\n /**\n * Determines whether the received object contains all expected key-value pairs.\n *\n * @param received - The object to test\n *\n * @returns True if all expected pairs are contained; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (typeof received !== 'object' || received === null) {\n return this.applyInverse(false);\n }\n\n const allMatch = Object.keys(this.expected).every((key) => {\n if (!hasKey(received, key)) return false;\n\n return this.matchElement((received as Record<string, unknown>)[key], this.expected[key]);\n });\n\n return this.applyInverse(allMatch);\n }\n\n /**\n * Tests whether an item matches a matcher or equals a value, supporting asymmetric matchers.\n *\n * @param item - The actual item to test\n * @param matcher - The matcher or value to compare against\n *\n * @returns True if the item matches the matcher or equals the value; otherwise false\n *\n * @since 1.0.0\n */\n\n private matchElement(item: unknown, matcher: unknown): boolean {\n if (isAsymmetric(matcher)) return matcher.matches(item);\n\n return equals(item, matcher);\n }\n\n /**\n * Returns a string description of the expected value, supporting asymmetric matchers.\n *\n * @param value - The value to describe\n *\n * @returns A string description of the value\n *\n * @since 1.0.0\n */\n\n private describe(value: unknown): string {\n if (isAsymmetric(value)) return value.expectedLabel;\n\n return serialize(value, '').join(' ');\n }\n}\n", "/**\n * Imports\n */\n\nimport { AbstractPattern } from '@patterns/abstract.pattern';\n\n/**\n * Asymmetric matcher that checks if a string contains the expected substring.\n *\n * Supports optional inversion of the match result.\n *\n * @param isInverse - Indicates whether the match result should be inverted\n * @param expected - The substring expected to be contained within the tested string\n *\n * @remarks\n * Use `StringContainingPattern.create` to instantiate this matcher. Throws a `TypeError` if the expected value is not a string.\n *\n * @example\n * ```ts\n * xExpect(value).toEqual(xExpect.stringContaining('hello'));\n * ```\n *\n * @since 1.0.0\n */\n\nexport class StringContainingPattern extends AbstractPattern {\n /**\n * Constructs a new `StringContainingPattern`.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected substring\n *\n * @since 1.0.0\n */\n\n private constructor(isInverse: boolean, public readonly expected: string) {\n super('StringContaining', isInverse);\n }\n\n /**\n * Creates a `StringContainingPattern` matcher.\n *\n * @param isInverse - Whether to invert the match result\n * @param expected - The expected substring\n *\n * @returns A new `StringContainingPattern` instance\n *\n * @throws TypeError - If `expected` is not a string\n *\n * @since 1.0.0\n */\n\n static create(isInverse: boolean, expected: string): StringContainingPattern {\n const expectedType = typeof expected;\n if (expectedType !== 'string')\n throw new TypeError('stringContaining() expects a string.');\n\n return new StringContainingPattern(isInverse, expected);\n }\n\n /**\n * A label describing the expected string containing a pattern.\n *\n * @returns A string indicating the expected substring and inversion status\n *\n * @since 1.0.0\n */\n\n get expectedLabel(): string {\n return `${ this.isInverse ? 'Not ' : '' }stringContaining(\"${ this.expected }\")`;\n }\n\n /**\n * Determines whether the received string contains the expected substring.\n *\n * @param received - The string to test\n *\n * @returns True if the string contains the substring; otherwise false (inverted if `isInverse` is true)\n *\n * @since 1.0.0\n */\n\n matches(received: unknown): boolean {\n if (typeof received !== 'string') {\n return this.applyInverse(false);\n }\n\n return this.applyInverse(received.includes(this.expected));\n }\n}\n", "/**\n * Imports\n */\n\nimport { AnyPattern } from '@patterns/any.pattern';\nimport { ArrayOfPattern } from '@patterns/array-of.pattern';\nimport { CloseToPattern } from '@patterns/close-to.pattern';\nimport { AnythingPattern } from '@patterns/anything.pattern';\nimport { StringMatchingPattern } from '@patterns/string-matching.pattern';\nimport { ArrayContainingPattern } from '@patterns/array-containing.pattern';\nimport { ObjectContainingPattern } from '@patterns/object-containing.pattern';\nimport { StringContainingPattern } from '@patterns/string-containing.pattern';\n\n/**\n * Collection of factory methods for creating common pattern matchers in the xJet framework.\n *\n * Provides easy access to asymmetric matcher creators for various matching strategies,\n * including positive and negated (`not`) variants.\n *\n * @remarks\n * Each factory method returns an instance of a pattern matcher configured\n * for the specified matching behavior.\n *\n * The `not` namespace provides inverse matchers that negate the match result.\n *\n * @example\n * ```ts\n * const pattern = Patterns.any(String);\n * const notPattern = Patterns.not.closeTo(5, 0.1);\n * ```\n *\n * @since 1.0.0\n */\n\nexport const Patterns = {\n any: AnyPattern.create,\n anything: AnythingPattern.create,\n closeTo: CloseToPattern.create.bind(null, false),\n arrayOf: ArrayOfPattern.create.bind(null, false),\n stringMatching: StringMatchingPattern.create.bind(null, false),\n arrayContaining: ArrayContainingPattern.create.bind(null, false),\n objectContaining: ObjectContainingPattern.create.bind(null, false),\n stringContaining: StringContainingPattern.create.bind(null, false),\n not: {\n closeTo: CloseToPattern.create.bind(null, true),\n arrayOf: ArrayOfPattern.create.bind(null, true),\n stringMatching: StringMatchingPattern.create.bind(null, true),\n arrayContaining: ArrayContainingPattern.create.bind(null, true),\n objectContaining: ObjectContainingPattern.create.bind(null, false),\n stringContaining: StringContainingPattern.create.bind(null, true)\n }\n} as const;\n\n\n\n", "/**\n * Import will remove at compile time\n */\n\nimport type { OptionsPromiseErrorInterface } from '@errors/interfaces/promise-error.interface';\n\n/**\n * Imports\n */\n\nimport { xJetBaseError } from '@errors/base.error';\nimport { RECEIVED } from '@components/color.component';\nimport { serialize } from '@components/serialize.component';\nimport { composeStatement } from '@components/format.component';\n\n/**\n * Error type representing a failed Promise-related matcher assertion.\n *\n * @remarks\n * Extends xJetBaseError to provide a formatted, Jest-style error message\n * for failed promise expectations. The message includes:\n * - A matcher statement from the provided assertion chain.\n * - A clear description of the matcher failure.\n * - The kind of promise result (`Resolved` or `Rejected`) and its serialized value.\n *\n * Formatting is handled using:\n * - composeStatement to construct the matcher statement.\n * - RECEIVED for styling the received value.\n * - serialize to generate a readable string representation.\n *\n * @example\n * ```ts\n * throw new xJetPromiseError({\n * message: `${RECEIVED('received')} promise resolved instead of rejected`,\n * received: myValue,\n * promiseKind: 'Resolved',\n * assertionChain: ['rejects', 'toThrow'],\n * });\n * ```\n *\n * @see RECEIVED\n * @see serialize\n * @see composeStatement\n * @see OptionsPromiseErrorInterface\n *\n * @since 1.0.0\n */\n\nexport class xJetPromiseError extends xJetBaseError {\n\n /**\n * Creates an xJetPromiseError instance with a formatted,\n * Jest-style matcher error message for promise-related failures.\n *\n * @param options - Configuration object containing the matcher\n * details, failure message, received value, and result kind.\n *\n * @throws Error - If the assertion chain is empty\n * (thrown by composeStatement).\n *\n * @see composeStatement\n * @see OptionsPromiseErrorInterface\n *\n * @since 1.0.0\n */\n\n constructor(options: OptionsPromiseErrorInterface) {\n const lines = [\n `${ composeStatement(options) }\\n`,\n `Matcher error: ${ options.message }`,\n `${ options.promiseKind } to value: ${\n RECEIVED(serialize(options.received, '').join(' '))\n }`\n ];\n\n super(lines.join('\\n'), 'xJetPromiseError');\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionType } from '@interfaces/functions.interface';\nimport type { PromisifiedMatchersType } from '@interfaces/matchers.interface';\n\n/**\n * Imports\n */\n\nimport { xJetTypeError } from '@errors/type.error';\nimport { RECEIVED } from '@components/color.component';\nimport { xJetPromiseError } from '@errors/promise.error';\nimport { isPromise } from '@components/promise.component';\nimport { getType } from '@diff/components/diff.component';\n\n/**\n * Service class for managing matcher assertions with support for modifiers and async handling.\n *\n * @template T - Type of the value being tested.\n *\n * @remarks\n * This class provides the core logic for matcher evaluation in the xJet framework,\n * including support for `.not`, `.resolves`, and `.rejects` modifiers.\n * It handles synchronous and asynchronous matcher invocation, promise validation,\n * and error throwing with detailed context.\n *\n * Internally tracks an assertion chain for composing error messages.\n *\n * @example\n * ```ts\n * await xExpect(promiseValue).resolves.toBe(expectedValue)\n * ```\n *\n * @since 1.0.0\n */\n\nexport class MatcherService<T = unknown> {\n /**\n * The name of the matcher or assertion that was invoked.\n *\n * @since 1.0.0\n */\n\n macherName: string = '';\n\n /**\n * Indicates if the matcher is dealing with a promise resolution or rejection.\n *\n * @internal\n * @since 1.0.0\n */\n\n protected promise?: 'resolves' | 'rejects';\n\n /**\n * Tracks whether the `.not` modifier has been applied.\n *\n * @internal\n * @since 1.0.0\n */\n\n protected notModifier: boolean = false;\n\n /**\n * Chains the sequence of assertions and modifiers applied.\n *\n * @internal\n * @since 1.0.0\n */\n\n protected assertionChain: Array<string> = [];\n\n /**\n * Tracks if the `.rejects` modifier has been applied.\n *\n * @internal\n * @since 1.0.0\n */\n\n protected rejectsModifier: boolean = false;\n\n /**\n * Tracks if the `.resolves` modifier has been applied.\n *\n * @internal\n * @since 1.0.0\n */\n\n protected resolvesModifier: boolean = false;\n\n /**\n * Creates a new MatcherService instance for the received value.\n *\n * @param received - The value or function under test.\n *\n * @since 1.0.0\n */\n\n constructor(protected received: T) {\n }\n\n /**\n * Applies the `.not` modifier, inverting matcher logic.\n *\n * @returns The matcher instance with `.not` applied, excluding chaining `.not`, `.rejects`, and `.resolves`.\n *\n * @since 1.0.0\n */\n\n get not(): Omit<this & PromisifiedMatchersType, 'not' | 'rejects' | 'resolved'> {\n this.notModifier = true;\n\n return <this & PromisifiedMatchersType>this;\n }\n\n\n /**\n * Applies the `.rejects` modifier, expecting the promise to reject.\n *\n * @throws Error - If `.resolves` was previously applied.\n *\n * @returns The matcher instance with `.rejects` applied, excluding chaining `.rejects` and `.resolves`.\n *\n * @since 1.0.0\n */\n\n get rejects(): Omit<PromisifiedMatchersType & this, 'rejects' | 'resolved'> {\n if (this.resolvesModifier) throw new Error('Cannot use \"rejects\" modifier after \"resolved\" modifier.');\n this.rejectsModifier = true;\n\n return <PromisifiedMatchersType & this>this;\n }\n\n /**\n * Applies the `.resolves` modifier, expecting the promise to resolve.\n *\n * @throws Error - If `.rejects` was previously applied.\n *\n * @returns The matcher instance with `.resolves` applied, excluding chaining `.rejects` and `.resolves`.\n *\n * @since 1.0.0\n */\n\n get resolves(): Omit<PromisifiedMatchersType & this, 'rejects' | 'resolved'> {\n if (this.rejectsModifier) throw new Error('Cannot use \"resolved\" modifier after \"rejects\" modifier.');\n this.resolvesModifier = true;\n\n return <PromisifiedMatchersType & this>this;\n }\n\n /**\n * Invokes the matcher synchronously or asynchronously based on modifiers.\n *\n * @param name - The matcher method name.\n * @param matcher - The matcher function to invoke.\n * @param args - Arguments to pass to the matcher.\n *\n * @returns Possibly a Promise resolving when async matchers are used, otherwise void.\n *\n * @since 1.0.0\n */\n\n protected invoke(name: string, matcher: FunctionType, args: Array<unknown>): void | Promise<void> {\n this.macherName = name;\n\n // todo remove invoke and invokeAsync from the stack\n if (this.rejectsModifier || this.resolvesModifier) {\n this.pushToChain(name);\n this.promise = this.resolvesModifier ? 'resolves' : 'rejects';\n\n return this.invokeAsync(matcher, args);\n }\n\n this.pushToChain(name);\n\n return matcher.call(this, ...args);\n }\n\n /**\n * Invokes the matcher asynchronously, handling promises and throwing detailed errors on mismatch.\n *\n * @param matcher - The matcher function to invoke.\n * @param args - Arguments to pass to the matcher.\n *\n * @throws xJetTypeError - If the received value or function result is not a Promise.\n * @throws xJetPromiseError - If the promise resolves or rejects contrary to the expected modifier.\n *\n * @returns A Promise resolving after matcher invocation.\n *\n * @since 1.0.0\n */\n\n protected async invokeAsync(matcher: FunctionType, args: Array<unknown>): Promise<void> {\n let isResolved = false;\n const isFunction = typeof this.received === 'function';\n const valueOrPromise = isFunction ? (this.received as FunctionType)() : this.received;\n\n if (!isPromise(valueOrPromise)) {\n throw new xJetTypeError({\n message: `${ RECEIVED('received') } value must be a promise or a function returning a promise`,\n assertionChain: this.assertionChain,\n received: {\n type: getType(valueOrPromise),\n value: valueOrPromise\n }\n });\n }\n\n try {\n this.received = <T> await valueOrPromise;\n isResolved = true;\n\n } catch (error) {\n if (this.resolvesModifier) this.throwPromiseError('Rejected', error);\n this.received = error as T;\n }\n\n if (isResolved && this.rejectsModifier) this.throwPromiseError('Resolved', this.received);\n\n return matcher.call(this, ...args);\n }\n\n /**\n * Adds modifiers and matcher name to the assertion chain for error message composition.\n *\n * @param name - The matcher method name to add.\n *\n * @internal\n * @since 1.0.0\n */\n\n private pushToChain(name: string): void {\n if (this.promise) this.assertionChain.push(this.promise);\n if (this.notModifier) this.assertionChain.push('not');\n this.assertionChain.push(name);\n }\n\n /**\n * Throws a detailed xJetPromiseError indicating promise resolution/rejection mismatch.\n *\n * @param kind - The kind of promise result encountered ('Resolved' or 'Rejected').\n * @param receivedValue - The actual resolved or rejected value.\n *\n * @throws xJetPromiseError\n *\n * @internal\n * @since 1.0.0\n */\n\n private throwPromiseError(kind: 'Resolved' | 'Rejected', receivedValue: unknown): never {\n const received = kind === 'Resolved' ? 'resolved' : 'rejected';\n const expected = kind === 'Resolved' ? 'rejected' : 'resolved';\n throw new xJetPromiseError({\n message: `${ RECEIVED('received') } promise ${ received } instead of ${ expected }`,\n received: receivedValue,\n promiseKind: kind,\n assertionChain: this.assertionChain\n });\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BoundMatchersType } from '@interfaces/matchers.interface';\n\n/**\n * Imports\n */\n\nimport { Matchers } from '@providers/matchers.provider';\nimport { Patterns } from '@providers/patterns.provider';\nimport { MatcherService } from '@services/matcher.service';\n\n/**\n * Dynamically adds matcher methods to the MatcherService prototype by iterating through\n * the Matchers object and defining properties for each matcher function.\n *\n * @remarks\n * This code creates a dynamic interface for matchers by:\n * 1. Iterating through each key in Matchers object\n * 2. Retrieving the corresponding matcher function\n * 3. Defining a property on the MatcherService prototype with the same name\n * 4. The property value is a function that invokes the matcher via the MatcherService.invoke method\n *\n * This approach allows for extending the matcher functionality without modifying the\n * MatcherService class directly. Each matcher function is bound to the MatcherService\n * instance context when invoked.\n *\n * @example\n * ```ts\n * // Define a matcher in Matchers object\n * const Matchers = {\n * isTrue: function(this: MatcherService) {\n * return this.invoke('isTrue', (actual) => actual === true);\n * }\n * };\n *\n * // The above code will automatically make this available:\n * xExpect(value).isTrue();\n * ```\n *\n * @see Matchers - The object containing all matcher functions\n * @see MatcherService - The service that processes and executes matchers\n *\n * @since 1.0.0\n */\n\nfor (const key of Object.keys(Matchers) as Array<keyof typeof Matchers>) {\n const proto = <MatcherService & BoundMatchersType> MatcherService.prototype;\n const matcherFn = Matchers[key];\n\n Object.defineProperty(proto, key, {\n value: function (...args: Array<unknown>) {\n return this.invoke(key, matcherFn, args);\n }\n });\n\n Object.defineProperty(proto[key], 'name', { value: key });\n}\n\n/**\n * Creates a new matcher service instance for the provided actual value to perform assertions against.\n *\n * @param received - The value to perform assertions on\n * @param rest - Additional arguments (not supported, included only for error handling)\n * @returns An augmented MatcherService instance with bound matcher methods\n *\n * @throws Error - When more than one argument is provided to the function\n *\n * @remarks\n * This function serves as the core implementation of the xExpect function. It creates a new\n * MatcherService instance with the provided value and augments it with all available matcher\n * methods defined in the BoundMatchersType. The resulting object provides a fluent API for\n * writing test assertions.\n *\n * @example\n * ```ts\n * // Basic usage with a single argument\n * const result = coreExpect(42);\n * result.toBe(42); // Passes\n *\n * // Will throw an error due to extra arguments\n * coreExpect(42, 'extra'); // Error: Expect takes at most one argument\n * ```\n *\n * @see MatcherService - The service that processes and executes matchers\n * @see BoundMatchersType - The type that defines all available matcher methods\n *\n * @since 1.0.0\n */\n\nconst coreExpect = (received: unknown, ...rest: Array<never>): MatcherService & BoundMatchersType => {\n if (rest.length > 0) {\n throw new Error(`Expect takes at most one argument. Received ${ rest.length + 1 } arguments instead.`);\n }\n\n return new MatcherService(received) as MatcherService & BoundMatchersType;\n};\n\n/**\n * Main assertion function that creates a new matcher service for the provided value and\n * extends it with additional pattern matching utilities.\n *\n * @remarks\n * This is the primary entry point for the assertion library. It combines the core expect\n * functionality with pattern matchers that allow for powerful asymmetric matching.\n * The `Object.assign` merges the core assertion function with pattern matchers, making\n * them available as properties on the xExpect function itself.\n *\n * @example\n * ```ts\n * // Basic value assertion\n * xExpect(value).toBe(expected);\n *\n * // Using pattern matchers\n * xExpect(value).toEqual(xExpect.any(Number));\n *\n * // Direct use of patterns\n * const matcher = xExpect.any(String);\n * ```\n *\n * @see coreExpect - The base assertion function\n * @see Patterns - Collection of asymmetric matcher patterns\n *\n * @since 2.0.0\n */\n\nexport const xExpect: typeof coreExpect & typeof Patterns = Object.assign(coreExpect, Patterns);\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BoundInterface } from '@shared/components/interfaces/polyfill-component.interface';\nimport type { FunctionLikeType, RejectedValueType, ResolvedValueType } from '@remotex-labs/xjet-expect';\nimport type { MockInvocationResultInterface, MocksStateInterface } from './interfaces/mock-state.interface';\n\n/**\n * @template DEFAULT_MOCK_NAME\n * A constant that holds the default name used for mocking purposes.\n * It is commonly used in testing scenarios to provide a standard mock identifier.\n *\n * @remarks\n * The value of `DEFAULT_MOCK_NAME` is set to 'xJet.mock()'. It is recommended\n * to use this variable as the default name to maintain consistency across\n * mock-related functionalities in your application.\n *\n * @since 1.0.0\n */\n\nconst DEFAULT_MOCK_NAME = 'xJet.mock()';\n\n/**\n * A class representing the mock state for tracking and managing the behavior of mocked functions or classes.\n *\n * @template ReturnType - The type of value returned by the mock function.\n * @template Context - The type representing the context (`this` value) used in the mock function.\n * @template Args - The types of arguments for the mocked function.\n *\n * @remarks\n * This class provides mechanisms to customize and manage the behavior of mocked functions or constructors.\n * It tracks invocation details, allows for behavior customization, and enables resetting or restoring the mock to its original state.\n *\n * @since v1.0.0\n */\n\nexport class MockState<ReturnType = unknown, Args extends Array<unknown> = unknown[], Context = unknown> extends Function {\n /**\n * List of all mocks that created\n */\n\n static mocks: Array<MockState> = [];\n\n /**\n * The `name` property represents the name of the mock function.\n */\n\n override name: string;\n\n /**\n * Flag to detect mock functions\n */\n\n readonly xJetMock: boolean = true;\n\n /**\n * The `state` property holds the detailed state of the mock invocations.\n * It tracks information such as the arguments passed, the results returned, the context (`this` value) used,\n * the instances created, and the order of invocations.\n * This data is automatically updated after each call to the mock.\n *\n * @template ReturnType - The type of value returned by the mock function.\n * @template Context - The type representing the context (`this` value) used in the mock function.\n * @template Args - The types of arguments for the mocked function.\n *\n * @see MocksStateInterface\n *\n * @since v1.0.0\n */\n\n private state: MocksStateInterface<ReturnType, Args, Context>;\n\n /**\n * A private function that restores the mocks original implementation.\n * It resets the mock to its initial state, typically used when restoring\n * the mock after a call to `mockReset` or `mockRestore`.\n *\n * This function is invoked internally to ensure that the mock behaves as\n * originally defined before any changes were made to its behavior or implementation.\n *\n * @since v1.0.0\n */\n\n private readonly restore: FunctionLikeType<void>;\n\n /**\n * A private array that stores the implementations queued to be executed\n * for future invocations of the mock.\n * Each function in this array is invoked in sequence when the mock function is called,\n * with the first queued implementation being used on the first call, the second on the second call, and so on.\n *\n * This property is used in conjunction with methods like `mockImplementationOnce`\n * to specify different behaviors for consecutive calls to the mock.\n *\n * @since v1.0.0\n */\n\n private queuedImplementations: Array<FunctionLikeType<ReturnType, Args, Context>> = [];\n\n /**\n * A private property that holds the current implementation of the mock function.\n * This function is executed whenever the mock is invoked, and can be changed\n * using methods like `mockImplementation` or `mockImplementationOnce`.\n *\n * The `implementation` allows for customizing the behavior of the mock,\n * such as returning specific values, throwing errors, or performing actions.\n *\n * @since v1.0.0\n */\n\n private implementation: FunctionLikeType<ReturnType, Args, Context> | undefined;\n\n /**\n * A private property that holds the original implementation of the mock function.\n * This is the initial function passed to the constructor that defines the mock's default behavior\n * before any customization.\n *\n * @template ReturnType - The type of value returned by the original function.\n * @template Args - The types of arguments for the original function.\n * @template Context - The type representing the context (`this` value) used in the original function.\n *\n * @remarks\n * This property stores the initial implementation provided when creating the mock.\n * If no implementation is provided during construction, it defaults to a function\n * that returns `undefined` cast to the appropriate return type.\n * Unlike `implementation` which can be modified, this property maintains a reference\n * to the original function for scenarios where the original behavior needs to be preserved\n * or restored.\n *\n * @see FunctionLikeType\n * @see MockState.original\n *\n * @since 1.0.0\n */\n\n private readonly originalImplementation: FunctionLikeType<ReturnType, Args, Context>;\n\n /**\n * Constructs a mock object that allows custom implementation, restore capability,\n * and optional naming functionality. This mock is proxied to handle function invocation\n * and class instantiation.\n *\n * @template ReturnType - The type of the value returned by the mock function.\n * @template Context - The type of the context (`this`) for the mock function.\n * @template Args - The type of arguments accepted by the mock function.\n *\n * @param implementation - Optional implementation for the mock function.\n * @param restore - Optional function to restore the mock to its initial state. Defaults to resetting to the provided implementation.\n * @param name - Optional name for the mock instance. Default to a predefined mock name if not provided.\n *\n * @returns A proxied mock object capable of behaving as a callable function or a constructible class.\n *\n * @remarks\n * The mock object can work as both a function and a class, using JavaScript's Proxy API. The restore functionality\n * allows resetting to the original state or implementation. If no implementation is provided, the mock remains uninitialized\n * but still functional.\n *\n * @see FunctionLikeType\n * @see VoidFunctionType\n *\n * @since 1.0.0\n */\n\n constructor(implementation?: FunctionLikeType<ReturnType, Args, Context>, restore?: FunctionLikeType<void>, name?: string) {\n super();\n this.name = name ?? DEFAULT_MOCK_NAME;\n this.state = this.initState();\n this.implementation = implementation;\n this.restore = restore ? restore : (): void => {\n this.implementation = implementation;\n };\n\n this.originalImplementation = implementation || ((): ReturnType => undefined as unknown as ReturnType);\n\n return <this> new Proxy(this, {\n apply: this.invokeFunction,\n construct: <ProxyHandler<object>['construct']> this.invokeClass\n });\n }\n\n /**\n * todo remove it\n * only for jest expect will support this mock\n */\n\n getMockName(): string {\n return this.name;\n }\n\n /**\n * Retrieves the current state of mocks.\n *\n * @return The current state of the mocks.\n * @see MocksStateInterface\n *\n * @since 1.0.0\n */\n\n get mock(): Readonly<MocksStateInterface<ReturnType, Args, Context>> {\n return this.state;\n }\n\n /**\n * Returns the original implementation of the function that was instrumented\n *\n * @returns The original function implementation that was wrapped or modified\n *\n * @remarks\n * This getter provides access to the unmodified function that was originally passed\n * to the instrumentation system. Useful for debugging, testing, or when you need\n * to bypass the instrumented behavior temporarily.\n *\n * @example\n * ```ts\n * const mockFn = jest.fn(x => x * 2);\n * // Later in test\n * const originalImplementation = mockFn.original;\n * expect(originalImplementation(5)).toBe(10);\n * ```\n *\n * @see FunctionLikeType\n *\n * @since 1.0.0\n */\n\n get original(): FunctionLikeType<ReturnType, Args, Context> {\n return this.originalImplementation;\n }\n\n /**\n * Clears the `mock.calls`, `mock.results`, `mock.contexts`, `mock.instances`, and `mock.invocationCallOrder` properties.\n *\n * @returns The current instance of the mock, allowing for method chaining.\n *\n * @remarks\n * This method resets the state of the mock function, clearing all invocation data and results,\n * ensuring that previous mock states do not affect the following tests.\n * Equivalent to calling `.mockClear()` on every mocked function.\n *\n * @see MockState.initState\n *\n * @since v1.0.0\n */\n\n mockClear(): this {\n this.state = this.initState();\n\n return this;\n }\n\n /**\n * Resets the mock function to its initial state.\n *\n * @returns The current instance of the mock, allowing for method chaining.\n *\n * @remarks\n * The `mockReset` method clears all invocation data and results by calling `mockClear()`, and also resets\n * the queued implementations,\n * removing any previously queued behavior set by methods like `mockImplementationOnce`.\n * This ensures that the mock is in a clean state and ready for new invocations or configurations.\n *\n * @see MockState.mockClear\n *\n * @since v1.0.0\n */\n\n mockReset(): this {\n this.mockClear();\n this.queuedImplementations = [];\n\n return this;\n }\n\n /**\n * Restores the mock function to its original implementation and resets its state.\n *\n * @returns The current instance of the mock, allowing for method chaining.\n *\n * @remarks\n * The `mockRestore` method does two things:\n * 1. It restores the mock to its initial implementation, which was set during the mocks creation or\n * via the `mockImplementation` method.\n * 2. It clears all tracking data, such as calls, results, contexts, instances, and invocation call order\n * by calling `mockReset()`, ensuring the mock is fully reset and ready for new invocations.\n *\n * This method is useful for ensuring that the mock is completely restored and cleared, making it behave as it did\n * when it was first created or last restored.\n *\n * @see MockState.restore\n * @see MockState.mockReset\n *\n * @since v1.0.0\n */\n\n mockRestore(): this {\n this.restore();\n this.mockReset();\n\n const index = MockState.mocks.indexOf(<MockState> <unknown> this);\n if (index !== -1) {\n MockState.mocks.splice(index, 1);\n }\n\n return this;\n }\n\n /**\n * Retrieves the mock implementation for a function, if available.\n *\n * @template ReturnType The type of the return value of the function.\n * @template Context The type of the `this` context for the function.\n * @template Args The type of the argument(s) of the function.\n *\n * @return A function matching `FunctionLikeType` that represents the mock implementation,\n * or `undefined` if no implementation is set.\n *\n * @remarks\n * This method returns the mock implementation associated with the instance.\n * If no mock implementation exists, it returns `undefined`.\n *\n * @since 1.0.0\n */\n\n getMockImplementation(): FunctionLikeType<ReturnType, Args, Context> | undefined {\n return this.implementation;\n }\n\n /**\n * Retrieves the next implementation from the queued implementations or defaults to the current implementation.\n *\n * @template ReturnType The return type of the function-like implementation.\n * @template Context The context in which the implementation executes.\n * @template Args The argument types expected by the implementation.\n *\n * @return The next implementation from the queue if available, or the current implementation.\n * Returns are `undefined` if no implementation is found.\n *\n * @remarks\n * This method first checks if there are any queued implementations available.\n * If a queued implementation exists, it will be removed from the queue and returned.\n * If the queue is empty, the primary current implementation is returned.\n * Returns are `undefined` if there is no implementation available.\n *\n * @since 1.0.0\n */\n\n getNextImplementation(): FunctionLikeType<ReturnType, Args, Context> | undefined {\n return this.queuedImplementations.length ? this.queuedImplementations.shift() : this.implementation;\n }\n\n /**\n * Replaces the default implementation of a mock function with the provided function.\n *\n * @template ReturnType - The type of the value returned by the implementation function.\n * @template Context - The context (`this`) expected by the implementation function.\n * @template Args - The types of the arguments expected by the implementation function.\n *\n * @param fn - The function to be used as the mock implementation. It defines\n * the behavior of the mock when called.\n *\n * @return Returns the instance of the current object for method chaining.\n *\n * @remarks\n * This method is useful when you need to mock the behavior of a function\n * dynamically during tests or in controlled scenarios.\n *\n * @since 1.0.0\n */\n\n mockImplementation(fn: FunctionLikeType<ReturnType, Args, Context>): this {\n this.implementation = fn;\n\n return this;\n }\n\n /**\n * Sets a mock implementation that will be used once for the next call to the mocked function.\n *\n * @template ReturnType The type of the value that the mock function will return.\n * @template Context The type of the `this` context for the mock function.\n * @template Args The type of arguments that the mock function will receive.\n *\n * @param fn - The function to be used as the mock implementation for the next call.\n * @returns The current instance, allowing for chaining of mock configurations.\n *\n * @remarks\n * The provided mock implementation will only be executed once. Further calls will fall back\n * to a different implementation, if provided, or the default behavior of the mock function.\n *\n * @example\n * ```ts\n * const mockFn = new MockState();\n *\n * // Set default implementation\n * mockFn.mockImplementation(() => 'default');\n *\n * // Set one-time behavior for the next call\n * mockFn.mockImplementationOnce(() => 'first call');\n *\n * console.log(mockFn()); // Output: 'first call' (from mockImplementationOnce)\n * console.log(mockFn()); // Output: 'default' (from mockImplementation)\n * ```\n *\n * @see FunctionLikeType\n *\n * @since 1.0.0\n */\n\n mockImplementationOnce(fn: FunctionLikeType<ReturnType, Args, Context>): this {\n this.queuedImplementations.push(fn);\n\n return this;\n }\n\n /**\n * Sets a mock implementation to always return a specified value when invoked.\n *\n * @template ReturnType The type of the value returned by the mock implementation.\n *\n * @param value - The value to always return when the mock function is called.\n * @return The current instance for chaining.\n *\n * @remarks\n * This method overrides any previous mock implementation configured for the function.\n *\n * @example\n * ```ts\n * const mockFn = new MockState();\n *\n * // Set mock to return 'Hello World' on each call\n * mockFn.mockReturnValue('Hello World');\n *\n * console.log(mockFn()); // Output: 'Hello World'\n * console.log(mockFn()); // Output: 'Hello World'\n * ```\n *\n * @since 1.0.0\n */\n\n mockReturnValue(value: ReturnType): this {\n this.mockImplementation(() => value);\n\n return this;\n }\n\n /**\n * Sets up a mock function to always resolve a promise with the specified value when called.\n *\n * @template ResolvedValueType - The type of the value to be resolved by the promise.\n * @template ReturnType - The return type of the function, which should include a Promise of the specified resolved value type.\n *\n * @param value - The value to be returned as the resolved value of the promise.\n * @returns The mock function instance, enabling method chaining.\n *\n * @remarks\n * This method is particularly useful for mocking asynchronous functions that return promises.\n * It ensures that the mock function resolves with the provided value every time it is called.\n *\n * @example\n * ```ts\n * const mockFn = new MockState<Promise<string>>();\n *\n * // Set mock to return a resolved promise with the value 'Success'\n * mockFn.mockResolvedValue('Success');\n *\n * mockFn().then((result: string) => {\n * console.log(result); // Output: 'Success'\n * });\n * ```\n *\n * @since 1.0.0\n */\n\n mockResolvedValue(value: ResolvedValueType<ReturnType>): this {\n this.mockImplementation(() => <ReturnType> Promise.resolve(value));\n\n return this;\n }\n\n /**\n * Sets a mock implementation for a single call that resolves to the specified value.\n *\n * @template ReturnType The type of the resolved value.\n * @template ResolvedValueType The type of the input value to be resolved.\n *\n * @param value - The value that the promise should resolve with when the mock is called once.\n * @return The current mock object instance, enabling method chaining.\n *\n * @remarks\n * This method is useful for defining custom behavior for a specific invocation of a mocked function,\n * returning a resolved promise with the provided value.\n *\n * @example\n * ```ts\n * const mockFn = new MockState(async () => {\n * return 'end';\n * });\n *\n * // Set mock to return a resolved promise with the value 'Success'\n * mockFn.mockResolvedValueOnce('Success');\n *\n * mockFn().then((result: string) => {\n * console.log(result); // Output: 'Success'\n * });\n *\n * mockFn().then((result: string) => {\n * console.log(result); // Output: 'end'\n * });\n * ```\n *\n * @since 1.0.0\n */\n\n mockResolvedValueOnce(value: ResolvedValueType<ReturnType>): this {\n this.mockImplementationOnce(() => <ReturnType> Promise.resolve(value));\n\n return this;\n }\n\n /**\n * Sets the return value of the mock function for a single call.\n *\n * @template ReturnType The type of the value to be returned.\n *\n * @param value - The value to be returned by the mock function for the next call.\n * @return The mock function instance, allowing for method chaining.\n *\n * @remarks\n * This method only affects the return value for the next call to the mock function.\n * All further calls will use the usual mock implementation or other specified behaviors.\n *\n * @example\n * ```ts\n * const mockFn = new MockState();\n *\n * // Set default return value\n * mockFn.mockReturnValue('Default Value');\n *\n * // Set one-time return value for the next call\n * mockFn.mockReturnValueOnce('First Call');\n * mockFn.mockReturnValueOnce('Second Call');\n *\n * console.log(mockFn()); // Output: 'First Call' (from mockReturnValueOnce)\n * console.log(mockFn()); // Output: 'Second Call' (from mockReturnValueOnce)\n * console.log(mockFn()); // Output: 'Default Value' (from mockReturnValue)\n * ```\n *\n * @since 1.0.0\n */\n\n mockReturnValueOnce(value: ReturnType): this {\n this.mockImplementationOnce(() => value);\n\n return this;\n }\n\n /**\n * Mocks the method to always return a rejected Promise with the specified value.\n *\n * @template ReturnType - The expected type of the return value for the mocked method.\n * @template RejectedValueType - The type of the value used to reject the Promise.\n *\n * @param value - The value with which the mocked Promise will be rejected.\n *\n * @return The current instance of the mock for chaining purposes.\n *\n * @remarks\n * This method is useful for testing scenarios where the function being mocked\n * is expected to reject with a specific value.\n *\n * @example\n * ```ts\n * const mockFn = new MockState<Promise<string>>();\n *\n * // Set mock to return a rejected promise with the value 'Error'\n * mockFn.mockRejectedValue('Error');\n *\n * mockFn().catch(error => {\n * console.log(error); // Output: 'Error'\n * });\n * ```\n *\n * @since 1.0.0\n */\n\n mockRejectedValue(value: RejectedValueType<ReturnType>): this {\n this.mockImplementation(() => <ReturnType> Promise.reject(value));\n\n return this;\n }\n\n /**\n * Adds a one-time rejection with the provided value to the mock function.\n *\n * @template ReturnType - The type of the value the mock function would return.\n *\n * @param value - The value to reject the promise with in the mock function.\n * @return The current instance of the mock function, allowing for method chaining.\n *\n * @remarks\n * This method configures a mock function to return a rejected promise with the\n * specified value the next time it is called. After the rejection occurs, the\n * mock function's behavior will revert to the next defined mock behavior, or\n * to the default behavior if no behaviors are defined.\n *\n * @example\n * ```ts\n * const mockFn = new MockState<Promise<string>>();\n *\n * // Set default rejected value\n * mockFn.mockRejectedValue('Default Error');\n *\n * // Set one-time rejected value for the next call\n * mockFn.mockRejectedValueOnce('First Call Error');\n *\n * mockFn().catch(error => {\n * console.log(error); // Output: 'First Call Error' (from mockRejectedValueOnce)\n * });\n *\n * mockFn().catch(error => {\n * console.log(error); // Output: 'Default Error' (from mockRejectedValue)\n * });\n * ```\n *\n * @since 1.0.0\n */\n\n mockRejectedValueOnce(value: RejectedValueType<ReturnType>): this {\n this.mockImplementationOnce(() => <ReturnType> Promise.reject(value));\n\n return this;\n }\n\n // todo: withImplementation\n\n /**\n * Custom inspection method for the `util.inspect` function.\n *\n * @returns A string representing the mock constructor with the specified `name` property.\n *\n * @remarks\n * This method is triggered when `util.inspect` is invoked on an instance of this class.\n * It provides a customized string representation of the class instance, enhancing debugging\n * and inspection output for developers.\n *\n * @example\n * ```ts\n * const mockFn = new MockState();\n * mockFn.name = 'MyMockFunction';\n *\n * // Inspect the mock function\n * console.log(mockFn); // Output: <Mock Constructor MyMockFunction>\n * ```\n *\n * @since 1.0.0\n */\n\n [Symbol.for('nodejs.util.inspect.custom')](): string {\n return `<Mock Constructor ${ this.name }>`;\n }\n\n /**\n * Initializes and returns the state object for mock function tracking.\n *\n * @return An object containing the initialized mock function state.\n *\n * @remarks\n * The state object contains the structure necessary to keep track of\n * calls, results, contexts, instances, and invocation orders of the function.\n *\n * @see MocksStateInterface\n *\n * @since v1.0.0\n */\n\n private initState(): MocksStateInterface<ReturnType, Args, Context> {\n return {\n calls: [],\n results: [],\n lastCall: undefined,\n contexts: [],\n instances: [],\n invocationCallOrder: []\n };\n }\n\n /**\n * Invokes the next implementation of a mock function with the provided context and arguments.\n *\n * @template Context The type of `this` context in which the function is invoked.\n * @template Args The type of the arguments passed to the function.\n * @template ReturnType The type of the return value, of the function being invoked.\n *\n * @param thisArg - The context (`this`) in which the function is executed.\n * @param args - The arguments to be passed to the function.\n *\n * @returns The result of the function invocation, which is either the return value, the thrown error, or undefined.\n *\n * @remarks\n * This method simulates the function call for a mocked implementation. It tracks all invocations,\n * including the call order, the provided arguments, and the context. It handles binding, default\n * arguments, and maintains a record of results (either successful returns or thrown errors).\n *\n * @since 1.0.0\n */\n\n private invoke(thisArg: Context, args: Args): ReturnType | undefined {\n let thisContext = thisArg;\n const impl = <FunctionLikeType<ReturnType, Args, Context> & BoundInterface> this.getNextImplementation();\n\n const argsArray = <Array<unknown>> args;\n if (typeof impl === 'function') {\n if (impl.__boundArgs) argsArray.unshift(...impl.__boundArgs);\n if (impl.__boundThis) thisContext = <Context> impl.__boundThis;\n }\n\n this.state.calls.push(<Args> argsArray);\n this.state.contexts.push(<Context> thisContext);\n this.state.invocationCallOrder.push(this.state.invocationCallOrder.length + 1);\n\n let result: MockInvocationResultInterface<ReturnType>;\n const index = this.state.results.push({ value: undefined, type: 'incomplete' }) - 1;\n\n if (impl) {\n try {\n const value = impl.call(<Context> undefined, ...args);\n result = { type: 'return', value };\n } catch (error) {\n result = { value: error, type: 'throw' };\n }\n } else {\n result = { type: 'return', value: undefined };\n }\n\n this.state.lastCall = args;\n this.state.results[index] = result;\n\n return <ReturnType> result.value;\n }\n\n /**\n * Invokes a function within a specific context and with provided arguments.\n *\n * @template Context The type of the context in which the function is invoked.\n * @template Args The type of the arguments passed to the function.\n * @template ReturnType The type of the value that the invoked function returns.\n *\n * @param target - The instance of the class containing the method to be invoked.\n * @param thisArg - The context object that will be bound to the invoked function.\n * @param argumentsList - The list of arguments to pass to the invoked function.\n * @returns The result of the invoked function or `undefined` if no value is returned.\n *\n * @remarks\n * This method modifies the state of the `target` instance by adding the `thisArg`\n * to the `target.state.instances` array before invoking the function.\n *\n * @since 1.0.0\n */\n\n private invokeFunction(target: this, thisArg: Context, argumentsList: Args): ReturnType | undefined {\n target.state.instances.push(thisArg);\n\n return target.invoke.call(target, thisArg, argumentsList);\n }\n\n /**\n * Invokes a class method on the provided target with specified arguments and a new target.\n *\n * @template Args - The type of arguments to be passed to the invoked method.\n *\n * @param target - The object on which the class method is invoked.\n * @param argArray - The array of arguments to pass to the invoked method.\n * @param newTarget - The new object used as the invocation context.\n * @returns The result of the invocation, typically an object. If the result is not an object,\n * the `newTarget` is returned instead.\n *\n * @remarks\n * This method ensures that the result is stored in the `instances` array of the target's state\n * if it is detected as a proper class instance. Otherwise, the `newTarget` is registered.\n *\n * @since 1.0.0\n */\n\n private invokeClass(target: this, argArray: Args, newTarget: object): object {\n const result = target.invoke.call(target, <Context> newTarget, argArray);\n const isClassInstance = typeof result === 'object' && result !== null && result.constructor;\n target.state.instances.push(isClassInstance ? <Context> result : <Context> newTarget);\n\n return typeof result === 'object' ? <object> result : newTarget;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConstructorType } from '@remotex-labs/xjet-expect';\nimport type { InjectableOptionsInterface, TokenElementType } from '@symlinks/interfaces/symlinks.interface';\n\n/**\n * Stores singleton instances of injectable classes.\n *\n * @since 1.0.0\n */\n\nconst SINGLETONS = new Map<ConstructorType, unknown>();\n\n/**\n * Stores metadata for classes marked as injectable via `@Injectable`.\n *\n * @internal\n * @since 1.0.0\n */\n\nconst INJECTABLES = new Map<ConstructorType, InjectableOptionsInterface>();\n\n/**\n * Marks a class as injectable and stores its configuration metadata.\n *\n * @template T - The type of the class instance\n * @template Args - The types of arguments accepted by the constructor, defaults to `unknown[]`\n *\n * @param options - Optional configuration for the injectable, including scope and factory\n *\n * @example\n * ```ts\n * @Injectable({ scope: 'singleton' })\n * class MyService {}\n * ```\n *\n * @see InjectableOptionsInterface\n * @since 1.0.0\n */\n\nexport function Injectable<T = unknown, Args extends Array<unknown> = unknown[]>(options?: InjectableOptionsInterface) {\n return function (target: new (...args: Args) => T): void {\n INJECTABLES.set(target, options || {});\n };\n}\n\n/**\n * Resolves and returns an instance of the given injectable token.\n *\n * @template T - The type of the instance to return\n * @template Args - The types of arguments passed to the constructor or factory\n *\n * @param token - The injectable class or token to resolve\n * @param args - Arguments to pass to the constructor or factory\n *\n * @returns The resolved instance of type `T`\n *\n * @throws Error - If the token is not registered as injectable via `@Injectable`\n *\n * @remarks\n * If the injectable is marked with scope `'singleton'`, the same instance will be returned\n * on the following calls. Otherwise, a new instance is created for each call.\n *\n * @example\n * ```ts\n * const service = inject(MyService);\n * ```\n *\n * @see TokenElementType\n * @since 1.0.0\n */\n\nexport function inject<T, Args extends Array<unknown>>(token: TokenElementType<T, Args>, ...args: Args): T {\n if (SINGLETONS.has(token)) return <T>SINGLETONS.get(token);\n\n const metadata = INJECTABLES.get(token);\n if (!metadata) throw new Error(`Cannot inject ${ token.name } \u2013 not marked @Injectable`);\n\n const instance: T = metadata.factory\n ? <T>metadata.factory(...args)\n : new token(...args);\n\n if (metadata?.scope === 'singleton') {\n SINGLETONS.set(token, instance);\n }\n\n return instance;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ReadMethodType, WriteMethodType } from '@components/interfaces/buffer-component.interface';\n\n/**\n * Retrieves a bound buffer method for reading from or writing to a Buffer\n *\n * @template T - The type of the returned buffer method\n *\n * @param buffer - The Buffer instance to get the method from\n * @param operation - The operation type ('read' or 'write')\n * @param type - The data type to read or write (e.g., 'UInt8', 'Int16LE')\n * @returns The bound buffer method of the specified type\n *\n * @throws Error - When the type parameter is empty or invalid\n * @throws Error - When the method does not exist on the Buffer object\n *\n * @remarks\n * This is a utility function that dynamically retrieves and binds Buffer methods.\n * It constructs method names by combining the operation and type parameters.\n * The returned method is bound to the buffer instance for immediate use.\n *\n * @example\n * ```ts\n * const buffer = Buffer.from([0x01, 0x02, 0x03, 0x04]);\n * const readUInt16LE = getBufferMethod<(offset: number) => number>(buffer, 'read', 'UInt16LE');\n * const value = readUInt16LE(0); // Returns 513 (0x0201)\n * ```\n *\n * @since 2.0.0\n */\n\nexport function getBufferMethod<T>(buffer: Buffer, operation: 'read' | 'write', type: string): T {\n const methodName = `${operation}${type}` as keyof Buffer;\n const method = <WriteMethodType<number>> buffer[methodName];\n\n if (!type)\n throw new Error(`Invalid type(${ type }) parameter`);\n\n if (!(methodName in buffer))\n throw new Error(`Method \"${ methodName.toString() }\" does not exist on Buffer`);\n\n return method.bind(buffer) as T;\n}\n\n/**\n * Gets a bound read method from a Buffer for the specified data type\n *\n * @template T - The type of value that will be read, defaults to number (number | bigint)\n *\n * @param buffer - The Buffer instance to read from\n * @param type - The data type to read (e.g., 'UInt8', 'Int16LE')\n * @returns A bound read method of the specified type\n *\n * @throws Error - When the type parameter is empty or invalid\n * @throws Error - When the method does not exist on the Buffer object\n *\n * @remarks\n * This function is a specialized wrapper around getBufferMethod that\n * specifically retrieves read methods from the Buffer instance.\n * It simplifies the API by fixing the operation parameter to 'read'.\n *\n * @example\n * ```ts\n * const buffer = Buffer.from([0x01, 0x02, 0x03, 0x04]);\n * const readUInt16LE = readMethod(buffer, 'UInt16LE');\n * const value = readUInt16LE(0); // Returns 513 (0x0201)\n * ```\n *\n * @see getBufferMethod - The underlying implementation\n * @since 2.0.0\n */\n\nexport function readMethod<T extends number | bigint = number>(buffer: Buffer, type: string): ReadMethodType<T> {\n return getBufferMethod<ReadMethodType<T>>(buffer, 'read', type);\n}\n\n/**\n * Gets a bound write method from a Buffer for the specified data type\n *\n * @template T - The type of value that will be written, defaults to number\n *\n * @param buffer - The Buffer instance to write to\n * @param type - The data type to write (e.g., 'UInt8', 'Int16LE')\n * @returns A bound write method of the specified type\n *\n * @throws Error - When the type parameter is empty or invalid\n * @throws Error - When the method does not exist on the Buffer object\n *\n * @remarks\n * This function is a specialized wrapper around getBufferMethod that\n * specifically retrieves write methods from the Buffer instance.\n * It simplifies the API by fixing the operation parameter to 'write'.\n *\n * @example\n * ```ts\n * const buffer = Buffer.alloc(4);\n * const writeUInt16LE = writeMethod(buffer, 'UInt16LE');\n * writeUInt16LE(513, 0); // Writes [0x01, 0x02, 0x00, 0x00] to buffer\n * ```\n *\n * @see getBufferMethod - The underlying implementation\n * @since 2.0.0\n */\n\nexport function writeMethod<T extends number | bigint = number>(buffer: Buffer, type: string): WriteMethodType<T> {\n return getBufferMethod<WriteMethodType<T>>(buffer, 'write', type);\n}\n\n/**\n * Splits a buffer into two parts with an optional gap between them\n *\n * @param buffer - The Buffer instance to split\n * @param splitPosition - The position at which to split the buffer\n * @param skipBytes - The number of bytes to skip after the split position\n * @returns A tuple containing two Buffer instances: the portion before the split and the portion after the gap\n *\n * @throws Error - When the split position is negative\n * @throws Error - When the split position exceeds the buffer length\n *\n * @remarks\n * This function divides a buffer at the specified position and allows skipping a number of bytes\n * after the split position before creating the second buffer.\n * If the skip extends beyond the buffer's length, the second buffer will be empty.\n *\n * @example\n * ```ts\n * const buffer = Buffer.from([1, 2, 3, 4, 5, 6]);\n * const [first, second] = splitBufferWithGap(buffer, 2, 1);\n * // first: Buffer [1, 2]\n * // second: Buffer [4, 5, 6]\n * ```\n *\n * @since 2.0.0\n */\n\nexport function splitBufferWithGap(buffer: Buffer, splitPosition: number, skipBytes: number = 0): [ Buffer, Buffer ] {\n if (splitPosition < 0)\n throw new Error('Split position cannot be negative');\n\n if (splitPosition > buffer.length)\n throw new Error('Split position cannot exceed buffer length');\n\n const beforeSplit = buffer.subarray(0, splitPosition);\n const afterPosition = splitPosition + skipBytes;\n\n if (afterPosition >= buffer.length)\n return [ beforeSplit, Buffer.alloc(0) ];\n\n return [ beforeSplit, buffer.subarray(afterPosition) ];\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n StructType,\n StructDataType,\n StructContextInterface\n} from '@components/interfaces/struct-component.interface';\n\n/**\n * Imports\n */\n\nimport { splitBufferWithGap } from '@components/buffer.component';\n\n/**\n * Reads a single structure from a binary buffer at a specified position\n *\n * @param arrayOffset - Optional offset to apply when reading structures within an array (defaults to 0)\n * @returns The deserialized structure object with its properties populated from binary data\n *\n * @throws Error - If the binary data is malformed or cannot be deserialized into the expected structure\n *\n * @remarks\n * This function calculates the absolute position in the buffer by combining the base offset,\n * the structure's defined position, and any additional array offset. It then uses the structure's\n * type definition to deserialize the binary data at that position into a JavaScript object.\n * The callback provided to toObject updates the context's offset to account for any dynamic-sized data.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: myBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct\n * }\n * };\n *\n * const person = readSingleStruct.call(context);\n * ```\n *\n * @see writeStruct\n * @see readStructArray\n *\n * @since 2.0.0\n */\n\nexport function readSingleStruct(this: StructContextInterface, arrayOffset: number = 0): StructType {\n const { position, type } = this.descriptor;\n const absolutePosition = this.offset + position + arrayOffset;\n\n return <StructType> type.toObject(this.buffer.subarray(absolutePosition), (offset) => {\n this.offset += offset;\n });\n}\n\n/**\n * Reads an array of structures from a binary buffer\n *\n * @returns An array of deserialized structure objects\n *\n * @throws Error - If the binary data is malformed or cannot be deserialized into the expected structures\n *\n * @remarks\n * This function extracts multiple structure instances from a binary buffer based on the descriptor's\n * arraySize property. It pre-allocates the result array for performance and calls readSingleStruct\n * for each structure in the array, calculating the appropriate offset based on the structure size.\n * The arraySize in the descriptor determines how many structures will be read from the buffer.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: myBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct,\n * arraySize: 5,\n * size: 32\n * }\n * };\n *\n * const people = readStructArray.call(context);\n * // Returns an array of 5 person objects\n * ```\n *\n * @see readSingleStruct\n * @see writeStructArray\n *\n * @since 2.0.0\n */\n\nexport function readStructArray(this: StructContextInterface): Array<StructType> {\n const result: Array<StructType> = [];\n const { arraySize = 0, size } = this.descriptor;\n\n result.length = arraySize;\n for (let i = 0; i < arraySize; i++) {\n result[i] = readSingleStruct.call(this, i * size);\n }\n\n return result;\n}\n\n/**\n * Reads a structure or array of structures from a binary buffer based on the descriptor\n *\n * @returns A single structure object or an array of structure objects depending on the descriptor configuration\n *\n * @throws Error - If the binary data is malformed or cannot be deserialized into the expected structure(s)\n *\n * @remarks\n * This function serves as a dispatcher that determines whether to read a single structure or\n * an array of structures based on the descriptor's configuration. It checks if the descriptor\n * contains an arraySize property with a truthy value, and if so, delegates to readStructArray.\n * Otherwise, it calls readSingleStruct to deserialize a single structure instance.\n *\n * @example\n * ```ts\n * // For a single structure descriptor\n * const singleContext = {\n * buffer: myBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct\n * }\n * };\n * const person = readStruct.call(singleContext);\n *\n * // For an array structure descriptor\n * const arrayContext = {\n * buffer: myBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct,\n * arraySize: 5,\n * size: 32\n * }\n * };\n * const people = readStruct.call(arrayContext);\n * ```\n *\n * @see writeStruct\n * @see readStructArray\n * @see readSingleStruct\n *\n * @since 2.0.0\n */\n\nexport function readStruct(this: StructContextInterface): StructDataType {\n if(('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return readStructArray.call(this);\n\n return readSingleStruct.call(this);\n}\n\n/**\n * Writes a single structure to a binary buffer at a specified position\n *\n * @param value - The structure object to serialize into binary format\n * @param arrayOffset - Optional offset to apply when writing structures within an array (defaults to 0)\n *\n * @throws Error - If the structure cannot be properly serialized or buffer operations fail\n *\n * @remarks\n * This function serializes a structure object into binary data and writes it to the buffer at\n * the calculated absolute position. It handles null/undefined values by defaulting to an empty object.\n * The function splits the existing buffer at the insertion point with appropriate sizing,\n * then reconstructs the buffer by concatenating the start segment, the serialized structure,\n * and the end segment. If the serialized structure is larger than the expected size, it also\n * adjusts the current offset to account for the dynamic sizing.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: existingBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct,\n * size: 32\n * }\n * };\n *\n * const person = { name: \"John\", age: 30 };\n * writeSingleStruct.call(context, person);\n * ```\n *\n * @see readSingleStruct\n * @see writeStructArray\n *\n * @since 2.0.0\n */\n\nexport function writeSingleStruct(this: StructContextInterface, value: StructType, arrayOffset: number = 0): void {\n value ??= {};\n const { position, type, size } = this.descriptor;\n const StructBuffer = type.toBuffer(value);\n const absolutePosition = this.offset + position + arrayOffset;\n const [ start, end ] = splitBufferWithGap(this.buffer, absolutePosition, size);\n\n this.buffer = Buffer.concat([ start, StructBuffer, end ]);\n if (StructBuffer.length > size) {\n this.offset += (StructBuffer.length - size);\n }\n}\n\n/**\n * Writes an array of structures to a binary buffer\n *\n * @param values - The array of structure objects to serialize into binary format\n * @returns Nothing\n *\n * @throws Error - If the structures cannot be properly serialized or buffer operations fail\n *\n * @remarks\n * This function writes multiple structure instances to the binary buffer based on the descriptor's\n * arraySize property. It iterates through each position in the array and calls writeSingleStruct\n * for each structure, calculating the appropriate offset based on the structure size.\n * If there are fewer values provided than the arraySize specification, empty objects will be\n * written for the remaining positions to ensure the full array space is properly initialized.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: existingBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct,\n * arraySize: 5,\n * size: 32\n * }\n * };\n *\n * const people = [\n * { name: \"John\", age: 30 },\n * { name: \"Jane\", age: 28 },\n * { name: \"Bob\", age: 45 }\n * ];\n *\n * writeStructArray.call(context, people);\n * // Writes the 3 provided people and 2 empty objects to fill the array\n * ```\n *\n * @see readStructArray\n * @see writeSingleStruct\n *\n * @since 2.0.0\n */\n\nexport function writeStructArray(this: StructContextInterface, values: Array<StructType>): void {\n const { arraySize = 0, size } = this.descriptor;\n\n for (let i = 0; i < arraySize; i++) {\n const elementValue = i < values.length ? values[i] : {};\n writeSingleStruct.call(this, elementValue, i * size);\n }\n}\n\n/**\n * Writes a structure or array of structures to a binary buffer based on the descriptor\n *\n * @param value - The structure object or array of structure objects to serialize\n *\n * @throws Error - If the structure(s) cannot be properly serialized or buffer operations fail\n *\n * @remarks\n * This function serves as a dispatcher that determines whether to write a single structure or\n * an array of structures based on the descriptor's configuration. It checks if the descriptor\n * contains an arraySize property with a truthy value, and if so, delegates to writeStructArray.\n * Otherwise, it calls writeSingleStruct to serialize a single structure instance.\n *\n * The function handles type mismatches between the provided value and the descriptor configuration:\n * - When descriptor indicates an array but a single object is provided, it wraps the object in an array\n * - When descriptor indicates a single object but an array is provided, it uses the first element of the array\n *\n * @example\n * ```ts\n * // For a single structure descriptor\n * const singleContext = {\n * buffer: existingBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct\n * }\n * };\n * const person = { name: \"John\", age: 30 };\n * writeStruct.call(singleContext, person);\n *\n * // For an array structure descriptor\n * const arrayContext = {\n * buffer: existingBuffer,\n * offset: 0,\n * descriptor: {\n * position: 10,\n * type: PersonStruct,\n * arraySize: 3,\n * size: 32\n * }\n * };\n * const people = [\n * { name: \"John\", age: 30 },\n * { name: \"Jane\", age: 28 }\n * ];\n * writeStruct.call(arrayContext, people);\n * ```\n *\n * @see readStruct\n * @see writeStructArray\n * @see writeSingleStruct\n *\n * @since 2.0.0\n */\n\nexport function writeStruct(this: StructContextInterface, value: StructDataType): void {\n if (('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return writeStructArray.call(this, Array.isArray(value) ? value : [ value ]);\n\n return writeSingleStruct.call(this, Array.isArray(value) ? (value[0] || {}) : value);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n PrimitiveType,\n PrimitiveDataType,\n FloatPrimitiveType,\n PrimitiveContextInterface,\n PositionedPrimitiveDescriptorType\n} from '@components/interfaces/primitive-component.interface';\n\n/**\n * Imports\n */\n\nimport { readMethod, writeMethod } from '@components/buffer.component';\n\n/**\n * Maps primitive data types to their size in bits\n *\n * @returns A record mapping each primitive type to its size in bits\n *\n * @remarks\n * This constant provides a mapping between all supported primitive types and their\n * corresponding bit sizes. The sizes are expressed in bits, not bytes.\n * - 8-bit types: Int8, UInt8\n * - 16-bit types: Int16LE, Int16BE, UInt16LE, UInt16BE\n * - 32-bit types: Int32LE, Int32BE, UInt32LE, UInt32BE, FloatLE, FloatBE\n * - 64-bit types: BigInt64LE, BigInt64BE, BigUInt64LE, BigUInt64BE, DoubleLE, DoubleBE\n *\n * The 'LE' and 'BE' suffixes indicate Little Endian and Big Endian byte order respectively.\n *\n * @example\n * ```ts\n * // Get the size of a UInt32LE\n * const bitSize = PRIMITIVE_TYPE_SIZES['UInt32LE']; // 32\n *\n * // Calculate byte size\n * const byteSize = PRIMITIVE_TYPE_SIZES['BigInt64BE'] / 8; // 8 bytes\n * ```\n *\n * @since 2.0.0\n */\n\nexport const PRIMITIVE_TYPE_SIZES: Record<PrimitiveType | FloatPrimitiveType, number> = {\n 'Int8': 8,\n 'UInt8': 8,\n 'Int16LE': 16,\n 'Int16BE': 16,\n 'UInt16LE': 16,\n 'UInt16BE': 16,\n 'FloatLE': 32,\n 'FloatBE': 32,\n 'Int32LE': 32,\n 'Int32BE': 32,\n 'UInt32LE': 32,\n 'UInt32BE': 32,\n 'DoubleLE': 64,\n 'DoubleBE': 64,\n 'BigInt64LE': 64,\n 'BigInt64BE': 64,\n 'BigUInt64LE': 64,\n 'BigUInt64BE': 64\n};\n\n/**\n * Parses a string representation of a primitive type descriptor into a structured positioned object\n *\n * @param field - String representation of the primitive descriptor in format \"type\" or \"type[size]\"\n * @param position - The starting byte position of this element within the buffer\n * @returns A structured PositionedPrimitiveDescriptorType object\n *\n * @throws Error - When the descriptor format is invalid\n * @throws Error - When the primitive type is not supported\n *\n * @remarks\n * This function converts a string-based primitive type specification into a structured descriptor object with positioning information.\n * The input string can be in one of two formats:\n * - A simple type name (e.g., \"UInt8\", \"Int16LE\")\n * - An array type with size (e.g., \"UInt8[10]\", \"Float32[4]\")\n *\n * The function validates that:\n * 1. The input string matches the expected pattern for a valid primitive descriptor\n * 2. The specified type is supported by checking against the PRIMITIVE_TYPE_SIZES registry\n *\n * If the descriptor includes an array size specification, it is parsed as an integer.\n * For non-array types, the arraySize field will be undefined.\n *\n * @example\n * ```ts\n * // Parse a simple primitive type at offset 0\n * const descriptor1 = parsePrimitiveDescriptor('UInt8');\n * // Returns: { type: 'UInt8', size: 1, offset: 0, arraySize: undefined }\n *\n * // Parse an array primitive type at offset 4\n * const descriptor2 = parsePrimitiveDescriptor('Int16LE[5]', 4);\n * // Returns: { type: 'Int16LE', size: 2, offset: 4, arraySize: 5 }\n *\n * // The following would throw errors:\n * // Invalid format: parsePrimitiveDescriptor('UInt8[]');\n * // Invalid format: parsePrimitiveDescriptor('8UInt');\n * // Invalid type: parsePrimitiveDescriptor('Unknown[5]');\n * ```\n *\n * @see PRIMITIVE_TYPE_SIZES\n * @see PositionedPrimitiveDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function parsePrimitiveDescriptor(field: string, position: number = 0): PositionedPrimitiveDescriptorType {\n const pattern = /^([A-Za-z][A-Za-z0-9]*)(?:\\[(\\d+)\\])?$/i;\n const match = <[string, PrimitiveType, string]> field.match(pattern);\n\n if (!match)\n throw new Error(`Invalid primitive descriptor: ${ field }`);\n\n const size = PRIMITIVE_TYPE_SIZES[match[1]];\n if (!size)\n throw new Error(`Invalid primitive type: ${ match[1] }`);\n\n const type = match[1];\n const arraySize = match[2] ? parseInt(match[2]) : undefined;\n\n return { type, position, size: size / 8, arraySize, kind: 'primitive' };\n}\n\n/**\n * Reads a single primitive value from the buffer at the specified position\n *\n * @param arrayOffset - Optional offset within an array structure, defaults to 0\n *\n * @returns The primitive value (number or bigint) read from the buffer\n *\n * @remarks\n * Uses the descriptor's position and type information to determine where and how to read from the buffer.\n * The absolute position is calculated by adding the context offset, descriptor position, and any array offset.\n *\n * The function supports all primitive types defined in the PrimitiveType interface, including both\n * signed and unsigned integers of various sizes with their respective endianness formats.\n *\n * @example\n * ```ts\n * const context: PrimitiveContextInterface = {\n * buffer: Buffer.alloc(16),\n * offset: 4,\n * descriptor: {\n * position: 2,\n * type: 'UInt32LE'\n * }\n * };\n *\n * const value = readSinglePrimitive.call(context);\n * ```\n *\n * @see readMethod\n * @see PrimitiveContextInterface\n *\n * @since 2.0.0\n */\n\nexport function readSinglePrimitive(this: PrimitiveContextInterface, arrayOffset: number = 0): number | bigint {\n const { position, type } = this.descriptor;\n const absolutePosition = this.offset + position + arrayOffset;\n\n return readMethod<number | bigint>(this.buffer, type)(absolutePosition);\n}\n\n/**\n * Reads an array of primitive values from the buffer based on descriptor information\n *\n * @returns An array of primitive values (numbers or bigint's) read from the buffer\n *\n * @throws Error - If the arraySize is not defined in the descriptor\n *\n * @remarks\n * Uses the descriptor's arraySize and size properties to determine how many values to read\n * and the stride between array elements. The array is pre-allocated to avoid resizing\n * during population.\n *\n * This function is used internally when processing primitive array types as defined in the\n * PrimitiveArrayType.\n *\n * @example\n * ```ts\n * const context: PrimitiveContextInterface = {\n * buffer: Buffer.alloc(32),\n * offset: 0,\n * descriptor: {\n * position: 0,\n * type: 'UInt16BE',\n * arraySize: 8,\n * size: 2\n * }\n * };\n *\n * const values = readPrimitiveArray.call(context);\n * ```\n *\n * @see readSinglePrimitive\n *\n * @since 2.0.0\n */\n\nexport function readPrimitiveArray(this: PrimitiveContextInterface): Array<bigint | number> {\n const result: Array<number | bigint> = [];\n const { arraySize = 0, size } = this.descriptor;\n\n // Preallocate the array to avoid resizing\n result.length = arraySize;\n for (let i = 0; i < arraySize; i++) {\n result[i] = readSinglePrimitive.call(this, i * size);\n }\n\n return result;\n}\n\n/**\n * Reads primitive data from the buffer based on the context's descriptor\n *\n * @returns A primitive value or array of primitive values (number|bigint or Array\\<number | bigint\\>)\n *\n * @remarks\n * This function acts as a smart dispatcher that determines whether to read a single primitive value\n * or an array of primitive values based on the descriptor's configuration.\n *\n * If the descriptor contains an 'arraySize' property with a truthy value, the function will call\n * readPrimitiveArray to read multiple values. Otherwise, it calls readSinglePrimitive to read\n * a single value.\n *\n * This is the main entry point for reading primitive data from a buffer and should be used\n * in preference to calling readSinglePrimitive or readPrimitiveArray directly.\n *\n * @example\n * ```ts\n * // Reading a single value\n * const singleContext: PrimitiveContextInterface = {\n * buffer: buffer,\n * offset: 0,\n * descriptor: { position: 4, type: 'UInt8' }\n * };\n * const singleValue = readPrimitive.call(singleContext);\n *\n * // Reading an array\n * const arrayContext: PrimitiveContextInterface = {\n * buffer: buffer,\n * offset: 0,\n * descriptor: { position: 0, type: 'Int32LE', arraySize: 5, size: 4 }\n * };\n * const arrayValues = readPrimitive.call(arrayContext);\n * ```\n *\n * @see readPrimitiveArray\n * @see readSinglePrimitive\n *\n * @since 2.0.0\n */\n\nexport function readPrimitive(this: PrimitiveContextInterface): PrimitiveDataType {\n if(('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return readPrimitiveArray.call(this);\n\n return readSinglePrimitive.call(this);\n}\n\n/**\n * Writes a single primitive value to the buffer at the specified position\n *\n * @param value - The primitive value (number or bigint) to write to the buffer\n * @param arrayOffset - Optional offset within an array structure, defaults to 0\n *\n * @throws TypeError - If the provided value type doesn't match the expected type for the field\n * (e.g., providing a number for a BigInt field or a BigInt for a number field)\n *\n * @remarks\n * Uses the descriptor's position and type information to determine where and how to write to the buffer.\n * The absolute position is calculated by adding the context offset, descriptor position, and any array offset.\n *\n * The function automatically validates that the value type matches the expected type based on the field descriptor:\n * - BigInt types (fields whose names include 'Big') require bigint values\n * - Non-BigInt types require number values\n *\n * @example\n * ```ts\n * const context: PrimitiveContextInterface = {\n * buffer: Buffer.alloc(16),\n * offset: 4,\n * descriptor: {\n * position: 2,\n * type: 'UInt32LE'\n * }\n * };\n *\n * // Write a 32-bit unsigned integer\n * writeSinglePrimitive.call(context, 42);\n *\n * // For BigInt types\n * const bigIntContext: PrimitiveContextInterface = {\n * buffer: Buffer.alloc(16),\n * offset: 0,\n * descriptor: {\n * position: 0,\n * type: 'BigInt64LE'\n * }\n * };\n *\n * // Write a 64-bit signed integer\n * writeSinglePrimitive.call(bigIntContext, BigInt(9007199254740991));\n * ```\n *\n * @since 2.0.0\n */\n\nexport function writeSinglePrimitive(this: PrimitiveContextInterface, value: number | bigint, arrayOffset: number = 0): void {\n value ??= 0;\n const { position, type } = this.descriptor;\n const isBigIntType = type.includes('Big');\n\n if(isBigIntType && value === 0)\n value = BigInt(0);\n\n if (isBigIntType && typeof value !== 'bigint')\n throw new TypeError(`Expected a BigInt for field \"${ type }\", but received ${ value }`);\n\n if (!isBigIntType && typeof value !== 'number')\n throw new TypeError(`Expected a number for field \"${ type }\", but received ${ value }`);\n\n\n const absolutePosition = this.offset + position + arrayOffset;\n writeMethod<number | bigint>(this.buffer, type)(value, absolutePosition);\n}\n\n/**\n * Writes an array of primitive values to the buffer based on descriptor information\n *\n * @param values - Array of primitive values (numbers or bigint's) to write to the buffer\n *\n * @remarks\n * Uses the descriptor's arraySize and size properties to determine how many values to write\n * and the stride between array elements. If the provided values array is shorter than the\n * arraySize specified in the descriptor, the remaining elements will be filled with zeros.\n *\n * Each element is written using the writeSinglePrimitive function, which enforces type checking\n * based on the field descriptor.\n *\n * @example\n * ```ts\n * const context: PrimitiveContextInterface = {\n * buffer: Buffer.alloc(32),\n * offset: 0,\n * descriptor: {\n * position: 0,\n * type: 'UInt16BE',\n * arraySize: 8,\n * size: 2\n * }\n * };\n *\n * // Write an array of 16-bit unsigned integers\n * writePrimitiveArray.call(context, [1, 2, 3, 4, 5, 6, 7, 8]);\n *\n * // If fewer values are provided, remaining slots are filled with zeros\n * writePrimitiveArray.call(context, [100, 200, 300]); // Writes [100, 200, 300, 0, 0, 0, 0, 0]\n * ```\n *\n * @see writeSinglePrimitive\n *\n * @since 2.0.0\n */\n\nexport function writePrimitiveArray(this: PrimitiveContextInterface, values: Array<number | bigint>): void {\n const { arraySize = 0, size } = this.descriptor;\n\n for (let i = 0; i < arraySize; i++) {\n const elementValue = i < values.length ? values[i] : 0;\n writeSinglePrimitive.call(this, elementValue, i * size);\n }\n}\n\n/**\n * Writes primitive data to the buffer based on the context's descriptor\n *\n * @param value - A primitive value or array of primitive values (number|bigint or (number|bigint)[])\n *\n * @remarks\n * This function acts as a smart dispatcher that determines whether to write a single primitive value\n * or an array of primitive values based on the descriptor's configuration.\n *\n * If the descriptor contains an 'arraySize' property with a truthy value, the function will call\n * writePrimitiveArray to write multiple values. Otherwise, it calls writeSinglePrimitive to write\n * a single value.\n *\n * The function handles type conversion intelligently:\n * - When writing to an array field, a single value will be converted to a single-element array\n * - When writing to a single field, an array input will use only the first element (or 0 if empty)\n *\n * This is the main entry point for writing primitive data to a buffer and should be used\n * in preference to calling writeSinglePrimitive or writePrimitiveArray directly.\n *\n * @example\n * ```ts\n * // Writing a single value\n * const singleContext: PrimitiveContextInterface = {\n * buffer: buffer,\n * offset: 0,\n * descriptor: { position: 4, type: 'UInt8' }\n * };\n * writePrimitive.call(singleContext, 42);\n *\n * // Writing an array\n * const arrayContext: PrimitiveContextInterface = {\n * buffer: buffer,\n * offset: 0,\n * descriptor: { position: 0, type: 'Int32LE', arraySize: 5, size: 4 }\n * };\n * writePrimitive.call(arrayContext, [10, 20, 30, 40, 50]);\n * ```\n *\n * @see writePrimitiveArray\n * @see writeSinglePrimitive\n *\n * @since 2.0.0\n */\n\nexport function writePrimitive(this: PrimitiveContextInterface, value: PrimitiveDataType): void {\n if(('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return writePrimitiveArray.call(this, Array.isArray(value) ? value : [ value ]);\n\n writeSinglePrimitive.call(this, Array.isArray(value) ? (value[0] || 0) : value);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n BitfieldContextInterface,\n BitfieldDescriptorInterface,\n PositionedBitfieldDescriptorType\n} from '@components/interfaces/bitfield-component.interface';\nimport type { PrimitiveType } from '@components/interfaces/primitive-component.interface';\n\n/**\n * Imports\n */\n\nimport { PRIMITIVE_TYPE_SIZES } from '@components/primitive.component';\n\n/**\n * Cache for bit masks to improve the performance of bitfield operations\n *\n * @remarks\n * This map caches bit masks for different bit sizes to avoid recalculating\n * them repeatedly. The keys represent bit sizes, and the values are pre-calculated\n * masks for those sizes (e.g., 3 bits \u2192 0b111, 4 bits \u2192 0b1111).\n *\n * Using this cache improves performance in applications with heavy bitfield operations,\n * as mask generation is a common operation that can be optimized through caching.\n *\n * @private\n * @since 2.0.0\n */\n\nexport const maskCache = new Map<number, number>();\n\n/**\n * Determines if a primitive type is signed\n *\n * @param type - The primitive type name to check\n * @returns `true` if the type is signed, `false` otherwise\n *\n * @remarks\n * This function checks if a given primitive type represents a signed value.\n * Types that start with \"Int\" (e.g., Int8, Int16, Int32) are considered signed,\n * while other types (e.g., UInt8, Float32) are considered unsigned.\n *\n * @example\n * ```ts\n * isSignedType('Int8'); // Returns true\n * isSignedType('UInt8'); // Returns false\n * ```\n *\n * @since 2.0.0\n */\n\nexport function isSignedType(type: string): boolean {\n return type.startsWith('Int');\n}\n\n/**\n * Creates a bit mask of a specific size with optimized caching\n *\n * @param size - The number of bits to set in the mask (from the least significant bit)\n * @returns A number with the specified number of the least significant bits set to 1\n *\n * @remarks\n * This function generates a bit mask with the specified number of the least significant bits set to 1.\n * For performance optimization, it uses a cache to store previously calculated masks.\n * For example, for size 3, it returns 0b111 (decimal 7).\n *\n * The function first checks if the requested mask already exists in the cache.\n * If found, it returns the cached value; otherwise, it calculates a new mask,\n * stores it in the cache for future use, and returns it.\n *\n * @example\n * ```ts\n * getBitMask(3); // Returns 7 (binary 0b111)\n * getBitMask(8); // Returns 255 (binary 0b11111111)\n * ```\n *\n * @since 2.0.0\n */\n\nexport function getBitMask(size: number): number {\n let mask = maskCache.get(size);\n if (mask === undefined) {\n mask = (1 << size) - 1;\n maskCache.set(size, mask);\n }\n\n return mask;\n}\n\n/**\n * Processes a value according to the bitfield's type specifications\n *\n * @param descriptor - The descriptor defining the bitfield's properties\n * @param value - The numeric value to process\n * @returns The processed value, adjusted for the bitfield's type\n *\n * @remarks\n * This function ensures that a numeric value is properly formatted according to\n * the constraints of a bitfield descriptor. For signed types, it applies the correct\n * sign extension using BigInt operations to handle possible overflow/underflow\n * situations, then converts the result back to a JavaScript number.\n *\n * For unsigned types, the value is returned unchanged as no additional processing\n * is needed.\n *\n * @example\n * ```ts\n * // Process a value for a signed 4-bit field\n * const descriptor: BitfieldDescriptorInterface = {\n * type: 'Int8',\n * bitSize: 4,\n * bitPosition: 0\n * };\n *\n * processValueForBitfield(descriptor, 15); // Returns -1 (sign extension applied)\n * processValueForBitfield(descriptor, 7); // Returns 7 (no sign extension needed)\n * ```\n *\n * @since 2.0.0\n */\n\nexport function processValueForBitfield(descriptor: BitfieldDescriptorInterface, value: number): number {\n if (isSignedType(descriptor.type as string)) {\n return Number(BigInt.asIntN(descriptor.bitSize, BigInt(value)));\n }\n\n return value;\n}\n\n/**\n * Validates that a value fits within the bounds of a specified bitfield\n *\n * @param descriptor - The descriptor defining the bitfield's properties\n * @param value - The numeric value to validate\n *\n * @throws RangeError - When the value exceeds the allowable range for the bitfield\n *\n * @remarks\n * This function checks if a given value can be safely stored in a bitfield with\n * the specified characteristics. It calculates the minimum and maximum allowable values\n * based on the bitfield's size and whether it's signed or unsigned.\n *\n * For unsigned bitfields, the range is 0 to (2^bitSize - 1).\n * For signed bitfields, the range is -(2^(bitSize-1)) to (2^(bitSize-1) - 1).\n *\n * If the value falls outside the valid range, a RangeError is thrown with a\n * descriptive message indicating the constraint violation.\n *\n * @example\n * ```ts\n * // Validate a value for a 3-bit unsigned field\n * const unsignedField: BitfieldDescriptorInterface = {\n * type: 'UInt8',\n * bitSize: 3,\n * bitPosition: 0\n * };\n * validateBitFieldBounds(unsignedField, 5); // Valid (0-7 is valid range)\n * validateBitFieldBounds(unsignedField, 8); // Throws RangeError\n *\n * // Validate a value for a 3-bit signed field\n * const signedField: BitfieldDescriptorInterface = {\n * type: 'Int8',\n * bitSize: 3,\n * bitPosition: 0\n * };\n * validateBitFieldBounds(signedField, -4); // Valid (-4 to 3 is valid range)\n * validateBitFieldBounds(signedField, 4); // Throws RangeError\n * ```\n *\n * @since 2.0.0\n */\n\nexport function validateBitFieldBounds(descriptor: BitfieldDescriptorInterface, value: number): void {\n const isSigned = isSignedType(descriptor.type as string);\n const { bitSize, type } = descriptor;\n\n // Fix operator precedence with parentheses for shift operations\n const maxBitValue = isSigned ? ((1 << (bitSize - 1)) - 1) : ((1 << bitSize) - 1);\n const minBitValue = isSigned ? -(1 << (bitSize - 1)) : 0;\n\n if (value < minBitValue || value > maxBitValue) {\n throw new RangeError(\n `Value ${ value } does not fit within ${ bitSize } bits for type ${ type }`\n );\n }\n}\n\n/**\n * Validates the structural parameters of a bitfield descriptor\n *\n * @param descriptor - The bitfield descriptor to validate\n * @param operation - A string describing the operation context (for error messages)\n *\n * @throws Error - When the descriptor has invalid parameters\n *\n * @remarks\n * This function performs two key validation checks on bitfield descriptors:\n *\n * 1. It verifies that the primitive type size is supported (currently limited to 32 bits or fewer)\n * 2. It ensures that the bitfield's position and size do not exceed the bounds of its containing type\n *\n * These validations help prevent buffer overflows, data corruption, and other\n * potential issues that could occur when working with binary data structures.\n *\n * The operation parameter is used in error messages to provide context about\n * where the validation failure occurred.\n *\n * @example\n * ```ts\n * // Valid bitfield descriptor\n * const validDescriptor: BitfieldDescriptorInterface = {\n * type: 'UInt8',\n * bitSize: 3,\n * bitPosition: 5\n * };\n * validateBitfieldParameters(validDescriptor, 'read'); // No error thrown\n *\n * // Invalid: position + size exceeds type size (8 bits for UInt8)\n * const invalidDescriptor: BitfieldDescriptorInterface = {\n * type: 'UInt8',\n * bitSize: 6,\n * bitPosition: 4\n * };\n * validateBitfieldParameters(invalidDescriptor, 'write'); // Throws Error\n * ```\n *\n * @since 2.0.0\n */\n\nexport function validateBitfieldParameters(descriptor: BitfieldDescriptorInterface, operation: string): void {\n if (descriptor.bitSize < 1 || descriptor.bitPosition < 0) {\n throw new Error(`bitSize(${ descriptor.bitSize }) and bitPosition(${ descriptor.bitPosition }) ` +\n `must be greater than bitSize(1) and bitPosition(0) for ${ operation }`);\n }\n\n if (PRIMITIVE_TYPE_SIZES[descriptor.type] > 32) {\n throw new Error(`${ descriptor.type } is not supported yet`);\n }\n\n if (descriptor.bitPosition + descriptor.bitSize > PRIMITIVE_TYPE_SIZES[descriptor.type]) {\n throw new Error(\n `bitPosition(${ descriptor.bitPosition }) + bitSize(${ descriptor.bitSize }) ` +\n `exceeds ${ descriptor.type } size for ${ operation }`\n );\n }\n}\n\n/**\n * Extracts a bitfield value from a raw numeric value\n *\n * @param rawValue - The source value containing the bitfield\n * @param descriptor - The descriptor defining the bitfield's properties\n * @returns The extracted value from the bitfield\n *\n * @throws Error - When the bitfield parameters are invalid\n *\n * @remarks\n * This function extracts a specific bitfield from a larger numeric value according\n * to the provided descriptor. It first validates the bitfield parameters to ensure\n * they are within allowable bounds. Then it performs the following operations:\n *\n * 1. Creates an appropriate bit mask for the field's size\n * 2. Shifts the raw value right to align the target bits with the least significant position\n * 3. Applies the mask to extract only the relevant bits\n * 4. For signed types, if the most significant bit is set (indicating a negative value),\n * it extends the sign bit by OR'ing with the complement of the mask\n *\n * This function properly handles both signed and unsigned bitfields of various sizes.\n *\n * @example\n * ```ts\n * // Extracting an unsigned 3-bit field from bit position 2\n * const unsignedField: BitfieldDescriptorInterface = {\n * type: 'UInt8',\n * bitSize: 3,\n * bitPosition: 2\n * };\n *\n * extractBitfieldValue(0b10111100, unsignedField); // Returns 7 (0b111)\n *\n * // Extracting a signed 3-bit field from bit position 2\n * const signedField: BitfieldDescriptorInterface = {\n * type: 'Int8',\n * bitSize: 3,\n * bitPosition: 2\n * };\n *\n * extractBitfieldValue(0b10111100, signedField); // Returns -1 (sign extended from 0b111)\n * extractBitfieldValue(0b00011100, signedField); // Returns 3 (positive value 0b011)\n * ```\n *\n * @since 2.0.0\n */\n\nexport function extractBitfieldValue(rawValue: number, descriptor: BitfieldDescriptorInterface): number {\n validateBitfieldParameters(descriptor, 'read operation');\n\n const { type, bitPosition, bitSize } = descriptor;\n const mask = getBitMask(bitSize);\n const extractedValue = (rawValue >> bitPosition) & mask;\n\n if (isSignedType(type as string) && (extractedValue & (1 << (bitSize - 1)))) {\n return extractedValue | (~mask);\n }\n\n return extractedValue;\n}\n\n/**\n * Composes a new value by integrating a bitfield into a larger number\n *\n * @param rawValue - The original value containing multiple bitfields\n * @param descriptor - The descriptor defining the target bitfield's properties\n * @param value - The value to integrate into the bitfield\n * @returns A new composite value with the specified bitfield updated\n *\n * @throws Error - When the bitfield parameters are invalid\n * @throws RangeError - When the provided value exceeds the bounds of the bitfield\n *\n * @remarks\n * This function composes a new numeric value by integrating a specific bitfield with an existing value.\n * It precisely targets and modifies only the bits defined\n * by the descriptor while preserving all other bits in the original value.\n * The process involves:\n *\n * 1. Validating the bitfield parameters to ensure they are within allowable bounds\n * 2. Validating that the value to integrate fits within the bitfield's size constraints\n * 3. Processing the value to account for the bitfield's type (signed/unsigned)\n * 4. Creating an appropriate bit mask for the field's size\n * 5. Clearing only the target bits in the original value\n * 6. Inserting the new bits at the appropriate position\n *\n * The original value is not modified; instead, a new composite value is returned.\n *\n * @example\n * ```ts\n * // Composing a value with an unsigned 3-bit field at bit position 2\n * const unsignedField: BitfieldDescriptorInterface = {\n * type: 'UInt8',\n * bitSize: 3,\n * bitPosition: 2\n * };\n *\n * // Original: 0b10000010 (130)\n * // Composed: 0b10011010 (154)\n * composeBitfieldValue(0b10000010, unsignedField, 6); // Returns 154\n *\n * // Composing a value with a signed 3-bit field at bit position 1\n * const signedField: BitfieldDescriptorInterface = {\n * type: 'Int8',\n * bitSize: 3,\n * bitPosition: 1\n * };\n *\n * // Original: 0b11110000 (240)\n * // Composed: 0b11101110 (238) - integrating -1 (0b111 in 3-bit signed form)\n * composeBitfieldValue(0b11110000, signedField, -1); // Returns 238\n * ```\n *\n * @since 2.0.0\n */\n\nexport function composeBitfieldValue(rawValue: number, descriptor: BitfieldDescriptorInterface, value: number): number {\n validateBitfieldParameters(descriptor, 'write operation');\n validateBitFieldBounds(descriptor, value);\n\n const { bitPosition, bitSize } = descriptor;\n const processedValue = processValueForBitfield(descriptor, value);\n const mask = getBitMask(bitSize);\n const shiftedMask = mask << bitPosition;\n\n // Clear the bits at the target position and then set the new value\n return (rawValue & ~shiftedMask) | ((processedValue << bitPosition) & shiftedMask);\n}\n\n/**\n * Parses a string representation of a bitfield and returns a structured positioned descriptor object\n *\n * @param field - String in the format \"type:bitSize\" where type is a primitive type (e.g., \"Int8\", \"UInt16BE\")\n * and bitSize is the number of bits to allocate (e.g., \"Int8:4\")\n * @param position - The starting byte position of this element within the buffer\n * @param bitPosition - Starting position of the bitfield within the primitive type (0-based index, defaults to 0)\n * @returns A PositionedBitfieldDescriptorType object containing the parsed type, size, offset, bitSize, and bitPosition\n *\n * @throws Error - When the type is not supported (not found in PRIMITIVE_TYPE_SIZES)\n * @throws Error - When the bitPosition is negative or greater than or equal to the type size\n * @throws Error - When the bitSize is invalid (zero or non-numeric)\n * @throws Error - When the bitSize + bitPosition exceeds the available bits in the type\n *\n * @remarks\n * This function parses a string descriptor for a bitfield and validates that the\n * specified bitfield can fit within the given primitive type.\n * It creates a positioned descriptor that includes both the bitfield definition and its location in memory.\n * It ensures that:\n * - The primitive type is supported\n * - The bit position is within the valid range for the type\n * - The bit size is a valid number greater than zero\n * - The bitfield (of size bitSize starting at bitPosition) fits within the primitive type\n *\n * @example\n * ```ts\n * // Parse an 8-bit signed integer with 3 bits starting at position 0, at offset 0\n * const descriptor = parseBitfieldDescriptor('Int8:3');\n * // Returns: { type: 'Int8', size: 1, offset: 0, bitSize: 3, bitPosition: 0 }\n *\n * // Parse a 16-bit unsigned integer with 5 bits starting at position 2, at offset 4\n * const descriptor = parseBitfieldDescriptor('UInt16:5', 4, 2);\n * // Returns: { type: 'UInt16LE', size: 2, offset: 4, bitSize: 5, bitPosition: 2 }\n * ```\n *\n * @see PRIMITIVE_TYPE_SIZES\n * @see PositionedBitfieldDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function parseBitfieldDescriptor(field: string, position: number = 0, bitPosition: number = 0): PositionedBitfieldDescriptorType {\n const [ type, bitSizeStr ] = <[PrimitiveType, string]> field.split(':', 2);\n const bitSize = parseInt(bitSizeStr, 10);\n const typeSize = PRIMITIVE_TYPE_SIZES[type];\n const isBigEndian = type.endsWith('BE');\n\n if (!typeSize)\n throw new Error(`${ type } is not supported`);\n\n if (bitPosition < 0 || bitPosition >= typeSize)\n throw new Error(`Bitfield position ${ bitPosition } is out of bounds (must be between 0 and ${ typeSize - 1 })`);\n\n if (!bitSize)\n throw new Error(`${ field } is not valid`);\n\n if (bitSize + bitPosition >= typeSize)\n throw new Error(`${ type } size (${ typeSize }) is not enough to hold ${ bitSize } bits starting at position ${ bitPosition }`);\n\n return {\n kind: 'bitfield',\n type,\n size: typeSize / 8,\n position,\n bitSize,\n bitPosition,\n isBigEndian\n };\n}\n\n/**\n * Reads a bitfield value from a buffer at the specified position based on the provided context.\n *\n * @returns The extracted bitfield value after applying masks and shifts\n *\n * @throws Error - If the buffer is too small for the requested read\n *\n * @remarks\n * This function handles both big-endian and little-endian values based on the descriptor's\n * isBigEndian property. The function uses the BitfieldContextInterface as its 'this' context\n * to access buffer, descriptor, and offset properties.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: Buffer.from([0x12, 0x34, 0x56, 0x78]),\n * descriptor: {\n * position: 0,\n * size: 2,\n * isBigEndian: true,\n * bitOffset: 4,\n * bitLength: 8,\n * type: 'UInt16'\n * },\n * offset: 0\n * };\n * const value = readBitfield.call(context);\n * ```\n *\n * @see extractBitfieldValue\n * @see BitfieldContextInterface\n * @see PositionedBitfieldDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function readBitfield(this: BitfieldContextInterface): number {\n const absolutePosition = this.descriptor.position + this.offset;\n const endianMethod = this.descriptor.isBigEndian ? 'BE' : 'LE';\n const rawValue = this.buffer[`readUInt${ endianMethod }`](absolutePosition, this.descriptor.size);\n\n return extractBitfieldValue(rawValue, this.descriptor);\n}\n\n/**\n * Writes a bitfield value to a buffer at the specified position based on the provided context.\n *\n * @param value - The value to write to the bitfield\n * @returns\n *\n * @throws Error - If the buffer is too small for the requested write\n *\n * @remarks\n * This function handles both big-endian and little-endian values based on the descriptor's isBigEndian property.\n * It first reads the current value, modifies the specific bits, and then\n * writes the updated value back to the buffer.\n * The function uses the BitfieldContextInterface as its 'this' context to access buffer, descriptor, and offset.\n *\n * @example\n * ```ts\n * const context = {\n * buffer: Buffer.alloc(4),\n * descriptor: {\n * position: 0,\n * size: 2,\n * isBigEndian: true,\n * bitOffset: 4,\n * bitLength: 8\n * },\n * offset: 0\n * };\n * writeBitfield.call(context, 0xAB);\n * ```\n *\n * @see composeBitfieldValue\n * @see BitfieldContextInterface\n * @see PositionedBitfieldDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function writeBitfield(this: BitfieldContextInterface, value: number): void {\n const absolutePosition = this.descriptor.position + this.offset;\n const endianMethod = this.descriptor.isBigEndian ? 'BE' : 'LE';\n const rawValue = this.buffer[`readUInt${ endianMethod }`](absolutePosition, this.descriptor.size);\n const bitFieldValue = composeBitfieldValue(rawValue, this.descriptor, value);\n\n this.buffer[`writeUInt${ endianMethod }`](bitFieldValue, absolutePosition, this.descriptor.size);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n StringType,\n StringContextInterface,\n PositionedStringDescriptorType, StringDataType\n} from '@components/interfaces/string-component.interface';\n\n/**\n * Imports\n */\n\nimport { readMethod, splitBufferWithGap, writeMethod } from '@components/buffer.component';\n\n/**\n * A set containing all valid string primitive type identifiers\n *\n * @remarks\n * This constant provides a convenient way\n * to validate or check if a given string represents a valid string primitive type.\n * The set contains all supported string\n * encoding formats that can be used in data structures:\n * - 'utf8': UTF-8 encoding supporting the full Unicode character set\n * - 'ascii': ASCII encoding limited to 7-bit ASCII characters\n * - 'string': Default string representation based on the system's encoding\n *\n * This collection is useful for validation functions, type checking, or when\n * determining if a string identifier refers to a string primitive type.\n *\n * @example\n * ```ts\n * function isStringPrimitive(type: string): boolean {\n * return STRING_PRIMITIVE_LIST.has(type.toLowerCase());\n * }\n * ```\n *\n * @see StringType\n *\n * @since 2.0.0\n */\n\nexport const STRING_PRIMITIVE_LIST: Set<string> = new Set([ 'utf8', 'ascii', 'string' ]);\n\n/**\n * Parses a string representation of a string type descriptor into a structured object with positioning information\n *\n * @param field - String representation of the string descriptor in format \"type\" or \"type[size]\"\n * @param position - The starting position of this string within the buffer (defaults to 0)\n * @returns A structured PositionedStringDescriptor object with type, size, and offset information\n *\n * @throws Error - When the descriptor format doesn't match the expected pattern\n *\n * @remarks\n * This function converts a string-based string type specification into a structured descriptor object.\n * The input string can be in one of two formats:\n * - A simple string type name (e.g., \"utf8\", \"ascii\", \"string\")\n * - A string type with array size specification (e.g., \"utf8[10]\", \"ascii[25]\")\n *\n * When an array size is specified (e.g., \"utf8[10]\"),\n * it represents an array of 10 dynamic strings, each with its own length prefix.\n * Each string is stored sequentially in the buffer, one after another.\n *\n * The function validates that the input string matches the expected pattern for a valid string descriptor.\n * If an array size is specified in the descriptor, it is parsed as an integer and included in the returned object.\n *\n * By default, the function sets lengthType to 'UInt16LE', which means each string will be encoded with a\n * 2-byte length prefix, and size is initialized to 2 to account for the length prefix.\n *\n * @example\n * ```ts\n * // Parse a simple string type with offset\n * const descriptor1 = parseStringDescriptor('utf8', 0);\n * // Returns: { type: 'utf8', lengthType: 'UInt16LE', arraySize: undefined, offset: 0, size: 2 }\n *\n * // Parse a string type as an array of 15 dynamic strings with offset\n * const descriptor2 = parseStringDescriptor('ascii[15]', 24);\n * // Returns: { type: 'ascii', lengthType: 'UInt16LE', arraySize: 15, offset: 24, size: 2 }\n * ```\n *\n * @see StringType\n * @see UnsignedPrimitiveType\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function parseStringDescriptor(field: string, position: number = 0): PositionedStringDescriptorType {\n const pattern = /^(utf8|ascii|string)(?:\\[(\\d+)\\])?$/i;\n const match = <[string, StringType, string]> field.match(pattern);\n\n if (!match)\n throw new Error(`Invalid string descriptor: ${ field }`);\n\n const type = <StringType> match[1].toLowerCase();\n const arraySize = match[2] ? parseInt(match[2]) : undefined;\n\n return { type, arraySize, position, size: 2, lengthType: 'UInt16LE', kind: 'string' };\n}\n\n/**\n * Reads a single string from a buffer at the specified position based on the provided context.\n *\n * @param arrayOffset - Optional offset for reading strings within an array, defaults to 0\n * @returns The string value read from the buffer\n *\n * @throws Error - If null string exceeds the specified maxLength constraint\n * @throws Error - If BigInt is used in lengthType (e.g., 'BigInt64' or 'BigUint64')\n * @throws Error - If the buffer is too small for the requested read or if the encoding is invalid\n * @throws Error - If the string's length prefix indicates a size that would exceed the buffer's bounds\n *\n * @remarks\n * This function supports three different string formats:\n * 1. Length-prefixed strings - Where a length value precedes the string data (using lengthType)\n * 2. Null-terminated strings - Where the string ends with a null byte (0x00)\n * 3. Fixed-size strings - Where the string has a predetermined size\n *\n * The function uses the StringContextInterface as its 'this' context to access buffer,\n * descriptor, and offset properties. The encoding is determined by the descriptor's type property.\n *\n * @example\n * ```ts\n * // Reading a null-terminated string\n * const context = {\n * buffer: Buffer.from(\"Hello\\0World\"),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 6,\n * nullTerminated: true\n * },\n * offset: 0\n * };\n * const str = readSingleString.call(context);\n * // Returns: \"Hello\"\n * ```\n *\n * @see readMethod\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function readSingleString(this: StringContextInterface, arrayOffset: number = 0): string {\n const { position, type, size } = this.descriptor;\n const absolutePosition = this.offset + position + arrayOffset;\n const encoding = type === 'string' ? 'utf8' : type;\n\n if ('lengthType' in this.descriptor && this.descriptor.lengthType) {\n if(this.descriptor.lengthType.includes('Big'))\n throw new Error('BigInt are not supported');\n\n const lengthType = this.descriptor.lengthType as string;\n const stringLength = Number(readMethod<bigint | number>(this.buffer, lengthType)(absolutePosition));\n const dataOffset = absolutePosition + size;\n this.offset += stringLength;\n\n if((dataOffset + stringLength) > this.buffer.length)\n throw new Error(\n `String prefix length exceeds buffer position: ${ dataOffset } size: ${ stringLength } > ${ this.buffer.length }`\n );\n\n return this.buffer.subarray(dataOffset, dataOffset + stringLength).toString(encoding);\n }\n\n if ('nullTerminated' in this.descriptor) {\n let endPos = absolutePosition;\n const maxLength = 'maxLength' in this.descriptor ? this.descriptor.maxLength : 0;\n while (endPos < this.buffer.length && this.buffer[endPos] !== 0) {\n if(maxLength && endPos > maxLength)\n throw new Error(`NullTerminated String exceeds maximum length of ${ maxLength }`);\n\n endPos++;\n }\n\n const stringLength = endPos - absolutePosition;\n this.offset += stringLength + 1;\n\n return this.buffer.subarray(absolutePosition, endPos).toString(encoding);\n }\n\n return this.buffer.subarray(absolutePosition, absolutePosition + size).toString(encoding);\n}\n\n/**\n * Reads an array of strings from a buffer based on the provided context.\n *\n * @returns An array of strings read from the buffer\n *\n * @throws Error - If the buffer is too small for the requested read or if the encoding is invalid\n *\n * @remarks\n * This function reads multiple strings from a buffer by iteratively calling readSingleString\n * for each element in the array. The number of strings to read is determined by the descriptor's\n * arraySize property. For performance optimization, the result array is pre-allocated to the\n * exact size needed.\n *\n * The function uses the StringContextInterface as its 'this' context to access buffer,\n * descriptor, and offset properties. Each string in the array is positioned at intervals\n * determined by the descriptor's size property.\n *\n * @example\n * ```ts\n * // Reading an array of two fixed-length strings\n * const context = {\n * buffer: Buffer.from(\"HelloWorld\"),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 5,\n * arraySize: 2\n * },\n * offset: 0\n * };\n * const strArray = readStringArray.call(context);\n * // Returns: [\"Hello\", \"World\"]\n * ```\n *\n * @see readSingleString\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function readStringArray(this: StringContextInterface): Array<string> {\n const result: Array<string> = [];\n const { arraySize = 0, size } = this.descriptor;\n\n // Preallocate the array to avoid resizing\n result.length = arraySize;\n for (let i = 0; i < arraySize; i++) {\n result[i] = readSingleString.call(this, i * size);\n }\n\n return result;\n}\n\n/**\n * Reads a string or array of strings from a buffer based on the provided context.\n *\n * @returns A string value or array of strings depending on the descriptor configuration\n *\n * @throws Error - If the buffer is too small for the requested read or if the encoding is invalid\n *\n * @remarks\n * This function acts as a dispatcher that determines whether to read a single string\n * or an array of strings based on the descriptor's arraySize property. It uses the\n * StringContextInterface as its 'this' context to access buffer, descriptor, and offset properties.\n *\n * @example\n * ```ts\n * // Reading a single string\n * const singleStringContext = {\n * buffer: Buffer.from(\"Hello\\0World\"),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 6,\n * nullTerminated: true\n * },\n * offset: 0\n * };\n * const str = readString.call(singleStringContext);\n * // Returns: \"Hello\"\n *\n * // Reading an array of strings\n * const arrayStringContext = {\n * buffer: Buffer.from(\"HelloWorld\"),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 5,\n * arraySize: 2\n * },\n * offset: 0\n * };\n * const strArray = readString.call(arrayStringContext);\n * // Returns: [\"Hello\", \"World\"]\n * ```\n *\n * @see readStringArray\n * @see readSingleString\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function readString(this: StringContextInterface): StringDataType {\n if(('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return readStringArray.call(this);\n\n return readSingleString.call(this);\n}\n\n/**\n * Writes a single string to a buffer at the specified position based on the provided context.\n *\n * @param value - The string value to write to the buffer\n * @param arrayOffset - Optional offset for writing strings within an array, defaults to 0\n * @returns void\n *\n * @throws Error - If the buffer is too small or if the encoding is invalid\n * @throws Error - If BigInt is used in lengthType (e.g., 'BigInt64' or 'BigUint64')\n *\n * @remarks\n * This function supports three different string formats:\n * 1. Length-prefixed strings - Where a length value precedes the string data (using lengthType)\n * 2. Null-terminated strings - Where the string ends with a null byte (0x00)\n * 3. Fixed-size strings - Where the string has a predetermined size\n *\n * The function uses the StringContextInterface as its 'this' context to access buffer,\n * descriptor, and offset properties. The encoding is determined by the descriptor's type property.\n *\n * For length-prefixed and null-terminated strings, the buffer may be resized to accommodate\n * the string data using the splitBufferWithGap utility.\n *\n * @example\n * ```ts\n * // Writing a null-terminated string\n * const context = {\n * buffer: Buffer.alloc(10),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 6,\n * nullTerminated: true\n * },\n * offset: 0\n * };\n * writeSingleString.call(context, \"Hello\");\n * // Result: Buffer contains \"Hello\\0\"\n * ```\n *\n * @see writeMethod\n * @see splitBufferWithGap\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function writeSingleString(this: StringContextInterface, value: string, arrayOffset: number = 0): void {\n value ??= '';\n const { position, type, size } = this.descriptor;\n const absolutePosition = this.offset + position + arrayOffset;\n const encoding = type === 'string' ? 'utf8' : type;\n\n if ('lengthType' in this.descriptor && this.descriptor.lengthType) {\n if(this.descriptor.lengthType.includes('Big'))\n throw new Error('BigInt are not supported');\n\n const stringBuffer = Buffer.from(value, encoding);\n writeMethod<bigint | number>(\n this.buffer,\n this.descriptor.lengthType as string\n )(stringBuffer.length, absolutePosition);\n\n const [ start, end ] = splitBufferWithGap(this.buffer, absolutePosition + size);\n this.buffer = Buffer.concat([ start, stringBuffer, end ]);\n this.offset += stringBuffer.length;\n\n return;\n }\n\n if ('nullTerminated' in this.descriptor) {\n if('maxLength' in this.descriptor && this.descriptor.maxLength)\n value = value.length > this.descriptor.maxLength ? value.slice(0, this.descriptor.maxLength) : value;\n\n const nullTerminatedString = value.endsWith('\\0') ? value : `${value}\\0`;\n const stringBuffer = Buffer.from(nullTerminatedString, encoding);\n const [ start, end ] = splitBufferWithGap(this.buffer, absolutePosition, size);\n\n this.buffer = Buffer.concat([ start, stringBuffer, end ]);\n this.offset += stringBuffer.length;\n\n return;\n }\n\n this.buffer.write(value, absolutePosition, size, encoding);\n}\n\n/**\n * Writes an array of strings to a buffer based on the provided context.\n *\n * @param values - The array of string values to write to the buffer\n * @returns void\n *\n * @throws Error - If the buffer is too small or if the encoding is invalid\n *\n * @remarks\n * This function writes multiple strings to a buffer by iteratively calling writeSingleString\n * for each element in the input array. The number of strings to write is determined by\n * the descriptor's arraySize property.\n *\n * If the input array contains fewer elements than arraySize, empty strings will be written\n * for the remaining positions. Each string in the array is positioned at intervals\n * determined by the descriptor's size property.\n *\n * The function uses the StringContextInterface as its 'this' context to access buffer,\n * descriptor, and offset properties.\n *\n * @example\n * ```ts\n * // Writing an array of two fixed-length strings\n * const context = {\n * buffer: Buffer.alloc(10),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 5,\n * arraySize: 2\n * },\n * offset: 0\n * };\n * writeStringArray.call(context, [\"Hello\", \"World\"]);\n * // Result: Buffer contains \"HelloWorld\"\n * ```\n *\n * @see writeSingleString\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function writeStringArray(this: StringContextInterface, values: Array<string>): void {\n const { arraySize = 0, size } = this.descriptor;\n\n for (let i = 0; i < arraySize; i++) {\n const elementValue = i < values.length ? values[i] : '';\n writeSingleString.call(this, elementValue, i * size);\n }\n}\n\n/**\n * Writes a string or array of strings to a buffer based on the provided context.\n *\n * @param value - The string value or array of strings to write to the buffer\n * @returns void\n *\n * @throws Error - If the buffer is too small for the write operation or if the encoding is invalid\n *\n * @remarks\n * This function acts as a dispatcher that determines whether to write a single string\n * or an array of strings based on the descriptor's arraySize property. It handles\n * type conversion to ensure compatibility between the provided value and the expected format.\n *\n * - If the descriptor specifies an array (arraySize property exists), any single string\n * will be wrapped in an array before being processed.\n * - If the descriptor does not specify an array but an array is provided, only the first\n * element (or an empty string if the array is empty) will be used.\n *\n * The function uses the StringContextInterface as its 'this' context to access buffer,\n * descriptor, and offset properties.\n *\n * @example\n * ```ts\n * // Writing a single string\n * const singleStringContext = {\n * buffer: Buffer.alloc(10),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 6,\n * nullTerminated: true\n * },\n * offset: 0\n * };\n * writeString.call(singleStringContext, \"Hello\");\n * // Result: Buffer contains \"Hello\\0\"\n *\n * // Writing an array of strings\n * const arrayStringContext = {\n * buffer: Buffer.alloc(10),\n * descriptor: {\n * position: 0,\n * type: 'utf8',\n * size: 5,\n * arraySize: 2\n * },\n * offset: 0\n * };\n * writeString.call(arrayStringContext, [\"Hello\", \"World\"]);\n * // Result: Buffer contains \"HelloWorld\"\n * ```\n *\n * @see writeSingleString\n * @see writeStringArray\n * @see StringContextInterface\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\nexport function writeString(this: StringContextInterface, value: StringDataType): void {\n if(('arraySize' in this.descriptor) && this.descriptor.arraySize)\n return writeStringArray.call(this, Array.isArray(value) ? value : [ value ]);\n\n return writeSingleString.call(this, Array.isArray(value) ? (value[0] || '') : value);\n}\n", "/**\n * Type imports\n */\n\nimport type {\n StringType,\n StringDataType,\n StringContextInterface,\n PositionedStringDescriptorType,\n LengthPrefixedDescriptorInterface\n} from '@components/interfaces/string-component.interface';\n\nimport type {\n PrimitiveType,\n PrimitiveDataType,\n PrimitiveContextInterface,\n PositionedDescriptorInterface\n} from '@components/interfaces/primitive-component.interface';\n\nimport type {\n FieldsType,\n StringFieldType,\n ContextInterface,\n DescriptorFieldType,\n AccumulatorInterface,\n StructSchemaInterface,\n PositionedDescriptorFieldType\n} from '@services/interfaces/struct-service.interface';\n\nimport type {\n BitfieldContextInterface,\n PositionedBitfieldDescriptorType\n} from '@components/interfaces/bitfield-component.interface';\n\nimport type {\n StructDataType,\n StructContextInterface\n} from '@components/interfaces/struct-component.interface';\n\n/**\n * Implementation imports\n */\n\nimport { readStruct, writeStruct } from '@components/struct.component';\nimport { parseBitfieldDescriptor, readBitfield, writeBitfield } from '@components/bitfield.component';\nimport { parseStringDescriptor, readString, STRING_PRIMITIVE_LIST, writeString } from '@components/string.component';\nimport {\n readPrimitive,\n writePrimitive,\n PRIMITIVE_TYPE_SIZES,\n parsePrimitiveDescriptor\n} from '@components/primitive.component';\n\n/**\n * A versatile class for creating and manipulating structured binary data objects\n *\n * @template T - The type of the object structure this class represents\n * @remarks\n * The Struct class provides a type-safe way to define, read, and write structured binary data.\n * It supports various field types including:\n *\n * Numeric types with explicit size and endianness:\n * - `UInt8`, `Int8`, `UInt16LE/BE`, `Int16LE/BE`, `UInt32LE/BE`, `Int32LE/BE`\n * - `BigUInt64LE/BE`, `BigInt64LE/BE`, `FloatLE/BE`, `DoubleLE/BE`\n *\n * Arrays of numeric types:\n * - `UInt8[20]`, `Int32LE[15]`\n *\n * Bitfields:\n * - `UInt16LE:7` (7 bits within a 16-bit field)\n * - `UInt8:4` (4 bits within an 8-bit field)\n * - `UInt16BE:12` (12 bits within a 16-bit big-endian field)\n *\n * String types:\n * - Array of strings: `string[10]`, `ascii[10]`, `utf8[10]`\n * (array of 10 strings, each preceded by a UInt16LE length prefix)\n * - Null-terminated: `{ type: 'string', nullTerminated: true }`\n * (variable-length string that reads until the first null character)\n * - Length-prefixed: `{ type: 'string', lengthType: 'UInt32LE' }`\n * (variable-length string preceded by its length stored as UInt32LE)\n * - Fixed-length string: `{ type: 'string', size: 10, arraySize: 2 }`\n * (array of 2 fixed-length strings, each 10 characters long)\n *\n * Nested structures:\n * - `Struct` (nested structure)\n * - `{ type: Struct, arraySize: 2 }` (array of structures)\n *\n * @since 2.0.0\n */\n\nexport class Struct<T extends object = object> {\n /**\n * The total fixed size of the schema in bytes.\n *\n * @since 2.0.0\n */\n\n readonly size: number;\n\n /**\n * Internal map that stores field descriptors with their positions in the binary structure.\n * Maps property names to their corresponding descriptor metadata.\n *\n * @since 2.0.0\n */\n\n private readonly schema: Map<string, PositionedDescriptorFieldType> = new Map();\n\n /**\n * Creates a new binary structure schema instance.\n *\n * @param schema - The structure schema definition that describes field types and their layout\n *\n * @throws SchemaValidationError - When the provided schema contains invalid field definitions\n *\n * @since 2.0.0\n */\n\n constructor(schema: StructSchemaInterface) {\n this.size = this.compileSchema(schema);\n }\n\n /**\n * Deserializes binary data from a Buffer into a structured object according to the defined schema.\n *\n * @param buffer - The binary buffer containing the serialized data to convert to an object\n * @param getDynamicOffset - Optional callback function that receives the offset of dynamic content that changes the buffer's static size.\n * The offset represents the difference between the original and final buffer positions.\n *\n * @throws Error - When the provided input is not a Buffer instance\n * @throws Error - When the provided buffer size is smaller than the expected schema size\n * @throws DeserializationError - When buffer data doesn't match the expected schema format\n *\n * @since 2.0.0\n */\n\n toObject(buffer: Buffer, getDynamicOffset?: (offset: number) => void): Required<T> {\n if(!Buffer.isBuffer(buffer))\n throw new Error(`Expected a buffer, but received ${ typeof buffer }`);\n\n if(buffer.length < this.size)\n throw new Error(`Buffer size is less than expected: ${ buffer.length } < ${ this.size }`);\n\n const result: Record<string, unknown> = {};\n const context: ContextInterface = {\n buffer,\n offset: 0\n } as ContextInterface;\n\n for (const [ name, descriptor ] of this.schema) {\n context.descriptor = descriptor;\n result[name] = this.readValue(context, descriptor.kind);\n }\n\n if (getDynamicOffset && typeof getDynamicOffset === 'function')\n getDynamicOffset(context.offset);\n\n return result as Required<T>;\n }\n\n /**\n * Serializes a structured object into a binary buffer according to the defined schema.\n *\n * @param data - The object containing fields to be serialized\n * @returns A buffer containing the binary representation of the data\n *\n * @throws Error - When input is not an object or when field values don't match their type definitions\n *\n * @since 2.0.0\n */\n\n toBuffer(data: T): Buffer {\n if (!data || typeof data !== 'object')\n throw new Error(`Expected an object of fields, but received ${ typeof data }`);\n\n const context: ContextInterface = {\n buffer: Buffer.alloc(this.size),\n offset: 0\n } as ContextInterface;\n\n for (const [ name, descriptor ] of this.schema) {\n context.descriptor = descriptor;\n const value = data[name as keyof T];\n this.writeValue(context, descriptor.kind, value);\n }\n\n return context.buffer;\n }\n\n /**\n * Reads a value from the buffer based on its descriptor kind.\n *\n * @param context - The current reading context containing buffer and offset information\n * @param kind - The descriptor kind that determines how to interpret binary data\n * @returns The deserialized value of the appropriate type\n *\n * @see ContextInterface\n * @see PositionedDescriptorInterface\n *\n * @since 2.0.0\n */\n\n private readValue(context: ContextInterface, kind: PositionedDescriptorInterface['kind']): unknown {\n switch (kind) {\n case 'struct':\n return readStruct.call(context as StructContextInterface);\n case 'bitfield':\n return readBitfield.call(context as BitfieldContextInterface);\n case 'string':\n return readString.call(context as StringContextInterface);\n default:\n return readPrimitive.call(context as PrimitiveContextInterface);\n }\n }\n\n /**\n * Writes a value to the buffer based on its descriptor kind.\n *\n * @param context - The current writing context containing buffer and offset information\n * @param kind - The descriptor kind that determines how to serialize the data\n * @param value - The value to write into the buffer\n *\n * @throws Error - When the value type doesn't match the expected type for the given descriptor\n *\n * @see ContextInterface\n * @see PositionedDescriptorInterface\n *\n * @since 2.0.0\n */\n\n private writeValue(context: ContextInterface, kind: PositionedDescriptorInterface['kind'], value: unknown): void {\n switch (kind) {\n case 'struct':\n writeStruct.call(context as StructContextInterface, value as StructDataType);\n break;\n case 'bitfield':\n writeBitfield.call(context as BitfieldContextInterface, value as number);\n break;\n case 'string':\n writeString.call(context as StringContextInterface, value as StringDataType);\n break;\n default:\n writePrimitive.call(context as PrimitiveContextInterface, value as PrimitiveDataType);\n }\n }\n\n /**\n * Calculates the size and position of a field within the binary structure.\n *\n * @param field - The field descriptor containing type information\n * @param position - The current position in the buffer where this field should be placed\n * @returns A positioned field descriptor with size and position information\n *\n * @throws Error - When an invalid field type is encountered\n *\n * @see DescriptorFieldType\n * @see PositionedDescriptorFieldType\n *\n * @since 2.0.0\n */\n\n private computeFieldSize(field: DescriptorFieldType, position: number): PositionedDescriptorFieldType {\n if (field.type instanceof Struct)\n return { ...field, position, size: field.type.size, kind: 'struct' };\n\n if (STRING_PRIMITIVE_LIST.has(field.type as StringType))\n return this.computeStringFieldSize(field, position);\n\n const size = PRIMITIVE_TYPE_SIZES[field.type as PrimitiveType];\n if (size !== undefined)\n return { ...field, position, size: size / 8, kind: 'primitive' };\n\n throw new Error(`Invalid field type: ${ field.type }`);\n }\n\n /**\n * Calculates the size and position information for string fields based on their configuration.\n *\n * @param field - The string field descriptor containing type and encoding information\n * @param position - The current position in the buffer where this field should be placed\n * @returns A positioned string field descriptor with size and position information\n *\n * @see DescriptorFieldType\n * @see PositionedStringDescriptorType\n *\n * @since 2.0.0\n */\n\n private computeStringFieldSize(field: DescriptorFieldType, position: number): PositionedStringDescriptorType {\n const positionedDescriptor: PositionedStringDescriptorType = {\n ...field,\n position,\n kind: 'string'\n } as PositionedStringDescriptorType;\n\n if ('lengthType' in field && field.lengthType) {\n const primitiveSize = PRIMITIVE_TYPE_SIZES[field.lengthType as PrimitiveType];\n if (!primitiveSize) {\n throw new Error(`Invalid length type: ${field.lengthType}`);\n }\n\n positionedDescriptor.size = primitiveSize / 8;\n } else if ('nullTerminated' in field && field.nullTerminated) {\n positionedDescriptor.size = 0;\n } else if (!('size' in field) || !field.size) {\n (positionedDescriptor as LengthPrefixedDescriptorInterface).lengthType = 'UInt16LE';\n positionedDescriptor.size = PRIMITIVE_TYPE_SIZES['UInt16LE'] / 8;\n }\n\n return positionedDescriptor;\n }\n\n /**\n * Parses a string field notation into a properly typed descriptor with position information.\n *\n * @param fieldNotation - The string representation of the field definition\n * @param offset - The current offset in the buffer where this field should be placed\n * @returns A positioned field descriptor with the appropriate type (bitfield, string, or primitive)\n *\n * @see StringFieldType\n * @see PositionedDescriptorFieldType\n *\n * @since 2.0.0\n */\n\n\n private parseStringNotation(fieldNotation: StringFieldType, offset: number): PositionedDescriptorFieldType {\n if (fieldNotation.includes(':'))\n return parseBitfieldDescriptor(fieldNotation, offset);\n\n const stringType = [ ...STRING_PRIMITIVE_LIST ].find(prefix =>\n fieldNotation.startsWith(prefix));\n\n return stringType\n ? parseStringDescriptor(fieldNotation, offset)\n : parsePrimitiveDescriptor(fieldNotation, offset);\n }\n\n /**\n * Converts a field definition into a positioned descriptor with size information.\n *\n * @param field - The field to convert, which can be a Struct instance, string notation, or field descriptor\n * @param position - The current position in the buffer where this field should be placed\n * @returns A positioned field descriptor with calculated size and position information\n *\n * @see FieldsType\n * @see PositionedDescriptorFieldType\n *\n * @since 2.0.0\n */\n\n private convertToSizedField(field: FieldsType, position: number): PositionedDescriptorFieldType {\n if (field instanceof Struct)\n return { type: field, position, size: field.size, kind: 'struct' };\n\n return typeof field === 'string'\n ? this.parseStringNotation(field, position)\n : this.computeFieldSize(field, position);\n }\n\n /**\n * Compiles a schema definition into a binary structure with calculated field positions and sizes.\n *\n * @param schema - The structure schema definition containing field definitions\n * @returns The total size of the compiled structure in bytes\n *\n * @throws Error - If any field's array size exceeds Number.MAX_SAFE_INTEGER\n *\n * @remarks\n * This method processes the schema field by field, handling both standard fields and bitfields.\n * For bitfields, it tracks bit positions and packs them appropriately.\n * The final byte count includes any remaining bits from the last bitfield.\n *\n * @see StructSchemaInterface\n * @since 2.0.0\n */\n\n private compileSchema(schema: StructSchemaInterface): number {\n const accumulator: AccumulatorInterface = {\n bits: 0,\n bytes: 0,\n bitFieldSize: 0,\n bitFieldType: 'UInt8'\n };\n\n for (const [ fieldName, field ] of Object.entries(schema)) {\n const sizedField = this.convertToSizedField(field, accumulator.bytes);\n if('arraySize' in sizedField && sizedField.arraySize) {\n if(sizedField.arraySize >= Number.MAX_SAFE_INTEGER) {\n throw new Error(`Array size exceeds maximum safe integer: ${ sizedField.arraySize }`);\n }\n }\n\n if ('bitSize' in sizedField && sizedField.bitSize > 0) {\n this.processBitfield(accumulator, fieldName, sizedField);\n } else {\n this.processStandardField(accumulator, fieldName, sizedField);\n }\n }\n\n if (accumulator.bits > 0)\n accumulator.bytes += accumulator.bitFieldSize;\n\n return accumulator.bytes;\n }\n\n /**\n * Processes a bitfield descriptor and updates the structure's accumulator.\n *\n * @param accumulator - The current state accumulator for the schema compilation\n * @param name - The field name in the schema\n * @param field - The positioned bitfield descriptor with size and type information\n\n * @remarks\n * This method handles the placement of bitfields within the structure.\n * It determines whether a new bitfield container needs to be started based on:\n * - If the current bitfield is full\n * - If the requested type differs from the current bitfield type\n * - If the sizes don't match\n *\n * When a new bitfield container is needed, the byte position is advanced\n * and bit counting resets. The field's bit position is tracked for later\n * value extraction/insertion.\n *\n * @see AccumulatorInterface\n * @see PositionedBitfieldDescriptorType\n *\n * @since 2.0.0\n */\n\n private processBitfield(accumulator: AccumulatorInterface, name: string, field: PositionedBitfieldDescriptorType): void {\n const bitsInField = field.size * 8;\n const requestedBitSize = field.bitSize;\n\n const needsNewBitfield =\n accumulator.bits + requestedBitSize > bitsInField ||\n accumulator.bitFieldType !== field.type ||\n accumulator.bitFieldSize !== field.size;\n\n if (needsNewBitfield) {\n accumulator.bytes += accumulator.bitFieldSize;\n accumulator.bits = 0;\n field.position = accumulator.bytes;\n }\n\n field.bitPosition = accumulator.bits;\n this.schema.set(name, field);\n\n accumulator.bits += requestedBitSize;\n accumulator.bitFieldType = field.type;\n accumulator.bitFieldSize = field.size;\n }\n\n /**\n * Processes a standard (non-bitfield) field descriptor and updates the structure's accumulator.\n *\n * @param accumulator - The current state accumulator for the schema compilation\n * @param name - The field name in the schema\n * @param field - The positioned field descriptor with size information\n *\n * @remarks\n * This method handles the placement of standard fields within the structure.\n * If there's an active bitfield being processed (accumulator.bits \\> 0), it finalizes\n * that bitfield first by advancing the byte position before placing this new field.\n *\n * For array fields, the total size is calculated as the product of the element size\n * and the array size. The accumulator's byte position is advanced by the total field size.\n *\n * @see AccumulatorInterface\n * @see PositionedDescriptorFieldType\n *\n * @since 2.0.0\n */\n\n private processStandardField(accumulator: AccumulatorInterface, name: string, field: PositionedDescriptorFieldType): void {\n if (accumulator.bits > 0) {\n accumulator.bytes += accumulator.bitFieldSize;\n accumulator.bits = 0;\n field.position = accumulator.bytes;\n }\n\n this.schema.set(name, field);\n const arraySize = 'arraySize' in field ? field.arraySize || 0 : 0;\n const totalSize = arraySize > 0 ? field.size * arraySize : field.size;\n accumulator.bytes += totalSize;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PacketLogInterface, PacketStatusInterface } from '@packets/interfaces/packet-schema.interface';\nimport type { PacketErrorInterface, PacketEventsInterface } from '@packets/interfaces/packet-schema.interface';\nimport type { PacketHeaderInterface, PacketInvocationInterface } from '@packets/interfaces/packet-schema.interface';\n\n/**\n * Imports\n */\n\nimport { Struct } from '@remotex-labs/xstruct';\n\n/**\n * Schema for serializing and deserializing {@link PacketInvocationInterface} data.\n *\n * @remarks\n * Represents the location in source code where a test, describe, or log originates.\n *\n * @since 1.0.0\n */\n\nexport const invocationSchema = new Struct<PacketInvocationInterface>({\n line: 'UInt32LE',\n column: 'UInt32LE',\n source: 'string'\n});\n\n/**\n * Schema for serializing and deserializing {@link PacketHeaderInterface} data.\n *\n * @remarks\n * Contains metadata for each packet, including kind, suite and runner identifiers, and timestamp.\n *\n * @since 1.0.0\n */\n\nexport const headerSchema = new Struct<PacketHeaderInterface>({\n kind: 'UInt8:4',\n suiteId: { type: 'string', size: 14 },\n runnerId: { type: 'string', size: 14 },\n timestamp: 'string'\n});\n\n/**\n * Schema for serializing and deserializing {@link PacketLogInterface} data.\n *\n * @remarks\n * Used for console-like logs emitted by tests or describes, including message, level, ancestry, and invocation.\n *\n * @since 1.0.0\n */\n\nexport const logSchema = new Struct<PacketLogInterface>({\n level: 'UInt8',\n message: { type: 'string', lengthType: 'UInt32LE' },\n ancestry: { type: 'string', lengthType: 'UInt32LE' },\n invocation: invocationSchema\n});\n\n/**\n * Schema for serializing and deserializing {@link PacketErrorInterface} data.\n *\n * @remarks\n * Represents suite-level fatal errors that are not tied to specific tests or describes.\n *\n * @since 1.0.0\n */\n\nexport const errorSchema = new Struct<PacketErrorInterface>({\n error: { type: 'string', lengthType: 'UInt32LE' }\n});\n\n/**\n * Schema for serializing and deserializing {@link PacketStatusInterface} data.\n *\n * @remarks\n * Represents status updates for individual tests or describe blocks,\n * including whether it is TODO, skipped, and its ancestry and description.\n *\n * @since 1.0.0\n */\n\nexport const statusSchema = new Struct<PacketStatusInterface>({\n type: 'UInt8:5',\n todo: 'UInt8:1',\n skipped: 'UInt8:1',\n duration: 'UInt32LE',\n ancestry: { type: 'string', lengthType: 'UInt32LE' },\n description: { type: 'string', lengthType: 'UInt32LE' }\n});\n\n/**\n * Schema for serializing and deserializing {@link PacketEventsInterface} data.\n *\n * @remarks\n * Represents events emitted during the test or describe execution,\n * including pass/fail status, duration, error messages, ancestry, and invocation.\n *\n * @since 1.0.0\n */\n\nexport const eventsSchema = new Struct<PacketEventsInterface>({\n type: 'UInt8:5',\n passed: 'UInt8:1',\n duration: 'UInt32LE',\n ancestry: { type: 'string', lengthType: 'UInt32LE' },\n description: { type: 'string', lengthType: 'UInt32LE' },\n errors: { type: 'string', lengthType: 'UInt32LE' }\n});\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Struct } from '@remotex-labs/xstruct';\n\n/**\n * Imports\n */\n\nimport { errorSchema, eventsSchema, logSchema, statusSchema } from '@packets/schema/packet.schema';\n\n/**\n * Defines the different kinds of packets that can be transmitted or received.\n *\n * @remarks\n * Each packet kind corresponds to a specific type of event or message in the test framework:\n * - `Log`: Console or logging messages\n * - `Error`: Suite-level fatal errors\n * - `Status`: Test or describe start events, including `skipped` and `todo` flags\n * - `Events`: Test or describe end events, only for completed tests/describes (no skipped or TODO)\n *\n * @since 1.0.0\n */\n\nexport const enum PacketKind {\n /**\n * Represents a log message packet, e.g., `console.log`, `console.error`.\n * @since 1.0.0\n */\n\n Log = 1,\n\n /**\n * Represents a fatal suite-level error.\n * Not associated with any test, describe, or hook.\n * @since 1.0.0\n */\n\n Error = 2,\n\n /**\n * Represents a status packet for test or describe start events.\n *\n * @remarks\n * Includes flags for:\n * - `skipped`: Whether the test or describe was skipped\n * - `todo`: Whether the test is marked as TODO\n *\n * @since 1.0.0\n */\n\n Status = 3,\n\n /**\n * Represents an event packet for test or describe end events.\n *\n * @remarks\n * Only includes completed tests/describes; skipped or TODO tests are not included.\n * Contains information such as `passed` and `duration`.\n *\n * @since 1.0.0\n */\n\n Events = 4\n}\n\n/**\n * Maps each {@link PacketKind} to its corresponding {@link Struct} schema for serialization/deserialization.\n *\n * @remarks\n * This object allows encoding and decoding packets of different kinds using\n * their respective `xStruct` schemas. Use `PacketSchemas[PacketKind.Log]` to\n * get the schema for log packets, etc.\n *\n * @see PacketKind\n * @see Struct\n *\n * @since 1.0.0\n */\n\nexport const PacketSchemas: Record<PacketKind, Struct> = {\n [PacketKind.Log]: logSchema,\n [PacketKind.Error]: errorSchema,\n [PacketKind.Status]: statusSchema,\n [PacketKind.Events]: eventsSchema\n} as const;\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PacketHeaderInterface } from '@packets/interfaces/packet-schema.interface';\nimport type { DecodedPacketType, PacketPayloadMapType } from '@packets/interfaces/packets.interface';\n\n/**\n * Imports\n */\n\nimport { serializeError } from '@remotex-labs/xjet-expect';\nimport { PacketKind } from '@packets/constants/packet-schema.constants';\nimport { errorSchema, headerSchema } from '@packets/schema/packet.schema';\nimport { PacketSchemas } from '@packets/constants/packet-schema.constants';\n\n/**\n * Exports constants\n */\n\nexport * from '@packets/constants/packet-schema.constants';\n\n/**\n * Exports interfaces\n */\n\nexport * from '@packets/interfaces/packets.interface';\nexport * from '@packets/interfaces/packet-schema.interface';\n\n/**\n * Encodes a packet of a given kind into a `Buffer`.\n *\n * @template T - The packet kind (`PacketKind.Log`, `PacketKind.Error`, `PacketKind.Status`, or `PacketKind.Events`)\n *\n * @param kind - The type of packet to encode\n * @param data - Partial data matching the packet type; will be combined with header information\n *\n * @returns A `Buffer` containing the serialized packet\n *\n * @throws Error if the provided `kind` does not correspond to a known packet schema\n *\n * @remarks\n * This function combines a header and the payload according to the packet kind.\n * The header includes the suite ID, runner ID, and a timestamp.\n *\n * @since 1.0.0\n */\n\nexport function encodePacket<T extends PacketKind>(kind: T, data: Partial<PacketPayloadMapType[T]>): Buffer {\n const schema = PacketSchemas[kind];\n if (!schema) throw new Error(`Invalid schema kind: ${ kind }`);\n\n const header: PacketHeaderInterface = {\n kind: kind,\n suiteId: globalThis?.__XJET?.runtime?.suiteId ?? '',\n runnerId: globalThis?.__XJET?.runtime.runnerId ?? '',\n timestamp: (new Date()).toISOString()\n };\n\n return Buffer.concat([\n headerSchema.toBuffer(header),\n schema.toBuffer(data)\n ]);\n}\n\n/**\n * Decodes a packet from a `Buffer` into its corresponding object representation.\n *\n * @template T - The expected packet kind (`PacketKind.Log`, `PacketKind.Error`, `PacketKind.Status`, or `PacketKind.Events`)\n *\n * @param buffer - The buffer containing the encoded packet\n * @returns The decoded packet object, combining the header and payload fields\n *\n * @throws Error if the packet kind is unknown or invalid\n *\n * @remarks\n * Decodes both the header and payload based on the packet kind.\n *\n * @since 1.0.0\n */\n\nexport function decodePacket<T extends PacketKind>(buffer: Buffer): DecodedPacketType<T> {\n let offset = headerSchema.size;\n const header = headerSchema.toObject(buffer, (dynamicOffset: number): void => {\n offset += dynamicOffset;\n });\n\n const type = header.kind as PacketKind;\n const schema = PacketSchemas[type];\n if (!schema) {\n throw new Error(`Unknown packet kind: ${ type }`);\n }\n\n const dataBuffer = buffer.subarray(offset);\n const data = schema.toObject(dataBuffer) as PacketPayloadMapType[T];\n\n return { ...header, ...data };\n}\n\n/**\n * Encodes an {@link Error} instance into a binary buffer following the packet schema.\n *\n * @param error - The error object to be serialized and encoded.\n * @param suiteId - Identifier of the suite where the error occurred.\n * @param runnerId - Identifier of the runner reporting the error.\n *\n * @returns A {@link Buffer} containing the encoded error packet, ready for transmission.\n *\n * @remarks\n * The function creates two binary sections:\n * - A **header**, describing the packet kind (`Error`), suite ID, runner ID, and timestamp.\n * - A **data buffer**, holding the serialized error details in JSON format.\n *\n * These two sections are concatenated into a single buffer.\n *\n * @example\n * ```ts\n * try {\n * throw new Error(\"Test failed\");\n * } catch (err) {\n * const buffer = encodeErrorSchema(err, \"suite-123\", \"runner-456\");\n * socket.send(buffer); // transmit over a transport channel\n * }\n * ```\n *\n * @see serializeError\n * @see PacketKind.Error\n *\n * @since 1.0.0\n */\n\nexport function encodeErrorSchema(error: Error, suiteId: string, runnerId: string): Buffer {\n const header = headerSchema.toBuffer({\n kind: PacketKind.Error,\n suiteId: suiteId ?? '',\n runnerId: runnerId ?? '',\n timestamp: (new Date()).toISOString()\n });\n\n const dataBuffer = errorSchema.toBuffer({\n error: JSON.stringify(serializeError(error))\n });\n\n return Buffer.concat([ header, dataBuffer ]);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { MessageType } from '@messages/constants/report.constant';\nimport type { EmitEventInterface, EmitStatusInterface } from '@shared/services/interfaces/emit-service.interface';\n\n/**\n * Imports\n */\n\nimport { serializeError } from '@remotex-labs/xjet-expect';\nimport { encodePacket, PacketKind } from '@packets/packets.module';\n\n/**\n * Emits a status update packet to the dispatcher.\n *\n * @param type - The {@link MessageType} representing the kind of status (e.g., suite start, suite end).\n * @param notification - The {@link EmitStatusInterface} containing ancestry and description details.\n *\n * @remarks\n * This function encodes the notification into a `PacketKind.Status` packet\n * and sends it via the global `dispatch` mechanism.\n *\n * @see MessageType\n * @see encodePacket\n * @see PacketKind.Status\n * @see EmitStatusInterface\n *\n * @since 1.0.0\n */\n\nexport function emitStatus(type: MessageType, notification: EmitStatusInterface = {}): void {\n dispatch(encodePacket(PacketKind.Status, {\n type: type,\n todo: notification?.todo,\n skipped: notification?.skipped,\n duration: notification?.duration,\n ancestry: notification?.ancestry?.join(','),\n description: notification?.description\n }));\n}\n\n/**\n * Emits an action (event) packet to the dispatcher.\n *\n * @param type - The {@link MessageType} representing the kind of action (e.g., test end, describe end).\n * @param notification - The {@link EmitEventInterface} containing ancestry, description,\n * duration, and possible test errors.\n *\n * @remarks\n * - Errors are serialized with {@link serializeError} before being encoded.\n * - The function encodes the notification into a `PacketKind.Events` packet\n * and sends it via the global `dispatch` mechanism.\n *\n * @see MessageType\n * @see encodePacket\n * @see serializeError\n * @see PacketKind.Events\n * @see EmitEventInterface\n *\n * @since 1.0.0\n */\n\nexport function emitEvent(type: MessageType, notification: EmitEventInterface): void {\n const stringErrors = notification.errors?.map((error: Error) =>\n serializeError(error)\n ) || [];\n\n dispatch(encodePacket(PacketKind.Events, {\n type: type,\n errors: stringErrors.length > 0 ? JSON.stringify(stringErrors) : '',\n ancestry: notification.ancestry.join(''),\n duration: notification.duration,\n description: notification.description\n }));\n}\n", "/**\n * Defines the log verbosity levels for reporters and test execution.\n *\n * @remarks\n * Each level represents the minimum severity of messages that should be\n * captured or displayed. Higher levels include all messages from lower levels.\n *\n * @example\n * ```ts\n * if (log.level >= LogLevel.Warn) {\n * console.warn(log.message);\n * }\n * ```\n *\n * @since 1.0.0\n */\n\nexport enum LogLevel {\n Silent = 0,\n Error = 1,\n Warn = 2,\n Info = 3,\n Debug = 4\n}\n\n/**\n * Defines the types of messages emitted during test execution.\n *\n * @remarks\n * These message types are used internally by reporters, runners,\n * and event emitters to categorize test events. Each type corresponds\n * to a specific stage or element of the test lifecycle.\n *\n * @example\n * ```ts\n * if (message.type === MessageType.Test) {\n * console.log('Test event received');\n * }\n * ```\n *\n * @since 1.0.0\n */\n\nexport const enum MessageType {\n Test = 1,\n Describe = 2,\n EndSuite = 3,\n StartSuite = 4\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { HookModel } from './hook.model';\nimport type { TestModel } from '@shared/models/test.model';\nimport type { ContextType } from '@remotex-labs/xjet-expect';\nimport type { ContextInterface } from '@shared/models/interfaces/describe-model.interface';\nimport type { DescribeHooksInterface } from '@shared/models/interfaces/describe-model.interface';\nimport type { DescribeOptionsInterface } from '@shared/models/interfaces/describe-model.interface';\n\n/**\n * Imports\n */\n\nimport { MessageType } from '@messages/constants/report.constant';\nimport { emitEvent, emitStatus } from '@shared/services/emit.service';\nimport { HookType } from '@shared/models/constants/hook.model.constants';\n\n/**\n * Represents a test suite container that manages test execution flow and hierarchy\n *\n * @template T - Context type for test execution\n * @param description - The description of the test suite\n * @param describeFlags - Configuration options for the test suite\n * @returns A new DescribeModel instance that can contain tests and nested suites\n *\n * @remarks\n * The DescribeModel manages the execution lifecycle of tests, including\n * - Maintaining parent-child relationships between test suites\n * - Executing hooks in the correct order (beforeAll, beforeEach, afterEach, afterAll)\n * - Tracking test execution status and reporting results\n * - Supporting test filtering with skip/only options\n *\n * @example\n * ```ts\n * const rootSuite = new DescribeModel('Root suite');\n * const testCase = new TestModel('should work', () => {\n * expect(true).toBe(true);\n * });\n * rootSuite.addTest(testCase);\n * await rootSuite.run({});\n * ```\n *\n * @see TestModel\n * @see HookModel\n * @see DescribeHooksInterface\n *\n * @since 1.0.0\n */\n\nexport class DescribeModel {\n /**\n * Array containing the hierarchical path of parent describe blocks for this test suite\n *\n * @since 1.0.0\n */\n\n readonly ancestry: string[] = [];\n\n /**\n * Collection of test cases directly contained within this test suite\n *\n * @internal\n * @since 1.0.0\n */\n\n readonly testsStack: TestModel[] = [];\n\n /**\n * Collection of nested test suites within this suite\n *\n * @internal\n * @since 1.0.0\n */\n\n readonly describesStack: DescribeModel[] = [];\n\n /**\n * Timestamp when the test suite execution started\n *\n * @default 0\n * @internal\n * @since 1.0.0\n */\n\n private startTime = 0;\n\n /**\n * Collection of lifecycle hooks for this test suite\n *\n * @internal\n * @since 1.0.0\n */\n\n private readonly hooks: DescribeHooksInterface = {\n afterAll: [],\n afterEach: [],\n beforeAll: [],\n beforeEach: []\n };\n\n /**\n * Creates a new test suite with the specified description and options\n *\n * @param description - Human-readable description of the test suite\n * @param describeOptions - Configuration options to control test suite execution\n *\n * @since 1.0.0\n */\n\n constructor(\n readonly description: string = '',\n private readonly describeOptions: DescribeOptionsInterface = { skip: false, only: false }\n ) {\n }\n\n /**\n * Retrieves the execution configuration options for this test suite\n *\n * @returns Test suite configuration options\n *\n * @since 1.0.0\n */\n\n get options(): DescribeOptionsInterface {\n return this.describeOptions;\n }\n\n /**\n * Gets all tests in this suite, including tests from nested suites\n *\n * @returns Flattened array of all tests in this suite and its children\n *\n * @remarks\n * Recursively collects and flattens all test cases from this suite and any nested suites\n *\n * @since 1.0.0\n */\n\n get tests(): TestModel[] {\n // Use flatMap for cleaner code and better performance\n return [\n ...this.testsStack,\n ...this.describesStack.flatMap(child => child.tests)\n ];\n }\n\n /**\n * Registers a hook function to be executed at a specific point in the test lifecycle\n *\n * @param type - The lifecycle point at which to execute the hook\n * @param hook - The hook function model to register\n *\n * @throws Error - If an invalid hook type is provided\n *\n * @since 1.0.0\n */\n\n addHook(type: HookType, hook: HookModel): void {\n const hookArray = this.hooks[type];\n if (!hookArray) {\n throw new Error(`Invalid hook type: ${ type }`);\n }\n\n hookArray.push(hook);\n }\n\n /**\n * Adds a test case to this test suite\n *\n * @param test - The test model to add to the suite\n *\n * @remarks\n * When adding a test, this method automatically:\n * - Updates the test's ancestry to include this suite\n * - Propagates execution options (skip/only) from the suite to the test\n *\n * @since 1.0.0\n */\n\n addTest(test: TestModel): void {\n if (!test) return;\n\n test.setAncestry(this.ancestry);\n if (this.description) test.setAncestry([ this.description ]);\n test.applyExecutionFlags(this.options.skip, this.options.only);\n this.testsStack.push(test);\n }\n\n /**\n * Adds a nested test describe to this test describe\n *\n * @param describe - The child test describe to add\n *\n * @remarks\n * When adding nested describe, this method automatically:\n * - Sets up the parent-child relationship\n * - Propagates execution options and ancestry information from parent to child\n *\n * @since 1.0.0\n */\n\n addDescribe(describe: DescribeModel): void {\n if (!describe) return;\n\n describe.inheritFromParentDescribe(this);\n this.describesStack.push(describe);\n }\n\n /**\n * Executes the test suite and all contained tests\n *\n * @param context - The test execution context containing shared state\n * @returns Promise that resolves when all tests in the suite complete\n *\n * @remarks\n * Execution follows this order:\n * 1. Check if the suite is marked as skipped\n * 2. Execute all beforeAll hooks\n * 3. Run all tests in this suite\n * 4. Run all nested test suites\n * 5. Execute all afterAll hooks\n * If any step fails, the entire suite is marked as failed\n *\n * @example\n * ```ts\n * const suite = new DescribeModel('My test suite');\n * const context = createTestContext();\n * await suite.run(context);\n * ```\n *\n * @since 1.0.0\n */\n\n async run(context: ContextType<ContextInterface>): Promise<void> {\n this.startTime = Date.now();\n this.notifyDescribeStatus(this.options.skip);\n const afterAllErrorsEmpty = !context.afterAllErrors?.length;\n const beforeAllErrorsEmpty = !context.beforeAllErrors?.length;\n\n try {\n if (!context.beforeAllErrors?.length)\n await this.executeHooks(HookType.BEFORE_ALL, context);\n\n for (const test of this.shuffleTests(this.testsStack)) {\n if(context.hasError) return;\n await test.run(context, this.executeHooks.bind(this));\n }\n\n for (const describe of this.describesStack) {\n if(context.hasError) return;\n await describe.run(context);\n }\n\n await this.executeHooks(HookType.AFTER_ALL, context);\n\n if (context.afterAllErrors?.length) this.notifyDescribeFailure(context.afterAllErrors);\n else this.notifyDescribeAction();\n } catch (error) {\n this.notifyDescribeFailure([ error, ...context.afterAllErrors ]);\n if(globalThis.__XJET?.runtime.bail) {\n context.hasError = true;\n }\n } finally {\n if (afterAllErrorsEmpty) context.afterAllErrors = [];\n if (beforeAllErrorsEmpty) context.beforeAllErrors = [];\n }\n }\n\n /**\n * Inherits properties from a parent test suite\n *\n * @param parent - The parent test describe to inherit from\n *\n * @remarks\n * This method performs the following inheritance operations:\n * - Adds parent's ancestry chain to this suite's ancestry\n * - Propagates the 'skip' flag (if parent is skipped, child is skipped)\n * - Propagates the 'only' flag if the parent has it set\n *\n * @since 1.0.0\n */\n\n inheritFromParentDescribe(parent: DescribeModel): void {\n this.ancestry.push(...parent.ancestry);\n this.hooks.beforeEach = [ ...parent.hooks.beforeEach, ...this.hooks.beforeEach ];\n this.hooks.afterEach = [ ...parent.hooks.afterEach, ...this.hooks.afterEach ];\n\n if (parent.description)\n this.ancestry.push(parent.description);\n\n if (parent.options.skip) {\n this.describeOptions.skip = true;\n }\n\n if (parent.options.only) {\n this.describeOptions.only = true;\n }\n }\n\n /**\n * Executes all hooks of the specified type in sequence\n *\n * @param type - The lifecycle hook type to execute\n * @param context - The test execution context\n *\n * @throws Error - When a beforeEach or afterEach hook fails\n *\n * @remarks\n * Errors in beforeAll hooks are collected but don't immediately abort execution.\n * Errors in afterAll hooks are collected for reporting.\n * Errors in beforeEach/afterEach hooks cause immediate test failure.\n *\n * @internal\n * @since 1.0.0\n */\n\n private async executeHooks(type: HookType, context: ContextType<ContextInterface>): Promise<void> {\n if (this.options.skip) return;\n context.beforeAllErrors = context.beforeAllErrors || [];\n context.afterAllErrors = context.afterAllErrors || [];\n\n for (const hook of this.hooks[type]) {\n try {\n await hook.run(context);\n } catch (error) {\n await this.handleHookError(type, error, context);\n }\n }\n }\n\n /**\n * Handles errors that occur during hook execution\n *\n * @param type - The type of hook where the error occurred\n * @param error - The error that was thrown\n * @param context - The test execution context\n *\n * @throws Error - When the error occurs in a beforeEach or afterEach hook\n *\n * @remarks\n * Error handling differs by hook type:\n * - beforeAll: Error is collected but execution continues\n * - afterAll: Error is collected for reporting\n * - beforeEach/afterEach: Error is immediately thrown to fail the test\n *\n * @internal\n *\n * @since 1.0.0\n */\n\n private async handleHookError(type: HookType, error: unknown, context: ContextType<ContextInterface>): Promise<void> {\n if (type === HookType.BEFORE_ALL) {\n context.beforeAllErrors.push(error);\n } else if (type === HookType.AFTER_ALL) {\n context.afterAllErrors.push(error);\n } else {\n throw error;\n }\n }\n\n /**\n * Calculates the execution duration of the test suite in milliseconds\n *\n * @returns Duration in milliseconds since the test started, or 0 if not started\n *\n * @remarks\n * Returns the elapsed time between when the suite started execution and the current time\n * If the suite hasn't started (startTime is 0), returns 0 instead\n *\n * @internal\n * @since 1.0.0\n */\n\n private getExecutionDuration(): number {\n if (this.startTime === 0)\n return 0;\n\n return Date.now() - this.startTime;\n }\n\n private notifyDescribeStatus(skip: boolean = false): void {\n emitStatus(MessageType.Describe, {\n skipped: skip,\n ancestry: this.ancestry,\n description: this.description\n });\n }\n\n private notifyDescribeAction(errors: Array<unknown> = []): void {\n emitEvent(MessageType.Describe, {\n errors: <Array<Error>> errors,\n ancestry: this.ancestry,\n description: this.description,\n duration: this.getExecutionDuration()\n });\n }\n\n /**\n * Reports test suite failure with associated errors\n *\n * @param errors - Collection of errors that caused the test suite to fail\n *\n * @remarks\n * Skips reporting if no errors are provided\n * Uses notifyDescribeAction to emit a failure event with the error details\n *\n * @internal\n * @since 1.0.0\n */\n\n private notifyDescribeFailure(errors: Array<unknown>): void {\n if (!errors?.length) return;\n\n this.notifyDescribeAction(errors);\n }\n\n /**\n * Randomizes the order of tests in an array using the Fisher-Yates shuffle algorithm\n *\n * @param testsToShuffle - Array of test models to be randomly reordered\n * @returns The same array with elements potentially reordered in a random sequence\n *\n * @remarks\n * The shuffling only occurs if the global randomization flag is enabled\n * (accessed via globalThis.__XJET?.runtime.randomize) and the array has more\n * than one element. The algorithm used is Fisher-Yates shuffle, which ensures\n * each permutation has equal probability.\n *\n * @example\n * ```ts\n * const tests = [new TestModel('test1'), new TestModel('test2')];\n * const randomizedTests = this.shuffleTests(tests);\n * // The order of tests may be different from the original if randomization is enabled\n * ```\n *\n * @internal\n * @since 1.0.0\n */\n\n private shuffleTests(testsToShuffle: Array<TestModel>): Array<TestModel> {\n const randomize = globalThis.__XJET?.runtime.randomize ?? false;\n if (!randomize || testsToShuffle.length <= 1) return testsToShuffle;\n const length = testsToShuffle.length;\n\n // Start from the last element and swap with a random element\n // before the current position (including itself)\n for (let i = length - 1; i > 0; i--) {\n // Generate a random index from 0 to i (inclusive)\n const j = Math.floor(Math.random() * (i + 1));\n\n // Swap elements at indices i and j\n // Use destructuring assignment for a clean swap without a temp variable\n [ testsToShuffle[i], testsToShuffle[j] ] = [ testsToShuffle[j], testsToShuffle[i] ];\n }\n\n return testsToShuffle;\n }\n}\n", "/**\n * A base error class that extends the standard Error class with enhanced JSON serialization and location tracking\n *\n * @param message - The error message describing what went wrong\n * @param location - The precise source code location where the error occurred\n * @returns The constructed ExecutionError instance\n *\n * @remarks\n * Serves as a foundation for custom error types in the application.\n * It enhances the native Error object by adding JSON serialization capabilities\n * and source code location information, allowing for better error reporting,\n * debugging, and troubleshooting. The location tracking feature helps pinpoint\n * exactly where in the codebase an error originated.\n *\n * @example\n * ```ts\n * // Creating a basic execution error with location information\n * const error = new ExecutionError(\n * 'Failed to process data',\n * { line: 42, column: 10 }\n * );\n *\n * // The error can be thrown or used in promise rejection\n * throw error;\n * ```\n *\n * @see InvocationLocationType\n *\n * @since 1.0.0\n */\n\nexport class ExecutionError extends Error {\n\n /**\n * Creates a new ExecutionError instance with the specified error message and source code location\n *\n * @param message - The error message describing what went wrong\n *\n * @remarks\n * This constructor initializes both the standard Error message property and the location\n * information that helps pinpoint exactly where in the codebase the error originated. The\n * location parameter follows the InvocationLocationType structure, typically containing\n * line and column information.\n *\n * @example\n * ```ts\n * const error = new ExecutionError(\n * 'Failed to process input data',\n * { line: 42, column: 8 }\n * );\n * ```\n *\n * @since 1.0.0\n */\n\n constructor(message: string) {\n super(message);\n\n // Assign the name of the error\n this.name = 'xJetExecutionError';\n }\n\n /**\n * Converts the error instance to a plain JavaScript object for JSON serialization.\n *\n * @returns A plain object containing all properties of the error.\n *\n * @remarks\n * This method enhances error serialization by ensuring all properties from the error\n * instance are properly included in the resulting JSON representation. The standard\n * `JSON.stringify()` method doesn't properly serialize Error objects by default, as\n * their properties are typically not enumerable.\n *\n * @example\n * ```ts\n * const error = new ExecutionError('Something went wrong');\n * error.code = 'ERR_INVALID_INPUT';\n *\n * // Convert to JSON\n * const serialized = JSON.stringify(error);\n * // Result includes all properties: message, name, stack, code, etc.\n * ```\n *\n * @since 1.0.0\n */\n\n toJSON(): Record<string, unknown> {\n const json: Record<string, unknown> = {};\n\n for (const key of Object.keys(this)) {\n const value = this[key as keyof this];\n if(value) json[key] = value;\n }\n\n json.name = this.name;\n json.stack = this.stack;\n json.message = this.message;\n\n return json;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { TestModel } from '@shared/models/test.model';\nimport type { ContextType, FunctionType } from '@remotex-labs/xjet-expect';\nimport type { ContextInterface, DescribeOptionsInterface } from '@shared/models/interfaces/describe-model.interface';\n\n/**\n * Imports\n */\n\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { emitStatus } from '@shared/services/emit.service';\nimport { encodeErrorSchema } from '@packets/packets.module';\nimport { DescribeModel } from '@shared/models/describe.model';\nimport { ExecutionError } from '@shared/errors/execution.error';\nimport { MessageType } from '@messages/constants/report.constant';\n\n/**\n * Manages the state of test suites within the testing framework, tracking the hierarchy of describe blocks and test cases.\n * Implemented as a singleton to ensure a single source of truth for the test suite structure.\n *\n * @template TestModel - The model type representing individual test cases\n * @template FunctionType - The function type for describe block implementations\n * @template DescribeModel - The model type representing test suite describe blocks\n * @template DescribeOptionsInterface - Configuration options for describe blocks\n *\n * @throws Error - If you attempt to instantiate this class directly instead of using getInstance()\n *\n * @remarks\n * The singleton pattern ensures that all test registration operations work with the same\n * state instance, properly maintaining the hierarchical structure of tests.\n * Use the static getInstance() method to access the singleton instance.\n *\n * @example\n * ```ts\n * // Get the singleton instance\n * const suiteState = SuiteState.getInstance();\n *\n * // Add a describe block\n * suiteState.addDescribe('My test suite', () => {\n * // Test suite implementation\n * }, { only: true });\n *\n * // Add a test case to the current describe block\n * suiteState.addTest(new TestModel('should work', () => {}, { skip: false }));\n * ```\n *\n * @see TestModel\n * @see DescribeModel\n *\n * @since 1.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class SuiteState {\n /**\n * Tracks whether any test or describe block has the 'only' flag set\n *\n * @since 1.0.0\n */\n\n private onlyMode = false;\n\n /**\n * Reference to the currently active describe block in the test hierarchy\n *\n * @see DescribeModel\n * @since 1.0.0\n */\n\n private currentDescribe: DescribeModel;\n\n /**\n * Reference to the test currently being defined or executed\n *\n * @see TestModel\n * @since 1.0.0\n */\n\n private currentTest?: TestModel;\n\n /**\n * Suite has at least one test\n * @since 1.0.0\n */\n\n private hasTests = false;\n\n /**\n * The top-level describe block that contains all tests and nested describe blocks\n *\n * @see DescribeModel\n * @since 1.0.0\n */\n\n private readonly rootDescribe: DescribeModel;\n\n /**\n * Array of regular expressions used for filtering test paths\n *\n * @remarks\n * This array stores regular expressions created from filter strings specified in runtime configuration.\n * Used to determine which tests should be executed when filtering is enabled.\n *\n * @see SuiteState.matchesFilter - Method that uses these regex patterns for test filtering\n * @since 1.0.0\n */\n\n private readonly filterRegexChain: Array<RegExp> = [];\n\n /**\n * Creates a new instance of the class with a root describe block\n *\n * @internal\n * @since 1.0.0\n */\n\n constructor() {\n this.rootDescribe = new DescribeModel();\n this.currentDescribe = this.rootDescribe;\n\n if (Array.isArray(__XJET?.runtime.filter) && __XJET.runtime.filter.length > 0) {\n this.onlyMode = true;\n this.filterRegexChain = __XJET.runtime.filter.map(\n (part: string) => new RegExp(`^${ part }$`)\n );\n }\n }\n\n /**\n * Checks if a test path matches the provided regular expression filter patterns\n *\n * This method compares a test's full path (including ancestry and description) against one or more\n * regular expression patterns to determine if the test should be included in execution.\n *\n * @param path - Array of path segments representing test ancestry and description\n * @param filter - Array of RegExp objects to test against the path\n * @returns Boolean indicating whether the path matches the filter patterns\n *\n * @throws Error - When invalid regular expressions are provided\n *\n * @remarks\n * The method aligns the filter from the end of the path, allowing partial matching of nested test structures.\n * This is particularly useful for selecting specific test cases within a larger test hierarchy.\n *\n * @example\n * ```ts\n * // Match tests with description containing \"login\"\n * const matches = SuiteState.matchesFilter(\n * ['Auth', 'User', 'should handle login correctly'],\n * [/login/i]\n * );\n * // Returns: true\n *\n * // Match specific test path structure\n * const matches = SuiteState.matchesFilter(\n * ['API', 'GET', 'should return 200 status'],\n * [/API/, /GET/, /status/]\n * );\n * // Returns: true\n * ```\n *\n * @see filterChain - String-based alternative for exact matching\n * @see addTest - Method that uses matchesFilter to determine which tests to run\n *\n * @since 1.0.0\n */\n\n static matchesFilter(path: string[], filter: RegExp[]): boolean {\n if (filter.length > path.length) return false;\n\n // Align from the end of the path\n const offset = path.length - filter.length;\n\n return filter.every((re, i) => re.test(path[offset + i]));\n }\n\n /**\n * Indicates whether the test suite is running in \"only\" mode\n *\n * @returns True if only specifically marked tests should run\n *\n * @since 1.0.0\n */\n\n get isOnlyMode(): boolean {\n return this.onlyMode;\n }\n\n /**\n * Gets the root describe block of the test suite\n *\n * @returns The top-level describe block\n *\n * @see DescribeModel\n * @since 1.0.0\n */\n\n get root(): DescribeModel {\n return this.rootDescribe;\n }\n\n /**\n * Gets the current describe block being defined\n *\n * @returns The active describe block\n *\n * @see DescribeModel\n * @since 1.0.0\n */\n\n get describe(): DescribeModel {\n return this.currentDescribe;\n }\n\n /**\n * Gets the test currently being defined or executed\n *\n * @returns The current test or null if no test is active\n *\n * @see TestModel\n * @since 1.0.0\n */\n\n get test(): TestModel | undefined {\n return this.currentTest;\n }\n\n /**\n * Sets the current test being defined or executed\n *\n * @param test - The test to set as current\n *\n * @see TestModel\n * @since 1.0.0\n */\n\n set test(test: TestModel | undefined) {\n this.currentTest = test;\n }\n\n /**\n * Executes the entire test suite from the root describe block\n *\n * @param context - The execution context containing runtime information\n *\n * @throws Error - When test execution fails, the error is encoded and dispatched\n *\n * @remarks\n * This method initiates the test execution flow by calling run() on the root describe block\n * and emits an END status notification when all tests complete successfully. If an error\n * occurs during execution, it's captured, encoded, and dispatched through the error schema.\n *\n * @example\n * ```ts\n * const suiteState = SuiteState.getInstance();\n * await suiteState.run({\n * timeout: 5000,\n * currentPath: '/tests',\n * skipAfterFailure: true\n * });\n * ```\n *\n * @see emitStatus\n * @see DescribeModel\n *\n * @since 1.0.0\n */\n\n async run(context: ContextType<ContextInterface>): Promise<void> {\n try {\n const time = Date.now();\n emitStatus(MessageType.StartSuite);\n if (!this.hasTests)\n throw new ExecutionError('Your test suite must contain at least one test');\n\n await this.root.run(context);\n emitStatus(MessageType.EndSuite, { duration: Date.now() - time });\n } catch (e) {\n dispatch(\n encodeErrorSchema(<Error>e, __XJET.runtime.suiteId, __XJET.runtime.runnerId)\n );\n }\n }\n\n /**\n * Adds a new describe block to the test suite hierarchy\n *\n * @param description - The textual description of the describe block\n * @param describeFn - The function containing the tests and nested describes\n * @param flags - Configuration options for the describe block\n * @param describeArgs - Arguments to pass to the describe function\n *\n * @throws Error - If the describe function throws any exceptions\n *\n * @remarks\n * This method temporarily changes the current describe context while executing\n * the describeFn, then restores it afterward, ensuring proper nesting of test blocks.\n * If the 'only' flag is set, it enables only-mode for the entire test suite.\n *\n * @example\n * ```ts\n * suiteState.addDescribe(\n * 'my test group',\n * () => {\n * // test definitions here\n * },\n * { only: true }\n * );\n * ```\n *\n * @see FunctionType\n * @see DescribeModel\n * @see DescribeOptionsInterface\n *\n * @since 1.0.0\n */\n\n addDescribe(description: string, describeFn: FunctionType, flags: DescribeOptionsInterface = {}, describeArgs: Array<unknown> = []): void {\n const options = { skip: false, only: false, ...flags };\n if (options.only) {\n this.onlyMode = true;\n }\n\n if (this.filterRegexChain.length > 0) {\n const fullPath = [\n ...this.currentDescribe.ancestry,\n this.currentDescribe.description,\n description\n ];\n\n if (SuiteState.matchesFilter(fullPath, this.filterRegexChain)) {\n options.only = true;\n }\n }\n\n const newDescribe = new DescribeModel(description, options);\n this.currentDescribe.addDescribe(newDescribe);\n const previousDescribe = this.currentDescribe;\n this.currentDescribe = newDescribe;\n\n try {\n describeFn.apply({}, describeArgs);\n } finally {\n this.currentDescribe = previousDescribe;\n }\n }\n\n /**\n * Adds a test to the current describe block\n *\n * @param test - The test model to add\n *\n * @remarks\n * If the test has the 'only' option set, it enables only-mode for the entire test suite.\n *\n * @see TestModel\n * @since 1.0.0\n */\n\n addTest(test: TestModel): void {\n // Mark the suite as having at least one test\n this.hasTests = true;\n\n if (test.options.only) this.onlyMode = true;\n this.currentDescribe.addTest(test);\n\n if (this.filterRegexChain.length > 0) {\n const fullPath = [ ...test.ancestry, test.description ];\n\n if (SuiteState.matchesFilter(fullPath, this.filterRegexChain)) {\n test.options.only = true;\n }\n }\n }\n}\n", "/**\n * Export interfaces\n */\n\nexport type * from '@components/interfaces/parse-component.interface';\n\n/**\n * Import will remove at compile time\n */\n\nimport type { ParsedStackTraceInterface, StackFrameInterface } from '@components/interfaces/parse-component.interface';\n\n/**\n * Regular expression patterns for different JavaScript engines' stack traces\n *\n * @since 2.1.0\n */\n\nconst PATTERNS = {\n V8: {\n GLOBAL: /at\\s(.*):(\\d+):(\\d+)/,\n STANDARD: /at\\s(.*?)\\((?:(.+?):(\\d+):(\\d+)|(native))\\)/,\n EVAL: /^at\\s(.+?)\\s\\(eval\\sat\\s(.+?)\\s?\\((.*):(\\d+):(\\d+)\\),\\s(.+?):(\\d+):(\\d+)\\)$/\n },\n SPIDERMONKEY: {\n EVAL: /^(.*)@(.+?):(\\d+):(\\d+),\\s(.+?)@(.+?):(\\d+):(\\d+)$/,\n STANDARD: /^(.*)@(.*?)(?:(\\[native code\\])|:(\\d+):(\\d+))$/\n },\n JAVASCRIPT_CORE: {\n STANDARD: /^(?:(global|eval)\\s)?(.*)@(.*?)(?::(\\d+)(?::(\\d+))?)?$/\n }\n};\n\n/**\n * Enumeration of JavaScript engines that can be detected from stack traces\n *\n * @since 2.1.0\n */\n\nexport const enum JSEngines {\n V8,\n SPIDERMONKEY,\n JAVASCRIPT_CORE,\n UNKNOWN\n}\n\n/**\n * Detects the JavaScript engine based on the format of a stack trace line\n *\n * @param stack - The stack trace to analyze\n * @returns The identified JavaScript engine type\n *\n * @example\n * ```ts\n * const engine = detectJSEngine(\"at functionName (/path/to/file.js:10:15)\");\n * if (engine === JSEngines.V8) {\n * // Handle V8 specific logic\n * }\n * ```\n *\n * @since 2.1.0\n */\n\nexport function detectJSEngine(stack: string): JSEngines {\n if (stack.startsWith(' at ') || stack.startsWith('at '))\n return JSEngines.V8;\n\n if (stack.includes('@'))\n return /(?:global|eval) code@/.test(stack)\n ? JSEngines.JAVASCRIPT_CORE : JSEngines.SPIDERMONKEY;\n\n return JSEngines.UNKNOWN;\n}\n\n/**\n * Normalizes file paths from various formats to a standard format\n *\n * @param filePath - The file path to normalize, which may include protocol prefixes\n * @returns A normalized file path with consistent separators and without protocol prefixes\n *\n * @remarks\n * Handles both Windows and Unix-style paths, as well as file:// protocol URLs.\n * Converts all backslashes to forward slashes for consistency.\n *\n * @example\n * ```ts\n * // Windows file URL to a normal path\n * normalizePath(\"file:///C:/path/to/file.js\"); // \"C:/path/to/file.js\"\n *\n * // Unix file URL to a normal path\n * normalizePath(\"file:///path/to/file.js\"); // \"/path/to/file.js\"\n *\n * // Windows backslashes to forward slashes\n * normalizePath(\"C:\\\\path\\\\to\\\\file.js\"); // \"C:/path/to/file.js\"\n * ```\n *\n * @since 2.1.0\n */\n\nexport function normalizePath(filePath: string): string {\n // Handle file:// protocol URLs\n if (filePath.startsWith('file://')) {\n // Handle Windows file:/// format\n if (filePath.startsWith('file:///') && /^file:\\/\\/\\/[A-Za-z]:/.test(filePath)) {\n // Windows absolute path: file:///C:/path/to/file.js\n return filePath.substring(8);\n }\n\n // Handle *nix file:// format\n return filePath.substring(7);\n }\n\n // Handle Windows-style paths with backward slashes\n filePath = filePath.replace(/\\\\/g, '/');\n\n return filePath;\n}\n\n/**\n * Creates a default stack frame object with initial values\n *\n * @param source - The original source line from the stack trace\n * @returns A new StackFrameInterface object with default null values\n *\n * @see ParsedStackTraceInterface\n * @see StackFrameInterface\n *\n * @since 2.1.0\n */\n\nexport function createDefaultFrame(source: string): StackFrameInterface {\n return {\n source,\n eval: false,\n async: false,\n native: false,\n constructor: false\n };\n}\n\n/**\n * Safely parses a string value to an integer, handling undefined and null cases\n *\n * @param value - The string value to parse\n * @returns The parsed integer or null if the input is undefined/null\n *\n * @example\n * ```ts\n * safeParseInt(\"42\"); // 42\n * safeParseInt(undefined); // null\n * safeParseInt(null); // null\n * ```\n *\n * @since 2.1.0\n */\n\nexport function safeParseInt(value: string | undefined | null): number | undefined {\n return value && value.trim() !== '' ? parseInt(value, 10) : undefined;\n}\n\n/**\n * Parses a V8 JavaScript engine stack trace line into a structured StackFrameInterface object\n *\n * @param line - The stack trace line to parse\n * @returns A StackFrameInterface object containing the parsed information\n *\n * @remarks\n * Handles both standard V8 stack frames and eval-generated stack frames which\n * have a more complex structure with nested origin information.\n *\n * @example\n * ```ts\n * // Standard frame\n * parseV8StackLine(\"at functionName (/path/to/file.js:10:15)\");\n *\n * // Eval frame\n * parseV8StackLine(\"at eval (eval at evalFn (/source.js:5:10), <anonymous>:1:5)\");\n * ```\n *\n * @throws Error - If the line format doesn't match any known V8 pattern\n *\n * @see StackFrameInterface\n * @see createDefaultFrame\n *\n * @since 2.1.0\n */\n\nexport function parseV8StackLine(line: string): StackFrameInterface {\n const frame = createDefaultFrame(line);\n\n // Common flags that apply to all formats\n if (line.toLowerCase().includes('new')) frame.constructor = true;\n if (line.toLowerCase().includes('async')) frame.async = true;\n\n // Try to match against each pattern\n const evalMatch = line.match(PATTERNS.V8.EVAL);\n const globalMatch = line.match(PATTERNS.V8.GLOBAL);\n const standardMatch = !evalMatch && line.match(PATTERNS.V8.STANDARD);\n\n if (evalMatch) {\n // Handle eval format\n frame.eval = true;\n frame.functionName = evalMatch[1] || undefined;\n\n // Add eval origin information\n frame.evalOrigin = {\n line: safeParseInt(evalMatch[4]) ?? undefined,\n column: safeParseInt(evalMatch[5]) ?? undefined,\n fileName: evalMatch[3] ? normalizePath(evalMatch[3]) : undefined,\n functionName: evalMatch[2] || '<anonymous>'\n };\n\n // Position inside evaluated code\n frame.line = safeParseInt(evalMatch[7]) ?? undefined;\n frame.column = safeParseInt(evalMatch[8]) ?? undefined;\n frame.fileName = evalMatch[6] ? normalizePath(evalMatch[6]) : undefined;\n } else if (standardMatch) {\n // Handle standard format\n frame.functionName = standardMatch[1] ? standardMatch[1].trim() : undefined;\n\n if (standardMatch[5] === 'native') {\n frame.native = true;\n frame.fileName = '[native code]';\n } else {\n frame.line = safeParseInt(standardMatch[3]) ?? undefined;\n frame.column = safeParseInt(standardMatch[4]) ?? undefined;\n frame.fileName = standardMatch[2] ? normalizePath(standardMatch[2]) : undefined;\n if(frame.fileName?.includes('node:')) frame.native = true;\n }\n } else if (globalMatch) {\n frame.fileName = globalMatch[1] ? normalizePath(globalMatch[1]) : undefined;\n frame.line = safeParseInt(globalMatch[2]) ?? undefined;\n frame.column = safeParseInt(globalMatch[3]) ?? undefined;\n }\n\n return frame;\n}\n\n/**\n * Parses a SpiderMonkey JavaScript engine stack trace line into a structured StackFrameInterface object\n *\n * @param line - The stack trace line to parse\n * @returns A StackFrameInterface object containing the parsed information\n *\n * @remarks\n * Handles both standard SpiderMonkey stack frames and eval/Function-generated stack frames\n * which contain additional evaluation context information.\n *\n * @example\n * ```ts\n * // Standard frame\n * parseSpiderMonkeyStackLine(\"functionName@/path/to/file.js:10:15\");\n *\n * // Eval frame\n * parseSpiderMonkeyStackLine(\"evalFn@/source.js line 5 > eval:1:5\");\n * ```\n *\n * @see StackFrameInterface\n * @see createDefaultFrame\n *\n * @since 2.1.0\n */\n\nexport function parseSpiderMonkeyStackLine(line: string): StackFrameInterface {\n const frame = createDefaultFrame(line);\n\n // Check for eval/Function format\n const evalMatch = line.match(PATTERNS.SPIDERMONKEY.EVAL);\n if (evalMatch) {\n frame.eval = true;\n frame.functionName = evalMatch[1] ? evalMatch[1] : undefined;\n\n if (line.toLowerCase().includes('constructor'))\n frame.constructor = true;\n\n if (line.toLowerCase().includes('async'))\n frame.async = true;\n\n // Add eval origin information\n frame.evalOrigin = {\n line: safeParseInt(evalMatch[7]) ?? undefined,\n column: safeParseInt(evalMatch[8]) ?? undefined,\n fileName: normalizePath(evalMatch[6]),\n functionName: evalMatch[5] ? evalMatch[5] : undefined\n };\n\n // Position inside evaluated code\n frame.line = safeParseInt(evalMatch[3]) ?? undefined;\n frame.column = safeParseInt(evalMatch[4]) ?? undefined;\n\n return frame;\n }\n\n // Standard SpiderMonkey format\n const match = line.match(PATTERNS.SPIDERMONKEY.STANDARD);\n if (match) {\n frame.functionName = match[1] ? match[1] : undefined;\n frame.fileName = normalizePath(match[2]);\n\n if (match[3] === '[native code]') {\n frame.fileName = '[native code]';\n } else {\n frame.line = safeParseInt(match[4]) ?? undefined;\n frame.column = safeParseInt(match[5]) ?? undefined;\n }\n }\n\n return frame;\n}\n\n/**\n * Parses a JavaScriptCore engine stack trace line into a structured StackFrameInterface object\n *\n * @param line - The stack trace line to parse\n * @returns A StackFrameInterface object containing the parsed information\n *\n * @remarks\n * Handles both standard JavaScriptCore stack frames and eval-generated stack frames.\n * Special handling is provided for \"global code\" references and native code.\n *\n * @example\n * ```ts\n * // Standard frame\n * parseJavaScriptCoreStackLine(\"functionName@/path/to/file.js:10:15\");\n *\n * // Eval frame\n * parseJavaScriptCoreStackLine(\"eval code@\");\n * ```\n *\n * @see StackFrameInterface\n * @see createDefaultFrame\n *\n * @since 2.1.0\n */\n\nexport function parseJavaScriptCoreStackLine(line: string): StackFrameInterface {\n const frame = createDefaultFrame(line);\n\n // Standard JavaScriptCore format\n const match = line.match(PATTERNS.JAVASCRIPT_CORE.STANDARD);\n if (match) {\n frame.functionName = match[2];\n frame.eval = (match[1] === 'eval' || match[3] === 'eval');\n\n if (line.toLowerCase().includes('constructor'))\n frame.constructor = true;\n\n if (line.toLowerCase().includes('async'))\n frame.async = true;\n\n if (match[3] === '[native code]') {\n frame.native = true;\n frame.fileName = '[native code]';\n } else {\n frame.line = safeParseInt(match[4]) ?? undefined;\n frame.column = safeParseInt(match[5]) ?? undefined;\n frame.fileName = normalizePath(match[3]);\n }\n }\n\n return frame;\n}\n\n/**\n * Parses a stack trace line based on the detected JavaScript engine\n *\n * @param line - The stack trace line to parse\n * @param engine - The JavaScript engine type that generated the stack trace\n * @returns A StackFrameInterface object containing the parsed information\n *\n * @remarks\n * Delegates to the appropriate parsing function based on the JavaScript engine.\n * Defaults to V8 parsing if the engine is unknown.\n *\n * @example\n * ```ts\n * const engine = detectJSEngine(stackLine);\n * const frame = parseStackLine(stackLine, engine);\n * ```\n *\n * @see JSEngines\n * @see parseV8StackLine\n * @see parseSpiderMonkeyStackLine\n * @see parseJavaScriptCoreStackLine\n *\n * @since 2.1.0\n */\n\nexport function parseStackLine(line: string, engine: JSEngines): StackFrameInterface {\n switch (engine) {\n case JSEngines.SPIDERMONKEY:\n return parseSpiderMonkeyStackLine(line);\n case JSEngines.JAVASCRIPT_CORE:\n return parseJavaScriptCoreStackLine(line);\n case JSEngines.V8:\n default:\n return parseV8StackLine(line);\n }\n}\n\n/**\n * Extracts the stack frames from a full stack trace string, removing the error message line.\n *\n * @param stack - The full error stack string, possibly including the error message\n * @returns The stack trace starting from the first stack frame, or an empty string if no frames are found\n *\n * @remarks\n * This function scans the stack string for lines matching common stack frame formats,\n * including V8 (`at ...`) and SpiderMonkey/JavaScriptCore (`function@file:line:column`) patterns.\n * It returns only the portion of the stack that contains the frames, discarding the initial\n * error message or any non-stack lines.\n *\n * @example\n * ```ts\n * const stack = `\n * Error: Something went wrong\n * at doSomething (file.js:10:15)\n * at main (file.js:20:5)\n * `;\n *\n * console.log(getStackWithoutMessage(stack));\n * // Output:\n * // at doSomething (file.js:10:15)\n * // at main (file.js:20:5)\n * ```\n *\n * @since 4.0.1\n */\n\nexport function getStackWithoutMessage(stack: string): string {\n if (!stack) return '';\n\n const stackFramePattern = /^\\s*at .+$|^.+@.+:\\d+:\\d+$|^@.+:\\d+:\\d+$|^.+@\\[native code\\]$/;\n const lines = stack.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n if (stackFramePattern.test(lines[i])) {\n return lines.slice(i).join('\\n');\n }\n }\n\n return '';\n}\n\n/**\n * Parses a complete error stack trace into a structured format\n *\n * @param error - Error object or error message string to parse\n * @returns A ParsedStackTraceInterface object containing structured stack trace information\n *\n * @remarks\n * Automatically detects the JavaScript engine from the stack format.\n * Filters out redundant information like the error name/message line.\n * Handles both Error objects and string error messages.\n *\n * @example\n * ```ts\n * try {\n * throw new Error (\"Something went wrong\");\n * } catch (error) {\n * const parsedStack = parseErrorStack(error);\n * console.log(parsedStack.name); // \"Error\"\n * console.log(parsedStack.message); // \"Something went wrong\"\n * console.log(parsedStack.stack); // Array of StackFrameInterface objects\n * }\n * ```\n *\n * @see ParsedStackTraceInterface\n * @see StackFrameInterface\n * @see parseStackLine\n * @see detectJSEngine\n *\n * @since 2.1.0\n */\n\nexport function parseErrorStack(error: Error | string): ParsedStackTraceInterface {\n const errorObj = typeof error === 'string' ? { stack: error, message: error, name: '' } : error;\n const name = errorObj.name || 'Error';\n const stack = getStackWithoutMessage(errorObj.stack || '');\n const message = errorObj?.message || '';\n\n const engine = detectJSEngine(stack);\n const stackLines = stack.split('\\n')\n .map(line => line.trim())\n .filter(line => line.trim() !== '');\n\n return {\n name,\n message,\n stack: stackLines.map(line => parseStackLine(line, engine)),\n rawStack: stack\n };\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PacketInvocationInterface } from '@packets/interfaces/packet-schema.interface';\n\n/**\n * Imports\n */\n\nimport { parseErrorStack } from '@remotex-labs/xmap/parser.component';\n\n/**\n * Retrieves the location in the source code where this function was invoked.\n *\n * @param position - The stack frame index to inspect (default is 3). This allows skipping\n * internal frames to reach the actual caller.\n * @returns A {@link PacketInvocationInterface} containing `line`, `column`, and `source` file\n * of the invocation, or `undefined` if the location could not be determined.\n *\n * @remarks\n * This function generates a new `Error` to capture the stack trace, parses it using\n * {@link parseErrorStack}, and returns the requested frame as a structured object.\n * It is useful for logging or reporting the exact location of a call within test suites\n * or framework code.\n *\n * @see parseErrorStack\n * @see PacketInvocationInterface\n *\n * @since 1.0.0\n */\n\nexport function getInvocationLocation(position: number = 2): PacketInvocationInterface | undefined {\n const errorObject = parseErrorStack(new Error());\n const stack = errorObject.stack[position];\n\n if (stack?.line && stack?.column && stack?.fileName) {\n return {\n line: stack.line!,\n column: stack.column!,\n source: stack.fileName!\n };\n }\n\n return undefined;\n}\n\n/**\n * Returns a native-style stack trace string,\n * trimmed to start at the specified frame index.\n *\n * @remarks\n * The first line (error name/message) is preserved,\n * while the following lines are sliced starting from `position`.\n *\n * @param position - Index of the first stack frame to include.\n * Defaults to `2` to skip this helper and its caller.\n *\n * @returns A string identical in format to `Error.stack`,\n * or an empty string if the stack is unavailable.\n *\n * @example\n * ```ts\n * console.log(getTrimmedStackString(2));\n * ```\n *\n * @since 3.1.0\n */\n\nexport function getTrimmedStackString(position: number = 2): string {\n const err = new Error();\n if (!err.stack) return '';\n\n const lines = err.stack.split('\\n');\n const frames = lines.slice(position + 1);\n\n return frames.join('\\n');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { TestModel } from '@shared/models/test.model';\nimport type { DescribeModel } from '@shared/models/describe.model';\n\n/**\n * Imports\n */\n\nimport { serialize } from '@remotex-labs/xjet-expect';\nimport { encodePacket } from '@packets/packets.module';\nimport { SuiteState } from '@shared/states/suite.state';\nimport { inject } from '@symlinks/services/inject.service';\nimport { LogLevel } from '@messages/constants/report.constant';\nimport { getInvocationLocation } from '@components/location.component';\nimport { PacketKind } from '@packets/constants/packet-schema.constants';\n\n/**\n * Creates a logging function that formats and dispatches log messages with timestamps\n *\n * @template T - Console method type that determines the log level\n * @param type - The type of console method (log, info, warn, error) to create a handler for\n * @returns A function that accepts any number of arguments, formats them, and dispatches a log event\n *\n * @throws TypeError - When invalid arguments are provided to the returned function\n *\n * @remarks\n * This function acts as a factory for creating specialized logging handlers. Each handler:\n * - Timestamps the log entry with ISO format\n * - Formats all arguments into string representations\n * - Dispatches the log event with the appropriate log level\n * - Maintains a consistent format for all log messages\n *\n * @example\n * ```ts\n * const logInfo = createLogHandler('info');\n * logInfo('User', user.id, 'logged in successfully');\n * // Dispatches a log event with level: 'INFO', formatted arguments, and timestamp\n * ```\n *\n * @see formatValue\n * @see dispatch\n * @see SchemaType\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport function createLogHandler(type: keyof typeof LogLevel) {\n return function (...args: unknown[]): void {\n let parent: TestModel | DescribeModel | undefined = inject(SuiteState).test;\n if (!parent) {\n parent = inject(SuiteState).describe;\n }\n\n const context = [ ...parent?.ancestry ?? [], parent?.description ].join(',');\n\n // Format arguments for the description\n const formattedArgs = args.map((data: unknown) => serialize(data).join('\\n')).join(' ');\n const location = getInvocationLocation();\n\n // Dispatch log event\n dispatch(encodePacket(PacketKind.Log, {\n level: LogLevel[type],\n message: formattedArgs,\n ancestry: context ?? '',\n invocation: location\n }));\n };\n}\n\n/**\n * Standard log level function for general purpose logging\n *\n * @see createLogHandler\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport const log = createLogHandler('Info');\n\n/**\n * Informational log function for highlighting noteworthy application events\n *\n * @see createLogHandler\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport const info = createLogHandler('Info');\n\n/**\n * Warning log function for potential issues that aren't errors\n *\n * @see createLogHandler\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport const warn = createLogHandler('Warn');\n\n/**\n * Error log function for reporting application errors and exceptions\n *\n * @see createLogHandler\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport const error = createLogHandler('Error');\n\n/**\n * Debug log function for detailed diagnostic information\n *\n * @see createLogHandler\n * @see LogLevel\n *\n * @since 1.0.0\n */\n\nexport const debug = createLogHandler('Debug');\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConstructorLikeType, FunctionLikeType, FunctionType } from '@remotex-labs/xjet-expect';\nimport type { ConstructorKeysType, KeysExtendingConstructorType } from '@shared/mock/interfaces/spy-mock.interface';\n\n/**\n * Imports\n */\n\nimport { MockState } from '@shared/states/mock.state';\nimport { ExecutionError } from '@shared/errors/execution.error';\n\n/**\n * Intercepts and mocks the property descriptor of a specified property on a target object.\n *\n * @template Target - The target object type.\n * @template Key - The key of the property to be mocked.\n *\n * @param target - The object whose property descriptor is being intercepted and mocked.\n * @param key - The property key on the target object to spy on.\n * @return A `MockState` instance that provides control over the mocked property and its interactions.\n *\n * @remarks\n * This function replaces the property's getter and setter to allow interception and testing of their behavior.\n * A `MockState` instance is returned to control and observes mocked behavior.\n *\n * @since 1.0.0\n */\n\nexport function spyOnDescriptorProperty<Target, Key extends keyof Target>(target: Target, key: Key): MockState<Target[Key], []> {\n const original = target[key];\n const originalDescriptor = Object.getOwnPropertyDescriptor(target, key) || {};\n const mockInstance = new MockState(() => original, () => {\n target[key] = originalDescriptor.value;\n Object.defineProperty(target, key, originalDescriptor);\n }, 'xJet.spyOn()');\n\n MockState.mocks.push(mockInstance);\n Object.defineProperty(target, key, {\n get() {\n return mockInstance.apply(this, []);\n },\n set(value: unknown) {\n mockInstance.mockImplementation(() => <Target[Key]> value);\n\n return mockInstance.apply(this, [ value ]);\n }\n });\n\n return mockInstance;\n}\n\n/**\n * Creates a spy on a specified static method or static property of a target class (not a class instance).\n * Useful for mocking behavior during testing.\n *\n * @template Target - The type of the target class.\n * @template Key - The static method or static property key on the target object to spy on.\n *\n * @param target - The object on which to spy.\n * @param key - The key of the method or property of the target to spy on.\n * @returns If the spied-on property is a function, returns a `MockState` object for the function,\n * allowing tracking of calls and modifying the return value or behavior.\n * Otherwise, returns a `MockState` object for the property, enabling tracking and manipulation of its value.\n *\n * @throws Error Throws an error if the `target` is a primitive value.\n * @throws Error Throws an error if `key` is null or undefined.\n * @throws Error Throws an error if the specified property does not exist on the target object.\n *\n * @remarks\n * This function is commonly used in testing environments to replace or monitor functionality without\n * altering the actual logic in the source code. It provides fine-grained control over target behavior.\n *\n * @example\n * ```ts\n * class ClassTest {\n * static name: string = 'ClassTest';\n *\n * static x(param: string) {\n * console.log(`original static x ${ param }`);\n * }\n * }\n *\n * const spy1 = xJet.spyOn(ClassTest, 'name');\n * const spy2 = xJet.spyOn(ClassTest, 'x');\n *\n * spy1.mockReturnValueOnce('Mock name');\n * spy2.mockImplementationOnce((param: string) => {\n * console.log(`Mock x ${ param }`);\n * });\n *\n * console.log(ClassTest.name); // Mock name\n * console.log(ClassTest.name); // ClassTest\n *\n * ClassTest.x('test1'); // Mock x test1\n * ClassTest.x('test2'); // original static x test2\n * ```\n *\n * @see FunctionType\n * @see KeysExtendingConstructorType\n *\n * @since 1.0.0\n */\n\nexport function spyOnImplementation<Target, Key extends KeysExtendingConstructorType<Target>>(target: Target, key: Key): Target[Key] extends FunctionType\n ? MockState<ReturnType<Target[Key]>, Parameters<Target[Key]>, Target>\n : MockState<Target[Key], [], Target>;\n\n/**\n * Creates a mock spy on the specified method or constructor of the target object.\n *\n * @template Target The type of the target object.\n * @template Key The type of the method or constructor key on the target object.\n *\n * @param target - The object whose method or constructor needs to be spied on.\n * @param key - The property key of the method or constructor to spy on.\n * @return A mock state representing the spied method or constructor if the key corresponds to a constructor type;\n * otherwise, throws a type error.\n *\n * @throws Error Throws an error if the `target` is a primitive value.\n * @throws Error Throws an error if `key` is null or undefined.\n * @throws Error Throws an error if the specified property does not exist on the target object.\n *\n * @remarks\n * This method is typically used for testing purposes to observe or manipulate calls to the method or constructor of an object.\n * The returned mock state may allow additional configuration, such as altering its behavior or tracking calls.\n *\n * @example\n * ```ts\n * const coolObject = {\n * ClassTest: class {\n * constructor(param: number) {\n * console.log('original Constructor');\n * }\n *\n * justAnFunction() {\n * console.log('original justAnFunction');\n * }\n * }\n * };\n *\n * const spy = xJet.spyOn(coolObject, 'ClassTest');\n * spy.mockImplementationOnce((param: number) => {\n * console.log(`mock Constructor with param: ${ param }`);\n *\n * return <any> {\n * justAnFunction() {\n * console.log('mock justAnFunction');\n * }\n * };\n * });\n *\n * const instance = new coolObject.ClassTest(1); // mock Constructor with param: 1\n * instance.justAnFunction(); // mock justAnFunction\n *\n * const instance2 = new coolObject.ClassTest(2); // original Constructor\n * instance2.justAnFunction(); // original justAnFunction\n * ```\n *\n * @see ConstructorType\n * @see ConstructorKeysType\n *\n * @since 1.0.0\n */\n\nexport function spyOnImplementation<Target, Key extends ConstructorKeysType<Target>>(target: Target, key: Key): Target[Key] extends ConstructorLikeType\n ? MockState<InstanceType<Target[Key]>, ConstructorParameters<Target[Key]>, Target>\n : never;\n\n/**\n * Creates a spy on a specific method or property of the given target object.\n *\n * @template Target - The type of the target object to spy on.\n * @template Key - The key of the property or method to spy on within the target object.\n *\n * @param target - The target object containing the property or method to be spied upon.\n * @param key - The name of the property or method on the target object to spy on.\n * @returns If the spied target is a function, it returns a `MockState` object to observe calls and arguments of the function.\n * Otherwise, it returns a `MockState` object to observe the value or state of the property.\n *\n * @throws Error Throws an error if the `target` is a primitive value.\n * @throws Error Throws an error if `key` is null or undefined.\n * @throws Error Throws an error if the specified property does not exist on the target object.\n *\n * @remarks This method is commonly used in test environments to monitor and assert interactions with a specific property\n * or method on an object. The returned `MockState` can be used to retrieve call history or observe mutations.\n *\n * @example\n * ```ts\n * const coolObject = {\n * myMethod() {\n * return 'Original myMethod';\n * },\n * coolString: 'Original coolString'\n * };\n *\n * const spy = xJet.spyOn(coolObject, 'coolString');\n * const spy2 = xJet.spyOn(coolObject, 'myMethod');\n *\n * spy.mockImplementationOnce(() => 'mock coolString');\n * spy2.mockImplementationOnce(() => 'mock myMethod string');\n *\n * console.log(coolObject.coolString); // mock coolString\n * console.log(coolObject.coolString); // Original coolString\n * console.log(coolObject.myMethod()); // mock myMethod string\n * console.log(coolObject.myMethod()); // Original myMethod\n * ```\n *\n * @see FunctionType\n *\n * @since 1.0.0\n */\n\nexport function spyOnImplementation<Target, Key extends keyof Target>(target: Target, key: Key): Target[Key] extends FunctionType\n ? MockState<ReturnType<Target[Key]>, Parameters<Target[Key]>, ThisParameterType<Target[Key]>>\n : MockState<Target[Key] | void, [ Target[Key] ], ThisParameterType<Target[Key]>>\n\n/**\n * Creates a spy on the specified method or property of the given target object.\n *\n * Replaces the specified method or property with a mock implementation that can be tracked during testing.\n *\n * @template T - The type of the target object.\n * @template K - The keyof the target used to specify the method or property being spied upon.\n *\n * @param target - The object that contains the method or property to spy on. Must be a non-primitive object or function.\n * @param key - The name of the property or method to spy on.\n *\n * @return MockState A `MockState` instance representing the state of the spied-on property or method, allowing tracking and mocking.\n *\n * @throws Error If the target is null, undefined, or a primitive value such as a string or number.\n * @throws Error If the `key` parameter is null or undefined.\n * @throws Error If the specified property does not exist in the target object.\n *\n * @remarks\n * This function is part of a testing framework and is used to track interactions with an object's method or property.\n * It can modify non-function properties or replace function properties with a mock function for testing purposes.\n * The original method or property can be restored after the spy lifecycle is completed.\n *\n * This method will throw errors for invalid inputs, or if the target object does not have the specified property.\n *\n * @since 1.0.0\n */\n\nexport function spyOnImplementation<T extends object, K extends keyof T>(target: T, key: K): MockState {\n if (target == null || (typeof target !== 'object' && typeof target !== 'function'))\n throw new ExecutionError('Target must be an object or function');\n\n if (key === null)\n throw new ExecutionError('Spied property/method key is required');\n\n if (!(key in target))\n throw new ExecutionError(`Property/method '${ String(key) }' does not exist on target`);\n\n const method = <MockState | T[K]> Reflect.get(target, key);\n const targetObject = target as T & { default: T };\n\n if (!method)\n throw new Error(`Property '${ String(key) }' does not exist in the provided object`);\n\n if((<MockState> method).xJetMock) {\n return <MockState> method;\n }\n\n let descriptor = Object.getOwnPropertyDescriptor(target, key);\n if (descriptor?.get && !descriptor.configurable) {\n if ('default' in targetObject && targetObject.default[key] === method) {\n target = targetObject.default;\n descriptor = Object.getOwnPropertyDescriptor(target, key);\n } else {\n throw new Error(`Property '${ String(key) }' is not configurable in an getter object`);\n }\n }\n\n if (typeof method !== 'function' || descriptor?.get) {\n return spyOnDescriptorProperty(target, key);\n }\n\n let fn: FunctionLikeType = method as FunctionLikeType;\n const protoDesc = Object.getOwnPropertyDescriptor(fn, 'prototype');\n if (fn.prototype && protoDesc && !protoDesc.writable) {\n fn = (...args: unknown[]): unknown => new (method as ConstructorLikeType<unknown, unknown[]>)(...args);\n }\n\n const mockState = new MockState(fn, () => {\n Reflect.set(target, key, method);\n }, 'xJet.spyOn()');\n\n MockState.mocks.push(mockState);\n Reflect.set(target, key, mockState);\n\n return mockState;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionLikeType } from '@remotex-labs/xjet-expect';\nimport type { TimerInterface } from '@shared/services/interfaces/timer-service.interface';\n\n/**\n * Imports\n */\n\nimport { Injectable, inject } from '@symlinks/services/inject.service';\n\n/**\n * Provides a virtual timer system that mimics native `setTimeout`/`setInterval`\n * while allowing controlled execution for deterministic tests.\n *\n * @remarks\n * This service replaces the global timing functions with fake timers so that\n * time can be manually advanced and callbacks triggered predictably.\n * It is intended for unit testing scenarios where you need full control over\n * asynchronous timing without waiting in real time.\n *\n * @example\n * ```ts\n * useFakeTimers();\n * setTimeout(() => console.log('done'), 1000);\n * advanceTimersByTime(1000); // logs 'done' immediately\n * useRealTimers();\n * ```\n *\n * @since 1.1.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class TimerService {\n /**\n * Active timers managed by the fake timer engine.\n * @since 1.1.0\n */\n\n readonly timers = new Map<number, TimerInterface>();\n\n /**\n * Stores original `Date.now` to restore when real timers are re-enabled.\n * @since 1.1.0\n */\n\n readonly originalDateNow = Date.now;\n\n /**\n * Stores original global `setTimeout`.\n * @since 1.1.0\n */\n\n readonly originalSetTimeout = globalThis.setTimeout;\n\n /**\n * Stores original global `setInterval`.\n * @since 1.1.0\n */\n\n readonly originalSetInterval = globalThis.setInterval;\n\n /**\n * Stores original global `clearTimeout`.\n * @since 1.1.0\n */\n\n readonly originalClearTimeout = globalThis.clearTimeout;\n\n /**\n * Stores original global `clearInterval`.\n * @since 1.1.0\n */\n\n readonly originalClearInterval = globalThis.clearInterval;\n\n /**\n * Simulated current timestamp for the fake timers.\n * @since 1.1.0\n */\n\n private now = 0;\n\n /**\n * Incremental id used to register timers uniquely.\n * @since 1.1.0\n */\n\n private nextId = 1;\n\n /**\n * Replaces the global timer functions with in-memory fakes.\n *\n * @remarks\n * After calling this method, any calls to `setTimeout`, `setInterval`,\n * `clearTimeout`, or `clearInterval` will be intercepted and stored in the\n * {@link timers} map instead of scheduling real OS timers.\n * This allows tests to control time progression manually using\n * {@link advanceTimersByTime}, {@link runAllTimers}, or\n * {@link runOnlyPendingTimers}.\n *\n * @example\n * ```ts\n * timerService.useFakeTimers();\n * const id = setTimeout(() => console.log('done'), 1000);\n * timerService.advanceTimersByTime(1000); // logs \"done\" immediately\n * ```\n *\n * @since 1.1.0\n */\n\n useFakeTimers(): void {\n const setTimeout = (cb: FunctionLikeType<void>, delay: number = 0, ...args: Array<unknown>): number => {\n const id = this.nextId++;\n this.timers.set(id, { id, callback: cb, time: this.now + delay, interval: null, args: args ?? [] });\n\n return id;\n };\n\n const setInterval = (cb: FunctionLikeType<void>, interval: number = 0): number => {\n const id = this.nextId++;\n this.timers.set(id, { id, callback: cb, time: this.now + interval, interval, args: [] });\n\n return id;\n };\n\n const clearTimeout = (id: number): void => {\n this.timers.delete(id);\n };\n\n\n const clearInterval = (id: number): void => {\n this.timers.delete(id);\n };\n\n const global = <Record<string, unknown>> globalThis;\n global.setTimeout = setTimeout;\n global.setInterval = setInterval;\n global.clearTimeout = clearTimeout;\n global.clearInterval = clearInterval;\n }\n\n /**\n * Restores the original global timer APIs and `Date.now`.\n *\n * @remarks\n * This method undoes the effects of {@link useFakeTimers}, re-binding\n * the native implementations of `setTimeout`, `setInterval`,\n * `clearTimeout`, `clearInterval`, and `Date.now`.\n * After calling this, timers once again behave according to real system\n * time and manual advancement methods such as\n * {@link advanceTimersByTime} no longer apply.\n *\n * @example\n * ```ts\n * timerService.useFakeTimers();\n * // ...run tests with controlled time...\n * timerService.useRealTimers(); // restore native timers\n * ```\n *\n * @since 1.1.0\n */\n\n useRealTimers(): void {\n globalThis.setTimeout = this.originalSetTimeout;\n globalThis.clearTimeout = this.originalClearTimeout;\n globalThis.setInterval = this.originalSetInterval;\n globalThis.clearInterval = this.originalClearInterval;\n Date.now = this.originalDateNow;\n }\n\n /**\n * Advances the simulated clock by a specific number of milliseconds and\n * executes all timers whose scheduled time has elapsed.\n *\n * @remarks\n * Use this method after calling {@link useFakeTimers} to fast-forward the\n * internal clock without waiting in real time.\n * Any `setTimeout` or `setInterval` callbacks scheduled within the\n * advanced period will run immediately in order of their scheduled time.\n *\n * @param ms - The number of milliseconds to move the simulated time forward.\n *\n * @example\n * ```ts\n * timerService.useFakeTimers();\n * setTimeout(() => console.log('done'), 500);\n * timerService.advanceTimersByTime(500); // logs \"done\"\n * ```\n *\n * @since 1.1.0\n */\n\n advanceTimersByTime(ms: number) : void {\n this.now += ms;\n this.runDueTimers();\n }\n\n /**\n * Executes every scheduled timer until none remain.\n *\n * @remarks\n * This method repeatedly advances the simulated clock to the next\n * scheduled timer and runs its callback until the {@link timers} map\n * is empty.\n * It is useful when you want to immediately flush **all** pending\n * `setTimeout` or `setInterval` callbacks regardless of their delay,\n * without specifying a time increment.\n *\n * @example\n * ```ts\n * timerService.useFakeTimers();\n * setTimeout(() => console.log('A'), 100);\n * setTimeout(() => console.log('B'), 200);\n * timerService.runAllTimers(); // logs \"A\" then \"B\"\n * ```\n *\n * @since 1.1.0\n */\n\n runAllTimers(): void {\n while (this.timers.size > 0) {\n this.now = Math.min(...Array.from(this.timers.values()).map(t => t.time));\n this.runDueTimers();\n }\n }\n\n /**\n * Executes only the timers that are currently pending at the time of call,\n * without running any new timers that may be scheduled by those callbacks.\n *\n * @remarks\n * Unlike {@link runAllTimers}, this method captures the set of timers\n * that exist when the method is invoked and restricts execution to that\n * initial set.\n * If any of those timers schedule additional timers while running,\n * the newly scheduled ones will **not** be executed during this call.\n *\n * @example\n * ```ts\n * timerService.useFakeTimers();\n * setTimeout(() => {\n * console.log('first');\n * setTimeout(() => console.log('second'), 100);\n * }, 100);\n *\n * timerService.runOnlyPendingTimers();\n * // Logs only \"first\" because \"second\" was created afterward.\n * ```\n *\n * @since 1.1.0\n */\n\n runOnlyPendingTimers(): void {\n const pendingTimers = new Set(this.timers.keys());\n\n while (pendingTimers.size > 0) {\n const nextTimerTimes = Array.from(this.timers.values())\n .filter(t => pendingTimers.has(t.id))\n .map(t => t.time);\n\n if (nextTimerTimes.length === 0) break;\n\n this.now = Math.min(...nextTimerTimes);\n this.runDueTimers(pendingTimers);\n\n for (const id of pendingTimers) {\n if (!this.timers.has(id)) pendingTimers.delete(id);\n }\n }\n }\n\n /**\n * Executes all timers whose scheduled time is less than or equal to the\n * current simulated time (`this.now`).\n *\n * @remarks\n * This internal method is called by {@link advanceTimersByTime},\n * {@link runAllTimers}, and {@link runOnlyPendingTimers} to trigger\n * due timers.\n * If `limitTimers` is provided, only timers included in that set are executed.\n * Repeating timers (`setInterval`) are rescheduled automatically until\n * their next execution time exceeds the current simulated time.\n *\n * @param limitTimers - Optional set of timer IDs to restrict execution.\n *\n * @internal\n * @since 1.1.0\n */\n\n private runDueTimers(limitTimers?: Set<number>): void {\n let executed = true;\n while (executed) {\n executed = false;\n\n const timers = Array.from(this.timers.values()).sort((a, b) => a.time - b.time);\n\n for (const timer of timers) {\n if (!this.timers.has(timer.id)) continue;\n if (limitTimers && !limitTimers.has(timer.id)) continue;\n\n if (timer.time <= this.now) {\n if (timer.interval !== null) {\n while (timer.time <= this.now) {\n timer.callback();\n timer.time += timer.interval;\n }\n } else {\n timer.callback();\n this.timers.delete(timer.id);\n }\n executed = true;\n }\n }\n }\n }\n}\n\n/**\n * Globally enables fake timers using the shared {@link TimerService}.\n *\n * @remarks\n * After calling this function, all calls to `setTimeout`, `setInterval`,\n * `clearTimeout`, and `clearInterval` will be intercepted by the\n * {@link TimerService} and stored in-memory instead of executing in real time.\n * This allows deterministic testing by manually advancing time with\n * {@link advanceTimersByTime}, {@link runAllTimers}, or\n * {@link runOnlyPendingTimers}.\n *\n * @example\n * ```ts\n * useFakeTimers();\n * setTimeout(() => console.log('done'), 1000);\n * advanceTimersByTime(1000); // logs \"done\" immediately\n * ```\n *\n * @since 1.1.0\n */\n\nexport function useFakeTimers(): void {\n inject(TimerService).useFakeTimers();\n}\n\n/**\n * Restores real timers globally using the shared {@link TimerService}.\n *\n * @remarks\n * This function undoes the effects of {@link useFakeTimers}, restoring the\n * native implementations of `setTimeout`, `setInterval`, `clearTimeout`,\n * `clearInterval`, and `Date.now`.\n * After calling this, timers once again behave according to real system time,\n * and manual advancement methods like {@link advanceTimersByTime} no longer apply.\n *\n * @example\n * ```ts\n * useFakeTimers();\n * // ...run tests with controlled time...\n * useRealTimers(); // restore native timers\n * ```\n *\n * @since 1.1.0\n */\n\nexport function useRealTimers(): void {\n inject(TimerService).useRealTimers();\n}\n\n/**\n * Executes all timers currently registered in the {@link TimerService}.\n *\n * @remarks\n * This function repeatedly runs all pending `setTimeout` and `setInterval`\n * callbacks until no timers remain.\n * It is equivalent to calling {@link TimerService.runAllTimers} on the\n * injected service instance and is useful for immediately flushing\n * all scheduled timers in tests.\n *\n * @example\n * ```ts\n * useFakeTimers();\n * setTimeout(() => console.log('A'), 100);\n * setTimeout(() => console.log('B'), 200);\n * runAllTimers(); // logs \"A\" then \"B\"\n * ```\n *\n * @since 1.1.0\n */\n\nexport function runAllTimers(): void {\n inject(TimerService).runAllTimers();\n}\n\n\n/**\n * Executes only the timers that are pending at the time of invocation.\n *\n * @remarks\n * This function runs the callbacks of timers that exist when the function\n * is called, without executing any new timers that may be scheduled\n * during their execution.\n * It delegates to {@link TimerService.runOnlyPendingTimers} on the injected\n * service instance.\n *\n * @example\n * ```ts\n * useFakeTimers();\n * setTimeout(() => {\n * console.log('first');\n * setTimeout(() => console.log('second'), 100);\n * }, 100);\n *\n * runOnlyPendingTimers();\n * // Logs only \"first\"; \"second\" is not executed yet\n * ```\n *\n * @since 1.1.0\n */\nexport function runOnlyPendingTimers(): void {\n inject(TimerService).runOnlyPendingTimers();\n}\n\n/**\n * Advances the simulated time by a specified number of milliseconds and\n * executes all timers that are due.\n *\n * @remarks\n * This function delegates to {@link TimerService.advanceTimersByTime}\n * on the injected service instance.\n * It is intended to be used after {@link useFakeTimers} to fast-forward\n * time in tests without waiting for real timers.\n *\n * @param ms - The number of milliseconds to advance (default is `0`).\n *\n * @example\n * ```ts\n * useFakeTimers();\n * setTimeout(() => console.log('done'), 500);\n * advanceTimersByTime(500); // logs \"done\"\n * ```\n *\n * @since 1.1.0\n */\n\nexport function advanceTimersByTime(ms: number = 0): void {\n inject(TimerService).advanceTimersByTime(ms);\n}\n\n", "/**\n * A regular expression pattern used to match variable-like strings prefixed with a `$` symbol.\n *\n * @default /\\$([#\\\\w.])+/g\n *\n * @see resolveVariable\n * @see interpolateVariables\n *\n * @since 1.0.0\n */\n\nconst VARIABLE_PATTERN = /\\$([#\\w.])+/g;\n\n/**\n * Formats a given value into a human-readable string representation.\n *\n * @param value - The value to be formatted\n * @returns The formatted string representation of the input value\n *\n * @remarks\n * This method ensures that non-string values are converted into a JSON string with\n * indentation for easier readability. If the input is a string, it is returned as-is.\n *\n * @example\n * ```ts\n * // String input is returned unchanged\n * const str = prettyFormat(\"hello\"); // Returns: \"hello\"\n *\n * // Objects are converted to indented JSON\n * const obj = prettyFormat({ name: \"John\", age: 30 });\n * // Returns:\n * // {\n * // \"name\": \"John\",\n * // \"age\": 30\n * // }\n * ```\n *\n * @see printf\n *\n * @since 1.0.0\n */\n\nexport function prettyFormat(value: unknown): string {\n if (typeof value === 'string') return value;\n\n return JSON.stringify(value, null, 4);\n}\n\n/**\n * Retrieves a value from a nested object structure based on a specified path.\n *\n * @param data - The object containing the nested data to traverse\n * @param path - An array of strings representing the sequence of keys to access the desired value\n * @returns The value found at the specified path within the object, or `undefined` if the path does not exist\n *\n * @remarks\n * This function safely traverses the given object structure without throwing errors\n * for missing keys or null/undefined values.\n *\n * @example\n * ```ts\n * const data = {\n * user: {\n * profile: {\n * name: \"John Doe\",\n * email: \"john@example.com\"\n * }\n * }\n * };\n *\n * const name = getValueByPath(data, [\"user\", \"profile\", \"name\"]);\n * // Returns: \"John Doe\"\n *\n * const missing = getValueByPath(data, [\"user\", \"settings\", \"theme\"]);\n * // Returns: undefined\n * ```\n *\n * @see resolveVariable\n *\n * @since 1.0.0\n */\n\nexport function getValueByPath(data: Record<string, unknown>, path: string[]): unknown {\n if (!path.length || !data) return undefined;\n\n try {\n return path.reduce((obj, key) => {\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n throw new Error('Path traversal failed');\n }\n\n return (obj as Record<string, unknown>)[key];\n }, data as unknown);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolves a variable token into its corresponding value from the provided data object.\n *\n * @param token - The variable token to resolve\n * @param data - The object containing data used for resolving the variable token\n * @param arrayIndex - The index value to be used if the token represents an array index (`$#`)\n * @returns The resolved value as a string, or the original token if resolution fails\n *\n * @remarks\n * This function assumes the use of dot notation in token paths to access nested properties\n * within the `data` object. Tokens starting with `$#` will be replaced by the array index.\n *\n * @example\n * ```ts\n * const data = {\n * user: {\n * name: \"John\"\n * }\n * };\n *\n * const value1 = resolveVariable(\"$user.name\", data, 0);\n * // Returns: \"John\"\n *\n * const value2 = resolveVariable(\"$#\", data, 5);\n * // Returns: \"5\"\n * ```\n *\n * @see getValueByPath\n * @see interpolateVariables\n *\n * @since 1.0.0\n */\n\nexport function resolveVariable(token: string, data: Record<string, unknown>, arrayIndex: number): string {\n if (!token || typeof <unknown> token !== 'string' || !token.startsWith('$'))\n return token;\n\n if (token === '$#')\n return String(arrayIndex);\n\n const propertyPath = token.slice(1).split('.');\n const resolvedValue = getValueByPath(data, propertyPath);\n\n if (resolvedValue === undefined || resolvedValue === null) {\n return token;\n }\n\n if (typeof resolvedValue === 'object') {\n try {\n return JSON.stringify(resolvedValue, (key, value) => {\n if (key && typeof value === 'object')\n return '[Object]';\n\n return value;\n });\n } catch {\n return String(resolvedValue);\n }\n }\n\n return String(resolvedValue);\n}\n\n/**\n * Replaces variable placeholders within a template string with corresponding values from a provided data object.\n *\n * @param template - The template string containing variable placeholders\n * @param data - An object mapping variable names to their respective values\n * @param arrayIndex - The index to be applied when resolving variables that reference array values\n * @returns The resulting string with all variable placeholders replaced by their resolved values\n *\n * @throws Error - If a required variable cannot be resolved\n *\n * @remarks\n * The function uses a regular expression to identify variable placeholders within the template string\n * and replaces them with corresponding values derived from the `data` object.\n *\n * @example\n * ```ts\n * const data = {\n * user: {\n * name: \"Jane\",\n * id: 42\n * },\n * status: \"active\"\n * };\n *\n * const result = interpolateVariables(\"User $user.name ($user.id) is $status\", data, 0);\n * // Returns: \"User Jane (42) is active\"\n * ```\n *\n * @see VARIABLE_PATTERN\n * @see resolveVariable\n *\n * @since 1.0.0\n */\n\nexport function interpolateVariables(template: string, data: Record<string, unknown>, arrayIndex: number): string {\n return template.replace(\n VARIABLE_PATTERN, (variableToken) => resolveVariable(variableToken, data, arrayIndex)\n );\n}\n\n/**\n * Formats a given string by interpolating it with the provided parameters.\n *\n * @param description - The format string containing variables or tokens to be replaced\n * @param params - An array of values to interpolate or substitute into the format string\n * @param index - An index used for specific token replacements (e.g., `%#`)\n * @returns The formatted string after performing substitutions and formatting\n *\n * @remarks\n * This function supports two formatting approaches:\n * 1. `$variable` style interpolation using the first object in the `params` array\n * 2. Printf-style format specifiers with the following options:\n * - `%p`: Pretty prints a value\n * - `%s`: Converts value to a string\n * - `%d`: Converts value to a numeric string\n * - `%i`: Converts value to an integer string (floor of the number)\n * - `%f`: Converts value to a floating-point string\n * - `%j`: Converts value to its JSON representation\n * - `%o`: Outputs the object's `toString` representation\n * - `%#`: Replaced with the provided `index`\n * - `%%`: Escapes the `%` character\n *\n * If the `description` contains `$`-style variables, it will interpolate those using the first object in the `params` array.\n * This behavior does not apply if the string also contains `%%`.\n *\n * @example\n * ```ts\n * // Format with printf-style specifiers\n * const result1 = printf(\"Value: %s, Number: %d\", [\"test\", 42], 0);\n * // Returns: \"Value: test, Number: 42\"\n *\n * // Format with variable interpolation\n * const data = { name: \"Alice\", age: 30 };\n * const result2 = printf(\"Name: $name, Age: $age\", [data], 0);\n * // Returns: \"Name: Alice, Age: 30\"\n * ```\n *\n * @see prettyFormat\n * @see interpolateVariables\n *\n * @since 1.0.0\n */\n\nexport function printf(description: string, params: Array<unknown>, index: number): string {\n let paramIndex = 0;\n // Handle $variable style interpolation first\n if (description.includes('$') && !description.includes('%%')) {\n description = interpolateVariables(description, <Record<string, unknown>> params[0], index);\n }\n\n return description.replace(/%([psdifjo#%])/g, (match, format) => {\n if (format === '%') return '%';\n if (format === '#') return String(index);\n\n const value = params[paramIndex++];\n switch (format) {\n case 'p':\n return prettyFormat(value);\n case 's':\n return String(value);\n case 'd':\n return Number(value).toString();\n case 'i':\n return Math.floor(Number(value)).toString();\n case 'f':\n return Number(value).toString();\n case 'j':\n return JSON.stringify(value);\n case 'o':\n return Object.prototype.toString.call(value);\n default:\n return match;\n }\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionType } from '@remotex-labs/xjet-expect';\nimport type { InvokeType } from '@shared/directives/interfaces/each-directive.interface';\n\n/**\n * Imports\n */\n\nimport { printf } from '@shared/components/printf.component';\n\n/**\n * Converts a template string and input data into an array of structured objects\n *\n * @param templateString - Template string containing column headings separated by pipe characters\n * @param inputData - Array of values to be organized according to the template structure\n * @returns Array of objects where each object represents a row with properties named after the headings\n *\n * @throws Error - When template headings are empty or missing pipe delimiters\n * @throws Error - When the input data length is not a multiple of the headings length\n *\n * @example\n * ```ts\n * const template = parseTemplate(`name|age|role`, ['John', 30, 'Developer', 'Jane', 25, 'Designer']);\n * // Returns: [\n * // { name: 'John', age: 30, role: 'Developer' },\n * // { name: 'Jane', age: 25, role: 'Designer' }\n * // ]\n * ```\n *\n * @see each - Function that uses parseTemplate for test case generation\n *\n * @since 1.0.0\n */\n\nexport function parseTemplate(templateString: TemplateStringsArray, inputData: Array<unknown>): Array<Record<string, unknown>> {\n // Extract the column headings and remove any leading/trailing whitespace\n const headings: string[] = templateString[0].split('|').map((h: string) => h.trim());\n if (headings.length === 0 || headings.some((h) => h === ''))\n throw new Error('Template string headings must not be empty and should contain pipe delimiters.');\n\n if ((inputData.length % headings.length) !== 0)\n throw new Error('Not enough arguments supplied for given headings.');\n\n return Array.from({ length: inputData.length / headings.length }, (_, rowIndex) => {\n return headings.reduce((acc, heading, columnIndex) => {\n acc[heading] = inputData[rowIndex * headings.length + columnIndex];\n\n return acc;\n }, {} as Record<string, unknown>);\n });\n}\n\n/**\n * Executes a function block as a test case with the specified description\n *\n * @template T - Type extending Array of unknown values\n * @param executor - The function that will execute each test case\n * @param args - Arguments representing test cases or a tagged template literal\n * @returns A function that accepts a test name, test block function, and optional timeout\n *\n * @throws Error - When called with fewer than 2 arguments\n *\n * @remarks\n * This method provides a way to directly invoke a test function with optional arguments.\n * It is typically used with the `each` function to create parameterized test cases.\n * The provided description will be used for test reporting and identification.\n *\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * // As part of the each function with direct arguments\n * test.each(1, 2, 3)('test with %s', (val) => {\n * expect(val).toBeGreaterThan(0);\n * });\n *\n * test.each(\n * { name: 'John', age: 30 },\n * { name: 'Jane', age: 25 }\n * )('User %s is %s years old', (name, age) => {\n * expect(typeof name).toBe('string');\n * expect(typeof age).toBe('number');\n * });\n *\n * test.each`\n * a | b | sum\n * ${ 1 } | ${ 2 } | ${ 3 }\n * ${ 2 } | ${ 5 } | ${ 7 }\n * `('adds $a + $b -> $sum', ({ a, b, sum }) => {\n * expect(a + b).toBe(sum);\n * });\n *\n * describe.each` a | b | expected ${ 1 } | ${ 2 } | ${ 3 } ${ 2 } | ${ 3 } | ${ 5 }`\n * ('%# adds $a and $b to get $expected', ({ a, b, expected }) => {\n * test('calculates sum', () => {\n * expect(a + b).toBe(expected);\n * });\n * });\n * ```\n *\n * @see InvokeType - Type definition for the executor function\n * @see FunctionType - Type definition for the test block function\n * @see parseTemplate - Function used to parse tagged template literals\n *\n * @since 1.0.0\n */\n\nexport function each<T extends Array<unknown>>(executor: InvokeType, ...args: T) {\n if (args.length < 2) {\n throw new Error('`.each` must be called with at leas 2 argument or Tagged Template Literal.');\n }\n\n // eslint-disable-next-line\n const isTemplateStrings = args[0] instanceof Array && (<any> args[0]).raw !== undefined;\n const cases: Array<unknown> = isTemplateStrings ? parseTemplate(<TemplateStringsArray> args.shift(), args) : args;\n\n return (name: string, blockFn: FunctionType, timeout?: number): void => {\n cases.forEach((testCase, index) => {\n const parseArgs = Array.isArray(testCase) ? testCase : [ testCase ];\n executor(printf(name, parseArgs, Number(index)), blockFn, parseArgs, timeout);\n });\n };\n}\n", "export class TimeoutError extends Error {\n constructor(timeout: number, at: string, stack: string = '') {\n super(`Exceeded timeout of ${ timeout } ms at ${ at }`);\n\n // Ensure a correct prototype chain (important for `instanceof`)\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = 'xJetTimeoutError';\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = 'xJetFailingError';\n if(stack) {\n this.stack = `${ this.name }: ${ this.message }\\n${ stack }`;\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionLikeType } from '@remotex-labs/xjet-expect';\n\n/**\n * Imports\n */\n\nimport { TimeoutError } from '@errors/timeout.error';\nimport { inject } from '@symlinks/services/inject.service';\nimport { TimerService } from '@shared/services/timer.service';\n\n\n/**\n * Executes a given asynchronous or synchronous task with an optional timeout constraint.\n *\n * @typeParam T - The resolved value type.\n *\n * @param task - Either a function that returns a value or promise, or a promise itself.\n * @param delay - Timeout in milliseconds, or `-1` to disable the timeout.\n * @param at - A contextual label (e.g., method name or operation name) to aid debugging.\n * @param stack - Optional stack trace to provide more detailed error context.\n *\n * @throws {@link TimeoutError} If the task does not complete within the specified `delay`\n * (only when `delay` is not `-1`).\n *\n * @remarks\n * The function accepts either:\n * - a function returning a value or a promise, or\n * - a promise directly.\n *\n * If `delay` is `-1`, no timeout is applied. Otherwise the task is raced against\n * a timer and a {@link TimeoutError} is thrown on expiry.\n *\n * @example\n * ```ts\n * // Passing a function\n * await withTimeout(\n * () => fetchData(),\n * 5000,\n * 'fetchData'\n * );\n *\n * // Passing a promise directly\n * await withTimeout(\n * fetchData(),\n * 5000,\n * 'fetchDataDirect'\n * );\n *\n * // No timeout\n * await withTimeout(fetchData(), -1, 'fetchDataNoTimeout');\n * ```\n *\n * @since 1.1.0\n */\n\nexport async function withTimeout<T>(\n task: FunctionLikeType<T | Promise<T>> | Promise<T> | T, delay: number, at: string, stack?: string\n): Promise<T> {\n const timers = inject(TimerService);\n\n const taskPromise =\n typeof task === 'function'\n ? Promise.resolve((task as FunctionLikeType<T | Promise<T>>)())\n : Promise.resolve(task);\n\n if (delay === -1 || !timers.originalSetTimeout) {\n return taskPromise;\n }\n\n let timeoutId: ReturnType<typeof setTimeout>;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = timers.originalSetTimeout?.(\n () => reject(new TimeoutError(delay, at, stack)),\n delay\n );\n });\n\n try {\n return await Promise.race([ taskPromise, timeoutPromise ]);\n } finally {\n timers.originalClearTimeout?.(timeoutId!);\n }\n}\n\n", "/**\n * Imports\n */\n\nimport { ExecutionError } from '@shared/errors/execution.error';\n\n\nexport class FailingError extends ExecutionError {\n\n\n constructor(stack: string) {\n super('Failing test passed even though it was supposed to fail. Remove `.failing` to remove error.');\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, FailingError);\n }\n\n this.name = 'xJetFailingError';\n this.stack = `${ this.name }: ${ this.message }\\n${ stack }`;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { TestFlagsType } from '@shared/models/interfaces/test-model.interface';\nimport type { ContextInterface } from '@shared/models/interfaces/describe-model.interface';\n\n/**\n * Imports\n */\n\nimport { SuiteState } from '@shared/states/suite.state';\nimport { inject } from '@symlinks/services/inject.service';\nimport { withTimeout } from '@components/timeout.component';\nimport { FailingError } from '@shared/errors/failing.error';\nimport { MessageType } from '@messages/constants/report.constant';\nimport { emitEvent, emitStatus } from '@shared/services/emit.service';\nimport { HookType } from '@shared/models/constants/hook.model.constants';\nimport { TestExecutionType } from '@shared/models/constants/test-model.constants';\nimport { type ContextType, type FunctionLikeType, type FunctionType, isPromise } from '@remotex-labs/xjet-expect';\n\n/**\n * Represents a test case within the testing framework that manages execution,\n * timing, and reporting of individual tests.\n *\n * @example\n * ```ts\n * const test = new TestModel(\n * 'should validate user input correctly',\n * async () => {\n * const result = await validateInput('test@example.com');\n * expect(result.isValid).toBe(true);\n * },\n * 2000\n * );\n *\n * // Set ancestry to show the test's location in the test hierarchy\n * test.ancestry = ['Authentication', 'Input Validation'];\n *\n * // Execute the test\n * await test.execute();\n * ```\n *\n * @remarks\n * The TestModel is responsible for tracking test execution time, handling timeouts,\n * managing test context, and reporting test status through the emit service.\n * It supports both synchronous and promise-based test implementations.\n *\n * @throws FailingError - When a test fails due to assertions or errors\n *\n * @see ContextInterface\n * @see EmitActionEventType\n * @see EmitStatusEventType\n * @see InvocationLocationType\n *\n * @since 1.0.0\n */\n\nexport class TestModel {\n /**\n * Stores the hierarchical path of parent test descriptions that contain this test\n *\n * @default []\n * @since 1.0.0\n */\n\n readonly ancestry: Array<string> = [];\n\n /**\n * Stores information about where this test is being executed in the source code\n *\n * @see InvocationLocationType\n * @since 1.0.0\n */\n\n private executionLocation: string = '';\n\n /**\n * Timestamp when test execution started, measured in milliseconds\n *\n * @default 0\n * @since 1.0.0\n */\n\n private executionStartTime: number = 0;\n\n /**\n * Creates a new instance of the TestModel to represent an executable test.\n *\n * @param description - The test description that explains the purpose of the test\n * @param testImplementation - The function containing the actual test code to be executed\n * @param timeoutDuration - The maximum time in milliseconds that the test is allowed to run\n * @param testParameters - An array of parameters to be passed to the test implementation\n * @param testOptions - Configuration options that control test execution behavior\n *\n * @example\n * ```ts\n * const test = new TestModel(\n * 'should calculate the correct sum',\n * () => expect(sum(2, 2)).toBe(4),\n * 5000\n * );\n * ```\n *\n * @since 1.0.0\n */\n\n constructor(\n readonly description: string,\n private readonly testImplementation: FunctionType,\n private readonly timeoutDuration: number,\n private readonly testParameters: unknown[] = [],\n private readonly testOptions: TestFlagsType = {}\n ) {}\n\n /**\n * Provides access to the test configuration options.\n *\n * @returns The test configuration options that control test execution behavior\n *\n * @since 1.0.0\n */\n\n get options(): TestFlagsType {\n return this.testOptions;\n }\n\n /**\n * Sets the location where the test is being executed.\n *\n * @param location - The execution location information containing position details\n *\n * @see InvocationLocationType\n * @since 1.0.0\n */\n\n setExecutionLocation(location: string): void {\n this.executionLocation = location;\n }\n\n /**\n * Applies execution control options to the test, allowing it to be skipped or run exclusively.\n *\n * @param skip - Flag indicating whether the test should be skipped during execution\n * @param only - Flag indicating whether only this test should be executed\n *\n * @remarks\n * This method uses logical OR assignment (||=) to ensure options are only set to true and\n * never reset from true to false. Existing flag values take precedence.\n *\n * @example\n * ```ts\n * testInstance.applyExecutionFlags(true, false); // Will mark test to be skipped\n * testInstance.applyExecutionFlags(false, true); // Will mark test to run exclusively\n * ```\n *\n * @see TestFlagsType\n * @since 1.0.0\n */\n\n applyExecutionFlags(skip?: boolean, only?: boolean): void {\n this.testOptions.skip ||= skip;\n this.testOptions.only ||= only;\n }\n\n /**\n * Sets the ancestry for this test by adding parent test descriptions to the ancestry chain.\n *\n * @param parentTests - Array of parent test description strings representing the test hierarchy\n *\n * @example\n * ```ts\n * const childTest = new TestModel(\"should work\", () => {}, 5000);\n * childTest.setAncestry([\"describe block A\", \"describe block B\"]);\n * ```\n *\n * @since 1.0.0\n */\n\n setAncestry(parentTests: string[]): void {\n this.ancestry.push(...parentTests);\n }\n\n /**\n * Executes the test within the specified context, managing test lifecycle and status reporting.\n *\n * @param context - The test execution context containing shared state and utilities\n * @param runLifecycleHooks - Function that runs before/after hooks at appropriate times\n * @param isExclusiveMode - Flag indicating if tests are running in exclusive mode (only marked tests)\n * @returns Promise that resolves when the test execution completes\n *\n * @throws Error - If any unhandled exceptions occur during test execution that aren't captured\n *\n * @remarks\n * The method tracks execution time, manages test lifecycle, handles skipping logic, and processes\n * test results. It also notifies about test status changes through observer pattern implementation.\n *\n * @example\n * ```ts\n * // Running a test with context and lifecycle hooks\n * await testInstance.run(\n * testContext,\n * async (hookType, ctx) => {\n * await runHooks(hookType, ctx);\n * },\n * false\n * );\n * ```\n *\n * @see HookType\n * @see ActionType\n * @see ContextInterface\n *\n * @since 1.0.0\n */\n\n async run(\n context: ContextType<ContextInterface>,\n runLifecycleHooks: FunctionLikeType<Promise<void>, [ HookType, ContextType<ContextInterface> ]>,\n isExclusiveMode: boolean = false\n ): Promise<void> {\n inject(SuiteState).test = this;\n this.executionStartTime = Date.now();\n\n if (this.shouldSkipDueToSetupErrors(context))\n return;\n\n if (this.determineSkipAction(isExclusiveMode)) return;\n\n try {\n await this.executeTestWithLifecycle(context, runLifecycleHooks);\n this.validateTestOutcome();\n } catch (error) {\n this.notifyTestFailure(error);\n if(globalThis.__XJET?.runtime.bail) {\n context.hasError = true;\n }\n } finally {\n inject(SuiteState).test = undefined;\n }\n }\n\n /**\n * Determines whether a test should be skipped due to errors in setup hooks.\n *\n * @param context - The test execution context containing shared state and potential setup errors\n * @returns Boolean indicating whether the test should be skipped\n *\n * @remarks\n * This method checks if any errors occurred in beforeAll hooks and reports them as test failures.\n * Tests are skipped when setup errors are present to prevent misleading test results.\n *\n * @see ContextInterface\n *\n * @internal\n *\n * @since 1.0.0\n */\n\n private shouldSkipDueToSetupErrors(context: ContextType<ContextInterface>): boolean {\n if (context.beforeAllErrors && context.beforeAllErrors.length > 0) {\n this.notifyTestFailure(context.beforeAllErrors as Array<unknown>);\n\n return true;\n }\n\n return false;\n }\n\n private determineSkipAction(isExclusiveMode: boolean): boolean {\n if(inject(SuiteState).isOnlyMode && !this.testOptions.only) {\n this.notifyTestStatus(true);\n\n return true;\n }\n\n if (this.testOptions.skip || this.testOptions.todo) {\n this.notifyTestStatus(this.testOptions.skip, this.testOptions.todo);\n\n return true;\n }\n\n if(isExclusiveMode && !this.testOptions.only) {\n this.notifyTestStatus(true);\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Executes a test with proper lifecycle hooks and timeout management.\n *\n * @param context - The test execution context containing shared state and utilities\n * @param runLifecycleHooks - Function that runs the specified hook type with the given context\n *\n * @returns Promise that resolves when the test and all its lifecycle hooks have completed\n *\n * @throws TimeoutError - When the test execution exceeds the configured timeout duration\n *\n * @remarks\n * This method orchestrates the complete test execution flow including:\n * 1. Running beforeEach hooks\n * 2. Executing the actual test body with timeout protection\n * 3. Running afterEach hooks regardless of test outcome\n *\n * @internal\n * @see HookType\n * @see ContextInterface\n * @see withTimeout\n *\n * @since 1.0.0\n */\n\n private async executeTestWithLifecycle(\n context: ContextType<ContextInterface>,\n runLifecycleHooks: FunctionLikeType<Promise<void>, [ HookType, ContextType<ContextInterface> ]>\n ): Promise<void> {\n await runLifecycleHooks(HookType.BEFORE_EACH, context);\n\n await withTimeout<void>(\n this.executeTestWithContext(context),\n this.timeoutDuration,\n `'${ this.timeoutDuration }' test`,\n this.executionLocation\n );\n\n await runLifecycleHooks(HookType.AFTER_EACH, context);\n }\n\n /**\n * Validates the test outcome, handling failing tests and notifying of success.\n *\n * @throws FailingError - When a test is marked as failing but successfully completes\n *\n * @remarks\n * This method implements special handling for tests marked with the 'failing' option.\n * For failing tests, it throws an error if the test unexpectedly succeeds.\n * For normal tests, it reports a successful test outcome.\n *\n * @internal\n * @see ActionType\n * @see FailingError\n *\n * @since 1.0.0\n */\n\n private validateTestOutcome(): void {\n if (this.testOptions.failing) {\n throw new FailingError(this.executionLocation!);\n }\n\n this.notifyTestAction();\n }\n\n /**\n * Determines if the test is using callback-style asynchronous execution.\n *\n * @returns Boolean indicating whether the test uses the callback pattern\n *\n * @remarks\n * This method analyzes the test implementation's parameter count to detect callback-style tests.\n * It identifies two callback patterns:\n * 1. A test function that expects exactly one parameter (the callback) with no test parameters\n * 2. A test function that expects exactly two parameters (test arguments and callback)\n *\n * The callback pattern is an alternative to Promise-based async tests.\n *\n * @internal\n * @since 1.0.0\n */\n\n private isCallbackStyle(): boolean {\n if (this.testImplementation.length === 1 && this.testParameters.length === 0)\n return true;\n\n // Or if it expects more parameters (test args + callback)\n return this.testImplementation.length === 2;\n }\n\n private getExecutionStrategy(): TestExecutionType {\n if (isPromise(this.testImplementation)) return TestExecutionType.ASYNC;\n if (this.isCallbackStyle()) return TestExecutionType.CALLBACK;\n\n return TestExecutionType.SYNC;\n }\n\n /**\n * Executes the test function with the appropriate execution strategy based on its type.\n *\n * @param context - The test execution context containing shared state and utilities\n *\n * @returns Promise that resolves when the test execution completes\n *\n * @throws Error - When the test execution fails for any reason\n *\n * @remarks\n * This method determines and applies the correct execution strategy for the test:\n * - For synchronous and async tests, it calls the test implementation directly with the context\n * - For callback-style tests, it delegates to a specialized execution method\n * The method ensures proper 'this' binding by using Function.prototype.apply\n *\n * @internal\n * @see ContextInterface\n * @see TestExecutionType\n *\n * @since 1.0.0\n */\n\n private async executeTestWithContext(context: ContextType<ContextInterface>): Promise<void> {\n const strategy = this.getExecutionStrategy();\n\n switch (strategy) {\n case TestExecutionType.ASYNC:\n case TestExecutionType.SYNC:\n await this.testImplementation.apply(context, this.testParameters);\n break;\n case TestExecutionType.CALLBACK:\n await this.executeCallbackStyleTest(context);\n break;\n }\n }\n\n /**\n * Executes a callback-style test by wrapping it in a Promise.\n *\n * @param context - The test execution context containing shared state and utilities\n *\n * @returns Promise that resolves when the callback is invoked without an error, or rejects when called with an error\n *\n * @throws Error - When the callback is invoked with an error parameter\n *\n * @remarks\n * This method adapts callback-style test functions to work within a Promise-based execution flow.\n * It creates a Promise wrapper around the test function and:\n * 1. Defines a callback function that resolves/rejects the Promise based on error parameter\n * 2. Appends this callback to the original test parameters\n * 3. Invokes the test with proper context binding using Function.prototype.apply\n *\n * The callback function follows Node.js convention with an optional error as first parameter.\n *\n * @internal\n * @see ContextInterface\n *\n * @since 1.0.0\n */\n\n private async executeCallbackStyleTest(context: ContextType<ContextInterface>): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const callbackFn = (error?: string | { message: string }): void => {\n if (error) reject(error);\n resolve();\n };\n\n const allParameters = [ ...this.testParameters ];\n allParameters.push(callbackFn);\n\n this.testImplementation.apply(context, allParameters);\n });\n }\n\n /**\n * Calculates the elapsed execution time of the test in milliseconds.\n *\n * @returns Number representing the test execution duration in milliseconds\n *\n * @remarks\n * This method computes the time difference between now and when the test started execution.\n * It returns 0 if the test has not yet started (when executionStartTime is 0).\n * The time measurement uses the system clock via Date.now().\n *\n * @internal\n * @since 1.0.0\n */\n\n private getExecutionDuration(): number {\n if (this.executionStartTime === 0) return 0;\n\n return Date.now() - this.executionStartTime;\n }\n\n\n private notifyTestStatus(skip: boolean = false, todo: boolean = false): void {\n emitStatus(MessageType.Test, {\n todo: todo,\n skipped: skip,\n ancestry: this.ancestry,\n description: this.description\n });\n }\n\n /**\n * Emits an action event when a test execution has a significant state change.\n *\n * @param type - The type of action event to emit (e.g., start, complete, skip)\n * @param errors - Collection of errors that occurred during test execution\n *\n * @remarks\n * This method broadcasts notifications about test execution actions through the event system.\n * It includes comprehensive information about the test:\n * - Any errors that occurred\n * - Test type as a KindType\n * - The test's ancestry (parent hierarchy)\n * - Execution duration up to the point of notification\n * - Source code location information\n * - The test's description text\n * These action events are typically consumed by reporters and test runners.\n *\n * @internal\n * @see KindType\n * @see EmitActionEventType\n *\n * @since 1.0.0\n */\n\n private notifyTestAction(errors: Array<unknown> = []): void {\n emitEvent(MessageType.Test, {\n errors: <Array<Error>> errors,\n ancestry: this.ancestry,\n duration: this.getExecutionDuration(),\n description: this.description\n });\n }\n\n /**\n * Emits a test failure action event with the associated error information.\n *\n * @param error - The error or errors that caused the test to fail\n *\n * @remarks\n * This method standardizes the reporting of test failures by:\n * 1. Ensuring errors are always passed as an array\n * 2. Converting single errors to array format when needed\n * 3. Delegating to the more general notifyTestAction method with the FAILURE action type\n * It serves as a specialized wrapper around the general action notification system.\n *\n * @internal\n * @see ActionType\n *\n * @since 1.0.0\n */\n\n private notifyTestFailure(error: unknown): void {\n this.notifyTestAction(Array.isArray(error) ? error : [ error ]);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionType } from '@remotex-labs/xjet-expect';\nimport type { TestFlagsType } from '@shared/models/interfaces/test-model.interface';\nimport type { TestCallbackType, TestDirectiveInterface } from '@shared/directives/interfaces/test-directive.interface';\n\n/**\n * Imports\n */\n\nimport { each } from './each.directive';\nimport { TestModel } from '@shared/models/test.model';\nimport { SuiteState } from '@shared/states/suite.state';\nimport { inject } from '@symlinks/services/inject.service';\nimport { getTrimmedStackString } from '@components/location.component';\n\n/**\n * Implementation of the test directive that allows for test definition with chainable modifiers.\n * Acts as a function that can be invoked directly while also providing chainable property access.\n *\n * @template T - Type parameter for the test callback return type\n *\n * @param description - The test description\n * @param block - The test implementation function\n * @param timeout - Optional timeout in milliseconds\n *\n * @returns void\n *\n * @throws Error - When attempting to nest tests inside other tests\n * @throws Error - When using incompatible flag combinations (e.g., skip with only)\n *\n * @remarks\n * This class extends Function to allow it to be invoked as a function while also\n * providing methods and properties. It uses a Proxy to capture function invocations\n * and redirects them to the invoke method.\n *\n * @example\n * ```ts\n * // Basic test\n * test('should work', () => {\n * expect(2 + 2).toBe(4);\n * });\n *\n * // With modifiers\n * test.only('runs exclusively', () => {\n * expect(true).toBe(true);\n * });\n *\n * // Parameterized tests\n * test.each([1, 2, 3])('test with value %s', (value) => {\n * expect(typeof value).toBe('number');\n * });\n * ```\n *\n * @see SuiteState\n * @see TestDirectiveInterface\n *\n * @since 1.0.0\n */\n\nexport class TestDirective extends Function {\n /**\n * Singleton instance of the TestDirective class.\n *\n * @see TestDirectiveInterface\n * @since 1.0.0\n */\n\n private static instance?: TestDirective;\n\n /**\n * Error messages for invalid flag combinations in test configuration.\n *\n * @since 1.0.0\n */\n\n private static readonly ERROR_MESSAGES = {\n SKIP_ONLY: 'Cannot use \"only\" flag on skipped test',\n ONLY_SKIP: 'Cannot use \"skip\" flag on only test',\n SKIP_TODO: 'Cannot use \"todo\" flag on skipped test',\n SKIP_FAILING: 'Cannot use \"failing\" flag on skipped test'\n };\n\n /**\n * Default timeout in milliseconds for test execution\n * @since 1.0.0\n */\n\n private static readonly DEFAULT_TIMEOUT = globalThis.__XJET?.runtime.timeout ?? 5000;\n\n /**\n * Configuration options controlling test behavior\n\n * @see TestFlagsType\n * @since 1.0.0\n */\n\n private options: TestFlagsType = {};\n\n /**\n * @param invokationStack - The precise source code invocationStack where the error occurred\n */\n\n private invocationStack: string = '';\n\n /**\n * Private constructor that initializes the TestDirective instance and returns a proxied version.\n *\n * @returns A Proxy that handles direct function invocation by redirecting to the invoke method\n *\n * @remarks\n * The constructor is private to enforce the singleton pattern. It creates a Proxy\n * that allows the object to be called as a function while maintaining its object properties.\n * When called as a function, the proxy redirects the call to the invoke method.\n *\n * @internal\n * @see invoke\n *\n * @since 1.0.0\n */\n\n private constructor() {\n super();\n\n return new Proxy(this, {\n apply: (target, _, args: [string, FunctionType, number?]): void => {\n const [ description, block, timeout ] = args;\n this.invocationStack = getTrimmedStackString(2);\n\n target.invoke(description, block, [], timeout);\n }\n });\n }\n\n /**\n * Returns the singleton instance of TestDirective, creating it if it doesn't exist\n *\n * @returns The singleton instance of the test directive implementation\n *\n * @remarks\n * This method implements the singleton pattern, ensuring only one instance of the test directive exists\n * throughout the application lifecycle\n *\n * @example\n * ```ts\n * const test = TestDirective.getInstance();\n * test('my test', () => {\n * // test implementation\n * });\n * ```\n *\n * @see TestDirectiveInterface\n *\n * @since 1.0.0\n */\n\n static getInstance(): TestDirectiveInterface {\n if (!TestDirective.instance) {\n TestDirective.instance = new TestDirective();\n }\n\n return TestDirective.instance as unknown as TestDirectiveInterface;\n }\n\n /**\n * Returns the singleton instance of TestDirective, creating it if it doesn't exist.\n *\n * @returns The singleton instance of TestDirective cast to TestDirectiveInterface\n *\n * @remarks\n * This method implements the Singleton pattern to ensure only one instance of\n * TestDirective exists in the application. It creates the instance on the first call\n * and returns the existing instance on subsequent calls.\n *\n * @example\n * ```ts\n * const test = TestDirective.getInstance();\n * test('example test', () => {\n * expect(true).toBe(true);\n * });\n * ```\n *\n * @since 1.0.0\n */\n\n get skip(): this {\n if (this.options.only) throw new Error(TestDirective.ERROR_MESSAGES.ONLY_SKIP);\n this.options.skip = true;\n\n return this;\n }\n\n /**\n * Sets the 'only' flag for this test, making it the only test to run in its suite.\n *\n * @returns This instance with the 'only' flag set\n *\n * @throws Error - When attempting to set 'only' flag on a skipped test\n *\n * @example\n * ```ts\n * test.only('this is the only test that will run', () => {\n * expect(true).toBe(true);\n * });\n * ```\n *\n * @see skip\n * @since 1.0.0\n */\n\n get only(): this {\n if (this.options.skip) throw new Error(TestDirective.ERROR_MESSAGES.SKIP_ONLY);\n this.options.only = true;\n\n return this;\n }\n\n /**\n * Marks a test as a todo item, indicating it's planned but not yet implemented\n *\n * @throws Error - When attempting to use todo flag on a skipped test\n *\n * @remarks\n * Todo tests appear in test reports to remind developers of planned work,\n * but don't execute any test code\n *\n * @example\n * ```ts\n * // Define a todo test\n * test.todo('feature that needs implementation');\n * ```\n *\n * @see TestFlagsType\n *\n * @since 1.0.0\n */\n\n get todo(): this {\n if (this.options.skip) throw new Error(TestDirective.ERROR_MESSAGES.SKIP_TODO);\n this.options.todo = true;\n\n return this;\n }\n\n /**\n * Marks the test as expected to fail.\n *\n * @returns This instance with the 'failing' flag set\n *\n * @throws Error - When attempting to mark a skipped test as failing\n *\n * @example\n * ```ts\n * test.failing('this test is expected to fail', () => {\n * throw new Error('This is an expected failure');\n * });\n * ```\n *\n * @see skip\n * @since 1.0.0\n */\n\n get failing(): this {\n if (this.options.skip) throw new Error(TestDirective.ERROR_MESSAGES.SKIP_FAILING);\n this.options.failing = true;\n\n return this;\n }\n\n /**\n * Creates a parameterized test using template strings.\n *\n * @template T - Array type containing the values to be used in the test\n *\n * @param string - Template string array used to create the test title\n * @param placeholders - Values to be inserted into the template string\n * @returns A callback function for creating the parameterized test\n *\n * @remarks\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * test.each`\n * a | b | expected\n * ${1} | ${1} | ${2}\n * ${2} | ${2} | ${4}\n * `('returns $expected when $a is added to $b', ({a, b, expected}) => {\n * expect(a + b).toBe(expected);\n * });\n * ```\n *\n * @see each.array\n * @since 1.0.0\n */\n\n each<T extends ReadonlyArray<unknown>>(string: TemplateStringsArray, ...placeholders: T): TestCallbackType<Record<string, T[number]>>;\n\n /**\n * Creates a parameterized test using arrays of test cases.\n *\n * @template T - Type representing the test case data structure\n *\n * @param cases - Arrays containing test case values\n * @returns A callback function for creating the parameterized test\n *\n * @remarks\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * test.each(\n * [1, 1, 2],\n * [1, 2, 3],\n * [2, 2, 4]\n * )('adds %i + %i to equal %i', (a, b, expected) => {\n * expect(a + b).toBe(expected);\n * });\n * ```\n *\n * @see each\n * @since 1.0.0\n */\n\n each<T extends Array<unknown> | [unknown]>(...cases: T[]): TestCallbackType<T>; // array\n\n /**\n * Creates a parameterized test using individual test case objects or primitive values.\n *\n * @template T - Type representing the test case data\n *\n * @param args - Test case objects or primitive values\n * @returns A callback function for creating the parameterized test\n *\n * @remarks\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * test.each(\n * { a: 1, b: 1, expected: 2 },\n * { a: 1, b: 2, expected: 3 },\n * { a: 2, b: 2, expected: 4 }\n * )('adds $a + $b to equal $expected', ({ a, b, expected }) => {\n * expect(a + b).toBe(expected);\n * });\n * ```\n *\n * @see each\n * @since 1.0.0\n */\n\n each<T>(...args: readonly T[]): TestCallbackType<T>; // object, and primitives\n\n /**\n * Creates a parameterized test using arrays of primitive values as test cases.\n *\n * @template T - Array type containing the primitive test values\n *\n * @param args - Arrays of primitive values to be used as test cases\n * @returns A callback function for creating the parameterized test\n *\n * @remarks\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * test.each(\n * [1, 2, 3],\n * [4, 5, 9],\n * [6, 7, 13]\n * )('adds %i + %i to equal %i', (a, b, expected) => {\n * expect(a + b).toBe(expected);\n * });\n * ```\n *\n * @see each\n * @since 1.0.0\n */\n\n each<T extends Array<unknown>>(...args: T): TestCallbackType<T[number]>; // primitives\n\n /**\n * Creates a parameterized test using various input formats.\n *\n * @param args - Test case data in array format\n * @returns A callback function for creating the parameterized test\n *\n * @remarks\n * This method delegates to the implementation after binding the invoke method to the current context.\n *\n * The description supports parameter formatting with the following placeholders:\n * - %p - pretty-format output\n * - %s - String value\n * - %d, %i - Number as integer\n * - %f - Floating point value\n * - %j - JSON string\n * - %o - Object representation\n * - %# - Index of the test case\n * - %% - Single percent sign (doesn't consume an argument)\n *\n * Alternatively, you can inject object properties using $variable notation:\n * - $variable - Injects the property value\n * - $variable.path.to.value - Injects nested property values (works only with own properties)\n * - $# - Injects the index of the test case\n * - Note: $variable cannot be combined with printf formatting except for %%\n *\n * @example\n * ```ts\n * test.each(\n * [1, 1, 2],\n * [1, 2, 3],\n * [2, 2, 4]\n * )('adds %i + %i to equal %i', (a, b, expected) => {\n * expect(a + b).toBe(expected);\n * });\n * ```\n *\n * @see each.table\n * @see each.array\n * @since 1.0.0\n */\n\n each(...args: Array<unknown>): TestCallbackType<unknown> {\n return each(this.invoke.bind(this), ...args);\n }\n\n /**\n * Invokes a test with the provided description, test function, arguments, and optional timeout.\n *\n * @param description - The description of the test to be displayed in test reports\n * @param block - The test function containing the test logic\n * @param args - Additional arguments to be passed to the test function\n * @param timeout - Optional timeout value in milliseconds for the test\n *\n * @throws TestNestingError - When attempting to create a nested test\n *\n * @remarks\n * This method handles the complete test registration flow, including validation,\n * creation, registration, and flag management. If no test function is provided,\n * the test will be automatically marked as todo.\n *\n * @example\n * ```ts\n * invoke('should sum two numbers', (a, b) => {\n * expect(sum(a, b)).toBe(a + b);\n * }, [5, 10], 2000);\n * ```\n *\n * @internal\n * @since 1.0.0\n */\n\n invoke(description: string, block: FunctionType, args: Array<unknown> = [], timeout?: number): void {\n this.validateTestNesting(description);\n\n // Auto-set todo flag if no test function provided\n if (!block) {\n this.options.todo = true;\n }\n\n // Create and register the test\n const test = this.createTest(description, block, args, timeout);\n this.registerTest(test, this.invocationStack);\n\n // Reset options after test creation\n this.resetFlags();\n }\n\n /**\n * Validates that tests are not being nested inside other tests.\n *\n * @param description - The description of the test being validated\n *\n * @throws Error - When a test is nested inside another test, with details about both tests\n *\n * @remarks\n * Nesting tests is not supported in the testing framework as it can lead to unpredictable behavior\n * and difficult-to-debug test scenarios.\n *\n * @internal\n * @since 1.0.0\n */\n\n private validateTestNesting(description: string): void {\n const runningTest = inject(SuiteState).test;\n if (runningTest) {\n // set invokation\n throw new Error(`Cannot nest a test inside a test '${ description }' in '${ runningTest.description }'`);\n }\n }\n\n /**\n * Creates a new TestModel with the current configuration\n */\n private createTest(description: string, block: FunctionType, args: Array<unknown>, timeout?: number): TestModel {\n return new TestModel(\n description,\n block,\n timeout ?? TestDirective.DEFAULT_TIMEOUT,\n args,\n { ...this.options } // Clone options to prevent shared references\n );\n }\n\n /**\n * Registers a test with the test suite and sets its execution invocationStack.\n *\n * @param test - The test model to register\n * @param location - The precise source code invocationStack where the error occurred\n *\n * @remarks\n * This method determines the invocationStack where the test was invoked in the source code\n * and attaches that information to the test before adding it to the suite state.\n * Location information is useful for error reporting and test navigation.\n *\n * @internal\n * @since 1.0.0\n */\n\n private registerTest(test: TestModel, location: string): void {\n if (location) {\n test.setExecutionLocation(location);\n }\n inject(SuiteState).addTest(test);\n }\n\n /**\n * Resets all test configuration options to their default state.\n *\n * @returns Nothing\n *\n * @remarks\n * This method clears all previously set options to ensure that configuration\n * from one test doesn't leak into subsequent tests.\n *\n * @internal\n * @since 1.0.0\n */\n\n private resetFlags(): void {\n this.options = {};\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionType } from '@remotex-labs/xjet-expect';\nimport type { DescribeOptionsInterface } from '@shared/models/interfaces/describe-model.interface';\nimport type { DescribeCallbackType } from '@shared/directives/interfaces/describe-directive.interface';\nimport type { DescribeDirectiveInterface } from '@shared/directives/interfaces/describe-directive.interface';\n\n/**\n * Imports\n */\n\nimport { SuiteState } from '@shared/states/suite.state';\nimport { each } from '@shared/directives/each.directive';\nimport { inject } from '@symlinks/services/inject.service';\n\n/**\n * Implementation of the describe directive that allows for test suite definition with chainable modifiers.\n * Acts as a function that can be invoked directly while also providing chainable property access.\n *\n * @param description - The test suite description\n * @param block - The test suite implementation function\n *\n * @throws Error - When attempting to nest describe blocks inside tests\n * @throws Error - When using incompatible flag combinations (e.g., skip with only)\n *\n * @remarks\n * This class extends Function to allow it to be invoked as a function while also\n * providing methods and properties. It uses a Proxy to capture function invocations\n * and redirects them to the invoke method.\n *\n * The describe directive creates a group of related tests, providing organization and structure\n * to test suites. It supports chainable modifiers for customizing test suite behavior,\n * and parameterized testing via the 'each' method.\n *\n * @example\n * ```ts\n * // Basic describe block\n * describe('Calculator', () => {\n * test('should add numbers', () => {\n * expect(2 + 2).toBe(4);\n * });\n * });\n *\n * // With modifiers\n * describe.only('Priority feature', () => {\n * test('important test case', () => {\n * expect(true).toBe(true);\n * });\n * });\n *\n * // With parameterized tests using each\n * describe.each([1, 2, 3])('Math operations for %s', (value) => {\n * test('square', () => {\n * expect(value * value).toBeGreaterThan(0);\n * });\n * });\n * ```\n *\n * @see SuiteState\n * @see DescribeDirectiveInterface\n *\n * @since 1.0.0\n */\n\nexport class DescribeDirective extends Function {\n /**\n * Singleton instance of the DescribeDirective class.\n *\n * @see DescribeDirectiveInterface\n * @since 1.0.0\n */\n\n private static instance: DescribeDirectiveInterface | null = null;\n\n /**\n * Configuration options controlling test suite behavior\n *\n * @see DescribeOptionsInterface\n * @since 1.0.0\n */\n\n private options: DescribeOptionsInterface = {};\n\n /**\n * Private constructor that initializes the DescribeDirective instance and returns a proxied version.\n *\n * @returns A Proxy that handles direct function invocation by redirecting to the invoke method\n *\n * @remarks\n * The constructor is private to enforce the singleton pattern. It creates a Proxy\n * that allows the object to be called as a function while maintaining its object properties.\n * When called as a function, the proxy redirects the call to the invoke method.\n *\n * @internal\n * @see invoke\n *\n * @since 1.0.0\n */\n\n private constructor() {\n super();\n\n return <this>new Proxy(this, {\n apply(target, thisArg, args: [ string, FunctionType ]): void {\n target.invoke(args[0], args[1]);\n }\n });\n }\n\n /**\n * Returns the singleton instance of DescribeDirective, creating it if it doesn't exist\n *\n * @returns The singleton instance of the describe directive implementation\n *\n * @remarks\n * This method implements the singleton pattern, ensuring only one instance of the describe directive\n * exists throughout the application lifecycle.\n *\n * @see DescribeDirectiveInterface\n * @since 1.0.0\n */\n\n static getInstance(): DescribeDirectiveInterface {\n if (!DescribeDirective.instance) {\n DescribeDirective.instance = <DescribeDirectiveInterface><unknown>new DescribeDirective();\n }\n\n return DescribeDirective.instance;\n }\n\n /**\n * Creates a skipped test suite that will be recognized but not executed during test runs\n *\n * @returns The same DescribeDirective instance with skip flag enabled, allowing for method chaining\n * @throws Error - When attempting to combine with 'only' flag which would create conflicting behavior\n *\n * @remarks\n * When applied, the test suite will be marked as skipped in test reports but won't be executed.\n * Cannot be combined with the 'only' modifier due to conflicting behavior.\n *\n * @example\n * ```ts\n * describe.skip('temporarily disabled suite', () => {\n * test('will not run', () => {\n * expect(result).toBe(true);\n * });\n * });\n * ```\n *\n * @see DescribeDirectiveInterface\n * @since 1.0.0\n */\n\n get skip(): this {\n if (this.options.only) throw new Error('Cannot use \"skip\" flag on only test');\n this.options.skip = true;\n\n return this;\n }\n\n /**\n * Creates an exclusive test suite that will run while other non-exclusive suites are skipped\n *\n * @returns The same DescribeDirective instance with only flag enabled, allowing for method chaining\n * @throws Error - When attempting to combine with 'skip' flag which would create conflicting behavior\n *\n * @remarks\n * When applied, only this test suite and other suites marked with 'only' will be executed.\n * This is useful for focusing on specific test suites during development or debugging.\n * Cannot be combined with the 'skip' modifier due to conflicting behavior.\n *\n * @example\n * ```ts\n * describe.only('focus on this suite', () => {\n * test('will run', () => {\n * expect(result).toBe(expectedValue);\n * });\n * });\n * ```\n *\n * @see DescribeDirectiveInterface\n * @since 1.0.0\n */\n\n get only(): this {\n if (this.options.skip) throw new Error('Cannot use \"only\" flag on skipped test');\n this.options.only = true;\n\n return this;\n }\n\n /**\n * Generates parameterized test suites from template strings and placeholders.\n *\n * @template T - An array type extending ReadonlyArray<unknown> that contains the placeholder values\n *\n * @param string - A template string array that defines the structure of test suite descriptions\n * @param placeholders - Values to be inserted into the template strings to create test suites\n *\n * @returns A callback function compatible with Jest's describe method that provides parameterized test data\n *\n * @throws TypeError - When the number of placeholders doesn't match the template string requirements\n *\n * @remarks\n * This method uses tagged template literals to create parameterized test suites.\n * The values provided as placeholders will be passed to describe callbacks as named parameters.\n *\n * The returned function accepts the following parameters:\n * - name: String - The title of the describe block.\n * Generate unique describe titles by positionally injecting parameters with printf formatting:\n * %p - pretty-format.\n * %s - String.\n * %d - Number.\n * %i - Integer.\n * %f - Floating point value.\n * %j - JSON.\n * %o - Object.\n * %# - Index of the test suite.\n * %% - single percent sign ('%'). This does not consume an argument.\n * Or generate unique describe titles by injecting properties of test suite object with $variable:\n * - To inject nested object values use a keyPath i.e. $variable.path.to.value (only works for \"own\" properties)\n * - You can use $# to inject the index of the test suite\n * - You cannot use $variable with the printf formatting except for %%\n * - fn: Function - The describe callback to be run, this is the function that will receive the parameters in each row as function arguments.\n * - timeout (optional): Number - Time in milliseconds to wait for each row before aborting. Default is 5 seconds.\n *\n * @example\n * ```ts\n * describe.each`\n * a | b | expected\n * ${1} | ${1} | ${2}\n * ${1} | ${2} | ${3}\n * ${2} | ${2} | ${4}\n * `('addition: $a + $b = $expected', ({a, b, expected}) => {\n * test('equals expected value', () => {\n * expect(a + b).toBe(expected);\n * });\n * });\n * ```\n *\n * @see DescribeCallbackType\n * @since 1.0.0\n */\n\n each<T extends ReadonlyArray<unknown>>(string: TemplateStringsArray, ...placeholders: T): DescribeCallbackType<Record<string, T[number]>>;\n\n /**\n * Creates parameterized test suites from arrays of test case values.\n *\n * @template T - A type extending Array<unknown> or [unknown] that contains the test case values\n *\n * @param cases - Arrays of values representing individual test cases\n *\n * @returns A callback function compatible with Jest's describe method that provides parameterized test data\n *\n * @throws TypeError - When the test cases have inconsistent formats or types\n *\n * @remarks\n * This method allows creating parameterized test suites from arrays of values.\n * Each array provided as a case will be passed to the describe callback as separate arguments.\n *\n * The returned function accepts the following parameters:\n * - name: String - The title of the describe block.\n * Generate unique describe titles by positionally injecting parameters with printf formatting:\n * %p - pretty-format.\n * %s - String.\n * %d - Number.\n * %i - Integer.\n * %f - Floating point value.\n * %j - JSON.\n * %o - Object.\n * %# - Index of the test suite.\n * %% - single percent sign ('%'). This does not consume an argument.\n * Or generate unique describe titles by injecting properties of test suite object with $variable:\n * - To inject nested object values use a keyPath i.e. $variable.path.to.value (only works for \"own\" properties)\n * - You can use $# to inject the index of the test suite\n * - You cannot use $variable with the printf formatting except for %%\n * - fn: Function - The describe callback to be run, this is the function that will receive the parameters in each row as function arguments.\n * - timeout (optional): Number - Time in milliseconds to wait for each row before aborting. Default is 5 seconds.\n *\n * @example\n * ```ts\n * describe.each(\n * [1, 1, 2],\n * [1, 2, 3],\n * [2, 2, 4]\n * )('addition: %d + %d = %d', (a, b, expected) => {\n * test('equals expected value', () => {\n * expect(a + b).toBe(expected);\n * });\n * });\n * ```\n *\n * @see DescribeCallbackType\n * @since 1.0.0\n */\n\n each<T extends Array<unknown> | [ unknown ]>(...cases: T[]): DescribeCallbackType<T>; // array\n\n /**\n * Creates parameterized test suites from individual test case values.\n *\n * @template T - The type of test case values (objects or primitives)\n *\n * @param args - Individual test case values to be used in the test suites\n *\n * @returns A callback function compatible with Jest's describe method that provides parameterized test data\n *\n * @throws TypeError - When the test cases have incompatible types\n *\n * @remarks\n * This method allows creating parameterized test suites from individual values.\n * Each value provided as an argument will be passed to the describe callback.\n * This overload is particularly useful for objects and primitive values.\n *\n * The returned function accepts the following parameters:\n * - name: String - The title of the describe block.\n * Generate unique describe titles by positionally injecting parameters with printf formatting:\n * %p - pretty-format.\n * %s - String.\n * %d - Number.\n * %i - Integer.\n * %f - Floating point value.\n * %j - JSON.\n * %o - Object.\n * %# - Index of the test suite.\n * %% - single percent sign ('%'). This does not consume an argument.\n * Or generate unique describe titles by injecting properties of test suite object with $variable:\n * - To inject nested object values use a keyPath i.e. $variable.path.to.value (only works for \"own\" properties)\n * - You can use $# to inject the index of the test suite\n * - You cannot use $variable with the printf formatting except for %%\n * - fn: Function - The describe callback to be run, this is the function that will receive the test case value as an argument.\n * - timeout (optional): Number - Time in milliseconds to wait for each test case before aborting. Default is 5 seconds.\n *\n * @example\n * ```ts\n * describe.each(\n * { a: 1, b: 1, expected: 2 },\n * { a: 1, b: 2, expected: 3 },\n * { a: 2, b: 2, expected: 4 }\n * )('addition: $a + $b = $expected', ({ a, b, expected }) => {\n * test('equals expected value', () => {\n * expect(a + b).toBe(expected);\n * });\n * });\n * ```\n *\n * @see DescribeCallbackType\n * @since 1.0.0\n */\n\n each<T>(...args: readonly T[]): DescribeCallbackType<T>; // object, and primitives\n\n /**\n * Creates parameterized test suites from individual objects or primitive values.\n *\n * @template T - The type of test case values\n *\n * @param args - Individual objects or primitive values to be used as test cases\n *\n * @returns A callback function compatible with Jest's describe method\n *\n * @remarks\n * This method creates parameterized test suites where each argument represents a complete test case.\n * Useful for testing with objects or primitive values that each represent a single test scenario.\n *\n * The returned function accepts the following parameters:\n * - name: String - The title of the describe block.\n * Generate unique describe titles by positionally injecting parameters with printf formatting:\n * %p - pretty-format.\n * %s - String.\n * %d - Number.\n * %i - Integer.\n * %f - Floating point value.\n * %j - JSON.\n * %o - Object.\n * %# - Index of the test suite.\n * %% - single percent sign ('%'). This does not consume an argument.\n * Or generate unique describe titles by injecting properties of test suite object with $variable:\n * - To inject nested object values use a keyPath i.e. $variable.path.to.value (only works for \"own\" properties)\n * - You can use $# to inject the index of the test suite\n * - You cannot use $variable with the printf formatting except for %%\n * - fn: Function - The describe callback to be run, this is the function that will receive the test case value as an argument.\n * - timeout (optional): Number - Time in milliseconds to wait for each test case before aborting. Default is 5 seconds.\n *\n * @example\n * ```ts\n * describe.each(\n * { input: 'hello', expected: 'HELLO' },\n * { input: 'world', expected: 'WORLD' }\n * )('toUpperCase($input) \u2192 $expected', (testCase) => {\n * test('converts correctly', () => {\n * expect(testCase.input.toUpperCase()).toBe(testCase.expected);\n * });\n * });\n * ```\n *\n * @see DescribeCallbackType\n * @since 1.0.0\n */\n\n each<T extends Array<unknown>>(...args: T): DescribeCallbackType<T[number]>; // primitives\n\n /**\n * Creates parameterized test suites by delegating to the external 'each' function.\n *\n * @param args - Test case values to be used in the parameterized test suites\n *\n * @returns A callback function compatible with Jest's describe method\n *\n * @remarks\n * This method serves as a bridge between the describe context and the external 'each' utility.\n * It binds the current context's 'invoke' method and passes it along with the test cases\n * to the external 'each' function, which handles the creation of parameterized test suites.\n *\n * The returned function has the same behavior as the one returned by the external 'each' function,\n * but ensures that tests are executed within the proper describe context.\n *\n * The returned function accepts the following parameters:\n * - name: String - The title of the describe block, which can include parameter placeholders\n * - fn: Function - The describe callback function that will receive the test case values\n * - timeout (optional): Number - Time in milliseconds before test timeout\n *\n * @example\n * ```ts\n * // Internal implementation used when calling describe.each\n * // Users don't directly call this method, but rather use:\n * describe.each([1, 2, 3])('test with %d', (num) => {\n * test('works with ' + num, () => {\n * expect(num).toBeDefined();\n * });\n * });\n * ```\n *\n * @internal\n * @since 1.0.0\n */\n\n each(...args: Array<unknown>): DescribeCallbackType<unknown> {\n return each(this.invoke.bind(this), ...args);\n }\n\n /**\n * Executes a describe block with the given description and function.\n *\n * @param description - The title of the describe block\n * @param block - The function containing the tests to be run within this describe block\n * @param args - Optional array of arguments to pass to the block function\n *\n * @throws Error - When attempting to nest a describe block inside a test\n *\n * @remarks\n * This method is the core implementation for creating test suites in the testing framework.\n * It registers a describe block with the suite state manager and applies any options\n * that were set on the describe object before this method was called.\n *\n * This method is primarily called internally by the testing framework and\n * typically not meant to be called directly by users.\n *\n * @example\n * ```ts\n * // Internal implementation example - not for direct use\n * const describeObj = new Describe();\n * describeObj.invoke('My test suite', () => {\n * // Test implementations\n * });\n * ```\n *\n * @internal\n * @since 1.0.0\n */\n\n invoke(description: string, block: FunctionType, args: Array<unknown> = []): void {\n const suiteState = inject(SuiteState);\n const runningTest = suiteState.test;\n\n if (runningTest) {\n throw new Error(\n `Cannot nest a describe inside a test '${ description }' in '${ runningTest.description }'`\n );\n }\n\n suiteState.addDescribe(description, block, this.options, args);\n // Reset options after use\n this.options = {};\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FnMockInterface } from '@shared/mock/interfaces/fn-mock.interface';\nimport type { ConstructorLikeType, FunctionLikeType } from '@remotex-labs/xjet-expect';\n\n/**\n * Imports\n */\n\nimport { MockState } from '@shared/states/mock.state';\nimport { ExecutionError } from '@shared/errors/execution.error';\n\n/**\n * Retrieves the parent object of the specified function if it exists within the global context.\n *\n * @template FunctionLikeType - The type representing the input function.\n *\n * @param fn - The function whose parent object is to be retrieved.\n * @returns The parent object containing the function, or `undefined` if no such object is found.\n *\n * @remarks\n * This method searches for the parent object of a given function within the global context\n * by checking if the function name exists as a key of an object in the global scope.\n * If the function exists directly in the global scope, the global object itself is returned.\n *\n * @since 1.0.0\n */\n\nexport function getParentObject(fn: FunctionLikeType): Record<string, unknown> | undefined {\n if (fn.name in globalThis) return globalThis;\n\n const name = fn.name;\n const globalElements: typeof globalThis = globalThis;\n\n for (const key of Object.keys(globalThis) as unknown as (keyof typeof globalThis)[]) {\n const val = <Record<string, unknown>> globalElements[key];\n if(typeof val !== 'function' && typeof val !== 'object') continue;\n if (val && name in val) {\n return globalElements[key];\n }\n }\n\n return undefined;\n}\n\n/**\n * Creates a mock function interface with the specified implementation and optional restore function.\n *\n * @template ReturnType - The return type of the mocked function.\n * @template Context - The context type that the mocked function binds to.\n * @template Args - The argument type of the mocked function. Defaults to an array of unknown values.\n *\n * @param implementation - An optional implementation of the mocked function.\n * @param restore - An optional restore function used to reset the mock.\n * @returns A mocked function interface with the specified behaviors.\n *\n * @remarks\n * This function creates a mock function handler, typically used in testing scenarios.\n * You can provide an implementation for the mock behavior or specify a restore\n * handler for resetting the mock's state.\n *\n * @example\n * ```ts\n * // Creating a mock with a custom implementation\n * const mock = xJet.fn((x: number) => x * 2);\n * console.log(mock(5)); // 10\n *\n * // Creating a mock with a restore function\n * const mockWithRestore = xJet.fnImplementation(undefined, () => { console.log('Restored!'); });\n * mockWithRestore.restore(); // \"Restored!\"\n * ```\n *\n * @see MockState\n *\n * @since 1.0.0\n */\n\nexport function fnImplementation<ReturnType, Args extends Array<unknown>, Context>(\n implementation?: FunctionLikeType<ReturnType, Args, Context>,\n restore?: FunctionLikeType<void>\n): FnMockInterface<ReturnType, Args, Context> {\n const instance = new MockState(implementation, restore, 'xJet.fn()');\n\n return <FnMockInterface<ReturnType, Args, Context>> instance;\n}\n\n/**\n * Creates a mock instance for the given method or constructor.\n *\n * @template Method - The type of the method being mocked.\n * @template Context - The `this` context type of the method.\n * @template Args - The types of the arguments accepted by the method.\n *\n * @param method - The method or constructor to mock. This can either be a function-like type or a\n * constructor-like type.\n * @returns A `MockState` instance associated with the provided method, allowing for capturing\n * interactions and controlling behavior during testing.\n *\n * @remarks\n * This method identifies whether the provided method is a function or constructor and creates\n * a suitable mock state. If the method is already mocked, the existing mock state is returned.\n * Throws an error if the method does not belong to an object or if it has an invalid type.\n *\n * @example\n * ```ts\n * // Mocking a regular method\n * function greet(name: string) {\n * return `Hello, ${ name }`;\n * }\n *\n * const greetMock = xJet.mock(greet);\n * greetMock.mockImplementation(() => 'Hi!');\n * console.log(greet('World')); // \"Hi!\"\n *\n * // Mocking a constructor\n * class Person {\n * constructor(public name: string) {}\n * }\n * const personMock = xJet.mock(Person);\n * personMock.mockImplementation((name: string) => ({ name: `${name} (mocked)` }));\n * const person = new Person('Alice');\n * console.log(person.name); // \"Alice (mocked)\"\n *\n * // Restoring the original method\n * greetMock.mockRestore();\n * console.log(greet('World')); // \"Hello, World\"\n * ```\n *\n * @since 1.0.0\n */\n\nexport function mockImplementation<Method, Args extends Array<unknown>, Context>(\n method: FunctionLikeType<Method, Args, Context> | ConstructorLikeType<Method, Args>\n): MockState<Method, Args, Context> {\n if ((method as unknown as MockState).xJetMock)\n return <MockState<Method, Args, Context>> <unknown> method;\n\n let parentObject = getParentObject(<FunctionLikeType> method);\n if (!parentObject) {\n throw new ExecutionError('Method is not part of an object');\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(parentObject, method.name);\n if (descriptor?.get && !descriptor.configurable) {\n if ('default' in parentObject && (<Record<string, unknown>> parentObject.default)[method.name] === method) {\n parentObject = <typeof parentObject> parentObject.default;\n }\n }\n\n // todo bind to class constructor\n const originalMethod = parentObject[method.name];\n if (method.prototype && !Object.getOwnPropertyDescriptor(method, 'prototype')?.writable) {\n const mock = new MockState<Method, Args, Context>(\n (...args: Args) => new (method as ConstructorLikeType<Method, Args>)(...args),\n () => {\n parentObject[method.name] = originalMethod;\n }\n );\n\n parentObject[method.name] = mock;\n MockState.mocks.push(<MockState> <unknown> mock);\n\n return parentObject[method.name] as MockState<Method, Args, Context>;\n }\n\n if (typeof method === 'function') {\n const mock = new MockState(<FunctionLikeType> method, () => {\n parentObject[method.name] = originalMethod;\n });\n\n parentObject[method.name] = mock;\n MockState.mocks.push(<MockState> <unknown> mock);\n\n return parentObject[method.name] as MockState<Method, Args, Context>;\n }\n\n throw new ExecutionError('Invalid method type');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ContextType, FunctionType } from '@remotex-labs/xjet-expect';\nimport type { CallbackHandlerType } from '@shared/models/interfaces/hook-model.interface';\n\n\n/**\n * Imports\n */\n\nimport { isPromise } from '@remotex-labs/xjet-expect';\nimport { withTimeout } from '@components/timeout.component';\n\n/**\n * Represents a model for managing and executing hook functions with a specified timeout.\n * Provides functionality for associating invocation locations and handling errors during execution.\n *\n * @remarks\n * This class ensures that hooks are executed with proper timeout enforcement\n * and supports both synchronous and asynchronous hook functions.\n * It throws an error if an asynchronous hook\n * incorrectly uses a \"done\" callback or if it fails to complete execution within the specified timeout.\n *\n * @since 1.0.0\n */\n\nexport class HookModel {\n /**\n * Represents the current location of an invocation within the application or a fallback to undefined.\n *\n * @remarks\n * This variable is designed\n * to hold the interface representing the invocation's location for tracking.\n * If no invocation location is available, it defaults to undefined.\n *\n * @since 1.0.0\n */\n\n private location: string = '';\n\n /**\n * Constructs an instance of the class.\n *\n * @param hookFunction - The callback function that will be executed based on specific conditions.\n * @param timeout - The time in milliseconds before the callback function is triggered.\n * @throws Will throw an error if the provided timeout value is negative or invalid.\n *\n * @remarks This constructor sets up the necessary callback function and timeout configuration for the instance.\n *\n * @since 1.0.0\n */\n\n constructor(\n private readonly hookFunction: CallbackHandlerType, private readonly timeout: number\n ) {}\n\n /**\n * Sets the location of the invocation based on the provided location object.\n *\n * @param location - An object implementing the `InvocationLocationType` or `undefined`\n * to reset the location.\n *\n * @remarks\n * This method assigns a new location value to the current location of the invocation.\n * Passing `undefined` will clear the current location.\n *\n * @since 1.0.0\n */\n\n setLocation(location: string): void {\n this.location = location;\n }\n\n /**\n * Executes a hook function with a timeout mechanism.\n *\n * @param context - The context object passed to the hook function, containing execution-specific information.\n * @return A promise that resolves when the hook function completes its execution successfully.\n *\n * @throws TimeoutError - If the hook function does not call `done()` within the specified timeout duration.\n *\n * @remarks This method concurrently runs the hook function and a timeout check, ensuring that execution does not\n * exceed the predefined timeout.\n * If the timeout is reached without the hook function completing, an ` TimeoutError ` is thrown.\n *\n * @since 1.0.0\n */\n\n async run(context: ContextType<unknown>): Promise<void> {\n return withTimeout<void>(\n this.executeHook(this.hookFunction, context),\n this.timeout,\n 'hook while waiting for \\'done()\\' to be called.',\n this.location\n );\n }\n\n /**\n * Executes a given hook function, handling both synchronous and asynchronous hooks,\n * with or without a callback mechanism.\n *\n * @param hook - The function representing the hook to be executed.\n * It Can be a synchronous or asynchronous function.\n * @param context - An object to be used as the `this` context\n * when invoking the hook function.\n\n * @remarks This method ensures correct execution and error handling\n * for both callback-based and promise-based hooks.\n *\n * @since 1.0.0\n */\n\n private async executeHook(hook: FunctionType, context: unknown): Promise<void> {\n if (isPromise(hook) && hook.length > 0) {\n throw new Error(`Async hook '${ hook.name }' should not use 'done' callback.`);\n }\n\n if (hook.length > 0) {\n return this.executeCallbackHook(hook, context);\n }\n\n return hook.call(context);\n }\n\n /**\n * Executes a callback-style hook by wrapping it in a Promise\n *\n * @param hook - The callback hook function to execute\n * @param context - Execution context to bind to the hook function\n * @returns A Promise that resolves when the hook completes or rejects when it fails\n *\n * @throws Error - When the hook callback is invoked with an error parameter\n *\n * @remarks This method converts traditional Node.js-style callback patterns (error-first callbacks)\n * into Promise-based async/await compatible functions. The hook function receives a done callback\n * as its argument and must call it to signal completion.\n *\n * @example\n * ```ts\n * const callbackHook = (done) => {\n * setTimeout(() => done(), 100);\n * };\n *\n * await executeCallbackHook(callbackHook, this);\n * ```\n *\n * @see isPromise\n * @since 1.0.0\n */\n\n private executeCallbackHook(hook: FunctionType, context: unknown): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n hook.call(context, (error?: string | { message: string }): void => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FunctionType } from '@remotex-labs/xjet-expect';\n\n/**\n * Imports\n */\n\nimport { HookModel } from '@shared/models/hook.model';\nimport { SuiteState } from '@shared/states/suite.state';\nimport { inject } from '@symlinks/services/inject.service';\nimport { getTrimmedStackString } from '@components/location.component';\nimport { HookType } from '@shared/models/constants/hook.model.constants';\n\n/**\n * Default timeout\n */\n\nconst DEFAULT_TIMEOUT = globalThis.__XJET?.runtime.timeout ?? 5000;\n\n/**\n * Creates and registers a hook with the current test suite\n *\n * @param hookType - Type of hook to register\n * @param callback - Function to execute for this hook\n * @param location - The precise source code location where the error occurred\n * @param timeout - Maximum execution time in milliseconds\n * @returns void\n *\n * @example\n * ```ts\n * createHook(HookType.BEFORE_EACH, () => {\n * // Setup code to run before each test\n * resetTestDatabase();\n * }, 10000);\n * ```\n *\n * @see HookType\n * @see HookModel\n * @see SuiteState\n *\n * @since 1.0.0\n */\n\nexport function createHook(hookType: HookType, callback: FunctionType, location: string, timeout: number = DEFAULT_TIMEOUT): void {\n const hook = new HookModel(callback, timeout);\n hook.setLocation(location);\n inject(SuiteState).describe.addHook(hookType, hook);\n}\n\n/**\n * Registers an after-all hook to be executed once after all tests in a suite have completed\n *\n * @param callback - Function to execute after all tests in the suite\n * @param timeout - Maximum execution time in milliseconds\n * @returns void\n *\n * @throws Error - If called outside a test suite context\n *\n * @remarks\n * This function is a wrapper around the createHook function, specifically for creating AFTER_ALL hooks.\n * After-all hooks are useful for cleanup operations that should occur once after all tests complete.\n *\n * @example\n * ```ts\n * afterAllDirective(() => {\n * // Teardown code to run after all tests\n * disconnectFromDatabase();\n * }, 10000);\n * ```\n *\n * @see createHook\n * @see HookType.AFTER_ALL\n *\n * @since 1.0.0\n */\n\nexport function afterAllDirective(callback: FunctionType, timeout?: number): void {\n createHook(HookType.AFTER_ALL, callback, getTrimmedStackString(), timeout);\n}\n\n/**\n * Registers a before-all hook to be executed once before any tests in a suite run\n *\n * @param callback - Function to execute before any tests in the suite\n * @param timeout - Maximum execution time in milliseconds\n * @returns void\n *\n * @throws Error - If called outside a test suite context\n *\n * @remarks\n * This function is a wrapper around the createHook function, specifically for creating BEFORE_ALL hooks.\n * Before-all hooks are useful for setup operations that should occur once before any tests run.\n *\n * @default timeout 5000\n *\n * @example\n * ```ts\n * beforeAllDirective(() => {\n * // Setup code to run before any tests\n * initializeTestDatabase();\n * }, 10000);\n * ```\n *\n * @see createHook\n * @see HookType.BEFORE_ALL\n *\n * @since 1.0.0\n */\n\nexport function beforeAllDirective(callback: FunctionType, timeout?: number): void {\n createHook(HookType.BEFORE_ALL, callback, getTrimmedStackString(), timeout);\n}\n\n/**\n * Registers an after-each hook to be executed after each test in a suite completes\n *\n * @param callback - Function to execute after each test\n * @param timeout - Maximum execution time in milliseconds\n * @returns void\n *\n * @throws Error - If called outside a test suite context\n *\n * @remarks\n * This function is a wrapper around the createHook function, specifically for creating AFTER_EACH hooks.\n * After-each hooks run after each test case and are useful for cleanup operations that should occur\n * after every individual test.\n *\n * @default timeout 5000\n *\n * @example\n * ```ts\n * afterEachDirective(() => {\n * // Cleanup code to run after each test\n * resetTestState();\n * }, 8000);\n * ```\n *\n * @see createHook\n * @see HookType.AFTER_EACH\n *\n * @since 1.0.0\n */\n\nexport function afterEachDirective(callback: FunctionType, timeout?: number): void {\n createHook(HookType.AFTER_EACH, callback, getTrimmedStackString(), timeout);\n}\n\n/**\n * Registers a before-each hook to be executed before each test in a suite runs\n *\n * @param callback - Function to execute before each test\n * @param timeout - Maximum execution time in milliseconds\n *\n * @returns void\n *\n * @throws Error - If called outside a test suite context\n *\n * @remarks\n * This function is a wrapper around the createHook function, specifically for creating BEFORE_EACH hooks.\n * Before-each hooks run before each test case and are useful for setup operations that should occur\n * before every individual test.\n *\n * @default timeout 5000\n *\n * @example\n * ```ts\n * beforeEachDirective(() => {\n * // Setup code to run before each test\n * prepareTestEnvironment();\n * }, 8000);\n * ```\n *\n * @see createHook\n * @see HookType.BEFORE_EACH\n *\n * @since 1.0.0\n */\n\nexport function beforeEachDirective(callback: FunctionType, timeout?: number): void {\n createHook(HookType.BEFORE_EACH, callback, getTrimmedStackString(), timeout); // Fixed a bug here - was using AFTER_ALL\n}\n", "/**\n * Imports\n */\n\nimport { xExpect } from '@remotex-labs/xjet-expect';\nimport { MockState } from '@shared/states/mock.state';\nimport { SuiteState } from '@shared/states/suite.state';\nimport { inject } from '@symlinks/services/inject.service';\nimport * as logging from '@shared/components/log.component';\nimport { spyOnImplementation } from '@shared/mock/spy.mock';\nimport * as FakeTimer from '@shared/services/timer.service';\nimport { TestDirective } from '@shared/directives/test.directive';\nimport { DescribeDirective } from '@shared/directives/describe.directive';\nimport { fnImplementation, mockImplementation } from '@shared/mock/fn.mock';\nimport { afterAllDirective, afterEachDirective } from '@shared/directives/hook.directive';\nimport { beforeAllDirective, beforeEachDirective } from '@shared/directives/hook.directive';\n\n/**\n * Clears the specified mock method on all registered mocks\n *\n * @param method - The method name to clear on all mock instances\n *\n * @throws TypeError - When called with an invalid method name\n *\n * @remarks\n * This utility function iterates through all mocks registered in the MockState\n * and calls the specified method on each one, effectively performing a batch operation\n * across all mock instances.\n *\n * @example\n * ```ts\n * // Clear all recorded calls on all mocks\n * clearMocks('resetHistory');\n *\n * // Reset behavior on all mocks\n * clearMocks('resetBehavior');\n * ```\n *\n * @see MockState\n *\n * @since 1.0.0\n */\n\nfunction clearMocks(method: keyof MockState): void {\n const mock = [ ...MockState.mocks ];\n mock.map((mock) => {\n mock[method]();\n });\n}\n\n/**\n * Set global\n */\n\nconst setupGlobals = (): void => {\n const globals = globalThis as { [key: string]: unknown; };\n\n globals.xJet = {\n /**\n * Mock\n */\n\n fn: fnImplementation,\n mock: mockImplementation,\n spyOn: spyOnImplementation,\n clearAllMocks: (): void => clearMocks('mockClear'),\n resetAllMocks: (): void => clearMocks('mockReset'),\n restoreAllMocks: (): void => clearMocks('mockRestore'),\n\n /**\n * Logs\n */\n\n log: logging.log,\n info: logging.info,\n warn: logging.warn,\n error: logging.error,\n debug: logging.debug,\n\n /**\n * Timers\n */\n\n runAllTimers: FakeTimer.runAllTimers,\n useFakeTimers: FakeTimer.useFakeTimers,\n useRealTimers: FakeTimer.useRealTimers,\n advanceTimersByTime: FakeTimer.advanceTimersByTime,\n runOnlyPendingTimers: FakeTimer.runOnlyPendingTimers\n };\n\n globals.expect = xExpect;\n globals.state = inject(SuiteState);\n globals.it = TestDirective.getInstance();\n globals.test = TestDirective.getInstance();\n globals.describe = DescribeDirective.getInstance();\n globals.afterAll = afterAllDirective;\n globals.beforeAll = beforeAllDirective;\n globals.afterEach = afterEachDirective;\n globals.beforeEach = beforeEachDirective;\n};\n\nsetupGlobals();\n"],
|
|
6
|
+
"mappings": "64DG2BO,IAAMA,GAAgB,CACzB,IAAK,CAAE,EAAG,EAAG,EACb,KAAM,CAAE,EAAG,EAAG,EACd,MAAO,CAAE,EAAG,CAAE,EACd,OAAQ,CAAE,EAAG,EAAG,EAChB,QAAS,CAAE,EAAG,EAAG,CACrB,EA2BaC,GAAuB,CAChC,IAAK,CAAE,GAAI,EAAG,EACd,KAAM,CAAE,GAAI,EAAG,EACf,KAAM,CAAE,GAAI,EAAG,EACf,KAAM,CAAE,GAAI,EAAG,EACf,MAAO,CAAE,GAAI,EAAG,EAChB,MAAO,CAAE,GAAI,EAAG,EAChB,MAAO,CAAE,GAAI,EAAG,EAChB,OAAQ,CAAE,GAAI,EAAG,EACjB,QAAS,CAAE,GAAI,EAAG,EAClB,UAAW,CAAE,GAAI,EAAG,EACpB,WAAY,CAAE,GAAI,EAAG,EACrB,WAAY,CAAE,GAAI,EAAG,EACrB,YAAa,CAAE,GAAI,EAAG,EACtB,YAAa,CAAE,GAAI,EAAG,EACtB,YAAa,CAAE,GAAI,EAAG,EACtB,aAAc,CAAE,GAAI,EAAG,EACvB,cAAe,CAAE,GAAI,EAAG,EACxB,SAAU,CAAE,WAAY,EAAG,EAC3B,UAAW,CAAE,WAAY,EAAG,EAC5B,UAAW,CAAE,UAAW,EAAG,EAC3B,WAAY,CAAE,WAAY,EAAG,EAC7B,WAAY,CAAE,WAAY,EAAG,EAC7B,WAAY,CAAE,WAAY,EAAG,EAC7B,WAAY,CAAE,WAAY,EAAG,EAC7B,YAAa,CAAE,WAAY,EAAG,EAC9B,YAAa,CAAE,WAAY,EAAG,EAC9B,YAAa,CAAE,WAAY,EAAG,EAC9B,aAAc,CAAE,WAAY,EAAG,EAC/B,qBAAsB,CAAE,WAAY,EAAG,CAC3C,EA4Ba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cC,GACd,MAAeC,GACf,MAAeC,GAMf,aAAwBC,GACxB,cAAyBC,GACzB,cAAyBC,GACzB,oBAA+BC,GAC/B,qBAAgCC,EACpC,EAEAb,EAAQ,OAASc,GACjBd,EAAQ,MAAQe,EAAOC,CAAU,EACjChB,EAAQ,GAAKiB,GAAc,YAAY,EACvCjB,EAAQ,KAAOiB,GAAc,YAAY,EACzCjB,EAAQ,SAAWkB,GAAkB,YAAY,EACjDlB,EAAQ,SAAWmB,GACnBnB,EAAQ,UAAYoB,GACpBpB,EAAQ,UAAYqB,GACpBrB,EAAQ,WAAasB,EACzB,EA7CqB,gBA+CrBvB,GAAa",
|
|
7
|
+
"names": ["ansiModifiers", "ansiForegroundColors", "ansiBackgroundColors", "styles", "ESC", "ESC_END", "wrapWithAnsi", "codes", "text", "codesLength", "endCodes", "startCodes", "i", "rgbCode", "type", "r", "g", "b", "code", "reset", "hexToRgb", "hex", "cleanHex", "createXtermChain", "formatter", "__name", "args", "strings", "values", "combined", "acc", "str", "colorHandlers", "target", "prop", "xterm", "isA", "constructor", "value", "__name", "hasKey", "obj", "key", "isAsymmetric", "asymmetricMatch", "a", "b", "asymmetricA", "asymmetricB", "deepEquals", "strictCheck", "val", "i", "equals", "aKeys", "bKeys", "asymmetricResult", "serializesError", "error", "json", "isPromise", "candidate", "INDENT", "serializePrimitive", "element", "serializeMapKey", "appendLines", "source", "target", "isLast", "indent", "last", "serializeMap", "map", "lines", "seen", "entries", "keyStr", "subLines", "serializeValue", "serializeArray", "arr", "item", "serializeSet", "set", "serializeBuffer", "values", "comma", "serializeTypedArray", "name", "serializeObject", "primitive", "stringLines", "line", "serializeError", "serialize", "DiffTypes", "countCommonForward", "count", "countCommonBackward", "backtrackFlat", "trace", "offset", "dFinal", "x", "y", "result", "d", "vPrev", "k", "prevK", "kMinus", "kPlus", "prevKIndex", "prevX", "prevY", "findMiddleSnake", "n", "m", "max", "v", "vCopy", "kIndex", "diffSequence", "prefixLen", "isFullyEqual", "suffixLen", "createDiff", "aLength", "bLength", "isMatch", "foundSubsequence", "context", "diffStringsRaw", "aIndex", "bIndex", "pendingInsert", "pendingDelete", "diffs", "pushDiff", "type", "text", "iA", "iB", "nCommon", "aCommon", "bCommon", "diffLinesRaw", "hasCommaA", "hasCommaB", "cleanupSemantic", "delBuf", "insBuf", "flushBuffers", "prevType", "nextType", "isEdit", "t", "ch", "DIM", "xterm", "MARK", "RECEIVED", "EXPECTED", "CYAN", "INVERSE", "TITLE", "getType", "normalizeStrings", "clean", "resultA", "resultB", "normalizeArrays", "aResult", "bResult", "len", "normalizeAsymmetric", "normalizeObjects", "keys", "aType", "bType", "diffStrings", "aLines", "bLines", "lineA", "lineB", "expectedLine", "receivedLine", "diffArgs", "diffComponent", "aNormalize", "bNormalize", "xJetBaseError", "message", "composeStatement", "options", "comment", "assertionChain", "expectedLabels", "receivedLabeled", "parts", "xJetTypeError", "xJetExpectError", "ensureType", "types", "label", "ensureNotNullish", "serializeOneLine", "handleFailure", "pass", "info", "assertion", "handleDiffFailure", "handleComparisonFailure", "operator", "space", "getThrown", "err", "e", "hasMessage", "isError", "buildInfo", "expectedLabel", "expectedValue", "thrown", "asymmetric", "toThrowExpectedClass", "expected", "handleNot", "handleInfo", "toThrowExpectedString", "toThrowExpectedRegExp", "toThrowExpectedAsymmetric", "toThrowExpectedObject", "toThrow", "toHaveLength", "length", "received", "toMatch", "ensurePositiveNumber", "handleNumericComparison", "toBeCloseTo", "precision", "actual", "receivedDifference", "expectedDifference", "expectedDifferenceStr", "not", "notLabel", "details", "toBeGreaterThan", "toBeGreaterThanOrEqual", "toBeLessThan", "toBeLessThanOrEqual", "ensureMock", "serializeCallArgs", "args", "arg", "serializeList", "items", "symbol", "sliceArgs", "maxLines", "start", "highlightIndex", "total", "end", "width", "symbolPad", "num", "prefix", "diff", "serializeHighlightedCalls", "calls", "highlights", "results", "idx", "serializeCallList", "returns", "serializeReturnList", "toHaveBeenCalled", "toHaveBeenCalledTimes", "toHaveBeenCalledWith", "indices", "call", "index", "toHaveBeenLastCalledWith", "callIndex", "toHaveBeenNthCalledWith", "nthCall", "toHaveReturned", "resultsCount", "toHaveReturnedTimes", "toHaveLastReturnedWith", "toHaveNthReturnedWith", "toBe", "note", "toEqual", "toBeNull", "toBeUndefined", "toBeNaN", "toBeTruthy", "toBeFalsy", "toBeDefined", "toHaveProperty", "path", "current", "pathFound", "pathArray", "segment", "toBeInstanceOf", "instance", "toContain", "receivedType", "toContainEqual", "toMatchObject", "Matchers", "AbstractPattern", "isInverse", "AnyPattern", "_AnyPattern", "ArrayOfPattern", "_ArrayOfPattern", "allMatch", "matcher", "CloseToPattern", "_CloseToPattern", "inverse", "precisionLabel", "sample", "AnythingPattern", "_AnythingPattern", "StringMatchingPattern", "_StringMatchingPattern", "expectedType", "ArrayContainingPattern", "_ArrayContainingPattern", "allContained", "expItem", "recItem", "ObjectContainingPattern", "_ObjectContainingPattern", "StringContainingPattern", "_StringContainingPattern", "Patterns", "xJetPromiseError", "MatcherService", "isResolved", "valueOrPromise", "kind", "receivedValue", "proto", "matcherFn", "coreExpect", "rest", "xExpect", "DEFAULT_MOCK_NAME", "MockState", "_MockState", "__name", "implementation", "restore", "name", "index", "fn", "value", "thisArg", "args", "thisContext", "impl", "argsArray", "result", "error", "target", "argumentsList", "argArray", "newTarget", "isClassInstance", "SINGLETONS", "INJECTABLES", "Injectable", "options", "target", "__name", "inject", "token", "args", "metadata", "instance", "getBufferMethod", "buffer", "operation", "type", "methodName", "method", "readMethod", "writeMethod", "splitBufferWithGap", "splitPosition", "skipBytes", "beforeSplit", "afterPosition", "readSingleStruct", "arrayOffset", "position", "absolutePosition", "offset", "readStructArray", "result", "arraySize", "size", "readStruct", "writeSingleStruct", "value", "StructBuffer", "start", "end", "writeStructArray", "values", "elementValue", "writeStruct", "PRIMITIVE_TYPE_SIZES", "parsePrimitiveDescriptor", "field", "pattern", "match", "readSinglePrimitive", "readPrimitiveArray", "readPrimitive", "writeSinglePrimitive", "isBigIntType", "writePrimitiveArray", "writePrimitive", "maskCache", "isSignedType", "getBitMask", "mask", "processValueForBitfield", "descriptor", "validateBitFieldBounds", "isSigned", "bitSize", "maxBitValue", "minBitValue", "validateBitfieldParameters", "extractBitfieldValue", "rawValue", "bitPosition", "extractedValue", "composeBitfieldValue", "processedValue", "shiftedMask", "parseBitfieldDescriptor", "bitSizeStr", "typeSize", "isBigEndian", "readBitfield", "endianMethod", "writeBitfield", "bitFieldValue", "STRING_PRIMITIVE_LIST", "parseStringDescriptor", "readSingleString", "encoding", "lengthType", "stringLength", "dataOffset", "endPos", "maxLength", "readStringArray", "readString", "writeSingleString", "stringBuffer", "nullTerminatedString", "writeStringArray", "writeString", "Struct", "_Struct", "__name", "schema", "getDynamicOffset", "context", "name", "data", "kind", "positionedDescriptor", "primitiveSize", "fieldNotation", "prefix", "accumulator", "fieldName", "sizedField", "bitsInField", "requestedBitSize", "totalSize", "invocationSchema", "g", "headerSchema", "logSchema", "errorSchema", "statusSchema", "eventsSchema", "PacketSchemas", "logSchema", "errorSchema", "statusSchema", "eventsSchema", "encodePacket", "kind", "data", "schema", "PacketSchemas", "header", "headerSchema", "__name", "encodeErrorSchema", "error", "suiteId", "runnerId", "header", "headerSchema", "dataBuffer", "errorSchema", "ae", "__name", "emitStatus", "type", "notification", "encodePacket", "__name", "emitEvent", "stringErrors", "error", "ae", "LogLevel", "DescribeModel", "description", "describeOptions", "__name", "child", "type", "hook", "hookArray", "test", "describe", "context", "afterAllErrorsEmpty", "beforeAllErrorsEmpty", "error", "parent", "skip", "emitStatus", "errors", "emitEvent", "testsToShuffle", "length", "i", "j", "ExecutionError", "__name", "message", "json", "key", "value", "_SuiteState_decorators", "_init", "Injectable", "_SuiteState", "__name", "DescribeModel", "part", "path", "filter", "offset", "re", "i", "test", "context", "time", "emitStatus", "ExecutionError", "e", "encodeErrorSchema", "description", "describeFn", "flags", "describeArgs", "options", "fullPath", "newDescribe", "previousDescribe", "__decoratorStart", "__decorateElement", "__runInitializers", "SuiteState", "PATTERNS", "JSEngines", "detectJSEngine", "stack", "normalizePath", "filePath", "createDefaultFrame", "source", "safeParseInt", "value", "parseV8StackLine", "line", "frame", "evalMatch", "globalMatch", "standardMatch", "parseSpiderMonkeyStackLine", "match", "parseJavaScriptCoreStackLine", "parseStackLine", "engine", "getStackWithoutMessage", "stackFramePattern", "lines", "i", "parseErrorStack", "error", "errorObj", "name", "message", "stackLines", "getInvocationLocation", "position", "stack", "E", "__name", "getTrimmedStackString", "err", "createLogHandler", "type", "args", "parent", "inject", "SuiteState", "context", "formattedArgs", "data", "v", "location", "getInvocationLocation", "encodePacket", "LogLevel", "__name", "log", "info", "warn", "error", "debug", "spyOnDescriptorProperty", "target", "key", "original", "originalDescriptor", "mockInstance", "MockState", "value", "__name", "spyOnImplementation", "ExecutionError", "method", "targetObject", "descriptor", "fn", "protoDesc", "args", "mockState", "_TimerService_decorators", "_init", "Injectable", "TimerService", "__name", "setTimeout", "cb", "delay", "args", "id", "setInterval", "interval", "clearTimeout", "clearInterval", "global", "ms", "t", "pendingTimers", "nextTimerTimes", "limitTimers", "executed", "timers", "a", "b", "timer", "__decoratorStart", "__decorateElement", "__runInitializers", "useFakeTimers", "inject", "useRealTimers", "runAllTimers", "runOnlyPendingTimers", "advanceTimersByTime", "VARIABLE_PATTERN", "prettyFormat", "value", "__name", "getValueByPath", "data", "path", "obj", "key", "resolveVariable", "token", "arrayIndex", "propertyPath", "resolvedValue", "interpolateVariables", "template", "variableToken", "printf", "description", "params", "index", "paramIndex", "match", "format", "parseTemplate", "templateString", "inputData", "headings", "h", "_", "rowIndex", "acc", "heading", "columnIndex", "__name", "each", "executor", "args", "cases", "name", "blockFn", "timeout", "testCase", "index", "parseArgs", "printf", "TimeoutError", "__name", "timeout", "at", "stack", "withTimeout", "task", "delay", "at", "stack", "timers", "inject", "TimerService", "taskPromise", "timeoutId", "timeoutPromise", "_", "reject", "TimeoutError", "__name", "FailingError", "_FailingError", "ExecutionError", "__name", "stack", "TestModel", "description", "testImplementation", "timeoutDuration", "testParameters", "testOptions", "__name", "location", "skip", "only", "parentTests", "context", "runLifecycleHooks", "isExclusiveMode", "inject", "SuiteState", "error", "withTimeout", "FailingError", "me", "resolve", "reject", "callbackFn", "allParameters", "todo", "emitStatus", "errors", "emitEvent", "TestDirective", "_TestDirective", "__name", "target", "_", "args", "description", "block", "timeout", "getTrimmedStackString", "each", "test", "runningTest", "inject", "SuiteState", "TestModel", "location", "DescribeDirective", "_DescribeDirective", "__name", "target", "thisArg", "args", "each", "description", "block", "suiteState", "inject", "SuiteState", "runningTest", "getParentObject", "fn", "name", "globalElements", "key", "val", "__name", "fnImplementation", "implementation", "restore", "MockState", "mockImplementation", "method", "parentObject", "ExecutionError", "descriptor", "originalMethod", "mock", "args", "HookModel", "hookFunction", "timeout", "__name", "location", "context", "withTimeout", "hook", "me", "resolve", "reject", "error", "DEFAULT_TIMEOUT", "createHook", "hookType", "callback", "location", "timeout", "hook", "HookModel", "inject", "SuiteState", "__name", "afterAllDirective", "getTrimmedStackString", "beforeAllDirective", "afterEachDirective", "beforeEachDirective", "clearMocks", "method", "MockState", "mock", "__name", "setupGlobals", "globals", "fnImplementation", "mockImplementation", "spyOnImplementation", "log", "info", "warn", "error", "debug", "runAllTimers", "useFakeTimers", "useRealTimers", "advanceTimersByTime", "runOnlyPendingTimers", "At", "inject", "SuiteState", "TestDirective", "DescribeDirective", "afterAllDirective", "beforeAllDirective", "afterEachDirective", "beforeEachDirective"]
|
|
8
8
|
}
|