@polyxml/wasm 0.23.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bailey Nguyen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # `@polyxml/wasm`
2
+
3
+ WebAssembly XML/JSON conversion for Node.js, Bun, and browsers. This package
4
+ uses PolyXML's Rust core without a native Node addon.
5
+
6
+ ```js
7
+ import { createPolyXml } from '@polyxml/wasm'
8
+
9
+ const polyxml = await createPolyXml()
10
+ const value = polyxml.xmlToJson('<order><qty>2</qty></order>')
11
+ const xml = polyxml.jsonToXml(value)
12
+ ```
13
+
14
+ The browser entry point loads the adjacent `.wasm` asset with `fetch`; Node.js
15
+ and Bun load it from the package. An application can pass Wasm bytes or a URL
16
+ to `createPolyXml(source)` to control loading. `xmlToJsonBytes` and
17
+ `jsonToXmlBytes` return `Uint8Array` instead of converting to JS values/text.
18
+
19
+ For typed conversion, compile a self-contained XSD once:
20
+
21
+ ```js
22
+ const schema = polyxml.schemaFromXsd(xsdText, 'order')
23
+ const order = schema.xmlToJson(xmlBytes)
24
+ const xmlBytes = schema.jsonToXmlBytes(order)
25
+ schema.free()
26
+ ```
27
+
28
+ Inline XSDs with `include`, `import`, `redefine`, or `override` are rejected;
29
+ browser runtimes cannot read referenced schema files. Schema-free conversion
30
+ is dynamic and does not validate against an XSD.
31
+
32
+ Input `Uint8Array` values are copied into Wasm memory by `wasm-bindgen`, and
33
+ output bytes are copied back into JS memory. Converting to JS objects incurs
34
+ further allocations. The API does not promise zero-copy behavior or a speedup
35
+ over native JS parsers.
36
+
37
+ For documents containing repeated children under one root, stream records as
38
+ they complete:
39
+
40
+ ```js
41
+ for await (const record of polyxml.parseStream(readableStream)) {
42
+ console.log(record)
43
+ }
44
+ ```
45
+
46
+ `parseStream` accepts a web `ReadableStream` or async iterable of byte/string
47
+ chunks. It uses schema-free conversion and retains one record at a time, plus
48
+ the root tag and transient Wasm copies; the default per-record limit is 16 MiB.
49
+ DTDs and mixed root text are not supported.
50
+
51
+ ## Build from source
52
+
53
+ Install the `wasm32-unknown-unknown` Rust target and `wasm-pack`, then run:
54
+
55
+ ```bash
56
+ ./crates/polyxml-wasm/build.sh
57
+ node --test crates/polyxml-wasm/test/*.test.mjs
58
+ ```
59
+
60
+ The publishable package is generated in `crates/polyxml-wasm/pkg/`.
package/index.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ export type Bytes = string | Uint8Array | ArrayBuffer
2
+
3
+ export interface PolyXmlSchema {
4
+ xmlToJsonBytes(xml: Bytes): Uint8Array
5
+ xmlToJson(xml: Bytes): unknown
6
+ jsonToXmlBytes(json: unknown): Uint8Array
7
+ jsonToXml(json: unknown): string
8
+ free(): void
9
+ }
10
+
11
+ export interface PolyXml {
12
+ parseStream(source: ReadableStream<Uint8Array> | AsyncIterable<string | Uint8Array | ArrayBuffer>, options?: { maxRecordBytes?: number }): AsyncIterable<unknown>
13
+ xmlToJsonBytes(xml: Bytes): Uint8Array
14
+ xmlToJson(xml: Bytes): unknown
15
+ jsonToXmlBytes(json: unknown, rootName?: string): Uint8Array
16
+ jsonToXml(json: unknown, rootName?: string): string
17
+ schemaFromXsd(xsd: string, rootName?: string): PolyXmlSchema
18
+ }
19
+
20
+ export function createPolyXml(source?: BufferSource | WebAssembly.Module | Response | URL): Promise<PolyXml>
package/index.js ADDED
@@ -0,0 +1,52 @@
1
+ import initWasm, {
2
+ WasmSchema,
3
+ json_to_xml as rawJsonToXml,
4
+ xml_to_json as rawXmlToJson,
5
+ } from './polyxml_wasm.js'
6
+ import { parseStream } from './stream.js'
7
+
8
+ const encoder = new TextEncoder()
9
+ const decoder = new TextDecoder('utf-8', { fatal: true })
10
+ let initialization
11
+
12
+ function bytes(value) {
13
+ if (typeof value === 'string') return encoder.encode(value)
14
+ if (value instanceof Uint8Array) return value
15
+ if (value instanceof ArrayBuffer) return new Uint8Array(value)
16
+ throw new TypeError('Expected a string, Uint8Array, or ArrayBuffer')
17
+ }
18
+
19
+ function jsonBytes(value) {
20
+ if (typeof value === 'string' || value instanceof Uint8Array || value instanceof ArrayBuffer) {
21
+ return bytes(value)
22
+ }
23
+ return encoder.encode(JSON.stringify(value))
24
+ }
25
+
26
+ function wrapSchema(schema) {
27
+ return {
28
+ xmlToJsonBytes(xml) { return schema.xml_to_json(bytes(xml)) },
29
+ xmlToJson(xml) { return JSON.parse(decoder.decode(schema.xml_to_json(bytes(xml)))) },
30
+ jsonToXmlBytes(json) { return schema.json_to_xml(jsonBytes(json)) },
31
+ jsonToXml(json) { return decoder.decode(schema.json_to_xml(jsonBytes(json))) },
32
+ free() { schema.free() },
33
+ }
34
+ }
35
+
36
+ /** Initialize the Wasm module and return the XML/JSON API. */
37
+ export async function createPolyXml(source = new URL('./polyxml_wasm_bg.wasm', import.meta.url)) {
38
+ initialization ??= initWasm({ module_or_path: source }).catch((error) => {
39
+ initialization = undefined
40
+ throw error
41
+ })
42
+ await initialization
43
+ const api = {
44
+ parseStream(source, options) { return parseStream(api, source, options) },
45
+ xmlToJsonBytes(xml) { return rawXmlToJson(bytes(xml)) },
46
+ xmlToJson(xml) { return JSON.parse(decoder.decode(rawXmlToJson(bytes(xml)))) },
47
+ jsonToXmlBytes(json, rootName) { return rawJsonToXml(jsonBytes(json), rootName) },
48
+ jsonToXml(json, rootName) { return decoder.decode(rawJsonToXml(jsonBytes(json), rootName)) },
49
+ schemaFromXsd(xsd, rootName) { return wrapSchema(new WasmSchema(xsd, rootName)) },
50
+ }
51
+ return api
52
+ }
package/index.node.js ADDED
@@ -0,0 +1,8 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { createPolyXml as createPolyXmlWeb } from './index.js'
3
+
4
+ /** Node.js and Bun entry point; loads the local Wasm file automatically. */
5
+ export async function createPolyXml(source) {
6
+ const moduleSource = source ?? await readFile(new URL('./polyxml_wasm_bg.wasm', import.meta.url))
7
+ return createPolyXmlWeb(moduleSource)
8
+ }
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@polyxml/wasm",
3
+ "type": "module",
4
+ "collaborators": [
5
+ "Bailey Nguyen <bailey.tan.nguyen@gmail.com>"
6
+ ],
7
+ "description": "WebAssembly bindings for PolyXML XML/JSON transcoding",
8
+ "version": "0.23.0",
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/nth-bailey/PolyXML"
13
+ },
14
+ "files": [
15
+ "*.js",
16
+ "*.wasm",
17
+ "*.d.ts",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "main": "./index.node.js",
22
+ "types": "./index.d.ts",
23
+ "sideEffects": [
24
+ "./snippets/*"
25
+ ],
26
+ "module": "./index.js",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./index.d.ts",
30
+ "browser": "./index.js",
31
+ "node": "./index.node.js",
32
+ "default": "./index.js"
33
+ },
34
+ "./raw": "./polyxml_wasm.js"
35
+ }
36
+ }
@@ -0,0 +1,70 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ /**
5
+ * An inline XSD compiled once and reused for typed XML/JSON conversion.
6
+ */
7
+ export class WasmSchema {
8
+ free(): void;
9
+ [Symbol.dispose](): void;
10
+ /**
11
+ * Transcode JSON into XML using this schema's root element.
12
+ */
13
+ json_to_xml(json: Uint8Array): Uint8Array;
14
+ /**
15
+ * Compile a self-contained XSD. File-based includes/imports are unavailable in browsers.
16
+ */
17
+ constructor(xsd: string, root_name?: string | null);
18
+ /**
19
+ * Transcode XML into JSON using this schema's field types and aliases.
20
+ */
21
+ xml_to_json(xml: Uint8Array): Uint8Array;
22
+ }
23
+
24
+ /**
25
+ * Convert JSON bytes to XML bytes without a schema.
26
+ */
27
+ export function json_to_xml(json: Uint8Array, root_name?: string | null): Uint8Array;
28
+
29
+ /**
30
+ * Convert XML bytes to JSON bytes without a schema.
31
+ */
32
+ export function xml_to_json(xml: Uint8Array): Uint8Array;
33
+
34
+ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
35
+
36
+ export interface InitOutput {
37
+ readonly memory: WebAssembly.Memory;
38
+ readonly __wbg_wasmschema_free: (a: number, b: number) => void;
39
+ readonly json_to_xml: (a: number, b: number, c: number, d: number, e: number) => void;
40
+ readonly wasmschema_json_to_xml: (a: number, b: number, c: number, d: number) => void;
41
+ readonly wasmschema_new: (a: number, b: number, c: number, d: number, e: number) => void;
42
+ readonly wasmschema_xml_to_json: (a: number, b: number, c: number, d: number) => void;
43
+ readonly xml_to_json: (a: number, b: number, c: number) => void;
44
+ readonly __wbindgen_add_to_stack_pointer: (a: number) => number;
45
+ readonly __wbindgen_export: (a: number, b: number) => number;
46
+ readonly __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
47
+ readonly __wbindgen_export3: (a: number, b: number, c: number) => void;
48
+ }
49
+
50
+ export type SyncInitInput = BufferSource | WebAssembly.Module;
51
+
52
+ /**
53
+ * Instantiates the given `module`, which can either be bytes or
54
+ * a precompiled `WebAssembly.Module`.
55
+ *
56
+ * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
57
+ *
58
+ * @returns {InitOutput}
59
+ */
60
+ export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
61
+
62
+ /**
63
+ * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
64
+ * for everything else, calls `WebAssembly.instantiate` directly.
65
+ *
66
+ * @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
67
+ *
68
+ * @returns {Promise<InitOutput>}
69
+ */
70
+ export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
@@ -0,0 +1,397 @@
1
+ /* @ts-self-types="./polyxml_wasm.d.ts" */
2
+
3
+ /**
4
+ * An inline XSD compiled once and reused for typed XML/JSON conversion.
5
+ */
6
+ export class WasmSchema {
7
+ __destroy_into_raw() {
8
+ const ptr = this.__wbg_ptr;
9
+ this.__wbg_ptr = 0;
10
+ WasmSchemaFinalization.unregister(this);
11
+ return ptr;
12
+ }
13
+ free() {
14
+ const ptr = this.__destroy_into_raw();
15
+ wasm.__wbg_wasmschema_free(ptr, 0);
16
+ }
17
+ /**
18
+ * Transcode JSON into XML using this schema's root element.
19
+ * @param {Uint8Array} json
20
+ * @returns {Uint8Array}
21
+ */
22
+ json_to_xml(json) {
23
+ try {
24
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
25
+ const ptr0 = passArray8ToWasm0(json, wasm.__wbindgen_export);
26
+ const len0 = WASM_VECTOR_LEN;
27
+ wasm.wasmschema_json_to_xml(retptr, this.__wbg_ptr, ptr0, len0);
28
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
29
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
30
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
31
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
32
+ if (r3) {
33
+ throw takeObject(r2);
34
+ }
35
+ var v2 = getArrayU8FromWasm0(r0, r1).slice();
36
+ wasm.__wbindgen_export3(r0, r1 * 1, 1);
37
+ return v2;
38
+ } finally {
39
+ wasm.__wbindgen_add_to_stack_pointer(16);
40
+ }
41
+ }
42
+ /**
43
+ * Compile a self-contained XSD. File-based includes/imports are unavailable in browsers.
44
+ * @param {string} xsd
45
+ * @param {string | null} [root_name]
46
+ */
47
+ constructor(xsd, root_name) {
48
+ try {
49
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
50
+ const ptr0 = passStringToWasm0(xsd, wasm.__wbindgen_export, wasm.__wbindgen_export2);
51
+ const len0 = WASM_VECTOR_LEN;
52
+ var ptr1 = isLikeNone(root_name) ? 0 : passStringToWasm0(root_name, wasm.__wbindgen_export, wasm.__wbindgen_export2);
53
+ var len1 = WASM_VECTOR_LEN;
54
+ wasm.wasmschema_new(retptr, ptr0, len0, ptr1, len1);
55
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
56
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
57
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
58
+ if (r2) {
59
+ throw takeObject(r1);
60
+ }
61
+ this.__wbg_ptr = r0;
62
+ WasmSchemaFinalization.register(this, this.__wbg_ptr, this);
63
+ return this;
64
+ } finally {
65
+ wasm.__wbindgen_add_to_stack_pointer(16);
66
+ }
67
+ }
68
+ /**
69
+ * Transcode XML into JSON using this schema's field types and aliases.
70
+ * @param {Uint8Array} xml
71
+ * @returns {Uint8Array}
72
+ */
73
+ xml_to_json(xml) {
74
+ try {
75
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
76
+ const ptr0 = passArray8ToWasm0(xml, wasm.__wbindgen_export);
77
+ const len0 = WASM_VECTOR_LEN;
78
+ wasm.wasmschema_xml_to_json(retptr, this.__wbg_ptr, ptr0, len0);
79
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
80
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
81
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
82
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
83
+ if (r3) {
84
+ throw takeObject(r2);
85
+ }
86
+ var v2 = getArrayU8FromWasm0(r0, r1).slice();
87
+ wasm.__wbindgen_export3(r0, r1 * 1, 1);
88
+ return v2;
89
+ } finally {
90
+ wasm.__wbindgen_add_to_stack_pointer(16);
91
+ }
92
+ }
93
+ }
94
+ if (Symbol.dispose) WasmSchema.prototype[Symbol.dispose] = WasmSchema.prototype.free;
95
+
96
+ /**
97
+ * Convert JSON bytes to XML bytes without a schema.
98
+ * @param {Uint8Array} json
99
+ * @param {string | null} [root_name]
100
+ * @returns {Uint8Array}
101
+ */
102
+ export function json_to_xml(json, root_name) {
103
+ try {
104
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
105
+ const ptr0 = passArray8ToWasm0(json, wasm.__wbindgen_export);
106
+ const len0 = WASM_VECTOR_LEN;
107
+ var ptr1 = isLikeNone(root_name) ? 0 : passStringToWasm0(root_name, wasm.__wbindgen_export, wasm.__wbindgen_export2);
108
+ var len1 = WASM_VECTOR_LEN;
109
+ wasm.json_to_xml(retptr, ptr0, len0, ptr1, len1);
110
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
111
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
112
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
113
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
114
+ if (r3) {
115
+ throw takeObject(r2);
116
+ }
117
+ var v3 = getArrayU8FromWasm0(r0, r1).slice();
118
+ wasm.__wbindgen_export3(r0, r1 * 1, 1);
119
+ return v3;
120
+ } finally {
121
+ wasm.__wbindgen_add_to_stack_pointer(16);
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Convert XML bytes to JSON bytes without a schema.
127
+ * @param {Uint8Array} xml
128
+ * @returns {Uint8Array}
129
+ */
130
+ export function xml_to_json(xml) {
131
+ try {
132
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
133
+ const ptr0 = passArray8ToWasm0(xml, wasm.__wbindgen_export);
134
+ const len0 = WASM_VECTOR_LEN;
135
+ wasm.xml_to_json(retptr, ptr0, len0);
136
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
137
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
138
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
139
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
140
+ if (r3) {
141
+ throw takeObject(r2);
142
+ }
143
+ var v2 = getArrayU8FromWasm0(r0, r1).slice();
144
+ wasm.__wbindgen_export3(r0, r1 * 1, 1);
145
+ return v2;
146
+ } finally {
147
+ wasm.__wbindgen_add_to_stack_pointer(16);
148
+ }
149
+ }
150
+ function __wbg_get_imports() {
151
+ const import0 = {
152
+ __proto__: null,
153
+ __wbg___wbindgen_throw_5d9e815e6fdf150f: function(arg0, arg1) {
154
+ throw new Error(getStringFromWasm0(arg0, arg1));
155
+ },
156
+ __wbindgen_generic_0000000000000001: function(arg0, arg1) {
157
+ // Cast intrinsic for `Ref(String) -> Externref`.
158
+ const ret = getStringFromWasm0(arg0, arg1);
159
+ return addHeapObject(ret);
160
+ },
161
+ };
162
+ return {
163
+ __proto__: null,
164
+ "./polyxml_wasm_bg.js": import0,
165
+ };
166
+ }
167
+
168
+ const WasmSchemaFinalization = (typeof FinalizationRegistry === 'undefined')
169
+ ? { register: () => {}, unregister: () => {} }
170
+ : new FinalizationRegistry(ptr => wasm.__wbg_wasmschema_free(ptr, 1));
171
+
172
+ function addHeapObject(obj) {
173
+ if (heap_next === heap.length) heap.push(heap.length + 1);
174
+ const idx = heap_next;
175
+ heap_next = heap[idx];
176
+
177
+ heap[idx] = obj;
178
+ return idx;
179
+ }
180
+
181
+ function dropObject(idx) {
182
+ if (idx < 1028) return;
183
+ heap[idx] = heap_next;
184
+ heap_next = idx;
185
+ }
186
+
187
+ function getArrayU8FromWasm0(ptr, len) {
188
+ ptr = ptr >>> 0;
189
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
190
+ }
191
+
192
+ let cachedDataViewMemory0 = null;
193
+ function getDataViewMemory0() {
194
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
195
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
196
+ }
197
+ return cachedDataViewMemory0;
198
+ }
199
+
200
+ function getStringFromWasm0(ptr, len) {
201
+ return decodeText(ptr >>> 0, len);
202
+ }
203
+
204
+ let cachedUint8ArrayMemory0 = null;
205
+ function getUint8ArrayMemory0() {
206
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
207
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
208
+ }
209
+ return cachedUint8ArrayMemory0;
210
+ }
211
+
212
+ function getObject(idx) { return heap[idx]; }
213
+
214
+ let heap = new Array(1024).fill(undefined);
215
+ heap.push(undefined, null, true, false);
216
+
217
+ let heap_next = heap.length;
218
+
219
+ function isLikeNone(x) {
220
+ return x === undefined || x === null;
221
+ }
222
+
223
+ function passArray8ToWasm0(arg, malloc) {
224
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
225
+ getUint8ArrayMemory0().set(arg, ptr / 1);
226
+ WASM_VECTOR_LEN = arg.length;
227
+ return ptr;
228
+ }
229
+
230
+ function passStringToWasm0(arg, malloc, realloc) {
231
+ if (realloc === undefined) {
232
+ const buf = cachedTextEncoder.encode(arg);
233
+ const ptr = malloc(buf.length, 1) >>> 0;
234
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
235
+ WASM_VECTOR_LEN = buf.length;
236
+ return ptr;
237
+ }
238
+
239
+ let len = arg.length;
240
+ let ptr = malloc(len, 1) >>> 0;
241
+
242
+ const mem = getUint8ArrayMemory0();
243
+
244
+ let offset = 0;
245
+
246
+ for (; offset < len; offset++) {
247
+ const code = arg.charCodeAt(offset);
248
+ if (code > 0x7F) break;
249
+ mem[ptr + offset] = code;
250
+ }
251
+ if (offset !== len) {
252
+ if (offset !== 0) {
253
+ arg = arg.slice(offset);
254
+ }
255
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
256
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
257
+ const ret = cachedTextEncoder.encodeInto(arg, view);
258
+
259
+ offset += ret.written;
260
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
261
+ }
262
+
263
+ WASM_VECTOR_LEN = offset;
264
+ return ptr;
265
+ }
266
+
267
+ function takeObject(idx) {
268
+ const ret = getObject(idx);
269
+ dropObject(idx);
270
+ return ret;
271
+ }
272
+
273
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
274
+ cachedTextDecoder.decode();
275
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
276
+ let numBytesDecoded = 0;
277
+ function decodeText(ptr, len) {
278
+ numBytesDecoded += len;
279
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
280
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
281
+ cachedTextDecoder.decode();
282
+ numBytesDecoded = len;
283
+ }
284
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
285
+ }
286
+
287
+ const cachedTextEncoder = new TextEncoder();
288
+
289
+ if (!('encodeInto' in cachedTextEncoder)) {
290
+ cachedTextEncoder.encodeInto = function (arg, view) {
291
+ const buf = cachedTextEncoder.encode(arg);
292
+ view.set(buf);
293
+ return {
294
+ read: arg.length,
295
+ written: buf.length
296
+ };
297
+ };
298
+ }
299
+
300
+ let WASM_VECTOR_LEN = 0;
301
+
302
+ let wasmModule, wasmInstance, wasm;
303
+ function __wbg_finalize_init(instance, module) {
304
+ wasmInstance = instance;
305
+ wasm = instance.exports;
306
+ wasmModule = module;
307
+ cachedDataViewMemory0 = null;
308
+ cachedUint8ArrayMemory0 = null;
309
+ return wasm;
310
+ }
311
+
312
+ async function __wbg_load(module, imports) {
313
+ if (typeof Response === 'function' && module instanceof Response) {
314
+ if (!module.ok) {
315
+ throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);
316
+ }
317
+
318
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
319
+ try {
320
+ return await WebAssembly.instantiateStreaming(module, imports);
321
+ } catch (e) {
322
+ const validResponse = expectedResponseType(module.type);
323
+
324
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
325
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
326
+
327
+ } else { throw e; }
328
+ }
329
+ }
330
+
331
+ const bytes = await module.arrayBuffer();
332
+ return await WebAssembly.instantiate(bytes, imports);
333
+ } else {
334
+ const instance = await WebAssembly.instantiate(module, imports);
335
+
336
+ if (instance instanceof WebAssembly.Instance) {
337
+ return { instance, module };
338
+ } else {
339
+ return instance;
340
+ }
341
+ }
342
+
343
+ function expectedResponseType(type) {
344
+ switch (type) {
345
+ case 'basic': case 'cors': case 'default': return true;
346
+ }
347
+ return false;
348
+ }
349
+ }
350
+
351
+ function initSync(module) {
352
+ if (wasm !== undefined) return wasm;
353
+
354
+
355
+ if (module !== undefined) {
356
+ if (Object.getPrototypeOf(module) === Object.prototype) {
357
+ ({module} = module)
358
+ } else {
359
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
360
+ }
361
+ }
362
+
363
+ const imports = __wbg_get_imports();
364
+ if (!(module instanceof WebAssembly.Module)) {
365
+ module = new WebAssembly.Module(module);
366
+ }
367
+ const instance = new WebAssembly.Instance(module, imports);
368
+ return __wbg_finalize_init(instance, module);
369
+ }
370
+
371
+ async function __wbg_init(module_or_path) {
372
+ if (wasm !== undefined) return wasm;
373
+
374
+
375
+ if (module_or_path !== undefined) {
376
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
377
+ ({module_or_path} = module_or_path)
378
+ } else {
379
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
380
+ }
381
+ }
382
+
383
+ if (module_or_path === undefined) {
384
+ module_or_path = new URL('polyxml_wasm_bg.wasm', import.meta.url);
385
+ }
386
+ const imports = __wbg_get_imports();
387
+
388
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
389
+ module_or_path = fetch(module_or_path);
390
+ }
391
+
392
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
393
+
394
+ return __wbg_finalize_init(instance, module);
395
+ }
396
+
397
+ export { initSync, __wbg_init as default };
Binary file
@@ -0,0 +1,13 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ export const memory: WebAssembly.Memory;
4
+ export const __wbg_wasmschema_free: (a: number, b: number) => void;
5
+ export const json_to_xml: (a: number, b: number, c: number, d: number, e: number) => void;
6
+ export const wasmschema_json_to_xml: (a: number, b: number, c: number, d: number) => void;
7
+ export const wasmschema_new: (a: number, b: number, c: number, d: number, e: number) => void;
8
+ export const wasmschema_xml_to_json: (a: number, b: number, c: number, d: number) => void;
9
+ export const xml_to_json: (a: number, b: number, c: number) => void;
10
+ export const __wbindgen_add_to_stack_pointer: (a: number) => number;
11
+ export const __wbindgen_export: (a: number, b: number) => number;
12
+ export const __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
13
+ export const __wbindgen_export3: (a: number, b: number, c: number) => void;
package/stream.js ADDED
@@ -0,0 +1,134 @@
1
+ const encoder = new TextEncoder()
2
+
3
+ function tagEnd(source, start) {
4
+ if (source.startsWith('<!--', start)) {
5
+ const end = source.indexOf('-->', start + 4)
6
+ return end < 0 ? -1 : end + 3
7
+ }
8
+ if (source.startsWith('<![CDATA[', start)) {
9
+ const end = source.indexOf(']]>', start + 9)
10
+ return end < 0 ? -1 : end + 3
11
+ }
12
+ if (source.startsWith('<?', start)) {
13
+ const end = source.indexOf('?>', start + 2)
14
+ return end < 0 ? -1 : end + 2
15
+ }
16
+ let quote = ''
17
+ for (let i = start + 1; i < source.length; i++) {
18
+ const char = source[i]
19
+ if (quote) {
20
+ if (char === quote) quote = ''
21
+ } else if (char === '"' || char === "'") {
22
+ quote = char
23
+ } else if (char === '>') {
24
+ return i + 1
25
+ }
26
+ }
27
+ return -1
28
+ }
29
+
30
+ /** Yield each direct child of an XML document root as soon as it is complete.
31
+ * Memory use is bounded by the largest child and root tag, subject to maxRecordBytes.
32
+ */
33
+ export async function* parseStream(api, source, { maxRecordBytes = 16 * 1024 * 1024 } = {}) {
34
+ if (!Number.isSafeInteger(maxRecordBytes) || maxRecordBytes < 1) {
35
+ throw new RangeError('maxRecordBytes must be a positive safe integer')
36
+ }
37
+ const input = source?.getReader ? readableChunks(source) : source
38
+ if (!input?.[Symbol.asyncIterator]) throw new TypeError('Expected a ReadableStream or async iterable')
39
+ const utf8 = new TextDecoder('utf-8', { fatal: true })
40
+ let buffer = ''
41
+ let cursor = 0
42
+ let root = ''
43
+ let rootName = ''
44
+ let childStart = -1
45
+ let childName = ''
46
+ const names = []
47
+ let done = false
48
+
49
+ for await (const chunk of input) {
50
+ if (typeof chunk !== 'string' && !(chunk instanceof Uint8Array) && !(chunk instanceof ArrayBuffer)) {
51
+ throw new TypeError('Stream chunks must be strings, Uint8Array, or ArrayBuffer')
52
+ }
53
+ buffer += typeof chunk === 'string' ? chunk : utf8.decode(chunk, { stream: true })
54
+ while (true) {
55
+ const start = buffer.indexOf('<', cursor)
56
+ if (start < 0) break
57
+ if (childStart < 0 && buffer.slice(cursor, start).trim()) {
58
+ throw new Error('Text outside a record is not supported')
59
+ }
60
+ if (buffer.length - start < 2) break
61
+ const end = tagEnd(buffer, start)
62
+ if (end < 0) break
63
+ const tag = buffer.slice(start, end)
64
+ cursor = end
65
+ if (tag.startsWith('<!--') || tag.startsWith('<?')) continue
66
+ if (tag.startsWith('<![CDATA[')) {
67
+ if (childStart < 0) throw new Error('CDATA outside a record is not supported')
68
+ continue
69
+ }
70
+ if (tag.startsWith('<!')) throw new Error('DOCTYPE and declarations are not supported by parseStream')
71
+ const closing = tag.startsWith('</')
72
+ const name = /^<\/?([^\s/>]+)/.exec(tag)?.[1]
73
+ if (!name) throw new Error('Invalid XML tag')
74
+ const empty = !closing && /\/\s*>$/.test(tag)
75
+ if (!root) {
76
+ if (closing || empty) throw new Error('Expected a nonempty document root')
77
+ root = tag
78
+ rootName = name
79
+ } else if (done) {
80
+ throw new Error('Content after document root')
81
+ } else if (closing && names.length === 0) {
82
+ if (name !== rootName) throw new Error('Mismatched document root')
83
+ done = true
84
+ } else if (closing) {
85
+ if (names.pop() !== name) throw new Error('Mismatched XML end tag')
86
+ } else {
87
+ if (names.length === 0) {
88
+ childStart = start
89
+ childName = name.split(':').pop()
90
+ }
91
+ if (!empty) names.push(name)
92
+ }
93
+ if (childStart >= 0 && names.length === 0) {
94
+ const child = buffer.slice(childStart, end)
95
+ if (encoder.encode(child).length > maxRecordBytes) throw new RangeError('XML record exceeds maxRecordBytes')
96
+ const document = root + child + `</${rootName}>`
97
+ const result = api.xmlToJson(document)
98
+ yield { [childName]: result[rootName][childName] }
99
+ buffer = buffer.slice(end)
100
+ cursor = 0
101
+ childStart = -1
102
+ }
103
+ }
104
+ if (childStart >= 0 && buffer.length - childStart > maxRecordBytes) {
105
+ throw new RangeError('XML record exceeds maxRecordBytes')
106
+ }
107
+ if (!root && buffer.length > maxRecordBytes) {
108
+ throw new RangeError('XML root tag exceeds maxRecordBytes')
109
+ }
110
+ if (childStart < 0 && !buffer.trim()) {
111
+ buffer = ''
112
+ cursor = 0
113
+ }
114
+ if (childStart < 0 && cursor > 0) {
115
+ buffer = buffer.slice(cursor)
116
+ cursor = 0
117
+ }
118
+ }
119
+ buffer += utf8.decode()
120
+ if (!done || buffer.trim()) throw new Error('Incomplete XML document')
121
+ }
122
+
123
+ async function* readableChunks(stream) {
124
+ const reader = stream.getReader()
125
+ try {
126
+ while (true) {
127
+ const { done, value } = await reader.read()
128
+ if (done) return
129
+ yield value
130
+ }
131
+ } finally {
132
+ reader.releaseLock()
133
+ }
134
+ }