import { editsBetween, envHasCsp, hasDomain, hasOwn, holdsWeakly, printable, throwParseError, type ArkRegistry, type requireKeys, type show } from "@ark/util" import type { intrinsic } from "./intrinsic.ts" import type { BaseNode } from "./node.ts" import type { nodesById } from "./parse.ts" import type { BaseRoot } from "./roots/root.ts" import type { RootApplyRuntime } from "./shared/rootApply.ts" import type { BaseScope } from "./scope.ts" import type { TypeMeta } from "./shared/declare.ts" import { configureLocale, writeConfigureAfterTypeMessage, type ActualConfig, type ArkErrorCode, type ArkErrors, type ExpectedConfig, type MessageConfig } from "./shared/errors.ts" import { isNodeKind, nodeKinds, type DescriptionConfig, type DescriptionWriter, type NodeKind } from "./shared/implement.ts" import { copyConfig, isSameConfig } from "./shared/configured.ts" import { validateToJsonSchemaTarget } from "./shared/jsonSchema.ts" import type { Locale } from "./shared/locale.ts" import { $ark } from "./shared/registry.ts" import type { SetEngine } from "./shared/sets.ts" import type { InPlaceTransforms } from "./shared/transform.ts" import { ToJsonSchema } from "./shared/toJsonSchema.ts" import { removedCloneMessage, removedProblemMessage } from "./shared/utils.ts" export { removedCloneMessage } from "./shared/utils.ts" import type { UndeclaredKeyBehavior } from "./structure/structure.ts" export interface ArkSchemaRegistry extends ArkRegistry { /** the intrinsic nodes keywords are built from, like `unknown` and `string` */ kw: typeof intrinsic config: ArkSchemaConfig defaultConfig: ResolvedConfig cfg?: ResolvedConfig /** the first Type that froze `cfg`, for configure() ordering diagnostics */ cfgFrozenBy?: string | (() => string | undefined) | undefined nodesById: typeof nodesById sets?: SetEngine encode?: (node: BaseRoot) => BaseRoot inPlace?: InPlaceTransforms // standalone builds check a default where its Type is created deferDefaultCheck?: | (( node: BaseRoot, value: unknown, key: PropertyKey | null, owner: BaseNode | undefined ) => boolean) | undefined reached?: CacheReach | undefined // set by a tool comparing or recording what a Type's definition does at its call eagerTypes?: boolean | undefined // installed by @ark/schema/errors errorModes?: Record<"first" | "none", RootApplyRuntime> } // read by standalone builds export interface CacheReach { // a node returned from the node cache node: (node: BaseNode) => void // an entry returned from another cache cached: (cache: object, key: unknown) => void // a Scope alias the definition resolves alias: ($: BaseScope, alias: string) => void mark: () => number | undefined store: (mark: number | undefined, cache: object, key: unknown) => void } type nodeConfigForKind = Readonly< show< { description?: DescriptionConfig } & (kind extends ArkErrorCode ? ErrorConfig : {}) > > export type ErrorConfig = { expected?: ExpectedConfig actual?: ActualConfig message?: MessageConfig } type NodeConfigsByKind = { [kind in NodeKind]: nodeConfigForKind } export type NodeConfig = NodeConfigsByKind[kind] export interface UnknownErrorConfigs { expected?: ExpectedConfig actual?: ActualConfig message?: MessageConfig } interface UnknownNodeConfig extends UnknownErrorConfigs { description?: DescriptionWriter } export type ResolvedUnknownNodeConfig = requireKeys< UnknownNodeConfig, "description" > // $ark.config could already be set if it were imported previously from the // dedicated config entrypoint, in which case we don't want to reinitialize it $ark.config ??= {} // every option but a node kind's, which adding one to ArkSchemaConfig fails // to compile without const optionNames = { undeclared: 1, discriminant: 1, jitless: 1, onUndeclaredKey: 1, numberAllowsNaN: 1, numberAllowsInfinity: 1, dateAllowsInvalid: 1, exactOptionalPropertyTypes: 1, onFail: 1, errors: 1, mutatesInput: 1, keywords: 1, toJsonSchema: 1, locale: 1 } satisfies Record, 1> export const writeUnknownConfigOptionMessage = ( name: name ): writeUnknownConfigOptionMessage => `configure() has no option '${name}'` export type writeUnknownConfigOptionMessage = `configure() has no option '${name}'` // the option a mistyped one is nearest to, within two edits const nearestOptionTo = (name: string): string | undefined => { let nearest: string | undefined let fewest = 3 for (const option of [...Object.keys(optionNames), ...nodeKinds]) { const edits = editsBetween(name.toLowerCase(), option.toLowerCase()) if (edits < fewest) [nearest, fewest] = [option, edits] } return nearest } const undeclaredKeyBehaviors = { reject: 1, delete: 1, ignore: 1 } export const writeInvalidUndeclaredKeyBehaviorMessage = ( actual: unknown ): string => `onUndeclaredKey must be 'reject', 'delete', or 'ignore' (was ${printable(actual)})` /** * @internal throws for 2.x's `problem` in a code's config, which a cast or * JavaScript still passes, and which would otherwise be kept and never read */ export const assertNoProblemConfig = ( config: ArkSchemaConfig | undefined ): void => { for (const k in config) { const ofCode: unknown = config[k as never] if ( (isNodeKind(k) || k === "undeclared" || k === "discriminant") && hasDomain(ofCode, "object") && "problem" in ofCode ) throwParseError(removedProblemMessage) } } const maxFirstTypeLength = 80 const previewExpression = (expression: string): string => expression.length > maxFirstTypeLength ? `${expression.slice(0, maxFirstTypeLength - 3)}...` : expression const formatFirstType = (expression: string, alias?: string): string => { const preview = previewExpression(expression) return alias && alias !== preview ? `${alias} (${preview})` : preview } let bootstrapping = 0 /** @internal suppresses recording internal intrinsic/bootstrap nodes as the user's first Type */ export const whileBootstrapping = (fn: () => t): t => { bootstrapping++ try { return fn() } finally { bootstrapping-- } } /** @internal records the first Type that froze `$ark.cfg` for configure() errors */ export const recordFirstType = ( node: BaseRoot, deferred?: boolean, alias?: string ): void => { if (bootstrapping || !$ark.cfg || $ark.cfgFrozenBy !== undefined) return if (deferred) { // deferred Type: avoid settling unless configure() fails, and don't retain it for GC const ref = holdsWeakly ? new WeakRef(node) : undefined $ark.cfgFrozenBy = () => { const live = ref?.deref() return live ? formatFirstType(live.expression, alias) : undefined } } else { // writing its expression can resolve a keyword it names, e.g. string.url, // which isn't the first Type, and whose own expression, written here // before the keyword resolves, couldn't name it. Not through a callback, // whose reference to the node the deferred one above would hold as well bootstrapping++ try { $ark.cfgFrozenBy = formatFirstType(node.expression, alias) } finally { bootstrapping-- } } } export const configureSchema = (config: ArkSchemaConfig): ArkSchemaConfig => { assertNoProblemConfig(config) if ("clone" in config) throwParseError(removedCloneMessage) // a misspelled option would otherwise be kept and never read for (const k in config) { if (isNodeKind(k) || hasOwn(optionNames, k)) continue const nearest = nearestOptionTo(k) throwParseError( writeUnknownConfigOptionMessage(k) + (nearest ? `. Did you mean '${nearest}'?` : "") ) } // as is another library's word for one, like "strip" if ( config.onUndeclaredKey !== undefined && !hasOwn(undeclaredKeyBehaviors, config.onUndeclaredKey) ) { throwParseError( writeInvalidUndeclaredKeyBehaviorMessage(config.onUndeclaredKey) ) } if (config.locale !== undefined && !hasDomain(config.locale, "object")) throwParseError(writeInvalidLocaleMessage(config.locale)) const merged = mergeConfigs($ark.config, copyConfig(config)) if ($ark.cfg) { // a config file evaluated again, as after a test runner resets modules, // can reapply what's set, which changes nothing if (!isSameConfig(merged, $ark.config)) { const frozenBy = $ark.cfgFrozenBy let firstType: string | undefined if (typeof frozenBy === "function") { try { firstType = frozenBy() } catch { firstType = undefined } } else firstType = frozenBy return throwParseError(writeConfigureAfterTypeMessage(firstType)) } } else Object.assign($ark.config, merged) // what was passed, as a precompiled program's configure() returns, rather // than $ark.config, whose writes would skip this validation return config } /** $ark.config merged over base, with its static locale */ export const resolveGlobalConfig = (base: ResolvedConfig): ResolvedConfig => { $ark.cfgFrozenBy = undefined const resolved = mergeConfigs( // probed as the config is fixed, so configuring jitless after import skips it { ...base, jitless: $ark.config.jitless ?? envHasCsp() }, $ark.config ) // a locale function selects a locale per read, which is en if it returns none ;(resolved as { locale: Locale.Resolved }).locale = configureLocale( $ark.config.locale, base ) return resolved } export const writeInvalidLocaleMessage = (locale: unknown): string => `locale must be a Locale or a function returning one (was ${printable(locale)})` export const mergeConfigs = ( base: base, merged: ArkSchemaConfig | undefined ): base => { if (!merged) return base const result: any = { ...base, ...merged } let k: keyof ArkSchemaConfig for (k in merged) { const keywords = { ...base.keywords } if (k === "keywords") { for (const flatAlias in merged[k]) { const v = merged.keywords![flatAlias] if (v === undefined) continue keywords[flatAlias] = typeof v === "string" ? { description: v } : v } result.keywords = keywords } else if (k === "toJsonSchema") { result[k] = mergeToJsonSchemaConfigs( base.toJsonSchema, merged.toJsonSchema ) } else if (isNodeKind(k) || k === "undeclared" || k === "discriminant") { result[k] = // not casting this makes TS compute a very inefficient // type that is not needed { ...base[k], ...merged[k] } as never } } return result } const jsonSchemaTargetToDialect: Record = { "draft-2020-12": "https://json-schema.org/draft/2020-12/schema", "draft-07": "http://json-schema.org/draft-07/schema#", // an OpenAPI Schema Object has no $schema "openapi-3.0": null, "openapi-3.1": null } type MergeToJsonSchemaConfigs = ( baseConfig: base, mergedConfig: ToJsonSchema.Options | undefined ) => base extends ToJsonSchema.Context ? ToJsonSchema.Context : ToJsonSchema.Options export const mergeToJsonSchemaConfigs: MergeToJsonSchemaConfigs = (( baseConfig: ToJsonSchema.Options | undefined, mergedConfig: ToJsonSchema.Options | undefined ) => { if (!baseConfig) return resolveTargetToDialect(mergedConfig ?? {}, mergedConfig) if (!mergedConfig) return baseConfig const result: ToJsonSchema.Options = { ...baseConfig } let k: keyof ToJsonSchema.Options for (k in mergedConfig) { if (k === "fallback") { result.fallback = mergeFallbacks( baseConfig.fallback, mergedConfig.fallback ) } else result[k] = mergedConfig[k] as never } return resolveTargetToDialect(result, mergedConfig) }) as MergeToJsonSchemaConfigs const resolveTargetToDialect = ( opts: T, userOpts: ToJsonSchema.Options | undefined ): T => { if (userOpts?.target === undefined) return opts const dialect = jsonSchemaTargetToDialect[validateToJsonSchemaTarget(userOpts.target)] // a dialect passed with the target was already merged and takes precedence return userOpts.dialect === undefined ? { ...opts, dialect } : opts } const mergeFallbacks = ( base: ToJsonSchema.FallbackOption | undefined, merged: ToJsonSchema.FallbackOption | undefined ): ToJsonSchema.FallbackObject => { base = normalizeFallback(base) merged = normalizeFallback(merged) const result: ToJsonSchema.HandlerByCode = {} as never let code: ToJsonSchema.Code for (code in ToJsonSchema.defaultConfig.fallback) { result[code] = merged[code] ?? merged.default ?? base[code] ?? base.default ?? (ToJsonSchema.defaultConfig.fallback[code] as any) } return result } const normalizeFallback = ( fallback?: ToJsonSchema.FallbackOption | ToJsonSchema.UniversalFallback ): ToJsonSchema.FallbackObject => typeof fallback === "function" ? { default: fallback } : (fallback ?? {}) export type ErrorDetail = "all" | "first" | "none" /** * #### whether a valid input is transformed in place * * - `false`: transforms copy what they change, so the input is never written * - `true`: writes where no other place can read what it wrote, else copies * - `"always"`: writes every transform into the input */ export type MutatesInput = boolean | "always" export interface ArkSchemaConfig extends Partial> { readonly undeclared?: Readonly> readonly discriminant?: Readonly> readonly jitless?: boolean readonly onUndeclaredKey?: UndeclaredKeyBehavior readonly numberAllowsNaN?: boolean readonly numberAllowsInfinity?: boolean readonly dateAllowsInvalid?: boolean readonly exactOptionalPropertyTypes?: boolean readonly onFail?: ArkErrors.Handler | null readonly errors?: ErrorDetail readonly mutatesInput?: MutatesInput readonly keywords?: Record readonly toJsonSchema?: ToJsonSchema.Options readonly locale?: Locale | (() => Locale | undefined) } export type resolveConfig = show< { [k in keyof ArkSchemaConfig]-?: k extends NodeKind | ArkErrorCode ? Required : k extends "keywords" ? Record : k extends "toJsonSchema" ? ToJsonSchema.Context : k extends "locale" ? Locale.Resolved : config[k] } & Omit > export type ResolvedConfig = resolveConfig