@arrirpc/schema 0.45.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.cjs ADDED
@@ -0,0 +1,2186 @@
1
+ 'use strict';
2
+
3
+ const timestamp = require('./shared/schema.34cb5fb7.cjs');
4
+ const jtdUtils = require('jtd-utils');
5
+ const scule = require('scule');
6
+
7
+ function createParsingTemplate(input, schema) {
8
+ const fallbackTemplate = `
9
+ function $fallback(instancePath, schemaPath) {
10
+ throw new Error(\`Error parsing input. InstancePath: "\${instancePath}". SchemaPath: "\${schemaPath}"\`);
11
+ }`;
12
+ let jsonParseCheck = "";
13
+ const subFunctions = {};
14
+ const template = schemaTemplate$1({
15
+ val: input,
16
+ targetVal: "result",
17
+ schema,
18
+ instancePath: "",
19
+ schemaPath: "",
20
+ subFunctions
21
+ });
22
+ const jsonTemplate = schemaTemplate$1({
23
+ val: "json",
24
+ targetVal: "result",
25
+ schema,
26
+ instancePath: "",
27
+ schemaPath: "",
28
+ subFunctions
29
+ });
30
+ if (jtdUtils.isSchemaFormProperties(schema) || jtdUtils.isSchemaFormValues(schema) || jtdUtils.isSchemaFormElements(schema) || jtdUtils.isSchemaFormDiscriminator(schema)) {
31
+ jsonParseCheck = `if (typeof ${input} === 'string') {
32
+ const json = JSON.parse(${input});
33
+ let result = {};
34
+ ${jsonTemplate}
35
+ return result;
36
+ }`;
37
+ }
38
+ if (jtdUtils.isSchemaFormEmpty(schema)) {
39
+ jsonParseCheck = `try {
40
+ const json = JSON.parse(${input});
41
+ return json;
42
+ } catch {
43
+ return ${input};
44
+ }`;
45
+ }
46
+ const functionBodyParts = Object.keys(subFunctions).map(
47
+ (key) => subFunctions[key]
48
+ );
49
+ const finalTemplate = `${fallbackTemplate}
50
+ ${functionBodyParts.join("\n")}
51
+ ${jsonParseCheck}
52
+ let result = {};
53
+ ${template}
54
+ return result;`;
55
+ return finalTemplate;
56
+ }
57
+ function schemaTemplate$1(input) {
58
+ if (jtdUtils.isSchemaFormType(input.schema)) {
59
+ switch (input.schema.type) {
60
+ case "boolean":
61
+ return booleanTemplate$2(input);
62
+ case "string":
63
+ return stringTemplate$2(input);
64
+ case "timestamp":
65
+ return timestampTemplate$2(input);
66
+ case "float64":
67
+ case "float32":
68
+ return floatTemplate$1(input);
69
+ case "int32":
70
+ return intTemplate$1(input, timestamp.int32Min, timestamp.int32Max);
71
+ case "int16":
72
+ return intTemplate$1(input, timestamp.int16Min, timestamp.int16Max);
73
+ case "int8":
74
+ return intTemplate$1(input, timestamp.int8Min, timestamp.int8Max);
75
+ case "uint32":
76
+ return intTemplate$1(input, timestamp.uint32Min, timestamp.uint32Max);
77
+ case "uint16":
78
+ return intTemplate$1(input, timestamp.uint16Min, timestamp.uint16Max);
79
+ case "uint8":
80
+ return intTemplate$1(input, timestamp.uint8Min, timestamp.uint8Max);
81
+ case "int64":
82
+ return bigIntTemplate$2(input, false);
83
+ case "uint64":
84
+ return bigIntTemplate$2(input, true);
85
+ }
86
+ }
87
+ if (jtdUtils.isSchemaFormEnum(input.schema)) {
88
+ return enumTemplate$2(input);
89
+ }
90
+ if (jtdUtils.isSchemaFormProperties(input.schema)) {
91
+ return objectTemplate$2(input);
92
+ }
93
+ if (jtdUtils.isSchemaFormElements(input.schema)) {
94
+ return arrayTemplate$2(input);
95
+ }
96
+ if (jtdUtils.isSchemaFormValues(input.schema)) {
97
+ return recordTemplate$2(input);
98
+ }
99
+ if (jtdUtils.isSchemaFormDiscriminator(input.schema)) {
100
+ return discriminatorTemplate$2(input);
101
+ }
102
+ if (jtdUtils.isSchemaFormRef(input.schema)) {
103
+ return refTemplate$2(input);
104
+ }
105
+ return anyTemplate$1(input);
106
+ }
107
+ function anyTemplate$1(input) {
108
+ if (input.instancePath.length === 0) {
109
+ return `try {
110
+ ${input.targetVal} = JSON.parse(${input.val});
111
+ } catch {
112
+ ${input.targetVal} = ${input.val};
113
+ }`;
114
+ }
115
+ return `${input.targetVal} = ${input.val}`;
116
+ }
117
+ function booleanTemplate$2(input) {
118
+ const errorMessage = input.instancePath.length ? `Expected boolean for ${input.instancePath}` : `Expected boolean`;
119
+ const templateParts = [];
120
+ if (input.instancePath.length === 0) {
121
+ templateParts.push(`if (typeof ${input.val} === 'string') {
122
+ if (${input.val} === 'true') {
123
+ ${input.targetVal} = true;
124
+ }
125
+ if (${input.val} === 'false') {
126
+ ${input.targetVal} = false;
127
+ }`);
128
+ if (input.schema.nullable) {
129
+ templateParts.push(`if (${input.val} === 'null') {
130
+ ${input.targetVal} = null;
131
+ }`);
132
+ }
133
+ templateParts.push(
134
+ `$fallback("${input.instancePath}", "${input.schemaPath}/type", "${errorMessage}");`
135
+ );
136
+ templateParts.push("}");
137
+ }
138
+ const mainTemplate = `if (typeof ${input.val} === 'boolean') {
139
+ ${input.targetVal} = ${input.val};
140
+ } else {
141
+ $fallback("${input.instancePath}", "${input.schemaPath}/type", "${errorMessage}");
142
+ }`;
143
+ if (input.schema.nullable) {
144
+ templateParts.push(`if (${input.val} === null) {
145
+ ${input.targetVal} = null;
146
+ } else {
147
+ ${mainTemplate}
148
+ }`);
149
+ } else {
150
+ templateParts.push(mainTemplate);
151
+ }
152
+ return templateParts.join("\n");
153
+ }
154
+ function stringTemplate$2(input) {
155
+ const errorMessage = `Expected string at ${input.instancePath}`;
156
+ const mainTemplate = `if (typeof ${input.val} === 'string') {
157
+ ${input.targetVal} = ${input.val};
158
+ } else {
159
+ $fallback("${input.instancePath}", "${input.schemaPath}/type", "${errorMessage}");
160
+ }`;
161
+ if (input.schema.nullable) {
162
+ return `if (${input.val} === null) {
163
+ ${input.targetVal} = ${input.val};
164
+ } else {
165
+ ${mainTemplate}
166
+ }`;
167
+ }
168
+ return mainTemplate;
169
+ }
170
+ function getVarName(input) {
171
+ return scule.camelCase(
172
+ input.split(".").join("_").split("[").join("_").split("]").join("_")
173
+ );
174
+ }
175
+ function floatTemplate$1(input) {
176
+ const valName = getVarName(`${input.val}Val`);
177
+ const templateParts = [];
178
+ if (input.instancePath.length === 0) {
179
+ templateParts.push(`if (typeof ${input.val} === 'string') {
180
+ const ${valName} = Number(${input.val});
181
+ if (!Number.isNaN(parsedVal)) {
182
+ ${input.targetVal} = ${valName};
183
+ }`);
184
+ if (input.schema.nullable) {
185
+ templateParts.push(`if (${input.val} === 'null') {
186
+ ${input.targetVal} = null;
187
+ }`);
188
+ }
189
+ templateParts.push(
190
+ `$fallback("${input.instancePath}", "${input.schemaPath}/type", \`Could not parse number from \${${input.val}}\`);`
191
+ );
192
+ templateParts.push("}");
193
+ }
194
+ const errorMessage = `Expected number at ${input.instancePath}`;
195
+ const mainTemplate = `if (typeof ${input.val} === 'number' && !Number.isNaN(${input.val})) {
196
+ ${input.targetVal} = ${input.val};
197
+ } else {
198
+ $fallback("${input.instancePath}", "${input.schemaPath}/type", "${errorMessage}");
199
+ }`;
200
+ if (input.schema.nullable) {
201
+ templateParts.push(`if (${input.val} === null) {
202
+ ${input.targetVal} = null;
203
+ } else {
204
+ ${mainTemplate}
205
+ }`);
206
+ } else {
207
+ templateParts.push(mainTemplate);
208
+ }
209
+ return templateParts.join("\n");
210
+ }
211
+ function intTemplate$1(input, min, max) {
212
+ const templateParts = [];
213
+ if (input.instancePath.length === 0) {
214
+ templateParts.push(`if (typeof ${input.val} === 'string') {
215
+ const parsedVal = Number(${input.val});
216
+ if (Number.isInteger(parsedVal) && parsedVal >= ${min} && parsedVal <= ${max}) {
217
+ ${input.targetVal} = ${input.val};
218
+ }`);
219
+ if (input.schema.nullable) {
220
+ templateParts.push(`if (${input.val} === 'null') {
221
+ ${input.targetVal} = null;
222
+ }`);
223
+ }
224
+ templateParts.push(
225
+ `$fallback("${input.instancePath}", "${input.schemaPath}", "Expected valid integer between ${min} and ${max});`
226
+ );
227
+ templateParts.push("}");
228
+ }
229
+ const mainTemplate = `if (typeof ${input.val} === 'number' && Number.isInteger(${input.val}) && ${input.val} >= ${min} && ${input.val} <= ${max}) {
230
+ ${input.targetVal} = ${input.val};
231
+ } else {
232
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Expected valid integer between ${min} and ${max}");
233
+ }`;
234
+ if (input.schema.nullable) {
235
+ templateParts.push(`if (${input.val} === null) {
236
+ ${input.targetVal} = null;
237
+ } else {
238
+ ${mainTemplate}
239
+ }`);
240
+ } else {
241
+ templateParts.push(mainTemplate);
242
+ }
243
+ return templateParts.join("\n");
244
+ }
245
+ function bigIntTemplate$2(input, isUnsigned) {
246
+ const templateParts = [];
247
+ templateParts.push(
248
+ `if (typeof ${input.val} === 'string' || typeof ${input.val} === 'number') {`
249
+ );
250
+ if (input.instancePath.length === 0 && input.schema.nullable) {
251
+ templateParts.push(`if (${input.val} === 'null') {
252
+ ${input.targetVal} = null;
253
+ } else {`);
254
+ }
255
+ templateParts.push(`try {
256
+ const val = BigInt(${input.val});`);
257
+ if (isUnsigned) {
258
+ templateParts.push(`if (val >= BigInt("0")) {
259
+ ${input.targetVal} = val;
260
+ } else {
261
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Unsigned int must be greater than or equal to 0.");
262
+ }`);
263
+ } else {
264
+ templateParts.push(`${input.targetVal} = val;`);
265
+ }
266
+ templateParts.push(`} catch(err) {
267
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Unable to parse BigInt from ${input.val}.");
268
+ }`);
269
+ if (input.instancePath.length === 0 && input.schema.nullable) {
270
+ templateParts.push("}");
271
+ }
272
+ templateParts.push("}");
273
+ if (isUnsigned) {
274
+ templateParts.push(`else if (typeof ${input.val} === 'bigint') {
275
+ if (${input.val} >= BigInt("0")) {
276
+ ${input.targetVal} = ${input.val};
277
+ } else {
278
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Unsigned int must be greater than or equal to 0.");
279
+ }
280
+ }`);
281
+ } else {
282
+ templateParts.push(`else if (typeof ${input.val} === 'bigint') {
283
+ ${input.targetVal} = ${input.val};
284
+ }`);
285
+ }
286
+ if (input.schema.nullable) {
287
+ templateParts.push(`else if (${input.val} === null) {
288
+ ${input.targetVal} = null;
289
+ }`);
290
+ }
291
+ templateParts.push(`else {
292
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Expected BigInt or Integer string. Got \${${input.val}}");
293
+ }`);
294
+ return templateParts.join("\n");
295
+ }
296
+ function timestampTemplate$2(input) {
297
+ const templateParts = [];
298
+ if (input.instancePath.length === 0) {
299
+ templateParts.push(`if (typeof ${input.val} === 'string') {
300
+ const parsedVal = new Date(${input.val});
301
+ if (!Number.isNaN(parsedVal.getMonth())) {
302
+ ${input.targetVal} = parsedVal;
303
+ }`);
304
+ if (input.schema.nullable) {
305
+ templateParts.push(`if (${input.val} === 'null') {
306
+ ${input.targetVal} = null;
307
+ }`);
308
+ }
309
+ templateParts.push(
310
+ `$fallback("${input.instancePath}", "${input.schemaPath}", "Expected instanceof Date or ISO Date string");`
311
+ );
312
+ templateParts.push("}");
313
+ }
314
+ const mainTemplate = `if (typeof ${input.val} === 'object' && ${input.val} instanceof Date) {
315
+ ${input.targetVal} = ${input.val};
316
+ } else if (typeof ${input.val} === 'string') {
317
+ ${input.targetVal} = new Date(${input.val});
318
+ } else {
319
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Expected instanceof Date or ISO Date string at ${input.instancePath}")
320
+ }`;
321
+ if (input.schema.nullable) {
322
+ templateParts.push(`if (${input.val} === null) {
323
+ ${input.targetVal} = null
324
+ } else {
325
+ ${mainTemplate}
326
+ }`);
327
+ } else {
328
+ templateParts.push(mainTemplate);
329
+ }
330
+ return templateParts.join("\n");
331
+ }
332
+ function enumTemplate$2(input) {
333
+ const enumTemplate2 = input.schema.enum.map((val) => `${input.val} === "${val}"`).join(" || ");
334
+ const errorMessage = `Expected one of the following values: [${input.schema.enum.join(
335
+ ", "
336
+ )}]${input.instancePath.length ? ` at ${input.instancePath}` : ""}.`;
337
+ const templateParts = [];
338
+ templateParts.push(`if (typeof ${input.val} === 'string') {
339
+ if (${enumTemplate2}) {
340
+ ${input.targetVal} = ${input.val};
341
+ }
342
+ `);
343
+ if (input.instancePath.length === 0 && input.schema.nullable) {
344
+ templateParts.push(`else if (${input.val} === 'null') {
345
+ ${input.targetVal} = null;
346
+ }`);
347
+ }
348
+ templateParts.push(
349
+ `else {
350
+ $fallback("${input.instancePath}", "${input.schemaPath}", "${errorMessage}");
351
+ }
352
+ } else {
353
+ $fallback("${input.instancePath}", "${input.schemaPath}", "${errorMessage}");
354
+ }`
355
+ );
356
+ const mainTemplate = templateParts.join("\n");
357
+ if (input.schema.nullable) {
358
+ return `if (${input.val} === null) {
359
+ ${input.targetVal} = null;
360
+ } else {
361
+ ${mainTemplate}
362
+ }`;
363
+ }
364
+ return mainTemplate;
365
+ }
366
+ function objectTemplate$2(input) {
367
+ const depthStr = getDepthStr(input.instancePath);
368
+ const innerTargetVal = `__${depthStr}`;
369
+ const parsingParts = [];
370
+ if (input.discriminatorKey && input.discriminatorValue) {
371
+ parsingParts.push(
372
+ `${innerTargetVal}.${input.discriminatorKey} = "${input.discriminatorValue}";`
373
+ );
374
+ }
375
+ if (!input.schema.additionalProperties) {
376
+ const keyVal = `_${depthStr}_keys`;
377
+ const optionalKeyVal = `_${depthStr}_optionalKeys`;
378
+ const keys = Object.keys(input.schema.properties).map((key) => `"${key}"`).join(",");
379
+ const optionalKeys = Object.keys(input.schema.optionalProperties ?? {}).map((key) => `"${key}"`).join(",");
380
+ parsingParts.push(
381
+ `const ${keyVal} = [${keys}];
382
+ const ${optionalKeyVal} = [${optionalKeys}];
383
+ for (let _key of Object.keys(${input.val})) {
384
+ if(!${keyVal}.includes(_key) && !${optionalKeyVal}.includes(_key) && _key !== "${input.discriminatorKey ?? ""}") {
385
+ $fallback("${input.instancePath}", "${input.schemaPath}/additionalProperties", \`The following key is now allowed by the schema "\${_key}".\`);
386
+ }
387
+ }
388
+ `
389
+ );
390
+ }
391
+ for (const key of Object.keys(input.schema.properties)) {
392
+ const subSchema = input.schema.properties[key];
393
+ const innerTemplate = schemaTemplate$1({
394
+ val: `${input.val}.${key}`,
395
+ targetVal: `${innerTargetVal}.${key}`,
396
+ schema: subSchema,
397
+ instancePath: `${input.instancePath}/${key}`,
398
+ schemaPath: `${input.schemaPath}/properties/${key}`,
399
+ subFunctions: input.subFunctions
400
+ });
401
+ parsingParts.push(innerTemplate);
402
+ }
403
+ if (input.schema.optionalProperties) {
404
+ for (const key of Object.keys(input.schema.optionalProperties)) {
405
+ const subSchema = input.schema.optionalProperties[key];
406
+ const innerTemplate = schemaTemplate$1({
407
+ val: `${input.val}.${key}`,
408
+ targetVal: `${innerTargetVal}.${key}`,
409
+ schema: subSchema,
410
+ instancePath: `${input.instancePath}/${key}`,
411
+ schemaPath: `${input.schemaPath}/optionalProperties/${key}`,
412
+ subFunctions: input.subFunctions
413
+ });
414
+ parsingParts.push(`if (typeof ${input.val}.${key} === 'undefined') {
415
+ // ignore undefined
416
+ } else {
417
+ ${innerTemplate}
418
+ }`);
419
+ }
420
+ }
421
+ let mainTemplate = `if (typeof ${input.val} === 'object' && ${input.val} !== null) {
422
+ const ${innerTargetVal} = {};
423
+ ${parsingParts.join("\n")}
424
+ ${input.targetVal} = ${innerTargetVal};
425
+ } else {
426
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Expected object");
427
+ }`;
428
+ const fnName = refFunctionName$1(input.schema.metadata?.id ?? "");
429
+ if (Object.keys(input.subFunctions).includes(fnName)) {
430
+ if (!input.subFunctions[fnName]) {
431
+ input.subFunctions[fnName] = `function ${fnName}(_fnVal) {
432
+ let _fnTarget
433
+ ${mainTemplate.split(` ${input.val}`).join(" _fnVal").split(`(${input.val}`).join(`(_fnVal`).split(` ${input.targetVal}`).join(` _fnTarget`).split(`(${input.targetVal}`).join("(_fnTarget")}
434
+ return _fnTarget;
435
+ }`;
436
+ }
437
+ mainTemplate = `${input.targetVal} = ${fnName}(${input.val});`;
438
+ }
439
+ if (input.schema.nullable) {
440
+ return `if (${input.val} === null) {
441
+ ${input.targetVal} = null;
442
+ } else {
443
+ ${mainTemplate}
444
+ }`;
445
+ }
446
+ return mainTemplate;
447
+ }
448
+ function arrayTemplate$2(input) {
449
+ const resultVar = `__${getDepthStr(input.instancePath)}`;
450
+ const itemVar = `${resultVar}AItem`;
451
+ const itemResultVar = `${itemVar}AResult`;
452
+ const innerTemplate = schemaTemplate$1({
453
+ val: itemVar,
454
+ targetVal: itemResultVar,
455
+ instancePath: `${input.instancePath}/[0]`,
456
+ schemaPath: `${input.schemaPath}/elements`,
457
+ schema: input.schema.elements,
458
+ subFunctions: input.subFunctions
459
+ });
460
+ const mainTemplate = `if (Array.isArray(${input.val})) {
461
+ const ${resultVar} = [];
462
+ for(const ${itemVar} of ${input.val}) {
463
+ let ${itemResultVar};
464
+ ${innerTemplate}
465
+ ${resultVar}.push(${itemResultVar});
466
+ }
467
+ ${input.targetVal} = ${resultVar};
468
+ } else {
469
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Expected Array");
470
+ }`;
471
+ if (input.schema.nullable) {
472
+ return `if (${input.val} === null) {
473
+ ${input.targetVal} = null;
474
+ } else {
475
+ ${mainTemplate}
476
+ }`;
477
+ }
478
+ return mainTemplate;
479
+ }
480
+ function discriminatorTemplate$2(input) {
481
+ const switchParts = [];
482
+ const types = Object.keys(input.schema.mapping);
483
+ for (const type of types) {
484
+ const innerSchema = input.schema.mapping[type];
485
+ const template = objectTemplate$2({
486
+ val: input.val,
487
+ targetVal: input.targetVal,
488
+ schema: innerSchema,
489
+ schemaPath: `${input.schemaPath}/mapping`,
490
+ instancePath: `${input.instancePath}`,
491
+ discriminatorKey: input.schema.discriminator,
492
+ discriminatorValue: type,
493
+ subFunctions: input.subFunctions
494
+ });
495
+ switchParts.push(`case "${type}": {
496
+ ${template}
497
+ break;
498
+ }`);
499
+ }
500
+ let mainTemplate = `if (typeof ${input.val} === 'object' && ${input.val} !== null) {
501
+ switch(${input.val}.${input.schema.discriminator}) {
502
+ ${switchParts.join("\n")}
503
+ default:
504
+ $fallback("${input.instancePath}", "${input.schemaPath}/mapping", "${input.val}.${input.schema.discriminator} did not match one of the specified values");
505
+ break;
506
+ }
507
+ } else {
508
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Expected Object.");
509
+ }`;
510
+ const fnName = refFunctionName$1(input.schema.metadata?.id ?? "");
511
+ if (Object.keys(input.subFunctions).includes(fnName)) {
512
+ if (!input.subFunctions[fnName]) {
513
+ input.subFunctions[fnName] = `function ${fnName}(_fnVal) {
514
+ let _fnTarget;
515
+ ${mainTemplate.split(` ${input.val}`).join(` _fnVal`).split(`(${input.val}`).join(`(_fnVal`).split(` ${input.targetVal}`).join(` _fnTarget`).split(`(${input.targetVal}`).join(`(_fnTarget`)}
516
+ return _fnTarget;
517
+ }`;
518
+ }
519
+ mainTemplate = `${input.targetVal} = ${fnName}(${input.val});`;
520
+ }
521
+ if (input.schema.nullable) {
522
+ return `if (${input.val} === null) {
523
+ ${input.targetVal} = null;
524
+ } else {
525
+ ${mainTemplate}
526
+ }`;
527
+ }
528
+ return mainTemplate;
529
+ }
530
+ function getDepthStr(instancePath) {
531
+ const parts = instancePath.split("/");
532
+ const depth = parts.length;
533
+ return `D${depth}`;
534
+ }
535
+ function recordTemplate$2(input) {
536
+ const valPrefix = getDepthStr(input.instancePath);
537
+ const resultVal = `__${valPrefix}RResult`;
538
+ const loopVal = `__${valPrefix}RKey`;
539
+ const loopResultVal = `${loopVal}RVal`;
540
+ const innerTemplate = schemaTemplate$1({
541
+ val: `${input.val}[${loopVal}]`,
542
+ targetVal: loopResultVal,
543
+ instancePath: `${input.instancePath}/[key]`,
544
+ schemaPath: `${input.schemaPath}/values`,
545
+ schema: input.schema.values,
546
+ subFunctions: input.subFunctions
547
+ });
548
+ const mainTemplate = `if (typeof ${input.val} === 'object' && ${input.val} !== null) {
549
+ const ${resultVal} = {};
550
+ for(const ${loopVal} of Object.keys(${input.val})) {
551
+ let ${loopResultVal};
552
+ ${innerTemplate};
553
+ ${resultVal}[${loopVal}] = ${loopResultVal};
554
+ }
555
+ ${input.targetVal} = ${resultVal};
556
+ } else {
557
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Expected object.");
558
+ }`;
559
+ if (input.schema.nullable) {
560
+ return `if (${input.val} === null) {
561
+ ${input.targetVal} = null;
562
+ } else {
563
+ ${mainTemplate}
564
+ }`;
565
+ }
566
+ return mainTemplate;
567
+ }
568
+ function refFunctionName$1(id) {
569
+ return `__parse_${id}`;
570
+ }
571
+ function refTemplate$2(input) {
572
+ const fnName = refFunctionName$1(input.schema.ref);
573
+ if (!Object.keys(input.subFunctions).includes(fnName)) {
574
+ input.subFunctions[fnName] = "";
575
+ }
576
+ if (input.schema.nullable) {
577
+ return `if (${input.val} === null) {
578
+ ${input.targetVal} = null;
579
+ } else {
580
+ ${input.targetVal} = ${fnName}(${input.val});
581
+ }`;
582
+ }
583
+ return `${input.targetVal} = ${fnName}(${input.val})`;
584
+ }
585
+
586
+ function createSerializationV2Template(inputName, schema) {
587
+ const subFunctions = {};
588
+ const context = {
589
+ val: inputName,
590
+ targetVal: "json",
591
+ schema,
592
+ schemaPath: "",
593
+ instancePath: "",
594
+ outputPrefix: "",
595
+ needsSanitization: [],
596
+ subFunctions
597
+ };
598
+ const result = template(context);
599
+ if (jtdUtils.isSchemaFormType(schema) || jtdUtils.isSchemaFormEnum(schema)) {
600
+ return result;
601
+ }
602
+ const subFunctionParts = Object.keys(subFunctions).map(
603
+ (key) => subFunctions[key]
604
+ );
605
+ return `
606
+ let json = '';
607
+ ${subFunctionParts.join("\n")}
608
+ ${context.needsSanitization.length > 0 ? `const STR_ESCAPE = /[\\u0000-\\u001f\\u0022\\u005c\\ud800-\\udfff]|[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?:[^\\ud800-\\udbff]|^)[\\udc00-\\udfff]/;` : ""}
609
+ ${result}
610
+ return json;`;
611
+ }
612
+ function template(input) {
613
+ if (jtdUtils.isSchemaFormType(input.schema)) {
614
+ return scalarTemplate(input);
615
+ }
616
+ if (jtdUtils.isSchemaFormEnum(input.schema)) {
617
+ return enumTemplate$1(input);
618
+ }
619
+ if (jtdUtils.isSchemaFormProperties(input.schema)) {
620
+ return objectTemplate$1(input);
621
+ }
622
+ if (jtdUtils.isSchemaFormElements(input.schema)) {
623
+ return arrayTemplate$1(input);
624
+ }
625
+ if (jtdUtils.isSchemaFormValues(input.schema)) {
626
+ return recordTemplate$1(input);
627
+ }
628
+ if (jtdUtils.isSchemaFormDiscriminator(input.schema)) {
629
+ return discriminatorTemplate$1(input);
630
+ }
631
+ if (jtdUtils.isSchemaFormRef(input.schema)) {
632
+ return refTemplate$1(input);
633
+ }
634
+ return anyTemplate(input);
635
+ }
636
+ function scalarTemplate(input) {
637
+ switch (input.schema.type) {
638
+ case "string":
639
+ return stringTemplate$1(input);
640
+ case "boolean":
641
+ return booleanTemplate$1(input);
642
+ case "timestamp":
643
+ return timestampTemplate$1(input);
644
+ case "float32":
645
+ case "float64":
646
+ return numberTemplate(input);
647
+ case "int64":
648
+ return bigIntTemplate$1(input);
649
+ case "int32":
650
+ case "int16":
651
+ case "int8":
652
+ return numberTemplate(input);
653
+ case "uint64":
654
+ return bigIntTemplate$1(input);
655
+ case "uint32":
656
+ case "uint16":
657
+ case "uint8":
658
+ return numberTemplate(input);
659
+ default:
660
+ input.schema.type;
661
+ throw new Error("Invalid value in 'type'");
662
+ }
663
+ }
664
+ function stringTemplate$1(input) {
665
+ if (input.instancePath.length === 0) {
666
+ if (input.schema.nullable) {
667
+ return `if (typeof ${input.val} === 'string') {
668
+ return ${input.val};
669
+ }
670
+ return 'null';`;
671
+ }
672
+ return `return ${input.val};`;
673
+ }
674
+ input.needsSanitization.push(input.instancePath);
675
+ const mainTemplate = `${input.targetVal} += \`${input.outputPrefix ?? ""}\`;
676
+ if (${input.val}.length < 42) {
677
+ let __result__ = "";
678
+ let __last__ = -1;
679
+ let __point__ = 255;
680
+ let __finished__ = false;
681
+ for (let i = 0; i < ${input.val}.length; i++) {
682
+ __point__ = ${input.val}.charCodeAt(i);
683
+ if (__point__ < 32 || (__point__ >= 0xd800 && __point__ <= 0xdfff)) {
684
+ ${input.targetVal} += JSON.stringify(${input.val});
685
+ __finished__ = true;
686
+ break;
687
+ }
688
+ if (__point__ === 0x22 || __point__ === 0x5c) {
689
+ __last__ === -1 && (__last__ = 0);
690
+ __result__ += ${input.val}.slice(__last__, i) + '\\\\';
691
+ __last__ = i;
692
+ }
693
+ }
694
+ if(!__finished__) {
695
+ if (__last__ === -1) {
696
+ ${input.targetVal} += \`"\${${input.val}}"\`;
697
+ } else {
698
+ ${input.targetVal} += \`"\${__result__}\${${input.val}.slice(__last__)}"\`;
699
+ }
700
+ }
701
+ } else if (${input.val}.length < 5000 && !STR_ESCAPE.test(${input.val})) {
702
+ ${input.targetVal} += \`"\${${input.val}}"\`;
703
+ } else {
704
+ ${input.targetVal} += JSON.stringify(${input.val});
705
+ }`;
706
+ if (input.schema.nullable) {
707
+ return `if (typeof ${input.val} === 'string') {
708
+ ${mainTemplate}
709
+ } else {
710
+ ${input.targetVal} += '${input.outputPrefix ?? ""}null';
711
+ }`;
712
+ }
713
+ return mainTemplate;
714
+ }
715
+ function booleanTemplate$1(input) {
716
+ if (input.instancePath.length === 0) {
717
+ return `return \`\${${input.val}}\`;`;
718
+ }
719
+ const mainTemplate = `${input.targetVal} += \`${input.outputPrefix}\${${input.val}}\`;`;
720
+ if (input.schema.nullable) {
721
+ return `if (typeof ${input.val} === 'boolean') {
722
+ ${mainTemplate}
723
+ } else {
724
+ ${input.targetVal} += '${input.outputPrefix}null';
725
+ }`;
726
+ }
727
+ return mainTemplate;
728
+ }
729
+ function timestampTemplate$1(input) {
730
+ if (input.instancePath.length === 0) {
731
+ if (input.schema.nullable) {
732
+ return `if (typeof ${input.val} === 'object' && ${input.val} instanceof Date) {
733
+ return ${input.val}.toISOString();
734
+ }
735
+ return 'null';`;
736
+ }
737
+ return `return ${input.val}.toISOString();`;
738
+ }
739
+ const mainTemplate = `${input.targetVal} += \`${input.outputPrefix}"\${${input.val}.toISOString()}"\`;`;
740
+ if (input.schema.nullable) {
741
+ return `if (typeof ${input.val} === 'object' && ${input.val} instanceof Date) {
742
+ ${mainTemplate}
743
+ } else {
744
+ ${input.targetVal} += '${input.outputPrefix}null';
745
+ }`;
746
+ }
747
+ return mainTemplate;
748
+ }
749
+ function numberTemplate(input) {
750
+ if (input.instancePath.length === 0) {
751
+ if (input.schema.nullable) {
752
+ return `if (typeof ${input.val} === 'number' && !Number.isNaN(${input.val})) {
753
+ return \`\${${input.val}}\`;
754
+ }
755
+ return 'null';`;
756
+ }
757
+ return `return \`\${${input.val}}\`;`;
758
+ }
759
+ const mainTemplate = `
760
+ if(Number.isNaN(${input.val})) {
761
+ throw new Error("Expected number at ${input.instancePath} got NaN");
762
+ }
763
+ ${input.targetVal} += \`${input.outputPrefix}\${${input.val}}\`;`;
764
+ if (input.schema.nullable) {
765
+ return `if (typeof ${input.val} === 'number' && !Number.isNaN(${input.val})) {
766
+ ${mainTemplate}
767
+ } else {
768
+ ${input.targetVal} += '${input.outputPrefix}null';
769
+ }`;
770
+ }
771
+ return mainTemplate;
772
+ }
773
+ function bigIntTemplate$1(input) {
774
+ if (input.instancePath.length === 0) {
775
+ if (input.schema.nullable) {
776
+ return `if (typeof ${input.val} === 'bigint') {
777
+ return ${input.val}.toString();
778
+ }
779
+ return 'null';`;
780
+ }
781
+ return `return ${input.val}.toString();`;
782
+ }
783
+ const mainTemplate = `${input.targetVal} += \`${input.outputPrefix}"\${${input.val}.toString()}"\`;`;
784
+ if (input.schema.nullable) {
785
+ return `if (typeof ${input.val} === 'bigint') {
786
+ ${mainTemplate}
787
+ } else {
788
+ ${input.targetVal} += '${input.outputPrefix}null';
789
+ }`;
790
+ }
791
+ return mainTemplate;
792
+ }
793
+ function enumTemplate$1(input) {
794
+ if (input.instancePath.length === 0) {
795
+ if (input.schema.nullable) {
796
+ return `if (typeof ${input.val} === 'string') {
797
+ return ${input.val};
798
+ }
799
+ return 'null';`;
800
+ }
801
+ return `return ${input.val};`;
802
+ }
803
+ const mainTemplate = `${input.targetVal} += \`${input.outputPrefix}"\${${input.val}}"\``;
804
+ if (input.schema.nullable) {
805
+ return `if (typeof ${input.val} === 'string') {
806
+ ${mainTemplate}
807
+ } else {
808
+ ${input.targetVal} += '${input.outputPrefix}null';
809
+ }`;
810
+ }
811
+ return mainTemplate;
812
+ }
813
+ function objectTemplate$1(input) {
814
+ const templateParts = [`${input.targetVal} += '{';`];
815
+ if (input.discriminatorKey && input.discriminatorValue) {
816
+ templateParts.push(
817
+ `${input.targetVal} += \`"${input.discriminatorKey}":"${input.discriminatorValue}"\`;`
818
+ );
819
+ }
820
+ const propKeys = Object.keys(input.schema.properties);
821
+ const optionalPropKeys = Object.keys(input.schema.optionalProperties ?? {});
822
+ const isAllOptionalKeys = propKeys.length === 0 && !input.discriminatorKey?.length && !input.discriminatorValue?.length;
823
+ for (let i = 0; i < propKeys.length; i++) {
824
+ const key = propKeys[i];
825
+ const propSchema = input.schema.properties[key];
826
+ const includeComma = i !== 0 || input.discriminatorKey && input.discriminatorValue;
827
+ const innerTemplate = template({
828
+ schema: propSchema,
829
+ val: `___val___.${key}`,
830
+ targetVal: input.targetVal,
831
+ instancePath: `${input.instancePath}/${key}`,
832
+ schemaPath: `${input.schemaPath}/properties/${key}`,
833
+ outputPrefix: includeComma ? `,"${key}":` : `"${key}":`,
834
+ needsSanitization: input.needsSanitization,
835
+ subFunctions: input.subFunctions
836
+ });
837
+ templateParts.push(innerTemplate);
838
+ }
839
+ if (isAllOptionalKeys) {
840
+ const hasFieldsVar = input.instancePath.length ? scule.camelCase(`${input.instancePath}_HasFields`) : scule.camelCase(
841
+ `${input.val}_HasFields`.split("[").join("").split("]").join("")
842
+ );
843
+ templateParts.push(`let ${hasFieldsVar} = false;`);
844
+ for (let i = 0; i < optionalPropKeys.length; i++) {
845
+ const key = optionalPropKeys[i];
846
+ const optionalPropSchema = input.schema.optionalProperties?.[key];
847
+ if (!optionalPropSchema) {
848
+ continue;
849
+ }
850
+ const innerVal = `___val___.${key}`;
851
+ const innerTemplate = template({
852
+ schema: optionalPropSchema,
853
+ schemaPath: `${input.schemaPath}/optionalProperties/${key}`,
854
+ instancePath: `${input.instancePath}/${key}`,
855
+ val: innerVal,
856
+ targetVal: input.targetVal,
857
+ outputPrefix: `"${key}":`,
858
+ needsSanitization: input.needsSanitization,
859
+ subFunctions: input.subFunctions
860
+ });
861
+ const innerTemplateWithComma = template({
862
+ schema: optionalPropSchema,
863
+ schemaPath: `${input.schemaPath}/optionalProperties/${key}`,
864
+ instancePath: `${input.instancePath}/${key}`,
865
+ val: innerVal,
866
+ targetVal: input.targetVal,
867
+ outputPrefix: `,"${key}":`,
868
+ needsSanitization: input.needsSanitization,
869
+ subFunctions: input.subFunctions
870
+ });
871
+ templateParts.push(`if (typeof ${innerVal} !== 'undefined') {
872
+ if (${hasFieldsVar}) {
873
+ ${innerTemplateWithComma}
874
+ } else {
875
+ ${innerTemplate}
876
+ ${hasFieldsVar} = true;
877
+ }
878
+ }`);
879
+ }
880
+ } else {
881
+ for (let i = 0; i < optionalPropKeys.length; i++) {
882
+ const key = optionalPropKeys[i];
883
+ const optionalPropSchema = input.schema.optionalProperties?.[key];
884
+ if (!optionalPropSchema) {
885
+ continue;
886
+ }
887
+ const innerVal = `___val___.${key}`;
888
+ const innerTemplate = template({
889
+ schema: optionalPropSchema,
890
+ schemaPath: `${input.schemaPath}/optionalProperties/${key}`,
891
+ instancePath: `${input.instancePath}/${key}`,
892
+ val: innerVal,
893
+ targetVal: "json",
894
+ outputPrefix: `,"${key}":`,
895
+ needsSanitization: input.needsSanitization,
896
+ subFunctions: input.subFunctions
897
+ });
898
+ const completeInnerTemplate = `if (typeof ${innerVal} !== 'undefined') {
899
+ ${innerTemplate}
900
+ }`;
901
+ templateParts.push(completeInnerTemplate);
902
+ }
903
+ }
904
+ templateParts.push(`${input.targetVal} += '}';`);
905
+ let mainTemplate = templateParts.join("\n");
906
+ const fnName = refFnName(input.schema.metadata?.id ?? "");
907
+ if (hasFunctionName(fnName, input.subFunctions)) {
908
+ if (!hasFunctionBody(fnName, input.subFunctions)) {
909
+ input.subFunctions[fnName] = `function ${fnName}(__inputVal__) {
910
+ ${mainTemplate.split("___val___").join("__inputVal__")}
911
+ }`;
912
+ }
913
+ mainTemplate = `${fnName}(${input.val});`;
914
+ }
915
+ if (input.schema.nullable) {
916
+ return `if (typeof ${input.val} === 'object' && ${input.val} !== null) {
917
+ ${input.targetVal} += '${input.outputPrefix}';
918
+ ${mainTemplate.split("___val___").join(input.val)}
919
+ } else {
920
+ ${input.targetVal} += '${input.outputPrefix}null';
921
+ }`;
922
+ }
923
+ return `
924
+ ${input.targetVal} += '${input.outputPrefix}';
925
+ ${mainTemplate.split("___val___").join(input.val)}`;
926
+ }
927
+ function hasFunctionName(name, fns) {
928
+ return typeof fns[name] === "string";
929
+ }
930
+ function hasFunctionBody(name, fns) {
931
+ return typeof fns[name] === "string" && fns[name].length > 0;
932
+ }
933
+ function arrayTemplate$1(input) {
934
+ const itemVarName = scule.camelCase(`${input.val || "list"}_item`);
935
+ const templateParts = [
936
+ `${input.targetVal} += '${input.outputPrefix}[';`
937
+ ];
938
+ const innerTemplate = template({
939
+ schema: input.schema.elements,
940
+ schemaPath: `${input.schemaPath}/elements`,
941
+ instancePath: `${input.instancePath}/i`,
942
+ val: itemVarName,
943
+ targetVal: input.targetVal,
944
+ outputPrefix: "",
945
+ needsSanitization: input.needsSanitization,
946
+ subFunctions: input.subFunctions
947
+ });
948
+ templateParts.push(`for (let i = 0; i < ${input.val}.length; i++) {
949
+ const ${itemVarName} = ${input.val}[i];
950
+ if (i !== 0) {
951
+ ${input.targetVal} += ',';
952
+ }
953
+ ${innerTemplate}
954
+ }`);
955
+ templateParts.push(`${input.targetVal} += ']';`);
956
+ const mainTemplate = templateParts.join("\n");
957
+ if (input.schema.nullable) {
958
+ return `if (Array.isArray(${input.val})) {
959
+ ${mainTemplate}
960
+ } else {
961
+ ${input.targetVal} += '${input.outputPrefix}null';
962
+ }`;
963
+ }
964
+ return mainTemplate;
965
+ }
966
+ function recordTemplate$1(input) {
967
+ const keysVarName = input.instancePath.length ? scule.camelCase(input.instancePath.split("/").join("_")) + "Keys" : scule.camelCase(`${input.val.split(".").join("_")}_Keys`);
968
+ const templateParts = [
969
+ `const ${keysVarName} = Object.keys(${input.val});`,
970
+ `${input.targetVal} += '${input.outputPrefix}{';`
971
+ ];
972
+ const innerTemplate = template({
973
+ schema: input.schema.values,
974
+ schemaPath: `${input.schemaPath}/values`,
975
+ instancePath: `${input.instancePath}/key`,
976
+ val: `innerVal`,
977
+ targetVal: input.targetVal,
978
+ outputPrefix: "",
979
+ needsSanitization: input.needsSanitization,
980
+ subFunctions: input.subFunctions
981
+ });
982
+ templateParts.push(`for (let i = 0; i < ${keysVarName}.length; i++) {
983
+ const key = ${keysVarName}[i];
984
+ const innerVal = ${input.val}[key];
985
+ if(i !== 0) {
986
+ ${input.targetVal} += \`,"\${key}":\`;
987
+ } else {
988
+ ${input.targetVal} += \`"\${key}":\`;
989
+ }
990
+ ${innerTemplate}
991
+ }`);
992
+ templateParts.push(`${input.targetVal} += '}';`);
993
+ const mainTemplate = templateParts.join("\n");
994
+ if (input.schema.nullable) {
995
+ return `if (typeof ${input.val} === 'object' && ${input.val} !== null) {
996
+ ${mainTemplate}
997
+ } else {
998
+ ${input.targetVal} += '${input.outputPrefix}null';
999
+ }`;
1000
+ }
1001
+ return mainTemplate;
1002
+ }
1003
+ function discriminatorTemplate$1(input) {
1004
+ const discriminatorKey = input.schema.discriminator;
1005
+ const discriminatorVals = Object.keys(input.schema.mapping);
1006
+ const inputPlaceholder = "<<<tempval>>>";
1007
+ const templateParts = [`switch(${inputPlaceholder}.${discriminatorKey}) {`];
1008
+ for (const val of discriminatorVals) {
1009
+ const valSchema = input.schema.mapping[val];
1010
+ const innerTemplate = template({
1011
+ schema: valSchema,
1012
+ schemaPath: `${input.schemaPath}/mapping/${val}`,
1013
+ instancePath: `${input.instancePath}`,
1014
+ val: inputPlaceholder,
1015
+ targetVal: input.targetVal,
1016
+ discriminatorKey,
1017
+ discriminatorValue: val,
1018
+ outputPrefix: input.outputPrefix,
1019
+ needsSanitization: input.needsSanitization,
1020
+ subFunctions: input.subFunctions
1021
+ });
1022
+ templateParts.push(`case '${val}': {
1023
+ ${innerTemplate}
1024
+ break;
1025
+ }`);
1026
+ }
1027
+ templateParts.push("}");
1028
+ let mainTemplate = templateParts.join("\n");
1029
+ const fnName = refFnName(input.schema.metadata?.id ?? "");
1030
+ if (hasFunctionName(fnName, input.subFunctions)) {
1031
+ if (!hasFunctionBody(fnName, input.subFunctions)) {
1032
+ input.subFunctions[fnName] = `function ${fnName}(__fnInput__){
1033
+ ${mainTemplate.split(inputPlaceholder).join("__fnInput__")}
1034
+ }`;
1035
+ }
1036
+ mainTemplate = `${fnName}(${input.val});`;
1037
+ }
1038
+ if (input.schema.nullable) {
1039
+ return `if (typeof ${input.val} === 'object' && ${input.val} !== null) {
1040
+ ${mainTemplate.split(inputPlaceholder).join(input.val)}
1041
+ } else {
1042
+ ${input.targetVal} += '${input.outputPrefix}null';
1043
+ }`;
1044
+ }
1045
+ return mainTemplate.split(inputPlaceholder).join(input.val);
1046
+ }
1047
+ function anyTemplate(input) {
1048
+ if (input.outputPrefix) {
1049
+ const mainTemplate = `if (typeof ${input.val} !== 'undefined') {
1050
+ ${input.targetVal} += '${input.outputPrefix}' + JSON.stringify(${input.val});
1051
+ }`;
1052
+ if (input.schema.nullable) {
1053
+ return `if (${input.val} === null) {
1054
+ ${input.targetVal} += '${input.outputPrefix}null';
1055
+ } else {
1056
+ ${mainTemplate}
1057
+ }`;
1058
+ }
1059
+ return mainTemplate;
1060
+ }
1061
+ return `if (typeof ${input.val} !== 'undefined') {
1062
+ ${input.targetVal} += JSON.stringify(${input.val});
1063
+ }`;
1064
+ }
1065
+ function refFnName(id) {
1066
+ return `__serialize_${id}`;
1067
+ }
1068
+ function refTemplate$1(input) {
1069
+ const fnName = refFnName(input.schema.ref);
1070
+ if (!Object.keys(input.subFunctions).includes(fnName)) {
1071
+ input.subFunctions[fnName] = "";
1072
+ }
1073
+ if (input.schema.nullable) {
1074
+ return `if (${input.val} === null) {
1075
+ ${input.targetVal} += '${input.outputPrefix}null';
1076
+ } else {
1077
+ ${input.targetVal} += '${input.outputPrefix}';
1078
+ ${fnName}(${input.val});
1079
+ }`;
1080
+ }
1081
+ return `${input.targetVal} += '${input.outputPrefix}';
1082
+ ${fnName}(${input.val});`;
1083
+ }
1084
+
1085
+ function createValidationTemplate(inputName, schema) {
1086
+ const subFunctions = {};
1087
+ const template = schemaTemplate({
1088
+ val: inputName,
1089
+ targetVal: "",
1090
+ schema,
1091
+ schemaPath: ``,
1092
+ instancePath: "",
1093
+ subFunctions
1094
+ });
1095
+ const subFunctionBodies = Object.keys(subFunctions).map(
1096
+ (key) => subFunctions[key]
1097
+ );
1098
+ return `${subFunctionBodies.join("\n")}
1099
+ return ${template}`;
1100
+ }
1101
+ function schemaTemplate(input) {
1102
+ if (timestamp.isAScalarSchema(input.schema)) {
1103
+ switch (input.schema.type) {
1104
+ case "boolean":
1105
+ return booleanTemplate(input);
1106
+ case "float32":
1107
+ case "float64":
1108
+ return floatTemplate(input);
1109
+ case "int8":
1110
+ return intTemplate(input, timestamp.int8Min, timestamp.int8Max);
1111
+ case "int16":
1112
+ return intTemplate(input, timestamp.int16Min, timestamp.int16Max);
1113
+ case "int32":
1114
+ return intTemplate(input, timestamp.int32Min, timestamp.int32Max);
1115
+ case "uint8":
1116
+ return intTemplate(input, timestamp.uint8Min, timestamp.uint8Max);
1117
+ case "uint16":
1118
+ return intTemplate(input, timestamp.uint16Min, timestamp.uint16Max);
1119
+ case "uint32":
1120
+ return intTemplate(input, timestamp.uint32Min, timestamp.uint32Max);
1121
+ case "int64":
1122
+ return bigIntTemplate(input, false);
1123
+ case "uint64":
1124
+ return bigIntTemplate(input, true);
1125
+ case "string":
1126
+ return stringTemplate(input);
1127
+ case "timestamp":
1128
+ return timestampTemplate(input);
1129
+ }
1130
+ }
1131
+ if (timestamp.isAObjectSchema(input.schema)) {
1132
+ return objectTemplate(input);
1133
+ }
1134
+ if (timestamp.isAStringEnumSchema(input.schema)) {
1135
+ return enumTemplate(input);
1136
+ }
1137
+ if (timestamp.isAAraySchema(input.schema)) {
1138
+ return arrayTemplate(input);
1139
+ }
1140
+ if (timestamp.isARecordSchema(input.schema)) {
1141
+ return recordTemplate(input);
1142
+ }
1143
+ if (timestamp.isADiscriminatorSchema(input.schema)) {
1144
+ return discriminatorTemplate(input);
1145
+ }
1146
+ if (timestamp.isARefSchema(input.schema)) {
1147
+ return refTemplate(input);
1148
+ }
1149
+ return "true";
1150
+ }
1151
+ function booleanTemplate(input) {
1152
+ if (input.schema.nullable) {
1153
+ return `(${input.val} === null || typeof ${input.val} === 'boolean')`;
1154
+ }
1155
+ return `typeof ${input.val} === 'boolean'`;
1156
+ }
1157
+ function floatTemplate(input) {
1158
+ if (input.schema.nullable) {
1159
+ return `((typeof ${input.val} === 'number' && !Number.isNaN(${input.val})) || ${input.val} === null)`;
1160
+ }
1161
+ return `(typeof ${input.val} === 'number' && !Number.isNaN(${input.val}))`;
1162
+ }
1163
+ function intTemplate(input, min, max) {
1164
+ if (input.schema.nullable) {
1165
+ return `((typeof ${input.val} === 'number' && Number.isInteger(${input.val}) && ${input.val} >= ${min} && ${input.val} <= ${max}) || ${input.val} === null)`;
1166
+ }
1167
+ return `(typeof ${input.val} === 'number' && Number.isInteger(${input.val}) && ${input.val} >= ${min} && ${input.val} <= ${max})`;
1168
+ }
1169
+ function bigIntTemplate(input, isUnsigned = false) {
1170
+ const mainTemplate = isUnsigned ? `typeof ${input.val} === 'bigint' && ${input.val} >= BigInt("0")` : `typeof ${input.val} === 'bigint' && ${input.val} < BigInt("9223372036854775808") && ${input.val} > BigInt("-9223372036854775809")`;
1171
+ if (input.schema.nullable) {
1172
+ return `(${mainTemplate}) || ${input.val} === null`;
1173
+ }
1174
+ return mainTemplate;
1175
+ }
1176
+ function stringTemplate(input) {
1177
+ if (input.schema.nullable) {
1178
+ return `(typeof ${input.val} === 'string' || ${input.val} === null)`;
1179
+ }
1180
+ return `typeof ${input.val} === 'string'`;
1181
+ }
1182
+ function timestampTemplate(input) {
1183
+ if (input.schema.nullable) {
1184
+ return `((typeof ${input.val} === 'object' && ${input.val} instanceof Date) || ${input.val} === null)`;
1185
+ }
1186
+ return `typeof ${input.val} === 'object' && ${input.val} instanceof Date`;
1187
+ }
1188
+ function objectTemplate(input) {
1189
+ const parts = [];
1190
+ if (input.discriminatorKey && input.discriminatorValue) {
1191
+ parts.push(
1192
+ `${input.val}.${input.discriminatorKey} === "${input.discriminatorValue}"`
1193
+ );
1194
+ } else {
1195
+ parts.push(`typeof ${input.val} === 'object' && ${input.val} !== null`);
1196
+ }
1197
+ if (!input.schema.additionalProperties) {
1198
+ const allowedKeys = Object.keys(input.schema.properties);
1199
+ for (const key of Object.keys(input.schema.optionalProperties ?? {})) {
1200
+ allowedKeys.push(key);
1201
+ }
1202
+ parts.push(
1203
+ `Object.keys(${input.val}).every((key) => "${input.discriminatorKey}" === key || ${JSON.stringify(allowedKeys)}.includes(key))`
1204
+ );
1205
+ }
1206
+ for (const key of Object.keys(input.schema.properties)) {
1207
+ const prop = input.schema.properties[key];
1208
+ parts.push(
1209
+ schemaTemplate({
1210
+ schema: prop,
1211
+ schemaPath: `${input.schemaPath}/properties/${key}`,
1212
+ instancePath: `${input.instancePath}/${key}`,
1213
+ val: `${input.val}.${key}`,
1214
+ targetVal: "",
1215
+ subFunctions: input.subFunctions
1216
+ })
1217
+ );
1218
+ }
1219
+ if (input.schema.optionalProperties) {
1220
+ for (const key of Object.keys(input.schema.optionalProperties)) {
1221
+ const prop = input.schema.optionalProperties[key];
1222
+ const template = schemaTemplate({
1223
+ schema: prop,
1224
+ schemaPath: `${input.schemaPath}/optionalProperties/${key}`,
1225
+ instancePath: `${input.instancePath}/${key}`,
1226
+ val: `${input.val}.${key}`,
1227
+ targetVal: "",
1228
+ subFunctions: input.subFunctions
1229
+ });
1230
+ parts.push(
1231
+ `(typeof ${input.val}.${key} === 'undefined' || (${template}))`
1232
+ );
1233
+ }
1234
+ }
1235
+ let mainTemplate = parts.join(" && ");
1236
+ const fnName = refFunctionName(input.schema.metadata.id ?? "");
1237
+ if (Object.keys(input.subFunctions).includes(fnName)) {
1238
+ if (!input.subFunctions[fnName]) {
1239
+ input.subFunctions[fnName] = `function ${fnName}(input) {
1240
+ return ${mainTemplate}
1241
+ }`;
1242
+ }
1243
+ mainTemplate = `${fnName}(${input.val})`;
1244
+ }
1245
+ if (input.schema.nullable) {
1246
+ return `((${mainTemplate}) || ${input.val} === null)`;
1247
+ }
1248
+ return mainTemplate;
1249
+ }
1250
+ function enumTemplate(input) {
1251
+ const enumPart = input.schema.enum.map((val) => `${input.val} === "${val}"`).join(" || ");
1252
+ if (input.schema.nullable) {
1253
+ return `((typeof ${input.val} === 'string' && (${enumPart})) || ${input.val} === null)`;
1254
+ }
1255
+ return `(typeof ${input.val} === 'string' && (${enumPart}))`;
1256
+ }
1257
+ function arrayTemplate(input) {
1258
+ const innerTemplate = schemaTemplate({
1259
+ val: "item",
1260
+ instancePath: `${input.instancePath}/item`,
1261
+ schemaPath: `${input.schemaPath}/elements`,
1262
+ schema: input.schema.elements,
1263
+ targetVal: "",
1264
+ subFunctions: input.subFunctions
1265
+ });
1266
+ if (input.schema.nullable) {
1267
+ return `((Array.isArray(${input.val}) && ${input.val}.every((item) => ${innerTemplate})) || ${input.val} === null)`;
1268
+ }
1269
+ return `(Array.isArray(${input.val}) && ${input.val}.every((item) => ${innerTemplate}))`;
1270
+ }
1271
+ function recordTemplate(input) {
1272
+ const subTemplate = schemaTemplate({
1273
+ schema: input.schema.values,
1274
+ instancePath: `${input.instancePath}`,
1275
+ schemaPath: `${input.schemaPath}/values`,
1276
+ val: `${input.val}[key]`,
1277
+ targetVal: "",
1278
+ subFunctions: input.subFunctions
1279
+ });
1280
+ const mainTemplate = `typeof ${input.val} === 'object' && ${input.val} !== null && Object.keys(${input.val}).every((key) => ${subTemplate})`;
1281
+ if (input.schema.nullable) {
1282
+ return `((${mainTemplate}) || ${input.val} === null)`;
1283
+ }
1284
+ return mainTemplate;
1285
+ }
1286
+ function discriminatorTemplate(input) {
1287
+ const parts = [];
1288
+ for (const discriminatorVal of Object.keys(input.schema.mapping)) {
1289
+ const subSchema = input.schema.mapping[discriminatorVal];
1290
+ if (!subSchema) {
1291
+ continue;
1292
+ }
1293
+ parts.push(
1294
+ objectTemplate({
1295
+ val: input.val,
1296
+ targetVal: "",
1297
+ schema: subSchema,
1298
+ schemaPath: `${input.schemaPath}/mapping/${discriminatorVal}`,
1299
+ instancePath: input.instancePath,
1300
+ discriminatorKey: input.schema.discriminator,
1301
+ discriminatorValue: discriminatorVal,
1302
+ subFunctions: input.subFunctions
1303
+ })
1304
+ );
1305
+ }
1306
+ let mainTemplate = `typeof ${input.val} === 'object' && ${input.val} !== null && (${parts.join(" || ")})`;
1307
+ const fnName = refFunctionName(input.schema.metadata.id ?? "");
1308
+ if (Object.keys(input.subFunctions).includes(fnName)) {
1309
+ if (!input.subFunctions[fnName]) {
1310
+ input.subFunctions[fnName] = `function ${fnName}(input) {
1311
+ return ${mainTemplate}
1312
+ }`;
1313
+ }
1314
+ mainTemplate = `${fnName}(${input.val})`;
1315
+ }
1316
+ if (input.schema.nullable) {
1317
+ return `((${mainTemplate}) || ${input.val} === null)`;
1318
+ }
1319
+ return mainTemplate;
1320
+ }
1321
+ function refFunctionName(id) {
1322
+ return `__validate_${id}`;
1323
+ }
1324
+ function refTemplate(input) {
1325
+ const fnName = refFunctionName(input.schema.ref);
1326
+ if (!Object.keys(input.subFunctions).includes(fnName)) {
1327
+ input.subFunctions[fnName] = "";
1328
+ }
1329
+ if (input.schema.nullable) {
1330
+ return `(${input.val} === null || ${fnName}(${input.val}))`;
1331
+ }
1332
+ return `${fnName}(${input.val})`;
1333
+ }
1334
+
1335
+ function compile(schema) {
1336
+ const validateCode = createValidationTemplate("input", schema);
1337
+ const parser = getCompiledParser("input", schema);
1338
+ const parseFn = parser.fn;
1339
+ const serializer = getCompiledSerializer(schema);
1340
+ const serializeFn = serializer.fn;
1341
+ const validate = new Function(
1342
+ "input",
1343
+ validateCode
1344
+ );
1345
+ return {
1346
+ validate,
1347
+ parse(input) {
1348
+ try {
1349
+ return parseFn(input);
1350
+ } catch (err) {
1351
+ const errors = timestamp.errors(schema, input);
1352
+ let errorMessage = err instanceof Error ? err.message : "";
1353
+ if (errors.length) {
1354
+ errorMessage = errors[0].message ?? `Parsing error at ${errors[0].instancePath}`;
1355
+ }
1356
+ throw new timestamp.ValidationError({
1357
+ message: errorMessage,
1358
+ errors
1359
+ });
1360
+ }
1361
+ },
1362
+ safeParse(input) {
1363
+ try {
1364
+ const result = parseFn(input);
1365
+ return {
1366
+ success: true,
1367
+ value: result
1368
+ };
1369
+ } catch (err) {
1370
+ const errors = timestamp.errors(schema, input);
1371
+ let errorMessage = err instanceof Error ? err.message : "";
1372
+ if (errors.length) {
1373
+ errorMessage = errors[0].message ?? `Parsing error at ${errors[0].instancePath}`;
1374
+ }
1375
+ return {
1376
+ success: false,
1377
+ error: new timestamp.ValidationError({
1378
+ message: errorMessage,
1379
+ errors
1380
+ })
1381
+ };
1382
+ }
1383
+ },
1384
+ // eslint-disable-next-line no-eval
1385
+ serialize(input) {
1386
+ try {
1387
+ return serializeFn(input);
1388
+ } catch (err) {
1389
+ const errors = timestamp.errors(schema, input);
1390
+ let errorMessage = err instanceof Error ? err.message : "";
1391
+ if (errors.length) {
1392
+ errorMessage = errors[0].message ?? `Serialization error at ${errors[0].instancePath}`;
1393
+ }
1394
+ throw new timestamp.ValidationError({ message: errorMessage, errors });
1395
+ }
1396
+ },
1397
+ compiledCode: {
1398
+ validate: validateCode,
1399
+ parse: parser.code,
1400
+ serialize: serializer.code
1401
+ }
1402
+ };
1403
+ }
1404
+ function getCompiledParser(input, schema) {
1405
+ const code = createParsingTemplate(input, schema);
1406
+ if (jtdUtils.isSchemaFormType(schema)) {
1407
+ switch (schema.type) {
1408
+ case "float32":
1409
+ case "float64":
1410
+ if (schema.nullable) {
1411
+ return {
1412
+ fn: nullableFloatParser,
1413
+ code
1414
+ };
1415
+ }
1416
+ return {
1417
+ fn: compiledFloatParser,
1418
+ code
1419
+ };
1420
+ case "int64":
1421
+ return {
1422
+ fn(input2) {
1423
+ return bigIntParser(
1424
+ input2,
1425
+ false,
1426
+ schema.nullable ?? false
1427
+ );
1428
+ },
1429
+ code
1430
+ };
1431
+ case "uint64":
1432
+ return {
1433
+ fn(input2) {
1434
+ return bigIntParser(
1435
+ input2,
1436
+ true,
1437
+ schema.nullable ?? false
1438
+ );
1439
+ },
1440
+ code
1441
+ };
1442
+ case "int32":
1443
+ if (schema.nullable) {
1444
+ return {
1445
+ fn(input2) {
1446
+ return nullableIntParser(input2, timestamp.int32Min, timestamp.int32Max);
1447
+ },
1448
+ code
1449
+ };
1450
+ }
1451
+ return {
1452
+ fn(input2) {
1453
+ return intParser(input2, timestamp.int32Min, timestamp.int32Max);
1454
+ },
1455
+ code
1456
+ };
1457
+ case "int16":
1458
+ if (schema.nullable) {
1459
+ return {
1460
+ fn(input2) {
1461
+ return nullableIntParser(input2, timestamp.int16Min, timestamp.int16Max);
1462
+ },
1463
+ code
1464
+ };
1465
+ }
1466
+ return {
1467
+ fn(input2) {
1468
+ return intParser(input2, timestamp.int16Min, timestamp.int16Max);
1469
+ },
1470
+ code
1471
+ };
1472
+ case "int8":
1473
+ if (schema.nullable) {
1474
+ return {
1475
+ fn(input2) {
1476
+ return nullableIntParser(input2, timestamp.int8Min, timestamp.int8Max);
1477
+ },
1478
+ code
1479
+ };
1480
+ }
1481
+ return {
1482
+ fn(input2) {
1483
+ return intParser(input2, timestamp.int8Min, timestamp.int8Max);
1484
+ },
1485
+ code
1486
+ };
1487
+ case "uint32":
1488
+ if (schema.nullable) {
1489
+ return {
1490
+ fn(input2) {
1491
+ return nullableIntParser(
1492
+ input2,
1493
+ timestamp.uint32Min,
1494
+ timestamp.uint32Max
1495
+ );
1496
+ },
1497
+ code
1498
+ };
1499
+ }
1500
+ return {
1501
+ fn(input2) {
1502
+ return intParser(input2, timestamp.uint32Min, timestamp.uint32Max);
1503
+ },
1504
+ code
1505
+ };
1506
+ case "uint16":
1507
+ if (schema.nullable) {
1508
+ return {
1509
+ fn(input2) {
1510
+ return nullableIntParser(
1511
+ input2,
1512
+ timestamp.uint16Min,
1513
+ timestamp.uint16Max
1514
+ );
1515
+ },
1516
+ code
1517
+ };
1518
+ }
1519
+ return {
1520
+ fn(input2) {
1521
+ return intParser(input2, timestamp.uint16Min, timestamp.uint16Max);
1522
+ },
1523
+ code
1524
+ };
1525
+ case "uint8":
1526
+ if (schema.nullable) {
1527
+ return {
1528
+ fn(input2) {
1529
+ return nullableIntParser(input2, timestamp.uint8Min, timestamp.uint8Max);
1530
+ },
1531
+ code
1532
+ };
1533
+ }
1534
+ return {
1535
+ fn(input2) {
1536
+ return intParser(input2, timestamp.uint8Min, timestamp.uint8Max);
1537
+ },
1538
+ code
1539
+ };
1540
+ case "boolean":
1541
+ if (schema.nullable) {
1542
+ return {
1543
+ code,
1544
+ fn(input2) {
1545
+ if (typeof input2 === "string") {
1546
+ if (input2 === "true") {
1547
+ return true;
1548
+ }
1549
+ if (input2 === "false") {
1550
+ return false;
1551
+ }
1552
+ if (input2 === "null") {
1553
+ return null;
1554
+ }
1555
+ }
1556
+ if (typeof input2 === "boolean") {
1557
+ return input2;
1558
+ }
1559
+ if (input2 === null) {
1560
+ return null;
1561
+ }
1562
+ throw new timestamp.ValidationError({
1563
+ message: `Expected boolean. Got ${typeof input2}`,
1564
+ errors: [
1565
+ {
1566
+ instancePath: "",
1567
+ schemaPath: "/type"
1568
+ }
1569
+ ]
1570
+ });
1571
+ }
1572
+ };
1573
+ }
1574
+ return {
1575
+ fn(input2) {
1576
+ if (typeof input2 === "string") {
1577
+ if (input2 === "true") {
1578
+ return true;
1579
+ }
1580
+ if (input2 === "false") {
1581
+ return false;
1582
+ }
1583
+ }
1584
+ if (typeof input2 === "boolean") {
1585
+ return input2;
1586
+ }
1587
+ throw new timestamp.ValidationError({
1588
+ message: `Expected boolean. Got ${typeof input2}`,
1589
+ errors: [
1590
+ {
1591
+ instancePath: "",
1592
+ schemaPath: "/type"
1593
+ }
1594
+ ]
1595
+ });
1596
+ },
1597
+ code
1598
+ };
1599
+ case "string":
1600
+ if (schema.nullable) {
1601
+ return {
1602
+ fn(input2) {
1603
+ if (typeof input2 === "string") {
1604
+ if (input2 === "null") {
1605
+ return null;
1606
+ }
1607
+ return input2;
1608
+ }
1609
+ if (input2 === null) {
1610
+ return null;
1611
+ }
1612
+ throw new timestamp.ValidationError({
1613
+ message: `Expected string or null. Got ${typeof input2}.`,
1614
+ errors: [
1615
+ {
1616
+ instancePath: "",
1617
+ schemaPath: "/type"
1618
+ }
1619
+ ]
1620
+ });
1621
+ },
1622
+ code
1623
+ };
1624
+ }
1625
+ return {
1626
+ fn(input2) {
1627
+ if (typeof input2 === "string") {
1628
+ return input2;
1629
+ }
1630
+ throw new timestamp.ValidationError({
1631
+ message: `Expected string. Got ${typeof input2}.`,
1632
+ errors: [
1633
+ {
1634
+ instancePath: "",
1635
+ schemaPath: "/type"
1636
+ }
1637
+ ]
1638
+ });
1639
+ },
1640
+ code
1641
+ };
1642
+ case "timestamp":
1643
+ if (schema.nullable) {
1644
+ return {
1645
+ fn(input2) {
1646
+ if (typeof input2 === "string") {
1647
+ const parsedInput = new Date(input2);
1648
+ if (!Number.isNaN(parsedInput.getMonth())) {
1649
+ return parsedInput;
1650
+ }
1651
+ if (input2 === "null") {
1652
+ return null;
1653
+ }
1654
+ }
1655
+ if (typeof input2 === "object" && input2 instanceof Date) {
1656
+ return input2;
1657
+ }
1658
+ if (input2 === null) {
1659
+ return null;
1660
+ }
1661
+ throw new timestamp.ValidationError({
1662
+ message: `Expected instanceof Date, ISO Date string, or null. Got ${typeof input2}.`,
1663
+ errors: [
1664
+ {
1665
+ instancePath: "",
1666
+ schemaPath: "/type"
1667
+ }
1668
+ ]
1669
+ });
1670
+ },
1671
+ code
1672
+ };
1673
+ }
1674
+ return {
1675
+ fn(input2) {
1676
+ if (typeof input2 === "string") {
1677
+ const parsedInput = new Date(input2);
1678
+ if (!Number.isNaN(parsedInput.getMonth())) {
1679
+ return parsedInput;
1680
+ }
1681
+ }
1682
+ if (typeof input2 === "object" && input2 instanceof Date) {
1683
+ return input2;
1684
+ }
1685
+ throw new timestamp.ValidationError({
1686
+ message: `Expected instance of Date or ISO date string. Got ${typeof input2}.`,
1687
+ errors: [
1688
+ {
1689
+ instancePath: "",
1690
+ schemaPath: "/type"
1691
+ }
1692
+ ]
1693
+ });
1694
+ },
1695
+ code
1696
+ };
1697
+ }
1698
+ }
1699
+ if (jtdUtils.isSchemaFormEnum(schema)) {
1700
+ if (schema.nullable) {
1701
+ return {
1702
+ fn(input2) {
1703
+ if (typeof input2 === "string") {
1704
+ for (const val of schema.enum) {
1705
+ if (input2 === val) {
1706
+ return val;
1707
+ }
1708
+ }
1709
+ if (input2 === "null") {
1710
+ return null;
1711
+ }
1712
+ }
1713
+ if (input2 === null) {
1714
+ return null;
1715
+ }
1716
+ throw new timestamp.ValidationError({
1717
+ message: `Expected one of the following values: [${schema.enum.join(
1718
+ ", "
1719
+ )}] or null. Got ${typeof input2}.`,
1720
+ errors: [
1721
+ {
1722
+ instancePath: "",
1723
+ schemaPath: "/enum"
1724
+ }
1725
+ ]
1726
+ });
1727
+ },
1728
+ code
1729
+ };
1730
+ }
1731
+ return {
1732
+ fn(input2) {
1733
+ if (typeof input2 === "string") {
1734
+ for (const val of schema.enum) {
1735
+ if (input2 === val) {
1736
+ return val;
1737
+ }
1738
+ }
1739
+ }
1740
+ throw new timestamp.ValidationError({
1741
+ message: `Expected one of the following values: [${schema.enum.join(
1742
+ ", "
1743
+ )}]. Got ${typeof input2}.`,
1744
+ errors: [
1745
+ {
1746
+ instancePath: "",
1747
+ schemaPath: "/enum"
1748
+ }
1749
+ ]
1750
+ });
1751
+ },
1752
+ code
1753
+ };
1754
+ }
1755
+ return { fn: new Function(input, code), code };
1756
+ }
1757
+ function compiledFloatParser(input) {
1758
+ if (typeof input === "string") {
1759
+ const parsedVal = Number(input);
1760
+ if (!Number.isNaN(parsedVal)) {
1761
+ return parsedVal;
1762
+ }
1763
+ throw new timestamp.ValidationError({
1764
+ message: `Unable to parse number from ${input}`,
1765
+ errors: [
1766
+ {
1767
+ instancePath: "",
1768
+ schemaPath: "/type"
1769
+ }
1770
+ ]
1771
+ });
1772
+ }
1773
+ if (typeof input === "number" && !Number.isNaN(input)) {
1774
+ return input;
1775
+ }
1776
+ throw new timestamp.ValidationError({
1777
+ message: `Expected number. Got ${typeof input}`,
1778
+ errors: [
1779
+ {
1780
+ instancePath: "",
1781
+ schemaPath: "/type"
1782
+ }
1783
+ ]
1784
+ });
1785
+ }
1786
+ function nullableFloatParser(input) {
1787
+ if (typeof input === "string") {
1788
+ const parsedVal = Number(input);
1789
+ if (!Number.isNaN(parsedVal)) {
1790
+ return parsedVal;
1791
+ }
1792
+ if (input === "null") {
1793
+ return null;
1794
+ }
1795
+ throw new timestamp.ValidationError({
1796
+ message: `Unable to parse number from ${input}`,
1797
+ errors: [
1798
+ {
1799
+ instancePath: "",
1800
+ schemaPath: "/type"
1801
+ }
1802
+ ]
1803
+ });
1804
+ }
1805
+ if (typeof input === "number" && !Number.isNaN(input)) {
1806
+ return input;
1807
+ }
1808
+ if (input === null) {
1809
+ return null;
1810
+ }
1811
+ throw new timestamp.ValidationError({
1812
+ message: `Expected number or null. Got ${typeof input}`,
1813
+ errors: [
1814
+ {
1815
+ instancePath: "",
1816
+ schemaPath: "/type"
1817
+ }
1818
+ ]
1819
+ });
1820
+ }
1821
+ function bigIntParser(input, isUnsigned, isNullable) {
1822
+ if (typeof input === "string" || typeof input === "number") {
1823
+ if (isNullable && input === "null") {
1824
+ return null;
1825
+ }
1826
+ try {
1827
+ const val = BigInt(input);
1828
+ if (isUnsigned) {
1829
+ if (val >= BigInt("0")) {
1830
+ return val;
1831
+ }
1832
+ throw new timestamp.ValidationError({
1833
+ message: "uint64 must be greater than or equal to 0",
1834
+ errors: [
1835
+ {
1836
+ message: "uint64 must be greater than or equal to 0",
1837
+ schemaPath: "/type",
1838
+ instancePath: ""
1839
+ }
1840
+ ]
1841
+ });
1842
+ }
1843
+ return val;
1844
+ } catch (err) {
1845
+ throw new timestamp.ValidationError({
1846
+ message: `Error transforming ${input} to BigInt`,
1847
+ errors: [
1848
+ {
1849
+ schemaPath: "/type",
1850
+ instancePath: "",
1851
+ data: err
1852
+ }
1853
+ ]
1854
+ });
1855
+ }
1856
+ }
1857
+ if (typeof input === "bigint") {
1858
+ if (isUnsigned) {
1859
+ if (input >= BigInt("0")) {
1860
+ return input;
1861
+ }
1862
+ throw new timestamp.ValidationError({
1863
+ message: "uint64 must be greater than or equal to 0",
1864
+ errors: [
1865
+ {
1866
+ message: "uint64 must be greater than or equal to 0",
1867
+ schemaPath: "/type",
1868
+ instancePath: ""
1869
+ }
1870
+ ]
1871
+ });
1872
+ }
1873
+ return input;
1874
+ }
1875
+ if (isNullable && input === null) {
1876
+ return null;
1877
+ }
1878
+ throw new timestamp.ValidationError({
1879
+ message: "Expected BigInt or Integer string",
1880
+ errors: [
1881
+ {
1882
+ schemaPath: "/type",
1883
+ instancePath: ""
1884
+ }
1885
+ ]
1886
+ });
1887
+ }
1888
+ function nullableIntParser(input, minNum, maxNum) {
1889
+ if (typeof input === "string") {
1890
+ const parsedInput = Number(input);
1891
+ if (Number.isInteger(parsedInput) && parsedInput >= minNum && parsedInput <= maxNum) {
1892
+ return parsedInput;
1893
+ }
1894
+ if (input === "null") {
1895
+ return null;
1896
+ }
1897
+ }
1898
+ if (typeof input === "number" && Number.isInteger(input) && input >= minNum && input <= maxNum) {
1899
+ return input;
1900
+ }
1901
+ if (input === null) {
1902
+ return null;
1903
+ }
1904
+ throw new timestamp.ValidationError({
1905
+ message: `Expected valid integer between ${minNum} & ${maxNum} or null. Got ${typeof input}.`,
1906
+ errors: [
1907
+ {
1908
+ instancePath: "",
1909
+ schemaPath: "/type"
1910
+ }
1911
+ ]
1912
+ });
1913
+ }
1914
+ function intParser(input, minNum, maxNum) {
1915
+ if (typeof input === "string") {
1916
+ const parsedInput = Number(input);
1917
+ if (Number.isInteger(parsedInput) && parsedInput >= minNum && parsedInput <= maxNum) {
1918
+ return parsedInput;
1919
+ }
1920
+ }
1921
+ if (typeof input === "number" && Number.isInteger(input) && input >= minNum && input <= maxNum) {
1922
+ return input;
1923
+ }
1924
+ throw new timestamp.ValidationError({
1925
+ message: `Expected valid integer between ${minNum} & ${maxNum}`,
1926
+ errors: [
1927
+ {
1928
+ instancePath: "",
1929
+ schemaPath: "/type"
1930
+ }
1931
+ ]
1932
+ });
1933
+ }
1934
+ function getCompiledSerializer(schema) {
1935
+ const code = createSerializationV2Template("input", schema);
1936
+ if (jtdUtils.isSchemaFormType(schema)) {
1937
+ switch (schema.type) {
1938
+ case "string":
1939
+ if (schema.nullable) {
1940
+ return {
1941
+ fn(input) {
1942
+ if (typeof input === "string") {
1943
+ return input;
1944
+ }
1945
+ return "null";
1946
+ },
1947
+ code
1948
+ };
1949
+ }
1950
+ return {
1951
+ fn(input) {
1952
+ return input;
1953
+ },
1954
+ code
1955
+ };
1956
+ case "timestamp":
1957
+ if (schema.nullable) {
1958
+ return {
1959
+ fn(input) {
1960
+ if (typeof input === "object" && input !== null) {
1961
+ return input.toISOString();
1962
+ }
1963
+ return "null";
1964
+ },
1965
+ code
1966
+ };
1967
+ }
1968
+ return {
1969
+ fn(input) {
1970
+ return input.toISOString();
1971
+ },
1972
+ code
1973
+ };
1974
+ case "boolean":
1975
+ if (schema.nullable) {
1976
+ return {
1977
+ fn(input) {
1978
+ if (typeof input === "boolean") {
1979
+ return `${input}`;
1980
+ }
1981
+ return "null";
1982
+ },
1983
+ code
1984
+ };
1985
+ }
1986
+ return {
1987
+ fn(input) {
1988
+ return `${input}`;
1989
+ },
1990
+ code
1991
+ };
1992
+ case "float32":
1993
+ case "float64":
1994
+ case "int8":
1995
+ case "int16":
1996
+ case "int32":
1997
+ case "uint8":
1998
+ case "uint16":
1999
+ case "uint32":
2000
+ if (schema.nullable) {
2001
+ return {
2002
+ fn(input) {
2003
+ if (typeof input === "number") {
2004
+ return `${input}`;
2005
+ }
2006
+ return `null`;
2007
+ },
2008
+ code
2009
+ };
2010
+ }
2011
+ return {
2012
+ fn(input) {
2013
+ return `${input}`;
2014
+ },
2015
+ code
2016
+ };
2017
+ case "int64":
2018
+ case "uint64":
2019
+ if (schema.nullable) {
2020
+ return {
2021
+ fn(input) {
2022
+ if (typeof input === "bigint") {
2023
+ return input.toString();
2024
+ }
2025
+ return "null";
2026
+ },
2027
+ code
2028
+ };
2029
+ }
2030
+ return {
2031
+ fn(input) {
2032
+ return input.toString();
2033
+ },
2034
+ code
2035
+ };
2036
+ }
2037
+ }
2038
+ if (jtdUtils.isSchemaFormEnum(schema)) {
2039
+ if (schema.nullable) {
2040
+ return {
2041
+ fn(input) {
2042
+ if (typeof input === "string" && schema.enum.includes(input)) {
2043
+ return input;
2044
+ }
2045
+ return "null";
2046
+ },
2047
+ code
2048
+ };
2049
+ }
2050
+ return {
2051
+ fn(input) {
2052
+ return input;
2053
+ },
2054
+ code
2055
+ };
2056
+ }
2057
+ const fn = new Function("input", code);
2058
+ return {
2059
+ fn,
2060
+ code
2061
+ };
2062
+ }
2063
+
2064
+ const _namespace = {
2065
+ __proto__: null,
2066
+ any: timestamp.any,
2067
+ array: timestamp.array,
2068
+ boolean: timestamp.boolean,
2069
+ clone: timestamp.clone,
2070
+ coerce: timestamp.coerce,
2071
+ compile: compile,
2072
+ discriminator: timestamp.discriminator,
2073
+ enumerator: timestamp.enumerator,
2074
+ errors: timestamp.errors,
2075
+ extend: timestamp.extend,
2076
+ float32: timestamp.float32,
2077
+ float64: timestamp.float64,
2078
+ int16: timestamp.int16,
2079
+ int32: timestamp.int32,
2080
+ int64: timestamp.int64,
2081
+ int8: timestamp.int8,
2082
+ nullable: timestamp.nullable,
2083
+ number: timestamp.number,
2084
+ object: timestamp.object,
2085
+ omit: timestamp.omit,
2086
+ optional: timestamp.optional,
2087
+ parse: timestamp.parse,
2088
+ partial: timestamp.partial,
2089
+ pick: timestamp.pick,
2090
+ record: timestamp.record,
2091
+ recursive: timestamp.recursive,
2092
+ safeCoerce: timestamp.safeCoerce,
2093
+ safeParse: timestamp.safeParse,
2094
+ serialize: timestamp.serialize,
2095
+ string: timestamp.string,
2096
+ stringEnum: timestamp.stringEnum,
2097
+ timestamp: timestamp.timestamp,
2098
+ uint16: timestamp.uint16,
2099
+ uint32: timestamp.uint32,
2100
+ uint64: timestamp.uint64,
2101
+ uint8: timestamp.uint8,
2102
+ validate: timestamp.validate
2103
+ };
2104
+
2105
+ function isAAdaptedSchema(input) {
2106
+ return timestamp.isASchema(input) && "_isAdaptedSchema" in input.metadata[timestamp.SCHEMA_METADATA] && input.metadata[timestamp.SCHEMA_METADATA]._isAdaptedSchema === true;
2107
+ }
2108
+
2109
+ exports.NumberTypeValues = timestamp.NumberTypeValues;
2110
+ exports.SCHEMA_METADATA = timestamp.SCHEMA_METADATA;
2111
+ exports.ValidationError = timestamp.ValidationError;
2112
+ exports.any = timestamp.any;
2113
+ exports.array = timestamp.array;
2114
+ exports.boolean = timestamp.boolean;
2115
+ exports.clone = timestamp.clone;
2116
+ exports.coerce = timestamp.coerce;
2117
+ exports.discriminator = timestamp.discriminator;
2118
+ exports.enumerator = timestamp.enumerator;
2119
+ exports.errors = timestamp.errors;
2120
+ exports.extend = timestamp.extend;
2121
+ exports.float32 = timestamp.float32;
2122
+ exports.float64 = timestamp.float64;
2123
+ exports.int16 = timestamp.int16;
2124
+ exports.int16Max = timestamp.int16Max;
2125
+ exports.int16Min = timestamp.int16Min;
2126
+ exports.int32 = timestamp.int32;
2127
+ exports.int32Max = timestamp.int32Max;
2128
+ exports.int32Min = timestamp.int32Min;
2129
+ exports.int64 = timestamp.int64;
2130
+ exports.int64Max = timestamp.int64Max;
2131
+ exports.int64Min = timestamp.int64Min;
2132
+ exports.int8 = timestamp.int8;
2133
+ exports.int8Max = timestamp.int8Max;
2134
+ exports.int8Min = timestamp.int8Min;
2135
+ exports.isAAraySchema = timestamp.isAAraySchema;
2136
+ exports.isADiscriminatorSchema = timestamp.isADiscriminatorSchema;
2137
+ exports.isAObjectSchema = timestamp.isAObjectSchema;
2138
+ exports.isARecordSchema = timestamp.isARecordSchema;
2139
+ exports.isARefSchema = timestamp.isARefSchema;
2140
+ exports.isAScalarSchema = timestamp.isAScalarSchema;
2141
+ exports.isASchema = timestamp.isASchema;
2142
+ exports.isAStringEnumSchema = timestamp.isAStringEnumSchema;
2143
+ exports.isObject = timestamp.isObject;
2144
+ exports.isValidationError = timestamp.isValidationError;
2145
+ exports.nullable = timestamp.nullable;
2146
+ exports.number = timestamp.number;
2147
+ exports.object = timestamp.object;
2148
+ exports.omit = timestamp.omit;
2149
+ exports.optional = timestamp.optional;
2150
+ exports.parse = timestamp.parse;
2151
+ exports.parseObjectSchema = timestamp.parseObjectSchema;
2152
+ exports.partial = timestamp.partial;
2153
+ exports.pick = timestamp.pick;
2154
+ exports.record = timestamp.record;
2155
+ exports.recursive = timestamp.recursive;
2156
+ exports.safeCoerce = timestamp.safeCoerce;
2157
+ exports.safeParse = timestamp.safeParse;
2158
+ exports.sanitizeJson = timestamp.sanitizeJson;
2159
+ exports.serialize = timestamp.serialize;
2160
+ exports.serializeObject = timestamp.serializeObject;
2161
+ exports.serializeSmallString = timestamp.serializeSmallString;
2162
+ exports.string = timestamp.string;
2163
+ exports.stringEnum = timestamp.stringEnum;
2164
+ exports.timestamp = timestamp.timestamp;
2165
+ exports.uint16 = timestamp.uint16;
2166
+ exports.uint16Max = timestamp.uint16Max;
2167
+ exports.uint16Min = timestamp.uint16Min;
2168
+ exports.uint32 = timestamp.uint32;
2169
+ exports.uint32Max = timestamp.uint32Max;
2170
+ exports.uint32Min = timestamp.uint32Min;
2171
+ exports.uint64 = timestamp.uint64;
2172
+ exports.uint64Max = timestamp.uint64Max;
2173
+ exports.uint64Min = timestamp.uint64Min;
2174
+ exports.uint8 = timestamp.uint8;
2175
+ exports.uint8Max = timestamp.uint8Max;
2176
+ exports.uint8Min = timestamp.uint8Min;
2177
+ exports.validate = timestamp.validate;
2178
+ exports.validateObjectSchema = timestamp.validateObjectSchema;
2179
+ exports.a = _namespace;
2180
+ exports.compile = compile;
2181
+ exports.getCompiledParser = getCompiledParser;
2182
+ exports.getCompiledSerializer = getCompiledSerializer;
2183
+ exports.getSchemaParsingCode = createParsingTemplate;
2184
+ exports.getSchemaSerializationCode = createSerializationV2Template;
2185
+ exports.getSchemaValidationCode = createValidationTemplate;
2186
+ exports.isAAdaptedSchema = isAAdaptedSchema;