@scalar/validation 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/src/coerce.ts ADDED
@@ -0,0 +1,171 @@
1
+ import { isObject } from './helpers/is-object'
2
+ import type { Schema } from './schema'
3
+ import type { Static } from './types'
4
+ import { validate } from './validate'
5
+
6
+ /**
7
+ * Computes a "score" indicating how well a value matches a schema,
8
+ * used for picking the best branch in union coercion.
9
+ *
10
+ * Higher score means a closer match. Literals and matching object shapes
11
+ * are weighted more heavily. Objects are scored by shape/literals;
12
+ * arrays/records by structural type; primitives by validation; unions try all branches.
13
+ */
14
+ const scoreUnion = (schema: Schema, value: unknown): number => {
15
+ if (schema.type === 'object') {
16
+ if (!isObject(value)) {
17
+ return 0
18
+ }
19
+
20
+ // For each key in the schema's properties:
21
+ // - +10 if the value matches an explicit literal for the key.
22
+ // - +1 if the property exists (not literal match).
23
+ return Object.keys(schema.properties).reduce<number>((acc, key) => {
24
+ const exists = key in value
25
+ const isLiteralMatch = schema.properties[key].type === 'literal' && value[key] === schema.properties[key].value
26
+ if (isLiteralMatch) {
27
+ return acc + 10
28
+ }
29
+ return acc + (exists ? 1 : 0)
30
+ }, 0)
31
+ }
32
+ if (schema.type === 'array') {
33
+ // Score 1 if value is an array, otherwise 0
34
+ return Array.isArray(value) ? 1 : 0
35
+ }
36
+ if (schema.type === 'record') {
37
+ // TODO: implement smarter scoring for records (just a placeholder for now)
38
+ return isObject(value) ? 1 : 0
39
+ }
40
+ if (schema.type === 'union') {
41
+ // For a union, use the highest score among all sub-schemas
42
+ return Math.max(...schema.schemas.map((schema) => scoreUnion(schema, value)))
43
+ }
44
+
45
+ if (schema.type === 'lazy') {
46
+ // For a lazy schema, evaluate the inner schema and recurse
47
+ return scoreUnion(schema.schema(), value)
48
+ }
49
+
50
+ if (schema.type === 'evaluate') {
51
+ // For an evaluate schema, evaluate the expression and recurse
52
+ return scoreUnion(schema.schema, schema.expression(value))
53
+ }
54
+
55
+ // For primitives and any other type, return 1 if valid, otherwise 0
56
+ return validate(schema, value) ? 1 : 0
57
+ }
58
+
59
+ /**
60
+ * Coerces an unknown value toward the static type implied by `schema`. Values that
61
+ * pass {@link validate} for that branch are kept; otherwise primitives default to
62
+ * `0`, `''`, or `false`, and arrays, records, and objects are built recursively.
63
+ * Unions pick the best-matching branch; `evaluate` runs `expression` before the inner schema.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * import { coerce, number, object, string } from '@scalar/validation'
68
+ *
69
+ * coerce(number(), 42) // 42
70
+ * coerce(number(), 'nope') // 0 — invalid number uses default
71
+ * coerce(object({ id: number(), name: string() }), { id: '1', name: 'Ada' }) // { id: 0, name: 'Ada' }
72
+ * ```
73
+ *
74
+ * The optional `cache` argument tracks visited object–schema pairs to stop infinite recursion
75
+ * on cyclic graphs; callers normally omit it.
76
+ */
77
+ export const coerce = <S extends Schema>(
78
+ schema: S,
79
+ value: unknown,
80
+ cache: WeakMap<object, Set<Schema>> = new WeakMap(),
81
+ ): Static<S> => {
82
+ // Prevent infinite recursion
83
+ if (isObject(value) && cache.get(value)?.has(schema)) {
84
+ return value as Static<S>
85
+ }
86
+ // Track visited schemas to prevent infinite recursion
87
+ if (isObject(value)) {
88
+ const schemas = cache.get(value) || new Set<Schema>()
89
+ schemas.add(schema)
90
+ cache.set(value, schemas)
91
+ }
92
+
93
+ // If no schema is provided, return the value as is
94
+ if (!schema) {
95
+ return value as Static<S>
96
+ }
97
+
98
+ if (schema.type === 'any') {
99
+ return value as unknown as Static<S>
100
+ }
101
+ if (schema.type === 'number') {
102
+ if (validate(schema, value)) {
103
+ return value as Static<S>
104
+ }
105
+ return 0 as Static<S>
106
+ }
107
+ if (schema.type === 'string') {
108
+ if (validate(schema, value)) {
109
+ return value as unknown as Static<S>
110
+ }
111
+ return '' as unknown as Static<S>
112
+ }
113
+ if (schema.type === 'boolean') {
114
+ if (validate(schema, value)) {
115
+ return value as unknown as Static<S>
116
+ }
117
+ return false as unknown as Static<S>
118
+ }
119
+ if (schema.type === 'nullable') {
120
+ return null as unknown as Static<S>
121
+ }
122
+ if (schema.type === 'notDefined') {
123
+ return undefined as unknown as Static<S>
124
+ }
125
+ if (schema.type === 'array') {
126
+ if (!Array.isArray(value)) {
127
+ return [] as unknown as Static<S>
128
+ }
129
+ return value.map((item) => coerce(schema.items, item, cache)) as unknown as Static<S>
130
+ }
131
+ if (schema.type === 'record') {
132
+ if (!isObject(value)) {
133
+ return {} as unknown as Static<S>
134
+ }
135
+ return Object.fromEntries(
136
+ Object.entries(value).map(([key, value]) => [key, coerce(schema.value, value, cache)]),
137
+ ) as unknown as Static<S>
138
+ }
139
+ if (schema.type === 'object') {
140
+ const keys = Object.keys(schema.properties)
141
+ const target = isObject(value) ? value : null
142
+ return Object.fromEntries(
143
+ keys.map((key) => [key, coerce(schema.properties[key], target?.[key], cache)]),
144
+ ) as unknown as Static<S>
145
+ }
146
+ if (schema.type === 'union') {
147
+ const branch = schema.schemas.reduce(
148
+ (acc, schema) => {
149
+ const score = scoreUnion(schema, value)
150
+ return score > acc.score ? { schema, score } : acc
151
+ },
152
+ { schema: schema.schemas[0], score: 0 },
153
+ )
154
+ // We need some way to pick one of the union values
155
+ return coerce(branch.schema, value, cache)
156
+ }
157
+ if (schema.type === 'literal') {
158
+ return schema.value
159
+ }
160
+ if (schema.type === 'lazy') {
161
+ return coerce(schema.schema(), value, cache)
162
+ }
163
+ if (schema.type === 'evaluate') {
164
+ return coerce(schema.schema, schema.expression(value), cache)
165
+ }
166
+
167
+ // We need to assert here that schema has the type never so we know we handle all cases
168
+ const _exhaustive: never = schema
169
+ console.warn('Unknown schema type:', _exhaustive)
170
+ return value as unknown as Static<S>
171
+ }
@@ -0,0 +1,168 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { isObject } from './is-object'
4
+
5
+ describe('isObject', () => {
6
+ it('returns true for plain empty objects', () => {
7
+ expect(isObject({})).toBe(true)
8
+ })
9
+
10
+ it('returns true for objects with properties', () => {
11
+ expect(isObject({ a: 1 })).toBe(true)
12
+ expect(isObject({ a: 1, b: 2, c: 3 })).toBe(true)
13
+ })
14
+
15
+ it('returns true for objects with different value types', () => {
16
+ const obj = {
17
+ string: 'hello',
18
+ number: 42,
19
+ boolean: true,
20
+ null: null,
21
+ undefined: undefined,
22
+ array: [],
23
+ nested: { x: 1 },
24
+ }
25
+ expect(isObject(obj)).toBe(true)
26
+ })
27
+
28
+ it('returns true for objects created with Object.create(null)', () => {
29
+ const obj = Object.create(null)
30
+ expect(isObject(obj)).toBe(true)
31
+ })
32
+
33
+ it('returns false for Date objects', () => {
34
+ expect(isObject(new Date())).toBe(false)
35
+ })
36
+
37
+ it('returns false for RegExp objects', () => {
38
+ expect(isObject(/test/)).toBe(false)
39
+ expect(isObject(new RegExp('test'))).toBe(false)
40
+ })
41
+
42
+ it('returns false for Error objects', () => {
43
+ expect(isObject(new Error('test'))).toBe(false)
44
+ })
45
+
46
+ it('returns false for Map objects', () => {
47
+ expect(isObject(new Map())).toBe(false)
48
+ })
49
+
50
+ it('returns false for Set objects', () => {
51
+ expect(isObject(new Set())).toBe(false)
52
+ })
53
+
54
+ it('returns false for WeakMap objects', () => {
55
+ expect(isObject(new WeakMap())).toBe(false)
56
+ })
57
+
58
+ it('returns false for WeakSet objects', () => {
59
+ expect(isObject(new WeakSet())).toBe(false)
60
+ })
61
+
62
+ it('returns false for Promise objects', () => {
63
+ expect(isObject(Promise.resolve())).toBe(false)
64
+ })
65
+
66
+ it('returns false for arrays', () => {
67
+ expect(isObject([])).toBe(false)
68
+ expect(isObject([1, 2, 3])).toBe(false)
69
+ expect(isObject(new Array(10))).toBe(false)
70
+ })
71
+
72
+ it('returns false for null', () => {
73
+ expect(isObject(null)).toBe(false)
74
+ })
75
+
76
+ it('returns false for undefined', () => {
77
+ expect(isObject(undefined)).toBe(false)
78
+ })
79
+
80
+ it('returns false for numbers', () => {
81
+ expect(isObject(0)).toBe(false)
82
+ expect(isObject(123)).toBe(false)
83
+ expect(isObject(-456)).toBe(false)
84
+ expect(isObject(3.14)).toBe(false)
85
+ expect(isObject(Number.NaN)).toBe(false)
86
+ expect(isObject(Number.POSITIVE_INFINITY)).toBe(false)
87
+ expect(isObject(Number.NEGATIVE_INFINITY)).toBe(false)
88
+ })
89
+
90
+ it('returns false for strings', () => {
91
+ expect(isObject('')).toBe(false)
92
+ expect(isObject('string')).toBe(false)
93
+ expect(isObject('hello world')).toBe(false)
94
+ })
95
+
96
+ it('returns false for booleans', () => {
97
+ expect(isObject(true)).toBe(false)
98
+ expect(isObject(false)).toBe(false)
99
+ })
100
+
101
+ it('returns false for functions', () => {
102
+ expect(
103
+ isObject(() => {
104
+ return
105
+ }),
106
+ ).toBe(false)
107
+ expect(
108
+ isObject(() => {
109
+ return
110
+ }),
111
+ ).toBe(false)
112
+ expect(
113
+ isObject(async () => {
114
+ return await Promise.resolve()
115
+ }),
116
+ ).toBe(false)
117
+ })
118
+
119
+ it('returns false for symbols', () => {
120
+ expect(isObject(Symbol('test'))).toBe(false)
121
+ expect(isObject(Symbol.for('test'))).toBe(false)
122
+ })
123
+
124
+ it('returns false for BigInt values', () => {
125
+ expect(isObject(BigInt(123))).toBe(false)
126
+ expect(isObject(123n)).toBe(false)
127
+ })
128
+
129
+ it('works correctly as a type guard', () => {
130
+ const value: unknown = { a: 1, b: 2 }
131
+
132
+ if (isObject(value)) {
133
+ // TypeScript should narrow the type to Record<string, unknown>
134
+ const keys = Object.keys(value)
135
+ expect(keys).toEqual(['a', 'b'])
136
+ expect(value.a).toBe(1)
137
+ }
138
+ })
139
+
140
+ it('handles objects with nested structures', () => {
141
+ const obj = {
142
+ nested: {
143
+ deeper: {
144
+ value: 'test',
145
+ },
146
+ },
147
+ }
148
+ expect(isObject(obj)).toBe(true)
149
+ })
150
+
151
+ it('returns false for class instances', () => {
152
+ class CustomClass {
153
+ prop = 'value'
154
+ }
155
+ const instance = new CustomClass()
156
+ expect(isObject(instance)).toBe(false)
157
+ })
158
+
159
+ it('handles frozen objects', () => {
160
+ const obj = Object.freeze({ a: 1 })
161
+ expect(isObject(obj)).toBe(true)
162
+ })
163
+
164
+ it('handles sealed objects', () => {
165
+ const obj = Object.seal({ a: 1 })
166
+ expect(isObject(obj)).toBe(true)
167
+ })
168
+ })
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Stolen from |@scalar/helpers/object/is-object.ts|
3
+ * so we don't have to depend on it.
4
+ */
5
+
6
+ /**
7
+ * Returns true if the provided value is a record object
8
+ * (i.e. not null, not an array, and has an actual object as the prototype).
9
+ *
10
+ * Differs from the previous isObject in that it returns false for Date,
11
+ * RegExp, Error, Map, Set, WeakMap, WeakSet, Promise, and other non-plain objects.
12
+ *
13
+ * Examples:
14
+ * isObject({}) // true
15
+ * isObject({ a: 1 }) // true
16
+ * isObject([]) // false (Array)
17
+ * isObject(null) // false
18
+ * isObject(123) // false
19
+ * isObject('string') // false
20
+ * isObject(new Error('test')) // false
21
+ * isObject(new Date()) // false
22
+ * isObject(Object.create(null)) // true
23
+ */
24
+ export const isObject = (value: unknown): value is Record<string | number | symbol, unknown> => {
25
+ if (value === null || typeof value !== 'object') {
26
+ return false
27
+ }
28
+
29
+ const proto = Object.getPrototypeOf(value)
30
+ return proto === Object.prototype || proto === null
31
+ }
package/src/index.ts ADDED
@@ -0,0 +1,20 @@
1
+ export { coerce } from './coerce'
2
+ export {
3
+ type Schema,
4
+ any,
5
+ array,
6
+ boolean,
7
+ evaluate,
8
+ lazy,
9
+ literal,
10
+ notDefined,
11
+ nullable,
12
+ number,
13
+ object,
14
+ optional,
15
+ record,
16
+ string,
17
+ union,
18
+ } from './schema'
19
+ export type { Static } from './types'
20
+ export { validate } from './validate'
package/src/schema.ts ADDED
@@ -0,0 +1,178 @@
1
+ /** Schema for finite numeric values. {@link Static} resolves to `number`. */
2
+ export type NumberSchema = {
3
+ type: 'number'
4
+ }
5
+
6
+ /** Schema for string values. {@link Static} resolves to `string`. */
7
+ export type StringSchema = {
8
+ type: 'string'
9
+ }
10
+
11
+ /** Schema for boolean values. {@link Static} resolves to `boolean`. */
12
+ export type BooleanSchema = {
13
+ type: 'boolean'
14
+ }
15
+
16
+ /** Schema for `null`. {@link Static} resolves to `null`. */
17
+ export type NullableSchema = {
18
+ type: 'nullable'
19
+ }
20
+
21
+ /** Schema for a missing or omitted value. {@link Static} resolves to `undefined`. */
22
+ export type NotDefinedSchema = {
23
+ type: 'notDefined'
24
+ }
25
+
26
+ /** Schema that accepts any value without narrowing. {@link Static} resolves to `any`. */
27
+ export type AnySchema = {
28
+ type: 'any'
29
+ }
30
+
31
+ /** Schema for homogeneous lists. {@link Static} resolves to an array of the item static type. */
32
+ export type ArraySchema<Item extends Schema> = {
33
+ type: 'array'
34
+ items: Item
35
+ }
36
+
37
+ /** Schema for key-value maps with uniform value shape. Keys are constrained to string or number schemas. */
38
+ export type RecordSchema<Key extends StringSchema | NumberSchema | AnySchema, Value extends Schema> = {
39
+ type: 'record'
40
+ key: Key
41
+ value: Value
42
+ }
43
+
44
+ /** Schema for objects with a fixed set of named properties, each with its own schema. */
45
+ export type ObjectSchema<Properties extends Record<string, Schema>> = {
46
+ type: 'object'
47
+ properties: Properties
48
+ }
49
+
50
+ /** Schema that matches if any member schema matches (discriminated union when literals or object tags differ). */
51
+ export type UnionSchema<Schemas extends Schema[]> = {
52
+ type: 'union'
53
+ schemas: Schemas
54
+ }
55
+
56
+ /** Schema for a single exact constant (string, number, boolean, or bigint). {@link Static} is that literal type. */
57
+ export type LiteralSchema<T extends string | number | boolean | bigint> = {
58
+ type: 'literal'
59
+ value: T
60
+ }
61
+
62
+ /**
63
+ * Schema for self-referential or recursive types (such as trees or linked lists).
64
+ * The `schema` property is a factory function returning a schema instance, allowing
65
+ * references to itself without causing circular definition errors at type-level.
66
+ */
67
+ export type LazySchema<S extends () => Schema> = {
68
+ type: 'lazy'
69
+ schema: S
70
+ }
71
+
72
+ /**
73
+ * Schema that runs a coercion or transform (`expression`) on the input, then validates with the inner schema.
74
+ * Use when parsing needs a preprocessing step before the usual rules apply.
75
+ */
76
+ export type EvaluateSchema<S extends Schema> = {
77
+ type: 'evaluate'
78
+ expression: (value: unknown) => unknown
79
+ schema: S
80
+ }
81
+
82
+ export type Schema =
83
+ | NumberSchema
84
+ | StringSchema
85
+ | BooleanSchema
86
+ | NullableSchema
87
+ | NotDefinedSchema
88
+ | AnySchema
89
+ | ArraySchema<any>
90
+ | RecordSchema<any, any>
91
+ | ObjectSchema<Record<string, any>>
92
+ | UnionSchema<any[]>
93
+ | LiteralSchema<any>
94
+ | LazySchema<any>
95
+ | EvaluateSchema<any>
96
+
97
+ const number = (): NumberSchema => ({
98
+ type: 'number',
99
+ })
100
+
101
+ const string = (): StringSchema => ({
102
+ type: 'string',
103
+ })
104
+
105
+ const boolean = (): BooleanSchema => ({
106
+ type: 'boolean',
107
+ })
108
+
109
+ const nullable = (): NullableSchema => ({
110
+ type: 'nullable',
111
+ })
112
+
113
+ const notDefined = (): NotDefinedSchema => ({
114
+ type: 'notDefined',
115
+ })
116
+
117
+ const any = (): AnySchema => ({
118
+ type: 'any',
119
+ })
120
+
121
+ const array = <Item extends Schema>(items: Item): ArraySchema<Item> => ({
122
+ type: 'array',
123
+ items,
124
+ })
125
+
126
+ const record = <Key extends StringSchema | AnySchema, Value extends Schema>(
127
+ key: Key,
128
+ value: Value,
129
+ ): RecordSchema<Key, Value> => ({
130
+ type: 'record',
131
+ key,
132
+ value,
133
+ })
134
+
135
+ const object = <Properties extends Record<string, Schema>>(properties: Properties): ObjectSchema<Properties> => ({
136
+ type: 'object',
137
+ properties,
138
+ })
139
+
140
+ const union = <Schemas extends Schema[]>(schemas: Schemas): UnionSchema<Schemas> => ({
141
+ type: 'union',
142
+ schemas,
143
+ })
144
+
145
+ const optional = <S extends Schema>(schema: S) => union([schema, notDefined()])
146
+
147
+ const literal = <Value extends string | number | boolean | bigint>(value: Value): LiteralSchema<Value> => ({
148
+ type: 'literal',
149
+ value,
150
+ })
151
+
152
+ const lazy = <S extends () => Schema>(schema: S): LazySchema<S> => ({
153
+ type: 'lazy',
154
+ schema,
155
+ })
156
+
157
+ const evaluate = <S extends Schema>(expression: (value: unknown) => unknown, schema: S): EvaluateSchema<S> => ({
158
+ type: 'evaluate',
159
+ expression,
160
+ schema,
161
+ })
162
+
163
+ export {
164
+ number,
165
+ string,
166
+ boolean,
167
+ nullable,
168
+ notDefined,
169
+ any,
170
+ array,
171
+ record,
172
+ object,
173
+ union,
174
+ optional,
175
+ literal,
176
+ lazy,
177
+ evaluate,
178
+ }
package/src/types.ts ADDED
@@ -0,0 +1,72 @@
1
+ import type {
2
+ AnySchema,
3
+ ArraySchema,
4
+ BooleanSchema,
5
+ EvaluateSchema,
6
+ LazySchema,
7
+ LiteralSchema,
8
+ NotDefinedSchema,
9
+ NullableSchema,
10
+ NumberSchema,
11
+ ObjectSchema,
12
+ RecordSchema,
13
+ StringSchema,
14
+ UnionSchema,
15
+ } from './schema'
16
+
17
+ // Export Static type with depth limit to prevent infinite recursion
18
+ export type Static<T> = _Static<T, 10>
19
+
20
+ // Internal type with depth counter
21
+ type _Static<T, Depth extends number = 10> = Depth extends 0
22
+ ? any
23
+ : T extends LiteralSchema<infer Value>
24
+ ? Value
25
+ : T extends NumberSchema
26
+ ? number
27
+ : T extends StringSchema
28
+ ? string
29
+ : T extends BooleanSchema
30
+ ? boolean
31
+ : T extends NullableSchema
32
+ ? null
33
+ : T extends NotDefinedSchema
34
+ ? undefined
35
+ : T extends AnySchema
36
+ ? any
37
+ : T extends ArraySchema<infer Item>
38
+ ? Array<_Static<Item, Prev<Depth>>>
39
+ : T extends RecordSchema<infer Key, infer Value>
40
+ ? Record<_Static<Key, Prev<Depth>> & PropertyKey, _Static<Value, Prev<Depth>>>
41
+ : T extends ObjectSchema<infer Properties>
42
+ ? { [K in keyof Properties]: _Static<Properties[K], Prev<Depth>> }
43
+ : T extends UnionSchema<infer Schemas>
44
+ ? _Static<Schemas[number], Prev<Depth>>
45
+ : T extends EvaluateSchema<infer S>
46
+ ? _Static<S, Prev<Depth>>
47
+ : T extends LazySchema<infer S>
48
+ ? _Static<ReturnType<S>, Prev<Depth>>
49
+ : never
50
+
51
+ // Helper type to decrement depth counter
52
+ type Prev<T extends number> = T extends 10
53
+ ? 9
54
+ : T extends 9
55
+ ? 8
56
+ : T extends 8
57
+ ? 7
58
+ : T extends 7
59
+ ? 6
60
+ : T extends 6
61
+ ? 5
62
+ : T extends 5
63
+ ? 4
64
+ : T extends 4
65
+ ? 3
66
+ : T extends 3
67
+ ? 2
68
+ : T extends 2
69
+ ? 1
70
+ : T extends 1
71
+ ? 0
72
+ : 0