@zenstackhq/zod 3.5.6 → 3.6.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/dist/index.cjs CHANGED
@@ -1,858 +1,719 @@
1
- "use strict";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
7
  var __getProtoOf = Object.getPrototypeOf;
7
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
9
+ var __exportAll = (all, no_symbols) => {
10
+ let target = {};
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ return target;
12
17
  };
13
18
  var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
19
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
+ key = keys[i];
21
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
22
+ get: ((k) => from[k]).bind(null, key),
23
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
+ });
25
+ }
26
+ return to;
20
27
  };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
-
31
- // src/index.ts
32
- var src_exports = {};
33
- __export(src_exports, {
34
- ZodUtils: () => utils_exports,
35
- createSchemaFactory: () => createSchemaFactory
36
- });
37
- module.exports = __toCommonJS(src_exports);
38
-
39
- // src/factory.ts
40
- var import_schema2 = require("@zenstackhq/schema");
41
- var import_decimal2 = __toESM(require("decimal.js"), 1);
42
- var import_zod2 = __toESM(require("zod"), 1);
43
-
44
- // src/error.ts
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
29
+ value: mod,
30
+ enumerable: true
31
+ }) : target, mod));
32
+ //#endregion
33
+ let _zenstackhq_schema = require("@zenstackhq/schema");
34
+ let decimal_js = require("decimal.js");
35
+ decimal_js = __toESM(decimal_js, 1);
36
+ let zod = require("zod");
37
+ zod = __toESM(zod, 1);
38
+ //#region src/error.ts
39
+ /**
40
+ * Error representing failures in Zod schema building.
41
+ */
45
42
  var SchemaFactoryError = class extends Error {
46
- static {
47
- __name(this, "SchemaFactoryError");
48
- }
49
- constructor(message) {
50
- super(message);
51
- }
43
+ constructor(message) {
44
+ super(message);
45
+ }
52
46
  };
53
-
54
- // src/utils.ts
55
- var utils_exports = {};
56
- __export(utils_exports, {
57
- addBigIntValidation: () => addBigIntValidation,
58
- addCustomValidation: () => addCustomValidation,
59
- addDecimalValidation: () => addDecimalValidation,
60
- addListValidation: () => addListValidation,
61
- addNumberValidation: () => addNumberValidation,
62
- addStringValidation: () => addStringValidation,
63
- collectFieldRefs: () => collectFieldRefs
47
+ //#endregion
48
+ //#region src/utils.ts
49
+ var utils_exports = /* @__PURE__ */ __exportAll({
50
+ addBigIntValidation: () => addBigIntValidation,
51
+ addCustomValidation: () => addCustomValidation,
52
+ addDecimalValidation: () => addDecimalValidation,
53
+ addListValidation: () => addListValidation,
54
+ addNumberValidation: () => addNumberValidation,
55
+ addStringValidation: () => addStringValidation,
56
+ collectFieldRefs: () => collectFieldRefs
64
57
  });
65
- var import_schema = require("@zenstackhq/schema");
66
- var import_decimal = __toESM(require("decimal.js"), 1);
67
- var import_zod = require("zod");
68
58
  function getArgValue(expr) {
69
- if (!expr || !import_schema.ExpressionUtils.isLiteral(expr)) {
70
- return void 0;
71
- }
72
- return expr.value;
59
+ if (!expr || !_zenstackhq_schema.ExpressionUtils.isLiteral(expr)) return;
60
+ return expr.value;
73
61
  }
74
- __name(getArgValue, "getArgValue");
75
62
  function addStringValidation(schema, attributes) {
76
- if (!attributes || attributes.length === 0) {
77
- return schema;
78
- }
79
- let result = schema;
80
- for (const attr of attributes) {
81
- switch (attr.name) {
82
- case "@length": {
83
- const min = getArgValue(attr.args?.find((a) => a.name === "min")?.value);
84
- if (min !== void 0) {
85
- result = result.min(min);
86
- }
87
- const max = getArgValue(attr.args?.find((a) => a.name === "max")?.value);
88
- if (max !== void 0) {
89
- result = result.max(max);
90
- }
91
- break;
92
- }
93
- case "@startsWith": {
94
- const value = getArgValue(attr.args?.[0]?.value);
95
- if (value !== void 0) {
96
- result = result.startsWith(value);
97
- }
98
- break;
99
- }
100
- case "@endsWith": {
101
- const value = getArgValue(attr.args?.[0]?.value);
102
- if (value !== void 0) {
103
- result = result.endsWith(value);
104
- }
105
- break;
106
- }
107
- case "@contains": {
108
- const value = getArgValue(attr.args?.[0]?.value);
109
- if (value !== void 0) {
110
- result = result.includes(value);
111
- }
112
- break;
113
- }
114
- case "@regex": {
115
- const pattern = getArgValue(attr.args?.[0]?.value);
116
- if (pattern !== void 0) {
117
- result = result.regex(new RegExp(pattern));
118
- }
119
- break;
120
- }
121
- case "@email":
122
- result = result.email();
123
- break;
124
- case "@datetime":
125
- result = result.datetime();
126
- break;
127
- case "@url":
128
- result = result.url();
129
- break;
130
- case "@trim":
131
- result = result.trim();
132
- break;
133
- case "@lower":
134
- result = result.toLowerCase();
135
- break;
136
- case "@upper":
137
- result = result.toUpperCase();
138
- break;
139
- }
140
- }
141
- return result;
63
+ if (!attributes || attributes.length === 0) return schema;
64
+ let result = schema;
65
+ for (const attr of attributes) switch (attr.name) {
66
+ case "@length": {
67
+ const min = getArgValue(attr.args?.find((a) => a.name === "min")?.value);
68
+ if (min !== void 0) result = result.min(min);
69
+ const max = getArgValue(attr.args?.find((a) => a.name === "max")?.value);
70
+ if (max !== void 0) result = result.max(max);
71
+ break;
72
+ }
73
+ case "@startsWith": {
74
+ const value = getArgValue(attr.args?.[0]?.value);
75
+ if (value !== void 0) result = result.startsWith(value);
76
+ break;
77
+ }
78
+ case "@endsWith": {
79
+ const value = getArgValue(attr.args?.[0]?.value);
80
+ if (value !== void 0) result = result.endsWith(value);
81
+ break;
82
+ }
83
+ case "@contains": {
84
+ const value = getArgValue(attr.args?.[0]?.value);
85
+ if (value !== void 0) result = result.includes(value);
86
+ break;
87
+ }
88
+ case "@regex": {
89
+ const pattern = getArgValue(attr.args?.[0]?.value);
90
+ if (pattern !== void 0) result = result.regex(new RegExp(pattern));
91
+ break;
92
+ }
93
+ case "@email":
94
+ result = result.email();
95
+ break;
96
+ case "@datetime":
97
+ result = result.datetime();
98
+ break;
99
+ case "@url":
100
+ result = result.url();
101
+ break;
102
+ case "@trim":
103
+ result = result.trim();
104
+ break;
105
+ case "@lower":
106
+ result = result.toLowerCase();
107
+ break;
108
+ case "@upper":
109
+ result = result.toUpperCase();
110
+ break;
111
+ }
112
+ return result;
142
113
  }
143
- __name(addStringValidation, "addStringValidation");
144
114
  function addNumberValidation(schema, attributes) {
145
- if (!attributes || attributes.length === 0) {
146
- return schema;
147
- }
148
- let result = schema;
149
- for (const attr of attributes) {
150
- const val = getArgValue(attr.args?.[0]?.value);
151
- if (val === void 0) {
152
- continue;
153
- }
154
- switch (attr.name) {
155
- case "@gt":
156
- result = result.gt(val);
157
- break;
158
- case "@gte":
159
- result = result.gte(val);
160
- break;
161
- case "@lt":
162
- result = result.lt(val);
163
- break;
164
- case "@lte":
165
- result = result.lte(val);
166
- break;
167
- }
168
- }
169
- return result;
115
+ if (!attributes || attributes.length === 0) return schema;
116
+ let result = schema;
117
+ for (const attr of attributes) {
118
+ const val = getArgValue(attr.args?.[0]?.value);
119
+ if (val === void 0) continue;
120
+ switch (attr.name) {
121
+ case "@gt":
122
+ result = result.gt(val);
123
+ break;
124
+ case "@gte":
125
+ result = result.gte(val);
126
+ break;
127
+ case "@lt":
128
+ result = result.lt(val);
129
+ break;
130
+ case "@lte":
131
+ result = result.lte(val);
132
+ break;
133
+ }
134
+ }
135
+ return result;
170
136
  }
171
- __name(addNumberValidation, "addNumberValidation");
172
137
  function addBigIntValidation(schema, attributes) {
173
- if (!attributes || attributes.length === 0) {
174
- return schema;
175
- }
176
- let result = schema;
177
- for (const attr of attributes) {
178
- const val = getArgValue(attr.args?.[0]?.value);
179
- if (val === void 0) {
180
- continue;
181
- }
182
- switch (attr.name) {
183
- case "@gt":
184
- result = result.gt(BigInt(val));
185
- break;
186
- case "@gte":
187
- result = result.gte(BigInt(val));
188
- break;
189
- case "@lt":
190
- result = result.lt(BigInt(val));
191
- break;
192
- case "@lte":
193
- result = result.lte(BigInt(val));
194
- break;
195
- }
196
- }
197
- return result;
138
+ if (!attributes || attributes.length === 0) return schema;
139
+ let result = schema;
140
+ for (const attr of attributes) {
141
+ const val = getArgValue(attr.args?.[0]?.value);
142
+ if (val === void 0) continue;
143
+ switch (attr.name) {
144
+ case "@gt":
145
+ result = result.gt(BigInt(val));
146
+ break;
147
+ case "@gte":
148
+ result = result.gte(BigInt(val));
149
+ break;
150
+ case "@lt":
151
+ result = result.lt(BigInt(val));
152
+ break;
153
+ case "@lte":
154
+ result = result.lte(BigInt(val));
155
+ break;
156
+ }
157
+ }
158
+ return result;
198
159
  }
199
- __name(addBigIntValidation, "addBigIntValidation");
200
160
  function addDecimalValidation(schema, attributes, addExtraValidation) {
201
- let result = schema;
202
- if (schema instanceof import_zod.z.ZodString) {
203
- result = schema.superRefine((v, ctx) => {
204
- try {
205
- new import_decimal.default(v);
206
- } catch (err) {
207
- ctx.addIssue({
208
- code: "custom",
209
- message: `Invalid decimal: ${err}`
210
- });
211
- }
212
- }).transform((val) => new import_decimal.default(val));
213
- }
214
- function refine(schema2, op, value) {
215
- return schema2.superRefine((v, ctx) => {
216
- const base = import_zod.z.number();
217
- const { error } = base[op](value).safeParse(v.toNumber());
218
- error?.issues.forEach((issue) => {
219
- if (op === "gt" || op === "gte") {
220
- ctx.addIssue({
221
- code: "too_small",
222
- origin: "number",
223
- minimum: value,
224
- type: "decimal",
225
- inclusive: op === "gte",
226
- message: issue.message
227
- });
228
- } else {
229
- ctx.addIssue({
230
- code: "too_big",
231
- origin: "number",
232
- maximum: value,
233
- type: "decimal",
234
- inclusive: op === "lte",
235
- message: issue.message
236
- });
237
- }
238
- });
239
- });
240
- }
241
- __name(refine, "refine");
242
- if (attributes && addExtraValidation) {
243
- for (const attr of attributes) {
244
- const val = getArgValue(attr.args?.[0]?.value);
245
- if (val === void 0) {
246
- continue;
247
- }
248
- switch (attr.name) {
249
- case "@gt":
250
- result = refine(result, "gt", val);
251
- break;
252
- case "@gte":
253
- result = refine(result, "gte", val);
254
- break;
255
- case "@lt":
256
- result = refine(result, "lt", val);
257
- break;
258
- case "@lte":
259
- result = refine(result, "lte", val);
260
- break;
261
- }
262
- }
263
- }
264
- return result;
161
+ let result = schema;
162
+ if (schema instanceof zod.z.ZodString) result = schema.superRefine((v, ctx) => {
163
+ try {
164
+ new decimal_js.default(v);
165
+ } catch (err) {
166
+ ctx.addIssue({
167
+ code: "custom",
168
+ message: `Invalid decimal: ${err}`
169
+ });
170
+ }
171
+ }).transform((val) => new decimal_js.default(val));
172
+ function refine(schema, op, value) {
173
+ return schema.superRefine((v, ctx) => {
174
+ const { error } = zod.z.number()[op](value).safeParse(v.toNumber());
175
+ error?.issues.forEach((issue) => {
176
+ if (op === "gt" || op === "gte") ctx.addIssue({
177
+ code: "too_small",
178
+ origin: "number",
179
+ minimum: value,
180
+ type: "decimal",
181
+ inclusive: op === "gte",
182
+ message: issue.message
183
+ });
184
+ else ctx.addIssue({
185
+ code: "too_big",
186
+ origin: "number",
187
+ maximum: value,
188
+ type: "decimal",
189
+ inclusive: op === "lte",
190
+ message: issue.message
191
+ });
192
+ });
193
+ });
194
+ }
195
+ if (attributes && addExtraValidation) for (const attr of attributes) {
196
+ const val = getArgValue(attr.args?.[0]?.value);
197
+ if (val === void 0) continue;
198
+ switch (attr.name) {
199
+ case "@gt":
200
+ result = refine(result, "gt", val);
201
+ break;
202
+ case "@gte":
203
+ result = refine(result, "gte", val);
204
+ break;
205
+ case "@lt":
206
+ result = refine(result, "lt", val);
207
+ break;
208
+ case "@lte":
209
+ result = refine(result, "lte", val);
210
+ break;
211
+ }
212
+ }
213
+ return result;
265
214
  }
266
- __name(addDecimalValidation, "addDecimalValidation");
267
215
  function addListValidation(schema, attributes) {
268
- if (!attributes || attributes.length === 0) {
269
- return schema;
270
- }
271
- let result = schema;
272
- for (const attr of attributes) {
273
- if (attr.name === "@length") {
274
- const min = getArgValue(attr.args?.find((a) => a.name === "min")?.value);
275
- if (min !== void 0) {
276
- result = result.min(min);
277
- }
278
- const max = getArgValue(attr.args?.find((a) => a.name === "max")?.value);
279
- if (max !== void 0) {
280
- result = result.max(max);
281
- }
282
- }
283
- }
284
- return result;
216
+ if (!attributes || attributes.length === 0) return schema;
217
+ let result = schema;
218
+ for (const attr of attributes) if (attr.name === "@length") {
219
+ const min = getArgValue(attr.args?.find((a) => a.name === "min")?.value);
220
+ if (min !== void 0) result = result.min(min);
221
+ const max = getArgValue(attr.args?.find((a) => a.name === "max")?.value);
222
+ if (max !== void 0) result = result.max(max);
223
+ }
224
+ return result;
285
225
  }
286
- __name(addListValidation, "addListValidation");
226
+ /**
227
+ * Recursively collects all field names referenced by `kind: 'field'` nodes
228
+ * inside an expression tree.
229
+ */
287
230
  function collectFieldRefs(expr) {
288
- const refs = /* @__PURE__ */ new Set();
289
- function walk(e) {
290
- switch (e.kind) {
291
- case "field":
292
- refs.add(e.field);
293
- break;
294
- case "unary":
295
- walk(e.operand);
296
- break;
297
- case "binary":
298
- walk(e.left);
299
- walk(e.right);
300
- break;
301
- case "call":
302
- e.args?.forEach(walk);
303
- break;
304
- case "array":
305
- e.items.forEach(walk);
306
- break;
307
- case "member":
308
- walk(e.receiver);
309
- break;
310
- }
311
- }
312
- __name(walk, "walk");
313
- walk(expr);
314
- return refs;
231
+ const refs = /* @__PURE__ */ new Set();
232
+ function walk(e) {
233
+ switch (e.kind) {
234
+ case "field":
235
+ refs.add(e.field);
236
+ break;
237
+ case "unary":
238
+ walk(e.operand);
239
+ break;
240
+ case "binary":
241
+ walk(e.left);
242
+ walk(e.right);
243
+ break;
244
+ case "call":
245
+ e.args?.forEach(walk);
246
+ break;
247
+ case "array":
248
+ e.items.forEach(walk);
249
+ break;
250
+ case "member":
251
+ walk(e.receiver);
252
+ break;
253
+ }
254
+ }
255
+ walk(expr);
256
+ return refs;
315
257
  }
316
- __name(collectFieldRefs, "collectFieldRefs");
258
+ /**
259
+ * Applies `@@validate` rules from `attributes` to `schema` as Zod refinements.
260
+ *
261
+ * When `presentFields` is provided, only rules whose every field reference is
262
+ * present in the set are applied. Rules that reference a field absent from the
263
+ * set are silently skipped — they cannot be evaluated correctly against a
264
+ * partial payload (e.g. when `select` or `omit` has been used).
265
+ *
266
+ * Omit `presentFields` (or pass `undefined`) to apply all rules
267
+ * unconditionally, which is the correct behaviour for full-model schemas.
268
+ *
269
+ * Note: `@@validate` conditions are restricted by the ZModel compiler to
270
+ * scalar fields of the same model only — relation fields are a compile error.
271
+ * A flat field-name set is therefore sufficient.
272
+ */
317
273
  function addCustomValidation(schema, attributes, presentFields) {
318
- const attrs = attributes?.filter((a) => a.name === "@@validate");
319
- if (!attrs || attrs.length === 0) {
320
- return schema;
321
- }
322
- let result = schema;
323
- for (const attr of attrs) {
324
- const expr = attr.args?.[0]?.value;
325
- if (!expr) {
326
- continue;
327
- }
328
- if (presentFields !== void 0) {
329
- const refs = collectFieldRefs(expr);
330
- if ([
331
- ...refs
332
- ].some((ref) => !presentFields.has(ref))) {
333
- continue;
334
- }
335
- }
336
- const message = getArgValue(attr.args?.[1]?.value);
337
- const pathExpr = attr.args?.[2]?.value;
338
- let path = void 0;
339
- if (pathExpr && import_schema.ExpressionUtils.isArray(pathExpr)) {
340
- path = pathExpr.items.map((e) => import_schema.ExpressionUtils.getLiteralValue(e));
341
- }
342
- result = applyValidation(result, expr, message, path);
343
- }
344
- return result;
274
+ const attrs = attributes?.filter((a) => a.name === "@@validate");
275
+ if (!attrs || attrs.length === 0) return schema;
276
+ let result = schema;
277
+ for (const attr of attrs) {
278
+ const expr = attr.args?.[0]?.value;
279
+ if (!expr) continue;
280
+ if (presentFields !== void 0) {
281
+ if ([...collectFieldRefs(expr)].some((ref) => !presentFields.has(ref))) continue;
282
+ }
283
+ const message = getArgValue(attr.args?.[1]?.value);
284
+ const pathExpr = attr.args?.[2]?.value;
285
+ let path = void 0;
286
+ if (pathExpr && _zenstackhq_schema.ExpressionUtils.isArray(pathExpr)) path = pathExpr.items.map((e) => _zenstackhq_schema.ExpressionUtils.getLiteralValue(e));
287
+ result = applyValidation(result, expr, message, path);
288
+ }
289
+ return result;
345
290
  }
346
- __name(addCustomValidation, "addCustomValidation");
347
291
  function applyValidation(schema, expr, message, path) {
348
- const options = {};
349
- if (message) {
350
- options.error = message;
351
- }
352
- if (path) {
353
- options.path = path;
354
- }
355
- return schema.refine((data) => Boolean(evalExpression(data, expr)), options);
292
+ const options = {};
293
+ if (message) options.error = message;
294
+ if (path) options.path = path;
295
+ return schema.refine((data) => Boolean(evalExpression(data, expr)), options);
356
296
  }
357
- __name(applyValidation, "applyValidation");
358
297
  function evalExpression(data, expr) {
359
- switch (expr.kind) {
360
- case "literal":
361
- return expr.value;
362
- case "array":
363
- return expr.items.map((item) => evalExpression(data, item));
364
- case "field":
365
- return evalField(data, expr);
366
- case "member":
367
- return evalMember(data, expr);
368
- case "unary":
369
- return evalUnary(data, expr);
370
- case "binary":
371
- return evalBinary(data, expr);
372
- case "call":
373
- return evalCall(data, expr);
374
- case "this":
375
- return data ?? null;
376
- case "null":
377
- return null;
378
- case "binding":
379
- throw new SchemaFactoryError("Binding expression is not supported in validation expressions");
380
- }
298
+ switch (expr.kind) {
299
+ case "literal": return expr.value;
300
+ case "array": return expr.items.map((item) => evalExpression(data, item));
301
+ case "field": return evalField(data, expr);
302
+ case "member": return evalMember(data, expr);
303
+ case "unary": return evalUnary(data, expr);
304
+ case "binary": return evalBinary(data, expr);
305
+ case "call": return evalCall(data, expr);
306
+ case "this": return data ?? null;
307
+ case "null": return null;
308
+ case "binding": throw new SchemaFactoryError("Binding expression is not supported in validation expressions");
309
+ }
381
310
  }
382
- __name(evalExpression, "evalExpression");
311
+ /**
312
+ * Sentinel value returned by `evalField` when a field key is entirely absent
313
+ * from the data object (as opposed to being present with a `null` value).
314
+ * Used by comparison operators to skip @@validate rules against missing
315
+ * optional fields (e.g. when `optionality: 'all'` produces a partial payload).
316
+ */
317
+ const ABSENT = Symbol("absent");
383
318
  function evalField(data, e) {
384
- return data?.[e.field] ?? null;
319
+ if (data == null || !(e.field in data)) return ABSENT;
320
+ return data[e.field] ?? null;
385
321
  }
386
- __name(evalField, "evalField");
387
322
  function evalUnary(data, expr) {
388
- const operand = evalExpression(data, expr.operand);
389
- switch (expr.op) {
390
- case "!":
391
- return !operand;
392
- default:
393
- throw new SchemaFactoryError(`Unsupported unary operator: ${expr.op}`);
394
- }
323
+ const operand = evalExpression(data, expr.operand);
324
+ switch (expr.op) {
325
+ case "!": return !operand;
326
+ default: throw new SchemaFactoryError(`Unsupported unary operator: ${expr.op}`);
327
+ }
395
328
  }
396
- __name(evalUnary, "evalUnary");
397
329
  function evalBinary(data, expr) {
398
- const left = evalExpression(data, expr.left);
399
- const right = evalExpression(data, expr.right);
400
- switch (expr.op) {
401
- case "&&":
402
- return Boolean(left) && Boolean(right);
403
- case "||":
404
- return Boolean(left) || Boolean(right);
405
- case "==":
406
- return left == right;
407
- case "!=":
408
- return left != right;
409
- case "<":
410
- return left < right;
411
- case "<=":
412
- return left <= right;
413
- case ">":
414
- return left > right;
415
- case ">=":
416
- return left >= right;
417
- case "?":
418
- if (!Array.isArray(left)) {
419
- return false;
420
- }
421
- return left.some((item) => item === right);
422
- case "!":
423
- if (!Array.isArray(left)) {
424
- return false;
425
- }
426
- return left.every((item) => item === right);
427
- case "^":
428
- if (!Array.isArray(left)) {
429
- return false;
430
- }
431
- return !left.some((item) => item === right);
432
- case "in":
433
- if (!Array.isArray(right)) {
434
- return false;
435
- }
436
- return right.includes(left);
437
- default:
438
- throw new SchemaFactoryError(`Unsupported binary operator: ${expr.op}`);
439
- }
330
+ const left = evalExpression(data, expr.left);
331
+ const right = evalExpression(data, expr.right);
332
+ switch (expr.op) {
333
+ case "&&": return Boolean(left) && Boolean(right);
334
+ case "||": return Boolean(left) || Boolean(right);
335
+ case "==": return (left === ABSENT ? null : left) == (right === ABSENT ? null : right);
336
+ case "!=": return (left === ABSENT ? null : left) != (right === ABSENT ? null : right);
337
+ case "<":
338
+ case "<=":
339
+ case ">":
340
+ case ">=":
341
+ if (left === ABSENT || right === ABSENT) return true;
342
+ return expr.op === "<" ? left < right : expr.op === "<=" ? left <= right : expr.op === ">" ? left > right : left >= right;
343
+ case "?":
344
+ if (!Array.isArray(left)) return false;
345
+ return left.some((item) => item === right);
346
+ case "!":
347
+ if (!Array.isArray(left)) return false;
348
+ return left.every((item) => item === right);
349
+ case "^":
350
+ if (!Array.isArray(left)) return false;
351
+ return !left.some((item) => item === right);
352
+ case "in":
353
+ if (!Array.isArray(right)) return false;
354
+ return right.includes(left);
355
+ default: throw new SchemaFactoryError(`Unsupported binary operator: ${expr.op}`);
356
+ }
440
357
  }
441
- __name(evalBinary, "evalBinary");
442
358
  function evalMember(data, expr) {
443
- let result = evalExpression(data, expr.receiver);
444
- for (const member of expr.members) {
445
- if (!result || typeof result !== "object") {
446
- return void 0;
447
- }
448
- result = result[member];
449
- }
450
- return result ?? null;
359
+ let result = evalExpression(data, expr.receiver);
360
+ for (const member of expr.members) {
361
+ if (!result || typeof result !== "object") return;
362
+ result = result[member];
363
+ }
364
+ return result ?? null;
451
365
  }
452
- __name(evalMember, "evalMember");
453
366
  function evalCall(data, expr) {
454
- const f = expr.function;
455
- const fieldArg = expr.args?.[0] ? evalExpression(data, expr.args[0]) : void 0;
456
- switch (f) {
457
- // string functions
458
- case "length": {
459
- if (fieldArg === void 0 || fieldArg === null) {
460
- return false;
461
- }
462
- invariant(typeof fieldArg === "string" || Array.isArray(fieldArg), `"${f}" first argument must be a string or a list`);
463
- return fieldArg.length;
464
- }
465
- case "startsWith":
466
- case "endsWith":
467
- case "contains": {
468
- if (fieldArg === void 0 || fieldArg === null) {
469
- return false;
470
- }
471
- invariant(typeof fieldArg === "string", `"${f}" first argument must be a string`);
472
- invariant(expr.args?.[1], `"${f}" requires a search argument`);
473
- const search = getArgValue(expr.args?.[1]);
474
- const caseInsensitive = getArgValue(expr.args?.[2]) ?? false;
475
- const applyStringOp = /* @__PURE__ */ __name((x, y) => {
476
- switch (f) {
477
- case "startsWith":
478
- return x.startsWith(y);
479
- case "endsWith":
480
- return x.endsWith(y);
481
- case "contains":
482
- return x.includes(y);
483
- }
484
- }, "applyStringOp");
485
- return caseInsensitive ? applyStringOp(fieldArg.toLowerCase(), search.toLowerCase()) : applyStringOp(fieldArg, search);
486
- }
487
- case "regex": {
488
- if (fieldArg === void 0 || fieldArg === null) {
489
- return false;
490
- }
491
- invariant(typeof fieldArg === "string", `"${f}" first argument must be a string`);
492
- const pattern = getArgValue(expr.args?.[1]);
493
- invariant(pattern !== void 0, `"${f}" requires a pattern argument`);
494
- return new RegExp(pattern).test(fieldArg);
495
- }
496
- case "isEmail":
497
- case "isUrl":
498
- case "isDateTime": {
499
- if (fieldArg === void 0 || fieldArg === null) {
500
- return false;
501
- }
502
- invariant(typeof fieldArg === "string", `"${f}" first argument must be a string`);
503
- const fn = f === "isEmail" ? "email" : f === "isUrl" ? "url" : "datetime";
504
- return import_zod.z.string()[fn]().safeParse(fieldArg).success;
505
- }
506
- // list functions
507
- case "has":
508
- case "hasEvery":
509
- case "hasSome": {
510
- invariant(expr.args?.[1], `${f} requires a search argument`);
511
- if (fieldArg === void 0 || fieldArg === null) {
512
- return false;
513
- }
514
- invariant(Array.isArray(fieldArg), `"${f}" first argument must be an array field`);
515
- const search = evalExpression(data, expr.args?.[1]);
516
- if (f === "has") {
517
- return fieldArg.some((item) => item === search);
518
- } else if (f === "hasEvery") {
519
- invariant(Array.isArray(search), "hasEvery second argument must be an array");
520
- return search.every((v) => fieldArg.some((item) => item === v));
521
- } else {
522
- invariant(Array.isArray(search), "hasSome second argument must be an array");
523
- return search.some((v) => fieldArg.some((item) => item === v));
524
- }
525
- }
526
- case "isEmpty": {
527
- if (fieldArg === void 0 || fieldArg === null) {
528
- return false;
529
- }
530
- invariant(Array.isArray(fieldArg), `"${f}" first argument must be an array field`);
531
- return fieldArg.length === 0;
532
- }
533
- default:
534
- throw new SchemaFactoryError(`Unsupported function "${f}"`);
535
- }
367
+ const f = expr.function;
368
+ const fieldArg = expr.args?.[0] ? evalExpression(data, expr.args[0]) : void 0;
369
+ switch (f) {
370
+ case "length":
371
+ if (fieldArg === void 0 || fieldArg === null || fieldArg === ABSENT) return false;
372
+ invariant(typeof fieldArg === "string" || Array.isArray(fieldArg), `"${f}" first argument must be a string or a list`);
373
+ return fieldArg.length;
374
+ case "startsWith":
375
+ case "endsWith":
376
+ case "contains": {
377
+ if (fieldArg === void 0 || fieldArg === null || fieldArg === ABSENT) return false;
378
+ invariant(typeof fieldArg === "string", `"${f}" first argument must be a string`);
379
+ invariant(expr.args?.[1], `"${f}" requires a search argument`);
380
+ const search = getArgValue(expr.args?.[1]);
381
+ const caseInsensitive = getArgValue(expr.args?.[2]) ?? false;
382
+ const applyStringOp = (x, y) => {
383
+ switch (f) {
384
+ case "startsWith": return x.startsWith(y);
385
+ case "endsWith": return x.endsWith(y);
386
+ case "contains": return x.includes(y);
387
+ }
388
+ };
389
+ return caseInsensitive ? applyStringOp(fieldArg.toLowerCase(), search.toLowerCase()) : applyStringOp(fieldArg, search);
390
+ }
391
+ case "regex": {
392
+ if (fieldArg === void 0 || fieldArg === null || fieldArg === ABSENT) return false;
393
+ invariant(typeof fieldArg === "string", `"${f}" first argument must be a string`);
394
+ const pattern = getArgValue(expr.args?.[1]);
395
+ invariant(pattern !== void 0, `"${f}" requires a pattern argument`);
396
+ return new RegExp(pattern).test(fieldArg);
397
+ }
398
+ case "isEmail":
399
+ case "isUrl":
400
+ case "isDateTime": {
401
+ if (fieldArg === void 0 || fieldArg === null || fieldArg === ABSENT) return false;
402
+ invariant(typeof fieldArg === "string", `"${f}" first argument must be a string`);
403
+ const fn = f === "isEmail" ? "email" : f === "isUrl" ? "url" : "datetime";
404
+ return zod.z.string()[fn]().safeParse(fieldArg).success;
405
+ }
406
+ case "has":
407
+ case "hasEvery":
408
+ case "hasSome": {
409
+ invariant(expr.args?.[1], `${f} requires a search argument`);
410
+ if (fieldArg === void 0 || fieldArg === null || fieldArg === ABSENT) return false;
411
+ invariant(Array.isArray(fieldArg), `"${f}" first argument must be an array field`);
412
+ const search = evalExpression(data, expr.args?.[1]);
413
+ if (f === "has") return fieldArg.some((item) => item === search);
414
+ else if (f === "hasEvery") {
415
+ invariant(Array.isArray(search), "hasEvery second argument must be an array");
416
+ return search.every((v) => fieldArg.some((item) => item === v));
417
+ } else {
418
+ invariant(Array.isArray(search), "hasSome second argument must be an array");
419
+ return search.some((v) => fieldArg.some((item) => item === v));
420
+ }
421
+ }
422
+ case "isEmpty":
423
+ if (fieldArg === void 0 || fieldArg === null || fieldArg === ABSENT) return false;
424
+ invariant(Array.isArray(fieldArg), `"${f}" first argument must be an array field`);
425
+ return fieldArg.length === 0;
426
+ default: throw new SchemaFactoryError(`Unsupported function "${f}"`);
427
+ }
536
428
  }
537
- __name(evalCall, "evalCall");
538
429
  function invariant(condition, message) {
539
- if (!condition) {
540
- throw new SchemaFactoryError(message ?? "Invariant failed");
541
- }
430
+ if (!condition) throw new SchemaFactoryError(message ?? "Invariant failed");
542
431
  }
543
- __name(invariant, "invariant");
544
-
545
- // src/factory.ts
432
+ //#endregion
433
+ //#region src/factory.ts
546
434
  function createSchemaFactory(schema) {
547
- return new SchemaFactory(schema);
435
+ return new SchemaFactory(schema);
548
436
  }
549
- __name(createSchemaFactory, "createSchemaFactory");
550
- var rawOptionsSchema = import_zod2.default.lazy(() => import_zod2.default.object({
551
- select: import_zod2.default.record(import_zod2.default.string(), import_zod2.default.union([
552
- import_zod2.default.boolean(),
553
- rawOptionsSchema
554
- ])).optional(),
555
- include: import_zod2.default.record(import_zod2.default.string(), import_zod2.default.union([
556
- import_zod2.default.boolean(),
557
- rawOptionsSchema
558
- ])).optional(),
559
- omit: import_zod2.default.record(import_zod2.default.string(), import_zod2.default.boolean()).optional()
437
+ /**
438
+ * Recursive Zod schema that validates a `RawOptions` object at runtime,
439
+ * enforcing the same mutual-exclusion rules that the TypeScript union type
440
+ * enforces at compile time:
441
+ * - `select` and `include` cannot be used together.
442
+ * - `select` and `omit` cannot be used together.
443
+ * Nested relation options are validated with the same rules.
444
+ */
445
+ const rawOptionsSchema = zod.default.lazy(() => zod.default.strictObject({
446
+ select: zod.default.record(zod.default.string(), zod.default.union([zod.default.literal(true), rawOptionsSchema])).optional(),
447
+ include: zod.default.record(zod.default.string(), zod.default.union([zod.default.literal(true), rawOptionsSchema])).optional(),
448
+ omit: zod.default.record(zod.default.string(), zod.default.literal(true)).optional(),
449
+ optionality: zod.default.enum(["all", "defaults"]).optional()
560
450
  }).superRefine((val, ctx) => {
561
- if (val.select && val.include) {
562
- ctx.addIssue({
563
- code: "custom",
564
- message: "`select` and `include` cannot be used together"
565
- });
566
- }
567
- if (val.select && val.omit) {
568
- ctx.addIssue({
569
- code: "custom",
570
- message: "`select` and `omit` cannot be used together"
571
- });
572
- }
451
+ if (val.select && val.include) ctx.addIssue({
452
+ code: "custom",
453
+ message: "`select` and `include` cannot be used together"
454
+ });
455
+ if (val.select && val.omit) ctx.addIssue({
456
+ code: "custom",
457
+ message: "`select` and `omit` cannot be used together"
458
+ });
573
459
  }));
574
- var SchemaFactory = class SchemaFactory2 {
575
- static {
576
- __name(this, "SchemaFactory");
577
- }
578
- schema;
579
- constructor(_schema) {
580
- this.schema = new import_schema2.SchemaAccessor(_schema);
581
- }
582
- makeModelSchema(model, options) {
583
- const modelDef = this.schema.requireModel(model);
584
- if (!options) {
585
- const fields2 = {};
586
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
587
- if (fieldDef.relation) {
588
- const relatedModelName = fieldDef.type;
589
- const lazySchema = import_zod2.default.lazy(() => this.makeModelSchema(relatedModelName));
590
- fields2[fieldName] = this.applyDescription(this.applyCardinality(lazySchema, fieldDef).optional(), fieldDef.attributes);
591
- } else {
592
- fields2[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
593
- }
594
- }
595
- const shape2 = import_zod2.default.strictObject(fields2);
596
- return this.applyDescription(addCustomValidation(shape2, modelDef.attributes), modelDef.attributes);
597
- }
598
- const rawOptions = rawOptionsSchema.parse(options);
599
- const fields = this.buildFieldsWithOptions(model, rawOptions);
600
- const shape = import_zod2.default.strictObject(fields);
601
- const presentFields = this.buildPresentFields(model, rawOptions);
602
- const withValidation = addCustomValidation(shape, modelDef.attributes, presentFields);
603
- return this.applyDescription(withValidation, modelDef.attributes);
604
- }
605
- makeModelCreateSchema(model) {
606
- const modelDef = this.schema.requireModel(model);
607
- const fields = {};
608
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
609
- if (fieldDef.relation || fieldDef.computed || fieldDef.isDiscriminator) {
610
- continue;
611
- }
612
- let fieldSchema = this.makeScalarFieldSchema(fieldDef);
613
- if (fieldDef.optional || fieldDef.default !== void 0 || fieldDef.updatedAt) {
614
- fieldSchema = fieldSchema.optional();
615
- }
616
- fields[fieldName] = this.applyDescription(fieldSchema, fieldDef.attributes);
617
- }
618
- const shape = import_zod2.default.strictObject(fields);
619
- return this.applyDescription(addCustomValidation(shape, modelDef.attributes), modelDef.attributes);
620
- }
621
- makeModelUpdateSchema(model) {
622
- const modelDef = this.schema.requireModel(model);
623
- const fields = {};
624
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
625
- if (fieldDef.relation || fieldDef.computed || fieldDef.isDiscriminator) {
626
- continue;
627
- }
628
- let fieldSchema = this.makeScalarFieldSchema(fieldDef);
629
- fieldSchema = fieldSchema.optional();
630
- fields[fieldName] = this.applyDescription(fieldSchema, fieldDef.attributes);
631
- }
632
- const shape = import_zod2.default.strictObject(fields);
633
- return this.applyDescription(addCustomValidation(shape, modelDef.attributes), modelDef.attributes);
634
- }
635
- // -------------------------------------------------------------------------
636
- // Options-aware field building
637
- // -------------------------------------------------------------------------
638
- /**
639
- * Internal loose options shape used at runtime (we've already validated the
640
- * type-level constraints via the overload signatures).
641
- */
642
- buildFieldsWithOptions(model, options) {
643
- const { select, include, omit } = options;
644
- const modelDef = this.schema.requireModel(model);
645
- const fields = {};
646
- if (select) {
647
- for (const [key, value] of Object.entries(select)) {
648
- if (!value) continue;
649
- const fieldDef = modelDef.fields[key];
650
- if (!fieldDef) {
651
- throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
652
- }
653
- if (fieldDef.relation) {
654
- const subOptions = typeof value === "object" ? value : void 0;
655
- const relSchema = this.makeRelationFieldSchema(fieldDef, subOptions);
656
- fields[key] = this.applyDescription(this.applyCardinality(relSchema, fieldDef).optional(), fieldDef.attributes);
657
- } else {
658
- if (typeof value === "object") {
659
- throw new SchemaFactoryError(`Field "${key}" on model "${model}" is a scalar field and cannot have nested options`);
660
- }
661
- fields[key] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
662
- }
663
- }
664
- } else {
665
- if (omit) {
666
- for (const key of Object.keys(omit)) {
667
- const fieldDef = modelDef.fields[key];
668
- if (!fieldDef) {
669
- throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
670
- }
671
- if (fieldDef.relation) {
672
- throw new SchemaFactoryError(`Field "${key}" on model "${model}" is a relation field and cannot be used in "omit"`);
673
- }
674
- }
675
- }
676
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
677
- if (fieldDef.relation) continue;
678
- if (omit?.[fieldName] === true) continue;
679
- fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
680
- }
681
- if (include) {
682
- for (const [key, value] of Object.entries(include)) {
683
- if (!value) continue;
684
- const fieldDef = modelDef.fields[key];
685
- if (!fieldDef) {
686
- throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
687
- }
688
- if (!fieldDef.relation) {
689
- throw new SchemaFactoryError(`Field "${key}" on model "${model}" is not a relation field and cannot be used in "include"`);
690
- }
691
- const subOptions = typeof value === "object" ? value : void 0;
692
- const relSchema = this.makeRelationFieldSchema(fieldDef, subOptions);
693
- fields[key] = this.applyDescription(this.applyCardinality(relSchema, fieldDef).optional(), fieldDef.attributes);
694
- }
695
- }
696
- }
697
- return fields;
698
- }
699
- /**
700
- * Returns the set of scalar field names that will be present in the
701
- * resulting schema after applying `options`. Used by `addCustomValidation`
702
- * to skip `@@validate` rules that reference an absent field.
703
- *
704
- * Only scalar fields matter here because `@@validate` conditions are
705
- * restricted by the ZModel compiler to scalar fields of the same model.
706
- */
707
- buildPresentFields(model, options) {
708
- const { select, omit } = options;
709
- const modelDef = this.schema.requireModel(model);
710
- const fields = /* @__PURE__ */ new Set();
711
- if (select) {
712
- for (const [key, value] of Object.entries(select)) {
713
- if (!value) continue;
714
- const fieldDef = modelDef.fields[key];
715
- if (fieldDef && !fieldDef.relation) {
716
- fields.add(key);
717
- }
718
- }
719
- } else {
720
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
721
- if (fieldDef.relation) continue;
722
- if (omit?.[fieldName] === true) continue;
723
- fields.add(fieldName);
724
- }
725
- }
726
- return fields;
727
- }
728
- /**
729
- * Build the inner Zod schema for a relation field, optionally with nested
730
- * query options. Does NOT apply cardinality/optional wrappers — the caller
731
- * does that.
732
- */
733
- makeRelationFieldSchema(fieldDef, subOptions) {
734
- const relatedModelName = fieldDef.type;
735
- if (subOptions) {
736
- return this.makeModelSchema(relatedModelName, subOptions);
737
- }
738
- return import_zod2.default.lazy(() => this.makeModelSchema(relatedModelName));
739
- }
740
- makeScalarFieldSchema(fieldDef) {
741
- const { type, attributes } = fieldDef;
742
- const enumDef = this.schema.getEnum(type);
743
- if (enumDef) {
744
- return this.applyCardinality(this.makeEnumSchema(type), fieldDef);
745
- }
746
- const typedefDef = this.schema.getTypeDef(type);
747
- if (typedefDef) {
748
- return this.applyCardinality(this.makeTypeSchema(type), fieldDef);
749
- }
750
- let base;
751
- switch (type) {
752
- case "String":
753
- base = addStringValidation(import_zod2.default.string(), attributes);
754
- break;
755
- case "Int":
756
- base = addNumberValidation(import_zod2.default.number().int(), attributes);
757
- break;
758
- case "Float":
759
- base = addNumberValidation(import_zod2.default.number(), attributes);
760
- break;
761
- case "Boolean":
762
- base = import_zod2.default.boolean();
763
- break;
764
- case "BigInt":
765
- base = addBigIntValidation(import_zod2.default.bigint(), attributes);
766
- break;
767
- case "Decimal":
768
- base = import_zod2.default.union([
769
- addNumberValidation(import_zod2.default.number(), attributes),
770
- addDecimalValidation(import_zod2.default.string(), attributes, true),
771
- addDecimalValidation(import_zod2.default.instanceof(import_decimal2.default), attributes, true)
772
- ]);
773
- break;
774
- case "DateTime":
775
- base = import_zod2.default.union([
776
- import_zod2.default.date(),
777
- import_zod2.default.iso.datetime()
778
- ]);
779
- break;
780
- case "Bytes":
781
- base = import_zod2.default.instanceof(Uint8Array);
782
- break;
783
- case "Json":
784
- base = this.makeJsonSchema();
785
- break;
786
- case "Unsupported":
787
- base = import_zod2.default.unknown();
788
- break;
789
- default: {
790
- const _exhaustive = type;
791
- throw new SchemaFactoryError(`Unsupported field type: ${_exhaustive}`);
792
- }
793
- }
794
- return this.applyCardinality(base, fieldDef);
795
- }
796
- makeJsonSchema() {
797
- return import_zod2.default.union([
798
- import_zod2.default.string(),
799
- import_zod2.default.number(),
800
- import_zod2.default.boolean(),
801
- import_zod2.default.null(),
802
- import_zod2.default.array(import_zod2.default.lazy(() => this.makeJsonSchema())),
803
- import_zod2.default.object({}).catchall(import_zod2.default.lazy(() => this.makeJsonSchema()))
804
- ]);
805
- }
806
- applyCardinality(schema, fieldDef) {
807
- let result = schema;
808
- if (fieldDef.array) {
809
- result = result.array();
810
- }
811
- if (fieldDef.optional) {
812
- result = result.nullable().optional();
813
- }
814
- return result;
815
- }
816
- makeTypeSchema(type) {
817
- const typeDef = this.schema.requireTypeDef(type);
818
- const fields = {};
819
- for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) {
820
- fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
821
- }
822
- const shape = import_zod2.default.strictObject(fields);
823
- return this.applyDescription(addCustomValidation(shape, typeDef.attributes), typeDef.attributes);
824
- }
825
- makeEnumSchema(_enum) {
826
- const enumDef = this.schema.requireEnum(_enum);
827
- const schema = import_zod2.default.enum(Object.keys(enumDef.values));
828
- return this.applyDescription(schema, enumDef.attributes);
829
- }
830
- getMetaDescription(attributes) {
831
- if (!attributes) return void 0;
832
- for (const attr of attributes) {
833
- if (attr.name !== "@meta" && attr.name !== "@@meta") continue;
834
- const nameExpr = attr.args?.[0]?.value;
835
- if (!nameExpr || import_schema2.ExpressionUtils.getLiteralValue(nameExpr) !== "description") continue;
836
- const valueExpr = attr.args?.[1]?.value;
837
- if (valueExpr) {
838
- return import_schema2.ExpressionUtils.getLiteralValue(valueExpr);
839
- }
840
- }
841
- return void 0;
842
- }
843
- applyDescription(schema, attributes) {
844
- const description = this.getMetaDescription(attributes);
845
- if (description) {
846
- return schema.meta({
847
- description
848
- });
849
- }
850
- return schema;
851
- }
460
+ var SchemaFactory = class {
461
+ schema;
462
+ constructor(_schema) {
463
+ this.schema = new _zenstackhq_schema.SchemaAccessor(_schema);
464
+ }
465
+ makeModelSchema(model, options) {
466
+ const modelDef = this.schema.requireModel(model);
467
+ if (!options) {
468
+ const fields = {};
469
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
470
+ if (fieldDef.relation) continue;
471
+ fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
472
+ }
473
+ const shape = zod.default.strictObject(fields);
474
+ return this.applyDescription(addCustomValidation(shape, modelDef.attributes), modelDef.attributes);
475
+ }
476
+ const rawOptions = rawOptionsSchema.parse(options);
477
+ const fields = this.buildFieldsWithOptions(model, rawOptions);
478
+ const optionalizedFields = this.applyOptionality(fields, model, rawOptions.optionality);
479
+ const shape = zod.default.strictObject(optionalizedFields);
480
+ const presentFields = this.buildPresentFields(model, rawOptions);
481
+ const withValidation = addCustomValidation(shape, modelDef.attributes, presentFields);
482
+ return this.applyDescription(withValidation, modelDef.attributes);
483
+ }
484
+ /**
485
+ * @deprecated Use `makeModelSchema(model, { optionality: 'defaults' })` instead.
486
+ */
487
+ makeModelCreateSchema(model) {
488
+ const modelDef = this.schema.requireModel(model);
489
+ const fields = {};
490
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
491
+ if (fieldDef.relation || fieldDef.computed || fieldDef.isDiscriminator) continue;
492
+ let fieldSchema = this.makeScalarFieldSchema(fieldDef);
493
+ if (fieldDef.optional || fieldDef.default !== void 0 || fieldDef.updatedAt) fieldSchema = fieldSchema.optional();
494
+ fields[fieldName] = this.applyDescription(fieldSchema, fieldDef.attributes);
495
+ }
496
+ const shape = zod.default.strictObject(fields);
497
+ return this.applyDescription(addCustomValidation(shape, modelDef.attributes), modelDef.attributes);
498
+ }
499
+ /**
500
+ * @deprecated Use `makeModelSchema(model, { optionality: 'all' })` instead.
501
+ */
502
+ makeModelUpdateSchema(model) {
503
+ const modelDef = this.schema.requireModel(model);
504
+ const fields = {};
505
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
506
+ if (fieldDef.relation || fieldDef.computed || fieldDef.isDiscriminator) continue;
507
+ let fieldSchema = this.makeScalarFieldSchema(fieldDef);
508
+ fieldSchema = fieldSchema.optional();
509
+ fields[fieldName] = this.applyDescription(fieldSchema, fieldDef.attributes);
510
+ }
511
+ const shape = zod.default.strictObject(fields);
512
+ return this.applyDescription(addCustomValidation(shape, modelDef.attributes), modelDef.attributes);
513
+ }
514
+ /**
515
+ * Applies the `optionality` option to a fields map.
516
+ *
517
+ * - `"all"` — wraps every field in `z.ZodOptional`.
518
+ * - `"defaults"` — only wraps fields that have a `@default` attribute or
519
+ * are `@updatedAt` in `z.ZodOptional`. Fields that are
520
+ * already optional (nullable optional) retain their shape;
521
+ * we just add the outer optional layer.
522
+ * - `undefined` — returns the fields map unchanged.
523
+ */
524
+ applyOptionality(fields, model, optionality) {
525
+ if (!optionality) return fields;
526
+ const modelDef = this.schema.requireModel(model);
527
+ const result = {};
528
+ for (const [fieldName, fieldSchema] of Object.entries(fields)) if (optionality === "all") result[fieldName] = this.wrapOptionalPreservingMeta(fieldSchema);
529
+ else {
530
+ const fieldDef = modelDef.fields[fieldName];
531
+ result[fieldName] = fieldDef && (fieldDef.default !== void 0 || fieldDef.updatedAt || fieldDef.optional) ? this.wrapOptionalPreservingMeta(fieldSchema) : fieldSchema;
532
+ }
533
+ return result;
534
+ }
535
+ /**
536
+ * Internal loose options shape used at runtime (we've already validated the
537
+ * type-level constraints via the overload signatures).
538
+ */
539
+ buildFieldsWithOptions(model, options) {
540
+ const { select, include, omit } = options;
541
+ const modelDef = this.schema.requireModel(model);
542
+ const fields = {};
543
+ if (select) for (const [key, value] of Object.entries(select)) {
544
+ const fieldDef = modelDef.fields[key];
545
+ if (!fieldDef) throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
546
+ if (fieldDef.relation) {
547
+ const subOptions = typeof value === "object" ? value : void 0;
548
+ const relSchema = this.makeRelationFieldSchema(fieldDef, subOptions);
549
+ fields[key] = this.applyDescription(this.applyCardinality(relSchema, fieldDef).optional(), fieldDef.attributes);
550
+ } else {
551
+ if (typeof value === "object") throw new SchemaFactoryError(`Field "${key}" on model "${model}" is a scalar field and cannot have nested options`);
552
+ fields[key] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
553
+ }
554
+ }
555
+ else {
556
+ if (omit) for (const key of Object.keys(omit)) {
557
+ const fieldDef = modelDef.fields[key];
558
+ if (!fieldDef) throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
559
+ if (fieldDef.relation) throw new SchemaFactoryError(`Field "${key}" on model "${model}" is a relation field and cannot be used in "omit"`);
560
+ }
561
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
562
+ if (fieldDef.relation) continue;
563
+ if (omit?.[fieldName] === true) continue;
564
+ fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
565
+ }
566
+ if (include) for (const [key, value] of Object.entries(include)) {
567
+ const fieldDef = modelDef.fields[key];
568
+ if (!fieldDef) throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
569
+ if (!fieldDef.relation) throw new SchemaFactoryError(`Field "${key}" on model "${model}" is not a relation field and cannot be used in "include"`);
570
+ const subOptions = typeof value === "object" ? value : void 0;
571
+ const relSchema = this.makeRelationFieldSchema(fieldDef, subOptions);
572
+ fields[key] = this.applyDescription(this.applyCardinality(relSchema, fieldDef).optional(), fieldDef.attributes);
573
+ }
574
+ }
575
+ return fields;
576
+ }
577
+ /**
578
+ * Returns the set of scalar field names that will be present in the
579
+ * resulting schema after applying `options`. Used by `addCustomValidation`
580
+ * to skip `@@validate` rules that reference an absent field.
581
+ *
582
+ * Only scalar fields matter here because `@@validate` conditions are
583
+ * restricted by the ZModel compiler to scalar fields of the same model.
584
+ */
585
+ buildPresentFields(model, options) {
586
+ const { select, omit } = options;
587
+ const modelDef = this.schema.requireModel(model);
588
+ const fields = /* @__PURE__ */ new Set();
589
+ if (select) for (const key of Object.keys(select)) {
590
+ const fieldDef = modelDef.fields[key];
591
+ if (fieldDef && !fieldDef.relation) fields.add(key);
592
+ }
593
+ else for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
594
+ if (fieldDef.relation) continue;
595
+ if (omit?.[fieldName] === true) continue;
596
+ fields.add(fieldName);
597
+ }
598
+ return fields;
599
+ }
600
+ /**
601
+ * Build the inner Zod schema for a relation field, optionally with nested
602
+ * query options. Does NOT apply cardinality/optional wrappers — the caller
603
+ * does that.
604
+ */
605
+ makeRelationFieldSchema(fieldDef, subOptions) {
606
+ const relatedModelName = fieldDef.type;
607
+ if (subOptions) return this.makeModelSchema(relatedModelName, subOptions);
608
+ return zod.default.lazy(() => this.makeModelSchema(relatedModelName));
609
+ }
610
+ makeScalarFieldSchema(fieldDef) {
611
+ const { type, attributes } = fieldDef;
612
+ if (this.schema.getEnum(type)) return this.applyCardinality(this.makeEnumSchema(type), fieldDef);
613
+ if (this.schema.getTypeDef(type)) return this.applyCardinality(this.makeTypeSchema(type), fieldDef);
614
+ let base;
615
+ switch (type) {
616
+ case "String":
617
+ base = addStringValidation(zod.default.string(), attributes);
618
+ break;
619
+ case "Int":
620
+ base = addNumberValidation(zod.default.number().int(), attributes);
621
+ break;
622
+ case "Float":
623
+ base = addNumberValidation(zod.default.number(), attributes);
624
+ break;
625
+ case "Boolean":
626
+ base = zod.default.boolean();
627
+ break;
628
+ case "BigInt":
629
+ base = addBigIntValidation(zod.default.bigint(), attributes);
630
+ break;
631
+ case "Decimal":
632
+ base = zod.default.union([
633
+ addNumberValidation(zod.default.number(), attributes),
634
+ addDecimalValidation(zod.default.string(), attributes, true),
635
+ addDecimalValidation(zod.default.instanceof(decimal_js.default), attributes, true)
636
+ ]);
637
+ break;
638
+ case "DateTime":
639
+ base = zod.default.union([zod.default.date(), zod.default.iso.datetime()]);
640
+ break;
641
+ case "Bytes":
642
+ base = zod.default.instanceof(Uint8Array);
643
+ break;
644
+ case "Json":
645
+ base = this.makeJsonSchema();
646
+ break;
647
+ case "Unsupported":
648
+ base = zod.default.unknown();
649
+ break;
650
+ default: throw new SchemaFactoryError(`Unsupported field type: ${type}`);
651
+ }
652
+ return this.applyCardinality(base, fieldDef);
653
+ }
654
+ makeJsonSchema() {
655
+ return zod.default.union([
656
+ zod.default.string(),
657
+ zod.default.number(),
658
+ zod.default.boolean(),
659
+ zod.default.null(),
660
+ zod.default.array(zod.default.lazy(() => this.makeJsonSchema())),
661
+ zod.default.object({}).catchall(zod.default.lazy(() => this.makeJsonSchema()))
662
+ ]);
663
+ }
664
+ /**
665
+ * Wraps a schema with `.optional()` and copies any `description` from its
666
+ * metadata onto the resulting `ZodOptional`, so that callers inspecting
667
+ * `.meta()?.description` on shape fields still find the value after
668
+ * optionality has been applied.
669
+ */
670
+ wrapOptionalPreservingMeta(schema) {
671
+ const optional = schema.optional();
672
+ const description = schema.meta()?.description;
673
+ if (description) return optional.meta({ description });
674
+ return optional;
675
+ }
676
+ applyCardinality(schema, fieldDef) {
677
+ let result = schema;
678
+ if (fieldDef.array) result = result.array();
679
+ if (fieldDef.optional) result = result.nullable().optional();
680
+ return result;
681
+ }
682
+ makeTypeSchema(type) {
683
+ const typeDef = this.schema.requireTypeDef(type);
684
+ const fields = {};
685
+ for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
686
+ const shape = zod.default.strictObject(fields);
687
+ return this.applyDescription(addCustomValidation(shape, typeDef.attributes), typeDef.attributes);
688
+ }
689
+ makeEnumSchema(_enum) {
690
+ const enumDef = this.schema.requireEnum(_enum);
691
+ const schema = zod.default.enum(Object.keys(enumDef.values));
692
+ return this.applyDescription(schema, enumDef.attributes);
693
+ }
694
+ getMetaDescription(attributes) {
695
+ if (!attributes) return void 0;
696
+ for (const attr of attributes) {
697
+ if (attr.name !== "@meta" && attr.name !== "@@meta") continue;
698
+ const nameExpr = attr.args?.[0]?.value;
699
+ if (!nameExpr || _zenstackhq_schema.ExpressionUtils.getLiteralValue(nameExpr) !== "description") continue;
700
+ const valueExpr = attr.args?.[1]?.value;
701
+ if (valueExpr) return _zenstackhq_schema.ExpressionUtils.getLiteralValue(valueExpr);
702
+ }
703
+ }
704
+ applyDescription(schema, attributes) {
705
+ const description = this.getMetaDescription(attributes);
706
+ if (description) return schema.meta({ description });
707
+ return schema;
708
+ }
852
709
  };
853
- // Annotate the CommonJS export names for ESM import in node:
854
- 0 && (module.exports = {
855
- ZodUtils,
856
- createSchemaFactory
710
+ //#endregion
711
+ Object.defineProperty(exports, "ZodUtils", {
712
+ enumerable: true,
713
+ get: function() {
714
+ return utils_exports;
715
+ }
857
716
  });
717
+ exports.createSchemaFactory = createSchemaFactory;
718
+
858
719
  //# sourceMappingURL=index.cjs.map