UNPKG

stax-xml

Version:

High-performance, pull-based XML parser for JavaScript/TypeScript with declarative converter API

1,352 lines 37.7 kB
//#region src/converter/errors.d.ts /** * XML parse error with detailed issue information * * @public */ declare class XmlParseError extends Error { /** * List of validation issues */ issues: Array<{ path: string[]; message: string; code: string; }>; constructor(issues: Array<{ path: string[]; message: string; code: string; }>); } /** * Parse result type for safe parsing operations * * @public */ type ParseResult<T> = { success: true; data: T; } | { success: false; error: XmlParseError; }; //#endregion //#region src/types.d.ts /** * Enumeration of XML stream event types used by the StAX parser * * @public */ declare const XmlEventType: { readonly START_DOCUMENT: "START_DOCUMENT"; readonly END_DOCUMENT: "END_DOCUMENT"; readonly START_ELEMENT: "START_ELEMENT"; readonly END_ELEMENT: "END_ELEMENT"; readonly CHARACTERS: "CHARACTERS"; readonly CDATA: "CDATA"; readonly ERROR: "ERROR"; }; type XmlEventType = typeof XmlEventType[keyof typeof XmlEventType]; /** * Event fired when the document starts parsing * * @public */ interface StartDocumentEvent { type: typeof XmlEventType.START_DOCUMENT; } /** * Event fired when the document ends parsing * * @public */ interface EndDocumentEvent { type: typeof XmlEventType.END_DOCUMENT; } /** * Event fired when an XML element starts * * @public */ interface StartElementEvent { type: typeof XmlEventType.START_ELEMENT; name: string; localName?: string; prefix?: string; uri?: string; attributes: Record<string, string>; attributesWithPrefix?: Record<string, AttributeInfo>; } interface EndElementEvent { type: typeof XmlEventType.END_ELEMENT; name: string; localName?: string; prefix?: string; uri?: string; } interface CharactersEvent { type: typeof XmlEventType.CHARACTERS; value: string; } interface CdataEvent { type: typeof XmlEventType.CDATA; value: string; } interface ErrorEvent { type: typeof XmlEventType.ERROR; error: Error; } /** * Discriminated Union type for developer use */ type AnyXmlEvent = StartDocumentEvent | EndDocumentEvent | StartElementEvent | EndElementEvent | CharactersEvent | CdataEvent | ErrorEvent; /** * Namespace declaration interface (for Writer) * Not used in this simple implementation. */ interface NamespaceDeclaration { prefix: string; uri: string; } /** * Attribute information interface */ interface AttributeInfo { value: string; localName: string; prefix?: string; uri?: string; } /** * Element writing options interface (for Writer) */ interface WriteElementOptions { prefix?: string; uri?: string; attributes?: Record<string, string | AttributeInfo>; selfClosing?: boolean; comment?: string; } //#endregion //#region src/StaxXmlWriter.d.ts /** * Configuration options for the StaxXmlWriter * * @public */ interface StaxXmlWriterOptions { /** * Text encoding for the output stream * @defaultValue 'utf-8' */ encoding?: string; /** * Whether to format output with indentation * @defaultValue false */ prettyPrint?: boolean; /** * String used for indentation when prettyPrint is true * @defaultValue ' ' */ indentString?: string; /** * Additional custom entities to encode * @defaultValue [] */ addEntities?: { entity: string; value: string; }[]; /** * Whether to automatically encode XML entities * @defaultValue true */ autoEncodeEntities?: boolean; /** * Namespace declarations to include * @defaultValue [] */ namespaces?: NamespaceDeclaration[]; /** * Internal buffer size in bytes * @defaultValue 16384 */ bufferSize?: number; /** * WritableStream backpressure threshold * @defaultValue 65536 */ highWaterMark?: number; /** * Automatic flush threshold (percentage of bufferSize) * @defaultValue 0.8 */ flushThreshold?: number; /** * Whether to enable automatic flushing * @defaultValue true */ enableAutoFlush?: boolean; } /** * High-performance asynchronous XML writer implementing the StAX (Streaming API for XML) pattern. * * This writer provides efficient streaming XML generation using WritableStream for handling * large XML documents with automatic buffering, backpressure management, and namespace support. * * @remarks * The writer supports streaming output with configurable buffering, automatic entity encoding, * pretty printing with customizable indentation, and comprehensive namespace handling. * * @example * Basic usage: * ```typescript * const writableStream = new WritableStream({ * write(chunk) { * console.log(new TextDecoder().decode(chunk)); * } * }); * * const writer = new StaxXmlWriter(writableStream); * await writer.writeStartElement('root'); * await writer.writeElement('item', { id: '1' }, 'Hello World'); * await writer.writeEndElement(); * await writer.close(); * ``` * * @example * With pretty printing: * ```typescript * const options = { * prettyPrint: true, * indentString: ' ', * autoEncodeEntities: true * }; * const writer = new StaxXmlWriter(writableStream, options); * ``` * * @public */ declare class StaxXmlWriter { private writer; private encoder; private buffer; private bufferPosition; private state; private elementStack; private hasTextContentStack; private namespaceStack; private readonly options; private currentIndentLevel; private needsIndent; private entityMap; private metrics; constructor(stream: WritableStream<Uint8Array>, options?: StaxXmlWriterOptions); private _initializeEntityMap; /** * Write data to buffer (with automatic flush) */ private _writeToBuffer; /** * Buffer flush */ private _flushBuffer; /** * Write XML declaration */ writeStartDocument(version?: string, encoding?: string): Promise<this>; /** * End document (automatically close all elements) */ writeEndDocument(): Promise<void>; /** * Write start element */ writeStartElement(localName: string, options?: WriteElementOptions): Promise<this>; /** * Write end element */ writeEndElement(): Promise<this>; /** * Write text */ writeCharacters(text: string): Promise<this>; /** * Write CDATA section */ writeCData(cdata: string): Promise<this>; /** * Write comment */ writeComment(comment: string): Promise<this>; /** * Write raw XML content without escaping * @param xml Raw XML string to write * @returns this (chainable) */ writeRaw(xml: string): Promise<this>; /** * Manual flush */ flush(): Promise<void>; /** * Return metrics */ getMetrics(): { bufferUtilization: number; averageFlushSize: number; totalBytesWritten: number; flushCount: number; lastFlushTime: number; }; private _closeStartElementTag; private _writeIndent; private _writeNewline; private _escapeXml; } //#endregion //#region src/StaxXmlWriterSync.d.ts interface StaxXmlWriterSyncOptions { encoding?: string; prettyPrint?: boolean; indentString?: string; addEntities?: { entity: string; value: string; }[]; autoEncodeEntities?: boolean; namespaces?: NamespaceDeclaration[]; } /** * A class for writing XML similar to StAX XMLStreamWriter. * This is a simplified implementation that does not support namespace and complex PI/comment management. */ declare class StaxXmlWriterSync { private xmlString; private state; private elementStack; private hasTextContentStack; private namespaceStack; private readonly options; private currentIndentLevel; private needsIndent; private entityMap; constructor(options?: StaxXmlWriterSyncOptions); /** * Writes the XML declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>). * Should be called only once at the very beginning of the document. * @param version XML version (default: "1.0") * @param encoding Encoding (default: value set in constructor) * @param standalone Whether document is standalone (default: undefined) * @returns this (chainable) * @throws Error when called in incorrect state */ writeStartDocument(version?: string, encoding?: string): this; /** * Indicates the end of the document and automatically closes all open elements. * @returns Promise<void> Promise that resolves when stream is flushed */ writeEndDocument(): void; /** * Returns the written XML string. * Should be called after writeEndDocument() to get the complete XML. * @returns The written XML string */ getXmlString(): string; /** * Writes a start element (e.g., <element> or <prefix:element>). * @param localName Local name of the element * @param options Element writing options (prefix, uri, attributes, selfClosing) * @returns this (chainable) * @throws Error when called in incorrect state */ writeStartElement(localName: string, options?: WriteElementOptions): this; /** * Writes an attribute. Can only be called immediately after writeStartElement(). * @param localName Local name of the attribute * @param value Attribute value * @param prefix Namespace prefix of the attribute (note: this implementation does not manage namespace mapping) * @param uri Namespace URI of the attribute (note: this implementation does not manage namespace mapping) * @returns this (chainable) * @throws Error when called in incorrect state */ writeAttribute(localName: string, value: string, prefix?: string): this; /** * Writes a namespace declaration. Can only be called immediately after writeStartElement(). * This implementation simply writes the string in the form xmlns:prefix="uri" or xmlns="uri". * Actual namespace validation/management logic is not included. * @param prefix Namespace prefix * @param uri Namespace URI * @returns this (chainable) * @throws Error when called in incorrect state */ writeNamespace(prefix: string, uri: string): this; /** * Writes text content. * @param text Text to write * @returns this (chainable) * @throws Error when called in incorrect state */ writeCharacters(text: string): this; /** * Writes a CDATA section. * @param cdata CDATA content * @returns this (chainable) * @throws Error when called in incorrect state (especially when containing ']]>' sequence) */ writeCData(cdata: string): this; /** * Writes a comment. * @param comment Comment content * @returns this (chainable) * @throws Error when called in incorrect state (especially when containing '--' sequence) */ writeComment(comment: string): this; /** * Writes a processing instruction (Processing Instruction). * @param target PI target * @param data PI data (optional) * @returns this (chainable) * @throws Error when called in incorrect state (especially when containing '?>' sequence) */ writeProcessingInstruction(target: string, data?: string): this; /** * Writes raw XML content without escaping * @param xml Raw XML string to write * @returns this (chainable) */ writeRaw(xml: string): this; /** * Closes the currently open element (e.g., </element> or </prefix:element>). * @returns this (chainable) * @throws Error when called with no open elements */ writeEndElement(): this; /** * Enables/disables pretty print functionality. * @param enabled Whether to enable pretty print * @returns this (chainable) */ setPrettyPrint(enabled: boolean): this; /** * Sets the indentation string. * @param indentString String to use for indentation (e.g., ' ', '\t', ' ') * @returns this (chainable) */ setIndentString(indentString: string): this; /** * Returns the current pretty print setting. * @returns Whether pretty print is enabled */ isPrettyPrintEnabled(): boolean; /** * Returns the current indentation string. * @returns Currently set indentation string */ getIndentString(): string; /** * Closes the currently open start element tag (adds '>'). * For example, turns <element into <element>. * @private */ private _closeStartElementTag; /** * Applies indentation for pretty print. * @private */ private _writeIndent; /** * Adds newline for pretty print. * @private */ private _writeNewline; /** * Writes string to output stream. * @param chunk String to write * @private */ private _write; /** * Escapes XML text. * @param text Text to escape * @returns Escaped text * @private */ private _escapeXml; } //#endregion //#region src/converter/XmlStringSchema.d.ts /** * Schema for parsing XML string values * * @public */ declare class XmlStringSchema extends XmlSchema<string, string> { options: XmlStringOptions; readonly schemaType: "STRING"; constructor(options?: XmlStringOptions); _parse(input: ParseInput, parseOptions?: ParseOptions): string; _parseAsync(input: ParseInput, parseOptions?: ParseOptions): Promise<string>; _parseText(text: string): string; /** * Parse from current iterator position * @internal */ _parseFromPosition(iterator: Iterator<AnyXmlEvent> | AsyncIterator<AnyXmlEvent>, startEvent: StartElementEvent, startDepth: number, options?: ParseOptions): string | Promise<string>; private collectTextSync; private collectTextAsync; /** * Set XPath expression for locating the element * @param path - XPath expression * @returns New schema with XPath */ xpath(path: string): XmlStringSchema; /** * Write raw content only (used inside object schema) * @internal */ _writeContent(data: string, options?: XmlWriteOptions): string; /** * Write string data to XML synchronously * @internal */ _writeSync(data: string, options?: XmlWriteOptions): string; /** * Write string data to WritableStream asynchronously * @internal */ _write(data: string, stream: WritableStream<Uint8Array>, options?: XmlWriteOptions): Promise<void>; } //#endregion //#region src/converter/XmlNumberSchema.d.ts /** * Schema for parsing XML number values * * @public */ declare class XmlNumberSchema extends XmlSchema<number, number> { options: XmlNumberOptions; readonly schemaType: "NUMBER"; constructor(options?: XmlNumberOptions); _parse(input: ParseInput, parseOptions?: ParseOptions): number; _parseAsync(input: ParseInput, parseOptions?: ParseOptions): Promise<number>; _parseText(text: string): number; /** * Parse from current iterator position * @internal */ _parseFromPosition(iterator: Iterator<AnyXmlEvent> | AsyncIterator<AnyXmlEvent>, startEvent: StartElementEvent, startDepth: number, options?: ParseOptions): number | Promise<number>; private collectAndParseSync; private collectAndParseAsync; /** * Set XPath expression for locating the element * @param path - XPath expression * @returns New schema with XPath */ xpath(path: string): XmlNumberSchema; /** * Set minimum value * @param value - Minimum value * @returns New schema with minimum */ min(value: number): XmlNumberSchema; /** * Set maximum value * @param value - Maximum value * @returns New schema with maximum */ max(value: number): XmlNumberSchema; /** * Require integer value * @returns New schema that only accepts integers */ int(): XmlNumberSchema; /** * Write raw content only (used inside object schema) * @internal */ _writeContent(data: number, options?: XmlWriteOptions): string; /** * Write number data to XML synchronously * @internal */ _writeSync(data: number, options?: XmlWriteOptions): string; /** * Write number data to WritableStream asynchronously * @internal */ _write(data: number, stream: WritableStream<Uint8Array>, options?: XmlWriteOptions): Promise<void>; } //#endregion //#region src/converter/XPathEngine.d.ts /** * XPath matcher using streaming evaluation * * @internal */ declare class XPathMatcher { private currentPath; private positionStack; private compiled; private elementStack; private contextDepth?; constructor(xpath: string, contextDepth?: number); onStartElement(event: StartElementEvent): void; onEndElement(): void; matches(event: StartElementEvent): boolean; /** * Check if XPath selects an attribute */ isAttributeSelector(): boolean; /** * Get attribute name if this is an attribute selector */ getAttributeName(): string | undefined; /** * Check if XPath selects a text node */ isTextNodeSelector(): boolean; private matchesDescendant; private matchesAbsolute; private matchesRelative; private matchesFromDepth; private matchesPredicate; reset(): void; } //#endregion //#region src/converter/XmlParsingStateMachine.d.ts /** * Collector types for different schema types * @internal */ type Collector<T> = StringCollector | NumberCollector | ArrayCollector<T> | ObjectCollector; interface StringCollector { type: 'string'; buffer: string; value?: string; } interface NumberCollector { type: 'number'; buffer: string; value?: number; } interface ArrayCollector<T> { type: 'array'; items: T[]; currentItem?: { depth: number; buffer: string; } | ObjectCollector | ArrayCollector<unknown>; } interface ObjectCollector { type: 'object'; fields: Map<string, Collector<unknown>>; } /** * Match context for relative XPath evaluation * @internal */ interface MatchContext { /** The element that owns this schema (context node) */ contextElement?: StartElementEvent; /** Depth of the context element */ contextDepth: number; /** Parent context for nested structures */ parentContext?: MatchContext; /** XPath of the context for debugging */ contextXPath?: string; } /** * Schema activation state tracker * @internal */ interface SchemaActivation { schema: XmlSchemaBase<unknown, unknown>; xpath: string; matcher: XPathMatcher; depth: number; collector: Collector<unknown>; context?: MatchContext; fieldName?: string; isTemporary?: boolean; parentCollector?: Collector<unknown>; } /** * Internal state machine for event-based XML parsing * Processes events and fills collectors without type awareness * * @internal */ declare class XmlParsingStateMachine { private readonly options; private activeSchemas; private currentDepth; private eventCount; private readonly maxDepth; private readonly maxEvents; constructor(options?: ParseOptions); /** * Register a schema for event-based activation */ registerSchema(schema: XmlSchemaBase<unknown, unknown>, xpath: string, collector: Collector<unknown>, context?: MatchContext, fieldName?: string): SchemaActivation; /** * Process events synchronously */ processEventSync(event: AnyXmlEvent): void; /** * Process events asynchronously */ processEvent(event: AnyXmlEvent): Promise<void>; /** * Alias for processEvent (async) */ processEventAsync(event: AnyXmlEvent): Promise<void>; /** * Unwrap Transform and Optional wrappers to get core schema */ private unwrapSchema; /** * Check if event matches activation's XPath within its context */ private matchesInContext; /** * Create a new array item for an already-active array schema (sync) * @internal */ private createArrayItemSync; /** * Create a new array item for an already-active array schema (async) * @internal */ private createArrayItemAsync; /** * Schema activated (sync) */ private onSchemaActivatedSync; /** * Schema activated (async) */ private onSchemaActivated; /** * Schema deactivated (sync) */ private onSchemaDeactivatedSync; /** * Schema deactivated (async) */ private onSchemaDeactivated; /** * Collect text content for active schema */ private onSchemaCollectText; /** * Check depth and event limits */ private checkLimits; /** * Reset state for reuse */ reset(): void; /** * Extract XPath from a schema (handles wrappers and different schema types) * @internal */ private extractXPath; /** * Create appropriate collector for a schema type * @internal */ private createCollectorForSchema; /** * Extract object from ObjectCollector * @internal */ private extractObjectFromCollector; /** * Get all transform functions from schema chain * @internal */ private getAllTransforms; /** * Extract value with field-level transforms * @internal */ private extractValueWithTransforms; /** * Extract simple value from collector (without transforms) * @internal */ private extractSimpleValue; /** * Check if schema chain contains XmlOptionalSchema * @internal */ private hasOptionalWrapper; } //#endregion //#region src/converter/XmlArraySchema.d.ts /** * Schema for parsing XML array values * * @public */ declare class XmlArraySchema<T extends XmlSchemaBase<unknown, unknown>> extends XmlSchemaBase<T['_output'][], T['_input'][]> { readonly element: T; readonly xpath?: string | undefined; readonly schemaType: "ARRAY"; constructor(element: T, xpath?: string | undefined); _parse(input: ParseInput, parseOptions?: ParseOptions): T['_output'][]; _parseAsync(input: ParseInput, parseOptions?: ParseOptions): Promise<T['_output'][]>; /** * Parse array from current iterator position (for nested array parsing) * @internal */ _parseFromPosition(iterator: Iterator<AnyXmlEvent> | AsyncIterator<AnyXmlEvent>, startEvent: StartElementEvent, startDepth: number, options?: ParseOptions, stateMachine?: XmlParsingStateMachine, parentContext?: unknown): T['_output'][] | Promise<T['_output'][]>; _parseText(text: string): T['_output'][]; /** * Write array data to XML synchronously * @internal */ _writeSync(data: T['_output'][], options?: XmlWriteOptions): string; /** * Write array data to WritableStream asynchronously * @internal */ _write(data: T['_output'][], stream: WritableStream<Uint8Array>, options?: XmlWriteOptions): Promise<void>; } //#endregion //#region src/converter/XmlObjectSchema.d.ts /** * Shape type for object schema * * @public */ type XmlObjectShape = Record<string, XmlSchema<unknown, unknown>>; /** * Infer output type from object shape * * @public */ type InferObjectOutput<T extends XmlObjectShape> = { [K in keyof T]: T[K]['_output'] }; /** * Schema for parsing XML object values * * @public */ declare class XmlObjectSchema<T extends XmlObjectShape> extends XmlSchema<InferObjectOutput<T>, unknown> { readonly shape: T; options: XmlObjectOptions; readonly schemaType: "OBJECT"; constructor(shape: T, options?: XmlObjectOptions); _parse(input: ParseInput, parseOptions?: ParseOptions): InferObjectOutput<T>; _parseAsync(input: ParseInput, parseOptions?: ParseOptions): Promise<InferObjectOutput<T>>; /** * Parse from current iterator position (for recursive/streaming parsing) * @internal */ _parseFromPosition(iterator: Iterator<AnyXmlEvent> | AsyncIterator<AnyXmlEvent>, startEvent: StartElementEvent, startDepth: number, options?: ParseOptions, stateMachine?: XmlParsingStateMachine, parentContext?: SchemaActivation): InferObjectOutput<T> | Promise<InferObjectOutput<T>>; _parseText(text: string): InferObjectOutput<T>; /** * Set XPath expression for locating the object * @param path - XPath expression * @returns New schema with XPath */ xpath(path: string): XmlObjectSchema<T>; /** * Write raw content only (used inside parent object/array schema) * @internal */ _writeContent(data: InferObjectOutput<T>, options?: XmlWriteOptions): string; /** * Write object data to XML synchronously * @internal */ _writeSync(data: InferObjectOutput<T>, options?: XmlWriteOptions): string; /** * Write object data to WritableStream asynchronously * @internal */ _write(data: InferObjectOutput<T>, stream: WritableStream<Uint8Array>, options?: XmlWriteOptions): Promise<void>; } //#endregion //#region src/converter/XmlTransformSchema.d.ts /** * Schema for transforming parsed values * * @public */ declare class XmlTransformSchema<Output, Input, IntermediateOutput = unknown> extends XmlSchemaBase<Output, Input> { readonly schemaType: "TRANSFORM"; /** @internal */ readonly schema: XmlSchemaBase<IntermediateOutput, Input>; /** @internal */ readonly transformFn: (value: IntermediateOutput) => Output; constructor(schema: XmlSchemaBase<IntermediateOutput, Input>, transformFn: (value: IntermediateOutput) => Output); _parse(input: ParseInput, options?: ParseOptions): Output; _parseAsync(input: ParseInput, options?: ParseOptions): Promise<Output>; /** * Parse from current iterator position and apply transform * @internal */ _parseFromPosition(iterator: Iterator<AnyXmlEvent> | AsyncIterator<AnyXmlEvent>, startEvent: StartElementEvent, startDepth: number, options?: ParseOptions): Output | Promise<Output>; _parseText(text: string): Output; /** * Write transformed data to XML synchronously * Note: Transform is not reversible, so writing is not supported * @internal */ _writeSync(data: Output, options?: XmlWriteOptions): string; /** * Write transformed data to WritableStream asynchronously * Note: Transform is not reversible, so writing is not supported * @internal */ _write(data: Output, stream: WritableStream<Uint8Array>, options?: XmlWriteOptions): Promise<void>; } //#endregion //#region src/converter/XmlOptionalSchema.d.ts /** * Schema for optional values * * @public */ declare class XmlOptionalSchema<T extends XmlSchemaBase<unknown, unknown>> extends XmlSchemaBase<T['_output'] | undefined, T['_input'] | undefined> { readonly schema: T; readonly schemaType: "OPTIONAL"; constructor(schema: T); _parse(input: ParseInput, options?: ParseOptions): T['_output'] | undefined; _parseAsync(input: ParseInput, options?: ParseOptions): Promise<T['_output'] | undefined>; _parseText(text: string): T['_output'] | undefined; /** * Write optional data to XML synchronously * @internal */ _writeSync(data: T['_output'] | undefined, options?: XmlWriteOptions): string; /** * Write optional data to WritableStream asynchronously * @internal */ _write(data: T['_output'] | undefined, stream: WritableStream<Uint8Array>, options?: XmlWriteOptions): Promise<void>; } //#endregion //#region src/converter/types.d.ts /** * Parse options for XML converter * * @public */ interface ParseOptions { /** * Whether to trim whitespace from text content * @defaultValue false */ trimText?: boolean; /** * Whether to decode XML entities * @defaultValue true */ decodeEntities?: boolean; /** * Strict mode for parsing * @defaultValue false */ strict?: boolean; /** * Maximum XML depth * @defaultValue 1000 */ maxDepth?: number; /** * Maximum number of events to process * @defaultValue 1000000 */ maxEvents?: number; } /** * Options for string schema * * @public */ interface XmlStringOptions { /** * XPath expression to locate the element */ xpath?: string; /** * Minimum string length */ min?: number; /** * Maximum string length */ max?: number; /** * Regular expression pattern to validate against */ pattern?: RegExp; } /** * Options for number schema * * @public */ interface XmlNumberOptions { /** * XPath expression to locate the element */ xpath?: string; /** * Minimum value */ min?: number; /** * Maximum value */ max?: number; /** * Whether the number must be an integer * @defaultValue false */ int?: boolean; } /** * Options for object schema * * @public */ interface XmlObjectOptions { /** * XPath expression to locate the element */ xpath?: string; /** * Strict mode - reject unknown properties * @defaultValue false */ strict?: boolean; } /** * Writer configuration for XML element * * @public */ interface XmlElementWriteConfig { /** * Element name (required) */ element: string; /** * Write as attribute instead of element * Value is the attribute name */ asAttribute?: string; /** * Namespace configuration */ namespace?: { /** * Namespace prefix (e.g., 'dc', 'xsi') */ prefix?: string; /** * Namespace URI (e.g., 'http://purl.org/dc/elements/1.1/') */ uri?: string; }; /** * Wrap content in CDATA section * @defaultValue false */ cdata?: boolean; /** * Use self-closing tag for empty elements * @defaultValue false */ selfClosing?: boolean; /** * Add XML comment before element */ comment?: string; } /** * Options for XML writer * * @public */ interface XmlWriteOptions { /** * Format output with indentation * @defaultValue false */ prettyPrint?: boolean; /** * Indentation string * @defaultValue ' ' */ indentString?: string; /** * Text encoding for output * @defaultValue 'utf-8' */ encoding?: string; /** * Root element name * If not provided, no root element wrapper is added */ rootElement?: string; /** * Global namespace declarations */ namespaces?: Array<{ prefix: string; uri: string; }>; /** * Include XML declaration * @defaultValue true */ includeDeclaration?: boolean; /** * XML version for declaration * @defaultValue '1.0' */ xmlVersion?: string; /** * Custom writer instance * - StaxXmlWriterSync: for writeSync() method * - StaxXmlWriter: for write() async method */ writer?: StaxXmlWriterSync | StaxXmlWriter; } /** * Schema type constants for XML schema classification * * @public */ declare const SchemaType: { readonly STRING: "STRING"; readonly NUMBER: "NUMBER"; readonly ARRAY: "ARRAY"; readonly OBJECT: "OBJECT"; readonly TRANSFORM: "TRANSFORM"; readonly OPTIONAL: "OPTIONAL"; }; /** * Schema type union * * @public */ type SchemaType = typeof SchemaType[keyof typeof SchemaType]; //#endregion //#region src/converter/base.d.ts /** * Parse input type - accepts string, sync iterator, async iterator, or ReadableStream * * @public */ type ParseInput = string | ReadableStream<Uint8Array> | AsyncIterator<AnyXmlEvent> | Iterator<AnyXmlEvent>; /** * Base abstract class for all XML schema types * * @remarks * This class provides the foundation for zod-style declarative XML parsing. * Each schema type extends this class and implements the parsing logic. * * @public */ declare abstract class XmlSchemaBase<Output, Input = Output> { readonly _output: Output; readonly _input: Input; /** * Schema type identifier * @internal */ abstract readonly schemaType: SchemaType; /** * Writer configuration for this schema * @internal */ protected writeConfig?: XmlElementWriteConfig; /** * Parse XML input synchronously * @param input - XML string or sync iterator * @param options - Parse options * @returns Parsed output * @throws {XmlParseError} If parsing fails */ abstract _parse(input: ParseInput, options?: ParseOptions): Output; /** * Parse XML input asynchronously * @param input - XML string, stream, or async iterator * @param options - Parse options * @returns Parsed output * @throws {XmlParseError} If parsing fails */ abstract _parseAsync(input: ParseInput, options?: ParseOptions): Promise<Output>; /** * Write data to XML string synchronously * @param data - Data to write * @param options - Write options * @returns XML string * @internal */ abstract _writeSync(data: Output, options?: XmlWriteOptions): string; /** * Write data to WritableStream asynchronously * @param data - Data to write * @param stream - Writable stream to write to * @param options - Write options * @internal */ abstract _write(data: Output, stream: WritableStream<Uint8Array>, options?: XmlWriteOptions): Promise<void>; /** * Parse text content (used internally by parser) * @param text - Text content * @returns Parsed output * @internal */ abstract _parseText?(text: string): Output; /** * Parse from current iterator position (for streaming/recursive parsing) * @param iterator - Event iterator at current position * @param startEvent - The start element event * @param startDepth - Depth of the start element * @param options - Parse options * @returns Parsed output * @internal */ _parseFromPosition?(iterator: Iterator<AnyXmlEvent> | AsyncIterator<AnyXmlEvent>, startEvent: StartElementEvent, startDepth: number, options?: ParseOptions): Output | Promise<Output>; /** * Parse XML asynchronously (public API) * @param input - XML string, stream, or async iterator * @param options - Parse options * @returns Parsed output * @throws {XmlParseError} If parsing fails */ parse(input: ParseInput, options?: ParseOptions): Promise<Output>; /** * Parse XML synchronously (public API) * @param input - XML string or sync iterator * @param options - Parse options * @returns Parsed output * @throws {XmlParseError} If parsing fails */ parseSync(input: string | Iterator<AnyXmlEvent>, options?: ParseOptions): Output; /** * Parse XML asynchronously with error handling * @param input - XML string, stream, or async iterator * @param options - Parse options * @returns Parse result with success flag */ safeParse(input: ParseInput, options?: ParseOptions): Promise<ParseResult<Output>>; /** * Parse XML synchronously with error handling * @param input - XML string or sync iterator * @param options - Parse options * @returns Parse result with success flag */ safeParseSync(input: string | Iterator<AnyXmlEvent>, options?: ParseOptions): ParseResult<Output>; /** * Transform the parsed output * @param fn - Transform function * @returns New schema with transform applied */ transform<NewOutput>(fn: (value: Output) => NewOutput): XmlSchemaBase<NewOutput, Input>; /** * Make this schema optional * @returns New optional schema */ optional(): XmlSchemaBase<Output | undefined, Input | undefined>; /** * Convert this schema to an array schema * @param xpath - XPath expression for array elements * @returns New array schema */ array(xpath?: string): XmlSchemaBase<Output[], Input[]>; /** * Write data to XML string asynchronously (public API) * @param data - Data to write * @param options - Write options * @returns XML string */ write(data: Output, options?: XmlWriteOptions): Promise<string>; /** * Write data to WritableStream asynchronously (public API) * @param data - Data to write * @param stream - Writable stream to write to * @param options - Write options */ writeToStream(data: Output, stream: WritableStream<Uint8Array>, options?: XmlWriteOptions): Promise<void>; /** * Write data to XML string synchronously (public API) * @param data - Data to write * @param options - Write options * @returns XML string */ writeSync(data: Output, options?: XmlWriteOptions): string; /** * Configure writer settings for this schema * @param config - Writer configuration * @returns This schema with writer config */ writer(config: XmlElementWriteConfig): this; static _createTransform: <Output, Input, NewOutput>(schema: XmlSchemaBase<Output, Input>, fn: (value: Output) => NewOutput) => XmlSchemaBase<NewOutput, Input>; static _createOptional: <T extends XmlSchemaBase<unknown, unknown>>(schema: T) => XmlSchemaBase<T['_output'] | undefined, T['_input'] | undefined>; static _createArray: <T extends XmlSchemaBase<unknown, unknown>>(schema: T, xpath?: string) => XmlSchemaBase<T['_output'][], T['_input'][]>; } //#endregion //#region src/converter/XmlSchema.d.ts /** * Main XML schema class (extends XmlSchemaBase with all methods) * * @public */ declare abstract class XmlSchema<Output, Input = Output> extends XmlSchemaBase<Output, Input> {} //#endregion //#region src/converter/XmlBuilder.d.ts /** * Builder API for creating XML schemas * * @public */ declare class XmlBuilder { /** * Create a string schema * @param xpath - Optional XPath expression * @returns String schema */ string(xpath?: string): XmlStringSchema; /** * Create a number schema * @param xpath - Optional XPath expression * @returns Number schema */ number(xpath?: string): XmlNumberSchema; /** * Create an object schema * @param shape - Object shape definition * @param options - Optional object options * @returns Object schema */ object<T extends XmlObjectShape>(shape: T, options?: XmlObjectOptions): XmlObjectSchema<T>; /** * Create an array schema * @param element - Element schema * @param xpath - XPath expression for array elements * @returns Array schema */ array<T extends XmlSchema<unknown, unknown>>(element: T, xpath?: string): XmlArraySchema<T>; } /** * Singleton builder instance * * @public */ declare const x: XmlBuilder; //#endregion //#region src/converter/index.d.ts type Infer<T extends XmlSchema<unknown, unknown>> = T['_output']; //#endregion export { Infer, type InferObjectOutput, type ParseInput, type ParseOptions, type ParseResult, XmlArraySchema, XmlBuilder, type XmlNumberOptions, XmlNumberSchema, type XmlObjectOptions, XmlObjectSchema, type XmlObjectShape, XmlOptionalSchema, XmlParseError, XmlSchema, type XmlStringOptions, XmlStringSchema, XmlTransformSchema, x };