@nullix/zod-mongoose-studio 3.2.0 → 3.3.1

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 (118) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/_fonts/57NSSoFy1VLVs2gqly8Ls9awBnZMFyXGrefpmqvdqmc-zJfbBtpgM4cDmcXBsqZNW79_kFnlpPd62b48glgdydA.woff2 +0 -0
  3. package/.output/public/_fonts/8VR2wSMN-3U4NbWAVYXlkRV6hA0jFBXP-0RtL3X7fko-x2gYI4qfmkRdxyQQUPaBZdZdgl1TeVrquF_TxHeM4lM.woff2 +0 -0
  4. package/.output/public/_fonts/GsKUclqeNLJ96g5AU593ug6yanivOiwjW_7zESNPChw-jHA4tBeM1bjF7LATGUpfBuSTyomIFrWBTzjF7txVYfg.woff2 +0 -0
  5. package/.output/public/_fonts/Ld1FnTo3yTIwDyGfTQ5-Fws9AWsCbKfMvgxduXr7JcY-W25bL8NF1fjpLRSOgJb7RoZPHqGQNwMTM7S9tHVoxx8.woff2 +0 -0
  6. package/.output/public/_fonts/NdzqRASp2bovDUhQT1IRE_EMqKJ2KYQdTCfFcBvL8yw-KhwZiS86o3fErOe5GGMExHUemmI_dBfaEFxjISZrBd0.woff2 +0 -0
  7. package/.output/public/_fonts/iTkrULNFJJkTvihIg1Vqi5IODRH_9btXCioVF5l98I8-AndUyau2HR2felA_ra8V2mutQgschhasE5FD1dXGJX8.woff2 +0 -0
  8. package/.output/public/_nuxt/{qQyvCkbV.js → 5Tu2WUJz.js} +1 -1
  9. package/.output/public/_nuxt/B0N6xv5E.js +1 -0
  10. package/.output/public/_nuxt/{DjPT-NCE.js → B0cUlOSM.js} +1 -1
  11. package/.output/public/_nuxt/B9paGgN0.js +33 -0
  12. package/.output/public/_nuxt/{IxYCG8hB.js → BCIlnd0g.js} +1 -1
  13. package/.output/public/_nuxt/{ikxafTHA.js → BNDnV2op.js} +180 -184
  14. package/.output/public/_nuxt/{Ce-T_1aD.js → BO4hqv6q.js} +1 -1
  15. package/.output/public/_nuxt/{Bd32GOUy.js → BOsJJ_ZU.js} +1 -1
  16. package/.output/public/_nuxt/{BzhSDy30.js → C2BHp-MG.js} +1 -1
  17. package/.output/public/_nuxt/{Cs8GXJCB.js → CKULsFUz.js} +1 -1
  18. package/.output/public/_nuxt/CMH9iX_E.js +6 -0
  19. package/.output/public/_nuxt/{tzj4nvDE.js → CzbCpNnc.js} +2 -2
  20. package/.output/public/_nuxt/{CC3n3Aga.js → D87QMS6j.js} +1 -1
  21. package/.output/public/_nuxt/DA0pQuyP.js +27 -0
  22. package/.output/public/_nuxt/{B7P0wQ35.js → DcJ7oPvZ.js} +1 -1
  23. package/.output/public/_nuxt/{Ick_23I4.js → Dce9SnGa.js} +1 -1
  24. package/.output/public/_nuxt/{CAd-qHfI.js → DpKrXpkK.js} +1 -1
  25. package/.output/public/_nuxt/DsnIpnT9.js +1 -0
  26. package/.output/public/_nuxt/{CNZorjDf.js → I3Ucam2s.js} +1 -1
  27. package/.output/public/_nuxt/builds/latest.json +1 -1
  28. package/.output/public/_nuxt/builds/meta/51f1351c-0667-4235-9ddc-16582a51ce03.json +1 -0
  29. package/.output/public/_nuxt/{entry.J_CbC0oY.css → entry.B-vs1tRH.css} +1 -1
  30. package/.output/public/_nuxt/error-404.CTSXlFYa.css +1 -0
  31. package/.output/public/_nuxt/error-500.DqEfQnVZ.css +1 -0
  32. package/.output/public/_nuxt/{nDZOJ7rN.js → o-NCh2rp.js} +2 -2
  33. package/.output/public/_nuxt/{qwxNOyg7.js → sKEJiAHO.js} +1 -1
  34. package/.output/public/_nuxt/{81vqh61j.js → tqQNlhT9.js} +1 -1
  35. package/.output/public/_nuxt/ypRHVLFO.js +1 -0
  36. package/.output/server/chunks/_/error-500.mjs.map +1 -1
  37. package/.output/server/chunks/build/client.precomputed.mjs +1 -1
  38. package/.output/server/chunks/build/{error-404-BN-7rNE4.mjs → error-404-KRkA0DPI.mjs} +10 -4
  39. package/.output/server/chunks/build/error-404-KRkA0DPI.mjs.map +1 -0
  40. package/.output/server/chunks/build/error-404-styles.I0NYw-Bn.mjs +8 -0
  41. package/.output/server/chunks/build/error-404-styles.I0NYw-Bn.mjs.map +1 -0
  42. package/.output/server/chunks/build/{error-500-DhIQ-2yt.mjs → error-500-DIIFf55p.mjs} +10 -4
  43. package/.output/server/chunks/build/error-500-DIIFf55p.mjs.map +1 -0
  44. package/.output/server/chunks/build/error-500-styles.D1cs9hQy.mjs +8 -0
  45. package/.output/server/chunks/build/error-500-styles.D1cs9hQy.mjs.map +1 -0
  46. package/.output/server/chunks/build/index-CB1N4gax.mjs +557 -0
  47. package/.output/server/chunks/build/index-CB1N4gax.mjs.map +1 -0
  48. package/.output/server/chunks/build/server.mjs +326 -248
  49. package/.output/server/chunks/build/server.mjs.map +1 -1
  50. package/.output/server/chunks/build/styles.mjs +4 -4
  51. package/.output/server/chunks/nitro/nitro.mjs +2302 -835
  52. package/.output/server/chunks/nitro/nitro.mjs.map +1 -1
  53. package/.output/server/chunks/routes/api/editor-types.get.mjs +44 -0
  54. package/.output/server/chunks/routes/api/editor-types.get.mjs.map +1 -0
  55. package/.output/server/chunks/routes/api/parse.post.mjs +26 -1316
  56. package/.output/server/chunks/routes/api/parse.post.mjs.map +1 -1
  57. package/.output/server/chunks/routes/api/resolve.get.mjs +6 -0
  58. package/.output/server/chunks/routes/api/resolve.get.mjs.map +1 -1
  59. package/.output/server/chunks/routes/api/studio/run.post.mjs +35 -0
  60. package/.output/server/chunks/routes/api/studio/run.post.mjs.map +1 -0
  61. package/.output/server/chunks/routes/renderer.mjs +1 -1
  62. package/.output/server/chunks/routes/renderer.mjs.map +1 -1
  63. package/.output/server/index.mjs +7 -1
  64. package/.output/server/index.mjs.map +1 -1
  65. package/.output/server/node_modules/acorn/dist/acorn.mjs +6266 -0
  66. package/.output/server/node_modules/acorn/package.json +50 -0
  67. package/.output/server/node_modules/ip-address/dist/common.js +112 -4
  68. package/.output/server/node_modules/ip-address/dist/ipv4.js +322 -87
  69. package/.output/server/node_modules/ip-address/dist/ipv6.js +654 -199
  70. package/.output/server/node_modules/ip-address/dist/v4/constants.js +45 -2
  71. package/.output/server/node_modules/ip-address/dist/v6/constants.js +55 -3
  72. package/.output/server/node_modules/ip-address/dist/v6/helpers.js +12 -3
  73. package/.output/server/node_modules/ip-address/package.json +49 -37
  74. package/.output/server/node_modules/ufo/dist/index.mjs +2 -2
  75. package/.output/server/node_modules/ufo/package.json +9 -9
  76. package/.output/server/package.json +4 -3
  77. package/README.md +62 -19
  78. package/app/assets/css/main.css +1 -0
  79. package/app/assets/css/studio.css +131 -0
  80. package/app/components/StudioConversion.vue +41 -0
  81. package/app/components/StudioDataPanel.vue +21 -0
  82. package/app/components/StudioEditor.vue +78 -102
  83. package/app/components/StudioExpandButton.vue +11 -0
  84. package/app/components/StudioOutput.vue +7 -1
  85. package/app/components/StudioSourcePanel.vue +16 -0
  86. package/app/components/StudioValidation.vue +47 -0
  87. package/app/components/ZodMongooseStudio.vue +216 -198
  88. package/app/composables/useStudioRunner.ts +142 -0
  89. package/app/pages/index.vue +1 -1
  90. package/app/plugins/monaco.client.ts +2 -0
  91. package/bin/index.mjs +5 -0
  92. package/nuxt.config.ts +4 -3
  93. package/package.json +4 -2
  94. package/server/api/editor-types.get.ts +28 -0
  95. package/server/api/parse.post.ts +17 -175
  96. package/server/api/studio/run.post.ts +17 -0
  97. package/server/middleware/security.ts +29 -7
  98. package/server/utils/example-data.ts +80 -0
  99. package/server/utils/parse-request.ts +28 -0
  100. package/server/utils/runner-client.ts +40 -0
  101. package/server/utils/studio-execution.ts +176 -0
  102. package/.output/public/_nuxt/BD40YYqZ.js +0 -33
  103. package/.output/public/_nuxt/BlQmLjV4.js +0 -1
  104. package/.output/public/_nuxt/CJ4Cv9fY.js +0 -61
  105. package/.output/public/_nuxt/builds/meta/34871c14-b0f4-4898-9ff0-debaff743355.json +0 -1
  106. package/.output/public/_nuxt/error-404.64pZEiDn.css +0 -1
  107. package/.output/public/_nuxt/error-500.DHOpI0Ir.css +0 -1
  108. package/.output/public/_nuxt/rH_O4qXT.js +0 -1
  109. package/.output/server/chunks/build/error-404-BN-7rNE4.mjs.map +0 -1
  110. package/.output/server/chunks/build/error-404-styles.Byx46oLR.mjs +0 -8
  111. package/.output/server/chunks/build/error-404-styles.Byx46oLR.mjs.map +0 -1
  112. package/.output/server/chunks/build/error-500-DhIQ-2yt.mjs.map +0 -1
  113. package/.output/server/chunks/build/error-500-styles.BL3UT0Wa.mjs +0 -8
  114. package/.output/server/chunks/build/error-500-styles.BL3UT0Wa.mjs.map +0 -1
  115. package/.output/server/chunks/build/index-B4T6zHp0.mjs +0 -1904
  116. package/.output/server/chunks/build/index-B4T6zHp0.mjs.map +0 -1
  117. package/.output/server/node_modules/zod/index.js +0 -4
  118. /package/.output/public/_nuxt/{editor.CdBKkuhR.css → monaco.CdBKkuhR.css} +0 -0
@@ -1,1340 +1,50 @@
1
- import process from 'node:process';globalThis._importMeta_=globalThis._importMeta_||{url:"file:///_entry.js",env:process.env};import { d as defineEventHandler, u as useRuntimeConfig, r as readBody, c as createError } from '../../nitro/nitro.mjs';
2
- import vm from 'node:vm';
3
- import { transformSync } from 'esbuild';
4
- import util from 'node:util';
5
- import { fileURLToPath } from 'node:url';
6
- import { dirname } from 'node:path';
7
- import * as zod from 'zod';
8
- import * as mongoose from 'mongoose';
9
- import { z } from 'zod/v4';
1
+ import { d as defineEventHandler, u as useRuntimeConfig, c as createError, r as readStudioRequest, e as executeStudio, S as StudioExecutionError } from '../../nitro/nitro.mjs';
10
2
  import 'node:http';
3
+ import 'node:vm';
4
+ import 'esbuild';
5
+ import 'node:util';
6
+ import 'acorn';
7
+ import 'zod/v4';
8
+ import 'mongoose';
11
9
  import 'node:https';
12
10
  import 'node:events';
13
11
  import 'node:buffer';
14
12
  import 'node:fs';
13
+ import 'node:path';
15
14
  import 'node:crypto';
15
+ import 'node:url';
16
16
  import '@iconify/utils';
17
17
  import 'consola';
18
18
 
19
- var __defProp = Object.defineProperty;
20
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
21
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
- function flatHooks(configHooks, hooks2 = {}, parentName) {
23
- for (const key in configHooks) {
24
- const subHook = configHooks[key];
25
- const name = parentName ? `${parentName}:${key}` : key;
26
- if (typeof subHook === "object" && subHook !== null) flatHooks(subHook, hooks2, name);
27
- else if (typeof subHook === "function") hooks2[name] = subHook;
28
- }
29
- return hooks2;
30
- }
31
- const createTask = /* @__PURE__ */ (() => {
32
- if (console.createTask) return console.createTask;
33
- const defaultTask = { run: (fn) => fn() };
34
- return () => defaultTask;
35
- })();
36
- function callHooks(hooks2, args, startIndex, task) {
37
- for (let i = startIndex; i < hooks2.length; i += 1) try {
38
- const result = task ? task.run(() => hooks2[i](...args)) : hooks2[i](...args);
39
- if (result instanceof Promise) return result.then(() => callHooks(hooks2, args, i + 1, task));
40
- } catch (error) {
41
- return Promise.reject(error);
42
- }
43
- }
44
- function serialTaskCaller(hooks2, args, name) {
45
- if (hooks2.length > 0) return callHooks(hooks2, args, 0, createTask(name));
46
- }
47
- function parallelTaskCaller(hooks2, args, name) {
48
- if (hooks2.length > 0) {
49
- const task = createTask(name);
50
- return Promise.all(hooks2.map((hook) => task.run(() => hook(...args))));
51
- }
52
- }
53
- function callEachWith(callbacks, arg0) {
54
- for (const callback of [...callbacks]) callback(arg0);
55
- }
56
- var Hookable = class {
57
- constructor() {
58
- __publicField(this, "_hooks");
59
- __publicField(this, "_before");
60
- __publicField(this, "_after");
61
- __publicField(this, "_deprecatedHooks");
62
- __publicField(this, "_deprecatedMessages");
63
- this._hooks = {};
64
- this._before = void 0;
65
- this._after = void 0;
66
- this._deprecatedMessages = void 0;
67
- this._deprecatedHooks = {};
68
- this.hook = this.hook.bind(this);
69
- this.callHook = this.callHook.bind(this);
70
- this.callHookWith = this.callHookWith.bind(this);
71
- }
72
- hook(name, function_, options = {}) {
73
- if (!name || typeof function_ !== "function") return () => {
74
- };
75
- const originalName = name;
76
- let dep;
77
- while (this._deprecatedHooks[name]) {
78
- dep = this._deprecatedHooks[name];
79
- name = dep.to;
80
- }
81
- if (dep && !options.allowDeprecated) {
82
- let message = dep.message;
83
- if (!message) message = `${originalName} hook has been deprecated` + (dep.to ? `, please use ${dep.to}` : "");
84
- if (!this._deprecatedMessages) this._deprecatedMessages = /* @__PURE__ */ new Set();
85
- if (!this._deprecatedMessages.has(message)) {
86
- console.warn(message);
87
- this._deprecatedMessages.add(message);
88
- }
89
- }
90
- if (!function_.name) try {
91
- Object.defineProperty(function_, "name", {
92
- get: () => "_" + name.replace(/\W+/g, "_") + "_hook_cb",
93
- configurable: true
94
- });
95
- } catch {
96
- }
97
- this._hooks[name] = this._hooks[name] || [];
98
- this._hooks[name].push(function_);
99
- return () => {
100
- if (function_) {
101
- this.removeHook(name, function_);
102
- function_ = void 0;
103
- }
104
- };
105
- }
106
- hookOnce(name, function_) {
107
- let _unreg;
108
- let _function = (...arguments_) => {
109
- if (typeof _unreg === "function") _unreg();
110
- _unreg = void 0;
111
- _function = void 0;
112
- return function_(...arguments_);
113
- };
114
- _unreg = this.hook(name, _function);
115
- return _unreg;
116
- }
117
- removeHook(name, function_) {
118
- const hooks2 = this._hooks[name];
119
- if (hooks2) {
120
- const index = hooks2.indexOf(function_);
121
- if (index !== -1) hooks2.splice(index, 1);
122
- if (hooks2.length === 0) this._hooks[name] = void 0;
123
- }
124
- }
125
- clearHook(name) {
126
- this._hooks[name] = void 0;
127
- }
128
- deprecateHook(name, deprecated) {
129
- this._deprecatedHooks[name] = typeof deprecated === "string" ? { to: deprecated } : deprecated;
130
- const _hooks = this._hooks[name] || [];
131
- this._hooks[name] = void 0;
132
- for (const hook of _hooks) this.hook(name, hook);
133
- }
134
- deprecateHooks(deprecatedHooks) {
135
- for (const name in deprecatedHooks) this.deprecateHook(name, deprecatedHooks[name]);
136
- }
137
- addHooks(configHooks) {
138
- const hooks2 = flatHooks(configHooks);
139
- const removeFns = Object.keys(hooks2).map((key) => this.hook(key, hooks2[key]));
140
- return () => {
141
- for (const unreg of removeFns) unreg();
142
- removeFns.length = 0;
143
- };
144
- }
145
- removeHooks(configHooks) {
146
- const hooks2 = flatHooks(configHooks);
147
- for (const key in hooks2) this.removeHook(key, hooks2[key]);
148
- }
149
- removeAllHooks() {
150
- this._hooks = {};
151
- }
152
- callHook(name, ...args) {
153
- return this.callHookWith(serialTaskCaller, name, args);
154
- }
155
- callHookParallel(name, ...args) {
156
- return this.callHookWith(parallelTaskCaller, name, args);
157
- }
158
- callHookWith(caller, name, args) {
159
- const event = this._before || this._after ? {
160
- name,
161
- args,
162
- context: {}
163
- } : void 0;
164
- if (this._before) callEachWith(this._before, event);
165
- const result = caller(this._hooks[name] ? [...this._hooks[name]] : [], args, name);
166
- if (result instanceof Promise) return result.finally(() => {
167
- if (this._after && event) callEachWith(this._after, event);
168
- });
169
- if (this._after && event) callEachWith(this._after, event);
170
- return result;
171
- }
172
- beforeEach(function_) {
173
- this._before = this._before || [];
174
- this._before.push(function_);
175
- return () => {
176
- if (this._before !== void 0) {
177
- const index = this._before.indexOf(function_);
178
- if (index !== -1) this._before.splice(index, 1);
179
- }
180
- };
181
- }
182
- afterEach(function_) {
183
- this._after = this._after || [];
184
- this._after.push(function_);
185
- return () => {
186
- if (this._after !== void 0) {
187
- const index = this._after.indexOf(function_);
188
- if (index !== -1) this._after.splice(index, 1);
189
- }
190
- };
191
- }
192
- };
193
- function createHooks() {
194
- return new Hookable();
195
- }
196
- const hooks = createHooks();
197
- function callHookSync(name, ...args) {
198
- hooks.callHookWith((callbacks, args2) => {
199
- for (const callback of callbacks) {
200
- callback(...args2);
201
- }
202
- }, name, args);
203
- }
204
- const mongooseRegistry = z.registry();
205
- function withMongoose(schema, meta = {}) {
206
- callHookSync("registry:get:before", { schema });
207
- const existing = mongooseRegistry.get(schema) || {};
208
- callHookSync("registry:get", { schema, meta: existing });
209
- const merged = { ...existing, ...meta };
210
- callHookSync("registry:add", { schema, meta: merged });
211
- mongooseRegistry.add(schema, merged);
212
- callHookSync("registry:added", { schema, meta: merged });
213
- return schema;
214
- }
215
- function getMongooseMeta(schema) {
216
- const def = schema._def;
217
- if (!def)
218
- return {};
219
- let meta = mongooseRegistry.get(schema) || {};
220
- if (def.innerType) {
221
- meta = { ...getMongooseMeta(def.innerType), ...meta };
222
- } else if (def.schema) {
223
- meta = { ...getMongooseMeta(def.schema), ...meta };
224
- }
225
- if (def.type === "pipe") {
226
- meta = { ...getMongooseMeta(def.in), ...getMongooseMeta(def.out), ...meta };
227
- }
228
- return meta;
229
- }
230
- function unwrapZodSchema(schema, features = { required: true }, visited = /* @__PURE__ */ new Set()) {
231
- var _a, _b, _c, _d, _e;
232
- if (!schema)
233
- return { schema, features };
234
- if (visited.has(schema))
235
- return { schema, features };
236
- const def = schema._def;
237
- if (!def)
238
- return { schema, features };
239
- if (!(schema instanceof z.ZodOptional) && !(schema instanceof z.ZodNullable) && !(schema instanceof z.ZodDefault) && def.type !== "pipe") {
240
- visited.add(schema);
241
- }
242
- if (schema instanceof z.ZodOptional) {
243
- const inner = schema.unwrap();
244
- return unwrapZodSchema(
245
- // @ts-expect-error Zod v4 schema.unwrap() return type mismatch
246
- inner,
247
- {
248
- ...features,
249
- required: false,
250
- isOptional: true
251
- },
252
- visited
253
- );
254
- }
255
- if (schema instanceof z.ZodNullable) {
256
- return unwrapZodSchema(
257
- // @ts-expect-error Zod v4 schema.unwrap() return type mismatch
258
- schema.unwrap(),
259
- {
260
- ...features,
261
- isNullable: true
262
- },
263
- visited
264
- );
265
- }
266
- if (schema instanceof z.ZodDefault) {
267
- const defaultValue = typeof def.defaultValue === "function" ? def.defaultValue() : def.defaultValue;
268
- return unwrapZodSchema(def.innerType, {
269
- ...features,
270
- default: defaultValue
271
- }, visited);
272
- }
273
- const { type } = def;
274
- if (type === "pipe") {
275
- const inType = (_b = (_a = def.in) == null ? void 0 : _a._def) == null ? void 0 : _b.type;
276
- const outType = (_d = (_c = def.out) == null ? void 0 : _c._def) == null ? void 0 : _d.type;
277
- if (inType === "transform") {
278
- return unwrapZodSchema(def.out, features, visited);
279
- }
280
- if (outType === "transform" || outType === "refinement") {
281
- const transformFeatures = { ...features };
282
- const outDef = (_e = def.out) == null ? void 0 : _e._def;
283
- const effects = (outDef == null ? void 0 : outDef.effects) || (outDef == null ? void 0 : outDef.transformations) || (outType === "transform" ? [outDef] : []);
284
- if (effects && Array.isArray(effects)) {
285
- transformFeatures.transformations = [
286
- ...transformFeatures.transformations || [],
287
- ...effects
288
- ];
289
- }
290
- return unwrapZodSchema(def.in, transformFeatures, visited);
291
- }
292
- return unwrapZodSchema(def.out, features, visited);
293
- }
294
- if (type === "transform" || type === "preprocess" || type === "refinement" || type === "effects") {
295
- const transformFeatures = { ...features };
296
- const effects = def.effects || def.transformations || (def.type === "transform" || type === "transform" ? [def] : []);
297
- if (effects && Array.isArray(effects)) {
298
- transformFeatures.transformations = [
299
- ...transformFeatures.transformations || [],
300
- ...effects
301
- ];
302
- }
303
- const inner = def.schema || def.innerType;
304
- if (inner) {
305
- const result = unwrapZodSchema(inner, transformFeatures, visited);
306
- return result;
307
- }
308
- }
309
- if (type === "lazy") {
310
- return { schema, features };
311
- }
312
- if (type === "branded" || type === "readonly") {
313
- return unwrapZodSchema(schema.unwrap(), {
314
- ...features,
315
- ...type === "readonly" ? { readOnly: true } : {}
316
- }, visited);
317
- }
318
- if (def.checks && Array.isArray(def.checks)) {
319
- features.checks = [...features.checks || [], ...def.checks];
320
- }
321
- return { schema, features };
322
- }
323
- let mongooseInstance = null;
324
- let isFrontend;
325
- const setFrontendMode = (enabled) => {
326
- console.warn("[zod-mongoose] setFrontendMode() is deprecated and will be removed in v4. Conditional exports select the appropriate implementation automatically.");
327
- isFrontend = enabled;
328
- };
329
- const getFrontendMode = () => {
330
- if (isFrontend === void 0 || isFrontend === null) {
331
- return globalThis.window !== void 0 && globalThis.document !== void 0;
332
- }
333
- return isFrontend;
334
- };
335
- const setMongoose = (m) => {
336
- mongooseInstance = m;
337
- };
338
- const getMongoose = () => {
339
- var _a;
340
- if (getFrontendMode()) {
341
- return null;
342
- }
343
- if (mongooseInstance) {
344
- return mongooseInstance;
345
- }
346
- try {
347
- if (typeof require !== "undefined") {
348
- const m = require("mongoose");
349
- if (m && (m.Schema || ((_a = m.default) == null ? void 0 : _a.Schema))) {
350
- return m.default || m;
351
- }
352
- return m;
353
- }
354
- return null;
355
- } catch {
356
- if (globalThis.mongoose) {
357
- return globalThis.mongoose;
358
- }
359
- return null;
360
- }
361
- };
362
- function mapZodChecksToMongoose(checks, mongooseProp) {
363
- var _a, _b;
364
- if (!checks || !Array.isArray(checks))
365
- return;
366
- for (const check of checks) {
367
- const traitSet = (_a = check._zod) == null ? void 0 : _a.traits;
368
- const checkDef = (_b = check._zod) == null ? void 0 : _b.def;
369
- if (!traitSet || !checkDef)
370
- continue;
371
- if (traitSet.has("$ZodCheckMinLength")) {
372
- mongooseProp.minlength = checkDef.minimum;
373
- }
374
- if (traitSet.has("$ZodCheckMaxLength")) {
375
- mongooseProp.maxlength = checkDef.maximum;
376
- }
377
- if (traitSet.has("$ZodCheckLengthEquals")) {
378
- mongooseProp.minlength = checkDef.length;
379
- mongooseProp.maxlength = checkDef.length;
380
- }
381
- if (traitSet.has("$ZodCheckGreaterThan")) {
382
- mongooseProp.min = checkDef.value;
383
- }
384
- if (traitSet.has("$ZodCheckLessThan")) {
385
- mongooseProp.max = checkDef.value;
386
- }
387
- if (traitSet.has("$ZodCheckRegex")) {
388
- mongooseProp.match = checkDef.pattern;
389
- }
390
- if (traitSet.has("$ZodUUID")) {
391
- const mongoose = globalThis.mongoose || globalThis.__mongoose;
392
- if (mongoose == null ? void 0 : mongoose.Schema.Types.UUID) {
393
- mongooseProp.type = mongoose.Schema.Types.UUID;
394
- }
395
- }
396
- if (traitSet.has("$ZodISODateTime") || traitSet.has("$ZodISODate")) {
397
- mongooseProp.type = Date;
398
- }
399
- if (traitSet.has("$ZodCheckOverwrite") && typeof checkDef.tx === "function") {
400
- const txStr = checkDef.tx.toString();
401
- if (txStr.includes(".trim()")) {
402
- mongooseProp.trim = true;
403
- } else if (txStr.includes(".toLowerCase()")) {
404
- mongooseProp.lowercase = true;
405
- } else if (txStr.includes(".toUpperCase()")) {
406
- mongooseProp.uppercase = true;
407
- }
408
- }
409
- }
410
- callHookSync("validation:mappers", { checks, mongooseProp });
411
- }
412
- function handleObject(unwrapped, mongooseProp, visited, extractMongooseDef2, isField = false) {
413
- var _a;
414
- callHookSync("schema:object:before", { schema: unwrapped, mongooseProp, visited });
415
- const { shape } = unwrapped;
416
- const objDef = {};
417
- const placeholder = mongooseProp.type ? mongooseProp : objDef;
418
- visited.set(unwrapped, placeholder);
419
- for (const key in shape) {
420
- if (!Object.prototype.hasOwnProperty.call(shape, key))
421
- continue;
422
- if (key === "_id") {
423
- const idMeta = mongooseRegistry.get(shape[key]) || {};
424
- const unwrappedId = unwrapZodSchema(shape[key]).schema;
425
- const unwrappedIdMeta = mongooseRegistry.get(unwrappedId) || {};
426
- if (idMeta.includeId !== true && unwrappedIdMeta.includeId !== true && mongooseProp.includeId !== true) {
427
- continue;
428
- }
429
- }
430
- const def = extractMongooseDef2(shape[key], visited);
431
- if (def && typeof def === "object" && def.__isDiscriminatorUnion) {
432
- const mongoose = getMongoose();
433
- if (mongoose) {
434
- const baseSchema = new mongoose.Schema(def.baseDef, {
435
- discriminatorKey: def.discriminatorKey,
436
- _id: false
437
- });
438
- const discriminators = {};
439
- for (const [dKey, dDef] of Object.entries(def.discriminators)) {
440
- discriminators[dKey] = new mongoose.Schema(dDef, { _id: false });
441
- }
442
- objDef[key] = {
443
- type: baseSchema,
444
- discriminators
445
- };
446
- } else {
447
- objDef[key] = def;
448
- }
449
- } else if (typeof def === "object" && def !== null && !Array.isArray(def)) {
450
- const { includeId, ...cleanDef } = def;
451
- objDef[key] = cleanDef;
452
- } else {
453
- objDef[key] = def;
454
- }
455
- callHookSync("schema:object:field", { key, schema: shape[key], objDef, visited });
456
- }
457
- let result;
458
- const shouldBeSubSchema = isField && mongooseProp.schema !== false;
459
- if (shouldBeSubSchema && !mongooseProp.type) {
460
- const mongoose = getMongoose();
461
- if (mongoose) {
462
- const options = typeof mongooseProp.schema === "object" ? mongooseProp.schema : {};
463
- const { plugins, ...schemaOptions } = options;
464
- const subSchema = new mongoose.Schema(objDef, schemaOptions);
465
- if (plugins && Array.isArray(plugins)) {
466
- for (const plugin of plugins) {
467
- subSchema.plugin(plugin);
468
- }
469
- }
470
- mongooseProp.type = subSchema;
471
- }
472
- }
473
- if (mongooseProp.type) {
474
- const mongoose = getMongoose();
475
- const isSchema = mongoose && (mongooseProp.type instanceof mongoose.Schema || ((_a = mongooseProp.type.constructor) == null ? void 0 : _a.name) === "Schema");
476
- if (!isSchema) {
477
- Object.assign(mongooseProp, objDef);
478
- }
479
- result = mongooseProp;
480
- } else {
481
- Object.assign(mongooseProp, objDef);
482
- const topLevelOptions = /* @__PURE__ */ new Set([
483
- "collection",
484
- "versionKey",
485
- "timestamps",
486
- "discriminatorKey",
487
- "strict",
488
- "id",
489
- "_id",
490
- "minimize",
491
- "validateBeforeSave",
492
- "schema"
493
- ]);
494
- const hasFieldMetadata = Object.keys(mongooseProp).some((k) => {
495
- if (Object.prototype.hasOwnProperty.call(objDef, k))
496
- return false;
497
- if (topLevelOptions.has(k))
498
- return false;
499
- if (k === "required" && mongooseProp[k] === false)
500
- return false;
501
- return true;
502
- });
503
- result = hasFieldMetadata ? mongooseProp : objDef;
504
- }
505
- callHookSync("schema:object:after", { schema: unwrapped, mongooseProp, objDef, result });
506
- return result;
507
- }
508
- function handleArray(unwrapped, mongooseProp, visited, extractMongooseDef2) {
509
- var _a;
510
- callHookSync("schema:array:before", { schema: unwrapped, mongooseProp, visited });
511
- const element = unwrapped.element || unwrapped._def.valueType || unwrapped._def.rest || ((_a = unwrapped._def.items) == null ? void 0 : _a[0]);
512
- const mongoose = getMongoose();
513
- const innerDef = element ? extractMongooseDef2(element, visited) : (mongoose == null ? void 0 : mongoose.Schema.Types.Mixed) || "Mixed";
514
- if (!mongooseProp.type) {
515
- if (innerDef && typeof innerDef === "object" && innerDef.__isDiscriminatorUnion && mongoose) {
516
- const discriminators = {};
517
- for (const [dKey, dDef] of Object.entries(innerDef.discriminators)) {
518
- discriminators[dKey] = new mongoose.Schema(dDef, { _id: false });
519
- }
520
- mongooseProp.type = [
521
- new mongoose.Schema({}, {
522
- discriminatorKey: innerDef.discriminatorKey,
523
- _id: false
524
- })
525
- ];
526
- mongooseProp.discriminators = discriminators;
527
- } else {
528
- const innerType = innerDef.type || innerDef;
529
- mongooseProp.type = [innerType];
530
- if (typeof innerDef === "object") {
531
- const { type: _extractedType, ...innerMeta } = innerDef;
532
- Object.assign(mongooseProp, innerMeta);
533
- mongooseProp.type = [innerType];
534
- }
535
- }
536
- }
537
- callHookSync("schema:array:after", { schema: unwrapped, mongooseProp, innerDef });
538
- }
539
- function handleRecord(unwrapped, mongooseProp, visited, extractMongooseDef2) {
540
- var _a, _b;
541
- callHookSync("schema:record:before", { schema: unwrapped, mongooseProp, visited });
542
- const type = (_a = unwrapped._def) == null ? void 0 : _a.type;
543
- const isMap = type === "map";
544
- const valueType = unwrapped.valueType || unwrapped.valueSchema || unwrapped._def.valueType || unwrapped._def.valueSchema || unwrapped._def.innerType;
545
- let innerDef;
546
- if (!mongooseProp.type || mongooseProp.type === Map || mongooseProp.type === Object) {
547
- mongooseProp.type = isMap ? Map : Object;
548
- const finalValueType = valueType || unwrapped.valueSchema || ((_b = unwrapped._def) == null ? void 0 : _b.valueSchema);
549
- if (finalValueType) {
550
- innerDef = extractMongooseDef2(finalValueType, visited);
551
- mongooseProp.of = innerDef.type || innerDef;
552
- }
553
- }
554
- callHookSync("schema:record:after", { schema: unwrapped, mongooseProp, innerDef });
555
- }
556
- function areDefinitionsEqual(left, right, seen = /* @__PURE__ */ new WeakMap()) {
557
- if (left === right)
558
- return true;
559
- if (left === null || right === null || typeof left !== "object" || typeof right !== "object") {
560
- return false;
561
- }
562
- const mongoose = getMongoose();
563
- const leftIsSchema = mongoose && left instanceof mongoose.Schema;
564
- const rightIsSchema = mongoose && right instanceof mongoose.Schema;
565
- if (leftIsSchema || rightIsSchema) {
566
- return Boolean(leftIsSchema && rightIsSchema && areDefinitionsEqual(left.obj, right.obj, seen));
567
- }
568
- let seenRight = seen.get(left);
569
- if (seenRight == null ? void 0 : seenRight.has(right))
570
- return true;
571
- if (!seenRight) {
572
- seenRight = /* @__PURE__ */ new WeakSet();
573
- seen.set(left, seenRight);
574
- }
575
- seenRight.add(right);
576
- if (Array.isArray(left) || Array.isArray(right)) {
577
- return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => areDefinitionsEqual(value, right[index], seen));
578
- }
579
- const leftKeys = Object.keys(left);
580
- const rightKeys = Object.keys(right);
581
- return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && areDefinitionsEqual(left[key], right[key], seen));
582
- }
583
- function extractMongooseDef(schema, visited = /* @__PURE__ */ new Map(), isField = false, noWrap = false) {
584
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
585
- if (visited.size === 0) {
586
- callHookSync("converter:before", { schema, visited });
587
- }
588
- callHookSync("converter:start", { schema, visited });
589
- const { schema: unwrapped, features } = unwrapZodSchema(schema);
590
- const meta = mongooseRegistry.get(schema) || {};
591
- const mongooseProp = getMongooseMeta(schema);
592
- callHookSync("converter:unwrapped", {
593
- schema,
594
- unwrapped,
595
- features,
596
- meta: mongooseProp,
597
- mongooseProp
598
- });
599
- if (features.isOptional === true && mongooseProp.type && mongooseProp.required !== true) {
600
- mongooseProp.required = false;
601
- }
602
- if (visited.has(schema)) {
603
- const existing = visited.get(schema);
604
- if (existing === mongooseProp) {
605
- return existing;
606
- }
607
- if (Object.keys(meta).length > 0) {
608
- Object.assign(existing, mongooseProp);
609
- }
610
- return existing;
611
- }
612
- visited.set(schema, mongooseProp);
613
- if (features.default !== void 0) {
614
- mongooseProp.default = features.default;
615
- }
616
- if (features.required === false) {
617
- mongooseProp.required = false;
618
- }
619
- if (features.readOnly === true) {
620
- mongooseProp.readOnly = true;
621
- }
622
- mapZodChecksToMongoose(features.checks, mongooseProp);
623
- const def = unwrapped._def;
624
- if (!def) {
625
- callHookSync("converter:after", {
626
- schema,
627
- mongooseProp
628
- });
629
- return mongooseProp;
630
- }
631
- const { type } = def;
632
- callHookSync("converter:node", {
633
- schema: unwrapped,
634
- mongooseProp,
635
- type
636
- });
637
- if (type === "object") {
638
- const wrapperFn = (s, v) => extractMongooseDef(s, v, true);
639
- const result = handleObject(unwrapped, mongooseProp, visited, wrapperFn, isField && !noWrap);
640
- callHookSync("converter:after", {
641
- schema,
642
- mongooseProp: result
643
- });
644
- if (typeof result === "object" && result !== null && !Array.isArray(result)) {
645
- delete result.includeId;
646
- }
647
- return result;
648
- }
649
- if (type === "array" || type === "set" || type === "tuple") {
650
- handleArray(unwrapped, mongooseProp, visited, (s, v) => extractMongooseDef(s, v, true));
651
- }
652
- if (type === "record" || type === "map") {
653
- handleRecord(unwrapped, mongooseProp, visited, (s, v) => extractMongooseDef(s, v, true));
654
- }
655
- if (type === "intersection") {
656
- const left = extractMongooseDef(unwrapped._def.left, visited, isField, true);
657
- const right = extractMongooseDef(unwrapped._def.right, visited, isField, true);
658
- if (typeof left === "object" && typeof right === "object") {
659
- Object.assign(mongooseProp, left, right);
660
- if (isField && !noWrap && mongooseProp.schema !== false && !mongooseProp.type) {
661
- const mongoose = getMongoose();
662
- if (mongoose) {
663
- const options = typeof mongooseProp.schema === "object" ? mongooseProp.schema : {};
664
- const { plugins, ...schemaOptions } = options;
665
- const definition = { ...mongooseProp };
666
- delete definition.schema;
667
- const subSchema = new mongoose.Schema(definition, schemaOptions);
668
- if (plugins && Array.isArray(plugins)) {
669
- for (const plugin of plugins) {
670
- subSchema.plugin(plugin);
671
- }
672
- }
673
- mongooseProp.type = subSchema;
674
- for (const key of Object.keys(mongooseProp)) {
675
- if (key !== "type")
676
- delete mongooseProp[key];
677
- }
678
- }
679
- }
680
- } else if (!mongooseProp.type) {
681
- mongooseProp.type = ((_a = getMongoose()) == null ? void 0 : _a.Schema.Types.Mixed) || "Mixed";
682
- }
683
- }
684
- if ((type === "union" || type === "discriminatedunion" || type === "discriminated_union" || type === "xor") && !mongooseProp.type) {
685
- const mongoose = getMongoose();
686
- const options = unwrapped.options || unwrapped._def.options;
687
- const discriminatorKey = unwrapped._def.discriminator;
688
- const unionCtx = {
689
- isSimpleUnion: false,
690
- isObjectUnion: false,
691
- isXor: type === "xor" || (((_b = unwrapped._def) == null ? void 0 : _b.inclusive) === false || ((_c = schema._def) == null ? void 0 : _c.inclusive) === false) && !discriminatorKey && !((_d = schema._def) == null ? void 0 : _d.discriminator)
692
- };
693
- if (Array.isArray(options) && options.length > 0) {
694
- unionCtx.isSimpleUnion = options.every((opt) => {
695
- const { type: type2 } = unwrapZodSchema(opt).schema._def;
696
- return ["string", "number", "boolean", "date", "bigint", "literal"].includes(type2);
697
- });
698
- unionCtx.isObjectUnion = options.every((opt) => {
699
- const { type: type2 } = unwrapZodSchema(opt).schema._def;
700
- return type2 === "object";
701
- });
702
- }
703
- callHookSync("schema:union:before", { schema: unwrapped, mongooseProp, ctx: unionCtx });
704
- if (discriminatorKey && unionCtx.isObjectUnion) {
705
- const discriminators = {};
706
- const allOptionDefs = [];
707
- for (const option of options) {
708
- const { schema: unwrappedOpt } = unwrapZodSchema(option);
709
- const { shape } = unwrappedOpt._def;
710
- const discriminatorProp = shape[discriminatorKey];
711
- const { schema: unwrappedDisc } = unwrapZodSchema(discriminatorProp);
712
- const discriminatorValue = (_f = unwrappedDisc._def.value) != null ? _f : (_e = unwrappedDisc._def.values) == null ? void 0 : _e[0];
713
- const optionDef = extractMongooseDef(option, /* @__PURE__ */ new Map(), true, true);
714
- if (optionDef && typeof optionDef === "object" && !Array.isArray(optionDef)) {
715
- const cleanOptionDef = { ...optionDef };
716
- delete cleanOptionDef[discriminatorKey];
717
- discriminators[discriminatorValue] = cleanOptionDef;
718
- allOptionDefs.push(cleanOptionDef);
719
- }
720
- }
721
- const baseDef = {};
722
- if (allOptionDefs.length > 0) {
723
- const firstOption = allOptionDefs[0];
724
- for (const key of Object.keys(firstOption)) {
725
- const isCommon = allOptionDefs.every((def2) => {
726
- if (!(key in def2))
727
- return false;
728
- return areDefinitionsEqual(def2[key], firstOption[key]);
729
- });
730
- if (isCommon) {
731
- baseDef[key] = firstOption[key];
732
- for (const def2 of allOptionDefs) {
733
- delete def2[key];
734
- }
735
- }
736
- }
737
- }
738
- const result = {
739
- __isDiscriminatorUnion: true,
740
- discriminatorKey,
741
- discriminators,
742
- baseDef,
743
- validate: {
744
- validator(_v) {
745
- var _a2, _b2;
746
- try {
747
- const mongoose2 = getMongoose();
748
- const doc = mongoose2 && this instanceof mongoose2.Document ? this.toObject() : this || {};
749
- schema.parse(doc);
750
- return true;
751
- } catch (err) {
752
- const message = ((_b2 = (_a2 = err == null ? void 0 : err.errors) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.message) || err.message;
753
- if (this && typeof this.invalidate === "function") {
754
- this.invalidate(discriminatorKey, `Zod validation failed: ${message}`);
755
- }
756
- return false;
757
- }
758
- },
759
- message: (props) => `Validation failed for ${props.path}`
760
- }
761
- };
762
- if (mongooseProp && typeof mongooseProp === "object" && !Array.isArray(mongooseProp)) {
763
- Object.assign(mongooseProp, result);
764
- callHookSync("schema:union:after", {
765
- schema: unwrapped,
766
- mongooseProp,
767
- ctx: unionCtx
768
- });
769
- return mongooseProp;
770
- }
771
- callHookSync("schema:union:after", {
772
- schema: unwrapped,
773
- mongooseProp: result,
774
- ctx: unionCtx
775
- });
776
- return result;
777
- }
778
- if (((_g = getMongoose()) == null ? void 0 : _g.Schema.Types.Union) && unionCtx.isSimpleUnion && options.length > 0 && !unionCtx.isXor) {
779
- mongooseProp.type = mongoose.Schema.Types.Union;
780
- mongooseProp.of = options.map((opt) => {
781
- const def2 = extractMongooseDef(opt, visited, true, true);
782
- return def2.type || def2;
783
- });
784
- } else if (unionCtx.isObjectUnion && options.length > 0) {
785
- const mergedDef = {};
786
- for (const opt of options) {
787
- const def2 = extractMongooseDef(opt, /* @__PURE__ */ new Map(), true, true);
788
- if (typeof def2 === "object" && def2 !== null) {
789
- for (const [key, prop] of Object.entries(def2)) {
790
- if (typeof prop === "object" && prop !== null && !Array.isArray(prop)) {
791
- prop.required = false;
792
- }
793
- if (mergedDef[key] && typeof mergedDef[key] === "object" && typeof prop === "object" && !Array.isArray(mergedDef[key]) && !Array.isArray(prop)) {
794
- const existingType = mergedDef[key].type || mergedDef[key].instance || (typeof mergedDef[key] === "function" ? mergedDef[key] : null);
795
- const newType = prop.type || prop.instance || (typeof prop === "function" ? prop : null);
796
- const isMixed = (t) => {
797
- var _a2, _b2;
798
- return !t || t === "Mixed" || t === "SchemaMixed" || (t == null ? void 0 : t.name) === "Mixed" || (t == null ? void 0 : t.instance) === "Mixed" || (t == null ? void 0 : t.name) === "SchemaMixed" || (t == null ? void 0 : t.instance) === "SchemaMixed" || ((_a2 = getMongoose()) == null ? void 0 : _a2.Schema.Types.Mixed) && (t === ((_b2 = getMongoose()) == null ? void 0 : _b2.Schema.Types.Mixed) || (t == null ? void 0 : t.instance) === "Mixed" || (t == null ? void 0 : t.instance) === "SchemaMixed");
799
- };
800
- if (isMixed(existingType) && !isMixed(newType)) {
801
- mergedDef[key] = prop;
802
- } else if (!isMixed(existingType) && isMixed(newType)) ;
803
- else {
804
- Object.assign(mergedDef[key], prop);
805
- }
806
- } else if (!mergedDef[key] || typeof mergedDef[key] !== "object" || Array.isArray(mergedDef[key])) {
807
- mergedDef[key] = prop;
808
- }
809
- }
810
- }
811
- }
812
- if (isField && unionCtx.isXor) {
813
- mongooseProp.type = (mongoose == null ? void 0 : mongoose.Schema.Types.Mixed) || "Mixed";
814
- mongooseProp.validate = {
815
- validator(v) {
816
- try {
817
- schema.parse(v);
818
- return true;
819
- } catch {
820
- return false;
821
- }
822
- },
823
- message: "XOR validation failed"
824
- };
825
- } else {
826
- if (!mongooseProp.type || mongooseProp.type === (((_h = getMongoose()) == null ? void 0 : _h.Schema.Types.Mixed) || "Mixed")) {
827
- delete mongooseProp.type;
828
- }
829
- Object.assign(mongooseProp, mergedDef);
830
- if (isField && Object.prototype.hasOwnProperty.call(mongooseProp, "type") && Object.keys(mongooseProp).length > 1) {
831
- const mongooseInstance3 = getMongoose();
832
- if (mongooseInstance3) {
833
- mongooseProp.type = new mongooseInstance3.Schema(mongooseProp, { _id: false });
834
- for (const key of Object.keys(mongooseProp)) {
835
- if (key !== "type")
836
- delete mongooseProp[key];
837
- }
838
- }
839
- }
840
- }
841
- } else {
842
- mongooseProp.type = (mongoose == null ? void 0 : mongoose.Schema.Types.Mixed) || "Mixed";
843
- if (isField && (type === "xor" || type === "discriminated_union" || type === "discriminatedunion" || type === "union") && !mongooseProp.ref && // Skip Zod validation for populated fields
844
- !Array.isArray(mongooseProp.type) && // Skip Zod validation for arrays
845
- mongooseProp.type !== Map && // Skip Zod validation for maps
846
- !mongooseProp.of) {
847
- mongooseProp.validate = {
848
- validator(v) {
849
- try {
850
- schema.parse(v);
851
- return true;
852
- } catch (err) {
853
- return false;
854
- }
855
- },
856
- message: (props) => {
857
- if (unionCtx.isXor)
858
- return "XOR validation failed";
859
- try {
860
- schema.parse(props.value);
861
- } catch (err) {
862
- return `Union validation failed: ${err.message}`;
863
- }
864
- return "Union validation failed";
865
- }
866
- };
867
- }
868
- }
869
- callHookSync("schema:union:after", {
870
- schema: unwrapped,
871
- mongooseProp,
872
- ctx: unionCtx
873
- });
874
- }
875
- if (type === "literal" && !mongooseProp.type) {
876
- mongooseProp.type = ((_i = getMongoose()) == null ? void 0 : _i.Schema.Types.Mixed) || "Mixed";
877
- }
878
- switch (type) {
879
- case "string":
880
- case "number":
881
- case "boolean":
882
- case "date":
883
- case "bigint":
884
- case "stringbool":
885
- case "boolstring":
886
- case "booleanstring": {
887
- if (!mongooseProp.type) {
888
- if (type === "bigint") {
889
- mongooseProp.type = typeof BigInt === "undefined" ? Number : BigInt;
890
- } else {
891
- const typeMap = {
892
- string: String,
893
- number: Number,
894
- boolean: Boolean,
895
- date: Date,
896
- stringbool: Boolean,
897
- boolstring: Boolean,
898
- booleanstring: Boolean
899
- };
900
- mongooseProp.type = typeMap[type];
901
- if (mongooseProp.default !== void 0) {
902
- const defaultType = typeof mongooseProp.default;
903
- if (defaultType === "boolean" && type !== "boolean") {
904
- mongooseProp.type = Boolean;
905
- } else if (defaultType === "number" && type !== "number") {
906
- mongooseProp.type = Number;
907
- } else if (defaultType === "string" && type !== "string") {
908
- mongooseProp.type = String;
909
- } else if (mongooseProp.default instanceof Date && type !== "date") {
910
- mongooseProp.type = Date;
911
- }
912
- }
913
- if (mongooseProp.type === String && features.transformations) {
914
- for (const tx of features.transformations) {
915
- const txStr = ((_j = tx.transform) == null ? void 0 : _j.toString()) || tx.toString();
916
- if (txStr.includes("stringbool") || txStr.includes("boolstring") || txStr.includes("booleanstring")) {
917
- mongooseProp.type = Boolean;
918
- break;
919
- }
920
- if (txStr.includes('=== "true"') || txStr.includes("=== 'true'")) {
921
- mongooseProp.type = Boolean;
922
- break;
923
- }
924
- }
925
- }
926
- }
927
- }
928
- if (mongooseProp.required !== false)
929
- mongooseProp.required = true;
930
- break;
931
- }
932
- case "enum":
933
- case "nativeenum":
934
- case "native_enum": {
935
- if (!mongooseProp.type)
936
- mongooseProp.type = String;
937
- mongooseProp.enum = type === "enum" ? unwrapped.options || def.values : Object.values(unwrapped.enum || def.values);
938
- if (mongooseProp.required !== false)
939
- mongooseProp.required = true;
940
- break;
941
- }
942
- }
943
- const mongooseInstance2 = getMongoose();
944
- if (type === "any" || type === "unknown" || type === "custom") {
945
- const cls = def.cls || unwrapped.cls;
946
- if (cls === Buffer || typeof Uint8Array !== "undefined" && cls === Uint8Array) {
947
- if (!mongooseProp.type)
948
- mongooseProp.type = (mongooseInstance2 == null ? void 0 : mongooseInstance2.Schema.Types.Buffer) || "Buffer";
949
- } else if (((cls == null ? void 0 : cls.name) === "ObjectId" || mongooseInstance2 && cls === mongooseInstance2.Types.ObjectId) && !mongooseProp.type) {
950
- mongooseProp.type = (mongooseInstance2 == null ? void 0 : mongooseInstance2.Schema.Types.ObjectId) || "ObjectId";
951
- }
952
- }
953
- if (type === "lazy") {
954
- const inner = def.getter();
955
- const result = extractMongooseDef(inner, visited, isField);
956
- if (Object.keys(meta).length > 0 && result !== mongooseProp) {
957
- if (typeof result === "object" && !Array.isArray(result)) {
958
- Object.assign(mongooseProp, result);
959
- } else {
960
- mongooseProp.type = result.type || result;
961
- }
962
- return mongooseProp;
963
- }
964
- return result;
965
- }
966
- if (!mongooseProp.type && type !== "object") {
967
- mongooseProp.type = ((_k = getMongoose()) == null ? void 0 : _k.Schema.Types.Mixed) || "Mixed";
968
- }
969
- callHookSync("converter:after", {
970
- schema,
971
- mongooseProp
972
- });
973
- if (typeof mongooseProp === "object" && mongooseProp !== null && !Array.isArray(mongooseProp)) {
974
- delete mongooseProp.includeId;
975
- }
976
- return mongooseProp;
977
- }
978
- function modelNameFromCollection(collection) {
979
- const singular = collection.replace(/ies$/i, "y").replace(/(ses|xes|zes|ches|shes)$/i, (suffix) => suffix.slice(0, -2)).replace(/s$/i, "");
980
- return singular.slice(0, 1).toUpperCase() + singular.slice(1);
981
- }
982
- function toMongooseSchema(schema, options) {
983
- var _a, _b;
984
- const { schema: unwrapped } = unwrapZodSchema(schema);
985
- const meta = mongooseRegistry.get(schema) || mongooseRegistry.get(unwrapped) || ((_a = schema.meta) == null ? void 0 : _a.call(schema)) || ((_b = unwrapped.meta) == null ? void 0 : _b.call(unwrapped)) || {};
986
- const { plugins, modelName, ...schemaOptions } = options || {};
987
- const mergedOptions = {
988
- // Also merge other schema options from meta if they exist
989
- ...meta.collection ? { collection: meta.collection } : {},
990
- // eslint-disable-next-line unicorn/no-negated-condition
991
- ...meta.strict !== void 0 ? { strict: meta.strict } : {},
992
- // eslint-disable-next-line unicorn/no-negated-condition
993
- ...meta.minimize !== void 0 ? { minimize: meta.minimize } : {},
994
- // eslint-disable-next-line unicorn/no-negated-condition
995
- ...meta.validateBeforeSave !== void 0 ? { validateBeforeSave: meta.validateBeforeSave } : {},
996
- // eslint-disable-next-line unicorn/no-negated-condition
997
- ...meta.versionKey !== void 0 ? { versionKey: meta.versionKey } : {},
998
- ...meta.id === void 0 ? {} : { id: meta.id },
999
- ...meta._id === void 0 ? {} : { _id: meta._id },
1000
- ...meta.timestamps ? { timestamps: meta.timestamps } : {},
1001
- ...meta.discriminatorKey ? { discriminatorKey: meta.discriminatorKey } : {},
1002
- ...schemaOptions
1003
- };
1004
- let definition = extractMongooseDef(schema, /* @__PURE__ */ new Map(), false);
1005
- const mongoose = getMongoose();
1006
- if (!mongoose) {
1007
- throw new Error("Mongoose must be installed to use toMongooseSchema. If you are in an ESM environment, ensure mongoose is loaded.");
1008
- }
1009
- let mongooseSchema;
1010
- if (definition && typeof definition === "object" && definition.__isDiscriminatorUnion) {
1011
- const baseModelName = modelName || schemaOptions.collection && modelNameFromCollection(schemaOptions.collection);
1012
- if (!baseModelName) {
1013
- throw new Error("toMongooseSchema() found a top-level discriminated union. Provide `modelName` or `collection` so discriminator model names can be made unique, for example `{ modelName: 'Activity' }`.");
1014
- }
1015
- const { discriminatorKey, discriminators, baseDef, validate } = definition;
1016
- mongooseSchema = new mongoose.Schema(baseDef, {
1017
- ...mergedOptions,
1018
- discriminatorKey
1019
- });
1020
- if (validate) {
1021
- if (!mongooseSchema.path(discriminatorKey)) {
1022
- mongooseSchema.add({ [discriminatorKey]: { type: String } });
1023
- }
1024
- mongooseSchema.path(discriminatorKey).validate(validate);
1025
- }
1026
- for (const [key, dDef] of Object.entries(discriminators)) {
1027
- const discriminatorModelName = `${baseModelName}_${key}`;
1028
- if (mongooseSchema.discriminators && mongooseSchema.discriminators[discriminatorModelName]) {
1029
- continue;
1030
- }
1031
- mongooseSchema.discriminator(discriminatorModelName, new mongoose.Schema(dDef, { _id: false }), { value: key });
1032
- }
1033
- } else {
1034
- if (typeof definition === "object" && definition !== null) {
1035
- const { includeId, ...cleanDefinition } = definition;
1036
- definition = cleanDefinition;
1037
- for (const value of Object.values(definition)) {
1038
- if (value && typeof value === "object" && !Array.isArray(value)) {
1039
- delete value.includeId;
1040
- }
1041
- }
1042
- }
1043
- mongooseSchema = new mongoose.Schema(definition, mergedOptions);
1044
- }
1045
- if (mergedOptions.validateBeforeSave !== false) {
1046
- mongooseSchema.post("validate", function() {
1047
- var _a2, _b2, _c, _d;
1048
- try {
1049
- schema.parse(this.toObject());
1050
- } catch (e) {
1051
- if (e instanceof z.ZodError) {
1052
- e.message = JSON.stringify({
1053
- context: {
1054
- model: ((_a2 = this.constructor) == null ? void 0 : _a2.modelName) || ((_b2 = this.constructor) == null ? void 0 : _b2.name) || "_unknown_",
1055
- id: ((_c = this._id) == null ? void 0 : _c.toString()) || ((_d = this.id) == null ? void 0 : _d.toString()) || "_unknown_"
1056
- },
1057
- errors: e.issues || e.errors || []
1058
- });
1059
- }
1060
- throw e;
1061
- }
1062
- });
1063
- }
1064
- if (plugins && Array.isArray(plugins)) {
1065
- for (const plugin of plugins) {
1066
- mongooseSchema.plugin(plugin);
1067
- }
1068
- }
1069
- callHookSync("schema:created", {
1070
- schema,
1071
- mongooseSchema,
1072
- options: mergedOptions
1073
- });
1074
- return mongooseSchema;
1075
- }
1076
- function populateZodSchema(schema, keys) {
1077
- const { shape } = schema;
1078
- const newShape = { ...shape };
1079
- const keysToPopulate = keys || Object.keys(shape);
1080
- const populateField = (field) => {
1081
- const meta = getMongooseMeta(field);
1082
- const { schema: unwrapped, features } = unwrapZodSchema(field);
1083
- let result = field;
1084
- if (meta == null ? void 0 : meta.refSchema) {
1085
- result = meta.refSchema;
1086
- } else if (unwrapped instanceof z.ZodArray) {
1087
- const populatedInner = populateField(unwrapped.element);
1088
- if (populatedInner !== unwrapped.element) {
1089
- result = z.array(populatedInner);
1090
- }
1091
- } else if (unwrapped instanceof z.ZodObject) {
1092
- result = populateZodSchema(unwrapped);
1093
- }
1094
- if (result !== field && result !== unwrapped) {
1095
- if (features.isOptional && !(result instanceof z.ZodOptional))
1096
- result = result.optional();
1097
- if (features.isNullable && !(result instanceof z.ZodNullable))
1098
- result = result.nullable();
1099
- if (features.default !== void 0 && !(result instanceof z.ZodDefault))
1100
- result = result.default(features.default);
1101
- }
1102
- return result;
1103
- };
1104
- for (const key of keysToPopulate) {
1105
- newShape[key] = populateField(shape[key]);
1106
- }
1107
- return z.object(newShape);
1108
- }
1109
- const genTimestampsSchema = (createdAtField = "createdAt", updatedAtField = "updatedAt") => {
1110
- if (createdAtField != null && updatedAtField != null && createdAtField === updatedAtField) {
1111
- throw new Error("`createdAt` and `updatedAt` fields must be different");
1112
- }
1113
- const shape = {};
1114
- if (createdAtField != null)
1115
- shape[createdAtField] = z.date().default(() => /* @__PURE__ */ new Date());
1116
- if (updatedAtField != null)
1117
- shape[updatedAtField] = z.date().default(() => /* @__PURE__ */ new Date());
1118
- return shape;
1119
- };
1120
- const bufferMongooseGetter = (value) => value != null && value._bsontype === "Binary" ? value.buffer : value;
1121
- const position = z.tuple([z.number(), z.number()]);
1122
- const zPoint = (options) => withMongoose(z.object({
1123
- type: withMongoose(z.literal("Point"), { type: String, enum: ["Point"], required: true }),
1124
- coordinates: withMongoose(position, { required: true })
1125
- }), { schema: { _id: false }, required: true, ...options });
1126
- const zPolygon = (options) => withMongoose(z.object({
1127
- type: withMongoose(z.literal("Polygon"), { type: String, enum: ["Polygon"], required: true }),
1128
- coordinates: withMongoose(z.array(z.array(position).refine((ring) => {
1129
- var _a, _b, _c, _d;
1130
- return ring.length >= 4 && ((_a = ring[0]) == null ? void 0 : _a[0]) === ((_b = ring.at(-1)) == null ? void 0 : _b[0]) && ((_c = ring[0]) == null ? void 0 : _c[1]) === ((_d = ring.at(-1)) == null ? void 0 : _d[1]);
1131
- }, "Polygon rings must be closed")).refine((rings) => rings.length > 0, "Polygon must have at least one ring"), { required: true })
1132
- }), { schema: { _id: false }, required: true, ...options });
1133
- const preprocessFn = (val) => val === null ? void 0 : val;
1134
- const zObjectId = (options) => {
1135
- var _a;
1136
- const objectIdSchema = z.custom((val) => {
1137
- const mongooseInstance2 = getMongoose();
1138
- return mongooseInstance2 && val instanceof mongooseInstance2.Types.ObjectId;
1139
- });
1140
- const baseUnion = z.preprocess(preprocessFn, z.union([objectIdSchema, z.string().regex(/^[\dA-Fa-f]{24}$/, "Invalid ObjectId")]));
1141
- const inputSchema = z.codec(baseUnion, objectIdSchema, {
1142
- decode: (val) => {
1143
- const mongooseInstance2 = getMongoose();
1144
- if (!mongooseInstance2)
1145
- return val;
1146
- if (val instanceof mongooseInstance2.Types.ObjectId) {
1147
- return val;
1148
- }
1149
- return new mongooseInstance2.Types.ObjectId(val);
1150
- },
1151
- encode: (val) => val.toString()
1152
- });
1153
- return withMongoose(inputSchema, {
1154
- type: ((_a = getMongoose()) == null ? void 0 : _a.Schema.Types.ObjectId) || "ObjectId",
1155
- ...options
1156
- });
1157
- };
1158
- const zBuffer = (options) => {
1159
- var _a;
1160
- return withMongoose(z.custom((val) => getMongoose() && val instanceof Buffer || val instanceof Uint8Array), { type: ((_a = getMongoose()) == null ? void 0 : _a.Schema.Types.Buffer) || "Buffer", ...options });
1161
- };
1162
- const zRef = (ref, schema, options) => {
1163
- var _a;
1164
- const objectIdSchema = zObjectId();
1165
- const base = z.codec(z.union([objectIdSchema, schema]), objectIdSchema, {
1166
- decode: (val) => typeof val === "object" && val !== null && "_id" in val ? val._id : val,
1167
- encode: (val) => val
1168
- });
1169
- return withMongoose(base, {
1170
- type: ((_a = getMongoose()) == null ? void 0 : _a.Schema.Types.ObjectId) || "ObjectId",
1171
- ref,
1172
- refSchema: schema,
1173
- ...options
1174
- });
1175
- };
1176
- function toStrictModel(name, mongooseSchema) {
1177
- const m = getMongoose();
1178
- if (!m) {
1179
- throw new Error("Mongoose must be installed to use toStrictModel.");
1180
- }
1181
- const rawModel = m.model(name, mongooseSchema);
1182
- return rawModel;
1183
- }
1184
-
1185
- const mongooseZod = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
1186
- __proto__: null,
1187
- bufferMongooseGetter: bufferMongooseGetter,
1188
- callHookSync: callHookSync,
1189
- extractMongooseDef: extractMongooseDef,
1190
- genTimestampsSchema: genTimestampsSchema,
1191
- getFrontendMode: getFrontendMode,
1192
- getMongoose: getMongoose,
1193
- getMongooseMeta: getMongooseMeta,
1194
- hooks: hooks,
1195
- mongooseRegistry: mongooseRegistry,
1196
- populateZodSchema: populateZodSchema,
1197
- setFrontendMode: setFrontendMode,
1198
- setMongoose: setMongoose,
1199
- toMongooseSchema: toMongooseSchema,
1200
- toStrictModel: toStrictModel,
1201
- unwrapZodSchema: unwrapZodSchema,
1202
- withMongoose: withMongoose,
1203
- zBuffer: zBuffer,
1204
- zObjectId: zObjectId,
1205
- zPoint: zPoint,
1206
- zPolygon: zPolygon,
1207
- zRef: zRef
1208
- }, Symbol.toStringTag, { value: 'Module' }));
1209
-
1210
- setMongoose(mongoose.default || mongoose);
1211
- let _filename = "/sandbox/main.ts";
1212
- let _dirname = "/sandbox";
1213
- try {
1214
- _filename = fileURLToPath(globalThis._importMeta_.url);
1215
- _dirname = dirname(_filename);
1216
- } catch {
1217
- }
19
+ const MAX_PENDING_PARSES = 3;
1218
20
  let parseQueue = Promise.resolve();
1219
- async function acquireParseLock() {
21
+ let pendingParses = 0;
22
+ async function acquireLocalLock() {
23
+ if (pendingParses >= MAX_PENDING_PARSES) throw createError({ statusCode: 503, message: "Studio is busy. Try again shortly." });
24
+ pendingParses++;
1220
25
  const previous = parseQueue;
1221
26
  let release;
1222
27
  parseQueue = new Promise((resolve) => {
1223
- release = resolve;
28
+ release = () => {
29
+ pendingParses--;
30
+ resolve();
31
+ };
1224
32
  });
1225
33
  await previous;
1226
34
  return release;
1227
35
  }
1228
- function getErrorMessage(error) {
1229
- if (error instanceof Error) return error.message || error.name;
1230
- return String(error);
1231
- }
1232
- if (typeof __filename === "undefined") {
1233
- globalThis.__filename = _filename;
1234
- }
1235
- if (typeof __dirname === "undefined") {
1236
- globalThis.__dirname = _dirname;
1237
- }
1238
36
  const parse_post = defineEventHandler(async (event) => {
1239
- const config = useRuntimeConfig(event);
1240
- const isDocsMode = config.public.isDocsMode;
1241
- const { sourceCode } = await readBody(event);
1242
- if (!sourceCode) {
1243
- throw createError({ statusCode: 400, message: "Missing sourceCode" });
37
+ if (useRuntimeConfig(event).public.isDocsMode) {
38
+ throw createError({ statusCode: 403, message: "Local Studio execution is unavailable in docs mode." });
1244
39
  }
1245
- const releaseParseLock = await acquireParseLock();
40
+ const body = await readStudioRequest(event);
41
+ const release = await acquireLocalLock();
1246
42
  try {
1247
- hooks.removeAllHooks();
1248
- let jsCode;
1249
- try {
1250
- jsCode = transformSync(sourceCode, {
1251
- loader: "ts",
1252
- format: "cjs",
1253
- target: "esnext",
1254
- // Provide these globals during transpilation just in case
1255
- define: {
1256
- __filename: '"/sandbox/main.ts"',
1257
- __dirname: '"/sandbox"'
1258
- }
1259
- }).code;
1260
- } catch (error) {
1261
- throw createError({
1262
- statusCode: 400,
1263
- message: `Compilation Error: ${getErrorMessage(error)}`
1264
- });
1265
- }
1266
- const sandboxRequire = (moduleName) => {
1267
- if (moduleName === "zod" || moduleName === "zod/v4") return zod;
1268
- if (moduleName === "@nullix/zod-mongoose") return mongooseZod;
1269
- if (moduleName === "mongoose") return mongoose.default || mongoose;
1270
- throw new Error(`Security Exception: Module "${moduleName}" is blocked.`);
1271
- };
1272
- const sandbox = {
1273
- require: sandboxRequire,
1274
- console: { log: () => {
1275
- }, warn: () => {
1276
- }, error: () => {
1277
- } },
1278
- __filename: "/sandbox/main.ts",
1279
- __dirname: "/sandbox"
1280
- };
1281
- const context = vm.createContext(sandbox);
1282
- const script = new vm.Script(`
1283
- ((__filename, __dirname) => {
1284
- let exports = {};
1285
- let module = { exports };
1286
-
1287
- ${jsCode}
1288
-
1289
- return module.exports;
1290
- })("/sandbox/main.ts", "/sandbox");
1291
- `);
1292
- const rawExport = script.runInContext(context, {
1293
- timeout: isDocsMode ? 1e3 : 5e3
1294
- });
1295
- const schema = rawExport.default || rawExport;
1296
- if (!schema || !schema._def) {
1297
- throw new Error("You must `export default` a valid Zod schema.");
1298
- }
1299
- const extractedDef = extractMongooseDef(schema);
1300
- const mongooseSchema = toMongooseSchema(schema, { modelName: "ParsedSchema" });
1301
- const formatOpts = { depth: null, showHidden: false, colors: false };
1302
- const formatValue = (val) => {
1303
- if (typeof val === "function") {
1304
- return val.name || val.toString();
1305
- }
1306
- if (Array.isArray(val)) {
1307
- return val.map(formatValue);
1308
- }
1309
- if (val !== null && typeof val === "object" && val.constructor === Object) {
1310
- const formatted = {};
1311
- for (const key in val) {
1312
- formatted[key] = formatValue(val[key]);
1313
- }
1314
- return formatted;
1315
- }
1316
- return val;
1317
- };
1318
- const formattedDef = formatValue(extractedDef);
1319
- const formattedSchema = formatValue(mongooseSchema.obj);
1320
- const formattedTree = formatValue(mongooseSchema.tree);
1321
- const formattedPaths = formatValue(mongooseSchema.paths);
1322
- return {
1323
- definition: util.inspect(formattedDef, formatOpts),
1324
- schemaObj: util.inspect(formattedSchema, formatOpts),
1325
- schemaTree: util.inspect(formattedTree, formatOpts),
1326
- schemaPaths: util.inspect(formattedPaths, formatOpts)
1327
- };
1328
- } catch (err) {
1329
- const message = getErrorMessage(err);
1330
- const isCompilationError = (err == null ? void 0 : err.statusCode) === 400;
1331
- throw createError({
1332
- statusCode: isCompilationError ? 400 : 500,
1333
- message: isCompilationError ? message : `Execution Error: ${message}`
1334
- });
43
+ return executeStudio(body, 5e3);
44
+ } catch (error) {
45
+ throw createError({ statusCode: error instanceof StudioExecutionError ? 400 : 500, message: (error == null ? void 0 : error.message) || "Studio execution failed." });
1335
46
  } finally {
1336
- hooks.removeAllHooks();
1337
- releaseParseLock();
47
+ release();
1338
48
  }
1339
49
  });
1340
50