@xapi-js/core 1.1.1 → 1.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/dist/index.js CHANGED
@@ -1,745 +1,1025 @@
1
- // src/handler.ts
2
- import { StaxXmlWriter } from "stax-xml";
3
- import * as txml from "txml";
4
-
5
- // src/types.ts
6
- var rowType = ["insert", "update", "delete"];
7
- var columnType = ["STRING", "INT", "FLOAT", "DECIMAL", "BIGDECIMAL", "DATE", "DATETIME", "TIME", "BLOB"];
8
- var XplatformVersion = {
9
- xmlns: "http://www.tobesoft.com/platform/Dataset",
10
- version: "4000"
1
+ //#region src/types.ts
2
+ /**
3
+ * Defines the possible types of rows in an X-API dataset (e.g., "insert", "update", "delete").
4
+ */
5
+ const rowType = [
6
+ "insert",
7
+ "update",
8
+ "delete"
9
+ ];
10
+ /**
11
+ * Defines the possible data types for columns in an X-API dataset.
12
+ */
13
+ const columnType = [
14
+ "STRING",
15
+ "INT",
16
+ "FLOAT",
17
+ "DECIMAL",
18
+ "BIGDECIMAL",
19
+ "DATE",
20
+ "DATETIME",
21
+ "TIME",
22
+ "BLOB"
23
+ ];
24
+ /**
25
+ * Xplatform version definition for X-API XML.
26
+ */
27
+ const XplatformVersion = {
28
+ xmlns: "http://www.tobesoft.com/platform/Dataset",
29
+ version: "4000"
11
30
  };
12
- var NexaVersion = {
13
- xmlns: "http://www.nexacroplatform.com/platform/dataset",
14
- version: "4000"
31
+ /**
32
+ * Nexacro version definition for X-API XML.
33
+ */
34
+ const NexaVersion = {
35
+ xmlns: "http://www.nexacroplatform.com/platform/dataset",
36
+ version: "4000"
15
37
  };
38
+ /**
39
+ * Custom error class for column type related issues.
40
+ */
16
41
  var ColumnTypeError = class extends Error {
17
- constructor(message) {
18
- super(message);
19
- this.name = "ColumnTypeError";
20
- }
42
+ constructor(message) {
43
+ super(message);
44
+ this.name = "ColumnTypeError";
45
+ }
21
46
  };
22
47
  var InvalidXmlError = class extends Error {
23
- constructor(message) {
24
- super(message);
25
- this.name = "InvalidXmlError";
26
- }
48
+ constructor(message) {
49
+ super(message);
50
+ this.name = "InvalidXmlError";
51
+ }
27
52
  };
28
53
 
29
- // src/utils.ts
54
+ //#endregion
55
+ //#region src/xapi-data.ts
56
+ /**
57
+ * Represents the root of an X-API XML structure, containing datasets and parameters.
58
+ */
59
+ var XapiRoot = class {
60
+ /** An array of datasets within the X-API root. */
61
+ datasets = [];
62
+ /** Parameters associated with the X-API root. */
63
+ parameters = { params: [] };
64
+ /**
65
+ * Creates an instance of XapiRoot.
66
+ * @param datasets - Initial array of datasets.
67
+ * @param parameters - Initial parameters.
68
+ */
69
+ constructor(datasets = [], parameters = { params: [] }) {
70
+ this.datasets = datasets;
71
+ this.parameters = parameters;
72
+ }
73
+ /**
74
+ * Adds a dataset to the X-API root.
75
+ * @param dataset - The dataset to add.
76
+ */
77
+ addDataset(dataset) {
78
+ this.datasets.push(dataset);
79
+ }
80
+ /**
81
+ * Retrieves a dataset by its ID.
82
+ * @param id - The ID of the dataset to retrieve.
83
+ * @returns The Dataset object, or undefined if not found.
84
+ */
85
+ getDataset(id) {
86
+ return this.datasets.find((dataset) => dataset.id === id);
87
+ }
88
+ /**
89
+ * Adds a parameter to the X-API root.
90
+ * @param parameter - The parameter to add.
91
+ */
92
+ addParameter(parameter) {
93
+ this.parameters.params.push(parameter);
94
+ }
95
+ /**
96
+ * Retrieves a parameter by its ID.
97
+ * @param id - The ID of the parameter to retrieve.
98
+ * @returns The Parameter object, or undefined if not found.
99
+ */
100
+ getParameter(id) {
101
+ return this.parameters.params.find((param) => param.id === id);
102
+ }
103
+ /**
104
+ * Sets all parameters for the X-API root.
105
+ * @param parameters - The XapiParameters object to set.
106
+ */
107
+ setParameters(parameters) {
108
+ this.parameters = parameters;
109
+ }
110
+ /**
111
+ * Sets the value of a specific parameter, or adds it if it doesn't exist.
112
+ * @param id - The ID of the parameter.
113
+ * @param value - The value to set for the parameter.
114
+ */
115
+ setParameter(id, value) {
116
+ const param = this.parameters.params.find((p) => p.id === id);
117
+ if (param) param.value = value;
118
+ else this.addParameter({
119
+ id,
120
+ value
121
+ });
122
+ }
123
+ /**
124
+ * Returns the number of parameters.
125
+ * @returns The count of parameters.
126
+ */
127
+ parameterSize() {
128
+ return this.parameters.params.length;
129
+ }
130
+ /**
131
+ * Returns the number of datasets.
132
+ * @returns The count of datasets.
133
+ */
134
+ datasetSize() {
135
+ return this.datasets.length;
136
+ }
137
+ /**
138
+ * Returns all parameters as an array.
139
+ * @returns An array of parameters.
140
+ */
141
+ getParameters() {
142
+ return this.parameters.params;
143
+ }
144
+ /**
145
+ * Returns all datasets as an array.
146
+ * @returns An array of datasets.
147
+ */
148
+ getDatasets() {
149
+ return this.datasets;
150
+ }
151
+ };
152
+ /**
153
+ * Represents a dataset within an X-API XML structure.
154
+ */
155
+ var Dataset = class {
156
+ /** The ID of the dataset. */
157
+ id;
158
+ constColumns = [];
159
+ columns = [];
160
+ /** An array of rows in the dataset. */
161
+ rows = [];
162
+ _columnIndexMap = /* @__PURE__ */ new Map();
163
+ /**
164
+ * Creates an instance of Dataset.
165
+ * @param id - The ID of the dataset.
166
+ * @param constColumns - Initial array of constant columns.
167
+ * @param columns - Initial array of columns.
168
+ * @param rows - Initial array of rows.
169
+ */
170
+ constructor(id, constColumns = [], columns = [], rows = []) {
171
+ this.id = id;
172
+ this.constColumns = constColumns;
173
+ this.columns = columns;
174
+ this.rows = rows;
175
+ }
176
+ /**
177
+ * Adds a column definition to the dataset.
178
+ * @param column - The column definition to add.
179
+ */
180
+ addColumn(column) {
181
+ this.columns.push(column);
182
+ this._columnIndexMap.set(column.id, this.columns.length - 1);
183
+ }
184
+ /**
185
+ * Adds a constant column definition to the dataset.
186
+ * @param column - The constant column definition to add.
187
+ */
188
+ addConstColumn(column) {
189
+ this.constColumns.push(column);
190
+ }
191
+ /**
192
+ * Creates a new empty row and adds it to the dataset.
193
+ * @returns The index of the newly created row.
194
+ */
195
+ newRow() {
196
+ this.rows.push({ cols: [] });
197
+ return this.rows.length - 1;
198
+ }
199
+ /**
200
+ * Adds an existing row to the dataset.
201
+ * @param row - The row to add.
202
+ */
203
+ addRow(row) {
204
+ this.rows.push(row);
205
+ }
206
+ /**
207
+ * Retrieves the index of a column by its ID.
208
+ * @param columnId - The ID of the column.
209
+ * @returns The index of the column, or undefined if not found.
210
+ */
211
+ getColumnIndex(columnId) {
212
+ return this._columnIndexMap.get(columnId);
213
+ }
214
+ /**
215
+ * Retrieves the column definition by its ID.
216
+ * @param columnId - The ID of the column.
217
+ * @returns The Column object, or undefined if not found.
218
+ */
219
+ getColumnInfo(columnId) {
220
+ const colIndex = this.getColumnIndex(columnId);
221
+ if (colIndex !== void 0) return this.columns[colIndex];
222
+ }
223
+ /**
224
+ * Retrieves the constant column definition by its ID.
225
+ * @param columnId - The ID of the constant column.
226
+ * @returns The ConstColumn object, or undefined if not found.
227
+ */
228
+ getConstColumnInfo(columnId) {
229
+ return this.constColumns.find((col) => col.id === columnId);
230
+ }
231
+ /**
232
+ * Retrieves the value of a column in a specific row.
233
+ * @param rowIdx - The index of the row.
234
+ * @param columnId - The ID of the column.
235
+ * @returns The value of the column, or undefined if the row or column is not found.
236
+ * @throws {Error} if the column ID is not found in the dataset.
237
+ */
238
+ getColumn(rowIdx, columnId) {
239
+ if (rowIdx < this.rows.length) {
240
+ const colIndex = this.getColumnIndex(columnId);
241
+ if (colIndex === void 0) throw new Error(`Column with id ${columnId} not found in dataset ${this.id}`);
242
+ return this.rows[rowIdx].cols[colIndex]?.value;
243
+ }
244
+ }
245
+ /**
246
+ * Retrieves the original value of a column in a specific row (for OrgRow).
247
+ * @param rowIdx - The index of the row.
248
+ * @param columnId - The ID of the column.
249
+ * @returns The original value of the column, or undefined if the row or column is not found.
250
+ * @throws {Error} if the column ID is not found in the dataset.
251
+ */
252
+ getOrgColumn(rowIdx, columnId) {
253
+ if (rowIdx < this.rows.length) {
254
+ const colIndex = this.getColumnIndex(columnId);
255
+ if (colIndex === void 0) throw new Error(`Column with id ${columnId} not found in dataset ${this.id}`);
256
+ return (this.rows[rowIdx].orgRow?.[colIndex])?.value;
257
+ }
258
+ }
259
+ /**
260
+ * Sets the value of a column in a specific row.
261
+ * @param rowIdx - The index of the row.
262
+ * @param columnId - The ID of the column.
263
+ * @param value - The value to set.
264
+ * @throws {Error} if the row index is out of bounds or the column ID is not found.
265
+ */
266
+ setColumn(rowIdx, columnId, value) {
267
+ if (rowIdx < this.rows.length) {
268
+ const colIndex = this.getColumnIndex(columnId);
269
+ if (colIndex === void 0) throw new Error(`Column with id ${columnId} not found in dataset ${this.id}`);
270
+ this.rows[rowIdx].cols[colIndex] = {
271
+ id: columnId,
272
+ value
273
+ };
274
+ } else throw new Error(`Row index ${rowIdx} out of bounds in dataset ${this.id}`);
275
+ }
276
+ /**
277
+ * Returns all constant column definitions as an array.
278
+ * @returns An array of constant columns.
279
+ */
280
+ getConstColumns() {
281
+ return this.constColumns;
282
+ }
283
+ /**
284
+ * Returns all column definitions as an array.
285
+ * @returns An array of columns.
286
+ */
287
+ getColumns() {
288
+ return this.columns;
289
+ }
290
+ /**
291
+ * Returns all rows in the dataset as an array.
292
+ * @returns An array of rows.
293
+ */
294
+ getRows() {
295
+ return this.rows;
296
+ }
297
+ /**
298
+ * Returns the number of column definitions.
299
+ * @returns The count of columns.
300
+ */
301
+ columnSize() {
302
+ return this.columns.length;
303
+ }
304
+ /**
305
+ * Returns the number of constant column definitions.
306
+ * @returns The count of constant columns.
307
+ */
308
+ constColumnSize() {
309
+ return this.constColumns.length;
310
+ }
311
+ /**
312
+ * Returns the number of rows in the dataset.
313
+ * @returns The count of rows.
314
+ */
315
+ rowSize() {
316
+ return this.rows.length;
317
+ }
318
+ };
319
+
320
+ //#endregion
321
+ //#region src/utils.ts
30
322
  function arrayBufferToString(buffer) {
31
- const decoder = new TextDecoder();
32
- return decoder.decode(buffer);
323
+ return new TextDecoder().decode(buffer);
33
324
  }
325
+ /**
326
+ * Creates an array of entities for parsing XML, including control characters.
327
+ * @returns An array of objects, each with an `entity` (e.g., "&#1;") and its `value` (e.g., "\x01").
328
+ */
34
329
  function makeParseEntities() {
35
- const entities2 = [];
36
- for (let i = 1; i <= 32; i++) {
37
- entities2.push({ entity: `&#${i};`, value: String.fromCharCode(i) });
38
- }
39
- return entities2;
40
- }
41
- function makeWriterEntities() {
42
- const entities2 = [];
43
- for (let i = 1; i <= 32; i++) {
44
- entities2.push({ entity: `&#${i};`, value: String.fromCharCode(i) });
45
- }
46
- return entities2;
330
+ const entities$1 = [];
331
+ for (let i = 1; i <= 32; i++) entities$1.push({
332
+ entity: `&#${i};`,
333
+ value: String.fromCharCode(i)
334
+ });
335
+ return entities$1;
47
336
  }
337
+ /**
338
+ * Converts a Base64 string to a Uint8Array.
339
+ * @param base64String - The Base64 string to convert.
340
+ * @returns A Uint8Array.
341
+ */
48
342
  function base64ToUint8Array(base64String) {
49
- const binaryString = atob(base64String);
50
- const bytes = new Uint8Array(binaryString.length);
51
- for (let i = 0; i < binaryString.length; i++) {
52
- bytes[i] = binaryString.charCodeAt(i);
53
- }
54
- return bytes;
343
+ const binaryString = atob(base64String);
344
+ const bytes = new Uint8Array(binaryString.length);
345
+ for (let i = 0; i < binaryString.length; i++) bytes[i] = binaryString.charCodeAt(i);
346
+ return bytes;
55
347
  }
348
+ /**
349
+ * Converts a Uint8Array to a Base64 string.
350
+ * @param uint8Array - The Uint8Array to convert.
351
+ * @returns A Base64 string.
352
+ */
56
353
  function uint8ArrayToBase64(uint8Array) {
57
- let binaryString = "";
58
- for (let i = 0; i < uint8Array.length; i++) {
59
- binaryString += String.fromCharCode(uint8Array[i]);
60
- }
61
- return btoa(binaryString);
354
+ let binaryString = "";
355
+ for (let i = 0; i < uint8Array.length; i++) binaryString += String.fromCharCode(uint8Array[i]);
356
+ return btoa(binaryString);
62
357
  }
358
+ /**
359
+ * Converts a string representation of a date/time to a Date object.
360
+ * Supports "yyyyMMdd", "yyyyMMddHHmmss", "yyyyMMddHHmmssSSS", and "HHmmss" formats.
361
+ * @param value - The string to convert.
362
+ * @returns A Date object if the string is a valid date/time, otherwise undefined.
363
+ */
63
364
  function stringToDate(value) {
64
- if (!value) return void 0;
65
- let year;
66
- let month;
67
- let day;
68
- let hours = 0;
69
- let minutes = 0;
70
- let seconds = 0;
71
- let milliseconds = 0;
72
- if (value.length < 6 || value.length > 16) {
73
- return void 0;
74
- }
75
- if (value.length >= 8) {
76
- year = parseInt(value.substring(0, 4), 10);
77
- month = parseInt(value.substring(4, 6), 10) - 1;
78
- day = parseInt(value.substring(6, 8), 10);
79
- } else {
80
- year = 1970;
81
- month = 0;
82
- day = 1;
83
- }
84
- if (value.length === 6) {
85
- hours = parseInt(value.substring(0, 2), 10);
86
- minutes = parseInt(value.substring(2, 4), 10);
87
- seconds = parseInt(value.substring(4, 6), 10);
88
- } else if (value.length >= 10) {
89
- hours = parseInt(value.substring(8, 10), 10);
90
- minutes = parseInt(value.substring(10, 12), 10);
91
- seconds = parseInt(value.substring(12, 14), 10);
92
- }
93
- if (value.length === 16) {
94
- milliseconds = parseInt(value.substring(14, 16), 10);
95
- }
96
- if (year < 1970 || year > 9999 || month < 0 || month > 11 || day < 1 || day > 31 || hours < 0 || hours > 23 || minutes < 0 || minutes > 59 || seconds < 0 || seconds > 59 || milliseconds < 0 || milliseconds > 999) {
97
- return void 0;
98
- }
99
- const date = new Date(year, month, day, hours, minutes, seconds, milliseconds);
100
- if (isNaN(date.getTime())) {
101
- return void 0;
102
- }
103
- return date;
365
+ if (!value) return void 0;
366
+ let year;
367
+ let month;
368
+ let day;
369
+ let hours = 0;
370
+ let minutes = 0;
371
+ let seconds = 0;
372
+ let milliseconds = 0;
373
+ if (value.length < 6 || value.length > 16) return;
374
+ if (value.length >= 8) {
375
+ year = parseInt(value.substring(0, 4), 10);
376
+ month = parseInt(value.substring(4, 6), 10) - 1;
377
+ day = parseInt(value.substring(6, 8), 10);
378
+ } else {
379
+ year = 1970;
380
+ month = 0;
381
+ day = 1;
382
+ }
383
+ if (value.length === 6) {
384
+ hours = parseInt(value.substring(0, 2), 10);
385
+ minutes = parseInt(value.substring(2, 4), 10);
386
+ seconds = parseInt(value.substring(4, 6), 10);
387
+ } else if (value.length >= 10) {
388
+ hours = parseInt(value.substring(8, 10), 10);
389
+ minutes = parseInt(value.substring(10, 12), 10);
390
+ seconds = parseInt(value.substring(12, 14), 10);
391
+ }
392
+ if (value.length === 16) milliseconds = parseInt(value.substring(14, 16), 10);
393
+ if (year < 1970 || year > 9999 || month < 0 || month > 11 || day < 1 || day > 31 || hours < 0 || hours > 23 || minutes < 0 || minutes > 59 || seconds < 0 || seconds > 59 || milliseconds < 0 || milliseconds > 999) return;
394
+ const date = new Date(year, month, day, hours, minutes, seconds, milliseconds);
395
+ if (isNaN(date.getTime())) return;
396
+ return date;
104
397
  }
398
+ /**
399
+ * Converts a Date object to a string representation based on the specified column type.
400
+ * @param date - The Date object to convert.
401
+ * @param type - The column type ("DATE", "DATETIME", or "TIME").
402
+ * @returns A string representation of the date/time.
403
+ */
105
404
  function dateToString(date, type) {
106
- const year = date.getFullYear().toString().padStart(4, "0");
107
- const month = (date.getMonth() + 1).toString().padStart(2, "0");
108
- const day = date.getDate().toString().padStart(2, "0");
109
- const hours = date.getHours().toString().padStart(2, "0");
110
- const minutes = date.getMinutes().toString().padStart(2, "0");
111
- const seconds = date.getSeconds().toString().padStart(2, "0");
112
- switch (type) {
113
- case "DATE":
114
- return `${year}${month}${day}`;
115
- case "DATETIME":
116
- return `${year}${month}${day}${hours}${minutes}${seconds}`;
117
- case "TIME":
118
- return `${hours}${minutes}${seconds}`;
119
- default:
120
- return "";
121
- }
405
+ const year = date.getFullYear().toString().padStart(4, "0");
406
+ const month = (date.getMonth() + 1).toString().padStart(2, "0");
407
+ const day = date.getDate().toString().padStart(2, "0");
408
+ const hours = date.getHours().toString().padStart(2, "0");
409
+ const minutes = date.getMinutes().toString().padStart(2, "0");
410
+ const seconds = date.getSeconds().toString().padStart(2, "0");
411
+ switch (type) {
412
+ case "DATE": return `${year}${month}${day}`;
413
+ case "DATETIME": return `${year}${month}${day}${hours}${minutes}${seconds}`;
414
+ case "TIME": return `${hours}${minutes}${seconds}`;
415
+ default: return "";
416
+ }
122
417
  }
418
+ /**
419
+ * A WritableStream that collects all written Uint8Array chunks and provides them as a single string.
420
+ */
123
421
  var StringWritableStream = class extends WritableStream {
124
- result = "";
125
- constructor() {
126
- const decoder = new TextDecoder();
127
- super({
128
- write: (chunk) => {
129
- this.result += decoder.decode(chunk, { stream: true });
130
- },
131
- close: () => {
132
- this.result += decoder.decode();
133
- }
134
- });
135
- }
136
- /**
137
- * Returns the collected string result.
138
- * @returns The concatenated string from all written chunks.
139
- */
140
- getResult() {
141
- return this.result;
142
- }
422
+ result = "";
423
+ constructor() {
424
+ const decoder = new TextDecoder();
425
+ super({
426
+ write: (chunk) => {
427
+ this.result += decoder.decode(chunk, { stream: true });
428
+ },
429
+ close: () => {
430
+ this.result += decoder.decode();
431
+ }
432
+ });
433
+ }
434
+ /**
435
+ * Returns the collected string result.
436
+ * @returns The concatenated string from all written chunks.
437
+ */
438
+ getResult() {
439
+ return this.result;
440
+ }
143
441
  };
442
+ /**
443
+ * Converts a string to a ReadableStream of Uint8Array.
444
+ * @param str - The string to convert.
445
+ * @returns A ReadableStream containing the string as Uint8Array.
446
+ */
144
447
  function stringToReadableStream(str) {
145
- const encoder = new TextEncoder();
146
- const bytes = encoder.encode(str);
147
- return new ReadableStream({
148
- start(controller) {
149
- controller.enqueue(bytes);
150
- controller.close();
151
- }
152
- });
448
+ const bytes = new TextEncoder().encode(str);
449
+ return new ReadableStream({ start(controller) {
450
+ controller.enqueue(bytes);
451
+ controller.close();
452
+ } });
153
453
  }
454
+ /**
455
+ * Converts a value to the specified ColumnType.
456
+ * @param value - The value to convert.
457
+ * @param type - The target ColumnType.
458
+ * @returns The converted value, or the original value if conversion fails or is not applicable.
459
+ * @throws {ColumnTypeError} if the column type is unsupported.
460
+ */
154
461
  function convertToColumnType(value, type) {
155
- switch (type) {
156
- case "INT":
157
- case "BIGDECIMAL":
158
- const intValue = parseInt(value, 10);
159
- return isNaN(intValue) ? value : intValue;
160
- case "FLOAT":
161
- const floatValue = parseFloat(value);
162
- return isNaN(floatValue) ? value : floatValue;
163
- case "DECIMAL":
164
- const decimalValue = parseFloat(value);
165
- return isNaN(decimalValue) ? value : decimalValue;
166
- case "DATE":
167
- case "DATETIME":
168
- case "TIME":
169
- return stringToDate(value) || value;
170
- case "BLOB":
171
- try {
172
- return base64ToUint8Array(value);
173
- } catch {
174
- return value;
175
- }
176
- case "STRING":
177
- return value;
178
- default:
179
- throw new ColumnTypeError(`Unsupported column type: ${type}`);
180
- }
462
+ switch (type) {
463
+ case "INT":
464
+ case "BIGDECIMAL":
465
+ const intValue = parseInt(value, 10);
466
+ return isNaN(intValue) ? value : intValue;
467
+ case "FLOAT":
468
+ const floatValue = parseFloat(value);
469
+ return isNaN(floatValue) ? value : floatValue;
470
+ case "DECIMAL":
471
+ const decimalValue = parseFloat(value);
472
+ return isNaN(decimalValue) ? value : decimalValue;
473
+ case "DATE":
474
+ case "DATETIME":
475
+ case "TIME": return stringToDate(value) || value;
476
+ case "BLOB": try {
477
+ return base64ToUint8Array(value);
478
+ } catch {
479
+ return value;
480
+ }
481
+ case "STRING": return value;
482
+ default: throw new ColumnTypeError(`Unsupported column type: ${type}`);
483
+ }
181
484
  }
485
+ /**
486
+ * Converts an XapiValueType to its string representation based on the specified ColumnType.
487
+ * @param value - The value to convert.
488
+ * @param type - The ColumnType to guide the conversion.
489
+ * @returns The string representation of the value.
490
+ */
182
491
  function convertToString(value, type) {
183
- switch (type) {
184
- case "INT":
185
- case "BIGDECIMAL":
186
- case "FLOAT":
187
- case "DECIMAL":
188
- return String(value);
189
- case "DATE":
190
- case "DATETIME":
191
- case "TIME":
192
- return dateToString(value, type);
193
- case "BLOB":
194
- return uint8ArrayToBase64(value);
195
- case "STRING":
196
- return String(value);
197
- default:
198
- return String(value);
199
- }
492
+ switch (type) {
493
+ case "INT":
494
+ case "BIGDECIMAL":
495
+ case "FLOAT":
496
+ case "DECIMAL": return String(value);
497
+ case "DATE":
498
+ case "DATETIME":
499
+ case "TIME": return dateToString(value, type);
500
+ case "BLOB": return uint8ArrayToBase64(value);
501
+ case "STRING": return String(value);
502
+ default: return String(value);
503
+ }
200
504
  }
201
- var entities = makeParseEntities();
505
+ const entities = makeParseEntities();
202
506
  function _unescapeXml(str) {
203
- if (!str) return str;
204
- const regex = new RegExp(entities.map((e) => e.entity).join("|"), "g");
205
- return str.replace(regex, (match) => {
206
- const entity = entities.find((e) => e.entity === match);
207
- return entity ? entity.value : match;
208
- });
507
+ if (!str) return str;
508
+ let result = str.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&apos;/g, "'").replace(/&amp;/g, "&");
509
+ const regex = new RegExp(entities.map((e) => e.entity).join("|"), "g");
510
+ result = result.replace(regex, (match) => {
511
+ const entity = entities.find((e) => e.entity === match);
512
+ return entity ? entity.value : match;
513
+ });
514
+ return result;
209
515
  }
210
-
211
- // src/xapi-data.ts
212
- var XapiRoot = class {
213
- /** An array of datasets within the X-API root. */
214
- datasets = [];
215
- /** Parameters associated with the X-API root. */
216
- parameters = { params: [] };
217
- /**
218
- * Creates an instance of XapiRoot.
219
- * @param datasets - Initial array of datasets.
220
- * @param parameters - Initial parameters.
221
- */
222
- constructor(datasets = [], parameters = { params: [] }) {
223
- this.datasets = datasets;
224
- this.parameters = parameters;
225
- }
226
- /**
227
- * Adds a dataset to the X-API root.
228
- * @param dataset - The dataset to add.
229
- */
230
- addDataset(dataset) {
231
- this.datasets.push(dataset);
232
- }
233
- /**
234
- * Retrieves a dataset by its ID.
235
- * @param id - The ID of the dataset to retrieve.
236
- * @returns The Dataset object, or undefined if not found.
237
- */
238
- getDataset(id) {
239
- return this.datasets.find((dataset) => dataset.id === id);
240
- }
241
- /**
242
- * Adds a parameter to the X-API root.
243
- * @param parameter - The parameter to add.
244
- */
245
- addParameter(parameter) {
246
- this.parameters.params.push(parameter);
247
- }
248
- /**
249
- * Retrieves a parameter by its ID.
250
- * @param id - The ID of the parameter to retrieve.
251
- * @returns The Parameter object, or undefined if not found.
252
- */
253
- getParameter(id) {
254
- return this.parameters.params.find((param) => param.id === id);
255
- }
256
- /**
257
- * Sets all parameters for the X-API root.
258
- * @param parameters - The XapiParameters object to set.
259
- */
260
- setParameters(parameters) {
261
- this.parameters = parameters;
262
- }
263
- /**
264
- * Sets the value of a specific parameter, or adds it if it doesn't exist.
265
- * @param id - The ID of the parameter.
266
- * @param value - The value to set for the parameter.
267
- */
268
- setParameter(id, value) {
269
- const param = this.parameters.params.find((p) => p.id === id);
270
- if (param) {
271
- param.value = value;
272
- } else {
273
- this.addParameter({ id, value });
274
- }
275
- }
276
- /**
277
- * Returns the number of parameters.
278
- * @returns The count of parameters.
279
- */
280
- parameterSize() {
281
- return this.parameters.params.length;
282
- }
283
- /**
284
- * Returns the number of datasets.
285
- * @returns The count of datasets.
286
- */
287
- datasetSize() {
288
- return this.datasets.length;
289
- }
290
- /**
291
- * Iterates over the parameters.
292
- * @returns An IterableIterator for parameters.
293
- */
294
- *iterParameters() {
295
- for (const param of this.parameters.params) {
296
- yield param;
297
- }
298
- }
299
- /**
300
- * Iterates over the datasets.
301
- * @returns An IterableIterator for datasets.
302
- */
303
- *iterDatasets() {
304
- for (const dataset of this.datasets) {
305
- yield dataset;
306
- }
307
- }
516
+ function isXapiRoot(value) {
517
+ return value instanceof XapiRoot;
518
+ }
519
+ /**
520
+ * Escapes XML special characters in a string.
521
+ * @param str - The string to escape.
522
+ * @returns The escaped string.
523
+ */
524
+ function escapeXml(str) {
525
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
526
+ }
527
+ /**
528
+ * Encodes control characters as XML entities, excluding standard whitespace.
529
+ * Encodes 0x01-0x08, 0x0B-0x0C, 0x0E-0x1F but NOT 0x09 (tab), 0x0A (LF), 0x0D (CR), 0x20 (space).
530
+ * @param str - The string to encode.
531
+ * @returns The encoded string.
532
+ */
533
+ function encodeControlChars(str) {
534
+ let result = "";
535
+ for (let i = 0; i < str.length; i++) {
536
+ const charCode = str.charCodeAt(i);
537
+ if (charCode >= 1 && charCode <= 8 || charCode >= 11 && charCode <= 12 || charCode >= 14 && charCode <= 31) result += `&#${charCode};`;
538
+ else result += str[i];
539
+ }
540
+ return result;
541
+ }
542
+ /**
543
+ * A string builder for generating formatted XML.
544
+ */
545
+ var XmlStringBuilder = class {
546
+ lines = [];
547
+ indentLevel = 0;
548
+ indentString = " ";
549
+ /**
550
+ * Writes the XML declaration.
551
+ * @param version - The XML version (default: "1.0").
552
+ * @param encoding - The encoding (default: "UTF-8").
553
+ */
554
+ writeDeclaration(version = "1.0", encoding = "UTF-8") {
555
+ this.lines.push(`<?xml version="${version}" encoding="${encoding}"?>`);
556
+ }
557
+ /**
558
+ * Writes a start element tag.
559
+ * @param name - The element name.
560
+ * @param attributes - Optional attributes object.
561
+ * @param selfClosing - Whether to create a self-closing tag.
562
+ */
563
+ writeStartElement(name, attributes, selfClosing) {
564
+ let tag = `${this.indentString.repeat(this.indentLevel)}<${name}`;
565
+ if (attributes) for (const [key, value] of Object.entries(attributes)) {
566
+ const encodedValue = encodeControlChars(escapeXml(value));
567
+ tag += ` ${key}="${encodedValue}"`;
568
+ }
569
+ if (selfClosing) {
570
+ tag += "/>";
571
+ this.lines.push(tag);
572
+ } else {
573
+ tag += ">";
574
+ this.lines.push(tag);
575
+ this.indentLevel++;
576
+ }
577
+ }
578
+ /**
579
+ * Writes an end element tag.
580
+ * @param name - The element name.
581
+ */
582
+ writeEndElement(name) {
583
+ this.indentLevel--;
584
+ const indent = this.indentString.repeat(this.indentLevel);
585
+ this.lines.push(`${indent}</${name}>`);
586
+ }
587
+ /**
588
+ * Writes an element with text content.
589
+ * @param name - The element name.
590
+ * @param attributes - Optional attributes object.
591
+ * @param text - The text content.
592
+ */
593
+ writeElementWithText(name, attributes, text) {
594
+ let tag = `${this.indentString.repeat(this.indentLevel)}<${name}`;
595
+ if (attributes) for (const [key, value] of Object.entries(attributes)) {
596
+ const encodedValue = encodeControlChars(escapeXml(value));
597
+ tag += ` ${key}="${encodedValue}"`;
598
+ }
599
+ const encodedText = encodeControlChars(escapeXml(text));
600
+ tag += `>${encodedText}</${name}>`;
601
+ this.lines.push(tag);
602
+ }
603
+ /**
604
+ * Returns the generated XML string.
605
+ * @returns The complete XML string with line breaks.
606
+ */
607
+ toString() {
608
+ return this.lines.join("\n") + "\n";
609
+ }
308
610
  };
309
- var Dataset = class {
310
- /** The ID of the dataset. */
311
- id;
312
- constColumns = [];
313
- columns = [];
314
- /** An array of rows in the dataset. */
315
- rows = [];
316
- _columnIndexMap = /* @__PURE__ */ new Map();
317
- /**
318
- * Creates an instance of Dataset.
319
- * @param id - The ID of the dataset.
320
- * @param constColumns - Initial array of constant columns.
321
- * @param columns - Initial array of columns.
322
- * @param rows - Initial array of rows.
323
- */
324
- constructor(id, constColumns = [], columns = [], rows = []) {
325
- this.id = id;
326
- this.constColumns = constColumns;
327
- this.columns = columns;
328
- this.rows = rows;
329
- }
330
- /**
331
- * Adds a column definition to the dataset.
332
- * @param column - The column definition to add.
333
- */
334
- addColumn(column) {
335
- this.columns.push(column);
336
- this._columnIndexMap.set(column.id, this.columns.length - 1);
337
- }
338
- /**
339
- * Adds a constant column definition to the dataset.
340
- * @param column - The constant column definition to add.
341
- */
342
- addConstColumn(column) {
343
- this.constColumns.push(column);
344
- }
345
- /**
346
- * Creates a new empty row and adds it to the dataset.
347
- * @returns The index of the newly created row.
348
- */
349
- newRow() {
350
- this.rows.push({ cols: [] });
351
- return this.rows.length - 1;
352
- }
353
- /**
354
- * Adds an existing row to the dataset.
355
- * @param row - The row to add.
356
- */
357
- addRow(row) {
358
- this.rows.push(row);
359
- }
360
- /**
361
- * Retrieves the index of a column by its ID.
362
- * @param columnId - The ID of the column.
363
- * @returns The index of the column, or undefined if not found.
364
- */
365
- getColumnIndex(columnId) {
366
- return this._columnIndexMap.get(columnId);
367
- }
368
- /**
369
- * Retrieves the column definition by its ID.
370
- * @param columnId - The ID of the column.
371
- * @returns The Column object, or undefined if not found.
372
- */
373
- getColumnInfo(columnId) {
374
- const colIndex = this.getColumnIndex(columnId);
375
- if (colIndex !== void 0) {
376
- return this.columns[colIndex];
377
- }
378
- return void 0;
379
- }
380
- /**
381
- * Retrieves the constant column definition by its ID.
382
- * @param columnId - The ID of the constant column.
383
- * @returns The ConstColumn object, or undefined if not found.
384
- */
385
- getConstColumnInfo(columnId) {
386
- return this.constColumns.find((col) => col.id === columnId);
387
- }
388
- /**
389
- * Retrieves the value of a column in a specific row.
390
- * @param rowIdx - The index of the row.
391
- * @param columnId - The ID of the column.
392
- * @returns The value of the column, or undefined if the row or column is not found.
393
- * @throws {Error} if the column ID is not found in the dataset.
394
- */
395
- getColumn(rowIdx, columnId) {
396
- if (rowIdx < this.rows.length) {
397
- const colIndex = this.getColumnIndex(columnId);
398
- if (colIndex === void 0) {
399
- throw new Error(`Column with id ${columnId} not found in dataset ${this.id}`);
400
- }
401
- const col = this.rows[rowIdx].cols[colIndex];
402
- return col?.value;
403
- }
404
- return void 0;
405
- }
406
- /**
407
- * Retrieves the original value of a column in a specific row (for OrgRow).
408
- * @param rowIdx - The index of the row.
409
- * @param columnId - The ID of the column.
410
- * @returns The original value of the column, or undefined if the row or column is not found.
411
- * @throws {Error} if the column ID is not found in the dataset.
412
- */
413
- getOrgColumn(rowIdx, columnId) {
414
- if (rowIdx < this.rows.length) {
415
- const colIndex = this.getColumnIndex(columnId);
416
- if (colIndex === void 0) {
417
- throw new Error(`Column with id ${columnId} not found in dataset ${this.id}`);
418
- }
419
- const col = this.rows[rowIdx].orgRow?.[colIndex];
420
- return col?.value;
421
- }
422
- return void 0;
423
- }
424
- /**
425
- * Sets the value of a column in a specific row.
426
- * @param rowIdx - The index of the row.
427
- * @param columnId - The ID of the column.
428
- * @param value - The value to set.
429
- * @throws {Error} if the row index is out of bounds or the column ID is not found.
430
- */
431
- setColumn(rowIdx, columnId, value) {
432
- if (rowIdx < this.rows.length) {
433
- const colIndex = this.getColumnIndex(columnId);
434
- if (colIndex === void 0) {
435
- throw new Error(`Column with id ${columnId} not found in dataset ${this.id}`);
436
- }
437
- this.rows[rowIdx].cols[colIndex] = { id: columnId, value };
438
- } else {
439
- throw new Error(`Row index ${rowIdx} out of bounds in dataset ${this.id}`);
440
- }
441
- }
442
- /**
443
- * Iterates over the constant column definitions.
444
- * @returns An IterableIterator for constant columns.
445
- */
446
- *iterConstColumns() {
447
- for (const column of this.constColumns) {
448
- yield column;
449
- }
450
- }
451
- /**
452
- * Iterates over the column definitions.
453
- * @returns An IterableIterator for columns.
454
- */
455
- *iterColumns() {
456
- for (const column of this.columns) {
457
- yield column;
458
- }
459
- }
460
- /**
461
- * Iterates over the rows in the dataset.
462
- * @returns An IterableIterator for rows.
463
- */
464
- *iterRows() {
465
- for (const row of this.rows) {
466
- yield row;
467
- }
468
- }
469
- /**
470
- * Returns the number of column definitions.
471
- * @returns The count of columns.
472
- */
473
- columnSize() {
474
- return this.columns.length;
475
- }
476
- /**
477
- * Returns the number of constant column definitions.
478
- * @returns The count of constant columns.
479
- */
480
- constColumnSize() {
481
- return this.constColumns.length;
482
- }
483
- /**
484
- * Returns the number of rows in the dataset.
485
- * @returns The count of rows.
486
- */
487
- rowSize() {
488
- return this.rows.length;
489
- }
611
+ /**
612
+ * Parses XML string into an XML node structure.
613
+ * This is a lightweight parser optimized for X-API XML structure.
614
+ *
615
+ * @param xml - The XML string to parse.
616
+ * @returns An array of parsed XML nodes.
617
+ */
618
+ function parseXml(xml) {
619
+ if (!xml || xml.trim() === "") return [];
620
+ return new XapiXmlParser(xml).parse();
621
+ }
622
+ /**
623
+ * A lightweight XML parser optimized for X-API structure.
624
+ */
625
+ var XapiXmlParser = class {
626
+ xml;
627
+ pos = 0;
628
+ length;
629
+ constructor(xml) {
630
+ this.xml = xml;
631
+ this.length = xml.length;
632
+ }
633
+ parse() {
634
+ const nodes = [];
635
+ while (this.pos < this.length) {
636
+ this.skipWhitespace();
637
+ if (this.pos >= this.length) break;
638
+ if (this.peek(5) === "<?xml") {
639
+ this.skipUntil("?>");
640
+ this.pos += 2;
641
+ continue;
642
+ }
643
+ if (this.peek(4) === "<!--") {
644
+ this.skipUntil("-->");
645
+ this.pos += 3;
646
+ continue;
647
+ }
648
+ if (this.current() === "<") {
649
+ const node = this.parseElement();
650
+ if (node) nodes.push(node);
651
+ } else this.pos++;
652
+ }
653
+ return nodes;
654
+ }
655
+ parseElement() {
656
+ if (this.current() !== "<") return null;
657
+ this.pos++;
658
+ if (this.current() === "/") return null;
659
+ const tagName = this.parseTagName();
660
+ if (!tagName) return null;
661
+ const node = { tagName };
662
+ const attributes = this.parseAttributes();
663
+ if (attributes && Object.keys(attributes).length > 0) node.attributes = attributes;
664
+ this.skipWhitespace();
665
+ if (this.peek(2) === "/>") {
666
+ this.pos += 2;
667
+ return node;
668
+ }
669
+ if (this.current() === ">") this.pos++;
670
+ const children = [];
671
+ let textContent = "";
672
+ while (this.pos < this.length) {
673
+ if (this.peek(9) === "<![CDATA[") {
674
+ const cdataText = this.parseCDATA();
675
+ if (cdataText !== null) textContent += cdataText;
676
+ continue;
677
+ }
678
+ if (this.peek(2) === "</") {
679
+ if (textContent) children.push(textContent);
680
+ this.pos += 2;
681
+ this.skipUntil(">");
682
+ this.pos++;
683
+ break;
684
+ }
685
+ if (this.current() === "<") {
686
+ if (textContent.trim()) {
687
+ children.push(textContent);
688
+ textContent = "";
689
+ }
690
+ const child = this.parseElement();
691
+ if (child) children.push(child);
692
+ } else {
693
+ textContent += this.current();
694
+ this.pos++;
695
+ }
696
+ }
697
+ if (children.length > 0) node.children = children;
698
+ return node;
699
+ }
700
+ parseTagName() {
701
+ let name = "";
702
+ while (this.pos < this.length) {
703
+ const ch = this.current();
704
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === ">" || ch === "/") break;
705
+ name += ch;
706
+ this.pos++;
707
+ }
708
+ return name;
709
+ }
710
+ parseAttributes() {
711
+ const attrs = {};
712
+ while (this.pos < this.length) {
713
+ this.skipWhitespace();
714
+ const ch = this.current();
715
+ if (ch === ">" || ch === "/" || this.peek(2) === "/>") break;
716
+ const attrName = this.parseAttributeName();
717
+ if (!attrName) break;
718
+ this.skipWhitespace();
719
+ if (this.current() === "=") this.pos++;
720
+ this.skipWhitespace();
721
+ attrs[attrName] = this.parseAttributeValue();
722
+ }
723
+ return Object.keys(attrs).length > 0 ? attrs : void 0;
724
+ }
725
+ parseAttributeName() {
726
+ let name = "";
727
+ while (this.pos < this.length) {
728
+ const ch = this.current();
729
+ if (ch === "=" || ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === ">" || ch === "/") break;
730
+ name += ch;
731
+ this.pos++;
732
+ }
733
+ return name;
734
+ }
735
+ parseAttributeValue() {
736
+ let value = "";
737
+ const quote = this.current();
738
+ if (quote !== "\"" && quote !== "'") {
739
+ while (this.pos < this.length) {
740
+ const ch = this.current();
741
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === ">" || ch === "/") break;
742
+ value += ch;
743
+ this.pos++;
744
+ }
745
+ return value;
746
+ }
747
+ this.pos++;
748
+ while (this.pos < this.length) {
749
+ const ch = this.current();
750
+ if (ch === quote) {
751
+ this.pos++;
752
+ break;
753
+ }
754
+ value += ch;
755
+ this.pos++;
756
+ }
757
+ return value;
758
+ }
759
+ parseCDATA() {
760
+ if (this.peek(9) !== "<![CDATA[") return null;
761
+ this.pos += 9;
762
+ let content = "";
763
+ while (this.pos < this.length) {
764
+ if (this.peek(3) === "]]>") {
765
+ this.pos += 3;
766
+ break;
767
+ }
768
+ content += this.current();
769
+ this.pos++;
770
+ }
771
+ return content;
772
+ }
773
+ skipWhitespace() {
774
+ while (this.pos < this.length) {
775
+ const ch = this.current();
776
+ if (ch !== " " && ch !== " " && ch !== "\n" && ch !== "\r") break;
777
+ this.pos++;
778
+ }
779
+ }
780
+ skipUntil(target) {
781
+ while (this.pos < this.length) {
782
+ if (this.peek(target.length) === target) break;
783
+ this.pos++;
784
+ }
785
+ }
786
+ current() {
787
+ return this.xml[this.pos];
788
+ }
789
+ peek(length) {
790
+ return this.xml.substring(this.pos, this.pos + length);
791
+ }
490
792
  };
491
793
 
492
- // src/handler.ts
493
- var defaultOptions = {
494
- xapiVersion: NexaVersion,
495
- parseToTypes: true
496
- };
497
- var _options = {
498
- ...defaultOptions
794
+ //#endregion
795
+ //#region src/handler.ts
796
+ let _options = {
797
+ xapiVersion: NexaVersion,
798
+ parseToTypes: true
499
799
  };
800
+ /**
801
+ * Initializes the X-API handler with the provided options.
802
+ * @param options - The options to initialize the X-API handler.
803
+ * @returns void
804
+ */
500
805
  function initXapi(options) {
501
- _options = {
502
- ...options
503
- };
806
+ _options = { ...options };
504
807
  }
505
- function parse2(xml) {
506
- const parsedXml = txml.parse(xml);
507
- const xapiRoot = new XapiRoot();
508
- const rootElement = parsedXml.find((node) => {
509
- const rootNode = node;
510
- return rootNode.tagName === "Root";
511
- });
512
- if (rootElement === void 0) return xapiRoot;
513
- const parametersElement = rootElement.children?.find((node) => node.tagName === "Parameters");
514
- parseParameters(parametersElement, xapiRoot);
515
- const datasetsElements = rootElement.children?.filter((node) => node.tagName === "Dataset");
516
- if (datasetsElements && datasetsElements?.length && datasetsElements.length > 0) {
517
- for (const datasetsElement of datasetsElements) {
518
- if (!datasetsElement.attributes || !datasetsElement.attributes.id) {
519
- throw new InvalidXmlError("Dataset element must have an 'id' attribute");
520
- }
521
- const datasetId = datasetsElement.attributes?.id;
522
- const dataset = new Dataset(datasetId);
523
- xapiRoot.addDataset(dataset);
524
- const columnInfoElement = datasetsElement.children?.find((node) => node.tagName === "ColumnInfo");
525
- parseColumnInfo(columnInfoElement, dataset);
526
- const rowsElement = datasetsElement.children?.find((node) => node.tagName === "Rows");
527
- parseRows(rowsElement, dataset);
528
- }
529
- }
530
- return xapiRoot;
808
+ /**
809
+ * Parses an XML string into an XapiRoot object using custom parser.
810
+ * @param xml - The string containing the XML data.
811
+ * @returns An XapiRoot object.
812
+ */
813
+ function parse(xml) {
814
+ const parsedXml = parseXml(xml);
815
+ const xapiRoot = new XapiRoot();
816
+ let rootElement;
817
+ for (let i = 0; i < parsedXml.length; i++) if (parsedXml[i].tagName === "Root") {
818
+ rootElement = parsedXml[i];
819
+ break;
820
+ }
821
+ if (rootElement === void 0) return xapiRoot;
822
+ const rootChildren = rootElement.children;
823
+ if (rootChildren && rootChildren.length > 0) for (let i = 0; i < rootChildren.length; i++) {
824
+ const child = rootChildren[i];
825
+ if (typeof child === "string") continue;
826
+ const tagName = child.tagName;
827
+ if (tagName === "Parameters") parseParameters(child, xapiRoot);
828
+ else if (tagName === "Dataset") {
829
+ if (!child.attributes || !child.attributes.id) throw new InvalidXmlError("Dataset element must have an 'id' attribute");
830
+ const datasetId = child.attributes.id;
831
+ const dataset = new Dataset(datasetId);
832
+ xapiRoot.addDataset(dataset);
833
+ const datasetChildren = child.children;
834
+ let columnInfoElement;
835
+ let rowsElement;
836
+ if (datasetChildren) for (let j = 0; j < datasetChildren.length; j++) {
837
+ const datasetChild = datasetChildren[j];
838
+ if (typeof datasetChild === "string") continue;
839
+ const childTagName = datasetChild.tagName;
840
+ if (childTagName === "ColumnInfo") columnInfoElement = datasetChild;
841
+ else if (childTagName === "Rows") rowsElement = datasetChild;
842
+ if (columnInfoElement && rowsElement) break;
843
+ }
844
+ parseColumnInfo(columnInfoElement, dataset);
845
+ parseRows(rowsElement, dataset);
846
+ }
847
+ }
848
+ return xapiRoot;
531
849
  }
532
850
  function parseValue(value, type = "STRING") {
533
- value = _unescapeXml(value);
534
- return _options.parseToTypes ? convertToColumnType(value, type) : value;
851
+ value = _unescapeXml(value);
852
+ return _options.parseToTypes ? convertToColumnType(value, type) : value;
535
853
  }
536
854
  function parseColumnInfo(columnInfoElement, dataset) {
537
- if (!columnInfoElement) throw new InvalidXmlError("ColumnInfo element is missing in the dataset");
538
- columnInfoElement.children?.forEach((colInfo) => {
539
- if (colInfo.tagName === "ConstColumn") {
540
- dataset.addConstColumn({
541
- id: colInfo.attributes?.id,
542
- size: parseInt(colInfo.attributes?.size || "0", 10),
543
- type: colInfo.attributes?.type || "STRING",
544
- value: parseValue(colInfo.attributes?.value, colInfo.attributes?.type)
545
- });
546
- } else if (colInfo.tagName === "Column") {
547
- dataset.addColumn({
548
- id: colInfo.attributes?.id,
549
- size: parseInt(colInfo.attributes?.size || "0", 10),
550
- type: colInfo.attributes?.type || "STRING"
551
- });
552
- }
553
- });
855
+ if (!columnInfoElement || typeof columnInfoElement === "string") throw new InvalidXmlError("ColumnInfo element is missing in the dataset");
856
+ const children = columnInfoElement.children;
857
+ if (!children) return;
858
+ for (let i = 0; i < children.length; i++) {
859
+ const colInfo = children[i];
860
+ if (typeof colInfo !== "string") {
861
+ const tagName = colInfo.tagName;
862
+ if (tagName === "ConstColumn") {
863
+ const attrs = colInfo.attributes;
864
+ const sizeStr = attrs?.size;
865
+ dataset.addConstColumn({
866
+ id: attrs?.id,
867
+ size: sizeStr ? parseInt(sizeStr, 10) : 0,
868
+ type: attrs?.type || "STRING",
869
+ value: parseValue(attrs?.value, attrs?.type)
870
+ });
871
+ } else if (tagName === "Column") {
872
+ const attrs = colInfo.attributes;
873
+ const sizeStr = attrs?.size;
874
+ dataset.addColumn({
875
+ id: attrs?.id,
876
+ size: sizeStr ? parseInt(sizeStr, 10) : 0,
877
+ type: attrs?.type || "STRING"
878
+ });
879
+ }
880
+ }
881
+ }
554
882
  }
555
883
  function parseRows(rowsElement, dataset) {
556
- rowsElement?.children?.forEach((r) => {
557
- if (r.tagName === "Row") {
558
- const rowIndex = dataset.newRow();
559
- dataset.rows[rowIndex].type = r.attributes?.type || void 0;
560
- r.children?.forEach((col) => {
561
- if (col.tagName === "Col") {
562
- const colId = col.attributes?.id;
563
- const value = col.children?.[0];
564
- const columnInfo = dataset.getColumnInfo(colId);
565
- if (!columnInfo) throw new InvalidXmlError(`Column with id ${colId} not found in dataset ${dataset.id}`);
566
- const castedValue = parseValue(value, columnInfo.type);
567
- dataset.rows[rowIndex].cols.push({ id: colId, value: castedValue });
568
- } else if (col.tagName === "OrgRow") {
569
- dataset.rows[rowIndex].orgRow = [];
570
- col.children?.forEach((orgCol) => {
571
- if (orgCol.tagName === "Col") {
572
- const colId = orgCol.attributes?.id;
573
- const value = orgCol.children?.[0];
574
- const columnInfo = dataset.getColumnInfo(colId);
575
- const castedValue = parseValue(value, columnInfo.type);
576
- if (dataset && dataset.rows && dataset.rows[rowIndex] && dataset.rows[rowIndex].orgRow) {
577
- dataset.rows[rowIndex].orgRow.push({ id: colId, value: castedValue });
578
- }
579
- }
580
- });
581
- }
582
- });
583
- } else if (r.tagName === "Col") {
584
- throw new InvalidXmlError("Row must be defined before Col");
585
- } else if (r.tagName === "OrgRow") {
586
- throw new InvalidXmlError("Row must be defined before OrgRow");
587
- }
588
- });
884
+ if (typeof rowsElement === "string") return;
885
+ const rows = rowsElement?.children;
886
+ if (!rows) return;
887
+ const datasetRows = dataset.rows;
888
+ for (let i = 0; i < rows.length; i++) {
889
+ const r = rows[i];
890
+ if (typeof r !== "string") {
891
+ const tagName = r.tagName;
892
+ if (tagName === "Row") {
893
+ const currentRow = datasetRows[dataset.newRow()];
894
+ currentRow.type = r.attributes?.type || void 0;
895
+ const cols = r.children;
896
+ if (cols) for (let j = 0; j < cols.length; j++) {
897
+ const col = cols[j];
898
+ if (typeof col !== "string") {
899
+ const colTagName = col.tagName;
900
+ if (colTagName === "Col") {
901
+ const colId = col.attributes?.id;
902
+ const value = col.children?.[0];
903
+ const columnInfo = dataset.getColumnInfo(colId);
904
+ if (!columnInfo) throw new InvalidXmlError(`Column with id ${colId} not found in dataset ${dataset.id}`);
905
+ const castedValue = parseValue(value, columnInfo.type);
906
+ currentRow.cols.push({
907
+ id: colId,
908
+ value: castedValue
909
+ });
910
+ } else if (colTagName === "OrgRow") {
911
+ const orgRow = [];
912
+ currentRow.orgRow = orgRow;
913
+ const orgCols = col.children;
914
+ if (orgCols) for (let k = 0; k < orgCols.length; k++) {
915
+ const orgCol = orgCols[k];
916
+ if (typeof orgCol !== "string" && orgCol.tagName === "Col") {
917
+ const colId = orgCol.attributes?.id;
918
+ const value = orgCol.children?.[0];
919
+ const castedValue = parseValue(value, dataset.getColumnInfo(colId).type);
920
+ orgRow.push({
921
+ id: colId,
922
+ value: castedValue
923
+ });
924
+ }
925
+ }
926
+ }
927
+ }
928
+ }
929
+ } else if (tagName === "Col") throw new InvalidXmlError("Row must be defined before Col");
930
+ else if (tagName === "OrgRow") throw new InvalidXmlError("Row must be defined before OrgRow");
931
+ }
932
+ }
589
933
  }
590
934
  function parseParameters(parametersElement, xapiRoot) {
591
- if (!parametersElement) return;
592
- parametersElement.children?.forEach((p) => {
593
- if (p.tagName === "Parameter") {
594
- const id = p.attributes?.id;
595
- const type = p.attributes?.type || "STRING";
596
- const value = p.children?.[0];
597
- xapiRoot.addParameter({
598
- id,
599
- type,
600
- value: parseValue(value, type)
601
- });
602
- }
603
- });
604
- }
605
- async function writeString(root) {
606
- const stringStream = new StringWritableStream();
607
- await write(stringStream, root);
608
- return stringStream.getResult();
935
+ if (typeof parametersElement === "string") return;
936
+ if (!parametersElement) return;
937
+ const children = parametersElement.children;
938
+ if (!children) return;
939
+ for (let i = 0; i < children.length; i++) {
940
+ const p = children[i];
941
+ if (typeof p !== "string" && p.tagName === "Parameter") {
942
+ const attrs = p.attributes;
943
+ const id = attrs?.id;
944
+ const type = attrs?.type || "STRING";
945
+ const value = p.children?.[0];
946
+ xapiRoot.addParameter({
947
+ id,
948
+ type,
949
+ value: parseValue(value, type)
950
+ });
951
+ }
952
+ }
609
953
  }
610
- async function write(stream, root) {
611
- const writer = new StaxXmlWriter(stream, {
612
- addEntities: makeWriterEntities(),
613
- encoding: "UTF-8",
614
- indentString: " ",
615
- prettyPrint: true
616
- });
617
- await writer.writeStartDocument("1.0", "UTF-8");
618
- await writer.writeStartElement("Root", {
619
- // Root
620
- attributes: {
621
- xmlns: _options.xapiVersion?.xmlns || NexaVersion.xmlns,
622
- version: _options.xapiVersion?.version || NexaVersion.version
623
- }
624
- });
625
- if (root.parameterSize() > 0) {
626
- await writeParameters(writer, root.iterParameters());
627
- }
628
- if (root.datasetSize() > 0) {
629
- await writer.writeStartElement("Datasets");
630
- for (const dataset of root.iterDatasets()) {
631
- await writeDataset(writer, dataset);
632
- }
633
- await writer.writeEndElement();
634
- }
635
- await writer.writeEndElement();
954
+ function write(root) {
955
+ const builder = new XmlStringBuilder();
956
+ builder.writeDeclaration("1.0", "UTF-8");
957
+ builder.writeStartElement("Root", {
958
+ xmlns: _options.xapiVersion?.xmlns || NexaVersion.xmlns,
959
+ version: _options.xapiVersion?.version || NexaVersion.version
960
+ });
961
+ if (root.parameterSize() > 0) writeParameters(builder, root.getParameters());
962
+ if (root.datasetSize() > 0) {
963
+ builder.writeStartElement("Datasets");
964
+ for (const dataset of root.getDatasets()) writeDataset(builder, dataset);
965
+ builder.writeEndElement("Datasets");
966
+ }
967
+ builder.writeEndElement("Root");
968
+ return builder.toString();
636
969
  }
637
- async function writeParameters(writer, iterator) {
638
- if (iterator) {
639
- await writer.writeStartElement("Parameters");
640
- for (const parameter of iterator) {
641
- await writer.writeStartElement("Parameter", { attributes: { id: parameter.id } });
642
- if (parameter.type !== void 0) {
643
- await writer.writeAttribute("type", parameter.type);
644
- }
645
- if (parameter.value !== void 0) {
646
- if (typeof parameter.value === "string") {
647
- await writer.writeAttribute("value", parameter.value);
648
- } else if (parameter.value instanceof Date) {
649
- await writer.writeAttribute("value", dateToString(parameter.value, parameter.type));
650
- } else if (parameter.value instanceof Uint8Array) {
651
- await writer.writeAttribute("value", uint8ArrayToBase64(parameter.value));
652
- } else {
653
- await writer.writeAttribute("value", String(parameter.value));
654
- }
655
- }
656
- await writer.writeEndElement();
657
- }
658
- await writer.writeEndElement();
659
- }
970
+ function writeParameters(builder, parameters) {
971
+ if (parameters) {
972
+ builder.writeStartElement("Parameters");
973
+ for (const parameter of parameters) {
974
+ const attrs = { id: parameter.id };
975
+ if (parameter.type !== void 0) attrs.type = parameter.type;
976
+ if (parameter.value !== void 0) if (typeof parameter.value === "string") attrs.value = parameter.value;
977
+ else if (parameter.value instanceof Date) attrs.value = dateToString(parameter.value, parameter.type);
978
+ else if (parameter.value instanceof Uint8Array) attrs.value = uint8ArrayToBase64(parameter.value);
979
+ else attrs.value = String(parameter.value);
980
+ builder.writeStartElement("Parameter", attrs, true);
981
+ }
982
+ builder.writeEndElement("Parameters");
983
+ }
660
984
  }
661
- async function writeDataset(writer, dataset) {
662
- await writer.writeStartElement("Dataset", { attributes: { id: dataset.id } });
663
- if (dataset.constColumnSize() > 0 || dataset.columnSize() > 0) {
664
- await writer.writeStartElement("ColumnInfo");
665
- for (const constCol of dataset.iterConstColumns()) {
666
- await writer.writeStartElement("ConstColumn", {
667
- attributes: {
668
- id: constCol.id,
669
- size: String(constCol.size),
670
- type: constCol.type,
671
- value: constCol.value !== void 0 ? String(constCol.value) : ""
672
- },
673
- selfClosing: true
674
- });
675
- }
676
- for (const col of dataset.iterColumns()) {
677
- await writer.writeStartElement("Column", {
678
- attributes: {
679
- id: col.id,
680
- size: String(col.size),
681
- type: col.type
682
- },
683
- selfClosing: true
684
- });
685
- }
686
- await writer.writeEndElement();
687
- }
688
- await writer.writeStartElement("Rows");
689
- for (const row of dataset.iterRows()) {
690
- if (row.type) {
691
- await writer.writeStartElement("Row", { attributes: { type: row.type } });
692
- } else {
693
- await writer.writeStartElement("Row");
694
- }
695
- for (const col of row.cols) {
696
- await writeColumn(writer, dataset, col);
697
- }
698
- if (row.orgRow && row.orgRow.length > 0) {
699
- await writer.writeStartElement("OrgRow");
700
- for (const orgCol of row.orgRow) {
701
- await writeColumn(writer, dataset, orgCol);
702
- }
703
- await writer.writeEndElement();
704
- }
705
- await writer.writeEndElement();
706
- }
707
- await writer.writeEndElement();
708
- await writer.writeEndElement();
985
+ function writeDataset(builder, dataset) {
986
+ builder.writeStartElement("Dataset", { id: dataset.id });
987
+ if (dataset.constColumnSize() > 0 || dataset.columnSize() > 0) {
988
+ builder.writeStartElement("ColumnInfo");
989
+ for (const constCol of dataset.getConstColumns()) builder.writeStartElement("ConstColumn", {
990
+ id: constCol.id,
991
+ size: String(constCol.size),
992
+ type: constCol.type,
993
+ value: constCol.value !== void 0 ? String(constCol.value) : ""
994
+ }, true);
995
+ for (const col of dataset.getColumns()) builder.writeStartElement("Column", {
996
+ id: col.id,
997
+ size: String(col.size),
998
+ type: col.type
999
+ }, true);
1000
+ builder.writeEndElement("ColumnInfo");
1001
+ }
1002
+ builder.writeStartElement("Rows");
1003
+ for (const row of dataset.getRows()) {
1004
+ if (row.type) builder.writeStartElement("Row", { type: row.type });
1005
+ else builder.writeStartElement("Row");
1006
+ for (const col of row.cols) writeColumn(builder, dataset, col);
1007
+ if (row.orgRow && row.orgRow.length > 0) {
1008
+ builder.writeStartElement("OrgRow");
1009
+ for (const orgCol of row.orgRow) writeColumn(builder, dataset, orgCol);
1010
+ builder.writeEndElement("OrgRow");
1011
+ }
1012
+ builder.writeEndElement("Row");
1013
+ }
1014
+ builder.writeEndElement("Rows");
1015
+ builder.writeEndElement("Dataset");
709
1016
  }
710
- async function writeColumn(writer, dataset, col) {
711
- if (col.value !== void 0 && col.value !== null) {
712
- const colInfo = dataset.getColumnInfo(col.id);
713
- await writer.writeStartElement("Col", { attributes: { id: col.id } });
714
- await writer.writeCharacters(convertToString(col.value, colInfo.type));
715
- await writer.writeEndElement();
716
- } else {
717
- await writer.writeStartElement("Col", { attributes: { id: col.id }, selfClosing: true });
718
- }
1017
+ function writeColumn(builder, dataset, col) {
1018
+ if (col.value !== void 0 && col.value !== null) {
1019
+ const colInfo = dataset.getColumnInfo(col.id);
1020
+ builder.writeElementWithText("Col", { id: col.id }, convertToString(col.value, colInfo.type));
1021
+ } else builder.writeStartElement("Col", { id: col.id }, true);
719
1022
  }
720
- export {
721
- ColumnTypeError,
722
- Dataset,
723
- InvalidXmlError,
724
- NexaVersion,
725
- StringWritableStream,
726
- XapiRoot,
727
- XplatformVersion,
728
- _unescapeXml,
729
- arrayBufferToString,
730
- base64ToUint8Array,
731
- columnType,
732
- convertToColumnType,
733
- convertToString,
734
- dateToString,
735
- initXapi,
736
- makeParseEntities,
737
- makeWriterEntities,
738
- parse2 as parse,
739
- rowType,
740
- stringToDate,
741
- stringToReadableStream,
742
- uint8ArrayToBase64,
743
- write,
744
- writeString
745
- };
1023
+
1024
+ //#endregion
1025
+ export { ColumnTypeError, Dataset, InvalidXmlError, NexaVersion, StringWritableStream, XapiRoot, XmlStringBuilder, XplatformVersion, _unescapeXml, arrayBufferToString, base64ToUint8Array, columnType, convertToColumnType, convertToString, dateToString, encodeControlChars, escapeXml, initXapi, isXapiRoot, makeParseEntities, parse, parseXml, rowType, stringToDate, stringToReadableStream, uint8ArrayToBase64, write };