UNPKG

@init-kz/jsonparse-ts

Version:

Library for parsing partial jsons inspired by original jsonparse written on js

416 lines (405 loc) 13.5 kB
declare class EventEmitter { private valueHandlers; private tokenHandlers; private errorHandlers; /** * Subscribes a value event callback. */ onValue(callback: (value: any) => void): void; /** * Emits a parsed value event. */ emitValue(value: any): boolean; /** * Unsubscribes a value event callback. */ offValue(callback: (value: any) => void): void; /** * Returns true if length of value subscribers more than zero */ hasValueHandler(): boolean; /** * Subscribes a callback to token events. * @param callback - Function to handle tokens. */ onToken(callback: (token: number, value: any) => void): void; /** * Subscribes a callback to token events. * @param callback - Function to handle tokens. */ offToken(callback: (token: number, value: any) => void): void; /** * Emits a token event to all subscribers. * @param token - The token type. * @param value - The associated value. */ emitToken(token: number, value: any): boolean; /** * Subscribes an error handler callback. * @param callback - A function to handle errors. */ onError(callback: (err: Error) => void): void; /** * Subscribes an error handler callback. * @param callback - A function to handle errors. */ offError(callback: (err: Error) => void): void; /** * Handles errors by either notifying subscribers or throwing the error. * @param err - The error to handle. */ handleError(err: Error): void; } declare class StringHandler { /** Current string being parsed */ protected string: string | undefined; /** Buffer to store string data */ protected stringBuffer: Uint8Array; /** Offset within the string buffer */ protected stringBufferOffset: number; /** Unicode processing variables */ protected unicode: string | undefined; protected highSurrogate: number | undefined; constructor(); /** * Appends a character to the string buffer. */ appendStringChar(char: number): void; /** * Appends a portion of a buffer to the internal string buffer. * @param buf - The source Uint8Array buffer. * @param start - The starting index (optional, defaults to 0). * @param end - The ending index (optional, defaults to `buf.length`). */ appendStringBuf(buf: Uint8Array, start?: number, end?: number): void; /** * Flushes the current buffer into the string. */ flushBuffer(): this; /** * Gets the final string value. * Ensures that if no string has been accumulated, it returns an empty string. * @returns {string} The current accumulated string. */ getString(): string; /** * Resets the string buffer and optionally sets a new initial string value. * This is useful when starting a new string parsing session. * @param {string} [stringValue] - Optional initial string value after reset. */ reset(stringValue?: string): void; /** * Resets only the stored string without affecting the buffer offset. * This can be useful when clearing the current string but keeping buffer state. * @param {string} [stringValue] - Optional new string value. */ resetString(stringValue?: string): void; /** * Sets the string value from a single character's char code. * Useful when initializing a string with a character (e.g., starting a number or string). * @param {number} n - The character code to set as the string. */ setFromCharcode(n: number): void; /** * Appends a single character (from its char code) to the existing string. * Useful for dynamically building strings one character at a time. * @param {number} n - The character code to append to the string. */ addFromCharCode(n: number): this; setUnicode(unicode?: string): this; getUnicode(): string; setHighSurrogate(n?: number): this; getHighSurrogate(): number | undefined; addUnicodeFromCharCode(n: number): this; } declare class StateHandler { protected eventEmitter: EventEmitter; protected stringHandler: StringHandler; /** Tokenizer State - Tracks the current state of the tokenizer */ protected tState: number; /** Current Parsed Value */ protected value: any; protected lastValue: any; /** Parser Mode (OBJECT, ARRAY) */ protected mode: number | undefined; /** Stack to maintain parsing context */ protected stack: Array<{ value: any; key?: string | number; mode?: number; }>; /** Current Parsing State (VALUE, KEY) */ protected state: number; /** Current byte offset in the stream */ protected offset: number; /** Current key being processed (for objects) */ protected key: string | undefined | number; constructor(eventEmitter: EventEmitter, stringHandler: StringHandler); getTokenizerState(): number; incTokenizerState(): this; setOffset(n: number): this; getOffset(): number; addOffset(n: number): this; setTokenizerState(n: number): this; getParsingState(): number; getStack(): { value: any; key?: string | number; mode?: number; }[]; /** * Pushes the current parsing context onto the stack. */ push(): void; /** * Pops the last parsing context from the stack and emits a value. */ pop(): void; incOffset(): this; getValue(): any; getLastIncompleteValue(omitEmpty?: boolean): any; getLastValue(): any; getKey(): string | number | undefined; getTokenizerStateName(): string; getMode(): number | undefined; setValue(value: any): this; setKey(value: any): this; setKeyValue(value: any): void; setState(n: number): this; setMode(n: number): this; } declare class ErrorHandler { protected eventEmitter: EventEmitter; protected stateHandler: StateHandler; constructor(eventEmitter: EventEmitter, stateHandler: StateHandler); /** * Handles unexpected token errors. */ parseError(token: number, value?: any): Error; /** * Handles character-related errors. */ charError(buffer: Uint8Array, i: number): Error; } declare class TokenHandler { protected eventEmitter: EventEmitter; protected stateHandler: StateHandler; protected errorHandler: ErrorHandler; constructor(eventEmitter: EventEmitter, stateHandler: StateHandler, errorHandler: ErrorHandler); /** * Handles incoming tokens and builds the JSON structure. */ handleToken(token: number, value: any): void; /** * Handles tokens when in VALUE state. */ private handleValueToken; /** * Handles tokens when in KEY state. */ private handleKeyToken; /** * Handles tokens when in COLON state. */ private handleColonToken; /** * Handles tokens when in COMMA state. */ private handleCommaToken; /** * Starts a new object `{}`. */ private startObject; /** * Starts a new array `[]`. */ private startArray; } declare class UTF8Handler { /** Remaining bytes for a multi-byte UTF-8 character, number of bytes remaining in multi byte utf8 char to read after split boundary */ protected bytes_remaining: number; /** Total bytes in the current UTF-8 character sequence, bytes in multi byte utf8 char to read */ protected bytes_in_sequence: number; /** Temporary buffers for rebuilding chars split before boundary is reached */ protected temp_buffs: Record<number, Uint8Array>; constructor(); /** Get the remaining bytes for a multi-byte character */ getBytesRemaining(): number; getRemainingBytesInBuff(buffer: Uint8Array): Uint8Array; handleBoundarySplit(i: number, buffer: Uint8Array): void; /** Set the remaining bytes, ensuring it's not negative */ setBytesRemaining(value: number): void; /** Get the total bytes in the current UTF-8 character sequence */ getBytesInSequence(): number; /** Set the total bytes, ensuring it's not negative */ setBytesInSequence(value: number): void; /** Get the temporary buffers for multi-byte characters */ getTempBuffs(): Record<string, Uint8Array>; /** Set the temporary buffers */ setTempBuffs(buffers: Record<string, Uint8Array>): void; hasBytesRemaining(): boolean; } declare abstract class BaseParser { /** Event Emitter */ protected eventEmitter: EventEmitter; /** Handler for current state */ protected stateHandler: StateHandler; /** Handler for strings, including multybytes */ protected stringHandler: StringHandler; /** Handler for utf8 symbols */ protected utf8Handler: UTF8Handler; protected errorHandler: ErrorHandler; protected tokenHandler: TokenHandler; protected encoder: TextEncoder; constructor(); /** * Parses and processes numeric values. * Can be overridden for custom number handling. * @param text - The numeric text to parse. */ protected numberReviver(text: string): Error | undefined; } declare class Parser extends BaseParser { getEmitter(): EventEmitter; onToken(callback: (token: number, value: any) => void): void; onValue(callback: (value: any) => void): void; onError(callback: (err: Error) => void): void; getLastValue(): any; getLastIncompleteValue(omitEmpty?: boolean): any; getCurrentKey(): string | number | undefined; getStack(): { value: any; key?: string | number; mode?: number; }[]; getOffset(): number; /** * Processes an incoming buffer of JSON data. * @param buffer - The input JSON chunk. */ write(buffer: Uint8Array | string): Error | undefined; /** * Processes tokens at the root level (e.g. `{`, `[`, `:`, `,`). */ private processStartState; private processStringUnicodeState; private processStringBackslashState; private processStringStartingState; /** * Parses numeric values. */ private processNumberState; private processFalseState; private processTrueState; /** * Processes `null` value. */ private processNullState; } declare const TOKENS: { readonly LEFT_BRACE: 1; readonly RIGHT_BRACE: 2; readonly LEFT_BRACKET: 3; readonly RIGHT_BRACKET: 4; readonly COLON: 5; readonly COMMA: 6; readonly TRUE: 7; readonly FALSE: 8; readonly NULL: 9; readonly STRING: 10; readonly NUMBER: 11; }; declare const TOKENIZER_STATES: { readonly START: 17; readonly STOP: 18; readonly TRUE1: 33; readonly TRUE2: 34; readonly TRUE3: 35; readonly FALSE1: 49; readonly FALSE2: 50; readonly FALSE3: 51; readonly FALSE4: 52; readonly NULL1: 65; readonly NULL2: 66; readonly NULL3: 67; readonly NUMBER1: 81; readonly NUMBER3: 83; readonly STRING1: 97; readonly STRING2: 98; readonly STRING3: 99; readonly STRING4: 100; readonly STRING5: 101; readonly STRING6: 102; }; declare const PARSER_STATES: { readonly VALUE: 113; readonly KEY: 114; readonly COLON: 58; readonly COMMA: 44; }; declare const PARSER_MODES: { readonly OBJECT: 129; readonly ARRAY: 130; }; declare const CHARS: { readonly BACKSLASH: 92; readonly FORWARD_SLASH: 47; readonly BACKSPACE: 8; readonly FORM_FEED: 12; readonly NEWLINE: 10; readonly CARRIAGE_RETURN: 13; readonly TAB: 9; readonly SPACE: 32; readonly LEFT_BRACE: 123; readonly RIGHT_BRACE: 125; readonly LEFT_BRACKET: 91; readonly RIGHT_BRACKET: 93; readonly COLON: 58; readonly COMMA: 44; readonly QUOTE: 34; readonly MINUS: 45; readonly PLUS: 43; readonly DOT: 46; readonly E: 101; readonly BIG_E: 69; readonly T: 116; readonly F: 102; readonly N: 110; readonly L: 108; readonly S: 115; readonly B: 98; readonly R: 114; readonly U: 117; readonly A: 97; readonly BIG_A: 65; readonly BIG_F: 70; readonly ZERO: 48; readonly NINE: 57; readonly WHITESPACES: number[]; }; declare const UTF8_BOUNDS: { readonly MIN_MULTI_BYTE: 128; readonly INVALID_LOWER: 193; readonly BYTE_2_MIN: 194; readonly BYTE_2_MAX: 223; readonly BYTE_3_MIN: 224; readonly BYTE_3_MAX: 239; readonly BYTE_4_MIN: 240; readonly BYTE_4_MAX: 244; readonly HIGH_SURROGATE_START: 55296; readonly HIGH_SURROGATE_END: 56319; readonly LOW_SURROGATE_START: 56320; readonly LOW_SURROGATE_END: 57343; }; declare const STRING_BUFFER_SIZE: number; declare const constants_CHARS: typeof CHARS; declare const constants_PARSER_MODES: typeof PARSER_MODES; declare const constants_PARSER_STATES: typeof PARSER_STATES; declare const constants_STRING_BUFFER_SIZE: typeof STRING_BUFFER_SIZE; declare const constants_TOKENIZER_STATES: typeof TOKENIZER_STATES; declare const constants_TOKENS: typeof TOKENS; declare const constants_UTF8_BOUNDS: typeof UTF8_BOUNDS; declare namespace constants { export { constants_CHARS as CHARS, constants_PARSER_MODES as PARSER_MODES, constants_PARSER_STATES as PARSER_STATES, constants_STRING_BUFFER_SIZE as STRING_BUFFER_SIZE, constants_TOKENIZER_STATES as TOKENIZER_STATES, constants_TOKENS as TOKENS, constants_UTF8_BOUNDS as UTF8_BOUNDS }; } export { constants as CONSTANTS, Parser };