@orpc/zod 0.16.0 → 0.18.0

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -1,4 +1,346 @@
1
- // src/index.ts
1
+ // ../../node_modules/.pnpm/is-what@5.0.2/node_modules/is-what/dist/getType.js
2
+ function getType(payload) {
3
+ return Object.prototype.toString.call(payload).slice(8, -1);
4
+ }
5
+
6
+ // ../../node_modules/.pnpm/is-what@5.0.2/node_modules/is-what/dist/isPlainObject.js
7
+ function isPlainObject(payload) {
8
+ if (getType(payload) !== "Object")
9
+ return false;
10
+ const prototype = Object.getPrototypeOf(payload);
11
+ return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
12
+ }
13
+
14
+ // ../../node_modules/.pnpm/radash@12.1.0/node_modules/radash/dist/esm/async.mjs
15
+ var guard = (func, shouldGuard) => {
16
+ const _guard = (err) => {
17
+ if (shouldGuard && !shouldGuard(err))
18
+ throw err;
19
+ return void 0;
20
+ };
21
+ const isPromise2 = (result) => result instanceof Promise;
22
+ try {
23
+ const result = func();
24
+ return isPromise2(result) ? result.catch(_guard) : result;
25
+ } catch (err) {
26
+ return _guard(err);
27
+ }
28
+ };
29
+
30
+ // src/coercer.ts
31
+ import {
32
+ ZodFirstPartyTypeKind
33
+ } from "zod";
34
+ var ZodCoercer = class {
35
+ coerce(schema, value) {
36
+ if (!schema || schema["~standard"].vendor !== "zod") {
37
+ return value;
38
+ }
39
+ const zodSchema = schema;
40
+ const coerced = zodCoerceInternal(zodSchema, value, { bracketNotation: true });
41
+ return coerced;
42
+ }
43
+ };
44
+ function zodCoerceInternal(schema, value, options) {
45
+ const isRoot = options?.isRoot ?? true;
46
+ const options_ = { ...options, isRoot: false };
47
+ if (isRoot && options?.bracketNotation && Array.isArray(value) && value.length === 1) {
48
+ const newValue = zodCoerceInternal(schema, value[0], options_);
49
+ if (schema.safeParse(newValue).success) {
50
+ return newValue;
51
+ }
52
+ return zodCoerceInternal(schema, value, options_);
53
+ }
54
+ const customType = getCustomZodType(schema._def);
55
+ if (customType === "Invalid Date") {
56
+ if (typeof value === "string" && value.toLocaleLowerCase() === "invalid date") {
57
+ return /* @__PURE__ */ new Date("Invalid Date");
58
+ }
59
+ } else if (customType === "RegExp") {
60
+ if (typeof value === "string" && value.startsWith("/")) {
61
+ const match = value.match(/^\/(.*)\/([a-z]*)$/);
62
+ if (match) {
63
+ const [, pattern, flags] = match;
64
+ return new RegExp(pattern, flags);
65
+ }
66
+ }
67
+ } else if (customType === "URL") {
68
+ if (typeof value === "string") {
69
+ const url2 = guard(() => new URL(value));
70
+ if (url2 !== void 0) {
71
+ return url2;
72
+ }
73
+ }
74
+ }
75
+ if (schema._def.typeName === void 0) {
76
+ return value;
77
+ }
78
+ const typeName = schema._def.typeName;
79
+ if (typeName === ZodFirstPartyTypeKind.ZodNumber) {
80
+ if (options_?.bracketNotation && typeof value === "string") {
81
+ const num = Number(value);
82
+ if (!Number.isNaN(num)) {
83
+ return num;
84
+ }
85
+ }
86
+ } else if (typeName === ZodFirstPartyTypeKind.ZodNaN) {
87
+ if (typeof value === "string" && value.toLocaleLowerCase() === "nan") {
88
+ return Number.NaN;
89
+ }
90
+ } else if (typeName === ZodFirstPartyTypeKind.ZodBoolean) {
91
+ if (options_?.bracketNotation && typeof value === "string") {
92
+ const lower = value.toLowerCase();
93
+ if (lower === "false" || lower === "off" || lower === "f") {
94
+ return false;
95
+ }
96
+ if (lower === "true" || lower === "on" || lower === "t") {
97
+ return true;
98
+ }
99
+ }
100
+ } else if (typeName === ZodFirstPartyTypeKind.ZodNull) {
101
+ if (options_?.bracketNotation && typeof value === "string" && value.toLowerCase() === "null") {
102
+ return null;
103
+ }
104
+ } else if (typeName === ZodFirstPartyTypeKind.ZodUndefined || typeName === ZodFirstPartyTypeKind.ZodVoid) {
105
+ if (typeof value === "string" && value.toLowerCase() === "undefined") {
106
+ return void 0;
107
+ }
108
+ } else if (typeName === ZodFirstPartyTypeKind.ZodDate) {
109
+ if (typeof value === "string" && (value.includes("-") || value.includes(":") || value.toLocaleLowerCase() === "invalid date")) {
110
+ return new Date(value);
111
+ }
112
+ } else if (typeName === ZodFirstPartyTypeKind.ZodBigInt) {
113
+ if (typeof value === "string") {
114
+ const num = guard(() => BigInt(value));
115
+ if (num !== void 0) {
116
+ return num;
117
+ }
118
+ }
119
+ } else if (typeName === ZodFirstPartyTypeKind.ZodArray || typeName === ZodFirstPartyTypeKind.ZodTuple) {
120
+ const schema_ = schema;
121
+ if (Array.isArray(value)) {
122
+ return value.map((v) => zodCoerceInternal(schema_._def.type, v, options_));
123
+ }
124
+ if (options_?.bracketNotation) {
125
+ if (value === void 0) {
126
+ return [];
127
+ }
128
+ if (isPlainObject(value) && Object.keys(value).every((k) => /^[1-9]\d*$/.test(k) || k === "0")) {
129
+ const indexes = Object.keys(value).map((k) => Number(k)).sort((a, b) => a - b);
130
+ const arr = Array.from({ length: (indexes.at(-1) ?? -1) + 1 });
131
+ for (const i of indexes) {
132
+ arr[i] = zodCoerceInternal(schema_._def.type, value[i], options_);
133
+ }
134
+ return arr;
135
+ }
136
+ }
137
+ } else if (typeName === ZodFirstPartyTypeKind.ZodObject) {
138
+ const schema_ = schema;
139
+ if (isPlainObject(value)) {
140
+ const newObj = {};
141
+ const keys = /* @__PURE__ */ new Set([
142
+ ...Object.keys(value),
143
+ ...Object.keys(schema_.shape)
144
+ ]);
145
+ for (const k of keys) {
146
+ if (!(k in value))
147
+ continue;
148
+ const v = value[k];
149
+ newObj[k] = zodCoerceInternal(
150
+ schema_.shape[k] ?? schema_._def.catchall,
151
+ v,
152
+ options_
153
+ );
154
+ }
155
+ return newObj;
156
+ }
157
+ if (options_?.bracketNotation) {
158
+ if (value === void 0) {
159
+ return {};
160
+ }
161
+ if (Array.isArray(value) && value.length === 1) {
162
+ const emptySchema = schema_.shape[""] ?? schema_._def.catchall;
163
+ return { "": zodCoerceInternal(emptySchema, value[0], options_) };
164
+ }
165
+ }
166
+ } else if (typeName === ZodFirstPartyTypeKind.ZodSet) {
167
+ const schema_ = schema;
168
+ if (Array.isArray(value)) {
169
+ return new Set(
170
+ value.map((v) => zodCoerceInternal(schema_._def.valueType, v, options_))
171
+ );
172
+ }
173
+ if (options_?.bracketNotation) {
174
+ if (value === void 0) {
175
+ return /* @__PURE__ */ new Set();
176
+ }
177
+ if (isPlainObject(value) && Object.keys(value).every((k) => /^[1-9]\d*$/.test(k) || k === "0")) {
178
+ const indexes = Object.keys(value).map((k) => Number(k)).sort((a, b) => a - b);
179
+ const arr = Array.from({ length: (indexes.at(-1) ?? -1) + 1 });
180
+ for (const i of indexes) {
181
+ arr[i] = zodCoerceInternal(schema_._def.valueType, value[i], options_);
182
+ }
183
+ return new Set(arr);
184
+ }
185
+ }
186
+ } else if (typeName === ZodFirstPartyTypeKind.ZodMap) {
187
+ const schema_ = schema;
188
+ if (Array.isArray(value) && value.every((i) => Array.isArray(i) && i.length === 2)) {
189
+ return new Map(
190
+ value.map(([k, v]) => [
191
+ zodCoerceInternal(schema_._def.keyType, k, options_),
192
+ zodCoerceInternal(schema_._def.valueType, v, options_)
193
+ ])
194
+ );
195
+ }
196
+ if (options_?.bracketNotation) {
197
+ if (value === void 0) {
198
+ return /* @__PURE__ */ new Map();
199
+ }
200
+ if (isPlainObject(value)) {
201
+ const arr = Array.from({ length: Object.keys(value).length }).fill(void 0).map(
202
+ (_, i) => isPlainObject(value[i]) && Object.keys(value[i]).length === 2 && "0" in value[i] && "1" in value[i] ? [value[i]["0"], value[i]["1"]] : void 0
203
+ );
204
+ if (arr.every((v) => !!v)) {
205
+ return new Map(
206
+ arr.map(([k, v]) => [
207
+ zodCoerceInternal(schema_._def.keyType, k, options_),
208
+ zodCoerceInternal(schema_._def.valueType, v, options_)
209
+ ])
210
+ );
211
+ }
212
+ }
213
+ }
214
+ } else if (typeName === ZodFirstPartyTypeKind.ZodRecord) {
215
+ const schema_ = schema;
216
+ if (isPlainObject(value)) {
217
+ const newObj = {};
218
+ for (const [k, v] of Object.entries(value)) {
219
+ const key = zodCoerceInternal(schema_._def.keyType, k, options_);
220
+ const val = zodCoerceInternal(schema_._def.valueType, v, options_);
221
+ newObj[key] = val;
222
+ }
223
+ return newObj;
224
+ }
225
+ } else if (typeName === ZodFirstPartyTypeKind.ZodUnion || typeName === ZodFirstPartyTypeKind.ZodDiscriminatedUnion) {
226
+ const schema_ = schema;
227
+ if (schema_.safeParse(value).success) {
228
+ return value;
229
+ }
230
+ const results = [];
231
+ for (const s of schema_._def.options) {
232
+ const newValue = zodCoerceInternal(s, value, { ...options_, isRoot });
233
+ if (newValue === value)
234
+ continue;
235
+ const result = schema_.safeParse(newValue);
236
+ if (result.success) {
237
+ return newValue;
238
+ }
239
+ results.push([newValue, result.error.issues.length]);
240
+ }
241
+ if (results.length === 0) {
242
+ return value;
243
+ }
244
+ return results.sort((a, b) => a[1] - b[1])[0]?.[0];
245
+ } else if (typeName === ZodFirstPartyTypeKind.ZodIntersection) {
246
+ const schema_ = schema;
247
+ return zodCoerceInternal(
248
+ schema_._def.right,
249
+ zodCoerceInternal(schema_._def.left, value, { ...options_, isRoot }),
250
+ { ...options_, isRoot }
251
+ );
252
+ } else if (typeName === ZodFirstPartyTypeKind.ZodReadonly) {
253
+ const schema_ = schema;
254
+ return zodCoerceInternal(schema_._def.innerType, value, { ...options_, isRoot });
255
+ } else if (typeName === ZodFirstPartyTypeKind.ZodPipeline) {
256
+ const schema_ = schema;
257
+ return zodCoerceInternal(schema_._def.in, value, { ...options_, isRoot });
258
+ } else if (typeName === ZodFirstPartyTypeKind.ZodLazy) {
259
+ const schema_ = schema;
260
+ return zodCoerceInternal(schema_._def.getter(), value, { ...options_, isRoot });
261
+ } else if (typeName === ZodFirstPartyTypeKind.ZodEffects) {
262
+ const schema_ = schema;
263
+ return zodCoerceInternal(schema_._def.schema, value, { ...options_, isRoot });
264
+ } else if (typeName === ZodFirstPartyTypeKind.ZodBranded) {
265
+ const schema_ = schema;
266
+ return zodCoerceInternal(schema_._def.type, value, { ...options_, isRoot });
267
+ } else if (typeName === ZodFirstPartyTypeKind.ZodCatch) {
268
+ const schema_ = schema;
269
+ return zodCoerceInternal(schema_._def.innerType, value, { ...options_, isRoot });
270
+ } else if (typeName === ZodFirstPartyTypeKind.ZodDefault) {
271
+ const schema_ = schema;
272
+ return zodCoerceInternal(schema_._def.innerType, value, { ...options_, isRoot });
273
+ } else if (typeName === ZodFirstPartyTypeKind.ZodNullable) {
274
+ const schema_ = schema;
275
+ if (value === null) {
276
+ return null;
277
+ }
278
+ if (typeof value === "string" && value.toLowerCase() === "null") {
279
+ return schema_.safeParse(value).success ? value : null;
280
+ }
281
+ return zodCoerceInternal(schema_._def.innerType, value, { ...options_, isRoot });
282
+ } else if (typeName === ZodFirstPartyTypeKind.ZodOptional) {
283
+ const schema_ = schema;
284
+ if (value === void 0) {
285
+ return void 0;
286
+ }
287
+ if (typeof value === "string" && value.toLowerCase() === "undefined") {
288
+ return schema_.safeParse(value).success ? value : void 0;
289
+ }
290
+ return zodCoerceInternal(schema_._def.innerType, value, { ...options_, isRoot });
291
+ } else if (typeName === ZodFirstPartyTypeKind.ZodNativeEnum) {
292
+ const schema_ = schema;
293
+ if (Object.values(schema_._def.values).includes(value)) {
294
+ return value;
295
+ }
296
+ if (options?.bracketNotation && typeof value === "string") {
297
+ for (const expectedValue of Object.values(schema_._def.values)) {
298
+ if (expectedValue.toString() === value) {
299
+ return expectedValue;
300
+ }
301
+ }
302
+ }
303
+ } else if (typeName === ZodFirstPartyTypeKind.ZodLiteral) {
304
+ const schema_ = schema;
305
+ const expectedValue = schema_._def.value;
306
+ if (typeof value === "string" && typeof expectedValue !== "string") {
307
+ if (typeof expectedValue === "bigint") {
308
+ const num = guard(() => BigInt(value));
309
+ if (num !== void 0) {
310
+ return num;
311
+ }
312
+ } else if (expectedValue === void 0) {
313
+ if (value.toLocaleLowerCase() === "undefined") {
314
+ return void 0;
315
+ }
316
+ } else if (options?.bracketNotation) {
317
+ if (typeof expectedValue === "number") {
318
+ const num = Number(value);
319
+ if (!Number.isNaN(num)) {
320
+ return num;
321
+ }
322
+ } else if (typeof expectedValue === "boolean") {
323
+ const lower = value.toLowerCase();
324
+ if (lower === "false" || lower === "off" || lower === "f") {
325
+ return false;
326
+ }
327
+ if (lower === "true" || lower === "on" || lower === "t") {
328
+ return true;
329
+ }
330
+ } else if (expectedValue === null) {
331
+ if (value.toLocaleLowerCase() === "null") {
332
+ return null;
333
+ }
334
+ }
335
+ }
336
+ }
337
+ } else {
338
+ const _expected = typeName;
339
+ }
340
+ return value;
341
+ }
342
+
343
+ // src/schemas.ts
2
344
  import wcmatch from "wildcard-match";
3
345
  import {
4
346
  custom
@@ -134,6 +476,7 @@ var oz = {
134
476
  url
135
477
  };
136
478
  export {
479
+ ZodCoercer,
137
480
  blob,
138
481
  file,
139
482
  getCustomJSONSchema,
@@ -0,0 +1,6 @@
1
+ import type { Schema } from '@orpc/contract';
2
+ import type { SchemaCoercer } from '@orpc/openapi/fetch';
3
+ export declare class ZodCoercer implements SchemaCoercer {
4
+ coerce(schema: Schema, value: unknown): unknown;
5
+ }
6
+ //# sourceMappingURL=coercer.d.ts.map
@@ -1,31 +1,3 @@
1
- import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
2
- import { type CustomErrorParams, type input, type output, type ZodEffects, type ZodType, type ZodTypeAny, type ZodTypeDef } from 'zod';
3
- export type CustomZodType = 'File' | 'Blob' | 'Invalid Date' | 'RegExp' | 'URL';
4
- type CustomParams = CustomErrorParams & {
5
- fatal?: boolean;
6
- };
7
- export declare function getCustomZodType(def: ZodTypeDef): CustomZodType | undefined;
8
- export declare function getCustomZodFileMimeType(def: ZodTypeDef): string | undefined;
9
- export declare function getCustomJSONSchema(def: ZodTypeDef, options?: {
10
- mode?: 'input' | 'output';
11
- }): Exclude<JSONSchema, boolean> | undefined;
12
- export declare function file(params?: string | CustomParams | ((input: unknown) => CustomParams)): ZodType<InstanceType<typeof File>, ZodTypeDef, InstanceType<typeof File>> & {
13
- type: (mimeType: string, params?: string | CustomParams | ((input: unknown) => CustomParams)) => ZodEffects<ZodType<InstanceType<typeof File>, ZodTypeDef, InstanceType<typeof File>>, InstanceType<typeof File>, InstanceType<typeof File>>;
14
- };
15
- export declare function blob(params?: string | CustomParams | ((input: unknown) => CustomParams)): ZodType<InstanceType<typeof Blob>, ZodTypeDef, InstanceType<typeof Blob>>;
16
- export declare function invalidDate(params?: string | CustomParams | ((input: unknown) => CustomParams)): ZodType<Date, ZodTypeDef, Date>;
17
- export declare function regexp(options?: CustomParams): ZodType<RegExp, ZodTypeDef, RegExp>;
18
- export declare function url(options?: CustomParams): ZodType<URL, ZodTypeDef, URL>;
19
- export declare function openapi<T extends ZodTypeAny, TMode extends 'input' | 'output' | 'both' = 'both'>(schema: T, custom: Exclude<JSONSchema<TMode extends 'input' ? input<T> : TMode extends 'output' ? output<T> : input<T> & output<T>>, boolean>, options?: {
20
- mode: TMode;
21
- }): ReturnType<T['refine']>;
22
- export declare const oz: {
23
- openapi: typeof openapi;
24
- file: typeof file;
25
- blob: typeof blob;
26
- invalidDate: typeof invalidDate;
27
- regexp: typeof regexp;
28
- url: typeof url;
29
- };
30
- export {};
1
+ export * from './coercer';
2
+ export * from './schemas';
31
3
  //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,31 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
2
+ import { type CustomErrorParams, type input, type output, type ZodEffects, type ZodType, type ZodTypeAny, type ZodTypeDef } from 'zod';
3
+ export type CustomZodType = 'File' | 'Blob' | 'Invalid Date' | 'RegExp' | 'URL';
4
+ type CustomParams = CustomErrorParams & {
5
+ fatal?: boolean;
6
+ };
7
+ export declare function getCustomZodType(def: ZodTypeDef): CustomZodType | undefined;
8
+ export declare function getCustomZodFileMimeType(def: ZodTypeDef): string | undefined;
9
+ export declare function getCustomJSONSchema(def: ZodTypeDef, options?: {
10
+ mode?: 'input' | 'output';
11
+ }): Exclude<JSONSchema, boolean> | undefined;
12
+ export declare function file(params?: string | CustomParams | ((input: unknown) => CustomParams)): ZodType<InstanceType<typeof File>, ZodTypeDef, InstanceType<typeof File>> & {
13
+ type: (mimeType: string, params?: string | CustomParams | ((input: unknown) => CustomParams)) => ZodEffects<ZodType<InstanceType<typeof File>, ZodTypeDef, InstanceType<typeof File>>, InstanceType<typeof File>, InstanceType<typeof File>>;
14
+ };
15
+ export declare function blob(params?: string | CustomParams | ((input: unknown) => CustomParams)): ZodType<InstanceType<typeof Blob>, ZodTypeDef, InstanceType<typeof Blob>>;
16
+ export declare function invalidDate(params?: string | CustomParams | ((input: unknown) => CustomParams)): ZodType<Date, ZodTypeDef, Date>;
17
+ export declare function regexp(options?: CustomParams): ZodType<RegExp, ZodTypeDef, RegExp>;
18
+ export declare function url(options?: CustomParams): ZodType<URL, ZodTypeDef, URL>;
19
+ export declare function openapi<T extends ZodTypeAny, TMode extends 'input' | 'output' | 'both' = 'both'>(schema: T, custom: Exclude<JSONSchema<TMode extends 'input' ? input<T> : TMode extends 'output' ? output<T> : input<T> & output<T>>, boolean>, options?: {
20
+ mode: TMode;
21
+ }): ReturnType<T['refine']>;
22
+ export declare const oz: {
23
+ openapi: typeof openapi;
24
+ file: typeof file;
25
+ blob: typeof blob;
26
+ invalidDate: typeof invalidDate;
27
+ regexp: typeof regexp;
28
+ url: typeof url;
29
+ };
30
+ export {};
31
+ //# sourceMappingURL=schemas.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/zod",
3
3
  "type": "module",
4
- "version": "0.16.0",
4
+ "version": "0.18.0",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -28,6 +28,9 @@
28
28
  "!**/*.tsbuildinfo",
29
29
  "dist"
30
30
  ],
31
+ "peerDependencies": {
32
+ "@orpc/openapi": "0.18.0"
33
+ },
31
34
  "dependencies": {
32
35
  "json-schema-typed": "^8.0.1",
33
36
  "wildcard-match": "^5.1.3",