UNPKG

@sinclair/typebox

Version:

Json Schema Type Builder with Static Type Resolution for TypeScript

41 lines (39 loc) 2.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TemplateLiteralPattern = exports.TemplateLiteralPatternError = void 0; const index_1 = require("../patterns/index"); const index_2 = require("../symbols/index"); const index_3 = require("../error/index"); // ------------------------------------------------------------------ // TypeGuard // ------------------------------------------------------------------ // prettier-ignore const type_1 = require("../guard/type"); // ------------------------------------------------------------------ // TemplateLiteralPatternError // ------------------------------------------------------------------ class TemplateLiteralPatternError extends index_3.TypeBoxError { } exports.TemplateLiteralPatternError = TemplateLiteralPatternError; // ------------------------------------------------------------------ // TemplateLiteralPattern // ------------------------------------------------------------------ function Escape(value) { return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } // prettier-ignore function Visit(schema, acc) { return ((0, type_1.IsTemplateLiteral)(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) : (0, type_1.IsUnion)(schema) ? `(${schema.anyOf.map((schema) => Visit(schema, acc)).join('|')})` : (0, type_1.IsNumber)(schema) ? `${acc}${index_1.PatternNumber}` : (0, type_1.IsInteger)(schema) ? `${acc}${index_1.PatternNumber}` : (0, type_1.IsBigInt)(schema) ? `${acc}${index_1.PatternNumber}` : (0, type_1.IsString)(schema) ? `${acc}${index_1.PatternString}` : (0, type_1.IsLiteral)(schema) ? `${acc}${Escape(schema.const.toString())}` : (0, type_1.IsBoolean)(schema) ? `${acc}${index_1.PatternBoolean}` : (() => { throw new TemplateLiteralPatternError(`Unexpected Kind '${schema[index_2.Kind]}'`); })()); } function TemplateLiteralPattern(kinds) { return `^${kinds.map((schema) => Visit(schema, '')).join('')}\$`; } exports.TemplateLiteralPattern = TemplateLiteralPattern;