@cslug/validation 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/docs/README.md +48 -0
- package/docs/api.md +96 -0
- package/package.json +28 -4
- package/src/composites.ts +190 -0
- package/src/config.ts +9 -0
- package/src/domain.ts +241 -0
- package/src/icu.ts +95 -0
- package/src/index.ts +52 -0
- package/src/issue.ts +115 -0
- package/src/primitives.ts +305 -0
- package/src/schema.ts +268 -0
- package/src/standard-schema.ts +37 -0
- package/src/v.ts +75 -0
- package/src/validator.ts +81 -0
package/src/icu.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ICU message format, the subset apps use: `{name}` arguments, `plural` (with `=N` and `#`) and `select`.
|
|
3
|
+
* Pure (no Node APIs), so it runs on the server (core's Translator) and in the browser (island `useT`).
|
|
4
|
+
*/
|
|
5
|
+
export type Part =
|
|
6
|
+
| string
|
|
7
|
+
| { arg: string }
|
|
8
|
+
| { arg: string; kind: 'plural' | 'select'; options: Record<string, Part[]> }
|
|
9
|
+
|
|
10
|
+
function parse(message: string): Part[] {
|
|
11
|
+
let i = 0
|
|
12
|
+
const parseParts = (inPlural: boolean, untilBrace: boolean): Part[] => {
|
|
13
|
+
const parts: Part[] = []
|
|
14
|
+
let text = ''
|
|
15
|
+
const flush = () => {
|
|
16
|
+
if (text) parts.push(text)
|
|
17
|
+
text = ''
|
|
18
|
+
}
|
|
19
|
+
while (i < message.length) {
|
|
20
|
+
const ch = message[i] as string
|
|
21
|
+
if (ch === '}' && untilBrace) break
|
|
22
|
+
if (ch === '#' && inPlural) {
|
|
23
|
+
flush()
|
|
24
|
+
parts.push({ arg: '#' })
|
|
25
|
+
i++
|
|
26
|
+
} else if (ch === '{') {
|
|
27
|
+
flush()
|
|
28
|
+
i++
|
|
29
|
+
parts.push(parseArgument())
|
|
30
|
+
} else {
|
|
31
|
+
text += ch
|
|
32
|
+
i++
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
flush()
|
|
36
|
+
return parts
|
|
37
|
+
}
|
|
38
|
+
const parseArgument = (): Part => {
|
|
39
|
+
const close = message.indexOf('}', i)
|
|
40
|
+
const header = message.slice(i, close === -1 ? undefined : close)
|
|
41
|
+
const [name, kind] = header.split(',').map((s) => s.trim())
|
|
42
|
+
if (kind !== 'plural' && kind !== 'select') {
|
|
43
|
+
i = close + 1
|
|
44
|
+
return { arg: name as string }
|
|
45
|
+
}
|
|
46
|
+
i = message.indexOf(',', message.indexOf(',', i) + 1) + 1 // after "name, kind,"
|
|
47
|
+
const options: Record<string, Part[]> = {}
|
|
48
|
+
while (i < message.length && message[i] !== '}') {
|
|
49
|
+
const open = message.indexOf('{', i)
|
|
50
|
+
const key = message.slice(i, open).trim()
|
|
51
|
+
i = open + 1
|
|
52
|
+
options[key] = parseParts(kind === 'plural', true)
|
|
53
|
+
i++ // past the option's closing brace
|
|
54
|
+
while (message[i] === ' ' || message[i] === '\n') i++
|
|
55
|
+
}
|
|
56
|
+
i++ // past the argument's closing brace
|
|
57
|
+
return { arg: name as string, kind, options }
|
|
58
|
+
}
|
|
59
|
+
return parseParts(false, false)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function render(parts: Part[], params: Record<string, unknown>, locale: string, hash?: number): string {
|
|
63
|
+
let out = ''
|
|
64
|
+
for (const p of parts) {
|
|
65
|
+
if (typeof p === 'string') out += p
|
|
66
|
+
else if (!('kind' in p)) {
|
|
67
|
+
if (p.arg === '#') out += new Intl.NumberFormat(locale).format(hash ?? 0)
|
|
68
|
+
else {
|
|
69
|
+
const v = params[p.arg]
|
|
70
|
+
out += v === undefined ? `{${p.arg}}` : Array.isArray(v) ? v.join(', ') : String(v)
|
|
71
|
+
}
|
|
72
|
+
} else if (p.kind === 'plural') {
|
|
73
|
+
const n = Number(params[p.arg] ?? 0)
|
|
74
|
+
const branch = p.options[`=${n}`] ?? p.options[new Intl.PluralRules(locale).select(n)] ?? p.options.other ?? []
|
|
75
|
+
out += render(branch, params, locale, n)
|
|
76
|
+
} else {
|
|
77
|
+
const branch = p.options[String(params[p.arg])] ?? p.options.other ?? []
|
|
78
|
+
out += render(branch, params, locale, hash)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return out
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const cache = new Map<string, Part[]>()
|
|
85
|
+
|
|
86
|
+
/** Format an ICU message: `formatIcu('{count, plural, one {# day} other {# days}}', { count: 2 }, 'en')` → `2 days`. */
|
|
87
|
+
export function formatIcu(message: string, params: Record<string, unknown> = {}, locale = 'en'): string {
|
|
88
|
+
let parts = cache.get(message)
|
|
89
|
+
if (!parts) {
|
|
90
|
+
parts = parse(message)
|
|
91
|
+
if (cache.size > 5000) cache.clear()
|
|
92
|
+
cache.set(message, parts)
|
|
93
|
+
}
|
|
94
|
+
return render(parts, params, locale)
|
|
95
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/validation: schemas and validators with a Zod-like API, no dependencies.
|
|
3
|
+
* Standard Schema compatible; every schema exports JSON Schema.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export {
|
|
7
|
+
ArraySchema,
|
|
8
|
+
type ObjectInput,
|
|
9
|
+
type ObjectOutput,
|
|
10
|
+
ObjectSchema,
|
|
11
|
+
RecordSchema,
|
|
12
|
+
type Shape,
|
|
13
|
+
UnionSchema,
|
|
14
|
+
} from './composites'
|
|
15
|
+
export { configure } from './config'
|
|
16
|
+
export {
|
|
17
|
+
CountrySchema,
|
|
18
|
+
CurrencySchema,
|
|
19
|
+
FileSchema,
|
|
20
|
+
MoneySchema,
|
|
21
|
+
type MoneyValue,
|
|
22
|
+
PhoneSchema,
|
|
23
|
+
parseSize,
|
|
24
|
+
sniffType,
|
|
25
|
+
} from './domain'
|
|
26
|
+
export { formatIcu } from './icu'
|
|
27
|
+
export { formatMessage, type Issue, interpolate, type Translate, ValidationError } from './issue'
|
|
28
|
+
export {
|
|
29
|
+
BigIntSchema,
|
|
30
|
+
BooleanSchema,
|
|
31
|
+
DateSchema,
|
|
32
|
+
DateTimeSchema,
|
|
33
|
+
EnumSchema,
|
|
34
|
+
LiteralSchema,
|
|
35
|
+
NumberSchema,
|
|
36
|
+
StringSchema,
|
|
37
|
+
} from './primitives'
|
|
38
|
+
export {
|
|
39
|
+
type Ctx,
|
|
40
|
+
DefaultSchema,
|
|
41
|
+
type JsonSchema,
|
|
42
|
+
NullableSchema,
|
|
43
|
+
OptionalSchema,
|
|
44
|
+
type RefineOptions,
|
|
45
|
+
type SafeParseResult,
|
|
46
|
+
Schema,
|
|
47
|
+
TransformSchema,
|
|
48
|
+
UnknownSchema,
|
|
49
|
+
} from './schema'
|
|
50
|
+
export type { StandardSchemaV1 } from './standard-schema'
|
|
51
|
+
export * as v from './v'
|
|
52
|
+
export { type AfterHook, type Fail, type Output, type Validatable, Validator, validate } from './validator'
|
package/src/issue.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/** A problem found while validating, at a path inside the input. `message` is a translation key. */
|
|
2
|
+
export type Issue = {
|
|
3
|
+
path: (string | number)[]
|
|
4
|
+
/** Stable machine code, e.g. `string.min`, `required`, `email`. */
|
|
5
|
+
code: string
|
|
6
|
+
/** Translation key, e.g. `validation.string.min`, or a custom key such as `bookings.terms_required`. */
|
|
7
|
+
message: string
|
|
8
|
+
/** Values for the message, e.g. `{ min: 3 }`. */
|
|
9
|
+
params?: Record<string, unknown>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Translate a message key with params; return undefined to fall back to the built-in English text. */
|
|
13
|
+
export type Translate = (key: string, params: Record<string, unknown>) => string | undefined
|
|
14
|
+
|
|
15
|
+
const english: Record<string, string> = {
|
|
16
|
+
'validation.required': 'This field is required.',
|
|
17
|
+
'validation.invalid_type': 'Must be a {expected}.',
|
|
18
|
+
'validation.string.min': 'Must be at least {min} characters.',
|
|
19
|
+
'validation.string.max': 'Must be at most {max} characters.',
|
|
20
|
+
'validation.string.length': 'Must be exactly {length} characters.',
|
|
21
|
+
'validation.string.regex': 'Has an invalid format.',
|
|
22
|
+
'validation.email': 'Must be a valid email address.',
|
|
23
|
+
'validation.url': 'Must be a valid URL.',
|
|
24
|
+
'validation.uuid': 'Must be a valid UUID.',
|
|
25
|
+
'validation.number.min': 'Must be at least {min}.',
|
|
26
|
+
'validation.number.max': 'Must be at most {max}.',
|
|
27
|
+
'validation.int': 'Must be a whole number.',
|
|
28
|
+
'validation.int.min': 'Must be at least {min}.',
|
|
29
|
+
'validation.int.max': 'Must be at most {max}.',
|
|
30
|
+
'validation.bigint.min': 'Must be at least {min}.',
|
|
31
|
+
'validation.bigint.max': 'Must be at most {max}.',
|
|
32
|
+
'validation.array.min': 'Must contain at least {min} items.',
|
|
33
|
+
'validation.array.max': 'Must contain at most {max} items.',
|
|
34
|
+
'validation.enum': 'Must be one of: {options}.',
|
|
35
|
+
'validation.literal': 'Must be {expected}.',
|
|
36
|
+
'validation.date': 'Must be a valid date (YYYY-MM-DD).',
|
|
37
|
+
'validation.date.future': 'Must be a date in the future.',
|
|
38
|
+
'validation.date.past': 'Must be a date in the past.',
|
|
39
|
+
'validation.date.min': 'Must be on or after {min}.',
|
|
40
|
+
'validation.date.max': 'Must be on or before {max}.',
|
|
41
|
+
'validation.datetime': 'Must be a valid date and time.',
|
|
42
|
+
'validation.unrecognized_keys': 'Unexpected field(s): {keys}.',
|
|
43
|
+
'validation.union': 'Does not match any allowed shape.',
|
|
44
|
+
'validation.currency': 'Must be a supported currency.',
|
|
45
|
+
'validation.money': 'Must be an amount in minor units with a currency.',
|
|
46
|
+
'validation.country': 'Must be a valid country code.',
|
|
47
|
+
'validation.phone': 'Must be a valid phone number.',
|
|
48
|
+
'validation.file': 'Must be a file.',
|
|
49
|
+
'validation.file.size': 'Must be at most {max}.',
|
|
50
|
+
'validation.file.type': 'Must be one of: {types}.',
|
|
51
|
+
'validation.unique': 'This value is already taken.',
|
|
52
|
+
'validation.custom': 'Is invalid.',
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Replace `{name}` placeholders. Arrays are joined with ", ". */
|
|
56
|
+
export function interpolate(template: string, params: Record<string, unknown> = {}): string {
|
|
57
|
+
return template.replace(/\{(\w+)\}/g, (whole, name: string) => {
|
|
58
|
+
const value = params[name]
|
|
59
|
+
if (value === undefined) return whole
|
|
60
|
+
return Array.isArray(value) ? value.join(', ') : String(value)
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Human-readable text for an issue: the translator first, then the built-in English text, then the key itself. */
|
|
65
|
+
export function formatMessage(issue: Pick<Issue, 'message' | 'params'>, translate?: Translate): string {
|
|
66
|
+
const params = issue.params ?? {}
|
|
67
|
+
return translate?.(issue.message, params) ?? interpolate(english[issue.message] ?? issue.message, params)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function groupByPath(issues: Issue[], text: (issue: Issue) => string): Record<string, string[]> {
|
|
71
|
+
const out: Record<string, string[]> = {}
|
|
72
|
+
for (const issue of issues) {
|
|
73
|
+
const key = issue.path.join('.')
|
|
74
|
+
const list = out[key] ?? []
|
|
75
|
+
list.push(text(issue))
|
|
76
|
+
out[key] = list
|
|
77
|
+
}
|
|
78
|
+
return out
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const toIssues = (errors: Record<string, string | string[]>): Issue[] =>
|
|
82
|
+
Object.entries(errors).flatMap(([path, keys]) =>
|
|
83
|
+
(Array.isArray(keys) ? keys : [keys]).map((key) => ({
|
|
84
|
+
path: path === '' ? [] : path.split('.').map((p) => (/^\d+$/.test(p) ? Number(p) : p)),
|
|
85
|
+
code: key.startsWith('validation.') ? key.slice('validation.'.length) : 'custom',
|
|
86
|
+
message: key,
|
|
87
|
+
})),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Thrown when input is invalid. HTTP renders it as 422 (problem+json for APIs, redirect back with errors for
|
|
92
|
+
* forms). Construct from issues, or from `{ field: ['message.key'] }` in application code.
|
|
93
|
+
*/
|
|
94
|
+
export class ValidationError extends Error {
|
|
95
|
+
readonly status = 422
|
|
96
|
+
readonly code = 'validation.failed'
|
|
97
|
+
readonly issues: Issue[]
|
|
98
|
+
|
|
99
|
+
constructor(input: Issue[] | Record<string, string | string[]>) {
|
|
100
|
+
const issues = Array.isArray(input) ? input : toIssues(input)
|
|
101
|
+
super(`Validation failed: ${issues.map((i) => `${i.path.join('.') || '(root)'} ${i.message}`).join('; ')}`)
|
|
102
|
+
this.name = 'ValidationError'
|
|
103
|
+
this.issues = issues
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Message keys by dot path: `{ 'budget.currency': ['validation.currency'] }`. */
|
|
107
|
+
get errors(): Record<string, string[]> {
|
|
108
|
+
return groupByPath(this.issues, (i) => i.message)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Translated messages by dot path, for responses. */
|
|
112
|
+
messages(translate?: Translate): Record<string, string[]> {
|
|
113
|
+
return groupByPath(this.issues, (i) => formatMessage(i, translate))
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { settings } from './config'
|
|
2
|
+
import { type Ctx, INVALID, type Invalid, type JsonSchema, Schema } from './schema'
|
|
3
|
+
|
|
4
|
+
const typeOf = (value: unknown) => (value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value)
|
|
5
|
+
|
|
6
|
+
// ── string ───────────────────────────────────────────────────────────────────────────────────────────
|
|
7
|
+
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
|
8
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
|
9
|
+
const UUID7 = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
|
10
|
+
|
|
11
|
+
type StringFormat = 'email' | 'url' | 'uuid' | 'uuid7'
|
|
12
|
+
/** Rejected by `v.url()` unless explicitly allowed with `.protocols(...)`. */
|
|
13
|
+
const UNSAFE_PROTOCOLS = new Set(['javascript:', 'data:', 'vbscript:', 'file:', 'blob:'])
|
|
14
|
+
|
|
15
|
+
export class StringSchema extends Schema<string> {
|
|
16
|
+
_run(input: unknown, ctx: Ctx): string | Invalid {
|
|
17
|
+
let value = input
|
|
18
|
+
if (this._def.coerce && value !== undefined && value !== null && typeof value !== 'object') value = String(value)
|
|
19
|
+
if (value === undefined || value === null) return this._issue(ctx, 'required')
|
|
20
|
+
if (typeof value !== 'string')
|
|
21
|
+
return this._issue(ctx, 'invalid_type', { expected: 'string', received: typeOf(value) })
|
|
22
|
+
let s = value
|
|
23
|
+
if (this._def.trim) s = s.trim()
|
|
24
|
+
if (this._def.case === 'lower') s = s.toLowerCase()
|
|
25
|
+
if (this._def.case === 'upper') s = s.toUpperCase()
|
|
26
|
+
const min = this._def.min as number | undefined
|
|
27
|
+
const max = this._def.max as number | undefined
|
|
28
|
+
const length = this._def.length as number | undefined
|
|
29
|
+
if (min !== undefined && s.length < min) return this._issue(ctx, 'string.min', { min })
|
|
30
|
+
if (max !== undefined && s.length > max) return this._issue(ctx, 'string.max', { max })
|
|
31
|
+
if (length !== undefined && s.length !== length) return this._issue(ctx, 'string.length', { length })
|
|
32
|
+
const regex = this._def.regex as RegExp | undefined
|
|
33
|
+
if (regex && !regex.test(s)) return this._issue(ctx, 'string.regex', { pattern: regex.source })
|
|
34
|
+
switch (this._def.format as StringFormat | undefined) {
|
|
35
|
+
case 'email':
|
|
36
|
+
if (!EMAIL.test(s)) return this._issue(ctx, 'email')
|
|
37
|
+
break
|
|
38
|
+
case 'url': {
|
|
39
|
+
if (!URL.canParse(s)) return this._issue(ctx, 'url')
|
|
40
|
+
const protocol = new URL(s).protocol
|
|
41
|
+
const allowed = this._def.protocols as string[] | undefined
|
|
42
|
+
if (allowed ? !allowed.includes(protocol) : UNSAFE_PROTOCOLS.has(protocol)) return this._issue(ctx, 'url')
|
|
43
|
+
break
|
|
44
|
+
}
|
|
45
|
+
case 'uuid':
|
|
46
|
+
if (!UUID.test(s)) return this._issue(ctx, 'uuid')
|
|
47
|
+
break
|
|
48
|
+
case 'uuid7':
|
|
49
|
+
if (!UUID7.test(s)) return this._issue(ctx, 'uuid')
|
|
50
|
+
break
|
|
51
|
+
}
|
|
52
|
+
return s
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
min(min: number) {
|
|
56
|
+
return this._with({ min })
|
|
57
|
+
}
|
|
58
|
+
max(max: number) {
|
|
59
|
+
return this._with({ max })
|
|
60
|
+
}
|
|
61
|
+
length(length: number) {
|
|
62
|
+
return this._with({ length })
|
|
63
|
+
}
|
|
64
|
+
/** At least one character (after trimming, if trimmed). */
|
|
65
|
+
nonempty() {
|
|
66
|
+
return this._with({ min: 1 })
|
|
67
|
+
}
|
|
68
|
+
regex(regex: RegExp) {
|
|
69
|
+
return this._with({ regex })
|
|
70
|
+
}
|
|
71
|
+
trim() {
|
|
72
|
+
return this._with({ trim: true })
|
|
73
|
+
}
|
|
74
|
+
toLowerCase() {
|
|
75
|
+
return this._with({ case: 'lower' })
|
|
76
|
+
}
|
|
77
|
+
toUpperCase() {
|
|
78
|
+
return this._with({ case: 'upper' })
|
|
79
|
+
}
|
|
80
|
+
email() {
|
|
81
|
+
return this._with({ format: 'email' })
|
|
82
|
+
}
|
|
83
|
+
/** Any absolute URL (`https://…`, `postgres://…`, `redis://…`) except javascript:, data:, vbscript:, file:, blob:. */
|
|
84
|
+
url() {
|
|
85
|
+
return this._with({ format: 'url' })
|
|
86
|
+
}
|
|
87
|
+
/** Restrict a URL to these protocols, e.g. `.protocols('https:')` for links shown to users. */
|
|
88
|
+
protocols(...protocols: string[]) {
|
|
89
|
+
return this._with({ format: 'url', protocols: protocols.map((p) => (p.endsWith(':') ? p : `${p}:`)) })
|
|
90
|
+
}
|
|
91
|
+
uuid() {
|
|
92
|
+
return this._with({ format: 'uuid' })
|
|
93
|
+
}
|
|
94
|
+
uuid7() {
|
|
95
|
+
return this._with({ format: 'uuid7' })
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
_json(): JsonSchema {
|
|
99
|
+
const d = this._def
|
|
100
|
+
const format = { email: 'email', url: 'uri', uuid: 'uuid', uuid7: 'uuid' }[d.format as StringFormat]
|
|
101
|
+
return this._jsonMeta({
|
|
102
|
+
type: 'string',
|
|
103
|
+
...(d.min !== undefined ? { minLength: d.min } : {}),
|
|
104
|
+
...(d.max !== undefined ? { maxLength: d.max } : {}),
|
|
105
|
+
...(d.length !== undefined ? { minLength: d.length, maxLength: d.length } : {}),
|
|
106
|
+
...(d.regex ? { pattern: (d.regex as RegExp).source } : {}),
|
|
107
|
+
...(format ? { format } : {}),
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ── number / int ─────────────────────────────────────────────────────────────────────────────────────
|
|
113
|
+
export class NumberSchema extends Schema<number> {
|
|
114
|
+
_run(input: unknown, ctx: Ctx): number | Invalid {
|
|
115
|
+
let value = input
|
|
116
|
+
if (this._def.coerce && typeof value === 'string' && value.trim() !== '') value = Number(value)
|
|
117
|
+
if (value === undefined || value === null) return this._issue(ctx, 'required')
|
|
118
|
+
const kind = this._def.int ? 'int' : 'number'
|
|
119
|
+
if (typeof value !== 'number' || Number.isNaN(value)) {
|
|
120
|
+
return this._issue(ctx, 'invalid_type', {
|
|
121
|
+
expected: kind === 'int' ? 'whole number' : 'number',
|
|
122
|
+
received: typeOf(input),
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
if (!Number.isFinite(value))
|
|
126
|
+
return this._issue(ctx, 'invalid_type', { expected: 'finite number', received: 'infinity' })
|
|
127
|
+
if (this._def.int && !Number.isSafeInteger(value)) return this._issue(ctx, 'int')
|
|
128
|
+
const min = this._def.min as number | undefined
|
|
129
|
+
const max = this._def.max as number | undefined
|
|
130
|
+
if (min !== undefined && value < min) return this._issue(ctx, `${kind}.min`, { min })
|
|
131
|
+
if (max !== undefined && value > max) return this._issue(ctx, `${kind}.max`, { max })
|
|
132
|
+
return value
|
|
133
|
+
}
|
|
134
|
+
int() {
|
|
135
|
+
return this._with({ int: true })
|
|
136
|
+
}
|
|
137
|
+
min(min: number) {
|
|
138
|
+
return this._with({ min })
|
|
139
|
+
}
|
|
140
|
+
max(max: number) {
|
|
141
|
+
return this._with({ max })
|
|
142
|
+
}
|
|
143
|
+
positive() {
|
|
144
|
+
return this._with({ min: this._def.int ? 1 : Number.MIN_VALUE })
|
|
145
|
+
}
|
|
146
|
+
nonnegative() {
|
|
147
|
+
return this._with({ min: 0 })
|
|
148
|
+
}
|
|
149
|
+
_json(): JsonSchema {
|
|
150
|
+
const d = this._def
|
|
151
|
+
return this._jsonMeta({
|
|
152
|
+
type: d.int ? 'integer' : 'number',
|
|
153
|
+
...(d.min !== undefined ? { minimum: d.min } : {}),
|
|
154
|
+
...(d.max !== undefined ? { maximum: d.max } : {}),
|
|
155
|
+
})
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ── bigint (money minor units) ───────────────────────────────────────────────────────────────────────
|
|
160
|
+
/**
|
|
161
|
+
* Integer as `bigint`. Accepts a bigint, a safe integer number, or a string of digits, because JSON has no
|
|
162
|
+
* bigint and amounts travel as strings (`"220000"`).
|
|
163
|
+
*/
|
|
164
|
+
export class BigIntSchema extends Schema<bigint, bigint | number | string> {
|
|
165
|
+
_run(value: unknown, ctx: Ctx): bigint | Invalid {
|
|
166
|
+
if (value === undefined || value === null) return this._issue(ctx, 'required')
|
|
167
|
+
let n: bigint
|
|
168
|
+
if (typeof value === 'bigint') n = value
|
|
169
|
+
else if (typeof value === 'number' && Number.isSafeInteger(value)) n = BigInt(value)
|
|
170
|
+
else if (typeof value === 'string' && /^-?\d+$/.test(value.trim())) n = BigInt(value.trim())
|
|
171
|
+
else return this._issue(ctx, 'invalid_type', { expected: 'whole number', received: typeOf(value) })
|
|
172
|
+
const min = this._def.min as bigint | undefined
|
|
173
|
+
const max = this._def.max as bigint | undefined
|
|
174
|
+
if (min !== undefined && n < min) return this._issue(ctx, 'bigint.min', { min: String(min) })
|
|
175
|
+
if (max !== undefined && n > max) return this._issue(ctx, 'bigint.max', { max: String(max) })
|
|
176
|
+
return n
|
|
177
|
+
}
|
|
178
|
+
min(min: bigint | number) {
|
|
179
|
+
return this._with({ min: BigInt(min) })
|
|
180
|
+
}
|
|
181
|
+
max(max: bigint | number) {
|
|
182
|
+
return this._with({ max: BigInt(max) })
|
|
183
|
+
}
|
|
184
|
+
nonnegative() {
|
|
185
|
+
return this._with({ min: 0n })
|
|
186
|
+
}
|
|
187
|
+
_json(): JsonSchema {
|
|
188
|
+
return this._jsonMeta({ type: ['string', 'integer'], pattern: '^-?\\d+$' })
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ── boolean ──────────────────────────────────────────────────────────────────────────────────────────
|
|
193
|
+
const TRUE = new Set(['true', '1', 'on', 'yes'])
|
|
194
|
+
const FALSE = new Set(['false', '0', 'off', 'no', ''])
|
|
195
|
+
|
|
196
|
+
export class BooleanSchema extends Schema<boolean> {
|
|
197
|
+
_run(input: unknown, ctx: Ctx): boolean | Invalid {
|
|
198
|
+
let value = input
|
|
199
|
+
if (this._def.coerce) {
|
|
200
|
+
if (value === undefined || value === null)
|
|
201
|
+
value = false // an unchecked checkbox is absent
|
|
202
|
+
else if (typeof value === 'string' && TRUE.has(value.toLowerCase())) value = true
|
|
203
|
+
else if (typeof value === 'string' && FALSE.has(value.toLowerCase())) value = false
|
|
204
|
+
else if (value === 1 || value === 0) value = value === 1
|
|
205
|
+
}
|
|
206
|
+
if (value === undefined || value === null) return this._issue(ctx, 'required')
|
|
207
|
+
if (typeof value !== 'boolean')
|
|
208
|
+
return this._issue(ctx, 'invalid_type', { expected: 'boolean', received: typeOf(input) })
|
|
209
|
+
return value
|
|
210
|
+
}
|
|
211
|
+
_json(): JsonSchema {
|
|
212
|
+
return this._jsonMeta({ type: 'boolean' })
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ── calendar date: 'YYYY-MM-DD' string ───────────────────────────────────────────────────────────────
|
|
217
|
+
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/
|
|
218
|
+
|
|
219
|
+
/** A calendar date without time, as a `'YYYY-MM-DD'` string. Invalid dates (Feb 30) are rejected. */
|
|
220
|
+
export class DateSchema extends Schema<string> {
|
|
221
|
+
_run(value: unknown, ctx: Ctx): string | Invalid {
|
|
222
|
+
if (value === undefined || value === null || value === '') return this._issue(ctx, 'required')
|
|
223
|
+
if (typeof value !== 'string' || !DATE.test(value)) return this._issue(ctx, 'date')
|
|
224
|
+
const d = new Date(`${value}T00:00:00Z`)
|
|
225
|
+
if (Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== value) return this._issue(ctx, 'date')
|
|
226
|
+
const today = settings.today()
|
|
227
|
+
if (this._def.future && !(value > today)) return this._issue(ctx, 'date.future')
|
|
228
|
+
if (this._def.past && !(value < today)) return this._issue(ctx, 'date.past')
|
|
229
|
+
const min = this._def.min as string | undefined
|
|
230
|
+
const max = this._def.max as string | undefined
|
|
231
|
+
if (min && value < min) return this._issue(ctx, 'date.min', { min })
|
|
232
|
+
if (max && value > max) return this._issue(ctx, 'date.max', { max })
|
|
233
|
+
return value
|
|
234
|
+
}
|
|
235
|
+
/** After today (in the app's time zone, via the configured clock). */
|
|
236
|
+
future() {
|
|
237
|
+
return this._with({ future: true })
|
|
238
|
+
}
|
|
239
|
+
past() {
|
|
240
|
+
return this._with({ past: true })
|
|
241
|
+
}
|
|
242
|
+
min(min: string) {
|
|
243
|
+
return this._with({ min })
|
|
244
|
+
}
|
|
245
|
+
max(max: string) {
|
|
246
|
+
return this._with({ max })
|
|
247
|
+
}
|
|
248
|
+
_json(): JsonSchema {
|
|
249
|
+
return this._jsonMeta({ type: 'string', format: 'date' })
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** An instant as a `Date`. Accepts a Date, an ISO 8601 string, or (with coerce) epoch milliseconds. */
|
|
254
|
+
export class DateTimeSchema extends Schema<Date, Date | string | number> {
|
|
255
|
+
_run(value: unknown, ctx: Ctx): Date | Invalid {
|
|
256
|
+
if (value === undefined || value === null || value === '') return this._issue(ctx, 'required')
|
|
257
|
+
let d: Date | undefined
|
|
258
|
+
if (value instanceof Date) d = value
|
|
259
|
+
else if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value)) d = new Date(value)
|
|
260
|
+
else if (this._def.coerce && typeof value === 'number') d = new Date(value)
|
|
261
|
+
if (!d || Number.isNaN(d.getTime())) return this._issue(ctx, 'datetime')
|
|
262
|
+
return d
|
|
263
|
+
}
|
|
264
|
+
_json(): JsonSchema {
|
|
265
|
+
return this._jsonMeta({ type: 'string', format: 'date-time' })
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// ── enum / literal ───────────────────────────────────────────────────────────────────────────────────
|
|
270
|
+
export class EnumSchema<const T extends readonly [string, ...string[]]> extends Schema<T[number]> {
|
|
271
|
+
constructor(readonly options: T) {
|
|
272
|
+
super({})
|
|
273
|
+
}
|
|
274
|
+
_run(value: unknown, ctx: Ctx): T[number] | Invalid {
|
|
275
|
+
if (value === undefined || value === null || value === '') return this._issue(ctx, 'required')
|
|
276
|
+
if (typeof value !== 'string' || !this.options.includes(value)) {
|
|
277
|
+
return this._issue(ctx, 'enum', { options: [...this.options] })
|
|
278
|
+
}
|
|
279
|
+
return value as T[number]
|
|
280
|
+
}
|
|
281
|
+
_json(): JsonSchema {
|
|
282
|
+
return this._jsonMeta({ type: 'string', enum: [...this.options] })
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export type Primitive = string | number | boolean | null
|
|
287
|
+
|
|
288
|
+
export class LiteralSchema<const T extends Primitive> extends Schema<T> {
|
|
289
|
+
constructor(
|
|
290
|
+
readonly value: T,
|
|
291
|
+
message?: string,
|
|
292
|
+
) {
|
|
293
|
+
super(message ? { message } : {})
|
|
294
|
+
}
|
|
295
|
+
_run(value: unknown, ctx: Ctx): T | Invalid {
|
|
296
|
+
if (value === this.value) return this.value
|
|
297
|
+
if (value === undefined) return this._issue(ctx, 'required')
|
|
298
|
+
return this._issue(ctx, 'literal', { expected: JSON.stringify(this.value) })
|
|
299
|
+
}
|
|
300
|
+
_json(): JsonSchema {
|
|
301
|
+
return this._jsonMeta({ const: this.value })
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export { INVALID }
|