UNPKG

juniper

Version:

ESM JSON Schema builder for static Typescript inference.

120 lines (119 loc) 3.35 kB
import escapeStringRegexp from 'escape-string-regexp'; import { maxInt } from '../lib/constants.js'; import { AbstractSchema } from '../lib/schema.js'; import { mergeAllOf } from '../lib/utils.js'; export class StringSchema extends AbstractSchema { #contentEncoding; #contentMediaType; #format; #maxLength; #minLength; #patterns = []; schemaType = 'string'; constructor(options = {}){ super(options); this.#contentEncoding = options.contentEncoding ?? null; this.#contentMediaType = options.contentMediaType ?? null; this.#format = options.format ?? null; this.#maxLength = options.maxLength ?? Number.POSITIVE_INFINITY; this.#minLength = options.minLength ?? 0; this.#patterns = [ options.pattern ?? [] ].flat(); } static create(options) { return new StringSchema(options); } format(format) { return this.clone({ format }); } maxLength(maxLength) { return this.clone({ maxLength }); } minLength(minLength) { return this.clone({ minLength }); } pattern(pattern) { return this.clone({ pattern: [ ...this.#patterns, pattern ] }); } startsWith(start) { return this.pattern(`^${escapeStringRegexp(start)}`); } endsWith(end) { return this.pattern(`${escapeStringRegexp(end)}$`); } contains(contain) { return this.pattern(escapeStringRegexp(contain)); } contentEncoding(contentEncoding) { return this.clone({ contentEncoding }); } contentMediaType(contentMediaType) { return this.clone({ contentMediaType }); } getCloneParams() { return { ...super.getCloneParams(), contentEncoding: this.#contentEncoding, contentMediaType: this.#contentMediaType, format: this.#format, maxLength: this.#maxLength, minLength: this.#minLength, pattern: [ ...this.#patterns ] }; } static getDefaultValues(params) { return { ...super.getDefaultValues(params), contentEncoding: null, contentMediaType: null, format: null, maxLength: maxInt, minLength: 0 }; } toSchema(params) { const base = super.toSchema(params); if (this.#format) { base.format = this.#format; } if (this.#minLength > 0) { base.minLength = this.#minLength; } if (this.#maxLength < Number.POSITIVE_INFINITY) { base.maxLength = this.#maxLength; } if (this.#contentEncoding) { base.contentEncoding = this.#contentEncoding; } if (this.#contentMediaType) { base.contentMediaType = this.#contentMediaType; } const [pattern, ...patterns] = this.#patterns; if (pattern) { base.pattern = pattern; mergeAllOf(base, patterns.map((p)=>({ pattern: p }))); } return base; } } //# sourceMappingURL=string.js.map