@deepseek-ai/schemastery 3.18.1-rc.1

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/lib/index.cjs ADDED
@@ -0,0 +1,596 @@
1
+ let _deepseek_ai_cosmokit = require("@deepseek-ai/cosmokit");
2
+ //#region lib/types/index.js
3
+ const kSchema = Symbol.for("schemastery");
4
+ const kValidationError = Symbol.for("ValidationError");
5
+ globalThis.__schemastery_index__ ??= 0;
6
+ globalThis.__schemastery_refs__ = void 0;
7
+ var ValidationError = class extends TypeError {
8
+ options;
9
+ name = "ValidationError";
10
+ constructor(message, options) {
11
+ let prefix = "$";
12
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
13
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
14
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
15
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
16
+ super((prefix === "$" ? "" : `${prefix} `) + message);
17
+ this.options = options;
18
+ }
19
+ static is(error) {
20
+ return !!error?.[kValidationError];
21
+ }
22
+ };
23
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
24
+ const Schema = function(options) {
25
+ const schema = function(data, options = {}) {
26
+ return Schema.resolve(data, schema, options)[0];
27
+ };
28
+ if (options.refs) {
29
+ const refs = (0, _deepseek_ai_cosmokit.valueMap)(options.refs, (options) => new Schema(options));
30
+ const getRef = (uid) => refs[uid];
31
+ for (const key in refs) {
32
+ const options = refs[key];
33
+ options.sKey = getRef(options.sKey);
34
+ options.inner = getRef(options.inner);
35
+ options.list = options.list && options.list.map(getRef);
36
+ options.dict = options.dict && (0, _deepseek_ai_cosmokit.valueMap)(options.dict, getRef);
37
+ }
38
+ return refs[options.uid];
39
+ }
40
+ Object.assign(schema, options);
41
+ if (typeof schema.callback === "string") try {
42
+ schema.callback = new Function("return " + schema.callback)();
43
+ } catch {}
44
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
45
+ Object.setPrototypeOf(schema, Schema.prototype);
46
+ schema.meta ||= {};
47
+ schema.toString = schema.toString.bind(schema);
48
+ return schema;
49
+ };
50
+ Schema.prototype = Object.create(Function.prototype);
51
+ Schema.prototype[kSchema] = true;
52
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
53
+ return {
54
+ version: 1,
55
+ vendor: "schemastery",
56
+ validate: (value) => {
57
+ try {
58
+ return { value: Schema.resolve(value, this, {})[0] };
59
+ } catch (error) {
60
+ if (ValidationError.is(error)) return { issues: [{
61
+ message: error.message,
62
+ path: error.options.path
63
+ }] };
64
+ throw error;
65
+ }
66
+ }
67
+ };
68
+ } });
69
+ Schema.ValidationError = ValidationError;
70
+ Schema.prototype.toJSON = function toJSON() {
71
+ if (globalThis.__schemastery_refs__) {
72
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
73
+ return this.uid;
74
+ }
75
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
76
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
77
+ const result = {
78
+ uid: this.uid,
79
+ refs: globalThis.__schemastery_refs__
80
+ };
81
+ globalThis.__schemastery_refs__ = void 0;
82
+ return result;
83
+ };
84
+ Schema.prototype.set = function set(key, value) {
85
+ this.dict[key] = value;
86
+ return this;
87
+ };
88
+ Schema.prototype.push = function push(value) {
89
+ this.list.push(value);
90
+ return this;
91
+ };
92
+ function mergeDesc(original, messages) {
93
+ const result = typeof original === "string" ? { "": original } : { ...original };
94
+ for (const locale in messages) {
95
+ const value = messages[locale];
96
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
97
+ else if (typeof value === "string") result[locale] = value;
98
+ }
99
+ return result;
100
+ }
101
+ function getInner(value) {
102
+ return value?.$value ?? value?.$inner;
103
+ }
104
+ function extractKeys(data) {
105
+ return (0, _deepseek_ai_cosmokit.filterKeys)(data ?? {}, (key) => !key.startsWith("$"));
106
+ }
107
+ Schema.prototype.i18n = function i18n(messages) {
108
+ const schema = Schema(this);
109
+ const desc = mergeDesc(schema.meta.description, messages);
110
+ if (Object.keys(desc).length) schema.meta.description = desc;
111
+ if (schema.dict) schema.dict = (0, _deepseek_ai_cosmokit.valueMap)(schema.dict, (inner, key) => {
112
+ return inner.i18n((0, _deepseek_ai_cosmokit.valueMap)(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
113
+ });
114
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
115
+ return inner.i18n((0, _deepseek_ai_cosmokit.valueMap)(messages, (data = {}) => {
116
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
117
+ if (Array.isArray(data)) return data[index];
118
+ return extractKeys(data);
119
+ }));
120
+ });
121
+ if (schema.inner) schema.inner = schema.inner.i18n((0, _deepseek_ai_cosmokit.valueMap)(messages, (data) => {
122
+ if (getInner(data)) return getInner(data);
123
+ return extractKeys(data);
124
+ }));
125
+ if (schema.sKey) schema.sKey = schema.sKey.i18n((0, _deepseek_ai_cosmokit.valueMap)(messages, (data) => data?.$key));
126
+ return schema;
127
+ };
128
+ Schema.prototype.extra = function extra(key, value) {
129
+ const schema = Schema(this);
130
+ schema.meta = {
131
+ ...schema.meta,
132
+ [key]: value
133
+ };
134
+ return schema;
135
+ };
136
+ for (const key of [
137
+ "required",
138
+ "disabled",
139
+ "collapse",
140
+ "hidden",
141
+ "loose"
142
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
143
+ const schema = Schema(this);
144
+ schema.meta = {
145
+ ...schema.meta,
146
+ [key]: value
147
+ };
148
+ return schema;
149
+ } });
150
+ Schema.prototype.deprecated = function deprecated() {
151
+ const schema = Schema(this);
152
+ schema.meta.badges ||= [];
153
+ schema.meta.badges.push({
154
+ text: "deprecated",
155
+ type: "danger"
156
+ });
157
+ return schema;
158
+ };
159
+ Schema.prototype.experimental = function experimental() {
160
+ const schema = Schema(this);
161
+ schema.meta.badges ||= [];
162
+ schema.meta.badges.push({
163
+ text: "experimental",
164
+ type: "warning"
165
+ });
166
+ return schema;
167
+ };
168
+ Schema.prototype.pattern = function pattern(regexp) {
169
+ const schema = Schema(this);
170
+ const pattern = (0, _deepseek_ai_cosmokit.pick)(regexp, ["source", "flags"]);
171
+ schema.meta = {
172
+ ...schema.meta,
173
+ pattern
174
+ };
175
+ return schema;
176
+ };
177
+ Schema.prototype.simplify = function simplify(value) {
178
+ if ((0, _deepseek_ai_cosmokit.deepEqual)(value, this.meta.default, this.type === "dict")) return null;
179
+ if ((0, _deepseek_ai_cosmokit.isNullable)(value)) return value;
180
+ if (this.type === "object" || this.type === "dict") {
181
+ const result = {};
182
+ for (const key in value) {
183
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
184
+ if (this.type === "dict" || !(0, _deepseek_ai_cosmokit.isNullable)(item)) result[key] = item;
185
+ }
186
+ if ((0, _deepseek_ai_cosmokit.deepEqual)(result, this.meta.default, this.type === "dict")) return null;
187
+ return result;
188
+ } else if (this.type === "array" || this.type === "tuple") {
189
+ const result = [];
190
+ value.forEach((value, index) => {
191
+ const schema = this.type === "array" ? this.inner : this.list[index];
192
+ const item = schema ? schema.simplify(value) : value;
193
+ result.push(item);
194
+ });
195
+ return result;
196
+ } else if (this.type === "intersect") {
197
+ const result = {};
198
+ for (const item of this.list) Object.assign(result, item.simplify(value));
199
+ return result;
200
+ } else if (this.type === "union") for (const schema of this.list) try {
201
+ Schema.resolve(value, schema, {});
202
+ return schema.simplify(value);
203
+ } catch {}
204
+ return value;
205
+ };
206
+ Schema.prototype.toString = function toString(inline) {
207
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
208
+ };
209
+ Schema.prototype.role = function role(role, extra) {
210
+ const schema = Schema(this);
211
+ schema.meta = {
212
+ ...schema.meta,
213
+ role,
214
+ extra
215
+ };
216
+ return schema;
217
+ };
218
+ for (const key of [
219
+ "default",
220
+ "link",
221
+ "comment",
222
+ "description",
223
+ "max",
224
+ "min",
225
+ "step"
226
+ ]) Object.assign(Schema.prototype, { [key](value) {
227
+ const schema = Schema(this);
228
+ schema.meta = {
229
+ ...schema.meta,
230
+ [key]: value
231
+ };
232
+ return schema;
233
+ } });
234
+ const resolvers = {};
235
+ Schema.extend = function extend(type, resolve) {
236
+ resolvers[type] = resolve;
237
+ };
238
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
239
+ if (!schema) return [data];
240
+ if (options.ignore?.(data, schema)) return [data];
241
+ if ((0, _deepseek_ai_cosmokit.isNullable)(data) && schema.type !== "lazy") {
242
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
243
+ let current = schema;
244
+ let fallback = schema.meta.default;
245
+ while (current?.type === "intersect" && (0, _deepseek_ai_cosmokit.isNullable)(fallback)) {
246
+ current = current.list[0];
247
+ fallback = current?.meta.default;
248
+ }
249
+ if ((0, _deepseek_ai_cosmokit.isNullable)(fallback)) return [data];
250
+ data = (0, _deepseek_ai_cosmokit.clone)(fallback);
251
+ }
252
+ const callback = resolvers[schema.type];
253
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
254
+ try {
255
+ return callback(data, schema, options, strict);
256
+ } catch (error) {
257
+ if (!schema.meta.loose) throw error;
258
+ return [schema.meta.default];
259
+ }
260
+ };
261
+ Schema.from = function from(source) {
262
+ if ((0, _deepseek_ai_cosmokit.isNullable)(source)) return Schema.any();
263
+ else if ([
264
+ "string",
265
+ "number",
266
+ "boolean"
267
+ ].includes(typeof source)) return Schema.const(source).required();
268
+ else if (source[kSchema]) return source;
269
+ else if (typeof source === "function") switch (source) {
270
+ case String: return Schema.string().required();
271
+ case Number: return Schema.number().required();
272
+ case Boolean: return Schema.boolean().required();
273
+ case Function: return Schema.function().required();
274
+ default: return Schema.is(source).required();
275
+ }
276
+ else throw new TypeError(`cannot infer schema from ${source}`);
277
+ };
278
+ Schema.lazy = function lazy(builder) {
279
+ const toJSON = () => {
280
+ if (!schema.inner[kSchema]) {
281
+ schema.inner = schema.builder();
282
+ schema.inner.meta = {
283
+ ...schema.meta,
284
+ ...schema.inner.meta
285
+ };
286
+ }
287
+ return schema.inner.toJSON();
288
+ };
289
+ const schema = new Schema({
290
+ type: "lazy",
291
+ builder,
292
+ inner: { toJSON }
293
+ });
294
+ return schema;
295
+ };
296
+ Schema.natural = function natural() {
297
+ return Schema.number().step(1).min(0);
298
+ };
299
+ Schema.percent = function percent() {
300
+ return Schema.number().step(.01).min(0).max(1).role("slider");
301
+ };
302
+ Schema.date = function date() {
303
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
304
+ const date = new Date(value);
305
+ if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
306
+ return date;
307
+ }, true)]);
308
+ };
309
+ Schema.regExp = function regExp(flag = "") {
310
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
311
+ try {
312
+ return new RegExp(value, flag);
313
+ } catch (e) {
314
+ throw new ValidationError(e.message, options);
315
+ }
316
+ }, true)]);
317
+ };
318
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
319
+ return Schema.union([
320
+ Schema.is(ArrayBuffer),
321
+ Schema.is(SharedArrayBuffer),
322
+ Schema.transform(Schema.any(), (value, options) => {
323
+ if (_deepseek_ai_cosmokit.Binary.isSource(value)) return _deepseek_ai_cosmokit.Binary.fromSource(value);
324
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
325
+ }, true),
326
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
327
+ try {
328
+ return encoding === "base64" ? _deepseek_ai_cosmokit.Binary.fromBase64(value) : _deepseek_ai_cosmokit.Binary.fromHex(value);
329
+ } catch (e) {
330
+ throw new ValidationError(e.message, options);
331
+ }
332
+ }, true)] : []
333
+ ]);
334
+ };
335
+ Schema.extend("lazy", (data, schema, options, strict) => {
336
+ if (!schema.inner[kSchema]) {
337
+ schema.inner = schema.builder();
338
+ schema.inner.meta = {
339
+ ...schema.meta,
340
+ ...schema.inner.meta
341
+ };
342
+ }
343
+ return Schema.resolve(data, schema.inner, options, strict);
344
+ });
345
+ Schema.extend("any", (data) => {
346
+ return [data];
347
+ });
348
+ Schema.extend("never", (data, _, options) => {
349
+ throw new ValidationError(`expected nullable but got ${data}`, options);
350
+ });
351
+ Schema.extend("const", (data, { value }, options) => {
352
+ if ((0, _deepseek_ai_cosmokit.deepEqual)(data, value)) return [value];
353
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
354
+ });
355
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
356
+ const { max = Infinity, min = -Infinity } = meta;
357
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
358
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
359
+ }
360
+ Schema.extend("string", (data, { meta }, options) => {
361
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
362
+ if (meta.pattern) {
363
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
364
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
365
+ }
366
+ checkWithinRange(data.length, meta, "string length", options);
367
+ return [data];
368
+ });
369
+ function decimalShift(data, digits) {
370
+ const str = data.toString();
371
+ if (str.includes("e")) return data * Math.pow(10, digits);
372
+ const index = str.indexOf(".");
373
+ if (index === -1) return data * Math.pow(10, digits);
374
+ const frac = str.slice(index + 1);
375
+ const integer = str.slice(0, index);
376
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
377
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
378
+ }
379
+ function isMultipleOf(data, min, step) {
380
+ step = Math.abs(step);
381
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
382
+ const index = step.toString().indexOf(".");
383
+ const digits = step.toString().slice(index + 1).length;
384
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
385
+ }
386
+ Schema.extend("number", (data, { meta }, options) => {
387
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
388
+ checkWithinRange(data, meta, "number", options);
389
+ const { step } = meta;
390
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
391
+ return [data];
392
+ });
393
+ Schema.extend("boolean", (data, _, options) => {
394
+ if (typeof data === "boolean") return [data];
395
+ throw new ValidationError(`expected boolean but got ${data}`, options);
396
+ });
397
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
398
+ let value = 0, keys = [];
399
+ if (typeof data === "number") {
400
+ value = data;
401
+ for (const key in bits) if (data & bits[key]) keys.push(key);
402
+ } else if (Array.isArray(data)) {
403
+ keys = data;
404
+ for (const key of keys) {
405
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
406
+ if (key in bits) value |= bits[key];
407
+ }
408
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
409
+ if (value === meta.default) return [value];
410
+ return [value, keys];
411
+ });
412
+ Schema.extend("function", (data, _, options) => {
413
+ if (typeof data === "function") return [data];
414
+ throw new ValidationError(`expected function but got ${data}`, options);
415
+ });
416
+ Schema.extend("is", (data, { constructor }, options) => {
417
+ if (typeof constructor === "function") {
418
+ if (data instanceof constructor) return [data];
419
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
420
+ } else {
421
+ if ((0, _deepseek_ai_cosmokit.isNullable)(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
422
+ let prototype = Object.getPrototypeOf(data);
423
+ while (prototype) {
424
+ if (prototype.constructor?.name === constructor) return [data];
425
+ prototype = Object.getPrototypeOf(prototype);
426
+ }
427
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
428
+ }
429
+ });
430
+ function property(data, key, schema, options) {
431
+ try {
432
+ const [value, adapted] = Schema.resolve(data[key], schema, {
433
+ ...options,
434
+ path: [...options.path || [], key]
435
+ });
436
+ if (adapted !== void 0) data[key] = adapted;
437
+ return value;
438
+ } catch (e) {
439
+ if (!options?.autofix) throw e;
440
+ delete data[key];
441
+ return schema.meta.default;
442
+ }
443
+ }
444
+ Schema.extend("array", (data, { inner, meta }, options) => {
445
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
446
+ checkWithinRange(data.length, meta, "array length", options, !(0, _deepseek_ai_cosmokit.isNullable)(inner.meta.default));
447
+ return [data.map((_, index) => property(data, index, inner, options))];
448
+ });
449
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
450
+ if (!(0, _deepseek_ai_cosmokit.isPlainObject)(data)) throw new ValidationError(`expected object but got ${data}`, options);
451
+ const result = {};
452
+ for (const key in data) {
453
+ let rKey;
454
+ try {
455
+ rKey = Schema.resolve(key, sKey, options)[0];
456
+ } catch (error) {
457
+ if (strict) continue;
458
+ throw error;
459
+ }
460
+ result[rKey] = property(data, key, inner, options);
461
+ data[rKey] = data[key];
462
+ if (key !== rKey) delete data[key];
463
+ }
464
+ return [result];
465
+ });
466
+ Schema.extend("tuple", (data, { list }, options, strict) => {
467
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
468
+ const result = list.map((inner, index) => property(data, index, inner, options));
469
+ if (strict) return [result];
470
+ result.push(...data.slice(list.length));
471
+ return [result];
472
+ });
473
+ function merge(result, data) {
474
+ for (const key in data) {
475
+ if (key in result) continue;
476
+ result[key] = data[key];
477
+ }
478
+ }
479
+ Schema.extend("object", (data, { dict }, options, strict) => {
480
+ if (!(0, _deepseek_ai_cosmokit.isPlainObject)(data)) throw new ValidationError(`expected object but got ${data}`, options);
481
+ const result = {};
482
+ for (const key in dict) {
483
+ const value = property(data, key, dict[key], options);
484
+ if (!(0, _deepseek_ai_cosmokit.isNullable)(value) || key in data) result[key] = value;
485
+ }
486
+ if (!strict) merge(result, data);
487
+ return [result];
488
+ });
489
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
490
+ const messages = [];
491
+ for (const inner of list) try {
492
+ return Schema.resolve(data, inner, options, strict);
493
+ } catch (error) {
494
+ messages.push(error);
495
+ }
496
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
497
+ });
498
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
499
+ if (!list.length) return [data];
500
+ let result;
501
+ for (const inner of list) {
502
+ const value = Schema.resolve(data, inner, options, true)[0];
503
+ if ((0, _deepseek_ai_cosmokit.isNullable)(value)) continue;
504
+ if ((0, _deepseek_ai_cosmokit.isNullable)(result)) result = value;
505
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
506
+ else if (typeof value === "object") merge(result ??= {}, value);
507
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
508
+ }
509
+ if (!strict && (0, _deepseek_ai_cosmokit.isPlainObject)(data)) merge(result, data);
510
+ return [result];
511
+ });
512
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
513
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
514
+ if (preserve) return [callback(result)];
515
+ else return [callback(result), callback(adapted)];
516
+ });
517
+ const formatters = {};
518
+ function defineMethod(name, keys, format) {
519
+ formatters[name] = format;
520
+ Object.assign(Schema, { [name](...args) {
521
+ const schema = new Schema({ type: name });
522
+ keys.forEach((key, index) => {
523
+ switch (key) {
524
+ case "sKey":
525
+ schema.sKey = args[index] ?? Schema.string();
526
+ break;
527
+ case "inner":
528
+ schema.inner = Schema.from(args[index]);
529
+ break;
530
+ case "list":
531
+ schema.list = args[index].map(Schema.from);
532
+ break;
533
+ case "dict":
534
+ schema.dict = (0, _deepseek_ai_cosmokit.valueMap)(args[index], Schema.from);
535
+ break;
536
+ case "bits":
537
+ schema.bits = {};
538
+ for (const key in args[index]) {
539
+ if (typeof args[index][key] !== "number") continue;
540
+ schema.bits[key] = args[index][key];
541
+ }
542
+ break;
543
+ case "callback": {
544
+ const callback = schema.callback = args[index];
545
+ callback["toJSON"] ||= () => callback.toString();
546
+ break;
547
+ }
548
+ case "constructor": {
549
+ const constructor = schema.constructor = args[index];
550
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
551
+ break;
552
+ }
553
+ default: schema[key] = args[index];
554
+ }
555
+ });
556
+ if (name === "object" || name === "dict") schema.meta.default = {};
557
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
558
+ else if (name === "bitset") schema.meta.default = 0;
559
+ return schema;
560
+ } });
561
+ }
562
+ defineMethod("is", ["constructor"], ({ constructor }) => {
563
+ if (typeof constructor === "function") return constructor.name;
564
+ else return constructor;
565
+ });
566
+ defineMethod("any", [], () => "any");
567
+ defineMethod("never", [], () => "never");
568
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
569
+ defineMethod("string", [], () => "string");
570
+ defineMethod("number", [], () => "number");
571
+ defineMethod("boolean", [], () => "boolean");
572
+ defineMethod("bitset", ["bits"], () => "bitset");
573
+ defineMethod("function", [], () => "function");
574
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
575
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
576
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
577
+ defineMethod("object", ["dict"], ({ dict }) => {
578
+ if (Object.keys(dict).length === 0) return "{}";
579
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
580
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
581
+ }).join(", ")} }`;
582
+ });
583
+ defineMethod("union", ["list"], ({ list }, inline) => {
584
+ const result = list.map(({ toString: format }) => format()).join(" | ");
585
+ return inline ? `(${result})` : result;
586
+ });
587
+ defineMethod("intersect", ["list"], ({ list }) => {
588
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
589
+ });
590
+ defineMethod("transform", [
591
+ "inner",
592
+ "callback",
593
+ "preserve"
594
+ ], ({ inner }, isInner) => inner.toString(isInner));
595
+ //#endregion
596
+ module.exports = Schema;