@cslug/validation 0.0.0-stage → 0.2.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 +10 -0
- package/src/domain.ts +242 -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/README.md
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cslug/validation
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Schemas and validators with a Zod-like API and no dependencies. Every schema implements
|
|
4
|
+
[Standard Schema](https://standardschema.dev) and exports JSON Schema.
|
|
5
|
+
|
|
6
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
|
|
7
|
+
[guide 07](../../guides/07-validation.md).
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# @cslug/validation
|
|
2
|
+
|
|
3
|
+
Schemas and validators with a Zod-like API and **no dependencies**. Every schema implements
|
|
4
|
+
[Standard Schema](https://standardschema.dev) and exports JSON Schema, so the same definition validates HTTP
|
|
5
|
+
input, job payloads, env vars, AI tool inputs and AI structured output.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { v } from '@cslug/validation'
|
|
9
|
+
|
|
10
|
+
export const StoreTripRequestValidator = v.object({
|
|
11
|
+
circuitId: v.uuid(),
|
|
12
|
+
startDate: v.date().future(), // 'YYYY-MM-DD'
|
|
13
|
+
groupSize: v.int().min(1).max(12),
|
|
14
|
+
budget: v.money({ currencies: ['EUR', 'USD', 'GBP'] }), // { amount: bigint, currency }
|
|
15
|
+
email: v.email().toLowerCase(),
|
|
16
|
+
whatsapp: v.phone().optional(), // normalised to E.164
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
type StoreTripRequest = v.infer<typeof StoreTripRequestValidator>
|
|
20
|
+
|
|
21
|
+
const data = StoreTripRequestValidator.parse(input) // or safeParse / parseAsync
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Errors are `ValidationError` (status 422) with **translation keys**, so messages follow the request's locale:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
try { Schema.parse(input) } catch (e) {
|
|
28
|
+
e.errors // { groupSize: ['validation.int.max'] }
|
|
29
|
+
e.messages() // { groupSize: ['Must be at most 12.'] } (or pass a translator)
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
When validation needs services (database checks), write a `Validator` class. The container builds it, and
|
|
34
|
+
`after()` runs once the schema passed:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
@inject(OperatorRepository)
|
|
38
|
+
export class RegisterOperatorValidator extends Validator {
|
|
39
|
+
constructor(private operators: OperatorRepository) { super() }
|
|
40
|
+
schema = v.object({ email: v.email() })
|
|
41
|
+
async after(data: v.infer<this['schema']>, fail: Fail) {
|
|
42
|
+
if (await this.operators.existsBy({ email: data.email })) fail('email', 'validation.unique')
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
- Full reference: [api.md](./api.md)
|
|
48
|
+
- How it's used in apps: [guides/07-validation.md](../../../guides/07-validation.md)
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# @cslug/validation: API
|
|
2
|
+
|
|
3
|
+
Everything below is exported from `@cslug/validation`.
|
|
4
|
+
|
|
5
|
+
## `v`: schema builders
|
|
6
|
+
|
|
7
|
+
| Builder | Output type | Accepts | Notes |
|
|
8
|
+
|---|---|---|---|
|
|
9
|
+
| `v.string()` | `string` | string | |
|
|
10
|
+
| `v.email()` | `string` | string | Trimmed, checked |
|
|
11
|
+
| `v.url()` | `string` | string | Any absolute URL (`https:`, `postgres:`, `redis:` …) except `javascript:`, `data:`, `vbscript:`, `file:`, `blob:`. Narrow it with `.protocols('https:')` |
|
|
12
|
+
| `v.uuid()` / `v.uuid7()` | `string` | string | `uuid7` checks the version nibble |
|
|
13
|
+
| `v.secret()` | `string` | string | Marked secret: redacted by the logger, `writeOnly` in JSON Schema |
|
|
14
|
+
| `v.number()` / `v.int()` | `number` | finite number | `int` = safe integer |
|
|
15
|
+
| `v.bigint()` / `v.amount()` | `bigint` | bigint, safe integer, digit string | JSON has no bigint, so amounts travel as `"220000"` |
|
|
16
|
+
| `v.boolean()` | `boolean` | boolean | |
|
|
17
|
+
| `v.date()` | `string` | `'YYYY-MM-DD'` | Real calendar dates only (Feb 30 is rejected) |
|
|
18
|
+
| `v.datetime()` | `Date` | Date, ISO 8601 string | |
|
|
19
|
+
| `v.enum(['a', 'b'])` | `'a' \| 'b'` | one of the values | Readonly tuples work: `v.enum(TodoPriority)` |
|
|
20
|
+
| `v.literal(x, { message? })` | `x` | exactly `x` | |
|
|
21
|
+
| `v.object(shape)` | inferred | plain object | Unknown keys are **stripped** |
|
|
22
|
+
| `v.array(schema)` | `T[]` | array | |
|
|
23
|
+
| `v.union([a, b])` | `A \| B` | first match | One `union` issue when nothing matches |
|
|
24
|
+
| `v.record(schema)` | `Record<string, T>` | plain object | |
|
|
25
|
+
| `v.money({ currencies?, min?, max? })` | `{ amount: bigint; currency: C }` | `{ amount, currency }` | Currency upper-cased, ISO 4217 |
|
|
26
|
+
| `v.currency(only?)` | `string` / `C` | ISO 4217 code | |
|
|
27
|
+
| `v.country()` | `string` | ISO 3166-1 alpha-2 | Upper-cased; `UK`, `EU` and reserved codes rejected |
|
|
28
|
+
| `v.phone({ defaultCountry? })` | `string` | phone number | Normalised to E.164. With `defaultCountry`, national numbers too (MG, FR, IT, GB, US and ~20 more) |
|
|
29
|
+
| `v.file({ maxSize?, types? })` | `File` | `File` / `Blob` | Size and declared type checked; for PDF, PNG, JPEG, GIF and WebP the **bytes** are checked as well (`parseAsync`) |
|
|
30
|
+
| `v.unknown()` | `unknown` | anything | |
|
|
31
|
+
| `v.coerce.string/number/int/boolean/bigint/date()` | | strings | For query strings, form posts and env vars. `coerce.boolean`: `'1'/'on'/'true'/'yes'` → true; `'0'/'off'/'false'/'no'/''`/absent → false |
|
|
32
|
+
|
|
33
|
+
Types: `v.infer<typeof S>` (parsed) and `v.input<typeof S>` (before parsing, e.g. what a form holds).
|
|
34
|
+
|
|
35
|
+
## Modifiers (every schema)
|
|
36
|
+
|
|
37
|
+
| Modifier | Effect |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `.optional()` | Accepts `undefined`. In objects, the key becomes optional (`key?:`) |
|
|
40
|
+
| `.nullable()` | Accepts `null` |
|
|
41
|
+
| `.default(value \| () => value)` | Used when the input is `undefined`; output is never undefined |
|
|
42
|
+
| `.describe(text)` | Exported as JSON Schema `description` |
|
|
43
|
+
| `.refine(check, { message?, path?, params? })` | Extra rule on the parsed value |
|
|
44
|
+
| `.refineAsync(check, options)` | Async rule; needs `parseAsync()` |
|
|
45
|
+
| `.transform(fn)` | Map the parsed value |
|
|
46
|
+
| `.parse(x)` / `.safeParse(x)` / `.parseAsync(x)` | Throw / result object / async |
|
|
47
|
+
| `.toJSONSchema()` | JSON Schema draft 2020-12 |
|
|
48
|
+
|
|
49
|
+
Schema-specific: `string().min/max/length/nonempty/regex/trim/toLowerCase/toUpperCase/email/url/protocols/uuid/uuid7` ·
|
|
50
|
+
`number().int/min/max/positive/nonnegative` · `bigint().min/max/nonnegative` · `date().future/past/min/max` ·
|
|
51
|
+
`array().min/max/nonempty` · `object().strict/passthrough/partial/pick/omit/extend/shape`.
|
|
52
|
+
|
|
53
|
+
Schemas are **immutable**: every modifier returns a new schema.
|
|
54
|
+
|
|
55
|
+
## Errors
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
class ValidationError extends Error {
|
|
59
|
+
status: 422
|
|
60
|
+
code: 'validation.failed'
|
|
61
|
+
issues: Issue[]
|
|
62
|
+
constructor(input: Issue[] | Record<string, string | string[]>) // e.g. new ValidationError({ email: ['auth.failed'] })
|
|
63
|
+
get errors(): Record<string, string[]> // message keys by dot path
|
|
64
|
+
messages(translate?: Translate): Record<string, string[]> // human text
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
type Issue = { path: (string | number)[]; code: string; message: string; params?: Record<string, unknown> }
|
|
68
|
+
type Translate = (key: string, params: Record<string, unknown>) => string | undefined
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Message keys are `validation.<code>` (`validation.required`, `validation.int.max`, …) unless the schema has a
|
|
72
|
+
custom `message`. `formatMessage(issue, translate?)` and `interpolate(template, params)` are exported for
|
|
73
|
+
renderers. English fallbacks are built in.
|
|
74
|
+
|
|
75
|
+
## Validators
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
abstract class Validator {
|
|
79
|
+
abstract readonly schema: Schema
|
|
80
|
+
// optional: after(data, fail): void | Promise<void>, which needs no `override`
|
|
81
|
+
validate(input: unknown): Promise<Output>
|
|
82
|
+
}
|
|
83
|
+
type Fail = (path: string, message: string, params?: Record<string, unknown>) => void
|
|
84
|
+
|
|
85
|
+
validate(target: Schema | Validator | StandardSchemaV1, input): Promise<Output<typeof target>>
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Configuration
|
|
89
|
+
|
|
90
|
+
`configure({ today: () => 'YYYY-MM-DD' })`: `@cslug/core` sets this from its `Clock` at boot, so
|
|
91
|
+
`date().future()` uses the app's time zone. The default is UTC.
|
|
92
|
+
|
|
93
|
+
## Standard Schema
|
|
94
|
+
|
|
95
|
+
Every schema has `'~standard'` (vendor `cslug`). `validate()` accepts any Standard Schema (Zod, Valibot,
|
|
96
|
+
ArkType). `StandardSchemaV1` types are exported.
|
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/validation",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Schemas and validators (Zod-like API, Standard Schema, JSON Schema export).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/cslugts/cslug.git",
|
|
10
|
+
"directory": "packages/validation"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cslugts/cslug/tree/main/packages/validation",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cslug",
|
|
15
|
+
"bun",
|
|
16
|
+
"framework"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/index.ts"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"src",
|
|
23
|
+
"docs",
|
|
24
|
+
"stubs",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"bun": ">=1.3.14"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { type Ctx, INVALID, type Invalid, type JsonSchema, OptionalSchema, Schema } from './schema'
|
|
2
|
+
|
|
3
|
+
type Flatten<T> = { [K in keyof T]: T[K] } & {}
|
|
4
|
+
export type Shape = Record<string, Schema>
|
|
5
|
+
|
|
6
|
+
type OptionalOutKeys<S extends Shape> = { [K in keyof S]: undefined extends S[K]['_output'] ? K : never }[keyof S]
|
|
7
|
+
type OptionalInKeys<S extends Shape> = { [K in keyof S]: undefined extends S[K]['_input'] ? K : never }[keyof S]
|
|
8
|
+
|
|
9
|
+
/** Keys whose schema accepts `undefined` become optional (`key?:`), as you would write the type by hand. */
|
|
10
|
+
export type ObjectOutput<S extends Shape> = Flatten<
|
|
11
|
+
{ [K in Exclude<keyof S, OptionalOutKeys<S>>]: S[K]['_output'] } & { [K in OptionalOutKeys<S>]?: S[K]['_output'] }
|
|
12
|
+
>
|
|
13
|
+
export type ObjectInput<S extends Shape> = Flatten<
|
|
14
|
+
{ [K in Exclude<keyof S, OptionalInKeys<S>>]: S[K]['_input'] } & { [K in OptionalInKeys<S>]?: S[K]['_input'] }
|
|
15
|
+
>
|
|
16
|
+
|
|
17
|
+
type UnknownKeys = 'strip' | 'strict' | 'passthrough'
|
|
18
|
+
|
|
19
|
+
const isPlainObject = (v: unknown): v is Record<string, unknown> =>
|
|
20
|
+
typeof v === 'object' && v !== null && !Array.isArray(v) && !(v instanceof Date)
|
|
21
|
+
|
|
22
|
+
export class ObjectSchema<S extends Shape> extends Schema<ObjectOutput<S>, ObjectInput<S>> {
|
|
23
|
+
constructor(
|
|
24
|
+
readonly shape: S,
|
|
25
|
+
def: Record<string, unknown> = {},
|
|
26
|
+
) {
|
|
27
|
+
super(def)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
_run(value: unknown, ctx: Ctx): ObjectOutput<S> | Invalid {
|
|
31
|
+
if (value === undefined || value === null) return this._issue(ctx, 'required')
|
|
32
|
+
if (!isPlainObject(value)) {
|
|
33
|
+
return this._issue(ctx, 'invalid_type', {
|
|
34
|
+
expected: 'object',
|
|
35
|
+
received: Array.isArray(value) ? 'array' : typeof value,
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
const out: Record<string, unknown> = {}
|
|
39
|
+
let ok = true
|
|
40
|
+
for (const [key, schema] of Object.entries(this.shape)) {
|
|
41
|
+
ctx.path.push(key)
|
|
42
|
+
const r = schema._parse(value[key], ctx)
|
|
43
|
+
ctx.path.pop()
|
|
44
|
+
if (r === INVALID) ok = false
|
|
45
|
+
else if (r !== undefined || key in value) out[key] = r
|
|
46
|
+
}
|
|
47
|
+
const mode = (this._def.unknownKeys as UnknownKeys | undefined) ?? 'strip'
|
|
48
|
+
if (mode !== 'strip') {
|
|
49
|
+
const extra = Object.keys(value).filter((k) => !(k in this.shape))
|
|
50
|
+
if (mode === 'strict' && extra.length) {
|
|
51
|
+
this._issue(ctx, 'unrecognized_keys', { keys: extra })
|
|
52
|
+
ok = false
|
|
53
|
+
}
|
|
54
|
+
if (mode === 'passthrough') for (const k of extra) out[k] = value[k]
|
|
55
|
+
}
|
|
56
|
+
return ok ? (out as ObjectOutput<S>) : INVALID
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Reject unknown keys (the default is to drop them silently). */
|
|
60
|
+
strict(): this {
|
|
61
|
+
return this._with({ unknownKeys: 'strict' })
|
|
62
|
+
}
|
|
63
|
+
/** Keep unknown keys as they are. */
|
|
64
|
+
passthrough(): this {
|
|
65
|
+
return this._with({ unknownKeys: 'passthrough' })
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Every field optional, for PATCH-style updates. Refinements of the original object are not kept. */
|
|
69
|
+
partial(): ObjectSchema<{ [K in keyof S]: OptionalSchema<S[K]> }> {
|
|
70
|
+
const shape = Object.fromEntries(Object.entries(this.shape).map(([k, s]) => [k, s.optional()]))
|
|
71
|
+
return new ObjectSchema(shape as { [K in keyof S]: OptionalSchema<S[K]> }, { unknownKeys: this._def.unknownKeys })
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
pick<K extends keyof S & string>(...keys: K[]): ObjectSchema<Pick<S, K>> {
|
|
75
|
+
const shape = Object.fromEntries(keys.map((k) => [k, this.shape[k]]))
|
|
76
|
+
return new ObjectSchema(shape as Pick<S, K>, { unknownKeys: this._def.unknownKeys })
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
omit<K extends keyof S & string>(...keys: K[]): ObjectSchema<Omit<S, K>> {
|
|
80
|
+
const shape = Object.fromEntries(Object.entries(this.shape).filter(([k]) => !keys.includes(k as K)))
|
|
81
|
+
return new ObjectSchema(shape as unknown as Omit<S, K>, { unknownKeys: this._def.unknownKeys })
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
extend<E extends Shape>(extra: E): ObjectSchema<Flatten<Omit<S, keyof E> & E>> {
|
|
85
|
+
return new ObjectSchema({ ...this.shape, ...extra } as Flatten<Omit<S, keyof E> & E>, {
|
|
86
|
+
unknownKeys: this._def.unknownKeys,
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
_json(): JsonSchema {
|
|
91
|
+
const properties: Record<string, JsonSchema> = {}
|
|
92
|
+
const required: string[] = []
|
|
93
|
+
for (const [k, s] of Object.entries(this.shape)) {
|
|
94
|
+
properties[k] = s._json()
|
|
95
|
+
if (!(s instanceof OptionalSchema) && !('fallback' in s)) required.push(k)
|
|
96
|
+
}
|
|
97
|
+
return this._jsonMeta({
|
|
98
|
+
type: 'object',
|
|
99
|
+
properties,
|
|
100
|
+
...(required.length ? { required } : {}),
|
|
101
|
+
additionalProperties: this._def.unknownKeys === 'passthrough',
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export class ArraySchema<T extends Schema> extends Schema<T['_output'][], T['_input'][]> {
|
|
107
|
+
constructor(readonly element: T) {
|
|
108
|
+
super({})
|
|
109
|
+
}
|
|
110
|
+
_run(value: unknown, ctx: Ctx): T['_output'][] | Invalid {
|
|
111
|
+
if (value === undefined || value === null) return this._issue(ctx, 'required')
|
|
112
|
+
if (!Array.isArray(value)) return this._issue(ctx, 'invalid_type', { expected: 'array', received: typeof value })
|
|
113
|
+
const min = this._def.min as number | undefined
|
|
114
|
+
const max = this._def.max as number | undefined
|
|
115
|
+
if (min !== undefined && value.length < min) return this._issue(ctx, 'array.min', { min })
|
|
116
|
+
if (max !== undefined && value.length > max) return this._issue(ctx, 'array.max', { max })
|
|
117
|
+
const out: T['_output'][] = []
|
|
118
|
+
let ok = true
|
|
119
|
+
value.forEach((item, i) => {
|
|
120
|
+
ctx.path.push(i)
|
|
121
|
+
const r = this.element._parse(item, ctx)
|
|
122
|
+
ctx.path.pop()
|
|
123
|
+
if (r === INVALID) ok = false
|
|
124
|
+
else out.push(r)
|
|
125
|
+
})
|
|
126
|
+
return ok ? out : INVALID
|
|
127
|
+
}
|
|
128
|
+
min(min: number) {
|
|
129
|
+
return this._with({ min })
|
|
130
|
+
}
|
|
131
|
+
max(max: number) {
|
|
132
|
+
return this._with({ max })
|
|
133
|
+
}
|
|
134
|
+
nonempty() {
|
|
135
|
+
return this._with({ min: 1 })
|
|
136
|
+
}
|
|
137
|
+
_json(): JsonSchema {
|
|
138
|
+
return this._jsonMeta({
|
|
139
|
+
type: 'array',
|
|
140
|
+
items: this.element._json(),
|
|
141
|
+
...(this._def.min !== undefined ? { minItems: this._def.min } : {}),
|
|
142
|
+
...(this._def.max !== undefined ? { maxItems: this._def.max } : {}),
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The first matching option wins. If none matches, one `union` issue is reported (not every option's issues). */
|
|
148
|
+
export class UnionSchema<T extends readonly [Schema, ...Schema[]]> extends Schema<
|
|
149
|
+
T[number]['_output'],
|
|
150
|
+
T[number]['_input']
|
|
151
|
+
> {
|
|
152
|
+
constructor(readonly options: T) {
|
|
153
|
+
super({})
|
|
154
|
+
}
|
|
155
|
+
_run(value: unknown, ctx: Ctx): T[number]['_output'] | Invalid {
|
|
156
|
+
for (const option of this.options) {
|
|
157
|
+
const trial: Ctx = { path: [...ctx.path], issues: [], pending: ctx.pending }
|
|
158
|
+
const r = option._parse(value, trial)
|
|
159
|
+
if (r !== INVALID && trial.issues.length === 0) return r
|
|
160
|
+
}
|
|
161
|
+
return this._issue(ctx, value === undefined ? 'required' : 'union')
|
|
162
|
+
}
|
|
163
|
+
_json(): JsonSchema {
|
|
164
|
+
return this._jsonMeta({ anyOf: this.options.map((o) => o._json()) })
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** An object with arbitrary keys whose values all match one schema. */
|
|
169
|
+
export class RecordSchema<T extends Schema> extends Schema<Record<string, T['_output']>, Record<string, T['_input']>> {
|
|
170
|
+
constructor(readonly value: T) {
|
|
171
|
+
super({})
|
|
172
|
+
}
|
|
173
|
+
_run(input: unknown, ctx: Ctx): Record<string, T['_output']> | Invalid {
|
|
174
|
+
if (input === undefined || input === null) return this._issue(ctx, 'required')
|
|
175
|
+
if (!isPlainObject(input)) return this._issue(ctx, 'invalid_type', { expected: 'object', received: typeof input })
|
|
176
|
+
const out: Record<string, T['_output']> = {}
|
|
177
|
+
let ok = true
|
|
178
|
+
for (const [k, v] of Object.entries(input)) {
|
|
179
|
+
ctx.path.push(k)
|
|
180
|
+
const r = this.value._parse(v, ctx)
|
|
181
|
+
ctx.path.pop()
|
|
182
|
+
if (r === INVALID) ok = false
|
|
183
|
+
else out[k] = r
|
|
184
|
+
}
|
|
185
|
+
return ok ? out : INVALID
|
|
186
|
+
}
|
|
187
|
+
_json(): JsonSchema {
|
|
188
|
+
return this._jsonMeta({ type: 'object', additionalProperties: this.value._json() })
|
|
189
|
+
}
|
|
190
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Hooks that @cslug/core sets at boot, so validation follows the app's clock and time zone. */
|
|
2
|
+
export const settings = {
|
|
3
|
+
/** Today's date as `YYYY-MM-DD`. Core replaces this with its `Clock`; the default is UTC. */
|
|
4
|
+
today: (): string => new Date().toISOString().slice(0, 10),
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/** Replace the hooks in `settings` (called by @cslug/core at boot). */
|
|
8
|
+
export function configure(options: Partial<typeof settings>): void {
|
|
9
|
+
Object.assign(settings, options)
|
|
10
|
+
}
|
package/src/domain.ts
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/** Schemas for real-world values: money, currencies, countries, phone numbers, uploaded files. */
|
|
2
|
+
import { BigIntSchema } from './primitives'
|
|
3
|
+
import { type Ctx, INVALID, type Invalid, type JsonSchema, Schema } from './schema'
|
|
4
|
+
|
|
5
|
+
// ── currency (ISO 4217) ─────────────────────────────────────────────────────────────────────────────
|
|
6
|
+
const CURRENCIES = new Set(Intl.supportedValuesOf('currency'))
|
|
7
|
+
|
|
8
|
+
export class CurrencySchema<const C extends string = string> extends Schema<C, string> {
|
|
9
|
+
constructor(readonly only?: readonly C[]) {
|
|
10
|
+
super({})
|
|
11
|
+
}
|
|
12
|
+
_run(value: unknown, ctx: Ctx): C | Invalid {
|
|
13
|
+
if (value === undefined || value === null || value === '') return this._issue(ctx, 'required')
|
|
14
|
+
const code = typeof value === 'string' ? value.trim().toUpperCase() : ''
|
|
15
|
+
const allowed = this.only
|
|
16
|
+
? (this.only as readonly string[]).includes(code)
|
|
17
|
+
: /^[A-Z]{3}$/.test(code) && CURRENCIES.has(code)
|
|
18
|
+
return allowed ? (code as C) : this._issue(ctx, 'currency', this.only ? { options: [...this.only] } : undefined)
|
|
19
|
+
}
|
|
20
|
+
_json(): JsonSchema {
|
|
21
|
+
return this._jsonMeta({ type: 'string', ...(this.only ? { enum: [...this.only] } : { pattern: '^[A-Z]{3}$' }) })
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// ── money: { amount: bigint minor units, currency } ─────────────────────────────────────────────────
|
|
26
|
+
export type MoneyValue<C extends string = string> = { amount: bigint; currency: C }
|
|
27
|
+
|
|
28
|
+
export class MoneySchema<const C extends string = string> extends Schema<
|
|
29
|
+
MoneyValue<C>,
|
|
30
|
+
{ amount: bigint | number | string; currency: string }
|
|
31
|
+
> {
|
|
32
|
+
readonly amountSchema: BigIntSchema
|
|
33
|
+
readonly currencySchema: CurrencySchema<C>
|
|
34
|
+
|
|
35
|
+
constructor(options: { currencies?: readonly C[]; min?: bigint | number; max?: bigint | number } = {}) {
|
|
36
|
+
super({})
|
|
37
|
+
let amount = new BigIntSchema()
|
|
38
|
+
if (options.min !== undefined) amount = amount.min(options.min)
|
|
39
|
+
if (options.max !== undefined) amount = amount.max(options.max)
|
|
40
|
+
this.amountSchema = amount
|
|
41
|
+
this.currencySchema = new CurrencySchema<C>(options.currencies)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
_run(value: unknown, ctx: Ctx): MoneyValue<C> | Invalid {
|
|
45
|
+
if (value === undefined || value === null) return this._issue(ctx, 'required')
|
|
46
|
+
if (typeof value !== 'object' || Array.isArray(value)) return this._issue(ctx, 'money')
|
|
47
|
+
const v = value as Record<string, unknown>
|
|
48
|
+
ctx.path.push('amount')
|
|
49
|
+
const amount = this.amountSchema._parse(v.amount, ctx)
|
|
50
|
+
ctx.path.pop()
|
|
51
|
+
ctx.path.push('currency')
|
|
52
|
+
const currency = this.currencySchema._parse(v.currency, ctx)
|
|
53
|
+
ctx.path.pop()
|
|
54
|
+
return amount === INVALID || currency === INVALID ? INVALID : { amount, currency }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
_json(): JsonSchema {
|
|
58
|
+
return this._jsonMeta({
|
|
59
|
+
type: 'object',
|
|
60
|
+
properties: { amount: this.amountSchema._json(), currency: this.currencySchema._json() },
|
|
61
|
+
required: ['amount', 'currency'],
|
|
62
|
+
additionalProperties: false,
|
|
63
|
+
description: this._def.description ?? 'Amount in minor units (e.g. cents) and ISO 4217 currency',
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ── country (ISO 3166-1 alpha-2) ─────────────────────────────────────────────────────────────────────
|
|
69
|
+
const regions = new Intl.DisplayNames(['en'], { type: 'region' })
|
|
70
|
+
/** Codes Intl knows that are not ISO 3166-1 countries (exceptionally reserved, user-assigned, groupings). */
|
|
71
|
+
const NOT_COUNTRIES = new Set(['UK', 'EU', 'EZ', 'UN', 'ZZ', 'QO', 'AC', 'CP', 'DG', 'EA', 'IC', 'TA'])
|
|
72
|
+
|
|
73
|
+
export class CountrySchema extends Schema<string> {
|
|
74
|
+
_run(value: unknown, ctx: Ctx): string | Invalid {
|
|
75
|
+
if (value === undefined || value === null || value === '') return this._issue(ctx, 'required')
|
|
76
|
+
const code = typeof value === 'string' ? value.trim().toUpperCase() : ''
|
|
77
|
+
const known = /^[A-Z]{2}$/.test(code) && !NOT_COUNTRIES.has(code) && regions.of(code) !== code
|
|
78
|
+
return known ? code : this._issue(ctx, 'country')
|
|
79
|
+
}
|
|
80
|
+
_json(): JsonSchema {
|
|
81
|
+
return this._jsonMeta({ type: 'string', pattern: '^[A-Z]{2}$' })
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ── phone (E.164) ────────────────────────────────────────────────────────────────────────────────────
|
|
86
|
+
/**
|
|
87
|
+
* Calling codes for `defaultCountry`, with the national trunk prefix that is dropped ("0" in Madagascar and
|
|
88
|
+
* France, none in Italy). Numbers in other countries must be written with "+".
|
|
89
|
+
*/
|
|
90
|
+
const CALLING: Record<string, { code: string; trunk: string | null }> = {
|
|
91
|
+
MG: { code: '261', trunk: '0' },
|
|
92
|
+
RE: { code: '262', trunk: '0' },
|
|
93
|
+
YT: { code: '262', trunk: '0' },
|
|
94
|
+
MU: { code: '230', trunk: null },
|
|
95
|
+
KM: { code: '269', trunk: null },
|
|
96
|
+
SC: { code: '248', trunk: null },
|
|
97
|
+
MZ: { code: '258', trunk: null },
|
|
98
|
+
ZA: { code: '27', trunk: '0' },
|
|
99
|
+
KE: { code: '254', trunk: '0' },
|
|
100
|
+
FR: { code: '33', trunk: '0' },
|
|
101
|
+
BE: { code: '32', trunk: '0' },
|
|
102
|
+
CH: { code: '41', trunk: '0' },
|
|
103
|
+
DE: { code: '49', trunk: '0' },
|
|
104
|
+
NL: { code: '31', trunk: '0' },
|
|
105
|
+
ES: { code: '34', trunk: null },
|
|
106
|
+
PT: { code: '351', trunk: null },
|
|
107
|
+
IT: { code: '39', trunk: null },
|
|
108
|
+
GB: { code: '44', trunk: '0' },
|
|
109
|
+
IE: { code: '353', trunk: '0' },
|
|
110
|
+
US: { code: '1', trunk: '1' },
|
|
111
|
+
CA: { code: '1', trunk: '1' },
|
|
112
|
+
AU: { code: '61', trunk: '0' },
|
|
113
|
+
JP: { code: '81', trunk: '0' },
|
|
114
|
+
CN: { code: '86', trunk: '0' },
|
|
115
|
+
IN: { code: '91', trunk: '0' },
|
|
116
|
+
KR: { code: '82', trunk: '0' },
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export class PhoneSchema extends Schema<string> {
|
|
120
|
+
readonly calling?: { code: string; trunk: string | null }
|
|
121
|
+
|
|
122
|
+
constructor(readonly defaultCountry?: string) {
|
|
123
|
+
super({})
|
|
124
|
+
if (defaultCountry) {
|
|
125
|
+
this.calling = CALLING[defaultCountry]
|
|
126
|
+
if (!this.calling) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
`v.phone(): no calling code known for "${defaultCountry}"; numbers must then be written with "+"`,
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
_run(value: unknown, ctx: Ctx): string | Invalid {
|
|
134
|
+
if (value === undefined || value === null || value === '') return this._issue(ctx, 'required')
|
|
135
|
+
if (typeof value !== 'string') return this._issue(ctx, 'phone')
|
|
136
|
+
const raw = value.trim().replace(/[\s().-]/g, '')
|
|
137
|
+
let e164: string | undefined
|
|
138
|
+
if (/^\+\d+$/.test(raw)) e164 = raw
|
|
139
|
+
else if (/^00\d+$/.test(raw)) e164 = `+${raw.slice(2)}`
|
|
140
|
+
else if (/^\d+$/.test(raw) && this.calling) {
|
|
141
|
+
const { code, trunk } = this.calling
|
|
142
|
+
const national = trunk && raw.startsWith(trunk) ? raw.slice(trunk.length) : raw
|
|
143
|
+
e164 = `+${code}${national}`
|
|
144
|
+
}
|
|
145
|
+
// E.164: at most 15 digits; 8 is a safe lower bound for real subscriber numbers
|
|
146
|
+
return e164 && /^\+[1-9]\d{7,14}$/.test(e164) ? e164 : this._issue(ctx, 'phone')
|
|
147
|
+
}
|
|
148
|
+
_json(): JsonSchema {
|
|
149
|
+
return this._jsonMeta({
|
|
150
|
+
type: 'string',
|
|
151
|
+
pattern: '^\\+[1-9]\\d{7,14}$',
|
|
152
|
+
description: this._def.description ?? 'E.164 phone number',
|
|
153
|
+
})
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ── uploaded file ───────────────────────────────────────────────────────────────────────────────────
|
|
158
|
+
const SIZE = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)$/i
|
|
159
|
+
const UNITS: Record<string, number> = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3 }
|
|
160
|
+
/** `'2mb'` → 2097152 bytes (b, kb, mb, gb; powers of 1024). */
|
|
161
|
+
export const parseSize = (size: string | number): number => {
|
|
162
|
+
if (typeof size === 'number') return size
|
|
163
|
+
const [, amount, unit] = SIZE.exec(size.trim()) ?? []
|
|
164
|
+
const factor = unit ? UNITS[unit.toLowerCase()] : undefined
|
|
165
|
+
if (!amount || !factor) throw new Error(`Invalid size "${size}" (use e.g. "10mb")`)
|
|
166
|
+
return Math.round(Number(amount) * factor)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Magic numbers for the types we can recognise from the first bytes. */
|
|
170
|
+
const SIGNATURES: [type: string, test: (b: Uint8Array) => boolean][] = [
|
|
171
|
+
['application/pdf', (b) => b[0] === 0x25 && b[1] === 0x50 && b[2] === 0x44 && b[3] === 0x46],
|
|
172
|
+
['image/png', (b) => b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47],
|
|
173
|
+
['image/jpeg', (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff],
|
|
174
|
+
['image/gif', (b) => b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38],
|
|
175
|
+
[
|
|
176
|
+
'image/webp',
|
|
177
|
+
(b) => b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x45,
|
|
178
|
+
],
|
|
179
|
+
]
|
|
180
|
+
|
|
181
|
+
/** The type recognised from the bytes, or undefined if it is not one we can recognise. */
|
|
182
|
+
export async function sniffType(file: Blob): Promise<string | undefined> {
|
|
183
|
+
const head = new Uint8Array(await file.slice(0, 16).arrayBuffer())
|
|
184
|
+
return SIGNATURES.find(([, test]) => test(head))?.[0]
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* An uploaded file (a `File`/`Blob` from multipart form data). Size and declared type are checked by `parse()`;
|
|
189
|
+
* when `types` lists types we can recognise, the **bytes** are checked too, which needs `parseAsync()`
|
|
190
|
+
* (`request.validate()` always uses it).
|
|
191
|
+
*/
|
|
192
|
+
export class FileSchema extends Schema<File> {
|
|
193
|
+
readonly maxBytes?: number
|
|
194
|
+
readonly types?: readonly string[]
|
|
195
|
+
|
|
196
|
+
constructor(options: { maxSize?: string | number; types?: readonly string[] } = {}) {
|
|
197
|
+
super({})
|
|
198
|
+
this.maxBytes = options.maxSize === undefined ? undefined : parseSize(options.maxSize)
|
|
199
|
+
this.types = options.types
|
|
200
|
+
const sniffable = options.types?.filter((t) => SIGNATURES.some(([s]) => s === t)) ?? []
|
|
201
|
+
if (sniffable.length) {
|
|
202
|
+
this._def.refines = [
|
|
203
|
+
{
|
|
204
|
+
check: async (file: File) => {
|
|
205
|
+
const actual = await sniffType(file)
|
|
206
|
+
return actual !== undefined && (options.types as readonly string[]).includes(actual)
|
|
207
|
+
},
|
|
208
|
+
message: 'validation.file.type',
|
|
209
|
+
code: 'file.type',
|
|
210
|
+
path: [],
|
|
211
|
+
params: { types: [...(options.types ?? [])] },
|
|
212
|
+
async: true,
|
|
213
|
+
},
|
|
214
|
+
]
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
_run(value: unknown, ctx: Ctx): File | Invalid {
|
|
219
|
+
if (value === undefined || value === null || value === '') return this._issue(ctx, 'required')
|
|
220
|
+
if (!(value instanceof Blob)) return this._issue(ctx, 'file')
|
|
221
|
+
if (this.maxBytes !== undefined && value.size > this.maxBytes) {
|
|
222
|
+
return this._issue(ctx, 'file.size', { max: formatSize(this.maxBytes) })
|
|
223
|
+
}
|
|
224
|
+
if (this.types && !this.types.includes(value.type)) return this._issue(ctx, 'file.type', { types: [...this.types] })
|
|
225
|
+
return value as File
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
_json(): JsonSchema {
|
|
229
|
+
return this._jsonMeta({
|
|
230
|
+
type: 'string',
|
|
231
|
+
contentEncoding: 'binary',
|
|
232
|
+
...(this.types ? { contentMediaType: this.types.join(', ') } : {}),
|
|
233
|
+
})
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const formatSize = (bytes: number) =>
|
|
238
|
+
bytes >= 1024 ** 2
|
|
239
|
+
? `${+(bytes / 1024 ** 2).toFixed(1)} MB`
|
|
240
|
+
: bytes >= 1024
|
|
241
|
+
? `${+(bytes / 1024).toFixed(1)} KB`
|
|
242
|
+
: `${bytes} B`
|