@uipath/uipath-typescript 1.0.0-beta.15 → 1.0.0-beta.17

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.mjs CHANGED
@@ -1,15 +1,3772 @@
1
- import { z } from 'zod';
2
1
  import { BatchLogRecordProcessor, LoggerProvider } from '@opentelemetry/sdk-logs';
3
2
  import axios from 'axios';
4
3
 
5
- z.object({
6
- baseUrl: z.string().url().default('https://cloud.uipath.com'),
7
- orgName: z.string().min(1),
8
- tenantName: z.string().min(1),
9
- secret: z.string().optional(),
10
- clientId: z.string().optional(),
11
- redirectUri: z.string().url().optional(),
12
- scope: z.string().optional()
4
+ /** A special constant with type `never` */
5
+ function $constructor(name, initializer, params) {
6
+ function init(inst, def) {
7
+ if (!inst._zod) {
8
+ Object.defineProperty(inst, "_zod", {
9
+ value: {
10
+ def,
11
+ constr: _,
12
+ traits: new Set(),
13
+ },
14
+ enumerable: false,
15
+ });
16
+ }
17
+ if (inst._zod.traits.has(name)) {
18
+ return;
19
+ }
20
+ inst._zod.traits.add(name);
21
+ initializer(inst, def);
22
+ // support prototype modifications
23
+ const proto = _.prototype;
24
+ const keys = Object.keys(proto);
25
+ for (let i = 0; i < keys.length; i++) {
26
+ const k = keys[i];
27
+ if (!(k in inst)) {
28
+ inst[k] = proto[k].bind(inst);
29
+ }
30
+ }
31
+ }
32
+ // doesn't work if Parent has a constructor with arguments
33
+ const Parent = params?.Parent ?? Object;
34
+ class Definition extends Parent {
35
+ }
36
+ Object.defineProperty(Definition, "name", { value: name });
37
+ function _(def) {
38
+ var _a;
39
+ const inst = params?.Parent ? new Definition() : this;
40
+ init(inst, def);
41
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
42
+ for (const fn of inst._zod.deferred) {
43
+ fn();
44
+ }
45
+ return inst;
46
+ }
47
+ Object.defineProperty(_, "init", { value: init });
48
+ Object.defineProperty(_, Symbol.hasInstance, {
49
+ value: (inst) => {
50
+ if (params?.Parent && inst instanceof params.Parent)
51
+ return true;
52
+ return inst?._zod?.traits?.has(name);
53
+ },
54
+ });
55
+ Object.defineProperty(_, "name", { value: name });
56
+ return _;
57
+ }
58
+ class $ZodAsyncError extends Error {
59
+ constructor() {
60
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
61
+ }
62
+ }
63
+ class $ZodEncodeError extends Error {
64
+ constructor(name) {
65
+ super(`Encountered unidirectional transform during encode: ${name}`);
66
+ this.name = "ZodEncodeError";
67
+ }
68
+ }
69
+ const globalConfig = {};
70
+ function config(newConfig) {
71
+ return globalConfig;
72
+ }
73
+
74
+ // functions
75
+ function getEnumValues(entries) {
76
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
77
+ const values = Object.entries(entries)
78
+ .filter(([k, _]) => numericValues.indexOf(+k) === -1)
79
+ .map(([_, v]) => v);
80
+ return values;
81
+ }
82
+ function jsonStringifyReplacer(_, value) {
83
+ if (typeof value === "bigint")
84
+ return value.toString();
85
+ return value;
86
+ }
87
+ function cached(getter) {
88
+ return {
89
+ get value() {
90
+ {
91
+ const value = getter();
92
+ Object.defineProperty(this, "value", { value });
93
+ return value;
94
+ }
95
+ },
96
+ };
97
+ }
98
+ function nullish(input) {
99
+ return input === null || input === undefined;
100
+ }
101
+ function cleanRegex(source) {
102
+ const start = source.startsWith("^") ? 1 : 0;
103
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
104
+ return source.slice(start, end);
105
+ }
106
+ const EVALUATING = Symbol("evaluating");
107
+ function defineLazy(object, key, getter) {
108
+ let value = undefined;
109
+ Object.defineProperty(object, key, {
110
+ get() {
111
+ if (value === EVALUATING) {
112
+ // Circular reference detected, return undefined to break the cycle
113
+ return undefined;
114
+ }
115
+ if (value === undefined) {
116
+ value = EVALUATING;
117
+ value = getter();
118
+ }
119
+ return value;
120
+ },
121
+ set(v) {
122
+ Object.defineProperty(object, key, {
123
+ value: v,
124
+ // configurable: true,
125
+ });
126
+ // object[key] = v;
127
+ },
128
+ configurable: true,
129
+ });
130
+ }
131
+ function assignProp(target, prop, value) {
132
+ Object.defineProperty(target, prop, {
133
+ value,
134
+ writable: true,
135
+ enumerable: true,
136
+ configurable: true,
137
+ });
138
+ }
139
+ function mergeDefs(...defs) {
140
+ const mergedDescriptors = {};
141
+ for (const def of defs) {
142
+ const descriptors = Object.getOwnPropertyDescriptors(def);
143
+ Object.assign(mergedDescriptors, descriptors);
144
+ }
145
+ return Object.defineProperties({}, mergedDescriptors);
146
+ }
147
+ function esc(str) {
148
+ return JSON.stringify(str);
149
+ }
150
+ function slugify(input) {
151
+ return input
152
+ .toLowerCase()
153
+ .trim()
154
+ .replace(/[^\w\s-]/g, "")
155
+ .replace(/[\s_-]+/g, "-")
156
+ .replace(/^-+|-+$/g, "");
157
+ }
158
+ const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
159
+ function isObject(data) {
160
+ return typeof data === "object" && data !== null && !Array.isArray(data);
161
+ }
162
+ const allowsEval = cached(() => {
163
+ // @ts-ignore
164
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
165
+ return false;
166
+ }
167
+ try {
168
+ const F = Function;
169
+ new F("");
170
+ return true;
171
+ }
172
+ catch (_) {
173
+ return false;
174
+ }
175
+ });
176
+ function isPlainObject(o) {
177
+ if (isObject(o) === false)
178
+ return false;
179
+ // modified constructor
180
+ const ctor = o.constructor;
181
+ if (ctor === undefined)
182
+ return true;
183
+ if (typeof ctor !== "function")
184
+ return true;
185
+ // modified prototype
186
+ const prot = ctor.prototype;
187
+ if (isObject(prot) === false)
188
+ return false;
189
+ // ctor doesn't have static `isPrototypeOf`
190
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
191
+ return false;
192
+ }
193
+ return true;
194
+ }
195
+ function shallowClone(o) {
196
+ if (isPlainObject(o))
197
+ return { ...o };
198
+ if (Array.isArray(o))
199
+ return [...o];
200
+ return o;
201
+ }
202
+ const propertyKeyTypes = new Set(["string", "number", "symbol"]);
203
+ function escapeRegex(str) {
204
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
205
+ }
206
+ // zod-specific utils
207
+ function clone(inst, def, params) {
208
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
209
+ if (!def || params?.parent)
210
+ cl._zod.parent = inst;
211
+ return cl;
212
+ }
213
+ function normalizeParams(_params) {
214
+ const params = _params;
215
+ if (!params)
216
+ return {};
217
+ if (typeof params === "string")
218
+ return { error: () => params };
219
+ if (params?.message !== undefined) {
220
+ if (params?.error !== undefined)
221
+ throw new Error("Cannot specify both `message` and `error` params");
222
+ params.error = params.message;
223
+ }
224
+ delete params.message;
225
+ if (typeof params.error === "string")
226
+ return { ...params, error: () => params.error };
227
+ return params;
228
+ }
229
+ function optionalKeys(shape) {
230
+ return Object.keys(shape).filter((k) => {
231
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
232
+ });
233
+ }
234
+ function pick(schema, mask) {
235
+ const currDef = schema._zod.def;
236
+ const def = mergeDefs(schema._zod.def, {
237
+ get shape() {
238
+ const newShape = {};
239
+ for (const key in mask) {
240
+ if (!(key in currDef.shape)) {
241
+ throw new Error(`Unrecognized key: "${key}"`);
242
+ }
243
+ if (!mask[key])
244
+ continue;
245
+ newShape[key] = currDef.shape[key];
246
+ }
247
+ assignProp(this, "shape", newShape); // self-caching
248
+ return newShape;
249
+ },
250
+ checks: [],
251
+ });
252
+ return clone(schema, def);
253
+ }
254
+ function omit(schema, mask) {
255
+ const currDef = schema._zod.def;
256
+ const def = mergeDefs(schema._zod.def, {
257
+ get shape() {
258
+ const newShape = { ...schema._zod.def.shape };
259
+ for (const key in mask) {
260
+ if (!(key in currDef.shape)) {
261
+ throw new Error(`Unrecognized key: "${key}"`);
262
+ }
263
+ if (!mask[key])
264
+ continue;
265
+ delete newShape[key];
266
+ }
267
+ assignProp(this, "shape", newShape); // self-caching
268
+ return newShape;
269
+ },
270
+ checks: [],
271
+ });
272
+ return clone(schema, def);
273
+ }
274
+ function extend(schema, shape) {
275
+ if (!isPlainObject(shape)) {
276
+ throw new Error("Invalid input to extend: expected a plain object");
277
+ }
278
+ const checks = schema._zod.def.checks;
279
+ const hasChecks = checks && checks.length > 0;
280
+ if (hasChecks) {
281
+ throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");
282
+ }
283
+ const def = mergeDefs(schema._zod.def, {
284
+ get shape() {
285
+ const _shape = { ...schema._zod.def.shape, ...shape };
286
+ assignProp(this, "shape", _shape); // self-caching
287
+ return _shape;
288
+ },
289
+ checks: [],
290
+ });
291
+ return clone(schema, def);
292
+ }
293
+ function safeExtend(schema, shape) {
294
+ if (!isPlainObject(shape)) {
295
+ throw new Error("Invalid input to safeExtend: expected a plain object");
296
+ }
297
+ const def = {
298
+ ...schema._zod.def,
299
+ get shape() {
300
+ const _shape = { ...schema._zod.def.shape, ...shape };
301
+ assignProp(this, "shape", _shape); // self-caching
302
+ return _shape;
303
+ },
304
+ checks: schema._zod.def.checks,
305
+ };
306
+ return clone(schema, def);
307
+ }
308
+ function merge(a, b) {
309
+ const def = mergeDefs(a._zod.def, {
310
+ get shape() {
311
+ const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
312
+ assignProp(this, "shape", _shape); // self-caching
313
+ return _shape;
314
+ },
315
+ get catchall() {
316
+ return b._zod.def.catchall;
317
+ },
318
+ checks: [], // delete existing checks
319
+ });
320
+ return clone(a, def);
321
+ }
322
+ function partial(Class, schema, mask) {
323
+ const def = mergeDefs(schema._zod.def, {
324
+ get shape() {
325
+ const oldShape = schema._zod.def.shape;
326
+ const shape = { ...oldShape };
327
+ if (mask) {
328
+ for (const key in mask) {
329
+ if (!(key in oldShape)) {
330
+ throw new Error(`Unrecognized key: "${key}"`);
331
+ }
332
+ if (!mask[key])
333
+ continue;
334
+ // if (oldShape[key]!._zod.optin === "optional") continue;
335
+ shape[key] = Class
336
+ ? new Class({
337
+ type: "optional",
338
+ innerType: oldShape[key],
339
+ })
340
+ : oldShape[key];
341
+ }
342
+ }
343
+ else {
344
+ for (const key in oldShape) {
345
+ // if (oldShape[key]!._zod.optin === "optional") continue;
346
+ shape[key] = Class
347
+ ? new Class({
348
+ type: "optional",
349
+ innerType: oldShape[key],
350
+ })
351
+ : oldShape[key];
352
+ }
353
+ }
354
+ assignProp(this, "shape", shape); // self-caching
355
+ return shape;
356
+ },
357
+ checks: [],
358
+ });
359
+ return clone(schema, def);
360
+ }
361
+ function required(Class, schema, mask) {
362
+ const def = mergeDefs(schema._zod.def, {
363
+ get shape() {
364
+ const oldShape = schema._zod.def.shape;
365
+ const shape = { ...oldShape };
366
+ if (mask) {
367
+ for (const key in mask) {
368
+ if (!(key in shape)) {
369
+ throw new Error(`Unrecognized key: "${key}"`);
370
+ }
371
+ if (!mask[key])
372
+ continue;
373
+ // overwrite with non-optional
374
+ shape[key] = new Class({
375
+ type: "nonoptional",
376
+ innerType: oldShape[key],
377
+ });
378
+ }
379
+ }
380
+ else {
381
+ for (const key in oldShape) {
382
+ // overwrite with non-optional
383
+ shape[key] = new Class({
384
+ type: "nonoptional",
385
+ innerType: oldShape[key],
386
+ });
387
+ }
388
+ }
389
+ assignProp(this, "shape", shape); // self-caching
390
+ return shape;
391
+ },
392
+ checks: [],
393
+ });
394
+ return clone(schema, def);
395
+ }
396
+ // invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom
397
+ function aborted(x, startIndex = 0) {
398
+ if (x.aborted === true)
399
+ return true;
400
+ for (let i = startIndex; i < x.issues.length; i++) {
401
+ if (x.issues[i]?.continue !== true) {
402
+ return true;
403
+ }
404
+ }
405
+ return false;
406
+ }
407
+ function prefixIssues(path, issues) {
408
+ return issues.map((iss) => {
409
+ var _a;
410
+ (_a = iss).path ?? (_a.path = []);
411
+ iss.path.unshift(path);
412
+ return iss;
413
+ });
414
+ }
415
+ function unwrapMessage(message) {
416
+ return typeof message === "string" ? message : message?.message;
417
+ }
418
+ function finalizeIssue(iss, ctx, config) {
419
+ const full = { ...iss, path: iss.path ?? [] };
420
+ // for backwards compatibility
421
+ if (!iss.message) {
422
+ const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
423
+ unwrapMessage(ctx?.error?.(iss)) ??
424
+ unwrapMessage(config.customError?.(iss)) ??
425
+ unwrapMessage(config.localeError?.(iss)) ??
426
+ "Invalid input";
427
+ full.message = message;
428
+ }
429
+ // delete (full as any).def;
430
+ delete full.inst;
431
+ delete full.continue;
432
+ if (!ctx?.reportInput) {
433
+ delete full.input;
434
+ }
435
+ return full;
436
+ }
437
+ function getLengthableOrigin(input) {
438
+ if (Array.isArray(input))
439
+ return "array";
440
+ if (typeof input === "string")
441
+ return "string";
442
+ return "unknown";
443
+ }
444
+ function issue(...args) {
445
+ const [iss, input, inst] = args;
446
+ if (typeof iss === "string") {
447
+ return {
448
+ message: iss,
449
+ code: "custom",
450
+ input,
451
+ inst,
452
+ };
453
+ }
454
+ return { ...iss };
455
+ }
456
+
457
+ const initializer$1 = (inst, def) => {
458
+ inst.name = "$ZodError";
459
+ Object.defineProperty(inst, "_zod", {
460
+ value: inst._zod,
461
+ enumerable: false,
462
+ });
463
+ Object.defineProperty(inst, "issues", {
464
+ value: def,
465
+ enumerable: false,
466
+ });
467
+ inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
468
+ Object.defineProperty(inst, "toString", {
469
+ value: () => inst.message,
470
+ enumerable: false,
471
+ });
472
+ };
473
+ const $ZodError = $constructor("$ZodError", initializer$1);
474
+ const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
475
+ function flattenError(error, mapper = (issue) => issue.message) {
476
+ const fieldErrors = {};
477
+ const formErrors = [];
478
+ for (const sub of error.issues) {
479
+ if (sub.path.length > 0) {
480
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
481
+ fieldErrors[sub.path[0]].push(mapper(sub));
482
+ }
483
+ else {
484
+ formErrors.push(mapper(sub));
485
+ }
486
+ }
487
+ return { formErrors, fieldErrors };
488
+ }
489
+ function formatError(error, mapper = (issue) => issue.message) {
490
+ const fieldErrors = { _errors: [] };
491
+ const processError = (error) => {
492
+ for (const issue of error.issues) {
493
+ if (issue.code === "invalid_union" && issue.errors.length) {
494
+ issue.errors.map((issues) => processError({ issues }));
495
+ }
496
+ else if (issue.code === "invalid_key") {
497
+ processError({ issues: issue.issues });
498
+ }
499
+ else if (issue.code === "invalid_element") {
500
+ processError({ issues: issue.issues });
501
+ }
502
+ else if (issue.path.length === 0) {
503
+ fieldErrors._errors.push(mapper(issue));
504
+ }
505
+ else {
506
+ let curr = fieldErrors;
507
+ let i = 0;
508
+ while (i < issue.path.length) {
509
+ const el = issue.path[i];
510
+ const terminal = i === issue.path.length - 1;
511
+ if (!terminal) {
512
+ curr[el] = curr[el] || { _errors: [] };
513
+ }
514
+ else {
515
+ curr[el] = curr[el] || { _errors: [] };
516
+ curr[el]._errors.push(mapper(issue));
517
+ }
518
+ curr = curr[el];
519
+ i++;
520
+ }
521
+ }
522
+ }
523
+ };
524
+ processError(error);
525
+ return fieldErrors;
526
+ }
527
+
528
+ const _parse = (_Err) => (schema, value, _ctx, _params) => {
529
+ const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
530
+ const result = schema._zod.run({ value, issues: [] }, ctx);
531
+ if (result instanceof Promise) {
532
+ throw new $ZodAsyncError();
533
+ }
534
+ if (result.issues.length) {
535
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
536
+ captureStackTrace(e, _params?.callee);
537
+ throw e;
538
+ }
539
+ return result.value;
540
+ };
541
+ const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
542
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
543
+ let result = schema._zod.run({ value, issues: [] }, ctx);
544
+ if (result instanceof Promise)
545
+ result = await result;
546
+ if (result.issues.length) {
547
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
548
+ captureStackTrace(e, params?.callee);
549
+ throw e;
550
+ }
551
+ return result.value;
552
+ };
553
+ const _safeParse = (_Err) => (schema, value, _ctx) => {
554
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
555
+ const result = schema._zod.run({ value, issues: [] }, ctx);
556
+ if (result instanceof Promise) {
557
+ throw new $ZodAsyncError();
558
+ }
559
+ return result.issues.length
560
+ ? {
561
+ success: false,
562
+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
563
+ }
564
+ : { success: true, data: result.value };
565
+ };
566
+ const safeParse$1 = /* @__PURE__*/ _safeParse($ZodRealError);
567
+ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
568
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
569
+ let result = schema._zod.run({ value, issues: [] }, ctx);
570
+ if (result instanceof Promise)
571
+ result = await result;
572
+ return result.issues.length
573
+ ? {
574
+ success: false,
575
+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
576
+ }
577
+ : { success: true, data: result.value };
578
+ };
579
+ const safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError);
580
+ const _encode = (_Err) => (schema, value, _ctx) => {
581
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
582
+ return _parse(_Err)(schema, value, ctx);
583
+ };
584
+ const _decode = (_Err) => (schema, value, _ctx) => {
585
+ return _parse(_Err)(schema, value, _ctx);
586
+ };
587
+ const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
588
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
589
+ return _parseAsync(_Err)(schema, value, ctx);
590
+ };
591
+ const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
592
+ return _parseAsync(_Err)(schema, value, _ctx);
593
+ };
594
+ const _safeEncode = (_Err) => (schema, value, _ctx) => {
595
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
596
+ return _safeParse(_Err)(schema, value, ctx);
597
+ };
598
+ const _safeDecode = (_Err) => (schema, value, _ctx) => {
599
+ return _safeParse(_Err)(schema, value, _ctx);
600
+ };
601
+ const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
602
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
603
+ return _safeParseAsync(_Err)(schema, value, ctx);
604
+ };
605
+ const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
606
+ return _safeParseAsync(_Err)(schema, value, _ctx);
607
+ };
608
+
609
+ const cuid = /^[cC][^\s-]{8,}$/;
610
+ const cuid2 = /^[0-9a-z]+$/;
611
+ const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
612
+ const xid = /^[0-9a-vA-V]{20}$/;
613
+ const ksuid = /^[A-Za-z0-9]{27}$/;
614
+ const nanoid = /^[a-zA-Z0-9_-]{21}$/;
615
+ /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
616
+ const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
617
+ /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
618
+ const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
619
+ /** Returns a regex for validating an RFC 9562/4122 UUID.
620
+ *
621
+ * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
622
+ const uuid = (version) => {
623
+ if (!version)
624
+ return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
625
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
626
+ };
627
+ /** Practical email validation */
628
+ const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
629
+ // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
630
+ const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
631
+ function emoji() {
632
+ return new RegExp(_emoji$1, "u");
633
+ }
634
+ const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
635
+ const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
636
+ const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
637
+ const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
638
+ // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
639
+ const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
640
+ const base64url = /^[A-Za-z0-9_-]*$/;
641
+ // https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
642
+ const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
643
+ // const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
644
+ const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
645
+ const date$1 = /*@__PURE__*/ new RegExp(`^${dateSource}$`);
646
+ function timeSource(args) {
647
+ const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
648
+ const regex = typeof args.precision === "number"
649
+ ? args.precision === -1
650
+ ? `${hhmm}`
651
+ : args.precision === 0
652
+ ? `${hhmm}:[0-5]\\d`
653
+ : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`
654
+ : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
655
+ return regex;
656
+ }
657
+ function time$1(args) {
658
+ return new RegExp(`^${timeSource(args)}$`);
659
+ }
660
+ // Adapted from https://stackoverflow.com/a/3143231
661
+ function datetime$1(args) {
662
+ const time = timeSource({ precision: args.precision });
663
+ const opts = ["Z"];
664
+ if (args.local)
665
+ opts.push("");
666
+ // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`);
667
+ if (args.offset)
668
+ opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
669
+ const timeRegex = `${time}(?:${opts.join("|")})`;
670
+ return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
671
+ }
672
+ const string$1 = (params) => {
673
+ const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
674
+ return new RegExp(`^${regex}$`);
675
+ };
676
+ // regex for string with no uppercase letters
677
+ const lowercase = /^[^A-Z]*$/;
678
+ // regex for string with no lowercase letters
679
+ const uppercase = /^[^a-z]*$/;
680
+
681
+ // import { $ZodType } from "./schemas.js";
682
+ const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
683
+ var _a;
684
+ inst._zod ?? (inst._zod = {});
685
+ inst._zod.def = def;
686
+ (_a = inst._zod).onattach ?? (_a.onattach = []);
687
+ });
688
+ const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => {
689
+ var _a;
690
+ $ZodCheck.init(inst, def);
691
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
692
+ const val = payload.value;
693
+ return !nullish(val) && val.length !== undefined;
694
+ });
695
+ inst._zod.onattach.push((inst) => {
696
+ const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);
697
+ if (def.maximum < curr)
698
+ inst._zod.bag.maximum = def.maximum;
699
+ });
700
+ inst._zod.check = (payload) => {
701
+ const input = payload.value;
702
+ const length = input.length;
703
+ if (length <= def.maximum)
704
+ return;
705
+ const origin = getLengthableOrigin(input);
706
+ payload.issues.push({
707
+ origin,
708
+ code: "too_big",
709
+ maximum: def.maximum,
710
+ inclusive: true,
711
+ input,
712
+ inst,
713
+ continue: !def.abort,
714
+ });
715
+ };
716
+ });
717
+ const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => {
718
+ var _a;
719
+ $ZodCheck.init(inst, def);
720
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
721
+ const val = payload.value;
722
+ return !nullish(val) && val.length !== undefined;
723
+ });
724
+ inst._zod.onattach.push((inst) => {
725
+ const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);
726
+ if (def.minimum > curr)
727
+ inst._zod.bag.minimum = def.minimum;
728
+ });
729
+ inst._zod.check = (payload) => {
730
+ const input = payload.value;
731
+ const length = input.length;
732
+ if (length >= def.minimum)
733
+ return;
734
+ const origin = getLengthableOrigin(input);
735
+ payload.issues.push({
736
+ origin,
737
+ code: "too_small",
738
+ minimum: def.minimum,
739
+ inclusive: true,
740
+ input,
741
+ inst,
742
+ continue: !def.abort,
743
+ });
744
+ };
745
+ });
746
+ const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => {
747
+ var _a;
748
+ $ZodCheck.init(inst, def);
749
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
750
+ const val = payload.value;
751
+ return !nullish(val) && val.length !== undefined;
752
+ });
753
+ inst._zod.onattach.push((inst) => {
754
+ const bag = inst._zod.bag;
755
+ bag.minimum = def.length;
756
+ bag.maximum = def.length;
757
+ bag.length = def.length;
758
+ });
759
+ inst._zod.check = (payload) => {
760
+ const input = payload.value;
761
+ const length = input.length;
762
+ if (length === def.length)
763
+ return;
764
+ const origin = getLengthableOrigin(input);
765
+ const tooBig = length > def.length;
766
+ payload.issues.push({
767
+ origin,
768
+ ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }),
769
+ inclusive: true,
770
+ exact: true,
771
+ input: payload.value,
772
+ inst,
773
+ continue: !def.abort,
774
+ });
775
+ };
776
+ });
777
+ const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => {
778
+ var _a, _b;
779
+ $ZodCheck.init(inst, def);
780
+ inst._zod.onattach.push((inst) => {
781
+ const bag = inst._zod.bag;
782
+ bag.format = def.format;
783
+ if (def.pattern) {
784
+ bag.patterns ?? (bag.patterns = new Set());
785
+ bag.patterns.add(def.pattern);
786
+ }
787
+ });
788
+ if (def.pattern)
789
+ (_a = inst._zod).check ?? (_a.check = (payload) => {
790
+ def.pattern.lastIndex = 0;
791
+ if (def.pattern.test(payload.value))
792
+ return;
793
+ payload.issues.push({
794
+ origin: "string",
795
+ code: "invalid_format",
796
+ format: def.format,
797
+ input: payload.value,
798
+ ...(def.pattern ? { pattern: def.pattern.toString() } : {}),
799
+ inst,
800
+ continue: !def.abort,
801
+ });
802
+ });
803
+ else
804
+ (_b = inst._zod).check ?? (_b.check = () => { });
805
+ });
806
+ const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => {
807
+ $ZodCheckStringFormat.init(inst, def);
808
+ inst._zod.check = (payload) => {
809
+ def.pattern.lastIndex = 0;
810
+ if (def.pattern.test(payload.value))
811
+ return;
812
+ payload.issues.push({
813
+ origin: "string",
814
+ code: "invalid_format",
815
+ format: "regex",
816
+ input: payload.value,
817
+ pattern: def.pattern.toString(),
818
+ inst,
819
+ continue: !def.abort,
820
+ });
821
+ };
822
+ });
823
+ const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => {
824
+ def.pattern ?? (def.pattern = lowercase);
825
+ $ZodCheckStringFormat.init(inst, def);
826
+ });
827
+ const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => {
828
+ def.pattern ?? (def.pattern = uppercase);
829
+ $ZodCheckStringFormat.init(inst, def);
830
+ });
831
+ const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => {
832
+ $ZodCheck.init(inst, def);
833
+ const escapedRegex = escapeRegex(def.includes);
834
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
835
+ def.pattern = pattern;
836
+ inst._zod.onattach.push((inst) => {
837
+ const bag = inst._zod.bag;
838
+ bag.patterns ?? (bag.patterns = new Set());
839
+ bag.patterns.add(pattern);
840
+ });
841
+ inst._zod.check = (payload) => {
842
+ if (payload.value.includes(def.includes, def.position))
843
+ return;
844
+ payload.issues.push({
845
+ origin: "string",
846
+ code: "invalid_format",
847
+ format: "includes",
848
+ includes: def.includes,
849
+ input: payload.value,
850
+ inst,
851
+ continue: !def.abort,
852
+ });
853
+ };
854
+ });
855
+ const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => {
856
+ $ZodCheck.init(inst, def);
857
+ const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
858
+ def.pattern ?? (def.pattern = pattern);
859
+ inst._zod.onattach.push((inst) => {
860
+ const bag = inst._zod.bag;
861
+ bag.patterns ?? (bag.patterns = new Set());
862
+ bag.patterns.add(pattern);
863
+ });
864
+ inst._zod.check = (payload) => {
865
+ if (payload.value.startsWith(def.prefix))
866
+ return;
867
+ payload.issues.push({
868
+ origin: "string",
869
+ code: "invalid_format",
870
+ format: "starts_with",
871
+ prefix: def.prefix,
872
+ input: payload.value,
873
+ inst,
874
+ continue: !def.abort,
875
+ });
876
+ };
877
+ });
878
+ const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => {
879
+ $ZodCheck.init(inst, def);
880
+ const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
881
+ def.pattern ?? (def.pattern = pattern);
882
+ inst._zod.onattach.push((inst) => {
883
+ const bag = inst._zod.bag;
884
+ bag.patterns ?? (bag.patterns = new Set());
885
+ bag.patterns.add(pattern);
886
+ });
887
+ inst._zod.check = (payload) => {
888
+ if (payload.value.endsWith(def.suffix))
889
+ return;
890
+ payload.issues.push({
891
+ origin: "string",
892
+ code: "invalid_format",
893
+ format: "ends_with",
894
+ suffix: def.suffix,
895
+ input: payload.value,
896
+ inst,
897
+ continue: !def.abort,
898
+ });
899
+ };
900
+ });
901
+ const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => {
902
+ $ZodCheck.init(inst, def);
903
+ inst._zod.check = (payload) => {
904
+ payload.value = def.tx(payload.value);
905
+ };
906
+ });
907
+
908
+ class Doc {
909
+ constructor(args = []) {
910
+ this.content = [];
911
+ this.indent = 0;
912
+ if (this)
913
+ this.args = args;
914
+ }
915
+ indented(fn) {
916
+ this.indent += 1;
917
+ fn(this);
918
+ this.indent -= 1;
919
+ }
920
+ write(arg) {
921
+ if (typeof arg === "function") {
922
+ arg(this, { execution: "sync" });
923
+ arg(this, { execution: "async" });
924
+ return;
925
+ }
926
+ const content = arg;
927
+ const lines = content.split("\n").filter((x) => x);
928
+ const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
929
+ const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
930
+ for (const line of dedented) {
931
+ this.content.push(line);
932
+ }
933
+ }
934
+ compile() {
935
+ const F = Function;
936
+ const args = this?.args;
937
+ const content = this?.content ?? [``];
938
+ const lines = [...content.map((x) => ` ${x}`)];
939
+ // console.log(lines.join("\n"));
940
+ return new F(...args, lines.join("\n"));
941
+ }
942
+ }
943
+
944
+ const version = {
945
+ major: 4,
946
+ minor: 2,
947
+ patch: 1,
948
+ };
949
+
950
+ const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
951
+ var _a;
952
+ inst ?? (inst = {});
953
+ inst._zod.def = def; // set _def property
954
+ inst._zod.bag = inst._zod.bag || {}; // initialize _bag object
955
+ inst._zod.version = version;
956
+ const checks = [...(inst._zod.def.checks ?? [])];
957
+ // if inst is itself a checks.$ZodCheck, run it as a check
958
+ if (inst._zod.traits.has("$ZodCheck")) {
959
+ checks.unshift(inst);
960
+ }
961
+ for (const ch of checks) {
962
+ for (const fn of ch._zod.onattach) {
963
+ fn(inst);
964
+ }
965
+ }
966
+ if (checks.length === 0) {
967
+ // deferred initializer
968
+ // inst._zod.parse is not yet defined
969
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
970
+ inst._zod.deferred?.push(() => {
971
+ inst._zod.run = inst._zod.parse;
972
+ });
973
+ }
974
+ else {
975
+ const runChecks = (payload, checks, ctx) => {
976
+ let isAborted = aborted(payload);
977
+ let asyncResult;
978
+ for (const ch of checks) {
979
+ if (ch._zod.def.when) {
980
+ const shouldRun = ch._zod.def.when(payload);
981
+ if (!shouldRun)
982
+ continue;
983
+ }
984
+ else if (isAborted) {
985
+ continue;
986
+ }
987
+ const currLen = payload.issues.length;
988
+ const _ = ch._zod.check(payload);
989
+ if (_ instanceof Promise && ctx?.async === false) {
990
+ throw new $ZodAsyncError();
991
+ }
992
+ if (asyncResult || _ instanceof Promise) {
993
+ asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
994
+ await _;
995
+ const nextLen = payload.issues.length;
996
+ if (nextLen === currLen)
997
+ return;
998
+ if (!isAborted)
999
+ isAborted = aborted(payload, currLen);
1000
+ });
1001
+ }
1002
+ else {
1003
+ const nextLen = payload.issues.length;
1004
+ if (nextLen === currLen)
1005
+ continue;
1006
+ if (!isAborted)
1007
+ isAborted = aborted(payload, currLen);
1008
+ }
1009
+ }
1010
+ if (asyncResult) {
1011
+ return asyncResult.then(() => {
1012
+ return payload;
1013
+ });
1014
+ }
1015
+ return payload;
1016
+ };
1017
+ const handleCanaryResult = (canary, payload, ctx) => {
1018
+ // abort if the canary is aborted
1019
+ if (aborted(canary)) {
1020
+ canary.aborted = true;
1021
+ return canary;
1022
+ }
1023
+ // run checks first, then
1024
+ const checkResult = runChecks(payload, checks, ctx);
1025
+ if (checkResult instanceof Promise) {
1026
+ if (ctx.async === false)
1027
+ throw new $ZodAsyncError();
1028
+ return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
1029
+ }
1030
+ return inst._zod.parse(checkResult, ctx);
1031
+ };
1032
+ inst._zod.run = (payload, ctx) => {
1033
+ if (ctx.skipChecks) {
1034
+ return inst._zod.parse(payload, ctx);
1035
+ }
1036
+ if (ctx.direction === "backward") {
1037
+ // run canary
1038
+ // initial pass (no checks)
1039
+ const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
1040
+ if (canary instanceof Promise) {
1041
+ return canary.then((canary) => {
1042
+ return handleCanaryResult(canary, payload, ctx);
1043
+ });
1044
+ }
1045
+ return handleCanaryResult(canary, payload, ctx);
1046
+ }
1047
+ // forward
1048
+ const result = inst._zod.parse(payload, ctx);
1049
+ if (result instanceof Promise) {
1050
+ if (ctx.async === false)
1051
+ throw new $ZodAsyncError();
1052
+ return result.then((result) => runChecks(result, checks, ctx));
1053
+ }
1054
+ return runChecks(result, checks, ctx);
1055
+ };
1056
+ }
1057
+ inst["~standard"] = {
1058
+ validate: (value) => {
1059
+ try {
1060
+ const r = safeParse$1(inst, value);
1061
+ return r.success ? { value: r.data } : { issues: r.error?.issues };
1062
+ }
1063
+ catch (_) {
1064
+ return safeParseAsync$1(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));
1065
+ }
1066
+ },
1067
+ vendor: "zod",
1068
+ version: 1,
1069
+ };
1070
+ });
1071
+ const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
1072
+ $ZodType.init(inst, def);
1073
+ inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string$1(inst._zod.bag);
1074
+ inst._zod.parse = (payload, _) => {
1075
+ if (def.coerce)
1076
+ try {
1077
+ payload.value = String(payload.value);
1078
+ }
1079
+ catch (_) { }
1080
+ if (typeof payload.value === "string")
1081
+ return payload;
1082
+ payload.issues.push({
1083
+ expected: "string",
1084
+ code: "invalid_type",
1085
+ input: payload.value,
1086
+ inst,
1087
+ });
1088
+ return payload;
1089
+ };
1090
+ });
1091
+ const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => {
1092
+ // check initialization must come first
1093
+ $ZodCheckStringFormat.init(inst, def);
1094
+ $ZodString.init(inst, def);
1095
+ });
1096
+ const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => {
1097
+ def.pattern ?? (def.pattern = guid);
1098
+ $ZodStringFormat.init(inst, def);
1099
+ });
1100
+ const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
1101
+ if (def.version) {
1102
+ const versionMap = {
1103
+ v1: 1,
1104
+ v2: 2,
1105
+ v3: 3,
1106
+ v4: 4,
1107
+ v5: 5,
1108
+ v6: 6,
1109
+ v7: 7,
1110
+ v8: 8,
1111
+ };
1112
+ const v = versionMap[def.version];
1113
+ if (v === undefined)
1114
+ throw new Error(`Invalid UUID version: "${def.version}"`);
1115
+ def.pattern ?? (def.pattern = uuid(v));
1116
+ }
1117
+ else
1118
+ def.pattern ?? (def.pattern = uuid());
1119
+ $ZodStringFormat.init(inst, def);
1120
+ });
1121
+ const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => {
1122
+ def.pattern ?? (def.pattern = email);
1123
+ $ZodStringFormat.init(inst, def);
1124
+ });
1125
+ const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => {
1126
+ $ZodStringFormat.init(inst, def);
1127
+ inst._zod.check = (payload) => {
1128
+ try {
1129
+ // Trim whitespace from input
1130
+ const trimmed = payload.value.trim();
1131
+ // @ts-ignore
1132
+ const url = new URL(trimmed);
1133
+ if (def.hostname) {
1134
+ def.hostname.lastIndex = 0;
1135
+ if (!def.hostname.test(url.hostname)) {
1136
+ payload.issues.push({
1137
+ code: "invalid_format",
1138
+ format: "url",
1139
+ note: "Invalid hostname",
1140
+ pattern: def.hostname.source,
1141
+ input: payload.value,
1142
+ inst,
1143
+ continue: !def.abort,
1144
+ });
1145
+ }
1146
+ }
1147
+ if (def.protocol) {
1148
+ def.protocol.lastIndex = 0;
1149
+ if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
1150
+ payload.issues.push({
1151
+ code: "invalid_format",
1152
+ format: "url",
1153
+ note: "Invalid protocol",
1154
+ pattern: def.protocol.source,
1155
+ input: payload.value,
1156
+ inst,
1157
+ continue: !def.abort,
1158
+ });
1159
+ }
1160
+ }
1161
+ // Set the output value based on normalize flag
1162
+ if (def.normalize) {
1163
+ // Use normalized URL
1164
+ payload.value = url.href;
1165
+ }
1166
+ else {
1167
+ // Preserve the original input (trimmed)
1168
+ payload.value = trimmed;
1169
+ }
1170
+ return;
1171
+ }
1172
+ catch (_) {
1173
+ payload.issues.push({
1174
+ code: "invalid_format",
1175
+ format: "url",
1176
+ input: payload.value,
1177
+ inst,
1178
+ continue: !def.abort,
1179
+ });
1180
+ }
1181
+ };
1182
+ });
1183
+ const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => {
1184
+ def.pattern ?? (def.pattern = emoji());
1185
+ $ZodStringFormat.init(inst, def);
1186
+ });
1187
+ const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => {
1188
+ def.pattern ?? (def.pattern = nanoid);
1189
+ $ZodStringFormat.init(inst, def);
1190
+ });
1191
+ const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => {
1192
+ def.pattern ?? (def.pattern = cuid);
1193
+ $ZodStringFormat.init(inst, def);
1194
+ });
1195
+ const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => {
1196
+ def.pattern ?? (def.pattern = cuid2);
1197
+ $ZodStringFormat.init(inst, def);
1198
+ });
1199
+ const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => {
1200
+ def.pattern ?? (def.pattern = ulid);
1201
+ $ZodStringFormat.init(inst, def);
1202
+ });
1203
+ const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => {
1204
+ def.pattern ?? (def.pattern = xid);
1205
+ $ZodStringFormat.init(inst, def);
1206
+ });
1207
+ const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => {
1208
+ def.pattern ?? (def.pattern = ksuid);
1209
+ $ZodStringFormat.init(inst, def);
1210
+ });
1211
+ const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => {
1212
+ def.pattern ?? (def.pattern = datetime$1(def));
1213
+ $ZodStringFormat.init(inst, def);
1214
+ });
1215
+ const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => {
1216
+ def.pattern ?? (def.pattern = date$1);
1217
+ $ZodStringFormat.init(inst, def);
1218
+ });
1219
+ const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => {
1220
+ def.pattern ?? (def.pattern = time$1(def));
1221
+ $ZodStringFormat.init(inst, def);
1222
+ });
1223
+ const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => {
1224
+ def.pattern ?? (def.pattern = duration$1);
1225
+ $ZodStringFormat.init(inst, def);
1226
+ });
1227
+ const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => {
1228
+ def.pattern ?? (def.pattern = ipv4);
1229
+ $ZodStringFormat.init(inst, def);
1230
+ inst._zod.bag.format = `ipv4`;
1231
+ });
1232
+ const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => {
1233
+ def.pattern ?? (def.pattern = ipv6);
1234
+ $ZodStringFormat.init(inst, def);
1235
+ inst._zod.bag.format = `ipv6`;
1236
+ inst._zod.check = (payload) => {
1237
+ try {
1238
+ // @ts-ignore
1239
+ new URL(`http://[${payload.value}]`);
1240
+ // return;
1241
+ }
1242
+ catch {
1243
+ payload.issues.push({
1244
+ code: "invalid_format",
1245
+ format: "ipv6",
1246
+ input: payload.value,
1247
+ inst,
1248
+ continue: !def.abort,
1249
+ });
1250
+ }
1251
+ };
1252
+ });
1253
+ const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => {
1254
+ def.pattern ?? (def.pattern = cidrv4);
1255
+ $ZodStringFormat.init(inst, def);
1256
+ });
1257
+ const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => {
1258
+ def.pattern ?? (def.pattern = cidrv6); // not used for validation
1259
+ $ZodStringFormat.init(inst, def);
1260
+ inst._zod.check = (payload) => {
1261
+ const parts = payload.value.split("/");
1262
+ try {
1263
+ if (parts.length !== 2)
1264
+ throw new Error();
1265
+ const [address, prefix] = parts;
1266
+ if (!prefix)
1267
+ throw new Error();
1268
+ const prefixNum = Number(prefix);
1269
+ if (`${prefixNum}` !== prefix)
1270
+ throw new Error();
1271
+ if (prefixNum < 0 || prefixNum > 128)
1272
+ throw new Error();
1273
+ // @ts-ignore
1274
+ new URL(`http://[${address}]`);
1275
+ }
1276
+ catch {
1277
+ payload.issues.push({
1278
+ code: "invalid_format",
1279
+ format: "cidrv6",
1280
+ input: payload.value,
1281
+ inst,
1282
+ continue: !def.abort,
1283
+ });
1284
+ }
1285
+ };
1286
+ });
1287
+ ////////////////////////////// ZodBase64 //////////////////////////////
1288
+ function isValidBase64(data) {
1289
+ if (data === "")
1290
+ return true;
1291
+ if (data.length % 4 !== 0)
1292
+ return false;
1293
+ try {
1294
+ // @ts-ignore
1295
+ atob(data);
1296
+ return true;
1297
+ }
1298
+ catch {
1299
+ return false;
1300
+ }
1301
+ }
1302
+ const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => {
1303
+ def.pattern ?? (def.pattern = base64);
1304
+ $ZodStringFormat.init(inst, def);
1305
+ inst._zod.bag.contentEncoding = "base64";
1306
+ inst._zod.check = (payload) => {
1307
+ if (isValidBase64(payload.value))
1308
+ return;
1309
+ payload.issues.push({
1310
+ code: "invalid_format",
1311
+ format: "base64",
1312
+ input: payload.value,
1313
+ inst,
1314
+ continue: !def.abort,
1315
+ });
1316
+ };
1317
+ });
1318
+ ////////////////////////////// ZodBase64 //////////////////////////////
1319
+ function isValidBase64URL(data) {
1320
+ if (!base64url.test(data))
1321
+ return false;
1322
+ const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/"));
1323
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
1324
+ return isValidBase64(padded);
1325
+ }
1326
+ const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => {
1327
+ def.pattern ?? (def.pattern = base64url);
1328
+ $ZodStringFormat.init(inst, def);
1329
+ inst._zod.bag.contentEncoding = "base64url";
1330
+ inst._zod.check = (payload) => {
1331
+ if (isValidBase64URL(payload.value))
1332
+ return;
1333
+ payload.issues.push({
1334
+ code: "invalid_format",
1335
+ format: "base64url",
1336
+ input: payload.value,
1337
+ inst,
1338
+ continue: !def.abort,
1339
+ });
1340
+ };
1341
+ });
1342
+ const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => {
1343
+ def.pattern ?? (def.pattern = e164);
1344
+ $ZodStringFormat.init(inst, def);
1345
+ });
1346
+ ////////////////////////////// ZodJWT //////////////////////////////
1347
+ function isValidJWT(token, algorithm = null) {
1348
+ try {
1349
+ const tokensParts = token.split(".");
1350
+ if (tokensParts.length !== 3)
1351
+ return false;
1352
+ const [header] = tokensParts;
1353
+ if (!header)
1354
+ return false;
1355
+ // @ts-ignore
1356
+ const parsedHeader = JSON.parse(atob(header));
1357
+ if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
1358
+ return false;
1359
+ if (!parsedHeader.alg)
1360
+ return false;
1361
+ if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
1362
+ return false;
1363
+ return true;
1364
+ }
1365
+ catch {
1366
+ return false;
1367
+ }
1368
+ }
1369
+ const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => {
1370
+ $ZodStringFormat.init(inst, def);
1371
+ inst._zod.check = (payload) => {
1372
+ if (isValidJWT(payload.value, def.alg))
1373
+ return;
1374
+ payload.issues.push({
1375
+ code: "invalid_format",
1376
+ format: "jwt",
1377
+ input: payload.value,
1378
+ inst,
1379
+ continue: !def.abort,
1380
+ });
1381
+ };
1382
+ });
1383
+ const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => {
1384
+ $ZodType.init(inst, def);
1385
+ inst._zod.parse = (payload) => payload;
1386
+ });
1387
+ const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => {
1388
+ $ZodType.init(inst, def);
1389
+ inst._zod.parse = (payload, _ctx) => {
1390
+ payload.issues.push({
1391
+ expected: "never",
1392
+ code: "invalid_type",
1393
+ input: payload.value,
1394
+ inst,
1395
+ });
1396
+ return payload;
1397
+ };
1398
+ });
1399
+ function handleArrayResult(result, final, index) {
1400
+ if (result.issues.length) {
1401
+ final.issues.push(...prefixIssues(index, result.issues));
1402
+ }
1403
+ final.value[index] = result.value;
1404
+ }
1405
+ const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => {
1406
+ $ZodType.init(inst, def);
1407
+ inst._zod.parse = (payload, ctx) => {
1408
+ const input = payload.value;
1409
+ if (!Array.isArray(input)) {
1410
+ payload.issues.push({
1411
+ expected: "array",
1412
+ code: "invalid_type",
1413
+ input,
1414
+ inst,
1415
+ });
1416
+ return payload;
1417
+ }
1418
+ payload.value = Array(input.length);
1419
+ const proms = [];
1420
+ for (let i = 0; i < input.length; i++) {
1421
+ const item = input[i];
1422
+ const result = def.element._zod.run({
1423
+ value: item,
1424
+ issues: [],
1425
+ }, ctx);
1426
+ if (result instanceof Promise) {
1427
+ proms.push(result.then((result) => handleArrayResult(result, payload, i)));
1428
+ }
1429
+ else {
1430
+ handleArrayResult(result, payload, i);
1431
+ }
1432
+ }
1433
+ if (proms.length) {
1434
+ return Promise.all(proms).then(() => payload);
1435
+ }
1436
+ return payload; //handleArrayResultsAsync(parseResults, final);
1437
+ };
1438
+ });
1439
+ function handlePropertyResult(result, final, key, input) {
1440
+ if (result.issues.length) {
1441
+ final.issues.push(...prefixIssues(key, result.issues));
1442
+ }
1443
+ if (result.value === undefined) {
1444
+ if (key in input) {
1445
+ final.value[key] = undefined;
1446
+ }
1447
+ }
1448
+ else {
1449
+ final.value[key] = result.value;
1450
+ }
1451
+ }
1452
+ function normalizeDef(def) {
1453
+ const keys = Object.keys(def.shape);
1454
+ for (const k of keys) {
1455
+ if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
1456
+ throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
1457
+ }
1458
+ }
1459
+ const okeys = optionalKeys(def.shape);
1460
+ return {
1461
+ ...def,
1462
+ keys,
1463
+ keySet: new Set(keys),
1464
+ numKeys: keys.length,
1465
+ optionalKeys: new Set(okeys),
1466
+ };
1467
+ }
1468
+ function handleCatchall(proms, input, payload, ctx, def, inst) {
1469
+ const unrecognized = [];
1470
+ // iterate over input keys
1471
+ const keySet = def.keySet;
1472
+ const _catchall = def.catchall._zod;
1473
+ const t = _catchall.def.type;
1474
+ for (const key in input) {
1475
+ if (keySet.has(key))
1476
+ continue;
1477
+ if (t === "never") {
1478
+ unrecognized.push(key);
1479
+ continue;
1480
+ }
1481
+ const r = _catchall.run({ value: input[key], issues: [] }, ctx);
1482
+ if (r instanceof Promise) {
1483
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
1484
+ }
1485
+ else {
1486
+ handlePropertyResult(r, payload, key, input);
1487
+ }
1488
+ }
1489
+ if (unrecognized.length) {
1490
+ payload.issues.push({
1491
+ code: "unrecognized_keys",
1492
+ keys: unrecognized,
1493
+ input,
1494
+ inst,
1495
+ });
1496
+ }
1497
+ if (!proms.length)
1498
+ return payload;
1499
+ return Promise.all(proms).then(() => {
1500
+ return payload;
1501
+ });
1502
+ }
1503
+ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1504
+ // requires cast because technically $ZodObject doesn't extend
1505
+ $ZodType.init(inst, def);
1506
+ // const sh = def.shape;
1507
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
1508
+ if (!desc?.get) {
1509
+ const sh = def.shape;
1510
+ Object.defineProperty(def, "shape", {
1511
+ get: () => {
1512
+ const newSh = { ...sh };
1513
+ Object.defineProperty(def, "shape", {
1514
+ value: newSh,
1515
+ });
1516
+ return newSh;
1517
+ },
1518
+ });
1519
+ }
1520
+ const _normalized = cached(() => normalizeDef(def));
1521
+ defineLazy(inst._zod, "propValues", () => {
1522
+ const shape = def.shape;
1523
+ const propValues = {};
1524
+ for (const key in shape) {
1525
+ const field = shape[key]._zod;
1526
+ if (field.values) {
1527
+ propValues[key] ?? (propValues[key] = new Set());
1528
+ for (const v of field.values)
1529
+ propValues[key].add(v);
1530
+ }
1531
+ }
1532
+ return propValues;
1533
+ });
1534
+ const isObject$1 = isObject;
1535
+ const catchall = def.catchall;
1536
+ let value;
1537
+ inst._zod.parse = (payload, ctx) => {
1538
+ value ?? (value = _normalized.value);
1539
+ const input = payload.value;
1540
+ if (!isObject$1(input)) {
1541
+ payload.issues.push({
1542
+ expected: "object",
1543
+ code: "invalid_type",
1544
+ input,
1545
+ inst,
1546
+ });
1547
+ return payload;
1548
+ }
1549
+ payload.value = {};
1550
+ const proms = [];
1551
+ const shape = value.shape;
1552
+ for (const key of value.keys) {
1553
+ const el = shape[key];
1554
+ const r = el._zod.run({ value: input[key], issues: [] }, ctx);
1555
+ if (r instanceof Promise) {
1556
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
1557
+ }
1558
+ else {
1559
+ handlePropertyResult(r, payload, key, input);
1560
+ }
1561
+ }
1562
+ if (!catchall) {
1563
+ return proms.length ? Promise.all(proms).then(() => payload) : payload;
1564
+ }
1565
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
1566
+ };
1567
+ });
1568
+ const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => {
1569
+ // requires cast because technically $ZodObject doesn't extend
1570
+ $ZodObject.init(inst, def);
1571
+ const superParse = inst._zod.parse;
1572
+ const _normalized = cached(() => normalizeDef(def));
1573
+ const generateFastpass = (shape) => {
1574
+ const doc = new Doc(["shape", "payload", "ctx"]);
1575
+ const normalized = _normalized.value;
1576
+ const parseStr = (key) => {
1577
+ const k = esc(key);
1578
+ return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
1579
+ };
1580
+ doc.write(`const input = payload.value;`);
1581
+ const ids = Object.create(null);
1582
+ let counter = 0;
1583
+ for (const key of normalized.keys) {
1584
+ ids[key] = `key_${counter++}`;
1585
+ }
1586
+ // A: preserve key order {
1587
+ doc.write(`const newResult = {};`);
1588
+ for (const key of normalized.keys) {
1589
+ const id = ids[key];
1590
+ const k = esc(key);
1591
+ doc.write(`const ${id} = ${parseStr(key)};`);
1592
+ doc.write(`
1593
+ if (${id}.issues.length) {
1594
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1595
+ ...iss,
1596
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
1597
+ })));
1598
+ }
1599
+
1600
+
1601
+ if (${id}.value === undefined) {
1602
+ if (${k} in input) {
1603
+ newResult[${k}] = undefined;
1604
+ }
1605
+ } else {
1606
+ newResult[${k}] = ${id}.value;
1607
+ }
1608
+
1609
+ `);
1610
+ }
1611
+ doc.write(`payload.value = newResult;`);
1612
+ doc.write(`return payload;`);
1613
+ const fn = doc.compile();
1614
+ return (payload, ctx) => fn(shape, payload, ctx);
1615
+ };
1616
+ let fastpass;
1617
+ const isObject$1 = isObject;
1618
+ const jit = !globalConfig.jitless;
1619
+ const allowsEval$1 = allowsEval;
1620
+ const fastEnabled = jit && allowsEval$1.value; // && !def.catchall;
1621
+ const catchall = def.catchall;
1622
+ let value;
1623
+ inst._zod.parse = (payload, ctx) => {
1624
+ value ?? (value = _normalized.value);
1625
+ const input = payload.value;
1626
+ if (!isObject$1(input)) {
1627
+ payload.issues.push({
1628
+ expected: "object",
1629
+ code: "invalid_type",
1630
+ input,
1631
+ inst,
1632
+ });
1633
+ return payload;
1634
+ }
1635
+ if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
1636
+ // always synchronous
1637
+ if (!fastpass)
1638
+ fastpass = generateFastpass(def.shape);
1639
+ payload = fastpass(payload, ctx);
1640
+ if (!catchall)
1641
+ return payload;
1642
+ return handleCatchall([], input, payload, ctx, value, inst);
1643
+ }
1644
+ return superParse(payload, ctx);
1645
+ };
1646
+ });
1647
+ function handleUnionResults(results, final, inst, ctx) {
1648
+ for (const result of results) {
1649
+ if (result.issues.length === 0) {
1650
+ final.value = result.value;
1651
+ return final;
1652
+ }
1653
+ }
1654
+ const nonaborted = results.filter((r) => !aborted(r));
1655
+ if (nonaborted.length === 1) {
1656
+ final.value = nonaborted[0].value;
1657
+ return nonaborted[0];
1658
+ }
1659
+ final.issues.push({
1660
+ code: "invalid_union",
1661
+ input: final.value,
1662
+ inst,
1663
+ errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
1664
+ });
1665
+ return final;
1666
+ }
1667
+ const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => {
1668
+ $ZodType.init(inst, def);
1669
+ defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
1670
+ defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
1671
+ defineLazy(inst._zod, "values", () => {
1672
+ if (def.options.every((o) => o._zod.values)) {
1673
+ return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
1674
+ }
1675
+ return undefined;
1676
+ });
1677
+ defineLazy(inst._zod, "pattern", () => {
1678
+ if (def.options.every((o) => o._zod.pattern)) {
1679
+ const patterns = def.options.map((o) => o._zod.pattern);
1680
+ return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
1681
+ }
1682
+ return undefined;
1683
+ });
1684
+ const single = def.options.length === 1;
1685
+ const first = def.options[0]._zod.run;
1686
+ inst._zod.parse = (payload, ctx) => {
1687
+ if (single) {
1688
+ return first(payload, ctx);
1689
+ }
1690
+ let async = false;
1691
+ const results = [];
1692
+ for (const option of def.options) {
1693
+ const result = option._zod.run({
1694
+ value: payload.value,
1695
+ issues: [],
1696
+ }, ctx);
1697
+ if (result instanceof Promise) {
1698
+ results.push(result);
1699
+ async = true;
1700
+ }
1701
+ else {
1702
+ if (result.issues.length === 0)
1703
+ return result;
1704
+ results.push(result);
1705
+ }
1706
+ }
1707
+ if (!async)
1708
+ return handleUnionResults(results, payload, inst, ctx);
1709
+ return Promise.all(results).then((results) => {
1710
+ return handleUnionResults(results, payload, inst, ctx);
1711
+ });
1712
+ };
1713
+ });
1714
+ const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => {
1715
+ $ZodType.init(inst, def);
1716
+ inst._zod.parse = (payload, ctx) => {
1717
+ const input = payload.value;
1718
+ const left = def.left._zod.run({ value: input, issues: [] }, ctx);
1719
+ const right = def.right._zod.run({ value: input, issues: [] }, ctx);
1720
+ const async = left instanceof Promise || right instanceof Promise;
1721
+ if (async) {
1722
+ return Promise.all([left, right]).then(([left, right]) => {
1723
+ return handleIntersectionResults(payload, left, right);
1724
+ });
1725
+ }
1726
+ return handleIntersectionResults(payload, left, right);
1727
+ };
1728
+ });
1729
+ function mergeValues(a, b) {
1730
+ // const aType = parse.t(a);
1731
+ // const bType = parse.t(b);
1732
+ if (a === b) {
1733
+ return { valid: true, data: a };
1734
+ }
1735
+ if (a instanceof Date && b instanceof Date && +a === +b) {
1736
+ return { valid: true, data: a };
1737
+ }
1738
+ if (isPlainObject(a) && isPlainObject(b)) {
1739
+ const bKeys = Object.keys(b);
1740
+ const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1741
+ const newObj = { ...a, ...b };
1742
+ for (const key of sharedKeys) {
1743
+ const sharedValue = mergeValues(a[key], b[key]);
1744
+ if (!sharedValue.valid) {
1745
+ return {
1746
+ valid: false,
1747
+ mergeErrorPath: [key, ...sharedValue.mergeErrorPath],
1748
+ };
1749
+ }
1750
+ newObj[key] = sharedValue.data;
1751
+ }
1752
+ return { valid: true, data: newObj };
1753
+ }
1754
+ if (Array.isArray(a) && Array.isArray(b)) {
1755
+ if (a.length !== b.length) {
1756
+ return { valid: false, mergeErrorPath: [] };
1757
+ }
1758
+ const newArray = [];
1759
+ for (let index = 0; index < a.length; index++) {
1760
+ const itemA = a[index];
1761
+ const itemB = b[index];
1762
+ const sharedValue = mergeValues(itemA, itemB);
1763
+ if (!sharedValue.valid) {
1764
+ return {
1765
+ valid: false,
1766
+ mergeErrorPath: [index, ...sharedValue.mergeErrorPath],
1767
+ };
1768
+ }
1769
+ newArray.push(sharedValue.data);
1770
+ }
1771
+ return { valid: true, data: newArray };
1772
+ }
1773
+ return { valid: false, mergeErrorPath: [] };
1774
+ }
1775
+ function handleIntersectionResults(result, left, right) {
1776
+ if (left.issues.length) {
1777
+ result.issues.push(...left.issues);
1778
+ }
1779
+ if (right.issues.length) {
1780
+ result.issues.push(...right.issues);
1781
+ }
1782
+ if (aborted(result))
1783
+ return result;
1784
+ const merged = mergeValues(left.value, right.value);
1785
+ if (!merged.valid) {
1786
+ throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
1787
+ }
1788
+ result.value = merged.data;
1789
+ return result;
1790
+ }
1791
+ const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
1792
+ $ZodType.init(inst, def);
1793
+ const values = getEnumValues(def.entries);
1794
+ const valuesSet = new Set(values);
1795
+ inst._zod.values = valuesSet;
1796
+ inst._zod.pattern = new RegExp(`^(${values
1797
+ .filter((k) => propertyKeyTypes.has(typeof k))
1798
+ .map((o) => (typeof o === "string" ? escapeRegex(o) : o.toString()))
1799
+ .join("|")})$`);
1800
+ inst._zod.parse = (payload, _ctx) => {
1801
+ const input = payload.value;
1802
+ if (valuesSet.has(input)) {
1803
+ return payload;
1804
+ }
1805
+ payload.issues.push({
1806
+ code: "invalid_value",
1807
+ values,
1808
+ input,
1809
+ inst,
1810
+ });
1811
+ return payload;
1812
+ };
1813
+ });
1814
+ const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => {
1815
+ $ZodType.init(inst, def);
1816
+ inst._zod.parse = (payload, ctx) => {
1817
+ if (ctx.direction === "backward") {
1818
+ throw new $ZodEncodeError(inst.constructor.name);
1819
+ }
1820
+ const _out = def.transform(payload.value, payload);
1821
+ if (ctx.async) {
1822
+ const output = _out instanceof Promise ? _out : Promise.resolve(_out);
1823
+ return output.then((output) => {
1824
+ payload.value = output;
1825
+ return payload;
1826
+ });
1827
+ }
1828
+ if (_out instanceof Promise) {
1829
+ throw new $ZodAsyncError();
1830
+ }
1831
+ payload.value = _out;
1832
+ return payload;
1833
+ };
1834
+ });
1835
+ function handleOptionalResult(result, input) {
1836
+ if (result.issues.length && input === undefined) {
1837
+ return { issues: [], value: undefined };
1838
+ }
1839
+ return result;
1840
+ }
1841
+ const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
1842
+ $ZodType.init(inst, def);
1843
+ inst._zod.optin = "optional";
1844
+ inst._zod.optout = "optional";
1845
+ defineLazy(inst._zod, "values", () => {
1846
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
1847
+ });
1848
+ defineLazy(inst._zod, "pattern", () => {
1849
+ const pattern = def.innerType._zod.pattern;
1850
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
1851
+ });
1852
+ inst._zod.parse = (payload, ctx) => {
1853
+ if (def.innerType._zod.optin === "optional") {
1854
+ const result = def.innerType._zod.run(payload, ctx);
1855
+ if (result instanceof Promise)
1856
+ return result.then((r) => handleOptionalResult(r, payload.value));
1857
+ return handleOptionalResult(result, payload.value);
1858
+ }
1859
+ if (payload.value === undefined) {
1860
+ return payload;
1861
+ }
1862
+ return def.innerType._zod.run(payload, ctx);
1863
+ };
1864
+ });
1865
+ const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => {
1866
+ $ZodType.init(inst, def);
1867
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1868
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1869
+ defineLazy(inst._zod, "pattern", () => {
1870
+ const pattern = def.innerType._zod.pattern;
1871
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
1872
+ });
1873
+ defineLazy(inst._zod, "values", () => {
1874
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
1875
+ });
1876
+ inst._zod.parse = (payload, ctx) => {
1877
+ // Forward direction (decode): allow null to pass through
1878
+ if (payload.value === null)
1879
+ return payload;
1880
+ return def.innerType._zod.run(payload, ctx);
1881
+ };
1882
+ });
1883
+ const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => {
1884
+ $ZodType.init(inst, def);
1885
+ // inst._zod.qin = "true";
1886
+ inst._zod.optin = "optional";
1887
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1888
+ inst._zod.parse = (payload, ctx) => {
1889
+ if (ctx.direction === "backward") {
1890
+ return def.innerType._zod.run(payload, ctx);
1891
+ }
1892
+ // Forward direction (decode): apply defaults for undefined input
1893
+ if (payload.value === undefined) {
1894
+ payload.value = def.defaultValue;
1895
+ /**
1896
+ * $ZodDefault returns the default value immediately in forward direction.
1897
+ * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
1898
+ return payload;
1899
+ }
1900
+ // Forward direction: continue with default handling
1901
+ const result = def.innerType._zod.run(payload, ctx);
1902
+ if (result instanceof Promise) {
1903
+ return result.then((result) => handleDefaultResult(result, def));
1904
+ }
1905
+ return handleDefaultResult(result, def);
1906
+ };
1907
+ });
1908
+ function handleDefaultResult(payload, def) {
1909
+ if (payload.value === undefined) {
1910
+ payload.value = def.defaultValue;
1911
+ }
1912
+ return payload;
1913
+ }
1914
+ const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => {
1915
+ $ZodType.init(inst, def);
1916
+ inst._zod.optin = "optional";
1917
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1918
+ inst._zod.parse = (payload, ctx) => {
1919
+ if (ctx.direction === "backward") {
1920
+ return def.innerType._zod.run(payload, ctx);
1921
+ }
1922
+ // Forward direction (decode): apply prefault for undefined input
1923
+ if (payload.value === undefined) {
1924
+ payload.value = def.defaultValue;
1925
+ }
1926
+ return def.innerType._zod.run(payload, ctx);
1927
+ };
1928
+ });
1929
+ const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => {
1930
+ $ZodType.init(inst, def);
1931
+ defineLazy(inst._zod, "values", () => {
1932
+ const v = def.innerType._zod.values;
1933
+ return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
1934
+ });
1935
+ inst._zod.parse = (payload, ctx) => {
1936
+ const result = def.innerType._zod.run(payload, ctx);
1937
+ if (result instanceof Promise) {
1938
+ return result.then((result) => handleNonOptionalResult(result, inst));
1939
+ }
1940
+ return handleNonOptionalResult(result, inst);
1941
+ };
1942
+ });
1943
+ function handleNonOptionalResult(payload, inst) {
1944
+ if (!payload.issues.length && payload.value === undefined) {
1945
+ payload.issues.push({
1946
+ code: "invalid_type",
1947
+ expected: "nonoptional",
1948
+ input: payload.value,
1949
+ inst,
1950
+ });
1951
+ }
1952
+ return payload;
1953
+ }
1954
+ const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => {
1955
+ $ZodType.init(inst, def);
1956
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1957
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1958
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1959
+ inst._zod.parse = (payload, ctx) => {
1960
+ if (ctx.direction === "backward") {
1961
+ return def.innerType._zod.run(payload, ctx);
1962
+ }
1963
+ // Forward direction (decode): apply catch logic
1964
+ const result = def.innerType._zod.run(payload, ctx);
1965
+ if (result instanceof Promise) {
1966
+ return result.then((result) => {
1967
+ payload.value = result.value;
1968
+ if (result.issues.length) {
1969
+ payload.value = def.catchValue({
1970
+ ...payload,
1971
+ error: {
1972
+ issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())),
1973
+ },
1974
+ input: payload.value,
1975
+ });
1976
+ payload.issues = [];
1977
+ }
1978
+ return payload;
1979
+ });
1980
+ }
1981
+ payload.value = result.value;
1982
+ if (result.issues.length) {
1983
+ payload.value = def.catchValue({
1984
+ ...payload,
1985
+ error: {
1986
+ issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())),
1987
+ },
1988
+ input: payload.value,
1989
+ });
1990
+ payload.issues = [];
1991
+ }
1992
+ return payload;
1993
+ };
1994
+ });
1995
+ const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => {
1996
+ $ZodType.init(inst, def);
1997
+ defineLazy(inst._zod, "values", () => def.in._zod.values);
1998
+ defineLazy(inst._zod, "optin", () => def.in._zod.optin);
1999
+ defineLazy(inst._zod, "optout", () => def.out._zod.optout);
2000
+ defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
2001
+ inst._zod.parse = (payload, ctx) => {
2002
+ if (ctx.direction === "backward") {
2003
+ const right = def.out._zod.run(payload, ctx);
2004
+ if (right instanceof Promise) {
2005
+ return right.then((right) => handlePipeResult(right, def.in, ctx));
2006
+ }
2007
+ return handlePipeResult(right, def.in, ctx);
2008
+ }
2009
+ const left = def.in._zod.run(payload, ctx);
2010
+ if (left instanceof Promise) {
2011
+ return left.then((left) => handlePipeResult(left, def.out, ctx));
2012
+ }
2013
+ return handlePipeResult(left, def.out, ctx);
2014
+ };
2015
+ });
2016
+ function handlePipeResult(left, next, ctx) {
2017
+ if (left.issues.length) {
2018
+ // prevent further checks
2019
+ left.aborted = true;
2020
+ return left;
2021
+ }
2022
+ return next._zod.run({ value: left.value, issues: left.issues }, ctx);
2023
+ }
2024
+ const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
2025
+ $ZodType.init(inst, def);
2026
+ defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
2027
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2028
+ defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
2029
+ defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
2030
+ inst._zod.parse = (payload, ctx) => {
2031
+ if (ctx.direction === "backward") {
2032
+ return def.innerType._zod.run(payload, ctx);
2033
+ }
2034
+ const result = def.innerType._zod.run(payload, ctx);
2035
+ if (result instanceof Promise) {
2036
+ return result.then(handleReadonlyResult);
2037
+ }
2038
+ return handleReadonlyResult(result);
2039
+ };
2040
+ });
2041
+ function handleReadonlyResult(payload) {
2042
+ payload.value = Object.freeze(payload.value);
2043
+ return payload;
2044
+ }
2045
+ const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => {
2046
+ $ZodCheck.init(inst, def);
2047
+ $ZodType.init(inst, def);
2048
+ inst._zod.parse = (payload, _) => {
2049
+ return payload;
2050
+ };
2051
+ inst._zod.check = (payload) => {
2052
+ const input = payload.value;
2053
+ const r = def.fn(input);
2054
+ if (r instanceof Promise) {
2055
+ return r.then((r) => handleRefineResult(r, payload, input, inst));
2056
+ }
2057
+ handleRefineResult(r, payload, input, inst);
2058
+ return;
2059
+ };
2060
+ });
2061
+ function handleRefineResult(result, payload, input, inst) {
2062
+ if (!result) {
2063
+ const _iss = {
2064
+ code: "custom",
2065
+ input,
2066
+ inst, // incorporates params.error into issue reporting
2067
+ path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting
2068
+ continue: !inst._zod.def.abort,
2069
+ // params: inst._zod.def.params,
2070
+ };
2071
+ if (inst._zod.def.params)
2072
+ _iss.params = inst._zod.def.params;
2073
+ payload.issues.push(issue(_iss));
2074
+ }
2075
+ }
2076
+
2077
+ var _a;
2078
+ class $ZodRegistry {
2079
+ constructor() {
2080
+ this._map = new WeakMap();
2081
+ this._idmap = new Map();
2082
+ }
2083
+ add(schema, ..._meta) {
2084
+ const meta = _meta[0];
2085
+ this._map.set(schema, meta);
2086
+ if (meta && typeof meta === "object" && "id" in meta) {
2087
+ if (this._idmap.has(meta.id)) {
2088
+ throw new Error(`ID ${meta.id} already exists in the registry`);
2089
+ }
2090
+ this._idmap.set(meta.id, schema);
2091
+ }
2092
+ return this;
2093
+ }
2094
+ clear() {
2095
+ this._map = new WeakMap();
2096
+ this._idmap = new Map();
2097
+ return this;
2098
+ }
2099
+ remove(schema) {
2100
+ const meta = this._map.get(schema);
2101
+ if (meta && typeof meta === "object" && "id" in meta) {
2102
+ this._idmap.delete(meta.id);
2103
+ }
2104
+ this._map.delete(schema);
2105
+ return this;
2106
+ }
2107
+ get(schema) {
2108
+ // return this._map.get(schema) as any;
2109
+ // inherit metadata
2110
+ const p = schema._zod.parent;
2111
+ if (p) {
2112
+ const pm = { ...(this.get(p) ?? {}) };
2113
+ delete pm.id; // do not inherit id
2114
+ const f = { ...pm, ...this._map.get(schema) };
2115
+ return Object.keys(f).length ? f : undefined;
2116
+ }
2117
+ return this._map.get(schema);
2118
+ }
2119
+ has(schema) {
2120
+ return this._map.has(schema);
2121
+ }
2122
+ }
2123
+ // registries
2124
+ function registry() {
2125
+ return new $ZodRegistry();
2126
+ }
2127
+ (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
2128
+ const globalRegistry = globalThis.__zod_globalRegistry;
2129
+
2130
+ function _string(Class, params) {
2131
+ return new Class({
2132
+ type: "string",
2133
+ ...normalizeParams(params),
2134
+ });
2135
+ }
2136
+ function _email(Class, params) {
2137
+ return new Class({
2138
+ type: "string",
2139
+ format: "email",
2140
+ check: "string_format",
2141
+ abort: false,
2142
+ ...normalizeParams(params),
2143
+ });
2144
+ }
2145
+ function _guid(Class, params) {
2146
+ return new Class({
2147
+ type: "string",
2148
+ format: "guid",
2149
+ check: "string_format",
2150
+ abort: false,
2151
+ ...normalizeParams(params),
2152
+ });
2153
+ }
2154
+ function _uuid(Class, params) {
2155
+ return new Class({
2156
+ type: "string",
2157
+ format: "uuid",
2158
+ check: "string_format",
2159
+ abort: false,
2160
+ ...normalizeParams(params),
2161
+ });
2162
+ }
2163
+ function _uuidv4(Class, params) {
2164
+ return new Class({
2165
+ type: "string",
2166
+ format: "uuid",
2167
+ check: "string_format",
2168
+ abort: false,
2169
+ version: "v4",
2170
+ ...normalizeParams(params),
2171
+ });
2172
+ }
2173
+ function _uuidv6(Class, params) {
2174
+ return new Class({
2175
+ type: "string",
2176
+ format: "uuid",
2177
+ check: "string_format",
2178
+ abort: false,
2179
+ version: "v6",
2180
+ ...normalizeParams(params),
2181
+ });
2182
+ }
2183
+ function _uuidv7(Class, params) {
2184
+ return new Class({
2185
+ type: "string",
2186
+ format: "uuid",
2187
+ check: "string_format",
2188
+ abort: false,
2189
+ version: "v7",
2190
+ ...normalizeParams(params),
2191
+ });
2192
+ }
2193
+ function _url(Class, params) {
2194
+ return new Class({
2195
+ type: "string",
2196
+ format: "url",
2197
+ check: "string_format",
2198
+ abort: false,
2199
+ ...normalizeParams(params),
2200
+ });
2201
+ }
2202
+ function _emoji(Class, params) {
2203
+ return new Class({
2204
+ type: "string",
2205
+ format: "emoji",
2206
+ check: "string_format",
2207
+ abort: false,
2208
+ ...normalizeParams(params),
2209
+ });
2210
+ }
2211
+ function _nanoid(Class, params) {
2212
+ return new Class({
2213
+ type: "string",
2214
+ format: "nanoid",
2215
+ check: "string_format",
2216
+ abort: false,
2217
+ ...normalizeParams(params),
2218
+ });
2219
+ }
2220
+ function _cuid(Class, params) {
2221
+ return new Class({
2222
+ type: "string",
2223
+ format: "cuid",
2224
+ check: "string_format",
2225
+ abort: false,
2226
+ ...normalizeParams(params),
2227
+ });
2228
+ }
2229
+ function _cuid2(Class, params) {
2230
+ return new Class({
2231
+ type: "string",
2232
+ format: "cuid2",
2233
+ check: "string_format",
2234
+ abort: false,
2235
+ ...normalizeParams(params),
2236
+ });
2237
+ }
2238
+ function _ulid(Class, params) {
2239
+ return new Class({
2240
+ type: "string",
2241
+ format: "ulid",
2242
+ check: "string_format",
2243
+ abort: false,
2244
+ ...normalizeParams(params),
2245
+ });
2246
+ }
2247
+ function _xid(Class, params) {
2248
+ return new Class({
2249
+ type: "string",
2250
+ format: "xid",
2251
+ check: "string_format",
2252
+ abort: false,
2253
+ ...normalizeParams(params),
2254
+ });
2255
+ }
2256
+ function _ksuid(Class, params) {
2257
+ return new Class({
2258
+ type: "string",
2259
+ format: "ksuid",
2260
+ check: "string_format",
2261
+ abort: false,
2262
+ ...normalizeParams(params),
2263
+ });
2264
+ }
2265
+ function _ipv4(Class, params) {
2266
+ return new Class({
2267
+ type: "string",
2268
+ format: "ipv4",
2269
+ check: "string_format",
2270
+ abort: false,
2271
+ ...normalizeParams(params),
2272
+ });
2273
+ }
2274
+ function _ipv6(Class, params) {
2275
+ return new Class({
2276
+ type: "string",
2277
+ format: "ipv6",
2278
+ check: "string_format",
2279
+ abort: false,
2280
+ ...normalizeParams(params),
2281
+ });
2282
+ }
2283
+ function _cidrv4(Class, params) {
2284
+ return new Class({
2285
+ type: "string",
2286
+ format: "cidrv4",
2287
+ check: "string_format",
2288
+ abort: false,
2289
+ ...normalizeParams(params),
2290
+ });
2291
+ }
2292
+ function _cidrv6(Class, params) {
2293
+ return new Class({
2294
+ type: "string",
2295
+ format: "cidrv6",
2296
+ check: "string_format",
2297
+ abort: false,
2298
+ ...normalizeParams(params),
2299
+ });
2300
+ }
2301
+ function _base64(Class, params) {
2302
+ return new Class({
2303
+ type: "string",
2304
+ format: "base64",
2305
+ check: "string_format",
2306
+ abort: false,
2307
+ ...normalizeParams(params),
2308
+ });
2309
+ }
2310
+ function _base64url(Class, params) {
2311
+ return new Class({
2312
+ type: "string",
2313
+ format: "base64url",
2314
+ check: "string_format",
2315
+ abort: false,
2316
+ ...normalizeParams(params),
2317
+ });
2318
+ }
2319
+ function _e164(Class, params) {
2320
+ return new Class({
2321
+ type: "string",
2322
+ format: "e164",
2323
+ check: "string_format",
2324
+ abort: false,
2325
+ ...normalizeParams(params),
2326
+ });
2327
+ }
2328
+ function _jwt(Class, params) {
2329
+ return new Class({
2330
+ type: "string",
2331
+ format: "jwt",
2332
+ check: "string_format",
2333
+ abort: false,
2334
+ ...normalizeParams(params),
2335
+ });
2336
+ }
2337
+ function _isoDateTime(Class, params) {
2338
+ return new Class({
2339
+ type: "string",
2340
+ format: "datetime",
2341
+ check: "string_format",
2342
+ offset: false,
2343
+ local: false,
2344
+ precision: null,
2345
+ ...normalizeParams(params),
2346
+ });
2347
+ }
2348
+ function _isoDate(Class, params) {
2349
+ return new Class({
2350
+ type: "string",
2351
+ format: "date",
2352
+ check: "string_format",
2353
+ ...normalizeParams(params),
2354
+ });
2355
+ }
2356
+ function _isoTime(Class, params) {
2357
+ return new Class({
2358
+ type: "string",
2359
+ format: "time",
2360
+ check: "string_format",
2361
+ precision: null,
2362
+ ...normalizeParams(params),
2363
+ });
2364
+ }
2365
+ function _isoDuration(Class, params) {
2366
+ return new Class({
2367
+ type: "string",
2368
+ format: "duration",
2369
+ check: "string_format",
2370
+ ...normalizeParams(params),
2371
+ });
2372
+ }
2373
+ function _unknown(Class) {
2374
+ return new Class({
2375
+ type: "unknown",
2376
+ });
2377
+ }
2378
+ function _never(Class, params) {
2379
+ return new Class({
2380
+ type: "never",
2381
+ ...normalizeParams(params),
2382
+ });
2383
+ }
2384
+ function _maxLength(maximum, params) {
2385
+ const ch = new $ZodCheckMaxLength({
2386
+ check: "max_length",
2387
+ ...normalizeParams(params),
2388
+ maximum,
2389
+ });
2390
+ return ch;
2391
+ }
2392
+ function _minLength(minimum, params) {
2393
+ return new $ZodCheckMinLength({
2394
+ check: "min_length",
2395
+ ...normalizeParams(params),
2396
+ minimum,
2397
+ });
2398
+ }
2399
+ function _length(length, params) {
2400
+ return new $ZodCheckLengthEquals({
2401
+ check: "length_equals",
2402
+ ...normalizeParams(params),
2403
+ length,
2404
+ });
2405
+ }
2406
+ function _regex(pattern, params) {
2407
+ return new $ZodCheckRegex({
2408
+ check: "string_format",
2409
+ format: "regex",
2410
+ ...normalizeParams(params),
2411
+ pattern,
2412
+ });
2413
+ }
2414
+ function _lowercase(params) {
2415
+ return new $ZodCheckLowerCase({
2416
+ check: "string_format",
2417
+ format: "lowercase",
2418
+ ...normalizeParams(params),
2419
+ });
2420
+ }
2421
+ function _uppercase(params) {
2422
+ return new $ZodCheckUpperCase({
2423
+ check: "string_format",
2424
+ format: "uppercase",
2425
+ ...normalizeParams(params),
2426
+ });
2427
+ }
2428
+ function _includes(includes, params) {
2429
+ return new $ZodCheckIncludes({
2430
+ check: "string_format",
2431
+ format: "includes",
2432
+ ...normalizeParams(params),
2433
+ includes,
2434
+ });
2435
+ }
2436
+ function _startsWith(prefix, params) {
2437
+ return new $ZodCheckStartsWith({
2438
+ check: "string_format",
2439
+ format: "starts_with",
2440
+ ...normalizeParams(params),
2441
+ prefix,
2442
+ });
2443
+ }
2444
+ function _endsWith(suffix, params) {
2445
+ return new $ZodCheckEndsWith({
2446
+ check: "string_format",
2447
+ format: "ends_with",
2448
+ ...normalizeParams(params),
2449
+ suffix,
2450
+ });
2451
+ }
2452
+ function _overwrite(tx) {
2453
+ return new $ZodCheckOverwrite({
2454
+ check: "overwrite",
2455
+ tx,
2456
+ });
2457
+ }
2458
+ // normalize
2459
+ function _normalize(form) {
2460
+ return _overwrite((input) => input.normalize(form));
2461
+ }
2462
+ // trim
2463
+ function _trim() {
2464
+ return _overwrite((input) => input.trim());
2465
+ }
2466
+ // toLowerCase
2467
+ function _toLowerCase() {
2468
+ return _overwrite((input) => input.toLowerCase());
2469
+ }
2470
+ // toUpperCase
2471
+ function _toUpperCase() {
2472
+ return _overwrite((input) => input.toUpperCase());
2473
+ }
2474
+ // slugify
2475
+ function _slugify() {
2476
+ return _overwrite((input) => slugify(input));
2477
+ }
2478
+ function _array(Class, element, params) {
2479
+ return new Class({
2480
+ type: "array",
2481
+ element,
2482
+ // get element() {
2483
+ // return element;
2484
+ // },
2485
+ ...normalizeParams(params),
2486
+ });
2487
+ }
2488
+ // same as _custom but defaults to abort:false
2489
+ function _refine(Class, fn, _params) {
2490
+ const schema = new Class({
2491
+ type: "custom",
2492
+ check: "custom",
2493
+ fn: fn,
2494
+ ...normalizeParams(_params),
2495
+ });
2496
+ return schema;
2497
+ }
2498
+ function _superRefine(fn) {
2499
+ const ch = _check((payload) => {
2500
+ payload.addIssue = (issue$1) => {
2501
+ if (typeof issue$1 === "string") {
2502
+ payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
2503
+ }
2504
+ else {
2505
+ // for Zod 3 backwards compatibility
2506
+ const _issue = issue$1;
2507
+ if (_issue.fatal)
2508
+ _issue.continue = false;
2509
+ _issue.code ?? (_issue.code = "custom");
2510
+ _issue.input ?? (_issue.input = payload.value);
2511
+ _issue.inst ?? (_issue.inst = ch);
2512
+ _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...
2513
+ payload.issues.push(issue(_issue));
2514
+ }
2515
+ };
2516
+ return fn(payload.value, payload);
2517
+ });
2518
+ return ch;
2519
+ }
2520
+ function _check(fn, params) {
2521
+ const ch = new $ZodCheck({
2522
+ check: "custom",
2523
+ ...normalizeParams(params),
2524
+ });
2525
+ ch._zod.check = fn;
2526
+ return ch;
2527
+ }
2528
+
2529
+ // function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {
2530
+ // return {
2531
+ // processor: inputs.processor,
2532
+ // metadataRegistry: inputs.metadata ?? globalRegistry,
2533
+ // target: inputs.target ?? "draft-2020-12",
2534
+ // unrepresentable: inputs.unrepresentable ?? "throw",
2535
+ // };
2536
+ // }
2537
+ function initializeContext(params) {
2538
+ // Normalize target: convert old non-hyphenated versions to hyphenated versions
2539
+ let target = params?.target ?? "draft-2020-12";
2540
+ if (target === "draft-4")
2541
+ target = "draft-04";
2542
+ if (target === "draft-7")
2543
+ target = "draft-07";
2544
+ return {
2545
+ processors: params.processors ?? {},
2546
+ metadataRegistry: params?.metadata ?? globalRegistry,
2547
+ target,
2548
+ unrepresentable: params?.unrepresentable ?? "throw",
2549
+ override: params?.override ?? (() => { }),
2550
+ io: params?.io ?? "output",
2551
+ counter: 0,
2552
+ seen: new Map(),
2553
+ cycles: params?.cycles ?? "ref",
2554
+ reused: params?.reused ?? "inline",
2555
+ external: params?.external ?? undefined,
2556
+ };
2557
+ }
2558
+ function process(schema, ctx, _params = { path: [], schemaPath: [] }) {
2559
+ var _a;
2560
+ const def = schema._zod.def;
2561
+ // check for schema in seens
2562
+ const seen = ctx.seen.get(schema);
2563
+ if (seen) {
2564
+ seen.count++;
2565
+ // check if cycle
2566
+ const isCycle = _params.schemaPath.includes(schema);
2567
+ if (isCycle) {
2568
+ seen.cycle = _params.path;
2569
+ }
2570
+ return seen.schema;
2571
+ }
2572
+ // initialize
2573
+ const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
2574
+ ctx.seen.set(schema, result);
2575
+ // custom method overrides default behavior
2576
+ const overrideSchema = schema._zod.toJSONSchema?.();
2577
+ if (overrideSchema) {
2578
+ result.schema = overrideSchema;
2579
+ }
2580
+ else {
2581
+ const params = {
2582
+ ..._params,
2583
+ schemaPath: [..._params.schemaPath, schema],
2584
+ path: _params.path,
2585
+ };
2586
+ const parent = schema._zod.parent;
2587
+ if (parent) {
2588
+ // schema was cloned from another schema
2589
+ result.ref = parent;
2590
+ process(parent, ctx, params);
2591
+ ctx.seen.get(parent).isParent = true;
2592
+ }
2593
+ else if (schema._zod.processJSONSchema) {
2594
+ schema._zod.processJSONSchema(ctx, result.schema, params);
2595
+ }
2596
+ else {
2597
+ const _json = result.schema;
2598
+ const processor = ctx.processors[def.type];
2599
+ if (!processor) {
2600
+ throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
2601
+ }
2602
+ processor(schema, ctx, _json, params);
2603
+ }
2604
+ }
2605
+ // metadata
2606
+ const meta = ctx.metadataRegistry.get(schema);
2607
+ if (meta)
2608
+ Object.assign(result.schema, meta);
2609
+ if (ctx.io === "input" && isTransforming(schema)) {
2610
+ // examples/defaults only apply to output type of pipe
2611
+ delete result.schema.examples;
2612
+ delete result.schema.default;
2613
+ }
2614
+ // set prefault as default
2615
+ if (ctx.io === "input" && result.schema._prefault)
2616
+ (_a = result.schema).default ?? (_a.default = result.schema._prefault);
2617
+ delete result.schema._prefault;
2618
+ // pulling fresh from ctx.seen in case it was overwritten
2619
+ const _result = ctx.seen.get(schema);
2620
+ return _result.schema;
2621
+ }
2622
+ function extractDefs(ctx, schema
2623
+ // params: EmitParams
2624
+ ) {
2625
+ // iterate over seen map;
2626
+ const root = ctx.seen.get(schema);
2627
+ if (!root)
2628
+ throw new Error("Unprocessed schema. This is a bug in Zod.");
2629
+ // returns a ref to the schema
2630
+ // defId will be empty if the ref points to an external schema (or #)
2631
+ const makeURI = (entry) => {
2632
+ // comparing the seen objects because sometimes
2633
+ // multiple schemas map to the same seen object.
2634
+ // e.g. lazy
2635
+ // external is configured
2636
+ const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
2637
+ if (ctx.external) {
2638
+ const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`;
2639
+ // check if schema is in the external registry
2640
+ const uriGenerator = ctx.external.uri ?? ((id) => id);
2641
+ if (externalId) {
2642
+ return { ref: uriGenerator(externalId) };
2643
+ }
2644
+ // otherwise, add to __shared
2645
+ const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
2646
+ entry[1].defId = id; // set defId so it will be reused if needed
2647
+ return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
2648
+ }
2649
+ if (entry[1] === root) {
2650
+ return { ref: "#" };
2651
+ }
2652
+ // self-contained schema
2653
+ const uriPrefix = `#`;
2654
+ const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
2655
+ const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
2656
+ return { defId, ref: defUriPrefix + defId };
2657
+ };
2658
+ // stored cached version in `def` property
2659
+ // remove all properties, set $ref
2660
+ const extractToDef = (entry) => {
2661
+ // if the schema is already a reference, do not extract it
2662
+ if (entry[1].schema.$ref) {
2663
+ return;
2664
+ }
2665
+ const seen = entry[1];
2666
+ const { ref, defId } = makeURI(entry);
2667
+ seen.def = { ...seen.schema };
2668
+ // defId won't be set if the schema is a reference to an external schema
2669
+ // or if the schema is the root schema
2670
+ if (defId)
2671
+ seen.defId = defId;
2672
+ // wipe away all properties except $ref
2673
+ const schema = seen.schema;
2674
+ for (const key in schema) {
2675
+ delete schema[key];
2676
+ }
2677
+ schema.$ref = ref;
2678
+ };
2679
+ // throw on cycles
2680
+ // break cycles
2681
+ if (ctx.cycles === "throw") {
2682
+ for (const entry of ctx.seen.entries()) {
2683
+ const seen = entry[1];
2684
+ if (seen.cycle) {
2685
+ throw new Error("Cycle detected: " +
2686
+ `#/${seen.cycle?.join("/")}/<root>` +
2687
+ '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
2688
+ }
2689
+ }
2690
+ }
2691
+ // extract schemas into $defs
2692
+ for (const entry of ctx.seen.entries()) {
2693
+ const seen = entry[1];
2694
+ // convert root schema to # $ref
2695
+ if (schema === entry[0]) {
2696
+ extractToDef(entry); // this has special handling for the root schema
2697
+ continue;
2698
+ }
2699
+ // extract schemas that are in the external registry
2700
+ if (ctx.external) {
2701
+ const ext = ctx.external.registry.get(entry[0])?.id;
2702
+ if (schema !== entry[0] && ext) {
2703
+ extractToDef(entry);
2704
+ continue;
2705
+ }
2706
+ }
2707
+ // extract schemas with `id` meta
2708
+ const id = ctx.metadataRegistry.get(entry[0])?.id;
2709
+ if (id) {
2710
+ extractToDef(entry);
2711
+ continue;
2712
+ }
2713
+ // break cycles
2714
+ if (seen.cycle) {
2715
+ // any
2716
+ extractToDef(entry);
2717
+ continue;
2718
+ }
2719
+ // extract reused schemas
2720
+ if (seen.count > 1) {
2721
+ if (ctx.reused === "ref") {
2722
+ extractToDef(entry);
2723
+ // biome-ignore lint:
2724
+ continue;
2725
+ }
2726
+ }
2727
+ }
2728
+ }
2729
+ function finalize(ctx, schema) {
2730
+ //
2731
+ // iterate over seen map;
2732
+ const root = ctx.seen.get(schema);
2733
+ if (!root)
2734
+ throw new Error("Unprocessed schema. This is a bug in Zod.");
2735
+ // flatten _refs
2736
+ const flattenRef = (zodSchema) => {
2737
+ const seen = ctx.seen.get(zodSchema);
2738
+ const schema = seen.def ?? seen.schema;
2739
+ const _cached = { ...schema };
2740
+ // already seen
2741
+ if (seen.ref === null) {
2742
+ return;
2743
+ }
2744
+ // flatten ref if defined
2745
+ const ref = seen.ref;
2746
+ seen.ref = null; // prevent recursion
2747
+ if (ref) {
2748
+ flattenRef(ref);
2749
+ // merge referenced schema into current
2750
+ const refSchema = ctx.seen.get(ref).schema;
2751
+ if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
2752
+ schema.allOf = schema.allOf ?? [];
2753
+ schema.allOf.push(refSchema);
2754
+ }
2755
+ else {
2756
+ Object.assign(schema, refSchema);
2757
+ Object.assign(schema, _cached); // prevent overwriting any fields in the original schema
2758
+ }
2759
+ }
2760
+ // execute overrides
2761
+ if (!seen.isParent)
2762
+ ctx.override({
2763
+ zodSchema: zodSchema,
2764
+ jsonSchema: schema,
2765
+ path: seen.path ?? [],
2766
+ });
2767
+ };
2768
+ for (const entry of [...ctx.seen.entries()].reverse()) {
2769
+ flattenRef(entry[0]);
2770
+ }
2771
+ const result = {};
2772
+ if (ctx.target === "draft-2020-12") {
2773
+ result.$schema = "https://json-schema.org/draft/2020-12/schema";
2774
+ }
2775
+ else if (ctx.target === "draft-07") {
2776
+ result.$schema = "http://json-schema.org/draft-07/schema#";
2777
+ }
2778
+ else if (ctx.target === "draft-04") {
2779
+ result.$schema = "http://json-schema.org/draft-04/schema#";
2780
+ }
2781
+ else if (ctx.target === "openapi-3.0") ;
2782
+ else ;
2783
+ if (ctx.external?.uri) {
2784
+ const id = ctx.external.registry.get(schema)?.id;
2785
+ if (!id)
2786
+ throw new Error("Schema is missing an `id` property");
2787
+ result.$id = ctx.external.uri(id);
2788
+ }
2789
+ Object.assign(result, root.def ?? root.schema);
2790
+ // build defs object
2791
+ const defs = ctx.external?.defs ?? {};
2792
+ for (const entry of ctx.seen.entries()) {
2793
+ const seen = entry[1];
2794
+ if (seen.def && seen.defId) {
2795
+ defs[seen.defId] = seen.def;
2796
+ }
2797
+ }
2798
+ // set definitions in result
2799
+ if (ctx.external) ;
2800
+ else {
2801
+ if (Object.keys(defs).length > 0) {
2802
+ if (ctx.target === "draft-2020-12") {
2803
+ result.$defs = defs;
2804
+ }
2805
+ else {
2806
+ result.definitions = defs;
2807
+ }
2808
+ }
2809
+ }
2810
+ try {
2811
+ // this "finalizes" this schema and ensures all cycles are removed
2812
+ // each call to finalize() is functionally independent
2813
+ // though the seen map is shared
2814
+ const finalized = JSON.parse(JSON.stringify(result));
2815
+ Object.defineProperty(finalized, "~standard", {
2816
+ value: {
2817
+ ...schema["~standard"],
2818
+ jsonSchema: {
2819
+ input: createStandardJSONSchemaMethod(schema, "input"),
2820
+ output: createStandardJSONSchemaMethod(schema, "output"),
2821
+ },
2822
+ },
2823
+ enumerable: false,
2824
+ writable: false,
2825
+ });
2826
+ return finalized;
2827
+ }
2828
+ catch (_err) {
2829
+ throw new Error("Error converting schema to JSON.");
2830
+ }
2831
+ }
2832
+ function isTransforming(_schema, _ctx) {
2833
+ const ctx = _ctx ?? { seen: new Set() };
2834
+ if (ctx.seen.has(_schema))
2835
+ return false;
2836
+ ctx.seen.add(_schema);
2837
+ const def = _schema._zod.def;
2838
+ if (def.type === "transform")
2839
+ return true;
2840
+ if (def.type === "array")
2841
+ return isTransforming(def.element, ctx);
2842
+ if (def.type === "set")
2843
+ return isTransforming(def.valueType, ctx);
2844
+ if (def.type === "lazy")
2845
+ return isTransforming(def.getter(), ctx);
2846
+ if (def.type === "promise" ||
2847
+ def.type === "optional" ||
2848
+ def.type === "nonoptional" ||
2849
+ def.type === "nullable" ||
2850
+ def.type === "readonly" ||
2851
+ def.type === "default" ||
2852
+ def.type === "prefault") {
2853
+ return isTransforming(def.innerType, ctx);
2854
+ }
2855
+ if (def.type === "intersection") {
2856
+ return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
2857
+ }
2858
+ if (def.type === "record" || def.type === "map") {
2859
+ return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
2860
+ }
2861
+ if (def.type === "pipe") {
2862
+ return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
2863
+ }
2864
+ if (def.type === "object") {
2865
+ for (const key in def.shape) {
2866
+ if (isTransforming(def.shape[key], ctx))
2867
+ return true;
2868
+ }
2869
+ return false;
2870
+ }
2871
+ if (def.type === "union") {
2872
+ for (const option of def.options) {
2873
+ if (isTransforming(option, ctx))
2874
+ return true;
2875
+ }
2876
+ return false;
2877
+ }
2878
+ if (def.type === "tuple") {
2879
+ for (const item of def.items) {
2880
+ if (isTransforming(item, ctx))
2881
+ return true;
2882
+ }
2883
+ if (def.rest && isTransforming(def.rest, ctx))
2884
+ return true;
2885
+ return false;
2886
+ }
2887
+ return false;
2888
+ }
2889
+ /**
2890
+ * Creates a toJSONSchema method for a schema instance.
2891
+ * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.
2892
+ */
2893
+ const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
2894
+ const ctx = initializeContext({ ...params, processors });
2895
+ process(schema, ctx);
2896
+ extractDefs(ctx, schema);
2897
+ return finalize(ctx, schema);
2898
+ };
2899
+ const createStandardJSONSchemaMethod = (schema, io) => (params) => {
2900
+ const { libraryOptions, target } = params ?? {};
2901
+ const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors: {} });
2902
+ process(schema, ctx);
2903
+ extractDefs(ctx, schema);
2904
+ return finalize(ctx, schema);
2905
+ };
2906
+
2907
+ const formatMap = {
2908
+ guid: "uuid",
2909
+ url: "uri",
2910
+ datetime: "date-time",
2911
+ json_string: "json-string",
2912
+ regex: "", // do not set
2913
+ };
2914
+ // ==================== SIMPLE TYPE PROCESSORS ====================
2915
+ const stringProcessor = (schema, ctx, _json, _params) => {
2916
+ const json = _json;
2917
+ json.type = "string";
2918
+ const { minimum, maximum, format, patterns, contentEncoding } = schema._zod
2919
+ .bag;
2920
+ if (typeof minimum === "number")
2921
+ json.minLength = minimum;
2922
+ if (typeof maximum === "number")
2923
+ json.maxLength = maximum;
2924
+ // custom pattern overrides format
2925
+ if (format) {
2926
+ json.format = formatMap[format] ?? format;
2927
+ if (json.format === "")
2928
+ delete json.format; // empty format is not valid
2929
+ }
2930
+ if (contentEncoding)
2931
+ json.contentEncoding = contentEncoding;
2932
+ if (patterns && patterns.size > 0) {
2933
+ const regexes = [...patterns];
2934
+ if (regexes.length === 1)
2935
+ json.pattern = regexes[0].source;
2936
+ else if (regexes.length > 1) {
2937
+ json.allOf = [
2938
+ ...regexes.map((regex) => ({
2939
+ ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0"
2940
+ ? { type: "string" }
2941
+ : {}),
2942
+ pattern: regex.source,
2943
+ })),
2944
+ ];
2945
+ }
2946
+ }
2947
+ };
2948
+ const neverProcessor = (_schema, _ctx, json, _params) => {
2949
+ json.not = {};
2950
+ };
2951
+ const unknownProcessor = (_schema, _ctx, _json, _params) => {
2952
+ // empty schema accepts anything
2953
+ };
2954
+ const enumProcessor = (schema, _ctx, json, _params) => {
2955
+ const def = schema._zod.def;
2956
+ const values = getEnumValues(def.entries);
2957
+ // Number enums can have both string and number values
2958
+ if (values.every((v) => typeof v === "number"))
2959
+ json.type = "number";
2960
+ if (values.every((v) => typeof v === "string"))
2961
+ json.type = "string";
2962
+ json.enum = values;
2963
+ };
2964
+ const customProcessor = (_schema, ctx, _json, _params) => {
2965
+ if (ctx.unrepresentable === "throw") {
2966
+ throw new Error("Custom types cannot be represented in JSON Schema");
2967
+ }
2968
+ };
2969
+ const transformProcessor = (_schema, ctx, _json, _params) => {
2970
+ if (ctx.unrepresentable === "throw") {
2971
+ throw new Error("Transforms cannot be represented in JSON Schema");
2972
+ }
2973
+ };
2974
+ // ==================== COMPOSITE TYPE PROCESSORS ====================
2975
+ const arrayProcessor = (schema, ctx, _json, params) => {
2976
+ const json = _json;
2977
+ const def = schema._zod.def;
2978
+ const { minimum, maximum } = schema._zod.bag;
2979
+ if (typeof minimum === "number")
2980
+ json.minItems = minimum;
2981
+ if (typeof maximum === "number")
2982
+ json.maxItems = maximum;
2983
+ json.type = "array";
2984
+ json.items = process(def.element, ctx, { ...params, path: [...params.path, "items"] });
2985
+ };
2986
+ const objectProcessor = (schema, ctx, _json, params) => {
2987
+ const json = _json;
2988
+ const def = schema._zod.def;
2989
+ json.type = "object";
2990
+ json.properties = {};
2991
+ const shape = def.shape;
2992
+ for (const key in shape) {
2993
+ json.properties[key] = process(shape[key], ctx, {
2994
+ ...params,
2995
+ path: [...params.path, "properties", key],
2996
+ });
2997
+ }
2998
+ // required keys
2999
+ const allKeys = new Set(Object.keys(shape));
3000
+ const requiredKeys = new Set([...allKeys].filter((key) => {
3001
+ const v = def.shape[key]._zod;
3002
+ if (ctx.io === "input") {
3003
+ return v.optin === undefined;
3004
+ }
3005
+ else {
3006
+ return v.optout === undefined;
3007
+ }
3008
+ }));
3009
+ if (requiredKeys.size > 0) {
3010
+ json.required = Array.from(requiredKeys);
3011
+ }
3012
+ // catchall
3013
+ if (def.catchall?._zod.def.type === "never") {
3014
+ // strict
3015
+ json.additionalProperties = false;
3016
+ }
3017
+ else if (!def.catchall) {
3018
+ // regular
3019
+ if (ctx.io === "output")
3020
+ json.additionalProperties = false;
3021
+ }
3022
+ else if (def.catchall) {
3023
+ json.additionalProperties = process(def.catchall, ctx, {
3024
+ ...params,
3025
+ path: [...params.path, "additionalProperties"],
3026
+ });
3027
+ }
3028
+ };
3029
+ const unionProcessor = (schema, ctx, json, params) => {
3030
+ const def = schema._zod.def;
3031
+ // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)
3032
+ // This includes both z.xor() and discriminated unions
3033
+ const isExclusive = def.inclusive === false;
3034
+ const options = def.options.map((x, i) => process(x, ctx, {
3035
+ ...params,
3036
+ path: [...params.path, isExclusive ? "oneOf" : "anyOf", i],
3037
+ }));
3038
+ if (isExclusive) {
3039
+ json.oneOf = options;
3040
+ }
3041
+ else {
3042
+ json.anyOf = options;
3043
+ }
3044
+ };
3045
+ const intersectionProcessor = (schema, ctx, json, params) => {
3046
+ const def = schema._zod.def;
3047
+ const a = process(def.left, ctx, {
3048
+ ...params,
3049
+ path: [...params.path, "allOf", 0],
3050
+ });
3051
+ const b = process(def.right, ctx, {
3052
+ ...params,
3053
+ path: [...params.path, "allOf", 1],
3054
+ });
3055
+ const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
3056
+ const allOf = [
3057
+ ...(isSimpleIntersection(a) ? a.allOf : [a]),
3058
+ ...(isSimpleIntersection(b) ? b.allOf : [b]),
3059
+ ];
3060
+ json.allOf = allOf;
3061
+ };
3062
+ const nullableProcessor = (schema, ctx, json, params) => {
3063
+ const def = schema._zod.def;
3064
+ const inner = process(def.innerType, ctx, params);
3065
+ const seen = ctx.seen.get(schema);
3066
+ if (ctx.target === "openapi-3.0") {
3067
+ seen.ref = def.innerType;
3068
+ json.nullable = true;
3069
+ }
3070
+ else {
3071
+ json.anyOf = [inner, { type: "null" }];
3072
+ }
3073
+ };
3074
+ const nonoptionalProcessor = (schema, ctx, _json, params) => {
3075
+ const def = schema._zod.def;
3076
+ process(def.innerType, ctx, params);
3077
+ const seen = ctx.seen.get(schema);
3078
+ seen.ref = def.innerType;
3079
+ };
3080
+ const defaultProcessor = (schema, ctx, json, params) => {
3081
+ const def = schema._zod.def;
3082
+ process(def.innerType, ctx, params);
3083
+ const seen = ctx.seen.get(schema);
3084
+ seen.ref = def.innerType;
3085
+ json.default = JSON.parse(JSON.stringify(def.defaultValue));
3086
+ };
3087
+ const prefaultProcessor = (schema, ctx, json, params) => {
3088
+ const def = schema._zod.def;
3089
+ process(def.innerType, ctx, params);
3090
+ const seen = ctx.seen.get(schema);
3091
+ seen.ref = def.innerType;
3092
+ if (ctx.io === "input")
3093
+ json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
3094
+ };
3095
+ const catchProcessor = (schema, ctx, json, params) => {
3096
+ const def = schema._zod.def;
3097
+ process(def.innerType, ctx, params);
3098
+ const seen = ctx.seen.get(schema);
3099
+ seen.ref = def.innerType;
3100
+ let catchValue;
3101
+ try {
3102
+ catchValue = def.catchValue(undefined);
3103
+ }
3104
+ catch {
3105
+ throw new Error("Dynamic catch values are not supported in JSON Schema");
3106
+ }
3107
+ json.default = catchValue;
3108
+ };
3109
+ const pipeProcessor = (schema, ctx, _json, params) => {
3110
+ const def = schema._zod.def;
3111
+ const innerType = ctx.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out;
3112
+ process(innerType, ctx, params);
3113
+ const seen = ctx.seen.get(schema);
3114
+ seen.ref = innerType;
3115
+ };
3116
+ const readonlyProcessor = (schema, ctx, json, params) => {
3117
+ const def = schema._zod.def;
3118
+ process(def.innerType, ctx, params);
3119
+ const seen = ctx.seen.get(schema);
3120
+ seen.ref = def.innerType;
3121
+ json.readOnly = true;
3122
+ };
3123
+ const optionalProcessor = (schema, ctx, _json, params) => {
3124
+ const def = schema._zod.def;
3125
+ process(def.innerType, ctx, params);
3126
+ const seen = ctx.seen.get(schema);
3127
+ seen.ref = def.innerType;
3128
+ };
3129
+
3130
+ const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
3131
+ $ZodISODateTime.init(inst, def);
3132
+ ZodStringFormat.init(inst, def);
3133
+ });
3134
+ function datetime(params) {
3135
+ return _isoDateTime(ZodISODateTime, params);
3136
+ }
3137
+ const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => {
3138
+ $ZodISODate.init(inst, def);
3139
+ ZodStringFormat.init(inst, def);
3140
+ });
3141
+ function date(params) {
3142
+ return _isoDate(ZodISODate, params);
3143
+ }
3144
+ const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => {
3145
+ $ZodISOTime.init(inst, def);
3146
+ ZodStringFormat.init(inst, def);
3147
+ });
3148
+ function time(params) {
3149
+ return _isoTime(ZodISOTime, params);
3150
+ }
3151
+ const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => {
3152
+ $ZodISODuration.init(inst, def);
3153
+ ZodStringFormat.init(inst, def);
3154
+ });
3155
+ function duration(params) {
3156
+ return _isoDuration(ZodISODuration, params);
3157
+ }
3158
+
3159
+ const initializer = (inst, issues) => {
3160
+ $ZodError.init(inst, issues);
3161
+ inst.name = "ZodError";
3162
+ Object.defineProperties(inst, {
3163
+ format: {
3164
+ value: (mapper) => formatError(inst, mapper),
3165
+ // enumerable: false,
3166
+ },
3167
+ flatten: {
3168
+ value: (mapper) => flattenError(inst, mapper),
3169
+ // enumerable: false,
3170
+ },
3171
+ addIssue: {
3172
+ value: (issue) => {
3173
+ inst.issues.push(issue);
3174
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
3175
+ },
3176
+ // enumerable: false,
3177
+ },
3178
+ addIssues: {
3179
+ value: (issues) => {
3180
+ inst.issues.push(...issues);
3181
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
3182
+ },
3183
+ // enumerable: false,
3184
+ },
3185
+ isEmpty: {
3186
+ get() {
3187
+ return inst.issues.length === 0;
3188
+ },
3189
+ // enumerable: false,
3190
+ },
3191
+ });
3192
+ // Object.defineProperty(inst, "isEmpty", {
3193
+ // get() {
3194
+ // return inst.issues.length === 0;
3195
+ // },
3196
+ // });
3197
+ };
3198
+ const ZodRealError = $constructor("ZodError", initializer, {
3199
+ Parent: Error,
3200
+ });
3201
+ // /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
3202
+ // export type ErrorMapCtx = core.$ZodErrorMapCtx;
3203
+
3204
+ const parse = /* @__PURE__ */ _parse(ZodRealError);
3205
+ const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
3206
+ const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
3207
+ const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
3208
+ // Codec functions
3209
+ const encode = /* @__PURE__ */ _encode(ZodRealError);
3210
+ const decode = /* @__PURE__ */ _decode(ZodRealError);
3211
+ const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
3212
+ const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
3213
+ const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
3214
+ const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
3215
+ const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
3216
+ const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
3217
+
3218
+ const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
3219
+ $ZodType.init(inst, def);
3220
+ Object.assign(inst["~standard"], {
3221
+ jsonSchema: {
3222
+ input: createStandardJSONSchemaMethod(inst, "input"),
3223
+ output: createStandardJSONSchemaMethod(inst, "output"),
3224
+ },
3225
+ });
3226
+ inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
3227
+ inst.def = def;
3228
+ inst.type = def.type;
3229
+ Object.defineProperty(inst, "_def", { value: def });
3230
+ // base methods
3231
+ inst.check = (...checks) => {
3232
+ return inst.clone(mergeDefs(def, {
3233
+ checks: [
3234
+ ...(def.checks ?? []),
3235
+ ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
3236
+ ],
3237
+ }));
3238
+ };
3239
+ inst.clone = (def, params) => clone(inst, def, params);
3240
+ inst.brand = () => inst;
3241
+ inst.register = ((reg, meta) => {
3242
+ reg.add(inst, meta);
3243
+ return inst;
3244
+ });
3245
+ // parsing
3246
+ inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
3247
+ inst.safeParse = (data, params) => safeParse(inst, data, params);
3248
+ inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
3249
+ inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
3250
+ inst.spa = inst.safeParseAsync;
3251
+ // encoding/decoding
3252
+ inst.encode = (data, params) => encode(inst, data, params);
3253
+ inst.decode = (data, params) => decode(inst, data, params);
3254
+ inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
3255
+ inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
3256
+ inst.safeEncode = (data, params) => safeEncode(inst, data, params);
3257
+ inst.safeDecode = (data, params) => safeDecode(inst, data, params);
3258
+ inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
3259
+ inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
3260
+ // refinements
3261
+ inst.refine = (check, params) => inst.check(refine(check, params));
3262
+ inst.superRefine = (refinement) => inst.check(superRefine(refinement));
3263
+ inst.overwrite = (fn) => inst.check(_overwrite(fn));
3264
+ // wrappers
3265
+ inst.optional = () => optional(inst);
3266
+ inst.nullable = () => nullable(inst);
3267
+ inst.nullish = () => optional(nullable(inst));
3268
+ inst.nonoptional = (params) => nonoptional(inst, params);
3269
+ inst.array = () => array(inst);
3270
+ inst.or = (arg) => union([inst, arg]);
3271
+ inst.and = (arg) => intersection(inst, arg);
3272
+ inst.transform = (tx) => pipe(inst, transform(tx));
3273
+ inst.default = (def) => _default(inst, def);
3274
+ inst.prefault = (def) => prefault(inst, def);
3275
+ // inst.coalesce = (def, params) => coalesce(inst, def, params);
3276
+ inst.catch = (params) => _catch(inst, params);
3277
+ inst.pipe = (target) => pipe(inst, target);
3278
+ inst.readonly = () => readonly(inst);
3279
+ // meta
3280
+ inst.describe = (description) => {
3281
+ const cl = inst.clone();
3282
+ globalRegistry.add(cl, { description });
3283
+ return cl;
3284
+ };
3285
+ Object.defineProperty(inst, "description", {
3286
+ get() {
3287
+ return globalRegistry.get(inst)?.description;
3288
+ },
3289
+ configurable: true,
3290
+ });
3291
+ inst.meta = (...args) => {
3292
+ if (args.length === 0) {
3293
+ return globalRegistry.get(inst);
3294
+ }
3295
+ const cl = inst.clone();
3296
+ globalRegistry.add(cl, args[0]);
3297
+ return cl;
3298
+ };
3299
+ // helpers
3300
+ inst.isOptional = () => inst.safeParse(undefined).success;
3301
+ inst.isNullable = () => inst.safeParse(null).success;
3302
+ return inst;
3303
+ });
3304
+ /** @internal */
3305
+ const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => {
3306
+ $ZodString.init(inst, def);
3307
+ ZodType.init(inst, def);
3308
+ inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json);
3309
+ const bag = inst._zod.bag;
3310
+ inst.format = bag.format ?? null;
3311
+ inst.minLength = bag.minimum ?? null;
3312
+ inst.maxLength = bag.maximum ?? null;
3313
+ // validations
3314
+ inst.regex = (...args) => inst.check(_regex(...args));
3315
+ inst.includes = (...args) => inst.check(_includes(...args));
3316
+ inst.startsWith = (...args) => inst.check(_startsWith(...args));
3317
+ inst.endsWith = (...args) => inst.check(_endsWith(...args));
3318
+ inst.min = (...args) => inst.check(_minLength(...args));
3319
+ inst.max = (...args) => inst.check(_maxLength(...args));
3320
+ inst.length = (...args) => inst.check(_length(...args));
3321
+ inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
3322
+ inst.lowercase = (params) => inst.check(_lowercase(params));
3323
+ inst.uppercase = (params) => inst.check(_uppercase(params));
3324
+ // transforms
3325
+ inst.trim = () => inst.check(_trim());
3326
+ inst.normalize = (...args) => inst.check(_normalize(...args));
3327
+ inst.toLowerCase = () => inst.check(_toLowerCase());
3328
+ inst.toUpperCase = () => inst.check(_toUpperCase());
3329
+ inst.slugify = () => inst.check(_slugify());
3330
+ });
3331
+ const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => {
3332
+ $ZodString.init(inst, def);
3333
+ _ZodString.init(inst, def);
3334
+ inst.email = (params) => inst.check(_email(ZodEmail, params));
3335
+ inst.url = (params) => inst.check(_url(ZodURL, params));
3336
+ inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
3337
+ inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
3338
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
3339
+ inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
3340
+ inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
3341
+ inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
3342
+ inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
3343
+ inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
3344
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
3345
+ inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
3346
+ inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
3347
+ inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
3348
+ inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
3349
+ inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
3350
+ inst.xid = (params) => inst.check(_xid(ZodXID, params));
3351
+ inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
3352
+ inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
3353
+ inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
3354
+ inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
3355
+ inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
3356
+ inst.e164 = (params) => inst.check(_e164(ZodE164, params));
3357
+ // iso
3358
+ inst.datetime = (params) => inst.check(datetime(params));
3359
+ inst.date = (params) => inst.check(date(params));
3360
+ inst.time = (params) => inst.check(time(params));
3361
+ inst.duration = (params) => inst.check(duration(params));
3362
+ });
3363
+ function string(params) {
3364
+ return _string(ZodString, params);
3365
+ }
3366
+ const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => {
3367
+ $ZodStringFormat.init(inst, def);
3368
+ _ZodString.init(inst, def);
3369
+ });
3370
+ const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => {
3371
+ // ZodStringFormat.init(inst, def);
3372
+ $ZodEmail.init(inst, def);
3373
+ ZodStringFormat.init(inst, def);
3374
+ });
3375
+ const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => {
3376
+ // ZodStringFormat.init(inst, def);
3377
+ $ZodGUID.init(inst, def);
3378
+ ZodStringFormat.init(inst, def);
3379
+ });
3380
+ const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => {
3381
+ // ZodStringFormat.init(inst, def);
3382
+ $ZodUUID.init(inst, def);
3383
+ ZodStringFormat.init(inst, def);
3384
+ });
3385
+ const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
3386
+ // ZodStringFormat.init(inst, def);
3387
+ $ZodURL.init(inst, def);
3388
+ ZodStringFormat.init(inst, def);
3389
+ });
3390
+ const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => {
3391
+ // ZodStringFormat.init(inst, def);
3392
+ $ZodEmoji.init(inst, def);
3393
+ ZodStringFormat.init(inst, def);
3394
+ });
3395
+ const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => {
3396
+ // ZodStringFormat.init(inst, def);
3397
+ $ZodNanoID.init(inst, def);
3398
+ ZodStringFormat.init(inst, def);
3399
+ });
3400
+ const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => {
3401
+ // ZodStringFormat.init(inst, def);
3402
+ $ZodCUID.init(inst, def);
3403
+ ZodStringFormat.init(inst, def);
3404
+ });
3405
+ const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => {
3406
+ // ZodStringFormat.init(inst, def);
3407
+ $ZodCUID2.init(inst, def);
3408
+ ZodStringFormat.init(inst, def);
3409
+ });
3410
+ const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => {
3411
+ // ZodStringFormat.init(inst, def);
3412
+ $ZodULID.init(inst, def);
3413
+ ZodStringFormat.init(inst, def);
3414
+ });
3415
+ const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => {
3416
+ // ZodStringFormat.init(inst, def);
3417
+ $ZodXID.init(inst, def);
3418
+ ZodStringFormat.init(inst, def);
3419
+ });
3420
+ const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => {
3421
+ // ZodStringFormat.init(inst, def);
3422
+ $ZodKSUID.init(inst, def);
3423
+ ZodStringFormat.init(inst, def);
3424
+ });
3425
+ const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => {
3426
+ // ZodStringFormat.init(inst, def);
3427
+ $ZodIPv4.init(inst, def);
3428
+ ZodStringFormat.init(inst, def);
3429
+ });
3430
+ const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => {
3431
+ // ZodStringFormat.init(inst, def);
3432
+ $ZodIPv6.init(inst, def);
3433
+ ZodStringFormat.init(inst, def);
3434
+ });
3435
+ const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => {
3436
+ $ZodCIDRv4.init(inst, def);
3437
+ ZodStringFormat.init(inst, def);
3438
+ });
3439
+ const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => {
3440
+ $ZodCIDRv6.init(inst, def);
3441
+ ZodStringFormat.init(inst, def);
3442
+ });
3443
+ const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => {
3444
+ // ZodStringFormat.init(inst, def);
3445
+ $ZodBase64.init(inst, def);
3446
+ ZodStringFormat.init(inst, def);
3447
+ });
3448
+ const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => {
3449
+ // ZodStringFormat.init(inst, def);
3450
+ $ZodBase64URL.init(inst, def);
3451
+ ZodStringFormat.init(inst, def);
3452
+ });
3453
+ const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => {
3454
+ // ZodStringFormat.init(inst, def);
3455
+ $ZodE164.init(inst, def);
3456
+ ZodStringFormat.init(inst, def);
3457
+ });
3458
+ const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => {
3459
+ // ZodStringFormat.init(inst, def);
3460
+ $ZodJWT.init(inst, def);
3461
+ ZodStringFormat.init(inst, def);
3462
+ });
3463
+ const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => {
3464
+ $ZodUnknown.init(inst, def);
3465
+ ZodType.init(inst, def);
3466
+ inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor();
3467
+ });
3468
+ function unknown() {
3469
+ return _unknown(ZodUnknown);
3470
+ }
3471
+ const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => {
3472
+ $ZodNever.init(inst, def);
3473
+ ZodType.init(inst, def);
3474
+ inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json);
3475
+ });
3476
+ function never(params) {
3477
+ return _never(ZodNever, params);
3478
+ }
3479
+ const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => {
3480
+ $ZodArray.init(inst, def);
3481
+ ZodType.init(inst, def);
3482
+ inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
3483
+ inst.element = def.element;
3484
+ inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
3485
+ inst.nonempty = (params) => inst.check(_minLength(1, params));
3486
+ inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
3487
+ inst.length = (len, params) => inst.check(_length(len, params));
3488
+ inst.unwrap = () => inst.element;
3489
+ });
3490
+ function array(element, params) {
3491
+ return _array(ZodArray, element, params);
3492
+ }
3493
+ const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
3494
+ $ZodObjectJIT.init(inst, def);
3495
+ ZodType.init(inst, def);
3496
+ inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
3497
+ defineLazy(inst, "shape", () => {
3498
+ return def.shape;
3499
+ });
3500
+ inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
3501
+ inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });
3502
+ inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
3503
+ inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
3504
+ inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
3505
+ inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });
3506
+ inst.extend = (incoming) => {
3507
+ return extend(inst, incoming);
3508
+ };
3509
+ inst.safeExtend = (incoming) => {
3510
+ return safeExtend(inst, incoming);
3511
+ };
3512
+ inst.merge = (other) => merge(inst, other);
3513
+ inst.pick = (mask) => pick(inst, mask);
3514
+ inst.omit = (mask) => omit(inst, mask);
3515
+ inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
3516
+ inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
3517
+ });
3518
+ function object(shape, params) {
3519
+ const def = {
3520
+ type: "object",
3521
+ shape: shape ?? {},
3522
+ ...normalizeParams(params),
3523
+ };
3524
+ return new ZodObject(def);
3525
+ }
3526
+ const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => {
3527
+ $ZodUnion.init(inst, def);
3528
+ ZodType.init(inst, def);
3529
+ inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params);
3530
+ inst.options = def.options;
3531
+ });
3532
+ function union(options, params) {
3533
+ return new ZodUnion({
3534
+ type: "union",
3535
+ options: options,
3536
+ ...normalizeParams(params),
3537
+ });
3538
+ }
3539
+ const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => {
3540
+ $ZodIntersection.init(inst, def);
3541
+ ZodType.init(inst, def);
3542
+ inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
3543
+ });
3544
+ function intersection(left, right) {
3545
+ return new ZodIntersection({
3546
+ type: "intersection",
3547
+ left: left,
3548
+ right: right,
3549
+ });
3550
+ }
3551
+ const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => {
3552
+ $ZodEnum.init(inst, def);
3553
+ ZodType.init(inst, def);
3554
+ inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json);
3555
+ inst.enum = def.entries;
3556
+ inst.options = Object.values(def.entries);
3557
+ const keys = new Set(Object.keys(def.entries));
3558
+ inst.extract = (values, params) => {
3559
+ const newEntries = {};
3560
+ for (const value of values) {
3561
+ if (keys.has(value)) {
3562
+ newEntries[value] = def.entries[value];
3563
+ }
3564
+ else
3565
+ throw new Error(`Key ${value} not found in enum`);
3566
+ }
3567
+ return new ZodEnum({
3568
+ ...def,
3569
+ checks: [],
3570
+ ...normalizeParams(params),
3571
+ entries: newEntries,
3572
+ });
3573
+ };
3574
+ inst.exclude = (values, params) => {
3575
+ const newEntries = { ...def.entries };
3576
+ for (const value of values) {
3577
+ if (keys.has(value)) {
3578
+ delete newEntries[value];
3579
+ }
3580
+ else
3581
+ throw new Error(`Key ${value} not found in enum`);
3582
+ }
3583
+ return new ZodEnum({
3584
+ ...def,
3585
+ checks: [],
3586
+ ...normalizeParams(params),
3587
+ entries: newEntries,
3588
+ });
3589
+ };
3590
+ });
3591
+ function _enum(values, params) {
3592
+ const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
3593
+ return new ZodEnum({
3594
+ type: "enum",
3595
+ entries,
3596
+ ...normalizeParams(params),
3597
+ });
3598
+ }
3599
+ const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => {
3600
+ $ZodTransform.init(inst, def);
3601
+ ZodType.init(inst, def);
3602
+ inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx);
3603
+ inst._zod.parse = (payload, _ctx) => {
3604
+ if (_ctx.direction === "backward") {
3605
+ throw new $ZodEncodeError(inst.constructor.name);
3606
+ }
3607
+ payload.addIssue = (issue$1) => {
3608
+ if (typeof issue$1 === "string") {
3609
+ payload.issues.push(issue(issue$1, payload.value, def));
3610
+ }
3611
+ else {
3612
+ // for Zod 3 backwards compatibility
3613
+ const _issue = issue$1;
3614
+ if (_issue.fatal)
3615
+ _issue.continue = false;
3616
+ _issue.code ?? (_issue.code = "custom");
3617
+ _issue.input ?? (_issue.input = payload.value);
3618
+ _issue.inst ?? (_issue.inst = inst);
3619
+ // _issue.continue ??= true;
3620
+ payload.issues.push(issue(_issue));
3621
+ }
3622
+ };
3623
+ const output = def.transform(payload.value, payload);
3624
+ if (output instanceof Promise) {
3625
+ return output.then((output) => {
3626
+ payload.value = output;
3627
+ return payload;
3628
+ });
3629
+ }
3630
+ payload.value = output;
3631
+ return payload;
3632
+ };
3633
+ });
3634
+ function transform(fn) {
3635
+ return new ZodTransform({
3636
+ type: "transform",
3637
+ transform: fn,
3638
+ });
3639
+ }
3640
+ const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => {
3641
+ $ZodOptional.init(inst, def);
3642
+ ZodType.init(inst, def);
3643
+ inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
3644
+ inst.unwrap = () => inst._zod.def.innerType;
3645
+ });
3646
+ function optional(innerType) {
3647
+ return new ZodOptional({
3648
+ type: "optional",
3649
+ innerType: innerType,
3650
+ });
3651
+ }
3652
+ const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => {
3653
+ $ZodNullable.init(inst, def);
3654
+ ZodType.init(inst, def);
3655
+ inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params);
3656
+ inst.unwrap = () => inst._zod.def.innerType;
3657
+ });
3658
+ function nullable(innerType) {
3659
+ return new ZodNullable({
3660
+ type: "nullable",
3661
+ innerType: innerType,
3662
+ });
3663
+ }
3664
+ const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => {
3665
+ $ZodDefault.init(inst, def);
3666
+ ZodType.init(inst, def);
3667
+ inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params);
3668
+ inst.unwrap = () => inst._zod.def.innerType;
3669
+ inst.removeDefault = inst.unwrap;
3670
+ });
3671
+ function _default(innerType, defaultValue) {
3672
+ return new ZodDefault({
3673
+ type: "default",
3674
+ innerType: innerType,
3675
+ get defaultValue() {
3676
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3677
+ },
3678
+ });
3679
+ }
3680
+ const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => {
3681
+ $ZodPrefault.init(inst, def);
3682
+ ZodType.init(inst, def);
3683
+ inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params);
3684
+ inst.unwrap = () => inst._zod.def.innerType;
3685
+ });
3686
+ function prefault(innerType, defaultValue) {
3687
+ return new ZodPrefault({
3688
+ type: "prefault",
3689
+ innerType: innerType,
3690
+ get defaultValue() {
3691
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3692
+ },
3693
+ });
3694
+ }
3695
+ const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => {
3696
+ $ZodNonOptional.init(inst, def);
3697
+ ZodType.init(inst, def);
3698
+ inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
3699
+ inst.unwrap = () => inst._zod.def.innerType;
3700
+ });
3701
+ function nonoptional(innerType, params) {
3702
+ return new ZodNonOptional({
3703
+ type: "nonoptional",
3704
+ innerType: innerType,
3705
+ ...normalizeParams(params),
3706
+ });
3707
+ }
3708
+ const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => {
3709
+ $ZodCatch.init(inst, def);
3710
+ ZodType.init(inst, def);
3711
+ inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
3712
+ inst.unwrap = () => inst._zod.def.innerType;
3713
+ inst.removeCatch = inst.unwrap;
3714
+ });
3715
+ function _catch(innerType, catchValue) {
3716
+ return new ZodCatch({
3717
+ type: "catch",
3718
+ innerType: innerType,
3719
+ catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue),
3720
+ });
3721
+ }
3722
+ const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => {
3723
+ $ZodPipe.init(inst, def);
3724
+ ZodType.init(inst, def);
3725
+ inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
3726
+ inst.in = def.in;
3727
+ inst.out = def.out;
3728
+ });
3729
+ function pipe(in_, out) {
3730
+ return new ZodPipe({
3731
+ type: "pipe",
3732
+ in: in_,
3733
+ out: out,
3734
+ // ...util.normalizeParams(params),
3735
+ });
3736
+ }
3737
+ const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => {
3738
+ $ZodReadonly.init(inst, def);
3739
+ ZodType.init(inst, def);
3740
+ inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
3741
+ inst.unwrap = () => inst._zod.def.innerType;
3742
+ });
3743
+ function readonly(innerType) {
3744
+ return new ZodReadonly({
3745
+ type: "readonly",
3746
+ innerType: innerType,
3747
+ });
3748
+ }
3749
+ const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => {
3750
+ $ZodCustom.init(inst, def);
3751
+ ZodType.init(inst, def);
3752
+ inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx);
3753
+ });
3754
+ function refine(fn, _params = {}) {
3755
+ return _refine(ZodCustom, fn, _params);
3756
+ }
3757
+ // superRefine
3758
+ function superRefine(fn) {
3759
+ return _superRefine(fn);
3760
+ }
3761
+
3762
+ object({
3763
+ baseUrl: string().url().default('https://cloud.uipath.com'),
3764
+ orgName: string().min(1),
3765
+ tenantName: string().min(1),
3766
+ secret: string().optional(),
3767
+ clientId: string().optional(),
3768
+ redirectUri: string().url().optional(),
3769
+ scope: string().optional()
13
3770
  });
14
3771
  class UiPathConfig {
15
3772
  constructor(options) {
@@ -615,6 +4372,15 @@ const CONTENT_TYPES = {
615
4372
  XML: 'application/xml',
616
4373
  OCTET_STREAM: 'application/octet-stream'
617
4374
  };
4375
+ /**
4376
+ * Response type constants for HTTP requests
4377
+ */
4378
+ const RESPONSE_TYPES = {
4379
+ JSON: 'json',
4380
+ TEXT: 'text',
4381
+ BLOB: 'blob',
4382
+ ARRAYBUFFER: 'arraybuffer'
4383
+ };
618
4384
 
619
4385
  class ApiClient {
620
4386
  constructor(config, executionContext, tokenManager, clientConfig = {}) {
@@ -709,6 +4475,11 @@ class ApiClient {
709
4475
  if (response.status === 204) {
710
4476
  return undefined;
711
4477
  }
4478
+ // Handle blob response type for binary data (e.g., file downloads)
4479
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
4480
+ const blob = await response.blob();
4481
+ return blob;
4482
+ }
712
4483
  // Check if we're expecting XML
713
4484
  const acceptHeader = headers['Accept'] || headers['accept'];
714
4485
  if (acceptHeader === CONTENT_TYPES.XML) {
@@ -979,6 +4750,12 @@ function createHeaders(headersObj) {
979
4750
  const ODATA_PREFIX = '$';
980
4751
  const UNKNOWN$1 = 'Unknown';
981
4752
  const NO_INSTANCE = 'no-instance';
4753
+ /**
4754
+ * HTTP methods
4755
+ */
4756
+ const HTTP_METHODS = {
4757
+ GET: 'GET',
4758
+ POST: 'POST'};
982
4759
  /**
983
4760
  * OData pagination constants
984
4761
  */
@@ -997,6 +4774,16 @@ const ENTITY_PAGINATION = {
997
4774
  /** Field name for total count in entity response */
998
4775
  TOTAL_COUNT_FIELD: 'totalRecordCount'
999
4776
  };
4777
+ /**
4778
+ * Choice Set values endpoint pagination constants
4779
+ * Note: The API returns items as a JSON string in 'jsonValue' field
4780
+ */
4781
+ const CHOICESET_VALUES_PAGINATION = {
4782
+ /** Field name for items in choice set values response (contains JSON string) */
4783
+ ITEMS_FIELD: 'jsonValue',
4784
+ /** Field name for total count in choice set values response */
4785
+ TOTAL_COUNT_FIELD: 'totalRecordCount'
4786
+ };
1000
4787
  /**
1001
4788
  * Bucket pagination constants for token-based pagination
1002
4789
  */
@@ -1516,10 +5303,10 @@ class PaginationHelpers {
1516
5303
  * @returns Promise resolving to a paginated result
1517
5304
  */
1518
5305
  static async getAllPaginated(params) {
1519
- const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, options = {} } = params;
5306
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1520
5307
  const endpoint = getEndpoint(folderId);
1521
5308
  const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1522
- const paginatedResponse = await serviceAccess.requestWithPagination('GET', endpoint, paginationParams, {
5309
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1523
5310
  headers,
1524
5311
  params: additionalParams,
1525
5312
  pagination: {
@@ -1530,10 +5317,10 @@ class PaginationHelpers {
1530
5317
  paginationParams: options.paginationParams
1531
5318
  }
1532
5319
  });
1533
- // Transform items only if a transform function is provided
1534
- const transformedItems = transformFn
1535
- ? paginatedResponse.items.map(transformFn)
1536
- : paginatedResponse.items;
5320
+ // Parse items - automatically handle JSON string responses
5321
+ const rawItems = paginatedResponse.items;
5322
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
5323
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1537
5324
  return {
1538
5325
  ...paginatedResponse,
1539
5326
  items: transformedItems
@@ -1546,27 +5333,32 @@ class PaginationHelpers {
1546
5333
  * @returns Promise resolving to an object with data and totalCount
1547
5334
  */
1548
5335
  static async getAllNonPaginated(params) {
1549
- const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, options = {} } = params;
5336
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1550
5337
  // Set default field names
1551
5338
  const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1552
5339
  const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1553
5340
  // Determine endpoint and headers based on folderId
1554
5341
  const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1555
5342
  const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1556
- // Make the API call
1557
- const response = await serviceAccess.get(endpoint, {
1558
- params: additionalParams,
1559
- headers
1560
- });
1561
- // Extract data
1562
- const items = response.data?.[itemsField] || [];
1563
- // Transform items if a transform function is provided
1564
- const data = transformFn
1565
- ? items.map(transformFn)
1566
- : items;
5343
+ // Make the API call based on method
5344
+ let response;
5345
+ if (method === HTTP_METHODS.POST) {
5346
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
5347
+ }
5348
+ else {
5349
+ response = await serviceAccess.get(endpoint, {
5350
+ params: additionalParams,
5351
+ headers
5352
+ });
5353
+ }
5354
+ // Extract and transform items from response
5355
+ const rawItems = response.data?.[itemsField];
1567
5356
  const totalCount = response.data?.[totalCountField];
5357
+ // Parse items - automatically handle JSON string responses
5358
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
5359
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1568
5360
  return {
1569
- items: data,
5361
+ items,
1570
5362
  totalCount
1571
5363
  };
1572
5364
  }
@@ -1610,6 +5402,7 @@ class PaginationHelpers {
1610
5402
  paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1611
5403
  additionalParams: prefixedOptions,
1612
5404
  transformFn: config.transformFn,
5405
+ method: config.method,
1613
5406
  options: {
1614
5407
  ...paginationOptions,
1615
5408
  paginationParams: config.pagination?.paginationParams
@@ -1625,6 +5418,7 @@ class PaginationHelpers {
1625
5418
  folderId,
1626
5419
  additionalParams: prefixedOptions,
1627
5420
  transformFn: config.transformFn,
5421
+ method: config.method,
1628
5422
  options: {
1629
5423
  itemsField: paginationOptions.itemsField,
1630
5424
  totalCountField: paginationOptions.totalCountField
@@ -1646,6 +5440,7 @@ class BaseService {
1646
5440
  createPaginationServiceAccess() {
1647
5441
  return {
1648
5442
  get: (path, options) => this.get(path, options || {}),
5443
+ post: (path, body, options) => this.post(path, body, options || {}),
1649
5444
  requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1650
5445
  };
1651
5446
  }
@@ -1700,11 +5495,22 @@ class BaseService {
1700
5495
  const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1701
5496
  // Prepare request parameters based on pagination type
1702
5497
  const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1703
- // Merge pagination parameters with existing parameters
1704
- options.params = {
1705
- ...options.params,
1706
- ...requestParams
1707
- };
5498
+ // For POST requests, merge pagination params into body; for GET, use query params
5499
+ if (method.toUpperCase() === 'POST') {
5500
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
5501
+ options.body = {
5502
+ ...existingBody,
5503
+ ...options.params,
5504
+ ...requestParams
5505
+ };
5506
+ }
5507
+ else {
5508
+ // Merge pagination parameters with existing parameters
5509
+ options.params = {
5510
+ ...options.params,
5511
+ ...requestParams
5512
+ };
5513
+ }
1708
5514
  // Make the request
1709
5515
  const response = await this.request(method, path, options);
1710
5516
  // Extract data from the response and create page result
@@ -2069,105 +5875,117 @@ class TokenManager {
2069
5875
  * API Endpoint Constants
2070
5876
  * Centralized location for all API endpoints used throughout the SDK
2071
5877
  */
5878
+ /**
5879
+ * Base path constants for different services
5880
+ */
5881
+ const ORCHESTRATOR_BASE = 'orchestrator_';
5882
+ const PIMS_BASE = 'pims_';
5883
+ const DATAFABRIC_BASE = 'datafabric_';
5884
+ const IDENTITY_BASE = 'identity_';
2072
5885
  /**
2073
5886
  * Maestro Process Service Endpoints
2074
5887
  */
2075
5888
  const MAESTRO_ENDPOINTS = {
2076
- BASE_PATH: 'pims_/api/v1',
2077
5889
  PROCESSES: {
2078
- GET_ALL: 'pims_/api/v1/processes/summary',
2079
- GET_SETTINGS: (processKey) => `pims_/api/v1/processes/${processKey}/settings`,
5890
+ GET_ALL: `${PIMS_BASE}/api/v1/processes/summary`,
5891
+ GET_SETTINGS: (processKey) => `${PIMS_BASE}/api/v1/processes/${processKey}/settings`,
2080
5892
  },
2081
5893
  INSTANCES: {
2082
- GET_ALL: 'pims_/api/v1/instances',
2083
- GET_BY_ID: (instanceId) => `pims_/api/v1/instances/${instanceId}`,
2084
- GET_EXECUTION_HISTORY: (instanceId) => `pims_/api/v1/spans/${instanceId}`,
2085
- GET_BPMN: (instanceId) => `pims_/api/v1/instances/${instanceId}/bpmn`,
2086
- GET_VARIABLES: (instanceId) => `pims_/api/v1/instances/${instanceId}/variables`,
2087
- CANCEL: (instanceId) => `pims_/api/v1/instances/${instanceId}/cancel`,
2088
- PAUSE: (instanceId) => `pims_/api/v1/instances/${instanceId}/pause`,
2089
- RESUME: (instanceId) => `pims_/api/v1/instances/${instanceId}/resume`,
5894
+ GET_ALL: `${PIMS_BASE}/api/v1/instances`,
5895
+ GET_BY_ID: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}`,
5896
+ GET_EXECUTION_HISTORY: (instanceId) => `${PIMS_BASE}/api/v1/spans/${instanceId}`,
5897
+ GET_BPMN: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/bpmn`,
5898
+ GET_VARIABLES: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/variables`,
5899
+ CANCEL: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/cancel`,
5900
+ PAUSE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/pause`,
5901
+ RESUME: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/resume`,
2090
5902
  },
2091
5903
  INCIDENTS: {
2092
- GET_ALL: 'pims_/api/v1/incidents/summary',
2093
- GET_BY_PROCESS: (processKey) => `pims_/api/v1/incidents/process/${processKey}`,
2094
- GET_BY_INSTANCE: (instanceId) => `pims_/api/v1/instances/${instanceId}/incidents`,
5904
+ GET_ALL: `${PIMS_BASE}/api/v1/incidents/summary`,
5905
+ GET_BY_PROCESS: (processKey) => `${PIMS_BASE}/api/v1/incidents/process/${processKey}`,
5906
+ GET_BY_INSTANCE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/incidents`,
2095
5907
  },
2096
5908
  CASES: {
2097
- GET_CASE_JSON: (instanceId) => `pims_/api/v1/cases/${instanceId}/case-json`,
2098
- GET_ELEMENT_EXECUTIONS: (instanceId) => `pims_/api/v1alpha1/element-executions/case-instances/${instanceId}`,
5909
+ GET_CASE_JSON: (instanceId) => `${PIMS_BASE}/api/v1/cases/${instanceId}/case-json`,
5910
+ GET_ELEMENT_EXECUTIONS: (instanceId) => `${PIMS_BASE}/api/v1alpha1/element-executions/case-instances/${instanceId}`,
2099
5911
  },
2100
5912
  };
2101
5913
  /**
2102
5914
  * Task Service (Action Center) Endpoints
2103
5915
  */
2104
5916
  const TASK_ENDPOINTS = {
2105
- CREATE_GENERIC_TASK: '/tasks/GenericTasks/CreateTask',
2106
- GET_TASK_USERS: (folderId) => `/odata/Tasks/UiPath.Server.Configuration.OData.GetTaskUsers(organizationUnitId=${folderId})`,
2107
- GET_TASKS_ACROSS_FOLDERS: '/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFoldersForAdmin',
2108
- GET_BY_ID: (id) => `/odata/Tasks(${id})`,
2109
- ASSIGN_TASKS: '/odata/Tasks/UiPath.Server.Configuration.OData.AssignTasks',
2110
- REASSIGN_TASKS: '/odata/Tasks/UiPath.Server.Configuration.OData.ReassignTasks',
2111
- UNASSIGN_TASKS: '/odata/Tasks/UiPath.Server.Configuration.OData.UnassignTasks',
2112
- COMPLETE_FORM_TASK: '/forms/TaskForms/CompleteTask',
2113
- COMPLETE_APP_TASK: '/tasks/AppTasks/CompleteAppTask',
2114
- COMPLETE_GENERIC_TASK: '/tasks/GenericTasks/CompleteTask',
2115
- GET_TASK_FORM_BY_ID: '/forms/TaskForms/GetTaskFormById',
5917
+ CREATE_GENERIC_TASK: `${ORCHESTRATOR_BASE}/tasks/GenericTasks/CreateTask`,
5918
+ GET_TASK_USERS: (folderId) => `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTaskUsers(organizationUnitId=${folderId})`,
5919
+ GET_TASKS_ACROSS_FOLDERS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFolders`,
5920
+ GET_TASKS_ACROSS_FOLDERS_ADMIN: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFoldersForAdmin`,
5921
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/Tasks(${id})`,
5922
+ ASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.AssignTasks`,
5923
+ REASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.ReassignTasks`,
5924
+ UNASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.UnassignTasks`,
5925
+ COMPLETE_FORM_TASK: `${ORCHESTRATOR_BASE}/forms/TaskForms/CompleteTask`,
5926
+ COMPLETE_APP_TASK: `${ORCHESTRATOR_BASE}/tasks/AppTasks/CompleteAppTask`,
5927
+ COMPLETE_GENERIC_TASK: `${ORCHESTRATOR_BASE}/tasks/GenericTasks/CompleteTask`,
5928
+ GET_TASK_FORM_BY_ID: `${ORCHESTRATOR_BASE}/forms/TaskForms/GetTaskFormById`,
2116
5929
  };
2117
5930
  /**
2118
5931
  * Data Fabric Service Endpoints
2119
5932
  */
2120
5933
  const DATA_FABRIC_ENDPOINTS = {
2121
5934
  ENTITY: {
2122
- GET_ALL: 'datafabric_/api/Entity',
2123
- GET_ENTITY_RECORDS: (entityId) => `datafabric_/api/EntityService/entity/${entityId}/read`,
2124
- GET_BY_ID: (entityId) => `datafabric_/api/Entity/${entityId}`,
2125
- INSERT_BY_ID: (entityId) => `datafabric_/api/EntityService/entity/${entityId}/insert-batch`,
2126
- UPDATE_BY_ID: (entityId) => `datafabric_/api/EntityService/entity/${entityId}/update-batch`,
2127
- DELETE_BY_ID: (entityId) => `datafabric_/api/EntityService/entity/${entityId}/delete-batch`,
5935
+ GET_ALL: `${DATAFABRIC_BASE}/api/Entity`,
5936
+ GET_ENTITY_RECORDS: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/read`,
5937
+ GET_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/Entity/${entityId}`,
5938
+ INSERT_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/insert-batch`,
5939
+ UPDATE_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/update-batch`,
5940
+ DELETE_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/delete-batch`,
5941
+ DOWNLOAD_ATTACHMENT: (entityName, recordId, fieldName) => `${DATAFABRIC_BASE}/api/Attachment/${entityName}/${recordId}/${fieldName}`,
5942
+ },
5943
+ CHOICESETS: {
5944
+ GET_ALL: `${DATAFABRIC_BASE}/api/Entity/choiceset`,
5945
+ GET_BY_ID: (choiceSetId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${choiceSetId}/query_expansion`,
2128
5946
  },
2129
5947
  };
2130
5948
  /**
2131
5949
  * Orchestrator Bucket Endpoints
2132
5950
  */
2133
5951
  const BUCKET_ENDPOINTS = {
2134
- GET_BY_FOLDER: '/odata/Buckets',
2135
- GET_ALL: '/odata/Buckets/UiPath.Server.Configuration.OData.GetBucketsAcrossFolders',
2136
- GET_BY_ID: (id) => `/odata/Buckets(${id})`,
2137
- GET_FILE_META_DATA: (id) => `/api/Buckets/${id}/ListFiles`,
2138
- GET_READ_URI: (id) => `/odata/Buckets(${id})/UiPath.Server.Configuration.OData.GetReadUri`,
2139
- GET_WRITE_URI: (id) => `/odata/Buckets(${id})/UiPath.Server.Configuration.OData.GetWriteUri`,
5952
+ GET_BY_FOLDER: `${ORCHESTRATOR_BASE}/odata/Buckets`,
5953
+ GET_ALL: `${ORCHESTRATOR_BASE}/odata/Buckets/UiPath.Server.Configuration.OData.GetBucketsAcrossFolders`,
5954
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/Buckets(${id})`,
5955
+ GET_FILE_META_DATA: (id) => `${ORCHESTRATOR_BASE}/api/Buckets/${id}/ListFiles`,
5956
+ GET_READ_URI: (id) => `${ORCHESTRATOR_BASE}/odata/Buckets(${id})/UiPath.Server.Configuration.OData.GetReadUri`,
5957
+ GET_WRITE_URI: (id) => `${ORCHESTRATOR_BASE}/odata/Buckets(${id})/UiPath.Server.Configuration.OData.GetWriteUri`,
2140
5958
  };
2141
5959
  /**
2142
5960
  * Identity/Authentication Endpoints
2143
5961
  */
2144
5962
  const IDENTITY_ENDPOINTS = {
2145
- TOKEN: 'identity_/connect/token',
2146
- AUTHORIZE: 'identity_/connect/authorize',
5963
+ TOKEN: `${IDENTITY_BASE}/connect/token`,
5964
+ AUTHORIZE: `${IDENTITY_BASE}/connect/authorize`,
2147
5965
  };
2148
5966
  /**
2149
5967
  * Orchestrator Process Service Endpoints
2150
5968
  */
2151
5969
  const PROCESS_ENDPOINTS = {
2152
- GET_ALL: '/odata/Releases',
2153
- START_PROCESS: '/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs',
2154
- GET_BY_ID: (id) => `/odata/Releases(${id})`,
5970
+ GET_ALL: `${ORCHESTRATOR_BASE}/odata/Releases`,
5971
+ START_PROCESS: `${ORCHESTRATOR_BASE}/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs`,
5972
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/Releases(${id})`,
2155
5973
  };
2156
5974
  /**
2157
5975
  * Orchestrator Queue Service Endpoints
2158
5976
  */
2159
5977
  const QUEUE_ENDPOINTS = {
2160
- GET_BY_FOLDER: '/odata/QueueDefinitions',
2161
- GET_ALL: '/odata/QueueDefinitions/UiPath.Server.Configuration.OData.GetQueuesAcrossFolders',
2162
- GET_BY_ID: (id) => `/odata/QueueDefinitions(${id})`,
5978
+ GET_BY_FOLDER: `${ORCHESTRATOR_BASE}/odata/QueueDefinitions`,
5979
+ GET_ALL: `${ORCHESTRATOR_BASE}/odata/QueueDefinitions/UiPath.Server.Configuration.OData.GetQueuesAcrossFolders`,
5980
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/QueueDefinitions(${id})`,
2163
5981
  };
2164
5982
  /**
2165
5983
  * Orchestrator Asset Service Endpoints
2166
5984
  */
2167
5985
  const ASSET_ENDPOINTS = {
2168
- GET_BY_FOLDER: '/odata/Assets/UiPath.Server.Configuration.OData.GetFiltered',
2169
- GET_ALL: '/odata/Assets/UiPath.Server.Configuration.OData.GetAssetsAcrossFolders',
2170
- GET_BY_ID: (id) => `/odata/Assets(${id})`,
5986
+ GET_BY_FOLDER: `${ORCHESTRATOR_BASE}/odata/Assets/UiPath.Server.Configuration.OData.GetFiltered`,
5987
+ GET_ALL: `${ORCHESTRATOR_BASE}/odata/Assets/UiPath.Server.Configuration.OData.GetAssetsAcrossFolders`,
5988
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/Assets(${id})`,
2171
5989
  };
2172
5990
 
2173
5991
  class AuthService extends BaseService {
@@ -2179,6 +5997,9 @@ class AuthService extends BaseService {
2179
5997
  const tokenManager = new TokenManager(executionContext, effectiveConfig, isOAuth);
2180
5998
  super(effectiveConfig, executionContext, tokenManager);
2181
5999
  this.tokenManager = tokenManager;
6000
+ // Auto-load token from storage on initialization
6001
+ // This ensures isAuthenticated() returns true after page refresh if a valid token exists
6002
+ this.tokenManager.loadFromStorage();
2182
6003
  }
2183
6004
  /**
2184
6005
  * Check if we're in an OAuth callback state
@@ -2366,12 +6187,17 @@ class AuthService extends BaseService {
2366
6187
  }
2367
6188
  else {
2368
6189
  // In Node.js environment
2369
- const crypto = require('crypto');
2370
- return crypto.randomBytes(32)
2371
- .toString('base64')
2372
- .replace(/\+/g, '-')
2373
- .replace(/\//g, '_')
2374
- .replace(/=/g, '');
6190
+ try {
6191
+ const crypto = require('crypto');
6192
+ return crypto.randomBytes(32)
6193
+ .toString('base64')
6194
+ .replace(/\+/g, '-')
6195
+ .replace(/\//g, '_')
6196
+ .replace(/=/g, '');
6197
+ }
6198
+ catch (e) {
6199
+ throw new Error("crypto not available in browser");
6200
+ }
2375
6201
  }
2376
6202
  }
2377
6203
  /**
@@ -2386,13 +6212,18 @@ class AuthService extends BaseService {
2386
6212
  }
2387
6213
  else {
2388
6214
  // In Node.js environment
2389
- const crypto = require('crypto');
2390
- return crypto.createHash('sha256')
2391
- .update(codeVerifier)
2392
- .digest('base64')
2393
- .replace(/\+/g, '-')
2394
- .replace(/\//g, '_')
2395
- .replace(/=/g, '');
6215
+ try {
6216
+ const crypto = require('crypto');
6217
+ return crypto.createHash('sha256')
6218
+ .update(codeVerifier)
6219
+ .digest('base64')
6220
+ .replace(/\+/g, '-')
6221
+ .replace(/\//g, '_')
6222
+ .replace(/=/g, '');
6223
+ }
6224
+ catch (e) {
6225
+ throw new Error("crypto not available in browser");
6226
+ }
2396
6227
  }
2397
6228
  }
2398
6229
  /**
@@ -2555,6 +6386,15 @@ function createEntityMethods(entityData, service) {
2555
6386
  if (!entityData.id)
2556
6387
  throw new Error('Entity ID is undefined');
2557
6388
  return service.getRecordsById(entityData.id, options);
6389
+ },
6390
+ async downloadAttachment(recordId, fieldName) {
6391
+ if (!entityData.name)
6392
+ throw new Error('Entity name is undefined');
6393
+ return service.downloadAttachment({
6394
+ entityName: entityData.name,
6395
+ recordId,
6396
+ fieldName
6397
+ });
2558
6398
  }
2559
6399
  };
2560
6400
  }
@@ -2719,7 +6559,7 @@ const EntityFieldTypeMap = {
2719
6559
  // Connection string placeholder that will be replaced during build
2720
6560
  const CONNECTION_STRING = "InstrumentationKey=a6efa11d-1feb-4508-9738-e13e12dcae5e;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/;LiveEndpoint=https://westeurope.livediagnostics.monitor.azure.com/;ApplicationId=7c58eb1c-9581-4ba6-839e-11725848a037";
2721
6561
  // SDK Version placeholder
2722
- const SDK_VERSION = "1.0.0-beta.15";
6562
+ const SDK_VERSION = "1.0.0-beta.17";
2723
6563
  const VERSION = "Version";
2724
6564
  const SERVICE = "Service";
2725
6565
  const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
@@ -3032,76 +6872,6 @@ class EntityService extends BaseService {
3032
6872
  // Return the entity metadata with methods attached
3033
6873
  return createEntityWithMethods(metadata, this);
3034
6874
  }
3035
- /**
3036
- * Orchestrates all field mapping transformations
3037
- *
3038
- * @param metadata - Entity metadata to transform
3039
- * @private
3040
- */
3041
- applyFieldMappings(metadata) {
3042
- this.mapFieldTypes(metadata);
3043
- this.mapExternalFields(metadata);
3044
- }
3045
- /**
3046
- * Maps SQL field types to friendly EntityFieldTypes
3047
- *
3048
- * @param metadata - Entity metadata with fields
3049
- * @private
3050
- */
3051
- mapFieldTypes(metadata) {
3052
- if (!metadata.fields?.length)
3053
- return;
3054
- metadata.fields = metadata.fields.map(field => {
3055
- // Rename sqlType to fieldDataType
3056
- let transformedField = transformData(field, EntityMap);
3057
- // Map SQL field type to friendly name
3058
- if (transformedField.fieldDataType?.name) {
3059
- const sqlTypeName = transformedField.fieldDataType.name;
3060
- if (EntityFieldTypeMap[sqlTypeName]) {
3061
- transformedField.fieldDataType.name = EntityFieldTypeMap[sqlTypeName];
3062
- }
3063
- }
3064
- this.transformNestedReferences(transformedField);
3065
- return transformedField;
3066
- });
3067
- }
3068
- /**
3069
- * Transforms nested reference objects in field metadata
3070
- */
3071
- transformNestedReferences(field) {
3072
- if (field.referenceEntity) {
3073
- field.referenceEntity = transformData(field.referenceEntity, EntityMap);
3074
- }
3075
- if (field.referenceChoiceSet) {
3076
- field.referenceChoiceSet = transformData(field.referenceChoiceSet, EntityMap);
3077
- }
3078
- if (field.referenceField?.definition) {
3079
- field.referenceField.definition = transformData(field.referenceField.definition, EntityMap);
3080
- }
3081
- }
3082
- /**
3083
- * Maps external field names to consistent naming
3084
- *
3085
- * @param metadata - Entity metadata with externalFields
3086
- * @private
3087
- */
3088
- mapExternalFields(metadata) {
3089
- if (!metadata.externalFields?.length)
3090
- return;
3091
- metadata.externalFields = metadata.externalFields.map(externalSource => {
3092
- if (externalSource.fields?.length) {
3093
- externalSource.fields = externalSource.fields.map(field => {
3094
- const transformedField = transformData(field, EntityMap);
3095
- if (transformedField.fieldMetaData) {
3096
- transformedField.fieldMetaData = transformData(transformedField.fieldMetaData, EntityMap);
3097
- this.transformNestedReferences(transformedField.fieldMetaData);
3098
- }
3099
- return transformedField;
3100
- });
3101
- }
3102
- return externalSource;
3103
- });
3104
- }
3105
6875
  /**
3106
6876
  * Gets entity records by entity ID
3107
6877
  *
@@ -3136,7 +6906,6 @@ class EntityService extends BaseService {
3136
6906
  return PaginationHelpers.getAll({
3137
6907
  serviceAccess: this.createPaginationServiceAccess(),
3138
6908
  getEndpoint: () => DATA_FABRIC_ENDPOINTS.ENTITY.GET_ENTITY_RECORDS(entityId),
3139
- transformFn: (item) => pascalToCamelCaseKeys(item),
3140
6909
  pagination: {
3141
6910
  paginationType: PaginationType.OFFSET,
3142
6911
  itemsField: ENTITY_PAGINATION.ITEMS_FIELD,
@@ -3283,6 +7052,98 @@ class EntityService extends BaseService {
3283
7052
  });
3284
7053
  return entities;
3285
7054
  }
7055
+ /**
7056
+ * Downloads an attachment from an entity record field
7057
+ *
7058
+ * @param options - Options containing entityName, recordId, and fieldName
7059
+ * @returns Promise resolving to Blob containing the file content
7060
+ *
7061
+ * @example
7062
+ * ```typescript
7063
+ * // Download attachment for a specific record and field
7064
+ * const blob = await sdk.entities.downloadAttachment({
7065
+ * entityName: 'Invoice',
7066
+ * recordId: '<record-uuid>',
7067
+ * fieldName: 'Documents'
7068
+ * });
7069
+ */
7070
+ async downloadAttachment(options) {
7071
+ const { entityName, recordId, fieldName } = options;
7072
+ const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.DOWNLOAD_ATTACHMENT(entityName, recordId, fieldName), {
7073
+ responseType: RESPONSE_TYPES.BLOB
7074
+ });
7075
+ return response.data;
7076
+ }
7077
+ /**
7078
+ * Orchestrates all field mapping transformations
7079
+ *
7080
+ * @param metadata - Entity metadata to transform
7081
+ * @private
7082
+ */
7083
+ applyFieldMappings(metadata) {
7084
+ this.mapFieldTypes(metadata);
7085
+ this.mapExternalFields(metadata);
7086
+ }
7087
+ /**
7088
+ * Maps SQL field types to friendly EntityFieldTypes
7089
+ *
7090
+ * @param metadata - Entity metadata with fields
7091
+ * @private
7092
+ */
7093
+ mapFieldTypes(metadata) {
7094
+ if (!metadata.fields?.length)
7095
+ return;
7096
+ metadata.fields = metadata.fields.map(field => {
7097
+ // Rename sqlType to fieldDataType
7098
+ let transformedField = transformData(field, EntityMap);
7099
+ // Map SQL field type to friendly name
7100
+ if (transformedField.fieldDataType?.name) {
7101
+ const sqlTypeName = transformedField.fieldDataType.name;
7102
+ if (EntityFieldTypeMap[sqlTypeName]) {
7103
+ transformedField.fieldDataType.name = EntityFieldTypeMap[sqlTypeName];
7104
+ }
7105
+ }
7106
+ this.transformNestedReferences(transformedField);
7107
+ return transformedField;
7108
+ });
7109
+ }
7110
+ /**
7111
+ * Transforms nested reference objects in field metadata
7112
+ */
7113
+ transformNestedReferences(field) {
7114
+ if (field.referenceEntity) {
7115
+ field.referenceEntity = transformData(field.referenceEntity, EntityMap);
7116
+ }
7117
+ if (field.referenceChoiceSet) {
7118
+ field.referenceChoiceSet = transformData(field.referenceChoiceSet, EntityMap);
7119
+ }
7120
+ if (field.referenceField?.definition) {
7121
+ field.referenceField.definition = transformData(field.referenceField.definition, EntityMap);
7122
+ }
7123
+ }
7124
+ /**
7125
+ * Maps external field names to consistent naming
7126
+ *
7127
+ * @param metadata - Entity metadata with externalFields
7128
+ * @private
7129
+ */
7130
+ mapExternalFields(metadata) {
7131
+ if (!metadata.externalFields?.length)
7132
+ return;
7133
+ metadata.externalFields = metadata.externalFields.map(externalSource => {
7134
+ if (externalSource.fields?.length) {
7135
+ externalSource.fields = externalSource.fields.map(field => {
7136
+ const transformedField = transformData(field, EntityMap);
7137
+ if (transformedField.fieldMetaData) {
7138
+ transformedField.fieldMetaData = transformData(transformedField.fieldMetaData, EntityMap);
7139
+ this.transformNestedReferences(transformedField.fieldMetaData);
7140
+ }
7141
+ return transformedField;
7142
+ });
7143
+ }
7144
+ return externalSource;
7145
+ });
7146
+ }
3286
7147
  }
3287
7148
  __decorate([
3288
7149
  track('Entities.GetById')
@@ -3302,6 +7163,105 @@ __decorate([
3302
7163
  __decorate([
3303
7164
  track('Entities.GetAll')
3304
7165
  ], EntityService.prototype, "getAll", null);
7166
+ __decorate([
7167
+ track('Entities.DownloadAttachment')
7168
+ ], EntityService.prototype, "downloadAttachment", null);
7169
+
7170
+ class ChoiceSetService extends BaseService {
7171
+ /**
7172
+ * @hideconstructor
7173
+ */
7174
+ constructor(config, executionContext, tokenManager) {
7175
+ super(config, executionContext, tokenManager);
7176
+ }
7177
+ /**
7178
+ * Gets all choice sets in the system
7179
+ *
7180
+ * @returns Promise resolving to an array of choice set metadata
7181
+ *
7182
+ * @example
7183
+ * ```typescript
7184
+ * // Get all choice sets
7185
+ * const choiceSets = await sdk.entities.choicesets.getAll();
7186
+ *
7187
+ * // Iterate through choice sets
7188
+ * choiceSets.forEach(choiceSet => {
7189
+ * console.log(`ChoiceSet: ${choiceSet.displayName} (${choiceSet.name})`);
7190
+ * console.log(`Description: ${choiceSet.description}`);
7191
+ * });
7192
+ * ```
7193
+ */
7194
+ async getAll() {
7195
+ const rawResponse = await this.get(DATA_FABRIC_ENDPOINTS.CHOICESETS.GET_ALL);
7196
+ // Transform field names
7197
+ const data = rawResponse.data || [];
7198
+ return data.map(choiceSet => transformData(choiceSet, EntityMap));
7199
+ }
7200
+ /**
7201
+ * Gets choice set values by choice set ID with optional pagination
7202
+ *
7203
+ * The method returns either:
7204
+ * - A NonPaginatedResponse with items array (when no pagination parameters are provided)
7205
+ * - A PaginatedResponse with navigation cursors (when any pagination parameter is provided)
7206
+ *
7207
+ * @param choiceSetId - UUID of the choice set
7208
+ * @param options - Pagination options
7209
+ * @returns Promise resolving to choice set values or paginated result
7210
+ *
7211
+ * @example
7212
+ * ```typescript
7213
+ * // First, get the choice set ID using getAll()
7214
+ * const choiceSets = await sdk.entities.choicesets.getAll();
7215
+ * const expenseTypes = choiceSets.find(cs => cs.name === 'ExpenseTypes');
7216
+ * const choiceSetId = expenseTypes.id;
7217
+ *
7218
+ * // Get all values (non-paginated)
7219
+ * const values = await sdk.entities.choicesets.getById(choiceSetId);
7220
+ *
7221
+ * // Iterate through choice set values
7222
+ * for (const value of values.items) {
7223
+ * console.log(`Value: ${value.displayName} (${value.name})`);
7224
+ * }
7225
+ *
7226
+ * // First page with pagination
7227
+ * const page1 = await sdk.entities.choicesets.getById(choiceSetId, { pageSize: 10 });
7228
+ *
7229
+ * // Navigate using cursor
7230
+ * if (page1.hasNextPage) {
7231
+ * const page2 = await sdk.entities.choicesets.getById(choiceSetId, { cursor: page1.nextCursor });
7232
+ * }
7233
+ * ```
7234
+ */
7235
+ async getById(choiceSetId, options) {
7236
+ // Transform a single item from PascalCase to camelCase
7237
+ const transformFn = (item) => {
7238
+ const camelCased = pascalToCamelCaseKeys(item);
7239
+ return transformData(camelCased, EntityMap);
7240
+ };
7241
+ return PaginationHelpers.getAll({
7242
+ serviceAccess: this.createPaginationServiceAccess(),
7243
+ getEndpoint: () => DATA_FABRIC_ENDPOINTS.CHOICESETS.GET_BY_ID(choiceSetId),
7244
+ transformFn,
7245
+ method: HTTP_METHODS.POST,
7246
+ pagination: {
7247
+ paginationType: PaginationType.OFFSET,
7248
+ itemsField: CHOICESET_VALUES_PAGINATION.ITEMS_FIELD,
7249
+ totalCountField: CHOICESET_VALUES_PAGINATION.TOTAL_COUNT_FIELD,
7250
+ paginationParams: {
7251
+ pageSizeParam: ENTITY_OFFSET_PARAMS.PAGE_SIZE_PARAM,
7252
+ offsetParam: ENTITY_OFFSET_PARAMS.OFFSET_PARAM,
7253
+ countParam: ENTITY_OFFSET_PARAMS.COUNT_PARAM
7254
+ }
7255
+ }
7256
+ }, options);
7257
+ }
7258
+ }
7259
+ __decorate([
7260
+ track('Choicesets.GetAll')
7261
+ ], ChoiceSetService.prototype, "getAll", null);
7262
+ __decorate([
7263
+ track('Choicesets.GetById')
7264
+ ], ChoiceSetService.prototype, "getById", null);
3305
7265
 
3306
7266
  /**
3307
7267
  * Maestro Process Models
@@ -4479,7 +8439,7 @@ class TaskService extends BaseService {
4479
8439
  * - An array of tasks (when no pagination parameters are provided)
4480
8440
  * - A paginated result with navigation cursors (when any pagination parameter is provided)
4481
8441
  *
4482
- * @param options - Query options including optional folderId and pagination options
8442
+ * @param options - Query options including optional folderId, asTaskAdmin flag and pagination options
4483
8443
  * @returns Promise resolving to an array of tasks or paginated result
4484
8444
  *
4485
8445
  * @example
@@ -4492,6 +8452,11 @@ class TaskService extends BaseService {
4492
8452
  * folderId: 123
4493
8453
  * });
4494
8454
  *
8455
+ * // Get tasks with admin permissions
8456
+ * const tasks = await sdk.tasks.getAll({
8457
+ * asTaskAdmin: true
8458
+ * });
8459
+ *
4495
8460
  * // First page with pagination
4496
8461
  * const page1 = await sdk.tasks.getAll({ pageSize: 10 });
4497
8462
  *
@@ -4508,6 +8473,10 @@ class TaskService extends BaseService {
4508
8473
  * ```
4509
8474
  */
4510
8475
  async getAll(options) {
8476
+ // Determine which endpoint to use based on asTaskAdmin flag
8477
+ const endpoint = options?.asTaskAdmin
8478
+ ? TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS_ADMIN
8479
+ : TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS;
4511
8480
  // Transformation function for tasks
4512
8481
  const transformTaskResponse = (task) => {
4513
8482
  const transformedTask = transformData(pascalToCamelCaseKeys(task), TaskMap);
@@ -4515,7 +8484,7 @@ class TaskService extends BaseService {
4515
8484
  };
4516
8485
  return PaginationHelpers.getAll({
4517
8486
  serviceAccess: this.createPaginationServiceAccess(),
4518
- getEndpoint: () => TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS,
8487
+ getEndpoint: () => endpoint,
4519
8488
  transformFn: transformTaskResponse,
4520
8489
  processParametersFn: this.processTaskParameters,
4521
8490
  excludeFromPrefix: ['event'], // Exclude 'event' key from ODATA prefix transformation
@@ -5834,11 +9803,9 @@ class ProcessService extends BaseService {
5834
9803
  delete apiRequest[clientKey];
5835
9804
  }
5836
9805
  });
5837
- // Convert to PascalCase for API
5838
- const pascalOptions = camelToPascalCaseKeys(apiRequest);
5839
9806
  // Create the request object according to API spec
5840
9807
  const requestBody = {
5841
- startInfo: pascalOptions
9808
+ startInfo: apiRequest
5842
9809
  };
5843
9810
  // Prefix all query parameter keys with '$' for OData
5844
9811
  const keysToPrefix = Object.keys(options);
@@ -6160,7 +10127,12 @@ class UiPath {
6160
10127
  * Access to Entity service
6161
10128
  */
6162
10129
  get entities() {
6163
- return this.getService(EntityService);
10130
+ return Object.assign(this.getService(EntityService), {
10131
+ /**
10132
+ * Access to ChoiceSet service for managing choice sets
10133
+ */
10134
+ choicesets: this.getService(ChoiceSetService)
10135
+ });
6164
10136
  }
6165
10137
  /**
6166
10138
  * Access to Tasks service