import { isEmpty } from './utils.js'; import { safeParseSchema, type SchemaSafeParseResult } from './validate.js'; import { toJsonSchema, type ConfigFeatureLevels, type ConfigFieldMetadata, type ConfigFieldI18n } from './json-schema.js'; export { SchemaValidationError, type SchemaSafeParseResult, type SchemaValidationIssue } from './validate.js'; export { safeParseSchema }; declare const configPresent: unique symbol; declare const inputRequired: unique symbol; export class Schema { /** Type-only output witness used by Plugin configuration inference. */ declare readonly output?: T; public [Symbol.toStringTag] = 'Schema'; constructor( public meta: Schema.Meta, public options: Schema.Options = {}, ) { const _this = this; const schema = function (value?: S, key: string = 'value') { const formatter = Schema.resolve(_this.meta.type); if (!formatter) throw new Error(`type ${_this.meta.type} not found`); return formatter.call(_this, key, value); } as Schema; return new Proxy(schema, { get(target, p: string | symbol, receiver: any): any { return Reflect.get(_this, p, receiver); }, set(target, p: string | symbol, value: any, receiver: any): boolean { return Reflect.set(_this, p, value, receiver); }, has(target, p: string | symbol): boolean { return Reflect.has(_this, p) || Reflect.has(target, p); }, }); } static fromJSON(json: Schema.JSON) { const { object, inner, list, ...meta } = json; const options: Schema.Options = {}; if (object) options.object = Object.fromEntries(Object.entries(object).map(([key, value]) => [key, Schema.fromJSON(value)])); if (inner) options.inner = Schema.fromJSON(inner); if (list) options.list = list.map(item => Schema.fromJSON(item)); return new Schema(meta, options); } toJSON(): Record { return Object.fromEntries( Object.entries({ ...this.meta, default: typeof this.meta.default === 'function' ? this.meta.default() : this.meta.default, inner: this.options.inner?.toJSON(), object: this.options.object ? Object.fromEntries(Object.entries(this.options.object || {}).map(([key, value]) => [ key, { ...value.toJSON(), key } ])) : undefined, list: this.options.list?.map(item => item.toJSON()), }).filter(([key, value]) => typeof value !== 'undefined'), ); } [Symbol.unscopables]() { return { options: true, meta: true, }; } /** 设置是否必填 */ required(): this & Schema.Present & Schema.Required { this.meta.required = true; return this as this & Schema.Present & Schema.Required; } /** 是否隐藏 */ hidden(): this { this.meta.hidden = true; return this; } /** 设置描述 */ description(description: string): this { this.meta.description = description; return this; } /** Translate form labels without changing validation, defaults or values. */ i18n(translations: ConfigFieldI18n): this { this.meta.i18n = structuredClone(translations); return this; } /** 设置默认值 */ default(defaultValue: T): this & Schema.Present { this.meta.default = defaultValue; return this as this & Schema.Present; } /** Secret values remain environment references in application configuration. */ secret(): this { if (this.meta.type !== 'string') throw new TypeError('secret only supports string fields'); this.meta.secret = true; return this; } /** Declare the effect shown in configuration forms. */ effect(effect: ConfigFieldMetadata['effect']): this { if (effect !== 'reload') throw new TypeError('Plugin configuration fields support only reload'); this.meta.effect = effect; return this; } /** * Plugin root only: layered feature levels (ADR 0050 / 0055) and the fields editable at the * conversation level, in chat by group admins, and in chat above the conversation level. */ featureLevels(levels: ConfigFeatureLevels['levels'], fields: Omit = {}): this { if (this.meta.type !== 'object') throw new TypeError('featureLevels only supports the plugin root object'); this.meta.feature = structuredClone({ levels, ...fields }); return this; } /** * Plugin property only: narrow the feature levels that may override this field (ADR 0050 §2), * e.g. `.fieldLevels(['global'])` for secrets and process-wide resources. It can never widen * the root `featureLevels` declaration; the Runtime rejects a wider list at startup. */ fieldLevels(levels: ConfigFeatureLevels['levels']): this { if (!levels.length || !levels.includes('global')) throw new TypeError('fieldLevels must include global'); this.meta.fieldLevels = [...levels]; return this; } /** Export the standard JSON Schema consumed by Runtime and Console. */ toJsonSchema(): Readonly> { return toJsonSchema(this); } /** 设置选项列表 */ option(list: (T | Schema.Option)[]): this { this.meta.options = Schema.formatOptionList(list); return this; } /** 设置是否允许多选 */ multiple(): this { if (this.meta.type !== 'list') throw new Error('multiple only support list type'); this.meta.multiple = true; return this; } /** * 设置最小值。 * `min` / `max` / `step` are range constraints of the exported JSON Schema * (minimum/minLength/minItems, maximum/…, multipleOf) and are enforced where that * schema is compiled (Runtime config validation). The callable schema and * `safeParse` are structural only; `toJsonSchema` relies on that when it matches * union branches (see assertPublicDefault). */ min(value: number): this { this.meta.min = value; return this; } /** 设置最大值 */ max(value: number): this { this.meta.max = value; return this; } /** 设置步进值 */ step(value: number): this { this.meta.step = value; return this; } /** 设置组件类型 */ component(type: string): this { this.meta.component = type; return this; } /** 声明一个数字类型 */ static number(key?: string): Schema { return new Schema({ type: 'number', key }); } /** 声明一个字符串类型 */ static string(key?: string): Schema { return new Schema({ type: 'string', key }); } /** 声明一个布尔类型 */ static boolean(key?: string): Schema { return new Schema({ type: 'boolean', key }); } /** 声明一个正则类型 */ static regexp(key?: string) { return new Schema({ type: 'regexp', key }); } /** 声明一个日期类型 */ static date(key?: string) { return new Schema({ type: 'date', key }); } /** 声明一个字典类型 */ static dict(input: X, key?: string) { return new Schema>, Record>>({ type: 'dict', key }, { inner: input }); } static object>>( input: X, key: string = '', ): Schema, Schema.RecordTypes> & { readonly output?: Schema.RecordTypes } { return new Schema, Schema.RecordTypes>({ type: 'object', key }, { object: input }); } /** 声明一个列表类型 */ static list(inner: X, key?: string) { return new Schema[], Schema.Output[]>({ type: 'list', key }, { inner }); } /** 声明一个元组类型 */ static tuple(list: X, key?: string) { return new Schema, Schema.Tuple>({ type: 'tuple', key }, { list }); } /** 声明一个联合类型 */ static union(list: X, key?: string): Schema, Schema.Union> { return new Schema, Schema.Union>({ type: 'union', key }, { list }); } /** 声明一个交叉类型 */ static intersect(list: X, key?: string) { return new Schema, Schema.Intersect>({ type: 'intersect', key }, { list }); } /** 声明一个常量 */ static const(value: X, key?: string) { return new Schema({ type: 'const', default: value, key }) as Schema & Schema.Present; } /** 声明任意类型 */ static any(key?: any) { return new Schema({ type: 'any', key }); } /** * 按判别字段声明联合类型(各分支自动补上 `discriminator: const(tag)`)。 * 用于 Segment / 消息体等 tagged union。 */ static discriminatedUnion< D extends string, V extends Record>>, >(discriminator: D, variants: V, key?: string): Schema { const branches = Object.entries(variants).map(([tag, shape]) => Schema.object({ [discriminator]: Schema.const(tag), ...shape, }), ); return Schema.union(branches as unknown as readonly Schema[]) as unknown as Schema; } /** validate-only:不填默认值、不 throw */ safeParse(value?: unknown): SchemaSafeParseResult { return safeParseSchema(this, value); } static resolve(type: T): Schema.Formatter { return Schema.formatters.get(type)!; } static extend(type: T, formatter: Schema.Formatter) { Schema.formatters.set(type, formatter); } } export interface Schema { (value?: S, key?: string): S; } export namespace Schema { export interface Present { readonly [configPresent]: true } export interface Required { readonly [inputRequired]: true } export type Input = T extends Schema ? I : never; export type Output = T extends Schema ? O : never; export type InputRecord> = { [K in keyof X as X[K] extends Required ? K : never]-?: Input } & { [K in keyof X as X[K] extends Required ? never : K]?: Input }; export type InputUnion = X extends readonly [infer L, ...infer R] ? Input | InputUnion : never; export type InputIntersect = X extends readonly [infer L, ...infer R] ? Input & InputIntersect : unknown; export type InputTuple = X extends readonly [infer L, ...infer R] ? [Input, ...InputTuple] : []; export const formatters: Map = new Map(); export type Formatter = (this: Schema, key: string, value: S) => T; export type JSON = Meta & { object?: Record; inner?: JSON; list?: JSON[]; }; export interface Meta { hidden?: boolean; type: string; default?: T; required?: boolean; options?: Option[]; multiple?: boolean; key?: string; description?: string; i18n?: ConfigFieldI18n; component?: string; min?: number; max?: number; step?: number; secret?: boolean; effect?: ConfigFieldMetadata['effect']; feature?: ConfigFeatureLevels; fieldLevels?: ConfigFeatureLevels['levels']; } export interface Options { object?: Record; inner?: Schema; list?: readonly Schema[]; } export type Types = Output; export type RecordTypes> = { [K in keyof T as T[K] extends Present ? K : never]-?: Output } & { [K in keyof T as T[K] extends Present ? never : K]?: Output }; export type Union = T extends readonly [infer L, ...infer R] ? Types | Union : never; export type Intersect = T extends readonly [infer L, ...infer R] ? Types & Intersect : unknown; export type Tuple = T extends readonly [infer L, ...infer R] ? [Types, ...Tuple] : []; export function checkDefault(schema: Schema, key: string, value: T, fallback: T = value) { if (isEmpty(value)) { value = schema.meta.default ?? fallback; } const validateType = (schema: Schema, key: string, value: any) => { switch (schema.meta.type) { case 'string': if (!['string', 'undefined'].includes(typeof value)) throw new TypeError(`${key} is not a string`); break; case 'number': if (!['number', 'undefined'].includes(typeof value) || (typeof value === 'number' && Number.isNaN(value))) throw new TypeError(`${key} is not a number`); break; case 'boolean': if (!['boolean', 'undefined'].includes(typeof value)) throw new TypeError(`${key} is not a boolean`); break; case 'regexp': if (!['string', 'undefined'].includes(typeof value) && !(value instanceof RegExp)) throw new TypeError(`${key} is not a RegExp|string`); break; case 'date': if (!['number', 'undefined'].includes(typeof value) && !(value instanceof Date)) throw new TypeError(`${key} is not a Date|number`); if (value instanceof Date && isNaN(value.getTime())) throw new TypeError(`${key} is not a valid Date`); break; case 'dict': if (!['object', 'undefined'].includes(typeof value) || value === null || Array.isArray(value)) throw new TypeError(`${key} is not a object`); break; case 'object': if (!['object', 'undefined'].includes(typeof value) || value === null || Array.isArray(value)) throw new TypeError(`${key} is not a object`); break; case 'list': if (typeof value !== 'undefined' && !Array.isArray(value)) throw new TypeError(`${key} is not a list`); break; case 'tuple': if (typeof value !== 'undefined' && !Array.isArray(value)) throw new TypeError(`${key} is not a tuple`); break; case 'union': // union类型不在这里验证,在extend函数中验证 break; case 'intersect': // intersect类型不在这里验证,在extend函数中验证 break; case 'const': if (typeof value !== 'undefined' && value !== schema.meta.default) throw new TypeError(`${key} is not const`); break; case 'any': // any类型不验证 break; default: throw new TypeError(`${key} is not a valid type`); } }; if (schema.meta.required && typeof value === 'undefined') throw new Error(`${key} is required`); validateType(schema, key, value); return value; } export type Option = { label: string; value: T; }; export function formatOptionList(list: T): Schema.Option[] { return list.map(item => { if (typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean') { return { label: `${item}`, value: item, } as Schema.Option; } return item as unknown as Schema.Option; }); } } Schema.extend('number', function (this: Schema, key: string, value: any) { value = Schema.checkDefault(this, key, value); return value; }); Schema.extend('string', function (this: Schema, key: string, value: any) { value = Schema.checkDefault(this, key, value); return value; }); Schema.extend('boolean', function (this: Schema, key: string, value: any) { return Schema.checkDefault(this, key, value); }); Schema.extend('dict', function (this: Schema, key: string, value: any) { value = Schema.checkDefault(this, key, value, {}); return Object.fromEntries( Object.entries(value).map(([k, schema]) => { return [k, this.options.inner!(schema, `${key}.${k}`)]; }), ); }); Schema.extend('object', function (this: Schema, key: string, value: any) { const getDefault = (schema: Schema) => { const result = Object.create(null); for (const propKey in schema.options.object) { const propSchema = schema.options.object[propKey]; result[propKey] = propSchema.meta.default !== undefined ? propSchema.meta.default : undefined; } return result; }; value = Schema.checkDefault(this, key, value, getDefault(this)); if (value === undefined) return value; const result = Object.create(null); const shape = this.options.object || {}; const allKeys = new Set([...Object.keys(shape), ...Object.keys(value)]); for (const k of allKeys) { const val = value[k]; const propSchema = shape[k]; if (propSchema) { // propSchema是一个可调用的Schema实例 const evaluated = (propSchema as any)(val, `${key}.${k}`); if (evaluated !== undefined || k in value) { result[k] = evaluated; } } else { result[k] = val; } } return result; }); Schema.extend('list', function (this: Schema, key: string, value: any) { value = Schema.checkDefault(this, key, value, []); return value.map((item: any, index: number) => this.options.inner!(item, `${key}[${index}]`)); }); Schema.extend('regexp', function (this: Schema, key: string, value: any) { value = Schema.checkDefault(this, key, value); if (typeof value === 'string') { return new RegExp(value); } return value; }); Schema.extend('date', function (this: Schema, key: string, value: any) { value = Schema.checkDefault(this, key, value); if (typeof value === 'undefined') return value; return new Date(value); }); Schema.extend('const', function (this: Schema, key: string, value: any) { value = Schema.checkDefault(this, key, value); if (value !== this.meta.default) { throw new Error(`${key} const value not match`); } return value; }); Schema.extend('tuple', function (this: Schema, key: string, value: any) { // No `[]` fallback: an empty array is not a valid tuple (JSON Schema exports // minItems = maxItems = length, and safeParse rejects it), so absent stays absent. value = Schema.checkDefault(this, key, value); if (value === undefined) return value; if (value.length !== this.options.list!.length) throw new TypeError(`${key} tuple length mismatch`); return value.map((item: any, index: number) => this.options.list![index](item, `${key}[${index}]`)); }); Schema.extend('union', function (this: Schema, key: string, value: any) { value = Schema.checkDefault(this, key, value); let lastError: unknown; const issues: string[] = []; for (const schema of this.options.list!) { try { return (schema as any)(value, key); } catch (e) { lastError = e; issues.push(e instanceof Error ? e.message : String(e)); } } const error = new Error(`${key} union type not match: ${issues.join('; ')}`); (error as any).lastError = lastError; throw error; }); Schema.extend('intersect', function (this: Schema, key: string, value: any) { value = Schema.checkDefault(this, key, value); for (const schema of this.options.list!) { try { value = (schema as any)(value, key); } catch (e) { throw new Error(`${key} intersect type not match`); } } return value; }); Schema.extend('any', function (this: Schema, key: string, value: any) { return Schema.checkDefault(this, key, value); });