@tinyactors/sxml 0.0.0-stage → 0.3.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 +601 -2
- package/dist/allkeys.txt +39435 -0
- package/dist/index.d.ts +679 -0
- package/dist/index.js +1990 -0
- package/dist/linker.d.ts +20 -0
- package/dist/linker.js +196 -0
- package/dist/stream.d.ts +45 -0
- package/dist/stream.js +259 -0
- package/dist/sxml.wasm +0 -0
- package/dist/wasi.d.ts +3 -0
- package/dist/wasi.js +55 -0
- package/package.json +36 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1990 @@
|
|
|
1
|
+
// sxml for JavaScript: XML parsing, XPath 4.0, XQuery 4.0, XSLT 4.0, XSD 1.1
|
|
2
|
+
// validation and serialization in Node.js and browsers, over sxml.wasm
|
|
3
|
+
// (docs/DECISIONS.md, D10, D138, D272).
|
|
4
|
+
//
|
|
5
|
+
// import { load } from '@tinyactors/sxml';
|
|
6
|
+
// const sxml = await load();
|
|
7
|
+
// const processor = sxml.createProcessor();
|
|
8
|
+
// const book = processor.parse('<book><title>XPath</title></book>');
|
|
9
|
+
// processor.evaluate('//title/string()', { context: book }).toString();
|
|
10
|
+
// // '"XPath"' (the adaptive method of Serialization 4.0)
|
|
11
|
+
//
|
|
12
|
+
// The one module has every language and every optional feature (D272):
|
|
13
|
+
// XQuery 4.0 (Processor.compileQuery), XSLT 4.0 (Processor.compileStylesheet)
|
|
14
|
+
// and XSD 1.1 validation (Processor.compileSchema) besides XPath, and EXI
|
|
15
|
+
// (Processor.encodeExi and Processor.parseExi, D333).
|
|
16
|
+
//
|
|
17
|
+
// Every object that owns memory in the module (Processor, XPathExpression,
|
|
18
|
+
// XQuery, Stylesheet, Schema, Value) has dispose(); one that is never disposed is released when it is
|
|
19
|
+
// garbage collected (FinalizationRegistry). The C side is the shim in
|
|
20
|
+
// ../sxml_javascript.c; the word offsets below follow its structs.
|
|
21
|
+
import { linkLanguageModule } from "./linker.js";
|
|
22
|
+
import { ChunkReader, OutputRouter, readWhole, } from "./stream.js";
|
|
23
|
+
import { wasiImports } from "./wasi.js";
|
|
24
|
+
export { nodeStreamSink, outputReadableStream, textSink, writableStreamSink, } from "./stream.js";
|
|
25
|
+
/** The alignments of ExiOptions, in sxml_exi_alignment's order. */
|
|
26
|
+
const exi_alignments = ['bit-packed', 'byte-alignment', 'pre-compression', 'compression'];
|
|
27
|
+
/** The items of ExiOptions.preserve, in the order of the words of
|
|
28
|
+
* sxml_host_exi_options. */
|
|
29
|
+
const exi_preserved_items = ['comments', 'pis', 'dtd', 'prefixes', 'lexical-values'];
|
|
30
|
+
/** The two words of an optional count of ExiOptions (whether it is given,
|
|
31
|
+
* its value); a RangeError for a number that is not an integer from 0 to
|
|
32
|
+
* 2^32 - 1. */
|
|
33
|
+
function exiCountWords(name, count) {
|
|
34
|
+
if (count === undefined) {
|
|
35
|
+
return [0, 0];
|
|
36
|
+
}
|
|
37
|
+
if (typeof count !== 'number') {
|
|
38
|
+
throw new TypeError(`sxml: the EXI option ${name} is not a number`);
|
|
39
|
+
}
|
|
40
|
+
if (!Number.isInteger(count) || count < 0 || count > 0xffffffff) {
|
|
41
|
+
throw new RangeError(`sxml: the EXI option ${name} is not an integer from 0 to 4294967295`);
|
|
42
|
+
}
|
|
43
|
+
return [1, count];
|
|
44
|
+
}
|
|
45
|
+
/** Whether an optional flag of ExiOptions is set; a TypeError for a value
|
|
46
|
+
* that is not a boolean. */
|
|
47
|
+
function exiFlag(name, flag) {
|
|
48
|
+
if (flag !== undefined && typeof flag !== 'boolean') {
|
|
49
|
+
throw new TypeError(`sxml: the EXI option ${name} is not a boolean`);
|
|
50
|
+
}
|
|
51
|
+
return flag === true;
|
|
52
|
+
}
|
|
53
|
+
/** The sixteen words of sxml_host_exi_options, checked: a TypeError for
|
|
54
|
+
* an unknown alignment or preserve item, a RangeError for a count out of
|
|
55
|
+
* range. The schema's handle is the last word. */
|
|
56
|
+
function exiOptionWords(options, schemaAddress) {
|
|
57
|
+
const alignment = exi_alignments.indexOf(options.alignment ?? 'bit-packed');
|
|
58
|
+
if (alignment < 0) {
|
|
59
|
+
throw new TypeError(`sxml: unknown EXI alignment ${String(options.alignment)}`);
|
|
60
|
+
}
|
|
61
|
+
const preserve = options.preserve ?? [];
|
|
62
|
+
if (!Array.isArray(preserve)) {
|
|
63
|
+
throw new TypeError('sxml: the EXI option preserve is not an array');
|
|
64
|
+
}
|
|
65
|
+
for (const item of preserve) {
|
|
66
|
+
if (typeof item !== 'string' || !exi_preserved_items.includes(item)) {
|
|
67
|
+
throw new TypeError(`sxml: unknown EXI preserve item ${String(item)}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return [
|
|
71
|
+
alignment,
|
|
72
|
+
...exi_preserved_items.map((item) => (preserve.includes(item) ? 1 : 0)),
|
|
73
|
+
exiFlag('fragment', options.fragment) ? 1 : 0,
|
|
74
|
+
exiFlag('strict', options.strict) ? 1 : 0,
|
|
75
|
+
exiFlag('selfContained', options.selfContained) ? 1 : 0,
|
|
76
|
+
...exiCountWords('blockSize', options.blockSize),
|
|
77
|
+
...exiCountWords('valueMaxLength', options.valueMaxLength),
|
|
78
|
+
...exiCountWords('valuePartitionCapacity', options.valuePartitionCapacity),
|
|
79
|
+
schemaAddress,
|
|
80
|
+
];
|
|
81
|
+
}
|
|
82
|
+
// ----------------------------------------------------------------- Errors
|
|
83
|
+
/** A failure in sxml: a static, dynamic or type error of the expression
|
|
84
|
+
* (with its error code), a document that is not well-formed, a limit, or
|
|
85
|
+
* out of memory. */
|
|
86
|
+
export class SxmlError extends Error {
|
|
87
|
+
/** The status, such as 'DYNAMIC_ERROR' or 'MALFORMED_INPUT'. */
|
|
88
|
+
status;
|
|
89
|
+
/** The error code as prefix:local, such as 'err:FOAR0001'; '' when the
|
|
90
|
+
* status has none. */
|
|
91
|
+
code;
|
|
92
|
+
codeNamespaceUri;
|
|
93
|
+
codeLocalName;
|
|
94
|
+
description;
|
|
95
|
+
/** The module or document the location is in: 'expression', 'query',
|
|
96
|
+
* a module's URI; '' when unknown. */
|
|
97
|
+
sourceName;
|
|
98
|
+
lineNumber;
|
|
99
|
+
columnNumber;
|
|
100
|
+
constructor(fields) {
|
|
101
|
+
const code = fields.codeLocalName === ''
|
|
102
|
+
? ''
|
|
103
|
+
: fields.codePrefix !== ''
|
|
104
|
+
? `${fields.codePrefix}:${fields.codeLocalName}`
|
|
105
|
+
: fields.codeNamespaceUri !== ''
|
|
106
|
+
? `Q{${fields.codeNamespaceUri}}${fields.codeLocalName}`
|
|
107
|
+
: fields.codeLocalName;
|
|
108
|
+
const where = fields.lineNumber > 0 ? `${fields.lineNumber}:${fields.columnNumber}: ` : '';
|
|
109
|
+
const what = fields.description !== '' ? fields.description : fields.status;
|
|
110
|
+
super(`${where}${code !== '' ? `${code}: ` : ''}${what}`);
|
|
111
|
+
this.name = 'SxmlError';
|
|
112
|
+
this.status = fields.status;
|
|
113
|
+
this.code = code;
|
|
114
|
+
this.codeNamespaceUri = fields.codeNamespaceUri;
|
|
115
|
+
this.codeLocalName = fields.codeLocalName;
|
|
116
|
+
this.description = fields.description;
|
|
117
|
+
this.sourceName = fields.sourceName ?? '';
|
|
118
|
+
this.lineNumber = fields.lineNumber;
|
|
119
|
+
this.columnNumber = fields.columnNumber;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** A schema that does not compile: every error, with the first as the
|
|
123
|
+
* SxmlError's own code, description and location. */
|
|
124
|
+
export class SchemaError extends SxmlError {
|
|
125
|
+
reports;
|
|
126
|
+
constructor(error, reports) {
|
|
127
|
+
const prefix = /^([^:{}]+):/.exec(error.code)?.[1] ?? '';
|
|
128
|
+
super({ ...error, codePrefix: prefix });
|
|
129
|
+
this.name = 'SchemaError';
|
|
130
|
+
this.reports = Object.freeze(reports);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// sxml_status values the package itself returns from the resolver import.
|
|
134
|
+
const status_ok = 0;
|
|
135
|
+
const status_out_of_memory = 6;
|
|
136
|
+
const status_input_output_failed = 13;
|
|
137
|
+
const resource_kinds = [
|
|
138
|
+
'xml-document',
|
|
139
|
+
'text',
|
|
140
|
+
'binary',
|
|
141
|
+
'collection',
|
|
142
|
+
'uri-collection',
|
|
143
|
+
'xquery-module',
|
|
144
|
+
'xslt-module',
|
|
145
|
+
'xslt-package',
|
|
146
|
+
'schema-document',
|
|
147
|
+
'external-entity',
|
|
148
|
+
'timezone-data',
|
|
149
|
+
'collation-data',
|
|
150
|
+
'locale-data',
|
|
151
|
+
];
|
|
152
|
+
/** The URI the uca-collation feature asks for its DUCET by. */
|
|
153
|
+
const ducet_uri = 'http://www.unicode.org/Public/UCA/16.0.0/allkeys.txt';
|
|
154
|
+
const encoder = new TextEncoder();
|
|
155
|
+
const decoder = new TextDecoder();
|
|
156
|
+
/** A processor's C side and the handles made with it, so that destroying
|
|
157
|
+
* it releases them first (they could not outlive it in C). */
|
|
158
|
+
/** The conventional prefixes of the optional features' namespaces, bound
|
|
159
|
+
* for XPath and XQuery wherever the feature is present, as the sxml
|
|
160
|
+
* command binds them (EXPath Binary 4.0, 1.5; EXPath File 4.0, 1.7;
|
|
161
|
+
* D235; tree-sitter for tree-sitter:parse and sxml for the elements of
|
|
162
|
+
* its documents, D307; exi for exi:serialize, exi:parse and the output
|
|
163
|
+
* method exi:exi, D333): feature name, prefix, namespace URI. */
|
|
164
|
+
const featurePrefixes = [
|
|
165
|
+
['expath-binary', 'bin', 'http://expath.org/ns/binary'],
|
|
166
|
+
['source-code', 'sxml', 'urn:sxml'],
|
|
167
|
+
['source-code', 'tree-sitter', 'urn:sxml:tree-sitter'],
|
|
168
|
+
['expath-file', 'file', 'http://expath.org/ns/file'],
|
|
169
|
+
['exi', 'exi', 'urn:sxml:exi'],
|
|
170
|
+
];
|
|
171
|
+
class ProcessorState {
|
|
172
|
+
module;
|
|
173
|
+
address;
|
|
174
|
+
resolver;
|
|
175
|
+
/** Handles not yet released: address to kind. */
|
|
176
|
+
live = new Map();
|
|
177
|
+
/** The exception the resolver threw during the current call. */
|
|
178
|
+
pendingException = undefined;
|
|
179
|
+
isInResolver = false;
|
|
180
|
+
/** Whether an output sink or chunk source is running (D294). */
|
|
181
|
+
isInSink = false;
|
|
182
|
+
/** The router of the current streaming call's output (D294). */
|
|
183
|
+
outputRouter = undefined;
|
|
184
|
+
/** The chunk sources the resolver delivered, by reader identifier. */
|
|
185
|
+
readers = new Map();
|
|
186
|
+
nextReaderIdentifier = 1;
|
|
187
|
+
/** ProcessorOptions.outputChunkByteCount. */
|
|
188
|
+
outputChunkByteCount = default_output_chunk_byte_count;
|
|
189
|
+
/** parse-json($json), compiled when first needed. */
|
|
190
|
+
jsonExpression = 0;
|
|
191
|
+
/** What sxml_javascript_processor_destroy found still allocated. */
|
|
192
|
+
leakedAllocationCount = 0;
|
|
193
|
+
/** The processor's sxml_source_code_language_view and its array, made
|
|
194
|
+
* with malloc, which must outlive it; 0 for none. */
|
|
195
|
+
codeLanguageView = 0;
|
|
196
|
+
/** The prefixes of the processor's features' namespaces (D235). */
|
|
197
|
+
featureNamespaces;
|
|
198
|
+
constructor(module, address, resolver, features) {
|
|
199
|
+
this.module = module;
|
|
200
|
+
this.address = address;
|
|
201
|
+
this.resolver = resolver;
|
|
202
|
+
const namespaces = {};
|
|
203
|
+
for (const [feature, prefix, uri] of featurePrefixes) {
|
|
204
|
+
if (features.includes(feature)) {
|
|
205
|
+
namespaces[prefix] = uri;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
this.featureNamespaces = Object.freeze(namespaces);
|
|
209
|
+
}
|
|
210
|
+
/** The namespaces of a compilation: the features' prefixes, then the
|
|
211
|
+
* caller's, which may rebind them. */
|
|
212
|
+
staticNamespaces(namespaces) {
|
|
213
|
+
return Object.entries({ ...this.featureNamespaces, ...(namespaces ?? {}) });
|
|
214
|
+
}
|
|
215
|
+
releaseHandle(kind, address) {
|
|
216
|
+
if (this.address === 0 || !this.live.delete(address)) {
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
this.destroyHandle(kind, address);
|
|
220
|
+
}
|
|
221
|
+
/** Releases a handle by its kind's export. */
|
|
222
|
+
destroyHandle(kind, address) {
|
|
223
|
+
const exports = this.module.exports;
|
|
224
|
+
switch (kind) {
|
|
225
|
+
case 'value':
|
|
226
|
+
exports.sxml_javascript_value_release(address);
|
|
227
|
+
break;
|
|
228
|
+
case 'expression':
|
|
229
|
+
exports.sxml_javascript_expression_destroy(address);
|
|
230
|
+
break;
|
|
231
|
+
case 'query':
|
|
232
|
+
exports.sxml_javascript_query_destroy?.(address);
|
|
233
|
+
break;
|
|
234
|
+
case 'stylesheet':
|
|
235
|
+
exports.sxml_javascript_stylesheet_destroy?.(address);
|
|
236
|
+
break;
|
|
237
|
+
case 'schema':
|
|
238
|
+
exports.sxml_javascript_schema_destroy?.(address);
|
|
239
|
+
break;
|
|
240
|
+
case 'schematron':
|
|
241
|
+
exports.sxml_javascript_schematron_destroy?.(address);
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
destroy() {
|
|
246
|
+
if (this.address === 0) {
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
for (const [address, kind] of this.live) {
|
|
250
|
+
this.destroyHandle(kind, address);
|
|
251
|
+
}
|
|
252
|
+
this.live.clear();
|
|
253
|
+
if (this.jsonExpression !== 0) {
|
|
254
|
+
this.module.exports.sxml_javascript_expression_destroy(this.jsonExpression);
|
|
255
|
+
this.jsonExpression = 0;
|
|
256
|
+
}
|
|
257
|
+
this.module.processors.delete(this.address);
|
|
258
|
+
this.leakedAllocationCount = this.module.exports.sxml_javascript_processor_destroy(this.address);
|
|
259
|
+
this.address = 0;
|
|
260
|
+
if (this.codeLanguageView !== 0) {
|
|
261
|
+
this.module.exports.free(this.codeLanguageView);
|
|
262
|
+
this.codeLanguageView = 0;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/** Memory for one call's request: texts and words, released together. */
|
|
267
|
+
class Scratch {
|
|
268
|
+
state;
|
|
269
|
+
addresses = [];
|
|
270
|
+
constructor(state) {
|
|
271
|
+
this.state = state;
|
|
272
|
+
}
|
|
273
|
+
allocate(byteCount) {
|
|
274
|
+
const address = this.state.module.exports.sxml_javascript_allocate(this.state.address, byteCount);
|
|
275
|
+
if (address === 0) {
|
|
276
|
+
throw outOfMemory();
|
|
277
|
+
}
|
|
278
|
+
this.addresses.push(address);
|
|
279
|
+
return address;
|
|
280
|
+
}
|
|
281
|
+
/** Copies text (UTF-8) or bytes in; returns the two words of a byte
|
|
282
|
+
* view. */
|
|
283
|
+
view(content) {
|
|
284
|
+
const bytes = typeof content === 'string' ? encoder.encode(content) : content;
|
|
285
|
+
const address = this.allocate(bytes.byteLength);
|
|
286
|
+
this.state.module.bytes().set(bytes, address);
|
|
287
|
+
return [address, bytes.byteLength];
|
|
288
|
+
}
|
|
289
|
+
/** Writes 32-bit words; returns their address. */
|
|
290
|
+
words(words) {
|
|
291
|
+
const address = this.allocate(words.length * 4);
|
|
292
|
+
this.state.module.words().set(words, address / 4);
|
|
293
|
+
return address;
|
|
294
|
+
}
|
|
295
|
+
release() {
|
|
296
|
+
for (const address of this.addresses) {
|
|
297
|
+
this.state.module.exports.sxml_javascript_release(this.state.address, address);
|
|
298
|
+
}
|
|
299
|
+
this.addresses.length = 0;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
function outOfMemory() {
|
|
303
|
+
return new SxmlError({
|
|
304
|
+
status: 'OUT_OF_MEMORY',
|
|
305
|
+
codeNamespaceUri: '',
|
|
306
|
+
codeLocalName: '',
|
|
307
|
+
codePrefix: '',
|
|
308
|
+
description: 'Out of memory',
|
|
309
|
+
lineNumber: 0,
|
|
310
|
+
columnNumber: 0,
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
function disposed(what) {
|
|
314
|
+
return new Error(`sxml: this ${what} has been disposed`);
|
|
315
|
+
}
|
|
316
|
+
/** sxml_javascript_side_result_kind. */
|
|
317
|
+
const side_result_updated_tree = 0;
|
|
318
|
+
const side_result_put_document = 1;
|
|
319
|
+
const side_result_result_document = 2;
|
|
320
|
+
const side_result_message = 3;
|
|
321
|
+
const side_result_schema_report = 4;
|
|
322
|
+
/** sxml_xslt_invocation_kind and sxml_xslt_result_delivery. */
|
|
323
|
+
const invocation_apply_templates = 0;
|
|
324
|
+
const invocation_call_template = 1;
|
|
325
|
+
const invocation_call_function = 2;
|
|
326
|
+
const result_deliveries = { raw: 1, tree: 2, serialized: 3 };
|
|
327
|
+
/** sxml_validity. */
|
|
328
|
+
const validities = ['valid', 'invalid', 'not-known'];
|
|
329
|
+
/** The four words of a name (sxml_javascript_name); '' gives none. */
|
|
330
|
+
function nameWords(scratch, name) {
|
|
331
|
+
if (name === undefined || name === '') {
|
|
332
|
+
return [0, 0, 0, 0];
|
|
333
|
+
}
|
|
334
|
+
const [namespaceUri, localName] = splitName(name);
|
|
335
|
+
return [...scratch.view(namespaceUri), ...scratch.view(localName)];
|
|
336
|
+
}
|
|
337
|
+
/** Splits an NCName or Q{uri}local into namespace URI and local name. */
|
|
338
|
+
function splitName(name) {
|
|
339
|
+
const match = /^Q\{([^{}]*)\}(.+)$/.exec(name);
|
|
340
|
+
return match === null ? ['', name] : [match[1] ?? '', match[2] ?? ''];
|
|
341
|
+
}
|
|
342
|
+
/** The loaded module: makes processors. One per page or process is enough;
|
|
343
|
+
* processors made from it are independent. */
|
|
344
|
+
export class Sxml {
|
|
345
|
+
/** @internal */
|
|
346
|
+
exports;
|
|
347
|
+
/** The library version, such as '0.2.0'. */
|
|
348
|
+
version;
|
|
349
|
+
/** The optional features of the module: all of them (D272; 'test' adds
|
|
350
|
+
* nothing, it checks that the list reaches the processor). */
|
|
351
|
+
features;
|
|
352
|
+
/** The DUCET served for 'collation-data' (LoadOptions.collationData).
|
|
353
|
+
* @internal */
|
|
354
|
+
collationData;
|
|
355
|
+
/** Processors by address, for the resolver import. @internal */
|
|
356
|
+
processors = new Map();
|
|
357
|
+
registry;
|
|
358
|
+
/** @internal Use load(). */
|
|
359
|
+
constructor(exports) {
|
|
360
|
+
this.exports = exports;
|
|
361
|
+
this.registry = new FinalizationRegistry((held) => {
|
|
362
|
+
if (held.kind === 'processor') {
|
|
363
|
+
held.processor.destroy();
|
|
364
|
+
}
|
|
365
|
+
else {
|
|
366
|
+
held.processor.releaseHandle(held.kind, held.address);
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
const versionAddress = exports.sxml_javascript_version_text();
|
|
370
|
+
const bytes = this.bytes();
|
|
371
|
+
let end = versionAddress;
|
|
372
|
+
while (bytes[end] !== 0) {
|
|
373
|
+
end += 1;
|
|
374
|
+
}
|
|
375
|
+
this.version = decoder.decode(bytes.subarray(versionAddress, end));
|
|
376
|
+
const features = [];
|
|
377
|
+
for (let index = 0; index < exports.sxml_javascript_feature_count(); index += 1) {
|
|
378
|
+
features.push(this.text(exports.sxml_javascript_feature_name_bytes(index), exports.sxml_javascript_feature_name_byte_count(index)));
|
|
379
|
+
}
|
|
380
|
+
this.features = Object.freeze(features);
|
|
381
|
+
}
|
|
382
|
+
/** The module's memory as bytes; a new view after every call, since
|
|
383
|
+
* memory may have grown. @internal */
|
|
384
|
+
bytes() {
|
|
385
|
+
return new Uint8Array(this.exports.memory.buffer);
|
|
386
|
+
}
|
|
387
|
+
/** @internal */
|
|
388
|
+
words() {
|
|
389
|
+
return new Uint32Array(this.exports.memory.buffer);
|
|
390
|
+
}
|
|
391
|
+
/** @internal */
|
|
392
|
+
text(address, byteCount) {
|
|
393
|
+
return decoder.decode(this.bytes().subarray(address, address + byteCount));
|
|
394
|
+
}
|
|
395
|
+
/** @internal */
|
|
396
|
+
track(owner, held) {
|
|
397
|
+
this.registry.register(owner, held, owner);
|
|
398
|
+
}
|
|
399
|
+
/** @internal */
|
|
400
|
+
untrack(owner) {
|
|
401
|
+
this.registry.unregister(owner);
|
|
402
|
+
}
|
|
403
|
+
createProcessor(options = {}) {
|
|
404
|
+
let featureMask = 0;
|
|
405
|
+
for (const name of options.features ?? this.features) {
|
|
406
|
+
const index = this.features.indexOf(name);
|
|
407
|
+
if (index < 0) {
|
|
408
|
+
throw new Error(`sxml: this module has no optional feature '${name}'`);
|
|
409
|
+
}
|
|
410
|
+
featureMask |= 1 << index;
|
|
411
|
+
}
|
|
412
|
+
const stepCount = options.maximumEvaluationStepCount ?? 0;
|
|
413
|
+
if (!Number.isSafeInteger(stepCount) || stepCount < 0) {
|
|
414
|
+
throw new RangeError('sxml: maximumEvaluationStepCount must be a whole number from 0 to 2^53 - 1');
|
|
415
|
+
}
|
|
416
|
+
const locationPolicy = locationPolicies.indexOf(options.locations ?? 'automatic');
|
|
417
|
+
if (locationPolicy < 0) {
|
|
418
|
+
throw new RangeError("sxml: locations must be 'automatic', 'always' or 'never'");
|
|
419
|
+
}
|
|
420
|
+
const codeLanguageView = this.codeLanguageView(options.codeLanguages ?? []);
|
|
421
|
+
// sxml_javascript_processor_request (sxml_javascript.h): four words
|
|
422
|
+
// and the step count's two, low first.
|
|
423
|
+
const request = this.exports.malloc(processor_request_byte_count);
|
|
424
|
+
if (request === 0) {
|
|
425
|
+
if (codeLanguageView !== 0) {
|
|
426
|
+
this.exports.free(codeLanguageView);
|
|
427
|
+
}
|
|
428
|
+
throw outOfMemory();
|
|
429
|
+
}
|
|
430
|
+
this.words().set([options.failingAllocationNumber ?? 0, featureMask >>> 0, codeLanguageView, locationPolicy, stepCount % 2 ** 32, Math.floor(stepCount / 2 ** 32)], request / 4);
|
|
431
|
+
const address = this.exports.sxml_javascript_processor_create(request);
|
|
432
|
+
this.exports.free(request);
|
|
433
|
+
if (address === 0) {
|
|
434
|
+
if (codeLanguageView !== 0) {
|
|
435
|
+
this.exports.free(codeLanguageView);
|
|
436
|
+
}
|
|
437
|
+
throw outOfMemory();
|
|
438
|
+
}
|
|
439
|
+
const state = new ProcessorState(this, address, options.resolver, options.features ?? this.features);
|
|
440
|
+
state.codeLanguageView = codeLanguageView;
|
|
441
|
+
this.exports.sxml_javascript_set_byte_reader(address);
|
|
442
|
+
if (options.outputChunkByteCount !== undefined) {
|
|
443
|
+
if (!Number.isInteger(options.outputChunkByteCount) || options.outputChunkByteCount < 1) {
|
|
444
|
+
throw new RangeError('sxml: outputChunkByteCount must be a positive integer');
|
|
445
|
+
}
|
|
446
|
+
state.outputChunkByteCount = options.outputChunkByteCount;
|
|
447
|
+
}
|
|
448
|
+
this.processors.set(address, state);
|
|
449
|
+
const processor = new Processor(state);
|
|
450
|
+
this.track(processor, { processor: state, kind: 'processor', address });
|
|
451
|
+
return processor;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Loads a tree-sitter language file (tree-sitter-NAME.wasm, as
|
|
455
|
+
* `tree-sitter build --wasm` writes it) into this module for
|
|
456
|
+
* tree-sitter:parse: links it into sxml.wasm (src/linker.ts) and checks
|
|
457
|
+
* its ABI and queries. Give it to processors with createProcessor({
|
|
458
|
+
* codeLanguages }). It stays loaded as long as this Sxml. Rejects with
|
|
459
|
+
* an Error that says what is wrong with the file, the name or a query.
|
|
460
|
+
*/
|
|
461
|
+
async loadCodeLanguage(options) {
|
|
462
|
+
const exports = this.exports;
|
|
463
|
+
const module = await compileModule(options.wasm);
|
|
464
|
+
const functions = new Map();
|
|
465
|
+
for (const [name, value] of Object.entries(exports)) {
|
|
466
|
+
// The C library functions the build exports for external scanners
|
|
467
|
+
// (bindings/javascript/CMakeLists.txt); sxml's own are sxml_.
|
|
468
|
+
if (typeof value === 'function' && !name.startsWith('sxml_') && !name.startsWith('_')) {
|
|
469
|
+
functions.set(name, value);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
const linked = await linkLanguageModule(module, {
|
|
473
|
+
memory: exports.memory,
|
|
474
|
+
table: exports.__indirect_function_table,
|
|
475
|
+
stackPointer: exports.__stack_pointer,
|
|
476
|
+
functions,
|
|
477
|
+
reserve: (byteCount, alignment) => {
|
|
478
|
+
const address = this.reserve(byteCount + alignment - 1);
|
|
479
|
+
const aligned = Math.ceil(address / alignment) * alignment;
|
|
480
|
+
this.bytes().fill(0, aligned, aligned + byteCount);
|
|
481
|
+
return aligned;
|
|
482
|
+
},
|
|
483
|
+
}, options.name);
|
|
484
|
+
const name = options.name ?? linked.functionName;
|
|
485
|
+
// sxml_source_code_language (processor.h): six byte views but the
|
|
486
|
+
// grammar, eleven words; the texts stay with the language.
|
|
487
|
+
const view = (text) => {
|
|
488
|
+
const bytes = encoder.encode(text ?? '');
|
|
489
|
+
const address = this.reserve(bytes.byteLength);
|
|
490
|
+
this.bytes().set(bytes, address);
|
|
491
|
+
return [address, bytes.byteLength];
|
|
492
|
+
};
|
|
493
|
+
const words = [
|
|
494
|
+
...view(name),
|
|
495
|
+
linked.languageAddress,
|
|
496
|
+
...view(options.highlights),
|
|
497
|
+
...view(options.locals),
|
|
498
|
+
...view(options.injections),
|
|
499
|
+
...view(options.injectionRegex),
|
|
500
|
+
];
|
|
501
|
+
const language = this.reserve(code_language_byte_count);
|
|
502
|
+
this.words().set(words, language / 4);
|
|
503
|
+
// sxml_source_code_language_report: problem, abi_version, byte_offset.
|
|
504
|
+
const report = this.reserve(12);
|
|
505
|
+
const status = exports.sxml_javascript_check_code_language(language, report);
|
|
506
|
+
const [problem = 0, abiVersion = 0, byteOffset = 0] = this.words().subarray(report / 4, report / 4 + 3);
|
|
507
|
+
exports.free(report);
|
|
508
|
+
if (status === status_out_of_memory) {
|
|
509
|
+
throw outOfMemory();
|
|
510
|
+
}
|
|
511
|
+
if (status !== status_ok) {
|
|
512
|
+
throw new Error(codeLanguageProblem(problem, { name, abiVersion, byteOffset }));
|
|
513
|
+
}
|
|
514
|
+
return new CodeLanguage(this, language, name, abiVersion);
|
|
515
|
+
}
|
|
516
|
+
/** malloc of sxml.wasm, for memory that outlives processors.
|
|
517
|
+
* @internal */
|
|
518
|
+
reserve(byteCount) {
|
|
519
|
+
const address = this.exports.malloc(Math.max(byteCount, 1));
|
|
520
|
+
if (address === 0) {
|
|
521
|
+
throw outOfMemory();
|
|
522
|
+
}
|
|
523
|
+
return address;
|
|
524
|
+
}
|
|
525
|
+
/** A processor's sxml_source_code_language_view: the view, then a copy
|
|
526
|
+
* of each language; 0 for none. @internal */
|
|
527
|
+
codeLanguageView(languages) {
|
|
528
|
+
if (languages.length === 0) {
|
|
529
|
+
return 0;
|
|
530
|
+
}
|
|
531
|
+
const names = new Set();
|
|
532
|
+
for (const language of languages) {
|
|
533
|
+
if (language.module !== this) {
|
|
534
|
+
throw new Error('sxml: this code language was loaded by another sxml module');
|
|
535
|
+
}
|
|
536
|
+
if (names.has(language.name)) {
|
|
537
|
+
throw new Error(`sxml: two code languages are named '${language.name}'`);
|
|
538
|
+
}
|
|
539
|
+
names.add(language.name);
|
|
540
|
+
}
|
|
541
|
+
const view = this.reserve(8 + languages.length * code_language_byte_count);
|
|
542
|
+
const bytes = this.bytes();
|
|
543
|
+
languages.forEach((language, index) => {
|
|
544
|
+
const at = view + 8 + index * code_language_byte_count;
|
|
545
|
+
bytes.copyWithin(at, language.address, language.address + code_language_byte_count);
|
|
546
|
+
});
|
|
547
|
+
this.words().set([view + 8, languages.length], view / 4);
|
|
548
|
+
return view;
|
|
549
|
+
}
|
|
550
|
+
/** The resolver import (sxml_javascript_host_resolve). @internal */
|
|
551
|
+
resolve(processorAddress, requestAddress, resourceAddress) {
|
|
552
|
+
const state = this.processors.get(processorAddress);
|
|
553
|
+
if (state === undefined) {
|
|
554
|
+
return status_ok;
|
|
555
|
+
}
|
|
556
|
+
const request = this.words().subarray(requestAddress / 4, requestAddress / 4 + 5);
|
|
557
|
+
const resourceRequest = {
|
|
558
|
+
kind: resource_kinds[request[0] ?? 0] ?? 'xml-document',
|
|
559
|
+
uriReference: this.text(request[1] ?? 0, request[2] ?? 0),
|
|
560
|
+
absoluteUri: this.text(request[3] ?? 0, request[4] ?? 0),
|
|
561
|
+
};
|
|
562
|
+
let answer;
|
|
563
|
+
if (state.resolver !== undefined) {
|
|
564
|
+
state.isInResolver = true;
|
|
565
|
+
try {
|
|
566
|
+
answer = state.resolver(resourceRequest);
|
|
567
|
+
}
|
|
568
|
+
catch (exception) {
|
|
569
|
+
state.pendingException = exception;
|
|
570
|
+
return status_input_output_failed;
|
|
571
|
+
}
|
|
572
|
+
finally {
|
|
573
|
+
state.isInResolver = false;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
if ((answer === null || answer === undefined) &&
|
|
577
|
+
resourceRequest.kind === 'collation-data' &&
|
|
578
|
+
resourceRequest.absoluteUri === ducet_uri) {
|
|
579
|
+
answer = this.collationData;
|
|
580
|
+
}
|
|
581
|
+
if (answer === null || answer === undefined) {
|
|
582
|
+
return status_ok;
|
|
583
|
+
}
|
|
584
|
+
if (typeof answer !== 'string' && !(answer instanceof Uint8Array)) {
|
|
585
|
+
// A chunk source (D294): read as it is parsed for an XML document,
|
|
586
|
+
// whole for the other kinds.
|
|
587
|
+
if (resourceRequest.kind === 'xml-document') {
|
|
588
|
+
const identifier = state.nextReaderIdentifier;
|
|
589
|
+
state.nextReaderIdentifier += 1;
|
|
590
|
+
state.readers.set(identifier, new ChunkReader(answer));
|
|
591
|
+
this.words().set([resource_form_byte_reader, 0, 0, identifier], resourceAddress / 4);
|
|
592
|
+
return status_ok;
|
|
593
|
+
}
|
|
594
|
+
try {
|
|
595
|
+
state.isInResolver = true;
|
|
596
|
+
answer = readWhole(answer);
|
|
597
|
+
}
|
|
598
|
+
catch (exception) {
|
|
599
|
+
state.pendingException = exception;
|
|
600
|
+
return status_input_output_failed;
|
|
601
|
+
}
|
|
602
|
+
finally {
|
|
603
|
+
state.isInResolver = false;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
const bytes = typeof answer === 'string' ? encoder.encode(answer) : answer;
|
|
607
|
+
const address = this.exports.sxml_javascript_allocate(processorAddress, bytes.byteLength);
|
|
608
|
+
if (address === 0) {
|
|
609
|
+
return status_out_of_memory;
|
|
610
|
+
}
|
|
611
|
+
this.bytes().set(bytes, address);
|
|
612
|
+
this.words().set([1, address, bytes.byteLength, 0], resourceAddress / 4);
|
|
613
|
+
return status_ok;
|
|
614
|
+
}
|
|
615
|
+
/** The import sxml_host.write (sxml_host_output_event: kind, bytes,
|
|
616
|
+
* is_abandoned). @internal */
|
|
617
|
+
write(processorAddress, eventAddress) {
|
|
618
|
+
const state = this.processors.get(processorAddress);
|
|
619
|
+
const router = state?.outputRouter;
|
|
620
|
+
if (state === undefined || router === undefined) {
|
|
621
|
+
return status_ok;
|
|
622
|
+
}
|
|
623
|
+
const [kind = 0, address = 0, byteCount = 0, isAbandoned = 0] = this.words().subarray(eventAddress / 4, eventAddress / 4 + 4);
|
|
624
|
+
state.isInSink = true;
|
|
625
|
+
try {
|
|
626
|
+
router.event(kind, this.bytes().subarray(address, address + byteCount), isAbandoned !== 0, () => this.text(address, byteCount));
|
|
627
|
+
return status_ok;
|
|
628
|
+
}
|
|
629
|
+
catch (exception) {
|
|
630
|
+
state.pendingException = exception;
|
|
631
|
+
return status_input_output_failed;
|
|
632
|
+
}
|
|
633
|
+
finally {
|
|
634
|
+
state.isInSink = false;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
/** The import sxml_host.read (sxml_host_read_request: identifier,
|
|
638
|
+
* buffer, byte_count, is_end). @internal */
|
|
639
|
+
read(processorAddress, requestAddress) {
|
|
640
|
+
const state = this.processors.get(processorAddress);
|
|
641
|
+
const at = requestAddress / 4;
|
|
642
|
+
const [identifier = 0, buffer = 0, bufferByteCount = 0] = this.words().subarray(at, at + 3);
|
|
643
|
+
const reader = state?.readers.get(identifier);
|
|
644
|
+
if (state === undefined || reader === undefined) {
|
|
645
|
+
this.words().set([0, 1], at + 3);
|
|
646
|
+
return status_ok;
|
|
647
|
+
}
|
|
648
|
+
state.isInSink = true;
|
|
649
|
+
try {
|
|
650
|
+
const [byteCount, isEnd] = reader.read(this.bytes().subarray(buffer, buffer + bufferByteCount));
|
|
651
|
+
this.words().set([byteCount, isEnd ? 1 : 0], at + 3);
|
|
652
|
+
return status_ok;
|
|
653
|
+
}
|
|
654
|
+
catch (exception) {
|
|
655
|
+
state.pendingException = exception;
|
|
656
|
+
return status_input_output_failed;
|
|
657
|
+
}
|
|
658
|
+
finally {
|
|
659
|
+
state.isInSink = false;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
/** The import sxml_host.release_reader. @internal */
|
|
663
|
+
releaseReader(processorAddress, identifier) {
|
|
664
|
+
const state = this.processors.get(processorAddress);
|
|
665
|
+
const reader = state?.readers.get(identifier);
|
|
666
|
+
if (state === undefined || reader === undefined) {
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
state.readers.delete(identifier);
|
|
670
|
+
try {
|
|
671
|
+
reader.close();
|
|
672
|
+
}
|
|
673
|
+
catch (exception) {
|
|
674
|
+
state.pendingException ??= exception;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
/** ProcessorOptions.outputChunkByteCount's default. */
|
|
679
|
+
const default_output_chunk_byte_count = 65536;
|
|
680
|
+
/** SXML_RESOURCE_FORM_BYTE_READER (include/sxml/processor.h). */
|
|
681
|
+
const resource_form_byte_reader = 4;
|
|
682
|
+
/** The size of sxml_source_code_language in sxml.wasm (checked by the
|
|
683
|
+
* shim, sxml_javascript_exports.c). */
|
|
684
|
+
const code_language_byte_count = 44;
|
|
685
|
+
/** sizeof(sxml_javascript_processor_request) on wasm32 (D295). */
|
|
686
|
+
const processor_request_byte_count = 24;
|
|
687
|
+
/** The values of ProcessorOptions.locations, in the order of the C
|
|
688
|
+
* enumeration sxml_source_location_policy. */
|
|
689
|
+
const locationPolicies = ['automatic', 'always', 'never'];
|
|
690
|
+
/** sxml_source_code_language_problem, as the sxml command words it
|
|
691
|
+
* (apps/sxml/code_languages.c). */
|
|
692
|
+
function codeLanguageProblem(problem, { name, abiVersion, byteOffset }) {
|
|
693
|
+
const queries = ['highlights', 'locals', 'injections'];
|
|
694
|
+
if (problem === 1) {
|
|
695
|
+
return `sxml: '${name}' is no language name (ASCII letters, digits, '_', '-', '+' and '.')`;
|
|
696
|
+
}
|
|
697
|
+
if (problem === 2) {
|
|
698
|
+
return `sxml: the grammar's ABI is ${abiVersion}; sxml reads 13 to 15`;
|
|
699
|
+
}
|
|
700
|
+
return `sxml: the ${queries[problem - 3] ?? 'highlights'} query does not fit the grammar at byte ${byteOffset}`;
|
|
701
|
+
}
|
|
702
|
+
/** A tree-sitter language loaded by Sxml.loadCodeLanguage, for
|
|
703
|
+
* createProcessor({ codeLanguages }). */
|
|
704
|
+
export class CodeLanguage {
|
|
705
|
+
/** @internal */
|
|
706
|
+
module;
|
|
707
|
+
/** @internal Its sxml_source_code_language in the module's memory. */
|
|
708
|
+
address;
|
|
709
|
+
/** Its name in tree-sitter:parse. */
|
|
710
|
+
name;
|
|
711
|
+
/** The grammar's tree-sitter language ABI, 13 to 15. */
|
|
712
|
+
abiVersion;
|
|
713
|
+
/** @internal Use Sxml.loadCodeLanguage(). */
|
|
714
|
+
constructor(module, address, name, abiVersion) {
|
|
715
|
+
this.module = module;
|
|
716
|
+
this.address = address;
|
|
717
|
+
this.name = name;
|
|
718
|
+
this.abiVersion = abiVersion;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
/** Loads and instantiates sxml.wasm. */
|
|
722
|
+
export async function load(options = {}) {
|
|
723
|
+
const module = await compileModule(options.wasm ?? new URL('./sxml.wasm', import.meta.url));
|
|
724
|
+
let sxml;
|
|
725
|
+
let memory;
|
|
726
|
+
const instance = await WebAssembly.instantiate(module, {
|
|
727
|
+
wasi_snapshot_preview1: wasiImports(module, () => {
|
|
728
|
+
if (memory === undefined) {
|
|
729
|
+
throw new Error('sxml.wasm called WASI before it was instantiated');
|
|
730
|
+
}
|
|
731
|
+
return memory;
|
|
732
|
+
}),
|
|
733
|
+
sxml_host: {
|
|
734
|
+
resolve: (processor, request, resource) => sxml === undefined ? status_ok : sxml.resolve(processor, request, resource),
|
|
735
|
+
write: (processor, event) => sxml === undefined ? status_ok : sxml.write(processor, event),
|
|
736
|
+
read: (processor, request) => sxml === undefined ? status_ok : sxml.read(processor, request),
|
|
737
|
+
release_reader: (processor, identifier) => sxml?.releaseReader(processor, identifier),
|
|
738
|
+
},
|
|
739
|
+
});
|
|
740
|
+
const exports = instance.exports;
|
|
741
|
+
if (typeof exports.sxml_javascript_query_compile !== 'function') {
|
|
742
|
+
// A module of an older package, without XQuery, XSLT and XSD.
|
|
743
|
+
throw new Error('sxml: this module is not the package\'s sxml.wasm');
|
|
744
|
+
}
|
|
745
|
+
memory = exports.memory;
|
|
746
|
+
exports._initialize();
|
|
747
|
+
sxml = new Sxml(exports);
|
|
748
|
+
if (sxml.features.includes('uca-collation') && options.collationData !== false) {
|
|
749
|
+
if (options.collationData === undefined) {
|
|
750
|
+
// The package's copy; without it the feature falls back (D213).
|
|
751
|
+
sxml.collationData = await readBytes(new URL('./allkeys.txt', import.meta.url)).catch(() => undefined);
|
|
752
|
+
}
|
|
753
|
+
else {
|
|
754
|
+
sxml.collationData = await readBytes(options.collationData);
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
return sxml;
|
|
758
|
+
}
|
|
759
|
+
/** The bytes of a URL, a path or a buffer. */
|
|
760
|
+
async function readBytes(source) {
|
|
761
|
+
if (source instanceof ArrayBuffer) {
|
|
762
|
+
return new Uint8Array(source);
|
|
763
|
+
}
|
|
764
|
+
if (ArrayBuffer.isView(source)) {
|
|
765
|
+
return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
|
|
766
|
+
}
|
|
767
|
+
const url = source instanceof URL ? source : new URL(source, import.meta.url);
|
|
768
|
+
if (url.protocol === 'file:') {
|
|
769
|
+
const { readFile } = await import('node:fs/promises');
|
|
770
|
+
return new Uint8Array(await readFile(url));
|
|
771
|
+
}
|
|
772
|
+
const response = await fetch(url);
|
|
773
|
+
if (!response.ok) {
|
|
774
|
+
throw new Error(`sxml: cannot fetch ${url.href} (${response.status})`);
|
|
775
|
+
}
|
|
776
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
777
|
+
}
|
|
778
|
+
async function compileModule(source) {
|
|
779
|
+
if (source instanceof WebAssembly.Module) {
|
|
780
|
+
return source;
|
|
781
|
+
}
|
|
782
|
+
if (source instanceof ArrayBuffer || ArrayBuffer.isView(source)) {
|
|
783
|
+
return WebAssembly.compile(source);
|
|
784
|
+
}
|
|
785
|
+
if (typeof source === 'string' || source instanceof URL) {
|
|
786
|
+
const url = source instanceof URL ? source : new URL(source, import.meta.url);
|
|
787
|
+
if (url.protocol === 'file:') {
|
|
788
|
+
// Node.js: fetch() does not read files.
|
|
789
|
+
const { readFile } = await import('node:fs/promises');
|
|
790
|
+
return WebAssembly.compile(await readFile(url));
|
|
791
|
+
}
|
|
792
|
+
return compileResponse(fetch(url));
|
|
793
|
+
}
|
|
794
|
+
return compileResponse(source);
|
|
795
|
+
}
|
|
796
|
+
async function compileResponse(response) {
|
|
797
|
+
const resolved = await response;
|
|
798
|
+
if (!resolved.ok) {
|
|
799
|
+
throw new Error(`sxml: cannot fetch sxml.wasm (${resolved.status})`);
|
|
800
|
+
}
|
|
801
|
+
return WebAssembly.compile(await resolved.arrayBuffer());
|
|
802
|
+
}
|
|
803
|
+
// --------------------------------------------------------------- Processor
|
|
804
|
+
/** A processor (include/sxml/processor.h): its name pool, types and items.
|
|
805
|
+
* Values and expressions belong to the processor that made them. */
|
|
806
|
+
export class Processor {
|
|
807
|
+
state;
|
|
808
|
+
/** @internal Use Sxml.createProcessor(). */
|
|
809
|
+
constructor(state) {
|
|
810
|
+
this.state = state;
|
|
811
|
+
}
|
|
812
|
+
/** Parses an XML document and returns its document node. */
|
|
813
|
+
parse(xml, options = {}) {
|
|
814
|
+
const state = this.enter();
|
|
815
|
+
const scratch = new Scratch(state);
|
|
816
|
+
try {
|
|
817
|
+
const request = scratch.words([...scratch.view(xml), ...scratch.view(options.uri ?? '')]);
|
|
818
|
+
return this.adopt(state.module.exports.sxml_javascript_parse(state.address, request));
|
|
819
|
+
}
|
|
820
|
+
finally {
|
|
821
|
+
scratch.release();
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
/** Compiles an XPath 4.0 expression, for evaluating it many times. */
|
|
825
|
+
compile(expression, options = {}) {
|
|
826
|
+
const state = this.enter();
|
|
827
|
+
const variables = options.variables ?? [];
|
|
828
|
+
const address = this.compileAddress(expression, options, variables);
|
|
829
|
+
state.live.set(address, 'expression');
|
|
830
|
+
const compiled = new XPathExpression(this, address, variables);
|
|
831
|
+
state.module.track(compiled, { processor: state, kind: 'expression', address });
|
|
832
|
+
return compiled;
|
|
833
|
+
}
|
|
834
|
+
/** Compiles and evaluates an expression once; the variables are those
|
|
835
|
+
* options.variables names. */
|
|
836
|
+
evaluate(expression, options = {}) {
|
|
837
|
+
const compiled = this.compile(expression, {
|
|
838
|
+
...options,
|
|
839
|
+
variables: Object.keys(options.variables ?? {}),
|
|
840
|
+
});
|
|
841
|
+
try {
|
|
842
|
+
return compiled.evaluate(options);
|
|
843
|
+
}
|
|
844
|
+
finally {
|
|
845
|
+
compiled.dispose();
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
/** Compiles an XQuery 4.0 main module, with the library modules it
|
|
849
|
+
* imports (the resolver is asked for them, kind 'xquery-module'), for
|
|
850
|
+
* evaluating it many times. */
|
|
851
|
+
compileQuery(query, options = {}) {
|
|
852
|
+
const exports = this.exports();
|
|
853
|
+
const state = this.enter();
|
|
854
|
+
const scratch = new Scratch(state);
|
|
855
|
+
let address;
|
|
856
|
+
try {
|
|
857
|
+
const namespaceWords = [];
|
|
858
|
+
for (const [prefix, uri] of state.staticNamespaces(options.namespaces)) {
|
|
859
|
+
namespaceWords.push(...scratch.view(prefix), ...scratch.view(uri));
|
|
860
|
+
}
|
|
861
|
+
const request = scratch.words([
|
|
862
|
+
...scratch.view(query),
|
|
863
|
+
...scratch.view(options.baseUri ?? ''),
|
|
864
|
+
namespaceWords.length > 0 ? scratch.words(namespaceWords) : 0,
|
|
865
|
+
namespaceWords.length / 4,
|
|
866
|
+
]);
|
|
867
|
+
address = exports.sxml_javascript_query_compile(state.address, request);
|
|
868
|
+
if (address === 0) {
|
|
869
|
+
throw this.failure();
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
finally {
|
|
873
|
+
scratch.release();
|
|
874
|
+
}
|
|
875
|
+
const compiled = new XQuery(this, address, exports.sxml_javascript_query_is_updating(address) !== 0);
|
|
876
|
+
this.track(compiled, 'query', address);
|
|
877
|
+
return compiled;
|
|
878
|
+
}
|
|
879
|
+
/** Compiles an XSLT 4.0 stylesheet, with the modules it includes and
|
|
880
|
+
* imports (kind 'xslt-module') and the packages it uses (kind
|
|
881
|
+
* 'xslt-package'), for running it many times. A stylesheet with errors
|
|
882
|
+
* throws a SchemaError with every error as its reports (codes with
|
|
883
|
+
* their prefix, such as 'err:XPST0003'). */
|
|
884
|
+
compileStylesheet(stylesheet, options = {}) {
|
|
885
|
+
const exports = this.exports();
|
|
886
|
+
const state = this.enter();
|
|
887
|
+
const scratch = new Scratch(state);
|
|
888
|
+
const made = [];
|
|
889
|
+
let address;
|
|
890
|
+
try {
|
|
891
|
+
const request = scratch.words([
|
|
892
|
+
...scratch.view(stylesheet),
|
|
893
|
+
...scratch.view(options.baseUri ?? ''),
|
|
894
|
+
...this.bindingWords(scratch, options.staticParameters, made),
|
|
895
|
+
]);
|
|
896
|
+
address = exports.sxml_javascript_stylesheet_compile(state.address, request);
|
|
897
|
+
if (address === 0) {
|
|
898
|
+
// Every error of the compilation (D320), on the exception.
|
|
899
|
+
const reports = schemaReports(this.sideResults(exports.sxml_javascript_compile_reports_of(state.address) / 4));
|
|
900
|
+
const failure = this.failure();
|
|
901
|
+
throw failure instanceof SxmlError && reports.length > 0 ? new SchemaError(failure, reports) : failure;
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
finally {
|
|
905
|
+
scratch.release();
|
|
906
|
+
for (const value of made) {
|
|
907
|
+
value.dispose();
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
const compiled = new Stylesheet(this, address);
|
|
911
|
+
this.track(compiled, 'stylesheet', address);
|
|
912
|
+
return compiled;
|
|
913
|
+
}
|
|
914
|
+
/** Compiles an XSD 1.1 schema from one or more schema documents (a
|
|
915
|
+
* string is a document's text), with every document they include,
|
|
916
|
+
* import, redefine or override (the resolver is asked, kind
|
|
917
|
+
* 'schema-document'). Throws a SchemaError with every report when the
|
|
918
|
+
* schema has errors. */
|
|
919
|
+
compileSchema(documents, options = {}) {
|
|
920
|
+
const exports = this.exports();
|
|
921
|
+
const state = this.enter();
|
|
922
|
+
const address = exports.sxml_javascript_schema_create(state.address);
|
|
923
|
+
if (address === 0) {
|
|
924
|
+
throw outOfMemory();
|
|
925
|
+
}
|
|
926
|
+
const schema = new Schema(this, address);
|
|
927
|
+
this.track(schema, 'schema', address);
|
|
928
|
+
const scratch = new Scratch(state);
|
|
929
|
+
try {
|
|
930
|
+
const documentWords = [];
|
|
931
|
+
const list = Array.isArray(documents) ? documents : [documents];
|
|
932
|
+
for (const document of list) {
|
|
933
|
+
const { text, uri } = typeof document === 'string' ? { text: document, uri: '' } : document;
|
|
934
|
+
documentWords.push(...(text === undefined ? [0, 0] : scratch.view(text)), ...scratch.view(uri ?? ''));
|
|
935
|
+
}
|
|
936
|
+
const request = scratch.words([
|
|
937
|
+
documentWords.length > 0 ? scratch.words(documentWords) : 0,
|
|
938
|
+
list.length,
|
|
939
|
+
...scratch.view(options.baseUri ?? ''),
|
|
940
|
+
0,
|
|
941
|
+
0,
|
|
942
|
+
]);
|
|
943
|
+
const status = exports.sxml_javascript_schema_compile(address, request);
|
|
944
|
+
const reports = schemaReports(this.sideResults(request / 4 + 4));
|
|
945
|
+
if (status !== status_ok) {
|
|
946
|
+
const failure = this.failure();
|
|
947
|
+
throw failure instanceof SxmlError ? new SchemaError(failure, reports) : failure;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
catch (exception) {
|
|
951
|
+
schema.dispose();
|
|
952
|
+
throw exception;
|
|
953
|
+
}
|
|
954
|
+
finally {
|
|
955
|
+
scratch.release();
|
|
956
|
+
}
|
|
957
|
+
return schema;
|
|
958
|
+
}
|
|
959
|
+
/** Compiles a Schematron schema (ISO/IEC 19757-3:2025) from its text or
|
|
960
|
+
* its URI (the resolver is asked, kind 'xml-document', for it and for
|
|
961
|
+
* the documents its include and extends href name), for the phase
|
|
962
|
+
* options.phase names (an id, '#ALL', '#ANY', or '#DEFAULT', the
|
|
963
|
+
* default) with the schema parameters options.parameters gives. Throws a
|
|
964
|
+
* SchemaError with every error when it does not compile (codes such as
|
|
965
|
+
* 'schematron:syntax', 'err:XPST0003'). */
|
|
966
|
+
compileSchematron(schema, options = {}) {
|
|
967
|
+
const exports = this.exports();
|
|
968
|
+
const state = this.enter();
|
|
969
|
+
const address = exports.sxml_javascript_schematron_create(state.address);
|
|
970
|
+
if (address === 0) {
|
|
971
|
+
throw outOfMemory();
|
|
972
|
+
}
|
|
973
|
+
const compiled = new Schematron(this, address);
|
|
974
|
+
this.track(compiled, 'schematron', address);
|
|
975
|
+
const scratch = new Scratch(state);
|
|
976
|
+
try {
|
|
977
|
+
const { text, uri } = typeof schema === 'string' ? { text: schema, uri: '' } : schema;
|
|
978
|
+
const parameterWords = [];
|
|
979
|
+
const parameters = Object.entries(options.parameters ?? {});
|
|
980
|
+
for (const [name, value] of parameters) {
|
|
981
|
+
parameterWords.push(...scratch.view(name), ...scratch.view(value));
|
|
982
|
+
}
|
|
983
|
+
const request = scratch.words([
|
|
984
|
+
...(text === undefined ? [0, 0] : scratch.view(text)),
|
|
985
|
+
...scratch.view(uri ?? ''),
|
|
986
|
+
...scratch.view(options.baseUri ?? ''),
|
|
987
|
+
...scratch.view(options.phase ?? ''),
|
|
988
|
+
parameterWords.length > 0 ? scratch.words(parameterWords) : 0,
|
|
989
|
+
parameters.length,
|
|
990
|
+
0,
|
|
991
|
+
0,
|
|
992
|
+
]);
|
|
993
|
+
const status = exports.sxml_javascript_schematron_compile(address, request);
|
|
994
|
+
const reports = schemaReports(this.sideResults(request / 4 + 10));
|
|
995
|
+
const warnings = reports.filter(isSchematronWarning);
|
|
996
|
+
if (status !== status_ok) {
|
|
997
|
+
const failure = this.failure();
|
|
998
|
+
throw failure instanceof SxmlError
|
|
999
|
+
? new SchemaError(failure, reports.filter((report) => !isSchematronWarning(report)))
|
|
1000
|
+
: failure;
|
|
1001
|
+
}
|
|
1002
|
+
const description = scratch.words([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
|
|
1003
|
+
exports.sxml_javascript_schematron_describe(address, description);
|
|
1004
|
+
const words = state.module.words();
|
|
1005
|
+
const field = (index) => state.module.text(words[description / 4 + index * 2] ?? 0, words[description / 4 + index * 2 + 1] ?? 0);
|
|
1006
|
+
compiled.describe({
|
|
1007
|
+
title: field(0),
|
|
1008
|
+
schemaVersion: field(1),
|
|
1009
|
+
schematronEdition: field(2),
|
|
1010
|
+
queryBinding: field(3),
|
|
1011
|
+
phase: field(4),
|
|
1012
|
+
warnings,
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
catch (exception) {
|
|
1016
|
+
compiled.dispose();
|
|
1017
|
+
throw exception;
|
|
1018
|
+
}
|
|
1019
|
+
finally {
|
|
1020
|
+
scratch.release();
|
|
1021
|
+
}
|
|
1022
|
+
return compiled;
|
|
1023
|
+
}
|
|
1024
|
+
/** Converts JSON-like data to a value (see JsonData). */
|
|
1025
|
+
value(data) {
|
|
1026
|
+
if (data instanceof Value) {
|
|
1027
|
+
return data;
|
|
1028
|
+
}
|
|
1029
|
+
const state = this.enter();
|
|
1030
|
+
const scratch = new Scratch(state);
|
|
1031
|
+
let text;
|
|
1032
|
+
try {
|
|
1033
|
+
const view = scratch.words(scratch.view(typeof data === 'string' ? data : JSON.stringify(data)));
|
|
1034
|
+
text = this.adopt(state.module.exports.sxml_javascript_string(state.address, view));
|
|
1035
|
+
}
|
|
1036
|
+
finally {
|
|
1037
|
+
scratch.release();
|
|
1038
|
+
}
|
|
1039
|
+
if (typeof data === 'string') {
|
|
1040
|
+
return text;
|
|
1041
|
+
}
|
|
1042
|
+
try {
|
|
1043
|
+
if (state.jsonExpression === 0) {
|
|
1044
|
+
state.jsonExpression = this.compileAddress('parse-json($json)', {}, ['json']);
|
|
1045
|
+
}
|
|
1046
|
+
return this.evaluateAddress(state.jsonExpression, { variableValues: [text] });
|
|
1047
|
+
}
|
|
1048
|
+
finally {
|
|
1049
|
+
text.dispose();
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
/** Serializes a value: by the adaptive method without options, else as
|
|
1053
|
+
* fn:serialize with them (method xml unless they name another). */
|
|
1054
|
+
serialize(value, options) {
|
|
1055
|
+
this.enter();
|
|
1056
|
+
this.check(value);
|
|
1057
|
+
const optionsValue = this.serializationOptions(options);
|
|
1058
|
+
try {
|
|
1059
|
+
return this.serializeWith(value, optionsValue);
|
|
1060
|
+
}
|
|
1061
|
+
finally {
|
|
1062
|
+
optionsValue?.dispose();
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
/** Serializes a value as serialize() does, writing the output to sink a
|
|
1066
|
+
* chunk at a time instead of returning it (D294). */
|
|
1067
|
+
serializeTo(value, sink, options) {
|
|
1068
|
+
this.enter();
|
|
1069
|
+
this.check(value);
|
|
1070
|
+
const optionsValue = this.serializationOptions(options);
|
|
1071
|
+
try {
|
|
1072
|
+
this.serializeWith(value, optionsValue, sink);
|
|
1073
|
+
}
|
|
1074
|
+
finally {
|
|
1075
|
+
optionsValue?.dispose();
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
/** Encodes a document or element node as an EXI stream (Efficient XML
|
|
1079
|
+
* Interchange 1.0) with options: by default bit-packed, with the
|
|
1080
|
+
* built-in grammars, keeping elements, attributes and text only. Throws
|
|
1081
|
+
* a TypeError or RangeError for options it does not take, and an
|
|
1082
|
+
* SxmlError for a value that is not one document or element node or
|
|
1083
|
+
* content the options cannot represent. */
|
|
1084
|
+
encodeExi(node, options = {}) {
|
|
1085
|
+
this.check(node);
|
|
1086
|
+
const words = exiOptionWords(options, this.exiSchemaAddress(options));
|
|
1087
|
+
const names = options.selfContainedElements ?? [];
|
|
1088
|
+
if (!Array.isArray(names) || names.some((name) => typeof name !== 'string')) {
|
|
1089
|
+
throw new TypeError('sxml: the EXI option selfContainedElements is not an array of strings');
|
|
1090
|
+
}
|
|
1091
|
+
const headerWords = [
|
|
1092
|
+
exiFlag('includeCookie', options.includeCookie) ? 1 : 0,
|
|
1093
|
+
exiFlag('includeOptions', options.includeOptions) ? 1 : 0,
|
|
1094
|
+
exiFlag('canonical', options.canonical) ? 1 : 0,
|
|
1095
|
+
exiFlag('includeSchemaId', options.includeSchemaId) ? 1 : 0,
|
|
1096
|
+
exiFlag('omitOptionsDocument', options.omitOptionsDocument) ? 1 : 0,
|
|
1097
|
+
exiFlag('utcTime', options.utcTime) ? 1 : 0,
|
|
1098
|
+
];
|
|
1099
|
+
const state = this.enter();
|
|
1100
|
+
const scratch = new Scratch(state);
|
|
1101
|
+
try {
|
|
1102
|
+
const nameViews = names.length === 0 ? 0 : scratch.words(names.flatMap((name) => scratch.view(name)));
|
|
1103
|
+
const request = scratch.words([node.address(), ...words, ...headerWords, nameViews, names.length]);
|
|
1104
|
+
if (state.module.exports.sxml_javascript_exi_encode(state.address, request) !== status_ok) {
|
|
1105
|
+
throw this.failure();
|
|
1106
|
+
}
|
|
1107
|
+
return this.outputBytes();
|
|
1108
|
+
}
|
|
1109
|
+
finally {
|
|
1110
|
+
scratch.release();
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
/** Decodes an EXI stream into a new document and returns its document
|
|
1114
|
+
* node, as parse() does for XML text. options are those the stream was
|
|
1115
|
+
* encoded with, needed when its header does not carry them;
|
|
1116
|
+
* options.uri is the document URI. A stream that is not EXI throws an
|
|
1117
|
+
* SxmlError with status 'MALFORMED_INPUT'. */
|
|
1118
|
+
parseExi(stream, options = {}) {
|
|
1119
|
+
const words = exiOptionWords(options, this.exiSchemaAddress(options));
|
|
1120
|
+
const state = this.enter();
|
|
1121
|
+
const scratch = new Scratch(state);
|
|
1122
|
+
try {
|
|
1123
|
+
const request = scratch.words([...scratch.view(stream), ...scratch.view(options.uri ?? ''), ...words]);
|
|
1124
|
+
return this.adopt(state.module.exports.sxml_javascript_exi_parse(state.address, request));
|
|
1125
|
+
}
|
|
1126
|
+
finally {
|
|
1127
|
+
scratch.release();
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
/** Releases the processor and every value and expression made with it. */
|
|
1131
|
+
dispose() {
|
|
1132
|
+
this.state.module.untrack(this);
|
|
1133
|
+
this.state.destroy();
|
|
1134
|
+
}
|
|
1135
|
+
/** The allocations the processor holds, for leak checks in tests; after
|
|
1136
|
+
* dispose(), those that were left when it was destroyed (0 unless the
|
|
1137
|
+
* package or sxml leaked). */
|
|
1138
|
+
liveAllocationCount() {
|
|
1139
|
+
if (this.state.address === 0) {
|
|
1140
|
+
return this.state.leakedAllocationCount;
|
|
1141
|
+
}
|
|
1142
|
+
return this.state.module.exports.sxml_javascript_live_allocation_count(this.state.address);
|
|
1143
|
+
}
|
|
1144
|
+
// ----------------------------------------------------- For the package
|
|
1145
|
+
/** @internal The state, checked usable. */
|
|
1146
|
+
enter() {
|
|
1147
|
+
if (this.state.address === 0) {
|
|
1148
|
+
throw disposed('processor');
|
|
1149
|
+
}
|
|
1150
|
+
if (this.state.isInResolver) {
|
|
1151
|
+
throw new Error('sxml: a resolver must not use its processor');
|
|
1152
|
+
}
|
|
1153
|
+
if (this.state.isInSink) {
|
|
1154
|
+
throw new Error('sxml: an output sink or chunk source must not use its processor');
|
|
1155
|
+
}
|
|
1156
|
+
this.state.pendingException = undefined;
|
|
1157
|
+
return this.state;
|
|
1158
|
+
}
|
|
1159
|
+
/** @internal Throws unless value belongs to this processor. */
|
|
1160
|
+
check(value) {
|
|
1161
|
+
if (value.processor !== this) {
|
|
1162
|
+
throw new Error('sxml: the value belongs to another processor');
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
/** @internal Wraps the address an operation returned, or throws its
|
|
1166
|
+
* failure. */
|
|
1167
|
+
adopt(address) {
|
|
1168
|
+
if (address === 0) {
|
|
1169
|
+
throw this.failure();
|
|
1170
|
+
}
|
|
1171
|
+
this.state.live.set(address, 'value');
|
|
1172
|
+
const value = new Value(this, address);
|
|
1173
|
+
this.state.module.track(value, { processor: this.state, kind: 'value', address });
|
|
1174
|
+
return value;
|
|
1175
|
+
}
|
|
1176
|
+
/** @internal Releases a value or expression made with this processor. */
|
|
1177
|
+
releaseHandle(owner, kind, address) {
|
|
1178
|
+
this.state.module.untrack(owner);
|
|
1179
|
+
this.state.releaseHandle(kind, address);
|
|
1180
|
+
}
|
|
1181
|
+
/** @internal Compiles; returns the expression's address. */
|
|
1182
|
+
compileAddress(expression, options, variables) {
|
|
1183
|
+
const state = this.state;
|
|
1184
|
+
const scratch = new Scratch(state);
|
|
1185
|
+
try {
|
|
1186
|
+
const namespaceWords = [];
|
|
1187
|
+
for (const [prefix, uri] of state.staticNamespaces(options.namespaces)) {
|
|
1188
|
+
namespaceWords.push(...scratch.view(prefix), ...scratch.view(uri));
|
|
1189
|
+
}
|
|
1190
|
+
const variableWords = [];
|
|
1191
|
+
for (const name of variables) {
|
|
1192
|
+
const [namespaceUri, localName] = splitName(name);
|
|
1193
|
+
variableWords.push(...scratch.view(namespaceUri), ...scratch.view(localName));
|
|
1194
|
+
}
|
|
1195
|
+
const request = scratch.words([
|
|
1196
|
+
...scratch.view(expression),
|
|
1197
|
+
...scratch.view(options.baseUri ?? ''),
|
|
1198
|
+
namespaceWords.length > 0 ? scratch.words(namespaceWords) : 0,
|
|
1199
|
+
namespaceWords.length / 4,
|
|
1200
|
+
variableWords.length > 0 ? scratch.words(variableWords) : 0,
|
|
1201
|
+
variables.length,
|
|
1202
|
+
]);
|
|
1203
|
+
const address = state.module.exports.sxml_javascript_compile(state.address, request);
|
|
1204
|
+
if (address === 0) {
|
|
1205
|
+
throw this.failure();
|
|
1206
|
+
}
|
|
1207
|
+
return address;
|
|
1208
|
+
}
|
|
1209
|
+
finally {
|
|
1210
|
+
scratch.release();
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
/** @internal Evaluates the expression at address. */
|
|
1214
|
+
evaluateAddress(expression, request) {
|
|
1215
|
+
const state = this.enter();
|
|
1216
|
+
const scratch = new Scratch(state);
|
|
1217
|
+
try {
|
|
1218
|
+
const values = request.variableValues.map((value) => value?.address() ?? 0);
|
|
1219
|
+
const words = scratch.words([
|
|
1220
|
+
request.context?.address() ?? 0,
|
|
1221
|
+
values.length > 0 ? scratch.words(values) : 0,
|
|
1222
|
+
values.length,
|
|
1223
|
+
]);
|
|
1224
|
+
return this.adopt(state.module.exports.sxml_javascript_evaluate(expression, words));
|
|
1225
|
+
}
|
|
1226
|
+
finally {
|
|
1227
|
+
scratch.release();
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
/** @internal options as the map fn:serialize takes, keys in kebab
|
|
1231
|
+
* case; undefined for none. */
|
|
1232
|
+
serializationOptions(options) {
|
|
1233
|
+
if (options === undefined) {
|
|
1234
|
+
return undefined;
|
|
1235
|
+
}
|
|
1236
|
+
const parameters = {};
|
|
1237
|
+
for (const [key, parameter] of Object.entries(options)) {
|
|
1238
|
+
parameters[key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)] = parameter;
|
|
1239
|
+
}
|
|
1240
|
+
return this.value(parameters);
|
|
1241
|
+
}
|
|
1242
|
+
serializeWith(value, options, sink) {
|
|
1243
|
+
const state = this.enter();
|
|
1244
|
+
const scratch = new Scratch(state);
|
|
1245
|
+
try {
|
|
1246
|
+
const request = scratch.words([value.address(), options?.address() ?? 0]);
|
|
1247
|
+
const status = this.streaming(new OutputRouter(sink), sink !== undefined, () => state.module.exports.sxml_javascript_serialize(state.address, request));
|
|
1248
|
+
if (status !== status_ok) {
|
|
1249
|
+
throw this.failure();
|
|
1250
|
+
}
|
|
1251
|
+
return sink === undefined ? this.output() : undefined;
|
|
1252
|
+
}
|
|
1253
|
+
finally {
|
|
1254
|
+
scratch.release();
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
/** @internal Runs call, a call of the shim that serializes, with its
|
|
1258
|
+
* output written to router's sinks when streams is true (D294); ends
|
|
1259
|
+
* them as the call ends, failed when it returned failed (0 or a status
|
|
1260
|
+
* other than OK, as isFailure says) or threw. */
|
|
1261
|
+
streaming(router, streams, call, isFailure) {
|
|
1262
|
+
if (!streams) {
|
|
1263
|
+
return call();
|
|
1264
|
+
}
|
|
1265
|
+
const state = this.state;
|
|
1266
|
+
const exports = state.module.exports;
|
|
1267
|
+
exports.sxml_javascript_set_output(state.address, state.outputChunkByteCount);
|
|
1268
|
+
state.outputRouter = router;
|
|
1269
|
+
let result;
|
|
1270
|
+
try {
|
|
1271
|
+
result = call();
|
|
1272
|
+
}
|
|
1273
|
+
catch (exception) {
|
|
1274
|
+
router.finish(true, exception);
|
|
1275
|
+
throw exception;
|
|
1276
|
+
}
|
|
1277
|
+
finally {
|
|
1278
|
+
state.outputRouter = undefined;
|
|
1279
|
+
exports.sxml_javascript_set_output(state.address, 0);
|
|
1280
|
+
}
|
|
1281
|
+
const failed = isFailure !== undefined ? isFailure(result) : result !== status_ok;
|
|
1282
|
+
if (failed) {
|
|
1283
|
+
// The failure stays readable: failure() reads it, and the sinks are
|
|
1284
|
+
// aborted with it after the caller has.
|
|
1285
|
+
const reason = this.peekFailure();
|
|
1286
|
+
router.finish(true, reason);
|
|
1287
|
+
}
|
|
1288
|
+
else {
|
|
1289
|
+
router.finish(false);
|
|
1290
|
+
}
|
|
1291
|
+
return result;
|
|
1292
|
+
}
|
|
1293
|
+
/** @internal The last failure without taking the resolver's exception. */
|
|
1294
|
+
peekFailure() {
|
|
1295
|
+
if (this.state.pendingException !== undefined) {
|
|
1296
|
+
return this.state.pendingException;
|
|
1297
|
+
}
|
|
1298
|
+
return this.failureRecord();
|
|
1299
|
+
}
|
|
1300
|
+
/** @internal The text of the processor's last serialization. */
|
|
1301
|
+
output() {
|
|
1302
|
+
const module = this.state.module;
|
|
1303
|
+
const output = module.exports.sxml_javascript_output_of(this.state.address) / 4;
|
|
1304
|
+
const words = module.words();
|
|
1305
|
+
return module.text(words[output] ?? 0, words[output + 1] ?? 0);
|
|
1306
|
+
}
|
|
1307
|
+
/** @internal A copy of the bytes of the processor's last
|
|
1308
|
+
* serialization. */
|
|
1309
|
+
outputBytes() {
|
|
1310
|
+
const module = this.state.module;
|
|
1311
|
+
const output = module.exports.sxml_javascript_output_of(this.state.address) / 4;
|
|
1312
|
+
const words = module.words();
|
|
1313
|
+
const address = words[output] ?? 0;
|
|
1314
|
+
return module.bytes().slice(address, address + (words[output + 1] ?? 0));
|
|
1315
|
+
}
|
|
1316
|
+
/** @internal The handle of options.schema, a schema of this processor;
|
|
1317
|
+
* 0 for none. */
|
|
1318
|
+
exiSchemaAddress(options) {
|
|
1319
|
+
const schema = options.schema;
|
|
1320
|
+
if (schema === undefined) {
|
|
1321
|
+
return 0;
|
|
1322
|
+
}
|
|
1323
|
+
if (!(schema instanceof Schema)) {
|
|
1324
|
+
throw new TypeError('sxml: the EXI option schema is not a Schema');
|
|
1325
|
+
}
|
|
1326
|
+
if (schema.processor !== this) {
|
|
1327
|
+
throw new Error('sxml: the schema belongs to another processor');
|
|
1328
|
+
}
|
|
1329
|
+
return schema.address();
|
|
1330
|
+
}
|
|
1331
|
+
/** @internal An input as a value of this processor; values it made are
|
|
1332
|
+
* pushed to made, for the caller to dispose. */
|
|
1333
|
+
input(data, made) {
|
|
1334
|
+
if (data instanceof Value) {
|
|
1335
|
+
this.check(data);
|
|
1336
|
+
return data;
|
|
1337
|
+
}
|
|
1338
|
+
const value = this.value(data);
|
|
1339
|
+
made.push(value);
|
|
1340
|
+
return value;
|
|
1341
|
+
}
|
|
1342
|
+
/** @internal The words of bindings (sxml_javascript_binding: name,
|
|
1343
|
+
* value), as a binding list's two words. */
|
|
1344
|
+
bindingWords(scratch, bindings, made) {
|
|
1345
|
+
const words = [];
|
|
1346
|
+
const entries = Object.entries(bindings ?? {});
|
|
1347
|
+
for (const [name, data] of entries) {
|
|
1348
|
+
words.push(...nameWords(scratch, name), this.input(data, made).address());
|
|
1349
|
+
}
|
|
1350
|
+
return [words.length > 0 ? scratch.words(words) : 0, entries.length];
|
|
1351
|
+
}
|
|
1352
|
+
/** @internal The module's exports. */
|
|
1353
|
+
exports() {
|
|
1354
|
+
return this.state.module.exports;
|
|
1355
|
+
}
|
|
1356
|
+
/** @internal Registers the handle of a compiled object. */
|
|
1357
|
+
track(owner, kind, address) {
|
|
1358
|
+
this.state.live.set(address, kind);
|
|
1359
|
+
this.state.module.track(owner, { processor: this.state, kind, address });
|
|
1360
|
+
}
|
|
1361
|
+
/** @internal Adopts a value handle that may be 0 (none). */
|
|
1362
|
+
adoptOptional(address) {
|
|
1363
|
+
return address === 0 ? undefined : this.adopt(address);
|
|
1364
|
+
}
|
|
1365
|
+
/** @internal The side results a call wrote at words[at], [at + 1]
|
|
1366
|
+
* (sxml_javascript_side_result_list), every value adopted. */
|
|
1367
|
+
sideResults(at) {
|
|
1368
|
+
const module = this.state.module;
|
|
1369
|
+
const list = module.words();
|
|
1370
|
+
const first = (list[at] ?? 0) / 4;
|
|
1371
|
+
const count = list[at + 1] ?? 0;
|
|
1372
|
+
const words = module.words().slice(first, first + count * 12);
|
|
1373
|
+
const results = [];
|
|
1374
|
+
for (let index = 0; index < count; index += 1) {
|
|
1375
|
+
const word = (offset) => words[index * 12 + offset] ?? 0;
|
|
1376
|
+
const text = (offset) => module.text(word(offset), word(offset + 1));
|
|
1377
|
+
results.push({
|
|
1378
|
+
kind: word(0),
|
|
1379
|
+
uri: text(1),
|
|
1380
|
+
text: text(3),
|
|
1381
|
+
code: text(5),
|
|
1382
|
+
// Every value is the package's now (sxml_javascript.h).
|
|
1383
|
+
first: this.adoptOptional(word(7)),
|
|
1384
|
+
second: this.adoptOptional(word(8)),
|
|
1385
|
+
lineNumber: word(9),
|
|
1386
|
+
columnNumber: word(10),
|
|
1387
|
+
isTerminating: word(11) !== 0,
|
|
1388
|
+
});
|
|
1389
|
+
}
|
|
1390
|
+
return results;
|
|
1391
|
+
}
|
|
1392
|
+
/** @internal Hands the MESSAGE side results to a callback. */
|
|
1393
|
+
deliverMessages(results, receive) {
|
|
1394
|
+
for (const result of results) {
|
|
1395
|
+
if (result.kind === side_result_message && receive !== undefined) {
|
|
1396
|
+
receive({
|
|
1397
|
+
text: result.text,
|
|
1398
|
+
code: result.code,
|
|
1399
|
+
isTerminating: result.isTerminating,
|
|
1400
|
+
sourceName: result.uri,
|
|
1401
|
+
lineNumber: result.lineNumber,
|
|
1402
|
+
columnNumber: result.columnNumber,
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
/** @internal Whether the last operation failed: its error has a
|
|
1408
|
+
* status, or the resolver threw. */
|
|
1409
|
+
hasFailed() {
|
|
1410
|
+
const state = this.state;
|
|
1411
|
+
const at = state.module.exports.sxml_javascript_error_of(state.address) / 4;
|
|
1412
|
+
return state.pendingException !== undefined || (state.module.words()[at] ?? 0) !== 0;
|
|
1413
|
+
}
|
|
1414
|
+
/** @internal The last operation's failure, or the resolver's exception. */
|
|
1415
|
+
failure() {
|
|
1416
|
+
const state = this.state;
|
|
1417
|
+
if (state.pendingException !== undefined) {
|
|
1418
|
+
const exception = state.pendingException;
|
|
1419
|
+
state.pendingException = undefined;
|
|
1420
|
+
return exception;
|
|
1421
|
+
}
|
|
1422
|
+
return this.failureRecord();
|
|
1423
|
+
}
|
|
1424
|
+
/** @internal The processor's error as an SxmlError. */
|
|
1425
|
+
failureRecord() {
|
|
1426
|
+
const state = this.state;
|
|
1427
|
+
const module = state.module;
|
|
1428
|
+
const at = module.exports.sxml_javascript_error_of(state.address) / 4;
|
|
1429
|
+
const words = module.words().slice(at, at + 15);
|
|
1430
|
+
const word = (index) => words[index] ?? 0;
|
|
1431
|
+
const text = (index) => module.text(word(index), word(index + 1));
|
|
1432
|
+
return new SxmlError({
|
|
1433
|
+
status: text(1).replace(/^SXML_STATUS_/, ''),
|
|
1434
|
+
codeNamespaceUri: text(3),
|
|
1435
|
+
codeLocalName: text(5),
|
|
1436
|
+
codePrefix: text(7),
|
|
1437
|
+
description: text(9),
|
|
1438
|
+
sourceName: text(11),
|
|
1439
|
+
lineNumber: word(13),
|
|
1440
|
+
columnNumber: word(14),
|
|
1441
|
+
});
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
// ------------------------------------------------------------ Expressions
|
|
1445
|
+
/** A compiled XPath 4.0 expression (include/sxml/xpath.h). */
|
|
1446
|
+
export class XPathExpression {
|
|
1447
|
+
processor;
|
|
1448
|
+
/** The external variables, in the order compile() was given them. */
|
|
1449
|
+
variables;
|
|
1450
|
+
handle;
|
|
1451
|
+
/** @internal Use Processor.compile(). */
|
|
1452
|
+
constructor(processor, address, variables) {
|
|
1453
|
+
this.processor = processor;
|
|
1454
|
+
this.handle = address;
|
|
1455
|
+
this.variables = [...variables];
|
|
1456
|
+
}
|
|
1457
|
+
/** Evaluates the expression; the result is a new value. */
|
|
1458
|
+
evaluate(options = {}) {
|
|
1459
|
+
if (this.handle === 0) {
|
|
1460
|
+
throw disposed('expression');
|
|
1461
|
+
}
|
|
1462
|
+
const made = [];
|
|
1463
|
+
const convert = (input) => {
|
|
1464
|
+
if (input === undefined) {
|
|
1465
|
+
return undefined;
|
|
1466
|
+
}
|
|
1467
|
+
if (input instanceof Value) {
|
|
1468
|
+
this.processor.check(input);
|
|
1469
|
+
return input;
|
|
1470
|
+
}
|
|
1471
|
+
const value = this.processor.value(input);
|
|
1472
|
+
made.push(value);
|
|
1473
|
+
return value;
|
|
1474
|
+
};
|
|
1475
|
+
try {
|
|
1476
|
+
const bindings = options.variables ?? {};
|
|
1477
|
+
return this.processor.evaluateAddress(this.handle, {
|
|
1478
|
+
context: convert(options.context),
|
|
1479
|
+
variableValues: this.variables.map((name) => Object.hasOwn(bindings, name) ? convert(bindings[name]) : undefined),
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
finally {
|
|
1483
|
+
for (const value of made) {
|
|
1484
|
+
value.dispose();
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
dispose() {
|
|
1489
|
+
if (this.handle !== 0) {
|
|
1490
|
+
this.processor.releaseHandle(this, 'expression', this.handle);
|
|
1491
|
+
this.handle = 0;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
// ---------------------------------------------------------------- XQuery
|
|
1496
|
+
/** A compiled XQuery 4.0 main module (include/sxml/xquery.h).
|
|
1497
|
+
* Processor.compileQuery makes it. */
|
|
1498
|
+
export class XQuery {
|
|
1499
|
+
processor;
|
|
1500
|
+
/** Whether its body is an updating expression (XQUF 3.0, 2.2): its
|
|
1501
|
+
* result is then empty and its changes go to options.updates. */
|
|
1502
|
+
isUpdating;
|
|
1503
|
+
handle;
|
|
1504
|
+
/** @internal Use Processor.compileQuery(). */
|
|
1505
|
+
constructor(processor, address, isUpdating) {
|
|
1506
|
+
this.processor = processor;
|
|
1507
|
+
this.handle = address;
|
|
1508
|
+
this.isUpdating = isUpdating;
|
|
1509
|
+
}
|
|
1510
|
+
/** Evaluates the query; the result is a new value. */
|
|
1511
|
+
evaluate(options = {}) {
|
|
1512
|
+
const processor = this.processor;
|
|
1513
|
+
const exports = processor.exports();
|
|
1514
|
+
const address = this.address();
|
|
1515
|
+
const state = processor.enter();
|
|
1516
|
+
const scratch = new Scratch(state);
|
|
1517
|
+
const made = [];
|
|
1518
|
+
let result = 0;
|
|
1519
|
+
let failure;
|
|
1520
|
+
let sideResults = [];
|
|
1521
|
+
try {
|
|
1522
|
+
const request = scratch.words([
|
|
1523
|
+
options.context === undefined ? 0 : processor.input(options.context, made).address(),
|
|
1524
|
+
...processor.bindingWords(scratch, options.variables, made),
|
|
1525
|
+
options.updates?.putDocument === undefined ? 0 : 1,
|
|
1526
|
+
0,
|
|
1527
|
+
0,
|
|
1528
|
+
]);
|
|
1529
|
+
result = exports.sxml_javascript_query_evaluate(address, request);
|
|
1530
|
+
// Read before a callback can use the processor.
|
|
1531
|
+
failure = result === 0 ? processor.failure() : undefined;
|
|
1532
|
+
sideResults = processor.sideResults(request / 4 + 4);
|
|
1533
|
+
}
|
|
1534
|
+
finally {
|
|
1535
|
+
scratch.release();
|
|
1536
|
+
for (const value of made) {
|
|
1537
|
+
value.dispose();
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
const value = result === 0 ? undefined : processor.adopt(result);
|
|
1541
|
+
processor.deliverMessages(sideResults, options.messages);
|
|
1542
|
+
deliverUpdates(processor, sideResults, options.updates);
|
|
1543
|
+
if (value === undefined) {
|
|
1544
|
+
throw failure;
|
|
1545
|
+
}
|
|
1546
|
+
return value;
|
|
1547
|
+
}
|
|
1548
|
+
/** Serializes a value with the serialization parameters the query's
|
|
1549
|
+
* output declarations give (XQuery 4.0, 5.22: method xml unless they
|
|
1550
|
+
* name another). Value.serialize(options) uses options instead. */
|
|
1551
|
+
serialize(value) {
|
|
1552
|
+
this.serializeOutput(value, undefined);
|
|
1553
|
+
return this.processor.output();
|
|
1554
|
+
}
|
|
1555
|
+
/** Serializes a value as serialize() does, writing the output to sink a
|
|
1556
|
+
* chunk at a time instead of returning it (D294). */
|
|
1557
|
+
serializeTo(value, sink) {
|
|
1558
|
+
this.serializeOutput(value, sink);
|
|
1559
|
+
}
|
|
1560
|
+
/** Evaluates the query and serializes its result as serialize() does. */
|
|
1561
|
+
run(options = {}) {
|
|
1562
|
+
const result = this.evaluate(options);
|
|
1563
|
+
try {
|
|
1564
|
+
return this.serialize(result);
|
|
1565
|
+
}
|
|
1566
|
+
finally {
|
|
1567
|
+
result.dispose();
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
/** Evaluates the query and writes its serialized result to sink a chunk
|
|
1571
|
+
* at a time, as serializeTo() does (D294). */
|
|
1572
|
+
runTo(sink, options = {}) {
|
|
1573
|
+
const result = this.evaluate(options);
|
|
1574
|
+
try {
|
|
1575
|
+
this.serializeTo(result, sink);
|
|
1576
|
+
}
|
|
1577
|
+
finally {
|
|
1578
|
+
result.dispose();
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
serializeOutput(value, sink) {
|
|
1582
|
+
const processor = this.processor;
|
|
1583
|
+
const exports = processor.exports();
|
|
1584
|
+
processor.enter();
|
|
1585
|
+
processor.check(value);
|
|
1586
|
+
const address = this.address();
|
|
1587
|
+
const status = processor.streaming(new OutputRouter(sink), sink !== undefined, () => exports.sxml_javascript_query_serialize(address, value.address()));
|
|
1588
|
+
if (status !== status_ok) {
|
|
1589
|
+
throw processor.failure();
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
dispose() {
|
|
1593
|
+
if (this.handle !== 0) {
|
|
1594
|
+
this.processor.releaseHandle(this, 'query', this.handle);
|
|
1595
|
+
this.handle = 0;
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
address() {
|
|
1599
|
+
if (this.handle === 0) {
|
|
1600
|
+
throw disposed('query');
|
|
1601
|
+
}
|
|
1602
|
+
return this.handle;
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
/** Hands UPDATED_TREE and PUT_DOCUMENT side results to the sink; disposes
|
|
1606
|
+
* what it does not take. */
|
|
1607
|
+
function deliverUpdates(processor, results, sink) {
|
|
1608
|
+
for (const result of results) {
|
|
1609
|
+
if (result.kind === side_result_updated_tree && result.first !== undefined && result.second !== undefined) {
|
|
1610
|
+
if (sink?.updatedTree !== undefined) {
|
|
1611
|
+
sink.updatedTree({ original: result.first, updated: result.second });
|
|
1612
|
+
}
|
|
1613
|
+
else {
|
|
1614
|
+
result.first.dispose();
|
|
1615
|
+
result.second.dispose();
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
else if (result.kind === side_result_put_document && result.first !== undefined) {
|
|
1619
|
+
const node = result.first;
|
|
1620
|
+
const parameters = result.second;
|
|
1621
|
+
if (sink?.putDocument !== undefined) {
|
|
1622
|
+
sink.putDocument({
|
|
1623
|
+
uri: result.uri,
|
|
1624
|
+
node,
|
|
1625
|
+
parameters,
|
|
1626
|
+
serialize: () => {
|
|
1627
|
+
if (parameters !== undefined) {
|
|
1628
|
+
return processor.serializeWith(node, parameters);
|
|
1629
|
+
}
|
|
1630
|
+
const options = processor.value({});
|
|
1631
|
+
try {
|
|
1632
|
+
return processor.serializeWith(node, options);
|
|
1633
|
+
}
|
|
1634
|
+
finally {
|
|
1635
|
+
options.dispose();
|
|
1636
|
+
}
|
|
1637
|
+
},
|
|
1638
|
+
serializeTo: (sink) => {
|
|
1639
|
+
if (parameters !== undefined) {
|
|
1640
|
+
processor.serializeWith(node, parameters, sink);
|
|
1641
|
+
return;
|
|
1642
|
+
}
|
|
1643
|
+
const options = processor.value({});
|
|
1644
|
+
try {
|
|
1645
|
+
processor.serializeWith(node, options, sink);
|
|
1646
|
+
}
|
|
1647
|
+
finally {
|
|
1648
|
+
options.dispose();
|
|
1649
|
+
}
|
|
1650
|
+
},
|
|
1651
|
+
});
|
|
1652
|
+
}
|
|
1653
|
+
else {
|
|
1654
|
+
node.dispose();
|
|
1655
|
+
parameters?.dispose();
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
// ------------------------------------------------------------------ XSLT
|
|
1661
|
+
/** A compiled XSLT 4.0 stylesheet (include/sxml/xslt.h).
|
|
1662
|
+
* Processor.compileStylesheet makes it. */
|
|
1663
|
+
export class Stylesheet {
|
|
1664
|
+
processor;
|
|
1665
|
+
handle;
|
|
1666
|
+
/** @internal Use Processor.compileStylesheet(). */
|
|
1667
|
+
constructor(processor, address) {
|
|
1668
|
+
this.processor = processor;
|
|
1669
|
+
this.handle = address;
|
|
1670
|
+
}
|
|
1671
|
+
/** Runs one transformation (XSLT 4.0, 2.3): applies templates to the
|
|
1672
|
+
* source, or calls options.initialTemplate or options.initialFunction. */
|
|
1673
|
+
transform(options = {}) {
|
|
1674
|
+
const processor = this.processor;
|
|
1675
|
+
const exports = processor.exports();
|
|
1676
|
+
const address = this.address();
|
|
1677
|
+
const state = processor.enter();
|
|
1678
|
+
const scratch = new Scratch(state);
|
|
1679
|
+
const made = [];
|
|
1680
|
+
const delivery = options.delivery ?? 'serialized';
|
|
1681
|
+
const resultDocumentDelivery = options.resultDocumentDelivery ?? 'serialized';
|
|
1682
|
+
if (options.output !== undefined && delivery !== 'serialized') {
|
|
1683
|
+
throw new Error("sxml: TransformOptions.output needs delivery 'serialized'");
|
|
1684
|
+
}
|
|
1685
|
+
if (options.streamedSource !== undefined &&
|
|
1686
|
+
(options.source !== undefined || options.initialMatchSelection !== undefined)) {
|
|
1687
|
+
throw new Error('sxml: TransformOptions.streamedSource is the initial match selection');
|
|
1688
|
+
}
|
|
1689
|
+
// With a sink, the serialized results are written in chunks (D294).
|
|
1690
|
+
const router = new OutputRouter(options.output, options.resultDocumentOutput);
|
|
1691
|
+
const streams = options.output !== undefined ||
|
|
1692
|
+
(options.resultDocumentOutput !== undefined && resultDocumentDelivery === 'serialized');
|
|
1693
|
+
let result = 0;
|
|
1694
|
+
let failure;
|
|
1695
|
+
let output;
|
|
1696
|
+
let sideResults = [];
|
|
1697
|
+
try {
|
|
1698
|
+
const input = (data) => data === undefined ? 0 : processor.input(data, made).address();
|
|
1699
|
+
const args = (options.args ?? []).map(input);
|
|
1700
|
+
const serialization = processor.serializationOptions(options.serialization);
|
|
1701
|
+
if (serialization !== undefined) {
|
|
1702
|
+
made.push(serialization);
|
|
1703
|
+
}
|
|
1704
|
+
const invocation = options.initialFunction !== undefined
|
|
1705
|
+
? invocation_call_function
|
|
1706
|
+
: options.initialTemplate !== undefined ||
|
|
1707
|
+
(options.source === undefined &&
|
|
1708
|
+
options.initialMatchSelection === undefined &&
|
|
1709
|
+
options.streamedSource === undefined)
|
|
1710
|
+
? invocation_call_template
|
|
1711
|
+
: invocation_apply_templates;
|
|
1712
|
+
const unnamedMode = options.initialMode === '#unnamed';
|
|
1713
|
+
const request = scratch.words([
|
|
1714
|
+
input(options.source),
|
|
1715
|
+
input(options.initialMatchSelection),
|
|
1716
|
+
...processor.bindingWords(scratch, options.parameters, made),
|
|
1717
|
+
...processor.bindingWords(scratch, options.templateParameters, made),
|
|
1718
|
+
...processor.bindingWords(scratch, options.tunnelParameters, made),
|
|
1719
|
+
args.length > 0 ? scratch.words(args) : 0,
|
|
1720
|
+
args.length,
|
|
1721
|
+
...scratch.view(options.baseOutputUri ?? ''),
|
|
1722
|
+
serialization?.address() ?? 0,
|
|
1723
|
+
...nameWords(scratch, unnamedMode ? undefined : options.initialMode),
|
|
1724
|
+
...nameWords(scratch, options.initialTemplate),
|
|
1725
|
+
...nameWords(scratch, options.initialFunction),
|
|
1726
|
+
invocation,
|
|
1727
|
+
result_deliveries[delivery],
|
|
1728
|
+
result_deliveries[resultDocumentDelivery],
|
|
1729
|
+
unnamedMode ? 1 : 0,
|
|
1730
|
+
0,
|
|
1731
|
+
0,
|
|
1732
|
+
...scratch.view(options.streamedSource ?? ''),
|
|
1733
|
+
]);
|
|
1734
|
+
result = processor.streaming(router, streams, () => exports.sxml_javascript_stylesheet_transform(address, request), (made) => made === 0);
|
|
1735
|
+
// Read before a callback can use the processor.
|
|
1736
|
+
failure = result === 0 ? processor.failure() : undefined;
|
|
1737
|
+
if (result !== 0 && delivery === 'serialized' && options.output === undefined) {
|
|
1738
|
+
output = streams ? router.principalOutput() : processor.output();
|
|
1739
|
+
}
|
|
1740
|
+
sideResults = processor.sideResults(request / 4 + 29);
|
|
1741
|
+
}
|
|
1742
|
+
finally {
|
|
1743
|
+
scratch.release();
|
|
1744
|
+
for (const value of made) {
|
|
1745
|
+
value.dispose();
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
const value = result === 0 ? undefined : processor.adopt(result);
|
|
1749
|
+
processor.deliverMessages(sideResults, options.messages);
|
|
1750
|
+
const resultDocuments = router.gathered.map((document) => ({
|
|
1751
|
+
uri: document.uri,
|
|
1752
|
+
output: document.output,
|
|
1753
|
+
value: undefined,
|
|
1754
|
+
}));
|
|
1755
|
+
for (const side of sideResults) {
|
|
1756
|
+
if (side.kind === side_result_result_document) {
|
|
1757
|
+
resultDocuments.push({
|
|
1758
|
+
uri: side.uri,
|
|
1759
|
+
output: side.first === undefined ? side.text : undefined,
|
|
1760
|
+
value: side.first,
|
|
1761
|
+
});
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
if (value === undefined) {
|
|
1765
|
+
for (const document of resultDocuments) {
|
|
1766
|
+
document.value?.dispose();
|
|
1767
|
+
}
|
|
1768
|
+
throw failure;
|
|
1769
|
+
}
|
|
1770
|
+
if (delivery === 'serialized') {
|
|
1771
|
+
value.dispose();
|
|
1772
|
+
return { output, value: undefined, resultDocuments };
|
|
1773
|
+
}
|
|
1774
|
+
return { output: undefined, value, resultDocuments };
|
|
1775
|
+
}
|
|
1776
|
+
dispose() {
|
|
1777
|
+
if (this.handle !== 0) {
|
|
1778
|
+
this.processor.releaseHandle(this, 'stylesheet', this.handle);
|
|
1779
|
+
this.handle = 0;
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
address() {
|
|
1783
|
+
if (this.handle === 0) {
|
|
1784
|
+
throw disposed('stylesheet');
|
|
1785
|
+
}
|
|
1786
|
+
return this.handle;
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
// ------------------------------------------------------------------- XSD
|
|
1790
|
+
/** A Schematron compile report that is a warning, not an error: a known
|
|
1791
|
+
* deviation of real rule sets, read as its authors mean it. */
|
|
1792
|
+
function isSchematronWarning(report) {
|
|
1793
|
+
return report.code === 'schematron:compatibility';
|
|
1794
|
+
}
|
|
1795
|
+
/** The SCHEMA_REPORT side results as reports. */
|
|
1796
|
+
function schemaReports(results) {
|
|
1797
|
+
return results
|
|
1798
|
+
.filter((result) => result.kind === side_result_schema_report)
|
|
1799
|
+
.map((result) => ({
|
|
1800
|
+
code: result.code,
|
|
1801
|
+
description: result.text,
|
|
1802
|
+
sourceName: result.uri,
|
|
1803
|
+
lineNumber: result.lineNumber,
|
|
1804
|
+
columnNumber: result.columnNumber,
|
|
1805
|
+
}));
|
|
1806
|
+
}
|
|
1807
|
+
/** A compiled XSD 1.1 schema (include/sxml/schema.h).
|
|
1808
|
+
* Processor.compileSchema makes it. */
|
|
1809
|
+
export class Schema {
|
|
1810
|
+
processor;
|
|
1811
|
+
handle;
|
|
1812
|
+
/** @internal Use Processor.compileSchema(). */
|
|
1813
|
+
constructor(processor, address) {
|
|
1814
|
+
this.processor = processor;
|
|
1815
|
+
this.handle = address;
|
|
1816
|
+
}
|
|
1817
|
+
/** Validates a document (XSD 1.1 Part 1, 5.2): XML text, parsed and
|
|
1818
|
+
* validated in one pass so that reports have its lines and columns, or
|
|
1819
|
+
* a document or element node of this processor. An invalid document is
|
|
1820
|
+
* not an exception: see the result's validity and reports. Text that
|
|
1821
|
+
* is not well-formed throws, as Processor.parse does. */
|
|
1822
|
+
validate(input, options = {}) {
|
|
1823
|
+
const processor = this.processor;
|
|
1824
|
+
const exports = processor.exports();
|
|
1825
|
+
const address = this.address();
|
|
1826
|
+
if (input instanceof Value) {
|
|
1827
|
+
processor.check(input);
|
|
1828
|
+
}
|
|
1829
|
+
const state = processor.enter();
|
|
1830
|
+
const scratch = new Scratch(state);
|
|
1831
|
+
let result = 0;
|
|
1832
|
+
let failure;
|
|
1833
|
+
let validity = 'invalid';
|
|
1834
|
+
let reports = [];
|
|
1835
|
+
try {
|
|
1836
|
+
const request = scratch.words([
|
|
1837
|
+
input instanceof Value ? input.address() : 0,
|
|
1838
|
+
...(input instanceof Value ? [0, 0] : scratch.view(input)),
|
|
1839
|
+
...scratch.view(options.uri ?? ''),
|
|
1840
|
+
options.mode === 'lax' ? 1 : 0,
|
|
1841
|
+
...nameWords(scratch, options.type),
|
|
1842
|
+
0,
|
|
1843
|
+
0,
|
|
1844
|
+
0,
|
|
1845
|
+
]);
|
|
1846
|
+
result = exports.sxml_javascript_schema_validate(address, request);
|
|
1847
|
+
failure = result === 0 && processor.hasFailed() ? processor.failure() : undefined;
|
|
1848
|
+
validity = validities[state.module.words()[request / 4 + 10] ?? 1] ?? 'invalid';
|
|
1849
|
+
reports = schemaReports(processor.sideResults(request / 4 + 11));
|
|
1850
|
+
}
|
|
1851
|
+
finally {
|
|
1852
|
+
scratch.release();
|
|
1853
|
+
}
|
|
1854
|
+
if (failure !== undefined) {
|
|
1855
|
+
throw failure;
|
|
1856
|
+
}
|
|
1857
|
+
return { validity, reports, document: processor.adoptOptional(result) };
|
|
1858
|
+
}
|
|
1859
|
+
dispose() {
|
|
1860
|
+
if (this.handle !== 0) {
|
|
1861
|
+
this.processor.releaseHandle(this, 'schema', this.handle);
|
|
1862
|
+
this.handle = 0;
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
/** @internal The handle, checked usable. */
|
|
1866
|
+
address() {
|
|
1867
|
+
if (this.handle === 0) {
|
|
1868
|
+
throw disposed('schema');
|
|
1869
|
+
}
|
|
1870
|
+
return this.handle;
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
// ------------------------------------------------------------ Schematron
|
|
1874
|
+
/** A compiled Schematron schema (include/sxml/schematron.h).
|
|
1875
|
+
* Processor.compileSchematron makes it. */
|
|
1876
|
+
export class Schematron {
|
|
1877
|
+
processor;
|
|
1878
|
+
handle;
|
|
1879
|
+
/** The schema's title, schemaVersion, schematronEdition (any value, as
|
|
1880
|
+
* written) and queryBinding; empty when absent. */
|
|
1881
|
+
title = '';
|
|
1882
|
+
schemaVersion = '';
|
|
1883
|
+
schematronEdition = '';
|
|
1884
|
+
queryBinding = '';
|
|
1885
|
+
/** The phase compiled ('#DEFAULT' resolved). */
|
|
1886
|
+
phase = '';
|
|
1887
|
+
/** The schema's warnings (code 'schematron:compatibility'): a parameter
|
|
1888
|
+
* named twice in one pattern instance, a pattern's let read by another
|
|
1889
|
+
* pattern, a rule's let after its assertions. Read as their authors
|
|
1890
|
+
* mean them; each names the clause it deviates from. */
|
|
1891
|
+
warnings = [];
|
|
1892
|
+
/** @internal Use Processor.compileSchematron(). */
|
|
1893
|
+
constructor(processor, address) {
|
|
1894
|
+
this.processor = processor;
|
|
1895
|
+
this.handle = address;
|
|
1896
|
+
}
|
|
1897
|
+
/** @internal */
|
|
1898
|
+
describe(fields) {
|
|
1899
|
+
this.warnings = Object.freeze(fields.warnings);
|
|
1900
|
+
this.title = fields.title;
|
|
1901
|
+
this.schemaVersion = fields.schemaVersion;
|
|
1902
|
+
this.schematronEdition = fields.schematronEdition;
|
|
1903
|
+
this.queryBinding = fields.queryBinding;
|
|
1904
|
+
this.phase = fields.phase;
|
|
1905
|
+
}
|
|
1906
|
+
/** Validates a document: XML text, parsed with its locations, or a node
|
|
1907
|
+
* of this processor. Findings are not exceptions: see the result. A
|
|
1908
|
+
* dynamic error in the rules, or text that is not well-formed, throws. */
|
|
1909
|
+
validate(input, options = {}) {
|
|
1910
|
+
const processor = this.processor;
|
|
1911
|
+
const exports = processor.exports();
|
|
1912
|
+
const address = this.address();
|
|
1913
|
+
if (input instanceof Value) {
|
|
1914
|
+
processor.check(input);
|
|
1915
|
+
}
|
|
1916
|
+
const state = processor.enter();
|
|
1917
|
+
const scratch = new Scratch(state);
|
|
1918
|
+
let status = status_ok;
|
|
1919
|
+
let output = '';
|
|
1920
|
+
try {
|
|
1921
|
+
const request = scratch.words([
|
|
1922
|
+
input instanceof Value ? input.address() : 0,
|
|
1923
|
+
...(input instanceof Value ? [0, 0] : scratch.view(input)),
|
|
1924
|
+
...scratch.view(options.uri ?? ''),
|
|
1925
|
+
options.firedRules === true ? 1 : 0,
|
|
1926
|
+
options.svrl === true ? 1 : 0,
|
|
1927
|
+
]);
|
|
1928
|
+
status = exports.sxml_javascript_schematron_validate(address, request);
|
|
1929
|
+
output = status === status_ok ? processor.output() : '';
|
|
1930
|
+
}
|
|
1931
|
+
finally {
|
|
1932
|
+
scratch.release();
|
|
1933
|
+
}
|
|
1934
|
+
if (status !== status_ok) {
|
|
1935
|
+
throw processor.failure();
|
|
1936
|
+
}
|
|
1937
|
+
return JSON.parse(output);
|
|
1938
|
+
}
|
|
1939
|
+
dispose() {
|
|
1940
|
+
if (this.handle !== 0) {
|
|
1941
|
+
this.processor.releaseHandle(this, 'schematron', this.handle);
|
|
1942
|
+
this.handle = 0;
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
address() {
|
|
1946
|
+
if (this.handle === 0) {
|
|
1947
|
+
throw disposed('schematron');
|
|
1948
|
+
}
|
|
1949
|
+
return this.handle;
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
// ----------------------------------------------------------------- Values
|
|
1953
|
+
/** An XDM value: a sequence of items in its processor (a parsed document,
|
|
1954
|
+
* an evaluation's result). */
|
|
1955
|
+
export class Value {
|
|
1956
|
+
processor;
|
|
1957
|
+
handle;
|
|
1958
|
+
/** @internal */
|
|
1959
|
+
constructor(processor, address) {
|
|
1960
|
+
this.processor = processor;
|
|
1961
|
+
this.handle = address;
|
|
1962
|
+
}
|
|
1963
|
+
/** @internal The handle, checked usable. */
|
|
1964
|
+
address() {
|
|
1965
|
+
if (this.handle === 0) {
|
|
1966
|
+
throw disposed('value');
|
|
1967
|
+
}
|
|
1968
|
+
return this.handle;
|
|
1969
|
+
}
|
|
1970
|
+
/** Serializes the value (Processor.serialize). */
|
|
1971
|
+
serialize(options) {
|
|
1972
|
+
return this.processor.serialize(this, options);
|
|
1973
|
+
}
|
|
1974
|
+
/** Serializes the value to sink a chunk at a time
|
|
1975
|
+
* (Processor.serializeTo). */
|
|
1976
|
+
serializeTo(sink, options) {
|
|
1977
|
+
this.processor.serializeTo(this, sink, options);
|
|
1978
|
+
}
|
|
1979
|
+
/** The value by the adaptive method: items one per line, strings
|
|
1980
|
+
* quoted, nodes as XML. */
|
|
1981
|
+
toString() {
|
|
1982
|
+
return this.processor.serialize(this);
|
|
1983
|
+
}
|
|
1984
|
+
dispose() {
|
|
1985
|
+
if (this.handle !== 0) {
|
|
1986
|
+
this.processor.releaseHandle(this, 'value', this.handle);
|
|
1987
|
+
this.handle = 0;
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
}
|