import type { ConditionalResult, SchemaGenerics, SchemaParams, SerializationParams, } from '#internal/lib/schema.js'; import type { AbstractClean, ConditionalNullable, JsonSchema, NotNullParameter, Nullable, SchemaType, } from '#internal/lib/types.js'; import type { NullSchema } from './null.js'; import escapeStringRegexp from 'escape-string-regexp'; import { maxInt } from '#internal/lib/constants.js'; import { AbstractSchema } from '#internal/lib/schema.js'; import { mergeAllOf } from '#internal/lib/utils.js'; /** * String `format`s defined by JSON Schema 2020-12 and OpenAPI 3.0. * Any other string is accepted as a custom format. * * @see {@link https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.7.3} */ export type KnownFormat = | 'binary' | 'byte' | 'date' | 'date-time' | 'duration' | 'email' | 'hostname' | 'idn-email' | 'idn-hostname' | 'ipv4' | 'ipv6' | 'iri' | 'iri-reference' | 'json-pointer' | 'password' | 'regex' | 'relative-json-pointer' | 'time' | 'uri' | 'uri-reference' | 'uri-template' | 'uuid'; // `string & {}` keeps autocomplete for known formats, while accepting any string type Format = KnownFormat | (string & {}); interface StringParams extends SchemaParams> { /** * Content encoding. */ contentEncoding?: string | null; contentMediaType?: string | null; format?: Format | null; maxLength?: number; minLength?: number; pattern?: string | string[]; } interface StringGenerics extends SchemaGenerics> { params: StringParams; } type StripString = AbstractClean; type AnyStringSchema = StringSchema; /** * Schema for defining `string` types. * * Some `pattern` assertions are built in to help TypeScript, but most * likely end TypeScript result will just be `string`. * * Supports multiple `patterns`. * * @template T * @template N */ export class StringSchema< T extends string, // Nullable N extends boolean = false, > extends AbstractSchema> { readonly #contentEncoding: string | null; readonly #contentMediaType: string | null; readonly #format: string | null; readonly #maxLength: number; readonly #minLength: number; readonly #patterns: string[] = []; protected override readonly schemaType = 'string'; declare public allOf: >( this: AnyStringSchema, schema: S ) => StringSchema> & T, null extends SchemaType ? N : boolean>; declare public anyOf: >( this: AnyStringSchema, schemas: readonly S[] ) => StringSchema> & T, null extends SchemaType ? N : boolean>; declare public if: < IfT extends string, IfN extends boolean, ThenT extends string, ElseT extends string, ThenN extends boolean = true, ElseN extends boolean = true, >( this: AnyStringSchema, schema: StringSchema, conditionals: ConditionalResult, StringSchema> ) => StringSchema< StripString, ConditionalNullable >; /** * `.not(nullSchema())` makes a nullable schema non-nullable. * Any other schema is excluded in JSON Schema, but TypeScript can't express it, * so it only removes `null` from the type when the schema is nullable. */ declare public not: (( this: AnyStringSchema, schema: NotNullParameter & NullSchema ) => StringSchema) & (( this: AnyStringSchema, schema: StringSchema ) => NotN extends true ? StringSchema : this); declare public nullable: ( this: AnyStringSchema ) => StringSchema; declare public oneOf: >( this: AnyStringSchema, schemas: readonly S[] ) => StringSchema> & T, null extends SchemaType ? N : boolean>; /** * @override */ public constructor(options: StringParams = {}) { 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(); } /** * Create a new instance of StringSchema. * * @param [options] - optional * @param [options.contentEncoding] - contentEncoding property * @param [options.contentMediaType] - contentMediaType property * @param [options.format] - text format of string * @param [options.minLength] - minimum length of string (inclusive) * @param [options.maxLength] - maximum length of string (inclusive) * @param [options.pattern] - RegExp patterns to describe string * @param [options.title] - Add title to schema * @param [options.description] - Add description to schema * @param [options.deprecated] - flag schema as deprecated * @param [options.readOnly] - value should not be modified * @param [options.writeOnly] - value should be hidden * @returns new string schema */ public static override create( this: void, options?: StringParams ): StringSchema { return new StringSchema(options); } /** * Set the `format` of the string. * Set to `null` to effectively clear restriction. * * Known formats (see `KnownFormat`) autocomplete, and any other string is accepted as a custom format. * * Usage and restrictions of `format` are implementation-specific. No enforcement is guaranteed * by default in JSON Schema. * * Does not alter typings. * Overwrites existing restriction. * * @see {@link https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.7} * * @param this - this instance * @param format - format property * @returns cloned schema */ public format(this: this, format: Format | null): this { return this.clone({ format }); } /** * Set the `maxLength` of the string. * Set to `Infinity` to effectively clear restriction. * * Does not alter typings. * Overwrites existing restriction. * * @see {@link https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.3.1} * * @param this - this instance * @param maxLength - max length property * @returns cloned schema */ public maxLength(this: this, maxLength: number): this { return this.clone({ maxLength }); } /** * Set the `minLength` of the string. * Set to `0` to effectively clear restriction. * * Does not alter typings. * Overwrites existing restriction. * * @see {@link https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.3.2} * * @param this - this instance * @param minLength - min length property * @returns cloned schema */ public minLength(this: this, minLength: number): this { return this.clone({ minLength }); } /** * Add a `pattern` to the string. * * Optionally alters typings, which restrict outputted string type. * Use with caution, as there is no validation that pattern actually asserts type. * * @see {@link https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.3.3} * * @param this - this instance * @param pattern - regular expression pattern * @returns cloned schema */ public pattern( this: this, pattern: string ): StringSchema, N> { return this.clone({ pattern: [...this.#patterns, pattern], }) as unknown as StringSchema, N>; } /** * Add a special case `pattern` that enforces a string occurs as the start. * * @param this - this instance * @param start - string literal * @returns cloned schema */ public startsWith( this: this, start: Start ): StringSchema, N> { // Not `RegExp.escape`: it hex-escapes a leading letter or digit, which would change the generated `pattern` return this.pattern<`${Start}${string}`>(`^${escapeStringRegexp(start)}`); } /** * Add a special case `pattern` that enforces a string occurs as the end. * * @param this - this instance * @param end - string literal * @returns cloned schema */ public endsWith( this: this, end: End ): StringSchema, N> { // Not `RegExp.escape`: it hex-escapes a leading letter or digit, which would change the generated `pattern` return this.pattern<`${string}${End}`>(`${escapeStringRegexp(end)}$`); } /** * Add a special case `pattern` that enforces a string occurs somewhere in the string. * * @param this - this instance * @param contain - string literal * @returns cloned schema */ public contains( this: this, contain: Contain ): StringSchema, N> { // Not `RegExp.escape`: it hex-escapes a leading letter or digit, which would change the generated `pattern` return this.pattern<`${string}${Contain}${string}`>(escapeStringRegexp(contain)); } /** * Set `contentEncoding` of string. * Set to `null` to remove. * * Does not alter typings. * Overwrites existing encoding. * * @see {@link https://json-schema.org/understanding-json-schema/reference/non_json_data.html#contentencoding} * * @param this - this instance * @param contentEncoding - content encoding property * @returns cloned string schema */ public contentEncoding(this: this, contentEncoding: string | null): this { return this.clone({ contentEncoding, }); } /** * Set `contentMediaType` of string. * Set to `null` to remove. * * Does not alter typings. * Overwrites existing encoding. * * @see {@link https://json-schema.org/understanding-json-schema/reference/non_json_data.html#contentmediatype} * * @param this - this instance * @param contentMediaType - content media type property * @returns cloned string schema */ public contentMediaType(this: this, contentMediaType: string | null): this { return this.clone({ contentMediaType, }); } /** * @override */ protected override getCloneParams(): Required> { return { ...super.getCloneParams(), contentEncoding: this.#contentEncoding, contentMediaType: this.#contentMediaType, format: this.#format, maxLength: this.#maxLength, minLength: this.#minLength, pattern: [...this.#patterns], }; } /** * @override */ protected static override getDefaultValues( params: SerializationParams ): Record { return { ...super.getDefaultValues(params), contentEncoding: null, contentMediaType: null, format: null, maxLength: maxInt, minLength: 0, }; } /** * @override */ protected override toSchema(params: SerializationParams): JsonSchema> { const base = super.toSchema(params); if (this.#format !== null) { base.format = this.#format; } if (this.#minLength > 0) { base.minLength = this.#minLength; } if (this.#maxLength < Number.POSITIVE_INFINITY) { base.maxLength = this.#maxLength; } // OpenAPI 3.0 has no content keywords (`format: 'byte'` or `'binary'` is its equivalent) if (!params.openApi30) { if (this.#contentEncoding !== null) { base.contentEncoding = this.#contentEncoding; } if (this.#contentMediaType !== null) { base.contentMediaType = this.#contentMediaType; } } const [pattern, ...patterns] = this.#patterns; if (pattern !== undefined) { base.pattern = pattern; mergeAllOf( base, patterns.map(p => ({ pattern: p })) ); } return base; } }