@atproto/lex-schema 0.1.5 → 0.1.6

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.
Files changed (263) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/core/$type.d.ts +2 -2
  3. package/dist/core/$type.d.ts.map +1 -1
  4. package/dist/core/$type.js.map +1 -1
  5. package/dist/core/record-key.d.ts +1 -1
  6. package/dist/core/record-key.d.ts.map +1 -1
  7. package/dist/core/record-key.js.map +1 -1
  8. package/dist/core/schema.d.ts +3 -2
  9. package/dist/core/schema.d.ts.map +1 -1
  10. package/dist/core/schema.js +1 -1
  11. package/dist/core/schema.js.map +1 -1
  12. package/dist/core/standard-schema.d.ts +2 -2
  13. package/dist/core/standard-schema.d.ts.map +1 -1
  14. package/dist/core/standard-schema.js.map +1 -1
  15. package/dist/core/string-format.d.ts +2 -2
  16. package/dist/core/string-format.d.ts.map +1 -1
  17. package/dist/core/string-format.js.map +1 -1
  18. package/dist/core/validation-error.d.ts +1 -1
  19. package/dist/core/validation-error.d.ts.map +1 -1
  20. package/dist/core/validation-error.js +1 -1
  21. package/dist/core/validation-error.js.map +1 -1
  22. package/dist/core/validator.d.ts +1 -1
  23. package/dist/core/validator.d.ts.map +1 -1
  24. package/dist/core/validator.js +1 -1
  25. package/dist/core/validator.js.map +1 -1
  26. package/dist/helpers.d.ts +2 -2
  27. package/dist/helpers.d.ts.map +1 -1
  28. package/dist/helpers.js +2 -2
  29. package/dist/helpers.js.map +1 -1
  30. package/dist/schema/array.d.ts +1 -1
  31. package/dist/schema/array.d.ts.map +1 -1
  32. package/dist/schema/array.js +1 -1
  33. package/dist/schema/array.js.map +1 -1
  34. package/dist/schema/blob.d.ts +1 -1
  35. package/dist/schema/blob.d.ts.map +1 -1
  36. package/dist/schema/blob.js +2 -2
  37. package/dist/schema/blob.js.map +1 -1
  38. package/dist/schema/boolean.js +1 -1
  39. package/dist/schema/boolean.js.map +1 -1
  40. package/dist/schema/bytes.js +1 -1
  41. package/dist/schema/bytes.js.map +1 -1
  42. package/dist/schema/cid.d.ts +1 -1
  43. package/dist/schema/cid.d.ts.map +1 -1
  44. package/dist/schema/cid.js +3 -3
  45. package/dist/schema/cid.js.map +1 -1
  46. package/dist/schema/custom.js +1 -1
  47. package/dist/schema/custom.js.map +1 -1
  48. package/dist/schema/dict.d.ts +1 -1
  49. package/dist/schema/dict.d.ts.map +1 -1
  50. package/dist/schema/dict.js +1 -1
  51. package/dist/schema/dict.js.map +1 -1
  52. package/dist/schema/discriminated-union.d.ts +1 -1
  53. package/dist/schema/discriminated-union.d.ts.map +1 -1
  54. package/dist/schema/discriminated-union.js +2 -1
  55. package/dist/schema/discriminated-union.js.map +1 -1
  56. package/dist/schema/enum.js +1 -1
  57. package/dist/schema/enum.js.map +1 -1
  58. package/dist/schema/integer.js +1 -1
  59. package/dist/schema/integer.js.map +1 -1
  60. package/dist/schema/intersection.d.ts +1 -1
  61. package/dist/schema/intersection.d.ts.map +1 -1
  62. package/dist/schema/intersection.js +3 -1
  63. package/dist/schema/intersection.js.map +1 -1
  64. package/dist/schema/lex-map.d.ts +1 -1
  65. package/dist/schema/lex-map.d.ts.map +1 -1
  66. package/dist/schema/lex-map.js +1 -1
  67. package/dist/schema/lex-map.js.map +1 -1
  68. package/dist/schema/lex-value.d.ts +1 -1
  69. package/dist/schema/lex-value.d.ts.map +1 -1
  70. package/dist/schema/lex-value.js +1 -1
  71. package/dist/schema/lex-value.js.map +1 -1
  72. package/dist/schema/literal.js +1 -1
  73. package/dist/schema/literal.js.map +1 -1
  74. package/dist/schema/never.js +1 -1
  75. package/dist/schema/never.js.map +1 -1
  76. package/dist/schema/null.js +1 -1
  77. package/dist/schema/null.js.map +1 -1
  78. package/dist/schema/nullable.d.ts +1 -1
  79. package/dist/schema/nullable.d.ts.map +1 -1
  80. package/dist/schema/nullable.js +1 -1
  81. package/dist/schema/nullable.js.map +1 -1
  82. package/dist/schema/object.d.ts +2 -1
  83. package/dist/schema/object.d.ts.map +1 -1
  84. package/dist/schema/object.js +1 -1
  85. package/dist/schema/object.js.map +1 -1
  86. package/dist/schema/optional.d.ts +2 -1
  87. package/dist/schema/optional.d.ts.map +1 -1
  88. package/dist/schema/optional.js +2 -1
  89. package/dist/schema/optional.js.map +1 -1
  90. package/dist/schema/params.d.ts +1 -1
  91. package/dist/schema/params.d.ts.map +1 -1
  92. package/dist/schema/params.js +1 -1
  93. package/dist/schema/params.js.map +1 -1
  94. package/dist/schema/payload.d.ts +3 -2
  95. package/dist/schema/payload.d.ts.map +1 -1
  96. package/dist/schema/payload.js +2 -1
  97. package/dist/schema/payload.js.map +1 -1
  98. package/dist/schema/permission-set.d.ts +1 -1
  99. package/dist/schema/permission-set.d.ts.map +1 -1
  100. package/dist/schema/permission-set.js +1 -0
  101. package/dist/schema/permission-set.js.map +1 -1
  102. package/dist/schema/permission.d.ts +1 -1
  103. package/dist/schema/permission.d.ts.map +1 -1
  104. package/dist/schema/permission.js.map +1 -1
  105. package/dist/schema/procedure.d.ts +1 -1
  106. package/dist/schema/procedure.d.ts.map +1 -1
  107. package/dist/schema/procedure.js +2 -0
  108. package/dist/schema/procedure.js.map +1 -1
  109. package/dist/schema/query.d.ts +1 -1
  110. package/dist/schema/query.d.ts.map +1 -1
  111. package/dist/schema/query.js +2 -0
  112. package/dist/schema/query.js.map +1 -1
  113. package/dist/schema/record.d.ts +2 -2
  114. package/dist/schema/record.d.ts.map +1 -1
  115. package/dist/schema/record.js +1 -1
  116. package/dist/schema/record.js.map +1 -1
  117. package/dist/schema/ref.d.ts +1 -1
  118. package/dist/schema/ref.d.ts.map +1 -1
  119. package/dist/schema/ref.js +1 -1
  120. package/dist/schema/ref.js.map +1 -1
  121. package/dist/schema/refine.d.ts +2 -2
  122. package/dist/schema/refine.d.ts.map +1 -1
  123. package/dist/schema/refine.js +1 -1
  124. package/dist/schema/refine.js.map +1 -1
  125. package/dist/schema/regexp.js +1 -1
  126. package/dist/schema/regexp.js.map +1 -1
  127. package/dist/schema/string.d.ts +2 -2
  128. package/dist/schema/string.d.ts.map +1 -1
  129. package/dist/schema/string.js +1 -1
  130. package/dist/schema/string.js.map +1 -1
  131. package/dist/schema/subscription.d.ts +3 -2
  132. package/dist/schema/subscription.d.ts.map +1 -1
  133. package/dist/schema/subscription.js +2 -0
  134. package/dist/schema/subscription.js.map +1 -1
  135. package/dist/schema/token.d.ts +1 -1
  136. package/dist/schema/token.d.ts.map +1 -1
  137. package/dist/schema/token.js +1 -1
  138. package/dist/schema/token.js.map +1 -1
  139. package/dist/schema/typed-object.d.ts +2 -2
  140. package/dist/schema/typed-object.d.ts.map +1 -1
  141. package/dist/schema/typed-object.js +1 -1
  142. package/dist/schema/typed-object.js.map +1 -1
  143. package/dist/schema/typed-ref.d.ts +1 -1
  144. package/dist/schema/typed-ref.d.ts.map +1 -1
  145. package/dist/schema/typed-ref.js +1 -1
  146. package/dist/schema/typed-ref.js.map +1 -1
  147. package/dist/schema/typed-union.d.ts +1 -1
  148. package/dist/schema/typed-union.d.ts.map +1 -1
  149. package/dist/schema/typed-union.js +3 -1
  150. package/dist/schema/typed-union.js.map +1 -1
  151. package/dist/schema/union.d.ts +1 -1
  152. package/dist/schema/union.d.ts.map +1 -1
  153. package/dist/schema/union.js +1 -1
  154. package/dist/schema/union.js.map +1 -1
  155. package/dist/schema/unknown.js +1 -1
  156. package/dist/schema/unknown.js.map +1 -1
  157. package/dist/schema/with-default.d.ts +1 -1
  158. package/dist/schema/with-default.d.ts.map +1 -1
  159. package/dist/schema/with-default.js +1 -1
  160. package/dist/schema/with-default.js.map +1 -1
  161. package/package.json +6 -10
  162. package/src/core/$type.test.ts +0 -24
  163. package/src/core/$type.ts +0 -199
  164. package/src/core/record-key.ts +0 -85
  165. package/src/core/result.ts +0 -15
  166. package/src/core/schema.ts +0 -412
  167. package/src/core/standard-schema.test.ts +0 -124
  168. package/src/core/standard-schema.ts +0 -31
  169. package/src/core/string-format.ts +0 -411
  170. package/src/core/types.ts +0 -120
  171. package/src/core/validation-error.ts +0 -134
  172. package/src/core/validation-issue.ts +0 -340
  173. package/src/core/validator.ts +0 -636
  174. package/src/core.ts +0 -9
  175. package/src/external.ts +0 -3
  176. package/src/helpers.test.ts +0 -694
  177. package/src/helpers.ts +0 -222
  178. package/src/index.ts +0 -3
  179. package/src/schema/array.test.ts +0 -251
  180. package/src/schema/array.ts +0 -126
  181. package/src/schema/blob.test.ts +0 -733
  182. package/src/schema/blob.ts +0 -150
  183. package/src/schema/boolean.test.ts +0 -118
  184. package/src/schema/boolean.ts +0 -46
  185. package/src/schema/bytes.test.ts +0 -227
  186. package/src/schema/bytes.ts +0 -81
  187. package/src/schema/cid.test.ts +0 -125
  188. package/src/schema/cid.ts +0 -69
  189. package/src/schema/custom.test.ts +0 -414
  190. package/src/schema/custom.ts +0 -106
  191. package/src/schema/dict.test.ts +0 -181
  192. package/src/schema/dict.ts +0 -122
  193. package/src/schema/discriminated-union.test.ts +0 -676
  194. package/src/schema/discriminated-union.ts +0 -196
  195. package/src/schema/enum.test.ts +0 -398
  196. package/src/schema/enum.ts +0 -77
  197. package/src/schema/integer.test.ts +0 -314
  198. package/src/schema/integer.ts +0 -86
  199. package/src/schema/intersection.test.ts +0 -33
  200. package/src/schema/intersection.ts +0 -113
  201. package/src/schema/lex-map.test.ts +0 -593
  202. package/src/schema/lex-map.ts +0 -63
  203. package/src/schema/lex-value.test.ts +0 -81
  204. package/src/schema/lex-value.ts +0 -86
  205. package/src/schema/literal.test.ts +0 -533
  206. package/src/schema/literal.ts +0 -70
  207. package/src/schema/never.test.ts +0 -175
  208. package/src/schema/never.ts +0 -56
  209. package/src/schema/null.test.ts +0 -80
  210. package/src/schema/null.ts +0 -49
  211. package/src/schema/nullable.test.ts +0 -470
  212. package/src/schema/nullable.ts +0 -74
  213. package/src/schema/object.test.ts +0 -69
  214. package/src/schema/object.ts +0 -136
  215. package/src/schema/optional.test.ts +0 -479
  216. package/src/schema/optional.ts +0 -92
  217. package/src/schema/params.test.ts +0 -1118
  218. package/src/schema/params.ts +0 -371
  219. package/src/schema/payload.test.ts +0 -340
  220. package/src/schema/payload.ts +0 -204
  221. package/src/schema/permission-set.test.ts +0 -613
  222. package/src/schema/permission-set.ts +0 -86
  223. package/src/schema/permission.test.ts +0 -537
  224. package/src/schema/permission.ts +0 -63
  225. package/src/schema/procedure.test.ts +0 -324
  226. package/src/schema/procedure.ts +0 -98
  227. package/src/schema/query.test.ts +0 -348
  228. package/src/schema/query.ts +0 -86
  229. package/src/schema/record.test.ts +0 -812
  230. package/src/schema/record.ts +0 -217
  231. package/src/schema/ref.test.ts +0 -349
  232. package/src/schema/ref.ts +0 -103
  233. package/src/schema/refine.test.ts +0 -579
  234. package/src/schema/refine.ts +0 -153
  235. package/src/schema/regexp.test.ts +0 -577
  236. package/src/schema/regexp.ts +0 -82
  237. package/src/schema/string.test.ts +0 -773
  238. package/src/schema/string.ts +0 -229
  239. package/src/schema/subscription.test.ts +0 -499
  240. package/src/schema/subscription.ts +0 -108
  241. package/src/schema/token.test.ts +0 -152
  242. package/src/schema/token.ts +0 -103
  243. package/src/schema/typed-object.test.ts +0 -745
  244. package/src/schema/typed-object.ts +0 -181
  245. package/src/schema/typed-ref.test.ts +0 -796
  246. package/src/schema/typed-ref.ts +0 -126
  247. package/src/schema/typed-union.test.ts +0 -355
  248. package/src/schema/typed-union.ts +0 -130
  249. package/src/schema/union.test.ts +0 -191
  250. package/src/schema/union.ts +0 -89
  251. package/src/schema/unknown.test.ts +0 -313
  252. package/src/schema/unknown.ts +0 -47
  253. package/src/schema/with-default.ts +0 -81
  254. package/src/schema.ts +0 -43
  255. package/src/util/array-agg.test.ts +0 -42
  256. package/src/util/array-agg.ts +0 -44
  257. package/src/util/assertion-util.ts +0 -1
  258. package/src/util/if-any.ts +0 -3
  259. package/src/util/lazy-property.ts +0 -14
  260. package/src/util/memoize.ts +0 -37
  261. package/tsconfig.build.json +0 -12
  262. package/tsconfig.json +0 -7
  263. package/tsconfig.tests.json +0 -8
@@ -1,371 +0,0 @@
1
- import { isPlainObject } from '@atproto/lex-data'
2
- import {
3
- Infer,
4
- InferInput,
5
- InferOutput,
6
- Issue,
7
- IssueInvalidType,
8
- IssueInvalidValue,
9
- LexValidationError,
10
- ParseOptions,
11
- Schema,
12
- ValidationContext,
13
- Validator,
14
- WithOptionalProperties,
15
- } from '../core.js'
16
- import { lazyProperty } from '../util/lazy-property.js'
17
- import { memoizedOptions } from '../util/memoize.js'
18
- import { ArraySchema, array } from './array.js'
19
- import { BooleanSchema, boolean } from './boolean.js'
20
- import { dict } from './dict.js'
21
- import { EnumSchema } from './enum.js'
22
- import { IntegerSchema, integer } from './integer.js'
23
- import { LiteralSchema } from './literal.js'
24
- import { OptionalSchema, optional } from './optional.js'
25
- import { StringSchema, string } from './string.js'
26
- import { union } from './union.js'
27
- import { WithDefaultSchema } from './with-default.js'
28
-
29
- /**
30
- * Scalar types allowed in URL parameters: boolean, integer, or string.
31
- */
32
- export type ParamScalar = Infer<typeof paramScalarSchema>
33
- const paramScalarSchema = union([boolean(), integer(), string()])
34
-
35
- /**
36
- * A single parameter value: scalar or array of scalars.
37
- */
38
- export type Param = Infer<typeof paramSchema>
39
-
40
- /**
41
- * Schema for validating individual parameter values.
42
- */
43
- export const paramSchema = union([
44
- paramScalarSchema,
45
- array(boolean()),
46
- array(integer()),
47
- array(string()),
48
- ])
49
-
50
- /**
51
- * Type for a params object with string keys and optional param values.
52
- */
53
- export type Params = Infer<typeof paramsSchema>
54
-
55
- /**
56
- * Schema for validating arbitrary params objects.
57
- */
58
- export const paramsSchema = dict(string(), optional(paramSchema))
59
-
60
- export type ParamScalarValidator =
61
- // @NOTE In order to properly coerce URLSearchParams, we need to distinguish
62
- // between scalar and array validators, requiring to be able to detect which
63
- // schema types are being used, restricting the allowed param validators here.
64
- | LiteralSchema<string>
65
- | LiteralSchema<number>
66
- | LiteralSchema<boolean>
67
- | EnumSchema<string>
68
- | EnumSchema<number>
69
- // | EnumSchema<boolean> // Boolean lexicon definitions don't allow "enum"
70
- | StringSchema<any>
71
- | BooleanSchema
72
- | IntegerSchema
73
-
74
- type AsArrayParamSchema<TSchema extends Validator> =
75
- // This allows to "distribute" any union of scalar validators into a union of
76
- // arrays of those validators, instead of an array of union. If TSchema is
77
- // BooleanSchema | IntegerSchema, we want the result to be
78
- // ArraySchema<BooleanSchema> | ArraySchema<IntegerSchema>, not
79
- // ArraySchema<BooleanSchema | IntegerSchema>, since the latter would allow
80
- // arrays with mixed types (e.g. [true, 42]), which we don't want.
81
- TSchema extends any ? ArraySchema<TSchema> : never
82
-
83
- export type ParamValueValidator =
84
- | ParamScalarValidator
85
- | AsArrayParamSchema<ParamScalarValidator>
86
-
87
- export type ParamValidator =
88
- | ParamValueValidator
89
- | OptionalSchema<ParamValueValidator>
90
- | OptionalSchema<WithDefaultSchema<ParamValueValidator>>
91
- | WithDefaultSchema<ParamValueValidator>
92
-
93
- /**
94
- * Type representing the shape of a params schema definition.
95
- *
96
- * Maps parameter names to their validators (must be Param or undefined).
97
- */
98
- export type ParamsShape = {
99
- [x: string]: ParamValidator
100
- }
101
-
102
- /**
103
- * Schema for validating URL query parameters in Lexicon endpoints.
104
- *
105
- * Params are the query string parameters passed to queries, procedures,
106
- * and subscriptions. Values must be scalars (boolean, integer, string)
107
- * or arrays of scalars, as they need to be serializable to URL format.
108
- *
109
- * Provides methods for converting to/from URLSearchParams.
110
- *
111
- * @template TShape - The params shape type mapping names to validators
112
- *
113
- * @example
114
- * ```ts
115
- * const schema = new ParamsSchema({
116
- * limit: l.optional(l.integer({ minimum: 1, maximum: 100 })),
117
- * cursor: l.optional(l.string()),
118
- * })
119
- * ```
120
- */
121
- export class ParamsSchema<
122
- const TShape extends ParamsShape = ParamsShape,
123
- > extends Schema<
124
- WithOptionalProperties<{
125
- [K in keyof TShape]: InferInput<TShape[K]>
126
- }>,
127
- WithOptionalProperties<{
128
- [K in keyof TShape]: InferOutput<TShape[K]>
129
- }>
130
- > {
131
- readonly type = 'params' as const
132
-
133
- constructor(readonly shape: TShape) {
134
- super()
135
- }
136
-
137
- get shapeValidators(): Map<string, ParamValidator> {
138
- const map = new Map(Object.entries(this.shape))
139
-
140
- return lazyProperty(this, 'shapeValidators', map)
141
- }
142
-
143
- validateInContext(input: unknown, ctx: ValidationContext) {
144
- if (!isPlainObject(input)) {
145
- return ctx.issueUnexpectedType(input, 'object')
146
- }
147
-
148
- // Lazily copy value
149
- let copy: undefined | Record<string, unknown>
150
-
151
- // Ensure that non-specified params conform to param schema
152
- for (const key in input) {
153
- if (this.shapeValidators.has(key)) continue
154
-
155
- const result = ctx.validateChild(input, key, paramSchema)
156
- if (!result.success) return result
157
-
158
- if (result.value !== input[key]) {
159
- if (ctx.options.mode === 'validate') {
160
- // In "validate" mode, we can't modify the input, so we issue an error
161
- return ctx.issueInvalidPropertyValue(input, key, [result.value])
162
- }
163
-
164
- copy ??= { ...input }
165
- copy[key] = result.value
166
- }
167
- }
168
-
169
- for (const [key, propDef] of this.shapeValidators) {
170
- const result = ctx.validateChild(input, key, propDef)
171
- if (!result.success) {
172
- if (!(key in input)) {
173
- // Transform into "required key" issue
174
- return ctx.issueRequiredKey(input, key)
175
- }
176
-
177
- return result
178
- }
179
-
180
- // Skip copying if key is not present in input (and value is undefined)
181
- if (result.value === undefined && !(key in input)) {
182
- continue
183
- }
184
-
185
- if (!Object.is(result.value, input[key])) {
186
- if (ctx.options.mode === 'validate') {
187
- // In "validate" mode, we can't modify the input, so we issue an error
188
- return ctx.issueInvalidPropertyValue(input, key, [result.value])
189
- }
190
-
191
- // Copy on write
192
- copy ??= { ...input }
193
- copy[key] = result.value
194
- }
195
- }
196
-
197
- return ctx.success(copy ?? input)
198
- }
199
-
200
- fromURLSearchParams(
201
- input: string | Iterable<[string, string]>,
202
- options?: ParseOptions,
203
- ): InferOutput<this> {
204
- const params: Record<string, unknown> = {}
205
-
206
- const iterable =
207
- typeof input === 'string' ? new URLSearchParams(input) : input
208
- const entries =
209
- iterable instanceof URLSearchParams ? iterable.entries() : iterable
210
-
211
- for (const [name, value] of entries) {
212
- // Ignore empty strings
213
- if (!value) continue
214
-
215
- const validator = this.shapeValidators.get(name)
216
- const innerValidator = validator ? unwrapSchema(validator) : undefined
217
- const expectsArray = innerValidator instanceof ArraySchema
218
- const scalarValidator = expectsArray
219
- ? unwrapSchema(innerValidator.validator)
220
- : innerValidator
221
-
222
- const coerced = coerceParam(name, value, scalarValidator, options)
223
-
224
- const currentParam = params[name]
225
- if (currentParam === undefined) {
226
- params[name] = expectsArray ? [coerced] : coerced
227
- } else if (Array.isArray(currentParam)) {
228
- currentParam.push(coerced)
229
- } else {
230
- params[name] = [currentParam, coerced]
231
- }
232
- }
233
-
234
- return this.parse(params, options)
235
- }
236
-
237
- toURLSearchParams(input: InferInput<this>): URLSearchParams {
238
- const urlSearchParams = new URLSearchParams()
239
-
240
- // @NOTE We apply defaults here to ensure that server with different
241
- // defaults still receive all expected parameters.
242
- const params = this.parse(input)
243
-
244
- for (const [key, value] of Object.entries(params)) {
245
- if (Array.isArray(value)) {
246
- for (const v of value) {
247
- urlSearchParams.append(key, String(v))
248
- }
249
- } else if (value !== undefined) {
250
- urlSearchParams.append(key, String(value))
251
- }
252
- }
253
-
254
- return urlSearchParams
255
- }
256
- }
257
-
258
- function coerceParam(
259
- name: string,
260
- param: string,
261
- schema?: ParamScalarValidator,
262
- options?: ParseOptions,
263
- ): ParamScalar {
264
- let issue: Issue
265
-
266
- if (!schema) {
267
- // The param is unknown (not defined in schema), so we don't apply any
268
- // coercion and just return the string value.
269
- return param
270
- } else if (schema instanceof StringSchema) {
271
- return param
272
- } else if (schema instanceof IntegerSchema) {
273
- if (/^-?\d+$/.test(param)) return Number(param)
274
- issue = new IssueInvalidType(paramPath(name, options), param, ['integer'])
275
- } else if (schema instanceof BooleanSchema) {
276
- if (param === 'true') return true
277
- if (param === 'false') return false
278
- issue = new IssueInvalidType(paramPath(name, options), param, ['boolean'])
279
- } else if (schema instanceof LiteralSchema) {
280
- const { value } = schema
281
- if (String(value) === param) return value
282
- issue = new IssueInvalidValue(paramPath(name, options), param, [value])
283
- } else if (schema instanceof EnumSchema) {
284
- const { values } = schema
285
- for (const value of values) {
286
- if (String(value) === param) return value
287
- }
288
- issue = new IssueInvalidValue(paramPath(name, options), param, values)
289
- } else {
290
- // This should never happen. If it *does*, it means that the user of
291
- // lex-schema is mixing different versions of the lib, which is not
292
- // supported. Throwing an error here is better than silently accepting
293
- // invalid params and causing unexpected behavior down the line (ie. error
294
- // message returning the string value instead of the expected
295
- // boolean/number/string value).
296
- throw new Error(`Unsupported schema type for param coercion: ${schema}`)
297
- }
298
-
299
- // We were not able to coerce the param to the expected type. There is no
300
- // point in returning the original string value since it doesn't conform to
301
- // the expected schema, so we throw a validation error instead. We could
302
- // return the "param" here, which would cause the validation to fail later on
303
- // (see fromURLSearchParams()'s return statement). The main benefit of
304
- // returning the original "param" value is that the error path would include
305
- // the index of the param in case of array params (e.g. "tags[1]"), which
306
- // could be helpful for debugging. The cost overhead is not worth it though
307
- // (IMO).
308
- throw new LexValidationError([issue])
309
- }
310
-
311
- function paramPath(key: string, options?: ParseOptions) {
312
- return options?.path ? [...options.path, key] : [key]
313
- }
314
-
315
- /**
316
- * Creates a params schema for URL query parameters.
317
- *
318
- * Params schemas validate query string parameters for Lexicon endpoints.
319
- * Values must be boolean, integer, string, or arrays of those types.
320
- *
321
- * @param properties - Object mapping parameter names to their validators
322
- * @returns A new {@link ParamsSchema} instance
323
- *
324
- * @example
325
- * ```ts
326
- * // Simple pagination params
327
- * const paginationParams = l.params({
328
- * limit: l.optional(l.withDefault(l.integer({ minimum: 1, maximum: 100 }), 50)),
329
- * cursor: l.optional(l.string()),
330
- * })
331
- *
332
- * // Required parameter
333
- * const actorParams = l.params({
334
- * actor: l.string({ format: 'at-identifier' }),
335
- * })
336
- *
337
- * // Array parameter (multiple values)
338
- * const filterParams = l.params({
339
- * tags: l.optional(l.array(l.string())),
340
- * })
341
- *
342
- * // Convert from URL
343
- * const urlParams = new URLSearchParams('limit=25&cursor=abc')
344
- * const validated = paginationParams.fromURLSearchParams(urlParams)
345
- *
346
- * // Convert to URL
347
- * const searchParams = paginationParams.toURLSearchParams({ limit: 25 })
348
- * ```
349
- */
350
- export const params = /*#__PURE__*/ memoizedOptions(function params<
351
- const TShape extends ParamsShape = NonNullable<unknown>,
352
- >(properties: TShape = {} as TShape) {
353
- return new ParamsSchema<TShape>(properties)
354
- })
355
-
356
- type UnwrapSchema<S extends Validator> =
357
- S extends OptionalSchema<infer U>
358
- ? UnwrapSchema<U>
359
- : S extends WithDefaultSchema<infer U>
360
- ? UnwrapSchema<U>
361
- : S
362
-
363
- function unwrapSchema<S extends Validator>(schema: S): UnwrapSchema<S> {
364
- while (
365
- schema instanceof OptionalSchema ||
366
- schema instanceof WithDefaultSchema
367
- ) {
368
- return unwrapSchema(schema.validator)
369
- }
370
- return schema as UnwrapSchema<S>
371
- }
@@ -1,340 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
- import { integer } from './integer.js'
3
- import { lexMap } from './lex-map.js'
4
- import { object } from './object.js'
5
- import { payload } from './payload.js'
6
- import { string } from './string.js'
7
-
8
- describe('Payload', () => {
9
- describe('basic construction', () => {
10
- it('creates payload with encoding and no schema', () => {
11
- const def = payload('application/json', undefined)
12
- expect(def.encoding).toBe('application/json')
13
- expect(def.schema).toBeUndefined()
14
- })
15
-
16
- it('creates payload with encoding and schema', () => {
17
- const schema = object({
18
- name: string(),
19
- })
20
- const def = payload('application/json', schema)
21
- expect(def.encoding).toBe('application/json')
22
- expect(def.schema).toBe(schema)
23
- })
24
-
25
- it('creates payload with undefined encoding and undefined schema', () => {
26
- const def = payload(undefined, undefined)
27
- expect(def.encoding).toBeUndefined()
28
- expect(def.schema).toBeUndefined()
29
- })
30
-
31
- it('creates payload with text encoding', () => {
32
- const def = payload('text/plain', undefined)
33
- expect(def.encoding).toBe('text/plain')
34
- expect(def.schema).toBeUndefined()
35
- })
36
-
37
- it('creates payload with text/html encoding', () => {
38
- const def = payload('text/html', undefined)
39
- expect(def.encoding).toBe('text/html')
40
- expect(def.schema).toBeUndefined()
41
- })
42
-
43
- it('creates payload with application/octet-stream encoding', () => {
44
- const def = payload('application/octet-stream', undefined)
45
- expect(def.encoding).toBe('application/octet-stream')
46
- expect(def.schema).toBeUndefined()
47
- })
48
-
49
- it('creates payload with image encoding', () => {
50
- const def = payload('image/png', undefined)
51
- expect(def.encoding).toBe('image/png')
52
- expect(def.schema).toBeUndefined()
53
- })
54
- })
55
-
56
- describe('encoding types', () => {
57
- it('handles application/json encoding', () => {
58
- const def = payload('application/json', undefined)
59
- expect(def.encoding).toBe('application/json')
60
- })
61
-
62
- it('handles text/* encodings', () => {
63
- const textPlain = payload('text/plain', undefined)
64
- expect(textPlain.encoding).toBe('text/plain')
65
-
66
- const textHtml = payload('text/html', undefined)
67
- expect(textHtml.encoding).toBe('text/html')
68
-
69
- const textCss = payload('text/css', undefined)
70
- expect(textCss.encoding).toBe('text/css')
71
- })
72
-
73
- it('handles binary encodings', () => {
74
- const octetStream = payload('application/octet-stream', undefined)
75
- expect(octetStream.encoding).toBe('application/octet-stream')
76
-
77
- const imagePng = payload('image/png', undefined)
78
- expect(imagePng.encoding).toBe('image/png')
79
-
80
- const imageJpeg = payload('image/jpeg', undefined)
81
- expect(imageJpeg.encoding).toBe('image/jpeg')
82
- })
83
-
84
- it('handles custom mime types', () => {
85
- const def = payload('application/vnd.custom+json', undefined)
86
- expect(def.encoding).toBe('application/vnd.custom+json')
87
- })
88
- })
89
-
90
- describe('with schemas', () => {
91
- it('creates payload with object schema', () => {
92
- const schema = object({
93
- id: integer(),
94
- name: string(),
95
- })
96
- const def = payload('application/json', schema)
97
- expect(def.encoding).toBe('application/json')
98
- expect(def.schema).toBe(schema)
99
- })
100
-
101
- it('creates payload with string schema', () => {
102
- const schema = string()
103
- const def = payload('application/json', schema)
104
- expect(def.encoding).toBe('application/json')
105
- expect(def.schema).toBe(schema)
106
- })
107
-
108
- it('creates payload with integer schema', () => {
109
- const schema = integer()
110
- const def = payload('application/json', schema)
111
- expect(def.encoding).toBe('application/json')
112
- expect(def.schema).toBe(schema)
113
- })
114
-
115
- it('creates payload with unknown schema', () => {
116
- const schema = object({})
117
- const def = payload('application/json', schema)
118
- expect(def.encoding).toBe('application/json')
119
- expect(def.schema).toBe(schema)
120
- })
121
-
122
- it('creates payload with complex nested schema', () => {
123
- const schema = object({
124
- user: object({
125
- id: integer(),
126
- name: string(),
127
- email: string({ format: 'uri' }),
128
- }),
129
- metadata: object({
130
- createdAt: string({ format: 'datetime' }),
131
- updatedAt: string({ format: 'datetime' }),
132
- }),
133
- })
134
- const def = payload('application/json', schema)
135
- expect(def.encoding).toBe('application/json')
136
- expect(def.schema).toBe(schema)
137
- })
138
- })
139
-
140
- describe('validation constraints', () => {
141
- it('throws error when schema is defined but encoding is undefined', () => {
142
- const schema = string()
143
- expect(() => {
144
- // @ts-expect-error
145
- payload(undefined, schema)
146
- }).toThrow(TypeError)
147
- expect(() => {
148
- // @ts-expect-error
149
- payload(undefined, schema)
150
- }).toThrow('schema cannot be defined when encoding is undefined')
151
- })
152
-
153
- it('throws error when object schema is defined but encoding is undefined', () => {
154
- const schema = object({
155
- name: string(),
156
- })
157
- expect(() => {
158
- // @ts-expect-error
159
- payload(undefined, schema)
160
- }).toThrow(TypeError)
161
- expect(() => {
162
- // @ts-expect-error
163
- payload(undefined, schema)
164
- }).toThrow('schema cannot be defined when encoding is undefined')
165
- })
166
-
167
- it('throws error when integer schema is defined but encoding is undefined', () => {
168
- const schema = integer()
169
- expect(() => {
170
- // @ts-expect-error
171
- payload(undefined, schema)
172
- }).toThrow(TypeError)
173
- })
174
-
175
- it('allows undefined encoding with undefined schema', () => {
176
- expect(() => {
177
- payload(undefined, undefined)
178
- }).not.toThrow()
179
- })
180
-
181
- it('allows defined encoding with undefined schema', () => {
182
- expect(() => {
183
- payload('application/json', undefined)
184
- }).not.toThrow()
185
- })
186
-
187
- it('allows defined encoding with defined schema', () => {
188
- const schema = string()
189
- expect(() => {
190
- payload('application/json', schema)
191
- }).not.toThrow()
192
- })
193
- })
194
-
195
- describe('property access', () => {
196
- it('has accessible encoding property', () => {
197
- const def = payload('application/json', undefined)
198
- expect(def.encoding).toBe('application/json')
199
- })
200
-
201
- it('has accessible schema property', () => {
202
- const schema = string()
203
- const def = payload('application/json', schema)
204
- expect(def.schema).toBe(schema)
205
- })
206
-
207
- it('encoding property is immutable in TypeScript', () => {
208
- const def = payload('application/json', undefined)
209
- // TypeScript enforces readonly at compile time
210
- expect(def.encoding).toBe('application/json')
211
- })
212
-
213
- it('schema property is immutable in TypeScript', () => {
214
- const schema = string()
215
- const def = payload('application/json', schema)
216
- // TypeScript enforces readonly at compile time
217
- expect(def.schema).toBe(schema)
218
- })
219
- })
220
-
221
- describe('usage scenarios', () => {
222
- it('creates payload for JSON API response', () => {
223
- const def = payload(
224
- 'application/json',
225
- object({
226
- success: string(),
227
- data: lexMap(),
228
- }),
229
- )
230
- expect(def.encoding).toBe('application/json')
231
- expect(def.schema).toBeDefined()
232
- })
233
-
234
- it('creates payload for plain text response', () => {
235
- const def = payload('text/plain', undefined)
236
- expect(def.encoding).toBe('text/plain')
237
- expect(def.schema).toBeUndefined()
238
- })
239
-
240
- it('creates payload for binary data', () => {
241
- const def = payload('application/octet-stream', undefined)
242
- expect(def.encoding).toBe('application/octet-stream')
243
- expect(def.schema).toBeUndefined()
244
- })
245
-
246
- it('creates payload for image upload', () => {
247
- const def = payload('image/jpeg', undefined)
248
- expect(def.encoding).toBe('image/jpeg')
249
- expect(def.schema).toBeUndefined()
250
- })
251
-
252
- it('creates payload for multipart form data', () => {
253
- const def = payload('multipart/form-data', undefined)
254
- expect(def.encoding).toBe('multipart/form-data')
255
- expect(def.schema).toBeUndefined()
256
- })
257
-
258
- it('creates payload for URL encoded form', () => {
259
- const def = payload('application/x-www-form-urlencoded', undefined)
260
- expect(def.encoding).toBe('application/x-www-form-urlencoded')
261
- expect(def.schema).toBeUndefined()
262
- })
263
-
264
- it('creates empty payload (no encoding, no schema)', () => {
265
- const def = payload(undefined, undefined)
266
- expect(def.encoding).toBeUndefined()
267
- expect(def.schema).toBeUndefined()
268
- })
269
- })
270
-
271
- describe('edge cases', () => {
272
- it('handles encoding with charset parameter', () => {
273
- const def = payload('application/json; charset=utf-8', undefined)
274
- expect(def.encoding).toBe('application/json; charset=utf-8')
275
- })
276
-
277
- it('handles encoding with multiple parameters', () => {
278
- const def = payload('multipart/form-data; boundary=something', undefined)
279
- expect(def.encoding).toBe('multipart/form-data; boundary=something')
280
- })
281
-
282
- it('handles empty string encoding', () => {
283
- const def = payload('', undefined)
284
- expect(def.encoding).toBe('')
285
- })
286
-
287
- it('creates multiple payloads with same schema reference', () => {
288
- const sharedSchema = object({
289
- id: integer(),
290
- })
291
- const def1 = payload('application/json', sharedSchema)
292
- const def2 = payload('application/json', sharedSchema)
293
-
294
- expect(def1.schema).toBe(def2.schema)
295
- expect(def1.schema).toBe(sharedSchema)
296
- })
297
-
298
- it('creates multiple payloads with different schemas', () => {
299
- const schema1 = string()
300
- const schema2 = integer()
301
- const def1 = payload('application/json', schema1)
302
- const def2 = payload('application/json', schema2)
303
-
304
- expect(def1.schema).not.toBe(def2.schema)
305
- expect(def1.schema).toBe(schema1)
306
- expect(def2.schema).toBe(schema2)
307
- })
308
- })
309
-
310
- describe('type inference scenarios', () => {
311
- it('works with application/json and object schema', () => {
312
- const schema = object({
313
- message: string(),
314
- })
315
- const def = payload('application/json', schema)
316
- expect(def.encoding).toBe('application/json')
317
- expect(def.schema).toBe(schema)
318
- })
319
-
320
- it('works with text/* encodings expecting string bodies', () => {
321
- const def1 = payload('text/plain', undefined)
322
- const def2 = payload('text/html', undefined)
323
- const def3 = payload('text/csv', undefined)
324
-
325
- expect(def1.encoding).toBe('text/plain')
326
- expect(def2.encoding).toBe('text/html')
327
- expect(def3.encoding).toBe('text/csv')
328
- })
329
-
330
- it('works with binary encodings expecting Uint8Array bodies', () => {
331
- const def1 = payload('image/png', undefined)
332
- const def2 = payload('application/octet-stream', undefined)
333
- const def3 = payload('video/mp4', undefined)
334
-
335
- expect(def1.encoding).toBe('image/png')
336
- expect(def2.encoding).toBe('application/octet-stream')
337
- expect(def3.encoding).toBe('video/mp4')
338
- })
339
- })
340
- })